Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CHANGES.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CHANGES.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CHANGES.rst	(revision 14097)
@@ -0,0 +1,7 @@
+*******
+Changes
+*******
+
+.. todo::
+
+   List the main additions of the the new release
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CONTRIBUTING.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CONTRIBUTING.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/CONTRIBUTING.rst	(revision 14097)
@@ -0,0 +1,73 @@
+************
+Contributing
+************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Sending feedbacks
+=================
+
+|  Sending feedbacks is a useful way to contribute to NEMO efficency and reliability. Before doing so,
+   please check here :forge:`search <search on the developement platform>` in wiki, tickets, forum and online
+   documentation if the subject has already been discussed. You can either contribute to an existing
+   discussion, or
+| Create an entry for the discussion online, according to your needs
+
+- You have a question: create a topic in the appropriate :forge:`discussion <forum>`
+- You would like to raise and issue: open a new ticket of the right type depending of its severity
+
+  - "Unavoidable" :forge:`newticket?type=Bug       <bug>`
+
+  - "Workable"    :forge:`newticket?type=Defect <defect>`
+
+Please follow the guidelines and try to be as specific as possible in the ticket description.
+
+New development
+===============
+
+You have build a development relevant for NEMO shared reference: an addition of the source code,
+a full fork of the reference, ...
+
+You may want to share it with the community (see Hack below) or to propose it for implementation in the future
+NEMO release (see Proposal / Task below).
+
+The proposals for developments to be included in the shared NEMO reference are first examined by NEMO Developers
+Committee / Scientific Advisory Board.
+The implementation of a new development requires some additionnal work from the intial developer.
+These tasks will need to be scheduled with NEMO System Team.
+
+
+Hack
+----
+
+You only would like to inform NEMO community about your developments.
+You can promote your work on NEMO forum gathering  the contributions fromof the community by creating
+a specific topic here :forge:`discussion/forum/5 <dedicated forum>`
+
+
+Proposal / Task
+---------------
+
+| Your development is quite small, and you would only like to offer it as a possible enhancement. Please suggest it
+  as an enhancement here :forge:`newticket?type=Enhancement <enhancement>` . It will be taken in account, if
+  feasible, by NEMO System Team. To ease the process, it is suggested, rather than attaching the modified
+  routines to the ticket, to highlight the proposed changes by adding to the ticket the output of ``svn diff``
+  or ``svn patch`` from your working copy.
+
+| Your development seems relevant for addition into the future release of NEMO shared reference.
+  Implementing it into NEMO shared reference following the usual quality control will require some additionnal work
+  from you and also from the NEMO System Team in charge of NEMO development. In order to evaluate the work,
+  your suggestion should be send as a proposed enhancement here :forge:`newticket?type=Enhancement <enhancement>`
+  including description of the development, its implementation, and the existing validations.
+
+  The proposed enhancement will be examined  by NEMO Developers Committee / Scientific Advisory Board.
+  Once approved by the  Committee, the assicated development task can be scheduled in NEMO development work plan,
+  and tasks distributed between you as initial developer and PI of this development action, and the NEMO System Team.
+
+  Once sucessful (meeting the usual quality control steps) this action will allow the merge of these developments with
+  other developments of the year, building the future NEMO.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/INSTALL.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/INSTALL.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/INSTALL.rst	(revision 14097)
@@ -0,0 +1,270 @@
+*******************
+Build the framework
+*******************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Prerequisites
+=============
+
+| The NEMO source code is written in *Fortran 95* and
+  some of its prerequisite tools and libraries are already included in the download.
+| It contains the AGRIF_ preprocessing program ``conv``; the FCM_ build system and
+  the IOIPSL_ library for parts of the output.
+
+System dependencies
+-------------------
+
+In the first place the other requirements should be provided natively by your system or
+can be installed from the official repositories of your Unix-like distribution:
+
+- *Perl* interpreter
+- *Fortran* compiler (``ifort``, ``gfortran``, ``pgfortran``, ...),
+- *Message Passing Interface (MPI)* implementation (e.g. |OpenMPI|_ or |MPICH|_).
+- |NetCDF|_ library with its underlying |HDF|_
+
+**NEMO, by default, takes advantage of some MPI features introduced into the MPI-3 standard.**
+
+.. hint::
+
+   The MPI implementation is not strictly essential
+   since it is possible to compile and run NEMO on a single processor.
+   However most realistic configurations will require the parallel capabilities of NEMO and
+   these use the MPI standard.
+
+.. note::
+
+   On older systems, that do not support MPI-3 features,
+   the ``key_mpi2`` preprocessor key should be used at compile time.
+   This will limit MPI features to those defined within the MPI-2 standard
+   (but will lose some performance benefits).
+
+.. |OpenMPI| replace:: *OpenMPI*
+.. _OpenMPI: https://www.open-mpi.org
+.. |MPICH|   replace:: *MPICH*
+.. _MPICH:   https://www.mpich.org
+.. |NetCDF|  replace:: *Network Common Data Form (NetCDF)*
+.. _NetCDF:  https://www.unidata.ucar.edu
+.. |HDF|     replace:: *Hierarchical Data Form (HDF)*
+.. _HDF:     https://www.hdfgroup.org
+
+Specifics for NetCDF and HDF
+----------------------------
+
+NetCDF and HDF versions from official repositories may have not been compiled with MPI support.
+However access to all the options available with the XIOS IO-server will require
+the parallelism of these libraries.
+
+| **To satisfy these requirements, it is common to have to compile from source
+  in this order HDF (C library) then NetCDF (C and Fortran libraries)**
+| It is also necessary to compile these libraries with the same version of the MPI implementation that
+  both NEMO and XIOS (see below) have been compiled and linked with.
+
+.. hint::
+
+   | It is difficult to define the options for the compilation as
+     they differ from one architecture to another according to
+     the hardware used and the software installed.
+   | The following is provided without any warranty
+
+   .. code-block:: console
+
+      $ ./configure [--{enable-fortran,disable-shared,enable-parallel}] ...
+
+   It is recommended to build the tests ``--enable-parallel-tests`` and run them with ``make check``
+
+Particular versions of these libraries may have their own restrictions.
+State the following requirements for netCDF-4 support:
+
+.. caution::
+
+   | When building NetCDF-C library versions older than 4.4.1, use only HDF5 1.8.x versions.
+   | Combining older NetCDF-C versions with newer HDF5 1.10 versions will create superblock 3 files
+     that are not readable by lots of older software.
+
+Extract and install XIOS
+========================
+
+With the sole exception of running NEMO in mono-processor mode
+(in which case output options are limited to those supported by the ``IOIPSL`` library),
+diagnostic outputs from NEMO are handled by the third party ``XIOS`` library.
+It can be used in two different modes:
+
+:*attached*:  Every NEMO process also acts as a XIOS server
+:*detached*:  Every NEMO process runs as a XIOS client.
+  Output is collected and collated by external, stand-alone XIOS server processors.
+
+Instructions on how to install XIOS can be found on its :xios:`wiki<>`.
+
+.. hint::
+
+   It is recommended to use XIOS 2.5 release.
+   This version should be more stable (in terms of future code changes) than the XIOS trunk.
+   It is also the one used by the NEMO system team when testing all developments and new releases.
+
+   This particular version has its own branch and can be checked out with:
+
+   .. code:: console
+
+      $ svn co https://forge.ipsl.jussieu.fr/ioserver/svn/XIOS/branchs/xios-2.5
+
+Download and install the NEMO code
+==================================
+
+Checkout the NEMO sources
+-------------------------
+
+.. code:: console
+
+   $ svn co https://forge.ipsl.jussieu.fr/nemo/svn/NEMO/releases/release-4.0-HEAD
+
+Description of 1\ :sup:`st` level tree structure
+------------------------------------------------
+
++---------------+----------------------------------------+
+| :file:`arch`  | Compilation settings                   |
++---------------+----------------------------------------+
+| :file:`cfgs`  | :doc:`Reference configurations <cfgs>` |
++---------------+----------------------------------------+
+| :file:`doc`   | :doc:`Documentation <doc>`             |
++---------------+----------------------------------------+
+| :file:`ext`   | Dependencies included                  |
+|               | (``AGRIF``, ``FCM`` & ``IOIPSL``)      |
++---------------+----------------------------------------+
+| :file:`mk`    | Compilation scripts                    |
++---------------+----------------------------------------+
+| :file:`src`   | :doc:`Modelling routines <src>`        |
++---------------+----------------------------------------+
+| :file:`tests` | :doc:`Test cases <tests>`              |
+|               | (unsupported)                          |
++---------------+----------------------------------------+
+| :file:`tools` | :doc:`Utilities <tools>`               |
+|               | to {pre,post}process data              |
++---------------+----------------------------------------+
+
+Setup your architecture configuration file
+------------------------------------------
+
+All compiler options in NEMO are controlled using files in :file:`./arch/arch-'my_arch'.fcm` where
+``my_arch`` is the name of the computing architecture
+(generally following the pattern ``HPCC-compiler`` or ``OS-compiler``).
+It is recommended to copy and rename an configuration file from an architecture similar to your owns.
+You will need to set appropriate values for all of the variables in the file.
+In particular the FCM variables:
+``%NCDF_HOME``; ``%HDF5_HOME`` and ``%XIOS_HOME`` should be set to
+the installation directories used for XIOS installation
+
+.. code-block:: sh
+
+   %NCDF_HOME    /usr/local/path/to/netcdf
+   %HDF5_HOME    /usr/local/path/to/hdf5
+   %XIOS_HOME    /home/$( whoami )/path/to/xios-2.5
+   %OASIS_HOME   /home/$( whoami )/path/to/oasis
+
+Create and compile a new configuration
+======================================
+
+The main script to {re}compile and create executable is called :file:`makenemo` located at
+the root of the working copy.
+It is used to identify the routines you need from the source code, to build the makefile and run it.
+As an example, compile a :file:`MY_GYRE` configuration from GYRE with 'my_arch':
+
+.. code-block:: sh
+
+   ./makenemo –m 'my_arch' –r GYRE -n 'MY_GYRE'
+
+Then at the end of the configuration compilation,
+:file:`MY_GYRE` directory will have the following structure.
+
++------------+----------------------------------------------------------------------------+
+| Directory  | Purpose                                                                    |
++============+============================================================================+
+| ``BLD``    | BuiLD folder: target executable, headers, libs, preprocessed routines, ... |
++------------+----------------------------------------------------------------------------+
+| ``EXP00``  | Run   folder: link to executable, namelists, ``*.xml`` and IOs             |
++------------+----------------------------------------------------------------------------+
+| ``EXPREF`` | Files under version control only for :doc:`official configurations <cfgs>` |
++------------+----------------------------------------------------------------------------+
+| ``MY_SRC`` | New routines or modified copies of NEMO sources                            |
++------------+----------------------------------------------------------------------------+
+| ``WORK``   | Links to all raw routines from :file:`./src` considered                    |
++------------+----------------------------------------------------------------------------+
+
+After successful execution of :file:`makenemo` command,
+the executable called `nemo` is available in the :file:`EXP00` directory
+
+More :file:`makenemo` options
+-----------------------------
+
+``makenemo`` has several other options that can control which source files are selected and
+the operation of the build process itself.
+
+.. literalinclude:: ../../../makenemo
+   :language: text
+   :lines: 119-143
+   :caption: Output of ``makenemo -h``
+
+These options can be useful for maintaining several code versions with only minor differences but
+they should be used sparingly.
+Note however the ``-j`` option which should be used more routinely to speed up the build process.
+For example:
+
+.. code-block:: sh
+
+        ./makenemo –m 'my_arch' –r GYRE -n 'MY_GYRE' -j 8
+
+will compile up to 8 processes simultaneously.
+
+Default behaviour
+-----------------
+
+At the first use,
+you need the ``-m`` option to specify the architecture configuration file
+(compiler and its options, routines and libraries to include),
+then for next compilation, it is assumed you will be using the same compiler.
+If the ``-n`` option is not specified the last compiled configuration will be used.
+
+Tools used during the process
+-----------------------------
+
+* :file:`functions.sh`: bash functions used by ``makenemo``, for instance to create the WORK directory
+* :file:`cfg.txt`     : text list of configurations and source directories
+* :file:`bld.cfg`     : FCM rules for compilation
+
+Examples
+--------
+
+.. literalinclude:: ../../../makenemo
+   :language: text
+   :lines: 146-153
+
+Running the model
+=================
+
+Once :file:`makenemo` has run successfully,
+the ``nemo`` executable is available in :file:`./cfgs/MY_CONFIG/EXP00`.
+For the reference configurations, the :file:`EXP00` folder also contains the initial input files
+(namelists, ``*.xml`` files for the IOs, ...).
+If the configuration needs other input files, they have to be placed here.
+
+.. code-block:: sh
+
+   cd 'MY_CONFIG'/EXP00
+   mpirun -n $NPROCS ./nemo   # $NPROCS is the number of processes
+                              # mpirun is your MPI wrapper
+
+Viewing and changing list of active CPP keys
+============================================
+
+For a given configuration (here called ``MY_CONFIG``),
+the list of active CPP keys can be found in :file:`./cfgs/'MYCONFIG'/cpp_MY_CONFIG.fcm`
+
+This text file can be edited by hand or with :file:`makenemo` to change the list of active CPP keys.
+Once changed, one needs to recompile ``nemo`` in order for this change to be taken in account.
+Note that most NEMO configurations will need to specify the following CPP keys:
+``key_iomput`` for IOs and ``key_mpp_mpi`` for parallelism.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/LICENSE
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/LICENSE	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/LICENSE	(revision 14097)
@@ -0,0 +1,506 @@
+
+CeCILL FREE SOFTWARE LICENSE AGREEMENT
+
+
+    Notice
+
+This Agreement is a Free Software license agreement that is the result
+of discussions between its authors in order to ensure compliance with
+the two main principles guiding its drafting:
+
+    * firstly, compliance with the principles governing the distribution
+      of Free Software: access to source code, broad rights granted to
+      users,
+    * secondly, the election of a governing law, French law, with which
+      it is conformant, both as regards the law of torts and
+      intellectual property law, and the protection that it offers to
+      both authors and holders of the economic rights over software.
+
+The authors of the CeCILL (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
+license are:
+
+Commissariat à l'Energie Atomique - CEA, a public scientific, technical
+and industrial research establishment, having its principal place of
+business at 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris, France.
+
+Centre National de la Recherche Scientifique - CNRS, a public scientific
+and technological establishment, having its principal place of business
+at 3 rue Michel-Ange, 75794 Paris cedex 16, France.
+
+Institut National de Recherche en Informatique et en Automatique -
+INRIA, a public scientific and technological establishment, having its
+principal place of business at Domaine de Voluceau, Rocquencourt, BP
+105, 78153 Le Chesnay cedex, France.
+
+
+    Preamble
+
+The purpose of this Free Software license agreement is to grant users
+the right to modify and redistribute the software governed by this
+license within the framework of an open source distribution model.
+
+The exercising of these rights is conditional upon certain obligations
+for users so as to preserve this status for all subsequent redistributions.
+
+In consideration of access to the source code and the rights to copy,
+modify and redistribute granted by the license, users are provided only
+with a limited warranty and the software's author, the holder of the
+economic rights, and the successive licensors only have limited liability.
+
+In this respect, the risks associated with loading, using, modifying
+and/or developing or reproducing the software by the user are brought to
+the user's attention, given its Free Software status, which may make it
+complicated to use, with the result that its use is reserved for
+developers and experienced professionals having in-depth computer
+knowledge. Users are therefore encouraged to load and test the
+suitability of the software as regards their requirements in conditions
+enabling the security of their systems and/or data to be ensured and,
+more generally, to use and operate it in the same conditions of
+security. This Agreement may be freely reproduced and published,
+provided it is not altered, and that no provisions are either added or
+removed herefrom.
+
+This Agreement may apply to any or all software for which the holder of
+the economic rights decides to submit the use thereof to its provisions.
+
+
+    Article 1 - DEFINITIONS
+
+For the purpose of this Agreement, when the following expressions
+commence with a capital letter, they shall have the following meaning:
+
+Agreement: means this license agreement, and its possible subsequent
+versions and annexes.
+
+Software: means the software in its Object Code and/or Source Code form
+and, where applicable, its documentation, "as is" when the Licensee
+accepts the Agreement.
+
+Initial Software: means the Software in its Source Code and possibly its
+Object Code form and, where applicable, its documentation, "as is" when
+it is first distributed under the terms and conditions of the Agreement.
+
+Modified Software: means the Software modified by at least one
+Contribution.
+
+Source Code: means all the Software's instructions and program lines to
+which access is required so as to modify the Software.
+
+Object Code: means the binary files originating from the compilation of
+the Source Code.
+
+Holder: means the holder(s) of the economic rights over the Initial
+Software.
+
+Licensee: means the Software user(s) having accepted the Agreement.
+
+Contributor: means a Licensee having made at least one Contribution.
+
+Licensor: means the Holder, or any other individual or legal entity, who
+distributes the Software under the Agreement.
+
+Contribution: means any or all modifications, corrections, translations,
+adaptations and/or new functions integrated into the Software by any or
+all Contributors, as well as any or all Internal Modules.
+
+Module: means a set of sources files including their documentation that
+enables supplementary functions or services in addition to those offered
+by the Software.
+
+External Module: means any or all Modules, not derived from the
+Software, so that this Module and the Software run in separate address
+spaces, with one calling the other when they are run.
+
+Internal Module: means any or all Module, connected to the Software so
+that they both execute in the same address space.
+
+GNU GPL: means the GNU General Public License version 2 or any
+subsequent version, as published by the Free Software Foundation Inc.
+
+Parties: mean both the Licensee and the Licensor.
+
+These expressions may be used both in singular and plural form.
+
+
+    Article 2 - PURPOSE
+
+The purpose of the Agreement is the grant by the Licensor to the
+Licensee of a non-exclusive, transferable and worldwide license for the
+Software as set forth in Article 5 hereinafter for the whole term of the
+protection granted by the rights over said Software. 
+
+
+    Article 3 - ACCEPTANCE
+
+3.1 The Licensee shall be deemed as having accepted the terms and
+conditions of this Agreement upon the occurrence of the first of the
+following events:
+
+    * (i) loading the Software by any or all means, notably, by
+      downloading from a remote server, or by loading from a physical
+      medium;
+    * (ii) the first time the Licensee exercises any of the rights
+      granted hereunder.
+
+3.2 One copy of the Agreement, containing a notice relating to the
+characteristics of the Software, to the limited warranty, and to the
+fact that its use is restricted to experienced users has been provided
+to the Licensee prior to its acceptance as set forth in Article 3.1
+hereinabove, and the Licensee hereby acknowledges that it has read and
+understood it.
+
+
+    Article 4 - EFFECTIVE DATE AND TERM
+
+
+      4.1 EFFECTIVE DATE
+
+The Agreement shall become effective on the date when it is accepted by
+the Licensee as set forth in Article 3.1.
+
+
+      4.2 TERM
+
+The Agreement shall remain in force for the entire legal term of
+protection of the economic rights over the Software.
+
+
+    Article 5 - SCOPE OF RIGHTS GRANTED
+
+The Licensor hereby grants to the Licensee, who accepts, the following
+rights over the Software for any or all use, and for the term of the
+Agreement, on the basis of the terms and conditions set forth hereinafter.
+
+Besides, if the Licensor owns or comes to own one or more patents
+protecting all or part of the functions of the Software or of its
+components, the Licensor undertakes not to enforce the rights granted by
+these patents against successive Licensees using, exploiting or
+modifying the Software. If these patents are transferred, the Licensor
+undertakes to have the transferees subscribe to the obligations set
+forth in this paragraph.
+
+
+      5.1 RIGHT OF USE
+
+The Licensee is authorized to use the Software, without any limitation
+as to its fields of application, with it being hereinafter specified
+that this comprises:
+
+   1. permanent or temporary reproduction of all or part of the Software
+      by any or all means and in any or all form.
+
+   2. loading, displaying, running, or storing the Software on any or
+      all medium.
+
+   3. entitlement to observe, study or test its operation so as to
+      determine the ideas and principles behind any or all constituent
+      elements of said Software. This shall apply when the Licensee
+      carries out any or all loading, displaying, running, transmission
+      or storage operation as regards the Software, that it is entitled
+      to carry out hereunder.
+
+
+      5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS
+
+The right to make Contributions includes the right to translate, adapt,
+arrange, or make any or all modifications to the Software, and the right
+to reproduce the resulting software.
+
+The Licensee is authorized to make any or all Contributions to the
+Software provided that it includes an explicit notice that it is the
+author of said Contribution and indicates the date of the creation thereof.
+
+
+      5.3 RIGHT OF DISTRIBUTION
+
+In particular, the right of distribution includes the right to publish,
+transmit and communicate the Software to the general public on any or
+all medium, and by any or all means, and the right to market, either in
+consideration of a fee, or free of charge, one or more copies of the
+Software by any means.
+
+The Licensee is further authorized to distribute copies of the modified
+or unmodified Software to third parties according to the terms and
+conditions set forth hereinafter.
+
+
+        5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION
+
+The Licensee is authorized to distribute true copies of the Software in
+Source Code or Object Code form, provided that said distribution
+complies with all the provisions of the Agreement and is accompanied by:
+
+   1. a copy of the Agreement,
+
+   2. a notice relating to the limitation of both the Licensor's
+      warranty and liability as set forth in Articles 8 and 9,
+
+and that, in the event that only the Object Code of the Software is
+redistributed, the Licensee allows future Licensees unhindered access to
+the full Source Code of the Software by indicating how to access it, it
+being understood that the additional cost of acquiring the Source Code
+shall not exceed the cost of transferring the data.
+
+
+        5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE
+
+When the Licensee makes a Contribution to the Software, the terms and
+conditions for the distribution of the resulting Modified Software
+become subject to all the provisions of this Agreement.
+
+The Licensee is authorized to distribute the Modified Software, in
+source code or object code form, provided that said distribution
+complies with all the provisions of the Agreement and is accompanied by:
+
+   1. a copy of the Agreement,
+
+   2. a notice relating to the limitation of both the Licensor's
+      warranty and liability as set forth in Articles 8 and 9,
+
+and that, in the event that only the object code of the Modified
+Software is redistributed, the Licensee allows future Licensees
+unhindered access to the full source code of the Modified Software by
+indicating how to access it, it being understood that the additional
+cost of acquiring the source code shall not exceed the cost of
+transferring the data.
+
+
+        5.3.3 DISTRIBUTION OF EXTERNAL MODULES
+
+When the Licensee has developed an External Module, the terms and
+conditions of this Agreement do not apply to said External Module, that
+may be distributed under a separate license agreement.
+
+
+        5.3.4 COMPATIBILITY WITH THE GNU GPL
+
+The Licensee can include a code that is subject to the provisions of one
+of the versions of the GNU GPL in the Modified or unmodified Software,
+and distribute that entire code under the terms of the same version of
+the GNU GPL.
+
+The Licensee can include the Modified or unmodified Software in a code
+that is subject to the provisions of one of the versions of the GNU GPL,
+and distribute that entire code under the terms of the same version of
+the GNU GPL.
+
+
+    Article 6 - INTELLECTUAL PROPERTY
+
+
+      6.1 OVER THE INITIAL SOFTWARE
+
+The Holder owns the economic rights over the Initial Software. Any or
+all use of the Initial Software is subject to compliance with the terms
+and conditions under which the Holder has elected to distribute its work
+and no one shall be entitled to modify the terms and conditions for the
+distribution of said Initial Software.
+
+The Holder undertakes that the Initial Software will remain ruled at
+least by this Agreement, for the duration set forth in Article 4.2.
+
+
+      6.2 OVER THE CONTRIBUTIONS
+
+The Licensee who develops a Contribution is the owner of the
+intellectual property rights over this Contribution as defined by
+applicable law.
+
+
+      6.3 OVER THE EXTERNAL MODULES
+
+The Licensee who develops an External Module is the owner of the
+intellectual property rights over this External Module as defined by
+applicable law and is free to choose the type of agreement that shall
+govern its distribution.
+
+
+      6.4 JOINT PROVISIONS
+
+The Licensee expressly undertakes:
+
+   1. not to remove, or modify, in any manner, the intellectual property
+      notices attached to the Software;
+
+   2. to reproduce said notices, in an identical manner, in the copies
+      of the Software modified or not.
+
+The Licensee undertakes not to directly or indirectly infringe the
+intellectual property rights of the Holder and/or Contributors on the
+Software and to take, where applicable, vis-à-vis its staff, any and all
+measures required to ensure respect of said intellectual property rights
+of the Holder and/or Contributors.
+
+
+    Article 7 - RELATED SERVICES
+
+7.1 Under no circumstances shall the Agreement oblige the Licensor to
+provide technical assistance or maintenance services for the Software.
+
+However, the Licensor is entitled to offer this type of services. The
+terms and conditions of such technical assistance, and/or such
+maintenance, shall be set forth in a separate instrument. Only the
+Licensor offering said maintenance and/or technical assistance services
+shall incur liability therefor.
+
+7.2 Similarly, any Licensor is entitled to offer to its licensees, under
+its sole responsibility, a warranty, that shall only be binding upon
+itself, for the redistribution of the Software and/or the Modified
+Software, under terms and conditions that it is free to decide. Said
+warranty, and the financial terms and conditions of its application,
+shall be subject of a separate instrument executed between the Licensor
+and the Licensee.
+
+
+    Article 8 - LIABILITY
+
+8.1 Subject to the provisions of Article 8.2, the Licensee shall be
+entitled to claim compensation for any direct loss it may have suffered
+from the Software as a result of a fault on the part of the relevant
+Licensor, subject to providing evidence thereof.
+
+8.2 The Licensor's liability is limited to the commitments made under
+this Agreement and shall not be incurred as a result of in particular:
+(i) loss due the Licensee's total or partial failure to fulfill its
+obligations, (ii) direct or consequential loss that is suffered by the
+Licensee due to the use or performance of the Software, and (iii) more
+generally, any consequential loss. In particular the Parties expressly
+agree that any or all pecuniary or business loss (i.e. loss of data,
+loss of profits, operating loss, loss of customers or orders,
+opportunity cost, any disturbance to business activities) or any or all
+legal proceedings instituted against the Licensee by a third party,
+shall constitute consequential loss and shall not provide entitlement to
+any or all compensation from the Licensor.
+
+
+    Article 9 - WARRANTY
+
+9.1 The Licensee acknowledges that the scientific and technical
+state-of-the-art when the Software was distributed did not enable all
+possible uses to be tested and verified, nor for the presence of
+possible defects to be detected. In this respect, the Licensee's
+attention has been drawn to the risks associated with loading, using,
+modifying and/or developing and reproducing the Software which are
+reserved for experienced users.
+
+The Licensee shall be responsible for verifying, by any or all means,
+the suitability of the product for its requirements, its good working
+order, and for ensuring that it shall not cause damage to either persons
+or properties.
+
+9.2 The Licensor hereby represents, in good faith, that it is entitled
+to grant all the rights over the Software (including in particular the
+rights set forth in Article 5).
+
+9.3 The Licensee acknowledges that the Software is supplied "as is" by
+the Licensor without any other express or tacit warranty, other than
+that provided for in Article 9.2 and, in particular, without any warranty 
+as to its commercial value, its secured, safe, innovative or relevant
+nature.
+
+Specifically, the Licensor does not warrant that the Software is free
+from any error, that it will operate without interruption, that it will
+be compatible with the Licensee's own equipment and software
+configuration, nor that it will meet the Licensee's requirements.
+
+9.4 The Licensor does not either expressly or tacitly warrant that the
+Software does not infringe any third party intellectual property right
+relating to a patent, software or any other property right. Therefore,
+the Licensor disclaims any and all liability towards the Licensee
+arising out of any or all proceedings for infringement that may be
+instituted in respect of the use, modification and redistribution of the
+Software. Nevertheless, should such proceedings be instituted against
+the Licensee, the Licensor shall provide it with technical and legal
+assistance for its defense. Such technical and legal assistance shall be
+decided on a case-by-case basis between the relevant Licensor and the
+Licensee pursuant to a memorandum of understanding. The Licensor
+disclaims any and all liability as regards the Licensee's use of the
+name of the Software. No warranty is given as regards the existence of
+prior rights over the name of the Software or as regards the existence
+of a trademark.
+
+
+    Article 10 - TERMINATION
+
+10.1 In the event of a breach by the Licensee of its obligations
+hereunder, the Licensor may automatically terminate this Agreement
+thirty (30) days after notice has been sent to the Licensee and has
+remained ineffective.
+
+10.2 A Licensee whose Agreement is terminated shall no longer be
+authorized to use, modify or distribute the Software. However, any
+licenses that it may have granted prior to termination of the Agreement
+shall remain valid subject to their having been granted in compliance
+with the terms and conditions hereof.
+
+
+    Article 11 - MISCELLANEOUS
+
+
+      11.1 EXCUSABLE EVENTS
+
+Neither Party shall be liable for any or all delay, or failure to
+perform the Agreement, that may be attributable to an event of force
+majeure, an act of God or an outside cause, such as defective
+functioning or interruptions of the electricity or telecommunications
+networks, network paralysis following a virus attack, intervention by
+government authorities, natural disasters, water damage, earthquakes,
+fire, explosions, strikes and labor unrest, war, etc.
+
+11.2 Any failure by either Party, on one or more occasions, to invoke
+one or more of the provisions hereof, shall under no circumstances be
+interpreted as being a waiver by the interested Party of its right to
+invoke said provision(s) subsequently.
+
+11.3 The Agreement cancels and replaces any or all previous agreements,
+whether written or oral, between the Parties and having the same
+purpose, and constitutes the entirety of the agreement between said
+Parties concerning said purpose. No supplement or modification to the
+terms and conditions hereof shall be effective as between the Parties
+unless it is made in writing and signed by their duly authorized
+representatives.
+
+11.4 In the event that one or more of the provisions hereof were to
+conflict with a current or future applicable act or legislative text,
+said act or legislative text shall prevail, and the Parties shall make
+the necessary amendments so as to comply with said act or legislative
+text. All other provisions shall remain effective. Similarly, invalidity
+of a provision of the Agreement, for any reason whatsoever, shall not
+cause the Agreement as a whole to be invalid.
+
+
+      11.5 LANGUAGE
+
+The Agreement is drafted in both French and English and both versions
+are deemed authentic.
+
+
+    Article 12 - NEW VERSIONS OF THE AGREEMENT
+
+12.1 Any person is authorized to duplicate and distribute copies of this
+Agreement.
+
+12.2 So as to ensure coherence, the wording of this Agreement is
+protected and may only be modified by the authors of the License, who
+reserve the right to periodically publish updates or new versions of the
+Agreement, each with a separate number. These subsequent versions may
+address new issues encountered by Free Software.
+
+12.3 Any Software distributed under a given version of the Agreement may
+only be subsequently distributed under the same version of the Agreement
+or a subsequent version, subject to the provisions of Article 5.3.4.
+
+
+    Article 13 - GOVERNING LAW AND JURISDICTION
+
+13.1 The Agreement is governed by French law. The Parties agree to
+endeavor to seek an amicable solution to any disagreements or disputes
+that may arise during the performance of the Agreement.
+
+13.2 Failing an amicable solution within two (2) months as from their
+occurrence, and unless emergency proceedings are necessary, the
+disagreements or disputes shall be referred to the Paris Courts having
+jurisdiction, by the more diligent Party.
+
+
+Version 2.0 dated 2006-09-05.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/README.rst	(revision 14097)
@@ -0,0 +1,99 @@
+.. todo::
+
+
+
+NEMO_ for *Nucleus for European Modelling of the Ocean* is a state-of-the-art modelling framework for
+research activities and forecasting services in ocean and climate sciences,
+developed in a sustainable way by a European consortium since 2008.
+
+.. contents::
+   :local:
+
+Overview
+========
+
+The NEMO ocean model has 3 major components:
+
+- |OCE| models the ocean {thermo}dynamics and solves the primitive equations
+  (:file:`./src/OCE`)
+- |ICE| simulates sea-ice {thermo}dynamics, brine inclusions and
+  subgrid-scale thickness variations (:file:`./src/ICE`)
+- |MBG| models the {on,off}line oceanic tracers transport and biogeochemical processes
+  (:file:`./src/TOP`)
+
+These physical core engines are described in
+their respective `reference publications <#project-documentation>`_ that
+must be cited for any work related to their use (see :doc:`cite`).
+
+Assets and solutions
+====================
+
+Not only does the NEMO framework model the ocean circulation,
+it offers various features to enable
+
+- Create :doc:`embedded zooms<zooms>` seamlessly thanks to 2-way nesting package AGRIF_.
+- Opportunity to integrate an :doc:`external biogeochemistry model<tracers>`
+- Versatile :doc:`data assimilation<da>`
+- Generation of :doc:`diagnostics<diags>` through effective XIOS_ system
+- Roll-out Earth system modeling with :doc:`coupling interface<cplg>` based on OASIS_
+
+Several :doc:`built-in configurations<cfgs>` are provided to
+evaluate the skills and performances of the model which
+can be used as templates for setting up a new configurations (:file:`./cfgs`).
+
+The user can also checkout available :doc:`idealized test cases<tests>` that
+address specific physical processes (:file:`./tests`).
+
+A set of :doc:`utilities <tools>` is also provided to {pre,post}process your data (:file:`./tools`).
+
+Project documentation
+=====================
+
+A walkthrough tutorial illustrates how to get code dependencies, compile and execute NEMO
+(:file:`./INSTALL.rst`).
+
+Reference manuals and quick start guide can be build from source and
+exported to HTML or PDF formats (:file:`./doc`) or
+downloaded directly from the :forge:`development platform<wiki/Documentations>`.
+
+============ ================== ===================
+ Component    Reference Manual   Quick Start Guide
+============ ================== ===================
+ |NEMO-OCE|   |DOI man OCE|_     |DOI qsg|
+ |NEMO-ICE|   |DOI man ICE|
+ |NEMO-MBG|   |DOI man MBG|
+============ ================== ===================
+
+Since 2014 the project has a `Special Issue`_ in the open-access journal
+Geoscientific Model Development (GMD) from the European Geosciences Union (EGU_).
+The main scope is to collect relevant manuscripts covering various topics and
+to provide a single portal to assess the model potential and evolution.
+
+Used by a wide audience,
+numerous :website:`associated projects<projects>` have been carried out and
+extensive :website:`bibliography<bibliography/publications>` published.
+
+Development board
+=================
+
+The NEMO Consortium pulling together 5 European institutes
+(CMCC_, CNRS_, MOI_, `Met Office`_ and NERC_) plans the sustainable development in order to
+keep a reliable evolving framework since 2008.
+
+It defines the |DOI dev stgy|_ that is implemented by the System Team on a yearly basis
+in order to release a new version almost every four years.
+
+When the need arises, :forge:`working groups<wiki/WorkingGroups>` are created or resumed to
+gather the community expertise for advising on the development activities.
+
+.. |DOI dev stgy| replace:: multi-year development strategy
+
+Disclaimer
+==========
+
+The NEMO source code is freely available and distributed under
+:download:`CeCILL v2.0 license <../../../LICENSE>` (GNU GPL compatible).
+
+You can use, modify and/or redistribute the software under its terms,
+but users are provided only with a limited warranty and the software's authors and
+the successive licensor's have only limited liability.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/REFERENCES.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/REFERENCES.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/REFERENCES.bib	(revision 14097)
@@ -0,0 +1,46 @@
+@manual{NEMO_man,
+   title="NEMO ocean engine",
+   author="NEMO System Team",
+   series="Scientific Notes of Climate Modelling Center",
+   number="27",
+   institution="Institut Pierre-Simon Laplace (IPSL)",
+   publisher="Zenodo",
+   doi="10.5281/zenodo.1464816",
+}
+%   edition="",
+%   year=""
+
+@manual{SI3_man,
+   title="Sea Ice modelling Integrated Initiative (SI$^3$) -- The NEMO Sea Ice engine",
+   author="NEMO Sea Ice Working Group",
+   series="Scientific Notes of Climate Modelling Center",
+   number="31",
+   institution="Institut Pierre-Simon Laplace (IPSL)",
+   publisher="Zenodo",
+   doi="10.5281/zenodo.1471689",
+}
+%   edition="",
+%   year=""
+
+@manual{TOP_man,
+   title="Tracers in Ocean Paradigm (TOP) -- The NEMO Tracers engine",
+   author="NEMO TOP Working Group",
+   series="Scientific Notes of Climate Modelling Center",
+   number="28",
+   institution="Institut Pierre-Simon Laplace (IPSL)",
+   publisher="Zenodo",
+   doi="10.5281/zenodo.1471700",
+}
+%   edition="",
+%   year=""
+
+@article{TAM_pub,
+   author = "Vidard, A. and Bouttier, P.-A. and Vigilant, F.",
+   title = "NEMOTAM: Tangent and Adjoint Models for the ocean modelling platform NEMO",
+   journal = "Geoscientific Model Development",
+   volume = "8",
+   year = "2015",
+   number = "4",
+   pages = "1245--1257",
+   doi = "10.5194/gmd-8-1245-2015"
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="1_nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>   <!--  NEMO ocean sea ice                      -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO ocean sea ice                      -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_cfg	(revision 14097)
@@ -0,0 +1,398 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!                         AGRIF ICE configuration                      !
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      = "Pacific" !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =      80   !  last  time step (std 5475)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 5400.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R2_zps_domcfg_agrif"    ! domain configuration filename
+      !
+      ln_closea    = .false.    !  F => suppress closed seas (defined by closea_mask field) 
+      !                         !       from the bathymetry at runtime.
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data                         (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   ln_tsd_dmp  = .true.          !  T-S restoring   (see namtra_dmp)
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''    ,    ''    ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+                           !     (also = the frequency of sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  =2 or 3 automatically for SI3 or CICE    ("key_si3" or "key_cice")
+                           !          except in AGRIF zoom where it has to be specified
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+   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      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namsbc_blk   !   namsbc_blk  generic Bulk formula                      (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR    = .true.     ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir = './'  !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+   !
+   nn_chldta   =      1       !  RGB : Chl data (=1) or cst value (=0)
+
+   cn_dir = './'  !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .true.    !  specific treatment at rivers mouths
+      rn_hrnf     =  15.e0    !  depth over which enhanced vertical mixing is used    (ln_rnf_mouth=T)
+      rn_avt_rnf  =   1.e-3   !  value of the additional vertical mixing coef. [m2/s] (ln_rnf_mouth=T)
+
+   cn_dir = './'  !  root directory for the location of the runoff files
+   !___________!_____________!___________________!___________!_____________!_________!___________!__________!__________!_______________!
+   !           !  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'  , ''       , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sssr     =     2     !  add a damping term to the surface freshwater flux
+      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]
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: No iceberg)
+!-----------------------------------------------------------------------
+   !  iceberg floats are not currently available with AGRIF
+   !     ===>>  forced deactivation in icbini.F90
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.     !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx   =    2      !  geothermal heat flux: = 2 read variable flux [mW/m2]
+
+   cn_dir = './'  !  root directory for the geothermal data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_qgh      ='geothermal_heating.nc'  ,       -12.        , 'heatflow',   .false.   , .true. , 'yearly'  ,   ''             ,   ''     ,   ''
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.     !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap   = .true.    !    laplacian operator
+   !                       !  Direction of action:
+   ln_traldf_iso   = .true.    !  iso-neutral (Standard operator)
+   !		       	         !  iso-neutral options:        
+   ln_traldf_msc   = .true.    !  Method of Stabilizing Correction      (both operators)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 20        !  space/time variation of eddy coef
+      !                             !   = 20     aht = 1/2  Ud. max(e1,e2)
+      rn_Ud        = 0.018          !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_eiv !   eddy induced velocity param.                            (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv     =.true.   ! use eddy induced velocity parameterization
+      !                        !  Coefficients:
+      nn_aei_ijk_t  = 21          ! space/time variation of the eiv coeficient
+      !                                !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                           !  time invariant coefficients:  aei0 = 1/2  Ue*Le 
+      rn_Ue        = 0.03              !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Le        = 200.e+3           !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+      !
+      ln_ldfeiv_dia =.true.   ! diagnose eiv stream function and velocities
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .true.   !  add a damping term (using resto.nc coef.)
+      nn_zdmp  =    0         !  vertical shape =0    damping throughout the water column
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true.  !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0   e3f = mean masked e3t divided by 4
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .true.     !  iso-level
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = -30         !  space/time variation of eddy coef
+   !                                !  =-30  read in eddy_viscosity_3D.nc
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  Enhanced Vertical Diffusion scheme
+      nn_evdm  =    0            !  evd apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd   =  100.           !  evd mixing coefficient [m2/s]
+   !
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,84 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/1_namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="2_nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>   <!--  NEMO ocean sea ice                      -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO ocean sea ice                      -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_cfg	(revision 14097)
@@ -0,0 +1,347 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/1_namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!                         AGRIF ICE configuration                      !
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      = "Nordic"  !  experience name 
+   nn_it000    =    1      !  first time step
+   nn_itend    =  320      !  last  time step
+   nn_istate   =      0    !  output the initial state (1) or not (0)
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 1350.     !  time step for the dynamics (and tracer if nn_acc=0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R05_zps_domcfg_agrif"    ! domain configuration filename
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data                         (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   ln_tsd_dmp  = .false.         !  T-S restoring   (see namtra_dmp)
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''    ,    ''    ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  =0   Use SI3 model
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namsbc_blk   !   namsbc_blk  generic Bulk formula                      (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR     = .true.    ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bicub.nc'     , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bicub.nc'     , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'     , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'     , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'     , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'     , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'     , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'  , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'  , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic1_bilin.nc'  , ''       , ''
+
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+   !
+   nn_chldta   =      1       !  RGB : Chl data (=1) or cst value (=0)
+
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''                                   , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: No iceberg)
+!-----------------------------------------------------------------------
+   !  iceberg floats are not currently available with AGRIF
+   !     ===>>  forced deactivation in icbini.F90 
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   ln_spc_dyn    = .true.  !  use 0 as special value for dynamics
+   rn_sponge_tra = 1440.   !  coefficient for tracer   sponge layer [m2/s]
+   rn_sponge_dyn = 1440.   !  coefficient for dynamics sponge layer [m2/s]
+   ln_chk_bathy  = .true.  !  =T  check the parent bathymetry
+/
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.    !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx   =    1      !  geothermal heat flux: = 2 read variable flux [mW/m2]
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_ubs = .true. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_OFF   =  .true.  !           No operator (no explicit advection)
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.    !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  Enhanced Vertical Diffusion scheme
+      nn_evdm  =    0            !  evd apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd   =  100.           !  evd mixing coefficient [m2/s]
+   !
+   ln_zdfddm   = .true.    ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,84 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 namelist:  
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link 1_namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/2_namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link 1_namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="3_nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>   <!--  NEMO ocean sea ice                      -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO ocean sea ice                      -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_cfg	(revision 14097)
@@ -0,0 +1,347 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/1_namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!                         AGRIF ICE configuration                      !
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      = "Nordic"  !  experience name 
+   nn_it000    =    1      !  first time step
+   nn_itend    =  960      !  last  time step
+   nn_istate   =      0    !  output the initial state (1) or not (0)
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 450.     !  time step for the dynamics (and tracer if nn_acc=0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R017_zps_domcfg_agrif"    ! domain configuration filename
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data                         (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   ln_tsd_dmp  = .false.         !  T-S restoring   (see namtra_dmp)
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''    ,    ''    ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  =0   Use SI3 model
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namsbc_blk   !   namsbc_blk  generic Bulk formula                      (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR     = .true.    ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bicub.nc'     , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bicub.nc'     , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core2_nordic2_bilin.nc'     , ''       , ''
+
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+   !
+   nn_chldta   =      1       !  RGB : Chl data (=1) or cst value (=0)
+
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''                                   , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: No iceberg)
+!-----------------------------------------------------------------------
+   !  iceberg floats are not currently available with AGRIF
+   !     ===>>  forced deactivation in icbini.F90 
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   ln_spc_dyn    = .true.  !  use 0 as special value for dynamics
+   rn_sponge_tra =  480.   !  coefficient for tracer   sponge layer [m2/s]
+   rn_sponge_dyn =  480.   !  coefficient for dynamics sponge layer [m2/s]
+   ln_chk_bathy  = .true.  !  =T  check the parent bathymetry
+/
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.    !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx   =    1      !  geothermal heat flux: = 2 read variable flux [mW/m2]
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_ubs = .true. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_OFF   =  .true.  !           No operator (no explicit advection)
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   !  not used in this zoom
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.    !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  Enhanced Vertical Diffusion scheme
+      nn_evdm  =    0            !  evd apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd   =  100.           !  evd mixing coefficient [m2/s]
+   !
+   ln_zdfddm   = .true.    ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,84 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 namelist:  
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/3_namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids.in
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
@@ -0,0 +1,7 @@
+2
+42 82 49 91 1 1 1
+122 153 110 143 4 4 4
+0
+1
+38 80 71 111 3 3 3
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids_1ghost.in
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids_1ghost.in	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/AGRIF_FixedGrids_1ghost.in	(revision 14097)
@@ -0,0 +1,7 @@
+2
+44 84 51 93 1 1 1
+124 155 112 145 4 4 4
+0
+1
+38 80 71 111 3 3 3
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>   <!--  NEMO ocean sea ice                      -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO ocean sea ice                      -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,130 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                      Define your own files for sea ice                                   =
+=                                         put the variables you want...                                    =
+============================================================================================================
+ -->
+    
+ <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="5d" min_digits="4">
+   
+   <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   	
+     <file id="file21" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+       <!-- ice mask -->
+       <field field_ref="icemask"          name="simsk"   />
+       <field field_ref="icemask05"        name="simsk05" />
+       <field field_ref="icemask15"        name="simsk15" />
+       
+       <!-- general -->
+       <field field_ref="snwvolu"          name="snvolu" />
+       <field field_ref="icethic"          name="sithic" />
+       <field field_ref="icevolu"          name="sivolu" />
+       <field field_ref="iceconc"          name="siconc" />
+       <field field_ref="icesalt"          name="sisali" />
+       <field field_ref="iceapnd"          name="siapnd" />
+       <field field_ref="icevpnd"          name="sivpnd" />
+       <field field_ref="sst_m"            name="sst_m"  />
+       <field field_ref="sss_m"            name="sss_m"  />
+       
+       <!-- heat -->
+       <field field_ref="icetemp"          name="sitemp" />
+       <field field_ref="icettop"          name="sittop" />
+       <field field_ref="icetbot"          name="sitbot" />
+       <field field_ref="icetsni"          name="sitsni" />
+       
+       <!-- momentum -->
+       <field field_ref="uice"             name="sivelu"  />
+       <field field_ref="vice"             name="sivelv"  />
+       <field field_ref="icevel"           name="sivelo"  />
+       <field field_ref="utau_ai"          name="utau_ai" />
+       <field field_ref="vtau_ai"          name="vtau_ai" />
+       <field field_ref="utau_oi"          name="utau_oi" />
+       <field field_ref="vtau_oi"          name="vtau_oi" />
+       
+       <!-- rheology -->
+       <field field_ref="icediv"           name="sidive"  />
+       <field field_ref="iceshe"           name="sishea"  />
+       <field field_ref="icestr"           name="sistre"  />
+       <field field_ref="normstr"          name="normstr" />
+       <field field_ref="sheastr"          name="sheastr" />
+       
+       <!-- heat fluxes -->
+       <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+       <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+       <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+       <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+       <field field_ref="qt_ice"           name="qt_ice"     />
+       <field field_ref="qsr_ice"          name="qsr_ice"    />
+       <field field_ref="qns_ice"          name="qns_ice"    />
+       <field field_ref="qemp_ice"         name="qemp_ice"   />
+       <field field_ref="albedo"           name="albedo"     />
+       
+       <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+       <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+       <field field_ref="hfxsensib"        name="hfxsensib"  />
+       
+       <!-- salt fluxes -->
+       <field field_ref="sfxice"           name="sfxice" />
+       
+       <!-- mass fluxes -->
+       <field field_ref="vfxice"           name="vfxice" />
+       <field field_ref="vfxsnw"           name="vfxsnw" />
+       
+       <!-- categories -->
+       <field field_ref="icemask_cat"      name="simskcat"/>
+       <field field_ref="snwthic_cat"      name="snthicat"/>
+       <field field_ref="iceconc_cat"      name="siconcat"/>
+       <field field_ref="icethic_cat"      name="sithicat"/>
+       <field field_ref="icesalt_cat"      name="sisalcat"/>
+       <field field_ref="icetemp_cat"      name="sitemcat"/>
+       
+     </file>
+     
+     <file id="file22" name_suffix="_SBC_scalar" description="scalar variables" enabled=".true." >
+       <!-- global contents -->
+       <field field_ref="ibgvol_tot"       name="ibgvol_tot"   />
+       <field field_ref="sbgvol_tot"       name="sbgvol_tot"   />
+       <field field_ref="ibgarea_tot"      name="ibgarea_tot"  />
+       <field field_ref="ibgsalt_tot"      name="ibgsalt_tot"  />
+       <field field_ref="ibgheat_tot"      name="ibgheat_tot"  />
+       <field field_ref="sbgheat_tot"      name="sbgheat_tot"  />
+       
+       <!-- global drifts (conservation checks) -->
+       <field field_ref="ibgvolume"        name="ibgvolume"    />
+       <field field_ref="ibgsaltco"        name="ibgsaltco"    />
+       <field field_ref="ibgheatco"        name="ibgheatco"    />
+       <field field_ref="ibgheatfx"        name="ibgheatfx"    />
+       
+       <!-- global forcings  -->
+       <field field_ref="ibgfrcvoltop"     name="ibgfrcvoltop" />
+       <field field_ref="ibgfrcvolbot"     name="ibgfrcvolbot" />
+       <field field_ref="ibgfrctemtop"     name="ibgfrctemtop" />
+       <field field_ref="ibgfrctembot"     name="ibgfrctembot" />
+       <field field_ref="ibgfrcsal"        name="ibgfrcsal"    />
+       <field field_ref="ibgfrchfxtop"     name="ibgfrchfxtop" />
+       <field field_ref="ibgfrchfxbot"     name="ibgfrchfxbot" />
+     </file>
+     
+   </file_group>
+   
+   <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="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="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>
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,108 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context               =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="5d" min_digits="4">
+    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
+        <file id="file11" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"      />
+          <field field_ref="toce"         name="thetao"                                                                      operation="instant" freq_op="5d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="so"                                                                          operation="instant" freq_op="5d" > @soce_e3t / @e3t </field>
+          <field field_ref="sst"          name="tos"   />
+          <field field_ref="sss"          name="sos"   />
+          <field field_ref="ssh"          name="zos"   />
+          <field field_ref="sst"          name="tosstd"       long_name="sea surface temperature standard deviation"         operation="instant" freq_op="5d" > sqrt( @sst2 - @sst * @sst ) </field>
+          <field field_ref="ssh"          name="zosstd"       long_name="sea surface height above geoid standard deviation"  operation="instant" freq_op="5d" > sqrt( @ssh2 - @ssh * @ssh ) </field>
+          <field field_ref="sst"          name="sstdcy"       long_name="amplitude of sst diurnal cycle"                     operation="average" freq_op="1d" > @sstmax - @sstmin </field>
+          <field field_ref="mldkz5"   />
+          <field field_ref="mldr10_1" />
+          <field field_ref="mldr10_1"     name="mldr10_1dcy"  long_name="amplitude of mldr10_1 diurnal cycle"                operation="average" freq_op="1d" > @mldr10_1max - @mldr10_1min </field>
+          <field field_ref="sbt"      />
+          <field field_ref="heatc"        name="heatc" />
+          <field field_ref="saltc"        name="saltc" />
+
+	  <field field_ref="empmr"        name="wfo"      />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  />
+	  <field field_ref="qns_oce"      name="qns_oce"  />
+	  <field field_ref="qt_oce"       name="qt_oce"   />
+	  <field field_ref="saltflx"      name="sfx"      />
+	  <field field_ref="taum"         name="taum"     />
+	  <field field_ref="wspd"         name="windsp"   />
+	  <field field_ref="precip"       name="precip"   />
+	  <!-- ice and snow -->
+	  <field field_ref="snowpre" />
+	</file>
+
+	<file id="file12" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u" />
+	  <field field_ref="ssu"          name="uos"      />
+	  <field field_ref="uoce"         name="uo"       operation="instant" freq_op="5d" > @uoce_e3u / @e3u </field>
+	  <field field_ref="utau"         name="tauuo"    />
+          <field field_ref="uocetr_eff"   name="uocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="u_masstr"     name="vozomatr" />
+	  <field field_ref="u_heattr"     name="sozohetr" />
+	  <field field_ref="u_salttr"     name="sozosatr" />
+	</file>
+	
+	<file id="file13" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v" />
+	  <field field_ref="ssv"          name="vos"      />
+	  <field field_ref="voce"         name="vo"       operation="instant" freq_op="5d" > @voce_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="tauvo"    />
+          <field field_ref="vocetr_eff"   name="vocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="v_masstr"     name="vomematr" />
+	  <field field_ref="v_heattr"     name="somehetr" />
+          <field field_ref="v_salttr"     name="somesatr" />
+	</file>
+	
+	<file id="file14" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w" />
+	  <field field_ref="woce"         name="wo"       />
+	  <field field_ref="avt"          name="difvho"   />
+	  <field field_ref="w_masstr"     name="vovematr" />
+         <!-- variables available with ln_zdfiwm =T -->
+          <field field_ref="av_wave"      name="av_wave"    />
+          <field field_ref="bn2"          name="bn2"        />
+          <field field_ref="bflx_iwm"     name="bflx_iwm"   />
+          <field field_ref="pcmap_iwm"    name="pcmap_iwm"  />
+          <field field_ref="emix_iwm"     name="emix_iwm"   />
+          <field field_ref="av_ratio"     name="av_ratio"   />
+	</file>
+
+
+      </file_group> 
+
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+      </file_group>
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+      </file_group>
+	
+      
+      <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="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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,28 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  <context id="1_nemo" src="./1_context_nemo.xml"/>   <!--  NEMO       -->
+  <context id="2_nemo" src="./2_context_nemo.xml"/>   <!--  NEMO       -->
+  <context id="3_nemo" src="./3_context_nemo.xml"/>   <!--  NEMO       -->
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,398 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!                         AGRIF ICE configuration                      !
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "ORCA2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =      80   !  last  time step (std 5475)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 5400.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R2_zps_domcfg_agrif"    ! domain configuration filename
+      !
+      ln_closea    = .false.    !  F => suppress closed seas (defined by closea_mask field) 
+      !                         !       from the bathymetry at runtime.
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data                         (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   ln_tsd_dmp  = .true.          !  T-S restoring   (see namtra_dmp)
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''    ,    ''    ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+                           !     (also = the frequency of sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  =2 or 3 automatically for SI3 or CICE    ("key_si3" or "key_cice")
+                           !          except in AGRIF zoom where it has to be specified
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+   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      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namsbc_blk   !   namsbc_blk  generic Bulk formula                      (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR    = .true.     ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir = './'  !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+   !
+   nn_chldta   =      1       !  RGB : Chl data (=1) or cst value (=0)
+
+   cn_dir = './'  !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .true.    !  specific treatment at rivers mouths
+      rn_hrnf     =  15.e0    !  depth over which enhanced vertical mixing is used    (ln_rnf_mouth=T)
+      rn_avt_rnf  =   1.e-3   !  value of the additional vertical mixing coef. [m2/s] (ln_rnf_mouth=T)
+
+   cn_dir = './'  !  root directory for the location of the runoff files
+   !___________!_____________!___________________!___________!_____________!_________!___________!__________!__________!_______________!
+   !           !  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'  , ''       , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sssr     =     2     !  add a damping term to the surface freshwater flux
+      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]
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: No iceberg)
+!-----------------------------------------------------------------------
+   !  iceberg floats are not currently available with AGRIF
+   !     ===>>  forced deactivation in icbini.F90
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.     !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx   =    2      !  geothermal heat flux: = 2 read variable flux [mW/m2]
+
+   cn_dir = './'  !  root directory for the geothermal data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_qgh      ='geothermal_heating.nc'  ,       -12.        , 'heatflow',   .false.   , .true. , 'yearly'  ,   ''             ,   ''     ,   ''
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.     !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap   = .true.    !    laplacian operator
+   !                       !  Direction of action:
+   ln_traldf_iso   = .true.    !  iso-neutral (Standard operator)
+   !		       	         !  iso-neutral options:        
+   ln_traldf_msc   = .true.    !  Method of Stabilizing Correction      (both operators)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 20        !  space/time variation of eddy coef
+      !                             !   = 20     aht = 1/2  Ud. max(e1,e2)
+      rn_Ud        = 0.018          !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_eiv !   eddy induced velocity param.                            (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv     =.true.   ! use eddy induced velocity parameterization
+      !                        !  Coefficients:
+      nn_aei_ijk_t  = 21          ! space/time variation of the eiv coeficient
+      !                                !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                           !  time invariant coefficients:  aei0 = 1/2  Ue*Le 
+      rn_Ue        = 0.03              !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Le        = 200.e+3           !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+      !
+      ln_ldfeiv_dia =.true.   ! diagnose eiv stream function and velocities
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .true.   !  add a damping term (using resto.nc coef.)
+      nn_zdmp  =    0         !  vertical shape =0    damping throughout the water column
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true.  !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0   e3f = mean masked e3t divided by 4
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .true.     !  iso-level
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = -30         !  space/time variation of eddy coef
+   !                                !  =-30  read in eddy_viscosity_3D.nc
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  Enhanced Vertical Diffusion scheme
+      nn_evdm  =    0            !  evd apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd   =  100.           !  evd mixing coefficient [m2/s]
+   !
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,85 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+      ln_aEVP       = .false.          !     adaptive rheology (Kimmritz et al. 2016 & 2017)
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/README.rst	(revision 14097)
@@ -0,0 +1,106 @@
+**************
+Embedded zooms
+**************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Overview
+========
+
+AGRIF (Adaptive Grid Refinement In Fortran) is a library that
+allows the seamless space and time refinement over rectangular regions in NEMO.
+Refinement factors can be odd or even (usually lower than 5 to maintain stability).
+Interaction between grid is "two-ways" in the sense that
+the parent grid feeds the child grid open boundaries and
+the child grid provides volume averages of prognostic variables once
+a given number of time step is completed.
+These pages provide guidelines how to use AGRIF in NEMO.
+For a more technical description of the library itself, please refer to AGRIF_.
+
+Compilation
+===========
+
+Activating AGRIF requires to append the cpp key ``key_agrif`` at compilation time:
+
+.. code-block:: sh
+
+   ./makenemo [...] add_key 'key_agrif'
+
+Although this is transparent to users,
+the way the code is processed during compilation is different from the standard case:
+a preprocessing stage (the so called ``conv`` program) translates the actual code so that
+saved arrays may be switched in memory space from one domain to an other.
+
+Definition of the grid hierarchy
+================================
+
+An additional text file :file:`AGRIF_FixedGrids.in` is required at run time.
+This is where the grid hierarchy is defined.
+An example of such a file, here taken from the ``ICEDYN`` test case, is given below
+
+.. literalinclude:: ../../../tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in
+
+The first line indicates the number of zooms (1).
+The second line contains the starting and ending indices in both directions on the root grid
+(``imin=34 imax=63 jmin=34 jmax=63``) followed by the space and time refinement factors (3 3 3).
+The last line is the number of child grid nested in the refined region (0).
+A more complex example with telescoping grids can be found below and
+in the :file:`AGRIF_DEMO` reference configuration directory.
+
+.. todo::
+
+   Add some plots here with grid staggering and positioning?
+
+When creating the nested domain, one must keep in mind that
+the child domain is shifted toward north-east and
+depends on the number of ghost cells as illustrated by
+the *attempted* drawing below for ``nbghostcells=1`` and ``nbghostcells=3``.
+The grid refinement is 3 and ``nxfin`` is the number of child grid points in i-direction.
+
+.. image:: _static/agrif_grid_position.jpg
+
+Note that rectangular regions must be defined so that they are connected to a single parent grid.
+Hence, defining overlapping grids with the same refinement ratio will not work properly,
+boundary data exchange and update being only performed between root and child grids.
+Use of east-west periodic or north-fold boundary conditions is not allowed in child grids either.
+Defining for instance a circumpolar zoom in a global model is therefore not possible.
+
+Preprocessing
+=============
+
+Knowing the refinement factors and area,
+a ``NESTING`` pre-processing tool may help to create needed input files
+(mesh file, restart, climatological and forcing files).
+The key is to ensure volume matching near the child grid interface,
+a step done by invoking the :file:`Agrif_create_bathy.exe` program.
+You may use the namelists provided in the :file:`NESTING` directory as a guide.
+These correspond to the namelists used to create ``AGRIF_DEMO`` inputs.
+
+Namelist options
+================
+
+Each child grid expects to read its own namelist so that different numerical choices can be made
+(these should be stored in the form :file:`1_namelist_cfg`, :file:`2_namelist_cfg`, etc...
+according to their rank in the grid hierarchy).
+Consistent time steps and number of steps with the chosen time refinement have to be provided.
+Specific to AGRIF is the following block:
+
+.. literalinclude:: ../../namelists/namagrif
+   :language: fortran
+
+where sponge layer coefficients have to be chosen according to the child grid mesh size.
+The sponge area is hard coded in NEMO and applies on the following grid points:
+2 x refinement factor (from ``i=1+nbghostcells+1`` to ``i=1+nbghostcells+sponge_area``)
+
+.. rubric:: References
+
+.. bibliography:: zooms.bib
+   :all:
+   :style: unsrt
+   :labelprefix: A
+   :keyprefix: a-
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/cpp_AGRIF_DEMO.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/cpp_AGRIF_DEMO.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/cpp_AGRIF_DEMO.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_si3 key_iomput key_mpp_mpi key_agrif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/zooms.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/zooms.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AGRIF_DEMO/zooms.bib	(revision 14097)
@@ -0,0 +1,35 @@
+@article{DEBREU2012,
+   title = "Two-way nesting in split-explicit ocean models: Algorithms, implementation and validation",
+   journal = "Ocean Modelling",
+   volume = "49-50",
+   pages = "1 - 21",
+   year = "2012",
+   issn = "1463-5003",
+   doi = "10.1016/j.ocemod.2012.03.003",
+   author = "Laurent Debreu and Patrick Marchesiello and Pierrick Penven and Gildas Cambon",
+   keywords = "Two-way nesting, Finite difference method, Modeling, Boundary conditions, Coastal upwelling"
+}
+
+@article{PENVEN2006,
+   title = "Evaluation and application of the {ROMS} 1-way embedding procedure to the central california upwelling system",
+   journal = "Ocean Modelling",
+   volume = "12",
+   number = "1",
+   pages = "157 - 187",
+   year = "2006",
+   issn = "1463-5003",
+   doi = "10.1016/j.ocemod.2005.05.002",
+   author = "Pierrick Penven and Laurent Debreu and Patrick Marchesiello and James C. McWilliams",
+   keywords = "Ocean models, Boundary conditions, Embedding, Coastal upwelling, Mesoscale eddies, Eddy kinetic energy, North America, West Coast, Central upwelling system, Monterey Bay, 35–41°N, 128–121°W"
+}
+
+@article{SPALL1991,
+   author = {Spall, Michael A. and Holland, William R.},
+   title = {A Nested Primitive Equation Model for Oceanic Applications},
+   journal = {Journal of Physical Oceanography},
+   volume = {21},
+   number = {2},
+   pages = {205-220},
+   year = {1991},
+   doi = {10.1175/1520-0485(1991)021<0205:ANPEMF>2.0.CO;2},
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>      <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,141 @@
+<?xml version="1.0"?>
+
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+
+      <!--old      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> old --> <!-- 1h files --> 
+      <!-- TB files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."  >                      
+
+	<file id="file9" name_suffix="_shelftb_grid_T" description="TB ocean T grid variables" enabled=".TRUE." >
+	  <field field_ref="sst"  operation="instant" enabled=".TRUE." />
+	  <field field_ref="sbt"  operation="instant" enabled=".TRUE." />
+	  <field field_ref="sss"  operation="instant" enabled=".TRUE." />
+	  <field field_ref="sbs"  operation="instant" enabled=".TRUE." /> 
+	</file>
+	
+	<file id="file10" name_suffix="_shelftb_grid_U" description="TB ocean U grid variables" enabled=".TRUE." >
+	  <field field_ref="ssu"  operation="instant" enabled=".TRUE." />
+	  <field field_ref="sbu"  operation="instant" enabled=".TRUE." />
+	</file>
+	
+	<file id="file11" name_suffix="_shelftb_grid_V" description="TB ocean V grid variables" enabled=".TRUE." >
+	  <field field_ref="ssv"  operation="instant" enabled=".TRUE." />
+	  <field field_ref="sbv"  operation="instant" enabled=".TRUE." />
+	</file>
+	
+      </file_group>
+
+      <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="25h_mean" output_freq="1d" output_level="10" enabled=".TRUE.">
+
+
+     <file id="file12" name_suffix="_25hourm_grid_T" description="ocean T grid variables, 25h meaned" enabled=".TRUE." >
+     <field field_ref="temper25h"   name="votemper"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="tempis25h"   name="votempis"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="salin25h"    name="vosaline"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="ssh25h"      name="sossheig"  operation="instant" enabled=".TRUE."/>
+    </file>
+
+     <file id="file13" name_suffix="_25hourm_grid_U" description="ocean U grid variables, 25h meaned" enabled=".TRUE." >
+     <field field_ref="vozocrtx25h" name="vozocrtx"  operation="instant" enabled=".TRUE."/>
+    </file>
+
+     <file id="file14" name_suffix="_25hourm_grid_V" description="ocean V grid variables, 25h meaned" enabled=".TRUE." >
+     <field field_ref="vomecrty25h" name="vomecrty"  operation="instant" enabled=".TRUE."/>
+    </file>
+
+     <file id="file15" name_suffix="_25hourm_grid_W" description="ocean W grid variables, 25h meaned" enabled=".TRUE." >
+     <field field_ref="vovecrtz25h"          name="vovecrtz"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="avt25h"               name="votkeavt"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="avm25h"               name="votkeavm"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="tke25h"               name="votke"  operation="instant" enabled=".TRUE."/>
+     <field field_ref="mxln25h"              name="mxln"   operation="instant" enabled=".TRUE."/>
+    </file>
+      </file_group>
+     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."> <!-- 1d files -->
+
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="sst"          name="tos" />
+	  <field field_ref="sss"          name="sos" />
+	  <field field_ref="ssh"          name="zos" />
+	</file>
+
+	<file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="ssu"          name="uos" />
+	</file>
+	
+	<file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="ssv"          name="vos" />
+	</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 -->   
+
+	<file id="file4" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="toce"         name="thetao" />
+	  <field field_ref="soce"         name="so"     />
+	  <field field_ref="sst"          name="tos"    />
+	  <field field_ref="sst2"         name="tossq"  />
+	  <field field_ref="sss"          name="sos"    />
+	  <field field_ref="ssh"          name="zos"    />
+	  <field field_ref="ssh2"         name="zossq"  />
+	  <field field_ref="empmr"        name="wfo"    />
+	  <field field_ref="qsr"          name="rsntds" />
+	  <field field_ref="qt"           name="tohfls" />
+	  <field field_ref="taum"     />
+	  <field field_ref="mldkz5"   />
+	  <field field_ref="mldr10_1" />
+	</file>
+	
+	<file id="file5" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="uoce"         name="uo"    />
+	  <field field_ref="ssu"          name="uos"   />
+	  <field field_ref="utau"         name="tauuo" />
+	</file>
+	
+	<file id="file6" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="voce"         name="vo"    />
+	  <field field_ref="ssv"          name="vos"   />
+	  <field field_ref="vtau"         name="tauvo" />
+	</file>
+	
+	<file id="file7" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="woce"         name="wo"     />
+	  <field field_ref="avt"          name="difvho" />
+	</file>
+	
+      </file_group>
+
+      <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="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>
+    
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios">
+
+      <variable_definition>
+	
+	  <variable id="info_level"                type="int">0</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+               
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,390 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!                          AMM12 configuration                         !
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "AMM12"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    1296   !  last  time step (std 1 day = 144)
+   nn_date0    =  20120102 !  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)
+   cn_ocerst_in   = "amm12_restart_oce"   !  suffix of ocean restart name (input)
+   cn_ocerst_out  = "restart"             !  suffix of ocean restart name (input)
+   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) 
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =   600.    !  time step for the dynamics (and tracer if nn_acc=0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.   !  (=T) read the domain configuration file
+      cn_domcfg = "AMM_R12_sco_domcfg" ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)          (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+   ln_flx      = .true.    !  flux formulation                          (T => fill namsbc_flx)
+   ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation
+!-----------------------------------------------------------------------
+   cn_dir      = './fluxes/'  !  root directory for the fluxes data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_utau     = 'amm12_utau'            ,          1.       , 'utau'    ,  .false.    , .false., 'daily'   ,  ''              ,  ''      , ''
+   sn_vtau     = 'amm12_vtau'            ,          1.       , 'vtau'    ,  .false.    , .false., 'daily'   ,  ''              ,  ''      , ''
+   sn_qtot     = 'amm12_flx'             ,          3.       , 'sonsfldo',  .true.     , .false., 'daily'   ,  ''              ,  ''      , ''
+   sn_qsr      = 'amm12_flx'             ,          3.       , 'soshfldo',  .true.     , .false., 'daily'   ,  ''              ,  ''      , ''
+   sn_emp      = 'amm12_flx'             ,          3.       , 'sowafldo',  .true.     , .false., 'daily'   ,  ''              ,  ''      , ''
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   nn_chldta   =      0      !  RGB : Chl data (=1) or cst value (=0)
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sstr     =     1     !  add a retroaction term in the surface heat       flux (=1) or not (=0)
+   nn_sssr     =     0     !  add a damping     term in the surface freshwater flux (=2)
+                           !  or to SSS only (=1) or no damping term (=0)
+   rn_deds     =  -27.7    !  magnitude of the damping on salinity   [mm/day]
+
+   cn_dir      = 'fluxes/' !  root directory for the location of the runoff files
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_sst      = 'amm12_sstref'          ,        24.        ,  'sst'     ,   .true.   , .false., 'daily'   , ''               , ''       , ''
+   sn_sss      = 'sss_data'              ,        -1.        ,  'sss'     ,   .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .false.   !  specific treatment at rivers mouths
+   ln_rnf_depth = .true.    !  read in depth information for runoff
+   ln_rnf_tem   = .true.    !  read in temperature information for runoff
+   ln_rnf_sal   = .true.    !  read in salinity information for runoff
+
+   cn_dir = './'  !  root directory for the flux data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_rnf      = 'amm12_rivers'          ,        24.        , 'rorunoff',   .false.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_cnf      = 'runoff_1m_nomask'      ,         0.        , 'socoefr0',   .false.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_s_rnf    = 'amm12_rivers'          ,        24.        , 'rosaline',   .false.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_t_rnf    = 'amm12_rivers'          ,        24.        , 'rotemper',   .false.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_dep_rnf  = 'amm12_rivers'          ,        24.        , 'rodepth' ,   .false.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+   rn_pref     = 101000.   !  reference atmospheric pressure   [N/m2]
+   ln_ref_apr  = .false.   !  ref. pressure: global mean Patm (T) or a constant (F)
+   ln_apr_obc  = .true.    !  inverse barometer added to OBC ssh data
+
+   cn_dir = './fluxes/'    !  root directory for the Patm data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_apr      = 'amm12_mslp'            ,          1.       ,'p_msl'    ,   .false.   , .false., 'daily'  ,    ''            ,    ''    ,      ''
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection
+!-----------------------------------------------------------------------
+   rn_shlat    =     0     !  free slip
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tide     = .true.    ! Activate tides
+      ln_tide_pot   = .true.  !  use tidal potential forcing
+
+   clname(1)     =   'Q1'   !  name of constituent
+   clname(2)     =   'O1'
+   clname(3)     =   'P1'
+   clname(4)     =   'S1'
+   clname(5)     =   'K1'
+   clname(6)     =   '2N2'
+   clname(7)     =   'MU2'
+   clname(8)     =   'N2'
+   clname(9)     =   'NU2'
+   clname(10)    =   'M2'
+   clname(11)    =   'L2'
+   clname(12)    =   'T2'
+   clname(13)    =   'S2'
+   clname(14)    =   'K2'
+   clname(15)    =   'M4'
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+    ln_bdy     = .true.   !  Use unstructured open boundaries
+    nb_bdy     =  1       !  number of open boundary sets
+    !
+    cn_dyn2d     = 'flather'
+    nn_dyn2d_dta =  3
+    cn_tra       =  'frs'
+    nn_tra_dta   =   1 
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       
+!-----------------------------------------------------------------------
+   ln_zinterp  = .false.      !  T if a vertical interpolation is required. Variables gdep[tuv] and e3[tuv] must exist in the file
+   !                          !  automatically defined to T if the number of vertical levels in bdy dta /= jpk
+   ln_full_vel = .false.      !  T if [uv]3d are "full" velocities and not only its baroclinic components
+   !                          !  in this case, baroclinic and barotropic velocities will be recomputed -> [uv]2d not needed
+   !
+   cn_dir  =    './bdydta/'
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   bn_ssh      = 'amm12_bdyT_dyn2d'      ,         24.       , 'sossheig',    .true.   , .false.,  'daily'  ,    ''            ,   ''     , ''
+   bn_u2d      = 'amm12_bdyU_dyn2d'      ,         24.       , 'vobtcrtx',    .true.   , .false.,  'daily'  ,    ''            ,   ''     , ''
+   bn_v2d      = 'amm12_bdyV_dyn2d'      ,         24.       , 'vobtcrty',    .true.   , .false.,  'daily'  ,    ''            ,   ''     , ''
+   bn_u3d      = 'amm12_bdyU_dyn3d'      ,         24.       , 'vozocrtx',    .true.   , .false.,  'daily'  ,    ''            ,   ''     , ''
+   bn_v3d      = 'amm12_bdyV_dyn3d'      ,         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'  ,    ''            ,   ''     , ''
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries
+!-----------------------------------------------------------------------
+   filtide      = 'bdydta/amm12_bdytide_'         !  file name root of tidal forcing files
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF =F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF =F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_loglayer = .true.     !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+   rn_Cd0     =  2.5e-3   !  drag coefficient [-]
+   rn_Uc0     =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax   =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0     =  0.0e0    !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0      =  0.003    !  roughness [m]  (ln_loglayer=T)
+/
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.     !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   =  .true.   !    laplacian operator
+   ln_traldf_hor   =  .true.   !  horizontal (geopotential)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 0         !  =  0   constant = 1/2  Ud*Ld   (lap case) 
+      rn_Ud        = 0.01           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 10.e+3         !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true.  !  energy & enstrophy scheme
+      nn_een_e3f = 1             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_prj  = .true.    !  s-coordinate (Pressure Jacobian scheme)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts = .true.   ! split-explicit free surface
+   ln_bt_auto   = .false.  ! Number of sub-step defined from:
+   nn_baro      = 30       ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_blp =  .true.     !  bilaplacian operator
+   ln_dynldf_lev =  .true.     !  iso-level
+   nn_ahm_ijk_t  = 0           !  =0   constant = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      =  0.12            !  lateral viscous velocity [m/s]
+      rn_Lv      = 10.e+3           !  lateral viscous length   [m]  
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfgls   = .true.    !  Generic Length Scale closure              (T =>   fill namzdf_gls)
+   !                       ! coefficients
+   rn_avm0     =   0.1e-6     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.1e-6     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+   rn_charn    =  100000.  !  Charnock constant for wb induced roughness length
+   nn_z0_met   = 1         !  Method for surface roughness computation (0/1/2)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default F)
+!-----------------------------------------------------------------------
+   ln_dia25h  = .true.    ! Choose 25h mean output or not
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/cpp_AMM12.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/cpp_AMM12.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/AMM12/cpp_AMM12.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_diainstant key_mpp_mpi key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,25 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" 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 id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"                           />
+          <field field_ref="toce"         name="votemper"     operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"     operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"                       />
+          <field field_ref="mldr10_1"                     />
+          <field field_ref="empmr"        name="wfo"      />
+          <field field_ref="qsr_oce"      name="qsr_oce"  />
+          <field field_ref="qns_oce"      name="qns_oce"  />
+          <field field_ref="qt_oce"       name="qt_oce"   />
+          <field field_ref="saltflx"      name="sfx"      />
+          <field field_ref="taum"         name="taum"     />
+          <field field_ref="wspd"         name="windsp"   />
+          <field field_ref="precip"       name="precip"   />
+        </file>
+
+       <file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="uo"       operation="instant" freq_op="1d" > @uoce_e3u / @e3u </field>
+          <field field_ref="utau"         name="tauuo"    />
+        </file>
+
+       <file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vo"       operation="instant" freq_op="1d" > @voce_e3v / @e3v </field>
+          <field field_ref="vtau"         name="tauvo"    />
+        </file>
+
+        <file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="e3w" />
+          <field field_ref="woce"         name="wo"       />
+          <field field_ref="avt"          name="difvho"   />
+        </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 -->   
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly 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>
+    
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,501 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE :   Reference namelist_ref                                !!
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  :  1 - Domain & run manager (namrun, namcfg, namdom, namtsd, namcrs, namc1d, namc1d_uvd)
+!! namelists    2 - Surface boundary (namsbc, namsbc_flx, namsbc_blk, namsbc_cpl,
+!!                                    namsbc_sas, namtra_qsr, namsbc_rnf,
+!!                                    namsbc_isf, namsbc_iscpl, namsbc_apr, 
+!!                                    namsbc_ssr, namsbc_wave, namberg)
+!!              3 - lateral boundary (namlbc, namagrif, nambdy, nambdy_tide)
+!!              4 - top/bot boundary (namdrg, namdrg_top, namdrg_bot, nambbc, nambbl)
+!!              5 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_eiv, namtra_dmp)
+!!              6 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
+!!              7 - Vertical physics (namzdf, namzdf_ric, namzdf_tke, namzdf_gls, namzdf_iwm)
+!!              8 - diagnostics      (namnc4, namtrd, namspr, namflo, namhsb)
+!!              9 - Obs & Assim      (namobs, nam_asminc)
+!!             10 - miscellaneous    (nammpp, namctl, namsto)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   C1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_bathy    =  4198.   ! depth in meters
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      = "C1D_PAPA"!  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   87600   !  last  time step (std 5475)
+   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_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)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =  360.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   
+   cn_dir      = './'      !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'init_PAPASTATION'       ,         24.       ,'votemper',  .false.     , .true.,  'daily'  ,    ''            ,    ''    ,    ''
+   sn_sal      = 'init_PAPASTATION'       ,         24.       ,'vosaline',  .false.     , .true.,  'daily'  ,    ''            ,    ''    ,    ''
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+   rn_lat1d    =      50   !  Column latitude
+   rn_lon1d    =    -145   !  Column longitude
+   ln_c1d_locpt =  .true.   ! Localization of 1D config in a grid (T) or independant point (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   !                       !  =T read U-V fields for:
+   ln_uvd_init   = .false.       !  ocean initialisation
+   ln_uvd_dyndmp = .false.       !  U-V restoring
+
+   cn_dir      = './'      !  root directory for the U-V data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ucur     = 'ucurrent'              ,         -1.       ,'u_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Ume'   , ''
+   sn_vcur     = 'vcurrent'              ,         -1.       ,'v_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Vme'   , ''
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.   !  Bulk formulation                          (T => fill namsbc_blk )
+      !              ! Type of coupling (Ocean/Ice/Atmosphere) :
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR     = .true.   ! "NCAR"      algorithm   (Large and Yeager 2008)
+      !
+      rn_zqt      =  2.       !  Air temperature & humidity reference height (m)
+      rn_zu       = 10.       !  Wind vector reference height (m)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !       weights filename               ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'forcing_C1D_PAPA'   ,  3.   , 'sowinu10',   .true.     , .false. , 'yearly'  , ''   ,''   , ''
+   sn_wndj     = 'forcing_C1D_PAPA'   ,  3.   , 'sowinv10',   .true.     , .false. , 'yearly'  , ''   ,''   , ''
+   sn_qsr      = 'forcing_C1D_PAPA'   ,  3.   , 'sosudosw',   .false.    , .false. , 'yearly'  , ''  , ''   , ''
+   sn_qlw      = 'forcing_C1D_PAPA'   ,  3.   , 'sosudolw',   .false.    , .false. , 'yearly'  , ''  , ''   , ''
+   sn_tair     = 'forcing_C1D_PAPA'   ,  3.   , 'sotemair',   .true.     , .false. , 'yearly'  , ''  , ''   , ''
+   sn_humi     = 'forcing_C1D_PAPA'   ,  3.   , 'sohumspe',   .true.     , .false. , 'yearly'  , ''  , ''   , ''
+   sn_prec     = 'forcing_C1D_PAPA'   ,  3.   , 'sowaprec',   .false.    , .false. , 'yearly'  , ''  , ''   , ''
+   sn_snow     = 'forcing_C1D_PAPA'   ,  3.   , 'sososnow',   .false.    , .false. , 'yearly'  , ''  , ''   , ''
+   sn_slp      = 'forcing_C1D_PAPA'   ,  3.   , 'somslpre',   .true.     , .false. , 'yearly'  , ''  , ''   , ''
+   sn_tdif     = 'forcing_C1D_PAPA'   , 24.   , 'taudif'  ,   .false.    , .false. , 'yearly'  , ''  , ''   , ''
+
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+
+   sn_chl      ='chlorophyll_PAPASTATION',         -1.       , 'CHLA'    ,   .true.     , .true. , 'yearly'  ,        ''       ,    ''    , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =  0.   !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin  = .true.   !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.         !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .true. !  No tracer advection
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   = .true.   !  No explicit diffusion
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true. !  energy    conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts   = .true.   ! split-explicit free surface
+      ln_bt_fw      = .false.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfgls   = .true.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diadct    ! transports through some sections                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc    !   assimilation increments                              ('key_asminc')
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,108 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                     ***  MODULE usrdef_hgr   ***
+   !!
+   !!                     ===  C1D_PAPA configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp        ! ocean space and time domain
+   USE c1d      ,  ONLY: rn_lon1d, rn_lat1d ! ocean lon/lat define by namelist
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE usrdef_nam     !
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called in domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!
+      !!                Here C1D_PAPA configuration :
+      !!          Rectangular 3x3 domain 
+      !!          - Located at 150E-50N
+      !!          - a constant horizontal resolution  
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) ::   zlam1, zlam0, zcos_alpha, zim1 , zjm1 , ze1  , ze1deg, zf0   ! local scalars
+      REAL(wp) ::   zphi1, zphi0, zsin_alpha, zim05, zjm05, zbeta, znorme, zfact !   -      -
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : C1D configuration'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   uniform grid spacing WITH Coriolis force'
+      !
+      !                       !==  grid point position  ==!   (Special case of 1D config: all lon/lat are the same)
+      !                       ! longitude
+      plamt(:,:) = rn_lon1d
+      plamu(:,:) = rn_lon1d 
+      plamv(:,:) = rn_lon1d
+      plamf(:,:) = rn_lon1d
+      !                       ! latitude
+      pphit(:,:) = rn_lat1d
+      pphiu(:,:) = rn_lat1d
+      pphiv(:,:) = rn_lat1d
+      pphif(:,:) = rn_lat1d
+      !                       !== Horizontal scale factors ==! (in meters)
+      !                     
+      !                                         ! constant grid spacing
+      pe1t(:,:) = 100.  ;   pe2t(:,:) = 100.
+      pe1u(:,:) = 100.  ;   pe2u(:,:) = 100.
+      pe1v(:,:) = 100.  ;   pe2v(:,:) = 100.
+      pe1f(:,:) = 100.  ;   pe2f(:,:) = 100.
+      !
+      !                                         ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                              !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp                       !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp                       !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 0                 !  indicate to compute Coriolis parameter afterward
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,100 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                     ***  MODULE usrdef_nam   ***
+   !!
+   !!                     ===  C1D_PAPA configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp             ! ocean space and time domain
+   USE dom_oce  , ONLY: ln_zco, ln_zps, ln_sco   ! flag of type of coordinate
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called in nemogcm.F90 module
+
+   !                              !!* namusr_def namelist *!!
+   LOGICAL, PUBLIC ::   ln_bench   ! =T benchmark test with gyre: the gridsize is constant (no need to adjust timestep or viscosity)
+   INTEGER, PUBLIC ::   nn_GYRE    ! 1/nn_GYRE = the resolution chosen in degrees and thus defining the horizontal domain size
+   REAL(wp), PUBLIC::   rn_bathy   ! Depth in meters for 1D configuration
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here C1D configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ rn_bathy
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'C1D'               ! name & resolution (not used)
+      kk_cfg = 0
+
+      ! Global Domain size:  C1D domain is 3 x 3 grid-points x 75 or vertical levels
+      kpi = 3
+      kpj = 3
+      kpk = 75 
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio =  7                   ! C1D configuration : 3x3 basin with cyclic Est-West and Norht-South condition
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : C1 case'
+         WRITE(numout,*) '      type of vertical coordinate : '
+         WRITE(numout,*) '         z-coordinate flag                     ln_zco = ', ln_zco
+         WRITE(numout,*) '         z-partial-step coordinate flag        ln_zps = ', ln_zps
+         WRITE(numout,*) '         s-coordinate flag                     ln_sco = ', ln_sco
+         WRITE(numout,*) '      C1D domain = 3 x 3 x75 grid-points                '
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      C1D : closed basin                       jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,185 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                       ===  C1D_PAPA configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-06  (R. Bourdalle-Badie)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE depth_e3       ! depth <=> e3
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   ji, jj, jk        ! dummy indices
+      INTEGER  ::   ik                ! local integers
+      REAL(wp) ::   zfact, z1_jpkm1   ! local scalar
+      REAL(wp) ::   ze3min            ! local scalar
+      REAL(wp) ::   zt, zw            ! local scalars
+      REAL(wp) ::   zsur, za0, za1, zkth, zacr        ! Values for the Madec & Imbard (1996) function
+      REAL(wp) ::   za2, zkth2, zacr2                 ! Values for optional double tanh function set from parameters
+      REAL(wp), DIMENSION(jpi,jpj) ::   zht, zhu, z2d ! 2D workspace
+
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : C1D configuration (zps-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .FALSE.         ! C1D case:  z-coordinate without ocean cavities
+      ld_zps    = .TRUE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      ! Set parameters of z(k) function
+      ! -------------------------------
+      zsur =   -3958.95137127683
+      za0  =    103.953009600000
+      za1  =    2.41595126900000
+      zkth =    15.3510137000000
+      zacr =    7.00000000000000
+      za2  =    100.760928500000
+      zkth2=    48.0298937200000
+      zacr2=    13.0000000000000
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '     zgr_z75L   : Reference vertical z-coordinates '
+         WRITE(numout,*) '     ~~~~~~~'
+         WRITE(numout,*) '       C1D case : L75 function with the following coefficients :'
+         WRITE(numout,*) '                 zsur = ', zsur
+         WRITE(numout,*) '                 za0  = ', za0
+         WRITE(numout,*) '                 za1  = ', za1
+         WRITE(numout,*) '                 zkth = ', zkth
+         WRITE(numout,*) '                 zacr = ', zacr
+         WRITE(numout,*) '                 za2  = ', za2
+         WRITE(numout,*) '                 zkth2= ', zkth2
+         WRITE(numout,*) '                 zacr2= ', zacr2
+      ENDIF
+
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      zht(:,:) = rn_bathy
+      !
+      DO jk = 1, jpk          ! depth at T and W-points
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) = ( zsur + za0 * zw + za1 * zacr * LOG ( COSH( (zw-zkth ) / zacr  ) )    &
+                  &                    + za2 * zacr2* LOG ( COSH( (zw-zkth2) / zacr2 ) )  )
+         pdept_1d(jk) = ( zsur + za0 * zt + za1 * zacr * LOG ( COSH( (zt-zkth ) / zacr  ) )    &
+                  &                    + za2 * zacr2* LOG ( COSH( (zt-zkth2) / zacr2 ) )  )
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d )
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d )
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      k_top(:,:) = 1 
+      !                                   !* bottom ocean compute from the depth of grid-points
+      k_bot(:,:) = jpkm1
+      DO jk = jpkm1, 1, -1
+        ze3min = 0.1_wp * pe3t_1d (jk)
+         WHERE( zht(:,:) < pdepw_1d(jk) + ze3min )   k_bot(:,:) = jk-1
+      END DO
+      !
+      !                                !* vertical coordinate system
+      DO jk = 1, jpk                      ! initialization to the reference z-coordinate
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      DO jj = 1, jpj                      ! bottom scale factors and depth at T- and W-points
+         DO ji = 1, jpi
+            ik = k_bot(ji,jj)
+            pdepw(ji,jj,ik+1) = MIN( zht(ji,jj) , pdepw_1d(ik+1) )
+            pe3t (ji,jj,ik  ) = pdepw(ji,jj,ik+1) - pdepw(ji,jj,ik)
+            pe3t (ji,jj,ik+1) = pe3t (ji,jj,ik  ) 
+            !
+            pdept(ji,jj,ik  ) = pdepw(ji,jj,ik  ) + pe3t (ji,jj,ik  ) * 0.5_wp
+            pdept(ji,jj,ik+1) = pdepw(ji,jj,ik+1) + pe3t (ji,jj,ik+1) * 0.5_wp
+            pe3w (ji,jj,ik+1) = pdept(ji,jj,ik+1) - pdept(ji,jj,ik)              ! = pe3t (ji,jj,ik  )
+         END DO
+      END DO         
+      !                                   ! bottom scale factors and depth at  U-, V-, UW and VW-points
+      !                                   ! usually Computed as the minimum of neighbooring scale factors
+      pe3u (:,:,:) = pe3t(:,:,:)          ! HERE C1D configuration : 
+      pe3v (:,:,:) = pe3t(:,:,:)          !    e3 increases with k-index 
+      pe3f (:,:,:) = pe3t(:,:,:)          !    so e3 minimum of (i,i+1) points is (i) point
+      pe3uw(:,:,:) = pe3w(:,:,:)          !    in j-direction e3v=e3t and e3f=e3v
+      pe3vw(:,:,:) = pe3w(:,:,:)          !    ==>>  no need of lbc_lnk calls
+      !      
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/cpp_C1D_PAPA.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/cpp_C1D_PAPA.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/C1D_PAPA/cpp_C1D_PAPA.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_c1d key_mpp_mpi key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,39 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>      <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-pisces.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-pisces.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/file_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/file_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/file_def_nemo.xml	(revision 14097)
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" 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_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>
+    
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios">
+
+      <variable_definition>
+	
+	  <variable id="info_level"                type="int">0</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+               
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,254 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  : GYRE Configuration namelist : overwrite reference namelist
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "GYRE"   !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    4320   !  last  time step
+   nn_leapy    =      30   !  Leap year calendar (1) or not (0)
+   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)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=F) user defined configuration           (F => create/check namusr_def)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   GYRE user defined namelist  
+!-----------------------------------------------------------------------
+   nn_GYRE     =     1     !  GYRE resolution [1/degrees]
+   ln_bench    = .false.   !  ! =T benchmark with gyre: the gridsize is kept constant
+   jpkglo      =    31     !  number of model levels
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 7200.     !  time step for the dynamics
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)          (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+   ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   ln_qsr_2bd  = .true.    !  2 bands              light penetration
+   nn_chldta   =      0    !  RGB : Chl data (=1) or cst value (=0)
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.     !  non-linear  drag: Cd = Cd0 |U|
+/
+
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.      !  = Use EOS80 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   =  .true.   !    laplacian operator
+   ln_traldf_iso   =  .true.   !  iso-neutral (standard operator)
+   nn_aht_ijk_t    = 0         !  = 0   constant = 1/2  Ud*Ld   (lap case) 
+      rn_Ud        = 0.02           !  lateral diffusive velocity [m/s]
+      rn_Ld        = 100.e+3        !  lateral diffusive length   [m]
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.    !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_lev =  .true.     !  iso-level
+   nn_ahm_ijk_t  = 0           !  = 0  constant = 1/2  Uv*Lv   (lap case) 
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] 
+      rn_Lv      = 100.e+3          !  lateral viscous length   [m]
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+      nn_evdm     =    1         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   !                       ! coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   nn_etau     =   0       !  penetration of tke below the mixed layer (ML) due to internal & intertial waves
+/
+
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,59 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO-TOP : GYRE_BFM configuration namelist used to overwrite SHARED/namelist_top_ref
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   ln_top_euler  = .true.    !  use Euler time-stepping for TOP
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   ln_trcdta     =  .false.        !  Initialisation from data input file (T) or not (F)
+!
+!                !    name   !           title of the field            !   units    ! initial data from file or not ! 
+   sn_tracer(1)   = 'DUMMY   ' , 'Dummy tracer      '                 ,  'dummy-units' ,  .false.
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+   ln_trcadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   =  .true.     !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/runscript
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/runscript	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/EXPREF/runscript	(revision 14097)
@@ -0,0 +1,40 @@
+#! /bin/sh 
+### This is an example of a runscript for the LSF queueing system
+#BSUB -a poe
+#BSUB -J GYRE_BFM         # Name of the job.
+#BSUB -o GYRE_BFM_%J.out  # Appends std output to file %J.out.
+#BSUB -e GYRE_BFM_%J.err  # Appends std error to file %J.out.
+#BSUB -P nemo
+#BSUB -q poe_short    # queue
+#BSUB -n 4            # Number of CPUs
+
+set -evx
+
+export MP_WAIT_MODE=poll
+export MP_POLLING_INTERVAL=30000000
+export MP_SHARED_MEMORY=yes
+export MP_EUILIB=us
+export MP_EUIDEVICE=sn_all
+export LDR_CNTRL=TEXTPSIZE=64K@STACKPSIZE=64K@DATAPSIZE=64K
+export MP_TASK_AFFINITY=core
+
+EXP="EXP00"
+
+workdir="TO_BE_SET_BY_USER"
+execdir=`pwd`
+
+if [ ! -d ${workdir} ] ; then
+  mkdir -p ${workdir}
+fi
+
+cd ${workdir}
+rm -rf *
+# Copy files to exp folder
+cp ${execdir}/opa ./opa.x
+cp ${execdir}/* ./
+
+# Launch the model
+
+mpirun.lsf opa.x 
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/README
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/README	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/README	(revision 14097)
@@ -0,0 +1,90 @@
+-----------------------------------------------------------------------
+Coupling with the Biogeochemical Flux Model (BFM)
+-----------------------------------------------------------------------
+Author: M. Vichi, BFM system team and NEMO system team
+INFO HELPDESK: info@bfm-community.eu
+WEB SITE: www.bfm-community.eu
+REVISION DATE: October 2013
+
+Please address any technical query to the BFM System Team 
+bfm_st@lists.cmcc.it
+-----------------------------------------------------------------------
+
+-----------------------------------------------------------------------
+What is the BFM?
+-----------------------------------------------------------------------
+The Biogeochemical Flux Model (BFM) is a numerical model for the 
+simulation of the dynamics of major biogeochemical properties 
+in marine ecosystems.  The BFM is open source software freely available 
+under the GNU Public License. The model can be used in standalone mode 
+to simulate a 0-D system or coupled with other OGCM.
+The coupling with NEMO is maintained by CMCC as part of the 
+NEMO system team activity
+
+-----------------------------------------------------------------------
+How to get the BFM code
+-----------------------------------------------------------------------
+The code can be downloaded from http://www.bfm-community.eu after
+the registration of a new user. Follow the instructions on how to 
+install the code. It is recommended to run the STANDALONE test cases 
+before using the NEMO-BFM coupled system.
+
+-----------------------------------------------------------------------
+Compile NEMO with the BFM 
+-----------------------------------------------------------------------
+NEMO-BFM is compiled from the BFM configuration script relying on the
+NEMO FCM compilation environment. This is done to allow BFM users to
+use new configurations in NEMO that are not part of the NEMO
+standard distribution code.
+The BFM configuration shipped with NEMO is GYRE_BFM (see next section)
+
+Make sure that the BFMDIR variable is defined in your environment
+and define the variable NEMODIR pointing to the root of NEMO source code
+It is assumed here that you have expanded the bfm in /home/user/bfm
+and the root of this NEMO directory in /home/user/nemo then
+and that you have already adjusted the appropriate ARCHFILE that
+is used for the NEMO compilation with makenemo in ../../ARCH
+
+Execute the following commands:
+>> export BFMDIR=/home/user/bfm
+>> export NEMODIR=/home/user/nemo
+>> cd $BFMDIR/build
+>> ./bfm_config.sh -gcd -p GYRE_BFM
+
+The script will generate (-g) the BFM code, then launch 
+makenemo for compilation (-c) and create the run directory
+(-d) in $BFMDIR/run.
+
+to get information on how to use the BFM configuration script run
+>> ./bfm_config.sh -h
+
+-----------------------------------------------------------------------
+Standard test case
+-----------------------------------------------------------------------
+The distributed standard test case is GYRE_BFM, a version of GYRE
+with a full-blown BFM. It is a demnstration simulation and it is not
+meant to produce any published result. 
+GYRE_BFM runs with analytical input data only.
+The namelists for the BFM are not distributed with NEMO but are 
+generated directly by the BFM, in directory $BFMDIR/run/gyre_bfm. 
+The generation of the BFM namelist also copy the required NEMO
+namelist and namelist_top files to this directory. 
+This is why there are no namelist files found in the standard 
+run directory $NEMODIR/NEMOGCM/CONFIG/GYRE_BFM/EXP00 
+
+Note for expert users:
+If a user prefers to work in the NEMO directory than she has to
+copy the generated namelists there 
+>> cp $BFMDIR/run/gyre_bfm/* $NEMODIR/NEMOGCM/CONFIG/GYRE_BFM/EXP00
+Once the BFM code has been generated the first time, the code can be 
+also rebuilt with the standard NEMO command:
+>> ./makenemo -n GYRE_BFM -m ARCHFILE -e $BFMDIR/src/nemo 
+
+-----------------------------------------------------------------------
+Other examples
+-----------------------------------------------------------------------
+Other couplings with NEMO are available in $BFMDIR/build/configurations.
+Run the command 
+>> ./bfm_config.sh -P
+to get a list of available presets
+Please refer to the README file in each directory for more information.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/cpp_GYRE_BFM.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/cpp_GYRE_BFM.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_BFM/cpp_GYRE_BFM.fcm	(revision 14097)
@@ -0,0 +1,2 @@
+bld::tool::fppkeys   key_top key_my_trc key_mpp_mpi key_iomput
+inc $BFMDIR/src/nemo/bfm.fcm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,39 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>      <!--  NEMO ocean dynamics                     -->
+    <field_definition src="./field_def_nemo-pisces.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-pisces.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/file_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/file_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/file_def_nemo.xml	(revision 14097)
@@ -0,0 +1,102 @@
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" 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 id="file1" 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"  />
+	  <field field_ref="empmr"        name="sowaflup"  />
+	  <field field_ref="qsr"          name="soshfldo"  />
+          <field field_ref="saltflx"      name="sosfldow"  />
+	  <field field_ref="qt"           name="sohefldo"  />
+	  <field field_ref="mldr10_1"     name="somxl010"  />
+	  <field field_ref="mldkz5"       name="somixhgt"  />
+        </file>
+	
+        <file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="vozocrtx"  />
+          <field field_ref="utau"         name="sozotaux"  />
+        </file>
+	
+        <file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vomecrty"  /> 
+          <field field_ref="vtau"         name="sometauy"  /> 
+        </file>
+	
+        <file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="woce"         name="vovecrtz" />
+          <field field_ref="avt"          name="votkeavt" />
+        </file>
+
+	<file id="file5" name_suffix="_ptrc_T" description="lobster sms variables" >
+          <field field_ref="DET"      />
+          <field field_ref="ZOO"      />
+          <field field_ref="PHY"      />
+          <field field_ref="NO3"      />
+          <field field_ref="NH4"      />
+          <field field_ref="DOM"      />
+	</file>
+	
+      </file_group>
+
+      <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="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+
+	<file id="file6" name_suffix="_diad_T" description="additional lobster diagnostics" >  
+          <field field_ref="FNO3PHY"   /> 
+          <field field_ref="FNH4PHY"   /> 
+          <field field_ref="FNH4NO3"   /> 
+          <field field_ref="TNO3PHY"   /> 
+          <field field_ref="TNH4PHY"   /> 
+          <field field_ref="TPHYDOM"   /> 
+          <field field_ref="TPHYNH4"   /> 
+          <field field_ref="TPHYZOO"   /> 
+          <field field_ref="TPHYDET"   /> 
+          <field field_ref="TDETZOO"   /> 
+          <field field_ref="TDETSED"   /> 
+          <field field_ref="TZOODET"   /> 
+          <field field_ref="TZOOBOD"   /> 
+          <field field_ref="TZOONH4"   /> 
+          <field field_ref="TZOODOM"   /> 
+          <field field_ref="TNH4NO3"   /> 
+          <field field_ref="TDOMNH4"   /> 
+          <field field_ref="TDETNH4"   /> 
+          <field field_ref="TPHYTOT"   /> 
+          <field field_ref="TZOOTOT"   /> 
+          <field field_ref="SEDPOC"    /> 
+	</file>
+
+      </file_group>
+
+      <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>
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios">
+
+      <variable_definition>
+	
+	  <variable id="info_level"                type="int">0</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+               
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,250 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite reference namelist
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                      GYRE PISCES configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "GYRE"   !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    4320   !  last  time step
+   nn_leapy    =      30   !  Leap year calendar (1) or not (0)
+   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)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=F) user defined configuration           (F => create/check namusr_def)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   GYRE user defined namelist  
+!-----------------------------------------------------------------------
+   nn_GYRE     =     1     !  GYRE resolution [1/degrees]
+   ln_bench    = .false.   !  ! =T benchmark with gyre: the gridsize is kept constant
+   jpkglo      =    31     !  number of model levels
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 7200.     !  time step for the dynamics
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)          (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+   ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   ln_qsr_2bd  = .true.    !  2 bands              light penetration
+   nn_chldta   =      0    !  RGB : Chl data (=1) or cst value (=0)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin = .true.     !  non-linear  drag: Cd = Cd0 |U|
+/
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.      !  = Use EOS80 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   =  .true.   !    laplacian operator
+   ln_traldf_iso   =  .true.   !  iso-neutral (standard operator)
+   nn_aht_ijk_t    = 0         !  = 0   constant = 1/2  Ud*Ld   (lap case) 
+      rn_Ud        = 0.02           !  lateral diffusive velocity [m/s]
+      rn_Ld        = 100.e+3        !  lateral diffusive length   [m]
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.    !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_lev =  .true.     !  iso-level
+   nn_ahm_ijk_t  = 0           !  = 0  constant = 1/2  Uv*Lv   (lap case) 
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] 
+      rn_Lv      = 100.e+3          !  lateral viscous length   [m]
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+      nn_evdm     =    1         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   !                       ! coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   nn_etau     =   0       !  penetration of tke below the mixed layer (ML) due to internal & intertial waves
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
@@ -0,0 +1,157 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! PISCES  (key_pisces) reference namelist (see below for key_pisces_reduced)
+!!              1  - air-sea exchange                         (nampisext)
+!!              2  - biological parameters                    (nampisbio)
+!!              3  - parameters for nutrient limitations      (nampislim)    
+!!              4  - parameters for phytoplankton             (nampisprod,nampismort)
+!!              5  - parameters for zooplankton               (nampismes,nampiszoo)
+!!              6  - parameters for remineralization          (nampisrem)
+!!              7  - parameters for calcite chemistry         (nampiscal)
+!!              8  - parameters for inputs deposition         (nampissed)
+!!              11 - Damping                                  (nampisdmp)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+    ln_p4z = .false.
+    ln_p2z = .true.
+/
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zice     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zice     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+/ 
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+/
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! PISCES reduced (key_pisces_reduced, ex LOBSTER) : namelists
+!!              1  - biological parameters for phytoplankton    (namlobphy)
+!!              2  - biological parameters for nutrients        (namlobnut)
+!!              3  - biological parameters for zooplankton      (namlobzoo)    
+!!              4  - biological parameters for detritus         (namlobdet)
+!!              5  - biological parameters for DOM              (namlobdom)
+!!              6  - parameters from aphotic layers to sediment (namlobsed)
+!!              7  - general coefficients                       (namlobrat)
+!!              8  - optical parameters                         (namlobopt)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_pisces_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,72 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP :   Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_top_ref
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  6
+   !
+   ln_pisces     =  .true.
+   ln_age        =  .false.
+   ln_cfc11      =  .false.
+   ln_cfc12      =  .false.
+   ln_c14        =  .false.
+   ln_my_trc     =  .false.
+   !_____________!__________!________________________________!______________!________________!
+   !             !   name   !           title of the field   !   units      ! init from file ! 
+   sn_tracer(1)   = 'DET'   , 'Detritus                   '  , 'mmole-N/m3' ,  .false.    
+   sn_tracer(2)   = 'ZOO'   , 'Zooplankton concentration  '  , 'mmole-N/m3' ,  .false.   
+   sn_tracer(3)   = 'PHY'   , 'Phytoplankton concentration'  , 'mmole-N/m3' ,  .false.  
+   sn_tracer(4)   = 'NO3'   , 'Nitrate concentration      '  , 'mmole-N/m3' ,  .false. 
+   sn_tracer(5)   = 'NH4'   , 'Ammonium concentration     '  , 'mmole-N/m3' ,  .false.   
+   sn_tracer(6)   = 'DOM'   , 'Dissolved organic matter   '  , 'mmole-N/m3' ,  .false.  
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   =  .true.     !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+   ln_trcrad   =  .false.  !  artificially correct negative concentrations (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping                   (ln_trcdmp=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/cpp_GYRE_PISCES.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/cpp_GYRE_PISCES.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/GYRE_PISCES/cpp_GYRE_PISCES.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_top key_mpp_mpi key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,42 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+    <field_definition src="./field_def_nemo-pisces.xml"/> <!--  NEMO ocean biology      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+    <file_definition src="./file_def_nemo-pisces.xml"/>  <!--  NEMO ocean biology       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-pisces.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,151 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                      Define your own files for sea ice                                   =
+=                                         put the variables you want...                                    =
+============================================================================================================
+ -->
+    
+ <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+   
+   <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   	
+     <file id="file21" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+       <!-- ice mask -->
+       <field field_ref="icemask"          name="simsk"   />
+       <field field_ref="icemask05"        name="simsk05" />
+       <field field_ref="icemask15"        name="simsk15" />
+       
+       <!-- general -->
+       <field field_ref="snwvolu"          name="snvolu" />
+       <field field_ref="icethic"          name="sithic" />
+       <field field_ref="icevolu"          name="sivolu" />
+       <field field_ref="iceconc"          name="siconc" />
+       <field field_ref="icesalt"          name="sisali" />
+       <field field_ref="iceapnd"          name="siapnd" />
+       <field field_ref="icevpnd"          name="sivpnd" />
+       <field field_ref="sst_m"            name="sst_m"  />
+       <field field_ref="sss_m"            name="sss_m"  />
+       
+       <!-- heat -->
+       <field field_ref="icetemp"          name="sitemp" />
+       <field field_ref="snwtemp"          name="sntemp" />
+       <field field_ref="icettop"          name="sittop" />
+       <field field_ref="icetbot"          name="sitbot" />
+       <field field_ref="icetsni"          name="sitsni" />
+       
+       <!-- momentum -->
+       <field field_ref="uice"             name="sivelu"  />
+       <field field_ref="vice"             name="sivelv"  />
+       <field field_ref="icevel"           name="sivelo"  />
+       <field field_ref="utau_ai"          name="utau_ai" />
+       <field field_ref="vtau_ai"          name="vtau_ai" />
+       <field field_ref="utau_oi"          name="utau_oi" />
+       <field field_ref="vtau_oi"          name="vtau_oi" />
+       
+       <!-- rheology -->
+       <field field_ref="icediv"           name="sidive"  />
+       <field field_ref="iceshe"           name="sishea"  />
+       <field field_ref="icestr"           name="sistre"  />
+       <field field_ref="normstr"          name="normstr" />
+       <field field_ref="sheastr"          name="sheastr" />
+       
+       <!-- heat fluxes -->
+       <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+       <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+       <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+       <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+       <field field_ref="qt_ice"           name="qt_ice"     />
+       <field field_ref="qsr_ice"          name="qsr_ice"    />
+       <field field_ref="qns_ice"          name="qns_ice"    />
+       <field field_ref="qemp_ice"         name="qemp_ice"   />
+       <field field_ref="albedo"           name="albedo"     />
+       
+       <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+       <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+       <field field_ref="hfxsensib"        name="hfxsensib"  />
+       
+       <!-- salt fluxes -->
+       <field field_ref="sfxice"           name="sfxice" />
+       
+       <!-- mass fluxes -->
+       <field field_ref="vfxice"           name="vfxice" />
+       <field field_ref="vfxsnw"           name="vfxsnw" />
+
+       <!-- categories -->
+       <field field_ref="icemask_cat"      name="simskcat"/>
+       <field field_ref="snwthic_cat"      name="snthicat"/>
+       <field field_ref="iceconc_cat"      name="siconcat"/>
+       <field field_ref="icethic_cat"      name="sithicat"/>
+       <field field_ref="icesalt_cat"      name="sisalcat"/>
+       <field field_ref="icetemp_cat"      name="sitemcat"/>
+       <field field_ref="snwtemp_cat"      name="sntemcat"/>
+       <field field_ref="icettop_cat"      name="sitopcat"/>
+
+     </file>
+     
+     <file id="file22" name_suffix="_SBC_scalar" description="scalar variables" enabled=".true." >
+       <!-- global contents -->
+       <field field_ref="ibgvol_tot"     name="ibgvol_tot"   />
+       <field field_ref="sbgvol_tot"     name="sbgvol_tot"   />
+       <field field_ref="ibgarea_tot"    name="ibgarea_tot"  />
+       <field field_ref="ibgsalt_tot"    name="ibgsalt_tot"  />
+       <field field_ref="ibgheat_tot"    name="ibgheat_tot"  />
+       <field field_ref="sbgheat_tot"    name="sbgheat_tot"  />
+       
+       <!-- global drifts (conservation checks) -->
+       <field field_ref="ibgvolume"      name="ibgvolume"    />
+       <field field_ref="ibgsaltco"      name="ibgsaltco"    />
+       <field field_ref="ibgheatco"      name="ibgheatco"    />
+       <field field_ref="ibgheatfx"      name="ibgheatfx"    />
+       
+       <!-- global forcings  -->
+       <field field_ref="ibgfrcvoltop"   name="ibgfrcvoltop" />
+       <field field_ref="ibgfrcvolbot"   name="ibgfrcvolbot" />
+       <field field_ref="ibgfrctemtop"   name="ibgfrctemtop" />
+       <field field_ref="ibgfrctembot"   name="ibgfrctembot" />
+       <field field_ref="ibgfrcsal"      name="ibgfrcsal"    />
+       <field field_ref="ibgfrchfxtop"   name="ibgfrchfxtop" />
+       <field field_ref="ibgfrchfxbot"   name="ibgfrchfxbot" />
+     </file>
+     
+   </file_group>
+
+   <file_group id="1m"  output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+     <!-- To compute transport through straits : need to read ice mask at ice iteration at freq_offset = 1mo - nn_fsbc
+        <file id="file23" name_suffix="_strait_ice" description="transport variables through straits" >
+          <field field_ref="strait_mifl"      name="simassacrossline"  freq_offset="1mo-4ts" />
+          <field field_ref="strait_msfl"      name="snmassacrossline"  freq_offset="1mo-4ts" />
+          <field field_ref="strait_arfl"      name="siareaacrossline"  freq_offset="1mo-4ts" />
+        </file>
+     -->
+    </file_group>
+
+   <!-- To compute transport through straits : need to read ice mask at ice iteration at freq_offset = - nn_fsbc + 1
+     <file id="maskMFO" name="maskMFO" enabled="true" mode="read" output_freq="1mo" cyclic="true"  >
+      <field id="maskMFO_u_ice" operation="instant"  freq_offset="-3ts"  grid_ref="grid_U_4strait_ice" />
+      <field id="maskMFO_v_ice" operation="instant"  freq_offset="-3ts"  grid_ref="grid_V_4strait_ice" />
+     </file>
+     -->
+
+   
+   <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="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>
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,168 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context               =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
+        <file id="file11" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"      />
+          <field field_ref="toce"         name="thetao"                                                                      operation="instant" freq_op="5d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="so"                                                                          operation="instant" freq_op="5d" > @soce_e3t / @e3t </field>
+          <field field_ref="sst"          name="tos"   />
+          <field field_ref="sss"          name="sos"   />
+          <field field_ref="ssh"          name="zos"   />
+          <field field_ref="sst"          name="tosstd"       long_name="sea surface temperature standard deviation"         operation="instant" freq_op="5d" > sqrt( @sst2 - @sst * @sst ) </field>
+          <field field_ref="ssh"          name="zosstd"       long_name="sea surface height above geoid standard deviation"  operation="instant" freq_op="5d" > sqrt( @ssh2 - @ssh * @ssh ) </field>
+          <field field_ref="sst"          name="sstdcy"       long_name="amplitude of sst diurnal cycle"                     operation="average" freq_op="1d" > @sstmax - @sstmin </field>
+          <field field_ref="mldkz5"   />
+          <field field_ref="mldr10_1" />
+          <field field_ref="mldr10_1"     name="mldr10_1dcy"  long_name="amplitude of mldr10_1 diurnal cycle"                operation="average" freq_op="1d" > @mldr10_1max - @mldr10_1min </field>
+          <field field_ref="sbt"      />
+          <field field_ref="heatc"        name="heatc" />
+          <field field_ref="saltc"        name="saltc" />
+
+	  <field field_ref="empmr"        name="wfo"      />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  />
+	  <field field_ref="qns_oce"      name="qns_oce"  />
+	  <field field_ref="qt_oce"       name="qt_oce"   />
+	  <field field_ref="saltflx"      name="sfx"      />
+	  <field field_ref="taum"         name="taum"     />
+	  <field field_ref="wspd"         name="windsp"   />
+	  <field field_ref="precip"       name="precip"   />
+	  <!-- ice and snow -->
+	  <field field_ref="snowpre" />
+	</file>
+
+	<file id="file12" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u" />
+	  <field field_ref="ssu"          name="uos"      />
+	  <field field_ref="uoce"         name="uo"       operation="instant" freq_op="5d" > @uoce_e3u / @e3u </field>
+	  <field field_ref="utau"         name="tauuo"    />
+          <field field_ref="uocetr_eff"   name="uocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="u_masstr"     name="vozomatr" />
+	  <field field_ref="u_heattr"     name="sozohetr" />
+	  <field field_ref="u_salttr"     name="sozosatr" />
+	</file>
+	
+	<file id="file13" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v" />
+	  <field field_ref="ssv"          name="vos"      />
+	  <field field_ref="voce"         name="vo"       operation="instant" freq_op="5d" > @voce_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="tauvo"    />
+          <field field_ref="vocetr_eff"   name="vocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="v_masstr"     name="vomematr" />
+	  <field field_ref="v_heattr"     name="somehetr" />
+          <field field_ref="v_salttr"     name="somesatr" />
+	</file>
+	
+	<file id="file14" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w" />
+	  <field field_ref="woce"         name="wo"       />
+	  <field field_ref="avt"          name="difvho"   />
+	  <field field_ref="w_masstr"     name="vovematr" />
+         <!-- variables available with ln_zdfiwm =T -->
+          <field field_ref="av_wave"      name="av_wave"    />
+          <field field_ref="bn2"          name="bn2"        />
+          <field field_ref="bflx_iwm"     name="bflx_iwm"   />
+          <field field_ref="pcmap_iwm"    name="pcmap_iwm"  />
+          <field field_ref="emix_iwm"     name="emix_iwm"   />
+          <field field_ref="av_ratio"     name="av_ratio"   />
+	</file>
+
+        <file id="file15" name_suffix="_scalar" description="scalar variables" >
+          <!-- global drifts (conservation checks) -->
+          <field field_ref="bgtemper"     name="bgtemper"    />
+          <field field_ref="bgsaline"     name="bgsaline"    />
+          <field field_ref="bgheatco"     name="bgheatco"    />
+          <field field_ref="bgheatfx"     name="bgheatfx"    />
+          <field field_ref="bgsaltco"     name="bgsaltco"    />
+          <field field_ref="bgvolssh"     name="bgvolssh"    />
+          <field field_ref="bgvole3t"     name="bgvole3t"    />
+
+          <!-- global surface forcings  -->
+          <field field_ref="bgfrcvol"     name="bgfrcvol"    />
+          <field field_ref="bgfrctem"     name="bgfrctem"    />
+          <field field_ref="bgfrchfx"     name="bgfrchfx"    />
+          <field field_ref="bgfrcsal"     name="bgfrcsal"    />
+        </file>
+
+      </file_group> 
+
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+
+
+        <file id="file16" name_suffix="_diaptr2D" description="zonal mean variables" >
+          <field field_ref="sophtove"    name="htovovrt"      grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstove"    name="sltovovrt"     grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophtgyre"   name="htovgyre"      grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstgyre"   name="sltogyre"      grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophtbtr"    name="htbtr"         grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstbtr"    name="sltbtr"        grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophtadv"    name="htadv"         grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstadv"    name="sltadv"        grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophtldf"    name="htldf"         grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstldf"    name="sltldf"        grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophtvtr"    name="hfbasin"       grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopstvtr"    name="sltbasin"      grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sophteiv"    name="hfbasinpmadv"  grid_ref="grid_ptr_T_2D"  />
+          <field field_ref="sopsteiv"    name="sltbasinpmadv" grid_ref="grid_ptr_T_2D"  />
+        </file>
+
+
+         <file id="file17" name_suffix="_diaptr3D" description="zonal mean variables" >
+          <field field_ref="zomsf"       name="msftyz"        grid_ref="grid_ptr_W_3D"  />
+          <field field_ref="zotem"       name="znltem"        grid_ref="grid_ptr_T_3D"  />
+          <field field_ref="zosal"       name="znlsal"        grid_ref="grid_ptr_T_3D"  />
+          <field field_ref="zosrf"       name="znlsrf"        grid_ref="grid_ptr_T_3D"  />
+        </file>
+
+      <!--  
+         <file id="file18" name_suffix="_strait_oce" description="transport variables through straits" >
+           <field field_ref="masstr_strait"        name="mfo"               />
+         </file>       
+      -->
+
+      </file_group>
+
+
+      <!--  To compute transport through straits : need to read mask file ( every month is the best otherwise costly )
+      <file id="maskMFO"  name="maskMFO" enabled="true" mode="read" output_freq="1mo" cyclic="true"  >
+        <field id="maskMFO_u" operation="instant" freq_offset="1mo" grid_ref="grid_U_4strait" />
+        <field id="maskMFO_v" operation="instant" freq_offset="1mo" grid_ref="grid_V_4strait" />
+      </file>
+
+    -->
+
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+      </file_group>
+	
+      
+      <file_group id="1ts" output_freq="1ts" output_level="10" enabled=".TRUE."/> <!-- 1 time step 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="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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/file_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,128 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context               =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
+
+        <file id="file31" 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="ppo4tot"  name="ppo4tot"   unit="umolP"  > ppo4tot * 1. / 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="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+
+        <file id="file32" name_suffix="_ptrc_T" description="pisces sms variables" >
+          <field field_ref="DIC"      />
+          <field field_ref="Alkalini" />
+          <field field_ref="O2"       />
+          <field field_ref="PO4"      />
+          <field field_ref="Si"       />
+          <field field_ref="Fer"      />
+          <field field_ref="NCHL"     />
+          <field field_ref="DCHL"     />
+          <field field_ref="NO3"      />
+        </file>
+
+        <file id="file33" name_suffix="_diad_T" description="additional pisces diagnostics" >
+          <field field_ref="Cflx"     />
+          <field field_ref="Dpco2"    />
+        </file>
+
+      </file_group>
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+
+        <file id="file34" name_suffix="_ptrc_T" description="pisces sms variables" >
+          <field field_ref="DIC"      />
+          <field field_ref="Alkalini" />
+          <field field_ref="O2"       />
+          <field field_ref="CaCO3"    />
+          <field field_ref="PO4"      />
+          <field field_ref="POC"      />
+          <field field_ref="Si"       />
+          <field field_ref="PHY"      />
+          <field field_ref="ZOO"      />
+          <field field_ref="DOC"      />
+          <field field_ref="PHY2"     />
+          <field field_ref="ZOO2"     />
+          <field field_ref="DSi"      />
+          <field field_ref="Fer"      />
+          <field field_ref="BFe"      />
+          <field field_ref="GOC"      />
+          <field field_ref="SFe"      />
+          <field field_ref="DFe"      />
+          <field field_ref="GSi"      />
+          <field field_ref="NFe"      />
+          <field field_ref="NCHL"     />
+          <field field_ref="DCHL"     />
+          <field field_ref="NO3"      />
+          <field field_ref="NH4"      />
+        </file>
+
+        <file id="file35" name_suffix="_diad_T" description="additional pisces diagnostics" >
+          <field field_ref="PH"       />
+          <field field_ref="PAR"      />
+          <field field_ref="PPPHYN"    />
+          <field field_ref="PPPHYD"   />
+          <field field_ref="PPPHYP"   />
+          <field field_ref="PPNEWN"   />
+          <field field_ref="PPNEWD"   />
+          <field field_ref="PPNEWP"   />
+          <field field_ref="PBSi"     />
+          <field field_ref="PFeN"     />
+          <field field_ref="PFeD"     />
+          <field field_ref="PCAL"     />
+          <field field_ref="DCAL"     />
+          <field field_ref="GRAZ1"    />
+          <field field_ref="GRAZ2"    />
+          <field field_ref="EPC100"   />
+          <field field_ref="EPFE100"  />
+          <field field_ref="EPSI100"  />
+          <field field_ref="EPCAL100" />
+          <field field_ref="Cflx"     />
+          <field field_ref="Dpco2"    />
+          <field field_ref="Heup"     />
+          <field field_ref="Nfix"     />
+        </file>
+     </file_group>
+	
+	
+      
+      <file_group id="1ts" output_freq="1ts" output_level="10" enabled=".TRUE."/> <!-- 1 time step 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="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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,425 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!             ORCA2 - ICE - PISCES configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "ORCA2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    5840   !  last  time step (std 5475)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      = 5400.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R2_zps_domcfg"    ! domain configuration filename
+      !
+      ln_closea    = .false.    !  F => suppress closed seas (defined by closea_mask field) 
+      !                         !       from the bathymetry at runtime.
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+   ln_tsd_dmp  = .true.          !  T-S restoring   (see namtra_dmp)
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''    ,    ''    ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 4         !  frequency of SBC module call
+                           !     (also = the frequency of sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  =2 or 3 automatically for SI3 or CICE    ("key_si3" or "key_cice")
+                           !          except in AGRIF zoom where it has to be specified
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_ssr      = .true.    !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   ln_rnf      = .true.    !  runoffs                                   (T => fill namsbc_rnf)
+   nn_fwb      = 2         !  FreshWater Budget: 
+   !                       !    =2 annual global mean of e-p-r set to zero
+   ln_wave     = .false.   !  Activate coupling with wave  (T => fill namsbc_wave)
+   ln_cdgw     = .false.   !  Neutral drag coefficient read from wave model (T => ln_wave=.true. & fill namsbc_wave)
+   ln_sdw      = .false.   !  Read 2D Surf Stokes Drift & Computation of 3D stokes drift (T => ln_wave=.true. & fill namsbc_wave) 
+   nn_sdrift   =  0        !  Parameterization for the calculation of 3D-Stokes drift from the surface Stokes drift
+      !                    !   = 0 Breivik 2015 parameterization: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
+      !                    !   = 1 Phillips:                      v_z=v_o*[exp(2*k*z)-beta*sqrt(-2*k*pi*z)*erfc(sqrt(-2*k*z))]
+      !                    !   = 2 Phillips as (1) but using the wave frequency from a wave model
+   ln_tauwoc   = .false.   !  Activate ocean stress modified by external wave induced stress (T => ln_wave=.true. & fill namsbc_wave)
+   ln_tauw     = .false.   !  Activate ocean stress components from wave model
+   ln_stcor    = .false.   !  Activate Stokes Coriolis term (T => ln_wave=.true. & ln_sdw=.true. & fill namsbc_wave)
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR    = .true.     ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir = './'  !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+   !
+   nn_chldta   =      1       !  RGB : Chl data (=1) or cst value (=0)
+
+   cn_dir = './'  !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sssr     =     2     !  add a damping term to the surface freshwater flux
+      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_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .true.    !  specific treatment at rivers mouths
+      rn_hrnf     =  15.e0    !  depth over which enhanced vertical mixing is used    (ln_rnf_mouth=T)
+      rn_avt_rnf  =   1.e-3   !  value of the additional vertical mixing coef. [m2/s] (ln_rnf_mouth=T)
+   rn_rfact    =   1.e0    !  multiplicative factor for runoff
+
+   cn_dir = './'  !  root directory for the location of the runoff files
+   !___________!_____________!___________________!___________!_____________!_________!___________!__________!__________!_______________!
+   !           !  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'  , ''       , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+   ln_icebergs = .true.    ! activate iceberg floats (force =F with "key_agrif")
+
+   cn_dir = './'  !  root directory for the location of drag coefficient files
+   !______!___________!___________________!______________!______________!_________!___________!__________!__________!_______________!
+   !      ! 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.         , 'calving'    ,   .true.     , .true.  , 'yearly'  , ''       , ''       , ''
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   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]
+   ln_chk_bathy  = .false. !  =T  check the parent bathymetry
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_lin = .true.         !     linear  drag: Cd = Cd0 Uc0
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx   =    2      !  geothermal heat flux: = 2 read variable flux [mW/m2]
+
+   cn_dir = './'  !  root directory for the geothermal data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_qgh      ='geothermal_heating.nc'  ,       -12.        , 'heatflow',   .false.   , .true. , 'yearly'  ,   ''             ,   ''     ,   ''
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.     !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   = .true.    !    laplacian operator
+   ln_traldf_iso   = .true.    !  iso-neutral (Standard operator)
+   ln_traldf_msc   = .true.    !  Method of Stabilizing Correction      (both operators)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 20        !  space/time variation of eddy coef
+      !                             !   = 20     aht = 1/2  Ud. max(e1,e2)
+      rn_Ud        = 0.018          !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .true.    ! use eddy induced velocity parameterization
+      !                        !  Coefficients:
+      nn_aei_ijk_t  = 21          ! space/time variation of the eiv coeficient
+      !                                !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                           !  time invariant coefficients:  aei0 = 1/2  Ue*Le 
+      rn_Ue        = 0.03              !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Le        = 200.e+3           !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+      !
+      ln_ldfeiv_dia =.true.   ! diagnose eiv stream function and velocities
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .true.   !  add a damping term (using resto.nc coef.)
+      nn_zdmp  =    0         !  vertical shape =0    damping throughout the water column
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true.  !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0   e3f = mean masked e3t divided by 4
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_lev =  .true.     !  iso-level
+   nn_ahm_ijk_t  = -30         !  =-30  3D coeff. read in eddy_diffusivity_3D.nc
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  Enhanced Vertical Diffusion scheme
+      nn_evdm  =    0            !  evd apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd   =  100.           !  evd mixing coefficient [m2/s]
+   ln_zdfddm   = .true.    ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   ln_zdfiwm   = .true.       ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+      nn_mxl      =   3       !  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 dissipative an mixing length scale
+      nn_etau     =   1       !  penetration of tke below the mixed layer (ML) due to NIWs
+                               !        = 0 none ; = 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           (ln_cpl=T)
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+   nn_zpyc     = 2         !  pycnocline-intensified dissipation scales as N (=1) or N^2 (=2)
+   ln_mevar    = .true.    !  variable (T) or constant (F) mixing efficiency
+   ln_tsdiff   = .true.    !  account for differential T/S mixing (T) or not (F)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,85 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+      ln_aEVP       = .false.          !     adaptive rheology (Kimmritz et al. 2016 & 2017)
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
@@ -0,0 +1,132 @@
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zlim     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zlim     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+/ 
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_pisces_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,114 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP1 :  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_top_ref
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   ln_top_euler  = .true.
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  24
+!
+   ln_pisces     =  .true.
+   ln_my_trc     =  .false.
+   ln_age        =  .false.
+   ln_cfc11      =  .false.
+   ln_cfc12      =  .false.
+   ln_c14        =  .false.
+!
+   ln_trcdta     =  .true.  !  Initialisation from data input file (T) or not (F)
+!                 !           !                                          !             !
+!                 !    name   !           title of the field             !   units     ! initial data from file or not !
+!                 !           !                                          !             !
+   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' ,  .true.
+   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   ,  .true.
+   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' ,  .true.
+   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' ,  .true.
+   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' ,  .false.
+   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' ,  .true.
+   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' ,  .true.
+   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' ,  .false.
+   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' ,  .false.
+   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' ,  .false.
+   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' ,  .false.
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!          !  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_trcdta(1)  = 'data_DIC_nomask'        ,        -12.       ,  'DIC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(2)  = 'data_Alkalini_nomask'   ,        -12.       ,  'Alkalini',    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(3)  = 'data_O2_nomask'         ,        -1.        ,  'O2'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(5)  = 'data_PO4_nomask'        ,        -1.        ,  'PO4'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(7)  = 'data_Si_nomask'         ,        -1.        ,  'Si'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(10) = 'data_DOC_nomask'        ,        -12.       ,  'DOC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(14) = 'data_Fer_nomask'        ,        -12.       ,  'Fer'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(23) = 'data_NO3_nomask'        ,        -1.        ,  'NO3'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   rn_trfac(1)   =   1.0e-06  !  multiplicative factor
+   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(3)   =  44.6e-06  !  -      -      -     -
+   rn_trfac(5)   = 122.0e-06  !  -      -      -     -
+   rn_trfac(7)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(10)  =   1.0      !  -      -      -     -
+   rn_trfac(14)  =   1.0      !  -      -      -     -
+   rn_trfac(23)  =   7.6e-06  !  -      -      -     -
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_mus =  .true.  !  MUSCL scheme
+      ln_mus_ups =  .false.         !  use upstream scheme near river mouths
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   = .true.      !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_snk      !  sedimentation of particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/README
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/README	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/README	(revision 14097)
@@ -0,0 +1,61 @@
+#----------------------------------------------------------------------
+# prerequired
+#----------------------------------------------------------------------
+First, you need either :
+- IDL (version 6.4 or above), see : http://www.exelisvis.com/ProductsServices/IDL.aspx
+  In this case, you also need to download SAXO which is a free package of IDL scripts:
+  define $PATH_SAXO, the path where you will download SAXO and get it through svn with the following command.
+  > PATH_SAXO=...
+  > svn checkout http://forge.ipsl.jussieu.fr/saxo/svn/trunk/SRC $PATH_SAXO/SAXO_DIR/SRC
+
+- or the IDL Virtual Machine which is free to use and does not require a license to run , see :
+  http://www.exelisvis.com/Support/HelpArticlesDetail/TabId/219/ArtMID/900/ArticleID/12395/The-IDL-Virtual-Machine.aspx
+  the virtual machine requites std_main.sav that is distributed with this README.
+
+Next, to use these idl tools, you need to download some climatogies and mask files;
+that you can find here: http://dodsp.idris.fr/reee512/NEMO_OUT/ORCA2_LIM/
+
+There is the wget command to get all those files (thanks to F. Pinsard)
+wget --recursive -l2 --no-directories --no-parent -A.nc -erobots=off http://dodsp.idris.fr/reee512/NEMO_OUT/ORCA2_LIM/
+
+You will aslo need the meshmask file (set ln_meshmask = TRUE in your namelist and run the model for at least 1 time step).
+
+#----------------------------------------------------------------------
+# define your std_plot_vardef.sh or std_ts_vardef.sh file
+#----------------------------------------------------------------------
+These files are needed to define your PATHs, the experiments and variables names you used in your experiment.
+ - std_plot_vardef.sh is used to do all plots based on temporal mean (maps, vertical profiles...).
+ - std_ts_vardef.sh is used to do all time-series type of plot.
+
+To build you own std_plot_vardef.sh or std_ts_vardef.sh file; use the examples provided such as:
+ - std_ts_vardef.sh_example1 or std_ts_vardef.sh_example2
+ - std_plot_vardef.sh_example1 or std_plot_vardef.sh_example2
+
+Note that if you use the IDL Virtual Machine, the variable SAXO_DIR defined in std_plot_vardef.sh or std_ts_vardef.sh is not used. Any definition will be ok.
+
+#----------------------------------------------------------------------
+# HOW TO USE 
+#----------------------------------------------------------------------
+./std_main.sh -plot -pdf
+or
+./std_main.sh -ts -pdf
+
+
+
+
+##########################################################################################################
+# short note for developers of this package on:
+#                   How to build the tarball required for IDL virtual Machine:
+##########################################################################################################
+#
+# we need to recreate std_main.sav as soon as we change IDL programmes files as
+# std_main.sav contains all ".pro" files aready compiled to be used with the virtual machine
+#
+. ./std_plot_vardef.sh # or . ./std_ts_vardef.sh 
+idl -IDL_STARTUP initenv
+IDL> .r std_main
+IDL> resolve_all
+IDL> save, /routines, filename='std_main.sav'
+IDL> exit
+#
+#----------------------------------------------------------------------
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/initenv.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/initenv.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/initenv.pro	(revision 14097)
@@ -0,0 +1,56 @@
+;
+; This is the initialisation file.
+; it defines the !path and the defaut values of some of the common variables
+;
+; this is supposed to speed-up IDL...
+;
+; a = fltarr(1000,1000,100)
+; a = 0
+;
+; path definition
+;
+!path = expand_path('+' + getenv('SAXO_DIR') ) + ':' + expand_path('+' + !dir)
+;
+; compatibility with the old version
+;
+keep_compatibility, 0
+;
+; define all the commons
+;
+@all_cm
+;
+; define default directories
+;
+homedir = './'
+iodir = './'
+psdir = isadirectory(getenv('PS_DIR'), title = 'Select the default postscripts directory')
+imagedir = './'
+animdir = './'
+;
+; define printer parameters
+;
+printer_human_names = ''
+printer_machine_names = ''
+print_command = ''
+;
+; colors ...
+;
+device, decomposed = 0
+device, retain = 2
+lct, 65
+;
+; postscript parameters ...
+;
+key_portrait = 0
+page_size = [20.9903, 29.7039]
+windowsize_scale = 1.0000
+archive_ps = 0
+;
+;========================================================
+; end of the part that should be modified by the users...
+;========================================================
+;
+; if needed, keep compatibility with the old version
+;
+@updateold
+;
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_common.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_common.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_common.pro	(revision 14097)
@@ -0,0 +1,9 @@
+COMMON std, cnt $
+   , std_iodir_climato, std_iodir_data $
+   , std_file1_T, std_file2_T $
+   , std_file1_U, std_file2_U $
+   , std_file1_V, std_file2_V $
+   , std_file1_I, std_file2_I $
+   , std_file_msksub $
+   , date1, date2, date1_2, date2_2 $
+   , allrec, blabla, htmltxt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.pro	(revision 14097)
@@ -0,0 +1,12 @@
+PRO std_main
+@initenv
+;
+  type = getenv('PLOTTYPE')
+  CASE type OF
+    '':print, 'The environment variable PLOTTYPE is not defined. We stop'
+    'ts':std_ts_all, /postscript
+    'plot':std_plot_all, /postscript
+    ELSE:print, 'Wrong definition of the environment variable PLOTTYPE. We stop'
+  ENDCASE
+;
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main.sh	(revision 14097)
@@ -0,0 +1,239 @@
+#!/bin/sh 
+#+
+#
+# .. program:: std_main.sh
+#
+# ================
+# std_main.sh
+# ================
+#
+# -------------------------------------
+# launch idl scripts to produce graphics diagnostics in Postscript, PDF or HTML document
+# -------------------------------------
+#
+# SYNOPSIS
+# ========
+#
+# ``std_main.sh -ts`` or ``std_main.sh -plot`` 
+# 
+# DESCRIPTION
+# ===========
+#
+# .. option:: -ts    to produce time series 
+# .. option:: -plot  to produce maps and sections
+# .. option:: -html  to produce html document
+# .. option:: -pdf   to produce pdf document
+# .. option:: -noidl to skip the call to IDL and the production of Postscript
+# .. option:: -vm    to use IDL virtual machine (free) instead of IDL
+# .. option:: -help  to get help!
+#
+# variables have to be defined in std_plot_vardef.sh (or std_ts_vardef.sh)
+# before calling std_main.sh -plot (or std_main.sh -ts)
+#
+# EXAMPLES
+# ========
+# $ ./std_main.sh -ts html
+# $ ./std_main.sh -ts pdf -noidl
+# 
+# $ ./std_main.sh -plot -pdf -vm
+#
+# AUTHOR - date
+# ===========
+# Françoise Pinsard - 01/2010 - LOCEAN
+# Simona Flavoni    - 01/2010 - LOCEAN
+# Sebastien Masson  - 04/2011 - LOCEAN
+#
+#-----------------------------------------------------------
+# Usage...
+#-----------------------------------------------------------
+#
+#-
+system=$(uname)
+case "${system}" in
+   AIX|IRIX64)
+      echo " www : no specific posix checking"
+   ;;
+   *)
+      set -o posix
+   ;;
+esac
+#
+usage="Usage: std_main.sh [OPTION]
+Options
+ -ts    to produce time series 
+ -plot  to produce maps and sections
+ -html  to produce html document
+ -pdf   to produce pdf document
+ -noidl to skip the call to IDL and the production of Postscript
+ -vm    to use IDL virtual machine (free) instead of IDL
+ -help  to get this help
+"
+#
+vm=0
+noidl=0
+format=ps
+while [ ! -z "${1}" ]
+do
+    case ${1} in
+	-plot|--plot) PLOTTYPE=plot ;;
+	-ts|--ts) PLOTTYPE=ts ;;
+	-f|-format|--format) format=${2}	  shift	 ;;
+	-html|--html) format=html ;;
+	-pdf|--pdf) format=pdf ;;
+	-h|-help|--help)	
+	    echo "${usage}"
+	    exit 0	
+	    ;;
+	-ni|--ni|-noidl|--noidl) noidl=1 ;;
+	-vm|--vm|-virtual_machine|--virtual_machine) vm=1 ;;
+	*) # other choice
+	    echo "${usage}"
+	    exit 1
+	    ;;
+    esac
+    shift # next flag
+done
+#
+PLOTTYPE=${PLOTTYPE:-NG}
+if [[ ( "$PLOTTYPE" != "plot" ) && ( "$PLOTTYPE" != "ts" ) ]]
+then
+    echo 'the type of plot must be defined with the option -plot or -ts'
+	exit 1
+fi
+export PLOTTYPE
+#
+set -u
+#
+#
+tstexe () {
+    type ${1}
+    status_type=${?}
+    if [ ${status_type} -ne 0 ]
+    then
+	echo "eee : ${2}"
+	exit 1
+    fi
+}
+#
+#-----------------------------------------------------------
+# define output directory for POSTCRIPT files
+#-----------------------------------------------------------
+#
+. ./std_${PLOTTYPE}_vardef.sh
+[ ! -d ${PS_DIR} ] && mkdir -p ${PS_DIR}
+#
+#-----------------------------------------------------------
+# run IDL
+#-----------------------------------------------------------
+#
+if [ $noidl -eq 0 ]
+then 
+    tstexe ${idl_command} "idl not found"
+#
+    if [ $vm -eq 1 ]
+    then
+	${idl_command} -vm=std_main.sav
+    else 
+	${idl_command} -IDL_STARTUP 'initenv' << EOF
+std_${PLOTTYPE}_all, /postscript
+EOF
+    fi
+    status_idl=${?}
+    if [ ${status_idl} -ne 0 ]
+    then
+	echo "eee : error in the execution of IDL"
+	exit 1
+    fi
+fi
+#
+#-----------------------------------------------------------
+# produce the final document
+#-----------------------------------------------------------
+#
+# build the list of ps that has been created by IDL
+pslist=$( grep "img width" ${PS_DIR}/std_${PLOTTYPE}_html_body.txt | sed -e "s/.*src=\(.*\)png.*/\1/" )
+#
+case ${format} in
+#__________________________________________________________
+# PDF
+    pdf)
+# check if ps2pdf available
+	ps2pdf_command=$( which ps2pdf )
+	tstexe ${ps2pdf_command} "ps2pdf not found"
+# check if texexec available
+	texexec_command=$( which texexec )
+	tstexe ${texexec_command} "texexec not found"
+#
+	filepdf=all_${PLOTTYPE}.pdf
+	[ ! -d ${PDF_DIR} ] && mkdir -p ${PDF_DIR}
+	pdflist=''
+	for file in ${pslist} ; do
+	    ps2pdf -sPAPERSIZE=a4 ${PS_DIR}/${file}ps ${PDF_DIR}/${file}pdf
+	    echo "ps2pdf ${file}ps done"
+	    pdflist=${pdflist}' '${PDF_DIR}/${file}pdf
+	done
+#pdfjam needed to use pdfjoin
+	pdfjoin ${pdflist} --outfile $PDF_DIR/${filepdf}
+	texexec --pdfarrange --result=$PDF_DIR/$filepdf $pdflist
+	rm -f $PDF_DIR/$( basename $filepdf .pdf ).aux $PDF_DIR/$( basename $filepdf .pdf ).log
+	if [ ! -e ${PDF_DIR}/$filepdf ]
+	then
+	        echo "\n ATTENTION !!!!! \n"
+                echo "${PDF_DIR}/$filepdf do not exist \n"
+        else
+                 echo "${PDF_DIR}/$filepdf done"
+       fi
+#commented because convert gives images of bad quality
+#	convert ${PS_DIR}/*.ps /tmp/all_${PLOTTYPE}.pdf
+#       convert -resize 800x600 ${PS_DIR}/${exp1}_${exp2}/ps/*.ps /tmp/all_${PLOTTYPE}.pdf
+	;;
+#__________________________________________________________
+# HTML
+    html)
+	filehtml=all_${PLOTTYPE}.html
+	[ ! -d ${HTML_DIR} ] && mkdir -p ${HTML_DIR}
+# check if convert available
+	convert_command=$( which convert )
+	tstexe ${convert_command} "convert not found"
+# convert each ps to png	
+	for file in ${pslist} ; do
+	    ${convert_command} -antialias ${PS_DIR}/${file}ps ${HTML_DIR}/${file}png
+	done
+# creation of the HTML file
+	cat << EOF > ${HTML_DIR}/$filehtml
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+</head>
+<body>
+EOF
+	cat ${PS_DIR}/std_${PLOTTYPE}_html_body.txt >>  ${HTML_DIR}/$filehtml
+	cat << EOF >> ${HTML_DIR}/$filehtml
+<hr>
+</body>
+</html>
+EOF
+	echo ${HTML_DIR}/$filehtml done
+	;;
+    ps)	;; # nothing to do...
+    *)	
+	echo " format ${format} not implemented"
+	exit 1
+	;;
+esac
+
+    #
+#=====================
+# prepare to put images on dods
+# +++ to finish it
+#LOGIN=xxxx
+#Tag_Name=ORCA2_LIM2
+#rsh ${LOGIN}@gaya.idris.fr exec /bin/ksh <<EOF
+#       cd ${homegaya}/IGCM_OUT/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1}
+#       /usr/local/bin/dods_rm DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#       /usr/local/bin/dods_cp ${exp1} DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#EOF
+#=====================
+# end
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_1Y.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_1Y.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_1Y.sh	(revision 14097)
@@ -0,0 +1,239 @@
+#!/bin/sh 
+#+
+#
+# .. program:: std_main.sh
+#
+# ================
+# std_main.sh
+# ================
+#
+# -------------------------------------
+# launch idl scripts to produce graphics diagnostics in Postscript, PDF or HTML document
+# -------------------------------------
+#
+# SYNOPSIS
+# ========
+#
+# ``std_main.sh -ts`` or ``std_main.sh -plot`` 
+# 
+# DESCRIPTION
+# ===========
+#
+# .. option:: -ts    to produce time series 
+# .. option:: -plot  to produce maps and sections
+# .. option:: -html  to produce html document
+# .. option:: -pdf   to produce pdf document
+# .. option:: -noidl to skip the call to IDL and the production of Postscript
+# .. option:: -vm    to use IDL virtual machine (free) instead of IDL
+# .. option:: -help  to get help!
+#
+# variables have to be defined in std_plot_vardef.sh (or std_ts_vardef.sh)
+# before calling std_main.sh -plot (or std_main.sh -ts)
+#
+# EXAMPLES
+# ========
+# $ ./std_main.sh -ts html
+# $ ./std_main.sh -ts pdf -noidl
+# 
+# $ ./std_main.sh -plot -pdf -vm
+#
+# AUTHOR - date
+# ===========
+# Françoise Pinsard - 01/2010 - LOCEAN
+# Simona Flavoni    - 01/2010 - LOCEAN
+# Sebastien Masson  - 04/2011 - LOCEAN
+#
+#-----------------------------------------------------------
+# Usage...
+#-----------------------------------------------------------
+#
+#-
+system=$(uname)
+case "${system}" in
+   AIX|IRIX64)
+      echo " www : no specific posix checking"
+   ;;
+   *)
+      set -o posix
+   ;;
+esac
+#
+usage="Usage: std_main.sh [OPTION]
+Options
+ -ts    to produce time series 
+ -plot  to produce maps and sections
+ -html  to produce html document
+ -pdf   to produce pdf document
+ -noidl to skip the call to IDL and the production of Postscript
+ -vm    to use IDL virtual machine (free) instead of IDL
+ -help  to get this help
+"
+#
+vm=0
+noidl=0
+format=ps
+while [ ! -z "${1}" ]
+do
+    case ${1} in
+	-plot|--plot) PLOTTYPE=plot ;;
+	-ts|--ts) PLOTTYPE=ts ;;
+	-f|-format|--format) format=${2}	  shift	 ;;
+	-html|--html) format=html ;;
+	-pdf|--pdf) format=pdf ;;
+	-h|-help|--help)	
+	    echo "${usage}"
+	    exit 0	
+	    ;;
+	-ni|--ni|-noidl|--noidl) noidl=1 ;;
+	-vm|--vm|-virtual_machine|--virtual_machine) vm=1 ;;
+	*) # other choice
+	    echo "${usage}"
+	    exit 1
+	    ;;
+    esac
+    shift # next flag
+done
+#
+PLOTTYPE=${PLOTTYPE:-NG}
+if [[ ( "$PLOTTYPE" != "plot" ) && ( "$PLOTTYPE" != "ts" ) ]]
+then
+    echo 'the type of plot must be defined with the option -plot or -ts'
+	exit 1
+fi
+export PLOTTYPE
+#
+set -u
+#
+#
+tstexe () {
+    type ${1}
+    status_type=${?}
+    if [ ${status_type} -ne 0 ]
+    then
+	echo "eee : ${2}"
+	exit 1
+    fi
+}
+#
+#-----------------------------------------------------------
+# define output directory for POSTCRIPT files
+#-----------------------------------------------------------
+#
+. ./std_${PLOTTYPE}_vardef.sh
+[ ! -d ${PS_DIR} ] && mkdir -p ${PS_DIR}
+#
+#-----------------------------------------------------------
+# run IDL
+#-----------------------------------------------------------
+#
+if [ $noidl -eq 0 ]
+then 
+    tstexe ${idl_command} "idl not found"
+#
+    if [ $vm -eq 1 ]
+    then
+	${idl_command} -vm=std_main.sav
+    else 
+	${idl_command} -IDL_STARTUP 'initenv' << EOF
+std_${PLOTTYPE}_all, /postscript
+EOF
+    fi
+    status_idl=${?}
+    if [ ${status_idl} -ne 0 ]
+    then
+	echo "eee : error in the execution of IDL"
+	exit 1
+    fi
+fi
+#
+#-----------------------------------------------------------
+# produce the final document
+#-----------------------------------------------------------
+#
+# build the list of ps that has been created by IDL
+pslist=$( grep "img width" ${PS_DIR}/std_${PLOTTYPE}_html_body.txt | sed -e "s/.*src=\(.*\)png.*/\1/" )
+#
+case ${format} in
+#__________________________________________________________
+# PDF
+    pdf)
+# check if ps2pdf available
+	ps2pdf_command=$( which ps2pdf )
+	tstexe ${ps2pdf_command} "ps2pdf not found"
+# check if texexec available
+	texexec_command=$( which texexec )
+	tstexe ${texexec_command} "texexec not found"
+#
+	filepdf=all_${PLOTTYPE}.pdf
+	[ ! -d ${PDF_DIR} ] && mkdir -p ${PDF_DIR}
+	pdflist=''
+	for file in ${pslist} ; do
+	    ps2pdf -sPAPERSIZE=a4 ${PS_DIR}/${file}ps ${PDF_DIR}/${file}pdf
+	    echo "ps2pdf ${file}ps done"
+	    pdflist=${pdflist}' '${PDF_DIR}/${file}pdf
+	done
+#pdfjam needed to use pdfjoin
+	pdfjoin ${pdflist} --outfile $PDF_DIR/${filepdf}
+	texexec --pdfarrange --result=$PDF_DIR/$filepdf $pdflist
+	rm -f $PDF_DIR/$( basename $filepdf .pdf ).aux $PDF_DIR/$( basename $filepdf .pdf ).log
+	if [ ! -e ${PDF_DIR}/$filepdf ]
+	then
+	        echo "\n ATTENTION !!!!! \n"
+                echo "${PDF_DIR}/$filepdf do not exist \n"
+        else
+                 echo "${PDF_DIR}/$filepdf done"
+       fi
+#commented because convert gives images of bad quality
+#	convert ${PS_DIR}/*.ps /tmp/all_${PLOTTYPE}.pdf
+#       convert -resize 800x600 ${PS_DIR}/${exp1}_${exp2}/ps/*.ps /tmp/all_${PLOTTYPE}.pdf
+	;;
+#__________________________________________________________
+# HTML
+    html)
+	filehtml=all_${PLOTTYPE}.html
+	[ ! -d ${HTML_DIR} ] && mkdir -p ${HTML_DIR}
+# check if convert available
+	convert_command=$( which convert )
+	tstexe ${convert_command} "convert not found"
+# convert each ps to png	
+	for file in ${pslist} ; do
+	    ${convert_command} -antialias ${PS_DIR}/${file}ps ${HTML_DIR}/${file}png
+	done
+# creation of the HTML file
+	cat << EOF > ${HTML_DIR}/$filehtml
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+</head>
+<body>
+EOF
+	cat ${PS_DIR}/std_${PLOTTYPE}_html_body.txt >>  ${HTML_DIR}/$filehtml
+	cat << EOF >> ${HTML_DIR}/$filehtml
+<hr>
+</body>
+</html>
+EOF
+	echo ${HTML_DIR}/$filehtml done
+	;;
+    ps)	;; # nothing to do...
+    *)	
+	echo " format ${format} not implemented"
+	exit 1
+	;;
+esac
+
+    #
+#=====================
+# prepare to put images on dods
+# +++ to finish it
+#LOGIN=xxxx
+#Tag_Name=ORCA2_LIM2
+#rsh ${LOGIN}@gaya.idris.fr exec /bin/ksh <<EOF
+#       cd ${homegaya}/IGCM_OUT/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1}
+#       /usr/local/bin/dods_rm DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#       /usr/local/bin/dods_cp ${exp1} DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#EOF
+#=====================
+# end
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_5D.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_5D.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_5D.sh	(revision 14097)
@@ -0,0 +1,238 @@
+#!/bin/sh 
+#+
+#
+# .. program:: std_main_5D.sh
+#
+# ================
+# std_main.sh
+# ================
+#
+# -------------------------------------
+# launch idl scripts to produce graphics diagnostics in Postscript, PDF or HTML document
+# for output of 5days for 1 year run
+# nota: it is like std_main.sh but it calls routins for 5days
+# -------------------------------------
+#
+# SYNOPSIS
+# ========
+#
+# ``std_main_5D.sh -ts`` or ``std_main_5D.sh -plot`` 
+# 
+# DESCRIPTION
+# ===========
+#
+# .. option:: -ts    to produce time series 
+# .. option:: -plot  to produce maps and sections
+# .. option:: -html  to produce html document
+# .. option:: -pdf   to produce pdf document
+# .. option:: -noidl to skip the call to IDL and the production of Postscript
+# .. option:: -vm    to use IDL virtual machine (free) instead of IDL
+# .. option:: -help  to get help!
+#
+# variables have to be defined in std_plot_vardef.sh (or std_ts_vardef.sh)
+# before calling std_main_5D.sh -plot 
+#
+# EXAMPLES
+# ========
+# $ ./std_main_5D.sh -plot -pdf 
+#
+# AUTHOR - date
+# ===========
+# Françoise Pinsard - 01/2010 - LOCEAN
+# Simona Flavoni    - 01/2010 - LOCEAN
+# Sebastien Masson  - 04/2011 - LOCEAN
+#
+#-----------------------------------------------------------
+# Usage...
+#-----------------------------------------------------------
+#
+#-
+system=$(uname)
+case "${system}" in
+   AIX|IRIX64)
+      echo " www : no specific posix checking"
+   ;;
+   *)
+      set -o posix
+   ;;
+esac
+#
+usage="Usage: std_main_5D.sh [OPTION]
+Options
+ -ts    to produce time series 
+ -plot  to produce maps and sections
+ -html  to produce html document
+ -pdf   to produce pdf document
+ -noidl to skip the call to IDL and the production of Postscript
+ -vm    to use IDL virtual machine (free) instead of IDL
+ -help  to get this help
+"
+#
+vm=0
+noidl=0
+format=ps
+while [ ! -z "${1}" ]
+do
+    case ${1} in
+	-plot|--plot) PLOTTYPE=plot ;;
+	-ts|--ts) PLOTTYPE=ts ;;
+	-f|-format|--format) format=${2}	  shift	 ;;
+	-html|--html) format=html ;;
+	-pdf|--pdf) format=pdf ;;
+	-h|-help|--help)	
+	    echo "${usage}"
+	    exit 0	
+	    ;;
+	-ni|--ni|-noidl|--noidl) noidl=1 ;;
+	-vm|--vm|-virtual_machine|--virtual_machine) vm=1 ;;
+	*) # other choice
+	    echo "${usage}"
+	    exit 1
+	    ;;
+    esac
+    shift # next flag
+done
+#
+PLOTTYPE=${PLOTTYPE:-NG}
+if [[ ( "$PLOTTYPE" != "plot" ) && ( "$PLOTTYPE" != "ts" ) ]]
+then
+    echo 'the type of plot must be defined with the option -plot or -ts'
+	exit 1
+fi
+export PLOTTYPE
+#
+set -u
+#
+#
+tstexe () {
+    type ${1}
+    status_type=${?}
+    if [ ${status_type} -ne 0 ]
+    then
+	echo "eee : ${2}"
+	exit 1
+    fi
+}
+#
+#-----------------------------------------------------------
+# define output directory for POSTCRIPT files
+#-----------------------------------------------------------
+#
+. ./std_${PLOTTYPE}_vardef.sh
+[ ! -d ${PS_DIR} ] && mkdir -p ${PS_DIR}
+#
+#-----------------------------------------------------------
+# run IDL
+#-----------------------------------------------------------
+#
+if [ $noidl -eq 0 ]
+then 
+    tstexe ${idl_command} "idl not found"
+#
+    if [ $vm -eq 1 ]
+    then
+	${idl_command} -vm=std_main.sav
+    else 
+	${idl_command} -IDL_STARTUP 'initenv' << EOF
+std_${PLOTTYPE}_all_last_year_5D, /postscript
+EOF
+    fi
+    status_idl=${?}
+    if [ ${status_idl} -ne 0 ]
+    then
+	echo "eee : error in the execution of IDL"
+	exit 1
+    fi
+fi
+#
+#-----------------------------------------------------------
+# produce the final document
+#-----------------------------------------------------------
+#
+# build the list of ps that has been created by IDL
+pslist=$( grep "img width" ${PS_DIR}/std_${PLOTTYPE}_html_body.txt | sed -e "s/.*src=\(.*\)png.*/\1/" )
+#
+case ${format} in
+#__________________________________________________________
+# PDF
+    pdf)
+# check if ps2pdf available
+	ps2pdf_command=$( which ps2pdf )
+	tstexe ${ps2pdf_command} "ps2pdf not found"
+# check if texexec available
+	texexec_command=$( which texexec )
+	tstexe ${texexec_command} "texexec not found"
+#
+	filepdf=all_${PLOTTYPE}.pdf
+	[ ! -d ${PDF_DIR} ] && mkdir -p ${PDF_DIR}
+	pdflist=''
+	for file in ${pslist} ; do
+	    ps2pdf -sPAPERSIZE=a4 ${PS_DIR}/${file}ps ${PDF_DIR}/${file}pdf
+	    echo "ps2pdf ${file}ps done"
+	    pdflist=${pdflist}' '${PDF_DIR}/${file}pdf
+	done
+#pdfjam needed to use pdfjoin
+	pdfjoin ${pdflist} --outfile $PDF_DIR/${filepdf}
+	texexec --pdfarrange --result=$PDF_DIR/$filepdf $pdflist
+	rm -f $PDF_DIR/$( basename $filepdf .pdf ).aux $PDF_DIR/$( basename $filepdf .pdf ).log
+	if [ ! -e ${PDF_DIR}/$filepdf ]
+	then
+	        echo "\n ATTENTION !!!!! \n"
+                echo "${PDF_DIR}/$filepdf do not exist \n"
+        else
+                 echo "${PDF_DIR}/$filepdf done"
+       fi
+#commented because convert gives images of bad quality
+#	convert ${PS_DIR}/*.ps /tmp/all_${PLOTTYPE}.pdf
+#       convert -resize 800x600 ${PS_DIR}/${exp1}_${exp2}/ps/*.ps /tmp/all_${PLOTTYPE}.pdf
+	;;
+#__________________________________________________________
+# HTML
+    html)
+	filehtml=all_${PLOTTYPE}.html
+	[ ! -d ${HTML_DIR} ] && mkdir -p ${HTML_DIR}
+# check if convert available
+	convert_command=$( which convert )
+	tstexe ${convert_command} "convert not found"
+# convert each ps to png	
+	for file in ${pslist} ; do
+	    ${convert_command} -antialias ${PS_DIR}/${file}ps ${HTML_DIR}/${file}png
+	done
+# creation of the HTML file
+	cat << EOF > ${HTML_DIR}/$filehtml
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+</head>
+<body>
+EOF
+	cat ${PS_DIR}/std_${PLOTTYPE}_html_body.txt >>  ${HTML_DIR}/$filehtml
+	cat << EOF >> ${HTML_DIR}/$filehtml
+<hr>
+</body>
+</html>
+EOF
+	echo ${HTML_DIR}/$filehtml done
+	;;
+    ps)	;; # nothing to do...
+    *)	
+	echo " format ${format} not implemented"
+	exit 1
+	;;
+esac
+
+    #
+#=====================
+# prepare to put images on dods
+# +++ to finish it
+#LOGIN=xxxx
+#Tag_Name=ORCA2_LIM2
+#rsh ${LOGIN}@gaya.idris.fr exec /bin/ksh <<EOF
+#       cd ${homegaya}/IGCM_OUT/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1}
+#       /usr/local/bin/dods_rm DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#       /usr/local/bin/dods_cp ${exp1} DODS/pub/${LOGIN}/${Tag_Name}/CORE2/INTERAN/${PLOTTYPE}_pdf/${exp1} > /dev/null 2>&1
+#EOF
+#=====================
+# end
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_last_year_5D.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_last_year_5D.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_main_last_year_5D.pro	(revision 14097)
@@ -0,0 +1,12 @@
+PRO std_main_last_year_5D
+@initenv
+;
+  type = getenv('PLOTTYPE')
+  CASE type OF
+    '':print, 'The environment variable PLOTTYPE is not defined. We stop'
+    'ts':std_ts_all, /postscript
+    'plot':std_plot_all_last_year_5D, /postscript
+    ELSE:print, 'Wrong definition of the environment variable PLOTTYPE. We stop'
+  ENDCASE
+;
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ArcSal.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ArcSal.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ArcSal.pro	(revision 14097)
@@ -0,0 +1,62 @@
+pro std_plot_ArcSal, S1, S2in, SLevin, Z100 = z100, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  CASE n_params() OF
+    2:BEGIN
+      Slev = S2in
+    END
+    3:BEGIN
+      IF S2in.arr[0] EQ -1 THEN return
+      S2 = S2in
+      Slev = Slevin
+    END
+  ENDCASE
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+;
+  IF keyword_set(z100) THEN tmp = min(abs(100 - gdept), ind) ELSE ind = 0
+  sdepref = strtrim(round(gdept[ind]), 1)+'m'
+  filename = cdti3 + '_Arctic_Sal'+sdepref+'_'+std_file1_T
+  IF keyword_set(S2) THEN filename = filename + '_' + std_file2_T
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+; 
+  domdef, 20, 380, 50, 90
+;
+  varunit = S1.unit
+  titleorg = 'Salinity ('+sdepref+')!C'
+;
+  IF keyword_set(S2) THEN BEGIN
+    title = titleorg+std_file1_T+ ' - '+std_file2_T
+    plt, S1.arr - S2.arr, MIN = -4., MAX = 4., INTER = 0.2, CELL_FILL = 2,  STYLE = 'so0so', format = '(f4.1)'  $     
+         , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, CHARSIZE = -0.55, GLINETHICK = 2. $      
+         , /ORTHO, MAP = [90, 0, 0], LATDEL = 5, boxzoom = [ind, ind], /zindex, /portrait, _extra = ex
+  ENDIF ELSE BEGIN 
+    title = titleorg+std_file1_T
+    plt, S1, MIN = 30.0, MAX = 36., INTER = 0.2, CELL_FILL = 2, format = '(f4.1)' $
+         , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, CHARSIZE = -0.55, GLINETHICK = 2. $
+         , /ORTHO, MAP = [90, 0, 0], LATDEL = 5, boxzoom = [ind, ind], /zindex, /PORTRAIT, _extra = ex
+  ENDELSE 
+; 
+  IF keyword_set(S2) THEN BEGIN
+    title = titleorg+std_file2_T+ ' - Levitus'
+    tmp = S2.arr - SLev.arr
+  ENDIF ELSE BEGIN 
+    title = titleorg+std_file1_T+ ' - Levitus'
+    tmp = S1.arr - SLev.arr
+  ENDELSE
+  plt, temporary(tmp), MIN = -4., MAX = 4., INTER = 0.2, CELL_FILL = 2,  STYLE = 'so0so', format = '(f4.1)'  $     
+       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, CHARSIZE = -0.55, GLINETHICK = 2. $      
+       , /ORTHO, MAP = [90, 0, 0], LATDEL = 5, boxzoom = [ind, ind], /zindex, /NOERASE, _extra = ex
+;
+  domdef
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqS.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqS.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqS.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_EqS, S1, S2, SLev, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_EqS_'+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
+  
+  title = 'Equatorial Salinity!C'+std_file1_T
+  pltz, S1, MININ = 33., MAXIN = 37., INTER = .2, typein = 'xz', FORMAT = '(f4.1)'  $
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], /PORTRAIT, _extra = ex
+  
+  if std_file1_T EQ std_file2_T then begin
+    S = S1.arr - Slev.arr
+    title = title+' - Levitus'
+  ENDIF ELSE BEGIN 
+    S = S1.arr - S2.arr
+    title = title+' - '+std_file2_T
+  ENDELSE
+  
+  pltz, S, MININ = -1., MAXIN = 1., INTER = 0.1, typein = 'xz', STYLE = 'so0so', FORMAT = '(f4.1)' $
+        , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], /noerase, _extra = ex
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqT.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqT.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqT.pro	(revision 14097)
@@ -0,0 +1,42 @@
+pro std_plot_EqT, T1, T2, TLev, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_EqT_'+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
+  
+  title = 'Equatorial Temperature!C'+std_file1_T
+  pltz, T1, MININ = 2., MAXIN = 30., INTER = 1., typein = 'xz', FORMAT = '(I2)'  $
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], /PORTRAIT, _extra = ex
+  
+  if std_file1_T EQ std_file2_T then begin
+    T = T1.arr - TLev.arr
+    title = title+' - Levitus'
+    min = -4.
+    max = -min
+    inter = .5
+    fmt = '(I2)'
+  ENDIF ELSE BEGIN 
+    T = T1.arr - T2.arr
+    title = title+' - '+std_file2_T
+    min =  -2.
+    max = -min
+    inter = .25
+    fmt = '(f4.1)'
+  ENDELSE 
+  
+  pltz, T, MININ = min, MAXIN = max, INTER = inter, typein = 'xz', STYLE = 'so0so', FORMAT = fmt $
+        , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], /NOERASE, _extra = ex
+                                ; 
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqU.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqU.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_EqU.pro	(revision 14097)
@@ -0,0 +1,28 @@
+pro std_plot_EqU, U1, U2, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_EqU_'+std_file1_U
+  if std_file1_U NE std_file2_U then filename = filename + '_'+std_file2_U
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  title = 'Equatorial Zonal Current!C'+std_file1_U
+  pltz, U1, MININ = -1., MAXIN = 1., INTER = .1, typein = 'xz', STYLE = 'so0so', FORMAT = '(f4.1)' $
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], ZOOM = 500, /PORTRAIT, _extra = ex
+
+  if std_file1_U NE std_file2_U then begin
+    title = title+' - '+std_file2_U
+    pltz, U1.arr-U2.arr, MININ = -.5, MAXIN = .5, INTER = .1, typein = 'xz', STYLE = 'so0so', FORMAT = '(f4.1)' $
+          , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [20., 380., -1., 1., 0., 500.], ZOOM = 500, /PORTRAIT, _extra = ex
+  endif
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_GlobMeanTS.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_GlobMeanTS.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_GlobMeanTS.pro	(revision 14097)
@@ -0,0 +1,39 @@
+pro std_plot_GlobMeanTS, T1, T2, TLev, S1, S2, SLev, sEXP1, sEXP2, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_GlobMeanTS_'+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
+
+  varunit = T1.unit
+  title = 'Temperature Global mean!C'+std_file1_T+' - Levitus (Black)'
+  if std_file1_T NE std_file2_T THEN title = title+'!C'+std_file2_T+' - Levitus (Red)'
+  plt1d, T1.arr - TLev.arr, typein = 'z', ticklen = 1, MIN = -2., MAX = 2., boxzoom = [4., 5300.], /KEEPBOTTOM $
+         , small = [1, 2, 1], XGRIDSTYLE = 2, YGRIDSTYLE = 2, TITLE = title, /PORTRAIT,  _extra = ex
+  if std_file1_T NE std_file2_T then begin
+    plt1d, T2.arr - TLev.arr, typein = 'z',  ticklen = 1, MIN = -2., MAX = 2., boxzoom = [4., 5300.], /KEEPBOTTOM  $
+           , /ov1d, COLOR = 250, TITLE = title, _extra = ex 
+  endif
+;
+  varunit = S1.unit
+  title = 'Salinity Global mean!C'+std_file1_T+' - Levitus (Black)'
+  if std_file1_T NE std_file2_T THEN title = title+'!C'+std_file2_T+' - Levitus (Red)'
+  plt1d, S1.arr - SLev.arr, typein = 'z', ticklen = 1, MIN = -.2, MAX = .4, boxzoom = [4., 5300.], /KEEPBOTTOM $
+         , small = [1, 2, 2], XGRIDSTYLE = 2, YGRIDSTYLE = 2, TITLE = title, /NOERASE, _extra = ex
+  if std_file1_T NE std_file2_T then begin
+    plt1d, S2.arr - SLev.arr, typein = 'z',  ticklen = 1, MIN = -2., MAX = 4., boxzoom = [4., 5300.], /KEEPBOTTOM $
+           ,  /ov1d, COLOR = 250, TITLE = title, _extra = ex 
+  endif
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceAge.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceAge.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceAge.pro	(revision 14097)
@@ -0,0 +1,75 @@
+pro std_plot_IceAge, Iage1, Iage2, Ifra1, Ifra2, ARC = arc, ANT = ant, FEBR = febr, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'IceAge'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(febr) THEN var = var+'Febr'
+  IF keyword_set(march) THEN var = var+'March'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  IF std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  IF KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  IF keyword_set(arc) THEN BEGIN 
+    domdef, 20, 380, 50, 90
+    vmin = 0.
+    vmax = 7.
+    vint = 0.5 
+    fmtd = '(f4.1)'
+    vmind = -3.
+    vmaxd = 3.
+    vintd = 0.5
+    fmtd = '(f4.1)'
+    div = 7
+    map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN 
+    domdef, 20, 380, -90, -50
+    vmin = 0.
+    vmax = 2.
+    vint = 0.2
+    fmt = '(f4.1)'
+    vmind = -1.
+    vmaxd = 1.
+    vintd = 0.2
+    fmtd = '(f4.1)'
+    div = 5
+    map = [-90, 0, 0]
+  ENDIF
+;
+  varunit = Iage1.unit
+;
+  title = var+'!C'+std_file1_I
+  
+  Iage1.arr = Iage1.arr * ( Ifra1.arr gt 0.15 )
+ 
+  plt, Iage1.arr - 1.E-04, MIN = vmin, MAX = vmax, INTER = vint, /STRICTFILL, CELL_FILL = 2, format = fmt $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, divisions = div  $
+       , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+;                                ;
+  if std_file1_I NE std_file2_I then begin            
+    title = title + std_file2_I
+ 
+    Iage2.arr = Iage2.arr * ( Ifra2.arr gt 0.15 )
+  
+    plt, Iage1.arr - Iage2.arr, MIN = vmind, MAX = vmaxd, INTER = vintd, STYLE = 'so0so', format = fmtd $
+         , small = [1, 2, 2], COAST_THICK = 2, CELL_FILL = 2, TITLE = title  $
+         , CHARSIZE = 1.05, GLINETHICK = 2., /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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceFrac.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceFrac.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceFrac.pro	(revision 14097)
@@ -0,0 +1,60 @@
+pro std_plot_IceFrac, Ifra1, Ifra2, ARC = arc, ANT = ant, FEBR = febr, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'IceFra'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(febr) THEN var = var+'Febr'
+  IF keyword_set(march) THEN var = var+'March'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  if std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  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 = Ifra1.unit
+;
+  title = var+'!C'+std_file1_I
+  Ifra1.arr = Ifra1.arr * ( Ifra1.arr gt 0.15 )
+  plt, Ifra1.arr - 1.E-04, MIN = 0., MAX = 1., INTER = .1, /STRICTFILL, CELL_FILL = 2, format = '(f4.1)' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title $
+       , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+;                                ;
+  if std_file1_I NE std_file2_I then begin            
+    title = title + std_file2_I
+    Ifra2.arr = Ifra2.arr * ( Ifra2.arr gt 0.15 )
+    plt, Ifra1.arr - Ifra2.arr, MIN = -1, MAX = 1, INTER = .1, STYLE = 'so0so', format = '(f4.1)' $
+         , small = [1, 2, 2], COAST_THICK = 2, CELL_FILL = 2, TITLE = title $
+         , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /NOERASE, _extra = ex
+;;SF  finire, aggiungere lettura obs
+;;SF  endif else begin
+;;SF    title = title+ ' - Observations'
+;;SF    plt, Ifra1.arr - Ifra_obs.arr, MIN = -1., MAX = 1., INTER = 0.1, STYLE = 'so0so', format = '(f4.1)' $
+;;SF         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, CELL_FILL = 2, TITLE = title $
+;;SF         , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /NOERASE, _extra = ex
+;;SF  endelse  
+endif
+
+  domdef
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceSal.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceSal.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceSal.pro	(revision 14097)
@@ -0,0 +1,57 @@
+pro std_plot_IceSal, Isal1, Isal2, Ifra1, Ifra2, ARC = arc, ANT = ant, FEBR = febr, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+;
+  var = 'IceSal'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(febr) THEN var = var+'Febr'
+  IF keyword_set(march) THEN var = var+'March'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  if std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+ 
+  IF keyword_set(arc) THEN BEGIN
+     domdef, 20, 380, 50, 90
+     map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN
+     domdef, 20, 380, -90, -50
+     map = [-90, 0, 0]
+  ENDIF
+  ;
+  varunit = Isal1.unit
+  ;
+   title = var+'!C'+std_file1_I
+
+   Isal1.arr = Isal1.arr * ( Ifra1.arr gt 0.15 )
+   plt, Isal1.arr - 1.E-04, MIN = 0., MAX = 10., INTER = 1., /STRICTFILL, CELL_FILL = 2, format = '(f4.1)' $
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title $
+        , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+ ;                                ;
+   if std_file1_I NE std_file2_I then begin
+     title = title + std_file2_I
+     
+     Isal2.arr = Isal2.arr * ( Ifra2.arr gt 0.15 )
+     
+     plt, Isal1.arr - Isal2.arr, MIN = -2., MAX = 2., INTER = 1., STYLE = 'so0so', format = '(f4.1)' $
+          , small = [1, 2, 2], COAST_THICK = 2, CELL_FILL = 2, TITLE = title $
+          , CHARSIZE = 1.05, GLINETHICK = 2., /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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceThick.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceThick.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceThick.pro	(revision 14097)
@@ -0,0 +1,75 @@
+pro std_plot_IceThick, Ithi1, Ithi2, Ifra1, Ifra2, ARC = arc, ANT = ant, APRIL = april, JAN = jan, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'IceThi'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(april) THEN var = var+'April'
+  IF keyword_set(jan) THEN var = var+'Jan'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  IF std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  IF KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  IF keyword_set(arc) THEN BEGIN 
+    domdef, 20, 380, 50, 90
+    vmin = 0.
+    vmax = 6.
+    vint = 0.5
+    fmtd = '(f4.1)'
+    vmind = -3.
+    vmaxd = 3.
+    vintd = 0.5
+    fmtd = '(f4.1)'
+    div = 6
+    map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN 
+    domdef, 20, 380, -90, -50
+    vmin = 0.
+    vmax = 3.
+    vint = 0.2
+    fmt = '(f4.1)'
+    vmind = -1.
+    vmaxd = 1.
+    vintd = 0.2
+    fmtd = '(f4.1)'
+    div = 5
+    map = [-90, 0, 0]
+  ENDIF
+;
+  varunit = Ithi1.unit
+;
+  title = var+'!C'+std_file1_I
+
+  Ithi1.arr = Ithi1.arr * ( Ifra1.arr gt 0.15 )
+ 
+  plt, (Ithi1.arr < 10. ) - 1.E-04, MIN = vmin, MAX = vmax, INTER = vint, /STRICTFILL, CELL_FILL = 2, format = fmt $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, divisions = div  $
+       , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+;                                ;
+  if std_file1_I NE std_file2_I then begin            
+    title = title + std_file2_I
+
+    Ithi2.arr = Ithi2.arr * ( Ifra2.arr gt 0.15 )
+
+    plt, Ithi1.arr - Ithi2.arr, MIN = vmind, MAX = vmaxd, INTER = vintd, STYLE = 'so0so', format = fmtd $
+         , small = [1, 2, 2], COAST_THICK = 2, CELL_FILL = 2, TITLE = title  $
+         , CHARSIZE = 1.05, GLINETHICK = 2., /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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceVel.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceVel.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_IceVel.pro	(revision 14097)
@@ -0,0 +1,60 @@
+pro std_plot_IceVel, IvelU1, IvelU2, IvelV1, IvelV2, Ivelo1, Ivelo2, ARC = arc, ANT = ant, FEBR = febr, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'IceVel'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(febr) THEN var = var+'Febr'
+  IF keyword_set(march) THEN var = var+'March'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  if std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+ 
+  IF keyword_set(arc) THEN BEGIN
+     domdef, 20, 380, 50, 90
+     map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN
+     domdef, 20, 380, -90, -50
+     map = [-90, 0, 0]
+  ENDIF
+  ;
+  title = var+'!C'+std_file1_I
+   
+  Ivelo1 = {arr: Ivelo1.arr - 1.E-04, g: 'T'}
+  ; Ivelo1 = {arr: Ivelo1.arr, g: 'T'}
+  
+  plt, Ivelo1, vecteur={u:IvelU1, v:IvelV1}, unvectsur=[3,3], normeref = 0.5, cmref = 1.  $
+        , small = [1, 2, 1], TITLE = title $
+        , /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+ ;                                
+ 
+  if std_file1_I NE std_file2_I then begin
+     title = title + std_file2_I  
+  ;   
+     Ivelo = {arr: Ivelo1.arr - Ivelo2.arr, g: 'T'}
+     ; Ivelo1 = {arr: Ivelo1.arr, g: 'T'}
+     ; Ivelo2 = {arr: Ivelo2.arr - 1.E-04, g: 'T'}
+     Ivelo2 = {arr: Ivelo2.arr , g: 'T'}
+    
+     plt, Ivelo, vecteur={u: IvelU2, v: IvelV2}, unvectsur=[3,3], normeref = 0.5, cmref = 1.  $
+          , small = [1, 2, 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_MLD_ortho.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_MLD_ortho.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_MLD_ortho.pro	(revision 14097)
@@ -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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sdepth.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sdepth.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sdepth.pro	(revision 14097)
@@ -0,0 +1,36 @@
+pro std_plot_Med_Sdepth, S1, S2, SLev, lat, POSTSCRIPT = postscript,  _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  slat = strtrim(lat, 1)+'N'
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_Med_Sdepth_'+slat+'_'+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
+;
+  title = 'Salinity ('+slat+')!C'+std_file1_T
+  pltz, S1, MININ = 35., MAXIN = 37., INTER = 0.1, FORMAT = '(f4.1)' $
+        , small = [1, 2, 1], COAST_THICK = 2, endpoints = [300., lat, 357., lat], TITLE = title $
+        , boxzoom = [2000.], ZOOM = 2000., /PORTRAIT, _extra = ex 
+;
+  if std_file1_T NE std_file2_T then begin
+    title = title+ ' - '+std_file2_T
+    pltz, S1.arr - S2.arr + valmask*(1.-tmask), MININ = -.4, MAXIN = .4, INTER = .05, STYLE = 'so0so', FORMAT = '(f4.1)' $ 
+          , small = [1, 2, 2], COAST_THICK = 2, endpoints = [300., lat, 357., lat], TITLE = title $
+          , boxzoom = [2000.], ZOOM = 2000., /noerase, _extra = ex 
+  endif else begin
+    title = title+ ' - Levitus'
+    pltz, S1.arr - SLev.arr + valmask*(1.-tmask), MININ = -1., MAXIN = 1., INTER = 0.1, STYLE = 'so0so', FORMAT = '(f4.1)' $ 
+          , small = [1, 2, 2], COAST_THICK = 2, endpoints = [300., lat, 357., lat], TITLE = title $
+          , boxzoom = [2000.], ZOOM = 2000., /noerase, _extra = ex 
+  endelse
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sspread.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sspread.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_Med_Sspread.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_Med_Sspread, S1, S2, SLev, depth, POSTSCRIPT = postscript,  _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  tmp = min(abs(depth - gdept), ind)
+  sdepref = strtrim(round(gdept[ind]), 1)+'m'
+  filename = cdti3 + '_Med_Sspread_'+sdepref+'_'+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
+;  
+  title = 'Salinity ('+sdepref+')!C'+std_file1_T
+  plt, S1, MININ = 35., MAXIN = 37., INTER = 0.1, FORMAT = '(f4.1)' $
+       , small = [1, 2, 1], boxzoom = [270, 365, 5, 70, ind, ind], /zindex, COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+;
+  if std_file1_T NE std_file2_T then begin
+    title = title+ ' - '+std_file2_T
+    plt, S1.arr - S2.arr, MININ = -.4, MAXIN = .4, INTER = .05, STYLE = 'so0so', FORMAT = '(f4.1)'  $
+         , small = [1, 2, 2], boxzoom = [270, 365, 5, 70, ind, ind], /zindex, COAST_THICK = 2, TITLE = title, /noerase, _extra = ex
+  endif else begin
+    title = title+ ' - Levitus'
+    plt, S1.arr - SLev.arr, MININ = -1., MAXIN = 1., INTER = 0.1, STYLE = 'so0so', FORMAT = '(f4.1)'  $
+         , small = [1, 2, 2], boxzoom = [270, 365, 5, 70, ind, ind], /zindex, COAST_THICK = 2, TITLE = title, /noerase, _extra = ex
+  ENDELSE
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_S100m.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_S100m.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_S100m.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_S100m, S1, S2, SLev, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  tmp = min(abs(100 - gdept), ind)
+  sdepref = strtrim(round(gdept[ind]), 1)+'m'
+  filename = cdti3 + '_S'+sdepref+'_'+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
+;
+  title = 'Salinity ('+sdepref+')!C'+std_file1_T
+  plt, S1, MIN = 33., MAX = 38.2, INTER = .2, format = '(f4.1)' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /PORTRAIT, _extra = ex
+;
+  if std_file1_T NE std_file2_T then begin
+    title = title+ ' - '+std_file2_T
+    plt, S1.arr[*, *, 0] - S2.arr[*, *, 0], MIN = -1., MAX = 1., INTER = .1, STYLE = 'so0so', format = '(f4.1)' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /noerase, _extra = ex   
+  endif else begin
+    title = title+ ' - Levitus'
+    plt, S1.arr-SLev.arr, MIN = -1., MAX = 1., INTER = 0.1, STYLE = 'so0so', format = '(f4.1)' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /noerase, _extra = ex
+  endelse
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_SnowThick.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_SnowThick.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_SnowThick.pro	(revision 14097)
@@ -0,0 +1,75 @@
+pro std_plot_SnowThick, Isnow1, Isnow2, Ifra1, Ifra2, ARC = arc, ANT = ant, FEBR = febr, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'SnowThi'
+  IF keyword_set(arc) THEN var = var+'_Arc_'
+  IF keyword_set(ant) THEN var = var+'_Ant_'
+  IF keyword_set(febr) THEN var = var+'Febr'
+  IF keyword_set(march) THEN var = var+'March'
+  IF keyword_set(sept) THEN var = var+'Sept'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_I
+  if std_file1_I NE std_file2_I then filename = filename + '_'+std_file2_I
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  IF keyword_set(arc) THEN BEGIN 
+    domdef, 20, 380, 50, 90
+    vmin = 0.
+    vmax = .6
+    vint = 0.1
+    ;fmt = '(i2)'
+    fmt = '(f4.1)'
+    vmind = -1.
+    vmaxd = 1.
+    vintd = 0.1
+    ;fmtd = '(i2)'
+    fmtd = '(f4.1)'
+    map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN 
+    domdef, 20, 380, -90, -50
+    vmin = 0.
+    vmax = 1.
+    vint = 0.1
+    fmt = '(f4.1)'
+    vmind = -1.
+    vmaxd = 1.
+    vintd = 0.1
+    fmtd = '(f4.1)'
+    map = [-90, 0, 0]
+  ENDIF
+;
+  varunit = Isnow1.unit
+;
+  title = var+'!C'+std_file1_I
+  
+  Isnow1.arr = Isnow1.arr * ( Ifra1.arr gt 0.15 )
+  
+  plt, (Isnow1.arr < 10. ) - 1.E-04, MIN = vmin, MAX = vmax, INTER = vint, /STRICTFILL, CELL_FILL = 2, format = fmt $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title $
+       , CHARSIZE = 1.05, GLINETHICK = 2., /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+;                                ;
+  if std_file1_I NE std_file2_I then begin            
+    title = title + std_file2_I
+   
+    Isnow2.arr = Isnow2.arr * ( Ifra2.arr gt 0.15 )
+     
+    plt, Isnow1.arr - Isnow2.arr, MIN = vmind, MAX = vmaxd, INTER = vintd, STYLE = 'so0so', format = fmtd $
+         , small = [1, 2, 2], COAST_THICK = 2, CELL_FILL = 2, TITLE = title $
+         , CHARSIZE = 1.05, GLINETHICK = 2., /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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_T100m.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_T100m.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_T100m.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_T100m, T1, T2, TLev, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  tmp = min(abs(100 - gdept), ind)
+  sdepref = strtrim(round(gdept[ind]), 1)+'m'
+  filename = cdti3 + '_T'+sdepref+'_'+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
+;                              
+  title = 'Temperature ('+sdepref+')!C'+std_file1_T
+  plt, T1, MIN = -2., MAX = 32., INTER = 1., FORMAT = '(I2)'  $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /portrait, _extra = ex
+;
+  IF std_file1_T NE std_file2_T THEN BEGIN
+    title = title+ ' - '+std_file2_T
+    plt, T1.arr - T2.arr, MIN = -2., MAX = 2., INTER = .2, STYLE = 'so0so', FORMAT = '(f4.1)' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /noerase,  _extra = ex
+  ENDIF ELSE BEGIN
+    title = title+ ' - Levitus'
+    plt, T1.arr - TLev.arr, MIN = -5., MAX = 5., INTER = .5, STYLE = 'so0so', FORMAT = '(I2)'  $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = [floor(gdept[ind]), ceil(gdept[ind])], /noerase, _extra = ex   
+  ENDELSE
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ZonMld.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ZonMld.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_ZonMld.pro	(revision 14097)
@@ -0,0 +1,32 @@
+pro std_plot_ZonMld, MLD1, MLD2, MLD, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ZonMld_'+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
+                                ;
+  title = std_file1_T+' (Black)!C'
+  if std_file1_T NE std_file2_T THEN title = title + std_file2_T+' (Red)!C'
+  title = title + 'DeBoyer (Blue)!C'
+
+  plt1d, -MLD1.arr, MIN = -300., MAX = 0., INTER = 10., typein = 'y' $
+         , small = [1, 1, 1], boxzoom = 5500, ZOOM = 500, CHARSIZE = .8, TITLE = title, /PORTRAIT, _extra = ex 
+                                ;
+  IF std_file1_T NE std_file2_T THEN $
+     plt1d, -MLD2.arr, MIN = -300., MAX = 0., INTER = 10., typein = 'y' $
+            , /ov1d, COLOR = 250, TITLE = title, /NOERASE, _extra = ex ; color 250 = red
+                                ;
+  plt1d, -MLD.arr, MIN = -300., MAX = 0., INTER = 10., typein = 'y' $
+         ,  /ov1d, COLOR = 100, THICK = 3, TITLE = title, /NOERASE, _extra = ex ; color 100 = blue
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all.pro	(revision 14097)
@@ -0,0 +1,589 @@
+pro std_plot_all, doplot = doplot, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common
+@std_common
+                                ; scripts for nemo v3_2 and v3_3
+
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+  PRINT, '                    LAUNCH of std_plots'
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+;
+  std_iodir_data    = isadirectory(getenv('DIR_DATA'),     title = 'path of data in NetCdf format')
+  std_iodir_climato = isadirectory(getenv('DIR_CLIMATO'),  title = 'path of climatological data')
+  std_iodir_mask    = isadirectory(getenv('DIR_MASK'),     title = 'path of mask files (ex: subbasins)')
+; meshmask
+  std_file_mesh = isafile(getenv('FILE_MESH_MASK'),        title = 'mesh_mask', iodir = std_iodir_mask)
+  std_file_msksub = isafile(getenv('FILE_MASK_SUBDOMAIN'), title = 'sub-bassin masks', iodir = std_iodir_mask)
+
+; climatologies
+  std_file_Levitus_T =  isafile(getenv('FILE_TEMP_3D'),    title = 'Levitus_T', iodir = std_iodir_climato)
+  std_file_Levitus_S =  isafile(getenv('FILE_SAL_3D'),     title = 'Levitus_S', iodir = std_iodir_climato)
+  std_file_reynolds  =  isafile(getenv('FILE_SST'),        title = 'Reynolds', iodir = std_iodir_climato)
+  std_file_oaflux    =  isafile(getenv('FILE_FLUX'),       title = 'oaflux', iodir = std_iodir_climato)
+  std_file_mld       =  isafile(getenv('FILE_MLD'),        title = 'Mixed layer depth', iodir = std_iodir_climato)
+  std_file_ice       =  isafile(getenv('FILE_ICE'),        title = 'ICE', iodir = std_iodir_climato)
+  std_file_snow_arc  =  isafile(getenv('FILE_SNOW_ARC'),   title = 'SNOW_ARC', iodir = std_iodir_climato)
+  std_file_snow_ant  =  isafile(getenv('FILE_SNOW_ANT'),   title = 'SNOW_ANT', iodir = std_iodir_climato)
+
+  IF strlowcase(getenv('FILE_GEOHEAT')) EQ 'no' THEN std_file_geoheat = 'no' $
+  ELSE std_file_geoheat =  isafile(getenv('FILE_GEOHEAT'), title = 'Geothermal heating', iodir = std_iodir_climato)
+;
+  allrec =  1 - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+  
+; Output run experience1
+  std_file1_T     = isafile(getenv('FILE1_T'), title = 'exp1 grid T input file', iodir = std_iodir_data)
+  std_file1_U     = isafile(getenv('FILE1_U'), title = 'exp1 grid U input file', iodir = std_iodir_data)
+  std_file1_V     = isafile(getenv('FILE1_V'), title = 'exp1 grid V input file', iodir = std_iodir_data)
+  std_file1_I     = isafile(getenv('FILE1_I'), title = 'exp1 ice    input file', iodir = std_iodir_data)
+  
+; Output run experience2
+  std_file2_T     = isafile(getenv('FILE2_T'), title = 'exp2 grid T input file', iodir = std_iodir_data)
+  std_file2_U     = isafile(getenv('FILE2_U'), title = 'exp2 grid U input file', iodir = std_iodir_data)
+  std_file2_V     = isafile(getenv('FILE2_V'), title = 'exp2 grid V input file', iodir = std_iodir_data)
+  std_file2_I     = isafile(getenv('FILE2_I'), title = 'exp2 ice    input file', iodir = std_iodir_data)
+
+  PRINT, ''
+  PRINT, '	std_iodir_data : ' + std_iodir_data 
+  PRINT, '	std_file1T : ' + std_file1_T
+  PRINT, '	std_file1U : ' + std_file1_U
+  PRINT, '	std_file1V : ' + std_file1_V
+;  PRINT, '	std_file1W : ' + std_file1_W
+  PRINT, '	std_file2I : ' + std_file1_I
+  PRINT, '	std_file2T : ' + std_file2_T
+  PRINT, '	std_file2U : ' + std_file2_U
+  PRINT, '	std_file2V : ' + std_file2_V
+;  PRINT, '	std_file2W : ' + std_file2_W
+  PRINT, '	std_file2I : ' + std_file2_I
+  PRINT, ''
+
+;#########################################################################
+;##########################  Load Grids   ################################
+;#########################################################################
+; load the grid
+  load_orca, std_file_mesh  
+; reading variables
+  masknp = read_ncdf('tmaskutil', file = std_file_mesh, /nostruct, /cont_nofill)
+;#########################################################################
+;############################  Read Data  ################################
+;#########################################################################
+;
+  allrec =  1; - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+;
+;;; 3D ;;;
+; temperature
+  T1 = read_ncdf(getenv('VAR1_T'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    T2 = read_ncdf(getenv('VAR2_T'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE T2 = {arr:-1}
+  TLev = read_ncdf(getenv('VAR_TEMP_3D'), filename = std_file_Levitus_T ) 
+  TRey = read_ncdf(getenv('VAR_SST'), filename = std_file_reynolds ) 
+
+; salinity
+  S1 = read_ncdf(getenv('VAR1_S'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    S2 = read_ncdf(getenv('VAR2_S'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE S2 = {arr:-1}
+  SLev = read_ncdf(getenv('VAR_SAL_3D'), filename = std_file_Levitus_S ) 
+
+;;; 2D ;;;
+; Net Downward heat flux
+  Q1 = read_ncdf(getenv('VAR1_QNET'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    Q2 = read_ncdf(getenv('VAR2_QNET'), allrecords = allrec, direc = 't', filename = std_file2_T )
+  ENDIF ELSE Q2 = {arr:-1}
+; Geothermal heating
+  IF std_file_geoheat EQ 'no' THEN geo = {arr:float(getenv('VAR_GEOHEAT'))} $
+  ELSE geo = read_ncdf(getenv('VAR_GEOHEAT'), filename =  std_file_geoheat )
+  geo = geo.arr*1.e-3          ; convert into W/m2
+;climatology 
+  QNET = read_ncdf(getenv('VAR_FLUX'), filename = std_file_oaflux )
+
+; erp (evaporation damping)
+  ERP1 = read_ncdf(getenv('VAR1_ERP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  ERP1 = {arr:ERP1.arr * 86400., unit:'mm/day', grid:'T'}
+  IF std_file2_T NE std_file1_T THEN BEGIN
+     ERP2 = read_ncdf(getenv('VAR2_ERP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+     ERP2 = {arr:ERP2.arr * 86400., unit:'mm/day', grid:'T'}
+  ENDIF ELSE ERP2 = {arr:-1}
+ 
+; emp (evaporation minus precipitation)
+  EMP1 = read_ncdf(getenv('VAR1_EMP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  EMP1 = {arr:EMP1.arr * 86400., unit:'mm/day', grid:'T'}
+   IF std_file2_T NE std_file1_T THEN BEGIN
+     EMP2 = read_ncdf(getenv('VAR2_EMP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+     EMP2 = {arr:EMP2.arr * 86400., unit:'mm/day', grid:'T'}
+   ENDIF ELSE EMP2 = {arr:-1}
+   
+ ;mixed layer depth
+   MLD1 = read_ncdf(getenv('VAR1_MLD'), allrecords = allrec, direc = 't', filename = std_file1_T ) ; 10 m
+   IF std_file2_T NE std_file1_T THEN BEGIN
+     MLD2 = read_ncdf(getenv('VAR2_MLD'), allrecords = allrec, direc = 't', filename = std_file2_T ) ; 10 m
+   ENDIF ELSE MLD2 = {arr:-1}
+ ;climatology 
+   MLD = read_ncdf(getenv('VAR_MLD'), filename = std_file_mld )
+
+ ; velocities
+   U1 = read_ncdf(getenv('VAR1_U'), allrecords = allrec, direc = 't', filename = std_file1_U )
+   ; old formulation: we tested variable name
+   ; IF strlowcase(getenv('VAR1_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR1_U')) EQ 'vozoeftr' THEN BEGIN
+   IF strlowcase(U1.unit) EQ 'm3/s' THEN BEGIN
+     ;IF it is a transport it is transofrmed in velocity
+     U1.arr = U1.arr / e3u_3d(/e2) * umask()
+     U1.unit = 'm/s'
+   ENDIF 
+   IF std_file2_U NE std_file1_U THEN BEGIN
+     U2 = read_ncdf(getenv('VAR2_U'), allrecords = allrec, direc = 't', filename = std_file2_U )
+     ; old formulation: we tested variable name
+     ; IF strlowcase(getenv('VAR2_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR2_U')) EQ 'vozoeftr' THEN BEGIN
+     IF strlowcase(U2.unit) EQ 'm3/s' THEN BEGIN
+       U2.arr = U2.arr / e3u_3d(/e2) * umask()
+       U2.unit = 'm/s'
+     ENDIF 
+   ENDIF ELSE U2 = {arr:-1}
+;
+   V1 = read_ncdf(getenv('VAR1_V'), allrecords = allrec, direc = 't', filename = std_file1_V )
+   ; old formulation: we tested variable name
+   ; IF strlowcase(getenv('VAR1_V')) EQ 'vocetr_eff' OR strlowcase(getenv('VAR1_V')) EQ 'vomeeftr' THEN BEGIN
+   IF strlowcase(V1.unit) EQ 'm3/s' THEN BEGIN ; test on unit to understand if it is a transport or velocity
+     ;IF it is a transport it is transofrmed in velocity
+     V1.arr = V1.arr / e3v_3d(/e1) * vmask()
+     V1.unit = 'm/s'
+   ENDIF 
+   IF std_file2_V NE std_file1_V THEN BEGIN
+     V2 = read_ncdf(getenv('VAR2_V'), allrecords = allrec, direc = 't', filename = std_file2_V )
+     ; old formulation
+     ; IF strlowcase(getenv('VAR2_V')) EQ 'vocetr_eff' OR strlowcase(getenv('VAR2_V')) EQ 'vozoeftr' THEN BEGIN
+     IF strlowcase(V2.unit) EQ 'm3/s' THEN BEGIN 
+       V2.arr = V2.arr / e3v_3d(/e1) * vmask()
+       V2.unit = 'm/s'
+     ENDIF 
+   ENDIF ELSE V2 = {arr:-1}
+
+; ice
+  Ithi_1 = read_ncdf(getenv('VAR1_Ithick'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  april = where(mm EQ 4, cnt)
+  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_sept_1 = {arr:1./float(cnt) * total(reform(Ithi_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ithi_1.unit} 
+  undefine, Ithi_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Ithi_2 = read_ncdf(getenv('VAR2_Ithick'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     april = where(mm EQ 4, cnt)
+     Ithi_april_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     jan = where(mm EQ 1, cnt)
+     sept = where(mm EQ 9, cnt)
+     Ithi_sept_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     Ithi_jan_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     undefine, Ithi_2
+  ENDIF ELSE BEGIN 
+     Ithi_april_2 = {arr:-1}
+     Ithi_sept_2 = {arr:-1}
+     Ithi_jan_2 = {arr:-1}
+  ENDELSE
+;
+  Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  jan = where(mm EQ 1, cnt)
+  Ifra_jan_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  febr = where(mm EQ 2, cnt)
+  Ifra_febr_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  march = where(mm EQ 3, cnt)
+  Ifra_march_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  april = where(mm EQ 4, cnt)
+  Ifra_april_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  sept = where(mm EQ 9, cnt)
+  Ifra_sept_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_1.unit}
+  undefine, Ifra_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+    Ifra_2 = read_ncdf(getenv('VAR2_Ifrac'), allrecords = allrec, filename = std_file2_I ) 
+    caldat, time, mm
+    jan = where(mm EQ 1, cnt)
+    Ifra_jan_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    febr = where(mm EQ 2, cnt)
+    Ifra_febr_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    march = where(mm EQ 3, cnt)
+    Ifra_march_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    april = where(mm EQ 4, cnt)
+    Ifra_april_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    sept = where(mm EQ 9, cnt)
+    Ifra_sept_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    undefine, Ifra_2
+  ENDIF ELSE BEGIN 
+    Ifra_jan_2 = {arr:-1} 
+    Ifra_febr_2 = {arr:-1}
+    Ifra_march_2 = {arr:-1}
+    Ifra_april_2 = {arr:-1}
+    Ifra_sept_2 = {arr:-1}
+  ENDELSE
+;
+   Isnow_1 = read_ncdf(getenv('VAR1_Isnow'), allrecords = allrec, filename = std_file1_I ) 
+   caldat, time, mm
+   febr = where(mm EQ 2, cnt)
+   Isnow_febr_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   march = where(mm EQ 3, cnt)
+   Isnow_march_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isnow_sept_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_1.unit}
+   ;undefine, Isnow_1
+ ;
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     Isnow_2 = read_ncdf(getenv('VAR2_Isnow'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Isnow_febr_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     march = where(mm EQ 3, cnt)
+     Isnow_march_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isnow_sept_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+   ;  undefine, Isnow_2
+   ENDIF ELSE BEGIN 
+     Isnow_febr_2 = {arr:-1}
+     Isnow_march_2 = {arr:-1}
+     Isnow_sept_2 = {arr:-1}
+   ENDELSE
+;
+   Isal_1 = read_ncdf(getenv('VAR1_Isal'), allrecords = allrec, filename = std_file1_I ) 
+;SF  ready for mask : remove 0.15% for observations
+;SF
+;SF   Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I )
+;SF   msk = Ifra_1.arr gt 0.15 ; remove 0.15% for observations 
+   caldat, time, mm
+   march = where(mm EQ 3, cnt)
+   febr = where(mm EQ 2, cnt)
+   Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+;SF
+;SF   Isal_1.arr = Isal_1.arr * msk
+;SF 
+;SF   Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   Isal_febr_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isal_sept_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_1.unit}
+   ;undefine, Isal_1
+ ;
+   Isal_2 = read_ncdf(getenv('VAR2_Isal'), allrecords = allrec, filename = std_file2_I ) 
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     caldat, time, mm
+     march = where(mm EQ 3, cnt)
+     febr = where(mm EQ 2, cnt)
+     Isal_march_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     Isal_febr_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isal_sept_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+   ;  undefine, Isal_2
+   ENDIF ELSE BEGIN 
+     Isal_febr_2 = {arr:-1}
+     Isal_march_2 = {arr:-1}
+     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 ) 
+  Ivelo_1 = read_ncdf(getenv('VAR1_Ivelo'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  IvelU_febr_1 = {arr:1./float(cnt) * total(reform(IvelU_1.arr[*, *, febr],nxt,nyt,cnt), 3), unit:IvelU_1.unit, g: 'T'}
+  IvelV_febr_1 = {arr:1./float(cnt) * total(reform(IvelV_1.arr[*, *, febr],nxt,nyt,cnt), 3), unit:IvelV_1.unit, g: 'T'}
+  Ivelo_febr_1 = {arr:1./float(cnt) * total(reform(Ivelo_1.arr[*, *, febr],nxt,nyt,cnt), 3), unit:Ivelo_1.unit, g: 'T'} 
+  march = where(mm EQ 3, cnt)
+  IvelU_march_1 = {arr:1./float(cnt) * total(reform(IvelU_1.arr[*, *, march],nxt,nyt,cnt), 3), unit:IvelU_1.unit, g: 'T'}
+  IvelV_march_1 = {arr:1./float(cnt) * total(reform(IvelV_1.arr[*, *, march],nxt,nyt,cnt), 3), unit:IvelV_1.unit, g: 'T'}
+  Ivelo_march_1 = {arr:1./float(cnt) * total(reform(Ivelo_1.arr[*, *, march],nxt,nyt,cnt), 3), unit:Ivelo_1.unit, g: 'T'} 
+  sept = where(mm EQ 9, cnt)
+  IvelU_sept_1 = {arr:1./float(cnt) * total(reform(IvelU_1.arr[*, *, sept],nxt,nyt,cnt), 3), unit:IvelU_1.unit, g: 'T'}
+  IvelV_sept_1 = {arr:1./float(cnt) * total(reform(IvelV_1.arr[*, *, sept],nxt,nyt,cnt), 3), unit:IvelV_1.unit, g: 'T'}
+  Ivelo_sept_1 = {arr:1./float(cnt) * total(reform(Ivelo_1.arr[*, *, sept],nxt,nyt,cnt), 3), unit:Ivelo_1.unit, g: 'T'}
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+    IvelU_2 = read_ncdf(getenv('VAR2_IvelU'), allrecords = allrec, filename = std_file2_I ) 
+    IvelV_2 = read_ncdf(getenv('VAR2_IvelV'), allrecords = allrec, filename = std_file2_I ) 
+    Ivelo_2 = read_ncdf(getenv('VAR2_Ivelo'), allrecords = allrec, filename = std_file2_I ) 
+    caldat, time, mm
+    febr = where(mm EQ 2, cnt)
+    IvelU_febr_2 = {arr:1./float(cnt) * total(reform(IvelU_2.arr[*, *, febr],nxt,nyt,cnt), 3), unit:IvelU_2.unit}
+    IvelV_febr_2 = {arr:1./float(cnt) * total(reform(IvelV_2.arr[*, *, febr],nxt,nyt,cnt), 3), unit:IvelV_2.unit}
+    Ivelo_febr_2 = {arr:1./float(cnt) * total(reform(Ivelo_2.arr[*, *, febr],nxt,nyt,cnt), 3), unit:Ivelo_2.unit}
+    march = where(mm EQ 3, cnt)
+    IvelU_march_2 = {arr:1./float(cnt) * total(reform(IvelU_2.arr[*, *, march],nxt,nyt,cnt), 3), unit:IvelU_2.unit}
+    IvelV_march_2 = {arr:1./float(cnt) * total(reform(IvelV_2.arr[*, *, march],nxt,nyt,cnt), 3), unit:IvelV_2.unit}
+    Ivelo_march_2 = {arr:1./float(cnt) * total(reform(Ivelo_2.arr[*, *, march],nxt,nyt,cnt), 3), unit:Ivelo_2.unit}
+    sept = where(mm EQ 9, cnt)
+    IvelU_sept_2 = {arr:1./float(cnt) * total(reform(IvelU_2.arr[*, *, sept],nxt,nyt,cnt), 3), unit:IvelU_2.unit}
+    IvelV_sept_2 = {arr:1./float(cnt) * total(reform(IvelV_2.arr[*, *, sept],nxt,nyt,cnt), 3), unit:IvelV_2.unit}   
+    Ivelo_sept_2 = {arr:1./float(cnt) * total(reform(Ivelo_2.arr[*, *, sept],nxt,nyt,cnt), 3), unit:Ivelo_2.unit}
+    undefine, Ifra_2
+  ENDIF ELSE BEGIN 
+    IvelU_febr_2 = {arr:-1}
+    IvelV_febr_2 = {arr:-1}
+    Ivelo_febr_2 = {arr:-1}
+    IvelU_march_2 = {arr:-1}
+    IvelV_march_2 = {arr:-1}
+    Ivelo_march_2 = {arr:-1}
+    IvelU_sept_2 = {arr:-1}
+    IvelV_sept_2 = {arr:-1}
+    Ivelo_sept_2 = {arr:-1}
+  ENDELSE
+
+  Iage_1 = read_ncdf(getenv('VAR1_Iage'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  Iage_febr_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  march = where(mm EQ 3, cnt)
+  Iage_march_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  sept = where(mm EQ 9, cnt)
+  Iage_sept_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_1.unit} 
+  undefine, Iage_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Iage_2 = read_ncdf(getenv('VAR2_Iage'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Iage_febr_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     march = where(mm EQ 3, cnt)
+     Iage_march_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     sept = where(mm EQ 9, cnt)
+     Iage_sept_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     undefine, Iage_2
+  ENDIF ELSE BEGIN 
+     Iage_febr_2 = {arr:-1}
+     Iage_march_2 = {arr:-1}
+     Iage_sept_2 = {arr:-1}
+  ENDELSE
+;
+  jpt = 1
+;
+; shorter file names for legends...
+;
+  std_file1_T = file_basename(std_file1_T,'.nc')
+  std_file1_T = (strsplit(std_file1_T,'_grid_T',/extract,/regex))[0]
+  std_file2_T = file_basename(std_file2_T,'.nc')
+  std_file2_T = (strsplit(std_file2_T,'_grid_T',/extract,/regex))[0]
+  std_file1_U = file_basename(std_file1_U,'.nc')
+  std_file1_U = (strsplit(std_file1_U,'_grid_U',/extract,/regex))[0]
+  std_file2_U = file_basename(std_file2_U,'.nc')
+  std_file2_U = (strsplit(std_file2_U,'_grid_U',/extract,/regex))[0]
+  std_file1_V = file_basename(std_file1_V,'.nc')
+  std_file1_V = (strsplit(std_file1_V,'_grid_V',/extract,/regex))[0]
+  std_file2_V = file_basename(std_file2_V,'.nc')
+  std_file2_V = (strsplit(std_file2_V,'_grid_V',/extract,/regex))[0]
+  std_file1_I = file_basename(std_file1_I,'.nc')
+  std_file1_I = (strsplit(std_file1_I,'_icemod',/extract,/regex))[0]
+  std_file2_I = file_basename(std_file2_I,'.nc')
+  std_file2_I = (strsplit(std_file2_I,'_icemod',/extract,/regex))[0]
+
+;#########################################################################
+;######################  STANDARD PLOTS   ################################
+;#########################################################################
+
+  IF keyword_set(doplot) EQ 0 THEN doplot = 0
+
+; fixed color tabled
+  lct, 64
+  cnt = 0
+  htmltxt = ''
+;
+  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
+;
+  cnt = cnt+1   &   blabla = 'Net heat flux'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_qnet, Q1, Q2, QNET, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Meridionnal Heat Transport'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mht, Q1.arr+geo, Q2.arr+geo, masknp, std_file_msksub, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Global Barotropic stream Function'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_bsf, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with New Reynolds'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sst, T1, T2, TRey, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sss, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, _extra = ex       
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, /z100, _extra = ex       
+; 
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2 at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, /z100, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_T100m, T1, T2, Tlev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_S100m, S1, S2, SLev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Mixed layer depth'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD1, MLD, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mixed layer depth differences'
+  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
+;  
+  cnt = cnt+1   &   blabla = 'Vertical Global mean T & S'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_GlobMeanTS, T1, T2, TLev, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Atl', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Ind', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Pac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Atl', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Ind', _extra = ex 
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Pac', _extra = ex 
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Global (no Med)'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'GloNoMed', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Atl', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Ind', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indo-Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'IndoPac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Temperature'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqT, T1, T2, Tlev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Salinity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqS, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial zonal velocity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqU, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=700'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 700, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=1000'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 1000, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=40¡ N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 40, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=38¡ N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 38, _extra = ex
+;
+;;
+; all plot are done for ice fraction > 0.15%
+;;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: JAN'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_jan_1, Ithi_jan_2, Ifra_jan_1, Ifra_jan_2, /ARC, /JAN, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, Ifra_april_1, Ifra_april_2, /ARC, /APRIL, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, Ifra_april_1, Ifra_april_2, /ANT, /APRIL, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_sept_1, Ithi_sept_2, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_march_1, Isnow_march_2, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_febr_1, Isnow_febr_2, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_march_1, Isal_march_2, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: FEBRUARY'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_febr_1, Isal_febr_2, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Velocity: FEBRUARY'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceVel, IvelU_febr_1, IvelU_febr_2, IvelV_febr_1, IvelV_febr_2, Ivelo_febr_1, Ivelo_febr_2, /ARC, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic 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, /ARC,  /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antartic Ice Velocity: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceVel, IvelU_march_1, IvelU_march_2, IvelV_march_1, IvelV_march_2, Ivelo_march_1, Ivelo_march_2, /ANT,  /MARCH, _extra = ex
+;
+  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
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2,  Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: FEBR'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_febr_1, Iage_febr_2, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2,  Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+;
+ 
+  IF n_elements(htmltxt) GT 1 THEN putfile, psdir+'std_plot_html_body.txt', htmltxt[1:*]
+  
+  return
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_1Y.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_1Y.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_1Y.pro	(revision 14097)
@@ -0,0 +1,510 @@
+pro std_plot_all_1Y, doplot = doplot, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common
+@std_common
+                                ; scripts for nemo v3_2 and v3_3
+
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+  PRINT, '                    LAUNCH of std_plots'
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+;
+  std_iodir_data    = isadirectory(getenv('DIR_DATA'),     title = 'path of data in NetCdf format')
+  std_iodir_climato = isadirectory(getenv('DIR_CLIMATO'),  title = 'path of climatological data')
+  std_iodir_mask    = isadirectory(getenv('DIR_MASK'),     title = 'path of mask files (ex: subbasins)')
+; meshmask
+  std_file_mesh = isafile(getenv('FILE_MESH_MASK'),        title = 'mesh_mask', iodir = std_iodir_mask)
+  std_file_msksub = isafile(getenv('FILE_MASK_SUBDOMAIN'), title = 'sub-bassin masks', iodir = std_iodir_mask)
+
+; climatologies
+  std_file_Levitus_T =  isafile(getenv('FILE_TEMP_3D'),    title = 'Levitus_T', iodir = std_iodir_climato)
+  std_file_Levitus_S =  isafile(getenv('FILE_SAL_3D'),     title = 'Levitus_S', iodir = std_iodir_climato)
+  std_file_reynolds  =  isafile(getenv('FILE_SST'),        title = 'Reynolds', iodir = std_iodir_climato)
+  std_file_oaflux    =  isafile(getenv('FILE_FLUX'),       title = 'oaflux', iodir = std_iodir_climato)
+  std_file_mld       =  isafile(getenv('FILE_MLD'),        title = 'Mixed layer depth', iodir = std_iodir_climato)
+  std_file_ice       =  isafile(getenv('FILE_ICE'),        title = 'ICE', iodir = std_iodir_climato)
+  std_file_snow_arc  =  isafile(getenv('FILE_SNOW_ARC'),   title = 'SNOW_ARC', iodir = std_iodir_climato)
+  std_file_snow_ant  =  isafile(getenv('FILE_SNOW_ANT'),   title = 'SNOW_ANT', iodir = std_iodir_climato)
+
+  IF strlowcase(getenv('FILE_GEOHEAT')) EQ 'no' THEN std_file_geoheat = 'no' $
+  ELSE std_file_geoheat =  isafile(getenv('FILE_GEOHEAT'), title = 'Geothermal heating', iodir = std_iodir_climato)
+;
+  allrec =  1 - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+; Output run experience1
+  std_file1_T     = isafile(getenv('FILE1_T'), title = 'exp1 grid T input file', iodir = std_iodir_data)
+  std_file1_U     = isafile(getenv('FILE1_U'), title = 'exp1 grid U input file', iodir = std_iodir_data)
+  std_file1_V     = isafile(getenv('FILE1_V'), title = 'exp1 grid V input file', iodir = std_iodir_data)
+  std_file1_I     = isafile(getenv('FILE1_I'), title = 'exp1 ice    input file', iodir = std_iodir_data)
+  
+; Output run experience2
+  std_file2_T     = isafile(getenv('FILE2_T'), title = 'exp2 grid T input file', iodir = std_iodir_data)
+  std_file2_U     = isafile(getenv('FILE2_U'), title = 'exp2 grid U input file', iodir = std_iodir_data)
+  std_file2_V     = isafile(getenv('FILE2_V'), title = 'exp2 grid V input file', iodir = std_iodir_data)
+  std_file2_I     = isafile(getenv('FILE2_I'), title = 'exp2 ice    input file', iodir = std_iodir_data)
+
+  PRINT, ''
+  PRINT, '	std_iodir_data : ' + std_iodir_data 
+  PRINT, '	std_file1T : ' + std_file1_T
+  PRINT, '	std_file1U : ' + std_file1_U
+  PRINT, '	std_file1V : ' + std_file1_V
+;  PRINT, '	std_file1W : ' + std_file1_W
+  PRINT, '	std_file2I : ' + std_file1_I
+  PRINT, '	std_file2T : ' + std_file2_T
+  PRINT, '	std_file2U : ' + std_file2_U
+  PRINT, '	std_file2V : ' + std_file2_V
+;  PRINT, '	std_file2W : ' + std_file2_W
+  PRINT, '	std_file2I : ' + std_file2_I
+  PRINT, ''
+
+;#########################################################################
+;##########################  Load Grids   ################################
+;#########################################################################
+; load the grid
+  load_orca, std_file_mesh  
+; reading variables
+  masknp = read_ncdf('tmaskutil', file = std_file_mesh, /nostruct, /cont_nofill)
+;#########################################################################
+;############################  Read Data  ################################
+;#########################################################################
+;
+  allrec =  1; - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+;
+;;; 3D ;;;
+; temperature
+  T1 = read_ncdf(getenv('VAR1_T'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    T2 = read_ncdf(getenv('VAR2_T'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE T2 = {arr:-1}
+  TLev = read_ncdf(getenv('VAR_TEMP_3D'), filename = std_file_Levitus_T ) 
+  TRey = read_ncdf(getenv('VAR_SST'), filename = std_file_reynolds ) 
+
+; salinity
+  S1 = read_ncdf(getenv('VAR1_S'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    S2 = read_ncdf(getenv('VAR2_S'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE S2 = {arr:-1}
+  SLev = read_ncdf(getenv('VAR_SAL_3D'), filename = std_file_Levitus_S ) 
+
+;;; 2D ;;;
+; Net Downward heat flux
+  Q1 = read_ncdf(getenv('VAR1_QNET'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    Q2 = read_ncdf(getenv('VAR2_QNET'), allrecords = allrec, direc = 't', filename = std_file2_T )
+  ENDIF ELSE Q2 = {arr:-1}
+; Geothermal heating
+  IF std_file_geoheat EQ 'no' THEN geo = {arr:float(getenv('VAR_GEOHEAT'))} $
+  ELSE geo = read_ncdf(getenv('VAR_GEOHEAT'), filename =  std_file_geoheat )
+  geo = geo.arr*1.e-3          ; convert into W/m2
+;climatology 
+  QNET = read_ncdf(getenv('VAR_FLUX'), filename = std_file_oaflux )
+
+; erp (evaporation damping)
+  ERP1 = read_ncdf(getenv('VAR1_ERP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  ERP1 = {arr:ERP1.arr * 86400., unit:'mm/day', grid:'T'}
+  IF std_file2_T NE std_file1_T THEN BEGIN
+     ERP2 = read_ncdf(getenv('VAR2_ERP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+     ERP2 = {arr:ERP2.arr * 86400., unit:'mm/day', grid:'T'}
+  ENDIF ELSE ERP2 = {arr:-1}
+ 
+; emp (evaporation minus precipitation)
+  EMP1 = read_ncdf(getenv('VAR1_EMP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  EMP1 = {arr:EMP1.arr * 86400., unit:'mm/day', grid:'T'}
+   IF std_file2_T NE std_file1_T THEN BEGIN
+     EMP2 = read_ncdf(getenv('VAR2_EMP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+     EMP2 = {arr:EMP2.arr * 86400., unit:'mm/day', grid:'T'}
+   ENDIF ELSE EMP2 = {arr:-1}
+   
+ ;mixed layer depth
+   MLD1 = read_ncdf(getenv('VAR1_MLD'), allrecords = allrec, direc = 't', filename = std_file1_T ) ; 10 m
+   IF std_file2_T NE std_file1_T THEN BEGIN
+     MLD2 = read_ncdf(getenv('VAR2_MLD'), allrecords = allrec, direc = 't', filename = std_file2_T ) ; 10 m
+   ENDIF ELSE MLD2 = {arr:-1}
+ ;climatology 
+   MLD = read_ncdf(getenv('VAR_MLD'), filename = std_file_mld )
+
+ ; velocities
+   U1 = read_ncdf(getenv('VAR1_U'), allrecords = allrec, direc = 't', filename = std_file1_U )
+   ; old formulation: we tested variable name
+   ; IF strlowcase(getenv('VAR1_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR1_U')) EQ 'vozoeftr' THEN BEGIN
+   IF strlowcase(U1.unit) EQ 'm3/s' THEN BEGIN
+     ;IF it is a transport it is transofrmed in velocity
+     U1.arr = U1.arr / e3u_3d(/e2) * umask()
+     U1.unit = 'm/s'
+   ENDIF 
+   IF std_file2_U NE std_file1_U THEN BEGIN
+     U2 = read_ncdf(getenv('VAR2_U'), allrecords = allrec, direc = 't', filename = std_file2_U )
+     ; old formulation: we tested variable name
+     ; IF strlowcase(getenv('VAR2_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR2_U')) EQ 'vozoeftr' THEN BEGIN
+     IF strlowcase(U2.unit) EQ 'm3/s' THEN BEGIN
+       U2.arr = U2.arr / e3u_3d(/e2) * umask()
+       U2.unit = 'm/s'
+     ENDIF 
+   ENDIF ELSE U2 = {arr:-1}
+;
+   V1 = read_ncdf(getenv('VAR1_V'), allrecords = allrec, direc = 't', filename = std_file1_V )
+   ; old formulation: we tested variable name
+   ; IF strlowcase(getenv('VAR1_V')) EQ 'vocetr_eff' OR strlowcase(getenv('VAR1_V')) EQ 'vomeeftr' THEN BEGIN
+   IF strlowcase(V1.unit) EQ 'm3/s' THEN BEGIN ; test on unit to understand if it is a transport or velocity
+     ;IF it is a transport it is transofrmed in velocity
+     V1.arr = V1.arr / e3v_3d(/e1) * vmask()
+     V1.unit = 'm/s'
+   ENDIF 
+   IF std_file2_V NE std_file1_V THEN BEGIN
+     V2 = read_ncdf(getenv('VAR2_V'), allrecords = allrec, direc = 't', filename = std_file2_V )
+     ; old formulation
+     ; IF strlowcase(getenv('VAR2_V')) EQ 'vocetr_eff' OR strlowcase(getenv('VAR2_V')) EQ 'vozoeftr' THEN BEGIN
+     IF strlowcase(V2.unit) EQ 'm3/s' THEN BEGIN 
+       V2.arr = V2.arr / e3v_3d(/e1) * vmask()
+       V2.unit = 'm/s'
+     ENDIF 
+   ENDIF ELSE V2 = {arr:-1}
+
+; ice
+  Ithi_1 = read_ncdf(getenv('VAR1_Ithick'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  april = where(mm EQ 4, cnt)
+  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)
+  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
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Ithi_2 = read_ncdf(getenv('VAR2_Ithick'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     april = where(mm EQ 4, cnt)
+     Ithi_april_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     jan = where(mm EQ 1, cnt)
+     sept = where(mm EQ 9, cnt)
+     Ithi_sept_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     Ithi_jan_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     undefine, Ithi_2
+  ENDIF ELSE BEGIN 
+     Ithi_april_2 = {arr:-1}
+     Ithi_sept_2 = {arr:-1}
+     Ithi_jan_2 = {arr:-1}
+  ENDELSE
+;
+  Iage_1 = read_ncdf(getenv('VAR1_Iage'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  Iage_febr_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  march = where(mm EQ 3, cnt)
+  Iage_march_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  sept = where(mm EQ 9, cnt)
+  Iage_sept_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_1.unit} 
+  undefine, Iage_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Iage_2 = read_ncdf(getenv('VAR2_Iage'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Iage_febr_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     march = where(mm EQ 3, cnt)
+     Iage_march_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     sept = where(mm EQ 9, cnt)
+     Iage_sept_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     undefine, Iage_2
+  ENDIF ELSE BEGIN 
+     Iage_febr_2 = {arr:-1}
+     Iage_march_2 = {arr:-1}
+     Iage_sept_2 = {arr:-1}
+  ENDELSE
+;
+  Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  Ifra_febr_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  march = where(mm EQ 3, cnt)
+  Ifra_march_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  sept = where(mm EQ 9, cnt)
+  Ifra_sept_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_1.unit}
+  undefine, Ifra_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+    Ifra_2 = read_ncdf(getenv('VAR2_Ifrac'), allrecords = allrec, filename = std_file2_I ) 
+    caldat, time, mm
+    febr = where(mm EQ 2, cnt)
+    Ifra_febr_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    march = where(mm EQ 3, cnt)
+    Ifra_march_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    sept = where(mm EQ 9, cnt)
+    Ifra_sept_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    undefine, Ifra_2
+  ENDIF ELSE BEGIN 
+    Ifra_febr_2 = {arr:-1}
+    Ifra_march_2 = {arr:-1}
+    Ifra_sept_2 = {arr:-1}
+  ENDELSE
+;
+   Isnow_1 = read_ncdf(getenv('VAR1_Isnow'), allrecords = allrec, filename = std_file1_I ) 
+   caldat, time, mm
+   febr = where(mm EQ 2, cnt)
+   Isnow_febr_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   march = where(mm EQ 3, cnt)
+   Isnow_march_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isnow_sept_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_1.unit}
+   ;undefine, Isnow_1
+ ;
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     Isnow_2 = read_ncdf(getenv('VAR2_Isnow'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Isnow_febr_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     march = where(mm EQ 3, cnt)
+     Isnow_march_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isnow_sept_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+   ;  undefine, Isnow_2
+   ENDIF ELSE BEGIN 
+     Isnow_febr_2 = {arr:-1}
+     Isnow_march_2 = {arr:-1}
+     Isnow_sept_2 = {arr:-1}
+   ENDELSE
+;
+   Isal_1 = read_ncdf(getenv('VAR1_Isal'), allrecords = allrec, filename = std_file1_I ) 
+   Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I )
+   msk = Ifra_1.arr gt 0.15 ; remove 0.15% for observations 
+   caldat, time, mm
+   march = where(mm EQ 3, cnt)
+   febr = where(mm EQ 2, cnt)
+   ;SF  Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   Isal_1.arr = Isal_1.arr * msk
+   Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   Isal_febr_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isal_sept_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_1.unit}
+   ;undefine, Isal_1
+ ;
+   Isal_2 = read_ncdf(getenv('VAR2_Isal'), allrecords = allrec, filename = std_file2_I ) 
+   Ifra_2 = read_ncdf(getenv('VAR2_Ifrac'), allrecords = allrec, filename = std_file2_I )
+   msk = Ifra_2.arr gt 0.15 ; remove 0.15% for observations 
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     Isal_2 = read_ncdf(getenv('VAR2_Isal'), allrecords = allrec, filename = std_file2_I ) 
+     Isal_2.arr = Isal_2.arr * msk
+     caldat, time, mm
+     march = where(mm EQ 3, cnt)
+     febr = where(mm EQ 2, cnt)
+     Isal_march_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     Isal_febr_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isal_sept_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+   ;  undefine, Isal_2
+   ENDIF ELSE BEGIN 
+     Isal_febr_2 = {arr:-1}
+     Isal_march_2 = {arr:-1}
+     Isal_sept_2 = {arr:-1}
+   ENDELSE
+;
+  jpt = 1
+;
+; shorter file names for legends...
+;
+  std_file1_T = file_basename(std_file1_T,'.nc')
+  std_file1_T = (strsplit(std_file1_T,'_grid_T',/extract,/regex))[0]
+  std_file2_T = file_basename(std_file2_T,'.nc')
+  std_file2_T = (strsplit(std_file2_T,'_grid_T',/extract,/regex))[0]
+  std_file1_U = file_basename(std_file1_U,'.nc')
+  std_file1_U = (strsplit(std_file1_U,'_grid_U',/extract,/regex))[0]
+  std_file2_U = file_basename(std_file2_U,'.nc')
+  std_file2_U = (strsplit(std_file2_U,'_grid_U',/extract,/regex))[0]
+  std_file1_V = file_basename(std_file1_V,'.nc')
+  std_file1_V = (strsplit(std_file1_V,'_grid_V',/extract,/regex))[0]
+  std_file2_V = file_basename(std_file2_V,'.nc')
+  std_file2_V = (strsplit(std_file2_V,'_grid_V',/extract,/regex))[0]
+  std_file1_I = file_basename(std_file1_I,'.nc')
+  std_file1_I = (strsplit(std_file1_I,'_icemod',/extract,/regex))[0]
+  std_file2_I = file_basename(std_file2_I,'.nc')
+  std_file2_I = (strsplit(std_file2_I,'_icemod',/extract,/regex))[0]
+
+;#########################################################################
+;######################  STANDARD PLOTS   ################################
+;#########################################################################
+
+  IF keyword_set(doplot) EQ 0 THEN doplot = 0
+
+; fixed color tabled
+  lct, 64
+  cnt = 0
+  htmltxt = ''
+;
+  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
+;
+  cnt = cnt+1   &   blabla = 'Net heat flux'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_qnet, Q1, Q2, QNET, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Meridionnal Heat Transport'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mht, Q1.arr+geo, Q2.arr+geo, masknp, std_file_msksub, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Global Barotropic stream Function'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_bsf, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with New Reynolds'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sst, T1, T2, TRey, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sss, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, _extra = ex       
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, /z100, _extra = ex       
+; 
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2 at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, /z100, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_T100m, T1, T2, Tlev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_S100m, S1, S2, SLev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Mixed layer depth'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD1, MLD, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mixed layer depth differences'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD1, MLD2, MLD, _extra = ex
+;
+  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
+;  
+  cnt = cnt+1   &   blabla = 'Vertical Global mean T & S'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_GlobMeanTS, T1, T2, TLev, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Atl', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Ind', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Pac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Atl', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Ind', _extra = ex 
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Pac', _extra = ex 
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Global (no Med)'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'GloNoMed', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Atl', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Ind', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indo-Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'IndoPac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Temperature'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqT, T1, T2, Tlev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Salinity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqS, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial zonal velocity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqU, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=700'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 700, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=1000'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 1000, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=40°N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 40, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=38°N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 38, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: JAN'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_jan_1, Ithi_jan_2, /ARC, /JAN, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, /ARC, /APRIL, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, /ANT, /APRIL, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_sept_1, Ithi_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, /ARC, /MARCH, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_febr_1, Iage_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_march_1, Isnow_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_febr_1, Isnow_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, /ANT, /SEPT, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_march_1, Isal_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: FEBRUARY'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_febr_1, Isal_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, /ANT, /SEPT, _extra = ex
+; 
+ 
+  IF n_elements(htmltxt) GT 1 THEN putfile, psdir+'std_plot_html_body.txt', htmltxt[1:*]
+  
+  return
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_last_year_5D.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_last_year_5D.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_all_last_year_5D.pro	(revision 14097)
@@ -0,0 +1,531 @@
+pro std_plot_all_last_year_5D, doplot = doplot, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common
+@std_common
+                                ; scripts for nemo v3_2 and v3_3
+
+;; script for max MLD, output 5 days
+
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+  PRINT, '                    LAUNCH of std_plots_last_year_5D'
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+;
+  std_iodir_data    = isadirectory(getenv('DIR_DATA'),     title = 'path of data in NetCdf format')
+  std_iodir_climato = isadirectory(getenv('DIR_CLIMATO'),  title = 'path of climatological data')
+  std_iodir_mask    = isadirectory(getenv('DIR_MASK'),     title = 'path of mask files (ex: subbasins)')
+; meshmask
+  std_file_mesh = isafile(getenv('FILE_MESH_MASK'),        title = 'mesh_mask', iodir = std_iodir_mask)
+  std_file_msksub = isafile(getenv('FILE_MASK_SUBDOMAIN'), title = 'sub-bassin masks', iodir = std_iodir_mask)
+
+; climatologies
+  std_file_Levitus_T =  isafile(getenv('FILE_TEMP_3D'),    title = 'Levitus_T', iodir = std_iodir_climato)
+  std_file_Levitus_S =  isafile(getenv('FILE_SAL_3D'),     title = 'Levitus_S', iodir = std_iodir_climato)
+  std_file_reynolds  =  isafile(getenv('FILE_SST'),        title = 'Reynolds', iodir = std_iodir_climato)
+  std_file_oaflux    =  isafile(getenv('FILE_FLUX'),       title = 'oaflux', iodir = std_iodir_climato)
+  std_file_mld       =  isafile(getenv('FILE_MLD'),        title = 'Mixed layer depth', iodir = std_iodir_climato)
+  std_file_ice       =  isafile(getenv('FILE_ICE'),        title = 'ICE', iodir = std_iodir_climato)
+  std_file_snow_arc  =  isafile(getenv('FILE_SNOW_ARC'),   title = 'SNOW_ARC', iodir = std_iodir_climato)
+  std_file_snow_ant  =  isafile(getenv('FILE_SNOW_ANT'),   title = 'SNOW_ANT', iodir = std_iodir_climato)
+
+  IF strlowcase(getenv('FILE_GEOHEAT')) EQ 'no' THEN std_file_geoheat = 'no' $
+  ELSE std_file_geoheat =  isafile(getenv('FILE_GEOHEAT'), title = 'Geothermal heating', iodir = std_iodir_climato)
+;
+  allrec =  1 - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+; Output run experience1
+  std_file1_T     = isafile(getenv('FILE1_T'), title = 'exp1 grid T input file', iodir = std_iodir_data)
+  std_file1_U     = isafile(getenv('FILE1_U'), title = 'exp1 grid U input file', iodir = std_iodir_data)
+  std_file1_V     = isafile(getenv('FILE1_V'), title = 'exp1 grid V input file', iodir = std_iodir_data)
+  std_file1_I     = isafile(getenv('FILE1_I'), title = 'exp1 ice    input file', iodir = std_iodir_data)
+  
+; Output run experience2
+  std_file2_T     = isafile(getenv('FILE2_T'), title = 'exp2 grid T input file', iodir = std_iodir_data)
+  std_file2_U     = isafile(getenv('FILE2_U'), title = 'exp2 grid U input file', iodir = std_iodir_data)
+  std_file2_V     = isafile(getenv('FILE2_V'), title = 'exp2 grid V input file', iodir = std_iodir_data)
+  std_file2_I     = isafile(getenv('FILE2_I'), title = 'exp2 ice    input file', iodir = std_iodir_data)
+
+  PRINT, ''
+  PRINT, '	std_iodir_data : ' + std_iodir_data 
+  PRINT, '	std_file1T : ' + std_file1_T
+  PRINT, '	std_file1U : ' + std_file1_U
+  PRINT, '	std_file1V : ' + std_file1_V
+;  PRINT, '	std_file1W : ' + std_file1_W
+  PRINT, '	std_file2I : ' + std_file1_I
+  PRINT, '	std_file2T : ' + std_file2_T
+  PRINT, '	std_file2U : ' + std_file2_U
+  PRINT, '	std_file2V : ' + std_file2_V
+;  PRINT, '	std_file2W : ' + std_file2_W
+  PRINT, '	std_file2I : ' + std_file2_I
+  PRINT, ''
+
+;#########################################################################
+;##########################  Load Grids   ################################
+;#########################################################################
+; load the grid
+  load_orca, std_file_mesh  
+; reading variables
+  masknp = read_ncdf('tmaskutil', file = std_file_mesh, /nostruct, /cont_nofill)
+;#########################################################################
+;############################  Read Data  ################################
+;#########################################################################
+;
+  allrec =  1; - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+;
+;;; 3D ;;;
+; temperature
+  T1 = read_ncdf(getenv('VAR1_T'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    T2 = read_ncdf(getenv('VAR2_T'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE T2 = {arr:-1}
+  TLev = read_ncdf(getenv('VAR_TEMP_3D'), filename = std_file_Levitus_T ) 
+  TRey = read_ncdf(getenv('VAR_SST'), filename = std_file_reynolds ) 
+
+; salinity
+  S1 = read_ncdf(getenv('VAR1_S'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    S2 = read_ncdf(getenv('VAR2_S'), allrecords = allrec, direc = 't', filename = std_file2_T ) 
+  ENDIF ELSE S2 = {arr:-1}
+  SLev = read_ncdf(getenv('VAR_SAL_3D'), filename = std_file_Levitus_S ) 
+
+;;; 2D ;;;
+; Net Downward heat flux
+  Q1 = read_ncdf(getenv('VAR1_QNET'), allrecords = allrec, direc = 't', filename = std_file1_T ) 
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    Q2 = read_ncdf(getenv('VAR2_QNET'), allrecords = allrec, direc = 't', filename = std_file2_T )
+  ENDIF ELSE Q2 = {arr:-1}
+; Geothermal heating
+  IF std_file_geoheat EQ 'no' THEN geo = {arr:float(getenv('VAR_GEOHEAT'))} $
+  ELSE geo = read_ncdf(getenv('VAR_GEOHEAT'), filename =  std_file_geoheat )
+  geo = geo.arr*1.e-3          ; convert into W/m2
+;climatology 
+  QNET = read_ncdf(getenv('VAR_FLUX'), filename = std_file_oaflux )
+
+; erp (evaporation damping)
+  ERP1 = read_ncdf(getenv('VAR1_ERP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  ERP1 = {arr:ERP1.arr * 86400., unit:'mm/day', grid:'T'}
+  IF std_file2_T NE std_file1_T THEN BEGIN
+     ERP2 = read_ncdf(getenv('VAR2_ERP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+     ERP2 = {arr:ERP2.arr * 86400., unit:'mm/day', grid:'T'}
+  ENDIF ELSE ERP2 = {arr:-1}
+ 
+; emp (evaporation minus precipitation)
+  EMP1 = read_ncdf(getenv('VAR1_EMP'), allrecords = allrec, direc = 't', filename = std_file1_T )
+  EMP1 = {arr:EMP1.arr * 86400., unit:'mm/day', grid:'T'}
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    EMP2 = read_ncdf(getenv('VAR2_EMP'), allrecords = allrec, direc = 't', filename = std_file2_T )
+    EMP2 = {arr:EMP2.arr * 86400., unit:'mm/day', grid:'T'}
+  ENDIF ELSE EMP2 = {arr:-1}
+  
+  ;mixed layer depth
+  ;; nyear=jpt/73
+  MLD_1 = read_ncdf(getenv('VAR1_MLD'), allrecords = allrec, filename = std_file1_T ) 
+  caldat, time, mm
+  march = where(mm EQ 3, cnt)
+  MLD_march_1 = max(MLD_1.arr[*,*,march], dim=3)
+  MLD_march_1 = {arr: MLD_march_1, unit: MLD_1.unit}
+  sept = where(mm EQ 9, cnt)
+  MLD_sept_1 = max(MLD_1.arr[*,*,sept], dim=3) 
+  MLD_sept_1 = {arr: MLD_sept_1, unit: MLD_1.unit}
+  MLD_1 = {arr: max(MLD_1.arr[*,*,*], dim=3), unit: MLD_1.unit}
+  IF std_file2_T NE std_file1_T THEN BEGIN
+    MLD_2 = read_ncdf(getenv('VAR2_MLD'), allrecords = allrec, filename = std_file2_T ) ; 10 m
+    caldat, time, mm
+    march = where(mm EQ 3, cnt)
+    MLD_march_2 = max(MLD_2.arr[*,*,march], dim=3)
+    MLD_march_2 = {arr: MLD_march_2, unit: MLD_2.unit}
+    sept = where(mm EQ 9, cnt)
+    MLD_sept_2 = max(MLD_2.arr[*,*,sept], dim=3) 
+    MLD_sept_2 = {arr:MLD_sept_2, unit: MLD_2.unit}
+    MLD_2 = {arr: max(MLD_2.arr[*,*,*], dim=3), unit: MLD_2.unit}
+  ENDIF ELSE BEGIN
+    MLD_2 = {arr:-1}
+    MLD_march_2 = {arr:-1}
+    MLD_sept_2 = {arr:-1}
+  ENDELSE
+  
+  ;climatology 
+  MLD = read_ncdf(getenv('VAR_MLD'), filename = std_file_mld )
+; if monthly climatology
+;  MLD = {arr: max(MLD.arr[*,*,*], dim=3), unit: MLD.unit} 
+
+; velocities
+  U1 = read_ncdf(getenv('VAR1_U'), allrecords = allrec, direc = 't', filename = std_file1_U )
+  IF strlowcase(getenv('VAR1_U')) EQ 'uocetr_eff' THEN BEGIN
+    U1.arr = U1.arr / e3u_3d(/e2) * umask()
+    U1.unit = 'm/s'
+  ENDIF 
+  IF std_file2_U NE std_file1_U THEN BEGIN
+    U2 = read_ncdf(getenv('VAR2_U'), allrecords = allrec, direc = 't', filename = std_file2_U )
+    IF strlowcase(getenv('VAR2_U')) EQ 'uocetr_eff' THEN BEGIN
+      U2.arr = U2.arr / e3u_3d(/e2) * umask()
+      U2.unit = 'm/s'
+    ENDIF 
+  ENDIF ELSE U2 = {arr:-1}
+;
+  V1 = read_ncdf(getenv('VAR1_V'), allrecords = allrec, direc = 't', filename = std_file1_V )
+  IF strlowcase(getenv('VAR1_V')) EQ 'vocetr_eff' THEN BEGIN
+    V1.arr = V1.arr / e3v_3d(/e1) * vmask()
+    V1.unit = 'm/s'
+  ENDIF 
+  IF std_file2_V NE std_file1_V THEN BEGIN
+    V2 = read_ncdf(getenv('VAR2_V'), allrecords = allrec, direc = 't', filename = std_file2_V )
+    IF strlowcase(getenv('VAR2_V')) EQ 'vocetr_eff' THEN BEGIN
+      V2.arr = V2.arr / e3v_3d(/e1) * vmask()
+      V2.unit = 'm/s'
+    ENDIF 
+  ENDIF ELSE V2 = {arr:-1}
+
+; ice
+  Ithi_1 = read_ncdf(getenv('VAR1_Ithick'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  april = where(mm EQ 4, cnt)
+  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)
+  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
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Ithi_2 = read_ncdf(getenv('VAR2_Ithick'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     april = where(mm EQ 4, cnt)
+     Ithi_april_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     jan = where(mm EQ 1, cnt)
+     sept = where(mm EQ 9, cnt)
+     Ithi_sept_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     Ithi_jan_2 = {arr:1./float(cnt) * total(reform(Ithi_2.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ithi_2.unit} 
+     undefine, Ithi_2
+  ENDIF ELSE BEGIN 
+     Ithi_april_2 = {arr:-1}
+     Ithi_sept_2 = {arr:-1}
+     Ithi_jan_2 = {arr:-1}
+  ENDELSE
+;
+  Iage_1 = read_ncdf(getenv('VAR1_Iage'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  Iage_febr_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  march = where(mm EQ 3, cnt)
+  Iage_march_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_1.unit}
+  sept = where(mm EQ 9, cnt)
+  Iage_sept_1 = {arr:1./float(cnt) * total(reform(Iage_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_1.unit} 
+  undefine, Iage_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+     Iage_2 = read_ncdf(getenv('VAR2_Iage'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Iage_febr_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     march = where(mm EQ 3, cnt)
+     Iage_march_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     sept = where(mm EQ 9, cnt)
+     Iage_sept_2 = {arr:1./float(cnt) * total(reform(Iage_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Iage_2.unit} 
+     undefine, Iage_2
+  ENDIF ELSE BEGIN 
+     Iage_febr_2 = {arr:-1}
+     Iage_march_2 = {arr:-1}
+     Iage_sept_2 = {arr:-1}
+  ENDELSE
+;
+  Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I ) 
+  caldat, time, mm
+  febr = where(mm EQ 2, cnt)
+  Ifra_febr_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  march = where(mm EQ 3, cnt)
+  Ifra_march_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_1.unit} 
+  sept = where(mm EQ 9, cnt)
+  Ifra_sept_1 = {arr:1./float(cnt) * total(reform(Ifra_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_1.unit}
+  undefine, Ifra_1
+;
+  IF std_file2_I NE std_file1_I THEN BEGIN
+    Ifra_2 = read_ncdf(getenv('VAR2_Ifrac'), allrecords = allrec, filename = std_file2_I ) 
+    caldat, time, mm
+    febr = where(mm EQ 2, cnt)
+    Ifra_febr_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    march = where(mm EQ 3, cnt)
+    Ifra_march_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    sept = where(mm EQ 9, cnt)
+    Ifra_sept_2 = {arr:1./float(cnt) * total(reform(Ifra_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ifra_2.unit}
+    undefine, Ifra_2
+  ENDIF ELSE BEGIN 
+    Ifra_febr_2 = {arr:-1}
+    Ifra_march_2 = {arr:-1}
+    Ifra_sept_2 = {arr:-1}
+  ENDELSE
+;
+   Isnow_1 = read_ncdf(getenv('VAR1_Isnow'), allrecords = allrec, filename = std_file1_I ) 
+   caldat, time, mm
+   febr = where(mm EQ 2, cnt)
+   Isnow_febr_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   march = where(mm EQ 3, cnt)
+   Isnow_march_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isnow_sept_1 = {arr:1./float(cnt) * total(reform(Isnow_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_1.unit}
+   ;undefine, Isnow_1
+ ;
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     Isnow_2 = read_ncdf(getenv('VAR2_Isnow'), allrecords = allrec, filename = std_file2_I ) 
+     caldat, time, mm
+     febr = where(mm EQ 2, cnt)
+     Isnow_febr_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     march = where(mm EQ 3, cnt)
+     Isnow_march_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isnow_sept_2 = {arr:1./float(cnt) * total(reform(Isnow_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isnow_2.unit}
+   ;  undefine, Isnow_2
+   ENDIF ELSE BEGIN 
+     Isnow_febr_2 = {arr:-1}
+     Isnow_march_2 = {arr:-1}
+     Isnow_sept_2 = {arr:-1}
+   ENDELSE
+;
+   Isal_1 = read_ncdf(getenv('VAR1_Isal'), allrecords = allrec, filename = std_file1_I ) 
+   Ifra_1 = read_ncdf(getenv('VAR1_Ifrac'), allrecords = allrec, filename = std_file1_I )
+   msk = Ifra_1.arr gt 0.15 ; remove 0.15% for observations 
+   caldat, time, mm
+   march = where(mm EQ 3, cnt)
+   febr = where(mm EQ 2, cnt)
+   ;SF  Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   Isal_1.arr = Isal_1.arr * msk
+   Isal_march_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   Isal_febr_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_1.unit} 
+   sept = where(mm EQ 9, cnt)
+   Isal_sept_1 = {arr:1./float(cnt) * total(reform(Isal_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_1.unit}
+   ;undefine, Isal_1
+ ;
+   Isal_2 = read_ncdf(getenv('VAR2_Isal'), allrecords = allrec, filename = std_file2_I ) 
+   Ifra_2 = read_ncdf(getenv('VAR2_Ifrac'), allrecords = allrec, filename = std_file2_I )
+   msk = Ifra_2.arr gt 0.15 ; remove 0.15% for observations 
+   IF std_file2_I NE std_file1_I THEN BEGIN
+     Isal_2 = read_ncdf(getenv('VAR2_Isal'), allrecords = allrec, filename = std_file2_I ) 
+     Isal_2.arr = Isal_2.arr * msk
+     caldat, time, mm
+     march = where(mm EQ 3, cnt)
+     febr = where(mm EQ 2, cnt)
+     Isal_march_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(march)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     Isal_febr_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(febr)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+     sept = where(mm EQ 9, cnt)
+     Isal_sept_2 = {arr:1./float(cnt) * total(reform(Isal_2.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Isal_2.unit}
+   ;  undefine, Isal_2
+   ENDIF ELSE BEGIN 
+     Isal_febr_2 = {arr:-1}
+     Isal_march_2 = {arr:-1}
+     Isal_sept_2 = {arr:-1}
+   ENDELSE
+;
+  jpt = 1
+;
+; shorter file names for legends...
+;
+  std_file1_T = file_basename(std_file1_T,'.nc')
+  std_file1_T = (strsplit(std_file1_T,'_grid_T',/extract,/regex))[0]
+  std_file2_T = file_basename(std_file2_T,'.nc')
+  std_file2_T = (strsplit(std_file2_T,'_grid_T',/extract,/regex))[0]
+  std_file1_U = file_basename(std_file1_U,'.nc')
+  std_file1_U = (strsplit(std_file1_U,'_grid_U',/extract,/regex))[0]
+  std_file2_U = file_basename(std_file2_U,'.nc')
+  std_file2_U = (strsplit(std_file2_U,'_grid_U',/extract,/regex))[0]
+  std_file1_V = file_basename(std_file1_V,'.nc')
+  std_file1_V = (strsplit(std_file1_V,'_grid_V',/extract,/regex))[0]
+  std_file2_V = file_basename(std_file2_V,'.nc')
+  std_file2_V = (strsplit(std_file2_V,'_grid_V',/extract,/regex))[0]
+  std_file1_I = file_basename(std_file1_I,'.nc')
+  std_file1_I = (strsplit(std_file1_I,'_icemod',/extract,/regex))[0]
+  std_file2_I = file_basename(std_file2_I,'.nc')
+  std_file2_I = (strsplit(std_file2_I,'_icemod',/extract,/regex))[0]
+
+;#########################################################################
+;######################  STANDARD PLOTS   ################################
+;#########################################################################
+
+  IF keyword_set(doplot) EQ 0 THEN doplot = 0
+
+; fixed color tabled
+  lct, 64
+  cnt = 0
+  htmltxt = ''
+;
+  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
+;
+  cnt = cnt+1   &   blabla = 'Net heat flux'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_qnet, Q1, Q2, QNET, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Meridionnal Heat Transport'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mht, Q1.arr+geo, Q2.arr+geo, masknp, std_file_msksub, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Global Barotropic stream Function'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_bsf, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with New Reynolds'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sst, T1, T2, TRey, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_sss, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, _extra = ex       
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, SLev, /z100, _extra = ex       
+; 
+  cnt = cnt+1   &   blabla = 'Arctic mean Salinity diff with Levitus and exp2 at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ArcSal, S1, S2, SLev, /z100, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'mean Temperature diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_T100m, T1, T2, Tlev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'mean Salinity diff with Levitus at z=100 meters'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_S100m, S1, S2, SLev, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Mixed layer depth'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD1, MLD, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mixed layer depth differences'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD_1, MLD_2, MLD, _extra = ex
+
+  ;SF: add 2 cases for max of Mixed Layer depth on march & septembre
+  cnt = cnt+1   &   blabla = 'Mixed layer depth on March'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_max_mld, MLD_march_1, MLD_march_2, /MARCH, _extra = ex
+
+  cnt = cnt+1   &   blabla = 'Mixed layer depth on September'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_max_mld, MLD_sept_1, MLD_sept_2, /SEPT, _extra = ex
+
+;; SF: commented because not ok for max MLD, output 5 days
+;; cnt = cnt+1   &   blabla = 'Zonal mean Mixed layer depth'
+;; IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ZonMld, MLD_1, MLD_2, MLD, _extra = ex
+  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Atl', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Ind', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Zonal mean Temperature diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_T, T1, T2, TLev, SUBBASIN = 'Pac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Global'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Atl', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Ind', _extra = ex 
+;
+  cnt = cnt+1   &   blabla = 'Zonal mean Salinity diff with Levitus: Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_zonal_S, S1, S2, SLev, SUBBASIN = 'Pac', _extra = ex 
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Global (no Med)'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'GloNoMed', _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Atlantic'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Atl', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indian'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'Ind', _extra = ex
+ ;
+  cnt = cnt+1   &   blabla = 'Meridional stream Function: Indo-Pacific'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_msf, V1, V2, SUBBASIN = 'IndoPac', _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Temperature'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqT, T1, T2, Tlev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial Salinity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqS, S1, S2, SLev, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Equatorial zonal velocity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_EqU, U1, U2, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=700'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 700, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean salt tongue at depth=1000'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sspread, S1, S2, SLev, 1000, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=40°N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 40, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Mediterranean water at lat=38°N'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_Med_Sdepth, S1, S2, SLev, 38, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: JAN'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_jan_1, Ithi_jan_2, /ARC, /JAN, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, /ARC, /APRIL, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: APRIL'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_april_1, Ithi_april_2, /ANT, /APRIL, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceThick, Ithi_sept_1, Ithi_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, /ARC, /MARCH, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_febr_1, Iage_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Age: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_sept_1, Iage_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Arctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_febr_1, Ifra_febr_2, /ANT, /FEBR, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Fraction: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceFrac, Ifra_sept_1, Ifra_sept_2, /ANT, /SEPT, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_march_1, Isnow_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_febr_1, Isnow_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic SNOW Thickness: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_SnowThick, Isnow_sept_1, Isnow_sept_2, /ANT, /SEPT, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: MARCH'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_march_1, Isal_march_2, /ARC, /MARCH, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Arctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, /ARC, /SEPT, _extra = ex
+;  
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: FEBRUARY'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_febr_1, Isal_febr_2, /ANT, /FEBR, _extra = ex
+; 
+  cnt = cnt+1   &   blabla = 'Antarctic Ice Salinity: SEPT'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceSal, Isal_sept_1, Isal_sept_2, /ANT, /SEPT, _extra = ex
+; 
+ 
+  IF n_elements(htmltxt) GT 1 THEN putfile, psdir+'std_plot_html_body.txt', htmltxt[1:*]
+  
+  return
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_bsf.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_bsf.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_bsf.pro	(revision 14097)
@@ -0,0 +1,40 @@
+pro std_plot_bsf, U1, U2, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_BSF_'+std_file1_U
+  if std_file1_U NE std_file2_U then filename = filename + '_'+std_file2_U
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  domdef, 0, 6000
+
+  ;formulation for variable: TRANSPORT
+  ;bb1 = bsf(U1.arr, refvalue = 0., refpoint = [25, 0], /transport )
+  ;
+  ;formulation for variable: VELOCITY
+  bb1 = bsf(U1.arr, refvalue = 0., refpoint = [25, 0])
+  title = 'Barotropic Stream Function!C'+std_file1_U
+  plt, bb1, min = -200., max = 200., int = 10., /portrait, FORMAT = '(I4)', STYLE = 'so0so' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title,  _extra = ex
+
+  if std_file1_U NE std_file2_U then BEGIN
+    ;formulation for variable: TRANSPORT
+    ;bb2 = bsf(U2.arr, refvalue = 0., refpoint = [25, 0], /transport )
+    ;formulation for variable: VELOCITY
+    bb2 = bsf(U2.arr, refvalue = 0., refpoint = [25, 0] )
+    title = 'Barotropic Stream Function!C'+std_file1_U+' - '+std_file2_U
+    plt, bb1.arr - bb2.arr, min = -20., max = 20., int = 2.,  FORMAT = '(I2)', STYLE = 'so0so' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /NOERASE, _extra = ex
+  endif
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_emp.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_emp.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_emp.pro	(revision 14097)
@@ -0,0 +1,29 @@
+pro std_plot_emp, EMP1, EMP2, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_Emp_'+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
+  
+  title = 'Emp!C'+std_file1_T
+  plt, EMP1,  MIN = -10., MAX = 10., INTER = 1., style = 'so0so' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, format = '(i3)', /PORTRAIT, _extra = ex
+  
+  if std_file1_T NE std_file2_T then begin
+    title = title+' - '+std_file2_T
+    plt, EMP1.arr - EMP2.arr, MIN = -5., MAX = 5., INTER = 1., style = 'so0so' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, format = '(i3)', /NOERASE, _extra = ex
+  endif
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_erp.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_erp.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_erp.pro	(revision 14097)
@@ -0,0 +1,29 @@
+pro std_plot_erp, ERP1, ERP2, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_Erp_'+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
+  
+  title = 'Erp!C'+std_file1_T
+  plt, ERP1,  MIN = -5., MAX = 5., INTER = .5, style = 'so0so' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /PORTRAIT, format = '(i2)', _extra = ex
+  
+  if std_file1_T NE std_file2_T then begin
+    title = title+' - '+std_file2_T
+    plt, ERP1.arr - ERP2.arr, MIN = -2., MAX = 2., INTER = .25, style = 'so0so' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, format = '(f4.1)', /NOERASE, _extra = ex
+  endif
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_max_mld.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_max_mld.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_max_mld.pro	(revision 14097)
@@ -0,0 +1,70 @@
+pro std_plot_max_mld, MLD1, MLD2, MARCH = march, SEPT = sept, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  
+  var = 'max_MLD'
+  IF keyword_set(march) THEN var = var+'_March'
+  IF keyword_set(sept) THEN var = var+'_Sept'
+  
+  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
+;
+  varunit = MLD1.unit
+  titleorg =  var+'!C'
+;
+;;   IF MLD2.arr[0] NE -1  THEN BEGIN
+;;     title = titleorg+std_file1_T+ ' - '+std_file2_T
+;;     plt, MLD1.arr - MLD2.arr, MIN = -80., MAX = 80., INTER = 10., FORMAT = '(I3)'  $
+;;          , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /NOCONTOUR, /PORTRAIT, _extra = ex
+;;   ENDIF ELSE BEGIN 
+;;     title = titleorg+std_file1_T
+;;     plt, MLD1,label=4, cb_label=[0, 15, 25, 50, 75, 100, 125, 150, 250, 400, 600, 850],/NOCONTOUR,FORMAT = '(I3)' $
+;;        , small = [1, 2, 1],COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+;;  ;
+;;  ;ORI SF    plt, MLD1, MIN = 0., MAX = 500., INTER = 25., /NOCONTOUR, FORMAT = '(I3)' $
+;;  ;ORI SF         , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+;;  ;
+;;    ENDELSE 
+;
+
+   IF MLD2.arr[0] NE -1  THEN BEGIN
+     title = titleorg+ std_file2_T
+     ; plt, MLD2.arr, MIN = 0., MAX = 800., INTER = 50., FORMAT = '(I3)'  $
+     plt, MLD2.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, /NOCONTOUR, /PORTRAIT, _extra = ex   
+     ;
+     title = titleorg+std_file1_T+ ' - '+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, /NOCONTOUR, /PORTRAIT, _extra = ex
+   ENDIF ELSE BEGIN 
+     title = titleorg+std_file1_T
+     plt, MLD1,label=4, cb_label=[0, 15, 25, 50, 75, 100, 125, 150, 250, 400, 600, 850],/NOCONTOUR,FORMAT = '(I3)' $
+        , small = [1, 2, 1],COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+   ENDELSE
+
+
+  
+;;  IF MLD2.arr[0] NE -1  THEN BEGIN
+;;    title = titleorg+std_file2_T+ ' - DeBoyer'
+;;    tmp = MLD2.arr - MLD.arr
+;;  ENDIF ELSE BEGIN 
+;;    title = titleorg+std_file1_T+ ' - DeBoyer'
+;;    tmp = MLD1.arr - MLD.arr
+;;  ENDELSE
+;;  plt, temporary(tmp), MIN = -80., MAX = 80., INTER = 10., FORMAT = '(I3)'  $
+;;       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /NOCONTOUR, /NOERASE, _extra = ex
+;  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+;
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mht.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mht.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mht.pro	(revision 14097)
@@ -0,0 +1,89 @@
+PRO std_plot_domht, Q, masknp, mask_filename, ibce, htr, htr_atl
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+
+  Qave = moyenne(Q, 'xy', mask2d = masknp) ; mean value
+  Qnet = Q - Qave
+  ibce = STRTRIM(Qave, 1)
+; 
+  msk = read_ncdf('atlmsk_nomed', filename = mask_filename, /nostruct)
+  msk = msk[*]#replicate(1., nzt) ; from 2D array to 3D array 
+                                
+; *1.E-15 to have PetaWatt
+  Qx     = moyenne(Qnet*e2t    , 'x', mask2d = masknp, /integration)*1.E-15
+  Qx_atl = moyenne(Qnet*e2t*msk, 'x', mask2d = masknp, /integration)*1.E-15
+; northward heat flux transport from antartic  
+  htr     = total(Qx, /cumulative)
+  htr_atl = total(reverse(Qx_atl), /cumulative) ; ! from north to south
+  htr_atl = -reverse(htr_atl)
+; we take from values north till 30° South
+  htr_atl[where(gphit[0, *] lt -30.)] = !Values.F_NaN 
+
+return
+END
+
+pro std_plot_mht, Q1, Q2, masknp, mask_filename, POSTSCRIPT = postscript,  _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_MHT_'+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
+  
+; find the x index with the highest latitude (for the plot)
+  index = where(gphit eq max(gphit))
+  nx = index[0] mod jpi
+  gphi_save = gphit
+  gphit[0, *] = gphit[nx, *]
+; compute meridional heat transport
+  std_plot_domht, Q1, masknp, mask_filename, ibce1, htr1, htr1_atl
+  
+; update data informations
+  varname = 'MHT'
+  varunit = 'Pw'
+  vargrid = 'T' 
+
+  title = 'MHT (Black) & Atlantic MHT (Blue)!C'+std_file1_T
+  subtitle = '(Qnet='+ibce1+' W/m2)'
+  plt1d, htr1, 'y', min = -2., max = 2.5, TITLE = title, SUBTITLE = subtitle, /portrait $ 
+         , SMALL = [2-(std_file1_T EQ std_file2_T), 2, 1], YTITLE = 'PW',  XGRIDSTYLE = 2, TICKLEN = 1, YGRIDSTYLE = 2, _extra = ex
+  plt1d, htr1_atl, 'y', COLOR = 50, /ov1d,  _extra = ex
+
+  if std_file1_T NE std_file2_T then begin
+; compute meridional heat transport
+    std_plot_domht, Q2, masknp, mask_filename, ibce2, htr2, htr2_atl
+
+    title = 'MHT (Black) & Atlantic MHT (Blue)!C'+std_file2_T
+    subtitle = '(Qnet='+ibce2+' W/m2)'
+    plt1d, htr2, 'y', min = -2., max = 2.5, TITLE = title, SUBTITLE = subtitle, /noerase $ 
+           , SMALL = [2, 2, 2], YTITLE = 'PW',  XGRIDSTYLE = 2, TICKLEN = 1, YGRIDSTYLE = 2, _extra = ex
+    plt1d, htr2_atl, 'y', COLOR = 50, /ov1d,  _extra = ex
+
+    title = 'MHT (Black) & Atlantic MHT (Blue) '+std_file1_T+' !C (Red) '+std_file2_T
+    plt1d, htr1, 'y', min = -2., max = 2., TITLE = title $
+           , SMALL = [2, 2, 3], TICKLEN = 1, XGRIDSTYLE = 2 $
+           , YTITLE = 'PW', YGRIDSTYLE = 2, /NOERASE, _extra = ex
+    plt1d, htr2, 'y', COLOR = 250, /ov1d,  _extra = ex
+    plt1d, htr1_atl, 'y', COLOR = 50, /ov1d,  _extra = ex
+    plt1d, htr2_atl, 'y', COLOR = 250, /ov1d,  _extra = ex
+    ;plt1d, (htr1-htr2)*1.e3, 'y', min = -250., max = 250., TITLE = title $
+    ;       , SMALL = [2, 2, 3], TICKLEN = 1, XGRIDSTYLE = 2 $
+    ;       , YTITLE = 'TW', YGRIDSTYLE = 2, /NOERASE, _extra = ex
+    ;plt1d, (htr1_atl - htr2_atl)*1.e3, 'y', COLOR = 50, /ov1d,  _extra = ex
+    
+  endif 
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  gphit = gphi_save
+  
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mld.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mld.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_mld.pro	(revision 14097)
@@ -0,0 +1,55 @@
+pro std_plot_mld, MLD1, MLD2in, MLDin, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  CASE n_params() OF
+    2:BEGIN
+      MLD = MLD2in
+    END
+    3:BEGIN
+      IF MLD2in.arr[0] EQ -1 THEN return
+      MLD2 = MLD2in
+      MLD = MLDin
+    END
+  ENDCASE
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_MLD_'+std_file1_T
+  IF keyword_set(MLD2) THEN filename = filename + '_' + std_file2_T
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  varunit = MLD1.unit
+  titleorg = 'MLD!C'
+;
+  IF keyword_set(MLD2) THEN BEGIN
+    title = titleorg+std_file1_T+ ' - '+std_file2_T
+    plt, MLD1.arr - MLD2.arr, MIN = -80., MAX = 80., INTER = 10., FORMAT = '(I3)'  $
+         , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /NOCONTOUR, /PORTRAIT, _extra = ex
+  ENDIF ELSE BEGIN 
+    title = titleorg+std_file1_T
+    plt, MLD1,label=4, cb_label=[0, 15, 25, 50, 75, 100, 125, 150, 250, 400, 600, 850],/NOCONTOUR,FORMAT = '(I3)' $
+            , small = [1, 2, 1],COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+;ORI SF    plt, MLD1, MIN = 0., MAX = 500., INTER = 25., /NOCONTOUR, FORMAT = '(I3)' $
+;ORI SF         , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex
+  ENDELSE 
+; 
+  IF keyword_set(MLD2) THEN BEGIN
+    title = titleorg+std_file2_T+ ' - DeBoyer'
+    tmp = MLD2.arr - MLD.arr
+  ENDIF ELSE BEGIN 
+    title = titleorg+std_file1_T+ ' - DeBoyer'
+    tmp = MLD1.arr - MLD.arr
+  ENDELSE
+  plt, temporary(tmp), MIN = -80., MAX = 80., INTER = 10., FORMAT = '(I3)'  $
+       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /NOCONTOUR, /NOERASE, _extra = ex
+;  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+;
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_msf.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_msf.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_msf.pro	(revision 14097)
@@ -0,0 +1,60 @@
+pro std_plot_msf, V1, V2, SUBBASIN = subbasin, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  if KEYWORD_SET(SUBBASIN) then subname = subbasin else subname = "Glo"
+  filename = cdti3 + '_MSF_'+subname+'_'+std_file1_V
+  if std_file1_V NE std_file2_V then filename = filename + '_'+std_file2_V
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  if KEYWORD_SET(SUBBASIN) then begin
+    CASE subname of 
+      'Atl' : var = 'atlmsk_nomed'
+      'Ind' : var = 'indmsk'
+      'IndoPac' : var = 'indpacmsk'
+      'GloNoMed' : var = 'glomsk_nomed'
+    ENDCASE
+    msk = read_ncdf( var, filename = std_file_msksub, /nostruct, _extra = ex )
+  endif else msk = tmask[*, *, 0]
+;
+  CASE subname OF
+    'GloNoMed':lat_ext = [-80, 90]
+    'Glo':lat_ext = [-80, 90]
+    'Atl':lat_ext = [-30, 90]
+    'Ind':lat_ext = [-30, 30]
+    'IndoPac':lat_ext = [-30, 70]
+  ENDCASE
+  
+  domdef, 0, 6000
+
+  ;formulation for variable: TRANSPORT
+  ;mm1 = msf(V1.arr, msk, indexboxzoom = ind, maskout = ma, /transport )
+  ;
+  ;formulation for variable: VELOCITY
+  mm1 = msf(V1.arr, msk, indexboxzoom = ind, maskout = ma )
+  title = 'Meridional Stream Function, '+subname+'!C'+std_file1_V
+  pltz, mm1, 'yz', -20., 20., int = 1., boxzoom = [ind[0:1], lat_ext, 0, 5500], /xindex, FORMAT = '(I3)', /portrait $
+        , small = [1, 2, 1], COAST_THICK = 2, zoom = 5500, maskdta = ma, /no_partial, TITLE = title, style = 'so0so'
+
+  if std_file1_V NE std_file2_V then begin
+    ;formulation for variable: TRANSPORT
+    ;mm2 = msf(V2.arr, msk, indexboxzoom = ind, maskout = ma, /transport )
+    ;
+    ;formulation for variable: VELOCITY
+    mm2 = msf(V2.arr, msk, indexboxzoom = ind, maskout = ma)
+    title = title+' - '+std_file2_V
+    pltz, mm1.arr-mm2.arr, 'yz', -10., 10., int = 1., boxzoom = [ind[0:1], lat_ext, 0, 5500], /xindex,  FORMAT = '(I3)'  $
+          , small = [1, 2, 2], COAST_THICK = 2, zoom = 5500, maskdta = ma, /no_partial, TITLE = title, /NOERASE, style = 'so0so'
+  endif
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_qnet.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_qnet.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_qnet.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_qnet,  Q1, Q2, QNET, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_Qnet_'+std_file1_T
+  if std_file1_T EQ std_file2_T then filename = filename + '_OAFlux' $
+  ELSE filename = filename + '_'+std_file2_T
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  title = 'Qnet!C'+std_file1_T
+  plt,  Q1,  MIN = -200., MAX = 200., INTER = 20., STYLE = 'so0so' $
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, FORMAT = '(I4)', /PORTRAIT, _extra = ex
+
+  if std_file1_T EQ std_file2_T then begin
+    title = 'Qnet!C'+std_file1_T+' - OAFlux'
+    Q = Q1.arr - QNET.arr
+  ENDIF ELSE BEGIN 
+    title = 'Qnet!C'+std_file1_T+' - '+std_file2_T
+    Q = Q1.arr - Q2.arr
+  ENDELSE 
+  plt, Q, MIN = -100, MAX = 100, INTER = 10, STYLE = 'so0so'  $
+       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, FORMAT = '(I4)', /NOERASE, _extra = ex
+                                ;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sss.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sss.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sss.pro	(revision 14097)
@@ -0,0 +1,34 @@
+pro std_plot_sss, S1, S2, SLev, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_SSS_'+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
+  
+  varunit = S1.unit  
+  
+  title = 'SSS!C'+std_file1_T
+  plt, S1.arr[*, *, 0], MIN = 33., MAX = 41., INTER = .25, format = '(f4.1)' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, /PORTRAIT, _extra = ex 
+                                ;
+  if std_file1_T NE std_file2_T then begin
+    title = 'SSS!C'+std_file1_T+' - '+std_file2_T
+    plt, S1.arr[*, *, 0] - S2.arr[*, *, 0], MIN = -2., MAX = 2., INTER = 0.2, STYLE = 'so0so' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /noerase, format = '(f4.1)', _extra = ex
+  endif else begin
+    title = 'SSS!C'+std_file1_T+' - Levitus'
+    plt, S1.arr[*, *, 0] - SLev.arr[*, *, 0], MIN = -3., MAX = 3., INTER = 0.2, STYLE = 'so0so' $
+         , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /noerase, format = '(f4.1)', _extra = ex
+  endelse
+                                ;
+   htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sst.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sst.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_sst.pro	(revision 14097)
@@ -0,0 +1,43 @@
+pro std_plot_sst, T1, T2, TRey, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_SST_'+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 std_file1_T EQ std_file2_T then begin
+    T = T1.arr[*, *, 0]
+    min = -2.
+    max = 32.
+    inter = 1. 
+    STYLE = 0
+    title = 'SST!C'+std_file1_T
+  ENDIF ELSE BEGIN 
+    T = T1.arr[*, *, 0] - T2.arr[*, *, 0]
+    min =  -1.
+    max = -min
+    inter = 0.1
+    STYLE = 'so0so'
+    title = 'SST!C'+std_file1_T+' - '+std_file2_T
+  ENDELSE 
+;
+  varunit = T1.unit
+; 
+  plt, T, MIN = min, MAX = max, INTER = inter, STYLE = STYLE $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, FORMAT = '(I2)', /PORTRAIT, _extra = ex
+; 
+  title = 'SST!C'+std_file1_T+' - NewReynolds'
+  plt, T1.arr[*, *, 0] - TRey.arr, MIN = -8., MAX = 8., INTER = 0.5, STYLE = 'so0so', FORMAT = '(I2)' $
+       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, /NOERASE, _extra = ex
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh	(revision 14097)
@@ -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 )/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/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=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=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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.last_year_5D
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.last_year_5D	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.last_year_5D	(revision 14097)
@@ -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 )/l3fwb178-plot_lastyear_ps
+PDF_DIR=$( pwd )/l3fwb178_plot_lastyear_pdf
+HTML_DIR=$( pwd )/html_plot
+SAXO_DIR=/Users/sflod/SAXO_DIR
+#
+DIR_DATA=~/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
+DIR_CLIMATO=~/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
+DIR_MASK=~//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=l3fwb178_25010101_25011231_5D_grid_T.nc   # exp1 grid T input file
+FILE1_U=l3fwb178_25010101_25011231_5D_grid_U.nc   # exp1 grid U input file
+FILE1_V=l3fwb178_25010101_25011231_5D_grid_V.nc   # exp1 grid V input file
+FILE1_I=l3fwb178_25010101_25011231_5D_icemod.nc   # exp1 ice    input file
+VAR1_T=votemper
+VAR1_S=vosaline
+VAR1_QNET=sohflxdo
+VAR1_ERP=sowafldp
+VAR1_EMP=sowaflup
+VAR1_MLD=max5dmld
+VAR1_U=vozoeftr
+VAR1_V=vomeeftr
+VAR1_Ithick=iicethic
+VAR1_Ifrac=iiceconc
+VAR1_Isnow=isnowvol
+VAR1_Isal=iicesali
+VAR1_Iage=iiceages
+VAR1_IvelU=iicevelu
+VAR1_IvelV=iicevelv
+VAR1_Ivelo=iicevelo
+#
+#===================== EXP2 =====================
+#
+FILE2_T=l3fwb178_25010101_25011231_5D_grid_T.nc   # exp1 grid T input file
+FILE2_U=l3fwb178_25010101_25011231_5D_grid_U.nc   # exp1 grid U input file
+FILE2_V=l3fwb178_25010101_25011231_5D_grid_V.nc   # exp1 grid V input file
+FILE2_I=l3fwb178_25010101_25011231_5D_icemod.nc   # exp1 ice    input file
+VAR2_T=votemper
+VAR2_S=vosaline
+VAR2_QNET=sohflxdo
+VAR2_ERP=sowafldp
+VAR2_EMP=sowaflup
+VAR2_MLD=max5dmld
+VAR2_U=vozoeftr
+VAR2_V=vomeeftr
+VAR2_Ithick=iicethic
+VAR2_Ifrac=iiceconc
+VAR2_Isnow=isnowthi
+VAR2_Isal=iicesali
+VAR2_Iage=iiceages
+VAR2_IvelU=iicevelu
+VAR2_IvelV=iicevelv
+VAR2_Ivelo=iicevelo
+#
+######################### 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.new_names
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.new_names	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.new_names	(revision 14097)
@@ -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 )/sbcmodMV_ps_plot
+PDF_DIR=$( pwd )/sbcmodMV_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=sbcmodMV_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=sbcmodMV_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=sbcmodMV_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=sbcmodMV_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=thetao
+VAR1_S=so        
+VAR1_QNET=tohfls
+VAR1_ERP=sowafldp      
+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=sbcmodMV_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE2_U=sbcmodMV_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE2_V=sbcmodMV_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE2_I=sbcmodMV_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
+VAR2_T=thetao
+VAR2_S=so
+VAR2_QNET=tohfls
+VAR2_ERP=sowafldp
+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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.old_names
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.old_names	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh.old_names	(revision 14097)
@@ -0,0 +1,131 @@
+#!/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 )/500yfwb0_ps_plot_500y
+PDF_DIR=$( pwd )/500yfwb0_pdf_plot_500y
+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=500yfwb0_24910101_25001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=500yfwb0_24910101_25001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=500yfwb0_24910101_25001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=500yfwb0_24910101_25001231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=votemper
+VAR1_S=vosaline
+VAR1_QNET=sohflxdo
+VAR1_ERP=sowafldp
+VAR1_EMP=sowaflup
+VAR1_MLD=somxl010
+VAR1_U=vozoeftr
+VAR1_V=vomeeftr
+VAR1_Ithick=iicethic
+VAR1_Ifrac=iiceconc
+VAR1_Isnow=isnowvol
+VAR1_Isal=iicesali
+VAR1_Iage=iiceages
+VAR1_IvelU=iicevelu
+VAR1_IvelV=iicevelv
+#VAR1_Ivelo=iicevelo
+#
+#===================== EXP2 =====================
+#
+FILE2_T=500yfwb0_24910101_25001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE2_U=500yfwb0_24910101_25001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE2_V=500yfwb0_24910101_25001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE2_I=500yfwb0_24910101_25001231_1M_icemod.nc   # exp1 ice    input file
+VAR2_T=votemper
+VAR2_S=vosaline
+VAR2_QNET=sohflxdo
+VAR2_ERP=sowafldp
+VAR2_EMP=sowaflup
+VAR2_MLD=somxl010
+#VAR2_U=uoce
+VAR2_U=vozoeftr
+#VAR2_V=voce
+VAR2_V=vomeeftr
+VAR2_Ithick=iicethic
+VAR2_Ifrac=iiceconc
+VAR2_Isnow=isnowthi
+VAR2_Isal=iicesali
+VAR2_Iage=iiceages
+VAR2_IvelU=iicevelu
+VAR2_IvelV=iicevelv
+#VAR2_Ivelo=iicevelo
+#
+######################### 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example1
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example1	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example1	(revision 14097)
@@ -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 )/ps_plot
+PDF_DIR=$( pwd )/pdf_plot
+HTML_DIR=$( pwd )/html_plot
+SAXO_DIR=/Users/sflod/SAXO_DIR
+#
+DIR_DATA=~/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
+DIR_CLIMATO=~/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
+DIR_MASK=~//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=500yfwb0_24910101_25001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=500yfwb0_24910101_25001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=500yfwb0_24910101_25001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=500yfwb0_24910101_25001231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=votemper
+VAR1_S=vosaline
+VAR1_QNET=sohflxdo
+VAR1_ERP=sowafldp
+VAR1_EMP=sowaflup
+VAR1_MLD=somxl010
+VAR1_U=vozoeftr
+VAR1_V=vomeeftr
+VAR1_Ithick=iicethic
+VAR1_Ifrac=iiceconc
+VAR1_Isnow=isnowvol
+VAR1_Isal=iicesali
+VAR1_Iage=iiceages
+VAR1_IvelU=iicevelu
+VAR1_IvelV=iicevelv
+VAR1_Ivelo=iicevelo
+#
+#===================== EXP2 =====================
+#
+FILE2_T=tr33beta_00910101_01001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE2_U=tr33beta_00910101_01001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE2_V=tr33beta_00910101_01001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE2_I=tr33beta_00910101_01001231_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=sit
+VAR2_Ifrac=sic
+VAR2_Isnow=isnowthi
+VAR2_Isal=iicesali
+VAR2_Iage=iiceages
+VAR2_IvelU=iicevelu
+VAR2_IvelV=iicevelv
+VAR2_Ivelo=iicevelo
+#
+######################### 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example2
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example2	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_vardef.sh_example2	(revision 14097)
@@ -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 )/ps_plot
+PDF_DIR=$( pwd )/pdf_plot
+HTML_DIR=$( pwd )/html_plot
+SAXO_DIR=/Users/sflod/SAXO_DIR
+#
+DIR_DATA=~/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
+DIR_CLIMATO=~/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
+DIR_MASK=~//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=500yfwb0_24910101_25001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=500yfwb0_24910101_25001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=500yfwb0_24910101_25001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=500yfwb0_24910101_25001231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=votemper
+VAR1_S=vosaline
+VAR1_QNET=sohflxdo
+VAR1_ERP=sowafldp
+VAR1_EMP=sowaflup
+VAR1_MLD=somxl010
+VAR1_U=vozoeftr
+VAR1_V=vomeeftr
+VAR1_Ithick=iicethic
+VAR1_Ifrac=iiceconc
+VAR1_Isnow=isnowvol
+VAR1_Isal=iicesali
+VAR1_Iage=iiceages
+VAR1_IvelU=iicevelu
+VAR1_IvelV=iicevelv
+VAR1_Ivelo=iicevelo
+#
+#===================== EXP2 =====================
+#
+FILE1_T=500yfwb0_24910101_25001231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=500yfwb0_24910101_25001231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=500yfwb0_24910101_25001231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=500yfwb0_24910101_25001231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=votemper
+VAR1_S=vosaline
+VAR1_QNET=sohflxdo
+VAR1_ERP=sowafldp
+VAR1_EMP=sowaflup
+VAR1_MLD=somxl010
+VAR1_U=vozoeftr
+VAR1_V=vomeeftr
+VAR1_Ithick=iicethic
+VAR1_Ifrac=iiceconc
+VAR1_Isnow=isnowvol
+VAR1_Isal=iicesali
+VAR1_Iage=iiceages
+VAR2_IvelU=iicevelu
+VAR2_IvelV=iicevelv
+VAR2_Ivelo=iicevelo
+#
+######################### 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_S.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_S.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_S.pro	(revision 14097)
@@ -0,0 +1,55 @@
+pro std_plot_zonal_S, S1, S2, SLev, SUBBASIN = subbasin, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  if KEYWORD_SET(SUBBASIN) then subname = subbasin else subname = "Glo"
+  filename = cdti3 + '_ZonalS_'+subname+'_'+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
+
+; looking for longitudinal index corresponding to the highest latitude (closest to the North Pole)
+  index = where(gphit eq max(gphit))
+  nx = index[0] mod jpi
+  gphi_save = gphit
+  gphit[0, *] = gphit[nx, *]
+
+  if KEYWORD_SET(SUBBASIN) then begin
+    tmasksv = tmask
+    CASE 1 of 
+      subbasin eq 'Atl' : var = 'atlmsk_nomed'
+      subbasin eq 'Ind' : var = 'indmsk_nored'
+      subbasin eq 'Pac' : var = 'pacmsk'
+    ENDCASE
+    msk = read_ncdf( var, filename = std_file_msksub, _extra = ex)
+; from 2D array to 3D array
+    msk = msk.arr[*]#replicate(1., nzt)
+    tmask[firstxt:lastxt, firstyt:lastyt, firstzt:lastzt] = tmask[firstxt:lastxt, firstyt:lastyt, firstzt:lastzt] * msk
+  endif
+;
+  title = 'Salinity, '+subname+'!C'+std_file1_T
+  pltz, S1, MININ = 31., MAXIN = 36.8, INTER = .2, typein = 'yz', FORMAT = '(f4.1)' $ 
+        , small = [1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /PORTRAIT,  _extra = ex 
+; 
+  if std_file1_T NE std_file2_T then begin
+    title = title+' - '+std_file2_T
+    pltz, S1.arr-S2.arr, MIN = -1., MAX = 1., INTER = .1, typein = 'yz', FORMAT = '(f4.1)', style = 'so0so' $
+          , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /NOERASE,  _extra = ex    
+  endif else begin
+    title = title+' - Levitus'
+    pltz, S1.arr-SLev.arr, MININ = -1, MAXIN = 1., INTER = .1, typein = 'yz', FORMAT = '(f4.1)', style = 'so0so'  $
+          , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /NOERASE, _extra = ex
+  endelse
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+;
+  if KEYWORD_SET(SUBBASIN) then tmask = tmasksv
+  gphit = gphi_save
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_T.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_T.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_plot_zonal_T.pro	(revision 14097)
@@ -0,0 +1,55 @@
+pro std_plot_zonal_T, T1, T2, TLev, SUBBASIN = subbasin, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  if KEYWORD_SET(SUBBASIN) then subname = subbasin else subname = "Glo"
+  filename = cdti3 + '_ZonalT_'+subname+'_'+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
+;  
+; looking for longitudinal index corresponding to the highest latitude (closest to the North Pole)
+  index = where(gphit eq max(gphit))
+  nx = index[0] mod jpi
+  gphi_save = gphit
+  gphit[0, *] = gphit[nx, *]
+;
+  if KEYWORD_SET(SUBBASIN) then begin
+    tmasksv = tmask
+    CASE 1 of 
+      subbasin eq 'Atl' : var = 'atlmsk_nomed'
+      subbasin eq 'Ind' : var = 'indmsk_nored'
+      subbasin eq 'Pac' : var = 'pacmsk'
+    ENDCASE
+    msk = read_ncdf( var, filename = std_file_msksub, _extra = ex)
+; from 2D array to 3D array
+    msk = msk.arr[*]#replicate(1., nzt)
+    tmask[firstxt:lastxt, firstyt:lastyt, firstzt:lastzt] = tmask[firstxt:lastxt, firstyt:lastyt, firstzt:lastzt] * msk
+  endif
+;
+  title = 'Temperature, '+subname+'!C'+std_file1_T
+  pltz, T1, MININ = -2., MAXIN = 30., INTER = 1., typein = 'yz', FORMAT = '(I2)' $ 
+        , small = [ 1, 2, 1], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /PORTRAIT, _extra = ex 
+; 
+  if std_file1_T NE std_file2_T then begin
+    title = title+' - '+std_file2_T
+    pltz, T1.arr-T2.arr, MIN = -2., MAX = 2., INTER = .2, typein = 'yz', FORMAT = '(f4.1)', style = 'so0so' $
+          , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /NOERASE, _extra = ex
+  endif else begin
+    title = title+' - Levitus'
+    pltz, T1.arr-TLev.arr, MININ = -4., MAXIN = 4., INTER = .5, typein = 'yz', FORMAT = '(I2)', style = 'so0so' $
+          , small = [1, 2, 2], COAST_THICK = 2, TITLE = title, boxzoom = 5500, ZOOM = 1000, /NOERASE, _extra = ex
+  endelse
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+;
+  if KEYWORD_SET(SUBBASIN) then tmask = tmasksv  
+  gphit = gphi_save
+;
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_AMOC.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_AMOC.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_AMOC.pro	(revision 14097)
@@ -0,0 +1,143 @@
+PRO std_ts_read_AMOC, var_name, dt1, dt2, prefix, suffix, t45, t70, t50
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+  list = rseries_ncdf(var_name, dt1, dt2, prefix, suffix, /fileslist)
+  nfiles = n_elements(list)
+
+  t45 = 0.
+  t70 = 0.
+  t50 = 0.
+  ts_Time = 0.
+
+  trans = strlowcase(var_name) EQ 'vocetr_eff' OR strlowcase(var_name) EQ 'vomeeftr'
+  ;trans = strlowcase(var_name) EQ 'vomeeftr'
+
+  ; ADD definition of mask_atl_nomed to compute AMOC (with no Mediterranean Sea)
+  msk_atl_nomed = read_ncdf( 'atlmsk_nomed', filename = std_file_msksub, /nostruct, _extra = ex )
+  FOR i = 0, nfiles-1 DO BEGIN
+    var = read_ncdf(var_name, allrecords = allrec, filename = list[i], /nostruct)
+    ts_Time = [ ts_Time, Time]
+;
+    FOR t = 0, jpt-1 DO BEGIN
+      msfatl = msf(var[*, *, *, t], msk_atl_nomed, TRANSPORT = trans, /nostruct, indexboxzoom = ind)
+      msftot = msf(var[*, *, *, t], TRANSPORT = trans, /nostruct, indexboxzoom = ind)
+      yaxis = gphit[ind[0], ind[2]:ind[3]]
+
+; computation of max Atlatic Meridional Overturninc Circulation at 40°N and 50°N
+      indy = where(yaxis gt 40 and yaxis le 50)
+      domdef, 0, 3500
+      ;SF commented because we've to compute msftot starting from msf atlantic; i.e. without mediterranean sea.
+      ;SF t45 = [t45, max(msftot[indy, firstzw:lastzw], /NaN)]
+      t45 = [t45, max(msfatl[indy, firstzw:lastzw], /NaN)]
+      
+; computation of max atlantic Antarctic Bottom Water between 80°S and 65°S
+      indy = where(yaxis gt -80 and yaxis le -65)
+      domdef, 300, 3500
+      t70 = [t70, min(msftot[indy, firstzw:lastzw], /NaN)]
+
+;  computation of max Antarctic Abyssal Bottom Cell between 65°S and 30°N , 
+      indy = where(yaxis gt -65 and yaxis le 30)
+      domdef, 2500, 5000
+      t50 = [t50, min(msftot[indy, firstzw:lastzw], /NaN)]
+      
+      domdef, 0, jpk-1, /zindex
+    ENDFOR
+
+  ENDFOR
+
+  time = ts_Time[1:*]           ; remove first record of 0
+  jpt = n_elements(time)
+  
+  t45 = t45[1:*]                ; remove first record of 0 
+  t70 = t70[1:*]                ; remove first record of 0 
+  t50 = t50[1:*]                ; remove first record of 0 
+
+  return
+end
+
+pro std_ts_AMOC, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vV1 = getenv('VAR1_V')   &   prefix = getenv('V1V_PREF')    &   suffix = getenv('V1V_SUFF')
+; get exp2 info
+  vV2 = getenv('VAR2_V')   &   prefix2 = getenv('V2V_PREF')   &   suffix2 = getenv('V2V_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_AMOC_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'_1.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+  d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+;
+  iodir = std_iodir_data
+
+; compute the MSF
+;  
+  std_ts_read_AMOC, vV1, date1, date2, prefix, suffix, t45, t70, t50
+  if prefix NE prefix2 then begin
+    tsave = time
+    std_ts_read_AMOC, vV2, date1_2, date2_2, prefix2, suffix2, t45_2, t70_2, t50_2
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+  ENDIF
+
+; plots...  
+
+  title = prefix+' '+d1_d2+'!C'+'Max Atlantic MOC between 40N and 50N'
+  pltt, t45, 't', MIN = 0., MAX = 30., date1, date2, /REMPLI, /PORTRAIT, XGRIDSTYLE = 1 $
+        ,  small = [1, 2, 1],  TITLE = title, YTITLE = varunit, _extra = ex
+  IF prefix NE prefix2 then begin
+    title = prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'Max Atlantic MOC between 40N and 50N'
+    pltt, t45, 't', MIN = 0., MAX = 30., date1, date2, /REMPLI , /NOERASE, XGRIDSTYLE = 1 $
+          ,  small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; BLACK
+    pltt, t45_2, 't', date1, date2, /REMPLI, /NOERASE $
+          ,  /ov1d, COLOR = 250, small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; RED
+  endif
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_1.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+  title = prefix+' '+d1_d2+'!C'+'Max AntArctic Bottom Water between 80S and 65S '+d1_d2
+  pltt, -t70, 't', MIN = 0., MAX = 20., date1, date2, /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, window = 2  $
+        , small = [1, 2, 1],  TITLE = title, YTITLE = varunit, _extra = ex
+  if prefix NE prefix2 then begin 
+    title = prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'Max AntArctic Bottom Water between 80S and 65S'
+    pltt, -t70, 't', MIN = 0.,MAX =  20., date1, date2, /REMPLI, /NOERASE, XGRIDSTYLE = 1 $
+          ,  small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; BLACK
+    pltt, -t70_2, 't', date1, date2, /REMPLI, /NOERASE $
+          , /ov1d, COLOR = 250, small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; RED
+  endif
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  if KEYWORD_SET(postscript) then openps, filename+'_3.ps', portrait = 1
+
+  title = prefix+' '+d1_d2+'!C '+'Max AntArctic Bottom Cell between 65S and 30N '+d1_d2
+  pltt, -t50, 't', MIN = 5., MAX = 30., date1, date2, /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, window = 3  $
+        ,  small = [1, 2, 1],  TITLE = title, YTITLE = varunit, _extra = ex
+  if prefix NE prefix2 then begin
+    title = prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'Max AntArctic Bottom Cell between 65S and 30N'
+    pltt, -t50 , 't', MIN = 5., MAX = 30., date1, date2, /REMPLI, /NOERASE, XGRIDSTYLE = 1 $
+          ,  small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; BLACK
+    pltt, -t50_2, 't', date1, date2, /REMPLI, /NOERASE  $
+          , /ov1d, COLOR = 250, small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; RED
+  endif
+  
+  domdef, 0, jpk-1, /zindex
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_3.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+    
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Drake.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Drake.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Drake.pro	(revision 14097)
@@ -0,0 +1,75 @@
+pro std_ts_Drake, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vU1 = getenv('VAR1_U')   &   prefix = getenv('V1U_PREF')    &   suffix = getenv('V1U_SUFF')
+; get exp2 info
+  vU2 = getenv('VAR2_U')   &   prefix2 = getenv('V2U_PREF')   &   suffix2 = getenv('V2U_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_Drake_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+ 
+; find a point in south America (around 60E-30S)
+  if max(glamt) gt 300 then testlam = abs(glamt - 300) else testlam = abs(glamt + 60)
+  testlat = abs(gphit + 30)
+  index = where(abs(testlam - min(testlam)) lt 1 and abs(testlat - min(testlat)) lt 1 )
+  xindex = index[0] mod jpi
+  yindex = index[0]/jpi
+; define a domain limited to a thin band going from Antactica to this point in south America
+  domdef, xindex, xindex+1, 0, yindex, 0, jpk-1, /index ; keep 2 points for x to avoid degenerated dimension...
+;
+  u1 = rseries_ncdf(vU1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, /nostruct)
+  drk1 = fltarr(jpt)
+  ; old formulation: we tested variable name
+  trans = strlowcase(getenv('VAR1_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR1_U')) EQ 'vozoeftr'
+  ;SF trans = strlowcase(getenv('VAR1_U')) EQ 'vozoeftr'
+  FOR t = 0, jpt-1 DO BEGIN
+    tmp = bsf(u1[*, *, *, t], TRANSPORT = trans, /nostruct)
+    drk1[t] = tmp[0, nyt-1]-tmp[0, 0]
+  ENDFOR
+;
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, drk1, 't', 0., 200., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1],  TITLE = title, YTITLE = varunit, /PORTRAIT, _extra = ex
+  
+  if prefix NE prefix2 then begin
+;
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    u2 = rseries_ncdf(vU2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, /nostruct)
+    drk2 = fltarr(jpt)
+    ; old formulation: we tested variable name
+    trans = strlowcase(getenv('VAR2_U')) EQ 'uocetr_eff' OR strlowcase(getenv('VAR2_U')) EQ 'vozoeftr'
+    ;SF trans = strlowcase(getenv('VAR1_U')) EQ 'vozoeftr'
+    FOR t = 0, jpt-1 DO BEGIN
+      tmp = bsf(u2[*, *, *, t], TRANSPORT = trans, /nostruct)
+      drk2[t] = tmp[0, nyt-1]-tmp[0, 0]
+    ENDFOR
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    title = prefix+' (BLACK) - '+prefix2+' (RED)  '+d1_d2_2+'!C'+blabla
+    pltt, drk1 , 't', 0., 200., date1, date2, /REMPLI, /NOERASE, XGRIDSTYLE = 1 $
+          , COLOR = 000, small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; BLACK
+    pltt, drk2, 't', 0., 200., date1, date2, /REMPLI, /NOERASE $
+          , /ov1d, COLOR = 250, small = [1, 2, 2],  TITLE = title, YTITLE = varunit, _extra = ex ; RED
+    
+  endif
+
+  domdef
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_EMP.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_EMP.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_EMP.pro	(revision 14097)
@@ -0,0 +1,51 @@
+pro std_ts_EMP, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vemp = getenv('VAR1_EMP')    &   prefix = getenv('V1EMP_PREF')    &   suffix = getenv('V1EMP_SUFF')
+; get exp2 info
+  vemp2 = getenv('VAR2_EMP')   &   prefix2 = getenv('V2EMP_PREF')   &   suffix2 = getenv('V2EMP_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_EMP_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+;
+  surf_oce = e1t * e2t * tmask[*,*,0] * masknp
+  surf_oce = total(surf_oce)
+;
+  ts_EMP = rseries_ncdf(vemp, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+  ts_EMP.arr = ts_EMP.arr * ( 1.E-09 * surf_oce )   &   ts_EMP.unit = 'Sv'
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, ts_EMP, 't', MIN = -2.,MAX = 2., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = 'Sv', TITLE = title, /PORTRAIT, _extra = ex
+  
+  IF prefix NE prefix2 THEN BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    ts_EMP2 = rseries_ncdf(vemp2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+    ts_EMP2.arr = ts_EMP2.arr * ( 1.E-09 * surf_oce )   &   ts_EMP2.unit = 'Sv'
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    title = prefix+' (BLACK) - ' +prefix2+' (RED) '+d1_d2_2+'!C'+blabla
+    pltt, ts_EMP.arr - ts_EMP2.arr, 't', MIN = -2., MAX = 2., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+          , color = 250, small = [1, 2, 2], YTITLE = 'Sv', TITLE = title, /noerase, _extra = ex
+
+  ENDIF 
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE.pro	(revision 14097)
@@ -0,0 +1,204 @@
+function read_arr2d, filename, varname, t1, t2
+;; function that read input file and return 2d array with monthly timecounter 
+nyear = (t2-t1+1)/12
+arr2d = ncdf_lec(filename, VAR=varname)
+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)
+
+return, arr2d
+end 
+
+;; here start procedure that use function read_arr2d  
+pro std_ts_ICE, masknp, s_iodir_data,  POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vICE1 = getenv('VAR1_ICE')   &   prefix = getenv('V1ICE_PREF')    &   suffix = getenv('V1ICE_SUFF')
+; get exp2 info
+  vICE2 = getenv('VAR2_ICE')   &   prefix2 = getenv('V2ICE_PREF')   &   suffix2 = getenv('V2ICE_SUFF')
+; get ice climatology info
+  std_file_ice =  isafile(getenv('FILE_ICE'), title = 'ICE Extent Climatology', iodir = std_iodir_climato)
+;
+  time_ice = ncdf_lec( std_file_ice, VAR='time' )
+  time_ice = (time_ice - FLOOR(time_ice) ) * 12
+  time_ice = (round(time_ice) + 11) mod 12; round to nearest integer
+  t1 = where(time_ice eq 0)
+  t1 = t1[0] ;  january
+  t2 = where(time_ice eq 11, count)
+  t2 = t2[count-1] ; last day of december
+
+  vICE_ext_NH = read_arr2d(std_file_ice, getenv('VAR_ICE_EXT_NH'), t1, t2 )
+  vICE_ext_SH = read_arr2d(std_file_ice, getenv('VAR_ICE_EXT_SH'), t1, t2 )
+;
+  vICE_area_NH = read_arr2d(std_file_ice, getenv('VAR_ICE_area_NH'), t1, t2 )
+  vICE_area_SH = read_arr2d(std_file_ice, getenv('VAR_ICE_area_SH'), t1, t2 )
+;  
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_ICE_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+  ; ICE Area in NORTH Hemisphere
+  domdef, 0, jpi-1, 30, 90, /xindex
+  ICE_N = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ICE_N = grossemoyenne(ICE_N.arr, 'xy', /integration, mask2d = masknp)
+
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_N = reform(ice_n, 12,nyr)
+  ICE_n = total(ice_n,2)/nyr
+  ICE_N = {arr:ICE_N * 1.e-12, unit : '10^12 m^2'}
+
+  ; ICE EXTENT (Area minus 15%) in NORTH Hemisphere
+  ICE_N_15 = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  msk = ICE_N_15.arr gt 0.15 ; remove 0.15% for observations
+  ICE_N_15 = grossemoyenne( msk, 'xy', /integration, mask2d = masknp)
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_N_15 = reform(ice_n_15, 12,nyr)
+  ICE_n_15 = total(ice_n_15,2)/nyr
+  ICE_N_15 = {arr:ICE_N_15 * 1.e-12, unit : '10^12 m^2'}
+  ;
+  ;ICE Area in SOUTH Hemisphere
+  domdef, 0, jpi-1, -90, -30, /xindex 
+  ICE_S = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ICE_S = grossemoyenne(ICE_S.arr, 'xy', /integration, mask2d = masknp)
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_S = reform(ice_S, 12,nyr)
+  ICE_S = total(ice_S,2)/nyr
+  ICE_S = {arr:ICE_S * 1.e-12, unit : '10^12 m^2'}
+  ; ICE EXTENT (Area minus 15%) in SOUTH Hemisphere
+  ICE_S_15 = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  msk = ICE_S_15.arr gt 0.15 ; remove 0.15% for observations
+  ICE_S_15 = grossemoyenne(msk, 'xy', /integration, mask2d = masknp)
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_S_15 = reform(ice_S_15, 12,nyr)
+  ICE_S_15 = total(ice_S_15,2)/nyr
+  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 (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, 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 $       ;;; 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, 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 $   ;;; 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 (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 $ 
+        , /ov1d, COLOR = 000, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex 
+  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 $ 
+        , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  if prefix NE prefix2 then BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    domdef, 0, jpi-1, 30, 90, /xindex
+    ;ICE Extent in NORTH Hemisphere
+    ICE_N2 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ICE_N2 = grossemoyenne(ICE_N2.arr, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_N2 = reform(ICE_N2, 12,nyr)
+    ICE_N2 = total(ICE_N2,2)/nyr
+    ICE_N2 = {arr:ICE_N2 * 1.e-12, unit : '10^12 m^2'}
+    ;ICE Extent minus 15% in NORTH Hemisphere
+    ICE_N2_15 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    msk = ICE_N2_15.arr gt 0.15  ; remove 0.15% for observations
+    ICE_N2_15 = grossemoyenne( msk, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_N2_15 = reform(ICE_N2_15, 12,nyr)
+    ICE_N2_15 = total(ICE_N2_15,2)/nyr
+    ICE_N2_15 = {arr:ICE_N2_15 * 1.e-12, unit : '10^12 m^2'}
+    ;ICE Extent in SOUTH Hemisphere
+    domdef, 0, jpi-1, -90, -30, /xindex 
+    ICE_S2 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ICE_S2 = grossemoyenne(ICE_S2.arr, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_S2 = reform(ICE_S2, 12,nyr)
+    ICE_S2 = total(ICE_S2,2)/nyr
+    ICE_S2 = {arr:ICE_S2 * 1.e-12, unit : '10^12 m^2'}
+    ;ICE Extent minus 15% in SOUTH Hemisphere
+    ICE_S2_15 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    msk = ICE_S2_15.arr gt 0.15  ; remove 0.15% for observations
+    ICE_S2_15 = grossemoyenne(msk, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_S2_15 = reform(ICE_S2_15, 12,nyr)
+    ICE_S2_15 = total(ICE_S2_15,2)/nyr
+    ICE_S2_15 = {arr:ICE_S2_15 * 1.e-12, unit : '10^12 m^2'}
+  ;
+ ;   time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+
+  ;;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, 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 , 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 $ ; 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 $ ; 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, 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 $ 
+        , /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 (DASHED)'+'!C'+ 'and Extend minus 15% (CONTINUOUS)'
+;  title ='Southern Hemisphere'+'!C'
+  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, 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 $ ; 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 $ ; 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, 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 $ 
+        , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
+;
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+
+  endif
+
+  domdef
+  
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_FRAM.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_FRAM.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_FRAM.pro	(revision 14097)
@@ -0,0 +1,211 @@
+function read_arr2d, filename, varname, t1, t2
+;; function that read input file and return 2d array with monthly timecounter 
+nyear = (t2-t1+1)/12
+arr2d = ncdf_lec(filename, VAR=varname)
+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 = arr2d[*, nyear-1] ;  select last year
+
+return, arr2d
+end 
+
+;; here start procedure that use function read_arr2d
+pro std_ts_ICE_FRAM, masknp, s_iodir_data,  POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vICE1     = getenv('VAR1_ICE')     &   prefix = getenv('V1ICE_PREF')  &   suffix = getenv('V1ICE_SUFF')
+  v1_Ithick = getenv('VAR1_Ithick')  &   prefix = getenv('V1It_PREF')   &   suffix = getenv('V1It_SUFF')
+  v1_IV     = getenv('VAR1_IvelV')   &   prefix = getenv('V1IvV_PREF')  &   suffix = getenv('V1IvV_SUFF')
+; get exp2 info
+  vICE2     = getenv('VAR2_ICE')     &   prefix2 = getenv('V2ICE_PREF')   &   suffix2 = getenv('V2ICE_SUFF')
+  v2_Ithick = getenv('VAR2_Ithick')  &   prefix2 = getenv('V2It_PREF')    &   suffix2 = getenv('V2It_SUFF')
+  v2_IV     = getenv('VAR2_IvelV')   &   prefix2 = getenv('V2IvV_PREF')   &   suffix2 = getenv('V2IvV_SUFF')
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_ICE_FRAM_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+  d2 = '('+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+  ; ICE Area(=Surface) in FRAM Strait
+  ;; FRAM Strait points, computed with ncview meshmask for ORCA2 grid (133-1434-135-136, 137)
+  indx0 = 133 
+  indx0_last = 136
+  indy0 = 137
+  indy0_last = 137
+  ;; ORI domdef, 133, 137, 136, 136, /xindex, /yindex,/memeindices
+  indx1= (indx0 - ixminmesh + key_shift)mod(jpi)
+  indx2= (indx0_last - ixminmesh + key_shift)mod(jpi)
+  indy1= indy0 - iyminmesh
+  indy2= indy1 
+ ;
+ ;OBSERVATIONS : mean seasonal cycle/month
+ ; vol_obs = [0.261625, 0.230750, 0.325375, 0.252000, 0.172500, 0.0805000, 0.0805000, 0.0805000, 0.0805000, 0.176500, 0.148500, 0.235000]
+  vol_obs = [261.625, 230.750, 325.375, 252.000, 172.500, 80.5000, 80.5000, 80.5000, 80.5000, 176.500, 148.500, 235.000]
+  area_obs = [0.103292, 0.0997500, 0.107625, 0.0944167, 0.0612083, 0.0262500, 0.0262500, 0.0262500, 0.0262500, 0.0843750, 0.0914583, 0.104083]
+ ;
+  domdef, indx1, indx2, indy1, indy2, /xindex, /yindex,/memeindices
+  ICE = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, /nostruct)
+  ICE_thick = rseries_ncdf(v1_Ithick, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, /nostruct)
+ ; domdef for V-Point in j-1
+ ; REALLY NOT NECESSARY, BECAUSE FLUX CAN BE COMPUTED IN J POINT, is the same
+  domdef, indx1, indx2, indy1-1, indy2-1, /xindex, /yindex,/memeindices
+  VN = rseries_ncdf(v1_IV, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec,/nostruct) ;!! warning positive northward
+
+  ;; Area export
+  ICE_area_export = (-1) * ICE * VN * ((e1v[firstxv:lastxv, firstyv:lastyv])[*]#replicate(1., jpt))
+  ICE_area_export = total(reform(ICE_area_export),1) ; in m2/s -> need to change the unit?
+
+  ;; Volume export
+  ICE_vol_export = (-1) * ICE * ICE_thick * VN * ((e1v[firstxv:lastxv, firstyv:lastyv])[*]#replicate(1., jpt))
+  ICE_vol_export = total(reform(ICE_vol_export),1) ;! in m3/s -> need to change the unit?
+
+  ;   needed for seasonal cycle :
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ;; AREA
+  ICE_area_export = reform(ICE_area_export, 12, 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
+  
+  ;
+  ICE_vol_export = reform(ICE_vol_export, 12, 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: 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)
+  pltt, ICE_area_export, 't', /REMPLI, /PORTRAIT, MIN = 0., MAX = .5 , XGRIDSTYLE = 1 $
+        , small = [1, 2, 1],YTITLE = '10^6 Km^2/month',  TITLE = title, DATE_FORMAT = '%M', _extra = ex    
+  pltt, area_obs, 't', /REMPLI, /NOERASE, psym = 4, THICK = 4  $    ; light blue
+         , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^6 Km^2/month', TITLE = title, DATE_FORMAT = '%M', _extra = ex
+  ;
+  tot_area_expo = total(ICE_area_export.arr)
+  ;
+  xyouts, julday(5,15,1900), 0.49, 'Tot. Annual Export OBS = 0.851 million Km2', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+  xyouts, julday(5,15,1900), 0.46, 'Tot. Annual Export Model = '+strtrim(tot_area_expo, 1)+' million Km2', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+  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 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
+  pltt, vol_obs, 't', /REMPLI, /NOERASE, psym = 4, THICK = 4  $    ; light blue
+         , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^6 Km^2/month',DATE_FORMAT = '%M', TITLE = title, _extra = ex
+  ;
+  tot_vol_expo = total(ICE_vol_export.arr)
+  tot_vol_expo_Sv = tot_vol_expo * 1.e06 * 1/86400 * 1/365 ; annual mean in Sverdrup
+  xyouts, julday(5,15,1900), 490, 'Tot. Annual Export OBS = 2124 10^3 Km3/year', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+  xyouts, julday(5,15,1900), 460, 'Tot. Annual Export Model = '+strtrim(tot_vol_expo, 1)+' 10^3 Km3/year', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+  xyouts, julday(9,15,1900), 440, 'in Sv = '+strtrim(tot_vol_expo_Sv, 1)+' Sv', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+  xyouts, julday(7,15,1900), 360, 'Data from Kwok et al.(2004), 1992-1998 ', ALIGN = 0, CHARTHICK = 2, CHARSIZE=0.8, COLOR=2
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  if prefix NE prefix2 then BEGIN
+
+    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
+    ICE_2= rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, /nostruct)
+    ICE_thick_2 = rseries_ncdf(v2_Ithick, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, /nostruct)
+    ; domdef for V-Point in j-1
+    ; REALLY NOT NECESSARY, BECAUSE FLUX CAN BE COMPUTED IN J POINT, is the same
+    domdef, indx1, indx2, indy1-1, indy2-1, /xindex, /yindex,/memeindices
+    VN_2 = rseries_ncdf(v2_IV, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec,/nostruct) ;!! warning positive northward
+
+    ;; Area export
+    ICE_area_export_2 = (-1) * ICE_2 * VN_2 * ((e1v[firstxv:lastxv, firstyv:lastyv])[*]#replicate(1., jpt))
+    ICE_area_export_2 = total(reform(ICE_area_export_2),1) ; in m2/s -> need to change the unit?
+
+    ;; Volume export
+    ICE_vol_export_2 = (-1) * ICE_2 * ICE_thick_2 * VN_2 * ((e1v[firstxv:lastxv, firstyv:lastyv])[*]#replicate(1., jpt))
+    ICE_vol_export_2 = total(reform(ICE_vol_export_2),1) ;! in m3/s -> need to change the unit?
+
+    ;   needed for seasonal cycle :
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/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 = 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 = 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
+    ;
+    ;
+    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 LAST YEAR'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d2_2
+    jpt=12
+    time=julday(1,15,1900)+30*lindgen(12)
+    pltt, ICE_area_export, 't', /REMPLI, /PORTRAIT, MIN = 0., MAX = .5, XGRIDSTYLE = 1, window = 2 $
+        , small = [1, 2, 1], YTITLE = '10^6 Km^2/month',  TITLE = title, DATE_FORMAT = '%M', _extra = ex    
+    pltt, ICE_area_export_2 ,'t', /REMPLI, /PORTRAIT, /NOERASE $
+        , /ov1d, COLOR = 250, small = [1, 2, 1],YTITLE = '10^6 Km^2/month',  TITLE = title, DATE_FORMAT = '%M', _extra = ex
+    pltt, area_obs, 't', /REMPLI, /NOERASE, psym = 4, THICK = 4  $    ; light blue
+         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^6 Km^2/month', TITLE = title, DATE_FORMAT = '%M', _extra = ex
+    ;
+    tot_area_expo = total(ICE_area_export.arr)
+    tot_area_expo_2 = total(ICE_area_export_2.arr)
+    ;
+    xyouts, julday(5,15,1900), 0.49, 'Tot. Annual Export OBS = 0.851 million Km2', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(5,15,1900), 0.46, 'Tot. Annual Export Model 1= '+strtrim(tot_area_expo, 1)+' million Km2', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(5,15,1900), 0.43, 'Tot. Annual Export Model 2= '+strtrim(tot_area_expo_2, 1)+' million Km2', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    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 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
+    pltt, ICE_vol_export_2, 't', /REMPLI, /NOERASE  $
+        , /ov1d, COLOR = 250, small = [1, 2, 2], YTITLE = '10^3 Km^3/month', TITLE = title, DATE_FORMAT = '%M',  _extra = ex
+    pltt, vol_obs, 't', /REMPLI, /NOERASE, psym = 4, THICK = 4  $    ; light blue
+         , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^6 Km^2/month', TITLE = title, DATE_FORMAT = '%M', _extra = ex
+    ;
+    tot_vol_expo = total(ICE_vol_export.arr)
+    tot_vol_expo_2 = total(ICE_vol_export_2.arr)
+    tot_vol_expo_Sv = tot_vol_expo * 1.e06 * 1/86400 * 1/365 ; annual mean in Sverdrup
+    tot_vol_expo_2_Sv = tot_vol_expo_2 * 1.e06 * 1/86400 * 1/365 ; annual mean in Sverdrup
+    xyouts, julday(5,15,1900), 490, 'Tot. Annual Export OBS = 2124 10^3 Km3/year', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(5,15,1900), 460, 'Tot. Annual Export Model 1 = '+strtrim(tot_vol_expo, 1)+' 10^3 Km3/year', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(9,15,1900), 440, 'in Sv = '+strtrim(tot_vol_expo_Sv, 1)+' Sv', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(5,15,1900), 410, 'Tot. Annual Export Model 2 = '+strtrim(tot_vol_expo_2, 1)+' 10^3 Km3/year', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(9,15,1900), 390, 'in Sv = '+strtrim(tot_vol_expo_2_Sv, 1)+' Sv', ALIGN = 0, CHARTHICK = 2, CHARSIZE=1, COLOR=2
+    xyouts, julday(7,15,1900), 360, 'Data from Kwok et al.(2004), 1992-1998 ', ALIGN = 0, CHARTHICK = 2, CHARSIZE=0.8, COLOR=2
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+
+  endif
+
+  domdef
+  
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vel.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vel.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vel.pro	(revision 14097)
@@ -0,0 +1,132 @@
+function read_arr2d, filename, varname, t1, t2
+;; function that read input file and return 2d array with monthly timecounter 
+nyear = (t2-t1+1)/12
+arr2d = ncdf_lec(filename, VAR=varname)
+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)
+
+return, arr2d
+end 
+
+;; here start procedure that use function read_arr2d
+pro std_ts_ICE_Vel, masknp, s_iodir_data,  POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+; get exp1 info
+  vICE1 = getenv('VAR1_ICE')   &   prefix = getenv('V1ICE_PREF')    &   suffix = getenv('V1ICE_SUFF')
+; get exp2 info
+  vICE2 = getenv('VAR2_ICE')   &   prefix2 = getenv('V2ICE_PREF')   &   suffix2 = getenv('V2ICE_SUFF')
+; get exp1 info
+  vICE_vel_1 = getenv('VAR1_Ivel')   &   prefix = getenv('V1Iv_PREF')  &   suffix = getenv('V1Iv_SUFF')
+; get exp2 info
+  vICE_vel_2 = getenv('VAR2_Ivel')   &   prefix2 = getenv('V2Iv_PREF')  &  suffix2 = getenv('V2Iv_SUFF')
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_ICE_Vel_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+  ; ICE Velocity in NORTH Hemisphere
+  domdef, 0, jpi-1, 30, 90, /xindex
+  Velo_N = rseries_ncdf(vICE_vel_1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, /nostruct) ;!! warning positive northward
+  ICE_N_15 = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec,  /nostruct) 
+  print, 'N15', max(ICE_N_15)
+  
+  
+  ICE_N_15[where(ICE_N_15 lt 0.15)] = 0.
+  
+  ICE_velo_N = grossemoyenne( (Velo_N < 1.e10) * (ICE_N_15 < 1.e10), 'xy',/integration, mask2d = masknp)
+  ICE_N_15 = grossemoyenne(ICE_N_15, 'xy',/integration, mask2d = masknp)
+  
+  ICE_velo_N = ICE_velo_N / ICE_N_15
+  
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_velo_N = reform(ICE_velo_N, 12, nyr)
+  ICE_velo_N = total(ICE_velo_N,2)/nyr
+  ICE_velo_N = {arr:ICE_velo_N , unit : 'm/s'}  
+   
+ 
+  ;ICE Velocity in SOUTH Hemisphere
+  domdef, 0, jpi-1, -90, -30, /xindex
+  Velo_S = rseries_ncdf(vICE_vel_1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec,/nostruct) ;!! warning positive northward
+
+   
+    
+  title = 'Northern Hemisphere'+'!C'+prefix+' '+d1_d2+'!C'+'Ice Velocity (Black SOLID simulation)'
+  jpt=12
+  time=julday(1,15,1900)+30*lindgen(12)
+
+
+  pltt, ICE_velo_N, 't', /REMPLI, /PORTRAIT, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, _extra = ex    
+  ;
+  title ='Southern Hemisphere' +'!C'+prefix+' '+d1_d2+' - '+'!C'+'Ice Velocity (Black SOLID simulation)'
+  pltt, Velo_S, 't',  /REMPLI, /NOERASE, XGRIDSTYLE = 1 $
+       , small = [1, 2, 2], YTITLE = varunit, TITLE = title, _extra = ex
+  ;
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  if prefix NE prefix2 then BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    ; ICE Velocity in NORTH Hemisphere
+    domdef, 0, jpi-1, 30, 90, /xindex
+    Velo_N_2 = rseries_ncdf(vICE_vel_2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec,/nostruct)
+    
+    ;;;;;; if grossempoyenne is not present dimension of array is not ok: 54   Array[180, 54, 120] 
+    ;;;;;; with the domain dimensions [jpi/nx, jpj/ny, jpk/nz, jpt] = [180/180, 149/50, 31/31, 12]
+  
+    ICE_velo_N_2 = grossemoyenne(Velo_N_2, 'xy', /integration, mask2d = masknp)
+    print, 'max ice velo', max(ICE_velo_N_2)
+  
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_velo_N_2 = reform(ICE_velo_N_2, 12, nyr)
+    ICE_velo_N_2 = total(ICE_velo_N_2,2)/nyr
+    ICE_velo_N_2 = {arr:ICE_velo_N_2 * 86400 * 365, unit : 'm/year'}  
+    print, 'max ice velo', max(ICE_velo_N_2.arr)
+    
+  
+    ;ICE Velocity in SOUTH Hemisphere
+    domdef, 0, jpi-1, -90, -30, /xindex
+    Velo_S_2 = rseries_ncdf(vICE_vel_2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec,/nostruct)
+      
+    if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+    jpt=12
+    time=julday(1,15,1900)+30*lindgen(12)
+
+    title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2 +'!C'+'Ice Velocity (BLACK) '
+    pltt, ICE_velo_N , 't', /REMPLI, XGRIDSTYLE = 1, window = 2  $
+          , small = [1, 2, 1], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+    pltt, ICE_velo_N_2, 't', /REMPLI $
+          , /ov1d, color = 250, small = [1, 2, 1], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+ 
+    title = 'Southern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2 +'!C'+'Ice Velocity (BLACK) '
+    pltt, Velo_S , 't', /REMPLI, XGRIDSTYLE = 1 $
+          , small = [1, 2, 2], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+    pltt, Velo_S_2, 't', /REMPLI $
+         , /ov1d, color = 250, small = [1, 2, 2], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+
+  endif
+
+  domdef
+  
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vol.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vol.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_ICE_Vol.pro	(revision 14097)
@@ -0,0 +1,135 @@
+function read_arr2d, filename, varname, t1, t2
+;; function that read input file and return 2d array with monthly timecounter 
+nyear = (t2-t1+1)/12
+arr2d = ncdf_lec(filename, VAR=varname)
+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)
+
+return, arr2d
+end 
+
+;
+;
+pro std_ts_ICE_Vol, masknp, s_iodir_data,  POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vICE1     = getenv('VAR1_ICE')     &   prefix = getenv('V1ICE_PREF')  &   suffix = getenv('V1ICE_SUFF')
+  v1_Ithick = getenv('VAR1_Ithick')  &   prefix = getenv('V1It_PREF')   &   suffix = getenv('V1It_SUFF')
+; get exp2 info
+  vICE2     = getenv('VAR2_ICE')     &   prefix2 = getenv('V2ICE_PREF')   &   suffix2 = getenv('V2ICE_SUFF')
+  v2_Ithick = getenv('VAR2_Ithick')  &   prefix2 = getenv('V2It_PREF')    &   suffix2 = getenv('V2It_SUFF')
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_ICE_Vol_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+;
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+  ; ICE Area(=Surface) in NORTH Hemisphere
+  domdef, 0, jpi-1, 30, 90, /xindex
+  ICE_N = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ICE_thick = rseries_ncdf(v1_Ithick, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ; Volume = Area(=Surface) * Thickness
+  ICE_vol_N = (ICE_N.arr < 1.e10 ) * ( ICE_thick.arr < 1.e10)  ; limited mask value of 1.e20, because 1.e20 * 1.e20 = inf for idl
+  ICE_vol_N = grossemoyenne(ICE_vol_N, 'xy', /integration, mask2d = masknp)
+
+  ;
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_vol_N = reform(ICE_vol_N, 12, nyr)
+  ICE_vol_N = total(ICE_vol_N,2)/nyr
+  ICE_vol_N = {arr:ICE_vol_N * 1.e-9, unit : '10^9 Km^3'}
+  ;
+  ;ICE Area(=Surface) in SOUTH Hemisphere
+  domdef, 0, jpi-1, -90, -30, /xindex 
+  ICE_S = rseries_ncdf(vICE1, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ICE_thick = rseries_ncdf(v1_Ithick, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec)
+  ; Volume = Area(=Surface) * Thickness
+  ICE_vol_S = (ICE_S.arr < 1.e10 ) * ( ICE_thick.arr < 1.e10)  ; limited mask value of 1.e20, because 1.e20 * 1.e20 = inf for idl
+  ICE_vol_S = grossemoyenne(ICE_vol_S, 'xy', /integration, mask2d = masknp)
+  if jpt mod 12 ne 0 then stop
+  nyr=jpt/12.
+  ICE_vol_S = reform(ICE_vol_S, 12, nyr)
+  ICE_vol_S = total(ICE_vol_S,2)/nyr
+  ICE_vol_S = {arr:ICE_vol_S * 1.e-9, unit : '10^9 Km^3'}
+  ;
+  title = 'Northern Hemisphere'+'!C'+prefix+' '+d1_d2+'!C'+'Global Annual Mean Ice Volume (BLACK) '
+  jpt=12
+  time=julday(1,15,1900)+30*lindgen(12)
+  pltt, ICE_vol_N, 't', MIN = 0., MAX = 40000., /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
+        , small = [1, 2, 1], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex
+;
+  title ='Southern Hemisphere' +'!C'+prefix+' '+d1_d2+' - '+'!C'+'Global Annual Mean Ice Volume (BLACK)'
+  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
+;
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  if prefix NE prefix2 then BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    domdef, 0, jpi-1, 30, 90, /xindex
+    ;ICE Area(=Surface) in NORTH Hemisphere
+    ICE_N2 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ICE_thick2 = rseries_ncdf(v2_Ithick, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ; Volume = Area(=Surface) * Thickness
+    ICE_vol_N2 = (ICE_N2.arr < 1.e10 ) * ( ICE_thick2.arr < 1.e10) ; limited mask value of 1.e20, because 1.e20 * 1.e20 = inf for idl
+    ICE_vol_N2 = grossemoyenne(ICE_vol_N2, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_vol_N2 = reform(ICE_vol_N2, 12, nyr)
+    ICE_vol_N2 = total(ICE_vol_N2,2)/nyr
+    ICE_vol_N2 = {arr:ICE_vol_N2 * 1.e-9, unit : '10^3 Km^3'}
+
+    ;ICE Area(=Surface) in SOUTH Hemisphere
+    domdef, 0, jpi-1, -90, -30, /xindex 
+    ICE_S2 = rseries_ncdf(vICE2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ICE_thick2 = rseries_ncdf(v2_Ithick, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec)
+    ; Volume = Area(=Surface) * Thickness
+    ICE_vol_S2 = (ICE_S2.arr < 1.e10 ) * ( ICE_thick.arr < 1.e10) ; limited mask value of 1.e20, because 1.e20 * 1.e20 = inf for idl
+    ICE_vol_S2 = grossemoyenne(ICE_vol_S2, 'xy', /integration, mask2d = masknp)
+    if jpt mod 12 ne 0 then stop
+    nyr=jpt/12.
+    ICE_vol_S2 = reform(ICE_vol_S2, 12, nyr)
+    ICE_vol_S2 = total(ICE_vol_S2,2)/nyr
+    ICE_vol_S2 = {arr:ICE_vol_S2 * 1.e-9, unit : '10^3 Km^3'}
+
+   ; time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+    title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2 +'!C'+'Global Annual Mean Ice Volume (BLACK) '
+    jpt=12
+    time=julday(1,15,1900)+30*lindgen(12)
+    pltt, ICE_vol_N, 't', MIN = 0., MAX = 40000., /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, window = 2, DATE_FORMAT = '%M' $
+          , small = [1, 2, 1], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex
+    pltt, ICE_vol_N2 , 't', /REMPLI, /PORTRAIT $ ; linee tratteggiate LINESTYLE=2  $
+        , /ov1d, COLOR = 250, small = [1, 2, 1], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex
+    ;
+    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 = 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 $
+          , /ov1d, COLOR = 250, small = [1, 2, 2], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex   
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+
+  endif
+
+  domdef
+  
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Q.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Q.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_Q.pro	(revision 14097)
@@ -0,0 +1,48 @@
+pro std_ts_Q, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vq = getenv('VAR1_Q')    &   prefix = getenv('V1Q_PREF')    &   suffix = getenv('V1Q_SUFF')
+; get exp2 info
+  vq2 = getenv('VAR2_Q')   &   prefix2 = getenv('V2Q_PREF')   &   suffix2 = getenv('V2Q_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_Q_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+;
+  ts_Q = rseries_ncdf(vq, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, ts_Q, 't', MIN = -4, MAX = 4, date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, /PORTRAIT, _extra = ex
+  
+  IF prefix NE prefix2 THEN BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    ts_Q2 = rseries_ncdf(vq2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    title = prefix+' (BLACK)  - '+prefix2+' (RED) '+d1_d2_2+'!C'+blabla
+    pltt, ts_Q.arr , 't', MIN = -4., MAX = 4., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+          , small = [1, 2, 2], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+    pltt, ts_Q2.arr, 't', date1, date2, /REMPLI $
+          , /ov1d, color = 250, small = [1, 2, 2], YTITLE = varunit, TITLE = title, /noerase, _extra = ex
+
+  ENDIF 
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_S.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_S.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_S.pro	(revision 14097)
@@ -0,0 +1,85 @@
+pro std_ts_S, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vsal = getenv('VAR1_S')      &   prefix = getenv('V1S_PREF')         &   suffix = getenv('V1S_SUFF')
+  vssh = getenv('VAR1_SSH')    &   sshprefix = getenv('V1SSH_PREF')    &   sshsuffix = getenv('V1SSH_SUFF')
+; get exp2 info
+  vsal2 = getenv('VAR2_S')     &   prefix2 = getenv('V2S_PREF')        &   suffix2 = getenv('V2S_SUFF')
+  vssh2 = getenv('VAR2_SSH')   &   sshprefix2 = getenv('V2SSH_PREF')   &   sshsuffix2 = getenv('V2SSH_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_S_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'_1.ps', portrait = 1
+
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+
+; read levitus data
+  std_file_Levitus_S =  isafile(getenv('FILE_SAL_3D'), title = 'Levitus_S', iodir = std_iodir_climato)
+  Lev = read_ncdf(getenv('VAR_SAL_3D'), filename = std_file_Levitus_S, /nostruct ) 
+  Lev_xyz = moyenne(Lev, 'xyz', mask2d = masknp)
+  levz = moyenne(temporary(Lev), 'xy', mask2d = masknp, /KEEPBOTTOM)
+;
+  iodir = std_iodir_data
+;
+
+; read exp1 data
+  std_ts_read, vsal, date1, date2, prefix, suffix, ts_Sal, ts_z, masknp $
+               , WITHSSH = vssh, SSHPREFIX = sshprefix, SSHSUFFIX = sshsuffix, LEVZ = levz
+
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, ts_Sal, 't', MIN = 34.54, MAX = 34.76, date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, /PORTRAIT, _extra = ex
+
+  title = prefix+' '+d1_d2+' - Levitus!C'+blabla
+  pltt, ts_Sal - Lev_xyz, 't', MIN = -.05, MAX = .05, date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 2], YTITLE = varunit, TITLE = title, /NOERASE, _extra = ex
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_1.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+  title = prefix+' '+d1_d2+' - Levitus!C ZT-plot (0-1500m) '+blabla
+  pltt, ts_z, 'zt', MIN = -.5, MAX = .5, INTER = .05, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, boxzoom = 1500., /portrait, window = 1, _extra = ex
+  
+  title = prefix+' '+d1_d2+' - Levitus!C ZT-plot (0-6000m) '+blabla
+  pltt, ts_z, 'zt', MIN = -.5, MAX = .5, INTER = .05, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+        , small = [1, 2, 2], YTITLE = varunit, TITLE = title, boxzoom = 6000., /NOERASE, _extra = ex
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  IF prefix NE prefix2 THEN BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+; read exp2 data
+    tsave = time
+    std_ts_read, vsal2, date1_2, date2_2, prefix2, suffix2, ts_Sal2, ts_z2, masknp $
+                 , WITHSSH = vssh2, SSHPREFIX = sshprefix2, SSHSUFFIX = sshsuffix2, LEVZ = levz
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    if KEYWORD_SET(postscript) then openps, filename+'_3.ps', portrait = 1
+
+    title = prefix+' - '+prefix2+' '+d1_d2_2+'!C'+blabla
+    pltt, ts_Sal - ts_Sal2, 't', MIN = -0.1, MAX = 0.1, date1, date2, /REMPLI , XGRIDSTYLE = 1 $
+          , COLOR = 250, small = [1, 2, 1], YTITLE = varunit, TITLE = title, /PORTRAIT, window = 2, _extra = ex
+
+    title = prefix+' - '+prefix2+' '+d1_d2_2+'!C ZT-plot (0-6000m) '+blabla
+    pltt, ts_z - ts_z2, 'zt', MIN = -0.1, MAX = 0.1, INTER = .01, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+          , small = [1, 2, 2], YTITLE = varunit, TITLE = title, boxzoom = 6000., /NOERASE, _extra = ex
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_3.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+
+  ENDIF
+
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_SSH.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_SSH.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_SSH.pro	(revision 14097)
@@ -0,0 +1,48 @@
+pro std_ts_SSH, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vssh = getenv('VAR1_SSH')    &   prefix = getenv('V1SSH_PREF')    &   suffix = getenv('V1SSH_SUFF')
+; get exp2 info
+  vssh2 = getenv('VAR2_SSH')   &   prefix2 = getenv('V2SSH_PREF')   &   suffix2 = getenv('V2SSH_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_SSH_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+;
+  iodir = std_iodir_data
+;
+  ts_SSH = rseries_ncdf(vssh, date1, date2, prefix, suffix, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+  ts_SSH.arr = ts_SSH.arr   &   ts_SSH.unit = 'm'
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, ts_SSH, 't', MIN = -12., MAX = 12., date1, date2, /REMPLI , XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = 'm', TITLE = title, /PORTRAIT, _extra = ex
+  
+  IF prefix NE prefix2 THEN BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    tsave = time
+    ts_SSH2 = rseries_ncdf(vssh2, date1_2, date2_2, prefix2, suffix2, FIRSTONLY = 1 - allrec, direc = 'xy', mask2d = masknp)
+    ts_SSH2.arr = ts_SSH2.arr   &   ts_SSH2.unit = 'm'
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    title = prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+blabla
+    pltt, ts_SSH.arr - ts_SSH2.arr, 't', MIN = -10., MAX = 10., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+          , color = 250, small = [1, 2, 2], YTITLE = 'm', TITLE = title, /noerase, _extra = ex
+
+  ENDIF 
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  
+  return
+end
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_T.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_T.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_T.pro	(revision 14097)
@@ -0,0 +1,84 @@
+pro std_ts_T, masknp, s_iodir_data, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+; get exp1 info
+  vtemp = getenv('VAR1_T')     &   prefix = getenv('V1T_PREF')         &   suffix = getenv('V1T_SUFF')
+  vssh = getenv('VAR1_SSH')    &   sshprefix = getenv('V1SSH_PREF')    &   sshsuffix = getenv('V1SSH_SUFF')
+; get exp2 info
+  vtemp2 = getenv('VAR2_T')    &   prefix2 = getenv('V2T_PREF')        &   suffix2 = getenv('V2T_SUFF')
+  vssh2 = getenv('VAR2_SSH')   &   sshprefix2 = getenv('V2SSH_PREF')   &   sshsuffix2 = getenv('V2SSH_SUFF')
+;
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+  filename = cdti3 + '_ts_T_'+prefix
+  if prefix NE prefix2 then filename = filename + '_'+prefix2
+  if KEYWORD_SET(postscript) then openps, filename+'_1.ps', portrait = 1
+
+  d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+
+; read levitus data
+  std_file_Levitus_T = isafile(getenv('FILE_TEMP_3D'), title = 'Levitus_T', iodir = std_iodir_climato)
+  Lev = read_ncdf(getenv('VAR_TEMP_3D'), filename = std_file_Levitus_T, /nostruct ) 
+  Lev_xyz = moyenne(Lev, 'xyz', mask2d = masknp)
+  levz = moyenne(temporary(Lev), 'xy', mask2d = masknp, /KEEPBOTTOM)
+;
+  iodir = std_iodir_data
+;
+
+; read exp1 data
+  std_ts_read, vtemp, date1, date2, prefix, suffix, ts_Temp, ts_z, masknp $
+               , WITHSSH = vssh, SSHPREFIX = sshprefix, SSHSUFFIX = sshsuffix, LEVZ = levz
+
+  title = prefix+' '+d1_d2+'!C'+blabla
+  pltt, ts_Temp, 't', MIN = 1., MAX = 4.5, date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, /PORTRAIT, _extra = ex
+
+  title = prefix+' '+d1_d2+' - Levitus!C'+blabla
+  pltt, ts_Temp - Lev_xyz, 't', MIN = -1., MAX = 1., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+        , small = [1, 2, 2], YTITLE = varunit, TITLE = title, /NOERASE, _extra = ex
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_1.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+  if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
+
+  title = prefix+' '+d1_d2+' - Levitus!C ZT-plot (0-1500m) '+blabla
+  pltt, ts_z, 'zt', MIN = -2.,MAX = 2., inter = .1, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+        , small = [1, 2, 1], YTITLE = varunit, TITLE = title, boxzoom = 1500., /portrait, window = 1, _extra = ex
+  
+  title = prefix+' '+d1_d2+' - Levitus!C ZT-plot (0-6000m) '+blabla
+  pltt, ts_z, 'zt', MIN = -2., MAX = 2., inter = .1, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+        , small = [1, 2, 2], YTITLE = varunit, TITLE = title, boxzoom = 6000., /NOERASE, _extra = ex
+  
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_2.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  IF prefix NE prefix2 THEN BEGIN
+
+    d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+; read exp2 data
+    tsave = time
+    std_ts_read, vtemp2, date1_2, date2_2, prefix2, suffix2, ts_Temp2, ts_z2, masknp $
+                 , WITHSSH = vssh2, SSHPREFIX = sshprefix2, SSHSUFFIX = sshsuffix2, LEVZ = levz
+    time = tsave   &   IF n_elements(time) NE jpt THEN stop
+
+    if KEYWORD_SET(postscript) then openps, filename+'_3.ps', portrait = 1
+
+    title = prefix+' - '+prefix2+' '+d1_d2_2+'!C'+blabla
+    pltt, ts_Temp - ts_Temp2, 't', MIN = -1., MAX = 1., date1, date2, /REMPLI, XGRIDSTYLE = 1 $
+          , COLOR = 250, small = [1, 2, 1], YTITLE = varunit, TITLE = title, /PORTRAIT, window = 2, _extra = ex
+
+    title = prefix+' - '+prefix2+' '+d1_d2_2+'!C ZT-plot (0-6000m) '+blabla
+    pltt, ts_z - ts_z2, 'zt', MIN = -1., MAX = 1., inter = .1, date1, date2, /REMPLI, style = 'so0so', XGRIDSTYLE = 1 $ 
+          , small = [1, 2, 2], YTITLE = varunit, TITLE = title, boxzoom = 6000., /NOERASE, _extra = ex
+
+    htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'_3.png  />  ' ]
+    if KEYWORD_SET(postscript) then closeps
+    
+  ENDIF
+
+  return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_all.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_all.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_all.pro	(revision 14097)
@@ -0,0 +1,89 @@
+pro std_ts_all, doplot = doplot, _extra=ex
+
+  compile_opt idl2, strictarrsubs
+
+@common
+@std_common
+
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+  PRINT, '                   plot of all TIME SERIES'
+  PRINT, ''
+  PRINT, ' 	############################################'
+  PRINT, ''
+;
+  std_iodir_data    = isadirectory(getenv('DIR_DATA'), title = 'path of data in NetCdf format')
+  std_iodir_climato = isadirectory(getenv('DIR_CLIMATO'), title = 'path of climatological data')
+  std_iodir_mask    = isadirectory(getenv('DIR_MASK'), title = 'path of mask files (ex: subbasins)')
+; meshmask
+  std_file_mesh = isafile(getenv('FILE_MESH_MASK'), title = 'mesh_mask', iodir = std_iodir_mask)
+  std_file_msksub = isafile(getenv('FILE_MASK_SUBDOMAIN'), title = 'sub-bassin masks', iodir = std_iodir_mask)
+; load the grid
+  load_orca, std_file_mesh  
+; reading variables
+  masknp = read_ncdf('tmaskutil', file = std_file_mesh, /nostruct, /cont_nofill)
+; climatologies
+  std_file_Levitus_T =  isafile(getenv('FILE_TEMP_3D'),  title = 'Levitus_T', iodir = std_iodir_climato)
+  std_file_Levitus_S =  isafile(getenv('FILE_SAL_3D'),   title = 'Levitus_S', iodir = std_iodir_climato)
+  std_file_reynolds  =  isafile(getenv('FILE_SST'),      title = 'Reynolds', iodir = std_iodir_climato)
+  std_file_oaflux    =  isafile(getenv('FILE_FLUX'),     title = 'oaflux', iodir = std_iodir_climato)
+  std_file_mld       =  isafile(getenv('FILE_MLD'),      title = 'Mixed layer depth', iodir = std_iodir_climato)
+  std_file_ice       =  isafile(getenv('FILE_ICE'),      title = 'ICE', iodir = std_iodir_climato)
+  std_file_snow_arc  =  isafile(getenv('FILE_SNOW_ARC'), title = 'SNOW_ARC', iodir = std_iodir_climato)
+  std_file_snow_ant  =  isafile(getenv('FILE_SNOW_ANT'), title = 'SNOW_ANT', iodir = std_iodir_climato)
+
+
+  date1   = long(getenv('DATE1'))     &   date2   = long(getenv('DATE2'))
+  date1_2 = long(getenv('DATE1_2'))   &   date2_2 = long(getenv('DATE2_2'))
+
+  allrec =  1 - keyword_set(long(getenv('READ_ONLY_FIRST_RECORD')))
+
+;#########################################################################
+;######################  STANDARD PLOTS   ################################
+;#########################################################################
+
+  IF keyword_set(doplot) EQ 0 THEN doplot = 0
+
+; fixed color tabled
+  lct, 64
+  cnt = 0
+  htmltxt = ''
+;
+  cnt = cnt+1   &   blabla = 'Global Mean Temperature'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_T, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Global Mean Salinity'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_S, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Global Mean SSH'
+  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 EMP'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_EMP, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Drake Transport'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_Drake, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Max AMOC'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_AMOC, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  cnt = cnt+1   &   blabla = 'Sea-Ice Cover'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_ICE, masknp, POSTSCRIPT = postscript, _extra = ex
+;
+  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
+;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
+;
+  IF n_elements(htmltxt) GT 1 THEN putfile, psdir+'std_ts_html_body.txt', htmltxt[1:*]
+
+  return
+END
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_read.pro
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_read.pro	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_read.pro	(revision 14097)
@@ -0,0 +1,44 @@
+PRO std_ts_read, var_name, dt1, dt2, prefix, suffix, ts, ts_z, masknp $
+                 , WITHSSH = withssh, SSHPREFIX = sshprefix, SSHSUFFIX = sshsuffix, LEVZ = levz
+
+  compile_opt idl2, strictarrsubs
+  
+@common
+@std_common
+
+
+  list = rseries_ncdf(var_name, dt1, dt2, prefix, suffix, /fileslist)
+  nfiles = n_elements(list)
+  IF keyword_set(withssh) THEN BEGIN
+    sshlist = rseries_ncdf(withssh, dt1, dt2, sshprefix, sshsuffix, /fileslist)
+    IF nfiles NE n_elements(sshlist) THEN stop
+  ENDIF
+
+  ts = 0.
+  ts_Time = 0.
+  ts_z = fltarr(jpk)
+
+  FOR i = 0, nfiles-1 DO BEGIN
+    IF keyword_set(withssh) THEN ssh = read_ncdf(withssh, allrecords = allrec, filename = sshlist[i], /nostruct)
+    var = read_ncdf(var_name, allrecords = allrec, filename = list[i], /nostruct)
+    ts_Time = [ ts_Time, Time]
+;
+    IF jpt EQ 1 THEN txyz = moyenne(var, 'xyz', mask2d = masknp, ssh = ssh) $
+    ELSE txyz = grossemoyenne(var, 'xyz', mask2d = masknp, ssh = ssh)
+    ts = [ ts, txyz ]
+;
+    IF jpt EQ 1 THEN tz = moyenne(temporary(var), 'xy', mask2d = masknp, ssh = ssh, /KEEPBOTTOM) $
+    ELSE tz = grossemoyenne(temporary(var), 'xy', mask2d = masknp, ssh = ssh, /KEEPBOTTOM)
+    IF keyword_set(levz) THEN ts_z = [ [ts_z], [tz - (levz[*] # replicate(1., jpt))] ] $
+    ELSE ts_z = [ [ts_z], [tz] ]
+  ENDFOR
+
+  time = ts_Time[1:*]           ; remove first record of 0
+  jpt = n_elements(time)
+  
+  ts = ts[1:*]        ; remove first record of 0 
+  ts_z = ts_z[*, 1:*]           ; remove first record of 0
+
+
+return
+end
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh	(revision 14097)
@@ -0,0 +1,133 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+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_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
+#
+# 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 =====================
+#
+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=20501231
+#
+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=20501231
+#
+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 ###############################
+#
+#===================== 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+export VAR1_Ivel    V1Iv_PREF    V1Iv_SUFF
+
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF     V2T_SUFF
+export VAR2_S       V2S_PREF     V2S_SUFF
+export VAR2_SSH     V2SSH_PREF   V2SSH_SUFF
+export VAR2_Q       V2Q_PREF     V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF   V2EMP_SUFF
+export VAR2_U       V2U_PREF     V2U_SUFF
+export VAR2_V       V2V_PREF     V2V_SUFF
+export VAR2_ICE     V2ICE_PREF   V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF    V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF  V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+export VAR2_Ivel    V2Iv_PREF    V2Iv_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh.new_names
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh.new_names	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh.new_names	(revision 14097)
@@ -0,0 +1,136 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+PS_DIR=$( pwd )/ts_sbcmodMV_ps
+PDF_DIR=$( pwd )/ts_sbcmodMV_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_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
+#
+# 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 =====================
+#
+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=20010101    ;   DATE2=20501231
+#DATE1=00010101  		;   DATE2=00101231
+#
+VAR1_T=thetao        ;   V1T_PREF=sbcmodMV      ;   V1T_SUFF=_1Y_grid_T.nc
+VAR1_S=so            ;   V1S_PREF=sbcmodMV      ;   V1S_SUFF=_1Y_grid_T.nc
+VAR1_SSH=zos         ;   V1SSH_PREF=sbcmodMV    ;   V1SSH_SUFF=_1Y_grid_T.nc
+VAR1_Q=tohfls        ;   V1Q_PREF=sbcmodMV      ;   V1Q_SUFF=_1Y_grid_T.nc
+VAR1_EMP=wfo         ;   V1EMP_PREF=sbcmodMV    ;   V1EMP_SUFF=_1Y_grid_T.nc
+VAR1_U=uocetr_eff    ;   V1U_PREF=sbcmodMV      ;   V1U_SUFF=_1Y_grid_U.nc
+VAR1_V=vocetr_eff    ;   V1V_PREF=sbcmodMV      ;   V1V_SUFF=_1Y_grid_V.nc
+VAR1_ICE=siconc      ;   V1ICE_PREF=sbcmodMV    ;   V1ICE_SUFF=_1M_icemod.nc
+VAR1_Ithick=sithic   ;   V1It_PREF=sbcmodMV     ;   V1It_SUFF=_1M_icemod.nc
+VAR1_SNOW=sndept     ;   V1SNOW_PREF=sbcmodMV   ;   V1SNOW_SUFF=_1M_icemod.nc
+VAR1_IvelV=sivelv    ;   V1IvV_PREF=sbcmodMV    ;   V1IvV_SUFF=_1M_icemod.nc
+VAR1_Ivel=sivelo     ;   V1Iv_PREF=sbcmodMV     ;   V1Iv_SUFF=_1M_icemod.nc
+#
+#===================== EXP2 =====================
+#
+#DATE1_2=20010101    ;   DATE2_2=20101231
+DATE1_2=20010101     ;   DATE2_2=20501231
+#
+VAR2_T=thetao        ;   V2T_PREF=sbcmodMV      ;   V2T_SUFF=_1Y_grid_T.nc
+VAR2_S=so            ;   V2S_PREF=sbcmodMV      ;   V2S_SUFF=_1Y_grid_T.nc
+VAR2_SSH=zos         ;   V2SSH_PREF=sbcmodMV    ;   V2SSH_SUFF=_1Y_grid_T.nc
+VAR2_Q=tohfls        ;   V2Q_PREF=sbcmodMV      ;   V2Q_SUFF=_1Y_grid_T.nc
+VAR2_EMP=wfo         ;   V2EMP_PREF=sbcmodMV    ;   V2EMP_SUFF=_1Y_grid_T.nc
+VAR2_U=uocetr_eff    ;   V2U_PREF=sbcmodMV      ;   V2U_SUFF=_1Y_grid_U.nc
+VAR2_V=vocetr_eff    ;   V2V_PREF=sbcmodMV      ;   V2V_SUFF=_1Y_grid_V.nc
+VAR2_ICE=siconc      ;   V2ICE_PREF=sbcmodMV    ;   V2ICE_SUFF=_1M_icemod.nc
+VAR2_Ithick=sithic   ;   V2It_PREF=sbcmodMV     ;   V2It_SUFF=_1M_icemod.nc
+VAR2_SNOW=sndept     ;   V2SNOW_PREF=sbcmodMV   ;   V2SNOW_SUFF=_1M_icemod.nc
+VAR2_IvelV=sivelv    ;   V2IvV_PREF=sbcmodMV    ;   V2IvV_SUFF=_1M_icemod.nc
+VAR2_Ivel=sivelo     ;   V2Iv_PREF=sbcmodMV     ;   V2Iv_SUFF=_1M_icemod.nc
+#
+######################### 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+export VAR1_Ivel    V1Iv_PREF    V1Iv_SUFF
+
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF     V2T_SUFF
+export VAR2_S       V2S_PREF     V2S_SUFF
+export VAR2_SSH     V2SSH_PREF   V2SSH_SUFF
+export VAR2_Q       V2Q_PREF     V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF   V2EMP_SUFF
+export VAR2_U       V2U_PREF     V2U_SUFF
+export VAR2_V       V2V_PREF     V2V_SUFF
+export VAR2_ICE     V2ICE_PREF   V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF    V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF  V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+export VAR2_Ivel    V2Iv_PREF    V2Iv_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example1
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example1	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example1	(revision 14097)
@@ -0,0 +1,128 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+PS_DIR=$( pwd )/ps_tag33_tag331
+PDF_DIR=$( pwd )/pdf_tag33_tag331
+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_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
+#
+# 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 =====================
+#
+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=21001231
+#
+VAR1_T=thetao          ;   V1T_PREF=tmx_2000     ;   V1T_SUFF=_1Y_grid_T.nc
+VAR1_S=so              ;   V1S_PREF=tmx_2000     ;   V1S_SUFF=_1Y_grid_T.nc
+VAR1_SSH=zos           ;   V1SSH_PREF=tmx_2000   ;   V1SSH_SUFF=_1Y_grid_T.nc
+VAR1_Q=qns+qsr         ;   V1Q_PREF=tmx_2000     ;   V1Q_SUFF=_1Y_grid_T.nc
+VAR1_EMP=wfo           ;   V1EMP_PREF=tmx_2000   ;   V1EMP_SUFF=_1Y_grid_T.nc
+VAR1_U=uoce_eff        ;   V1U_PREF=tmx_2000     ;   V1U_SUFF=_1Y_grid_U.nc
+VAR1_V=voce_eff        ;   V1V_PREF=tmx_2000     ;   V1V_SUFF=_1Y_grid_V.nc
+VAR1_ICE=sic           ;   V1ICE_PREF=tmx_2000   ;   V1ICE_SUFF=_1M_icemod.nc
+VAR1_Ithick=sit        ;   V1It_PREF=tmx_2000    ;   V1It_SUFF=_1M_icemod.nc
+VAR1_SNOW=isnowthi     ;   V1SNOW_PREF=tmx_2000  ;   V1SNOW_SUFF=_1M_icemod.nc
+VAR1_IvelV=vice_ipa    ;   V1IvV_PREF=tmx_2000   ;   V1IvV_SUFF=_1M_icemod.nc
+#
+#===================== EXP2 =====================
+#
+DATE1_2=10101   ;   DATE2_2=20001231
+#
+VAR2_T=thetao         ;   V2T_PREF=core2000     ;   V2T_SUFF=_1Y_grid_T.nc
+VAR2_S=so             ;   V2S_PREF=core2000     ;   V2S_SUFF=_1Y_grid_T.nc
+VAR2_SSH=zos          ;   V2SSH_PREF=core2000   ;   V2SSH_SUFF=_1Y_grid_T.nc
+VAR2_Q=qns+qsr        ;   V2Q_PREF=core2000     ;   V2Q_SUFF=_1Y_grid_T.nc
+VAR2_EMP=wfo          ;   V2EMP_PREF=core2000   ;   V2EMP_SUFF=_1Y_grid_T.nc
+VAR2_U=uoce_eff       ;   V2U_PREF=core2000     ;   V2U_SUFF=_1Y_grid_U.nc
+VAR2_V=voce_eff       ;   V2V_PREF=core2000     ;   V2V_SUFF=_1Y_grid_V.nc
+VAR2_ICE=sic          ;   V2ICE_PREF=core2000   ;   V2ICE_SUFF=_1M_icemod.nc
+VAR2_Ithick=sit       ;   V2It_PREF=core2000    ;   V2It_SUFF=_1M_icemod.nc
+VAR2_SNOW=isnowthi    ;   V2ICE_SNOW=core2000   ;   V2SNOW_SUFF=_1M_icemod.nc
+VAR2_IvelV=vice_ipa   ;   V2IvV_PREF=core2000   ;   V2IvV_SUFF=_1M_icemod.nc
+#
+######################### 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF    V2T_SUFF
+export VAR2_S       V2S_PREF    V2S_SUFF
+export VAR2_SSH     V2SSH_PREF  V2SSH_SUFF
+export VAR2_Q       V2Q_PREF    V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF  V2EMP_SUFF
+export VAR2_U       V2U_PREF    V2U_SUFF
+export VAR2_V       V2V_PREF    V2V_SUFF
+export VAR2_ICE     V2ICE_PREF  V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF   V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example2
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example2	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example2	(revision 14097)
@@ -0,0 +1,128 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+PS_DIR=$( pwd )/ps_tag33_tag331
+PDF_DIR=$( pwd )/pdf_tag33_tag331
+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_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
+#
+# 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 =====================
+#
+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=21001231
+#
+VAR1_T=thetao         ;   V1T_PREF=tag33        ;   V1T_SUFF=_1Y_grid_T.nc
+VAR1_S=so             ;   V1S_PREF=tag33        ;   V1S_SUFF=_1Y_grid_T.nc
+VAR1_SSH=zos          ;   V1SSH_PREF=tag33      ;   V1SSH_SUFF=_1Y_grid_T.nc
+VAR1_Q=qt             ;   V1Q_PREF=tag33        ;   V1Q_SUFF=_1Y_grid_T.nc
+VAR1_EMP=wfo          ;   V1EMP_PREF=tag33      ;   V1EMP_SUFF=_1Y_grid_T.nc
+VAR1_U=uocetr_eff     ;   V1U_PREF=tag33        ;   V1U_SUFF=_1Y_grid_U.nc
+VAR1_V=vocetr_eff     ;   V1V_PREF=tag33        ;   V1V_SUFF=_1Y_grid_V.nc
+VAR1_ICE=sic          ;   V1ICE_PREF=tag33      ;   V1ICE_SUFF=_1M_icemod.nc
+VAR1_Ithick=sit       ;   V1It_PREF=tag33       ;   V1It_SUFF=_1M_icemod.nc
+VAR1_SNOW=isnowthi    ;   V1SNOW_PREF=tag33     ;   V1SNOW_SUFF=_1M_icemod.nc
+VAR1_IvelV=vice_ipa   ;   V1IvV_PREF=tag33      ;   V1IvV_SUFF=_1M_icemod.nc
+#
+#===================== EXP2 =====================
+#
+DATE1_2=20010101   ;   DATE2_2=21001231
+#
+VAR2_T=thetao         ;   V2T_PREF=trunk331     ;   V2T_SUFF=_1Y_grid_T.nc
+VAR2_S=so             ;   V2S_PREF=trunk331     ;   V2S_SUFF=_1Y_grid_T.nc
+VAR2_SSH=zos          ;   V2SSH_PREF=trunk331   ;   V2SSH_SUFF=_1Y_grid_T.nc
+VAR2_Q=qt             ;   V2Q_PREF=trunk331     ;   V2Q_SUFF=_1Y_grid_T.nc
+VAR2_EMP=wfo          ;   V2EMP_PREF=trunk331   ;   V2EMP_SUFF=_1Y_grid_T.nc
+VAR2_U=uocetr_eff     ;   V2U_PREF=trunk331     ;   V2U_SUFF=_1Y_grid_U.nc
+VAR2_V=vocetr_eff     ;   V2V_PREF=trunk331     ;   V2V_SUFF=_1Y_grid_V.nc
+VAR2_ICE=sic          ;   V2ICE_PREF=trunk331   ;   V2ICE_SUFF=_1M_icemod.nc
+VAR2_Ithick=sit       ;   V2It_PREF=trunk331    ;   V2It_SUFF=_1M_icemod.nc
+VAR2_SNOW=isnowthi    ;   V2ICE_SNOW=trunk331   ;   V2SNOW_SUFF=_1M_icemod.nc
+VAR2_IvelV=vice_ipa   ;   V2IvV_PREF=trunk331   ;   V2IvV_SUFF=_1M_icemod.nc
+#
+######################### 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF    V2T_SUFF
+export VAR2_S       V2S_PREF    V2S_SUFF
+export VAR2_SSH     V2SSH_PREF  V2SSH_SUFF
+export VAR2_Q       V2Q_PREF    V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF  V2EMP_SUFF
+export VAR2_U       V2U_PREF    V2U_SUFF
+export VAR2_V       V2V_PREF    V2V_SUFF
+export VAR2_ICE     V2ICE_PREF  V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF   V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_ipcc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_ipcc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_ipcc	(revision 14097)
@@ -0,0 +1,133 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+PS_DIR=$( pwd )/ps_tag33_tag331
+PDF_DIR=$( pwd )/pdf_tag33_tag331
+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_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
+#
+# 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 =====================
+#
+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=21001231
+#
+VAR1_T=thetao       ;   V1T_PREF=tag33      ;   V1T_SUFF=_1Y_grid_T.nc
+VAR1_S=so           ;   V1S_PREF=tag33      ;   V1S_SUFF=_1Y_grid_T.nc
+VAR1_SSH=zos        ;   V1SSH_PREF=tag33    ;   V1SSH_SUFF=_1Y_grid_T.nc
+VAR1_Q=qt           ;   V1Q_PREF=tag33      ;   V1Q_SUFF=_1Y_grid_T.nc
+VAR1_EMP=wfo        ;   V1EMP_PREF=tag33    ;   V1EMP_SUFF=_1Y_grid_T.nc
+VAR1_U=uocetr_eff   ;   V1U_PREF=tag33      ;   V1U_SUFF=_1Y_grid_U.nc
+VAR1_V=vocetr_eff   ;   V1V_PREF=tag33      ;   V1V_SUFF=_1Y_grid_V.nc
+VAR1_ICE=sic        ;   V1ICE_PREF=tag33    ;   V1ICE_SUFF=_1M_icemod.nc
+VAR1_Ithick=sit     ;   V1It_PREF=tag33     ;   V1It_SUFF=_1M_icemod.nc
+VAR1_SNOW=isnowthi  ;   V1SNOW_PREF=tag33   ;   V1SNOW_SUFF=_1M_icemod.nc
+VAR1_IvelV=iicevelv ;   V1IvV_PREF=tag33    ;   V1IvV_SUFF=_1M_icemod.nc
+VAR1_Ivel=iicevelo  ;   V1Iv_PREF=tag33     ;   V1Iv_SUFF=_1M_icemod.nc
+#
+#===================== EXP2 =====================
+#
+DATE1_2=20010101    ;   DATE2_2=21001231
+#
+VAR2_T=thetao       ;   V2T_PREF=trunk331      ;   V2T_SUFF=_1Y_grid_T.nc
+VAR2_S=so           ;   V2S_PREF=trunk331      ;   V2S_SUFF=_1Y_grid_T.nc
+VAR2_SSH=zos        ;   V2SSH_PREF=trunk331    ;   V2SSH_SUFF=_1Y_grid_T.nc
+VAR2_Q=qt           ;   V2Q_PREF=trunk331      ;   V2Q_SUFF=_1Y_grid_T.nc
+VAR2_EMP=wfo        ;   V2EMP_PREF=trunk331    ;   V2EMP_SUFF=_1Y_grid_T.nc
+VAR2_U=uocetr_eff   ;   V2U_PREF=trunk331      ;   V2U_SUFF=_1Y_grid_U.nc
+VAR2_V=vocetr_eff   ;   V2V_PREF=trunk331      ;   V2V_SUFF=_1Y_grid_V.nc
+VAR2_ICE=sic        ;   V2ICE_PREF=trunk331    ;   V2ICE_SUFF=_1M_icemod.nc
+VAR2_Ithick=sit     ;   V2It_PREF=trunk331     ;   V2It_SUFF=_1M_icemod.nc
+VAR2_SNOW=isnowthi  ;   V2ICE_SNOW=trunk331    ;   V2SNOW_SUFF=_1M_icemod.nc
+VAR2_IvelV=iicevelv ;   V2IvV_PREF=trunk331    ;   V2IvV_SUFF=_1M_icemod.nc
+VAR2_Ivel=iicevelo  ;   V2Iv_PREF=trunk331     ;   V2Iv_SUFF=_1M_icemod.nc
+#
+######################### 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+export VAR1_Ivel    V1Iv_PREF    V1Iv_SUFF
+
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF     V2T_SUFF
+export VAR2_S       V2S_PREF     V2S_SUFF
+export VAR2_SSH     V2SSH_PREF   V2SSH_SUFF
+export VAR2_Q       V2Q_PREF     V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF   V2EMP_SUFF
+export VAR2_U       V2U_PREF     V2U_SUFF
+export VAR2_V       V2V_PREF     V2V_SUFF
+export VAR2_ICE     V2ICE_PREF   V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF    V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF  V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+export VAR2_Ivel    V2Iv_PREF    V2Iv_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_old_names
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_old_names	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/IDL_scripts/std_ts_vardef.sh_example_old_names	(revision 14097)
@@ -0,0 +1,133 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_ts.sh and std_ts.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_ts_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+idl_command=/Applications/itt/idl64/bin/idl
+#
+PS_DIR=$( pwd )/amax9999_ts_ps
+PDF_DIR=$( pwd )/amax9999_ts_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_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
+#
+# 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 =====================
+#
+READ_ONLY_FIRST_RECORD=0   # if 0 then read all records in files else read only the first reacord in each file
+#
+DATE1=00010101  		;   DATE2=00101231
+#
+VAR1_T=votemper       	;   V1T_PREF=ow_amax9999      ;   V1T_SUFF=_1m_grid_T.nc
+VAR1_S=vosaline        	;   V1S_PREF=ow_amax9999      ;   V1S_SUFF=_1m_grid_T.nc
+VAR1_SSH=sossheig      	;   V1SSH_PREF=ow_amax9999    ;   V1SSH_SUFF=_1m_grid_T.nc
+VAR1_Q=sohefldo        	;   V1Q_PREF=ow_amax9999      ;   V1Q_SUFF=_1m_grid_T.nc
+VAR1_EMP=sowaflup      	;   V1EMP_PREF=ow_amax9999    ;   V1EMP_SUFF=_1m_grid_T.nc
+VAR1_U=uocetr_eff      	;   V1U_PREF=ow_amax9999      ;   V1U_SUFF=_1m_grid_U.nc
+VAR1_V=vocetr_eff   	;   V1V_PREF=ow_amax9999      ;   V1V_SUFF=_1m_grid_V.nc
+VAR1_ICE=iiceconc 	    ;   V1ICE_PREF=ow_amax9999    ;   V1ICE_SUFF=_1m_icemod.nc
+VAR1_Ithick=iicethic    ;   V1It_PREF=ow_amax9999     ;   V1It_SUFF=_1m_icemod.nc
+VAR1_SNOW=isnowthi   	;   V1SNOW_PREF=ow_amax9999   ;   V1SNOW_SUFF=_1m_icemod.nc
+VAR1_IvelV=sivelv       ;   V1IvV_PREF=ow_amax9999    ;   V1IvV_SUFF=_1m_icemod.nc 
+VAR1_Ivel=sivelo        ;   V1Iv_PREF=ow_amax9999     ;   V1Iv_SUFF=_1m_icemod.nc
+#
+#===================== EXP2 =====================
+#
+DATE1_2=00010101   		;   DATE2_2=00101231
+#
+VAR2_T=votemper     	;   V2T_PREF=ow_amax9999     ;   V2T_SUFF=_1m_grid_T.nc
+VAR2_S=vosaline        	;   V2S_PREF=ow_amax9999     ;   V2S_SUFF=_1m_grid_T.nc
+VAR2_SSH=sossheig      	;   V2SSH_PREF=ow_amax9999   ;   V2SSH_SUFF=_1m_grid_T.nc
+VAR2_Q=sohefldo       	;   V2Q_PREF=ow_amax9999     ;   V2Q_SUFF=_1m_grid_T.nc
+VAR2_EMP=sowaflup     	;   V2EMP_PREF=ow_amax9999   ;   V2EMP_SUFF=_1m_grid_T.nc
+VAR2_U=uocetr_eff   	;   V2U_PREF=ow_amax9999     ;   V2U_SUFF=_1m_grid_U.nc
+VAR2_V=vocetr_eff   	;   V2V_PREF=ow_amax9999     ;   V2V_SUFF=_1m_grid_V.nc
+VAR2_ICE=iiceconc     	;   V2ICE_PREF=ow_amax9999   ;   V2ICE_SUFF=_1m_icemod.nc
+VAR2_Ithick=iicethic    ;   V2It_PREF=ow_amax9999    ;   V2It_SUFF=_1m_icemod.nc
+VAR2_SNOW=isnowthi   	;   V2SNOW_PREF=ow_amax9999  ;   V2SNOW_SUFF=_1m_icemod.nc
+VAR2_IvelV=sivelv       ;   V2IvV_PREF=ow_amax9999   ;   V2IvV_SUFF=_1m_icemod.nc 
+VAR2_Ivel=sivelo        ;   V2IvV_PREF=ow_amax9999   ;   V2IvV_SUFF=_1m_icemod.nc 
+#
+######################### 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     VAR_SNOW_NH     VAR_SNOW_SH    VAR_SNOW_area_NH VAR_SNOW_area_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+#
+export DATE1        DATE2
+export VAR1_T       V1T_PREF     V1T_SUFF
+export VAR1_S       V1S_PREF     V1S_SUFF
+export VAR1_SSH     V1SSH_PREF   V1SSH_SUFF
+export VAR1_Q       V1Q_PREF     V1Q_SUFF
+export VAR1_EMP     V1EMP_PREF   V1EMP_SUFF
+export VAR1_U       V1U_PREF     V1U_SUFF
+export VAR1_V       V1V_PREF     V1V_SUFF
+export VAR1_ICE     V1ICE_PREF   V1ICE_SUFF
+export VAR1_Ithick  V1It_PREF    V1It_SUFF
+export VAR1_SNOW    V1SNOW_PREF  V1SNOW_SUFF
+export VAR1_IvelV   V1IvV_PREF   V1IvV_SUFF
+export VAR1_Ivel    V1Iv_PREF    V1Iv_SUFF
+
+#===================== EXP2 =====================
+export DATE1_2      DATE2_2
+export VAR2_T       V2T_PREF     V2T_SUFF
+export VAR2_S       V2S_PREF     V2S_SUFF
+export VAR2_SSH     V2SSH_PREF   V2SSH_SUFF
+export VAR2_Q       V2Q_PREF     V2Q_SUFF
+export VAR2_EMP     V2EMP_PREF   V2EMP_SUFF
+export VAR2_U       V2U_PREF     V2U_SUFF
+export VAR2_V       V2V_PREF     V2V_SUFF
+export VAR2_ICE     V2ICE_PREF   V2ICE_SUFF
+export VAR2_Ithick  V2It_PREF    V2It_SUFF
+export VAR2_SNOW    V2SNOW_PREF  V2SNOW_SUFF
+export VAR2_IvelV   V2IvV_PREF   V2IvV_SUFF
+export VAR2_Ivel    V2Iv_PREF    V2Iv_SUFF
+#
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/cpp_ORCA2_ICE_PISCES.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/cpp_ORCA2_ICE_PISCES.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_ICE_PISCES/cpp_ORCA2_ICE_PISCES.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_si3 key_top key_iomput key_mpp_mpi 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,39 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-pisces.xml"/> <!--  NEMO ocean biology      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-pisces.xml"/>  <!--  NEMO ocean biology       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/field_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-pisces.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/file_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/file_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/file_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,145 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+
+   <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" 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 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="ppo4tot"  name="ppo4tot"   unit="umolP"  > ppo4tot * 1. / 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 -->   
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+
+	<file id="file2" name_suffix="_ptrc_T" description="pisces sms variables" >
+          <field field_ref="DIC"      />
+          <field field_ref="Alkalini" />
+          <field field_ref="O2"       />
+          <field field_ref="PO4"      />
+          <field field_ref="Si"       />
+          <field field_ref="Fer"      />
+          <field field_ref="NCHL"     />
+          <field field_ref="DCHL"     />
+          <field field_ref="NO3"      />
+	</file>
+	
+	<file id="file3" name_suffix="_diad_T" description="additional pisces diagnostics" >
+          <field field_ref="Cflx"     />
+          <field field_ref="Dpco2"    />
+	</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 id="file4" name_suffix="_ptrc_T" description="pisces sms variables" >
+          <field field_ref="DIC"      />
+          <field field_ref="Alkalini" />
+          <field field_ref="O2"       />
+          <field field_ref="CaCO3"    />
+          <field field_ref="PO4"      />
+          <field field_ref="POC"      />
+          <field field_ref="Si"       />
+          <field field_ref="PHY"      />
+          <field field_ref="ZOO"      />
+          <field field_ref="DOC"      />
+          <field field_ref="PHY2"     />
+          <field field_ref="ZOO2"     />
+          <field field_ref="DSi"      />
+          <field field_ref="Fer"      />
+          <field field_ref="BFe"      />
+          <field field_ref="GOC"      />
+          <field field_ref="SFe"      />
+          <field field_ref="DFe"      />
+          <field field_ref="GSi"      />
+          <field field_ref="NFe"      />
+          <field field_ref="NCHL"     />
+          <field field_ref="DCHL"     />
+          <field field_ref="NO3"      />
+          <field field_ref="NH4"      />
+	</file>
+
+	<file id="file5" name_suffix="_diad_T" description="additional pisces diagnostics" >
+          <field field_ref="PH"       />
+          <field field_ref="CO3"      />
+          <field field_ref="CO3sat"   />
+          <field field_ref="PAR"      />
+          <field field_ref="PPPHYN"    />
+          <field field_ref="PPPHYD"   />
+          <field field_ref="PPNEWN"   />
+          <field field_ref="PPNEWD"   />
+          <field field_ref="PBSi"     />
+          <field field_ref="PFeN"     />
+          <field field_ref="PFeD"     />
+          <field field_ref="xfracal"  />
+          <field field_ref="PCAL"     />
+          <field field_ref="DCAL"     />
+          <field field_ref="GRAZ1"    />
+          <field field_ref="GRAZ2"    />
+          <field field_ref="EPC100"   />
+          <field field_ref="EPFE100"  />
+          <field field_ref="EPSI100"  />
+          <field field_ref="EPCAL100" />
+          <field field_ref="Cflx"     />
+          <field field_ref="Oflx"     />
+          <field field_ref="Kg"       />
+          <field field_ref="Dpco2"    />
+          <field field_ref="Dpo2"     />
+          <field field_ref="Heup"     />
+          <field field_ref="Irondep"  />
+          <field field_ref="Ironsed"  />
+          <field field_ref="Ironice"  />
+          <field field_ref="Nfix"     />
+          <field field_ref="MuN"      />
+          <field field_ref="MuD"      />
+          <field field_ref="LNnut"    />
+          <field field_ref="LDnut"    />
+          <field field_ref="LNFe"     />
+          <field field_ref="LDFe"     />
+          <field field_ref="LNlight"  />
+          <field field_ref="LDlight"  />
+          <field field_ref="pdust"    />
+          <field field_ref="Fe3"      />
+          <field field_ref="FeL1"     />
+          <field field_ref="TL1"      />
+          <field field_ref="Sdenit"   />
+          <field field_ref="Totlig"   />
+	</file>
+
+      </file_group>
+      <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>
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,455 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ORCA2 - OFF - TRC configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "PISCES"   !  experience name
+   nn_it000    =       1     !  first time step
+   nn_itend    =    1460     !  last  time step (std 5475)
+   nn_date0    =  19600101   !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
+   nn_stock    =    1460     !  frequency of creation of a restart file (modulo referenced to 1)
+   ln_mskland  = .true.      !  mask land points in NetCDF outputs (costly: + ~15%)
+   ln_cfmeta   = .true.      !  output additional data to netCDF files required for compliance with the CF metadata standard
+   ln_clobber  = .true.      !  clobber (overwrite) an existing file
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 21600.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration           (F => create/check namusr_def)
+      cn_domcfg = "ORCA_R2_zps_domcfg"   ! domain configuration filename
+      !
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  free slip  !   partial slip  !   no slip   ! strong slip
+   rn_shlat    =  2        !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.         !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap   = .true.   !    laplacian operator
+   !
+   !                       !  Direction of action:
+   ln_traldf_iso   = .true.   !  iso-neutral (standard operator)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 20         !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_diffusivity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                             !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+      !                        !  time invariant coefficients:  aht0 = 1/2  Ud*Ld   (lap case) 
+      !                             !                           or   = 1/12 Ud*Ld^3 (blp case)
+      rn_Ud        = 0.018           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+   ln_dynrnf       =  .false.    !  runoffs option enabled (T) or not (F)
+   ln_dynrnf_depth =  .false.    !  runoffs is spread in vertical (T) or not (F)
+!   fwbcorr        = 3.786e-06   !  annual global mean of empmr for ssh correction
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'dyna_grid_T'           ,       120.        , 'votemper'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_sal      = 'dyna_grid_T'           ,       120.        , 'vosaline'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_mld      = 'dyna_grid_T'           ,       120.        , 'somixhgt'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_emp      = 'dyna_grid_T'           ,       120.        , 'sowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_fmf      = 'dyna_grid_T'           ,       120.        , 'iowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ice      = 'dyna_grid_T'           ,       120.        , 'soicecov'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_qsr      = 'dyna_grid_T'           ,       120.        , 'soshfldo'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wnd      = 'dyna_grid_T'           ,       120.        , 'sowindsp'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_uwd      = 'dyna_grid_U'           ,       120.        , 'uocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vwd      = 'dyna_grid_V'           ,       120.        , 'vocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wwd      = 'dyna_grid_W'           ,       120.        , 'wocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_avt      = 'dyna_grid_W'           ,       120.        , 'voddmavs'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ubl      = 'dyna_grid_U'           ,       120.        , 'sobblcox'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vbl      = 'dyna_grid_V'           ,       120.        , 'sobblcoy'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diadct    !   transports through some sections                     (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc    !   assimilation increments                              ('key_asminc')
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_cfg	(revision 14097)
@@ -0,0 +1,134 @@
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+   nrdttrc    =  4        ! time step frequency for biology
+/
+!-----------------------------------------------------------------------
+&namp4zlim     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zlim     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+/ 
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+   nn_pisdmp    =  1460       !  Frequency of Relaxation
+/
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_pisces_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_pisces_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,113 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP1 :  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_top_ref
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   ln_top_euler  = .true.
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  24
+!
+   ln_pisces     =  .true.
+   ln_my_trc     =  .false.
+   ln_age        =  .false.
+   ln_cfc11      =  .false.
+   ln_cfc12      =  .false.
+   ln_c14        =  .false.
+!
+   ln_trcdta     =  .true.  !  Initialisation from data input file (T) or not (F)
+!                !           !                                         !            !                               !
+!                !    name   !           title of the field            !   units    ! initial data from file or not ! 
+   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' ,  .true.
+   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   ,  .true.
+   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' ,  .true.
+   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' ,  .true.
+   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' ,  .false.
+   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' ,  .true.
+   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' ,  .true.
+   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' ,  .false.
+   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' ,  .false.
+   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' ,  .false.
+   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' ,  .false.
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!          !  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_trcdta(1)  = 'data_DIC_nomask'        ,        -12.       ,  'DIC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(2)  = 'data_Alkalini_nomask'   ,        -12.       ,  'Alkalini',    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(3)  = 'data_O2_nomask'         ,        -1.        ,  'O2'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(5)  = 'data_PO4_nomask'        ,        -1.        ,  'PO4'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(7)  = 'data_Si_nomask'         ,        -1.        ,  'Si'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(10) = 'data_DOC_nomask'        ,        -12.       ,  'DOC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(14) = 'data_Fer_nomask'        ,        -12.       ,  'Fer'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(23) = 'data_NO3_nomask'        ,        -1.        ,  'NO3'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   rn_trfac(1)   =   1.0e-06  !  multiplicative factor
+   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(3)   =  44.6e-06  !  -      -      -     -
+   rn_trfac(5)   = 122.0e-06  !  -      -      -     -
+   rn_trfac(7)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(10)  =   1.0      !  -      -      -     -
+   rn_trfac(14)  =   1.0      !  -      -      -     -
+   rn_trfac(23)  =   7.6e-06  !  -      -      -     -
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_mus =  .true.   !  MUSCL scheme
+      ln_mus_ups =  .false.         !  use upstream scheme near river mouths
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   =  .true.     !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_snk      !  sedimentation of particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/cpp_ORCA2_OFF_PISCES.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/cpp_ORCA2_OFF_PISCES.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_PISCES/cpp_ORCA2_OFF_PISCES.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_top key_iomput key_mpp_mpi
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CDIAC.dat
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CDIAC.dat	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CDIAC.dat	(revision 14097)
@@ -0,0 +1,91 @@
+// Source   : https://www.nodc.noaa.gov/ocads/oceans/CFC_ATM_Hist2015.html  
+// Dataset  : CDIAC Atmospheric Histories (1765-2015) for CFC-11, CFC-12, SF6 (Bullister, 2017) 
+// Units    : mole_fraction_of_gas_in_air (ppt) 
+// Gas (Lifetime in yrs): CFC-11 (45) ; CFC-12 (100) ; SF6 (3200) 
+// --------------- 
+// Time    CFC11_NH   CFC11_SH   CFC12_NH   CFC12_SH     SF6_NH     SF6_SH  
+ 1931.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1932.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1933.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1934.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1935.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1936.50     0.0000     0.0000     0.1000     0.0000     0.0000     0.0000
+ 1937.50     0.0000     0.0000     0.1000     0.1000     0.0000     0.0000
+ 1938.50     0.0000     0.0000     0.2000     0.1000     0.0000     0.0000
+ 1939.50     0.0000     0.0000     0.3000     0.2000     0.0000     0.0000
+ 1940.50     0.0000     0.0000     0.4000     0.3000     0.0000     0.0000
+ 1941.50     0.0000     0.0000     0.5000     0.4000     0.0000     0.0000
+ 1942.50     0.0000     0.0000     0.7000     0.5000     0.0000     0.0000
+ 1943.50     0.0000     0.0000     0.9000     0.7000     0.0000     0.0000
+ 1944.50     0.0000     0.0000     1.2000     0.9000     0.0000     0.0000
+ 1945.50     0.1000     0.0000     1.7000     1.2000     0.0000     0.0000
+ 1946.50     0.1000     0.1000     2.3000     1.7000     0.0000     0.0000
+ 1947.50     0.1000     0.1000     3.4000     2.4000     0.0000     0.0000
+ 1948.50     0.2000     0.1000     4.8000     3.4000     0.0000     0.0000
+ 1949.50     0.4000     0.2000     6.1000     4.7000     0.0000     0.0000
+ 1950.50     0.7000     0.4000     7.6000     6.0000     0.0000     0.0000
+ 1951.50     1.0100     0.7000     9.2000     7.4000     0.0000     0.0000
+ 1952.50     1.5100     1.0100    11.0000     9.0000     0.0000     0.0000
+ 1953.50     2.2100     1.5100    12.8000    10.7000     0.0400     0.0400
+ 1954.50     3.0200     2.2100    15.0000    12.6000     0.0400     0.0400
+ 1955.50     4.1200     3.0200    17.4000    14.7000     0.0400     0.0400
+ 1956.50     5.3300     4.0200    20.2000    17.1000     0.0400     0.0400
+ 1957.50     6.8300     5.2300    23.4000    19.9000     0.0500     0.0400
+ 1958.50     8.1400     6.5300    26.8000    23.0000     0.0500     0.0400
+ 1959.50     9.4500     7.8400    30.5000    26.3000     0.0500     0.0500
+ 1960.50    11.0600     9.1500    35.0000    30.1000     0.0500     0.0500
+ 1961.50    13.2700    10.8500    40.0000    34.4000     0.0600     0.0600
+ 1962.50    16.1800    13.0700    45.8000    39.4000     0.0700     0.0600
+ 1963.50    19.6000    15.7800    52.5000    45.1000     0.0800     0.0700
+ 1964.50    23.7200    19.2000    60.4000    51.8000     0.0900     0.0800
+ 1965.50    28.4400    23.1200    69.3000    59.5000     0.1100     0.1000
+ 1966.50    33.6700    27.6400    79.2000    68.2000     0.1300     0.1200
+ 1967.50    39.4000    32.6600    90.3000    77.9000     0.1500     0.1400
+ 1968.50    46.0300    38.2900   102.8000    88.8000     0.1800     0.1700
+ 1969.50    53.7700    44.8200   116.8000   101.1000     0.2100     0.1900
+ 1970.50    62.4100    52.2600   132.0000   114.7000     0.2300     0.2200
+ 1971.50    72.0600    60.7000   148.4000   129.6000     0.2600     0.2400
+ 1972.50    82.7100    69.9500   166.1000   145.7000     0.3000     0.2800
+ 1973.50    94.8700    80.4000   185.8000   163.3000     0.3400     0.3100
+ 1974.50   108.3400    92.1600   207.1000   182.5000     0.3800     0.3500
+ 1975.50   121.4100   104.7200   228.2000   202.9000     0.4400     0.4000
+ 1976.50   133.9700   117.0900   248.1000   223.2000     0.5000     0.4600
+ 1977.50   145.9300   129.3500   266.9000   242.7000     0.5800     0.5300
+ 1978.50   156.5800   140.8000   284.3000   261.2000     0.6600     0.6100
+ 1979.50   168.3400   148.7400   306.1000   273.5000     0.7600     0.7000
+ 1980.50   176.6800   159.3000   323.2000   292.3000     0.8800     0.8100
+ 1981.50   184.3200   167.8400   339.6000   308.8000     1.0000     0.9300
+ 1982.50   191.4600   176.0800   353.4000   325.5000     1.1300     1.0400
+ 1983.50   199.3000   184.5200   369.0000   342.6000     1.2700     1.1700
+ 1984.50   208.0400   192.4600   385.7000   359.4000     1.4000     1.2900
+ 1985.50   217.9900   202.0100   403.4000   378.2000     1.5500     1.4300
+ 1986.50   229.3500   211.3600   424.3000   396.5000     1.7100     1.5800
+ 1987.50   241.6100   222.2100   444.0000   416.3000     1.8800     1.7300
+ 1988.50   252.8600   233.2700   465.4000   435.8000     2.0500     1.8900
+ 1989.50   259.3000   242.1100   483.6000   454.4000     2.2200     2.0500
+ 1990.50   265.8300   251.0600   497.7000   472.7000     2.4100     2.2200
+ 1991.50   268.2400   256.6800   506.0000   487.3000     2.6200     2.4200
+ 1992.50   268.1400   260.8000   516.3000   498.3000     2.8500     2.6300
+ 1993.50   269.5500   262.5100   523.2000   507.0000     3.0900     2.8400
+ 1994.50   269.6500   263.7200   528.5000   514.8000     3.3300     3.0700
+ 1995.50   268.3400   263.2200   533.4000   521.0000     3.5800     3.3000
+ 1996.50   266.9300   262.9100   537.3000   526.5000     3.8600     3.5500
+ 1997.50   265.7300   262.0100   540.1000   530.8000     4.0700     3.8100
+ 1998.50   264.5200   261.0100   542.9000   534.3000     4.2500     4.0100
+ 1999.50   263.1200   259.9000   544.4000   537.2000     4.4800     4.2500
+ 2000.50   261.7100   258.2900   545.9000   539.0000     4.6800     4.4600
+ 2001.50   260.0000   256.9800   546.5000   540.6000     4.9000     4.6500
+ 2002.50   258.1900   255.0800   546.7000   541.3000     5.1400     4.8800
+ 2003.50   256.1800   253.2700   546.7000   541.6000     5.3700     5.0700
+ 2004.50   253.9700   251.3600   545.7000   541.5000     5.5800     5.3000
+ 2005.50   251.9600   249.1500   544.9000   540.7000     5.8000     5.5100
+ 2006.50   249.5500   247.3400   543.1000   539.8000     6.0400     5.7500
+ 2007.50   247.5400   245.0300   541.1000   538.1000     6.3300     6.0300
+ 2008.50   245.6300   243.1200   538.6000   536.2000     6.6200     6.2900
+ 2009.50   243.6100   241.0500   536.1200   533.4700     6.8900     6.5800
+ 2010.50   241.3100   239.1500   533.2600   531.0300     7.2100     6.8700
+ 2011.50   239.4000   236.8400   530.6000   528.5300     7.4600     7.1700
+ 2012.50   236.8900   234.7700   527.2000   526.0000     7.7300     7.4300
+ 2013.50   235.5700   232.8800   525.2200   523.2500     8.0900     7.7300
+ 2014.50   234.9700   231.4900   522.9700   521.0000     8.4000     8.1100
+ 2015.50   234.3600   230.0900   520.7100   518.7400     8.7200     8.5000
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CMIP6.dat
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CMIP6.dat	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/CFCs_CMIP6.dat	(revision 14097)
@@ -0,0 +1,90 @@
+// Source   : http://www.climate-energy-college.net/cmip6  
+// Dataset  : input4MIPs_GHGConcentrations_CMIP_UoM-CMIP-1-1-0_gr3-GMNHSH_0000-2014 
+// Units    : mole_fraction_of_gas_in_air (ppt) 
+// Gas (Lifetime in yrs): CFC-11 (45) ; CFC-12 (100) ; SF6 (3200) 
+// --------------- 
+// Time    CFC11_NH   CFC11_SH   CFC12_NH   CFC12_SH     SF6_NH     SF6_SH  
+ 1931.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1932.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1933.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1934.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1935.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1936.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1937.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1938.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1939.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1940.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1941.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1942.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1943.50     0.0000     0.0000     0.0000     0.0000     0.0000     0.0000
+ 1944.50     0.0000     0.0000     0.0389     0.0000     0.0000     0.0000
+ 1945.50     0.0097     0.0000     0.6632     0.1798     0.0000     0.0000
+ 1946.50     0.1430     0.0237     1.9860     1.2854     0.0000     0.0000
+ 1947.50     0.3792     0.2208     3.1940     2.4761     0.0000     0.0000
+ 1948.50     0.5809     0.4191     4.3875     3.6625     0.0000     0.0000
+ 1949.50     0.7827     0.6174     5.5813     4.8488     0.0005     0.0000
+ 1950.50     0.9846     0.8032     6.7696     5.9949     0.0038     0.0000
+ 1951.50     1.2843     1.0094     8.2644     7.2863     0.0094     0.0015
+ 1952.50     1.7519     1.3561     9.9730     8.9158     0.0194     0.0106
+ 1953.50     2.3962     1.8627    11.8029    10.6238     0.0294     0.0206
+ 1954.50     3.1975     2.5297    13.8700    12.5378     0.0394     0.0306
+ 1955.50     4.1818     3.3538    16.1926    14.6867     0.0494     0.0406
+ 1956.50     5.4084     4.3932    18.8780    17.1363     0.0594     0.0506
+ 1957.50     6.8006     5.6782    21.9592    19.9959     0.0694     0.0606
+ 1958.50     8.1092     7.0252    25.2321    23.1365     0.0794     0.0706
+ 1959.50     9.3648     8.2294    28.7821    26.4360     0.0900     0.0800
+ 1960.50    10.9617     9.5125    32.9815    30.2292     0.1033     0.0867
+ 1961.50    13.0988    11.2369    37.7986    34.6748     0.1194     0.1006
+ 1962.50    15.8065    13.4733    43.2782    39.6754     0.1421     0.1179
+ 1963.50    19.1422    16.2919    49.7137    45.4955     0.1644     0.1456
+ 1964.50    23.1083    19.7350    57.2452    52.3544     0.1888     0.1712
+ 1965.50    27.6347    23.7849    65.7934    60.2646     0.2088     0.1912
+ 1966.50    32.6658    28.3416    75.3530    69.1428     0.2299     0.2101
+ 1967.50    38.3166    33.4164    86.1078    79.1125     0.2554     0.2246
+ 1968.50    44.7353    39.1430    98.1830    90.3364     0.2805     0.2595
+ 1969.50    52.1513    45.6939   111.6563   102.9221     0.3127     0.2873
+ 1970.50    60.6132    53.2933   126.4224   116.8759     0.3385     0.3115
+ 1971.50    69.8971    61.7959   142.2978   131.9786     0.3704     0.3396
+ 1972.50    80.2349    71.1069   159.4922   148.2202     0.4067     0.3733
+ 1973.50    92.0607    81.6845   178.4721   166.0425     0.4440     0.4059
+ 1974.50   105.1788    93.8990   199.2271   185.9014     0.4803     0.4397
+ 1975.50   117.9118   106.7517   219.8109   206.6596     0.5239     0.4761
+ 1976.50   130.3438   119.1177   239.4081   226.5863     0.5723     0.5165
+ 1977.50   142.2200   131.3714   258.2146   245.7738     0.6264     0.5627
+ 1978.50   153.1134   142.8958   276.0173   263.9851     0.6962     0.6238
+ 1979.50   162.2028   153.0742   292.3476   280.6407     0.8121     0.7279
+ 1980.50   170.5498   161.6052   307.8804   296.4841     0.9350     0.8449
+ 1981.50   179.3513   170.1257   324.9629   313.8773     1.0467     0.9533
+ 1982.50   187.9503   178.6046   340.5308   329.7557     1.1699     1.0701
+ 1983.50   196.7353   185.5994   357.7383   347.2739     1.2912     1.1888
+ 1984.50   204.7625   195.1718   371.8763   361.7221     1.4169     1.3031
+ 1985.50   215.8735   212.1934   388.1887   378.3458     1.5618     1.4381
+ 1986.50   227.5221   217.1573   407.1783   397.6461     1.7160     1.5839
+ 1987.50   240.1905   226.4808   427.9579   418.7369     1.8697     1.7303
+ 1988.50   252.0584   237.5931   453.7782   444.8680     2.0444     1.8956
+ 1989.50   262.0493   251.1293   472.3727   463.7717     2.2289     2.0710
+ 1990.50   267.5756   258.5948   486.9013   478.6108     2.4359     2.2640
+ 1991.50   271.2310   264.3494   497.7744   489.7940     2.6542     2.4657
+ 1992.50   273.8311   267.7208   509.7028   502.0332     2.8665     2.6735
+ 1993.50   273.9458   268.3918   515.6682   508.3080     3.0855     2.8944
+ 1994.50   271.7952   267.4604   521.7385   514.6896     3.3091     3.1109
+ 1995.50   269.6854   266.5223   528.0264   521.2878     3.5424     3.3176
+ 1996.50   268.0736   265.4381   534.5837   528.2323     3.7731     3.5468
+ 1997.50   266.4531   264.1306   537.7316   532.1944     3.9942     3.7858
+ 1998.50   264.9137   262.8540   540.0532   535.2809     4.2065     4.0135
+ 1999.50   263.4598   261.6319   542.0468   538.2392     4.4461     4.2712
+ 2000.50   262.1325   260.2072   544.1802   540.5858     4.6513     4.4764
+ 2001.50   260.4715   258.6281   544.8814   541.5086     4.8658     4.6879
+ 2002.50   258.4897   256.8479   545.0656   542.2464     5.0800     4.9010
+ 2003.50   256.1665   254.6592   544.6391   542.0629     5.3020     5.1137
+ 2004.50   253.8825   252.5051   543.9137   541.7823     5.5307     5.3397
+ 2005.50   251.6731   250.1566   543.1487   541.1432     5.7538     5.5583
+ 2006.50   249.4018   247.9278   541.5136   539.7864     5.9925     5.7912
+ 2007.50   247.1505   245.6772   539.3451   537.5069     6.2679     6.0601
+ 2008.50   245.2019   243.7518   537.3547   535.3132     6.5649     6.3421
+ 2009.50   243.1215   241.8001   534.7938   532.7581     6.8439     6.6128
+ 2010.50   241.1162   239.7874   532.2179   530.3461     7.1274     6.8930
+ 2011.50   238.9335   237.5581   529.4227   527.6433     7.4222     7.1925
+ 2012.50   236.8707   235.5429   526.6390   525.0289     7.7157     7.4813
+ 2013.50   235.1576   233.6041   523.8412   522.3888     8.0341     7.7876
+ 2014.50   234.0237   232.1361   521.3281   519.8338     8.3456     8.0972
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/atmc14.dat
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/atmc14.dat	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/atmc14.dat	(revision 14097)
@@ -0,0 +1,245 @@
+ Year    South 30S-30N   North 
+ 1765.5       0        0      0
+ 1766.5       0        0      0
+ 1767.5       0        0      0
+ 1768.5       0        0      0
+ 1769.5       0        0      0
+ 1770.5       0        0      0
+ 1771.5       0        0      0
+ 1772.5       0        0      0
+ 1773.5       0        0      0
+ 1774.5       0        0      0
+ 1775.5       0        0      0
+ 1776.5       0        0      0
+ 1777.5       0        0      0
+ 1778.5       0        0      0
+ 1779.5       0        0      0
+ 1780.5       0        0      0
+ 1781.5       0        0      0
+ 1782.5       0        0      0
+ 1783.5       0        0      0
+ 1784.5       0        0      0
+ 1785.5       0        0      0
+ 1786.5       0        0      0
+ 1787.5       0        0      0
+ 1788.5       0        0      0
+ 1789.5       0        0      0
+ 1790.5       0        0      0
+ 1791.5       0        0      0
+ 1792.5       0        0      0
+ 1793.5       0        0      0
+ 1794.5       0        0      0
+ 1795.5       0        0      0
+ 1796.5       0        0      0
+ 1797.5       0        0      0
+ 1798.5       0        0      0
+ 1799.5       0        0      0
+ 1800.5       0        0      0
+ 1801.5       0        0      0
+ 1802.5       0        0      0
+ 1803.5       0        0      0
+ 1804.5       0        0      0
+ 1805.5       0        0      0
+ 1806.5       0        0      0
+ 1807.5       0        0      0
+ 1808.5       0        0      0
+ 1809.5       0        0      0
+ 1810.5       0        0      0
+ 1811.5       0        0      0
+ 1812.5       0        0      0
+ 1813.5       0        0      0
+ 1814.5       0        0      0
+ 1815.5       0        0      0
+ 1816.5       0        0      0
+ 1817.5       0        0      0
+ 1818.5       0        0      0
+ 1819.5       0        0      0
+ 1820.5       0        0      0
+ 1821.5       0        0      0
+ 1822.5       0        0      0
+ 1823.5       0        0      0
+ 1824.5       0        0      0
+ 1825.5       0        0      0
+ 1826.5       0        0      0
+ 1827.5       0        0      0
+ 1828.5       0        0      0
+ 1829.5       0        0      0
+ 1830.5       0        0      0
+ 1831.5       0        0      0
+ 1832.5       0        0      0
+ 1833.5       0        0      0
+ 1834.5       0        0      0
+ 1835.5       0        0      0
+ 1836.5       0        0      0
+ 1837.5       0        0      0
+ 1838.5       0        0      0
+ 1839.5       0        0      0
+ 1840.5    -0.9     -0.9   -0.9
+ 1841.5      -1       -1     -1
+ 1842.5    -1.2     -1.2   -1.2
+ 1843.5    -1.3     -1.3   -1.3
+ 1844.5    -1.5     -1.5   -1.5
+ 1845.5    -1.6     -1.6   -1.6
+ 1846.5    -1.7     -1.7   -1.7
+ 1847.5    -1.9     -1.9   -1.9
+ 1848.5      -2       -2     -2
+ 1849.5    -2.2     -2.2   -2.2
+ 1850.5    -2.3     -2.3   -2.3
+ 1851.5    -2.5     -2.5   -2.5
+ 1852.5    -2.6     -2.6   -2.6
+ 1853.5    -2.8     -2.8   -2.8
+ 1854.5      -3       -3     -3
+ 1855.5    -3.1     -3.1   -3.1
+ 1856.5    -3.3     -3.3   -3.3
+ 1857.5    -3.6     -3.6   -3.6
+ 1858.5    -3.8     -3.8   -3.8
+ 1859.5      -4       -4     -4
+ 1860.5    -4.2     -4.2   -4.2
+ 1861.5    -4.5     -4.5   -4.5
+ 1862.5    -4.7     -4.7   -4.7
+ 1863.5    -4.9     -4.9   -4.9
+ 1864.5    -5.2     -5.2   -5.2
+ 1865.5    -5.4     -5.4   -5.4
+ 1866.5    -5.4     -5.4   -5.4
+ 1867.5    -5.4     -5.4   -5.4
+ 1868.5    -5.4     -5.4   -5.4
+ 1869.5    -5.4     -5.4   -5.4
+ 1870.5    -5.4     -5.4   -5.4
+ 1871.5    -5.3     -5.3   -5.3
+ 1872.5    -5.3     -5.3   -5.3
+ 1873.5    -5.3     -5.3   -5.3
+ 1874.5    -5.3     -5.3   -5.3
+ 1875.5    -5.3     -5.3   -5.3
+ 1876.5    -5.3     -5.3   -5.3
+ 1877.5    -5.3     -5.3   -5.3
+ 1878.5    -5.2     -5.2   -5.2
+ 1879.5    -5.2     -5.2   -5.2
+ 1880.5    -5.2     -5.2   -5.2
+ 1881.5    -5.2     -5.2   -5.2
+ 1882.5    -5.2     -5.2   -5.2
+ 1883.5    -5.1     -5.1   -5.1
+ 1884.5    -5.1     -5.1   -5.1
+ 1885.5    -5.1     -5.1   -5.1
+ 1886.5    -4.9     -4.9   -4.9
+ 1887.5    -4.8     -4.8   -4.8
+ 1888.5    -4.6     -4.6   -4.6
+ 1889.5    -4.5     -4.5   -4.5
+ 1890.5      -7     -4.5     -2
+ 1891.5      -7     -4.5     -2
+ 1892.5      -7     -4.5     -2
+ 1893.5      -7     -4.5     -2
+ 1894.5      -7     -4.5     -2
+ 1895.5      -7     -4.5     -2
+ 1896.5    -7.3     -4.8   -2.3
+ 1897.5    -7.7     -5.2   -2.7
+ 1898.5      -8     -5.5     -3
+ 1899.5    -8.3     -5.8   -3.3
+ 1900.5    -8.7     -6.2   -3.7
+ 1901.5      -9     -6.5     -4
+ 1902.5    -9.3     -6.8   -4.3
+ 1903.5    -9.7     -7.2   -4.7
+ 1904.5     -10     -7.5     -5
+ 1905.5   -10.3     -7.8   -5.3
+ 1906.5   -10.7     -8.2   -5.7
+ 1907.5     -11     -8.5     -6
+ 1908.5   -11.3     -8.8   -6.3
+ 1909.5   -11.7     -9.2   -6.7
+ 1910.5     -12     -9.5     -7
+ 1911.5   -12.3     -9.8   -7.3
+ 1912.5   -12.7    -10.2   -7.7
+ 1913.5     -13    -10.5     -8
+ 1914.5   -13.3    -10.8   -8.3
+ 1915.5   -13.7    -11.2   -8.7
+ 1916.5     -14    -11.5     -9
+ 1917.5   -14.3    -11.8   -9.3
+ 1918.5   -14.7    -12.2   -9.7
+ 1919.5     -15    -12.5    -10
+ 1920.5   -15.3    -12.8  -10.3
+ 1921.5   -15.7    -13.2  -10.7
+ 1922.5     -16    -13.5    -11
+ 1923.5   -16.3    -13.8  -11.3
+ 1924.5   -16.7    -14.2  -11.7
+ 1925.5     -17    -14.5    -12
+ 1926.5   -17.3    -14.8  -12.3
+ 1927.5   -17.7    -15.2  -12.7
+ 1928.5     -18    -15.5    -13
+ 1929.5   -18.3    -15.8  -13.3
+ 1930.5   -18.7    -16.2  -13.7
+ 1931.5     -19    -16.5    -14
+ 1932.5   -19.3    -16.8  -14.3
+ 1933.5   -19.7    -17.2  -14.7
+ 1934.5     -20    -17.5    -15
+ 1935.5   -20.3    -17.8  -15.3
+ 1936.5   -20.7    -18.2  -15.7
+ 1937.5     -21    -18.5    -16
+ 1938.5   -21.3    -18.8  -16.3
+ 1939.5   -21.7    -19.2  -16.7
+ 1940.5   -22.2    -21.5  -20.2
+ 1941.5   -21.4    -20.8  -19.4
+ 1942.5   -21.6      -21  -19.6
+ 1943.5   -24.5    -23.9  -22.5
+ 1944.5   -23.7      -23  -21.7
+ 1945.5   -24.1    -23.4  -22.1
+ 1946.5   -23.6    -22.8  -21.6
+ 1947.5   -23.1    -22.2  -21.1
+ 1948.5   -24.3    -23.4  -22.3
+ 1949.5   -26.6    -25.9  -24.6
+ 1950.5   -26.8    -26.1  -24.8
+ 1951.5   -26.8      -26  -24.8
+ 1952.5   -26.9    -25.7  -24.9
+ 1953.5   -25.9    -23.5  -23.9
+ 1954.5   -23.8    -14.4  -21.1
+ 1955.5     -11     -6.4   -8.2
+ 1956.5    14.7     23.4   26.5
+ 1957.5    35.8     51.9     73
+ 1958.5    81.8    105.7  140.2
+ 1959.5   141.1    176.8    228
+ 1960.5   185.6    200.3  212.3
+ 1961.5   198.7    205.8  221.6
+ 1962.5   215.9    256.2  358.5
+ 1963.5   330.6    474.3  718.3
+ 1964.5   520.6    672.3  835.7
+ 1965.5   637.3    697.5  756.3
+ 1966.5   619.7    658.5  691.9
+ 1967.5   585.6    605.4  623.6
+ 1968.5   549.7    559.6  564.5
+ 1969.5   528.5    537.1  545.4
+ 1970.5     506    519.1  529.1
+ 1971.5     489    495.4  499.4
+ 1972.5   461.6    466.6  465.6
+ 1973.5   430.9    426.1  418.6
+ 1974.5   394.9    400.7  400.8
+ 1975.5   378.2    378.7  369.8
+ 1976.5   349.8    354.4  352.5
+ 1977.5   326.7      330  333.9
+ 1978.5   310.2    320.6  325.8
+ 1979.5     291    296.1  295.8
+ 1980.5   274.8      272  264.5
+ 1981.5   257.5    254.8  256.7
+ 1982.5   241.1    241.1  238.3
+ 1983.5   221.5      225  224.2
+ 1984.5   206.7    209.7  209.3
+ 1985.5   197.1      204  201.1
+ 1986.5   187.4    193.9  191.1
+ 1987.5   175.5    186.5  183.6
+ 1988.5   171.6    177.6  174.7
+ 1989.5   157.3    166.6  163.7
+ 1990.5   148.3    155.1  152.2
+ 1991.5   141.2    145.3  142.4
+ 1992.5   132.2    137.6  136.3
+ 1993.5   127.2    131.8  128.7
+ 1994.5   120.4    125.5  122.1
+ 1995.5   114.9      120  115.8
+ 1996.5   110.3    109.6  109.8
+ 1997.5   105.2    109.7    104
+ 1998.5   100.2    103.2  100.3
+ 1999.5    92.7     98.6   95.7
+ 2000.5    86.5     92.6   89.7
+ 2001.5    80.7     87.6   84.8
+ 2002.5    72.9     80.4   77.5
+ 2003.5    79.5     77.4   73.5
+ 2004.5    77.7       75   70.6
+ 2005.5    75.7       73     67
+ 2006.5      75       72     66
+ 2007.5      74       71     65
+ 2008.5      73       70     64
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,39 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-innerttrc.xml"/> <!--  NEMO ocean biology      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-innerttrc.xml"/>  <!--  NEMO ocean biology       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-innerttrc.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-innerttrc.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-innerttrc.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-innerttrc.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/file_def_nemo-innerttrc.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/file_def_nemo-innerttrc.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/file_def_nemo-innerttrc.xml	(revision 14097)
@@ -0,0 +1,48 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+
+   <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" 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>
+
+      <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>
+      <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 id="file1" name_suffix="_ptrc_T" description="passive tracers variables" >
+           <field field_ref="Age"    />
+           <field field_ref="CFC11"  />
+           <field field_ref="CFC12"  />
+           <field field_ref="SF6"    />
+           <field field_ref="RC14"   />
+         </file>
+
+      </file_group>
+      <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>
+   
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,453 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ORCA2 - OFF - TRC configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "TRACERS"  !  experience name
+   nn_it000    =       1     !  first time step
+   nn_itend    =    14600    !  last  time step (std 5475)
+   nn_date0    =  19600101   !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
+   nn_stock    =    14600    !  frequency of creation of a restart file (modulo referenced to 1)
+   ln_mskland  = .true.      !  mask land points in NetCDF outputs (costly: + ~15%)
+   ln_cfmeta   = .true.      !  output additional data to netCDF files required for compliance with the CF metadata standard
+   ln_clobber  = .true.      !  clobber (overwrite) an existing file
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 21600.     !  time step for the dynamics and tracer
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration           (F => create/check namusr_def)
+      cn_domcfg = "ORCA_R2_zps_domcfg"   ! domain configuration filename
+      !
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  free slip  !   partial slip  !   no slip   ! strong slip
+   rn_shlat    =  2        !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.         !  = Use EOS80
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap   = .true.   !    laplacian operator
+   !
+   !                       !  Direction of action:
+   ln_traldf_iso   = .true.   !  iso-neutral (standard operator)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 20         !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_diffusivity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                             !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+      !                        !  time invariant coefficients:  aht0 = 1/2  Ud*Ld   (lap case) 
+      !                             !                           or   = 1/12 Ud*Ld^3 (blp case)
+      rn_Ud        = 0.018           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+   ln_dynrnf       =  .false.    !  runoffs option enabled (T) or not (F)
+   ln_dynrnf_depth =  .false.    !  runoffs is spread in vertical (T) or not (F)
+!   fwbcorr        = 3.786e-06   !  annual global mean of empmr for ssh correction
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'dyna_grid_T'           ,       120.        , 'votemper'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_sal      = 'dyna_grid_T'           ,       120.        , 'vosaline'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_mld      = 'dyna_grid_T'           ,       120.        , 'somixhgt'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_emp      = 'dyna_grid_T'           ,       120.        , 'sowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_fmf      = 'dyna_grid_T'           ,       120.        , 'iowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ice      = 'dyna_grid_T'           ,       120.        , 'soicecov'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_qsr      = 'dyna_grid_T'           ,       120.        , 'soshfldo'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wnd      = 'dyna_grid_T'           ,       120.        , 'sowindsp'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_uwd      = 'dyna_grid_U'           ,       120.        , 'uocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vwd      = 'dyna_grid_V'           ,       120.        , 'vocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wwd      = 'dyna_grid_W'           ,       120.        , 'wocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_avt      = 'dyna_grid_W'           ,       120.        , 'voddmavs'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ubl      = 'dyna_grid_U'           ,       120.        , 'sobblcox'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vbl      = 'dyna_grid_V'           ,       120.        , 'sobblcoy'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               ("key_diaharm")
+!!   namdct       transports through some sections                      ("key_diadct")
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              ("key_diaharm")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdct        ! transports through some sections                       ("key_diadct")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc    !   assimilation increments                              ('key_asminc')
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,62 @@
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   ln_top_euler = .true.
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  0           !  Number of passive tracers of the BGC model
+!
+   ln_pisces     =  .false.     !  Run PISCES BGC model
+   ln_my_trc     =  .false.     !  Run MY_TRC BGC model
+   ln_age        =  .true.      !  Run the sea water age tracer
+   ln_cfc11      =  .true.      !  Run the CFC11 passive tracer
+   ln_cfc12      =  .true.      !  Run the CFC12 passive tracer
+   ln_sf6        =  .true.      !  Run the SF6 passive tracer
+   ln_c14        =  .true.      !  Run the Radiocarbon passive tracer
+/
+!-----------------------------------------------------------------------
+&namage         !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_fct =  .true.  !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   =  .true.     !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_cfg	(revision 14097)
@@ -0,0 +1,16 @@
+!-----------------------------------------------------------------------
+&namcfc     !   CFC 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc14_typ     !  C14 - type of C14 tracer, default values of C14/C and pco2
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc14_sbc     !  C14 - surface BC
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc14_fcg     !  files & dates
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/namelist_trc_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_trc_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/splco2.dat
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/splco2.dat	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/EXPREF/splco2.dat	(revision 14097)
@@ -0,0 +1,482 @@
+#  4  452
+#   Weighted smoothing spline fit
+# Ice core and Mauna Loa CO2                                       
+# 50% attenuation at     23.4968    ; REG =     100.000 
+#     Time     Smoothed data   
+ 1765.0  277.9514
+ 1765.5  277.9652
+ 1766.0  277.9797
+ 1766.5  277.9949
+ 1767.0  278.0108
+ 1767.5  278.0275
+ 1768.0  278.0448
+ 1768.5  278.0628
+ 1769.0  278.0816
+ 1769.5  278.1011
+ 1770.0  278.1213
+ 1770.5  278.1423
+ 1771.0  278.1640
+ 1771.5  278.1864
+ 1772.0  278.2096
+ 1772.5  278.2335
+ 1773.0  278.2581
+ 1773.5  278.2835
+ 1774.0  278.3097
+ 1774.5  278.3366
+ 1775.0  278.3642
+ 1775.5  278.3927
+ 1776.0  278.4218
+ 1776.5  278.4518
+ 1777.0  278.4825
+ 1777.5  278.5140
+ 1778.0  278.5463
+ 1778.5  278.5793
+ 1779.0  278.6132
+ 1779.5  278.6478
+ 1780.0  278.6832
+ 1780.5  278.7194
+ 1781.0  278.7564
+ 1781.5  278.7942
+ 1782.0  278.8327
+ 1782.5  278.8721
+ 1783.0  278.9123
+ 1783.5  278.9533
+ 1784.0  278.9951
+ 1784.5  279.0378
+ 1785.0  279.0812
+ 1785.5  279.1255
+ 1786.0  279.1706
+ 1786.5  279.2165
+ 1787.0  279.2633
+ 1787.5  279.3109
+ 1788.0  279.3593
+ 1788.5  279.4085
+ 1789.0  279.4586
+ 1789.5  279.5096
+ 1790.0  279.5614
+ 1790.5  279.6140
+ 1791.0  279.6676
+ 1791.5  279.7219
+ 1792.0  279.7772
+ 1792.5  279.8332
+ 1793.0  279.8902
+ 1793.5  279.9480
+ 1794.0  280.0067
+ 1794.5  280.0662
+ 1795.0  280.1266
+ 1795.5  280.1878
+ 1796.0  280.2499
+ 1796.5  280.3129
+ 1797.0  280.3767
+ 1797.5  280.4414
+ 1798.0  280.5069
+ 1798.5  280.5732
+ 1799.0  280.6401
+ 1799.5  280.7077
+ 1800.0  280.7759
+ 1800.5  280.8447
+ 1801.0  280.9139
+ 1801.5  280.9836
+ 1802.0  281.0537
+ 1802.5  281.1241
+ 1803.0  281.1948
+ 1803.5  281.2657
+ 1804.0  281.3369
+ 1804.5  281.4081
+ 1805.0  281.4794
+ 1805.5  281.5508
+ 1806.0  281.6221
+ 1806.5  281.6933
+ 1807.0  281.7644
+ 1807.5  281.8354
+ 1808.0  281.9060
+ 1808.5  281.9764
+ 1809.0  282.0465
+ 1809.5  282.1161
+ 1810.0  282.1853
+ 1810.5  282.2540
+ 1811.0  282.3222
+ 1811.5  282.3897
+ 1812.0  282.4566
+ 1812.5  282.5228
+ 1813.0  282.5882
+ 1813.5  282.6528
+ 1814.0  282.7166
+ 1814.5  282.7794
+ 1815.0  282.8412
+ 1815.5  282.9021
+ 1816.0  282.9619
+ 1816.5  283.0205
+ 1817.0  283.0779
+ 1817.5  283.1343
+ 1818.0  283.1896
+ 1818.5  283.2438
+ 1819.0  283.2971
+ 1819.5  283.3495
+ 1820.0  283.4011
+ 1820.5  283.4519
+ 1821.0  283.5020
+ 1821.5  283.5513
+ 1822.0  283.6001
+ 1822.5  283.6483
+ 1823.0  283.6959
+ 1823.5  283.7432
+ 1824.0  283.7900
+ 1824.5  283.8365
+ 1825.0  283.8827
+ 1825.5  283.9286
+ 1826.0  283.9745
+ 1826.5  284.0201
+ 1827.0  284.0658
+ 1827.5  284.1115
+ 1828.0  284.1573
+ 1828.5  284.2032
+ 1829.0  284.2494
+ 1829.5  284.2958
+ 1830.0  284.3426
+ 1830.5  284.3898
+ 1831.0  284.4375
+ 1831.5  284.4857
+ 1832.0  284.5346
+ 1832.5  284.5842
+ 1833.0  284.6345
+ 1833.5  284.6856
+ 1834.0  284.7376
+ 1834.5  284.7906
+ 1835.0  284.8445
+ 1835.5  284.8995
+ 1836.0  284.9557
+ 1836.5  285.0131
+ 1837.0  285.0718
+ 1837.5  285.1318
+ 1838.0  285.1932
+ 1838.5  285.2561
+ 1839.0  285.3206
+ 1839.5  285.3866
+ 1840.0  285.4543
+ 1840.5  285.5233
+ 1841.0  285.5936
+ 1841.5  285.6647
+ 1842.0  285.7366
+ 1842.5  285.8088
+ 1843.0  285.8812
+ 1843.5  285.9535
+ 1844.0  286.0255
+ 1844.5  286.0971
+ 1845.0  286.1683
+ 1845.5  286.2390
+ 1846.0  286.3091
+ 1846.5  286.3786
+ 1847.0  286.4475
+ 1847.5  286.5157
+ 1848.0  286.5831
+ 1848.5  286.6498
+ 1849.0  286.7157
+ 1849.5  286.7808
+ 1850.0  286.8451
+ 1850.5  286.9087
+ 1851.0  286.9714
+ 1851.5  287.0332
+ 1852.0  287.0943
+ 1852.5  287.1544
+ 1853.0  287.2138
+ 1853.5  287.2722
+ 1854.0  287.3298
+ 1854.5  287.3865
+ 1855.0  287.4423
+ 1855.5  287.4972
+ 1856.0  287.5515
+ 1856.5  287.6052
+ 1857.0  287.6583
+ 1857.5  287.7111
+ 1858.0  287.7635
+ 1858.5  287.8158
+ 1859.0  287.8680
+ 1859.5  287.9202
+ 1860.0  287.9725
+ 1860.5  288.0250
+ 1861.0  288.0778
+ 1861.5  288.1310
+ 1862.0  288.1848
+ 1862.5  288.2392
+ 1863.0  288.2942
+ 1863.5  288.3501
+ 1864.0  288.4070
+ 1864.5  288.4648
+ 1865.0  288.5238
+ 1865.5  288.5840
+ 1866.0  288.6455
+ 1866.5  288.7084
+ 1867.0  288.7726
+ 1867.5  288.8382
+ 1868.0  288.9053
+ 1868.5  288.9737
+ 1869.0  289.0437
+ 1869.5  289.1151
+ 1870.0  289.1880
+ 1870.5  289.2624
+ 1871.0  289.3384
+ 1871.5  289.4160
+ 1872.0  289.4954
+ 1872.5  289.5764
+ 1873.0  289.6592
+ 1873.5  289.7439
+ 1874.0  289.8304
+ 1874.5  289.9188
+ 1875.0  290.0092
+ 1875.5  290.1014
+ 1876.0  290.1957
+ 1876.5  290.2918
+ 1877.0  290.3899
+ 1877.5  290.4898
+ 1878.0  290.5917
+ 1878.5  290.6954
+ 1879.0  290.8010
+ 1879.5  290.9083
+ 1880.0  291.0174
+ 1880.5  291.1281
+ 1881.0  291.2405
+ 1881.5  291.3543
+ 1882.0  291.4697
+ 1882.5  291.5864
+ 1883.0  291.7044
+ 1883.5  291.8237
+ 1884.0  291.9442
+ 1884.5  292.0658
+ 1885.0  292.1885
+ 1885.5  292.3122
+ 1886.0  292.4368
+ 1886.5  292.5622
+ 1887.0  292.6884
+ 1887.5  292.8154
+ 1888.0  292.9430
+ 1888.5  293.0711
+ 1889.0  293.1996
+ 1889.5  293.3284
+ 1890.0  293.4572
+ 1890.5  293.5860
+ 1891.0  293.7147
+ 1891.5  293.8430
+ 1892.0  293.9709
+ 1892.5  294.0982
+ 1893.0  294.2247
+ 1893.5  294.3504
+ 1894.0  294.4751
+ 1894.5  294.5987
+ 1895.0  294.7210
+ 1895.5  294.8422
+ 1896.0  294.9626
+ 1896.5  295.0822
+ 1897.0  295.2014
+ 1897.5  295.3202
+ 1898.0  295.4390
+ 1898.5  295.5578
+ 1899.0  295.6769
+ 1899.5  295.7964
+ 1900.0  295.9167
+ 1900.5  296.0378
+ 1901.0  296.1599
+ 1901.5  296.2834
+ 1902.0  296.4082
+ 1902.5  296.5348
+ 1903.0  296.6631
+ 1903.5  296.7935
+ 1904.0  296.9261
+ 1904.5  297.0609
+ 1905.0  297.1977
+ 1905.5  297.3365
+ 1906.0  297.4772
+ 1906.5  297.6196
+ 1907.0  297.7637
+ 1907.5  297.9093
+ 1908.0  298.0562
+ 1908.5  298.2043
+ 1909.0  298.3535
+ 1909.5  298.5036
+ 1910.0  298.6545
+ 1910.5  298.8061
+ 1911.0  298.9584
+ 1911.5  299.1113
+ 1912.0  299.2648
+ 1912.5  299.4189
+ 1913.0  299.5734
+ 1913.5  299.7285
+ 1914.0  299.8839
+ 1914.5  300.0397
+ 1915.0  300.1958
+ 1915.5  300.3522
+ 1916.0  300.5088
+ 1916.5  300.6656
+ 1917.0  300.8225
+ 1917.5  300.9796
+ 1918.0  301.1368
+ 1918.5  301.2941
+ 1919.0  301.4514
+ 1919.5  301.6087
+ 1920.0  301.7659
+ 1920.5  301.9232
+ 1921.0  302.0803
+ 1921.5  302.2373
+ 1922.0  302.3942
+ 1922.5  302.5508
+ 1923.0  302.7071
+ 1923.5  302.8628
+ 1924.0  303.0179
+ 1924.5  303.1723
+ 1925.0  303.3258
+ 1925.5  303.4783
+ 1926.0  303.6298
+ 1926.5  303.7800
+ 1927.0  303.9290
+ 1927.5  304.0764
+ 1928.0  304.2224
+ 1928.5  304.3668
+ 1929.0  304.5098
+ 1929.5  304.6515
+ 1930.0  304.7920
+ 1930.5  304.9312
+ 1931.0  305.0694
+ 1931.5  305.2066
+ 1932.0  305.3428
+ 1932.5  305.4782
+ 1933.0  305.6128
+ 1933.5  305.7468
+ 1934.0  305.8803
+ 1934.5  306.0135
+ 1935.0  306.1465
+ 1935.5  306.2795
+ 1936.0  306.4126
+ 1936.5  306.5461
+ 1937.0  306.6801
+ 1937.5  306.8148
+ 1938.0  306.9503
+ 1938.5  307.0871
+ 1939.0  307.2251
+ 1939.5  307.3647
+ 1940.0  307.5059
+ 1940.5  307.6490
+ 1941.0  307.7943
+ 1941.5  307.9417
+ 1942.0  308.0917
+ 1942.5  308.2444
+ 1943.0  308.3999
+ 1943.5  308.5586
+ 1944.0  308.7204
+ 1944.5  308.8857
+ 1945.0  309.0544
+ 1945.5  309.2267
+ 1946.0  309.4026
+ 1946.5  309.5824
+ 1947.0  309.7661
+ 1947.5  309.9538
+ 1948.0  310.1455
+ 1948.5  310.3415
+ 1949.0  310.5418
+ 1949.5  310.7465
+ 1950.0  310.9557
+ 1950.5  311.1696
+ 1951.0  311.3883
+ 1951.5  311.6119
+ 1952.0  311.8406
+ 1952.5  312.0746
+ 1953.0  312.3139
+ 1953.5  312.5587
+ 1954.0  312.8091
+ 1954.5  313.0653
+ 1955.0  313.3275
+ 1955.5  313.5958
+ 1956.0  313.8704
+ 1956.5  314.1514
+ 1957.0  314.4390
+ 1957.5  314.7334
+ 1958.0  315.0347
+ 1958.5  315.3430
+ 1959.0  315.6585
+ 1959.5  315.9810
+ 1960.0  316.3099
+ 1960.5  316.6444
+ 1961.0  316.9835
+ 1961.5  317.3266
+ 1962.0  317.6732
+ 1962.5  318.0236
+ 1963.0  318.3782
+ 1963.5  318.7385
+ 1964.0  319.1062
+ 1964.5  319.4833
+ 1965.0  319.8721
+ 1965.5  320.2745
+ 1966.0  320.6922
+ 1966.5  321.1253
+ 1967.0  321.5737
+ 1967.5  322.0377
+ 1968.0  322.5174
+ 1968.5  323.0131
+ 1969.0  323.5248
+ 1969.5  324.0520
+ 1970.0  324.5937
+ 1970.5  325.1487
+ 1971.0  325.7158
+ 1971.5  326.2941
+ 1972.0  326.8828
+ 1972.5  327.4806
+ 1973.0  328.0859
+ 1973.5  328.6966
+ 1974.0  329.3108
+ 1974.5  329.9296
+ 1975.0  330.5549
+ 1975.5  331.1889
+ 1976.0  331.8340
+ 1976.5  332.4917
+ 1977.0  333.1631
+ 1977.5  333.8474
+ 1978.0  334.5436
+ 1978.5  335.2500
+ 1979.0  335.9649
+ 1979.5  336.6871
+ 1980.0  337.4153
+ 1980.5  338.1481
+ 1981.0  338.8848
+ 1981.5  339.6254
+ 1982.0  340.3708
+ 1982.5  341.1221
+ 1983.0  341.8802
+ 1983.5  342.6460
+ 1984.0  343.4197
+ 1984.5  344.2017
+ 1985.0  344.9922
+ 1985.5  345.7917
+ 1986.0  346.6006
+ 1986.5  347.4193
+ 1987.0  348.2476
+ 1987.5  349.0837
+ 1988.0  349.9257
+ 1988.5  350.7702
+ 1989.0  351.6200
+ 1989.5  352.4700
+ 1990.0  353.3200
+ 1990.5  354.1700
+ 1991.0  354.9666
+ 1991.5  355.4840
+ 1992.0  355.9125
+ 1992.5  356.2656
+ 1993.0  356.4832
+ 1993.5  356.9545
+ 1994.0  357.6902
+ 1994.5  358.6209
+ 1995.0  359.6369
+ 1995.5  360.6260
+ 1996.0  361.5229
+ 1996.5  362.3600
+ 1997.0  362.8839
+ 1997.5  363.4538
+ 1998.0  364.7527
+ 1998.5  366.5040
+ 1999.0  367.6363
+ 1999.5  368.1512
+ 2000.0  368.5849
+ 2000.5  369.4103
+ 2001.0  370.3523
+ 2001.5  371.0773
+ 2002.0  371.9717
+ 2002.5  373.1636
+ 2003.0  374.4362
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/cpp_ORCA2_OFF_TRC.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/cpp_ORCA2_OFF_TRC.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_OFF_TRC/cpp_ORCA2_OFF_TRC.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_top key_iomput key_mpp_mpi
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,134 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                      Define your own files for sea ice                                   =
+=                                         put the variables you want...                                    =
+============================================================================================================
+ -->
+    
+ <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+   
+   <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   	
+     <file id="file21" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+       <!-- ice mask -->
+       <field field_ref="icemask"          name="simsk"   />
+       <field field_ref="icemask05"        name="simsk05" />
+       <field field_ref="icemask15"        name="simsk15" />
+       
+       <!-- general -->
+       <field field_ref="snwvolu"          name="snvolu" />
+       <field field_ref="icethic"          name="sithic" />
+       <field field_ref="icevolu"          name="sivolu" />
+       <field field_ref="iceconc"          name="siconc" />
+       <field field_ref="icesalt"          name="sisali" />
+       <field field_ref="iceapnd"          name="siapnd" />
+       <field field_ref="icevpnd"          name="sivpnd" />
+       <field field_ref="sst_m"            name="sst_m"  />
+       <field field_ref="sss_m"            name="sss_m"  />
+       
+       <!-- heat -->
+       <field field_ref="icetemp"          name="sitemp" />
+       <field field_ref="icettop"          name="sittop" />
+       <field field_ref="icetbot"          name="sitbot" />
+       <field field_ref="icetsni"          name="sitsni" />
+       
+       <!-- momentum -->
+       <field field_ref="uice"             name="sivelu"  />
+       <field field_ref="vice"             name="sivelv"  />
+       <field field_ref="icevel"           name="sivelo"  />
+       <field field_ref="utau_ai"          name="utau_ai" />
+       <field field_ref="vtau_ai"          name="vtau_ai" />
+       <field field_ref="utau_oi"          name="utau_oi" />
+       <field field_ref="vtau_oi"          name="vtau_oi" />
+       
+       <!-- rheology -->
+       <field field_ref="icediv"           name="sidive"  />
+       <field field_ref="iceshe"           name="sishea"  />
+       <field field_ref="icestr"           name="sistre"  />
+       <field field_ref="normstr"          name="normstr" />
+       <field field_ref="sheastr"          name="sheastr" />
+       <field field_ref="isig1"            name="isig1"   />
+       <field field_ref="isig2"            name="isig2"   />
+       <field field_ref="isig3"            name="isig3"   />
+       
+       <!-- heat fluxes -->
+       <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+       <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+       <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+       <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+       <field field_ref="qt_ice"           name="qt_ice"     />
+       <field field_ref="qsr_ice"          name="qsr_ice"    />
+       <field field_ref="qns_ice"          name="qns_ice"    />
+       <field field_ref="qemp_ice"         name="qemp_ice"   />
+       <field field_ref="albedo"           name="albedo"     />
+       
+       <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+       <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+       <field field_ref="hfxsensib"        name="hfxsensib"  />
+       
+       <!-- salt fluxes -->
+       <field field_ref="sfxice"           name="sfxice" />
+       
+       <!-- mass fluxes -->
+       <field field_ref="vfxice"           name="vfxice" />
+       <field field_ref="vfxsnw"           name="vfxsnw" />
+       
+       <!-- categories -->
+       <field field_ref="icemask_cat"      name="simskcat"/>
+       <field field_ref="snwthic_cat"      name="snthicat"/>
+       <field field_ref="iceconc_cat"      name="siconcat"/>
+       <field field_ref="icethic_cat"      name="sithicat"/>
+       <field field_ref="icesalt_cat"      name="sisalcat"/>
+       <field field_ref="icetemp_cat"      name="sitemcat"/>
+       
+     </file>
+     
+     <file id="file22" name_suffix="_SBC_scalar" description="scalar variables" enabled=".true." >
+       <!-- global contents -->
+       <field field_ref="ibgvol_tot"       name="ibgvol_tot"   />
+       <field field_ref="sbgvol_tot"       name="sbgvol_tot"   />
+       <field field_ref="ibgarea_tot"      name="ibgarea_tot"  />
+       <field field_ref="ibgsalt_tot"      name="ibgsalt_tot"  />
+       <field field_ref="ibgheat_tot"      name="ibgheat_tot"  />
+       <field field_ref="sbgheat_tot"      name="sbgheat_tot"  />
+       
+       <!-- global drifts (conservation checks) -->
+       <field field_ref="ibgvolume"        name="ibgvolume"    />
+       <field field_ref="ibgsaltco"        name="ibgsaltco"    />
+       <field field_ref="ibgheatco"        name="ibgheatco"    />
+       <field field_ref="ibgheatfx"        name="ibgheatfx"    />
+       
+       <!-- global forcings  -->
+       <field field_ref="ibgfrcvoltop"     name="ibgfrcvoltop" />
+       <field field_ref="ibgfrcvolbot"     name="ibgfrcvolbot" />
+       <field field_ref="ibgfrctemtop"     name="ibgfrctemtop" />
+       <field field_ref="ibgfrctembot"     name="ibgfrctembot" />
+       <field field_ref="ibgfrcsal"        name="ibgfrcsal"    />
+       <field field_ref="ibgfrchfxtop"     name="ibgfrchfxtop" />
+       <field field_ref="ibgfrchfxbot"     name="ibgfrchfxbot" />
+     </file>
+     
+   </file_group>
+   
+   <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="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="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>
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,109 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context               =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
+        <file id="file11" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"      />
+          <field field_ref="toce"         name="thetao"                                                                      operation="instant" freq_op="5d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="so"                                                                          operation="instant" freq_op="5d" > @soce_e3t / @e3t </field>
+          <field field_ref="sst"          name="tos"   />
+          <field field_ref="sss"          name="sos"   />
+          <field field_ref="ssh"          name="zos"   />
+          <field field_ref="sst"          name="tosstd"       long_name="sea surface temperature standard deviation"         operation="instant" freq_op="5d" > sqrt( @sst2 - @sst * @sst ) </field>
+          <field field_ref="ssh"          name="zosstd"       long_name="sea surface height above geoid standard deviation"  operation="instant" freq_op="5d" > sqrt( @ssh2 - @ssh * @ssh ) </field>
+          <field field_ref="sst"          name="sstdcy"       long_name="amplitude of sst diurnal cycle"                     operation="average" freq_op="1d" > @sstmax - @sstmin </field>
+          <field field_ref="mldkz5"   />
+          <field field_ref="mldr10_1" />
+          <field field_ref="mldr10_1"     name="mldr10_1dcy"  long_name="amplitude of mldr10_1 diurnal cycle"                operation="average" freq_op="1d" > @mldr10_1max - @mldr10_1min </field>
+          <field field_ref="sbt"      />
+          <field field_ref="heatc"        name="heatc" />
+          <field field_ref="saltc"        name="saltc" />
+
+	  <field field_ref="empmr"        name="wfo"      />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  />
+	  <field field_ref="qns_oce"      name="qns_oce"  />
+	  <field field_ref="qt_oce"       name="qt_oce"   />
+	  <field field_ref="saltflx"      name="sfx"      />
+	  <field field_ref="taum"         name="taum"     />
+	  <field field_ref="wspd"         name="windsp"   />
+	  <field field_ref="precip"       name="precip"   />
+	  <!-- ice and snow -->
+	  <field field_ref="snowpre" />
+	</file>
+
+	<file id="file12" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u" />
+	  <field field_ref="ssu"          name="uos"      />
+	  <field field_ref="uoce"         name="uo"       operation="instant" freq_op="5d" > @uoce_e3u / @e3u </field>
+	  <field field_ref="utau"         name="tauuo"    />
+          <field field_ref="uocetr_eff"   name="uocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="u_masstr"     name="vozomatr" />
+	  <field field_ref="u_heattr"     name="sozohetr" />
+	  <field field_ref="u_salttr"     name="sozosatr" />
+	</file>
+	
+	<file id="file13" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v" />
+	  <field field_ref="ssv"          name="vos"      />
+	  <field field_ref="voce"         name="vo"       operation="instant" freq_op="5d" > @voce_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="tauvo"    />
+          <field field_ref="vocetr_eff"   name="vocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="v_masstr"     name="vomematr" />
+	  <field field_ref="v_heattr"     name="somehetr" />
+          <field field_ref="v_salttr"     name="somesatr" />
+	</file>
+	
+	<file id="file14" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w" />
+	  <field field_ref="woce"         name="wo"       />
+	  <field field_ref="avt"          name="difvho"   />
+	  <field field_ref="w_masstr"     name="vovematr" />
+         <!-- variables available with ln_zdfiwm =T -->
+          <field field_ref="av_wave"      name="av_wave"    />
+          <field field_ref="bn2"          name="bn2"        />
+          <field field_ref="bflx_iwm"     name="bflx_iwm"   />
+          <field field_ref="pcmap_iwm"    name="pcmap_iwm"  />
+          <field field_ref="emix_iwm"     name="emix_iwm"   />
+          <field field_ref="av_ratio"     name="av_ratio"   />
+	</file>
+
+
+      </file_group> 
+
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+      </file_group>
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+      </file_group>
+	
+      
+      <file_group id="1ts" output_freq="1ts" output_level="10" enabled=".TRUE."/> <!-- 1 time step 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="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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,212 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                ORCA2-ICE (with SAS) configuration                  !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =  "ORCA2_SAS"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =     100   !  last  time step (std 5475)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.   !  =T  linear free surface  ==>>  model level are fixed in time
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      cn_domcfg = "ORCA_R2_zps_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!                           SAS case                                 !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of SBC module call
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_ice      = 2         !  =2  sea-ice model                         ("key_SI3" or "key_cice")
+/
+!-----------------------------------------------------------------------
+&namsbc_blk   !   namsbc_blk  generic Bulk formula                      (ln_blk =T)
+!-----------------------------------------------------------------------
+   ln_NCAR     = .true.   ! "NCAR"      algorithm   (Large and Yeager 2008)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !       weights filename               ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface boundary condition
+!-----------------------------------------------------------------------
+   l_sasread   = .true.    !  =T Read in file ;  =F set all to 0. (see sbcssm)
+      ln_3d_uve   = .false.   !  specify whether we are supplying a 3D u,v and e3 field
+      ln_read_frq = .false.   !  specify whether we must read frq or not
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_usp      = 'sas_grid_U'            ,       120.        , 'uos'     ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_vsp      = 'sas_grid_V'            ,       120.        , 'vos'     ,   .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'  ,    ''            ,    ''    ,    ''
+   sn_e3t      = 'sas_grid_T'            ,       120.        , 'e3t_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_frq      = 'sas_grid_T'            ,       120.        , 'frq_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,84 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/cpp_ORCA2_SAS_ICE.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/cpp_ORCA2_SAS_ICE.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ORCA2_SAS_ICE/cpp_ORCA2_SAS_ICE.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_si3 key_iomput key_mpp_mpi
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/README.rst	(revision 14097)
@@ -0,0 +1,331 @@
+********************************
+Run the Reference configurations
+********************************
+
+.. todo::
+
+   Lack of illustrations for ref. cfgs, and more generally in the guide.
+
+NEMO is distributed with a set of reference configurations allowing both
+the user to set up his own first applications and
+the developer to test/validate his NEMO developments (using SETTE package).
+
+.. contents::
+   :local:
+   :depth: 1
+
+.. attention::
+
+   Concerning the configurations,
+   the NEMO System Team is only in charge of the so-called reference configurations described below.
+
+.. hint::
+
+   Configurations developed by external research projects or initiatives that
+   make use of NEMO are welcome to be publicized through the website by
+   filling up the form :website:`to add an associated project<projects/add>`.
+
+How to compile an experiment from a reference configuration
+===========================================================
+
+To compile the ORCA2_ICE_PISCES_ reference configuration using :file:`makenemo`,
+one should use the following, by selecting among available architecture file or
+providing a user defined one:
+
+.. code-block:: console
+
+   $ ./makenemo -r 'ORCA2_ICE_PISCES' -m 'my_arch' -j '4'
+
+A new ``EXP00`` folder will be created within the selected reference configurations,
+namely ``./cfgs/ORCA2_ICE_PISCES/EXP00``.
+It will be necessary to uncompress the archives listed in the above table for
+the given reference configuration that includes input & forcing files.
+
+Then it will be possible to launch the execution of the model through a runscript
+(opportunely adapted to the user system).
+
+List of Configurations
+======================
+
+All forcing files listed below in the table are available from |DOI data|_
+
+=================== === === === === === ==================================
+ Configuration       Component(s)        Archives (input & forcing files)
+------------------- ------------------- ----------------------------------
+ Name                O   S   T   P   A
+=================== === === === === === ==================================
+ AGRIF_DEMO_         X   X           X   AGRIF_DEMO_v4.0.tar,
+                                         ORCA2_ICE_v4.0.tar
+ AMM12_              X                   AMM12_v4.0.tar
+ C1D_PAPA_           X                   INPUTS_C1D_PAPA_v4.0.tar
+ GYRE_BFM_           X       X           *none*
+ GYRE_PISCES_        X       X   X       *none*
+ ORCA2_ICE_PISCES_   X   X   X   X       ORCA2_ICE_v4.0.tar,
+                                         INPUTS_PISCES_v4.0.tar
+ ORCA2_OFF_PISCES_           X   X       ORCA2_OFF_v4.0.tar,
+                                         INPUTS_PISCES_v4.0.tar
+ ORCA2_OFF_TRC_              X           ORCA2_OFF_v4.0.tar
+ ORCA2_SAS_ICE_          X               ORCA2_ICE_v4.0.tar,
+                                         INPUTS_SAS_v4.0.tar
+ SPITZ12_            X   X               SPITZ12_v4.0.tar
+=================== === === === === === ==================================
+
+.. admonition:: Legend for component combination
+
+   O for OCE, S for SI\ :sup:`3`, T for TOP, P for PISCES and A for AGRIF
+
+AGRIF_DEMO
+----------
+
+``AGRIF_DEMO`` is based on the ``ORCA2_ICE_PISCES`` global configuration at 2° of resolution with
+the inclusion of 3 online nested grids to demonstrate the overall capabilities of AGRIF in
+a realistic context (including the nesting of sea ice models).
+
+The configuration includes a 1:1 grid in the Pacific and two successively nested grids with
+odd and even refinement ratios over the Arctic ocean,
+with the finest grid spanning the whole Svalbard archipelago that is of
+particular interest to test sea ice coupling.
+
+.. image:: _static/AGRIF_DEMO_no_cap.jpg
+   :scale: 66%
+   :align: center
+
+The 1:1 grid can be used alone as a benchmark to check that
+the model solution is not corrupted by grid exchanges.
+Note that since grids interact only at the baroclinic time level,
+numerically exact results can not be achieved in the 1:1 case.
+Perfect reproducibility is obtained only by switching to a fully explicit setup instead of
+a split explicit free surface scheme.
+
+AMM12
+-----
+
+``AMM12`` stands for *Atlantic Margin Model at 12 km* that is
+a regional configuration covering the Northwest European Shelf domain on
+a regular horizontal grid of ~12 km of resolution (see :cite:`ODEA2012`).
+
+.. image:: _static/AMM_domain.png
+   :align: center
+
+This configuration allows to tests several features of NEMO specifically addressed to the shelf seas.
+In particular, ``AMM12`` accounts for vertical s-coordinates system, GLS turbulence scheme,
+tidal lateral boundary conditions using a flather scheme (see more in ``BDY``).
+Boundaries may be completely omitted by setting ``ln_bdy = .false.`` in ``nambdy``.
+
+Sample surface fluxes, river forcing and an initial restart file are included to test a realistic model run
+(``AMM12_v4.0.tar``).
+
+Note that, the Baltic boundary is included within the river input file and is specified as a river source,
+but unlike ordinary river points the Baltic inputs also include salinity and temperature data.
+
+C1D_PAPA
+--------
+
+.. figure:: _static/Papa2015.jpg
+   :height: 225px
+   :align:  left
+
+``C1D_PAPA`` is a 1D configuration for the `PAPA station`_ located in
+the northern-eastern Pacific Ocean at 50.1°N, 144.9°W.
+See :gmd:`Reffray et al. (2015) <8/69/2015>` for the description of
+its physical and numerical turbulent-mixing behaviour.
+
+| The water column setup, called NEMO1D, is activated with
+  the inclusion of the CPP key ``key_c1d`` and
+  has a horizontal domain of 3x3 grid points.
+| This reference configuration uses 75 vertical levels grid (1m at the surface),
+  GLS turbulence scheme with K-epsilon closure and the NCAR bulk formulae.
+
+Data provided with ``INPUTS_C1D_PAPA_v4.0.tar`` file account for:
+
+- :file:`forcing_PAPASTATION_1h_y201[0-1].nc`:
+  ECMWF operational analysis atmospheric forcing rescaled to 1h
+  (with long and short waves flux correction) for years 2010 and 2011
+- :file:`init_PAPASTATION_m06d15.nc`: Initial Conditions from
+  observed data and Levitus 2009 climatology
+- :file:`chlorophyll_PAPASTATION.nc`: surface chlorophyll file from Seawifs data
+
+GYRE_BFM
+--------
+
+``GYRE_BFM`` shares the same physical setup of GYRE_PISCES_,
+but NEMO is coupled with the `BFM`_ biogeochemical model as described in ``./cfgs/GYRE_BFM/README``.
+
+GYRE_PISCES
+-----------
+
+``GYRE_PISCES`` is an idealized configuration representing a Northern hemisphere double gyres system,
+in the Beta-plane approximation with a regular 1° horizontal resolution and 31 vertical levels,
+with PISCES BGC model :cite:`gmd-8-2465-2015`.
+Analytical forcing for heat, freshwater and wind-stress fields are applied.
+
+This configuration acts also as demonstrator of the **user defined setup**
+(``ln_read_cfg = .false.``) and grid setting are handled through
+the ``&namusr_def`` controls in :file:`namelist_cfg`:
+
+.. literalinclude:: ../../../cfgs/GYRE_PISCES/EXPREF/namelist_cfg
+   :language: fortran
+   :lines:    35-41
+
+Note that, the default grid size is 30x20 grid points (with ``nn_GYRE = 1``) and
+vertical levels are set by ``jpkglo``.
+The specific code changes can be inspected in :file:`./src/OCE/USR`.
+
+.. rubric:: Running GYRE as a benchmark
+
+| This simple configuration can be used as a benchmark since it is easy to increase resolution,
+  with the drawback of getting results that have a very limited physical meaning.
+| GYRE grid resolution can be increased at runtime by setting a different value of ``nn_GYRE``
+  (integer multiplier scaling factor), as described in the following table:
+
+=========== ============ ============ ============ ===============
+``nn_GYRE``  ``jpiglo``   ``jpjglo``   ``jpkglo``   Equivalent to
+=========== ============ ============ ============ ===============
+ 1           30           20           31           GYRE 1°
+ 25          750          500          101          ORCA 1/2°
+ 50          1500         1000         101          ORCA 1/4°
+ 150         4500         3000         101          ORCA 1/12°
+ 200         6000         4000         101          ORCA 1/16°
+=========== ============ ============ ============ ===============
+
+| Note that, it is necessary to set ``ln_bench = .true.`` in ``&namusr_def`` to
+  avoid problems in the physics computation and that
+  the model timestep should be adequately rescaled.
+| For example if ``nn_GYRE = 150``, equivalent to an ORCA 1/12° grid,
+  the timestep ``rn_rdt`` should be set to 1200 seconds
+  Differently from previous versions of NEMO, the code uses by default the time-splitting scheme and
+  internally computes the number of sub-steps.
+
+ORCA2_ICE_PISCES
+----------------
+
+``ORCA2_ICE_PISCES`` is a reference configuration for the global ocean with
+a 2°x2° curvilinear horizontal mesh and 31 vertical levels,
+distributed using z-coordinate system and with 10 levels in the top 100m.
+ORCA is the generic name given to global ocean Mercator mesh,
+(i.e. variation of meridian scale factor as cosinus of the latitude),
+with two poles in the northern hemisphere so that
+the ratio of anisotropy is nearly one everywhere
+
+This configuration uses the three components
+
+- |OCE|, the ocean dynamical core
+- |ICE|, the thermodynamic-dynamic sea ice model.
+- |MBG|, passive tracer transport module and PISCES BGC model :cite:`gmd-8-2465-2015`
+
+All components share the same grid.
+The model is forced with CORE-II normal year atmospheric forcing and
+it uses the NCAR bulk formulae.
+
+.. rubric:: Ocean Physics
+
+:horizontal diffusion on momentum:
+   the eddy viscosity coefficient depends on the geographical position.
+   It is taken as 40000 m\ :sup:`2`/s, reduced in the equator regions (2000 m\ :sup:`2`/s)
+   excepted near the western boundaries.
+:isopycnal diffusion on tracers:
+   the diffusion acts along the isopycnal surfaces (neutral surface) with
+   an eddy diffusivity coefficient of 2000 m\ :sup:`2`/s.
+:Eddy induced velocity parametrization:
+   With a coefficient that depends on the growth rate of baroclinic instabilities
+   (it usually varies from 15 m\ :sup:`2`/s to 3000 m\ :sup:`2`/s).
+:lateral boundary conditions:
+   Zero fluxes of heat and salt and no-slip conditions are applied through lateral solid boundaries.
+:bottom boundary condition:
+   Zero fluxes of heat and salt are applied through the ocean bottom.
+   The Beckmann [19XX] simple bottom boundary layer parameterization is applied along
+   continental slopes.
+   A linear friction is applied on momentum.
+:convection:
+   The vertical eddy viscosity and diffusivity coefficients are increased to 1 m\ :sup:`2`/s in
+   case of static instability.
+:time step: is 5760sec (1h36') so that there is 15 time steps in one day.
+
+ORCA2_OFF_PISCES
+----------------
+
+``ORCA2_OFF_PISCES`` shares the same general offline configuration of ``ORCA2_ICE_TRC``,
+but only PISCES model is an active component of TOP.
+
+ORCA2_OFF_TRC
+-------------
+
+| ``ORCA2_OFF_TRC`` is based on the ORCA2 global ocean configuration
+  (see ORCA2_ICE_PISCES_ for general description) along with
+  the tracer passive transport module (TOP),
+  but dynamical fields are pre-calculated and read with specific time frequency.
+| This enables for an offline coupling of TOP components,
+  here specifically inorganic carbon compounds (CFC11, CFC12, SF6, C14) and water age module (age).
+  See :file:`namelist_top_cfg` to inspect the selection of
+  each component with the dedicated logical keys.
+
+Pre-calculated dynamical fields are provided to NEMO using
+the namelist ``&namdta_dyn``  in :file:`namelist_cfg`,
+in this case with a 5 days frequency (120 hours):
+
+.. literalinclude:: ../../namelists/namdta_dyn
+   :language: fortran
+
+Input dynamical fields for this configuration (:file:`ORCA2_OFF_v4.0.tar`) comes from
+a 2000 years long climatological simulation of ORCA2_ICE using ERA40 atmospheric forcing.
+
+| Note that,
+  this configuration default uses linear free surface (``ln_linssh = .true.``) assuming that
+  model mesh is not varying in time and
+  it includes the bottom boundary layer parameterization (``ln_trabbl = .true.``) that
+  requires the provision of BBL coefficients through ``sn_ubl`` and ``sn_vbl`` fields.
+| It is also possible to activate PISCES model (see ``ORCA2_OFF_PISCES``) or
+  a user defined set of tracers and source-sink terms with ``ln_my_trc = .true.``
+  (and adaptation of ``./src/TOP/MY_TRC`` routines).
+
+In addition, the offline module (OFF) allows for the provision of further fields:
+
+1. **River runoff** can be provided to TOP components by setting ``ln_dynrnf = .true.`` and
+   by including an input datastream similarly to the following:
+
+   .. code-block:: fortran
+
+      sn_rnf  = 'dyna_grid_T', 120, 'sorunoff' , .true., .true., 'yearly', '', '', ''
+
+2. **VVL dynamical fields**, in the case input data were produced by a dyamical core using
+   variable volume (``ln_linssh = .false.``)
+   it is necessary to provide also diverce and E-P at before timestep by
+   including input datastreams similarly to the following
+
+   .. code-block:: fortran
+
+      sn_div  = 'dyna_grid_T', 120, 'e3t'      , .true., .true., 'yearly', '', '', ''
+      sn_empb = 'dyna_grid_T', 120, 'sowaflupb', .true., .true., 'yearly', '', '', ''
+
+More details can be found by inspecting the offline data manager in
+the routine :file:`./src/OFF/dtadyn.F90`.
+
+ORCA2_SAS_ICE
+-------------
+
+| ORCA2_SAS_ICE is a demonstrator of the Stand-Alone Surface (SAS) module and
+  it relies on ORCA2 global ocean configuration (see ORCA2_ICE_PISCES_ for general description).
+| The standalone surface module allows surface elements such as sea-ice, iceberg drift, and
+  surface fluxes to be run using prescribed model state fields.
+  It can profitably be used to compare different bulk formulae or
+  adjust the parameters of a given bulk formula.
+
+More informations about SAS can be found in :doc:`NEMO manual <cite>`.
+
+SPITZ12
+-------
+
+``SPITZ12`` is a regional configuration around the Svalbard archipelago
+at 1/12° of horizontal resolution and 75 vertical levels.
+See :gmd:`Rousset et al. (2015) <8/2991/2015>` for more details.
+
+This configuration references to year 2002,
+with atmospheric forcing provided every 2 hours using NCAR bulk formulae,
+while lateral boundary conditions for dynamical fields have 3 days time frequency.
+
+.. rubric:: References
+
+.. bibliography:: cfgs.bib
+   :all:
+   :style: unsrt
+   :labelprefix: C
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.namelists
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.namelists	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.namelists	(revision 14097)
@@ -0,0 +1,109 @@
+Simple style rules for namelists
+--------------------------------
+
+NEMO reference namelists should adhere to the following simple style rules:
+
+1.	Comments outside a namelist block start with !! in column 1
+2.	Each namelist block starts with 3 lines of the form:
+
+!-----------------------------------------------------------------------
+&namblockname        !   short description of block
+!-----------------------------------------------------------------------
+
+        with all ! and & 's starting in column 1
+3.	The closing / for each namelist block is in column 1
+4.	Comments within namelist blocks never start with !- . Use ! followed
+        by space or != etc. 
+
+These conventions make it possible to construct empty configuration namelists.
+For example, a namelist_cfg template can be produced from namelist_ref with
+the following grep command; e.g.:
+
+grep -E  '^!-|^&|^/' namelist_ref > namelist_cfg.template
+
+head namelist_cfg.template
+  
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                     
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+/
+.
+.
+
+If all configuration namelists are produced and maintained using this
+strategy then standard, side-by-side comaparators, such as vimdiff or xxdiff,
+can be used to compare and transfer lines from the reference namelist to a
+configuration namelist when setting up a new configuration.
+
+Tips and tricks
+---------------
+
+1. The following bash function is useful when checking which namelist blocks
+are in active use in a configuration namelist:
+
+  function  list_used_nl(){ grep -n -E '^&|^/' "$1" | sed -e 's/:/ /' \
+    | awk ' BEGIN { x = 0 } \
+      {if ( NR % 2 == 0 && $1 - x > 2 ) printf("%3d  %s\n", $1 - x , n) ; \
+       else x = $1; n = $2}' \
+    | sort -k 2;}
+
+which (assuming the namelist adheres to the conventions) will list the number
+of entries in each non-empty namelist block. The list is sorted on the block
+name to ease comparisons. For example:
+
+  list_used_nl ORCA2_LIM3_PISCES/EXP00/namelist_cfg
+
+  1 &nambbc
+  5 &nambbl
+  30 &namberg
+  10 &namcfg
+  4 &namctl
+  3 &namdom
+  1 &namdrg
+  5 &namdyn_adv
+  1 &namdyn_hpg
+  22 &namdyn_ldf
+  1 &namdyn_spg
+  5 &namdyn_vor
+  3 &nameos
+  1 &namhsb
+  4 &namrun
+  1 &namsbc
+  1 &namsbc_blk
+  3 &namtra_adv
+  28 &namtra_ldf
+  10 &namtra_ldfeiv
+  25 &namzdf
+  3 &namzdf_iwm
+
+2. vimdiff can give garish colours in some terminals. Usually this is because
+vim assumes, incorrectly, that the terminal only supports 8 colours. Try forcing
+256 colours with:
+
+  :set t_Co=256
+
+to produce more pastel shades (add this to ~/.vimrc if successful).
+
+3. Switching between vsplit panes in vim is a multi-key sequence. The tool is 
+much easier to use if the sequence is mapped to a spare key. Here I use the
+§ and ± key on my Mac keyboard (add to ~/.vimrc):
+
+  map § ^Wl
+  map ± ^Wh 
+
+4. With easy switching between panes, constructing namelists in vimdiff just
+requires the following commands in addition to normal editing:
+
+  ]c    - Go to next block of the diff
+  dp    - Push version of the block under cursor into the other pane
+  do    - Pull version of the block under cursor from the other pane
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/README.rst	(revision 14097)
@@ -0,0 +1,119 @@
+***********
+Diagnostics
+***********
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Output of diagnostics in NEMO is usually done using XIOS.
+This is an efficient way of writing diagnostics because
+the time averaging, file writing and even some simple arithmetic or regridding is carried out in
+parallel to the NEMO model run.
+This page gives a basic introduction to using XIOS with NEMO.
+Much more information is available from the :xios:`XIOS homepage<>` above and from the NEMO manual.
+
+Use of XIOS for diagnostics is activated using the pre-compiler key ``key_iomput``.
+
+Extracting and installing XIOS
+==============================
+
+1. Install the NetCDF4 library.
+   If you want to use single file output you will need to compile the HDF & NetCDF libraries to
+   allow parallel IO.
+2. Download the version of XIOS that you wish to use.
+   The recommended version is now XIOS 2.5:
+
+   .. code-block:: console
+
+      $ svn co http://forge.ipsl.jussieu.fr/ioserver/svn/XIOS/branchs/xios-2.5
+
+and follow the instructions in :xios:`XIOS documentation <wiki/documentation>` to compile it.
+If you find problems at this stage, support can be found by subscribing to
+the :xios:`XIOS mailing list <../mailman/listinfo.cgi/xios-users>` and sending a mail message to it.
+
+XIOS Configuration files
+------------------------
+
+XIOS is controlled using XML input files that should be copied to
+your model run directory before running the model.
+Examples of these files can be found in the reference configurations (:file:`./cfgs`).
+The XIOS executable expects to find a file called :file:`iodef.xml` in the model run directory.
+In NEMO we have made the decision to use include statements in the :file:`iodef.xml` file to include:
+
+- :file:`field_def_nemo-oce.xml` (for physics),
+- :file:`field_def_nemo-ice.xml` (for ice),
+- :file:`field_def_nemo-pisces.xml` (for biogeochemistry) and
+- :file:`domain_def.xml` from the :file:`./cfgs/SHARED` directory.
+
+Most users will not need to modify :file:`domain_def.xml` or :file:`field_def_nemo-???.xml` unless
+they want to add new diagnostics to the NEMO code.
+The definition of the output files is organized into separate :file:`file_definition.xml` files which
+are included in the :file:`iodef.xml` file.
+
+Modes
+=====
+
+Detached Mode
+-------------
+
+In detached mode the XIOS executable is executed on separate cores from the NEMO model.
+This is the recommended method for using XIOS for realistic model runs.
+To use this mode set ``using_server`` to ``true`` at the bottom of the :file:`iodef.xml` file:
+
+.. code-block:: xml
+
+   <variable id="using_server" type="boolean">true</variable>
+
+Make sure there is a copy (or link to) your XIOS executable in the working directory and
+in your job submission script allocate processors to XIOS.
+
+Attached Mode
+-------------
+
+In attached mode XIOS runs on each of the cores used by NEMO.
+This method is less efficient than the detached mode but can be more convenient for testing or
+with small configurations.
+To activate this mode simply set ``using_server`` to false in the :file:`iodef.xml` file
+
+.. code-block:: xml
+
+   <variable id="using_server" type="boolean">false</variable>
+
+and don't allocate any cores to XIOS.
+
+.. note::
+
+   Due to the different domain decompositions between XIOS and NEMO,
+   if the total number of cores is larger than the number of grid points in the ``j`` direction then
+   the model run will fail.
+
+Adding new diagnostics
+======================
+
+If you want to add a NEMO diagnostic to the NEMO code you will need to do the following:
+
+1. Add any necessary code to calculate you new diagnostic in NEMO
+2. Send the field to XIOS using ``CALL iom_put( 'field_id', variable )`` where
+   ``field_id`` is a unique id for your new diagnostics and
+   variable is the fortran variable containing the data.
+   This should be called at every model timestep regardless of how often you want to output the field.
+   No time averaging should be done in the model code.
+3. If it is computationally expensive to calculate your new diagnostic
+   you should also use "iom_use" to determine if it is requested in the current model run.
+   For example,
+
+   .. code-block:: fortran
+
+      IF iom_use('field_id') THEN
+         !Some expensive computation
+         !...
+         !...
+	 iom_put('field_id', variable)
+      ENDIF
+
+4. Add a variable definition to the :file:`field_def_nemo-???.xml` file.
+5. Add the variable to the :file:`iodef.xml` or :file:`file_definition.xml` file.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,27 @@
+<!--
+============================================================================================================
+= Axis definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+
+    <axis_definition>
+      <axis id="deptht" long_name="Vertical T levels" unit="m" positive="down" />
+      <!--   Vertical zoom for a 31-levels ORCA2 grid for eORCA1 300m corresponds to n=35 -->
+      <axis id="deptht300" axis_ref="deptht" >
+         <zoom_axis begin="0" n="19" />
+      </axis>
+      <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="1"               />
+      <axis id="ncatice" long_name="Ice category"       unit="1"               />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"            />
+      <axis id="iax_26C" long_name="26 degC isotherm"   unit="degC"            />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"            />
+      <axis id="basin"   long_name="Sub-basin mask (1=Global 2=Atlantic 3=Indo-Pacific 4=Indian, 5=Pacific)"  unit="1" />
+      <axis id="nstrait" long_name="Number of straits" unit="1" />
+      <axis id="section"     n_glo="16" />
+      <axis id="section_ice" n_glo="4" />
+      <axis id="gau" />
+    </axis_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,197 @@
+
+   <domain_definition>
+
+     <!--   T grid   -->
+     <domain id="grid_T" long_name="grid T"/>
+     
+     <!--   My zoom: example of hand defined zoom   -->
+     <domain id="myzoomT" domain_ref="grid_T" >
+       <zoom_domain ibegin="1" jbegin="1" ni="2" nj="3"/>
+     </domain>
+
+      <domain id="1point" domain_ref="grid_T" >
+         <zoom_domain ibegin="139" jbegin="119" ni="1" nj="1"/>
+      </domain>
+
+
+     <!--   Eq section -->
+     <domain id="EqT" domain_ref="grid_T" > <zoom_domain id="EqT"/> </domain>
+     <!--   TAO : see example above   -->
+     <!--   137e   -->
+     <domain id="2n137eT" domain_ref="grid_T" > <zoom_domain id="2n137eT"/> </domain>
+     <domain id="5n137eT" domain_ref="grid_T" > <zoom_domain id="5n137eT"/> </domain>
+     <domain id="8n137eT" domain_ref="grid_T" > <zoom_domain id="8n137eT"/> </domain>
+     <!-- <\!--   147e   -\-> -->
+     <domain id="0n147eT" domain_ref="grid_T" > <zoom_domain id="0n147eT"/> </domain>
+     <domain id="2n147eT" domain_ref="grid_T" > <zoom_domain id="2n147eT"/> </domain>
+     <domain id="5n147eT" domain_ref="grid_T" > <zoom_domain id="5n147eT"/> </domain>
+     <!-- <\!--   156e   -\-> -->
+     <domain id="5s156eT" domain_ref="grid_T" > <zoom_domain id="5s156eT"/> </domain>
+     <domain id="2s156eT" domain_ref="grid_T" > <zoom_domain id="2s156eT"/> </domain>
+     <domain id="0n156eT" domain_ref="grid_T" > <zoom_domain id="0n156eT"/> </domain>
+     <domain id="2n156eT" domain_ref="grid_T" > <zoom_domain id="2n156eT"/> </domain>
+     <domain id="5n156eT" domain_ref="grid_T" > <zoom_domain id="5n156eT"/> </domain>
+     <domain id="8n156eT" domain_ref="grid_T" > <zoom_domain id="8n156eT"/> </domain>
+     <!-- <\!--   165e   -\-> -->
+     <domain id="8s165eT" domain_ref="grid_T" > <zoom_domain id="8s165eT"/> </domain>
+     <domain id="5s165eT" domain_ref="grid_T" > <zoom_domain id="5s165eT"/> </domain>
+     <domain id="2s165eT" domain_ref="grid_T" > <zoom_domain id="2s165eT"/> </domain>
+     <domain id="0n165eT" domain_ref="grid_T" > <zoom_domain id="0n165eT"/> </domain>
+     <domain id="2n165eT" domain_ref="grid_T" > <zoom_domain id="2n165eT"/> </domain>
+     <domain id="5n165eT" domain_ref="grid_T" > <zoom_domain id="5n165eT"/> </domain>
+     <domain id="8n165eT" domain_ref="grid_T" > <zoom_domain id="8n165eT"/> </domain>
+     <!-- <\!--   180w   -\-> -->
+     <domain id="8s180wT" domain_ref="grid_T" > <zoom_domain id="8s180wT"/> </domain>
+     <domain id="5s180wT" domain_ref="grid_T" > <zoom_domain id="5s180wT"/> </domain>
+     <domain id="2s180wT" domain_ref="grid_T" > <zoom_domain id="2s180wT"/> </domain>
+     <domain id="0n180wT" domain_ref="grid_T" > <zoom_domain id="0n180wT"/> </domain>
+     <domain id="2n180wT" domain_ref="grid_T" > <zoom_domain id="2n180wT"/> </domain>
+     <domain id="5n180wT" domain_ref="grid_T" > <zoom_domain id="5n180wT"/> </domain>
+     <domain id="8n180wT" domain_ref="grid_T" > <zoom_domain id="8n180wT"/> </domain>
+     <!-- <\!--   170w   -\-> -->
+     <domain id="8s170wT" domain_ref="grid_T" > <zoom_domain id="8s170wT"/> </domain>
+     <domain id="5s170wT" domain_ref="grid_T" > <zoom_domain id="5s170wT"/> </domain>
+     <domain id="2s170wT" domain_ref="grid_T" > <zoom_domain id="2s170wT"/> </domain>
+     <domain id="0n170wT" domain_ref="grid_T" > <zoom_domain id="0n170wT"/> </domain>
+     <domain id="2n170wT" domain_ref="grid_T" > <zoom_domain id="2n170wT"/> </domain>
+     <domain id="5n170wT" domain_ref="grid_T" > <zoom_domain id="5n170wT"/> </domain>
+     <domain id="8n170wT" domain_ref="grid_T" > <zoom_domain id="8n170wT"/> </domain>
+     <!-- <\!--   155w   -\-> -->
+     <domain id="8s155wT" domain_ref="grid_T" > <zoom_domain id="8s155wT"/> </domain>
+     <domain id="5s155wT" domain_ref="grid_T" > <zoom_domain id="5s155wT"/> </domain>
+     <domain id="2s155wT" domain_ref="grid_T" > <zoom_domain id="2s155wT"/> </domain>
+     <domain id="0n155wT" domain_ref="grid_T" > <zoom_domain id="0n155wT"/> </domain>
+     <domain id="2n155wT" domain_ref="grid_T" > <zoom_domain id="2n155wT"/> </domain>
+     <domain id="5n155wT" domain_ref="grid_T" > <zoom_domain id="5n155wT"/> </domain>
+     <domain id="8n155wT" domain_ref="grid_T" > <zoom_domain id="8n155wT"/> </domain>
+     <!-- <\!--   140w   -\-> -->
+     <domain id="8s140wT" domain_ref="grid_T" > <zoom_domain id="8s140wT"/> </domain>
+     <domain id="5s140wT" domain_ref="grid_T" > <zoom_domain id="5s140wT"/> </domain>
+     <domain id="2s140wT" domain_ref="grid_T" > <zoom_domain id="2s140wT"/> </domain>
+     <domain id="0n140wT" domain_ref="grid_T" > <zoom_domain id="0n140wT"/> </domain>
+     <domain id="2n140wT" domain_ref="grid_T" > <zoom_domain id="2n140wT"/> </domain>
+     <domain id="5n140wT" domain_ref="grid_T" > <zoom_domain id="5n140wT"/> </domain>
+     <domain id="8n140wT" domain_ref="grid_T" > <zoom_domain id="8n140wT"/> </domain>
+     <!-- <\!--   125w   -\-> -->
+     <domain id="8s125wT" domain_ref="grid_T" > <zoom_domain id="8s125wT"/> </domain>
+     <domain id="5s125wT" domain_ref="grid_T" > <zoom_domain id="5s125wT"/> </domain>
+     <domain id="2s125wT" domain_ref="grid_T" > <zoom_domain id="2s125wT"/> </domain>
+     <domain id="0n125wT" domain_ref="grid_T" > <zoom_domain id="0n125wT"/> </domain>
+     <domain id="2n125wT" domain_ref="grid_T" > <zoom_domain id="2n125wT"/> </domain>
+     <domain id="5n125wT" domain_ref="grid_T" > <zoom_domain id="5n125wT"/> </domain>
+     <domain id="8n125wT" domain_ref="grid_T" > <zoom_domain id="8n125wT"/> </domain>
+     <!-- <\!--   110w   -\-> -->
+     <domain id="8s110wT" domain_ref="grid_T" > <zoom_domain id="8s110wT"/> </domain>
+     <domain id="5s110wT" domain_ref="grid_T" > <zoom_domain id="5s110wT"/> </domain>
+     <domain id="2s110wT" domain_ref="grid_T" > <zoom_domain id="2s110wT"/> </domain>
+     <domain id="0n110wT" domain_ref="grid_T" > <zoom_domain id="0n110wT"/> </domain>
+     <domain id="2n110wT" domain_ref="grid_T" > <zoom_domain id="2n110wT"/> </domain>
+     <domain id="5n110wT" domain_ref="grid_T" > <zoom_domain id="5n110wT"/> </domain>
+     <domain id="8n110wT" domain_ref="grid_T" > <zoom_domain id="8n110wT"/> </domain>
+     <!-- <\!--   95w   -\-> -->
+     <domain id="8s95wT" domain_ref="grid_T" > <zoom_domain id="8s95wT"/> </domain>
+     <domain id="5s95wT" domain_ref="grid_T" > <zoom_domain id="5s95wT"/> </domain>
+     <domain id="2s95wT" domain_ref="grid_T" > <zoom_domain id="2s95wT"/> </domain>
+     <domain id="0n95wT" domain_ref="grid_T" > <zoom_domain id="0n95wT"/> </domain>
+     <domain id="2n95wT" domain_ref="grid_T" > <zoom_domain id="2n95wT"/> </domain>
+     <domain id="5n95wT" domain_ref="grid_T" > <zoom_domain id="5n95wT"/> </domain>
+     <domain id="8n95wT" domain_ref="grid_T" > <zoom_domain id="8n95wT"/> </domain>
+     <!-- <\!--   RAMA   -\-> -->
+     <!-- <\!--   55e   -\-> -->
+     <domain id="16s55eT"    domain_ref="grid_T" > <zoom_domain id="16s55eT"   /> </domain>
+     <domain id="12s55eT"    domain_ref="grid_T" > <zoom_domain id="12s55eT"   /> </domain>
+     <domain id="8s55eT"     domain_ref="grid_T" > <zoom_domain id="8s55eT"    /> </domain>
+     <domain id="4s55eT"     domain_ref="grid_T" > <zoom_domain id="4s55eT"    /> </domain>
+     <domain id="1.5s55eT"   domain_ref="grid_T" > <zoom_domain id="1.5s55eT"  /> </domain>
+     <domain id="0n55eT"     domain_ref="grid_T" > <zoom_domain id="0n55eT"    /> </domain>
+     <domain id="1.5n55eT"   domain_ref="grid_T" > <zoom_domain id="1.5n55eT"  /> </domain>
+     <domain id="4n55eT"     domain_ref="grid_T" > <zoom_domain id="4n55eT"    /> </domain>
+     <!--    <\!--   65e   -\-> -->
+     <domain id="15n65eT"    domain_ref="grid_T" > <zoom_domain id="15n65eT"   /> </domain>
+     <!--    <\!--   67e   -\-> -->
+     <domain id="16s67eT"    domain_ref="grid_T" > <zoom_domain id="16s67eT"   /> </domain>
+     <domain id="12s67eT"    domain_ref="grid_T" > <zoom_domain id="12s67eT"   /> </domain>
+     <domain id="8s67eT"     domain_ref="grid_T" > <zoom_domain id="8s67eT"    /> </domain>
+     <domain id="4s67eT"     domain_ref="grid_T" > <zoom_domain id="4s67eT"    /> </domain>
+     <domain id="1.5s67eT"   domain_ref="grid_T" > <zoom_domain id="1.5s67eT"  /> </domain>
+     <domain id="0n67eT"     domain_ref="grid_T" > <zoom_domain id="0n67eT"    /> </domain>
+     <domain id="1.5n67eT"   domain_ref="grid_T" > <zoom_domain id="1.5n67eT"  /> </domain>
+     <domain id="4n67eT"     domain_ref="grid_T" > <zoom_domain id="4n67eT"    /> </domain>
+     <domain id="8n67eT"     domain_ref="grid_T" > <zoom_domain id="8n67eT"    /> </domain>
+     <!-- <\!--   80.5e   -\-> -->
+     <domain id="16s80.5eT"  domain_ref="grid_T" > <zoom_domain id="16s80.5eT" /> </domain>
+     <domain id="12s80.5eT"  domain_ref="grid_T" > <zoom_domain id="12s80.5eT" /> </domain>
+     <domain id="8s80.5eT"   domain_ref="grid_T" > <zoom_domain id="8s80.5eT"  /> </domain>
+     <domain id="4s80.5eT"   domain_ref="grid_T" > <zoom_domain id="4s80.5eT"  /> </domain>
+     <domain id="1.5s80.5eT" domain_ref="grid_T" > <zoom_domain id="1.5s80.5eT"/> </domain>
+     <domain id="0n80.5eT"   domain_ref="grid_T" > <zoom_domain id="0n80.5eT"  /> </domain>
+     <domain id="1.5n80.5eT" domain_ref="grid_T" > <zoom_domain id="1.5n80.5eT"/> </domain>
+     <domain id="4n80.5eT"   domain_ref="grid_T" > <zoom_domain id="4n80.5eT"  /> </domain>
+     <!-- <\!--   90e   -\-> -->
+     <domain id="1.5s90eT"   domain_ref="grid_T" > <zoom_domain id="1.5s90eT"  /> </domain>
+     <domain id="0n90eT"     domain_ref="grid_T" > <zoom_domain id="0n90eT"    /> </domain>
+     <domain id="1.5n90eT"   domain_ref="grid_T" > <zoom_domain id="1.5n90eT"  /> </domain>
+     <domain id="4n90eT"     domain_ref="grid_T" > <zoom_domain id="4n90eT"    /> </domain>
+     <domain id="8n90eT"     domain_ref="grid_T" > <zoom_domain id="8n90eT"    /> </domain>
+     <domain id="12n90eT"    domain_ref="grid_T" > <zoom_domain id="12n90eT"   /> </domain>
+     <domain id="15n90eT"    domain_ref="grid_T" > <zoom_domain id="15n90eT"   /> </domain>
+     <!-- <\!--   95e   -\-> -->
+     <domain id="16s95eT"    domain_ref="grid_T" > <zoom_domain id="16s95eT"   /> </domain>
+     <domain id="12s95eT"    domain_ref="grid_T" > <zoom_domain id="12s95eT"   /> </domain>
+     <domain id="8s95eT"     domain_ref="grid_T" > <zoom_domain id="8s95eT"    /> </domain>
+     <domain id="5s95eT"     domain_ref="grid_T" > <zoom_domain id="5s95eT"    /> </domain>
+     <!-- <\!--   PIRATA   -\-> -->
+     <!-- <\!--   38w-30w   -\-> -->
+     <domain id="19s34wT" domain_ref="grid_T" > <zoom_domain id="19s34wT"/> </domain>
+     <domain id="14s32wT" domain_ref="grid_T" > <zoom_domain id="14s32wT"/> </domain>
+     <domain id="8s30wT"  domain_ref="grid_T" > <zoom_domain id="8s30wT" /> </domain>
+     <domain id="0n35wT"  domain_ref="grid_T" > <zoom_domain id="0n35wT" /> </domain>
+     <domain id="4n38wT"  domain_ref="grid_T" > <zoom_domain id="4n38wT" /> </domain>
+     <domain id="8n38wT"  domain_ref="grid_T" > <zoom_domain id="8n38wT" /> </domain>
+     <domain id="12n38wT" domain_ref="grid_T" > <zoom_domain id="12n38wT"/> </domain>
+     <domain id="15n38wT" domain_ref="grid_T" > <zoom_domain id="15n38wT"/> </domain>
+     <domain id="20n38wT" domain_ref="grid_T" > <zoom_domain id="20n38wT"/> </domain>
+     <!-- <\!--   23w   -\-> -->
+     <domain id="0n23wT"  domain_ref="grid_T" > <zoom_domain id="0n23wT" /> </domain>
+     <domain id="4n23wT"  domain_ref="grid_T" > <zoom_domain id="4n23wT" /> </domain>
+     <domain id="12n23wT" domain_ref="grid_T" > <zoom_domain id="12n23wT"/> </domain>
+     <domain id="21n23wT" domain_ref="grid_T" > <zoom_domain id="21n23wT"/> </domain>
+     <!-- <\!--   10w   -\-> -->
+     <domain id="10s10wT" domain_ref="grid_T" > <zoom_domain id="10s10wT"/> </domain>
+     <domain id="6s10wT"  domain_ref="grid_T" > <zoom_domain id="6s10wT" /> </domain>
+     <domain id="0n10wT"  domain_ref="grid_T" > <zoom_domain id="0n10wT" /> </domain>
+     <!-- <\!--   0e   -\-> -->
+     <domain id="0n0eT"   domain_ref="grid_T" > <zoom_domain id="0n0eT"  /> </domain>
+
+     
+     <!--   U grid   -->
+     <domain id="grid_U" long_name="grid U"/>
+     <!--   Eq section   -->
+     <domain id="EqU" domain_ref="grid_U" > <zoom_domain id="EqU"/> </domain>
+
+      
+     <!--   V grid   -->
+     <domain id="grid_V" long_name="grid V"/>
+     <!--   Eq section : no V point on the Equator...   -->
+
+     
+     <!--   W grid   -->
+     <domain id="grid_W" long_name="grid W"/>
+     <!--   Eq section   -->
+     <domain id="EqW" domain_ref="grid_W" > <zoom_domain id="EqW"/> </domain>
+
+	           <!--   zonal mean grid   -->
+     <domain_group id="gznl">
+        <domain id="gznl" long_name="gznl"/>
+        <domain id="ptr" domain_ref="gznl" > 
+            <zoom_domain id="ptr" ibegin="0000" jbegin="0" ni="1" nj="0000" /> 
+        </domain>
+      </domain_group>
+
+     
+     <!--   other grids   -->
+     <domain id="scalarpoint" long_name="scalar"/>
+      
+
+   </domain_definition>    
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,626 @@
+<?xml version="1.0"?> 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                              definition of all existing sea ice variables                                =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                  Physical sea ice model variables
+============================================================================================================
+    -->
+
+      <field_group id="SBC" > <!-- time step automaticaly defined based on nn_fsbc -->
+
+	<!-- 2D variables -->
+        <field_group id="SBC_2D" grid_ref="grid_T_2D" >
+
+          <!-- =================== -->
+          <!-- standard ice fields -->  
+          <!-- =================== -->
+	  <!-- ice presence masks -->
+          <field id="icemask"      long_name="Fraction of time steps with sea ice"                     standard_name="sea_ice_mask"                              unit="" />
+          <field id="icemask05"    long_name="Ice mask (0 if ice conc. lower than  5%, 1 otherwise)"   standard_name="sea_ice_mask05"                            unit="" />
+          <field id="icemask15"    long_name="Ice mask (0 if ice conc. lower than 15%, 1 otherwise)"   standard_name="sea_ice_mask15"                            unit="" />
+	  <field id="icepres"      long_name="Fraction of time steps with sea ice"                     standard_name="sea_ice_time_fraction"                     unit="" />
+          <field id="fasticepres"  long_name="Fraction of time steps with landfast ice"                standard_name="fast_ice_time_fraction"                    unit="" />
+ 
+	  <!-- general fields -->
+          <field id="icemass"      long_name="Sea-ice mass per gridcell area"                          standard_name="sea_ice_amount"                            unit="kg/m2"/>
+          <field id="snwmass"      long_name="Snow mass per area"                                      standard_name="liquid_water_content_of_surface_snow"      unit="kg/m2"/>
+          <field id="iceconc"      long_name="Sea-ice area fraction"                                   standard_name="sea_ice_area_fraction"                     unit=""     />
+          <field id="icevolu"      long_name="Sea-ice volume per area"                                 standard_name="sea_ice_thickness"                         unit="m"    />
+          <field id="icethic"      long_name="Sea-ice thickness"                                       standard_name="sea_ice_thickness"                         unit="m"    />
+          <field id="snwthic"      long_name="Snow thickness"                                          standard_name="snow_thickness"                            unit="m"    />
+          <field id="icebrv"       long_name="brine volume"                                                                                                      unit="%"    />
+          <field id="iceage"       long_name="ice age"                                                                                                           unit="days" detect_missing_value="true"/>
+          <field id="icehnew"      long_name="frazil ice collection thickness"                                                                                   unit="m"    />
+          <field id="snwvolu"      long_name="snow volume"                                                                                                       unit="m"    />
+          <field id="icefrb"       long_name="Sea-ice freeboard"                                       standard_name="sea_ice_freeboard"                         unit="m"    />
+          <field id="icealb"       long_name="Sea-ice or snow albedo"                                  standard_name="sea_ice_albedo"                            unit=""    detect_missing_value="true" />
+	  
+	  <!-- melt ponds -->
+	  <field id="iceapnd"      long_name="melt pond concentration"                                 standard_name="sea_ice_meltpond_concentration"            unit=""  /> 
+          <field id="icehpnd"      long_name="melt pond depth"                                         standard_name="sea_ice_meltpond_depth"                    unit="m" /> 
+          <field id="icevpnd"      long_name="melt pond volume"                                        standard_name="sea_ice_meltpond_volume"                   unit="m" /> 
+          <field id="icehlid"      long_name="melt pond lid depth"                                     standard_name="sea_ice_meltpondlid_depth"                 unit="m" /> 
+          <field id="icevlid"      long_name="melt pond lid volume"                                    standard_name="sea_ice_meltpondlid_volume"                unit="m" /> 
+	  
+	  <!-- heat -->
+          <field id="icetemp"      long_name="Mean ice temperature"                                                                                              unit="degC" detect_missing_value="true" />
+          <field id="snwtemp"      long_name="Mean snow temperature"                                                                                             unit="degC" detect_missing_value="true" />
+          <field id="icettop"      long_name="temperature at the ice surface"                                                                                    unit="degC" detect_missing_value="true" />
+          <field id="icetbot"      long_name="temperature at the ice bottom"                                                                                     unit="degC" detect_missing_value="true" />
+          <field id="icetsni"      long_name="temperature at the snow-ice interface"                                                                             unit="degC" detect_missing_value="true" />
+          <field id="icehc"        long_name="ice heat content"                                                                                                  unit="J/m2" /> 
+          <field id="snwhc"        long_name="snow heat content"                                                                                                 unit="J/m2" />
+	  
+	  <!-- salt -->
+          <field id="icesalt"      long_name="Sea ice salinity"                                                                                                  unit="g/kg"  detect_missing_value="true" />
+          <field id="icesalm"      long_name="Mass of salt in sea ice per area"                        standard_name="sea_ice_salt_mass"                         unit="kg/m2" />
+	  
+	  <!-- momentum (rheology) -->
+          <field id="uice"         long_name="X-component of sea ice velocity"                         standard_name="sea_ice_x_velocity"                        unit="m/s"  /> 
+          <field id="vice"         long_name="Y-component of sea ice velocity"                         standard_name="sea_ice_y_velocity"                        unit="m/s"  />      
+          <field id="icevel"       long_name="Sea-ice speed"                                           standard_name="sea_ice_speed"                             unit="m/s"  />
+          <field id="utau_ai"      long_name="X-component of atmospheric stress on sea ice"            standard_name="surface_downward_x_stress"                 unit="N/m2" />
+          <field id="vtau_ai"      long_name="Y-component of atmospheric stress on sea ice"            standard_name="surface_downward_y_stress"                 unit="N/m2" />
+          <field id="utau_oi"      long_name="X-component of ocean stress on sea ice"                  standard_name="sea_ice_base_upward_x_stress"              unit="N/m2" />
+          <field id="vtau_oi"      long_name="Y-component of ocean stress on sea ice"                  standard_name="sea_ice_base_upward_y_stress"              unit="N/m2" />
+          <field id="utau_bi"      long_name="X-component of ocean bottom stress on sea ice -landfast" standard_name="ocean_bottom_upward_x_stress"              unit="N/m2" />
+          <field id="vtau_bi"      long_name="Y-component of ocean bottom stress on sea ice -landfast" standard_name="ocean_bottom_upward_y_stress"              unit="N/m2" />
+          <!-- the fields isig1 isig2 isig3 are obsolete -->
+	  <field id="isig1"        long_name="1st principal stress component for EVP rhg"                                                                        unit=""     />
+          <field id="isig2"        long_name="2nd principal stress component for EVP rhg"                                                                        unit=""     />
+          <field id="isig3"        long_name="convergence measure for EVP rheology (must be around 1)"                                                           unit=""     />
+          <field id="sig1_pnorm"   long_name="P-normalized 1st principal stress component"                                                                       unit=""     />
+          <field id="sig2_pnorm"   long_name="P-normalized 2nd principal stress component"                                                                       unit=""     />
+          <field id="normstr"      long_name="Average normal stress in sea ice"                        standard_name="average_normal_stress"                     unit="N/m"  />
+          <field id="sheastr"      long_name="Maximum shear stress in sea ice"                         standard_name="maximum_shear_stress"                      unit="N/m"  />
+          <field id="icestr"       long_name="Compressive sea ice strength"                            standard_name="compressive_strength_of_sea_ice"           unit="N/m"  />
+          <field id="icediv"       long_name="Divergence of the sea-ice velocity field"                standard_name="divergence_of_sea_ice_velocity"            unit="s-1"  />
+          <field id="iceshe"       long_name="Maximum shear of sea-ice velocity field"                 standard_name="maximum_shear_of_sea_ice_velocity"         unit="s-1"  />
+          <field id="beta_evp"     long_name="Relaxation parameter of ice rheology (beta)"             standard_name="relaxation_parameter_of_ice_rheology"      unit=""  />	 
+ 
+	  <!-- surface heat fluxes -->
+          <field id="qt_ice"       long_name="total heat flux at ice surface"                          standard_name="surface_downward_heat_flux_in_air"         unit="W/m2" />
+          <field id="qsr_ice"      long_name="solar heat flux at ice surface"                          standard_name="surface_downwelling_shortwave_flux_in_air" unit="W/m2" />
+          <field id="qns_ice"      long_name="non-solar heat flux at ice surface (including E-P)"                                                                unit="W/m2" />
+          <field id="qtr_ice_bot"  long_name="solar heat flux transmitted through the ice (to the ocean)"                                                        unit="W/m2" />
+          <field id="qtr_ice_top"  long_name="solar heat flux transmitted through the ice surface"                                                               unit="W/m2" />
+          <field id="qt_oce_ai"    long_name="total heat flux at the ocean   surface: interface oce-(ice+atm)"                                                   unit="W/m2" />
+          <field id="qt_atm_oi"    long_name="total heat flux at the oce-ice surface: interface atm-(ice+oce)"                                                   unit="W/m2" />
+          <field id="qemp_ice"     long_name="Downward Heat Flux from E-P over ice"                                                                              unit="W/m2" />
+          <field id="albedo"       long_name="Mean albedo over sea ice and ocean"                                                                                unit=""     />
+	  
+	  <!-- trends -->
+          <field id="afxthd"       long_name="sea-ice area fraction change from thermodynamics" standard_name="tendency_of_sea_ice_area_fraction_due_to_dynamics" unit="s-1" />
+          <field id="afxdyn"       long_name="sea-ice area fraction change from dynamics"       standard_name="tendency_of_sea_ice_area_fraction_due_to_dynamics" unit="s-1" />
+	  <field id="afxtot"       long_name="area tendency (total)"                                                                                              unit="s-1" />
+	  
+	  <!-- momentum (advection) -->
+          <field id="icemtrp"      long_name="ice  mass transport"                                          unit="kg/m2/s" />
+          <field id="snwmtrp"      long_name="snw  mass transport"                                          unit="kg/m2/s" />
+          <field id="salmtrp"      long_name="salt mass transport"                                          unit="kg/m2/s" />
+          <field id="dihctrp"      long_name="ice heat content transport"                                   unit="W/m2"    />
+          <field id="dshctrp"      long_name="snw heat content transport"                                   unit="W/m2"    />
+	  
+	  <!-- salt fluxes -->
+          <field id="sfxice"       long_name="ice-ocean salt flux from ice growth/melt (neg = growth)"      unit="kg/m2/s" />
+          <field id="sfxbog"       long_name="ice-ocean salt flux from ice bottom growth"                   unit="kg/m2/s" />
+          <field id="sfxbom"       long_name="ice-ocean salt flux from ice bottom melt"                     unit="kg/m2/s" />
+          <field id="sfxsum"       long_name="ice-ocean salt flux from ice surface melt"                    unit="kg/m2/s" />
+          <field id="sfxlam"       long_name="ice-ocean salt flux from ice lateral melt"                    unit="kg/m2/s" />
+          <field id="sfxsni"       long_name="ice-ocean salt flux from snow-ice formation"                  unit="kg/m2/s" />
+          <field id="sfxopw"       long_name="ice-ocean salt flux from ice formation in open water"         unit="kg/m2/s" />
+          <field id="sfxdyn"       long_name="ice-ocean salt flux from ice dynamics (ridging)"              unit="kg/m2/s" />
+          <field id="sfxbri"       long_name="ice-ocean salt flux from brines"                              unit="kg/m2/s" />
+          <field id="sfxres"       long_name="ice-ocean salt flux from undiagnosed processes"               unit="kg/m2/s" />
+          <field id="sfxsub"       long_name="ice-ocean salt flux from ice sublimation"                     unit="kg/m2/s" />
+
+	  <!-- mass fluxes -->
+          <field id="vfxice"       long_name="ice-ocean mass flux from ice melt/growth (neg = growth)"      unit="kg/m2/s" />
+          <field id="vfxbog"       long_name="ice-ocean mass flux from ice bottom growth"                   unit="kg/m2/s" />
+          <field id="vfxbom"       long_name="ice-ocean mass flux from ice bottom melt"                     unit="kg/m2/s" />
+          <field id="vfxsum"       long_name="ice-ocean mass flux from ice surface melt"                    unit="kg/m2/s" />
+          <field id="vfxlam"       long_name="ice-ocean mass flux from ice lateral melt"                    unit="kg/m2/s" />
+          <field id="vfxsni"       long_name="ice-ocean mass flux from snow-ice formation"                  unit="kg/m2/s" />
+          <field id="vfxopw"       long_name="ice-ocean mass flux from ice growth in open water"            unit="kg/m2/s" />
+          <field id="vfxdyn"       long_name="ice-ocean mass flux from ice dynamics (ridging)"              unit="kg/m2/s" />
+          <field id="vfxres"       long_name="ice-ocean mass flux from undiagnosed processes"               unit="kg/m2/s" />
+          <field id="vfxpnd"       long_name="ice-ocean mass flux from ice melt ponds"                      unit="kg/m2/s" />
+          <field id="vfxsub"       long_name="ice-atm.  mass flux from ice sublimation"                     unit="kg/m2/s" />
+          <field id="vfxsub_err"   long_name="ice-ocean mass flux from unbalance in sublimation (incl. in qt_oce_ai)" unit="kg/m2/s" />
+          <field id="vfxthin"      long_name="ice-ocean mass flux from ice growth in open water + thin ice(20cm)"     unit="kg/m2/s" />
+
+          <field id="vfxsnw"       long_name="ice-ocean mass flux from snw melt/growth (neg = growth)"      unit="kg/m2/s" />
+          <field id="vfxsnw_sum"   long_name="ice-ocean mass flux from snw surface melt"                    unit="kg/m2/s" />
+          <field id="vfxsnw_sni"   long_name="ice-ocean mass flux from snow-ice formation"                  unit="kg/m2/s" />
+          <field id="vfxsnw_dyn"   long_name="ice-ocean mass flux from dynamics (ridging)"                  unit="kg/m2/s" />
+          <field id="vfxsnw_sub"   long_name="ice-atm.  mass flux from snw sublimation"                     unit="kg/m2/s" />
+          <field id="vfxsnw_pre"   long_name="snw precipitation on ice"                                     unit="kg/m2/s" />
+
+	  <!-- heat fluxes -->
+          <field id="hfxbog"       long_name="heat flux used for bottom ice growth (neg.)"                  unit="W/m2" />
+          <field id="hfxbom"       long_name="heat flux used for bottom ice melt (pos.)"                    unit="W/m2" />
+          <field id="hfxsum"       long_name="heat flux used for surface ice melt"                          unit="W/m2" />
+          <field id="hfxopw"       long_name="heat flux used for open water ice formation"                  unit="W/m2" />
+          <field id="hfxdif"       long_name="heat flux used for ice temperature change"                    unit="W/m2" />
+          <field id="hfxsnw"       long_name="heat flux used for snow melt"                                 unit="W/m2" />
+          <field id="hfxerr"       long_name="heat flux error after heat diffusion"                         unit="W/m2" />
+          <!-- heat fluxes 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 undiagnosed processes"                       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" />
+
+          <field id="hfxsensib"    long_name="Net sensible heat flux under sea ice (neg = ice cooling)"         standard_name="ice_ocean_heat_flux"                        unit="W/m2" />
+          <field id="hfxcndtop"    long_name="Net conductive heat flux at the ice surface (neg = ice cooling)"  standard_name="conductive_heat_flux_at_sea_ice_surface"    unit="W/m2" /> 
+          <field id="hfxcndbot"    long_name="Net conductive heat flux at the ice bottom (neg = ice cooling)"   standard_name="conductive_heat_flux_at_sea_ice_bottom"     unit="W/m2" />
+
+          <!-- diags -->
+          <field id="hfxdhc"       long_name="Heat content variation in snow and ice (neg = ice cooling)"   unit="W/m2" />
+
+	  <!-- sbcssm variables -->
+          <field id="sst_m"    unit="degC" />
+          <field id="sss_m"    unit="psu"  />
+          <field id="ssu_m"    unit="m/s"  />
+          <field id="ssv_m"    unit="m/s"  />
+          <field id="ssh_m"    unit="m"    />
+          <field id="e3t_m"    unit="m"    />
+          <field id="frq_m"    unit="-"    />
+
+          <!-- rheology convergence tests -->
+          <field id="uice_cvg"   long_name="sea ice velocity convergence"      standard_name="sea_ice_velocity_convergence"      unit="m/s" />
+
+	  <!-- ================= -->
+          <!-- Add-ons for SIMIP -->
+          <!-- ================= -->
+          <field id="icemass_cmip" long_name="Sea-ice mass per area"                                   standard_name="sea_ice_amount"                          detect_missing_value="true" unit="kg/m2"  > icemass * icemask   + $missval * (1.-icemask  ) </field>
+          <field id="icethic_cmip" long_name="Sea-ice thickness"                                       standard_name="sea_ice_thickness"                       detect_missing_value="true" unit="m"      > icethic * icemask05 + $missval * (1.-icemask05) </field>
+          <field id="snwmass_cmip" long_name="Snow mass per area"                                      standard_name="liquid_water_content_of_surface_snow"    detect_missing_value="true" unit="kg/m2"  > snwmass * icemask   + $missval * (1.-icemask  ) </field>
+          <field id="snwthic_cmip" long_name="Snow thickness"                                          standard_name="surface_snow_thickness"                  detect_missing_value="true" unit="m"      > snwthic * icemask05 + $missval * (1.-icemask05) </field>
+          <field id="iceconc_pct"  long_name="Sea-ice area fraction in percent"                        standard_name="sea_ice_area_fraction_in_percent"                                    unit="%"      > iceconc * 100.                                  </field>
+          <field id="iceage_cmip"  long_name="Age of sea ice"                                          standard_name="age_of_sea_ice"                          detect_missing_value="true" unit="days"   > iceage  * icemask15 + $missval * (1.-icemask15) </field>
+          <field id="icesalt_cmip" long_name="Sea ice salinity"                                        standard_name="sea_ice_salinity"                        detect_missing_value="true" unit="g/kg"   > icesalt * icemask   + $missval * (1.-icemask  ) </field>
+          <field id="icefrb_cmip"  long_name="Sea-ice freeboard"                                       standard_name="sea_ice_freeboard"                       detect_missing_value="true" unit="m"      > icefrb  * icemask   + $missval * (1.-icemask  ) </field>
+
+	  <!-- heat -->
+          <field id="icettop_cmip" long_name="Surface temperature of sea ice"                          standard_name="sea_ice_surface_temperature"             detect_missing_value="true" unit="K"  > (icettop+273.15) * icemask + $missval * (1.-icemask) </field>
+          <field id="icetsni_cmip" long_name="Temperature at snow-ice interface"                       standard_name="sea_ice_snow_interface_temperature"      detect_missing_value="true" unit="K"  > (icetsni+273.15) * icemask + $missval * (1.-icemask) </field>
+          <field id="icetbot_cmip" long_name="Temperature at ice-ocean interface"                      standard_name="sea_ice_bottom_temperature"              detect_missing_value="true" unit="K"  > (icetbot+273.15) * icemask + $missval * (1.-icemask) </field>
+          <field id="icehc_cmip"   long_name="Sea-ice heat content per unit area"                      standard_name="integral_of_sea_ice_temperature_wrt_depth_expressed_as_heat_content" detect_missing_value="true" unit="J/m2" > icehc * icemask + $missval * (1.-icemask) </field>
+          <field id="snwhc_cmip"   long_name="Snow-heat content per unit area"                         standard_name="thermal_energy_content_of_surface_snow"                              detect_missing_value="true" unit="J/m2" > snwhc * icemask + $missval * (1.-icemask) </field>
+
+	  <!-- fluxes (mass, heat, salt) -->
+          <field id="vfxsum_cmip"    long_name="Freshwater flux from sea-ice surface"                  standard_name="freshwater_flux_from_ice_surface"        detect_missing_value="true" unit="kg/m2/s"  > vfxsum    * icemask + $missval * (1.-icemask) </field>
+          <field id="vfxice_cmip"    long_name="Freshwater flux from sea ice"                          standard_name="freshwater_flux_from_ice"                detect_missing_value="true" unit="kg/m2/s"  > vfxice    * icemask + $missval * (1.-icemask) </field>
+          <field id="hfxsensib_cmip" long_name="Net sensible heat flux under sea ice"                  standard_name="ice_ocean_heat_flux"                     detect_missing_value="true" unit="W/m2"     > hfxsensib * icemask + $missval * (1.-icemask) </field> 
+          <field id="hfxcndtop_cmip" long_name="Net conductive heat flux at the ice surface"           standard_name="conductive_heat_flux_at_sea_ice_surface" detect_missing_value="true" unit="W/m2"     > hfxcndtop * icemask + $missval * (1.-icemask) </field> 
+          <field id="hfxcndbot_cmip" long_name="Net conductive heat flux at the ice bottom"            standard_name="conductive_heat_flux_at_sea_ice_bottom"  detect_missing_value="true" unit="W/m2"     > hfxcndbot * icemask + $missval * (1.-icemask) </field>
+          <field id="sfxice_cmip"    long_name="Salt flux from sea ice"                                standard_name="salt_flux_from_ice"                      detect_missing_value="true" unit="kg/m2/s"  > sfxice    * icemask + $missval * (1.-icemask) </field>
+
+	  <!-- trends -->
+          <field id="dmithd"       long_name="sea-ice mass change from thermodynamics"                 standard_name="tendency_of_sea_ice_amount_due_to_thermodynamics"                        unit="kg/m2/s" />
+          <field id="dmidyn"       long_name="sea-ice mass change from dynamics"                       standard_name="tendency_of_sea_ice_amount_due_to_dynamics"                              unit="kg/m2/s" />
+          <field id="dmiopw"       long_name="sea-ice mass change through growth in supercooled open water (frazil)" standard_name="tendency_of_sea_ice_amount_due_to_freezing_in_open_water"  unit="kg/m2/s" />
+          <field id="dmibog"       long_name="sea-ice mass change through basal growth"                standard_name="tendency_of_sea_ice_amount_due_to_congelation_ice_accumulation"          unit="kg/m2/s" />
+          <field id="dmisni"       long_name="sea-ice mass change through snow-to-ice conversion"      standard_name="tendency_of_sea_ice_amount_due_to_snow_conversion"                       unit="kg/m2/s" />
+          <field id="dmtsub"       long_name="snow and sea ice mass change through sublimation"        standard_name="tendency_of_snow_and_ice_amount_due_to_sublimation"                      unit="kg/m2/s" />
+          <field id="dmssub"       long_name="sea-ice mass change through evaporation and sublimation" standard_name="water_evaporation_flux"                                                  unit="kg/m2/s" />
+          <field id="dmisub"       long_name="snow mass change through evaporation or sublimation"     standard_name="surface_snow_sublimation_flux"                                           unit="kg/m2/s" />
+          <field id="dmisum"       long_name="sea-ice mass change through surface melting"             standard_name="tendency_of_sea_ice_amount_due_to_surface_melting"                       unit="kg/m2/s" />
+          <field id="dmibom"       long_name="sea-ice mass change through bottom melting"              standard_name="tendency_of_sea_ice_amount_due_to_basal_melting"                         unit="kg/m2/s" />
+          <field id="dmilam"       long_name="sea-ice mass change through lateral melting"             standard_name="tendency_of_sea_ice_amount_due_to_lateral_melting"                       unit="kg/m2/s" />
+          <field id="dmsspr"       long_name="snow mass change through snow fall"                      standard_name="snowfall_flux"                                                           unit="kg/m2/s" />
+          <field id="dmsmel"       long_name="snow mass change through melt"                           standard_name="surface_snow_melt_flux"                                                  unit="kg/m2/s" />
+          <field id="dmsdyn"       long_name="snow mass change through advection by sea-ice dynamics"  standard_name="tendency_of_snow_mass_due_to_sea_ice_dynamics"                           unit="kg/m2/s" />
+          <field id="dmsssi"       long_name="snow mass change through snow-to-ice conversion"         standard_name="tendency_of_snow_mass_due_to_snow_to_ice_conversion"                     unit="kg/m2/s" />
+
+	  <!-- momentum (rheology) -->
+          <field id="uice_cmip"    long_name="X-component of sea ice velocity"                         standard_name="sea_ice_x_velocity"                    detect_missing_value="true" unit="m/s"   > uice    * icemask + $missval * (1.-icemask) </field>
+          <field id="vice_cmip"    long_name="Y-component of sea ice velocity"                         standard_name="sea_ice_y_velocity"                    detect_missing_value="true" unit="m/s"   > vice    * icemask + $missval * (1.-icemask) </field>     
+          <field id="icevel_cmip"  long_name="Sea-ice speed"                                           standard_name="sea_ice_speed"                         detect_missing_value="true" unit="m/s"   > icevel  * icemask + $missval * (1.-icemask) </field> 
+          <field id="utau_ai_cmip" long_name="X-component of atmospheric stress on sea ice"            standard_name="surface_downward_x_stress"             detect_missing_value="true" unit="N/m2"  > utau_ai * icemask + $missval * (1.-icemask) </field>
+          <field id="vtau_ai_cmip" long_name="Y-component of atmospheric stress on sea ice"            standard_name="surface_downward_y_stress"             detect_missing_value="true" unit="N/m2"  > vtau_ai * icemask + $missval * (1.-icemask) </field>
+          <field id="dssh_dx"      long_name="Sea-surface tilt term in force balance (x-component)"    standard_name="sea_surface_tilt_force_on_sea_ice_x"                               unit="N/m2" />
+          <field id="dssh_dy"      long_name="Sea-surface tilt term in force balance (y-component)"    standard_name="sea_surface_tilt_force_on_sea_ice_y"                               unit="N/m2" />
+          <field id="corstrx"      long_name="Coriolis force term in force balance (x-component)"      standard_name="coriolis_force_on_sea_ice_x"                                       unit="N/m2" />
+          <field id="corstry"      long_name="Coriolis force term in force balance (y-component)"      standard_name="coriolis_force_on_sea_ice_y"                                       unit="N/m2" />
+          <field id="intstrx"      long_name="Internal stress term in force balance (x-component)"     standard_name="internal_stress_in_sea_ice_x"                                      unit="N/m2" />
+          <field id="intstry"      long_name="Internal stress term in force balance (y-component)"     standard_name="internal_stress_in_sea_ice_y"                                      unit="N/m2" />
+
+	  <!-- momentum (advection) -->
+    	  <field id="xmtrpice"     long_name="X-component of ice mass transport"                       standard_name="ice_x_transport"       grid_ref="grid_U_2D"         unit="kg/s" />
+          <field id="ymtrpice"     long_name="Y-component of ice mass transport"                       standard_name="ice_y_transport"       grid_ref="grid_V_2D"         unit="kg/s" />
+          <field id="xmtrpsnw"     long_name="X-component of snw mass transport"                       standard_name="snw_x_transport"       grid_ref="grid_U_2D"         unit="kg/s" />
+          <field id="ymtrpsnw"     long_name="Y-component of snw mass transport"                       standard_name="snw_y_transport"       grid_ref="grid_V_2D"         unit="kg/s" />
+          <field id="xatrp"        long_name="X-component of ice area transport"                       standard_name="area_x_transport"      grid_ref="grid_U_2D"         unit="m2/s" />
+          <field id="yatrp"        long_name="Y-component of ice area transport"                       standard_name="area_y_transport"      grid_ref="grid_V_2D"         unit="m2/s" />
+          <field id="xmtrptot"     long_name="X-component of sea-ice mass transport"                   standard_name="sea_ice_x_transport"   grid_ref="grid_U_2D"         unit="kg/s" > xmtrpice + xmtrpsnw </field>
+    	  <field id="ymtrptot"     long_name="Y-component of sea-ice mass transport"                   standard_name="sea_ice_y_transport"   grid_ref="grid_V_2D"         unit="kg/s" > ymtrpice + ymtrpsnw </field>
+
+	  <!-- Ice transport through straits" -->
+         <field id="xmtrpice_ave"     long_name="Monthly average of x-ice mass transport"   field_ref="xmtrpice"          grid_ref="grid_U_2D"        freq_op="1mo" freq_offset="_reset_"  > @xmtrpice </field>
+         <field id="xmtrpice_section"                                                                                     grid_ref="grid_U_scalar"  > xmtrpice_ave </field>
+         <field id="xmtrpice_strait"                                                        field_ref="xmtrpice_section"  grid_ref="grid_U_4strait_ice"  />
+         <field id="xstrait_mifl"                                                           field_ref="xmtrpice_strait"   grid_ref="grid_U_4strait_ice_hsum" unit="kg/s" detect_missing_value="true" > this * maskMFO_u_ice </field>
+
+         <field id="ymtrpice_ave"     long_name="Monthly average of y-ice mass transport"   field_ref="ymtrpice"          grid_ref="grid_V_2D"        freq_op="1mo" freq_offset="_reset_"  > @ymtrpice </field>
+         <field id="ymtrpice_section"                                                                                     grid_ref="grid_V_scalar"  > ymtrpice_ave </field>
+         <field id="ymtrpice_strait"                                                        field_ref="ymtrpice_section"  grid_ref="grid_V_4strait_ice"  />
+	 <field id="ystrait_mifl"                                                           field_ref="ymtrpice_strait"   grid_ref="grid_V_4strait_ice_hsum" unit="kg/s" detect_missing_value="true"  > this * maskMFO_v_ice </field>
+
+         <field id="xmtrpsnw_ave"     long_name="Monthly average of x-snow mass transport"  field_ref="xmtrpsnw"          grid_ref="grid_U_2D"        freq_op="1mo" freq_offset="_reset_"  > @xmtrpsnw </field>
+         <field id="xmtrpsnw_section"                                                                                     grid_ref="grid_U_scalar"  > xmtrpsnw_ave </field>
+         <field id="xmtrpsnw_strait"                                                        field_ref="xmtrpsnw_section"  grid_ref="grid_U_4strait_ice"  />
+         <field id="xstrait_msfl"                                                           field_ref="xmtrpsnw_strait"   grid_ref="grid_U_4strait_ice_hsum" unit="kg/s" detect_missing_value="true" > this * maskMFO_u_ice </field>
+
+         <field id="ymtrpsnw_ave"     long_name="Monthly average of y-snow mass transport"  field_ref="ymtrpsnw"          grid_ref="grid_V_2D"        freq_op="1mo" freq_offset="_reset_"  > @ymtrpsnw </field>
+         <field id="ymtrpsnw_section"                                                                                     grid_ref="grid_V_scalar"  > ymtrpsnw_ave </field>
+         <field id="ymtrpsnw_strait"                                                        field_ref="ymtrpsnw_section"  grid_ref="grid_V_4strait_ice"  />
+	 <field id="ystrait_msfl"                                                           field_ref="ymtrpsnw_strait"   grid_ref="grid_V_4strait_ice_hsum" unit="kg/s" detect_missing_value="true"  > this * maskMFO_v_ice </field>
+
+         <field id="xatrp_ave"        long_name="Monthly average of x-ice area transport"   field_ref="xatrp"             grid_ref="grid_U_2D"        freq_op="1mo" freq_offset="_reset_"  > @xatrp </field>
+         <field id="xatrp_section"                                                                                        grid_ref="grid_U_scalar"  > xatrp_ave </field>
+         <field id="xatrp_strait"                                                           field_ref="xatrp_section"     grid_ref="grid_U_4strait_ice"  />
+         <field id="xstrait_arfl"                                                           field_ref="xatrp_strait"      grid_ref="grid_U_4strait_ice_hsum" unit="kg/s" detect_missing_value="true" > this * maskMFO_u_ice </field>
+
+         <field id="yatrp_ave"        long_name="Monthly average of y-ice area transport"   field_ref="yatrp"             grid_ref="grid_V_2D"        freq_op="1mo" freq_offset="_reset_"  > @yatrp </field>
+         <field id="yatrp_section"                                                                                        grid_ref="grid_V_scalar"  > yatrp_ave </field>
+         <field id="yatrp_strait"                                                           field_ref="yatrp_section"     grid_ref="grid_V_4strait_ice"  />
+	 <field id="ystrait_arfl"                                                           field_ref="yatrp_strait"      grid_ref="grid_V_4strait_ice_hsum" unit="m2/s" detect_missing_value="true"  > this * maskMFO_v_ice </field>
+
+         <field id="strait_mifl"      long_name="Sea ice mass flux through straits"      standard_name="sea_ice_mass_transport_across_line"   unit="kg/s"  freq_op="1mo"  grid_ref="grid_4strait_ice" > xstrait_mifl + ystrait_mifl </field>
+         <field id="strait_msfl"      long_name="Snow mass flux through straits"         standard_name="snow_mass_transport_across_line"      unit="kg/s"  freq_op="1mo"  grid_ref="grid_4strait_ice" > xstrait_msfl + ystrait_msfl </field>
+	 <field id="strait_arfl"      long_name="Sea ice area flux through straits"      standard_name="sea_area_mass_transport_across_line"  unit="m2/s"  freq_op="1mo"  grid_ref="grid_4strait_ice" > xstrait_arfl + ystrait_arfl </field>
+
+	</field_group> <!-- SBC_2D -->
+
+	<!-- categories -->
+        <field_group id="SBC_3D" grid_ref="grid_T_ncatice" >
+
+          <!-- standard ice fields -->  
+	  <field id="iceconc_cat"  long_name="Sea-ice concentration per category"                unit=""        />
+          <field id="icethic_cat"  long_name="Sea-ice thickness per category"                    unit="m"       detect_missing_value="true" />
+          <field id="snwthic_cat"  long_name="Snow thickness per category"                       unit="m"       detect_missing_value="true" />
+          <field id="icesalt_cat"  long_name="Sea-Ice Bulk salinity per category"                unit="g/kg"    detect_missing_value="true" />
+          <field id="icetemp_cat"  long_name="Ice temperature per category"                      unit="degC"    detect_missing_value="true" />
+          <field id="snwtemp_cat"  long_name="Snow temperature per category"                     unit="degC"    detect_missing_value="true" />
+          <field id="icettop_cat"  long_name="Ice/snow surface temperature per category"         unit="degC"    detect_missing_value="true" />
+          <field id="iceapnd_cat"  long_name="Ice melt pond concentration per category"          unit=""        /> 
+          <field id="icehpnd_cat"  long_name="Ice melt pond thickness per category"              unit="m"       detect_missing_value="true" /> 
+          <field id="icehlid_cat"  long_name="Ice melt pond lid thickness per category"          unit="m"       detect_missing_value="true" /> 
+          <field id="iceafpnd_cat" long_name="Ice melt pond fraction per category"               unit=""        /> 
+          <field id="iceaepnd_cat" long_name="Ice melt pond effective fraction per category"     unit=""        /> 
+          <field id="icemask_cat"  long_name="Fraction of time step with sea ice (per category)" unit=""        />
+          <field id="iceage_cat"   long_name="Ice age per category"                              unit="days"    detect_missing_value="true" />
+          <field id="icebrv_cat"   long_name="Brine volume per category"                         unit="%"       detect_missing_value="true" />
+          <field id="icealb_cat"   long_name="Sea-ice or snow albedo"                            unit=""        detect_missing_value="true" />
+
+          <!-- Add-ons for SIMIP -->
+          <field id="iceconc_cat_cmip"     long_name="Sea-ice area fractions in thickness categories"  standard_name="sea_ice_area_fraction_over_categories" detect_missing_value="true" unit=""   > iceconc_cat      * icemask_cat + $missval * (1.-icemask_cat) </field>
+          <field id="icethic_cat_cmip"     long_name="Sea-ice thickness in thickness categories"       standard_name="sea_ice_thickness_over_categories"     detect_missing_value="true" unit="m"  > icethic_cat      * icemask_cat + $missval * (1.-icemask_cat) </field>
+          <field id="snwthic_cat_cmip"     long_name="Snow thickness in thickness categories"          standard_name="snow_thickness_over_categories"        detect_missing_value="true" unit="m"  > snwthic_cat      * icemask_cat + $missval * (1.-icemask_cat) </field>
+          <field id="iceconc_cat_pct_cmip" long_name="Sea-ice area fractions in thickness categories"  standard_name="sea_ice_area_fraction_over_categories" detect_missing_value="true" unit="%"  > iceconc_cat*100. * icemask_cat + $missval * (1.-icemask_cat) </field>
+
+          <!-- heat diffusion convergence tests -->
+          <field id="tice_cvgerr" long_name="sea ice temperature convergence error"      standard_name="sea_ice_temperature_convergence_err" unit="K" />
+          <field id="tice_cvgstp" long_name="sea ice temperature convergence iterations" standard_name="sea_ice_temperature_convergence_stp" unit=""  />
+
+	</field_group> <!-- SBC_3D -->
+	
+	<!-- scalar variables -->
+	<field_group id="SBC_scalar"  grid_ref="grid_scalar" >
+          <field id="NH_iceextt"      long_name="Sea ice extent North"                   standard_name="sea_ice_extent_n"                   unit="1e6_km2"  />
+          <field id="SH_iceextt"      long_name="Sea ice extent South"                   standard_name="sea_ice_extent_s"                   unit="1e6_km2"  />
+          <field id="NH_icevolu"      long_name="Sea ice volume North"                   standard_name="sea_ice_volume_n"                   unit="1e3_km3"  />
+          <field id="SH_icevolu"      long_name="Sea ice volume South"                   standard_name="sea_ice_volume_s"                   unit="1e3_km3"  />
+          <field id="NH_icearea"      long_name="Sea ice area North"                     standard_name="sea_ice_area_n"                     unit="1e6_km2"  />
+          <field id="SH_icearea"      long_name="Sea ice area South"                     standard_name="sea_ice_area_s"                     unit="1e6_km2"  />
+
+          <!-- available with ln_icediaout -->
+          <field id="ibgfrcvoltop"    long_name="global mean ice/snow forcing at interface ice/snow-atm (volume equivalent ocean volume)"   unit="km3"      />
+          <field id="ibgfrcvolbot"    long_name="global mean ice/snow forcing at interface ice/snow-ocean (volume equivalent ocean volume)" unit="km3"      />
+          <field id="ibgfrctemtop"    long_name="global mean heat on top of ice/snw/ocean-atm "                                             unit="1e20J"    />
+          <field id="ibgfrctembot"    long_name="global mean heat below ice (on top of ocean) "                                             unit="1e20J"    />
+          <field id="ibgfrcsal"       long_name="global mean ice/snow forcing (salt equivalent ocean volume)"                               unit="pss*km3"  />
+          <field id="ibgfrchfxtop"    long_name="global mean heat flux on top of ice/snw/ocean-atm "                                        unit="W/m2"     />
+          <field id="ibgfrchfxbot"    long_name="global mean heat flux below ice (on top of ocean) "                                        unit="W/m2"     />
+	  
+          <field id="ibgvolume"       long_name="drift in ice/snow volume (equivalent ocean volume)"                                        unit="km3"      />
+          <field id="ibgsaltco"       long_name="drift in ice salt content (equivalent ocean volume)"                                       unit="pss*km3"  />
+          <field id="ibgheatco"       long_name="drift in ice/snow heat content"                                                            unit="1e20J"    />
+          <field id="ibgheatfx"       long_name="drift in ice/snow heat flux"                                                               unit="W/m2"     />
+
+          <field id="ibgvol_tot"      long_name="global mean ice volume"                                                                    unit="km3"      />
+          <field id="sbgvol_tot"      long_name="global mean snow volume"                                                                   unit="km3"      />
+          <field id="ibgarea_tot"     long_name="global mean ice area"                                                                      unit="km2"      />
+          <field id="ibgsalt_tot"     long_name="global mean ice salt content"                                                              unit="1e-3*km3" />
+          <field id="ibgheat_tot"     long_name="global mean ice heat content"                                                              unit="1e20J"    />
+          <field id="sbgheat_tot"     long_name="global mean snow heat content"                                                             unit="1e20J"    />
+
+	</field_group>
+  
+	<!-- 
+============================================================================================================
+	-->
+	<!-- output variables for my configuration (example) --> 
+      
+	<field_group id="myvarICE"        grid_ref="grid_T_2D" >
+	  <!-- ice mask -->
+	  <field field_ref="icemask"          name="simsk"   />
+	  <field field_ref="icemask05"        name="simsk05" />
+	  <field field_ref="icemask15"        name="simsk15" />
+	  
+	  <!-- general -->
+	  <field field_ref="snwvolu"          name="snvolu" />
+	  <field field_ref="snwthic"          name="snthic" />
+	  <field field_ref="icethic"          name="sithic" />
+<!--
+	  <field field_ref="icethic"          name="sithic_max" operation="maximum" />
+	  <field field_ref="icethic"          name="sithic_min" operation="minimum" />
+-->
+	  <field field_ref="fasticepres"      name="fasticepres" />
+	  <field field_ref="icevolu"          name="sivolu" />
+	  <field field_ref="iceconc"          name="siconc" />
+	  <field field_ref="icesalt"          name="sisali" />
+	  <field field_ref="iceapnd"          name="siapnd" />
+	  <field field_ref="icehpnd"          name="sihpnd" />
+	  <field field_ref="icevpnd"          name="sivpnd" />
+          <field field_ref="iceage"           name="siage"  />
+	  <field field_ref="sst_m"            name="sst_m"  />
+	  <field field_ref="sss_m"            name="sss_m"  />
+	  
+	  <!-- heat -->
+	  <field field_ref="icetemp"          name="sitemp" />
+	  <field field_ref="snwtemp"          name="sntemp" />
+	  <field field_ref="icettop"          name="sittop" />
+	  <field field_ref="icetbot"          name="sitbot" />
+	  <field field_ref="icetsni"          name="sitsni" />
+	  
+	  <!-- momentum -->
+	  <field field_ref="uice"             name="sivelu"  />
+	  <field field_ref="vice"             name="sivelv"  />
+	  <field field_ref="icevel"           name="sivelo"  />
+	  <field field_ref="utau_ai"          name="utau_ai" />
+	  <field field_ref="vtau_ai"          name="vtau_ai" />
+	  <field field_ref="utau_oi"          name="utau_oi" />
+	  <field field_ref="vtau_oi"          name="vtau_oi" />
+	  
+	  <!-- rheology -->
+	  <field field_ref="icediv"           name="sidive"  />
+	  <field field_ref="iceshe"           name="sishea"  />
+	  <field field_ref="icestr"           name="sistre"  />
+	  <field field_ref="normstr"          name="normstr" />
+	  <field field_ref="sheastr"          name="sheastr" />
+	  
+	  <!-- heat fluxes -->
+	  <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+	  <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+	  <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+	  <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+	  <field field_ref="qt_ice"           name="qt_ice"     />
+	  <field field_ref="qsr_ice"          name="qsr_ice"    />
+	  <field field_ref="qns_ice"          name="qns_ice"    />
+	  <field field_ref="qemp_ice"         name="qemp_ice"   />
+	  <field field_ref="albedo"           name="albedo"     />
+          <field field_ref="icealb"           name="icealb"     />
+	  
+	  <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+	  <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+	  <field field_ref="hfxsensib"        name="hfxsensib"  />
+
+	  <field field_ref="icehc"         name="icehc"  />
+	  <field field_ref="snwhc"         name="snwhc"  />
+	  <field field_ref="hfxbog"        name="hfxbog"  />
+	  <field field_ref="hfxbom"        name="hfxbom"  />
+	  <field field_ref="hfxsum"        name="hfxsum"  />
+	  <field field_ref="hfxopw"        name="hfxopw"  />
+	  <field field_ref="hfxdif"        name="hfxdif"  />
+	  <field field_ref="hfxsnw"        name="hfxsnw"  />
+	  <field field_ref="hfxerr"        name="hfxerr"  />
+	  <field field_ref="hfxthd"        name="hfxthd"  />
+	  <field field_ref="hfxdyn"        name="hfxdyn"  />
+	  <field field_ref="hfxres"        name="hfxres"  />
+	  <field field_ref="hfxsub"        name="hfxsub"  />
+	  <field field_ref="hfxspr"        name="hfxspr"  />
+
+<!--
+	  <field field_ref="hfxdhc"        name="hfxbudget"  operation="average" freq_op="1d" > @qt_atm_oi - @qt_oce_ai -@hfxdhc </field>
+-->
+	  
+	  <!-- salt fluxes -->
+	  <field field_ref="sfxice"           name="sfxice" />
+	  
+	  <!-- mass fluxes -->
+	  <field field_ref="vfxice"           name="vfxice" />
+	  <field field_ref="vfxsnw"           name="vfxsnw" />
+
+	  <field field_ref="vfxbom"           name="vfxbom" />
+	  <field field_ref="vfxbog"           name="vfxbog" />
+	  <field field_ref="vfxsum"           name="vfxsum" />
+	  <field field_ref="vfxopw"           name="vfxopw" />
+	  <field field_ref="vfxlam"           name="vfxlam" />
+	  <field field_ref="vfxsni"           name="vfxsni" />
+	  <field field_ref="vfxdyn"           name="vfxdyn" />
+	  <field field_ref="vfxres"           name="vfxres" />
+	  <field field_ref="vfxpnd"           name="vfxpnd" />
+	  <field field_ref="vfxsub"           name="vfxsub" />
+	  <field field_ref="vfxsub_err"       name="vfxsub_err" />
+          <field field_ref="vfxthin"          name="vfxthin" />
+	
+	  <!-- diag error for negative ice volume after advection -->
+	  <field field_ref="iceneg_pres"      name="sineg_pres" />
+	  <field field_ref="iceneg_volu"      name="sineg_volu" />
+	  <field field_ref="iceneg_hfx"       name="sineg_hfx"  />
+        </field_group>
+
+
+        <field_group id="myvarICE_cat"        grid_ref="grid_T_ncatice" >
+
+	  <!-- categories -->
+	  <field field_ref="icemask_cat"      name="simskcat"/>
+	  <field field_ref="snwthic_cat"      name="snthicat"/>
+	  <field field_ref="iceconc_cat"      name="siconcat"/>
+	  <field field_ref="icethic_cat"      name="sithicat"/>
+	  <field field_ref="icesalt_cat"      name="sisalcat"/>
+	  <field field_ref="icetemp_cat"      name="sitemcat"/>
+	  <field field_ref="snwtemp_cat"      name="sntemcat"/>
+	  <field field_ref="icettop_cat"      name="sitopcat"/>
+
+	</field_group>    
+
+	<field_group id="ICE_globalbudget"  grid_ref="grid_scalar" >
+	  <!-- global contents -->
+    	  <field field_ref="ibgvol_tot"       name="ibgvol_tot"   />
+	  <field field_ref="sbgvol_tot"       name="sbgvol_tot"   />
+    	  <field field_ref="ibgarea_tot"      name="ibgarea_tot"  />
+    	  <field field_ref="ibgsalt_tot"      name="ibgsalt_tot"  />
+    	  <field field_ref="ibgheat_tot"      name="ibgheat_tot"  />
+    	  <field field_ref="sbgheat_tot"      name="sbgheat_tot"  />
+
+	  <!-- global drifts (conservation checks) -->
+	  <field field_ref="ibgvolume"        name="ibgvolume"    />
+    	  <field field_ref="ibgsaltco"        name="ibgsaltco"    />
+    	  <field field_ref="ibgheatco"        name="ibgheatco"    />
+          <field field_ref="ibgheatfx"        name="ibgheatfx"    />
+
+	  <!-- global forcings  -->
+    	  <field field_ref="ibgfrcvoltop"     name="ibgfrcvoltop" />
+    	  <field field_ref="ibgfrcvolbot"     name="ibgfrcvolbot" />
+    	  <field field_ref="ibgfrctemtop"     name="ibgfrctemtop" />
+    	  <field field_ref="ibgfrctembot"     name="ibgfrctembot" />
+    	  <field field_ref="ibgfrcsal"        name="ibgfrcsal"    />
+          <field field_ref="ibgfrchfxtop"     name="ibgfrchfxtop" />
+          <field field_ref="ibgfrchfxbot"     name="ibgfrchfxbot" />
+	</field_group>
+
+
+	<!--============================-->
+	<!-- SIMIP sea ice field groups -->
+	<!--     Notz et al 2016        -->
+	<!--============================-->
+
+	<!-- SIMIP monthly scalar variables -->
+	<field_group id="SImon_scalars"   grid_ref="grid_scalar" >
+          <!-- Integrated quantities -->
+          <field field_ref="NH_iceextt"       name="siextentn"    />
+          <field field_ref="SH_iceextt"       name="siextents"    />
+          <field field_ref="NH_icevolu"       name="sivoln"       />
+          <field field_ref="SH_icevolu"       name="sivols"       />
+          <field field_ref="NH_icearea"       name="siarean"      />
+          <field field_ref="SH_icearea"       name="siareas"      />
+	</field_group>
+
+	<!-- SIMIP daily fields -->
+	<field_group id="SIday_fields"    grid_ref="grid_T_2D" > 
+          <field field_ref="icepres"          name="sitimefrac"   /> 
+          <field field_ref="iceconc_pct"      name="siconc"       /> 
+          <field field_ref="icethic_cmip"     name="sithick"      /> 
+          <field field_ref="snwthic_cmip"     name="sisnthick"    />
+          <field field_ref="icettop_cmip"     name="sitemptop"    />
+          <field field_ref="uice_cmip"        name="siu"          />
+          <field field_ref="vice_cmip"        name="siv"          />
+          <field field_ref="icevel_cmip"      name="sispeed"      />
+	</field_group>
+
+	<!-- SIMIP monthly fields -->
+	<field_group id="SImon_fields"    grid_ref="grid_T_2D"  >
+          <!-- Sea-ice state variables -->
+          <field field_ref="icepres"          name="sitimefrac"   />
+          <field field_ref="iceconc_pct"      name="siconc"       />
+          <field field_ref="icemass_cmip"     name="simass"       />
+          <field field_ref="icethic_cmip"     name="sithick"      />
+          <field field_ref="icevolu"          name="sivol"        />
+          <field field_ref="snwmass_cmip"     name="sisnmass"     /> 
+          <field field_ref="snwthic_cmip"     name="sisnthick"    />
+	  
+          <!-- additional state variables-->
+          <field field_ref="icettop_cmip"     name="sitemptop"    />
+          <field field_ref="icetsni_cmip"     name="sitempsnic"   />
+          <field field_ref="icetbot_cmip"     name="sitempbot"    />
+          <field field_ref="iceage_cmip"      name="siage"        />
+          <field field_ref="icesalm"          name="sisaltmass"   />
+          <field field_ref="icesalt_cmip"     name="sisali"       />
+          <field field_ref="icefrb_cmip"      name="sifb"         />
+          <field field_ref="icehc_cmip"       name="sihc"         />
+          <field field_ref="snwhc_cmip"       name="sisnhc"       />
+
+          <!-- freshwater fluxes -->
+          <field field_ref="vfxice_cmip"      name="siflfwbot"    />
+          <field field_ref="vfxsum_cmip"      name="siflfwdrain"  />
+
+          <!-- area balance -->
+          <field field_ref="afxthd"           name="sidconcth"    />
+          <field field_ref="afxdyn"           name="sidconcdyn"   />
+
+          <!-- mass balance -->
+          <field field_ref="dmithd"           name="sidmassth"        />
+          <field field_ref="dmidyn"           name="sidmassdyn"       />
+          <field field_ref="dmiopw"           name="sidmassgrowthwat" />
+          <field field_ref="dmibog"           name="sidmassgrowthbot" />
+          <field field_ref="dmisni"           name="sidmasssi"        />
+          <field field_ref="dmisub"           name="sidmassevapsubl"  />
+          <field field_ref="dmisum"           name="sidmassmelttop"   />
+          <field field_ref="dmibom"           name="sidmassmeltbot"   />
+          <field field_ref="dmilam"           name="sidmassmeltlat"   />
+          <field field_ref="dmsspr"           name="sndmasssnf"       />
+          <field field_ref="dmsmel"           name="sndmassmelt"      />
+          <field field_ref="dmssub"           name="sndmasssubl"      />
+          <field field_ref="dmsdyn"           name="sndmassdyn"       />
+          <field field_ref="dmsssi"           name="sndmasssi"        />
+
+          <!-- heat balance -->
+          <field field_ref="hfxsensib"        name="siflsensupbot"    />
+          <field field_ref="hfxcndtop"        name="siflcondtop"      />
+          <field field_ref="hfxcndbot"        name="siflcondbot"      />
+
+          <!-- salt balance -->
+          <field field_ref="sfxice_cmip"      name="siflsaltbot"      />
+
+          <!-- sea-ice dynamics -->
+          <field field_ref="uice_cmip"        name="siu"              />
+          <field field_ref="vice_cmip"        name="siv"              />
+          <field field_ref="icevel_cmip"      name="sispeed"          />
+          <field field_ref="utau_ai_cmip"     name="sistrxdtop"       />
+          <field field_ref="vtau_ai_cmip"     name="sistrydtop"       />
+          <field field_ref="utau_oi"          name="sistrxubot"       />
+          <field field_ref="vtau_oi"          name="sistryubot"       />
+          <field field_ref="icestr"           name="sicompstren"      />
+          <field field_ref="dssh_dx"          name="siforcetiltx"     />
+          <field field_ref="dssh_dy"          name="siforcetilty"     />
+          <field field_ref="corstrx"          name="siforcecoriolx"   />
+          <field field_ref="corstry"          name="siforcecorioly"   />
+          <field field_ref="intstrx"          name="siforceintstrx"   />
+          <field field_ref="intstry"          name="siforceintstry"   />
+          <field field_ref="xmtrptot"         name="sidmasstranx"     />
+          <field field_ref="ymtrptot"         name="sidmasstrany"     />
+          <field field_ref="normstr"          name="sistresave"       operation="instant" />
+          <field field_ref="sheastr"          name="sistremax"        operation="instant" />
+          <field field_ref="icediv"           name="sidivvel"         operation="instant" />
+          <field field_ref="iceshe"           name="sishevel"         operation="instant" />
+
+          <!-- sea ice fluxes across straits: 2D arrays to be post-processed  -->
+          <field field_ref="xmtrpice"         name="simassacrossline_x" />
+          <field field_ref="ymtrpice"         name="simassacrossline_y" />
+          <field field_ref="xmtrpsnw"         name="snmassacrossline_x" />
+          <field field_ref="ymtrpsnw"         name="snmassacrossline_y" />
+          <field field_ref="xatrp"            name="siareaacrossline_x" />
+          <field field_ref="yatrp"            name="siareaacrossline_y" />
+
+          <!-- category-dependent fields -->
+          <field field_ref="iceconc_cat_pct_cmip" name="siitdconc"    />
+          <field field_ref="icethic_cat_cmip"     name="siitdthick"   />
+          <field field_ref="snwthic_cat_cmip"     name="siitdsnthick" />
+	</field_group>
+
+      </field_group> <!-- SBC -->
+      
+    </field_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-innerttrc.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-innerttrc.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-innerttrc.xml	(revision 14097)
@@ -0,0 +1,59 @@
+<?xml version="1.0"?> 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                     Inert tracers variables
+============================================================================================================
+    -->
+
+
+     <field_group id="inerttrc" grid_ref="grid_T_2D">
+
+       <!-- CFC11 : variables available with ln_cfc11 -->
+       <field id="CFC11"        long_name="Chlorofluoro carbon11 Concentration"      unit="umol/m3"   grid_ref="grid_T_3D" />
+       <field id="CFC11_e3t"    long_name="CFC11 * e3t"                              unit="umol/m2"   grid_ref="grid_T_3D"  > CFC11 * e3t </field >
+       <field id="qtr_CFC11"    long_name="Air-sea flux of CFC-11"                   unit="mol/m2/s"   />
+       <field id="qint_CFC11"   long_name="Cumulative air-sea flux of CFC-11"        unit="mol/m2"     />
+
+       <!-- CFC12 : variables available with ln_cfc12 -->
+       <field id="CFC12"        long_name="Chlorofluoro carbon12 Concentration"      unit="umol/m3"   grid_ref="grid_T_3D" />
+       <field id="CFC12_e3t"    long_name="CFC12 * e3t"                              unit="umol/m2"   grid_ref="grid_T_3D"  > CFC12 * e3t </field >
+       <field id="qtr_CFC12"    long_name="Air-sea flux of CFC12"                    unit="mol/m2/s"   />
+       <field id="qint_CFC12"   long_name="Cumulative air-sea flux of CFC12"         unit="mol/m2"     />
+
+       <!-- SF6 : variables available with ln_sf6 -->
+       <field id="SF6"          long_name="Sulfur hexafluoride Concentration"        unit="umol/m3"   grid_ref="grid_T_3D" />
+       <field id="SF6_e3t"      long_name="SF6 * e3t"                                unit="umol/m2"   grid_ref="grid_T_3D"  > SF6 * e3t </field >
+       <field id="qtr_SF6"      long_name="Air-sea flux of SF6"                      unit="mol/m2/s"   />
+       <field id="qint_SF6"     long_name="Cumulative air-sea flux of SF6"           unit="mol/m2"     />
+
+       <!-- C14 : variables available with ln_c14 -->
+       <field id="RC14"         long_name="Radiocarbon ratio"                        unit="-"         grid_ref="grid_T_3D"  />
+       <field id="RC14_e3t"     long_name="RC14 * e3t"                               unit="m"         grid_ref="grid_T_3D"   > RC14 * e3t </field >
+       <field id="DeltaC14"     long_name="Delta C14"                                unit="permil"    grid_ref="grid_T_3D"  />
+       <field id="C14Age"       long_name="Radiocarbon age"                          unit="yr"        grid_ref="grid_T_3D"  />
+       <field id="RAge"         long_name="Reservoir Age"                            unit="yr"       />
+       <field id="qtr_C14"      long_name="Air-sea flux of C14"                      unit="1/m2/s"   />
+       <field id="qint_C14"     long_name="Cumulative air-sea flux of C14"           unit="1/m2"     />
+       <field id="AtmCO2"       long_name="Global atmospheric CO2"                   unit="ppm"      />
+       <field id="AtmC14"       long_name="Global atmospheric DeltaC14"              unit="permil"   />
+       <field id="K_C14"        long_name="Global 14C/C exchange velocity"           unit="m/yr"     />
+       <field id="K_CO2"        long_name="Global CO2 piston velocity"               unit="cm/h"     />
+       <field id="C14Inv"       long_name="global Radiocarbon ocean inventory"       unit="10^26 atoms"   />
+
+       <!-- AGE : variables available with ln_age -->
+       <field id="Age"          long_name="Sea water age since surface contact"      unit="yr"        grid_ref="grid_T_3D"  />
+       <field id="Age_e3t"      long_name="Age * e3t"                                unit="yr * m"   grid_ref="grid_T_3D"    > Age * e3t </field >
+
+     </field_group>
+
+   </field_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1028 @@
+<?xml version="1.0"?> 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                  Physical ocean model variables
+============================================================================================================
+    -->
+
+      <!-- T grid -->
+      
+      <field_group id="grid_T" grid_ref="grid_T_2D" >
+        <field id="e3t"          long_name="T-cell thickness"                    standard_name="cell_thickness"        unit="m"   grid_ref="grid_T_3D" />
+        <field id="e3ts"         long_name="T-cell thickness"   field_ref="e3t"  standard_name="cell_thickness"        unit="m"   grid_ref="grid_T_SFC"/>
+        <field id="e3t_0"        long_name="Initial T-cell thickness"            standard_name="ref_cell_thickness"    unit="m"   grid_ref="grid_T_3D" />
+        <field id="e3tb"         long_name="bottom T-cell thickness"             standard_name="bottom_cell_thickness" unit="m"   grid_ref="grid_T_2D"/> 
+        <field id="e3t_300"      field_ref="e3t"                grid_ref="grid_T_zoom_300"       detect_missing_value="true" />
+        <field id="e3t_vsum300"  field_ref="e3t_300"            grid_ref="grid_T_vsum"   detect_missing_value="true" />
+	<field id="masscello"    long_name="Sea Water Mass per unit area"   standard_name="sea_water_mass_per_unit_area"   unit="kg/m2"   grid_ref="grid_T_3D"/>
+        <field id="volcello"     long_name="Ocean Volume"                   standard_name="ocean_volume"   unit="m3"       grid_ref="grid_T_3D"/> 
+        <field id="toce"         long_name="temperature"                         standard_name="sea_water_potential_temperature"   unit="degC"     grid_ref="grid_T_3D"/>
+        <field id="toce_e3t"     long_name="temperature (thickness weighted)"                                                      unit="degC"     grid_ref="grid_T_3D" > toce * e3t </field >
+        <field id="soce"         long_name="salinity"                            standard_name="sea_water_practical_salinity"      unit="1e-3"     grid_ref="grid_T_3D"/>
+        <field id="soce_e3t"     long_name="salinity    (thickness weighted)"                                                      unit="1e-3"     grid_ref="grid_T_3D" > soce * e3t </field >
+
+        <field id="toce_e3t_300"      field_ref="toce_e3t"          unit="degree_C"     grid_ref="grid_T_zoom_300"      detect_missing_value="true" />
+        <field id="toce_e3t_vsum300"  field_ref="toce_e3t_300"      unit="degress_C*m"  grid_ref="grid_T_vsum"  detect_missing_value="true" />
+        <field id="toce_vmean300"     field_ref="toce_e3t_vsum300"  unit="degree_C"     grid_ref="grid_T_vsum"  detect_missing_value="true" > toce_e3t_vsum300/e3t_vsum300 </field>
+
+	<!-- additions to diawri.F90 -->
+        <field id="socegrad"    long_name="module of salinity gradient"              unit="psu/m"   grid_ref="grid_T_3D"/>
+        <field id="socegrad2"   long_name="square of module of salinity gradient"    unit="psu2/m2" grid_ref="grid_T_3D"/>
+        <field id="eken_int"    long_name="vertical integration of kinetic energy"   unit="m3/s2"   />
+        <field id="relvor"      long_name="relative vorticity"                       unit="s-1"    grid_ref="grid_T_3D"/>
+        <field id="absvor"      long_name="absolute vorticity"                       unit="s-1"    grid_ref="grid_T_3D"/>
+        <field id="potvor"      long_name="potential vorticity"                      unit="s-1"    grid_ref="grid_T_3D"/>
+        <field id="salt2c"      long_name="Salt content vertically integrated"       unit="1e-3*kg/m2" />
+
+        <!-- t-eddy viscosity coefficients (ldfdyn) -->
+	<field id="ahmt_2d"      long_name=" surface t-eddy viscosity coefficient"   unit="m2/s or m4/s"                      />
+	<field id="ahmt_3d"      long_name=" 3D      t-eddy viscosity coefficient"   unit="m2/s or m4/s"  grid_ref="grid_T_3D"/>
+
+        <field id="sst"          long_name="sea surface temperature"                            standard_name="sea_surface_temperature"             unit="degC"     />
+        <field id="sst2"         long_name="square of sea surface temperature"                  standard_name="square_of_sea_surface_temperature"   unit="degC2"     > sst * sst </field >
+        <field id="sstmax"       long_name="max of sea surface temperature"   field_ref="sst"   operation="maximum"                                                 />
+        <field id="sstmin"       long_name="min of sea surface temperature"   field_ref="sst"   operation="minimum"                                                 />
+        <field id="sstgrad"      long_name="module of sst gradient"                                                                                 unit="degC/m"   />
+        <field id="sstgrad2"     long_name="square of module of sst gradient"                                                                       unit="degC2/m2" />
+        <field id="sbt"          long_name="sea bottom temperature"                                                                                 unit="degC"     />
+        <field id="tosmint"      long_name="vertical integral of temperature times density"     standard_name="integral_wrt_depth_of_product_of_density_and_potential_temperature"  unit="(kg m2) degree_C" />
+        <field id="sst_wl"       long_name="Delta SST of warm layer"                                                                                unit="degC"     />
+        <field id="sst_cs"       long_name="Delta SST of cool skin"                                                                                 unit="degC"     />
+	<field id="temp_3m"      long_name="temperature at 3m"                                                                                      unit="degC"     />
+        
+        <field id="sss"          long_name="sea surface salinity"                               standard_name="sea_surface_salinity"                unit="1e-3"     />
+        <field id="sss2"         long_name="square of sea surface salinity"                                                                         unit="1e-6"      > sss * sss </field >
+        <field id="sssmax"       long_name="max of sea surface salinity"      field_ref="sss"   operation="maximum"                                                 />
+        <field id="sssmin"       long_name="min of sea surface salinity"      field_ref="sss"   operation="minimum"                                                 />
+        <field id="sbs"          long_name="sea bottom salinity"                                                                                    unit="0.001"    />
+        <field id="somint"       long_name="vertical integral of salinity times density"        standard_name="integral_wrt_depth_of_product_of_density_and_salinity"  unit="(kg m2) x (1e-3)" /> 
+
+        <field id="taubot"       long_name="bottom stress module"                                                                                   unit="N/m2"     /> 
+
+         <!-- Case EOS = TEOS-10 : output potential temperature -->
+	<field id="toce_pot"     long_name="Sea Water Potential Temperature"              standard_name="sea_water_potential_temperature"   unit="degC"     grid_ref="grid_T_3D"/>
+        <field id="sst_pot"      long_name="potential sea surface temperature"             standard_name="sea_surface_temperature"             unit="degC"     />
+        <field id="tosmint_pot"  long_name="vertical integral of potential temperature times density"   standard_name="integral_wrt_depth_of_product_of_density_and_potential_temperature"  unit="(kg m2) degree_C" />
+
+
+        <field id="ssh"          long_name="sea surface height"                                 standard_name="sea_surface_height_above_geoid"             unit="m" />
+        <field id="ssh2"         long_name="square of sea surface height"                       standard_name="square_of_sea_surface_height_above_geoid"   unit="m2" > ssh * ssh </field >
+        <field id="wetdep"       long_name="wet depth"                                          standard_name="wet_depth"                                  unit="m" />
+        <field id="sshmax"       long_name="max of sea surface height"        field_ref="ssh"   operation="maximum"                                                 />
+
+        <field id="mldkz5"       long_name="Turbocline depth (Kz = 5e-4)"                       standard_name="ocean_mixed_layer_thickness_defined_by_vertical_tracer_diffusivity"                unit="m"          />
+        <field id="mldr10_1"     long_name="Mixed Layer Depth (dsigma = 0.01 wrt 10m)"          standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"          />
+        <field id="mldr10_1max"  long_name="Max of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="maximum"                                                                          />
+        <field id="mldr10_1min"  long_name="Min of Mixed Layer Depth (dsigma = 0.01 wrt 10m)"   field_ref="mldr10_1"   operation="minimum"                                                                          />
+        <field id="heatc"        long_name="Heat content vertically integrated"                 standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"       />
+        <field id="saltc"        long_name="Salt content vertically integrated"                                                                                                                   unit="1e-3*kg/m2" />
+
+        <!-- EOS -->
+        <field id="alpha"        long_name="thermal expansion"                                                         unit="degC-1" grid_ref="grid_T_3D" />
+        <field id="beta"         long_name="haline contraction"                                                        unit="1e3"    grid_ref="grid_T_3D" />
+        <field id="rhop"         long_name="potential density (sigma0)"        standard_name="sea_water_sigma_theta"   unit="kg/m3"  grid_ref="grid_T_3D" />
+
+        <!-- Energy - horizontal divergence -->
+        <field id="eken"         long_name="kinetic energy"          standard_name="specific_kinetic_energy_of_sea_water"   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" />
+
+        <!-- next variables available with ln_zad_Aimp=.true. -->
+        <field id="Courant"      long_name="Courant number"                                                                 unit="#"   grid_ref="grid_T_3D" />
+        <field id="wimp"         long_name="Implicit vertical velocity"                                                     unit="m/s" grid_ref="grid_T_3D" />
+        <field id="wexp"         long_name="Explicit vertical velocity"                                                     unit="m/s" grid_ref="grid_T_3D" />
+        <field id="wi_cff"       long_name="Fraction of implicit vertical velocity"                                         unit="#"   grid_ref="grid_T_3D" />
+
+        <!-- next variables available with key_diahth -->
+        <field id="mlddzt"       long_name="Thermocline Depth (depth of max dT/dz)"         standard_name="depth_at_maximum_upward_derivative_of_sea_water_potential_temperature"             unit="m"                         />
+        <field id="mldr10_3"     long_name="Mixed Layer Depth (dsigma = 0.03 wrt 10m)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"                         />
+        <field id="mldr0_1"      long_name="Mixed Layer Depth (dsigma = 0.01 wrt sfc)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"                         />
+        <field id="mldr0_3"      long_name="Mixed Layer Depth (dsigma = 0.03 wrt sfc)"      standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"                         />
+        <field id="mld_dt02"     long_name="Mixed Layer Depth (|dT| = 0.2 wrt 10m)"         standard_name="ocean_mixed_layer_thickness_defined_by_temperature"                                unit="m"                         />
+        <field id="topthdep"     long_name="Top of Thermocline Depth (dT = -0.2 wrt 10m)"   standard_name="ocean_mixed_layer_thickness_defined_by_temperature"                                unit="m"                         />
+        <field id="pycndep"      long_name="Pycnocline Depth (dsigma[dT=-0.2] wrt 10m)"     standard_name="ocean_mixed_layer_thickness_defined_by_sigma_theta"                                unit="m"                         />
+        <field id="BLT"          long_name="Barrier Layer Thickness"                                                                                                                          unit="m"   > topthdep - pycndep </field>
+        <field id="tinv"         long_name="Max of vertical invertion of temperature"                                                                                                         unit="degC"                      />
+        <field id="depti"        long_name="Depth of max. vert. inv. of temperature"                                                                                                          unit="m"                         />
+	<field id="20d"          long_name="Depth of 20C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"   axis_ref="iax_20C" />
+        <field id="26d"          long_name="Depth of 26C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"   axis_ref="iax_26C"   />
+        <field id="28d"          long_name="Depth of 28C isotherm"                          standard_name="depth_of_isosurface_of_sea_water_potential_temperature"                            unit="m"   axis_ref="iax_28C" />
+        <field id="hc300"        long_name="Heat content 0-300m"                            standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"                      />
+        <field id="hc700"        long_name="Heat content 0-700m"                            standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"                      />
+        <field id="hc2000"       long_name="Heat content 0-2000m"                           standard_name="integral_of_sea_water_potential_temperature_wrt_depth_expressed_as_heat_content"   unit="J/m2"                      />
+
+        <!-- variables available with diaar5 -->
+        <field id="botpres"      long_name="Sea Water Pressure at Sea Floor"          standard_name="sea_water_pressure_at_sea_floor"                    unit="dbar" />
+        <field id="sshdyn"       long_name="dynamic sea surface height"               standard_name="dynamic_sea_surface_height_above_geoid"             unit="m"    />
+        <field id="sshdyn2"      long_name="square of dynamic sea surface height"     standard_name="dynamic_sea_surface_height_above_geoid_squared"     unit="m2"    > sshdyn * sshdyn </field>
+        <field id="tnpeo"      long_name="Tendency of ocean potential energy content"                                                                    unit="W/m2" />
+
+        <!-- variables available ln_linssh=.FALSE. -->
+        <field id="tpt_dep"      long_name="T-point depth"                  standard_name="depth_below_geoid"   unit="m"   grid_ref="grid_T_3D" />
+        <field id="e3tdef"       long_name="T-cell thickness deformation"                                       unit="%"   grid_ref="grid_T_3D" />
+
+        <!-- variables available with ln_diacfl=.true. -->
+        <field id="cfl_cu"       long_name="u-courant number"   unit="#" />
+        <field id="cfl_cv"       long_name="v-courant number"   unit="#" />
+        <field id="cfl_cw"       long_name="w-courant number"   unit="#" />
+
+      </field_group> <!-- grid_T -->
+
+      <!-- Tides -->
+
+      <field_group id="Tides_T" grid_ref="grid_T_2D" operation="once" >
+        <!-- tidal composante -->
+        <field id="M2x"          long_name="M2 Elevation harmonic real part "                             unit="m"        />
+        <field id="M2y"          long_name="M2 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="S2x"          long_name="S2 Elevation harmonic real part "                             unit="m"        />
+        <field id="S2y"          long_name="S2 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="N2x"          long_name="N2 Elevation harmonic real part "                             unit="m"        />
+        <field id="N2y"          long_name="N2 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="K1x"          long_name="K1 Elevation harmonic real part "                             unit="m"        />
+        <field id="K1y"          long_name="K1 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="O1x"          long_name="O1 Elevation harmonic real part "                             unit="m"        />
+        <field id="O1y"          long_name="O1 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="Q1x"          long_name="Q1 Elevation harmonic real part "                             unit="m"        />
+        <field id="Q1y"          long_name="Q1 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="M4x"          long_name="M4 Elevation harmonic real part "                             unit="m"        />
+        <field id="M4y"          long_name="M4 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="K2x"          long_name="K2 Elevation harmonic real part "                             unit="m"        />
+        <field id="K2y"          long_name="K2 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="P1x"          long_name="P1 Elevation harmonic real part "                             unit="m"        />
+        <field id="P1y"          long_name="P1 Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="Mfx"          long_name="Mf Elevation harmonic real part "                             unit="m"        />
+        <field id="Mfy"          long_name="Mf Elevation harmonic imaginary part"                         unit="m"        />
+        <field id="Mmx"          long_name="Mm Elevation harmonic real part "                             unit="m"        />
+        <field id="Mmy"          long_name="Mm Elevation harmonic imaginary part"                         unit="m"        />
+      </field_group>
+	 
+      <field_group id="Tides_U" grid_ref="grid_U_2D" operation="once" >
+        <field id="M2x_u"        long_name="M2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="M2y_u"        long_name="M2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="S2x_u"        long_name="S2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="S2y_u"        long_name="S2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="N2x_u"        long_name="N2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="N2y_u"        long_name="N2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="K1x_u"        long_name="K1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="K1y_u"        long_name="K1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="O1x_u"        long_name="O1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="O1y_u"        long_name="O1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Q1x_u"        long_name="Q1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="Q1y_u"        long_name="Q1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="M4x_u"        long_name="M4 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="M4y_u"        long_name="M4 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="K2x_u"        long_name="K2 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="K2y_u"        long_name="K2 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="P1x_u"        long_name="P1 current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="P1y_u"        long_name="P1 current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Mfx_u"        long_name="Mf current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="Mfy_u"        long_name="Mf current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Mmx_u"        long_name="Mm current barotrope along i-axis harmonic real part "        unit="m/s"      />
+        <field id="Mmy_u"        long_name="Mm current barotrope along i-axis harmonic imaginary part "   unit="m/s"      />
+      </field_group>
+	 
+      <field_group id="Tides_V" grid_ref="grid_V_2D" operation="once" >
+        <field id="M2x_v"        long_name="M2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="M2y_v"        long_name="M2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="S2x_v"        long_name="S2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="S2y_v"        long_name="S2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="N2x_v"        long_name="N2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="N2y_v"        long_name="N2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="K1x_v"        long_name="K1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="K1y_v"        long_name="K1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="O1x_v"        long_name="O1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="O1y_v"        long_name="O1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Q1x_v"        long_name="Q1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="Q1y_v"        long_name="Q1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="M4x_v"        long_name="M4 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="M4y_v"        long_name="M4 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="K2x_v"        long_name="K2 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="K2y_v"        long_name="K2 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="P1x_v"        long_name="P1 current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="P1y_v"        long_name="P1 current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Mfx_v"        long_name="Mf current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="Mfy_v"        long_name="Mf current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />
+        <field id="Mmx_v"        long_name="Mm current barotrope along j-axis harmonic real part "        unit="m/s"      />
+        <field id="Mmy_v"        long_name="Mm current barotrope along j-axis harmonic imaginary part "   unit="m/s"      />	 
+      </field_group>
+
+      <!-- OSMOSIS variables (available with ln_zdfosm=.true.) -->
+
+      <field_group id="OSMOSIS_T" grid_ref="grid_T_2D">
+        <field id="zwth0"               long_name="surface non-local temperature flux"       unit="deg m/s" />
+        <field id="zws0"                long_name="surface non-local salinity flux"          unit="psu m/s" />
+        <field id="hbl"                 long_name="boundary layer depth"                     unit="m"       />
+        <field id="hbli"                long_name="initial boundary layer depth"             unit="m"       />
+        <field id="dstokes"             long_name="stokes drift  depth scale"                unit="m"       />
+        <field id="zustke"              long_name="magnitude of stokes drift  at T-points"   unit="m/s"     />
+        <field id="zwstrc"              long_name="convective velocity scale"                unit="m/s"     />
+        <field id="zwstrl"              long_name="langmuir velocity scale"                  unit="m/s"     />
+        <field id="zustar"              long_name="friction velocity"                        unit="m/s"     />
+        <field id="zhbl"                long_name="boundary layer depth"                     unit="m"       />
+        <field id="zhml"                long_name="mixed layer depth"                        unit="m"       />
+        <field id="wind_wave_abs_power" long_name="\rho |U_s| x u*^2"                        unit="mW"      />
+        <field id="wind_wave_power"     long_name="U_s \dot  tau"                            unit="mW"      />
+        <field id="wind_power"          long_name="\rho  u*^3"                               unit="mW"      />
+
+        <!-- extra OSMOSIS diagnostics -->
+        <field id="zwthav"              long_name="av turb flux of T in ml"                  unit="deg m/s" />
+        <field id="zt_ml"               long_name="av T in ml"                               unit="deg"     />
+        <field id="zwth_ent"            long_name="entrainment turb flux of T"               unit="deg m/s" />
+        <field id="zhol"                long_name="Hoenekker number"                         unit="#"       />
+        <field id="zdh"                 long_name="Pycnocline  depth - grid"                 unit=" m"      />
+      </field_group>
+
+      <field_group id="OSMOSIS_W" grid_ref="grid_W_3D" operation="instant" >
+        <field id="ghamt"       long_name="non-local temperature flux"                       unit="deg m/s" />
+        <field id="ghams"       long_name="non-local salinity flux"                          unit="psu m/s" />
+        <field id="zdtdz_pyc"   long_name="Pycnocline temperature gradient"                  unit=" deg/m"  />
+      </field_group>
+
+      <field_group id="OSMOSIS_U" grid_ref="grid_U_2D" >
+        <field id="ghamu"       long_name="non-local u-momentum flux"   grid_ref="grid_U_3D" unit="m^2/s^2" />
+        <field id="us_x"        long_name="i component of Stokes drift"                      unit="m/s"     />
+      </field_group>
+
+      <field_group id="OSMOSIS_V" grid_ref="grid_V_2D" >
+        <field id="ghamv"       long_name="non-local v-momentum flux"   grid_ref="grid_V_3D" unit="m^2/s^2" />
+        <field id="us_y"        long_name="j component of Stokes drift"                      unit="m/s"     />
+      </field_group>
+      
+      <!-- SBC -->
+      <field_group id="SBC" > <!-- time step automaticaly defined based on nn_fsbc -->
+
+        <field_group id="SBC_2D" grid_ref="grid_T_2D" >
+
+          <field id="empmr"        long_name="Net Upward Water Flux"                standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
+          <field id="empbmr"       long_name="Net Upward Water Flux at pre. tstep"  standard_name="water_flux_out_of_sea_ice_and_sea_water"                              unit="kg/m2/s"   />
+          <field id="emp_oce"      long_name="Evap minus Precip over ocean"         standard_name="evap_minus_precip_over_sea_water"                                     unit="kg/m2/s"   />
+          <field id="emp_ice"      long_name="Evap minus Precip over ice"           standard_name="evap_minus_precip_over_sea_ice"                                       unit="kg/m2/s"   />
+          <field id="saltflx"      long_name="Downward salt flux"                                                                                                        unit="1e-3/m2/s" />
+          <field id="fmmflx"       long_name="Water flux due to freezing/melting"                                                                                        unit="kg/m2/s"   />
+          <field id="snowpre"      long_name="Snow precipitation"                   standard_name="snowfall_flux"                                                        unit="kg/m2/s"   />
+          <field id="runoffs"      long_name="River Runoffs"                        standard_name="water_flux_into_sea_water_from_rivers"                                unit="kg/m2/s"   />
+          <field id="precip"       long_name="Total precipitation"                  standard_name="precipitation_flux"                                                   unit="kg/m2/s"   />
+	  
+          <field id="qt"           long_name="Net Downward Heat Flux"                standard_name="surface_downward_heat_flux_in_sea_water"                              unit="W/m2"                           />
+          <field id="qns"          long_name="non solar Downward Heat Flux"                                                                                               unit="W/m2"                           />
+          <field id="qsr"          long_name="Shortwave Radiation"                   standard_name="net_downward_shortwave_flux_at_sea_water_surface"                     unit="W/m2"                           />
+          <field id="qsr3d"        long_name="Shortwave Radiation 3D distribution"   standard_name="downwelling_shortwave_flux_in_sea_water"                              unit="W/m2"      grid_ref="grid_T_3D" />
+          <field id="qrp"          long_name="Surface Heat Flux: Damping"            standard_name="heat_flux_into_sea_water_due_to_newtonian_relaxation"                 unit="W/m2"                           />
+          <field id="erp"          long_name="Surface Water Flux: Damping"           standard_name="water_flux_out_of_sea_water_due_to_newtonian_relaxation"              unit="kg/m2/s"                        />
+          <field id="taum"         long_name="wind stress module"                    standard_name="magnitude_of_surface_downward_stress"                                 unit="N/m2"                           />
+          <field id="wspd"         long_name="wind speed module"                     standard_name="wind_speed"                                                           unit="m/s"                            />
+          
+          <!-- * variable relative to atmospheric pressure forcing : available with ln_apr_dyn -->
+          <field id="ssh_ib"       long_name="Inverse barometer sea surface height"  standard_name="sea_surface_height_correction_due_to_air_pressure_at_low_frequency"   unit="m"        />
+
+          <!-- * variable related to ice shelf forcing * -->
+          <field id="fwfisf"       long_name="Ice shelf melting"                             unit="kg/m2/s"  />
+          <field id="fwfisf3d"     long_name="Ice shelf melting"                             unit="kg/m2/s"  grid_ref="grid_T_3D" />
+          <field id="qlatisf"      long_name="Ice shelf latent heat flux"                    unit="W/m2"     />
+          <field id="qlatisf3d"    long_name="Ice shelf latent heat flux"                    unit="W/m2"     grid_ref="grid_T_3D" />
+          <field id="qhcisf"       long_name="Ice shelf heat content flux"                   unit="W/m2"     />
+          <field id="qhcisf3d"     long_name="Ice shelf heat content flux"                   unit="W/m2"     grid_ref="grid_T_3D" />
+          <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"        />
+          <field id="utbl"         long_name="zonal current in the Losh tbl at T point    "  unit="m/s"      />
+          <field id="vtbl"         long_name="merid current in the Losh tbl at T point    "  unit="m/s"      />
+          <field id="thermald"     long_name="thermal driving of ice shelf melting        "  unit="C"        />
+          <field id="tfrz"         long_name="top freezing point (used to compute melt)   "  unit="C"        />
+          <field id="tinsitu"      long_name="top insitu temperature (used to cmpt melt)  "  unit="C"        />
+          <field id="ustar"        long_name="ustar at T point used in ice shelf melting  "  unit="m/s"      />
+
+          <!-- *_oce variables available with ln_blk_clio or ln_blk_core -->
+          <field id="qlw_oce"      long_name="Longwave Downward Heat Flux over open ocean"  standard_name="surface_net_downward_longwave_flux"                 unit="W/m2"  />
+          <field id="qsb_oce"      long_name="Sensible Downward Heat Flux over open ocean"  standard_name="surface_downward_sensible_heat_flux"                unit="W/m2"  />
+          <field id="qla_oce"      long_name="Latent Downward Heat Flux over open ocean"    standard_name="surface_downward_latent_heat_flux"                  unit="W/m2"  />
+          <field id="qt_oce"       long_name="total flux at ocean surface"                  standard_name="surface_downward_heat_flux_in_sea_water"            unit="W/m2"  />
+          <field id="qsr_oce"      long_name="solar heat flux at ocean surface"             standard_name="net_downward_shortwave_flux_at_sea_water_surface"   unit="W/m2"  />
+          <field id="qns_oce"      long_name="non-solar heat flux at ocean surface (including E-P)"                                                            unit="W/m2"  />
+          <field id="qemp_oce"     long_name="Downward Heat Flux from E-P over open ocean"                                                                     unit="W/m2"  />
+          <field id="taum_oce"     long_name="wind stress module over open ocean"           standard_name="magnitude_of_surface_downward_stress"               unit="N/m2"  />
+
+          <!-- available key_oasis3 -->
+          <field id="snow_ao_cea"  long_name="Snow over ice-free ocean (cell average)"   standard_name="snowfall_flux"                             unit="kg/m2/s"  />
+          <field id="snow_ai_cea"  long_name="Snow over sea-ice (cell average)"          standard_name="snowfall_flux"                             unit="kg/m2/s"  />
+          <field id="subl_ai_cea"  long_name="Sublimation over sea-ice (cell average)"   standard_name="surface_snow_and_ice_sublimation_flux"     unit="kg/m2/s"  />
+          <field id="icealb_cea"   long_name="Ice albedo (cell average)"                 standard_name="sea_ice_albedo"                            unit="1"        />
+          <field id="calving_cea"  long_name="Calving"                                   standard_name="water_flux_into_sea_water_from_icebergs"   unit="kg/m2/s"  />
+          <field id="iceberg_cea"  long_name="Iceberg"                                   standard_name="water_flux_into_sea_water_from_icebergs"   unit="kg/m2/s"  />
+          <field id="iceshelf_cea" long_name="Iceshelf"                                  standard_name="water_flux_into_sea_water_from_iceshelf"   unit="kg/m2/s"  />
+
+
+          <!-- available if key_oasis3 + conservative method -->
+	  <field id="rain"          long_name="Liquid precipitation"                                     standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
+          <field id="rain_ao_cea"   long_name="Liquid precipitation over ice-free ocean (cell average)"  standard_name="rainfall_flux"                                                                 unit="kg/m2/s"  />
+          <field id="evap_ao_cea"   long_name="Evaporation over ice-free ocean (cell average)"           standard_name="water_evaporation_flux"                                                        unit="kg/m2/s"  />
+          <field id="isnwmlt_cea"   long_name="Snow over Ice melting (cell average)"                     standard_name="surface_snow_melt_flux"                                                        unit="kg/m2/s"  />
+          <field id="fsal_virt_cea" long_name="Virtual salt flux due to ice formation (cell average)"    standard_name="virtual_salt_flux_into_sea_water_due_to_sea_ice_thermodynamics"                unit="kg/m2/s"  />
+          <field id="fsal_real_cea" long_name="Real salt flux due to ice formation (cell average)"       standard_name="downward_sea_ice_basal_salt_flux"                                              unit="kg/m2/s"  />
+          <field id="hflx_rain_cea" long_name="heat flux due to rainfall"                                standard_name="temperature_flux_due_to_rainfall_expressed_as_heat_flux_into_sea_water"        unit="W/m2"     />
+          <field id="hflx_evap_cea" long_name="heat flux due to evaporation"                             standard_name="temperature_flux_due_to_evaporation_expressed_as_heat_flux_out_of_sea_water"   unit="W/m2"     />
+          <field id="hflx_prec_cea" long_name="heat flux due to all precip"                              standard_name="temperature_flux_due_to_all_precip_expressed_as_heat_flux_into_sea_water"      unit="W/m2"     />
+          <field id="hflx_snow_cea" long_name="heat flux due to snow falling"                            standard_name="heat_flux_onto_ocean_and_ice_due_to_snow_thermodynamics"                       unit="W/m2"     />
+          <field id="hflx_snow_ai_cea" long_name="heat flux due to snow falling over ice"                standard_name="heat_flux_onto_ice_due_to_snow_thermodynamics"                                 unit="W/m2"     />
+          <field id="hflx_snow_ao_cea" long_name="heat flux due to snow falling over ice-free ocean"     standard_name="heat_flux_onto_sea_water_due_to_snow_thermodynamics"                           unit="W/m2"     />
+          <field id="hflx_ice_cea"  long_name="heat flux due to ice thermodynamics"                      standard_name="heat_flux_into_sea_water_due_to_sea_ice_thermodynamics"                        unit="W/m2"     />
+          <field id="hflx_rnf_cea"  long_name="heat flux due to runoffs"                                 standard_name="temperature_flux_due_to_runoff_expressed_as_heat_flux_into_sea_water"          unit="W/m2"     />
+          <field id="hflx_cal_cea"  long_name="heat flux due to calving"                                 standard_name="heat_flux_into_sea_water_due_to_calving"                                       unit="W/m2"     />
+          <field id="hflx_icb_cea"  long_name="heat flux due to iceberg"                                 standard_name="heat_flux_into_sea_water_due_to_icebergs"                                      unit="W/m2"     />
+          <field id="hflx_isf_cea"  long_name="heat flux due to iceshelf"                                standard_name="heat_flux_into_sea_water_due_to_iceshelf"                                      unit="W/m2"     />
+          <field id="bicemel_cea"   long_name="Rate of Melt at Sea Ice Base (cell average)"              standard_name="tendency_of_sea_ice_amount_due_to_basal_melting"                               unit="kg/m2/s"  />
+          <field id="licepro_cea"   long_name="Lateral Sea Ice Growth Rate (cell average)"               standard_name="tendency_of_sea_ice_amount_due_to_lateral_growth_of_ice_floes"                 unit="kg/m2/s"  />
+          <field id="snowmel_cea"   long_name="Snow Melt Rate (cell average)"                            standard_name="surface_snow_melt_flux"                                                        unit="kg/m2/s"  />
+          <field id="sntoice_cea"   long_name="Snow-Ice Formation Rate (cell average)"                   standard_name="tendency_of_sea_ice_amount_due_to_snow_conversion"                             unit="kg/m2/s"  />
+          <field id="ticemel_cea"   long_name="Rate of Melt at Upper Surface of Sea Ice (cell average)"  standard_name="tendency_of_sea_ice_amount_due_to_surface_melting"                             unit="kg/m2/s"  />
+
+          <!-- ice field (nn_ice=1)  -->
+          <field id="ice_cover"    long_name="Ice fraction"                                                 standard_name="sea_ice_area_fraction"                              unit="1"            />
+          
+          <!-- dilution -->
+          <field id="emp_x_sst"    long_name="Concentration/Dilution term on SST"                                                                                              unit="kg*degC/m2/s" />
+          <field id="emp_x_sss"    long_name="Concentration/Dilution term on SSS"                                                                                              unit="kg*1e-3/m2/s" />        
+          <field id="rnf_x_sst"    long_name="Runoff term on SST"                                                                                                              unit="kg*degC/m2/s" />
+          <field id="rnf_x_sss"    long_name="Runoff term on SSS"                                                                                                              unit="kg*1e-3/m2/s" />
+	  
+	  <!-- sbcssm variables -->
+          <field id="sst_m"    unit="degC" />
+          <field id="sss_m"    unit="psu"  />
+          <field id="ssu_m"    unit="m/s"  />
+          <field id="ssv_m"    unit="m/s"  />
+          <field id="ssh_m"    unit="m"    />
+          <field id="e3t_m"    unit="m"    />
+          <field id="frq_m"    unit="-"    />
+
+	</field_group>
+	
+	<!-- scalar variables -->
+	<field_group id="SBC_0D"  grid_ref="grid_1point" >
+	</field_group>
+
+      </field_group> <!-- SBC -->
+
+      <!-- U grid -->
+      
+      <field_group id="grid_U"   grid_ref="grid_U_2D">
+        <field id="e2u"           long_name="U-cell width in meridional direction"                   standard_name="cell_width"                  unit="m"                               />
+        <field id="e3u"           long_name="U-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_U_3D" />
+        <field id="e3u_0"         long_name="Initial U-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_U_3D"/>
+        <field id="utau"          long_name="Wind Stress along i-axis"                               standard_name="surface_downward_x_stress"   unit="N/m2"                            />
+        <field id="uoce"          long_name="ocean current along i-axis"                             standard_name="sea_water_x_velocity"        unit="m/s"        grid_ref="grid_U_3D" />
+    	<field id="uoce_e3u"      long_name="ocean current along i-axis  (thickness weighted)"                                                   unit="m/s"        grid_ref="grid_U_3D"  > uoce * e3u </field>
+    	<field id="uoce_e3u_vsum" long_name="ocean current along i-axis * e3u summed on the vertical"  field_ref="uoce_e3u"    unit="m3/s"       grid_ref="grid_U_vsum"/>
+        <field id="uocetr_vsum"   long_name="ocean transport along i-axis  summed on the vertical"         field_ref="e2u"       unit="m3/s"> this * uoce_e3u_vsum  </field> 
+
+        <field id="uocetr_vsum_op"    long_name="ocean current along i-axis * e3u * e2u summed on the vertical"  read_access="true"  freq_op="1mo"    field_ref="e2u"       unit="m3/s"> @uocetr_vsum </field>
+        <field id="uocetr_vsum_cumul" long_name="ocean current along i-axis * e3u * e2u cumulated from southwest point" freq_offset="_reset_" operation="instant" freq_op="1mo"  unit="m3/s" /> 
+        <field id="msftbarot"         long_name="ocean_barotropic_mass_streamfunction"   unit="kg s-1" > uocetr_vsum_cumul * $rau0 </field>
+
+
+        <field id="ssu"          long_name="ocean surface current along i-axis"                                                                 unit="m/s"                             />
+        <field id="sbu"          long_name="ocean bottom current along i-axis"                                                                  unit="m/s"                             />
+        <field id="ubar"         long_name="ocean barotropic current along i-axis"                                                              unit="m/s"                             />
+        <field id="uocetr_eff"   long_name="Effective ocean transport along i-axis"                 standard_name="ocean_volume_x_transport"    unit="m3/s"       grid_ref="grid_U_3D" />
+        <field id="uocet"        long_name="ocean transport along i-axis times temperature (CRS)"                                               unit="degC*m/s"   grid_ref="grid_U_3D" />
+        <field id="uoces"        long_name="ocean transport along i-axis times salinity (CRS)"                                                  unit="1e-3*m/s"   grid_ref="grid_U_3D" />
+
+        <!-- u-eddy diffusivity coefficients (available if ln_traldf_OFF=F) -->
+        <field id="ahtu_2d"      long_name=" surface u-eddy diffusivity coefficient"   unit="m2/s or m4/s" />
+        <field id="ahtu_3d"      long_name=" 3D u-EIV coefficient"                     unit="m2/s or m4/s"      grid_ref="grid_U_3D"/>
+        <!-- u-eiv diffusivity coefficients (available if ln_ldfeiv=F) -->
+        <field id="aeiu_2d"      long_name=" surface u-EIV coefficient"                unit="m2/s" />
+        <field id="aeiu_3d"      long_name=" 3D u-EIV coefficient"                     unit="m2/s"              grid_ref="grid_U_3D"/>
+
+        <!-- variables available with MLE (ln_mle=T) -->
+        <field id="psiu_mle"     long_name="MLE streamfunction along i-axis"   unit="m3/s"   grid_ref="grid_U_3D" />
+
+        <!-- uoce_eiv: available EIV (ln_ldfeiv=T and ln_ldfeiv_dia=T) -->
+    	<field id="uoce_eiv"      long_name="EIV ocean current along i-axis"                                  standard_name="bolus_sea_water_x_velocity"                     unit="m/s"   grid_ref="grid_U_3D" />
+        <field id="ueiv_masstr"   long_name="EIV Ocean Mass X Transport"                                      standard_name="bolus_ocean_mass_x_transport"                   unit="kg/s"  grid_ref="grid_U_3D" />
+        <field id="ueiv_heattr"   long_name="ocean bolus heat transport along i-axis"                         standard_name="ocean_heat_x_transport_due_to_bolus_advection"  unit="W"                         />
+        <field id="ueiv_salttr"   long_name="ocean bolus salt transport along i-axis"                         standard_name="ocean_salt_x_transport_due_to_bolus_advection"  unit="Kg"                        />
+        <field id="ueiv_heattr3d" long_name="ocean bolus heat transport along i-axis"                         standard_name="ocean_heat_x_transport_due_to_bolus_advection"  unit="W"     grid_ref="grid_U_3D" />
+        <field id="ueiv_salttr3d" long_name="ocean bolus salt transport along i-axis"                         standard_name="ocean_salt_x_transport_due_to_bolus_advection"  unit="kg"    grid_ref="grid_U_3D" />
+
+        <!-- uoce_bbl: available with ln_trabbl=T and nn_bbl_adv=1 -->
+        <field id="uoce_bbl"     long_name="BBL ocean current along i-axis"    unit="m/s"  />
+        <!-- ahu_bbl : available with ln_trabbl=T and nn_bbl_ldf=1 -->
+        <field id="ahu_bbl"      long_name="BBL diffusive flux along i-axis"   unit="m3/s" />
+
+        <!-- variables available with WAVE (ln_wave=T) -->
+        <field id="ustokes"      long_name="Stokes Drift Velocity i-axis"      standard_name="StokesDrift_x_velocity"      unit="m/s"        grid_ref="grid_U_3D" />
+        <field id="ustokes_e3u"  long_name="Stokes Drift Velocity i-axis  (thickness weighted)"                            unit="m/s"        grid_ref="grid_U_3D"  > ustokes * e3u </field>
+
+        <!-- variable for ice shelves -->
+        <field id="utbl"         long_name="zonal current in the Losh tbl"     unit="m/s" />
+
+        <!-- variables available with diaar5 -->
+        <field id="u_masstr"      long_name="Ocean Mass X Transport"                                          standard_name="ocean_mass_x_transport"                         unit="kg/s"  grid_ref="grid_U_3D" />
+        <field id="u_masstr_vint" long_name="vertical integral of ocean eulerian mass transport along i-axis" standard_name="vertical_integral_of_ocean_mass_x_transport"    unit="kg/s"                      />
+        <field id="u_heattr"      long_name="ocean eulerian heat transport along i-axis"                      standard_name="ocean_heat_x_transport"                         unit="W"                         />
+        <field id="u_salttr"      long_name="ocean eulerian salt transport along i-axis"                      standard_name="ocean_salt_x_transport"                         unit="1e-3*kg/s"                 />
+        <field id="uadv_heattr"   long_name="ocean advective heat transport along i-axis"                     standard_name="advectice_ocean_heat_x_transport"               unit="W"                         />
+        <field id="uadv_salttr"   long_name="ocean advective salt transport along i-axis"                     standard_name="advectice_ocean_salt_x_transport"               unit="1e-3*kg/s"                 />
+        <field id="udiff_heattr"  long_name="ocean diffusion heat transport along i-axis"                     standard_name="ocean_heat_x_transport_due_to_diffusion"        unit="W"                         />
+        <field id="udiff_salttr"  long_name="ocean diffusion salt transport along i-axis"                     standard_name="ocean_salt_x_transport_due_to_diffusion"        unit="1e-3*kg/s"                 />
+      </field_group>
+      
+      <!-- V grid -->
+      
+      <field_group id="grid_V"   grid_ref="grid_V_2D">
+        <field id="e1v"          long_name="V-cell width in longitudinal direction"                 standard_name="cell_width"                  unit="m"                              />
+        <field id="e3v"          long_name="V-cell thickness"                                       standard_name="cell_thickness"              unit="m"          grid_ref="grid_V_3D" />
+        <field id="e3v_0"        long_name="Initial V-cell thickness"                               standard_name="ref_cell_thickness"          unit="m"          grid_ref="grid_V_3D" />
+        <field id="vtau"         long_name="Wind Stress along j-axis"                               standard_name="surface_downward_y_stress"   unit="N/m2"                            />
+        <field id="voce"         long_name="ocean current along j-axis"                             standard_name="sea_water_y_velocity"        unit="m/s"        grid_ref="grid_V_3D" />
+        <field id="voce_e3v"     long_name="ocean current along j-axis  (thickness weighted)"                                                   unit="m/s"        grid_ref="grid_V_3D"  > voce * e3v </field>
+        <field id="ssv"          long_name="ocean surface current along j-axis"                                                                 unit="m/s"                             />
+        <field id="sbv"          long_name="ocean bottom current along j-axis"                                                                  unit="m/s"                             />
+        <field id="vbar"         long_name="ocean barotropic current along j-axis"                                                              unit="m/s"                             />
+        <field id="vocetr_eff"   long_name="Effective ocean transport along j-axis"                 standard_name="ocean_volume_y_transport"    unit="m3/s"       grid_ref="grid_V_3D" />
+        <field id="vocet"        long_name="ocean transport along j-axis times temperature (CRS)"                                               unit="degC*m/s"   grid_ref="grid_V_3D" />
+        <field id="voces"        long_name="ocean transport along j-axis times salinity (CRS)"                                                  unit="1e-3*m/s"   grid_ref="grid_V_3D" />
+
+        <!-- v-eddy diffusivity coefficients (available if ln_traldf_OFF=F) -->
+        <field id="ahtv_2d"      long_name=" surface v-eddy diffusivity coefficient"     unit="m2/s or (m4/s)^1/2" />
+        <field id="ahtv_3d"      long_name=" 3D v-eddy diffusivity coefficient"          unit="m2/s or (m4/s)^1/2"           grid_ref="grid_V_3D"/>
+        <!-- v-eiv diffusivity coefficients (available if ln_ldfeiv=F) -->
+        <field id="aeiv_2d"      long_name=" surface v-EIV coefficient"                  unit="m2/s" />
+        <field id="aeiv_3d"      long_name=" 3D v-EIV coefficient"                       unit="m2/s"                         grid_ref="grid_V_3D" />
+
+        <!-- variables available with MLE (ln_mle=T) -->
+        <field id="psiv_mle"     long_name="MLE streamfunction along j-axis"   unit="m3/s"   grid_ref="grid_V_3D" />
+
+        <!-- voce_eiv: available EIV (ln_ldfeiv=T and ln_ldfeiv_dia=T)  -->
+	<field id="voce_eiv"     long_name="EIV ocean current along j-axis"  standard_name="bolus_sea_water_y_velocity"     unit="m/s"   grid_ref="grid_V_3D" />
+        <field id="veiv_masstr"  long_name="EIV Ocean Mass Y Transport"      standard_name="bolus_ocean_mass_y_transport"   unit="kg/s"  grid_ref="grid_V_3D" />
+        <field id="veiv_heattr"   long_name="ocean bolus heat transport along j-axis"       standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"                         />
+        <field id="veiv_salttr"   long_name="ocean bolus salt transport along j-axis"       standard_name="ocean_salt_x_transport_due_to_bolus_advection"   unit="Kg"                        />
+        <field id="veiv_heattr3d" long_name="ocean bolus heat transport along j-axis"       standard_name="ocean_heat_y_transport_due_to_bolus_advection"   unit="W"    grid_ref="grid_V_3D" />
+        <field id="veiv_salttr3d" long_name="ocean bolus salt transport along j-axis"       standard_name="ocean_salt_y_transport_due_to_bolus_advection"   unit="kg"   grid_ref="grid_V_3D" />
+
+
+        <!-- voce_bbl: available with ln_trabbl=T and nn_bbl_adv=1 -->
+        <field id="voce_bbl"     long_name="BBL ocean current along j-axis"    unit="m/s"  />
+        <!-- ahu_bbl : available with ln_trabbl=T and nn_bbl_ldf=1 -->
+        <field id="ahv_bbl"      long_name="BBL diffusive flux along j-axis"   unit="m3/s" />
+
+        <!-- variables available with WAVE (ln_wave=T) -->
+        <field id="vstokes"      long_name="Stokes Drift Velocity j-axis"      standard_name="StokesDrift_y_velocity"      unit="m/s"        grid_ref="grid_V_3D" />
+        <field id="vstokes_e3v"  long_name="Stokes Drift Velocity j-axis  (thickness weighted)"                            unit="m/s"        grid_ref="grid_V_3D"  > vstokes * e3v </field>
+
+        <!-- variable for ice shelves -->
+        <field id="vtbl"         long_name="meridional current in the Losh tbl"   unit="m/s" />
+
+        <!-- variables available with diaar5 -->
+        <field id="v_masstr"      long_name="ocean eulerian mass transport along j-axis"    standard_name="ocean_mass_y_transport"                          unit="kg/s" grid_ref="grid_V_3D" />
+        <field id="v_heattr"      long_name="ocean eulerian heat transport along j-axis"    standard_name="ocean_heat_y_transport"                          unit="W"                         />
+        <field id="v_salttr"      long_name="ocean eulerian salt transport along i-axis"    standard_name="ocean_salt_y_transport"                          unit="1e-3*kg/s"                 />
+        <field id="vadv_heattr"   long_name="ocean advective heat transport along j-axis"   standard_name="advectice_ocean_heat_y_transport"                unit="W"                         />
+        <field id="vadv_salttr"   long_name="ocean advective salt transport along j-axis"   standard_name="advectice_ocean_salt_y_transport"                unit="1e-3*kg/s"                 />
+        <field id="vdiff_heattr"  long_name="ocean diffusion heat transport along j-axis"   standard_name="ocean_heat_y_transport_due_to_diffusion"         unit="W"                         />
+        <field id="vdiff_salttr"  long_name="ocean diffusion salt transport along j-axis"   standard_name="ocean_salt_y_transport_due_to_diffusion"         unit="1e-3*kg/s"                 />
+      </field_group>
+      
+      <!-- W grid -->
+      
+      <field_group id="grid_W" grid_ref="grid_W_3D">
+        <field id="e3w"          long_name="W-cell thickness"                              standard_name="cell_thickness"                         unit="m"    />
+	<field id="woce"         long_name="ocean vertical velocity"                       standard_name="upward_sea_water_velocity"              unit="m/s"  />
+	<field id="woce_e3w"     long_name="ocean vertical velocity * e3w"                                                                        unit="m2/s"  > woce * e3w </field>	
+        <field id="wocetr_eff"   long_name="effective ocean vertical transport"                                                                   unit="m3/s" />
+
+        <!-- woce_eiv: available with EIV  (ln_ldfeiv=T and ln_ldfeiv_dia=T)  -->
+        <field id="woce_eiv"     long_name="EIV ocean vertical velocity"                    standard_name="bolus_upward_sea_water_velocity"       unit="m/s"  />
+        <field id="weiv_masstr"  long_name="EIV Upward Ocean Mass Transport"  standard_name="bolus_upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="weiv_heattr3d" long_name="ocean bolus heat transport"    standard_name="ocean_heat_z_transport_due_to_bolus_advection"   unit="W"    />
+        <field id="weiv_salttr3d" long_name="ocean bolus salt transport"    standard_name="ocean_salt_z_transport_due_to_bolus_advection"   unit="kg"   />
+
+	<field id="avt"          long_name="vertical eddy diffusivity"                      standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+        <field id="avt_e3w"      long_name="vertical heat diffusivity * e3w"                unit="m3/s" > avt * e3w </field> 		
+        <field id="logavt"       long_name="logarithm of vertical eddy diffusivity"         standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+        <field id="avm"          long_name="vertical eddy viscosity"                        standard_name="ocean_vertical_momentum_diffusivity"   unit="m2/s" />
+        <field id="avm_e3w"      long_name="vertical eddy viscosity * e3w"   unit="m3/s" > avm * e3w </field> 
+
+        <!-- avs: /= avt with ln_zdfddm=T -->
+        <field id="avs"          long_name="salt vertical eddy diffusivity"                 standard_name="ocean_vertical_salt_diffusivity"       unit="m2/s" />
+        <field id="avs_e3w"      long_name="vertical salt diffusivity * e3w"   unit="m3/s" > avs * e3w </field> 
+	<field id="logavs"       long_name="logarithm of salt vertical eddy diffusivity"    standard_name="ocean_vertical_heat_diffusivity"       unit="m2/s" />
+
+        <!-- avt_evd and avm_evd: available with ln_zdfevd -->
+        <field id="avt_evd"      long_name="convective enhancement of vertical diffusivity" standard_name="ocean_vertical_tracer_diffusivity_due_to_convection"     unit="m2/s" />
+        <field id="avt_evd_e3w"  long_name="convective enhancement to vertical diffusivity * e3w "    unit="m3/s" > avt_evd * e3w </field> 
+	<field id="avm_evd"      long_name="convective enhancement of vertical viscosity"   standard_name="ocean_vertical_momentum_diffusivity_due_to_convection"   unit="m2/s" />
+
+        <!-- avt_tide: available with ln_zdfiwm=T -->
+        <field id="av_ratio"     long_name="S over T diffusivity ratio"                     standard_name="salinity_over_temperature_diffusivity_ratio"                     unit="1"    />
+        <field id="av_wave"      long_name="internal wave-induced vertical diffusivity"     standard_name="ocean_vertical_tracer_diffusivity_due_to_internal_waves"         unit="m2/s" />
+        <field id="bflx_iwm"     long_name="internal wave-induced buoyancy flux"            standard_name="buoyancy_flux_due_to_internal_waves"                             unit="W/kg" />
+        <field id="pcmap_iwm"    long_name="power consumed by wave-driven mixing"           standard_name="vertically_integrated_power_consumption_by_wave_driven_mixing"   unit="W/m2"      grid_ref="grid_W_2D" />
+        <field id="emix_iwm"     long_name="power density available for mixing"             standard_name="power_available_for_mixing_from_breaking_internal_waves"         unit="W/kg" />
+
+        <!-- variables available with WAVE (ln_wave=T) -->
+        <field id="wstokes"      long_name="Stokes Drift vertical velocity"                 standard_name="upward_StokesDrift_velocity"   unit="m/s" />
+
+        <!-- variables available with diaar5 -->   
+        <field id="w_masstr"     long_name="vertical mass transport"                        standard_name="upward_ocean_mass_transport"             unit="kg/s"   />
+        <field id="w_masstr2"    long_name="square of vertical mass transport"              standard_name="square_of_upward_ocean_mass_transport"   unit="kg2/s2" />
+
+        <!-- EOS -->
+        <field id="bn2"          long_name="squared Brunt-Vaisala frequency"                unit="s-2" />
+
+      </field_group>
+      
+      <!-- F grid -->
+      <!-- f-eddy viscosity coefficients (ldfdyn) -->
+      <field id="ahmf_2d"      long_name=" surface f-eddy viscosity coefficient"   unit="m2/s or m4/s" />
+      <field id="ahmf_3d"      long_name=" 3D      f-eddy viscosity coefficient"   unit="m2/s or m4/s"  grid_ref="grid_T_3D"/>
+
+      <field_group id="scalar"  grid_ref="grid_scalar"  >
+      	<!-- Need to have a salinity reference climatological file : sali_ref_clim_monthly -->
+        <field id="voltot"     long_name="global total volume"                          standard_name="sea_water_volume"                               unit="m3"   />
+        <field id="sshtot"     long_name="global mean ssh"                              standard_name="global_average_sea_level_change"                unit="m"    />
+        <field id="sshsteric"  long_name="global mean ssh steric"                       standard_name="global_average_steric_sea_level_change"         unit="m"    />
+        <field id="sshthster"  long_name="global mean ssh thermosteric"                 standard_name="global_average_thermosteric_sea_level_change"   unit="m"    />
+        <field id="masstot"    long_name="global total mass"                            standard_name="sea_water_mass"                                 unit="kg"   />
+        <field id="temptot"    long_name="global mean temperature"                      standard_name="sea_water_potential_temperature"                unit="degC" />
+	<field id="saltot"     long_name="global mean salinity"                         standard_name="sea_water_salinity"                             unit="1e-3" />
+        <field id="ssttot"     long_name="global mean sea surface temperature"          standard_name="sea_water_conservative_temperature"             unit="degC" />
+         <!-- EOS = TEOS-10 -->
+        <field id="temptot_pot" long_name="global mean potential temperature"            standard_name="sea_water_potential_temperature"               unit="degC" />
+
+      	<!-- available with ln_diahsb -->
+        <field id="bgtemper"     long_name="drift in global mean temperature wrt timestep 1"                 standard_name="change_over_time_in_sea_water_potential_temperature"   unit="degC"     />
+        <field id="bgsaline"     long_name="drift in global mean salinity wrt timestep 1"                    standard_name="change_over_time_in_sea_water_practical_salinity"      unit="1e-3"     />
+        <field id="bgheatco"     long_name="drift in global mean heat content wrt timestep 1"                                                                                      unit="1.e20J"   />
+        <field id="bgheatfx"     long_name="drift in global mean heat flux    wrt timestep 1"                                                                                      unit="W/m2"     />
+        <field id="bgsaltco"     long_name="drift in global mean salt content wrt timestep 1"                                                                                      unit="1e-3*km3" />
+        <field id="bgvolssh"     long_name="drift in global mean ssh volume wrt timestep 1"                                                                                        unit="km3"      />
+        <field id="bgvole3t"     long_name="drift in global mean volume variation (e3t) wrt timestep 1"                                                                            unit="km3"      />
+        <field id="bgfrcvol"     long_name="global mean volume from forcing"                                                                                                       unit="km3"      />
+        <field id="bgfrctem"     long_name="global mean heat content from forcing"                                                                                                 unit="1.e20J"   />
+        <field id="bgfrchfx"     long_name="global mean heat flux from forcing"                                                                                                    unit="W/m2"     />
+        <field id="bgfrcsal"     long_name="global mean salt content from forcing"                                                                                                 unit="1e-3*km3" />
+        <field id="bgmistem"     long_name="global mean temperature error due to free surface (linssh true)"                                                                       unit="degC"     />
+        <field id="bgmissal"     long_name="global mean salinity error due to free surface (linssh true)"                                                                          unit="1e-3"     />
+      </field_group>
+
+
+      <!-- transects -->
+      <field_group id="oce_straits">
+         <field id="uoce_e3u_ave"         long_name="Monthly average of u*e3u"                        field_ref="uoce_e3u"                    freq_op="1mo"   freq_offset="_reset_" > @uoce_e3u </field>
+         <field id="uoce_e3u_ave_vsum"    long_name="Vertical sum of u*e3u"                           field_ref="uoce_e3u_ave"         grid_ref="grid_U_vsum"     />
+         <field id="uocetr_vsum_section"  long_name="Total 2D transport in i-direction"               field_ref="uoce_e3u_ave_vsum"    grid_ref="grid_U_scalar"  detect_missing_value="true"> this * e2u </field>
+         <field id="uocetr_strait"        long_name="Total transport across lines in i-direction"     field_ref="uocetr_vsum_section"  grid_ref="grid_U_4strait" />
+         <field id="u_masstr_strait"      long_name="Sea water transport across line in i-direction"  field_ref="uocetr_strait"        grid_ref="grid_U_4strait_hsum" unit="kg/s"> this * maskMFO_u * $rau0 </field>
+
+         <field id="voce_e3v_ave"         long_name="Monthly average of v*e3v"                        field_ref="voce_e3v"                    freq_op="1mo"   freq_offset="_reset_" > @voce_e3v </field>
+         <field id="voce_e3v_ave_vsum"    long_name="Vertical sum of v*e3v"                           field_ref="voce_e3v_ave"         grid_ref="grid_V_vsum"      />
+         <field id="vocetr_vsum_section"  long_name="Total 2D transport of in j-direction"            field_ref="voce_e3v_ave_vsum"    grid_ref="grid_V_scalar"  detect_missing_value="true"> this * e1v </field>
+         <field id="vocetr_strait"        long_name="Total transport across lines in j-direction"     field_ref="vocetr_vsum_section"  grid_ref="grid_V_4strait"  />
+         <field id="v_masstr_strait"      long_name="Sea water transport across line in j-direction"  field_ref="vocetr_strait"        grid_ref="grid_V_4strait_hsum" unit="kg/s"> this * maskMFO_v * $rau0 </field>
+
+         <field id="masstr_strait"        long_name="Sea water transport across line"                                                  grid_ref="grid_4strait"  > u_masstr_strait + v_masstr_strait </field>
+      </field_group>
+
+      
+      <!-- variables available with ln_floats -->
+
+      <field_group id="floatvar" grid_ref="grid_T_nfloat"  operation="instant" >
+        <field id="traj_lon"      long_name="floats longitude"                                                           unit="degrees_east"  />
+        <field id="traj_lat"      long_name="floats latitude"                                                            unit="degrees_north" />
+        <field id="traj_dep"      long_name="floats depth"                                                               unit="m"             />
+        <field id="traj_temp"     long_name="floats temperature"       standard_name="sea_water_potential_temperature"   unit="degC"          />
+        <field id="traj_salt"     long_name="floats salinity"          standard_name="sea_water_practical_salinity"      unit="1e-3"          />
+        <field id="traj_dens"     long_name="floats in-situ density"   standard_name="sea_water_density"                 unit="kg/m3"         />
+        <field id="traj_group"    long_name="floats group"                                                               unit="1"             />
+      </field_group>
+
+      <!-- variables available with iceberg trajectories -->
+
+      <field_group id="icbvar" domain_ref="grid_T"  > 
+        <field id="berg_melt"          long_name="icb melt rate of icebergs"                       unit="kg/m2/s"                    />
+        <field id="berg_melt_hcflx"    long_name="icb heat flux to ocean due to melting heat content"   unit="J/m2/s"                />
+        <field id="berg_melt_qlat"     long_name="icb heat flux to ocean due to melting latent heat"    unit="J/m2/s"                />
+        <field id="berg_buoy_melt"     long_name="icb buoyancy component of iceberg melt rate"     unit="kg/m2/s"                    />
+        <field id="berg_eros_melt"     long_name="icb erosion component of iceberg melt rate"      unit="kg/m2/s"                    />
+        <field id="berg_conv_melt"     long_name="icb convective component of iceberg melt rate"   unit="kg/m2/s"                    />
+        <field id="berg_virtual_area"  long_name="icb virtual coverage by icebergs"                unit="m2"                         />
+        <field id="bits_src"           long_name="icb mass source of bergy bits"                   unit="kg/m2/s"                    />
+        <field id="bits_melt"          long_name="icb melt rate of bergy bits"                     unit="kg/m2/s"                    />
+        <field id="bits_mass"          long_name="icb bergy bit density field"                     unit="kg/m2"                      />
+        <field id="berg_mass"          long_name="icb iceberg density field"                       unit="kg/m2"                      />
+        <field id="calving"            long_name="icb calving mass input"                          unit="kg/s"                       />
+        <field id="berg_floating_melt" long_name="icb melt rate of icebergs + bits"                unit="kg/m2/s"                    />
+        <field id="berg_real_calving"  long_name="icb calving into iceberg class"                  unit="kg/s"     axis_ref="icbcla" />
+        <field id="berg_stored_ice"    long_name="icb accumulated ice mass by class"               unit="kg"       axis_ref="icbcla" />
+      </field_group>
+
+      <!-- Poleward transport : ptr -->     
+      <field_group id="diaptr" >  
+        <field id="zomsf"         long_name="Overturning Stream-Function : All basins"                     unit="Sv"         grid_ref="grid_znl_W_3D" />
+        <field id="zotem"         long_name="Zonal Mean Temperature : All basins"                          unit="degree_C"   grid_ref="grid_znl_T_3D" />
+        <field id="zosal"         long_name="Zonal Mean Salinity : All basins"                             unit="0.001"      grid_ref="grid_znl_T_3D" />
+        <field id="zosrf"         long_name="Zonal Mean Surface : All basins"                              unit="m2"         grid_ref="grid_znl_T_3D" />
+        <field id="sophtove"      long_name="Overturning Heat Transport: All basins"                       unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopstove"      long_name="Overturning Salt Transport: All basins"                       unit="Giga g/s"   grid_ref="grid_znl_T_2D" />
+        <field id="sophtbtr"      long_name="Barotropic Heat Transport: All basins"                        unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopstbtr"      long_name="Barotropic Salt Transport: All basins"                        unit="Giga g/s"   grid_ref="grid_znl_T_2D" /> 
+        <field id="sophtadv"      long_name="Advective Heat Transport: All basins"                         unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopstadv"      long_name="Advective Salt Transport: All basins"                         unit="Giga g/s"   grid_ref="grid_znl_T_2D" />
+        <field id="sophtldf"      long_name="Diffusive Heat Transport: All basins"                         unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopstldf"      long_name="Diffusive Salt Transport: All basins"                         unit="Giga g/s"   grid_ref="grid_znl_T_2D" />
+        <field id="sophtvtr"      long_name="Heat Transport : All basins"                                  unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopstvtr"      long_name="Salt Transport : All basins"                                  unit="Giga g/s"   grid_ref="grid_znl_T_2D" />  
+        <field id="sophteiv"      long_name="Heat Transport from mesoscale eddy advection: All basins"     unit="PW"         grid_ref="grid_znl_T_2D" />
+        <field id="sopsteiv"      long_name="Salt Transport from mesoscale eddy advection : All basins"    unit="Giga g/s"   grid_ref="grid_znl_T_2D" />
+	<field id="sopstadv"      long_name="Advective Salt Transport"                                     unit="Giga g/s"   grid_ref="grid_znl_T_2D" />
+        <field id="sophtgyre"     long_name="Overturning heat transport due to gyre" field_ref="sophtove"  unit="W"          grid_ref="grid_znl_T_2D" > sophtvtr - sophtove  </field>
+	<field id="sopstgyre"     long_name="Overturning salt transport due to gyre" field_ref="sopstove"  unit="kg/s"       grid_ref="grid_znl_T_2D" > sophtvtr - sopstove  </field>
+       </field_group>
+
+       <field_group id="constant_fields"  grid_ref="grid_T_2D"  operation="once" >
+         <field id="bathy"       long_name="Sea floor depth below geoid"               standard_name="sea_floor_depth_below_geoid"               unit="m"/>
+         <field id="areacello"   long_name="Horizontal area of ocean grid cells"       standard_name="cell_area"                                 unit="m2" />
+         <field id="hfgeou"      long_name="Upward geothermal heat flux at sea floor"  standard_name="upward_geothermal_heat_flux_at_sea_floor"  unit="W/m2"/>
+         <field id="basins"      long_name="ocean tracer region masks"                 standard_name="ocean_tracer_region_masks"   unit="none" grid_ref="grid_basin"  />
+       </field_group>
+
+
+    <!-- 
+============================================================================================================
+                  Physical ocean model trend diagnostics : temperature, KE, PE, momentum
+============================================================================================================
+    -->
+
+   <!-- variables available with ln_tra_trd -->
+   <!-- Asselin trends  calculated on odd time steps-->
+   <field_group id="trendT_odd"  grid_ref="grid_T_3D">
+     <field id="ttrd_atf"      long_name="temperature-trend: asselin time filter"       unit="degree_C/s" />
+     <field id="strd_atf"      long_name="salinity   -trend: asselin time filter"       unit="0.001/s" />
+     <!-- Thickness weighted versions: -->
+     <field id="ttrd_atf_e3t"      unit="degC/s * m"  >  ttrd_atf * e3t </field>
+     <field id="strd_atf_e3t"      unit="1e-3/s * m"  >  strd_atf * e3t </field>
+     <!-- OMIP  layer-integrated trends -->
+     <field id="ttrd_atf_li"      long_name="layer integrated heat-trend: asselin time filter "       unit="W/m^2" > ttrd_atf_e3t * 1026.0 * 3991.86795711963  </field>
+     <field id="strd_atf_li"      long_name="layer integrated salt   -trend: asselin time filter "       unit="kg/(m^2 s)" > strd_atf_e3t * 1026.0 * 0.001 </field>
+   </field_group>
+
+   <!-- Other trends  calculated on even time steps-->
+   <field_group id="trendT_even" grid_ref="grid_T_3D">
+     <field id="ttrd_xad"      long_name="temperature-trend: i-advection"                                                                                          unit="degC/s"                        />
+     <field id="strd_xad"      long_name="salinity   -trend: i-advection"                                                                                          unit="1e-3/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="1e-3/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="1e-3/s"                        />
+     <field id="ttrd_ad"       long_name="temperature-trend: advection"               standard_name="tendency_of_sea_water_temperature_due_to_advection"           unit="degC/s"                         > sqrt( ttrd_xad^2 + ttrd_yad^2 + ttrd_zad^2 ) </field>
+     <field id="strd_ad"       long_name="salinity   -trend: advection"               standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                         > sqrt( strd_xad^2 + strd_yad^2 + strd_zad^2 ) </field>
+     <field id="ttrd_totad"    long_name="temperature-trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="degC/s"                        />
+     <field id="strd_totad"    long_name="salinity   -trend: total advection"         standard_name="tendency_of_sea_water_salinity_due_to_advection"              unit="1e-3/s"                        />
+     <field id="ttrd_sad"      long_name="temperature-trend: surface adv. (linssh true)"                                                                           unit="degC/s"   grid_ref="grid_T_2D" />
+     <field id="strd_sad"      long_name="salinity   -trend: surface adv. (linssh true)"                                                                           unit="1e-3/s"   grid_ref="grid_T_2D" />
+     <field id="ttrd_ldf"      long_name="temperature-trend: lateral  diffusion"      standard_name="tendency_of_sea_water_temperature_due_to_horizontal_mixing"   unit="degC/s"                        />
+     <field id="strd_ldf"      long_name="salinity   -trend: lateral  diffusion"      standard_name="tendency_of_sea_water_salinity_due_to_horizontal_mixing"      unit="1e-3/s"                        />
+     <field id="ttrd_zdf"      long_name="temperature-trend: vertical diffusion"      standard_name="tendency_of_sea_water_temperature_due_to_vertical_mixing"     unit="degC/s"                        />
+     <field id="strd_zdf"      long_name="salinity   -trend: vertical diffusion"      standard_name="tendency_of_sea_water_salinity_due_to_vertical_mixing"        unit="1e-3/s"                        />
+     <field id="ttrd_evd"      long_name="temperature-trend: EVD convection"                                                                                       unit="degC/s"                        />
+     <field id="strd_evd"      long_name="salinity   -trend: EVD convection"                                                                                       unit="1e-3/s"                        />
+
+     <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+     <field id="ttrd_iso"      long_name="temperature-trend: isopycnal diffusion"                             unit="degC/s" > ttrd_ldf + ttrd_zdf - ttrd_zdfp </field>
+     <field id="strd_iso"      long_name="salinity   -trend: isopycnal diffusion"                             unit="1e-3/s" > strd_ldf + strd_zdf - strd_zdfp </field>
+     <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="1e-3/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="1e-3/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="1e-3/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="1e-3/s" />
+     <field id="ttrd_qns"      long_name="temperature-trend: non-solar flux + runoff"   unit="degC/s" grid_ref="grid_T_2D" />
+     <field id="strd_cdt"      long_name="salinity   -trend: C/D term       + runoff"   unit="degC/s" grid_ref="grid_T_2D" />
+     <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" />
+
+     <!-- Thickness weighted versions: -->
+     <field id="ttrd_xad_e3t"      unit="degC/s * m" >  ttrd_xad * e3t </field>
+     <field id="strd_xad_e3t"      unit="1e-3/s * m" >  strd_xad * e3t </field>
+     <field id="ttrd_yad_e3t"      unit="degC/s * m" >  ttrd_yad * e3t </field>
+     <field id="strd_yad_e3t"      unit="1e-3/s * m" >  strd_yad * e3t </field>
+     <field id="ttrd_zad_e3t"      unit="degC/s * m" >  ttrd_zad * e3t </field>
+     <field id="strd_zad_e3t"      unit="1e-3/s * m" >  strd_zad * e3t </field>
+     <field id="ttrd_ad_e3t"       unit="degC/s * m" >  ttrd_ad  * e3t </field>
+     <field id="strd_ad_e3t"       unit="1e-3/s * m" >  strd_ad  * e3t </field>
+     <field id="ttrd_totad_e3t"    unit="degC/s * m" >  ttrd_totad  * e3t </field>
+     <field id="strd_totad_e3t"    unit="1e-3/s * m" >  strd_totad  * e3t </field>
+     <field id="ttrd_ldf_e3t"      unit="degC/s * m" >  ttrd_ldf * e3t </field>
+     <field id="strd_ldf_e3t"      unit="1e-3/s * m" >  strd_ldf * e3t </field>
+     <field id="ttrd_zdf_e3t"      unit="degC/s * m" >  ttrd_zdf * e3t </field>
+     <field id="strd_zdf_e3t"      unit="1e-3/s * m" >  strd_zdf * e3t </field>
+     <field id="ttrd_evd_e3t"      unit="degC/s * m" >  ttrd_evd * e3t </field>
+     <field id="strd_evd_e3t"      unit="1e-3/s * m" >  strd_evd * e3t </field>
+
+     <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+     <field id="ttrd_iso_e3t"      unit="degC/s * m"  >  ttrd_iso * e3t </field>
+     <field id="strd_iso_e3t"      unit="1e-3/s * m"  >  strd_iso * e3t </field>
+     <field id="ttrd_zdfp_e3t"     unit="degC/s * m"  >  ttrd_zdfp * e3t </field>
+     <field id="strd_zdfp_e3t"     unit="1e-3/s * m"  >  strd_zdfp * e3t </field>
+
+     <!-- -->
+     <field id="ttrd_dmp_e3t"      unit="degC/s * m"  >  ttrd_dmp * e3t </field>
+     <field id="strd_dmp_e3t"      unit="1e-3/s * m"  >  strd_dmp * e3t </field>
+     <field id="ttrd_bbl_e3t"      unit="degC/s * m"  >  ttrd_bbl * e3t </field>
+     <field id="strd_bbl_e3t"      unit="1e-3/s * m"  >  strd_bbl * e3t </field>
+     <field id="ttrd_npc_e3t"      unit="degC/s * m"  >  ttrd_npc * e3t </field>
+     <field id="strd_npc_e3t"      unit="1e-3/s * m"  >  strd_npc * e3t </field>
+     <field id="ttrd_qns_e3t"      unit="degC/s * m"  >  ttrd_qns * e3ts </field>
+     <field id="strd_cdt_e3t"      unit="degC/s * m"  >  strd_cdt * e3ts </field>
+     <field id="ttrd_qsr_e3t"      unit="degC/s * m"  >  ttrd_qsr * e3t </field>
+     <field id="ttrd_bbc_e3t"      unit="degC/s * m"  >  ttrd_bbc * e3t </field>
+
+     <!-- OMIP  layer-integrated trends -->
+     <field id="ttrd_totad_li"    long_name="layer integrated heat-trend: total advection"         unit="W/m^2"     > ttrd_totad_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_totad_li"    long_name="layer integrated salt-trend: total advection"         unit="kg/(m^2 s)"    > strd_totad_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_evd_li"      long_name="layer integrated heat-trend: EVD convection"          unit="W/m^2"    > ttrd_evd_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_evd_li"      long_name="layer integrated salt-trend: EVD convection"          unit="kg/(m^2 s)"  > strd_evd_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_iso_li"      long_name="layer integrated heat-trend: isopycnal diffusion"     unit="W/m^2" > ttrd_iso_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_iso_li"      long_name="layer integrated salt-trend: isopycnal diffusion"     unit="kg/(m^2 s)" > strd_iso_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_zdfp_li"     long_name="layer integrated heat-trend: pure vert. diffusion"    unit="W/m^2" > ttrd_zdfp_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_zdfp_li"     long_name="layer integrated salt-trend: pure vert. diffusion"    unit="kg/(m^2 s)" > strd_zdfp_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_qns_li"      long_name="layer integrated heat-trend: non-solar flux + runoff" unit="W/m^2" grid_ref="grid_T_2D"> ttrd_qns_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="ttrd_qsr_li"      long_name="layer integrated heat-trend: solar flux"              unit="W/m^2"  grid_ref="grid_T_3D"> ttrd_qsr_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="ttrd_bbl_li"      long_name="layer integrated heat-trend: bottom boundary layer "  unit="W/m^2" > ttrd_bbl_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_bbl_li"      long_name="layer integrated salt-trend: bottom boundary layer "  unit="kg/(m^2 s)" > strd_bbl_e3t * 1026.0 * 0.001  </field>
+     <field id="ttrd_evd_li"      long_name="layer integrated heat-trend: evd convection "         unit="W/m^2" >ttrd_evd_e3t * 1026.0 * 3991.86795711963  </field>
+     <field id="strd_evd_li"      long_name="layer integrated salt-trend: evd convection "         unit="kg/(m^2 s)" > strd_evd_e3t * 1026.0 * 0.001  </field>
+
+   </field_group>
+
+   <!--  Total trends calculated every time step-->
+   <field_group id="trendT" grid_ref="grid_T_3D">
+     <field id="ttrd_tot"      long_name="temperature-trend: total model trend"         unit="degC/s" />
+     <field id="strd_tot"      long_name="salinity   -trend: total model trend"         unit="1e-3/s" />
+     <!-- Thickness weighted versions: -->
+     <field id="ttrd_tot_e3t"      unit="degC/s * m"  >  ttrd_tot * e3t </field>
+     <field id="strd_tot_e3t"      unit="1e-3/s * m"  >  strd_tot * e3t </field>
+     <!-- OMIP  layer-integrated total trends -->
+     <field id="ttrd_tot_li"      long_name="layer integrated heat-trend: total model trend :"         unit="W/m^2" > ttrd_tot_e3t * 1026.0 * 3991.86795711963 </field>
+     <field id="strd_tot_li"      long_name="layer integrated salt-trend: total model trend :"         unit="kg/(m^2 s)" > strd_tot_e3t * 1026.0 * 0.001  </field>
+
+     <!-- **** these trends have not been apportioned to all/even/odd ts yet **** -->
+     <!-- 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 when explicit lateral mixing is used (ln_dynldf_OFF=F) -->
+     <field id="dispkexyfo"    long_name="KE-trend: lateral  mixing induced dissipation"   standard_name="ocean_kinetic_energy_dissipation_per_unit_area_due_to_xy_friction"                   unit="W/m^2" grid_ref="grid_T_2D" />   
+     <field id="dispkevfo"     long_name="KE-trend: vertical mixing induced dissipation"   standard_name="ocean_kinetic_energy_dissipation_per_unit_area_due_to_vertical_friction"             unit="W/m^2" grid_ref="grid_T_2D" />   
+     <!-- variables available with ln_traadv_eiv=T and ln_diaeiv=T -->
+     <field id="eketrd_eiv"    long_name="EKE-trend due to parameterized eddy advection"   standard_name="tendency_of_ocean_eddy_kinetic_energy_content_due_to_parameterized_eddy_advection"   unit="W/m^2" grid_ref="grid_T_2D" />   
+
+     <!-- 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. (linssh true)" 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="1"                            />   
+     <field id="alphaPE"       long_name="partial deriv. of PEanom wrt T"       unit="degC-1"                       />   
+     <field id="betaPE"        long_name="partial deriv. of PEanom wrt S"       unit="1e3"                          />   
+   </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>
+
+
+    <!-- 
+============================================================================================================
+                                        Definitions for iodef_demo.xml
+============================================================================================================
+    -->
+
+    <field_group id="TRD" >
+      <field field_ref="ttrd_totad_li"   name="opottempadvect"  />
+      <field field_ref="ttrd_iso_li"     name="opottemppmdiff"  />
+      <field field_ref="ttrd_zdfp_li"    name="opottempdiff"  />
+      <field field_ref="ttrd_evd_li"     name="opottempevd" />
+      <field field_ref="strd_evd_li"     name="osaltevd" />
+      <field field_ref="ttrd_qns_li"     name="opottempqns"  />
+      <field field_ref="ttrd_qsr_li"     name="rsdoabsorb" operation="accumulate" />
+      <field field_ref="strd_totad_li"   name="osaltadvect" />
+      <field field_ref="strd_iso_li"     name="osaltpmdiff"  />
+      <field field_ref="strd_zdfp_li"    name="osaltdiff" />
+    </field_group>
+    
+    <field_group id="mooring" >
+      <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"      />
+      <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                   />
+      <field field_ref="uoce"         name="uo"       long_name="sea_water_x_velocity"                 />
+      <field field_ref="voce"         name="vo"       long_name="sea_water_y_velocity"                 />
+      <field field_ref="woce"         name="wo"       long_name="sea_water_z_velocity"                 />
+      <field field_ref="avt"          name="difvho"   long_name="ocean_vertical_heat_diffusivity"      />
+      <field field_ref="avm"          name="difvmo"   long_name="ocean_vertical_momentum_diffusivity"  />
+      
+      <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"                       />
+      <field field_ref="sst2"         name="tossq"    long_name="square_of_sea_surface_temperature"             />
+      <field field_ref="sstgrad"      name="tosgrad"  long_name="module_of_sea_surface_temperature_gradient"    />
+      <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"                          />
+      <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"                />
+      <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="taum"                                                                                   />
+      <field field_ref="20d"                                                                                    />
+      <field field_ref="mldkz5"                                                                                 />
+      <field field_ref="mldr10_1"                                                                               />
+      <field field_ref="mldr10_3"                                                                               />
+      <field field_ref="mldr0_1"                                                                                />
+      <field field_ref="mldr0_3"                                                                                />
+      <field field_ref="mld_dt02"                                                                               />
+      <field field_ref="topthdep"                                                                               />
+      <field field_ref="pycndep"                                                                                />
+      <field field_ref="tinv"                                                                                   />
+      <field field_ref="depti"                                                                                  />
+      <field field_ref="BLT"          name="blt"      long_name="barrier_layer_thickness"                       />
+      <field field_ref="utau"         name="tauuo"    long_name="surface_downward_x_stress"                     />
+      <field field_ref="vtau"         name="tauvo"    long_name="surface_downward_y_stress"                     />
+    </field_group>
+
+    <field_group id="groupT" >
+      <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"               />
+      <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                            />
+      <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"                       />
+      <field field_ref="sst2"         name="tossq"    long_name="square_of_sea_surface_temperature"             />
+      <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"                          />
+      <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"                />
+      <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="taum"                                                                                   />
+      <field field_ref="20d"                                                                                    />
+      <field field_ref="mldkz5"                                                                                 />
+      <field field_ref="mldr10_1"                                                                               />
+      <field field_ref="mldr10_3"                                                                               />
+      <field field_ref="mld_dt02"                                                                               />
+      <field field_ref="topthdep"                                                                               />
+      <field field_ref="pycndep"                                                                                />
+      <field field_ref="tinv"                                                                                   />
+      <field field_ref="depti"                                                                                  />
+      <field field_ref="BLT"          name="blt"      long_name="Barrier Layer Thickness"                       />
+    </field_group>
+    
+    <field_group id="groupU" >
+      <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
+      <field field_ref="utau"         name="tauuo"   long_name="surface_downward_x_stress" />
+    </field_group>
+    
+    <field_group id="groupV" >
+      <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
+      <field field_ref="vtau"         name="tauvo"   long_name="surface_downward_y_stress" />
+    </field_group>
+    
+    <field_group id="groupW" >
+      <field field_ref="woce"         name="wo"       long_name="ocean vertical velocity"  />
+    </field_group>
+
+    <field_group  id="1h_grid_U_tmb" grid_ref="grid_U_2D" operation="instant">
+      <field id="top_u"           name="vozocrtx_top"  unit="m/s"  />
+      <field id="mid_u"           name="vozocrtx_mid"  unit="m/s"  />
+      <field id="bot_u"           name="vozocrtx_bot"  unit="m/s"  />
+      <field id="baro_u"          name="vobtcrtx"      unit="m/s"  />
+    </field_group>
+
+    <field_group  id="1h_grid_V_tmb" grid_ref="grid_V_2D" operation="instant">
+      <field id="top_v"           name="vomecrty_top"  unit="m/s"  />
+      <field id="mid_v"           name="vomecrty_mid"  unit="m/s"  />
+      <field id="bot_v"           name="vomecrty_bot"  unit="m/s"  />
+      <field id="baro_v"          name="vobtcrty"      unit="m/s"  />
+    </field_group>
+
+    <!-- 25h diagnostic output -->
+    <field_group id="25h_grid_T" grid_ref="grid_T_3D" operation="instant">
+      <field id="temper25h"         name="potential temperature 25h mean"    unit="degC" />
+      <field id="tempis25h"         name="insitu temperature 25h mean"    unit="degC" />
+      <field id="salin25h"          name="salinity 25h mean"                 unit="psu"  />
+      <field id="ssh25h"            name="sea surface height 25h mean"  grid_ref="grid_T_2D"      unit="m"    />
+    </field_group>
+
+    <field_group id="25h_grid_U" grid_ref="grid_U_3D" operation="instant" >
+      <field id="vozocrtx25h"         name="i current 25h mean"    unit="m/s"   />
+    </field_group>
+
+    <field_group id="25h_grid_V" grid_ref="grid_V_3D" operation="instant">
+      <field id="vomecrty25h"         name="j current 25h mean"    unit="m/s"    />
+    </field_group>
+
+    <field_group id="25h_grid_W" grid_ref="grid_W_3D" operation="instant">
+      <field id="vovecrtz25h"         name="k current 25h mean"                 unit="m/s"      />
+      <field id="avt25h"              name="vertical diffusivity25h mean"       unit="m2/s" />
+      <field id="avm25h"              name="vertical viscosity 25h mean"        unit="m2/s" />
+      <field id="tke25h"              name="turbulent kinetic energy 25h mean" />
+      <field id="mxln25h"             name="mixing length 25h mean"             unit="m" />
+    </field_group>
+
+    <!-- 
+============================================================================================================
+    -->
+    <!-- output variables for my configuration (example) --> 
+    
+    <field_group id="myvarOCE" >
+      <!-- grid T --> 
+      <field field_ref="e3t"          name="e3t"      long_name="vertical scale factor"           />
+      <field field_ref="sst"          name="tos"      long_name="sea_surface_temperature"         />
+      <field field_ref="sss"          name="sos"      long_name="sea_surface_salinity"            />
+      <field field_ref="ssh"          name="zos"      long_name="sea_surface_height_above_geoid"  />
+      
+      <!-- grid U --> 
+      <field field_ref="e3u"          name="e3u"     long_name="vertical scale factor"            />
+      <field field_ref="ssu"          name="uos"     long_name="sea_surface_x_velocity"           />
+      
+      <!-- grid V --> 
+      <field field_ref="e3v"          name="e3v"     long_name="vertical scale factor"            />
+      <field field_ref="ssv"          name="vos"     long_name="sea_surface_y_velocity"           />     
+    </field_group>    
+
+   </field_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-pisces.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-pisces.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/field_def_nemo-pisces.xml	(revision 14097)
@@ -0,0 +1,320 @@
+<?xml version="1.0"?> 
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+   <field_definition level="1" prec="4" operation="average" enabled=".TRUE." default_value="1.e20" > <!-- time step automaticaly defined -->
+
+    <!-- 
+============================================================================================================
+                                     Biogeochemistry model variables
+============================================================================================================
+    -->
+
+      <!-- ptrc on T grid -->
+
+     <field_group id="ptrc_T" grid_ref="grid_T_3D">
+       <!-- PISCES standard : variables available with ln_p4z  -->
+       <field id="DIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
+       <field id="DIC_e3t"      long_name="DIC * e3t"                                unit="mmol/m2" > DIC * e3t </field >
+       <field id="Alkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
+       <field id="Alkalini_e3t" long_name="Alkalini * e3t"                           unit="mmol/m2"  > Alkalini * e3t </field >
+       <field id="O2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
+       <field id="O2_e3t"       long_name="O2 * e3t"                                 unit="mmol/m2"  > O2 * e3t </field >
+       <field id="CaCO3"        long_name="Calcite Concentration"                    unit="mmol/m3" />
+       <field id="CaCO3_e3t"    long_name="CaCO3 * e3t"                              unit="mmol/m2"  > CaCO3 * e3t </field >
+       <field id="PO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
+       <field id="PO4_e3t"      long_name="PO4 * e3t"                                unit="mmol/m2"  > PO4 * e3t </field >
+       <field id="POC"          long_name="Small organic carbon Concentration"       unit="mmol/m3" />
+       <field id="POC_e3t"      long_name="POC * e3t"                                unit="mmol/m2"  > POC * e3t </field >
+       <field id="Si"           long_name="Silicate Concentration"                   unit="mmol/m3" />
+       <field id="Si_e3t"       long_name="Si * e3t"                                 unit="mmol/m2"  > Si * e3t </field >
+       <field id="PHY"          long_name="(Nano)Phytoplankton Concentration"        unit="mmol/m3" />
+       <field id="PHY_e3t"      long_name="PHY * e3t"                                unit="mmol/m2"  > PHY * e3t </field >
+       <field id="ZOO"          long_name="(Micro)Zooplankton Concentration"         unit="mmol/m3" />
+       <field id="ZOO_e3t"      long_name="ZOO2 * e3t"                               unit="mmol/m2"  > ZOO * e3t </field >
+       <field id="DOC"          long_name="Dissolved organic Concentration"          unit="mmol/m3" />
+       <field id="DOC_e3t"      long_name="DOC * e3t"                                unit="mmol/m2"  > DOC * e3t </field >
+       <field id="PHY2"         long_name="Diatoms Concentration"                    unit="mmol/m3" />
+       <field id="PHY2_e3t"     long_name="PHY2 * e3t"                               unit="mmol/m2"  > PHY2 * e3t </field >
+       <field id="ZOO2"         long_name="Mesozooplankton Concentration"            unit="mmol/m3" />
+       <field id="ZOO2_e3t"     long_name="ZOO2 * e3t"                               unit="mmol/m2"  > ZOO2 * e3t </field >
+       <field id="DSi"          long_name="Diatoms Silicate Concentration"           unit="mmol/m3" />
+       <field id="DSi_e3t"      long_name="Dsi * e3t"                                unit="mmol/m2"  > DSi * e3t </field >
+       <field id="Fer"          long_name="Dissolved Iron Concentration"             unit="mmol/m3" />
+       <field id="Fer_e3t"      long_name="Fer * e3t"                                unit="mmol/m2"  > Fer * e3t </field >
+       <field id="BFe"          long_name="Big iron particles Concentration"         unit="mmol/m3" />
+       <field id="BFe_e3t"      long_name="BFe * e3t"                                unit="mmol/m2"  > BFe * e3t </field >
+       <field id="GOC"          long_name="Big organic carbon Concentration"         unit="mmol/m3" />
+       <field id="GOC_e3t"      long_name="GOC * e3t"                                unit="mmol/m2"  > GOC * e3t </field >
+       <field id="SFe"          long_name="Small iron particles Concentration"       unit="mmol/m3" />
+       <field id="SFe_e3t"      long_name="SFe * e3t"                                unit="mmol/m2"  > SFe * e3t </field >
+       <field id="DFe"          long_name="Diatoms iron  Concentration"              unit="mmol/m3" />
+       <field id="DFe_e3t"      long_name="DFe * e3t"                                unit="mmol/m2"  > DFe * e3t </field >
+       <field id="GSi"          long_name="Sinking biogenic Silicate Concentration"  unit="mmol/m3" />
+       <field id="GSi_e3t"      long_name="GSi * e3t"                                unit="mmol/m2"  > GSi * e3t </field >
+       <field id="NFe"          long_name="Nano iron Concentration"                  unit="mmol/m3" />
+       <field id="NFe_e3t"      long_name="NFe * e3t"                                unit="mmol/m2"  > NFe * e3t </field >
+       <field id="NCHL"         long_name="Nano chlorophyl Concentration"            unit="mg/m3"   />
+       <field id="NCHL_e3t"     long_name="NCHL * e3t"                               unit="mmol/m2"  > NCHL * e3t </field >
+       <field id="DCHL"         long_name="Diatoms chlorophyl Concentration"         unit="mg/m3"   />
+       <field id="DCHL_e3t"     long_name="DCHL * e3t"                               unit="mmol/m2"  > DCHL * e3t </field >
+       <field id="NO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
+       <field id="NO3_e3t"      long_name="NO3 * e3t"                                unit="mmol/m2"  > NO3 * e3t </field >
+       <field id="NH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
+       <field id="NH4_e3t"      long_name="NH4 * e3t"                                unit="mmol/m2"  > NH4 * e3t </field >
+
+       <!-- PISCES quota : variables available with ln_p5z  -->
+
+       <field id="DON"          long_name="Dissolved organic N Concentration"        unit="mmol/m3" />
+       <field id="DON_e3t"      long_name="DON * e3t"                                unit="mmol/m2"  > DON * e3t </field >
+       <field id="DOP"          long_name="Dissolved organic P Concentration"        unit="mmol/m3" />
+       <field id="DOP_e3t"      long_name="DOP * e3t"                                unit="mmol/m2"  > DOP * e3t </field >
+       <field id="PON"          long_name="Small PON Concentration"                  unit="mmol/m3" />
+       <field id="PON_e3t"      long_name="PON * e3t"                                unit="mmol/m2"  > PON * e3t </field >
+       <field id="POP"          long_name="Small POP Concentration"                  unit="mmol/m3" />
+       <field id="POP_e3t"      long_name="POP * e3t"                                unit="mmol/m2"  > POP * e3t </field >
+       <field id="GON"          long_name="Big PON Concentration"                    unit="mmol/m3" />
+       <field id="GON_e3t"      long_name="GON * e3t"                                unit="mmol/m2"  > GON * e3t </field >
+       <field id="GOP"          long_name="Big POP Concentration"                    unit="mmol/m3" />
+       <field id="GOP_e3t"      long_name="GOP * e3t"                                unit="mmol/m2"  > GOP * e3t </field >
+       <field id="PHYN"         long_name="Nanophytoplankton N biomass"              unit="mmol/m3" />
+       <field id="PHYN_e3t"     long_name="PHYN * e3t"                               unit="mmol/m2"  > PHYN * e3t </field >
+       <field id="PHYP"         long_name="Nanophytoplankton P biomass"              unit="mmol/m3" />
+       <field id="PHYP_e3t"     long_name="PHYP * e3t"                               unit="mmol/m2"  > PHYP * e3t </field >
+       <field id="DIAN"         long_name="Diatoms N biomass"                        unit="mmol/m3" />
+       <field id="DIAN_e3t"     long_name="DIAN * e3t"                               unit="mmol/m2"  > DIAN * e3t </field >
+       <field id="DIAP"         long_name="Diatoms P biomass"                        unit="mmol/m3" />
+       <field id="DIAP_e3t"     long_name="DIAP * e3t"                               unit="mmol/m2"  > DIAP * e3t </field >
+       <field id="PIC"          long_name="Picophytoplankton C biomass"              unit="mmol/m3" />
+       <field id="PIC_e3t"      long_name="PIC * e3t"                                unit="mmol/m2"  > PIC * e3t </field >
+       <field id="PICN"         long_name="Picophytoplankton N biomass"              unit="mmol/m3" />
+       <field id="PICN_e3t"     long_name="PICN * e3t"                               unit="mmol/m2"  > PICN * e3t </field >
+       <field id="PICP"         long_name="Picophytoplankton P biomass"              unit="mmol/m3" />
+       <field id="PICP_e3t"     long_name="PICP * e3t"                               unit="mmol/m2"  > PICP * e3t </field >
+       <field id="PFe"          long_name="Picophytoplankton Fe biomass"             unit="mmol/m3" />
+       <field id="PFe_e3t"      long_name="PFe * e3t"                                unit="mmol/m2"  > PFe * e3t </field >
+       <field id="PCHL"         long_name="Picophytoplankton Chl biomass"            unit="mg/m3" />
+       <field id="PCHL_e3t"     long_name="PCHL * e3t"                               unit="mmol/m2"  > PCHL * e3t </field >
+
+      <!-- PISCES with ligand parametisation : variables available namelist paramter ln_ligand -->
+       <field id="LGW"         long_name="Weak ligands concentration"                unit="mmol/m3" />
+       <field id="LGW_e3t"     long_name="LGW * e3t"                                 unit="mmol/m2"  > LGW * e3t </field >
+
+       <!-- PISCES light : variables available with ln_p2z  -->
+       <field id="DET"         long_name="Detritus"                                 unit="mmol-N/m3" />
+       <field id="DET_e3t"     long_name="DET * e3t"                                unit="mmol-N/m2"  > DET * e3t </field >
+       <field id="DOM"         long_name="Dissolved Organic Matter"                 unit="mmol-N/m3" />
+       <field id="DOM_e3t"     long_name="DOM * e3t"                                unit="mmol-N/m2"  > DOM * e3t </field >
+
+     </field_group>
+
+     <!-- SEDIMENT variables on T sediment grid  -->
+     <field_group id="sed_T" grid_ref="grid_T_3DS">
+       <field id="SedDIC"          long_name="Dissolved inorganic Concentration"        unit="mmol/m3" />
+       <field id="SedAlkalini"     long_name="Total Alkalinity Concentration"           unit="mmol/m3" />
+       <field id="SedO2"           long_name="Oxygen Concentration"                     unit="mmol/m3" />
+       <field id="SedCaCO3"        long_name="Calcite Concentration"                    unit="%" />
+       <field id="SedPOS"          long_name="Semi-ref POC Concentration"               unit="%" />
+       <field id="SedPOR"          long_name="Refractory POC Concentration"             unit="%" />
+       <field id="SedPO4"          long_name="Phosphate Concentration"                  unit="mmol/m3" />
+       <field id="SedPOC"          long_name="Labile POC Concentration"                 unit="%" />
+       <field id="SedSil"          long_name="Silicate Concentration"                   unit="mmol/m3" />
+       <field id="SedFe2"          long_name="Fe2+ Concentration"                       unit="mmol/m3" />
+       <field id="SedBSi"          long_name="Biogenic Silicate Concentration"          unit="%" />
+       <field id="SedNO3"          long_name="Nitrate Concentration"                    unit="mmol/m3" />
+       <field id="SedNH4"          long_name="Ammonium Concentration"                   unit="mmol/m3" />
+       <field id="SedH2S"          long_name="H2S Concentration"                        unit="mmol/m3" />
+       <field id="SedSO4"          long_name="SO4 Concentration"                        unit="mmol/m3" />
+       <field id="SedClay"         long_name="Clay Concentration"                       unit="%" />
+       <field id="SedFeO"          long_name="Fe(OH)3 Concentration"                    unit="%" />
+       <field id="SedFeS"          long_name="FeS Concentration"                        unit="%" />
+       <field id="SedpH"           long_name="PH"                                       unit="1"          />
+       <field id="SedCO3por"       long_name="Bicarbonates"                             unit="mol/m3" />
+     </field_group>
+
+     <!-- SEDIMENT additional variables on T sediment grid  -->
+     <field_group id="Diag_S" grid_ref="grid_T_2D">
+       <field id="FlxSi"       long_name="Si sediment flux"                        unit="mol/cm2/s"     />
+       <field id="FlxO2"       long_name="O2 sediment flux"                        unit="mol/cm2/s"     />
+       <field id="FlxDIC"      long_name="DIC sediment flux"                       unit="mol/cm2/s"     />
+       <field id="FlxNO3"      long_name="NO3 sediment flux"                       unit="mol/cm2/s"     />
+       <field id="FlxPO4"      long_name="PO4 sediment flux"                       unit="mol/cm2/s"     />
+       <field id="FlxAlkalini" long_name="Alkalinity sediment flux"                unit="mol/cm2/s"     />
+       <field id="FlxNH4"      long_name="Ammonium sediment flux"                  unit="mol/cm2/s"     />
+       <field id="FlxH2S"      long_name="H2S sediment flux"                       unit="mol/cm2/s"     />
+       <field id="FlxSO4"      long_name="SO4 sediment flux"                       unit="mol/cm2/s"     />
+       <field id="FlxFe2"      long_name="Fe2+ sediment flux"                      unit="mol/cm2/s"     />
+       <field id="Flxtot"      long_name="Sediment net burial rate"                unit="cm/s"     />
+       <field id="dzdep"       long_name="Sedimentation rate"                      unit="cm/s"     />
+       <field id="sflxclay"    long_name="Clay sedimentation rate"                 unit="g/m2/s"     />
+       <field id="sflxcal"     long_name="Calcite sedimentation rate"              unit="mol/m2/s"     />
+       <field id="sflxbsi"     long_name="BSi Sedimentation rate"                  unit="mol/m2/s"     />
+       <field id="sflxpoc"     long_name="POC Sedimentation rate"                  unit="mol/m2/s"     />
+       <field id="sflxfeo"     long_name="Fe(OH)3 Sedimentation rate"              unit="mol/m2/s"     />
+</field_group>
+
+     <!-- PISCES additional diagnostics on T grid  -->
+
+     <field_group id="diad_T" grid_ref="grid_T_2D">
+       <field id="PH"          long_name="PH"                                      unit="1"          grid_ref="grid_T_3D" />
+       <field id="CO3"         long_name="Bicarbonates"                            unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="CO3sat"      long_name="CO3 saturation"                          unit="mol/m3"     grid_ref="grid_T_3D" />
+       <field id="PAR"         long_name="Photosynthetically Available Radiation"  unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PARDM"       long_name="Daily mean PAR"                          unit="W/m2"       grid_ref="grid_T_3D" />
+       <field id="PPPHYN"      long_name="Primary production of nanophyto"         unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PPPHYP"      long_name="Primary production of picophyto"         unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PPPHYD"      long_name="Primary production of diatoms"           unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PPNEWN"      long_name="New Primary production of nanophyto"     unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PPNEWP"      long_name="New Primary production of picophyto"     unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PPNEWD"      long_name="New Primary production of diatoms"       unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PBSi"        long_name="Primary production of Si diatoms"        unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PFeN"        long_name="Primary production of nano iron"         unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PFeP"        long_name="Primary production of pico iron"         unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="PFeD"        long_name="Primary production of diatoms iron"      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="xfracal"     long_name="Calcifying fraction"                     unit="1"          grid_ref="grid_T_3D" />
+       <field id="PCAL"        long_name="Calcite production"                      unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DCAL"        long_name="Calcite dissolution"                     unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ1"       long_name="Grazing by microzooplankton"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="GRAZ2"       long_name="Grazing by mesozooplankton"              unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="REMIN"       long_name="Oxic remineralization of OM"             unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="DENIT"       long_name="Anoxic remineralization of OM"           unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="REMINP"       long_name="Oxic remineralization rate of POC"      unit="d-1"        grid_ref="grid_T_3D" />
+       <field id="REMING"       long_name="Oxic remineralization rate of GOC"      unit="d-1"        grid_ref="grid_T_3D" />
+       <field id="Nfix"        long_name="Nitrogen fixation"                       unit="mol/m3/s"   grid_ref="grid_T_3D" />
+       <field id="Mumax"       long_name="Maximum growth rate"                     unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuN"         long_name="Realized growth rate for nanophyto"      unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuP"         long_name="Realized growth rate for picophyto"      unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MuD"         long_name="Realized growth rate for diatomes"       unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MunetN"      long_name="Net growth rate for nanophyto"           unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MunetP"      long_name="Net growth rate for picophyto"           unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="MunetD"      long_name="Net growth rate for diatomes"            unit="s-1"        grid_ref="grid_T_3D" />
+       <field id="LNnut"       long_name="Nutrient limitation term in Nanophyto"   unit=""           grid_ref="grid_T_3D" />
+       <field id="LPnut"       long_name="Nutrient limitation term in Picophyto"   unit="-"          grid_ref="grid_T_3D" />
+       <field id="LDnut"       long_name="Nutrient limitation term in Diatoms"     unit=""           grid_ref="grid_T_3D" />
+       <field id="LNFe"        long_name="Iron limitation term in Nanophyto"       unit=""           grid_ref="grid_T_3D" />
+       <field id="LPFe"        long_name="Iron limitation term in Picophyto"       unit="-"          grid_ref="grid_T_3D" />
+       <field id="LDFe"        long_name="Iron limitation term in Diatoms"         unit=""           grid_ref="grid_T_3D" />
+       <field id="LNlight"     long_name="Light limitation term in Nanophyto"      unit=""           grid_ref="grid_T_3D" />
+       <field id="LPlight"     long_name="Light limitation term in Picophyto"      unit="-"          grid_ref="grid_T_3D" />
+       <field id="LDlight"     long_name="Light limitation term in Diatoms"        unit=""           grid_ref="grid_T_3D" />
+       <field id="SIZEN"       long_name="Mean relative size of nanophyto."        unit="-"          grid_ref="grid_T_3D" />
+       <field id="SIZEP"       long_name="Mean relative size of picophyto."        unit="-"          grid_ref="grid_T_3D" />
+       <field id="SIZED"       long_name="Mean relative size of diatoms"           unit="-"          grid_ref="grid_T_3D" />
+       <field id="Fe3"         long_name="Iron III concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="FeL1"        long_name="Complexed Iron concentration with L1"    unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="TL1"         long_name="Total L1 concentration"                  unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="pdust"       long_name="dust concentration"                      unit="g/m3"                            />
+       <field id="Totlig"      long_name="Total ligand concentation"               unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Biron"       long_name="Bioavailable iron"                       unit="nmol/m3"    grid_ref="grid_T_3D" />
+       <field id="Sdenit"      long_name="Nitrate reduction in the sediments"      unit="mol/m2/s"                        />
+       <field id="Ironice"     long_name="Iron input/uptake due to sea ice"        unit="mol/m2/s"                        />
+       <field id="SedCal"      long_name="Calcite burial in the sediments"         unit="molC/m2/s"                       />
+       <field id="SedSi"       long_name="Silicon burial in the sediments"         unit="molSi/m2/s"                      />
+       <field id="SedC"        long_name="Organic C burial in the sediments"       unit="molC/m2/s"                       />
+       <field id="HYDR"        long_name="Iron input from hydrothemal vents"       unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EPC100"      long_name="Export of carbon particles at 100 m"     unit="mol/m2/s"                        />
+       <field id="EPFE100"     long_name="Export of biogenic iron at 100 m"        unit="mol/m2/s"                        />
+       <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="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPSI"       long_name="Export of Silicate"                      unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="mol/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"                        />
+       <field id="Kg"          long_name="Gas transfer"                            unit="mol/m2/s/uatm"                   />
+       <field id="Dpco2"       long_name="Delta CO2"                               unit="uatm"                            />
+       <field id="pCO2sea"     long_name="surface ocean pCO2"                      unit="uatm"                            />
+       <field id="Dpo2"        long_name="Delta O2"                                unit="uatm"                            />
+       <field id="Heup"        long_name="Euphotic layer depth"                    unit="m"                               />
+       <field id="AtmCo2"      long_name="Atmospheric CO2 concentration"           unit="ppm"                               />
+       <field id="Irondep"     long_name="Iron deposition from dust"               unit="mol/m2/s"                        />
+       <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="FESCAV"      long_name="Scavenging of Iron"                      unit="mmol-Fe/m3/s"   grid_ref="grid_T_3D" />
+       <field id="FECOLL"      long_name="Colloidal Pumping of FeL"                unit="mmol-FeL/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LGWCOLL"     long_name="Coagulation loss of ligands"             unit="mmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="REMINF"      long_name="Oxic remineralization suppy of Fe"       unit="mmol-Fe/m3/s"  grid_ref="grid_T_3D" />
+       <field id="BACT"        long_name="Bacterial Biomass"                       unit="mmol/m3"  grid_ref="grid_T_3D" />
+       <field id="FEBACT"      long_name="Bacterial uptake of Fe"                  unit="molFe/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LPRODR"      long_name="OM remineralisation ligand production rate" unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LPRODP"      long_name="phytoplankton ligand production rate"    unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LIGREM"      long_name="Remineralisation loss of ligands"        unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LIGPR"       long_name="Photochemical loss of ligands"           unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LDETP"       long_name="Ligand destruction during phytoplankton uptake" unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LPRODZ2"     long_name="mesozooplankton ligand production rate"  unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="LPRODZ"      long_name="microzooplankton ligand production rate" unit="nmol-L/m3/s"  grid_ref="grid_T_3D" />
+       <field id="FEZOO"       long_name="microzooplankton iron recycling rate"    unit="nmol-FeL/m3/s"  grid_ref="grid_T_3D" />
+       <field id="FEZOO2"      long_name="mesozooplankton iron recycling rate"     unit="nmol-FeL/m3/s"  grid_ref="grid_T_3D" />
+
+       <!-- PISCES tracers trends -->
+       <field id="INTdtAlk"    long_name="Vertically int. of change of alkalinity"             unit="mol/m2/s"                       />
+       <field id="INTdtDIC"    long_name="Vertically int. of change of dissic    "             unit="mol/m2/s"                       />
+       <field id="INTdtFer"    long_name="Vertically int. of change of iron      "             unit="mol/m2/s"                       />
+       <field id="INTdtDIN"    long_name="Vertically int. of change of nitrogen  "             unit="mol/m2/s"                       />
+       <field id="INTdtDIP"    long_name="Vertically int. of change of phophate  "             unit="mol/m2/s"                       />
+       <field id="INTdtSil"    long_name="Vertically int. of change of silicon   "             unit="mol/m2/s"                       />
+
+
+       <!-- dbio_T on T grid : variables available with diaar5 -->
+       <!-- dbio_T on T grid : variables available with diaar5 -->
+       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="mol/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="mol/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="mol/m3"                          />
+       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"                              />
+
+       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > Nfix * e3t </field >
+       <field id="INTPPPHYN"   long_name="Vertically integrated primary production by nanophy" unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > PPPHYN * e3t </field >
+       <field id="INTPPPHYD"   long_name="Vertically integrated primary production by diatom"  unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > PPPHYD * e3t </field >
+       <field id="INTPPPHYP"   long_name="Vertically integrated primary production by picophy" unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > PPPHYP * e3t </field >
+       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > TPP * e3t </field >
+       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > TPNEW * e3t </field >
+       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > TPBFE * e3t </field >
+       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="mol/m2/s"  grid_ref="grid_T_vsum"  detect_missing_value="true" > PBSi * e3t </field >
+
+       <!-- PISCES light : variables available with key_pisces_reduced -->
+       <field id="FNO3PHY"     long_name="FNO3PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4PHY"     long_name="FNH4PHY"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="FNH4NO3"     long_name="FNH4NO3"                                 unit=""          grid_ref="grid_T_3D" /> 
+       <field id="TNO3PHY"     long_name="TNO3PHY"                                 unit=""  /> 
+       <field id="TNH4PHY"     long_name="TNH4PHY"                                 unit=""  /> 
+       <field id="TPHYDOM"     long_name="TPHYDOM"                                 unit=""  /> 
+       <field id="TPHYNH4"     long_name="TPHYNH4"                                 unit=""  /> 
+       <field id="TPHYZOO"     long_name="TPHYZOO"                                 unit=""  /> 
+       <field id="TPHYDET"     long_name="TPHYDET"                                 unit=""  /> 
+       <field id="TDETZOO"     long_name="TDETZOO"                                 unit=""  /> 
+       <field id="TZOODET"     long_name="TZOODET"                                 unit=""  /> 
+       <field id="TZOOBOD"     long_name="TZOOBOD"                                 unit=""  /> 
+       <field id="TZOONH4"     long_name="TZOONH4"                                 unit=""  /> 
+       <field id="TZOODOM"     long_name="TZOODOM"                                 unit=""  /> 
+       <field id="TNH4NO3"     long_name="TNH4NO3"                                 unit=""  /> 
+       <field id="TDOMNH4"     long_name="TDOMNH4"                                 unit=""  /> 
+       <field id="TDETNH4"     long_name="TDETNH4"                                 unit=""  /> 
+       <field id="TPHYTOT"     long_name="TPHYTOT"                                 unit=""  /> 
+       <field id="TZOOTOT"     long_name="TZOOTOT"                                 unit=""  /> 
+       <field id="SEDPOC"      long_name="SEDPOC"                                  unit=""  /> 
+       <field id="TDETSED"     long_name="TDETSED"                                 unit=""  /> 
+     </field_group>
+
+     <field_group id="tracer_scalar"  grid_ref="grid_scalar"  >
+     <!-- PISCES scalar  -->
+       <field id="pno3tot"         long_name="Global mean nitrate concentration"                  unit="mol/m3"   />
+       <field id="ppo4tot"         long_name="global mean phosphorus concentration"               unit="mol/m3"   />
+       <field id="psiltot"         long_name="Global mean silicate concentration"                 unit="mol/m3"   />
+       <field id="palktot"         long_name="Global mean alkalinity concentration"               unit="mol/m3"   />
+       <field id="pfertot"         long_name="Global mean iron concentration"                     unit="mol/m3"   />
+       <field id="tcflx"           long_name="Total Flux of Carbon out of the ocean"              unit="mol/s"   />
+       <field id="tcflxcum"        long_name="Cumulative total Flux of Carbon out of the ocean"   unit="mol/s"   />
+       <field id="tcexp"           long_name="Total Carbon export at 100m"                        unit="mol/s"   />
+       <field id="tintpp"          long_name="Global total integrated primary production"         unit="mol/s"   />
+       <field id="tnfix"           long_name="Global total nitrogen fixation"                     unit="mol/s"   />
+       <field id="tdenit"          long_name="Total denitrification"                              unit="mol/s"   />
+     </field_group>
+
+   </field_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,268 @@
+<!--
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+ 
+    <grid_definition>    
+
+        <!--  -->
+       <grid id="grid_T_2D" >
+         <domain domain_ref="grid_T" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_ncatice" >
+         <domain domain_ref="grid_T" />
+         <axis axis_ref="ncatice" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3D" >
+         <domain domain_ref="grid_T" />
+         <axis axis_ref="deptht" />
+       </grid>
+        <!--  -->
+       <grid id="grid_T_3DS" >
+         <domain domain_ref="grid_T" />
+         <axis axis_ref="profsed" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_2D" >
+         <domain domain_ref="grid_U" />
+       </grid>
+        <!--  -->
+       <grid id="grid_U_3D" >
+         <domain domain_ref="grid_U" />
+         <axis axis_ref="depthu" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_2D" >
+         <domain domain_ref="grid_V" />
+       </grid>
+        <!--  -->
+       <grid id="grid_V_3D" >
+         <domain domain_ref="grid_V" />
+         <axis axis_ref="depthv" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_2D" >
+         <domain domain_ref="grid_W" />
+       </grid>
+        <!--  -->
+       <grid id="grid_W_3D" >
+         <domain domain_ref="grid_W" />
+         <axis axis_ref="depthw" />
+       </grid>
+        <!--  -->
+       <grid id="grid_1point" >
+         <domain domain_ref="1point"/>
+       </grid>
+        <!--  -->
+       <grid id="grid_T_nfloat" >
+         <domain domain_ref="grid_T" />
+         <axis axis_ref="nfloat" />
+       </grid>
+        <!--  -->
+       <grid id="grid_EqT" >
+         <domain domain_ref="EqT" />
+       </grid>
+        <!--  -->
+
+
+       <grid id="grid_znl_T_2D">
+         <domain domain_ref="gznl" />
+         <axis axis_ref="basin" />
+       </grid>
+
+       <grid id="grid_znl_T_3D">
+         <domain domain_ref="gznl" />
+         <axis axis_ref="deptht"  />
+         <axis axis_ref="basin" />
+       </grid>
+
+       <grid id="grid_znl_W_3D">
+         <domain domain_ref="gznl" />
+         <axis axis_ref="depthw"  />
+         <axis axis_ref="basin" />
+       </grid>
+
+      <grid id="grid_ptr_T_2D">
+         <domain domain_ref="ptr" />
+         <axis axis_ref="basin" />
+       </grid>
+
+       <grid id="grid_ptr_T_3D">
+         <domain  domain_ref="ptr" />
+         <axis axis_ref="deptht"  />
+         <axis axis_ref="basin" />
+       </grid>
+
+       <grid id="grid_ptr_W_3D">
+         <domain  domain_ref="ptr" />
+         <axis axis_ref="depthw"  />
+         <axis axis_ref="basin" />
+       </grid>
+
+       <grid id="grid_ptr_W_GLO">
+         <domain  domain_ref="ptr" />
+         <axis axis_ref="depthw"  />
+         <scalar>
+           <extract_axis position="0" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_ptr_W_ATL">
+         <domain  domain_ref="ptr" />
+         <axis axis_ref="depthw"  />
+         <scalar>
+           <extract_axis position="1" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_ptr_W_IND">
+         <domain  domain_ref="ptr" />
+         <axis axis_ref="depthw"  />
+         <scalar>
+           <extract_axis position="2" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_T_SFC">
+         <domain domain_ref="grid_T" />
+         <scalar>
+           <extract_axis position="0" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_T_vsum">
+         <domain domain_ref="grid_T"/>
+         <scalar>
+            <reduce_axis operation="sum" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_U_vsum">
+         <domain domain_ref="grid_U"/>
+         <scalar>
+            <reduce_axis operation="sum" />
+         </scalar>
+       </grid>
+
+       <grid id="grid_V_vsum">
+         <domain domain_ref="grid_V"/>
+         <scalar>
+            <reduce_axis operation="sum" />
+         </scalar>
+       </grid>
+
+       <!-- for ORCA2 grid  -->
+       <grid id="cumul_U">
+         <axis axis_ref="cumul_U" n_glo="182" >
+           <reduce_domain local="true" operation="sum" direction="jDir" />
+           <reduce_axis operation="sum" />
+         </axis>
+         <axis axis_ref="depthu" />
+       </grid>
+
+       <!-- for eORCA1 grid
+
+       <grid id="cumul_U">
+         <axis axis_ref="cumul_U" n_glo="362" >
+           <reduce_domain local="true" operation="sum" direction="jDir" />
+           <reduce_axis operation="sum" />
+         </axis>
+         <axis axis_ref="depthu" />
+       </grid>
+
+      -->
+
+
+       <grid id="grid_T_zoom_300">
+         <domain domain_ref="grid_T" />
+         <axis axis_ref="deptht300" />
+       </grid>
+
+       <grid id="grid_U_scalar" >
+         <domain domain_ref="grid_U" />
+         <scalar/>
+       </grid>
+
+       <grid id="grid_V_scalar" >
+         <domain domain_ref="grid_V" />
+         <scalar/>
+       </grid>
+ 
+       <grid id="grid_U_4strait">
+         <domain domain_ref="grid_U" />
+         <axis axis_ref="section">
+           <duplicate_scalar/>
+         </axis>
+       </grid>
+ 
+       <grid id="grid_V_4strait">
+         <domain domain_ref="grid_V" />
+         <axis axis_ref="section">
+           <duplicate_scalar/>
+         </axis>
+       </grid>
+ 
+       <grid id="grid_U_4strait_hsum">
+         <scalar >
+           <reduce_domain operation="sum" local="true"/>
+           <reduce_scalar operation="sum" />
+         </scalar>
+         <axis axis_ref="section"/>
+       </grid>
+ 
+       <grid id="grid_V_4strait_hsum">
+         <scalar >
+           <reduce_domain operation="sum" local="true"/>
+           <reduce_scalar operation="sum" />
+         </scalar>
+         <axis axis_ref="section"/>
+       </grid>
+ 
+       <grid id="grid_4strait">
+         <axis axis_ref="section"/>
+       </grid>
+
+      <grid id="grid_U_4strait_ice">
+        <domain domain_ref="grid_U" />
+        <axis axis_ref="section_ice">
+          <duplicate_scalar/>
+        </axis>
+      </grid>
+
+      <grid id="grid_V_4strait_ice">
+        <domain domain_ref="grid_V" />
+        <axis axis_ref="section_ice">
+         <duplicate_scalar/>
+        </axis>
+      </grid>
+
+      <grid id="grid_U_4strait_ice_hsum">
+        <scalar >
+         <reduce_domain operation="sum" local="true"/>
+         <reduce_scalar operation="sum" />
+        </scalar>
+        <axis axis_ref="section_ice"/>
+      </grid>
+
+     <grid id="grid_V_4strait_ice_hsum">
+        <scalar >
+         <reduce_domain operation="sum" local="true"/>
+         <reduce_scalar operation="sum" />
+        </scalar>
+        <axis axis_ref="section_ice"/>
+     </grid>
+
+     <grid id="grid_4strait_ice">
+       <axis axis_ref="section_ice"/>
+     </grid>
+ 
+      <!-- scalars -->
+      <grid id="grid_scalar" >
+        <scalar/>
+      </grid>
+ 
+    </grid_definition>   
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,269 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 namelist:  
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   5             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   nlay_s           =   1             !  number of snow layers (only 1 is working)
+   ln_virtual_itd   =   .false.       !  virtual ITD mono-category parameterization (jpl=1 only)
+                                      !     i.e. enhanced thermal conductivity & virtual thin ice melting
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .true.          !  ice thermo   (T) or not (F)
+   rn_amax_n        =   0.997         !  maximum tolerated ice concentration NH
+   rn_amax_s        =   0.997         !  maximum tolerated ice concentration SH
+   cn_icerst_in     = "restart_ice"   !  suffix of ice restart name (input)
+   cn_icerst_out    = "restart_ice"   !  suffix of ice restart name (output)
+   cn_icerst_indir  = "."             !  directory to read   input ice restarts
+   cn_icerst_outdir = "."             !  directory to write output ice restarts
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+   ln_cat_hfn       = .true.          !  ice categories are defined by a function following rn_himean**(-0.05)
+      rn_himean     =   2.0           !  expected domain-average ice thickness (m)
+   ln_cat_usr       = .false.         !  ice categories are defined by rn_catbnd below (m)
+      rn_catbnd     =   0.,0.45,1.1,2.1,3.7,6.0  
+   rn_himin         =   0.1           !  minimum ice thickness (m) allowed
+   rn_himax         =  99.0           !  maximum ice thickness (m) allowed
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .true.          !  dyn.: full ice dynamics                  (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections     (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   0.5           !        prescribed ice u-velocity
+      rn_vice       =   0.5           !        prescribed ice v-velocity
+   rn_ishlat        =   2.            !  lbc : free slip (0) ; partial slip (0-2) ; no slip (2) ; strong slip (>2)
+   ln_landfast_L16  = .false.         !  landfast: parameterization from Lemieux 2016
+      rn_lf_depfra  =   0.125         !        fraction of ocean depth that ice must reach to initiate landfast
+                                      !          recommended range: [0.1 ; 0.25]
+      rn_lf_bfr     =  15.            !        maximum bottom stress per unit volume [N/m3]
+      rn_lf_relax   =   1.e-5         !        relaxation time scale to reach static friction [s-1]
+      rn_lf_tensile =   0.05          !        isotropic tensile strength [0-0.5??]
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+          ! -- ice_rdgrft_strength -- !
+   ln_str_H79       = .true.          !  ice strength param.: Hibler_79   => P = pstar*<h>*exp(-c_rhg*A)                      
+      rn_pstar      =   2.0e+04       !     ice strength thickness parameter [N/m2]
+      rn_crhg       =   20.0          !     ice strength conc. parameter (-)
+                   ! -- ice_rdgrft -- !
+   rn_csrdg         =   0.5           !  fraction of shearing energy contributing to ridging
+              ! -- ice_rdgrft_prep -- !
+   ln_partf_lin     = .false.         !  Linear ridging participation function (Thorndike et al, 1975)
+      rn_gstar      =   0.15          !     fractional area of thin ice being ridged 
+   ln_partf_exp     = .true.          !  Exponential ridging participation function (Lipscomb, 2007)
+      rn_astar      =   0.03          !     exponential measure of ridging ice fraction [set to 0.05 if hstar=100]
+   ln_ridging       = .true.          !  ridging activated (T) or not (F)
+      rn_hstar      =  25.0           !     determines the maximum thickness of ridged ice [m] (Hibler, 1980)
+      rn_porordg    =   0.3           !     porosity of newly ridged ice (Lepparanta et al., 1995)
+      rn_fsnwrdg    =   0.5           !     snow volume fraction that survives in ridging
+      rn_fpndrdg    =   1.0           !     pond fraction that survives in ridging (small a priori)
+   ln_rafting       = .true.          !  rafting activated (T) or not (F)
+      rn_hraft      =   0.75          !     threshold thickness for rafting [m]
+      rn_craft      =   5.0           !     squeezing coefficient used in the rafting function
+      rn_fsnwrft    =   0.5           !     snow volume fraction that survives in rafting
+      rn_fpndrft    =   1.0           !     pond fraction that survives in rafting (0.5 a priori)
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+   ln_rhg_EVP       = .true.          !  EVP rheology
+      ln_aEVP       = .true.          !     adaptive rheology (Kimmritz et al. 2016 & 2017)
+      rn_creepl     =   2.0e-9        !     creep limit [1/s]
+      rn_ecc        =   2.0           !     eccentricity of the elliptical yield curve          
+      nn_nevp       = 100             !     number of EVP subcycles                             
+      rn_relast     =   0.333         !     ratio of elastic timescale to ice time step: Telast = dt_ice * rn_relast 
+                                      !        advised value: 1/3 (nn_nevp=100) or 1/9 (nn_nevp=300)
+   nn_rhg_chkcvg    =   0             !  check convergence of rheology
+                                      !     = 0  no check
+                                      !     = 1  check at the main time step (output xml: uice_cvg)
+                                      !     = 2  check at both main and rheology time steps (additional output: ice_cvg.nc)
+                                      !          this option 2 asks a lot of communications between cpu
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .true.          !  Advection scheme (Prather)
+   ln_adv_UMx       = .false.         !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+   rn_cio           =   5.0e-03       !  ice-ocean drag coefficient (-)
+   nn_snwfra        =   2             !  calculate the fraction of ice covered by snow (for zdf and albedo)
+                                      !     = 0  fraction = 1 (if snow) or 0 (if no snow)
+                                      !     = 1  fraction = 1-exp(-0.2*rhos*hsnw) [MetO formulation]
+                                      !     = 2  fraction = hsnw / (hsnw+0.02)    [CICE formulation]
+   rn_snwblow       =   0.66          !  mesure of snow blowing into the leads
+                                      !     = 1 => no snow blowing, < 1 => some snow blowing
+   nn_flxdist       =  -1             !  Redistribute heat flux over ice categories
+                                      !     =-1  Do nothing (needs N(cat) fluxes)
+                                      !     = 0  Average N(cat) fluxes then apply the average over the N(cat) ice
+                                      !     = 1  Average N(cat) fluxes then redistribute over the N(cat) ice using T-ice and albedo sensitivity
+                                      !     = 2  Redistribute a single flux over categories
+   ln_cndflx        = .false.         !  Use conduction flux as surface boundary conditions (i.e. for Jules coupling)
+      ln_cndemulate = .false.         !     emulate conduction flux (if not provided in the inputs)
+   nn_qtrice        =   1             !  Solar flux transmitted thru the surface scattering layer:
+                                      !     = 0  Grenfell and Maykut 1977 (depends on cloudiness and is 0 when there is snow) 
+                                      !     = 1  Lebrun 2019 (equals 0.3 anytime with different melting/dry snw conductivities)
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+   ln_icedH         = .true.          !  activate ice thickness change from growing/melting (T) or not (F)
+   ln_icedA         = .true.          !  activate lateral melting param. (T) or not (F)
+   ln_icedO         = .true.          !  activate ice growth in open-water (T) or not (F)
+   ln_icedS         = .true.          !  activate brine drainage (T) or not (F)
+   !
+   ln_leadhfx       = .true.          !  heat in the leads is used to melt sea-ice before warming the ocean
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+   ln_zdf_BL99      = .true.          !  Heat diffusion follows Bitz and Lipscomb 1999
+   ln_cndi_U64      = .false.         !  sea ice thermal conductivity: k = k0 + beta.S/T            (Untersteiner, 1964)
+   ln_cndi_P07      = .true.          !  sea ice thermal conductivity: k = k0 + beta1.S/T - beta2.T (Pringle et al., 2007)
+   rn_cnd_s         =   0.31          !  thermal conductivity of the snow (0.31 W/m/K, Maykut and Untersteiner, 1971)
+                                      !     Obs: 0.1-0.5 (Lecomte et al, JAMES 2013)
+   rn_kappa_i       =   1.0           !  radiation attenuation coefficient in sea ice                     [1/m]
+   rn_kappa_s       =  10.0           !  nn_qtrice = 0: radiation attenuation coefficient in snow         [1/m]
+   rn_kappa_smlt    =   7.0           !  nn_qtrice = 1: radiation attenuation coefficient in melting snow [1/m]
+   rn_kappa_sdry    =  10.0           !                 radiation attenuation coefficient in dry snow     [1/m]
+   ln_zdf_chkcvg    = .false.         !  check convergence of heat diffusion scheme (outputs: tice_cvgerr, tice_cvgstp)
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+   rn_beta          =   1.0           !  coef. beta for lateral melting param. Recommended range=[0.8-1.2]
+                                      !   => decrease = more melt and melt peaks toward higher concentration (A~0.5 for beta=1 ; A~0.8 for beta=0.2)
+                                      !      0.3 = best fit for western Fram Strait and Antarctica
+                                      !      1.4 = best fit for eastern Fram Strait      
+   rn_dmin          =   8.            !  minimum floe diameter for lateral melting param. Recommended range=[6-10]
+                                      !   => 6  vs 8m = +40% melting at the peak (A~0.5)
+                                      !      10 vs 8m = -20% melting
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+   rn_hinew         =   0.1           !  thickness for new ice formation in open water (m), must be larger than rn_himin
+   ln_frazil        = .false.         !  Frazil ice parameterization (ice collection as a function of wind)
+      rn_maxfraz    =   1.0           !     maximum fraction of frazil ice collecting at the ice base
+      rn_vfraz      =   0.417         !     thresold drift speed for frazil ice collecting at the ice bottom (m/s)
+      rn_Cfraz      =   5.0           !     squeezing coefficient for frazil ice collecting at the ice bottom
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+   nn_icesal        =   2             !  ice salinity option
+                                      !     1: constant ice salinity (S=rn_icesal)
+                                      !     2: varying salinity parameterization S(z,t)
+                                      !     3: prescribed salinity profile S(z) (Schwarzacher 1959)
+   rn_icesal        =   4.            !      (nn_icesal=1) ice salinity (g/kg)
+   rn_sal_gd        =   5.            !      (nn_icesal=2) restoring ice salinity, gravity drainage (g/kg)
+   rn_time_gd       =   1.73e+6       !      (nn_icesal=2) restoring time scale,   gravity drainage  (s)
+   rn_sal_fl        =   2.            !      (nn_icesal=2) restoring ice salinity, flushing (g/kg)
+   rn_time_fl       =   8.64e+5       !      (nn_icesal=2) restoring time scale,   flushing (s)
+   rn_simax         =  20.            !  maximum tolerated ice salinity (g/kg)
+   rn_simin         =   0.1           !  minimum tolerated ice salinity (g/kg)
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+   ln_pnd            = .true.         !  activate melt ponds or not
+      ln_pnd_LEV     = .true.         !  level ice melt ponds (from Flocco et al 2007,2010 & Holland et al 2012)
+         rn_apnd_min =   0.15         !     minimum ice fraction that contributes to melt pond. range: 0.0 -- 0.15 ??
+         rn_apnd_max =   0.85         !     maximum ice fraction that contributes to melt pond. range: 0.7 -- 0.85 ??
+      ln_pnd_CST     = .false.        !  constant  melt ponds
+         rn_apnd     =   0.2          !     prescribed pond fraction, at Tsu=0 degC
+         rn_hpnd     =   0.05         !     prescribed pond depth,    at Tsu=0 degC
+      ln_pnd_lids    = .true.         !  frozen lids on top of the ponds (only for ln_pnd_LEV)
+      ln_pnd_alb     = .true.         !  effect of melt ponds on ice albedo
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =   0             !     0 = Initialise sea ice based on SSTs
+                                      !     1 = Initialise sea ice from single category netcdf file
+                                      !     2 = Initialise sea ice from multi category restart file
+   rn_thres_sst     =   2.0           !  max temp. above Tfreeze with initial ice = (sst - tfreeze)
+   rn_hti_ini_n     =   3.0           !  initial ice thickness       (m), North
+   rn_hti_ini_s     =   1.0           !        "            "             South
+   rn_hts_ini_n     =   0.3           !  initial snow thickness      (m), North
+   rn_hts_ini_s     =   0.3           !        "            "             South
+   rn_ati_ini_n     =   0.9           !  initial ice concentration   (-), North
+   rn_ati_ini_s     =   0.9           !        "            "             South
+   rn_smi_ini_n     =   6.3           !  initial ice salinity     (g/kg), North
+   rn_smi_ini_s     =   6.3           !        "            "             South
+   rn_tmi_ini_n     = 270.            !  initial ice temperature     (K), North
+   rn_tmi_ini_s     = 270.            !        "            "             South
+   rn_tsu_ini_n     = 270.            !  initial surface temperature (K), North
+   rn_tsu_ini_s     = 270.            !        "            "             South
+   rn_tms_ini_n     = 270.            !  initial snw temperature     (K), North
+   rn_tms_ini_s     = 270.            !        "            "             South
+   rn_apd_ini_n     =   0.2           !  initial pond fraction       (-), North
+   rn_apd_ini_s     =   0.2           !        "            "             South
+   rn_hpd_ini_n     =   0.05          !  initial pond depth          (m), North
+   rn_hpd_ini_s     =   0.05          !        "            "             South
+   rn_hld_ini_n     =   0.0           !  initial pond lid depth      (m), North
+   rn_hld_ini_s     =   0.0           !        "            "             South
+   ! -- for nn_iceini_file = 1
+   sn_hti = 'Ice_initialization'    , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'Ice_initialization'    , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'Ice_initialization'    , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'Ice_initialization'    , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'Ice_initialization'    , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'Ice_initialization'    , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tms = 'NOT USED'              , -12 ,'tms'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   !      melt ponds (be careful, sn_apd is the pond concentration (not fraction), so it differs from rn_apd)
+   sn_apd = 'NOT USED'              , -12 ,'apd'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hpd = 'NOT USED'              , -12 ,'hpd'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hld = 'NOT USED'              , -12 ,'hld'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+   !                                  !                          !  obs range (cloud-sky)
+   rn_alb_sdry      =   0.85          !  dry snow albedo         :  0.85 -- 0.87
+   rn_alb_smlt      =   0.75          !  melting snow albedo     :  0.72 -- 0.82
+   rn_alb_idry      =   0.60          !  dry ice albedo          :  0.54 -- 0.65
+   rn_alb_imlt      =   0.50          !  bare puddled ice albedo :  0.49 -- 0.58
+   rn_alb_dpnd      =   0.27          !  ponded ice albedo       :  0.10 -- 0.30 
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+   ln_icediachk     = .false.         !  check online heat, mass & salt budgets
+      !                               !   rate of ice spuriously gained/lost at each time step => rn_icechk=1 <=> 1.e-6 m/hour
+      rn_icechk_cel =  100.           !     check at each gridcell          (1.e-4m/h)=> stops the code if violated (and writes a file)
+      rn_icechk_glo =  1.             !     check over the entire ice cover (1.e-6m/h)=> only prints warnings
+   ln_icediahsb     = .false.         !  output the heat, mass & salt budgets (T) or not (F)
+   ln_icectl        = .false.         !  ice points output for debug (T or F)
+      iiceprt       =  10             !     i-index for debug
+      jiceprt       =  10             !     j-index for debug
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_pisces_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_pisces_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_pisces_ref	(revision 14097)
@@ -0,0 +1,525 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! PISCES reference namelist 
+!!              1  - air-sea exchange                         (nampisext)
+!!              2  - biological parameters                    (nampisbio)
+!!              3  - parameters for nutrient limitations      (nampislim)    
+!!              4  - parameters for phytoplankton             (nampisprod,nampismort)
+!!              5  - parameters for zooplankton               (nampismes,nampiszoo)
+!!              6  - parameters for remineralization          (nampisrem)
+!!              7  - parameters for calcite chemistry         (nampiscal)
+!!              8  - parameters for inputs deposition         (nampissed)
+!!              11 - Damping                                  (nampisdmp)
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+  ln_p2z    = .false.        !  LOBSTER model used
+  ln_p4z    = .true.         !  PISCES model used
+  ln_p5z    = .false.        !  PISCES QUOTA model used
+  ln_ligand = .false.        !  Enable  organic ligands
+  ln_sediment = .false.      !  Enable sediment module
+/
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+   ln_co2int  =  .false. ! read atm pco2 from a file (T) or constant (F)
+   atcco2     =  280.    ! Constant value atmospheric pCO2 - ln_co2int = F
+   clname     =  'atcco2.txt'  ! Name of atm pCO2 file - ln_co2int = T
+   nn_offset  =  0       ! Offset model-data start year - ln_co2int = T
+!                        ! If your model year is iyy, nn_offset=(years(1)-iyy) 
+!                        ! then the first atmospheric CO2 record read is at years(1)
+/
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+!              !  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_patm     = 'presatm'    ,     -1.           , 'patm'    ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   sn_atmco2   = 'presatmco2' ,     -1.           , 'xco2'    ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   cn_dir      = './'     !  root directory for the location of the dynamical files
+!
+   ln_presatm    = .false.   ! constant atmopsheric pressure (F) or from a file (T)
+   ln_presatmco2 = .false.   ! Read spatialized atm co2 files [ppm] if TRUE
+/
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+   nrdttrc    =  1        ! time step frequency for biology
+   wsbio      =  2.       ! POC sinking speed
+   xkmort     =  2.E-7    ! half saturation constant for mortality
+   ferat3     =  10.E-6   ! Fe/C in zooplankton 
+   wsbio2     =  50.      ! Big particles sinking speed
+   wsbio2max  =  50.      ! Big particles maximum sinking speed
+   wsbio2scale =  5000.    ! Big particles length scale of sinking
+!                         !  ln_ligand enabled
+   ldocp      =  1.E-4    ! Phyto ligand production per unit doc 
+   ldocz      =  1.E-4    ! Zoo ligand production per unit doc 
+   lthet      =  1.0      ! Proportional loss of ligands due to Fe uptake 
+!                         !  ln_p5z enabled
+   no3rat3    =  0.182    ! N/C ratio in zooplankton
+   po4rat3    =  0.0094   ! P/C ratio in zooplankton
+/
+!-----------------------------------------------------------------------
+&namp4zlim     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+   concnno3   =  1.e-6    ! Nitrate half saturation of nanophytoplankton
+   concdno3   =  3.E-6    ! Nitrate half saturation for diatoms
+   concnnh4   =  1.E-7    ! NH4 half saturation for phyto
+   concdnh4   =  3.E-7    ! NH4 half saturation for diatoms
+   concnfer   =  1.E-9    ! Iron half saturation for phyto
+   concdfer   =  3.E-9    ! Iron half saturation for diatoms
+   concbfe    =  1.E-11   ! Iron half-saturation for DOC remin.
+   concbnh4   =  2.E-8    ! NH4 half saturation for DOC remin.
+   concbno3   =  2.E-7    ! Nitrate half saturation for DOC remin.
+   xsizedia   =  1.E-6    ! Minimum size criteria for diatoms
+   xsizephy   =  1.E-6    ! Minimum size criteria for phyto
+   xsizern    =  3.0      ! Size ratio for nanophytoplankton
+   xsizerd    =  3.0      ! Size ratio for diatoms
+   xksi1      =  2.E-6    ! half saturation constant for Si uptake
+   xksi2      =  20E-6    ! half saturation constant for Si/C
+   xkdoc      =  417.E-6  ! half-saturation constant of DOC remineralization
+   qnfelim    =  7.E-6    ! Optimal quota of phyto
+   qdfelim    =  7.E-6    ! Optimal quota of diatoms
+   caco3r     =  0.3      ! mean rain ratio
+   oxymin     =  1.E-6    ! Half-saturation constant for anoxia
+/
+!-----------------------------------------------------------------------
+&namp5zlim     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+   concnno3   =  3e-6     ! Nitrate half saturation of nanophytoplankton
+   concpno3   =  1e-6
+   concdno3   =  4E-6     ! Phosphate half saturation for diatoms
+   concnnh4   =  1.5E-6   ! NH4 half saturation for phyto
+   concpnh4   =  4E-7
+   concdnh4   =  2E-6     ! NH4 half saturation for diatoms
+   concnpo4   =  3E-6     ! PO4 half saturation for phyto
+   concppo4   =  1.5E-6
+   concdpo4   =  4E-6     ! PO4 half saturation for diatoms
+   concnfer   =  3E-9   ! Iron half saturation for phyto
+   concpfer   =  1.5E-9
+   concdfer   =  4E-9   ! Iron half saturation for diatoms
+   concbfe    =  1.E-11   ! Half-saturation for Fe limitation of Bacteria
+   concbnh4   =  1.E-7    ! NH4 half saturation for phyto
+   concbno3   =  5.E-7    ! Phosphate half saturation for diatoms
+   concbpo4   =  1E-7     ! Phosphate half saturation for bacteria
+   xsizedia   =  1.E-6    ! Minimum size criteria for diatoms
+   xsizephy   =  1.E-6    ! Minimum size criteria for phyto
+   xsizepic   =  1.E-6
+   xsizern    =  1.0      ! Size ratio for nanophytoplankton
+   xsizerp    =  1.0
+   xsizerd    =  4.0      ! Size ratio for diatoms
+   xksi1      =  2.E-6    ! half saturation constant for Si uptake
+   xksi2      =  20E-6  ! half saturation constant for Si/C
+   xkdoc      =  417.E-6  ! half-saturation constant of DOC remineralization
+   caco3r     =  0.35     ! mean rain ratio
+   oxymin     =  1.E-6    ! Half-saturation constant for anoxia
+/
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+   qfnopt     =  7.E-6    ! Optimal Fe quota of nanophyto
+   qfpopt     =  7.E-6    ! Optimal Fe quota of picophyto
+   qfdopt     =  7.E-6    ! Optimal quota of diatoms
+   qnnmin     =  0.29     ! Minimal N quota for nano
+   qnnmax     =  1.39     ! Maximal N quota for nano
+   qpnmin     =  0.28     ! Minimal P quota for nano
+   qpnmax     =  1.06     ! Maximal P quota for nano
+   qnpmin     =  0.42     ! Minimal N quota for pico
+   qnpmax     =  1.39     ! Maximal N quota for pico
+   qppmin     =  0.25     ! Minimal P quota for pico
+   qppmax     =  0.7      ! Maximal P quota for pico
+   qndmin     =  0.25     ! Minimal N quota for diatoms
+   qndmax     =  1.39     ! Maximal N quota for diatoms
+   qpdmin     =  0.29     ! Minimal P quota for diatoms
+   qpdmax     =  1.32     ! Maximal P quota for diatoms
+   qfnmax     =  40E-6    ! Maximal Fe quota for nano
+   qfpmax     =  40E-6    ! Maximal Fe quota for pico
+   qfdmax     =  40E-6    ! Maximal Fe quota for diatoms
+/
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+!              !  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_par      = 'par.orca'       ,     24.           , 'fr_par'  ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   cn_dir      = './'      !  root directory for the location of the dynamical files
+   ln_varpar   =  .true.   ! boolean for PAR variable
+   parlux      =  0.43      ! Fraction of shortwave as PAR
+/ 
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+   pislopen   =  2.       ! P-I slope
+   pisloped   =  2.       ! P-I slope  for diatoms
+   xadap      =  0.       ! Adaptation factor to low light
+   excretn    =  0.05     ! excretion ratio of phytoplankton
+   excretd    =  0.05     ! excretion ratio of diatoms
+   bresp      =  0.033    ! Basal respiration rate
+   chlcnm     =  0.033    ! Maximum Chl/C in nanophytoplankton
+   chlcdm     =  0.05     ! Maximum Chl/C in diatoms
+   chlcmin    =  0.004    ! Minimum Chl/c in phytoplankton
+   fecnm      =  40E-6    ! Maximum Fe/C in nanophytoplankton
+   fecdm      =  40E-6    ! Maximum Fe/C in diatoms
+   grosip     =  0.159    ! mean Si/C ratio
+/
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+   pislopen   =  3.       ! P-I slope
+   pislopep   =  3.       ! P-I slope for picophytoplankton
+   pisloped   =  3.       ! P-I slope  for diatoms
+   excretn    =  0.05     ! excretion ratio of phytoplankton
+   excretp    =  0.05     ! excretion ratio of picophytoplankton
+   excretd    =  0.05     ! excretion ratio of diatoms
+   xadap      =  0.       ! Adaptation factor to low light
+   bresp      =  0.02     ! Basal respiration rate
+   thetannm   =  0.25     ! Maximum Chl/N in nanophytoplankton
+   thetanpm   =  0.25     ! Maximum Chl/N in picophytoplankton
+   thetandm   =  0.3      ! Maximum Chl/N in diatoms
+   chlcmin    =  0.004    ! Minimum Chl/c in phytoplankton
+   grosip     =  0.131    ! mean Si/C ratio
+/
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+   wchl       =  0.01     ! quadratic mortality of phytoplankton
+   wchld      =  0.01     ! maximum quadratic mortality of diatoms
+   wchldm     =  0.03     ! maximum quadratic mortality of diatoms
+   mprat      =  0.01     ! phytoplankton mortality rate
+   mprat2     =  0.01     ! Diatoms mortality rate
+/
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+   wchln      =  0.01     ! quadratic mortality of nanophytoplankton
+   wchlp      =  0.01     ! quadratic mortality of picophytoplankton
+   wchld      =  0.01     ! maximum quadratic mortality of diatoms
+   wchldm     =  0.02     ! maximum quadratic mortality of diatoms
+   mpratn     =  0.01     ! nanophytoplankton mortality rate
+   mpratp     =  0.01     ! picophytoplankton mortality rate
+   mpratd     =  0.01     ! Diatoms mortality rate
+/
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+   part2      =  0.75     ! part of calcite not dissolved in mesozoo guts
+   grazrat2   =  0.75     ! maximal mesozoo grazing rate
+   resrat2    =  0.005    ! exsudation rate of mesozooplankton
+   mzrat2     =  0.03     ! mesozooplankton mortality rate
+   xpref2d    =  1.       ! mesozoo preference for diatoms
+   xpref2n    =  0.3      ! mesozoo preference for nanophyto.
+   xpref2z    =  1.       ! mesozoo preference for microzoo.
+   xpref2c    =  0.3      ! mesozoo preference for poc
+   xthresh2zoo = 1E-8     ! zoo feeding threshold for mesozooplankton 
+   xthresh2dia = 1E-8     ! diatoms feeding threshold for mesozooplankton 
+   xthresh2phy = 1E-8     ! nanophyto feeding threshold for mesozooplankton 
+   xthresh2poc = 1E-8     ! poc feeding threshold for mesozooplankton 
+   xthresh2   =  3E-7     ! Food threshold for grazing
+   xkgraz2    =  20.E-6   ! half saturation constant for meso grazing
+   epsher2    =  0.35     ! Efficicency of Mesozoo growth
+   epsher2min =  0.35     ! Minimum efficiency of mesozoo growth
+   sigma2     =  0.6      ! Fraction of mesozoo excretion as DOM
+   unass2     =  0.3      ! non assimilated fraction of P by mesozoo
+   grazflux   =  3.e3     ! flux-feeding rate
+/
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+   part2      =  0.75     ! part of calcite not dissolved in mesozoo guts
+   grazrat2   =  0.85     ! maximal mesozoo grazing rate
+   bmetexc2   =  .true.   ! Metabolic use of excess carbon 
+   resrat2    =  0.005    ! exsudation rate of mesozooplankton
+   mzrat2     =  0.02     ! mesozooplankton mortality rate
+   xpref2d    =  1.       ! zoo preference for Diatoms
+   xpref2n    =  1.       ! zoo preference for nanophyto
+   xpref2z    =  1.       ! zoo preference for zoo
+   xpref2m    =  0.2      ! zoo preference for mesozoo
+   xpref2c    =  0.3      ! zoo preference for POC
+   xthresh2zoo = 1E-8     ! zoo feeding threshold for mesozooplankton
+   xthresh2dia = 1E-8     ! diatoms feeding threshold for mesozooplankton
+   xthresh2phy = 1E-8     ! nanophyto feeding threshold for mesozooplankton
+   xthresh2mes = 1E-8     ! meso feeding threshold for mesozooplankton
+   xthresh2poc = 1E-8     ! poc feeding threshold for mesozooplankton
+   xthresh2    =  3E-7     ! Food threshold for grazing
+   xkgraz2     =  20.E-6   ! half sturation constant for meso grazing
+   epsher2     =  0.5      ! Efficicency of Mesozoo growth
+   epsher2min  =  0.2     ! Minimum efficiency of mesozoo growth
+   ssigma2     =  0.5     ! Fraction excreted as semi-labile DOM
+   srespir2    =  0.2     ! Active respiration
+   unass2c     =  0.3     ! non assimilated fraction of P by mesozoo
+   unass2n     =  0.3     ! non assimilated fraction of N by mesozoo
+   unass2p     =  0.3     ! non assimilated fraction of P by mesozoo
+   grazflux   =  3.e3     ! flux-feeding rate
+/
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+   part       =  0.5      ! part of calcite not dissolved in microzoo guts
+   grazrat    =  3.0      ! maximal zoo grazing rate
+   resrat     =  0.03     ! exsudation rate of zooplankton
+   mzrat      =  0.004    ! zooplankton mortality rate
+   xprefc     =  0.1      ! Microzoo preference for POM
+   xprefn     =  1.       ! Microzoo preference for Nanophyto
+   xprefd     =  0.6      ! Microzoo preference for Diatoms
+   xthreshdia =  1.E-8    ! Diatoms feeding threshold for microzooplankton 
+   xthreshphy =  1.E-8    ! Nanophyto feeding threshold for microzooplankton 
+   xthreshpoc =  1.E-8    ! POC feeding threshold for microzooplankton 
+   xthresh    =  3.E-7    ! Food threshold for feeding
+   xkgraz     =  20.E-6   ! half sturation constant for grazing
+   epsher     =  0.3      ! Efficiency of microzoo growth
+   epshermin  =  0.3      ! Minimum efficiency of microzoo growth
+   sigma1     =  0.6      ! Fraction of microzoo excretion as DOM
+   unass      =  0.3      ! non assimilated fraction of phyto by zoo
+/
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+   part       =  0.5      ! part of calcite not dissolved in microzoo gutsa
+   grazrat    =  2.75     ! maximal zoo grazing rate
+   bmetexc    =  .true.   ! Metabolic use of excess carbon
+   resrat     =  0.03     ! exsudation rate of zooplankton
+   mzrat      =  0.005    ! zooplankton mortality rate
+   xprefc     =  0.1      ! Microzoo preference for POM
+   xprefn     =  1.       ! Microzoo preference for Nanophyto
+   xprefp     =  1.6      ! Microzoo preference for picophyto
+   xprefd     =  1.0      ! Microzoo preference for Diatoms
+   xprefz     =  0.3      ! Microzoo preference for microzooplankton
+   xthreshdia =  1.E-8    ! Diatoms feeding threshold for microzooplankton
+   xthreshphy =  1.E-8    ! Nanophyto feeding threshold for microzooplankton
+   xthreshpic =  1.E-8
+   xthreshzoo =  1.E-8    ! Nanophyto feeding threshold for microzooplankton
+   xthreshpoc =  1.E-8    ! POC feeding threshold for microzooplankton
+   xthresh    =  3.E-7    ! Food threshold for feeding
+   xkgraz     =  20.E-6   ! half sturation constant for grazing
+   epsher     =  0.5      ! Efficiency of microzoo growth
+   epshermin  =  0.2      ! Minimum efficiency of microzoo growth
+   ssigma     =  0.5      ! Fraction excreted as semi-labile DOM
+   srespir    =  0.2      ! Active respiration
+   unassc     =  0.3      ! non assimilated fraction of C by zoo
+   unassn     =  0.3      ! non assimilated fraction of C by zoo
+   unassp     =  0.3      ! non assimilated fraction of C by zoo
+/
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+   ln_ligvar =  .false.    ! variable ligand concentration
+   xlam1     =  0.005     ! scavenging rate of Iron
+   xlamdust  =  150.0     ! Scavenging rate of dust
+   ligand    =  0.7E-9    ! Ligands concentration 
+   kfep      =  0.01      ! Nanoparticle formation rate constant
+/
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+   xremik    =  0.3       ! remineralization rate of DOC
+   nitrif    =  0.05      ! NH4 nitrification rate
+   xsirem    =  0.003     ! remineralization rate of Si
+   xsiremlab =  0.03      ! fast remineralization rate of Si
+   xsilab    =  0.5       ! Fraction of labile biogenic silica
+   feratb    =  10.E-6    ! Fe/C quota in bacteria
+   xkferb    =  3E-10     ! Half-saturation constant for bacteria Fe/C
+!                         ! ln_p5z
+   xremikc   =  0.25      ! remineralization rate of DOC
+   xremikn   =  0.35      ! remineralization rate of DON
+   xremikp   =  0.4       ! remineralization rate of DOP
+!   feratb    =  20E-6     ! Bacterial Fe/C ratio
+!   xkferb    =  3E-10     ! Half-saturation constant for bact. Fe/C
+/
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+   xremip    =  0.035     ! remineralisation rate of PON
+   jcpoc     =  15        ! Number of lability classes
+   rshape    =  1.0       ! Shape of the gamma function
+!                         ! ln_p5z
+   xremipc   =  0.02      ! remineralisation rate of POC
+   xremipn   =  0.025     ! remineralisation rate of PON
+   xremipp   =  0.03      ! remineralisation rate of POP
+/
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+   kdca       =  6.       ! calcite dissolution rate constant (1/time)
+   nca        =  1.       ! order of dissolution reaction (dimensionless)
+/
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+!              !  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_dust     = 'dust.orca'       ,     -1.           , 'dust'        ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_solub    = 'solubility.orca' ,    -12.           , 'solubility1' ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdic = 'river.orca'      ,    120.           , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdoc = 'river.orca'      ,    120.           , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdin = 'river.orca'      ,    120.           , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdon = 'river.orca'      ,    120.           , 'riverdon'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdip = 'river.orca'      ,    120.           , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdop = 'river.orca'      ,    120.           , 'riverdop'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdsi = 'river.orca'      ,    120.           , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_ndepo    = 'ndeposition.orca',    -12.           , 'ndep'        ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_ironsed  = 'bathy.orca'      ,    -12.           , 'bathy'       ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_hydrofe  = 'hydrofe.orca'    ,    -12.           , 'epsdb'       ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+!
+   cn_dir      = './'      !  root directory for the location of the dynamical files
+   ln_dust     =  .true.   ! boolean for dust input from the atmosphere
+   ln_solub    =  .true.   ! boolean for variable solubility of atm. Iron
+   ln_river    =  .true.   ! boolean for river input of nutrients
+   ln_ndepo    =  .true.   ! boolean for atmospheric deposition of N
+   ln_ironsed  =  .true.   ! boolean for Fe input from sediments
+   ln_ironice  =  .true.   ! boolean for Fe input from sea ice
+   ln_hydrofe  =  .true.   ! boolean for from hydrothermal vents
+   sedfeinput  =  2.e-9    ! Coastal release of Iron
+   distcoast   =  5.e3     ! Distance off the coast for Iron from sediments
+   dustsolub   =  0.02     ! Solubility of the dusta
+   mfrac       =  0.035    ! Fe mineral fraction of dust
+   wdust       =  2.0      ! Dust sinking speed 
+   icefeinput  =  15.e-9   ! Iron concentration in sea ice
+   nitrfix     =  1.e-7    ! Nitrogen fixation rate
+   diazolight  =  50.      ! Diazotrophs sensitivity to light (W/m2)
+   concfediaz  =  1.e-10   ! Diazotrophs half-saturation Cste for Iron
+   hratio      =  1.e+7    ! Fe to 3He ratio assumed for vent iron supply 
+!                          ! ln_ligand
+   lgw_rath    =  0.5      ! Weak ligand ratio from sed hydro sources 
+/
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+   rlgw        =  100.     ! Lifetime (years) of weak ligands
+   rlig        =  1.E-4    ! Remin ligand production per unit C
+   prlgw       =  1.E-4    ! Photolysis of weak ligand
+   rlgs        =  1.       ! Lifetime (years) of strong ligands
+/
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+!========================================================================
+! constant ocean tracer concentrations are defined in trcice_pisces.F90 
+!                               (Global, Arctic, Antarctic and Baltic)
+! trc_ice_ratio  : >=0 & <=1 => prescribed ice/ocean tracer concentration ratio
+!                :  = -1     => the ice-ocean tracer concentration ratio
+!                               follows the ice-ocean salinity ratio
+!                :  = -2     => tracer concentration in sea ice is prescribed
+!                               and trc_ice_prescr is used
+! trc_ice_prescr : prescribed tracer concentration. used only if 
+!                  trc_ice_ratio = -2. equals -99 if not used.
+! cn_trc_o       :  = 'GL'   => use global ocean values making the Baltic 
+!                               distinction only
+!                :  = 'AA'   => use specific Arctic/Antarctic/Baltic values
+!========================================================================
+!    sn_tri_ ! trc_ice_ratio ! trc_ice_prescr !     cn_trc_o
+   sn_tri_dic =           -1.,           -99.,          'AA'
+   sn_tri_doc =            0.,           -99.,          'AA'
+   sn_tri_tal =           -1.,           -99.,          'AA'
+   sn_tri_oxy =           -1.,           -99.,          'AA'
+   sn_tri_cal =            0.,           -99.,          'AA'
+   sn_tri_po4 =           -1.,           -99.,          'AA'
+   sn_tri_poc =            0.,           -99.,          'AA'
+   sn_tri_goc =            0.,           -99.,          'AA'
+   sn_tri_bfe =            0.,           -99.,          'AA'
+   sn_tri_num =            0.,           -99.,          'AA'
+   sn_tri_sil =           -1.,           -99.,          'AA'
+   sn_tri_dsi =            0.,           -99.,          'AA'
+   sn_tri_gsi =            0.,           -99.,          'AA'
+   sn_tri_phy =            0.,           -99.,          'AA'
+   sn_tri_dia =            0.,           -99.,          'AA'
+   sn_tri_zoo =            0.,           -99.,          'AA'
+   sn_tri_mes =            0.,           -99.,          'AA'
+   sn_tri_fer =           -2.,          15E-9,          'AA'
+   sn_tri_sfe =            0.,           -99.,          'AA'
+   sn_tri_dfe =            0.,           -99.,          'AA'
+   sn_tri_nfe =            0.,           -99.,          'AA'
+   sn_tri_nch =            0.,           -99.,          'AA'
+   sn_tri_dch =            0.,           -99.,          'AA'
+   sn_tri_no3 =           -1.,           -99.,          'AA'
+   sn_tri_nh4 =            1.,           -99.,          'AA'
+/
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+   ln_pisdmp    =  .true.     !  Relaxation for some tracers to a mean value
+   nn_pisdmp    =  5475       !  Frequency of Relaxation 
+/
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+   ln_check_mass =  .false.    !  Check mass conservation
+/
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! PISCES reduced (key_pisces_reduced, ex LOBSTER) : namelists
+!!              1  - biological parameters for phytoplankton    (namlobphy)
+!!              2  - biological parameters for nutrients        (namlobnut)
+!!              3  - biological parameters for zooplankton      (namlobzoo)    
+!!              4  - biological parameters for detritus         (namlobdet)
+!!              5  - biological parameters for DOM              (namlobdom)
+!!              6  - parameters from aphotic layers to sediment (namlobsed)
+!!              7  - general coefficients                       (namlobrat)
+!!              8  - optical parameters                         (namlobopt)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+   tmumax  =  1.21e-5   ! maximal phytoplankton growth rate            [s-1] 
+   rgamma  =  0.05      ! phytoplankton exudation fraction             [%]
+   fphylab =  0.75      ! NH4 fraction of phytoplankton exsudation     
+   tmminp  =  5.8e-7    ! minimal phytoplancton mortality rate         [0.05/86400 s-1=20 days] 
+   aki     =  33.       ! light photosynthesis half saturation constant[W/m2]
+/
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+   akno3   =  0.7       ! nitrate limitation half-saturation value     [mmol/m3]
+   aknh4   =  0.001     ! ammonium limitation half-saturation value    [mmol/m3]
+   taunn   =  5.80e-7   ! nitrification rate                           [s-1]  
+   psinut  =  3.        ! inhibition of nitrate uptake by ammonium
+/
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+   rppz    = 0.8        ! zooplankton nominal preference for phytoplancton food  [%]
+   taus    = 9.26E-6    ! specific zooplankton maximal grazing rate              [s-1] 
+!                       ! 0.75/86400 s-1=8.680555E-6    1/86400 = 1.15e-5
+   aks     = 1.         ! half-saturation constant for total zooplankton grazing [mmolN.m-3]
+   rpnaz   = 0.3        ! non-assimilated phytoplankton by zooplancton           [%]
+   rdnaz   = 0.3        ! non-assimilated detritus by zooplankton                [%] 
+   tauzn   = 8.1e-7     ! zooplancton specific excretion rate                    [0.1/86400 s-1=10 days] 
+   fzoolab = 0.5        ! NH4 fraction of zooplankton excretion
+   fdbod   = 0.5        ! zooplankton mortality fraction that goes to detritus
+   tmminz  = 2.31e-6    ! minimal zooplankton mortality rate                     [(mmolN/m3)-1 d-1]
+/
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+   taudn   = 5.80e-7    ! detritus breakdown rate                        [0.1/86400 s-1=10 days]
+   fdetlab = 0.         ! NH4 fraction of detritus dissolution           
+/
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+   taudomn = 6.43e-8    ! DOM breakdown rate                             [s-1] 
+!                       ! slow remineralization rate of semi-labile dom to nh4 (1 month)
+/
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+   sedlam     = 3.86e-7    ! time coefficient of POC remineralization in sediments [s-1]
+   sedlostpoc = 0.         ! mass of POC lost in sediments
+   vsed       = 3.47e-5    ! detritus sedimentation speed                   [m/s]
+   xhr        = -0.858     ! coeff for martin''s remineralisation profile
+/
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+   rcchl   = 60.       ! Carbone/Chlorophyl ratio                     [mgC.mgChla-1]
+   redf    = 6.56       ! redfield ratio (C:N) for phyto
+   reddom  = 6.56       ! redfield ratio (C:N) for DOM
+/
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+   xkg0   = 0.0232     ! green absorption coefficient of water
+   xkr0   = 0.225      ! red absorption coefficent of water
+   xkgp   = 0.074      ! green absorption coefficient of chl
+   xkrp   = 0.037      ! red absorption coefficient of chl
+   xlg    = 0.674      ! green chl exposant for absorption
+   xlr    = 0.629      ! red chl exposant for absorption
+   rpig   = 0.7        ! chla/chla+pheo ratio
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_ref	(revision 14097)
@@ -0,0 +1,1380 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE :   Reference namelist_ref                                !!
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  :  1 - Domain & run manager (namrun, namcfg, namdom, namtsd, namcrs, namc1d, namc1d_uvd)
+!! namelists    2 - Surface boundary (namsbc, namsbc_flx, namsbc_blk, namsbc_cpl,
+!!                                    namsbc_sas, namtra_qsr, namsbc_rnf,
+!!                                    namsbc_isf, namsbc_iscpl, namsbc_apr, 
+!!                                    namsbc_ssr, namsbc_wave, namberg)
+!!              3 - lateral boundary (namlbc, namagrif, nambdy, nambdy_tide)
+!!              4 - top/bot boundary (namdrg, namdrg_top, namdrg_bot, nambbc, nambbl)
+!!              5 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_eiv, namtra_dmp)
+!!              6 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
+!!              7 - Vertical physics (namzdf, namzdf_ric, namzdf_tke, namzdf_gls, namzdf_iwm)
+!!              8 - diagnostics      (namnc4, namtrd, namspr, namflo, namhsb)
+!!              9 - Obs & Assim      (namobs, nam_asminc)
+!!             10 - miscellaneous    (nammpp, namctl, namsto)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  Assimilation cycle index
+   cn_exp      =  "ORCA2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    5840   !  last  time step (std 5840)
+   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 hhmm
+   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=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_indir = "."         !  directory from which to read input ocean restarts
+      cn_ocerst_out   = "restart"   !  suffix of ocean restart name (output)
+      cn_ocerst_outdir = "."        !  directory in which to write output ocean restarts
+   ln_iscpl    = .false.   !  cavity evolution forcing or coupling to ice sheet model
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   ln_rst_list = .false.   !  output restarts at list of times using nn_stocklist (T) or at set frequency with nn_stock (F)
+   nn_stock    =       0   !  used only if ln_rst_list = F: output restart freqeuncy (modulo referenced to 1)
+      !                          !    =  0 force to write restart files only at the end of the run
+      !                          !    = -1 do not do any restart
+   nn_stocklist = 0,0,0,0,0,0,0,0,0,0 ! List of timesteps when a restart file is to be written
+   nn_write    =       0   !  used only if key_iomput is not defined: output frequency (modulo referenced to nn_it000)
+      !                          !    =  0 force to write output files only at the end of the run
+      !                          !    = -1 do not do any output file
+   ln_mskland  = .false.   !  mask land points in NetCDF outputs
+   ln_cfmeta   = .false.   !  output additional data to netCDF files required for compliance with the CF metadata standard
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+   nn_chunksz  =       0   !  chunksize (bytes) for NetCDF file (works only with iom_nf90 routines)
+   ln_xios_read = .FALSE.  !  use XIOS to read restart file (only for a single file restart)
+   nn_wxios = 0      !  use XIOS to write restart file 0 - no, 1 - single file output, 2 - multiple file output
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_isfhmin  =    1.00   !  treshold [m] to discriminate grounding ice from floating ice
+   !
+   rn_rdt      = 5400.     !  time step for the dynamics and tracer
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module      (T => fill namcrs)
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration           (F => create/check namusr_def)
+      cn_domcfg = "domain_cfg"  ! domain configuration filename
+      !
+      ln_closea    = .false.    !  T => keep closed seas (defined by closea_mask field) in the  
+      !                         !       domain and apply special treatment of freshwater fluxes.
+      !                         !  F => suppress closed seas (defined by closea_mask field) 
+      !                         !       from the bathymetry at runtime.
+      !                         !  If closea_mask field doesn't exist in the domain_cfg file
+      !                         !       then this logical does nothing.
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+      cn_domcfg_out = "domain_cfg_out" ! newly created domain configuration filename
+      !
+   ln_use_jattr = .false.  !  use (T) the file attribute: open_ocean_jstart, if present
+   !                       !  in netcdf input files, as the start j-row for reading
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .false.         !  ocean initialisation
+   ln_tsd_dmp  = .false.         !  T-S restoring   (see namtra_dmp)
+   
+   cn_dir      = './'      !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''            ,    ''    ,    ''
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+   ln_wd_il    = .false.   !  T/F activation of iterative   limiter
+   ln_wd_dl    = .false.   !  T/F activation of directional limiter
+   ln_wd_dl_bc = .false.   !  T/F Directional limiteer Baroclinic option
+   ln_wd_dl_rmp = .false.  !  T/F Turn on directional limiter ramp
+   rn_wdmin0   =  0.30     !  depth at which WaD starts
+   rn_wdmin1   =  0.2      !  Minimum wet depth on dried cells
+   rn_wdmin2   =  0.0001   !  Tolerance of min wet depth on dried cells
+   rn_wdld     =  2.5      !  Land elevation below which WaD is allowed
+   nn_wdit     =   20      !  Max iterations for WaD limiter
+   rn_wd_sbcdep =  5.0     !  Depth at which to taper sbc fluxes
+   rn_wd_sbcfra =  0.999   !  Fraction of SBC fluxes at taper depth (Must be <1)
+/
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+   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.
+   ln_msh_crs  = .false.   ! =T create a mesh & mask file
+   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 )
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+   rn_lat1d    =      50   !  Column latitude
+   rn_lon1d    =    -145   !  Column longitude
+   ln_c1d_locpt =  .true.   ! Localization of 1D config in a grid (T) or independant point (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   !                       !  =T read U-V fields for:
+   ln_uvd_init   = .false.       !  ocean initialisation
+   ln_uvd_dyndmp = .false.       !  U-V restoring
+
+   cn_dir      = './'      !  root directory for the U-V data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ucur     = 'ucurrent'              ,         -1.       ,'u_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Ume'   , ''
+   sn_vcur     = 'vcurrent'              ,         -1.       ,'v_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Vme'   , ''
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 2         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_usr      = .false.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_flx      = .false.   !  flux formulation                          (T => fill namsbc_flx )
+   ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+      !              ! Type of coupling (Ocean/Ice/Atmosphere) :
+   ln_cpl      = .false.   !  atmosphere coupled   formulation          ( requires key_oasis3 )
+   ln_mixcpl   = .false.   !  forced-coupled mixed formulation          ( requires key_oasis3 )
+   nn_components = 0       !  configuration of the opa-sas OASIS coupling
+      !                    !  =0 no opa-sas OASIS coupling: default single executable config.
+      !                    !  =1 opa-sas OASIS coupling: multi executable config., OPA component
+      !                    !  =2 opa-sas OASIS coupling: multi executable config., SAS component 
+                     ! Sea-ice :
+   nn_ice      = 0         !  =0 no ice boundary condition    
+      !                    !  =1 use observed ice-cover                 (  => fill namsbc_iif )
+      !                    !  =2 or 3 automatically for SI3 or CICE    ("key_si3" or "key_cice")
+      !                    !          except in AGRIF zoom where it has to be specified
+   ln_ice_embd = .false.   !  =T embedded sea-ice (pressure + mass and salt exchanges)
+      !                    !  =F levitating ice (no pressure, mass and salt exchanges)
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_dm2dc    = .false.   !  daily mean to diurnal cycle on short wave
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   nn_fwb      = 0         !  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_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
+   ln_isf      = .false.   !  ice shelf                                 (T   => fill namsbc_isf & namsbc_iscpl)
+   ln_wave     = .false.   !  Activate coupling with wave  (T => fill namsbc_wave)
+   ln_cdgw     = .false.   !  Neutral drag coefficient read from wave model (T => ln_wave=.true. & fill namsbc_wave)
+   ln_sdw      = .false.   !  Read 2D Surf Stokes Drift & Computation of 3D stokes drift (T => ln_wave=.true. & fill namsbc_wave) 
+   nn_sdrift   =  0        !  Parameterization for the calculation of 3D-Stokes drift from the surface Stokes drift
+      !                    !   = 0 Breivik 2015 parameterization: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
+      !                    !   = 1 Phillips:                      v_z=v_o*[exp(2*k*z)-beta*sqrt(-2*k*pi*z)*erfc(sqrt(-2*k*z))]
+      !                    !   = 2 Phillips as (1) but using the wave frequency from a wave model
+   ln_tauwoc   = .false.   !  Activate ocean stress modified by external wave induced stress (T => ln_wave=.true. & fill namsbc_wave)
+   ln_tauw     = .false.   !  Activate ocean stress components from wave model
+   ln_stcor    = .false.   !  Activate Stokes Coriolis term (T => ln_wave=.true. & ln_sdw=.true. & fill namsbc_wave)
+   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)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the fluxes data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR     = .false.   ! "NCAR"      algorithm   (Large and Yeager 2008)
+   ln_COARE_3p0 = .false.   ! "COARE 3.0" algorithm   (Fairall et al. 2003)
+   ln_COARE_3p5 = .false.   ! "COARE 3.5" algorithm   (Edson et al. 2013)
+   ln_ECMWF    = .false.   ! "ECMWF"     algorithm   (IFS cycle 31)
+      !
+      rn_zqt      = 10.       !  Air temperature & humidity reference height (m)
+      rn_zu       = 10.       !  Wind vector reference height (m)
+      ln_Cd_L12   = .false.   !  air-ice drags = F(ice concentration) (Lupkes et al. 2012)
+      ln_Cd_L15   = .false.   !  air-ice drags = F(ice concentration) (Lupkes et al. 2015)
+      ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
+      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 used to
+      !                       !  calculate the wind stress (0.=absolute or 1.=relative winds)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !       weights filename               ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_cc       = 'NOT USED'                   ,   24.        , 'CC'      ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24.        , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+   nn_cplmodel       =     1   !  Maximum number of models to/from which NEMO is potentially 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)
+   ln_scale_ice_flux = .false. !  use ice fluxes that are already "ice weighted" ( i.e. multiplied ice concentration)
+   nn_cats_cpl       =     5   !  Number of sea ice categories over which coupling is to be carried out (if not 1)
+   !_____________!__________________________!____________!_____________!______________________!________!
+   !             !        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'    ,     ''      ,         ''           ,   ''
+   sn_snd_crtw   =   'none'                 ,    'no'    ,     ''      ,         ''           , 'U,V'
+   sn_snd_ifrac  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_wlev   =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_cond   =   'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_thick1 =   'ice and snow'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_mpnd   =   'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_sstfrz =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_ttilyr =   'weighted ice'         ,    '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_hsig   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_iceflx =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_mslp   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_phioc  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_sdrfx  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_sdrfy  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wper   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wnum   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wfreq  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_ts_ice =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_isf    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_icb    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_tauwoc =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_tauw   =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .true.    !  =T Read in file ;  =F set all to 0. (see sbcssm)
+      ln_3d_uve   = .false.   !  specify whether we are supplying a 3D u,v and e3 field
+      ln_read_frq = .false.   !  specify whether we must read frq or not
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_usp      = 'sas_grid_U'            ,       120.        , 'uos'     ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_vsp      = 'sas_grid_V'            ,       120.        , 'vos'     ,   .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'  ,    ''            ,    ''    ,    ''
+   sn_e3t      = 'sas_grid_T'            ,       120.        , 'e3t_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_frq      = 'sas_grid_T'            ,       120.        , 'frq_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+/
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the ice cover data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ice      ='ice_cover_clim.nc'      ,        -12.       ,'ice_cover',   .true.    , .true.  , 'yearly'  ,   ''            ,   ''     ,   ''
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .false.      !  RGB light penetration (Red-Green-Blue)
+   ln_qsr_2bd  = .false.      !  2BD light penetration (two bands)
+   ln_qsr_bio  = .false.      !  bio-model light penetration
+   !                       !  RGB & 2BD choices:
+   rn_abs      =   0.58       !  RGB & 2BD: fraction absorbed in the very near surface
+   rn_si0      =   0.35       !  RGB & 2BD: shortess depth of extinction
+   nn_chldta   =      0       !  RGB : Chl data (=1) or cst value (=0)
+   rn_si1      =   23.0       !  2BD : longest depth of extinction
+   
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sstr     =     0     !  add a retroaction term to the surface heat flux (=1) or not (=0)
+      rn_dqdt     = -40.      !  magnitude of the retroaction on temperature   [W/m2/K]
+   nn_sssr     =     0     !  add a damping term to the surface freshwater flux (=2)
+      !                    !  or to SSS only (=1) or no damping term (=0)
+      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]
+      nn_sssr_ice =   1       ! control of sea surface restoring under sea-ice
+                              ! 0 = no restoration under ice : * (1-icefrac)
+                              ! 1 = restoration everywhere
+                              ! >1 = enhanced restoration under ice : 1+(nn_icedmp-1)*icefrac
+   cn_dir      = './'      !  root directory for the SST/SSS data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_sst      = 'sst_data'              ,        24.        ,  'sst'    ,    .false.  , .false., 'yearly'  ,    ''            ,    ''    ,     ''
+   sn_sss      = 'sss_data'              ,        -1.        ,  'sss'    ,    .true.   , .true. , 'yearly'  ,    ''            ,    ''    ,     ''
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .false.   !  specific treatment at rivers mouths
+      rn_hrnf     =  15.e0    !  depth over which enhanced vertical mixing is used    (ln_rnf_mouth=T)
+      rn_avt_rnf  =   1.e-3   !  value of the additional vertical mixing coef. [m2/s] (ln_rnf_mouth=T)
+   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
+   ln_rnf_depth_ini = .false. ! compute depth at initialisation from runoff file
+      rn_rnf_max  = 5.735e-4  !  max value of the runoff climatologie over global domain ( ln_rnf_depth_ini = .true )
+      rn_dep_max  = 150.      !  depth over which runoffs is spread ( ln_rnf_depth_ini = .true )
+      nn_rnf_depth_file = 0   !  create (=1) a runoff depth file or not (=0)
+   ln_rnf_icb  = .false.   !  read in iceberg flux from a file (fill sn_i_rnf if .true.)
+
+   cn_dir      = './'      !  root directory for the runoff data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  , ''               , ''       , ''
+   sn_i_rnf    = 'NOT_USED'              ,        -1.        , 'sorunoff',   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+   rn_pref     = 101000.   !  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
+
+   cn_dir = './'        !  root directory for the Patm data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_apr      = 'patm'                  ,         -1.       ,'somslpre' ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,      ''
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+   !                 ! type of top boundary layer 
+   nn_isf      = 1         !  ice shelf melting/freezing
+                           !  1 = presence of ISF   ;  2 = bg03 parametrisation 
+                           !  3 = rnf file for ISF  ;  4 = ISF specified freshwater flux
+                           !  options 1 and 4 need ln_isfcav = .true. (domzgr)
+      !              !  nn_isf = 1 or 2 cases:
+      rn_gammat0  = 1.e-4     ! gammat coefficient used in blk formula
+      rn_gammas0  = 1.e-4     ! gammas coefficient used in blk formula
+      !              !  nn_isf = 1 or 4 cases:
+      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
+      !              ! nn_isf = 1 case
+      nn_isfblk   = 1         ! 1 ISOMIP  like: 2 equations formulation (Hunter et al., 2006)
+      !                       ! 2 ISOMIP+ like: 3 equations formulation (Asay-Davis et al., 2015)
+      nn_gammablk = 1         ! 0 = cst Gammat (= gammat/s)
+      !                       ! 1 = velocity dependend Gamma (u* * gammat/s)  (Jenkins et al. 2010)
+      !                       ! 2 = velocity and stability dependent Gamma    (Holland et al. 1999)
+
+   !___________!_____________!___________________!___________!_____________!_________!___________!__________!__________!_______________!
+   !           !  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      !
+!* nn_isf = 4 case
+   sn_fwfisf   = 'rnfisf'    ,         -12.      ,'sowflisf' ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 3 case
+   sn_rnfisf   = 'rnfisf'    ,         -12.      ,'sofwfisf' ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 2 and 3 cases 
+   sn_depmax_isf ='rnfisf'   ,         -12.      ,'sozisfmax',  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+   sn_depmin_isf ='rnfisf'   ,         -12.      ,'sozisfmin',  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 2 case
+   sn_Leff_isf = 'rnfisf'    ,         -12.      ,'Leff'     ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+   nn_drown    = 10        ! number of iteration of the extrapolation loop (fill the new wet cells)
+   ln_hsb      = .false.   ! activate conservation module (conservation exact after a time of rn_fiscpl)
+   nn_fiscpl   = 43800     ! (number of time step) conservation period (maybe should be fix to the coupling frequencey of restart frequency)
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the waves data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_cdg      =  'sdw_ecwaves_orca2'    ,        6.         , 'drag_coeff' ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_usd      =  'sdw_ecwaves_orca2'    ,        6.         , 'u_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_vsd      =  'sdw_ecwaves_orca2'    ,        6.         , 'v_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_hsw      =  'sdw_ecwaves_orca2'    ,        6.         , 'hs'         ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wmp      =  'sdw_ecwaves_orca2'    ,        6.         , 'wmp'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wfr      =  'sdw_ecwaves_orca2'    ,        6.         , 'wfr'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wnum     =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_num'   ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwoc   =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwx    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwy    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+   ln_icebergs = .false.      ! activate iceberg floats (force =F with "key_agrif")
+   !
+   !                          ! diagnostics:
+   ln_bergdia        = .true.        ! Calculate budgets
+   nn_verbose_level  = 0             ! 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
+   !
+   !                          ! iceberg setting:
+   !                                 ! 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
+   ln_use_calving          = .false. ! Use calving data even when nn_test_icebergs > 0
+   rn_speed_limit          = 0.      ! CFL speed limit for a berg
+
+   cn_dir      = './'      !  root directory for the calving data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_icb     =  'calving'              ,         -1.        ,'calvingmask',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  free slip  !   partial slip  !   no slip   ! strong slip
+   rn_shlat    =  -9999.   !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+   ln_vorlat   = .false.   !  consistency of vorticity boundary condition with analytical Eqs.
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   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]
+   ln_chk_bathy  = .false. !  =T  check the parent bathymetry
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tide     = .false.      ! Activate tides
+      ln_tide_pot   = .true.                !  use tidal potential forcing
+         ln_scal_load  = .false.               ! Use scalar approximation for
+            rn_scal_load = 0.094               !     load potential
+         ln_read_load  = .false.               ! Or read load potential from file
+            cn_tide_load = 'tide_LOAD_grid_T.nc'  ! filename for load potential
+            !      
+      ln_tide_ramp  = .false.               !  Use linear ramp for tides at startup
+         rdttideramp   =    0.                 !  ramp duration in days
+      clname(1)     = 'DUMMY'               !  name of constituent - all tidal components must be set in namelist_cfg
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+   ln_bdy         = .false.   !  Use unstructured open boundaries
+   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
+   cn_ice        =  'none'    !
+   nn_ice_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                       (see nam_bdy)
+!-----------------------------------------------------------------------
+   ln_zinterp  = .false.      !  T if a vertical interpolation is required. Variables gdep[tuv] and e3[tuv] must exist in the file
+   !                          !  automatically defined to T if the number of vertical levels in bdy dta /= jpk
+   ln_full_vel = .false.      !  T if [uv]3d are "full" velocities and not only its baroclinic components
+   !                          !  in this case, baroclinic and barotropic velocities will be recomputed -> [uv]2d not needed
+   !
+   cn_dir      = 'bdydta/'    !  root directory for the BDY data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''            ,   ''     ,     ''
+!* for si3
+   bn_a_i      = 'amm12_bdyT_ice'        ,         24.       , 'siconc'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_h_i      = 'amm12_bdyT_ice'        ,         24.       , 'sithic'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_h_s      = 'amm12_bdyT_ice'        ,         24.       , 'snthic'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_t_i      = 'NOT USED'              ,         24.       , 'sitemp'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_t_s      = 'NOT USED'              ,         24.       , 'sntemp'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_tsu      = 'NOT USED'              ,         24.       , 'sittop'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_s_i      = 'NOT USED'              ,         24.       , 'sisalt'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   ! melt ponds (be careful, bn_aip is the pond concentration (not fraction), so it differs from rn_iceapnd)
+   bn_aip      = 'NOT USED'              ,         24.       , 'siapnd'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_hip      = 'NOT USED'              ,         24.       , 'sihpnd'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_hil      = 'NOT USED'              ,         24.       , 'sihlid'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   ! if bn_t_i etc are "not used", then define arbitrary temperatures and salinity and ponds
+   rn_ice_tem  = 270.         !  arbitrary temperature               of incoming sea ice
+   rn_ice_sal  = 10.          !       --   salinity                            --
+   rn_ice_age  = 30.          !       --   age                                 --
+   rn_ice_apnd = 0.2          !       --   pond fraction = a_ip/a_i            --
+   rn_ice_hpnd = 0.05         !       --   pond depth                          --
+   rn_ice_hlid = 0.0          !       --   pond lid depth                      --
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+   filtide          = 'bdydta/amm12_bdytide_'   !  file name root of tidal forcing files
+   ln_bdytide_2ddta = .false.                   !
+   ln_bdytide_conj  = .false.                   ! 
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF  = .false.   !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin      = .false.   !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin  = .false.   !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.   !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp   = .true.    !  implicit top/bottom friction flag
+      ln_drgice_imp = .false. ! implicit ice-ocean drag
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+   rn_Cd0      =  1.e-3    !  drag coefficient [-]
+   rn_Uc0      =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax    =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0      =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0       =  3.0e-3   !  roughness [m] (ln_loglayer=T)
+   ln_boost    = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+   rn_Cd0      =  1.e-3    !  drag coefficient [-]
+   rn_Uc0      =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax    =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0      =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0       =  3.e-3    !  roughness [m] (ln_loglayer=T)
+   ln_boost    = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .false.   !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx     = 2       !  geothermal heat flux: = 1 constant flux
+      !                       !                        = 2 read variable flux [mW/m2]
+      rn_geoflx_cst = 86.4e-3 !  Constant value of geothermal heat flux       [mW/m2]
+
+   cn_dir      = './'      !  root directory for the geothermal data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_qgh      ='geothermal_heating.nc'  ,       -12.        , 'heatflow',   .false.   , .true. , 'yearly'  ,   ''             ,   ''     ,   ''
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .false.   !  Bottom Boundary Layer parameterisation flag
+      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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .false.         !  = Use TEOS-10
+   ln_eos80    = .false.         !  = Use EOS80
+   ln_seos     = .false.         !  = Use S-EOS (simplified Eq.)
+                                 !
+   !                     ! S-EOS coefficients (ln_seos=T):
+   !                             !  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
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient
+   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                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .false. !  No tracer advection
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .false. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order 
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   = .false.   !  No explicit diffusion
+   ln_traldf_lap   = .false.   !    laplacian operator
+   ln_traldf_blp   = .false.   !  bilaplacian operator
+   !
+   !                       !  Direction of action:
+   ln_traldf_lev   = .false.   !  iso-level
+   ln_traldf_hor   = .false.   !  horizontal  (geopotential)
+   ln_traldf_iso   = .false.   !  iso-neutral (standard operator)
+   ln_traldf_triad = .false.   !  iso-neutral (triad    operator)
+   !
+   !		       	         !  iso-neutral options:        
+   ln_traldf_msc   = .false.   !  Method of Stabilizing Correction      (both operators)
+   rn_slpmax       =  0.01     !  slope limit                           (both operators)
+   ln_triad_iso    = .false.   !  pure horizontal mixing in ML              (triad only)
+   rn_sw_triad     = 1         !  =1 switching triad ; =0 all 4 triads used (triad only)
+   ln_botmix_triad = .false.   !  lateral mixing on bottom                  (triad only)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 0         !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_diffusivity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                             !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+      !                        !  time invariant coefficients:  aht0 = 1/2  Ud*Ld   (lap case) 
+      !                             !                           or   = 1/12 Ud*Ld^3 (blp case)
+      rn_Ud        = 0.01           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .false.   ! (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_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .false.   ! use eddy induced velocity parameterization
+      !
+      !                        !  Coefficients:
+      nn_aei_ijk_t    = 0           !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_induced_velocity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                        !  time invariant coefficients:  aei0 = 1/2  Ue*Le 
+      rn_Ue        = 0.02           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Le        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+      !
+      ln_ldfeiv_dia =.false.   ! diagnose eiv stream function and velocities
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .false.  !  add a damping term (using resto.nc coef.)
+      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)
+      cn_resto = 'resto.nc'   !  Name of file containing restoration coeff. field (use dmp_tools to create this)
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+   ln_vvl_ztilde = .false.          !  z-tilde 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
+   ln_vvl_zstar_at_eqtor  = .false. !  ztilde near the equator
+   rn_ahe3       =  0.0             !  thickness diffusion coefficient
+   rn_rst_e3t    = 30.0             !  ztilde to zstar restoration timescale [days]
+   rn_lf_cutoff  =  5.0             !  cutoff frequency for low-pass filter  [days]
+   rn_zdef_max   =  0.9             !  maximum fractional e3t deformation
+   ln_vvl_dbg    = .true.           !  debug prints    (T/F)
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  energy    conserving scheme
+   ln_dynvor_ens = .false. !  enstrophy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_enT = .false. !  energy conserving scheme (T-point)
+   ln_dynvor_eeT = .false. !  energy conserving scheme (een using e3t)
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0  e3f = mi(mj(e3t))/4 
+      !                       ! =1  e3f = mi(mj(e3t))/mi(mj( tmask))
+   ln_dynvor_msk = .false. !  vorticity multiplied by fmask (=T)        ==>>> PLEASE DO NOT ACTIVATE
+      !                    !  (f-point vorticity schemes only)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   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_isf  = .false.   !  s-coordinate (sco ) adapted to isf
+   ln_hpg_djc  = .false.   !  s-coordinate (Density Jacobian with Cubic polynomial)
+   ln_hpg_prj  = .false.   !  s-coordinate (Pressure Jacobian scheme)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_exp  = .false.   ! explicit free surface
+   ln_dynspg_ts   = .false.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         rn_bt_cmax   =  0.8        ! =T : the Maximum Courant Number allowed
+         nn_baro      = 30          ! =F : the number of sub-step in rn_rdt seconds
+      rn_bt_alpha   = 0.         ! Temporal diffusion parameter (if ln_bt_av=F)
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF = .false.     !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap = .false.     !    laplacian operator
+   ln_dynldf_blp = .false.     !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev = .false.     !  iso-level
+   ln_dynldf_hor = .false.     !  horizontal  (geopotential)
+   ln_dynldf_iso = .false.     !  iso-neutral (lap only)
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coefficient :
+      !                             !  =-30  read in eddy_viscosity_3D.nc file
+      !                             !  =-20  read in eddy_viscosity_2D.nc file
+      !                             !  =  0  constant 
+      !                             !  = 10  F(k)=c1d
+      !                             !  = 20  F(i,j)=F(grid spacing)=c2d
+      !                             !  = 30  F(i,j,k)=c2d*c1d
+      !                             !  = 31  F(i,j,k)=F(grid spacing and local velocity)
+      !                             !  = 32  F(i,j,k)=F(local gridscale and deformation rate)
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            or  = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 0.1              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 10.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+      !                       !  Smagorinsky settings  (nn_ahm_ijk_t= 32) :
+      rn_csmc       = 3.5         !  Smagorinsky constant of proportionality
+      rn_minfac     = 1.0         !  multiplier of theorectical lower limit
+      rn_maxfac     = 1.0         !  multiplier of theorectical upper limit
+      !                       !  iso-neutral laplacian operator (ln_dynldf_iso=T) :
+      rn_ahm_b      = 0.0         !  background eddy viscosity  [m2/s]
+/
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+   ln_dynrnf       =  .false.    !  runoffs option enabled (T) or not (F)
+   ln_dynrnf_depth =  .false.    !  runoffs is spread in vertical (T) or not (F)
+!   fwbcorr        = 3.786e-06   !  annual global mean of empmr for ssh correction
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'dyna_grid_T'           ,       120.        , 'votemper'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_sal      = 'dyna_grid_T'           ,       120.        , 'vosaline'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_mld      = 'dyna_grid_T'           ,       120.        , 'somixhgt'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_emp      = 'dyna_grid_T'           ,       120.        , 'sowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_fmf      = 'dyna_grid_T'           ,       120.        , 'iowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ice      = 'dyna_grid_T'           ,       120.        , 'soicecov'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_qsr      = 'dyna_grid_T'           ,       120.        , 'soshfldo'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wnd      = 'dyna_grid_T'           ,       120.        , 'sowindsp'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_uwd      = 'dyna_grid_U'           ,       120.        , 'uocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vwd      = 'dyna_grid_V'           ,       120.        , 'vocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wwd      = 'dyna_grid_W'           ,       120.        , 'wocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_avt      = 'dyna_grid_W'           ,       120.        , 'voddmavs'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ubl      = 'dyna_grid_U'           ,       120.        , 'sobblcox'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vbl      = 'dyna_grid_V'           ,       120.        , 'sobblcoy'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! adaptive-implicit vertical advection
+   ln_zad_Aimp = .false.      !  Courant number dependent scheme (Shchepetkin 2015)
+   !
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .false.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   ln_zdfosm   = .false.      !  OSMOSIS BL closure                     (T =>   fill namzdf_osm)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+   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
+   ln_mldw     =  .false.  !  enhanced mixing in the Ekman layer
+      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
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   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_pdl      =   1       !  Prandtl number function of richarson number (=1, avt=pdl(Ri)*avm) or not (=0, avt=avm)
+   nn_mxl      =   3       !  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 dissipative an mixing length scale
+   ln_mxl0     = .true.    !  surface mixing length scale = F(wind stress) (T) or not (F)
+      nn_mxlice    = 2        ! type of scaling under sea-ice
+                              !    = 0 no scaling under sea-ice
+                              !    = 1 scaling with constant sea-ice thickness
+                              !    = 2 scaling with mean sea-ice thickness ( only with SI3 sea-ice model )
+                              !    = 3 scaling with maximum sea-ice thickness
+      rn_mxlice   = 10.       ! max constant ice thickness value when scaling under sea-ice ( nn_mxlice=1)
+   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 NIWs
+                              !        = 0 none ; = 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           (ln_cpl=T)
+      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
+   nn_eice     =   1       !  attenutaion of langmuir & surface wave breaking under ice
+   !                       !           = 0 no impact of ice cover on langmuir & surface wave breaking
+   !                       !           = 1 weigthed by 1-TANH(10*fr_i)
+   !                       !           = 2 weighted by 1-fr_i
+   !                       !           = 3 weighted by 1-MIN(1,4*fr_i)   
+/
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+   rn_emin       = 1.e-7   !  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.267   !  galperin limit
+   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
+   rn_hsro       =  0.02   !  Minimum surface roughness
+   rn_hsri       =  0.03   !  Ice-ocean roughness
+   rn_frac_hs    =   1.3   !  Fraction of wave height as roughness (if nn_z0_met>1)
+   nn_z0_met     =     2   !  Method for surface roughness computation (0/1/2/3)
+   !                       !     = 3 requires ln_wave=T
+   nn_z0_ice     =   1     !  attenutaion of surface wave breaking under ice
+   !                       !           = 0 no impact of ice cover
+   !                       !           = 1 roughness uses rn_hsri and is weigthed by 1-TANH(10*fr_i)
+   !                       !           = 2 roughness uses rn_hsri and is weighted by 1-fr_i
+   !                       !           = 3 roughness uses rn_hsri and is weighted by 1-MIN(1,4*fr_i)
+   nn_bc_surf    =     1   !  surface condition (0/1=Dir/Neum)
+   nn_bc_bot     =     1   !  bottom 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_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+   ln_use_osm_la = .false.      !  Use namelist  rn_osm_la
+   rn_osm_la     = 0.3         !  Turbulent Langmuir number
+   rn_osm_dstokes     = 5.     !  Depth scale of Stokes drift (m)
+   nn_ave = 0                  ! choice of horizontal averaging on avt, avmu, avmv
+   ln_dia_osm = .true.         ! output OSMOSIS-OBL variables
+   rn_osm_hbl0 = 10.           ! initial hbl value
+   ln_kpprimix = .true.        ! Use KPP-style Ri# mixing below BL
+   rn_riinfty  = 0.7           ! Highest local Ri_g permitting shear instability
+   rn_difri  =  0.005          ! max Ri# diffusivity at Ri_g = 0 (m^2/s)
+   ln_convmix  = .true.        ! Use convective instability mixing below BL
+   rn_difconv = 1.             ! diffusivity when unstable below BL  (m2/s)
+   nn_osm_wave = 0             ! Method used to calculate Stokes drift
+      !                        !  = 2: Use ECMWF wave fields
+      !                        !  = 1: Pierson Moskowitz wave spectrum
+      !                        !  = 0: Constant La# = 0.3
+/
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+   nn_zpyc     = 1         !  pycnocline-intensified dissipation scales as N (=1) or N^2 (=2)
+   ln_mevar    = .true.    !  variable (T) or constant (F) mixing efficiency
+   ln_tsdiff   = .true.    !  account for differential T/S mixing (T) or not (F)
+/
+
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+   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
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diaptr   = .false.   !  Poleward heat and salt transport (T) or not (F)
+   ln_subbas   = .false.   !  Atlantic/Pacific/Indian basins computation (T) or not
+/
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diahsb   = .false.   !  output the heat and salt budgets (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diurnal      = .false.   !
+   ln_diurnal_only = .false.   !
+/
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+   ln_floats   = .false.      ! activate floats or not
+      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)
+/
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              (default: OFF)
+!-----------------------------------------------------------------------
+    ln_diaharm = .false.   ! Choose tidal harmonic output or not
+       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'   !              ---
+/
+!-----------------------------------------------------------------------
+&nam_diadct    !   transports through some sections                     (default: OFF)
+!-----------------------------------------------------------------------
+    ln_diadct  = .false.   ! Calculate transport thru sections or not
+       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
+/
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dia25h   = .false.   ! Choose 25h mean output or not
+/
+!-----------------------------------------------------------------------
+&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
+/
+
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diaobs   = .false.             ! Logical switch for the observation operator
+   !
+   ln_t3d      = .false.             ! Logical switch for T profile observations
+   ln_s3d      = .false.             ! Logical switch for S profile observations
+   ln_sla      = .false.             ! Logical switch for SLA observations
+   ln_sst      = .false.             ! Logical switch for SST observations
+   ln_sss      = .false.             ! Logical swithc for SSS observations
+   ln_sic      = .false.             ! Logical switch for Sea Ice observations
+   ln_vel3d    = .false.             ! Logical switch for velocity observations
+   ln_altbias  = .false.             ! Logical switch for altimeter bias correction
+   ln_sstbias  = .false.             ! Logical switch for SST bias correction
+   ln_nea      = .false.             ! Logical switch for rejection of observations near land
+   ln_grid_global = .true.           ! Logical switch for global distribution of observations
+   ln_grid_search_lookup = .false.   ! Logical switch for obs grid search w/lookup table
+   ln_ignmis   = .true.              ! Logical switch for ignoring missing files
+   ln_s_at_t   = .false.             ! Logical switch for computing model S at T obs if not there
+   ln_sstnight = .false.             ! Logical switch for calculating night-time average for SST obs
+   ln_bound_reject  = .false.        ! Logical to remove obs near boundaries in LAMs.
+   ln_sla_fp_indegs = .true.         ! Logical for SLA: T=> averaging footprint is in degrees, F=> in metres
+   ln_sst_fp_indegs = .true.         ! Logical for SST: T=> averaging footprint is in degrees, F=> in metres
+   ln_sss_fp_indegs = .true.         ! Logical for SSS: T=> averaging footprint is in degrees, F=> in metres
+   ln_sic_fp_indegs = .true.         ! Logical for SIC: T=> averaging footprint is in degrees, F=> in metres
+! All of the *files* variables below are arrays. Use namelist_cfg to add more files
+   cn_profbfiles = 'profiles_01.nc'  ! Profile feedback input observation file names
+   cn_slafbfiles = 'sla_01.nc'       ! SLA feedback input observation file names
+   cn_sstfbfiles = 'sst_01.nc'       ! SST feedback input observation file names
+   cn_sssfbfiles = 'sss_01.nc'       ! SSS feedback input observation file names
+   cn_sicfbfiles = 'sic_01.nc'       ! SIC feedback input observation file names
+   cn_velfbfiles = 'vel_01.nc'       ! Velocity feedback input observation file names
+   cn_altbiasfile = 'altbias.nc'     ! Altimeter bias input file name
+   cn_sstbiasfiles = 'sstbias.nc'    ! SST bias input file name
+   cn_gridsearchfile ='gridsearch.nc' ! Grid search file name
+   rn_gridsearchres = 0.5            ! Grid search resolution
+   rn_mdtcorr  = 1.61                ! MDT  correction
+   rn_mdtcutoff = 65.0               ! MDT cutoff for computed correction
+   rn_dobsini  = 00010101.000000     ! Initial date in window YYYYMMDD.HHMMSS
+   rn_dobsend  = 00010102.000000     ! Final date in window YYYYMMDD.HHMMSS
+   rn_sla_avglamscl = 0.             ! E/W diameter of SLA observation footprint (metres/degrees)
+   rn_sla_avgphiscl = 0.             ! N/S diameter of SLA observation footprint (metres/degrees)
+   rn_sst_avglamscl = 0.             ! E/W diameter of SST observation footprint (metres/degrees)
+   rn_sst_avgphiscl = 0.             ! N/S diameter of SST observation footprint (metres/degrees)
+   rn_sss_avglamscl = 0.             ! E/W diameter of SSS observation footprint (metres/degrees)
+   rn_sss_avgphiscl = 0.             ! N/S diameter of SSS observation footprint (metres/degrees)
+   rn_sic_avglamscl = 0.             ! E/W diameter of SIC observation footprint (metres/degrees)
+   rn_sic_avgphiscl = 0.             ! N/S diameter of SIC observation footprint (metres/degrees)
+   nn_1dint = 0                      ! Type of vertical interpolation method
+   nn_2dint = 0                      ! Default horizontal interpolation method
+   nn_2dint_sla = 0                  ! Horizontal interpolation method for SLA
+   nn_2dint_sst = 0                  ! Horizontal interpolation method for SST
+   nn_2dint_sss = 0                  ! Horizontal interpolation method for SSS
+   nn_2dint_sic = 0                  ! Horizontal interpolation method for SIC
+   nn_msshc     = 0                  ! MSSH correction scheme
+   nn_profdavtypes = -1              ! Profile daily average types - array
+/
+!-----------------------------------------------------------------------
+&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
+/
+
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+   ln_listonly =  .false.  !  do nothing else than listing the best domain decompositions (with land domains suppression)
+   !                       !  if T: the largest number of cores tested is defined by max(mppsize, jpni*jpnj)
+   ln_nnogather =  .true.  !  activate code to avoid mpi_allgather use at the northfold
+   jpni        =   0       !  number of processors following i (set automatically if < 1), see also ln_listonly = T
+   jpnj        =   0       !  number of processors following j (set automatically if < 1), see also ln_listonly = T
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ctl = .FALSE.                 ! Toggle all report printing on/off (T/F); Ignored if sn_cfctl%l_config is T
+     sn_cfctl%l_config = .TRUE.     ! IF .true. then control which reports are written with the following
+       sn_cfctl%l_runstat = .FALSE. ! switches and which areas produce reports with the proc integer settings.
+       sn_cfctl%l_trcstat = .FALSE. ! The default settings for the proc integers should ensure
+       sn_cfctl%l_oceout  = .FALSE. ! that  all areas report.
+       sn_cfctl%l_layout  = .FALSE. !
+       sn_cfctl%l_mppout  = .FALSE. !
+       sn_cfctl%l_mpptop  = .FALSE. !
+       sn_cfctl%procmin   = 0       ! Minimum area number for reporting [default:0]
+       sn_cfctl%procmax   = 1000000 ! Maximum area number for reporting [default:1000000]
+       sn_cfctl%procincr  = 1       ! Increment for optional subsetting of areas [default:1]
+       sn_cfctl%ptimincr  = 1       ! Timestep increment for writing time step progress info
+   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
+   ln_timing   = .false.   !  timing by routine write out in timing.output file
+   ln_diacfl   = .false.   !  CFL diagnostics write out in cfl_diagnostics.ascii
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_sto_eos  = .false.   ! stochastic equation of state
+   nn_sto_eos  = 1         ! number of independent random walks
+   rn_eos_stdxy = 1.4       ! random walk horz. standard deviation (in grid points)
+   rn_eos_stdz = 0.7       ! random walk vert. standard deviation (in grid points)
+   rn_eos_tcor = 1440.     ! random walk time correlation (in timesteps)
+   nn_eos_ord  = 1         ! order of autoregressive processes
+   nn_eos_flt  = 0         ! passes of Laplacian filter
+   rn_eos_lim  = 2.0       ! limitation factor (default = 3.0)
+   ln_rststo   = .false.   ! start from mean parameter (F) or from restart file (T)
+   ln_rstseed  = .true.    ! read seed of RNG from restart file
+   cn_storst_in  = "restart_sto" !  suffix of stochastic parameter restart file (input)
+   cn_storst_out = "restart_sto" !  suffix of stochastic parameter restart file (output)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_top_ref	(revision 14097)
@@ -0,0 +1,151 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP :   Reference namelist 
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               - tracer run information                (namtrc_run)
+!!               - tracer definition                     (namtrc    )
+!!               - tracer data initialisation            (namtrc_dta)
+!!               - tracer advection                      (namtrc_adv)
+!!               - tracer lateral diffusion              (namtrc_ldf)
+!!               - tracer vertical physics               (namtrc_zdf)
+!!               - tracer newtonian damping              (namtrc_dmp)
+!!               - dynamical tracer trends               (namtrc_trd)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   nn_dttrc      =  1        !  time step frequency for passive sn_tracers
+   ln_top_euler  = .false.   !  use Euler time-stepping for TOP
+   ln_rsttr      = .false.   !  start from a restart file (T) or not (F)
+   nn_rsttr      =   0       !  restart control = 0 initial time step is not compared to the restart file value
+                             !                  = 1 do not use the value in the restart file
+                             !                  = 2 calendar parameters read in the restart file
+   cn_trcrst_in  = "restart_trc"   !  suffix of pass. sn_tracer restart name (input)
+   cn_trcrst_indir = "."           !  directory from which to read input passive tracer restarts
+   cn_trcrst_out = "restart_trc"   !  suffix of pass. sn_tracer restart name (output)
+   cn_trcrst_outdir = "."          !  directory to which to write output passive tracer restarts
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  0           !  Number of passive tracers of the BGC model
+   !
+   ln_pisces     =  .false.     !  Run PISCES BGC model 
+   ln_my_trc     =  .false.     !  Run MY_TRC BGC model
+   ln_age        =  .false.     !  Run the sea water age tracer
+   ln_cfc11      =  .false.     !  Run the CFC11 passive tracer
+   ln_cfc12      =  .false.     !  Run the CFC12 passive tracer
+   ln_sf6        =  .false.     !  Run the SF6 passive tracer
+   ln_c14        =  .false.     !  Run the Radiocarbon passive tracer
+   !
+   ln_trcdta     =  .false.  !  Initialisation from data input file (T) or not (F)
+   ln_trcdmp     =  .false.  !  add a damping termn (T) or not (F)
+   ln_trcdmp_clo =  .false.  !  damping term (T) or not (F) on closed seas
+   !
+   jp_dia3d      = 0         ! Number of 3D diagnostic variables
+   jp_dia2d      = 0         ! Number of 2D diagnostic variables
+   !_____________!___________!_________________________________________!____________!________________!
+   !             !    name   !           title of the field            !   units    ! init from file ! 
+!  sn_tracer(1)  = 'tracer  ', 'Tracer  Concentration                 ',   ' - '    ,   .false.
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+   rn_age_depth      = 10            ! depth over which age tracer reset to zero
+   rn_age_kill_rate  = -0.000138888  !  = -1/7200 recip of relaxation timescale (s) for  age tracer shallower than age_depth
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!                !  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_trcdta(1)  = 'data_TRC_nomask' ,        -12.       ,  'TRC'    ,    .false.   , .true. , 'yearly'  , ''       , ''       , ''
+   !
+   cn_dir        =  './'     !  root directory for the location of the data files
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_OFF =  .false.  !  No passive tracer advection
+   ln_trcadv_cen =  .false.  !  2nd order centered scheme
+      nn_cen_h   =  4               !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4               !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_trcadv_fct =  .false.  !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+   ln_trcadv_mus =  .false.  !  MUSCL scheme
+      ln_mus_ups =  .false.         !  use upstream scheme near river mouths
+   ln_trcadv_ubs =  .false.  !  UBS scheme
+      nn_ubs_v   =  2               !  =2  , vertical 2nd order FCT
+   ln_trcadv_qck =  .false.  !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+!                            !  Type of the operator:
+   ln_trcldf_OFF   =  .false.    !  No explicit diffusion
+   ln_trcldf_tra   =  .false.    !  use active tracer setting
+   !                         !  Coefficient (defined with namtra_ldf coefficient)
+   rn_ldf_multi    = 1.          !  multiplier of aht for TRC mixing coefficient
+   rn_fact_lap     = 1.          !  Equatorial enhanced zonal eddy diffusivity (lap only)
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+   ln_trcrad     =  .true.   !  artificially correct negative concentrations (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namtrc_snk      !  Sedimentation of particles
+!-----------------------------------------------------------------------
+   nitermax      =  2   !  number of iterations for sedimentation
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping                   (ln_trcdmp=T)
+!-----------------------------------------------------------------------
+   nn_zdmp_tr    =    1      !  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)
+   cn_resto_tr   = 'resto_tr.nc'    !  create a damping.coeff NetCDF file (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+   nn_ice_tr     =  -1       !  tracer concentration in sea ice 
+                             !    =-1 (no vvl: identical cc in ice and ocean / vvl: cc_ice = 0)
+                             !    = 0 (no vvl: cc_ice = zero / vvl: cc_ice = )
+                             !    = 1 prescribed to a namelist value (implemented in pisces only)
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!                          or mixed-layer trends                        ('key_trdmld_trc')
+!----------------------------------------------------------------------
+   nn_trd_trc    =  5475     !  time step frequency and tracers trends
+   nn_ctls_trc   =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
+   rn_ucf_trc    =   1       !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
+   ln_trdmxl_trc_restart = .false.   !  restart for ML diagnostics
+   ln_trdmxl_trc_instant = .true.    !  flag to diagnose trends of instantantaneous or mean ML T/S
+   cn_trdrst_trc_in  = 'restart_trd' !  suffix of pass. tracer trends restart name (input)
+   cn_trdrst_trc_out = 'restart_trd' !  suffix of pass. tracer trends restart name (output)
+   ln_trdtrc( 1) = .true.
+   ln_trdtrc( 2) = .true.
+   ln_trdtrc(23) = .true.
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+   cn_dir_sbc    =  './'     !  root directory for the location of SURFACE data files
+   cn_dir_cbc    =  './'     !  root directory for the location of COASTAL data files
+   cn_dir_obc    =  './'     !  root directory for the location of OPEN data files
+   ln_rnf_ctl    = .false.   !  Remove runoff dilution on tracers with absent river load
+   rn_bc_time    =  86400.   !  Time scaling factor for SBC and CBC data (seconds in a day)
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+   cn_trc_dflt   = 'neumann' !  OBC applied by default to all tracers
+   cn_trc        = 'none'    !  Boundary conditions used for tracers with data files (selected in namtrc)
+
+   nn_trcdmp_bdy = 0         !  Use damping timescales defined in nambdy of namelist
+                             !  = 0 NO damping of tracers at open boudaries
+                             !  = 1 Only for tracers forced with external data
+                             !  = 2 Damping applied to all tracers
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_trc_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_trc_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SHARED/namelist_trc_ref	(revision 14097)
@@ -0,0 +1,45 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! Inert tracers reference namelist 
+!!       1  - CFC                (namcfc)
+!!       2  - C14               (namc14_typ, namc14_sbc, namc14_fcg)
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namcfc     !   CFC 
+!-----------------------------------------------------------------------
+   ndate_beg  = 300101    !  datedeb1
+   nyear_res  = 1932      !  iannee1
+   !
+   ! Formatted file of annual hemisperic CFCs concentration in the atmosphere (ppt)
+   clname     = 'CFCs_CDIAC.dat'
+/
+!
+!-----------------------------------------------------------------------
+&namc14_typ     !  C14 - type of C14 tracer, default values of C14/C and pco2
+!-----------------------------------------------------------------------
+   kc14typ  = 0          ! Type of C14 tracer (0=equilibrium; 1=bomb transient; 2=past transient)
+   rc14at   = 1.0        ! Default value for atmospheric C14/C (used for equil run)
+   pco2at   = 280.0      ! Default value for atmospheric pcO2 [atm] (used for equil run)
+   rc14init = 0.85       ! Default value for initialization of ocean C14/C (when no restart)
+/
+!
+!-----------------------------------------------------------------------
+&namc14_sbc     !  C14 - surface BC
+!-----------------------------------------------------------------------
+   ln_chemh = .true.     ! Chemical enhancement in piston vel.: yes/no
+   xkwind   = 0.360      ! Coefficient for gas exchange velocity
+   xdicsur  = 2.0        ! Reference DIC surface concentration (mol/m3)
+/
+!
+!-----------------------------------------------------------------------
+&namc14_fcg     !  files & dates
+!               !  For Paleo-historical: specify tyrc14_beg in yr BP
+!               !  For Bomb: tyrc14_beg=0
+!-----------------------------------------------------------------------
+   cfileco2    = 'splco2.dat'  !  atmospheric co2 - Bomb
+   cfilec14    = 'atmc14.dat'  !  atmospheric c14 - Bomb
+   tyrc14_beg  = 0.00          !  starting year of experiment - Bomb
+!   cfileco2    = 'ByrdEdcCO2.txt' !  atmospheric co2 - Paleo
+!   cfilec14    = 'intcal13.14c'   !  atmospheric c14 - Paleo
+!   tyrc14_beg  =  35000.00        !  starting year of experiment - Paleo (yr BP)
+/
+!
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,134 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                      Define your own files for sea ice                                   =
+=                                         put the variables you want...                                    =
+============================================================================================================
+ -->
+    
+ <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+   
+   <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   	
+     <file id="file21" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+       <!-- ice mask -->
+       <field field_ref="icemask"          name="simsk"   />
+       <field field_ref="icemask05"        name="simsk05" />
+       <field field_ref="icemask15"        name="simsk15" />
+       
+       <!-- general -->
+       <field field_ref="snwvolu"          name="snvolu" />
+       <field field_ref="icethic"          name="sithic" />
+       <field field_ref="icevolu"          name="sivolu" />
+       <field field_ref="iceconc"          name="siconc" />
+       <field field_ref="icesalt"          name="sisali" />
+       <field field_ref="iceapnd"          name="siapnd" />
+       <field field_ref="icevpnd"          name="sivpnd" />
+       <field field_ref="sst_m"            name="sst_m"  />
+       <field field_ref="sss_m"            name="sss_m"  />
+       
+       <!-- heat -->
+       <field field_ref="icetemp"          name="sitemp" />
+       <field field_ref="snwtemp"          name="sntemp" />
+       <field field_ref="icettop"          name="sittop" />
+       <field field_ref="icetbot"          name="sitbot" />
+       <field field_ref="icetsni"          name="sitsni" />
+       
+       <!-- momentum -->
+       <field field_ref="uice"             name="sivelu"  />
+       <field field_ref="vice"             name="sivelv"  />
+       <field field_ref="icevel"           name="sivelo"  />
+       <field field_ref="utau_ai"          name="utau_ai" />
+       <field field_ref="vtau_ai"          name="vtau_ai" />
+       <field field_ref="utau_oi"          name="utau_oi" />
+       <field field_ref="vtau_oi"          name="vtau_oi" />
+       
+       <!-- rheology -->
+       <field field_ref="icediv"           name="sidive"  />
+       <field field_ref="iceshe"           name="sishea"  />
+       <field field_ref="icestr"           name="sistre"  />
+       <field field_ref="normstr"          name="normstr" />
+       <field field_ref="sheastr"          name="sheastr" />
+       
+       <!-- heat fluxes -->
+       <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+       <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+       <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+       <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+       <field field_ref="qt_ice"           name="qt_ice"     />
+       <field field_ref="qsr_ice"          name="qsr_ice"    />
+       <field field_ref="qns_ice"          name="qns_ice"    />
+       <field field_ref="qemp_ice"         name="qemp_ice"   />
+       <field field_ref="albedo"           name="albedo"     />
+       
+       <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+       <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+       <field field_ref="hfxsensib"        name="hfxsensib"  />
+       
+       <!-- salt fluxes -->
+       <field field_ref="sfxice"           name="sfxice" />
+       
+       <!-- mass fluxes -->
+       <field field_ref="vfxice"           name="vfxice" />
+       <field field_ref="vfxsnw"           name="vfxsnw" />
+
+       <!-- categories -->
+       <field field_ref="icemask_cat"      name="simskcat"/>
+       <field field_ref="snwthic_cat"      name="snthicat"/>
+       <field field_ref="iceconc_cat"      name="siconcat"/>
+       <field field_ref="icethic_cat"      name="sithicat"/>
+       <field field_ref="icesalt_cat"      name="sisalcat"/>
+       <field field_ref="icetemp_cat"      name="sitemcat"/>
+       <field field_ref="snwtemp_cat"      name="sntemcat"/>
+       <field field_ref="icettop_cat"      name="sitopcat"/>
+
+     </file>
+     
+     <file id="file22" name_suffix="_SBC_scalar" description="scalar variables" enabled=".true." >
+       <!-- global contents -->
+       <field field_ref="ibgvol_tot"     name="ibgvol_tot"   />
+       <field field_ref="sbgvol_tot"     name="sbgvol_tot"   />
+       <field field_ref="ibgarea_tot"    name="ibgarea_tot"  />
+       <field field_ref="ibgsalt_tot"    name="ibgsalt_tot"  />
+       <field field_ref="ibgheat_tot"    name="ibgheat_tot"  />
+       <field field_ref="sbgheat_tot"    name="sbgheat_tot"  />
+       
+       <!-- global drifts (conservation checks) -->
+       <field field_ref="ibgvolume"      name="ibgvolume"    />
+       <field field_ref="ibgsaltco"      name="ibgsaltco"    />
+       <field field_ref="ibgheatco"      name="ibgheatco"    />
+       <field field_ref="ibgheatfx"      name="ibgheatfx"    />
+       
+       <!-- global forcings  -->
+       <field field_ref="ibgfrcvoltop"   name="ibgfrcvoltop" />
+       <field field_ref="ibgfrcvolbot"   name="ibgfrcvolbot" />
+       <field field_ref="ibgfrctemtop"   name="ibgfrctemtop" />
+       <field field_ref="ibgfrctembot"   name="ibgfrctembot" />
+       <field field_ref="ibgfrcsal"      name="ibgfrcsal"    />
+       <field field_ref="ibgfrchfxtop"   name="ibgfrchfxtop" />
+       <field field_ref="ibgfrchfxbot"   name="ibgfrchfxbot" />
+     </file>
+     
+   </file_group>
+   
+   <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="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="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>
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,125 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context               =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+   
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1mo" min_digits="4">
+    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
+        <file id="file11" name_suffix="_grid_T" description="ocean T grid variables" >
+          <field field_ref="e3t"      />
+          <field field_ref="toce"         name="thetao"                                                                      operation="instant" freq_op="5d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="so"                                                                          operation="instant" freq_op="5d" > @soce_e3t / @e3t </field>
+          <field field_ref="sst"          name="tos"   />
+          <field field_ref="sss"          name="sos"   />
+          <field field_ref="ssh"          name="zos"   />
+          <field field_ref="sst"          name="tosstd"       long_name="sea surface temperature standard deviation"         operation="instant" freq_op="5d" > sqrt( @sst2 - @sst * @sst ) </field>
+          <field field_ref="ssh"          name="zosstd"       long_name="sea surface height above geoid standard deviation"  operation="instant" freq_op="5d" > sqrt( @ssh2 - @ssh * @ssh ) </field>
+          <field field_ref="sst"          name="sstdcy"       long_name="amplitude of sst diurnal cycle"                     operation="average" freq_op="1d" > @sstmax - @sstmin </field>
+          <field field_ref="mldkz5"   />
+          <field field_ref="mldr10_1" />
+          <field field_ref="mldr10_1"     name="mldr10_1dcy"  long_name="amplitude of mldr10_1 diurnal cycle"                operation="average" freq_op="1d" > @mldr10_1max - @mldr10_1min </field>
+          <field field_ref="sbt"      />
+          <field field_ref="heatc"        name="heatc" />
+          <field field_ref="saltc"        name="saltc" />
+
+	  <field field_ref="empmr"        name="wfo"      />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  />
+	  <field field_ref="qns_oce"      name="qns_oce"  />
+	  <field field_ref="qt_oce"       name="qt_oce"   />
+	  <field field_ref="saltflx"      name="sfx"      />
+	  <field field_ref="taum"         name="taum"     />
+	  <field field_ref="wspd"         name="windsp"   />
+	  <field field_ref="precip"       name="precip"   />
+	  <!-- ice and snow -->
+	  <field field_ref="snowpre" />
+	</file>
+
+	<file id="file12" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u" />
+	  <field field_ref="ssu"          name="uos"      />
+	  <field field_ref="uoce"         name="uo"       operation="instant" freq_op="5d" > @uoce_e3u / @e3u </field>
+	  <field field_ref="utau"         name="tauuo"    />
+          <field field_ref="uocetr_eff"   name="uocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="u_masstr"     name="vozomatr" />
+	  <field field_ref="u_heattr"     name="sozohetr" />
+	  <field field_ref="u_salttr"     name="sozosatr" />
+	</file>
+	
+	<file id="file13" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v" />
+	  <field field_ref="ssv"          name="vos"      />
+	  <field field_ref="voce"         name="vo"       operation="instant" freq_op="5d" > @voce_e3v / @e3v </field>
+	  <field field_ref="vtau"         name="tauvo"    />
+          <field field_ref="vocetr_eff"   name="vocetr_eff"  />
+          <!-- available with diaar5 -->
+	  <field field_ref="v_masstr"     name="vomematr" />
+	  <field field_ref="v_heattr"     name="somehetr" />
+          <field field_ref="v_salttr"     name="somesatr" />
+	</file>
+	
+	<file id="file14" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w" />
+	  <field field_ref="woce"         name="wo"       />
+	  <field field_ref="avt"          name="difvho"   />
+	  <field field_ref="w_masstr"     name="vovematr" />
+         <!-- variables available with ln_zdfiwm =T -->
+          <field field_ref="av_wave"      name="av_wave"    />
+          <field field_ref="bn2"          name="bn2"        />
+          <field field_ref="bflx_iwm"     name="bflx_iwm"   />
+          <field field_ref="pcmap_iwm"    name="pcmap_iwm"  />
+          <field field_ref="emix_iwm"     name="emix_iwm"   />
+          <field field_ref="av_ratio"     name="av_ratio"   />
+	</file>
+
+        <file id="file15" name_suffix="_scalar" description="scalar variables" >
+          <!-- global drifts (conservation checks) -->
+          <field field_ref="bgtemper"     name="bgtemper"    />
+          <field field_ref="bgsaline"     name="bgsaline"    />
+          <field field_ref="bgheatco"     name="bgheatco"    />
+          <field field_ref="bgheatfx"     name="bgheatfx"    />
+          <field field_ref="bgsaltco"     name="bgsaltco"    />
+          <field field_ref="bgvolssh"     name="bgvolssh"    />
+          <field field_ref="bgvole3t"     name="bgvole3t"    />
+
+          <!-- global surface forcings  -->
+          <field field_ref="bgfrcvol"     name="bgfrcvol"    />
+          <field field_ref="bgfrctem"     name="bgfrctem"    />
+          <field field_ref="bgfrchfx"     name="bgfrchfx"    />
+          <field field_ref="bgfrcsal"     name="bgfrcsal"    />
+        </file>
+
+      </file_group> 
+
+
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
+      </file_group>
+
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
+      </file_group>
+	
+      
+      <file_group id="1ts" output_freq="1ts" output_level="10" enabled=".TRUE."/> <!-- 1 time step 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="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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,411 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                       SPITZ 1/12 configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "SPITZ"  !  experience name
+   nn_it000    = 1         !  first time step
+   nn_itend    = 100       !  last  time step (std 5475)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =  720.     !  time step for the dynamics and tracer
+   !
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .true.    !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration           (F => create/check namusr_def)
+      cn_domcfg = "domain_cfg"  ! domain configuration filename
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .true.          !  ocean initialisation
+
+   cn_dir = './'     !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem    = 'T_SPITZ12'   ,  24.          ,'votemper',    .false.   , .false., 'daily'   , ''      , '' ,    ''
+   sn_sal    = 'S_SPITZ12'   ,  24.          ,'vosaline',    .false.   , .false., 'daily'   , ''      , '' ,    ''
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     =  1        !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_usr      = .false.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_flx      = .false.   !  flux formulation                          (T => fill namsbc_flx )
+   ln_blk      = .true.    !  Bulk formulation                          (T => fill namsbc_blk )
+                     ! Sea-ice :
+   nn_ice      = 2         !  SI3
+   ln_ice_embd = .false.   !  =T embedded sea-ice (pressure + mass and salt exchanges)
+      !                    !  =F levitating ice (no pressure, mass and salt exchanges)
+                     ! Misc. options of sbc :
+   ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr )
+/
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR    = .true.     ! "NCAR"      algorithm   (Large and Yeager 2008)
+      !
+      ln_Cd_L12   = .false.   !  air-ice drags = F(ice concentration) (Lupkes et al. 2012)
+      ln_Cd_L15   = .true.    !  air-ice drags = F(ice concentration) (Lupkes et al. 2015)
+      !
+   cn_dir = './'  !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !          weights filename            ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'u10'     ,   .true.    , .false. , 'yearly'  , 'weights_bicub', 'Uwnd' , ''
+   sn_wndj     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'v10'     ,   .true.    , .false. , 'yearly'  , 'weights_bicub', 'Vwnd' , ''
+   sn_qsr      = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'ssrd'    ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_qlw      = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'strd'    ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_tair     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  't10'     ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_humi     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'humi'    ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_prec     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'precip'  ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_snow     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'snow'    ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_slp      = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'slp'     ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+   sn_tdif     = 'MARv3.6-9km-Svalbard-2hourly_spitz' ,  2. ,  'tdif'    ,   .true.    , .false. , 'yearly'  , 'weights_bilin', '' , ''
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.    !  =T Read in file ;  =F set all to 0. (see sbcssm)
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       ! type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.       !  RGB light penetration (Red-Green-Blue)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    2.     !  no slip
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tide     = .true.      ! Activate tides
+      ln_tide_pot   = .false.                !  use tidal potential forcing
+      clname(1)     =   'M2'    !  name of constituent
+      clname(2)     =   'S2'
+      clname(3)     =   'N2'
+      clname(4)     =   'K2'
+      clname(5)     =   'K1'
+      clname(6)     =   'O1'
+      clname(7)     =   'P1'
+      clname(8)     =   'Q1'
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+   ln_bdy         = .true.    !  Use unstructured open boundaries
+   nb_bdy         = 1         !  number of open boundary sets
+   ln_coords_file = .true.    !  =T : read bdy coordinates from file
+      cn_coords_file = 'coordinates_bdyr1_grid12.nc'  !  bdy coordinates files
+   cn_dyn2d    = 'flather'    !
+   nn_dyn2d_dta   =  3        !  = 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      =  'frs'     !
+   nn_dyn3d_dta  =  1         !  = 0, bdy data are equal to the initial state
+   !                          !  = 1, bdy data are read in 'bdydata   .nc' files
+   cn_tra        =  'frs'     !
+   nn_tra_dta    =  1         !  = 0, bdy data are equal to the initial state
+   !                          !  = 1, bdy data are read in 'bdydata   .nc' files
+   cn_ice        =  'frs'     !
+   nn_ice_dta    =  1         !  = 0, bdy data are equal to the initial state
+   !                          !  = 1, bdy data are read in 'bdydata   .nc' files
+   nn_rimwidth   = 1          !  width of the relaxation zone
+   ln_vol        = .false.    !  total volume correction (see nn_volctl parameter)
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+   ln_zinterp  = .false.      !  T if a vertical interpolation is required. Variables gdep[tuv] and e3[tuv] must exist in the file
+   !                          !  automatically defined to T if the number of vertical levels in bdy dta /= jpk
+   ln_full_vel = .false.      !  T if [uv]3d are "full" velocities and not only its baroclinic components
+   !                          !  in this case, baroclinic and barotropic velocities will be recomputed -> [uv]2d not needed
+   !
+   cn_dir  =  './'
+!              !  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 =   'bdyT_u2d_grid12' ,         72.      , 'sossheig' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_u2d =   'bdyU_u2d_grid12' ,         72.      , 'vobtcrtx' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_v2d =   'bdyV_u2d_grid12' ,         72.      , 'vobtcrty' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_u3d  =  'bdyU_u3d_grid12' ,         72.      , 'vozocrtx' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_v3d  =  'bdyV_u3d_grid12' ,         72.      , 'vomecrty' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_tem  =  'bdyT_tem_grid12' ,         72.      , 'votemper' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_sal  =  'bdyT_sal_grid12' ,         72.      , 'vosaline' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_a_i  =  'bdyT_ice_grid12' ,         72.      , 'ileadfra' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_h_i  =  'bdyT_ice_grid12' ,         72.      , 'iicethic' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+   bn_h_s  =  'bdyT_ice_grid12' ,         72.      , 'isnowthi' ,     .true.     , .false. ,  'yearly'  ,    ''    ,   ''   , ''
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+   filtide          = 'bdytide_grid12_'         !  file name root of tidal forcing files
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_loglayer = .true.   !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   ln_drgimp   = .true.   !  implicit top/bottom friction flag
+      ln_drgice_imp = .true. ! implicit ice-ocean drag
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+   rn_Cd0      =  2.5e-3   !  drag coefficient [-]
+   rn_Cdmax    =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0      =  0.       !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0       =  3.e-3    !  roughness [m] (ln_loglayer=T)
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.    !  Bottom Boundary Layer parameterisation flag
+      nn_bbl_ldf  =  1        !  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                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80
+   ln_teos10   = .false.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.     !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_blp   = .true.    !  bilaplacian operator
+   ln_traldf_iso   = .true.    !  iso-neutral (Standard operator)
+   ln_traldf_msc   = .true.    !  Method of Stabilizing Correction      (both operators)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 31        !  space/time variation of eddy coefficient:
+   !                                !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_eeT = .true.  !  energy conserving scheme (een using e3t)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+      ln_bt_fw      = .false.     ! Forward integration of barotropic Eqs.
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! adaptive-implicit vertical advection
+   ln_zad_Aimp = .true.      !  Courant number dependent scheme (Shchepetkin 2015)
+   !                       ! type of vertical closure (required)
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !                       ! convection
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+   !
+   ln_zdfddm   = .true.    ! double diffusive mixing
+   !
+   !                       !  Coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   2.0e-6     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    1         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   ln_mxl0     = .true.    !  surface mixing length scale = F(wind stress) (T) or not (F)
+      nn_mxlice    = 0        ! type of scaling under sea-ice
+                              !    = 0 no scaling under sea-ice
+                              !    = 1 scaling with constant sea-ice thickness
+                              !    = 2 scaling with mean sea-ice thickness ( only with SI3 sea-ice model )
+                              !    = 3 scaling with maximum sea-ice thickness
+   nn_eice     =   0       !  attenutaion of langmuir & surface wave breaking under ice
+   !                       !           = 0 no impact of ice cover on langmuir & surface wave breaking
+   !                       !           = 1 weigthed by 1-TANH(10*fr_i)
+   !                       !           = 2 weighted by 1-fr_i
+   !                       !           = 3 weighted by 1-MIN(1,4*fr_i)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diahsb   = .false.   !  check the heat and salt budgets (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+   nn_nchunks_k =   75      !  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
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,112 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =    10         !  number of ice  categories
+   nlay_i           =    5          !  number of ice  layers
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+   ln_cat_hfn       = .true.          !  ice categories are defined by a function following rn_himean**(-0.05)
+      rn_himean     =   2.0           !  expected domain-average ice thickness (m)
+   rn_himin         =   0.01          !  minimum ice thickness (m) used in remapping
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_landfast_L16  = .true.          !  landfast: parameterization from Lemieux 2016
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+   nn_snwfra        =   0             !  calculate the fraction of ice covered by snow (for zdf and albedo)
+                                      !     = 0  fraction = 1 (if snow) or 0 (if no snow)
+                                      !     = 1  fraction = 1-exp(-0.2*rhos*hsnw) [MetO formulation]
+                                      !     = 2  fraction = hsnw / (hsnw+0.02)    [CICE formulation]
+   nn_qtrice        =   0             !  Solar flux transmitted thru the surface scattering layer:
+                                      !     = 0  Grenfell and Maykut 1977 (depends on cloudiness and is 0 when there is snow)
+                                      !     = 1  Lebrun 2019 (equals 0.3 anytime with different melting/dry snw conductivities)
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+   rn_hinew         =   0.02          !  thickness for new ice formation in open water (m), must be larger than rn_himin
+   ln_frazil        = .true.          !  Frazil ice parameterization (ice collection as a function of wind)
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+   ln_pnd           = .false.          !  activate melt ponds or not
+     ln_pnd_LEV     = .false.          !  activate level ice melt ponds
+/
+
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.         !  activate ice initialization (T) or not (F)
+   rn_thres_sst     =   0.5           !  max delta temp. above Tfreeze with initial ice = (sst - tfreeze)
+   rn_hts_ini_n     =   0.1           !  initial real snow thickness (m), North
+   rn_hti_ini_n     =   1.0           !  initial real ice thickness  (m), North
+   rn_ati_ini_n     =   0.9           !  initial ice concentration   (-), North
+   rn_smi_ini_n     =   6.0           !  initial ice salinity     (g/kg), North
+   rn_tmi_ini_n     = 267.            !  initial ice/snw temperature (K), North
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/cpp_SPITZ12.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/cpp_SPITZ12.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/SPITZ12/cpp_SPITZ12.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys key_mpp_mpi key_iomput key_si3
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ref_cfgs.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ref_cfgs.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/cfgs/ref_cfgs.txt	(revision 14097)
@@ -0,0 +1,10 @@
+AGRIF_DEMO OCE ICE NST
+AMM12 OCE
+C1D_PAPA OCE
+GYRE_BFM OCE TOP
+GYRE_PISCES OCE TOP
+ORCA2_OFF_PISCES OCE TOP OFF
+ORCA2_OFF_TRC OCE TOP OFF
+ORCA2_SAS_ICE OCE ICE NST SAS
+ORCA2_ICE_PISCES OCE TOP ICE NST
+SPITZ12 OCE ICE
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/NEMO_manual_state.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/NEMO_manual_state.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/NEMO_manual_state.txt	(revision 14097)
@@ -0,0 +1,112 @@
+¤ Missing namelist groups in NEMO manual
+namage namagrif namalb namc14_fcg namc14_sbc namc14_typ namc1d namc1d_dyndmp namc1d_uvd namcfc namcrs namdia namdrg namdrg_bot namdrg_top namdta_dyn namdyn namdyn_rdgrft namdyn_rhg namforcing namhsb namini namitd namlobdet namlobdom namlobnut namlobopt namlobphy namlobrat namlobsed namlobzoo nammpp namp4zlim namp4zmes namp4zmort namp4zprod namp4zzoo namp5zlim namp5zmes namp5zmort namp5zprod namp5zquota namp5zzoo nampar nampisatm nampisbio nampiscal nampisdmp nampisext nampisfer nampisice nampislig nampismass nampismod nampisopt nampispoc nampisrem nampissbc namsbc_blk namsbc_iif namthd namthd_da namthd_do namthd_pnd namthd_sal namthd_zdf namtra_eiv namtra_mle namtrc namtrc_adv namtrc_bc namtrc_bdy namtrc_dmp namtrc_dta namtrc_ice namtrc_ldf namtrc_rad namtrc_run namtrc_snk namtrc_trd nam_vvl namzdf_iwm 
+
+¤ Vanished index entries in NEMO manual (\{hf,jp,key,mdl,ngn,nlst,np,rou}{...})
+chap_DYN.tex: key{dynspg\_exp} key{dynspg\_flt} key{dynspg\_ts} key{trddyn} key{trdvor} key{vvl} mdl{dynspg\_flt} mdl{zpsdhe} nlst{namsplit} np{ln\_bt\_nn\_auto} np{ln\_dynhpg\_djc} np{ln\_dynhpg\_imp} np{ln\_dynhpg\_isf} np{ln\_dynhpg\_prj} np{ln\_dynhpg\_sco} np{ln\_dynhpg\_vec} np{ln\_dynhpg\_zco} np{ln\_dynhpg\_zps} np{ln\_dynldf\_bilap} np{ln\_dynvor\_con} np{ln\_dynzad\_zts} np{ln\_traadv\_tvd\_zts} np{ln\_wd\_dl\_ramp} np{ln\_zdfexp} np{nn\_atfp} np{nn\_dynhpg\_rst} np{nn\_ice\_embd} np{nn\_zdfexp} 
+introduction.tex: 
+chap_model_basics_zstar.tex: key{dynspg\_exp} key{dynspg\_flt} key{dynspg\_ts} key{vvl} mdl{dynspg\_flt} np{rdtbt} np{rnu} 
+chap_DIA.tex: key{diaar5} key{diadct} key{diaharm} key{diahth} key{diainstant} key{floats} key{IOM} key{iomput} key{mpp\_mpi} key{netcdf4} key{trdmld\_trc} key{trdtrc} key{vvl} ngn{namdia\_harm} np{init\_float\_ariane} np{iom\_put} np{jpnflnewflo} np{nb\_ana} np{nit000} np{nitend} np{nn\_debug} np{nn\_diacfl} np{tname} rou{iom\_rstput} 
+annex_E.tex: key{traldf\_eiv} 
+chap_TRA.tex: jp{lk\_vvl} key{trabbl} key{traTTT} key{zdfddm} mdl{traldf\_lap} ngn{namtra\_bbc} np{ln\_flxqsr} np{ln\_sco} np{ln\_traadv\_NONE} np{ln\_traldf} np{ln\_traldf\_grif} np{ln\_traldf\_NONE} np{ln\_tsd\_tradmp} np{ln\_useCT} np{ln\_zco} np{ln\_zdfexp} np{ln\_zps} np{nn\_chdta} np{nn\_eos} np{nn\_fct\_zts} np{nn\_geoflx\_cst} np{nn\_zdfexp} rou{traldf\_blp} rou{traldf\_lap} 
+chap_DIU.tex: 
+chap_ASM.tex: key{asminc} ngn{namasm} 
+chap_ZDF.tex: key{dynspg\_exp} key{dynspg\_flt} key{dynspg\_ts} key{trabbl} key{vvl} key{zdf} key{zdfcst} key{zdfddm} key{zdfgls} key{zdfosm} key{zdfric} key{zdftke} key{zdftmx} key{zdftmx\_new} mdl{dynbfr} mdl{dynzdf\_imp} mdl{zdfbfr} mdl{zdfini} mdl{zdfkpp} ngn{namzdf\_ddm} ngn{namzdf\_tmx} ngn{namzdf\_tmx\_new} nlst{nambfr} nlst{namzdf_ddm} nlst{namzdf_tmx} nlst{namzdf_tmx_new} np{ln\_bfr2d} np{ln\_bfrimp} np{ln\_crban} np{ln\_tmx\_itf} np{ln\_tranpc} np{ln\_zdfexp} np{ln\_zdftmx\_itf} np{nn\_botfr} np{nn\_clo} np{nn\_ediff} np{nn\_ediss} np{nn\_tkebc\_bot} np{nn\_tkebc\_surf} np{rn\_avevd} np{rn\_bfeb2} np{rn\_bfri1} np{rn\_bfri2} np{rn\_bfri2\_max} np{rn\_bfrien} np{rn\_bfrz0} np{rn\_htmx} np{rn\_me} np{rn\_n2min} np{rn\_tfe} np{rn\_tfe\_itf} np{rn\_tfri2} np{rn\_tfri2\_max} np{rn\_tfrz0} rou{zdf\_bfr} 
+chap_OBS.tex: 
+chap_misc.tex: key{mpp\_mpi} key{nosignedzero} key{vectopt\_loop} np{iom\_get} np{jpjdta} np{jpjglo} np{nn\_bench} np{nn\_bit\_cmp} np{open\_ocean\_jstart} 
+chap_LDF.tex: hf{dynldf\_cNd} hf{ldfdyn\_substitute} hf{ldftra\_substitute} hf{traldf\_c1d} hf{traldf\_cNd} key{dynldf\_c1d} key{dynldf\_c2d} key{dynldf\_c3d} key{traldf\_c1d} key{traldf\_c2d} key{traldf\_c3d} key{traldf\_cNd} key{traldf\_eiv} mdl{ldfdyn\_c2d} mdl{ldfeiv} mdl{traadv\_eiv} np{ln\_dynldf\_bilap} np{ln\_sco} np{nn\_eos} np{rn\_aeih\_0} np{rn\_aeiv} np{rn\_aeiv\_0} np{rn\_ahm0} np{rn\_ahmb0} np{rn\_aht0} np{rn\_ahtb0} np{traldf\_grif} np{traldf\_grif\_iso} rou{ldf\_dyn\_c2d\_orca} rou{ldfslp\_init} 
+chap_LBC.tex: jp{jpreci} key{mpp\_mpi} np{jperio} np{jpiglo} np{jpindt} np{jpinft} np{jpjglo} np{jpjnob} np{nbdysegn} np{nn\_bdy\_jpk} np{nn\_msh} np{nn\_tra} rou{inimpp2} 
+chap_DOM.tex: key{mpp\_mpi} ngn{namzgr} ngn{namzgr\_sco} nlst{namzgr} nlst{namzgr_sco} np{jperio} np{jpiglo} np{jpjglo} np{jpkglo} np{ln\_sco} np{ln\_sigcrit} np{ln\_s\_SF12} np{ln\_s\_SH94} np{ln\_tsd\_ini} np{ln\_zco} np{ln\_zps} np{nn\_bathy} np{nn\_msh} np{ppa0} np{ppa1} np{ppacr} np{ppdzmin} np{pphmax} np{ppkth} np{ppsur} np{rn\_alpha} np{rn\_bb} np{rn\_e3zps\_min} np{rn\_e3zps\_rat} np{rn\_hc} np{rn\_rmax} np{rn\_sbot\_max} np{rn\_sbot\_min} np{rn\_theta} np{rn\_zb\_a} np{rn\_zb\_b} np{rn\_zs} rou{istate\_t\_s} 
+chap_conservation.tex: key{\_} 
+annex_iso.tex: key{trabbl} key{traldf\_eiv} np{ln\_traldf\_eiv} np{ln\_traldf\_gdia} 
+chap_time_domain.tex: np{ln\_zdfexp} np{nn\_dynhpg\_rst} np{nn\_zdfexp} 
+annex_C.tex: 
+chap_CONFIG.tex: key{agrif} key{c1d} key{dynspg\_ts} key{orca\_r12} key{orca\_r8} key{vvl} key{zdfgls} ngn{namusr\_def} np{jpiglo} np{jpizoom} np{jpjglo} np{jpjzoom} np{ln\_bench} np{nn\_GYRE} np{ORCA\_index} 
+chap_SBC.tex: key{cice} key{coupled} key{cpl\_carbon\_cycle} key{lim3} key{mpp\_mpi} key{nemocice\_decomp} key{oasis3} key{pisces} key{top} key{vvl} mdl{sbcana} mdl{sbc\_ana\_gyre} mdl{sbcsas} ngn{namsbc\_ana} ngn{namsbc\_clio} ngn{namsbc\_core} nlst{namsbc_ana} nlst{namsbc_clio} nlst{namsbc_core} np{clim} np{ln\_ana} np{ln\_blk\_clio} np{ln\_blk\_core} np{ln\_clio} np{ln\_core} np{ln\_rnf\_temp} np{nn\_nit000} np{nn\_tau000} np{nn\_test\_box} np{nz\_rnf} np{rn\_emp0} np{rn\_fiscpl} np{rn\_qns0} np{rn\_qsr0} np{rn\_utau0} np{rn\_vtau0} 
+chap_STO.tex: 
+
+¤ Namelist parameters unfollowing naming conventions (^[cdlnr]n_* or uppercase somewhere)
+     nam_asminc: nitbkg nitdin nitiaustr nitiaufin niaufn salfixmin
+         nambbc: sn_qgh
+         nambdy: nb_bdy nb_jpk_bdy ctypebdy nbdyind nbdybeg nbdyend
+     nambdy_dta: bn_ssh bn_u2d bn_v2d bn_u3d bn_v3d bn_tem bn_sal
+    nambdy_tide: filtide
+        namberg: rn_LoW_ratio sn_icb
+     namc14_fcg: cfileco2 cfilec14 tyrc14_beg
+     namc14_sbc: xkwind xdicsur
+     namc14_typ: kc14typ rc14at pco2at rc14init
+     namc1d_uvd: sn_ucur sn_vcur
+         namcfc: ndate_beg nyear_res clname
+         namdia: iiceprt jiceprt
+    nam_diaharm: nit000_han nitend_han nstep_han tname(1) tname(2)
+         namdrg: ln_OFF
+     namdrg_bot: rn_Cd0 rn_Uc0 rn_Cdmax
+     namdrg_top: rn_Cd0 rn_Uc0 rn_Cdmax
+     namdta_dyn: sn_tem sn_sal sn_mld sn_emp sn_fmf sn_ice sn_qsr sn_wnd sn_uwd sn_vwd sn_wwd sn_avt sn_ubl sn_vbl
+         namdyn: ln_dynALL ln_dynRHGADV ln_dynADV1D ln_dynADV2D ln_landfast_L16
+     namdyn_adv: ln_dynadv_OFF
+     namdyn_ldf: ln_dynldf_OFF rn_Uv rn_Lv
+  namdyn_rdgrft: ln_str_H79
+     namdyn_rhg: ln_rhg_EVP ln_aEVP
+     namdyn_vor: ln_dynvor_enT ln_dynvor_eeT
+         namflo: jpnfl jpnnewflo
+     namforcing: nice_jules
+         namini: sn_hti sn_hts sn_ati sn_tsu sn_tmi sn_smi
+      namlobdet: taudn fdetlab
+      namlobdom: taudomn
+      namlobnut: akno3 aknh4 taunn psinut
+      namlobopt: xkg0 xkr0 xkgp xkrp xlg xlr rpig
+      namlobphy: tmumax rgamma fphylab tmminp aki
+      namlobrat: rcchl redf reddom
+      namlobsed: sedlam sedlostpoc vsed xhr
+      namlobzoo: rppz taus aks rpnaz rdnaz tauzn fzoolab fdbod tmminz
+         nammpp: jpni jpnj
+      namp4zlim: concnno3 concdno3 concnnh4 concdnh4 concnfer concdfer concbfe concbnh4 concbno3 xsizedia xsizephy xsizern xsizerd xksi1 xksi2 xkdoc qnfelim qdfelim caco3r oxymin
+      namp4zmes: part2 grazrat2 resrat2 mzrat2 xpref2d xpref2n xpref2z xpref2c xthresh2zoo xthresh2dia xthresh2phy xthresh2poc xthresh2 xkgraz2 epsher2 epsher2min sigma2 unass2 grazflux
+     namp4zmort: wchl wchld wchldm mprat mprat2
+     namp4zprod: pislopen pisloped xadap excretn excretd bresp chlcnm chlcdm chlcmin fecnm fecdm grosip
+      namp4zzoo: part grazrat resrat mzrat xprefc xprefn xprefd xthreshdia xthreshphy xthreshpoc xthresh xkgraz epsher epshermin sigma1 unass
+      namp5zlim: concnno3 concpno3 concdno3 concnnh4 concpnh4 concdnh4 concnpo4 concppo4 concdpo4 concnfer concpfer concdfer concbfe concbnh4 concbno3 concbpo4 xsizedia xsizephy xsizepic xsizern xsizerp xsizerd xksi1 xksi2 xkdoc caco3r oxymin
+      namp5zmes: part2 grazrat2 bmetexc2 resrat2 mzrat2 xpref2d xpref2p xpref2z xpref2m xpref2c xthresh2zoo xthresh2dia xthresh2phy xthresh2mes xthresh2poc xthresh2 xkgraz2 epsher2 epsher2min ssigma2 srespir2 unass2c unass2n unass2p grazflux
+     namp5zmort: wchln wchlp wchld wchldm mpratn mpratp mprat2
+     namp5zprod: pislopen pislopep pisloped excretn excretp excretd xadap bresp thetannm thetanpm thetandm chlcmin grosip
+    namp5zquota: qfnopt qfpopt qfdopt qnnmin qnnmax qpnmin qpnmax qnpmin qnpmax qppmin qppmax qndmin qndmax qpdmin qpdmax qfnmax qfpmax qfdmax
+      namp5zzoo: part grazrat bmetexc resrat mzrat xprefc xprefn xprefp xprefd xprefz xthreshdia xthreshphy xthreshpic xthreshzoo xthreshpoc xthresh xkgraz epsher epshermin ssigma srespir unassc unassn unassp
+         nampar: jpl nlay_i nlay_s
+      nampisatm: sn_patm sn_atmco2
+      nampisbio: nrdttrc wsbio xkmort ferat3 wsbio2 wsbio2max wsbio2scale ldocp ldocz lthet no3rat3 po4rat3
+      nampiscal: kdca nca
+      nampisext: atcco2 clname
+      nampisfer: xlam1 xlamdust ligand kfep
+      nampisice: sn_tri_dic sn_tri_doc sn_tri_tal sn_tri_oxy sn_tri_cal sn_tri_po4 sn_tri_poc sn_tri_goc sn_tri_bfe sn_tri_num sn_tri_sil sn_tri_dsi sn_tri_gsi sn_tri_phy sn_tri_dia sn_tri_zoo sn_tri_mes sn_tri_fer sn_tri_sfe sn_tri_dfe sn_tri_nfe sn_tri_nch sn_tri_dch sn_tri_no3 sn_tri_nh4
+      nampislig: rlgw rlig prlgw rlgs
+      nampisopt: sn_par parlux
+      nampispoc: xremip jcpoc rshape xremipc xremipn xremipp
+      nampisrem: xremik nitrif xsirem xsiremlab xsilab feratb xkferb xremikc xremikn xremikp
+      nampissbc: sn_dust sn_solub sn_riverdic sn_riverdoc sn_riverdin sn_riverdon sn_riverdip sn_riverdop sn_riverdsi sn_ndepo sn_ironsed sn_hydrofe sedfeinput distcoast dustsolub mfrac wdust icefeinput nitrfix diazolight concfediaz hratio lgw_rath
+     namsbc_apr: sn_apr
+     namsbc_blk: ln_NCAR ln_COARE_3p0 ln_COARE_3p5 ln_ECMWF ln_Cd_L12 ln_Cd_L15 sn_wndi sn_wndj sn_qsr sn_qlw sn_tair sn_humi sn_prec sn_snow sn_slp sn_tdif
+     namsbc_cpl: sn_snd_temp sn_snd_alb sn_snd_thick sn_snd_crt sn_snd_co2 sn_snd_crtw sn_snd_ifrac sn_snd_wlev sn_snd_cond sn_snd_thick1 sn_snd_mpnd sn_snd_sstfrz sn_snd_ttilyr 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_co2 sn_rcv_hsig sn_rcv_iceflx sn_rcv_mslp sn_rcv_phioc sn_rcv_sdrfx sn_rcv_sdrfy sn_rcv_wper sn_rcv_wnum sn_rcv_wstrf sn_rcv_wdrag sn_rcv_ts_ice sn_rcv_isf sn_rcv_icb sn_rcv_tauwoc sn_rcv_tauw sn_rcv_wdrag
+     namsbc_flx: sn_utau sn_vtau sn_qtot sn_qsr sn_emp
+     namsbc_iif: sn_ice
+     namsbc_isf: sn_fwfisf sn_rnfisf sn_depmax_isf sn_depmin_isf sn_Leff_isf
+     namsbc_rnf: sn_rnf sn_cnf sn_s_rnf sn_t_rnf sn_dep_rnf
+     namsbc_sas: l_sasread sn_usp sn_vsp sn_tem sn_sal sn_ssh sn_e3t sn_frq
+     namsbc_ssr: sn_sst sn_sss
+    namsbc_wave: sn_cdg sn_usd sn_vsd sn_hsw sn_wmp sn_wfr sn_wnum sn_tauwoc sn_tauwx sn_tauwy
+         namthd: ln_icedH ln_icedA ln_icedO ln_icedS
+      namthd_do: rn_Cfraz
+     namthd_pnd: ln_pnd_H12 ln_pnd_CST
+     namthd_zdf: ln_zdf_BL99 ln_cndi_U64 ln_cndi_P07
+       nam_tide: rdttideramp clname(1)
+     namtra_adv: ln_traadv_OFF
+     namtra_eiv: rn_Ue rn_Le
+     namtra_ldf: ln_traldf_OFF rn_Ud rn_Ld
+     namtra_qsr: sn_chl
+         namtrc: jp_bgc jp_dia3d jp_dia2d
+     namtrc_adv: ln_trcadv_OFF
+     namtrc_dta: sn_trcdta(1)
+     namtrc_ldf: ln_trcldf_OFF
+     namtrc_snk: nitermax
+         namtrd: ln_KE_trd ln_PE_trd
+         namtsd: sn_tem sn_sal
+         namzdf: ln_zad_Aimp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/README.rst	(revision 14097)
@@ -0,0 +1,19 @@
+**************************
+Building the documentation
+**************************
+
+.. todo::
+
+
+
+:file:`latex`    : LaTeX sources and Latexmk configuration to build reference manuals with :file:`manual_build.sh`
+
+:file:`namelists`: Namelist blocks included in the documentation
+
+:file:`rst`      : |RST man|_ sources and Sphinx configuration to build this guide hereby with :file:`guide_build.sh`
+
+.. |RST man| replace:: reStructuredText (rst)
+
+.. warning::
+
+    Mention `svnignore` hidden file
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/guide_build.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/guide_build.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/guide_build.sh	(revision 14097)
@@ -0,0 +1,29 @@
+#!/bin/sh
+
+## Avoid the use of shell builtin echo (for -e option)
+alias echo='/bin/echo -e'
+
+## Check dependancies
+##-------------------
+
+## Sphinx, BibTeX extension and "Read The Docs" theme
+if [ -n "$( ./tools/check_pkg.py sphinx sphinxcontrib.bibtex sphinx_rtd_theme )" ]; then
+    echo 'One of the Python dependencies is missing => QUIT'
+    exit 2
+fi
+
+cd rst
+
+echo "\t¤ Clean previous build"
+make clean
+echo
+
+echo "\t¤ Generation of the guide"
+make html > /dev/null
+echo
+
+echo "\t¤ End of building run"
+echo "Open ./rst/build/html/NEMO_guide.html"
+cd - > /dev/null
+
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/.svnignore
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/.svnignore	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/.svnignore	(revision 14097)
@@ -0,0 +1,17 @@
+*.aux
+*.bbl
+*.blg
+*.dvi
+*.fdb*
+*.fls
+*.idx
+*.ilg
+*.ind
+*.lo*
+*.maf
+*.mtc*
+*.out
+*.pdf
+*.toc
+*.xdv
+_minted-*
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/DEPS
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/DEPS	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/DEPS	(revision 14097)
@@ -0,0 +1,58 @@
+amsmath
+babel
+caption
+capt-of
+carlisle
+cmap
+courier
+draftwatermark
+ec
+enumitem
+epstopdf
+etoolbox
+everypage
+fancyhdr
+fancyvrb
+float
+fncychap
+framed
+fvextra
+geometry
+graphics
+graphics-cfg
+helvetic
+hyperref
+ifplatform
+imakeidx
+koma-script
+latex
+latexconfig
+latex-bin
+latex-fonts
+latexmk
+lineno
+lm
+marvosym
+minitoc
+minted
+natbib
+needspace
+oberdiek
+parskip
+preview
+psnfss
+subfiles
+tabulary
+times
+titlesec
+titling
+tools
+upquote
+url
+varwidth
+wrapfig
+xcolor
+xkeyval
+xstring
+zapfchan
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_htlatex.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_htlatex.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_htlatex.sh	(revision 14097)
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+./inc/clean.sh
+./inc/build.sh
+
+mkdir -p html_htlatex
+cd tex_main
+htlatex NEMO_manual "NEMO_manual,2" "" "-d../html_htlatex/" "-shell-escape"
+cd -
+
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_latex2html.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_latex2html.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/HTML_latex2html.sh	(revision 14097)
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+#./inc/clean.sh
+#./inc/build.sh
+
+sed -i -e 's#utf8#latin1#'                                 \
+       -e 's#\[outputdir=../build\]{minted}#\[\]{minted}#' \
+       -e '/graphicspath/ s#{../#{../../#g'                \
+          global/packages.tex
+
+cd ./NEMO/main
+sed -i -e 's#\\documentclass#%\\documentclass#' -e '/{document}/ s#^#%#'   ../subfiles/*.tex
+sed -i    's#\\subfile{#\\input{#'                                         chapters.tex appendices.tex
+
+#latex2html                                   -noimages -local_icons -no_footnode -split 4 -link 2 -dir ../html_LaTeX2HTML $*	NEMO_manual
+latex2html -debug -noreuse -init_file ../../l2hconf.pm -local_icons                               -dir ../build/html               NEMO_manual
+
+sed -i -e 's#%\\documentclass#\\documentclass#' -e '/{document}/ s#^%##'   ../subfiles/*.tex
+sed -i    's#\\input{#\\subfile{#'                                         chapters.tex appendices.tex
+cd -
+
+sed -i -e 's#latin1#utf8#'                                 \
+       -e 's#\[\]{minted}#\[outputdir=../build\]{minted}#' \
+       -e '/graphicspath/ s#{../../#{../#g'                \
+	  global/packages.tex
+
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.cfg	(revision 14097)
@@ -0,0 +1,10 @@
+\Preamble{xhtml,mathml}
+
+\Configure{@HEAD}{%
+\HCode{<script type="text/javascript"
+   src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=MML_CHTML">
+ </script>\Hnewline}}
+
+\begin{document}
+
+\EndPreamble
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/NEMO_manual.tex	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../global/document.tex
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/abstract.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/abstract.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/abstract.tex	(revision 14097)
@@ -0,0 +1,27 @@
+%% ================================================================
+%% Abstract
+%% ================================================================
+
+%% Common part between NEMO-SI3-TOP
+\NEMO\ (``Nucleus for European Modelling of the Ocean'') is a framework of ocean-related engines.
+It is intended to be a flexible tool for studying the ocean dynamics and thermodynamics (``blue ocean''),
+as well as its interactions with the components of the Earth climate system over
+a wide range of space and time scales.
+Within \NEMO, the ocean engine is interfaced with a sea-ice model (\SIcube\ or
+\href{http://github.com/CICE-Consortium/CICE}{CICE}),
+passive tracers and biogeochemical models (\TOP) and,
+via the \href{http://portal.enes.org/oasis}{OASIS} coupler,
+with several atmospheric general circulation models.
+It also supports two-way grid embedding by means of the \href{http://agrif.imag.fr}{AGRIF} software.
+
+%% Specific part
+The primitive equation model is adapted to regional and global ocean circulation problems down to
+kilometric scale.
+Prognostic variables are the three-dimensional velocity field, a non-linear sea surface height,
+the \textit{Conservative} Temperature and the \textit{Absolute} Salinity.
+In the horizontal direction, the model uses a curvilinear orthogonal grid and
+in the vertical direction, a full or partial step $z$-coordinate, or $s$-coordinate, or
+a mixture of the two.
+The distribution of variables is a three-dimensional Arakawa C-type grid.
+Various physical choices are available to describe ocean physics,
+so as various HPC functionalities to improve performances.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/appendices.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/appendices.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/appendices.tex	(revision 14097)
@@ -0,0 +1,12 @@
+
+\subfile{../subfiles/apdx_s_coord}      %% A. Generalised vertical coordinate
+\subfile{../subfiles/apdx_diff_opers}   %% B. Diffusive operators
+\subfile{../subfiles/apdx_invariants}   %% C. Discrete invariants of the eqs.
+\subfile{../subfiles/apdx_triads}       %% D. Isoneutral diffusion using triads
+\subfile{../subfiles/apdx_DOMAINcfg}    %% E. Brief notes on DOMAINcfg
+
+%% Not included
+%\subfile{../subfiles/chap_model_basics_zstar}
+%\subfile{../subfiles/chap_DIU}
+%\subfile{../subfiles/chap_conservation}
+%\subfile{../subfiles/apdx_algos}   %% Notes on some on going staff
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/authors.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/authors.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/authors.tex	(revision 14097)
@@ -0,0 +1,50 @@
+%Romain Bourdall\'{e}-Badie
+%\orcid{0000-0002-8742-3289} \\
+%Mike Bell                   \\
+%J\'{e}r\^{o}me Chanut       \\
+%Emanuela Clementi
+%\orcid{0000-0002-5752-1849} \\
+%Andrew Coward
+%\orcid{0000-0002-0456-129X} \\
+%Massimiliano Drudi
+%\orcid{0000-0002-9951-740X} \\
+%Christian \'{E}th\'{e}      \\
+%Doroteaciro Iovino
+%\orcid{0000-0001-5132-7255} \\
+%Dan Lea                     \\
+%Claire L\'{e}vy
+%\orcid{0000-0003-2518-6692} \\
+%Gurvan Madec
+%\orcid{0000-0002-6447-4198} \\
+%Nicolas Martin              \\
+%S\'{e}bastien Masson
+%\orcid{0000-0002-1694-8117} \\
+%Pierre Mathiot              \\
+%Silvia Mocavero
+%\orcid{0000-0002-6309-8282} \\
+%Simon M\"{u}ller            \\
+%George Nurser               \\
+%Guillaume Samson
+%\orcid{0000-0001-7481-6369} \\
+%Dave Storkey
+
+\orcid{0000-0002-8742-3289} Romain Bourdall\'{e}-Badie  \\
+                            Mike Bell                   \\
+                            J\'{e}r\^{o}me Chanut       \\
+\orcid{0000-0002-5752-1849} Emanuela Clementi           \\
+\orcid{0000-0002-0456-129X} Andrew Coward               \\
+\orcid{0000-0002-9951-740X} Massimiliano Drudi          \\
+                            Christian \'{E}th\'{e}      \\
+\orcid{0000-0001-5132-7255} Doroteaciro Iovino          \\
+                            Dan Lea                     \\
+\orcid{0000-0003-2518-6692} Claire L\'{e}vy             \\
+\orcid{0000-0002-6447-4198} Gurvan Madec                \\
+                            Nicolas Martin              \\
+\orcid{0000-0002-1694-8117} S\'{e}bastien Masson        \\
+                            Pierre Mathiot              \\
+\orcid{0000-0002-6309-8282} Silvia Mocavero             \\
+                            Simon M\"{u}ller            \\
+                            George Nurser               \\
+\orcid{0000-0001-7481-6369} Guillaume Samson            \\
+                            Dave Storkey                \\
+%% Don't forget the last break for the right alignment
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/bibliography.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/bibliography.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/bibliography.bib	(revision 14097)
@@ -0,0 +1,3135 @@
+
+@article{         adcroft.campin_OM04,
+  title         = "Rescaled height coordinates for accurate representation of
+                  free-surface flows in ocean circulation models",
+  pages         = "269--284",
+  journal       = "Ocean Modelling",
+  volume        = "7",
+  number        = "3-4",
+  author        = "A. Adcroft and J.-M. Campin",
+  year          = "2004",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2003.09.003"
+}
+
+@article{         arakawa.hsu_MWR90,
+  title         = "Energy Conserving and Potential-Enstrophy Dissipating
+                  Schemes for the Shallow Water Equations",
+  pages         = "1960--1969",
+  journal       = "Monthly Weather Review",
+  volume        = "118",
+  number        = "10",
+  author        = "A. Arakawa and Y.-J. G. Hsu",
+  year          = "1990",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1990)118<1960:ecaped>2.0.co;2"
+}
+
+@article{         arakawa.lamb_MWR81,
+  title         = "A Potential Enstrophy and Energy Conserving Scheme for the
+                  Shallow Water Equations",
+  pages         = "18--36",
+  journal       = "Monthly Weather Review",
+  volume        = "109",
+  number        = "1",
+  author        = "A. Arakawa and V. R. Lamb",
+  year          = "1981",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1981)109<0018:apeaec>2.0.co;2"
+}
+
+@article{         arakawa_JCP66,
+  title         = "Computational design for long-term numerical integration
+                  of the equations of fluid motion: Two-dimensional
+                  incompressible flow. Part {I}",
+  pages         = "119--143",
+  journal       = "Journal of Computational Physics",
+  volume        = "1",
+  number        = "1",
+  author        = "A. Arakawa",
+  year          = "1966",
+  month         = "Aug",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1016/0021-9991(66)90015-5"
+}
+
+@article{         arbic.garner.ea_DSR04,
+  title         = "The accuracy of surface elevations in forward global
+                  barotropic and baroclinic tide models",
+  pages         = "3069--3101",
+  journal       = "Deep Sea Research",
+  volume        = "51",
+  number        = "25-26",
+  author        = "B. K. Arbic and S. T. Garner and R. W. Hallberg and H. L.
+                  Simmons",
+  year          = "2004",
+  month         = "dec",
+  publisher     = "Elsevier BV",
+  issn          = "0967-0645",
+  doi           = "10.1016/j.dsr2.2004.09.014"
+}
+
+@article{         artale.iudicone.ea_JGR02,
+  title         = "Role of surface fluxes in Ocean General Circulation Models
+                  using satellite sea surface temperature: Validation of and
+                  sensitivity to the forcing frequency of the Mediterranean
+                  thermohaline circulation",
+  pages         = "2901--2924",
+  journal       = "Journal of Geophysical Research",
+  volume        = "107",
+  number        = "C8",
+  author        = "V. Artale and D. Iudicone and R. Santoleri and V. Rupolo
+                  and S. Marullo and F. {D'O}rtenzio",
+  year          = "2002",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2000jc000452"
+}
+
+@article{         asselin_MWR72,
+  title         = "Frequency Filter for Time Integrations",
+  pages         = "487--490",
+  journal       = "Monthly Weather Review",
+  volume        = "100",
+  number        = "6",
+  author        = "R. Asselin",
+  year          = "1972",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1972)100<0487:fffti>2.3.co;2"
+}
+
+@article{         axell_JGR02,
+  title         = "Wind-driven internal waves and Langmuir circulations in a
+                  numerical ocean model of the southern Baltic Sea",
+  journal       = "Journal of Geophysical Research",
+  volume        = "107",
+  number        = "C11",
+  author        = "L. B. Axell",
+  year          = "2002",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2001jc000922"
+}
+
+@article{         barnier.madec.ea_OD06,
+  title         = "Impact of partial steps and momentum advection schemes in
+                  a global ocean circulation model at eddy-permitting
+                  resolution",
+  pages         = "543--567",
+  journal       = "Ocean Dynamics",
+  volume        = "56",
+  number        = "5-6",
+  author        = "B. Barnier and G. Madec and T. Penduff and J.-M. Molines
+                  and A.-M. Tr\'{e}guier and J. {Le Sommer} and A. Beckmann
+                  and A. Biastoch and C. B{\"{o}}ning and J. Dengg and C.
+                  Derval and E. Durand and S. Gulev and E. Remy and C.
+                  Talandier and S. Theetten and M. Maltrud and J. McClean and
+                  B. {de Cuevas}",
+  year          = "2006",
+  month         = "jun",
+  publisher     = "Springer Nature",
+  issn          = "1616-7228",
+  doi           = "10.1007/s10236-006-0082-1"
+}
+
+@article{         beckmann.doscher_JPO97,
+  title         = "A method for improved representation of dense water
+                  spreading over topography in geopotential-coordinate
+                  models",
+  pages         = "581--591",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "27",
+  number        = "4",
+  author        = "A. Beckmann and R. D{\"{o}}scher",
+  year          = "1997",
+  month         = "apr",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1997)027<0581:amfiro>2.0.co;2"
+}
+
+@article{         beckmann.goosse_OM03,
+  title         = "A parameterization of ice shelf-ocean interaction for
+                  climate models",
+  pages         = "157--170",
+  journal       = "Ocean Modelling",
+  volume        = "5",
+  number        = "2",
+  author        = "A. Beckmann and H. Goosse",
+  year          = "2003",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/s1463-5003(02)00019-7"
+}
+
+@article{         beckmann.haidvogel_JPO93,
+  title         = "Numerical Simulation of Flow around a Tall Isolated
+                  Seamount. Part {I}: Problem Formulation and Model Accuracy",
+  pages         = "1736--1753",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "23",
+  number        = "8",
+  author        = "A. Beckmann and D. B. Haidvogel",
+  year          = "1993",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1993)023<1736:nsofaa>2.0.co;2"
+}
+
+@article{ beljaars_QJRMS95,
+title = "The parametrization of surface fluxes in large-scale models under free convection",
+pages = "255--270",
+journal = "Quarterly Journal of the Royal Meteorological Society",
+volume = "121",
+number = "522",
+author = "Beljaars, Anton C. M.",
+year = "1995",
+month = "jan",
+ publisher     = "Wiley",
+issn = "00359009",
+doi = "10.1002/qj.49712152203"
+}
+
+@article{         bernie.guilyardi.ea_CD07,
+  title         = "Impact of resolving the diurnal cycle in an
+                  ocean-atmosphere {GCM}. Part 1: a diurnally forced {OGCM}",
+  pages         = "575--590",
+  journal       = "Climate Dynamics",
+  volume        = "29",
+  number        = "6",
+  author        = "D. J. Bernie and E. Guilyardi and G. Madec and J. M.
+                  Slingo and S. J. Woolnough",
+  year          = "2007",
+  month         = "may",
+  publisher     = "Springer Nature",
+  issn          = "1432-0894",
+  doi           = "10.1007/s00382-007-0249-6"
+}
+
+@article{         bernie.woolnough.ea_JC05,
+  title         = "Modeling diurnal and intraseasonal variability of the
+                  ocean mixed layer",
+  pages         = "1190--1202",
+  journal       = "Journal of Climate",
+  volume        = "18",
+  number        = "8",
+  author        = "D. J. Bernie and S. J. Woolnough and J. M. Slingo and E.
+                  Guilyardi",
+  year          = "2005",
+  month         = "apr",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0442",
+  doi           = "10.1175/jcli3319.1"
+}
+
+@article{         blanke.delecluse_JPO93,
+  title         = "Variability of the tropical Atlantic Ocean simulated by a
+                  General Circulation Model with two different mixed-layer
+                  physics",
+  pages         = "1363--1388",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "23",
+  number        = "7",
+  author        = "B. Blanke and P. Del\'{e}cluse",
+  year          = "1993",
+  month         = "jul",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1993)023<1363:vottao>2.0.co;2"
+}
+
+@article{         blanke.raynaud_JPO97,
+  title         = "Kinematics of the Pacific Equatorial Undercurrent: An
+                  Eulerian and Lagrangian Approach from {GCM} Results",
+  pages         = "1038--1053",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "27",
+  number        = "6",
+  author        = "B. Blanke and S. Raynaud",
+  year          = "1997",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1997)027<1038:kotpeu>2.0.co;2"
+}
+
+@article{         bloom.takacs.ea_MWR96,
+  title         = "Data assimilation using incremental analysis updates",
+  pages         = "1256--1271",
+  journal       = "Monthly Weather Review",
+  volume        = "124",
+  number        = "6",
+  author        = "S. C. Bloom and L. L. Takacs and A. M. Da Silva and D.
+                  Ledvina",
+  year          = "1996",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1996)124<1256:dauiau>2.0.co;2"
+}
+
+@article{         bouffard.boegman_DAO13,
+  title         = "A diapycnal diffusivity model for stratified environmental
+                  flows",
+  pages         = "14--34",
+  journal       = "Dynamics of Atmospheres and Oceans",
+  volume        = "61-62",
+  author        = "D. Bouffard and L. Boegman",
+  year          = "2013",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "0377-0265",
+  doi           = "10.1016/j.dynatmoce.2013.02.002"
+}
+
+@article{         bougeault.lacarrere_MWR89,
+  title         = "Parameterization of Orography-Induced Turbulence in a
+                  Mesobeta--Scale Model",
+  pages         = "1872--1890",
+  journal       = "Monthly Weather Review",
+  volume        = "117",
+  number        = "8",
+  author        = "P. Bougeault and P. Lacarrere",
+  year          = "1989",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1989)117<1872:pooiti>2.0.co;2"
+}
+
+@article{         bouillon.maqueda.ea_OM09,
+  title         = "An elastic-viscous-plastic sea ice model formulated on
+                  Arakawa {B} and {C} grids",
+  pages         = "174--184",
+  journal       = "Ocean Modelling",
+  volume        = "27",
+  number        = "3-4",
+  author        = "S. Bouillon and M. A. Morales Maqueda and V. Legat and T.
+                  Fichefet",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2009.01.004"
+}
+
+@article{         brankart.candille.ea_GMD15,
+  title         = "A generic approach to explicit simulation of uncertainty
+                  in the {NEMO} ocean model",
+  pages         = "1285--1297",
+  journal       = "Geoscientific Model Development",
+  volume        = "8",
+  number        = "5",
+  author        = "J.-M. Brankart and G. Candille and F. Garnier and C.
+                  Calone and A. Melet and P.-A. Bouttier and P. Brasseur and
+                  J. Verron",
+  year          = "2015",
+  month         = "may",
+  publisher     = "Copernicus GmbH",
+  issn          = "1991-9603",
+  doi           = "10.5194/gmd-8-1285-2015"
+}
+
+@article{         brankart_OM13,
+  title         = "Impact of uncertainties in the horizontal density gradient
+                  upon low resolution global ocean modelling",
+  pages         = "64--76",
+  journal       = "Ocean Modelling",
+  volume        = "66",
+  author        = "J.-M. Brankart",
+  year          = "2013",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2013.02.004"
+}
+
+@article{         breivik.bidlot.ea_OM16,
+  title         = "A Stokes drift approximation based on the Phillips
+                  spectrum",
+  pages         = "49--56",
+  journal       = "Ocean Modelling",
+  volume        = "100",
+  author        = "{\O}. Breivik and J.-R. Bidlot and P. A. E. M. Janssen",
+  year          = "2016",
+  month         = "apr",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2016.01.005"
+}
+
+@article{         breivik.janssen.ea_JPO14,
+  title         = "Approximate Stokes Drift Profiles in Deep Water",
+  pages         = "2433--2445",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "44",
+  number        = "9",
+  author        = "{\O}. Breivik and P. A. E. M. Janssen and J.-R. Bidlot",
+  year          = "2014",
+  month         = "sep",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/jpo-d-14-0020.1"
+}
+
+@article{         brodeau.barnier.ea_OM10,
+  title         = "An {ERA40}-based atmospheric forcing for global ocean
+                  circulation models",
+  pages         = "88--104",
+  journal       = "Ocean Modelling",
+  volume        = "31",
+  number        = "3-4",
+  author        = "L. Brodeau and B. Barnier and A.-M. Tr\'{e}guier and T.
+                  Penduff and S. Gulev",
+  year          = "2010",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2009.10.005"
+}
+
+@article{         brodeau.barnier.ea_JPO16,
+  title         = "Climatologically Significant Effects of Some Approximations in the Bulk Parameterizations of Turbulent Air–Sea Fluxes",
+  pages         = "5--28",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "47",
+  number        = "1",
+  author        = "Brodeau, Laurent and Barnier, Bernard and Gulev, Sergey K. and Woods, Cian",
+  year          = "2016",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "0022-3670",
+  doi           = "10.1175/jpo-d-16-0169.1",
+}
+
+@article{         brown.campana_MWR78,
+  title         = "An economical time-differencing system for numerical
+                  weather prediction",
+  pages         = "1125--1136",
+  journal       = "Monthly Weather Review",
+  volume        = "106",
+  number        = "8",
+  author        = "J. A. Brown and K. A. Campana",
+  year          = "1978",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1978)106<1125:aetsfn>2.0.co;2"
+}
+
+@article{         bryan_JCP97,
+  title         = "A numerical method for the study of the circulation of the
+                  world ocean",
+  pages         = "154--169",
+  journal       = "Journal of Computational Physics",
+  volume        = "135",
+  number        = "2",
+  author        = "K. Bryan",
+  year          = "1997",
+  month         = "Aug",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1006/jcph.1997.5699"
+}
+
+@article{         burchard_OM02,
+  title         = "Energy-conserving discretisation of turbulent shear and
+                  buoyancy production",
+  pages         = "347--361",
+  journal       = "Ocean Modelling",
+  volume        = "4",
+  number        = "3-4",
+  author        = "H. Burchard",
+  year          = "2002",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/s1463-5003(02)00009-4"
+}
+
+@article{         campin.adcroft.ea_OM04,
+  title         = "Conservation of properties in a free-surface model",
+  pages         = "221--244",
+  journal       = "Ocean Modelling",
+  volume        = "6",
+  number        = "3-4",
+  author        = "J.-M. Campin and A. Adcroft and C. Hill and J. Marshall",
+  year          = "2004",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/s1463-5003(03)00009-x"
+}
+
+@article{         campin.goosse_T99,
+  title         = "Parameterization of density-driven downsloping flow for a
+                  coarse-resolution ocean model in z-coordinate",
+  pages         = "412--430",
+  journal       = "Tellus A",
+  volume        = "51",
+  number        = "3",
+  author        = "J.-M. Campin and H. Goosse",
+  year          = "1999",
+  month         = "may",
+  publisher     = "Informa UK Limited",
+  issn          = "1600-0870",
+  doi           = "10.1034/j.1600-0870.1999.t01-3-00006.x"
+}
+
+@article{         campin.marshall.ea_OM08,
+  title         = "Sea ice-ocean coupling using a rescaled vertical
+                  coordinate \zstar",
+  pages         = "1--14",
+  journal       = "Ocean Modelling",
+  volume        = "24",
+  number        = "1-2",
+  author        = "J.-M. Campin and J. Marshall and D. Ferreira",
+  year          = "2008",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2008.05.005"
+}
+
+@article{         canuto.howard.ea_JPO01,
+  title         = "Ocean turbulence. Part {I}: One-point closure
+                  model-momentum and heat vertical diffusivities",
+  pages         = "1413--1426",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "31",
+  number        = "6",
+  author        = "V. M. Canuto and A. Howard and Y. Cheng and M. S.
+                  Dubovikov",
+  year          = "2001",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(2001)031<1413:otpiop>2.0.co;2"
+}
+
+@article{         carrere.lyard_GRL03,
+  title         = "Modeling the barotropic response of the global ocean to
+                  atmospheric wind and pressure forcing - comparisons with
+                  observations",
+  journal       = "Geophysical Research Letters",
+  volume        = "30",
+  number        = "6",
+  author        = "L. Carr\`{e}re and F. Lyard",
+  year          = "2003",
+  month         = "mar",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0094-8276",
+  doi           = "10.1029/2002gl016473"
+}
+
+@techreport{      chanut_rpt05,
+  title         = "Nesting code for {NEMO}",
+  pages         = "25",
+  author        = "J. Chanut",
+  institution   = "European Union: Marine Environment and Security for the
+                  European Area (MERSEA) Integrated Project",
+  year          = "2005",
+  month         = "may",
+  doi           = "10.5281/zenodo.3243409"
+}
+
+@article{         chassignet.smith.ea_JPO03,
+  title         = "North Atlantic Simulations with the Hybrid Coordinate
+                  Ocean Model ({HYCOM}): Impact of the Vertical Coordinate
+                  Choice, Reference Pressure, and Thermobaricity",
+  pages         = "2504--2526",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "33",
+  number        = "12",
+  author        = "E. P. Chassignet and L. T. Smith and G. R. Halliwell and
+                  R. Bleck",
+  year          = "2003",
+  month         = "dec",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(2003)033<2504:naswth>2.0.co;2"
+}
+
+@article{         cox_OM87,
+  title         = "Isopycnal diffusion in a z-coordinate ocean model",
+  pages         = "1--9",
+  journal       = "Ocean Modelling",
+  volume        = "74",
+  author        = "M. D. Cox",
+  year          = "1987",
+  month         = "jan",
+  url           = "https://www.researchgate.net/publication/243768762_Isopycnal_diffusion_in_a_z-coordinate_ocean_model"
+}
+
+@article{         craig.banner_JPO94,
+  title         = "Modeling wave-enhanced turbulence in the ocean surface
+                  layer",
+  pages         = "2546--2559",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "24",
+  number        = "12",
+  author        = "P. D. Craig and M. L. Banner",
+  year          = "1994",
+  month         = "dec",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1994)024<2546:mwetit>2.0.co;2"
+}
+
+@article{         craik.leibovich_JFM76,
+  title         = "A rational model for Langmuir circulations",
+  pages         = "401--426",
+  journal       = "Journal of Fluid Mechanics",
+  volume        = "73",
+  number        = "3",
+  author        = "A. D. D. Craik and S. Leibovich",
+  year          = "1976",
+  month         = "feb",
+  publisher     = "Cambridge University Press (CUP)",
+  issn          = "1469-7645",
+  doi           = "10.1017/s0022112076001420"
+}
+
+@article{         dalessio.abdella.ea_JPO98,
+  title         = "A new second-order turbulence closure scheme for modeling
+                  the oceanic mixed layer",
+  pages         = "1624--1641",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "28",
+  number        = "8",
+  author        = "S. J. D. D'Alessio and K. Abdella and N. A. McFarlane",
+  year          = "1998",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1998)028<1624:ansotc>2.0.co;2"
+}
+
+@book{            daley.barker_bk01,
+  pages         = "163",
+  booktitle     = "{NAVDAS} Source Book 2001: {NRL} Atmospheric Variational
+                  Data Assimilation System",
+  editor        = "Naval Research Laboratory, Marine Meteorology Division",
+  author        = "R. Daley and E. Barker",
+  year          = "2001",
+  month         = "jul",
+  publisher     = "Defense Technical Information Center",
+  doi           = "10.21236/ada396883"
+}
+
+@article{         danabasoglu.ferrari.ea_JC08,
+  title         = "Sensitivity of an Ocean General Circulation Model to a
+                  parameterization of near-surface eddy fluxes",
+  pages         = "1192--1208",
+  journal       = "Journal of Climate",
+  volume        = "21",
+  number        = "6",
+  author        = "G. Danabasoglu and R. Ferrari and J. C. McWilliams",
+  year          = "2008",
+  month         = "mar",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0442",
+  doi           = "10.1175/2007jcli1508.1"
+}
+
+@article{         davies_QJRMS76,
+  title         = "A lateral boundary formulation for multi-level prediction
+                  models",
+  pages         = "405--418",
+  journal       = "Quarterly Journal of the Royal Meteorological Society",
+  volume        = "102",
+  number        = "432",
+  author        = "H. C. Davies",
+  year          = "1976",
+  month         = "apr",
+  publisher     = "Wiley",
+  issn          = "0035-9009",
+  doi           = "10.1002/qj.49710243210"
+}
+
+@article{         de-boyer-montegut.madec.ea_JGR04,
+  title         = "Mixed layer depth over the global ocean: An examination of
+                  profile data and a profile-based climatology",
+  pages         = "C12003",
+  journal       = "Journal of Geophysical Research",
+  volume        = "109",
+  number        = "C12",
+  author        = "C. {de Boyer Mont\'{e}gut} and G. Madec and A. S. Fischer
+                  and A. Lazar and D. Iudicone",
+  year          = "2004",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2004jc002378"
+}
+
+@article{         de-lavergne.madec.ea_JPO16,
+  title         = "The impact of a variable mixing efficiency on the abyssal
+                  overturning",
+  pages         = "663--681",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "46",
+  number        = "2",
+  author        = "C. {de Lavergne} and G. Madec and J. {Le Sommer} and A. J.
+                  G. Nurser and A. C. Naveira Garabato",
+  year          = "2016",
+  month         = "feb",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/jpo-d-14-0259.1"
+}
+
+@article{         debreu.vouland.ea_CG08,
+  title         = "{AGRIF}: Adaptive Grid Refinement In Fortran",
+  pages         = "8--13",
+  journal       = "Computers \& Geosciences",
+  volume        = "34",
+  number        = "1",
+  author        = "L. Debreu and C. Vouland and E. Blayo",
+  year          = "2008",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "0098-3004",
+  doi           = "10.1016/j.cageo.2007.01.009"
+}
+
+@incollection{    delecluse.madec_icol99,
+  title         = "Ocean modelling and the role of the ocean in the climate
+                  system",
+  pages         = "237--313",
+  booktitle     = "Modeling the Earth's Climate and its Variability",
+  editor        = "W. R. Holland and S. Joussaume and F. David",
+  series        = "Les Houches",
+  volume        = "67",
+  author        = "P. Del\'{e}cluse and G. Madec",
+  year          = "1999",
+  publisher     = "North Holland",
+  isbn          = "978-0-444-50338-1"
+}
+
+@phdthesis{       demange_phd14,
+  title         = "Advection and gravity waves propagation numerical schemes
+                  for oceanic circulation models",
+  pages         = "138",
+  author        = "J. Demange",
+  school        = "Grenoble University, France",
+  year          = "2014",
+  url           = "https://tel.archives-ouvertes.fr/tel-01104703/file/DEMANGE_2014_archivage.pdf"
+}
+
+@article{         dobricic.pinardi.ea_OS07,
+  title         = "Daily oceanographic analyses by Mediterranean Forecasting
+                  System at the basin scale",
+  pages         = "149--157",
+  journal       = "Ocean Science",
+  volume        = "3",
+  number        = "1",
+  author        = "S. Dobricic and N. Pinardi and M. Adani and M. Tonani and
+                  C. Fratianni and A. Bonazzi and V. Fernandez",
+  year          = "2007",
+  month         = "mar",
+  publisher     = "Copernicus GmbH",
+  issn          = "1812-0792",
+  doi           = "10.5194/os-3-149-2007"
+}
+
+@article{         drijfhout_JPO94,
+  title         = "Heat transport by mesoscale eddies in an ocean circulation
+                  Model",
+  pages         = "353--369",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "24",
+  number        = "2",
+  author        = "S. S. Drijfhout",
+  year          = "1994",
+  month         = "feb",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1994)024<0353:htbmei>2.0.co;2"
+}
+
+@article{         dukowicz.smith_JGR94,
+  title         = "Implicit free-surface method for the Bryan-Cox-Semtner
+                  ocean model",
+  pages         = "7991--8014",
+  journal       = "Journal of Geophysical Research",
+  volume        = "99",
+  number        = "C4",
+  author        = "J. K. Dukowicz and R. D. Smith",
+  year          = "1994",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/93jc03455"
+}
+
+@article{ edson.jampana.ea_JPO13,
+title = "On the Exchange of Momentum over the Open Ocean",
+pages = "1589--1610",
+journal = "Journal of Physical Oceanography",
+volume = "43",
+number = "8",
+author = "Edson, James B. and Jampana, Venkata and Weller, Robert A. and Bigorre, Sebastien P. and Plueddemann, Albert J. and Fairall, Christopher W. and Miller, Scott D. and Mahrt, Larry and Vickers, Dean and Hersbach, Hans",
+year = "2013",
+month = "aug",
+publisher = "American Meteorological Society",
+issn = "0022-3670",
+doi = "10.1175/JPO-D-12-0173.1"
+}
+
+@article{         egbert.ray_JGR01,
+  title         = "Estimates of {M2} tidal energy dissipation from
+                  {TOPEX}/Poseidon altimeter data",
+  pages         = "22475--22502",
+  journal       = "Journal of Geophysical Research",
+  volume        = "106",
+  number        = "C10",
+  author        = "G. D. Egbert and R. D. Ray",
+  year          = "2001",
+  month         = "oct",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2000jc000699"
+}
+
+@article{         egbert.ray_N00,
+  title         = "Significant dissipation of tidal energy in the deep ocean
+                  inferred from satellite altimeter data",
+  pages         = "775--778",
+  journal       = "Nature",
+  volume        = "405",
+  number        = "6788",
+  author        = "G. D. Egbert and R. D. Ray",
+  year          = "2000",
+  month         = "jun",
+  publisher     = "Springer Nature",
+  issn          = "1476-4687",
+  doi           = "10.1038/35015531"
+}
+
+@article{         eiseman.stone_SR80,
+  title         = "Conservation laws of fluid dynamics - {A} survey",
+  pages         = "12--27",
+  journal       = "SIAM Review",
+  volume        = "22",
+  number        = "1",
+  author        = "P. R. Eiseman and A. P. Stone",
+  year          = "1980",
+  month         = "jan",
+  publisher     = "Society for Industrial & Applied Mathematics (SIAM)",
+  issn          = "1095-7200",
+  doi           = "10.1137/1022002"
+}
+
+@article{         emile-geay.madec_OS09,
+  title         = "Geothermal heating, diapycnal mixing and the abyssal
+                  circulation",
+  pages         = "203--217",
+  journal       = "Ocean Science",
+  volume        = "5",
+  number        = "2",
+  author        = "J. Emile-Geay and G. Madec",
+  year          = "2009",
+  month         = "jun",
+  publisher     = "Copernicus GmbH",
+  issn          = "1812-0792",
+  doi           = "10.5194/os-5-203-2009"
+}
+
+@article{         engedahl_T95,
+  title         = "Use of the flow relaxation scheme in a three-dimensional
+                  baroclinic ocean model with realistic topography",
+  pages         = "365--382",
+  journal       = "Tellus A",
+  volume        = "47",
+  number        = "3",
+  author        = "H. Engedahl",
+  year          = "1995",
+  month         = "jan",
+  publisher     = "Informa UK Limited",
+  issn          = "1600-0870",
+  doi           = "10.3402/tellusa.v47i3.11523"
+}
+
+@article{ fairall.bradley.ea_JC03,
+title = "Bulk parameterization of air-sea fluxes: Updates and verification for the COARE algorithm",
+pages = "571--591",
+journal = "Journal of Climate",
+volume = "16",
+number = "4",
+author = "Fairall, C. W. and Bradley, E. F. and Hare, J. E. and Grachev, A. A. and Edson, J. B.",
+year = "2003",
+publisher = "American Meteorological Society",
+issn = "08948755",
+doi = "10.1175/1520-0442(2003)016<0571:BPOASF>2.0.CO;2"
+}
+
+@phdthesis{       farge-coulombier_phd87,
+  title         = "Dynamique non-lin\'{e}aire des ondes et des tourbillons
+                  dans les \'{e}quations de Saint-Venant",
+  pages         = "353",
+  author        = "M. {Farge Coulombier}",
+  school        = "Paris VI University, France",
+  year          = "1987",
+  url           = "http://www.theses.fr/1987PA066365"
+}
+
+@article{         farrow.stevens_JPO95,
+  title         = "A new tracer advection scheme for Bryan and Cox type Ocean
+                  General Circulation Models",
+  pages         = "1731--1741",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "25",
+  number        = "7",
+  author        = "D. E. Farrow and D. P. Stevens",
+  year          = "1995",
+  month         = "jul",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1995)025<1731:antasf>2.0.co;2"
+}
+
+@article{         flather_JPO94,
+  title         = "A storm surge prediction model for the northern Bay of
+                  Bengal with application to the cyclone disaster in April
+                  1991",
+  pages         = "172--190",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "24",
+  number        = "1",
+  author        = "R. A. Flather",
+  year          = "1994",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1994)024<0172:asspmf>2.0.co;2"
+}
+
+@book{            fofonoff.millard_bk83,
+  pages         = "53",
+  booktitle     = "Algorithms for computation of fundamental properties of
+                  seawater",
+  editor        = "UNESCO/ICES/SCOR/IAPSO",
+  series        = "Technical Paper in Marine Science",
+  volume        = "44",
+  author        = "N P. Fofonoff and R. C. Millard",
+  year          = "1983",
+  publisher     = "UNESCO",
+  url           = "https://unesdoc.unesco.org/ark:/48223/pf0000059832.locale=en"
+}
+
+@article{         foxkemper.ferrari_JPO08,
+  title         = "Parameterization of Mixed Layer Eddies. Part I: Theory and Diagnosis",
+  pages         = "1145--1165",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "38",
+  number        = "6",
+  author        = "B. Fox-Kemper and R. Ferrari and B. Hallberg",
+  year          = "2008",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/2007JPO3792.1"
+}
+
+@article{         galperin.kantha.ea_JAS88,
+  title         = "A quasi-equilibrium turbulent energy model for geophysical
+                  flows",
+  pages         = "55--62",
+  journal       = "Journal of the Atmospheric Sciences",
+  volume        = "45",
+  number        = "1",
+  author        = "B. Galperin and L. H. Kantha and S. Hassid and A. Rosati",
+  year          = "1988",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0469",
+  doi           = "10.1175/1520-0469(1988)045<0055:aqetem>2.0.co;2"
+}
+
+@article{         gargett_JMR84,
+  title         = "Vertical eddy diffusivity in the ocean interior",
+  pages         = "359--393",
+  journal       = "Journal of Marine Research",
+  volume        = "42",
+  number        = "2",
+  author        = "A. E. Gargett",
+  year          = "1984",
+  month         = "may",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "1543-9542",
+  doi           = "10.1357/002224084788502756"
+}
+
+@article{         gaspar.gregoris.ea_JGR90,
+  title         = "A simple eddy kinetic energy model for simulations of the
+                  oceanic vertical mixing: Tests at station Papa and
+                  long-term upper ocean study site",
+  pages         = "16179",
+  journal       = "Journal of Geophysical Research",
+  volume        = "95",
+  number        = "C9",
+  author        = "P. Gaspar and Y. Gr{\'e}goris and J.-M. Lefevre",
+  year          = "1990",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/jc095ic09p16179"
+}
+
+@article{         gent.mcwilliams_JPO90,
+  title         = "Isopycnal Mixing in Ocean Circulation Models",
+  pages         = "150--155",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "20",
+  number        = "1",
+  author        = "P. R. Gent and J. C. McWilliams",
+  year          = "1990",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1990)020<0150:imiocm>2.0.co;2"
+}
+
+@article{         gentemann.minnett.ea_JGR09,
+  title         = "Profiles of Ocean Surface Heating ({POSH}): {A} new model
+                  of upper ocean diurnal warming",
+  pages         = "C07017",
+  journal       = "Journal of Geophysical Research",
+  volume        = "114",
+  number        = "C7",
+  author        = "C. L. Gentemann and P. J. Minnett and B. Ward",
+  year          = "2009",
+  month         = "jul",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2008jc004825"
+}
+
+@article{         gerdes.koberle.ea_CD91,
+  title         = "The influence of numerical advection schemes on the
+                  results of Ocean General Circulation Models",
+  pages         = "211--226",
+  journal       = "Climate Dynamics",
+  volume        = "5",
+  number        = "4",
+  author        = "R. Gerdes and C. K{\"{o}}berle and J. Willebrand",
+  year          = "1991",
+  month         = "jun",
+  publisher     = "Springer Nature",
+  issn          = "1432-0894",
+  doi           = "10.1007/bf00210006"
+}
+
+@article{         gerdes_JGR93*a,
+  title         = "A primitive equation ocean circulation model using a
+                  general vertical coordinate transformation: 1. Description
+                  and testing of the model",
+  pages         = "14683--14701",
+  journal       = "Journal of Geophysical Research",
+  volume        = "98",
+  number        = "C8",
+  author        = "R. Gerdes",
+  year          = "1993",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/93jc00760"
+}
+
+@article{         gerdes_JGR93*b,
+  title         = "A primitive equation ocean circulation model using a
+                  general vertical coordinate transformation: 2. Application
+                  to an overflow problem",
+  pages         = "14703--14726",
+  journal       = "Journal of Geophysical Research",
+  volume        = "98",
+  number        = "C8",
+  author        = "R. Gerdes",
+  year          = "1993",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/93jc00788"
+}
+
+@techreport{      gibson_rpt86,
+  title         = "Standards for software development and maintenance",
+  pages         = "21",
+  series        = "ECMWF Technical Memoranda",
+  number        = "120",
+  author        = "J. K. Gibson",
+  institution   = "ECMWF Operations Department; Reading, United Kingdom",
+  year          = "1986",
+  month         = "aug",
+  doi           = "10.21957/gi113q4gn"
+}
+
+@book{            gill_bk82,
+  pages         = "662",
+  booktitle     = "Atmosphere-Ocean Dynamics",
+  series        = "International Geophysics",
+  volume        = "30",
+  author        = "A. E. Gill",
+  year          = "1982",
+  month         = "nov",
+  publisher     = "Elsevier",
+  issn          = "0074-6142",
+  isbn          = "978-0-12-283522-3",
+  doi           = "10.1016/s0074-6142(08)x6002-4"
+}
+
+@article{         goff_JGR10,
+  title         = "Global prediction of abyssal hill root-mean-square heights
+                  from small-scale altimetric gravity variability",
+  pages         = "B12104",
+  journal       = "Journal of Geophysical Research",
+  volume        = "115",
+  number        = "B12",
+  author        = "J. A. Goff",
+  year          = "2010",
+  month         = "dec",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2010jb007867"
+}
+
+@article{         goosse.deleersnijder.ea_JGR99,
+  title         = "Sensitivity of a global coupled ocean-sea ice model to the
+                  parameterization of vertical mixing",
+  pages         = "13681--13695",
+  journal       = "Journal of Geophysical Research",
+  volume        = "104",
+  number        = "C6",
+  author        = "H. Goosse and E. Deleersnijder and T. Fichefet and M. H.
+                  England",
+  year          = "1999",
+  month         = "jun",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/1999jc900099"
+}
+
+@article{         graham.mcdougall_JPO13,
+  title         = "Quantifying the nonconservative production of conservative
+                  temperature, potential temperature, and entropy",
+  pages         = "838--862",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "43",
+  number        = "5",
+  author        = "F. S. Graham and T. J. McDougall",
+  year          = "2013",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/jpo-d-11-0188.1"
+}
+
+@article{         greatbatch_JGR94,
+  title         = "A note on the representation of steric sea level in models
+                  that conserve volume rather than mass",
+  pages         = "12767--12771",
+  journal       = "Journal of Geophysical Research",
+  volume        = "99",
+  number        = "C6",
+  author        = "R. J. Greatbatch",
+  year          = "1994",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/94jc00847"
+}
+
+@article{         griffies.biastoch.ea_OM09,
+  title         = "Coordinated Ocean-ice Reference Experiments ({CORE}s)",
+  pages         = "1--46",
+  journal       = "Ocean Modelling",
+  volume        = "26",
+  number        = "1-2",
+  author        = "S. M. Griffies and A. Biastoch and C. B{\"{o}}ning and F.
+                  Bryan and G. Danabasoglu and E. P. Chassignet and M. H.
+                  England and R. Gerdes and H. Haak and R. W. Hallberg and W.
+                  Hazeleger and J. Jungclaus and W. G. Large and G. Madec and
+                  A. Pirani and B. L. Samuels and M. Scheinert and A. Sen
+                  Gupta and C. A. Severijns and H. L. Simmons and A.-M.
+                  Tr\'{e}guier and M. Winton and S. Yeager and J. Yin",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2008.08.007"
+}
+
+@article{         griffies.gnanadesikan.ea_JPO98,
+  title         = "Isoneutral Diffusion in a z-coordinate Ocean Model",
+  pages         = "805--830",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "28",
+  number        = "5",
+  author        = "S. M. Griffies and A. Gnanadesikan and R. C. Pacanowski
+                  and V. D. Larichev and J. K. Dukowicz and R. D. Smith",
+  year          = "1998",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1998)028<0805:idiazc>2.0.co;2"
+}
+
+@article{         griffies.pacanowski.ea_MWR01,
+  title         = "Tracer Conservation with an Explicit Free Surface Method
+                  for z-coordinate Ocean Models",
+  pages         = "1081--1098",
+  journal       = "Monthly Weather Review",
+  volume        = "129",
+  number        = "5",
+  author        = "S. M. Griffies and R. C. Pacanowski and M. Schmidt and V.
+                  Balaji",
+  year          = "2001",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(2001)129<1081:tcwaef>2.0.co;2"
+}
+
+@article{         griffies_JPO98,
+  title         = "The Gent-McWilliams skew-flux",
+  pages         = "831--841",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "28",
+  number        = "5",
+  author        = "S. M. Griffies",
+  year          = "1998",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1998)028<0831:tgmsf>2.0.co;2"
+}
+
+@book{            griffies_bk04,
+  pages         = "434",
+  booktitle     = "Fundamentals of ocean climate models",
+  author        = "S. M. Griffies",
+  year          = "2004",
+  month         = "dec",
+  publisher     = "Princeton University Press",
+  isbn          = "978-0-691-18712-9",
+  doi           = "10.2307/j.ctv301gzg"
+}
+
+@article{         guilyardi.madec.ea_CD01,
+  title         = "The role of lateral ocean physics in the upper ocean
+                  thermal balance of a coupled ocean-atmosphere {GCM}",
+  pages         = "589--599",
+  journal       = "Climate Dynamics",
+  volume        = "17",
+  number        = "8",
+  author        = "E. Guilyardi and G. Madec and L. Terray",
+  year          = "2001",
+  month         = "may",
+  publisher     = "Springer Science and Business Media LLC",
+  issn          = "0930-7575",
+  doi           = "10.1007/pl00007930"
+}
+
+@article{         haney_JPO91,
+  title         = "On the Pressure Gradient Force over Steep Topography in
+                  Sigma Coordinate Ocean Models",
+  pages         = "610--619",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "21",
+  number        = "4",
+  author        = "R. L. Haney",
+  year          = "1991",
+  month         = "apr",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1991)021<0610:otpgfo>2.0.co;2"
+}
+
+@article{         hazeleger.drijfhout_JGR00,
+  title         = "A model study on internally generated variability in
+                  subtropical mode water formation",
+  pages         = "13965--13979",
+  journal       = "Journal of Geophysical Research",
+  volume        = "105",
+  number        = "C6",
+  author        = "W. Hazeleger and S. S. Drijfhout",
+  year          = "2000",
+  month         = "jun",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2000jc900041"
+}
+
+@article{         hazeleger.drijfhout_JPO00,
+  title         = "Eddy subduction in a model of the subtropical gyre",
+  pages         = "677--695",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "30",
+  number        = "4",
+  author        = "W. Hazeleger and S. S. Drijfhout",
+  year          = "2000",
+  month         = "apr",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(2000)030<0677:esiamo>2.0.co;2"
+}
+
+@article{         hazeleger.drijfhout_JPO98,
+  title         = "Mode water variability in a model of the subtropical gyre:
+                  response to anomalous forcing",
+  pages         = "266--288",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "28",
+  number        = "2",
+  author        = "W. Hazeleger and S. S. Drijfhout",
+  year          = "1998",
+  month         = "feb",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1998)028<0266:mwviam>2.0.co;2"
+}
+
+@article{         hazeleger.drijfhout_JPO99,
+  title         = "Stochastically forced mode water variability",
+  pages         = "1772--1786",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "29",
+  number        = "8",
+  author        = "W. Hazeleger and S. S. Drijfhout",
+  year          = "1999",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1999)029<1772:sfmwv>2.0.co;2"
+}
+
+@article{         he.ding_JS01,
+  title         = "Using accurate arithmetics to improve numerical
+                  reproducibility and stability in parallel applications",
+  pages         = "259--277",
+  journal       = "The Journal of Supercomputing",
+  volume        = "18",
+  number        = "3",
+  author        = "Y. He and C. H. Q. Ding",
+  year          = "2001",
+  publisher     = "Springer Nature",
+  issn          = "0920-8542",
+  doi           = "10.1023/a:1008153532043"
+}
+
+@article{         hirt.amsden.ea_JCP74,
+  title         = "An arbitrary Lagrangian-Eulerian computing method for all
+                  flow speeds",
+  pages         = "227--253",
+  journal       = "Journal of Computational Physics",
+  volume        = "14",
+  number        = "3",
+  author        = "C. W. Hirt and A. A. Amsden and J. L. Cook",
+  year          = "1974",
+  month         = "mar",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1016/0021-9991(74)90051-5"
+}
+
+@article{         hofmeister.burchard.ea_OM10,
+  title         = "Non-uniform adaptive vertical grids for 3{D} numerical
+                  ocean models",
+  pages         = "70--86",
+  journal       = "Ocean Modelling",
+  volume        = "33",
+  number        = "1-2",
+  author        = "R. Hofmeister and H. Burchard and J.-M. Beckers",
+  year          = "2010",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2009.12.003"
+}
+
+@article{         holland.jenkins_JPO99,
+  title         = "Modeling thermodynamic ice-ocean interactions at the base
+                  of an ice shelf",
+  pages         = "1787--1800",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "29",
+  number        = "8",
+  author        = "D. M. Holland and A. Jenkins",
+  year          = "1999",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1999)029<1787:mtioia>2.0.co;2"
+}
+
+@techreport{      hunter_rpt06,
+  title         = "Specification for Test Models of Ice Shelf Cavities",
+  pages         = "17",
+  number        = "7",
+  author        = "J. R. Hunter",
+  institution   = "Antarctic Climate \& Ecosystems Cooperative Research
+                  Centre",
+  year          = "2006",
+  month         = "jun",
+  url           = "http://staff.acecrc.org.au/~bkgalton/ISOMIP/test_cavities.pdf"
+}
+
+@book{            ioc.iapso_bk10,
+  title         = "The international thermodynamic equation of seawater -
+                  2010: Calculation and use of thermodynamic properties",
+  pages         = "196",
+  editor        = "Intergovernmental Oceanographic Commission",
+  series        = "Manuals and Guides",
+  volume        = "56",
+  author        = "IOC, SCOR and IAPSO",
+  year          = "2010",
+  month         = "mar",
+  publisher     = "UNESCO",
+  url           = "https://unesdoc.unesco.org/ark:/48223/pf0000188170.locale=en"
+}
+
+@article{         jackson.rehmann_JPO14,
+  title         = "Experiments on differential scalar mixing in turbulence in
+                  a sheared, stratified flow",
+  pages         = "2661--2680",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "44",
+  number        = "10",
+  author        = "P. R. Jackson and C. R. Rehmann",
+  year          = "2014",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/jpo-d-14-0027.1"
+}
+
+@techreport{      janssen.breivik.ea_rpt13,
+  title         = "Air-sea interaction and surface waves",
+  pages         = "36",
+  series        = "ECMWF Technical Memoranda",
+  volume        = "712",
+  author        = "P. A. E. M. Janssen and {\O}. Breivik and K. Mogensen and
+                  F. Vitart and M. Alonso-Balmaseda and J.-R. Bidlot and S.
+                  Keeley and M. Leutbecher and L. Magnusson and F. Molteni",
+  institution   = "ECMWF Research Departement; Reading, United Kingdom",
+  year          = "2013",
+  month         = "nov",
+  doi           = "10.21957/0kg73joh"
+}
+
+@article{         jenkins.nicholls.ea_JPO10,
+  title         = "Observation and parameterization of ablation at the base
+                  of Ronne Ice Shelf, Antarctica",
+  pages         = "2298--2312",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "40",
+  number        = "10",
+  author        = "A. Jenkins and K. W. Nicholls and H. F. J. Corr",
+  year          = "2010",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/2010jpo4317.1"
+}
+
+@article{         jenkins_JGR91,
+  title         = "A one-dimensional model of ice shelf-ocean interaction",
+  pages         = "20671--20677",
+  journal       = "Journal of Geophysical Research",
+  volume        = "96",
+  number        = "C11",
+  author        = "A. Jenkins",
+  year          = "1991",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/91jc01842"
+}
+
+@article{         kantha.carniel_JMR03,
+  title         = "Comments on ``{A} generic length-scale equation for
+                  geophysical turbulence models'' by {L}. Umlauf and {H}.
+                  Burchard",
+  pages         = "693--702",
+  journal       = "Journal of Marine Research",
+  volume        = "61",
+  number        = "5",
+  author        = "L. Kantha and S. Carniel",
+  year          = "2003",
+  month         = "sep",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "1543-9542",
+  doi           = "10.1357/002224003771816007"
+}
+
+@article{         kantha.clayson_JGR94,
+  title         = "An improved mixed layer model for geophysical
+                  applications",
+  pages         = "25235--25266",
+  journal       = "Journal of Geophysical Research",
+  volume        = "99",
+  number        = "C12",
+  author        = "L. H. Kantha and C. A. Clayson",
+  year          = "1994",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/94jc02257"
+}
+
+@article{         kasahara_MWR74,
+  title         = "Various vertical coordinate systems used for numerical
+                  weather prediction",
+  pages         = "509--522",
+  journal       = "Monthly Weather Review",
+  volume        = "102",
+  number        = "7",
+  author        = "A. Kasahara",
+  year          = "1974",
+  month         = "jul",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1974)102<0509:vvcsuf>2.0.co;2"
+}
+
+@article{         killworth.webb.ea_JPO91,
+  title         = "The development of a free-surface Bryan-Cox-Semtner ocean
+                  model",
+  pages         = "1333--1348",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "21",
+  number        = "9",
+  author        = "P. D. Killworth and D. J. Webb and D. Stainforth and S. M.
+                  Paterson",
+  year          = "1991",
+  month         = "sep",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1991)021<1333:tdoafs>2.0.co;2"
+}
+
+@article{         killworth_JPO92,
+  title         = "An equivalent-barotropic mode in the fine resolution
+                  Antarctic model",
+  pages         = "1379--1387",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "22",
+  number        = "11",
+  author        = "P. D. Killworth",
+  year          = "1992",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1992)022<1379:aebmit>2.0.co;2"
+}
+
+@inproceedings{   killworth_iprc89,
+  title         = "On the parameterization of deep convection in ocean
+                  models",
+  pages         = "59--74",
+  booktitle     = "Parameterization of small-scale processes",
+  editor        = "P. Muller and D. Henderson",
+  author        = "P. D. Killworth",
+  year          = "1989",
+  month         = "jan",
+  publisher     = "Hawaii Institute of Geophysics",
+  url           = "http://www.soest.hawaii.edu/PubServices/1989pdfs/Killworth.pdf"
+}
+
+@article{         koch-larrouy.lengaigne.ea_CD10,
+  title         = "Tidal mixing in the Indonesian Seas and its effect on the
+                  tropical climate system",
+  pages         = "891--904",
+  journal       = "Climate Dynamics",
+  volume        = "34",
+  number        = "6",
+  author        = "A. Koch-Larrouy and M. Lengaigne and P. Terray and G.
+                  Madec and S. Masson",
+  year          = "2010",
+  month         = "aug",
+  publisher     = "Springer Nature",
+  issn          = "1432-0894",
+  doi           = "10.1007/s00382-009-0642-4"
+}
+
+@article{         koch-larrouy.madec.ea_GRL07,
+  title         = "On the transformation of Pacific water into Indonesian
+                  ThroughFlow water by internal tidal mixing",
+  pages         = "L04604",
+  journal       = "Geophysical Research Letters",
+  volume        = "34",
+  number        = "4",
+  author        = "A. Koch-Larrouy and G. Madec and P. Bouruet-Aubertot and
+                  T. Gerkema and L. Bessi\`{e}res and R. Molcard",
+  year          = "2007",
+  month         = "feb",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0094-8276",
+  doi           = "10.1029/2006gl028405"
+}
+
+@article{         koch-larrouy.madec.ea_OD08*a,
+  title         = "Water mass transformation along the Indonesian ThroughFlow
+                  in an {OGCM}",
+  pages         = "289--309",
+  journal       = "Ocean Dynamics",
+  volume        = "58",
+  number        = "3-4",
+  author        = "A. Koch-Larrouy and G. Madec and B. Blanke and R. Molcard",
+  year          = "2008",
+  month         = "oct",
+  publisher     = "Springer Nature",
+  issn          = "1616-7228",
+  doi           = "10.1007/s10236-008-0155-4"
+}
+
+@article{         koch-larrouy.madec.ea_OD08*b,
+  title         = "Physical processes contributing to the water mass
+                  transformation of the Indonesian ThroughFlow",
+  pages         = "275--288",
+  journal       = "Ocean Dynamics",
+  volume        = "58",
+  number        = "3-4",
+  author        = "A. Koch-Larrouy and G. Madec and D. Iudicone and A.
+                  Atmadipoera and R. Molcard",
+  year          = "2008",
+  month         = "oct",
+  publisher     = "Springer Nature",
+  issn          = "1616-7228",
+  doi           = "10.1007/s10236-008-0154-5"
+}
+
+@article{         kolmogorov_IANS42,
+  title         = "Equations of turbulent motion in an incompressible fluid",
+  pages         = "56--58",
+  journal       = "Izvestiya Akademiya Nauk SSSR",
+  series        = "Fizika",
+  volume        = "6",
+  author        = "A. N. Kolmogorov",
+  year          = "1942"
+}
+
+@article{         kraus.turner_tellus67,
+  author = {Kraus, E.B. and Turner, J.},
+  journal = {Tellus},
+  pages = {98--106},
+  title = {A one dimensional model of the seasonal thermocline {II}. {T}he general theory and its consequences},
+  volume = {19},
+  year = {1967}
+}
+
+@article{        large.ea_RG97,
+  author        = "Large, W. G. and McWilliams, J. C. and Doney, S. C.",
+  doi           = "10.1029/94RG01872",
+  journal       = "Reviews of Geophysics",
+  number        = {4},
+  pages         = {363--403},
+  publisher     = {AGU},
+  title         = "Oceanic vertical mixing: {A} review and a model with a nonlocal boundary layer parameterization",
+  year          = "1994"
+}
+
+@techreport{      large.yeager_rpt04,
+  title         = "Diurnal to decadal global forcing for ocean and sea-ice
+                  models: the data sets and flux climatologies",
+  author        = "W. G. Large and S. G. Yeager",
+  institution   = "{NCAR} Climate and global dynamics division; Boulder, CO,
+                  United States",
+  year          = "2004",
+  month         = "may",
+  doi           = "10.5065/d6kk98q6"
+}
+
+@article{         lazar.madec.ea_JPO99,
+  title         = "The Deep Interior Downwelling, the Veronis Effect, and
+                  Mesoscale Tracer Transport Parameterizations in an {OGCM}",
+  pages         = "2945--2961",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "29",
+  number        = "11",
+  author        = "A. Lazar and G. Madec and P. Del\'{e}cluse",
+  year          = "1999",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1999)029<2945:tdidtv>2.0.co;2"
+}
+
+@phdthesis{       lazar_phd97,
+  title         = "La branche froide de la circulation thermohaline -
+                  sensibilit\'{e} \`{a} la diffusion turbulente dans un
+                  mod\`{e}le de circulation g\'{e}n\'{e}rale
+                  id\'{e}alis\'{e}e",
+  pages         = "269",
+  author        = "A. Lazar",
+  school        = "Universit\'{e} Pierre et Marie Curie, Paris, France",
+  year          = "1997",
+  url           = "http://www.theses.fr/1997PA066680"
+}
+
+@article{         le-sommer.penduff.ea_OM09,
+  title         = "How momentum advection schemes influence
+                  current-topography interactions at eddy permitting
+                  resolution",
+  pages         = "1--14",
+  journal       = "Ocean Modelling",
+  volume        = "29",
+  number        = "1",
+  author        = "J. {Le Sommer} and T. Penduff and S. Theetten and G. Madec
+                  and B. Barnier",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2008.11.007"
+}
+
+@article{         leclair.madec_OM09,
+  title         = "A conservative leapfrog time stepping method",
+  pages         = "88--94",
+  journal       = "Ocean Modelling",
+  volume        = "30",
+  number        = "2-3",
+  author        = "M. Leclair and G. Madec",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2009.06.006"
+}
+
+@article{         leclair.madec_OM11,
+  title         = "$\tilde{z}$-coordinate, an arbitrary Lagrangian-Eulerian
+                  coordinate separating high and low frequency motions",
+  pages         = "139--152",
+  journal       = "Ocean Modelling",
+  volume        = "37",
+  number        = "3-4",
+  author        = "M. Leclair and G. Madec",
+  year          = "2011",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2011.02.001"
+}
+
+@phdthesis{       leclair_phd10,
+  title         = "Introduction d'une coordonn\'{e}e verticale arbitrairement
+                  Lagrangienne Eul\'{e}rienne dans le code d'oc\'{e}an
+                  {NEMO}",
+  pages         = "163",
+  author        = "M. Leclair",
+  school        = "Universit\'{e} Pierre and Marie Curie, Paris, France",
+  year          = "2010",
+  url           = "http://www.theses.fr/2010PA066728"
+}
+
+@article{         lele_JCP92,
+  title         = "Compact finite difference schemes with spectral-like
+                  resolution",
+  pages         = "16--42",
+  journal       = "Journal of Computational Physics",
+  volume        = "103",
+  number        = "1",
+  author        = "S. K. Lele",
+  year          = "1992",
+  month         = "nov",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1016/0021-9991(92)90324-r"
+}
+
+@article{         lemarie.debreu.ea_OM12,
+  title         = "On the stability and accuracy of the harmonic and
+                  biharmonic isoneutral mixing operators in ocean models",
+  pages         = "9--35",
+  journal       = "Ocean Modelling",
+  volume        = "52-53",
+  author        = "F. Lemari\'{e} and L. Debreu and A. F. Shchepetkin and J.
+                  C. McWilliams",
+  year          = "2012",
+  month         = "aug",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2012.04.007"
+}
+
+@article{         lemarie.debreu.ea_OM15,
+  title         = "Stability constraints for oceanic numerical models:
+                  implications for the formulation of time and space
+                  discretizations",
+  pages         = "124--148",
+  journal       = "Ocean Modelling",
+  volume        = "92",
+  author        = "F. Lemari\'{e} and L. Debreu and G. Madec and J. Demange
+                  and J. M. Molines and M. Honnorat",
+  year          = "2015",
+  month         = "aug",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2015.06.006"
+}
+
+@article{         lengaigne.madec.ea_JGR03,
+  title         = "Impact of isopycnal mixing on the tropical ocean
+                  circulation",
+  pages         = "3345",
+  journal       = "Journal of Geophysical Research",
+  volume        = "108",
+  number        = "C11",
+  author        = "M. Lengaigne and G. Madec and G. Alory and C. Menkes",
+  year          = "2003",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2002jc001704"
+}
+
+@article{         lengaigne.menkes.ea_CD07,
+  title         = "Influence of the oceanic biology on the tropical Pacific
+                  climate in a Coupled General Circulation Model",
+  pages         = "503--516",
+  journal       = "Climate Dynamics",
+  volume        = "28",
+  number        = "5",
+  author        = "M. Lengaigne and C. Menkes and O. Aumont and T. Gorgues
+                  and L. Bopp and J.-M. Andr\'{e} and G. Madec",
+  year          = "2007",
+  month         = "nov",
+  publisher     = "Springer Nature",
+  issn          = "1432-0894",
+  doi           = "10.1007/s00382-006-0200-2"
+}
+
+@article{         leonard_CMAME79,
+  title         = "A stable and accurate convective modelling procedure based
+                  on quadratic upstream interpolation",
+  pages         = "59--98",
+  journal       = "Computer Methods in Applied Mechanics and Engineering",
+  volume        = "19",
+  number        = "1",
+  author        = "B. P. Leonard",
+  year          = "1979",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "0045-7825",
+  doi           = "10.1016/0045-7825(79)90034-3"
+}
+
+@article{         leonard_CMAME91,
+  title         = "The {ULTIMATE} conservative difference scheme applied to
+                  unsteady one-dimensional advection",
+  pages         = "17--74",
+  journal       = "Computer Methods in Applied Mechanics and Engineering",
+  volume        = "88",
+  number        = "1",
+  author        = "B. P. Leonard",
+  year          = "1991",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "0045-7825",
+  doi           = "10.1016/0045-7825(91)90232-u"
+}
+
+@article{         lermusiaux_JMS01,
+  title         = "Evolving the subspace of the three-dimensional multiscale
+                  ocean variability: Massachusetts Bay",
+  pages         = "385--422",
+  journal       = "Journal of Marine Systems",
+  volume        = "29",
+  number        = "1-4",
+  author        = "P. F. J. Lermusiaux",
+  year          = "2001",
+  month         = "may",
+  publisher     = "Elsevier BV",
+  issn          = "0924-7963",
+  doi           = "10.1016/s0924-7963(01)00025-2"
+}
+
+@techreport{      levier.treguier.ea_rpt07,
+  title         = "Free surface and variable volume in the {NEMO} code",
+  pages         = "47",
+  author        = "B. Levier and A.-M. Tr\'{e}guier and G. Madec and V.
+                  Garnier",
+  institution   = "European Union: Marine Environment and Security for the
+                  European Area (MERSEA) Integrated Project",
+  year          = "2007",
+  month         = "may",
+  doi           = "10.5281/zenodo.3244182"
+}
+
+@article{         levy.estublier.ea_GRL01,
+  title         = "Choice of an advection scheme for biogeochemical models",
+  pages         = "3725--3728",
+  journal       = "Geophysical Research Letters",
+  volume        = "28",
+  number        = "19",
+  author        = "M. L\'{e}vy and A. Estublier and G Madec",
+  year          = "2001",
+  month         = "oct",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0094-8276",
+  doi           = "10.1029/2001gl012947"
+}
+
+@article{         levy.klein.ea_OM10,
+  title         = "Modifications of gyre circulation by sub-mesoscale
+                  physics",
+  pages         = "1--15",
+  journal       = "Ocean Modelling",
+  volume        = "34",
+  number        = "1-2",
+  author        = "M. L\'{e}vy and P. Klein and A.-M. Tr\'{e}guier and D.
+                  Iovino and G. Madec and S. Masson and K. Takahashi",
+  year          = "2010",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2010.04.001"
+}
+
+@article{         li.garrett_JMR93,
+  title         = "Cell merging and the jet/downwelling ratio in Langmuir
+                  circulation",
+  pages         = "737--769",
+  journal       = "Journal of Marine Research",
+  volume        = "51",
+  number        = "4",
+  author        = "M. Li and C. Garrett",
+  year          = "1993",
+  month         = "nov",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "1543-9542",
+  doi           = "10.1357/0022240933223945"
+}
+
+@article{         losch_JGR08,
+  title         = "Modeling ice shelf cavities in a z coordinate Ocean
+                  General Circulation Model",
+  journal       = "Journal of Geophysical Research",
+  volume        = "113",
+  number        = "C8",
+  author        = "M. Losch",
+  year          = "2008",
+  month         = "aug",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2007jc004368"
+}
+
+@article{         lott.madec.ea_OM90,
+  title         = "Topographic experiments in an Ocean General Circulation
+                  Model",
+  pages         = "1--4",
+  journal       = "Ocean Modelling",
+  volume        = "88",
+  author        = "F. Lott and G. Madec and J. Verron",
+  year          = "1990"
+}
+
+@article{	  lupkes.gryanik.ea_JGR12,
+  author 	= "L{\"{u}}pkes, Christof and Gryanik, Vladimir M. and Hartmann, J{\"{o}}rg and Andreas, Edgar L.",
+  doi 		= "10.1029/2012JD017630",
+  issn 		= "01480227",
+  journal 	= "Journal of Geophysical Research Atmospheres",
+  number 	= "13",
+  pages 	= "1--18",
+  title 	= "A parametrization, based on sea ice morphology, of the neutral atmospheric drag coefficients for weather prediction and climate models",
+  volume 	= "117",
+  year 		= "2012"
+}
+
+@article{	  lupkes.gryanik_JGR15,
+  author 	= "L{\"{u}}pkes, Christof and Gryanik, Vladimir M.",
+  doi 		= "10.1002/2014JD022418",
+  issn 		= "21562202",
+  journal 	= "Journal of Geophysical Research",
+  number 	= "2",
+  pages 	= "552--581",
+  title 	= "A stability-dependent parametrization of transfer coefficients formomentum and heat over polar sea ice to be used in climate models",
+  volume 	= "120",
+  year 		= "2015"
+}
+
+@article{         madec.chartier.ea_DAO91,
+  title         = "The effect of thermohaline forcing variability on deep
+                  water formation in the western Mediterranean Sea: a
+                  high-resolution three-dimensional numerical study",
+  pages         = "301--332",
+  journal       = "Dynamics of Atmospheres and Oceans",
+  volume        = "15",
+  number        = "3-5",
+  author        = "G. Madec and M. Chartier and M. Cr\'{e}pon",
+  year          = "1991",
+  month         = "apr",
+  publisher     = "Elsevier BV",
+  issn          = "0377-0265",
+  doi           = "10.1016/0377-0265(91)90024-a"
+}
+
+@inproceedings{   madec.crepon_iprc91,
+  title         = "Thermohaline-driven deep water formation in the
+                  northwestern Mediterranean Sea",
+  chapter       = "15",
+  pages         = "241--265",
+  booktitle     = "Deep convection and deep water formation in the oceans,
+                  Proceedings of the international Monterey colloquium on
+                  deep convection and deep water formation in the oceans",
+  editor        = "P.C. Chu and J.C. Gascard",
+  series        = "Elsevier Oceanography",
+  volume        = "57",
+  author        = "G. Madec and M. Cr\'{e}pon",
+  year          = "1991",
+  publisher     = "Elsevier",
+  issn          = "0422-9894",
+  isbn          = "978-0-444-88764-1",
+  doi           = "10.1016/s0422-9894(08)70071-0"
+}
+
+@article{         madec.delecluse.ea_JPO91,
+  title         = "A three-dimensional numerical study of deep-water
+                  formation in the northwestern Mediterranean Sea",
+  pages         = "1349--1371",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "21",
+  number        = "9",
+  author        = "G. Madec and P. Del\'{e}cluse and M. Cr\'{e}pon and M.
+                  Chartier",
+  year          = "1991",
+  month         = "sep",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1991)021<1349:atdnso>2.0.co;2"
+}
+
+@article{         madec.delecluse.ea_JPO96,
+  title         = "Large-Scale Preconditioning of Deep-Water Formation in the
+                  northwestern Mediterranean Sea",
+  pages         = "1393--1408",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "26",
+  number        = "8",
+  author        = "G. Madec and P. Del\'{e}cluse and M. Cr\'{e}pon and F.
+                  Lott",
+  year          = "1996",
+  month         = "aug",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1996)026<1393:lspodw>2.0.co;2"
+}
+
+@book{            madec.delecluse.ea_NPM98,
+  title         = "{OPA} 8.1 Ocean General Circulation Model reference
+                  manual",
+  pages         = "91",
+  journal       = "Note du Pole de Mod\'{e}lisation",
+  volume        = "11",
+  author        = "G. Madec and P. Del\'{e}cluse and M. Imbard and C.
+                  L\'{e}vy",
+  year          = "1998",
+  publisher     = "Institut Pierre Simon Laplace ({IPSL})",
+  issn          = "1288-1619",
+  url           = "http://cmc.ipsl.fr/images/publications/scientific_notes/note11.pdf"
+}
+
+@article{         madec.delecluse_IWN97,
+  title         = "The {OPA}/{ARPEGE} and {OPA}/{LMD} Global Ocean-Atmosphere
+                  Coupled Model",
+  pages         = "12--15",
+  journal       = "International WOCE Newsletter",
+  volume        = "26",
+  author        = "G. Madec and P. Del\'{e}cluse",
+  year          = "1997",
+  month         = "apr",
+  publisher     = "University of Southampton",
+  url           = "https://www.nodc.noaa.gov/woce/wdiu/wocedocs/newsltr/news26/news26.pdf"
+}
+
+@article{         madec.imbard_CD96,
+  title         = "A global ocean mesh to overcome the North Pole
+                  singularity",
+  pages         = "381--388",
+  journal       = "Climate Dynamics",
+  volume        = "12",
+  number        = "6",
+  author        = "G. Madec and M. Imbard",
+  year          = "1996",
+  month         = "may",
+  publisher     = "Springer Nature",
+  issn          = "1432-0894",
+  doi           = "10.1007/bf00211684"
+}
+
+@article{         maltrud.smith.ea_JGR98,
+  title         = "Global eddy-resolving ocean simulations driven by
+                  1985-1995 atmospheric winds",
+  pages         = "30825--30853",
+  journal       = "Journal of Geophysical Research",
+  volume        = "103",
+  number        = "C13",
+  author        = "M. E. Maltrud and R. D. Smith and A. J. Semtner and R. C.
+                  Malone",
+  year          = "1998",
+  month         = "dec",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/1998jc900013"
+}
+
+@article{         marchesiello.mcwilliams.ea_OM01,
+  title         = "Open boundary conditions for long-term integration of
+                  regional oceanic models",
+  pages         = "1--20",
+  journal       = "Ocean Modelling",
+  volume        = "3",
+  number        = "1-2",
+  author        = "P. Marchesiello and J. C. McWilliams and A. Shchepetkin",
+  year          = "2001",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/s1463-5003(00)00013-5"
+}
+
+@article{         marsaleix.auclair.ea_OM08,
+  title         = "Energy conservation issues in sigma-coordinate
+                  free-surface ocean models",
+  pages         = "61--89",
+  journal       = "Ocean Modelling",
+  volume        = "20",
+  number        = "1",
+  author        = "P. Marsaleix and F. Auclair and J. W. Floor and M. J.
+                  Herrmann and C. Estournel and I. Pairaud and C. Ulses",
+  year          = "2008",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2007.07.005"
+}
+
+@article{         marsh.ivchenko.ea_GMD15,
+  title         = "{NEMO}-{ICB} (v1.0): interactive icebergs in the {NEMO}
+                  ocean model globally configured at eddy-permitting
+                  resolution",
+  pages         = "1547--1562",
+  journal       = "Geoscientific Model Development",
+  volume        = "8",
+  number        = "5",
+  author        = "R. Marsh and V. O. Ivchenko and N. Skliris and S. Alderson
+                  and G. R. Bigg and G. Madec and A. T. Blaker and Y. Aksenov
+                  and B. Sinha and A. C. Coward and J. {Le Sommer} and N.
+                  Merino and V. B. Zalesny",
+  year          = "2015",
+  month         = "may",
+  publisher     = "Copernicus GmbH",
+  issn          = "1991-9603",
+  doi           = "10.5194/gmd-8-1547-2015"
+}
+
+@article{         marti.madec.ea_JGR92,
+  title         = "Comment on ``{N}et diffusivity in ocean general
+                  circulation models with nonuniform grids'' by {F}. {L}. Yin
+                  and {I}. {Y}. Fung",
+  pages         = "12763--12766",
+  journal       = "Journal of Geophysical Research",
+  volume        = "97",
+  number        = "C8",
+  author        = "O. Marti and G. Madec and P. Del\'{e}cluse",
+  year          = "1992",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/92jc00306"
+}
+
+@article{         martin.adcroft_OM10,
+  title         = "Parameterizing the fresh-water flux from land ice to ocean
+                  with interactive icebergs in a coupled climate model",
+  pages         = "111--124",
+  journal       = "Ocean Modelling",
+  volume        = "34",
+  number        = "3-4",
+  author        = "T. Martin and A. Adcroft",
+  year          = "2010",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2010.05.001"
+}
+
+@article{         mathiot.jenkins.ea_GMD17,
+  title         = "Explicit representation and parametrised impacts of under
+                  ice shelf seas in the \zstar coordinate ocean model {NEMO}
+                  3.6",
+  pages         = "2849--2874",
+  journal       = "Geoscientific Model Development",
+  volume        = "10",
+  number        = "7",
+  author        = "P. Mathiot and A. Jenkins and C. Harris and G. Madec",
+  year          = "2017",
+  month         = "jul",
+  publisher     = "Copernicus GmbH",
+  issn          = "1991-9603",
+  doi           = "10.5194/gmd-10-2849-2017"
+}
+
+@article{         mcdougall.taylor_JMR84,
+  title         = "Flux measurements across a finger interface at low values
+                  of the stability ratio",
+  pages         = "1--14",
+  journal       = "Journal of Marine Research",
+  volume        = "42",
+  number        = "1",
+  author        = "T. J. McDougall and J. R. Taylor",
+  year          = "1984",
+  month         = "feb",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "1543-9542",
+  doi           = "10.1357/002224084788506095"
+}
+
+@article{         mcdougall_JPO87,
+  title         = "Neutral Surfaces",
+  pages         = "1950--1964",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "17",
+  number        = "11",
+  author        = "T. J. McDougall",
+  year          = "1987",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1987)017<1950:ns>2.0.co;2"
+}
+
+@article{mcwilliams.ea_JFM97,
+	author = {McWilliams, James C. and Sullivan, Peter P. and Moeng, Chin-Hoh},
+	doi = {10.1017/S0022112096004375},
+	journal = {Journal of Fluid Mechanics},
+	pages = {1--30},
+	title = {Langmuir turbulence in the ocean},
+	volume = {334},
+	year = {1997},
+}
+@article{         mellor.blumberg_JPO04,
+  title         = "Wave Breaking and Ocean Surface Layer Thermal Response",
+  pages         = "693--698",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "34",
+  number        = "3",
+  author        = "G. Mellor and A. Blumberg",
+  year          = "2004",
+  month         = "mar",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/2517.1"
+}
+
+@article{         mellor.yamada_RG82,
+  title         = "Development of a turbulence closure model for geophysical
+                  fluid problems",
+  pages         = "851--875",
+  journal       = "Reviews of Geophysics",
+  volume        = "20",
+  number        = "4",
+  author        = "G. L. Mellor and T. Yamada",
+  year          = "1982",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "8755-1209",
+  doi           = "10.1029/rg020i004p00851"
+}
+
+@article{         merryfield.holloway.ea_JPO99,
+  title         = "A Global Ocean Model with Double-Diffusive Mixing",
+  pages         = "1124--1142",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "29",
+  number        = "6",
+  author        = "W. J. Merryfield and G. Holloway and A. E. Gargett",
+  year          = "1999",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1999)029<1124:agomwd>2.0.co;2"
+}
+
+@book{            mesinger.arakawa_bk76,
+  booktitle     = "Numerical methods used in atmospheric models",
+  series        = "GARP Publication",
+  volume        = "1",
+  number        = "17",
+  author        = "F. Mesinger and A. Arakawa",
+  year          = "1976",
+  month         = "aug",
+  url           = "https://www.researchgate.net/publication/234333726_Numerical_Methods_Used_In_Atmospheric_Models"
+}
+
+@article{         morel.berthon_LO89,
+  title         = "Surface pigments, algal biomass profiles, and potential
+                  production of the euphotic layer: Relationships
+                  reinvestigated in view of remote-sensing applications",
+  pages         = "1545--1562",
+  journal       = "Limnology and Oceanography",
+  volume        = "34",
+  number        = "8",
+  author        = "A. Morel and J.-F. Berthon",
+  year          = "1989",
+  month         = "dec",
+  publisher     = "Wiley",
+  issn          = "0024-3590",
+  doi           = "10.4319/lo.1989.34.8.1545"
+}
+
+@article{         morel.maritorena_JGR01,
+  title         = "Bio-optical properties of oceanic waters: {A} reappraisal",
+  pages         = "7163--7180",
+  journal       = "Journal of Geophysical Research",
+  volume        = "106",
+  number        = "C4",
+  author        = "A. Morel and S. Maritorena",
+  year          = "2001",
+  month         = "apr",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2000jc000319"
+}
+
+@article{         morel_JGR88,
+  title         = "Optical modeling of the upper ocean in relation to its
+                  biogenous matter content (case {I} waters)",
+  pages         = "10749--10768",
+  journal       = "Journal of Geophysical Research",
+  volume        = "93",
+  number        = "C9",
+  author        = "A. Morel",
+  year          = "1988",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/jc093ic09p10749"
+}
+
+@article{         murray_JCP96,
+  title         = "Explicit Generation of Orthogonal Grids for Ocean Models",
+  pages         = "251--273",
+  journal       = "Journal of Computational Physics",
+  volume        = "126",
+  number        = "2",
+  author        = "R. J. Murray",
+  year          = "1996",
+  month         = "jul",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1006/jcph.1996.0136"
+}
+
+@article{         oey_OM06,
+  title         = "An {OGCM} with movable land-sea boundaries",
+  pages         = "176--195",
+  journal       = "Ocean Modelling",
+  volume        = "13",
+  number        = "2",
+  author        = "L.-Y. Oey",
+  year          = "2006",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2006.01.001"
+}
+
+@article{         osborn_JPO80,
+  title         = "Estimates of the local rate of vertical diffusion from
+                  dissipation measurements",
+  pages         = "83--89",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "10",
+  number        = "1",
+  author        = "T. R. Osborn",
+  year          = "1980",
+  month         = "jan",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1980)010<0083:eotlro>2.0.co;2"
+}
+
+@article{         pacanowski.gnanadesikan_MWR98,
+  title         = "Transient response in a z-level ocean model that resolves
+                  topography with partial-cells",
+  pages         = "3248--3270",
+  journal       = "Monthly Weather Review",
+  volume        = "126",
+  number        = "12",
+  author        = "R. C. Pacanowski and A. Gnanadesikan",
+  year          = "1998",
+  month         = "dec",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1998)126<3248:triazl>2.0.co;2"
+}
+
+@article{         pacanowski.philander_JPO81,
+  title         = "Parameterization of Vertical Mixing in Numerical Models of
+                  Tropical Oceans",
+  pages         = "1443--1451",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "11",
+  number        = "11",
+  author        = "R. C. Pacanowski and S. G. H. Philander",
+  year          = "1981",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1981)011<1443:povmin>2.0.co;2"
+}
+
+@article{         paulson.simpson_JPO77,
+  title         = "Irradiance Measurements in the Upper Ocean",
+  pages         = "952--956",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "7",
+  number        = "6",
+  author        = "C. A. Paulson and J. J. Simpson",
+  year          = "1977",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1977)007<0952:imituo>2.0.co;2"
+}
+
+@article{         penduff.le-sommer.ea_OS07,
+  title         = "Influence of numerical schemes on current-topography
+                  interactions in 1/4\deg global ocean simulations",
+  pages         = "509--524",
+  journal       = "Ocean Science",
+  volume        = "3",
+  number        = "4",
+  author        = "T. Penduff and J. {Le Sommer} and B. Barnier and A.-M.
+                  Tr\'{e}guier and J.-M. Molines and G. Madec",
+  year          = "2007",
+  month         = "dec",
+  publisher     = "Copernicus GmbH",
+  issn          = "1812-0792",
+  doi           = "10.5194/os-3-509-2007"
+}
+
+@article{         phillips_TAMS59,
+  title         = "Dissipative operators and hyperbolic systems of partial
+                  differential equations",
+  pages         = "193--254",
+  journal       = "Transactions of the American Mathematical Society",
+  volume        = "90",
+  number        = "2",
+  author        = "R. S. Phillips",
+  year          = "1959",
+  month         = "feb",
+  publisher     = "American Mathematical Society (AMS)",
+  issn          = "0002-9947",
+  doi           = "10.1090/s0002-9947-1959-0104919-1"
+}
+
+@article{         qiao.yuan.ea_OD10,
+  title         = "A three-dimensional surface wave–ocean circulation coupled 
+                  model and its initial testing",
+  pages         = "1339--1335",
+  journal       = "Ocean Dynamics",
+  volume        = "60",
+  number        = "5",
+  author        = "F. Qiao and Y. Yuan and T. Ezer and C. Xia and 
+                   Y. Yang and X. Lu and Z. Song ",
+  year          = "2010",
+  month         = "oct",
+  publisher     = "Springer-Verlag",
+  issn          = "1616-7341",
+  doi           = "10.1007/s10236-010-0326-y"
+}
+
+@article{         redi_JPO82,
+  title         = "Oceanic isopycnal mixing by coordinate rotation",
+  pages         = "1154--1158",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "12",
+  number        = "10",
+  author        = "M. H. Redi",
+  year          = "1982",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1982)012<1154:oimbcr>2.0.co;2"
+}
+
+@article{         reffray.guillaume.ea_GMD15,
+  title         = "Modelling turbulent vertical mixing sensitivity using
+                   a 1-D version of NEMO",
+  pages         = "69--86",
+  journal       = "Geoscientific Model Development",
+  volume        = "8",
+  number        = "1",
+  author        = "G. Reffray. and R. Bourdalle-Badie and C. Calone",
+  year          = "2015",
+  month         = "jan",
+  publisher     = "Copernicus GmbH",
+  issn          = "1991-9603",
+  doi           = "10.5194/gmd-8-69-2015"
+}
+
+@book{            richtmyer.morton_bk67,
+  pages         = "405",
+  booktitle     = "Difference methods for initial-value problems",
+  edition       = "2",
+  series        = "Interscience tracts in pure and applied mathematics",
+  author        = "R. D. Richtmyer and K. W. Morton",
+  year          = "1967",
+  publisher     = "Interscience",
+  issn          = "0074-994X",
+  isbn          = "9780470720400",
+  url           = "https://books.google.fr/books?id=nd1QAAAAMAAJ"
+}
+
+@article{         robert_JMSJ66,
+  title         = "The integration of a low order spectral form of the
+                  primitive meteorological equations",
+  pages         = "237--245",
+  journal       = "Journal of the Meteorological Society of Japan",
+  volume        = "44",
+  number        = "5",
+  author        = "A. J. Robert",
+  year          = "1966",
+  publisher     = "Meteorological Society of Japan",
+  issn          = "2186-9057",
+  doi           = "10.2151/jmsj1965.44.5\_237"
+}
+
+@article{         rodgers.aumont.ea_B14,
+  title         = "Strong sensitivity of Southern Ocean carbon uptake and
+                  nutrient cycling to wind stirring",
+  pages         = "4077--4098",
+  journal       = "Biogeosciences",
+  volume        = "11",
+  number        = "15",
+  author        = "K. B. Rodgers and O. Aumont and S. E. Mikaloff Fletcher
+                  and Y. Plancherel and L. Bopp and C. {de Boyer
+                  Mont\'{e}gut} and D. Iudicone and R. F. Keeling and G.
+                  Madec and R. Wanninkhof",
+  year          = "2014",
+  month         = "aug",
+  publisher     = "Copernicus GmbH",
+  issn          = "1726-4189",
+  doi           = "10.5194/bg-11-4077-2014"
+}
+
+@article{         rodi_JGR87,
+  title         = "Examples of calculation methods for flow and mixing in
+                  stratified fluids",
+  pages         = "5305--5328",
+  journal       = "Journal of Geophysical Research",
+  volume        = "92",
+  number        = "C5",
+  author        = "W. Rodi",
+  year          = "1987",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/jc092ic05p05305"
+}
+
+@article{         roquet.madec.ea_JPO15,
+  title         = "Defining a simplified yet ``realistic'' equation of state
+                  for seawater",
+  pages         = "2564--2579",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "45",
+  number        = "10",
+  author        = "F. Roquet and G. Madec and L. Brodeau and J. Nycander",
+  year          = "2015",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/jpo-d-15-0080.1"
+}
+
+@article{         roquet.madec.ea_OM15,
+  title         = "Accurate polynomial expressions for the density and
+                  specific volume of seawater using the {TEOS}-10 standard",
+  pages         = "29--43",
+  journal       = "Ocean Modelling",
+  volume        = "90",
+  author        = "F. Roquet and G. Madec and T. J. McDougall and P. M.
+                  Barker",
+  year          = "2015",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2015.04.002"
+}
+
+@article{         roullet.madec_JGR00,
+  title         = "Salt conservation, free surface, and varying levels: {A}
+                  new formulation for Ocean General Circulation Models",
+  pages         = "23927--23942",
+  journal       = "Journal of Geophysical Research",
+  volume        = "105",
+  number        = "C10",
+  author        = "G. Roullet and G. Madec",
+  year          = "2000",
+  month         = "oct",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2000jc900089"
+}
+
+@article{         sarmiento.bryan_JGR82,
+  title         = "An ocean transport model for the North Atlantic",
+  pages         = "394--409",
+  journal       = "Journal of Geophysical Research",
+  volume        = "87",
+  number        = "C1",
+  author        = "J. L. Sarmiento and K. Bryan",
+  year          = "1982",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/jc087ic01p00394"
+}
+
+@article{         saunders_JAS67,
+  title         = "The temperature at the ocean-air interface",
+  pages         = "269--273",
+  journal       = "Journal of the Atmospheric Sciences",
+  volume        = "24",
+  number        = "3",
+  author        = "P. M. Saunders",
+  year          = "1967",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0469",
+  doi           = "10.1175/1520-0469(1967)024<0269:ttatoa>2.0.co;2"
+}
+
+@article{         shchepetkin.mcwilliams_OM05,
+  title         = "The regional oceanic modeling system ({ROMS}): a
+                  split-explicit, free-surface,
+                  topography-following-coordinate oceanic model",
+  pages         = "347--404",
+  journal       = "Ocean Modelling",
+  volume        = "9",
+  number        = "4",
+  author        = "A. F. Shchepetkin and J. C. McWilliams",
+  year          = "2005",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2004.08.002"
+}
+
+@inbook{          shchepetkin.mcwilliams_ibk09,
+  title         = "Computational kernel algorithms for fine-scale,
+                  multiprocess, longtime oceanic simulations",
+  chapter       = "2",
+  pages         = "121--183",
+  booktitle     = "Computational Methods for the Atmosphere and the Oceans",
+  editor        = "R. M. Temam and J. J. Tribbia",
+  series        = "Handbook of Numerical Analysis",
+  volume        = "14",
+  author        = "A. F. Shchepetkin and J. C. McWilliams",
+  year          = "2009",
+  publisher     = "Elsevier",
+  issn          = "1570-8659",
+  isbn          = "9780444518934",
+  doi           = "10.1016/s1570-8659(08)01202-0"
+}
+
+@article{         shchepetkin_OM15,
+  title         = "An Adaptive, Courant-number-dependent implicit
+  		 scheme for vertical advection in oceanic modeling",
+  pages         = "38--69",
+  journal       = "Ocean Modelling",
+  volume        = "91",
+  author        = "A. F. Shchepetkin",
+  year          = "2015",
+  month         = "july",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2015.03.006"
+}
+
+@article{         siddorn.furner_OM13,
+  title         = "An analytical stretching function that combines the best
+                  attributes of geopotential and terrain-following vertical
+                  coordinates",
+  pages         = "1--13",
+  journal       = "Ocean Modelling",
+  volume        = "66",
+  author        = "J. R. Siddorn and R. Furner",
+  year          = "2013",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2013.02.001"
+}
+
+@article{         simmons.jayne.ea_OM04,
+  title         = "Tidally driven mixing in a numerical model of the ocean
+                  general circulation",
+  pages         = "245--263",
+  journal       = "Ocean Modelling",
+  volume        = "6",
+  number        = "3-4",
+  author        = "H. L. Simmons and S. R. Jayne and L. C. {St Laurent} and
+                  A. J. Weaver",
+  year          = "2004",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/s1463-5003(03)00011-8"
+}
+
+@article{         smagorinsky_MW63,
+  title         = "General circulation experiments with the primitive equations: I. The basic experiment ",
+  pages         = "99--164",
+  journal       = "Monthly Weather Review",
+  volume        = "91",
+  number        = "3",
+  author        = "J. Smagorinsky",
+  year          = "1963",
+  month         = "mar",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1963)091<0099:GCEWTP>2.3.CO;2"
+}
+
+@article{         song.haidvogel_JCP94,
+  title         = "A semi-implicit ocean circulation model using a
+                  generalized topography-following coordinate system",
+  pages         = "228--244",
+  journal       = "Journal of Computational Physics",
+  volume        = "115",
+  number        = "1",
+  author        = "Y. Song and D. Haidvogel",
+  year          = "1994",
+  month         = "nov",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1006/jcph.1994.1189"
+}
+
+@article{         song_MWR98,
+  title         = "A General Pressure Gradient Formulation for Ocean Models.
+                  Part {I}: Scheme Design and Diagnostic Analysis",
+  pages         = "3213--3230",
+  journal       = "Monthly Weather Review",
+  volume        = "126",
+  number        = "12",
+  author        = "Y. T. Song",
+  year          = "1998",
+  month         = "dec",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0493",
+  doi           = "10.1175/1520-0493(1998)126<3213:agpgff>2.0.co;2"
+}
+
+@article{         st-laurent.nash_DSR04,
+  title         = "An examination of the radiative and dissipative properties
+                  of deep ocean internal tides",
+  pages         = "3029--3042",
+  journal       = "Deep Sea Research",
+  volume        = "51",
+  number        = "25-26",
+  author        = "L. C. {St Laurent} and J. D. Nash",
+  year          = "2004",
+  month         = "dec",
+  publisher     = "Elsevier BV",
+  issn          = "0967-0645",
+  doi           = "10.1016/j.dsr2.2004.09.008"
+}
+
+@article{         st-laurent.simmons.ea_GRL02,
+  title         = "Estimating tidally driven mixing in the deep ocean",
+  pages         = "2101--2104",
+  journal       = "Geophysical Research Letters",
+  volume        = "29",
+  number        = "23",
+  author        = "L. C. {St Laurent} and H. L. Simmons and S. R. Jayne",
+  year          = "2002",
+  month         = "dec",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0094-8276",
+  doi           = "10.1029/2002gl015633"
+}
+
+@article{         stacey_JPO99,
+  title         = "Simulations of the wind-forced near-surface circulation in
+                  Knight Inlet: {A} parameterization of the roughness length",
+  pages         = "1363--1367",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "29",
+  number        = "6",
+  author        = "M. W. Stacey",
+  year          = "1999",
+  month         = "jun",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1999)029<1363:sotwfn>2.0.co;2"
+}
+
+@article{         steele.morley.ea_JC01,
+  title         = "{PHC}: {A} global ocean hydrography with a high-quality
+                  Arctic Ocean",
+  pages         = "2079--2087",
+  journal       = "Journal of Climate",
+  volume        = "14",
+  number        = "9",
+  author        = "M. Steele and R. Morley and W. Ermold",
+  year          = "2001",
+  month         = "may",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0442",
+  doi           = "10.1175/1520-0442(2001)014<2079:pagohw>2.0.co;2"
+}
+
+@article{         stein.stein_N92,
+  title         = "A model for the global variation in oceanic depth and heat
+                  flow with lithospheric age",
+  pages         = "123--129",
+  journal       = "Nature",
+  volume        = "359",
+  number        = "6391",
+  author        = "C. A. Stein and S. Stein",
+  year          = "1992",
+  month         = "sep",
+  publisher     = "Springer Nature",
+  issn          = "1476-4687",
+  doi           = "10.1038/359123a0"
+}
+
+@inbook{          stokes_ibk09,
+  title         = "On the theory of oscillatory waves",
+  chapter       = "12",
+  pages         = "197--229",
+  booktitle     = "Mathematical and Physical Papers",
+  series        = "Cambridge Library Collection - Mathematics",
+  volume        = "1",
+  author        = "G. G. Stokes",
+  year          = "2009",
+  publisher     = "Cambridge University Press",
+  isbn          = "9780511702242",
+  doi           = "10.1017/cbo9780511702242.013"
+}
+
+@article{         takaya.bidlot.ea_JGR10,
+  title         = "Refinements to a prognostic scheme of skin sea surface
+                  temperature",
+  pages         = "C06009",
+  journal       = "Journal of Geophysical Research",
+  volume        = "115",
+  number        = "C6",
+  author        = "Y. Takaya and J-R. Bidlot and A. C. M. Beljaars and P. A.
+                  E. M. Janssen",
+  year          = "2010",
+  month         = "jun",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/2009jc005985"
+}
+
+@article{         talagrand_JAS72,
+  title         = "On the damping of high-frequency motions in
+                  four-dimensional assimilation of meteorological data",
+  pages         = "1571--1574",
+  journal       = "Journal of the Atmospheric Sciences",
+  volume        = "29",
+  number        = "8",
+  author        = "O. Talagrand",
+  year          = "1972",
+  month         = "nov",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0469",
+  doi           = "10.1175/1520-0469(1972)029<1571:otdohf>2.0.co;2"
+}
+
+@article{         treguier.dukowicz.ea_JGR96,
+  title         = "Properties of nonuniform grids used in ocean general
+                  circulation models",
+  pages         = "20877--20881",
+  journal       = "Journal of Geophysical Research",
+  volume        = "101",
+  number        = "C9",
+  author        = "A.-M. Tr\'{e}guier and J. K. Dukowicz and K. Bryan",
+  year          = "1996",
+  month         = "sep",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/96jc01753"
+}
+
+@article{         treguier.held.ea_JPO97,
+  title         = "Parameterization of Quasigeostrophic Eddies in Primitive
+                  Equation Ocean Models",
+  pages         = "567--580",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "27",
+  number        = "4",
+  author        = "A. M. Tr\'{e}guier and I. M. Held and V. D. Larichev",
+  year          = "1997",
+  month         = "apr",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1997)027<0567:poqeip>2.0.co;2"
+}
+
+@article{         treguier_JGR92,
+  title         = "Kinetic energy analysis of an eddy resolving, primitive
+                  equation model of the North Atlantic",
+  pages         = "687--701",
+  journal       = "Journal of Geophysical Research",
+  volume        = "97",
+  number        = "C1",
+  author        = "A. M. Tr\'{e}guier",
+  year          = "1992",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/91jc02350"
+}
+
+@article{         tu.tsuang_GRL05,
+  title         = "Cool-skin simulation by a one-column ocean model",
+  pages         = "L22602",
+  journal       = "Geophysical Research Letters",
+  volume        = "32",
+  number        = "22",
+  author        = "C.-Y. Tu and B.-J. Tsuang",
+  year          = "2005",
+  month         = "nov",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0094-8276",
+  doi           = "10.1029/2005gl024252"
+}
+
+@article{         umlauf.burchard_CSR05,
+  title         = "Second-order turbulence closure models for geophysical
+                  boundary layers. {A} review of recent work",
+  pages         = "795--827",
+  journal       = "Continental Shelf Research",
+  volume        = "25",
+  number        = "7-8",
+  author        = "L. Umlauf and H. Burchard",
+  year          = "2005",
+  month         = "may",
+  publisher     = "Elsevier BV",
+  issn          = "0278-4343",
+  doi           = "10.1016/j.csr.2004.08.004"
+}
+
+@article{         umlauf.burchard_JMR03,
+  title         = "A generic length-scale equation for geophysical turbulence
+                  models",
+  pages         = "235--265",
+  journal       = "Journal of Marine Research",
+  volume        = "61",
+  number        = "2",
+  author        = "L. Umlauf and H. Burchard",
+  year          = "2003",
+  month         = "mar",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "0022-2402",
+  doi           = "10.1357/002224003322005087"
+}
+
+@book{            vallis_bk06,
+  booktitle     = "Atmospheric and Oceanic Fluid Dynamics",
+  author        = "G. K. Vallis",
+  year          = "2006",
+  publisher     = "Cambridge University Press",
+  isbn          = "9780511790447",
+  doi           = "10.1017/cbo9780511790447"
+}
+
+@article{         vancoppenolle.fichefet.ea_OM09*a,
+  title         = "Simulating the mass balance and salinity of Arctic and
+                  Antarctic sea ice. 1. Model description and validation",
+  pages         = "33--53",
+  journal       = "Ocean Modelling",
+  volume        = "27",
+  number        = "1-2",
+  author        = "M. Vancoppenolle and T. Fichefet and H. Goosse and S.
+                  Bouillon and G. Madec and M. A. Morales Maqueda",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2008.10.005"
+}
+
+@article{         vancoppenolle.fichefet.ea_OM09*b,
+  title         = "Simulating the mass balance and salinity of Arctic and
+                  Antarctic sea ice. 2. Importance of sea ice salinity
+                  variations",
+  pages         = "54--69",
+  journal       = "Ocean Modelling",
+  volume        = "27",
+  number        = "1-2",
+  author        = "M. Vancoppenolle and T. Fichefet and H. Goosse",
+  year          = "2009",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2008.11.003"
+}
+
+@article{         warner.defne.ea_CG13,
+  title         = "A wetting and drying scheme for {ROMS}",
+  pages         = "54--61",
+  journal       = "Computers \& Geosciences",
+  volume        = "58",
+  author        = "J. C. Warner and Z. Defne and K. Haas and H. G. Arango",
+  year          = "2013",
+  month         = "aug",
+  publisher     = "Elsevier BV",
+  issn          = "0098-3004",
+  doi           = "10.1016/j.cageo.2013.05.004"
+}
+
+@article{         warner.sherwood.ea_OM05,
+  title         = "Performance of four turbulence closure models implemented
+                  using a generic length scale method",
+  pages         = "81--113",
+  journal       = "Ocean Modelling",
+  volume        = "8",
+  number        = "1-2",
+  author        = "J. C. Warner and C. R. Sherwood and H. G. Arango and R. P.
+                  Signell",
+  year          = "2005",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "1463-5003",
+  doi           = "10.1016/j.ocemod.2003.12.003"
+}
+
+@article{         weatherly_JMR84,
+  title         = "An estimate of bottom frictional dissipation by Gulf
+                  Stream fluctuations",
+  pages         = "289--301",
+  journal       = "Journal of Marine Research",
+  volume        = "42",
+  number        = "2",
+  author        = "G. L. Weatherly",
+  year          = "1984",
+  month         = "may",
+  publisher     = "Journal of Marine Research/Yale",
+  issn          = "1543-9542",
+  doi           = "10.1357/002224084788502729"
+}
+
+@article{         weaver.eby_JPO97,
+  title         = "On the numerical implementation of advection schemes for
+                  use in conjuction with various mixing parameterizations in
+                  the {GFDL} ocean model",
+  pages         = "369--377",
+  journal       = "Journal of Physical Oceanography",
+  volume        = "27",
+  number        = "2",
+  author        = "A. J. Weaver and M. Eby",
+  year          = "1997",
+  month         = "feb",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0485",
+  doi           = "10.1175/1520-0485(1997)027<0369:otnioa>2.0.co;2"
+}
+
+@article{         webb.de-cuevas.ea_JAOT98,
+  title         = "Improved Advection Schemes for Ocean Models",
+  pages         = "1171--1187",
+  journal       = "Journal of Atmospheric and Oceanic Technology",
+  volume        = "15",
+  number        = "5",
+  author        = "D. J. Webb and B. A. {de Cuevas} and C. S. Richmond",
+  year          = "1998",
+  month         = "oct",
+  publisher     = "American Meteorological Society",
+  issn          = "1520-0426",
+  doi           = "10.1175/1520-0426(1998)015<1171:iasfom>2.0.co;2"
+}
+
+@article{         white.hoskins.ea_QJRMS05,
+  title         = "Consistent approximate models of the global atmosphere: shallow, deep,
+                  hydrostatic, quasi-hydrostatic and non-hydrostatic",
+  pages         = "2081--2107",
+  journal       = "Quarterly Journal of the Royal Meteorological Society",
+  volume        = "131",
+  author        = "A. A. White and B. J. Hoskins and I. Roulstone and A. Staniforth",
+  year          = "2005",
+  doi           = "10.1256/qj.04.49"
+}
+
+@article{         white.adcroft.ea_JCP09,
+  title         = "High-order regridding-remapping schemes for continuous
+                  isopycnal and generalized coordinates in ocean models",
+  pages         = "8665--8692",
+  journal       = "Journal of Computational Physics",
+  volume        = "228",
+  number        = "23",
+  author        = "L. White and A. Adcroft and R. Hallberg",
+  year          = "2009",
+  month         = "dec",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1016/j.jcp.2009.08.016"
+}
+
+@article{         wilcox_AJ88,
+  title         = "Reassessment of the scale-determining equation for
+                  advanced turbulence models",
+  pages         = "1299--1310",
+  journal       = "AIAA Journal",
+  volume        = "26",
+  number        = "11",
+  author        = "D. C. Wilcox",
+  year          = "1988",
+  month         = "nov",
+  publisher     = "American Institute of Aeronautics and Astronautics (AIAA)",
+  issn          = "1533-385X",
+  doi           = "10.2514/3.10041"
+}
+
+@article{         willebrand.barnier.ea_PO01,
+  title         = "Circulation characteristics in three eddy-permitting
+                  models of the North Atlantic",
+  pages         = "123--161",
+  journal       = "Progress in Oceanography",
+  volume        = "48",
+  number        = "2-3",
+  author        = "J. Willebrand and B. Barnier and C. B{\"{o}}ning and C.
+                  Dieterich and P. D. Killworth and C. Le Provost and Y. Jia
+                  and J.-M. Molines and A. L. New",
+  year          = "2001",
+  month         = "jan",
+  publisher     = "Elsevier BV",
+  issn          = "0079-6611",
+  doi           = "10.1016/s0079-6611(01)00003-9"
+}
+
+@article{         zalesak_JCP79,
+  title         = "Fully multidimensional flux-corrected transport algorithms
+                  for fluids",
+  pages         = "335--362",
+  journal       = "Journal of Computational Physics",
+  volume        = "31",
+  number        = "3",
+  author        = "S. T. Zalesak",
+  year          = "1979",
+  month         = "jun",
+  publisher     = "Elsevier BV",
+  issn          = "0021-9991",
+  doi           = "10.1016/0021-9991(79)90051-2"
+}
+
+@article{         zhang.endoh_JGR92,
+  title         = "A free surface General Circulation Model for the tropical
+                  Pacific Ocean",
+  pages         = "11237--11255",
+  journal       = "Journal of Geophysical Research",
+  volume        = "97",
+  number        = "C7",
+  author        = "R.-H. Zhang and M. Endoh",
+  year          = "1992",
+  publisher     = "American Geophysical Union (AGU)",
+  issn          = "0148-0227",
+  doi           = "10.1029/92jc00911"
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/chapters.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/chapters.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/chapters.tex	(revision 14097)
@@ -0,0 +1,20 @@
+\subfile{../subfiles/chap_model_basics}   %% 1.
+\subfile{../subfiles/chap_time_domain}    %% 2.  Time discretisation (time stepping strategy)
+\subfile{../subfiles/chap_DOM}            %% 3.  Space discretisation
+\subfile{../subfiles/chap_TRA}            %% 4.  Tracer advection/diffusion equation
+\subfile{../subfiles/chap_DYN}            %% 5.  Dynamics : momentum equation
+\subfile{../subfiles/chap_SBC}            %% 6.  Surface Boundary Conditions
+\subfile{../subfiles/chap_LBC}            %% 7.  Lateral Boundary Conditions
+\subfile{../subfiles/chap_LDF}            %% 8.  Lateral diffusion
+\subfile{../subfiles/chap_ZDF}            %% 9.  Vertical diffusion
+\subfile{../subfiles/chap_DIA}            %% 10. Outputs and Diagnostics
+\subfile{../subfiles/chap_OBS}            %% 11. Observation operator
+\subfile{../subfiles/chap_ASM}            %% 12. Assimilation increments
+\subfile{../subfiles/chap_STO}            %% 13. Stochastic param.
+\subfile{../subfiles/chap_misc}           %% 14. Miscellaneous topics
+\subfile{../subfiles/chap_cfgs}           %% 15. Predefined configurations
+
+%% Not included
+%\subfile{../subfiles/chap_model_basics_zstar}
+%\subfile{../subfiles/chap_DIU}
+%\subfile{../subfiles/chap_conservation}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/introduction.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/introduction.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/introduction.tex	(revision 14097)
@@ -0,0 +1,142 @@
+
+\chapter*{Introduction}
+
+%\chaptertoc
+
+%\paragraph{Changes record} ~\\
+
+%\thispagestyle{plain}
+
+%{\footnotesize
+%  \begin{tabularx}{\textwidth}{l||X|X}
+%    Release & Author(s) & Modifications \\
+%    \hline
+%    {\em x.x} & {\em ...} & {\em ...}   \\
+%    {\em ...} & {\em ...} & {\em ...}   \\
+%  \end{tabularx}
+%}
+
+%\clearpage
+
+The \textbf{N}ucleus for \textbf{E}uropean \textbf{M}odelling of the \textbf{O}cean (\NEMO) is
+a framework of ocean related engines, namely the aforementioned for
+the ocean dynamics and thermodynamics,
+\SIcube \footnote{\textbf{S}ea-\textbf{I}ce modelling \textbf{I}ntegrated \textbf{I}nitiative}
+for the sea-ice dynamics and thermodynamics,
+\TOP \footnote{\textbf{T}racer in the \textbf{O}cean \textbf{P}aradigm} for
+the biogeochemistry (both transport and sources minus sinks
+(\PISCES \footnote{
+  \textbf{P}elagic \textbf{I}nteractions \textbf{S}cheme for
+  \textbf{C}arbon and \textbf{E}cosystem \textbf{S}tudies
+}
+)).
+The ocean component has been developed from the legacy of
+the \OPA \footnote{\textbf{O}c\'{e}an \textbf{PA}rall\'{e}lis\'{e} (French)}
+model, described in \citet{madec.delecluse.ea_NPM98}.
+This model has been used for a wide range of applications, both regional or global,
+as a forced ocean model and as a model coupled with the sea-ice and/or the atmosphere.
+
+This manual provides information about the physics represented by the ocean component of \NEMO\ and
+the rationale for the choice of numerical schemes and the model design.
+For the use of framework,
+a guide which gathers the \texttt{README} files spread out in the source code can be build and
+exported in a web or printable format (see \path{./doc/rst}).
+Also a online copy is available on the \href{http://forge.ipsl.jussieu.fr/nemo}{forge platform}.
+
+%% =================================================================================================
+\section*{Manual outline}
+
+\subsection*{Chapters}
+
+The manual mirrors the organization of the model and it is organised in as follows:
+after the presentation of the continuous equations
+(primitive equations with temperature and salinity, and an equation of seawater) in the next chapter,
+the following chapters refer to specific terms of the equations each associated with
+a group of modules.
+
+\begin{description}
+\item [\nameref{chap:MB}] presents the equations and their assumptions, the vertical coordinates used,
+and the subgrid scale physics.
+The equations are written in a curvilinear coordinate system, with a choice of vertical coordinates
+($z$, $s$, \zstar, \sstar, \ztilde, \stilde, and a mix of them).
+Momentum equations are formulated in vector invariant or flux form.
+Dimensional units in the meter, kilogram, second (MKS) international system are used throughout.
+The following chapters deal with the discrete equations.
+\item [\nameref{chap:TD}] presents the model time stepping environment.
+it is a three level scheme in which the tendency terms of the equations are evaluated either
+centered in time, or forward, or backward depending of the nature of the term.
+\item [\nameref{chap:DOM}] presents the model \textbf{DOM}ain.
+It is discretised on a staggered grid (Arakawa C grid) with masking of land areas.
+Vertical discretisation used depends on both how the bottom topography is represented and whether
+the free surface is linear or not.
+Full step or partial step $z$-coordinate or $s$- (terrain-following) coordinate is used with
+linear free surface (level position are then fixed in time).
+In non-linear free surface, the corresponding rescaled height coordinate formulation
+(\zstar or \sstar) is used
+(the level position then vary in time as a function of the sea surface heigh).
+\item [\nameref{chap:TRA} and \nameref{chap:DYN}] describe the discretisation of
+the prognostic equations for the active \textbf{TRA}cers (potential temperature and salinity) and
+the momentum (\textbf{DYN}amic).
+Explicit, split-explicit and filtered free surface formulations are implemented.
+A number of numerical schemes are available for momentum advection,
+for the computation of the pressure gradients, as well as for the advection of tracers
+(second or higher order advection schemes, including positive ones).
+\item [\nameref{chap:SBC}] can be implemented as prescribed fluxes,
+or bulk formulations for the surface fluxes (wind stress, heat, freshwater).
+The model allows penetration of solar radiation.
+There is an optional geothermal heating at the ocean bottom.
+Within the \NEMO\ system the ocean model is interactively coupled with
+a sea ice model (\SIcube) and a biogeochemistry model (\PISCES).
+Interactive coupling to Atmospheric models is possible via the \OASIS\ coupler.
+Two-way nesting is also available through an interface to the \AGRIF\ package,
+\ie\ \textbf{A}daptative \textbf{G}rid \textbf{R}efinement in \textbf{F}ortran
+\citep{debreu.vouland.ea_CG08}.
+The interface code for coupling to an alternative sea ice model (\CICE) has now been upgraded so that
+it works for both global and regional domains.
+\item [\nameref{chap:LBC}] presents the \textbf{L}ateral
+\textbf{B}oun\textbf{D}ar\textbf{Y} \textbf{C}onditions.
+Global configurations of the model make use of the ORCA tripolar grid,
+with special north fold boundary condition.
+Free-slip or no-slip boundary conditions are allowed at land boundaries.
+Closed basin geometries as well as periodic domains and open boundary conditions are possible.
+\item [\nameref{chap:LDF} and \nameref{chap:ZDF}] describe the physical parameterisations
+(\textbf{L}ateral \textbf{D}i\textbf{F}fusion and vertical \textbf{Z} \textbf{D}i\textbf{F}fusion)
+The model includes an implicit treatment of vertical viscosity and diffusivity.
+The lateral Laplacian and biharmonic viscosity and diffusion can be rotated following
+a geopotential or neutral direction.
+There is an optional eddy induced velocity \citep{gent.mcwilliams_JPO90} with
+a space and time variable coefficient \citet{treguier.held.ea_JPO97}.
+The model has vertical harmonic viscosity and diffusion with a space and time variable coefficient,
+with options to compute the coefficients with \citet{blanke.delecluse_JPO93},
+\citet{pacanowski.philander_JPO81}, or \citet{umlauf.burchard_JMR03} mixing schemes.
+\item [\nameref{chap:DIA}] describes model \textbf{I}n-\textbf{O}utputs \textbf{M}anagement and
+specific online \textbf{DIA}gnostics.
+The diagnostics includes the output of all the tendencies of the momentum and tracers equations,
+the output of tracers \textbf{TR}en\textbf{D}s averaged over the time evolving mixed layer,
+the output of the tendencies of the barotropic vorticity equation,
+the computation of on-line \textbf{FLO}ats trajectories...
+\item [\nameref{chap:OBS}] describes a tool which reads in \textbf{OBS}ervation files
+(profile temperature and salinity, sea surface temperature, sea level anomaly and
+sea ice concentration) and calculates an interpolated model equivalent value at
+the observation location and nearest model timestep.
+Originally developed of data assimilation, it is a fantastic tool for model and data comparison.
+\item [\nameref{chap:ASM}] describes how increments produced by
+data \textbf{A}s\textbf{S}i\textbf{M}ilation may be applied to the model equations.
+\item [\nameref{chap:STO}]
+\item [\nameref{chap:MISC}] (including solvers)
+\item [\nameref{chap:CFGS}] provides finally a brief introduction to
+the pre-defined model configurations
+(water column model \texttt{C1D}, ORCA and GYRE families of configurations).
+\end{description}
+
+%% =================================================================================================
+\subsection*{Appendices}
+
+\begin{description}
+\item [\nameref{apdx:SCOORD}]
+\item [\nameref{apdx:DIFFOPERS}]
+\item [\nameref{apdx:INVARIANTS}]
+\item [\nameref{apdx:TRIADS}]
+\item [\nameref{apdx:DOMCFG}]
+\item [\nameref{apdx:CODING}]
+\end{description}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/settings.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/settings.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/settings.tex	(revision 14097)
@@ -0,0 +1,20 @@
+%% Engine (subfolder name)
+\def \engine{NEMO}
+
+%% Cover page settings
+\def \spacetop{  \vspace*{1.85cm} }
+\def \heading{NEMO ocean engine}
+%\def \subheading{}
+\def \spacedown{ \vspace*{0.75cm } }
+\def \authorswidth{ 0.3\linewidth}
+\def \rulelenght{270pt}
+\def \abstractwidth{0.6\linewidth}
+
+%% Manual color (frontpage banner, links  and chapter boxes)
+\def \setmanualcolor{ \definecolor{manualcolor}{cmyk}{1, .60, 0, .4} }
+
+%% IPSL publication number
+\def \ipslnum{27}
+
+%% Zenodo ID, i.e. doi:10.5281/zenodo.\([0-9]*\)
+\def \zid{1464816}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/main/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_DOMAINcfg.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_DOMAINcfg.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_DOMAINcfg.tex	(revision 14097)
@@ -0,0 +1,534 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{A brief guide to the DOMAINcfg tool}
+\label{apdx:DOMCFG}
+
+%    {\em 4.0} & {\em Andrew Coward} & {\em Created at v4.0 from materials removed from chap\_DOM that are still relevant to the \forcode{DOMAINcfg} tool and which illustrate and explain the choices to be made by the user when setting up new domains }  \\
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+This appendix briefly describes some of the options available in the
+\forcode{DOMAINcfg} tool mentioned in \autoref{chap:DOM}.
+
+This tool will evolve into an independent utility with its own documentation but its
+current manifestation is mostly a wrapper for \NEMO\ \forcode{DOM} modules more aligned to
+those in the previous versions of \NEMO. These versions allowed the user to define some
+horizontal and vertical grids through additional namelist parameters. Explanations of
+these parameters are retained here for reference pending better documentation for
+\forcode{DOMAINcfg}. Please note that the namelist blocks named in this appendix refer to
+those read by \forcode{DOMAINcfg} via its own \forcode{namelist_ref} and
+\forcode{namelist_cfg} files. Although, due to their origins, these namelists share names
+with those used by \NEMO, they are not interchangeable and should be considered independent
+of those described elsewhere in this manual.
+
+%% =================================================================================================
+\section{Choice of horizontal grid}
+\label{sec:DOMCFG_hor}
+
+\begin{listing}
+  \nlst{namdom_domcfg}
+  \caption{\forcode{&namdom_domcfg}}
+  \label{lst:namdom_domcfg}
+\end{listing}
+
+The user has three options available in defining a horizontal grid, which involve the
+namelist variable \np{jphgr_mesh}{jphgr\_mesh} of the \nam{dom}{dom} (\texttt{DOMAINcfg} variant only)
+namelist.
+
+\begin{description}
+ \item [{\np{jphgr_mesh}{jphgr\_mesh}=0}]  The most general curvilinear orthogonal grids.
+  The coordinates and their first derivatives with respect to $i$ and $j$ are provided
+  in a input file (\ifile{coordinates}), read in \rou{hgr\_read} subroutine of the domhgr module.
+  This is now the only option available within \NEMO\ itself from v4.0 onwards.
+\item [{\np{jphgr_mesh}{jphgr\_mesh}=1 to 5}] A few simple analytical grids are provided (see below).
+  For other analytical grids, the \mdl{domhgr} module (\texttt{DOMAINcfg} variant) must be
+  modified by the user. In most cases, modifying the \mdl{usrdef\_hgr} module of \NEMO\ is
+  a better alternative since this is designed to allow simple analytical domains to be
+  configured and used without the need for external data files.
+\end{description}
+
+There are two simple cases of geographical grids on the sphere. With
+\np{jphgr_mesh}{jphgr\_mesh}=1, the grid (expressed in degrees) is regular in space,
+with grid sizes specified by parameters \np{ppe1_deg}{ppe1\_deg} and \np{ppe2_deg}{ppe2\_deg},
+respectively. Such a geographical grid can be very anisotropic at high latitudes
+because of the convergence of meridians (the zonal scale factors $e_1$
+become much smaller than the meridional scale factors $e_2$). The Mercator
+grid (\np{jphgr_mesh}{jphgr\_mesh}=4) avoids this anisotropy by refining the meridional scale
+factors in the same way as the zonal ones. In this case, meridional scale factors
+and latitudes are calculated analytically using the formulae appropriate for
+a Mercator projection, based on \np{ppe1_deg}{ppe1\_deg} which is a reference grid spacing
+at the equator (this applies even when the geographical equator is situated outside
+the model domain).
+
+In these two cases (\np{jphgr_mesh}{jphgr\_mesh}=1 or 4), the grid position is defined by the
+longitude and latitude of the south-westernmost point (\np{ppglamt0}
+and \np{ppgphi0}{ppgphi0}). Note that for the Mercator grid the user need only provide
+an approximate starting latitude: the real latitude will be recalculated analytically,
+in order to ensure that the equator corresponds to line passing through $t$-
+and $u$-points.
+
+Rectangular grids ignoring the spherical geometry are defined with
+\np{jphgr_mesh}{jphgr\_mesh} = 2, 3, 5. The domain is either an $f$-plane (\np{jphgr_mesh}{jphgr\_mesh} = 2,
+Coriolis factor is constant) or a beta-plane (\np{jphgr_mesh}{jphgr\_mesh} = 3, the Coriolis factor
+is linear in the $j$-direction). The grid size is uniform in meter in each direction,
+and given by the parameters \np{ppe1_m}{ppe1\_m} and \np{ppe2_m}{ppe2\_m} respectively.
+The zonal grid coordinate (\textit{glam} arrays) is in kilometers, starting at zero
+with the first $t$-point. The meridional coordinate (gphi. arrays) is in kilometers,
+and the second $t$-point corresponds to coordinate $gphit=0$. The input
+variable \np{ppglam0}{ppglam0} is ignored. \np{ppgphi0}{ppgphi0} is used to set the reference
+latitude for computation of the Coriolis parameter. In the case of the beta plane,
+\np{ppgphi0}{ppgphi0} corresponds to the center of the domain. Finally, the special case
+\np{jphgr_mesh}{jphgr\_mesh}=5 corresponds to a beta plane in a rotated domain for the
+GYRE configuration, representing a classical mid-latitude double gyre system.
+The rotation allows us to maximize the jet length relative to the gyre areas
+(and the number of grid points).
+
+%% =================================================================================================
+\section{Vertical grid}
+\label{sec:DOMCFG_vert}
+
+%% =================================================================================================
+\subsection{Vertical reference coordinate}
+\label{sec:DOMCFG_zref}
+
+\begin{figure}[!tb]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DOMCFG_zgr}
+  \caption[DOMAINcfg: default vertical mesh for ORCA2]{
+    Default vertical mesh for ORCA2: 30 ocean levels (L30).
+    Vertical level functions for (a) T-point depth and (b) the associated scale factor for
+    the $z$-coordinate case.}
+  \label{fig:DOMCFG_zgr}
+\end{figure}
+
+The reference coordinate transformation $z_0(k)$ defines the arrays $gdept_0$ and
+$gdepw_0$ for $t$- and $w$-points, respectively. See \autoref{sec:DOMCFG_sco} for the
+S-coordinate options.  As indicated on \autoref{fig:DOM_index_vert} \jp{jpk} is the number of
+$w$-levels.  $gdepw_0(1)$ is the ocean surface.  There are at most \jp{jpk}-1 $t$-points
+inside the ocean, the additional $t$-point at $jk = jpk$ is below the sea floor and is not
+used.  The vertical location of $w$- and $t$-levels is defined from the analytic
+expression of the depth $z_0(k)$ whose analytical derivative with respect to $k$ provides
+the vertical scale factors.  The user must provide the analytical expression of both $z_0$
+and its first derivative with respect to $k$.  This is done in routine \mdl{domzgr}
+through statement functions, using parameters provided in the \nam{dom}{dom} namelist
+(\texttt{DOMAINcfg} variant).
+
+It is possible to define a simple regular vertical grid by giving zero stretching
+(\np[=0]{ppacr}{ppacr}).  In that case, the parameters \jp{jpk} (number of $w$-levels)
+and \np{pphmax}{pphmax} (total ocean depth in meters) fully define the grid.
+
+For climate-related studies it is often desirable to concentrate the vertical resolution
+near the ocean surface.  The following function is proposed as a standard for a
+$z$-coordinate (with either full or partial steps):
+\begin{gather}
+  \label{eq:DOMCFG_zgr_ana_1}
+    z_0  (k) = h_{sur} - h_0 \; k - \; h_1 \; \log  \big[ \cosh ((k - h_{th}) / h_{cr}) \big] \\
+    e_3^0(k) = \lt|    - h_0      -    h_1 \; \tanh \big[        (k - h_{th}) / h_{cr}  \big] \rt|
+\end{gather}
+
+where $k = 1$ to \jp{jpk} for $w$-levels and $k = 1$ to $k = 1$ for $t-$levels.  Such an
+expression allows us to define a nearly uniform vertical location of levels at the ocean
+top and bottom with a smooth hyperbolic tangent transition in between (\autoref{fig:DOMCFG_zgr}).
+
+A double hyperbolic tangent version (\np[=.true.]{ldbletanh}{ldbletanh}) is also available
+which permits finer control and is used, typically, to obtain a well resolved upper ocean
+without compromising on resolution at depth using a moderate number of levels.
+
+\begin{gather}
+  \label{eq:DOMCFG_zgr_ana_1b}
+    \begin{split}
+    z_0  (k) = h_{sur} - h_0 \; k &- \; h_1 \; \log  \big[ \cosh ((k - h_{th}) / h_{cr}) \big] \\
+                             \;   &- \; h2_1 \; \log  \big[ \cosh ((k - h2_{th}) / h2_{cr}) \big]
+    \end{split}
+\end{gather}
+\begin{gather}
+    \begin{split}
+    e_3^0(k) = \big|    - h_0    &-   h_1 \; \tanh \big[       (k - h_{th})  / h_{cr}   \big]  \\
+                                 &-  h2_1 \; \tanh \big[       (k - h2_{th}) / h2_{cr}  \big] \big|
+    \end{split}
+\end{gather}
+
+If the ice shelf cavities are opened (\np[=.true.]{ln_isfcav}{ln\_isfcav}), the definition
+of $z_0$ is the same.  However, definition of $e_3^0$ at $t$- and $w$-points is
+respectively changed to:
+\begin{equation}
+  \label{eq:DOMCFG_zgr_ana_2}
+  \begin{split}
+    e_3^T(k) &= z_W (k + 1) - z_W (k    ) \\
+    e_3^W(k) &= z_T (k    ) - z_T (k - 1)
+  \end{split}
+\end{equation}
+
+This formulation decreases the self-generated circulation into the ice shelf cavity
+(which can, in extreme case, leads to numerical instability). This is now the recommended formulation for all configurations using v4.0 onwards. The analytical derivation of thicknesses is maintained for backwards compatibility.
+
+The most used vertical grid for ORCA2 has $10~m$ ($500~m$) resolution in the surface
+(bottom) layers and a depth which varies from 0 at the sea surface to a minimum of
+$-5000~m$.  This leads to the following conditions:
+
+\begin{equation}
+  \label{eq:DOMCFG_zgr_coef}
+  \begin{array}{ll}
+    e_3 (1   + 1/2) =  10. & z(1  ) =     0. \\
+    e_3 (jpk - 1/2) = 500. & z(jpk) = -5000.
+  \end{array}
+\end{equation}
+
+With the choice of the stretching $h_{cr} = 3$ and the number of levels \jp{jpk}~$= 31$,
+the four coefficients $h_{sur}$, $h_0$, $h_1$, and $h_{th}$ in
+\autoref{eq:DOMCFG_zgr_ana_2} have been determined such that \autoref{eq:DOMCFG_zgr_coef}
+is satisfied, through an optimisation procedure using a bisection method.
+For the first standard ORCA2 vertical grid this led to the following values:
+$h_{sur} = 4762.96$, $h_0 = 255.58, h_1 = 245.5813$, and $h_{th} = 21.43336$.
+The resulting depths and scale factors as a function of the model levels are shown in
+\autoref{fig:DOMCFG_zgr} and given in \autoref{tab:DOMCFG_orca_zgr}.
+Those values correspond to the parameters \np{ppsur}{ppsur}, \np{ppa0}{ppa0}, \np{ppa1}{ppa1}, \np{ppkth}{ppkth} in \nam{cfg}{cfg} namelist.
+
+Rather than entering parameters $h_{sur}$, $h_0$, and $h_1$ directly, it is possible to
+recalculate them.  In that case the user sets \np{ppsur}{ppsur}~$=$~\np{ppa0}{ppa0}~$=$~\np{ppa1}{ppa1}~$=
+999999$., in \nam{cfg}{cfg} namelist, and specifies instead the four following parameters:
+\begin{itemize}
+\item \np{ppacr}{ppacr}~$= h_{cr}$: stretching factor (nondimensional).
+  The larger \np{ppacr}{ppacr}, the smaller the stretching.
+  Values from $3$ to $10$ are usual.
+\item \np{ppkth}{ppkth}~$= h_{th}$: is approximately the model level at which maximum stretching occurs
+  (nondimensional, usually of order 1/2 or 2/3 of \jp{jpk})
+\item \np{ppdzmin}{ppdzmin}: minimum thickness for the top layer (in meters).
+\item \np{pphmax}{pphmax}: total depth of the ocean (meters).
+\end{itemize}
+
+As an example, for the $45$ layers used in the DRAKKAR configuration those parameters are:
+\jp{jpk}~$= 46$, \np{ppacr}{ppacr}~$= 9$, \np{ppkth}{ppkth}~$= 23.563$, \np{ppdzmin}{ppdzmin}~$= 6~m$,
+\np{pphmax}{pphmax}~$= 5750~m$.
+
+\begin{table}
+  \centering
+  \begin{tabular}{c||r|r|r|r}
+    \hline
+    \textbf{LEVEL} & \textbf{gdept\_1d} & \textbf{gdepw\_1d} & \textbf{e3t\_1d } & \textbf{e3w\_1d} \\
+    \hline
+    1              & \textbf{     5.00} &               0.00 & \textbf{   10.00} &            10.00 \\
+    \hline
+    2              & \textbf{    15.00} &              10.00 & \textbf{   10.00} &            10.00 \\
+    \hline
+    3              & \textbf{    25.00} &              20.00 & \textbf{   10.00} &            10.00 \\
+    \hline
+    4              & \textbf{    35.01} &              30.00 & \textbf{   10.01} &            10.00 \\
+    \hline
+    5              & \textbf{    45.01} &              40.01 & \textbf{   10.01} &            10.01 \\
+    \hline
+    6              & \textbf{    55.03} &              50.02 & \textbf{   10.02} &            10.02 \\
+    \hline
+    7              & \textbf{    65.06} &              60.04 & \textbf{   10.04} &            10.03 \\
+    \hline
+    8              & \textbf{    75.13} &              70.09 & \textbf{   10.09} &            10.06 \\
+    \hline
+    9              & \textbf{    85.25} &              80.18 & \textbf{   10.17} &            10.12 \\
+    \hline
+    10             & \textbf{    95.49} &              90.35 & \textbf{   10.33} &            10.24 \\
+    \hline
+    11             & \textbf{   105.97} &             100.69 & \textbf{   10.65} &            10.47 \\
+    \hline
+    12             & \textbf{   116.90} &             111.36 & \textbf{   11.27} &            10.91 \\
+    \hline
+    13             & \textbf{   128.70} &             122.65 & \textbf{   12.47} &            11.77 \\
+    \hline
+    14             & \textbf{   142.20} &             135.16 & \textbf{   14.78} &            13.43 \\
+    \hline
+    15             & \textbf{   158.96} &             150.03 & \textbf{   19.23} &            16.65 \\
+    \hline
+    16             & \textbf{   181.96} &             169.42 & \textbf{   27.66} &            22.78 \\
+    \hline
+    17             & \textbf{   216.65} &             197.37 & \textbf{   43.26} &            34.30 \\
+    \hline
+    18             & \textbf{   272.48} &             241.13 & \textbf{   70.88} &            55.21 \\
+    \hline
+    19             & \textbf{   364.30} &             312.74 & \textbf{  116.11} &            90.99 \\
+    \hline
+    20             & \textbf{   511.53} &             429.72 & \textbf{  181.55} &           146.43 \\
+    \hline
+    21             & \textbf{   732.20} &             611.89 & \textbf{  261.03} &           220.35 \\
+    \hline
+    22             & \textbf{  1033.22} &             872.87 & \textbf{  339.39} &           301.42 \\
+    \hline
+    23             & \textbf{  1405.70} &            1211.59 & \textbf{  402.26} &           373.31 \\
+    \hline
+    24             & \textbf{  1830.89} &            1612.98 & \textbf{  444.87} &           426.00 \\
+    \hline
+    25             & \textbf{  2289.77} &            2057.13 & \textbf{  470.55} &           459.47 \\
+    \hline
+    26             & \textbf{  2768.24} &            2527.22 & \textbf{  484.95} &           478.83 \\
+    \hline
+    27             & \textbf{  3257.48} &            3011.90 & \textbf{  492.70} &           489.44 \\
+    \hline
+    28             & \textbf{  3752.44} &            3504.46 & \textbf{  496.78} &           495.07 \\
+    \hline
+    29             & \textbf{  4250.40} &            4001.16 & \textbf{  498.90} &           498.02 \\
+    \hline
+    30             & \textbf{  4749.91} &            4500.02 & \textbf{  500.00} &           499.54 \\
+    \hline
+    31             & \textbf{  5250.23} &            5000.00 & \textbf{  500.56} &           500.33 \\
+    \hline
+  \end{tabular}
+  \caption[Default vertical mesh in $z$-coordinate for 30 layers ORCA2 configuration]{
+    Default vertical mesh in $z$-coordinate for 30 layers ORCA2 configuration as
+    computed from \autoref{eq:DOMCFG_zgr_ana_2} using
+    the coefficients given in \autoref{eq:DOMCFG_zgr_coef}}
+  \label{tab:DOMCFG_orca_zgr}
+\end{table}
+%%%YY
+%% % -------------------------------------------------------------------------------------------------------------
+%% %        Meter Bathymetry
+%% % -------------------------------------------------------------------------------------------------------------
+%% =================================================================================================
+\subsection{Model bathymetry}
+\label{subsec:DOMCFG_bathy}
+
+Three options are possible for defining the bathymetry, according to the namelist variable
+\np{nn_bathy}{nn\_bathy} (found in \nam{dom}{dom} namelist (\texttt{DOMAINCFG} variant) ):
+\begin{description}
+\item [{\np[=0]{nn_bathy}{nn\_bathy}}]: a flat-bottom domain is defined.
+  The total depth $z_w (jpk)$ is given by the coordinate transformation.
+  The domain can either be a closed basin or a periodic channel depending on the parameter \np{jperio}{jperio}.
+\item [{\np[=-1]{nn_bathy}{nn\_bathy}}]: a domain with a bump of topography one third of the domain width at the central latitude.
+  This is meant for the "EEL-R5" configuration, a periodic or open boundary channel with a seamount.
+\item [{\np[=1]{nn_bathy}{nn\_bathy}}]: read a bathymetry and ice shelf draft (if needed).
+  The \ifile{bathy\_meter} file (Netcdf format) provides the ocean depth (positive, in meters) at
+  each grid point of the model grid.
+  The bathymetry is usually built by interpolating a standard bathymetry product (\eg\ ETOPO2) onto
+  the horizontal ocean mesh.
+  Defining the bathymetry also defines the coastline: where the bathymetry is zero,
+  no wet levels are defined (all levels are masked).
+
+  The \ifile{isfdraft\_meter} file (Netcdf format) provides the ice shelf draft (positive, in meters) at
+  each grid point of the model grid.
+  This file is only needed if \np[=.true.]{ln_isfcav}{ln\_isfcav}.
+  Defining the ice shelf draft will also define the ice shelf edge and the grounding line position.
+\end{description}
+
+%% =================================================================================================
+\subsection{Choice of vertical grid}
+\label{sec:DOMCFG_vgrd}
+
+After reading the bathymetry, the algorithm for vertical grid definition differs between the different options:
+\begin{description}
+\item [\forcode{ln_zco = .true.}] set a reference coordinate transformation $z_0(k)$, and set $z(i,j,k,t) = z_0(k)$ where $z_0(k)$ is the closest match to the depth at $(i,j)$.
+\item [\forcode{ln_zps = .true.}] set a reference coordinate transformation $z_0(k)$, and calculate the thickness of the deepest level at
+  each $(i,j)$ point using the bathymetry, to obtain the final three-dimensional depth and scale factor arrays.
+\item [\forcode{ln_sco = .true.}] smooth the bathymetry to fulfill the hydrostatic consistency criteria and
+  set the three-dimensional transformation.
+\item [\forcode{s-z and s-zps}] smooth the bathymetry to fulfill the hydrostatic consistency criteria and
+  set the three-dimensional transformation $z(i,j,k)$,
+  and possibly introduce masking of extra land points to better fit the original bathymetry file.
+\end{description}
+
+%% =================================================================================================
+\subsubsection[$Z$-coordinate with uniform thickness levels (\forcode{ln_zco})]{$Z$-coordinate with uniform thickness levels (\protect\np{ln_zco}{ln\_zco})}
+\label{subsec:DOMCFG_zco}
+
+With this option the model topography can be fully described by the reference vertical
+coordinate and a 2D integer field giving the number of wet levels at each location
+(\forcode{bathy_level}). The resulting match to the real topography is likely to be poor
+though (especially with thick, deep levels) and slopes poorly represented. This option is
+rarely used in modern simulations but it can be useful for testing purposes.
+
+%% =================================================================================================
+\subsubsection[$Z$-coordinate with partial step (\forcode{ln_zps})]{$Z$-coordinate with partial step (\protect\np{ln_zps}{ln\_zps})}
+\label{subsec:DOMCFG_zps}
+
+In $z$-coordinate partial step, the depths of the model levels are defined by the
+reference analytical function $z_0(k)$ as described in \autoref{sec:DOMCFG_zref},
+\textit{except} in the bottom layer.  The thickness of the bottom layer is allowed to vary
+as a function of geographical location $(\lambda,\varphi)$ to allow a better
+representation of the bathymetry, especially in the case of small slopes (where the
+bathymetry varies by less than one level thickness from one grid point to the next).  The
+reference layer thicknesses $e_{3t}^0$ have been defined in the absence of bathymetry.
+With partial steps, layers from 1 to \jp{jpk}-2 can have a thickness smaller than
+$e_{3t}(jk)$.
+
+The model deepest layer (\jp{jpk}-1) is allowed to have either a smaller or larger
+thickness than $e_{3t}(jpk)$: the maximum thickness allowed is $2*e_{3t}(jpk - 1)$.
+
+This has to be kept in mind when specifying values in \nam{dom}{dom} namelist
+(\texttt{DOMAINCFG} variant), such as the maximum depth \np{pphmax}{pphmax} in partial steps.
+
+For example, with \np{pphmax}{pphmax}~$= 5750~m$ for the DRAKKAR 45 layer grid, the maximum ocean
+depth allowed is actually $6000~m$ (the default thickness $e_{3t}(jpk - 1)$ being
+$250~m$).  Two variables in the namdom namelist are used to define the partial step
+vertical grid.  The mimimum water thickness (in meters) allowed for a cell partially
+filled with bathymetry at level jk is the minimum of \np{rn_e3zps_min}{rn\_e3zps\_min} (thickness in
+meters, usually $20~m$) or $e_{3t}(jk)*$\np{rn_e3zps_rat}{rn\_e3zps\_rat} (a fraction, usually 10\%, of
+the default thickness $e_{3t}(jk)$).
+
+%% =================================================================================================
+\subsubsection[$S$-coordinate (\forcode{ln_sco})]{$S$-coordinate (\protect\np{ln_sco}{ln\_sco})}
+\label{sec:DOMCFG_sco}
+\begin{listing}
+  \nlst{namzgr_sco_domcfg}
+  \caption{\forcode{&namzgr_sco_domcfg}}
+  \label{lst:namzgr_sco_domcfg}
+\end{listing}
+Options are defined in \nam{zgr_sco}{zgr\_sco} (\texttt{DOMAINcfg} only).
+In $s$-coordinate (\np[=.true.]{ln_sco}{ln\_sco}), the depth and thickness of the model levels are defined from
+the product of a depth field and either a stretching function or its derivative, respectively:
+
+\begin{align*}
+  % \label{eq:DOMCFG_sco_ana}
+  z(k)   &= h(i,j) \; z_0 (k) \\
+  e_3(k) &= h(i,j) \; z_0'(k)
+\end{align*}
+
+where $h$ is the depth of the last $w$-level ($z_0(k)$) defined at the $t$-point location in the horizontal and
+$z_0(k)$ is a function which varies from $0$ at the sea surface to $1$ at the ocean bottom.
+The depth field $h$ is not necessary the ocean depth,
+since a mixed step-like and bottom-following representation of the topography can be used
+(\autoref{fig:DOM_z_zps_s_sps}) or an envelop bathymetry can be defined (\autoref{fig:DOM_z_zps_s_sps}).
+The namelist parameter \np{rn_rmax}{rn\_rmax} determines the slope at which
+the terrain-following coordinate intersects the sea bed and becomes a pseudo z-coordinate.
+The coordinate can also be hybridised by specifying \np{rn_sbot_min}{rn\_sbot\_min} and \np{rn_sbot_max}{rn\_sbot\_max} as
+the minimum and maximum depths at which the terrain-following vertical coordinate is calculated.
+
+Options for stretching the coordinate are provided as examples,
+but care must be taken to ensure that the vertical stretch used is appropriate for the application.
+
+The original default \NEMO\ s-coordinate stretching is available if neither of the other options are specified as true
+(\np[=.false.]{ln_s_SH94}{ln\_s\_SH94} and \np[=.false.]{ln_s_SF12}{ln\_s\_SF12}).
+This uses a depth independent $\tanh$ function for the stretching \citep{madec.delecluse.ea_JPO96}:
+
+\[
+  z = s_{min} + C (s) (H - s_{min})
+  % \label{eq:DOMCFG_SH94_1}
+\]
+
+where $s_{min}$ is the depth at which the $s$-coordinate stretching starts and
+allows a $z$-coordinate to placed on top of the stretched coordinate,
+and $z$ is the depth (negative down from the asea surface).
+\begin{gather*}
+  s = - \frac{k}{n - 1} \quad \text{and} \quad 0 \leq k \leq n - 1
+  % \label{eq:DOMCFG_s}
+ \\
+ \label{eq:DOMCFG_sco_function}
+  C(s) = \frac{[\tanh(\theta \, (s + b)) - \tanh(\theta \, b)]}{2 \; \sinh(\theta)}
+\end{gather*}
+
+A stretching function,
+modified from the commonly used \citet{song.haidvogel_JCP94} stretching (\np[=.true.]{ln_s_SH94}{ln\_s\_SH94}),
+is also available and is more commonly used for shelf seas modelling:
+
+\[
+  C(s) =   (1 - b) \frac{\sinh(\theta s)}{\sinh(\theta)}
+         + b       \frac{\tanh \lt[ \theta \lt(s + \frac{1}{2} \rt) \rt] -   \tanh \lt( \frac{\theta}{2} \rt)}
+                        {                                                  2 \tanh \lt( \frac{\theta}{2} \rt)}
+ \label{eq:DOMCFG_SH94_2}
+\]
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DOMCFG_sco_function}
+  \caption[DOMAINcfg: examples of the stretching function applied to a seamount]{
+    Examples of the stretching function applied to a seamount;
+    from left to right: surface, surface and bottom, and bottom intensified resolutions}
+  \label{fig:DOMCFG_sco_function}
+\end{figure}
+
+where $H_c$ is the critical depth (\np{rn_hc}{rn\_hc}) at which the coordinate transitions from pure $\sigma$ to
+the stretched coordinate, and $\theta$ (\np{rn_theta}{rn\_theta}) and $b$ (\np{rn_bb}{rn\_bb}) are the surface and
+bottom control parameters such that $0 \leqslant \theta \leqslant 20$, and $0 \leqslant b \leqslant 1$.
+$b$ has been designed to allow surface and/or bottom increase of the vertical resolution
+(\autoref{fig:DOMCFG_sco_function}).
+
+Another example has been provided at version 3.5 (\np{ln_s_SF12}{ln\_s\_SF12}) that allows a fixed surface resolution in
+an analytical terrain-following stretching \citet{siddorn.furner_OM13}.
+In this case the a stretching function $\gamma$ is defined such that:
+
+\begin{equation}
+  z = - \gamma h \quad \text{with} \quad 0 \leq \gamma \leq 1
+  % \label{eq:DOMCFG_z}
+\end{equation}
+
+The function is defined with respect to $\sigma$, the unstretched terrain-following coordinate:
+
+\begin{gather*}
+  % \label{eq:DOMCFG_gamma_deriv}
+  \gamma =   A \lt( \sigma   - \frac{1}{2} (\sigma^2     + f (\sigma)) \rt)
+           + B \lt( \sigma^3 - f           (\sigma) \rt) + f (\sigma)       \\
+  \intertext{Where:}
+ \label{eq:DOMCFG_gamma}
+  f(\sigma) = (\alpha + 2) \sigma^{\alpha + 1} - (\alpha + 1) \sigma^{\alpha + 2}
+  \quad \text{and} \quad \sigma = \frac{k}{n - 1}
+\end{gather*}
+
+This gives an analytical stretching of $\sigma$ that is solvable in $A$ and $B$ as a function of
+the user prescribed stretching parameter $\alpha$ (\np{rn_alpha}{rn\_alpha}) that stretches towards
+the surface ($\alpha > 1.0$) or the bottom ($\alpha < 1.0$) and
+user prescribed surface (\np{rn_zs}{rn\_zs}) and bottom depths.
+The bottom cell depth in this example is given as a function of water depth:
+
+\[
+  % \label{eq:DOMCFG_zb}
+  Z_b = h a + b
+\]
+
+where the namelist parameters \np{rn_zb_a}{rn\_zb\_a} and \np{rn_zb_b}{rn\_zb\_b} are $a$ and $b$ respectively.
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DOMCFG_compare_coordinates_surface}
+  \caption[DOMAINcfg: comparison of $s$- and $z$-coordinate]{
+    A comparison of the \citet{song.haidvogel_JCP94} $S$-coordinate (solid lines),
+    a 50 level $Z$-coordinate (contoured surfaces) and
+    the \citet{siddorn.furner_OM13} $S$-coordinate (dashed lines) in the surface $100~m$ for
+    a idealised bathymetry that goes from $50~m$ to $5500~m$ depth.
+    For clarity every third coordinate surface is shown.}
+  \label{fig:DOMCFG_fig_compare_coordinates_surface}
+\end{figure}
+ % >>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+This gives a smooth analytical stretching in computational space that is constrained to
+given specified surface and bottom grid cell thicknesses in real space.
+This is not to be confused with the hybrid schemes that
+superimpose geopotential coordinates on terrain following coordinates thus
+creating a non-analytical vertical coordinate that
+therefore may suffer from large gradients in the vertical resolutions.
+This stretching is less straightforward to implement than the \citet{song.haidvogel_JCP94} stretching,
+but has the advantage of resolving diurnal processes in deep water and has generally flatter slopes.
+
+As with the \citet{song.haidvogel_JCP94} stretching the stretch is only applied at depths greater than
+the critical depth $h_c$.
+In this example two options are available in depths shallower than $h_c$,
+with pure sigma being applied if the \np{ln_sigcrit}{ln\_sigcrit} is true and pure z-coordinates if it is false
+(the z-coordinate being equal to the depths of the stretched coordinate at $h_c$).
+
+Minimising the horizontal slope of the vertical coordinate is important in terrain-following systems as
+large slopes lead to hydrostatic consistency.
+A hydrostatic consistency parameter diagnostic following \citet{haney_JPO91} has been implemented,
+and is output as part of the model mesh file at the start of the run.
+
+%% =================================================================================================
+\subsubsection[\zstar- or \sstar-coordinate (\forcode{ln_linssh})]{\zstar- or \sstar-coordinate (\protect\np{ln_linssh}{ln\_linssh})}
+\label{subsec:DOMCFG_zgr_star}
+
+This option is described in the Report by Levier \textit{et al.} (2007), available on the \NEMO\ web site.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_algos.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_algos.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_algos.tex	(revision 14097)
@@ -0,0 +1,825 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Note on some algorithms}
+\label{apdx:ALGOS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+This appendix some on going consideration on algorithms used or planned to be used in \NEMO.
+
+%% =================================================================================================
+\section{Upstream Biased Scheme (UBS) (\protect\np[=.true.]{ln_traadv_ubs}{ln\_traadv\_ubs})}
+\label{sec:ALGOS_tra_adv_ubs}
+
+The UBS advection scheme is an upstream biased third order scheme based on
+an upstream-biased parabolic interpolation.
+It is also known as Cell Averaged QUICK scheme (Quadratic Upstream Interpolation for Convective Kinematics).
+For example, in the $i$-direction:
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \tau_u^{ubs} = \left\{
+	 \begin{aligned}
+      & \tau_u^{cen4} + \frac{1}{12} \,\tau"_i	   & \quad \text{if }\ u_{i+1/2} \geqslant 0 \\
+      & \tau_u^{cen4} - \frac{1}{12} \,\tau"_{i+1} & \quad \text{if }\ u_{i+1/2}       <       0
+    \end{aligned}
+  \right.
+\end{equation}
+or equivalently, the advective flux is
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  U_{i+1/2} \ \tau_u^{ubs}
+  =U_{i+1/2} \ \overline{ T_i - \frac{1}{6}\,\tau"_i }^{\,i+1/2}
+  - \frac{1}{2}\, |U|_{i+1/2} \;\frac{1}{6} \;\delta_{i+1/2}[\tau"_i]
+\end{equation}
+where $U_{i+1/2} = e_{1u}\,e_{3u}\,u_{i+1/2}$ and
+$\tau "_i =\delta_i \left[ {\delta_{i+1/2} \left[ \tau \right]} \right]$.
+By choosing this expression for $\tau "$ we consider a fourth order approximation of $\partial_i^2$ with
+a constant i-grid spacing ($\Delta i=1$).
+
+Alternative choice: introduce the scale factors:
+$\tau "_i =\frac{e_{1T}}{e_{2T}\,e_{3T}}\delta_i \left[ \frac{e_{2u} e_{3u} }{e_{1u} }\delta_{i+1/2}[\tau] \right]$.
+
+This results in a dissipatively dominant (\ie\ hyper-diffusive) truncation error
+\citep{shchepetkin.mcwilliams_OM05}.
+The overall performance of the advection scheme is similar to that reported in \cite{farrow.stevens_JPO95}.
+It is a relatively good compromise between accuracy and smoothness.
+It is not a \emph{positive} scheme meaning false extrema are permitted but
+the amplitude of such are significantly reduced over the centred second order method.
+Nevertheless it is not recommended to apply it to a passive tracer that requires positivity.
+
+The intrinsic diffusion of UBS makes its use risky in the vertical direction where
+the control of artificial diapycnal fluxes is of paramount importance.
+It has therefore been preferred to evaluate the vertical flux using the TVD scheme when
+\np[=.true.]{ln_traadv_ubs}{ln\_traadv\_ubs}.
+
+For stability reasons, in \autoref{eq:TRA_adv_ubs}, the first term which corresponds to
+a second order centred scheme is evaluated using the \textit{now} velocity (centred in time) while
+the second term which is the diffusive part of the scheme, is evaluated using the \textit{before} velocity
+(forward in time).
+This is discussed by \citet{webb.de-cuevas.ea_JAOT98} in the context of the Quick advection scheme.
+UBS and QUICK schemes only differ by one coefficient.
+Substituting 1/6 with 1/8 in (\autoref{eq:TRA_adv_ubs}) leads to the QUICK advection scheme \citep{webb.de-cuevas.ea_JAOT98}.
+This option is not available through a namelist parameter, since the 1/6 coefficient is hard coded.
+Nevertheless it is quite easy to make the substitution in \mdl{traadv\_ubs} module and obtain a QUICK scheme.
+
+NB 1: When a high vertical resolution $O(1m)$ is used, the model stability can be controlled by vertical advection
+(not vertical diffusion which is usually solved using an implicit scheme).
+Computer time can be saved by using a time-splitting technique on vertical advection.
+This possibility have been implemented and validated in ORCA05-L301.
+It is not currently offered in the current reference version.
+
+NB 2: In a forthcoming release four options will be proposed for the vertical component used in the UBS scheme.
+$\tau_w^{ubs}$ will be evaluated using either \textit{(a)} a centered $2^{nd}$ order scheme,
+or \textit{(b)} a TVD scheme, or \textit{(c)} an interpolation based on conservative parabolic splines following
+\citet{shchepetkin.mcwilliams_OM05} implementation of UBS in ROMS, or \textit{(d)} an UBS.
+The $3^{rd}$ case has dispersion properties similar to an eight-order accurate conventional scheme.
+
+NB 3: It is straight forward to rewrite \autoref{eq:TRA_adv_ubs} as follows:
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \tau_u^{ubs} = \left\{
+	 \begin{aligned}
+      & \tau_u^{cen4} + \frac{1}{12} \tau"_i		& \quad \text{if }\ u_{i+1/2} \geqslant 0 \\
+      & \tau_u^{cen4} - \frac{1}{12} \tau"_{i+1}	& \quad \text{if }\ u_{i+1/2}       <       0
+    \end{aligned}
+  \right.
+\end{equation}
+or equivalently
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \begin{split}
+    e_{2u} e_{3u}\,u_{i+1/2} \ \tau_u^{ubs}
+    &= e_{2u} e_{3u}\,u_{i+1/2} \ \overline{ T - \frac{1}{6}\,\tau"_i }^{\,i+1/2} \\
+    & - \frac{1}{2} e_{2u} e_{3u}\,|u|_{i+1/2} \;\frac{1}{6} \;\delta_{i+1/2}[\tau"_i]
+  \end{split}
+\end{equation}
+\autoref{eq:TRA_adv_ubs2} has several advantages.
+First it clearly evidences that the UBS scheme is based on the fourth order scheme to which
+is added an upstream biased diffusive term.
+Second, this emphasises that the $4^{th}$ order part have to be evaluated at \emph{now} time step,
+not only the $2^{th}$ order part as stated above using \autoref{eq:TRA_adv_ubs}.
+Third, the diffusive term is in fact a biharmonic operator with a eddy coefficient which
+is simply proportional to the velocity.
+
+laplacian diffusion:
+\begin{equation}
+  \label{eq:ALGOS_tra_ldf_lap}
+  \begin{split}
+    D_T^{lT} =\frac{1}{e_{1T} \; e_{2T}\;  e_{3T} } &\left[ {\quad \delta_i
+        \left[ {A_u^{lT} \frac{e_{2u} e_{3u} }{e_{1u} }\;\delta_{i+1/2}
+            \left[ T \right]} \right]} \right. \\
+    &\ \left. {+\; \delta_j \left[
+          {A_v^{lT} \left( {\frac{e_{1v} e_{3v} }{e_{2v} }\;\delta_{j+1/2} \left[ T
+                \right]} \right)} \right]\quad } \right]
+  \end{split}
+\end{equation}
+
+bilaplacian:
+\begin{equation}
+  \label{eq:ALGOS_tra_ldf_lap}
+  \begin{split}
+    D_T^{lT} =&-\frac{1}{e_{1T} \; e_{2T}\;  e_{3T}} \\
+    & \delta_i \left[  \sqrt{A_u^{lT}}\ \frac{e_{2u}\,e_{3u}}{e_{1u}}\;\delta_{i+1/2}
+      \left[ \frac{1}{e_{1T}\,e_{2T}\, e_{3T}}
+        \delta_i \left[ \sqrt{A_u^{lT}}\ \frac{e_{2u}\,e_{3u}}{e_{1u}}\;\delta_{i+1/2}
+          [T] \right] \right] \right]
+  \end{split}
+\end{equation}
+with ${A_u^{lT}}^2 = \frac{1}{12} {e_{1u}}^3\ |u|$,
+\ie\ $A_u^{lT} = \frac{1}{\sqrt{12}} \,e_{1u}\ \sqrt{ e_{1u}\,|u|\,}$
+it comes:
+\begin{equation}
+  \label{eq:ALGOS_tra_ldf_lap}
+  \begin{split}
+    D_T^{lT} =&-\frac{1}{12}\,\frac{1}{e_{1T} \; e_{2T}\;  e_{3T}} \\
+    & \delta_i \left[ e_{2u}\,e_{3u}\,\sqrt{ e_{1u}\,|u|\,}\;\delta_{i+1/2}
+      \left[ \frac{1}{e_{1T}\,e_{2T}\, e_{3T}}
+        \delta_i \left[ e_{2u}\,e_{3u}\,\sqrt{ e_{1u}\,|u|\,}\;\delta_{i+1/2}
+          [T] \right] \right] \right]
+  \end{split}
+\end{equation}
+if the velocity is uniform (\ie\ $|u|=cst$) then the diffusive flux is
+\begin{equation}
+  \label{eq:ALGOS_tra_ldf_lap}
+  \begin{split}
+    F_u^{lT} = - \frac{1}{12}
+    e_{2u}\,e_{3u}\,|u| \;\sqrt{ e_{1u}}\,\delta_{i+1/2}
+    \left[ \frac{1}{e_{1T}\,e_{2T}\, e_{3T}}
+      \delta_i \left[ e_{2u}\,e_{3u}\,\sqrt{ e_{1u}}\:\delta_{i+1/2}
+        [T] \right] \right]
+  \end{split}
+\end{equation}
+beurk....  reverte the logic: starting from the diffusive part of the advective flux it comes:
+
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \begin{split}
+    F_u^{lT} &= - \frac{1}{2} e_{2u} e_{3u}\,|u|_{i+1/2} \;\frac{1}{6} \;\delta_{i+1/2}[\tau"_i]
+  \end{split}
+\end{equation}
+if the velocity is uniform (\ie\ $|u|=cst$) and
+choosing $\tau "_i =\frac{e_{1T}}{e_{2T}\,e_{3T}}\delta_i \left[ \frac{e_{2u} e_{3u} }{e_{1u} } \delta_{i+1/2}[\tau] \right]$
+
+sol 1 coefficient at T-point ( add $e_{1u}$ and $e_{1T}$ on both side of first $\delta$):
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \begin{split}
+    F_u^{lT} &= - \frac{1}{12} \frac{e_{2u} e_{3u}}{e_{1u}}\;\delta_{i+1/2}\left[ \frac{e_{1T}^3\,|u|}{e_{1T}e_{2T}\,e_{3T}}\,\delta_i \left[ \frac{e_{2u} e_{3u} }{e_{1u} } \delta_{i+1/2}[\tau] \right] \right]
+  \end{split}
+\end{equation}
+which leads to ${A_T^{lT}}^2 = \frac{1}{12} {e_{1T}}^3\ \overline{|u|}^{\,i+1/2}$
+
+sol 2 coefficient at u-point: split $|u|$ into $\sqrt{|u|}$ and $e_{1T}$ into $\sqrt{e_{1u}}$
+\begin{equation}
+  \label{eq:ALGOS_tra_adv_ubs2}
+  \begin{split}
+    F_u^{lT} &= - \frac{1}{12} {e_{1u}}^1 \sqrt{e_{1u}|u|} \frac{e_{2u} e_{3u}}{e_{1u}}\;\delta_{i+1/2}\left[ \frac{1}{e_{2T}\,e_{3T}}\,\delta_i \left[ \sqrt{e_{1u}|u|} \frac{e_{2u} e_{3u} }{e_{1u} } \delta_{i+1/2}[\tau] \right] \right] \\
+    &= - \frac{1}{12} e_{1u} \sqrt{e_{1u}|u|\,} \frac{e_{2u} e_{3u}}{e_{1u}}\;\delta_{i+1/2}\left[ \frac{1}{e_{1T}\,e_{2T}\,e_{3T}}\,\delta_i \left[ e_{1u} \sqrt{e_{1u}|u|\,} \frac{e_{2u} e_{3u} }{e_{1u}} \delta_{i+1/2}[\tau] \right] \right]
+  \end{split}
+\end{equation}
+which leads to ${A_u^{lT}} = \frac{1}{12} {e_{1u}}^3\ |u|$
+
+%% =================================================================================================
+\section{Leapfrog energetic}
+\label{sec:ALGOS_LF}
+
+We adopt the following semi-discrete notation for time derivative.
+Given the values of a variable $q$ at successive time step,
+the time derivation and averaging operators at the mid time step are:
+\[
+  % \label{eq:ALGOS_dt_mt}
+  \begin{split}
+    \delta_{t+\rdt/2} [q]     &=  \  \ \,   q^{t+\rdt}  - q^{t}		\\
+    \overline q^{\,t+\rdt/2} &= \left\{ q^{t+\rdt} + q^{t} \right\} \; / \; 2
+  \end{split}
+\]
+As for space operator,
+the adjoint of the derivation and averaging time operators are $\delta_t^*=\delta_{t+\rdt/2}$ and
+$\overline{\cdot}^{\,t\,*}= \overline{\cdot}^{\,t+\Delta/2}$, respectively.
+
+The Leap-frog time stepping given by \autoref{eq:DOM_nxt} can be defined as:
+\[
+  % \label{eq:ALGOS_LF}
+  \frac{\partial q}{\partial t}
+  \equiv \frac{1}{\rdt} \overline{ \delta_{t+\rdt/2}[q]}^{\,t}
+  =         \frac{q^{t+\rdt}-q^{t-\rdt}}{2\rdt}
+\]
+Note that \autoref{chap:LF} shows that the leapfrog time step is $\rdt$,
+not $2\rdt$ as it can be found sometimes in literature.
+The leap-Frog time stepping is a second order centered scheme.
+As such it respects the quadratic invariant in integral forms, \ie\ the following continuous property,
+\[
+  % \label{eq:ALGOS_Energy}
+  \int_{t_0}^{t_1} {q\, \frac{\partial q}{\partial t} \;dt}
+  =\int_{t_0}^{t_1} {\frac{1}{2}\, \frac{\partial q^2}{\partial t} \;dt}
+  =  \frac{1}{2} \left( {q_{t_1}}^2 - {q_{t_0}}^2 \right) ,
+\]
+is satisfied in discrete form.
+Indeed,
+\[
+  \begin{split}
+    \int_{t_0}^{t_1} {q\, \frac{\partial q}{\partial t} \;dt}
+    &\equiv \sum\limits_{0}^{N}
+    {\frac{1}{\rdt} q^t \ \overline{ \delta_{t+\rdt/2}[q]}^{\,t} \ \rdt}
+    \equiv \sum\limits_{0}^{N}  { q^t \ \overline{ \delta_{t+\rdt/2}[q]}^{\,t} } \\
+    &\equiv \sum\limits_{0}^{N}  { \overline{q}^{\,t+\Delta/2}{ \delta_{t+\rdt/2}[q]}}
+    \equiv \sum\limits_{0}^{N}  { \frac{1}{2} \delta_{t+\rdt/2}[q^2] }\\
+    &\equiv \sum\limits_{0}^{N}  { \frac{1}{2} \delta_{t+\rdt/2}[q^2] }
+    \equiv \frac{1}{2} \left( {q_{t_1}}^2 - {q_{t_0}}^2 \right)
+  \end{split}
+\]
+NB here pb of boundary condition when applying the adjoint!
+In space, setting to 0 the quantity in land area is sufficient to get rid of the boundary condition
+(equivalently of the boundary value of the integration by part).
+In time this boundary condition is not physical and \textbf{add something here!!!}
+
+%% =================================================================================================
+\section{Lateral diffusion operator}
+
+%% =================================================================================================
+\subsection{Griffies iso-neutral diffusion operator}
+
+Let try to define a scheme that get its inspiration from the \citet{griffies.gnanadesikan.ea_JPO98} scheme,
+but is formulated within the \NEMO\ framework
+(\ie\ using scale factors rather than grid-size and having a position of $T$-points that
+is not necessary in the middle of vertical velocity points, see \autoref{fig:DOM_zgr_e3}).
+
+In the formulation \autoref{eq:TRA_ldf_iso} introduced in 1995 in OPA, the ancestor of \NEMO,
+the off-diagonal terms of the small angle diffusion tensor contain several double spatial averages of a gradient,
+for example $\overline{\overline{\delta_k \cdot}}^{\,i,k}$.
+It is apparent that the combination of a $k$ average and a $k$ derivative of the tracer allows for
+the presence of grid point oscillation structures that will be invisible to the operator.
+These structures are \textit{computational modes}.
+They will not be damped by the iso-neutral operator, and even possibly amplified by it.
+In other word, the operator applied to a tracer does not warranties the decrease of its global average variance.
+To circumvent this, we have introduced a smoothing of the slopes of the iso-neutral surfaces
+(see \autoref{chap:LDF}).
+Nevertheless, this technique works fine for $T$ and $S$ as they are active tracers
+(\ie\ they enter the computation of density), but it does not work for a passive tracer.
+\citep{griffies.gnanadesikan.ea_JPO98} introduce a different way to discretise the off-diagonal terms that
+nicely solve the problem.
+The idea is to get rid of combinations of an averaged in one direction combined with
+a derivative in the same direction by considering triads.
+For example in the (\textbf{i},\textbf{k}) plane, the four triads are defined at the $(i,k)$ $T$-point as follows:
+\begin{equation}
+  \label{eq:ALGOS_Gf_triads}
+  _i^k \mathbb{T}_{i_p}^{k_p} (T)
+  = \frac{1}{4} \ {b_u}_{\,i+i_p}^{\,k}  \  A_i^k  	\left(
+    \frac{ \delta_{i + i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+    -\ {_i^k \mathbb{R}_{i_p}^{k_p}} \ \frac{ \delta_{k+k_p} [T^i] }{ {e_{3w}}_{\,i}^{\,k+k_p} }
+  \right)
+\end{equation}
+where the indices $i_p$ and $k_p$ define the four triads and take the following value:
+$i_p = -1/2$ or $1/2$ and $k_p = -1/2$ or $1/2$,
+$b_u= e_{1u}\,e_{2u}\,e_{3u}$ is the volume of $u$-cells,
+$A_i^k$ is the lateral eddy diffusivity coefficient defined at $T$-point,
+and $_i^k \mathbb{R}_{i_p}^{k_p}$ is the slope associated with each triad:
+\begin{equation}
+  \label{eq:ALGOS_Gf_slopes}
+  _i^k \mathbb{R}_{i_p}^{k_p}
+  =\frac{ {e_{3w}}_{\,i}^{\,k+k_p}} { {e_{1u}}_{\,i+i_p}^{\,k}} \ \frac
+  {\left(\alpha / \beta \right)_i^k  \ \delta_{i + i_p}[T^k] - \delta_{i + i_p}[S^k] }
+  {\left(\alpha / \beta \right)_i^k  \ \delta_{k+k_p}[T^i ] - \delta_{k+k_p}[S^i ] }
+\end{equation}
+Note that in \autoref{eq:ALGOS_Gf_slopes} we use the ratio $\alpha / \beta$ instead of
+multiplying the temperature derivative by $\alpha$ and the salinity derivative by $\beta$.
+This is more efficient as the ratio $\alpha / \beta$ can to be evaluated directly.
+
+Note that in \autoref{eq:ALGOS_Gf_triads}, we chose to use ${b_u}_{\,i+i_p}^{\,k}$ instead of ${b_{uw}}_{\,i+i_p}^{\,k+k_p}$.
+This choice has been motivated by the decrease of tracer variance and
+the presence of partial cell at the ocean bottom (see \autoref{subsec:ALGOS_Gf_operator}).
+
+\begin{figure}[!ht]
+  \centering
+  %\includegraphics[width=0.66\textwidth]{ALGOS_ISO_triad}
+  \caption[Triads used in the Griffies's like iso-neutral diffision scheme for
+    $u$- and $w$-components)]{
+    Triads used in the Griffies's like iso-neutral diffision scheme for
+    $u$-component (upper panel) and $w$-component (lower panel).}
+  \label{fig:ALGOS_ISO_triad}
+\end{figure}
+
+The four iso-neutral fluxes associated with the triads are defined at $T$-point.
+They take the following expression:
+\begin{flalign*}
+  % \label{eq:ALGOS_Gf_fluxes}
+  \begin{split}
+    {_i^k {\mathbb{F}_u}_{i_p}^{k_p} } (T)
+    &= \ \; \qquad  \quad    { _i^k \mathbb{T}_{i_p}^{k_p} }(T) \;\ / \ { {e_{1u}}_{\,i+i_p}^{\,k}}    \\
+    {_i^k {\mathbb{F}_w}_{i_p}^{k_p} } (T)
+    &=  -\; { _i^k \mathbb{R}_{i_p}^{k_p} }
+    \ \; { _i^k \mathbb{T}_{i_p}^{k_p} }(T) \;\ / \ { {e_{3w}}_{\,i}^{\,k+k_p}}
+  \end{split}
+\end{flalign*}
+
+The resulting iso-neutral fluxes at $u$- and $w$-points are then given by
+the sum of the fluxes that cross the $u$- and $w$-face (\autoref{fig:TRIADS_ISO_triad}):
+\begin{flalign}
+  \label{eq:ALGOS_iso_flux}
+  \textbf{F}_{iso}(T)
+  &\equiv  \sum_{\substack{i_p,\,k_p}}
+  \begin{pmatrix}
+    {_{i+1/2-i_p}^k {\mathbb{F}_u}_{i_p}^{k_p} } (T) \\ \\
+    {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p} } (T)
+  \end{pmatrix}
+  \notag \\
+  &  \notag \\
+  &\equiv  \sum_{\substack{i_p,\,k_p}}
+  \begin{pmatrix}
+    && { _{i+1/2-i_p}^k \mathbb{T}_{i_p}^{k_p} }(T) \;\ / \ { {e_{1u}}_{\,i+1/2}^{\,k} } \\ \\
+    & -\; { _i^{k+1/2-k_p} \mathbb{R}_{i_p}^{k_p} }
+    & {_i^{k+1/2-k_p} \mathbb{T}_{i_p}^{k_p} }(T) \;\ / \ { {e_{3w}}_{\,i}^{\,k+1/2} }
+  \end{pmatrix}      % \\
+  % &\\
+  % &\equiv  \sum_{\substack{i_p,\,k_p}}
+  % \begin{pmatrix}
+  %   \qquad  \qquad  \qquad
+  %   \frac{1}{ {e_{1u}}_{\,i+1/2}^{\,k} }  \ \;
+  %   { _{i+1/2-i_p}^k \mathbb{T}_{i_p}^{k_p} }(T)\\
+  %   \\
+  %   -\frac{1}{ {e_{3w}}_{\,i}^{\,k+1/2} }  \ \;
+  %   { _i^{k+1/2-k_p} \mathbb{R}_{i_p}^{k_p} } \ \;
+  %   {_i^{k+1/2-k_p} \mathbb{T}_{i_p}^{k_p} }(T)\\
+  % \end{pmatrix}
+\end{flalign}
+resulting in a iso-neutral diffusion tendency on temperature given by
+the divergence of the sum of all the four triad fluxes:
+\begin{equation}
+  \label{eq:ALGOS_Gf_operator}
+  D_l^T = \frac{1}{b_T}  \sum_{\substack{i_p,\,k_p}} \left\{
+    \delta_{i} \left[{_{i+1/2-i_p}^k {\mathbb{F}_u }_{i_p}^{k_p}} \right]
+    + \delta_{k} \left[ {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}} \right]   \right\}
+\end{equation}
+where $b_T= e_{1T}\,e_{2T}\,e_{3T}$ is the volume of $T$-cells.
+
+This expression of the iso-neutral diffusion has been chosen in order to satisfy the following six properties:
+\begin{description}
+\item [Horizontal diffusion] The discretization of the diffusion operator recovers the traditional five-point Laplacian in the limit of flat iso-neutral direction:
+  \[
+    % \label{eq:ALGOS_Gf_property1a}
+    D_l^T = \frac{1}{b_T}  \ \delta_{i}
+    \left[ \frac{e_{2u}\,e_{3u}}{e_{1u}} \; \overline{A}^{\,i} \; \delta_{i+1/2}[T] \right]
+    \qquad  \text{when} \quad
+    { _i^k \mathbb{R}_{i_p}^{k_p} }=0
+  \]
+\item [Implicit treatment in the vertical] In the diagonal term associated with the vertical divergence of the iso-neutral fluxes
+  \ie\ the term associated with a second order vertical derivative)
+  appears only tracer values associated with a single water column.
+  This is of paramount importance since it means that
+  the implicit in time algorithm for solving the vertical diffusion equation can be used to evaluate this term.
+  It is a necessity since the vertical eddy diffusivity associated with this term,
+  \[
+	 \sum_{\substack{i_p, \,k_p}} \left\{
+		A_i^k \; \left(_i^k \mathbb{R}_{i_p}^{k_p}\right)^2
+    \right\}
+  \]
+  can be quite large.
+\item [Pure iso-neutral operator] The iso-neutral flux of locally referenced potential density is zero, \ie
+  \begin{align*}
+    % \label{eq:ALGOS_Gf_property2}
+    \begin{matrix}
+      &{_i^k {\mathbb{F}_u}_{i_p}^{k_p} (\rho)}
+      &=    &\alpha_i^k   &{_i^k {\mathbb{F}_u}_{i_p}^{k_p} } (T)
+      &- \ \;  \beta _i^k    &{_i^k {\mathbb{F}_u}_{i_p}^{k_p} } (S) & = \ 0   \\
+      &{_i^k {\mathbb{F}_w}_{i_p}^{k_p} (\rho)}
+      &=    &\alpha_i^k   &{_i^k {\mathbb{F}_w}_{i_p}^{k_p} } (T)
+      &- \  \; \beta _i^k    &{_i^k {\mathbb{F}_w}_{i_p}^{k_p} } (S)  &= \ 0
+    \end{matrix}
+  \end{align*}
+  This result is trivially obtained using the \autoref{eq:ALGOS_Gf_triads} applied to $T$ and $S$ and
+  the definition of the triads' slopes \autoref{eq:ALGOS_Gf_slopes}.
+\item [Conservation of tracer] The iso-neutral diffusion term conserve the total tracer content, \ie
+  \[
+    % \label{eq:ALGOS_Gf_property1}
+    \sum_{i,j,k} \left\{ D_l^T \ b_T \right\} = 0
+  \]
+This property is trivially satisfied since the iso-neutral diffusive operator is written in flux form.
+\item [Decrease of tracer variance] The iso-neutral diffusion term does not increase the total tracer variance, \ie
+  \[
+    % \label{eq:ALGOS_Gf_property1}
+    \sum_{i,j,k} \left\{ T \ D_l^T \ b_T \right\} \leq 0
+  \]
+The property is demonstrated in the \autoref{subsec:ALGOS_Gf_operator}.
+It is a key property for a diffusion term.
+It means that the operator is also a dissipation term,
+\ie\ it is a sink term for the square of the quantity on which it is applied.
+It therfore ensures that, when the diffusivity coefficient is large enough,
+the field on which it is applied become free of grid-point noise.
+\item [Self-adjoint operator] The iso-neutral diffusion operator is self-adjoint, \ie
+  \[
+    % \label{eq:ALGOS_Gf_property1}
+    \sum_{i,j,k} \left\{ S \ D_l^T \ b_T \right\} = \sum_{i,j,k} \left\{ D_l^S \ T \ b_T \right\}
+  \]
+In other word, there is no needs to develop a specific routine from the adjoint of this operator.
+We just have to apply the same routine.
+This properties can be demonstrated quite easily in a similar way the "non increase of tracer variance" property
+has been proved (see \autoref{apdx:ALGOS_Gf_operator}).
+\end{description}
+
+%% =================================================================================================
+\subsection{Eddy induced velocity and skew flux formulation}
+
+When Gent and McWilliams [1990] diffusion is used (\key{traldf\_eiv} defined),
+an additional advection term is added.
+The associated velocity is the so called eddy induced velocity,
+the formulation of which depends on the slopes of iso-neutral surfaces.
+Contrary to the case of iso-neutral mixing, the slopes used here are referenced to the geopotential surfaces,
+\ie\ \autoref{eq:LDF_slp_geo} is used in $z$-coordinate,
+and the sum \autoref{eq:LDF_slp_geo} + \autoref{eq:LDF_slp_iso} in $z^*$ or $s$-coordinates.
+
+The eddy induced velocity is given by:
+\begin{equation}
+  \label{eq:ALGOS_eiv_v}
+  \begin{split}
+    u^* & = - \frac{1}{e_2\,e_{3}}          \;\partial_k \left( e_2 \, A_e \; r_i  \right)
+    = - \frac{1}{e_3}                     \;\partial_k \left(           A_e \; r_i  \right)            \\
+    v^* & = - \frac{1}{e_1\,e_3}\;             \partial_k \left( e_1 \, A_e \; r_j  \right)
+    = - \frac{1}{e_3}                     \;\partial_k \left(           A_e \; r_j  \right)             \\
+    w^* & =    \frac{1}{e_1\,e_2}\; \left\{   \partial_i  \left( e_2 \, A_e \; r_i  \right)
+      + \partial_j  \left( e_1 \, A_e \;r_j   \right) \right\}
+  \end{split}
+\end{equation}
+where $A_{e}$ is the eddy induced velocity coefficient,
+and $r_i$ and $r_j$ the slopes between the iso-neutral and the geopotential surfaces.
+\cmtgm{Wrong: to be modified with 2 2D streamfunctions}
+In other words, the eddy induced velocity can be derived from a vector streamfuntion, $\phi$,
+which is given by $\phi = A_e\,\textbf{r}$ as $\textbf{U}^*  = \textbf{k} \times \nabla \phi$.
+
+A traditional way to implement this additional advection is to add it to the eulerian velocity prior to
+compute the tracer advection.
+This allows us to take advantage of all the advection schemes offered for the tracers
+(see \autoref{sec:TRA_adv}) and not just a $2^{nd}$ order advection scheme.
+This is particularly useful for passive tracers where
+\emph{positivity} of the advection scheme is of paramount importance.
+% give here the expression using the triads. It is different from the one given in \autoref{eq:LDF_eiv}
+% see just below a copy of this equation:
+%\begin{equation} \label{eq:ALGOS_ldfeiv}
+%\begin{split}
+% u^* & = \frac{1}{e_{2u}e_{3u}}\; \delta_k \left[e_{2u} \, A_{uw}^{eiv} \; \overline{r_{1w}}^{\,i+1/2} \right]\\
+% v^* & = \frac{1}{e_{1u}e_{3v}}\; \delta_k \left[e_{1v} \, A_{vw}^{eiv} \; \overline{r_{2w}}^{\,j+1/2} \right]\\
+%w^* & = \frac{1}{e_{1w}e_{2w}}\; \left\{ \delta_i \left[e_{2u} \, A_{uw}^{eiv} \; \overline{r_{1w}}^{\,i+1/2} \right] + %\delta_j \left[e_{1v} \, A_{vw}^{eiv} \; \overline{r_{2w}}^{\,j+1/2} \right] \right\} \\
+%\end{split}
+%\end{equation}
+\[
+  % \label{eq:ALGOS_eiv_vd}
+  \textbf{F}_{eiv}^T   \equiv   \left(
+    \begin{aligned}
+      \sum_{\substack{i_p,\,k_p}} &
+      +{e_{2u}}_{i+1/2-i_p}^{k}                                  \ \ {A_{e}}_{i+1/2-i_p}^{k}
+      \ \ \ { _{i+1/2-i_p}^k \mathbb{R}_{i_p}^{k_p} }    \ \ \delta_{k+k_p}[T_{i+1/2-i_p}] \\ \\
+      \sum_{\substack{i_p,\,k_p}} &
+      - {e_{2u}}_i^{k+1/2-k_p}                                      \ {A_{e}}_i^{k+1/2-k_p}
+      \ \ { _i^{k+1/2-k_p} \mathbb{R}_{i_p}^{k_p} }    \ \delta_{i+i_p}[T^{k+1/2-k_p}]
+    \end{aligned}
+  \right)
+\]
+
+\citep{griffies_JPO98} introduces another way to implement the eddy induced advection, the so-called skew form.
+It is based on a transformation of the advective fluxes using the non-divergent nature of the eddy induced velocity.
+For example in the (\textbf{i},\textbf{k}) plane, the tracer advective fluxes can be transformed as follows:
+\begin{flalign*}
+  \begin{split}
+    \textbf{F}_{eiv}^T =
+    \begin{pmatrix}
+      {e_{2}\,e_{3}\;  u^*} 	 	\\
+ 		{e_{1}\,e_{2}\; w^*}
+    \end{pmatrix}
+    \;   T
+    &=
+    \begin{pmatrix}
+      { - \partial_k \left( e_{2} \, A_{e} \; r_i \right) \; T \;} 	 	\\
+ 		{+ \partial_i  \left( e_{2} \, A_{e} \; r_i \right) \; T \;}
+    \end{pmatrix}
+    \\
+    &=
+    \begin{pmatrix}
+      { - \partial_k \left( e_{2} \, A_{e} \; r_i  \; T \right) \;}  \\
+ 		{+ \partial_i  \left( e_{2} \, A_{e} \; r_i  \; T \right) \;}
+    \end{pmatrix}
+    +
+    \begin{pmatrix}
+      {+ e_{2} \, A_{e} \; r_i  \; \partial_k T}  \\
+ 		{ - e_{2} \, A_{e} \; r_i  \; \partial_i  T}
+    \end{pmatrix}
+  \end{split}
+\end{flalign*}
+and since the eddy induces velocity field is no-divergent,
+we end up with the skew form of the eddy induced advective fluxes:
+\begin{equation}
+  \label{eq:ALGOS_eiv_skew_continuous}
+  \textbf{F}_{eiv}^T =
+  \begin{pmatrix}
+    {+ e_{2} \, A_{e} \; r_i  \; \partial_k T}   \\
+    { - e_{2} \, A_{e} \; r_i  \; \partial_i  T}
+  \end{pmatrix}
+\end{equation}
+The tendency associated with eddy induced velocity is then simply the divergence of
+the \autoref{eq:ALGOS_eiv_skew_continuous} fluxes.
+It naturally conserves the tracer content, as it is expressed in flux form and,
+as the advective form, it preserves the tracer variance.
+Another interesting property of \autoref{eq:ALGOS_eiv_skew_continuous} form is that when $A=A_e$,
+a simplification occurs in the sum of the iso-neutral diffusion and eddy induced velocity terms:
+\begin{flalign*}
+  % \label{eq:ALGOS_eiv_skew+eiv_continuous}
+  \textbf{F}_{iso}^T + \textbf{F}_{eiv}^T &=
+  \begin{pmatrix}
+    + \frac{e_2\,e_3\,}{e_1} A \;\partial_i T -  e_2 \, A \; r_i                              \;\partial_k T   \\
+    -  e_2 \, A_{e} \; r_i           \;\partial_i T + \frac{e_1\,e_2}{e_3} \, A \; r_i^2 \;\partial_k T
+  \end{pmatrix}
+  +
+  \begin{pmatrix}
+    {+ e_{2} \, A_{e} \; r_i  \; \partial_k T}   \\
+    { - e_{2} \, A_{e} \; r_i  \; \partial_i  T}
+  \end{pmatrix}
+  \\
+  &=
+  \begin{pmatrix}
+    + \frac{e_2\,e_3\,}{e_1} A \;\partial_i T    \\
+    -  2\; e_2 \, A_{e} \; r_i      \;\partial_i T + \frac{e_1\,e_2}{e_3} \, A \; r_i^2 \;\partial_k T
+  \end{pmatrix}
+\end{flalign*}
+The horizontal component reduces to the one use for an horizontal laplacian operator and
+the vertical one keeps the same complexity, but not more.
+This property has been used to reduce the computational time \citep{griffies_JPO98},
+but it is not of practical use as usually $A \neq A_e$.
+Nevertheless this property can be used to choose a discret form of \autoref{eq:ALGOS_eiv_skew_continuous} which
+is consistent with the iso-neutral operator \autoref{eq:ALGOS_Gf_operator}.
+Using the slopes \autoref{eq:ALGOS_Gf_slopes} and defining $A_e$ at $T$-point(\ie\ as $A$,
+the eddy diffusivity coefficient), the resulting discret form is given by:
+\begin{equation}
+  \label{eq:ALGOS_eiv_skew}
+  \textbf{F}_{eiv}^T   \equiv   \frac{1}{4} \left(
+    \begin{aligned}
+      \sum_{\substack{i_p,\,k_p}} &
+      +{e_{2u}}_{i+1/2-i_p}^{k}                                  \ \ {A_{e}}_{i+1/2-i_p}^{k}
+      \ \ \ { _{i+1/2-i_p}^k \mathbb{R}_{i_p}^{k_p} }    \ \ \delta_{k+k_p}[T_{i+1/2-i_p}] \\ \\
+      \sum_{\substack{i_p,\,k_p}} &
+      - {e_{2u}}_i^{k+1/2-k_p}                                      \ {A_{e}}_i^{k+1/2-k_p}
+      \ \ { _i^{k+1/2-k_p} \mathbb{R}_{i_p}^{k_p} }    \ \delta_{i+i_p}[T^{k+1/2-k_p}]
+    \end{aligned}
+  \right)
+\end{equation}
+Note that \autoref{eq:ALGOS_eiv_skew} is valid in $z$-coordinate with or without partial cells.
+In $z^*$ or $s$-coordinate, the slope between the level and the geopotential surfaces must be added to
+$\mathbb{R}$ for the discret form to be exact.
+
+Such a choice of discretisation is consistent with the iso-neutral operator as
+it uses the same definition for the slopes.
+It also ensures the conservation of the tracer variance (see \autoref{subsec:ALGOS_eiv_skew}),
+\ie\ it does not include a diffusive component but is a "pure" advection term.
+
+%% =================================================================================================
+\subsection{Discrete invariants of the iso-neutral diffrusion}
+\label{subsec:ALGOS_Gf_operator}
+
+Demonstration of the decrease of the tracer variance in the (\textbf{i},\textbf{j}) plane.
+
+This part will be moved in an Appendix.
+
+The continuous property to be demonstrated is:
+\[
+  \int_D  D_l^T \; T \;dv   \leq 0
+\]
+The discrete form of its left hand side is obtained using \autoref{eq:TRIADS_iso_flux}
+
+\begin{align*}
+  &\int_D  D_l^T \; T \;dv \equiv  \sum_{i,k} \left\{ T \ D_l^T \ b_T \right\}    \\
+  &\equiv + \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+    \delta_{i} \left[{_{i+1/2-i_p}^k {\mathbb{F}_u }_{i_p}^{k_p}} \right]
+    + \delta_{k} \left[ {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}} \right]  \ T \right\}    \\
+  &\equiv  - \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+    {_{i+1/2-i_p}^k {\mathbb{F}_u }_{i_p}^{k_p}} \ \delta_{i+1/2} [T]
+    + {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}}  \ \delta_{k+1/2} [T]   \right\}      \\
+  &\equiv -\sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+    \frac{ _{i+1/2-i_p}^k \mathbb{T}_{i_p}^{k_p} (T) }{ {e_{1u}}_{\,i+1/2}^{\,k} }  \ \delta_{i+1/2} [T]
+    - { _i^{k+1/2-k_p} \mathbb{R}_{i_p}^{k_p} } \ \;
+    \frac{ _i^{k+1/2-k_p} \mathbb{T}_{i_p}^{k_p} (T) }{ {e_{3w}}_{\,i}^{\,k+1/2}  } \ \delta_{k+1/2} [T]
+    \right\}      \\
+    %
+  \allowdisplaybreaks
+  \intertext{ Expending the summation on $i_p$ and $k_p$, it becomes:}
+  %
+  &\equiv -\sum_{i,k}
+    \begin{Bmatrix}
+      &\ \ \Bigl(  { _{i+1}^{k} \mathbb{T}_{-1/2}^{-1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_{i}^{k+1} \mathbb{R}_{-1/2}^{-1/2}}
+      &      {_{i}^{k+1} \mathbb{T}_{-1/2}^{-1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)
+      & \\
+      &+\Bigl( \ \;\; { _i^k \mathbb{T}_{+1/2}^{-1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_i^{k+1} \mathbb{R}_{+1/2}^{-1/2}}
+      & { _i^{k+1} \mathbb{T}_{+1/2}^{-1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}      \Bigr)
+      & \\
+      &+\Bigl(  { _{i+1}^{k} \mathbb{T}_{-1/2}^{+1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ \ \;\;{_{i}^{k} \mathbb{R}_{-1/2}^{+1/2}}
+      &      \ \;\;{_{i}^{k} \mathbb{T}_{-1/2}^{+1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)
+      & \\
+      &+\Bigl( \ \;\; { _{i}^{k} \mathbb{T}_{+1/2}^{+1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ \ \;\;{_{i}^{k} \mathbb{R}_{+1/2}^{+1/2}}
+      &      \ \;\;{_{i}^{k} \mathbb{T}_{+1/2}^{+1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)   \\
+    \end{Bmatrix}
+    %
+  \allowdisplaybreaks
+  \intertext{
+  The summation is done over all $i$ and $k$ indices,
+  it is therefore possible to introduce a shift of $-1$ either in $i$ or $k$ direction in order to
+  regroup all the terms of the summation by triad at a ($i$,$k$) point.
+  In other words, we regroup all the terms in the neighbourhood that contain a triad at the same ($i$,$k$) indices.
+  It becomes:
+  }
+  %
+  &\equiv -\sum_{i,k}
+    \begin{Bmatrix}
+      &\ \ \Bigl(  {_i^k \mathbb{T}_{-1/2}^{-1/2} (T) }
+      &\frac{ \delta_{i -1/2} [T] }{{e_{1u} }_{\,i-1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{-1/2}^{-1/2}}
+      &      {_i^k \mathbb{T}_{-1/2}^{-1/2} (T) }
+      &\frac{ \delta_{k-1/2} [T] }{{e_{3w}}_{\,i}^{\,k-1/2}}     \Bigr)
+      & \\
+      &+\Bigl(  { _i^k \mathbb{T}_{+1/2}^{-1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{+1/2}^{-1/2}}
+      &      { _i^k \mathbb{T}_{+1/2}^{-1/2} (T) }
+      &\frac{ \delta_{k-1/2} [T] }{{e_{3w}}_{\,i}^{\,k-1/2}}      \Bigr)
+      & \\
+      &+\Bigl(  {_i^k \mathbb{T}_{-1/2}^{+1/2} (T) }
+      &\frac{ \delta_{i -1/2} [T] }{{e_{1u} }_{\,i-1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{-1/2}^{+1/2}}
+      &      {_i^k \mathbb{T}_{-1/2}^{+1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)
+      & \\
+      &+\Bigl( { _i^k \mathbb{T}_{+1/2}^{+1/2} (T) }
+      &\frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{+1/2}^{+1/2}}
+      &      {_i^k \mathbb{T}_{+1/2}^{+1/2} (T) }
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)   \\
+    \end{Bmatrix}   \\
+    %
+  \allowdisplaybreaks
+  \intertext{
+  Then outing in factor the triad in each of the four terms of the summation and
+  substituting the triads by their expression given in \autoref{eq:ALGOS_Gf_triads}.
+  It becomes:
+  }
+  %
+  &\equiv -\sum_{i,k}
+    \begin{Bmatrix}
+      &\ \ \Bigl(  \frac{ \delta_{i -1/2} [T] }{{e_{1u} }_{\,i-1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{-1/2}^{-1/2}}
+      &\frac{ \delta_{k-1/2} [T] }{{e_{3w}}_{\,i}^{\,k-1/2}}     \Bigr)^2
+      & \frac{1}{4} \ {b_u}_{\,i-1/2}^{\,k}  \  A_i^k
+      & \\
+      &+\Bigl(  \frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{+1/2}^{-1/2}}
+      &\frac{ \delta_{k-1/2} [T] }{{e_{3w}}_{\,i}^{\,k-1/2}}      \Bigr)^2
+      & \frac{1}{4} \ {b_u}_{\,i+1/2}^{\,k}  \  A_i^k
+      & \\
+      &+\Bigl(  \frac{ \delta_{i -1/2} [T] }{{e_{1u} }_{\,i-1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{-1/2}^{+1/2}}
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)^2
+      & \frac{1}{4} \ {b_u}_{\,i-1/2}^{\,k}  \  A_i^k
+      & \\
+      &+\Bigl( \frac{ \delta_{i +1/2} [T] }{{e_{1u} }_{\,i+1/2}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{+1/2}^{+1/2}}
+      &\frac{ \delta_{k+1/2} [T] }{{e_{3w}}_{\,i}^{\,k+1/2}}     \Bigr)^2
+      & \frac{1}{4} \ {b_u}_{\,i+1/2}^{\,k}  \  A_i^k      \\
+    \end{Bmatrix}
+  \\
+  & \\
+  %
+  &\equiv - \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+    \begin{matrix}
+      &\Bigl( \frac{ \delta_{i +i_p} [T] }{{e_{1u} }_{\,i+i_p}^{\,k}}
+      & -\ \ {_i^k \mathbb{R}_{i_p}^{k_p}}
+      &\frac{ \delta_{k+k_p} [T] }{{e_{3w}}_{\,i}^{\,k+k_p}}     \Bigr)^2
+      & \frac{1}{4} \ {b_u}_{\,i+i_p}^{\,k}  \  A_i^k   \ \
+    \end{matrix}
+        \right\}
+        \quad   \leq 0
+\end{align*}
+The last inequality is obviously obtained as we succeed in obtaining a negative summation of square quantities.
+
+Note that, if instead of multiplying $D_l^T$ by $T$, we were using another tracer field, let say $S$,
+then the previous demonstration would have let to:
+\begin{align*}
+  \int_D  S \; D_l^T  \;dv &\equiv  \sum_{i,k} \left\{ S \ D_l^T \ b_T \right\}    \\
+                           &\equiv - \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+                             \left( \frac{ \delta_{i +i_p} [S] }{{e_{1u} }_{\,i+i_p}^{\,k}}
+                             - {_i^k \mathbb{R}_{i_p}^{k_p}}
+                             \frac{ \delta_{k+k_p} [S] }{{e_{3w}}_{\,i}^{\,k+k_p}}     \right)  \right. \\
+                           & \qquad \qquad \qquad \ \left.
+                             \left( \frac{ \delta_{i +i_p} [T] }{{e_{1u} }_{\,i+i_p}^{\,k}}
+                             - {_i^k \mathbb{R}_{i_p}^{k_p}}
+                             \frac{ \delta_{k+k_p} [T] }{{e_{3w}}_{\,i}^{\,k+k_p}}     \right)
+                             \frac{1}{4} \ {b_u}_{\,i+i_p}^{\,k}  \  A_i^k   \
+                             \right\}
+                             %
+                             \allowdisplaybreaks
+                             \intertext{
+                             which, by applying the same operation as before but in reverse order, leads to:
+                             }
+                             %
+                           &\equiv  \sum_{i,k} \left\{ D_l^S \ T \ b_T \right\}
+\end{align*}
+This means that the iso-neutral operator is self-adjoint.
+There is no need to develop a specific to obtain it.
+
+%% =================================================================================================
+\subsection{Discrete invariants of the skew flux formulation}
+\label{subsec:ALGOS_eiv_skew}
+
+Demonstration for the conservation of the tracer variance in the (\textbf{i},\textbf{j}) plane.
+
+This have to be moved in an Appendix.
+
+The continuous property to be demonstrated is:
+\begin{align*}
+  \int_D \nabla \cdot \textbf{F}_{eiv}(T) \; T \;dv  \equiv 0
+\end{align*}
+The discrete form of its left hand side is obtained using \autoref{eq:ALGOS_eiv_skew}
+\begin{align*}
+  \sum\limits_{i,k} \sum_{\substack{i_p,\,k_p}}  \Biggl\{   \;\;
+  \delta_i  &\left[
+              {e_{2u}}_{i+i_p+1/2}^{k}                                  \;\ \ {A_{e}}_{i+i_p+1/2}^{k}
+              \ \ \ { _{i+i_p+1/2}^k \mathbb{R}_{-i_p}^{k_p} }   \quad \delta_{k+k_p}[T_{i+i_p+1/2}]
+              \right] \; T_i^k      \\
+  - \delta_k &\left[
+               {e_{2u}}_i^{k+k_p+1/2}                                     \ \ {A_{e}}_i^{k+k_p+1/2}
+               \ \ { _i^{k+k_p+1/2} \mathbb{R}_{i_p}^{-k_p} }   \ \ \delta_{i+i_p}[T^{k+k_p+1/2}]
+               \right] \; T_i^k      \         \Biggr\}
+\end{align*}
+apply the adjoint of delta operator, it becomes
+\begin{align*}
+  \sum\limits_{i,k} \sum_{\substack{i_p,\,k_p}}  \Biggl\{   \;\;
+  &\left(
+    {e_{2u}}_{i+i_p+1/2}^{k}                                  \;\ \ {A_{e}}_{i+i_p+1/2}^{k}
+    \ \ \ { _{i+i_p+1/2}^k \mathbb{R}_{-i_p}^{k_p} }   \quad \delta_{k+k_p}[T_{i+i_p+1/2}]
+    \right) \; \delta_{i+1/2}[T^{k}]      \\
+  - &\left(
+      {e_{2u}}_i^{k+k_p+1/2}                                     \ \ {A_{e}}_i^{k+k_p+1/2}
+      \ \ { _i^{k+k_p+1/2} \mathbb{R}_{i_p}^{-k_p} }   \ \ \delta_{i+i_p}[T^{k+k_p+1/2}]
+      \right) \; \delta_{k+1/2}[T_{i}]       \         \Biggr\}
+\end{align*}
+Expending the summation on $i_p$ and $k_p$, it becomes:
+\begin{align*}
+  \begin{matrix}
+    &\sum\limits_{i,k}   \Bigl\{
+    &+{e_{2u}}_{i+1}^{k}                             &{A_{e}}_{i+1    }^{k}
+    &\ {_{i+1}^k \mathbb{R}_{- 1/2}^{-1/2}} &\delta_{k-1/2}[T_{i+1}]    &\delta_{i+1/2}[T^{k}]   &\\
+    &&+{e_{2u}}_i^{k\ \ \ \:}                            &{A_{e}}_{i}^{k\ \ \ \:}
+    &\ {\ \ \;_i^k \mathbb{R}_{+1/2}^{-1/2}}  &\delta_{k-1/2}[T_{i\ \ \ \;}]  &\delta_{i+1/2}[T^{k}] &\\
+    &&+{e_{2u}}_{i+1}^{k}                             &{A_{e}}_{i+1    }^{k}
+    &\ {_{i+1}^k \mathbb{R}_{- 1/2}^{+1/2}} &\delta_{k+1/2}[T_{i+1}]     &\delta_{i+1/2}[T^{k}] &\\
+    &&+{e_{2u}}_i^{k\ \ \ \:}                            &{A_{e}}_{i}^{k\ \ \ \:}
+    &\ {\ \ \;_i^k \mathbb{R}_{+1/2}^{+1/2}} &\delta_{k+1/2}[T_{i\ \ \ \;}] &\delta_{i+1/2}[T^{k}] &\\
+    %
+    &&-{e_{2u}}_i^{k+1}                                &{A_{e}}_i^{k+1}
+    &{_i^{k+1} \mathbb{R}_{-1/2}^{- 1/2}}   &\delta_{i-1/2}[T^{k+1}]      &\delta_{k+1/2}[T_{i}] &\\
+    &&-{e_{2u}}_i^{k\ \ \ \:}                             &{A_{e}}_i^{k\ \ \ \:}
+    &{\ \ \;_i^k  \mathbb{R}_{-1/2}^{+1/2}}   &\delta_{i-1/2}[T^{k\ \ \ \:}]  &\delta_{k+1/2}[T_{i}] &\\
+    &&-{e_{2u}}_i^{k+1    }                             &{A_{e}}_i^{k+1}
+    &{_i^{k+1} \mathbb{R}_{+1/2}^{- 1/2}}   &\delta_{i+1/2}[T^{k+1}]      &\delta_{k+1/2}[T_{i}] &\\
+    &&-{e_{2u}}_i^{k\ \ \ \:}                             &{A_{e}}_i^{k\ \ \ \:}
+    &{\ \ \;_i^k  \mathbb{R}_{+1/2}^{+1/2}}   &\delta_{i+1/2}[T^{k\ \ \ \:}]  &\delta_{k+1/2}[T_{i}]
+    &\Bigr\}  \\
+  \end{matrix}
+\end{align*}
+The two terms associated with the triad ${_i^k \mathbb{R}_{+1/2}^{+1/2}}$ are the same but of opposite signs,
+they cancel out.
+Exactly the same thing occurs for the triad ${_i^k \mathbb{R}_{-1/2}^{-1/2}}$.
+The two terms associated with the triad ${_i^k \mathbb{R}_{+1/2}^{-1/2}}$ are the same but both of opposite signs and
+shifted by 1 in $k$ direction.
+When summing over $k$ they cancel out with the neighbouring grid points.
+Exactly the same thing occurs for the triad ${_i^k \mathbb{R}_{-1/2}^{+1/2}}$ in the $i$ direction.
+Therefore the sum over the domain is zero,
+\ie\ the variance of the tracer is preserved by the discretisation of the skew fluxes.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_diff_opers.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_diff_opers.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_diff_opers.tex	(revision 14097)
@@ -0,0 +1,425 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Diffusive Operators}
+\label{apdx:DIFFOPERS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Horizontal/Vertical $2^{nd}$ order tracer diffusive operators}
+\label{sec:DIFFOPERS_1}
+
+%% =================================================================================================
+\subsubsection*{In z-coordinates}
+
+In $z$-coordinates, the horizontal/vertical second order tracer diffusion operator is given by:
+\begin{align}
+  \label{eq:DIFFOPERS_1}
+  &D^T = \frac{1}{e_1 \, e_2}      \left[
+    \left. \frac{\partial}{\partial i} \left( 	\frac{e_2}{e_1}A^{lT} \;\left. \frac{\partial T}{\partial i} \right|_z   \right)   \right|_z      \right.
+    \left.
+    + \left. \frac{\partial}{\partial j} \left(  \frac{e_1}{e_2}A^{lT} \;\left. \frac{\partial T}{\partial j} \right|_z   \right)   \right|_z      \right]
+    + \frac{\partial }{\partial z}\left( {A^{vT} \;\frac{\partial T}{\partial z}} \right)
+\end{align}
+
+%% =================================================================================================
+\subsubsection*{In generalized vertical coordinates}
+
+In $s$-coordinates, we defined the slopes of $s$-surfaces, $\sigma_1$ and $\sigma_2$ by \autoref{eq:SCOORD_s_slope} and
+the vertical/horizontal ratio of diffusion coefficient by $\epsilon = A^{vT} / A^{lT}$.
+The diffusion operator is given by:
+
+\begin{equation}
+  \label{eq:DIFFOPERS_2}
+  D^T = \left. \nabla \right|_s \cdot
+  \left[ A^{lT} \;\Re \cdot \left. \nabla \right|_s T  \right] \\
+  \;\;\text{where} \;\Re =\left( {{
+        \begin{array}{*{20}c}
+          1 \hfill & 0 \hfill & {-\sigma_1 } \hfill \\
+          0 \hfill & 1 \hfill & {-\sigma_2 } \hfill \\
+          {-\sigma_1 } \hfill & {-\sigma_2 } \hfill & {\varepsilon +\sigma_1
+                                                      ^2+\sigma_2 ^2} \hfill \\
+        \end{array}
+      }} \right)
+\end{equation}
+or in expanded form:
+\begin{align*}
+  {
+  \begin{array}{*{20}l}
+    D^T= \frac{1}{e_1\,e_2\,e_3 } & \left\{ \quad \quad \frac{\partial }{\partial i}  \left. \left[  e_2\,e_3 \, A^{lT}
+                               \left( \  \frac{1}{e_1}\; \left. \frac{\partial T}{\partial i} \right|_s
+                                       -\frac{\sigma_1 }{e_3 } \; \frac{\partial T}{\partial s} \right) \right]  \right|_s  \right. \\
+        &  \quad \  +   \            \left.   \frac{\partial }{\partial j}  \left. \left[  e_1\,e_3 \, A^{lT}
+                               \left( \ \frac{1}{e_2 }\; \left. \frac{\partial T}{\partial j} \right|_s
+                                       -\frac{\sigma_2 }{e_3 } \; \frac{\partial T}{\partial s} \right) \right]  \right|_s  \right. \\
+        &  \quad \  +   \           \left.  e_1\,e_2\, \frac{\partial }{\partial s}  \left[ A^{lT} \; \left(
+	                  -\frac{\sigma_1 }{e_1 } \; \left. \frac{\partial T}{\partial i} \right|_s
+	                  -\frac{\sigma_2 }{e_2 } \; \left. \frac{\partial T}{\partial j} \right|_s
+                          +\left( \varepsilon +\sigma_1^2+\sigma_2 ^2 \right) \; \frac{1}{e_3 } \; \frac{\partial T}{\partial s} \right) \; \right] \;  \right\} .
+  \end{array}
+          }
+\end{align*}
+
+\autoref{eq:DIFFOPERS_2} is obtained from \autoref{eq:DIFFOPERS_1} without any additional assumption.
+Indeed, for the special case $k=z$ and thus $e_3 =1$,
+we introduce an arbitrary vertical coordinate $s = s (i,j,z)$ as in \autoref{apdx:SCOORD} and
+use \autoref{eq:SCOORD_s_slope} and \autoref{eq:SCOORD_s_chain_rule1}.
+Since no cross horizontal derivative $\partial _i \partial _j $ appears in \autoref{eq:DIFFOPERS_1},
+the ($i$,$z$) and ($j$,$z$) planes are independent.
+The derivation can then be demonstrated for the ($i$,$z$)~$\to$~($j$,$s$) transformation without
+any loss of generality:
+
+\begin{align*}
+  {
+  \begin{array}{*{20}l}
+    D^T&=\frac{1}{e_1\,e_2} \left. {\frac{\partial }{\partial i}\left( {\frac{e_2}{e_1}A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_z } \right)} \right|_z
+         +\frac{\partial }{\partial z}\left( {A^{vT}\;\frac{\partial T}{\partial z}} \right) \\ \\
+         %
+       &=\frac{1}{e_1\,e_2 }\left[ {\left. {\;\frac{\partial }{\partial i}\left( {\frac{e_2}{e_1}A^{lT}\;\left( {\left. {\frac{\partial T}{\partial i}} \right|_s
+         -\frac{e_1\,\sigma_1 }{e_3 }\frac{\partial T}{\partial s}} \right)} \right)} \right|_s } \right. \\
+       & \qquad \qquad \left. { -\frac{e_1\,\sigma_1 }{e_3 }\frac{\partial }{\partial s}\left( {\frac{e_2 }{e_1 }A^{lT}\;\left. {\left( {\left. {\frac{\partial T}{\partial i}} \right|_s -\frac{e_1 \,\sigma_1 }{e_3 }\frac{\partial T}{\partial s}} \right)} \right|_s } \right)\;} \right]
+         \shoveright{ +\frac{1}{e_3 }\frac{\partial }{\partial s}\left[ {\frac{A^{vT}}{e_3 }\;\frac{\partial T}{\partial s}} \right]}  \qquad \qquad \qquad \\ \\
+         %
+       &=\frac{1}{e_1 \,e_2 \,e_3 }\left[ {\left. {\;\;\frac{\partial }{\partial i}\left( {\frac{e_2 \,e_3 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right)} \right|_s -\left. {\frac{e_2 }{e_1}A^{lT}\;\frac{\partial e_3 }{\partial i}} \right|_s \left. {\frac{\partial T}{\partial i}} \right|_s } \right. \\
+       &  \qquad \qquad \quad \left. {-e_3 \frac{\partial }{\partial i}\left( {\frac{e_2 \,\sigma_1 }{e_3 }A^{lT}\;\frac{\partial T}{\partial s}} \right)} \right|_s -e_1 \,\sigma_1 \frac{\partial }{\partial s}\left( {\frac{e_2 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right) \\
+       &  \qquad \qquad \quad \shoveright{ -e_1 \,\sigma_1 \frac{\partial }{\partial s}\left( {-\frac{e_2 \,\sigma_1 }{e_3 }A^{lT}\;\frac{\partial T}{\partial s}} \right)\;\,\left. {+\frac{\partial }{\partial s}\left( {\frac{e_1 \,e_2 }{e_3 }A^{vT}\;\frac{\partial T}{\partial s}} \right)\quad} \right] }\\
+  \end{array}
+  } 		\\
+  %
+  {
+  \begin{array}{*{20}l}
+    \intertext{Noting that $\frac{1}{e_1} \left. \frac{\partial e_3 }{\partial i} \right|_s = \frac{\partial \sigma_1 }{\partial s}$, this becomes:}
+    %
+    D^T & =\frac{1}{e_1\,e_2\,e_3 }\left[ {\left. {\;\;\;\frac{\partial }{\partial i}\left( {\frac{e_2\,e_3 }{e_1}\,A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right)} \right|_s \left. -\, {e_3 \frac{\partial }{\partial i}\left( {\frac{e_2 \,\sigma_1 }{e_3 }A^{lT}\;\frac{\partial T}{\partial s}} \right)} \right|_s } \right. \\
+    & \qquad \qquad \quad -e_2 A^{lT}\;\frac{\partial \sigma_1 }{\partial s}\left. {\frac{\partial T}{\partial i}} \right|_s -e_1 \,\sigma_1 \frac{\partial }{\partial s}\left( {\frac{e_2 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right) \\
+    & \qquad \qquad \quad\shoveright{ \left. { +e_1 \,\sigma_1 \frac{\partial }{\partial s}\left( {\frac{e_2 \,\sigma_1 }{e_3 }A^{lT}\;\frac{\partial T}{\partial s}} \right)+\frac{\partial }{\partial s}\left( {\frac{e_1 \,e_2 }{e_3 }A^{vT}\;\frac{\partial T}{\partial s}} \right)\;\;\;} \right] }\\
+    \\
+    &=\frac{1}{e_1 \,e_2 \,e_3 } \left[ {\left. {\;\;\;\frac{\partial }{\partial i} \left( {\frac{e_2 \,e_3 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right)} \right|_s \left. {-\frac{\partial }{\partial i}\left( {e_2 \,\sigma_1 A^{lT}\;\frac{\partial T}{\partial s}} \right)} \right|_s } \right. \\
+    & \qquad \qquad \quad \left. {+\frac{e_2 \,\sigma_1 }{e_3}A^{lT}\;\frac{\partial T}{\partial s} \;\frac{\partial e_3 }{\partial i}}  \right|_s -e_2 A^{lT}\;\frac{\partial \sigma_1 }{\partial s}\left. {\frac{\partial T}{\partial i}} \right|_s \\
+    & \qquad \qquad \quad-e_2 \,\sigma_1 \frac{\partial}{\partial s}\left( {A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right)+\frac{\partial }{\partial s}\left( {\frac{e_1 \,e_2 \,\sigma_1 ^2}{e_3 }A^{lT}\;\frac{\partial T}{\partial s}} \right) \\
+    & \qquad \qquad \quad\shoveright{ \left. {-\frac{\partial \left( {e_1 \,e_2 \,\sigma_1 } \right)}{\partial s} \left( {\frac{\sigma_1 }{e_3}A^{lT}\;\frac{\partial T}{\partial s}} \right) + \frac{\partial }{\partial s}\left( {\frac{e_1 \,e_2 }{e_3 }A^{vT}\;\frac{\partial T}{\partial s}} \right)\;\;\;} \right]} .
+  \end{array}
+      } \\
+  {
+  \begin{array}{*{20}l}
+    %
+    \intertext{Using the same remark as just above, $D^T$ becomes:}
+    %
+   D^T &= \frac{1}{e_1 \,e_2 \,e_3 } \left[ {\left. {\;\;\;\frac{\partial }{\partial i} \left( {\frac{e_2 \,e_3 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s -e_2 \,\sigma_1 A^{lT}\;\frac{\partial T}{\partial s}} \right)} \right|_s } \right.\;\;\; \\
+    & \qquad \qquad \quad+\frac{e_1 \,e_2 \,\sigma_1 }{e_3 }A^{lT}\;\frac{\partial T}{\partial s}\;\frac{\partial \sigma_1 }{\partial s} - \frac {\sigma_1 }{e_3} A^{lT} \;\frac{\partial \left( {e_1 \,e_2 \,\sigma_1 } \right)}{\partial s}\;\frac{\partial T}{\partial s} \\
+    & \qquad \qquad \quad-e_2 \left( {A^{lT}\;\frac{\partial \sigma_1 }{\partial s}\left. {\frac{\partial T}{\partial i}} \right|_s +\frac{\partial }{\partial s}\left( {\sigma_1 A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right)-\frac{\partial \sigma_1 }{\partial s}\;A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s } \right) \\
+    & \qquad \qquad \quad\shoveright{\left. {+\frac{\partial }{\partial s}\left( {\frac{e_1 \,e_2 \,\sigma_1 ^2}{e_3 }A^{lT}\;\frac{\partial T}{\partial s}+\frac{e_1 \,e_2}{e_3 }A^{vT}\;\frac{\partial T}{\partial s}} \right)\;\;\;} \right] . }
+  \end{array}
+      } \\
+  {
+  \begin{array}{*{20}l}
+    %
+    \intertext{Since the horizontal scale factors do not depend on the vertical coordinate,
+    the two terms on the second line cancel, while
+    the third line reduces to a single vertical derivative, so it becomes:}
+  %
+    D^T & =\frac{1}{e_1 \,e_2 \,e_3 }\left[ {\left. {\;\;\;\frac{\partial }{\partial i}\left( {\frac{e_2 \,e_3 }{e_1 }A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s -e_2 \,\sigma_1 \,A^{lT}\;\frac{\partial T}{\partial s}} \right)} \right|_s } \right. \\
+    & \qquad \qquad \quad \shoveright{ \left. {+\frac{\partial }{\partial s}\left( {-e_2 \,\sigma_1 \,A^{lT}\;\left. {\frac{\partial T}{\partial i}} \right|_s +A^{lT}\frac{e_1 \,e_2 }{e_3 }\;\left( {\varepsilon +\sigma_1 ^2} \right)\frac{\partial T}{\partial s}} \right)\;\;\;} \right]} \\
+    %
+    \intertext{In other words, the horizontal/vertical Laplacian operator in the ($i$,$s$) plane takes the following form:}
+  \end{array}
+  } \\
+  %
+  {\frac{1}{e_1\,e_2\,e_3}}
+  \left( {{
+  \begin{array}{*{30}c}
+    {\left. {\frac{\partial \left( {e_2 e_3 \bullet } \right)}{\partial i}} \right|_s } \hfill \\
+    {\frac{\partial \left( {e_1 e_2 \bullet } \right)}{\partial s}} \hfill \\
+  \end{array}}}
+  \right)
+  \cdot \left[ {A^{lT}
+  \left( {{
+  \begin{array}{*{30}c}
+    {1} \hfill & {-\sigma_1 } \hfill \\
+    {-\sigma_1} \hfill & {\varepsilon + \sigma_1^2} \hfill \\
+  \end{array}
+  }} \right)
+  \cdot
+  \left( {{
+  \begin{array}{*{30}c}
+    {\frac{1}{e_1 }\;\left. {\frac{\partial \bullet }{\partial i}} \right|_s } \hfill \\
+    {\frac{1}{e_3 }\;\frac{\partial \bullet }{\partial s}} \hfill \\
+  \end{array}
+  }}       \right) \left( T \right)} \right]
+\end{align*}
+%\addtocounter{equation}{-2}
+
+%% =================================================================================================
+\section{Iso/Diapycnal $2^{nd}$ order tracer diffusive operators}
+\label{sec:DIFFOPERS_2}
+
+%% =================================================================================================
+\subsubsection*{In z-coordinates}
+
+The iso/diapycnal diffusive tensor $\textbf {A}_{\textbf I}$ expressed in
+the ($i$,$j$,$k$) curvilinear coordinate system in which
+the equations of the ocean circulation model are formulated,
+takes the following form \citep{redi_JPO82}:
+
+\begin{equation}
+  \label{eq:DIFFOPERS_3}
+  \textbf {A}_{\textbf I} = \frac{A^{lT}}{\left( {1+a_1 ^2+a_2 ^2} \right)}
+  \left[ {{
+        \begin{array}{*{20}c}
+          {1+a_2 ^2 +\varepsilon a_1 ^2} \hfill & {-a_1 a_2 (1-\varepsilon)} \hfill & {-a_1 (1-\varepsilon) } \hfill \\
+          {-a_1 a_2 (1-\varepsilon) } \hfill & {1+a_1 ^2 +\varepsilon a_2 ^2} \hfill & {-a_2 (1-\varepsilon)} \hfill \\
+          {-a_1 (1-\varepsilon)} \hfill & {-a_2 (1-\varepsilon)} \hfill & {\varepsilon +a_1 ^2+a_2 ^2} \hfill \\
+        \end{array}
+      }} \right]
+\end{equation}
+where ($a_1$, $a_2$) are $(-1) \times$ the isopycnal slopes in
+($\textbf{i}$, $\textbf{j}$) directions, relative to geopotentials (or
+equivalently the slopes of the geopotential surfaces in the isopycnal
+coordinate framework):
+\[
+  a_1 =\frac{e_3 }{e_1 }\left( {\frac{\partial \rho }{\partial i}} \right)\left( {\frac{\partial \rho }{\partial k}} \right)^{-1}
+  \qquad , \qquad
+  a_2 =\frac{e_3 }{e_2 }\left( {\frac{\partial \rho }{\partial j}}
+  \right)\left( {\frac{\partial \rho }{\partial k}} \right)^{-1}
+\]
+and, as before, $\epsilon = A^{vT} / A^{lT}$.
+
+In practice, $\epsilon$ is small and isopycnal slopes are generally less than $10^{-2}$ in the ocean,
+so $\textbf {A}_{\textbf I}$ can be simplified appreciably \citep{cox_OM87}. Keeping leading order terms\footnote{Apart from the (1,0)
+and (0,1) elements which are set to zero. See \citet{griffies_bk04}, section 14.1.4.1 for a discussion of this point.}:
+\begin{subequations}
+  \label{eq:DIFFOPERS_4}
+  \begin{equation}
+    \label{eq:DIFFOPERS_4a}
+    {\textbf{A}_{\textbf{I}}} \approx A^{lT}\;\Re\;\text{where} \;\Re =
+    \left[ {{
+          \begin{array}{*{20}c}
+            1 \hfill & 0 \hfill & {-a_1 } \hfill \\
+            0 \hfill & 1 \hfill & {-a_2 } \hfill \\
+            {-a_1 } \hfill & {-a_2 } \hfill & {\varepsilon +a_1 ^2+a_2 ^2} \hfill \\
+          \end{array}
+        }} \right],
+  \end{equation}
+  and the iso/dianeutral diffusive operator in $z$-coordinates is then
+  \begin{equation}
+    \label{eq:DIFFOPERS_4b}
+    D^T = \left. \nabla \right|_z \cdot
+    \left[ A^{lT} \;\Re \cdot \left. \nabla \right|_z T  \right]. \\
+  \end{equation}
+\end{subequations}
+
+Physically, the full tensor \autoref{eq:DIFFOPERS_3} represents strong isoneutral diffusion on a plane parallel to
+the isoneutral surface and weak dianeutral diffusion perpendicular to this plane.
+However,
+the approximate `weak-slope' tensor \autoref{eq:DIFFOPERS_4a} represents strong diffusion along the isoneutral surface,
+with weak \emph{vertical} diffusion -- the principal axes of the tensor are no longer orthogonal.
+This simplification also decouples the ($i$,$z$) and ($j$,$z$) planes of the tensor.
+The weak-slope operator therefore takes the same form, \autoref{eq:DIFFOPERS_4}, as \autoref{eq:DIFFOPERS_2},
+the diffusion operator for geopotential diffusion written in non-orthogonal $i,j,s$-coordinates.
+Written out explicitly,
+
+\begin{multline}
+  \label{eq:DIFFOPERS_ldfiso}
+  D^T=\frac{1}{e_1 e_2 }\left\{
+    {\;\frac{\partial }{\partial i}\left[ {A_h \left( {\frac{e_2}{e_1}\frac{\partial T}{\partial i}-a_1 \frac{e_2}{e_3}\frac{\partial T}{\partial k}} \right)} \right]}
+    {+\frac{\partial}{\partial j}\left[ {A_h \left( {\frac{e_1}{e_2}\frac{\partial T}{\partial j}-a_2 \frac{e_1}{e_3}\frac{\partial T}{\partial k}} \right)} \right]\;} \right\} \\
+  \shoveright{+\frac{1}{e_3 }\frac{\partial }{\partial k}\left[ {A_h \left( {-\frac{a_1 }{e_1 }\frac{\partial T}{\partial i}-\frac{a_2 }{e_2 }\frac{\partial T}{\partial j}+\frac{\left( {a_1 ^2+a_2 ^2+\varepsilon} \right)}{e_3 }\frac{\partial T}{\partial k}} \right)} \right]}. \\
+\end{multline}
+
+The isopycnal diffusion operator \autoref{eq:DIFFOPERS_4},
+\autoref{eq:DIFFOPERS_ldfiso} conserves tracer quantity and dissipates its square.
+As \autoref{eq:DIFFOPERS_4} is the divergence of a flux, the demonstration of the first property is trivial, providing that the flux normal to the boundary is zero
+(as it is when $A_h$ is zero at the boundary). Let us demonstrate the second one:
+\[
+  \iiint\limits_D T\;\nabla .\left( {\textbf{A}}_{\textbf{I}} \nabla T \right)\,dv
+  = -\iiint\limits_D \nabla T\;.\left( {\textbf{A}}_{\textbf{I}} \nabla T \right)\,dv,
+\]
+and since
+\begin{align*}
+  {
+  \begin{array}{*{20}l}
+    \nabla T\;.\left( {{\mathrm {\mathbf A}}_{\mathrm {\mathbf I}} \nabla T}
+    \right)&=A^{lT}\left[ {\left( {\frac{\partial T}{\partial i}} \right)^2-2a_1
+             \frac{\partial T}{\partial i}\frac{\partial T}{\partial k}+\left(
+             {\frac{\partial T}{\partial j}} \right)^2} \right. \\
+           &\qquad \qquad \qquad
+             { \left. -\,{2a_2 \frac{\partial T}{\partial j}\frac{\partial T}{\partial k}+\left( {a_1 ^2+a_2 ^2+\varepsilon} \right)\left( {\frac{\partial T}{\partial k}} \right)^2} \right]} \\
+           &=A_h \left[ {\left( {\frac{\partial T}{\partial i}-a_1 \frac{\partial
+             T}{\partial k}} \right)^2+\left( {\frac{\partial T}{\partial
+             j}-a_2 \frac{\partial T}{\partial k}} \right)^2}
+             +\varepsilon \left(\frac{\partial T}{\partial k}\right) ^2\right]      \\
+           & \geq 0 .
+  \end{array}
+             }
+\end{align*}
+%\addtocounter{equation}{-1}
+the property becomes obvious.
+
+%% =================================================================================================
+\subsubsection*{In generalized vertical coordinates}
+
+Because the weak-slope operator \autoref{eq:DIFFOPERS_4},
+\autoref{eq:DIFFOPERS_ldfiso} is decoupled in the ($i$,$z$) and ($j$,$z$) planes,
+it may be transformed into generalized $s$-coordinates in the same way as
+\autoref{sec:DIFFOPERS_1} was transformed into \autoref{sec:DIFFOPERS_2}.
+The resulting operator then takes the simple form
+
+\begin{equation}
+  \label{eq:DIFFOPERS_ldfiso_s}
+  D^T = \left. \nabla \right|_s \cdot
+  \left[ A^{lT} \;\Re \cdot \left. \nabla \right|_s T  \right] \\
+  \;\;\text{where} \;\Re =\left( {{
+        \begin{array}{*{20}c}
+          1 \hfill & 0 \hfill & {-r _1 } \hfill \\
+          0 \hfill & 1 \hfill & {-r _2 } \hfill \\
+          {-r _1 } \hfill & {-r _2 } \hfill & {\varepsilon +r _1
+                                              ^2+r _2 ^2} \hfill \\
+        \end{array}
+      }} \right),
+\end{equation}
+
+where ($r_1$, $r_2$) are $(-1)\times$ the isopycnal slopes in ($\textbf{i}$, $\textbf{j}$) directions,
+relative to $s$-coordinate surfaces (or equivalently the slopes of the
+$s$-coordinate surfaces in the isopycnal coordinate framework):
+\[
+  r_1 =\frac{e_3 }{e_1 }\left( {\frac{\partial \rho }{\partial i}} \right)\left( {\frac{\partial \rho }{\partial s}} \right)^{-1}
+  \qquad , \qquad
+  r_2 =\frac{e_3 }{e_2 }\left( {\frac{\partial \rho }{\partial j}}
+  \right)\left( {\frac{\partial \rho }{\partial s}} \right)^{-1}.
+\]
+
+To prove \autoref{eq:DIFFOPERS_ldfiso_s} by direct re-expression of \autoref{eq:DIFFOPERS_ldfiso} is straightforward, but laborious.
+An easier way is first to note (by reversing the derivation of \autoref{sec:DIFFOPERS_2} from \autoref{sec:DIFFOPERS_1} ) that
+the weak-slope operator may be \emph{exactly} reexpressed in non-orthogonal $i,j,\rho$-coordinates as
+
+\begin{equation}
+  \label{eq:DIFFOPERS_5}
+  D^T = \left. \nabla \right|_\rho \cdot
+  \left[ A^{lT} \;\Re \cdot \left. \nabla \right|_\rho T  \right] \\
+  \;\;\text{where} \;\Re =\left( {{
+        \begin{array}{*{20}c}
+          1 \hfill & 0 \hfill &0 \hfill \\
+          0 \hfill & 1 \hfill & 0 \hfill \\
+          0 \hfill & 0 \hfill & \varepsilon \hfill \\
+        \end{array}
+      }} \right).
+\end{equation}
+Then direct transformation from $i,j,\rho$-coordinates to $i,j,s$-coordinates gives
+\autoref{eq:DIFFOPERS_ldfiso_s} immediately.
+
+Note that the weak-slope approximation is only made in transforming from
+the (rotated,orthogonal) isoneutral axes to the non-orthogonal $i,j,\rho$-coordinates.
+The further transformation into $i,j,s$-coordinates is exact, whatever the steepness of the $s$-surfaces,
+in the same way as the transformation of horizontal/vertical Laplacian diffusion in $z$-coordinates in
+\autoref{sec:DIFFOPERS_1} onto $s$-coordinates is exact, however steep the $s$-surfaces.
+
+%% =================================================================================================
+\section{Lateral/Vertical momentum diffusive operators}
+\label{sec:DIFFOPERS_3}
+
+The second order momentum diffusion operator (Laplacian) in $z$-coordinates is found by
+applying \autoref{eq:MB_lap_vector}, the expression for the Laplacian of a vector,
+to the horizontal velocity vector:
+\begin{align*}
+  \Delta {\textbf{U}}_h
+  &=\nabla \left( {\nabla \cdot {\textbf{U}}_h } \right)-
+    \nabla \times \left( {\nabla \times {\textbf{U}}_h } \right) \\ \\
+  &=\left( {{
+    \begin{array}{*{20}c}
+      {\frac{1}{e_1 }\frac{\partial \chi }{\partial i}} \hfill \\
+      {\frac{1}{e_2 }\frac{\partial \chi }{\partial j}} \hfill \\
+      {\frac{1}{e_3 }\frac{\partial \chi }{\partial k}} \hfill \\
+    \end{array}
+  }} \right)
+  -\left( {{
+  \begin{array}{*{20}c}
+    {\frac{1}{e_2 }\frac{\partial \zeta }{\partial j}-\frac{1}{e_3
+    }\frac{\partial }{\partial k}\left( {\frac{1}{e_3 }\frac{\partial
+    u}{\partial k}} \right)} \hfill \\
+    {\frac{1}{e_3 }\frac{\partial }{\partial k}\left( {-\frac{1}{e_3
+    }\frac{\partial v}{\partial k}} \right)-\frac{1}{e_1 }\frac{\partial \zeta
+    }{\partial i}} \hfill \\
+    {\frac{1}{e_1 e_2 }\left[ {\frac{\partial }{\partial i}\left( {\frac{e_2
+    }{e_3 }\frac{\partial u}{\partial k}} \right)-\frac{\partial }{\partial
+    j}\left( {-\frac{e_1 }{e_3 }\frac{\partial v}{\partial k}} \right)} \right]}
+    \hfill \\
+  \end{array}
+  }} \right) \\ \\
+  &=\left( {{
+    \begin{array}{*{20}c}
+      {\frac{1}{e_1 }\frac{\partial \chi }{\partial i}-\frac{1}{e_2 }\frac{\partial \zeta }{\partial j}} \\
+      {\frac{1}{e_2 }\frac{\partial \chi }{\partial j}+\frac{1}{e_1 }\frac{\partial \zeta }{\partial i}} \\
+      0 \\
+    \end{array}
+  }} \right)
+  +\frac{1}{e_3 }
+  \left( {{
+  \begin{array}{*{20}c}
+    {\frac{\partial }{\partial k}\left( {\frac{1}{e_3 }\frac{\partial u}{\partial k}} \right)} \\
+    {\frac{\partial }{\partial k}\left( {\frac{1}{e_3 }\frac{\partial v}{\partial k}} \right)} \\
+    {\frac{\partial \chi }{\partial k}-\frac{1}{e_1 e_2 }\left( {\frac{\partial ^2\left( {e_2 \,u} \right)}{\partial i\partial k}+\frac{\partial ^2\left( {e_1 \,v} \right)}{\partial j\partial k}} \right)} \\
+  \end{array}
+  }} \right)
+\end{align*}
+Using \autoref{eq:MB_div}, the definition of the horizontal divergence,
+the third component of the second vector is obviously zero and thus :
+\[
+  \Delta {\textbf{U}}_h = \nabla _h \left( \chi \right) - \nabla _h \times \left( \zeta \textbf{k} \right) + \frac {1}{e_3 } \frac {\partial }{\partial k} \left( {\frac {1}{e_3 } \frac{\partial {\textbf{ U}}_h }{\partial k}} \right) .
+\]
+
+Note that this operator ensures a full separation between
+the vorticity and horizontal divergence fields (see \autoref{apdx:INVARIANTS}).
+It is only equal to a Laplacian applied to each component in Cartesian coordinates, not on the sphere.
+
+The horizontal/vertical second order (Laplacian type) operator used to diffuse horizontal momentum in
+the $z$-coordinate therefore takes the following form:
+\begin{equation}
+  \label{eq:DIFFOPERS_Lap_U}
+  {
+    \textbf{D}}^{\textbf{U}} =
+  \nabla _h \left( {A^{lm}\;\chi } \right)
+  - \nabla _h \times \left( {A^{lm}\;\zeta \;{\textbf{k}}} \right)
+  + \frac{1}{e_3 }\frac{\partial }{\partial k}\left( {\frac{A^{vm}\;}{e_3 }
+      \frac{\partial {\mathrm {\mathbf U}}_h }{\partial k}} \right) , \\
+\end{equation}
+that is, in expanded form:
+\begin{align*}
+  D^{\textbf{U}}_u
+  & = \frac{1}{e_1} \frac{\partial \left( {A^{lm}\chi   } \right)}{\partial i}
+    -\frac{1}{e_2} \frac{\partial \left( {A^{lm}\zeta } \right)}{\partial j}
+    +\frac{1}{e_3} \frac{\partial }{\partial k} \left( \frac{A^{vm}}{e_3} \frac{\partial u}{\partial k} \right)   ,   \\
+  D^{\textbf{U}}_v
+  & = \frac{1}{e_2 }\frac{\partial \left( {A^{lm}\chi   } \right)}{\partial j}
+    +\frac{1}{e_1 }\frac{\partial \left( {A^{lm}\zeta } \right)}{\partial i}
+    +\frac{1}{e_3} \frac{\partial }{\partial k} \left( \frac{A^{vm}}{e_3} \frac{\partial v}{\partial k} \right) .
+\end{align*}
+
+Note Bene: introducing a rotation in \autoref{eq:DIFFOPERS_Lap_U} does not lead to
+a useful expression for the iso/diapycnal Laplacian operator in the $z$-coordinate.
+Similarly, we did not found an expression of practical use for
+the geopotential horizontal/vertical Laplacian operator in the $s$-coordinate.
+Generally, \autoref{eq:DIFFOPERS_Lap_U} is used in both $z$- and $s$-coordinate systems,
+that is a Laplacian diffusion is applied on momentum along the coordinate directions.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_invariants.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_invariants.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_invariants.tex	(revision 14097)
@@ -0,0 +1,1483 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Discrete Invariants of the Equations}
+\label{apdx:INVARIANTS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%%%  Appendix put in cmtgm as it has not been updated for \zstar and s coordinate
+%I'm writting this appendix. It will be available in a forthcoming release of the documentation
+
+%\cmtgm{
+
+%% =================================================================================================
+\section{Introduction / Notations}
+\label{sec:INVARIANTS_0}
+
+Notation used in this appendix in the demonstations:
+
+fluxes at the faces of a $T$-box:
+\[
+  U = e_{2u}\,e_{3u}\; u  \qquad  V = e_{1v}\,e_{3v}\; v  \qquad W = e_{1w}\,e_{2w}\; \omega
+\]
+
+volume of cells at $u$-, $v$-, and $T$-points:
+\[
+  b_u = e_{1u}\,e_{2u}\,e_{3u}  \qquad  b_v = e_{1v}\,e_{2v}\,e_{3v}  \qquad b_t = e_{1t}\,e_{2t}\,e_{3t}
+\]
+
+partial derivative notation: $\partial_\bullet = \frac{\partial}{\partial \bullet}$
+
+$dv=e_1\,e_2\,e_3 \,di\,dj\,dk$  is the volume element, with only $e_3$ that depends on time.
+$D$ and $S$ are the ocean domain volume and surface, respectively.
+No wetting/drying is allow (\ie\ $\frac{\partial S}{\partial t} = 0$).
+Let $k_s$ and $k_b$ be the ocean surface and bottom, resp.
+(\ie\ $s(k_s) = \eta$ and $s(k_b)=-H$, where $H$ is the bottom depth).
+\begin{flalign*}
+  z(k) = \eta - \int\limits_{\tilde{k}=k}^{\tilde{k}=k_s}  e_3(\tilde{k}) \;d\tilde{k}
+  = \eta - \int\limits_k^{k_s}  e_3 \;d\tilde{k}
+\end{flalign*}
+
+Continuity equation with the above notation:
+\[
+  \frac{1}{e_{3t}} \partial_t (e_{3t})+ \frac{1}{b_t}  \biggl\{  \delta_i [U] + \delta_j [V] + \delta_k [W] \biggr\} = 0
+\]
+
+A quantity, $Q$ is conserved when its domain averaged time change is zero, that is when:
+\[
+  \partial_t \left( \int_D{ Q\;dv } \right) =0
+\]
+Noting that the coordinate system used ....  blah blah
+\[
+  \partial_t \left( \int_D {Q\;dv} \right) =  \int_D { \partial_t \left( e_3 \, Q \right) e_1e_2\;di\,dj\,dk }
+  =  \int_D { \frac{1}{e_3} \partial_t \left( e_3 \, Q \right) dv } =0
+\]
+equation of evolution of $Q$ written as
+the time evolution of the vertical content of $Q$ like for tracers, or momentum in flux form,
+the quadratic quantity $\frac{1}{2}Q^2$ is conserved when:
+\begin{flalign*}
+  \partial_t \left(   \int_D{ \frac{1}{2} \,Q^2\;dv }   \right)
+  =&  \int_D{ \frac{1}{2} \partial_t \left( \frac{1}{e_3}\left( e_3 \, Q \right)^2 \right) e_1e_2\;di\,dj\,dk } \\
+  =&  \int_D {         Q   \;\partial_t\left( e_3 \, Q \right) e_1e_2\;di\,dj\,dk }
+  -  \int_D { \frac{1}{2} Q^2 \,\partial_t  (e_3) \;e_1e_2\;di\,dj\,dk } \\
+\end{flalign*}
+that is in a more compact form :
+\begin{flalign}
+  \label{eq:INVARIANTS_Q2_flux}
+  \partial_t \left( \int_D {\frac{1}{2} Q^2\;dv} \right)
+  =&                   \int_D { \frac{Q}{e_3}  \partial_t \left( e_3 \, Q \right) dv }
+  -   \frac{1}{2} \int_D {  \frac{Q^2}{e_3} \partial_t (e_3) \;dv }
+\end{flalign}
+equation of evolution of $Q$ written as the time evolution of $Q$ like for momentum in vector invariant form,
+the quadratic quantity $\frac{1}{2}Q^2$ is conserved when:
+\begin{flalign*}
+  \partial_t \left( \int_D {\frac{1}{2} Q^2\;dv} \right)
+  =&  \int_D { \frac{1}{2} \partial_t \left( e_3 \, Q^2 \right) \;e_1e_2\;di\,dj\,dk } \\
+  =& \int_D {         Q      \partial_t Q  \;e_1e_2e_3\;di\,dj\,dk }
+  +  \int_D { \frac{1}{2} Q^2 \, \partial_t e_3  \;e_1e_2\;di\,dj\,dk } \\
+\end{flalign*}
+that is in a more compact form:
+\begin{flalign}
+  \label{eq:INVARIANTS_Q2_vect}
+  \partial_t \left( \int_D {\frac{1}{2} Q^2\;dv} \right)
+  =& \int_D {         Q   \,\partial_t Q  \;dv }
+  +   \frac{1}{2} \int_D { \frac{1}{e_3} Q^2 \partial_t e_3 \;dv }
+\end{flalign}
+
+%% =================================================================================================
+\section{Continuous conservation}
+\label{sec:INVARIANTS_1}
+
+The discretization of pimitive equation in $s$-coordinate (\ie\ time and space varying vertical coordinate)
+must be chosen so that the discrete equation of the model satisfy integral constrains on energy and enstrophy.
+
+Let us first establish those constraint in the continuous world.
+The total energy (\ie\ kinetic plus potential energies) is conserved:
+\begin{flalign}
+  \label{eq:INVARIANTS_Tot_Energy}
+  \partial_t \left( \int_D \left( \frac{1}{2} {\textbf{U}_h}^2 +  \rho \, g \, z \right) \;dv \right)  = & 0
+\end{flalign}
+under the following assumptions: no dissipation, no forcing (wind, buoyancy flux, atmospheric pressure variations),
+mass conservation, and closed domain.
+
+This equation can be transformed to obtain several sub-equalities.
+The transformation for the advection term depends on whether the vector invariant form or
+the flux form is used for the momentum equation.
+Using \autoref{eq:INVARIANTS_Q2_vect} and introducing \autoref{eq:SCOORD_dyn_vect} in
+\autoref{eq:INVARIANTS_Tot_Energy} for the former form and
+using \autoref{eq:INVARIANTS_Q2_flux} and introducing \autoref{eq:SCOORD_dyn_flux} in
+\autoref{eq:INVARIANTS_Tot_Energy} for the latter form leads to:
+
+% \label{eq:INVARIANTS_E_tot}
+advection term (vector invariant form):
+\[
+  % \label{eq:INVARIANTS_E_tot_vect_vor_1}
+  \int\limits_D  \zeta \; \left( \textbf{k} \times \textbf{U}_h  \right) \cdot \textbf{U}_h  \;  dv   = 0   \\
+\]
+\[
+  % \label{eq:INVARIANTS_E_tot_vect_adv_1}
+  \int\limits_D  \textbf{U}_h \cdot \nabla_h \left( \frac{{\textbf{U}_h}^2}{2} \right)     dv
+  + \int\limits_D  \textbf{U}_h \cdot \nabla_z \textbf{U}_h  \;dv
+  -  \int\limits_D { \frac{{\textbf{U}_h}^2}{2} \frac{1}{e_3} \partial_t e_3 \;dv }   = 0
+\]
+advection term (flux form):
+\[
+  % \label{eq:INVARIANTS_E_tot_flux_metric}
+  \int\limits_D  \frac{1} {e_1 e_2 } \left( v \,\partial_i e_2 - u \,\partial_j e_1  \right)\;
+  \left(  \textbf{k} \times \textbf{U}_h  \right) \cdot \textbf{U}_h  \;  dv   = 0
+\]
+\[
+  % \label{eq:INVARIANTS_E_tot_flux_adv}
+  \int\limits_D \textbf{U}_h \cdot     \left(                 {{
+        \begin{array} {*{20}c}
+          \nabla \cdot \left( \textbf{U}\,u \right) \hfill \\
+          \nabla \cdot \left( \textbf{U}\,v \right) \hfill
+        \end{array}}
+    }           \right)   \;dv
+  +   \frac{1}{2} \int\limits_D {  {\textbf{U}_h}^2 \frac{1}{e_3} \partial_t e_3 \;dv } =\;0
+\]
+coriolis term
+\[
+  % \label{eq:INVARIANTS_E_tot_cor}
+  \int\limits_D  f   \; \left( \textbf{k} \times \textbf{U}_h  \right) \cdot \textbf{U}_h  \;  dv   = 0
+\]
+pressure gradient:
+\[
+  % \label{eq:INVARIANTS_E_tot_pg_1}
+  - \int\limits_D  \left. \nabla p \right|_z \cdot \textbf{U}_h \;dv
+  = - \int\limits_D \nabla \cdot \left( \rho \,\textbf {U} \right)\;g\;z\;\;dv
+  + \int\limits_D g\, \rho \; \partial_t z  \;dv
+\]
+
+where $\nabla_h = \left. \nabla \right|_k$ is the gradient along the $s$-surfaces.
+
+blah blah....
+
+The prognostic ocean dynamics equation can be summarized as follows:
+\[
+  \text{NXT} = \dbinom	{\text{VOR} + \text{KEG} + \text {ZAD} }
+  {\text{COR} + \text{ADV}                       }
+  + \text{HPG} + \text{SPG} + \text{LDF} + \text{ZDF}
+\]
+
+Vector invariant form:
+% \label{eq:INVARIANTS_E_tot_vect}
+\[
+  % \label{eq:INVARIANTS_E_tot_vect_vor_2}
+  \int\limits_D   \textbf{U}_h \cdot \text{VOR} \;dv   = 0
+\]
+\[
+  % \label{eq:INVARIANTS_E_tot_vect_adv_2}
+  \int\limits_D  \textbf{U}_h \cdot \text{KEG}  \;dv
+  + \int\limits_D  \textbf{U}_h \cdot \text{ZAD}  \;dv
+  -  \int\limits_D { \frac{{\textbf{U}_h}^2}{2} \frac{1}{e_3} \partial_t e_3 \;dv }   = 0
+\]
+\[
+  % \label{eq:INVARIANTS_E_tot_pg_2}
+  - \int\limits_D  \textbf{U}_h \cdot (\text{HPG}+ \text{SPG}) \;dv
+  = - \int\limits_D \nabla \cdot \left( \rho \,\textbf {U} \right)\;g\;z\;\;dv
+  + \int\limits_D g\, \rho \; \partial_t z  \;dv
+\]
+
+Flux form:
+\begin{subequations}
+  \label{eq:INVARIANTS_E_tot_flux}
+  \[
+    % \label{eq:INVARIANTS_E_tot_flux_metric_2}
+    \int\limits_D  \textbf{U}_h \cdot \text {COR} \;  dv   = 0
+  \]
+  \[
+    % \label{eq:INVARIANTS_E_tot_flux_adv_2}
+    \int\limits_D \textbf{U}_h \cdot \text{ADV}   \;dv
+    +   \frac{1}{2} \int\limits_D {  {\textbf{U}_h}^2 \frac{1}{e_3} \partial_t e_3  \;dv } =\;0
+  \]
+  \begin{equation}
+    \label{eq:INVARIANTS_E_tot_pg_3}
+    - \int\limits_D  \textbf{U}_h \cdot (\text{HPG}+ \text{SPG}) \;dv
+    = - \int\limits_D \nabla \cdot \left( \rho \,\textbf {U} \right)\;g\;z\;\;dv
+    + \int\limits_D g\, \rho \; \partial_t  z  \;dv
+  \end{equation}
+\end{subequations}
+
+\autoref{eq:INVARIANTS_E_tot_pg_3} is the balance between the conversion KE to PE and PE to KE.
+Indeed the left hand side of \autoref{eq:INVARIANTS_E_tot_pg_3} can be transformed as follows:
+\begin{flalign*}
+  \partial_t  \left( \int\limits_D { \rho \, g \, z  \;dv} \right)
+  &= + \int\limits_D \frac{1}{e_3} \partial_t (e_3\,\rho) \;g\;z\;\;dv
+  +  \int\limits_D g\, \rho \; \partial_t z  \;dv   &&&\\
+  &= - \int\limits_D \nabla \cdot \left( \rho \,\textbf {U} \right)\;g\;z\;\;dv
+  + \int\limits_D g\, \rho \; \partial_t z \;dv   &&&\\
+  &= + \int\limits_D  \rho \,g \left( \textbf {U}_h \cdot \nabla_h z + \omega \frac{1}{e_3} \partial_k z \right)  \;dv
+  + \int\limits_D g\, \rho \; \partial_t z \;dv   &&&\\
+  &= + \int\limits_D  \rho \,g \left( \omega + \partial_t z + \textbf {U}_h \cdot \nabla_h z  \right)  \;dv  &&&\\
+  &=+  \int\limits_D g\, \rho \; w \; dv   &&&\\
+\end{flalign*}
+where the last equality is obtained by noting that the brackets is exactly the expression of $w$,
+the vertical velocity referenced to the fixe $z$-coordinate system (see \autoref{eq:SCOORD_w_s}).
+
+The left hand side of \autoref{eq:INVARIANTS_E_tot_pg_3} can be transformed as follows:
+\begin{flalign*}
+  - \int\limits_D  \left. \nabla p \right|_z & \cdot \textbf{U}_h \;dv
+  = - \int\limits_D  \left( \nabla_h p + \rho \, g \nabla_h z \right) \cdot \textbf{U}_h \;dv   &&&\\
+  \allowdisplaybreaks
+  &= - \int\limits_D  \nabla_h  p \cdot \textbf{U}_h \;dv   - \int\limits_D  \rho \, g \, \nabla_h z \cdot \textbf{U}_h \;dv   &&&\\
+  \allowdisplaybreaks
+  &= +\int\limits_D p \,\nabla_h \cdot \textbf{U}_h \;dv   + \int\limits_D  \rho \, g \left( \omega - w + \partial_t z \right) \;dv   &&&\\
+  \allowdisplaybreaks
+  &= -\int\limits_D p \left( \frac{1}{e_3} \partial_t e_3 + \frac{1}{e_3} \partial_k \omega  \right) \;dv
+  +\int\limits_D  \rho \, g \left( \omega - w + \partial_t z \right) \;dv   &&&\\
+  \allowdisplaybreaks
+  &= -\int\limits_D \frac{p}{e_3} \partial_t e_3  \;dv
+  +\int\limits_D \frac{1}{e_3} \partial_k p\; \omega \;dv
+  +\int\limits_D  \rho \, g \left( \omega - w + \partial_t z \right) \;dv   &&&\\
+  &= -\int\limits_D \frac{p}{e_3} \partial_t e_3  \;dv
+  -\int\limits_D \rho \, g \, \omega \;dv
+  +\int\limits_D  \rho \, g \left( \omega - w + \partial_t z \right) \;dv   &&&\\
+  &= - \int\limits_D \frac{p}{e_3} \partial_t e_3 \; \;dv
+  - \int\limits_D  \rho \, g \, w \;dv
+  + \int\limits_D   \rho \, g \, \partial_t z \;dv   &&&\\
+  \allowdisplaybreaks
+  \intertext{introducing the hydrostatic balance $\partial_k p=-\rho \,g\,e_3$ in the last term,
+    it becomes:}
+  &= - \int\limits_D \frac{p}{e_3} \partial_t e_3 \;dv
+  - \int\limits_D  \rho \, g \, w \;dv
+  - \int\limits_D  \frac{1}{e_3} \partial_k p\, \partial_t z \;dv   &&&\\
+  &= - \int\limits_D \frac{p}{e_3} \partial_t e_3 \;dv
+  - \int\limits_D  \rho \, g \, w \;dv
+  + \int\limits_D \,\frac{p}{e_3}\partial_t ( \partial_k z )  dv   &&&\\
+  %
+  &= - \int\limits_D  \rho \, g \, w \;dv   &&&\\
+\end{flalign*}
+
+%gm comment
+\cmtgm{
+The last equality comes from the following equation,
+\begin{flalign*}
+  \int\limits_D p \frac{1}{e_3} \frac{\partial e_3}{\partial t}\; \;dv
+  = \int\limits_D   \rho \, g \, \frac{\partial z }{\partial t} \;dv \quad,
+\end{flalign*}
+that can be demonstrated as follows:
+
+\begin{flalign*}
+  \int\limits_D   \rho \, g \, \frac{\partial z }{\partial t} \;dv
+  &= \int\limits_D    \rho \, g \, \frac{\partial \eta}{\partial t} \;dv
+  -  \int\limits_D    \rho \, g \, \frac{\partial}{\partial t} \left(  \int\limits_k^{k_s}  e_3 \;d\tilde{k} \right) \;dv   &&&\\
+  &= \int\limits_D    \rho \, g \, \frac{\partial \eta}{\partial t} \;dv
+  -  \int\limits_D    \rho \, g    \left(  \int\limits_k^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k} \right) \;dv   &&&\\
+  %
+  \allowdisplaybreaks
+  \intertext{The second term of the right hand side can be transformed by applying the integration by part rule:
+    $\left[ a\,b \right]_{k_b}^{k_s} = \int_{k_b}^{k_s}  a\,\frac{\partial b}{\partial k}       \;dk
+    + \int_{k_b}^{k_s}      \frac{\partial a}{\partial k} \,b \;dk $
+    to the following function: $a=  \int_k^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k}$
+    and $b=  \int_k^{k_s}  \rho \, e_3 \;d\tilde{k}$
+    (note that $\frac{\partial}{\partial k} \left(  \int_k^{k_s}  a \;d\tilde{k}  \right) = - a$ as $k$ is the lower bound of the integral).
+    This leads to:  }
+\end{flalign*}
+\begin{flalign*}
+  &\left[ \int\limits_{k}^{k_s}  \frac{\partial e_3}{\partial t} \,dk \cdot \int\limits_{k}^{k_s}  \rho \, e_3 \,dk   \right]_{k_b}^{k_s}
+  =-\int\limits_{k_b}^{k_s} \left(  \int\limits_k^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k} \right)  \rho \,e_3 \;dk
+  -\int\limits_{k_b}^{k_s}  \frac{\partial e_3}{\partial t}  \left(  \int\limits_k^{k_s}  \rho \, e_3 \;d\tilde{k} \right)   dk  &&&\\
+  \allowdisplaybreaks
+  \intertext{Noting that $\frac{\partial \eta}{\partial t}
+    = \frac{\partial}{\partial t}  \left( \int_{k_b}^{k_s}   e_3  \;d\tilde{k}  \right)
+    = \int_{k_b}^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k}$
+    and
+    $p(k) = \int_k^{k_s}  \rho \,g \, e_3 \;d\tilde{k} $,
+    but also that $\frac{\partial \eta}{\partial t}$ does not depends on $k$, it comes:
+  }
+  & - \int\limits_{k_b}^{k_s}  \rho \, \frac{\partial \eta}{\partial t} \, e_3 \;dk
+  = - \int\limits_{k_b}^{k_s} \left(  \int\limits_k^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k} \right)   \, \rho \, g   e_3\;dk
+  - \int\limits_{k_b}^{k_s}  \frac{\partial e_3}{\partial t} \frac{p}{g}         \;dk       &&&\\
+\end{flalign*}
+Mutliplying by $g$ and integrating over the $(i,j)$ domain it becomes:
+\begin{flalign*}
+  \int\limits_D  \rho \, g \, \left(  \int\limits_k^{k_s}  \frac{\partial e_3}{\partial t} \;d\tilde{k} \right)    \;dv
+  =  \int\limits_D  \rho \, g \, \frac{\partial \eta}{\partial t} dv
+  - \int\limits_D  \frac{p}{e_3}\frac{\partial e_3}{\partial t}         \;dv
+\end{flalign*}
+Using this property, we therefore have:
+\begin{flalign*}
+  \int\limits_D   \rho \, g \, \frac{\partial z }{\partial t} \;dv
+  &= \int\limits_D    \rho \, g \, \frac{\partial \eta}{\partial t}   \;dv
+  - \left(  \int\limits_D  \rho \, g \, \frac{\partial \eta}{\partial t} dv
+    - \int\limits_D  \frac{p}{e_3}\frac{\partial e_3}{\partial t}   \;dv  \right)    &&&\\
+  %
+  &=\int\limits_D \frac{p}{e_3} \frac{\partial (e_3\,\rho)}{\partial t}\; \;dv
+\end{flalign*}
+% end gm comment
+}
+
+%% =================================================================================================
+\section{Discrete total energy conservation: vector invariant form}
+\label{sec:INVARIANTS_2}
+
+%% =================================================================================================
+\subsection{Total energy conservation}
+\label{subsec:INVARIANTS_KE+PE_vect}
+
+The discrete form of the total energy conservation, \autoref{eq:INVARIANTS_Tot_Energy}, is given by:
+\begin{flalign*}
+  \partial_t  \left(  \sum\limits_{i,j,k} \biggl\{ \frac{u^2}{2} \,b_u + \frac{v^2}{2}\, b_v +  \rho \, g \, z_t \,b_t  \biggr\} \right) &=0
+\end{flalign*}
+which in vector invariant forms, it leads to:
+\begin{equation}
+  \label{eq:INVARIANTS_KE+PE_vect_discrete}
+  \begin{split}
+    \sum\limits_{i,j,k} \biggl\{   u\,                        \partial_t u         \;b_u
+    + v\,                        \partial_t v          \;b_v  \biggr\}
+    + \frac{1}{2} \sum\limits_{i,j,k} \biggl\{  \frac{u^2}{e_{3u}}\partial_t e_{3u} \;b_u
+    +  \frac{v^2}{e_{3v}}\partial_t e_{3v} \;b_v   \biggr\}      \\
+    = - \sum\limits_{i,j,k} \biggl\{ \frac{1}{e_{3t}}\partial_t (e_{3t} \rho) \, g \, z_t \;b_t  \biggr\}
+    - \sum\limits_{i,j,k} \biggl\{ \rho \,g\,\partial_t (z_t) \,b_t  \biggr\}
+  \end{split}
+\end{equation}
+
+Substituting the discrete expression of the time derivative of the velocity either in vector invariant,
+leads to the discrete equivalent of the four equations \autoref{eq:INVARIANTS_E_tot_flux}.
+
+%% =================================================================================================
+\subsection{Vorticity term (coriolis + vorticity part of the advection)}
+\label{subsec:INVARIANTS_vor}
+
+Let $q$, located at $f$-points, be either the relative ($q=\zeta / e_{3f}$),
+or the planetary ($q=f/e_{3f}$), or the total potential vorticity ($q=(\zeta +f) /e_{3f}$).
+Two discretisation of the vorticity term (ENE and EEN) allows the conservation of the kinetic energy.
+%% =================================================================================================
+\subsubsection{Vorticity term with ENE scheme (\protect\np[=.true.]{ln_dynvor_ene}{ln\_dynvor\_ene})}
+\label{subsec:INVARIANTS_vorENE}
+
+For the ENE scheme, the two components of the vorticity term are given by:
+\[
+  - e_3 \, q \;{\textbf{k}}\times {\textbf {U}}_h    \equiv
+  \left( {{
+        \begin{array} {*{20}c}
+          + \frac{1} {e_{1u}} \;
+          \overline {\, q \ \overline {\left( e_{1v}\,e_{3v}\,v \right)}^{\,i+1/2}} ^{\,j}        \hfill \\
+          - \frac{1} {e_{2v}} \;
+          \overline {\, q \ \overline {\left( e_{2u}\,e_{3u}\,u \right)}^{\,j+1/2}} ^{\,i}       \hfill
+        \end{array}
+      } }    \right)
+\]
+
+This formulation does not conserve the enstrophy but it does conserve the total kinetic energy.
+Indeed, the kinetic energy tendency associated to the vorticity term and
+averaged over the ocean domain can be transformed as follows:
+\begin{flalign*}
+  &\int\limits_D -  \left(  e_3 \, q \;\textbf{k} \times \textbf{U}_h  \right) \cdot \textbf{U}_h  \;  dv &&  \\
+  & \qquad \qquad
+  {
+    \begin{array}{*{20}l}
+      &\equiv \sum\limits_{i,j,k} 	\biggl\{
+        \frac{1} {e_{1u}} \overline { \,q\ \overline{ V }^{\,i+1/2}} ^{\,j} \, u \; b_u
+        - \frac{1} {e_{2v}}\overline { \, q\ \overline{ U }^{\,j+1/2}} ^{\,i} \, v \; b_v \; \biggr\}    \\
+      &\equiv  \sum\limits_{i,j,k} 	\biggl\{
+        \overline { \,q\ \overline{ V }^{\,i+1/2}}^{\,j} \; U
+        - \overline { \,q\ \overline{ U }^{\,j+1/2}}^{\,i} \; V  \; \biggr\}     \\
+      &\equiv \sum\limits_{i,j,k} q \  \biggl\{  \overline{ V }^{\,i+1/2}\; \overline{ U }^{\,j+1/2}
+        - \overline{ U }^{\,j+1/2}\; \overline{ V }^{\,i+1/2}         \biggr\}  \quad  \equiv 0
+    \end{array}
+  }
+\end{flalign*}
+In other words, the domain averaged kinetic energy does not change due to the vorticity term.
+
+%% =================================================================================================
+\subsubsection{Vorticity term with EEN scheme (\protect\np[=.true.]{ln_dynvor_een}{ln\_dynvor\_een})}
+\label{subsec:INVARIANTS_vorEEN_vect}
+
+With the EEN scheme, the vorticity terms are represented as:
+\begin{equation}
+  \label{eq:INVARIANTS_dynvor_een1}
+  \left\{ {
+      \begin{aligned}
+        +q\,e_3 \, v 	&\equiv +\frac{1}{e_{1u} }   \sum_{\substack{i_p,\,k_p}}
+        {^{i+1/2-i_p}_j}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{1v} e_{3v} \ v  \right)^{i+i_p-1/2}_{j+j_p}   \\
+        - q\,e_3 \, u     &\equiv -\frac{1}{e_{2v} }    \sum_{\substack{i_p,\,k_p}}
+        {^i_{j+1/2-j_p}}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{2u} e_{3u} \ u  \right)^{i+i_p}_{j+j_p-1/2}
+      \end{aligned}
+    } \right.
+\end{equation}
+where the indices $i_p$ and $j_p$ take the following value: $i_p = -1/2$ or $1/2$ and $j_p = -1/2$ or $1/2$,
+and the vorticity triads, ${^i_j}\mathbb{Q}^{i_p}_{j_p}$, defined at $T$-point, are given by:
+\begin{equation}
+  \label{eq:INVARIANTS_Q_triads}
+  _i^j \mathbb{Q}^{i_p}_{j_p}
+  = \frac{1}{12} \ \left(   q^{i-i_p}_{j+j_p} + q^{i+j_p}_{j+i_p} + q^{i+i_p}_{j-j_p}  \right)
+\end{equation}
+
+This formulation does conserve the total kinetic energy.
+Indeed,
+\begin{flalign*}
+  &\int\limits_D - \textbf{U}_h \cdot   \left(  \zeta \;\textbf{k} \times \textbf{U}_h  \right)  \;  dv &&  \\
+  \equiv \sum\limits_{i,j,k} &	\biggl\{
+  \left[  \sum_{\substack{i_p,\,k_p}}
+    {^{i+1/2-i_p}_j}\mathbb{Q}^{i_p}_{j_p} \; V^{i+1/2-i_p}_{j+j_p} \right] U^{i+1/2}_{j}    %   &&\\
+  - \left[  \sum_{\substack{i_p,\,k_p}}
+    {^i_{j+1/2-j_p}}\mathbb{Q}^{i_p}_{j_p} \; U^{i+i_p}_{j+1/2-j_p}  \right] V^{i}_{j+1/2}    \biggr\}     && \\ \\
+  \equiv \sum\limits_{i,j,k} &  \sum_{\substack{i_p,\,k_p}} \biggl\{  \ \
+  {^{i+1/2-i_p}_j}\mathbb{Q}^{i_p}_{j_p} \; V^{i+1/2-i_p}_{j+j_p}  \, U^{i+1/2}_{j}     %  &&\\
+  - {^i_{j+1/2-j_p}}\mathbb{Q}^{i_p}_{j_p} \; U^{i+i_p}_{j+1/2-j_p} \, V^{i}_{j+1/2}     \ \;     \biggr\}     &&  \\
+  %
+  \allowdisplaybreaks
+  \intertext{ Expending the summation on $i_p$ and $k_p$, it becomes:}
+  %
+  \equiv \sum\limits_{i,j,k} & \biggl\{  \ \
+  {^{i+1}_j     }\mathbb{Q}^{-1/2}_{+1/2} \;V^{i+1}_{j+1/2} \; U^{\,i+1/2}_{j}
+  -  {^i_{j}\quad}\mathbb{Q}^{-1/2}_{+1/2} \; U^{i-1/2}_{j}    \; V^{\,i}_{j+1/2}         &&  \\
+  &       + {^{i+1}_j     }\mathbb{Q}^{-1/2}_{-1/2} \; V^{i+1}_{j-1/2} \; U^{\,i+1/2}_{j}
+  - {^i_{j+1}     }\mathbb{Q}^{-1/2}_{-1/2} \; U^{i-1/2}_{j+1} \; V^{\,i}_{j+1/2}        \biggr.     &&  \\
+  &       + {^{i}_j\quad}\mathbb{Q}^{+1/2}_{+1/2} \; V^{i}_{j+1/2}   \; U^{\,i+1/2}_{j}
+  - {^i_{j}\quad}\mathbb{Q}^{+1/2}_{+1/2} \; U^{i+1/2}_{j}   \; V^{\,i}_{j+1/2}          \biggr.        &&  \\
+  &       + {^{i}_j\quad}\mathbb{Q}^{+1/2}_{-1/2} \; V^{i}_{j-1/2}     \; U^{\,i+1/2}_{j}
+  -  {^i_{j+1}     }\mathbb{Q}^{+1/2}_{-1/2} \; U^{i+1/2}_{j+1}\; V^{\,i}_{j+1/2}  \ \;     \biggr\}     &&  \\
+  %
+  \allowdisplaybreaks
+  \intertext{The summation is done over all $i$ and $j$ indices, it is therefore possible to introduce
+    a shift of $-1$ either in $i$ or $j$ direction in some of the term of the summation (first term of the
+    first and second lines, second term of the second and fourth lines). By doning so, we can regroup
+    all the terms of the summation by triad at a ($i$,$j$) point. In other words, we regroup all the terms
+    in the neighbourhood  that contain a triad at the same ($i$,$j$) indices. It becomes: }
+  \allowdisplaybreaks
+  %
+  \equiv \sum\limits_{i,j,k} & \biggl\{  \ \
+  {^{i}_j}\mathbb{Q}^{-1/2}_{+1/2}  \left[  V^{i}_{j+1/2}\, U^{\,i-1/2}_{j}
+    -  U^{i-1/2}_{j} \, V^{\,i}_{j+1/2}      \right]    &&  \\
+  &       + {^{i}_j}\mathbb{Q}^{-1/2}_{-1/2}  \left[  V^{i}_{j-1/2} \, U^{\,i-1/2}_{j}
+    -    U^{i-1/2}_{j} \, V^{\,i}_{j-1/2}      \right]    \biggr.   &&  \\
+  &      + {^{i}_j}\mathbb{Q}^{+1/2}_{+1/2}  \left[  V^{i}_{j+1/2} \, U^{\,i+1/2}_{j}
+    -    U^{i+1/2}_{j} \, V^{\,i}_{j+1/2}     \right]  \biggr.  &&  \\
+  &     + {^{i}_j}\mathbb{Q}^{+1/2}_{-1/2}  \left[   V^{i}_{j-1/2} \, U^{\,i+1/2}_{j}
+    -    U^{i+1/2}_{j-1} \, V^{\,i}_{j-1/2}  \right]  \ \;   \biggr\}   \qquad
+  \equiv \ 0   &&
+\end{flalign*}
+
+%% =================================================================================================
+\subsubsection{Gradient of kinetic energy / Vertical advection}
+\label{subsec:INVARIANTS_zad}
+
+The change of Kinetic Energy (KE) due to the vertical advection is exactly balanced by the change of KE due to the horizontal gradient of KE~:
+\[
+  \int_D \textbf{U}_h \cdot \frac{1}{e_3 } \omega \partial_k \textbf{U}_h \;dv
+  =  -   \int_D \textbf{U}_h \cdot \nabla_h \left( \frac{1}{2}\;{\textbf{U}_h}^2 \right)\;dv
+  +   \frac{1}{2} \int_D {  \frac{{\textbf{U}_h}^2}{e_3} \partial_t ( e_3) \;dv }
+\]
+Indeed, using successively \autoref{eq:DOM_di_adj} (\ie\ the skew symmetry property of the $\delta$ operator)
+and the continuity equation, then \autoref{eq:DOM_di_adj} again,
+then the commutativity of operators $\overline {\,\cdot \,}$ and $\delta$, and finally \autoref{eq:DOM_mi_adj}
+(\ie\ the symmetry property of the $\overline {\,\cdot \,}$ operator)
+applied in the horizontal and vertical directions, it becomes:
+\begin{flalign*}
+  & - \int_D \textbf{U}_h \cdot \text{KEG}\;dv
+  = - \int_D \textbf{U}_h \cdot \nabla_h \left( \frac{1}{2}\;{\textbf{U}_h}^2 \right)\;dv    &&&\\
+  %
+  \equiv  & -  \sum\limits_{i,j,k} \frac{1}{2}  \biggl\{
+  \frac{1} {e_{1u}}  \delta_{i+1/2}   \left[   \overline {u^2}^{\,i} + \overline {v^2}^{\,j}   \right]  u \ b_u
+  + \frac{1} {e_{2v}}  \delta_{j+1/2}   \left[   \overline {u^2}^{\,i} + \overline {v^2}^{\,j}   \right]  v \ b_v   \biggr\}  	&&&  \\
+  %
+  \equiv & + \sum\limits_{i,j,k} \frac{1}{2}  \left(   \overline {u^2}^{\,i} + \overline {v^2}^{\,j}   \right)\;
+  \biggl\{ \delta_{i} \left[  U   \right] +  \delta_{j} \left[  V  \right]    \biggr\}       &&&  \\
+  \allowdisplaybreaks
+  %
+  \equiv   & - \sum\limits_{i,j,k}  \frac{1}{2}
+  \left(       \overline {u^2}^{\,i} + \overline {v^2}^{\,j}   \right)  \;
+  \biggl\{   \frac{b_t}{e_{3t}} \partial_t (e_{3t})  +  \delta_k \left[  W   \right]    \biggr\}    &&&\\
+  \allowdisplaybreaks
+  %
+  \equiv & +  \sum\limits_{i,j,k} \frac{1}{2} \delta_{k+1/2}   \left[ \overline{ u^2}^{\,i} + \overline{ v^2}^{\,j}   \right] \;  W
+  -  \sum\limits_{i,j,k} \frac{1}{2} \left(   \overline {u^2}^{\,i} + \overline {v^2}^{\,j}   \right) \;\partial_t b_t   &&& \\
+  \allowdisplaybreaks
+  %
+  \equiv   & + \sum\limits_{i,j,k} \frac{1} {2} \left(    \overline{\delta_{k+1/2} \left[ u^2 \right]}^{\,i}
+    + \overline{\delta_{k+1/2} \left[ v^2 \right]}^{\,j}    \right) \; W
+  -  \sum\limits_{i,j,k}  \left(  \frac{u^2}{2}\,\partial_t \overline{b_t}^{\,{i+1/2}}
+    + \frac{v^2}{2}\,\partial_t \overline{b_t}^{\,{j+1/2}}   \right)    &&& \\
+  \allowdisplaybreaks
+  \intertext{Assuming that $b_u= \overline{b_t}^{\,i+1/2}$ and $b_v= \overline{b_t}^{\,j+1/2}$, or at least that the time
+    derivative of these two equations is satisfied, it becomes:}
+  %
+  \equiv &     \sum\limits_{i,j,k} \frac{1} {2}
+  \biggl\{ \; \overline{W}^{\,i+1/2}\;\delta_{k+1/2} \left[ u^2 \right]
+  + \overline{W}^{\,j+1/2}\;\delta_{k+1/2} \left[ v^2 \right]  \;  \biggr\}
+  -  \sum\limits_{i,j,k}  \left(  \frac{u^2}{2}\,\partial_t b_u
+    + \frac{v^2}{2}\,\partial_t b_v   \right)    &&& \\
+  \allowdisplaybreaks
+  %
+  \equiv &     \sum\limits_{i,j,k}
+  \biggl\{ \; \overline{W}^{\,i+1/2}\; \overline {u}^{\,k+1/2}\; \delta_{k+1/2}[ u ]
+  + \overline{W}^{\,j+1/2}\; \overline {v}^{\,k+1/2}\; \delta_{k+1/2}[ v ]  \;  \biggr\}
+  -  \sum\limits_{i,j,k}  \left(  \frac{u^2}{2}\,\partial_t b_u
+    + \frac{v^2}{2}\,\partial_t b_v   \right)    &&& \\
+  %
+  \allowdisplaybreaks
+  \equiv  &  \sum\limits_{i,j,k}
+  \biggl\{ \; \frac{1} {b_u } \; \overline { \overline{W}^{\,i+1/2}\,\delta_{k+1/2}  \left[ u \right] }^{\,k} \;u\;b_u
+  + \frac{1} {b_v } \; \overline { \overline{W}^{\,j+1/2} \delta_{k+1/2}  \left[ v \right]  }^{\,k} \;v\;b_v  \; \biggr\}
+  -  \sum\limits_{i,j,k}  \left(  \frac{u^2}{2}\,\partial_t b_u
+    + \frac{v^2}{2}\,\partial_t b_v   \right)    &&& \\
+  %
+  \intertext{The first term provides the discrete expression for the vertical advection of momentum (ZAD),
+    while the second term corresponds exactly to \autoref{eq:INVARIANTS_KE+PE_vect_discrete}, therefore:}
+  \equiv&                   \int\limits_D \textbf{U}_h \cdot \text{ZAD} \;dv
+  + \frac{1}{2} \int_D { {\textbf{U}_h}^2 \frac{1}{e_3} \partial_t  (e_3)  \;dv }    &&&\\
+  \equiv&                   \int\limits_D \textbf{U}_h \cdot w \partial_k \textbf{U}_h \;dv
+  + \frac{1}{2} \int_D { {\textbf{U}_h}^2 \frac{1}{e_3} \partial_t  (e_3)  \;dv }    &&&\\
+\end{flalign*}
+
+There is two main points here.
+First, the satisfaction of this property links the choice of the discrete formulation of the vertical advection and
+of the horizontal gradient of KE.
+Choosing one imposes the other.
+For example KE can also be discretized as $1/2\,({\overline u^{\,i}}^2 + {\overline v^{\,j}}^2)$.
+This leads to the following expression for the vertical advection:
+\[
+  \frac{1} {e_3 }\; \omega\; \partial_k \textbf{U}_h
+  \equiv \left( {{
+        \begin{array} {*{20}c}
+          \frac{1} {e_{1u}\,e_{2u}\,e_{3u}} \;  \overline{\overline {e_{1t}\,e_{2t} \,\omega\;\delta_{k+1/2}
+          \left[ \overline u^{\,i+1/2} \right]}}^{\,i+1/2,k}  \hfill \\
+          \frac{1} {e_{1v}\,e_{2v}\,e_{3v}} \;   \overline{\overline {e_{1t}\,e_{2t} \,\omega \;\delta_{k+1/2}
+          \left[ \overline v^{\,j+1/2} \right]}}^{\,j+1/2,k} \hfill
+        \end{array}
+      } } \right)
+\]
+a formulation that requires an additional horizontal mean in contrast with the one used in \NEMO.
+Nine velocity points have to be used instead of 3.
+This is the reason why it has not been chosen.
+
+Second, as soon as the chosen $s$-coordinate depends on time,
+an extra constraint arises on the time derivative of the volume at $u$- and $v$-points:
+\begin{flalign*}
+  e_{1u}\,e_{2u}\,\partial_t (e_{3u}) =\overline{ e_{1t}\,e_{2t}\;\partial_t (e_{3t}) }^{\,i+1/2}    \\
+  e_{1v}\,e_{2v}\,\partial_t (e_{3v})  =\overline{ e_{1t}\,e_{2t}\;\partial_t (e_{3t}) }^{\,j+1/2}
+\end{flalign*}
+which is (over-)satified by defining the vertical scale factor as follows:
+\begin{flalign*}
+  % \label{eq:INVARIANTS_e3u-e3v}
+  e_{3u} = \frac{1}{e_{1u}\,e_{2u}}\;\overline{ e_{1t}^{ }\,e_{2t}^{ }\,e_{3t}^{ } }^{\,i+1/2}    \\
+  e_{3v} = \frac{1}{e_{1v}\,e_{2v}}\;\overline{ e_{1t}^{ }\,e_{2t}^{ }\,e_{3t}^{ } }^{\,j+1/2}
+\end{flalign*}
+
+Blah blah required on the the step representation of bottom topography.....
+
+%% =================================================================================================
+\subsection{Pressure gradient term}
+\label{subsec:INVARIANTS_2.6}
+
+\cmtgm{
+  A pressure gradient has no contribution to the evolution of the vorticity as the curl of a gradient is zero.
+  In the $z$-coordinate, this property is satisfied locally on a C-grid with 2nd order finite differences
+  (property \autoref{eq:DOM_curl_grad}).
+}
+
+When the equation of state is linear
+(\ie\ when an advection-diffusion equation for density can be derived from those of temperature and salinity)
+the change of KE due to the work of pressure forces is balanced by
+the change of potential energy due to buoyancy forces:
+\[
+  - \int_D  \left. \nabla p \right|_z \cdot \textbf{U}_h \;dv
+  = - \int_D \nabla \cdot \left( \rho \,\textbf {U} \right) \,g\,z \;dv
+  + \int_D g\, \rho \; \partial_t (z)  \;dv
+\]
+
+This property can be satisfied in a discrete sense for both $z$- and $s$-coordinates.
+Indeed, defining the depth of a $T$-point, $z_t$,
+as the sum of the vertical scale factors at $w$-points starting from the surface,
+the work of pressure forces can be written as:
+\begin{flalign*}
+  &- \int_D  \left. \nabla p \right|_z \cdot \textbf{U}_h \;dv
+  \equiv \sum\limits_{i,j,k} \biggl\{ \;  - \frac{1} {e_{1u}}   \Bigl(
+  \delta_{i+1/2} [p_t] - g\;\overline \rho^{\,i+1/2}\;\delta_{i+1/2} [z_t]     \Bigr)  \; u\;b_u && \\
+  & \qquad \qquad  \qquad \qquad  \qquad \quad \ \,
+  - \frac{1} {e_{2v}}    \Bigl(
+  \delta_{j+1/2} [p_t] - g\;\overline \rho^{\,j+1/2}\delta_{j+1/2} [z_t]      \Bigr)  \; v\;b_v \;  \biggr\}   && \\
+  %
+  \allowdisplaybreaks
+  \intertext{Using successively \autoref{eq:DOM_di_adj}, \ie\ the skew symmetry property of
+    the $\delta$ operator, \autoref{eq:DYN_wzv}, the continuity equation, \autoref{eq:DYN_hpg_sco},
+    the hydrostatic equation in the $s$-coordinate, and $\delta_{k+1/2} \left[ z_t \right] \equiv e_{3w} $,
+    which comes from the definition of $z_t$, it becomes: }
+  \allowdisplaybreaks
+  %
+  \equiv& +  \sum\limits_{i,j,k}   g  \biggl\{
+  \overline\rho^{\,i+1/2}\,U\,\delta_{i+1/2}[z_t]
+  +  	\overline\rho^{\,j+1/2}\,V\,\delta_{j+1/2}[z_t]
+  +\Bigl(  \delta_i[U] + \delta_j [V]  \Bigr)\;\frac{p_t}{g} \biggr\}  &&\\
+  %
+  \equiv& +  \sum\limits_{i,j,k}   g   \biggl\{
+  \overline\rho^{\,i+1/2}\,U\,\delta_{i+1/2}[z_t]
+  +  	\overline\rho^{\,j+1/2}\,V\,\delta_{j+1/2}[z_t]
+  -       \left(   \frac{b_t}{e_{3t}} \partial_t (e_{3t})  +  \delta_k \left[ W \right]    \right) \frac{p_t}{g}    \biggr\}   &&&\\
+  %
+  \equiv& +  \sum\limits_{i,j,k}  g   \biggl\{
+  \overline\rho^{\,i+1/2}\,U\,\delta_{i+1/2}[z_t]
+  +  	\overline\rho^{\,j+1/2}\,V\,\delta_{j+1/2}[z_t]
+  +	\frac{W}{g}\;\delta_{k+1/2} [p_t]
+  -        \frac{p_t}{g}\,\partial_t b_t    \biggr\}    &&&\\
+  %
+  \equiv& +  \sum\limits_{i,j,k}  g   \biggl\{
+  \overline\rho^{\,i+1/2}\,U\,\delta_{i+1/2}[z_t]
+  +  	\overline\rho^{\,j+1/2}\,V\,\delta_{j+1/2}[z_t]
+  - 	W\;e_{3w} \overline \rho^{\,k+1/2}
+  -        \frac{p_t}{g}\,\partial_t b_t    \biggr\}    &&&\\
+  %
+  \equiv& +  \sum\limits_{i,j,k}    g   \biggl\{
+  \overline\rho^{\,i+1/2}\,U\,\delta_{i+1/2}[z_t]
+  +  	\overline\rho^{\,j+1/2}\,V\,\delta_{j+1/2}[z_t]
+  + 	W\; \overline \rho^{\,k+1/2}\;\delta_{k+1/2} [z_t]
+  -        \frac{p_t}{g}\,\partial_t b_t    \biggr\}    &&&\\
+  %
+  \allowdisplaybreaks
+  %
+  \equiv& - \sum\limits_{i,j,k}   g \; z_t      \biggl\{
+  \delta_i 	\left[ U\;	\overline \rho^{\,i+1/2} 	\right]
+  + 	\delta_j 	\left[ V\;	\overline \rho^{\,j+1/2} 	\right]
+  + 	\delta_k 	\left[ W\;	\overline \rho^{\,k+1/2} 	\right]       \biggr\}
+  - \sum\limits_{i,j,k}       \biggl\{ p_t\;\partial_t b_t    \biggr\}   &&&\\
+  %
+  \equiv& + \sum\limits_{i,j,k}   g \; z_t    \biggl\{      \partial_t ( e_{3t} \,\rho)    \biggr\}  \; b_t
+  -  \sum\limits_{i,j,k}                 \biggl\{  p_t\;\partial_t b_t                     \biggr\}              &&&\\
+  %
+\end{flalign*}
+The first term is exactly the first term of the right-hand-side of \autoref{eq:INVARIANTS_KE+PE_vect_discrete}.
+It remains to demonstrate that the last term,
+which is obviously a discrete analogue of $\int_D \frac{p}{e_3} \partial_t (e_3)\;dv$ is equal to
+the last term of \autoref{eq:INVARIANTS_KE+PE_vect_discrete}.
+In other words, the following property must be satisfied:
+\begin{flalign*}
+  \sum\limits_{i,j,k}  \biggl\{  p_t\;\partial_t b_t                  \biggr\}
+  \equiv  \sum\limits_{i,j,k}  \biggl\{ \rho \,g\,\partial_t (z_t) \,b_t  \biggr\}
+\end{flalign*}
+
+Let introduce $p_w$ the pressure at $w$-point such that $\delta_k [p_w] = - \rho \,g\,e_{3t}$.
+The right-hand-side of the above equation can be transformed as follows:
+
+\begin{flalign*}
+  \sum\limits_{i,j,k}  \biggl\{ \rho \,g\,\partial_t (z_t) \,b_t  \biggr\}
+  &\equiv   - \sum\limits_{i,j,k}  \biggl\{ \delta_k [p_w]\,\partial_t (z_t) \,e_{1t}\,e_{2t}  \biggr\}        &&&\\
+  %
+  &\equiv  + \sum\limits_{i,j,k}  \biggl\{  p_w\, \delta_{k+1/2} [\partial_t (z_t)] \,e_{1t}\,e_{2t}  \biggr\}
+  \equiv  + \sum\limits_{i,j,k}  \biggl\{  p_w\, \partial_t (e_{3w}) \,e_{1t}\,e_{2t}  \biggr\}        &&&\\
+  &\equiv  + \sum\limits_{i,j,k}  \biggl\{  p_w\, \partial_t (b_w) \biggr\}
+  %
+  % & \equiv     \sum\limits_{i,j,k} \biggl\{  \frac{1}{e_{3t}} \delta_k [p_w]\;\partial_t (z_t) \,b_w   \right)   \biggr\}           &&&\\
+  % & \equiv     \sum\limits_{i,j,k} \biggl\{   p_w\;\partial_t \left(    \delta_k [z_t]   \right)  e_{1w}\,e_{2w}   \biggr\}           &&&\\
+  % & \equiv     \sum\limits_{i,j,k} \biggl\{   p_w\;\partial_t b_w   \biggr\}
+\end{flalign*}
+therefore, the balance to be satisfied is:
+\begin{flalign*}
+  \sum\limits_{i,j,k}  \biggl\{  p_t\;\partial_t (b_t) \biggr\}  \equiv  \sum\limits_{i,j,k}  \biggl\{  p_w\, \partial_t (b_w) \biggr\}
+\end{flalign*}
+which is a purely vertical balance:
+\begin{flalign*}
+  \sum\limits_{k}  \biggl\{  p_t\;\partial_t (e_{3t}) \biggr\}  \equiv  \sum\limits_{k}  \biggl\{  p_w\, \partial_t (e_{3w}) \biggr\}
+\end{flalign*}
+Defining $p_w = \overline{p_t}^{\,k+1/2}$
+
+%gm comment
+\cmtgm{
+  \begin{flalign*}
+    \sum\limits_{i,j,k} \biggl\{   p_t\;\partial_t b_t   \biggr\}                                &&&\\
+    %
+    & \equiv     \sum\limits_{i,j,k} \biggl\{  \frac{1}{e_{3t}} \delta_k [p_w]\;\partial_t (z_t) \,b_w    \biggr\}           &&&\\
+    & \equiv     \sum\limits_{i,j,k} \biggl\{   p_w\;\partial_t \left(    \delta_{k+1/2} [z_t]   \right)  e_{1w}\,e_{2w}   \biggr\}           &&&\\
+    & \equiv     \sum\limits_{i,j,k} \biggl\{   p_w\;\partial_t b_w   \biggr\}
+  \end{flalign*}
+
+  \begin{flalign*}
+    \int\limits_D   \rho \, g \, \frac{\partial z }{\partial t} \;dv
+    \equiv&  \sum\limits_{i,j,k}   \biggl\{  \frac{1}{e_{3t}} \frac{\partial e_{3t}}{\partial t} p   \biggr\} \; b_t   &&&\\
+    \equiv&  \sum\limits_{i,j,k}   \biggl\{      \biggr\} \; b_t   &&&\\
+  \end{flalign*}
+
+  %
+  \begin{flalign*}
+    \equiv& - \int_D \nabla \cdot \left( \rho \,\textbf {U} \right)\;g\;z\;\;dv
+    + \int\limits_D g\, \rho \; \frac{\partial z}{\partial t}  \;dv     &&& \\
+  \end{flalign*}
+  %
+}
+%end gm comment
+
+Note that this property strongly constrains the discrete expression of both the depth of $T-$points and
+of the term added to the pressure gradient in the $s$-coordinate.
+Nevertheless, it is almost never satisfied since a linear equation of state is rarely used.
+
+%% =================================================================================================
+\section{Discrete total energy conservation: flux form}
+\label{sec:INVARIANTS_3}
+
+%% =================================================================================================
+\subsection{Total energy conservation}
+\label{subsec:INVARIANTS_KE+PE_flux}
+
+The discrete form of the total energy conservation, \autoref{eq:INVARIANTS_Tot_Energy}, is given by:
+\begin{flalign*}
+  \partial_t \left(  \sum\limits_{i,j,k} \biggl\{ \frac{u^2}{2} \,b_u + \frac{v^2}{2}\, b_v +  \rho \, g \, z_t \,b_t  \biggr\} \right) &=0  \\
+\end{flalign*}
+which in flux form, it leads to:
+\begin{flalign*}
+  \sum\limits_{i,j,k} \biggl\{  \frac{u    }{e_{3u}}\,\frac{\partial (e_{3u}u)}{\partial t} \,b_u
+  +  \frac{v    }{e_{3v}}\,\frac{\partial (e_{3v}v)}{\partial t} \,b_v  \biggr\}
+  &  -  \frac{1}{2} \sum\limits_{i,j,k} \biggl\{  \frac{u^2}{e_{3u}}\frac{\partial    e_{3u}    }{\partial t} \,b_u
+  +  \frac{v^2}{e_{3v}}\frac{\partial    e_{3v}    }{\partial t} \,b_v   \biggr\} \\
+  &= - \sum\limits_{i,j,k} \biggl\{ \frac{1}{e_3t}\frac{\partial e_{3t} \rho}{\partial t} \, g \, z_t \,b_t  \biggr\}
+  - \sum\limits_{i,j,k} \biggl\{ \rho \,g\,\frac{\partial z_t}{\partial t} \,b_t  \biggr\} \\
+\end{flalign*}
+
+Substituting the discrete expression of the time derivative of the velocity either in
+vector invariant or in flux form, leads to the discrete equivalent of the ????
+
+%% =================================================================================================
+\subsection{Coriolis and advection terms: flux form}
+\label{subsec:INVARIANTS_3.2}
+
+%% =================================================================================================
+\subsubsection{Coriolis plus ``metric'' term}
+\label{subsec:INVARIANTS_3.3}
+
+In flux from the vorticity term reduces to a Coriolis term in which
+the Coriolis parameter has been modified to account for the ``metric'' term.
+This altered Coriolis parameter is discretised at an f-point.
+It is given by:
+\[
+  f+\frac{1} {e_1 e_2 } \left( v \frac{\partial e_2 } {\partial i} - u \frac{\partial e_1 } {\partial j}\right)\;
+  \equiv \;
+  f+\frac{1} {e_{1f}\,e_{2f}} \left( \overline v^{\,i+1/2} \delta_{i+1/2} \left[ e_{2u} \right]
+    -\overline u^{\,j+1/2} \delta_{j+1/2} \left[ e_{1u}  \right] \right)
+\]
+
+Either the ENE or EEN scheme is then applied to obtain the vorticity term in flux form.
+It therefore conserves the total KE.
+The derivation is the same as for the vorticity term in the vector invariant form (\autoref{subsec:INVARIANTS_vor}).
+
+%% =================================================================================================
+\subsubsection{Flux form advection}
+\label{subsec:INVARIANTS_3.4}
+
+The flux form operator of the momentum advection is evaluated using
+a centered second order finite difference scheme.
+Because of the flux form, the discrete operator does not contribute to the global budget of linear momentum.
+Because of the centered second order scheme, it conserves the horizontal kinetic energy, that is:
+
+\begin{equation}
+  \label{eq:INVARIANTS_ADV_KE_flux}
+  -  \int_D \textbf{U}_h \cdot     \left(                 {{
+        \begin{array} {*{20}c}
+          \nabla \cdot \left( \textbf{U}\,u \right) \hfill \\
+          \nabla \cdot \left( \textbf{U}\,v \right) \hfill \\
+        \end{array}
+      } }           \right)   \;dv
+  -   \frac{1}{2} \int_D {  {\textbf{U}_h}^2 \frac{1}{e_3} \frac{\partial  e_3 }{\partial t} \;dv } =\;0
+\end{equation}
+
+Let us first consider the first term of the scalar product
+(\ie\ just the the terms associated with the i-component of the advection):
+\begin{flalign*}
+  &  - \int_D u \cdot \nabla \cdot \left(   \textbf{U}\,u   \right) \; dv   \\
+  %
+  \equiv& - \sum\limits_{i,j,k} \biggl\{    \frac{1} {b_u}    \biggl(
+  \delta_{i+1/2}  \left[   \overline {U}^{\,i}      \;\overline u^{\,i}          \right]
+  + \delta_j           \left[   \overline {V}^{\,i+1/2}\;\overline u^{\,j+1/2}   \right]
+  + \delta_k          \left[   \overline {W}^{\,i+1/2}\;\overline u^{\,k+1/2} \right]  \biggr)   \;   \biggr\} \, b_u \;u &&&  \\
+  %
+  \equiv& - \sum\limits_{i,j,k}
+  \biggl\{
+  \delta_{i+1/2} \left[   \overline {U}^{\,i}\;  \overline u^{\,i}  \right]
+  + \delta_j          \left[   \overline {V}^{\,i+1/2}\;\overline u^{\,j+1/2}   \right]
+  + \delta_k         \left[   \overline {W}^{\,i+12}\;\overline u^{\,k+1/2}  \right]
+  \; \biggr\} \; u     \\
+  %
+  \equiv& + \sum\limits_{i,j,k}
+  \biggl\{
+  \overline {U}^{\,i}\;	\overline u^{\,i} 	\delta_i \left[ u \right]
+  + \overline {V}^{\,i+1/2}\;	\overline u^{\,j+1/2} 	\delta_{j+1/2} \left[ u \right]
+  + \overline {W}^{\,i+1/2}\;	\overline u^{\,k+1/2}	\delta_{k+1/2} 	\left[ u \right]     \biggr\}     && \\
+  %
+  \equiv& + \frac{1}{2} \sum\limits_{i,j,k}    \biggl\{
+  \overline{U}^{\,i} 		\delta_i 		\left[ u^2 \right]
+  + \overline{V}^{\,i+1/2} 	\delta_{j+/2} 	\left[ u^2 \right]
+  + \overline{W}^{\,i+1/2} 	\delta_{k+1/2} 	\left[ u^2 \right]      \biggr\} && \\
+  %
+  \equiv& -  \sum\limits_{i,j,k}    \frac{1}{2}   \bigg\{
+  U  \; \delta_{i+1/2}    \left[ \overline {u^2}^{\,i} \right]
+  + V  \; \delta_{j+1/2}    \left[ \overline {u^2}^{\,i} \right]
+  + W \; \delta_{k+1/2}   \left[ \overline {u^2}^{\,i} \right]     \biggr\}    &&& \\
+  %
+  \equiv& - \sum\limits_{i,j,k}  \frac{1}{2}  \overline {u^2}^{\,i}     \biggl\{
+  \delta_{i+1/2} 	\left[ U  \right]
+  + \delta_{j+1/2} 	\left[ V  \right]
+  + \delta_{k+1/2} 	\left[ W \right]     \biggr\}    &&& \\
+  %
+  \equiv& + \sum\limits_{i,j,k}  \frac{1}{2}  \overline {u^2}^{\,i}
+  \biggl\{     \left(   \frac{1}{e_{3t}} \frac{\partial e_{3t}}{\partial t}   \right) \; b_t     \biggr\}    &&& \\
+\end{flalign*}
+Applying similar manipulation applied to the second term of the scalar product leads to:
+\[
+  -  \int_D \textbf{U}_h \cdot     \left(                 {{
+        \begin{array} {*{20}c}
+          \nabla \cdot \left( \textbf{U}\,u \right) \hfill \\
+          \nabla \cdot \left( \textbf{U}\,v \right) \hfill \\
+        \end{array}
+      } }           \right)   \;dv
+  \equiv + \sum\limits_{i,j,k}  \frac{1}{2}  \left( \overline {u^2}^{\,i} + \overline {v^2}^{\,j} \right)
+  \biggl\{     \left(   \frac{1}{e_{3t}} \frac{\partial e_{3t}}{\partial t}   \right) \; b_t     \biggr\}
+\]
+which is the discrete form of $ \frac{1}{2} \int_D u \cdot \nabla \cdot \left(   \textbf{U}\,u   \right) \; dv $.
+\autoref{eq:INVARIANTS_ADV_KE_flux} is thus satisfied.
+
+When the UBS scheme is used to evaluate the flux form momentum advection,
+the discrete operator does not contribute to the global budget of linear momentum (flux form).
+The horizontal kinetic energy is not conserved, but forced to decay (\ie\ the scheme is diffusive).
+
+%% =================================================================================================
+\section{Discrete enstrophy conservation}
+\label{sec:INVARIANTS_4}
+
+%% =================================================================================================
+\subsubsection{Vorticity term with ENS scheme  (\protect\np[=.true.]{ln_dynvor_ens}{ln\_dynvor\_ens})}
+\label{subsec:INVARIANTS_vorENS}
+
+In the ENS scheme, the vorticity term is descretized as follows:
+\begin{equation}
+  \label{eq:INVARIANTS_dynvor_ens}
+  \left\{
+    \begin{aligned}
+      +\frac{1}{e_{1u}} & \overline{q}^{\,i}  & {\overline{ \overline{\left( e_{1v}\,e_{3v}\;  v \right) } } }^{\,i, j+1/2}    \\
+      - \frac{1}{e_{2v}} & \overline{q}^{\,j}  & {\overline{ \overline{\left( e_{2u}\,e_{3u}\; u \right) } } }^{\,i+1/2, j}
+    \end{aligned}
+  \right.
+\end{equation}
+
+The scheme does not allow but the conservation of the total kinetic energy but the conservation of $q^2$,
+the potential enstrophy for a horizontally non-divergent flow (\ie\ when $\chi$=$0$).
+Indeed, using the symmetry or skew symmetry properties of the operators
+( \autoref{eq:DOM_mi_adj} and \autoref{eq:DOM_di_adj}),
+it can be shown that:
+\begin{equation}
+  \label{eq:INVARIANTS_1.1}
+  \int_D {q\,\;{\textbf{k}}\cdot \frac{1} {e_3} \nabla \times \left( {e_3 \, q \;{\textbf{k}}\times {\textbf{U}}_h } \right)\;dv} \equiv 0
+\end{equation}
+where $dv=e_1\,e_2\,e_3 \; di\,dj\,dk$ is the volume element.
+Indeed, using \autoref{eq:DYN_vor_ens},
+the discrete form of the right hand side of \autoref{eq:INVARIANTS_1.1} can be transformed as follow:
+\begin{flalign*}
+  &\int_D q \,\; \textbf{k} \cdot \frac{1} {e_3 } \nabla \times
+  \left(  e_3 \, q \; \textbf{k} \times  \textbf{U}_h   \right)\;   dv \\
+  %
+  & \qquad
+  {
+    \begin{array}{*{20}l}
+      &\equiv \sum\limits_{i,j,k}
+        q \ \left\{  \delta_{i+1/2}  \left[ - \,\overline {q}^{\,i}\;  \overline{\overline  U }^{\,i,j+1/ 2} \right]
+        - \delta_{j+1/2} \left[	 \overline {q}^{\,j}\;  \overline{\overline  V }^{\,i+1/2, j} \right]     \right\}    \\
+      %
+      &\equiv \sum\limits_{i,j,k}
+        \left\{   \delta_i [q] \; \overline{q}^{\,i} \; \overline{  \overline U  }^{\,i,j+1/2}
+        + \delta_j [q] \; \overline{q}^{\,j} \; \overline{\overline V }^{\,i+1/2,j}        \right\}       &&  \\
+      %
+      &\equiv \,\frac{1} {2} \sum\limits_{i,j,k}
+        \left\{         \delta_i  \left[ q^2 \right] \; \overline{\overline U }^{\,i,j+1/2}
+        + \delta_j  \left[ q^2 \right] \; \overline{\overline V }^{\,i+1/2,j}      \right\}    &&  \\
+      %
+      &\equiv - \frac{1} {2} \sum\limits_{i,j,k} 	q^2 \;
+        \left\{    \delta_{i+1/2}   \left[   \overline{\overline{ U }}^{\,i,j+1/2}    \right]
+        + \delta_{j+1/2}  \left[   \overline{\overline{ V }}^{\,i+1/2,j}     \right]    \right\}    && \\
+    \end{array}
+  }
+  %
+  \allowdisplaybreaks
+  \intertext{ Since $\overline {\;\cdot \;} $ and $\delta $ operators commute: $\delta_{i+1/2}
+    \left[ {\overline a^{\,i}} \right] = \overline {\delta_i \left[ a \right]}^{\,i+1/2}$,
+    and introducing the horizontal divergence $\chi $, it becomes: }
+  \allowdisplaybreaks
+  %
+  & \qquad {
+    \begin{array}{*{20}l}
+      &\equiv \sum\limits_{i,j,k} - \frac{1} {2} q^2 \; \overline{\overline{ e_{1t}\,e_{2t}\,e_{3t}^{}\, \chi}}^{\,i+1/2,j+1/2}
+        \quad \equiv 0 &&
+    \end{array}
+  }
+\end{flalign*}
+The later equality is obtain only when the flow is horizontally non-divergent, \ie\ $\chi$=$0$.
+
+%% =================================================================================================
+\subsubsection{Vorticity Term with EEN scheme (\protect\np[=.true.]{ln_dynvor_een}{ln\_dynvor\_een})}
+\label{subsec:INVARIANTS_vorEEN}
+
+With the EEN scheme, the vorticity terms are represented as:
+\begin{equation}
+  \label{eq:INVARIANTS_dynvor_een2}
+  \left\{ {
+      \begin{aligned}
+        +q\,e_3 \, v 	&\equiv +\frac{1}{e_{1u} }   \sum_{\substack{i_p,\,k_p}}
+        {^{i+1/2-i_p}_j}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{1v} e_{3v} \ v  \right)^{i+i_p-1/2}_{j+j_p}   \\
+        - q\,e_3 \, u     &\equiv -\frac{1}{e_{2v} }    \sum_{\substack{i_p,\,k_p}}
+        {^i_{j+1/2-j_p}}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{2u} e_{3u} \ u  \right)^{i+i_p}_{j+j_p-1/2}   \\
+      \end{aligned}
+    } \right.
+\end{equation}
+where the indices $i_p$ and $k_p$ take the following values:
+$i_p = -1/2$ or $1/2$ and $j_p = -1/2$ or $1/2$,
+and the vorticity triads, ${^i_j}\mathbb{Q}^{i_p}_{j_p}$, defined at $T$-point, are given by:
+\begin{equation}
+  \tag{\ref{eq:INVARIANTS_Q_triads}}
+  _i^j \mathbb{Q}^{i_p}_{j_p}
+  = \frac{1}{12} \ \left(   q^{i-i_p}_{j+j_p} + q^{i+j_p}_{j+i_p} + q^{i+i_p}_{j-j_p}  \right)
+\end{equation}
+
+This formulation does conserve the potential enstrophy for a horizontally non-divergent flow (\ie\ $\chi=0$).
+
+Let consider one of the vorticity triad, for example ${^{i}_j}\mathbb{Q}^{+1/2}_{+1/2} $,
+similar manipulation can be done for the 3 others.
+The discrete form of the right hand side of \autoref{eq:INVARIANTS_1.1} applied to
+this triad only can be transformed as follow:
+
+\begin{flalign*}
+  &\int_D {q\,\;{\textbf{k}}\cdot \frac{1} {e_3} \nabla \times \left( {e_3 \, q \;{\textbf{k}}\times {\textbf{U}}_h } \right)\;dv} \\
+  %
+  \equiv& \sum\limits_{i,j,k}
+  {q} \    \biggl\{ \;\;
+  \delta_{i+1/2} \left[   -\, {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}  \; U^{i+1/2}_{j}}    \right]
+  - \delta_{j+1/2} \left[       {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}  \; V^{i}_{j+1/2}}    \right]
+  \;\;\biggr\}        &&  \\
+  %
+  \equiv& \sum\limits_{i,j,k}
+  \biggl\{   \delta_i [q] \  {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}  \; U^{i+1/2}_{j}}
+  + \delta_j [q] \  {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}  \; V^{i}_{j+1/2}}   \biggr\}
+  && \\
+  %
+  ... & &&\\
+  &Demonstation \ to \ be \ done... &&\\
+  ... & &&\\
+  %
+  \equiv& \frac{1} {2} \sum\limits_{i,j,k}
+  \biggl\{	\delta_i    \Bigl[    \left(  {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}} \right)^2   \Bigr]\;
+  \overline{\overline {U}}^{\,i,j+1/2}
+  + \delta_j 	\Bigl[    \left( {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}} \right)^2     \Bigr]\;
+  \overline{\overline {V}}^{\,i+1/2,j}
+  \biggr\}
+  &&  \\
+  %
+  \equiv& - \frac{1} {2} \sum\limits_{i,j,k} 	\left( {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}} \right)^2\;
+  \biggl\{    \delta_{i+1/2}
+  \left[   \overline{\overline {U}}^{\,i,j+1/2}    \right]
+  + \delta_{j+1/2}
+  \left[   \overline{\overline {V}}^{\,i+1/2,j}     \right]
+  \biggr\}    && \\
+  %
+  \equiv& \sum\limits_{i,j,k} - \frac{1} {2} \left( {{^i_j}\mathbb{Q}^{+1/2}_{+1/2}} \right)^2
+  \; \overline{\overline{ b_t^{}\, \chi}}^{\,i+1/2,\,j+1/2}  &&\\
+  %
+  \ \ \equiv& \ 0     &&\\
+\end{flalign*}
+
+%% =================================================================================================
+\section{Conservation properties on tracers}
+\label{sec:INVARIANTS_5}
+
+All the numerical schemes used in \NEMO\ are written such that the tracer content is conserved by
+the internal dynamics and physics (equations in flux form).
+For advection,
+only the CEN2 scheme (\ie\ $2^{nd}$ order finite different scheme) conserves the global variance of tracer.
+Nevertheless the other schemes ensure that the global variance decreases
+(\ie\ they are at least slightly diffusive).
+For diffusion, all the schemes ensure the decrease of the total tracer variance, except the iso-neutral operator.
+There is generally no strict conservation of mass,
+as the equation of state is non linear with respect to $T$ and $S$.
+In practice, the mass is conserved to a very high accuracy.
+%% =================================================================================================
+\subsection{Advection term}
+\label{subsec:INVARIANTS_5.1}
+
+conservation of a tracer, $T$:
+\[
+  \frac{\partial }{\partial t} \left(   \int_D {T\;dv}   \right)
+  =  \int_D { \frac{1}{e_3}\frac{\partial \left( e_3 \, T \right)}{\partial t} \;dv }=0
+\]
+
+conservation of its variance:
+\begin{flalign*}
+  \frac{\partial }{\partial t} \left( \int_D {\frac{1}{2} T^2\;dv} \right)
+  =&  \int_D { \frac{1}{e_3} Q      \frac{\partial \left( e_3 \, T \right) }{\partial t} \;dv }
+  -   \frac{1}{2} \int_D {  T^2 \frac{1}{e_3} \frac{\partial  e_3 }{\partial t} \;dv }
+\end{flalign*}
+
+Whatever the advection scheme considered it conserves of the tracer content as
+all the scheme are written in flux form.
+Indeed, let $T$ be the tracer and its $\tau_u$, $\tau_v$, and $\tau_w$ interpolated values at velocity point
+(whatever the interpolation is),
+the conservation of the tracer content due to the advection tendency is obtained as follows:
+\begin{flalign*}
+  &\int_D { \frac{1}{e_3}\frac{\partial \left( e_3 \, T \right)}{\partial t} \;dv } = - \int_D \nabla \cdot \left( T \textbf{U} \right)\;dv    &&&\\
+  &\equiv - \sum\limits_{i,j,k}    \biggl\{
+  \frac{1} {b_t}  \left(  \delta_i    \left[   U \;\tau_u   \right]
+    + \delta_j    \left[   V  \;\tau_v   \right] \right)
+  + \frac{1} {e_{3t}} \delta_k \left[ w\;\tau_w \right]    \biggl\}  b_t   &&&\\
+  %
+  &\equiv - \sum\limits_{i,j,k}     \left\{
+    \delta_i  \left[   U \;\tau_u   \right]
+    + \delta_j  \left[   V  \;\tau_v   \right]
+ 	 + \delta_k \left[ W \;\tau_w \right] \right\}   && \\
+  &\equiv 0 &&&
+\end{flalign*}
+
+The conservation of the variance of tracer due to the advection tendency can be achieved only with the CEN2 scheme,
+\ie\ when $\tau_u= \overline T^{\,i+1/2}$, $\tau_v= \overline T^{\,j+1/2}$, and $\tau_w= \overline T^{\,k+1/2}$.
+It can be demonstarted as follows:
+\begin{flalign*}
+  &\int_D { \frac{1}{e_3} Q      \frac{\partial \left( e_3 \, T \right) }{\partial t} \;dv }
+  = - \int\limits_D \tau\;\nabla \cdot \left( T\; \textbf{U} \right)\;dv &&&\\
+  \equiv& - \sum\limits_{i,j,k} T\;
+  \left\{
+    \delta_i  \left[ U  \overline T^{\,i+1/2}  \right]
+    + \delta_j  \left[ V  \overline T^{\,j+1/2}  \right]
+    + \delta_k \left[ W \overline T^{\,k+1/2} \right]          \right\} && \\
+  \equiv& + \sum\limits_{i,j,k}
+  \left\{     U  \overline T^{\,i+1/2} \,\delta_{i+1/2}  \left[ T \right]
+    +  V  \overline T^{\,j+1/2} \;\delta_{j+1/2}  \left[ T \right]
+    +  W \overline T^{\,k+1/2}\;\delta_{k+1/2} \left[ T \right]     \right\}      &&\\
+  \equiv&  + \frac{1} {2}  \sum\limits_{i,j,k}
+  \Bigl\{   U  \;\delta_{i+1/2} \left[ T^2 \right]
+  + V  \;\delta_{j+1/2}  \left[ T^2 \right]
+  + W \;\delta_{k+1/2} \left[ T^2 \right]   \Bigr\}     && \\
+  \equiv& - \frac{1} {2}  \sum\limits_{i,j,k} T^2
+  \Bigl\{    \delta_i  \left[ U  \right]
+  + \delta_j  \left[ V  \right]
+  + \delta_k \left[ W \right]     \Bigr\}      &&&  \\
+  \equiv& + \frac{1} {2}  \sum\limits_{i,j,k} T^2
+  \Bigl\{   \frac{1}{e_{3t}} \frac{\partial e_{3t}\,T }{\partial t}     \Bigr\}      &&& \\
+\end{flalign*}
+which is the discrete form of $ \frac{1}{2} \int_D {  T^2 \frac{1}{e_3} \frac{\partial  e_3 }{\partial t} \;dv }$.
+
+%% =================================================================================================
+\section{Conservation properties on lateral momentum physics}
+\label{sec:INVARIANTS_dynldf_properties}
+
+The discrete formulation of the horizontal diffusion of momentum ensures
+the conservation of potential vorticity and the horizontal divergence,
+and the dissipation of the square of these quantities
+(\ie\ enstrophy and the variance of the horizontal divergence) as well as
+the dissipation of the horizontal kinetic energy.
+In particular, when the eddy coefficients are horizontally uniform,
+it ensures a complete separation of vorticity and horizontal divergence fields,
+so that diffusion (dissipation) of vorticity (enstrophy) does not generate horizontal divergence
+(variance of the horizontal divergence) and \textit{vice versa}.
+
+These properties of the horizontal diffusion operator are a direct consequence of
+properties \autoref{eq:DOM_curl_grad} and \autoref{eq:DOM_div_curl}.
+When the vertical curl of the horizontal diffusion of momentum (discrete sense) is taken,
+the term associated with the horizontal gradient of the divergence is locally zero.
+
+%% =================================================================================================
+\subsection{Conservation of potential vorticity}
+\label{subsec:INVARIANTS_6.1}
+
+The lateral momentum diffusion term conserves the potential vorticity:
+\begin{flalign*}
+  &\int \limits_D \frac{1} {e_3 } \textbf{k} \cdot \nabla \times
+  \Bigl[    \nabla_h  \left( A^{\,lm}\;\chi  \right)
+  - \nabla_h \times \left( A^{\,lm}\;\zeta \; \textbf{k} \right)    \Bigr]\;dv   \\
+  % \end{flalign*}
+  %%%%%%%%%% recheck here....  (gm)
+  % \begin{flalign*}
+  =& \int \limits_D  -\frac{1} {e_3 } \textbf{k} \cdot \nabla \times
+  \Bigl[ \nabla_h \times \left( A^{\,lm}\;\zeta \; \textbf{k} \right)  \Bigr]\;dv  \\
+  % \end{flalign*}
+  % \begin{flalign*}
+  \equiv& \sum\limits_{i,j}
+  \left\{
+    \delta_{i+1/2} \left[  \frac {e_{2v}} {e_{1v}\,e_{3v}}  \delta_i \left[ A_f^{\,lm} e_{3f} \zeta  \right]  \right]
+    + \delta_{j+1/2} \left[  \frac {e_{1u}} {e_{2u}\,e_{3u}}  \delta_j \left[ A_f^{\,lm} e_{3f} \zeta  \right]  \right]
+  \right\} 	 \\
+  %
+  \intertext{Using \autoref{eq:DOM_di_adj}, it follows:}
+  %
+  \equiv& \sum\limits_{i,j,k}
+  -\,\left\{
+    \frac{e_{2v}} {e_{1v}\,e_{3v}}  \delta_i	\left[ A_f^{\,lm} e_{3f} \zeta  \right]\;\delta_i \left[ 1\right]
+	 + \frac{e_{1u}} {e_{2u}\,e_{3u}}  \delta_j 	\left[ A_f^{\,lm} e_{3f} \zeta  \right]\;\delta_j \left[ 1\right]
+  \right\} \quad \equiv 0
+  \\
+\end{flalign*}
+
+%% =================================================================================================
+\subsection{Dissipation of horizontal kinetic energy}
+\label{subsec:INVARIANTS_6.2}
+
+The lateral momentum diffusion term dissipates the horizontal kinetic energy:
+%\begin{flalign*}
+\[
+  \begin{split}
+    \int_D \textbf{U}_h \cdot
+    \left[ \nabla_h 		\right.   &     \left.       \left( A^{\,lm}\;\chi \right)
+      - \nabla_h \times  \left( A^{\,lm}\;\zeta \;\textbf{k} \right)     \right] \; dv    \\
+    \\  %%%
+    \equiv& \sum\limits_{i,j,k}
+    \left\{
+      \frac{1} {e_{1u}}               \delta_{i+1/2} \left[  A_T^{\,lm}          \chi     \right]
+      - \frac{1} {e_{2u}\,e_{3u}}  \delta_j           \left[ A_f^{\,lm} e_{3f} \zeta   \right]
+    \right\} \; e_{1u}\,e_{2u}\,e_{3u} \;u     \\
+    &\;\; + 	\left\{
+	   \frac{1} {e_{2u}}             \delta_{j+1/2}	\left[ A_T^{\,lm}          \chi    \right]
+      + \frac{1} {e_{1v}\,e_{3v}} \delta_i            \left[ A_f^{\,lm} e_{3f} \zeta  \right]
+    \right\} \; e_{1v}\,e_{2u}\,e_{3v} \;v     \qquad \\
+    \\  %%%
+    \equiv& \sum\limits_{i,j,k}
+    \Bigl\{
+    e_{2u}\,e_{3u} \;u\;  \delta_{i+1/2} \left[ A_T^{\,lm}           \chi    \right]
+    - e_{1u}             \;u\;  \delta_j           \left[ A_f^{\,lm} e_{3f} \zeta  \right]
+	 \Bigl\}
+	 \\
+    &\;\; + \Bigl\{
+    e_{1v}\,e_{3v} \;v\;  \delta_{j+1/2}  \left[ A_T^{\,lm}           \chi    \right]
+    + e_{2v}             \;v\;  \delta_i            \left[ A_f^{\,lm} e_{3f} \zeta  \right]
+    \Bigl\}      \\
+    \\  %%%
+    \equiv& \sum\limits_{i,j,k}
+    - \Bigl(
+    \delta_i   \left[  e_{2u}\,e_{3u} \;u  \right]
+    + \delta_j  \left[  e_{1v}\,e_{3v}  \;v  \right]
+    \Bigr) \;  A_T^{\,lm} \chi   \\
+    &\;\; - \Bigl(
+    \delta_{i+1/2}  \left[  e_{2v}  \;v  \right]
+    - \delta_{j+1/2}  \left[  e_{1u} \;u  \right]
+    \Bigr)\;  A_f^{\,lm} e_{3f} \zeta      \\
+    \\  %%%
+    \equiv& \sum\limits_{i,j,k}
+    - A_T^{\,lm}  \,\chi^2   \;e_{1t}\,e_{2t}\,e_{3t}
+    - A_f ^{\,lm}  \,\zeta^2 \;e_{1f }\,e_{2f }\,e_{3f}
+    \quad \leq 0       \\
+  \end{split}
+\]
+
+%% =================================================================================================
+\subsection{Dissipation of enstrophy}
+\label{subsec:INVARIANTS_6.3}
+
+The lateral momentum diffusion term dissipates the enstrophy when the eddy coefficients are horizontally uniform:
+\begin{flalign*}
+  &\int\limits_D  \zeta \; \textbf{k} \cdot \nabla \times
+  \left[   \nabla_h \left( A^{\,lm}\;\chi  \right)
+    - \nabla_h \times \left( A^{\,lm}\;\zeta \; \textbf{k} \right)   \right]\;dv &&&\\
+  &\quad = A^{\,lm} \int \limits_D \zeta \textbf{k} \cdot \nabla \times
+  \left[    \nabla_h \times \left( \zeta \; \textbf{k} \right)   \right]\;dv &&&\\
+  &\quad \equiv A^{\,lm} \sum\limits_{i,j,k}  \zeta \;e_{3f}
+  \left\{     \delta_{i+1/2} \left[  \frac{e_{2v}} {e_{1v}\,e_{3v}} \delta_i \left[ e_{3f} \zeta  \right]   \right]
+    + \delta_{j+1/2} \left[  \frac{e_{1u}} {e_{2u}\,e_{3u}} \delta_j \left[ e_{3f} \zeta  \right]   \right]      \right\}   &&&\\
+  %
+  \intertext{Using \autoref{eq:DOM_di_adj}, it follows:}
+  %
+  &\quad \equiv  - A^{\,lm} \sum\limits_{i,j,k}
+  \left\{    \left(  \frac{1} {e_{1v}\,e_{3v}}  \delta_i \left[ e_{3f} \zeta  \right]  \right)^2   b_v
+    + \left(  \frac{1} {e_{2u}\,e_{3u}}  \delta_j \left[ e_{3f} \zeta  \right] \right)^2   b_u  \right\}  \quad \leq \;0    &&&\\
+\end{flalign*}
+
+%% =================================================================================================
+\subsection{Conservation of horizontal divergence}
+\label{subsec:INVARIANTS_6.4}
+
+When the horizontal divergence of the horizontal diffusion of momentum (discrete sense) is taken,
+the term associated with the vertical curl of the vorticity is zero locally, due to \autoref{eq:DOM_div_curl}.
+The resulting term conserves the $\chi$ and dissipates $\chi^2$ when the eddy coefficients are horizontally uniform.
+\begin{flalign*}
+  & \int\limits_D  \nabla_h \cdot
+  \Bigl[     \nabla_h \left( A^{\,lm}\;\chi \right)
+  - \nabla_h \times \left( A^{\,lm}\;\zeta \;\textbf{k} \right)    \Bigr]  dv
+  = \int\limits_D  \nabla_h \cdot \nabla_h \left( A^{\,lm}\;\chi  \right)   dv   \\
+  %
+  &\equiv \sum\limits_{i,j,k}
+  \left\{   \delta_i \left[ A_u^{\,lm} \frac{e_{2u}\,e_{3u}} {e_{1u}}  \delta_{i+1/2} \left[ \chi \right]  \right]
+    + \delta_j \left[ A_v^{\,lm} \frac{e_{1v}\,e_{3v}} {e_{2v}}  \delta_{j+1/2} \left[ \chi \right]  \right]    \right\}    \\
+  %
+  \intertext{Using \autoref{eq:DOM_di_adj}, it follows:}
+  %
+  &\equiv \sum\limits_{i,j,k}
+  - \left\{   \frac{e_{2u}\,e_{3u}} {e_{1u}}  A_u^{\,lm} \delta_{i+1/2} \left[ \chi \right] \delta_{i+1/2} \left[ 1 \right]
+    + \frac{e_{1v}\,e_{3v}} {e_{2v}}  A_v^{\,lm} \delta_{j+1/2} \left[ \chi \right] \delta_{j+1/2} \left[ 1 \right]    \right\}
+  \quad \equiv 0
+\end{flalign*}
+
+%% =================================================================================================
+\subsection{Dissipation of horizontal divergence variance}
+\label{subsec:INVARIANTS_6.5}
+
+\begin{flalign*}
+  &\int\limits_D \chi \;\nabla_h \cdot
+  \left[    \nabla_h              \left( A^{\,lm}\;\chi                    \right)
+    - \nabla_h   \times  \left( A^{\,lm}\;\zeta \;\textbf{k} \right)    \right]\;  dv
+  = A^{\,lm}   \int\limits_D \chi \;\nabla_h \cdot \nabla_h \left( \chi \right)\;  dv    \\
+  %
+  &\equiv A^{\,lm}  \sum\limits_{i,j,k}  \frac{1} {e_{1t}\,e_{2t}\,e_{3t}}  \chi
+  \left\{
+    \delta_i  \left[   \frac{e_{2u}\,e_{3u}} {e_{1u}}  \delta_{i+1/2} \left[ \chi \right]   \right]
+    + \delta_j  \left[   \frac{e_{1v}\,e_{3v}} {e_{2v}}   \delta_{j+1/2} \left[ \chi \right]   \right]
+  \right\} \;   e_{1t}\,e_{2t}\,e_{3t}    \\
+  %
+  \intertext{Using \autoref{eq:DOM_di_adj}, it turns out to be:}
+  %
+  &\equiv - A^{\,lm} \sum\limits_{i,j,k}
+  \left\{    \left(  \frac{1} {e_{1u}}  \delta_{i+1/2}  \left[ \chi \right]  \right)^2  b_u
+    + \left(  \frac{1} {e_{2v}}  \delta_{j+1/2}  \left[ \chi \right]  \right)^2  b_v    \right\}
+  \quad \leq 0
+\end{flalign*}
+
+%% =================================================================================================
+\section{Conservation properties on vertical momentum physics}
+\label{sec:INVARIANTS_7}
+
+As for the lateral momentum physics,
+the continuous form of the vertical diffusion of momentum satisfies several integral constraints.
+The first two are associated with the conservation of momentum and the dissipation of horizontal kinetic energy:
+\begin{align*}
+  \int\limits_D   \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+  \left(   \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}   \right)\;  dv
+  \qquad \quad &= \vec{\textbf{0}}
+  %
+  \intertext{and}
+  %
+                 \int\limits_D
+                 \textbf{U}_h \cdot   \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+                 \left(   \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}   \right)\; dv    \quad &\leq 0
+\end{align*}
+
+The first property is obvious.
+The second results from:
+\begin{flalign*}
+  \int\limits_D
+  \textbf{U}_h \cdot   \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+  \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}   \right)\;dv    &&&\\
+\end{flalign*}
+\begin{flalign*}
+  &\equiv \sum\limits_{i,j,k}
+  \left(
+    u\; \delta_k \left[ \frac{A_u^{\,vm}} {e_{3uw}} \delta_{k+1/2}  \left[ u \right]  \right]\;  e_{1u}\,e_{2u}
+    + v\; \delta_k \left[ \frac{A_v^{\,vm}} {e_{3vw}} \delta_{k+1/2}   \left[ v \right]  \right]\;  e_{1v}\,e_{2v} \right)   &&&
+  %
+  \intertext{since the horizontal scale factor does not depend on $k$, it follows:}
+  %
+  &\equiv - \sum\limits_{i,j,k}
+  \left(  \frac{A_u^{\,vm}} {e_{3uw}} \left( \delta_{k+1/2} \left[ u \right] \right)^2\; e_{1u}\,e_{2u}
+    + \frac{A_v^{\,vm}} {e_{3vw}}  \left( \delta_{k+1/2} \left[ v \right] \right)^2\; e_{1v}\,e_{2v}  \right)
+  \quad \leq 0   &&&
+\end{flalign*}
+
+The vorticity is also conserved.
+Indeed:
+\begin{flalign*}
+  \int \limits_D
+  \frac{1} {e_3 } \textbf{k} \cdot \nabla \times
+  \left( \frac{1} {e_3 }\; \frac{\partial } {\partial k}  \left(
+      \frac{A^{\,vm}} {e_3}\; \frac{\partial \textbf{U}_h } {\partial k}
+    \right)  \right)\; dv   &&&
+\end{flalign*}
+\begin{flalign*}
+  \equiv \sum\limits_{i,j,k}  \frac{1} {e_{3f}}\; \frac{1} {e_{1f}\,e_{2f}}
+  \bigg\{    \biggr.   \quad
+  \delta_{i+1/2}
+  &\left(   \frac{e_{2v}} {e_{3v}} \delta_k  \left[  \frac{1} {e_{3vw}} \delta_{k+1/2} \left[ v \right]  \right]  \right)   &&\\
+  \biggl.
+  - \delta_{j+1/2}
+  &\left(   \frac{e_{1u}} {e_{3u}} \delta_k \left[  \frac{1} {e_{3uw}}\delta_{k+1/2} \left[ u \right]  \right]   \right)
+  \biggr\} \;
+  e_{1f}\,e_{2f}\,e_{3f} \; \equiv 0   &&
+\end{flalign*}
+
+If the vertical diffusion coefficient is uniform over the whole domain, the enstrophy is dissipated, \ie
+\begin{flalign*}
+  \int\limits_D \zeta \, \textbf{k} \cdot \nabla \times
+  \left(   \frac{1} {e_3}\; \frac{\partial } {\partial k}
+    \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}   \right)   \right)\; dv = 0   &&&
+\end{flalign*}
+
+This property is only satisfied in $z$-coordinates:
+\begin{flalign*}
+  \int\limits_D \zeta \, \textbf{k} \cdot \nabla \times
+  \left(  \frac{1} {e_3}\; \frac{\partial } {\partial k}
+    \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}  \right)   \right)\; dv   &&&
+\end{flalign*}
+\begin{flalign*}
+  \equiv \sum\limits_{i,j,k} \zeta \;e_{3f} \;
+  \biggl\{ 	\biggr.	\quad
+  \delta_{i+1/2}
+  &\left(   \frac{e_{2v}} {e_{3v}} \delta_k \left[ \frac{A_v^{\,vm}} {e_{3vw}} \delta_{k+1/2}[v]  \right]   \right)   &&\\
+  - \delta_{j+1/2}
+  &\biggl.
+  \left(   \frac{e_{1u}} {e_{3u}} \delta_k \left[ \frac{A_u^{\,vm}} {e_{3uw}} \delta_{k+1/2} [u]  \right]    \right) \biggr\}   &&
+\end{flalign*}
+\begin{flalign*}
+  \equiv \sum\limits_{i,j,k} \zeta \;e_{3f}
+  \biggl\{		\biggr.	\quad
+  \frac{1} {e_{3v}} \delta_k
+  &\left[ \frac{A_v^{\,vm}} {e_{3vw}} \delta_{k+1/2} \left[ \delta_{i+1/2} \left[ e_{2v}\,v \right] \right]   \right]    &&\\
+  \biggl.
+  - \frac{1} {e_{3u}} \delta_k
+  &\left[  \frac{A_u^{\,vm}} {e_{3uw}} \delta_{k+1/2} \left[ \delta_{j+1/2} \left[ e_{1u}\,u \right] \right]  \right]  \biggr\}  &&
+\end{flalign*}
+Using the fact that the vertical diffusion coefficients are uniform,
+and that in $z$-coordinate, the vertical scale factors do not depend on $i$ and $j$ so that:
+$e_{3f} =e_{3u} =e_{3v} =e_{3t} $ and $e_{3w} =e_{3uw} =e_{3vw} $, it follows:
+\begin{flalign*}
+  \equiv A^{\,vm} \sum\limits_{i,j,k} \zeta \;\delta_k
+  \left[   \frac{1} {e_{3w}} \delta_{k+1/2} \Bigl[   \delta_{i+1/2} \left[ e_{2v}\,v \right]
+    - \delta_{j+1/ 2} \left[ e_{1u}\,u \right]   \Bigr]    \right]    &&&
+\end{flalign*}
+\begin{flalign*}
+  \equiv - A^{\,vm} \sum\limits_{i,j,k} \frac{1} {e_{3w}}
+  \left( \delta_{k+1/2} \left[ \zeta  \right] \right)^2 \; e_{1f}\,e_{2f}  \; \leq 0    &&&
+\end{flalign*}
+Similarly, the horizontal divergence is obviously conserved:
+
+\begin{flalign*}
+  \int\limits_D \nabla \cdot
+  \left( \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+    \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k} \right) \right)\; dv = 0    &&&
+\end{flalign*}
+and the square of the horizontal divergence decreases (\ie\ the horizontal divergence is dissipated) if
+the vertical diffusion coefficient is uniform over the whole domain:
+
+\begin{flalign*}
+  \int\limits_D \chi \;\nabla \cdot
+  \left( \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+    \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k}  \right) \right)\;  dv = 0  &&&
+\end{flalign*}
+This property is only satisfied in the $z$-coordinate:
+\begin{flalign*}
+  \int\limits_D \chi \;\nabla \cdot
+  \left( \frac{1} {e_3 }\; \frac{\partial } {\partial k}
+    \left( \frac{A^{\,vm}} {e_3 }\; \frac{\partial \textbf{U}_h } {\partial k} \right)  \right)\; dv    &&&
+\end{flalign*}
+\begin{flalign*}
+  \equiv \sum\limits_{i,j,k} \frac{\chi } {e_{1t}\,e_{2t}}
+  \biggl\{ 	\Biggr.	\quad
+  \delta_{i+1/2}
+  &\left(   \frac{e_{2u}} {e_{3u}} \delta_k
+    \left[ \frac{A_u^{\,vm}} {e_{3uw}} \delta_{k+1/2} [u] \right] \right)    &&\\
+  \Biggl.
+  + \delta_{j+1/2}
+  &\left( \frac{e_{1v}} {e_{3v}} \delta_k
+    \left[ \frac{A_v^{\,vm}} {e_{3vw}} \delta_{k+1/2} [v] \right]   \right)
+  \Biggr\} \;  e_{1t}\,e_{2t}\,e_{3t}   &&
+\end{flalign*}
+
+\begin{flalign*}
+  \equiv A^{\,vm} \sum\limits_{i,j,k}  \chi \,
+  \biggl\{	\biggr.	\quad
+  \delta_{i+1/2}
+  &\left(
+    \delta_k \left[
+      \frac{1} {e_{3uw}} \delta_{k+1/2} \left[ e_{2u}\,u \right] \right]   \right)    && \\
+  \biggl.
+  + \delta_{j+1/2}
+  &\left(    \delta_k \left[
+      \frac{1} {e_{3vw}} \delta_{k+1/2} \left[ e_{1v}\,v \right] \right]   \right)   \biggr\}    &&
+\end{flalign*}
+
+\begin{flalign*}
+  \equiv -A^{\,vm} \sum\limits_{i,j,k}
+  \frac{\delta_{k+1/2} \left[ \chi \right]} {e_{3w}}\; \biggl\{
+  \delta_{k+1/2} \Bigl[
+  \delta_{i+1/2} \left[ e_{2u}\,u \right]
+  + \delta_{j+1/2} \left[ e_{1v}\,v \right]  \Bigr]    \biggr\}    &&&
+\end{flalign*}
+
+\begin{flalign*}
+  \equiv -A^{\,vm} \sum\limits_{i,j,k}
+  \frac{1} {e_{3w}} \delta_{k+1/2} \left[ \chi \right]\; \delta_{k+1/2} \left[ e_{1t}\,e_{2t} \;\chi \right]   &&&
+\end{flalign*}
+
+\begin{flalign*}
+  \equiv -A^{\,vm} \sum\limits_{i,j,k}
+  \frac{e_{1t}\,e_{2t}} {e_{3w}}\; \left( \delta_{k+1/2} \left[ \chi \right]  \right)^2     \quad  \equiv 0    &&&
+\end{flalign*}
+
+%% =================================================================================================
+\section{Conservation properties on tracer physics}
+\label{sec:INVARIANTS_8}
+
+The numerical schemes used for tracer subgridscale physics are written such that
+the heat and salt contents are conserved (equations in flux form).
+Since a flux form is used to compute the temperature and salinity,
+the quadratic form of these quantities (\ie\ their variance) globally tends to diminish.
+As for the advection term, there is conservation of mass only if the Equation Of Seawater is linear.
+
+%% =================================================================================================
+\subsection{Conservation of tracers}
+\label{subsec:INVARIANTS_8.1}
+
+constraint of conservation of tracers:
+\begin{flalign*}
+  &\int\limits_D  \nabla  \cdot \left( A\;\nabla T \right)\;dv  &&& \\ \\
+  &\equiv \sum\limits_{i,j,k}
+  \biggl\{ 	\biggr.
+  \delta_i
+  \left[
+    A_u^{\,lT} \frac{e_{2u}\,e_{3u}} {e_{1u}} \delta_{i+1/2}
+    \left[ T \right]
+  \right]
+  + \delta_j
+  \left[
+    A_v^{\,lT} \frac{e_{1v}\,e_{3v}} {e_{2v}} \delta_{j+1/2}
+    \left[ T \right]
+  \right] && \\
+  & \qquad \qquad \qquad \qquad \qquad \qquad \quad \;\;\;
+  + \delta_k
+  \left[
+    A_w^{\,vT} \frac{e_{1t}\,e_{2t}} {e_{3t}} \delta_{k+1/2}
+    \left[ T \right]
+  \right]
+  \biggr\}   \quad  \equiv 0
+  &&
+\end{flalign*}
+
+In fact, this property simply results from the flux form of the operator.
+
+%% =================================================================================================
+\subsection{Dissipation of tracer variance}
+\label{subsec:INVARIANTS_8.2}
+
+constraint on the dissipation of tracer variance:
+\begin{flalign*}
+  \int\limits_D T\;\nabla & \cdot \left( A\;\nabla T \right)\;dv	&&&\\
+  &\equiv   \sum\limits_{i,j,k} \; T
+  \biggl\{  \biggr.
+  \delta_i \left[ A_u^{\,lT} \frac{e_{2u}\,e_{3u}} {e_{1u}} \delta_{i+1/2} \left[T\right] \right]
+  & + \delta_j \left[ A_v^{\,lT} \frac{e_{1v} \,e_{3v}} {e_{2v}} \delta_{j+1/2} \left[T\right] \right]
+  \quad&& \\
+  \biggl.
+  &&+ \delta_k \left[A_w^{\,vT}\frac{e_{1t}\,e_{2t}} {e_{3t}}\delta_{k+1/2}\left[T\right]\right]
+  \biggr\} &&
+\end{flalign*}
+\begin{flalign*}
+  \equiv - \sum\limits_{i,j,k}
+  \biggl\{ 	\biggr.	\quad
+  &    A_u^{\,lT} \left( \frac{1} {e_{1u}} \delta_{i+1/2} \left[ T \right]  \right)^2   e_{1u}\,e_{2u}\,e_{3u}    && \\
+  & + A_v^{\,lT} \left( \frac{1} {e_{2v}} \delta_{j+1/2} \left[ T \right]  \right)^2   e_{1v}\,e_{2v}\,e_{3v}     && \\ \biggl.
+  & + A_w^{\,vT} \left( \frac{1} {e_{3w}} \delta_{k+1/2} \left[ T \right]   \right)^2    e_{1w}\,e_{2w}\,e_{3w}   \biggr\}
+  \quad      \leq 0      &&
+\end{flalign*}
+
+%%%%  end of appendix in gm comment
+%}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_s_coord.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_s_coord.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_s_coord.tex	(revision 14097)
@@ -0,0 +1,588 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Curvilinear $s-$Coordinate Equations}
+\label{apdx:SCOORD}
+
+%    {\em 4.0} & {\em Mike Bell} & {\em review}  \\
+%    {\em 3.x} & {\em Gurvan Madec} & {\em original}  \\
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+\section{Chain rule for $s-$coordinates}
+\label{sec:SCOORD_chain}
+
+In order to establish the set of Primitive Equation in curvilinear $s$-coordinates
+(\ie\ an orthogonal curvilinear coordinate in the horizontal and
+an Arbitrary Lagrangian Eulerian (ALE) coordinate in the vertical),
+we start from the set of equations established in \autoref{subsec:MB_zco_Eq} for
+the special case $k = z$ and thus $e_3 = 1$,
+and we introduce an arbitrary vertical coordinate $a = a(i,j,z,t)$.
+Let us define a new vertical scale factor by $e_3 = \partial z / \partial s$ (which now depends on $(i,j,z,t)$) and
+the horizontal slope of $s-$surfaces by:
+\begin{equation}
+  \label{eq:SCOORD_s_slope}
+  \sigma_1 =\frac{1}{e_1 } \; \left. {\frac{\partial z}{\partial i}} \right|_s
+  \quad \text{and} \quad
+  \sigma_2 =\frac{1}{e_2 } \; \left. {\frac{\partial z}{\partial j}} \right|_s .
+\end{equation}
+
+The model fields (e.g. pressure $p$) can be viewed as functions of $(i,j,z,t)$ (e.g. $p(i,j,z,t)$) or as
+functions of $(i,j,s,t)$ (e.g. $p(i,j,s,t)$). The symbol $\bullet$ will be used to represent any one of
+these fields.  Any ``infinitesimal'' change in $\bullet$ can be written in two forms:
+\begin{equation}
+  \label{eq:SCOORD_s_infin_changes}
+  \begin{aligned}
+    & \delta \bullet =  \delta i \left. \frac{ \partial \bullet }{\partial i} \right|_{j,s,t}
+                + \delta j \left. \frac{ \partial \bullet }{\partial i} \right|_{i,s,t}
+                + \delta s \left. \frac{ \partial \bullet }{\partial s} \right|_{i,j,t}
+                + \delta t \left. \frac{ \partial \bullet }{\partial t} \right|_{i,j,s} , \\
+    & \delta \bullet =  \delta i \left. \frac{ \partial \bullet }{\partial i} \right|_{j,z,t}
+                + \delta j \left. \frac{ \partial \bullet }{\partial i} \right|_{i,z,t}
+                + \delta z \left. \frac{ \partial \bullet }{\partial z} \right|_{i,j,t}
+                + \delta t \left. \frac{ \partial \bullet }{\partial t} \right|_{i,j,z} .
+  \end{aligned}
+\end{equation}
+Using the first form and considering a change $\delta i$ with $j, z$ and $t$ held constant, shows that
+\begin{equation}
+  \label{eq:SCOORD_s_chain_rule1}
+      \left. {\frac{\partial \bullet }{\partial i}} \right|_{j,z,t}  =
+      \left. {\frac{\partial \bullet }{\partial i}} \right|_{j,s,t}
+    + \left. {\frac{\partial s       }{\partial i}} \right|_{j,z,t} \;
+      \left. {\frac{\partial \bullet }{\partial s}} \right|_{i,j,t} .
+\end{equation}
+The term $\left. \partial s / \partial i \right|_{j,z,t}$ can be related to the slope of constant $s$ surfaces,
+(\autoref{eq:SCOORD_s_slope}), by applying the second of (\autoref{eq:SCOORD_s_infin_changes}) with $\bullet$ set to
+$s$ and $j, t$ held constant
+\begin{equation}
+\label{eq:SCOORD_delta_s}
+\delta s|_{j,t} =
+         \delta i \left. \frac{ \partial s }{\partial i} \right|_{j,z,t}
+       + \delta z \left. \frac{ \partial s }{\partial z} \right|_{i,j,t} .
+\end{equation}
+Choosing to look at a direction in the $(i,z)$ plane in which $\delta s = 0$ and using
+(\autoref{eq:SCOORD_s_slope}) we obtain
+\begin{equation}
+\left. \frac{ \partial s }{\partial i} \right|_{j,z,t} =
+         -  \left. \frac{ \partial z }{\partial i} \right|_{j,s,t} \;
+            \left. \frac{ \partial s }{\partial z} \right|_{i,j,t}
+	 = - \frac{e_1 }{e_3 }\sigma_1  .
+\label{eq:SCOORD_ds_di_z}
+\end{equation}
+Another identity, similar in form to (\autoref{eq:SCOORD_ds_di_z}), can be derived
+by choosing $\bullet$ to be $s$ and using the second form of (\autoref{eq:SCOORD_s_infin_changes}) to consider
+changes in which $i , j$ and $s$ are constant. This shows that
+\begin{equation}
+\label{eq:SCOORD_w_in_s}
+w_s = \left. \frac{ \partial z }{\partial t} \right|_{i,j,s} =
+- \left. \frac{ \partial z }{\partial s} \right|_{i,j,t}
+  \left. \frac{ \partial s }{\partial t} \right|_{i,j,z}
+  = - e_3 \left. \frac{ \partial s }{\partial t} \right|_{i,j,z} .
+\end{equation}
+
+In what follows, for brevity, indication of the constancy of the $i, j$ and $t$ indices is
+usually omitted. Using the arguments outlined above one can show that the chain rules needed to establish
+the model equations in the curvilinear $s-$coordinate system are:
+\begin{equation}
+  \label{eq:SCOORD_s_chain_rule2}
+  \begin{aligned}
+    &\left. {\frac{\partial \bullet }{\partial t}} \right|_z  =
+    \left. {\frac{\partial \bullet }{\partial t}} \right|_s
+	 + \frac{\partial \bullet }{\partial s}\; \frac{\partial s}{\partial t} , \\
+    &\left. {\frac{\partial \bullet }{\partial i}} \right|_z  =
+    \left. {\frac{\partial \bullet }{\partial i}} \right|_s
+    +\frac{\partial \bullet }{\partial s}\; \frac{\partial s}{\partial i}=
+    \left. {\frac{\partial \bullet }{\partial i}} \right|_s
+    -\frac{e_1 }{e_3 }\sigma_1 \frac{\partial \bullet }{\partial s} , \\
+    &\left. {\frac{\partial \bullet }{\partial j}} \right|_z  =
+    \left. {\frac{\partial \bullet }{\partial j}} \right|_s
+    + \frac{\partial \bullet }{\partial s}\;\frac{\partial s}{\partial j}=
+    \left. {\frac{\partial \bullet }{\partial j}} \right|_s
+    - \frac{e_2 }{e_3 }\sigma_2 \frac{\partial \bullet }{\partial s} , \\
+    &\;\frac{\partial \bullet }{\partial z}  \;\; = \frac{1}{e_3 }\frac{\partial \bullet }{\partial s} .
+  \end{aligned}
+\end{equation}
+
+%% =================================================================================================
+\section{Continuity equation in $s-$coordinates}
+\label{sec:SCOORD_continuity}
+
+Using (\autoref{eq:SCOORD_s_chain_rule1}) and
+the fact that the horizontal scale factors $e_1$ and $e_2$ do not depend on the vertical coordinate,
+the divergence of the velocity relative to the ($i$,$j$,$z$) coordinate system is transformed as follows in order to
+obtain its expression in the curvilinear $s-$coordinate system:
+
+\begin{subequations}
+  \begin{align*}
+    {
+    \begin{array}{*{20}l}
+      \nabla \cdot {\mathrm {\mathbf U}}
+      &= \frac{1}{e_1 \,e_2 }  \left[ \left. {\frac{\partial (e_2 \,u)}{\partial i}} \right|_z
+        +\left. {\frac{\partial(e_1 \,v)}{\partial j}} \right|_z  \right]
+        + \frac{\partial w}{\partial z} \\ \\
+      &     = \frac{1}{e_1 \,e_2 }  \left[
+		  \left.   \frac{\partial (e_2 \,u)}{\partial i}    \right|_s
+		  - \frac{e_1 }{e_3 } \sigma_1 \frac{\partial (e_2 \,u)}{\partial s}
+        + \left.   \frac{\partial (e_1 \,v)}{\partial j}    \right|_s
+		  - \frac{e_2 }{e_3 } \sigma_2 \frac{\partial (e_1 \,v)}{\partial s}	\right]
+        + \frac{\partial w}{\partial s} \; \frac{\partial s}{\partial z} \\ \\
+      &     = \frac{1}{e_1 \,e_2 }   \left[
+		  \left.   \frac{\partial (e_2 \,u)}{\partial i}    \right|_s
+        + \left.   \frac{\partial (e_1 \,v)}{\partial j}    \right|_s       	\right]
+        + \frac{1}{e_3 }\left[        \frac{\partial w}{\partial s}
+        -  \sigma_1 \frac{\partial u}{\partial s}
+        -  \sigma_2 \frac{\partial v}{\partial s}      \right] \\ \\
+      &     = \frac{1}{e_1 \,e_2 \,e_3 }   \left[
+		  \left.   \frac{\partial (e_2 \,e_3 \,u)}{\partial i}    \right|_s
+		  -\left.    e_2 \,u    \frac{\partial e_3 }{\partial i}     \right|_s
+        + \left.  \frac{\partial (e_1 \,e_3 \,v)}{\partial j}    \right|_s
+		  - \left.    e_1 v      \frac{\partial e_3 }{\partial j}    \right|_s   \right] \\
+      & \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad \qquad
+        + \frac{1}{e_3 } \left[        \frac{\partial w}{\partial s}
+        -  \sigma_1 \frac{\partial u}{\partial s}
+        -  \sigma_2 \frac{\partial v}{\partial s}      \right]      \\
+      %
+      \intertext{Noting that $
+      \frac{1}{e_1} \left.{ \frac{\partial e_3}{\partial i}} \right|_s
+      =\frac{1}{e_1} \left.{ \frac{\partial^2 z}{\partial i\,\partial s}} \right|_s
+      =\frac{\partial}{\partial s} \left( {\frac{1}{e_1 } \left.{ \frac{\partial z}{\partial i} }\right|_s } \right)
+      =\frac{\partial \sigma_1}{\partial s}
+      $ and $
+      \frac{1}{e_2 }\left. {\frac{\partial e_3 }{\partial j}} \right|_s
+      =\frac{\partial \sigma_2}{\partial s}
+      $, it becomes:}
+    %
+      \nabla \cdot {\mathrm {\mathbf U}}
+      & = \frac{1}{e_1 \,e_2 \,e_3 }  \left[
+		  \left.  \frac{\partial (e_2 \,e_3 \,u)}{\partial i} \right|_s
+        +\left.  \frac{\partial (e_1 \,e_3 \,v)}{\partial j} \right|_s        \right] \\
+      & \qquad \qquad \qquad \qquad \quad
+        +\frac{1}{e_3 }\left[ {\frac{\partial w}{\partial s}-u\frac{\partial \sigma_1 }{\partial s}-v\frac{\partial \sigma_2 }{\partial s}-\sigma_1 \frac{\partial u}{\partial s}-\sigma_2 \frac{\partial v}{\partial s}} \right] \\
+      \\
+      & = \frac{1}{e_1 \,e_2 \,e_3 }  \left[
+		  \left.  \frac{\partial (e_2 \,e_3 \,u)}{\partial i} \right|_s
+        +\left.  \frac{\partial (e_1 \,e_3 \,v)}{\partial j} \right|_s        \right]
+        + \frac{1}{e_3 } \; \frac{\partial}{\partial s}   \left[  w -  u\;\sigma_1  - v\;\sigma_2  \right]
+    \end{array}
+        }
+  \end{align*}
+\end{subequations}
+
+Here, $w$ is the vertical velocity relative to the $z-$coordinate system.
+Using the first form of (\autoref{eq:SCOORD_s_infin_changes})
+and the definitions (\autoref{eq:SCOORD_s_slope}) and (\autoref{eq:SCOORD_w_in_s}) for $\sigma_1$, $\sigma_2$ and  $w_s$,
+one can show that the vertical velocity, $w_p$ of a point
+moving with the horizontal velocity of the fluid along an $s$ surface is given by
+\begin{equation}
+\label{eq:SCOORD_w_p}
+\begin{split}
+w_p  = & \left. \frac{ \partial z }{\partial t} \right|_s
+     + \frac{u}{e_1} \left. \frac{ \partial z }{\partial i} \right|_s
+     + \frac{v}{e_2} \left. \frac{ \partial z }{\partial j} \right|_s \\
+     = & w_s + u \sigma_1 + v \sigma_2 .
+\end{split}
+\end{equation}
+ The vertical velocity across this surface is denoted by
+\begin{equation}
+  \label{eq:SCOORD_w_s}
+  \omega  = w - w_p = w - ( w_s + \sigma_1 \,u + \sigma_2 \,v )  .
+\end{equation}
+Hence
+\begin{equation}
+\frac{1}{e_3 } \frac{\partial}{\partial s}   \left[  w -  u\;\sigma_1  - v\;\sigma_2  \right] =
+\frac{1}{e_3 } \frac{\partial}{\partial s} \left[  \omega + w_s \right] =
+   \frac{1}{e_3 } \left[ \frac{\partial \omega}{\partial s}
+ + \left. \frac{ \partial }{\partial t} \right|_s \frac{\partial z}{\partial s} \right] =
+   \frac{1}{e_3 } \frac{\partial \omega}{\partial s} + \frac{1}{e_3 } \left. \frac{ \partial e_3}{\partial t} . \right|_s
+\end{equation}
+
+Using (\autoref{eq:SCOORD_w_s}) in our expression for $\nabla \cdot {\mathrm {\mathbf U}}$ we obtain
+our final expression for the divergence of the velocity in the curvilinear $s-$coordinate system:
+\begin{equation}
+      \nabla \cdot {\mathrm {\mathbf U}} =
+         \frac{1}{e_1 \,e_2 \,e_3 }    \left[
+		  \left.  \frac{\partial (e_2 \,e_3 \,u)}{\partial i} \right|_s
+        +\left.  \frac{\partial (e_1 \,e_3 \,v)}{\partial j} \right|_s        \right]
+        + \frac{1}{e_3 } \frac{\partial \omega }{\partial s}
+        + \frac{1}{e_3 } \left. \frac{\partial e_3}{\partial t} \right|_s .
+\end{equation}
+
+As a result, the continuity equation \autoref{eq:MB_PE_continuity} in the $s-$coordinates is:
+\begin{equation}
+  \label{eq:SCOORD_sco_Continuity}
+  \frac{1}{e_3 } \frac{\partial e_3}{\partial t}
+  + \frac{1}{e_1 \,e_2 \,e_3 }\left[
+    {\left. {\frac{\partial (e_2 \,e_3 \,u)}{\partial i}} \right|_s
+      +  \left. {\frac{\partial (e_1 \,e_3 \,v)}{\partial j}} \right|_s } \right]
+  +\frac{1}{e_3 }\frac{\partial \omega }{\partial s} = 0 .
+\end{equation}
+An additional term has appeared that takes into account
+the contribution of the time variation of the vertical coordinate to the volume budget.
+
+%% =================================================================================================
+\section{Momentum equation in $s-$coordinate}
+\label{sec:SCOORD_momentum}
+
+Here we only consider the first component of the momentum equation,
+the generalization to the second one being straightforward.
+
+$\bullet$ \textbf{Total derivative in vector invariant form}
+
+Let us consider \autoref{eq:MB_dyn_vect}, the first component of the momentum equation in the vector invariant form.
+Its total $z-$coordinate time derivative,
+$\left. \frac{D u}{D t} \right|_z$ can be transformed as follows in order to obtain
+its expression in the curvilinear $s-$coordinate system:
+
+\begin{subequations}
+  \begin{align*}
+    {
+    \begin{array}{*{20}l}
+      \left. \frac{D u}{D t} \right|_z
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \left. \zeta \right|_z v
+        + \frac{1}{2e_1} \left.{ \frac{\partial (u^2+v^2)}{\partial i}} \right|_z
+        + w \;\frac{\partial u}{\partial z} \\ \\
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        -  \frac{1}{e_1 \,e_2 }\left[ { \left.{ \frac{\partial (e_2 \,v)}{\partial i} }\right|_z
+        -\left.{ \frac{\partial (e_1 \,u)}{\partial j} }\right|_z } \right] \; v
+        +  \frac{1}{2e_1} \left.{ \frac{\partial (u^2+v^2)}{\partial i} } \right|_z
+        +  w \;\frac{\partial u}{\partial z}      \\
+        %
+      \intertext{introducing the chain rule (\autoref{eq:SCOORD_s_chain_rule1}) }
+      %
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \frac{1}{e_1\,e_2}\left[ { \left.{ \frac{\partial (e_2 \,v)}{\partial i} } \right|_s
+        -\left.{ \frac{\partial (e_1 \,u)}{\partial j} } \right|_s } \right.
+        \left. {-\frac{e_1}{e_3}\sigma_1 \frac{\partial (e_2 \,v)}{\partial s}
+        +\frac{e_2}{e_3}\sigma_2 \frac{\partial (e_1 \,u)}{\partial s}} \right] \; v  \\
+      & \qquad \qquad \qquad \qquad
+        {
+        + \frac{1}{2e_1} \left(                                  \left.  \frac{\partial (u^2+v^2)}{\partial i} \right|_s
+        - \frac{e_1}{e_3}\sigma_1 \frac{\partial (u^2+v^2)}{\partial s}               \right)
+        + \frac{w}{e_3 } \;\frac{\partial u}{\partial s}
+        } \\ \\
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \left. \zeta \right|_s \;v
+        + \frac{1}{2\,e_1}\left. {\frac{\partial (u^2+v^2)}{\partial i}} \right|_s \\
+      &\qquad \qquad \qquad \quad
+        + \frac{w}{e_3 } \;\frac{\partial u}{\partial s}
+        + \left[   {\frac{\sigma_1 }{e_3 }\frac{\partial v}{\partial s}
+        - \frac{\sigma_2 }{e_3 }\frac{\partial u}{\partial s}}   \right]\;v
+        - \frac{\sigma_1 }{2e_3 }\frac{\partial (u^2+v^2)}{\partial s} \\ \\
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \left. \zeta \right|_s \;v
+        + \frac{1}{2\,e_1}\left. {\frac{\partial (u^2+v^2)}{\partial i}} \right|_s \\
+      &\qquad \qquad \qquad \quad
+        + \frac{1}{e_3} \left[    {w\frac{\partial u}{\partial s}
+        +\sigma_1 v\frac{\partial v}{\partial s} - \sigma_2 v\frac{\partial u}{\partial s}
+        - \sigma_1 u\frac{\partial u}{\partial s} - \sigma_1 v\frac{\partial v}{\partial s}} \right] \\ \\
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \left. \zeta \right|_s \;v
+        + \frac{1}{2\,e_1}\left. {\frac{\partial (u^2+v^2)}{\partial i}} \right|_s
+        + \frac{1}{e_3} \left[  w - \sigma_2 v - \sigma_1 u  \right]
+        \; \frac{\partial u}{\partial s} .  \\
+        %
+      \intertext{Introducing $\omega$, the dia-s-surface velocity given by (\autoref{eq:SCOORD_w_s}) }
+      %
+      &= \left. {\frac{\partial u }{\partial t}} \right|_z
+        - \left. \zeta \right|_s \;v
+        + \frac{1}{2\,e_1}\left. {\frac{\partial (u^2+v^2)}{\partial i}} \right|_s
+        + \frac{1}{e_3 } \left( \omega + w_s \right) \frac{\partial u}{\partial s}   \\
+    \end{array}
+    }
+  \end{align*}
+\end{subequations}
+Applying the time derivative chain rule (first equation of (\autoref{eq:SCOORD_s_chain_rule1})) to $u$ and
+using (\autoref{eq:SCOORD_w_in_s}) provides the expression of the last term of the right hand side,
+\[
+  {
+    \begin{array}{*{20}l}
+      \frac{w_s}{e_3}  \;\frac{\partial u}{\partial s}
+      = - \left. \frac{\partial s}{\partial t} \right|_z \;  \frac{\partial u }{\partial s}
+      = \left. {\frac{\partial u }{\partial t}} \right|_s  - \left. {\frac{\partial u }{\partial t}} \right|_z \ .
+    \end{array}
+  }
+\]
+This leads to the $s-$coordinate formulation of the total $z-$coordinate time derivative,
+\ie\ the total $s-$coordinate time derivative :
+\begin{align}
+  \label{eq:SCOORD_sco_Dt_vect}
+  \left. \frac{D u}{D t} \right|_s
+  = \left. {\frac{\partial u }{\partial t}} \right|_s
+  - \left. \zeta \right|_s \;v
+  + \frac{1}{2\,e_1}\left. {\frac{\partial (u^2+v^2)}{\partial i}} \right|_s
+  + \frac{1}{e_3 } \omega \;\frac{\partial u}{\partial s} .
+\end{align}
+Therefore, the vector invariant form of the total time derivative has exactly the same mathematical form in
+$z-$ and $s-$coordinates.
+This is not the case for the flux form as shown in next paragraph.
+
+$\bullet$ \textbf{Total derivative in flux form}
+
+Let us start from the total time derivative in the curvilinear $s-$coordinate system we have just establish.
+Following the procedure used to establish (\autoref{eq:MB_flux_form}), it can be transformed into :
+% \begin{subequations}
+\begin{align*}
+  {
+  \begin{array}{*{20}l}
+    \left. \frac{D u}{D t} \right|_s  &= \left. {\frac{\partial u }{\partial t}} \right|_s
+    & -  \zeta \;v
+      + \frac{1}{2\;e_1 } \frac{\partial \left( {u^2+v^2} \right)}{\partial i}
+      + \frac{1}{e_3} \omega \;\frac{\partial u}{\partial s} \\ \\
+                                      &= \left. {\frac{\partial u }{\partial t}} \right|_s
+    &+\frac{1}{e_1\;e_2}  \left(    \frac{\partial \left( {e_2 \,u\,u } \right)}{\partial i}
+      + \frac{\partial \left( {e_1 \,u\,v } \right)}{\partial j}     \right)
+      + \frac{1}{e_3 } \frac{\partial \left( {\omega\,u} \right)}{\partial s} \\ \\
+                                      &&- \,u \left[     \frac{1}{e_1 e_2 } \left(    \frac{\partial(e_2 u)}{\partial i}
+                                         + \frac{\partial(e_1 v)}{\partial j}    \right)
+                                         + \frac{1}{e_3}        \frac{\partial \omega}{\partial s}                       \right] \\ \\
+                                      &&- \frac{v}{e_1 e_2 }\left(    v	\;\frac{\partial e_2 }{\partial i}
+                                         -u	\;\frac{\partial e_1 }{\partial j} 	\right) . \\
+  \end{array}
+  }
+\end{align*}
+Introducing the vertical scale factor inside the horizontal derivative of the first two terms
+(\ie\ the horizontal divergence), it becomes :
+\begin{align*}
+  {
+  \begin{array}{*{20}l}
+    % \begin{align*} {\begin{array}{*{20}l}
+    %     {\begin{array}{*{20}l} \left. \frac{D u}{D t} \right|_s
+    &= \left. {\frac{\partial u }{\partial t}} \right|_s
+    &+ \frac{1}{e_1\,e_2\,e_3}  \left(  \frac{\partial( e_2 e_3 \,u^2 )}{\partial i}
+      + \frac{\partial( e_1 e_3 \,u v )}{\partial j}
+      -  e_2 u u \frac{\partial e_3}{\partial i}
+      -  e_1 u v \frac{\partial e_3 }{\partial j}    \right)
+      + \frac{1}{e_3} \frac{\partial \left( {\omega\,u} \right)}{\partial s} \\ \\
+    && - \,u \left[  \frac{1}{e_1 e_2 e_3} \left(   \frac{\partial(e_2 e_3 \, u)}{\partial i}
+       + \frac{\partial(e_1 e_3 \, v)}{\partial j}
+       -  e_2 u \;\frac{\partial e_3 }{\partial i}
+       -  e_1 v \;\frac{\partial e_3 }{\partial j}   \right)
+       + \frac{1}{e_3}        \frac{\partial \omega}{\partial s}                       \right] \\ \\
+    && - \frac{v}{e_1 e_2 }\left( 	v  \;\frac{\partial e_2 }{\partial i}
+       -u  \;\frac{\partial e_1 }{\partial j} 	\right) \\ \\
+    &= \left. {\frac{\partial u }{\partial t}} \right|_s
+    &+ \frac{1}{e_1\,e_2\,e_3}  \left(  \frac{\partial( e_2 e_3 \,u\,u )}{\partial i}
+      + \frac{\partial( e_1 e_3 \,u\,v )}{\partial j}    \right)
+      + \frac{1}{e_3 } \frac{\partial \left( {\omega\,u} \right)}{\partial s} \\ \\
+    && - \,u \left[  \frac{1}{e_1 e_2 e_3} \left(   \frac{\partial(e_2 e_3 \, u)}{\partial i}
+       + \frac{\partial(e_1 e_3 \, v)}{\partial j}  \right)
+       + \frac{1}{e_3}        \frac{\partial \omega}{\partial s}                       \right]
+       - \frac{v}{e_1 e_2 }\left( 	v   \;\frac{\partial e_2 }{\partial i}
+       -u   \;\frac{\partial e_1 }{\partial j} 	\right)     .             \\
+     %
+    \intertext {Introducing a more compact form for the divergence of the momentum fluxes,
+    and using (\autoref{eq:SCOORD_sco_Continuity}), the $s-$coordinate continuity equation,
+    it becomes : }
+  %
+    &= \left. {\frac{\partial u }{\partial t}} \right|_s
+    &+ \left.  \nabla \cdot \left(   {{\mathrm {\mathbf U}}\,u}   \right)    \right|_s
+      + \,u \frac{1}{e_3 } \frac{\partial e_3}{\partial t}
+      - \frac{v}{e_1 e_2 }\left(    v  \;\frac{\partial e_2 }{\partial i}
+      -u  \;\frac{\partial e_1 }{\partial j} 	\right)
+    \\
+  \end{array}
+  }
+\end{align*}
+which leads to the $s-$coordinate flux formulation of the total $s-$coordinate time derivative,
+\ie\ the total $s-$coordinate time derivative in flux form:
+\begin{flalign}
+  \label{eq:SCOORD_sco_Dt_flux}
+  \left. \frac{D u}{D t} \right|_s   = \frac{1}{e_3}  \left. \frac{\partial ( e_3\,u)}{\partial t} \right|_s
+  + \left.  \nabla \cdot \left(   {{\mathrm {\mathbf U}}\,u}   \right)    \right|_s
+  - \frac{v}{e_1 e_2 }\left(    v  \;\frac{\partial e_2 }{\partial i}
+    -u  \;\frac{\partial e_1 }{\partial j}            \right).
+\end{flalign}
+which is the total time derivative expressed in the curvilinear $s-$coordinate system.
+It has the same form as in the $z-$coordinate but for
+the vertical scale factor that has appeared inside the time derivative which
+comes from the modification of (\autoref{eq:SCOORD_sco_Continuity}),
+the continuity equation.
+
+$\bullet$ \textbf{horizontal pressure gradient}
+
+The horizontal pressure gradient term can be transformed as follows:
+\[
+  \begin{split}
+    -\frac{1}{\rho_o \, e_1 }\left. {\frac{\partial p}{\partial i}} \right|_z
+    & =-\frac{1}{\rho_o e_1 }\left[ {\left. {\frac{\partial p}{\partial i}} \right|_s -\frac{e_1 }{e_3 }\sigma_1 \frac{\partial p}{\partial s}} \right] \\
+    & =-\frac{1}{\rho_o \,e_1 }\left. {\frac{\partial p}{\partial i}} \right|_s +\frac{\sigma_1 }{\rho_o \,e_3 }\left( {-g\;\rho \;e_3 } \right) \\
+    &=-\frac{1}{\rho_o \,e_1 }\left. {\frac{\partial p}{\partial i}} \right|_s -\frac{g\;\rho }{\rho_o }\sigma_1 .
+  \end{split}
+\]
+Applying similar manipulation to the second component and
+replacing $\sigma_1$ and $\sigma_2$ by their expression \autoref{eq:SCOORD_s_slope}, it becomes:
+\begin{equation}
+  \label{eq:SCOORD_grad_p_1}
+  \begin{split}
+    -\frac{1}{\rho_o \, e_1 } \left. {\frac{\partial p}{\partial i}} \right|_z
+    &=-\frac{1}{\rho_o \,e_1 } \left(     \left.              {\frac{\partial p}{\partial i}} \right|_s
+      + g\;\rho  \;\left. {\frac{\partial z}{\partial i}} \right|_s    \right) \\
+             %
+    -\frac{1}{\rho_o \, e_2 }\left. {\frac{\partial p}{\partial j}} \right|_z
+    &=-\frac{1}{\rho_o \,e_2 } \left(    \left.               {\frac{\partial p}{\partial j}} \right|_s
+      + g\;\rho \;\left. {\frac{\partial z}{\partial j}} \right|_s   \right) . \\
+  \end{split}
+\end{equation}
+
+An additional term appears in (\autoref{eq:SCOORD_grad_p_1}) which accounts for
+the tilt of $s-$surfaces with respect to geopotential $z-$surfaces.
+
+As in $z$-coordinate,
+the horizontal pressure gradient can be split in two parts following \citet{marsaleix.auclair.ea_OM08}.
+Let defined a density anomaly, $d$, by $d=(\rho - \rho_o)/ \rho_o$,
+and a hydrostatic pressure anomaly, $p_h'$, by $p_h'= g \; \int_z^\eta d \; e_3 \; dk$.
+The pressure is then given by:
+\[
+  \begin{split}
+    p &= g\; \int_z^\eta \rho \; e_3 \; dk = g\; \int_z^\eta \rho_o \left( d + 1 \right) \; e_3 \; dk   \\
+    &= g \, \rho_o \; \int_z^\eta d \; e_3 \; dk + \rho_o g \, \int_z^\eta e_3 \; dk .
+  \end{split}
+\]
+Therefore, $p$ and $p_h'$ are linked through:
+\begin{equation}
+  \label{eq:SCOORD_pressure}
+  p = \rho_o \; p_h' + \rho_o \, g \, ( \eta - z )
+\end{equation}
+and the hydrostatic pressure balance expressed in terms of $p_h'$ and $d$ is:
+\[
+  \frac{\partial p_h'}{\partial k} = - d \, g \, e_3 .
+\]
+
+Substituing \autoref{eq:SCOORD_pressure} in \autoref{eq:SCOORD_grad_p_1} and
+using the definition of the density anomaly it becomes an expression in two parts:
+\begin{equation}
+  \label{eq:SCOORD_grad_p_2}
+  \begin{split}
+    -\frac{1}{\rho_o \, e_1 } \left. {\frac{\partial p}{\partial i}} \right|_z
+    &=-\frac{1}{e_1 } \left(     \left.              {\frac{\partial p_h'}{\partial i}} \right|_s
+      + g\; d  \;\left. {\frac{\partial z}{\partial i}} \right|_s    \right)  - \frac{g}{e_1 } \frac{\partial \eta}{\partial i} ,  \\
+             %
+    -\frac{1}{\rho_o \, e_2 }\left. {\frac{\partial p}{\partial j}} \right|_z
+    &=-\frac{1}{e_2 } \left(    \left.               {\frac{\partial p_h'}{\partial j}} \right|_s
+      + g\; d \;\left. {\frac{\partial z}{\partial j}} \right|_s   \right)  - \frac{g}{e_2 } \frac{\partial \eta}{\partial j} . \\
+  \end{split}
+\end{equation}
+This formulation of the pressure gradient is characterised by the appearance of
+a term depending on the sea surface height only
+(last term on the right hand side of expression \autoref{eq:SCOORD_grad_p_2}).
+This term will be loosely termed \textit{surface pressure gradient} whereas
+the first term will be termed the \textit{hydrostatic pressure gradient} by analogy to
+the $z$-coordinate formulation.
+In fact, the true surface pressure gradient is $1/\rho_o \nabla (\rho \eta)$,
+and $\eta$ is implicitly included in the computation of $p_h'$ through the upper bound of the vertical integration.
+
+$\bullet$ \textbf{The other terms of the momentum equation}
+
+The coriolis and forcing terms as well as the the vertical physics remain unchanged as
+they involve neither time nor space derivatives.
+The form of the lateral physics is discussed in \autoref{apdx:DIFFOPERS}.
+
+$\bullet$ \textbf{Full momentum equation}
+
+To sum up, in a curvilinear $s$-coordinate system,
+the vector invariant momentum equation solved by the model has the same mathematical expression as
+the one in a curvilinear $z-$coordinate, except for the pressure gradient term:
+\begin{subequations}
+  \label{eq:SCOORD_dyn_vect}
+  \begin{multline}
+    \label{eq:SCOORD_PE_dyn_vect_u}
+    \frac{\partial u}{\partial t}=
+    +   \left( {\zeta +f} \right)\,v
+    -   \frac{1}{2\,e_1} \frac{\partial}{\partial i} \left(  u^2+v^2   \right)
+    -   \frac{1}{e_3} \omega \frac{\partial u}{\partial k}       \\
+    -   \frac{1}{e_1 } \left(    \frac{\partial p_h'}{\partial i} + g\; d  \; \frac{\partial z}{\partial i}    \right)
+    -   \frac{g}{e_1 } \frac{\partial \eta}{\partial i}
+    +   D_u^{\vect{U}}  +   F_u^{\vect{U}} ,
+  \end{multline}
+  \begin{multline}
+    \label{eq:SCOORD_dyn_vect_v}
+    \frac{\partial v}{\partial t}=
+    -   \left( {\zeta +f} \right)\,u
+    -   \frac{1}{2\,e_2 }\frac{\partial }{\partial j}\left(  u^2+v^2  \right)
+    -   \frac{1}{e_3 } \omega \frac{\partial v}{\partial k}         \\
+    -   \frac{1}{e_2 } \left(    \frac{\partial p_h'}{\partial j} + g\; d  \; \frac{\partial z}{\partial j}    \right)
+    -   \frac{g}{e_2 } \frac{\partial \eta}{\partial j}
+    +  D_v^{\vect{U}}  +   F_v^{\vect{U}} .
+  \end{multline}
+\end{subequations}
+whereas the flux form momentum equation differs from it by
+the formulation of both the time derivative and the pressure gradient term:
+\begin{subequations}
+  \label{eq:SCOORD_dyn_flux}
+  \begin{multline}
+    \label{eq:SCOORD_PE_dyn_flux_u}
+    \frac{1}{e_3} \frac{\partial \left(  e_3\,u  \right) }{\partial t} =
+    - \nabla \cdot \left(   {{\mathrm {\mathbf U}}\,u}   \right)
+    +   \left\{ {f + \frac{1}{e_1 e_2 }\left(    v  \;\frac{\partial e_2 }{\partial i}
+          -u  \;\frac{\partial e_1 }{\partial j}            \right)} \right\} \,v     \\
+    -   \frac{1}{e_1 } \left(    \frac{\partial p_h'}{\partial i} + g\; d  \; \frac{\partial z}{\partial i}    \right)
+    -   \frac{g}{e_1 } \frac{\partial \eta}{\partial i}
+    +   D_u^{\vect{U}}  +   F_u^{\vect{U}} ,
+  \end{multline}
+  \begin{multline}
+    \label{eq:SCOORD_dyn_flux_v}
+    \frac{1}{e_3}\frac{\partial \left(  e_3\,v  \right) }{\partial t}=
+    -  \nabla \cdot \left(   {{\mathrm {\mathbf U}}\,v}   \right)
+    -   \left\{ {f + \frac{1}{e_1 e_2 }\left(    v  \;\frac{\partial e_2 }{\partial i}
+          -u  \;\frac{\partial e_1 }{\partial j}            \right)} \right\} \,u     \\
+    -   \frac{1}{e_2 } \left(    \frac{\partial p_h'}{\partial j} + g\; d  \; \frac{\partial z}{\partial j}    \right)
+    -   \frac{g}{e_2 } \frac{\partial \eta}{\partial j}
+    +  D_v^{\vect{U}}  +   F_v^{\vect{U}} .
+  \end{multline}
+\end{subequations}
+Both formulation share the same hydrostatic pressure balance expressed in terms of
+hydrostatic pressure and density anomalies, $p_h'$ and $d=( \frac{\rho}{\rho_o}-1 )$:
+\begin{equation}
+  \label{eq:SCOORD_dyn_zph}
+  \frac{\partial p_h'}{\partial k} = - d \, g \, e_3 .
+\end{equation}
+
+It is important to realize that the change in coordinate system has only concerned the position on the vertical.
+It has not affected (\textbf{i},\textbf{j},\textbf{k}), the orthogonal curvilinear set of unit vectors.
+($u$,$v$) are always horizontal velocities so that their evolution is driven by \emph{horizontal} forces,
+in particular the pressure gradient.
+By contrast, $\omega$ is not $w$, the third component of the velocity, but the dia-surface velocity component,
+\ie\ the volume flux across the moving $s$-surfaces per unit horizontal area.
+
+%% =================================================================================================
+\section{Tracer equation}
+\label{sec:SCOORD_tracer}
+
+The tracer equation is obtained using the same calculation as for the continuity equation and then
+regrouping the time derivative terms in the left hand side :
+
+\begin{multline}
+  \label{eq:SCOORD_tracer}
+  \frac{1}{e_3} \frac{\partial \left(  e_3 T  \right)}{\partial t}
+  = -\frac{1}{e_1 \,e_2 \,e_3}
+  \left[           \frac{\partial }{\partial i} \left( {e_2 \,e_3 \;Tu} \right)
+    +   \frac{\partial }{\partial j} \left( {e_1 \,e_3 \;Tv} \right)               \right]       \\
+  -  \frac{1}{e_3}  \frac{\partial }{\partial k} \left(                   Tw  \right)
+  +  D^{T} +F^{T}
+\end{multline}
+
+The expression for the advection term is a straight consequence of (\autoref{eq:SCOORD_sco_Continuity}),
+the expression of the 3D divergence in the $s-$coordinates established above.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_triads.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_triads.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/apdx_triads.tex	(revision 14097)
@@ -0,0 +1,1181 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+%% Local cmds
+\newcommand{\rML}[1][i]{\ensuremath{_{\mathrm{ML}\,#1}}}
+\newcommand{\rMLt}[1][i]{\tilde{r}_{\mathrm{ML}\,#1}}
+%% Move to ../../global/new_cmds.tex to avoid error with \listoffigures
+%\newcommand{\triad}[6][]{\ensuremath{{}_{#2}^{#3}{\mathbb{#4}_{#1}}_{#5}^{\,#6}}
+\newcommand{\triadd}[5]{\ensuremath{{}_{#1}^{#2}{\mathbb{#3}}_{#4}^{\,#5}}}
+\newcommand{\triadt}[5]{\ensuremath{{}_{#1}^{#2}{\tilde{\mathbb{#3}}}_{#4}^{\,#5}}}
+\newcommand{\rtriad}[2][]{\ensuremath{\triad[#1]{i}{k}{#2}{i_p}{k_p}}}
+\newcommand{\rtriadt}[1]{\ensuremath{\triadt{i}{k}{#1}{i_p}{k_p}}}
+
+\begin{document}
+
+\chapter{Iso-Neutral Diffusion and Eddy Advection using Triads}
+\label{apdx:TRIADS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section[Choice of \forcode{namtra\_ldf} namelist parameters]{Choice of \protect\nam{tra_ldf}{tra\_ldf} namelist parameters}
+
+Two scheme are available to perform the iso-neutral diffusion.
+If the namelist logical \np{ln_traldf_triad}{ln\_traldf\_triad} is set true,
+\NEMO\ updates both active and passive tracers using the Griffies triad representation of iso-neutral diffusion and
+the eddy-induced advective skew (GM) fluxes.
+If the namelist logical \np{ln_traldf_iso}{ln\_traldf\_iso} is set true,
+the filtered version of Cox's original scheme (the Standard scheme) is employed (\autoref{sec:LDF_slp}).
+In the present implementation of the Griffies scheme,
+the advective skew fluxes are implemented even if \np{ln_traldf_eiv}{ln\_traldf\_eiv} is false.
+
+Values of iso-neutral diffusivity and GM coefficient are set as described in \autoref{sec:LDF_coef}.
+Note that when GM fluxes are used, the eddy-advective (GM) velocities are output for diagnostic purposes using XIOS,
+even though the eddy advection is accomplished by means of the skew fluxes.
+
+The options specific to the Griffies scheme include:
+\begin{description}
+\item [{\np{ln_triad_iso}{ln\_triad\_iso}}] See \autoref{sec:TRIADS_taper}.
+  If this is set false (the default),
+  then `iso-neutral' mixing is accomplished within the surface mixed-layer along slopes linearly decreasing with
+  depth from the value immediately below the mixed-layer to zero (flat) at the surface (\autoref{sec:TRIADS_lintaper}).
+  This is the same treatment as used in the default implementation
+  \autoref{subsec:LDF_slp_iso}; \autoref{fig:LDF_eiv_slp}.
+  Where \np{ln_triad_iso}{ln\_triad\_iso} is set true,
+  the vertical skew flux is further reduced to ensure no vertical buoyancy flux,
+  giving an almost pure horizontal diffusive tracer flux within the mixed layer.
+  This is similar to the tapering suggested by \citet{gerdes.koberle.ea_CD91}. See \autoref{subsec:TRIADS_Gerdes-taper}
+\item [{\np{ln_botmix_triad}{ln\_botmix\_triad}}] See \autoref{sec:TRIADS_iso_bdry}.
+  If this is set false (the default) then the lateral diffusive fluxes
+  associated with triads partly masked by topography are neglected.
+  If it is set true, however, then these lateral diffusive fluxes are applied,
+  giving smoother bottom tracer fields at the cost of introducing diapycnal mixing.
+\item [{\np{rn_sw_triad}{rn\_sw\_triad}}] blah blah to be added....
+\end{description}
+The options shared with the Standard scheme include:
+\begin{description}
+\item [{\np{ln_traldf_msc}{ln\_traldf\_msc}}] blah blah to be added
+\item [{\np{rn_slpmax}{rn\_slpmax}}]          blah blah to be added
+\end{description}
+
+%% =================================================================================================
+\section{Triad formulation of iso-neutral diffusion}
+\label{sec:TRIADS_iso}
+
+We have implemented into \NEMO\ a scheme inspired by \citet{griffies.gnanadesikan.ea_JPO98},
+but formulated within the \NEMO\ framework, using scale factors rather than grid-sizes.
+
+%% =================================================================================================
+\subsection{Iso-neutral diffusion operator}
+
+The iso-neutral second order tracer diffusive operator for small angles between
+iso-neutral surfaces and geopotentials is given by \autoref{eq:TRIADS_iso_tensor_1}:
+\begin{subequations}
+  \label{eq:TRIADS_iso_tensor_1}
+  \begin{equation}
+    D^{lT}=-\nabla \cdot\vect{f}^{lT}\equiv
+    -\frac{1}{e_1e_2e_3}\left[\pd{i}\left (f_1^{lT}e_2e_3\right) +
+      \pd{j}\left (f_2^{lT}e_2e_3\right) + \pd{k}\left (f_3^{lT}e_1e_2\right)\right],
+  \end{equation}
+  where the diffusive flux per unit area of physical space
+  \begin{equation}
+    \vect{f}^{lT}=-{A^{lT}}\Re\cdot\nabla T,
+  \end{equation}
+  \begin{equation}
+    \label{eq:TRIADS_iso_tensor_2}
+    \mbox{with}\quad \;\;\Re =
+    \begin{pmatrix}
+      1   &  0   & -r_1           \rule[-.9 em]{0pt}{1.79 em} \\
+      0   &  1   & -r_2           \rule[-.9 em]{0pt}{1.79 em} \\
+      -r_1 & -r_2 &  r_1 ^2+r_2 ^2 \rule[-.9 em]{0pt}{1.79 em}
+    \end{pmatrix}
+    \quad \text{and} \quad\nabla T=
+    \begin{pmatrix}
+      \frac{1}{e_1} \pd[T]{i} \rule[-.9 em]{0pt}{1.79 em} \\
+      \frac{1}{e_2} \pd[T]{j} \rule[-.9 em]{0pt}{1.79 em} \\
+      \frac{1}{e_3} \pd[T]{k} \rule[-.9 em]{0pt}{1.79 em}
+    \end{pmatrix}
+    .
+  \end{equation}
+\end{subequations}
+% \left( {{\begin{array}{*{20}c}
+%  1 \hfill & 0 \hfill & {-r_1 } \hfill \\
+%  0 \hfill & 1 \hfill & {-r_2 } \hfill \\
+%  {-r_1 } \hfill & {-r_2 } \hfill & {r_1 ^2+r_2 ^2} \hfill \\
+% \end{array} }} \right)
+Here \autoref{eq:MB_iso_slopes}
+\begin{align*}
+  r_1 &=-\frac{e_3 }{e_1 } \left( \frac{\partial \rho }{\partial i}
+        \right)
+        \left( {\frac{\partial \rho }{\partial k}} \right)^{-1} \\
+      &=-\frac{e_3 }{e_1 } \left( -\alpha\frac{\partial T }{\partial i} +
+        \beta\frac{\partial S }{\partial i} \right) \left(
+        -\alpha\frac{\partial T }{\partial k} + \beta\frac{\partial S
+        }{\partial k} \right)^{-1}
+\end{align*}
+is the $i$-component of the slope of the iso-neutral surface relative to the computational surface,
+and $r_2$ is the $j$-component.
+
+We will find it useful to consider the fluxes per unit area in $i,j,k$ space; we write
+\[
+  % \label{eq:TRIADS_Fijk}
+  \vect{F}_{\mathrm{iso}}=\left(f_1^{lT}e_2e_3, f_2^{lT}e_1e_3, f_3^{lT}e_1e_2\right).
+\]
+Additionally, we will sometimes write the contributions towards the fluxes $\vect{f}$ and
+$\vect{F}_{\mathrm{iso}}$ from the component $R_{ij}$ of $\Re$ as $f_{ij}$, $F_{\mathrm{iso}\: ij}$,
+with $f_{ij}=R_{ij}e_i^{-1}\partial T/\partial x_i$ (no summation) etc.
+
+The off-diagonal terms of the small angle diffusion tensor
+\autoref{eq:TRIADS_iso_tensor_1}, \autoref{eq:TRIADS_iso_tensor_2} produce skew-fluxes along
+the $i$- and $j$-directions resulting from the vertical tracer gradient:
+\begin{align}
+  \label{eq:TRIADS_i13c}
+  f_{13}=&+{A^{lT}} r_1\frac{1}{e_3}\frac{\partial T}{\partial k},\qquad f_{23}=+{A^{lT}} r_2\frac{1}{e_3}\frac{\partial T}{\partial k}\\
+  \intertext{and in the k-direction resulting from the lateral tracer gradients}
+  \label{eq:TRIADS_i31c}
+  f_{31}+f_{32}=& {A^{lT}} r_1\frac{1}{e_1}\frac{\partial T}{\partial i}+{A^{lT}} r_2\frac{1}{e_1}\frac{\partial T}{\partial i}
+\end{align}
+
+The vertical diffusive flux associated with the $_{33}$ component of the small angle diffusion tensor is
+\begin{equation}
+  \label{eq:TRIADS_i33c}
+  f_{33}=-{A^{lT}}(r_1^2 +r_2^2) \frac{1}{e_3}\frac{\partial T}{\partial k}.
+\end{equation}
+
+Since there are no cross terms involving $r_1$ and $r_2$ in the above,
+we can consider the iso-neutral diffusive fluxes separately in the $i$-$k$ and $j$-$k$ planes,
+just adding together the vertical components from each plane.
+The following description will describe the fluxes on the $i$-$k$ plane.
+
+There is no natural discretization for the $i$-component of the skew-flux, \autoref{eq:TRIADS_i13c},
+as although it must be evaluated at $u$-points,
+it involves vertical gradients (both for the tracer and the slope $r_1$), defined at $w$-points.
+Similarly, the vertical skew flux, \autoref{eq:TRIADS_i31c},
+is evaluated at $w$-points but involves horizontal gradients defined at $u$-points.
+
+%% =================================================================================================
+\subsection{Standard discretization}
+
+The straightforward approach to discretize the lateral skew flux
+\autoref{eq:TRIADS_i13c} from tracer cell $i,k$ to $i+1,k$, introduced in 1995 into OPA,
+\autoref{eq:TRA_ldf_iso}, is to calculate a mean vertical gradient at the $u$-point from
+the average of the four surrounding vertical tracer gradients, and multiply this by a mean slope at the $u$-point,
+calculated from the averaged surrounding vertical density gradients.
+The total area-integrated skew-flux (flux per unit area in $ijk$ space) from tracer cell $i,k$ to $i+1,k$,
+noting that the $e_{{3}_{i+1/2}^k}$ in the area $e{_{3}}_{i+1/2}^k{e_{2}}_{i+1/2}i^k$ at the $u$-point cancels out with
+the $1/{e_{3}}_{i+1/2}^k$ associated with the vertical tracer gradient, is then \autoref{eq:TRA_ldf_iso}
+\[
+  \left(F_u^{13} \right)_{i+\frac{1}{2}}^k = {A}_{i+\frac{1}{2}}^k
+  {e_{2}}_{i+1/2}^k \overline{\overline
+    r_1} ^{\,i,k}\,\overline{\overline{\delta_k T}}^{\,i,k},
+\]
+where
+\[
+  \overline{\overline
+    r_1} ^{\,i,k} = -\frac{{e_{3u}}_{i+1/2}^k}{{e_{1u}}_{i+1/2}^k}
+  \frac{\delta_{i+1/2} [\rho]}{\overline{\overline{\delta_k \rho}}^{\,i,k}},
+\]
+and here and in the following we drop the $^{lT}$ superscript from ${A^{lT}}$ for simplicity.
+Unfortunately the resulting combination $\overline{\overline{\delta_k\bullet}}^{\,i,k}$ of a $k$ average and
+a $k$ difference of the tracer reduces to $\bullet_{k+1}-\bullet_{k-1}$,
+so two-grid-point oscillations are invisible to this discretization of the iso-neutral operator.
+These \emph{computational modes} will not be damped by this operator, and may even possibly be amplified by it.
+Consequently, applying this operator to a tracer does not guarantee the decrease of its global-average variance.
+To correct this, we introduced a smoothing of the slopes of the iso-neutral surfaces (see \autoref{chap:LDF}).
+This technique works for $T$ and $S$ in so far as they are active tracers
+(\ie\ they enter the computation of density), but it does not work for a passive tracer.
+
+%% =================================================================================================
+\subsection{Expression of the skew-flux in terms of triad slopes}
+
+\citep{griffies.gnanadesikan.ea_JPO98} introduce a different discretization of the off-diagonal terms that
+nicely solves the problem.
+% Instead of multiplying the mean slope calculated at the $u$-point by
+% the mean vertical gradient at the $u$-point,
+\begin{figure}[tb]
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRIADS_GRIFF_triad_fluxes}
+  \caption[Triads arrangement and tracer gradients to give lateral and vertical tracer fluxes]{
+    (a) Arrangement of triads $S_i$ and tracer gradients to
+    give lateral tracer flux from box $i,k$ to $i+1,k$
+    (b) Triads $S'_i$ and tracer gradients to give vertical tracer flux from
+    box $i,k$ to $i,k+1$.}
+  \label{fig:TRIADS_ISO_triad}
+\end{figure}
+They get the skew flux from the products of the vertical gradients at each $w$-point surrounding the $u$-point with
+the corresponding `triad' slope calculated from the lateral density gradient across the $u$-point divided by
+the vertical density gradient at the same $w$-point as the tracer gradient.
+See \autoref{fig:TRIADS_ISO_triad}a, where the thick lines denote the tracer gradients,
+and the thin lines the corresponding triads, with slopes $s_1, \dotsc s_4$.
+The total area-integrated skew-flux from tracer cell $i,k$ to $i+1,k$
+\begin{multline}
+  \label{eq:TRIADS_i13}
+  \left( F_u^{13}  \right)_{i+\frac{1}{2}}^k = {A}_{i+1}^k a_1 s_1
+  \delta_{k+\frac{1}{2}} \left[ T^{i+1}
+  \right]/e_{{3w}_{i+1}}^{k+\frac{1}{2}}  + {A} _i^k a_2 s_2 \delta
+  _{k+\frac{1}{2}} \left[ T^i
+  \right]/e_{{3w}_{i+1}}^{k+\frac{1}{2}} \\
+  +{A} _{i+1}^k a_3 s_3 \delta_{k-\frac{1}{2}} \left[ T^{i+1}
+  \right]/e_{{3w}_{i+1}}^{k+\frac{1}{2}}  +{A} _i^k a_4 s_4 \delta
+  _{k-\frac{1}{2}} \left[ T^i \right]/e_{{3w}_{i+1}}^{k+\frac{1}{2}},
+\end{multline}
+where the contributions of the triad fluxes are weighted by areas $a_1, \dotsc a_4$,
+and ${A}$ is now defined at the tracer points rather than the $u$-points.
+This discretization gives a much closer stencil, and disallows the two-point computational modes.
+
+The vertical skew flux \autoref{eq:TRIADS_i31c} from tracer cell $i,k$ to $i,k+1$ at
+the $w$-point $i,k+\frac{1}{2}$ is constructed similarly (\autoref{fig:TRIADS_ISO_triad}b) by
+multiplying lateral tracer gradients from each of the four surrounding $u$-points by the appropriate triad slope:
+\begin{multline}
+  \label{eq:TRIADS_i31}
+  \left( F_w^{31} \right) _i ^{k+\frac{1}{2}} =  {A}_i^{k+1} a_{1}'
+  s_{1}' \delta_{i-\frac{1}{2}} \left[ T^{k+1} \right]/{e_{3u}}_{i-\frac{1}{2}}^{k+1}
+  +{A}_i^{k+1} a_{2}' s_{2}' \delta_{i+\frac{1}{2}} \left[ T^{k+1} \right]/{e_{3u}}_{i+\frac{1}{2}}^{k+1} \\
+  + {A}_i^k a_{3}' s_{3}' \delta_{i-\frac{1}{2}} \left[ T^k\right]/{e_{3u}}_{i-\frac{1}{2}}^k
+  +{A}_i^k a_{4}' s_{4}' \delta_{i+\frac{1}{2}} \left[ T^k \right]/{e_{3u}}_{i+\frac{1}{2}}^k.
+\end{multline}
+
+We notate the triad slopes $s_i$ and $s'_i$ in terms of the `anchor point' $i,k$
+(appearing in both the vertical and lateral gradient),
+and the $u$- and $w$-points $(i+i_p,k)$, $(i,k+k_p)$ at the centres of the `arms' of the triad as follows
+(see also \autoref{fig:TRIADS_ISO_triad}):
+\begin{equation}
+  \label{eq:TRIADS_R}
+  _i^k \mathbb{R}_{i_p}^{k_p}
+  =-\frac{ {e_{3w}}_{\,i}^{\,k+k_p}} { {e_{1u}}_{\,i+i_p}^{\,k}}
+  \
+  \frac
+  { \alpha_i^k  \ \delta_{i+i_p}[T^k] - \beta_i^k \ \delta_{i+i_p}[S^k] }
+  { \alpha_i^k  \ \delta_{k+k_p}[T^i] - \beta_i^k \ \delta_{k+k_p}[S^i] }.
+\end{equation}
+In calculating the slopes of the local neutral surfaces,
+the expansion coefficients $\alpha$ and $\beta$ are evaluated at the anchor points of the triad,
+while the metrics are calculated at the $u$- and $w$-points on the arms.
+
+\begin{figure}[tb]
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRIADS_GRIFF_qcells}
+  \caption[Triad notation for quarter cells]{
+    Triad notation for quarter cells.
+    $T$-cells are inside boxes,
+    while the $i+\fractext{1}{2},k$ $u$-cell is shaded in green and
+    the $i,k+\fractext{1}{2}$ $w$-cell is shaded in pink.}
+  \label{fig:TRIADS_qcells}
+\end{figure}
+
+Each triad $\{_i^{k}\:_{i_p}^{k_p}\}$ is associated (\autoref{fig:TRIADS_qcells}) with the quarter cell that is
+the intersection of the $i,k$ $T$-cell, the $i+i_p,k$ $u$-cell and the $i,k+k_p$ $w$-cell.
+Expressing the slopes $s_i$ and $s'_i$ in \autoref{eq:TRIADS_i13} and \autoref{eq:TRIADS_i31} in this notation,
+we have \eg\ \ $s_1=s'_1={\:}_i^k \mathbb{R}_{1/2}^{1/2}$.
+Each triad slope $_i^k\mathbb{R}_{i_p}^{k_p}$ is used once (as an $s$) to
+calculate the lateral flux along its $u$-arm, at $(i+i_p,k)$,
+and then again as an $s'$ to calculate the vertical flux along its $w$-arm at $(i,k+k_p)$.
+Each vertical area $a_i$ used to calculate the lateral flux and horizontal area $a'_i$ used to
+calculate the vertical flux can also be identified as the area across the $u$- and $w$-arms of a unique triad,
+and we notate these areas, similarly to the triad slopes,
+as $_i^k{\mathbb{A}_u}_{i_p}^{k_p}$, $_i^k{\mathbb{A}_w}_{i_p}^{k_p}$,
+where \eg\ in \autoref{eq:TRIADS_i13} $a_{1}={\:}_i^k{\mathbb{A}_u}_{1/2}^{1/2}$,
+and in \autoref{eq:TRIADS_i31} $a'_{1}={\:}_i^k{\mathbb{A}_w}_{1/2}^{1/2}$.
+
+%% =================================================================================================
+\subsection{Full triad fluxes}
+
+A key property of iso-neutral diffusion is that it should not affect the (locally referenced) density.
+In particular there should be no lateral or vertical density flux.
+The lateral density flux disappears so long as the area-integrated lateral diffusive flux from
+tracer cell $i,k$ to $i+1,k$ coming from the $_{11}$ term of the diffusion tensor takes the form
+\begin{equation}
+  \label{eq:TRIADS_i11}
+  \left( F_u^{11} \right) _{i+\frac{1}{2}} ^{k} =
+  - \left( {A}_i^{k+1} a_{1} + {A}_i^{k+1} a_{2} + {A}_i^k
+    a_{3} + {A}_i^k a_{4} \right)
+  \frac{\delta_{i+1/2} \left[ T^k\right]}{{e_{1u}}_{\,i+1/2}^{\,k}},
+\end{equation}
+where the areas $a_i$ are as in \autoref{eq:TRIADS_i13}.
+In this case, separating the total lateral flux, the sum of \autoref{eq:TRIADS_i13} and \autoref{eq:TRIADS_i11},
+into triad components, a lateral tracer flux
+\begin{equation}
+  \label{eq:TRIADS_latflux-triad}
+  _i^k {\mathbb{F}_u}_{i_p}^{k_p} (T) = - {A}_i^k{ \:}_i^k{\mathbb{A}_u}_{i_p}^{k_p}
+  \left(
+    \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+    -\ {_i^k\mathbb{R}_{i_p}^{k_p}} \
+    \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+  \right)
+\end{equation}
+can be identified with each triad.
+Then, because the same metric factors ${e_{3w}}_{\,i}^{\,k+k_p}$ and ${e_{1u}}_{\,i+i_p}^{\,k}$ are employed for both
+the density gradients in $ _i^k \mathbb{R}_{i_p}^{k_p}$ and the tracer gradients,
+the lateral density flux associated with each triad separately disappears.
+\begin{equation}
+  \label{eq:TRIADS_latflux-rho}
+  {\mathbb{F}_u}_{i_p}^{k_p} (\rho)=-\alpha _i^k {\:}_i^k {\mathbb{F}_u}_{i_p}^{k_p} (T) + \beta_i^k {\:}_i^k {\mathbb{F}_u}_{i_p}^{k_p} (S)=0
+\end{equation}
+Thus the total flux $\left( F_u^{31} \right) ^i _{i,k+\frac{1}{2}} + \left( F_u^{11} \right) ^i _{i,k+\frac{1}{2}}$ from
+tracer cell $i,k$ to $i+1,k$ must also vanish since it is a sum of four such triad fluxes.
+
+The squared slope $r_1^2$ in the expression \autoref{eq:TRIADS_i33c} for the $_{33}$ component is also expressed in
+terms of area-weighted squared triad slopes,
+so the area-integrated vertical flux from tracer cell $i,k$ to $i,k+1$ resulting from the $r_1^2$ term is
+\begin{equation}
+  \label{eq:TRIADS_i33}
+  \left( F_w^{33} \right) _i^{k+\frac{1}{2}} =
+  - \left( {A}_i^{k+1} a_{1}' s_{1}'^2
+    + {A}_i^{k+1} a_{2}' s_{2}'^2
+    + {A}_i^k a_{3}' s_{3}'^2
+    + {A}_i^k a_{4}' s_{4}'^2 \right)\delta_{k+\frac{1}{2}} \left[ T^{i+1} \right],
+\end{equation}
+where the areas $a'$ and slopes $s'$ are the same as in \autoref{eq:TRIADS_i31}.
+Then, separating the total vertical flux, the sum of \autoref{eq:TRIADS_i31} and \autoref{eq:TRIADS_i33},
+into triad components, a vertical flux
+\begin{align}
+  \label{eq:TRIADS_vertflux-triad}
+  _i^k {\mathbb{F}_w}_{i_p}^{k_p} (T)
+  &= {A}_i^k{\: }_i^k{\mathbb{A}_w}_{i_p}^{k_p}
+    \left(
+    {_i^k\mathbb{R}_{i_p}^{k_p}}\frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+    -\ \left({_i^k\mathbb{R}_{i_p}^{k_p}}\right)^2 \
+    \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+    \right) \\
+  &= - \left(\left.{ }_i^k{\mathbb{A}_w}_{i_p}^{k_p}\right/{ }_i^k{\mathbb{A}_u}_{i_p}^{k_p}\right)
+    {_i^k\mathbb{R}_{i_p}^{k_p}}{\: }_i^k{\mathbb{F}_u}_{i_p}^{k_p} (T) \label{eq:TRIADS_vertflux-triad2}
+\end{align}
+may be associated with each triad.
+Each vertical density flux $_i^k {\mathbb{F}_w}_{i_p}^{k_p} (\rho)$ associated with a triad then
+separately disappears (because the lateral flux $_i^k{\mathbb{F}_u}_{i_p}^{k_p} (\rho)$ disappears).
+Consequently the total vertical density flux
+$\left( F_w^{31} \right)_i ^{k+\frac{1}{2}} + \left( F_w^{33} \right)_i^{k+\frac{1}{2}}$ from
+tracer cell $i,k$ to $i,k+1$ must also vanish since it is a sum of four such triad fluxes.
+
+We can explicitly identify (\autoref{fig:TRIADS_qcells}) the triads associated with the $s_i$, $a_i$,
+and $s'_i$, $a'_i$ used in the definition of the $u$-fluxes and $w$-fluxes in \autoref{eq:TRIADS_i31},
+\autoref{eq:TRIADS_i13}, \autoref{eq:TRIADS_i11} \autoref{eq:TRIADS_i33} and \autoref{fig:TRIADS_ISO_triad} to write out
+the iso-neutral fluxes at $u$- and $w$-points as sums of the triad fluxes that cross the $u$- and $w$-faces:
+%(\autoref{fig:TRIADS_ISO_triad}):
+\begin{flalign}
+  \label{eq:TRIADS_iso_flux} \vect{F}_{\mathrm{iso}}(T) &\equiv
+  \sum_{\substack{i_p,\,k_p}}
+  \begin{pmatrix}
+    {_{i+1/2-i_p}^k {\mathbb{F}_u}_{i_p}^{k_p} } (T) \\ \\
+    {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p} } (T) \\
+  \end{pmatrix}.
+\end{flalign}
+
+%% =================================================================================================
+\subsection{Ensuring the scheme does not increase tracer variance}
+\label{subsec:TRIADS_variance}
+
+We now require that this operator should not increase the globally-integrated tracer variance.
+%This changes according to
+% \begin{align*}
+% &\int_D  D_l^T \; T \;dv \equiv  \sum_{i,k} \left\{ T \ D_l^T \ b_T \right\}    \\
+% &\equiv + \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+% 		\delta_{i} \left[{_{i+1/2-i_p}^k {\mathbb{F}_u }_{i_p}^{k_p}} \right]
+% 	     + \delta_{k} \left[ {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}} \right]  \ T \right\}    \\
+% &\equiv  - \sum_{i,k} \sum_{\substack{i_p,\,k_p}} \left\{
+%                 {_{i+1/2-i_p}^k {\mathbb{F}_u }_{i_p}^{k_p}} \ \delta_{i+1/2} [T]
+%              + {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}}  \ \delta_{k+1/2} [T]   \right\}      \\
+% \end{align*}
+Each triad slope $_i^k\mathbb{R}_{i_p}^{k_p}$ drives a lateral flux $_i^k{\mathbb{F}_u}_{i_p}^{k_p} (T)$ across
+the $u$-point $i+i_p,k$ and a vertical flux $_i^k{\mathbb{F}_w}_{i_p}^{k_p} (T)$ across the $w$-point $i,k+k_p$.
+The lateral flux drives a net rate of change of variance,
+summed over the two $T$-points $i+i_p-\fractext{1}{2},k$ and $i+i_p+\fractext{1}{2},k$, of
+\begin{multline}
+  {b_T}_{i+i_p-1/2}^k\left(\frac{\partial T}{\partial t}T\right)_{i+i_p-1/2}^k+
+  \quad {b_T}_{i+i_p+1/2}^k\left(\frac{\partial T}{\partial
+      t}T\right)_{i+i_p+1/2}^k \\
+  \begin{aligned}
+    &= -T_{i+i_p-1/2}^k{\;} _i^k{\mathbb{F}_u}_{i_p}^{k_p} (T) \quad + \quad  T_{i+i_p+1/2}^k
+    {\;}_i^k{\mathbb{F}_u}_{i_p}^{k_p} (T) \\
+    &={\;} _i^k{\mathbb{F}_u}_{i_p}^{k_p} (T)\,\delta_{i+ i_p}[T^k], \label{eq:TRIADS_dvar_iso_i}
+  \end{aligned}
+\end{multline}
+while the vertical flux similarly drives a net rate of change of variance summed over
+the $T$-points $i,k+k_p-\fractext{1}{2}$ (above) and $i,k+k_p+\fractext{1}{2}$ (below) of
+\begin{equation}
+  \label{eq:TRIADS_dvar_iso_k}
+  _i^k{\mathbb{F}_w}_{i_p}^{k_p} (T) \,\delta_{k+ k_p}[T^i].
+\end{equation}
+The total variance tendency driven by the triad is the sum of these two.
+Expanding $_i^k{\mathbb{F}_u}_{i_p}^{k_p} (T)$ and $_i^k{\mathbb{F}_w}_{i_p}^{k_p} (T)$ with
+\autoref{eq:TRIADS_latflux-triad} and \autoref{eq:TRIADS_vertflux-triad}, it is
+\begin{multline*}
+  -{A}_i^k\left \{
+    { } _i^k{\mathbb{A}_u}_{i_p}^{k_p}
+    \left(
+      \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+      - {_i^k\mathbb{R}_{i_p}^{k_p}} \
+      \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }\right)\,\delta_{i+ i_p}[T^k] \right.\\
+  - \left. { } _i^k{\mathbb{A}_w}_{i_p}^{k_p}
+    \left(
+      \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+      -{\:}_i^k\mathbb{R}_{i_p}^{k_p}
+      \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+    \right) {\,}_i^k\mathbb{R}_{i_p}^{k_p}\delta_{k+ k_p}[T^i]
+  \right \}.
+\end{multline*}
+The key point is then that if we require $_i^k{\mathbb{A}_u}_{i_p}^{k_p}$ and $_i^k{\mathbb{A}_w}_{i_p}^{k_p}$ to
+be related to a triad volume $_i^k\mathbb{V}_{i_p}^{k_p}$ by
+\begin{equation}
+  \label{eq:TRIADS_V-A}
+  _i^k\mathbb{V}_{i_p}^{k_p}
+  ={\;}_i^k{\mathbb{A}_u}_{i_p}^{k_p}\,{e_{1u}}_{\,i + i_p}^{\,k}
+  ={\;}_i^k{\mathbb{A}_w}_{i_p}^{k_p}\,{e_{3w}}_{\,i}^{\,k + k_p},
+\end{equation}
+the variance tendency reduces to the perfect square
+\begin{equation}
+  \label{eq:TRIADS_perfect-square}
+  -{A}_i^k{\:} _i^k\mathbb{V}_{i_p}^{k_p}
+  \left(
+    \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+    -{\:}_i^k\mathbb{R}_{i_p}^{k_p}
+    \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+  \right)^2\leq 0.
+\end{equation}
+Thus, the constraint \autoref{eq:TRIADS_V-A} ensures that the fluxes
+(\autoref{eq:TRIADS_latflux-triad}, \autoref{eq:TRIADS_vertflux-triad}) associated with
+a given slope triad $_i^k\mathbb{R}_{i_p}^{k_p}$ do not increase the net variance.
+Since the total fluxes are sums of such fluxes from the various triads, this constraint, applied to all triads,
+is sufficient to ensure that the globally integrated variance does not increase.
+
+The expression \autoref{eq:TRIADS_V-A} can be interpreted as a discretization of the global integral
+\begin{equation}
+  \label{eq:TRIADS_cts-var}
+  \frac{\partial}{\partial t}\int\!\fractext{1}{2} T^2\, dV =
+  \int\!\mathbf{F}\cdot\nabla T\, dV,
+\end{equation}
+where, within each triad volume $_i^k\mathbb{V}_{i_p}^{k_p}$, the lateral and vertical fluxes/unit area
+\[
+  \mathbf{F}=\left(
+    \left.{}_i^k{\mathbb{F}_u}_{i_p}^{k_p} (T)\right/{}_i^k{\mathbb{A}_u}_{i_p}^{k_p},
+    \left.{\:}_i^k{\mathbb{F}_w}_{i_p}^{k_p} (T)\right/{}_i^k{\mathbb{A}_w}_{i_p}^{k_p}
+  \right)
+\]
+and the gradient
+\[
+  \nabla T = \left(
+    \left.\delta_{i+ i_p}[T^k] \right/ {e_{1u}}_{\,i + i_p}^{\,k},
+    \left.\delta_{k+ k_p}[T^i] \right/ {e_{3w}}_{\,i}^{\,k + k_p}
+  \right)
+\]
+
+%% =================================================================================================
+\subsection{Triad volumes in Griffes's scheme and in \NEMO}
+
+To complete the discretization we now need only specify the triad volumes $_i^k\mathbb{V}_{i_p}^{k_p}$.
+\citet{griffies.gnanadesikan.ea_JPO98} identifies these $_i^k\mathbb{V}_{i_p}^{k_p}$ as the volumes of the quarter cells,
+defined in terms of the distances between $T$, $u$,$f$ and $w$-points.
+This is the natural discretization of \autoref{eq:TRIADS_cts-var}.
+The \NEMO\ model, however, operates with scale factors instead of grid sizes,
+and scale factors for the quarter cells are not defined.
+Instead, therefore we simply choose
+\begin{equation}
+  \label{eq:TRIADS_V-NEMO}
+  _i^k\mathbb{V}_{i_p}^{k_p}=\fractext{1}{4} {b_u}_{i+i_p}^k,
+\end{equation}
+as a quarter of the volume of the $u$-cell inside which the triad quarter-cell lies.
+This has the nice property that when the slopes $\mathbb{R}$ vanish,
+the lateral flux from tracer cell $i,k$ to $i+1,k$ reduces to the classical form
+\begin{equation}
+  \label{eq:TRIADS_lat-normal}
+  -\overline{A}_{\,i+1/2}^k\;
+  \frac{{b_u}_{i+1/2}^k}{{e_{1u}}_{\,i + i_p}^{\,k}}
+  \;\frac{\delta_{i+ 1/2}[T^k] }{{e_{1u}}_{\,i + i_p}^{\,k}}
+  = -\overline{A}_{\,i+1/2}^k\;\frac{{e_{1w}}_{\,i + 1/2}^{\,k}\:{e_{1v}}_{\,i + 1/2}^{\,k}\;\delta_{i+ 1/2}[T^k]}{{e_{1u}}_{\,i + 1/2}^{\,k}}.
+\end{equation}
+In fact if the diffusive coefficient is defined at $u$-points,
+so that we employ ${A}_{i+i_p}^k$ instead of  ${A}_i^k$ in the definitions of the triad fluxes
+\autoref{eq:TRIADS_latflux-triad} and \autoref{eq:TRIADS_vertflux-triad},
+we can replace $\overline{A}_{\,i+1/2}^k$ by $A_{i+1/2}^k$ in the above.
+
+%% =================================================================================================
+\subsection{Summary of the scheme}
+
+The iso-neutral fluxes at $u$- and $w$-points are the sums of the triad fluxes that
+cross the $u$- and $w$-faces \autoref{eq:TRIADS_iso_flux}:
+\begin{subequations}
+  % \label{eq:TRIADS_alltriadflux}
+  \begin{flalign*}
+    % \label{eq:TRIADS_vect_isoflux}
+    \vect{F}_{\mathrm{iso}}(T) &\equiv
+    \sum_{\substack{i_p,\,k_p}}
+    \begin{pmatrix}
+      {_{i+1/2-i_p}^k {\mathbb{F}_u}_{i_p}^{k_p} } (T) \\ \\
+      {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p} } (T)
+    \end{pmatrix},
+  \end{flalign*}
+  where \autoref{eq:TRIADS_latflux-triad}:
+  \begin{align}
+    \label{eq:TRIADS_triadfluxu}
+    _i^k {\mathbb{F}_u}_{i_p}^{k_p} (T) &= - {A}_i^k{
+                                          \:}\frac{{{}_i^k\mathbb{V}}_{i_p}^{k_p}}{{e_{1u}}_{\,i + i_p}^{\,k}}
+                                          \left(
+                                          \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+                                          -\ {_i^k\mathbb{R}_{i_p}^{k_p}} \
+                                          \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+                                          \right),\\
+    \intertext{and}
+    _i^k {\mathbb{F}_w}_{i_p}^{k_p} (T)
+                                        &= {A}_i^k{\: }\frac{{{}_i^k\mathbb{V}}_{i_p}^{k_p}}{{e_{3w}}_{\,i}^{\,k+k_p}}
+                                          \left(
+                                          {_i^k\mathbb{R}_{i_p}^{k_p}}\frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+                                          -\ \left({_i^k\mathbb{R}_{i_p}^{k_p}}\right)^2 \
+                                          \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+                                          \right),\label{eq:TRIADS_triadfluxw}
+  \end{align}
+  with \autoref{eq:TRIADS_V-NEMO}
+  \[
+    % \label{eq:TRIADS_V-NEMO2}
+    _i^k{\mathbb{V}}_{i_p}^{k_p}=\fractext{1}{4} {b_u}_{i+i_p}^k.
+  \]
+\end{subequations}
+
+The divergence of the expression \autoref{eq:TRIADS_iso_flux} for the fluxes gives the iso-neutral diffusion tendency at
+each tracer point:
+\[
+  % \label{eq:TRIADS_iso_operator}
+  D_l^T = \frac{1}{b_T}
+  \sum_{\substack{i_p,\,k_p}} \left\{ \delta_{i} \left[{_{i+1/2-i_p}^k
+        {\mathbb{F}_u }_{i_p}^{k_p}} \right] + \delta_{k} \left[
+      {_i^{k+1/2-k_p} {\mathbb{F}_w}_{i_p}^{k_p}} \right] \right\}
+\]
+where $b_T= e_{1T}\,e_{2T}\,e_{3T}$ is the volume of $T$-cells.
+The diffusion scheme satisfies the following six properties:
+
+\begin{description}
+\item [Horizontal diffusion] The discretization of the diffusion operator recovers the traditional five-point Laplacian
+  \autoref{eq:TRIADS_lat-normal} in the limit of flat iso-neutral direction:
+  \[
+    % \label{eq:TRIADS_iso_property0}
+    D_l^T = \frac{1}{b_T} \
+    \delta_{i} \left[ \frac{e_{2u}\,e_{3u}}{e_{1u}} \;
+      \overline{A}^{\,i} \; \delta_{i+1/2}[T] \right] \qquad
+    \text{when} \quad { _i^k \mathbb{R}_{i_p}^{k_p} }=0
+  \]
+\item [Implicit treatment in the vertical] Only tracer values associated with a single water column appear in the expression \autoref{eq:TRIADS_i33} for
+  the $_{33}$ fluxes, vertical fluxes driven by vertical gradients.
+  This is of paramount importance since it means that a time-implicit algorithm can be used to
+  solve the vertical diffusion equation.
+  This is necessary since the vertical eddy diffusivity associated with this term,
+  \[
+    \frac{1}{b_w}\sum_{\substack{i_p, \,k_p}} \left\{
+      {\:}_i^k\mathbb{V}_{i_p}^{k_p} \: {A}_i^k \: \left(_i^k \mathbb{R}_{i_p}^{k_p}\right)^2
+    \right\}  =
+    \frac{1}{4b_w}\sum_{\substack{i_p, \,k_p}} \left\{
+      {b_u}_{i+i_p}^k\: {A}_i^k \: \left(_i^k \mathbb{R}_{i_p}^{k_p}\right)^2
+    \right\},
+  \]
+  (where $b_w= e_{1w}\,e_{2w}\,e_{3w}$ is the volume of $w$-cells) can be quite large.
+\item [Pure iso-neutral operator] The iso-neutral flux of locally referenced potential density is zero.
+  See \autoref{eq:TRIADS_latflux-rho} and \autoref{eq:TRIADS_vertflux-triad2}.
+\item [Conservation of tracer] The iso-neutral diffusion conserves tracer content, \ie
+  \[
+    % \label{eq:TRIADS_iso_property1}
+    \sum_{i,j,k} \left\{ D_l^T \      b_T \right\} = 0
+  \]
+  This property is trivially satisfied since the iso-neutral diffusive operator is written in flux form.
+\item [No increase of tracer variance] The iso-neutral diffusion does not increase the tracer variance, \ie
+  \[
+    % \label{eq:TRIADS_iso_property2}
+    \sum_{i,j,k} \left\{ T \ D_l^T      \ b_T \right\} \leq 0
+  \]
+  The property is demonstrated in \autoref{subsec:TRIADS_variance} above.
+  It is a key property for a diffusion term.
+  It means that it is also a dissipation term,
+  \ie\ it dissipates the square of the quantity on which it is applied.
+  It therefore ensures that, when the diffusivity coefficient is large enough,
+  the field on which it is applied becomes free of grid-point noise.
+\item [Self-adjoint operator] The iso-neutral diffusion operator is self-adjoint, \ie
+  \begin{equation}
+    \label{eq:TRIADS_iso_property3}
+    \sum_{i,j,k} \left\{ S \ D_l^T \ b_T \right\} = \sum_{i,j,k} \left\{ D_l^S \ T \ b_T \right\}
+  \end{equation}
+  In other word, there is no need to develop a specific routine from the adjoint of this operator.
+  We just have to apply the same routine.
+  This property can be demonstrated similarly to the proof of the `no increase of tracer variance' property.
+  The contribution by a single triad towards the left hand side of \autoref{eq:TRIADS_iso_property3},
+  can be found by replacing $\delta[T]$ by $\delta[S]$ in \autoref{eq:TRIADS_dvar_iso_i} and \autoref{eq:TRIADS_dvar_iso_k}.
+  This results in a term similar to \autoref{eq:TRIADS_perfect-square},
+  \[
+    % \label{eq:TRIADS_TScovar}
+    - {A}_i^k{\:} _i^k\mathbb{V}_{i_p}^{k_p}
+    \left(
+      \frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+      -{\:}_i^k\mathbb{R}_{i_p}^{k_p}
+      \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+    \right)
+    \left(
+      \frac{ \delta_{i+ i_p}[S^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }
+      -{\:}_i^k\mathbb{R}_{i_p}^{k_p}
+      \frac{ \delta_{k+k_p} [S^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }
+    \right).
+  \]
+This is symmetrical in $T $ and $S$, so exactly the same term arises from
+the discretization of this triad's contribution towards the RHS of \autoref{eq:TRIADS_iso_property3}.
+\end{description}
+
+%% =================================================================================================
+\subsection{Treatment of the triads at the boundaries}
+\label{sec:TRIADS_iso_bdry}
+
+The triad slope can only be defined where both the grid boxes centred at the end of the arms exist.
+Triads that would poke up through the upper ocean surface into the atmosphere,
+or down into the ocean floor, must be masked out.
+See \autoref{fig:TRIADS_bdry_triads}.
+Surface layer triads \triad{i}{1}{R}{1/2}{-1/2} (magenta) and \triad{i+1}{1}{R}{-1/2}{-1/2} (blue) that
+require density to be specified above the ocean surface are masked (\autoref{fig:TRIADS_bdry_triads}a):
+this ensures that lateral tracer gradients produce no flux through the ocean surface.
+However, to prevent surface noise, it is customary to retain the $_{11}$ contributions towards
+the lateral triad fluxes \triad[u]{i}{1}{F}{1/2}{-1/2} and \triad[u]{i+1}{1}{F}{-1/2}{-1/2};
+this drives diapycnal tracer fluxes.
+Similar comments apply to triads that would intersect the ocean floor (\autoref{fig:TRIADS_bdry_triads}b).
+Note that both near bottom triad slopes \triad{i}{k}{R}{1/2}{1/2} and \triad{i+1}{k}{R}{-1/2}{1/2} are masked when
+either of the $i,k+1$ or $i+1,k+1$ tracer points is masked, \ie\ the $i,k+1$ $u$-point is masked.
+The associated lateral fluxes (grey-black dashed line) are masked if \np[=.false.]{ln_botmix_triad}{ln\_botmix\_triad},
+but left unmasked, giving bottom mixing, if \np[=.true.]{ln_botmix_triad}{ln\_botmix\_triad}.
+
+The default option \np[=.false.]{ln_botmix_triad}{ln\_botmix\_triad} is suitable when the bbl mixing option is enabled
+(\np[=.true.]{ln_trabbl}{ln\_trabbl}, with \np[=1]{nn_bbl_ldf}{nn\_bbl\_ldf}), or for simple idealized problems.
+For setups with topography without bbl mixing, \np[=.true.]{ln_botmix_triad}{ln\_botmix\_triad} may be necessary.
+\begin{figure}[h]
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRIADS_GRIFF_bdry_triads}
+  \caption[Boundary triads]{
+    (a) Uppermost model layer $k=1$ with $i,1$ and $i+1,1$ tracer points (black dots),
+    and $i+1/2,1$ $u$-point (blue square).
+    Triad slopes \triad{i}{1}{R}{1/2}{-1/2} (magenta) and
+    \triad{i+1}{1}{R}{-1/2}{-1/2} (blue) poking through the ocean surface are masked
+    (faded in figure).
+    However,
+    the lateral $_{11}$ contributions towards \triad[u]{i}{1}{F}{1/2}{-1/2} and
+    \triad[u]{i+1}{1}{F}{-1/2}{-1/2} (yellow line) are still applied,
+    giving diapycnal diffusive fluxes.
+    \newline
+    (b) Both near bottom triad slopes \triad{i}{k}{R}{1/2}{1/2} and
+    \triad{i+1}{k}{R}{-1/2}{1/2} are masked when
+    either of the $i,k+1$ or $i+1,k+1$ tracer points is masked,
+    \ie\ the $i,k+1$ $u$-point is masked.
+    The associated lateral fluxes (grey-black dashed line) are masked if
+    \protect\np[=.false.]{ln_botmix_triad}{ln\_botmix\_triad}, but left unmasked,
+    giving bottom mixing, if \protect\np[=.true.]{ln_botmix_triad}{ln\_botmix\_triad}}
+  \label{fig:TRIADS_bdry_triads}
+\end{figure}
+
+%% =================================================================================================
+\subsection{ Limiting of the slopes within the interior}
+\label{sec:TRIADS_limit}
+
+As discussed in \autoref{subsec:LDF_slp_iso},
+iso-neutral slopes relative to geopotentials must be bounded everywhere,
+both for consistency with the small-slope approximation and for numerical stability \citep{cox_OM87, griffies_bk04}.
+The bound chosen in \NEMO\ is applied to each component of the slope separately and
+has a value of $1/100$ in the ocean interior.
+%, ramping linearly down above 70~m depth to zero at the surface
+It is of course relevant to the iso-neutral slopes $\tilde{r}_i=r_i+\sigma_i$ relative to geopotentials
+(here the $\sigma_i$ are the slopes of the coordinate surfaces relative to geopotentials)
+\autoref{eq:MB_slopes_eiv} rather than the slope $r_i$ relative to coordinate surfaces, so we require
+\[
+  |\tilde{r}_i|\leq \tilde{r}_\mathrm{max}=0.01.
+\]
+and then recalculate the slopes $r_i$ relative to coordinates.
+Each individual triad slope
+\begin{equation}
+  \label{eq:TRIADS_Rtilde}
+  _i^k\tilde{\mathbb{R}}_{i_p}^{k_p} = {}_i^k\mathbb{R}_{i_p}^{k_p}  + \frac{\delta_{i+i_p}[z_T^k]}{{e_{1u}}_{\,i + i_p}^{\,k}}
+\end{equation}
+is limited like this and then the corresponding $_i^k\mathbb{R}_{i_p}^{k_p} $ are recalculated and
+combined to form the fluxes.
+Note that where the slopes have been limited, there is now a non-zero iso-neutral density flux that
+drives dianeutral mixing.
+In particular this iso-neutral density flux is always downwards,
+and so acts to reduce gravitational potential energy.
+
+%% =================================================================================================
+\subsection{Tapering within the surface mixed layer}
+\label{sec:TRIADS_taper}
+
+Additional tapering of the iso-neutral fluxes is necessary within the surface mixed layer.
+When the Griffies triads are used, we offer two options for this.
+
+%% =================================================================================================
+\subsubsection{Linear slope tapering within the surface mixed layer}
+\label{sec:TRIADS_lintaper}
+
+This is the option activated by the default choice \np[=.false.]{ln_triad_iso}{ln\_triad\_iso}.
+Slopes $\tilde{r}_i$ relative to geopotentials are tapered linearly from their value immediately below
+the mixed layer to zero at the surface, as described in option (c) of \autoref{fig:LDF_eiv_slp}, to values
+\begin{equation}
+  \label{eq:TRIADS_rmtilde}
+  \rMLt = -\frac{z}{h}\left.\tilde{r}_i\right|_{z=-h}\quad \text{ for  } z>-h,
+\end{equation}
+and then the $r_i$ relative to vertical coordinate surfaces are appropriately adjusted to
+\[
+  % \label{eq:TRIADS_rm}
+  \rML =\rMLt -\sigma_i \quad \text{ for  } z>-h.
+\]
+Thus the diffusion operator within the mixed layer is given by:
+\[
+  % \label{eq:TRIADS_iso_tensor_ML}
+  D^{lT}=\nabla {\mathrm {\mathbf .}}\left( {A^{lT}\;\Re \;\nabla T} \right) \qquad
+  \mbox{with}\quad \;\;\Re =\left( {{
+        \begin{array}{*{20}c}
+          1 \hfill & 0 \hfill & {-\rML[1]}\hfill \\
+          0 \hfill & 1 \hfill & {-\rML[2]} \hfill \\
+          {-\rML[1]}\hfill &   {-\rML[2]} \hfill & {\rML[1]^2+\rML[2]^2} \hfill
+        \end{array}
+      }} \right)
+\]
+
+This slope tapering gives a natural connection between tracer in the mixed-layer and
+in isopycnal layers immediately below, in the thermocline.
+It is consistent with the way the $\tilde{r}_i$ are tapered within the mixed layer
+(see \autoref{sec:TRIADS_taperskew} below) so as to ensure a uniform GM eddy-induced velocity throughout the mixed layer.
+However, it gives a downwards density flux and so acts so as to reduce potential energy in the same way as
+does the slope limiting discussed above in \autoref{sec:TRIADS_limit}.
+
+As in \autoref{sec:TRIADS_limit} above, the tapering \autoref{eq:TRIADS_rmtilde} is applied separately to
+each triad $_i^k\tilde{\mathbb{R}}_{i_p}^{k_p}$, and the $_i^k\mathbb{R}_{i_p}^{k_p}$ adjusted.
+For clarity, we assume $z$-coordinates in the following;
+the conversion from $\mathbb{R}$ to $\tilde{\mathbb{R}}$ and back to $\mathbb{R}$ follows exactly as
+described above by \autoref{eq:TRIADS_Rtilde}.
+\begin{enumerate}
+\item Mixed-layer depth is defined so as to avoid including regions of weak vertical stratification in
+  the slope definition.
+  At each $i,j$ (simplified to $i$ in \autoref{fig:TRIADS_MLB_triad}),
+  we define the mixed-layer by setting the vertical index of the tracer point immediately below the mixed layer,
+  $k_{\mathrm{ML}}$, as the maximum $k$ (shallowest tracer point) such that
+  the potential density ${\rho_0}_{i,k}>{\rho_0}_{i,k_{10}}+\Delta\rho_c$,
+  where $i,k_{10}$ is the tracer gridbox within which the depth reaches 10~m.
+  See the left side of \autoref{fig:TRIADS_MLB_triad}.
+  We use the $k_{10}$-gridbox instead of the surface gridbox to avoid problems \eg\ with thin daytime mixed-layers.
+  Currently we use the same $\Delta\rho_c=0.01\;\mathrm{kg\:m^{-3}}$ for ML triad tapering as is used to
+  output the diagnosed mixed-layer depth $h_{\mathrm{ML}}=|z_{W}|_{k_{\mathrm{ML}}+1/2}$,
+  the depth of the $w$-point above the $i,k_{\mathrm{ML}}$ tracer point.
+\item We define `basal' triad slopes ${\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p}$ as
+  the slopes of those triads whose vertical `arms' go down from the $i,k_{\mathrm{ML}}$ tracer point to
+  the $i,k_{\mathrm{ML}}-1$ tracer point below.
+  This is to ensure that the vertical density gradients associated with
+  these basal triad slopes ${\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p}$ are representative of the thermocline.
+  The four basal triads defined in the bottom part of \autoref{fig:TRIADS_MLB_triad} are then
+  \begin{align*}
+    {\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p} &=
+                                                       {\:}^{k_{\mathrm{ML}}-k_p-1/2}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p},
+                                                       % \label{eq:TRIADS_Rbase}
+    \\
+    \intertext{with \eg\ the green triad}
+    {\:}_i{\mathbb{R}_{\mathrm{base}}}_{1/2}^{-1/2}&=
+                                                     {\:}^{k_{\mathrm{ML}}}_i{\mathbb{R}_{\mathrm{base}}}_{\,1/2}^{-1/2}.
+  \end{align*}
+The vertical flux associated with each of these triads passes through
+the $w$-point $i,k_{\mathrm{ML}}-1/2$ lying \emph{below} the $i,k_{\mathrm{ML}}$ tracer point, so it is this depth
+\[
+  % \label{eq:TRIADS_zbase}
+  {z_\mathrm{base}}_{\,i}={z_{w}}_{k_\mathrm{ML}-1/2}
+\]
+one gridbox deeper than the diagnosed ML depth $z_{\mathrm{ML}})$ that sets the $h$ used to taper the slopes in
+\autoref{eq:TRIADS_rmtilde}.
+\item Finally, we calculate the adjusted triads ${\:}_i^k{\mathbb{R}_{\mathrm{ML}}}_{\,i_p}^{k_p}$ within
+  the mixed layer, by multiplying the appropriate ${\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p}$ by
+  the ratio of the depth of the $w$-point ${z_w}_{k+k_p}$ to ${z_{\mathrm{base}}}_{\,i}$.
+  For instance the green triad centred on $i,k$
+  \begin{align*}
+    {\:}_i^k{\mathbb{R}_{\mathrm{ML}}}_{\,1/2}^{-1/2} &=
+                                                        \frac{{z_w}_{k-1/2}}{{z_{\mathrm{base}}}_{\,i}}{\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,1/2}^{-1/2} \\
+    \intertext{and more generally}
+    {\:}_i^k{\mathbb{R}_{\mathrm{ML}}}_{\,i_p}^{k_p} &=
+                                                       \frac{{z_w}_{k+k_p}}{{z_{\mathrm{base}}}_{\,i}}{\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p}.
+                                                       % \label{eq:TRIADS_RML}
+  \end{align*}
+\end{enumerate}
+
+\begin{figure}[h]
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRIADS_GRIFF_MLB_triads}
+  \caption[Definition of mixed-layer depth and calculation of linearly tapered triads]{
+    Definition of mixed-layer depth and calculation of linearly tapered triads.
+    The figure shows a water column at a given $i,j$ (simplified to $i$),
+    with the ocean surface at the top.
+    Tracer points are denoted by bullets, and black lines the edges of the tracer cells;
+    $k$ increases upwards.
+    \newline
+    We define the mixed-layer by setting the vertical index of the tracer point immediately below
+    the mixed layer, $k_{\mathrm{ML}}$, as the maximum $k$ (shallowest tracer point) such that
+    ${\rho_0}_{i,k}>{\rho_0}_{i,k_{10}}+\Delta\rho_c$,
+    where $i,k_{10}$ is the tracer gridbox within which the depth reaches 10~m.
+    We calculate the triad slopes within the mixed layer by linearly tapering them from zero
+    (at the surface) to the `basal' slopes,
+    the slopes of the four triads passing through the $w$-point $i,k_{\mathrm{ML}}-1/2$ (blue square),
+    ${\:}_i{\mathbb{R}_{\mathrm{base}}}_{\,i_p}^{k_p}$.
+    Triads with different $i_p,k_p$, denoted by different colours,
+    (\eg\ the green triad $i_p=1/2,k_p=-1/2$) are tapered to the appropriate basal triad.}
+  \label{fig:TRIADS_MLB_triad}
+\end{figure}
+
+%% =================================================================================================
+\subsubsection{Additional truncation of skew iso-neutral flux components}
+\label{subsec:TRIADS_Gerdes-taper}
+
+The alternative option is activated by setting \np{ln_triad_iso}{ln\_triad\_iso} = true.
+This retains the same tapered slope $\rML$  described above for the calculation of the $_{33}$ term of
+the iso-neutral diffusion tensor (the vertical tracer flux driven by vertical tracer gradients),
+but replaces the $\rML$ in the skew term by
+\begin{equation}
+  \label{eq:TRIADS_rm*}
+  \rML^*=\left.\rMLt^2\right/\tilde{r}_i-\sigma_i,
+\end{equation}
+giving a ML diffusive operator
+\[
+  % \label{eq:TRIADS_iso_tensor_ML2}
+  D^{lT}=\nabla {\mathrm {\mathbf .}}\left( {A^{lT}\;\Re \;\nabla T} \right) \qquad
+  \mbox{with}\quad \;\;\Re =\left( {{
+        \begin{array}{*{20}c}
+          1 \hfill & 0 \hfill & {-\rML[1]^*}\hfill \\
+          0 \hfill & 1 \hfill & {-\rML[2]^*} \hfill \\
+          {-\rML[1]^*}\hfill &   {-\rML[2]^*} \hfill & {\rML[1]^2+\rML[2]^2} \hfill \\
+        \end{array}
+      }} \right).
+\]
+This operator
+\footnote{
+  To ensure good behaviour where horizontal density gradients are weak,
+  we in fact follow \citet{gerdes.koberle.ea_CD91} and
+  set $\rML^*=\mathrm{sgn}(\tilde{r}_i)\min(|\rMLt^2/\tilde{r}_i|,|\tilde{r}_i|)-\sigma_i$.
+}
+then has the property it gives no vertical density flux, and so does not change the potential energy.
+This approach is similar to multiplying the iso-neutral diffusion coefficient by
+$\tilde{r}_{\mathrm{max}}^{-2}\tilde{r}_i^{-2}$ for steep slopes,
+as suggested by \citet{gerdes.koberle.ea_CD91} (see also \citet{griffies_bk04}).
+Again it is applied separately to each triad $_i^k\mathbb{R}_{i_p}^{k_p}$
+
+In practice, this approach gives weak vertical tracer fluxes through the mixed-layer,
+as well as vanishing density fluxes.
+While it is theoretically advantageous that it does not change the potential energy,
+it may give a discontinuity between the fluxes within the mixed-layer (purely horizontal) and
+just below (along iso-neutral surfaces).
+% This may give strange looking results,
+% particularly where the mixed-layer depth varies strongly laterally.
+%% =================================================================================================
+\section{Eddy induced advection formulated as a skew flux}
+\label{sec:TRIADS_skew-flux}
+
+%% =================================================================================================
+\subsection{Continuous skew flux formulation}
+\label{sec:TRIADS_continuous-skew-flux}
+
+When Gent and McWilliams's [1990] diffusion is used, an additional advection term is added.
+The associated velocity is the so called eddy induced velocity,
+the formulation of which depends on the slopes of iso-neutral surfaces.
+Contrary to the case of iso-neutral mixing, the slopes used here are referenced to the geopotential surfaces,
+\ie\ \autoref{eq:LDF_slp_geo} is used in $z$-coordinate,
+and the sum \autoref{eq:LDF_slp_geo} + \autoref{eq:LDF_slp_iso} in $z^*$ or $s$-coordinates.
+
+The eddy induced velocity is given by:
+\begin{subequations}
+  % \label{eq:TRIADS_eiv}
+  \begin{equation}
+    \label{eq:TRIADS_eiv_v}
+    \begin{split}
+      u^* & = - \frac{1}{e_{3}}\;          \partial_i\psi_1,  \\
+      v^* & = - \frac{1}{e_{3}}\;          \partial_j\psi_2,    \\
+      w^* & =    \frac{1}{e_{1}e_{2}}\; \left\{ \partial_i  \left( e_{2} \, \psi_1\right)
+        + \partial_j  \left( e_{1} \, \psi_2\right) \right\},
+    \end{split}
+  \end{equation}
+  where the streamfunctions $\psi_i$ are given by
+  \begin{equation}
+    \label{eq:TRIADS_eiv_psi}
+    \begin{split}
+      \psi_1 & = A_{e} \; \tilde{r}_1,   \\
+      \psi_2 & = A_{e} \; \tilde{r}_2,
+    \end{split}
+  \end{equation}
+\end{subequations}
+with $A_{e}$ the eddy induced velocity coefficient,
+and $\tilde{r}_1$ and $\tilde{r}_2$ the slopes between the iso-neutral and the geopotential surfaces.
+
+The traditional way to implement this additional advection is to add it to the Eulerian velocity prior to
+computing the tracer advection.
+This is implemented if \texttt{traldf\_eiv?} is set in the default implementation,
+where \np{ln_traldf_triad}{ln\_traldf\_triad} is set false.
+This allows us to take advantage of all the advection schemes offered for the tracers
+(see \autoref{sec:TRA_adv}) and not just a $2^{nd}$ order advection scheme.
+This is particularly useful for passive tracers where
+\emph{positivity} of the advection scheme is of paramount importance.
+
+However, when \np{ln_traldf_triad}{ln\_traldf\_triad} is set true,
+\NEMO\ instead implements eddy induced advection according to the so-called skew form \citep{griffies_JPO98}.
+It is based on a transformation of the advective fluxes using the non-divergent nature of the eddy induced velocity.
+For example in the (\textbf{i},\textbf{k}) plane,
+the tracer advective fluxes per unit area in $ijk$ space can be transformed as follows:
+\begin{flalign*}
+  \begin{split}
+    \textbf{F}_{\mathrm{eiv}}^T =
+    \begin{pmatrix}
+      {e_{2}\,e_{3}\;  u^*} \\
+ 		{e_{1}\,e_{2}\; w^*}
+    \end{pmatrix}   \;   T
+    &=
+    \begin{pmatrix}
+      { - \partial_k \left( e_{2} \,\psi_1 \right) \; T \;} \\
+ 		{+ \partial_i  \left( e_{2} \, \psi_1 \right) \; T \;}
+    \end{pmatrix} 			\\
+    &=
+    \begin{pmatrix}
+      { - \partial_k \left( e_{2} \, \psi_1  \; T \right) \;} \\
+ 		{+ \partial_i  \left( e_{2} \,\psi_1 \; T \right) \;}
+    \end{pmatrix}
+    +
+    \begin{pmatrix}
+      {+ e_{2} \, \psi_1  \; \partial_k T} \\
+ 		{ - e_{2} \, \psi_1  \; \partial_i  T}
+    \end{pmatrix}
+  \end{split}
+\end{flalign*}
+and since the eddy induced velocity field is non-divergent,
+we end up with the skew form of the eddy induced advective fluxes per unit area in $ijk$ space:
+\begin{equation}
+  \label{eq:TRIADS_eiv_skew_ijk}
+  \textbf{F}_\mathrm{eiv}^T =
+  \begin{pmatrix}
+    {+ e_{2} \, \psi_1  \; \partial_k T}   \\
+    { - e_{2} \, \psi_1  \; \partial_i  T}
+  \end{pmatrix}
+\end{equation}
+The total fluxes per unit physical area are then
+\begin{equation}
+  \label{eq:TRIADS_eiv_skew_physical}
+  \begin{split}
+    f^*_1 & = \frac{1}{e_{3}}\; \psi_1 \partial_k T   \\
+    f^*_2 & = \frac{1}{e_{3}}\; \psi_2 \partial_k T   \\
+    f^*_3 & =  -\frac{1}{e_{1}e_{2}}\; \left\{ e_{2} \psi_1 \partial_i T + e_{1} \psi_2 \partial_j T \right\}.
+\end{split}
+\end{equation}
+Note that \autoref{eq:TRIADS_eiv_skew_physical} takes the same form whatever the vertical coordinate,
+though of course the slopes $\tilde{r}_i$ which define the $\psi_i$ in \autoref{eq:TRIADS_eiv_psi} are relative to
+geopotentials.
+The tendency associated with eddy induced velocity is then simply the convergence of the fluxes
+(\autoref{eq:TRIADS_eiv_skew_ijk}, \autoref{eq:TRIADS_eiv_skew_physical}), so
+\[
+  % \label{eq:TRIADS_skew_eiv_conv}
+  \frac{\partial T}{\partial t}= -\frac{1}{e_1 \, e_2 \, e_3 }      \left[
+    \frac{\partial}{\partial i} \left( e_2 \psi_1 \partial_k T\right)
+    + \frac{\partial}{\partial j} \left( e_1  \;
+      \psi_2 \partial_k T\right)
+    -  \frac{\partial}{\partial k} \left( e_{2} \psi_1 \partial_i T
+      + e_{1} \psi_2 \partial_j T \right)  \right]
+\]
+It naturally conserves the tracer content, as it is expressed in flux form.
+Since it has the same divergence as the advective form it also preserves the tracer variance.
+
+%% =================================================================================================
+\subsection{Discrete skew flux formulation}
+
+The skew fluxes in (\autoref{eq:TRIADS_eiv_skew_physical}, \autoref{eq:TRIADS_eiv_skew_ijk}),
+like the off-diagonal terms (\autoref{eq:TRIADS_i13c}, \autoref{eq:TRIADS_i31c}) of the small angle diffusion tensor,
+are best expressed in terms of the triad slopes, as in \autoref{fig:TRIADS_ISO_triad} and
+(\autoref{eq:TRIADS_i13}, \autoref{eq:TRIADS_i31});
+but now in terms of the triad slopes $\tilde{\mathbb{R}}$ relative to geopotentials instead of
+the $\mathbb{R}$ relative to coordinate surfaces.
+The discrete form of \autoref{eq:TRIADS_eiv_skew_ijk} using the slopes \autoref{eq:TRIADS_R} and
+defining $A_e$ at $T$-points is then given by:
+
+\begin{subequations}
+  % \label{eq:TRIADS_allskewflux}
+  \begin{flalign*}
+    % \label{eq:TRIADS_vect_skew_flux}
+    \vect{F}_{\mathrm{eiv}}(T) &\equiv    \sum_{\substack{i_p,\,k_p}}
+    \begin{pmatrix}
+      {_{i+1/2-i_p}^k {\mathbb{S}_u}_{i_p}^{k_p} } (T)      \\      \\
+      {_i^{k+1/2-k_p} {\mathbb{S}_w}_{i_p}^{k_p} } (T)      \\
+    \end{pmatrix},
+  \end{flalign*}
+  where the skew flux in the $i$-direction associated with a given triad is (\autoref{eq:TRIADS_latflux-triad},
+  \autoref{eq:TRIADS_triadfluxu}):
+  \begin{align}
+    \label{eq:TRIADS_skewfluxu}
+    _i^k {\mathbb{S}_u}_{i_p}^{k_p} (T) &= + \fractext{1}{4} {A_e}_i^k{
+                                          \:}\frac{{b_u}_{i+i_p}^k}{{e_{1u}}_{\,i + i_p}^{\,k}}
+                                          \ {_i^k\tilde{\mathbb{R}}_{i_p}^{k_p}} \
+                                          \frac{ \delta_{k+k_p} [T^i] }{{e_{3w}}_{\,i}^{\,k+k_p} }, \\
+    \intertext{
+    and \autoref{eq:TRIADS_triadfluxw} in the $k$-direction, changing the sign
+    to be consistent with \autoref{eq:TRIADS_eiv_skew_ijk}:
+    }
+    _i^k {\mathbb{S}_w}_{i_p}^{k_p} (T)
+                                        &= -\fractext{1}{4} {A_e}_i^k{\: }\frac{{b_u}_{i+i_p}^k}{{e_{3w}}_{\,i}^{\,k+k_p}}
+                                          {_i^k\tilde{\mathbb{R}}_{i_p}^{k_p}}\frac{ \delta_{i+ i_p}[T^k] }{ {e_{1u}}_{\,i + i_p}^{\,k} }.\label{eq:TRIADS_skewfluxw}
+  \end{align}
+\end{subequations}
+
+Such a discretisation is consistent with the iso-neutral operator as it uses the same definition for the slopes.
+It also ensures the following two key properties.
+
+%% =================================================================================================
+\subsubsection{No change in tracer variance}
+
+The discretization conserves tracer variance, \ie\ it does not include a diffusive component but is a `pure' advection term.
+This can be seen %either from Appendix \autoref{apdx:eiv_skew} or
+by considering the fluxes associated with a given triad slope $_i^k{\mathbb{R}}_{i_p}^{k_p} (T)$.
+For, following \autoref{subsec:TRIADS_variance} and \autoref{eq:TRIADS_dvar_iso_i},
+the associated horizontal skew-flux $_i^k{\mathbb{S}_u}_{i_p}^{k_p} (T)$ drives a net rate of change of variance,
+summed over the two $T$-points $i+i_p-\fractext{1}{2},k$ and $i+i_p+\fractext{1}{2},k$, of
+\begin{equation}
+  \label{eq:TRIADS_dvar_eiv_i}
+  _i^k{\mathbb{S}_u}_{i_p}^{k_p} (T)\,\delta_{i+ i_p}[T^k],
+\end{equation}
+while the associated vertical skew-flux gives a variance change summed over
+the $T$-points $i,k+k_p-\fractext{1}{2}$ (above) and $i,k+k_p+\fractext{1}{2}$ (below) of
+\begin{equation}
+  \label{eq:TRIADS_dvar_eiv_k}
+  _i^k{\mathbb{S}_w}_{i_p}^{k_p} (T) \,\delta_{k+ k_p}[T^i].
+\end{equation}
+Inspection of the definitions (\autoref{eq:TRIADS_skewfluxu}, \autoref{eq:TRIADS_skewfluxw}) shows that
+these two variance changes (\autoref{eq:TRIADS_dvar_eiv_i}, \autoref{eq:TRIADS_dvar_eiv_k}) sum to zero.
+Hence the two fluxes associated with each triad make no net contribution to the variance budget.
+
+%% =================================================================================================
+\subsubsection{Reduction in gravitational PE}
+
+The vertical density flux associated with the vertical skew-flux always has the same sign as
+the vertical density gradient;
+thus, so long as the fluid is stable (the vertical density gradient is negative)
+the vertical density flux is negative (downward) and hence reduces the gravitational PE.
+
+For the change in gravitational PE driven by the $k$-flux is
+\begin{align}
+  \label{eq:TRIADS_vert_densityPE}
+  g {e_{3w}}_{\,i}^{\,k+k_p}{\mathbb{S}_w}_{i_p}^{k_p} (\rho)
+  &=g {e_{3w}}_{\,i}^{\,k+k_p}\left[-\alpha _i^k {\:}_i^k
+    {\mathbb{S}_w}_{i_p}^{k_p} (T) + \beta_i^k {\:}_i^k
+    {\mathbb{S}_w}_{i_p}^{k_p} (S) \right]. \notag \\
+  \intertext{Substituting  ${\:}_i^k {\mathbb{S}_w}_{i_p}^{k_p}$ from \autoref{eq:TRIADS_skewfluxw}, gives}
+  % and separating out
+  % $\rtriadt{R}=\rtriad{R} + \delta_{i+i_p}[z_T^k]$,
+  % gives two terms. The
+  % first $\rtriad{R}$ term (the only term for $z$-coordinates) is:
+  &=-\fractext{1}{4} g{A_e}_i^k{\: }{b_u}_{i+i_p}^k {_i^k\tilde{\mathbb{R}}_{i_p}^{k_p}}
+    \frac{ -\alpha _i^k\delta_{i+ i_p}[T^k]+ \beta_i^k\delta_{i+ i_p}[S^k]} { {e_{1u}}_{\,i + i_p}^{\,k} } \notag \\
+  &=+\fractext{1}{4} g{A_e}_i^k{\: }{b_u}_{i+i_p}^k
+    \left({_i^k\mathbb{R}_{i_p}^{k_p}}+\frac{\delta_{i+i_p}[z_T^k]}{{e_{1u}}_{\,i + i_p}^{\,k}}\right) {_i^k\mathbb{R}_{i_p}^{k_p}}
+    \frac{-\alpha_i^k \delta_{k+ k_p}[T^i]+ \beta_i^k\delta_{k+ k_p}[S^i]} {{e_{3w}}_{\,i}^{\,k+k_p}},
+\end{align}
+using the definition of the triad slope $\rtriad{R}$, \autoref{eq:TRIADS_R} to
+express $-\alpha _i^k\delta_{i+ i_p}[T^k]+\beta_i^k\delta_{i+ i_p}[S^k]$ in terms of
+$-\alpha_i^k \delta_{k+ k_p}[T^i]+ \beta_i^k\delta_{k+ k_p}[S^i]$.
+
+Where the coordinates slope, the $i$-flux gives a PE change
+\begin{multline}
+  \label{eq:TRIADS_lat_densityPE}
+  g \delta_{i+i_p}[z_T^k]
+  \left[
+    -\alpha _i^k {\:}_i^k {\mathbb{S}_u}_{i_p}^{k_p} (T) + \beta_i^k {\:}_i^k {\mathbb{S}_u}_{i_p}^{k_p} (S)
+  \right] \\
+  = +\fractext{1}{4} g{A_e}_i^k{\: }{b_u}_{i+i_p}^k
+  \frac{\delta_{i+i_p}[z_T^k]}{{e_{1u}}_{\,i + i_p}^{\,k}}
+  \left({_i^k\mathbb{R}_{i_p}^{k_p}}+\frac{\delta_{i+i_p}[z_T^k]}{{e_{1u}}_{\,i + i_p}^{\,k}}\right)
+  \frac{-\alpha_i^k \delta_{k+ k_p}[T^i]+ \beta_i^k\delta_{k+ k_p}[S^i]} {{e_{3w}}_{\,i}^{\,k+k_p}},
+\end{multline}
+(using \autoref{eq:TRIADS_skewfluxu}) and so the total PE change \autoref{eq:TRIADS_vert_densityPE} +
+\autoref{eq:TRIADS_lat_densityPE} associated with the triad fluxes is
+\begin{multline*}
+  % \label{eq:TRIADS_tot_densityPE}
+  g{e_{3w}}_{\,i}^{\,k+k_p}{\mathbb{S}_w}_{i_p}^{k_p} (\rho) +
+  g\delta_{i+i_p}[z_T^k] {\:}_i^k {\mathbb{S}_u}_{i_p}^{k_p} (\rho) \\
+  = +\fractext{1}{4} g{A_e}_i^k{\: }{b_u}_{i+i_p}^k
+  \left({_i^k\mathbb{R}_{i_p}^{k_p}}+\frac{\delta_{i+i_p}[z_T^k]}{{e_{1u}}_{\,i + i_p}^{\,k}}\right)^2
+  \frac{-\alpha_i^k \delta_{k+ k_p}[T^i]+ \beta_i^k\delta_{k+ k_p}[S^i]} {{e_{3w}}_{\,i}^{\,k+k_p}}.
+\end{multline*}
+Where the fluid is stable, with $-\alpha_i^k \delta_{k+ k_p}[T^i]+
+\beta_i^k\delta_{k+ k_p}[S^i]<0$, this PE change is negative.
+
+%% =================================================================================================
+\subsection{Treatment of the triads at the boundaries}
+\label{sec:TRIADS_skew_bdry}
+
+Triad slopes \rtriadt{R} used for the calculation of the eddy-induced skew-fluxes are masked at the boundaries
+in exactly the same way as are the triad slopes \rtriad{R} used for the iso-neutral diffusive fluxes,
+as described in \autoref{sec:TRIADS_iso_bdry} and \autoref{fig:TRIADS_bdry_triads}.
+Thus surface layer triads $\triadt{i}{1}{R}{1/2}{-1/2}$ and $\triadt{i+1}{1}{R}{-1/2}{-1/2}$ are masked,
+and both near bottom triad slopes $\triadt{i}{k}{R}{1/2}{1/2}$ and $\triadt{i+1}{k}{R}{-1/2}{1/2}$ are masked when
+either of the $i,k+1$ or $i+1,k+1$ tracer points is masked, \ie\ the $i,k+1$ $u$-point is masked.
+The namelist parameter \np{ln_botmix_triad}{ln\_botmix\_triad} has no effect on the eddy-induced skew-fluxes.
+
+%% =================================================================================================
+\subsection{Limiting of the slopes within the interior}
+\label{sec:TRIADS_limitskew}
+
+Presently, the iso-neutral slopes $\tilde{r}_i$ relative to geopotentials are limited to be less than $1/100$,
+exactly as in calculating the iso-neutral diffusion, \S \autoref{sec:TRIADS_limit}.
+Each individual triad \rtriadt{R} is so limited.
+
+%% =================================================================================================
+\subsection{Tapering within the surface mixed layer}
+\label{sec:TRIADS_taperskew}
+
+The slopes $\tilde{r}_i$ relative to geopotentials (and thus the individual triads \rtriadt{R})
+are always tapered linearly from their value immediately below the mixed layer to zero at the surface
+\autoref{eq:TRIADS_rmtilde}, as described in \autoref{sec:TRIADS_lintaper}.
+This is option (c) of \autoref{fig:LDF_eiv_slp}.
+This linear tapering for the slopes used to calculate the eddy-induced fluxes is unaffected by
+the value of \np{ln_triad_iso}{ln\_triad\_iso}.
+
+The justification for this linear slope tapering is that, for $A_e$ that is constant or varies only in
+the horizontal (the most commonly used options in \NEMO: see \autoref{sec:LDF_coef}),
+it is equivalent to a horizontal eiv (eddy-induced velocity) that is uniform within the mixed layer
+\autoref{eq:TRIADS_eiv_v}.
+This ensures that the eiv velocities do not restratify the mixed layer \citep{treguier.held.ea_JPO97,danabasoglu.ferrari.ea_JC08}.
+Equivantly, in terms of the skew-flux formulation we use here,
+the linear slope tapering within the mixed-layer gives a linearly varying vertical flux,
+and so a tracer convergence uniform in depth
+(the horizontal flux convergence is relatively insignificant within the mixed-layer).
+
+%% =================================================================================================
+\subsection{Streamfunction diagnostics}
+\label{sec:TRIADS_sfdiag}
+
+Where the namelist parameter \np[=.true.]{ln_traldf_gdia}{ln\_traldf\_gdia},
+diagnosed mean eddy-induced velocities are output.
+Each time step, streamfunctions are calculated in the $i$-$k$ and $j$-$k$ planes at
+$uw$ (integer +1/2 $i$, integer $j$, integer +1/2 $k$) and $vw$ (integer $i$, integer +1/2 $j$, integer +1/2 $k$)
+points (see Table \autoref{tab:DOM_cell}) respectively.
+We follow \citep{griffies_bk04} and calculate the streamfunction at a given $uw$-point from
+the surrounding four triads according to:
+\[
+  % \label{eq:TRIADS_sfdiagi}
+  {\psi_1}_{i+1/2}^{k+1/2}={\fractext{1}{4}}\sum_{\substack{i_p,\,k_p}}
+  {A_e}_{i+1/2-i_p}^{k+1/2-k_p}\:\triadd{i+1/2-i_p}{k+1/2-k_p}{R}{i_p}{k_p}.
+\]
+The streamfunction $\psi_1$ is calculated similarly at $vw$ points.
+The eddy-induced velocities are then calculated from the straightforward discretisation of \autoref{eq:TRIADS_eiv_v}:
+\[
+  % \label{eq:TRIADS_eiv_v_discrete}
+  \begin{split}
+    {u^*}_{i+1/2}^{k} & = - \frac{1}{{e_{3u}}_{i}^{k}}\left({\psi_1}_{i+1/2}^{k+1/2}-{\psi_1}_{i+1/2}^{k+1/2}\right),   \\
+    {v^*}_{j+1/2}^{k} & = - \frac{1}{{e_{3v}}_{j}^{k}}\left({\psi_2}_{j+1/2}^{k+1/2}-{\psi_2}_{j+1/2}^{k+1/2}\right),   \\
+    {w^*}_{i,j}^{k+1/2} & =    \frac{1}{e_{1t}e_{2t}}\; \left\{
+      {e_{2u}}_{i+1/2}^{k+1/2} \,{\psi_1}_{i+1/2}^{k+1/2} -
+      {e_{2u}}_{i-1/2}^{k+1/2} \,{\psi_1}_{i-1/2}^{k+1/2} \right. + \\
+    \phantom{=} & \qquad\qquad\left. {e_{2v}}_{j+1/2}^{k+1/2} \,{\psi_2}_{j+1/2}^{k+1/2} - {e_{2v}}_{j-1/2}^{k+1/2} \,{\psi_2}_{j-1/2}^{k+1/2} \right\},
+  \end{split}
+\]
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ASM.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ASM.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ASM.tex	(revision 14097)
@@ -0,0 +1,198 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Apply Assimilation Increments (ASM)}
+\label{chap:ASM}
+
+%    {\em 4.0} & {\em D. J. Lea} & {\em \NEMO\ 4.0 updates}  \\
+%    {\em 3.4} & {\em D. J. Lea, M. Martin, K. Mogensen, A. Weaver} & {\em Initial version}  \\
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+The ASM code adds the functionality to apply increments to the model variables: temperature, salinity,
+sea surface height, velocity and sea ice concentration.
+These are read into the model from a NetCDF file which may be produced by separate data assimilation code.
+The code can also output model background fields which are used as an input to data assimilation code.
+This is all controlled by the namelist \nam{_asminc}{\_asminc}.
+There is a brief description of all the namelist options provided.
+To build the ASM code \key{asminc} must be set.
+
+%% =================================================================================================
+\section{Direct initialization}
+\label{sec:ASM_DI}
+
+Direct initialization (DI) refers to the instantaneous correction of the model background state using
+the analysis increment.
+DI is used when \np{ln_asmdin}{ln\_asmdin} is set to true.
+
+%% =================================================================================================
+\section{Incremental analysis updates}
+\label{sec:ASM_IAU}
+
+Rather than updating the model state directly with the analysis increment,
+it may be preferable to introduce the increment gradually into the ocean model in order to
+minimize spurious adjustment processes.
+This technique is referred to as Incremental Analysis Updates (IAU) \citep{bloom.takacs.ea_MWR96}.
+IAU is a common technique used with 3D assimilation methods such as 3D-Var or OI.
+IAU is used when \np{ln_asmiau}{ln\_asmiau} is set to true.
+
+With IAU, the model state trajectory ${\mathbf x}$ in the assimilation window ($t_{0} \leq t_{i} \leq t_{N}$)
+is corrected by adding the analysis increments for temperature, salinity, horizontal velocity and SSH as
+additional tendency terms to the prognostic equations:
+\begin{align*}
+  % \label{eq:ASM_wa_traj_iau}
+  {\mathbf x}^{a}(t_{i}) = M(t_{i}, t_{0})[{\mathbf x}^{b}(t_{0})] \; + \; F_{i} \delta \tilde{\mathbf x}^{a}
+\end{align*}
+where $F_{i}$ is a weighting function for applying the increments $\delta\tilde{\mathbf x}^{a}$ defined such that
+$\sum_{i=1}^{N} F_{i}=1$.
+${\mathbf x}^b$ denotes the model initial state and ${\mathbf x}^a$ is the model state after the increments are applied.
+To control the adjustment time of the model to the increment,
+the increment can be applied over an arbitrary sub-window, $t_{m} \leq t_{i} \leq t_{n}$,
+of the main assimilation window, where $t_{0} \leq t_{m} \leq t_{i}$ and $t_{i} \leq t_{n} \leq t_{N}$.
+Typically the increments are spread evenly over the full window.
+In addition, two different weighting functions have been implemented.
+The first function (namelist option \np{niaufn}{niaufn}=0) employs constant weights,
+\begin{align}
+  \label{eq:ASM_F1_i}
+  F^{(1)}_{i}
+  =\left\{
+  \begin{array}{ll}
+    0     &    {\mathrm if} \; \; \; t_{i} < t_{m}                \\
+    1/M &    {\mathrm if} \; \; \; t_{m} < t_{i} \leq t_{n} \\
+    0     &    {\mathrm if} \; \; \; t_{i} > t_{n}
+  \end{array}
+            \right.
+\end{align}
+where $M = m-n$.
+The second function (namelist option \np{niaufn}{niaufn}=1) employs peaked hat-like weights in order to give maximum weight in the centre of the sub-window,
+with the weighting reduced linearly to a small value at the window end-points:
+\begin{align}
+  \label{eq:ASM_F2_i}
+  F^{(2)}_{i}
+  =\left\{
+  \begin{array}{ll}
+    0                           &    {\mathrm if} \; \; \; t_{i}       <     t_{m}                        \\
+    \alpha \, i               &    {\mathrm if} \; \; \; t_{m}    \leq t_{i}    \leq   t_{M/2}   \\
+    \alpha \, (M - i +1) &    {\mathrm if} \; \; \; t_{M/2}  <    t_{i}    \leq   t_{n}       \\
+    0                            &   {\mathrm if} \; \; \; t_{i}        >    t_{n}
+  \end{array}
+                                   \right.
+\end{align}
+where $\alpha^{-1} = \sum_{i=1}^{M/2} 2i$ and $M$ is assumed to be even.
+The weights described by \autoref{eq:ASM_F2_i} provide a smoother transition of the analysis trajectory from
+one assimilation cycle to the next than that described by \autoref{eq:ASM_F1_i}.
+
+%% =================================================================================================
+\section{Divergence damping initialisation}
+\label{sec:ASM_div_dmp}
+
+It is quite challenging for data assimilation systems to provide non-divergent velocity increments.
+Applying divergent velocity increments will likely cause spurious vertical velocities in the model. This section describes a method to take velocity increments provided to \NEMO\ ($u^0_I$ and $v^0_I$) and adjust them by the iterative application of a divergence damping operator. The method is also described in \citet{dobricic.pinardi.ea_OS07}.
+
+In iteration step $n$ (starting at $n=1$) new estimates of velocity increments $u^{n}_I$ and $v^{n}_I$ are updated by:
+
+\begin{equation}
+  \label{eq:ASM_dmp}
+  \left\{
+    \begin{aligned}
+      u^{n}_I = u^{n-1}_I + \frac{1}{e_{1u} } \delta_{i+1/2} \left( {A_D
+          \;\chi^{n-1}_I } \right) \\ \\
+      v^{n}_I = v^{n-1}_I + \frac{1}{e_{2v} } \delta_{j+1/2} \left( {A_D
+          \;\chi^{n-1}_I } \right) \\
+    \end{aligned}
+  \right.,
+\end{equation}
+
+where the divergence is defined as
+
+\[
+  % \label{eq:ASM_div}
+  \chi^{n-1}_I = \frac{1}{e_{1t}\,e_{2t}\,e_{3t} }
+  \left( {\delta_i \left[ {e_{2u}\,e_{3u}\,u^{n-1}_I} \right]
+      +\delta_j \left[ {e_{1v}\,e_{3v}\,v^{n-1}_I} \right]} \right).
+\]
+
+By the application of \autoref{eq:ASM_dmp} the divergence is filtered in each iteration,
+and the vorticity is left unchanged.
+In the presence of coastal boundaries with zero velocity increments perpendicular to the coast
+the divergence is strongly damped.
+This type of the initialisation reduces the vertical velocity magnitude and
+alleviates the problem of the excessive unphysical vertical mixing in the first steps of the model integration
+\citep{talagrand_JAS72, dobricic.pinardi.ea_OS07}.
+Diffusion coefficients are defined as $A_D = \alpha e_{1t} e_{2t}$, where $\alpha = 0.2$.
+The divergence damping is activated by assigning to \np{nn_divdmp}{nn\_divdmp} in the \nam{_asminc}{\_asminc} namelist
+a value greater than zero.
+This specifies the number of iterations of the divergence damping. Setting a value of the order of 100 will result in a significant reduction in the vertical velocity induced by the increments.
+
+%% =================================================================================================
+\section{Implementation details}
+\label{sec:ASM_details}
+
+Here we show an example \nam{_asminc}{\_asminc} namelist and the header of an example assimilation increments file on
+the ORCA2 grid.
+
+\begin{listing}
+  \nlst{nam_asminc}
+  \caption{\forcode{&nam_asminc}}
+  \label{lst:nam_asminc}
+\end{listing}
+
+The header of an assimilation increments file produced using the NetCDF tool
+\mbox{\textit{ncdump~-h}} is shown below
+
+\begin{clines}
+netcdf assim_background_increments {
+dimensions:
+        x = 182 ;
+        y = 149 ;
+        z = 31 ;
+        t = UNLIMITED ; // (1 currently)
+variables:
+        float nav_lon(y, x) ;
+        float nav_lat(y, x) ;
+        float nav_lev(z) ;
+        double time_counter(t) ;
+        double time ;
+        double z_inc_dateb ;
+        double z_inc_datef ;
+        double bckint(t, z, y, x) ;
+        double bckins(t, z, y, x) ;
+        double bckinu(t, z, y, x) ;
+        double bckinv(t, z, y, x) ;
+        double bckineta(t, y, x) ;
+
+// global attributes:
+                :DOMAIN_number_total = 1 ;
+                :DOMAIN_number = 0 ;
+                :DOMAIN_dimensions_ids = 1, 2 ;
+                :DOMAIN_size_global = 182, 149 ;
+                :DOMAIN_size_local = 182, 149 ;
+                :DOMAIN_position_first = 1, 1 ;
+                :DOMAIN_position_last = 182, 149 ;
+                :DOMAIN_halo_size_start = 0, 0 ;
+                :DOMAIN_halo_size_end = 0, 0 ;
+                :DOMAIN_type = "BOX" ;
+}
+\end{clines}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIA.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIA.tex	(revision 14097)
@@ -0,0 +1,2050 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Output and Diagnostics (IOM, DIA, TRD, FLO)}
+\label{chap:DIA}
+
+%    {\em 4.0} & {\em Mirek Andrejczuk, Massimiliano Drudi} & {\em }  \\
+%    {\em }      & {\em Dorotea Iovino, Nicolas Martin} & {\em }  \\
+%    {\em 3.6} & {\em Gurvan Madec, Sebastien Masson } & {\em }  \\
+%    {\em 3.4} & {\em Gurvan Madec, Rachid Benshila, Andrew Coward } & {\em }  \\
+%    {\em }      & {\em Christian Ethe, Sebastien Masson } & {\em }  \\
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Model output}
+\label{sec:DIA_io_old}
+
+The model outputs are of three types: the restart file, the output listing, and the diagnostic output file(s).
+The restart file is used internally by the code when the user wants to start the model with
+initial conditions defined by a previous simulation.
+It contains all the information that is necessary in order for there to be no changes in the model results
+(even at the computer precision) between a run performed with several restarts and
+the same run performed in one step.
+It should be noted that this requires that the restart file contains two consecutive time steps for
+all the prognostic variables.
+
+The output listing and file(s) are predefined but should be checked and eventually adapted to the user's needs.
+The output listing is stored in the \textit{ocean.output} file.
+The information is printed from within the code on the logical unit \texttt{numout}.
+To locate these prints, use the UNIX command "\textit{grep -i numout}" in the source code directory.
+
+By default, diagnostic output files are written in NetCDF format.
+Since version 3.2, when defining \key{iomput}, an I/O server has been added which
+provides more flexibility in the choice of the fields to be written as well as how
+the writing work is distributed over the processors in massively parallel computing.
+A complete description of the use of this I/O server is presented in the next section.
+
+%\cmtgm{                    % start of gmcomment
+
+%% =================================================================================================
+\section{Standard model output (IOM)}
+\label{sec:DIA_iom}
+
+Since version 3.2, iomput is the \NEMO\ output interface of choice.
+It has been designed to be simple to use, flexible and efficient.
+The two main purposes of iomput are:
+
+\begin{enumerate}
+\item The complete and flexible control of the output files through external XML files adapted by
+  the user from standard templates.
+\item To achieve high performance and scalable output through the optional distribution of
+  all diagnostic output related tasks to dedicated processes.
+\end{enumerate}
+
+The first functionality allows the user to specify, without code changes or recompilation,
+aspects of the diagnostic output stream, such as:
+
+\begin{itemize}
+\item The choice of output frequencies that can be different for each file (including real months and years).
+\item The choice of file contents; includes complete flexibility over which data are written in which files
+  (the same data can be written in different files).
+\item The possibility to split output files at a chosen frequency.
+\item The possibility to extract a vertical or an horizontal subdomain.
+\item The choice of the temporal operation to perform, \eg: average, accumulate, instantaneous, min, max and once.
+\item Control over metadata via a large XML "database" of possible output fields.
+\end{itemize}
+
+In addition, iomput allows the user to add in the code the output of any new variable (scalar, 2D or 3D)
+in a very easy way.
+All details of iomput functionalities are listed in the following subsections.
+Examples of the XML files that control the outputs can be found in:
+\path{cfgs/ORCA2_ICE_PISCES/EXPREF/iodef.xml},
+\path{cfgs/SHARED/field_def_nemo-oce.xml},
+\path{cfgs/SHARED/field_def_nemo-pisces.xml},
+\path{cfgs/SHARED/field_def_nemo-ice.xml} and \path{cfgs/SHARED/domain_def_nemo.xml}. \\
+
+The second functionality targets output performance when running in parallel (\key{mpp\_mpi}).
+Iomput provides the possibility to specify N dedicated I/O processes (in addition to the \NEMO\ processes)
+to collect and write the outputs.
+With an appropriate choice of N by the user, the bottleneck associated with the writing of
+the output files can be greatly reduced.
+
+In version 3.6, the \rou{iom\_put} interface depends on
+an external code called \href{https://forge.ipsl.jussieu.fr/ioserver/browser/XIOS/branchs/xios-2.5}{XIOS-2.5}
+%(use of revision 618 or higher is required).
+This new IO server can take advantage of the parallel I/O functionality of NetCDF4 to
+create a single output file and therefore to bypass the rebuilding phase.
+Note that writing in parallel into the same NetCDF files requires that your NetCDF4 library is linked to
+an HDF5 library that has been correctly compiled (\ie\ with the configure option $--$enable-parallel).
+Note that the files created by iomput through XIOS are incompatible with NetCDF3.
+All post-processsing and visualization tools must therefore be compatible with NetCDF4 and not only NetCDF3.
+
+Even if not using the parallel I/O functionality of NetCDF4, using N dedicated I/O servers,
+where N is typically much less than the number of \NEMO\ processors, will reduce the number of output files created.
+This can greatly reduce the post-processing burden usually associated with using large numbers of \NEMO\ processors.
+Note that for smaller configurations, the rebuilding phase can be avoided,
+even without a parallel-enabled NetCDF4 library, simply by employing only one dedicated I/O server.
+
+%% =================================================================================================
+\subsection{XIOS: Reading and writing restart file}
+
+XIOS may be used to read single file restart produced by \NEMO. Currently only the variables written to
+file \forcode{numror} can be handled by XIOS. To activate restart reading using XIOS, set \np[=.true. ]{ln_xios_read}{ln\_xios\_read}
+in \textit{namelist\_cfg}. This setting will be ignored when multiple restart files are present, and default \NEMO
+functionality will be used for reading. There is no need to change iodef.xml file to use XIOS to read
+restart, all definitions are done within the \NEMO\ code. For high resolution configuration, however,
+there may be a need to add the following line in iodef.xml (xios context):
+
+\begin{xmllines}
+<variable id="recv_field_timeout"        type="double">1800</variable>
+\end{xmllines}
+
+This variable sets timeout for reading.
+
+If XIOS is to be used to read restart from file generated with an earlier \NEMO\ version (3.6 for instance),
+dimension \forcode{z} defined in restart file must be renamed to \forcode{nav_lev}.\\
+
+XIOS can also be used to write \NEMO\ restart. A namelist parameter \np{nn_wxios}{nn\_wxios} is used to determine the
+type of restart \NEMO\ will write. If it is set to 0, default \NEMO\ functionality will be used - each
+processor writes its own restart file; if it is set to 1 XIOS will write restart into a single file;
+for \np[=2]{nn_wxios}{nn\_wxios} the restart will be written by XIOS into multiple files, one for each XIOS server.
+Note, however, that \textbf{\NEMO\ will not read restart generated by XIOS when \np[=2]{nn_wxios}{nn\_wxios}}. The restart will
+have to be rebuild before continuing the run. This option aims to reduce number of restart files generated by \NEMO\ only,
+and may be useful when there is a need to change number of processors used to run simulation.
+
+If an additional variable must be written to a restart file, the following steps are needed:
+\begin{enumerate}
+\item Add variable name to a list of restart variables (in subroutine \rou{iom\_set\_rst\_vars,} \mdl{iom}) and
+define correct grid for the variable (\forcode{grid_N_3D} - 3D variable, \forcode{grid_N} - 2D variable, \forcode{grid_vector} -
+1D variable, \forcode{grid_scalar} - scalar),
+\item Add variable to the list of fields written by restart.  This can be done either in subroutine
+\rou{iom\_set\_rstw\_core} (\mdl{iom}) or by calling  \rou{iom\_set\_rstw\_active} (\mdl{iom}) with the name of a variable
+as an argument. This convention follows approach for writing restart using iom, where variables are
+written either by \rou{rst\_write} or by calling \rou{iom\_rstput} from individual routines.
+\end{enumerate}
+
+An older versions of XIOS do not support reading functionality. It's recommended to use at least XIOS2@1451.
+
+%% =================================================================================================
+\subsection{XIOS: XML Inputs-Outputs Server}
+
+%% =================================================================================================
+\subsubsection{Attached or detached mode?}
+
+Iomput is based on \href{http://forge.ipsl.jussieu.fr/ioserver/wiki}{XIOS},
+the io\_server developed by Yann Meurdesoif from IPSL.
+The behaviour of the I/O subsystem is controlled by settings in the external XML files listed above.
+Key settings in the iodef.xml file are the tags associated with each defined file.
+
+\xmlline|<variable id="using_server" type="bool"></variable>|
+
+The \texttt{using\_server} setting determines whether or not the server will be used in
+\textit{attached mode}
+(as a library) [\texttt{> false <}] or in \textit{detached mode}
+(as an external executable on N additional, dedicated cpus) [\texttt{ > true <}].
+The \textit{attached mode} is simpler to use but much less efficient for
+massively parallel applications.
+The type of each file can be either ''multiple\_file'' or ''one\_file''.
+
+In \textit{attached mode} and if the type of file is ''multiple\_file'',
+then each \NEMO\ process will also act as an IO server and produce its own set of output files.
+Superficially, this emulates the standard behaviour in previous versions.
+However, the subdomain written out by each process does not correspond to
+the \forcode{jpi x jpj x jpk} domain actually computed by the process (although it may if \forcode{jpni=1}).
+Instead each process will have collected and written out a number of complete longitudinal strips.
+If the ''one\_file'' option is chosen then all processes will collect their longitudinal strips and
+write (in parallel) to a single output file.
+
+In \textit{detached mode} and if the type of file is ''multiple\_file'',
+then each stand-alone XIOS process will collect data for a range of complete longitudinal strips and
+write to its own set of output files.
+If the ''one\_file'' option is chosen then all XIOS processes will collect their longitudinal strips and
+write (in parallel) to a single output file.
+Note running in detached mode requires launching a Multiple Process Multiple Data (MPMD) parallel job.
+The following subsection provides a typical example but the syntax will vary in different MPP environments.
+
+%% =================================================================================================
+\subsubsection{Number of cpu used by XIOS in detached mode}
+
+The number of cores used by the XIOS is specified when launching the model.
+The number of cores dedicated to XIOS should be from \texttildelow1/10 to \texttildelow1/50 of the number of
+cores dedicated to \NEMO.
+Some manufacturers suggest using O($\sqrt{N}$) dedicated IO processors for N processors but
+this is a general recommendation and not specific to \NEMO.
+It is difficult to provide precise recommendations because the optimal choice will depend on
+the particular hardware properties of the target system
+(parallel filesystem performance, available memory, memory bandwidth etc.)
+and the volume and frequency of data to be created.
+Here is an example of 2 cpus for the io\_server and 62 cpu for nemo using mpirun:
+\cmd|mpirun -np 62 ./nemo.exe : -np 2 ./xios_server.exe|
+
+%% =================================================================================================
+\subsubsection{Control of XIOS: the context in iodef.xml}
+
+As well as the \texttt{using\_server} flag, other controls on the use of XIOS are set in
+the XIOS context in \textit{iodef.xml}.
+See the XML basics section below for more details on XML syntax and rules.
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|lXl|}
+    \hline
+    variable name                                                           &
+    description                                                             &
+    example  \\
+    \hline
+    \hline
+    buffer\_size                                                            &
+    buffer size used by XIOS to send data from \NEMO\ to XIOS.
+    Larger is more efficient.
+    Note that needed/used buffer sizes are summarized at the end of the job &
+    25000000 \\
+    \hline
+    buffer\_server\_factor\_size                                            &
+    ratio between \NEMO\ and XIOS buffer size.
+    Should be 2.                                                            &
+    2        \\
+    \hline
+    info\_level                                                             &
+    verbosity level (0 to 100)                                              &
+    0        \\
+    \hline
+    using\_server                                                           &
+    activate attached(false) or detached(true) mode                         &
+    true     \\
+    \hline
+    using\_oasis                                                            &
+    XIOS is used with OASIS(true) or not (false)                            &
+    false    \\
+    \hline
+    oasis\_codes\_id                                                        &
+    when using oasis, define the identifier of \NEMO\ in the namcouple.
+    Note that the identifier of XIOS is xios.x                              &
+    oceanx   \\
+    \hline
+  \end{tabularx}
+\end{table}
+
+%% =================================================================================================
+\subsection{Practical issues}
+
+%% =================================================================================================
+\subsubsection{Installation}
+
+As mentioned, XIOS is supported separately and must be downloaded and compiled before it can be used with \NEMO.
+See the installation guide on the \href{http://forge.ipsl.jussieu.fr/ioserver/wiki}{XIOS} wiki for help and guidance.
+\NEMO\ will need to link to the compiled XIOS library.
+The \href{https://forge.ipsl.jussieu.fr/nemo/chrome/site/doc/NEMO/guide/html/install.html#extract-and-install-xios}
+{Extract and install XIOS} guide provides an example illustration of how this can be achieved.
+
+%% =================================================================================================
+\subsubsection{Add your own outputs}
+
+It is very easy to add your own outputs with iomput.
+Many standard fields and diagnostics are already prepared (\ie, steps 1 to 3 below have been done) and
+simply need to be activated by including the required output in a file definition in iodef.xml (step 4).
+To add new output variables, all 4 of the following steps must be taken.
+
+\begin{enumerate}
+\item in \NEMO\ code, add a \forcode{CALL iom_put( 'identifier', array )} where you want to output a 2D or 3D array.
+\item If necessary, add \forcode{USE iom ! I/O manager library} to the list of used modules in
+  the upper part of your module.
+\item in the field\_def.xml file, add the definition of your variable using the same identifier you used in the f90 code
+  (see subsequent sections for a details of the XML syntax and rules).
+  For example:
+\begin{xmllines}
+<field_definition>
+	<field_group id="grid_T" grid_ref="grid_T_3D"> <!-- T grid -->
+	...
+		<field id="identifier" long_name="blabla" ... />
+		...
+</field_definition>
+\end{xmllines}
+Note your definition must be added to the field\_group whose reference grid is consistent with the size of
+the array passed to iomput.
+The grid\_ref attribute refers to definitions set in iodef.xml which, in turn,
+reference grids and axes either defined in the code
+(iom\_set\_domain\_attr and iom\_set\_axis\_attr in \mdl{iom}) or defined in the domain\_def.xml file.
+\eg:
+\begin{xmllines}
+<grid id="grid_T_3D" domain_ref="grid_T" axis_ref="deptht"/>
+\end{xmllines}
+Note, if your array is computed within the surface module each \np{nn_fsbc}{nn\_fsbc} time\_step,
+add the field definition within the field\_group defined with the id "SBC":
+\xmlcode{<field_group id="SBC" ...>} which has been defined with the correct frequency of operations
+(iom\_set\_field\_attr in \mdl{iom})
+\item add your field in one of the output files defined in iodef.xml
+  (again see subsequent sections for syntax and rules)
+\begin{xmllines}
+<file id="file1" .../>
+...
+	<field field_ref="identifier" />
+	...
+</file>
+\end{xmllines}
+\end{enumerate}
+
+%% =================================================================================================
+\subsection{XML fundamentals}
+
+%% =================================================================================================
+\subsubsection{ XML basic rules}
+
+XML tags begin with the less-than character ("$<$") and end with the greater-than character ("$>$").
+You use tags to mark the start and end of elements, which are the logical units of information in an XML document.
+In addition to marking the beginning of an element, XML start tags also provide a place to specify attributes.
+An attribute specifies a single property for an element, using a name/value pair, for example:
+\xmlcode{<a b="x" c="y" d="z"> ... </a>}.
+See \href{http://www.xmlnews.org/docs/xml-basics.html}{here} for more details.
+
+%% =================================================================================================
+\subsubsection{Structure of the XML file used in \NEMO}
+
+The XML file used in XIOS is structured by 7 families of tags:
+context, axis, domain, grid, field, file and variable.
+Each tag family has hierarchy of three flavors (except for context):
+
+\begin{table}
+  \begin{tabular*}{\textwidth}{|p{0.15\textwidth}p{0.4\textwidth}p{0.35\textwidth}|}
+    \hline
+    flavor  & description                                                                 &
+                                                                                            example                          \\
+    \hline
+    \hline
+    root    & declaration of the root element that can contain element groups or elements &
+                                                                                            \xmlcode{<file_definition ... >} \\
+    \hline
+    group   & declaration of a group element that can contain element groups or elements  &
+                                                                                            \xmlcode{<file_group      ... >} \\
+    \hline
+    element & declaration of an element that can contain elements                         &
+                                                                                            \xmlcode{<file            ... >} \\
+    \hline
+  \end{tabular*}
+\end{table}
+
+Each element may have several attributes.
+Some attributes are mandatory, other are optional but have a default value and other are completely optional.
+Id is a special attribute used to identify an element or a group of elements.
+It must be unique for a kind of element.
+It is optional, but no reference to the corresponding element can be done if it is not defined.
+
+The XML file is split into context tags that are used to isolate IO definition from
+different codes or different parts of a code.
+No interference is possible between 2 different contexts.
+Each context has its own calendar and an associated timestep.
+In \NEMO, we used the following contexts (that can be defined in any order):
+
+\begin{table}
+  \begin{tabular}{|p{0.15\textwidth}p{0.4\textwidth}p{0.35\textwidth}|}
+    \hline
+    context         &	description                                                                &
+                                                                                                     example                              \\
+    \hline
+    \hline
+    context xios    &	context containing information for XIOS                                    &
+                                                                                                     \xmlcode{<context id="xios" ... >}   \\
+    \hline
+    context nemo    &	context containing IO information for \NEMO\ (mother grid when using AGRIF)  &
+                                                                                                     \xmlcode{<context id="nemo" ... >}   \\
+    \hline
+    context 1\_nemo &	context containing IO information for \NEMO\ child grid 1 (when using AGRIF) &
+                                                                                                     \xmlcode{<context id="1_nemo" ... >} \\
+    \hline
+    context n\_nemo &	context containing IO information for \NEMO\ child grid n (when using AGRIF) &
+                                                                                                     \xmlcode{<context id="n_nemo" ... >} \\
+    \hline
+  \end{tabular}
+\end{table}
+
+\noindent The xios context contains only 1 tag:
+
+\begin{table}
+  \begin{tabular}{|p{0.15\textwidth}p{0.4\textwidth}p{0.35\textwidth}|}
+    \hline
+    context tag                                      &
+                                                       description                                      &
+                                                                                                          example                              \\
+    \hline
+    \hline
+    variable\_definition                             &
+                                                       define variables needed by XIOS.
+                                                       This can be seen as a kind of namelist for XIOS. &
+                                                                                                          \xmlcode{<variable_definition ... >} \\
+    \hline
+	\end{tabular}
+\end{table}
+
+\noindent Each context tag related to \NEMO\ (mother or child grids) is divided into 5 parts
+(that can be defined in any order):
+
+\begin{table}
+  \begin{tabular}{|p{0.15\textwidth}p{0.4\textwidth}p{0.35\textwidth}|}
+    \hline
+    context tag        &	description                                                               &
+                                                                                                       example                            \\
+    \hline
+    \hline
+    field\_definition  &	define all variables that can potentially be outputted                    &
+                                                                                                       \xmlcode{<field_definition ... >}  \\
+    \hline
+    file\_definition   &	define the netcdf files to be created and the variables they will contain &
+                                                                                                       \xmlcode{<file_definition ... >}   \\
+    \hline
+    axis\_definition   &	define vertical axis                                                      &
+                                                                                                       \xmlcode{<axis_definition ... >}   \\
+    \hline
+    domain\_definition &	define the horizontal grids                                               &
+                                                                                                       \xmlcode{<domain_definition ... >} \\
+    \hline
+    grid\_definition   &	define the 2D and 3D grids (association of an axis and a domain)          &
+                                                                                                       \xmlcode{<grid_definition ... >}   \\
+    \hline
+  \end{tabular}
+\end{table}
+
+%% =================================================================================================
+\subsubsection{Nesting XML files}
+
+The XML file can be split in different parts to improve its readability and facilitate its use.
+The inclusion of XML files into the main XML file can be done through the attribute src:
+\xmlline|<context src="./nemo_def.xml" />|
+
+\noindent In \NEMO, by default, the field definition is done in 3 separate files (
+\path{cfgs/SHARED/field_def_nemo-oce.xml},
+\path{cfgs/SHARED/field_def_nemo-pisces.xml} and
+\path{cfgs/SHARED/field_def_nemo-ice.xml} ) and the  domain definition is done in another file ( \path{cfgs/SHARED/domain_def_nemo.xml} )
+that
+are included in the main iodef.xml file through the following commands:
+\begin{xmllines}
+<context id="nemo" src="./context_nemo.xml"/>
+\end{xmllines}
+
+%% =================================================================================================
+\subsubsection{Use of inheritance}
+
+XML extensively uses the concept of inheritance.
+XML has a tree based structure with a parent-child oriented relation: all children inherit attributes from parent,
+but an attribute defined in a child replace the inherited attribute value.
+Note that the special attribute ''id'' is never inherited.
+\\
+\\
+example 1: Direct inheritance.
+
+\begin{xmllines}
+<field_definition operation="average" >
+	<field id="sst"                    />   <!-- averaged      sst -->
+	<field id="sss" operation="instant"/>   <!-- instantaneous sss -->
+</field_definition>
+\end{xmllines}
+
+The field ''sst'' which is part (or a child) of the field\_definition will inherit the value ''average'' of
+the attribute ''operation'' from its parent.
+Note that a child can overwrite the attribute definition inherited from its parents.
+In the example above, the field ''sss'' will for example output instantaneous values instead of average values.
+\\
+\\
+example 2: Inheritance by reference.
+
+\begin{xmllines}
+<field_definition>
+	<field id="sst" long_name="sea surface temperature" />
+	<field id="sss" long_name="sea surface salinity"    />
+</field_definition>
+<file_definition>
+	<file id="myfile" output_freq="1d" />
+		<field field_ref="sst"                            />  <!-- default def -->
+		<field field_ref="sss" long_name="my description" />  <!-- overwrite   -->
+	</file>
+</file_definition>
+\end{xmllines}
+
+Inherit (and overwrite, if needed) the attributes of a tag you are refering to.
+
+%% =================================================================================================
+\subsubsection{Use of groups}
+
+Groups can be used for 2 purposes.
+Firstly, the group can be used to define common attributes to be shared by the elements of
+the group through inheritance.
+In the following example, we define a group of field that will share a common grid ''grid\_T\_2D''.
+Note that for the field ''toce'', we overwrite the grid definition inherited from the group by ''grid\_T\_3D''.
+
+\begin{xmllines}
+<field_group id="grid_T" grid_ref="grid_T_2D">
+	<field id="toce" long_name="temperature"             unit="degC" grid_ref="grid_T_3D"/>
+	<field id="sst"  long_name="sea surface temperature" unit="degC"                     />
+	<field id="sss"  long_name="sea surface salinity"    unit="psu"                      />
+	<field id="ssh"  long_name="sea surface height"      unit="m"                        />
+	...
+\end{xmllines}
+
+Secondly, the group can be used to replace a list of elements.
+Several examples of groups of fields are proposed at the end of the XML field files (
+\path{cfgs/SHARED/field_def_nemo-oce.xml},
+\path{cfgs/SHARED/field_def_nemo-pisces.xml} and
+\path{cfgs/SHARED/field_def_nemo-ice.xml} ) .
+For example, a short list of the usual variables related to the U grid:
+
+\begin{xmllines}
+<field_group id="groupU" >
+	<field field_ref="uoce"  />
+	<field field_ref="ssu" />
+	<field field_ref="utau"  />
+</field_group>
+\end{xmllines}
+
+that can be directly included in a file through the following syntax:
+
+\begin{xmllines}
+<file id="myfile_U" output_freq="1d" />
+	<field_group group_ref="groupU" />
+	<field field_ref="uocetr_eff"   />  <!-- add another field -->
+</file>
+\end{xmllines}
+
+%% =================================================================================================
+\subsection{Detailed functionalities}
+
+The file \path{NEMOGCM/CONFIG/ORCA2_LIM/iodef_demo.xml} provides several examples of the use of
+the new functionalities offered by the XML interface of XIOS.
+
+%% =================================================================================================
+\subsubsection{Define horizontal subdomains}
+
+Horizontal subdomains are defined through the attributs zoom\_ibegin, zoom\_jbegin, zoom\_ni, zoom\_nj of
+the tag family domain.
+It must therefore be done in the domain part of the XML file.
+For example, in \path{cfgs/SHARED/domain_def.xml}, we provide the following example of a definition of
+a 5 by 5 box with the bottom left corner at point (10,10).
+
+\begin{xmllines}
+<domain id="myzoomT" domain_ref="grid_T">
+	<zoom_domain ibegin="10" jbegin="10" ni="5" nj="5" />
+\end{xmllines}
+
+The use of this subdomain is done through the redefinition of the attribute domain\_ref of the tag family field.
+For example:
+
+\begin{xmllines}
+<file id="myfile_vzoom" output_freq="1d" >
+	<field field_ref="toce" domain_ref="myzoomT"/>
+</file>
+\end{xmllines}
+
+Moorings are seen as an extrem case corresponding to a 1 by 1 subdomain.
+The Equatorial section, the TAO, RAMA and PIRATA moorings are already registered in the code and
+can therefore be outputted without taking care of their (i,j) position in the grid.
+These predefined domains can be activated by the use of specific domain\_ref:
+''EqT'', ''EqU'' or ''EqW'' for the equatorial sections and
+the mooring position for TAO, RAMA and PIRATA followed by ''T'' (for example: ''8s137eT'', ''1.5s80.5eT'' ...)
+
+\begin{xmllines}
+<file id="myfile_vzoom" output_freq="1d" >
+	<field field_ref="toce" domain_ref="0n180wT"/>
+</file>
+\end{xmllines}
+
+Note that if the domain decomposition used in XIOS cuts the subdomain in several parts and if
+you use the ''multiple\_file'' type for your output files,
+you will endup with several files you will need to rebuild using unprovided tools (like ncpdq and ncrcat,
+\href{http://nco.sourceforge.net/nco.html#Concatenation}{see nco manual}).
+We are therefore advising to use the ''one\_file'' type in this case.
+
+%% =================================================================================================
+\subsubsection{Define vertical zooms}
+
+Vertical zooms are defined through the attributs zoom\_begin and zoom\_n of the tag family axis.
+It must therefore be done in the axis part of the XML file.
+For example, in \path{cfgs/ORCA2_ICE_PISCES/EXPREF/iodef_demo.xml}, we provide the following example:
+
+\begin{xmllines}
+<axis_definition>
+	<axis id="deptht" long_name="Vertical T levels" unit="m" positive="down" />
+	<axis id="deptht_zoom" azix_ref="deptht" >
+		<zoom_axis zoom_begin="1" zoom_n="10" />
+	</axis>
+\end{xmllines}
+
+The use of this vertical zoom is done through the redefinition of the attribute axis\_ref of the tag family field.
+For example:
+
+\begin{xmllines}
+<file id="myfile_hzoom" output_freq="1d" >
+	<field field_ref="toce" axis_ref="deptht_myzoom"/>
+</file>
+\end{xmllines}
+
+%% =================================================================================================
+\subsubsection{Control of the output file names}
+
+The output file names are defined by the attributs ''name'' and ''name\_suffix'' of the tag family file.
+For example:
+
+\begin{xmllines}
+<file_group id="1d" output_freq="1d" name="myfile_1d" >
+	<file id="myfileA" name_suffix="_AAA" > <!-- will create file "myfile_1d_AAA"  -->
+		...
+	</file>
+	<file id="myfileB" name_suffix="_BBB" > <!-- will create file "myfile_1d_BBB" -->
+		...
+	</file>
+</file_group>
+\end{xmllines}
+
+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{table}
+  \begin{tabularx}{\textwidth}{|lX|}
+    \hline
+    \centering placeholder string &
+    automatically replaced by                          \\
+    \hline
+    \hline
+    \centering @expname@          &
+    the experiment name (from cn\_exp in the namelist) \\
+    \hline
+    \centering @freq@             &
+    output frequency (from attribute output\_freq)     \\
+    \hline
+    \centering @startdate@        &
+    starting date of the simulation (from nn\_date0 in the restart or the namelist).
+    \newline
+    \verb?yyyymmdd?          format                   \\
+    \hline
+    \centering @startdatefull@    &
+    starting date of the simulation (from nn\_date0 in the restart or the namelist).
+    \newline
+    \verb?yyyymmdd_hh:mm:ss? format                    \\
+    \hline
+    \centering @enddate@          &
+    ending date of the simulation   (from nn\_date0 and nn\_itend  in the namelist).
+    \newline
+    \verb?yyyymmdd?          format                    \\
+    \hline
+    \centering @enddatefull@      &
+    ending date of the simulation   (from nn\_date0 and nn\_itend  in the namelist).
+    \newline
+    \verb?yyyymmdd_hh:mm:ss? format                    \\
+    \hline
+  \end{tabularx}
+\end{table}
+
+\noindent For example,
+\xmlline|<file id="myfile_hzoom" name="myfile_@expname@_@startdate@_freq@freq@" output_freq="1d" >|
+
+\noindent with the namelist:
+\begin{forlines}
+cn_exp    = "ORCA2"
+nn_date0  = 19891231
+ln_rstart = .false.
+\end{forlines}
+
+\noindent will give the following file name radical: \ifile{myfile\_ORCA2\_19891231\_freq1d}
+
+%% =================================================================================================
+\subsubsection{Other controls of the XML attributes from \NEMO}
+
+The values of some attributes are defined by subroutine calls within \NEMO
+(calls to iom\_set\_domain\_attr, iom\_set\_axis\_attr and iom\_set\_field\_attr in \mdl{iom}).
+Any definition given in the XML file will be overwritten.
+By convention, these attributes are defined to ''auto'' (for string) or ''0000'' (for integer) in the XML file
+(but this is not necessary).
+\\
+
+Here is the list of these attributes:
+\\
+
+\begin{table}
+  \begin{tabular}{|l|c|c|}
+    \hline
+    tag ids affected by automatic definition of some of their attributes &
+    name attribute                                                       &
+    attribute value                                                      \\
+    \hline
+    \hline
+    field\_definition                                                    &
+    freq\_op                                                             &
+    \np{rn_rdt}{rn\_rdt}                                                         \\
+    \hline
+    SBC                                                                  &
+    freq\_op                                                             &
+    \np{rn_rdt}{rn\_rdt} $\times$ \np{nn_fsbc}{nn\_fsbc}                                  \\
+    \hline
+    ptrc\_T                                                              &
+    freq\_op                                                             &
+    \np{rn_rdt}{rn\_rdt} $\times$ \np{nn_dttrc}{nn\_dttrc}                                 \\
+    \hline
+    diad\_T                                                              &
+    freq\_op                                                             &
+    \np{rn_rdt}{rn\_rdt} $\times$ \np{nn_dttrc}{nn\_dttrc}                                 \\
+    \hline
+    EqT, EqU, EqW                                                        &
+    jbegin, ni,                                                          &
+    according to the grid                                                \\
+                                                                         &
+    name\_suffix                                                         &
+                                                                         \\
+    \hline
+    TAO, RAMA and PIRATA moorings                                        &
+    zoom\_ibegin, zoom\_jbegin,                                          &
+    according to the grid                                                \\
+                                                                         &
+    name\_suffix                                                         &
+                                                                         \\
+    \hline
+  \end{tabular}
+\end{table}
+
+%% =================================================================================================
+\subsubsection{Advanced use of XIOS functionalities}
+
+%% =================================================================================================
+\subsection{XML reference tables}
+\label{subsec:DIA_IOM_xmlref}
+
+\begin{enumerate}
+\item Simple computation: directly define the computation when refering to the variable in the file definition.
+
+\begin{xmllines}
+<field field_ref="sst"  name="tosK"  unit="degK" > sst + 273.15 </field>
+<field field_ref="taum" name="taum2" unit="N2/m4" long_name="square of wind stress module" >	taum * taum </field>
+<field field_ref="qt"   name="stupid_check" > qt - qsr - qns </field>
+\end{xmllines}
+
+\item Simple computation: define a new variable and use it in the file definition.
+
+in field\_definition:
+
+\begin{xmllines}
+<field id="sst2" long_name="square of sea surface temperature" unit="degC2" >  sst * sst </field >
+\end{xmllines}
+
+in file\_definition:
+
+\begin{xmllines}
+<field field_ref="sst2" > sst2 </field>
+\end{xmllines}
+
+Note that in this case, the following syntaxe \xmlcode{<field field_ref="sst2" />} is not working as
+sst2 won't be evaluated.
+
+\item Change of variable precision:
+
+\begin{xmllines}
+<!-- force to keep real 8 -->
+<field field_ref="sst" name="tos_r8" prec="8" />
+<!-- integer 2  with add_offset and scale_factor attributes -->
+<field field_ref="sss" name="sos_i2" prec="2" add_offset="20." scale_factor="1.e-3" />
+\end{xmllines}
+
+Note that, then the code is crashing, writting real4 variables forces a numerical conversion from
+real8 to real4 which will create an internal error in NetCDF and will avoid the creation of the output files.
+Forcing double precision outputs with prec="8" (for example in the field\_definition) will avoid this problem.
+
+\item add user defined attributes:
+
+\begin{xmllines}
+<file_group id="1d" output_freq="1d" output_level="10" enabled=".true."> <!-- 1d files -->
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+		<field field_ref="sst" name="tos" >
+			<variable id="my_attribute1" type="string"  > blabla </variable>
+			<variable id="my_attribute2" type="integer" > 3      </variable>
+			<variable id="my_attribute3" type="float"   > 5.0    </variable>
+		</field>
+		<variable id="my_global_attribute" type="string" > blabla_global </variable>
+	</file>
+</file_group>
+\end{xmllines}
+
+\item use of the ``@'' function: example 1, weighted temporal average
+
+ - define a new variable in field\_definition
+
+\begin{xmllines}
+<field id="toce_e3t" long_name="temperature * e3t" unit="degC*m" grid_ref="grid_T_3D" >toce * e3t</field>
+\end{xmllines}
+
+ - use it when defining your file.
+
+\begin{xmllines}
+<file_group id="5d" output_freq="5d"  output_level="10" enabled=".true." >  <!-- 5d files -->
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+		<field field_ref="toce" operation="instant" freq_op="5d" > @toce_e3t / @e3t </field>
+	</file>
+</file_group>
+\end{xmllines}
+
+The freq\_op="5d" attribute is used to define the operation frequency of the ``@'' function: here 5 day.
+The temporal operation done by the ``@'' is the one defined in the field definition:
+here we use the default, average.
+So, in the above case, @toce\_e3t will do the 5-day mean of toce*e3t.
+Operation="instant" refers to the temporal operation to be performed on the field''@toce\_e3t / @e3t'':
+here the temporal average is alreday done by the ``@'' function so we just use instant to do the ratio of
+the 2 mean values.
+field\_ref="toce" means that attributes not explicitely defined, are inherited from toce field.
+Note that in this case, freq\_op must be equal to the file output\_freq.
+
+\item use of the ``@'' function: example 2, monthly SSH standard deviation
+
+ - define a new variable in field\_definition
+
+\begin{xmllines}
+<field id="ssh2" long_name="square of sea surface temperature" unit="degC2" > ssh * ssh </field >
+\end{xmllines}
+
+ - use it when defining your file.
+
+\begin{xmllines}
+<file_group id="1m" output_freq="1m"  output_level="10" enabled=".true." >  <!-- 1m files -->
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+		<field field_ref="ssh" name="sshstd" long_name="sea_surface_temperature_standard_deviation"
+		operation="instant" freq_op="1m" >
+			sqrt( @ssh2 - @ssh * @ssh )
+		</field>
+	</file>
+</file_group>
+\end{xmllines}
+
+The freq\_op="1m" attribute is used to define the operation frequency of the ``@'' function: here 1 month.
+The temporal operation done by the ``@'' is the one defined in the field definition:
+here we use the default, average.
+So, in the above case, @ssh2 will do the monthly mean of ssh*ssh.
+Operation="instant" refers to the temporal operation to be performed on the field ''sqrt( @ssh2 - @ssh * @ssh )'':
+here the temporal average is alreday done by the ``@'' function so we just use instant.
+field\_ref="ssh" means that attributes not explicitely defined, are inherited from ssh field.
+Note that in this case, freq\_op must be equal to the file output\_freq.
+
+\item use of the ``@'' function: example 3, monthly average of SST diurnal cycle
+
+ - define 2 new variables in field\_definition
+
+\begin{xmllines}
+<field id="sstmax" field_ref="sst" long_name="max of sea surface temperature" operation="maximum" />
+<field id="sstmin" field_ref="sst" long_name="min of sea surface temperature" operation="minimum" />
+\end{xmllines}
+
+ - use these 2 new variables when defining your file.
+
+\begin{xmllines}
+<file_group id="1m" output_freq="1m"  output_level="10" enabled=".true." >  <!-- 1m files -->
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+		<field field_ref="sst" name="sstdcy" long_name="amplitude of sst diurnal cycle" operation="average" freq_op="1d" >
+			@sstmax - @sstmin
+		</field>
+	</file>
+</file_group>
+\end{xmllines}
+
+\end{enumerate}
+
+The freq\_op="1d" attribute is used to define the operation frequency of the ``@'' function: here 1 day.
+The temporal operation done by the ``@'' is the one defined in the field definition:
+here maximum for sstmax and minimum for sstmin.
+So, in the above case, @sstmax will do the daily max and @sstmin the daily min.
+Operation="average" refers to the temporal operation to be performed on the field ``@sstmax - @sstmin'':
+here monthly mean (of daily max - daily min of the sst).
+field\_ref="sst" means that attributes not explicitely defined, are inherited from sst field.
+
+%% =================================================================================================
+\subsubsection{Tag list per family}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|l|X|}
+    \hline
+    tag name                                                                                     &
+    description                                                                                  &
+    accepted attribute                                                                           &
+    child of                                                                                     &
+    parent of                       \\
+    \hline
+    \hline
+    simulation                                                                                   &
+    this tag is the root tag which encapsulates all the content of the XML file                  &
+    none                                                                                         &
+    none                                                                                         &
+    context                         \\
+    \hline
+    context                                                                                      &
+    encapsulates parts of the XML file dedicated to different codes or different parts of a code &
+    id (''xios'', ''nemo'' or ''n\_nemo'' for the nth AGRIF zoom), src, time\_origin             &
+    simulation                                                                                   &
+    all root tags: ... \_definition \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: context tags}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|l|}
+    \hline
+    tag name                                                                                &
+    description                                                                             &
+    accepted attribute                                                                      &
+    child of                                                                                &
+    parent of             \\
+    \hline
+    \hline
+    field\_definition                                                                       &
+    encapsulates the definition of all the fields that can potentially be outputted         &
+    axis\_ref, default\_value, domain\_ref, enabled, grid\_ref, level, operation, prec, src &
+    context                                                                                 &
+    field or field\_group \\
+    \hline
+    field\_group                                                                            &
+    encapsulates a group of fields                                                          &
+    axis\_ref, default\_value, domain\_ref, enabled, group\_ref, grid\_ref,
+    id, level, operation, prec, src                                                         &
+    field\_definition, field\_group, file                                                   &
+    field or field\_group \\
+    \hline
+    field                                                                                   &
+    define a specific field                                                                 &
+    axis\_ref, default\_value, domain\_ref, enabled, field\_ref, grid\_ref,
+    id, level, long\_name, name, operation, prec, standard\_name, unit                      &
+    field\_definition, field\_group, file                                                   &
+    none                  \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: field tags ("\texttt{field\_*}")}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|l|}
+    \hline
+    tag name                                                            &
+    description                                                         &
+    accepted attribute                                                  &
+    child of                                                            &
+    parent of           \\
+    \hline
+    \hline
+    file\_definition                                                    &
+    encapsulates the definition of all the files that will be outputted &
+    enabled, min\_digits, name, name\_suffix, output\_level,
+    split\_freq\_format, split\_freq, sync\_freq, type, src             &
+    context                                                             &
+    file or file\_group \\
+    \hline
+    file\_group                                                         &
+    encapsulates a group of files that will be outputted                &
+    enabled, description, id, min\_digits, name, name\_suffix, output\_freq, output\_level,
+    split\_freq\_format, split\_freq, sync\_freq, type, src             &
+    file\_definition, file\_group                                       &
+    file or file\_group \\
+    \hline
+    file                                                                &
+    define the contents of a file to be outputted                       &
+    enabled, description, id, min\_digits, name, name\_suffix, output\_freq, output\_level,
+    split\_freq\_format, split\_freq, sync\_freq, type, src             &
+    file\_definition, file\_group                                       &
+    field               \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: file tags ("\texttt{file\_*}")}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|X|}
+    \hline
+    tag name                                                                               &
+    description                                                                            &
+    accepted attribute                                                                     &
+    child of                                                                               &
+    parent of         \\
+    \hline
+    \hline
+    axis\_definition                                                                       &
+    define all the vertical axis potentially used by the variables                         &
+    src                                                                                    &
+    context                                                                                &
+    axis\_group, axis \\
+    \hline
+    axis\_group                                                                            &
+    encapsulates a group of vertical axis                                                  &
+    id, lon\_name, positive, src, standard\_name, unit, zoom\_begin, zoom\_end, zoom\_size &
+    axis\_definition, axis\_group                                                          &
+    axis\_group, axis \\
+    \hline
+    axis                                                                                   &
+    define a vertical axis                                                                 &
+    id, lon\_name, positive, src, standard\_name, unit, zoom\_begin, zoom\_end, zoom\_size &
+    axis\_definition, axis\_group                                                          &
+    none					\\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: axis tags ("\texttt{axis\_*}")}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|X|}
+    \hline
+    tag name                                                            &
+    description                                                         &
+    accepted attribute                                                  &
+    child of                                                            &
+    parent of               \\
+    \hline
+    \hline
+    domain\_\-definition                                                &
+    define all the horizontal domains potentially used by the variables &
+    src                                                                 &
+    context                                                             &
+    domain\_\-group, domain \\
+    \hline
+    domain\_group                                                       &
+    encapsulates a group of horizontal domains                          &
+    id, lon\_name, src, zoom\_ibegin, zoom\_jbegin, zoom\_ni, zoom\_nj  &
+    domain\_\-definition, domain\_group                                 &
+    domain\_\-group, domain \\
+    \hline
+    domain                                                              &
+    define an horizontal domain                                         &
+    id, lon\_name, src, zoom\_ibegin, zoom\_jbegin, zoom\_ni, zoom\_nj  &
+    domain\_\-definition, domain\_group                                 &
+    none                    \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: domain tags ("\texttt{domain\_*)}"}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|X|}
+    \hline
+    tag name                                                                                     &
+    description                                                                                  &
+    accepted attribute                                                                           &
+    child of                                                                                     &
+    parent of                       \\
+    \hline
+    \hline
+    grid\_definition                                                                               &
+    define all the grid (association of a domain and/or an axis) potentially used by the variables &
+    src                                                                                            &
+    context                                                                                        &
+    grid\_group, grid	\\
+    \hline
+    grid\_group                                                                                    &
+    encapsulates a group of grids                                                                  &
+    id, domain\_ref,axis\_ref                                                                      &
+    grid\_definition, grid\_group                                                                  &
+    grid\_group, grid	\\
+    \hline
+    grid                                                                                           &
+    define a grid                                                                                  &
+    id, domain\_ref,axis\_ref                                                                      &
+    grid\_definition, grid\_group                                                                  &
+    none 					\\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: grid tags ("\texttt{grid\_*}")}
+\end{table}
+
+%% =================================================================================================
+\subsubsection{Attributes list per family}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|l|l|}
+    \hline
+    attribute name                           &
+    description                              &
+    example                                  &
+    accepted by            \\
+    \hline
+    \hline
+    axis\_ref                                &
+    refers to the id of a vertical axis      &
+    axis\_ref="deptht"                       &
+    field, grid families   \\
+    \hline
+    domain\_ref                              &
+    refers to the id of a domain             &
+    domain\_ref="grid\_T"                    &
+    field or grid families \\
+    \hline
+    field\_ref                               &
+    id of the field we want to add in a file &
+    field\_ref="toce"                        &
+    field                  \\
+    \hline
+    grid\_ref                                &
+    refers to the id of a grid               &
+    grid\_ref="grid\_T\_2D"                  &
+    field family           \\
+    \hline
+    group\_ref                               &
+    refer to a group of variables            &
+    group\_ref="mooring"                     &
+    field\_group           \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: reference attributes ("\texttt{*\_ref}")}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|l|l|}
+    \hline
+    attribute name                                     &
+    description                                        &
+    example                                            &
+    accepted by   \\
+    \hline
+    \hline
+    zoom\_ibegin                                       &
+    starting point along x direction of the zoom.
+    Automatically defined for TAO/RAMA/PIRATA moorings &
+    zoom\_ibegin="1"                                   &
+    domain family \\
+    \hline
+    zoom\_jbegin                                       &
+    starting point along y direction of the zoom.
+    Automatically defined for TAO/RAMA/PIRATA moorings &
+    zoom\_jbegin="1"                                   &
+    domain family \\
+    \hline
+    zoom\_ni                                           &
+    zoom extent along x direction                      &
+    zoom\_ni="1"                                       &
+    domain family \\
+    \hline
+    zoom\_nj                                           &
+    zoom extent along y direction                      &
+    zoom\_nj="1"                                       &
+    domain family \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: domain attributes ("\texttt{zoom\_*}")}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|l|l|}
+    \hline
+    attribute name                                                                                       &
+    description                                                                                          &
+    example                                                                                              &
+    accepted by                            \\
+    \hline
+    \hline
+    min\_digits                                                                                          &
+    specify the minimum of digits used in the core number in the name of the NetCDF file                 &
+    min\_digits="4"                                                                                      &
+    file family                            \\
+    \hline
+    name\_suffix                                                                                         &
+    suffix to be inserted after the name and before the cpu number and the ''.nc'' termination of a file &
+    name\_suffix="\_myzoom"                                                                              &
+    file family                            \\
+    \hline
+    output\_level                                                                                        &
+    output priority of variables in a file: 0 (high) to 10 (low).
+    All variables listed in the file with a level smaller or equal to output\_level will be output.
+    Other variables won't be output even if they are listed in the file.                                 &
+    output\_level="10"                                                                                   &
+    file family                            \\
+    \hline
+    split\_freq                                                                                          &
+    frequency at which to temporally split output files.
+    Units can be ts (timestep), y, mo, d, h, mi, s.
+    Useful for long runs to prevent over-sized output files.                                             &
+    split\_freq="1mo"                                                                                    &
+    file family                            \\
+    \hline
+    split\_freq\-\_format                                                                                &
+    date format used in the name of temporally split output files.
+    Can be specified using the following syntaxes: \%y, \%mo, \%d, \%h \%mi and \%s                      &
+    split\_freq\_format= "\%y\%mo\%d"                                                                    &
+    file family                            \\
+    \hline
+    sync\_freq                                                                                           &
+    NetCDF file synchronization frequency (update of the time\_counter).
+    Units can be ts (timestep), y, mo, d, h, mi, s.                                                      &
+    sync\_freq="10d"                                                                                     &
+    file family                            \\
+    \hline
+    type (1)                                                                                             &
+    specify if the output files are to be split spatially (multiple\_file) or not (one\_file)            &
+    type="multiple\_file"                                                                                &
+    file familly                           \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: file attributes}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|l|l|}
+    \hline
+    attribute name                                                                                       &
+    description                                                                                          &
+    example                                                                                              &
+    accepted by                            \\
+    \hline
+    \hline
+    default\_value                                                                                       &
+    missing\_value definition                                                                            &
+    default\_value="1.e20"                                                                               &
+    field family                           \\
+    \hline
+    level                                                                                                &
+    output priority of a field: 0 (high) to 10 (low)                                                     &
+    level="1"                                                                                            &
+    field family                           \\
+    \hline
+    operation                                                                                            &
+    type of temporal operation: average, accumulate, instantaneous, min, max and once                    &
+    operation="average"                                                                                  &
+    field family                           \\
+    \hline
+    output\_freq                                                                                         &
+    operation frequency. units can be ts (timestep), y, mo, d, h, mi, s.                                 &
+    output\_freq="1d12h"                                                                                 &
+    field family                           \\
+    \hline
+    prec                                                                                                 &
+    output precision: real 4 or real 8                                                                   &
+    prec="4"                                                                                             &
+    field family                           \\
+    \hline
+    long\_name                                                                                           &
+    define the long\_name attribute in the NetCDF file                                                   &
+    long\_name="Vertical T levels"                                                                       &
+    field                                  \\
+    \hline
+    standard\_name                                                                                       &
+    define the standard\_name attribute in the NetCDF file                                               &
+    standard\_name= "Eastward\_Sea\_Ice\_Transport"                                                      &
+    field                                  \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: field attributes}
+\end{table}
+
+\begin{table}
+  \begin{tabularx}{\textwidth}{|l|X|X|X|}
+    \hline
+    attribute name                                                                                       &
+    description                                                                                          &
+    example                                                                                              &
+    accepted by                            \\
+    \hline
+    \hline
+    enabled                                                                                              &
+    switch on/off the output of a field or a file                                                        &
+    enabled=".true."                                                                                     &
+    field, file families                   \\
+    \hline
+    description                                                                                          &
+    just for information, not used                                                                       &
+    description="ocean T grid variables"                                                                 &
+    all tags                               \\
+    \hline
+    id                                                                                                   &
+    allow to identify a tag                                                                              &
+    id="nemo"                                                                                            &
+    accepted by all tags except simulation \\
+    \hline
+    name                                                                                                 &
+    name of a variable or a file. If the name of a file is undefined, its id is used as a name           &
+    name="tos"                                                                                           &
+    field or file families                 \\
+    \hline
+    positive                                                                                             &
+    convention used for the orientation of vertival axis (positive downward in \NEMO).                   &
+    positive="down"                                                                                      &
+    axis family                            \\
+    \hline
+    src                                                                                                  &
+    allow to include a file                                                                              &
+    src="./field\_def.xml"                                                                               &
+    accepted by all tags except simulation \\
+    \hline
+    time\_origin                                                                                         &
+    specify the origin of the time counter                                                               &
+    time\_origin="1900-01-01 00:00:00"                                                                   &
+    context                                \\
+    \hline
+    type (2)                                                                                             &
+    define the type of a variable tag                                                                    &
+    type="boolean"                                                                                       &
+    variable                               \\
+    \hline
+    unit                                                                                                 &
+    unit of a variable or the vertical axis                                                              &
+    unit="m"                                                                                             &
+    field and axis families                \\
+    \hline
+  \end{tabularx}
+  \caption{XIOS: miscellaneous attributes}
+\end{table}
+
+%% =================================================================================================
+\subsection{CF metadata standard compliance}
+
+Output from the XIOS IO server is compliant with
+\href{http://cfconventions.org/Data/cf-conventions/cf-conventions-1.5/build/cf-conventions.html}{version 1.5} of
+the CF metadata standard.
+Therefore while a user may wish to add their own metadata to the output files (as demonstrated in example 4 of
+section \autoref{subsec:DIA_IOM_xmlref}) the metadata should, for the most part, comply with the CF-1.5 standard.
+
+Some metadata that may significantly increase the file size (horizontal cell areas and vertices) are controlled by
+the namelist parameter \np{ln_cfmeta}{ln\_cfmeta} in the \nam{run}{run} namelist.
+This must be set to true if these metadata are to be included in the output files.
+
+%% =================================================================================================
+\section[NetCDF4 support (\texttt{\textbf{key\_netcdf4}})]{NetCDF4 support (\protect\key{netcdf4})}
+\label{sec:DIA_nc4}
+
+Since version 3.3, support for NetCDF4 chunking and (loss-less) compression has been included.
+These options build on the standard NetCDF output and allow the user control over the size of the chunks via
+namelist settings.
+Chunking and compression can lead to significant reductions in file sizes for a small runtime overhead.
+For a fuller discussion on chunking and other performance issues the reader is referred to
+the NetCDF4 documentation found \href{https://www.unidata.ucar.edu/software/netcdf/docs/netcdf_perf_chunking.html}{here}.
+
+The new features are only available when the code has been linked with a NetCDF4 library
+(version 4.1 onwards, recommended) which has been built with HDF5 support (version 1.8.4 onwards, recommended).
+Datasets created with chunking and compression are not backwards compatible with NetCDF3 "classic" format but
+most analysis codes can be relinked simply with the new libraries and will then read both NetCDF3 and NetCDF4 files.
+\NEMO\ executables linked with NetCDF4 libraries can be made to produce NetCDF3 files by
+setting the \np{ln_nc4zip}{ln\_nc4zip} logical to false in the \nam{nc4}{nc4} namelist:
+
+\begin{listing}
+  \nlst{namnc4}
+  \caption{\forcode{&namnc4}}
+  \label{lst:namnc4}
+\end{listing}
+
+If \key{netcdf4} has not been defined, these namelist parameters are not read.
+In this case, \np{ln_nc4zip}{ln\_nc4zip} is set false and dummy routines for a few NetCDF4-specific functions are defined.
+These functions will not be used but need to be included so that compilation is possible with NetCDF3 libraries.
+
+When using NetCDF4 libraries, \key{netcdf4} should be defined even if the intention is to
+create only NetCDF3-compatible files.
+This is necessary to avoid duplication between the dummy routines and the actual routines present in the library.
+Most compilers will fail at compile time when faced with such duplication.
+Thus when linking with NetCDF4 libraries the user must define \key{netcdf4} and
+control the type of NetCDF file produced via the namelist parameter.
+
+Chunking and compression is applied only to 4D fields and
+there is no advantage in chunking across more than one time dimension since
+previously written chunks would have to be read back and decompressed before being added to.
+Therefore, user control over chunk sizes is provided only for the three space dimensions.
+The user sets an approximate number of chunks along each spatial axis.
+The actual size of the chunks will depend on global domain size for mono-processors or, more likely,
+the local processor domain size for distributed processing.
+The derived values are subject to practical minimum values (to avoid wastefully small chunk sizes) and
+cannot be greater than the domain size in any dimension.
+The algorithm used is:
+
+\begin{forlines}
+ichunksz(1) = MIN(idomain_size, MAX((idomain_size-1) / nn_nchunks_i + 1 ,16 ))
+ichunksz(2) = MIN(jdomain_size, MAX((jdomain_size-1) / nn_nchunks_j + 1 ,16 ))
+ichunksz(3) = MIN(kdomain_size, MAX((kdomain_size-1) / nn_nchunks_k + 1 , 1 ))
+ichunksz(4) = 1
+\end{forlines}
+
+\noindent As an example, setting:
+
+\begin{forlines}
+nn_nchunks_i=4, nn_nchunks_j=4 and nn_nchunks_k=31
+\end{forlines}
+
+\noindent for a standard ORCA2\_LIM configuration gives chunksizes of {\small\texttt 46x38x1} respectively in
+the mono-processor case (\ie\ global domain of {\small\texttt 182x149x31}).
+An illustration of the potential space savings that NetCDF4 chunking and compression provides is given in
+table \autoref{tab:DIA_NC4} which compares the results of two short runs of the ORCA2\_LIM reference configuration with
+a 4x2 mpi partitioning.
+Note the variation in the compression ratio achieved which reflects chiefly the dry to wet volume ratio of
+each processing region.
+
+\begin{table}
+  \centering
+  \begin{tabular}{lrrr}
+    Filename                    & NetCDF3	& NetCDF4  & Reduction \\
+                                & filesize	& filesize & \%        \\
+                                & (KB)		& (KB)	  &           \\
+    ORCA2\_restart\_0000.nc     & 16420 	& 8860 	  & 47\%      \\
+    ORCA2\_restart\_0001.nc     & 16064 	& 11456    & 29\%      \\
+    ORCA2\_restart\_0002.nc     & 16064		& 9744	  & 40\%      \\
+    ORCA2\_restart\_0003.nc     & 16420		& 9404	  & 43\%      \\
+    ORCA2\_restart\_0004.nc     & 16200 	& 5844	  & 64\%      \\
+    ORCA2\_restart\_0005.nc     & 15848 	& 8172	  & 49\%      \\
+    ORCA2\_restart\_0006.nc     & 15848 	& 8012 	  & 50\%      \\
+    ORCA2\_restart\_0007.nc     & 16200 	& 5148 	  & 69\%      \\
+    ORCA2\_2d\_grid\_T\_0000.nc & 2200 		& 1504	  & 32\%      \\
+    ORCA2\_2d\_grid\_T\_0001.nc & 2200 		& 1748	  & 21\%      \\
+    ORCA2\_2d\_grid\_T\_0002.nc & 2200 		& 1592	  & 28\%      \\
+    ORCA2\_2d\_grid\_T\_0003.nc & 2200 		& 1540	  & 30\%      \\
+    ORCA2\_2d\_grid\_T\_0004.nc & 2200 		& 1204	  & 46\%      \\
+    ORCA2\_2d\_grid\_T\_0005.nc & 2200 		& 1444	  & 35\%      \\
+    ORCA2\_2d\_grid\_T\_0006.nc & 2200 		& 1428	  & 36\%      \\
+    ORCA2\_2d\_grid\_T\_0007.nc & 2200		& 1148	  & 48\%      \\
+    ...                         & ...		& ...      & ...       \\
+    ORCA2\_2d\_grid\_W\_0000.nc & 4416		& 2240	  & 50\%      \\
+    ORCA2\_2d\_grid\_W\_0001.nc & 4416		& 2924	  & 34\%      \\
+    ORCA2\_2d\_grid\_W\_0002.nc & 4416		& 2512	  & 44\%      \\
+    ORCA2\_2d\_grid\_W\_0003.nc & 4416		& 2368	  & 47\%      \\
+    ORCA2\_2d\_grid\_W\_0004.nc & 4416		& 1432	  & 68\%      \\
+    ORCA2\_2d\_grid\_W\_0005.nc & 4416		& 1972	  & 56\%      \\
+    ORCA2\_2d\_grid\_W\_0006.nc & 4416		& 2028	  & 55\%      \\
+    ORCA2\_2d\_grid\_W\_0007.nc & 4416		& 1368	  & 70\%      \\
+  \end{tabular}
+  \caption{Filesize comparison between NetCDF3 and NetCDF4 with chunking and compression}
+  \label{tab:DIA_NC4}
+\end{table}
+
+When \key{iomput} is activated with \key{netcdf4} chunking and compression parameters for fields produced via
+\rou{iom\_put} calls are set via an equivalent and identically named namelist to \nam{nc4}{nc4} in
+\textit{xmlio\_server.def}.
+Typically this namelist serves the mean files whilst the \nam{nc4}{nc4} in the main namelist file continues to
+serve the restart files.
+This duplication is unfortunate but appropriate since, if using io\_servers, the domain sizes of
+the individual files produced by the io\_server processes may be different to those produced by
+the invidual processing regions and different chunking choices may be desired.
+
+%% =================================================================================================
+\section[Tracer/Dynamics trends (\forcode{&namtrd})]{Tracer/Dynamics trends (\protect\nam{trd}{trd})}
+\label{sec:DIA_trd}
+
+\begin{listing}
+  \nlst{namtrd}
+  \caption{\forcode{&namtrd}}
+  \label{lst:namtrd}
+\end{listing}
+
+Each trend of the dynamics and/or temperature and salinity time evolution equations can be send to
+\mdl{trddyn} and/or \mdl{trdtra} modules (see TRD directory) just after their computation
+(\ie\ at the end of each \textit{dyn....F90} and/or \textit{tra....F90} routines).
+This capability is controlled by options offered in \nam{trd}{trd} namelist.
+Note that the output are done with XIOS, and therefore the \key{iomput} is required.
+
+What is done depends on the \nam{trd}{trd} logical set to \forcode{.true.}:
+
+\begin{description}
+\item [{\np{ln_glo_trd}{ln\_glo\_trd}}]: at each \np{nn_trd}{nn\_trd} time-step a check of the basin averaged properties of
+  the momentum and tracer equations is performed.
+  This also includes a check of $T^2$, $S^2$, $\tfrac{1}{2} (u^2+v2)$,
+  and potential energy time evolution equations properties;
+\item [{\np{ln_dyn_trd}{ln\_dyn\_trd}}]: each 3D trend of the evolution of the two momentum components is output;
+\item [{\np{ln_dyn_mxl}{ln\_dyn\_mxl}}]: each 3D trend of the evolution of the two momentum components averaged over the mixed layer is output;
+\item [{\np{ln_vor_trd}{ln\_vor\_trd}}]: a vertical summation of the moment tendencies is performed,
+  then the curl is computed to obtain the barotropic vorticity tendencies which are output;
+\item [{\np{ln_KE_trd}{ln\_KE\_trd}}]  : each 3D trend of the Kinetic Energy equation is output;
+\item [{\np{ln_tra_trd}{ln\_tra\_trd}}]: each 3D trend of the evolution of temperature and salinity is output;
+\item [{\np{ln_tra_mxl}{ln\_tra\_mxl}}]: each 2D trend of the evolution of temperature and salinity averaged over the mixed layer is output;
+\end{description}
+
+Note that the mixed layer tendency diagnostic can also be used on biogeochemical models via
+the \key{trdtrc} and \key{trdmxl\_trc} CPP keys.
+
+\textbf{Note that} in the current version (v3.6), many changes has been introduced but not fully tested.
+In particular, options associated with \np{ln_dyn_mxl}{ln\_dyn\_mxl}, \np{ln_vor_trd}{ln\_vor\_trd}, and \np{ln_tra_mxl}{ln\_tra\_mxl} are not working,
+and none of the options have been tested with variable volume (\ie\ \np[=.true.]{ln_linssh}{ln\_linssh}).
+
+%% =================================================================================================
+\section[FLO: On-Line Floats trajectories (\texttt{\textbf{key\_floats}})]{FLO: On-Line Floats trajectories (\protect\key{floats})}
+\label{sec:DIA_FLO}
+
+\begin{listing}
+  \nlst{namflo}
+  \caption{\forcode{&namflo}}
+  \label{lst:namflo}
+\end{listing}
+
+The on-line computation of floats advected either by the three dimensional velocity field or constraint to
+remain at a given depth ($w = 0$ in the computation) have been introduced in the system during the CLIPPER project.
+Options are defined by \nam{flo}{flo} namelist variables.
+The algorithm used is based either on the work of \cite{blanke.raynaud_JPO97} (default option),
+or on a $4^th$ Runge-Hutta algorithm (\np[=.true.]{ln_flork4}{ln\_flork4}).
+Note that the \cite{blanke.raynaud_JPO97} algorithm have the advantage of providing trajectories which
+are consistent with the numeric of the code, so that the trajectories never intercept the bathymetry.
+
+%% =================================================================================================
+\subsubsection{Input data: initial coordinates}
+
+Initial coordinates can be given with Ariane Tools convention
+(IJK coordinates, (\np[=.true.]{ln_ariane}{ln\_ariane}) ) or with longitude and latitude.
+
+In case of Ariane convention, input filename is \textit{init\_float\_ariane}.
+Its format is: \\
+{ \texttt{I J K nisobfl itrash}}
+
+\noindent with:
+
+ - I,J,K  : indexes of initial position
+
+ - nisobfl: 0 for an isobar float, 1 for a float following the w velocity
+
+ - itrash : set to zero; it is a dummy variable to respect Ariane Tools convention
+
+\noindent Example: \\
+\noindent
+{
+  \texttt{
+    100.00000  90.00000  -1.50000 1.00000   0.00000   \\
+    102.00000  90.00000  -1.50000 1.00000   0.00000   \\
+    104.00000  90.00000  -1.50000 1.00000   0.00000   \\
+    106.00000  90.00000  -1.50000 1.00000   0.00000   \\
+    108.00000  90.00000  -1.50000 1.00000   0.00000}
+} \\
+
+In the other case (longitude and latitude), input filename is init\_float.
+Its format is: \\
+{ \texttt{Long Lat depth nisobfl ngrpfl itrash}}
+
+\noindent with:
+
+ - Long, Lat, depth  : Longitude, latitude, depth
+
+ - nisobfl: 0 for an isobar float, 1 for a float following the w velocity
+
+ - ngrpfl : number to identify searcher group
+
+ - itrash :set to 1; it is a dummy variable.
+
+\noindent Example: \\
+\noindent
+{
+  \texttt{
+    20.0 0.0 0.0 0 1 1    \\
+    -21.0 0.0 0.0 0 1 1    \\
+    -22.0 0.0 0.0 0 1 1    \\
+    -23.0 0.0 0.0 0 1 1    \\
+    -24.0 0.0 0.0 0 1 1 }
+} \\
+
+\np{jpnfl}{jpnfl} is the total number of floats during the run.
+When initial positions are read in a restart file (\np[=.true.]{ln_rstflo}{ln\_rstflo} ),
+\np{jpnflnewflo}{jpnflnewflo} can be added in the initialization file.
+
+%% =================================================================================================
+\subsubsection{Output data}
+
+\np{nn_writefl}{nn\_writefl} is the frequency of writing in float output file and \np{nn_stockfl}{nn\_stockfl} is the frequency of
+creation of the float restart file.
+
+Output data can be written in ascii files (\np[=.true.]{ln_flo_ascii}{ln\_flo\_ascii}).
+In that case, output filename is trajec\_float.
+
+Another possiblity of writing format is Netcdf (\np[=.false.]{ln_flo_ascii}{ln\_flo\_ascii}) with
+\key{iomput} and outputs selected in iodef.xml.
+Here it is an example of specification to put in files description section:
+
+\begin{xmllines}
+<group id="1d_grid_T" name="auto" description="ocean T grid variables" >   }
+	<file id="floats"  description="floats variables"> }
+		<field ref="traj_lon"   name="floats_longitude"   freq_op="86400" />}
+		<field ref="traj_lat"   name="floats_latitude"    freq_op="86400" />}
+		<field ref="traj_dep"   name="floats_depth"       freq_op="86400" />}
+		<field ref="traj_temp"  name="floats_temperature" freq_op="86400" />}
+		<field ref="traj_salt"  name="floats_salinity"    freq_op="86400" />}
+		<field ref="traj_dens"  name="floats_density"     freq_op="86400" />}
+		<field ref="traj_group" name="floats_group"       freq_op="86400" />}
+	</file>}
+</group>}
+\end{xmllines}
+
+%% =================================================================================================
+\section[Harmonic analysis of tidal constituents (\texttt{\textbf{key\_diaharm}})]{Harmonic analysis of tidal constituents (\protect\key{diaharm})}
+\label{sec:DIA_diag_harm}
+
+\begin{listing}
+  \nlst{nam_diaharm}
+  \caption{\forcode{&nam_diaharm}}
+  \label{lst:nam_diaharm}
+\end{listing}
+
+A module is available to compute the amplitude and phase of tidal waves.
+This on-line Harmonic analysis is actived with \key{diaharm}.
+
+Some parameters are available in namelist \nam{_diaharm}{\_diaharm}:
+
+ - \np{nit000_han}{nit000\_han} is the first time step used for harmonic analysis
+
+ - \np{nitend_han}{nitend\_han} is the  last time step used for harmonic analysis
+
+ - \np{nstep_han}{nstep\_han}  is the  time step frequency for harmonic analysis
+
+% - \np{nb_ana}{nb\_ana}     is the number of harmonics to analyse
+
+ - \np{tname}{tname}       is an array with names of tidal constituents to analyse
+
+ \np{nit000_han}{nit000\_han} and \np{nitend_han}{nitend\_han} must be between \np{nit000}{nit000} and \np{nitend}{nitend} of the simulation.
+ The restart capability is not implemented.
+
+ The Harmonic analysis solve the following equation:
+
+ \[
+   h_{i} - A_{0} + \sum^{nb\_ana}_{j=1}[A_{j}cos(\nu_{j}t_{j}-\phi_{j})] = e_{i}
+ \]
+
+With $A_{j}$, $\nu_{j}$, $\phi_{j}$, the amplitude, frequency and phase for each wave and $e_{i}$ the error.
+$h_{i}$ is the sea level for the time $t_{i}$ and $A_{0}$ is the mean sea level. \\
+We can rewrite this equation:
+
+\[
+  h_{i} - A_{0} + \sum^{nb\_ana}_{j=1}[C_{j}cos(\nu_{j}t_{j})+S_{j}sin(\nu_{j}t_{j})] = e_{i}
+\]
+
+with $A_{j}=\sqrt{C^{2}_{j}+S^{2}_{j}}$ and $\phi_{j}=arctan(S_{j}/C_{j})$.
+
+We obtain in output $C_{j}$ and $S_{j}$ for each tidal wave.
+
+%% =================================================================================================
+\section[Transports across sections (\texttt{\textbf{key\_diadct}})]{Transports across sections (\protect\key{diadct})}
+\label{sec:DIA_diag_dct}
+
+\begin{listing}
+  \nlst{nam_diadct}
+  \caption{\forcode{&nam_diadct}}
+  \label{lst:nam_diadct}
+\end{listing}
+
+A module is available to compute the transport of volume, heat and salt through sections.
+This diagnostic is actived with \key{diadct}.
+
+Each section is defined by the coordinates of its 2 extremities.
+The pathways between them are contructed using tools which can be found in \texttt{tools/SECTIONS\_DIADCT}
+and are written in a binary file \texttt{section\_ijglobal.diadct} which is later read in by
+\NEMO\ to compute on-line transports.
+
+The on-line transports module creates three output ascii files:
+
+- \texttt{volume\_transport} for volume transports (unit: $10^{6} m^{3} s^{-1}$)
+
+- \texttt{heat\_transport}   for   heat transports (unit: $10^{15} W$)
+
+- \texttt{salt\_transport}   for   salt transports (unit: $10^{9}Kg s^{-1}$) \\
+
+Namelist variables in \nam{_diadct}{\_diadct} control how frequently the flows are summed and the time scales over which
+they are averaged, as well as the level of output for debugging:
+\np{nn_dct}{nn\_dct}   : frequency of instantaneous transports computing
+\np{nn_dctwri}{nn\_dctwri}: frequency of writing ( mean of instantaneous transports )
+\np{nn_debug}{nn\_debug} : debugging of the section
+
+%% =================================================================================================
+\subsubsection{Creating a binary file containing the pathway of each section}
+
+In \texttt{tools/SECTIONS\_DIADCT/run},
+the file \textit{ {list\_sections.ascii\_global}} contains a list of all the sections that are to be computed
+(this list of sections is based on MERSEA project metrics).
+
+Another file is available for the GYRE configuration (\texttt{ {list\_sections.ascii\_GYRE}}).
+
+Each section is defined by: \\
+\noindent { \texttt{long1 lat1 long2 lat2 nclass (ok/no)strpond (no)ice section\_name}} \\
+with:
+
+ - \texttt{long1 lat1}, coordinates of the  first extremity of the section;
+
+ - \texttt{long2 lat2}, coordinates of the second extremity of the section;
+
+ - \texttt{nclass}    the number of bounds of your classes (\eg\ bounds for 2 classes);
+
+ - \texttt{okstrpond} to compute    heat and       salt transports, \texttt{nostrpond} if no;
+
+ - \texttt{ice}       to compute surface and volume ice transports, \texttt{noice}     if no. \\
+
+ \noindent The results of the computing of transports, and the directions of positive and
+ negative flow do not depend on the order of the 2 extremities in this file. \\
+
+\noindent If nclass $\neq$ 0, the next lines contain the class type and the nclass bounds: \\
+{
+  \texttt{
+    long1 lat1 long2 lat2 nclass (ok/no)strpond (no)ice section\_name \\
+    classtype                                                         \\
+    zbound1                                                           \\
+    zbound2                                                           \\
+    .                                                                 \\
+    .                                                                 \\
+    nclass-1                                                          \\
+    nclass}
+}
+
+\noindent where \texttt{classtype} can be:
+
+ - \texttt{zsal}  for          salinity classes
+
+ - \texttt{ztem}  for       temperature classes
+
+ - \texttt{zlay}  for             depth classes
+
+ - \texttt{zsigi} for    insitu density classes
+
+ - \texttt{zsigp} for potential density classes \\
+
+ The script \texttt{job.ksh} computes the pathway for each section and creates a binary file
+ \texttt{section\_ijglobal.diadct} which is read by \NEMO. \\
+
+ It is possible to use this tools for new configuations: \texttt{job.ksh} has to be updated with
+ the coordinates file name and path. \\
+
+ Examples of two sections, the ACC\_Drake\_Passage with no classes,
+ and the ATL\_Cuba\_Florida with 4 temperature clases (5 class bounds), are shown: \\
+ \noindent
+ {
+   \texttt{
+     -68.    -54.5   -60.    -64.7  00 okstrpond noice ACC\_Drake\_Passage \\
+     -80.5    22.5   -80.5    25.5  05 nostrpond noice ATL\_Cuba\_Florida  \\
+     ztem                                                                  \\
+     -2.0                                                                  \\
+     4.5                                                                  \\
+     7.0                                                                  \\
+     12.0                                                                  \\
+     40.0}
+ }
+
+%% =================================================================================================
+\subsubsection{To read the output files}
+
+The output format is: \\
+{
+  \texttt{
+    date, time-step number, section number,                \\
+    section name, section slope coefficient, class number, \\
+    class name, class bound 1 , classe bound2,             \\
+    transport\_direction1, transport\_direction2,          \\
+    transport\_total}
+}                                     \\
+
+For sections with classes, the first \texttt{nclass-1} lines correspond to the transport for each class and
+the last line corresponds to the total transport summed over all classes.
+For sections with no classes, class number \texttt{1} corresponds to \texttt{total class} and
+this class is called \texttt{N}, meaning \texttt{none}.
+
+- \texttt{transport\_direction1} is the positive part of the transport ($\geq$ 0).
+
+- \texttt{transport\_direction2} is the negative part of the transport ($\leq$ 0). \\
+
+\noindent The \texttt{section slope coefficient} gives information about the significance of transports signs and
+direction: \\
+
+\begin{table}
+  \begin{tabular}{|l|l|l|l|l|}
+    \hline
+    section slope coefficient      & section type & direction 1 & direction 2 & total transport    \\
+    \hline
+    0.                             & horizontal	 & northward	& southward   & postive: northward    \\
+    \hline
+    1000.                          & vertical     & eastward    & westward    & postive: eastward		\\
+    \hline
+    \texttt{$\neq$ 0, $\neq$ 1000.} & diagonal     & eastward    & westward	  & postive: eastward		\\
+    \hline
+  \end{tabular}
+\end{table}
+
+%% =================================================================================================
+\section{Diagnosing the steric effect in sea surface height}
+\label{sec:DIA_steric}
+
+Changes in steric sea level are caused when changes in the density of the water column imply an expansion or
+contraction of the column.
+It is essentially produced through surface heating/cooling and to a lesser extent through non-linear effects of
+the equation of state (cabbeling, thermobaricity...).
+Non-Boussinesq models contain all ocean effects within the ocean acting on the sea level.
+In particular, they include the steric effect.
+In contrast, Boussinesq models, such as \NEMO, conserve volume, rather than mass,
+and so do not properly represent expansion or contraction.
+The steric effect is therefore not explicitely represented.
+This approximation does not represent a serious error with respect to the flow field calculated by the model
+\citep{greatbatch_JGR94}, but extra attention is required when investigating sea level,
+as steric changes are an important contribution to local changes in sea level on seasonal and climatic time scales.
+This is especially true for investigation into sea level rise due to global warming.
+
+Fortunately, the steric contribution to the sea level consists of a spatially uniform component that
+can be diagnosed by considering the mass budget of the world ocean \citep{greatbatch_JGR94}.
+In order to better understand how global mean sea level evolves and thus how the steric sea level can be diagnosed,
+we compare, in the following, the non-Boussinesq and Boussinesq cases.
+
+Let denote
+$\mathcal{M}$ the total mass    of liquid seawater ($\mathcal{M} = \int_D \rho dv$),
+$\mathcal{V}$ the total volume  of        seawater      ($\mathcal{V} = \int_D dv$),
+$\mathcal{A}$ the total surface of       the ocean      ($\mathcal{A} = \int_S ds$),
+$\bar{\rho}$ the global mean  seawater (\textit{in situ}) density
+($\bar{\rho} = 1/\mathcal{V} \int_D \rho \,dv$), and
+$\bar{\eta}$ the global mean sea level
+($\bar{\eta} = 1/\mathcal{A} \int_S \eta \,ds$).
+
+A non-Boussinesq fluid conserves mass. It satisfies the following relations:
+
+\begin{equation}
+  \begin{split}
+    \mathcal{M} &=  \mathcal{V}  \;\bar{\rho} \\
+    \mathcal{V} &=  \mathcal{A}  \;\bar{\eta}
+  \end{split}
+  \label{eq:DIA_MV_nBq}
+\end{equation}
+
+Temporal changes in total mass is obtained from the density conservation equation:
+
+\begin{equation}
+  \frac{1}{e_3} \partial_t ( e_3\,\rho) + \nabla( \rho \, \textbf{U} )
+  = \left. \frac{\textit{emp}}{e_3}\right|_\textit{surface}
+  \label{eq:DIA_Co_nBq}
+\end{equation}
+
+where $\rho$ is the \textit{in situ} density, and \textit{emp} the surface mass exchanges with the other media of
+the Earth system (atmosphere, sea-ice, land).
+Its global averaged leads to the total mass change
+
+\begin{equation}
+  \partial_t \mathcal{M} = \mathcal{A} \;\overline{\textit{emp}}
+  \label{eq:DIA_Mass_nBq}
+\end{equation}
+
+where $\overline{\textit{emp}} = \int_S \textit{emp}\,ds$ is the net mass flux through the ocean surface.
+Bringing \autoref{eq:DIA_Mass_nBq} and the time derivative of \autoref{eq:DIA_MV_nBq} together leads to
+the evolution equation of the mean sea level
+
+\begin{equation}
+  \partial_t \bar{\eta} = \frac{\overline{\textit{emp}}}{ \bar{\rho}}
+  - \frac{\mathcal{V}}{\mathcal{A}} \;\frac{\partial_t \bar{\rho} }{\bar{\rho}}
+  \label{eq:DIA_ssh_nBq}
+\end{equation}
+
+The first term in equation \autoref{eq:DIA_ssh_nBq} alters sea level by adding or subtracting mass from the ocean.
+The second term arises from temporal changes in the global mean density; \ie\ from steric effects.
+
+In a Boussinesq fluid, $\rho$ is replaced by $\rho_o$ in all the equation except when $\rho$ appears multiplied by
+the gravity (\ie\ in the hydrostatic balance of the primitive Equations).
+In particular, the mass conservation equation, \autoref{eq:DIA_Co_nBq}, degenerates into the incompressibility equation:
+
+\[
+  \frac{1}{e_3} \partial_t ( e_3 ) + \nabla( \textbf{U} ) = \left. \frac{\textit{emp}}{\rho_o \,e_3}\right|_ \textit{surface}
+  % \label{eq:DIA_Co_Bq}
+\]
+
+and the global average of this equation now gives the temporal change of the total volume,
+
+\[
+  \partial_t \mathcal{V} = \mathcal{A} \;\frac{\overline{\textit{emp}}}{\rho_o}
+  % \label{eq:DIA_V_Bq}
+\]
+
+Only the volume is conserved, not mass, or, more precisely, the mass which is conserved is the Boussinesq mass,
+$\mathcal{M}_o = \rho_o \mathcal{V}$.
+The total volume (or equivalently the global mean sea level) is altered only by net volume fluxes across
+the ocean surface, not by changes in mean mass of the ocean: the steric effect is missing in a Boussinesq fluid.
+
+Nevertheless, following \citep{greatbatch_JGR94}, the steric effect on the volume can be diagnosed by
+considering the mass budget of the ocean.
+The apparent changes in $\mathcal{M}$, mass of the ocean, which are not induced by surface mass flux
+must be compensated by a spatially uniform change in the mean sea level due to expansion/contraction of the ocean
+\citep{greatbatch_JGR94}.
+In others words, the Boussinesq mass, $\mathcal{M}_o$, can be related to $\mathcal{M}$,
+the total mass of the ocean seen by the Boussinesq model, via the steric contribution to the sea level,
+$\eta_s$, a spatially uniform variable, as follows:
+
+\begin{equation}
+  \mathcal{M}_o = \mathcal{M} + \rho_o \,\eta_s \,\mathcal{A}
+  \label{eq:DIA_M_Bq}
+\end{equation}
+
+Any change in $\mathcal{M}$ which cannot be explained by the net mass flux through the ocean surface
+is converted into a mean change in sea level.
+Introducing the total density anomaly, $\mathcal{D}= \int_D d_a \,dv$,
+where $d_a = (\rho -\rho_o ) / \rho_o$ is the density anomaly used in \NEMO\ (cf. \autoref{subsec:TRA_eos})
+in \autoref{eq:DIA_M_Bq} leads to a very simple form for the steric height:
+
+\begin{equation}
+  \eta_s = - \frac{1}{\mathcal{A}} \mathcal{D}
+  \label{eq:DIA_steric_Bq}
+\end{equation}
+
+The above formulation of the steric height of a Boussinesq ocean requires four remarks.
+First, one can be tempted to define $\rho_o$ as the initial value of $\mathcal{M}/\mathcal{V}$,
+\ie\ set $\mathcal{D}_{t=0}=0$, so that the initial steric height is zero.
+We do not recommend that.
+Indeed, in this case $\rho_o$ depends on the initial state of the ocean.
+Since $\rho_o$ has a direct effect on the dynamics of the ocean
+(it appears in the pressure gradient term of the momentum equation)
+it is definitively not a good idea when inter-comparing experiments.
+We better recommend to fixe once for all $\rho_o$ to $1035\;Kg\,m^{-3}$.
+This value is a sensible choice for the reference density used in a Boussinesq ocean climate model since,
+with the exception of only a small percentage of the ocean, density in the World Ocean varies by no more than
+2$\%$ from this value (\cite{gill_bk82}, page 47).
+
+Second, we have assumed here that the total ocean surface, $\mathcal{A}$,
+does not change when the sea level is changing as it is the case in all global ocean GCMs
+(wetting and drying of grid point is not allowed).
+
+Third, the discretisation of \autoref{eq:DIA_steric_Bq} depends on the type of free surface which is considered.
+In the non linear free surface case, \ie\ \np[=.true.]{ln_linssh}{ln\_linssh}, it is given by
+
+\[
+  \eta_s = - \frac{ \sum_{i,\,j,\,k} d_a\; e_{1t} e_{2t} e_{3t} }{ \sum_{i,\,j,\,k}       e_{1t} e_{2t} e_{3t} }
+  % \label{eq:DIA_discrete_steric_Bq_nfs}
+\]
+
+whereas in the linear free surface,
+the volume above the \textit{z=0} surface must be explicitly taken into account to
+better approximate the total ocean mass and thus the steric sea level:
+
+\[
+  \eta_s = - \frac{ \sum_{i,\,j,\,k} d_a\; e_{1t}e_{2t}e_{3t} + \sum_{i,\,j} d_a\; e_{1t}e_{2t} \eta }
+                  { \sum_{i,\,j,\,k}       e_{1t}e_{2t}e_{3t} + \sum_{i,\,j}       e_{1t}e_{2t} \eta }
+  % \label{eq:DIA_discrete_steric_Bq_fs}
+\]
+
+The fourth and last remark concerns the effective sea level and the presence of sea-ice.
+In the real ocean, sea ice (and snow above it)  depresses the liquid seawater through its mass loading.
+This depression is a result of the mass of sea ice/snow system acting on the liquid ocean.
+There is, however, no dynamical effect associated with these depressions in the liquid ocean sea level,
+so that there are no associated ocean currents.
+Hence, the dynamically relevant sea level is the effective sea level,
+\ie\ the sea level as if sea ice (and snow) were converted to liquid seawater \citep{campin.marshall.ea_OM08}.
+However, in the current version of \NEMO\ the sea-ice is levitating above the ocean without mass exchanges between
+ice and ocean.
+Therefore the model effective sea level is always given by $\eta + \eta_s$, whether or not there is sea ice present.
+
+In AR5 outputs, the thermosteric sea level is demanded.
+It is steric sea level due to changes in ocean density arising just from changes in temperature.
+It is given by:
+
+\[
+  \eta_s = - \frac{1}{\mathcal{A}} \int_D d_a(T,S_o,p_o) \,dv
+  % \label{eq:DIA_thermosteric_Bq}
+\]
+
+where $S_o$ and $p_o$ are the initial salinity and pressure, respectively.
+
+Both steric and thermosteric sea level are computed in \mdl{diaar5}.
+
+%% =================================================================================================
+\section{Other diagnostics}
+\label{sec:DIA_diag_others}
+
+Aside from the standard model variables, other diagnostics can be computed on-line.
+The available ready-to-add diagnostics modules can be found in directory DIA.
+
+%% =================================================================================================
+\subsection[Depth of various quantities (\textit{diahth.F90})]{Depth of various quantities (\protect\mdl{diahth})}
+
+Among the available diagnostics the following ones are obtained when defining the \key{diahth} CPP key:
+
+- the mixed layer depth (based on a density criterion \citep{de-boyer-montegut.madec.ea_JGR04}) (\mdl{diahth})
+
+- the turbocline depth (based on a turbulent mixing coefficient criterion) (\mdl{diahth})
+
+- the depth of the 20\deg{C} isotherm (\mdl{diahth})
+
+- the depth of the thermocline (maximum of the vertical temperature gradient) (\mdl{diahth})
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DIA_mask_subasins}
+  \caption[Decomposition of the World Ocean to compute transports as well as
+  the meridional stream-function]{
+    Decomposition of the World Ocean (here ORCA2) into sub-basin used in to
+    compute the heat and salt transports as well as the meridional stream-function:
+    Atlantic basin (red), Pacific basin (green),
+    Indian basin (blue), Indo-Pacific basin (blue+green).
+    Note that semi-enclosed seas (Red, Med and Baltic seas) as well as
+    Hudson Bay are removed from the sub-basins.
+    Note also that the Arctic Ocean has been split into Atlantic and
+    Pacific basins along the North fold line.
+  }
+  \label{fig:DIA_mask_subasins}
+\end{figure}
+
+%% =================================================================================================
+\subsection[CMIP specific diagnostics (\textit{diaar5.F90}, \textit{diaptr.F90})]{CMIP specific diagnostics (\protect\mdl{diaar5})}
+
+A series of diagnostics has been added in the \mdl{diaar5} and \mdl{diaptr}.
+In \mdl{diaar5} they correspond to outputs that are required for AR5 simulations (CMIP5)
+(see also \autoref{sec:DIA_steric} for one of them).
+The module \mdl{diaar5} is active when one of the following outputs is required :
+global total volume (voltot), global mean ssh (sshtot), global total mass (masstot), global mean temperature (temptot),
+global mean ssh steric (sshsteric), global mean ssh thermosteric (sshthster), global mean salinity (saltot),
+sea water pressure at sea floor (botpres), dynamic sea surface height (sshdyn).
+
+In \mdl{diaptr} when \np[=.true.]{ln_diaptr}{ln\_diaptr}
+(see the \nam{ptr}{ptr} namelist below) can be computed on-line the poleward heat and salt transports,
+their advective and diffusive component, and the meriodional stream function .
+When \np[=.true.]{ln_subbas}{ln\_subbas}, transports and stream function are computed for the Atlantic, Indian,
+Pacific and Indo-Pacific Oceans (defined north of 30\deg{S}) as well as for the World Ocean.
+The sub-basin decomposition requires an input file (\ifile{subbasins}) which contains three 2D mask arrays,
+the Indo-Pacific mask been deduced from the sum of the Indian and Pacific mask (\autoref{fig:DIA_mask_subasins}).
+
+\begin{listing}
+  \nlst{namptr}
+  \caption{\forcode{&namptr}}
+  \label{lst:namptr}
+\end{listing}
+
+%% =================================================================================================
+\subsection{25 hour mean output for tidal models}
+
+\begin{listing}
+  \nlst{nam_dia25h}
+  \caption{\forcode{&nam_dia25h}}
+  \label{lst:nam_dia25h}
+\end{listing}
+
+A module is available to compute a crudely detided M2 signal by obtaining a 25 hour mean.
+The 25 hour mean is available for daily runs by summing up the 25 hourly instantananeous hourly values from
+midnight at the start of the day to midight at the day end.
+This diagnostic is actived with the logical $ln\_dia25h$.
+
+%% =================================================================================================
+\subsection{Courant numbers}
+
+Courant numbers provide a theoretical indication of the model's numerical stability.
+The advective Courant numbers can be calculated according to
+
+\[
+  C_u = |u|\frac{\rdt}{e_{1u}}, \quad C_v = |v|\frac{\rdt}{e_{2v}}, \quad C_w = |w|\frac{\rdt}{e_{3w}}
+  % \label{eq:DIA_CFL}
+\]
+
+in the zonal, meridional and vertical directions respectively.
+The vertical component is included although it is not strictly valid as the vertical velocity is calculated from
+the continuity equation rather than as a prognostic variable.
+Physically this represents the rate at which information is propogated across a grid cell.
+Values greater than 1 indicate that information is propagated across more than one grid cell in a single time step.
+
+The variables can be activated by setting the \np{nn_diacfl}{nn\_diacfl} namelist parameter to 1 in the \nam{ctl}{ctl} namelist.
+The diagnostics will be written out to an ascii file named cfl\_diagnostics.ascii.
+In this file the maximum value of $C_u$, $C_v$, and $C_w$ are printed at each timestep along with the coordinates of
+where the maximum value occurs.
+At the end of the model run the maximum value of $C_u$, $C_v$, and $C_w$ for the whole model run is printed along
+with the coordinates of each.
+The maximum values from the run are also copied to the ocean.output file.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIU.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIU.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DIU.tex	(revision 14097)
@@ -0,0 +1,164 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Diurnal SST Models (DIU)}
+\label{chap:DIU}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+Code to produce an estimate of the diurnal warming and cooling of the sea surface skin
+temperature (skin SST) is found in the DIU directory.
+The skin temperature can be split into three parts:
+\begin{itemize}
+\item A foundation SST which is free from diurnal warming.
+\item A warm layer, typically ~3\,m thick,
+  where heating from solar radiation can cause a warm stably stratified layer during the daytime
+\item A cool skin, a thin layer, approximately ~1\, mm thick,
+  where long wave cooling is dominant and cools the immediate ocean surface.
+\end{itemize}
+
+Models are provided for both the warm layer, \mdl{diurnal\_bulk}, and the cool skin, \mdl{cool\_skin}.
+Foundation SST is not considered as it can be obtained either from the main \NEMO\ model
+(\ie\ from the temperature of the top few model levels) or from some other source.
+It must be noted that both the cool skin and warm layer models produce estimates of the change in temperature
+($\Delta T_{\mathrm{cs}}$ and $\Delta T_{\mathrm{wl}}$) and
+both must be added to a foundation SST to obtain the true skin temperature.
+
+Both the cool skin and warm layer models are controlled through the namelist \nam{diu}{diu}:
+
+\begin{listing}
+  \nlst{namdiu}
+  \caption{\forcode{&namdiu}}
+  \label{lst:namdiu}
+\end{listing}
+
+This namelist contains only two variables:
+\begin{description}
+\item [{\np{ln_diurnal}{ln\_diurnal}}] A logical switch for turning on/off both the cool skin and warm layer.
+\item [{\np{ln_diurnal_only}{ln\_diurnal\_only}}] A logical switch which if \forcode{.true.} will run the diurnal model without the other dynamical parts of \NEMO.
+  \np{ln_diurnal_only}{ln\_diurnal\_only} must be \forcode{.false.} if \np{ln_diurnal}{ln\_diurnal} is \forcode{.false.}.
+\end{description}
+
+Output for the diurnal model is through the variables `sst\_wl' (warm\_layer) and `sst\_cs' (cool skin).
+These are 2-D variables which will be included in the model output if they are specified in the iodef.xml file.
+
+Initialisation is through the restart file.
+Specifically the code will expect the presence of the 2-D variable ``Dsst'' to initialise the warm layer.
+The cool skin model, which is determined purely by the instantaneous fluxes, has no initialisation variable.
+
+%% =================================================================================================
+\section{Warm layer model}
+\label{sec:DIU_warm_layer_sec}
+
+The warm layer is calculated using the model of \citet{takaya.bidlot.ea_JGR10} (TAKAYA10 model hereafter).
+This is a simple flux based model that is defined by the equations
+\begin{align}
+\frac{\partial{\Delta T_{\mathrm{wl}}}}{\partial{t}}&=&\frac{Q(\nu+1)}{D_T\rho_w c_p
+\nu}-\frac{(\nu+1)ku^*_{w}f(L_a)\Delta T}{D_T\Phi\!\left(\frac{D_T}{L}\right)} \mbox{,}
+\label{eq:DIU_ecmwf1} \\
+L&=&\frac{\rho_w c_p u^{*^3}_{w}}{\kappa g \alpha_w Q }\mbox{,}\label{eq:DIU_ecmwf2}
+\end{align}
+where $\Delta T_{\mathrm{wl}}$ is the temperature difference between the top of the warm layer and the depth $D_T=3$\,m at which there is assumed to be no diurnal signal.
+In equation (\autoref{eq:DIU_ecmwf1}) $\alpha_w=2\times10^{-4}$ is the thermal expansion coefficient of water,
+$\kappa=0.4$ is von K\'{a}rm\'{a}n's constant, $c_p$ is the heat capacity at constant pressure of sea water,
+$\rho_w$ is the water density, and $L$ is the Monin-Obukhov length.
+The tunable variable $\nu$ is a shape parameter that defines the expected subskin temperature profile via
+$T(z) = T(0) - \left( \frac{z}{D_T} \right)^\nu \Delta T_{\mathrm{wl}}$,
+where $T$ is the absolute temperature and $z\le D_T$ is the depth below the top of the warm layer.
+The influence of wind on TAKAYA10 comes through the magnitude of the friction velocity of the water $u^*_{w}$,
+which can be related to the 10\,m wind speed $u_{10}$ through
+the relationship $u^*_{w} = u_{10}\sqrt{\frac{C_d\rho_a}{\rho_w}}$, where $C_d$ is the drag coefficient,
+and $\rho_a$ is the density of air.
+The symbol $Q$ in equation (\autoref{eq:DIU_ecmwf1}) is the instantaneous total thermal energy flux into
+the diurnal layer, \ie
+\[
+  Q = Q_{\mathrm{sol}} + Q_{\mathrm{lw}} + Q_{\mathrm{h}}\mbox{,}
+  % \label{eq:DIU_e_flux_eqn}
+\]
+where $Q_{\mathrm{h}}$ is the sensible and latent heat flux, $Q_{\mathrm{lw}}$ is the long wave flux,
+and $Q_{\mathrm{sol}}$ is the solar flux absorbed within the diurnal warm layer.
+For $Q_{\mathrm{sol}}$ the 9 term representation of \citet{gentemann.minnett.ea_JGR09} is used.
+In equation \autoref{eq:DIU_ecmwf1} the function $f(L_a)=\max(1,L_a^{\frac{2}{3}})$,
+where $L_a=0.3$\footnote{
+  This is a global average value, more accurately $L_a$ could be computed as $L_a=(u^*_{w}/u_s)^{\frac{1}{2}}$,
+  where $u_s$ is the stokes drift, but this is not currently done
+} is the turbulent Langmuir number and is a parametrization of the effect of waves.
+The function $\Phi\!\left(\frac{D_T}{L}\right)$ is the similarity function that
+parametrizes the stability of the water column and is given by:
+\begin{equation}
+\Phi(\zeta) = \left\{ \begin{array}{cc} 1 + \frac{5\zeta +
+4\zeta^2}{1+3\zeta+0.25\zeta^2} &(\zeta \ge 0) \\
+                                    (1 - 16\zeta)^{-\frac{1}{2}} & (\zeta < 0) \mbox{,}
+                                    \end{array} \right. \label{eq:DIU_stab_func_eqn}
+\end{equation}
+where $\zeta=\frac{D_T}{L}$.  It is clear that the first derivative of (\autoref{eq:DIU_stab_func_eqn}),
+and thus of (\autoref{eq:DIU_ecmwf1}), is discontinuous at $\zeta=0$ (\ie\ $Q\rightarrow0$ in
+equation (\autoref{eq:DIU_ecmwf2})).
+
+The two terms on the right hand side of (\autoref{eq:DIU_ecmwf1}) represent different processes.
+The first term is simply the diabatic heating or cooling of the diurnal warm layer due to
+thermal energy fluxes into and out of the layer.
+The second term parametrizes turbulent fluxes of heat out of the diurnal warm layer due to wind induced mixing.
+In practice the second term acts as a relaxation on the temperature.
+
+%% =================================================================================================
+\section{Cool skin model}
+\label{sec:DIU_cool_skin_sec}
+
+The cool skin is modelled using the framework of \citet{saunders_JAS67} who used a formulation of the near surface temperature difference based upon the heat flux and the friction velocity $u^*_{w}$.
+As the cool skin is so thin (~1\,mm) we ignore the solar flux component to the heat flux and the Saunders equation for the cool skin temperature difference $\Delta T_{\mathrm{cs}}$ becomes
+\[
+  % \label{eq:DIU_sunders_eqn}
+  \Delta T_{\mathrm{cs}}=\frac{Q_{\mathrm{ns}}\delta}{k_t} \mbox{,}
+\]
+where $Q_{\mathrm{ns}}$ is the, usually negative, non-solar heat flux into the ocean and
+$k_t$ is the thermal conductivity of sea water.
+$\delta$ is the thickness of the skin layer and is given by
+\begin{equation}
+\label{eq:DIU_sunders_thick_eqn}
+\delta=\frac{\lambda \mu}{u^*_{w}} \mbox{,}
+\end{equation}
+where $\mu$ is the kinematic viscosity of sea water and $\lambda$ is a constant of proportionality which
+\citet{saunders_JAS67} suggested varied between 5 and 10.
+
+The value of $\lambda$ used in equation (\autoref{eq:DIU_sunders_thick_eqn}) is that of \citet{artale.iudicone.ea_JGR02},
+which is shown in \citet{tu.tsuang_GRL05} to outperform a number of other parametrisations at
+both low and high wind speeds.
+Specifically,
+\[
+  % \label{eq:DIU_artale_lambda_eqn}
+  \lambda = \frac{ 8.64\times10^4 u^*_{w} k_t }{ \rho c_p h \mu \gamma }\mbox{,}
+\]
+where $h=10$\,m is a reference depth and
+$\gamma$ is a dimensionless function of wind speed $u$:
+\[
+  % \label{eq:DIU_artale_gamma_eqn}
+  \gamma =
+  \begin{cases}
+    0.2u+0.5\mbox{,} & u \le 7.5\,\mbox{ms}^{-1} \\
+    1.6u-10\mbox{,} & 7.5 < u < 10\,\mbox{ms}^{-1} \\
+    6\mbox{,} & u \ge 10\,\mbox{ms}^{-1} \\
+  \end{cases}
+\]
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DOM.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DOM.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DOM.tex	(revision 14097)
@@ -0,0 +1,699 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Space Domain (DOM)}
+\label{chap:DOM}
+
+% Missing things
+% -    istate: description of the initial state   ==> this has to be put elsewhere..
+%              perhaps in MISC ?  By the way the initialisation of T S and dynamics
+%              should be put outside of DOM routine (better with TRC staff and off-line
+%              tracers)
+% - geo2ocean: how to switch from geographic to mesh coordinate
+% -    domclo: closed sea and lakes....
+%              management of closea sea area: specific to global cfg, both forced and coupled
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{0.8\textwidth}{l||X|X}
+    Release                                                                                 &
+    Author(s)                                                                               &
+    Modifications                                                                           \\
+    \hline
+    {\em 4.0                                                                              } &
+    {\em Simon M\"{u}ller \& Andrew Coward \newline \newline
+      Simona Flavoni and Tim Graham                                                       } &
+    {\em Compatibility changes: many options moved to external domain configuration tools
+      (see \autoref{apdx:DOMCFG}). \newline
+      Updates                                                                             } \\
+    {\em 3.6                                                                              } &
+    {\em Rachid Benshila, Christian \'{E}th\'{e}, Pierre Mathiot and Gurvan Madec         } &
+    {\em Updates                                                                          } \\
+    {\em $\leq$ 3.4                                                                       } &
+    {\em Gurvan Madec and S\'{e}bastien Masson                                            } &
+    {\em First version                                                                    }
+  \end{tabularx}
+}
+
+\clearpage
+
+Having defined the continuous equations in \autoref{chap:MB} and
+chosen a time discretisation \autoref{chap:TD},
+we need to choose a grid for spatial discretisation and related numerical algorithms.
+In the present chapter, we provide a general description of the staggered grid used in \NEMO,
+and other relevant information about the DOM (DOMain) source code modules.
+
+%% =================================================================================================
+\section{Fundamentals of the discretisation}
+\label{sec:DOM_basics}
+
+%% =================================================================================================
+\subsection{Arrangement of variables}
+\label{subsec:DOM_cell}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{DOM_cell}
+  \caption[Arrangement of variables in the unit cell of space domain]{
+    Arrangement of variables in the unit cell of space domain.
+    $t$ indicates scalar points where
+    temperature, salinity, density, pressure and horizontal divergence are defined.
+    $(u,v,w)$ indicates vector points, and $f$ indicates vorticity points where
+    both relative and planetary vorticities are defined.}
+  \label{fig:DOM_cell}
+\end{figure}
+
+The numerical techniques used to solve the Primitive Equations in this model are based on
+the traditional, centred second-order finite difference approximation.
+Special attention has been given to the homogeneity of the solution in the three spatial directions.
+The arrangement of variables is the same in all directions.
+It consists of cells centred on scalar points ($t$, $S$, $p$, $\rho$) with
+vector points $(u, v, w)$ defined in the centre of each face of the cells (\autoref{fig:DOM_cell}).
+This is the generalisation to three dimensions of the well-known ``C'' grid in
+Arakawa's classification \citep{mesinger.arakawa_bk76}.
+The relative and planetary vorticity, $\zeta$ and $f$, are defined in the centre of each
+vertical edge and the barotropic stream function $\psi$ is defined at horizontal points overlying
+the $\zeta$ and $f$-points.
+
+The ocean mesh (\ie\ the position of all the scalar and vector points) is defined by
+the transformation that gives $(\lambda,\varphi,z)$ as a function of $(i,j,k)$.
+The grid-points are located at integer or integer and a half value of $(i,j,k)$ as indicated on
+\autoref{tab:DOM_cell}.
+In all the following,
+subscripts $u$, $v$, $w$, $f$, $uw$, $vw$ or $fw$ indicate the position of the grid-point where
+the scale factors are defined.
+Each scale factor is defined as the local analytical value provided by \autoref{eq:MB_scale_factors}.
+As a result, the mesh on which partial derivatives $\pd[]{\lambda}$, $\pd[]{\varphi}$ and
+$\pd[]{z}$ are evaluated is a uniform mesh with a grid size of unity.
+Discrete partial derivatives are formulated by
+the traditional, centred second order finite difference approximation while
+the scale factors are chosen equal to their local analytical value.
+An important point here is that the partial derivative of the scale factors must be evaluated by
+centred finite difference approximation, not from their analytical expression.
+This preserves the symmetry of the discrete set of equations and
+therefore satisfies many of the continuous properties (see \autoref{apdx:INVARIANTS}).
+A similar, related remark can be made about the domain size:
+when needed, an area, volume, or the total ocean depth must be evaluated as
+the product or sum of the relevant scale factors (see \autoref{eq:DOM_bar} in the next section).
+
+\begin{table}
+  \centering
+  \begin{tabular}{|l|l|l|l|}
+    \hline
+    t   & $i      $ & $j      $ & $k      $ \\
+    \hline
+    u   & $i + 1/2$ & $j      $ & $k      $ \\
+    \hline
+    v   & $i      $ & $j + 1/2$ & $k      $ \\
+    \hline
+    w   & $i      $ & $j      $ & $k + 1/2$ \\
+    \hline
+    f   & $i + 1/2$ & $j + 1/2$ & $k      $ \\
+    \hline
+    uw  & $i + 1/2$ & $j      $ & $k + 1/2$ \\
+    \hline
+    vw  & $i      $ & $j + 1/2$ & $k + 1/2$ \\
+    \hline
+    fw  & $i + 1/2$ & $j + 1/2$ & $k + 1/2$ \\
+    \hline
+  \end{tabular}
+  \caption[Location of grid-points]{
+    Location of grid-points as a function of integer or
+    integer and a half value of the column, line or level.
+    This indexing is only used for the writing of the semi-discrete equations.
+    In the code, the indexing uses integer values only and
+    is positive downwards in the vertical with $k=1$ at the surface.
+    (see \autoref{subsec:DOM_Num_Index})}
+  \label{tab:DOM_cell}
+\end{table}
+
+Note that the definition of the scale factors
+(\ie\ as the analytical first derivative of the transformation that
+results in $(\lambda,\varphi,z)$ as a function of $(i,j,k)$)
+is specific to the \NEMO\ model \citep{marti.madec.ea_JGR92}.
+As an example, a scale factor in the $i$ direction is defined locally at a $t$-point,
+whereas many other models on a C grid choose to define such a scale factor as
+the distance between the $u$-points on each side of the $t$-point.
+Relying on an analytical transformation has two advantages:
+firstly, there is no ambiguity in the scale factors appearing in the discrete equations,
+since they are first introduced in the continuous equations;
+secondly, analytical transformations encourage good practice by
+the definition of smoothly varying grids
+(rather than allowing the user to set arbitrary jumps in thickness between adjacent layers)
+\citep{treguier.dukowicz.ea_JGR96}.
+An example of the effect of such a choice is shown in \autoref{fig:DOM_zgr_e3}.
+\begin{figure}
+  \centering
+  \includegraphics[width=0.5\textwidth]{DOM_zgr_e3}
+  \caption[Comparison of grid-point position, vertical grid-size and scale factors]{
+    Comparison of (a) traditional definitions of grid-point position and grid-size in the vertical,
+    and (b) analytically derived grid-point position and scale factors.
+    For both grids here, the same $w$-point depth has been chosen but
+    in (a) the $t$-points are set half way between $w$-points while
+    in (b) they are defined from an analytical function:
+    $z(k) = 5 \, (k - 1/2)^3 - 45 \, (k - 1/2)^2 + 140 \, (k - 1/2) - 150$.
+    Note the resulting difference between the value of the grid-size $\Delta_k$ and
+    those of the scale factor $e_k$.}
+  \label{fig:DOM_zgr_e3}
+\end{figure}
+
+%% =================================================================================================
+\subsection{Discrete operators}
+\label{subsec:DOM_operators}
+
+Given the values of a variable $q$ at adjacent points,
+the differencing and averaging operators at the midpoint between them are:
+\begin{alignat*}{2}
+  % \label{eq:DOM_di_mi}
+  \delta_i [q]      &= &       &q (i + 1/2) - q (i - 1/2) \\
+  \overline q^{\, i} &= &\big\{ &q (i + 1/2) + q (i - 1/2) \big\} / 2
+\end{alignat*}
+
+Similar operators are defined with respect to $i + 1/2$, $j$, $j + 1/2$, $k$, and $k + 1/2$.
+Following \autoref{eq:MB_grad} and \autoref{eq:MB_lap},
+the gradient of a variable $q$ defined at a $t$-point has
+its three components defined at $u$-, $v$- and $w$-points while
+its Laplacian is defined at the $t$-point.
+These operators have the following discrete forms in the curvilinear $s$-coordinates system:
+\begin{gather*}
+  % \label{eq:DOM_grad}
+  \nabla q \equiv   \frac{1}{e_{1u}} \delta_{i + 1/2} [q] \; \, \vect i
+                  + \frac{1}{e_{2v}} \delta_{j + 1/2} [q] \; \, \vect j
+                  + \frac{1}{e_{3w}} \delta_{k + 1/2} [q] \; \, \vect k \\
+  % \label{eq:DOM_lap}
+  \Delta q \equiv   \frac{1}{e_{1t} \, e_{2t} \, e_{3t}}
+                    \; \lt[   \delta_i \lt( \frac{e_{2u} \, e_{3u}}{e_{1u}} \; \delta_{i + 1/2} [q] \rt)
+                            + \delta_j \lt( \frac{e_{1v} \, e_{3v}}{e_{2v}} \; \delta_{j + 1/2} [q] \rt) \; \rt]
+                  + \frac{1}{e_{3t}}
+                              \delta_k \lt[ \frac{1              }{e_{3w}} \; \delta_{k + 1/2} [q] \rt]
+\end{gather*}
+
+Following \autoref{eq:MB_curl} and \autoref{eq:MB_div},
+a vector $\vect A = (a_1,a_2,a_3)$ defined at vector points $(u,v,w)$ has
+its three curl components defined at $vw$-, $uw$, and $f$-points, and
+its divergence defined at $t$-points:
+\begin{multline*}
+% \label{eq:DOM_curl}
+  \nabla \times \vect A \equiv   \frac{1}{e_{2v} \, e_{3vw}}
+                                 \Big[   \delta_{j + 1/2} (e_{3w} \, a_3)
+                                       - \delta_{k + 1/2} (e_{2v} \, a_2) \Big] \vect i \\
+                               + \frac{1}{e_{2u} \, e_{3uw}}
+                                 \Big[   \delta_{k + 1/2} (e_{1u} \, a_1)
+                                       - \delta_{i + 1/2} (e_{3w} \, a_3) \Big] \vect j \\
+                               + \frac{1}{e_{1f} \, e_{2f}}
+                                 \Big[   \delta_{i + 1/2} (e_{2v} \, a_2)
+                                       - \delta_{j + 1/2} (e_{1u} \, a_1) \Big] \vect k
+\end{multline*}
+\[
+% \label{eq:DOM_div}
+  \nabla \cdot \vect A \equiv   \frac{1}{e_{1t} \, e_{2t} \, e_{3t}}
+                                \Big[ \delta_i (e_{2u} \, e_{3u} \, a_1) + \delta_j (e_{1v} \, e_{3v} \, a_2) \Big]
+                              + \frac{1}{e_{3t}} \delta_k (a_3)
+\]
+
+The vertical average over the whole water column is denoted by an overbar and
+is for a masked field $q$ (\ie\ a quantity that is equal to zero inside solid areas):
+\begin{equation}
+  \label{eq:DOM_bar}
+  \bar q = \frac{1}{H} \int_{k^b}^{k^o} q \; e_{3q} \, dk \equiv \frac{1}{H_q} \sum \limits_k q \; e_{3q}
+\end{equation}
+where $H_q$  is the ocean depth, which is the masked sum of the vertical scale factors at $q$ points,
+$k^b$ and $k^o$ are the bottom and surface $k$-indices,
+and the symbol $\sum \limits_k$ refers to a summation over all grid points of the same type in
+the direction indicated by the subscript (here $k$).
+
+In continuous form, the following properties are satisfied:
+\begin{gather}
+  \label{eq:DOM_curl_grad}
+  \nabla \times \nabla q = \vect 0 \\
+  \label{eq:DOM_div_curl}
+  \nabla \cdot (\nabla \times \vect A) = 0
+\end{gather}
+
+It is straightforward to demonstrate that these properties are verified locally in discrete form as
+soon as the scalar $q$ is taken at $t$-points and the vector $\vect A$ has its components defined at
+vector points $(u,v,w)$.
+
+Let $a$ and $b$ be two fields defined on the mesh, with a value of zero inside continental areas.
+It can be shown that the differencing operators ($\delta_i$, $\delta_j$ and
+$\delta_k$) are skew-symmetric linear operators,
+and further that the averaging operators ($\overline{\cdots}^{\, i}$, $\overline{\cdots}^{\, j}$ and
+$\overline{\cdots}^{\, k}$) are symmetric linear operators, \ie
+\begin{alignat}{5}
+  \label{eq:DOM_di_adj}
+  &\sum \limits_i a_i \; \delta_i [b]      &\equiv &- &&\sum \limits_i \delta      _{   i + 1/2} [a] &b_{i + 1/2} \\
+  \label{eq:DOM_mi_adj}
+  &\sum \limits_i a_i \; \overline b^{\, i} &\equiv &  &&\sum \limits_i \overline a ^{\, i + 1/2}     &b_{i + 1/2}
+\end{alignat}
+
+In other words,
+the adjoint of the differencing and averaging operators are $\delta_i^* = \delta_{i + 1/2}$ and
+$(\overline{\cdots}^{\, i})^* = \overline{\cdots}^{\, i + 1/2}$, respectively.
+These two properties will be used extensively in the \autoref{apdx:INVARIANTS} to
+demonstrate integral conservative properties of the discrete formulation chosen.
+
+%% =================================================================================================
+\subsection{Numerical indexing}
+\label{subsec:DOM_Num_Index}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{DOM_index_hor}
+  \caption[Horizontal integer indexing]{
+    Horizontal integer indexing used in the \fortran\ code.
+    The dashed area indicates the cell in which
+    variables contained in arrays have the same $i$- and $j$-indices}
+  \label{fig:DOM_index_hor}
+\end{figure}
+
+The array representation used in the \fortran\ code requires an integer indexing.
+However, the analytical definition of the mesh (see \autoref{subsec:DOM_cell}) is associated with
+the use of integer values for $t$-points only while
+all the other points involve integer and a half values.
+Therefore, a specific integer indexing has been defined for points other than $t$-points
+(\ie\ velocity and vorticity grid-points).
+Furthermore, the direction of the vertical indexing has been reversed and
+the surface level set at $k = 1$.
+
+%% =================================================================================================
+\subsubsection{Horizontal indexing}
+\label{subsec:DOM_Num_Index_hor}
+
+The indexing in the horizontal plane has been chosen as shown in \autoref{fig:DOM_index_hor}.
+For an increasing $i$ index ($j$ index),
+the $t$-point and the eastward $u$-point (northward $v$-point) have the same index
+(see the dashed area in \autoref{fig:DOM_index_hor}).
+A $t$-point and its nearest north-east $f$-point have the same $i$-and $j$-indices.
+
+%% =================================================================================================
+\subsubsection{Vertical indexing}
+\label{subsec:DOM_Num_Index_vertical}
+
+In the vertical, the chosen indexing requires special attention since
+the direction of the $k$-axis in the \fortran\ code is the reverse of
+that used in the semi-discrete equations and given in \autoref{subsec:DOM_cell}.
+The sea surface corresponds to the $w$-level $k = 1$,
+which is the same index as the $t$-level just below (\autoref{fig:DOM_index_vert}).
+The last $w$-level ($k = jpk$) either corresponds to or is below the ocean floor while
+the last $t$-level is always outside the ocean domain (\autoref{fig:DOM_index_vert}).
+Note that a $w$-point and the directly underlaying $t$-point have a common $k$ index
+(\ie\ $t$-points and their nearest $w$-point neighbour in negative index direction),
+in contrast to the indexing on the horizontal plane where
+the $t$-point has the same index as the nearest velocity points in
+the positive direction of the respective horizontal axis index
+(compare the dashed area in \autoref{fig:DOM_index_hor} and \autoref{fig:DOM_index_vert}).
+Since the scale factors are chosen to be strictly positive,
+a \textit{minus sign} is included in the \fortran\ implementations of
+\textit{all the vertical derivatives} of the discrete equations given in this manual in order to
+accommodate the opposing vertical index directions in implementation and documentation.
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{DOM_index_vert}
+  \caption[Vertical integer indexing]{
+    Vertical integer indexing used in the \fortran\ code.
+    Note that the $k$-axis is oriented downward.
+    The dashed area indicates the cell in which
+    variables contained in arrays have a common $k$-index.}
+  \label{fig:DOM_index_vert}
+\end{figure}
+
+%% =================================================================================================
+\section{Spatial domain configuration}
+\label{subsec:DOM_config}
+
+Two typical methods are available to specify the spatial domain configuration;
+they can be selected using parameter \np{ln_read_cfg}{ln\_read\_cfg} parameter in
+namelist \nam{cfg}{cfg}.
+
+If \np{ln_read_cfg}{ln\_read\_cfg} is set to \forcode{.true.},
+the domain-specific parameters and fields are read from a NetCDF input file,
+whose name (without its .nc suffix) can be specified as
+the value of the \np{cn_domcfg}{cn\_domcfg} parameter in namelist \nam{cfg}{cfg}.
+
+If \np{ln_read_cfg}{ln\_read\_cfg} is set to \forcode{.false.},
+the domain-specific parameters and fields can be provided (\eg\ analytically computed) by
+subroutines \mdl{usrdef\_hgr} and \mdl{usrdef\_zgr}.
+These subroutines can be supplied in the \path{MY_SRC} directory of the configuration,
+and default versions that configure the spatial domain for the GYRE reference configuration are
+present in the \path{./src/OCE/USR} directory.
+
+In version 4.0 there are no longer any options for reading complex bathymetries and
+performing a vertical discretisation at run-time.
+Whilst it is occasionally convenient to have a common bathymetry file and, for example,
+to run similar models with and without partial bottom boxes and/or sigma-coordinates,
+supporting such choices leads to overly complex code.
+Worse still is the difficulty of ensuring the model configurations intended to be identical are
+indeed so when the model domain itself can be altered by runtime selections.
+The code previously used to perform vertical discretisation has been incorporated into
+an external tool (\path{./tools/DOMAINcfg}) which is briefly described in \autoref{apdx:DOMCFG}.
+
+The next subsections summarise the parameter and fields related to
+the configuration of the whole model domain.
+These represent the minimum information that must be provided either via
+the \np{cn_domcfg}{cn\_domcfg} file or
+set by code inserted into user-supplied versions of the \texttt{usrdef\_*} subroutines.
+The requirements are presented in three sections:
+the domain size (\autoref{subsec:DOM_size}), the horizontal mesh (\autoref{subsec:DOM_hgr}),
+and the vertical grid (\autoref{subsec:DOM_zgr}).
+
+%% =================================================================================================
+\subsection{Domain size}
+\label{subsec:DOM_size}
+
+The total size of the computational domain is set by the parameters \jp{jpiglo}, \jp{jpjglo} and
+\jp{jpkglo} for the $i$, $j$ and $k$ directions, respectively.
+Note, that the variables \texttt{jpi} and \texttt{jpj} refer to
+the size of each processor subdomain when the code is run in parallel using domain decomposition
+(\key{mpp\_mpi} defined, see \autoref{sec:LBC_mpp}).
+
+The name of the configuration is set through parameter \np{cn_cfg}{cn\_cfg},
+and the nominal resolution through parameter \np{nn_cfg}{nn\_cfg}
+(unless in the input file both of variables \texttt{ORCA} and \texttt{ORCA\_index} are present,
+in which case \np{cn_cfg}{cn\_cfg} and \np{nn_cfg}{nn\_cfg} are set from these values accordingly).
+
+The global lateral boundary condition type is selected from 8 options using parameter \jp{jperio}.
+See \autoref{sec:LBC_jperio} for details on the available options and
+the corresponding values for \jp{jperio}.
+
+%% =================================================================================================
+\subsection[Horizontal grid mesh (\textit{domhgr.F90}]{Horizontal grid mesh (\protect\mdl{domhgr})}
+\label{subsec:DOM_hgr}
+
+%% =================================================================================================
+\subsubsection{Required fields}
+\label{sec:DOM_hgr_fields}
+
+The explicit specification of a range of mesh-related fields are required for
+the definition of a configuration.
+These include:
+
+\begin{clines}
+int    jpiglo, jpjglo, jpkglo     /* global domain sizes                                    */
+int    jperio                     /* lateral global domain b.c.                             */
+double glamt, glamu, glamv, glamf /* geographic longitude (t,u,v and f points respectively) */
+double gphit, gphiu, gphiv, gphif /* geographic latitude                                    */
+double e1t, e1u, e1v, e1f         /* horizontal scale factors                               */
+double e2t, e2u, e2v, e2f         /* horizontal scale factors                               */
+\end{clines}
+
+The values of the geographic longitude and latitude arrays at indices $i,j$ correspond to
+the analytical expressions of the longitude $\lambda$ and latitude $\varphi$ as a function of $(i,j)$,
+evaluated at the values as specified in \autoref{tab:DOM_cell} for the respective grid-point position.
+The calculation of the values of the horizontal scale factor arrays in general additionally involves
+partial derivatives of $\lambda$ and $\varphi$ with respect to $i$ and $j$,
+evaluated for the same arguments as $\lambda$ and $\varphi$.
+
+%% =================================================================================================
+\subsubsection{Optional fields}
+
+\begin{clines}
+                        /* Optional:                                                 */
+int    ORCA, ORCA_index /* configuration name, configuration resolution              */
+double e1e2u, e1e2v     /* U and V surfaces (if grid size reduction in some straits) */
+double ff_f, ff_t       /* Coriolis parameter (if not on the sphere)                 */
+\end{clines}
+
+\NEMO\ can support the local reduction of key strait widths by
+altering individual values of e2u or e1v at the appropriate locations.
+This is particularly useful for locations such as Gibraltar or Indonesian Throughflow pinch-points
+(see \autoref{sec:MISC_strait} for illustrated examples).
+The key is to reduce the faces of $T$-cell
+(\ie\ change the value of the horizontal scale factors at $u$- or $v$-point) but
+not the volume of the cells.
+Doing otherwise can lead to numerical instability issues.
+In normal operation the surface areas are computed from $e1u * e2u$ and $e1v * e2v$ but
+in cases where a gridsize reduction is required,
+the unaltered surface areas at $u$ and $v$ grid points
+(\texttt{e1e2u} and \texttt{e1e2v}, respectively) must be read or pre-computed in \mdl{usrdef\_hgr}.
+If these arrays are present in the \np{cn_domcfg}{cn\_domcfg} file they are read and
+the internal computation is suppressed.
+Versions of \mdl{usrdef\_hgr} which set their own values of \texttt{e1e2u} and \texttt{e1e2v} should
+set the surface-area computation flag:
+\texttt{ie1e2u\_v} to a non-zero value to suppress their re-computation.
+
+\smallskip
+Similar logic applies to the other optional fields:
+\texttt{ff\_f} and \texttt{ff\_t} which can be used to
+provide the Coriolis parameter at F- and T-points respectively if the mesh is not on a sphere.
+If present these fields will be read and used and
+the normal calculation ($2 * \Omega * \sin(\varphi)$) suppressed.
+Versions of \mdl{usrdef\_hgr} which set their own values of \texttt{ff\_f} and \texttt{ff\_t} should
+set the Coriolis computation flag:
+\texttt{iff} to a non-zero value to suppress their re-computation.
+
+Note that longitudes, latitudes, and scale factors at $w$ points are exactly equal to
+those of $t$ points, thus no specific arrays are defined at $w$ points.
+
+%% =================================================================================================
+\subsection[Vertical grid (\textit{domzgr.F90})]{Vertical grid (\protect\mdl{domzgr})}
+\label{subsec:DOM_zgr}
+
+\begin{listing}
+  \nlst{namdom}
+  \caption{\forcode{&namdom}}
+  \label{lst:namdom}
+\end{listing}
+
+In the vertical, the model mesh is determined by four things:
+\begin{enumerate}
+\item the bathymetry given in meters;
+\item the number of levels of the model (\jp{jpk});
+\item the analytical transformation $z(i,j,k)$ and the vertical scale factors
+  (derivatives of the transformation); and
+\item the masking system,
+  \ie\ the number of wet model levels at each $(i,j)$ location of the horizontal grid.
+\end{enumerate}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.5\textwidth]{DOM_z_zps_s_sps}
+  \caption[Ocean bottom regarding coordinate systems ($z$, $s$ and hybrid $s-z$)]{
+    The ocean bottom as seen by the model:
+    \begin{enumerate*}[label=(\textit{\alph*})]
+    \item $z$-coordinate with full step,
+    \item $z$-coordinate with partial step,
+    \item $s$-coordinate: terrain following representation,
+    \item hybrid $s-z$ coordinate,
+    \item hybrid $s-z$ coordinate with partial step, and
+    \item same as (e) but in the non-linear free surface
+      (\protect\np[=.false.]{ln_linssh}{ln\_linssh}).
+  \end{enumerate*}
+  Note that the non-linear free surface can be used with any of the 5 coordinates (a) to (e).}
+  \label{fig:DOM_z_zps_s_sps}
+\end{figure}
+
+The choice of a vertical coordinate is made when setting up the configuration;
+it is not intended to be an option which can be changed in the middle of an experiment.
+The one exception to this statement being the choice of linear or non-linear free surface.
+In v4.0 the linear free surface option is implemented as
+a special case of the non-linear free surface.
+This is computationally wasteful since it uses the structures for time-varying 3D metrics
+for fields that (in the linear free surface case) are fixed.
+However, the linear free-surface is rarely used and
+implementing it this way means a single configuration file can support both options.
+
+By default a non-linear free surface is used
+(\np{ln_linssh}{ln\_linssh} set to \forcode{=.false.} in \nam{dom}{dom}):
+the coordinate follow the time-variation of the free surface so that
+the transformation is time dependent: $z(i,j,k,t)$ (\eg\ \autoref{fig:DOM_z_zps_s_sps}f).
+When a linear free surface is assumed
+(\np{ln_linssh}{ln\_linssh} set to \forcode{=.true.} in \nam{dom}{dom}),
+the vertical coordinates are fixed in time, but
+the seawater can move up and down across the $z_0$ surface
+(in other words, the top of the ocean in not a rigid lid).
+
+Note that settings:
+\np{ln_zco}{ln\_zco}, \np{ln_zps}{ln\_zps}, \np{ln_sco}{ln\_sco} and \np{ln_isfcav}{ln\_isfcav}
+mentioned in the following sections appear to be namelist options but
+they are no longer truly namelist options for \NEMO.
+Their value is written to and read from the domain configuration file and
+they should be treated as fixed parameters for a particular configuration.
+They are namelist options for the \texttt{DOMAINcfg} tool that can be used to
+build the configuration file and serve both to provide a record of the choices made whilst
+building the configuration and to trigger appropriate code blocks within \NEMO.
+These values should not be altered in the \np{cn_domcfg}{cn\_domcfg} file.
+
+\medskip
+The decision on these choices must be made when the \np{cn_domcfg}{cn\_domcfg} file is constructed.
+Three main choices are offered (\autoref{fig:DOM_z_zps_s_sps}a-c):
+
+\begin{itemize}
+\item $z$-coordinate with full step bathymetry (\np[=.true.]{ln_zco}{ln\_zco}),
+\item $z$-coordinate with partial step ($zps$) bathymetry (\np[=.true.]{ln_zps}{ln\_zps}),
+\item Generalized, $s$-coordinate (\np[=.true.]{ln_sco}{ln\_sco}).
+\end{itemize}
+
+Additionally, hybrid combinations of the three main coordinates are available:
+$s-z$ or $s-zps$ coordinate (\autoref{fig:DOM_z_zps_s_sps}d and \autoref{fig:DOM_z_zps_s_sps}e).
+
+A further choice related to vertical coordinate concerns
+the presence (or not) of ocean cavities beneath ice shelves within the model domain.
+A setting of \np{ln_isfcav}{ln\_isfcav} as \forcode{.true.} indicates that
+the domain contains ocean cavities,
+otherwise the top, wet layer of the ocean will always be at the ocean surface.
+This option is currently only available for $z$- or $zps$-coordinates.
+In the latter case, partial steps are also applied at the ocean/ice shelf interface.
+
+Within the model,
+the arrays describing the grid point depths and vertical scale factors are
+three set of three dimensional arrays $(i,j,k)$ defined at
+\textit{before}, \textit{now} and \textit{after} time step.
+The time at which they are defined is indicated by a suffix: $\_b$, $\_n$, or $\_a$, respectively.
+They are updated at each model time step.
+The initial fixed reference coordinate system is held in variable names with a $\_0$ suffix.
+When the linear free surface option is used (\np[=.true.]{ln_linssh}{ln\_linssh}),
+\textit{before}, \textit{now} and \textit{after} arrays are initially set to
+their reference counterpart and remain fixed.
+
+%% =================================================================================================
+\subsubsection{Required fields}
+\label{sec:DOM_zgr_fields}
+
+The explicit specification of a range of fields related to the vertical grid are required for
+the definition of a configuration.
+These include:
+
+\begin{clines}
+int    ln_zco, ln_zps, ln_sco            /* flags for z-coord, z-coord with partial steps and s-coord    */
+int    ln_isfcav                         /* flag  for ice shelf cavities                                 */
+double e3t_1d, e3w_1d                    /* reference vertical scale factors at T and W points           */
+double e3t_0, e3u_0, e3v_0, e3f_0, e3w_0 /* vertical scale factors 3D coordinate at T,U,V,F and W points */
+double e3uw_0, e3vw_0                    /* vertical scale factors 3D coordinate at UW and VW points     */
+int    bottom_level, top_level           /* last wet T-points, 1st wet T-points (for ice shelf cavities) */
+                                         /* For reference:                                               */
+float  bathy_metry                       /* bathymetry used in setting top and bottom levels             */
+\end{clines}
+
+This set of vertical metrics is sufficient to describe the initial depth and thickness of
+every gridcell in the model regardless of the choice of vertical coordinate.
+With constant z-levels, e3 metrics will be uniform across each horizontal level.
+In the partial step case each e3 at the \jp{bottom\_level}
+(and, possibly, \jp{top\_level} if ice cavities are present)
+may vary from its horizontal neighbours.
+And, in s-coordinates, variations can occur throughout the water column.
+With the non-linear free-surface, all the coordinates behave more like the s-coordinate in that
+variations occur throughout the water column with displacements related to the sea surface height.
+These variations are typically much smaller than those arising from bottom fitted coordinates.
+The values for vertical metrics supplied in the domain configuration file can be considered as
+those arising from a flat sea surface with zero elevation.
+
+The \jp{bottom\_level} and \jp{top\_level} 2D arrays define
+the \jp{bottom\_level} and top wet levels in each grid column.
+Without ice cavities, \jp{top\_level} is essentially a land mask (0 on land; 1 everywhere else).
+With ice cavities, \jp{top\_level} determines the first wet point below the overlying ice shelf.
+
+%% =================================================================================================
+\subsubsection{Level bathymetry and mask}
+\label{subsec:DOM_msk}
+
+From \jp{top\_level} and \jp{bottom\_level} fields, the mask fields are defined as follows:
+\begin{align*}
+  tmask(i,j,k) &=
+  \begin{cases}
+    0 &\text{if $                             k <    top\_level(i,j)$} \\
+    1 &\text{if $     bottom\_level(i,j) \leq k \leq top\_level(i,j)$} \\
+    0 &\text{if $k >  bottom\_level(i,j)                            $}
+  \end{cases} \\
+  umask(i,j,k) &= tmask(i,j,k) * tmask(i + 1,j,    k) \\
+  vmask(i,j,k) &= tmask(i,j,k) * tmask(i    ,j + 1,k) \\
+  fmask(i,j,k) &= tmask(i,j,k) * tmask(i + 1,j,    k) * tmask(i,j,k) * tmask(i + 1,j,    k) \\
+  wmask(i,j,k) &= tmask(i,j,k) * tmask(i    ,j,k - 1) \\
+  \text{with~} wmask(i,j,1) &= tmask(i,j,1)
+\end{align*}
+
+Note that, without ice shelves cavities,
+masks at $t-$ and $w-$points are identical with the numerical indexing used
+(\autoref{subsec:DOM_Num_Index}).
+Nevertheless,
+$wmask$ are required with ocean cavities to deal with the top boundary (ice shelf/ocean interface)
+exactly in the same way as for the bottom boundary.
+
+%% The specification of closed lateral boundaries requires that at least
+%% the first and last rows and columns of the \textit{mbathy} array are set to zero.
+%% In the particular case of an east-west cyclical boundary condition, \textit{mbathy} has its last column equal to
+%% the second one and its first column equal to the last but one (and so too the mask arrays)
+%% (see \autoref{fig:LBC_jperio}).
+
+%        Closed seas
+%% =================================================================================================
+\subsection{Closed seas}
+\label{subsec:DOM_closea}
+
+When a global ocean is coupled to an atmospheric model it is better to
+represent all large water bodies (\eg\ Great Lakes, Caspian sea, \dots) even if
+the model resolution does not allow their communication with the rest of the ocean.
+This is unnecessary when the ocean is forced by fixed atmospheric conditions,
+so these seas can be removed from the ocean domain.
+The user has the option to
+set the bathymetry in closed seas to zero (see \autoref{sec:MISC_closea}) and to
+optionally decide on the fate of any freshwater imbalance over the area.
+The options are explained in \autoref{sec:MISC_closea} but
+it should be noted here that a successful use of these options requires
+appropriate mask fields to be present in the domain configuration file.
+Among the possibilities are:
+
+\begin{clines}
+int closea_mask     /* non-zero values in closed sea areas for optional masking                */
+int closea_mask_rnf /* non-zero values in closed sea areas with runoff locations (precip only) */
+int closea_mask_emp /* non-zero values in closed sea areas with runoff locations (total emp)   */
+\end{clines}
+
+%% =================================================================================================
+\subsection{Output grid files}
+\label{subsec:DOM_meshmask}
+
+Most of the arrays relating to a particular ocean model configuration discussed in this chapter
+(grid-point position, scale factors) can be saved in a file if
+namelist parameter \np{ln_write_cfg}{ln\_write\_cfg} (namelist \nam{cfg}{cfg}) is set to
+\forcode{.true.};
+the output filename is set through parameter \np{cn_domcfg_out}{cn\_domcfg\_out}.
+This is only really useful if
+the fields are computed in subroutines \mdl{usrdef\_hgr} or \mdl{usrdef\_zgr} and
+checking or confirmation is required.
+
+Alternatively, all the arrays relating to a particular ocean model configuration
+(grid-point position, scale factors, depths and masks) can be saved in
+a file called \texttt{mesh\_mask} if
+namelist parameter \np{ln_meshmask}{ln\_meshmask} (namelist \nam{dom}{dom}) is set to
+\forcode{.true.}.
+This file contains additional fields that can be useful for post-processing applications.
+
+%% =================================================================================================
+\section[Initial state (\textit{istate.F90} and \textit{dtatsd.F90})]{Initial state (\protect\mdl{istate} and \protect\mdl{dtatsd})}
+\label{sec:DOM_DTA_tsd}
+
+\begin{listing}
+  \nlst{namtsd}
+  \caption{\forcode{&namtsd}}
+  \label{lst:namtsd}
+\end{listing}
+
+Basic initial state options are defined in \nam{tsd}{tsd}.
+By default, the ocean starts from rest (the velocity field is set to zero) and
+the initialization of temperature and salinity fields is controlled through the \np{ln_tsd_init}{ln\_tsd\_init} namelist parameter.
+
+\begin{description}
+\item [{\np[=.true.]{ln_tsd_init}{ln\_tsd\_init}}] Use T and S input files that can be given on
+  the model grid itself or on their native input data grids.
+  In the latter case,
+  the data will be interpolated on-the-fly both in the horizontal and the vertical to the model grid
+  (see \autoref{subsec:SBC_iof}).
+  The information relating to the input files are specified in
+  the \np{sn_tem}{sn\_tem} and \np{sn_sal}{sn\_sal} structures.
+  The computation is done in the \mdl{dtatsd} module.
+\item [{\np[=.false.]{ln_tsd_init}{ln\_tsd\_init}}] Initial values for T and S are set via
+  a user supplied \rou{usr\_def\_istate} routine contained in \mdl{userdef\_istate}.
+  The default version sets horizontally uniform T and profiles as used in the GYRE configuration
+  (see \autoref{sec:CFGS_gyre}).
+\end{description}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DYN.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DYN.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_DYN.tex	(revision 14097)
@@ -0,0 +1,1600 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Ocean Dynamics (DYN)}
+\label{chap:DYN}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+Using the representation described in \autoref{chap:DOM},
+several semi-discrete space forms of the dynamical equations are available depending on
+the vertical coordinate used and on the conservation properties of the vorticity term.
+In all the equations presented here, the masking has been omitted for simplicity.
+One must be aware that all the quantities are masked fields and
+that each time an average or difference operator is used, the resulting field is multiplied by a mask.
+
+The prognostic ocean dynamics equation can be summarized as follows:
+\[
+  \text{NXT} = \dbinom	{\text{VOR} + \text{KEG} + \text {ZAD} }
+  {\text{COR} + \text{ADV}                       }
+  + \text{HPG} + \text{SPG} + \text{LDF} + \text{ZDF}
+\]
+NXT stands for next, referring to the time-stepping.
+The first group of terms on the rhs of this equation corresponds to the Coriolis and advection terms that
+are decomposed into either a vorticity part (VOR), a kinetic energy part (KEG) and
+a vertical advection part (ZAD) in the vector invariant formulation,
+or a Coriolis and advection part (COR+ADV) in the flux formulation.
+The terms following these are the pressure gradient contributions
+(HPG, Hydrostatic Pressure Gradient, and SPG, Surface Pressure Gradient);
+and contributions from lateral diffusion (LDF) and vertical diffusion (ZDF),
+which are added to the rhs in the \mdl{dynldf} and \mdl{dynzdf} modules.
+The vertical diffusion term includes the surface and bottom stresses.
+The external forcings and parameterisations require complex inputs
+(surface wind stress calculation using bulk formulae, estimation of mixing coefficients)
+that are carried out in modules SBC, LDF and ZDF and are described in
+\autoref{chap:SBC}, \autoref{chap:LDF} and \autoref{chap:ZDF}, respectively.
+
+In the present chapter we also describe the diagnostic equations used to compute the horizontal divergence,
+curl of the velocities (\emph{divcur} module) and the vertical velocity (\emph{wzvmod} module).
+
+The different options available to the user are managed by namelist variables.
+For term \textit{ttt} in the momentum equations, the logical namelist variables are \textit{ln\_dynttt\_xxx},
+where \textit{xxx} is a 3 or 4 letter acronym corresponding to each optional scheme.
+%If a CPP key is used for this term its name is \key{ttt}.
+The corresponding code can be found in the \textit{dynttt\_xxx} module in the DYN directory,
+and it is usually computed in the \textit{dyn\_ttt\_xxx} subroutine.
+
+The user has the option of extracting and outputting each tendency term from the 3D momentum equations
+(\texttt{trddyn?} defined), as described in \autoref{chap:MISC}.
+Furthermore, the tendency terms associated with the 2D barotropic vorticity balance (when \texttt{trdvor?} is defined)
+can be derived from the 3D terms.
+\cmtgm{STEVEN: not quite sure I've got the sense of the last sentence.
+  Does MISC correspond to "extracting tendency terms" or "vorticity balance"?}
+
+%% =================================================================================================
+\section{Sea surface height and diagnostic variables ($\eta$, $\zeta$, $\chi$, $w$)}
+\label{sec:DYN_divcur_wzv}
+
+%% =================================================================================================
+\subsection[Horizontal divergence and relative vorticity (\textit{divcur.F90})]{Horizontal divergence and relative vorticity (\protect\mdl{divcur})}
+\label{subsec:DYN_divcur}
+
+The vorticity is defined at an $f$-point (\ie\ corner point) as follows:
+\begin{equation}
+  \label{eq:DYN_divcur_cur}
+  \zeta =\frac{1}{e_{1f}\,e_{2f} }\left( {\;\delta_{i+1/2} \left[ {e_{2v}\;v} \right]
+      -\delta_{j+1/2} \left[ {e_{1u}\;u} \right]\;} \right)
+\end{equation}
+
+The horizontal divergence is defined at a $T$-point.
+It is given by:
+\[
+  % \label{eq:DYN_divcur_div}
+  \chi =\frac{1}{e_{1t}\,e_{2t}\,e_{3t} }
+  \left( {\delta_i \left[ {e_{2u}\,e_{3u}\,u} \right]
+      +\delta_j \left[ {e_{1v}\,e_{3v}\,v} \right]} \right)
+\]
+
+Note that although the vorticity has the same discrete expression in $z$- and $s$-coordinates,
+its physical meaning is not identical.
+$\zeta$ is a pseudo vorticity along $s$-surfaces
+(only pseudo because $(u,v)$ are still defined along geopotential surfaces,
+but are not necessarily defined at the same depth).
+
+The vorticity and divergence at the \textit{before} step are used in the computation of
+the horizontal diffusion of momentum.
+Note that because they have been calculated prior to the Asselin filtering of the \textit{before} velocities,
+the \textit{before} vorticity and divergence arrays must be included in the restart file to
+ensure perfect restartability.
+The vorticity and divergence at the \textit{now} time step are used for the computation of
+the nonlinear advection and of the vertical velocity respectively.
+
+%% =================================================================================================
+\subsection[Horizontal divergence and relative vorticity (\textit{sshwzv.F90})]{Horizontal divergence and relative vorticity (\protect\mdl{sshwzv})}
+\label{subsec:DYN_sshwzv}
+
+The sea surface height is given by:
+\begin{equation}
+  \label{eq:DYN_spg_ssh}
+  \begin{aligned}
+    \frac{\partial \eta }{\partial t}
+    &\equiv    \frac{1}{e_{1t} e_{2t} }\sum\limits_k { \left\{  \delta_i \left[ {e_{2u}\,e_{3u}\;u} \right]
+        +\delta_j \left[ {e_{1v}\,e_{3v}\;v} \right]  \right\} }
+    -    \frac{\textit{emp}}{\rho_w }   \\
+    &\equiv    \sum\limits_k {\chi \ e_{3t}}  -  \frac{\textit{emp}}{\rho_w }
+  \end{aligned}
+\end{equation}
+where \textit{emp} is the surface freshwater budget (evaporation minus precipitation),
+expressed in Kg/m$^2$/s (which is equal to mm/s),
+and $\rho_w$=1,035~Kg/m$^3$ is the reference density of sea water (Boussinesq approximation).
+If river runoff is expressed as a surface freshwater flux (see \autoref{chap:SBC}) then
+\textit{emp} can be written as the evaporation minus precipitation, minus the river runoff.
+The sea-surface height is evaluated using exactly the same time stepping scheme as
+the tracer equation \autoref{eq:TRA_nxt}:
+a leapfrog scheme in combination with an Asselin time filter,
+\ie\ the velocity appearing in \autoref{eq:DYN_spg_ssh} is centred in time (\textit{now} velocity).
+This is of paramount importance.
+Replacing $T$ by the number $1$ in the tracer equation and summing over the water column must lead to
+the sea surface height equation otherwise tracer content will not be conserved
+\citep{griffies.pacanowski.ea_MWR01, leclair.madec_OM09}.
+
+The vertical velocity is computed by an upward integration of the horizontal divergence starting at the bottom,
+taking into account the change of the thickness of the levels:
+\begin{equation}
+  \label{eq:DYN_wzv}
+  \left\{
+    \begin{aligned}
+      &\left. w \right|_{k_b-1/2} \quad= 0    \qquad \text{where } k_b \text{ is the level just above the sea floor }  	\\
+      &\left. w \right|_{k+1/2}     = \left. w \right|_{k-1/2}  +  \left. e_{3t} \right|_{k}\;  \left. \chi \right|_k
+      - \frac{1} {2 \rdt} \left(  \left. e_{3t}^{t+1}\right|_{k} - \left. e_{3t}^{t-1}\right|_{k}\right)
+    \end{aligned}
+  \right.
+\end{equation}
+
+In the case of a non-linear free surface (\texttt{vvl?}), the top vertical velocity is $-\textit{emp}/\rho_w$,
+as changes in the divergence of the barotropic transport are absorbed into the change of the level thicknesses,
+re-orientated downward.
+\cmtgm{not sure of this...  to be modified with the change in emp setting}
+In the case of a linear free surface, the time derivative in \autoref{eq:DYN_wzv} disappears.
+The upper boundary condition applies at a fixed level $z=0$.
+The top vertical velocity is thus equal to the divergence of the barotropic transport
+(\ie\ the first term in the right-hand-side of \autoref{eq:DYN_spg_ssh}).
+
+Note also that whereas the vertical velocity has the same discrete expression in $z$- and $s$-coordinates,
+its physical meaning is not the same:
+in the second case, $w$ is the velocity normal to the $s$-surfaces.
+Note also that the $k$-axis is re-orientated downwards in the \fortran\ code compared to
+the indexing used in the semi-discrete equations such as \autoref{eq:DYN_wzv}
+(see \autoref{subsec:DOM_Num_Index_vertical}).
+
+%% =================================================================================================
+\section{Coriolis and advection: vector invariant form}
+\label{sec:DYN_adv_cor_vect}
+
+\begin{listing}
+  \nlst{namdyn_adv}
+  \caption{\forcode{&namdyn_adv}}
+  \label{lst:namdyn_adv}
+\end{listing}
+
+The vector invariant form of the momentum equations is the one most often used in
+applications of the \NEMO\ ocean model.
+The flux form option (see next section) has been present since version $2$.
+Options are defined through the \nam{dyn_adv}{dyn\_adv} namelist variables Coriolis and
+momentum advection terms are evaluated using a leapfrog scheme,
+\ie\ the velocity appearing in these expressions is centred in time (\textit{now} velocity).
+At the lateral boundaries either free slip, no slip or partial slip boundary conditions are applied following
+\autoref{chap:LBC}.
+
+%% =================================================================================================
+\subsection[Vorticity term (\textit{dynvor.F90})]{Vorticity term (\protect\mdl{dynvor})}
+\label{subsec:DYN_vor}
+
+\begin{listing}
+  \nlst{namdyn_vor}
+  \caption{\forcode{&namdyn_vor}}
+  \label{lst:namdyn_vor}
+\end{listing}
+
+Options are defined through the \nam{dyn_vor}{dyn\_vor} namelist variables.
+Four discretisations of the vorticity term (\texttt{ln\_dynvor\_xxx}\forcode{=.true.}) are available:
+conserving potential enstrophy of horizontally non-divergent flow (ENS scheme);
+conserving horizontal kinetic energy (ENE scheme);
+conserving potential enstrophy for the relative vorticity term and
+horizontal kinetic energy for the planetary vorticity term (MIX scheme);
+or conserving both the potential enstrophy of horizontally non-divergent flow and horizontal kinetic energy
+(EEN scheme) (see \autoref{subsec:INVARIANTS_vorEEN}).
+In the case of ENS, ENE or MIX schemes the land sea mask may be slightly modified to ensure the consistency of
+vorticity term with analytical equations (\np[=.true.]{ln_dynvor_con}{ln\_dynvor\_con}).
+The vorticity terms are all computed in dedicated routines that can be found in the \mdl{dynvor} module.
+
+%                 enstrophy conserving scheme
+%% =================================================================================================
+\subsubsection[Enstrophy conserving scheme (\forcode{ln_dynvor_ens})]{Enstrophy conserving scheme (\protect\np{ln_dynvor_ens}{ln\_dynvor\_ens})}
+\label{subsec:DYN_vor_ens}
+
+In the enstrophy conserving case (ENS scheme),
+the discrete formulation of the vorticity term provides a global conservation of the enstrophy
+($ [ (\zeta +f ) / e_{3f} ]^2 $ in $s$-coordinates) for a horizontally non-divergent flow (\ie\ $\chi$=$0$),
+but does not conserve the total kinetic energy.
+It is given by:
+\begin{equation}
+  \label{eq:DYN_vor_ens}
+  \left\{
+    \begin{aligned}
+      {+\frac{1}{e_{1u} } } & {\overline {\left( { \frac{\zeta +f}{e_{3f} }} \right)} }^{\,i}
+      & {\overline{\overline {\left( {e_{1v}\,e_{3v}\;v} \right)}} }^{\,i, j+1/2}    \\
+      {- \frac{1}{e_{2v} } } & {\overline {\left( {\frac{\zeta +f}{e_{3f} }} \right)} }^{\,j}
+      & {\overline{\overline {\left( {e_{2u}\,e_{3u}\;u} \right)}} }^{\,i+1/2, j}
+    \end{aligned}
+  \right.
+\end{equation}
+
+%                 energy conserving scheme
+%% =================================================================================================
+\subsubsection[Energy conserving scheme (\forcode{ln_dynvor_ene})]{Energy conserving scheme (\protect\np{ln_dynvor_ene}{ln\_dynvor\_ene})}
+\label{subsec:DYN_vor_ene}
+
+The kinetic energy conserving scheme (ENE scheme) conserves the global kinetic energy but not the global enstrophy.
+It is given by:
+\begin{equation}
+  \label{eq:DYN_vor_ene}
+  \left\{
+    \begin{aligned}
+      {+\frac{1}{e_{1u}}\; {\overline {\left( {\frac{\zeta +f}{e_{3f} }} \right)
+            \;  \overline {\left( {e_{1v}\,e_{3v}\;v} \right)} ^{\,i+1/2}} }^{\,j} }    \\
+      {- \frac{1}{e_{2v}}\; {\overline {\left( {\frac{\zeta +f}{e_{3f} }} \right)
+            \;  \overline {\left( {e_{2u}\,e_{3u}\;u} \right)} ^{\,j+1/2}} }^{\,i} }
+    \end{aligned}
+  \right.
+\end{equation}
+
+%                 mix energy/enstrophy conserving scheme
+%% =================================================================================================
+\subsubsection[Mixed energy/enstrophy conserving scheme (\forcode{ln_dynvor_mix})]{Mixed energy/enstrophy conserving scheme (\protect\np{ln_dynvor_mix}{ln\_dynvor\_mix})}
+\label{subsec:DYN_vor_mix}
+
+For the mixed energy/enstrophy conserving scheme (MIX scheme), a mixture of the two previous schemes is used.
+It consists of the ENS scheme (\autoref{eq:DYN_vor_ens}) for the relative vorticity term,
+and of the ENE scheme (\autoref{eq:DYN_vor_ene}) applied to the planetary vorticity term.
+\[
+  % \label{eq:DYN_vor_mix}
+  \left\{ {
+      \begin{aligned}
+        {+\frac{1}{e_{1u} }\; {\overline {\left( {\frac{\zeta }{e_{3f} }} \right)} }^{\,i}
+          \; {\overline{\overline {\left( {e_{1v}\,e_{3v}\;v} \right)}} }^{\,i,j+1/2} -\frac{1}{e_{1u} }
+          \; {\overline {\left( {\frac{f}{e_{3f} }} \right)
+              \;\overline {\left( {e_{1v}\,e_{3v}\;v} \right)} ^{\,i+1/2}} }^{\,j} } \\
+        {-\frac{1}{e_{2v} }\; {\overline {\left( {\frac{\zeta }{e_{3f} }} \right)} }^j
+          \; {\overline{\overline {\left( {e_{2u}\,e_{3u}\;u} \right)}} }^{\,i+1/2,j} +\frac{1}{e_{2v} }
+          \; {\overline {\left( {\frac{f}{e_{3f} }} \right)
+              \;\overline {\left( {e_{2u}\,e_{3u}\;u} \right)} ^{\,j+1/2}} }^{\,i} } \hfill
+      \end{aligned}
+    } \right.
+\]
+
+%                 energy and enstrophy conserving scheme
+%% =================================================================================================
+\subsubsection[Energy and enstrophy conserving scheme (\forcode{ln_dynvor_een})]{Energy and enstrophy conserving scheme (\protect\np{ln_dynvor_een}{ln\_dynvor\_een})}
+\label{subsec:DYN_vor_een}
+
+In both the ENS and ENE schemes,
+it is apparent that the combination of $i$ and $j$ averages of the velocity allows for
+the presence of grid point oscillation structures that will be invisible to the operator.
+These structures are \textit{computational modes} that will be at least partly damped by
+the momentum diffusion operator (\ie\ the subgrid-scale advection), but not by the resolved advection term.
+The ENS and ENE schemes therefore do not contribute to dump any grid point noise in the horizontal velocity field.
+Such noise would result in more noise in the vertical velocity field, an undesirable feature.
+This is a well-known characteristic of $C$-grid discretization where
+$u$ and $v$ are located at different grid points,
+a price worth paying to avoid a double averaging in the pressure gradient term as in the $B$-grid.
+\cmtgm{ To circumvent this, Adcroft (ADD REF HERE)
+Nevertheless, this technique strongly distort the phase and group velocity of Rossby waves....}
+
+A very nice solution to the problem of double averaging was proposed by \citet{arakawa.hsu_MWR90}.
+The idea is to get rid of the double averaging by considering triad combinations of vorticity.
+It is noteworthy that this solution is conceptually quite similar to the one proposed by
+\citep{griffies.gnanadesikan.ea_JPO98} for the discretization of the iso-neutral diffusion operator (see \autoref{apdx:INVARIANTS}).
+
+The \citet{arakawa.hsu_MWR90} vorticity advection scheme for a single layer is modified
+for spherical coordinates as described by \citet{arakawa.lamb_MWR81} to obtain the EEN scheme.
+First consider the discrete expression of the potential vorticity, $q$, defined at an $f$-point:
+\[
+  % \label{eq:DYN_pot_vor}
+  q  = \frac{\zeta +f} {e_{3f} }
+\]
+where the relative vorticity is defined by (\autoref{eq:DYN_divcur_cur}),
+the Coriolis parameter is given by $f=2 \,\Omega \;\sin \varphi _f $ and the layer thickness at $f$-points is:
+\begin{equation}
+  \label{eq:DYN_een_e3f}
+  e_{3f} = \overline{\overline {e_{3t} }} ^{\,i+1/2,j+1/2}
+\end{equation}
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DYN_een_triad}
+  \caption[Triads used in the energy and enstrophy conserving scheme (EEN)]{
+    Triads used in the energy and enstrophy conserving scheme (EEN) for
+    $u$-component (upper panel) and $v$-component (lower panel).}
+  \label{fig:DYN_een_triad}
+\end{figure}
+
+A key point in \autoref{eq:DYN_een_e3f} is how the averaging in the \textbf{i}- and \textbf{j}- directions is made.
+It uses the sum of masked t-point vertical scale factor divided either by the sum of the four t-point masks
+(\np[=1]{nn_een_e3f}{nn\_een\_e3f}), or just by $4$ (\np[=.true.]{nn_een_e3f}{nn\_een\_e3f}).
+The latter case preserves the continuity of $e_{3f}$ when one or more of the neighbouring $e_{3t}$ tends to zero and
+extends by continuity the value of $e_{3f}$ into the land areas.
+This case introduces a sub-grid-scale topography at f-points
+(with a systematic reduction of $e_{3f}$ when a model level intercept the bathymetry)
+that tends to reinforce the topostrophy of the flow
+(\ie\ the tendency of the flow to follow the isobaths) \citep{penduff.le-sommer.ea_OS07}.
+
+Next, the vorticity triads, $ {^i_j}\mathbb{Q}^{i_p}_{j_p}$ can be defined at a $T$-point as
+the following triad combinations of the neighbouring potential vorticities defined at f-points
+(\autoref{fig:DYN_een_triad}):
+\begin{equation}
+  \label{eq:DYN_Q_triads}
+  _i^j \mathbb{Q}^{i_p}_{j_p}
+  = \frac{1}{12} \ \left(   q^{i-i_p}_{j+j_p} + q^{i+j_p}_{j+i_p} + q^{i+i_p}_{j-j_p}  \right)
+\end{equation}
+where the indices $i_p$ and $k_p$ take the values: $i_p = -1/2$ or $1/2$ and $j_p = -1/2$ or $1/2$.
+
+Finally, the vorticity terms are represented as:
+\begin{equation}
+  \label{eq:DYN_vor_een}
+  \left\{ {
+      \begin{aligned}
+        +q\,e_3 \, v 	&\equiv +\frac{1}{e_{1u} }   \sum_{\substack{i_p,\,k_p}}
+        {^{i+1/2-i_p}_j}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{1v}\,e_{3v} \;v  \right)^{i+1/2-i_p}_{j+j_p}   \\
+        - q\,e_3 \, u     &\equiv -\frac{1}{e_{2v} }    \sum_{\substack{i_p,\,k_p}}
+        {^i_{j+1/2-j_p}}  \mathbb{Q}^{i_p}_{j_p}  \left( e_{2u}\,e_{3u} \;u  \right)^{i+i_p}_{j+1/2-j_p}   \\
+      \end{aligned}
+    } \right.
+\end{equation}
+
+This EEN scheme in fact combines the conservation properties of the ENS and ENE schemes.
+It conserves both total energy and potential enstrophy in the limit of horizontally nondivergent flow
+(\ie\ $\chi$=$0$) (see \autoref{subsec:INVARIANTS_vorEEN}).
+Applied to a realistic ocean configuration, it has been shown that it leads to a significant reduction of
+the noise in the vertical velocity field \citep{le-sommer.penduff.ea_OM09}.
+Furthermore, used in combination with a partial steps representation of bottom topography,
+it improves the interaction between current and topography,
+leading to a larger topostrophy of the flow \citep{barnier.madec.ea_OD06, penduff.le-sommer.ea_OS07}.
+
+%% =================================================================================================
+\subsection[Kinetic energy gradient term (\textit{dynkeg.F90})]{Kinetic energy gradient term (\protect\mdl{dynkeg})}
+\label{subsec:DYN_keg}
+
+As demonstrated in \autoref{apdx:INVARIANTS},
+there is a single discrete formulation of the kinetic energy gradient term that,
+together with the formulation chosen for the vertical advection (see below),
+conserves the total kinetic energy:
+\[
+  % \label{eq:DYN_keg}
+  \left\{
+    \begin{aligned}
+      -\frac{1}{2 \; e_{1u} }  & \ \delta_{i+1/2} \left[ {\overline {u^2}^{\,i} + \overline{v^2}^{\,j}} \right]   \\
+      -\frac{1}{2 \; e_{2v} }  & \ \delta_{j+1/2} \left[ {\overline {u^2}^{\,i} + \overline{v^2}^{\,j}} \right]
+    \end{aligned}
+  \right.
+\]
+
+%% =================================================================================================
+\subsection[Vertical advection term (\textit{dynzad.F90})]{Vertical advection term (\protect\mdl{dynzad})}
+\label{subsec:DYN_zad}
+
+The discrete formulation of the vertical advection, t
+ogether with the formulation chosen for the gradient of kinetic energy (KE) term,
+conserves the total kinetic energy.
+Indeed, the change of KE due to the vertical advection is exactly balanced by
+the change of KE due to the gradient of KE (see \autoref{apdx:INVARIANTS}).
+\[
+  % \label{eq:DYN_zad}
+  \left\{
+    \begin{aligned}
+      -\frac{1} {e_{1u}\,e_{2u}\,e_{3u}} &\ \overline{\ \overline{ e_{1t}\,e_{2t}\;w } ^{\,i+1/2}  \;\delta_{k+1/2} \left[ u \right]\  }^{\,k}  \\
+      -\frac{1} {e_{1v}\,e_{2v}\,e_{3v}}  &\ \overline{\ \overline{ e_{1t}\,e_{2t}\;w } ^{\,j+1/2}  \;\delta_{k+1/2} \left[ u \right]\  }^{\,k}
+    \end{aligned}
+  \right.
+\]
+When \np[=.true.]{ln_dynzad_zts}{ln\_dynzad\_zts},
+a split-explicit time stepping with 5 sub-timesteps is used on the vertical advection term.
+This option can be useful when the value of the timestep is limited by vertical advection \citep{lemarie.debreu.ea_OM15}.
+Note that in this case,
+a similar split-explicit time stepping should be used on vertical advection of tracer to ensure a better stability,
+an option which is only available with a TVD scheme (see \np{ln_traadv_tvd_zts}{ln\_traadv\_tvd\_zts} in \autoref{subsec:TRA_adv_tvd}).
+
+%% =================================================================================================
+\section{Coriolis and advection: flux form}
+\label{sec:DYN_adv_cor_flux}
+
+Options are defined through the \nam{dyn_adv}{dyn\_adv} namelist variables.
+In the flux form (as in the vector invariant form),
+the Coriolis and momentum advection terms are evaluated using a leapfrog scheme,
+\ie\ the velocity appearing in their expressions is centred in time (\textit{now} velocity).
+At the lateral boundaries either free slip,
+no slip or partial slip boundary conditions are applied following \autoref{chap:LBC}.
+
+%% =================================================================================================
+\subsection[Coriolis plus curvature metric terms (\textit{dynvor.F90})]{Coriolis plus curvature metric terms (\protect\mdl{dynvor})}
+\label{subsec:DYN_cor_flux}
+
+In flux form, the vorticity term reduces to a Coriolis term in which the Coriolis parameter has been modified to account for the "metric" term.
+This altered Coriolis parameter is thus discretised at $f$-points.
+It is given by:
+\begin{multline*}
+  % \label{eq:DYN_cor_metric}
+  f+\frac{1}{e_1 e_2 }\left( {v\frac{\partial e_2 }{\partial i}  -  u\frac{\partial e_1 }{\partial j}} \right)  \\
+  \equiv   f + \frac{1}{e_{1f} e_{2f} } \left( { \ \overline v ^{i+1/2}\delta_{i+1/2} \left[ {e_{2u} } \right]
+      -  \overline u ^{j+1/2}\delta_{j+1/2} \left[ {e_{1u} } \right]  }  \ \right)
+\end{multline*}
+
+Any of the (\autoref{eq:DYN_vor_ens}), (\autoref{eq:DYN_vor_ene}) and (\autoref{eq:DYN_vor_een}) schemes can be used to
+compute the product of the Coriolis parameter and the vorticity.
+However, the energy-conserving scheme (\autoref{eq:DYN_vor_een}) has exclusively been used to date.
+This term is evaluated using a leapfrog scheme, \ie\ the velocity is centred in time (\textit{now} velocity).
+
+%% =================================================================================================
+\subsection[Flux form advection term (\textit{dynadv.F90})]{Flux form advection term (\protect\mdl{dynadv})}
+\label{subsec:DYN_adv_flux}
+
+The discrete expression of the advection term is given by:
+\[
+  % \label{eq:DYN_adv}
+  \left\{
+    \begin{aligned}
+      \frac{1}{e_{1u}\,e_{2u}\,e_{3u}}
+      \left(      \delta_{i+1/2} \left[ \overline{e_{2u}\,e_{3u}\;u }^{i       }  \ u_t      \right]
+        + \delta_{j       } \left[ \overline{e_{1u}\,e_{3u}\;v }^{i+1/2}  \ u_f      \right] \right.  \ \;   \\
+      \left.   + \delta_{k      } \left[ \overline{e_{1w}\,e_{2w}\;w}^{i+1/2}  \ u_{uw} \right] \right)   \\
+      \\
+      \frac{1}{e_{1v}\,e_{2v}\,e_{3v}}
+      \left(     \delta_{i       } \left[ \overline{e_{2u}\,e_{3u }\;u }^{j+1/2} \ v_f       \right]
+        + \delta_{j+1/2} \left[ \overline{e_{1u}\,e_{3u }\;v }^{i       } \ v_t       \right] \right.  \ \, \, \\
+      \left.  + \delta_{k      } \left[ \overline{e_{1w}\,e_{2w}\;w}^{j+1/2} \ v_{vw}  \right] \right) \\
+    \end{aligned}
+  \right.
+\]
+
+Two advection schemes are available:
+a $2^{nd}$ order centered finite difference scheme, CEN2,
+or a $3^{rd}$ order upstream biased scheme, UBS.
+The latter is described in \citet{shchepetkin.mcwilliams_OM05}.
+The schemes are selected using the namelist logicals \np{ln_dynadv_cen2}{ln\_dynadv\_cen2} and \np{ln_dynadv_ubs}{ln\_dynadv\_ubs}.
+In flux form, the schemes differ by the choice of a space and time interpolation to define the value of
+$u$ and $v$ at the centre of each face of $u$- and $v$-cells, \ie\ at the $T$-, $f$-,
+and $uw$-points for $u$ and at the $f$-, $T$- and $vw$-points for $v$.
+
+%                 2nd order centred scheme
+%% =================================================================================================
+\subsubsection[CEN2: $2^{nd}$ order centred scheme (\forcode{ln_dynadv_cen2})]{CEN2: $2^{nd}$ order centred scheme (\protect\np{ln_dynadv_cen2}{ln\_dynadv\_cen2})}
+\label{subsec:DYN_adv_cen2}
+
+In the centered $2^{nd}$ order formulation, the velocity is evaluated as the mean of the two neighbouring points:
+\begin{equation}
+  \label{eq:DYN_adv_cen2}
+  \left\{
+    \begin{aligned}
+      u_T^{cen2} &=\overline u^{i }       \quad &  u_F^{cen2} &=\overline u^{j+1/2}  \quad &  u_{uw}^{cen2} &=\overline u^{k+1/2}   \\
+      v_F^{cen2} &=\overline v ^{i+1/2} \quad & v_F^{cen2} &=\overline v^j		\quad &  v_{vw}^{cen2} &=\overline v ^{k+1/2}  \\
+    \end{aligned}
+  \right.
+\end{equation}
+
+The scheme is non diffusive (\ie\ conserves the kinetic energy) but dispersive (\ie\ it may create false extrema).
+It is therefore notoriously noisy and must be used in conjunction with an explicit diffusion operator to
+produce a sensible solution.
+The associated time-stepping is performed using a leapfrog scheme in conjunction with an Asselin time-filter,
+so $u$ and $v$ are the \emph{now} velocities.
+
+%                 UBS scheme
+%% =================================================================================================
+\subsubsection[UBS: Upstream Biased Scheme (\forcode{ln_dynadv_ubs})]{UBS: Upstream Biased Scheme (\protect\np{ln_dynadv_ubs}{ln\_dynadv\_ubs})}
+\label{subsec:DYN_adv_ubs}
+
+The UBS advection scheme is an upstream biased third order scheme based on
+an upstream-biased parabolic interpolation.
+For example, the evaluation of $u_T^{ubs} $ is done as follows:
+\begin{equation}
+  \label{eq:DYN_adv_ubs}
+  u_T^{ubs} =\overline u ^i-\;\frac{1}{6}
+  \begin{cases}
+    u"_{i-1/2}& 	\text{if $\ \overline{e_{2u}\,e_{3u} \ u}^i  \geqslant 0$ } 	\\
+    u"_{i+1/2}& 	\text{if $\ \overline{e_{2u}\,e_{3u} \ u}^i  < 0$ }
+  \end{cases}
+\end{equation}
+where $u"_{i+1/2} =\delta_{i+1/2} \left[ {\delta_i \left[ u \right]} \right]$.
+This results in a dissipatively dominant (\ie\ hyper-diffusive) truncation error
+\citep{shchepetkin.mcwilliams_OM05}.
+The overall performance of the advection scheme is similar to that reported in \citet{farrow.stevens_JPO95}.
+It is a relatively good compromise between accuracy and smoothness.
+It is not a \emph{positive} scheme, meaning that false extrema are permitted.
+But the amplitudes of the false extrema are significantly reduced over those in the centred second order method.
+As the scheme already includes a diffusion component, it can be used without explicit lateral diffusion on momentum
+(\ie\ \np[=]{ln_dynldf_lap}{ln\_dynldf\_lap}\np[=.false.]{ln_dynldf_bilap}{ln\_dynldf\_bilap}),
+and it is recommended to do so.
+
+The UBS scheme is not used in all directions.
+In the vertical, the centred $2^{nd}$ order evaluation of the advection is preferred, \ie\ $u_{uw}^{ubs}$ and
+$u_{vw}^{ubs}$ in \autoref{eq:DYN_adv_cen2} are used.
+UBS is diffusive and is associated with vertical mixing of momentum. \cmtgm{ gm  pursue the
+sentence:Since vertical mixing of momentum is a source term of the TKE equation...  }
+
+For stability reasons, the first term in (\autoref{eq:DYN_adv_ubs}),
+which corresponds to a second order centred scheme, is evaluated using the \textit{now} velocity (centred in time),
+while the second term, which is the diffusion part of the scheme,
+is evaluated using the \textit{before} velocity (forward in time).
+This is discussed by \citet{webb.de-cuevas.ea_JAOT98} in the context of the Quick advection scheme.
+
+Note that the UBS and QUICK (Quadratic Upstream Interpolation for Convective Kinematics) schemes only differ by
+one coefficient.
+Replacing $1/6$ by $1/8$ in (\autoref{eq:DYN_adv_ubs}) leads to the QUICK advection scheme \citep{webb.de-cuevas.ea_JAOT98}.
+This option is not available through a namelist parameter, since the $1/6$ coefficient is hard coded.
+Nevertheless it is quite easy to make the substitution in the \mdl{dynadv\_ubs} module and obtain a QUICK scheme.
+
+Note also that in the current version of \mdl{dynadv\_ubs},
+there is also the possibility of using a $4^{th}$ order evaluation of the advective velocity as in ROMS.
+This is an error and should be suppressed soon.
+\cmtgm{action :  this have to be done}
+
+%% =================================================================================================
+\section[Hydrostatic pressure gradient (\textit{dynhpg.F90})]{Hydrostatic pressure gradient (\protect\mdl{dynhpg})}
+\label{sec:DYN_hpg}
+
+\begin{listing}
+  \nlst{namdyn_hpg}
+  \caption{\forcode{&namdyn_hpg}}
+  \label{lst:namdyn_hpg}
+\end{listing}
+
+Options are defined through the \nam{dyn_hpg}{dyn\_hpg} namelist variables.
+The key distinction between the different algorithms used for
+the hydrostatic pressure gradient is the vertical coordinate used,
+since HPG is a \emph{horizontal} pressure gradient, \ie\ computed along geopotential surfaces.
+As a result, any tilt of the surface of the computational levels will require a specific treatment to
+compute the hydrostatic pressure gradient.
+
+The hydrostatic pressure gradient term is evaluated either using a leapfrog scheme,
+\ie\ the density appearing in its expression is centred in time (\emph{now} $\rho$),
+or a semi-implcit scheme.
+At the lateral boundaries either free slip, no slip or partial slip boundary conditions are applied.
+
+%% =================================================================================================
+\subsection[Full step $Z$-coordinate (\forcode{ln_dynhpg_zco})]{Full step $Z$-coordinate (\protect\np{ln_dynhpg_zco}{ln\_dynhpg\_zco})}
+\label{subsec:DYN_hpg_zco}
+
+The hydrostatic pressure can be obtained by integrating the hydrostatic equation vertically from the surface.
+However, the pressure is large at great depth while its horizontal gradient is several orders of magnitude smaller.
+This may lead to large truncation errors in the pressure gradient terms.
+Thus, the two horizontal components of the hydrostatic pressure gradient are computed directly as follows:
+
+for $k=km$ (surface layer, $jk=1$ in the code)
+\begin{equation}
+  \label{eq:DYN_hpg_zco_surf}
+  \left\{
+    \begin{aligned}
+      \left. \delta_{i+1/2} \left[  p^h 			 \right] \right|_{k=km}
+      &= \frac{1}{2} g \ 	\left. \delta_{i+1/2} \left[  e_{3w} \ \rho \right] \right|_{k=km}   \\
+      \left. \delta_{j+1/2} \left[  p^h  			 \right] \right|_{k=km}
+      &= \frac{1}{2} g \ 	\left. \delta_{j+1/2} \left[  e_{3w} \ \rho \right] \right|_{k=km}   \\
+    \end{aligned}
+  \right.
+\end{equation}
+
+for $1<k<km$ (interior layer)
+\begin{equation}
+  \label{eq:DYN_hpg_zco}
+  \left\{
+    \begin{aligned}
+      \left. \delta_{i+1/2} \left[  p^h 			 \right] \right|_{k}
+      &=					\left. \delta_{i+1/2} \left[  p^h 			 \right] \right|_{k-1}
+      +    \frac{1}{2}\;g\;	\left. \delta_{i+1/2} \left[  e_{3w} \ \overline {\rho}^{k+1/2} \right] \right|_{k}   \\
+      \left. \delta_{j+1/2} \left[  p^h  			 \right] \right|_{k}
+      &=     				\left. \delta_{j+1/2} \left[  p^h  			 \right] \right|_{k-1}
+      +    \frac{1}{2}\;g\;	\left. \delta_{j+1/2} \left[  e_{3w} \ \overline {\rho}^{k+1/2} \right] \right|_{k}   \\
+    \end{aligned}
+  \right.
+\end{equation}
+
+Note that the $1/2$ factor in (\autoref{eq:DYN_hpg_zco_surf}) is adequate because of the definition of $e_{3w}$ as
+the vertical derivative of the scale factor at the surface level ($z=0$).
+Note also that in case of variable volume level (\texttt{vvl?} defined),
+the surface pressure gradient is included in \autoref{eq:DYN_hpg_zco_surf} and
+\autoref{eq:DYN_hpg_zco} through the space and time variations of the vertical scale factor $e_{3w}$.
+
+%% =================================================================================================
+\subsection[Partial step $Z$-coordinate (\forcode{ln_dynhpg_zps})]{Partial step $Z$-coordinate (\protect\np{ln_dynhpg_zps}{ln\_dynhpg\_zps})}
+\label{subsec:DYN_hpg_zps}
+
+With partial bottom cells, tracers in horizontally adjacent cells generally live at different depths.
+Before taking horizontal gradients between these tracer points,
+a linear interpolation is used to approximate the deeper tracer as if
+it actually lived at the depth of the shallower tracer point.
+
+Apart from this modification,
+the horizontal hydrostatic pressure gradient evaluated in the $z$-coordinate with partial step is exactly as in
+the pure $z$-coordinate case.
+As explained in detail in section \autoref{sec:TRA_zpshde},
+the nonlinearity of pressure effects in the equation of state is such that
+it is better to interpolate temperature and salinity vertically before computing the density.
+Horizontal gradients of temperature and salinity are needed for the TRA modules,
+which is the reason why the horizontal gradients of density at the deepest model level are computed in
+module \mdl{zpsdhe} located in the TRA directory and described in \autoref{sec:TRA_zpshde}.
+
+%% =================================================================================================
+\subsection{$S$- and $Z$-$S$-coordinates}
+\label{subsec:DYN_hpg_sco}
+
+Pressure gradient formulations in an $s$-coordinate have been the subject of a vast number of papers
+(\eg, \citet{song_MWR98, shchepetkin.mcwilliams_OM05}).
+A number of different pressure gradient options are coded but the ROMS-like,
+density Jacobian with cubic polynomial method is currently disabled whilst known bugs are under investigation.
+
+$\bullet$ Traditional coding (see for example \citet{madec.delecluse.ea_JPO96}: (\np[=.true.]{ln_dynhpg_sco}{ln\_dynhpg\_sco})
+\begin{equation}
+  \label{eq:DYN_hpg_sco}
+  \left\{
+    \begin{aligned}
+      - \frac{1}    					{\rho_o \, e_{1u}} \;	\delta_{i+1/2} \left[  p^h  \right]
+      + \frac{g\; \overline {\rho}^{i+1/2}}	{\rho_o \, e_{1u}} \;	\delta_{i+1/2} \left[  z_t   \right]    \\
+      - \frac{1}    					{\rho_o \, e_{2v}} \;	\delta_{j+1/2} \left[  p^h  \right]
+      + \frac{g\; \overline {\rho}^{j+1/2}}	{\rho_o \, e_{2v}} \;	\delta_{j+1/2} \left[  z_t   \right]    \\
+    \end{aligned}
+  \right.
+\end{equation}
+
+Where the first term is the pressure gradient along coordinates,
+computed as in \autoref{eq:DYN_hpg_zco_surf} - \autoref{eq:DYN_hpg_zco},
+and $z_T$ is the depth of the $T$-point evaluated from the sum of the vertical scale factors at the $w$-point
+($e_{3w}$).
+
+$\bullet$ Traditional coding with adaptation for ice shelf cavities (\np[=.true.]{ln_dynhpg_isf}{ln\_dynhpg\_isf}).
+This scheme need the activation of ice shelf cavities (\np[=.true.]{ln_isfcav}{ln\_isfcav}).
+
+$\bullet$ Pressure Jacobian scheme (prj) (a research paper in preparation) (\np[=.true.]{ln_dynhpg_prj}{ln\_dynhpg\_prj})
+
+$\bullet$ Density Jacobian with cubic polynomial scheme (DJC) \citep{shchepetkin.mcwilliams_OM05}
+(\np[=.true.]{ln_dynhpg_djc}{ln\_dynhpg\_djc}) (currently disabled; under development)
+
+Note that expression \autoref{eq:DYN_hpg_sco} is commonly used when the variable volume formulation is activated
+(\texttt{vvl?}) because in that case, even with a flat bottom,
+the coordinate surfaces are not horizontal but follow the free surface \citep{levier.treguier.ea_rpt07}.
+The pressure jacobian scheme (\np[=.true.]{ln_dynhpg_prj}{ln\_dynhpg\_prj}) is available as
+an improved option to \np[=.true.]{ln_dynhpg_sco}{ln\_dynhpg\_sco} when \texttt{vvl?} is active.
+The pressure Jacobian scheme uses a constrained cubic spline to
+reconstruct the density profile across the water column.
+This method maintains the monotonicity between the density nodes.
+The pressure can be calculated by analytical integration of the density profile and
+a pressure Jacobian method is used to solve the horizontal pressure gradient.
+This method can provide a more accurate calculation of the horizontal pressure gradient than the standard scheme.
+
+%% =================================================================================================
+\subsection{Ice shelf cavity}
+\label{subsec:DYN_hpg_isf}
+
+Beneath an ice shelf, the total pressure gradient is the sum of the pressure gradient due to the ice shelf load and
+the pressure gradient due to the ocean load (\np[=.true.]{ln_dynhpg_isf}{ln\_dynhpg\_isf}).\\
+
+The main hypothesis to compute the ice shelf load is that the ice shelf is in an isostatic equilibrium.
+The top pressure is computed integrating from surface to the base of the ice shelf a reference density profile
+(prescribed as density of a water at 34.4 PSU and -1.9\deg{C}) and
+corresponds to the water replaced by the ice shelf.
+This top pressure is constant over time.
+A detailed description of this method is described in \citet{losch_JGR08}.\\
+
+The pressure gradient due to ocean load is computed using the expression \autoref{eq:DYN_hpg_sco} described in
+\autoref{subsec:DYN_hpg_sco}.
+
+%% =================================================================================================
+\subsection[Time-scheme (\forcode{ln_dynhpg_imp})]{Time-scheme (\protect\np{ln_dynhpg_imp}{ln\_dynhpg\_imp})}
+\label{subsec:DYN_hpg_imp}
+
+The default time differencing scheme used for the horizontal pressure gradient is a leapfrog scheme and
+therefore the density used in all discrete expressions given above is the  \textit{now} density,
+computed from the \textit{now} temperature and salinity.
+In some specific cases
+(usually high resolution simulations over an ocean domain which includes weakly stratified regions)
+the physical phenomenon that controls the time-step is internal gravity waves (IGWs).
+A semi-implicit scheme for doubling the stability limit associated with IGWs can be used
+\citep{brown.campana_MWR78, maltrud.smith.ea_JGR98}.
+It involves the evaluation of the hydrostatic pressure gradient as
+an average over the three time levels $t-\rdt$, $t$, and $t+\rdt$
+(\ie\ \textit{before}, \textit{now} and  \textit{after} time-steps),
+rather than at the central time level $t$ only, as in the standard leapfrog scheme.
+
+$\bullet$ leapfrog scheme (\np[=.true.]{ln_dynhpg_imp}{ln\_dynhpg\_imp}):
+
+\begin{equation}
+  \label{eq:DYN_hpg_lf}
+  \frac{u^{t+\rdt}-u^{t-\rdt}}{2\rdt} = \;\cdots \;
+  -\frac{1}{\rho_o \,e_{1u} }\delta_{i+1/2} \left[ {p_h^t } \right]
+\end{equation}
+
+$\bullet$ semi-implicit scheme (\np[=.true.]{ln_dynhpg_imp}{ln\_dynhpg\_imp}):
+\begin{equation}
+  \label{eq:DYN_hpg_imp}
+  \frac{u^{t+\rdt}-u^{t-\rdt}}{2\rdt} = \;\cdots \;
+  -\frac{1}{4\,\rho_o \,e_{1u} } \delta_{i+1/2} \left[ p_h^{t+\rdt} +2\,p_h^t +p_h^{t-\rdt}  \right]
+\end{equation}
+
+The semi-implicit time scheme \autoref{eq:DYN_hpg_imp} is made possible without
+significant additional computation since the density can be updated to time level $t+\rdt$ before
+computing the horizontal hydrostatic pressure gradient.
+It can be easily shown that the stability limit associated with the hydrostatic pressure gradient doubles using
+\autoref{eq:DYN_hpg_imp} compared to that using the standard leapfrog scheme \autoref{eq:DYN_hpg_lf}.
+Note that \autoref{eq:DYN_hpg_imp} is equivalent to applying a time filter to the pressure gradient to
+eliminate high frequency IGWs.
+Obviously, when using \autoref{eq:DYN_hpg_imp},
+the doubling of the time-step is achievable only if no other factors control the time-step,
+such as the stability limits associated with advection or diffusion.
+
+In practice, the semi-implicit scheme is used when \np[=.true.]{ln_dynhpg_imp}{ln\_dynhpg\_imp}.
+In this case, we choose to apply the time filter to temperature and salinity used in the equation of state,
+instead of applying it to the hydrostatic pressure or to the density,
+so that no additional storage array has to be defined.
+The density used to compute the hydrostatic pressure gradient (whatever the formulation) is evaluated as follows:
+\[
+  % \label{eq:DYN_rho_flt}
+  \rho^t = \rho( \widetilde{T},\widetilde {S},z_t)
+  \quad	  \text{with}	\quad
+  \widetilde{X} = 1 / 4 \left(  X^{t+\rdt} +2 \,X^t + X^{t-\rdt}  \right)
+\]
+
+Note that in the semi-implicit case, it is necessary to save the filtered density,
+an extra three-dimensional field, in the restart file to restart the model with exact reproducibility.
+This option is controlled by  \np{nn_dynhpg_rst}{nn\_dynhpg\_rst}, a namelist parameter.
+
+%% =================================================================================================
+\section[Surface pressure gradient (\textit{dynspg.F90})]{Surface pressure gradient (\protect\mdl{dynspg})}
+\label{sec:DYN_spg}
+
+\begin{listing}
+  \nlst{namdyn_spg}
+  \caption{\forcode{&namdyn_spg}}
+  \label{lst:namdyn_spg}
+\end{listing}
+
+Options are defined through the \nam{dyn_spg}{dyn\_spg} namelist variables.
+The surface pressure gradient term is related to the representation of the free surface (\autoref{sec:MB_hor_pg}).
+The main distinction is between the fixed volume case (linear free surface) and
+the variable volume case (nonlinear free surface, \texttt{vvl?} is defined).
+In the linear free surface case (\autoref{subsec:MB_free_surface})
+the vertical scale factors $e_{3}$ are fixed in time,
+while they are time-dependent in the nonlinear case (\autoref{subsec:MB_free_surface}).
+With both linear and nonlinear free surface, external gravity waves are allowed in the equations,
+which imposes a very small time step when an explicit time stepping is used.
+Two methods are proposed to allow a longer time step for the three-dimensional equations:
+the filtered free surface, which is a modification of the continuous equations (see \autoref{eq:MB_flt?}),
+and the split-explicit free surface described below.
+The extra term introduced in the filtered method is calculated implicitly,
+so that the update of the next velocities is done in module \mdl{dynspg\_flt} and not in \mdl{dynnxt}.
+
+The form of the surface pressure gradient term depends on how the user wants to
+handle the fast external gravity waves that are a solution of the analytical equation (\autoref{sec:MB_hor_pg}).
+Three formulations are available, all controlled by a CPP key (ln\_dynspg\_xxx):
+an explicit formulation which requires a small time step;
+a filtered free surface formulation which allows a larger time step by
+adding a filtering term into the momentum equation;
+and a split-explicit free surface formulation, described below, which also allows a larger time step.
+
+The extra term introduced in the filtered method is calculated implicitly, so that a solver is used to compute it.
+As a consequence the update of the $next$ velocities is done in module \mdl{dynspg\_flt} and not in \mdl{dynnxt}.
+
+%% =================================================================================================
+\subsection[Explicit free surface (\forcode{ln_dynspg_exp})]{Explicit free surface (\protect\np{ln_dynspg_exp}{ln\_dynspg\_exp})}
+\label{subsec:DYN_spg_exp}
+
+In the explicit free surface formulation (\np{ln_dynspg_exp}{ln\_dynspg\_exp} set to true),
+the model time step is chosen to be small enough to resolve the external gravity waves
+(typically a few tens of seconds).
+The surface pressure gradient, evaluated using a leap-frog scheme (\ie\ centered in time),
+is thus simply given by :
+\begin{equation}
+  \label{eq:DYN_spg_exp}
+  \left\{
+    \begin{aligned}
+      - \frac{1}{e_{1u}\,\rho_o} \;	\delta_{i+1/2} \left[  \,\rho \,\eta\,  \right] 	\\
+      - \frac{1}{e_{2v}\,\rho_o} \;	\delta_{j+1/2} \left[  \,\rho \,\eta\,  \right]
+    \end{aligned}
+  \right.
+\end{equation}
+
+Note that in the non-linear free surface case (\ie\ \texttt{vvl?} defined),
+the surface pressure gradient is already included in the momentum tendency through
+the level thickness variation allowed in the computation of the hydrostatic pressure gradient.
+Thus, nothing is done in the \mdl{dynspg\_exp} module.
+
+%% =================================================================================================
+\subsection[Split-explicit free surface (\forcode{ln_dynspg_ts})]{Split-explicit free surface (\protect\np{ln_dynspg_ts}{ln\_dynspg\_ts})}
+\label{subsec:DYN_spg_ts}
+%\nlst{namsplit}
+
+The split-explicit free surface formulation used in \NEMO\ (\np{ln_dynspg_ts}{ln\_dynspg\_ts} set to true),
+also called the time-splitting formulation, follows the one proposed by \citet{shchepetkin.mcwilliams_OM05}.
+The general idea is to solve the free surface equation and the associated barotropic velocity equations with
+a smaller time step than $\rdt$, the time step used for the three dimensional prognostic variables
+(\autoref{fig:DYN_spg_ts}).
+The size of the small time step, $\rdt_e$ (the external mode or barotropic time step) is provided through
+the \np{nn_baro}{nn\_baro} namelist parameter as: $\rdt_e = \rdt / nn\_baro$.
+This parameter can be optionally defined automatically (\np[=.true.]{ln_bt_nn_auto}{ln\_bt\_nn\_auto}) considering that
+the stability of the barotropic system is essentially controled by external waves propagation.
+Maximum Courant number is in that case time independent, and easily computed online from the input bathymetry.
+Therefore, $\rdt_e$ is adjusted so that the Maximum allowed Courant number is smaller than \np{rn_bt_cmax}{rn\_bt\_cmax}.
+
+The barotropic mode solves the following equations:
+% \begin{subequations}
+%  \label{eq:DYN_BT}
+\begin{equation}
+  \label{eq:DYN_BT_dyn}
+  \frac{\partial {\mathrm \overline{{\mathbf U}}_h} }{\partial t}=
+  -f\;{\mathrm {\mathbf k}}\times {\mathrm \overline{{\mathbf U}}_h}
+  -g\nabla _h \eta -\frac{c_b^{\textbf U}}{H+\eta} \mathrm {\overline{{\mathbf U}}_h} + \mathrm {\overline{\mathbf G}}
+\end{equation}
+\[
+  % \label{eq:DYN_BT_ssh}
+  \frac{\partial \eta }{\partial t}=-\nabla \cdot \left[ {\left( {H+\eta } \right) \; {\mathrm{\mathbf \overline{U}}}_h \,} \right]+P-E
+\]
+% \end{subequations}
+where $\mathrm {\overline{\mathbf G}}$ is a forcing term held constant, containing coupling term between modes,
+surface atmospheric forcing as well as slowly varying barotropic terms not explicitly computed to gain efficiency.
+The third term on the right hand side of \autoref{eq:DYN_BT_dyn} represents the bottom stress
+(see section \autoref{sec:ZDF_drg}), explicitly accounted for at each barotropic iteration.
+Temporal discretization of the system above follows a three-time step Generalized Forward Backward algorithm
+detailed in \citet{shchepetkin.mcwilliams_OM05}.
+AB3-AM4 coefficients used in \NEMO\ follow the second-order accurate,
+"multi-purpose" stability compromise as defined in \citet{shchepetkin.mcwilliams_ibk09}
+(see their figure 12, lower left).
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DYN_dynspg_ts}
+  \caption[Split-explicit time stepping scheme for the external and internal modes]{
+    Schematic of the split-explicit time stepping scheme for the external and internal modes.
+    Time increases to the right.
+    In this particular exemple,
+    a boxcar averaging window over \np{nn_baro}{nn\_baro} barotropic time steps is used
+    (\np[=1]{nn_bt_flt}{nn\_bt\_flt}) and \np[=5]{nn_baro}{nn\_baro}.
+    Internal mode time steps (which are also the model time steps) are denoted by
+    $t-\rdt$, $t$ and $t+\rdt$.
+    Variables with $k$ superscript refer to instantaneous barotropic variables,
+    $< >$ and $<< >>$ operator refer to time filtered variables using respectively primary
+    (red vertical bars) and secondary weights (blue vertical bars).
+    The former are used to obtain time filtered quantities at $t+\rdt$ while
+    the latter are used to obtain time averaged transports to advect tracers.
+    a) Forward time integration:
+    \protect\np[=.true.]{ln_bt_fw}{ln\_bt\_fw},  \protect\np[=.true.]{ln_bt_av}{ln\_bt\_av}.
+    b) Centred time integration:
+    \protect\np[=.false.]{ln_bt_fw}{ln\_bt\_fw}, \protect\np[=.true.]{ln_bt_av}{ln\_bt\_av}.
+    c) Forward time integration with no time filtering (POM-like scheme):
+    \protect\np[=.true.]{ln_bt_fw}{ln\_bt\_fw},  \protect\np[=.false.]{ln_bt_av}{ln\_bt\_av}.}
+  \label{fig:DYN_spg_ts}
+\end{figure}
+
+In the default case (\np[=.true.]{ln_bt_fw}{ln\_bt\_fw}),
+the external mode is integrated between \textit{now} and \textit{after} baroclinic time-steps
+(\autoref{fig:DYN_spg_ts}a).
+To avoid aliasing of fast barotropic motions into three dimensional equations,
+time filtering is eventually applied on barotropic quantities (\np[=.true.]{ln_bt_av}{ln\_bt\_av}).
+In that case, the integration is extended slightly beyond \textit{after} time step to
+provide time filtered quantities.
+These are used for the subsequent initialization of the barotropic mode in the following baroclinic step.
+Since external mode equations written at baroclinic time steps finally follow a forward time stepping scheme,
+asselin filtering is not applied to barotropic quantities.\\
+Alternatively, one can choose to integrate barotropic equations starting from \textit{before} time step
+(\np[=.false.]{ln_bt_fw}{ln\_bt\_fw}).
+Although more computationaly expensive ( \np{nn_baro}{nn\_baro} additional iterations are indeed necessary),
+the baroclinic to barotropic forcing term given at \textit{now} time step become centred in
+the middle of the integration window.
+It can easily be shown that this property removes part of splitting errors between modes,
+which increases the overall numerical robustness.
+%references to Patrick Marsaleix' work here. Also work done by SHOM group.
+
+
+As far as tracer conservation is concerned,
+barotropic velocities used to advect tracers must also be updated at \textit{now} time step.
+This implies to change the traditional order of computations in \NEMO:
+most of momentum trends (including the barotropic mode calculation) updated first, tracers' after.
+This \textit{de facto} makes semi-implicit hydrostatic pressure gradient
+(see section \autoref{subsec:DYN_hpg_imp})
+and time splitting not compatible.
+Advective barotropic velocities are obtained by using a secondary set of filtering weights,
+uniquely defined from the filter coefficients used for the time averaging (\citet{shchepetkin.mcwilliams_OM05}).
+Consistency between the time averaged continuity equation and the time stepping of tracers is here the key to
+obtain exact conservation.
+
+
+One can eventually choose to feedback instantaneous values by not using any time filter
+(\np[=.false.]{ln_bt_av}{ln\_bt\_av}).
+In that case, external mode equations are continuous in time,
+\ie\ they are not re-initialized when starting a new sub-stepping sequence.
+This is the method used so far in the POM model, the stability being maintained by
+refreshing at (almost) each barotropic time step advection and horizontal diffusion terms.
+Since the latter terms have not been added in \NEMO\ for computational efficiency,
+removing time filtering is not recommended except for debugging purposes.
+This may be used for instance to appreciate the damping effect of the standard formulation on
+external gravity waves in idealized or weakly non-linear cases.
+Although the damping is lower than for the filtered free surface,
+it is still significant as shown by \citet{levier.treguier.ea_rpt07} in the case of an analytical barotropic Kelvin wave.
+
+\cmtgm{               %%% copy from griffies Book
+
+\textbf{title: Time stepping the barotropic system }
+
+Assume knowledge of the full velocity and tracer fields at baroclinic time $\tau$.
+Hence, we can update the surface height and vertically integrated velocity with a leap-frog scheme using
+the small barotropic time step $\rdt$.
+We have
+
+\[
+  % \label{eq:DYN_spg_ts_eta}
+  \eta^{(b)}(\tau,t_{n+1}) - \eta^{(b)}(\tau,t_{n+1}) (\tau,t_{n-1})
+  = 2 \rdt \left[-\nabla \cdot \textbf{U}^{(b)}(\tau,t_n) + \text{EMP}_w(\tau) \right]
+\]
+\begin{multline*}
+  % \label{eq:DYN_spg_ts_u}
+  \textbf{U}^{(b)}(\tau,t_{n+1}) - \textbf{U}^{(b)}(\tau,t_{n-1})  \\
+  = 2\rdt \left[ - f \textbf{k} \times \textbf{U}^{(b)}(\tau,t_{n})
+    - H(\tau) \nabla p_s^{(b)}(\tau,t_{n}) +\textbf{M}(\tau) \right]
+\end{multline*}
+\
+
+In these equations, araised (b) denotes values of surface height and vertically integrated velocity updated with
+the barotropic time steps.
+The $\tau$ time label on $\eta^{(b)}$ and $U^{(b)}$ denotes the baroclinic time at which
+the vertically integrated forcing $\textbf{M}(\tau)$
+(note that this forcing includes the surface freshwater forcing),
+the tracer fields, the freshwater flux $\text{EMP}_w(\tau)$,
+and total depth of the ocean $H(\tau)$ are held for the duration of the barotropic time stepping over
+a single cycle.
+This is also the time that sets the barotropic time steps via
+\[
+  % \label{eq:DYN_spg_ts_t}
+  t_n=\tau+n\rdt
+\]
+with $n$ an integer.
+The density scaled surface pressure is evaluated via
+\[
+  % \label{eq:DYN_spg_ts_ps}
+  p_s^{(b)}(\tau,t_{n}) =
+  \begin{cases}
+    g \;\eta_s^{(b)}(\tau,t_{n}) \;\rho(\tau)_{k=1}) / \rho_o  &      \text{non-linear case} \\
+    g \;\eta_s^{(b)}(\tau,t_{n})  &      \text{linear case}
+  \end{cases}
+\]
+To get started, we assume the following initial conditions
+\[
+  % \label{eq:DYN_spg_ts_eta}
+  \begin{split}
+    \eta^{(b)}(\tau,t_{n=0}) &= \overline{\eta^{(b)}(\tau)}    \\
+    \eta^{(b)}(\tau,t_{n=1}) &= \eta^{(b)}(\tau,t_{n=0}) + \rdt \ \text{RHS}_{n=0}
+  \end{split}
+\]
+with
+\[
+  % \label{eq:DYN_spg_ts_etaF}
+  \overline{\eta^{(b)}(\tau)} = \frac{1}{N+1} \sum\limits_{n=0}^N \eta^{(b)}(\tau-\rdt,t_{n})
+\]
+the time averaged surface height taken from the previous barotropic cycle.
+Likewise,
+\[
+  % \label{eq:DYN_spg_ts_u}
+  \textbf{U}^{(b)}(\tau,t_{n=0}) = \overline{\textbf{U}^{(b)}(\tau)}	\\ \\
+  \textbf{U}(\tau,t_{n=1}) = \textbf{U}^{(b)}(\tau,t_{n=0}) + \rdt \ \text{RHS}_{n=0}
+\]
+with
+\[
+  % \label{eq:DYN_spg_ts_u}
+  \overline{\textbf{U}^{(b)}(\tau)} = \frac{1}{N+1} \sum\limits_{n=0}^N\textbf{U}^{(b)}(\tau-\rdt,t_{n})
+\]
+the time averaged vertically integrated transport.
+Notably, there is no Robert-Asselin time filter used in the barotropic portion of the integration.
+
+Upon reaching $t_{n=N} = \tau + 2\rdt \tau$ ,
+the vertically integrated velocity is time averaged to produce the updated vertically integrated velocity at
+baroclinic time $\tau + \rdt \tau$
+\[
+  % \label{eq:DYN_spg_ts_u}
+  \textbf{U}(\tau+\rdt) = \overline{\textbf{U}^{(b)}(\tau+\rdt)} = \frac{1}{N+1} \sum\limits_{n=0}^N\textbf{U}^{(b)}(\tau,t_{n})
+\]
+The surface height on the new baroclinic time step is then determined via a baroclinic leap-frog using
+the following form
+
+\begin{equation}
+  \label{eq:DYN_spg_ts_ssh}
+  \eta(\tau+\Delta) - \eta^{F}(\tau-\Delta) = 2\rdt \ \left[ - \nabla \cdot \textbf{U}(\tau) + \text{EMP}_w \right]
+\end{equation}
+
+The use of this "big-leap-frog" scheme for the surface height ensures compatibility between
+the mass/volume budgets and the tracer budgets.
+More discussion of this point is provided in Chapter 10 (see in particular Section 10.2).
+
+In general, some form of time filter is needed to maintain integrity of the surface height field due to
+the leap-frog splitting mode in equation \autoref{eq:DYN_spg_ts_ssh}.
+We have tried various forms of such filtering,
+with the following method discussed in \cite{griffies.pacanowski.ea_MWR01} chosen due to
+its stability and reasonably good maintenance of tracer conservation properties (see ??).
+
+\begin{equation}
+  \label{eq:DYN_spg_ts_sshf}
+  \eta^{F}(\tau-\Delta) =  \overline{\eta^{(b)}(\tau)}
+\end{equation}
+Another approach tried was
+
+\[
+  % \label{eq:DYN_spg_ts_sshf2}
+  \eta^{F}(\tau-\Delta) = \eta(\tau)
+  + (\alpha/2) \left[\overline{\eta^{(b)}}(\tau+\rdt)
+    + \overline{\eta^{(b)}}(\tau-\rdt) -2 \;\eta(\tau) \right]
+\]
+
+which is useful since it isolates all the time filtering aspects into the term multiplied by $\alpha$.
+This isolation allows for an easy check that tracer conservation is exact when
+eliminating tracer and surface height time filtering (see ?? for more complete discussion).
+However, in the general case with a non-zero $\alpha$,
+the filter \autoref{eq:DYN_spg_ts_sshf} was found to be more conservative, and so is recommended.
+
+}            %%end gm comment (copy of griffies book)
+
+%% =================================================================================================
+\subsection{Filtered free surface (\forcode{dynspg_flt?})}
+\label{subsec:DYN_spg_fltp}
+
+The filtered formulation follows the \citet{roullet.madec_JGR00} implementation.
+The extra term introduced in the equations (see \autoref{subsec:MB_free_surface}) is solved implicitly.
+The elliptic solvers available in the code are documented in \autoref{chap:MISC}.
+
+%% gm %%======>>>>   given here the discrete eqs provided to the solver
+\cmtgm{               %%% copy from chap-model basics
+  \[
+    % \label{eq:DYN_spg_flt}
+    \frac{\partial {\mathrm {\mathbf U}}_h }{\partial t}= {\mathrm {\mathbf M}}
+    - g \nabla \left( \tilde{\rho} \ \eta \right)
+    - g \ T_c \nabla \left( \widetilde{\rho} \ \partial_t \eta \right)
+  \]
+  where $T_c$, is a parameter with dimensions of time which characterizes the force,
+  $\widetilde{\rho} = \rho / \rho_o$ is the dimensionless density,
+  and $\mathrm {\mathbf M}$ represents the collected contributions of the Coriolis, hydrostatic pressure gradient,
+  non-linear and viscous terms in \autoref{eq:MB_dyn}.
+}   %end cmtgm
+
+Note that in the linear free surface formulation (\texttt{vvl?} not defined),
+the ocean depth is time-independent and so is the matrix to be inverted.
+It is computed once and for all and applies to all ocean time steps.
+
+%% =================================================================================================
+\section[Lateral diffusion term and operators (\textit{dynldf.F90})]{Lateral diffusion term and operators (\protect\mdl{dynldf})}
+\label{sec:DYN_ldf}
+
+\begin{listing}
+  \nlst{namdyn_ldf}
+  \caption{\forcode{&namdyn_ldf}}
+  \label{lst:namdyn_ldf}
+\end{listing}
+
+Options are defined through the \nam{dyn_ldf}{dyn\_ldf} namelist variables.
+The options available for lateral diffusion are to use either laplacian (rotated or not) or biharmonic operators.
+The coefficients may be constant or spatially variable;
+the description of the coefficients is found in the chapter on lateral physics (\autoref{chap:LDF}).
+The lateral diffusion of momentum is evaluated using a forward scheme,
+\ie\ the velocity appearing in its expression is the \textit{before} velocity in time,
+except for the pure vertical component that appears when a tensor of rotation is used.
+This latter term is solved implicitly together with the vertical diffusion term (see \autoref{chap:TD}).
+
+At the lateral boundaries either free slip,
+no slip or partial slip boundary conditions are applied according to the user's choice (see \autoref{chap:LBC}).
+
+\cmtgm{
+  Hyperviscous operators are frequently used in the simulation of turbulent flows to
+  control the dissipation of unresolved small scale features.
+  Their primary role is to provide strong dissipation at the smallest scale supported by
+  the grid while minimizing the impact on the larger scale features.
+  Hyperviscous operators are thus designed to be more scale selective than the traditional,
+  physically motivated Laplace operator.
+  In finite difference methods,
+  the biharmonic operator is frequently the method of choice to achieve this scale selective dissipation since
+  its damping time (\ie\ its spin down time) scale like $\lambda^{-4}$ for disturbances of wavelength $\lambda$
+  (so that short waves damped more rapidelly than long ones),
+  whereas the Laplace operator damping time scales only like $\lambda^{-2}$.
+}
+
+%% =================================================================================================
+\subsection[Iso-level laplacian (\forcode{ln_dynldf_lap})]{Iso-level laplacian operator (\protect\np{ln_dynldf_lap}{ln\_dynldf\_lap})}
+\label{subsec:DYN_ldf_lap}
+
+For lateral iso-level diffusion, the discrete operator is:
+\begin{equation}
+  \label{eq:DYN_ldf_lap}
+  \left\{
+    \begin{aligned}
+      D_u^{l{\mathrm {\mathbf U}}} =\frac{1}{e_{1u} }\delta_{i+1/2} \left[ {A_T^{lm}
+          \;\chi } \right]-\frac{1}{e_{2u} {\kern 1pt}e_{3u} }\delta_j \left[
+        {A_f^{lm} \;e_{3f} \zeta } \right] \\ \\
+      D_v^{l{\mathrm {\mathbf U}}} =\frac{1}{e_{2v} }\delta_{j+1/2} \left[ {A_T^{lm}
+          \;\chi } \right]+\frac{1}{e_{1v} {\kern 1pt}e_{3v} }\delta_i \left[
+        {A_f^{lm} \;e_{3f} \zeta } \right]
+    \end{aligned}
+  \right.
+\end{equation}
+
+As explained in \autoref{subsec:MB_ldf},
+this formulation (as the gradient of a divergence and curl of the vorticity) preserves symmetry and
+ensures a complete separation between the vorticity and divergence parts of the momentum diffusion.
+
+%% =================================================================================================
+\subsection[Rotated laplacian (\forcode{ln_dynldf_iso})]{Rotated laplacian operator (\protect\np{ln_dynldf_iso}{ln\_dynldf\_iso})}
+\label{subsec:DYN_ldf_iso}
+
+A rotation of the lateral momentum diffusion operator is needed in several cases:
+for iso-neutral diffusion in the $z$-coordinate (\np[=.true.]{ln_dynldf_iso}{ln\_dynldf\_iso}) and
+for either iso-neutral (\np[=.true.]{ln_dynldf_iso}{ln\_dynldf\_iso}) or
+geopotential (\np[=.true.]{ln_dynldf_hor}{ln\_dynldf\_hor}) diffusion in the $s$-coordinate.
+In the partial step case, coordinates are horizontal except at the deepest level and
+no rotation is performed when \np[=.true.]{ln_dynldf_hor}{ln\_dynldf\_hor}.
+The diffusion operator is defined simply as the divergence of down gradient momentum fluxes on
+each momentum component.
+It must be emphasized that this formulation ignores constraints on the stress tensor such as symmetry.
+The resulting discrete representation is:
+\begin{equation}
+  \label{eq:DYN_ldf_iso}
+  \begin{split}
+    D_u^{l\textbf{U}} &= \frac{1}{e_{1u} \, e_{2u} \, e_{3u} }	\\
+    &  \left\{\quad  {\delta_{i+1/2} \left[ {A_T^{lm}  \left(
+              {\frac{e_{2t} \; e_{3t} }{e_{1t} } \,\delta_{i}[u]
+                -e_{2t} \; r_{1t} \,\overline{\overline {\delta_{k+1/2}[u]}}^{\,i,\,k}}
+            \right)} \right]} 	\right. \\
+    & \qquad +\ \delta_j \left[ {A_f^{lm} \left( {\frac{e_{1f}\,e_{3f} }{e_{2f}
+            }\,\delta_{j+1/2} [u] - e_{1f}\, r_{2f}
+            \,\overline{\overline {\delta_{k+1/2} [u]}} ^{\,j+1/2,\,k}}
+        \right)} \right] \\
+    &\qquad +\ \delta_k \left[ {A_{uw}^{lm} \left( {-e_{2u} \, r_{1uw} \,\overline{\overline
+              {\delta_{i+1/2} [u]}}^{\,i+1/2,\,k+1/2} }
+        \right.} \right. \\
+    &  \ \qquad \qquad \qquad \quad\
+    - e_{1u} \, r_{2uw} \,\overline{\overline {\delta_{j+1/2} [u]}} ^{\,j,\,k+1/2} \\
+    & \left. {\left. { \ \qquad \qquad \qquad \ \ \ \left. {\
+                +\frac{e_{1u}\, e_{2u} }{e_{3uw} }\,\left( {r_{1uw}^2+r_{2uw}^2}
+                \right)\,\delta_{k+1/2} [u]} \right)} \right]\;\;\;} \right\} \\ \\
+    D_v^{l\textbf{V}} &= \frac{1}{e_{1v} \, e_{2v} \, e_{3v} } \\
+    &  \left\{\quad  {\delta_{i+1/2} \left[ {A_f^{lm}  \left(
+              {\frac{e_{2f} \; e_{3f} }{e_{1f} } \,\delta_{i+1/2}[v]
+                -e_{2f} \; r_{1f} \,\overline{\overline {\delta_{k+1/2}[v]}}^{\,i+1/2,\,k}}
+            \right)} \right]} 	\right. \\
+    & \qquad +\ \delta_j \left[ {A_T^{lm} \left( {\frac{e_{1t}\,e_{3t} }{e_{2t}
+            }\,\delta_{j} [v] - e_{1t}\, r_{2t}
+            \,\overline{\overline {\delta_{k+1/2} [v]}} ^{\,j,\,k}}
+        \right)} \right] \\
+    & \qquad +\ \delta_k \left[ {A_{vw}^{lm} \left( {-e_{2v} \, r_{1vw} \,\overline{\overline
+              {\delta_{i+1/2} [v]}}^{\,i+1/2,\,k+1/2} }\right.} \right. \\
+    &  \ \qquad \qquad \qquad \quad\
+    - e_{1v} \, r_{2vw} \,\overline{\overline {\delta_{j+1/2} [v]}} ^{\,j+1/2,\,k+1/2} \\
+    & \left. {\left. { \ \qquad \qquad \qquad \ \ \ \left. {\
+                +\frac{e_{1v}\, e_{2v} }{e_{3vw} }\,\left( {r_{1vw}^2+r_{2vw}^2}
+                \right)\,\delta_{k+1/2} [v]} \right)} \right]\;\;\;} \right\}
+  \end{split}
+\end{equation}
+where $r_1$ and $r_2$ are the slopes between the surface along which the diffusion operator acts and
+the surface of computation ($z$- or $s$-surfaces).
+The way these slopes are evaluated is given in the lateral physics chapter (\autoref{chap:LDF}).
+
+%% =================================================================================================
+\subsection[Iso-level bilaplacian (\forcode{ln_dynldf_bilap})]{Iso-level bilaplacian operator (\protect\np{ln_dynldf_bilap}{ln\_dynldf\_bilap})}
+\label{subsec:DYN_ldf_bilap}
+
+The lateral fourth order operator formulation on momentum is obtained by applying \autoref{eq:DYN_ldf_lap} twice.
+It requires an additional assumption on boundary conditions:
+the first derivative term normal to the coast depends on the free or no-slip lateral boundary conditions chosen,
+while the third derivative terms normal to the coast are set to zero (see \autoref{chap:LBC}).
+\cmtgm{add a remark on the the change in the position of the coefficient}
+
+%% =================================================================================================
+\section[Vertical diffusion term (\textit{dynzdf.F90})]{Vertical diffusion term (\protect\mdl{dynzdf})}
+\label{sec:DYN_zdf}
+
+Options are defined through the \nam{zdf}{zdf} namelist variables.
+The large vertical diffusion coefficient found in the surface mixed layer together with high vertical resolution implies that in the case of explicit time stepping there would be too restrictive a constraint on the time step.
+Two time stepping schemes can be used for the vertical diffusion term:
+$(a)$ a forward time differencing scheme
+(\np[=.true.]{ln_zdfexp}{ln\_zdfexp}) using a time splitting technique (\np{nn_zdfexp}{nn\_zdfexp} $>$ 1) or
+$(b)$ a backward (or implicit) time differencing scheme (\np[=.false.]{ln_zdfexp}{ln\_zdfexp})
+(see \autoref{chap:TD}).
+Note that namelist variables \np{ln_zdfexp}{ln\_zdfexp} and \np{nn_zdfexp}{nn\_zdfexp} apply to both tracers and dynamics.
+
+The formulation of the vertical subgrid scale physics is the same whatever the vertical coordinate is.
+The vertical diffusion operators given by \autoref{eq:MB_zdf} take the following semi-discrete space form:
+\[
+  % \label{eq:DYN_zdf}
+  \left\{
+    \begin{aligned}
+      D_u^{vm} &\equiv \frac{1}{e_{3u}} \ \delta_k \left[ \frac{A_{uw}^{vm} }{e_{3uw} }
+        \ \delta_{k+1/2} [\,u\,]         \right]     \\
+      \\
+      D_v^{vm} &\equiv \frac{1}{e_{3v}} \ \delta_k \left[ \frac{A_{vw}^{vm} }{e_{3vw} }
+        \ \delta_{k+1/2} [\,v\,]         \right]
+    \end{aligned}
+  \right.
+\]
+where $A_{uw}^{vm} $ and $A_{vw}^{vm} $ are the vertical eddy viscosity and diffusivity coefficients.
+The way these coefficients are evaluated depends on the vertical physics used (see \autoref{chap:ZDF}).
+
+The surface boundary condition on momentum is the stress exerted by the wind.
+At the surface, the momentum fluxes are prescribed as the boundary condition on
+the vertical turbulent momentum fluxes,
+\begin{equation}
+  \label{eq:DYN_zdf_sbc}
+  \left.{\left( {\frac{A^{vm} }{e_3 }\ \frac{\partial \textbf{U}_h}{\partial k}} \right)} \right|_{z=1}
+  = \frac{1}{\rho_o} \binom{\tau_u}{\tau_v }
+\end{equation}
+where $\left( \tau_u ,\tau_v \right)$ are the two components of the wind stress vector in
+the (\textbf{i},\textbf{j}) coordinate system.
+The high mixing coefficients in the surface mixed layer ensure that the surface wind stress is distributed in
+the vertical over the mixed layer depth.
+If the vertical mixing coefficient is small (when no mixed layer scheme is used)
+the surface stress enters only the top model level, as a body force.
+The surface wind stress is calculated in the surface module routines (SBC, see \autoref{chap:SBC}).
+
+The turbulent flux of momentum at the bottom of the ocean is specified through a bottom friction parameterisation
+(see \autoref{sec:ZDF_drg})
+
+%% =================================================================================================
+\section{External forcings}
+\label{sec:DYN_forcing}
+
+Besides the surface and bottom stresses (see the above section)
+which are introduced as boundary conditions on the vertical mixing,
+three other forcings may enter the dynamical equations by affecting the surface pressure gradient.
+
+(1) When \np[=.true.]{ln_apr_dyn}{ln\_apr\_dyn} (see \autoref{sec:SBC_apr}),
+the atmospheric pressure is taken into account when computing the surface pressure gradient.
+
+(2) When \np[=.true.]{ln_tide_pot}{ln\_tide\_pot} and \np[=.true.]{ln_tide}{ln\_tide} (see \autoref{sec:SBC_tide}),
+the tidal potential is taken into account when computing the surface pressure gradient.
+
+(3) When \np[=2]{nn_ice_embd}{nn\_ice\_embd} and LIM or CICE is used
+(\ie\ when the sea-ice is embedded in the ocean),
+the snow-ice mass is taken into account when computing the surface pressure gradient.
+
+\cmtgm{ missing : the lateral boundary condition !!!   another external forcing
+ }
+
+%% =================================================================================================
+\section{Wetting and drying }
+\label{sec:DYN_wetdry}
+
+There are two main options for wetting and drying code (wd):
+(a) an iterative limiter (il) and (b) a directional limiter (dl).
+The directional limiter is based on the scheme developed by \cite{warner.defne.ea_CG13} for RO
+MS
+which was in turn based on ideas developed for POM by \cite{oey_OM06}. The iterative
+limiter is a new scheme.  The iterative limiter is activated by setting $\mathrm{ln\_wd\_il} = \mathrm{.true.}$
+and $\mathrm{ln\_wd\_dl} = \mathrm{.false.}$. The directional limiter is activated
+by setting $\mathrm{ln\_wd\_dl} = \mathrm{.true.}$ and $\mathrm{ln\_wd\_il} = \mathrm{.false.}$.
+
+\begin{listing}
+  \nlst{namwad}
+  \caption{\forcode{&namwad}}
+  \label{lst:namwad}
+\end{listing}
+
+The following terminology is used. The depth of the topography (positive downwards)
+at each $(i,j)$ point is the quantity stored in array $\mathrm{ht\_wd}$ in the \NEMO\ code.
+The height of the free surface (positive upwards) is denoted by $ \mathrm{ssh}$. Given the sign
+conventions used, the water depth, $h$, is the height of the free surface plus the depth of the
+topography (i.e. $\mathrm{ssh} + \mathrm{ht\_wd}$).
+
+Both wd schemes take all points in the domain below a land elevation of $\mathrm{rn\_wdld}$ to be
+covered by water. They require the topography specified with a model
+configuration to have negative depths at points where the land is higher than the
+topography's reference sea-level. The vertical grid in \NEMO\ is normally computed relative to an
+initial state with zero sea surface height elevation.
+The user can choose to compute the vertical grid and heights in the model relative to
+a non-zero reference height for the free surface. This choice affects the calculation of the metrics and depths
+(i.e. the $\mathrm{e3t\_0, ht\_0}$ etc. arrays).
+
+Points where the water depth is less than $\mathrm{rn\_wdmin1}$ are interpreted as ``dry''.
+$\mathrm{rn\_wdmin1}$ is usually chosen to be of order $0.05$m but extreme topographies
+with very steep slopes require larger values for normal choices of time-step. Surface fluxes
+are also switched off for dry cells to prevent freezing, boiling etc. of very thin water layers.
+The fluxes are tappered down using a $\mathrm{tanh}$ weighting function
+to no flux as the dry limit $\mathrm{rn\_wdmin1}$ is approached. Even wet cells can be very shallow.
+The depth at which to start tapering is controlled by the user by setting $\mathrm{rn\_wd\_sbcdep}$.
+The fraction $(<1)$ of sufrace fluxes to use at this depth is set by $\mathrm{rn\_wd\_sbcfra}$.
+
+Both versions of the code have been tested in six test cases provided in the WAD\_TEST\_CASES configuration
+and in ``realistic'' configurations covering parts of the north-west European shelf.
+All these configurations have used pure sigma coordinates. It is expected that
+the wetting and drying code will work in domains with more general s-coordinates provided
+the coordinates are pure sigma in the region where wetting and drying actually occurs.
+
+The next sub-section descrbies the directional limiter and the following sub-section the iterative limiter.
+The final sub-section covers some additional considerations that are relevant to both schemes.
+
+%   Iterative limiters
+%% =================================================================================================
+\subsection[Directional limiter (\textit{wet\_dry.F90})]{Directional limiter (\mdl{wet\_dry})}
+\label{subsec:DYN_wd_directional_limiter}
+
+The principal idea of the directional limiter is that
+water should not be allowed to flow out of a dry tracer cell (i.e. one whose water depth is less than \np{rn_wdmin1}{rn\_wdmin1}).
+
+All the changes associated with this option are made to the barotropic solver for the non-linear
+free surface code within dynspg\_ts.
+On each barotropic sub-step the scheme determines the direction of the flow across each face of all the tracer cells
+and sets the flux across the face to zero when the flux is from a dry tracer cell. This prevents cells
+whose depth is rn\_wdmin1 or less from drying out further. The scheme does not force $h$ (the water depth) at tracer cells
+to be at least the minimum depth and hence is able to conserve mass / volume.
+
+The flux across each $u$-face of a tracer cell is multiplied by a factor zuwdmask (an array which depends on ji and jj).
+If the user sets \np[=.false.]{ln_wd_dl_ramp}{ln\_wd\_dl\_ramp} then zuwdmask is 1 when the
+flux is from a cell with water depth greater than \np{rn_wdmin1}{rn\_wdmin1} and 0 otherwise. If the user sets
+\np[=.true.]{ln_wd_dl_ramp}{ln\_wd\_dl\_ramp} the flux across the face is ramped down as the water depth decreases
+from 2 * \np{rn_wdmin1}{rn\_wdmin1} to \np{rn_wdmin1}{rn\_wdmin1}. The use of this ramp reduced grid-scale noise in idealised test cases.
+
+At the point where the flux across a $u$-face is multiplied by zuwdmask , we have chosen
+also to multiply the corresponding velocity on the ``now'' step at that face by zuwdmask. We could have
+chosen not to do that and to allow fairly large velocities to occur in these ``dry'' cells.
+The rationale for setting the velocity to zero is that it is the momentum equations that are being solved
+and the total momentum of the upstream cell (treating it as a finite volume) should be considered
+to be its depth times its velocity. This depth is considered to be zero at ``dry'' $u$-points consistent with its
+treatment in the calculation of the flux of mass across the cell face.
+
+\cite{warner.defne.ea_CG13} state that in their scheme the velocity masks at the cell faces for the baroclinic
+timesteps are set to 0 or 1 depending on whether the average of the masks over the barotropic sub-steps is respectively less than
+or greater than 0.5. That scheme does not conserve tracers in integrations started from constant tracer
+fields (tracers independent of $x$, $y$ and $z$). Our scheme conserves constant tracers because
+the velocities used at the tracer cell faces on the baroclinic timesteps are carefully calculated by dynspg\_ts
+to equal their mean value during the barotropic steps. If the user sets \np[=.true.]{ln_wd_dl_bc}{ln\_wd\_dl\_bc}, the
+baroclinic velocities are also multiplied by a suitably weighted average of zuwdmask.
+
+%   Iterative limiters
+
+%% =================================================================================================
+\subsection[Iterative limiter (\textit{wet\_dry.F90})]{Iterative limiter (\mdl{wet\_dry})}
+\label{subsec:DYN_wd_iterative_limiter}
+
+%% =================================================================================================
+\subsubsection[Iterative flux limiter (\textit{wet\_dry.F90})]{Iterative flux limiter (\mdl{wet\_dry})}
+\label{subsec:DYN_wd_il_spg_limiter}
+
+The iterative limiter modifies the fluxes across the faces of cells that are either already ``dry''
+or may become dry within the next time-step using an iterative method.
+
+The flux limiter for the barotropic flow (devised by Hedong Liu) can be understood as follows:
+
+The continuity equation for the total water depth in a column
+\begin{equation}
+  \label{eq:DYN_wd_continuity}
+  \frac{\partial h}{\partial t} + \mathbf{\nabla.}(h\mathbf{u}) = 0 .
+\end{equation}
+can be written in discrete form  as
+
+\begin{align}
+  \label{eq:DYN_wd_continuity_2}
+  \frac{e_1 e_2}{\Delta t} ( h_{i,j}(t_{n+1}) - h_{i,j}(t_e) )
+  &= - ( \mathrm{flxu}_{i+1,j} - \mathrm{flxu}_{i,j}  + \mathrm{flxv}_{i,j+1} - \mathrm{flxv}_{i,j} ) \\
+  &= \mathrm{zzflx}_{i,j} .
+\end{align}
+
+In the above $h$ is the depth of the water in the column at point $(i,j)$,
+$\mathrm{flxu}_{i+1,j}$ is the flux out of the ``eastern'' face of the cell and
+$\mathrm{flxv}_{i,j+1}$ the flux out of the ``northern'' face of the cell; $t_{n+1}$ is
+the new timestep, $t_e$ is the old timestep (either $t_b$ or $t_n$) and $ \Delta t =
+t_{n+1} - t_e$; $e_1 e_2$ is the area of the tracer cells centred at $(i,j)$ and
+$\mathrm{zzflx}$ is the sum of the fluxes through all the faces.
+
+The flux limiter splits the flux $\mathrm{zzflx}$ into fluxes that are out of the cell
+(zzflxp) and fluxes that are into the cell (zzflxn).  Clearly
+
+\begin{equation}
+  \label{eq:DYN_wd_zzflx_p_n_1}
+  \mathrm{zzflx}_{i,j} = \mathrm{zzflxp}_{i,j} + \mathrm{zzflxn}_{i,j} .
+\end{equation}
+
+The flux limiter iteratively adjusts the fluxes $\mathrm{flxu}$ and $\mathrm{flxv}$ until
+none of the cells will ``dry out''. To be precise the fluxes are limited until none of the
+cells has water depth less than $\mathrm{rn\_wdmin1}$ on step $n+1$.
+
+Let the fluxes on the $m$th iteration step be denoted by $\mathrm{flxu}^{(m)}$ and
+$\mathrm{flxv}^{(m)}$.  Then the adjustment is achieved by seeking a set of coefficients,
+$\mathrm{zcoef}_{i,j}^{(m)}$ such that:
+
+\begin{equation}
+  \label{eq:DYN_wd_continuity_coef}
+  \begin{split}
+    \mathrm{zzflxp}^{(m)}_{i,j} =& \mathrm{zcoef}_{i,j}^{(m)} \mathrm{zzflxp}^{(0)}_{i,j} \\
+    \mathrm{zzflxn}^{(m)}_{i,j} =& \mathrm{zcoef}_{i,j}^{(m)} \mathrm{zzflxn}^{(0)}_{i,j}
+  \end{split}
+\end{equation}
+
+where the coefficients are $1.0$ generally but can vary between $0.0$ and $1.0$ around
+cells that would otherwise dry.
+
+The iteration is initialised by setting
+
+\begin{equation}
+  \label{eq:DYN_wd_zzflx_initial}
+  \mathrm{zzflxp^{(0)}}_{i,j} = \mathrm{zzflxp}_{i,j} , \quad  \mathrm{zzflxn^{(0)}}_{i,j} = \mathrm{zzflxn}_{i,j} .
+\end{equation}
+
+The fluxes out of cell $(i,j)$ are updated at the $m+1$th iteration if the depth of the
+cell on timestep $t_e$, namely $h_{i,j}(t_e)$, is less than the total flux out of the cell
+times the timestep divided by the cell area. Using (\autoref{eq:DYN_wd_continuity_2}) this
+condition is
+
+\begin{equation}
+  \label{eq:DYN_wd_continuity_if}
+  h_{i,j}(t_e)  - \mathrm{rn\_wdmin1} <  \frac{\Delta t}{e_1 e_2} ( \mathrm{zzflxp}^{(m)}_{i,j} + \mathrm{zzflxn}^{(m)}_{i,j} ) .
+\end{equation}
+
+Rearranging (\autoref{eq:DYN_wd_continuity_if}) we can obtain an expression for the maximum
+outward flux that can be allowed and still maintain the minimum wet depth:
+
+\begin{equation}
+  \label{eq:DYN_wd_max_flux}
+  \begin{split}
+    \mathrm{zzflxp}^{(m+1)}_{i,j} = \Big[ (h_{i,j}(t_e) & - \mathrm{rn\_wdmin1} - \mathrm{rn\_wdmin2})  \frac{e_1 e_2}{\Delta t} \phantom{]} \\
+    \phantom{[} & -  \mathrm{zzflxn}^{(m)}_{i,j} \Big]
+  \end{split}
+\end{equation}
+
+Note a small tolerance ($\mathrm{rn\_wdmin2}$) has been introduced here {\itshape [Q: Why is
+this necessary/desirable?]}. Substituting from (\autoref{eq:DYN_wd_continuity_coef}) gives an
+expression for the coefficient needed to multiply the outward flux at this cell in order
+to avoid drying.
+
+\begin{equation}
+  \label{eq:DYN_wd_continuity_nxtcoef}
+  \begin{split}
+    \mathrm{zcoef}^{(m+1)}_{i,j} = \Big[ (h_{i,j}(t_e) & - \mathrm{rn\_wdmin1} - \mathrm{rn\_wdmin2})  \frac{e_1 e_2}{\Delta t} \phantom{]} \\
+    \phantom{[} & -  \mathrm{zzflxn}^{(m)}_{i,j} \Big] \frac{1}{ \mathrm{zzflxp}^{(0)}_{i,j} }
+  \end{split}
+\end{equation}
+
+Only the outward flux components are altered but, of course, outward fluxes from one cell
+are inward fluxes to adjacent cells and the balance in these cells may need subsequent
+adjustment; hence the iterative nature of this scheme.  Note, for example, that the flux
+across the ``eastern'' face of the $(i,j)$th cell is only updated at the $m+1$th iteration
+if that flux at the $m$th iteration is out of the $(i,j)$th cell. If that is the case then
+the flux across that face is into the $(i+1,j)$ cell and that flux will not be updated by
+the calculation for the $(i+1,j)$th cell. In this sense the updates to the fluxes across
+the faces of the cells do not ``compete'' (they do not over-write each other) and one
+would expect the scheme to converge relatively quickly. The scheme is flux based so
+conserves mass. It also conserves constant tracers for the same reason that the
+directional limiter does.
+
+%      Surface pressure gradients
+%% =================================================================================================
+\subsubsection[Modification of surface pressure gradients (\textit{dynhpg.F90})]{Modification of surface pressure gradients (\mdl{dynhpg})}
+\label{subsec:DYN_wd_il_spg}
+
+At ``dry'' points the water depth is usually close to $\mathrm{rn\_wdmin1}$. If the
+topography is sloping at these points the sea-surface will have a similar slope and there
+will hence be very large horizontal pressure gradients at these points. The WAD modifies
+the magnitude but not the sign of the surface pressure gradients (zhpi and zhpj) at such
+points by mulitplying them by positive factors (zcpx and zcpy respectively) that lie
+between $0$ and $1$.
+
+We describe how the scheme works for the ``eastward'' pressure gradient, zhpi, calculated
+at the $(i,j)$th $u$-point. The scheme uses the ht\_wd depths and surface heights at the
+neighbouring $(i+1,j)$ and $(i,j)$ tracer points.  zcpx is calculated using two logicals
+variables, $\mathrm{ll\_tmp1}$ and $\mathrm{ll\_tmp2}$ which are evaluated for each grid
+column.  The three possible combinations are illustrated in \autoref{fig:DYN_WAD_dynhpg}.
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{DYN_WAD_dynhpg}
+  \caption[Combinations controlling the limiting of the horizontal pressure gradient in
+  wetting and drying regimes]{
+    Three possible combinations of the logical variables controlling the
+    limiting of the horizontal pressure gradient in wetting and drying regimes}
+  \label{fig:DYN_WAD_dynhpg}
+\end{figure}
+
+The first logical, $\mathrm{ll\_tmp1}$, is set to true if and only if the water depth at
+both neighbouring points is greater than $\mathrm{rn\_wdmin1} + \mathrm{rn\_wdmin2}$ and
+the minimum height of the sea surface at the two points is greater than the maximum height
+of the topography at the two points:
+
+\begin{equation}
+  \label{eq:DYN_ll_tmp1}
+  \begin{split}
+    \mathrm{ll\_tmp1}  = & \mathrm{MIN(sshn(ji,jj), sshn(ji+1,jj))} > \\
+                     & \quad \mathrm{MAX(-ht\_wd(ji,jj), -ht\_wd(ji+1,jj))\  .and.} \\
+                     & \mathrm{MAX(sshn(ji,jj) + ht\_wd(ji,jj),} \\
+                     & \mathrm{\phantom{MAX(}sshn(ji+1,jj) + ht\_wd(ji+1,jj))} >\\
+                     & \quad\quad\mathrm{rn\_wdmin1 + rn\_wdmin2 }
+  \end{split}
+\end{equation}
+
+The second logical, $\mathrm{ll\_tmp2}$, is set to true if and only if the maximum height
+of the sea surface at the two points is greater than the maximum height of the topography
+at the two points plus $\mathrm{rn\_wdmin1} + \mathrm{rn\_wdmin2}$
+
+\begin{equation}
+  \label{eq:DYN_ll_tmp2}
+  \begin{split}
+    \mathrm{ ll\_tmp2 } = & \mathrm{( ABS( sshn(ji,jj) - sshn(ji+1,jj) ) > 1.E-12 )\ .AND.}\\
+    & \mathrm{( MAX(sshn(ji,jj), sshn(ji+1,jj)) > } \\
+    & \mathrm{\phantom{(} MAX(-ht\_wd(ji,jj), -ht\_wd(ji+1,jj)) + rn\_wdmin1 + rn\_wdmin2}) .
+  \end{split}
+\end{equation}
+
+If $\mathrm{ll\_tmp1}$ is true then the surface pressure gradient, zhpi at the $(i,j)$
+point is unmodified. If both logicals are false zhpi is set to zero.
+
+If $\mathrm{ll\_tmp1}$ is true and $\mathrm{ll\_tmp2}$ is false then the surface pressure
+gradient is multiplied through by zcpx which is the absolute value of the difference in
+the water depths at the two points divided by the difference in the surface heights at the
+two points. Thus the sign of the sea surface height gradient is retained but the magnitude
+of the pressure force is determined by the difference in water depths rather than the
+difference in surface height between the two points. Note that dividing by the difference
+between the sea surface heights can be problematic if the heights approach parity. An
+additional condition is applied to $\mathrm{ ll\_tmp2 }$ to ensure it is .false. in such
+conditions.
+
+%% =================================================================================================
+\subsubsection[Additional considerations (\textit{usrdef\_zgr.F90})]{Additional considerations (\mdl{usrdef\_zgr})}
+\label{subsec:DYN_WAD_additional}
+
+In the very shallow water where wetting and drying occurs the parametrisation of
+bottom drag is clearly very important. In order to promote stability
+it is sometimes useful to calculate the bottom drag using an implicit time-stepping approach.
+
+Suitable specifcation of the surface heat flux in wetting and drying domains in forced and
+coupled simulations needs further consideration. In order to prevent freezing or boiling
+in uncoupled integrations the net surface heat fluxes need to be appropriately limited.
+
+%      The WAD test cases
+%% =================================================================================================
+\subsection[The WAD test cases (\textit{usrdef\_zgr.F90})]{The WAD test cases (\mdl{usrdef\_zgr})}
+\label{subsec:DYN_WAD_test_cases}
+
+See the WAD tests MY\_DOC documention for details of the WAD test cases.
+
+%% =================================================================================================
+\section[Time evolution term (\textit{dynnxt.F90})]{Time evolution term (\protect\mdl{dynnxt})}
+\label{sec:DYN_nxt}
+
+Options are defined through the \nam{dom}{dom} namelist variables.
+The general framework for dynamics time stepping is a leap-frog scheme,
+\ie\ a three level centred time scheme associated with an Asselin time filter (cf. \autoref{chap:TD}).
+The scheme is applied to the velocity, except when
+using the flux form of momentum advection (cf. \autoref{sec:DYN_adv_cor_flux})
+in the variable volume case (\texttt{vvl?} defined),
+where it has to be applied to the thickness weighted velocity (see \autoref{sec:SCOORD_momentum})
+
+$\bullet$ vector invariant form or linear free surface
+(\np[=.true.]{ln_dynhpg_vec}{ln\_dynhpg\_vec} ; \texttt{vvl?} not defined):
+\[
+  % \label{eq:DYN_nxt_vec}
+  \left\{
+    \begin{aligned}
+      &u^{t+\rdt} = u_f^{t-\rdt} + 2\rdt  \ \text{RHS}_u^t  	\\
+      &u_f^t \;\quad = u^t+\gamma \,\left[ {u_f^{t-\rdt} -2u^t+u^{t+\rdt}} \right]
+    \end{aligned}
+  \right.
+\]
+
+$\bullet$ flux form and nonlinear free surface
+(\np[=.false.]{ln_dynhpg_vec}{ln\_dynhpg\_vec} ; \texttt{vvl?} defined):
+\[
+  % \label{eq:DYN_nxt_flux}
+  \left\{
+    \begin{aligned}
+      &\left(e_{3u}\,u\right)^{t+\rdt} = \left(e_{3u}\,u\right)_f^{t-\rdt} + 2\rdt \; e_{3u} \;\text{RHS}_u^t  	\\
+      &\left(e_{3u}\,u\right)_f^t \;\quad = \left(e_{3u}\,u\right)^t
+      +\gamma \,\left[ {\left(e_{3u}\,u\right)_f^{t-\rdt} -2\left(e_{3u}\,u\right)^t+\left(e_{3u}\,u\right)^{t+\rdt}} \right]
+    \end{aligned}
+  \right.
+\]
+where RHS is the right hand side of the momentum equation,
+the subscript $f$ denotes filtered values and $\gamma$ is the Asselin coefficient.
+$\gamma$ is initialized as \np{nn_atfp}{nn\_atfp} (namelist parameter).
+Its default value is \np[=10.e-3]{nn_atfp}{nn\_atfp}.
+In both cases, the modified Asselin filter is not applied since perfect conservation is not an issue for
+the momentum equations.
+
+Note that with the filtered free surface,
+the update of the \textit{after} velocities is done in the \mdl{dynsp\_flt} module,
+and only array swapping and Asselin filtering is done in \mdl{dynnxt}.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LBC.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LBC.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LBC.tex	(revision 14097)
@@ -0,0 +1,712 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Lateral Boundary Condition (LBC)}
+\label{chap:LBC}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+\cmtgm{Add here introduction to this chapter}
+
+%% =================================================================================================
+\section[Boundary condition at the coast (\forcode{rn_shlat})]{Boundary condition at the coast (\protect\np{rn_shlat}{rn\_shlat})}
+\label{sec:LBC_coast}
+
+\begin{listing}
+  \nlst{namlbc}
+  \caption{\forcode{&namlbc}}
+  \label{lst:namlbc}
+\end{listing}
+
+%The lateral ocean boundary conditions contiguous to coastlines are Neumann conditions for heat and salt
+%(no flux across boundaries) and Dirichlet conditions for momentum (ranging from free-slip to "strong" no-slip).
+%They are handled automatically by the mask system (see \autoref{subsec:DOM_msk}).
+
+%OPA allows land and topography grid points in the computational domain due to the presence of continents or islands,
+%and includes the use of a full or partial step representation of bottom topography.
+%The computation is performed over the whole domain, \ie\ we do not try to restrict the computation to ocean-only points.
+%This choice has two motivations.
+%Firstly, working on ocean only grid points overloads the code and harms the code readability.
+%Secondly, and more importantly, it drastically reduces the vector portion of the computation,
+%leading to a dramatic increase of CPU time requirement on vector computers.
+%The current section describes how the masking affects the computation of the various terms of the equations
+%with respect to the boundary condition at solid walls.
+%The process of defining which areas are to be masked is described in \autoref{subsec:DOM_msk}.
+
+Options are defined through the \nam{lbc}{lbc} namelist variables.
+The discrete representation of a domain with complex boundaries (coastlines and bottom topography) leads to
+arrays that include large portions where a computation is not required as the model variables remain at zero.
+Nevertheless, vectorial supercomputers are far more efficient when computing over a whole array,
+and the readability of a code is greatly improved when boundary conditions are applied in
+an automatic way rather than by a specific computation before or after each computational loop.
+An efficient way to work over the whole domain while specifying the boundary conditions,
+is to use multiplication by mask arrays in the computation.
+A mask array is a matrix whose elements are $1$ in the ocean domain and $0$ elsewhere.
+A simple multiplication of a variable by its own mask ensures that it will remain zero over land areas.
+Since most of the boundary conditions consist of a zero flux across the solid boundaries,
+they can be simply applied by multiplying variables by the correct mask arrays,
+\ie\ the mask array of the grid point where the flux is evaluated.
+For example, the heat flux in the \textbf{i}-direction is evaluated at $u$-points.
+Evaluating this quantity as,
+
+\[
+  % \label{eq:LBC_aaaa}
+  \frac{A^{lT} }{e_1 }\frac{\partial T}{\partial i}\equiv \frac{A_u^{lT}
+  }{e_{1u} } \; \delta_{i+1 / 2} \left[ T \right]\;\;mask_u
+\]
+(where mask$_{u}$ is the mask array at a $u$-point) ensures that the heat flux is zero inside land and
+at the boundaries, since mask$_{u}$ is zero at solid boundaries which in this case are defined at $u$-points
+(normal velocity $u$ remains zero at the coast) (\autoref{fig:LBC_uv}).
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_uv}
+  \caption[Lateral boundary at $T$-level]{
+    Lateral boundary (thick line) at T-level.
+    The velocity normal to the boundary is set to zero.}
+  \label{fig:LBC_uv}
+\end{figure}
+
+For momentum the situation is a bit more complex as two boundary conditions must be provided along the coast
+(one each for the normal and tangential velocities).
+The boundary of the ocean in the C-grid is defined by the velocity-faces.
+For example, at a given $T$-level,
+the lateral boundary (a coastline or an intersection with the bottom topography) is made of
+segments joining $f$-points, and normal velocity points are located between two $f-$points (\autoref{fig:LBC_uv}).
+The boundary condition on the normal velocity (no flux through solid boundaries)
+can thus be easily implemented using the mask system.
+The boundary condition on the tangential velocity requires a more specific treatment.
+This boundary condition influences the relative vorticity and momentum diffusive trends,
+and is required in order to compute the vorticity at the coast.
+Four different types of lateral boundary condition are available,
+controlled by the value of the \np{rn_shlat}{rn\_shlat} namelist parameter
+(The value of the mask$_{f}$ array along the coastline is set equal to this parameter).
+These are:
+
+\begin{figure}[!p]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_shlat}
+  \caption[Lateral boundary conditions]{
+    Lateral boundary conditions
+    (a) free-slip                       (\protect\np[=0]{rn_shlat}{rn\_shlat});
+    (b) no-slip                         (\protect\np[=2]{rn_shlat}{rn\_shlat});
+    (c) "partial" free-slip (\forcode{0<}\protect\np[<2]{rn_shlat}{rn\_shlat}) and
+    (d) "strong" no-slip    (\forcode{2<}\protect\np{rn_shlat}{rn\_shlat}).
+    Implied "ghost" velocity inside land area is display in grey.}
+  \label{fig:LBC_shlat}
+\end{figure}
+
+\begin{description}
+
+\item [free-slip boundary condition ({\np[=0]{rn_shlat}{rn\_shlat}})] the tangential velocity at
+  the coastline is equal to the offshore velocity,
+  \ie\ the normal derivative of the tangential velocity is zero at the coast,
+  so the vorticity: mask$_{f}$ array is set to zero inside the land and just at the coast
+  (\autoref{fig:LBC_shlat}-a).
+
+\item [no-slip boundary condition ({\np[=2]{rn_shlat}{rn\_shlat}})] the tangential velocity vanishes at the coastline.
+  Assuming that the tangential velocity decreases linearly from
+  the closest ocean velocity grid point to the coastline,
+  the normal derivative is evaluated as if the velocities at the closest land velocity gridpoint and
+  the closest ocean velocity gridpoint were of the same magnitude but in the opposite direction
+  (\autoref{fig:LBC_shlat}-b).
+  Therefore, the vorticity along the coastlines is given by:
+
+  \[
+    \zeta \equiv 2 \left(\delta_{i+1/2} \left[e_{2v} v \right] - \delta_{j+1/2} \left[e_{1u} u \right] \right) / \left(e_{1f} e_{2f} \right) \ ,
+  \]
+  where $u$ and $v$ are masked fields.
+  Setting the mask$_{f}$ array to $2$ along the coastline provides a vorticity field computed with
+  the no-slip boundary condition, simply by multiplying it by the mask$_{f}$ :
+  \[
+    % \label{eq:LBC_bbbb}
+    \zeta \equiv \frac{1}{e_{1f} {\kern 1pt}e_{2f} }\left( {\delta_{i+1/2}
+        \left[ {e_{2v} \,v} \right]-\delta_{j+1/2} \left[ {e_{1u} \,u} \right]}
+    \right)\;\mbox{mask}_f
+  \]
+
+\item ["partial" free-slip boundary condition (0$<$\np{rn_shlat}{rn\_shlat}$<$2)] the tangential velocity at
+  the coastline is smaller than the offshore velocity, \ie\ there is a lateral friction but
+  not strong enough to make the tangential velocity at the coast vanish (\autoref{fig:LBC_shlat}-c).
+  This can be selected by providing a value of mask$_{f}$ strictly inbetween $0$ and $2$.
+
+\item ["strong" no-slip boundary condition (2$<$\np{rn_shlat}{rn\_shlat})] the viscous boundary layer is assumed to
+  be smaller than half the grid size (\autoref{fig:LBC_shlat}-d).
+  The friction is thus larger than in the no-slip case.
+
+\end{description}
+
+Note that when the bottom topography is entirely represented by the $s$-coordinates (pure $s$-coordinate),
+the lateral boundary condition on tangential velocity is of much less importance as
+it is only applied next to the coast where the minimum water depth can be quite shallow.
+
+%% =================================================================================================
+\section[Model domain boundary condition (\forcode{jperio})]{Model domain boundary condition (\protect\jp{jperio})}
+\label{sec:LBC_jperio}
+
+At the model domain boundaries several choices are offered:
+closed, cyclic east-west, cyclic north-south, a north-fold, and combination closed-north fold or
+bi-cyclic east-west and north-fold.
+The north-fold boundary condition is associated with the 3-pole ORCA mesh.
+
+%% =================================================================================================
+\subsection[Closed, cyclic (\forcode{=0,1,2,7})]{Closed, cyclic (\protect\jp{jperio}\forcode{=0,1,2,7})}
+\label{subsec:LBC_jperio012}
+
+The choice of closed or cyclic model domain boundary condition is made by
+setting \jp{jperio} to 0, 1, 2 or 7 in namelist \nam{cfg}{cfg}.
+Each time such a boundary condition is needed, it is set by a call to routine \mdl{lbclnk}.
+The computation of momentum and tracer trends proceeds from $i=2$ to $i=jpi-1$ and from $j=2$ to $j=jpj-1$,
+\ie\ in the model interior.
+To choose a lateral model boundary condition is to specify the first and last rows and columns of
+the model variables.
+
+\begin{description}
+
+\item [For closed boundary (\jp{jperio}\forcode{=0})], solid walls are imposed at all model boundaries:
+  first and last rows and columns are set to zero.
+
+\item [For cyclic east-west boundary (\jp{jperio}\forcode{=1})], first and last rows are set to zero (closed) whilst the first column is set to
+  the value of the last-but-one column and the last column to the value of the second one
+  (\autoref{fig:LBC_jperio}-a).
+  Whatever flows out of the eastern (western) end of the basin enters the western (eastern) end.
+
+\item [For cyclic north-south boundary (\jp{jperio}\forcode{=2})], first and last columns are set to zero (closed) whilst the first row is set to
+  the value of the last-but-one row and the last row to the value of the second one
+  (\autoref{fig:LBC_jperio}-a).
+  Whatever flows out of the northern (southern) end of the basin enters the southern (northern) end.
+
+\item [Bi-cyclic east-west and north-south boundary (\jp{jperio}\forcode{=7})] combines cases 1 and 2.
+
+\end{description}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_jperio}
+  \caption[Setting of east-west cyclic and symmetric across the Equator boundary conditions]{
+    Setting of (a) east-west cyclic (b) symmetric across the Equator boundary conditions}
+  \label{fig:LBC_jperio}
+\end{figure}
+
+%% =================================================================================================
+\subsection[North-fold (\forcode{=3,6})]{North-fold (\protect\jp{jperio}\forcode{=3,6})}
+\label{subsec:LBC_north_fold}
+
+The north fold boundary condition has been introduced in order to handle the north boundary of
+a three-polar ORCA grid.
+Such a grid has two poles in the northern hemisphere (\autoref{fig:CFGS_ORCA_msh},
+and thus requires a specific treatment illustrated in \autoref{fig:LBC_North_Fold_T}.
+Further information can be found in \mdl{lbcnfd} module which applies the north fold boundary condition.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_North_Fold_T}
+  \caption[North fold boundary in ORCA 2\deg, 1/4\deg and 1/12\deg]{
+    North fold boundary with a $T$-point pivot and cyclic east-west boundary condition ($jperio=4$),
+    as used in ORCA 2\deg, 1/4\deg and 1/12\deg.
+    Pink shaded area corresponds to the inner domain mask (see text).}
+  \label{fig:LBC_North_Fold_T}
+\end{figure}
+
+%% =================================================================================================
+\section[Exchange with neighbouring processors (\textit{lbclnk.F90}, \textit{lib\_mpp.F90})]{Exchange with neighbouring processors (\protect\mdl{lbclnk}, \protect\mdl{lib\_mpp})}
+\label{sec:LBC_mpp}
+
+\begin{listing}
+  \nlst{nammpp}
+  \caption{\forcode{&nammpp}}
+  \label{lst:nammpp}
+\end{listing}
+
+For massively parallel processing (mpp), a domain decomposition method is used.
+The basic idea of the method is to split the large computation domain of a numerical experiment into several smaller domains and
+solve the set of equations by addressing independent local problems.
+Each processor has its own local memory and computes the model equation over a subdomain of the whole model domain.
+The subdomain boundary conditions are specified through communications between processors which are organized by
+explicit statements (message passing method).
+The present implementation is largely inspired by Guyon's work [Guyon 1995].
+
+The parallelization strategy is defined by the physical characteristics of the ocean model.
+Second order finite difference schemes lead to local discrete operators that
+depend at the very most on one neighbouring point.
+The only non-local computations concern the vertical physics
+(implicit diffusion, turbulent closure scheme, ...).
+Therefore, a pencil strategy is used for the data sub-structuration:
+the 3D initial domain is laid out on local processor memories following a 2D horizontal topological splitting.
+Each sub-domain computes its own surface and bottom boundary conditions and
+has a side wall overlapping interface which defines the lateral boundary conditions for
+computations in the inner sub-domain.
+The overlapping area consists of the two rows at each edge of the sub-domain.
+After a computation, a communication phase starts:
+each processor sends to its neighbouring processors the update values of the points corresponding to
+the interior overlapping area to its neighbouring sub-domain (\ie\ the innermost of the two overlapping rows).
+Communications are first done according to the east-west direction and next according to the north-south direction.
+There is no specific communications for the corners.
+The communication is done through the Message Passing Interface (MPI) and requires \key{mpp\_mpi}.
+Use also \key{mpi2} if MPI3 is not available on your computer.
+The data exchanges between processors are required at the very place where
+lateral domain boundary conditions are set in the mono-domain computation:
+the \rou{lbc\_lnk} routine (found in \mdl{lbclnk} module) which manages such conditions is interfaced with
+routines found in \mdl{lib\_mpp} module.
+The output file \textit{communication\_report.txt} provides the list of which routines do how
+many communications during 1 time step of the model.\\
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_mpp}
+  \caption{Positioning of a sub-domain when massively parallel processing is used}
+  \label{fig:LBC_mpp}
+\end{figure}
+
+In \NEMO, the splitting is regular and arithmetic.
+The total number of subdomains corresponds to the number of MPI processes allocated to \NEMO\ when the model is launched
+(\ie\ mpirun -np x ./nemo will automatically give x subdomains).
+The i-axis is divided by \np{jpni}{jpni} and the j-axis by \np{jpnj}{jpnj}.
+These parameters are defined in \nam{mpp}{mpp} namelist.
+If \np{jpni}{jpni} and \np{jpnj}{jpnj} are < 1, they will be automatically redefined in the code to give the best domain decomposition
+(see bellow).
+
+Each processor is independent and without message passing or synchronous process, programs run alone and access just its own local memory.
+For this reason,
+the main model dimensions are now the local dimensions of the subdomain (pencil) that are named \jp{jpi}, \jp{jpj}, \jp{jpk}.
+These dimensions include the internal domain and the overlapping rows.
+The number of rows to exchange (known as the halo) is usually set to one (nn\_hls=1, in \mdl{par\_oce},
+and must be kept to one until further notice).
+The whole domain dimensions are named \jp{jpiglo}, \jp{jpjglo} and \jp{jpk}.
+The relationship between the whole domain and a sub-domain is:
+\begin{gather*}
+  jpi = ( jpiglo-2\times nn\_hls + (jpni-1) ) / jpni + 2\times nn\_hls \\
+  jpj = ( jpjglo-2\times nn\_hls + (jpnj-1) ) / jpnj + 2\times nn\_hls
+\end{gather*}
+
+One also defines variables nldi and nlei which correspond to the internal domain bounds, and the variables nimpp and njmpp which are the position of the (1,1) grid-point in the global domain (\autoref{fig:LBC_mpp}). Note that since the version 4, there is no more extra-halo area as defined in \autoref{fig:LBC_mpp} so \jp{jpi} is now always equal to nlci and \jp{jpj} equal to nlcj.
+
+An element of $T_{l}$, a local array (subdomain) corresponds to an element of $T_{g}$,
+a global array (whole domain) by the relationship:
+\[
+  % \label{eq:LBC_nimpp}
+  T_{g} (i+nimpp-1,j+njmpp-1,k) = T_{l} (i,j,k),
+\]
+with $1 \leq i \leq jpi$, $1  \leq j \leq jpj $ , and  $1  \leq k \leq jpk$.
+
+The 1-d arrays $mig(1:\jp{jpi})$ and $mjg(1:\jp{jpj})$, defined in \rou{dom\_glo} routine (\mdl{domain} module), should be used to get global domain indices from local domain indices. The 1-d arrays, $mi0(1:\jp{jpiglo})$, $mi1(1:\jp{jpiglo})$ and $mj0(1:\jp{jpjglo})$, $mj1(1:\jp{jpjglo})$ have the reverse purpose and should be used to define loop indices expressed in global domain indices (see examples in \mdl{dtastd} module).\\
+
+The \NEMO\ model computes equation terms with the help of mask arrays (0 on land points and 1 on sea points). It is therefore possible that an MPI subdomain contains only land points. To save ressources, we try to supress from the computational domain as much land subdomains as possible. For example if $N_{mpi}$ processes are allocated to NEMO, the domain decomposition will be given by the following equation:
+\[
+  N_{mpi} = jpni \times jpnj - N_{land} + N_{useless}
+\]
+$N_{land}$ is the total number of land subdomains in the domain decomposition defined by \np{jpni}{jpni} and \np{jpnj}{jpnj}. $N_{useless}$ is the number of land subdomains that are kept in the compuational domain in order to make sure that $N_{mpi}$ MPI processes are indeed allocated to a given subdomain. The values of $N_{mpi}$, \np{jpni}{jpni}, \np{jpnj}{jpnj},  $N_{land}$ and $N_{useless}$ are printed in the output file \texttt{ocean.output}. $N_{useless}$ must, of course, be as small as possible to limit the waste of ressources. A warning is issued in  \texttt{ocean.output} if $N_{useless}$ is not zero. Note that non-zero value of $N_{useless}$ is uselly required when using AGRIF as, up to now, the parent grid and each of the child grids must use all the $N_{mpi}$ processes.
+
+If the domain decomposition is automatically defined (when \np{jpni}{jpni} and \np{jpnj}{jpnj} are < 1), the decomposition chosen by the model will minimise the sub-domain size (defined as $max_{all domains}(jpi \times jpj)$) and maximize the number of eliminated land subdomains. This means that no other domain decomposition (a set of \np{jpni}{jpni} and \np{jpnj}{jpnj} values) will use less processes than $(jpni  \times  jpnj - N_{land})$ and get a smaller subdomain size.
+In order to specify $N_{mpi}$ properly (minimize $N_{useless}$), you must run the model once with \np{ln_list}{ln\_list} activated. In this case, the model will start the initialisation phase, print the list of optimum decompositions ($N_{mpi}$, \np{jpni}{jpni} and \np{jpnj}{jpnj}) in \texttt{ocean.output} and directly abort. The maximum value of $N_{mpi}$ tested in this list is given by $max(N_{MPI\_tasks}, jpni \times jpnj)$. For example, run the model on 40 nodes with ln\_list activated and $jpni = 10000$ and $jpnj = 1$, will print the list of optimum domains decomposition from 1 to about 10000.
+
+Processors are numbered from 0 to $N_{mpi} - 1$. Subdomains containning some ocean points are numbered first from 0 to $jpni * jpnj - N_{land} -1$. The remaining $N_{useless}$ land subdomains are numbered next, which means that, for a given (\np{jpni}{jpni}, \np{jpnj}{jpnj}), the numbers attributed to he ocean subdomains do not vary with $N_{useless}$.
+
+When land processors are eliminated, the value corresponding to these locations in the model output files is undefined. \np{ln_mskland}{ln\_mskland} must be activated in order avoid Not a Number values in output files. Note that it is better to not eliminate land processors when creating a meshmask file (\ie\ when setting a non-zero value to \np{nn_msh}{nn\_msh}).
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_mppini2}
+  \caption[Atlantic domain defined for the CLIPPER projet]{
+    Example of Atlantic domain defined for the CLIPPER projet.
+    Initial grid is composed of 773 x 1236 horizontal points.
+    (a) the domain is split onto 9 $times$ 20 subdomains (jpni=9, jpnj=20).
+    52 subdomains are land areas.
+    (b) 52 subdomains are eliminated (white rectangles) and
+    the resulting number of processors really used during the computation is jpnij=128.}
+  \label{fig:LBC_mppini2}
+\end{figure}
+
+%% =================================================================================================
+\section{Unstructured open boundary conditions (BDY)}
+\label{sec:LBC_bdy}
+
+\begin{listing}
+  \nlst{nambdy}
+  \caption{\forcode{&nambdy}}
+  \label{lst:nambdy}
+\end{listing}
+
+\begin{listing}
+  \nlst{nambdy_dta}
+  \caption{\forcode{&nambdy_dta}}
+  \label{lst:nambdy_dta}
+\end{listing}
+
+Options are defined through the \nam{bdy}{bdy} and \nam{bdy_dta}{bdy\_dta} namelist variables.
+The BDY module is the core implementation of open boundary conditions for regional configurations on
+ocean temperature, salinity, barotropic-baroclinic velocities, ice-snow concentration, thicknesses, temperatures, salinity and melt ponds concentration and thickness.
+
+The BDY module was modelled on the OBC module (see \NEMO\ 3.4) and shares many features and
+a similar coding structure \citep{chanut_rpt05}.
+The specification of the location of the open boundary is completely flexible and
+allows any type of setup, from regular boundaries to irregular contour (it includes the possibility to set an open boundary able to follow an isobath).
+Boundary data files used with versions of \NEMO\ prior to Version 3.4 may need to be re-ordered to work with this version.
+See the section on the Input Boundary Data Files for details.
+
+%% =================================================================================================
+\subsection{Namelists}
+\label{subsec:LBC_bdy_namelist}
+
+The BDY module is activated by setting \np[=.true.]{ln_bdy}{ln\_bdy} .
+It is possible to define more than one boundary ``set'' and apply different boundary conditions to each set.
+The number of boundary sets is defined by \np{nb_bdy}{nb\_bdy}.
+Each boundary set can be either defined as a series of straight line segments directly in the namelist
+(\np[=.false.]{ln_coords_file}{ln\_coords\_file}, and a namelist block \nam{bdy_index}{bdy\_index} must be included for each set) or read in from a file (\np[=.true.]{ln_coords_file}{ln\_coords\_file}, and a ``\ifile{coordinates.bdy}'' file must be provided).
+The coordinates.bdy file is analagous to the usual \NEMO\ ``\ifile{coordinates}'' file.
+In the example above, there are two boundary sets, the first of which is defined via a file and
+the second is defined in the namelist.
+For more details of the definition of the boundary geometry see section \autoref{subsec:LBC_bdy_geometry}.
+
+For each boundary set a boundary condition has to be chosen for the barotropic solution
+(``u2d'':sea-surface height and barotropic velocities), for the baroclinic velocities (``u3d''),
+for the active tracers \footnote{The BDY module does not deal with passive tracers at this version} (``tra''), and for sea-ice (``ice'').
+For each set of variables one has to choose an algorithm and the boundary data (set resp. by \np{cn_tra}{cn\_tra} and \np{nn_tra_dta}{nn\_tra\_dta} for tracers).\\
+
+The choice of algorithm is currently as follows:
+
+\begin{description}
+\item [\forcode{'none'}:] No boundary condition applied.
+  So the solution will ``see'' the land points around the edge of the edge of the domain.
+\item [\forcode{'specified'}:] Specified boundary condition applied (only available for baroclinic velocity and tracer variables).
+\item [\forcode{'neumann'}:] Value at the boundary are duplicated (No gradient). Only available for baroclinic velocity and tracer variables.
+\item [\forcode{'frs'}:] Flow Relaxation Scheme (FRS) available for all variables.
+\item [\forcode{'Orlanski'}:] Orlanski radiation scheme (fully oblique) for barotropic, baroclinic and tracer variables.
+\item [\forcode{'Orlanski_npo'}:] Orlanski radiation scheme for barotropic, baroclinic and tracer variables.
+\item [\forcode{'flather'}:] Flather radiation scheme for the barotropic variables only.
+\end{description}
+
+The boundary data is either set to initial conditions
+(\np[=0]{nn_tra_dta}{nn\_tra\_dta}) or forced with external data from a file (\np[=1]{nn_tra_dta}{nn\_tra\_dta}).
+In case the 3d velocity data contain the total velocity (ie, baroclinic and barotropic velocity),
+the bdy code can derived baroclinic and barotropic velocities by setting \np[=.true.]{ln_full_vel}{ln\_full\_vel}
+For the barotropic solution there is also the option to use tidal harmonic forcing either by
+itself (\np[=2]{nn_dyn2d_dta}{nn\_dyn2d\_dta}) or in addition to other external data (\np[=3]{nn_dyn2d_dta}{nn\_dyn2d\_dta}).\\
+If not set to initial conditions, sea-ice salinity, temperatures and melt ponds data at the boundary can either be read in a file or defined as constant (by \np{rn_ice_sal}{rn\_ice\_sal}, \np{rn_ice_tem}{rn\_ice\_tem}, \np{rn_ice_apnd}{rn\_ice\_apnd}, \np{rn_ice_hpnd}{rn\_ice\_hpnd}). Ice age is constant and defined by \np{rn_ice_age}{rn\_ice\_age}.
+
+If external boundary data is required then the \nam{bdy_dta}{bdy\_dta} namelist must be defined.
+One \nam{bdy_dta}{bdy\_dta} namelist is required for each boundary set, adopting the same order of indexes in which the boundary sets are defined in nambdy.
+In the example given, two boundary sets have been defined. The first one is reading data file in the \nam{bdy_dta}{bdy\_dta} namelist shown above
+and the second one is using data from intial condition (no namelist block needed).
+The boundary data is read in using the fldread module,
+so the \nam{bdy_dta}{bdy\_dta} namelist is in the format required for fldread.
+For each required variable, the filename, the frequency of the files and
+the frequency of the data in the files are given.
+Also whether or not time-interpolation is required and whether the data is climatological (time-cyclic) data.
+For sea-ice salinity, temperatures and melt ponds, reading the files are skipped and constant values are used if filenames are defined as {'NOT USED'}.\\
+
+There is currently an option to vertically interpolate the open boundary data onto the native grid at run-time.
+If \np{nn_bdy_jpk}{nn\_bdy\_jpk}$<-1$, it is assumed that the lateral boundary data are already on the native grid.
+However, if \np{nn_bdy_jpk}{nn\_bdy\_jpk} is set to the number of vertical levels present in the boundary data,
+a bilinear interpolation onto the native grid will be triggered at runtime.
+For this to be successful the additional variables: $gdept$, $gdepu$, $gdepv$, $e3t$, $e3u$ and $e3v$, are required to be present in the lateral boundary files.
+These correspond to the depths and scale factors of the input data,
+the latter used to make any adjustment to the velocity fields due to differences in the total water depths between the two vertical grids.\\
+
+In the example of given namelists, two boundary sets are defined.
+The first set is defined via a file and applies FRS conditions to temperature and salinity and
+Flather conditions to the barotropic variables. No condition specified for the baroclinic velocity and sea-ice.
+External data is provided in daily files (from a large-scale model).
+Tidal harmonic forcing is also used.
+The second set is defined in a namelist.
+FRS conditions are applied on temperature and salinity and climatological data is read from initial condition files.
+
+%% =================================================================================================
+\subsection{Flow relaxation scheme}
+\label{subsec:LBC_bdy_FRS_scheme}
+
+The Flow Relaxation Scheme (FRS) \citep{davies_QJRMS76,engedahl_T95},
+applies a simple relaxation of the model fields to externally-specified values over
+a zone next to the edge of the model domain.
+Given a model prognostic variable $\Phi$
+\[
+  % \label{eq:LBC_bdy_frs1}
+  \Phi(d) = \alpha(d)\Phi_{e}(d) + (1-\alpha(d))\Phi_{m}(d)\;\;\;\;\; d=1,N
+\]
+where $\Phi_{m}$ is the model solution and $\Phi_{e}$ is the specified external field,
+$d$ gives the discrete distance from the model boundary and
+$\alpha$ is a parameter that varies from $1$ at $d=1$ to a small value at $d=N$.
+It can be shown that this scheme is equivalent to adding a relaxation term to
+the prognostic equation for $\Phi$ of the form:
+\[
+  % \label{eq:LBC_bdy_frs2}
+  -\frac{1}{\tau}\left(\Phi - \Phi_{e}\right)
+\]
+where the relaxation time scale $\tau$ is given by a function of $\alpha$ and the model time step $\Delta t$:
+\[
+  % \label{eq:LBC_bdy_frs3}
+  \tau = \frac{1-\alpha}{\alpha}  \,\rdt
+\]
+Thus the model solution is completely prescribed by the external conditions at the edge of the model domain and
+is relaxed towards the external conditions over the rest of the FRS zone.
+The application of a relaxation zone helps to prevent spurious reflection of
+outgoing signals from the model boundary.
+
+The function $\alpha$ is specified as a $tanh$ function:
+\[
+  % \label{eq:LBC_bdy_frs4}
+  \alpha(d) = 1 - \tanh\left(\frac{d-1}{2}\right),       \quad d=1,N
+\]
+The width of the FRS zone is specified in the namelist as \np{nn_rimwidth}{nn\_rimwidth}.
+This is typically set to a value between 8 and 10.
+
+%% =================================================================================================
+\subsection{Flather radiation scheme}
+\label{subsec:LBC_bdy_flather_scheme}
+
+The \citet{flather_JPO94} scheme is a radiation condition on the normal,
+depth-mean transport across the open boundary.
+It takes the form
+\begin{equation}
+  \label{eq:LBC_bdy_fla1}
+  U = U_{e} + \frac{c}{h}\left(\eta - \eta_{e}\right),
+\end{equation}
+where $U$ is the depth-mean velocity normal to the boundary and $\eta$ is the sea surface height,
+both from the model.
+The subscript $e$ indicates the same fields from external sources.
+The speed of external gravity waves is given by $c = \sqrt{gh}$, and $h$ is the depth of the water column.
+The depth-mean normal velocity along the edge of the model domain is set equal to
+the external depth-mean normal velocity,
+plus a correction term that allows gravity waves generated internally to exit the model boundary.
+Note that the sea-surface height gradient in \autoref{eq:LBC_bdy_fla1} is a spatial gradient across the model boundary,
+so that $\eta_{e}$ is defined on the $T$ points with $nbr=1$ and $\eta$ is defined on the $T$ points with $nbr=2$.
+$U$ and $U_{e}$ are defined on the $U$ or $V$ points with $nbr=1$, \ie\ between the two $T$ grid points.
+
+%% =================================================================================================
+\subsection{Orlanski radiation scheme}
+\label{subsec:LBC_bdy_orlanski_scheme}
+
+The Orlanski scheme is based on the algorithm described by \citep{marchesiello.mcwilliams.ea_OM01}, hereafter MMS.
+
+The adaptive Orlanski condition solves a wave plus relaxation equation at the boundary:
+\begin{equation}
+  \label{eq:LBC_wave_continuous}
+  \frac{\partial\phi}{\partial t} + c_x \frac{\partial\phi}{\partial x} + c_y \frac{\partial\phi}{\partial y} =
+  -\frac{1}{\tau}(\phi - \phi^{ext})
+\end{equation}
+
+where $\phi$ is the model field, $x$ and $y$ refer to the normal and tangential directions to the boundary respectively, and the phase
+velocities are diagnosed from the model fields as:
+
+\begin{equation}
+  \label{eq:LBC_cx}
+  c_x = -\frac{\partial\phi}{\partial t}\frac{\partial\phi / \partial x}{(\partial\phi /\partial x)^2 + (\partial\phi /\partial y)^2}
+\end{equation}
+\begin{equation}
+  \label{eq:LBC_cy}
+  c_y = -\frac{\partial\phi}{\partial t}\frac{\partial\phi / \partial y}{(\partial\phi /\partial x)^2 + (\partial\phi /\partial y)^2}
+\end{equation}
+
+(As noted by MMS, this is a circular diagnosis of the phase speeds which only makes sense on a discrete grid).
+Equation (\autoref{eq:LBC_wave_continuous}) is defined adaptively depending on the sign of the phase velocity normal to the boundary $c_x$.
+For $c_x$ outward, we have
+
+\begin{equation}
+\tau = \tau_{out}
+\end{equation}
+
+For $c_x$ inward, the radiation equation is not applied:
+
+\begin{equation}
+  \label{eq:LBC_tau_in}
+  \tau = \tau_{in}\,\,\,;\,\,\, c_x = c_y = 0
+\end{equation}
+
+Generally the relaxation time scale at inward propagation points (\np{rn_time_dmp}{rn\_time\_dmp}) is set much shorter than the time scale at outward propagation
+points (\np{rn_time_dmp_out}{rn\_time\_dmp\_out}) so that the solution is constrained more strongly by the external data at inward propagation points.
+See \autoref{subsec:LBC_bdy_relaxation} for detailed on the spatial shape of the scaling.\\
+The ``normal propagation of oblique radiation'' or NPO approximation (called \forcode{'orlanski_npo'}) involves assuming
+that $c_y$ is zero in equation (\autoref{eq:LBC_wave_continuous}), but including
+this term in the denominator of equation (\autoref{eq:LBC_cx}). Both versions of the scheme are options in BDY. Equations
+(\autoref{eq:LBC_wave_continuous}) - (\autoref{eq:LBC_tau_in}) correspond to equations (13) - (15) and (2) - (3) in MMS.\\
+
+%% =================================================================================================
+\subsection{Relaxation at the boundary}
+\label{subsec:LBC_bdy_relaxation}
+
+In addition to a specific boundary condition specified as \np{cn_tra}{cn\_tra} and \np{cn_dyn3d}{cn\_dyn3d}, relaxation on baroclinic velocities and tracers variables are available.
+It is control by the namelist parameter \np{ln_tra_dmp}{ln\_tra\_dmp} and \np{ln_dyn3d_dmp}{ln\_dyn3d\_dmp} for each boundary set.
+
+The relaxation time scale value (\np{rn_time_dmp}{rn\_time\_dmp} and \np{rn_time_dmp_out}{rn\_time\_dmp\_out}, $\tau$) are defined at the boundaries itself.
+This time scale ($\alpha$) is weighted by the distance ($d$) from the boundary over \np{nn_rimwidth}{nn\_rimwidth} cells ($N$):
+
+\[
+  \alpha = \frac{1}{\tau}(\frac{N+1-d}{N})^2,       \quad d=1,N
+\]
+
+The same scaling is applied in the Orlanski damping.
+
+%% =================================================================================================
+\subsection{Boundary geometry}
+\label{subsec:LBC_bdy_geometry}
+
+Each open boundary set is defined as a list of points.
+The information is stored in the arrays $nbi$, $nbj$, and $nbr$ in the $idx\_bdy$ structure.
+The $nbi$ and $nbj$ arrays define the local $(i,j)$ indexes of each point in the boundary zone and
+the $nbr$ array defines the discrete distance from the boundary: $nbr=1$ means that
+the boundary point is next to the edge of the model domain, while $nbr>1$ means that
+the boundary point is increasingly further away from the edge of the model domain.
+A set of $nbi$, $nbj$, and $nbr$ arrays is defined for each of the $T$, $U$ and $V$ grids.
+\autoref{fig:LBC_bdy_geom} shows an example of an irregular boundary.
+
+The boundary geometry for each set may be defined in a namelist nambdy\_index or
+by reading in a ``\ifile{coordinates.bdy}'' file.
+The nambdy\_index namelist defines a series of straight-line segments for north, east, south and west boundaries.
+One nambdy\_index namelist block is needed for each boundary condition defined by indexes.
+For the northern boundary, \texttt{nbdysegn} gives the number of segments,
+\jp{jpjnob} gives the $j$ index for each segment and \jp{jpindt} and
+\jp{jpinft} give the start and end $i$ indices for each segment with similar for the other boundaries.
+These segments define a list of $T$ grid points along the outermost row of the boundary ($nbr\,=\, 1$).
+The code deduces the $U$ and $V$ points and also the points for $nbr\,>\, 1$ if \np[>1]{nn_rimwidth}{nn\_rimwidth}.
+
+The boundary geometry may also be defined from a ``\ifile{coordinates.bdy}'' file.
+\autoref{fig:LBC_nc_header} gives an example of the header information from such a file, based on the description of geometrical setup given above.
+The file should contain the index arrays for each of the $T$, $U$ and $V$ grids.
+The arrays must be in order of increasing $nbr$.
+Note that the $nbi$, $nbj$ values in the file are global values and are converted to local values in the code.
+Typically this file will be used to generate external boundary data via interpolation and so
+will also contain the latitudes and longitudes of each point as shown.
+However, this is not necessary to run the model.
+
+For some choices of irregular boundary the model domain may contain areas of ocean which
+are not part of the computational domain.
+For example, if an open boundary is defined along an isobath, say at the shelf break,
+then the areas of ocean outside of this boundary will need to be masked out.
+This can be done by reading a mask file defined as \np{cn_mask_file}{cn\_mask\_file} in the nam\_bdy namelist.
+Only one mask file is used even if multiple boundary sets are defined.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_bdy_geom}
+  \caption[Geometry of unstructured open boundary]{Example of geometry of unstructured open boundary}
+  \label{fig:LBC_bdy_geom}
+\end{figure}
+
+%% =================================================================================================
+\subsection{Input boundary data files}
+\label{subsec:LBC_bdy_data}
+
+The data files contain the data arrays in the order in which the points are defined in the $nbi$ and $nbj$ arrays.
+The data arrays are dimensioned on:
+a time dimension;
+$xb$ which is the index of the boundary data point in the horizontal;
+and $yb$ which is a degenerate dimension of 1 to enable the file to be read by the standard \NEMO\ I/O routines.
+The 3D fields also have a depth dimension.
+
+From Version 3.4 there are new restrictions on the order in which the boundary points are defined
+(and therefore restrictions on the order of the data in the file).
+In particular:
+
+\begin{enumerate}
+\item The data points must be in order of increasing $nbr$,
+  ie. all the $nbr=1$ points, then all the $nbr=2$ points etc.
+\item All the data for a particular boundary set must be in the same order.
+  (Prior to 3.4 it was possible to define barotropic data in a different order to
+  the data for tracers and baroclinic velocities).
+\end{enumerate}
+
+These restrictions mean that data files used with versions of the
+model prior to Version 3.4 may not work with Version 3.4 onwards.
+A \fortran\ utility {\itshape bdy\_reorder} exists in the TOOLS directory which
+will re-order the data in old BDY data files.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LBC_nc_header}
+  \caption[Header for a \protect\ifile{coordinates.bdy} file]{
+    Example of the header for a \protect\ifile{coordinates.bdy} file}
+  \label{fig:LBC_nc_header}
+\end{figure}
+
+%% =================================================================================================
+\subsection{Volume correction}
+\label{subsec:LBC_bdy_vol_corr}
+
+There is an option to force the total volume in the regional model to be constant.
+This is controlled  by the \np{ln_vol}{ln\_vol} parameter in the namelist.
+A value of \np[=.false.]{ln_vol}{ln\_vol} indicates that this option is not used.
+Two options to control the volume are available (\np{nn_volctl}{nn\_volctl}).
+If \np[=0]{nn_volctl}{nn\_volctl} then a correction is applied to the normal barotropic velocities around the boundary at
+each timestep to ensure that the integrated volume flow through the boundary is zero.
+If \np[=1]{nn_volctl}{nn\_volctl} then the calculation of the volume change on
+the timestep includes the change due to the freshwater flux across the surface and
+the correction velocity corrects for this as well.
+
+If more than one boundary set is used then volume correction is
+applied to all boundaries at once.
+
+%% =================================================================================================
+\subsection{Tidal harmonic forcing}
+\label{subsec:LBC_bdy_tides}
+
+\begin{listing}
+  \nlst{nambdy_tide}
+  \caption{\forcode{&nambdy_tide}}
+  \label{lst:nambdy_tide}
+\end{listing}
+
+Tidal forcing at open boundaries requires the activation of surface
+tides (i.e., in \nam{_tide}{\_tide}, \np{ln_tide}{ln\_tide} needs to be set to
+\forcode{.true.} and the required constituents need to be activated by
+including their names in the \np{clname}{clname} array; see
+\autoref{sec:SBC_tide}). Specific options related to the reading in of
+the complex harmonic amplitudes of elevation (SSH) and barotropic
+velocity (u,v) at open boundaries are defined through the
+\nam{bdy_tide}{bdy\_tide} namelist parameters.\\
+
+The tidal harmonic data at open boundaries can be specified in two
+different ways, either on a two-dimensional grid covering the entire
+model domain or along open boundary segments; these two variants can
+be selected by setting \np{ln_bdytide_2ddta }{ln\_bdytide\_2ddta } to \forcode{.true.} or
+\forcode{.false.}, respectively. In either case, the real and
+imaginary parts of SSH and the two barotropic velocity components for
+each activated tidal constituent \textit{tcname} have to be provided
+separately: when two-dimensional data is used, variables
+\textit{tcname\_z1} and \textit{tcname\_z2} for real and imaginary SSH,
+respectively, are expected in input file \np{filtide}{filtide} with suffix
+\ifile{\_grid\_T}, variables \textit{tcname\_u1} and
+\textit{tcname\_u2} for real and imaginary u, respectively, are
+expected in input file \np{filtide}{filtide} with suffix \ifile{\_grid\_U}, and
+\textit{tcname\_v1} and \textit{tcname\_v2} for real and imaginary v,
+respectively, are expected in input file \np{filtide}{filtide} with suffix
+\ifile{\_grid\_V}; when data along open boundary segments is used,
+variables \textit{z1} and \textit{z2} (real and imaginary part of SSH)
+are expected to be available from file \np{filtide}{filtide} with suffix
+\ifile{tcname\_grid\_T}, variables \textit{u1} and \textit{u2} (real
+and imaginary part of u) are expected to be available from file
+\np{filtide}{filtide} with suffix \ifile{tcname\_grid\_U}, and variables
+\textit{v1} and \textit{v2} (real and imaginary part of v) are
+expected to be available from file \np{filtide}{filtide} with suffix
+\ifile{tcname\_grid\_V}. If \np{ln_bdytide_conj}{ln\_bdytide\_conj} is set to
+\forcode{.true.}, the data is expected to be in complex conjugate
+form.
+
+Note that the barotropic velocity components are assumed to be defined
+on the native model grid and should be rotated accordingly when they
+are converted from their definition on a different source grid. To do
+so, the u, v amplitudes and phases can be converted into tidal
+ellipses, the grid rotation added to the ellipse inclination, and then
+converted back (care should be taken regarding conventions of the
+direction of rotation). %, e.g. anticlockwise or clockwise.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LDF.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LDF.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_LDF.tex	(revision 14097)
@@ -0,0 +1,548 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Lateral Ocean Physics (LDF)}
+\label{chap:LDF}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+The lateral physics terms in the momentum and tracer equations have been described in \autoref{eq:MB_zdf} and
+their discrete formulation in \autoref{sec:TRA_ldf} and \autoref{sec:DYN_ldf}).
+In this section we further discuss each lateral physics option.
+Choosing one lateral physics scheme means for the user defining,
+(1) the type of operator used (laplacian or bilaplacian operators, or no lateral mixing term);
+(2) the direction along which the lateral diffusive fluxes are evaluated
+(model level, geopotential or isopycnal surfaces); and
+(3) the space and time variations of the eddy coefficients.
+These three aspects of the lateral diffusion are set through namelist parameters
+(see the \nam{tra_ldf}{tra\_ldf} and \nam{dyn_ldf}{dyn\_ldf} below).
+Note that this chapter describes the standard implementation of iso-neutral tracer mixing.
+Griffies's implementation, which is used if \np[=.true.]{ln_traldf_triad}{ln\_traldf\_triad},
+is described in \autoref{apdx:TRIADS}
+
+%% =================================================================================================
+\section[Lateral mixing operators]{Lateral mixing operators}
+\label{sec:LDF_op}
+We remind here the different lateral mixing operators that can be used. Further details can be found in \autoref{subsec:TRA_ldf_op} and  \autoref{sec:DYN_ldf}.
+
+%% =================================================================================================
+\subsection[No lateral mixing (\forcode{ln_traldf_OFF} \& \forcode{ln_dynldf_OFF})]{No lateral mixing (\protect\np{ln_traldf_OFF}{ln\_traldf\_OFF} \& \protect\np{ln_dynldf_OFF}{ln\_dynldf\_OFF})}
+
+It is possible to run without explicit lateral diffusion on tracers (\protect\np[=.true.]{ln_traldf_OFF}{ln\_traldf\_OFF}) and/or
+momentum (\protect\np[=.true.]{ln_dynldf_OFF}{ln\_dynldf\_OFF}). The latter option is even recommended if using the
+UBS advection scheme on momentum (\np[=.true.]{ln_dynadv_ubs}{ln\_dynadv\_ubs},
+see \autoref{subsec:DYN_adv_ubs}) and can be useful for testing purposes.
+
+%% =================================================================================================
+\subsection[Laplacian mixing (\forcode{ln_traldf_lap} \& \forcode{ln_dynldf_lap})]{Laplacian mixing (\protect\np{ln_traldf_lap}{ln\_traldf\_lap} \& \protect\np{ln_dynldf_lap}{ln\_dynldf\_lap})}
+Setting \protect\np[=.true.]{ln_traldf_lap}{ln\_traldf\_lap} and/or \protect\np[=.true.]{ln_dynldf_lap}{ln\_dynldf\_lap} enables
+a second order diffusion on tracers and momentum respectively. Note that in \NEMO\ 4, one can not combine
+Laplacian and Bilaplacian operators for the same variable.
+
+%% =================================================================================================
+\subsection[Bilaplacian mixing (\forcode{ln_traldf_blp} \& \forcode{ln_dynldf_blp})]{Bilaplacian mixing (\protect\np{ln_traldf_blp}{ln\_traldf\_blp} \& \protect\np{ln_dynldf_blp}{ln\_dynldf\_blp})}
+Setting \protect\np[=.true.]{ln_traldf_blp}{ln\_traldf\_blp} and/or \protect\np[=.true.]{ln_dynldf_blp}{ln\_dynldf\_blp} enables
+a fourth order diffusion on tracers and momentum respectively. It is implemented by calling the above Laplacian operator twice.
+We stress again that from \NEMO\ 4, the simultaneous use Laplacian and Bilaplacian operators is not allowed.
+
+%% =================================================================================================
+\section[Direction of lateral mixing (\textit{ldfslp.F90})]{Direction of lateral mixing (\protect\mdl{ldfslp})}
+\label{sec:LDF_slp}
+
+\cmtgm{
+  we should emphasize here that the implementation is a rather old one.
+  Better work can be achieved by using \citet{griffies.gnanadesikan.ea_JPO98, griffies_bk04} iso-neutral scheme.
+}
+
+A direction for lateral mixing has to be defined when the desired operator does not act along the model levels.
+This occurs when $(a)$ horizontal mixing is required on tracer or momentum
+(\np{ln_traldf_hor}{ln\_traldf\_hor} or \np{ln_dynldf_hor}{ln\_dynldf\_hor}) in $s$- or mixed $s$-$z$- coordinates,
+and $(b)$ isoneutral mixing is required whatever the vertical coordinate is.
+This direction of mixing is defined by its slopes in the \textbf{i}- and \textbf{j}-directions at the face of
+the cell of the quantity to be diffused.
+For a tracer, this leads to the following four slopes:
+$r_{1u}$, $r_{1w}$, $r_{2v}$, $r_{2w}$ (see \autoref{eq:TRA_ldf_iso}),
+while for momentum the slopes are  $r_{1t}$, $r_{1uw}$, $r_{2f}$, $r_{2uw}$ for $u$ and
+$r_{1f}$, $r_{1vw}$, $r_{2t}$, $r_{2vw}$ for $v$.
+
+\cmtgm{Add here afigure of the slope in i-direction}
+
+%% =================================================================================================
+\subsection{Slopes for tracer geopotential mixing in the $s$-coordinate}
+
+In $s$-coordinates, geopotential mixing (\ie\ horizontal mixing) $r_1$ and $r_2$ are the slopes between
+the geopotential and computational surfaces.
+Their discrete formulation is found by locally solving \autoref{eq:TRA_ldf_iso} when
+the diffusive fluxes in the three directions are set to zero and $T$ is assumed to be horizontally uniform,
+\ie\ a linear function of $z_T$, the depth of a $T$-point.
+\cmtgm{Steven : My version is obviously wrong since
+  I'm left with an arbitrary constant which is the local vertical temperature gradient}
+
+\begin{equation}
+  \label{eq:LDF_slp_geo}
+  \begin{aligned}
+    r_{1u} &= \frac{e_{3u}}{ \left( e_{1u}\;\overline{\overline{e_{3w}}}^{\,i+1/2,\,k} \right)}
+    \;\delta_{i+1/2}[z_t]
+    &\approx \frac{1}{e_{1u}}\; \delta_{i+1/2}[z_t] \ \ \ \\
+    r_{2v} &= \frac{e_{3v}}{\left( e_{2v}\;\overline{\overline{e_{3w}}}^{\,j+1/2,\,k} \right)}
+    \;\delta_{j+1/2} [z_t]
+    &\approx \frac{1}{e_{2v}}\; \delta_{j+1/2}[z_t] \ \ \ \\
+    r_{1w} &= \frac{1}{e_{1w}}\;\overline{\overline{\delta_{i+1/2}[z_t]}}^{\,i,\,k+1/2}
+    &\approx \frac{1}{e_{1w}}\; \delta_{i+1/2}[z_{uw}]  \\
+    r_{2w} &= \frac{1}{e_{2w}}\;\overline{\overline{\delta_{j+1/2}[z_t]}}^{\,j,\,k+1/2}
+    &\approx \frac{1}{e_{2w}}\; \delta_{j+1/2}[z_{vw}]
+  \end{aligned}
+\end{equation}
+
+\cmtgm{Caution I'm not sure the simplification was a good idea!}
+
+These slopes are computed once in \rou{ldf\_slp\_init} when \np[=.true.]{ln_sco}{ln\_sco},
+and either \np[=.true.]{ln_traldf_hor}{ln\_traldf\_hor} or \np[=.true.]{ln_dynldf_hor}{ln\_dynldf\_hor}.
+
+%% =================================================================================================
+\subsection{Slopes for tracer iso-neutral mixing}
+\label{subsec:LDF_slp_iso}
+
+In iso-neutral mixing  $r_1$ and $r_2$ are the slopes between the iso-neutral and computational surfaces.
+Their formulation does not depend on the vertical coordinate used.
+Their discrete formulation is found using the fact that the diffusive fluxes of
+locally referenced potential density (\ie\ $in situ$ density) vanish.
+So, substituting $T$ by $\rho$ in \autoref{eq:TRA_ldf_iso} and setting the diffusive fluxes in
+the three directions to zero leads to the following definition for the neutral slopes:
+
+\begin{equation}
+  \label{eq:LDF_slp_iso}
+  \begin{split}
+    r_{1u} &= \frac{e_{3u}}{e_{1u}}\; \frac{\delta_{i+1/2}[\rho]}
+    {\overline{\overline{\delta_{k+1/2}[\rho]}}^{\,i+1/2,\,k}} \\
+    r_{2v} &= \frac{e_{3v}}{e_{2v}}\; \frac{\delta_{j+1/2}\left[\rho \right]}
+    {\overline{\overline{\delta_{k+1/2}[\rho]}}^{\,j+1/2,\,k}} \\
+    r_{1w} &= \frac{e_{3w}}{e_{1w}}\;
+    \frac{\overline{\overline{\delta_{i+1/2}[\rho]}}^{\,i,\,k+1/2}}
+    {\delta_{k+1/2}[\rho]} \\
+    r_{2w} &= \frac{e_{3w}}{e_{2w}}\;
+    \frac{\overline{\overline{\delta_{j+1/2}[\rho]}}^{\,j,\,k+1/2}}
+    {\delta_{k+1/2}[\rho]}
+  \end{split}
+\end{equation}
+
+\cmtgm{rewrite this as the explanation is not very clear !!!}
+%In practice, \autoref{eq:LDF_slp_iso} is of little help in evaluating the neutral surface slopes. Indeed, for an unsimplified equation of state, the density has a strong dependancy on pressure (here approximated as the depth), therefore applying \autoref{eq:LDF_slp_iso} using the $in situ$ density, $\rho$, computed at T-points leads to a flattening of slopes as the depth increases. This is due to the strong increase of the $in situ$ density with depth.
+
+%By definition, neutral surfaces are tangent to the local $in situ$ density \citep{mcdougall_JPO87}, therefore in \autoref{eq:LDF_slp_iso}, all the derivatives have to be evaluated at the same local pressure (which in decibars is approximated by the depth in meters).
+
+%In the $z$-coordinate, the derivative of the  \autoref{eq:LDF_slp_iso} numerator is evaluated at the same depth \nocite{as what?} ($T$-level, which is the same as the $u$- and $v$-levels), so  the $in situ$ density can be used for its evaluation.
+
+As the mixing is performed along neutral surfaces, the gradient of $\rho$ in \autoref{eq:LDF_slp_iso} has to
+be evaluated at the same local pressure
+(which, in decibars, is approximated by the depth in meters in the model).
+Therefore \autoref{eq:LDF_slp_iso} cannot be used as such,
+but further transformation is needed depending on the vertical coordinate used:
+
+\begin{description}
+\item [$z$-coordinate with full step:] in \autoref{eq:LDF_slp_iso} the densities appearing in the $i$ and $j$ derivatives  are taken at the same depth,
+  thus the $in situ$ density can be used.
+  This is not the case for the vertical derivatives: $\delta_{k+1/2}[\rho]$ is replaced by $-\rho N^2/g$,
+  where $N^2$ is the local Brunt-Vais\"{a}l\"{a} frequency evaluated following \citet{mcdougall_JPO87}
+  (see \autoref{subsec:TRA_bn2}).
+\item [$z$-coordinate with partial step:] this case is identical to the full step case except that at partial step level,
+  the \emph{horizontal} density gradient is evaluated as described in \autoref{sec:TRA_zpshde}.
+\item [$s$- or hybrid $s$-$z$- coordinate:] in the current release of \NEMO, iso-neutral mixing is only employed for $s$-coordinates if
+  the Griffies scheme is used (\np[=.true.]{ln_traldf_triad}{ln\_traldf\_triad};
+  see \autoref{apdx:TRIADS}).
+  In other words, iso-neutral mixing will only be accurately represented with a linear equation of state
+  (\np[=.true.]{ln_seos}{ln\_seos}).
+  In the case of a "true" equation of state, the evaluation of $i$ and $j$ derivatives in \autoref{eq:LDF_slp_iso}
+  will include a pressure dependent part, leading to the wrong evaluation of the neutral slopes.
+
+  Note: The solution for $s$-coordinate passes trough the use of different (and better) expression for
+  the constraint on iso-neutral fluxes.
+  Following \citet{griffies_bk04}, instead of specifying directly that there is a zero neutral diffusive flux of
+  locally referenced potential density, we stay in the $T$-$S$ plane and consider the balance between
+  the neutral direction diffusive fluxes of potential temperature and salinity:
+  \[
+    \alpha \ \textbf{F}(T) = \beta \ \textbf{F}(S)
+  \]
+  \cmtgm{where vector F is ....}
+
+This constraint leads to the following definition for the slopes:
+
+\[
+  % \label{eq:LDF_slp_iso2}
+  \begin{split}
+    r_{1u} &= \frac{e_{3u}}{e_{1u}}\; \frac
+    {\alpha_u \;\delta_{i+1/2}[T] - \beta_u \;\delta_{i+1/2}[S]}
+    {\alpha_u \;\overline{\overline{\delta_{k+1/2}[T]}}^{\,i+1/2,\,k}
+      -\beta_u  \;\overline{\overline{\delta_{k+1/2}[S]}}^{\,i+1/2,\,k} } \\
+    r_{2v} &= \frac{e_{3v}}{e_{2v}}\; \frac
+    {\alpha_v \;\delta_{j+1/2}[T] - \beta_v \;\delta_{j+1/2}[S]}
+    {\alpha_v \;\overline{\overline{\delta_{k+1/2}[T]}}^{\,j+1/2,\,k}
+      -\beta_v  \;\overline{\overline{\delta_{k+1/2}[S]}}^{\,j+1/2,\,k} }    \\
+    r_{1w} &= \frac{e_{3w}}{e_{1w}}\; \frac
+    {\alpha_w \;\overline{\overline{\delta_{i+1/2}[T]}}^{\,i,\,k+1/2}
+      -\beta_w  \;\overline{\overline{\delta_{i+1/2}[S]}}^{\,i,\,k+1/2} }
+    {\alpha_w \;\delta_{k+1/2}[T] - \beta_w \;\delta_{k+1/2}[S]} \\
+    r_{2w} &= \frac{e_{3w}}{e_{2w}}\; \frac
+    {\alpha_w \;\overline{\overline{\delta_{j+1/2}[T]}}^{\,j,\,k+1/2}
+      -\beta_w  \;\overline{\overline{\delta_{j+1/2}[S]}}^{\,j,\,k+1/2} }
+    {\alpha_w \;\delta_{k+1/2}[T] - \beta_w \;\delta_{k+1/2}[S]} \\
+  \end{split}
+\]
+where $\alpha$ and $\beta$, the thermal expansion and saline contraction coefficients introduced in
+\autoref{subsec:TRA_bn2}, have to be evaluated at the three velocity points.
+In order to save computation time, they should be approximated by the mean of their values at $T$-points
+(for example in the case of $\alpha$:
+$\alpha_u=\overline{\alpha_T}^{i+1/2}$,  $\alpha_v=\overline{\alpha_T}^{j+1/2}$ and
+$\alpha_w=\overline{\alpha_T}^{k+1/2}$).
+
+Note that such a formulation could be also used in the $z$-coordinate and $z$-coordinate with partial steps cases.
+\end{description}
+
+This implementation is a rather old one.
+It is similar to the one proposed by \citet{cox_OM87}, except for the background horizontal diffusion.
+Indeed, the \citet{cox_OM87} implementation of isopycnal diffusion in GFDL-type models requires
+a minimum background horizontal diffusion for numerical stability reasons.
+To overcome this problem, several techniques have been proposed in which the numerical schemes of
+the ocean model are modified \citep{weaver.eby_JPO97, griffies.gnanadesikan.ea_JPO98}.
+Griffies's scheme is now available in \NEMO\ if \np[=.true.]{ln_traldf_triad}{ln\_traldf\_triad}; see \autoref{apdx:TRIADS}.
+Here, another strategy is presented \citep{lazar_phd97}:
+a local filtering of the iso-neutral slopes (made on 9 grid-points) prevents the development of
+grid point noise generated by the iso-neutral diffusion operator (\autoref{fig:LDF_ZDF1}).
+This allows an iso-neutral diffusion scheme without additional background horizontal mixing.
+This technique can be viewed as a diffusion operator that acts along large-scale
+(2~$\Delta$x) \cmtgm{2deltax doesnt seem very large scale} iso-neutral surfaces.
+The diapycnal diffusion required for numerical stability is thus minimized and its net effect on the flow is quite small when compared to the effect of an horizontal background mixing.
+
+Nevertheless, this iso-neutral operator does not ensure that variance cannot increase,
+contrary to the \citet{griffies.gnanadesikan.ea_JPO98} operator which has that property.
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LDF_ZDF1}
+  \caption{Averaging procedure for isopycnal slope computation}
+  \label{fig:LDF_ZDF1}
+\end{figure}
+
+%There are three additional questions about the slope calculation.
+%First the expression for the rotation tensor has been obtain assuming the "small slope" approximation, so a bound has to be imposed on slopes.
+%Second, numerical stability issues also require a bound on slopes.
+%Third, the question of boundary condition specified on slopes...
+
+%from griffies: chapter 13.1....
+
+% In addition and also for numerical stability reasons \citep{cox_OM87, griffies_bk04},
+% the slopes are bounded by $1/100$ everywhere. This limit is decreasing linearly
+% to zero fom $70$ meters depth and the surface (the fact that the eddies "feel" the
+% surface motivates this flattening of isopycnals near the surface).
+
+For numerical stability reasons \citep{cox_OM87, griffies_bk04}, the slopes must also be bounded by
+the namelist scalar \np{rn_slpmax}{rn\_slpmax} (usually $1/100$) everywhere.
+This constraint is applied in a piecewise linear fashion, increasing from zero at the surface to
+$1/100$ at $70$ metres and thereafter decreasing to zero at the bottom of the ocean
+(the fact that the eddies "feel" the surface motivates this flattening of isopycnals near the surface).
+\colorbox{yellow}{The way slopes are tapered has be checked. Not sure that this is still what is actually done.}
+
+\begin{figure}[!ht]
+  \centering
+  \includegraphics[width=0.66\textwidth]{LDF_eiv_slp}
+  \caption[Vertical profile of the slope used for lateral mixing in the mixed layer]{
+    Vertical profile of the slope used for lateral mixing in the mixed layer:
+    \textit{(a)} in the real ocean the slope is the iso-neutral slope in the ocean interior,
+    which has to be adjusted at the surface boundary
+    \ie\ it must tend to zero at the surface since there is no mixing across the air-sea interface:
+    wall boundary condition).
+    Nevertheless,
+    the profile between the surface zero value and the interior iso-neutral one is unknown,
+    and especially the value at the base of the mixed layer;
+    \textit{(b)} profile of slope using a linear tapering of the slope near the surface and
+    imposing a maximum slope of 1/100;
+    \textit{(c)} profile of slope actually used in \NEMO:
+    a linear decrease of the slope from zero at the surface to
+    its ocean interior value computed just below the mixed layer.
+    Note the huge change in the slope at the base of the mixed layer between
+    \textit{(b)} and \textit{(c)}.}
+  \label{fig:LDF_eiv_slp}
+\end{figure}
+
+\colorbox{yellow}{add here a discussion about the flattening of the slopes, vs tapering the coefficient.}
+
+%% =================================================================================================
+\subsection{Slopes for momentum iso-neutral mixing}
+
+The iso-neutral diffusion operator on momentum is the same as the one used on tracers but
+applied to each component of the velocity separately
+(see \autoref{eq:DYN_ldf_iso} in section~\autoref{subsec:DYN_ldf_iso}).
+The slopes between the surface along which the diffusion operator acts and the surface of computation
+($z$- or $s$-surfaces) are defined at $T$-, $f$-, and \textit{uw}- points for the $u$-component, and $T$-, $f$- and
+\textit{vw}- points for the $v$-component.
+They are computed from the slopes used for tracer diffusion,
+\ie\ \autoref{eq:LDF_slp_geo} and \autoref{eq:LDF_slp_iso}:
+
+\[
+  % \label{eq:LDF_slp_dyn}
+  \begin{aligned}
+    &r_{1t}\ \ = \overline{r_{1u}}^{\,i}       &&&    r_{1f}\ \ &= \overline{r_{1u}}^{\,i+1/2} \\
+    &r_{2f} \ \ = \overline{r_{2v}}^{\,j+1/2} &&& 	r_{2t}\ &= \overline{r_{2v}}^{\,j} \\
+    &r_{1uw}  = \overline{r_{1w}}^{\,i+1/2} &&\ \ \text{and} \ \ &   r_{1vw}&= \overline{r_{1w}}^{\,j+1/2} \\
+    &r_{2uw}= \overline{r_{2w}}^{\,j+1/2} &&&         r_{2vw}&= \overline{r_{2w}}^{\,j+1/2}\\
+  \end{aligned}
+\]
+
+The major issue remaining is in the specification of the boundary conditions.
+The same boundary conditions are chosen as those used for lateral diffusion along model level surfaces,
+\ie\ using the shear computed along the model levels and with no additional friction at the ocean bottom
+(see \autoref{sec:LBC_coast}).
+
+%% =================================================================================================
+\section[Lateral mixing coefficient (\forcode{nn_aht_ijk_t} \& \forcode{nn_ahm_ijk_t})]{Lateral mixing coefficient (\protect\np{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+\label{sec:LDF_coef}
+
+The specification of the space variation of the coefficient is made in modules \mdl{ldftra} and \mdl{ldfdyn}.
+The way the mixing coefficients are set in the reference version can be described as follows:
+
+%% =================================================================================================
+\subsection[Mixing coefficients read from file (\forcode{=-20, -30})]{ Mixing coefficients read from file (\protect\np[=-20, -30]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=-20, -30]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+Mixing coefficients can be read from file if a particular geographical variation is needed. For example, in the ORCA2 global ocean model,
+the laplacian viscosity operator uses $A^l$~= 4.10$^4$ m$^2$/s poleward of 20$^{\circ}$ north and south and
+decreases linearly to $A^l$~= 2.10$^3$ m$^2$/s at the equator \citep{madec.delecluse.ea_JPO96, delecluse.madec_icol99}.
+Similar modified horizontal variations can be found with the Antarctic or Arctic sub-domain options of ORCA2 and ORCA05.
+The provided fields can either be 2d (\np[=-20]{nn_aht_ijk_t}{nn\_aht\_ijk\_t}, \np[=-20]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t}) or 3d (\np[=-30]{nn_aht_ijk_t}{nn\_aht\_ijk\_t},  \np[=-30]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t}). They must be given at U, V points for tracers and T, F points for momentum (see \autoref{tab:LDF_files}).
+
+\begin{table}[htb]
+  \centering
+  \begin{tabular}{|l|l|l|l|}
+    \hline
+    Namelist parameter				            & Input filename	                             & dimensions	& variable names                      \\	\hline
+    \np[=-20]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t}	    & \forcode{eddy_viscosity_2D.nc }            &     $(i,j)$	        & \forcode{ahmt_2d, ahmf_2d}  \\	\hline
+    \np[=-20]{nn_aht_ijk_t}{nn\_aht\_ijk\_t}           & \forcode{eddy_diffusivity_2D.nc }           &     $(i,j)$	        & \forcode{ahtu_2d, ahtv_2d}    \\	\hline
+    \np[=-30]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t} 	    & \forcode{eddy_viscosity_3D.nc }            &     $(i,j,k)$	        & \forcode{ahmt_3d, ahmf_3d}  \\	\hline
+    \np[=-30]{nn_aht_ijk_t}{nn\_aht\_ijk\_t}	    & \forcode{eddy_diffusivity_3D.nc }           &     $(i,j,k)$	        & \forcode{ahtu_3d, ahtv_3d}    \\	\hline
+  \end{tabular}
+  \caption{Description of expected input files if mixing coefficients are read from NetCDF files}
+  \label{tab:LDF_files}
+\end{table}
+
+%% =================================================================================================
+\subsection[Constant mixing coefficients (\forcode{=0})]{ Constant mixing coefficients (\protect\np[=0]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=0]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+If constant, mixing coefficients are set thanks to a velocity and a length scales ($U_{scl}$, $L_{scl}$) such that:
+
+\begin{equation}
+  \label{eq:LDF_constantah}
+  A_o^l = \left\{
+    \begin{aligned}
+      & \frac{1}{2} U_{scl} L_{scl}  		     & \text{for laplacian operator } \\
+      & \frac{1}{12} U_{scl} L_{scl}^3                    & \text{for bilaplacian operator }
+    \end{aligned}
+  \right.
+\end{equation}
+
+ $U_{scl}$ and $L_{scl}$ are given by the namelist parameters \np{rn_Ud}{rn\_Ud}, \np{rn_Uv}{rn\_Uv}, \np{rn_Ld}{rn\_Ld} and \np{rn_Lv}{rn\_Lv}.
+
+%% =================================================================================================
+\subsection[Vertically varying mixing coefficients (\forcode{=10})]{Vertically varying mixing coefficients (\protect\np[=10]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=10]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+In the vertically varying case, a hyperbolic variation of the lateral mixing coefficient is introduced in which
+the surface value is given by \autoref{eq:LDF_constantah}, the bottom value is 1/4 of the surface value,
+and the transition takes place around z=500~m with a width of 200~m.
+This profile is hard coded in module \mdl{ldfc1d\_c2d}, but can be easily modified by users.
+
+%% =================================================================================================
+\subsection[Mesh size dependent mixing coefficients (\forcode{=20})]{Mesh size dependent mixing coefficients (\protect\np[=20]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=20]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+In that case, the horizontal variation of the eddy coefficient depends on the local mesh size and
+the type of operator used:
+\begin{equation}
+  \label{eq:LDF_title}
+  A_l = \left\{
+    \begin{aligned}
+      & \frac{1}{2} U_{scl}  \max(e_1,e_2)  			& \text{for laplacian operator } \\
+      & \frac{1}{12} U_{scl}  \max(e_1,e_2)^{3}             & \text{for bilaplacian operator }
+    \end{aligned}
+  \right.
+\end{equation}
+where $U_{scl}$ is a user defined velocity scale (\np{rn_Ud}{rn\_Ud}, \np{rn_Uv}{rn\_Uv}).
+This variation is intended to reflect the lesser need for subgrid scale eddy mixing where
+the grid size is smaller in the domain.
+It was introduced in the context of the DYNAMO modelling project \citep{willebrand.barnier.ea_PO01}.
+Note that such a grid scale dependance of mixing coefficients significantly increases the range of stability of
+model configurations presenting large changes in grid spacing such as global ocean models.
+Indeed, in such a case, a constant mixing coefficient can lead to a blow up of the model due to
+large coefficient compare to the smallest grid size (see \autoref{sec:TD_forward_imp}),
+especially when using a bilaplacian operator.
+
+\colorbox{yellow}{CASE \np{nn_aht_ijk_t}{nn\_aht\_ijk\_t} = 21 to be added}
+
+%% =================================================================================================
+\subsection[Mesh size and depth dependent mixing coefficients (\forcode{=30})]{Mesh size and depth dependent mixing coefficients (\protect\np[=30]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=30]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+The 3D space variation of the mixing coefficient is simply the combination of the 1D and 2D cases above,
+\ie\ a hyperbolic tangent variation with depth associated with a grid size dependence of
+the magnitude of the coefficient.
+
+%% =================================================================================================
+\subsection[Velocity dependent mixing coefficients (\forcode{=31})]{Flow dependent mixing coefficients (\protect\np[=31]{nn_aht_ijk_t}{nn\_aht\_ijk\_t} \& \protect\np[=31]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+In that case, the eddy coefficient is proportional to the local velocity magnitude so that the Reynolds number $Re =  \lvert U \rvert  e / A_l$ is constant (and here hardcoded to $12$):
+\colorbox{yellow}{JC comment: The Reynolds is effectively set to 12 in the code for both operators but shouldn't it be 2 for Laplacian ?}
+
+\begin{equation}
+  \label{eq:LDF_flowah}
+  A_l = \left\{
+    \begin{aligned}
+      & \frac{1}{12} \lvert U \rvert e  			& \text{for laplacian operator } \\
+      & \frac{1}{12} \lvert U \rvert e^3 		        & \text{for bilaplacian operator }
+    \end{aligned}
+  \right.
+\end{equation}
+
+%% =================================================================================================
+\subsection[Deformation rate dependent viscosities (\forcode{nn_ahm_ijk_t=32})]{Deformation rate dependent viscosities (\protect\np[=32]{nn_ahm_ijk_t}{nn\_ahm\_ijk\_t})}
+
+This option refers to the \citep{smagorinsky_MW63} scheme which is here implemented for momentum only. Smagorinsky chose as a
+characteristic time scale $T_{smag}$ the deformation rate and for the lengthscale $L_{smag}$ the maximum wavenumber possible on the horizontal grid, e.g.:
+
+\begin{equation}
+  \label{eq:LDF_smag1}
+  \begin{split}
+    T_{smag}^{-1} & = \sqrt{\left( \partial_x u - \partial_y v\right)^2 + \left( \partial_y u + \partial_x v\right)^2  } \\
+    L_{smag} & = \frac{1}{\pi}\frac{e_1 e_2}{e_1 + e_2}
+  \end{split}
+\end{equation}
+
+Introducing a user defined constant $C$ (given in the namelist as \np{rn_csmc}{rn\_csmc}), one can deduce the mixing coefficients as follows:
+
+\begin{equation}
+  \label{eq:LDF_smag2}
+  A_{smag} = \left\{
+    \begin{aligned}
+      & C^2  T_{smag}^{-1}  L_{smag}^2			& \text{for laplacian operator } \\
+      & \frac{C^2}{8} T_{smag}^{-1} L_{smag}^4     	& \text{for bilaplacian operator }
+    \end{aligned}
+  \right.
+\end{equation}
+
+For stability reasons, upper and lower limits are applied on the resulting coefficient (see \autoref{sec:TD_forward_imp}) so that:
+\begin{equation}
+  \label{eq:LDF_smag3}
+    \begin{aligned}
+      & C_{min} \frac{1}{2}   \lvert U \rvert  e    < A_{smag} < C_{max} \frac{e^2}{   8\rdt}                 & \text{for laplacian operator } \\
+      & C_{min} \frac{1}{12} \lvert U \rvert  e^3 < A_{smag} < C_{max} \frac{e^4}{64 \rdt}                 & \text{for bilaplacian operator }
+    \end{aligned}
+\end{equation}
+
+where $C_{min}$ and $C_{max}$ are adimensional namelist parameters given by \np{rn_minfac}{rn\_minfac} and \np{rn_maxfac}{rn\_maxfac} respectively.
+
+%% =================================================================================================
+\subsection{About space and time varying mixing coefficients}
+
+The following points are relevant when the eddy coefficient varies spatially:
+
+(1) the momentum diffusion operator acting along model level surfaces is written in terms of curl and
+divergent components of the horizontal current (see \autoref{subsec:MB_ldf}).
+Although the eddy coefficient could be set to different values in these two terms,
+this option is not currently available.
+
+(2) with an horizontally varying viscosity, the quadratic integral constraints on enstrophy and on the square of
+the horizontal divergence for operators acting along model-surfaces are no longer satisfied
+(\autoref{sec:INVARIANTS_dynldf_properties}).
+
+%% =================================================================================================
+\section[Eddy induced velocity (\forcode{ln_ldfeiv})]{Eddy induced velocity (\protect\np{ln_ldfeiv}{ln\_ldfeiv})}
+
+\label{sec:LDF_eiv}
+
+\begin{listing}
+  \nlst{namtra_eiv}
+  \caption{\forcode{&namtra_eiv}}
+  \label{lst:namtra_eiv}
+\end{listing}
+
+%%gm  from Triad appendix  : to be incorporated....
+\cmtgm{
+  Values of iso-neutral diffusivity and GM coefficient are set as described in \autoref{sec:LDF_coef}.
+  If none of the keys \key{traldf\_cNd}, N=1,2,3 is set (the default), spatially constant iso-neutral $A_l$ and
+  GM diffusivity $A_e$ are directly set by \np{rn_aeih_0}{rn\_aeih\_0} and \np{rn_aeiv_0}{rn\_aeiv\_0}.
+  If 2D-varying coefficients are set with \key{traldf\_c2d} then $A_l$ is reduced in proportion with horizontal
+  scale factor according to \autoref{eq:title}
+  \footnote{
+    Except in global ORCA  $0.5^{\circ}$ runs with \key{traldf\_eiv},
+    where $A_l$ is set like $A_e$ but with a minimum vale of $100\;\mathrm{m}^2\;\mathrm{s}^{-1}$
+  }.
+  In idealised setups with \key{traldf\_c2d}, $A_e$ is reduced similarly, but if \key{traldf\_eiv} is set in
+  the global configurations with \key{traldf\_c2d}, a horizontally varying $A_e$ is instead set from
+  the Held-Larichev parameterisation
+  \footnote{
+    In this case, $A_e$ at low latitudes $|\theta|<20^{\circ}$ is further reduced by a factor $|f/f_{20}|$,
+    where $f_{20}$ is the value of $f$ at $20^{\circ}$~N
+  } (\mdl{ldfeiv}) and \np{rn_aeiv_0}{rn\_aeiv\_0} is ignored unless it is zero.
+}
+
+When  \citet{gent.mcwilliams_JPO90} diffusion is used (\np[=.true.]{ln_ldfeiv}{ln\_ldfeiv}),
+an eddy induced tracer advection term is added,
+the formulation of which depends on the slopes of iso-neutral surfaces.
+Contrary to the case of iso-neutral mixing, the slopes used here are referenced to the geopotential surfaces,
+\ie\ \autoref{eq:LDF_slp_geo} is used in $z$-coordinates,
+and the sum \autoref{eq:LDF_slp_geo} + \autoref{eq:LDF_slp_iso} in $s$-coordinates.
+
+If isopycnal mixing is used in the standard way, \ie\ \np[=.false.]{ln_traldf_triad}{ln\_traldf\_triad}, the eddy induced velocity is given by:
+\begin{equation}
+  \label{eq:LDF_eiv}
+  \begin{split}
+    u^* & = \frac{1}{e_{2u}e_{3u}}\; \delta_k \left[e_{2u} \, A_{uw}^{eiv} \; \overline{r_{1w}}^{\,i+1/2} \right]\\
+    v^* & = \frac{1}{e_{1u}e_{3v}}\; \delta_k \left[e_{1v} \, A_{vw}^{eiv} \; \overline{r_{2w}}^{\,j+1/2} \right]\\
+    w^* & = \frac{1}{e_{1w}e_{2w}}\; \left\{ \delta_i \left[e_{2u} \, A_{uw}^{eiv} \; \overline{r_{1w}}^{\,i+1/2} \right] + \delta_j \left[e_{1v} \, A_{vw}^{eiv} \; \overline{r_{2w}}^{\,j+1/2} \right] \right\} \\
+  \end{split}
+\end{equation}
+where $A^{eiv}$ is the eddy induced velocity coefficient whose value is set through \np{nn_aei_ijk_t}{nn\_aei\_ijk\_t} \nam{tra_eiv}{tra\_eiv} namelist parameter.
+The three components of the eddy induced velocity are computed in \rou{ldf\_eiv\_trp} and
+added to the eulerian velocity in \rou{tra\_adv} where tracer advection is performed.
+This has been preferred to a separate computation of the advective trends associated with the eiv velocity,
+since it allows us to take advantage of all the advection schemes offered for the tracers
+(see \autoref{sec:TRA_adv}) and not just the $2^{nd}$ order advection scheme as in
+previous releases of OPA \citep{madec.delecluse.ea_NPM98}.
+This is particularly useful for passive tracers where \emph{positivity} of the advection scheme is of
+paramount importance.
+
+At the surface, lateral and bottom boundaries, the eddy induced velocity,
+and thus the advective eddy fluxes of heat and salt, are set to zero.
+The value of the eddy induced mixing coefficient and its space variation is controlled in a similar way as for lateral mixing coefficient described in the preceding subsection (\np{nn_aei_ijk_t}{nn\_aei\_ijk\_t}, \np{rn_Ue}{rn\_Ue}, \np{rn_Le}{rn\_Le} namelist parameters).
+\colorbox{yellow}{CASE \np{nn_aei_ijk_t}{nn\_aei\_ijk\_t} = 21 to be added}
+
+In case of setting \np[=.true.]{ln_traldf_triad}{ln\_traldf\_triad}, a skew form of the eddy induced advective fluxes is used, which is described in \autoref{apdx:TRIADS}.
+
+%% =================================================================================================
+\section[Mixed layer eddies (\forcode{ln_mle})]{Mixed layer eddies (\protect\np{ln_mle}{ln\_mle})}
+\label{sec:LDF_mle}
+
+\begin{listing}
+  \nlst{namtra_mle}
+  \caption{\forcode{&namtra_mle}}
+  \label{lst:namtra_mle}
+\end{listing}
+
+If  \np[=.true.]{ln_mle}{ln\_mle} in \nam{tra_mle}{tra\_mle} namelist, a parameterization of the mixing due to unresolved mixed layer instabilities is activated (\citet{foxkemper.ferrari_JPO08}). Additional transport is computed in \rou{ldf\_mle\_trp} and added to the eulerian transport in \rou{tra\_adv} as done for eddy induced advection.
+
+\colorbox{yellow}{TBC}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_OBS.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_OBS.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_OBS.tex	(revision 14097)
@@ -0,0 +1,1184 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Observation and Model Comparison (OBS)}
+\label{chap:OBS}
+
+%\subsubsection*{Changes record}
+%\begin{tabular}{l||l|m{0.65\linewidth}}
+%    Release   & Author        & Modifications \\
+%    {\em 4.0} & {\em D. J. Lea} & {\em \NEMO\ 4.0 updates}  \\
+%    {\em 3.6} & {\em M. Martin, A. Ryan} & {\em Add averaging operator, standalone obs oper} \\
+%    {\em 3.4} & {\em D. J. Lea, M. Martin, ...} & {\em Initial version}  \\
+%    {\em --\texttt{"}--} & {\em ... K. Mogensen, A. Vidard, A. Weaver} & {\em ---\texttt{"}---}  \\
+%\end{tabular}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+The observation and model comparison code, the observation operator (OBS), reads in observation files
+(profile temperature and salinity, sea surface temperature, sea level anomaly, sea ice concentration, and velocity) and calculates an interpolated model equivalent value at the observation location and nearest model time step.
+The resulting data are saved in a ``feedback'' file (or files).
+The code was originally developed for use with the NEMOVAR data assimilation code,
+but can be used for validation or verification of the model or with any other data assimilation system.
+
+The OBS code is called from \mdl{nemogcm} for model initialisation and to calculate the model equivalent values for observations on the 0th time step.
+The code is then called again after each time step from \mdl{step}.
+The code is only activated if the \nam{obs}{obs} namelist logical \np{ln_diaobs}{ln\_diaobs} is set to true.
+
+For all data types a 2D horizontal interpolator or averager is needed to
+interpolate/average the model fields to the observation location.
+For {\em in situ} profiles, a 1D vertical interpolator is needed in addition to
+provide model fields at the observation depths.
+This now works in a generalised vertical coordinate system.
+
+Some profile observation types (\eg\ tropical moored buoys) are made available as daily averaged quantities.
+The observation operator code can be set-up to calculate the equivalent daily average model temperature fields using
+the \np{nn_profdavtypes}{nn\_profdavtypes} namelist array.
+Some SST observations are equivalent to a night-time average value and
+the observation operator code can calculate equivalent night-time average model SST fields by
+setting the namelist value \np{ln_sstnight}{ln\_sstnight} to true.
+Otherwise (by default) the model value from the nearest time step to the observation time is used.
+
+The code is controlled by the namelist \nam{obs}{obs}.
+See the following sections for more details on setting up the namelist.
+
+In \autoref{sec:OBS_example} a test example of the observation operator code is introduced, including
+where to obtain data and how to setup the namelist.
+In \autoref{sec:OBS_details} some more technical details of the different observation types used are introduced, and we
+also show a more complete namelist.
+In \autoref{sec:OBS_theory} some of the theoretical aspects of the observation operator are described including
+interpolation methods and running on multiple processors.
+In \autoref{sec:OBS_sao} the standalone observation operator code is described.
+In \autoref{sec:OBS_obsutils} we describe some utilities to help work with the files produced by the OBS code.
+
+%% =================================================================================================
+\section{Running the observation operator code example}
+\label{sec:OBS_example}
+
+In this section an example of running the observation operator code is described using
+profile observation data which can be freely downloaded.
+It shows how to adapt an existing run and build of \NEMO\ to run the observation operator. Note also the observation operator and the assimilation increments code are run in the ORCA2\_ICE\_OBS SETTE test.
+
+\begin{enumerate}
+\item Compile \NEMO.
+
+\item Download some EN4 data from \href{http://www.metoffice.gov.uk/hadobs}{www.metoffice.gov.uk/hadobs}.
+  Choose observations which are valid for the period of your test run because
+  the observation operator compares the model and observations for a matching date and time.
+
+\item Compile the OBSTOOLS code in the \path{tools} directory using:
+\begin{cmds}
+./maketools -n OBSTOOLS -m [ARCH]
+\end{cmds}
+
+replacing \texttt{[ARCH]} with the build architecture file for your machine. Note the tools are checked out from a separate location of the repository (under \path{/utils/tools}).
+
+\item Convert the EN4 data into feedback format:
+\begin{cmds}
+enact2fb.exe profiles_01.nc EN.4.1.1.f.profiles.g10.YYYYMM.nc
+\end{cmds}
+
+\item Include the following in the \NEMO\ namelist to run the observation operator on this data:
+\end{enumerate}
+
+Options are defined through the \nam{obs}{obs} namelist variables.
+The options \np{ln_t3d}{ln\_t3d} and \np{ln_s3d}{ln\_s3d} switch on the temperature and salinity profile observation operator code.
+The filename or array of filenames are specified using the \np{cn_profbfiles}{cn\_profbfiles} variable.
+The model grid points for a particular observation latitude and longitude are found using
+the grid searching part of the code.
+This can be expensive, particularly for large numbers of observations,
+setting \np{ln_grid_search_lookup}{ln\_grid\_search\_lookup} allows the use of a lookup table which
+is saved into an \np{cn_gridsearch}{cn\_gridsearch} file (or files).
+This will need to be generated the first time if it does not exist in the run directory.
+However, once produced it will significantly speed up future grid searches.
+Setting \np{ln_grid_global}{ln\_grid\_global} means that the code distributes the observations evenly between processors.
+Alternatively each processor will work with observations located within the model subdomain
+(see \autoref{subsec:OBS_parallel}).
+
+A number of utilities are now provided to plot the feedback files, convert and recombine the files.
+These are explained in more detail in \autoref{sec:OBS_obsutils}.
+Utilities to convert other input data formats into the feedback format are also described in
+\autoref{sec:OBS_obsutils}.
+
+%% =================================================================================================
+\section{Technical details (feedback type observation file headers)}
+\label{sec:OBS_details}
+
+Here we show a more complete example namelist \nam{obs}{obs} and also show the NetCDF headers of
+the observation files that may be used with the observation operator.
+
+\begin{listing}
+  \nlst{namobs}
+  \caption{\forcode{&namobs}}
+  \label{lst:namobs}
+\end{listing}
+
+The observation operator code uses the feedback observation file format for all data types.
+All the observation files must be in NetCDF format.
+Some example headers (produced using \mbox{\textit{ncdump~-h}}) for profile data, sea level anomaly and
+sea surface temperature are in the following subsections.
+
+%% =================================================================================================
+\subsection{Profile feedback file}
+
+\begin{clines}
+netcdf profiles_01 {
+dimensions:
+     N_OBS = 603 ;
+     N_LEVELS = 150 ;
+     N_VARS = 2 ;
+     N_QCF = 2 ;
+     N_ENTRIES = 1 ;
+     N_EXTRA = 1 ;
+     STRINGNAM = 8 ;
+     STRINGGRID = 1 ;
+     STRINGWMO = 8 ;
+     STRINGTYP = 4 ;
+     STRINGJULD = 14 ;
+variables:
+     char VARIABLES(N_VARS, STRINGNAM) ;
+          VARIABLES:long_name = "List of variables in feedback files" ;
+     char ENTRIES(N_ENTRIES, STRINGNAM) ;
+          ENTRIES:long_name = "List of additional entries for each variable in feedback files" ;
+     char EXTRA(N_EXTRA, STRINGNAM) ;
+          EXTRA:long_name = "List of extra variables" ;
+     char STATION_IDENTIFIER(N_OBS, STRINGWMO) ;
+          STATION_IDENTIFIER:long_name = "Station identifier" ;
+     char STATION_TYPE(N_OBS, STRINGTYP) ;
+          STATION_TYPE:long_name = "Code instrument type" ;
+     double LONGITUDE(N_OBS) ;
+          LONGITUDE:long_name = "Longitude" ;
+          LONGITUDE:units = "degrees_east" ;
+          LONGITUDE:_Fillvalue = 99999.f ;
+     double LATITUDE(N_OBS) ;
+          LATITUDE:long_name = "Latitude" ;
+          LATITUDE:units = "degrees_north" ;
+          LATITUDE:_Fillvalue = 99999.f ;
+     double DEPTH(N_OBS, N_LEVELS) ;
+          DEPTH:long_name = "Depth" ;
+          DEPTH:units = "metre" ;
+          DEPTH:_Fillvalue = 99999.f ;
+     int DEPTH_QC(N_OBS, N_LEVELS) ;
+          DEPTH_QC:long_name = "Quality on depth" ;
+          DEPTH_QC:Conventions = "q where q =[0,9]" ;
+          DEPTH_QC:_Fillvalue = 0 ;
+     int DEPTH_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          DEPTH_QC_FLAGS:long_name = "Quality flags on depth" ;
+          DEPTH_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+     double JULD(N_OBS) ;
+          JULD:long_name = "Julian day" ;
+          JULD:units = "days since JULD_REFERENCE" ;
+          JULD:Conventions = "relative julian days with decimal part (as parts of day)" ;
+          JULD:_Fillvalue = 99999.f ;
+     char JULD_REFERENCE(STRINGJULD) ;
+          JULD_REFERENCE:long_name = "Date of reference for julian days" ;
+          JULD_REFERENCE:Conventions = "YYYYMMDDHHMMSS" ;
+     int OBSERVATION_QC(N_OBS) ;
+          OBSERVATION_QC:long_name = "Quality on observation" ;
+          OBSERVATION_QC:Conventions = "q where q =[0,9]" ;
+          OBSERVATION_QC:_Fillvalue = 0 ;
+     int OBSERVATION_QC_FLAGS(N_OBS, N_QCF) ;
+          OBSERVATION_QC_FLAGS:long_name = "Quality flags on observation" ;
+          OBSERVATION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          OBSERVATION_QC_FLAGS:_Fillvalue = 0 ;
+     int POSITION_QC(N_OBS) ;
+          POSITION_QC:long_name = "Quality on position (latitude and longitude)" ;
+          POSITION_QC:Conventions = "q where q =[0,9]" ;
+          POSITION_QC:_Fillvalue = 0 ;
+     int POSITION_QC_FLAGS(N_OBS, N_QCF) ;
+          POSITION_QC_FLAGS:long_name = "Quality flags on position" ;
+          POSITION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          POSITION_QC_FLAGS:_Fillvalue = 0 ;
+     int JULD_QC(N_OBS) ;
+          JULD_QC:long_name = "Quality on date and time" ;
+          JULD_QC:Conventions = "q where q =[0,9]" ;
+          JULD_QC:_Fillvalue = 0 ;
+     int JULD_QC_FLAGS(N_OBS, N_QCF) ;
+          JULD_QC_FLAGS:long_name = "Quality flags on date and time" ;
+          JULD_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          JULD_QC_FLAGS:_Fillvalue = 0 ;
+     int ORIGINAL_FILE_INDEX(N_OBS) ;
+          ORIGINAL_FILE_INDEX:long_name = "Index in original data file" ;
+          ORIGINAL_FILE_INDEX:_Fillvalue = -99999 ;
+     float POTM_OBS(N_OBS, N_LEVELS) ;
+          POTM_OBS:long_name = "Potential temperature" ;
+          POTM_OBS:units = "Degrees Celsius" ;
+          POTM_OBS:_Fillvalue = 99999.f ;
+     float POTM_Hx(N_OBS, N_LEVELS) ;
+          POTM_Hx:long_name = "Model interpolated potential temperature" ;
+          POTM_Hx:units = "Degrees Celsius" ;
+          POTM_Hx:_Fillvalue = 99999.f ;
+     int POTM_QC(N_OBS) ;
+          POTM_QC:long_name = "Quality on potential temperature" ;
+          POTM_QC:Conventions = "q where q =[0,9]" ;
+          POTM_QC:_Fillvalue = 0 ;
+     int POTM_QC_FLAGS(N_OBS, N_QCF) ;
+          POTM_QC_FLAGS:long_name = "Quality flags on potential temperature" ;
+          POTM_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          POTM_QC_FLAGS:_Fillvalue = 0 ;
+     int POTM_LEVEL_QC(N_OBS, N_LEVELS) ;
+          POTM_LEVEL_QC:long_name = "Quality for each level on potential temperature" ;
+          POTM_LEVEL_QC:Conventions = "q where q =[0,9]" ;
+          POTM_LEVEL_QC:_Fillvalue = 0 ;
+     int POTM_LEVEL_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          POTM_LEVEL_QC_FLAGS:long_name = "Quality flags for each level on potential temperature" ;
+          POTM_LEVEL_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          POTM_LEVEL_QC_FLAGS:_Fillvalue = 0 ;
+     int POTM_IOBSI(N_OBS) ;
+          POTM_IOBSI:long_name = "ORCA grid search I coordinate" ;
+     int POTM_IOBSJ(N_OBS) ;
+          POTM_IOBSJ:long_name = "ORCA grid search J coordinate" ;
+     int POTM_IOBSK(N_OBS, N_LEVELS) ;
+          POTM_IOBSK:long_name = "ORCA grid search K coordinate" ;
+     char POTM_GRID(STRINGGRID) ;
+          POTM_GRID:long_name = "ORCA grid search grid (T,U,V)" ;
+     float PSAL_OBS(N_OBS, N_LEVELS) ;
+          PSAL_OBS:long_name = "Practical salinity" ;
+          PSAL_OBS:units = "PSU" ;
+          PSAL_OBS:_Fillvalue = 99999.f ;
+     float PSAL_Hx(N_OBS, N_LEVELS) ;
+          PSAL_Hx:long_name = "Model interpolated practical salinity" ;
+          PSAL_Hx:units = "PSU" ;
+          PSAL_Hx:_Fillvalue = 99999.f ;
+     int PSAL_QC(N_OBS) ;
+          PSAL_QC:long_name = "Quality on practical salinity" ;
+          PSAL_QC:Conventions = "q where q =[0,9]" ;
+          PSAL_QC:_Fillvalue = 0 ;
+     int PSAL_QC_FLAGS(N_OBS, N_QCF) ;
+          PSAL_QC_FLAGS:long_name = "Quality flags on practical salinity" ;
+          PSAL_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          PSAL_QC_FLAGS:_Fillvalue = 0 ;
+     int PSAL_LEVEL_QC(N_OBS, N_LEVELS) ;
+          PSAL_LEVEL_QC:long_name = "Quality for each level on practical salinity" ;
+          PSAL_LEVEL_QC:Conventions = "q where q =[0,9]" ;
+          PSAL_LEVEL_QC:_Fillvalue = 0 ;
+     int PSAL_LEVEL_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          PSAL_LEVEL_QC_FLAGS:long_name = "Quality flags for each level on practical salinity" ;
+          PSAL_LEVEL_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          PSAL_LEVEL_QC_FLAGS:_Fillvalue = 0 ;
+     int PSAL_IOBSI(N_OBS) ;
+          PSAL_IOBSI:long_name = "ORCA grid search I coordinate" ;
+     int PSAL_IOBSJ(N_OBS) ;
+          PSAL_IOBSJ:long_name = "ORCA grid search J coordinate" ;
+     int PSAL_IOBSK(N_OBS, N_LEVELS) ;
+          PSAL_IOBSK:long_name = "ORCA grid search K coordinate" ;
+     char PSAL_GRID(STRINGGRID) ;
+          PSAL_GRID:long_name = "ORCA grid search grid (T,U,V)" ;
+     float TEMP(N_OBS, N_LEVELS) ;
+          TEMP:long_name = "Insitu temperature" ;
+          TEMP:units = "Degrees Celsius" ;
+          TEMP:_Fillvalue = 99999.f ;
+
+// global attributes:
+          :title = "NEMO observation operator output" ;
+          :Convention = "NEMO unified observation operator output" ;
+}
+\end{clines}
+
+%% =================================================================================================
+\subsection{Sea level anomaly feedback file}
+
+\begin{clines}
+netcdf sla_01 {
+dimensions:
+     N_OBS = 41301 ;
+     N_LEVELS = 1 ;
+     N_VARS = 1 ;
+     N_QCF = 2 ;
+     N_ENTRIES = 1 ;
+     N_EXTRA = 1 ;
+     STRINGNAM = 8 ;
+     STRINGGRID = 1 ;
+     STRINGWMO = 8 ;
+     STRINGTYP = 4 ;
+     STRINGJULD = 14 ;
+variables:
+     char VARIABLES(N_VARS, STRINGNAM) ;
+          VARIABLES:long_name = "List of variables in feedback files" ;
+     char ENTRIES(N_ENTRIES, STRINGNAM) ;
+          ENTRIES:long_name = "List of additional entries for each variable in feedback files" ;
+     char EXTRA(N_EXTRA, STRINGNAM) ;
+          EXTRA:long_name = "List of extra variables" ;
+     char STATION_IDENTIFIER(N_OBS, STRINGWMO) ;
+          STATION_IDENTIFIER:long_name = "Station identifier" ;
+     char STATION_TYPE(N_OBS, STRINGTYP) ;
+          STATION_TYPE:long_name = "Code instrument type" ;
+     double LONGITUDE(N_OBS) ;
+          LONGITUDE:long_name = "Longitude" ;
+          LONGITUDE:units = "degrees_east" ;
+          LONGITUDE:_Fillvalue = 99999.f ;
+     double LATITUDE(N_OBS) ;
+          LATITUDE:long_name = "Latitude" ;
+          LATITUDE:units = "degrees_north" ;
+          LATITUDE:_Fillvalue = 99999.f ;
+     double DEPTH(N_OBS, N_LEVELS) ;
+          DEPTH:long_name = "Depth" ;
+          DEPTH:units = "metre" ;
+          DEPTH:_Fillvalue = 99999.f ;
+     int DEPTH_QC(N_OBS, N_LEVELS) ;
+          DEPTH_QC:long_name = "Quality on depth" ;
+          DEPTH_QC:Conventions = "q where q =[0,9]" ;
+          DEPTH_QC:_Fillvalue = 0 ;
+     int DEPTH_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          DEPTH_QC_FLAGS:long_name = "Quality flags on depth" ;
+          DEPTH_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+     double JULD(N_OBS) ;
+          JULD:long_name = "Julian day" ;
+          JULD:units = "days since JULD_REFERENCE" ;
+          JULD:Conventions = "relative julian days with decimal part (as parts of day)" ;
+          JULD:_Fillvalue = 99999.f ;
+     char JULD_REFERENCE(STRINGJULD) ;
+          JULD_REFERENCE:long_name = "Date of reference for julian days" ;
+          JULD_REFERENCE:Conventions = "YYYYMMDDHHMMSS" ;
+     int OBSERVATION_QC(N_OBS) ;
+          OBSERVATION_QC:long_name = "Quality on observation" ;
+          OBSERVATION_QC:Conventions = "q where q =[0,9]" ;
+          OBSERVATION_QC:_Fillvalue = 0 ;
+     int OBSERVATION_QC_FLAGS(N_OBS, N_QCF) ;
+          OBSERVATION_QC_FLAGS:long_name = "Quality flags on observation" ;
+          OBSERVATION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          OBSERVATION_QC_FLAGS:_Fillvalue = 0 ;
+     int POSITION_QC(N_OBS) ;
+          POSITION_QC:long_name = "Quality on position (latitude and longitude)" ;
+          POSITION_QC:Conventions = "q where q =[0,9]" ;
+          POSITION_QC:_Fillvalue = 0 ;
+     int POSITION_QC_FLAGS(N_OBS, N_QCF) ;
+          POSITION_QC_FLAGS:long_name = "Quality flags on position" ;
+          POSITION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          POSITION_QC_FLAGS:_Fillvalue = 0 ;
+     int JULD_QC(N_OBS) ;
+          JULD_QC:long_name = "Quality on date and time" ;
+          JULD_QC:Conventions = "q where q =[0,9]" ;
+          JULD_QC:_Fillvalue = 0 ;
+     int JULD_QC_FLAGS(N_OBS, N_QCF) ;
+          JULD_QC_FLAGS:long_name = "Quality flags on date and time" ;
+          JULD_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          JULD_QC_FLAGS:_Fillvalue = 0 ;
+     int ORIGINAL_FILE_INDEX(N_OBS) ;
+          ORIGINAL_FILE_INDEX:long_name = "Index in original data file" ;
+          ORIGINAL_FILE_INDEX:_Fillvalue = -99999 ;
+     float SLA_OBS(N_OBS, N_LEVELS) ;
+          SLA_OBS:long_name = "Sea level anomaly" ;
+          SLA_OBS:units = "metre" ;
+          SLA_OBS:_Fillvalue = 99999.f ;
+     float SLA_Hx(N_OBS, N_LEVELS) ;
+          SLA_Hx:long_name = "Model interpolated sea level anomaly" ;
+          SLA_Hx:units = "metre" ;
+          SLA_Hx:_Fillvalue = 99999.f ;
+     int SLA_QC(N_OBS) ;
+          SLA_QC:long_name = "Quality on sea level anomaly" ;
+          SLA_QC:Conventions = "q where q =[0,9]" ;
+          SLA_QC:_Fillvalue = 0 ;
+     int SLA_QC_FLAGS(N_OBS, N_QCF) ;
+          SLA_QC_FLAGS:long_name = "Quality flags on sea level anomaly" ;
+          SLA_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          SLA_QC_FLAGS:_Fillvalue = 0 ;
+     int SLA_LEVEL_QC(N_OBS, N_LEVELS) ;
+          SLA_LEVEL_QC:long_name = "Quality for each level on sea level anomaly" ;
+          SLA_LEVEL_QC:Conventions = "q where q =[0,9]" ;
+          SLA_LEVEL_QC:_Fillvalue = 0 ;
+     int SLA_LEVEL_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          SLA_LEVEL_QC_FLAGS:long_name = "Quality flags for each level on sea level anomaly" ;
+          SLA_LEVEL_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          SLA_LEVEL_QC_FLAGS:_Fillvalue = 0 ;
+     int SLA_IOBSI(N_OBS) ;
+          SLA_IOBSI:long_name = "ORCA grid search I coordinate" ;
+     int SLA_IOBSJ(N_OBS) ;
+          SLA_IOBSJ:long_name = "ORCA grid search J coordinate" ;
+     int SLA_IOBSK(N_OBS, N_LEVELS) ;
+          SLA_IOBSK:long_name = "ORCA grid search K coordinate" ;
+     char SLA_GRID(STRINGGRID) ;
+          SLA_GRID:long_name = "ORCA grid search grid (T,U,V)" ;
+     float MDT(N_OBS, N_LEVELS) ;
+          MDT:long_name = "Mean Dynamic Topography" ;
+          MDT:units = "metre" ;
+          MDT:_Fillvalue = 99999.f ;
+
+// global attributes:
+          :title = "NEMO observation operator output" ;
+          :Convention = "NEMO unified observation operator output" ;
+}
+\end{clines}
+
+To use Sea Level Anomaly (SLA) data the mean dynamic topography (MDT) must be provided in a separate file defined on
+the model grid called \ifile{slaReferenceLevel}.
+The MDT is required in order to produce the model equivalent sea level anomaly from the model sea surface height.
+Below is an example header for this file (on the ORCA025 grid).
+
+\begin{clines}
+dimensions:
+        x = 1442 ;
+        y = 1021 ;
+variables:
+        float nav_lon(y, x) ;
+                nav_lon:units = "degrees_east" ;
+        float nav_lat(y, x) ;
+                nav_lat:units = "degrees_north" ;
+        float sossheig(y, x) ;
+                sossheig:_FillValue = -1.e+30f ;
+                sossheig:coordinates = "nav_lon nav_lat" ;
+                sossheig:long_name = "Mean Dynamic Topography" ;
+                sossheig:units = "metres" ;
+                sossheig:grid = "orca025T" ;
+\end{clines}
+
+%% =================================================================================================
+\subsection{Sea surface temperature feedback file}
+
+\begin{clines}
+netcdf sst_01 {
+dimensions:
+     N_OBS = 33099 ;
+     N_LEVELS = 1 ;
+     N_VARS = 1 ;
+     N_QCF = 2 ;
+     N_ENTRIES = 1 ;
+     STRINGNAM = 8 ;
+     STRINGGRID = 1 ;
+     STRINGWMO = 8 ;
+     STRINGTYP = 4 ;
+     STRINGJULD = 14 ;
+variables:
+     char VARIABLES(N_VARS, STRINGNAM) ;
+          VARIABLES:long_name = "List of variables in feedback files" ;
+     char ENTRIES(N_ENTRIES, STRINGNAM) ;
+          ENTRIES:long_name = "List of additional entries for each variable in feedback files" ;
+     char STATION_IDENTIFIER(N_OBS, STRINGWMO) ;
+          STATION_IDENTIFIER:long_name = "Station identifier" ;
+     char STATION_TYPE(N_OBS, STRINGTYP) ;
+          STATION_TYPE:long_name = "Code instrument type" ;
+     double LONGITUDE(N_OBS) ;
+          LONGITUDE:long_name = "Longitude" ;
+          LONGITUDE:units = "degrees_east" ;
+          LONGITUDE:_Fillvalue = 99999.f ;
+     double LATITUDE(N_OBS) ;
+          LATITUDE:long_name = "Latitude" ;
+          LATITUDE:units = "degrees_north" ;
+          LATITUDE:_Fillvalue = 99999.f ;
+     double DEPTH(N_OBS, N_LEVELS) ;
+          DEPTH:long_name = "Depth" ;
+          DEPTH:units = "metre" ;
+          DEPTH:_Fillvalue = 99999.f ;
+     int DEPTH_QC(N_OBS, N_LEVELS) ;
+          DEPTH_QC:long_name = "Quality on depth" ;
+          DEPTH_QC:Conventions = "q where q =[0,9]" ;
+          DEPTH_QC:_Fillvalue = 0 ;
+     int DEPTH_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          DEPTH_QC_FLAGS:long_name = "Quality flags on depth" ;
+          DEPTH_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+     double JULD(N_OBS) ;
+          JULD:long_name = "Julian day" ;
+          JULD:units = "days since JULD_REFERENCE" ;
+          JULD:Conventions = "relative julian days with decimal part (as parts of day)" ;
+          JULD:_Fillvalue = 99999.f ;
+     char JULD_REFERENCE(STRINGJULD) ;
+          JULD_REFERENCE:long_name = "Date of reference for julian days" ;
+          JULD_REFERENCE:Conventions = "YYYYMMDDHHMMSS" ;
+     int OBSERVATION_QC(N_OBS) ;
+          OBSERVATION_QC:long_name = "Quality on observation" ;
+          OBSERVATION_QC:Conventions = "q where q =[0,9]" ;
+          OBSERVATION_QC:_Fillvalue = 0 ;
+     int OBSERVATION_QC_FLAGS(N_OBS, N_QCF) ;
+          OBSERVATION_QC_FLAGS:long_name = "Quality flags on observation" ;
+          OBSERVATION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          OBSERVATION_QC_FLAGS:_Fillvalue = 0 ;
+     int POSITION_QC(N_OBS) ;
+          POSITION_QC:long_name = "Quality on position (latitude and longitude)" ;
+          POSITION_QC:Conventions = "q where q =[0,9]" ;
+          POSITION_QC:_Fillvalue = 0 ;
+     int POSITION_QC_FLAGS(N_OBS, N_QCF) ;
+          POSITION_QC_FLAGS:long_name = "Quality flags on position" ;
+          POSITION_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          POSITION_QC_FLAGS:_Fillvalue = 0 ;
+     int JULD_QC(N_OBS) ;
+          JULD_QC:long_name = "Quality on date and time" ;
+          JULD_QC:Conventions = "q where q =[0,9]" ;
+          JULD_QC:_Fillvalue = 0 ;
+     int JULD_QC_FLAGS(N_OBS, N_QCF) ;
+          JULD_QC_FLAGS:long_name = "Quality flags on date and time" ;
+          JULD_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          JULD_QC_FLAGS:_Fillvalue = 0 ;
+     int ORIGINAL_FILE_INDEX(N_OBS) ;
+          ORIGINAL_FILE_INDEX:long_name = "Index in original data file" ;
+          ORIGINAL_FILE_INDEX:_Fillvalue = -99999 ;
+     float SST_OBS(N_OBS, N_LEVELS) ;
+          SST_OBS:long_name = "Sea surface temperature" ;
+          SST_OBS:units = "Degree centigrade" ;
+          SST_OBS:_Fillvalue = 99999.f ;
+     float SST_Hx(N_OBS, N_LEVELS) ;
+          SST_Hx:long_name = "Model interpolated sea surface temperature" ;
+          SST_Hx:units = "Degree centigrade" ;
+          SST_Hx:_Fillvalue = 99999.f ;
+     int SST_QC(N_OBS) ;
+          SST_QC:long_name = "Quality on sea surface temperature" ;
+          SST_QC:Conventions = "q where q =[0,9]" ;
+          SST_QC:_Fillvalue = 0 ;
+     int SST_QC_FLAGS(N_OBS, N_QCF) ;
+          SST_QC_FLAGS:long_name = "Quality flags on sea surface temperature" ;
+          SST_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          SST_QC_FLAGS:_Fillvalue = 0 ;
+     int SST_LEVEL_QC(N_OBS, N_LEVELS) ;
+          SST_LEVEL_QC:long_name = "Quality for each level on sea surface temperature" ;
+          SST_LEVEL_QC:Conventions = "q where q =[0,9]" ;
+          SST_LEVEL_QC:_Fillvalue = 0 ;
+     int SST_LEVEL_QC_FLAGS(N_OBS, N_LEVELS, N_QCF) ;
+          SST_LEVEL_QC_FLAGS:long_name = "Quality flags for each level on sea surface temperature" ;
+          SST_LEVEL_QC_FLAGS:Conventions = "NEMOVAR flag conventions" ;
+          SST_LEVEL_QC_FLAGS:_Fillvalue = 0 ;
+     int SST_IOBSI(N_OBS) ;
+          SST_IOBSI:long_name = "ORCA grid search I coordinate" ;
+     int SST_IOBSJ(N_OBS) ;
+          SST_IOBSJ:long_name = "ORCA grid search J coordinate" ;
+     int SST_IOBSK(N_OBS, N_LEVELS) ;
+          SST_IOBSK:long_name = "ORCA grid search K coordinate" ;
+     char SST_GRID(STRINGGRID) ;
+          SST_GRID:long_name = "ORCA grid search grid (T,U,V)" ;
+
+// global attributes:
+          :title = "NEMO observation operator output" ;
+          :Convention = "NEMO unified observation operator output" ;
+}
+\end{clines}
+
+%% =================================================================================================
+\section{Theoretical details}
+\label{sec:OBS_theory}
+
+%% =================================================================================================
+\subsection{Horizontal interpolation and averaging methods}
+
+For most observation types, the horizontal extent of the observation is small compared to the model grid size and so
+the model equivalent of the observation is calculated by interpolating from
+the four surrounding grid points to the observation location.
+Some satellite observations (\eg\ microwave satellite SST data, or satellite SSS data) have a footprint which
+is similar in size or larger than the model grid size (particularly when the grid size is small).
+In those cases the model counterpart should be calculated by averaging the model grid points over
+the same size as the footprint.
+\NEMO\ therefore has the capability to specify either an interpolation or an averaging
+(for surface observation types only).
+
+The main namelist option associated with the interpolation/averaging is \np{nn_2dint}{nn\_2dint}.
+This default option can be set to values from 0 to 6.
+Values between 0 to 4 are associated with interpolation while values 5 or 6 are associated with averaging.
+\begin{itemize}
+\item \np[=0]{nn_2dint}{nn\_2dint}: Distance-weighted interpolation
+\item \np[=1]{nn_2dint}{nn\_2dint}: Distance-weighted interpolation (small angle)
+\item \np[=2]{nn_2dint}{nn\_2dint}: Bilinear interpolation (geographical grid)
+\item \np[=3]{nn_2dint}{nn\_2dint}: Bilinear remapping interpolation (general grid)
+\item \np[=4]{nn_2dint}{nn\_2dint}: Polynomial interpolation
+\item \np[=5]{nn_2dint}{nn\_2dint}: Radial footprint averaging with diameter specified in the namelist as
+  \texttt{rn\_[var]\_avglamscl} in degrees or metres (set using \texttt{ln\_[var]\_fp\_indegs})
+\item \np[=6]{nn_2dint}{nn\_2dint}: Rectangular footprint averaging with E/W and N/S size specified in
+  the namelist as \texttt{rn\_[var]\_avglamscl} and \texttt{rn\_[var]\_avgphiscl} in degrees or metres
+  (set using \texttt{ln\_[var]\_fp\_indegs})
+\end{itemize}
+Replace \texttt{[var]} in the last two options with the observation type (sla, sst, sss or sic) for
+which the averaging is to be performed (see namelist example above).
+The \np{nn_2dint}{nn\_2dint} default option can be overridden for surface observation types using
+namelist values \texttt{nn\_2dint\_[var]} where \texttt{[var]} is the observation type.
+
+Below is some more detail on the various options for interpolation and averaging available in \NEMO.
+
+%% =================================================================================================
+\subsubsection{Horizontal interpolation}
+
+Consider an observation point ${\mathrm P}$ with longitude and latitude (${\lambda_{}}_{\mathrm P}$, $\phi_{\mathrm P}$) and
+the four nearest neighbouring model grid points ${\mathrm A}$, ${\mathrm B}$, ${\mathrm C}$ and ${\mathrm D}$ with
+longitude and latitude ($\lambda_{\mathrm A}$, $\phi_{\mathrm A}$),($\lambda_{\mathrm B}$, $\phi_{\mathrm B}$) etc.
+All horizontal interpolation methods implemented in \NEMO\ estimate the value of a model variable $x$ at point $P$ as
+a weighted linear combination of the values of the model variables at the grid points ${\mathrm A}$, ${\mathrm B}$ etc.:
+
+\begin{align*}
+  {x_{}}_{\mathrm P} =
+\frac{1}{w} \left( {w_{}}_{\mathrm A} {x_{}}_{\mathrm A} +
+{w_{}}_{\mathrm B} {x_{}}_{\mathrm B} +
+{w_{}}_{\mathrm C} {x_{}}_{\mathrm C} +
+{w_{}}_{\mathrm D} {x_{}}_{\mathrm D} \right)
+\end{align*}
+
+where ${w_{}}_{\mathrm A}$, ${w_{}}_{\mathrm B}$ etc. are the respective weights for the model field at
+points ${\mathrm A}$, ${\mathrm B}$ etc., and $w = {w_{}}_{\mathrm A} + {w_{}}_{\mathrm B} + {w_{}}_{\mathrm C} + {w_{}}_{\mathrm D}$.
+
+Four different possibilities are available for computing the weights.
+
+\begin{enumerate}
+\item {\bfseries Great-Circle distance-weighted interpolation.}
+  The weights are computed as a function of the great-circle distance $s(P, \cdot)$ between $P$ and
+  the model grid points $A$, $B$ etc.
+  For example, the weight given to the field ${x_{}}_{\mathrm A}$ is specified as the product of the distances
+  from ${\mathrm P}$ to the other points:
+
+  \begin{alignat*}{2}
+    {w_{}}_{\mathrm A} = s({\mathrm P}, {\mathrm B}) \, s({\mathrm P}, {\mathrm C}) \, s({\mathrm P}, {\mathrm D})
+  \end{alignat*}
+
+  where
+
+  \begin{alignat*}{2}
+    s\left({\mathrm P}, {\mathrm M} \right) & = & \hspace{0.25em} \cos^{-1} \! \left\{
+               \sin {\phi_{}}_{\mathrm P} \sin {\phi_{}}_{\mathrm M}
+             + \cos {\phi_{}}_{\mathrm P} \cos {\phi_{}}_{\mathrm M}
+               \cos ({\lambda_{}}_{\mathrm M} - {\lambda_{}}_{\mathrm P})
+                   \right\}
+   \end{alignat*}
+
+   and $M$ corresponds to $B$, $C$ or $D$.
+   A more stable form of the great-circle distance formula for small distances ($x$ near 1)
+   involves the arcsine function (\eg\ see p.~101 of \citet{daley.barker_bk01}:
+
+   \begin{alignat*}{2}
+     s\left( {\mathrm P}, {\mathrm M} \right) = \sin^{-1} \! \left\{ \sqrt{ 1 - x^2 } \right\}
+   \end{alignat*}
+
+   where
+
+   \begin{alignat*}{2}
+     x = {a_{}}_{\mathrm M} {a_{}}_{\mathrm P} + {b_{}}_{\mathrm M} {b_{}}_{\mathrm P} + {c_{}}_{\mathrm M} {c_{}}_{\mathrm P}
+   \end{alignat*}
+
+   and
+
+   \begin{alignat*}{3}
+   & {a_{}}_{\mathrm M} & = && \quad \sin {\phi_{}}_{\mathrm M}, \\
+   & {a_{}}_{\mathrm P} & = && \quad \sin {\phi_{}}_{\mathrm P}, \\
+   & {b_{}}_{\mathrm M} & = && \quad \cos {\phi_{}}_{\mathrm M} \cos {\phi_{}}_{\mathrm M}, \\
+   & {b_{}}_{\mathrm P} & = && \quad \cos {\phi_{}}_{\mathrm P} \cos {\phi_{}}_{\mathrm P}, \\
+   & {c_{}}_{\mathrm M} & = && \quad \cos {\phi_{}}_{\mathrm M} \sin {\phi_{}}_{\mathrm M}, \\
+   & {c_{}}_{\mathrm P} & = && \quad \cos {\phi_{}}_{\mathrm P} \sin {\phi_{}}_{\mathrm P}.
+   \end{alignat*}
+
+\item {\bfseries Great-Circle distance-weighted interpolation with small angle approximation.}
+  Similar to the previous interpolation but with the distance $s$ computed as
+  \begin{alignat*}{2}
+    s\left( {\mathrm P}, {\mathrm M} \right)
+    & = & \sqrt{ \left( {\phi_{}}_{\mathrm M} - {\phi_{}}_{\mathrm P} \right)^{2}
+                                      + \left( {\lambda_{}}_{\mathrm M} - {\lambda_{}}_{\mathrm P} \right)^{2}
+                                      \cos^{2} {\phi_{}}_{\mathrm M} }
+  \end{alignat*}
+  where $M$ corresponds to $A$, $B$, $C$ or $D$.
+
+\item {\bfseries Bilinear interpolation for a regular spaced grid.}
+  The interpolation is split into two 1D interpolations in the longitude and latitude directions, respectively.
+
+\item {\bfseries Bilinear remapping interpolation for a general grid.}
+  An iterative scheme that involves first mapping a quadrilateral cell into
+  a cell with coordinates (0,0), (1,0), (0,1) and (1,1).
+  This method is based on the \href{https://github.com/SCRIP-Project/SCRIP}{SCRIP interpolation package}.
+
+\end{enumerate}
+
+%% =================================================================================================
+\subsubsection{Horizontal averaging}
+
+For each surface observation type:
+\begin{itemize}
+\item The standard grid-searching code is used to find the nearest model grid point to the observation location
+  (see next subsection).
+\item The maximum number of grid points required for that observation in each local grid domain is calculated. Some of these points may later turn out to have zero weight depending on the shape of the footprint.
+\item The longitudes and latitudes of the grid points surrounding the nearest model grid box are extracted using
+  existing MPI routines.
+\item The weights for each grid point associated with each observation are calculated,
+  either for radial or rectangular footprints.
+  For grid points completely within the footprint, the weight is one;
+  for grid points completely outside the footprint, the weight is zero.
+  For grid points which are partly within the footprint the ratio between the area of the footprint within
+  the grid box and the total area of the grid box is used as the weight.
+\item The weighted average of the model grid points associated with each observation is calculated,
+  and this is then given as the model counterpart of the observation.
+\end{itemize}
+
+Examples of the weights calculated for an observation with rectangular and radial footprints are shown in
+\autoref{fig:OBS_avgrec} and~\autoref{fig:OBS_avgrad}.
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_avg_rec}
+  \caption[Observational weights with a rectangular footprint]{
+    Weights associated with each model grid box (blue lines and numbers)
+    for an observation at -170.5\deg{E}, 56.0\deg{N} with a rectangular footprint of 1\deg\ x 1\deg.}
+  \label{fig:OBS_avgrec}
+\end{figure}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_avg_rad}
+  \caption[Observational weights with a radial footprint]{
+    Weights associated with each model grid box (blue lines and numbers)
+    for an observation at -170.5\deg{E}, 56.0\deg{N} with a radial footprint with diameter 1\deg.}
+  \label{fig:OBS_avgrad}
+\end{figure}
+
+%% =================================================================================================
+\subsection{Grid search}
+
+For many grids used by the \NEMO\ model, such as the ORCA family, the horizontal grid coordinates $i$ and $j$ are not simple functions of latitude and longitude.
+Therefore, it is not always straightforward to determine the grid points surrounding any given observational position.
+Before the interpolation can be performed, a search algorithm is then required to determine the corner points of
+the quadrilateral cell in which the observation is located.
+This is the most difficult and time consuming part of the 2D interpolation procedure.
+A robust test for determining if an observation falls within a given quadrilateral cell is as follows.
+Let ${\mathrm P}({\lambda_{}}_{\mathrm P} ,{\phi_{}}_{\mathrm P} )$ denote the observation point,
+and let ${\mathrm A}({\lambda_{}}_{\mathrm A} ,{\phi_{}}_{\mathrm A} )$, ${\mathrm B}({\lambda_{}}_{\mathrm B} ,{\phi_{}}_{\mathrm B} )$,
+${\mathrm C}({\lambda_{}}_{\mathrm C} ,{\phi_{}}_{\mathrm C} )$ and ${\mathrm D}({\lambda_{}}_{\mathrm D} ,{\phi_{}}_{\mathrm D} )$
+denote the bottom left, bottom right, top left and top right corner points of the cell, respectively.
+To determine if P is inside the cell, we verify that the cross-products
+\begin{align*}
+  \begin{array}{lllll}
+    {{\mathbf r}_{}}_{\mathrm PA} \times {{\mathbf r}_{}}_{\mathrm PC}
+    & = & [({\lambda_{}}_{\mathrm A}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm C}   \; -\; {\phi_{}}_{\mathrm P} )
+          - ({\lambda_{}}_{\mathrm C}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm A}   \; -\; {\phi_{}}_{\mathrm P} )] \; \widehat{\mathbf k} \\
+    {{\mathbf r}_{}}_{\mathrm PB} \times {{\mathbf r}_{}}_{\mathrm PA}
+    & = & [({\lambda_{}}_{\mathrm B}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm A}   \; -\; {\phi_{}}_{\mathrm P} )
+          - ({\lambda_{}}_{\mathrm A}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm B}   \; -\; {\phi_{}}_{\mathrm P} )] \; \widehat{\mathbf k} \\
+    {{\mathbf r}_{}}_{\mathrm PC} \times {{\mathbf r}_{}}_{\mathrm PD}
+    & = & [({\lambda_{}}_{\mathrm C}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm D}   \; -\; {\phi_{}}_{\mathrm P} )
+          - ({\lambda_{}}_{\mathrm D}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm C}   \; -\; {\phi_{}}_{\mathrm P} )] \; \widehat{\mathbf k} \\
+    {{\mathbf r}_{}}_{\mathrm PD} \times {{\mathbf r}_{}}_{\mathrm PB}
+    & = & [({\lambda_{}}_{\mathrm D}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm B}   \; -\; {\phi_{}}_{\mathrm P} )
+          - ({\lambda_{}}_{\mathrm B}\; -\; {\lambda_{}}_{\mathrm P} )
+          ({\phi_{}}_{\mathrm D}  \;  - \; {\phi_{}}_{\mathrm P} )] \; \widehat{\mathbf k} \\
+  \end{array}
+  % \label{eq:OBS_cross}
+\end{align*}
+point in the opposite direction to the unit normal $\widehat{\mathbf k}$
+(\ie\ that the coefficients of $\widehat{\mathbf k}$ are negative),
+where ${{\mathbf r}_{}}_{\mathrm PA}$, ${{\mathbf r}_{}}_{\mathrm PB}$, etc. correspond to
+the vectors between points P and A, P and B, etc..
+The method used is similar to the method used in the \href{https://github.com/SCRIP-Project/SCRIP}{SCRIP interpolation package}.
+
+In order to speed up the grid search, there is the possibility to construct a lookup table for a user specified resolution.
+This lookup table contains the lower and upper bounds on the $i$ and $j$ indices to
+be searched for on a regular grid.
+For each observation position, the closest point on the regular grid of this position is computed and
+the $i$ and $j$ ranges of this point searched to determine the precise four points surrounding the observation.
+
+%% =================================================================================================
+\subsection{Parallel aspects of horizontal interpolation}
+\label{subsec:OBS_parallel}
+
+For horizontal interpolation, there is the basic problem that
+the observations are unevenly distributed on the globe.
+In \NEMO\ the model grid is divided into subgrids (or domains) where
+each subgrid is executed on a single processing element with explicit message passing for
+exchange of information along the domain boundaries when running on a massively parallel processor (MPP) system.
+
+For observations there is no natural distribution since the observations are not equally distributed on the globe.
+Two options have been made available:
+1) geographical distribution;
+and 2) round-robin.
+
+%% =================================================================================================
+\subsubsection{Geographical distribution of observations among processors}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_obsdist_local}
+  \caption[Observations with the geographical distribution]{
+    Example of the distribution of observations with
+    the geographical distribution of observational data}
+  \label{fig:OBS_local}
+\end{figure}
+
+This is the simplest option in which the observations are distributed according to
+the domain of the grid-point parallelization.
+\autoref{fig:OBS_local} shows an example of the distribution of the {\em in situ} data on processors with
+a different colour for each observation on a given processor for a 4 $\times$ 2 decomposition with ORCA2.
+The grid-point domain decomposition is clearly visible on the plot.
+
+The advantage of this approach is that all information needed for horizontal interpolation is available without
+any MPP communication.
+This is under the assumption that we are dealing with point observations and only using a $2 \times 2$ grid-point stencil for
+the interpolation (\eg\ bilinear interpolation).
+For higher order interpolation schemes this is no longer valid.
+A disadvantage with the above scheme is that the number of observations on each processor can be very different.
+If the cost of the actual interpolation is expensive relative to the communication of data needed for interpolation,
+this could lead to load imbalance.
+
+%% =================================================================================================
+\subsubsection{Round-robin distribution of observations among processors}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_obsdist_global}
+  \caption[Observations with the round-robin distribution]{
+    Example of the distribution of observations with
+    the round-robin distribution of observational data.}
+  \label{fig:OBS_global}
+\end{figure}
+
+An alternative approach is to distribute the observations equally among processors and
+use message passing in order to retrieve the stencil for interpolation.
+The simplest distribution of the observations is to distribute them using a round-robin scheme.
+\autoref{fig:OBS_global} shows the distribution of the {\em in situ} data on processors for
+the round-robin distribution of observations with a different colour for each observation on a given processor for
+a 4 $\times$ 2 decomposition with ORCA2 for the same input data as in \autoref{fig:OBS_local}.
+The observations are now clearly randomly distributed on the globe.
+In order to be able to perform horizontal interpolation in this case,
+a subroutine has been developed that retrieves any grid points in the global space.
+
+%% =================================================================================================
+\subsection{Vertical interpolation operator}
+
+Vertical interpolation is achieved using either a cubic spline or linear interpolation.
+For the cubic spline, the top and bottom boundary conditions for the second derivative of
+the interpolating polynomial in the spline are set to zero.
+At the bottom boundary, this is done using the land-ocean mask.
+
+For profile observation types we do both vertical and horizontal interpolation. \NEMO\ has a generalised vertical coordinate system this means the vertical level depths can vary with location. Therefore, it is necessary first to perform vertical interpolation of the model value to the observation depths for each of the four surrounding grid points. After this the model values, at these points, at the observation depth, are horizontally interpolated to the observation location.
+
+%\usepackage{framed}
+
+%% =================================================================================================
+\section{Standalone observation operator (\texttt{SAO})}
+\label{sec:OBS_sao}
+
+%% =================================================================================================
+\subsection{Concept}
+
+The observation operator maps model variables to observation space. This is normally done while the model is running, i.e. online, it is possible to apply this mapping offline without running the model with the \textbf{standalone observation operator} (SAO). The process is divided into an initialisation phase, an interpolation phase and an output phase.
+During the interpolation phase the SAO populates the model arrays by
+reading saved model fields from disk. The interpolation and the output phases use the same OBS code described in the preceding sections.
+
+There are two ways of exploiting the standalone capacity.
+The first is to mimic the behaviour of the online system by supplying model fields at
+regular intervals between the start and the end of the run.
+This approach results in a single model counterpart per observation.
+This kind of usage produces feedback files the same file format as the online observation operator.
+The second is to take advantage of the ability to run offline by calculating
+multiple model counterparts for each observation.
+In this case it is possible to consider all forecasts verifying at the same time.
+By forecast, we mean any method which produces an estimate of physical reality which is not an observed value.
+
+% sao.exe
+
+%% =================================================================================================
+\subsection{Using the standalone observation operator}
+
+%% =================================================================================================
+\subsubsection{Building}
+
+In addition to \emph{OPA\_SRC} the SAO requires the inclusion of the \emph{SAO\_SRC} directory.
+\emph{SAO\_SRC} contains a replacement \mdl{nemo} and \mdl{nemogcm} which
+overwrites the resultant \textbf{nemo.exe}.
+Note this a similar approach to that taken by the standalone surface scheme \emph{SAS\_SRC} and the offline TOP model \emph{OFF\_SRC}.
+
+% Running
+%% =================================================================================================
+\subsubsection{Running}
+
+The simplest way to use the executable is to edit and append the \textbf{sao.nml} namelist to
+a full \NEMO\ namelist and then to run the executable as if it were nemo.exe.
+
+% Configuration section
+%% =================================================================================================
+\subsection{Configuring the standalone observation operator}
+The observation files and settings understood by \nam{obs}{obs} have been outlined in the online observation operator section.
+In addition is a further namelist \nam{sao}{sao} which used to set the input model fields for the SAO
+
+%% =================================================================================================
+\subsubsection{Single field}
+
+In the SAO the model arrays are populated at appropriate time steps via input files.
+At present, \textbf{tsn} and \textbf{sshn} are populated by the default read routines.
+These routines will be expanded upon in future versions to allow the specification of any model variable.
+As such, input files must be global versions of the model domain with
+\textbf{votemper}, \textbf{vosaline} and optionally \textbf{sshn} present.
+
+For each field read there must be an entry in the \nam{sao}{sao} namelist specifying
+the name of the file to read and the index along the \emph{time\_counter}.
+For example, to read the second time counter from a single file the namelist would be.
+
+\begin{forlines}
+!----------------------------------------------------------------------
+!       namsao Standalone obs_oper namelist
+!----------------------------------------------------------------------
+!   sao_files    specifies the files containing the model counterpart
+!   nn_sao_idx   specifies the time_counter index within the model file
+&namsao
+   sao_files = "foo.nc"
+   nn_sao_idx = 2
+/
+\end{forlines}
+
+%% =================================================================================================
+\subsubsection{Multiple fields per run}
+
+Model field iteration is controlled via \textbf{nn\_sao\_freq} which
+specifies the number of model steps at which the next field gets read.
+For example, if 12 hourly fields are to be interpolated in a setup where 288 steps equals 24 hours.
+
+\begin{forlines}
+!----------------------------------------------------------------------
+!       namsao Standalone obs_oper namelist
+!----------------------------------------------------------------------
+!   sao_files    specifies the files containing the model counterpart
+!   nn_sao_idx   specifies the time_counter index within the model file
+!   nn_sao_freq  specifies number of time steps between read operations
+&namsao
+   sao_files = "foo.nc" "foo.nc"
+   nn_sao_idx = 1 2
+   nn_sao_freq = 144
+/
+\end{forlines}
+
+The above namelist will result in feedback files whose first 12 hours contain the first field of foo.nc and
+the second 12 hours contain the second field.
+
+%\begin{framed}
+\textbf{Note} Missing files can be denoted as "nofile".
+%\end{framed}
+
+A collection of fields taken from a number of files at different indices can be combined at
+a particular frequency in time to generate a pseudo model evolution.
+If all that is needed is a single model counterpart at a regular interval then
+the standard SAO is all that is required.
+However, just to note, it is possible to extend this approach by comparing multiple forecasts, analyses, persisted analyses and
+climatologies with the same set of observations.
+This approach is referred to as \emph{Class 4} since it is the fourth metric defined by the GODAE intercomparison project. This requires multiple runs of the SAO and running an additional utility (not currently in the \NEMO\ repository) to combine the feedback files into one class 4 file.
+
+%% =================================================================================================
+\section{Observation utilities}
+\label{sec:OBS_obsutils}
+
+For convenience some tools for viewing and processing of observation and feedback files are provided in
+the \NEMO\ repository.
+These tools include OBSTOOLS which are a collection of \fortran\ programs which are helpful to deal with feedback files.
+They do such tasks as observation file conversion, printing of file contents,
+some basic statistical analysis of feedback files.
+The other main tool is an IDL program called dataplot which uses a graphical interface to
+visualise observations and feedback files.
+OBSTOOLS and dataplot are described in more detail below.
+
+%% =================================================================================================
+\subsection{Obstools}
+
+A series of \fortran\ utilities is provided with \NEMO\ called OBSTOOLS.
+This are helpful in handling observation files and the feedback file output from the observation operator. A brief description of some of the utilities follows
+
+%% =================================================================================================
+\subsubsection{corio2fb}
+
+The program corio2fb converts profile observation files from the Coriolis format to the standard feedback format.
+It is called in the following way:
+
+\begin{cmds}
+corio2fb.exe outputfile inputfile1 inputfile2 ...
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{enact2fb}
+
+The program enact2fb converts profile observation files from the ENACT format to the standard feedback format.
+It is called in the following way:
+
+\begin{cmds}
+enact2fb.exe outputfile inputfile1 inputfile2 ...
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbcomb}
+
+The program fbcomb combines multiple feedback files produced by individual processors in
+an MPI run of \NEMO\ into a single feedback file.
+It is called in the following way:
+
+\begin{cmds}
+fbcomb.exe outputfile inputfile1 inputfile2 ...
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbmatchup}
+
+The program fbmatchup will match observations from two feedback files.
+It is called in the following way:
+
+\begin{cmds}
+fbmatchup.exe outputfile inputfile1 varname1 inputfile2 varname2 ...
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbprint}
+
+The program fbprint will print the contents of a feedback file or files to standard output.
+Selected information can be output using optional arguments.
+It is called in the following way:
+
+\begin{cmds}
+fbprint.exe [options] inputfile
+
+options:
+     -b            shorter output
+     -q            Select observations based on QC flags
+     -Q            Select observations based on QC flags
+     -B            Select observations based on QC flags
+     -u            unsorted
+     -s ID         select station ID
+     -t TYPE       select observation type
+     -v NUM1-NUM2  select variable range to print by number
+                      (default all)
+     -a NUM1-NUM2  select additional variable range to print by number
+                      (default all)
+     -e NUM1-NUM2  select extra variable range to print by number
+                      (default all)
+     -d            output date range
+     -D            print depths
+     -z            use zipped files
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbsel}
+
+The program fbsel will select or subsample observations.
+It is called in the following way:
+
+\begin{cmds}
+fbsel.exe <input filename> <output filename>
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbstat}
+
+The program fbstat will output summary statistics in different global areas into a number of files.
+It is called in the following way:
+
+\begin{cmds}
+fbstat.exe [-nmlev] <filenames>
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{fbthin}
+
+The program fbthin will thin the data to 1 degree resolution.
+The code could easily be modified to thin to a different resolution.
+It is called in the following way:
+
+\begin{cmds}
+fbthin.exe inputfile outputfile
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{sla2fb}
+
+The program sla2fb will convert an AVISO SLA format file to feedback format.
+It is called in the following way:
+
+\begin{cmds}
+sla2fb.exe [-s type] outputfile inputfile1 inputfile2 ...
+
+Option:
+     -s            Select altimeter data_source
+\end{cmds}
+
+%% =================================================================================================
+\subsubsection{vel2fb}
+
+The program vel2fb will convert TAO/PIRATA/RAMA currents files to feedback format.
+It is called in the following way:
+
+\begin{cmds}
+vel2fb.exe outputfile inputfile1 inputfile2 ...
+\end{cmds}
+
+%% =================================================================================================
+\subsection{Building the obstools}
+
+To build the obstools use in the tools directory use ./maketools -n OBSTOOLS -m [ARCH].
+
+%% =================================================================================================
+\subsection{Dataplot}
+
+An IDL program called dataplot is included which uses a graphical interface to
+visualise observations and feedback files. Note a similar package has recently developed in python (also called dataplot) which does some of the same things that the IDL dataplot does. Please contact the authors of the this chapter if you are interested in this.
+
+It is possible to zoom in, plot individual profiles and calculate some basic statistics.
+To plot some data run IDL and then:
+
+\begin{minted}{idl}
+IDL> dataplot, "filename"
+\end{minted}
+
+To read multiple files into dataplot,
+for example multiple feedback files from different processors or from different days,
+the easiest method is to use the spawn command to generate a list of files which can then be passed to dataplot.
+
+\begin{minted}{idl}
+IDL> spawn, 'ls profb*.nc', files
+IDL> dataplot, files
+\end{minted}
+
+\autoref{fig:OBS_dataplotmain} shows the main window which is launched when dataplot starts.
+This is split into three parts.
+At the top there is a menu bar which contains a variety of drop down menus.
+Areas - zooms into prespecified regions;
+plot - plots the data as a timeseries or a T-S diagram if appropriate;
+Find - allows data to be searched;
+Config - sets various configuration options.
+
+The middle part is a plot of the geographical location of the observations.
+This will plot the observation value, the model background value or observation minus background value depending on
+the option selected in the radio button at the bottom of the window.
+The plotting colour range can be changed by clicking on the colour bar.
+The title of the plot gives some basic information about the date range and depth range shown,
+the extreme values, and the mean and RMS values.
+It is possible to zoom in using a drag-box.
+You may also zoom in or out using the mouse wheel.
+
+The bottom part of the window controls what is visible in the plot above.
+There are two bars which select the level range plotted (for profile data).
+The other bars below select the date range shown.
+The bottom of the figure allows the option to plot the mean, root mean square, standard deviation or
+mean square values.
+As mentioned above you can choose to plot the observation value, the model background value or
+observation minus background value.
+The next group of radio buttons selects the map projection.
+This can either be regular longitude latitude grid, or north or south polar stereographic.
+The next group of radio buttons will plot bad observations, switch to salinity and
+plot density for profile observations.
+The rightmost group of buttons will print the plot window as a postscript, save it as png, or exit from dataplot.
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_dataplot_main}
+  \caption{Main window of dataplot}
+  \label{fig:OBS_dataplotmain}
+\end{figure}
+
+If a profile point is clicked with the mouse button a plot of the observation and background values as
+a function of depth (\autoref{fig:OBS_dataplotprofile}).
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{OBS_dataplot_prof}
+  \caption[Profile plot from dataplot]{
+    Profile plot from dataplot produced by right clicking on a point in the main window}
+  \label{fig:OBS_dataplotprofile}
+\end{figure}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_SBC.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_SBC.tex	(revision 14097)
@@ -0,0 +1,1543 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Surface Boundary Condition (SBC, SAS, ISF, ICB)}
+\label{chap:SBC}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+\begin{listing}
+  \nlst{namsbc}
+  \caption{\forcode{&namsbc}}
+  \label{lst:namsbc}
+\end{listing}
+
+The ocean needs seven fields as surface boundary condition:
+
+\begin{itemize}
+\item the two components of the surface ocean stress $\left( {\tau_u \;,\;\tau_v} \right)$
+\item the incoming solar and non solar heat fluxes $\left( {Q_{ns} \;,\;Q_{sr} } \right)$
+\item the surface freshwater budget $\left( {\textit{emp}} \right)$
+\item the surface salt flux associated with freezing/melting of seawater $\left( {\textit{sfx}} \right)$
+\item the atmospheric pressure at the ocean surface $\left( p_a \right)$
+\end{itemize}
+
+Four different ways are available to provide the seven fields to the ocean. They are controlled by
+namelist \nam{sbc}{sbc} variables:
+
+\begin{itemize}
+\item a bulk formulation (\np[=.true.]{ln_blk}{ln\_blk} with four possible bulk algorithms),
+\item a flux formulation (\np[=.true.]{ln_flx}{ln\_flx}),
+\item a coupled or mixed forced/coupled formulation (exchanges with a atmospheric model via the OASIS coupler),
+(\np{ln_cpl}{ln\_cpl} or \np[=.true.]{ln_mixcpl}{ln\_mixcpl}),
+\item a user defined formulation (\np[=.true.]{ln_usr}{ln\_usr}).
+\end{itemize}
+
+The frequency at which the forcing fields have to be updated is given by the \np{nn_fsbc}{nn\_fsbc} namelist parameter.
+
+When the fields are supplied from data files (bulk, flux and mixed formulations),
+the input fields do not need to be supplied on the model grid.
+Instead, a file of coordinates and weights can be supplied to map the data from the input fields grid to
+the model points (so called "Interpolation on the Fly", see \autoref{subsec:SBC_iof}).
+If the "Interpolation on the Fly" option is used, input data belonging to land points (in the native grid)
+should be masked or filled to avoid spurious results in proximity of the coasts, as
+large sea-land gradients characterize most of the atmospheric variables.
+
+In addition, the resulting fields can be further modified using several namelist options.
+These options control:
+
+\begin{itemize}
+\item the rotation of vector components supplied relative to an east-north coordinate system onto
+  the local grid directions in the model,
+\item the use of a land/sea mask for input fields (\np[=.true.]{nn_lsm}{nn\_lsm}),
+\item the addition of a surface restoring term to observed SST and/or SSS (\np[=.true.]{ln_ssr}{ln\_ssr}),
+\item the modification of fluxes below ice-covered areas (using climatological ice-cover or a sea-ice model)
+  (\np[=0..3]{nn_ice}{nn\_ice}),
+\item the addition of river runoffs as surface freshwater fluxes or lateral inflow (\np[=.true.]{ln_rnf}{ln\_rnf}),
+\item the addition of ice-shelf melting as lateral inflow (parameterisation) or
+  as fluxes applied at the land-ice ocean interface (\np[=.true.]{ln_isf}{ln\_isf}),
+\item the addition of a freshwater flux adjustment in order to avoid a mean sea-level drift
+  (\np[=0..2]{nn_fwb}{nn\_fwb}),
+\item the transformation of the solar radiation (if provided as daily mean) into an analytical diurnal cycle
+  (\np[=.true.]{ln_dm2dc}{ln\_dm2dc}),
+\item the activation of wave effects from an external wave model  (\np[=.true.]{ln_wave}{ln\_wave}),
+\item a neutral drag coefficient is read from an external wave model (\np[=.true.]{ln_cdgw}{ln\_cdgw}),
+\item the Stokes drift from an external wave model is accounted for (\np[=.true.]{ln_sdw}{ln\_sdw}),
+\item the choice of the Stokes drift profile parameterization (\np[=0..2]{nn_sdrift}{nn\_sdrift}),
+\item the surface stress given to the ocean is modified by surface waves (\np[=.true.]{ln_tauwoc}{ln\_tauwoc}),
+\item the surface stress given to the ocean is read from an external wave model (\np[=.true.]{ln_tauw}{ln\_tauw}),
+\item the Stokes-Coriolis term is included (\np[=.true.]{ln_stcor}{ln\_stcor}),
+\item the light penetration in the ocean (\np[=.true.]{ln_traqsr}{ln\_traqsr} with namelist \nam{tra_qsr}{tra\_qsr}),
+\item the atmospheric surface pressure gradient effect on ocean and ice dynamics (\np[=.true.]{ln_apr_dyn}{ln\_apr\_dyn} with namelist \nam{sbc_apr}{sbc\_apr}),
+\item the effect of sea-ice pressure on the ocean (\np[=.true.]{ln_ice_embd}{ln\_ice\_embd}).
+\end{itemize}
+
+In this chapter, we first discuss where the surface boundary conditions appear in the model equations.
+Then we present the three ways of providing the surface boundary conditions,
+followed by the description of the atmospheric pressure and the river runoff.
+Next, the scheme for interpolation on the fly is described.
+Finally, the different options that further modify the fluxes applied to the ocean are discussed.
+One of these is modification by icebergs (see \autoref{sec:SBC_ICB_icebergs}),
+which act as drifting sources of fresh water.
+Another example of modification is that due to the ice shelf melting/freezing (see \autoref{sec:SBC_isf}),
+which provides additional sources of fresh water.
+
+%% =================================================================================================
+\section{Surface boundary condition for the ocean}
+\label{sec:SBC_ocean}
+
+The surface ocean stress is the stress exerted by the wind and the sea-ice on the ocean.
+It is applied in \mdl{dynzdf} module as a surface boundary condition of the computation of
+the momentum vertical mixing trend (see \autoref{eq:DYN_zdf_sbc} in \autoref{sec:DYN_zdf}).
+As such, it has to be provided as a 2D vector interpolated onto the horizontal velocity ocean mesh,
+\ie\ resolved onto the model (\textbf{i},\textbf{j}) direction at $u$- and $v$-points.
+
+The surface heat flux is decomposed into two parts, a non solar and a solar heat flux,
+$Q_{ns}$ and $Q_{sr}$, respectively.
+The former is the non penetrative part of the heat flux
+(\ie\ the sum of sensible, latent and long wave heat fluxes plus
+the heat content of the mass exchange between the ocean and sea-ice).
+It is applied in \mdl{trasbc} module as a surface boundary condition trend of
+the first level temperature time evolution equation
+(see \autoref{eq:TRA_sbc} and \autoref{eq:TRA_sbc_lin} in \autoref{subsec:TRA_sbc}).
+The latter is the penetrative part of the heat flux.
+It is applied as a 3D trend of the temperature equation (\mdl{traqsr} module) when
+\np[=.true.]{ln_traqsr}{ln\_traqsr}.
+The way the light penetrates inside the water column is generally a sum of decreasing exponentials
+(see \autoref{subsec:TRA_qsr}).
+
+The surface freshwater budget is provided by the \textit{emp} field.
+It represents the mass flux exchanged with the atmosphere (evaporation minus precipitation) and
+possibly with the sea-ice and ice shelves (freezing minus melting of ice).
+It affects the ocean in two different ways:
+$(i)$  it changes the volume of the ocean, and therefore appears in the sea surface height equation as		%GS: autoref ssh equation to be added
+a volume flux, and
+$(ii)$ it changes the surface temperature and salinity through the heat and salt contents of
+the mass exchanged with atmosphere, sea-ice and ice shelves.
+
+%\colorbox{yellow}{Miss: }
+%A extensive description of all namsbc namelist (parameter that have to be
+%created!)
+%Especially the \np{nn_fsbc}{nn\_fsbc}, the \mdl{sbc\_oce} module (fluxes + mean sst sss ssu
+%ssv) \ie\ information required by flux computation or sea-ice
+%\mdl{sbc\_oce} containt the definition in memory of the 7 fields (6+runoff), add
+%a word on runoff: included in surface bc or add as lateral obc{\ldots}.
+%Sbcmod manage the ``providing'' (fourniture) to the ocean the 7 fields
+%Fluxes update only each nf\_sbc time step (namsbc) explain relation
+%between nf\_sbc and nf\_ice, do we define nf\_blk??? ? only one
+%nf\_sbc
+%Explain here all the namlist namsbc variable{\ldots}.
+% explain : use or not of surface currents
+%\colorbox{yellow}{End Miss }
+
+The ocean model provides, at each time step, to the surface module (\mdl{sbcmod})
+the surface currents, temperature and salinity.
+These variables are averaged over \np{nn_fsbc}{nn\_fsbc} time-step (\autoref{tab:SBC_ssm}), and
+these averaged fields are used to compute the surface fluxes at the frequency of \np{nn_fsbc}{nn\_fsbc} time-steps.
+
+\begin{table}[tb]
+  \centering
+  \begin{tabular}{|l|l|l|l|}
+    \hline
+    Variable description			                  & Model variable	& Units	& point                 \\
+    \hline
+    i-component of the surface current	& ssu\_m	              & $m.s^{-1}$	    & U     \\
+    \hline
+    j-component of the surface current	& ssv\_m	              & $m.s^{-1}$	    & V     \\
+    \hline
+    Sea surface temperature			         & sst\_m	              & \r{}$K$	             & T     \\\hline
+    Sea surface salinty			                  & sss\_m	              & $psu$		        & T     \\	\hline
+  \end{tabular}
+  \caption[Ocean variables provided to the surface module)]{
+    Ocean variables provided to the surface module (\texttt{SBC}).
+    The variable are averaged over \protect\np{nn_fsbc}{nn\_fsbc} time-step,
+    \ie\ the frequency of computation of surface fluxes.}
+  \label{tab:SBC_ssm}
+\end{table}
+
+%\colorbox{yellow}{Penser a} mettre dans le restant l'info nn\_fsbc ET nn\_fsbc*rdt de sorte de reinitialiser la moyenne si on change la frequence ou le pdt
+
+%% =================================================================================================
+\section{Input data generic interface}
+\label{sec:SBC_input}
+
+A generic interface has been introduced to manage the way input data
+(2D or 3D fields, like surface forcing or ocean T and S) are specified in \NEMO.
+This task is achieved by \mdl{fldread}.
+The module is designed with four main objectives in mind:
+\begin{enumerate}
+\item optionally provide a time interpolation of the input data every specified model time-step, whatever their input frequency is,
+  and according to the different calendars available in the model.
+\item optionally provide an on-the-fly space interpolation from the native input data grid to the model grid.
+\item make the run duration independent from the period cover by the input files.
+\item provide a simple user interface and a rather simple developer interface by
+  limiting the number of prerequisite informations.
+\end{enumerate}
+
+As a result, the user has only to fill in for each variable a structure in the namelist file to
+define the input data file and variable names, the frequency of the data (in hours or months),
+whether its is climatological data or not, the period covered by the input file (one year, month, week or day),
+and three additional parameters for the on-the-fly interpolation.
+When adding a new input variable, the developer has to add the associated structure in the namelist,
+read this information by mirroring the namelist read in \rou{sbc\_blk\_init} for example,
+and simply call \rou{fld\_read} to obtain the desired input field at the model time-step and grid points.
+
+The only constraints are that the input file is a NetCDF file, the file name follows a nomenclature
+(see \autoref{subsec:SBC_fldread}), the period it cover is one year, month, week or day, and,
+if on-the-fly interpolation is used, a file of weights must be supplied (see \autoref{subsec:SBC_iof}).
+
+Note that when an input data is archived on a disc which is accessible directly from the workspace where
+the code is executed, then the user can set the \np{cn_dir}{cn\_dir} to the pathway leading to the data.
+By default, the data are assumed to be in the same directory as the executable, so that cn\_dir='./'.
+
+%% =================================================================================================
+\subsection[Input data specification (\textit{fldread.F90})]{Input data specification (\protect\mdl{fldread})}
+\label{subsec:SBC_fldread}
+
+The structure associated with an input variable contains the following information:
+\begin{forlines}
+!  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      !
+\end{forlines}
+where
+\begin{description}
+\item [File name]: the stem name of the NetCDF file to be opened.
+  This stem will be completed automatically by the model, with the addition of a '.nc' at its end and
+  by date information and possibly a prefix (when using AGRIF).
+  \autoref{tab:SBC_fldread} provides the resulting file name in all possible cases according to
+  whether it is a climatological file or not, and to the open/close frequency (see below for definition).
+  \begin{table}[htbp]
+    \centering
+    \begin{tabular}{|l|c|c|c|}
+      \hline
+                                  &  daily or weekLL     &  monthly           &  yearly        \\
+      \hline
+      \np[=.false.]{clim}{clim} &  fn\_yYYYYmMMdDD.nc  &  fn\_yYYYYmMM.nc   &  fn\_yYYYY.nc  \\
+      \hline
+      \np[=.true.]{clim}{clim}  &  not possible        &  fn\_m??.nc        &  fn            \\
+      \hline
+    \end{tabular}
+    \caption[Naming nomenclature for climatological or interannual input file]{
+      Naming nomenclature for climatological or interannual input file,
+      as a function of the open/close frequency.
+      The stem name is assumed to be 'fn'.
+      For weekly files, the 'LLL' corresponds to the first three letters of the first day of the week
+      (\ie\ 'sun','sat','fri','thu','wed','tue','mon').
+      The 'YYYY', 'MM' and 'DD' should be replaced by the actual year/month/day,
+      always coded with 4 or 2 digits.
+      Note that (1) in mpp, if the file is split over each subdomain,
+      the suffix '.nc' is replaced by '\_PPPP.nc',
+      where 'PPPP' is the process number coded with 4 digits;
+      (2) when using AGRIF, the prefix '\_N' is added to files, where 'N' is the child grid number.
+    }
+    \label{tab:SBC_fldread}
+  \end{table}
+\item [Record frequency]: the frequency of the records contained in the input file.
+  Its unit is in hours if it is positive (for example 24 for daily forcing) or in months if negative
+  (for example -1 for monthly forcing or -12 for annual forcing).
+  Note that this frequency must REALLY be an integer and not a real.
+  On some computers, setting it to '24.' can be interpreted as 240!
+\item [Variable name]: the name of the variable to be read in the input NetCDF file.
+\item [Time interpolation]: a logical to activate, or not, the time interpolation.
+  If set to 'false', the forcing will have a steplike shape remaining constant during each forcing period.
+  For example, when using a daily forcing without time interpolation, the forcing remaining constant from
+  00h00'00'' to 23h59'59".
+  If set to 'true', the forcing will have a broken line shape.
+  Records are assumed to be dated at the middle of the forcing period.
+  For example, when using a daily forcing with time interpolation,
+  linear interpolation will be performed between mid-day of two consecutive days.
+\item [Climatological forcing]: a logical to specify if a input file contains climatological forcing which can be cycle in time,
+  or an interannual forcing which will requires additional files if
+  the period covered by the simulation exceeds the one of the file.
+  See the above file naming strategy which impacts the expected name of the file to be opened.
+\item [Open/close frequency]: the frequency at which forcing files must be opened/closed.
+  Four cases are coded:
+  'daily', 'weekLLL' (with 'LLL' the first 3 letters of the first day of the week), 'monthly' and 'yearly' which
+  means the forcing files will contain data for one day, one week, one month or one year.
+  Files are assumed to contain data from the beginning of the open/close period.
+  For example, the first record of a yearly file containing daily data is Jan 1st even if
+  the experiment is not starting at the beginning of the year.
+\item [Others]:  'weights filename', 'pairing rotation' and 'land/sea mask' are associated with
+  on-the-fly interpolation which is described in \autoref{subsec:SBC_iof}.
+\end{description}
+
+Additional remarks:\\
+(1) The time interpolation is a simple linear interpolation between two consecutive records of the input data.
+The only tricky point is therefore to specify the date at which we need to do the interpolation and
+the date of the records read in the input files.
+Following \citet{leclair.madec_OM09}, the date of a time step is set at the middle of the time step.
+For example, for an experiment starting at 0h00'00" with a one-hour time-step,
+a time interpolation will be performed at the following time: 0h30'00", 1h30'00", 2h30'00", etc.
+However, for forcing data related to the surface module,
+values are not needed at every time-step but at every \np{nn_fsbc}{nn\_fsbc} time-step.
+For example with \np[=3]{nn_fsbc}{nn\_fsbc}, the surface module will be called at time-steps 1, 4, 7, etc.
+The date used for the time interpolation is thus redefined to the middle of \np{nn_fsbc}{nn\_fsbc} time-step period.
+In the previous example, this leads to: 1h30'00", 4h30'00", 7h30'00", etc. \\
+(2) For code readablility and maintenance issues, we don't take into account the NetCDF input file calendar.
+The calendar associated with the forcing field is build according to the information provided by
+user in the record frequency, the open/close frequency and the type of temporal interpolation.
+For example, the first record of a yearly file containing daily data that will be interpolated in time is assumed to
+start Jan 1st at 12h00'00" and end Dec 31st at 12h00'00". \\
+(3) If a time interpolation is requested, the code will pick up the needed data in the previous (next) file when
+interpolating data with the first (last) record of the open/close period.
+For example, if the input file specifications are ''yearly, containing daily data to be interpolated in time'',
+the values given by the code between 00h00'00" and 11h59'59" on Jan 1st will be interpolated values between
+Dec 31st 12h00'00" and Jan 1st 12h00'00".
+If the forcing is climatological, Dec and Jan will be keep-up from the same year.
+However, if the forcing is not climatological, at the end of
+the open/close period, the code will automatically close the current file and open the next one.
+Note that, if the experiment is starting (ending) at the beginning (end) of
+an open/close period, we do accept that the previous (next) file is not existing.
+In this case, the time interpolation will be performed between two identical values.
+For example, when starting an experiment on Jan 1st of year Y with yearly files and daily data to be interpolated,
+we do accept that the file related to year Y-1 is not existing.
+The value of Jan 1st will be used as the missing one for Dec 31st of year Y-1.
+If the file of year Y-1 exists, the code will read its last record.
+Therefore, this file can contain only one record corresponding to Dec 31st,
+a useful feature for user considering that it is too heavy to manipulate the complete file for year Y-1.
+
+%% =================================================================================================
+\subsection{Interpolation on-the-fly}
+\label{subsec:SBC_iof}
+
+Interpolation on the Fly allows the user to supply input files required for the surface forcing on
+grids other than the model grid.
+To do this, he or she must supply, in addition to the source data file(s), a file of weights to be used to
+interpolate from the data grid to the model grid.
+The original development of this code used the SCRIP package
+(freely available \href{http://climate.lanl.gov/Software/SCRIP}{here} under a copyright agreement).
+In principle, any package such as CDO can be used to generate the weights, but the variables in
+the input weights file must have the same names and meanings as assumed by the model.
+Two methods are currently available: bilinear and bicubic interpolations.
+Prior to the interpolation, providing a land/sea mask file, the user can decide to remove land points from
+the input file and substitute the corresponding values with the average of the 8 neighbouring points in
+the native external grid.
+Only "sea points" are considered for the averaging.
+The land/sea mask file must be provided in the structure associated with the input variable.
+The netcdf land/sea mask variable name must be 'LSM' and must have the same horizontal and vertical dimensions as
+the associated variables and should be equal to 1 over land and 0 elsewhere.
+The procedure can be recursively applied by setting nn\_lsm > 1 in namsbc namelist.
+Note that nn\_lsm=0 forces the code to not apply the procedure, even if a land/sea mask file is supplied.
+
+%% =================================================================================================
+\subsubsection{Bilinear interpolation}
+\label{subsec:SBC_iof_bilinear}
+
+The input weights file in this case has two sets of variables:
+src01, src02, src03, src04 and wgt01, wgt02, wgt03, wgt04.
+The "src" variables correspond to the point in the input grid to which the weight "wgt" is applied.
+Each src value is an integer corresponding to the index of a point in the input grid when
+written as a one dimensional array.
+For example, for an input grid of size 5x10, point (3,2) is referenced as point 8, since (2-1)*5+3=8.
+There are four of each variable because bilinear interpolation uses the four points defining
+the grid box containing the point to be interpolated.
+All of these arrays are on the model grid, so that values src01(i,j) and wgt01(i,j) are used to
+generate a value for point (i,j) in the model.
+
+Symbolically, the algorithm used is:
+\[
+  f_{m}(i,j) = f_{m}(i,j) + \sum_{k=1}^{4} {wgt(k)f(idx(src(k)))}
+\]
+where function idx() transforms a one dimensional index src(k) into a two dimensional index,
+and wgt(1) corresponds to variable "wgt01" for example.
+
+%% =================================================================================================
+\subsubsection{Bicubic interpolation}
+\label{subsec:SBC_iof_bicubic}
+
+Again, there are two sets of variables: "src" and "wgt".
+But in this case, there are 16 of each.
+The symbolic algorithm used to calculate values on the model grid is now:
+
+\[
+  \begin{split}
+    f_{m}(i,j) =  f_{m}(i,j) +& \sum_{k=1}^{4} {wgt(k)f(idx(src(k)))}
+    +  \sum_{k=5 }^{8 } {wgt(k)\left.\frac{\partial f}{\partial i}\right| _{idx(src(k))} }    \\
+    +& \sum_{k=9 }^{12} {wgt(k)\left.\frac{\partial f}{\partial j}\right| _{idx(src(k))} }
+    +  \sum_{k=13}^{16} {wgt(k)\left.\frac{\partial ^2 f}{\partial i \partial j}\right| _{idx(src(k))} }
+  \end{split}
+\]
+The gradients here are taken with respect to the horizontal indices and not distances since
+the spatial dependency has been included into the weights.
+
+%% =================================================================================================
+\subsubsection{Implementation}
+\label{subsec:SBC_iof_imp}
+
+To activate this option, a non-empty string should be supplied in
+the weights filename column of the relevant namelist;
+if this is left as an empty string no action is taken.
+In the model, weights files are read in and stored in a structured type (WGT) in the fldread module,
+as and when they are first required.
+This initialisation procedure determines whether the input data grid should be treated as cyclical or not by
+inspecting a global attribute stored in the weights input file.
+This attribute must be called "ew\_wrap" and be of integer type.
+If it is negative, the input non-model grid is assumed to be not cyclic.
+If zero or greater, then the value represents the number of columns that overlap.
+$E.g.$ if the input grid has columns at longitudes 0, 1, 2, .... , 359, then ew\_wrap should be set to 0;
+if longitudes are 0.5, 2.5, .... , 358.5, 360.5, 362.5, ew\_wrap should be 2.
+If the model does not find attribute ew\_wrap, then a value of -999 is assumed.
+In this case, the \rou{fld\_read} routine defaults ew\_wrap to value 0 and
+therefore the grid is assumed to be cyclic with no overlapping columns.
+(In fact, this only matters when bicubic interpolation is required.)
+Note that no testing is done to check the validity in the model,
+since there is no way of knowing the name used for the longitude variable,
+so it is up to the user to make sure his or her data is correctly represented.
+
+Next the routine reads in the weights.
+Bicubic interpolation is assumed if it finds a variable with name "src05", otherwise bilinear interpolation is used.
+The WGT structure includes dynamic arrays both for the storage of the weights (on the model grid),
+and when required, for reading in the variable to be interpolated (on the input data grid).
+The size of the input data array is determined by examining the values in the "src" arrays to
+find the minimum and maximum i and j values required.
+Since bicubic interpolation requires the calculation of gradients at each point on the grid,
+the corresponding arrays are dimensioned with a halo of width one grid point all the way around.
+When the array of points from the data file is adjacent to an edge of the data grid,
+the halo is either a copy of the row/column next to it (non-cyclical case),
+or is a copy of one from the first few columns on the opposite side of the grid (cyclical case).
+
+%% =================================================================================================
+\subsubsection{Limitations}
+\label{subsec:SBC_iof_lim}
+
+\begin{enumerate}
+\item The case where input data grids are not logically rectangular (irregular grid case) has not been tested.
+\item This code is not guaranteed to produce positive definite answers from positive definite inputs when
+  a bicubic interpolation method is used.
+\item The cyclic condition is only applied on left and right columns, and not to top and bottom rows.
+\item The gradients across the ends of a cyclical grid assume that the grid spacing between
+  the two columns involved are consistent with the weights used.
+\item Neither interpolation scheme is conservative. (There is a conservative scheme available in SCRIP,
+  but this has not been implemented.)
+\end{enumerate}
+
+%% =================================================================================================
+\subsubsection{Utilities}
+\label{subsec:SBC_iof_util}
+
+% to be completed
+A set of utilities to create a weights file for a rectilinear input grid is available
+(see the directory NEMOGCM/TOOLS/WEIGHTS).
+
+%% =================================================================================================
+\subsection{Standalone surface boundary condition scheme (SAS)}
+\label{subsec:SBC_SAS}
+
+\begin{listing}
+  \nlst{namsbc_sas}
+  \caption{\forcode{&namsbc_sas}}
+  \label{lst:namsbc_sas}
+\end{listing}
+
+In some circumstances, it may be useful to avoid calculating the 3D temperature,
+salinity and velocity fields and simply read them in from a previous run or receive them from OASIS.
+For example:
+
+\begin{itemize}
+\item Multiple runs of the model are required in code development to
+  see the effect of different algorithms in the bulk formulae.
+\item The effect of different parameter sets in the ice model is to be examined.
+\item Development of sea-ice algorithms or parameterizations.
+\item Spinup of the iceberg floats
+\item Ocean/sea-ice simulation with both models running in parallel (\np[=.true.]{ln_mixcpl}{ln\_mixcpl})
+\end{itemize}
+
+The Standalone Surface scheme provides this capacity.
+Its options are defined through the \nam{sbc_sas}{sbc\_sas} namelist variables.
+A new copy of the model has to be compiled with a configuration based on ORCA2\_SAS\_LIM.
+However, no namelist parameters need be changed from the settings of the previous run (except perhaps nn\_date0).
+In this configuration, a few routines in the standard model are overriden by new versions.
+Routines replaced are:
+
+\begin{itemize}
+\item \mdl{nemogcm}: This routine initialises the rest of the model and repeatedly calls the stp time stepping routine (\mdl{step}).
+  Since the ocean state is not calculated all associated initialisations have been removed.
+\item \mdl{step}: The main time stepping routine now only needs to call the sbc routine (and a few utility functions).
+\item \mdl{sbcmod}: This has been cut down and now only calculates surface forcing and the ice model required.
+  New surface modules that can function when only the surface level of the ocean state is defined can also be added
+  (\eg\ icebergs).
+\item \mdl{daymod}: No ocean restarts are read or written (though the ice model restarts are retained),
+  so calls to restart functions have been removed.
+  This also means that the calendar cannot be controlled by time in a restart file,
+  so the user must check that nn\_date0 in the model namelist is correct for his or her purposes.
+\item \mdl{stpctl}: Since there is no free surface solver, references to it have been removed from \rou{stp\_ctl} module.
+\item \mdl{diawri}: All 3D data have been removed from the output.
+  The surface temperature, salinity and velocity components (which have been read in) are written along with
+  relevant forcing and ice data.
+\end{itemize}
+
+One new routine has been added:
+
+\begin{itemize}
+\item \mdl{sbcsas}: This module initialises the input files needed for reading temperature, salinity and
+  velocity arrays at the surface.
+  These filenames are supplied in namelist namsbc\_sas.
+  Unfortunately, because of limitations with the \mdl{iom} module,
+  the full 3D fields from the mean files have to be read in and interpolated in time,
+  before using just the top level.
+  Since fldread is used to read in the data, Interpolation on the Fly may be used to change input data resolution.
+\end{itemize}
+
+The user can also choose in the \nam{sbc_sas}{sbc\_sas} namelist to read the mean (nn\_fsbc time-step) fraction of solar net radiation absorbed in the 1st T level using
+ (\np[=.true.]{ln_flx}{ln\_flx}) and to provide 3D oceanic velocities instead of 2D ones (\np{ln_flx}{ln\_flx}\forcode{=.true.}). In that last case, only the 1st level will be read in.
+
+%% =================================================================================================
+\section[Flux formulation (\textit{sbcflx.F90})]{Flux formulation (\protect\mdl{sbcflx})}
+\label{sec:SBC_flx}
+
+\begin{listing}
+  \nlst{namsbc_flx}
+  \caption{\forcode{&namsbc_flx}}
+  \label{lst:namsbc_flx}
+\end{listing}
+
+In the flux formulation (\np[=.true.]{ln_flx}{ln\_flx}),
+the surface boundary condition fields are directly read from input files.
+The user has to define in the namelist \nam{sbc_flx}{sbc\_flx} the name of the file,
+the name of the variable read in the file, the time frequency at which it is given (in hours),
+and a logical setting whether a time interpolation to the model time step is required for this field.
+See \autoref{subsec:SBC_fldread} for a more detailed description of the parameters.
+
+Note that in general, a flux formulation is used in associated with a restoring term to observed SST and/or SSS.
+See \autoref{subsec:SBC_ssr} for its specification.
+
+%% =================================================================================================
+\section[Bulk formulation (\textit{sbcblk.F90})]{Bulk formulation (\protect\mdl{sbcblk})}
+\label{sec:SBC_blk}
+
+\begin{listing}
+  \nlst{namsbc_blk}
+  \caption{\forcode{&namsbc_blk}}
+  \label{lst:namsbc_blk}
+\end{listing}
+
+In the bulk formulation, the surface boundary condition fields are computed with bulk formulae using atmospheric fields
+and ocean (and sea-ice) variables averaged over \np{nn_fsbc}{nn\_fsbc} time-step.
+
+The atmospheric fields used depend on the bulk formulae used.
+In forced mode, when a sea-ice model is used, a specific bulk formulation is used.
+Therefore, different bulk formulae are used for the turbulent fluxes computation
+over the ocean and over sea-ice surface.
+For the ocean, four bulk formulations are available thanks to the \href{https://brodeau.github.io/aerobulk/}{Aerobulk} package (\citet{brodeau.barnier.ea_JPO16}):
+the NCAR (formerly named CORE), COARE 3.0, COARE 3.5 and ECMWF bulk formulae.
+The choice is made by setting to true one of the following namelist variable:
+ \np{ln_NCAR}{ln\_NCAR}, \np{ln_COARE_3p0}{ln\_COARE\_3p0},  \np{ln_COARE_3p5}{ln\_COARE\_3p5} and  \np{ln_ECMWF}{ln\_ECMWF}.
+For sea-ice, three possibilities can be selected:
+a constant transfer coefficient (1.4e-3; default value), \citet{lupkes.gryanik.ea_JGR12} (\np{ln_Cd_L12}{ln\_Cd\_L12}), and \citet{lupkes.gryanik_JGR15} (\np{ln_Cd_L15}{ln\_Cd\_L15}) parameterizations
+
+Common options are defined through the \nam{sbc_blk}{sbc\_blk} namelist variables.
+The required 9 input fields are:
+
+\begin{table}[htbp]
+  \centering
+  \begin{tabular}{|l|c|c|c|}
+    \hline
+    Variable description                 & Model variable & Units              & point \\
+    \hline
+    i-component of the 10m air velocity  & utau           & $m.s^{-1}$         & T     \\
+    \hline
+    j-component of the 10m air velocity  & vtau           & $m.s^{-1}$         & T     \\
+    \hline
+    10m air temperature                  & tair           & \r{}$K$            & T     \\
+    \hline
+    Specific humidity                    & humi           & \%                 & T     \\
+    \hline
+    Incoming long wave radiation         & qlw            & $W.m^{-2}$         & T     \\
+    \hline
+    Incoming short wave radiation        & qsr            & $W.m^{-2}$         & T     \\
+    \hline
+    Total precipitation (liquid + solid) & precip         & $Kg.m^{-2}.s^{-1}$ & T     \\
+    \hline
+    Solid precipitation                  & snow           & $Kg.m^{-2}.s^{-1}$ & T     \\
+    \hline
+    Mean sea-level pressure              & slp            & $hPa$              & T     \\
+    \hline
+    \end{tabular}
+  \label{tab:SBC_BULK}
+\end{table}
+
+Note that the air velocity is provided at a tracer ocean point, not at a velocity ocean point ($u$- and $v$-points).
+It is simpler and faster (less fields to be read), but it is not the recommended method when
+the ocean grid size is the same or larger than the one of the input atmospheric fields.
+
+The \np{sn_wndi}{sn\_wndi}, \np{sn_wndj}{sn\_wndj}, \np{sn_qsr}{sn\_qsr}, \np{sn_qlw}{sn\_qlw}, \np{sn_tair}{sn\_tair}, \np{sn_humi}{sn\_humi}, \np{sn_prec}{sn\_prec},
+\np{sn_snow}{sn\_snow}, \np{sn_tdif}{sn\_tdif} parameters describe the fields and the way they have to be used
+(spatial and temporal interpolations).
+
+\np{cn_dir}{cn\_dir} is the directory of location of bulk files
+\np{ln_taudif}{ln\_taudif} is the flag to specify if we use Hight Frequency (HF) tau information (.true.) or not (.false.)
+\np{rn_zqt}{rn\_zqt}: is the height of humidity and temperature measurements (m)
+\np{rn_zu}{rn\_zu}: is the height of wind measurements (m)
+
+Three multiplicative factors are available:
+\np{rn_pfac}{rn\_pfac} and \np{rn_efac}{rn\_efac} allow to adjust (if necessary) the global freshwater budget by
+increasing/reducing the precipitations (total and snow) and or evaporation, respectively.
+The third one,\np{rn_vfac}{rn\_vfac}, control to which extend the ice/ocean velocities are taken into account in
+the calculation of surface wind stress.
+Its range must be between zero and one, and it is recommended to set it to 0 at low-resolution (ORCA2 configuration).
+
+As for the flux formulation, information about the input data required by the model is provided in
+the namsbc\_blk namelist (see \autoref{subsec:SBC_fldread}).
+
+%% =================================================================================================
+\subsection[Ocean-Atmosphere Bulk formulae (\textit{sbcblk\_algo\_coare.F90, sbcblk\_algo\_coare3p5.F90, sbcblk\_algo\_ecmwf.F90, sbcblk\_algo\_ncar.F90})]{Ocean-Atmosphere Bulk formulae (\mdl{sbcblk\_algo\_coare}, \mdl{sbcblk\_algo\_coare3p5}, \mdl{sbcblk\_algo\_ecmwf}, \mdl{sbcblk\_algo\_ncar})}
+\label{subsec:SBC_blk_ocean}
+
+Four different bulk algorithms are available to compute surface turbulent momentum and heat fluxes over the ocean.
+COARE 3.0, COARE 3.5 and ECMWF schemes mainly differ by their roughness lenghts computation and consequently
+their neutral transfer coefficients relationships with neutral wind.
+\begin{itemize}
+\item NCAR (\np[=.true.]{ln_NCAR}{ln\_NCAR}): The NCAR bulk formulae have been developed by \citet{large.yeager_rpt04}.
+  They have been designed to handle the NCAR forcing, a mixture of NCEP reanalysis and satellite data.
+  They use an inertial dissipative method to compute the turbulent transfer coefficients
+  (momentum, sensible heat and evaporation) from the 10m wind speed, air temperature and specific humidity.
+  This \citet{large.yeager_rpt04} dataset is available through
+  the \href{http://nomads.gfdl.noaa.gov/nomads/forms/mom4/NCAR.html}{GFDL web site}.
+  Note that substituting ERA40 to NCEP reanalysis fields does not require changes in the bulk formulea themself.
+  This is the so-called DRAKKAR Forcing Set (DFS) \citep{brodeau.barnier.ea_OM10}.
+\item COARE 3.0 (\np[=.true.]{ln_COARE_3p0}{ln\_COARE\_3p0}): See \citet{fairall.bradley.ea_JC03} for more details
+\item COARE 3.5 (\np[=.true.]{ln_COARE_3p5}{ln\_COARE\_3p5}): See \citet{edson.jampana.ea_JPO13} for more details
+\item ECMWF (\np[=.true.]{ln_ECMWF}{ln\_ECMWF}): Based on \href{https://www.ecmwf.int/node/9221}{IFS (Cy31)} implementation and documentation.
+  Surface roughness lengths needed for the Obukhov length are computed following \citet{beljaars_QJRMS95}.
+\end{itemize}
+
+%% =================================================================================================
+\subsection{Ice-Atmosphere Bulk formulae}
+\label{subsec:SBC_blk_ice}
+
+Surface turbulent fluxes between sea-ice and the atmosphere can be computed in three different ways:
+
+\begin{itemize}
+\item Constant value (\np[ Cd_ice=1.4e-3 ]{constant value}{constant\ value}):
+  default constant value used for momentum and heat neutral transfer coefficients
+\item \citet{lupkes.gryanik.ea_JGR12} (\np[=.true.]{ln_Cd_L12}{ln\_Cd\_L12}):
+  This scheme adds a dependency on edges at leads, melt ponds and flows
+  of the constant neutral air-ice drag. After some approximations,
+  this can be resumed to a dependency on ice concentration (A).
+  This drag coefficient has a parabolic shape (as a function of ice concentration)
+  starting at 1.5e-3 for A=0, reaching 1.97e-3 for A=0.5 and going down 1.4e-3 for A=1.
+  It is theoretically applicable to all ice conditions (not only MIZ).
+\item \citet{lupkes.gryanik_JGR15} (\np[=.true.]{ln_Cd_L15}{ln\_Cd\_L15}):
+  Alternative turbulent transfer coefficients formulation between sea-ice
+  and atmosphere with distinct momentum and heat coefficients depending
+  on sea-ice concentration and atmospheric stability (no melt-ponds effect for now).
+  The parameterization is adapted from ECHAM6 atmospheric model.
+  Compared to Lupkes2012 scheme, it considers specific skin and form drags
+  to compute neutral transfer coefficients for both heat and momentum fluxes.
+  Atmospheric stability effect on transfer coefficient is also taken into account.
+\end{itemize}
+
+%% =================================================================================================
+\section[Coupled formulation (\textit{sbccpl.F90})]{Coupled formulation (\protect\mdl{sbccpl})}
+\label{sec:SBC_cpl}
+
+\begin{listing}
+  \nlst{namsbc_cpl}
+  \caption{\forcode{&namsbc_cpl}}
+  \label{lst:namsbc_cpl}
+\end{listing}
+
+In the coupled formulation of the surface boundary condition,
+the fluxes are provided by the OASIS coupler at a frequency which is defined in the OASIS coupler namelist,
+while sea and ice surface temperature, ocean and ice albedo, and ocean currents are sent to
+the atmospheric component.
+
+A generalised coupled interface has been developed.
+It is currently interfaced with OASIS-3-MCT versions 1 to 4 (\key{oasis3}).
+An additional specific CPP key (\key{oa3mct\_v1v2}) is needed for OASIS-3-MCT versions 1 and 2.
+It has been successfully used to interface \NEMO\ to most of the European atmospheric GCM
+(ARPEGE, ECHAM, ECMWF, HadAM, HadGAM, LMDz), as well as to \href{http://wrf-model.org/}{WRF}
+(Weather Research and Forecasting Model).
+
+When PISCES biogeochemical model (\key{top}) is also used in the coupled system,
+the whole carbon cycle is computed.
+In this case, CO$_2$ fluxes will be exchanged between the atmosphere and the ice-ocean system
+(and need to be activated in \nam{sbc_cpl}{sbc\_cpl} ).
+
+The namelist above allows control of various aspects of the coupling fields (particularly for vectors) and
+now allows for any coupling fields to have multiple sea ice categories (as required by LIM3 and CICE).
+When indicating a multi-category coupling field in \nam{sbc_cpl}{sbc\_cpl}, the number of categories will be determined by
+the number used in the sea ice model.
+In some limited cases, it may be possible to specify single category coupling fields even when
+the sea ice model is running with multiple categories -
+in this case, the user should examine the code to be sure the assumptions made are satisfactory.
+In cases where this is definitely not possible, the model should abort with an error message.
+
+%% =================================================================================================
+\section[Atmospheric pressure (\textit{sbcapr.F90})]{Atmospheric pressure (\protect\mdl{sbcapr})}
+\label{sec:SBC_apr}
+
+\begin{listing}
+  \nlst{namsbc_apr}
+  \caption{\forcode{&namsbc_apr}}
+  \label{lst:namsbc_apr}
+\end{listing}
+
+The optional atmospheric pressure can be used to force ocean and ice dynamics
+(\np[=.true.]{ln_apr_dyn}{ln\_apr\_dyn}, \nam{sbc}{sbc} namelist).
+The input atmospheric forcing defined via \np{sn_apr}{sn\_apr} structure (\nam{sbc_apr}{sbc\_apr} namelist)
+can be interpolated in time to the model time step, and even in space when the interpolation on-the-fly is used.
+When used to force the dynamics, the atmospheric pressure is further transformed into
+an equivalent inverse barometer sea surface height, $\eta_{ib}$, using:
+\[
+  % \label{eq:SBC_ssh_ib}
+  \eta_{ib} = -  \frac{1}{g\,\rho_o}  \left( P_{atm} - P_o \right)
+\]
+where $P_{atm}$ is the atmospheric pressure and $P_o$ a reference atmospheric pressure.
+A value of $101,000~N/m^2$ is used unless \np{ln_ref_apr}{ln\_ref\_apr} is set to true.
+In this case, $P_o$ is set to the value of $P_{atm}$ averaged over the ocean domain,
+\ie\ the mean value of $\eta_{ib}$ is kept to zero at all time steps.
+
+The gradient of $\eta_{ib}$ is added to the RHS of the ocean momentum equation (see \mdl{dynspg} for the ocean).
+For sea-ice, the sea surface height, $\eta_m$, which is provided to the sea ice model is set to $\eta - \eta_{ib}$
+(see \mdl{sbcssr} module).
+$\eta_{ib}$ can be written in the output.
+This can simplify altimetry data and model comparison as
+inverse barometer sea surface height is usually removed from these date prior to their distribution.
+
+When using time-splitting and BDY package for open boundaries conditions,
+the equivalent inverse barometer sea surface height $\eta_{ib}$ can be added to BDY ssh data:
+\np{ln_apr_obc}{ln\_apr\_obc}  might be set to true.
+
+%% =================================================================================================
+\section[Surface tides (\textit{sbctide.F90})]{Surface tides (\protect\mdl{sbctide})}
+\label{sec:SBC_tide}
+
+\begin{listing}
+  \nlst{nam_tide}
+  \caption{\forcode{&nam_tide}}
+  \label{lst:nam_tide}
+\end{listing}
+
+The tidal forcing, generated by the gravity forces of the Earth-Moon and Earth-Sun sytems,
+is activated if \np{ln_tide}{ln\_tide} and \np{ln_tide_pot}{ln\_tide\_pot} are both set to \forcode{.true.} in \nam{_tide}{\_tide}.
+This translates as an additional barotropic force in the momentum \autoref{eq:MB_PE_dyn} such that:
+\[
+  % \label{eq:SBC_PE_dyn_tides}
+  \frac{\partial {\mathrm {\mathbf U}}_h }{\partial t}= ...
+  +g\nabla (\Pi_{eq} + \Pi_{sal})
+\]
+where $\Pi_{eq}$ stands for the equilibrium tidal forcing and
+$\Pi_{sal}$ is a self-attraction and loading term (SAL).
+
+The equilibrium tidal forcing is expressed as a sum over a subset of
+constituents chosen from the set of available tidal constituents
+defined in file \hf{SBC/tide} (this comprises the tidal
+constituents \textit{M2, N2, 2N2, S2, K2, K1, O1, Q1, P1, M4, Mf, Mm,
+  Msqm, Mtm, S1, MU2, NU2, L2}, and \textit{T2}). Individual
+constituents are selected by including their names in the array
+\np{clname}{clname} in \nam{_tide}{\_tide} (e.g., \np{clname}{clname}\forcode{(1)='M2', }
+\np{clname}{clname}\forcode{(2)='S2'} to select solely the tidal consituents \textit{M2}
+and \textit{S2}). Optionally, when \np{ln_tide_ramp}{ln\_tide\_ramp} is set to
+\forcode{.true.}, the equilibrium tidal forcing can be ramped up
+linearly from zero during the initial \np{rdttideramp}{rdttideramp} days of the
+model run.
+
+The SAL term should in principle be computed online as it depends on
+the model tidal prediction itself (see \citet{arbic.garner.ea_DSR04} for a
+discussion about the practical implementation of this term).
+Nevertheless, the complex calculations involved would make this
+computationally too expensive. Here, two options are available:
+$\Pi_{sal}$ generated by an external model can be read in
+(\np[=.true.]{ln_read_load}{ln\_read\_load}), or a ``scalar approximation'' can be
+used (\np[=.true.]{ln_scal_load}{ln\_scal\_load}). In the latter case
+\[
+  \Pi_{sal} = \beta \eta,
+\]
+where $\beta$ (\np{rn_scal_load}{rn\_scal\_load} with a default value of 0.094) is a
+spatially constant scalar, often chosen to minimize tidal prediction
+errors. Setting both \np{ln_read_load}{ln\_read\_load} and \np{ln_scal_load}{ln\_scal\_load} to
+\forcode{.false.} removes the SAL contribution.
+
+%% =================================================================================================
+\section[River runoffs (\textit{sbcrnf.F90})]{River runoffs (\protect\mdl{sbcrnf})}
+\label{sec:SBC_rnf}
+
+\begin{listing}
+  \nlst{namsbc_rnf}
+  \caption{\forcode{&namsbc_rnf}}
+  \label{lst:namsbc_rnf}
+\end{listing}
+
+%River runoff generally enters the ocean at a nonzero depth rather than through the surface.
+%Many models, however, have traditionally inserted river runoff to the top model cell.
+%This was the case in \NEMO\ prior to the version 3.3. The switch toward a input of runoff
+%throughout a nonzero depth has been motivated by the numerical and physical problems
+%that arise when the top grid cells are of the order of one meter. This situation is common in
+%coastal modelling and becomes more and more often open ocean and climate modelling
+%\footnote{At least a top cells thickness of 1~meter and a 3 hours forcing frequency are
+%required to properly represent the diurnal cycle \citep{bernie.woolnough.ea_JC05}. see also \autoref{fig:SBC_dcy}.}.
+
+%To do this we need to treat evaporation/precipitation fluxes and river runoff differently in the
+%\mdl{tra\_sbc} module.  We decided to separate them throughout the code, so that the variable
+%\textit{emp} represented solely evaporation minus precipitation fluxes, and a new 2d variable
+%rnf was added which represents the volume flux of river runoff (in kg/m2s to remain consistent with
+%emp).  This meant many uses of emp and emps needed to be changed, a list of all modules which use
+%emp or emps and the changes made are below:
+
+%Rachel:
+River runoff generally enters the ocean at a nonzero depth rather than through the surface.
+Many models, however, have traditionally inserted river runoff to the top model cell.
+This was the case in \NEMO\ prior to the version 3.3,
+and was combined with an option to increase vertical mixing near the river mouth.
+
+However, with this method numerical and physical problems arise when the top grid cells are of the order of one meter.
+This situation is common in coastal modelling and is becoming more common in open ocean and climate modelling
+\footnote{
+  At least a top cells thickness of 1~meter and a 3 hours forcing frequency are required to
+  properly represent the diurnal cycle \citep{bernie.woolnough.ea_JC05}.
+  see also \autoref{fig:SBC_dcy}.}.
+
+As such from V~3.3 onwards it is possible to add river runoff through a non-zero depth,
+and for the temperature and salinity of the river to effect the surrounding ocean.
+The user is able to specify, in a NetCDF input file, the temperature and salinity of the river,
+along with the depth (in metres) which the river should be added to.
+
+Namelist variables in \nam{sbc_rnf}{sbc\_rnf}, \np{ln_rnf_depth}{ln\_rnf\_depth}, \np{ln_rnf_sal}{ln\_rnf\_sal} and
+\np{ln_rnf_temp}{ln\_rnf\_temp} control whether the river attributes (depth, salinity and temperature) are read in and used.
+If these are set as false the river is added to the surface box only, assumed to be fresh (0~psu),
+and/or taken as surface temperature respectively.
+
+The runoff value and attributes are read in in sbcrnf.
+For temperature -999 is taken as missing data and the river temperature is taken to
+be the surface temperatue at the river point.
+For the depth parameter a value of -1 means the river is added to the surface box only,
+and a value of -999 means the river is added through the entire water column.
+After being read in the temperature and salinity variables are multiplied by the amount of runoff
+(converted into m/s) to give the heat and salt content of the river runoff.
+After the user specified depth is read ini,
+the number of grid boxes this corresponds to is calculated and stored in the variable \np{nz_rnf}{nz\_rnf}.
+The variable \textit{h\_dep} is then calculated to be the depth (in metres) of
+the bottom of the lowest box the river water is being added to
+(\ie\ the total depth that river water is being added to in the model).
+
+The mass/volume addition due to the river runoff is, at each relevant depth level, added to
+the horizontal divergence (\textit{hdivn}) in the subroutine \rou{sbc\_rnf\_div} (called from \mdl{divhor}).
+This increases the diffusion term in the vicinity of the river, thereby simulating a momentum flux.
+The sea surface height is calculated using the sum of the horizontal divergence terms,
+and so the river runoff indirectly forces an increase in sea surface height.
+
+The \textit{hdivn} terms are used in the tracer advection modules to force vertical velocities.
+This causes a mass of water, equal to the amount of runoff, to be moved into the box above.
+The heat and salt content of the river runoff is not included in this step,
+and so the tracer concentrations are diluted as water of ocean temperature and salinity is moved upward out of
+the box and replaced by the same volume of river water with no corresponding heat and salt addition.
+
+For the linear free surface case, at the surface box the tracer advection causes a flux of water
+(of equal volume to the runoff) through the sea surface out of the domain,
+which causes a salt and heat flux out of the model.
+As such the volume of water does not change, but the water is diluted.
+
+For the non-linear free surface case, no flux is allowed through the surface.
+Instead in the surface box (as well as water moving up from the boxes below) a volume of runoff water is added with
+no corresponding heat and salt addition and so as happens in the lower boxes there is a dilution effect.
+(The runoff addition to the top box along with the water being moved up through
+boxes below means the surface box has a large increase in volume, whilst all other boxes remain the same size)
+
+In trasbc the addition of heat and salt due to the river runoff is added.
+This is done in the same way for both vvl and non-vvl.
+The temperature and salinity are increased through the specified depth according to
+the heat and salt content of the river.
+
+In the non-linear free surface case (vvl),
+near the end of the time step the change in sea surface height is redistrubuted through the grid boxes,
+so that the original ratios of grid box heights are restored.
+In doing this water is moved into boxes below, throughout the water column,
+so the large volume addition to the surface box is spread between all the grid boxes.
+
+It is also possible for runnoff to be specified as a negative value for modelling flow through straits,
+\ie\ modelling the Baltic flow in and out of the North Sea.
+When the flow is out of the domain there is no change in temperature and salinity,
+regardless of the namelist options used,
+as the ocean water leaving the domain removes heat and salt (at the same concentration) with it.
+
+%\colorbox{yellow}{Nevertheless, Pb of vertical resolution and 3D input : increase vertical mixing near river mouths to mimic a 3D river
+
+%All river runoff and emp fluxes are assumed to be fresh water (zero salinity) and at the same temperature as the sea surface.}
+
+%\colorbox{yellow}{river mouths{\ldots}}
+
+%IF( ln_rnf ) THEN                                     ! increase diffusivity at rivers mouths
+%        DO jk = 2, nkrnf   ;   avt(:,:,jk) = avt(:,:,jk) + rn_avt_rnf * rnfmsk(:,:)   ;   END DO
+%ENDIF
+
+\cmtgm{  word doc of runoffs:
+In the current \NEMO\ setup river runoff is added to emp fluxes,
+these are then applied at just the sea surface as a volume change (in the variable volume case
+this is a literal volume change, and in the linear free surface case the free surface is moved)
+and a salt flux due to the concentration/dilution effect.
+There is also an option to increase vertical mixing near river mouths;
+this gives the effect of having a 3d river.
+All river runoff and emp fluxes are assumed to be fresh water (zero salinity) and
+at the same temperature as the sea surface.
+Our aim was to code the option to specify the temperature and salinity of river runoff,
+(as well as the amount), along with the depth that the river water will affect.
+This would make it possible to model low salinity outflow, such as the Baltic,
+and would allow the ocean temperature to be affected by river runoff.
+
+The depth option makes it possible to have the river water affecting just the surface layer,
+throughout depth, or some specified point in between.
+
+To do this we need to treat evaporation/precipitation fluxes and river runoff differently in
+the \mdl{tra_sbc} module.
+We decided to separate them throughout the code,
+so that the variable emp represented solely evaporation minus precipitation fluxes,
+and a new 2d variable rnf was added which represents the volume flux of river runoff
+(in $kg/m^2s$ to remain consistent with $emp$).
+This meant many uses of emp and emps needed to be changed,
+a list of all modules which use $emp$ or $emps$ and the changes made are below:}
+
+%% =================================================================================================
+\section[Ice shelf melting (\textit{sbcisf.F90})]{Ice shelf melting (\protect\mdl{sbcisf})}
+\label{sec:SBC_isf}
+
+\begin{listing}
+  \nlst{namsbc_isf}
+  \caption{\forcode{&namsbc_isf}}
+  \label{lst:namsbc_isf}
+\end{listing}
+
+The namelist variable in \nam{sbc}{sbc}, \np{nn_isf}{nn\_isf}, controls the ice shelf representation.
+Description and result of sensitivity test to \np{nn_isf}{nn\_isf} are presented in \citet{mathiot.jenkins.ea_GMD17}.
+The different options are illustrated in \autoref{fig:SBC_isf}.
+
+\begin{description}
+  \item [{\np[=1]{nn_isf}{nn\_isf}}]: The ice shelf cavity is represented (\np[=.true.]{ln_isfcav}{ln\_isfcav} needed).
+  The fwf and heat flux are depending of the local water properties.
+
+  Two different bulk formulae are available:
+
+  \begin{description}
+  \item [{\np[=1]{nn_isfblk}{nn\_isfblk}}]: The melt rate is based on a balance between the upward ocean heat flux and
+    the latent heat flux at the ice shelf base. A complete description is available in \citet{hunter_rpt06}.
+  \item [{\np[=2]{nn_isfblk}{nn\_isfblk}}]: The melt rate and the heat flux are based on a 3 equations formulation
+    (a heat flux budget at the ice base, a salt flux budget at the ice base and a linearised freezing point temperature equation).
+    A complete description is available in \citet{jenkins_JGR91}.
+  \end{description}
+
+  Temperature and salinity used to compute the melt are the average temperature in the top boundary layer \citet{losch_JGR08}.
+  Its thickness is defined by \np{rn_hisf_tbl}{rn\_hisf\_tbl}.
+  The fluxes and friction velocity are computed using the mean temperature, salinity and velocity in the the first \np{rn_hisf_tbl}{rn\_hisf\_tbl} m.
+  Then, the fluxes are spread over the same thickness (ie over one or several cells).
+  If \np{rn_hisf_tbl}{rn\_hisf\_tbl} larger than top $e_{3}t$, there is no more feedback between the freezing point at the interface and the the top cell temperature.
+  This can lead to super-cool temperature in the top cell under melting condition.
+  If \np{rn_hisf_tbl}{rn\_hisf\_tbl} smaller than top $e_{3}t$, the top boundary layer thickness is set to the top cell thickness.\\
+
+  Each melt bulk formula depends on a exchange coeficient ($\Gamma^{T,S}$) between the ocean and the ice.
+  There are 3 different ways to compute the exchange coeficient:
+  \begin{description}
+  \item [{\np[=0]{nn_gammablk}{nn\_gammablk}}]: The salt and heat exchange coefficients are constant and defined by \np{rn_gammas0}{rn\_gammas0} and \np{rn_gammat0}{rn\_gammat0}.
+    \begin{gather*}
+       % \label{eq:SBC_isf_gamma_iso}
+      \gamma^{T} = rn\_gammat0 \\
+      \gamma^{S} = rn\_gammas0
+    \end{gather*}
+    This is the recommended formulation for ISOMIP.
+  \item [{\np[=1]{nn_gammablk}{nn\_gammablk}}]: The salt and heat exchange coefficients are velocity dependent and defined as
+    \begin{gather*}
+      \gamma^{T} = rn\_gammat0 \times u_{*} \\
+      \gamma^{S} = rn\_gammas0 \times u_{*}
+    \end{gather*}
+    where $u_{*}$ is the friction velocity in the top boundary layer (ie first \np{rn_hisf_tbl}{rn\_hisf\_tbl} meters).
+    See \citet{jenkins.nicholls.ea_JPO10} for all the details on this formulation. It is the recommended formulation for realistic application.
+  \item [{\np[=2]{nn_gammablk}{nn\_gammablk}}]: The salt and heat exchange coefficients are velocity and stability dependent and defined as:
+    \[
+      \gamma^{T,S} = \frac{u_{*}}{\Gamma_{Turb} + \Gamma^{T,S}_{Mole}}
+    \]
+    where $u_{*}$ is the friction velocity in the top boundary layer (ie first \np{rn_hisf_tbl}{rn\_hisf\_tbl} meters),
+    $\Gamma_{Turb}$ the contribution of the ocean stability and
+    $\Gamma^{T,S}_{Mole}$ the contribution of the molecular diffusion.
+    See \citet{holland.jenkins_JPO99} for all the details on this formulation.
+    This formulation has not been extensively tested in \NEMO\ (not recommended).
+  \end{description}
+\item [{\np[=2]{nn_isf}{nn\_isf}}]: The ice shelf cavity is not represented.
+  The fwf and heat flux are computed using the \citet{beckmann.goosse_OM03} parameterisation of isf melting.
+  The fluxes are distributed along the ice shelf edge between the depth of the average grounding line (GL)
+  (\np{sn_depmax_isf}{sn\_depmax\_isf}) and the base of the ice shelf along the calving front
+  (\np{sn_depmin_isf}{sn\_depmin\_isf}) as in (\np[=3]{nn_isf}{nn\_isf}).
+  The effective melting length (\np{sn_Leff_isf}{sn\_Leff\_isf}) is read from a file.
+\item [{\np[=3]{nn_isf}{nn\_isf}}]: The ice shelf cavity is not represented.
+  The fwf (\np{sn_rnfisf}{sn\_rnfisf}) is prescribed and distributed along the ice shelf edge between
+  the depth of the average grounding line (GL) (\np{sn_depmax_isf}{sn\_depmax\_isf}) and
+  the base of the ice shelf along the calving front (\np{sn_depmin_isf}{sn\_depmin\_isf}).
+  The heat flux ($Q_h$) is computed as $Q_h = fwf \times L_f$.
+\item [{\np[=4]{nn_isf}{nn\_isf}}]: The ice shelf cavity is opened (\np[=.true.]{ln_isfcav}{ln\_isfcav} needed).
+  However, the fwf is not computed but specified from file \np{sn_fwfisf}{sn\_fwfisf}).
+  The heat flux ($Q_h$) is computed as $Q_h = fwf \times L_f$.
+  As in \np[=1]{nn_isf}{nn\_isf}, the fluxes are spread over the top boundary layer thickness (\np{rn_hisf_tbl}{rn\_hisf\_tbl})
+\end{description}
+
+$\bullet$ \np[=1]{nn_isf}{nn\_isf} and \np[=2]{nn_isf}{nn\_isf} compute a melt rate based on
+the water mass properties, ocean velocities and depth.
+This flux is thus highly dependent of the model resolution (horizontal and vertical),
+realism of the water masses onto the shelf ...\\
+
+$\bullet$ \np[=3]{nn_isf}{nn\_isf} and \np[=4]{nn_isf}{nn\_isf} read the melt rate from a file.
+You have total control of the fwf forcing.
+This can be useful if the water masses on the shelf are not realistic or
+the resolution (horizontal/vertical) are too coarse to have realistic melting or
+for studies where you need to control your heat and fw input.\\
+
+The ice shelf melt is implemented as a volume flux as for the runoff.
+The fw addition due to the ice shelf melting is, at each relevant depth level, added to
+the horizontal divergence (\textit{hdivn}) in the subroutine \rou{sbc\_isf\_div}, called from \mdl{divhor}.
+See the runoff section \autoref{sec:SBC_rnf} for all the details about the divergence correction.\\
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{SBC_isf}
+  \caption[Ice shelf location and fresh water flux definition]{
+    Illustration of the location where the fwf is injected and
+    whether or not the fwf is interactif or not depending of \protect\np{nn_isf}{nn\_isf}.}
+  \label{fig:SBC_isf}
+\end{figure}
+
+%% =================================================================================================
+\section{Ice sheet coupling}
+\label{sec:SBC_iscpl}
+
+\begin{listing}
+  \nlst{namsbc_iscpl}
+  \caption{\forcode{&namsbc_iscpl}}
+  \label{lst:namsbc_iscpl}
+\end{listing}
+
+Ice sheet/ocean coupling is done through file exchange at the restart step.
+At each restart step:
+
+\begin{enumerate}
+\item the ice sheet model send a new bathymetry and ice shelf draft netcdf file.
+\item a new domcfg.nc file is built using the DOMAINcfg tools.
+\item \NEMO\ run for a specific period and output the average melt rate over the period.
+\item the ice sheet model run using the melt rate outputed in step 4.
+\item go back to 1.
+\end{enumerate}
+
+If \np[=.true.]{ln_iscpl}{ln\_iscpl}, the isf draft is assume to be different at each restart step with
+potentially some new wet/dry cells due to the ice sheet dynamics/thermodynamics.
+The wetting and drying scheme applied on the restart is very simple and described below for the 6 different possible cases:
+
+\begin{description}
+\item [Thin a cell down]: T/S/ssh are unchanged and U/V in the top cell are corrected to keep the barotropic transport (bt) constant
+  ($bt_b=bt_n$).
+\item [Enlarge  a cell]: See case "Thin a cell down"
+\item [Dry a cell]: mask, T/S, U/V and ssh are set to 0.
+  Furthermore, U/V into the water column are modified to satisfy ($bt_b=bt_n$).
+\item [Wet a cell]: mask is set to 1, T/S is extrapolated from neighbours, $ssh_n = ssh_b$ and U/V set to 0.
+  If no neighbours, T/S is extrapolated from old top cell value.
+  If no neighbours along i,j and k (both previous test failed), T/S/U/V/ssh and mask are set to 0.
+\item [Dry a column]: mask, T/S, U/V are set to 0 everywhere in the column and ssh set to 0.
+\item [Wet a column]: set mask to 1, T/S is extrapolated from neighbours, ssh is extrapolated from neighbours and U/V set to 0.
+  If no neighbour, T/S/U/V and mask set to 0.
+\end{description}
+
+Furthermore, as the before and now fields are not compatible (modification of the geometry),
+the restart time step is prescribed to be an euler time step instead of a leap frog and $fields_b = fields_n$.\\
+
+The horizontal extrapolation to fill new cell with realistic value is called \np{nn_drown}{nn\_drown} times.
+It means that if the grounding line retreat by more than \np{nn_drown}{nn\_drown} cells between 2 coupling steps,
+the code will be unable to fill all the new wet cells properly.
+The default number is set up for the MISOMIP idealised experiments.
+This coupling procedure is able to take into account grounding line and calving front migration.
+However, it is a non-conservative processe.
+This could lead to a trend in heat/salt content and volume.\\
+
+In order to remove the trend and keep the conservation level as close to 0 as possible,
+a simple conservation scheme is available with \np[=.true.]{ln_hsb}{ln\_hsb}.
+The heat/salt/vol. gain/loss is diagnosed, as well as the location.
+A correction increment is computed and apply each time step during the next \np{rn_fiscpl}{rn\_fiscpl} time steps.
+For safety, it is advised to set \np{rn_fiscpl}{rn\_fiscpl} equal to the coupling period (smallest increment possible).
+The corrective increment is apply into the cell itself (if it is a wet cell), the neigbouring cells or the closest wet cell (if the cell is now dry).
+
+%% =================================================================================================
+\section{Handling of icebergs (ICB)}
+\label{sec:SBC_ICB_icebergs}
+
+\begin{listing}
+  \nlst{namberg}
+  \caption{\forcode{&namberg}}
+  \label{lst:namberg}
+\end{listing}
+
+Icebergs are modelled as lagrangian particles in \NEMO\ \citep{marsh.ivchenko.ea_GMD15}.
+Their physical behaviour is controlled by equations as described in \citet{martin.adcroft_OM10} ).
+(Note that the authors kindly provided a copy of their code to act as a basis for implementation in \NEMO).
+Icebergs are initially spawned into one of ten classes which have specific mass and thickness as
+described in the \nam{berg}{berg} namelist: \np{rn_initial_mass}{rn\_initial\_mass} and \np{rn_initial_thickness}{rn\_initial\_thickness}.
+Each class has an associated scaling (\np{rn_mass_scaling}{rn\_mass\_scaling}),
+which is an integer representing how many icebergs of this class are being described as one lagrangian point
+(this reduces the numerical problem of tracking every single iceberg).
+They are enabled by setting \np[=.true.]{ln_icebergs}{ln\_icebergs}.
+
+Two initialisation schemes are possible.
+\begin{description}
+\item [{\np{nn_test_icebergs}{nn\_test\_icebergs}~$>$~0}] In this scheme, the value of \np{nn_test_icebergs}{nn\_test\_icebergs} represents the class of iceberg to generate
+  (so between 1 and 10), and \np{nn_test_icebergs}{nn\_test\_icebergs} provides a lon/lat box in the domain at each grid point of
+  which an iceberg is generated at the beginning of the run.
+  (Note that this happens each time the timestep equals \np{nn_nit000}{nn\_nit000}.)
+  \np{nn_test_icebergs}{nn\_test\_icebergs} is defined by four numbers in \np{nn_test_box}{nn\_test\_box} representing the corners of
+  the geographical box: lonmin,lonmax,latmin,latmax
+\item [{\np[=-1]{nn_test_icebergs}{nn\_test\_icebergs}}] In this scheme, the model reads a calving file supplied in the \np{sn_icb}{sn\_icb} parameter.
+  This should be a file with a field on the configuration grid (typically ORCA)
+  representing ice accumulation rate at each model point.
+  These should be ocean points adjacent to land where icebergs are known to calve.
+  Most points in this input grid are going to have value zero.
+  When the model runs, ice is accumulated at each grid point which has a non-zero source term.
+  At each time step, a test is performed to see if there is enough ice mass to
+  calve an iceberg of each class in order (1 to 10).
+  Note that this is the initial mass multiplied by the number each particle represents (\ie\ the scaling).
+  If there is enough ice, a new iceberg is spawned and the total available ice reduced accordingly.
+\end{description}
+
+Icebergs are influenced by wind, waves and currents, bottom melt and erosion.
+The latter act to disintegrate the iceberg.
+This is either all melted freshwater,
+or (if \np{rn_bits_erosion_fraction}{rn\_bits\_erosion\_fraction}~$>$~0) into melt and additionally small ice bits
+which are assumed to propagate with their larger parent and thus delay fluxing into the ocean.
+Melt water (and other variables on the configuration grid) are written into the main \NEMO\ model output files.
+
+Extensive diagnostics can be produced.
+Separate output files are maintained for human-readable iceberg information.
+A separate file is produced for each processor (independent of \np{ln_ctl}{ln\_ctl}).
+The amount of information is controlled by two integer parameters:
+\begin{description}
+\item [{\np{nn_verbose_level}{nn\_verbose\_level}}] takes a value between one and four and
+  represents an increasing number of points in the code at which variables are written,
+  and an increasing level of obscurity.
+\item [{\np{nn_verbose_write}{nn\_verbose\_write}}] is the number of timesteps between writes
+\end{description}
+
+Iceberg trajectories can also be written out and this is enabled by setting \np{nn_sample_rate}{nn\_sample\_rate}~$>$~0.
+A non-zero value represents how many timesteps between writes of information into the output file.
+These output files are in NETCDF format.
+When \key{mpp\_mpi} is defined, each output file contains only those icebergs in the corresponding processor.
+Trajectory points are written out in the order of their parent iceberg in the model's "linked list" of icebergs.
+So care is needed to recreate data for individual icebergs,
+since its trajectory data may be spread across multiple files.
+
+%% =================================================================================================
+\section[Interactions with waves (\textit{sbcwave.F90}, \forcode{ln_wave})]{Interactions with waves (\protect\mdl{sbcwave}, \protect\np{ln_wave}{ln\_wave})}
+\label{sec:SBC_wave}
+
+\begin{listing}
+  \nlst{namsbc_wave}
+  \caption{\forcode{&namsbc_wave}}
+  \label{lst:namsbc_wave}
+\end{listing}
+
+Ocean waves represent the interface between the ocean and the atmosphere, so \NEMO\ is extended to incorporate
+physical processes related to ocean surface waves, namely the surface stress modified by growth and
+dissipation of the oceanic wave field, the Stokes-Coriolis force and the Stokes drift impact on mass and
+tracer advection; moreover the neutral surface drag coefficient from a wave model can be used to evaluate
+the wind stress.
+
+Physical processes related to ocean surface waves can be accounted by setting the logical variable
+\np[=.true.]{ln_wave}{ln\_wave} in \nam{sbc}{sbc} namelist. In addition, specific flags accounting for
+different processes should be activated as explained in the following sections.
+
+Wave fields can be provided either in forced or coupled mode:
+\begin{description}
+\item [forced mode]: wave fields should be defined through the \nam{sbc_wave}{sbc\_wave} namelist
+for external data names, locations, frequency, interpolation and all the miscellanous options allowed by
+Input Data generic Interface (see \autoref{sec:SBC_input}).
+\item [coupled mode]: \NEMO\ and an external wave model can be coupled by setting \np[=.true.]{ln_cpl}{ln\_cpl}
+in \nam{sbc}{sbc} namelist and filling the \nam{sbc_cpl}{sbc\_cpl} namelist.
+\end{description}
+
+%% =================================================================================================
+\subsection[Neutral drag coefficient from wave model (\forcode{ln_cdgw})]{Neutral drag coefficient from wave model (\protect\np{ln_cdgw}{ln\_cdgw})}
+\label{subsec:SBC_wave_cdgw}
+
+The neutral surface drag coefficient provided from an external data source (\ie\ a wave model),
+can be used by setting the logical variable \np[=.true.]{ln_cdgw}{ln\_cdgw} in \nam{sbc}{sbc} namelist.
+Then using the routine \rou{sbcblk\_algo\_ncar} and starting from the neutral drag coefficent provided,
+the drag coefficient is computed according to the stable/unstable conditions of the
+air-sea interface following \citet{large.yeager_rpt04}.
+
+%% =================================================================================================
+\subsection[3D Stokes Drift (\forcode{ln_sdw} \& \forcode{nn_sdrift})]{3D Stokes Drift (\protect\np{ln_sdw}{ln\_sdw} \& \np{nn_sdrift}{nn\_sdrift})}
+\label{subsec:SBC_wave_sdw}
+
+The Stokes drift is a wave driven mechanism of mass and momentum transport \citep{stokes_ibk09}.
+It is defined as the difference between the average velocity of a fluid parcel (Lagrangian velocity)
+and the current measured at a fixed point (Eulerian velocity).
+As waves travel, the water particles that make up the waves travel in orbital motions but
+without a closed path. Their movement is enhanced at the top of the orbit and slowed slightly
+at the bottom, so the result is a net forward motion of water particles, referred to as the Stokes drift.
+An accurate evaluation of the Stokes drift and the inclusion of related processes may lead to improved
+representation of surface physics in ocean general circulation models. %GS: reference needed
+The Stokes drift velocity $\mathbf{U}_{st}$ in deep water can be computed from the wave spectrum and may be written as:
+
+\[
+  % \label{eq:SBC_wave_sdw}
+  \mathbf{U}_{st} = \frac{16{\pi^3}} {g}
+  \int_0^\infty \int_{-\pi}^{\pi} (cos{\theta},sin{\theta}) {f^3}
+  \mathrm{S}(f,\theta) \mathrm{e}^{2kz}\,\mathrm{d}\theta {d}f
+\]
+
+where: ${\theta}$ is the wave direction, $f$ is the wave intrinsic frequency,
+$\mathrm{S}($f$,\theta)$ is the 2D frequency-direction spectrum,
+$k$ is the mean wavenumber defined as:
+$k=\frac{2\pi}{\lambda}$ (being $\lambda$ the wavelength). \\
+
+In order to evaluate the Stokes drift in a realistic ocean wave field, the wave spectral shape is required
+and its computation quickly becomes expensive as the 2D spectrum must be integrated for each vertical level.
+To simplify, it is customary to use approximations to the full Stokes profile.
+Three possible parameterizations for the calculation for the approximate Stokes drift velocity profile
+are included in the code through the \np{nn_sdrift}{nn\_sdrift} parameter once provided the surface Stokes drift
+$\mathbf{U}_{st |_{z=0}}$ which is evaluated by an external wave model that accurately reproduces the wave spectra
+and makes possible the estimation of the surface Stokes drift for random directional waves in
+realistic wave conditions:
+
+\begin{description}
+\item [{\np{nn_sdrift}{nn\_sdrift} = 0}]: exponential integral profile parameterization proposed by
+\citet{breivik.janssen.ea_JPO14}:
+
+\[
+  % \label{eq:SBC_wave_sdw_0a}
+  \mathbf{U}_{st} \cong \mathbf{U}_{st |_{z=0}} \frac{\mathrm{e}^{-2k_ez}} {1-8k_ez}
+\]
+
+where $k_e$ is the effective wave number which depends on the Stokes transport $T_{st}$ defined as follows:
+
+\[
+  % \label{eq:SBC_wave_sdw_0b}
+  k_e = \frac{|\mathbf{U}_{\left.st\right|_{z=0}}|} {|T_{st}|}
+  \quad \text{and }\
+  T_{st} = \frac{1}{16} \bar{\omega} H_s^2
+\]
+
+where $H_s$ is the significant wave height and $\omega$ is the wave frequency.
+
+\item [{\np{nn_sdrift}{nn\_sdrift} = 1}]: velocity profile based on the Phillips spectrum which is considered to be a
+reasonable estimate of the part of the spectrum mostly contributing to the Stokes drift velocity near the surface
+\citep{breivik.bidlot.ea_OM16}:
+
+\[
+  % \label{eq:SBC_wave_sdw_1}
+  \mathbf{U}_{st} \cong \mathbf{U}_{st |_{z=0}} \Big[exp(2k_pz)-\beta \sqrt{-2 \pi k_pz}
+  \textit{ erf } \Big(\sqrt{-2 k_pz}\Big)\Big]
+\]
+
+where $erf$ is the complementary error function and $k_p$ is the peak wavenumber.
+
+\item [{\np{nn_sdrift}{nn\_sdrift} = 2}]: velocity profile based on the Phillips spectrum as for \np{nn_sdrift}{nn\_sdrift} = 1
+but using the wave frequency from a wave model.
+
+\end{description}
+
+The Stokes drift enters the wave-averaged momentum equation, as well as the tracer advection equations
+and its effect on the evolution of the sea-surface height ${\eta}$ is considered as follows:
+
+\[
+  % \label{eq:SBC_wave_eta_sdw}
+  \frac{\partial{\eta}}{\partial{t}} =
+  -\nabla_h \int_{-H}^{\eta} (\mathbf{U} + \mathbf{U}_{st}) dz
+\]
+
+The tracer advection equation is also modified in order for Eulerian ocean models to properly account
+for unresolved wave effect. The divergence of the wave tracer flux equals the mean tracer advection
+that is induced by the three-dimensional Stokes velocity.
+The advective equation for a tracer $c$ combining the effects of the mean current and sea surface waves
+can be formulated as follows:
+
+\[
+  % \label{eq:SBC_wave_tra_sdw}
+  \frac{\partial{c}}{\partial{t}} =
+  - (\mathbf{U} + \mathbf{U}_{st}) \cdot \nabla{c}
+\]
+
+%% =================================================================================================
+\subsection[Stokes-Coriolis term (\forcode{ln_stcor})]{Stokes-Coriolis term (\protect\np{ln_stcor}{ln\_stcor})}
+\label{subsec:SBC_wave_stcor}
+
+In a rotating ocean, waves exert a wave-induced stress on the mean ocean circulation which results
+in a force equal to $\mathbf{U}_{st}$×$f$, where $f$ is the Coriolis parameter.
+This additional force may have impact on the Ekman turning of the surface current.
+In order to include this term, once evaluated the Stokes drift (using one of the 3 possible
+approximations described in \autoref{subsec:SBC_wave_sdw}),
+\np[=.true.]{ln_stcor}{ln\_stcor} has to be set.
+
+%% =================================================================================================
+\subsection[Wave modified stress (\forcode{ln_tauwoc} \& \forcode{ln_tauw})]{Wave modified sress (\protect\np{ln_tauwoc}{ln\_tauwoc} \& \np{ln_tauw}{ln\_tauw})}
+\label{subsec:SBC_wave_tauw}
+
+The surface stress felt by the ocean is the atmospheric stress minus the net stress going
+into the waves \citep{janssen.breivik.ea_rpt13}. Therefore, when waves are growing, momentum and energy is spent and is not
+available for forcing the mean circulation, while in the opposite case of a decaying sea
+state, more momentum is available for forcing the ocean.
+Only when the sea state is in equilibrium, the ocean is forced by the atmospheric stress,
+but in practice, an equilibrium sea state is a fairly rare event.
+So the atmospheric stress felt by the ocean circulation $\tau_{oc,a}$ can be expressed as:
+
+\[
+  % \label{eq:SBC_wave_tauoc}
+  \tau_{oc,a} = \tau_a - \tau_w
+\]
+
+where $\tau_a$ is the atmospheric surface stress;
+$\tau_w$ is the atmospheric stress going into the waves defined as:
+
+\[
+  % \label{eq:SBC_wave_tauw}
+  \tau_w = \rho g \int {\frac{dk}{c_p} (S_{in}+S_{nl}+S_{diss})}
+\]
+
+where: $c_p$ is the phase speed of the gravity waves,
+$S_{in}$, $S_{nl}$ and $S_{diss}$ are three source terms that represent
+the physics of ocean waves. The first one, $S_{in}$, describes the generation
+of ocean waves by wind and therefore represents the momentum and energy transfer
+from air to ocean waves; the second term $S_{nl}$ denotes
+the nonlinear transfer by resonant four-wave interactions; while the third term $S_{diss}$
+describes the dissipation of waves by processes such as white-capping, large scale breaking
+eddy-induced damping.
+
+The wave stress derived from an external wave model can be provided either through the normalized
+wave stress into the ocean by setting \np[=.true.]{ln_tauwoc}{ln\_tauwoc}, or through the zonal and
+meridional stress components by setting \np[=.true.]{ln_tauw}{ln\_tauw}.
+
+%% =================================================================================================
+\section{Miscellaneous options}
+\label{sec:SBC_misc}
+
+%% =================================================================================================
+\subsection[Diurnal cycle (\textit{sbcdcy.F90})]{Diurnal cycle (\protect\mdl{sbcdcy})}
+\label{subsec:SBC_dcy}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{SBC_diurnal}
+  \caption[Reconstruction of the diurnal cycle variation of short wave flux]{
+    Example of reconstruction of the diurnal cycle variation of short wave flux from
+    daily mean values.
+    The reconstructed diurnal cycle (black line) is chosen as
+    the mean value of the analytical cycle (blue line) over a time step,
+    not as the mid time step value of the analytically cycle (red square).
+    From \citet{bernie.guilyardi.ea_CD07}.}
+  \label{fig:SBC_diurnal}
+\end{figure}
+
+\cite{bernie.woolnough.ea_JC05} have shown that to capture 90$\%$ of the diurnal variability of SST requires a vertical resolution in upper ocean of 1~m or better and a temporal resolution of the surface fluxes of 3~h or less.
+%Unfortunately high frequency forcing fields are rare, not to say inexistent. GS: not true anymore !
+Nevertheless, it is possible to obtain a reasonable diurnal cycle of the SST knowning only short wave flux (SWF) at high frequency \citep{bernie.guilyardi.ea_CD07}.
+Furthermore, only the knowledge of daily mean value of SWF is needed,
+as higher frequency variations can be reconstructed from them,
+assuming that the diurnal cycle of SWF is a scaling of the top of the atmosphere diurnal cycle of incident SWF.
+The \cite{bernie.guilyardi.ea_CD07} reconstruction algorithm is available in \NEMO\ by
+setting \np[=.true.]{ln_dm2dc}{ln\_dm2dc} (a \textit{\nam{sbc}{sbc}} namelist variable) when
+using a bulk formulation (\np[=.true.]{ln_blk}{ln\_blk}) or
+the flux formulation (\np[=.true.]{ln_flx}{ln\_flx}).
+The reconstruction is performed in the \mdl{sbcdcy} module.
+The detail of the algoritm used can be found in the appendix~A of \cite{bernie.guilyardi.ea_CD07}.
+The algorithm preserves the daily mean incoming SWF as the reconstructed SWF at
+a given time step is the mean value of the analytical cycle over this time step (\autoref{fig:SBC_diurnal}).
+The use of diurnal cycle reconstruction requires the input SWF to be daily
+(\ie\ a frequency of 24 hours and a time interpolation set to true in \np{sn_qsr}{sn\_qsr} namelist parameter).
+Furthermore, it is recommended to have a least 8 surface module time steps per day,
+that is  $\rdt \ nn\_fsbc < 10,800~s = 3~h$.
+An example of recontructed SWF is given in \autoref{fig:SBC_dcy} for a 12 reconstructed diurnal cycle,
+one every 2~hours (from 1am to 11pm).
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{SBC_dcy}
+  \caption[Reconstruction of the diurnal cycle variation of short wave flux on an ORCA2 grid]{
+    Example of reconstruction of the diurnal cycle variation of short wave flux from
+    daily mean values on an ORCA2 grid with a time sampling of 2~hours (from 1am to 11pm).
+    The display is on (i,j) plane.}
+  \label{fig:SBC_dcy}
+\end{figure}
+
+Note also that the setting a diurnal cycle in SWF is highly recommended when
+the top layer thickness approach 1~m or less, otherwise large error in SST can appear due to
+an inconsistency between the scale of the vertical resolution and the forcing acting on that scale.
+
+%% =================================================================================================
+\subsection{Rotation of vector pairs onto the model grid directions}
+\label{subsec:SBC_rotation}
+
+When using a flux (\np[=.true.]{ln_flx}{ln\_flx}) or bulk (\np[=.true.]{ln_blk}{ln\_blk}) formulation,
+pairs of vector components can be rotated from east-north directions onto the local grid directions.
+This is particularly useful when interpolation on the fly is used since here any vectors are likely to
+be defined relative to a rectilinear grid.
+To activate this option, a non-empty string is supplied in the rotation pair column of the relevant namelist.
+The eastward component must start with "U" and the northward component with "V".
+The remaining characters in the strings are used to identify which pair of components go together.
+So for example, strings "U1" and "V1" next to "utau" and "vtau" would pair the wind stress components together and
+rotate them on to the model grid directions;
+"U2" and "V2" could be used against a second pair of components, and so on.
+The extra characters used in the strings are arbitrary.
+The rot\_rep routine from the \mdl{geo2ocean} module is used to perform the rotation.
+
+%% =================================================================================================
+\subsection[Surface restoring to observed SST and/or SSS (\textit{sbcssr.F90})]{Surface restoring to observed SST and/or SSS (\protect\mdl{sbcssr})}
+\label{subsec:SBC_ssr}
+
+\begin{listing}
+  \nlst{namsbc_ssr}
+  \caption{\forcode{&namsbc_ssr}}
+  \label{lst:namsbc_ssr}
+\end{listing}
+
+Options are defined through the \nam{sbc_ssr}{sbc\_ssr} namelist variables.
+On forced mode using a flux formulation (\np[=.true.]{ln_flx}{ln\_flx}),
+a feedback term \emph{must} be added to the surface heat flux $Q_{ns}^o$:
+\[
+  % \label{eq:SBC_dmp_q}
+  Q_{ns} = Q_{ns}^o + \frac{dQ}{dT} \left( \left. T \right|_{k=1} - SST_{Obs} \right)
+\]
+where SST is a sea surface temperature field (observed or climatological),
+$T$ is the model surface layer temperature and
+$\frac{dQ}{dT}$ is a negative feedback coefficient usually taken equal to $-40~W/m^2/K$.
+For a $50~m$ mixed-layer depth, this value corresponds to a relaxation time scale of two months.
+This term ensures that if $T$ perfectly matches the supplied SST, then $Q$ is equal to $Q_o$.
+
+In the fresh water budget, a feedback term can also be added.
+Converted into an equivalent freshwater flux, it takes the following expression :
+
+\begin{equation}
+  \label{eq:SBC_dmp_emp}
+  \textit{emp} = \textit{emp}_o + \gamma_s^{-1} e_{3t}  \frac{  \left(\left.S\right|_{k=1}-SSS_{Obs}\right)}
+  {\left.S\right|_{k=1}}
+\end{equation}
+
+where $\textit{emp}_{o }$ is a net surface fresh water flux
+(observed, climatological or an atmospheric model product),
+\textit{SSS}$_{Obs}$ is a sea surface salinity
+(usually a time interpolation of the monthly mean Polar Hydrographic Climatology \citep{steele.morley.ea_JC01}),
+$\left.S\right|_{k=1}$ is the model surface layer salinity and
+$\gamma_s$ is a negative feedback coefficient which is provided as a namelist parameter.
+Unlike heat flux, there is no physical justification for the feedback term in \autoref{eq:SBC_dmp_emp} as
+the atmosphere does not care about ocean surface salinity \citep{madec.delecluse_IWN97}.
+The SSS restoring term should be viewed as a flux correction on freshwater fluxes to
+reduce the uncertainties we have on the observed freshwater budget.
+
+%% =================================================================================================
+\subsection{Handling of ice-covered area  (\textit{sbcice\_...})}
+\label{subsec:SBC_ice-cover}
+
+The presence at the sea surface of an ice covered area modifies all the fluxes transmitted to the ocean.
+There are several way to handle sea-ice in the system depending on
+the value of the \np{nn_ice}{nn\_ice} namelist parameter found in \nam{sbc}{sbc} namelist.
+\begin{description}
+\item [nn\_ice = 0] there will never be sea-ice in the computational domain.
+  This is a typical namelist value used for tropical ocean domain.
+  The surface fluxes are simply specified for an ice-free ocean.
+  No specific things is done for sea-ice.
+\item [nn\_ice = 1] sea-ice can exist in the computational domain, but no sea-ice model is used.
+  An observed ice covered area is read in a file.
+  Below this area, the SST is restored to the freezing point and
+  the heat fluxes are set to $-4~W/m^2$ ($-2~W/m^2$) in the northern (southern) hemisphere.
+  The associated modification of the freshwater fluxes are done in such a way that
+  the change in buoyancy fluxes remains zero.
+  This prevents deep convection to occur when trying to reach the freezing point
+  (and so ice covered area condition) while the SSS is too large.
+  This manner of managing sea-ice area, just by using a IF case,
+  is usually referred as the \textit{ice-if} model.
+  It can be found in the \mdl{sbcice\_if} module.
+\item [nn\_ice = 2 or more] A full sea ice model is used.
+  This model computes the ice-ocean fluxes,
+  that are combined with the air-sea fluxes using the ice fraction of each model cell to
+  provide the surface averaged ocean fluxes.
+  Note that the activation of a sea-ice model is done by defining a CPP key (\key{si3} or \key{cice}).
+  The activation automatically overwrites the read value of nn\_ice to its appropriate value
+  (\ie\ $2$ for SI3 or $3$ for CICE).
+\end{description}
+
+% {Description of Ice-ocean interface to be added here or in LIM 2 and 3 doc ?}
+%GS: ocean-ice (SI3) interface is not located in SBC directory anymore, so it should be included in SI3 doc
+
+%% =================================================================================================
+\subsection[Interface to CICE (\textit{sbcice\_cice.F90})]{Interface to CICE (\protect\mdl{sbcice\_cice})}
+\label{subsec:SBC_cice}
+
+It is possible to couple a regional or global \NEMO\ configuration (without AGRIF)
+to the CICE sea-ice model by using \key{cice}.
+The CICE code can be obtained from \href{http://oceans11.lanl.gov/trac/CICE/}{LANL} and
+the additional 'hadgem3' drivers will be required, even with the latest code release.
+Input grid files consistent with those used in \NEMO\ will also be needed,
+and CICE CPP keys \textbf{ORCA\_GRID}, \textbf{CICE\_IN\_NEMO} and \textbf{coupled} should be used
+(seek advice from UKMO if necessary).
+Currently, the code is only designed to work when using the NCAR forcing option for \NEMO\ %GS: still true ?
+(with \textit{calc\_strair}\forcode{=.true.} and \textit{calc\_Tsfc}\forcode{=.true.} in the CICE name-list),
+or alternatively when \NEMO\ is coupled to the HadGAM3 atmosphere model
+(with \textit{calc\_strair}\forcode{=.false.} and \textit{calc\_Tsfc}\forcode{=false}).
+The code is intended to be used with \np{nn_fsbc}{nn\_fsbc} set to 1
+(although coupling ocean and ice less frequently should work,
+it is possible the calculation of some of the ocean-ice fluxes needs to be modified slightly -
+the user should check that results are not significantly different to the standard case).
+
+There are two options for the technical coupling between \NEMO\ and CICE.
+The standard version allows complete flexibility for the domain decompositions in the individual models,
+but this is at the expense of global gather and scatter operations in the coupling which
+become very expensive on larger numbers of processors.
+The alternative option (using \key{nemocice\_decomp} for both \NEMO\ and CICE) ensures that
+the domain decomposition is identical in both models (provided domain parameters are set appropriately,
+and \textit{processor\_shape~=~square-ice} and \textit{distribution\_wght~=~block} in the CICE name-list) and
+allows much more efficient direct coupling on individual processors.
+This solution scales much better although it is at the expense of having more idle CICE processors in areas where
+there is no sea ice.
+
+%% =================================================================================================
+\subsection[Freshwater budget control (\textit{sbcfwb.F90})]{Freshwater budget control (\protect\mdl{sbcfwb})}
+\label{subsec:SBC_fwb}
+
+For global ocean simulation, it can be useful to introduce a control of the mean sea level in order to
+prevent unrealistic drift of the sea surface height due to inaccuracy in the freshwater fluxes.
+In \NEMO, two way of controlling the freshwater budget are proposed:
+
+\begin{description}
+\item [{\np[=0]{nn_fwb}{nn\_fwb}}] no control at all.
+  The mean sea level is free to drift, and will certainly do so.
+\item [{\np[=1]{nn_fwb}{nn\_fwb}}] global mean \textit{emp} set to zero at each model time step.
+  %GS: comment below still relevant ?
+  %Note that with a sea-ice model, this technique only controls the mean sea level with linear free surface and no mass flux between ocean and ice (as it is implemented in the current ice-ocean coupling).
+\item [{\np[=2]{nn_fwb}{nn\_fwb}}] freshwater budget is adjusted from the previous year annual mean budget which
+  is read in the \textit{EMPave\_old.dat} file.
+  As the model uses the Boussinesq approximation, the annual mean fresh water budget is simply evaluated from
+  the change in the mean sea level at January the first and saved in the \textit{EMPav.dat} file.
+\end{description}
+
+% Griffies doc:
+% When running ocean-ice simulations, we are not explicitly representing land processes,
+% such as rivers, catchment areas, snow accumulation, etc. However, to reduce model drift,
+% it is important to balance the hydrological cycle in ocean-ice models.
+% We thus need to prescribe some form of global normalization to the precipitation minus evaporation plus river runoff.
+% The result of the normalization should be a global integrated zero net water input to the ocean-ice system over
+% a chosen time scale.
+% How often the normalization is done is a matter of choice. In mom4p1, we choose to do so at each model time step,
+% so that there is always a zero net input of water to the ocean-ice system.
+% Others choose to normalize over an annual cycle, in which case the net imbalance over an annual cycle is used
+% to alter the subsequent year�s water budget in an attempt to damp the annual water imbalance.
+% Note that the annual budget approach may be inappropriate with interannually varying precipitation forcing.
+% When running ocean-ice coupled models, it is incorrect to include the water transport between the ocean
+% and ice models when aiming to balance the hydrological cycle.
+% The reason is that it is the sum of the water in the ocean plus ice that should be balanced when running ocean-ice models,
+% not the water in any one sub-component. As an extreme example to illustrate the issue,
+% consider an ocean-ice model with zero initial sea ice. As the ocean-ice model spins up,
+% there should be a net accumulation of water in the growing sea ice, and thus a net loss of water from the ocean.
+% The total water contained in the ocean plus ice system is constant, but there is an exchange of water between
+% the subcomponents. This exchange should not be part of the normalization used to balance the hydrological cycle
+% in ocean-ice models.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_STO.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_STO.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_STO.tex	(revision 14097)
@@ -0,0 +1,209 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Stochastic Parametrization of EOS (STO)}
+\label{chap:STO}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+% \vfill
+% \begin{figure}[b]
+%% =================================================================================================
+% \subsubsection*{Changes record}
+% \begin{tabular}{l||l|m{0.65\linewidth}}
+%    Release   & Author        & Modifications \\
+%    {\em 4.0.1} & {\em C. Levy} & {\em 4.0.1 update}  \\
+%    {\em 3.6} & {\em P.-A. Bouttier} & {\em initial version}  \\
+% \end{tabular}
+% \end{figure}
+
+\clearpage
+
+As a result of the nonlinearity of the seawater equation of state, unresolved scales represent a major source of uncertainties in the computation of the large-scale horizontal density gradient from the large-scale temperature and salinity fields. Following  \cite{brankart_OM13}, the impact of these uncertainties can be simulated by random processes representing unresolved T/S fluctuations. The Stochastic Parametrization of EOS (STO) module implements this parametrization.
+
+As detailed in \cite{brankart_OM13}, the stochastic formulation of the equation of state can be written as:
+\begin{equation}
+  \label{eq:STO_eos_sto}
+  \rho = \frac{1}{2} \sum_{i=1}^m\{ \rho[T+\Delta T_i,S+\Delta S_i,p_o(z)] + \rho[T-\Delta T_i,S-\Delta S_i,p_o(z)] \}
+\end{equation}
+where $p_o(z)$ is the reference pressure depending on the depth and,
+$\Delta T_i$ and $\Delta S_i$ (i=1,m) is a set of T/S perturbations defined as
+the scalar product of the respective local T/S gradients with random walks $\mathbf{\xi}$:
+\begin{equation}
+  \label{eq:STO_sto_pert}
+  \Delta T_i = \mathbf{\xi}_i \cdot \nabla T \qquad \hbox{and} \qquad \Delta S_i = \mathbf{\xi}_i \cdot \nabla S
+\end{equation}
+$\mathbf{\xi}_i$ are produced by a first-order autoregressive process (AR-1) with
+a parametrized decorrelation time scale, and horizontal and vertical standard deviations $\sigma_s$.
+$\mathbf{\xi}$ are uncorrelated over the horizontal and fully correlated along the vertical.
+
+%% =================================================================================================
+\section{Stochastic processes}
+\label{sec:STO_the_details}
+
+There are many existing parameterizations based on autoregressive processes,
+which are used as a basic source of randomness to transform a deterministic model into a probabilistic model.
+The generic approach here is to a new STO module,
+generating processes features with appropriate statistics to simulate these uncertainties in the model
+(see \cite{brankart.candille.ea_GMD15} for more details).
+
+In practice, at each model grid point,
+independent Gaussian autoregressive processes~$\xi^{(i)},\,i=1,\ldots,m$ are first generated using
+the same basic equation:
+
+\begin{equation}
+  \label{eq:STO_autoreg}
+  \xi^{(i)}_{k+1} = a^{(i)} \xi^{(i)}_k + b^{(i)} w^{(i)} + c^{(i)}
+\end{equation}
+
+\noindent
+where $k$ is the index of the model timestep and
+$a^{(i)}$, $b^{(i)}$, $c^{(i)}$ are parameters defining the mean ($\mu^{(i)}$) standard deviation ($\sigma^{(i)}$) and
+correlation timescale ($\tau^{(i)}$) of each process:
+
+\begin{itemize}
+\item for order~1 processes, $w^{(i)}$ is a Gaussian white noise, with zero mean and standard deviation equal to~1,
+  and the parameters $a^{(i)}$, $b^{(i)}$, $c^{(i)}$ are given by:
+
+  \[
+    % \label{eq:STO_ord1}
+    \left\{
+      \begin{array}{l}
+        a^{(i)} = \varphi \\
+        b^{(i)} = \sigma^{(i)} \sqrt{ 1 - \varphi^2 }        \qquad\qquad\mbox{with}\qquad\qquad \varphi = \exp \left( - 1 / \tau^{(i)} \right) \\
+        c^{(i)} = \mu^{(i)} \left( 1 - \varphi \right) \\
+      \end{array}
+    \right.
+  \]
+
+\item for order~$n>1$ processes, $w^{(i)}$ is an order~$n-1$ autoregressive process, with zero mean,
+  standard deviation equal to~$\sigma^{(i)}$;
+  correlation timescale equal to~$\tau^{(i)}$;
+  and the parameters $a^{(i)}$, $b^{(i)}$, $c^{(i)}$ are given by:
+
+  \begin{equation}
+    \label{eq:STO_ord2}
+    \left\{
+      \begin{array}{l}
+        a^{(i)} = \varphi \\
+        b^{(i)} = \frac{n-1}{2(4n-3)} \sqrt{ 1 - \varphi^2 }
+        \qquad\qquad\mbox{with}\qquad\qquad
+        \varphi = \exp \left( - 1 / \tau^{(i)} \right) \\
+        c^{(i)} = \mu^{(i)} \left( 1 - \varphi \right) \\
+      \end{array}
+    \right.
+  \end{equation}
+
+\end{itemize}
+
+\noindent
+In this way, higher order processes can be easily generated recursively using the same piece of code implementing
+\autoref{eq:STO_autoreg}, and using successive processes from order $0$ to~$n-1$ as~$w^{(i)}$.
+The parameters in \autoref{eq:STO_ord2} are computed so that this recursive application of
+\autoref{eq:STO_autoreg} leads to processes with the required standard deviation and correlation timescale,
+with the additional condition that the $n-1$ first derivatives of the autocorrelation function are equal to
+zero at~$t=0$, so that the resulting processes become smoother and smoother as $n$ increases.
+
+Overall, this method provides quite a simple and generic way of generating a wide class of stochastic processes.
+However, this also means that new model parameters are needed to specify each of these stochastic processes.
+As in any parameterization, the main issue is to tune the parameters using
+either first principles, model simulations, or real-world observations.
+The parameters are set by default as described in \cite{brankart_OM13}, which has been shown in the paper
+to give good results for a global low resolution (2°) \NEMO\ configuration. where this parametrization produces a major effect on the average large-scale circulation, especilally in regions of intense mesoscale activity.
+The set of parameters will need further investigation to find appropriate values
+for any other configuration or resolution of the model.
+
+%% =================================================================================================
+\section{Implementation details}
+\label{sec:STO_thech_details}
+
+The code implementing stochastic parametrisation is located in the src/OCE/STO directory.
+It contains three modules :
+% \begin{description}
+
+\mdl{stopar} : define the Stochastic parameters and their time evolution
+
+\mdl{storng} : random number generator based on and including the 64-bit KISS (Keep It Simple Stupid) random number generator distributed by George Marsaglia
+
+\mdl{stopts} : stochastic parametrisation associated with the non-linearity of the equation of
+ seawater, implementing \autoref{eq:STO_sto_pert} so as specifics in the equation of state
+ implementing \autoref{eq:STO_eos_sto}.
+% \end{description}
+
+The \mdl{stopar} module includes three public routines called in the model:
+
+(\rou{sto\_par}) is a direct implementation of \autoref{eq:STO_autoreg},
+applied at each model grid point (in 2D or 3D), and called at each model time step ($k$) to
+update every autoregressive process ($i=1,\ldots,m$).
+This routine also includes a filtering operator, applied to $w^{(i)}$,
+to introduce a spatial correlation between the stochastic processes.
+
+(\rou{sto\_par\_init}) is the initialization routine computing
+the values $a^{(i)}, b^{(i)}, c^{(i)}$ for each autoregressive process,
+as a function of the statistical properties required by the model user
+(mean, standard deviation, time correlation, order of the process,\ldots).
+This routine also includes the initialization (seeding) of the random number generator.
+
+(\rou{sto\_rst\_write}) writes a restart file
+(which suffix name is given by \np{cn_storst_out}{cn\_storst\_out} namelist parameter) containing the current value of
+all autoregressive processes to allow creating the file needed for a restart.
+This restart file also contains the current state of the random number generator.
+When \np{ln_rststo}{ln\_rststo} is set to \forcode{.true.}),
+the restart file (which suffix name is given by \np{cn_storst_in}{cn\_storst\_in} namelist parameter) is read by
+the initialization routine (\rou{sto\_par\_init}).
+The simulation will continue exactly as if it was not interrupted only
+when \np{ln_rstseed}{ln\_rstseed} is set to \forcode{.true.},
+\ie\ when the state of the random number generator is read in the restart file.\\
+
+The implementation includes the basics for a few possible stochastic parametrisations including equation of state,
+lateral diffusion, horizontal pressure gradient, ice strength, trend, tracers dynamics.
+As for this release, only the stochastic parametrisation of equation of state is fully available and tested. \\
+
+Options and parameters \\
+
+The \np{ln_sto_eos}{ln\_sto\_eos} namelist variable activates stochastic parametrisation of equation of state.
+By default it set to \forcode{.false.}) and not active.
+The set of parameters is available in \nam{sto}{sto} namelist
+(only the subset for equation of state stochastic parametrisation is listed below):
+
+\begin{listing}
+  \nlst{namsto}
+  \caption{\forcode{&namsto}}
+  \label{lst:namsto}
+\end{listing}
+
+The variables of stochastic paramtetrisation itself (based on the global 2° experiments as in \cite{brankart_OM13} are:
+
+\begin{description}
+\item [{\np{nn_sto_eos}{nn\_sto\_eos}:}]     number of independent random walks
+\item [{\np{rn_eos_stdxy}{rn\_eos\_stdxy}:}] random walk horizontal standard deviation
+  (in grid points)
+\item [{\np{rn_eos_stdz}{rn\_eos\_stdz}:}]   random walk vertical standard deviation
+  (in grid points)
+\item [{\np{rn_eos_tcor}{rn\_eos\_tcor}:}]   random walk time correlation (in timesteps)
+\item [{\np{nn_eos_ord}{nn\_eos\_ord}:}]     order of autoregressive processes
+\item [{\np{nn_eos_flt}{nn\_eos\_flt}:}]     passes of Laplacian filter
+\item [{\np{rn_eos_lim}{rn\_eos\_lim}:}]     limitation factor (default = 3.0)
+\end{description}
+
+The first four parameters define the stochastic part of equation of state.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_TRA.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_TRA.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_TRA.tex	(revision 14097)
@@ -0,0 +1,1470 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Ocean Tracers (TRA)}
+\label{chap:TRA}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release          & Author(s)                                   & Modifications       \\
+    \hline
+    {\em        4.0} & {\em Christian \'{E}th\'{e}               } & {\em Review       } \\
+    {\em        3.6} & {\em Gurvan Madec                         } & {\em Update       } \\
+    {\em $\leq$ 3.4} & {\em Gurvan Madec and S\'{e}bastien Masson} & {\em First version} \\
+  \end{tabularx}
+}
+
+\clearpage
+
+% missing/update
+% traqsr: need to coordinate with SBC module
+
+%STEVEN :  is the use of the word "positive" to describe a scheme enough, or should it be "positive definite"?
+%I added a comment to this effect on some instances of this below
+
+Using the representation described in \autoref{chap:DOM}, several semi -discrete space forms of
+the tracer equations are available depending on the vertical coordinate used and on the physics used.
+In all the equations presented here, the masking has been omitted for simplicity.
+One must be aware that all the quantities are masked fields and that
+each time a mean or difference operator is used, the resulting field is multiplied by a mask.
+
+The two active tracers are potential temperature and salinity.
+Their prognostic equations can be summarized as follows:
+\[
+  \text{NXT} =     \text{ADV} + \text{LDF} + \text{ZDF} + \text{SBC}
+               + \{\text{QSR},  \text{BBC},  \text{BBL},  \text{DMP}\}
+\]
+
+NXT stands for next, referring to the time-stepping.
+From left to right, the terms on the rhs of the tracer equations are the advection (ADV),
+the lateral diffusion (LDF), the vertical diffusion (ZDF),
+the contributions from the external forcings (SBC: Surface Boundary Condition,
+QSR: penetrative Solar Radiation, and BBC: Bottom Boundary Condition),
+the contribution from the bottom boundary Layer (BBL) parametrisation,
+and an internal damping (DMP) term.
+The terms QSR, BBC, BBL and DMP are optional.
+The external forcings and parameterisations require complex inputs and complex calculations
+(\eg\ bulk formulae, estimation of mixing coefficients) that are carried out in the SBC,
+LDF and ZDF modules and described in \autoref{chap:SBC}, \autoref{chap:LDF} and
+\autoref{chap:ZDF}, respectively.
+Note that \mdl{tranpc}, the non-penetrative convection module,
+although located in the \path{./src/OCE/TRA} directory as it directly modifies the tracer fields,
+is described with the model vertical physics (ZDF) together with
+other available parameterization of convection.
+
+In the present chapter we also describe the diagnostic equations used to
+compute the sea-water properties (density, Brunt-V\"{a}is\"{a}l\"{a} frequency, specific heat and
+freezing point with associated modules \mdl{eosbn2} and \mdl{phycst}).
+
+The different options available to the user are managed by namelist logicals.
+For each equation term \textit{TTT}, the namelist logicals are \textit{ln\_traTTT\_xxx},
+where \textit{xxx} is a 3 or 4 letter acronym corresponding to each optional scheme.
+The equivalent code can be found in the \textit{traTTT} or \textit{traTTT\_xxx} module,
+in the \path{./src/OCE/TRA} directory.
+
+The user has the option of extracting each tendency term on the RHS of the tracer equation for output
+(\np{ln_tra_trd}{ln\_tra\_trd} or \np[=.true.]{ln_tra_mxl}{ln\_tra\_mxl}),
+as described in \autoref{chap:DIA}.
+
+%% =================================================================================================
+\section[Tracer advection (\textit{traadv.F90})]{Tracer advection (\protect\mdl{traadv})}
+\label{sec:TRA_adv}
+
+\begin{listing}
+  \nlst{namtra_adv}
+  \caption{\forcode{&namtra_adv}}
+  \label{lst:namtra_adv}
+\end{listing}
+
+When considered (\ie\ when \np{ln_traadv_OFF}{ln\_traadv\_OFF} is not set to \forcode{.true.}),
+the advection tendency of a tracer is expressed in flux form,
+\ie\ as the divergence of the advective fluxes.
+Its discrete expression is given by:
+\begin{equation}
+  \label{eq:TRA_adv}
+  ADV_\tau = - \frac{1}{b_t} \Big(   \delta_i [ e_{2u} \, e_{3u} \; u \; \tau_u]
+                                   + \delta_j [ e_{1v} \, e_{3v} \; v \; \tau_v] \Big)
+             - \frac{1}{e_{3t}} \delta_k [w \; \tau_w]
+\end{equation}
+where $\tau$ is either T or S, and $b_t = e_{1t} \, e_{2t} \, e_{3t}$ is the volume of $T$-cells.
+The flux form in \autoref{eq:TRA_adv} implicitly requires the use of the continuity equation.
+Indeed, it is obtained by using the following equality:
+$\nabla \cdot (\vect U \, T) = \vect U \cdot \nabla T$ which
+results from the use of the continuity equation,
+$\partial_t e_3 + e_3 \; \nabla \cdot \vect U = 0$
+(which reduces to $\nabla \cdot \vect U = 0$ in linear free surface,
+\ie\ \np[=.true.]{ln_linssh}{ln\_linssh}).
+Therefore it is of paramount importance to
+design the discrete analogue of the advection tendency so that
+it is consistent with the continuity equation in order to
+enforce the conservation properties of the continuous equations.
+In other words, by setting $\tau = 1$ in (\autoref{eq:TRA_adv}) we recover
+the discrete form of the continuity equation which is used to calculate the vertical velocity.
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRA_adv_scheme}
+  \caption[Ways to evaluate the tracer value and the amount of tracer exchanged]{
+    Schematic representation of some ways used to evaluate the tracer value at $u$-point and
+    the amount of tracer exchanged between two neighbouring grid points.
+    Upsteam biased scheme (ups):
+    the upstream value is used and the black area is exchanged.
+    Piecewise parabolic method (ppm):
+    a parabolic interpolation is used and the black and dark grey areas are exchanged.
+    Monotonic upstream scheme for conservative laws (muscl):
+    a parabolic interpolation is used and black, dark grey and grey areas are exchanged.
+    Second order scheme (cen2):
+    the mean value is used and black, dark grey, grey and light grey areas are exchanged.
+    Note that this illustration does not include the flux limiter used in ppm and muscl schemes.}
+  \label{fig:TRA_adv_scheme}
+\end{figure}
+
+The key difference between the advection schemes available in \NEMO\ is the choice made in
+space and time interpolation to define the value of the tracer at the velocity points
+(\autoref{fig:TRA_adv_scheme}).
+
+Along solid lateral and bottom boundaries a zero tracer flux is automatically specified,
+since the normal velocity is zero there.
+At the sea surface the boundary condition depends on the type of sea surface chosen:
+
+\begin{description}
+\item [linear free surface] (\np[=.true.]{ln_linssh}{ln\_linssh})
+  the first level thickness is constant in time:
+  the vertical boundary condition is applied at the fixed surface $z = 0$ rather than
+  on the moving surface $z = \eta$.
+  There is a non-zero advective flux which is set for
+  all advection schemes as $\tau_w|_{k = 1/2} = T_{k = 1}$,
+  \ie\ the product of surface velocity (at $z = 0$) by the first level tracer value.
+\item [non-linear free surface] (\np[=.false.]{ln_linssh}{ln\_linssh})
+  convergence/divergence in the first ocean level moves the free surface up/down.
+  There is no tracer advection through it so that
+  the advective fluxes through the surface are also zero.
+\end{description}
+
+In all cases, this boundary condition retains local conservation of tracer.
+Global conservation is obtained in non-linear free surface case,
+but \textit{not} in the linear free surface case.
+Nevertheless, in the latter case,
+it is achieved to a good approximation since the non-conservative term is
+the product of the time derivative of the tracer and the free surface height,
+two quantities that are not correlated
+\citep{roullet.madec_JGR00, griffies.pacanowski.ea_MWR01, campin.adcroft.ea_OM04}.
+
+The velocity field that appears in (\autoref{eq:TRA_adv} is
+the centred (\textit{now}) \textit{effective} ocean velocity, \ie\ the \textit{eulerian} velocity
+(see \autoref{chap:DYN}) plus the eddy induced velocity (\textit{eiv}) and/or
+the mixed layer eddy induced velocity (\textit{eiv}) when those parameterisations are used
+(see \autoref{chap:LDF}).
+
+Several tracer advection scheme are proposed,
+namely a $2^{nd}$ or $4^{th}$ order \textbf{CEN}tred schemes (CEN),
+a $2^{nd}$ or $4^{th}$ order \textbf{F}lux \textbf{C}orrected \textbf{T}ransport scheme (FCT),
+a \textbf{M}onotone \textbf{U}pstream \textbf{S}cheme for
+\textbf{C}onservative \textbf{L}aws scheme (MUSCL),
+a $3^{rd}$ \textbf{U}pstream \textbf{B}iased \textbf{S}cheme (UBS, also often called UP3),
+and a \textbf{Q}uadratic \textbf{U}pstream \textbf{I}nterpolation for
+\textbf{C}onvective \textbf{K}inematics with
+\textbf{E}stimated \textbf{S}treaming \textbf{T}erms scheme (QUICKEST).
+The choice is made in the \nam{tra_adv}{tra\_adv} namelist,
+by setting to \forcode{.true.} one of the logicals \textit{ln\_traadv\_xxx}.
+The corresponding code can be found in the \textit{traadv\_xxx.F90} module,
+where \textit{xxx} is a 3 or 4 letter acronym corresponding to each scheme.
+By default (\ie\ in the reference namelist, \textit{namelist\_ref}),
+all the logicals are set to \forcode{.false.}.
+If the user does not select an advection scheme in the configuration namelist
+(\textit{namelist\_cfg}), the tracers will \textit{not} be advected!
+
+Details of the advection schemes are given below.
+The choosing an advection scheme is a complex matter which depends on the
+model physics, model resolution, type of tracer, as well as the issue of numerical cost.
+In particular, we note that
+
+\begin{enumerate}
+\item CEN and FCT schemes require an explicit diffusion operator while
+  the other schemes are diffusive enough so that they do not necessarily need additional diffusion;
+\item CEN and UBS are not \textit{positive} schemes \footnote{negative values can appear in
+    an initially strictly positive tracer field which is advected},
+  implying that false extrema are permitted.
+  Their use is not recommended on passive tracers;
+\item It is recommended that the same advection-diffusion scheme is used on
+  both active and passive tracers.
+\end{enumerate}
+
+Indeed, if a source or sink of a passive tracer depends on an active one,
+the difference of treatment of active and passive tracers can create
+very nice-looking frontal structures that are pure numerical artefacts.
+Nevertheless, most of our users set a different treatment on passive and active tracers,
+that's the reason why this possibility is offered.
+We strongly suggest them to perform a sensitivity experiment using a same treatment to
+assess the robustness of their results.
+
+%% =================================================================================================
+\subsection[CEN: Centred scheme (\forcode{ln_traadv_cen})]{CEN: Centred scheme (\protect\np{ln_traadv_cen}{ln\_traadv\_cen})}
+\label{subsec:TRA_adv_cen}
+
+%        2nd order centred scheme
+
+The \textbf{CEN}tred advection scheme (CEN) is used when \np[=.true.]{ln_traadv_cen}{ln\_traadv\_cen}.
+Its order ($2^{nd}$ or $4^{th}$) can be chosen independently on
+horizontal (iso-level) and vertical direction by
+setting \np{nn_cen_h}{nn\_cen\_h} and \np{nn_cen_v}{nn\_cen\_v} to $2$ or $4$.
+CEN implementation can be found in the \mdl{traadv\_cen} module.
+
+In the $2^{nd}$ order centred formulation (CEN2), the tracer at velocity points is evaluated as
+the mean of the two neighbouring $T$-point values.
+For example, in the $i$-direction :
+\begin{equation}
+  \label{eq:TRA_adv_cen2}
+  \tau_u^{cen2} = \overline T ^{i + 1/2}
+\end{equation}
+
+CEN2 is non diffusive (\ie\ it conserves the tracer variance, $\tau^2$) but
+dispersive (\ie\ it may create false extrema).
+It is therefore notoriously noisy and must be used in conjunction with
+an explicit diffusion operator to produce a sensible solution.
+The associated time-stepping is performed using
+a leapfrog scheme in conjunction with an Asselin time-filter,
+so $T$ in (\autoref{eq:TRA_adv_cen2}) is the \textit{now} tracer value.
+
+Note that using the CEN2, the overall tracer advection is of second order accuracy since
+both (\autoref{eq:TRA_adv}) and (\autoref{eq:TRA_adv_cen2}) have this order of accuracy.
+
+%        4nd order centred scheme
+
+In the $4^{th}$ order formulation (CEN4),
+tracer values are evaluated at u- and v-points as a $4^{th}$ order interpolation,
+and thus depend on the four neighbouring $T$-points.
+For example, in the $i$-direction:
+\begin{equation}
+  \label{eq:TRA_adv_cen4}
+  \tau_u^{cen4} = \overline{T - \frac{1}{6} \, \delta_i \Big[ \delta_{i + 1/2}[T] \, \Big]}^{\,i + 1/2}
+\end{equation}
+In the vertical direction (\np[=4]{nn_cen_v}{nn\_cen\_v}),
+a $4^{th}$ COMPACT interpolation has been prefered \citep{demange_phd14}.
+In the COMPACT scheme, both the field and its derivative are interpolated,
+which leads, after a matrix inversion, spectral characteristics similar to schemes of higher order
+\citep{lele_JCP92}.
+
+Strictly speaking, the CEN4 scheme is not a $4^{th}$ order advection scheme but
+a $4^{th}$ order evaluation of advective fluxes,
+since the divergence of advective fluxes \autoref{eq:TRA_adv} is kept at $2^{nd}$ order.
+The expression \textit{$4^{th}$ order scheme} used in oceanographic literature is
+usually associated with the scheme presented here.
+Introducing a ``true'' $4^{th}$ order advection scheme is feasible but, for consistency reasons,
+it requires changes in the discretisation of the tracer advection together with
+changes in the continuity equation, and the momentum advection and pressure terms.
+
+A direct consequence of the pseudo-fourth order nature of the scheme is that it is not non-diffusive,
+\ie\ the global variance of a tracer is not preserved using CEN4.
+Furthermore, it must be used in conjunction with an explicit diffusion operator to
+produce a sensible solution.
+As in CEN2 case, the time-stepping is performed using a leapfrog scheme in conjunction with
+an Asselin time-filter, so $T$ in (\autoref{eq:TRA_adv_cen4}) is the \textit{now} tracer.
+
+At a $T$-grid cell adjacent to a boundary (coastline, bottom and surface),
+an additional hypothesis must be made to evaluate $\tau_u^{cen4}$.
+This hypothesis usually reduces the order of the scheme.
+Here we choose to set the gradient of $T$ across the boundary to zero.
+Alternative conditions can be specified,
+such as a reduction to a second order scheme for these near boundary grid points.
+
+%% =================================================================================================
+\subsection[FCT: Flux Corrected Transport scheme (\forcode{ln_traadv_fct})]{FCT: Flux Corrected Transport scheme (\protect\np{ln_traadv_fct}{ln\_traadv\_fct})}
+\label{subsec:TRA_adv_tvd}
+
+The \textbf{F}lux \textbf{C}orrected \textbf{T}ransport schemes (FCT) is used when
+\np[=.true.]{ln_traadv_fct}{ln\_traadv\_fct}.
+Its order ($2^{nd}$ or $4^{th}$) can be chosen independently on
+horizontal (iso-level) and vertical direction by
+setting \np{nn_fct_h}{nn\_fct\_h} and \np{nn_fct_v}{nn\_fct\_v} to $2$ or $4$.
+FCT implementation can be found in the \mdl{traadv\_fct} module.
+
+In FCT formulation, the tracer at velocity points is evaluated using
+a combination of an upstream and a centred scheme.
+For example, in the $i$-direction :
+\begin{equation}
+  \label{eq:TRA_adv_fct}
+  \begin{split}
+    \tau_u^{ups} &=
+    \begin{cases}
+                     T_{i + 1} & \text{if~} u_{i + 1/2} <    0 \\
+                     T_i       & \text{if~} u_{i + 1/2} \geq 0 \\
+    \end{cases} \\
+    \tau_u^{fct} &= \tau_u^{ups} + c_u \, \big( \tau_u^{cen} - \tau_u^{ups} \big)
+  \end{split}
+\end{equation}
+where $c_u$ is a flux limiter function taking values between 0 and 1.
+The FCT order is the one of the centred scheme used
+(\ie\ it depends on the setting of \np{nn_fct_h}{nn\_fct\_h} and \np{nn_fct_v}{nn\_fct\_v}).
+There exist many ways to define $c_u$, each corresponding to a different FCT scheme.
+The one chosen in \NEMO\ is described in \citet{zalesak_JCP79}.
+$c_u$ only departs from $1$ when the advective term produces a local extremum in the tracer field.
+The resulting scheme is quite expensive but \textit{positive}.
+It can be used on both active and passive tracers.
+A comparison of FCT-2 with MUSCL and a MPDATA scheme can be found in \citet{levy.estublier.ea_GRL01}.
+
+For stability reasons (see \autoref{chap:TD}),
+$\tau_u^{cen}$ is evaluated in (\autoref{eq:TRA_adv_fct}) using the \textit{now} tracer while
+$\tau_u^{ups}$ is evaluated using the \textit{before} tracer.
+In other words, the advective part of the scheme is time stepped with a leap-frog scheme while
+a forward scheme is used for the diffusive part.
+
+%% =================================================================================================
+\subsection[MUSCL: Monotone Upstream Scheme for Conservative Laws (\forcode{ln_traadv_mus})]{MUSCL: Monotone Upstream Scheme for Conservative Laws (\protect\np{ln_traadv_mus}{ln\_traadv\_mus})}
+\label{subsec:TRA_adv_mus}
+
+The \textbf{M}onotone \textbf{U}pstream \textbf{S}cheme for \textbf{C}onservative \textbf{L}aws
+(MUSCL) is used when \np[=.true.]{ln_traadv_mus}{ln\_traadv\_mus}.
+MUSCL implementation can be found in the \mdl{traadv\_mus} module.
+
+MUSCL has been first implemented in \NEMO\ by \citet{levy.estublier.ea_GRL01}.
+In its formulation, the tracer at velocity points is evaluated assuming
+a linear tracer variation between two $T$-points (\autoref{fig:TRA_adv_scheme}).
+For example, in the $i$-direction :
+\[
+  % \label{eq:TRA_adv_mus}
+  \tau_u^{mus} = \lt\{
+  \begin{split}
+    \tau_i        &+ \frac{1}{2} \lt( 1 - \frac{u_{i + 1/2} \, \rdt}{e_{1u}} \rt)
+    \widetilde{\partial_i        \tau} & \text{if~} u_{i + 1/2} \geqslant 0 \\
+    \tau_{i + 1/2} &+ \frac{1}{2} \lt( 1 + \frac{u_{i + 1/2} \, \rdt}{e_{1u}} \rt)
+    \widetilde{\partial_{i + 1/2} \tau} & \text{if~} u_{i + 1/2} <         0
+  \end{split}
+                                                                                                      \rt.
+\]
+where $\widetilde{\partial_i \tau}$ is the slope of the tracer on which
+a limitation is imposed to ensure the \textit{positive} character of the scheme.
+
+The time stepping is performed using a forward scheme,
+that is the \textit{before} tracer field is used to evaluate $\tau_u^{mus}$.
+
+For an ocean grid point adjacent to land and where the ocean velocity is directed toward land,
+an upstream flux is used.
+This choice ensure the \textit{positive} character of the scheme.
+In addition, fluxes round a grid-point where a runoff is applied can optionally be computed using
+upstream fluxes (\np[=.true.]{ln_mus_ups}{ln\_mus\_ups}).
+
+%% =================================================================================================
+\subsection[UBS a.k.a. UP3: Upstream-Biased Scheme (\forcode{ln_traadv_ubs})]{UBS a.k.a. UP3: Upstream-Biased Scheme (\protect\np{ln_traadv_ubs}{ln\_traadv\_ubs})}
+\label{subsec:TRA_adv_ubs}
+
+The \textbf{U}pstream-\textbf{B}iased \textbf{S}cheme (UBS) is used when
+\np[=.true.]{ln_traadv_ubs}{ln\_traadv\_ubs}.
+UBS implementation can be found in the \mdl{traadv\_mus} module.
+
+The UBS scheme, often called UP3, is also known as the Cell Averaged QUICK scheme
+(\textbf{Q}uadratic \textbf{U}pstream \textbf{I}nterpolation for
+\textbf{C}onvective \textbf{K}inematics).
+It is an upstream-biased third order scheme based on an upstream-biased parabolic interpolation.
+For example, in the $i$-direction:
+\begin{equation}
+  \label{eq:TRA_adv_ubs}
+  \tau_u^{ubs} = \overline T ^{i + 1/2} - \frac{1}{6}
+    \begin{cases}
+      \tau"_i       & \text{if~} u_{i + 1/2} \geqslant 0 \\
+      \tau"_{i + 1} & \text{if~} u_{i + 1/2} <         0
+    \end{cases}
+  \quad \text{where~} \tau"_i = \delta_i \lt[ \delta_{i + 1/2} [\tau] \rt]
+\end{equation}
+
+This results in a dissipatively dominant (i.e. hyper-diffusive) truncation error
+\citep{shchepetkin.mcwilliams_OM05}.
+The overall performance of the advection scheme is similar to that reported in
+\cite{farrow.stevens_JPO95}.
+It is a relatively good compromise between accuracy and smoothness.
+Nevertheless the scheme is not \textit{positive}, meaning that false extrema are permitted,
+but the amplitude of such are significantly reduced over the centred second or fourth order method.
+Therefore it is not recommended that it should be applied to
+a passive tracer that requires positivity.
+
+The intrinsic diffusion of UBS makes its use risky in the vertical direction where
+the control of artificial diapycnal fluxes is of paramount importance
+\citep{shchepetkin.mcwilliams_OM05, demange_phd14}.
+Therefore the vertical flux is evaluated using either a $2^nd$ order FCT scheme or
+a $4^th$ order COMPACT scheme (\np[=2 or 4]{nn_ubs_v}{nn\_ubs\_v}).
+
+For stability reasons (see \autoref{chap:TD}),
+the first term  in \autoref{eq:TRA_adv_ubs} (which corresponds to a second order centred scheme)
+is evaluated using the \textit{now}    tracer (centred in time) while
+the second term (which is the diffusive part of the scheme),
+is evaluated using the \textit{before} tracer (forward in time).
+This choice is discussed by \citet{webb.de-cuevas.ea_JAOT98} in
+the context of the QUICK advection scheme.
+UBS and QUICK schemes only differ by one coefficient.
+Replacing 1/6 with 1/8 in \autoref{eq:TRA_adv_ubs} leads to the QUICK advection scheme
+\citep{webb.de-cuevas.ea_JAOT98}.
+This option is not available through a namelist parameter, since the 1/6 coefficient is hard coded.
+Nevertheless it is quite easy to make the substitution in the \mdl{traadv\_ubs} module and
+obtain a QUICK scheme.
+
+Note that it is straightforward to rewrite \autoref{eq:TRA_adv_ubs} as follows:
+\begin{gather}
+  \label{eq:TRA_adv_ubs2}
+  \tau_u^{ubs} = \tau_u^{cen4} + \frac{1}{12}
+    \begin{cases}
+      + \tau"_i       & \text{if} \ u_{i + 1/2} \geqslant 0 \\
+      - \tau"_{i + 1} & \text{if} \ u_{i + 1/2} <         0
+    \end{cases}
+  \intertext{or equivalently}
+  % \label{eq:TRA_adv_ubs2b}
+  u_{i + 1/2} \ \tau_u^{ubs} = u_{i + 1/2} \, \overline{T - \frac{1}{6} \, \delta_i \Big[ \delta_{i + 1/2}[T] \Big]}^{\,i + 1/2}
+                             - \frac{1}{2} |u|_{i + 1/2} \, \frac{1}{6} \, \delta_{i + 1/2} [\tau"_i] \nonumber
+\end{gather}
+
+\autoref{eq:TRA_adv_ubs2} has several advantages.
+Firstly, it clearly reveals that the UBS scheme is based on the fourth order scheme to which
+an upstream-biased diffusion term is added.
+Secondly,
+this emphasises that the $4^{th}$ order part (as well as the $2^{nd}$ order part as stated above) has to be evaluated at the \textit{now} time step using \autoref{eq:TRA_adv_ubs}.
+Thirdly, the diffusion term is in fact a biharmonic operator with
+an eddy coefficient which is simply proportional to the velocity:
+$A_u^{lm} = \frac{1}{12} \, {e_{1u}}^3 \, |u|$.
+Note the current version of \NEMO\ uses the computationally more efficient formulation
+\autoref{eq:TRA_adv_ubs}.
+
+%% =================================================================================================
+\subsection[QCK: QuiCKest scheme (\forcode{ln_traadv_qck})]{QCK: QuiCKest scheme (\protect\np{ln_traadv_qck}{ln\_traadv\_qck})}
+\label{subsec:TRA_adv_qck}
+
+The \textbf{Q}uadratic \textbf{U}pstream \textbf{I}nterpolation for
+\textbf{C}onvective \textbf{K}inematics with \textbf{E}stimated \textbf{S}treaming \textbf{T}erms
+(QUICKEST) scheme proposed by \citet{leonard_CMAME79} is used when
+\np[=.true.]{ln_traadv_qck}{ln\_traadv\_qck}.
+QUICKEST implementation can be found in the \mdl{traadv\_qck} module.
+
+QUICKEST is the third order Godunov scheme which is associated with the ULTIMATE QUICKEST limiter
+\citep{leonard_CMAME91}.
+It has been implemented in \NEMO\ by G. Reffray (Mercator Ocean) and
+can be found in the \mdl{traadv\_qck} module.
+The resulting scheme is quite expensive but \textit{positive}.
+It can be used on both active and passive tracers.
+However, the intrinsic diffusion of QCK makes its use risky in the vertical direction where
+the control of artificial diapycnal fluxes is of paramount importance.
+Therefore the vertical flux is evaluated using the CEN2 scheme.
+This no longer guarantees the positivity of the scheme.
+The use of FCT in the vertical direction (as for the UBS case) should be implemented to
+restore this property.
+
+\cmtgm{Cross term are missing in the current implementation....}
+
+%% =================================================================================================
+\section[Tracer lateral diffusion (\textit{traldf.F90})]{Tracer lateral diffusion (\protect\mdl{traldf})}
+\label{sec:TRA_ldf}
+
+\begin{listing}
+  \nlst{namtra_ldf}
+  \caption{\forcode{&namtra_ldf}}
+  \label{lst:namtra_ldf}
+\end{listing}
+
+Options are defined through the \nam{tra_ldf}{tra\_ldf} namelist variables.
+They are regrouped in four items, allowing to specify
+\begin{enumerate*}[label=(\textit{\roman*})]
+\item the type of operator used (none, laplacian, bilaplacian),
+\item the direction along which the operator acts (iso-level, horizontal, iso-neutral),
+\item some specific options related to the rotated operators (\ie\ non-iso-level operator), and
+\item the specification of eddy diffusivity coefficient
+  (either constant or variable in space and time).
+\end{enumerate*}
+Item (iv) will be described in \autoref{chap:LDF}.
+The direction along which the operators act is defined through the slope between
+this direction and the iso-level surfaces.
+The slope is computed in the \mdl{ldfslp} module and will also be described in \autoref{chap:LDF}.
+
+The lateral diffusion of tracers is evaluated using a forward scheme,
+\ie\ the tracers appearing in its expression are the \textit{before} tracers in time,
+except for the pure vertical component that appears when a rotation tensor is used.
+This latter component is solved implicitly together with the vertical diffusion term
+(see \autoref{chap:TD}).
+When \np[=.true.]{ln_traldf_msc}{ln\_traldf\_msc},
+a Method of Stabilizing Correction is used in which the pure vertical component is split into
+an explicit and an implicit part \citep{lemarie.debreu.ea_OM12}.
+
+%% =================================================================================================
+\subsection[Type of operator (\forcode{ln_traldf_}\{\forcode{OFF,lap,blp}\})]{Type of operator (\protect\np{ln_traldf_OFF}{ln\_traldf\_OFF}, \protect\np{ln_traldf_lap}{ln\_traldf\_lap}, or \protect\np{ln_traldf_blp}{ln\_traldf\_blp})}
+\label{subsec:TRA_ldf_op}
+
+Three operator options are proposed and, one and only one of them must be selected:
+
+\begin{description}
+\item [{\np[=.true.]{ln_traldf_OFF}{ln\_traldf\_OFF}}] no operator selected,
+  the lateral diffusive tendency will not be applied to the tracer equation.
+  This option can be used when the selected advection scheme is diffusive enough
+  (MUSCL scheme for example).
+\item [{\np[=.true.]{ln_traldf_lap}{ln\_traldf\_lap}}] a laplacian operator is selected.
+  This harmonic operator takes the following expression:
+  $\mathcal{L}(T) = \nabla \cdot A_{ht} \; \nabla T $,
+  where the gradient operates along the selected direction (see \autoref{subsec:TRA_ldf_dir}),
+  and $A_{ht}$ is the eddy diffusivity coefficient expressed in $m^2/s$ (see \autoref{chap:LDF}).
+\item [{\np[=.true.]{ln_traldf_blp}{ln\_traldf\_blp}}] a bilaplacian operator is selected.
+  This biharmonic operator takes the following expression:
+  $\mathcal{B} = - \mathcal{L}(\mathcal{L}(T)) = - \nabla \cdot b \nabla (\nabla \cdot b \nabla T)$
+  where the gradient operats along the selected direction,
+  and $b^2 = B_{ht}$ is the eddy diffusivity coefficient expressed in $m^4/s$
+  (see \autoref{chap:LDF}).
+  In the code, the bilaplacian operator is obtained by calling the laplacian twice.
+\end{description}
+
+Both laplacian and bilaplacian operators ensure the total tracer variance decrease.
+Their primary role is to provide strong dissipation at the smallest scale supported by the grid while
+minimizing the impact on the larger scale features.
+The main difference between the two operators is the scale selectiveness.
+The bilaplacian damping time (\ie\ its spin down time) scales like
+$\lambda^{-4}$ for disturbances of wavelength $\lambda$
+(so that short waves damped more rapidelly than long ones),
+whereas the laplacian damping time scales only like $\lambda^{-2}$.
+
+%% =================================================================================================
+\subsection[Action direction (\forcode{ln_traldf_}\{\forcode{lev,hor,iso,triad}\})]{Direction of action (\protect\np{ln_traldf_lev}{ln\_traldf\_lev}, \protect\np{ln_traldf_hor}{ln\_traldf\_hor}, \protect\np{ln_traldf_iso}{ln\_traldf\_iso}, or \protect\np{ln_traldf_triad}{ln\_traldf\_triad})}
+\label{subsec:TRA_ldf_dir}
+
+The choice of a direction of action determines the form of operator used.
+The operator is a simple (re-entrant) laplacian acting in the (\textbf{i},\textbf{j}) plane when
+iso-level option is used (\np[=.true.]{ln_traldf_lev}{ln\_traldf\_lev}) or when
+a horizontal (\ie\ geopotential) operator is demanded in \textit{z}-coordinate
+(\np{ln_traldf_hor}{ln\_traldf\_hor} and \np[=.true.]{ln_zco}{ln\_zco}).
+The associated code can be found in the \mdl{traldf\_lap\_blp} module.
+The operator is a rotated (re-entrant) laplacian when
+the direction along which it acts does not coincide with the iso-level surfaces,
+that is when standard or triad iso-neutral option is used
+(\np{ln_traldf_iso}{ln\_traldf\_iso} or \np{ln_traldf_triad}{ln\_traldf\_triad} = \forcode{.true.},
+see \mdl{traldf\_iso} or \mdl{traldf\_triad} module, resp.), or
+when a horizontal (\ie\ geopotential) operator is demanded in \textit{s}-coordinate
+(\np{ln_traldf_hor}{ln\_traldf\_hor} and \np{ln_sco}{ln\_sco} = \forcode{.true.}) \footnote{
+  In this case, the standard iso-neutral operator will be automatically selected}.
+In that case, a rotation is applied to the gradient(s) that appears in the operator so that
+diffusive fluxes acts on the three spatial direction.
+
+The resulting discret form of the three operators (one iso-level and two rotated one) is given in
+the next two sub-sections.
+
+%% =================================================================================================
+\subsection[Iso-level (bi-)laplacian operator (\forcode{ln_traldf_iso})]{Iso-level (bi-)laplacian operator ( \protect\np{ln_traldf_iso}{ln\_traldf\_iso})}
+\label{subsec:TRA_ldf_lev}
+
+The laplacian diffusion operator acting along the model (\textit{i,j})-surfaces is given by:
+\begin{equation}
+  \label{eq:TRA_ldf_lap}
+  D_t^{lT} = \frac{1}{b_t} \Bigg(   \delta_{i} \lt[ A_u^{lT} \; \frac{e_{2u} \, e_{3u}}{e_{1u}} \; \delta_{i + 1/2} [T] \rt]
+                                  + \delta_{j} \lt[ A_v^{lT} \; \frac{e_{1v} \, e_{3v}}{e_{2v}} \; \delta_{j + 1/2} [T] \rt] \Bigg)
+\end{equation}
+where $b_t = e_{1t} \, e_{2t} \, e_{3t}$  is the volume of $T$-cells and
+where zero diffusive fluxes is assumed across solid boundaries,
+first (and third in bilaplacian case) horizontal tracer derivative are masked.
+It is implemented in the \rou{tra\_ldf\_lap} subroutine found in the \mdl{traldf\_lap\_blp} module.
+The module also contains \rou{tra\_ldf\_blp},
+the subroutine calling twice \rou{tra\_ldf\_lap} in order to
+compute the iso-level bilaplacian operator.
+
+It is a \textit{horizontal} operator (\ie acting along geopotential surfaces) in
+the $z$-coordinate with or without partial steps,
+but is simply an iso-level operator in the $s$-coordinate.
+It is thus used when,
+in addition to \np{ln_traldf_lap}{ln\_traldf\_lap} or \np[=.true.]{ln_traldf_blp}{ln\_traldf\_blp},
+we have \np[=.true.]{ln_traldf_lev}{ln\_traldf\_lev} or
+\np[=]{ln_traldf_hor}{ln\_traldf\_hor}\np[=.true.]{ln_zco}{ln\_zco}.
+In both cases, it significantly contributes to diapycnal mixing.
+It is therefore never recommended, even when using it in the bilaplacian case.
+
+Note that in the partial step $z$-coordinate (\np[=.true.]{ln_zps}{ln\_zps}),
+tracers in horizontally adjacent cells are located at different depths in the vicinity of the bottom.
+In this case,
+horizontal derivatives in (\autoref{eq:TRA_ldf_lap}) at the bottom level require a specific treatment.
+They are calculated in the \mdl{zpshde} module, described in \autoref{sec:TRA_zpshde}.
+
+%% =================================================================================================
+\subsection{Standard and triad (bi-)laplacian operator}
+\label{subsec:TRA_ldf_iso_triad}
+
+%% =================================================================================================
+\subsubsection[Standard rotated (bi-)laplacian operator (\textit{traldf\_iso.F90})]{Standard rotated (bi-)laplacian operator (\protect\mdl{traldf\_iso})}
+\label{subsec:TRA_ldf_iso}
+
+The general form of the second order lateral tracer subgrid scale physics (\autoref{eq:MB_zdf})
+takes the following semi-discrete space form in $z$- and $s$-coordinates:
+\begin{equation}
+  \label{eq:TRA_ldf_iso}
+  \begin{split}
+    D_T^{lT} = \frac{1}{b_t} \Bigg[ \quad &\delta_i A_u^{lT} \lt( \frac{e_{2u} e_{3u}}{e_{1u}}                      \, \delta_{i + 1/2} [T]
+                                                                  - e_{2u} r_{1u} \, \overline{\overline{\delta_{k + 1/2} [T]}}^{\,i + 1/2,k} \rt) \Bigg. \\
+                                    +     &\delta_j A_v^{lT} \lt( \frac{e_{1v} e_{3v}}{e_{2v}}                       \, \delta_{j + 1/2} [T]
+                                                                  - e_{1v} r_{2v} \, \overline{\overline{\delta_{k + 1/2} [T]}}^{\,j + 1/2,k} \rt)        \\
+                                   +     &\delta_k A_w^{lT} \lt( \frac{e_{1w} e_{2w}}{e_{3w}} (r_{1w}^2 + r_{2w}^2) \, \delta_{k + 1/2} [T] \rt.           \\
+                                   & \qquad \quad \Bigg. \lt.     - e_{2w} r_{1w} \, \overline{\overline{\delta_{i + 1/2} [T]}}^{\,i,k + 1/2}
+                                                                  - e_{1w} r_{2w} \, \overline{\overline{\delta_{j + 1/2} [T]}}^{\,j,k + 1/2} \rt) \Bigg]
+  \end{split}
+\end{equation}
+where $b_t = e_{1t} \, e_{2t} \, e_{3t}$  is the volume of $T$-cells,
+$r_1$ and $r_2$ are the slopes between the surface of computation ($z$- or $s$-surfaces) and
+the surface along which the diffusion operator acts (\ie\ horizontal or iso-neutral surfaces).
+It is thus used when, in addition to \np[=.true.]{ln_traldf_lap}{ln\_traldf\_lap},
+we have \np[=.true.]{ln_traldf_iso}{ln\_traldf\_iso},
+or both \np[=.true.]{ln_traldf_hor}{ln\_traldf\_hor} and \np[=.true.]{ln_zco}{ln\_zco}.
+The way these slopes are evaluated is given in \autoref{sec:LDF_slp}.
+At the surface, bottom and lateral boundaries,
+the turbulent fluxes of heat and salt are set to zero using the mask technique
+(see \autoref{sec:LBC_coast}).
+
+The operator in \autoref{eq:TRA_ldf_iso} involves both lateral and vertical derivatives.
+For numerical stability, the vertical second derivative must be solved using
+the same implicit time scheme as that used in the vertical physics (see \autoref{sec:TRA_zdf}).
+For computer efficiency reasons, this term is not computed in the \mdl{traldf\_iso} module,
+but in the \mdl{trazdf} module where, if iso-neutral mixing is used,
+the vertical mixing coefficient is simply increased by
+$\frac{e_{1w} e_{2w}}{e_{3w}}(r_{1w}^2 + r_{2w}^2)$.
+
+This formulation conserves the tracer but does not ensure the decrease of the tracer variance.
+Nevertheless the treatment performed on the slopes (see \autoref{chap:LDF}) allows the model to
+run safely without any additional background horizontal diffusion \citep{guilyardi.madec.ea_CD01}.
+
+Note that in the partial step $z$-coordinate (\np[=.true.]{ln_zps}{ln\_zps}),
+the horizontal derivatives at the bottom level in \autoref{eq:TRA_ldf_iso} require
+a specific treatment.
+They are calculated in module zpshde, described in \autoref{sec:TRA_zpshde}.
+
+%% =================================================================================================
+\subsubsection[Triad rotated (bi-)laplacian operator (\forcode{ln_traldf_triad})]{Triad rotated (bi-)laplacian operator (\protect\np{ln_traldf_triad}{ln\_traldf\_triad})}
+\label{subsec:TRA_ldf_triad}
+
+An alternative scheme developed by \cite{griffies.gnanadesikan.ea_JPO98} which
+ensures tracer variance decreases is also available in \NEMO\
+(\np[=.true.]{ln_traldf_triad}{ln\_traldf\_triad}).
+A complete description of the algorithm is given in \autoref{apdx:TRIADS}.
+
+The lateral fourth order bilaplacian operator on tracers is obtained by
+applying (\autoref{eq:TRA_ldf_lap}) twice.
+The operator requires an additional assumption on boundary conditions:
+both first and third derivative terms normal to the coast are set to zero.
+
+The lateral fourth order operator formulation on tracers is obtained by
+applying (\autoref{eq:TRA_ldf_iso}) twice.
+It requires an additional assumption on boundary conditions:
+first and third derivative terms normal to the coast,
+normal to the bottom and normal to the surface are set to zero.
+
+%% =================================================================================================
+\subsubsection{Option for the rotated operators}
+\label{subsec:TRA_ldf_options}
+
+\begin{labeling}{{\np{ln_botmix_triad}{ln\_botmix\_triad}}}
+\item [{\np{ln_traldf_msc}{ln\_traldf\_msc}    }] Method of Stabilizing Correction (both operators)
+\item [{\np{rn_slpmax}{rn\_slpmax}             }] Slope limit (both operators)
+\item [{\np{ln_triad_iso}{ln\_triad\_iso}      }] Pure horizontal mixing in ML (triad only)
+\item [{\np{rn_sw_triad}{rn\_sw\_triad}        }] \forcode{=1} switching triad;
+  \forcode{= 0} all 4 triads used (triad only)
+\item [{\np{ln_botmix_triad}{ln\_botmix\_triad}}] Lateral mixing on bottom (triad only)
+\end{labeling}
+
+%% =================================================================================================
+\section[Tracer vertical diffusion (\textit{trazdf.F90})]{Tracer vertical diffusion (\protect\mdl{trazdf})}
+\label{sec:TRA_zdf}
+
+Options are defined through the \nam{zdf}{zdf} namelist variables.
+The formulation of the vertical subgrid scale tracer physics is the same for
+all the vertical coordinates, and is based on a laplacian operator.
+The vertical diffusion operator given by (\autoref{eq:MB_zdf}) takes
+the following semi-discrete space form:
+\[
+  % \label{eq:TRA_zdf}
+  D^{vT}_T = \frac{1}{e_{3t}} \, \delta_k \lt[ \, \frac{A^{vT}_w}{e_{3w}} \delta_{k + 1/2}[T] \, \rt] \quad
+  D^{vS}_T = \frac{1}{e_{3t}} \; \delta_k \lt[ \, \frac{A^{vS}_w}{e_{3w}} \delta_{k + 1/2}[S] \, \rt]
+\]
+where $A_w^{vT}$ and $A_w^{vS}$ are the vertical eddy diffusivity coefficients on
+temperature and salinity, respectively.
+Generally, $A_w^{vT} = A_w^{vS}$ except when double diffusive mixing is parameterised
+(\ie\ \np[=.true.]{ln_zdfddm}{ln\_zdfddm},).
+The way these coefficients are evaluated is given in \autoref{chap:ZDF} (ZDF).
+Furthermore, when iso-neutral mixing is used,
+both mixing coefficients are increased by $\frac{e_{1w} e_{2w}}{e_{3w} }({r_{1w}^2 + r_{2w}^2})$ to
+account for the vertical second derivative of \autoref{eq:TRA_ldf_iso}.
+
+At the surface and bottom boundaries, the turbulent fluxes of heat and salt must be specified.
+At the surface they are prescribed from the surface forcing and added in a dedicated routine
+(see \autoref{subsec:TRA_sbc}), whilst at the bottom they are set to zero for heat and salt unless
+a geothermal flux forcing is prescribed as a bottom boundary condition (see \autoref{subsec:TRA_bbc}).
+
+The large eddy coefficient found in the mixed layer together with high vertical resolution implies
+that there would be too restrictive constraint on the time step if we use explicit time stepping.
+Therefore an implicit time stepping is preferred for the vertical diffusion since
+it overcomes the stability constraint.
+
+%% =================================================================================================
+\section{External forcing}
+\label{sec:TRA_sbc_qsr_bbc}
+
+%% =================================================================================================
+\subsection[Surface boundary condition (\textit{trasbc.F90})]{Surface boundary condition (\protect\mdl{trasbc})}
+\label{subsec:TRA_sbc}
+
+The surface boundary condition for tracers is implemented in a separate module (\mdl{trasbc}) instead of
+entering as a boundary condition on the vertical diffusion operator (as in the case of momentum).
+This has been found to enhance readability of the code.
+The two formulations are completely equivalent;
+the forcing terms in trasbc are the surface fluxes divided by the thickness of the top model layer.
+
+Due to interactions and mass exchange of water ($F_{mass}$) with other Earth system components
+(\ie\ atmosphere, sea-ice, land),
+the change in the heat and salt content of the surface layer of the ocean is due both to
+the heat and salt fluxes crossing the sea surface (not linked with $F_{mass}$) and
+to the heat and salt content of the mass exchange.
+They are both included directly in $Q_{ns}$, the surface heat flux,
+and $F_{salt}$, the surface salt flux (see \autoref{chap:SBC} for further details).
+By doing this, the forcing formulation is the same for any tracer
+(including temperature and salinity).
+
+The surface module (\mdl{sbcmod}, see \autoref{chap:SBC}) provides the following forcing fields
+(used on tracers):
+
+\begin{labeling}{\textit{fwfisf}}
+\item [$Q_{ns}$] The non-solar part of the net surface heat flux that crosses the sea surface
+  (\ie\ the difference between the total surface heat flux and
+  the fraction of the short wave flux that penetrates into the water column,
+  see \autoref{subsec:TRA_qsr})
+  plus the heat content associated with of the mass exchange with the atmosphere and lands.
+\item [\textit{sfx}] The salt flux resulting from ice-ocean mass exchange
+  (freezing, melting, ridging...)
+\item [\textit{emp}] The mass flux exchanged with the atmosphere (evaporation minus precipitation) and
+  possibly with the sea-ice and ice-shelves.
+\item [\textit{rnf}] The mass flux associated with runoff
+  (see \autoref{sec:SBC_rnf} for further detail of how it acts on temperature and salinity tendencies)
+\item [\textit{fwfisf}] The mass flux associated with ice shelf melt,
+  (see \autoref{sec:SBC_isf} for further details on how the ice shelf melt is computed and applied).
+\end{labeling}
+
+The surface boundary condition on temperature and salinity is applied as follows:
+\begin{equation}
+  \label{eq:TRA_sbc}
+    F^T = \frac{1}{C_p} \frac{1}{\rho_o \lt. e_{3t} \rt|_{k = 1}} \overline{Q_{ns}      }^t \qquad
+    F^S =               \frac{1}{\rho_o \lt. e_{3t} \rt|_{k = 1}} \overline{\textit{sfx}}^t
+\end{equation}
+where $\overline x^t$ means that $x$ is averaged over two consecutive time steps
+($t - \rdt / 2$ and $t + \rdt / 2$).
+Such time averaging prevents the divergence of odd and even time step (see \autoref{chap:TD}).
+
+In the linear free surface case (\np[=.true.]{ln_linssh}{ln\_linssh}),
+an additional term has to be added on both temperature and salinity.
+On temperature, this term remove the heat content associated with
+mass exchange that has been added to $Q_{ns}$.
+On salinity, this term mimics the concentration/dilution effect that would have resulted from
+a change in the volume of the first level.
+The resulting surface boundary condition is applied as follows:
+\begin{equation}
+  \label{eq:TRA_sbc_lin}
+    F^T = \frac{1}{C_p} \frac{1}{\rho_o \lt. e_{3t} \rt|_{k = 1}}
+          \overline{(Q_{ns}       - C_p \, \textit{emp} \lt. T \rt|_{k = 1})}^t \qquad
+    F^S =               \frac{1}{\rho_o \lt. e_{3t} \rt|_{k = 1}}
+          \overline{(\textit{sfx} -        \textit{emp} \lt. S \rt|_{k = 1})}^t
+\end{equation}
+Note that an exact conservation of heat and salt content is only achieved with
+non-linear free surface.
+In the linear free surface case, there is a small imbalance.
+The imbalance is larger than the imbalance associated with the Asselin time filter
+\citep{leclair.madec_OM09}.
+This is the reason why the modified filter is not applied in the linear free surface case
+(see \autoref{chap:TD}).
+
+%% =================================================================================================
+\subsection[Solar radiation penetration (\textit{traqsr.F90})]{Solar radiation penetration (\protect\mdl{traqsr})}
+\label{subsec:TRA_qsr}
+
+\begin{listing}
+  \nlst{namtra_qsr}
+  \caption{\forcode{&namtra_qsr}}
+  \label{lst:namtra_qsr}
+\end{listing}
+
+Options are defined through the \nam{tra_qsr}{tra\_qsr} namelist variables.
+When the penetrative solar radiation option is used (\np[=.true.]{ln_traqsr}{ln\_traqsr}),
+the solar radiation penetrates the top few tens of meters of the ocean.
+If it is not used (\np[=.false.]{ln_traqsr}{ln\_traqsr}) all the heat flux is absorbed in
+the first ocean level.
+Thus, in the former case a term is added to the time evolution equation of temperature
+\autoref{eq:MB_PE_tra_T} and the surface boundary condition is modified to
+take into account only the non-penetrative part of the surface heat flux:
+\begin{equation}
+  \label{eq:TRA_PE_qsr}
+  \begin{gathered}
+    \pd[T]{t} = \ldots + \frac{1}{\rho_o \, C_p \, e_3} \; \pd[I]{k} \\
+    Q_{ns} = Q_\text{Total} - Q_{sr}
+  \end{gathered}
+\end{equation}
+where $Q_{sr}$ is the penetrative part of the surface heat flux (\ie\ the shortwave radiation) and
+$I$ is the downward irradiance ($\lt. I \rt|_{z = \eta} = Q_{sr}$).
+The additional term in \autoref{eq:TRA_PE_qsr} is discretized as follows:
+\begin{equation}
+  \label{eq:TRA_qsr}
+  \frac{1}{\rho_o \, C_p \, e_3} \, \pd[I]{k} \equiv \frac{1}{\rho_o \, C_p \, e_{3t}} \delta_k [I_w]
+\end{equation}
+
+The shortwave radiation, $Q_{sr}$, consists of energy distributed across a wide spectral range.
+The ocean is strongly absorbing for wavelengths longer than 700 $nm$ and
+these wavelengths contribute to heat the upper few tens of centimetres.
+The fraction of $Q_{sr}$ that resides in these almost non-penetrative wavebands, $R$, is $\sim$ 58\%
+(specified through namelist parameter \np{rn_abs}{rn\_abs}).
+It is assumed to penetrate the ocean with a decreasing exponential profile,
+with an e-folding depth scale, $\xi_0$, of a few tens of centimetres
+(typically $\xi_0 = 0.35~m$ set as \np{rn_si0}{rn\_si0} in the \nam{tra_qsr}{tra\_qsr} namelist).
+For shorter wavelengths (400-700 $nm$), the ocean is more transparent,
+and solar energy propagates to larger depths where it contributes to local heating.
+The way this second part of the solar energy penetrates into
+the ocean depends on which formulation is chosen.
+In the simple 2-waveband light penetration scheme (\np[=.true.]{ln_qsr_2bd}{ln\_qsr\_2bd})
+a chlorophyll-independent monochromatic formulation is chosen for the shorter wavelengths,
+leading to the following expression \citep{paulson.simpson_JPO77}:
+\[
+  % \label{eq:TRA_qsr_iradiance}
+  I(z) = Q_{sr} \lt[ Re^{- z / \xi_0} + (1 - R) e^{- z / \xi_1} \rt]
+\]
+where $\xi_1$ is the second extinction length scale associated with the shorter wavelengths.
+It is usually chosen to be 23~m by setting the \np{rn_si0}{rn\_si0} namelist parameter.
+The set of default values ($\xi_0, \xi_1, R$) corresponds to
+a Type I water in Jerlov's (1968) classification (oligotrophic waters).
+
+Such assumptions have been shown to provide a very crude and simplistic representation of
+observed light penetration profiles (\cite{morel_JGR88}, see also \autoref{fig:TRA_qsr_irradiance}).
+Light absorption in the ocean depends on particle concentration and is spectrally selective.
+\cite{morel_JGR88} has shown that an accurate representation of light penetration can be provided by
+a 61 waveband formulation.
+Unfortunately, such a model is very computationally expensive.
+Thus, \cite{lengaigne.menkes.ea_CD07} have constructed a simplified version of
+this formulation in which visible light is split into three wavebands:
+blue (400-500 $nm$), green (500-600 $nm$) and red (600-700 $nm$).
+For each wave-band, the chlorophyll-dependent attenuation coefficient is fitted to
+the coefficients computed from the full spectral model of \cite{morel_JGR88}
+(as modified by \cite{morel.maritorena_JGR01}), assuming the same power-law relationship.
+As shown in \autoref{fig:TRA_qsr_irradiance}, this formulation,
+called RGB (\textbf{R}ed-\textbf{G}reen-\textbf{B}lue),
+reproduces quite closely the light penetration profiles predicted by the full spectal model,
+but with much greater computational efficiency.
+The 2-bands formulation does not reproduce the full model very well.
+
+The RGB formulation is used when \np[=.true.]{ln_qsr_rgb}{ln\_qsr\_rgb}.
+The RGB attenuation coefficients (\ie\ the inverses of the extinction length scales) are
+tabulated over 61 nonuniform chlorophyll classes ranging from 0.01 to 10 $g.Chl/L$
+(see the routine \rou{trc\_oce\_rgb} in \mdl{trc\_oce} module).
+Four types of chlorophyll can be chosen in the RGB formulation:
+
+\begin{description}
+\item [{\np[=0]{nn_chldta}{nn\_chldta}}] a constant 0.05 $g.Chl/L$ value everywhere;
+\item [{\np[=1]{nn_chldta}{nn\_chldta}}] an observed time varying chlorophyll deduced from
+  satellite surface ocean color measurement spread uniformly in the vertical direction;
+\item [{\np[=2]{nn_chldta}{nn\_chldta}}] same as previous case except that
+  a vertical profile of chlorophyl is used.
+  Following \cite{morel.berthon_LO89},
+  the profile is computed from the local surface chlorophyll value;
+\item [{\np[=.true.]{ln_qsr_bio}{ln\_qsr\_bio}}] simulated time varying chlorophyll by
+  \TOP\ biogeochemical model.
+  In this case, the RGB formulation is used to calculate both
+  the phytoplankton light limitation in \PISCES\ and the oceanic heating rate.
+\end{description}
+
+The trend in \autoref{eq:TRA_qsr} associated with the penetration of the solar radiation is added to
+the temperature trend, and the surface heat flux is modified in routine \mdl{traqsr}.
+
+When the $z$-coordinate is preferred to the $s$-coordinate,
+the depth of $w-$levels does not significantly vary with location.
+The level at which the light has been totally absorbed
+(\ie\ it is less than the computer precision) is computed once,
+and the trend associated with the penetration of the solar radiation is only added down to that level.
+Finally, note that when the ocean is shallow ($<$ 200~m),
+part of the solar radiation can reach the ocean floor.
+In this case, we have chosen that all remaining radiation is absorbed in the last ocean level
+(\ie\ $I$ is masked).
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRA_Irradiance}
+  \caption[Penetration profile of the downward solar irradiance calculated by four models]{
+    Penetration profile of the downward solar irradiance calculated by four models.
+    Two waveband chlorophyll-independent formulation (blue),
+    a chlorophyll-dependent monochromatic formulation (green),
+    4 waveband RGB formulation (red),
+    61 waveband Morel (1988) formulation (black) for a chlorophyll concentration of
+    (a) Chl=0.05 $mg/m^3$ and (b) Chl=0.5 $mg/m^3$.
+    From \citet{lengaigne.menkes.ea_CD07}.}
+  \label{fig:TRA_qsr_irradiance}
+\end{figure}
+
+%% =================================================================================================
+\subsection[Bottom boundary condition (\textit{trabbc.F90}) - \forcode{ln_trabbc})]{Bottom boundary condition (\protect\mdl{trabbc} - \protect\np{ln_trabbc}{ln\_trabbc})}
+\label{subsec:TRA_bbc}
+
+\begin{listing}
+  \nlst{nambbc}
+  \caption{\forcode{&nambbc}}
+  \label{lst:nambbc}
+\end{listing}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{TRA_geoth}
+  \caption[Geothermal heat flux]{
+    Geothermal Heat flux (in $mW.m^{-2}$) used by \cite{emile-geay.madec_OS09}.
+    It is inferred from the age of the sea floor and the formulae of \citet{stein.stein_N92}.}
+  \label{fig:TRA_geothermal}
+\end{figure}
+
+Usually it is assumed that there is no exchange of heat or salt through the ocean bottom,
+\ie\ a no flux boundary condition is applied on active tracers at the bottom.
+This is the default option in \NEMO, and it is implemented using the masking technique.
+However, there is a non-zero heat flux across the seafloor that
+is associated with solid earth cooling.
+This flux is weak compared to surface fluxes
+(a mean global value of $\sim 0.1 \, W/m^2$ \citep{stein.stein_N92}),
+but it warms systematically the ocean and acts on the densest water masses.
+Taking this flux into account in a global ocean model increases the deepest overturning cell
+(\ie\ the one associated with the Antarctic Bottom Water) by
+a few Sverdrups \citep{emile-geay.madec_OS09}.
+
+Options are defined through the \nam{bbc}{bbc} namelist variables.
+The presence of geothermal heating is controlled by
+setting the namelist parameter \np{ln_trabbc}{ln\_trabbc} to true.
+Then, when \np{nn_geoflx}{nn\_geoflx} is set to 1, a constant geothermal heating is introduced whose
+value is given by the \np{rn_geoflx_cst}{rn\_geoflx\_cst}, which is also a namelist parameter.
+When \np{nn_geoflx}{nn\_geoflx} is set to 2,
+a spatially varying geothermal heat flux is introduced which is provided in
+the \ifile{geothermal\_heating} NetCDF file
+(\autoref{fig:TRA_geothermal}) \citep{emile-geay.madec_OS09}.
+
+%% =================================================================================================
+\section[Bottom boundary layer (\textit{trabbl.F90} - \forcode{ln_trabbl})]{Bottom boundary layer (\protect\mdl{trabbl} - \protect\np{ln_trabbl}{ln\_trabbl})}
+\label{sec:TRA_bbl}
+
+\begin{listing}
+  \nlst{nambbl}
+  \caption{\forcode{&nambbl}}
+  \label{lst:nambbl}
+\end{listing}
+
+Options are defined through the \nam{bbl}{bbl} namelist variables.
+In a $z$-coordinate configuration, the bottom topography is represented by a series of discrete steps.
+This is not adequate to represent gravity driven downslope flows.
+Such flows arise either downstream of sills such as the Strait of Gibraltar or Denmark Strait,
+where dense water formed in marginal seas flows into a basin filled with less dense water,
+or along the continental slope when dense water masses are formed on a continental shelf.
+The amount of entrainment that occurs in these gravity plumes is critical in
+determining the density and volume flux of the densest waters of the ocean,
+such as Antarctic Bottom Water, or North Atlantic Deep Water.
+$z$-coordinate models tend to overestimate the entrainment,
+because the gravity flow is mixed vertically by convection as
+it goes ''downstairs'' following the step topography,
+sometimes over a thickness much larger than the thickness of the observed gravity plume.
+A similar problem occurs in the $s$-coordinate when
+the thickness of the bottom level varies rapidly downstream of a sill
+\citep{willebrand.barnier.ea_PO01}, and the thickness of the plume is not resolved.
+
+The idea of the bottom boundary layer (BBL) parameterisation, first introduced by
+\citet{beckmann.doscher_JPO97},
+is to allow a direct communication between two adjacent bottom cells at different levels,
+whenever the densest water is located above the less dense water.
+The communication can be by a diffusive flux (diffusive BBL),
+an advective flux (advective BBL), or both.
+In the current implementation of the BBL, only the tracers are modified, not the velocities.
+Furthermore, it only connects ocean bottom cells,
+and therefore does not include all the improvements introduced by \citet{campin.goosse_T99}.
+
+%% =================================================================================================
+\subsection[Diffusive bottom boundary layer (\forcode{nn_bbl_ldf=1})]{Diffusive bottom boundary layer (\protect\np[=1]{nn_bbl_ldf}{nn\_bbl\_ldf})}
+\label{subsec:TRA_bbl_diff}
+
+When applying sigma-diffusion
+(\np[=.true.]{ln_trabbl}{ln\_trabbl} and \np{nn_bbl_ldf}{nn\_bbl\_ldf} set to 1),
+the diffusive flux between two adjacent cells at the ocean floor is given by
+\[
+  % \label{eq:TRA_bbl_diff}
+  \vect F_\sigma = A_l^\sigma \, \nabla_\sigma T
+\]
+with $\nabla_\sigma$ the lateral gradient operator taken between bottom cells,
+and $A_l^\sigma$ the lateral diffusivity in the BBL.
+Following \citet{beckmann.doscher_JPO97}, the latter is prescribed with a spatial dependence,
+\ie\ in the conditional form
+\begin{equation}
+  \label{eq:TRA_bbl_coef}
+  A_l^\sigma (i,j,t) =
+      \begin{cases}
+        A_{bbl} & \text{if~} \nabla_\sigma \rho \cdot \nabla H < 0 \\
+        0      & \text{otherwise}
+      \end{cases}
+\end{equation}
+where $A_{bbl}$ is the BBL diffusivity coefficient,
+given by the namelist parameter \np{rn_ahtbbl}{rn\_ahtbbl} and
+usually set to a value much larger than the one used for lateral mixing in the open ocean.
+The constraint in \autoref{eq:TRA_bbl_coef} implies that sigma-like diffusion only occurs when
+the density above the sea floor, at the top of the slope, is larger than in the deeper ocean
+(see green arrow in \autoref{fig:TRA_bbl}).
+In practice, this constraint is applied separately in the two horizontal directions,
+and the density gradient in \autoref{eq:TRA_bbl_coef} is evaluated with the log gradient formulation:
+\[
+  % \label{eq:TRA_bbl_Drho}
+  \nabla_\sigma \rho / \rho = \alpha \, \nabla_\sigma T + \beta \, \nabla_\sigma S
+\]
+where $\rho$, $\alpha$ and $\beta$ are functions of
+$\overline T^\sigma$, $\overline S^\sigma$ and $\overline H^\sigma$,
+the along bottom mean temperature, salinity and depth, respectively.
+
+%% =================================================================================================
+\subsection[Advective bottom boundary layer (\forcode{nn_bbl_adv=1,2})]{Advective bottom boundary layer (\protect\np[=1,2]{nn_bbl_adv}{nn\_bbl\_adv})}
+\label{subsec:TRA_bbl_adv}
+
+%\sgacomment{
+%  "downsloping flow" has been replaced by "downslope flow" in the following
+%  if this is not what is meant then "downwards sloping flow" is also a possibility"
+%}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{TRA_BBL_adv}
+  \caption[Advective/diffusive bottom boundary layer]{
+    Advective/diffusive Bottom Boundary Layer.
+    The BBL parameterisation is activated when $\rho^i_{kup}$ is larger than $\rho^{i + 1}_{kdnw}$.
+    Red arrows indicate the additional overturning circulation due to the advective BBL.
+    The transport of the downslope flow is defined either
+    as the transport of the bottom ocean cell (black arrow),
+    or as a function of the along slope density gradient.
+    The green arrow indicates the diffusive BBL flux directly connecting
+    $kup$ and $kdwn$ ocean bottom cells.}
+  \label{fig:TRA_bbl}
+\end{figure}
+
+%!!      nn_bbl_adv = 1   use of the ocean velocity as bbl velocity
+%!!      nn_bbl_adv = 2   follow Campin and Goosse (1999) implentation
+%!!        i.e. transport proportional to the along-slope density gradient
+
+\cmtgm{This section has to be really written}
+
+When applying an advective BBL (\np[=1..2]{nn_bbl_adv}{nn\_bbl\_adv}),
+an overturning circulation is added which connects two adjacent bottom grid-points only if
+dense water overlies less dense water on the slope.
+The density difference causes dense water to move down the slope.
+
+\begin{description}
+\item [{\np[=1]{nn_bbl_adv}{nn\_bbl\_adv}}] the downslope velocity is chosen to
+  be the Eulerian ocean velocity just above the topographic step
+  (see black arrow in \autoref{fig:TRA_bbl}) \citep{beckmann.doscher_JPO97}.
+  It is a \textit{conditional advection}, that is,
+  advection is allowed only if dense water overlies less dense water on the slope
+  (\ie\ $\nabla_\sigma \rho \cdot \nabla H < 0$) and if the velocity is directed towards greater depth
+  (\ie\ $\vect U \cdot \nabla H > 0$).
+\item [{\np[=2]{nn_bbl_adv}{nn\_bbl\_adv}}] the downslope velocity is chosen to be proportional to
+  $\Delta \rho$, the density difference between the higher cell and lower cell densities
+  \citep{campin.goosse_T99}.
+  The advection is allowed only  if dense water overlies less dense water on the slope
+  (\ie\ $\nabla_\sigma \rho \cdot \nabla H < 0$).
+  For example, the resulting transport of the downslope flow, here in the $i$-direction
+  (\autoref{fig:TRA_bbl}), is simply given by the following expression:
+  \[
+    % \label{eq:TRA_bbl_Utr}
+    u^{tr}_{bbl} = \gamma g \frac{\Delta \rho}{\rho_o} e_{1u} \, min ({e_{3u}}_{kup},{e_{3u}}_{kdwn})
+  \]
+  where $\gamma$, expressed in seconds, is the coefficient of proportionality provided as
+  \np{rn_gambbl}{rn\_gambbl}, a namelist parameter, and
+  \textit{kup} and \textit{kdwn} are the vertical index of the higher and lower cells, respectively.
+  The parameter $\gamma$ should take a different value for each bathymetric step, but for simplicity,
+  and because no direct estimation of this parameter is available, a uniform value has been assumed.
+  The possible values for $\gamma$ range between 1 and $10~s$ \citep{campin.goosse_T99}.
+\end{description}
+
+Scalar properties are advected by this additional transport $(u^{tr}_{bbl},v^{tr}_{bbl})$ using
+the upwind scheme.
+Such a diffusive advective scheme has been chosen to mimic the entrainment between
+the downslope plume and the surrounding water at intermediate depths.
+The entrainment is replaced by the vertical mixing implicit in the advection scheme.
+Let us consider as an example the case displayed in \autoref{fig:TRA_bbl} where
+the density at level $(i,kup)$ is larger than the one at level $(i,kdwn)$.
+The advective BBL scheme modifies the tracer time tendency of
+the ocean cells near the topographic step by the downslope flow \autoref{eq:TRA_bbl_dw},
+the horizontal \autoref{eq:TRA_bbl_hor} and the upward \autoref{eq:TRA_bbl_up} return flows as follows:
+\begin{alignat}{5}
+  \label{eq:TRA_bbl_dw}
+  \partial_t T^{do}_{kdw} &\equiv \partial_t T^{do}_{kdw} &&+ \frac{u^{tr}_{bbl}}{{b_t}^{do}_{kdw}} &&\lt( T^{sh}_{kup} - T^{do}_{kdw} \rt) \\
+  \label{eq:TRA_bbl_hor}
+  \partial_t T^{sh}_{kup} &\equiv \partial_t T^{sh}_{kup} &&+ \frac{u^{tr}_{bbl}}{{b_t}^{sh}_{kup}} &&\lt( T^{do}_{kup} - T^{sh}_{kup} \rt) \\
+  \shortintertext{and for $k =kdw-1,\;..., \; kup$ :}
+  \label{eq:TRA_bbl_up}
+  \partial_t T^{do}_{k}   &\equiv \partial_t S^{do}_{k}   &&+ \frac{u^{tr}_{bbl}}{{b_t}^{do}_{k}}   &&\lt( T^{do}_{k +1} - T^{sh}_{k}   \rt)
+\end{alignat}
+where $b_t$ is the $T$-cell volume.
+
+Note that the BBL transport, $(u^{tr}_{bbl},v^{tr}_{bbl})$, is available in the model outputs.
+It has to be used to compute the effective velocity as well as the effective overturning circulation.
+
+%% =================================================================================================
+\section[Tracer damping (\textit{tradmp.F90})]{Tracer damping (\protect\mdl{tradmp})}
+\label{sec:TRA_dmp}
+
+\begin{listing}
+  \nlst{namtra_dmp}
+  \caption{\forcode{&namtra_dmp}}
+  \label{lst:namtra_dmp}
+\end{listing}
+
+In some applications it can be useful to add a Newtonian damping term into
+the temperature and salinity equations:
+\begin{equation}
+  \label{eq:TRA_dmp}
+    \pd[T]{t} = \cdots - \gamma (T - T_o) \qquad \pd[S]{t} = \cdots - \gamma (S - S_o)
+\end{equation}
+where $\gamma$ is the inverse of a time scale,
+and $T_o$ and $S_o$ are given temperature and salinity fields (usually a climatology).
+Options are defined through the \nam{tra_dmp}{tra\_dmp} namelist variables.
+The restoring term is added when the namelist parameter \np{ln_tradmp}{ln\_tradmp} is set to true.
+It also requires that both \np{ln_tsd_init}{ln\_tsd\_init} and
+\np{ln_tsd_dmp}{ln\_tsd\_dmp} are set to true in \nam{tsd}{tsd} namelist as well as
+\np{sn_tem}{sn\_tem} and \np{sn_sal}{sn\_sal} structures are correctly set
+(\ie\ that $T_o$ and $S_o$ are provided in input files and read using \mdl{fldread},
+see \autoref{subsec:SBC_fldread}).
+The restoring coefficient $\gamma$ is a three-dimensional array read in during
+the \rou{tra\_dmp\_init} routine.
+The file name is specified by the namelist variable \np{cn_resto}{cn\_resto}.
+The \texttt{DMP\_TOOLS} are provided to allow users to generate the netcdf file.
+
+The two main cases in which \autoref{eq:TRA_dmp} is used are
+\begin{enumerate*}[label=(\textit{\alph*})]
+\item the specification of the boundary conditions along
+  artificial walls of a limited domain basin and
+\item the computation of the velocity field associated with a given $T$-$S$ field
+  (for example to build the initial state of a prognostic simulation,
+  or to use the resulting velocity field for a passive tracer study).
+\end{enumerate*}
+The first case applies to regional models that have artificial walls instead of open boundaries.
+In the vicinity of these walls, $\gamma$ takes large values (equivalent to a time scale of a few days)
+whereas it is zero in the interior of the model domain.
+The second case corresponds to the use of the robust diagnostic method \citep{sarmiento.bryan_JGR82}.
+It allows us to find the velocity field consistent with the model dynamics whilst
+having a $T$, $S$ field close to a given climatological field ($T_o$, $S_o$).
+
+The robust diagnostic method is very efficient in preventing temperature drift in
+intermediate waters but it produces artificial sources of heat and salt within the ocean.
+It also has undesirable effects on the ocean convection.
+It tends to prevent deep convection and subsequent deep-water formation,
+by stabilising the water column too much.
+
+The namelist parameter \np{nn_zdmp}{nn\_zdmp} sets whether the damping should be applied in
+the whole water column or only below the mixed layer (defined either on a density or $S_o$ criterion).
+It is common to set the damping to zero in the mixed layer as the adjustment time scale is short here
+\citep{madec.delecluse.ea_JPO96}.
+
+For generating \ifile{resto},
+see the documentation for the DMP tools provided with the source code under \path{./tools/DMP_TOOLS}.
+
+%% =================================================================================================
+\section[Tracer time evolution (\textit{tranxt.F90})]{Tracer time evolution (\protect\mdl{tranxt})}
+\label{sec:TRA_nxt}
+
+Options are defined through the \nam{dom}{dom} namelist variables.
+The general framework for tracer time stepping is a modified leap-frog scheme
+\citep{leclair.madec_OM09}, \ie\ a three level centred time scheme associated with
+a Asselin time filter (cf. \autoref{sec:TD_mLF}):
+\begin{equation}
+  \label{eq:TRA_nxt}
+  \begin{alignedat}{5}
+    &(e_{3t}T)^{t + \rdt} &&= (e_{3t}T)_f^{t - \rdt} &&+ 2 \, \rdt \,e_{3t}^t \ \text{RHS}^t \\
+    &(e_{3t}T)_f^t        &&= (e_{3t}T)^t            &&+ \, \gamma \, \lt[ (e_{3t}T)_f^{t - \rdt} - 2(e_{3t}T)^t + (e_{3t}T)^{t + \rdt} \rt] \\
+    &                     &&                         &&- \, \gamma \, \rdt \, \lt[ Q^{t + \rdt/2} - Q^{t - \rdt/2} \rt]
+  \end{alignedat}
+\end{equation}
+where RHS is the right hand side of the temperature equation,
+the subscript $f$ denotes filtered values, $\gamma$ is the Asselin coefficient,
+and $S$ is the total forcing applied on $T$ (\ie\ fluxes plus content in mass exchanges).
+$\gamma$ is initialized as \np{rn_atfp}{rn\_atfp}, its default value is \forcode{10.e-3}.
+Note that the forcing correction term in the filter is not applied in linear free surface
+(\jp{ln\_linssh}\forcode{=.true.}) (see \autoref{subsec:TRA_sbc}).
+Not also that in constant volume case, the time stepping is performed on $T$,
+not on its content, $e_{3t}T$.
+
+When the vertical mixing is solved implicitly,
+the update of the \textit{next} tracer fields is done in \mdl{trazdf} module.
+In this case only the swapping of arrays and the Asselin filtering is done in the \mdl{tranxt} module.
+
+In order to prepare for the computation of the \textit{next} time step,
+a swap of tracer arrays is performed: $T^{t - \rdt} = T^t$ and $T^t = T_f$.
+
+%% =================================================================================================
+\section[Equation of state (\textit{eosbn2.F90})]{Equation of state (\protect\mdl{eosbn2})}
+\label{sec:TRA_eosbn2}
+
+\begin{listing}
+  \nlst{nameos}
+  \caption{\forcode{&nameos}}
+  \label{lst:nameos}
+\end{listing}
+
+%% =================================================================================================
+\subsection[Equation of seawater (\forcode{ln_}\{\forcode{teos10,eos80,seos}\})]{Equation of seawater (\protect\np{ln_teos10}{ln\_teos10}, \protect\np{ln_teos80}{ln\_teos80}, or \protect\np{ln_seos}{ln\_seos})}
+\label{subsec:TRA_eos}
+
+The \textbf{E}quation \textbf{O}f \textbf{S}eawater (EOS) is
+an empirical nonlinear thermodynamic relationship linking
+seawater density, $\rho$, to a number of state variables,
+most typically temperature, salinity and pressure.
+Because density gradients control the pressure gradient force through the hydrostatic balance,
+the equation of state provides a fundamental bridge between
+the distribution of active tracers and the fluid dynamics.
+Nonlinearities of the EOS are of major importance, in particular influencing the circulation through
+determination of the static stability below the mixed layer,
+thus controlling rates of exchange between the atmosphere and the ocean interior
+\citep{roquet.madec.ea_JPO15}.
+Therefore an accurate EOS based on either the 1980 equation of state
+(EOS-80, \cite{fofonoff.millard_bk83}) or TEOS-10 \citep{ioc.iapso_bk10} standards should
+be used anytime a simulation of the real ocean circulation is attempted \citep{roquet.madec.ea_JPO15}.
+The use of TEOS-10 is highly recommended because
+\begin{enumerate*}[label=(\textit{\roman*})]
+\item it is the new official EOS,
+\item it is more accurate, being based on an updated database of laboratory measurements, and
+\item it uses Conservative Temperature and Absolute Salinity
+  (instead of potential temperature and practical salinity for EOS-80),
+  both variables being more suitable for use as model variables
+  \citep{ioc.iapso_bk10, graham.mcdougall_JPO13}.
+\end{enumerate*}
+EOS-80 is an obsolescent feature of the \NEMO\ system, kept only for backward compatibility.
+For process studies, it is often convenient to use an approximation of the EOS.
+To that purposed, a simplified EOS (S-EOS) inspired by \citet{vallis_bk06} is also available.
+
+In the computer code, a density anomaly, $d_a = \rho / \rho_o - 1$, is computed,
+with $\rho_o$ a reference density.
+Called \textit{rau0} in the code,
+$\rho_o$ is set in \mdl{phycst} to a value of \texttt{1,026} $Kg/m^3$.
+This is a sensible choice for the reference density used in a Boussinesq ocean climate model,
+as, with the exception of only a small percentage of the ocean,
+density in the World Ocean varies by no more than 2\% from that value \citep{gill_bk82}.
+
+Options which control the EOS used are defined through the \nam{eos}{eos} namelist variables.
+
+\begin{description}
+\item [{\np[=.true.]{ln_teos10}{ln\_teos10}}] the polyTEOS10-bsq equation of seawater
+  \citep{roquet.madec.ea_OM15} is used.
+  The accuracy of this approximation is comparable to the TEOS-10 rational function approximation,
+  but it is optimized for a Boussinesq fluid and
+  the polynomial expressions have simpler and more computationally efficient expressions for
+  their derived quantities which make them more adapted for use in ocean models.
+  Note that a slightly higher precision polynomial form is now used
+  replacement of the TEOS-10 rational function approximation for hydrographic data analysis
+  \citep{ioc.iapso_bk10}.
+  A key point is that conservative state variables are used:
+  Absolute Salinity (unit: $g/kg$, notation: $S_A$) and
+  Conservative Temperature (unit: $\deg{C}$, notation: $\Theta$).
+  The pressure in decibars is approximated by the depth in meters.
+  With TEOS10, the specific heat capacity of sea water, $C_p$, is a constant.
+  It is set to $C_p$ = 3991.86795711963 $J.Kg^{-1}.\deg{K}^{-1}$,
+  according to \citet{ioc.iapso_bk10}.
+  Choosing polyTEOS10-bsq implies that the state variables used by the model are $\Theta$ and $S_A$.
+  In particular, the initial state defined by the user have to be given as
+  \textit{Conservative} Temperature and \textit{Absolute} Salinity.
+  In addition, when using TEOS10, the Conservative SST is converted to potential SST prior to
+  either computing the air-sea and ice-sea fluxes (forced mode) or
+  sending the SST field to the atmosphere (coupled mode).
+\item [{\np[=.true.]{ln_eos80}{ln\_eos80}}] the polyEOS80-bsq equation of seawater is used.
+  It takes the same polynomial form as the polyTEOS10,
+  but the coefficients have been optimized to accurately fit EOS80 (Roquet, personal comm.).
+  The state variables used in both the EOS80 and the ocean model are:
+  the Practical Salinity (unit: $psu$, notation: $S_p$) and
+  Potential Temperature (unit: $\deg{C}$, notation: $\theta$).
+  The pressure in decibars is approximated by the depth in meters.
+  With EOS, the specific heat capacity of sea water, $C_p$, is a function of
+  temperature, salinity and pressure \citep{fofonoff.millard_bk83}.
+  Nevertheless, a severe assumption is made in order to have a heat content ($C_p T_p$) which
+  is conserved by the model: $C_p$ is set to a constant value, the TEOS10 value.
+\item [{\np[=.true.]{ln_seos}{ln\_seos}}] a simplified EOS (S-EOS) inspired by
+  \citet{vallis_bk06} is chosen,
+  the coefficients of which has been optimized to fit the behavior of TEOS10 (Roquet, personal comm.)
+  (see also \citet{roquet.madec.ea_JPO15}).
+  It provides a simplistic linear representation of both cabbeling and thermobaricity effects which
+  is enough for a proper treatment of the EOS in theoretical studies \citep{roquet.madec.ea_JPO15}.
+  With such an equation of state there is no longer a distinction between \textit{conservative} and
+  \textit{potential} temperature, as well as between \textit{absolute} and
+  \textit{practical} salinity.
+  S-EOS takes the following expression:
+  \begin{gather*}
+    % \label{eq:TRA_S-EOS}
+    d_a(T,S,z) = \frac{1}{\rho_o} \big[ - a_0 \; ( 1 + 0.5 \; \lambda_1 \; T_a + \mu_1 \; z ) * T_a \big.
+                                        + b_0 \; ( 1 - 0.5 \; \lambda_2 \; S_a - \mu_2 \; z ) * S_a
+                                  \big. - \nu \;                           T_a                  S_a \big] \\
+    \text{with~} T_a = T - 10 \, ; \, S_a = S - 35 \, ; \, \rho_o = 1026~Kg/m^3
+  \end{gather*}
+  where the computer name of the coefficients as well as their standard value are given in
+  \autoref{tab:TRA_SEOS}.
+  In fact, when choosing S-EOS, various approximation of EOS can be specified simply by
+  changing the associated coefficients.
+  Setting to zero the two thermobaric coefficients $(\mu_1,\mu_2)$
+  remove thermobaric effect from S-EOS.
+  Setting to zero the three cabbeling coefficients $(\lambda_1,\lambda_2,\nu)$
+  remove   cabbeling effect from S-EOS.
+  Keeping non-zero value to $a_0$ and $b_0$ provide a linear EOS function of T and S.
+\end{description}
+
+\begin{table}
+  \centering
+  \begin{tabular}{|l|l|l|l|}
+    \hline
+    coeff.      & computer name                & S-EOS            & description                     \\
+    \hline
+    $a_0      $ & \np{rn_a0}{rn\_a0}           & $1.6550~10^{-1}$ & linear thermal expansion coeff. \\
+    \hline
+    $b_0      $ & \np{rn_b0}{rn\_b0}           & $7.6554~10^{-1}$ & linear haline  expansion coeff. \\
+    \hline
+    $\lambda_1$ & \np{rn_lambda1}{rn\_lambda1} & $5.9520~10^{-2}$ & cabbeling coeff. in $T^2$       \\
+    \hline
+    $\lambda_2$ & \np{rn_lambda2}{rn\_lambda2} & $5.4914~10^{-4}$ & cabbeling coeff. in $S^2$       \\
+    \hline
+    $\nu      $ & \np{rn_nu}{rn\_nu}           & $2.4341~10^{-3}$ & cabbeling coeff. in $T \, S$    \\
+    \hline
+    $\mu_1    $ & \np{rn_mu1}{rn\_mu1}         & $1.4970~10^{-4}$ & thermobaric coeff. in T         \\
+    \hline
+    $\mu_2    $ & \np{rn_mu2}{rn\_mu2}         & $1.1090~10^{-5}$ & thermobaric coeff. in S         \\
+    \hline
+  \end{tabular}
+  \caption{Standard value of S-EOS coefficients}
+  \label{tab:TRA_SEOS}
+\end{table}
+
+%% =================================================================================================
+\subsection[Brunt-V\"{a}is\"{a}l\"{a} frequency]{Brunt-V\"{a}is\"{a}l\"{a} frequency}
+\label{subsec:TRA_bn2}
+
+An accurate computation of the ocean stability (i.e. of $N$, the Brunt-V\"{a}is\"{a}l\"{a} frequency) is of paramount importance as determine the ocean stratification and
+is used in several ocean parameterisations
+(namely TKE, GLS, Richardson number dependent vertical diffusion, enhanced vertical diffusion,
+non-penetrative convection, tidal mixing  parameterisation, iso-neutral diffusion).
+In particular, $N^2$ has to be computed at the local pressure
+(pressure in decibar being approximated by the depth in meters).
+The expression for $N^2$  is given by:
+\[
+  % \label{eq:TRA_bn2}
+  N^2 = \frac{g}{e_{3w}} \lt( \beta \; \delta_{k + 1/2}[S] - \alpha \; \delta_{k + 1/2}[T] \rt)
+\]
+where $(T,S) = (\Theta,S_A)$ for TEOS10, $(\theta,S_p)$ for TEOS-80, or $(T,S)$ for S-EOS, and,
+$\alpha$ and $\beta$ are the thermal and haline expansion coefficients.
+The coefficients are a polynomial function of temperature, salinity and depth which
+expression depends on the chosen EOS.
+They are computed through \textit{eos\_rab}, a \fortran\ function that can be found in \mdl{eosbn2}.
+
+%% =================================================================================================
+\subsection{Freezing point of seawater}
+\label{subsec:TRA_fzp}
+
+The freezing point of seawater is a function of salinity and pressure \citep{fofonoff.millard_bk83}:
+\begin{equation}
+  \label{eq:TRA_eos_fzp}
+  \begin{gathered}
+    T_f (S,p) = \lt( a + b \, \sqrt{S} + c \, S \rt) \, S + d \, p \\
+    \text{where~} a = -0.0575, \, b = 1.710523~10^{-3}, \, c = -2.154996~10^{-4} \text{and~} d = -7.53~10^{-3}
+    \end{gathered}
+\end{equation}
+
+\autoref{eq:TRA_eos_fzp} is only used to compute the potential freezing point of sea water
+(\ie\ referenced to the surface $p = 0$),
+thus the pressure dependent terms in \autoref{eq:TRA_eos_fzp} (last term) have been dropped.
+The freezing point is computed through \textit{eos\_fzp},
+a \fortran\ function that can be found in \mdl{eosbn2}.
+
+%% =================================================================================================
+%\subsection{Potential Energy anomalies}
+%\label{subsec:TRA_bn2}
+
+%    =====>>>>> TO BE written
+
+%% =================================================================================================
+\section[Horizontal derivative in \textit{zps}-coordinate (\textit{zpshde.F90})]{Horizontal derivative in \textit{zps}-coordinate (\protect\mdl{zpshde})}
+\label{sec:TRA_zpshde}
+
+\cmtgm{STEVEN: to be consistent with earlier discussion of differencing and averaging operators,
+I've changed "derivative" to "difference" and "mean" to "average"}
+
+With partial cells (\np[=.true.]{ln_zps}{ln\_zps}) at bottom and top
+(\np[=.true.]{ln_isfcav}{ln\_isfcav}),
+in general, tracers in horizontally adjacent cells live at different depths.
+Horizontal gradients of tracers are needed for horizontal diffusion
+(\mdl{traldf} module) and the hydrostatic pressure gradient calculations (\mdl{dynhpg} module).
+The partial cell properties at the top (\np[=.true.]{ln_isfcav}{ln\_isfcav}) are computed in
+the same way as for the bottom.
+So, only the bottom interpolation is explained below.
+
+Before taking horizontal gradients between the tracers next to the bottom,
+a linear interpolation in the vertical is used to approximate the deeper tracer as if
+it actually lived at the depth of the shallower tracer point (\autoref{fig:TRA_Partial_step_scheme}).
+For example, for temperature in the $i$-direction the needed interpolated temperature,
+$\widetilde T$, is:
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{TRA_partial_step_scheme}
+  \caption[Discretisation of the horizontal difference and average of tracers in
+  the $z$-partial step coordinate]{
+    Discretisation of the horizontal difference and average of tracers in
+    the $z$-partial step coordinate (\protect\np[=.true.]{ln_zps}{ln\_zps}) in
+    the case $(e3w_k^{i + 1} - e3w_k^i) > 0$.
+    A linear interpolation is used to estimate $\widetilde T_k^{i + 1}$,
+    the tracer value at the depth of the shallower tracer point of the two adjacent bottom $T$-points.
+    The horizontal difference is then given by:
+    $\delta_{i + 1/2} T_k = \widetilde T_k^{\, i + 1} -T_k^{\, i}$ and the average by:
+    $\overline T_k^{\, i + 1/2} = (\widetilde T_k^{\, i + 1/2} - T_k^{\, i}) / 2$.}
+  \label{fig:TRA_Partial_step_scheme}
+\end{figure}
+
+\[
+  \widetilde T = \lt\{
+    \begin{alignedat}{2}
+      &T^{\, i + 1} &-\frac{ \lt( e_{3w}^{i + 1} -e_{3w}^i \rt) }{ e_{3w}^{i + 1} } \; \delta_k T^{i + 1}
+      & \quad \text{if $e_{3w}^{i + 1} \geq e_{3w}^i$} \\
+      &T^{\, i}     &+\frac{ \lt( e_{3w}^{i + 1} -e_{3w}^i \rt )}{e_{3w}^i       } \; \delta_k T^{i + 1}
+      & \quad \text{if $e_{3w}^{i + 1} <    e_{3w}^i$}
+    \end{alignedat}
+  \rt.
+\]
+and the resulting forms for the horizontal difference and the horizontal average value of
+$T$ at a $U$-point are:
+\begin{equation}
+  \label{eq:TRA_zps_hde}
+  \begin{split}
+    \delta_{i + 1/2} T       &=
+    \begin{cases}
+      \widetilde T - T^i          & \text{if~} e_{3w}^{i + 1} \geq e_{3w}^i \\
+      T^{\, i + 1} - \widetilde T & \text{if~} e_{3w}^{i + 1} <    e_{3w}^i
+    \end{cases} \\
+    \overline T^{\, i + 1/2} &=
+    \begin{cases}
+      (\widetilde T - T^{\, i}    ) / 2 & \text{if~} e_{3w}^{i + 1} \geq e_{3w}^i \\
+      (T^{\, i + 1} - \widetilde T) / 2 & \text{if~} e_{3w}^{i + 1} <   e_{3w}^i
+    \end{cases}
+  \end{split}
+\end{equation}
+
+The computation of horizontal derivative of tracers as well as of density is performed once for all at
+each time step in \mdl{zpshde} module and stored in shared arrays to be used when needed.
+It has to be emphasized that the procedure used to compute the interpolated density,
+$\widetilde \rho$, is not the same as that used for $T$ and $S$.
+Instead of forming a linear approximation of density,
+we compute $\widetilde \rho$ from the interpolated values of $T$ and $S$,
+and the pressure at a $u$-point
+(in the equation of state pressure is approximated by depth, see \autoref{subsec:TRA_eos}):
+\[
+  % \label{eq:TRA_zps_hde_rho}
+  \widetilde \rho = \rho (\widetilde T,\widetilde S,z_u) \quad \text{where~} z_u = \min \lt( z_T^{i + 1},z_T^i \rt)
+\]
+
+This is a much better approximation as the variation of $\rho$ with depth (and thus pressure)
+is highly non-linear with a true equation of state and thus is badly approximated with
+a linear interpolation.
+This approximation is used to compute both the horizontal pressure gradient (\autoref{sec:DYN_hpg})
+and the slopes of neutral surfaces (\autoref{sec:LDF_slp}).
+
+Note that in almost all the advection schemes presented in this chapter,
+both averaging and differencing operators appear.
+Yet \autoref{eq:TRA_zps_hde} has not been used in these schemes:
+in contrast to diffusion and pressure gradient computations,
+no correction for partial steps is applied for advection.
+The main motivation is to preserve the domain averaged mean variance of the advected field when
+using the $2^{nd}$ order centred scheme.
+Sensitivity of the advection schemes to the way horizontal averages are performed in
+the vicinity of partial cells should be further investigated in the near future.
+\cmtgm{gm :   this last remark has to be done}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ZDF.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ZDF.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_ZDF.tex	(revision 14097)
@@ -0,0 +1,1647 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+%% Custom aliases
+\newcommand{\cf}{\ensuremath{C\kern-0.14em f}}
+
+\begin{document}
+
+\chapter{Vertical Ocean Physics (ZDF)}
+\label{chap:ZDF}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+\cmtgm{ Add here a small introduction to ZDF and naming of the different physics
+(similar to what have been written for TRA and DYN).}
+
+%% =================================================================================================
+\section{Vertical mixing}
+\label{sec:ZDF}
+
+The discrete form of the ocean subgrid scale physics has been presented in
+\autoref{sec:TRA_zdf} and \autoref{sec:DYN_zdf}.
+At the surface and bottom boundaries, the turbulent fluxes of momentum, heat and salt have to be defined.
+At the surface they are prescribed from the surface forcing (see \autoref{chap:SBC}),
+while at the bottom they are set to zero for heat and salt,
+unless a geothermal flux forcing is prescribed as a bottom boundary condition (\ie\ \np{ln_trabbc}{ln\_trabbc} defined,
+see \autoref{subsec:TRA_bbc}), and specified through a bottom friction parameterisation for momentum
+(see \autoref{sec:ZDF_drg}).
+
+In this section we briefly discuss the various choices offered to compute the vertical eddy viscosity and
+diffusivity coefficients, $A_u^{vm}$ , $A_v^{vm}$ and $A^{vT}$ ($A^{vS}$), defined at $uw$-, $vw$- and $w$- points,
+respectively (see \autoref{sec:TRA_zdf} and \autoref{sec:DYN_zdf}).
+These coefficients can be assumed to be either constant, or a function of the local Richardson number,
+or computed from a turbulent closure model (either TKE or GLS or OSMOSIS formulation).
+The computation of these coefficients is initialized in the \mdl{zdfphy} module and performed in
+the \mdl{zdfric}, \mdl{zdftke} or \mdl{zdfgls} or \mdl{zdfosm} modules.
+The trends due to the vertical momentum and tracer diffusion, including the surface forcing,
+are computed and added to the general trend in the \mdl{dynzdf} and \mdl{trazdf} modules, respectively.
+%These trends can be computed using either a forward time stepping scheme
+%(namelist parameter \np[=.true.]{ln_zdfexp}{ln\_zdfexp}) or a backward time stepping scheme
+%(\np[=.false.]{ln_zdfexp}{ln\_zdfexp}) depending on the magnitude of the mixing coefficients,
+%and thus of the formulation used (see \autoref{chap:TD}).
+
+\begin{listing}
+  \nlst{namzdf}
+  \caption{\forcode{&namzdf}}
+  \label{lst:namzdf}
+\end{listing}
+
+%% =================================================================================================
+\subsection[Constant (\forcode{ln_zdfcst})]{Constant (\protect\np{ln_zdfcst}{ln\_zdfcst})}
+\label{subsec:ZDF_cst}
+
+Options are defined through the \nam{zdf}{zdf} namelist variables.
+When \np{ln_zdfcst}{ln\_zdfcst} is defined, the momentum and tracer vertical eddy coefficients are set to
+constant values over the whole ocean.
+This is the crudest way to define the vertical ocean physics.
+It is recommended to use this option only in process studies, not in basin scale simulations.
+Typical values used in this case are:
+\begin{align*}
+  A_u^{vm} = A_v^{vm} &= 1.2\ 10^{-4}~m^2.s^{-1} 	\\
+  A^{vT} = A^{vS} &= 1.2\ 10^{-5}~m^2.s^{-1}
+\end{align*}
+
+These values are set through the \np{rn_avm0}{rn\_avm0} and \np{rn_avt0}{rn\_avt0} namelist parameters.
+In all cases, do not use values smaller that those associated with the molecular viscosity and diffusivity,
+that is $\sim10^{-6}~m^2.s^{-1}$ for momentum, $\sim10^{-7}~m^2.s^{-1}$ for temperature and
+$\sim10^{-9}~m^2.s^{-1}$ for salinity.
+
+%% =================================================================================================
+\subsection[Richardson number dependent (\forcode{ln_zdfric})]{Richardson number dependent (\protect\np{ln_zdfric}{ln\_zdfric})}
+\label{subsec:ZDF_ric}
+
+\begin{listing}
+  \nlst{namzdf_ric}
+  \caption{\forcode{&namzdf_ric}}
+  \label{lst:namzdf_ric}
+\end{listing}
+
+When \np[=.true.]{ln_zdfric}{ln\_zdfric}, a local Richardson number dependent formulation for the vertical momentum and
+tracer eddy coefficients is set through the \nam{zdf_ric}{zdf\_ric} namelist variables.
+The vertical mixing coefficients are diagnosed from the large scale variables computed by the model.
+\textit{In situ} measurements have been used to link vertical turbulent activity to large scale ocean structures.
+The hypothesis of a mixing mainly maintained by the growth of Kelvin-Helmholtz like instabilities leads to
+a dependency between the vertical eddy coefficients and the local Richardson number
+(\ie\ the ratio of stratification to vertical shear).
+Following \citet{pacanowski.philander_JPO81}, the following formulation has been implemented:
+\[
+  % \label{eq:ZDF_ric}
+  \left\{
+    \begin{aligned}
+      A^{vT} &= \frac {A_{ric}^{vT}}{\left( 1+a \; Ri \right)^n} + A_b^{vT}       \\
+      A^{vm} &= \frac{A^{vT}        }{\left( 1+ a \;Ri  \right)   } + A_b^{vm}
+    \end{aligned}
+  \right.
+\]
+where $Ri = N^2 / \left(\partial_z \textbf{U}_h \right)^2$ is the local Richardson number,
+$N$ is the local Brunt-Vais\"{a}l\"{a} frequency (see \autoref{subsec:TRA_bn2}),
+$A_b^{vT} $ and $A_b^{vm}$ are the constant background values set as in the constant case
+(see \autoref{subsec:ZDF_cst}), and $A_{ric}^{vT} = 10^{-4}~m^2.s^{-1}$ is the maximum value that
+can be reached by the coefficient when $Ri\leq 0$, $a=5$ and $n=2$.
+The last three values can be modified by setting the \np{rn_avmri}{rn\_avmri}, \np{rn_alp}{rn\_alp} and
+\np{nn_ric}{nn\_ric} namelist parameters, respectively.
+
+A simple mixing-layer model to transfer and dissipate the atmospheric forcings
+(wind-stress and buoyancy fluxes) can be activated setting the \np[=.true.]{ln_mldw}{ln\_mldw} in the namelist.
+
+In this case, the local depth of turbulent wind-mixing or "Ekman depth" $h_{e}(x,y,t)$ is evaluated and
+the vertical eddy coefficients prescribed within this layer.
+
+This depth is assumed proportional to the "depth of frictional influence" that is limited by rotation:
+\[
+  h_{e} = Ek \frac {u^{*}} {f_{0}}
+\]
+where, $Ek$ is an empirical parameter, $u^{*}$ is the friction velocity and $f_{0}$ is the Coriolis parameter.
+
+In this similarity height relationship, the turbulent friction velocity:
+\[
+  u^{*} = \sqrt \frac {|\tau|} {\rho_o}
+\]
+is computed from the wind stress vector $|\tau|$ and the reference density $ \rho_o$.
+The final $h_{e}$ is further constrained by the adjustable bounds \np{rn_mldmin}{rn\_mldmin} and \np{rn_mldmax}{rn\_mldmax}.
+Once $h_{e}$ is computed, the vertical eddy coefficients within $h_{e}$ are set to
+the empirical values \np{rn_wtmix}{rn\_wtmix} and \np{rn_wvmix}{rn\_wvmix} \citep{lermusiaux_JMS01}.
+
+%% =================================================================================================
+\subsection[TKE turbulent closure scheme (\forcode{ln_zdftke})]{TKE turbulent closure scheme (\protect\np{ln_zdftke}{ln\_zdftke})}
+\label{subsec:ZDF_tke}
+
+\begin{listing}
+  \nlst{namzdf_tke}
+  \caption{\forcode{&namzdf_tke}}
+  \label{lst:namzdf_tke}
+\end{listing}
+
+The vertical eddy viscosity and diffusivity coefficients are computed from a TKE turbulent closure model based on
+a prognostic equation for $\bar{e}$, the turbulent kinetic energy,
+and a closure assumption for the turbulent length scales.
+This turbulent closure model has been developed by \citet{bougeault.lacarrere_MWR89} in the atmospheric case,
+adapted by \citet{gaspar.gregoris.ea_JGR90} for the oceanic case, and embedded in OPA, the ancestor of \NEMO,
+by \citet{blanke.delecluse_JPO93} for equatorial Atlantic simulations.
+Since then, significant modifications have been introduced by \citet{madec.delecluse.ea_NPM98} in both the implementation and
+the formulation of the mixing length scale.
+The time evolution of $\bar{e}$ is the result of the production of $\bar{e}$ through vertical shear,
+its destruction through stratification, its vertical diffusion, and its dissipation of \citet{kolmogorov_IANS42} type:
+\begin{equation}
+  \label{eq:ZDF_tke_e}
+  \frac{\partial \bar{e}}{\partial t} =
+  \frac{K_m}{{e_3}^2 }\;\left[ {\left( {\frac{\partial u}{\partial k}} \right)^2
+      +\left( {\frac{\partial v}{\partial k}} \right)^2} \right]
+  -K_\rho\,N^2
+  +\frac{1}{e_3}	\;\frac{\partial }{\partial k}\left[ {\frac{A^{vm}}{e_3 }
+      \;\frac{\partial \bar{e}}{\partial k}} \right]
+  - c_\epsilon \;\frac{\bar {e}^{3/2}}{l_\epsilon }
+\end{equation}
+\[
+  % \label{eq:ZDF_tke_kz}
+  \begin{split}
+    K_m &= C_k\  l_k\  \sqrt {\bar{e}\; }  	\\
+    K_\rho &= A^{vm} / P_{rt}
+  \end{split}
+\]
+where $N$ is the local Brunt-Vais\"{a}l\"{a} frequency (see \autoref{subsec:TRA_bn2}),
+$l_{\epsilon }$ and $l_{\kappa }$ are the dissipation and mixing length scales,
+$P_{rt}$ is the Prandtl number, $K_m$ and $K_\rho$ are the vertical eddy viscosity and diffusivity coefficients.
+The constants $C_k =  0.1$ and $C_\epsilon = \sqrt {2} /2$ $\approx 0.7$ are designed to deal with
+vertical mixing at any depth \citep{gaspar.gregoris.ea_JGR90}.
+They are set through namelist parameters \np{nn_ediff}{nn\_ediff} and \np{nn_ediss}{nn\_ediss}.
+$P_{rt}$ can be set to unity or, following \citet{blanke.delecluse_JPO93}, be a function of the local Richardson number, $R_i$:
+\begin{align*}
+  % \label{eq:ZDF_prt}
+  P_{rt} =
+  \begin{cases}
+    \ \ \ 1 &      \text{if $\ R_i \leq 0.2$} 	\\
+    5\,R_i &      \text{if $\ 0.2 \leq R_i \leq 2$} 	\\
+    \ \ 10 &      \text{if $\ 2 \leq R_i$}
+  \end{cases}
+\end{align*}
+The choice of $P_{rt}$ is controlled by the \np{nn_pdl}{nn\_pdl} namelist variable.
+
+At the sea surface, the value of $\bar{e}$ is prescribed from the wind stress field as
+$\bar{e}_o = e_{bb} |\tau| / \rho_o$, with $e_{bb}$ the \np{rn_ebb}{rn\_ebb} namelist parameter.
+The default value of $e_{bb}$ is 3.75. \citep{gaspar.gregoris.ea_JGR90}), however a much larger value can be used when
+taking into account the surface wave breaking (see below Eq. \autoref{eq:ZDF_Esbc}).
+The bottom value of TKE is assumed to be equal to the value of the level just above.
+The time integration of the $\bar{e}$ equation may formally lead to negative values because
+the numerical scheme does not ensure its positivity.
+To overcome this problem, a cut-off in the minimum value of $\bar{e}$ is used (\np{rn_emin}{rn\_emin} namelist parameter).
+Following \citet{gaspar.gregoris.ea_JGR90}, the cut-off value is set to $\sqrt{2}/2~10^{-6}~m^2.s^{-2}$.
+This allows the subsequent formulations to match that of \citet{gargett_JMR84} for the diffusion in
+the thermocline and deep ocean :  $K_\rho = 10^{-3} / N$.
+In addition, a cut-off is applied on $K_m$ and $K_\rho$ to avoid numerical instabilities associated with
+too weak vertical diffusion.
+They must be specified at least larger than the molecular values, and are set through \np{rn_avm0}{rn\_avm0} and
+\np{rn_avt0}{rn\_avt0} (\nam{zdf}{zdf} namelist, see \autoref{subsec:ZDF_cst}).
+
+%% =================================================================================================
+\subsubsection{Turbulent length scale}
+
+For computational efficiency, the original formulation of the turbulent length scales proposed by
+\citet{gaspar.gregoris.ea_JGR90} has been simplified.
+Four formulations are proposed, the choice of which is controlled by the \np{nn_mxl}{nn\_mxl} namelist parameter.
+The first two are based on the following first order approximation \citep{blanke.delecluse_JPO93}:
+\begin{equation}
+  \label{eq:ZDF_tke_mxl0_1}
+  l_k = l_\epsilon = \sqrt {2 \bar{e}\; } / N
+\end{equation}
+which is valid in a stable stratified region with constant values of the Brunt-Vais\"{a}l\"{a} frequency.
+The resulting length scale is bounded by the distance to the surface or to the bottom
+(\np[=0]{nn_mxl}{nn\_mxl}) or by the local vertical scale factor (\np[=1]{nn_mxl}{nn\_mxl}).
+\citet{blanke.delecluse_JPO93} notice that this simplification has two major drawbacks:
+it makes no sense for locally unstable stratification and the computation no longer uses all
+the information contained in the vertical density profile.
+To overcome these drawbacks, \citet{madec.delecluse.ea_NPM98} introduces the \np[=2, 3]{nn_mxl}{nn\_mxl} cases,
+which add an extra assumption concerning the vertical gradient of the computed length scale.
+So, the length scales are first evaluated as in \autoref{eq:ZDF_tke_mxl0_1} and then bounded such that:
+\begin{equation}
+  \label{eq:ZDF_tke_mxl_constraint}
+  \frac{1}{e_3 }\left| {\frac{\partial l}{\partial k}} \right| \leq 1
+  \qquad \text{with }\  l =  l_k = l_\epsilon
+\end{equation}
+\autoref{eq:ZDF_tke_mxl_constraint} means that the vertical variations of the length scale cannot be larger than
+the variations of depth.
+It provides a better approximation of the \citet{gaspar.gregoris.ea_JGR90} formulation while being much less
+time consuming.
+In particular, it allows the length scale to be limited not only by the distance to the surface or
+to the ocean bottom but also by the distance to a strongly stratified portion of the water column such as
+the thermocline (\autoref{fig:ZDF_mixing_length}).
+In order to impose the \autoref{eq:ZDF_tke_mxl_constraint} constraint, we introduce two additional length scales:
+$l_{up}$ and $l_{dwn}$, the upward and downward length scales, and
+evaluate the dissipation and mixing length scales as
+(and note that here we use numerical indexing):
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_mixing_length}
+  \caption[Mixing length computation]{Illustration of the mixing length computation}
+  \label{fig:ZDF_mixing_length}
+\end{figure}
+\[
+  % \label{eq:ZDF_tke_mxl2}
+  \begin{aligned}
+    l_{up\ \ }^{(k)} &= \min \left(  l^{(k)} \ , \ l_{up}^{(k+1)} + e_{3t}^{(k)}\ \ \ \;  \right)
+    \quad &\text{ from $k=1$ to $jpk$ }\ \\
+    l_{dwn}^{(k)} &= \min \left(  l^{(k)} \ , \ l_{dwn}^{(k-1)} + e_{3t}^{(k-1)}  \right)
+    \quad &\text{ from $k=jpk$ to $1$ }\ \\
+  \end{aligned}
+\]
+where $l^{(k)}$ is computed using \autoref{eq:ZDF_tke_mxl0_1}, \ie\ $l^{(k)} = \sqrt {2 {\bar e}^{(k)} / {N^2}^{(k)} }$.
+
+In the \np[=2]{nn_mxl}{nn\_mxl} case, the dissipation and mixing length scales take the same value:
+$ l_k=  l_\epsilon = \min \left(\ l_{up} \;,\;  l_{dwn}\ \right)$, while in the \np[=3]{nn_mxl}{nn\_mxl} case,
+the dissipation and mixing turbulent length scales are give as in \citet{gaspar.gregoris.ea_JGR90}:
+\[
+  % \label{eq:ZDF_tke_mxl_gaspar}
+  \begin{aligned}
+    & l_k          = \sqrt{\  l_{up} \ \ l_{dwn}\ }  	\\
+    & l_\epsilon = \min \left(\ l_{up} \;,\;  l_{dwn}\ \right)
+  \end{aligned}
+\]
+
+At the ocean surface, a non zero length scale is set through the  \np{rn_mxl0}{rn\_mxl0} namelist parameter.
+Usually the surface scale is given by $l_o = \kappa \,z_o$ where $\kappa = 0.4$ is von Karman's constant and
+$z_o$ the roughness parameter of the surface.
+Assuming $z_o=0.1$~m \citep{craig.banner_JPO94} leads to a 0.04~m, the default value of \np{rn_mxl0}{rn\_mxl0}.
+In the ocean interior a minimum length scale is set to recover the molecular viscosity when
+$\bar{e}$ reach its minimum value ($1.10^{-6}= C_k\, l_{min} \,\sqrt{\bar{e}_{min}}$ ).
+
+%% =================================================================================================
+\subsubsection{Surface wave breaking parameterization}
+
+Following \citet{mellor.blumberg_JPO04}, the TKE turbulence closure model has been modified to
+include the effect of surface wave breaking energetics.
+This results in a reduction of summertime surface temperature when the mixed layer is relatively shallow.
+The \citet{mellor.blumberg_JPO04} modifications acts on surface length scale and TKE values and
+air-sea drag coefficient.
+The latter concerns the bulk formulae and is not discussed here.
+
+Following \citet{craig.banner_JPO94}, the boundary condition on surface TKE value is :
+\begin{equation}
+  \label{eq:ZDF_Esbc}
+  \bar{e}_o = \frac{1}{2}\,\left(  15.8\,\alpha_{CB} \right)^{2/3} \,\frac{|\tau|}{\rho_o}
+\end{equation}
+where $\alpha_{CB}$ is the \citet{craig.banner_JPO94} constant of proportionality which depends on the ''wave age'',
+ranging from 57 for mature waves to 146 for younger waves \citep{mellor.blumberg_JPO04}.
+The boundary condition on the turbulent length scale follows the Charnock's relation:
+\begin{equation}
+  \label{eq:ZDF_Lsbc}
+  l_o = \kappa \beta \,\frac{|\tau|}{g\,\rho_o}
+\end{equation}
+where $\kappa=0.40$ is the von Karman constant, and $\beta$ is the Charnock's constant.
+\citet{mellor.blumberg_JPO04} suggest $\beta = 2.10^{5}$ the value chosen by
+\citet{stacey_JPO99} citing observation evidence, and
+$\alpha_{CB} = 100$ the Craig and Banner's value.
+As the surface boundary condition on TKE is prescribed through $\bar{e}_o = e_{bb} |\tau| / \rho_o$,
+with $e_{bb}$ the \np{rn_ebb}{rn\_ebb} namelist parameter, setting \np[=67.83]{rn_ebb}{rn\_ebb} corresponds
+to $\alpha_{CB} = 100$.
+Further setting  \np[=.true.]{ln_mxl0}{ln\_mxl0},  applies \autoref{eq:ZDF_Lsbc} as the surface boundary condition on the length scale,
+with $\beta$ hard coded to the Stacey's value.
+Note that a minimal threshold of \np{rn_emin0}{rn\_emin0}$=10^{-4}~m^2.s^{-2}$ (namelist parameters) is applied on the
+surface $\bar{e}$ value.
+
+%% =================================================================================================
+\subsubsection{Langmuir cells}
+
+Langmuir circulations (LC) can be described as ordered large-scale vertical motions in
+the surface layer of the oceans.
+Although LC have nothing to do with convection, the circulation pattern is rather similar to
+so-called convective rolls in the atmospheric boundary layer.
+The detailed physics behind LC is described in, for example, \citet{craik.leibovich_JFM76}.
+The prevailing explanation is that LC arise from a nonlinear interaction between the Stokes drift and
+wind drift currents.
+
+Here we introduced in the TKE turbulent closure the simple parameterization of Langmuir circulations proposed by
+\citep{axell_JGR02} for a $k-\epsilon$ turbulent closure.
+The parameterization, tuned against large-eddy simulation, includes the whole effect of LC in
+an extra source term of TKE, $P_{LC}$.
+The presence of $P_{LC}$ in \autoref{eq:ZDF_tke_e}, the TKE equation, is controlled by setting \np{ln_lc}{ln\_lc} to
+\forcode{.true.} in the \nam{zdf_tke}{zdf\_tke} namelist.
+
+By making an analogy with the characteristic convective velocity scale (\eg, \citet{dalessio.abdella.ea_JPO98}),
+$P_{LC}$ is assumed to be :
+\[
+P_{LC}(z) = \frac{w_{LC}^3(z)}{H_{LC}}
+\]
+where $w_{LC}(z)$ is the vertical velocity profile of LC, and $H_{LC}$ is the LC depth.
+With no information about the wave field, $w_{LC}$ is assumed to be proportional to
+the Stokes drift $u_s = 0.377\,\,|\tau|^{1/2}$, where $|\tau|$ is the surface wind stress module
+\footnote{Following \citet{li.garrett_JMR93}, the surface Stoke drift velocity may be expressed as
+  $u_s =  0.016 \,|U_{10m}|$.
+  Assuming an air density of $\rho_a=1.22 \,Kg/m^3$ and a drag coefficient of
+  $1.5~10^{-3}$ give the expression used of $u_s$ as a function of the module of surface stress
+}.
+For the vertical variation, $w_{LC}$ is assumed to be zero at the surface as well as at
+a finite depth $H_{LC}$ (which is often close to the mixed layer depth),
+and simply varies as a sine function in between (a first-order profile for the Langmuir cell structures).
+The resulting expression for $w_{LC}$ is :
+\[
+  w_{LC}  =
+  \begin{cases}
+    c_{LC} \,u_s \,\sin(- \pi\,z / H_{LC} )    &      \text{if $-z \leq H_{LC}$} 	\\
+    0                 				 &      \text{otherwise}
+  \end{cases}
+\]
+where $c_{LC} = 0.15$ has been chosen by \citep{axell_JGR02} as a good compromise to fit LES data.
+The chosen value yields maximum vertical velocities $w_{LC}$ of the order of a few centimeters per second.
+The value of $c_{LC}$ is set through the \np{rn_lc}{rn\_lc} namelist parameter,
+having in mind that it should stay between 0.15 and 0.54 \citep{axell_JGR02}.
+
+The $H_{LC}$ is estimated in a similar way as the turbulent length scale of TKE equations:
+$H_{LC}$ is the depth to which a water parcel with kinetic energy due to Stoke drift can reach on its own by
+converting its kinetic energy to potential energy, according to
+\[
+- \int_{-H_{LC}}^0 { N^2\;z  \;dz} = \frac{1}{2} u_s^2
+\]
+
+%% =================================================================================================
+\subsubsection{Mixing just below the mixed layer}
+
+Vertical mixing parameterizations commonly used in ocean general circulation models tend to
+produce mixed-layer depths that are too shallow during summer months and windy conditions.
+This bias is particularly acute over the Southern Ocean.
+To overcome this systematic bias, an ad hoc parameterization is introduced into the TKE scheme \cite{rodgers.aumont.ea_B14}.
+The parameterization is an empirical one, \ie\ not derived from theoretical considerations,
+but rather is meant to account for observed processes that affect the density structure of
+the ocean’s planetary boundary layer that are not explicitly captured by default in the TKE scheme
+(\ie\ near-inertial oscillations and ocean swells and waves).
+
+When using this parameterization (\ie\ when \np[=1]{nn_etau}{nn\_etau}),
+the TKE input to the ocean ($S$) imposed by the winds in the form of near-inertial oscillations,
+swell and waves is parameterized by \autoref{eq:ZDF_Esbc} the standard TKE surface boundary condition,
+plus a depth depend one given by:
+\begin{equation}
+  \label{eq:ZDF_Ehtau}
+  S = (1-f_i) \; f_r \; e_s \; e^{-z / h_\tau}
+\end{equation}
+where $z$ is the depth, $e_s$ is TKE surface boundary condition, $f_r$ is the fraction of the surface TKE that
+penetrates in the ocean, $h_\tau$ is a vertical mixing length scale that controls exponential shape of
+the penetration, and $f_i$ is the ice concentration
+(no penetration if $f_i=1$, \ie\ if the ocean is entirely covered by sea-ice).
+The value of $f_r$, usually a few percents, is specified through \np{rn_efr}{rn\_efr} namelist parameter.
+The vertical mixing length scale, $h_\tau$, can be set as a 10~m uniform value (\np[=0]{nn_etau}{nn\_etau}) or
+a latitude dependent value (varying from 0.5~m at the Equator to a maximum value of 30~m at high latitudes
+(\np[=1]{nn_etau}{nn\_etau}).
+
+Note that two other option exist, \np[=2, 3]{nn_etau}{nn\_etau}.
+They correspond to applying \autoref{eq:ZDF_Ehtau} only at the base of the mixed layer,
+or to using the high frequency part of the stress to evaluate the fraction of TKE that penetrates the ocean.
+Those two options are obsolescent features introduced for test purposes.
+They will be removed in the next release.
+
+% This should be explain better below what this rn_eice parameter is meant for:
+In presence of Sea Ice, the value of this mixing can be modulated by the \np{rn_eice}{rn\_eice} namelist parameter.
+This parameter varies from \forcode{0} for no effect to \forcode{4} to suppress the TKE input into the ocean when Sea Ice concentration
+is greater than 25\%.
+
+% from Burchard et al OM 2008 :
+% the most critical process not reproduced by statistical turbulence models is the activity of
+% internal waves and their interaction with turbulence. After the Reynolds decomposition,
+% internal waves are in principle included in the RANS equations, but later partially
+% excluded by the hydrostatic assumption and the model resolution.
+% Thus far, the representation of internal wave mixing in ocean models has been relatively crude
+% (\eg\ Mellor, 1989; Large et al., 1994; Meier, 2001; Axell, 2002; St. Laurent and Garrett, 2002).
+
+%% =================================================================================================
+\subsection[GLS: Generic Length Scale (\forcode{ln_zdfgls})]{GLS: Generic Length Scale (\protect\np{ln_zdfgls}{ln\_zdfgls})}
+\label{subsec:ZDF_gls}
+
+\begin{listing}
+  \nlst{namzdf_gls}
+  \caption{\forcode{&namzdf_gls}}
+  \label{lst:namzdf_gls}
+\end{listing}
+
+The Generic Length Scale (GLS) scheme is a turbulent closure scheme based on two prognostic equations:
+one for the turbulent kinetic energy $\bar {e}$, and another for the generic length scale,
+$\psi$ \citep{umlauf.burchard_JMR03, umlauf.burchard_CSR05}.
+This later variable is defined as: $\psi = {C_{0\mu}}^{p} \ {\bar{e}}^{m} \ l^{n}$,
+where the triplet $(p, m, n)$ value given in Tab.\autoref{tab:ZDF_GLS} allows to recover a number of
+well-known turbulent closures ($k$-$kl$ \citep{mellor.yamada_RG82}, $k$-$\epsilon$ \citep{rodi_JGR87},
+$k$-$\omega$ \citep{wilcox_AJ88} among others \citep{umlauf.burchard_JMR03,kantha.carniel_JMR03}).
+The GLS scheme is given by the following set of equations:
+\begin{equation}
+  \label{eq:ZDF_gls_e}
+  \frac{\partial \bar{e}}{\partial t} =
+  \frac{K_m}{\sigma_e e_3 }\;\left[ {\left( \frac{\partial u}{\partial k} \right)^2
+      +\left( \frac{\partial v}{\partial k} \right)^2} \right]
+  -K_\rho \,N^2
+  +\frac{1}{e_3}\,\frac{\partial}{\partial k} \left[ \frac{K_m}{e_3}\,\frac{\partial \bar{e}}{\partial k} \right]
+  - \epsilon
+\end{equation}
+
+\[
+  % \label{eq:ZDF_gls_psi}
+  \begin{split}
+    \frac{\partial \psi}{\partial t} =& \frac{\psi}{\bar{e}} \left\{
+      \frac{C_1\,K_m}{\sigma_{\psi} {e_3}}\;\left[ {\left( \frac{\partial u}{\partial k} \right)^2
+          +\left( \frac{\partial v}{\partial k} \right)^2} \right]
+      - C_3 \,K_\rho\,N^2   - C_2 \,\epsilon \,Fw   \right\}             \\
+    &+\frac{1}{e_3}  \;\frac{\partial }{\partial k}\left[ {\frac{K_m}{e_3 }
+        \;\frac{\partial \psi}{\partial k}} \right]\;
+  \end{split}
+\]
+
+\[
+  % \label{eq:ZDF_gls_kz}
+  \begin{split}
+    K_m    &= C_{\mu} \ \sqrt {\bar{e}} \ l         \\
+    K_\rho &= C_{\mu'}\ \sqrt {\bar{e}} \ l
+  \end{split}
+\]
+
+\[
+  % \label{eq:ZDF_gls_eps}
+  {\epsilon} = C_{0\mu} \,\frac{\bar {e}^{3/2}}{l} \;
+\]
+where $N$ is the local Brunt-Vais\"{a}l\"{a} frequency (see \autoref{subsec:TRA_bn2}) and
+$\epsilon$ the dissipation rate.
+The constants $C_1$, $C_2$, $C_3$, ${\sigma_e}$, ${\sigma_{\psi}}$ and the wall function ($Fw$) depends of
+the choice of the turbulence model.
+Four different turbulent models are pre-defined (\autoref{tab:ZDF_GLS}).
+They are made available through the \np{nn_clo}{nn\_clo} namelist parameter.
+
+\begin{table}[htbp]
+  \centering
+  % \begin{tabular}{cp{70pt}cp{70pt}cp{70pt}cp{70pt}cp{70pt}cp{70pt}c}
+  \begin{tabular}{ccccc}
+    &   $k-kl$   & $k-\epsilon$ & $k-\omega$ &   generic   \\
+    % & \citep{mellor.yamada_RG82} &  \citep{rodi_JGR87}       & \citep{wilcox_AJ88} &                 \\
+    \hline
+    \hline
+    \np{nn_clo}{nn\_clo}     & \textbf{0} &   \textbf{1}  &   \textbf{2}   &    \textbf{3}   \\
+    \hline
+    $( p , n , m )$	       &   ( 0 , 1 , 1 )   & ( 3 , 1.5 , -1 )   & ( -1 , 0.5 , -1 )    &  ( 2 , 1 , -0.67 )  \\
+    $\sigma_k$      &    2.44         &     1.              &      2.                &      0.8          \\
+    $\sigma_\psi$  &    2.44         &     1.3            &      2.                 &       1.07       \\
+    $C_1$              &      0.9         &     1.44          &      0.555          &       1.           \\
+    $C_2$              &      0.5         &     1.92          &      0.833          &       1.22       \\
+    $C_3$              &      1.           &     1.              &      1.                &       1.           \\
+    $F_{wall}$        &      Yes        &       --             &     --                  &      --          \\
+    \hline
+    \hline
+  \end{tabular}
+  \caption[Set of predefined GLS parameters or equivalently predefined turbulence models available]{
+    Set of predefined GLS parameters, or equivalently predefined turbulence models available with
+    \protect\np[=.true.]{ln_zdfgls}{ln\_zdfgls} and controlled by
+    the \protect\np{nn_clos}{nn\_clos} namelist variable in \protect\nam{zdf_gls}{zdf\_gls}.}
+  \label{tab:ZDF_GLS}
+\end{table}
+
+In the Mellor-Yamada model, the negativity of $n$ allows to use a wall function to force the convergence of
+the mixing length towards $\kappa z_b$ ($\kappa$ is the Von Karman constant and $z_b$ the rugosity length scale) value near physical boundaries
+(logarithmic boundary layer law).
+$C_{\mu}$ and $C_{\mu'}$ are calculated from stability function proposed by \citet{galperin.kantha.ea_JAS88},
+or by \citet{kantha.clayson_JGR94} or one of the two functions suggested by \citet{canuto.howard.ea_JPO01}
+(\np[=0, 3]{nn_stab_func}{nn\_stab\_func}, resp.).
+The value of $C_{0\mu}$ depends on the choice of the stability function.
+
+The surface and bottom boundary condition on both $\bar{e}$ and $\psi$ can be calculated thanks to Dirichlet or
+Neumann condition through \np{nn_bc_surf}{nn\_bc\_surf} and \np{nn_bc_bot}{nn\_bc\_bot}, resp.
+As for TKE closure, the wave effect on the mixing is considered when
+\np[ > 0.]{rn_crban}{rn\_crban} \citep{craig.banner_JPO94, mellor.blumberg_JPO04}.
+The \np{rn_crban}{rn\_crban} namelist parameter is $\alpha_{CB}$ in \autoref{eq:ZDF_Esbc} and
+\np{rn_charn}{rn\_charn} provides the value of $\beta$ in \autoref{eq:ZDF_Lsbc}.
+
+The $\psi$ equation is known to fail in stably stratified flows, and for this reason
+almost all authors apply a clipping of the length scale as an \textit{ad hoc} remedy.
+With this clipping, the maximum permissible length scale is determined by $l_{max} = c_{lim} \sqrt{2\bar{e}}/ N$.
+A value of $c_{lim} = 0.53$ is often used \citep{galperin.kantha.ea_JAS88}.
+\cite{umlauf.burchard_CSR05} show that the value of the clipping factor is of crucial importance for
+the entrainment depth predicted in stably stratified situations,
+and that its value has to be chosen in accordance with the algebraic model for the turbulent fluxes.
+The clipping is only activated if \np[=.true.]{ln_length_lim}{ln\_length\_lim},
+and the $c_{lim}$ is set to the \np{rn_clim_galp}{rn\_clim\_galp} value.
+
+The time and space discretization of the GLS equations follows the same energetic consideration as for
+the TKE case described in \autoref{subsec:ZDF_tke_ene} \citep{burchard_OM02}.
+Evaluation of the 4 GLS turbulent closure schemes can be found in \citet{warner.sherwood.ea_OM05} in ROMS model and
+ in \citet{reffray.guillaume.ea_GMD15} for the \NEMO\ model.
+
+% -------------------------------------------------------------------------------------------------------------
+%        OSM OSMOSIS BL Scheme
+% -------------------------------------------------------------------------------------------------------------
+\subsection[OSM: OSMOSIS boundary layer scheme (\forcode{ln_zdfosm = .true.})]
+{OSM: OSMOSIS boundary layer scheme (\protect\np{ln_zdfosm}{ln\_zdfosm})}
+\label{subsec:ZDF_osm}
+
+\begin{listing}
+  \nlst{namzdf_osm}
+  \caption{\forcode{&namzdf_osm}}
+  \label{lst:namzdf_osm}
+\end{listing}
+
+%--------------------------------------------------------------------------------------------------------------
+\paragraph{Namelist choices}
+Most of the namelist options refer to how to specify the Stokes
+surface drift and penetration depth. There are three options:
+\begin{description}
+  \item \protect\np[=0]{nn_osm_wave}{nn\_osm\_wave} Default value in \texttt{namelist\_ref}. In this case the Stokes drift is
+      assumed to be parallel to the surface wind stress, with
+      magnitude consistent with a constant turbulent Langmuir number
+    $\mathrm{La}_t=$ \protect\np{rn_m_la} {rn\_m\_la} i.e.\
+    $u_{s0}=\tau/(\mathrm{La}_t^2\rho_0)$.  Default value of
+    \protect\np{rn_m_la}{rn\_m\_la} is 0.3. The Stokes penetration
+      depth $\delta = $ \protect\np{rn_osm_dstokes}{rn\_osm\_dstokes}; this has default value
+      of 5~m.
+
+  \item \protect\np[=1]{nn_osm_wave}{nn\_osm\_wave} In this case the Stokes drift is
+      assumed to be parallel to the surface wind stress, with
+      magnitude as in the classical Pierson-Moskowitz wind-sea
+      spectrum.  Significant wave height and
+      wave-mean period taken from this spectrum are used to calculate the Stokes penetration
+      depth, following the approach set out in  \citet{breivik.janssen.ea_JPO14}.
+
+    \item \protect\np[=2]{nn_osm_wave}{nn\_osm\_wave} In this case the Stokes drift is
+      taken from  ECMWF wave model output, though only the component parallel
+      to the wind stress is retained. Significant wave height and
+      wave-mean period from ECMWF wave model output are used to calculate the Stokes penetration
+      depth, again following \citet{breivik.janssen.ea_JPO14}.
+
+    \end{description}
+
+    Others refer to the treatment of diffusion and viscosity beneath
+    the surface boundary layer:
+\begin{description}
+   \item \protect\np{ln_kpprimix} {ln\_kpprimix}  Default is \np{.true.}. Switches on KPP-style Ri \#-dependent
+     mixing below the surface boundary layer. If this is set
+     \texttt{.true.}  the following variable settings are honoured:
+    \item \protect\np{rn_riinfty}{rn\_riinfty} Critical value of local Ri \# below which
+      shear instability increases vertical mixing from background value.
+    \item \protect\np{rn_difri} {rn\_difri} Maximum value of Ri \#-dependent mixing at $\mathrm{Ri}=0$.
+    \item \protect\np{ln_convmix}{ln\_convmix} If \texttt{.true.} then, where water column is unstable, specify
+       diffusivity equal to \protect\np{rn_dif_conv}{rn\_dif\_conv} (default value is 1 m~s$^{-2}$).
+ \end{description}
+ Diagnostic output is controlled by:
+  \begin{description}
+    \item \protect\np{ln_dia_osm}{ln\_dia\_osm} Default is \np{.false.}; allows XIOS output of OSMOSIS internal fields.
+  \end{description}
+Obsolete namelist parameters include:
+\begin{description}
+   \item \protect\np{ln_use_osm_la}\np{ln\_use\_osm\_la} With \protect\np[=0]{nn_osm_wave}{nn\_osm\_wave},
+      \protect\np{rn_osm_dstokes} {rn\_osm\_dstokes} is always used to specify the Stokes
+      penetration depth.
+   \item \protect\np{nn_ave} {nn\_ave} Choice of averaging method for KPP-style Ri \#
+      mixing. Not taken account of.
+   \item \protect\np{rn_osm_hbl0} {rn\_osm\_hbl0} Depth of initial boundary layer is now set
+     by a density criterion similar to that used in calculating \emph{hmlp} (output as \texttt{mldr10\_1}) in \mdl{zdfmxl}.
+\end{description}
+
+\subsubsection{Summary}
+Much of the time the turbulent motions in the ocean surface boundary
+layer (OSBL) are not given by
+classical shear turbulence. Instead they are in a regime known as
+`Langmuir turbulence',  dominated by an
+interaction between the currents and the Stokes drift of the surface waves \citep[e.g.][]{mcwilliams.ea_JFM97}.
+This regime is characterised by strong vertical turbulent motion, and appears when the surface Stokes drift $u_{s0}$ is much greater than the friction velocity $u_{\ast}$. More specifically Langmuir turbulence is thought to be crucial where the turbulent Langmuir number $\mathrm{La}_{t}=(u_{\ast}/u_{s0}) > 0.4$.
+
+The OSMOSIS model is fundamentally based on results of Large Eddy
+Simulations (LES) of Langmuir turbulence and aims to fully describe
+this Langmuir regime. The description in this section is of necessity incomplete and further details are available in Grant. A (2019); in prep.
+
+The OSMOSIS turbulent closure scheme is a similarity-scale scheme in
+the same spirit as the K-profile
+parameterization (KPP) scheme of \citet{large.ea_RG97}.
+A specified shape of diffusivity, scaled by the (OSBL) depth
+$h_{\mathrm{BL}}$ and a turbulent velocity scale, is imposed throughout the
+boundary layer
+$-h_{\mathrm{BL}}<z<\eta$. The turbulent closure model
+also includes fluxes of tracers and momentum that are``non-local'' (independent of the local property gradient).
+
+Rather than the OSBL
+depth being diagnosed in terms of a bulk Richardson number criterion,
+as in KPP, it is set by a prognostic equation that is informed by
+energy budget considerations reminiscent of the classical mixed layer
+models of \citet{kraus.turner_tellus67}.
+The model also includes an explicit parametrization of the structure
+of the pycnocline (the stratified region at the bottom of the OSBL).
+
+Presently, mixing below the OSBL is handled by the Richardson
+number-dependent mixing scheme used in \citet{large.ea_RG97}.
+
+Convective parameterizations such as described in \ref{sec:ZDF_conv}
+below should not be used with the OSMOSIS-OBL model: instabilities
+within the OSBL are part of the model, while instabilities below the
+ML are handled by the Ri \# dependent scheme.
+
+\subsubsection{Depth and velocity scales}
+The model supposes a boundary layer of thickness $h_{\mathrm{bl}}$ enclosing a well-mixed layer of thickness $h_{\mathrm{ml}}$ and a relatively thin pycnocline at the base of thickness $\Delta h$; Fig.~\ref{fig: OSBL_structure} shows typical (a) buoyancy structure and (b) turbulent buoyancy flux profile for the unstable boundary layer (losing buoyancy at the surface; e.g.\ cooling).
+\begin{figure}[!t]
+  \begin{center}
+    %\includegraphics[width=0.7\textwidth]{ZDF_OSM_structure_of_OSBL}
+    \caption{
+      \protect\label{fig: OSBL_structure}
+     The structure of the entraining  boundary layer. (a) Mean buoyancy profile. (b) Profile of the buoyancy flux.
+    }
+  \end{center}
+\end{figure}
+The pycnocline in the OSMOSIS scheme is assumed to have a finite thickness, and may include a number of model levels. This means that the OSMOSIS scheme must parametrize both the thickness of the pycnocline, and the turbulent fluxes within the pycnocline.
+
+Consideration of the power input by wind acting on the Stokes drift suggests that the Langmuir turbulence has velocity scale:
+\begin{equation}\label{eq:w_La}
+w_{*L}= \left(u_*^2 u_{s\,0}\right)^{1/3};
+\end{equation}
+but at times the Stokes drift may be weak due to e.g.\ ice cover, short fetch, misalignment with the surface stress, etc.\ so  a composite velocity scale is assumed for the stable (warming) boundary layer:
+\begin{equation}\label{eq:composite-nu}
+  \nu_{\ast}= \left\{ u_*^3 \left[1-\exp(-.5 \mathrm{La}_t^2)\right]+w_{*L}^3\right\}^{1/3}.
+\end{equation}
+For the unstable boundary layer this is merged with the standard convective velocity scale $w_{*C}=\left(\overline{w^\prime b^\prime}_0 \,h_\mathrm{ml}\right)^{1/3}$, where $\overline{w^\prime b^\prime}_0$ is the upwards surface buoyancy flux, to give:
+\begin{equation}\label{eq:vel-scale-unstable}
+\omega_* = \left(\nu_*^3 + 0.5 w_{*C}^3\right)^{1/3}.
+\end{equation}
+
+\subsubsection{The flux gradient model}
+The flux-gradient relationships used in the OSMOSIS scheme take the form:
+%
+\begin{equation}\label{eq:flux-grad-gen}
+\overline{w^\prime\chi^\prime}=-K\frac{\partial\overline{\chi}}{\partial z} + N_{\chi,s} +N_{\chi,b} +N_{\chi,t},
+\end{equation}
+%
+where $\chi$ is a general variable and $N_{\chi,s}, N_{\chi,b} \mathrm{and} N_{\chi,t}$  are the non-gradient terms, and represent the effects of the different terms in the turbulent flux-budget on the transport of $\chi$. $N_{\chi,s}$ represents the effects that the Stokes shear has on the transport of $\chi$, $N_{\chi,b}$  the effect of buoyancy, and $N_{\chi,t}$ the effect of the turbulent transport.  The same general form for the flux-gradient relationship is used to parametrize the transports of momentum, heat and salinity.
+
+In terms of the non-dimensionalized depth variables
+%
+\begin{equation}\label{eq:sigma}
+\sigma_{\mathrm{ml}}= -z/h_{\mathrm{ml}}; \;\sigma_{\mathrm{bl}}= -z/h_{\mathrm{bl}},
+\end{equation}
+%
+in unstable conditions the eddy diffusivity ($K_d$) and eddy viscosity ($K_\nu$) profiles are parametrized as:
+%
+\begin{align}\label{eq:diff-unstable}
+K_d=&0.8\, \omega_*\, h_{\mathrm{ml}} \, \sigma_{\mathrm{ml}} \left(1-\beta_d \sigma_{\mathrm{ml}}\right)^{3/2}
+\\\label{eq:visc-unstable}
+K_\nu =& 0.3\, \omega_* \,h_{\mathrm{ml}}\, \sigma_{\mathrm{ml}} \left(1-\beta_\nu \sigma_{\mathrm{ml}}\right)\left(1-\tfrac{1}{2}\sigma_{\mathrm{ml}}^2\right)
+\end{align}
+%
+where $\beta_d$ and $\beta_\nu$ are parameters that are determined by matching Eqs \ref{eq:diff-unstable} and \ref{eq:visc-unstable} to the eddy diffusivity and viscosity at the base of the well-mixed layer, given by
+%
+\begin{equation}\label{eq:diff-wml-base}
+K_{d,\mathrm{ml}}=K_{\nu,\mathrm{ml}}=\,0.16\,\omega_* \Delta h.
+\end{equation}
+%
+For stable conditions the eddy diffusivity/viscosity profiles are given by:
+%
+\begin{align}\label{diff-stable}
+K_d= & 0.75\,\, \nu_*\, h_{\mathrm{ml}}\,\,  \exp\left[-2.8 \left(h_{\mathrm{bl}}/L_L\right)^2\right]\sigma_{\mathrm{ml}} \left(1-\sigma_{\mathrm{ml}}\right)^{3/2} \\\label{eq:visc-stable}
+K_\nu = & 0.375\,\,  \nu_*\, h_{\mathrm{ml}} \,\, \exp\left[-2.8 \left(h_{\mathrm{bl}}/L_L\right)^2\right] \sigma_{\mathrm{ml}} \left(1-\sigma_{\mathrm{ml}}\right)\left(1-\tfrac{1}{2}\sigma_{\mathrm{ml}}^2\right).
+\end{align}
+%
+The shape of the eddy viscosity and diffusivity profiles is the same as the shape in the unstable OSBL. The eddy diffusivity/viscosity depends on the stability parameter $h_{\mathrm{bl}}/{L_L}$ where $ L_L$ is analogous to the Obukhov length, but for Langmuir turbulence:
+\begin{equation}\label{eq:L_L}
+  L_L=-w_{*L}^3/\left<\overline{w^\prime b^\prime}\right>_L,
+\end{equation}
+with the mean turbulent buoyancy flux averaged over the boundary layer given in terms of its surface value $\overline{w^\prime b^\prime}_0$ and (downwards) )solar irradiance $I(z)$ by
+\begin{equation} \label{eq:stable-av-buoy-flux}
+\left<\overline{w^\prime b^\prime}\right>_L = \tfrac{1}{2} {\overline{w^\prime b^\prime}}_0-g\alpha_E\left[\tfrac{1}{2}(I(0)+I(-h))-\left<I\right>\right].
+\end{equation}
+%
+In unstable conditions the eddy diffusivity and viscosity depend on stability through the velocity scale $\omega_*$, which depends on the two velocity scales $\nu_*$ and $w_{*C}$.
+
+Details of the non-gradient terms in \eqref{eq:flux-grad-gen} and of the fluxes within the pycnocline $-h_{\mathrm{bl}}<z<h_{\mathrm{ml}}$ can be found in Grant (2019).
+
+\subsubsection{Evolution of the boundary layer depth}
+
+The prognostic equation for the depth of the neutral/unstable boundary layer is given by \citep{grant+etal18},
+
+\begin{equation} \label{eq:dhdt-unstable}
+%\frac{\partial h_\mathrm{bl}}{\partial t} + \mathbf{U}_b\cdot\nabla h_\mathrm{bl}= W_b - \frac{{\overline{w^\prime b^\prime}}_\mathrm{ent}}{\Delta B_\mathrm{bl}}
+\frac{\partial h_\mathrm{bl}}{\partial t} = W_b - \frac{{\overline{w^\prime b^\prime}}_\mathrm{ent}}{\Delta B_\mathrm{bl}}
+\end{equation}
+where $h_\mathrm{bl}$ is the horizontally-varying depth of the OSBL,
+$\mathbf{U}_b$ and $W_b$ are the mean horizontal and vertical
+velocities at the base of the OSBL, ${\overline{w^\prime
+    b^\prime}}_\mathrm{ent}$ is the buoyancy flux due to entrainment
+and $\Delta B_\mathrm{bl}$ is the difference between the buoyancy
+averaged over the depth of the OSBL (i.e.\ including the ML and
+pycnocline) and the buoyancy just below the base of the OSBL. This
+equation for the case when the pycnocline has a finite thickness,
+based on the potential energy budget of the OSBL, is the leading term
+\citep{grant+etal18} of a generalization of that used in mixed-layer
+models e.g.\ \citet{kraus.turner_tellus67}, in which the thickness of the pycnocline is taken to be zero.
+
+The entrainment flux for the combination of convective and Langmuir turbulence is given by
+\begin{equation} \label{eq:entrain-flux}
+  {\overline{w^\prime b^\prime}}_\mathrm{ent} = -\alpha_{\mathrm{B}} {\overline{w^\prime b^\prime}}_0 - \alpha_{\mathrm{S}} \frac{u_*^3}{h_{\mathrm{ml}}}
+  + G\left(\delta/h_{\mathrm{ml}} \right)\left[\alpha_{\mathrm{S}}e^{-1.5\, \mathrm{La}_t}-\alpha_{\mathrm{L}} \frac{w_{\mathrm{*L}}^3}{h_{\mathrm{ml}}}\right]
+\end{equation}
+where the factor $G\equiv 1 - \mathrm{e}^ {-25\delta/h_{\mathrm{bl}}}(1-4\delta/h_{\mathrm{bl}})$ models the lesser efficiency of Langmuir mixing when the boundary-layer depth is much greater than the Stokes depth, and $\alpha_{\mathrm{B}}$, $\alpha_{S}$  and $\alpha_{\mathrm{L}}$ depend on the ratio of the appropriate eddy turnover time to the inertial timescale $f^{-1}$. Results from the LES suggest $\alpha_{\mathrm{B}}=0.18 F(fh_{\mathrm{bl}}/w_{*C})$, $\alpha_{S}=0.15 F(fh_{\mathrm{bl}}/u_*$  and $\alpha_{\mathrm{L}}=0.035 F(fh_{\mathrm{bl}}/u_{*L})$, where $F(x)\equiv\tanh(x^{-1})^{0.69}$.
+
+For the stable boundary layer, the equation for the depth of the OSBL is:
+
+\begin{equation}\label{eq:dhdt-stable}
+\max\left(\Delta B_{bl},\frac{w_{*L}^2}{h_\mathrm{bl}}\right)\frac{\partial h_\mathrm{bl}}{\partial t} = \left(0.06 + 0.52\,\frac{ h_\mathrm{bl}}{L_L}\right) \frac{w_{*L}^3}{h_\mathrm{bl}} +\left<\overline{w^\prime b^\prime}\right>_L.
+\end{equation}
+
+Equation. \ref{eq:dhdt-unstable} always leads to the depth of the entraining OSBL increasing (ignoring the effect of the mean vertical motion), but the change in the thickness of the stable OSBL given by Eq. \ref{eq:dhdt-stable} can be positive or negative, depending on the magnitudes of $\left<\overline{w^\prime b^\prime}\right>_L$ and $h_\mathrm{bl}/L_L$. The rate at which the depth of the OSBL can decrease is limited by choosing an effective buoyancy $w_{*L}^2/h_\mathrm{bl}$, in place of $\Delta B_{bl}$ which will be $\approx 0$ for the collapsing OSBL.
+
+
+%% =================================================================================================
+\subsection[ Discrete energy conservation for TKE and GLS schemes]{Discrete energy conservation for TKE and GLS schemes}
+\label{subsec:ZDF_tke_ene}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_TKE_time_scheme}
+  \caption[Subgrid kinetic energy integration in GLS and TKE schemes]{
+    Illustration of the subgrid kinetic energy integration in GLS and TKE schemes and
+    its links to the momentum and tracer time integration.}
+  \label{fig:ZDF_TKE_time_scheme}
+\end{figure}
+
+The production of turbulence by vertical shear (the first term of the right hand side of
+\autoref{eq:ZDF_tke_e}) and  \autoref{eq:ZDF_gls_e}) should balance the loss of kinetic energy associated with the vertical momentum diffusion
+(first line in \autoref{eq:MB_zdf}).
+To do so a special care has to be taken for both the time and space discretization of
+the kinetic energy equation \citep{burchard_OM02,marsaleix.auclair.ea_OM08}.
+
+Let us first address the time stepping issue. \autoref{fig:ZDF_TKE_time_scheme} shows how
+the two-level Leap-Frog time stepping of the momentum and tracer equations interplays with
+the one-level forward time stepping of the equation for $\bar{e}$.
+With this framework, the total loss of kinetic energy (in 1D for the demonstration) due to
+the vertical momentum diffusion is obtained by multiplying this quantity by $u^t$ and
+summing the result vertically:
+\begin{equation}
+  \label{eq:ZDF_energ1}
+  \begin{split}
+    \int_{-H}^{\eta}  u^t \,\partial_z &\left( {K_m}^t \,(\partial_z u)^{t+\rdt}  \right) \,dz   \\
+    &= \Bigl[  u^t \,{K_m}^t \,(\partial_z u)^{t+\rdt} \Bigr]_{-H}^{\eta}
+    - \int_{-H}^{\eta}{ {K_m}^t \,\partial_z{u^t} \,\partial_z u^{t+\rdt} \,dz }
+  \end{split}
+\end{equation}
+Here, the vertical diffusion of momentum is discretized backward in time with a coefficient, $K_m$,
+known at time $t$ (\autoref{fig:ZDF_TKE_time_scheme}), as it is required when using the TKE scheme
+(see \autoref{sec:TD_forward_imp}).
+The first term of the right hand side of \autoref{eq:ZDF_energ1} represents the kinetic energy transfer at
+the surface (atmospheric forcing) and at the bottom (friction effect).
+The second term is always negative.
+It is the dissipation rate of kinetic energy, and thus minus the shear production rate of $\bar{e}$.
+\autoref{eq:ZDF_energ1} implies that, to be energetically consistent,
+the production rate of $\bar{e}$ used to compute $(\bar{e})^t$ (and thus ${K_m}^t$) should be expressed as
+${K_m}^{t-\rdt}\,(\partial_z u)^{t-\rdt} \,(\partial_z u)^t$
+(and not by the more straightforward $K_m \left( \partial_z u \right)^2$ expression taken at time $t$ or $t-\rdt$).
+
+A similar consideration applies on the destruction rate of $\bar{e}$ due to stratification
+(second term of the right hand side of \autoref{eq:ZDF_tke_e} and \autoref{eq:ZDF_gls_e}).
+This term must balance the input of potential energy resulting from vertical mixing.
+The rate of change of potential energy (in 1D for the demonstration) due to vertical mixing is obtained by
+multiplying the vertical density diffusion tendency by $g\,z$ and and summing the result vertically:
+\begin{equation}
+  \label{eq:ZDF_energ2}
+  \begin{split}
+    \int_{-H}^{\eta} g\,z\,\partial_z &\left( {K_\rho}^t \,(\partial_k \rho)^{t+\rdt}   \right) \,dz    \\
+    &= \Bigl[  g\,z \,{K_\rho}^t \,(\partial_z \rho)^{t+\rdt} \Bigr]_{-H}^{\eta}
+    - \int_{-H}^{\eta}{ g \,{K_\rho}^t \,(\partial_k \rho)^{t+\rdt} } \,dz   \\
+    &= - \Bigl[  z\,{K_\rho}^t \,(N^2)^{t+\rdt} \Bigr]_{-H}^{\eta}
+    + \int_{-H}^{\eta}{  \rho^{t+\rdt} \, {K_\rho}^t \,(N^2)^{t+\rdt} \,dz  }
+  \end{split}
+\end{equation}
+where we use $N^2 = -g \,\partial_k \rho / (e_3 \rho)$.
+The first term of the right hand side of \autoref{eq:ZDF_energ2} is always zero because
+there is no diffusive flux through the ocean surface and bottom).
+The second term is minus the destruction rate of  $\bar{e}$ due to stratification.
+Therefore \autoref{eq:ZDF_energ1} implies that, to be energetically consistent,
+the product ${K_\rho}^{t-\rdt}\,(N^2)^t$ should be used in \autoref{eq:ZDF_tke_e} and  \autoref{eq:ZDF_gls_e}.
+
+Let us now address the space discretization issue.
+The vertical eddy coefficients are defined at $w$-point whereas the horizontal velocity components are in
+the centre of the side faces of a $t$-box in staggered C-grid (\autoref{fig:DOM_cell}).
+A space averaging is thus required to obtain the shear TKE production term.
+By redoing the \autoref{eq:ZDF_energ1} in the 3D case, it can be shown that the product of eddy coefficient by
+the shear at $t$ and $t-\rdt$ must be performed prior to the averaging.
+Furthermore, the time variation of $e_3$ has be taken into account.
+
+The above energetic considerations leads to the following final discrete form for the TKE equation:
+\begin{equation}
+  \label{eq:ZDF_tke_ene}
+  \begin{split}
+    \frac { (\bar{e})^t - (\bar{e})^{t-\rdt} } {\rdt}  \equiv
+    \Biggl\{ \Biggr.
+    &\overline{ \left( \left(\overline{K_m}^{\,i+1/2}\right)^{t-\rdt} \,\frac{\delta_{k+1/2}[u^{t+\rdt}]}{{e_3u}^{t+\rdt} }
+        \ \frac{\delta_{k+1/2}[u^ t         ]}{{e_3u}^ t          }  \right) }^{\,i} \\
+    +&\overline{  \left( \left(\overline{K_m}^{\,j+1/2}\right)^{t-\rdt} \,\frac{\delta_{k+1/2}[v^{t+\rdt}]}{{e_3v}^{t+\rdt} }
+        \ \frac{\delta_{k+1/2}[v^ t         ]}{{e_3v}^ t          }  \right) }^{\,j}
+    \Biggr. \Biggr\}   \\
+    %
+    - &{K_\rho}^{t-\rdt}\,{(N^2)^t}    \\
+    %
+    +&\frac{1}{{e_3w}^{t+\rdt}}  \;\delta_{k+1/2} \left[   {K_m}^{t-\rdt} \,\frac{\delta_{k}[(\bar{e})^{t+\rdt}]} {{e_3w}^{t+\rdt}}   \right]   \\
+    %
+    - &c_\epsilon \; \left( \frac{\sqrt{\bar {e}}}{l_\epsilon}\right)^{t-\rdt}\,(\bar {e})^{t+\rdt}
+  \end{split}
+\end{equation}
+where the last two terms in \autoref{eq:ZDF_tke_ene} (vertical diffusion and Kolmogorov dissipation)
+are time stepped using a backward scheme (see\autoref{sec:TD_forward_imp}).
+Note that the Kolmogorov term has been linearized in time in order to render the implicit computation possible.
+%The restart of the TKE scheme requires the storage of $\bar {e}$, $K_m$, $K_\rho$ and $l_\epsilon$ as
+%they all appear in the right hand side of \autoref{eq:ZDF_tke_ene}.
+%For the latter, it is in fact the ratio $\sqrt{\bar{e}}/l_\epsilon$ which is stored.
+
+%% =================================================================================================
+\section{Convection}
+\label{sec:ZDF_conv}
+
+Static instabilities (\ie\ light potential densities under heavy ones) may occur at particular ocean grid points.
+In nature, convective processes quickly re-establish the static stability of the water column.
+These processes have been removed from the model via the hydrostatic assumption so they must be parameterized.
+Three parameterisations are available to deal with convective processes:
+a non-penetrative convective adjustment or an enhanced vertical diffusion,
+or/and the use of a turbulent closure scheme.
+
+%% =================================================================================================
+\subsection[Non-penetrative convective adjustment (\forcode{ln_tranpc})]{Non-penetrative convective adjustment (\protect\np{ln_tranpc}{ln\_tranpc})}
+\label{subsec:ZDF_npc}
+
+\begin{figure}[!htb]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_npc}
+  \caption[Unstable density profile treated by the non penetrative convective adjustment algorithm]{
+    Example of an unstable density profile treated by
+    the non penetrative convective adjustment algorithm.
+    $1^{st}$ step: the initial profile is checked from the surface to the bottom.
+    It is found to be unstable between levels 3 and 4.
+    They are mixed.
+    The resulting $\rho$ is still larger than $\rho$(5): levels 3 to 5 are mixed.
+    The resulting $\rho$ is still larger than $\rho$(6): levels 3 to 6 are mixed.
+    The $1^{st}$ step ends since the density profile is then stable below the level 3.
+    $2^{nd}$ step: the new $\rho$ profile is checked following the same procedure as in $1^{st}$ step:
+    levels 2 to 5 are mixed.
+    The new density profile is checked.
+    It is found stable: end of algorithm.}
+  \label{fig:ZDF_npc}
+\end{figure}
+
+Options are defined through the \nam{zdf}{zdf} namelist variables.
+The non-penetrative convective adjustment is used when \np[=.true.]{ln_zdfnpc}{ln\_zdfnpc}.
+It is applied at each \np{nn_npc}{nn\_npc} time step and mixes downwards instantaneously the statically unstable portion of
+the water column, but only until the density structure becomes neutrally stable
+(\ie\ until the mixed portion of the water column has \textit{exactly} the density of the water just below)
+\citep{madec.delecluse.ea_JPO91}.
+The associated algorithm is an iterative process used in the following way (\autoref{fig:ZDF_npc}):
+starting from the top of the ocean, the first instability is found.
+Assume in the following that the instability is located between levels $k$ and $k+1$.
+The temperature and salinity in the two levels are vertically mixed, conserving the heat and salt contents of
+the water column.
+The new density is then computed by a linear approximation.
+If the new density profile is still unstable between levels $k+1$ and $k+2$,
+levels $k$, $k+1$ and $k+2$ are then mixed.
+This process is repeated until stability is established below the level $k$
+(the mixing process can go down to the ocean bottom).
+The algorithm is repeated to check if the density profile between level $k-1$ and $k$ is unstable and/or
+if there is no deeper instability.
+
+This algorithm is significantly different from mixing statically unstable levels two by two.
+The latter procedure cannot converge with a finite number of iterations for some vertical profiles while
+the algorithm used in \NEMO\ converges for any profile in a number of iterations which is less than
+the number of vertical levels.
+This property is of paramount importance as pointed out by \citet{killworth_iprc89}:
+it avoids the existence of permanent and unrealistic static instabilities at the sea surface.
+This non-penetrative convective algorithm has been proved successful in studies of the deep water formation in
+the north-western Mediterranean Sea \citep{madec.delecluse.ea_JPO91, madec.chartier.ea_DAO91, madec.crepon_iprc91}.
+
+The current implementation has been modified in order to deal with any non linear equation of seawater
+(L. Brodeau, personnal communication).
+Two main differences have been introduced compared to the original algorithm:
+$(i)$ the stability is now checked using the Brunt-V\"{a}is\"{a}l\"{a} frequency
+(not the difference in potential density);
+$(ii)$ when two levels are found unstable, their thermal and haline expansion coefficients are vertically mixed in
+the same way their temperature and salinity has been mixed.
+These two modifications allow the algorithm to perform properly and accurately with TEOS10 or EOS-80 without
+having to recompute the expansion coefficients at each mixing iteration.
+
+%% =================================================================================================
+\subsection[Enhanced vertical diffusion (\forcode{ln_zdfevd})]{Enhanced vertical diffusion (\protect\np{ln_zdfevd}{ln\_zdfevd})}
+\label{subsec:ZDF_evd}
+
+Options are defined through the  \nam{zdf}{zdf} namelist variables.
+The enhanced vertical diffusion parameterisation is used when \np[=.true.]{ln_zdfevd}{ln\_zdfevd}.
+In this case, the vertical eddy mixing coefficients are assigned very large values
+in regions where the stratification is unstable
+(\ie\ when $N^2$ the Brunt-Vais\"{a}l\"{a} frequency is negative) \citep{lazar_phd97, lazar.madec.ea_JPO99}.
+This is done either on tracers only (\np[=0]{nn_evdm}{nn\_evdm}) or
+on both momentum and tracers (\np[=1]{nn_evdm}{nn\_evdm}).
+
+In practice, where $N^2\leq 10^{-12}$, $A_T^{vT}$ and $A_T^{vS}$, and if \np[=1]{nn_evdm}{nn\_evdm},
+the four neighbouring $A_u^{vm} \;\mbox{and}\;A_v^{vm}$ values also, are set equal to
+the namelist parameter \np{rn_avevd}{rn\_avevd}.
+A typical value for $rn\_avevd$ is between 1 and $100~m^2.s^{-1}$.
+This parameterisation of convective processes is less time consuming than
+the convective adjustment algorithm presented above when mixing both tracers and
+momentum in the case of static instabilities.
+
+Note that the stability test is performed on both \textit{before} and \textit{now} values of $N^2$.
+This removes a potential source of divergence of odd and even time step in
+a leapfrog environment \citep{leclair_phd10} (see \autoref{sec:TD_mLF}).
+
+%% =================================================================================================
+\subsection[Handling convection with turbulent closure schemes (\forcode{ln_zdf_}\{\forcode{tke,gls,osm}\})]{Handling convection with turbulent closure schemes (\forcode{ln_zdf{tke,gls,osm}})}
+\label{subsec:ZDF_tcs}
+
+The turbulent closure schemes presented in \autoref{subsec:ZDF_tke}, \autoref{subsec:ZDF_gls} and
+\autoref{subsec:ZDF_osm} (\ie\ \np{ln_zdftke}{ln\_zdftke} or \np{ln_zdfgls}{ln\_zdfgls} or \np{ln_zdfosm}{ln\_zdfosm} defined) deal, in theory,
+with statically unstable density profiles.
+In such a case, the term corresponding to the destruction of turbulent kinetic energy through stratification in
+\autoref{eq:ZDF_tke_e} or \autoref{eq:ZDF_gls_e} becomes a source term, since $N^2$ is negative.
+It results in large values of $A_T^{vT}$ and  $A_T^{vT}$, and also of the four neighboring values at
+velocity points $A_u^{vm} {and}\;A_v^{vm}$ (up to $1\;m^2s^{-1}$).
+These large values restore the static stability of the water column in a way similar to that of
+the enhanced vertical diffusion parameterisation (\autoref{subsec:ZDF_evd}).
+However, in the vicinity of the sea surface (first ocean layer), the eddy coefficients computed by
+the turbulent closure scheme do not usually exceed $10^{-2}m.s^{-1}$,
+because the mixing length scale is bounded by the distance to the sea surface.
+It can thus be useful to combine the enhanced vertical diffusion with the turbulent closure scheme,
+\ie\ setting the \np{ln_zdfnpc}{ln\_zdfnpc} namelist parameter to true and
+defining the turbulent closure (\np{ln_zdftke}{ln\_zdftke} or \np{ln_zdfgls}{ln\_zdfgls} = \forcode{.true.}) all together.
+
+The OSMOSIS turbulent closure scheme already includes enhanced vertical diffusion in the case of convection,
+%as governed by the variables $bvsqcon$ and $difcon$ found in \mdl{zdfkpp},
+therefore \np[=.false.]{ln_zdfevd}{ln\_zdfevd} should be used with the OSMOSIS scheme.
+% gm%  + one word on non local flux with KPP scheme trakpp.F90 module...
+
+%% =================================================================================================
+\section[Double diffusion mixing (\forcode{ln_zdfddm})]{Double diffusion mixing (\protect\np{ln_zdfddm}{ln\_zdfddm})}
+\label{subsec:ZDF_ddm}
+
+%\nlst{namzdf_ddm}
+
+This parameterisation has been introduced in \mdl{zdfddm} module and is controlled by the namelist parameter
+\np{ln_zdfddm}{ln\_zdfddm} in \nam{zdf}{zdf}.
+Double diffusion occurs when relatively warm, salty water overlies cooler, fresher water, or vice versa.
+The former condition leads to salt fingering and the latter to diffusive convection.
+Double-diffusive phenomena contribute to diapycnal mixing in extensive regions of the ocean.
+\citet{merryfield.holloway.ea_JPO99} include a parameterisation of such phenomena in a global ocean model and show that
+it leads to relatively minor changes in circulation but exerts significant regional influences on
+temperature and salinity.
+
+Diapycnal mixing of S and T are described by diapycnal diffusion coefficients
+\begin{align*}
+  % \label{eq:ZDF_ddm_Kz}
+  &A^{vT} = A_o^{vT}+A_f^{vT}+A_d^{vT}	\\
+  &A^{vS} = A_o^{vS}+A_f^{vS}+A_d^{vS}
+\end{align*}
+where subscript $f$ represents mixing by salt fingering, $d$ by diffusive convection,
+and $o$ by processes other than double diffusion.
+The rates of double-diffusive mixing depend on the buoyancy ratio
+$R_\rho = \alpha \partial_z T / \beta \partial_z S$, where $\alpha$ and $\beta$ are coefficients of
+thermal expansion and saline contraction (see \autoref{subsec:TRA_eos}).
+To represent mixing of $S$ and $T$ by salt fingering, we adopt the diapycnal diffusivities suggested by Schmitt
+(1981):
+\begin{align}
+  \label{eq:ZDF_ddm_f}
+  A_f^{vS} &=
+             \begin{cases}
+               \frac{A^{\ast v}}{1+(R_\rho / R_c)^n   } &\text{if  $R_\rho > 1$ and $N^2>0$ } \\
+               0 				  					    &\text{otherwise}
+             \end{cases}
+  \\ 		    \label{eq:ZDF_ddm_f_T}
+  A_f^{vT} &= 0.7 \ A_f^{vS} / R_\rho
+\end{align}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_ddm}
+  \caption[Diapycnal diffusivities for temperature and salt in regions of salt fingering and
+  diffusive convection]{
+    From \citet{merryfield.holloway.ea_JPO99}:
+    (a) Diapycnal diffusivities $A_f^{vT}$ and $A_f^{vS}$ for temperature and salt in
+    regions of salt fingering.
+    Heavy curves denote $A^{\ast v} = 10^{-3}~m^2.s^{-1}$ and
+    thin curves $A^{\ast v} = 10^{-4}~m^2.s^{-1}$;
+    (b) diapycnal diffusivities $A_d^{vT}$ and $A_d^{vS}$ for temperature and salt in
+    regions of diffusive convection.
+    Heavy curves denote the Federov parameterisation and thin curves the Kelley parameterisation.
+    The latter is not implemented in \NEMO.}
+  \label{fig:ZDF_ddm}
+\end{figure}
+
+The factor 0.7 in \autoref{eq:ZDF_ddm_f_T} reflects the measured ratio $\alpha F_T /\beta F_S \approx  0.7$ of
+buoyancy flux of heat to buoyancy flux of salt (\eg, \citet{mcdougall.taylor_JMR84}).
+Following  \citet{merryfield.holloway.ea_JPO99}, we adopt $R_c = 1.6$, $n = 6$, and $A^{\ast v} = 10^{-4}~m^2.s^{-1}$.
+
+To represent mixing of S and T by diffusive layering,  the diapycnal diffusivities suggested by
+Federov (1988) is used:
+\begin{align}
+  % \label{eq:ZDF_ddm_d}
+  A_d^{vT} &=
+             \begin{cases}
+               1.3635 \, \exp{\left( 4.6\, \exp{ \left[  -0.54\,( R_{\rho}^{-1} - 1 )  \right] }    \right)}
+               &\text{if  $0<R_\rho < 1$ and $N^2>0$ } \\
+               0 								&\text{otherwise}
+             \end{cases}
+                                       \nonumber \\
+  \label{eq:ZDF_ddm_d_S}
+  A_d^{vS} &=
+             \begin{cases}
+               A_d^{vT}\ \left( 1.85\,R_{\rho} - 0.85 \right) &\text{if  $0.5 \leq R_\rho<1$ and $N^2>0$ } \\
+               A_d^{vT} \ 0.15 \ R_\rho               &\text{if  $\ \ 0 < R_\rho<0.5$ and $N^2>0$ } \\
+               0 								&\text{otherwise}
+             \end{cases}
+\end{align}
+
+The dependencies of \autoref{eq:ZDF_ddm_f} to \autoref{eq:ZDF_ddm_d_S} on $R_\rho$ are illustrated in
+\autoref{fig:ZDF_ddm}.
+Implementing this requires computing $R_\rho$ at each grid point on every time step.
+This is done in \mdl{eosbn2} at the same time as $N^2$ is computed.
+This avoids duplication in the computation of $\alpha$ and $\beta$ (which is usually quite expensive).
+
+%% =================================================================================================
+\section[Bottom and top friction (\textit{zdfdrg.F90})]{Bottom and top friction (\protect\mdl{zdfdrg})}
+\label{sec:ZDF_drg}
+
+\begin{listing}
+  \nlst{namdrg}
+  \caption{\forcode{&namdrg}}
+  \label{lst:namdrg}
+\end{listing}
+\begin{listing}
+  \nlst{namdrg_top}
+  \caption{\forcode{&namdrg_top}}
+  \label{lst:namdrg_top}
+\end{listing}
+\begin{listing}
+  \nlst{namdrg_bot}
+  \caption{\forcode{&namdrg_bot}}
+  \label{lst:namdrg_bot}
+\end{listing}
+
+Options to define the top and bottom friction are defined through the \nam{drg}{drg} namelist variables.
+The bottom friction represents the friction generated by the bathymetry.
+The top friction represents the friction generated by the ice shelf/ocean interface.
+As the friction processes at the top and the bottom are treated in and identical way,
+the description below considers mostly the bottom friction case, if not stated otherwise.
+
+Both the surface momentum flux (wind stress) and the bottom momentum flux (bottom friction) enter the equations as
+a condition on the vertical diffusive flux.
+For the bottom boundary layer, one has:
+ \[
+   % \label{eq:ZDF_bfr_flux}
+   A^{vm} \left( \partial {\textbf U}_h / \partial z \right) = {{\cal F}}_h^{\textbf U}
+ \]
+where ${\cal F}_h^{\textbf U}$ is represents the downward flux of horizontal momentum outside
+the logarithmic turbulent boundary layer (thickness of the order of 1~m in the ocean).
+How ${\cal F}_h^{\textbf U}$ influences the interior depends on the vertical resolution of the model near
+the bottom relative to the Ekman layer depth.
+For example, in order to obtain an Ekman layer depth $d = \sqrt{2\;A^{vm}} / f = 50$~m,
+one needs a vertical diffusion coefficient $A^{vm} = 0.125$~m$^2$s$^{-1}$
+(for a Coriolis frequency $f = 10^{-4}$~m$^2$s$^{-1}$).
+With a background diffusion coefficient $A^{vm} = 10^{-4}$~m$^2$s$^{-1}$, the Ekman layer depth is only 1.4~m.
+When the vertical mixing coefficient is this small, using a flux condition is equivalent to
+entering the viscous forces (either wind stress or bottom friction) as a body force over the depth of the top or
+bottom model layer.
+To illustrate this, consider the equation for $u$ at $k$, the last ocean level:
+\begin{equation}
+  \label{eq:ZDF_drg_flux2}
+  \frac{\partial u_k}{\partial t} = \frac{1}{e_{3u}} \left[ \frac{A_{uw}^{vm}}{e_{3uw}} \delta_{k+1/2}\;[u] - {\cal F}^u_h \right] \approx - \frac{{\cal F}^u_{h}}{e_{3u}}
+\end{equation}
+If the bottom layer thickness is 200~m, the Ekman transport will be distributed over that depth.
+On the other hand, if the vertical resolution is high (1~m or less) and a turbulent closure model is used,
+the turbulent Ekman layer will be represented explicitly by the model.
+However, the logarithmic layer is never represented in current primitive equation model applications:
+it is \emph{necessary} to parameterize the flux ${\cal F}^u_h $.
+Two choices are available in \NEMO: a linear and a quadratic bottom friction.
+Note that in both cases, the rotation between the interior velocity and the bottom friction is neglected in
+the present release of \NEMO.
+
+In the code, the bottom friction is imposed by adding the trend due to the bottom friction to
+ the general momentum trend in \mdl{dynzdf}.
+For the time-split surface pressure gradient algorithm, the momentum trend due to
+the barotropic component needs to be handled separately.
+For this purpose it is convenient to compute and store coefficients which can be simply combined with
+bottom velocities and geometric values to provide the momentum trend due to bottom friction.
+ These coefficients are computed in \mdl{zdfdrg} and generally take the form $c_b^{\textbf U}$ where:
+\begin{equation}
+  \label{eq:ZDF_bfr_bdef}
+  \frac{\partial {\textbf U_h}}{\partial t} =
+  - \frac{{\cal F}^{\textbf U}_{h}}{e_{3u}} = \frac{c_b^{\textbf U}}{e_{3u}} \;{\textbf U}_h^b
+\end{equation}
+where $\textbf{U}_h^b = (u_b\;,\;v_b)$ is the near-bottom, horizontal, ocean velocity.
+Note than from \NEMO\ 4.0, drag coefficients are only computed at cell centers (\ie\ at T-points) and refer to as $c_b^T$ in the following. These are then linearly interpolated in space to get $c_b^\textbf{U}$ at velocity points.
+
+%% =================================================================================================
+\subsection[Linear top/bottom friction (\forcode{ln_lin})]{Linear top/bottom friction (\protect\np{ln_lin}{ln\_lin})}
+\label{subsec:ZDF_drg_linear}
+
+The linear friction parameterisation (including the special case of a free-slip condition) assumes that
+the friction is proportional to the interior velocity (\ie\ the velocity of the first/last model level):
+\[
+  % \label{eq:ZDF_bfr_linear}
+  {\cal F}_h^\textbf{U} = \frac{A^{vm}}{e_3} \; \frac{\partial \textbf{U}_h}{\partial k} = r \; \textbf{U}_h^b
+\]
+where $r$ is a friction coefficient expressed in $m s^{-1}$.
+This coefficient is generally estimated by setting a typical decay time $\tau$ in the deep ocean,
+and setting $r = H / \tau$, where $H$ is the ocean depth.
+Commonly accepted values of $\tau$ are of the order of 100 to 200 days \citep{weatherly_JMR84}.
+A value $\tau^{-1} = 10^{-7}$~s$^{-1}$ equivalent to 115 days, is usually used in quasi-geostrophic models.
+One may consider the linear friction as an approximation of quadratic friction, $r \approx 2\;C_D\;U_{av}$
+(\citet{gill_bk82}, Eq. 9.6.6).
+For example, with a drag coefficient $C_D = 0.002$, a typical speed of tidal currents of $U_{av} =0.1$~m\;s$^{-1}$,
+and assuming an ocean depth $H = 4000$~m, the resulting friction coefficient is $r = 4\;10^{-4}$~m\;s$^{-1}$.
+This is the default value used in \NEMO. It corresponds to a decay time scale of 115~days.
+It can be changed by specifying \np{rn_Uc0}{rn\_Uc0} (namelist parameter).
+
+ For the linear friction case the drag coefficient used in the general expression \autoref{eq:ZDF_bfr_bdef} is:
+\[
+  % \label{eq:ZDF_bfr_linbfr_b}
+    c_b^T = - r
+\]
+When \np[=.true.]{ln_lin}{ln\_lin}, the value of $r$ used is \np{rn_Uc0}{rn\_Uc0}*\np{rn_Cd0}{rn\_Cd0}.
+Setting \np[=.true.]{ln_OFF}{ln\_OFF} (and \forcode{ln_lin=.true.}) is equivalent to setting $r=0$ and leads to a free-slip boundary condition.
+
+These values are assigned in \mdl{zdfdrg}.
+Note that there is support for local enhancement of these values via an externally defined 2D mask array
+(\np[=.true.]{ln_boost}{ln\_boost}) given in the \ifile{bfr\_coef} input NetCDF file.
+The mask values should vary from 0 to 1.
+Locations with a non-zero mask value will have the friction coefficient increased by
+$mask\_value$ * \np{rn_boost}{rn\_boost} * \np{rn_Cd0}{rn\_Cd0}.
+
+%% =================================================================================================
+\subsection[Non-linear top/bottom friction (\forcode{ln_non_lin})]{Non-linear top/bottom friction (\protect\np{ln_non_lin}{ln\_non\_lin})}
+\label{subsec:ZDF_drg_nonlinear}
+
+The non-linear bottom friction parameterisation assumes that the top/bottom friction is quadratic:
+\[
+  % \label{eq:ZDF_drg_nonlinear}
+  {\cal F}_h^\textbf{U} = \frac{A^{vm}}{e_3 }\frac{\partial \textbf {U}_h
+  }{\partial k}=C_D \;\sqrt {u_b ^2+v_b ^2+e_b } \;\; \textbf {U}_h^b
+\]
+where $C_D$ is a drag coefficient, and $e_b $ a top/bottom turbulent kinetic energy due to tides,
+internal waves breaking and other short time scale currents.
+A typical value of the drag coefficient is $C_D = 10^{-3} $.
+As an example, the CME experiment \citep{treguier_JGR92} uses $C_D = 10^{-3}$ and
+$e_b = 2.5\;10^{-3}$m$^2$\;s$^{-2}$, while the FRAM experiment \citep{killworth_JPO92} uses $C_D = 1.4\;10^{-3}$ and
+$e_b =2.5\;\;10^{-3}$m$^2$\;s$^{-2}$.
+The CME choices have been set as default values (\np{rn_Cd0}{rn\_Cd0} and \np{rn_ke0}{rn\_ke0} namelist parameters).
+
+As for the linear case, the friction is imposed in the code by adding the trend due to
+the friction to the general momentum trend in \mdl{dynzdf}.
+For the non-linear friction case the term computed in \mdl{zdfdrg} is:
+\[
+  % \label{eq:ZDF_drg_nonlinbfr}
+    c_b^T = - \; C_D\;\left[ \left(\bar{u_b}^{i}\right)^2 + \left(\bar{v_b}^{j}\right)^2 + e_b \right]^{1/2}
+\]
+
+The coefficients that control the strength of the non-linear friction are initialised as namelist parameters:
+$C_D$= \np{rn_Cd0}{rn\_Cd0}, and $e_b$ =\np{rn_bfeb2}{rn\_bfeb2}.
+Note that for applications which consider tides explicitly, a low or even zero value of \np{rn_bfeb2}{rn\_bfeb2} is recommended. A local enhancement of $C_D$ is again possible via an externally defined 2D mask array
+(\np[=.true.]{ln_boost}{ln\_boost}).
+This works in the same way as for the linear friction case with non-zero masked locations increased by
+$mask\_value$ * \np{rn_boost}{rn\_boost} * \np{rn_Cd0}{rn\_Cd0}.
+
+%% =================================================================================================
+\subsection[Log-layer top/bottom friction (\forcode{ln_loglayer})]{Log-layer top/bottom friction (\protect\np{ln_loglayer}{ln\_loglayer})}
+\label{subsec:ZDF_drg_loglayer}
+
+In the non-linear friction case, the drag coefficient, $C_D$, can be optionally enhanced using
+a "law of the wall" scaling. This assumes that the model vertical resolution can capture the logarithmic layer which typically occur for layers thinner than 1 m or so.
+If  \np[=.true.]{ln_loglayer}{ln\_loglayer}, $C_D$ is no longer constant but is related to the distance to the wall (or equivalently to the half of the top/bottom layer thickness):
+\[
+  C_D = \left ( {\kappa \over {\mathrm log}\left ( 0.5 \; e_{3b} / rn\_{z0} \right ) } \right )^2
+\]
+
+\noindent where $\kappa$ is the von-Karman constant and \np{rn_z0}{rn\_z0} is a roughness length provided via the namelist.
+
+The drag coefficient is bounded such that it is kept greater or equal to
+the base \np{rn_Cd0}{rn\_Cd0} value which occurs where layer thicknesses become large and presumably logarithmic layers are not resolved at all. For stability reason, it is also not allowed to exceed the value of an additional namelist parameter:
+\np{rn_Cdmax}{rn\_Cdmax}, \ie
+\[
+  rn\_Cd0 \leq C_D \leq rn\_Cdmax
+\]
+
+\noindent The log-layer enhancement can also be applied to the top boundary friction if
+under ice-shelf cavities are activated (\np[=.true.]{ln_isfcav}{ln\_isfcav}).
+%In this case, the relevant namelist parameters are \np{rn_tfrz0}{rn\_tfrz0}, \np{rn_tfri2}{rn\_tfri2} and \np{rn_tfri2_max}{rn\_tfri2\_max}.
+
+%% =================================================================================================
+\subsection[Explicit top/bottom friction (\forcode{ln_drgimp=.false.})]{Explicit top/bottom friction (\protect\np[=.false.]{ln_drgimp}{ln\_drgimp})}
+\label{subsec:ZDF_drg_stability}
+
+Setting \np[=.false.]{ln_drgimp}{ln\_drgimp} means that bottom friction is treated explicitly in time, which has the advantage of simplifying the interaction with the split-explicit free surface (see \autoref{subsec:ZDF_drg_ts}). The latter does indeed require the knowledge of bottom stresses in the course of the barotropic sub-iteration, which becomes less straightforward in the implicit case. In the explicit case, top/bottom stresses can be computed using \textit{before} velocities and inserted in the overall momentum tendency budget. This reads:
+
+At the top (below an ice shelf cavity):
+\[
+  \left.{\left( {\frac{A^{vm} }{e_3 }\ \frac{\partial \textbf{U}_h}{\partial k}} \right)} \right|_{t}
+  = c_{t}^{\textbf{U}}\textbf{u}^{n-1}_{t}
+\]
+
+At the bottom (above the sea floor):
+\[
+  \left.{\left( {\frac{A^{vm} }{e_3 }\ \frac{\partial \textbf{U}_h}{\partial k}} \right)} \right|_{b}
+  = c_{b}^{\textbf{U}}\textbf{u}^{n-1}_{b}
+\]
+
+Since this is conditionally stable, some care needs to exercised over the choice of parameters to ensure that the implementation of explicit top/bottom friction does not induce numerical instability.
+For the purposes of stability analysis, an approximation to \autoref{eq:ZDF_drg_flux2} is:
+\begin{equation}
+  \label{eq:ZDF_Eqn_drgstab}
+  \begin{split}
+    \Delta u &= -\frac{{{\cal F}_h}^u}{e_{3u}}\;2 \rdt    \\
+    &= -\frac{ru}{e_{3u}}\;2\rdt\\
+  \end{split}
+\end{equation}
+\noindent where linear friction and a leapfrog timestep have been assumed.
+To ensure that the friction cannot reverse the direction of flow it is necessary to have:
+\[
+  |\Delta u| < \;|u|
+\]
+\noindent which, using \autoref{eq:ZDF_Eqn_drgstab}, gives:
+\[
+  r\frac{2\rdt}{e_{3u}} < 1 \qquad  \Rightarrow \qquad r < \frac{e_{3u}}{2\rdt}\\
+\]
+This same inequality can also be derived in the non-linear bottom friction case if
+a velocity of 1 m.s$^{-1}$ is assumed.
+Alternatively, this criterion can be rearranged to suggest a minimum bottom box thickness to ensure stability:
+\[
+  e_{3u} > 2\;r\;\rdt
+\]
+\noindent which it may be necessary to impose if partial steps are being used.
+For example, if $|u| = 1$ m.s$^{-1}$, $rdt = 1800$ s, $r = 10^{-3}$ then $e_{3u}$ should be greater than 3.6 m.
+For most applications, with physically sensible parameters these restrictions should not be of concern.
+But caution may be necessary if attempts are made to locally enhance the bottom friction parameters.
+To ensure stability limits are imposed on the top/bottom friction coefficients both
+during initialisation and at each time step.
+Checks at initialisation are made in \mdl{zdfdrg} (assuming a 1 m.s$^{-1}$ velocity in the non-linear case).
+The number of breaches of the stability criterion are reported as well as
+the minimum and maximum values that have been set.
+The criterion is also checked at each time step, using the actual velocity, in \mdl{dynzdf}.
+Values of the friction coefficient are reduced as necessary to ensure stability;
+these changes are not reported.
+
+Limits on the top/bottom friction coefficient are not imposed if the user has elected to
+handle the friction implicitly (see \autoref{subsec:ZDF_drg_imp}).
+The number of potential breaches of the explicit stability criterion are still reported for information purposes.
+
+%% =================================================================================================
+\subsection[Implicit top/bottom friction (\forcode{ln_drgimp=.true.})]{Implicit top/bottom friction (\protect\np[=.true.]{ln_drgimp}{ln\_drgimp})}
+\label{subsec:ZDF_drg_imp}
+
+An optional implicit form of bottom friction has been implemented to improve model stability.
+We recommend this option for shelf sea and coastal ocean applications. %, especially for split-explicit time splitting.
+This option can be invoked by setting \np{ln_drgimp}{ln\_drgimp} to \forcode{.true.} in the \nam{drg}{drg} namelist.
+%This option requires \np{ln_zdfexp}{ln\_zdfexp} to be \forcode{.false.} in the \nam{zdf}{zdf} namelist.
+
+This implementation is performed in \mdl{dynzdf} where the following boundary conditions are set while solving the fully implicit diffusion step:
+
+At the top (below an ice shelf cavity):
+\[
+  % \label{eq:ZDF_dynZDF__drg_top}
+  \left.{\left( {\frac{A^{vm} }{e_3 }\ \frac{\partial \textbf{U}_h}{\partial k}} \right)} \right|_{t}
+  = c_{t}^{\textbf{U}}\textbf{u}^{n+1}_{t}
+\]
+
+At the bottom (above the sea floor):
+\[
+  % \label{eq:ZDF_dynZDF__drg_bot}
+  \left.{\left( {\frac{A^{vm} }{e_3 }\ \frac{\partial \textbf{U}_h}{\partial k}} \right)} \right|_{b}
+  = c_{b}^{\textbf{U}}\textbf{u}^{n+1}_{b}
+\]
+
+where $t$ and $b$ refers to top and bottom layers respectively.
+Superscript $n+1$ means the velocity used in the friction formula is to be calculated, so it is implicit.
+
+%% =================================================================================================
+\subsection[Bottom friction with split-explicit free surface]{Bottom friction with split-explicit free surface}
+\label{subsec:ZDF_drg_ts}
+
+With split-explicit free surface, the sub-stepping of barotropic equations needs the knowledge of top/bottom stresses. An obvious way to satisfy this is to take them as constant over the course of the barotropic integration and equal to the value used to update the baroclinic momentum trend. Provided \np[=.false.]{ln_drgimp}{ln\_drgimp} and a centred or \textit{leap-frog} like integration of barotropic equations is used (\ie\ \forcode{ln_bt_fw=.false.}, cf \autoref{subsec:DYN_spg_ts}), this does ensure that barotropic and baroclinic dynamics feel the same stresses during one leapfrog time step. However, if \np[=.true.]{ln_drgimp}{ln\_drgimp},  stresses depend on the \textit{after} value of the velocities which themselves depend on the barotropic iteration result. This cyclic dependency makes difficult obtaining consistent stresses in 2d and 3d dynamics. Part of this mismatch is then removed when setting the final barotropic component of 3d velocities to the time splitting estimate. This last step can be seen as a necessary evil but should be minimized since it interferes with the adjustment to the boundary conditions.
+
+The strategy to handle top/bottom stresses with split-explicit free surface in \NEMO\ is as follows:
+\begin{enumerate}
+\item To extend the stability of the barotropic sub-stepping, bottom stresses are refreshed at each sub-iteration. The baroclinic part of the flow entering the stresses is frozen at the initial time of the barotropic iteration. In case of non-linear friction, the drag coefficient is also constant.
+\item In case of an implicit drag, specific computations are performed in \mdl{dynzdf} which renders the overall scheme mixed explicit/implicit: the barotropic components of 3d velocities are removed before seeking for the implicit vertical diffusion result. Top/bottom stresses due to the barotropic components are explicitly accounted for thanks to the updated values of barotropic velocities. Then the implicit solution of 3d velocities is obtained. Lastly, the residual barotropic component is replaced by the time split estimate.
+\end{enumerate}
+
+Note that other strategies are possible, like considering vertical diffusion step in advance, \ie\ prior barotropic integration.
+
+%% =================================================================================================
+\section[Internal wave-driven mixing (\forcode{ln_zdfiwm})]{Internal wave-driven mixing (\protect\np{ln_zdfiwm}{ln\_zdfiwm})}
+\label{subsec:ZDF_tmx_new}
+
+\begin{listing}
+  \nlst{namzdf_iwm}
+  \caption{\forcode{&namzdf_iwm}}
+  \label{lst:namzdf_iwm}
+\end{listing}
+
+The parameterization of mixing induced by breaking internal waves is a generalization of
+the approach originally proposed by \citet{st-laurent.simmons.ea_GRL02}.
+A three-dimensional field of internal wave energy dissipation $\epsilon(x,y,z)$ is first constructed,
+and the resulting diffusivity is obtained as
+\[
+  % \label{eq:ZDF_Kwave}
+  A^{vT}_{wave} =  R_f \,\frac{ \epsilon }{ \rho \, N^2 }
+\]
+where $R_f$ is the mixing efficiency and $\epsilon$ is a specified three dimensional distribution of
+the energy available for mixing.
+If the \np{ln_mevar}{ln\_mevar} namelist parameter is set to \forcode{.false.}, the mixing efficiency is taken as constant and
+equal to 1/6 \citep{osborn_JPO80}.
+In the opposite (recommended) case, $R_f$ is instead a function of
+the turbulence intensity parameter $Re_b = \frac{ \epsilon}{\nu \, N^2}$,
+with $\nu$ the molecular viscosity of seawater, following the model of \cite{bouffard.boegman_DAO13} and
+the implementation of \cite{de-lavergne.madec.ea_JPO16}.
+Note that $A^{vT}_{wave}$ is bounded by $10^{-2}\,m^2/s$, a limit that is often reached when
+the mixing efficiency is constant.
+
+In addition to the mixing efficiency, the ratio of salt to heat diffusivities can chosen to vary
+as a function of $Re_b$ by setting the \np{ln_tsdiff}{ln\_tsdiff} parameter to \forcode{.true.}, a recommended choice.
+This parameterization of differential mixing, due to \cite{jackson.rehmann_JPO14},
+is implemented as in \cite{de-lavergne.madec.ea_JPO16}.
+
+The three-dimensional distribution of the energy available for mixing, $\epsilon(i,j,k)$,
+is constructed from three static maps of column-integrated internal wave energy dissipation,
+$E_{cri}(i,j)$, $E_{pyc}(i,j)$, and $E_{bot}(i,j)$, combined to three corresponding vertical structures:
+
+\begin{align*}
+  F_{cri}(i,j,k) &\propto e^{-h_{ab} / h_{cri} }\\
+  F_{pyc}(i,j,k) &\propto N^{n_p}\\
+  F_{bot}(i,j,k) &\propto N^2 \, e^{- h_{wkb} / h_{bot} }
+\end{align*}
+In the above formula, $h_{ab}$ denotes the height above bottom,
+$h_{wkb}$ denotes the WKB-stretched height above bottom, defined by
+\[
+  h_{wkb} = H \, \frac{ \int_{-H}^{z} N \, dz' } { \int_{-H}^{\eta} N \, dz'  } \; ,
+\]
+The $n_p$ parameter (given by \np{nn_zpyc}{nn\_zpyc} in \nam{zdf_iwm}{zdf\_iwm} namelist)
+controls the stratification-dependence of the pycnocline-intensified dissipation.
+It can take values of $1$ (recommended) or $2$.
+Finally, the vertical structures $F_{cri}$ and $F_{bot}$ require the specification of
+the decay scales $h_{cri}(i,j)$ and $h_{bot}(i,j)$, which are defined by two additional input maps.
+$h_{cri}$ is related to the large-scale topography of the ocean (etopo2) and
+$h_{bot}$ is a function of the energy flux $E_{bot}$, the characteristic horizontal scale of
+the abyssal hill topography \citep{goff_JGR10} and the latitude.
+% Jc: input files names ?
+
+%% =================================================================================================
+\section[Surface wave-induced mixing (\forcode{ln_zdfswm})]{Surface wave-induced mixing (\protect\np{ln_zdfswm}{ln\_zdfswm})}
+\label{subsec:ZDF_swm}
+
+Surface waves produce an enhanced mixing through wave-turbulence interaction.
+In addition to breaking waves induced turbulence (\autoref{subsec:ZDF_tke}),
+the influence of non-breaking waves can be accounted introducing
+wave-induced viscosity and diffusivity as a function of the wave number spectrum.
+Following \citet{qiao.yuan.ea_OD10}, a formulation of wave-induced mixing coefficient
+is provided  as a function of wave amplitude, Stokes Drift and wave-number:
+
+\begin{equation}
+  \label{eq:ZDF_Bv}
+  B_{v} = \alpha {A} {U}_{st} {exp(3kz)}
+\end{equation}
+
+Where $B_{v}$ is the wave-induced mixing coefficient, $A$ is the wave amplitude,
+${U}_{st}$ is the Stokes Drift velocity, $k$ is the wave number and $\alpha$
+is a constant which should be determined by observations or
+numerical experiments and is set to be 1.
+
+The coefficient $B_{v}$ is then directly added to the vertical viscosity
+and diffusivity coefficients.
+
+In order to account for this contribution set: \forcode{ln_zdfswm=.true.},
+then wave interaction has to be activated through \forcode{ln_wave=.true.},
+the Stokes Drift can be evaluated by setting \forcode{ln_sdw=.true.}
+(see \autoref{subsec:SBC_wave_sdw})
+and the needed wave fields can be provided either in forcing or coupled mode
+(for more information on wave parameters and settings see \autoref{sec:SBC_wave})
+
+%% =================================================================================================
+\section[Adaptive-implicit vertical advection (\forcode{ln_zad_Aimp})]{Adaptive-implicit vertical advection(\protect\np{ln_zad_Aimp}{ln\_zad\_Aimp})}
+\label{subsec:ZDF_aimp}
+
+The adaptive-implicit vertical advection option in NEMO is based on the work of
+\citep{shchepetkin_OM15}.  In common with most ocean models, the timestep used with NEMO
+needs to satisfy multiple criteria associated with different physical processes in order
+to maintain numerical stability. \citep{shchepetkin_OM15} pointed out that the vertical
+CFL criterion is commonly the most limiting. \citep{lemarie.debreu.ea_OM15} examined the
+constraints for a range of time and space discretizations and provide the CFL stability
+criteria for a range of advection schemes. The values for the Leap-Frog with Robert
+asselin filter time-stepping (as used in NEMO) are reproduced in
+\autoref{tab:ZDF_zad_Aimp_CFLcrit}. Treating the vertical advection implicitly can avoid these
+restrictions but at the cost of large dispersive errors and, possibly, large numerical
+viscosity. The adaptive-implicit vertical advection option provides a targetted use of the
+implicit scheme only when and where potential breaches of the vertical CFL condition
+occur. In many practical applications these events may occur remote from the main area of
+interest or due to short-lived conditions such that the extra numerical diffusion or
+viscosity does not greatly affect the overall solution. With such applications, setting:
+\forcode{ln_zad_Aimp=.true.} should allow much longer model timesteps to be used whilst
+retaining the accuracy of the high order explicit schemes over most of the domain.
+
+\begin{table}[htbp]
+  \centering
+  % \begin{tabular}{cp{70pt}cp{70pt}cp{70pt}cp{70pt}}
+  \begin{tabular}{r|ccc}
+    \hline
+    spatial discretization  & 2$^nd$ order centered & 3$^rd$ order upwind & 4$^th$ order compact \\
+    advective CFL criterion &                 0.904 &              0.472  &                0.522 \\
+    \hline
+  \end{tabular}
+  \caption[Advective CFL criteria for the leapfrog with Robert Asselin filter time-stepping]{
+    The advective CFL criteria for a range of spatial discretizations for
+    the leapfrog with Robert Asselin filter time-stepping
+    ($\nu=0.1$) as given in \citep{lemarie.debreu.ea_OM15}.}
+  \label{tab:ZDF_zad_Aimp_CFLcrit}
+\end{table}
+
+In particular, the advection scheme remains explicit everywhere except where and when
+local vertical velocities exceed a threshold set just below the explicit stability limit.
+Once the threshold is reached a tapered transition towards an implicit scheme is used by
+partitioning the vertical velocity into a part that can be treated explicitly and any
+excess that must be treated implicitly. The partitioning is achieved via a Courant-number
+dependent weighting algorithm as described in \citep{shchepetkin_OM15}.
+
+The local cell Courant number ($Cu$) used for this partitioning is:
+
+\begin{equation}
+  \label{eq:ZDF_Eqn_zad_Aimp_Courant}
+  \begin{split}
+    Cu &= {2 \rdt \over e^n_{3t_{ijk}}} \bigg (\big [ \texttt{Max}(w^n_{ijk},0.0) - \texttt{Min}(w^n_{ijk+1},0.0) \big ]    \\
+       &\phantom{=} +\big [ \texttt{Max}(e_{{2_u}ij}e^n_{{3_{u}}ijk}u^n_{ijk},0.0) - \texttt{Min}(e_{{2_u}i-1j}e^n_{{3_{u}}i-1jk}u^n_{i-1jk},0.0) \big ]
+                     \big / e_{{1_t}ij}e_{{2_t}ij}            \\
+       &\phantom{=} +\big [ \texttt{Max}(e_{{1_v}ij}e^n_{{3_{v}}ijk}v^n_{ijk},0.0) - \texttt{Min}(e_{{1_v}ij-1}e^n_{{3_{v}}ij-1k}v^n_{ij-1k},0.0) \big ]
+                     \big / e_{{1_t}ij}e_{{2_t}ij} \bigg )    \\
+  \end{split}
+\end{equation}
+
+\noindent and the tapering algorithm follows \citep{shchepetkin_OM15} as:
+
+\begin{align}
+  \label{eq:ZDF_Eqn_zad_Aimp_partition}
+Cu_{min} &= 0.15 \nonumber \\
+Cu_{max} &= 0.3  \nonumber \\
+Cu_{cut} &= 2Cu_{max} - Cu_{min} \nonumber \\
+Fcu    &= 4Cu_{max}*(Cu_{max}-Cu_{min}) \nonumber \\
+\cf &=
+     \begin{cases}
+        0.0                                                        &\text{if $Cu \leq Cu_{min}$} \\
+        (Cu - Cu_{min})^2 / (Fcu +  (Cu - Cu_{min})^2)             &\text{else if $Cu < Cu_{cut}$} \\
+        (Cu - Cu_{max}) / Cu                                       &\text{else}
+     \end{cases}
+\end{align}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_zad_Aimp_coeff}
+  \caption[Partitioning coefficient used to partition vertical velocities into parts]{
+    The value of the partitioning coefficient (\cf) used to partition vertical velocities into
+    parts to be treated implicitly and explicitly for a range of typical Courant numbers
+    (\forcode{ln_zad_Aimp=.true.}).}
+  \label{fig:ZDF_zad_Aimp_coeff}
+\end{figure}
+
+\noindent The partitioning coefficient is used to determine the part of the vertical
+velocity that must be handled implicitly ($w_i$) and to subtract this from the total
+vertical velocity ($w_n$) to leave that which can continue to be handled explicitly:
+
+\begin{align}
+  \label{eq:ZDF_Eqn_zad_Aimp_partition2}
+    w_{i_{ijk}} &= \cf_{ijk} w_{n_{ijk}}     \nonumber \\
+    w_{n_{ijk}} &= (1-\cf_{ijk}) w_{n_{ijk}}
+\end{align}
+
+\noindent Note that the coefficient is such that the treatment is never fully implicit;
+the three cases from \autoref{eq:ZDF_Eqn_zad_Aimp_partition} can be considered as:
+fully-explicit; mixed explicit/implicit and mostly-implicit.  With the settings shown the
+coefficient (\cf) varies as shown in \autoref{fig:ZDF_zad_Aimp_coeff}. Note with these values
+the $Cu_{cut}$ boundary between the mixed implicit-explicit treatment and 'mostly
+implicit' is 0.45 which is just below the stability limited given in
+\autoref{tab:ZDF_zad_Aimp_CFLcrit}  for a 3rd order scheme.
+
+The $w_i$ component is added to the implicit solvers for the vertical mixing in
+\mdl{dynzdf} and \mdl{trazdf} in a similar way to \citep{shchepetkin_OM15}.  This is
+sufficient for the flux-limited advection scheme (\forcode{ln_traadv_mus}) but further
+intervention is required when using the flux-corrected scheme (\forcode{ln_traadv_fct}).
+For these schemes the implicit upstream fluxes must be added to both the monotonic guess
+and to the higher order solution when calculating the antidiffusive fluxes. The implicit
+vertical fluxes are then removed since they are added by the implicit solver later on.
+
+The adaptive-implicit vertical advection option is new to NEMO at v4.0 and has yet to be
+used in a wide range of simulations. The following test simulation, however, does illustrate
+the potential benefits and will hopefully encourage further testing and feedback from users:
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_zad_Aimp_overflow_frames}
+  \caption[OVERFLOW: time-series of temperature vertical cross-sections]{
+    A time-series of temperature vertical cross-sections for the OVERFLOW test case.
+    These results are for the default settings with \forcode{nn_rdt=10.0} and
+    without adaptive implicit vertical advection (\forcode{ln_zad_Aimp=.false.}).}
+  \label{fig:ZDF_zad_Aimp_overflow_frames}
+\end{figure}
+
+%% =================================================================================================
+\subsection{Adaptive-implicit vertical advection in the OVERFLOW test-case}
+
+The \href{https://forge.ipsl.jussieu.fr/nemo/chrome/site/doc/NEMO/guide/html/test\_cases.html\#overflow}{OVERFLOW test case}
+provides a simple illustration of the adaptive-implicit advection in action. The example here differs from the basic test case
+by only a few extra physics choices namely:
+
+\begin{verbatim}
+     ln_dynldf_OFF = .false.
+     ln_dynldf_lap = .true.
+     ln_dynldf_hor = .true.
+     ln_zdfnpc     = .true.
+     ln_traadv_fct = .true.
+        nn_fct_h   =  2
+        nn_fct_v   =  2
+\end{verbatim}
+
+\noindent which were chosen to provide a slightly more stable and less noisy solution. The
+result when using the default value of \forcode{nn_rdt=10.} without adaptive-implicit
+vertical velocity is illustrated in \autoref{fig:ZDF_zad_Aimp_overflow_frames}. The mass of
+cold water, initially sitting on the shelf, moves down the slope and forms a
+bottom-trapped, dense plume. Even with these extra physics choices the model is close to
+stability limits and attempts with \forcode{nn_rdt=30.} will fail after about 5.5 hours
+with excessively high horizontal velocities. This time-scale corresponds with the time the
+plume reaches the steepest part of the topography and, although detected as a horizontal
+CFL breach, the instability originates from a breach of the vertical CFL limit. This is a good
+candidate, therefore, for use of the adaptive-implicit vertical advection scheme.
+
+The results with \forcode{ln_zad_Aimp=.true.} and a variety of model timesteps
+are shown in \autoref{fig:ZDF_zad_Aimp_overflow_all_rdt} (together with the equivalent
+frames from the base run).  In this simple example the use of the adaptive-implicit
+vertcal advection scheme has enabled a 12x increase in the model timestep without
+significantly altering the solution (although at this extreme the plume is more diffuse
+and has not travelled so far).  Notably, the solution with and without the scheme is
+slightly different even with \forcode{nn_rdt=10.}; suggesting that the base run was
+close enough to instability to trigger the scheme despite completing successfully.
+To assist in diagnosing how active the scheme is, in both location and time, the 3D
+implicit and explicit components of the vertical velocity are available via XIOS as
+\texttt{wimp} and \texttt{wexp} respectively.  Likewise, the partitioning coefficient
+(\cf) is also available as \texttt{wi\_cff}. For a quick oversight of
+the schemes activity the global maximum values of the absolute implicit component
+of the vertical velocity and the partitioning coefficient are written to the netCDF
+version of the run statistics file (\texttt{run.stat.nc}) if this is active (see
+\autoref{sec:MISC_opt} for activation details).
+
+\autoref{fig:ZDF_zad_Aimp_maxCf} shows examples of the maximum partitioning coefficient for
+the various overflow tests.  Note that the adaptive-implicit vertical advection scheme is
+active even in the base run with \forcode{nn_rdt=10.0s} adding to the evidence that the
+test case is close to stability limits even with this value. At the larger timesteps, the
+vertical velocity is treated mostly implicitly at some location throughout the run. The
+oscillatory nature of this measure appears to be linked to the progress of the plume front
+as each cusp is associated with the location of the maximum shifting to the adjacent cell.
+This is illustrated in \autoref{fig:ZDF_zad_Aimp_maxCf_loc} where the i- and k- locations of the
+maximum have been overlaid for the base run case.
+
+\medskip
+\noindent Only limited tests have been performed in more realistic configurations. In the
+ORCA2\_ICE\_PISCES reference configuration the scheme does activate and passes
+restartability and reproducibility tests but it is unable to improve the model's stability
+enough to allow an increase in the model time-step. A view of the time-series of maximum
+partitioning coefficient (not shown here)  suggests that the default time-step of 5400s is
+already pushing at stability limits, especially in the initial start-up phase. The
+time-series does not, however, exhibit any of the 'cuspiness' found with the overflow
+tests.
+
+\medskip
+\noindent A short test with an eORCA1 configuration promises more since a test using a
+time-step of 3600s remains stable with \forcode{ln_zad_Aimp=.true.} whereas the
+time-step is limited to 2700s without.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_zad_Aimp_overflow_all_rdt}
+  \caption[OVERFLOW: sample temperature vertical cross-sections from mid- and end-run]{
+    Sample temperature vertical cross-sections from mid- and end-run using
+    different values for \forcode{nn_rdt} and with or without adaptive implicit vertical advection.
+    Without the adaptive implicit vertical advection
+    only the run with the shortest timestep is able to run to completion.
+    Note also that the colour-scale has been chosen to confirm that
+    temperatures remain within the original range of 10$^o$ to 20$^o$.}
+  \label{fig:ZDF_zad_Aimp_overflow_all_rdt}
+\end{figure}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_zad_Aimp_maxCf}
+  \caption[OVERFLOW: maximum partitioning coefficient during a series of test runs]{
+    The maximum partitioning coefficient during a series of test runs with
+    increasing model timestep length.
+    At the larger timesteps,
+    the vertical velocity is treated mostly implicitly at some location throughout the run.}
+  \label{fig:ZDF_zad_Aimp_maxCf}
+\end{figure}
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{ZDF_zad_Aimp_maxCf_loc}
+  \caption[OVERFLOW: maximum partitioning coefficient for the case overlaid]{
+    The maximum partitioning coefficient for the \forcode{nn_rdt=10.0} case overlaid with
+    information on the gridcell i- and k-locations of the maximum value.}
+  \label{fig:ZDF_zad_Aimp_maxCf_loc}
+\end{figure}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_cfgs.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_cfgs.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_cfgs.tex	(revision 14097)
@@ -0,0 +1,296 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Configurations}
+\label{chap:CFGS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Introduction}
+\label{sec:CFGS_intro}
+
+The purpose of this part of the manual is to introduce the \NEMO\ reference configurations.
+These configurations are offered as means to explore various numerical and physical options,
+thus allowing the user to verify that the code is performing in a manner consistent with that we are running.
+This form of verification is critical as one adopts the code for his or her particular research purposes.
+The reference configurations also provide a sense for some of the options available in the code,
+though by no means are all options exercised in the reference configurations.
+Configuration is defined manually through the \nam{cfg}{cfg} namelist variables.
+
+\begin{listing}
+  \nlst{namcfg}
+  \caption{\forcode{&namcfg}}
+  \label{lst:namcfg}
+\end{listing}
+
+%% =================================================================================================
+\section[C1D: 1D Water column model (\texttt{\textbf{key\_c1d}})]{C1D: 1D Water column model (\protect\key{c1d})}
+\label{sec:CFGS_c1d}
+
+The 1D model option simulates a stand alone water column within the 3D \NEMO\ system.
+It can be applied to the ocean alone or to the ocean-ice system and can include passive tracers or a biogeochemical model.
+It is set up by defining the position of the 1D water column in the grid
+(see \path{./cfgs/SHARED/namelist\_ref}).
+The 1D model is a very useful tool
+\textit{(a)} to learn about the physics and numerical treatment of vertical mixing processes;
+\textit{(b)} to investigate suitable parameterisations of unresolved turbulence
+(surface wave breaking, Langmuir circulation, ...);
+\textit{(c)} to compare the behaviour of different vertical mixing schemes;
+\textit{(d)} to perform sensitivity studies on the vertical diffusion at a particular point of an ocean domain;
+\textit{(d)} to produce extra diagnostics, without the large memory requirement of the full 3D model.
+
+The methodology is based on the configuration of the smallest possible domain:
+a 3x3 domain with 75 vertical levels.
+
+The 1D model has some specifies. First, all the horizontal derivatives are assumed to be zero,
+and second, the two components of the velocity are moved on a $T$-point.
+Therefore, defining \key{c1d} changes some things in the code behaviour:
+\begin{enumerate}
+\item a simplified \rou{stp} routine is used (\rou{stp\_c1d}, see \mdl{step\_c1d} module) in which
+  both lateral tendancy terms and lateral physics are not called;
+\item the vertical velocity is zero
+  (so far, no attempt at introducing a Ekman pumping velocity has been made);
+\item a simplified treatment of the Coriolis term is performed as $U$- and $V$-points are the same
+  (see \mdl{dyncor\_c1d}).
+\end{enumerate}
+All the relevant \textit{\_c1d} modules can be found in the src/OCE/C1D directory of
+the \NEMO\ distribution.
+
+% to be added:  a test case on the yearlong Ocean Weather Station (OWS) Papa dataset of Martin (1985)
+
+%% =================================================================================================
+\section{ORCA family: global ocean with tripolar grid}
+\label{sec:CFGS_orca}
+
+The ORCA family is a series of global ocean configurations that are run together with
+the SI3 model (ORCA-ICE) and possibly with PISCES biogeochemical model (ORCA-ICE-PISCES).
+An appropriate namelist is available in \path{./cfgs/ORCA2_ICE_PISCES/EXPREF/namelist_cfg} for ORCA2.
+The domain of ORCA2 configuration is defined in \ifile{ORCA\_R2\_zps\_domcfg} file,
+this file is available in tar file on the \NEMO\ community zenodo platform: \\
+https://doi.org/10.5281/zenodo.2640723
+
+In this namelist\_cfg the name of domain input file is set in \nam{cfg}{cfg} block of namelist.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{CFGS_ORCA_NH_mesh}
+  \caption[ORCA mesh conception]{
+    ORCA mesh conception.
+    The departure from an isotropic Mercator grid start poleward of 20\deg{N}.
+    The two "north pole" are the foci of a series of embedded ellipses (blue curves) which
+    are determined analytically and form the i-lines of the ORCA mesh (pseudo latitudes).
+    Then, following \citet{madec.imbard_CD96},
+    the normal to the series of ellipses (red curves) is computed which
+    provides the j-lines of the mesh (pseudo longitudes).}
+  \label{fig:CFGS_ORCA_msh}
+\end{figure}
+
+%% =================================================================================================
+\subsection{ORCA tripolar grid}
+\label{subsec:CFGS_orca_grid}
+
+The ORCA grid is a tripolar grid based on the semi-analytical method of \citet{madec.imbard_CD96}.
+It allows to construct a global orthogonal curvilinear ocean mesh which has no singularity point inside
+the computational domain since two north mesh poles are introduced and placed on lands.
+The method involves defining an analytical set of mesh parallels in the stereographic polar plan,
+computing the associated set of mesh meridians, and projecting the resulting mesh onto the sphere.
+The set of mesh parallels used is a series of embedded ellipses which foci are the two mesh north poles
+(\autoref{fig:CFGS_ORCA_msh}).
+The resulting mesh presents no loss of continuity in either the mesh lines or the scale factors,
+or even the scale factor derivatives over the whole ocean domain, as the mesh is not a composite mesh.
+\begin{figure}[!tbp]
+  \centering
+  \includegraphics[width=0.66\textwidth]{CFGS_ORCA_NH_msh05_e1_e2}
+  \includegraphics[width=0.66\textwidth]{CFGS_ORCA_aniso}
+  \caption[Horizontal scale factors and ratio of anisotropy for ORCA 0.5\deg\ mesh]{
+    \textit{Top}: Horizontal scale factors ($e_1$, $e_2$) and
+    \textit{Bottom}: ratio of anisotropy ($e_1 / e_2$)
+    for ORCA 0.5\deg\ mesh.
+    South of 20\deg{N} a Mercator grid is used ($e_1 = e_2$) so that the anisotropy ratio is 1.
+    Poleward of 20\deg{N},
+    the two "north pole" introduce a weak anisotropy over the ocean areas ($< 1.2$) except in
+    vicinity of Victoria Island (Canadian Arctic Archipelago).}
+  \label{fig:CFGS_ORCA_e1e2}
+\end{figure}
+
+The method is applied to Mercator grid (\ie\ same zonal and meridional grid spacing) poleward of 20\deg{N},
+so that the Equator is a mesh line, which provides a better numerical solution for equatorial dynamics.
+The choice of the series of embedded ellipses (position of the foci and variation of the ellipses)
+is a compromise between maintaining the ratio of mesh anisotropy ($e_1 / e_2$) close to one in the ocean
+(especially in area of strong eddy activities such as the Gulf Stream) and keeping the smallest scale factor in
+the northern hemisphere larger than the smallest one in the southern hemisphere.
+The resulting mesh is shown in \autoref{fig:CFGS_ORCA_msh} and \autoref{fig:CFGS_ORCA_e1e2} for
+a half a degree grid (ORCA\_R05).
+The smallest ocean scale factor is found in along Antarctica,
+while the ratio of anisotropy remains close to one except near the Victoria Island in the Canadian Archipelago.
+
+%% =================================================================================================
+\subsection{ORCA pre-defined resolution}
+\label{subsec:CFGS_orca_resolution}
+
+The \NEMO\ system is provided with five built-in ORCA configurations which differ in the horizontal resolution.
+The value of the resolution is given by the resolution at the Equator expressed in degrees.
+Each of configuration is set through the \textit{domain\_cfg} domain configuration file,
+which sets the grid size and configuration name parameters.
+The \NEMO\ System Team provides only ORCA2 domain input file "\ifile{ORCA\_R2\_zps\_domcfg}" file
+(\autoref{tab:CFGS_ORCA}).
+
+\begin{table}[!t]
+  \centering
+  \begin{tabular}{p{4cm} c c c c}
+    Horizontal Grid & \jp{ORCA\_index} & \jp{jpiglo} & \jp{jpjglo} \\
+    \hline \hline
+    % 4   \deg\ &              4   &          92 &          76 \\
+    2   \deg\ &              2   &         182 &         149 \\
+    1   \deg\ &              1   &         362 &         292 \\
+    0.5 \deg\ &              05  &         722 &         511 \\
+    0.25\deg\ &              025 &        1442 &        1021 \\
+    \hline \hline
+  \end{tabular}
+  \caption[Domain size of ORCA family configurations]{
+    Domain size of ORCA family configurations.
+    The flag for configurations of ORCA family need to be set in \textit{domain\_cfg} file.}
+  \label{tab:CFGS_ORCA}
+\end{table}
+
+The ORCA\_R2 configuration has the following specificity: starting from a 2\deg\ ORCA mesh,
+local mesh refinements were applied to the Mediterranean, Red, Black and Caspian Seas,
+so that the resolution is 1\deg\ there.
+A local transformation were also applied with in the Tropics in order to refine the meridional resolution up to
+0.5\deg\ at the Equator.
+
+The ORCA\_R1 configuration has only a local tropical transformation to refine the meridional resolution up to
+1/3\deg\ at the Equator.
+Note that the tropical mesh refinements in ORCA\_R2 and R1 strongly increases the mesh anisotropy there.
+
+The ORCA\_R05 and higher global configurations do not incorporate any regional refinements.
+
+For ORCA\_R1 and R025, setting the configuration key to 75 allows to use 75 vertical levels, otherwise 46 are used.
+In the other ORCA configurations, 31 levels are used
+(see \autoref{tab:CFGS_ORCA}). %\sfcomment{HERE I need to put new table for ORCA2 values} and \autoref{fig:DOM_zgr_e3}).
+
+Only the ORCA\_R2 is provided with all its input files in the \NEMO\ distribution.
+%It is very similar to that used as part of the climate model developed at IPSL for the 4th IPCC assessment of
+%climate change (Marti et al., 2009).
+%It is also the basis for the \NEMO\ contribution to the Coordinate Ocean-ice Reference Experiments (COREs)
+%documented in \citet{griffies.biastoch.ea_OM09}.
+
+This version of ORCA\_R2 has 31 levels in the vertical, with the highest resolution (10m) in the upper 150m
+(see \autoref{tab:CFGS_ORCA} and \autoref{fig:DOM_zgr_e3}).
+The bottom topography and the coastlines are derived from the global atlas of Smith and Sandwell (1997).
+The default forcing uses the boundary forcing from \citet{large.yeager_rpt04} (see \autoref{subsec:SBC_blk_ocean}),
+which was developed for the purpose of running global coupled ocean-ice simulations without
+an interactive atmosphere.
+This \citet{large.yeager_rpt04} dataset is available through
+the \href{http://nomads.gfdl.noaa.gov/nomads/forms/mom4/CORE.html}{GFDL web site}.
+The "normal year" of \citet{large.yeager_rpt04} has been chosen of the \NEMO\ distribution since release v3.3.
+
+ORCA\_R2 pre-defined configuration can also be run with multiply online nested zooms (\ie\ with AGRIF, \key{agrif} defined).
+This is available as the AGRIF\_DEMO configuration that can be found in the \path{./cfgs/AGRIF_DEMO/} directory.
+
+A regional Arctic or peri-Antarctic configuration is extracted from an ORCA\_R2 or R05 configurations using
+sponge layers at open boundaries.
+
+%% =================================================================================================
+\section{GYRE family: double gyre basin}
+\label{sec:CFGS_gyre}
+
+The GYRE configuration \citep{levy.klein.ea_OM10} has been built to
+simulate the seasonal cycle of a double-gyre box model.
+It consists in an idealized domain similar to that used in the studies of \citet{drijfhout_JPO94} and
+\citet{hazeleger.drijfhout_JPO98, hazeleger.drijfhout_JPO99, hazeleger.drijfhout_JGR00, hazeleger.drijfhout_JPO00},
+over which an analytical seasonal forcing is applied.
+This allows to investigate the spontaneous generation of a large number of interacting, transient mesoscale eddies
+and their contribution to the large scale circulation.
+
+The GYRE configuration run together with the PISCES biogeochemical model (GYRE-PISCES).
+The domain geometry is a closed rectangular basin on the $\beta$-plane centred at $\sim$ 30\deg{N} and
+rotated by 45\deg, 3180~km long, 2120~km wide and 4~km deep (\autoref{fig:MISC_strait_hand}).
+The domain is bounded by vertical walls and by a flat bottom.
+The configuration is meant to represent an idealized North Atlantic or North Pacific basin.
+The circulation is forced by analytical profiles of wind and buoyancy fluxes.
+The applied forcings vary seasonally in a sinusoidal manner between winter and summer extrema \citep{levy.klein.ea_OM10}.
+The wind stress is zonal and its curl changes sign at 22\deg{N} and 36\deg{N}.
+It forces a subpolar gyre in the north, a subtropical gyre in the wider part of the domain and
+a small recirculation gyre in the southern corner.
+The net heat flux takes the form of a restoring toward a zonal apparent air temperature profile.
+A portion of the net heat flux which comes from the solar radiation is allowed to penetrate within the water column.
+The fresh water flux is also prescribed and varies zonally.
+It is determined such as, at each time step, the basin-integrated flux is zero.
+The basin is initialised at rest with vertical profiles of temperature and salinity uniformly applied to
+the whole domain.
+
+The GYRE configuration is set like an analytical configuration.
+Through \np[=.false.]{ln_read_cfg}{ln\_read\_cfg} in \nam{cfg}{cfg} namelist defined in
+the reference configuration \path{./cfgs/GYRE_PISCES/EXPREF/namelist_cfg}
+analytical definition of grid in GYRE is done in usrdef\_hrg, usrdef\_zgr routines.
+Its horizontal resolution (and thus the size of the domain) is determined by
+setting \np{nn_GYRE}{nn\_GYRE} in \nam{usr_def}{usr\_def}: \\
+
+\jp{jpiglo} $= 30 \times$ \np{nn_GYRE}{nn\_GYRE} + 2   \\
+
+\jp{jpjglo} $= 20 \times$ \np{nn_GYRE}{nn\_GYRE} + 2   \\
+
+Obviously, the namelist parameters have to be adjusted to the chosen resolution,
+see the Configurations pages on the \NEMO\ web site (\NEMO\ Configurations).
+In the vertical, GYRE uses the default 30 ocean levels (\jp{jpk}\forcode{ = 31}) (\autoref{fig:DOM_zgr_e3}).
+
+The GYRE configuration is also used in benchmark test as it is very simple to increase its resolution and
+as it does not requires any input file.
+For example, keeping a same model size on each processor while increasing the number of processor used is very easy,
+even though the physical integrity of the solution can be compromised.
+Benchmark is activate via \np[=.true.]{ln_bench}{ln\_bench} in \nam{usr_def}{usr\_def} in
+namelist \path{./cfgs/GYRE_PISCES/EXPREF/namelist_cfg}.
+
+\begin{figure}[!t]
+  \centering
+  \includegraphics[width=0.66\textwidth]{CFGS_GYRE}
+  \caption[Snapshot of relative vorticity at the surface of the model domain in GYRE R9, R27 and R54]{
+    Snapshot of relative vorticity at the surface of the model domain in GYRE R9, R27 and R54.
+    From \citet{levy.klein.ea_OM10}.}
+  \label{fig:CFGS_GYRE}
+\end{figure}
+
+%% =================================================================================================
+\section{AMM: atlantic margin configuration}
+\label{sec:CFGS_config_AMM}
+
+The AMM, Atlantic Margins Model, is a regional model covering the Northwest European Shelf domain on
+a regular lat-lon grid at approximately 12km horizontal resolution.
+The appropriate \textit{\&namcfg} namelist  is available in \path{./cfgs/AMM12/EXPREF/namelist\_cfg}.
+It is used to build the correct dimensions of the AMM domain.
+
+This configuration tests several features of \NEMO\ functionality specific to the shelf seas.
+In particular, the AMM uses $s$-coordinates in the vertical rather than $z$-coordinates and
+is forced with tidal lateral boundary conditions using a Flather boundary condition from the BDY module.
+Also specific to the AMM configuration is the use of the GLS turbulence scheme (\np[=.true.]{ln_zdfgls}{ln\_zdfgls}).
+
+In addition to the tidal boundary condition the model may also take open boundary conditions from
+a North Atlantic model.
+Boundaries may be completely omitted by setting \np{ln_bdy}{ln\_bdy} to false.
+Sample surface fluxes, river forcing and a sample initial restart file are included to test a realistic model run.
+The Baltic boundary is included within the river input file and is specified as a river source.
+Unlike ordinary river points the Baltic inputs also include salinity and temperature data.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_conservation.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_conservation.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_conservation.tex	(revision 14097)
@@ -0,0 +1,338 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Invariants of the Primitive Equations}
+\label{chap:CONS}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+The continuous equations of motion have many analytic properties.
+Many quantities (total mass, energy, enstrophy, etc.) are strictly conserved in the inviscid and unforced limit,
+while ocean physics conserve the total quantities on which they act (momentum, temperature, salinity) but
+dissipate their total variance (energy, enstrophy, etc.).
+Unfortunately, the finite difference form of these equations is not guaranteed to
+retain all these important properties.
+In constructing the finite differencing schemes, we wish to ensure that
+certain integral constraints will be maintained.
+In particular, it is desirable to construct the finite difference equations so that
+horizontal kinetic energy and/or potential enstrophy of horizontally non-divergent flow,
+and variance of temperature and salinity will be conserved in the absence of dissipative effects and forcing.
+\citet{arakawa_JCP66} has first pointed out the advantage of this approach.
+He showed that if integral constraints on energy are maintained,
+the computation will be free of the troublesome "non linear" instability originally pointed out by
+\citet{phillips_TAMS59}.
+A consistent formulation of the energetic properties is also extremely important in carrying out
+long-term numerical simulations for an oceanographic model.
+Such a formulation avoids systematic errors that accumulate with time \citep{bryan_JCP97}.
+
+The general philosophy of OPA which has led to the discrete formulation presented in {\S}II.2 and II.3 is to
+choose second order non-diffusive scheme for advective terms for both dynamical and tracer equations.
+At this level of complexity, the resulting schemes are dispersive schemes.
+Therefore, they require the addition of a diffusive operator to be stable.
+The alternative is to use diffusive schemes such as upstream or flux corrected schemes.
+This last option was rejected because we prefer a complete handling of the model diffusion,
+\ie\ of the model physics rather than letting the advective scheme produces its own implicit diffusion without
+controlling the space and time structure of this implicit diffusion.
+Note that in some very specific cases as passive tracer studies, the positivity of the advective scheme is required.
+In that case, and in that case only, the advective scheme used for passive tracer is a flux correction scheme
+\citep{Marti1992?, Levy1996?, Levy1998?}.
+
+%% =================================================================================================
+\section{Conservation properties on ocean dynamics}
+\label{sec:CONS_Invariant_dyn}
+
+The non linear term of the momentum equations has been split into a vorticity term,
+a gradient of horizontal kinetic energy and a vertical advection term.
+Three schemes are available for the former (see {\S}~II.2) according to the CPP variable defined
+(default option\textbf{?}or \textbf{key{\_}vorenergy} or \textbf{key{\_}vorcombined} defined).
+They differ in their conservative properties (energy or enstrophy conserving scheme).
+The two latter terms preserve the total kinetic energy:
+the large scale kinetic energy is also preserved in practice.
+The remaining non-diffusive terms of the momentum equation
+(namely the hydrostatic and surface pressure gradient terms) also preserve the total kinetic energy and
+have no effect on the vorticity of the flow.
+
+\textbf{* relative, planetary and total vorticity term:}
+
+Let us define as either the relative, planetary and total potential vorticity, \ie, ?, and ?, respectively.
+The continuous formulation of the vorticity term satisfies following integral constraints:
+\[
+  % \label{eq:CONS_vor_vorticity}
+  \int_D {{\textbf {k}}\cdot \frac{1}{e_3 }\nabla \times \left( {\varsigma
+        \;{\mathrm {\mathbf k}}\times {\textbf {U}}_h } \right)\;dv} =0
+\]
+
+\[
+  % \label{eq:CONS_vor_enstrophy}
+  if\quad \chi =0\quad \quad \int\limits_D {\varsigma \;{\textbf{k}}\cdot
+    \frac{1}{e_3 }\nabla \times \left( {\varsigma {\textbf{k}}\times {\textbf{U}}_h } \right)\;dv} =-\int\limits_D {\frac{1}{2}\varsigma ^2\,\chi \;dv}
+  =0
+\]
+
+\[
+  % \label{eq:CONS_vor_energy}
+  \int_D {{\textbf{U}}_h \times \left( {\varsigma \;{\textbf{k}}\times {\textbf{U}}_h } \right)\;dv} =0
+\]
+where $dv = e_1\, e_2\, e_3\, di\, dj\, dk$ is the volume element.
+(II.4.1a) means that $\varsigma $ is conserved. (II.4.1b) is obtained by an integration by part.
+It means that $\varsigma^2$ is conserved for a horizontally non-divergent flow.
+(II.4.1c) is even satisfied locally since the vorticity term is orthogonal to the horizontal velocity.
+It means that the vorticity term has no contribution to the evolution of the total kinetic energy.
+(II.4.1a) is obviously always satisfied, but (II.4.1b) and (II.4.1c) cannot be satisfied simultaneously with
+a second order scheme.
+Using the symmetry or anti-symmetry properties of the operators (Eqs II.1.10 and 11),
+it can be shown that the scheme (II.2.11) satisfies (II.4.1b) but not (II.4.1c),
+while scheme (II.2.12) satisfies (II.4.1c) but not (II.4.1b) (see appendix C).
+Note that the enstrophy conserving scheme on total vorticity has been chosen as the standard discrete form of
+the vorticity term.
+
+\textbf{* Gradient of kinetic energy / vertical advection}
+
+In continuous formulation, the gradient of horizontal kinetic energy has no contribution to the evolution of
+the vorticity as the curl of a gradient is zero.
+This property is satisfied locally with the discrete form of both the gradient and the curl operator we have made
+(property (II.1.9)~).
+Another continuous property is that the change of horizontal kinetic energy due to
+vertical advection is exactly balanced by the change of horizontal kinetic energy due to
+the horizontal gradient of horizontal kinetic energy:
+
+\begin{equation} \label{eq:CONS_keg_zad}
+\int_D {{\textbf{U}}_h \cdot \nabla _h \left( {1/2\;{\textbf{U}}_h ^2} \right)\;dv} =-\int_D {{\textbf{U}}_h \cdot \frac{w}{e_3 }\;\frac{\partial
+{\textbf{U}}_h }{\partial k}\;dv}
+\end{equation}
+
+Using the discrete form given in {\S}II.2-a and the symmetry or anti-symmetry properties of
+the mean and difference operators, \autoref{eq:CONS_keg_zad} is demonstrated in the Appendix C.
+The main point here is that satisfying \autoref{eq:CONS_keg_zad} links the choice of the discrete forms of
+the vertical advection and of the horizontal gradient of horizontal kinetic energy.
+Choosing one imposes the other.
+The discrete form of the vertical advection given in {\S}II.2-a is a direct consequence of
+formulating the horizontal kinetic energy as $1/2 \left( \overline{u^2}^i + \overline{v^2}^j \right) $ in
+the gradient term.
+
+\textbf{* hydrostatic pressure gradient term}
+
+In continuous formulation, a pressure gradient has no contribution to the evolution of the vorticity as
+the curl of a gradient is zero.
+This properties is satisfied locally with the choice of discretization we have made (property (II.1.9)~).
+In addition, when the equation of state is linear
+(\ie\ when an advective-diffusive equation for density can be derived from those of temperature and salinity)
+the change of horizontal kinetic energy due to the work of pressure forces is balanced by the change of
+potential energy due to buoyancy forces:
+
+\[
+  % \label{eq:CONS_hpg_pe}
+  \int_D {-\frac{1}{\rho_o }\left. {\nabla p^h} \right|_z \cdot {\textbf {U}}_h \;dv} \;=\;\int_D {\nabla .\left( {\rho \,{\textbf{U}}} \right)\;g\;z\;\;dv}
+\]
+
+Using the discrete form given in {\S}~II.2-a and the symmetry or anti-symmetry properties of
+the mean and difference operators, (II.4.3) is demonstrated in the Appendix C.
+The main point here is that satisfying (II.4.3) strongly constraints the discrete expression of the depth of
+$T$-points and of the term added to the pressure gradient in $s-$coordinates: the depth of a $T$-point, $z_T$,
+is defined as the sum the vertical scale factors at $w$-points starting from the surface.
+
+\textbf{* surface pressure gradient term}
+
+In continuous formulation, the surface pressure gradient has no contribution to the evolution of vorticity.
+This properties is trivially satisfied locally as (II.2.3)
+(the equation verified by $\psi$ has been derived from the discrete formulation of the momentum equations,
+vertical sum and curl).
+Nevertheless, the $\psi$-equation is solved numerically by an iterative solver (see {\S}~III.5),
+thus the property is only satisfied with the accuracy required on the solver.
+In addition, with the rigid-lid approximation, the change of horizontal kinetic energy due to the work of
+surface pressure forces is exactly zero:
+\[
+  % \label{eq:CONS_spg}
+  \int_D {-\frac{1}{\rho_o }\nabla _h } \left( {p_s } \right)\cdot {\textbf{U}}_h \;dv=0
+\]
+
+(II.4.4) is satisfied in discrete form only if
+the discrete barotropic streamfunction time evolution equation is given by (II.2.3) (see appendix C).
+This shows that (II.2.3) is the only way to compute the streamfunction,
+otherwise there is no guarantee that the surface pressure force work vanishes.
+
+%% =================================================================================================
+\section{Conservation properties on ocean thermodynamics}
+\label{sec:CONS_Invariant_tra}
+
+In continuous formulation, the advective terms of the tracer equations conserve the tracer content and
+the quadratic form of the tracer, \ie
+\[
+  % \label{eq:CONS_tra_tra2}
+  \int_D {\nabla .\left( {T\;{\textbf{U}}} \right)\;dv} =0
+  \;\text{and}
+  \int_D {T\;\nabla .\left( {T\;{\textbf{U}}} \right)\;dv} =0
+\]
+
+The numerical scheme used ({\S}II.2-b) (equations in flux form, second order centred finite differences) satisfies
+(II.4.5) (see appendix C).
+Note that in both continuous and discrete formulations, there is generally no strict conservation of mass,
+since the equation of state is non linear with respect to $T$ and $S$.
+In practice, the mass is conserved with a very good accuracy.
+
+%% =================================================================================================
+\subsection{Conservation properties on momentum physics}
+\label{subsec:CONS_Invariant_dyn_physics}
+
+\textbf{* lateral momentum diffusion term}
+
+The continuous formulation of the horizontal diffusion of momentum satisfies the following integral constraints~:
+\[
+  % \label{eq:CONS_dynldf_dyn}
+  \int\limits_D {\frac{1}{e_3 }{\mathrm {\mathbf k}}\cdot \nabla \times \left[ {\nabla
+        _h \left( {A^{lm}\;\chi } \right)-\nabla _h \times \left( {A^{lm}\;\zeta
+            \;{\mathrm {\mathbf k}}} \right)} \right]\;dv} =0
+\]
+
+\[
+  % \label{eq:CONS_dynldf_div}
+  \int\limits_D {\nabla _h \cdot \left[ {\nabla _h \left( {A^{lm}\;\chi }
+        \right)-\nabla _h \times \left( {A^{lm}\;\zeta \;{\mathrm {\mathbf k}}} \right)}
+    \right]\;dv} =0
+\]
+
+\[
+  % \label{eq:CONS_dynldf_curl}
+  \int_D {{\mathrm {\mathbf U}}_h \cdot \left[ {\nabla _h \left( {A^{lm}\;\chi }
+        \right)-\nabla _h \times \left( {A^{lm}\;\zeta \;{\mathrm {\mathbf k}}} \right)}
+    \right]\;dv} \leqslant 0
+\]
+
+\[
+  % \label{eq:CONS_dynldf_curl2}
+  \mbox{if}\quad A^{lm}=cste\quad \quad \int_D {\zeta \;{\mathrm {\mathbf k}}\cdot
+    \nabla \times \left[ {\nabla _h \left( {A^{lm}\;\chi } \right)-\nabla _h
+        \times \left( {A^{lm}\;\zeta \;{\mathrm {\mathbf k}}} \right)} \right]\;dv}
+  \leqslant 0
+\]
+
+\[
+  % \label{eq:CONS_dynldf_div2}
+  \mbox{if}\quad A^{lm}=cste\quad \quad \int_D {\chi \;\nabla _h \cdot \left[
+      {\nabla _h \left( {A^{lm}\;\chi } \right)-\nabla _h \times \left(
+          {A^{lm}\;\zeta \;{\mathrm {\mathbf k}}} \right)} \right]\;dv} \leqslant 0
+\]
+
+(II.4.6a) and (II.4.6b) means that the horizontal diffusion of momentum conserve both the potential vorticity and
+the divergence of the flow, while Eqs (II.4.6c) to (II.4.6e) mean that it dissipates the energy, the enstrophy and
+the square of the divergence.
+The two latter properties are only satisfied when the eddy coefficients are horizontally uniform.
+
+Using (II.1.8) and (II.1.9), and the symmetry or anti-symmetry properties of the mean and difference operators,
+it is shown that the discrete form of the lateral momentum diffusion given in
+{\S}II.2-c satisfies all the integral constraints (II.4.6) (see appendix C).
+In particular, when the eddy coefficients are horizontally uniform,
+a complete separation of vorticity and horizontal divergence fields is ensured,
+so that diffusion (dissipation) of vorticity (enstrophy) does not generate horizontal divergence
+(variance of the horizontal divergence) and \textit{vice versa}.
+When the vertical curl of the horizontal diffusion of momentum (discrete sense) is taken,
+the term associated to the horizontal gradient of the divergence is zero locally.
+When the horizontal divergence of the horizontal diffusion of momentum (discrete sense) is taken,
+the term associated to the vertical curl of the vorticity is zero locally.
+The resulting term conserves $\chi$ and dissipates $\chi^2$ when the eddy coefficient is horizontally uniform.
+
+\textbf{* vertical momentum diffusion term}
+
+As for the lateral momentum physics, the continuous form of the vertical diffusion of
+momentum satisfies following integral constraints~:
+
+conservation of momentum, dissipation of horizontal kinetic energy
+
+\[
+  % \label{eq:CONS_dynzdf_dyn}
+  \begin{aligned}
+    & \int_D {\frac{1}{e_3 }}  \frac{\partial }{\partial k}\left( \frac{A^{vm}}{e_3 }\frac{\partial {\textbf{U}}_h }{\partial k} \right) \;dv = \overrightarrow{\textbf{0}} \\
+    & \int_D \textbf{U}_h \cdot \frac{1}{e_3} \frac{\partial}{\partial k} \left( {\frac{A^{vm}}{e_3 }}{\frac{\partial \textbf{U}_h }{\partial k}} \right) \;dv \leq 0 \\
+  \end{aligned}
+\]
+conservation of vorticity, dissipation of enstrophy
+\[
+  % \label{eq:CONS_dynzdf_vor}
+  \begin{aligned}
+    & \int_D {\frac{1}{e_3 }{\mathrm {\mathbf k}}\cdot \nabla \times \left( {\frac{1}{e_3
+          }\frac{\partial }{\partial k}\left( {\frac{A^{vm}}{e_3 }\frac{\partial {\mathrm
+                  {\mathbf U}}_h }{\partial k}} \right)} \right)\;dv} =0 \\
+    & \int_D {\zeta \,{\mathrm {\mathbf k}}\cdot \nabla \times \left( {\frac{1}{e_3
+          }\frac{\partial }{\partial k}\left( {\frac{A^{vm}}{e_3 }\frac{\partial {\mathrm
+                  {\mathbf U}}_h }{\partial k}} \right)} \right)\;dv} \leq 0 \\
+  \end{aligned}
+\]
+conservation of horizontal divergence, dissipation of square of the horizontal divergence
+\[
+  % \label{eq:CONS_dynzdf_div}
+  \begin{aligned}
+    &\int_D {\nabla \cdot \left( {\frac{1}{e_3 }\frac{\partial }{\partial
+            k}\left( {\frac{A^{vm}}{e_3 }\frac{\partial {\mathrm {\mathbf U}}_h }{\partial k}}
+          \right)} \right)\;dv} =0 \\
+    & \int_D {\chi \;\nabla \cdot \left( {\frac{1}{e_3 }\frac{\partial }{\partial
+            k}\left( {\frac{A^{vm}}{e_3 }\frac{\partial {\mathrm {\mathbf U}}_h }{\partial k}}
+          \right)} \right)\;dv} \leq 0 \\
+  \end{aligned}
+\]
+
+In discrete form, all these properties are satisfied in $z$-coordinate (see Appendix C).
+In $s$-coordinates, only first order properties can be demonstrated,
+\ie\ the vertical momentum physics conserve momentum, potential vorticity, and horizontal divergence.
+
+%% =================================================================================================
+\subsection{Conservation properties on tracer physics}
+\label{subsec:CONS_Invariant_tra_physics}
+
+The numerical schemes used for tracer subgridscale physics are written in such a way that
+the heat and salt contents are conserved (equations in flux form, second order centred finite differences).
+As a form flux is used to compute the temperature and salinity,
+the quadratic form of these quantities (\ie\ their variance) globally tends to diminish.
+As for the advective term, there is generally no strict conservation of mass even if,
+in practice, the mass is conserved with a very good accuracy.
+
+\textbf{* lateral physics: }conservation of tracer, dissipation of tracer
+variance, i.e.
+
+\[
+  % \label{eq:CONS_traldf_t_t2}
+  \begin{aligned}
+    &\int_D \nabla\, \cdot\, \left( A^{lT} \,\Re \,\nabla \,T \right)\;dv = 0 \\
+    &\int_D \,T\, \nabla\, \cdot\, \left( A^{lT} \,\Re \,\nabla \,T \right)\;dv \leq 0 \\
+  \end{aligned}
+\]
+
+\textbf{* vertical physics: }conservation of tracer, dissipation of tracer variance, \ie
+
+\[
+  % \label{eq:CONS_trazdf_t_t2}
+  \begin{aligned}
+    & \int_D \frac{1}{e_3 } \frac{\partial }{\partial k}\left( \frac{A^{vT}}{e_3 }  \frac{\partial T}{\partial k}  \right)\;dv = 0 \\
+    & \int_D \,T \frac{1}{e_3 } \frac{\partial }{\partial k}\left( \frac{A^{vT}}{e_3 }  \frac{\partial T}{\partial k}  \right)\;dv \leq 0 \\
+  \end{aligned}
+\]
+
+Using the symmetry or anti-symmetry properties of the mean and difference operators,
+it is shown that the discrete form of tracer physics given in {\S}~II.2-c satisfies all the integral constraints
+(II.4.8) and (II.4.9) except the dissipation of the square of the tracer when non-geopotential diffusion is used
+(see appendix C).
+A discrete form of the lateral tracer physics can be derived which satisfies these last properties.
+Nevertheless, it requires a horizontal averaging of the vertical component of the lateral physics that
+prevents the use of implicit resolution in the vertical.
+It has not been implemented.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_misc.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_misc.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_misc.tex	(revision 14097)
@@ -0,0 +1,419 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Miscellaneous Topics}
+\label{chap:MISC}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Representation of unresolved straits}
+\label{sec:MISC_strait}
+
+In climate modeling, it often occurs that a crucial connections between water masses is broken as
+the grid mesh is too coarse to resolve narrow straits.
+For example, coarse grid spacing typically closes off the Mediterranean from the Atlantic at
+the Strait of Gibraltar.
+In this case, it is important for climate models to include the effects of salty water entering the Atlantic from
+the Mediterranean.
+Likewise, it is important for the Mediterranean to replenish its supply of water from the Atlantic to
+balance the net evaporation occurring over the Mediterranean region.
+This problem occurs even in eddy permitting simulations.
+For example, in ORCA 1/4\deg\ several straits of the Indonesian archipelago (Ombai, Lombok...)
+are much narrow than even a single ocean grid-point.
+
+We describe briefly here the two methods that can be used in \NEMO\ to handle such
+improperly resolved straits. The methods consist of opening the strait while ensuring
+that the mass exchanges through the strait are not too large by either artificially
+reducing the cross-sectional area of the strait grid-cells or, locally increasing the
+lateral friction.
+
+%% =================================================================================================
+\subsection{Hand made geometry changes}
+\label{subsec:MISC_strait_hand}
+
+The first method involves reducing the scale factor in the cross-strait direction to a
+value in better agreement with the true mean width of the strait
+(\autoref{fig:MISC_strait_hand}).  This technique is sometime called "partially open face"
+or "partially closed cells".  The key issue here is only to reduce the faces of $T$-cell
+(\ie\ change the value of the horizontal scale factors at $u$- or $v$-point) but not the
+volume of the $T$-cell.  Indeed, reducing the volume of strait $T$-cell can easily produce
+a numerical instability at that grid point which would require a reduction of the model
+time step.  Thus to instigate a local change in the width of a Strait requires two steps:
+
+\begin{itemize}
+
+\item Add \texttt{e1e2u} and \texttt{e1e2v} arrays to the \np{cn_domcfg}{cn\_domcfg} file. These 2D
+arrays should contain the products of the unaltered values of: $\texttt{e1u}*\texttt{e2u}$
+and $\texttt{e1u}*\texttt{e2v}$ respectively. That is the original surface areas of $u$-
+and $v$- cells respectively.  These areas are usually defined by the corresponding product
+within the \NEMO\ code but the presence of \texttt{e1e2u} and \texttt{e1e2v} in the
+\np{cn_domcfg}{cn\_domcfg} file will suppress this calculation and use the supplied fields instead.
+If the model domain is provided by user-supplied code in \mdl{usrdef\_hgr}, then this
+routine should also return \texttt{e1e2u} and \texttt{e1e2v} and set the integer return
+argument \texttt{ie1e2u\_v} to a non-zero value. Values other than 0 for this argument
+will suppress the calculation of the areas.
+
+\item Change values of \texttt{e2u} or \texttt{e1v} (either in the \np{cn_domcfg}{cn\_domcfg} file or
+via code in  \mdl{usrdef\_hgr}), whereever a Strait reduction is required. The choice of
+whether to alter \texttt{e2u} or \texttt{e1v} depends. respectively,  on whether the
+Strait in question is North-South orientated (\eg\ Gibraltar) or East-West orientated (\eg
+Lombok).
+
+\end{itemize}
+
+The second method is to increase the viscous boundary layer thickness by a local increase
+of the fmask value at the coast. This method can also be effective in wider passages.  The
+concept is illustarted in the second part of  \autoref{fig:MISC_strait_hand} and changes
+to specific locations can be coded in \mdl{usrdef\_fmask}. The \forcode{usr_def_fmask}
+routine is always called after \texttt{fmask} has been defined according to the choice of
+lateral boundary condition as discussed in \autoref{sec:LBC_coast}. The default version of
+\mdl{usrdef\_fmask} contains settings specific to ORCA2 and ORCA1 configurations. These are
+meant as examples only; it is up to the user to verify settings and provide alternatives
+for their own configurations. The default \forcode{usr_def_fmask} makes no changes to
+\texttt{fmask} for any other configuration.
+
+\begin{figure}[!tbp]
+  \centering
+  \includegraphics[width=0.66\textwidth]{MISC_Gibraltar}
+  \includegraphics[width=0.66\textwidth]{MISC_Gibraltar2}
+  \caption[Two methods to defined the Gibraltar strait]{
+    Example of the Gibraltar strait defined in a 1\deg\ $\times$ 1\deg\ mesh.
+    \textit{Top}: using partially open cells.
+    The meridional scale factor at $v$-point is reduced on both sides of the strait to
+    account for the real width of the strait (about 20 km).
+    Note that the scale factors of the strait $T$-point remains unchanged.
+    \textit{Bottom}: using viscous boundary layers.
+    The four fmask parameters along the strait coastlines are set to a value larger than 4,
+    \ie\ "strong" no-slip case (see \autoref{fig:LBC_shlat}) creating a large viscous boundary layer
+    that allows a reduced transport through the strait.}
+  \label{fig:MISC_strait_hand}
+\end{figure}
+
+\begin{figure}[!tbp]
+  \centering
+  \includegraphics[width=0.66\textwidth]{MISC_closea_mask_example}
+  \caption[Mask fields for the \protect\mdl{closea} module]{
+    Example of mask fields for the \protect\mdl{closea} module.
+    \textit{Left}: a closea\_mask field;
+    \textit{Right}: a closea\_mask\_rnf field.
+    In this example, if \protect\np{ln_closea}{ln\_closea} is set to \forcode{.true.},
+    the mean freshwater flux over each of the American Great Lakes will be set to zero,
+    and the total residual for all the lakes, if negative, will be put into
+    the St Laurence Seaway in the area shown.}
+  \label{fig:MISC_closea_mask_example}
+\end{figure}
+
+%% =================================================================================================
+\section[Closed seas (\textit{closea.F90})]{Closed seas (\protect\mdl{closea})}
+\label{sec:MISC_closea}
+
+Some configurations include inland seas and lakes as ocean
+points. This is particularly the case for configurations that are
+coupled to an atmosphere model where one might want to include inland
+seas and lakes as ocean model points in order to provide a better
+bottom boundary condition for the atmosphere. However there is no
+route for freshwater to run off from the lakes to the ocean and this
+can lead to large drifts in the sea surface height over the lakes. The
+closea module provides options to either fill in closed seas and lakes
+at run time, or to set the net surface freshwater flux for each lake
+to zero and put the residual flux into the ocean.
+
+Prior to \NEMO\ 4 the locations of inland seas and lakes was set via
+hardcoded indices for various ORCA configurations. From \NEMO\ 4 onwards
+the inland seas and lakes are defined using mask fields in the
+domain configuration file. The options are as follows.
+
+\begin{enumerate}
+\item {{\bfseries No ``closea\_mask'' field is included in domain configuration
+  file.} In this case the closea module does nothing.}
+
+\item {{\bfseries A field called closea\_mask is included in the domain
+configuration file and ln\_closea=.false. in namelist namcfg.} In this
+case the inland seas defined by the closea\_mask field are filled in
+(turned to land points) at run time. That is every point in
+closea\_mask that is nonzero is set to be a land point.}
+
+\item {{\bfseries A field called closea\_mask is included in the domain
+configuration file and ln\_closea=.true. in namelist namcfg.} Each
+inland sea or group of inland seas is set to a positive integer value
+in the closea\_mask field (see \autoref{fig:MISC_closea_mask_example}
+for an example). The net surface flux over each inland sea or group of
+inland seas is set to zero each timestep and the residual flux is
+distributed over the global ocean (ie. all ocean points where
+closea\_mask is zero).}
+
+\item {{\bfseries Fields called closea\_mask and closea\_mask\_rnf are
+included in the domain configuration file and ln\_closea=.true. in
+namelist namcfg.} This option works as for option 3, except that if
+the net surface flux over an inland sea is negative (net
+precipitation) it is put into the ocean at specified runoff points. A
+net positive surface flux (net evaporation) is still spread over the
+global ocean. The mapping from inland seas to runoff points is defined
+by the closea\_mask\_rnf field. Each mapping is defined by a positive
+integer value for the inland sea(s) and the corresponding runoff
+points. An example is given in
+\autoref{fig:MISC_closea_mask_example}. If no mapping is provided for a
+particular inland sea then the residual is spread over the global
+ocean.}
+
+\item {{\bfseries Fields called closea\_mask and closea\_mask\_emp are
+included in the domain configuration file and ln\_closea=.true. in
+namelist namcfg.} This option works the same as option 4 except that
+the nonzero net surface flux is sent to the ocean at the specified
+runoff points regardless of whether it is positive or negative. The
+mapping from inland seas to runoff points in this case is defined by
+the closea\_mask\_emp field.}
+\end{enumerate}
+
+There is a python routine to create the closea\_mask fields and append
+them to the domain configuration file in the utils/tools/DOMAINcfg directory.
+
+%% =================================================================================================
+\section{Sub-domain functionality}
+\label{sec:MISC_zoom}
+
+%% =================================================================================================
+\subsection{Simple subsetting of input files via NetCDF attributes}
+
+The extended grids for use with the under-shelf ice cavities will result in redundant rows
+around Antarctica if the ice cavities are not active.  A simple mechanism for subsetting
+input files associated with the extended domains has been implemented to avoid the need to
+maintain different sets of input fields for use with or without active ice cavities.  This
+subsetting operates for the j-direction only and works by optionally looking for and using
+a global file attribute (named: \np{open_ocean_jstart}{open\_ocean\_jstart}) to determine the starting j-row
+for input.  The use of this option is best explained with an example:
+\medskip
+
+\noindent Consider an ORCA1
+configuration using the extended grid domain configuration file: \ifile{eORCA1\_domcfg.nc}
+This file define a horizontal domain of 362x332.  The first row with
+open ocean wet points in the non-isf bathymetry for this set is row 42 (\fortran\ indexing)
+then the formally correct setting for \np{open_ocean_jstart}{open\_ocean\_jstart} is 41.  Using this value as
+the first row to be read will result in a 362x292 domain which is the same size as the
+original ORCA1 domain.  Thus the extended domain configuration file can be used with all
+the original input files for ORCA1 if the ice cavities are not active (\np{ln\_isfcav =
+.false.}).  Full instructions for achieving this are:
+
+\begin{itemize}
+\item Add the new attribute to any input files requiring a j-row offset, i.e:
+\begin{cmds}
+ncatted  -a open_ocean_jstart,global,a,d,41 eORCA1_domcfg.nc
+\end{cmds}
+
+\item Add the logical switch \np{ln_use_jattr}{ln\_use\_jattr} to \nam{cfg}{cfg} in the configuration
+namelist (if it is not already there) and set \forcode{.true.}
+\end{itemize}
+
+\noindent Note that with this option, the j-size of the global domain is (extended
+j-size minus \np{open_ocean_jstart}{open\_ocean\_jstart} + 1 ) and this must match the \texttt{jpjglo} value
+for the configuration. This means an alternative version of \ifile{eORCA1\_domcfg.nc} must
+be created for when \np{ln_use_jattr}{ln\_use\_jattr} is active. The \texttt{ncap2} tool provides a
+convenient way of achieving this:
+
+\begin{cmds}
+ncap2 -s 'jpjglo=292' eORCA1_domcfg.nc nORCA1_domcfg.nc
+\end{cmds}
+
+The domain configuration file is unique in this respect since it also contains the value of \jp{jpjglo}
+that is read and used by the model.
+Any other global, 2D and 3D, netcdf, input field can be prepared for use in a reduced domain by adding the
+\texttt{open\_ocean\_jstart} attribute to the file's global attributes.
+In particular this is true for any field that is read by \NEMO\ using the following optional argument to
+the appropriate call to \np{iom_get}{iom\_get}.
+
+\begin{forlines}
+lrowattr=ln_use_jattr
+\end{forlines}
+
+Currently, only the domain configuration variables make use of this optional argument so
+this facility is of little practical use except for tests where no other external input
+files are needed or you wish to use an extended domain configuration with inputs from
+earlier, non-extended configurations. Alternatively, it should be possible to exclude
+empty rows for extended domain, forced ocean runs using interpolation on the fly, by
+adding the optional argument to \texttt{iom\_get} calls for the weights and initial
+conditions. Experimenting with this remains an exercise for the user.
+
+%% =================================================================================================
+\section[Accuracy and reproducibility (\textit{lib\_fortran.F90})]{Accuracy and reproducibility (\protect\mdl{lib\_fortran})}
+\label{sec:MISC_fortran}
+
+%% =================================================================================================
+\subsection[Issues with intrinsinc SIGN function (\texttt{\textbf{key\_nosignedzero}})]{Issues with intrinsinc SIGN function (\protect\key{nosignedzero})}
+\label{subsec:MISC_sign}
+
+The SIGN(A, B) is the \fortran\ intrinsic function delivers the magnitude of A with the sign of B.
+For example, SIGN(-3.0,2.0) has the value 3.0.
+The problematic case is when the second argument is zero, because, on platforms that support IEEE arithmetic,
+zero is actually a signed number.
+There is a positive zero and a negative zero.
+
+In \fninety, the processor was required always to deliver a positive result for SIGN(A, B) if B was zero.
+Nevertheless, in \fninety, the processor is allowed to do the correct thing and deliver ABS(A) when
+B is a positive zero and -ABS(A) when B is a negative zero.
+This change in the specification becomes apparent only when B is of type real, and is zero,
+and the processor is capable of distinguishing between positive and negative zero,
+and B is negative real zero.
+Then SIGN delivers a negative result where, under \fninety\ rules, it used to return a positive result.
+This change may be especially sensitive for the ice model,
+so we overwrite the intrinsinc function with our own function simply performing :   \\
+\verb?   IF( B >= 0.e0 ) THEN   ;   SIGN(A,B) = ABS(A)  ?    \\
+\verb?   ELSE                   ;   SIGN(A,B) =-ABS(A)     ?  \\
+\verb?   ENDIF    ? \\
+This feature can be found in \mdl{lib\_fortran} module and is effective when \key{nosignedzero} is defined.
+We use a CPP key as the overwritting of a intrinsic function can present performance issues with
+some computers/compilers.
+
+%% =================================================================================================
+\subsection{MPP reproducibility}
+\label{subsec:MISC_glosum}
+
+The numerical reproducibility of simulations on distributed memory parallel computers is a critical issue.
+In particular, within \NEMO\ global summation of distributed arrays is most susceptible to rounding errors,
+and their propagation and accumulation cause uncertainty in final simulation reproducibility on
+different numbers of processors.
+To avoid so, based on \citet{he.ding_JS01} review of different technics,
+we use a so called self-compensated summation method.
+The idea is to estimate the roundoff error, store it in a buffer, and then add it back in the next addition.
+
+Suppose we need to calculate $b = a_1 + a_2 + a_3$.
+The following algorithm will allow to split the sum in two
+($sum_1 = a_{1} + a_{2}$ and $b = sum_2 = sum_1 + a_3$) with exactly the same rounding errors as
+the sum performed all at once.
+\begin{align*}
+	sum_1 \ \  &= a_1 + a_2 \\
+	error_1     &= a_2 + ( a_1 - sum_1 ) \\
+	sum_2 \ \  &= sum_1 + a_3 + error_1 \\
+	error_2     &= a_3 + error_1 + ( sum_1 - sum_2 ) \\
+	b \qquad \ &= sum_2 \\
+\end{align*}
+An example of this feature can be found in \mdl{lib\_fortran} module.
+It is systematicallt used in glob\_sum function (summation over the entire basin excluding duplicated rows and
+columns due to cyclic or north fold boundary condition as well as overlap MPP areas).
+The self-compensated summation method should be used in all summation in i- and/or j-direction.
+See \mdl{closea} module for an example.
+Note also that this implementation may be sensitive to the optimization level.
+
+%% =================================================================================================
+\subsection{MPP scalability}
+\label{subsec:MISC_mppsca}
+
+The default method of communicating values across the north-fold in distributed memory applications (\key{mpp\_mpi})
+uses a \textsc{MPI\_ALLGATHER} function to exchange values from each processing region in
+the northern row with every other processing region in the northern row.
+This enables a global width array containing the top 4 rows to be collated on every northern row processor and then
+folded with a simple algorithm.
+Although conceptually simple, this "All to All" communication will hamper performance scalability for
+large numbers of northern row processors.
+From version 3.4 onwards an alternative method is available which only performs direct "Peer to Peer" communications
+between each processor and its immediate "neighbours" across the fold line.
+This is achieved by using the default \textsc{MPI\_ALLGATHER} method during initialisation to
+help identify the "active" neighbours.
+Stored lists of these neighbours are then used in all subsequent north-fold exchanges to
+restrict exchanges to those between associated regions.
+The collated global width array for each region is thus only partially filled but is guaranteed to
+be set at all the locations actually required by each individual for the fold operation.
+This alternative method should give identical results to the default \textsc{ALLGATHER} method and
+is recommended for large values of \np{jpni}{jpni}.
+The new method is activated by setting \np{ln_nnogather}{ln\_nnogather} to be true (\nam{mpp}{mpp}).
+The reproducibility of results using the two methods should be confirmed for each new,
+non-reference configuration.
+
+%% =================================================================================================
+\section{Model optimisation, control print and benchmark}
+\label{sec:MISC_opt}
+
+\begin{listing}
+  \nlst{namctl}
+  \caption{\forcode{&namctl}}
+  \label{lst:namctl}
+\end{listing}
+
+Options are defined through the  \nam{ctl}{ctl} namelist variables.
+
+%% =================================================================================================
+\subsection{Vector optimisation}
+
+\key{vectopt\_loop} enables the internal loops to collapse.
+This is very a very efficient way to increase the length of vector calculations and thus
+to speed up the model on vector computers.
+
+% Add here also one word on NPROMA technique that has been found useless, since compiler have made significant progress during the last decade.
+
+% Add also one word on NEC specific optimisation (Novercheck option for example)
+
+%% =================================================================================================
+\subsection{Control print}
+
+The \np{ln_ctl}{ln\_ctl} switch was originally used as a debugging option in two modes:
+
+\begin{enumerate}
+\item {\np{ln_ctl}{ln\_ctl}: compute and print the trends averaged over the interior domain in all TRA, DYN, LDF and
+ZDF modules.
+This option is very helpful when diagnosing the origin of an undesired change in model results. }
+
+\item {also \np{ln_ctl}{ln\_ctl} but using the nictl and njctl namelist parameters to check the source of differences between
+mono and multi processor runs.}
+\end{enumerate}
+
+However, in recent versions it has also been used to force all processors to assume the
+reporting role. Thus when \np{ln_ctl}{ln\_ctl} is true all processors produce their own versions
+of files such as: ocean.output, layout.dat, etc.  All such files, beyond the the normal
+reporting processor (narea == 1), are named with a \_XXXX extension to their name, where
+XXXX is a 4-digit area number (with leading zeros, if required). Other reporting files
+such as run.stat (and its netCDF counterpart: run.stat.nc) and tracer.stat contain global
+information and are only ever produced by the reporting master (narea == 1). For version
+4.0 a start has been made to return \np{ln_ctl}{ln\_ctl} to its original function by introducing
+a new control structure which allows finer control over which files are produced. This
+feature is still evolving but it does already allow the user to: select individually the
+production of run.stat and tracer.stat files and to toggle the production of other files
+on processors other than the reporting master. These other reporters can be a simple
+subset of processors as defined by a minimum, maximum and incremental processor number.
+
+Note, that production of the run.stat and tracer.stat files require global communications.
+For run.stat, these are global min and max operations to find metrics such as the gloabl
+maximum velocity. For tracer.stat these are global sums of tracer fields. To improve model
+performance these operations are disabled by default and, where necessary, any use of the
+global values have been replaced with local calculations. For example, checks on the CFL
+criterion are now done on the local domain and only reported if a breach is detected.
+
+Experienced users may wish to still monitor this information as a check on model progress.
+If so, the best compromise will be to activate the files with:
+
+\begin{verbatim}
+     sn_cfctl%l_config = .TRUE.
+       sn_cfctl%l_runstat = .TRUE.
+       sn_cfctl%l_trcstat = .TRUE.
+\end{verbatim}
+
+and to use the new time increment setting to ensure the values are collected and reported
+at a suitably long interval. For example:
+
+\begin{verbatim}
+       sn_cfctl%ptimincr  = 25
+\end{verbatim}
+
+will carry out the global communications and write the information every 25 timesteps. This
+increment also applies to the time.step file which is otherwise updated every timestep.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics.tex	(revision 14097)
@@ -0,0 +1,1154 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Model Basics}
+\label{chap:MB}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabular}{l||l|l}
+    Release          & Author(s)                                   & Modifications       \\
+    \hline
+    {\em        4.0} & {\em Mike Bell                            } & {\em Review       } \\
+    {\em        3.6} & {\em Tim Graham and Gurvan Madec          } & {\em Updates      } \\
+    {\em $\leq$ 3.4} & {\em Gurvan Madec and S\'{e}bastien Masson} & {\em First version} \\
+  \end{tabular}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Primitive equations}
+\label{sec:MB_PE}
+
+%% =================================================================================================
+\subsection{Vector invariant formulation}
+\label{subsec:MB_PE_vector}
+
+The ocean is a fluid that can be described to a good approximation by the primitive equations,
+\ie\ the Navier-Stokes equations along with a nonlinear equation of state which
+couples the two active tracers (temperature and salinity) to the fluid velocity,
+plus the following additional assumptions made from scale considerations:
+
+\begin{labeling}{Neglect of additional Coriolis terms}
+\item [\textit{Spherical Earth approximation}] The geopotential surfaces are assumed to
+  be oblate spheroids that follow the Earth's bulge;
+  these spheroids are approximated by spheres with gravity locally vertical
+  (parallel to the Earth's radius) and independent of latitude
+  \citep[][section 2]{white.hoskins.ea_QJRMS05}.
+\item [\textit{Thin-shell approximation}] The ocean depth is neglected compared to the earth's radius
+\item [\textit{Turbulent closure hypothesis}] The turbulent fluxes
+  (which represent the effect of small scale processes on the large-scale)
+  are expressed in terms of large-scale features
+\item [\textit{Boussinesq hypothesis}] Density variations are neglected except in
+  their contribution to the buoyancy force
+  \begin{equation}
+    \label{eq:MB_PE_eos}
+    \rho = \rho \ (T,S,p)
+  \end{equation}
+\item [\textit{Hydrostatic hypothesis}] The vertical momentum equation is reduced to
+  a balance between the vertical pressure gradient and the buoyancy force
+  (this removes convective processes from the initial Navier-Stokes equations and so
+  convective processes must be parameterized instead)
+  \begin{equation}
+    \label{eq:MB_PE_hydrostatic}
+    \pd[p]{z} = - \rho \ g
+  \end{equation}
+\item [\textit{Incompressibility hypothesis}] The three dimensional divergence of
+  the velocity vector $\vect U$ is assumed to be zero.
+  \begin{equation}
+    \label{eq:MB_PE_continuity}
+    \nabla \cdot \vect U = 0
+  \end{equation}
+\item [\textit{Neglect of additional Coriolis terms}] The Coriolis terms that vary with
+  the cosine of latitude are neglected.
+  These terms may be non-negligible where the Brunt-V\"{a}is\"{a}l\"{a} frequency $N$ is small,
+  either in the deep ocean or in the sub-mesoscale motions of the mixed layer,
+  or near the equator \citep[][section 1]{white.hoskins.ea_QJRMS05}.
+  They can be consistently included as part of the ocean dynamics
+  \citep[][section 3(d)]{white.hoskins.ea_QJRMS05} and are retained in the MIT ocean model.
+\end{labeling}
+
+Because the gravitational force is so dominant in the equations of large-scale motions,
+it is useful to choose an orthogonal set of unit vectors $(i,j,k)$ linked to the Earth such that
+$k$ is the local upward vector and $(i,j)$ are two vectors orthogonal to $k$,
+\ie\ tangent to the geopotential surfaces.
+Let us define the following variables:
+$\vect U$ the vector velocity, $\vect U = \vect U_h + w \, \vect k$
+(the subscript $h$ denotes the local horizontal vector, \ie\ over the $(i,j)$ plane),
+$T$ the potential temperature, $S$ the salinity, $\rho$ the \textit{in situ} density.
+The vector invariant form of the primitive equations in the $(i,j,k)$ vector system provides
+the following equations:
+\begin{subequations}
+  \label{eq:MB_PE}
+  \begin{gather}
+    \shortintertext{$-$ the momentum balance}
+    \label{eq:MB_PE_dyn}
+    \pd[\vect U_h]{t} = - \lt[ (\nabla \times \vect U) \times \vect U + \frac{1}{2} \nabla \lt( \vect U^2 \rt) \rt]_h - f \; k \times \vect U_h - \frac{1}{\rho_o} \nabla_h p + \vect D^{\vect U} + \vect F^{\vect U}
+    \shortintertext{$-$ the heat and salt conservation equations}
+    \label{eq:MB_PE_tra_T}
+    \pd[T]{t} = - \nabla \cdot (T \ \vect U) + D^T + F^T \\
+    \label{eq:MB_PE_tra_S}
+    \pd[S]{t} = - \nabla \cdot (S \ \vect U) + D^S + F^S
+  \end{gather}
+\end{subequations}
+where $\nabla$ is the generalised derivative vector operator in $(i,j,k)$ directions, $t$ is the time,
+$z$ is the vertical coordinate, $\rho$ is the \textit{in situ} density given by the equation of state
+(\autoref{eq:MB_PE_eos}), $\rho_o$ is a reference density, $p$ the pressure,
+$f = 2 \vect \Omega \cdot k$ is the Coriolis acceleration
+(where $\vect \Omega$ is the Earth's angular velocity vector),
+and $g$ is the gravitational acceleration.
+$\vect D^{\vect U}$, $D^T$ and $D^S$ are the parameterisations of small-scale physics for momentum,
+temperature and salinity, and $\vect F^{\vect U}$, $F^T$ and $F^S$ surface forcing terms.
+Their nature and formulation are discussed in \autoref{sec:MB_zdf_ldf} and
+\autoref{subsec:MB_boundary_condition}.
+
+%% =================================================================================================
+\subsection{Boundary conditions}
+\label{subsec:MB_boundary_condition}
+
+An ocean is bounded by complex coastlines, bottom topography at its base and
+an air-sea or ice-sea interface at its top.
+These boundaries can be defined by two surfaces, $z = - H(i,j)$ and $z = \eta(i,j,k,t)$,
+where $H$ is the depth of the ocean bottom and $\eta$ is the height of the sea surface
+(discretisation can introduce additional artificial ``side-wall'' boundaries).
+Both $H$ and $\eta$ are referenced to a surface of constant geopotential
+(\ie\ a mean sea surface height) on which $z = 0$ (\autoref{fig:MB_ocean_bc}).
+Through these two boundaries, the ocean can exchange fluxes of heat, fresh water, salt,
+and momentum with the solid earth, the continental margins, the sea ice and the atmosphere.
+However, some of these fluxes are so weak that
+even on climatic time scales of thousands of years they can be neglected.
+In the following, we briefly review the fluxes exchanged at the interfaces between the ocean and
+the other components of the earth system.
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{MB_ocean_bc}
+  \caption[Ocean boundary conditions]{
+    The ocean is bounded by two surfaces, $z = - H(i,j)$ and $z = \eta(i,j,t)$,
+    where $H$ is the depth of the sea floor and $\eta$ the height of the sea surface.
+    Both $H$ and $\eta$ are referenced to $z = 0$.}
+  \label{fig:MB_ocean_bc}
+\end{figure}
+
+\begin{description}
+\item [Land - ocean] The major flux between continental margins and the ocean is a mass exchange of
+  fresh water through river runoff.
+  Such an exchange modifies the sea surface salinity especially in the vicinity of major river mouths.
+  It can be neglected for short range integrations but
+  has to be taken into account for long term integrations as
+  it influences the characteristics of water masses formed (especially at high latitudes).
+  It is required in order to close the water cycle of the climate system.
+  It is usually specified as a fresh water flux at the air-sea interface in
+  the vicinity of river mouths.
+\item [Solid earth - ocean] Heat and salt fluxes through the sea floor are small,
+  except in special areas of little extent.
+  They are usually neglected in the model \footnote{
+    In fact, it has been shown that the heat flux associated with the solid Earth cooling
+    (\ie\ the geothermal heating) is not negligible for
+    the thermohaline circulation of the world ocean (see \autoref{subsec:TRA_bbc}).
+  }.
+  The boundary condition is thus set to no flux of heat and salt across solid boundaries.
+  For momentum, the situation is different.
+  There is no flow across solid boundaries,
+  \ie\ the velocity normal to the ocean bottom and coastlines is zero
+  (in other words, the bottom velocity is parallel to solid boundaries).
+  This kinematic boundary condition can be expressed as:
+  \begin{equation}
+    \label{eq:MB_w_bbc}
+    w = - \vect U_h \cdot \nabla_h (H)
+  \end{equation}
+  In addition, the ocean exchanges momentum with the earth through frictional processes.
+  Such momentum transfer occurs at small scales in a boundary layer.
+  It must be parameterized in terms of turbulent fluxes using
+  bottom and/or lateral boundary conditions.
+  Its specification depends on the nature of the physical parameterisation used for
+  $\vect D^{\vect U}$ in \autoref{eq:MB_PE_dyn}.
+  It is discussed in \autoref{eq:MB_zdf}. % and Chap. III.6 to 9.
+\item [Atmosphere - ocean] The kinematic surface condition plus the mass flux of fresh water PE
+  (the precipitation minus evaporation budget) leads to:
+  \[
+    % \label{eq:MB_w_sbc}
+    w = \pd[\eta]{t} + \lt. \vect U_h \rt|_{z = \eta} \cdot \nabla_h (\eta) + P - E
+  \]
+  The dynamic boundary condition, neglecting the surface tension
+  (which removes capillary waves from the system) leads to
+  the continuity of pressure across the interface $z = \eta$.
+  The atmosphere and ocean also exchange horizontal momentum (wind stress), and heat.
+\item [Sea ice - ocean] The ocean and sea ice exchange heat, salt, fresh water and momentum.
+  The sea surface temperature is constrained to be at the freezing point at the interface.
+  Sea ice salinity is very low ($\sim4-6 \, psu$) compared to those of the ocean ($\sim34 \, psu$).
+  The cycle of freezing/melting is associated with fresh water and salt fluxes that
+  cannot be neglected.
+\end{description}
+
+%% =================================================================================================
+\section{Horizontal pressure gradient}
+\label{sec:MB_hor_pg}
+
+%% =================================================================================================
+\subsection{Pressure formulation}
+\label{subsec:MB_p_formulation}
+
+The total pressure at a given depth $z$ is composed of a surface pressure $p_s$ at
+a reference geopotential surface ($z = 0$) and a hydrostatic pressure $p_h$ such that:
+$p(i,j,k,t) = p_s(i,j,t) + p_h(i,j,k,t)$.
+The latter is computed by integrating (\autoref{eq:MB_PE_hydrostatic}),
+assuming that pressure in decibars can be approximated by depth in meters in (\autoref{eq:MB_PE_eos}).
+The hydrostatic pressure is then given by:
+\[
+  % \label{eq:MB_pressure}
+  p_h (i,j,z,t) = \int_{\varsigma = z}^{\varsigma = 0} g \; \rho (T,S,\varsigma) \; d \varsigma
+\]
+Two strategies can be considered for the surface pressure term:
+\begin{enumerate*}[label=(\textit{\alph*})]
+\item introduce of a new variable $\eta$, the free-surface elevation,
+for which a prognostic equation can be established and solved;
+\item assume that the ocean surface is a rigid lid,
+on which the pressure (or its horizontal gradient) can be diagnosed.
+\end{enumerate*}
+When the former strategy is used, one solution of the free-surface elevation consists of
+the excitation of external gravity waves.
+The flow is barotropic and the surface moves up and down with gravity as the restoring force.
+The phase speed of such waves is high (some hundreds of metres per second) so that
+the time step has to be very short when they are present in the model.
+The latter strategy filters out these waves since the rigid lid approximation implies $\eta = 0$,
+\ie\ the sea surface is the surface $z = 0$.
+This well known approximation increases the surface wave speed to infinity and
+modifies certain other longwave dynamics (\eg\ barotropic Rossby or planetary waves).
+The rigid-lid hypothesis is an obsolescent feature in modern OGCMs.
+It has been available until the release 3.1 of \NEMO,
+and it has been removed in release 3.2 and followings.
+Only the free surface formulation is now described in this document (see the next sub-section).
+
+%% =================================================================================================
+\subsection{Free surface formulation}
+\label{subsec:MB_free_surface}
+
+In the free surface formulation, a variable $\eta$, the sea-surface height,
+is introduced which describes the shape of the air-sea interface.
+This variable is solution of a prognostic equation which is established by
+forming the vertical average of the kinematic surface condition (\autoref{eq:MB_w_bbc}):
+\begin{equation}
+  \label{eq:MB_ssh}
+  \pd[\eta]{t} = - D + P - E \quad \text{where} \quad D = \nabla \cdot \lt[ (H + \eta) \; \overline{U}_h \, \rt]
+\end{equation}
+and using (\autoref{eq:MB_PE_hydrostatic}) the surface pressure is given by:
+$p_s = \rho \, g \, \eta$.
+
+Allowing the air-sea interface to move introduces
+the \textbf{E}xternal \textbf{G}ravity \textbf{W}aves (EGWs) as
+a class of solution of the primitive equations.
+These waves are barotropic (\ie\ nearly independent of depth) and their phase speed is quite high.
+Their time scale is short with respect to the other processes described by the primitive equations.
+
+Two choices can be made regarding the implementation of the free surface in the model,
+depending on the physical processes of interest.
+\begin{itemize}
+\item If one is interested in EGWs, in particular the tides and their interaction with
+  the baroclinic structure of the ocean (internal waves) possibly in shallow seas,
+  then a non linear free surface is the most appropriate.
+  This means that no approximation is made in \autoref{eq:MB_ssh} and that
+  the variation of the ocean volume is fully taken into account.
+  Note that in order to study the fast time scales associated with EGWs it is necessary to
+  minimize time filtering effects
+  (use an explicit time scheme with very small time step,
+  or a split-explicit scheme with reasonably small time step,
+  see \autoref{subsec:DYN_spg_exp} or \autoref{subsec:DYN_spg_ts}).
+\item If one is not interested in EGWs but rather sees them as high frequency noise,
+  it is possible to apply an explicit filter to slow down the fastest waves while
+  not altering the slow barotropic Rossby waves.
+  If further, an approximative conservation of heat and salt contents is sufficient for
+  the problem solved, then it is sufficient to solve a linearized version of \autoref{eq:MB_ssh},
+  which still allows to take into account freshwater fluxes applied at the ocean surface
+  \citep{roullet.madec_JGR00}.
+  Nevertheless, with the linearization, an exact conservation of heat and salt contents is lost.
+\end{itemize}
+The filtering of EGWs in models with a free surface is usually
+a matter of discretisation of the temporal derivatives,
+using a split-explicit method \citep{killworth.webb.ea_JPO91, zhang.endoh_JGR92} or
+the implicit scheme \citep{dukowicz.smith_JGR94} or the addition of a filtering force in
+the momentum equation \citep{roullet.madec_JGR00}.
+With the present release, \NEMO\ offers the choice between an explicit free surface
+(see \autoref{subsec:DYN_spg_exp}) or a split-explicit scheme strongly inspired the one proposed by
+\citet{shchepetkin.mcwilliams_OM05} (see \autoref{subsec:DYN_spg_ts}).
+
+%% =================================================================================================
+\section{Curvilinear \textit{z}-coordinate system}
+\label{sec:MB_zco}
+
+%% =================================================================================================
+\subsection{Tensorial formalism}
+\label{subsec:MB_tensorial}
+
+In many ocean circulation problems, the flow field has regions of enhanced dynamics
+(\ie\ surface layers, western boundary currents, equatorial currents, or ocean fronts).
+The representation of such dynamical processes can be improved by
+specifically increasing the model resolution in these regions.
+As well, it may be convenient to use a lateral boundary-following coordinate system to
+better represent coastal dynamics.
+Moreover, the common geographical coordinate system has a singular point at the North Pole that
+cannot be easily treated in a global model without filtering.
+A solution consists of introducing an appropriate coordinate transformation that
+shifts the singular point onto land \citep{madec.imbard_CD96, murray_JCP96}.
+As a consequence,
+it is important to solve the primitive equations in various curvilinear coordinate systems.
+An efficient way of introducing an appropriate coordinate transform can be found when
+using a tensorial formalism.
+This formalism is suited to any multidimensional curvilinear coordinate system.
+Ocean modellers mainly use three-dimensional orthogonal grids on the sphere
+(spherical earth approximation), with preservation of the local vertical.
+Here we give the simplified equations for this particular case.
+The general case is detailed by \citet{eiseman.stone_SR80} in
+their survey of the conservation laws of fluid dynamics.
+
+Let $(i,j,k)$ be a set of orthogonal curvilinear coordinates on
+the sphere associated with the positively oriented orthogonal set of unit vectors
+$(i,j,k)$ linked to the earth such that
+$k$ is the local upward vector and $(i,j)$ are two vectors orthogonal to $k$,
+\ie\ along geopotential surfaces (\autoref{fig:MB_referential}).
+Let $(\lambda,\varphi,z)$ be the geographical coordinate system in which a position is defined by
+the latitude $\varphi(i,j)$, the longitude $\lambda(i,j)$ and
+the distance from the centre of the earth $a + z(k)$ where $a$ is the earth's radius and
+$z$ the altitude above a reference sea level (\autoref{fig:MB_referential}).
+The local deformation of the curvilinear coordinate system is given by $e_1$, $e_2$ and $e_3$,
+the three scale factors:
+\begin{equation}
+  \label{eq:MB_scale_factors}
+    e_1 = (a + z) \lt[ \lt( \pd[\lambda]{i} \cos \varphi \rt)^2 + \lt( \pd[\varphi]{i} \rt)^2 \rt]^{1/2} \quad e_2 = (a + z) \lt[ \lt( \pd[\lambda]{j} \cos \varphi \rt)^2 + \lt( \pd[\varphi]{j} \rt)^2 \rt]^{1/2} \quad e_3 = \lt( \pd[z]{k} \rt)
+\end{equation}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.33\textwidth]{MB_earth_referential}
+  \caption[Geographical and curvilinear coordinate systems]{
+    the geographical coordinate system $(\lambda,\varphi,z)$ and the curvilinear
+    coordinate system $(i,j,k)$.}
+  \label{fig:MB_referential}
+\end{figure}
+
+Since the ocean depth is far smaller than the earth's radius, $a + z$, can be replaced by $a$ in
+(\autoref{eq:MB_scale_factors}) (thin-shell approximation).
+The resulting horizontal scale factors $e_1$, $e_2$  are independent of $k$ while
+the vertical scale factor is a single function of $k$ as $k$ is parallel to $z$.
+The scalar and vector operators that appear in the primitive equations
+(\autoref{eq:MB_PE_dyn} to \autoref{eq:MB_PE_eos}) can then be written in the tensorial form,
+invariant in any orthogonal horizontal curvilinear coordinate system transformation:
+\begin{subequations}
+  % \label{eq:MB_discrete_operators}
+  \begin{align}
+    \label{eq:MB_grad}
+    \nabla q &=   \frac{1}{e_1} \pd[q]{i} \; \vect i + \frac{1}{e_2} \pd[q]{j} \; \vect j + \frac{1}{e_3} \pd[q]{k} \; \vect k \\
+    \label{eq:MB_div}
+    \nabla \cdot \vect A &=   \frac{1}{e_1 \; e_2} \lt[ \pd[(e_2 \; a_1)]{\partial i} + \pd[(e_1 \; a_2)]{j} \rt] + \frac{1}{e_3} \lt[ \pd[a_3]{k} \rt] \\
+    \label{eq:MB_curl}
+      \nabla \times \vect{A} &=   \lt[ \frac{1}{e_2} \pd[a_3]{j} - \frac{1}{e_3} \pd[a_2]{k}   \rt] \vect i + \lt[ \frac{1}{e_3} \pd[a_1]{k} - \frac{1}{e_1} \pd[a_3]{i}   \rt] \vect j + \frac{1}{e_1 e_2} \lt[ \pd[(e_2 a_2)]{i} - \pd[(e_1 a_1)]{j} \rt] \vect k \\
+    \label{eq:MB_lap}
+    \Delta q &= \nabla \cdot (\nabla q) \\
+    \label{eq:MB_lap_vector}
+    \Delta \vect A &= \nabla (\nabla \cdot \vect A) - \nabla \times (\nabla \times \vect A)
+  \end{align}
+\end{subequations}
+where $q$ is a scalar quantity and
+$\vect A = (a_1,a_2,a_3)$ a vector in the $(i,j,k)$ coordinates system.
+
+%% =================================================================================================
+\subsection{Continuous model equations}
+\label{subsec:MB_zco_Eq}
+
+In order to express the Primitive Equations in tensorial formalism,
+it is necessary to compute the horizontal component of the non-linear and viscous terms of
+the equation using \autoref{eq:MB_grad}) to \autoref{eq:MB_lap_vector}.
+Let us set $\vect U = (u,v,w) = \vect U_h + w \; \vect k $,
+the velocity in the $(i,j,k)$ coordinates system,
+and define the relative vorticity $\zeta$ and the divergence of the horizontal velocity field $\chi$,
+by:
+\begin{gather}
+  \label{eq:MB_curl_Uh}
+  \zeta = \frac{1}{e_1 e_2} \lt[ \pd[(e_2 \, v)]{i} - \pd[(e_1 \, u)]{j} \rt] \\
+  \label{eq:MB_div_Uh}
+  \chi  = \frac{1}{e_1 e_2} \lt[ \pd[(e_2 \, u)]{i} + \pd[(e_1 \, v)]{j} \rt]
+\end{gather}
+
+Using again the fact that the horizontal scale factors $e_1$ and $e_2$ are independent of $k$ and that
+$e_3$  is a function of the single variable $k$,
+$NLT$ the nonlinear term of \autoref{eq:MB_PE_dyn} can be transformed as follows:
+\begin{align*}
+  NLT &= \lt[ (\nabla \times {\vect U}) \times {\vect U} + \frac{1}{2} \nabla \lt( {\vect U}^2 \rt) \rt]_h \\
+      &= \lt(
+        \begin{array}{*{20}c}
+          \lt[ \frac{1}{e_3} \pd[u]{k} - \frac{1}{e_1} \pd[w]{i} \rt] w - \zeta \; v   \\
+          \zeta \; u - \lt[ \frac{1}{e_2} \pd[w]{j} - \frac{1}{e_3} \pd[v]{k} \rt] \ w
+        \end{array}
+  \rt)
+  + \frac{1}{2} \lt(
+  \begin{array}{*{20}c}
+    \frac{1}{e_1} \pd[(u^2 + v^2 + w^2)]{i} \\
+    \frac{1}{e_2} \pd[(u^2 + v^2 + w^2)]{j}
+  \end{array}
+  \rt) \\
+      &= \lt(
+        \begin{array}{*{20}c}
+          -\zeta \; v \\
+          \zeta \; u
+        \end{array}
+  \rt)
+  + \frac{1}{2} \lt(
+  \begin{array}{*{20}c}
+    \frac{1}{e_1} \pd[(u^2 + v^2)]{i} \\
+    \frac{1}{e_2} \pd[(u^2 + v^2)]{j}
+  \end{array}
+  \rt)
+  + \frac{1}{e_3} \lt(
+  \begin{array}{*{20}c}
+    w \; \pd[u]{k} \\
+    w \; \pd[v]{k}
+  \end{array}
+  \rt)
+  - \lt(
+  \begin{array}{*{20}c}
+    \frac{w}{e_1} \pd[w]{i} - \frac{1}{2 e_1} \pd[w^2]{i} \\
+    \frac{w}{e_2} \pd[w]{j} - \frac{1}{2 e_2} \pd[w^2]{j}
+  \end{array}
+  \rt)
+\end{align*}
+The last term of the right hand side is obviously zero,
+and thus the \textbf{N}on\textbf{L}inear \textbf{T}erm ($NLT$) of \autoref{eq:MB_PE_dyn} is written in
+the $(i,j,k)$ coordinate system:
+\begin{equation}
+  \label{eq:MB_vector_form}
+  NLT = \zeta \; \vect k \times \vect U_h + \frac{1}{2} \nabla_h \lt( \vect U_h^2 \rt) + \frac{1}{e_3} w \pd[\vect U_h]{k}
+\end{equation}
+
+This is the so-called \textit{vector invariant form} of the momentum advection term.
+For some purposes, it can be advantageous to write this term in the so-called flux form,
+\ie\ to write it as the divergence of fluxes.
+For example,
+the first component of \autoref{eq:MB_vector_form} (the $i$-component) is transformed as follows:
+\begin{alignat*}{3}
+  &NLT_i &= &- \zeta \; v + \frac{1}{2 \; e_1} \pd[ (u^2 + v^2) ]{i} + \frac{1}{e_3} w \ \pd[u]{k} \\
+  &      &= &\frac{1}{e_1 \; e_2} \lt( -v \pd[(e_2 \, v)]{i} + v \pd[(e_1 \, u)]{j} \rt) + \frac{1}{e_1 e_2} \lt( e_2 \; u \pd[u]{i} + e_2 \; v \pd[v]{i} \rt) + \frac{1}{e_3} \lt( w \; \pd[u]{k} \rt) \\
+  &      &= &\frac{1}{e_1 \; e_2} \lt[ - \lt( v^2 \pd[e_2]{i} + e_2 \, v \pd[v]{i} \rt) + \lt( \pd[ \lt( e_1 \, u \, v \rt)]{j} - e_1 \, u \pd[v]{j} \rt) \rt. \lt. + \lt( \pd[ \lt( e_2 \, u \, u \rt)]{i} - u \pd[ \lt( e_2 u \rt)]{i} \rt) + e_2 v \pd[v]{i} \rt] \\
+  &      & &+ \frac{1}{e_3} \lt( \pd[(w \, u)]{k} - u \pd[w]{k} \rt) \\
+  &      &= &\frac{1}{e_1 \; e_2} \lt( \pd[(e_2 \, u \, u)]{i} + \pd[(e_1 \, u \, v)]{j} \rt) + \frac{1}{e_3} \pd[(w \, u)]{k} + \frac{1}{e_1 e_2} \lt[ - u \lt( \pd[(e_1 v)]{j} - v \, \pd[e_1]{j} \rt) - u \pd[(e_2 u)]{i} \rt] - \frac{1}{e_3} \pd[w]{k} u \\
+  &      & &+ \frac{1}{e_1 e_2} \lt( - v^2 \pd[e_2]{i} \rt) \\
+  &      &= &\nabla \cdot (\vect U \, u) - (\nabla \cdot \vect U) \ u + \frac{1}{e_1 e_2} \lt( -v^2 \pd[e_2]{i} + u v \, \pd[e_1]{j} \rt) \\
+  \shortintertext{as $\nabla \cdot {\vect U} \; = 0$ (incompressibility) it becomes:}
+  &      &= &\, \nabla \cdot (\vect U \, u) + \frac{1}{e_1 e_2} \lt( v \; \pd[e_2]{i} - u \; \pd[e_1]{j} \rt) (-v)
+\end{alignat*}
+
+The flux form of the momentum advection term is therefore given by:
+\begin{equation}
+  \label{eq:MB_flux_form}
+  NLT = \nabla \cdot \lt(
+  \begin{array}{*{20}c}
+    \vect U \, u \\
+    \vect U \, v
+  \end{array}
+  \rt)
+  + \frac{1}{e_1 e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt) \vect k \times \vect U_h
+\end{equation}
+
+The flux form has two terms,
+the first one is expressed as the divergence of momentum fluxes
+(hence the flux form name given to this formulation) and
+the second one is due to the curvilinear nature of the coordinate system used.
+The latter is called the \textit{metric} term and can be viewed as
+a modification of the Coriolis parameter:
+\[
+  % \label{eq:MB_cor+metric}
+  f \to f + \frac{1}{e_1 e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt)
+\]
+
+Note that in the case of geographical coordinate,
+\ie\ when $(i,j) \to (\lambda,\varphi)$ and $(e_1,e_2) \to (a \, \cos \varphi,a)$,
+we recover the commonly used modification of the Coriolis parameter $f \to f + (u / a) \tan \varphi$.
+
+To sum up, the curvilinear $z$-coordinate equations solved by the ocean model can be written in
+the following tensorial formalism:
+
+\begin{description}
+\item [Vector invariant form of the momentum equations]
+  \begin{equation}
+    \label{eq:MB_dyn_vect}
+    \begin{gathered}
+    % \label{eq:MB_dyn_vect_u}
+      \pd[u]{t} = + (\zeta + f) \, v - \frac{1}{2 e_1} \pd[]{i} (u^2 + v^2) - \frac{1}{e_3} w \pd[u]{k} - \frac{1}{e_1} \pd[]{i} \lt( \frac{p_s + p_h}{\rho_o} \rt) + D_u^{\vect U} + F_u^{\vect U} \\
+      \pd[v]{t} = - (\zeta + f) \, u - \frac{1}{2 e_2} \pd[]{j} (u^2 + v^2) - \frac{1}{e_3} w \pd[v]{k} - \frac{1}{e_2} \pd[]{j} \lt( \frac{p_s + p_h}{\rho_o} \rt) + D_v^{\vect U} + F_v^{\vect U}
+    \end{gathered}
+  \end{equation}
+\item [Flux form of the momentum equations]
+  % \label{eq:MB_dyn_flux}
+  \begin{alignat*}{2}
+    % \label{eq:MB_dyn_flux_u}
+    \pd[u]{t} = &+ \lt[ f + \frac{1}{e_1 \; e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt) \rt] \, v - \frac{1}{e_1 \; e_2} \lt( \pd[(e_2 \, u \, u)]{i} + \pd[(e_1 \, v \, u)]{j} \rt) - \frac{1}{e_3} \pd[(w \, u)]{k} \\
+    &- \frac{1}{e_1} \pd[]{i} \lt( \frac{p_s + p_h}{\rho_o} \rt) + D_u^{\vect U} + F_u^{\vect U}
+  \end{alignat*}
+  \begin{alignat*}{2}
+    % \label{eq:MB_dyn_flux_v}
+    \pd[v]{t} = &- \lt[ f + \frac{1}{e_1 \; e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt) \rt] \, u - \frac{1}{e_1 \; e_2} \lt( \pd[(e_2 \, u \, v)]{i} + \pd[(e_1 \, v \, v)]{j} \rt) - \frac{1}{e_3} \pd[(w \, v)]{k} \\
+    &- \frac{1}{e_2} \pd[]{j} \lt( \frac{p_s + p_h}{\rho_o} \rt) + D_v^{\vect U} + F_v^{\vect U}
+  \end{alignat*}
+  where $\zeta$, the relative vorticity, is given by \autoref{eq:MB_curl_Uh} and
+  $p_s$, the surface pressure, is given by:
+  \[
+  % \label{eq:MB_spg}
+    p_s = \rho \,g \, \eta
+  \]
+  and $\eta$ is the solution of \autoref{eq:MB_ssh}.
+
+  The vertical velocity and the hydrostatic pressure are diagnosed from the following equations:
+  \[
+  % \label{eq:MB_w_diag}
+    \pd[w]{k} = - \chi \; e_3 \qquad
+  % \label{eq:MB_hp_diag}
+    \pd[p_h]{k} = - \rho \; g \; e_3
+  \]
+  where the divergence of the horizontal velocity, $\chi$ is given by \autoref{eq:MB_div_Uh}.
+\item [Tracer equations]
+  \begin{gather*}
+    \pd[T]{t} = - \frac{1}{e_1 e_2} \lt[ \pd[(e_2 T \, u)]{i} + \pd[(e_1 T \, v)]{j} \rt] - \frac{1}{e_3} \pd[(T \, w)]{k} + D^T + F^T \\
+    \pd[S]{t} = - \frac{1}{e_1 e_2} \lt[ \pd[(e_2 S \, u)]{i} + \pd[(e_1 S \, v)]{j} \rt] - \frac{1}{e_3} \pd[(S \, w)]{k} + D^S + F^S \\
+    \rho = \rho \big( T,S,z(k) \big)
+  \end{gather*}
+\end{description}
+
+The expression of $\vect D^{U}$, $D^{S}$ and $D^{T}$ depends on
+the subgrid scale parameterisation used.
+It will be defined in \autoref{eq:MB_zdf}.
+The nature and formulation of $\vect F^{\vect U}$, $F^T$ and $F^S$, the surface forcing terms,
+are discussed in \autoref{chap:SBC}.
+
+%% =================================================================================================
+\section{Curvilinear generalised vertical coordinate system}
+\label{sec:MB_gco}
+
+The ocean domain presents a huge diversity of situation in the vertical.
+First the ocean surface is a time dependent surface (moving surface).
+Second the ocean floor depends on the geographical position,
+varying from more than 6,000 meters in abyssal trenches to zero at the coast.
+Last but not least, the ocean stratification exerts a strong barrier to vertical motions and mixing.
+Therefore, in order to represent the ocean with respect to the first point
+a space and time dependent vertical coordinate that follows the variation of the sea surface height
+\eg\ an \zstar-coordinate;
+for the second point,
+a space variation to fit the change of bottom topography
+\eg\ a terrain-following or $\sigma$-coordinate;
+and for the third point,
+one will be tempted to use a space and time dependent coordinate that follows the isopycnal surfaces,
+\eg\ an isopycnic coordinate.
+
+In order to satisfy two or more constraints one can even be tempted to mixed these coordinate systems,
+as in HYCOM (mixture of $z$-coordinate at the surface, isopycnic coordinate in the ocean interior and
+$\sigma$ at the ocean bottom) \citep{chassignet.smith.ea_JPO03} or
+OPA (mixture of $z$-coordinate in vicinity the surface and steep topography areas and
+$\sigma$-coordinate elsewhere) \citep{madec.delecluse.ea_JPO96} among others.
+
+In fact one is totally free to choose any space and time vertical coordinate by
+introducing an arbitrary vertical coordinate :
+\begin{equation}
+  \label{eq:MB_s}
+  s = s(i,j,k,t)
+\end{equation}
+with the restriction that the above equation gives a single-valued monotonic relationship between
+$s$ and $k$, when $i$, $j$ and $t$ are held fixed.
+\autoref{eq:MB_s} is a transformation from
+the $(i,j,k,t)$ coordinate system with independent variables into
+the $(i,j,s,t)$ generalised coordinate system with $s$ depending on the other three variables through
+\autoref{eq:MB_s}.
+This so-called \textit{generalised vertical coordinate} \citep{kasahara_MWR74} is in fact
+an \textbf{A}rbitrary \textbf{L}agrangian--\textbf{E}ulerian (ALE) coordinate.
+Indeed, one has a great deal of freedom in the choice of expression for $s$.
+The choice determines which part of the vertical velocity (defined from a fixed referential)
+will cross the levels (Eulerian part) and which part will be used to move them (Lagrangian part).
+The coordinate is also sometimes referenced as an adaptive coordinate
+\citep{hofmeister.burchard.ea_OM10}, since the coordinate system is adapted in
+the course of the simulation.
+Its most often used implementation is via an ALE algorithm,
+in which a pure lagrangian step is followed by regridding and remapping steps,
+the latter step implicitly embedding the vertical advection
+\citep{hirt.amsden.ea_JCP74, chassignet.smith.ea_JPO03, white.adcroft.ea_JCP09}.
+Here we follow the \citep{kasahara_MWR74} strategy:
+a regridding step (an update of the vertical coordinate) followed by an Eulerian step with
+an explicit computation of vertical advection relative to the moving s-surfaces.
+
+\cmtgm{A key point here is that the $s$-coordinate depends on $(i,j)$
+  ==> horizontal pressure gradient...}
+The generalized vertical coordinates used in ocean modelling are not orthogonal,
+which contrasts with many other applications in mathematical physics.
+Hence, it is useful to keep in mind the following properties that may seem odd on initial encounter.
+
+The horizontal velocity in ocean models measures motions in the horizontal plane,
+perpendicular to the local gravitational field.
+That is, horizontal velocity is mathematically the same regardless of the vertical coordinate,
+be it geopotential, isopycnal, pressure, or terrain following.
+The key motivation for maintaining the same horizontal velocity component is that
+the hydrostatic and geostrophic balances are dominant in the large-scale ocean.
+Use of an alternative quasi -horizontal velocity,
+for example one oriented parallel to the generalized surface,
+would lead to unacceptable numerical errors.
+Correspondingly, the vertical direction is anti -parallel to the gravitational force in
+all of the coordinate systems.
+We do not choose the alternative of a quasi -vertical direction oriented normal to
+the surface of a constant generalized vertical coordinate.
+
+It is the method used to measure transport across the generalized vertical coordinate surfaces which
+differs between the vertical coordinate choices.
+That is,
+computation of the dia-surface velocity component represents the fundamental distinction between
+the various coordinates.
+In some models, such as geopotential, pressure, and terrain following,
+this transport is typically diagnosed from volume or mass conservation.
+In other models, such as isopycnal layered models,
+this transport is prescribed based on assumptions about the physical processes producing
+a flux across the layer interfaces.
+
+In this section we first establish the PE in the generalised vertical $s$-coordinate,
+then we discuss the particular cases available in \NEMO, namely $z$, \zstar, $s$, and \ztilde.
+%}
+
+%% =================================================================================================
+\subsection{\textit{S}-coordinate formulation}
+
+Starting from the set of equations established in \autoref{sec:MB_zco} for
+the special case $k = z$ and thus $e_3 = 1$,
+we introduce an arbitrary vertical coordinate $s = s(i,j,k,t)$,
+which includes $z$-, \zstar- and $\sigma$-coordinates as special cases
+($s = z$, $s = \zstar$, and $s = \sigma = z / H$ or $ = z / \lt( H + \eta \rt)$, resp.).
+A formal derivation of the transformed equations is given in \autoref{apdx:SCOORD}.
+Let us define the vertical scale factor by $e_3 = \partial_s z$
+($e_3$ is now a function of $(i,j,k,t)$ ),
+and the slopes in the $(i,j)$ directions between $s$- and $z$-surfaces by:
+\begin{equation}
+  \label{eq:MB_sco_slope}
+  \sigma_1 = \frac{1}{e_1} \; \lt. \pd[z]{i} \rt|_s \quad \text{and} \quad
+  \sigma_2 = \frac{1}{e_2} \; \lt. \pd[z]{j} \rt|_s
+\end{equation}
+We also introduce $\omega$, a dia-surface velocity component,
+defined as the velocity relative to the moving $s$-surfaces and normal to them:
+\[
+  % \label{eq:MB_sco_w}
+  \omega = w -  \, \lt. \pd[z]{t} \rt|_s - \sigma_1 \, u - \sigma_2 \, v
+\]
+
+The equations solved by the ocean model \autoref{eq:MB_PE} in $s$-coordinate can be written as follows
+(see \autoref{sec:SCOORD_momentum}):
+
+\begin{description}
+\item [Vector invariant form of the momentum equation]
+  \begin{gather*}
+    % \label{eq:MB_sco_u_vector}
+    \pd[u]{t} = + (\zeta + f) \, v - \frac{1}{2 \, e_1} \pd[]{i} (u^2 + v^2) - \frac{1}{e_3} \omega \pd[u]{k} - \frac{1}{e_1} \pd[]{i} \lt( \frac{p_s + p_h}{\rho_o} \rt) - g \frac{\rho}{\rho_o} \sigma_1 + D_u^{\vect U} + F_u^{\vect U} \\
+    % \label{eq:MB_sco_v_vector}
+    \pd[v]{t} = - (\zeta + f) \, u - \frac{1}{2 \, e_2} \pd[]{j} (u^2 + v^2) - \frac{1}{e_3} \omega \pd[v]{k} - \frac{1}{e_2} \pd[]{j} \lt( \frac{p_s + p_h}{\rho_o} \rt) - g \frac{\rho}{\rho_o} \sigma_2 + D_v^{\vect U} + F_v^{\vect U}
+  \end{gather*}
+\item [Flux form of the momentum equation]
+  \begin{alignat*}{2}
+    % \label{eq:MB_sco_u_flux}
+    \frac{1}{e_3} \pd[(e_3 \, u)]{t} = &+ \lt[ f + \frac{1}{e_1 \; e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt) \rt] \, v - \frac{1}{e_1 \; e_2 \; e_3} \lt( \pd[(e_2 \, e_3 \, u \, u)]{i} + \pd[(e_1 \, e_3 \, v \, u)]{j} \rt) - \frac{1}{e_3} \pd[(\omega \, u)]{k} \\
+    &- \frac{1}{e_1} \pd[]{i} \lt( \frac{p_s + p_h}{\rho_o} \rt) - g \frac{\rho}{\rho_o} \sigma_1 + D_u^{\vect U} + F_u^{\vect U}
+  \end{alignat*}
+  \begin{alignat*}{2}
+  % \label{eq:MB_sco_v_flux}
+    \frac{1}{e_3} \pd[(e_3 \, v)]{t} = &- \lt[ f + \frac{1}{e_1 \; e_2} \lt( v \pd[e_2]{i} - u \pd[e_1]{j} \rt) \rt] \, u - \frac{1}{e_1 \; e_2 \; e_3} \lt( \pd[( e_2 \; e_3 \, u \, v)]{i} + \pd[(e_1 \; e_3 \, v \, v)]{j} \rt) - \frac{1}{e_3} \pd[(\omega \, v)]{k} \\
+    &- \frac{1}{e_2} \pd[]{j} \lt( \frac{p_s + p_h}{\rho_o} \rt) - g \frac{\rho}{\rho_o}\sigma_2 + D_v^{\vect U} + F_v^{\vect U}
+  \end{alignat*}
+  where the relative vorticity, $\zeta$, the surface pressure gradient,
+  and the hydrostatic pressure have the same expressions as in $z$-coordinates although
+  they do not represent exactly the same quantities.
+  $\omega$ is provided by the continuity equation (see \autoref{apdx:SCOORD}):
+  \[
+  % \label{eq:MB_sco_continuity}
+    \pd[e_3]{t} + e_3 \; \chi + \pd[\omega]{s} = 0 \quad \text{with} \quad
+    \chi = \frac{1}{e_1 e_2 e_3} \lt( \pd[(e_2 e_3 \, u)]{i} + \pd[(e_1 e_3 \, v)]{j} \rt)
+  \]
+\item [Tracer equations]
+  \begin{gather*}
+    % \label{eq:MB_sco_t}
+    \frac{1}{e_3} \pd[(e_3 \, T)]{t} = - \frac{1}{e_1 e_2 e_3} \lt(   \pd[(e_2 e_3 \, u \, T)]{i} + \pd[(e_1 e_3 \, v \, T)]{j} \rt) - \frac{1}{e_3} \pd[(T \, \omega)]{k} + D^T + F^S \\
+    % \label{eq:MB_sco_s}
+    \frac{1}{e_3} \pd[(e_3 \, S)]{t} = - \frac{1}{e_1 e_2 e_3} \lt(   \pd[(e_2 e_3 \, u \, S)]{i} + \pd[(e_1 e_3 \, v \, S)]{j} \rt) - \frac{1}{e_3} \pd[(S \, \omega)]{k} + D^S + F^S
+  \end{gather*}
+\end{description}
+The equation of state has the same expression as in $z$-coordinate,
+and similar expressions are used for mixing and forcing terms.
+
+\cmtgm{
+  \colorbox{yellow}{ to be updated $= = >$}
+  Add a few works on z and zps and s and underlies the differences between all of them
+  \colorbox{yellow}{$< = =$ end update}
+}
+
+%% =================================================================================================
+\subsection{Curvilinear \zstar-coordinate system}
+\label{subsec:MB_zco_star}
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{MB_z_zstar}
+  \caption[Curvilinear z-coordinate systems (\{non-\}linear free-surface cases and re-scaled \zstar)]{
+    \begin{enumerate*}[label=(\textit{\alph*})]
+    \item $z$-coordinate in linear free-surface case;
+    \item $z$-coordinate in non-linear free surface case;
+    \item re-scaled height coordinate
+      (become popular as the \zstar-coordinate \citep{adcroft.campin_OM04}).
+    \end{enumerate*}
+  }
+  \label{fig:MB_z_zstar}
+\end{figure}
+
+In this case, the free surface equation is nonlinear,
+and the variations of volume are fully taken into account.
+These coordinates systems is presented in a report \citep{levier.treguier.ea_rpt07} available on
+the \NEMO\ web site.
+
+The \zstar\ coordinate approach is an unapproximated, non-linear free surface implementation which
+allows one to deal with large amplitude free-surface variations relative to the vertical resolution
+\citep{adcroft.campin_OM04}.
+In the \zstar\ formulation, the variation of the column thickness due to sea-surface undulations is
+not concentrated in the surface level, as in the $z$-coordinate formulation,
+but is equally distributed over the full water column.
+Thus vertical levels naturally follow sea-surface variations, with a linear attenuation with depth,
+as illustrated by \autoref{fig:MB_z_zstar}.
+Note that with a flat bottom, such as in \autoref{fig:MB_z_zstar},
+the bottom-following $z$ coordinate and \zstar\ are equivalent.
+The definition and modified oceanic equations for the rescaled vertical coordinate \zstar,
+including the treatment of fresh-water flux at the surface, are detailed in Adcroft and Campin (2004).
+The major points are summarized here.
+The position (\zstar) and vertical discretization ($\delta \zstar$) are expressed as:
+\[
+  % \label{eq:MB_z-star}
+  H + \zstar = (H + z)  / r \quad \text{and}  \quad \delta \zstar = \delta z / r \quad \text{with} \quad r = \frac{H + \eta}{H}
+\]
+Simple re-organisation of the above expressions gives
+\[
+  % \label{eq:MB_zstar_2}
+  \zstar = H \lt( \frac{z - \eta}{H + \eta} \rt)
+\]
+Since the vertical displacement of the free surface is incorporated in the vertical coordinate \zstar,
+the upper and lower boundaries are at fixed \zstar\ position,
+$\zstar = 0$ and $\zstar = -H$ respectively.
+Also the divergence of the flow field is no longer zero as shown by the continuity equation:
+\[
+  \pd[r]{t} = \nabla_{\zstar} \cdot \lt( r \; \vect U_h \rt) + \pd[r \; w^*]{\zstar} = 0
+\]
+This \zstar\ coordinate is closely related to the $\eta$ coordinate used in many atmospheric models
+(see Black (1994) for a review of $\eta$ coordinate atmospheric models).
+It was originally used in ocean models by Stacey et al. (1995) for studies of tides next to shelves,
+and it has been recently promoted by Adcroft and Campin (2004) for global climate modelling.
+
+The surfaces of constant \zstar\ are quasi-horizontal.
+Indeed, the \zstar\ coordinate reduces to $z$ when $\eta$ is zero.
+In general, when noting the large differences between
+undulations of the bottom topography versus undulations in the surface height,
+it is clear that surfaces constant \zstar\ are very similar to the depth surfaces.
+These properties greatly reduce difficulties of computing the horizontal pressure gradient relative to
+terrain following sigma models discussed in \autoref{subsec:MB_sco}.
+Additionally, since $\zstar = z$ when $\eta = 0$,
+no flow is spontaneously generated in an unforced ocean starting from rest,
+regardless the bottom topography.
+This behaviour is in contrast to the case with ``s''-models,
+where pressure gradient errors in the presence of nontrivial topographic variations can generate
+nontrivial spontaneous flow from a resting state,
+depending on the sophistication of the pressure gradient solver.
+The quasi-horizontal nature of the coordinate surfaces also facilitates the implementation of
+neutral physics parameterizations in \zstar\ models using the same techniques as in $z$-models
+(see Chapters 13-16 of \cite{griffies_bk04}) for a discussion of neutral physics in $z$-models,
+as well as \autoref{sec:LDF_slp} in this document for treatment in \NEMO).
+
+The range over which \zstar\ varies is time independent $-H \leq \zstar \leq 0$.
+Hence, all cells remain nonvanishing, so long as the surface height maintains $\eta > -H$.
+This is a minor constraint relative to that encountered on the surface height when
+using $s = z$ or $s = z - \eta$.
+
+Because \zstar\ has a time independent range, all grid cells have static increments ds,
+and the sum of the vertical increments yields the time independent ocean depth. %k ds = H.
+The \zstar\ coordinate is therefore invisible to undulations of the free surface,
+since it moves along with the free surface.
+This property means that no spurious vertical transport is induced across
+surfaces of constant \zstar\  by the motion of external gravity waves.
+Such spurious transport can be a problem in z-models, especially those with tidal forcing.
+Quite generally,
+the time independent range for the \zstar\ coordinate is a very convenient property that
+allows for a nearly arbitrary vertical resolution even in
+the presence of large amplitude fluctuations of the surface height, again so long as $\eta > -H$.
+%end MOM doc %%%
+
+%% =================================================================================================
+\subsection{Curvilinear terrain-following \textit{s}--coordinate}
+\label{subsec:MB_sco}
+
+Several important aspects of the ocean circulation are influenced by bottom topography.
+Of course, the most important is that bottom topography determines deep ocean sub-basins, barriers,
+sills and channels that strongly constrain the path of water masses, but more subtle effects exist.
+For example,
+the topographic $\beta$-effect is usually larger than the planetary one along continental slopes.
+Topographic Rossby waves can be excited and can interact with the mean current.
+In the $z$-coordinate system presented in the previous section (\autoref{sec:MB_zco}),
+$z$-surfaces are geopotential surfaces.
+The bottom topography is discretised by steps.
+This often leads to a misrepresentation of a gradually sloping bottom and to
+large localized depth gradients associated with large localized vertical velocities.
+The response to such a velocity field often leads to numerical dispersion effects.
+One solution to strongly reduce this error is to use a partial step representation of
+bottom topography instead of a full step one \cite{pacanowski.gnanadesikan_MWR98}.
+Another solution is to introduce a terrain-following coordinate system (hereafter $s$-coordinate).
+
+The $s$-coordinate avoids the discretisation error in the depth field since
+the layers of computation are gradually adjusted with depth to the ocean bottom.
+Relatively small topographic features as well as
+gentle, large-scale slopes of the sea floor in the deep ocean,
+which would be ignored in typical $z$-model applications with
+the largest grid spacing at greatest depths,
+can easily be represented (with relatively low vertical resolution).
+A terrain-following model (hereafter $s$-model) also facilitates
+the modelling of the boundary layer flows over a large depth range,
+which in the framework of the $z$-model would require high vertical resolution over
+the whole depth range.
+Moreover,
+with a $s$-coordinate it is possible, at least in principle, to have the bottom and the sea surface as
+the only boundaries of the domain (no more lateral boundary condition to specify).
+Nevertheless, a $s$-coordinate also has its drawbacks.
+Perfectly adapted to a homogeneous ocean,
+it has strong limitations as soon as stratification is introduced.
+The main two problems come from the truncation error in the horizontal pressure gradient and
+a possibly increased diapycnal diffusion.
+The horizontal pressure force in $s$-coordinate consists of two terms (see \autoref{apdx:SCOORD}),
+\begin{equation}
+  \label{eq:MB_p_sco}
+  \nabla p |_z = \nabla p |_s - \frac{1}{e_3} \pd[p]{s} \nabla z |_s
+\end{equation}
+
+The second term in \autoref{eq:MB_p_sco} depends on the tilt of the coordinate surface and
+leads to a truncation error that is not present in a $z$-model.
+In the special case of a $\sigma$-coordinate
+(i.e. a depth-normalised coordinate system $\sigma = z/H$),
+\citet{haney_JPO91} and \citet{beckmann.haidvogel_JPO93} have given estimates of
+the magnitude of this truncation error.
+It depends on topographic slope, stratification, horizontal and vertical resolution,
+the equation of state, and the finite difference scheme.
+This error limits the possible topographic slopes that a model can handle at
+a given horizontal and vertical resolution.
+This is a severe restriction for large-scale applications using realistic bottom topography.
+The large-scale slopes require high horizontal resolution,
+and the computational cost becomes prohibitive.
+This problem can be at least partially overcome by mixing $s$-coordinate and
+step-like representation of bottom topography
+\citep{gerdes_JGR93*a,gerdes_JGR93*b,madec.delecluse.ea_JPO96}.
+However, the definition of the model domain vertical coordinate becomes then a non-trivial thing for
+a realistic bottom topography:
+an envelope topography is defined in $s$-coordinate on which
+a full or partial step bottom topography is then applied in order to
+adjust the model depth to the observed one (see \autoref{subsec:DOM_zgr}).
+
+For numerical reasons a minimum of diffusion is required along
+the coordinate surfaces of any finite difference model.
+It causes spurious diapycnal mixing when coordinate surfaces do not coincide with isoneutral surfaces.
+This is the case for a $z$-model as well as for a $s$-model.
+However, density varies more strongly on $s$-surfaces than on horizontal surfaces in
+regions of large topographic slopes,
+implying larger diapycnal diffusion in a $s$-model than in a $z$-model.
+Whereas such a diapycnal diffusion in a $z$-model tends to
+weaken horizontal density (pressure) gradients and thus the horizontal circulation,
+it usually reinforces these gradients in a $s$-model, creating spurious circulation.
+For example, imagine an isolated bump of topography in
+an ocean at rest with a horizontally uniform stratification.
+Spurious diffusion along $s$-surfaces will induce a bump of isoneutral surfaces over the topography,
+and thus will generate there a baroclinic eddy.
+In contrast, the ocean will stay at rest in a $z$-model.
+As for the truncation error, the problem can be reduced by
+introducing the terrain-following coordinate below the strongly stratified portion of the water column
+(\ie\ the main thermocline) \citep{madec.delecluse.ea_JPO96}.
+An alternate solution consists of rotating the lateral diffusive tensor to
+geopotential or to isoneutral surfaces (see \autoref{subsec:MB_ldf}).
+Unfortunately, the slope of isoneutral surfaces relative to the $s$-surfaces can very large,
+strongly exceeding the stability limit of such a operator when it is discretized
+(see \autoref{chap:LDF}).
+
+The $s$-coordinates introduced here \citep{lott.madec.ea_OM90,madec.delecluse.ea_JPO96}
+differ mainly in two aspects from similar models:
+it allows a representation of bottom topography with
+mixed full or partial step-like/terrain following topography;
+It also offers a completely general transformation, $s=s(i,j,z)$ for the vertical coordinate.
+
+%% =================================================================================================
+\subsection{Curvilinear \ztilde-coordinate}
+\label{subsec:MB_zco_tilde}
+
+The \ztilde-coordinate has been developed by \citet{leclair.madec_OM11}.
+It is available in \NEMO\ since the version 3.4 and is more robust in version 4.0 than previously.
+Nevertheless, it is currently not robust enough to be used in all possible configurations.
+Its use is therefore not recommended.
+
+%% =================================================================================================
+\section{Subgrid scale physics}
+\label{sec:MB_zdf_ldf}
+
+The hydrostatic primitive equations describe the behaviour of a geophysical fluid at
+space and time scales larger than a few kilometres in the horizontal,
+a few meters in the vertical and a few minutes.
+They are usually solved at larger scales: the specified grid spacing and time step of
+the numerical model.
+The effects of smaller scale motions (coming from the advective terms in the Navier-Stokes equations)
+must be represented entirely in terms of large-scale patterns to close the equations.
+These effects appear in the equations as the divergence of turbulent fluxes
+(\ie\ fluxes associated with the mean correlation of small scale perturbations).
+Assuming a turbulent closure hypothesis is equivalent to choose a formulation for these fluxes.
+It is usually called the subgrid scale physics.
+It must be emphasized that this is the weakest part of the primitive equations,
+but also one of the most important for long-term simulations as
+small scale processes \textit{in fine} balance the surface input of kinetic energy and heat.
+
+The control exerted by gravity on the flow induces a strong anisotropy between
+the lateral and vertical motions.
+Therefore subgrid-scale physics \textbf{D}$^{\vect U}$, $D^{S}$ and $D^{T}$  in
+\autoref{eq:MB_PE_dyn}, \autoref{eq:MB_PE_tra_T} and \autoref{eq:MB_PE_tra_S} are divided into
+a  lateral part \textbf{D}$^{l \vect U}$, $D^{l S}$ and $D^{l T}$ and
+a vertical part \textbf{D}$^{v \vect U}$, $D^{v S}$ and $D^{v T}$.
+The formulation of these terms and their underlying physics are briefly discussed in
+the next two subsections.
+
+%% =================================================================================================
+\subsection{Vertical subgrid scale physics}
+\label{subsec:MB_zdf}
+
+The model resolution is always larger than the scale at which
+the major sources of vertical turbulence occur (shear instability, internal wave breaking...).
+Turbulent motions are thus never explicitly solved, even partially, but always parameterized.
+The vertical turbulent fluxes are assumed to depend linearly on
+the gradients of large-scale quantities (for example,
+the turbulent heat flux is given by $\overline{T' w'} = -A^{v T} \partial_z \overline T$,
+where $A^{v T}$ is an eddy coefficient).
+This formulation is analogous to that of molecular diffusion and dissipation.
+This is quite clearly a necessary compromise: considering only the molecular viscosity acting on
+large scale severely underestimates the role of turbulent diffusion and dissipation,
+while an accurate consideration of the details of turbulent motions is simply impractical.
+The resulting vertical momentum and tracer diffusive operators are of second order:
+\begin{equation}
+  \label{eq:MB_zdf}
+  \begin{gathered}
+    \vect D^{v \vect U} = \pd[]{z} \lt( A^{vm} \pd[\vect U_h]{z} \rt) \text{,} \
+          D^{vT}       = \pd[]{z} \lt( A^{vT} \pd[T]{z}         \rt) \ \text{and} \
+          D^{vS}       = \pd[]{z} \lt( A^{vT} \pd[S]{z}         \rt)
+  \end{gathered}
+\end{equation}
+where $A^{vm}$ and $A^{vT}$ are the vertical eddy viscosity and diffusivity coefficients,
+respectively.
+At the sea surface and at the bottom, turbulent fluxes of momentum, heat and salt must be specified
+(see \autoref{chap:SBC} and \autoref{chap:ZDF} and \autoref{sec:TRA_bbl}).
+All the vertical physics is embedded in the specification of the eddy coefficients.
+They can be assumed to be either constant, or function of the local fluid properties
+(\eg\ Richardson number, Brunt-V\"{a}is\"{a}l\"{a} frequency, distance from the boundary ...),
+or computed from a turbulent closure model.
+The choices available in \NEMO\ are discussed in \autoref{chap:ZDF}).
+
+%% =================================================================================================
+\subsection{Formulation of the lateral diffusive and viscous operators}
+\label{subsec:MB_ldf}
+
+Lateral turbulence can be roughly divided into a mesoscale turbulence associated with eddies
+(which can be solved explicitly if the resolution is sufficient since
+their underlying physics are included in the primitive equations),
+and a sub mesoscale turbulence which is never explicitly solved even partially,
+but always parameterized.
+The formulation of lateral eddy fluxes depends on whether
+the mesoscale is below or above the grid-spacing (\ie\ the model is eddy-resolving or not).
+
+In non-eddy-resolving configurations, the closure is similar to that used for the vertical physics.
+The lateral turbulent fluxes are assumed to depend linearly on
+the lateral gradients of large-scale quantities.
+The resulting lateral diffusive and dissipative operators are of second order.
+Observations show that
+lateral mixing induced by mesoscale turbulence tends to be along isopycnal surfaces
+(or more precisely neutral surfaces \cite{mcdougall_JPO87}) rather than across them.
+As the slope of neutral surfaces is small in the ocean,
+a common approximation is to assume that the ``lateral'' direction is the horizontal,
+\ie\ the lateral mixing is performed along geopotential surfaces.
+This leads to a geopotential second order operator for lateral subgrid scale physics.
+This assumption can be relaxed:
+the eddy-induced turbulent fluxes can be better approached by assuming that
+they depend linearly on the gradients of large-scale quantities computed along neutral surfaces.
+In such a case, the diffusive operator is an isoneutral second order operator and
+it has components in the three space directions.
+However, both horizontal and isoneutral operators have no effect on
+mean (\ie\ large scale) potential energy whereas
+potential energy is a main source of turbulence (through baroclinic instabilities).
+\citet{gent.mcwilliams_JPO90} proposed a parameterisation of mesoscale eddy-induced turbulence which
+associates an eddy-induced velocity to the isoneutral diffusion.
+Its mean effect is to reduce the mean potential energy of the ocean.
+This leads to a formulation of lateral subgrid-scale physics made up of
+an isoneutral second order operator and an eddy induced advective part.
+In all these lateral diffusive formulations,
+the specification of the lateral eddy coefficients remains the problematic point as
+there is no really satisfactory formulation of these coefficients as
+a function of large-scale features.
+
+In eddy-resolving configurations, a second order operator can be used,
+but usually the more scale selective biharmonic operator is preferred as
+the grid-spacing is usually not small enough compared to the scale of the eddies.
+The role devoted to the subgrid-scale physics is to dissipate the energy that
+cascades toward the grid scale and thus to ensure the stability of the model while
+not interfering with the resolved mesoscale activity.
+Another approach is becoming more and more popular:
+instead of specifying explicitly a sub-grid scale term in
+the momentum and tracer time evolution equations,
+one uses an advective scheme which is diffusive enough to maintain the model stability.
+It must be emphasised that then,
+all the sub-grid scale physics is included in the formulation of the advection scheme.
+
+All these parameterisations of subgrid scale physics have advantages and drawbacks.
+They are not all available in \NEMO.
+For active tracers (temperature and salinity) the main ones are:
+Laplacian and bilaplacian operators acting along geopotential or iso-neutral surfaces,
+\citet{gent.mcwilliams_JPO90} parameterisation, and various slightly diffusive advection schemes.
+For momentum, the main ones are:
+Laplacian and bilaplacian operators acting along geopotential surfaces,
+and UBS advection schemes when flux form is chosen for the momentum advection.
+
+%% =================================================================================================
+\subsubsection{Lateral laplacian tracer diffusive operator}
+
+The lateral Laplacian tracer diffusive operator is defined by (see \autoref{apdx:DIFFOPERS}):
+\begin{equation}
+  \label{eq:MB_iso_tensor}
+  D^{lT} = \nabla \vect . \lt( A^{lT} \; \Re \; \nabla T \rt) \quad \text{with} \quad \Re =
+  \begin{pmatrix}
+    1    & 0    & -r_1          \\
+    0    & 1    & -r_2          \\
+    -r_1 & -r_2 & r_1^2 + r_2^2 \\
+  \end{pmatrix}
+\end{equation}
+where $r_1$ and $r_2$ are the slopes between the surface along which the diffusive operator acts and
+the model level (\eg\ $z$- or $s$-surfaces).
+Note that the formulation \autoref{eq:MB_iso_tensor} is exact for
+the rotation between geopotential and $s$-surfaces,
+while it is only an approximation for the rotation between isoneutral and $z$- or $s$-surfaces.
+Indeed, in the latter case, two assumptions are made to simplify \autoref{eq:MB_iso_tensor}
+\citep{cox_OM87}.
+First, the horizontal contribution of the dianeutral mixing is neglected since
+the ratio between iso and dia-neutral diffusive coefficients is known to be
+several orders of magnitude smaller than unity.
+Second, the two isoneutral directions of diffusion are assumed to be independent since
+the slopes are generally less than $10^{-2}$ in the ocean (see \autoref{apdx:DIFFOPERS}).
+
+For \textit{iso-level} diffusion, $r_1$ and $r_2 $ are zero.
+$\Re$ reduces to the identity in the horizontal direction, no rotation is applied.
+
+For \textit{geopotential} diffusion,
+$r_1$ and $r_2 $ are the slopes between the geopotential and computational surfaces:
+they are equal to $\sigma_1$ and $\sigma_2$, respectively (see \autoref{eq:MB_sco_slope}).
+
+For \textit{isoneutral} diffusion $r_1$ and $r_2$ are the slopes between
+the isoneutral and computational surfaces.
+Therefore, they are different quantities, but have similar expressions in $z$- and $s$-coordinates.
+In $z$-coordinates:
+\begin{equation}
+  \label{eq:MB_iso_slopes}
+  r_1 = \frac{e_3}{e_1} \lt( \pd[\rho]{i} \rt) \lt( \pd[\rho]{k} \rt)^{-1} \quad
+  r_2 = \frac{e_3}{e_2} \lt( \pd[\rho]{j} \rt) \lt( \pd[\rho]{k} \rt)^{-1}
+\end{equation}
+while in $s$-coordinates $\pd[]{k}$ is replaced by $\pd[]{s}$.
+
+%% =================================================================================================
+\subsubsection{Eddy induced velocity}
+
+When the \textit{eddy induced velocity} parametrisation (eiv) \citep{gent.mcwilliams_JPO90} is used,
+an additional tracer advection is introduced in combination with the isoneutral diffusion of tracers:
+\[
+  % \label{eq:MB_iso+eiv}
+  D^{lT} = \nabla \cdot \lt( A^{lT} \; \Re \; \nabla T \rt) + \nabla \cdot \lt( \vect U^\ast \, T \rt)
+\]
+where $ \vect U^\ast = \lt( u^\ast,v^\ast,w^\ast \rt)$ is a non-divergent,
+eddy-induced transport velocity. This velocity field is defined by:
+\[
+  % \label{eq:MB_eiv}
+  u^\ast =   \frac{1}{e_3}            \pd[]{k} \lt( A^{eiv} \;        \tilde{r}_1 \rt) \quad
+  v^\ast =   \frac{1}{e_3}            \pd[]{k} \lt( A^{eiv} \;        \tilde{r}_2 \rt) \quad
+  w^\ast = - \frac{1}{e_1 e_2} \lt[   \pd[]{i} \lt( A^{eiv} \; e_2 \, \tilde{r}_1 \rt)
+                                     + \pd[]{j} \lt( A^{eiv} \; e_1 \, \tilde{r}_2 \rt) \rt]
+\]
+where $A^{eiv}$ is the eddy induced velocity coefficient
+(or equivalently the isoneutral thickness diffusivity coefficient),
+and $\tilde r_1$ and $\tilde r_2$ are the slopes between
+isoneutral and \textit{geopotential} surfaces.
+Their values are thus independent of the vertical coordinate,
+but their expression depends on the coordinate:
+\begin{equation}
+  \label{eq:MB_slopes_eiv}
+  \tilde{r}_n =
+    \begin{cases}
+      r_n            & \text{in $z$-coordinate}                \\
+      r_n + \sigma_n & \text{in \zstar- and $s$-coordinates}
+    \end{cases}
+  \quad \text{where~} n = 1, 2
+\end{equation}
+
+The normal component of the eddy induced velocity is zero at all the boundaries.
+This can be achieved in a model by tapering either the eddy coefficient or the slopes to zero in
+the vicinity of the boundaries.
+The latter strategy is used in \NEMO\ (cf. \autoref{chap:LDF}).
+
+%% =================================================================================================
+\subsubsection{Lateral bilaplacian tracer diffusive operator}
+
+The lateral bilaplacian tracer diffusive operator is defined by:
+\[
+  % \label{eq:MB_bilapT}
+  D^{lT}= - \Delta \; (\Delta T) \quad \text{where} \quad
+  \Delta \bullet = \nabla \lt( \sqrt{B^{lT}} \; \Re \; \nabla \bullet \rt)
+\]
+It is the Laplacian operator given by \autoref{eq:MB_iso_tensor} applied twice with
+the harmonic eddy diffusion coefficient set to the square root of the biharmonic one.
+
+%% =================================================================================================
+\subsubsection{Lateral Laplacian momentum diffusive operator}
+
+The Laplacian momentum diffusive operator along $z$- or $s$-surfaces is found by
+applying \autoref{eq:MB_lap_vector} to the horizontal velocity vector (see \autoref{apdx:DIFFOPERS}):
+\begin{align*}
+  % \label{eq:MB_lapU}
+  \vect D^{l \vect U} &=   \nabla_h        \big( A^{lm}    \chi             \big)
+                         - \nabla_h \times \big( A^{lm} \, \zeta \; \vect k \big) \\
+                      &= \lt(   \frac{1}{e_1}     \pd[ \lt( A^{lm}    \chi      \rt) ]{i} \rt.
+                              - \frac{1}{e_2 e_3} \pd[ \lt( A^{lm} \; e_3 \zeta \rt) ]{j} ,
+                                \frac{1}{e_2}     \pd[ \lt( A^{lm}    \chi      \rt) ]{j}
+                         \lt. + \frac{1}{e_1 e_3} \pd[ \lt( A^{lm} \; e_3 \zeta \rt) ]{i} \rt)
+\end{align*}
+
+Such a formulation ensures a complete separation between
+the vorticity and horizontal divergence fields (see \autoref{apdx:INVARIANTS}).
+Unfortunately, it is only available in \textit{iso-level} direction.
+When a rotation is required
+(\ie\ geopotential diffusion in $s$-coordinates or
+isoneutral diffusion in both $z$- and $s$-coordinates),
+the $u$ and $v$-fields are considered as independent scalar fields,
+so that the diffusive operator is given by:
+\[
+  % \label{eq:MB_lapU_iso}
+    D_u^{l \vect U} = \nabla . \lt( A^{lm} \; \Re \; \nabla u \rt) \quad
+    D_v^{l \vect U} = \nabla . \lt( A^{lm} \; \Re \; \nabla v \rt)
+\]
+where $\Re$ is given by \autoref{eq:MB_iso_tensor}.
+It is the same expression as those used for diffusive operator on tracers.
+It must be emphasised that such a formulation is only exact in a Cartesian coordinate system,
+\ie\ on a $f$- or $\beta$-plane, not on the sphere.
+It is also a very good approximation in vicinity of the Equator in
+a geographical coordinate system \citep{lengaigne.madec.ea_JGR03}.
+
+%% =================================================================================================
+\subsubsection{Lateral bilaplacian momentum diffusive operator}
+
+As for tracers,
+the bilaplacian order momentum diffusive operator is a re-entering Laplacian operator with
+the harmonic eddy diffusion coefficient set to the square root of the biharmonic one.
+Nevertheless it is currently not available in the iso-neutral case.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics_zstar.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics_zstar.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_model_basics_zstar.tex	(revision 14097)
@@ -0,0 +1,315 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{ essai \zstar \sstar}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{\textwidth}{l||X|X}
+    Release & Author(s) & Modifications \\
+    \hline
+    {\em   4.0} & {\em ...} & {\em ...} \\
+    {\em   3.6} & {\em ...} & {\em ...} \\
+    {\em   3.4} & {\em ...} & {\em ...} \\
+    {\em <=3.4} & {\em ...} & {\em ...}
+  \end{tabularx}
+}
+
+\clearpage
+
+%% =================================================================================================
+\section{Curvilinear \zstar- or \sstar coordinate system}
+
+\colorbox{yellow}{ to be updated }
+
+In that case, the free surface equation is nonlinear, and the variations of volume are fully taken into account.
+These coordinates systems is presented in a report \citep{levier.treguier.ea_rpt07} available on the \NEMO\ web site.
+
+\colorbox{yellow}{  end of to be updated}
+
+% from MOM4p1 documentation
+
+To overcome problems with vanishing surface and/or bottom cells, we consider the zstar coordinate
+\[
+  % \label{eq:MBZ_PE_}
+  z^\star = H \left( \frac{z-\eta}{H+\eta} \right)
+\]
+
+This coordinate is closely related to the "eta" coordinate used in many atmospheric models
+(see Black (1994) for a review of eta coordinate atmospheric models).
+It was originally used in ocean models by Stacey et al. (1995) for studies of tides next to shelves,
+and it has been recently promoted by Adcroft and Campin (2004) for global climate modelling.
+
+The surfaces of constant $z^\star$ are quasi-horizontal.
+Indeed, the $z^\star$ coordinate reduces to $z$ when $\eta$ is zero.
+In general, when noting the large differences between undulations of the bottom topography versus undulations in
+the surface height, it is clear that surfaces constant $z^\star$ are very similar to the depth surfaces.
+These properties greatly reduce difficulties of computing the horizontal pressure gradient relative to
+terrain following sigma models discussed in \autoref{subsec:MB_sco}.
+Additionally, since $z^\star$ when $\eta = 0$, no flow is spontaneously generated in
+an unforced ocean starting from rest, regardless the bottom topography.
+This behaviour is in contrast to the case with "s"-models, where pressure gradient errors in the presence of
+nontrivial topographic variations can generate nontrivial spontaneous flow from a resting state,
+depending on the sophistication of the pressure gradient solver.
+The quasi-horizontal nature of the coordinate surfaces also facilitates the implementation of
+neutral physics parameterizations in $z^\star$ models using the same techniques as in $z$-models
+(see Chapters 13-16 of Griffies (2004) for a discussion of neutral physics in $z$-models,
+as well as  \autoref{sec:LDF_slp} in this document for treatment in \NEMO).
+
+The range over which $z^\star$ varies is time independent $-H \leq z^\star \leq 0$.
+Hence, all cells remain nonvanishing, so long as the surface height maintains $\eta > ?H$.
+This is a minor constraint relative to that encountered on the surface height when using $s = z$ or $s = z - \eta$.
+
+Because $z^\star$ has a time independent range, all grid cells have static increments ds,
+and the sum of the ver tical increments yields the time independent ocean depth %�k ds = H.
+The $z^\star$ coordinate is therefore invisible to undulations of the free surface,
+since it moves along with the free surface.
+This proper ty means that no spurious ver tical transpor t is induced across surfaces of
+constant $z^\star$ by the motion of external gravity waves.
+Such spurious transpor t can be a problem in z-models, especially those with tidal forcing.
+Quite generally, the time independent range for the $z^\star$ coordinate is a very convenient property that
+allows for a nearly arbitrary vertical resolution even in the presence of large amplitude fluctuations of
+the surface height, again so long as $\eta > -H$.
+
+%  essai update time splitting...
+
+%% =================================================================================================
+\section[Surface pressure gradient and sea surface heigth (\textit{dynspg.F90})]{Surface pressure gradient and sea surface heigth (\protect\mdl{dynspg})}
+\label{sec:MBZ_dyn_hpg_spg}
+
+%\nlst{nam_dynspg}
+Options are defined through the \nam{_dynspg}{\_dynspg} namelist variables.
+The surface pressure gradient term is related to the representation of the free surface (\autoref{sec:MB_hor_pg}).
+The main distinction is between the fixed volume case (linear free surface or rigid lid) and
+the variable volume case (nonlinear free surface, \key{vvl} is active).
+In the linear free surface case (\autoref{subsec:MB_free_surface}) and rigid lid (\autoref{PE_rigid_lid}),
+the vertical scale factors $e_{3}$ are fixed in time,
+while in the nonlinear case (\autoref{subsec:MB_free_surface}) they are time-dependent.
+With both linear and nonlinear free surface, external gravity waves are allowed in the equations,
+which imposes a very small time step when an explicit time stepping is used.
+Two methods are proposed to allow a longer time step for the three-dimensional equations:
+the filtered free surface, which is a modification of the continuous equations %(see \autoref{eq:MB_flt?}),
+and the split-explicit free surface described below.
+The extra term introduced in the filtered method is calculated implicitly,
+so that the update of the next velocities is done in module \mdl{dynspg\_flt} and not in \mdl{dynnxt}.
+
+% Explicit
+%% =================================================================================================
+\subsubsection[Explicit (\texttt{\textbf{key\_dynspg\_exp}})]{Explicit (\protect\key{dynspg\_exp})}
+\label{subsec:MBZ_dyn_spg_exp}
+
+In the explicit free surface formulation, the model time step is chosen small enough to
+describe the external gravity waves (typically a few ten seconds).
+The sea surface height is given by:
+\begin{equation}
+  \label{eq:MBZ_dynspg_ssh}
+  \frac{\partial \eta }{\partial t}\equiv \frac{\text{EMP}}{\rho_w }+\frac{1}{e_{1T}
+    e_{2T} }\sum\limits_k {\left( {\delta_i \left[ {e_{2u} e_{3u} u}
+        \right]+\delta_j \left[ {e_{1v} e_{3v} v} \right]} \right)}
+\end{equation}
+
+where EMP is the surface freshwater budget (evaporation minus precipitation, and minus river runoffs
+(if the later are introduced as a surface freshwater flux, see \autoref{chap:SBC}) expressed in $Kg.m^{-2}.s^{-1}$,
+and $\rho_w =1,000\,Kg.m^{-3}$ is the volumic mass of pure water.
+The sea-surface height is evaluated using a leapfrog scheme in combination with an Asselin time filter,
+(\ie\ the velocity appearing in (\autoref{eq:DYN_spg_ssh}) is centred in time (\textit{now} velocity).
+
+The surface pressure gradient, also evaluated using a leap-frog scheme, is then simply given by:
+\begin{equation}
+  \label{eq:MBZ_dynspg_exp}
+  \left\{
+    \begin{aligned}
+      - \frac{1}    						{e_{1u}} \;	\delta_{i+1/2} \left[  \,\eta\,  \right] \\ \\
+      - \frac{1}    						{e_{2v}} \;	\delta_{j+1/2} \left[  \,\eta\,  \right]
+    \end{aligned}
+  \right.
+\end{equation}
+
+Consistent with the linearization, a $\left. \rho \right|_{k=1} / \rho_o$ factor is omitted in
+(\autoref{eq:DYN_spg_exp}).
+
+% Split-explicit time-stepping
+%% =================================================================================================
+\subsubsection[Split-explicit time-stepping (\texttt{\textbf{key\_dynspg\_ts}})]{Split-explicit time-stepping (\protect\key{dynspg\_ts})}
+\label{subsec:MBZ_dyn_spg_ts}
+
+The split-explicit free surface formulation used in OPA follows the one proposed by \citet{Griffies2004?}.
+The general idea is to solve the free surface equation with a small time step,
+while the three dimensional prognostic variables are solved with a longer time step that
+is a multiple of \np{rdtbt}{rdtbt} in the \nam{dom}{dom} namelist (Figure III.3).
+
+\begin{figure}[!t]
+  \centering
+  %\includegraphics[width=0.66\textwidth]{MBZ_DYN_dynspg_ts}
+  \caption[Schematic of the split-explicit time stepping scheme for
+  the barotropic and baroclinic modes, after \citet{Griffies2004?}]{
+    Schematic of the split-explicit time stepping scheme for the barotropic and baroclinic modes,
+    after \citet{Griffies2004?}.
+    Time increases to the right.
+    Baroclinic time steps are denoted by $t-\Delta t$, $t, t+\Delta t$, and $t+2\Delta t$.
+    The curved line represents a leap-frog time step,
+    and the smaller barotropic time steps $N \Delta t=2\Delta t$ are denoted by the zig-zag line.
+    The vertically integrated forcing \textbf{M}(t) computed at
+    baroclinic time step t represents the interaction between the barotropic and baroclinic motions.
+    While keeping the total depth, tracer, and freshwater forcing fields fixed,
+    a leap-frog integration carries the surface height and vertically integrated velocity from
+    t to $t+2 \Delta t$ using N barotropic time steps of length $\Delta t$.
+    Time averaging the barotropic fields over the N+1 time steps (endpoints included)
+    centers the vertically integrated velocity at the baroclinic timestep $t+\Delta t$.
+    A baroclinic leap-frog time step carries the surface height to $t+\Delta t$ using
+    the convergence of the time averaged vertically integrated velocity taken from
+    baroclinic time step t.}
+  \label{fig:MBZ_dyn_dynspg_ts}
+\end{figure}
+
+The split-explicit formulation has a damping effect on external gravity waves,
+which is weaker than the filtered free surface but still significant as shown by \citet{levier.treguier.ea_rpt07} in
+the case of an analytical barotropic Kelvin wave.
+
+%from griffies book: .....   copy past !
+
+\textbf{title: Time stepping the barotropic system }
+
+Assume knowledge of the full velocity and tracer fields at baroclinic time $\tau$.
+Hence, we can update the surface height and vertically integrated velocity with a leap-frog scheme using
+the small barotropic time step $\Delta t$.
+We have
+\[
+  % \label{eq:MBZ_dyn_spg_ts_eta}
+  \eta^{(b)}(\tau,t_{n+1}) - \eta^{(b)}(\tau,t_{n+1}) (\tau,t_{n-1})
+  = 2 \Delta t \left[-\nabla \cdot \textbf{U}^{(b)}(\tau,t_n) + \text{EMP}_w(\tau) \right]
+\]
+\begin{multline*}
+  % \label{eq:MBZ_dyn_spg_ts_u}
+  \textbf{U}^{(b)}(\tau,t_{n+1}) - \textbf{U}^{(b)}(\tau,t_{n-1})  \\
+  = 2\Delta t \left[ - f \textbf{k} \times \textbf{U}^{(b)}(\tau,t_{n})
+    - H(\tau) \nabla p_s^{(b)}(\tau,t_{n}) +\textbf{M}(\tau) \right]
+\end{multline*}
+\
+
+In these equations, araised (b) denotes values of surface height and
+vertically integrated velocity updated with the barotropic time steps.
+The $\tau$ time label on $\eta^{(b)}$ and $U^{(b)}$ denotes the baroclinic time at which
+the vertically integrated forcing $\textbf{M}(\tau)$
+(note that this forcing includes the surface freshwater forcing), the tracer fields,
+the freshwater flux $\text{EMP}_w(\tau)$, and total depth of the ocean $H(\tau)$ are held for
+the duration of the barotropic time stepping over a single cycle.
+This is also the time that sets the barotropic time steps via
+\[
+  % \label{eq:MBZ_dyn_spg_ts_t}
+  t_n=\tau+n\Delta t
+\]
+with $n$ an integer.
+The density scaled surface pressure is evaluated via
+\[
+  % \label{eq:MBZ_dyn_spg_ts_ps}
+  p_s^{(b)}(\tau,t_{n}) =
+  \begin{cases}
+    g \;\eta_s^{(b)}(\tau,t_{n}) \;\rho(\tau)_{k=1}) / \rho_o  &      \text{non-linear case} \\
+    g \;\eta_s^{(b)}(\tau,t_{n})  &      \text{linear case}
+  \end{cases}
+\]
+To get started, we assume the following initial conditions
+\[
+  % \label{eq:MBZ_dyn_spg_ts_eta}
+  \begin{split}
+    \eta^{(b)}(\tau,t_{n=0}) &= \overline{\eta^{(b)}(\tau)} \\
+    \eta^{(b)}(\tau,t_{n=1}) &= \eta^{(b)}(\tau,t_{n=0}) + \Delta t \ \text{RHS}_{n=0}
+  \end{split}
+\]
+with
+\[
+  % \label{eq:MBZ_dyn_spg_ts_etaF}
+  \overline{\eta^{(b)}(\tau)} = \frac{1}{N+1} \sum\limits_{n=0}^N \eta^{(b)}(\tau-\Delta t,t_{n})
+\]
+the time averaged surface height taken from the previous barotropic cycle.
+Likewise,
+\[
+  % \label{eq:MBZ_dyn_spg_ts_u}
+  \textbf{U}^{(b)}(\tau,t_{n=0}) = \overline{\textbf{U}^{(b)}(\tau)}	\\ \\
+  \textbf{U}(\tau,t_{n=1}) = \textbf{U}^{(b)}(\tau,t_{n=0}) + \Delta t \ \text{RHS}_{n=0}
+\]
+with
+\[
+  % \label{eq:MBZ_dyn_spg_ts_u}
+  \overline{\textbf{U}^{(b)}(\tau)} = \frac{1}{N+1} \sum\limits_{n=0}^N\textbf{U}^{(b)}(\tau-\Delta t,t_{n})
+\]
+the time averaged vertically integrated transport.
+Notably, there is no Robert-Asselin time filter used in the barotropic portion of the integration.
+
+Upon reaching $t_{n=N} = \tau + 2\Delta \tau$ , the vertically integrated velocity is time averaged to
+produce the updated vertically integrated velocity at baroclinic time $\tau + \Delta \tau$
+\[
+  % \label{eq:MBZ_dyn_spg_ts_u}
+  \textbf{U}(\tau+\Delta t) = \overline{\textbf{U}^{(b)}(\tau+\Delta t)}
+  = \frac{1}{N+1} \sum\limits_{n=0}^N\textbf{U}^{(b)}(\tau,t_{n})
+\]
+The surface height on the new baroclinic time step is then determined via
+a baroclinic leap-frog using the following form
+\begin{equation}
+  \label{eq:MBZ_dyn_spg_ts_ssh}
+  \eta(\tau+\Delta) - \eta^{F}(\tau-\Delta) = 2\Delta t \ \left[ - \nabla \cdot \textbf{U}(\tau) + \text{EMP}_w \right]
+\end{equation}
+
+The use of this "big-leap-frog" scheme for the surface height ensures compatibility between
+the mass/volume budgets and the tracer budgets.
+More discussion of this point is provided in Chapter 10 (see in particular Section 10.2).
+
+In general, some form of time filter is needed to maintain integrity of the surface height field due to
+the leap-frog splitting mode in equation \autoref{eq:MBZ_dyn_spg_ts_ssh}.
+We have tried various forms of such filtering,
+with the following method discussed in Griffies et al. (2001) chosen due to its stability and
+reasonably good maintenance of tracer conservation properties (see ??)
+
+\begin{equation}
+  \label{eq:MBZ_dyn_spg_ts_sshf}
+  \eta^{F}(\tau-\Delta) =  \overline{\eta^{(b)}(\tau)}
+\end{equation}
+Another approach tried was
+
+\[
+  % \label{eq:MBZ_dyn_spg_ts_sshf2}
+  \eta^{F}(\tau-\Delta) = \eta(\tau)
+  + (\alpha/2) \left[\overline{\eta^{(b)}}(\tau+\Delta t)
+    + \overline{\eta^{(b)}}(\tau-\Delta t) -2 \;\eta(\tau) \right]
+\]
+
+which is useful since it isolates all the time filtering aspects into the term multiplied by $\alpha$.
+This isolation allows for an easy check that tracer conservation is exact when eliminating tracer and
+surface height time filtering (see ?? for more complete discussion).
+However, in the general case with a non-zero $\alpha$, the filter \autoref{eq:MBZ_dyn_spg_ts_sshf} was found to
+be more conservative, and so is recommended.
+
+% Filtered formulation
+%% =================================================================================================
+\subsubsection[Filtered formulation (\texttt{\textbf{key\_dynspg\_flt}})]{Filtered formulation (\protect\key{dynspg\_flt})}
+\label{subsec:MBZ_dyn_spg_flt}
+
+The filtered formulation follows the \citet{Roullet2000?} implementation.
+The extra term introduced in the equations (see {\S}I.2.2) is solved implicitly.
+The elliptic solvers available in the code are documented in \autoref{chap:MISC}.
+The amplitude of the extra term is given by the namelist variable \np{rnu}{rnu}.
+The default value is 1, as recommended by \citet{Roullet2000?}
+
+\colorbox{red}{\np[=1]{rnu}{rnu} to be suppressed from namelist !}
+
+% Non-linear free surface formulation
+%% =================================================================================================
+\subsection[Non-linear free surface formulation (\texttt{\textbf{key\_vvl}})]{Non-linear free surface formulation (\protect\key{vvl})}
+\label{subsec:MBZ_dyn_spg_vvl}
+
+In the non-linear free surface formulation, the variations of volume are fully taken into account.
+This option is presented in a report \citep{levier.treguier.ea_rpt07} available on the \NEMO\ web site.
+The three time-stepping methods (explicit, split-explicit and filtered) are the same as in
+\autoref{?:DYN_spg_linear?} except that the ocean depth is now time-dependent.
+In particular, this means that in filtered case, the matrix to be inverted has to be recomputed at each time-step.
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_time_domain.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_time_domain.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/chap_time_domain.tex	(revision 14097)
@@ -0,0 +1,406 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Time Domain}
+\label{chap:TD}
+
+\thispagestyle{plain}
+
+\chaptertoc
+
+\paragraph{Changes record} ~\\
+
+{\footnotesize
+  \begin{tabularx}{0.5\textwidth}{l||X|X}
+    Release          & Author(s)                                       &
+    Modifications                                                      \\
+    \hline
+    {\em        4.0} & {\em J\'{e}r\^{o}me Chanut \newline Tim Graham} &
+    {\em Review \newline Update                                      } \\
+    {\em        3.6} & {\em Christian \'{E}th\'{e}                   } &
+    {\em Update                                                      } \\
+    {\em $\leq$ 3.4} & {\em Gurvan Madec                             } &
+    {\em First version                                               } \\
+  \end{tabularx}
+}
+
+\clearpage
+
+% Missing things:
+% - daymod: definition of the time domain (nit000, nitend and the calendar)
+
+\cmtgm{STEVEN :maybe a picture of the directory structure in the introduction which
+could be referred to here, would help  ==> to be added}
+
+Having defined the continuous equations in \autoref{chap:MB},
+we need now to choose a time discretization,
+a key feature of an ocean model as it exerts a strong influence on the structure of the computer code
+(\ie\ on its flowchart).
+In the present chapter, we provide a general description of the \NEMO\ time stepping strategy and
+the consequences for the order in which the equations are solved.
+
+%% =================================================================================================
+\section{Time stepping environment}
+\label{sec:TD_environment}
+
+The time stepping used in \NEMO\ is a three level scheme that can be represented as follows:
+\begin{equation}
+  \label{eq:TD}
+  x^{t + \rdt} = x^{t - \rdt} + 2 \, \rdt \ \text{RHS}_x^{t - \rdt, \, t, \, t + \rdt}
+\end{equation}
+where $x$ stands for $u$, $v$, $T$ or $S$;
+RHS is the \textbf{R}ight-\textbf{H}and-\textbf{S}ide of the corresponding time evolution equation;
+$\rdt$ is the time step;
+and the superscripts indicate the time at which a quantity is evaluated.
+Each term of the RHS is evaluated at a specific time stepping depending on
+the physics with which it is associated.
+
+The choice of the time stepping used for this evaluation is discussed below as well as
+the implications for starting or restarting a model simulation.
+Note that the time stepping calculation is generally performed in a single operation.
+With such a complex and nonlinear system of equations it would be dangerous to
+let a prognostic variable evolve in time for each term separately.
+
+The three level scheme requires three arrays for each prognostic variable.
+For each variable $x$ there is $x_b$ (before), $x_n$ (now) and $x_a$.
+The third array, although referred to as $x_a$ (after) in the code,
+is usually not the variable at the after time step;
+but rather it is used to store the time derivative (RHS in \autoref{eq:TD})
+prior to time-stepping the equation.
+The time stepping itself is performed once at each time step where
+implicit vertical diffusion is computed,
+\ie\ in the \mdl{trazdf} and \mdl{dynzdf} modules.
+
+%% =================================================================================================
+\section{Non-diffusive part --- Leapfrog scheme}
+\label{sec:TD_leap_frog}
+
+The time stepping used for processes other than diffusion is
+the well-known \textbf{L}eap\textbf{F}rog (LF) scheme \citep{mesinger.arakawa_bk76}.
+This scheme is widely used for advection processes in low-viscosity fluids.
+It is a time centred scheme, \ie\ the RHS in \autoref{eq:TD} is evaluated at
+time step $t$, the now time step.
+It may be used for momentum and tracer advection, pressure gradient, and Coriolis terms,
+but not for diffusion terms.
+It is an efficient method that achieves second-order accuracy with
+just one right hand side evaluation per time step.
+Moreover, it does not artificially damp linear oscillatory motion
+nor does it produce instability by amplifying the oscillations.
+These advantages are somewhat diminished by the large phase-speed error of the leapfrog scheme,
+and the unsuitability of leapfrog differencing for the representation of diffusion and
+Rayleigh damping processes.
+However, the scheme allows the coexistence of a numerical and a physical mode due to
+its leading third order dispersive error.
+In other words a divergence of odd and even time steps may occur.
+To prevent it, the leapfrog scheme is often used in association with
+a \textbf{R}obert-\textbf{A}sselin time filter (hereafter the LF-RA scheme).
+This filter,
+first designed by \citet{robert_JMSJ66} and more comprehensively studied by \citet{asselin_MWR72},
+is a kind of laplacian diffusion in time that mixes odd and even time steps:
+\begin{equation}
+  \label{eq:TD_asselin}
+  x_F^t = x^t + \gamma \, \lt[ x_F^{t - \rdt} - 2 x^t + x^{t + \rdt} \rt]
+\end{equation}
+where the subscript $F$ denotes filtered values and $\gamma$ is the Asselin coefficient.
+$\gamma$ is initialized as \np{rn_atfp}{rn\_atfp} (namelist parameter).
+Its default value is \np[=10.e-3]{rn_atfp}{rn\_atfp} (see \autoref{sec:TD_mLF}),
+causing only a weak dissipation of high frequency motions (\citep{farge-coulombier_phd87}).
+The addition of a time filter degrades the accuracy of the calculation from second to first order.
+However, the second order truncation error is proportional to $\gamma$, which is small compared to 1.
+Therefore, the LF-RA is a quasi second order accurate scheme.
+The LF-RA scheme is preferred to other time differencing schemes such as
+predictor corrector or trapezoidal schemes, because the user has an explicit and simple control of
+the magnitude of the time diffusion of the scheme.
+When used with the 2$^nd$ order space centred discretisation of the advection terms in
+the momentum and tracer equations, LF-RA avoids implicit numerical diffusion:
+diffusion is set explicitly by the user through the Robert-Asselin filter parameter and
+the viscosity and diffusion coefficients.
+
+%% =================================================================================================
+\section{Diffusive part --- Forward or backward scheme}
+\label{sec:TD_forward_imp}
+
+The leapfrog differencing scheme is unsuitable for
+the representation of diffusion and damping processes.
+For a tendency $D_x$, representing a diffusion term or a restoring term to a tracer climatology
+(when present, see \autoref{sec:TRA_dmp}), a forward time differencing scheme is used :
+\[
+  %\label{eq:TD_euler}
+  x^{t + \rdt} = x^{t - \rdt} + 2 \, \rdt \ D_x^{t - \rdt}
+\]
+
+This is diffusive in time and conditionally stable.
+The conditions for stability of second and fourth order horizontal diffusion schemes are
+\citep{griffies_bk04}:
+\begin{equation}
+  \label{eq:TD_euler_stability}
+  A^h <
+  \begin{cases}
+    \frac{e^2}{ 8 \, \rdt} & \text{laplacian diffusion} \\
+    \frac{e^4}{64 \, \rdt} & \text{bilaplacian diffusion}
+  \end{cases}
+\end{equation}
+where $e$ is the smallest grid size in the two horizontal directions and
+$A^h$ is the mixing coefficient.
+The linear constraint \autoref{eq:TD_euler_stability} is a necessary condition, but not sufficient.
+If it is not satisfied, even mildly, then the model soon becomes wildly unstable.
+The instability can be removed by either reducing the length of the time steps or
+reducing the mixing coefficient.
+
+For the vertical diffusion terms, a forward time differencing scheme can be used,
+but usually the numerical stability condition imposes a strong constraint on the time step.
+To overcome the stability constraint, a backward (or implicit) time differencing scheme is used.
+This scheme is unconditionally stable but diffusive and can be written as follows:
+\begin{equation}
+  \label{eq:TD_imp}
+  x^{t + \rdt} = x^{t - \rdt} + 2 \, \rdt \ \text{RHS}_x^{t + \rdt}
+\end{equation}
+
+\cmtgm{UPDATE the next paragraphs with time varying thickness ...}
+
+This scheme is rather time consuming since it requires a matrix inversion.
+For example, the finite difference approximation of the temperature equation is:
+\[
+  % \label{eq:TD_imp_zdf}
+  \frac{T(k)^{t + 1} - T(k)^{t - 1}}{2 \; \rdt}
+  \equiv
+  \text{RHS} + \frac{1}{e_{3t}} \delta_k \lt[ \frac{A_w^{vT}}{e_{3w} } \delta_{k + 1/2} \lt[ T^{t + 1} \rt] \rt]
+\]
+where RHS is the right hand side of the equation except for the vertical diffusion term.
+We rewrite \autoref{eq:TD_imp} as:
+\begin{equation}
+  \label{eq:TD_imp_mat}
+  -c(k + 1) \; T^{t + 1}(k + 1) + d(k) \; T^{t + 1}(k) - \; c(k) \; T^{t + 1}(k - 1) \equiv b(k)
+\end{equation}
+where
+\[
+  c(k) = A_w^{vT} (k) \, / \, e_{3w} (k) \text{,} \quad
+  d(k) = e_{3t}   (k)       \, / \, (2 \rdt) + c_k + c_{k + 1} \quad \text{and} \quad
+  b(k) = e_{3t}   (k) \; \lt( T^{t - 1}(k) \, / \, (2 \rdt) + \text{RHS} \rt)
+\]
+
+\autoref{eq:TD_imp_mat} is a linear system of equations with
+an associated matrix which is tridiagonal.
+Moreover, $c(k)$ and $d(k)$ are positive and
+the diagonal term is greater than the sum of the two extra-diagonal terms,
+therefore a special adaptation of the Gauss elimination procedure is used to find the solution
+(see for example \citet{richtmyer.morton_bk67}).
+
+%% =================================================================================================
+\section{Surface pressure gradient}
+\label{sec:TD_spg_ts}
+
+The leapfrog environment supports a centred in time computation of the surface pressure,
+\ie\ evaluated at \textit{now} time step.
+This refers to as the explicit free surface case in the code
+(\np[=.true.]{ln_dynspg_exp}{ln\_dynspg\_exp}).
+This choice however imposes a strong constraint on the time step which
+should be small enough to resolve the propagation of external gravity waves.
+As a matter of fact, one rather use in a realistic setup,
+a split-explicit free surface (\np[=.true.]{ln_dynspg_ts}{ln\_dynspg\_ts}) in which
+barotropic and baroclinic dynamical equations are solved separately with ad-hoc time steps.
+The use of the time-splitting (in combination with non-linear free surface) imposes
+some constraints on the design of the overall flowchart,
+in particular to ensure exact tracer conservation (see \autoref{fig:TD_TimeStep_flowchart}).
+
+Compared to the former use of the filtered free surface in \NEMO\ v3.6 (\citet{roullet.madec_JGR00}),
+the use of a split-explicit free surface is advantageous on massively parallel computers.
+Indeed, no global computations are anymore required by the elliptic solver which
+saves a substantial amount of communication time.
+Fast barotropic motions (such as tides) are also simulated with a better accuracy.
+
+%\cmtgm{
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{TD_TimeStepping_flowchart_v4}
+  \caption[Leapfrog time stepping sequence with split-explicit free surface]{
+    Sketch of the leapfrog time stepping sequence in \NEMO\ with split-explicit free surface.
+    The latter combined with non-linear free surface requires
+    the dynamical tendency being updated prior tracers tendency to ensure conservation.
+    Note the use of time integrated fluxes issued from the barotropic loop in
+    subsequent calculations of tracer advection and in the continuity equation.
+    Details about the time-splitting scheme can be found in \autoref{subsec:DYN_spg_ts}.}
+  \label{fig:TD_TimeStep_flowchart}
+\end{figure}
+%}
+
+%% =================================================================================================
+\section{Modified LeapFrog -- Robert Asselin filter scheme (LF-RA)}
+\label{sec:TD_mLF}
+
+Significant changes have been introduced by \cite{leclair.madec_OM09} in
+the LF-RA scheme in order to ensure tracer conservation and to
+allow the use of a much smaller value of the Asselin filter parameter.
+The modifications affect both the forcing and filtering treatments in the LF-RA scheme.
+
+In a classical LF-RA environment,
+the forcing term is centred in time, \ie\ it is time-stepped over a $2 \rdt$ period:
+$x^t = x^t + 2 \rdt Q^t$ where $Q$ is the forcing applied to $x$,
+and the time filter is given by \autoref{eq:TD_asselin} so that
+$Q$ is redistributed over several time step.
+In the modified LF-RA environment, these two formulations have been replaced by:
+\begin{gather}
+  \label{eq:TD_forcing}
+  x^{t + \rdt} = x^{t - \rdt} + \rdt \lt( Q^{t - \rdt / 2} + Q^{t + \rdt / 2} \rt)  \\
+  \label{eq:TD_RA}
+  x_F^t       = x^t + \gamma \, \lt( x_F^{t - \rdt} - 2 x^t + x^{t + \rdt} \rt)
+                    - \gamma \, \rdt \, \lt( Q^{t + \rdt / 2} - Q^{t - \rdt / 2} \rt)
+\end{gather}
+The change in the forcing formulation given by \autoref{eq:TD_forcing}
+(see \autoref{fig:TD_MLF_forcing}) has a significant effect:
+the forcing term no longer excites the divergence of odd and even time steps
+\citep{leclair.madec_OM09}.
+% forcing seen by the model....
+This property improves the LF-RA scheme in two aspects.
+First, the LF-RA can now ensure the local and global conservation of tracers.
+Indeed, time filtering is no longer required on the forcing part.
+The influence of the Asselin filter on the forcing is explicitly removed by
+adding a new term in the filter (last term in \autoref{eq:TD_RA} compared to \autoref{eq:TD_asselin}).
+Since the filtering of the forcing was the source of non-conservation in the classical LF-RA scheme,
+the modified formulation becomes conservative \citep{leclair.madec_OM09}.
+Second, the LF-RA becomes a truly quasi-second order scheme.
+Indeed, \autoref{eq:TD_forcing} used in combination with a careful treatment of static instability
+(\autoref{subsec:ZDF_evd}) and of the TKE physics (\autoref{subsec:ZDF_tke_ene})
+(the two other main sources of time step divergence),
+allows a reduction by two orders of magnitude of the Asselin filter parameter.
+
+Note that the forcing is now provided at the middle of a time step:
+$Q^{t + \rdt / 2}$ is the forcing applied over the $[t,t + \rdt]$ time interval.
+This and the change in the time filter, \autoref{eq:TD_RA},
+allows for an exact evaluation of the contribution due to the forcing term between any two time steps,
+even if separated by only $\rdt$ since the time filter is no longer applied to the forcing term.
+
+\begin{figure}
+  \centering
+  \includegraphics[width=0.66\textwidth]{TD_MLF_forcing}
+  \caption[Forcing integration methods for modified leapfrog (top and bottom)]{
+    Illustration of forcing integration methods.
+    (top) ''Traditional'' formulation:
+    the forcing is defined at the same time as the variable to which it is applied
+    (integer value of the time step index) and it is applied over a $2 \rdt$ period.
+    (bottom)  modified formulation:
+    the forcing is defined in the middle of the time
+    (integer and a half value of the time step index) and
+    the mean of two successive forcing values ($n - 1 / 2$, $n + 1 / 2$) is applied over
+    a $2 \rdt$ period.}
+  \label{fig:TD_MLF_forcing}
+\end{figure}
+
+%% =================================================================================================
+\section{Start/Restart strategy}
+\label{sec:TD_rst}
+
+\begin{listing}
+  \nlst{namrun}
+  \caption{\forcode{&namrun}}
+  \label{lst:namrun}
+\end{listing}
+
+The first time step of this three level scheme when starting from initial conditions is
+a forward step (Euler time integration):
+\[
+  % \label{eq:TD_DOM_euler}
+  x^1 = x^0 + \rdt \ \text{RHS}^0
+\]
+This is done simply by keeping the leapfrog environment
+(\ie\ the \autoref{eq:TD} three level time stepping) but
+setting all $x^0$ (\textit{before}) and $x^1$ (\textit{now}) fields equal at the first time step and
+using half the value of a leapfrog time step ($2 \rdt$).
+
+It is also possible to restart from a previous computation, by using a restart file.
+The restart strategy is designed to ensure perfect restartability of the code:
+the user should obtain the same results to machine precision either by
+running the model for $2N$ time steps in one go,
+or by performing two consecutive experiments of $N$ steps with a restart.
+This requires saving two time levels and many auxiliary data in
+the restart files in machine precision.
+
+Note that the time step $\rdt$, is also saved in the restart file.
+When restarting, if the time step has been changed, or
+one of the prognostic variables at \textit{before} time step is missing,
+an Euler time stepping scheme is imposed.
+A forward initial step can still be enforced by the user by
+setting the namelist variable \np[=0]{nn_euler}{nn\_euler}.
+Other options to control the time integration of the model are defined through
+the \nam{run}{run} namelist variables.
+
+\cmtgm{
+add here how to force the restart to contain only one time step for operational purposes
+
+add also the idea of writing several restart for seasonal forecast : how is it done ?
+
+verify that all namelist parameters are truly described
+
+a word on the check of restart  .....
+}
+
+\cmtgm{       % add a subsection here
+
+%% =================================================================================================
+\subsection{Time domain}
+\label{subsec:TD_time}
+
+Options are defined through the\nam{dom}{dom} namelist variables.
+ \colorbox{yellow}{add here a few word on nit000 and nitend}
+
+ \colorbox{yellow}{Write documentation on the calendar and the key variable adatrj}
+
+add a description of daymod, and the model calendar (leap-year and co)
+
+}     %% end add
+
+\cmtgm{       % add implicit in vvl case  and Crant-Nicholson scheme
+
+Implicit time stepping in case of variable volume thickness.
+
+Tracer case (NB for momentum in vector invariant form take care!)
+
+\begin{flalign*}
+  &\frac{\lt( e_{3t}\,T \rt)_k^{t+1}-\lt( e_{3t}\,T \rt)_k^{t-1}}{2\rdt}
+  \equiv \text{RHS}+ \delta_k \lt[ {\frac{A_w^{vt} }{e_{3w}^{t+1} }\delta_{k + 1/2} \lt[ {T^{t+1}} \rt]}
+  \rt]      \\
+  &\lt( e_{3t}\,T \rt)_k^{t+1}-\lt( e_{3t}\,T \rt)_k^{t-1}
+  \equiv {2\rdt} \ \text{RHS}+ {2\rdt} \ \delta_k \lt[ {\frac{A_w^{vt} }{e_{3w}^{t+1} }\delta_{k + 1/2} \lt[ {T^{t+1}} \rt]}
+  \rt]      \\
+  &\lt( e_{3t}\,T \rt)_k^{t+1}-\lt( e_{3t}\,T \rt)_k^{t-1}
+  \equiv 2\rdt \ \text{RHS}
+  + 2\rdt \ \lt\{ \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k + 1/2} [ T_{k +1}^{t+1} - T_k      ^{t+1} ]
+    - \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k - 1/2} [ T_k       ^{t+1} - T_{k -1}^{t+1} ]  \rt\}     \\
+  &\\
+  &\lt( e_{3t}\,T \rt)_k^{t+1}
+  -  {2\rdt} \           \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k + 1/2}                  T_{k +1}^{t+1}
+  + {2\rdt} \ \lt\{  \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k + 1/2}
+    +  \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k - 1/2}     \rt\}   T_{k    }^{t+1}
+  -  {2\rdt} \           \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k - 1/2}                  T_{k -1}^{t+1}      \\
+  &\equiv \lt( e_{3t}\,T \rt)_k^{t-1} + {2\rdt} \ \text{RHS}    \\
+  %
+\end{flalign*}
+\begin{flalign*}
+  \allowdisplaybreaks
+  \intertext{ Tracer case }
+  %
+  &  \qquad \qquad  \quad   -  {2\rdt}                  \ \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k + 1/2}
+  \qquad \qquad \qquad  \qquad  T_{k +1}^{t+1}   \\
+  &+ {2\rdt} \ \biggl\{  (e_{3t})_{k   }^{t+1}  \bigg. +    \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k + 1/2}
+  +   \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k - 1/2} \bigg. \biggr\}  \ \ \ T_{k   }^{t+1}  &&\\
+  & \qquad \qquad  \qquad \qquad \qquad \quad \ \ -  {2\rdt} \                          \lt[ \frac{A_w^{vt}}{e_{3w}^{t+1}} \rt]_{k - 1/2}                          \quad \ \ T_{k -1}^{t+1}
+  \ \equiv \ \lt( e_{3t}\,T \rt)_k^{t-1} + {2\rdt} \ \text{RHS}  \\
+  %
+\end{flalign*}
+\begin{flalign*}
+  \allowdisplaybreaks
+  \intertext{ Tracer content case }
+  %
+  & -  {2\rdt} \              & \frac{(A_w^{vt})_{k + 1/2}} {(e_{3w})_{k + 1/2}^{t+1}\;(e_{3t})_{k +1}^{t+1}}  && \  \lt( e_{3t}\,T \rt)_{k +1}^{t+1}   &\\
+  & + {2\rdt} \ \lt[ 1  \rt.+ & \frac{(A_w^{vt})_{k + 1/2}} {(e_{3w})_{k + 1/2}^{t+1}\;(e_{3t})_k^{t+1}}
+  + & \frac{(A_w^{vt})_{k - 1/2}} {(e_{3w})_{k - 1/2}^{t+1}\;(e_{3t})_k^{t+1}}  \lt.  \rt]  & \lt( e_{3t}\,T \rt)_{k   }^{t+1}  &\\
+  & -  {2\rdt} \               & \frac{(A_w^{vt})_{k - 1/2}} {(e_{3w})_{k - 1/2}^{t+1}\;(e_{3t})_{k -1}^{t+1}}     &\  \lt( e_{3t}\,T \rt)_{k -1}^{t+1}
+  \equiv \lt( e_{3t}\,T \rt)_k^{t-1} + {2\rdt} \ \text{RHS}  &
+\end{flalign*}
+
+}
+
+\subinc{\input{../../global/epilogue}}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/NEMO/subfiles/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/SI3_manual.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/SI3_manual.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/SI3_manual.tex	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../global/document.tex
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/abstract.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/abstract.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/abstract.tex	(revision 14097)
@@ -0,0 +1,25 @@
+%% ================================================================
+%% Abstract
+%% ================================================================
+
+%% Common part between NEMO-SI3-TOP
+``Sea Ice Modelling Integrated Initiative'' (\SIcube) is the sea ice engine of
+the \NEMO\ ocean model (``Nucleus for European Modelling of the Ocean'').
+It is intended to be a flexible tool for studying the sea ice dynamics and thermodynamics,
+brine inclusions and subgrid-scale thickness variations (``white ocean''),
+as well as its interactions with the other components of the Earth climate system over
+a wide range of space and time scales.
+\SIcube\ is interfaced with the \NEMO\ ocean engine, and,
+via the \href{http://portal.enes.org/oasis}{OASIS} coupler,
+with several atmospheric general circulation models.
+It also supports two-way grid embedding by means of the \href{http://agrif.imag.fr}{AGRIF} software.
+
+%% Specific part
+Designed for global to regional applications up to $~$10 km of effective resolution,
+\SIcube\ is a curvilinear grid, finite-difference implementation of the classical AIDJEX model
+(Arctic Ice Dynamics Joint EXperiment),
+combining the conservation of momentum for viscous-plastic continuum,
+energy and salt-conserving halo-thermodynamics,
+an explicit representation of subgrid-scale ice thickness variations, snow and melt ponds.
+An option to switch back to the \textit{single-category} (or \textit{2-level}) framework provides
+a cheap sea ice modelling solution.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/authors.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/authors.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/authors.tex	(revision 14097)
@@ -0,0 +1,16 @@
+Yevgeny Aksenov       \\
+Ed Blockley           \\
+Matthieu Chevallier   \\
+Danny Feltham         \\
+Thierry Fichefet      \\
+Gilles Garric         \\
+Paul Holland          \\
+Dorotea Iovino        \\
+Gurvan Madec          \\
+Fran\c cois Massonnet \\
+Jeff Ridley           \\
+Cl\'ement Rousset     \\
+David Salas           \\
+David Schroeder       \\
+Steffen Tietsche      \\
+Martin Vancoppenolle
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/bibliography.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/bibliography.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/bibliography.bib	(revision 14097)
@@ -0,0 +1,677 @@
+
+@Article{	  assur_1958,
+  author	= {Assur, A},
+  year		= {1958},
+  month		= {01},
+  pages		= {106-138},
+  title		= {Composition of sea ice and its tensile strength},
+  volume	= {598},
+  journal	= {Arctic Sea Ice}
+}
+
+@Article{	  babko_2002,
+  author	= {Babko, O.},
+  title		= {Role of rafting in the mechanical redistribution of sea
+		  ice thickness},
+  year		= 2002,
+  volume	= 107,
+  number	= {C8},
+  issn		= {0148-0227},
+  doi		= {10.1029/1999jc000190},
+  url		= {http://dx.doi.org/10.1029/1999JC000190},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  bitz_1999,
+  author	= {Bitz, C. M. and Lipscomb, William H.},
+  title		= {An energy-conserving thermodynamic model of sea ice},
+  year		= 1999,
+  volume	= 104,
+  number	= {C7},
+  month		= {Jul},
+  pages		= {15669–15677},
+  issn		= {0148-0227},
+  doi		= {10.1029/1999jc900100},
+  url		= {http://dx.doi.org/10.1029/1999jc900100},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  bitz_2001,
+  author	= {Bitz, C. M. and Holland, M. M. and Weaver, A. J. and Eby,
+		  M.},
+  title		= {Simulating the ice-thickness distribution in a coupled
+		  climate model},
+  year		= 2001,
+  volume	= 106,
+  number	= {C2},
+  month		= {Feb},
+  pages		= {2441–2463},
+  issn		= {0148-0227},
+  doi		= {10.1029/1999jc000113},
+  url		= {http://dx.doi.org/10.1029/1999jc000113},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  bouillon_2013,
+  author	= {Bouillon, Sylvain and Fichefet, Thierry and Legat, Vincent
+		  and Madec, Gurvan},
+  title		= {The elastic–viscous–plastic method revisited},
+  year		= 2013,
+  volume	= 71,
+  month		= {Nov},
+  pages		= {2–12},
+  issn		= {1463-5003},
+  doi		= {10.1016/j.ocemod.2013.05.013},
+  url		= {http://dx.doi.org/10.1016/j.ocemod.2013.05.013},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  brandt_2005,
+  author	= {Brandt, Richard E. and Warren, Stephen G. and Worby,
+		  Anthony P. and Grenfell, Thomas C.},
+  title		= {Surface Albedo of the Antarctic Sea Ice Zone},
+  year		= 2005,
+  volume	= 18,
+  number	= 17,
+  month		= {Sep},
+  pages		= {3606–3622},
+  issn		= {1520-0442},
+  doi		= {10.1175/jcli3489.1},
+  url		= {http://dx.doi.org/10.1175/jcli3489.1},
+  journal	= {Journal of Climate},
+  publisher	= {American Meteorological Society}
+}
+
+@Article{	  coon_1974,
+  author	= {Coon, M.D. and Maykut, G.A. and Pritchard, R.S. and
+		  Rothrock, D.A. and Thorndike, A.S.},
+  year		= {1974},
+  month		= {01},
+  pages		= {1-106},
+  title		= {Modeling the pack ice as an elastic-plastic material},
+  volume	= {24},
+  journal	= {AIDJEX Bull.}
+}
+
+@Article{	  ebert_1993,
+  author	= {Ebert, Elizabeth E. and Curry, Judith A.},
+  title		= {An intermediate one-dimensional thermodynamic sea ice
+		  model for investigating ice-atmosphere interactions},
+  year		= 1993,
+  volume	= 98,
+  number	= {C6},
+  pages		= 10085,
+  issn		= {0148-0227},
+  doi		= {10.1029/93jc00656},
+  url		= {http://dx.doi.org/10.1029/93jc00656},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  fichefet_1997,
+  author	= {Fichefet, T. and Maqueda, M. A. Morales},
+  title		= {Sensitivity of a global sea ice model to the treatment of
+		  ice thermodynamics and dynamics},
+  year		= 1997,
+  volume	= 102,
+  number	= {C6},
+  month		= {Jun},
+  pages		= {12609–12646},
+  issn		= {0148-0227},
+  doi		= {10.1029/97jc00480},
+  url		= {http://dx.doi.org/10.1029/97jc00480},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  flato_1995,
+  author	= {Flato, Gregory M. and Hibler, William D.},
+  title		= {Ridging and strength in modeling the thickness
+		  distribution of Arctic sea ice},
+  year		= 1995,
+  volume	= 100,
+  number	= {C9},
+  pages		= 18611,
+  issn		= {0148-0227},
+  doi		= {10.1029/95jc02091},
+  url		= {http://dx.doi.org/10.1029/95jc02091},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  girard_2009,
+  author	= {Girard, L. and Weiss, J. and Molines, J. M. and Barnier,
+		  B. and Bouillon, S.},
+  title		= {Evaluation of high-resolution sea ice models on the basis
+		  of statistical and scaling properties of Arctic sea ice
+		  drift and deformation},
+  year		= 2009,
+  volume	= 114,
+  number	= {C8},
+  month		= {Aug},
+  issn		= {0148-0227},
+  doi		= {10.1029/2008jc005182},
+  url		= {http://dx.doi.org/10.1029/2008JC005182},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  grenfell_1977,
+  author	= {Grenfell, Thomas C. and Maykut, Gary A.},
+  title		= {The Optical Properties of Ice and Snow in the Arctic
+		  Basin},
+  year		= 1977,
+  volume	= 18,
+  number	= 80,
+  pages		= {445–463},
+  issn		= {1727-5652},
+  doi		= {10.3189/s0022143000021122},
+  url		= {http://dx.doi.org/10.3189/s0022143000021122},
+  journal	= {Journal of Glaciology},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  grenfell_2004,
+  author	= {Grenfell, Thomas C.},
+  title		= {Seasonal and spatial evolution of albedo in a
+		  snow-ice-land-ocean environment},
+  year		= 2004,
+  volume	= 109,
+  number	= {C1},
+  issn		= {0148-0227},
+  doi		= {10.1029/2003jc001866},
+  url		= {http://dx.doi.org/10.1029/2003JC001866},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  haapala_2000,
+  author	= {Haapala, Jari},
+  title		= {On the modelling of ice-thickness redistribution},
+  year		= 2000,
+  volume	= 46,
+  number	= 154,
+  pages		= {427–437},
+  issn		= {1727-5652},
+  doi		= {10.3189/172756500781833106},
+  url		= {http://dx.doi.org/10.3189/172756500781833106},
+  journal	= {Journal of Glaciology},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  hibler_1979,
+  author	= {Hibler, W. D.},
+  title		= {A Dynamic Thermodynamic Sea Ice Model},
+  year		= 1979,
+  volume	= 9,
+  number	= 4,
+  month		= {Jul},
+  pages		= {815–846},
+  issn		= {1520-0485},
+  doi		= {10.1175/1520-0485(1979)009<0815:adtsim>2.0.co;2},
+  url		= {http://dx.doi.org/10.1175/1520-0485(1979)009<0815:adtsim>2.0.co;2},
+  journal	= {Journal of Physical Oceanography},
+  publisher	= {American Meteorological Society}
+}
+
+@Article{	  hibler_1980,
+  author	= {Hibler, W. D.},
+  title		= {Modeling a Variable Thickness Sea Ice Cover},
+  year		= 1980,
+  volume	= 108,
+  number	= 12,
+  month		= {Dec},
+  pages		= {1943–1973},
+  issn		= {1520-0493},
+  doi		= {10.1175/1520-0493(1980)108<1943:mavtsi>2.0.co;2},
+  url		= {http://dx.doi.org/10.1175/1520-0493(1980)108<1943:mavtsi>2.0.co;2},
+  journal	= {Monthly Weather Review},
+  publisher	= {American Meteorological Society}
+}
+
+@Article{	  hoyland_2002,
+  author	= {Høyland, Knut V.},
+  title		= {Consolidation of first-year sea ice ridges},
+  year		= 2002,
+  volume	= 107,
+  number	= {C6},
+  issn		= {0148-0227},
+  doi		= {10.1029/2000jc000526},
+  url		= {http://dx.doi.org/10.1029/2000JC000526},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@techreport{	  kovacs_1996,
+  author	= {Kovacs, Austin},
+  title		= {Sea Ice. Part 1. Bulk Salinity Versus Ice Floe
+		  Thickness,},
+  year		= 1996,
+  month		= {Jun},
+  doi		= {10.21236/ada312027},
+  url		= {http://dx.doi.org/10.21236/ada312027},
+  publisher	= {Defense Technical Information Center}
+}
+
+@Article{	  kreyscher_2000,
+  author	= {Kreyscher, Martin and Harder, Markus and Lemke, Peter and
+		  Flato, Gregory M.},
+  title		= {Results of the Sea Ice Model Intercomparison Project:
+		  Evaluation of sea ice rheology schemes for use in climate
+		  simulations},
+  year		= 2000,
+  volume	= 105,
+  number	= {C5},
+  month		= {May},
+  pages		= {11299–11320},
+  issn		= {0148-0227},
+  doi		= {10.1029/1999jc000016},
+  url		= {http://dx.doi.org/10.1029/1999jc000016},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  lecomte_2011,
+  author	= {Lecomte, Olivier and Fichefet, Thierry and Vancoppenolle,
+		  Martin and Nicolaus, Marcel},
+  title		= {A new snow thermodynamic scheme for large-scale sea-ice
+		  models},
+  year		= 2011,
+  volume	= 52,
+  number	= 57,
+  pages		= {337–346},
+  issn		= {1727-5644},
+  doi		= {10.3189/172756411795931453},
+  url		= {http://dx.doi.org/10.3189/172756411795931453},
+  journal	= {Annals of Glaciology},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  lecomte_2015,
+  author	= {Lecomte, Olivier and Fichefet, Thierry and Flocco, Daniela
+		  and Schroeder, David and Vancoppenolle, Martin},
+  title		= {Interactions between wind-blown snow redistribution and
+		  melt ponds in a coupled ocean–sea ice model},
+  year		= 2015,
+  volume	= 87,
+  month		= {Mar},
+  pages		= {67–80},
+  issn		= {1463-5003},
+  doi		= {10.1016/j.ocemod.2014.12.003},
+  url		= {http://dx.doi.org/10.1016/j.ocemod.2014.12.003},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  lepparanta_1995,
+  author	= {Leppäranta, Matti and Lensu, Mikko and Kosloff, Pekka and
+		  Veitch, Brian},
+  title		= {The life story of a first-year sea ice ridge},
+  year		= 1995,
+  volume	= 23,
+  number	= 3,
+  month		= {May},
+  pages		= {279–290},
+  issn		= {0165-232X},
+  doi		= {10.1016/0165-232x(94)00019-t},
+  url		= {http://dx.doi.org/10.1016/0165-232x(94)00019-t},
+  journal	= {Cold Regions Science and Technology},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  lepparanta_2011,
+  author	= {Leppäranta, Matti},
+  title		= {Drift ice material},
+  year		= 2011,
+  pages		= {11–63},
+  doi		= {10.1007/978-3-642-04683-4\_2},
+  url		= {http://dx.doi.org/10.1007/978-3-642-04683-4\_2},
+  isbn		= 9783642046834,
+  journal	= {The Drift of Sea Ice},
+  publisher	= {Springer Berlin Heidelberg}
+}
+
+@Article{	  lipscomb_2001,
+  author	= {Lipscomb, William H.},
+  title		= {Remapping the thickness distribution in sea ice models},
+  year		= 2001,
+  volume	= 106,
+  number	= {C7},
+  month		= {Jul},
+  pages		= {13989–14000},
+  issn		= {0148-0227},
+  doi		= {10.1029/2000jc000518},
+  url		= {http://dx.doi.org/10.1029/2000jc000518},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  lipscomb_2007,
+  author	= {Lipscomb, William H. and Hunke, Elizabeth C. and
+		  Maslowski, Wieslaw and Jakacki, Jaromir},
+  title		= {Ridging, strength, and stability in high-resolution sea
+		  ice models},
+  year		= 2007,
+  volume	= 112,
+  number	= {C3},
+  month		= {Mar},
+  issn		= {0148-0227},
+  doi		= {10.1029/2005jc003355},
+  url		= {http://dx.doi.org/10.1029/2005JC003355},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  massonnet_2018,
+  author	= {Massonnet, F. and Barth\'el\'emy, A. and Worou, K. and
+		  Fichefet, T. and Vancoppenolle, M. and Rousset, C.},
+  title		= {Insights on the discretization of the ice thickness
+		  distribution in large-scale sea ice models},
+  journal	= {submitted},
+  year		= {2018}
+}
+
+@Article{	  maykut_1971,
+  author	= {Maykut, Gary A. and Untersteiner, Norbert},
+  title		= {Some results from a time-dependent thermodynamic model of
+		  sea ice},
+  year		= 1971,
+  volume	= 76,
+  number	= 6,
+  month		= {Feb},
+  pages		= {1550–1575},
+  issn		= {0148-0227},
+  doi		= {10.1029/jc076i006p01550},
+  url		= {http://dx.doi.org/10.1029/jc076i006p01550},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  maykut_1973,
+  author	= {Maykut, G. A. and Thorndike, A. S.},
+  title		= {An approach to coupling the dynamics and thermodynamics of
+		  Arctic sea ice},
+  journal	= {AIDJEX Bulletin},
+  year		= {1973},
+  volume	= {21},
+  pages		= {23--29}
+}
+
+@Article{	  maykut_1986,
+  author	= {Maykut, Gary A.},
+  title		= {The Surface Heat and Mass Balance},
+  year		= 1986,
+  pages		= {395–463},
+  doi		= {10.1007/978-1-4899-5352-0\_6},
+  url		= {http://dx.doi.org/10.1007/978-1-4899-5352-0\_6},
+  isbn		= 9781489953520,
+  journal	= {The Geophysics of Sea Ice},
+  publisher	= {Springer US}
+}
+
+@Article{	  maykut_1995,
+  author	= {Maykut, G. A. and McPhee, Miles G.},
+  title		= {Solar heating of the Arctic mixed layer},
+  year		= 1995,
+  volume	= 100,
+  number	= {C12},
+  pages		= 24691,
+  issn		= {0148-0227},
+  doi		= {10.1029/95jc02554},
+  url		= {http://dx.doi.org/10.1029/95jc02554},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  mcphee_1992,
+  author	= {McPhee, Miles G.},
+  title		= {Turbulent heat flux in the upper ocean under sea ice},
+  year		= 1992,
+  volume	= 97,
+  number	= {C4},
+  pages		= 5365,
+  issn		= {0148-0227},
+  doi		= {10.1029/92jc00239},
+  url		= {http://dx.doi.org/10.1029/92jc00239},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  mellor_1989,
+  author	= {Mellor, George L. and Kantha, Lakshmi},
+  title		= {An ice-ocean coupled model},
+  year		= 1989,
+  volume	= 94,
+  number	= {C8},
+  pages		= 10937,
+  issn		= {0148-0227},
+  doi		= {10.1029/jc094ic08p10937},
+  url		= {http://dx.doi.org/10.1029/jc094ic08p10937},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  notz_2016,
+  author	= {Notz, Dirk and Jahn, Alexandra and Holland, Marika and
+		  Hunke, Elizabeth and Massonnet, François and Stroeve,
+		  Julienne and Tremblay, Bruno and Vancoppenolle, Martin},
+  title		= {The CMIP6 Sea-Ice Model Intercomparison Project (SIMIP):
+		  understanding sea ice through climate-model simulations},
+  year		= 2016,
+  volume	= 9,
+  number	= 9,
+  month		= {Sep},
+  pages		= {3427–3446},
+  issn		= {1991-9603},
+  doi		= {10.5194/gmd-9-3427-2016},
+  url		= {http://dx.doi.org/10.5194/gmd-9-3427-2016},
+  journal	= {Geoscientific Model Development},
+  publisher	= {Copernicus GmbH}
+}
+
+@Article{	  parmerter_1975,
+  author	= {Parmerter, R. Reid},
+  title		= {A model of simple rafting in sea ice},
+  year		= 1975,
+  volume	= 80,
+  number	= 15,
+  month		= {May},
+  pages		= {1948–1952},
+  issn		= {0148-0227},
+  doi		= {10.1029/jc080i015p01948},
+  url		= {http://dx.doi.org/10.1029/jc080i015p01948},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  perovich_2002,
+  author	= {Perovich, D. K.},
+  title		= {Seasonal evolution of the albedo of multiyear Arctic sea
+		  ice},
+  year		= 2002,
+  volume	= 107,
+  number	= {C10},
+  issn		= {0148-0227},
+  doi		= {10.1029/2000jc000438},
+  url		= {http://dx.doi.org/10.1029/2000JC000438},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  prather_1986,
+  author	= {Prather, Michael J.},
+  title		= {Numerical advection by conservation of second-order
+		  moments},
+  year		= 1986,
+  volume	= 91,
+  number	= {D6},
+  pages		= 6671,
+  issn		= {0148-0227},
+  doi		= {10.1029/jd091id06p06671},
+  url		= {http://dx.doi.org/10.1029/jd091id06p06671},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  pringle_2007,
+  author	= {Pringle, D. J. and Eicken, H. and Trodahl, H. J. and
+		  Backstrom, L. G. E.},
+  title		= {Thermal conductivity of landfast Antarctic and Arctic sea
+		  ice},
+  year		= 2007,
+  volume	= 112,
+  number	= {C4},
+  month		= {Apr},
+  issn		= {0148-0227},
+  doi		= {10.1029/2006jc003641},
+  url		= {http://dx.doi.org/10.1029/2006JC003641},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  schmidt_2004,
+  author	= {Schmidt, Gavin A. and Bitz, Cecilia M. and Mikolajewicz,
+		  Uwe and Tremblay, L.-Bruno},
+  title		= {Ice–ocean boundary conditions for coupled models},
+  year		= 2004,
+  volume	= 7,
+  number	= {1-2},
+  month		= {Jan},
+  pages		= {59–74},
+  issn		= {1463-5003},
+  doi		= {10.1016/s1463-5003(03)00030-1},
+  url		= {http://dx.doi.org/10.1016/S1463-5003(03)00030-1},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  shine_1985,
+  author	= {Shine, K. P. and Henderson-Sellers, A.},
+  title		= {The sensitivity of a thermodynamic sea ice model to
+		  changes in surface albedo parameterization},
+  year		= 1985,
+  volume	= 90,
+  number	= {D1},
+  pages		= 2243,
+  issn		= {0148-0227},
+  doi		= {10.1029/jd090id01p02243},
+  url		= {http://dx.doi.org/10.1029/jd090id01p02243},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Book{		  teos-10_2010,
+  title		= {{The international thermodynamic equation of seawater -
+		  2010: Calculation and use of thermodynamic properties}},
+  publisher	= {UNESCO (English)},
+  year		= {2010},
+  author	= {{IOC, SCOR and IAPSO}},
+  series	= {Intergovernmental Oceanographic Commission, Manuals and
+		  Guides No. 56},
+  url =          {http://www.teos-10.org/pubs/TEOS-10_Manual.pdf}
+}
+
+@Article{	  thorndike_1975,
+  author	= {Thorndike, A. S. and Rothrock, D. A. and Maykut, G. A. and
+		  Colony, R.},
+  title		= {The thickness distribution of sea ice},
+  year		= 1975,
+  volume	= 80,
+  number	= 33,
+  month		= {Nov},
+  pages		= {4501–4513},
+  issn		= {0148-0227},
+  doi		= {10.1029/jc080i033p04501},
+  url		= {http://dx.doi.org/10.1029/JC080i033p04501},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  tuhkuri_2002,
+  author	= {Tuhkuri, Jukka},
+  title		= {Laboratory tests on ridging and rafting of ice sheets},
+  year		= 2002,
+  volume	= 107,
+  number	= {C9},
+  issn		= {0148-0227},
+  doi		= {10.1029/2001jc000848},
+  url		= {http://dx.doi.org/10.1029/2001JC000848},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  vancoppenolle_2009,
+  author	= {Vancoppenolle, Martin and Fichefet, Thierry and Goosse,
+		  Hugues},
+  title		= {Simulating the mass balance and salinity of Arctic and
+		  Antarctic sea ice. 2. Importance of sea ice salinity
+		  variations},
+  year		= 2009,
+  volume	= 27,
+  number	= {1-2},
+  month		= {Jan},
+  pages		= {54–69},
+  issn		= {1463-5003},
+  doi		= {10.1016/j.ocemod.2008.11.003},
+  url		= {http://dx.doi.org/10.1016/j.ocemod.2008.11.003},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  weiss_2013,
+  author	= {Weiss, Jérôme},
+  title		= {Drift, Deformation, and Fracture of Sea Ice},
+  year		= 2013,
+  issn		= {2191-5377},
+  doi		= {10.1007/978-94-007-6202-2},
+  url		= {http://dx.doi.org/10.1007/978-94-007-6202-2},
+  isbn		= 9789400762022,
+  journal	= {SpringerBriefs in Earth Sciences},
+  publisher	= {Springer Netherlands}
+}
+
+@Article{	  worster_1992,
+  author	= {Worster, M. G.},
+  title		= {The Dynamics of Mushy Layers},
+  year		= 1992,
+  pages		= {113–138},
+  doi		= {10.1007/978-94-011-2809-4\_20},
+  url		= {http://dx.doi.org/10.1007/978-94-011-2809-4\_20},
+  isbn		= 9789401128094,
+  journal	= {Interactive Dynamics of Convection and Solidification},
+  publisher	= {Springer Netherlands}
+}
+
+@Article{	  zhang_2001,
+  author	= {Zhang, Jinlun and Rothrock, Drew},
+  title		= {A Thickness and Enthalpy Distribution Sea-Ice Model},
+  year		= 2001,
+  volume	= 31,
+  number	= 10,
+  month		= {Oct},
+  pages		= {2986–3001},
+  issn		= {1520-0485},
+  doi		= {10.1175/1520-0485(2001)031<2986:ataeds>2.0.co;2},
+  url		= {http://dx.doi.org/10.1175/1520-0485(2001)031<2986:ataeds>2.0.co;2},
+  journal	= {Journal of Physical Oceanography},
+  publisher	= {American Meteorological Society}
+}
+
+@Article{	  zuo_1996,
+  author	= {Zuo, Z. and Oerlemans, J.},
+  title		= {Modelling albedo and specific balance of the Greenland ice
+		  sheet: calculations for the Søndre Strømfjord transect},
+  year		= 1996,
+  volume	= 42,
+  number	= 141,
+  pages		= {305–317},
+  issn		= {1727-5652},
+  doi		= {10.1017/s0022143000004160},
+  url		= {http://dx.doi.org/10.1017/s0022143000004160},
+  journal	= {Journal of Glaciology},
+  publisher	= {Cambridge University Press (CUP)}
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/chapters.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/chapters.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/chapters.tex	(revision 14097)
@@ -0,0 +1,14 @@
+\subfile{../subfiles/todolist}
+
+\subfile{../subfiles/chap_model_basics}
+\subfile{../subfiles/chap_domain}
+\subfile{../subfiles/chap_dynamics}
+\subfile{../subfiles/chap_transport}
+\subfile{../subfiles/chap_ridging_rafting}
+\subfile{../subfiles/chap_radiative_transfer}
+\subfile{../subfiles/chap_thermo}
+\subfile{../subfiles/chap_interfaces}
+\subfile{../subfiles/chap_output_diagnostics}
+\subfile{../subfiles/chap_single_category_use}
+\subfile{../subfiles/chap_bdy_agrif}
+\subfile{../subfiles/chap_miscellaneous}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/introduction.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/introduction.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/introduction.tex	(revision 14097)
@@ -0,0 +1,63 @@
+
+% ================================================================
+% INTRODUCTION
+% ================================================================
+
+\chapter*{Introduction}
+
+\textcolor{red}{[ \textit{July 2018} ]} \\
+
+%Near the poles of the Earth, the seas and oceans freeze when seawater at the freezing point loses heat. The resulting forms of saline ice are collectively called \textit{sea ice} \citep{WMO70}, reaching up to a few meters in thickness, where as sea ice coverage is about 5\% of the global ocean, about 30 million square kilometers. All sea ice characteristics vary over a wide range of spatio-temporal scales, reflecting changes in heat, mass and momentum exchanges with the atmosphere and the ocean; the clearest temporal signal being an ample seasonal cycle. Sea ice formation and melting affects water mass formation in the ocean \citep{goosse_1999}. It not only impacts, but also reflects the state of the climate system \citep{budyko_1969,notz_2016}.  Sea ice also affects marine life, water chemistry and human activities in polar regions. Local populations use sea ice for travelling and hunting, whereas navigation and resource exploitation are dependent on sea ice conditions. For such reasons, ocean modelling systems, including \NEMO, must include a sea ice component.
+
+\SIcube\ is the result of the recommendation of the Sea Ice Working Group (SIWG) to
+reduce duplication and better use development resources.
+\SIcube\ merges the capabilities of the 3 formerly sea ice models used in \NEMO\ (CICE, GELATO and LIM).
+The \textbf{3} in \SIcube\ refers either to the three formerly used sea ice models and
+linkages between 3 different media (ocean-ice-snow).
+The model would be pronounced as ``SI cube'' for short (or ``Sea Ice cubed'' for slightly longer),
+otherwise it can be spelt ``SI three'' in situations where the superscript could be problematic.
+
+% Limitations & scope
+%There are limitations to the applicability of models such as \SIcube. The continuum approach is not invalid for grid cell size above at least 1 km, below which sea ice particles may include just a few floes, which is not sufficient \citep{lepparanta_2011}. Second, one must remember that our current knowledge of sea ice is not as complete as for the ocean: there are no fundamental equations such as Navier Stokes equations for sea ice. Besides, important features and processes span widely different scales, such as brine inclusions (1 $\mu$m-1 mm) \citep{perovich_1996}, horizontal thickness variations (1 m-100 km) \citep{percival_2008}, deformation and fracturing (10 m-1000 km) \citep{marsan_2004}. These impose complicated and often subjective subgrid-scale treatments. All in all, there is more empiricism in sea ice models than in ocean models.
+
+In order to handle all the subsequent required subjective choices, we applied the following guidelines or principles:
+\begin{itemize}
+\item Sea ice is frozen seawater that is in tight interaction with the underlying ocean. This close connexion suggests that the sea ice and ocean model components must be as consistent as possible. In practice, this is materialized by the close match between LIM and \NEMO, in terms of numerical choices, regarding the grid (Arakawa C-type) and the numerical discretization (finite differences with \NEMO\ scale factors).
+\item It is useful to be able to either prescribe the atmospheric state or to use an atmospheric model. For consistency and simplicity of the code, we choose to use formulations as close as possible in both cases.
+\item Different resolutions and time steps can be used. There are parameters that depend on such choices. We thrived to achieve a resolution and time-step independent code, by imposing a priori scaling on the resolution / time step dependence of such parameters.
+\item Energy, mass and salt must be conserved as much as possible.
+\end{itemize}
+
+This manual is organised as follows. \\
+
+List of chapters... \\
+
+There are no more CPP keys in the code. \\
+
+Namelists and output management follow \NEMO\ guidelines. \\
+
+Changes between releases. \\
+
+The list of people that should be acknowledged is too long, but a great number of people or more exactly a number of great people contributed to the code and should be gratefully acknowledged. As for today,
+the SIWG members are \textit{(July 2018)}.
+
+\begin{itemize}
+\begin{footnotesize}
+\item Yevgeny Aksenov (NOCS, Southampton, UK)
+\item Ed Blockley (Met Office, Exeter, UK, co-chair)
+\item Matthieu Chevallier (CNRM-GAME, M\'et\'eo France, Toulouse)
+\item Danny Feltham (CPOM, Reading, UK)
+\item Thierry Fichefet (UCL, Louvain-la-Neuve, Belgium)
+\item Gilles Garric (Mercator-Oc\'ean, Toulouse, France)
+\item Paul Holland (BAS, Cambridge, UK)
+\item Dorotea Iovino (CMCC, Bologna, Italy)
+\item Gurvan Madec (LOCEAN, CNRS, Paris, France)
+\item Fran\c cois Massonnet (UCL, Louain-la-Neuve, Belgium)
+\item Jeff Ridley (Met Office, Exeter, UK)
+\item Cl\'ement Rousset (LOCEAN, CNRS, Paris, France)
+\item David Salas (CNRM-GAME, M\'et\'eo France, Toulouse)
+\item David Schroeder (CPOM, Reading, UK)
+\item Steffen Tietsche (ECMWF, Reading, UK)
+\item Martin Vancoppenolle (LOCEAN, CNRS, Paris, France, co-chair)
+\end{footnotesize}
+\end{itemize}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/settings.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/settings.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/settings.tex	(revision 14097)
@@ -0,0 +1,20 @@
+%% Engine (folder name)
+\def \engine{SI3}
+
+%% Title and cover page settings
+\def \spacetop{  \vspace*{1.2cm} }
+\def \heading{Sea Ice modelling Integrated Initiative (SI$^3$)}
+\def \subheading{The NEMO sea ice engine}
+\def \spacedown{ \vspace*{  1cm} }
+\def \authorswidth{0.2\linewidth}
+\def \rulelenght{230pt}
+\def \abstractwidth{0.65\linewidth}
+
+%% Color for document (frontpage banner, links and chapter boxes)
+\def \setmanualcolor{ \definecolor{manualcolor}{cmyk}{0, 0, 0, 0.4} }
+
+%% IPSL publication number
+\def \ipslnum{31}
+
+%% Zenodo ID, i.e. doi:10.5281/zenodo.\([0-9]*\)
+\def \zid{1471689}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/main/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namdyn_adv
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namdyn_adv	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namdyn_adv	(revision 14097)
@@ -0,0 +1,7 @@
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .true.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .false.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namsbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namsbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/namelists/namsbc	(revision 14097)
@@ -0,0 +1,14 @@
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+   rn_cio           =   5.0e-03       !  ice-ocean drag coefficient (-)
+   rn_blow_s        =   0.66          !  mesure of snow blowing into the leads
+                                      !     = 1 => no snow blowing, < 1 => some snow blowing
+   nn_flxdist       =  -1             !  Redistribute heat flux over ice categories
+                                      !     =-1  Do nothing (needs N(cat) fluxes)
+                                      !     = 0  Average N(cat) fluxes then apply the average over the N(cat) ice
+                                      !     = 1  Average N(cat) fluxes then redistribute over the N(cat) ice using T-ice and albedo sensitivity
+                                      !     = 2  Redistribute a single flux over categories
+   ln_cndflx        = .false.         !  Use conduction flux as surface boundary conditions (i.e. for Jules coupling)
+      ln_cndemulate = .false.         !     emulate conduction flux (if not provided in the inputs)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/abstract_foreword.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/abstract_foreword.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/abstract_foreword.tex	(revision 14097)
@@ -0,0 +1,44 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Abstract
+% ================================================================
+
+\chapter*{Abstract}
+
+SI$^3$ (Sea Ice modelling Integrated Initiative) is the sea ice engine of NEMO (Nucleus for European Modelling of the Ocean). It is adapted to regional and global sea ice and climate problems. It is intended to be a flexible tool for studying sea ice and its interactions with the other components of the Earth System over a wide range of space and time scales. SI$^3$ is based on the Arctic Ice Dynamics Joint EXperiment (AIDJEX) framework \citep{coon_1974}, combining the ice thickness distribution framework, the conservation of horizontal momentum, an elastic-viscous plastic rheology, and energy-conserving halo-thermodynamics. Prognostic variables are the two-dimensional horizontal velocity field, ice volume, area, enthalpy, salt content, snow volume and enthalpy. In the horizontal direction, the model uses a curvilinear orthogonal grid. In the vertical direction, the model uses equally-spaced layers. In thickness space, the model uses thickness categories with prescribed boundaries. Various physical and numerical choices are available to describe sea ice physics. SI$^3$ is interfaced with the NEMO ocean engine, and, via the OASIS coupler, with several atmospheric general circulation models. It also supports two-way grid embedding via the AGRIF software.
+
+%\vspace{-40pt}
+
+{\small
+} 
+
+% ================================================================
+% Disclaimer
+% ================================================================
+\chapter*{Disclaimer}
+
+Like all components of NEMO, the sea ice component is developed under the \href{http://www.cecill.info/}{CECILL license}, 
+which is a French adaptation of the GNU GPL (General Public License). Anyone may use it 
+freely for research purposes, and is encouraged to communicate back to the NEMO team 
+its own developments and improvements. The model and the present document have been 
+made available as a service to the community. We cannot certify that the code and its manual 
+are free of errors. Bugs are inevitable and some have undoubtedly survived the testing phase. 
+Users are encouraged to bring them to our attention. The authors assume no responsibility 
+for problems, errors, or incorrect usage of NEMO.
+
+\vspace{1cm}
+SI3 reference in papers and other publications is as follows:
+\vspace{0.5cm}
+
+The NEMO Sea Ice Working Group, 2018: SI$^3$ -- Sea Ice modelling Integrated Initiative -- The NEMO Sea Ice Engine, \textit{Note du P\^ole de mod\'{e}lisation}, Institut Pierre-Simon Laplace (IPSL), France, 
+No XX, ISSN No 1288-1619.\\
+
+\vspace{0.5cm}
+Additional information can be found on \href{http://www.nemo-ocean.eu/}{www.nemo-ocean.eu}.
+\vspace{0.5cm}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_bdy_agrif.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_bdy_agrif.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_bdy_agrif.tex	(revision 14097)
@@ -0,0 +1,16 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 11 - BDY and AGRIF with SI$^3$
+% ================================================================
+
+\chapter{BDY and AGRIF with SI$^3$}
+\label{chap:REG}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_domain.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_domain.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_domain.tex	(revision 14097)
@@ -0,0 +1,106 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 2 Ñ Domain
+% ================================================================
+
+\chapter{Time, space and thickness space domain}
+\label{chap:DOM}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+Having defined the model equations in previous Chapter, we need now to choose the numerical discretization.  In the present chapter, we provide a general description of the SI$^3$ discretization strategy, in terms of time, space and thickness, which is considered as an extra independent variable. 
+
+Sea ice state variables are typically expressed as:
+\begin{equation}
+X(ji,jj,\textcolor{gray}{jk},jl).
+\end{equation}
+$ji$ and $jj$ are x-y spatial indices, as in the ocean. $jk=1, ..., nlay\_i$ corresponds to the vertical coordinate system in sea ice (ice layers), and only applies to vertically-resolved quantities (ice enthalpy and salinity). $jl=1, ..., jpl$ corresponds to the ice categories, discretizing thickness space.
+
+\section{Time domain}
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Time Stepping
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=6cm,angle=-00]{time_stepping}
+\caption{Schematic representation of time stepping in SI$^3$, assuming $nn\_fsbc=5$.}
+\label{ice_scheme}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+The sea ice time stepping is synchronized with that of the ocean. Because of the potentially large numerical cost of sea ice physics, in particular rheology, SI$^3$ can be called every nn\_fsbc time steps (namsbc in \textit{namelist\_ref}). The sea ice time step is therefore $rdt\_ice = rdt * nn\_fsbc$. In terms of quality, the best value for \textit{nn\_fsbc} is 1, providing full consistency between sea ice and oceanic fields. Larger values (typically 2 to 5) can be used but numerical instabilities can appear because of the progressive decoupling between the state of sea ice and that of the ocean, hence changing $nn\_fsbc$ must be done carefully.
+
+Ice dynamics (rheology, advection, ridging/rafting) and thermodynamics are called successively. To avoid pathological situations, thermodynamics were chosen to be applied on fields that have been updated by dynamics, in a somehow semi-implicit procedure.
+
+There are a few iterative / subcycling procedures throughout the code, notably for rheology, advection, ridging/ rafting and the diffusion of heat. In some cases, the arrays at the beginning of the sea ice time step are required. Those are referred to as $X\_b$.
+
+\section{Spatial domain}
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIGx : Vertical grid
+%
+%
+\begin{figure}[!ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=10cm,angle=-00]{thermogrid.eps}
+\caption{\footnotesize{Vertical grid of the model, used to resolve vertical temperature and salinity profiles}}\label{fig_dom_icelayers}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+The horizontal indices $ji$ and $jj$ are handled as for the ocean in NEMO, assuming C-grid discretization and in most cases a finite difference expression for scale factors.
+
+The vertical index $jk=1, ..., nlay\_i$ is used for enthalpy (temperature) and salinity. In each ice category, the temperature and salinity profiles are vertically resolved over $nlay\_i$ equally-spaced layers. The number of snow layers can currently only be set to $nlay\_s=1$ (Fig. \ref{fig_dom_icelayers}).
+
+To increase numerical efficiency of the code, the two horizontal dimensions of an array $X(ji,jj,jk,jl)$ are collapsed into one (array $X\_1d(ji,jk,jl)$) for thermodynamic computations, and re-expanded afterwards.
+
+\nlst{nampar}
+
+\section{Thickness space domain}
+
+\nlst{namitd}
+
+Thickness space is discretized using $jl=1, ..., jpl$ thickness categories, with prescribed boundaries $hi\_max(jl-1),hi\_max(jl)$. Following \cite{lipscomb_2001}, ice thickness can freely evolve between these boundaries. The number of ice categories $jpl$ can be adjusted from the namelist ($nampar$).
+
+There are two means to specify the position of the thickness boundaries of ice categories. The first option (ln\_cat\_hfn) is to use a fitting function that places the category boundaries between 0 and 3$\overline h$, with $\overline h$ the expected mean ice thickness over the domain (namelist parameter rn\_himean), and with a greater resolution for thin ice (Fig. \ref{fig_dom_icecats}). More specifically, the upper limits for ice in category $jl=1, ..., jpl-1$ are:
+\begin{eqnarray} 
+hi\_max(jl) = \biggr ( \frac{jl \cdot (3\overline h + 1 )^{\alpha}}{ (jpl-jl)(3 \overline h + 1)^{\alpha} + jl }\biggr )^{\alpha^{-1}} - 1,
+\end{eqnarray}
+with $hi\_max(0)$=0 m and $\alpha = 0.05$. The last category has no upper boundary, so that it can contain arbitrarily thick ice.
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIGx : Ice categories
+%
+%
+\begin{figure}[!ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=6cm,angle=-00]{ice_cats.eps}
+\caption{\footnotesize{Boundaries of the model ice thickness categories (m) for varying number of categories and prescribed mean thickness ($\overline h$). The formerly used $tanh$ formulation is also depicted.}}\label{fig_dom_icecats}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+The other option (ln\_cat\_usr) is to specify category boundaries by hand using rn\_catbnd. The first category must always be thickner than rn\_himin (0.1 m by default).
+
+The choice of ice categories is important, because it constraints the ability of the model to resolve the ice thickness distribution. The latest study \citep{massonnet_2018} recommends to use at least 5 categories, which should include one thick ice with lower bounds at $\sim$4 m and $\sim$2 m for the Arctic and Antarctic, respectively, for allowing the storage of deformed ice.
+
+With a fixed number of cores, the cost of the model linearly increases with the number of ice categories. Using $jpl=1$ single ice category is also much cheaper than with 5 categories, but seriously deteriorates the ability of the model to grow and melt ice. Indeed, thin ice thicknes faster than thick ice, and shrinks more rapidly as well. When nn\_virtual\_itd=1 ($jpl$ = 1 only), two parameterizations are activated to compensate for these shortcomings. Heat conduction and areal decay of melting ice are adjusted to closely approach the 5 categories case.
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_dynamics.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_dynamics.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_dynamics.tex	(revision 14097)
@@ -0,0 +1,35 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 3 Ñ Ice dynamics
+% ================================================================
+
+\chapter{Ice dynamics}
+\label{chap:DYN}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+In this chapter, we describe how the momentum equation is solved.
+
+I guess we could be brief. Gurvan and Clem should take the lead to write this.
+
+1) aEVP approach, revisited by Bouillon et al (2013).
+
+2) Short description of the numerical method. NEMO scale factors.
+
+3) Landfast ice option
+
+4) Boundary conditions (free-slip, no-slip, ...)
+
+4) Practical use of namelist parameters (nevp, telast, ...).
+
+\end{document}
+
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_interfaces.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_interfaces.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_interfaces.tex	(revision 14097)
@@ -0,0 +1,30 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 8 Ñ Interfaces
+% ================================================================
+
+\chapter{Ice-atmosphere and ice-ocean interfaces}
+\label{chap:INT}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+In this chapter, we give information on the representation of interfaces.
+
+\section{Ice-ocean interface}
+
+\section{Ice-atmosphere interface}
+
+Drags?
+
+Blowing snow parameter
+
+Flux redistributor
+
+Jules coupling
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_miscellaneous.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_miscellaneous.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_miscellaneous.tex	(revision 14097)
@@ -0,0 +1,18 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 12 -Miscellaneous
+% ================================================================
+
+\chapter{Miscellaneous topics}
+\label{chap:MIS}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+getting started, namelists, configs, ...
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_model_basics.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_model_basics.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_model_basics.tex	(revision 14097)
@@ -0,0 +1,457 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+% ================================================================
+% Chapter 1 Ñ Model Basics
+% ================================================================
+
+\chapter{Model Basics}
+\label{chap:MB}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+%-------------------------------------------------------------------------------------------------------------------------
+%
+% 2.1 Assumptions
+\section{Rationale and assumptions}
+%
+%-------------------------------------------------------------------------------------------------------------------------
+\begin{itemize}
+\item Separation of horizontal dynamics and vertical thermodynamics;
+\item Dynamics: sea ice is a viscous-plastic continuum;
+\item Thermodynamics: sea ice is a mushy layer covered by snow
+\item Subgrid-scale physics
+\end{itemize}
+
+\subsection{Scales, thermodynamics and dynamics}
+Because sea ice is much wider -- $\mathcal{O}$(100-1000 km) -- than thick -- $\mathcal{O}$(1 m) -- ice drift can be considered as purely horizontal: vertical motions around the hydrostatic equilibrium position are negligible. The same scaling argument justifies the assumption that heat exchanges are purely vertical\footnote{The latter assumption is probably less valid, because the horizontal scales of temperature variations are $\mathcal{O}$(10-100 m)}. It is on this basis that thermodynamics and dynamics are separated and rely upon different frameworks and sets of hypotheses: thermodynamics use the ice thickness distribution \citep{thorndike_1975} and the mushy-layer \citep{worster_1992} frameworks, whereas dynamics assume continuum mechanics \citep[e.g.,][]{lepparanta_2011}. Thermodynamics and dynamics interact by two means: first, advection impacts state variables; second, the horizontal momentum equation depends, among other things, on the ice state.
+
+\subsection{Subgrid scale variations}
+
+Sea ice properties -- in particular ice thickness -- feature important changes at horizontal scales $\mathcal{O}$(1m) \citep{thorndike_1975}. An explicit representation of these variations is not and will not be -- at least in the next twenty years or so -- accessible to large-scale sea ice models. Yet important features, such as energy exchanges through the ice, quite non-linearly depend on ice thickness \citep{maykut_1986}; whereas ice motion depends on the presence of open water, thin and thick ice at the very least, suggesting that subgrid-scale variations in ice properties must be accounted for, at least in a statistical fashion \citep{maykut_1973}. 
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Ice scheme
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=10cm,angle=-00]{ice_scheme}
+\caption{Representation of the ice pack, using multiple categories with specific ice concentration ($a_l, l=1, 2, ..., L$), thickness ($h^i_l$), snow depth ($h^s_l$), vertical temperature and salinity profiles ($T^i_{kl}$, $S^{*}_{kl}$) and a single ice velocity vector ($\mathbf{u}$).}
+\label{ice_scheme}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+The \textit{multi-category} framework \citep{maykut_1973} addresses this issue by treating the ice thickness as an independent variable next to spatial coordinates and time, and introducing a thickness distribution\footnote{$g(h)$, termed the \textit{ice thickness distribution} is the density of probability of ice thickness \citep{thorndike_1975}.} $g(h)$ as the main prognostic model field. In the discrete world, the thickness distribution is converted into $L$ thickness categories. Ice thickness categories occupy a fraction of each grid cell, termed ice concentration ($a_l, l=1, 2, ..., L$), with specific thickness and properties. 
+
+The \textit{single-category} framework \citep{hibler_1979} tackles the subgrid-scale issue by drastically simplifying the ice thickness distribution. The grid cell is divided into open water and sea ice characterized by a single ice concentration $A$ and mean thickness $H$. Single-category models (in particular LIM2) typically add parameterizations to represent the effects of unresolved ice thickness distribution on ice growth and melt \citep[see, e.g.][]{mellor_1989,fichefet_1997}.
+
+SI$^3$ provides the choice between either a multi- or a single-category framework. The default mode is multi-category. The single-category mode can be activated by setting the number of categories ($jpl=1$) and by activating the virtual thickness distribution parameterizations (nn\_monocat=1).
+
+\subsection{Thermodynamic formulation}
+
+%
+%--------------------------------------------------------------------------------------------------------------------
+%
+% TABLE x Physical constants
+%
+%
+\begin{table}[ht]
+\begin{footnotesize}
+\caption{Thermodynamic constants of the model.}
+\begin{center}
+\begin{tabular}{@{}llccl}\hline
+ & Description & Value & Units & Ref \\ \hline
+$c_i$ (cpic) & Pure ice specific heat & 2067 & J/kg/K & ? \\
+$c_w$ (rcp) & Seawater specific heat & 3991 & J/kg/K & \cite{teos-10_2010} \\
+$L$ (lfus) & Latent heat of fusion (0$^\circ$C) & 334000 & J/kg/K & \cite{bitz_1999} \\
+$\rho_i$ (rhoic) & Sea ice density & 917 & kg/m$^3$ & \cite{bitz_1999} \\
+$\rho_s$ (rhosn) & Snow density & 330 & kg/m$^3$ & \cite{maykut_1971} \\
+$\mu$ (tmut) & Linear liquidus coefficient & 0.054 & $^\circ$C/(g/kg) & \cite{assur_1958} \\
+\hline
+\end{tabular}
+\end{center}
+\label{PhysicalConstants_table}
+\end{footnotesize}
+\end{table}
+%
+%--------------------------------------------------------------------------------------------------------------------
+%
+
+Ice thermodynamics are formulated assuming that sea ice is covered by snow. Within each thickness category, both snow and sea ice are horizontally uniform, hence each thickness category has a specific ice thickness ($h_i^l$) and snow depth ($h_s^l$). Snow is assumed to be fresh, with constant density and thermal conductivity. Sea ice is assumed to be a \textit{mushy layer}\footnote{Mushy layers are two-phase, two-component porous media.} \citep{worster_1992} of constant density, made of pure ice and brine in thermal equilibrium, related by a linear liquidus relationship \citep{bitz_1999}. A vertically-averaged bulk salinity $S_l$ uniquely characterizes brine fraction for each thickness category, and changes through  time from a simple parametrization of brine drainage. The linear vertical salinity profile ($S^*_{kl}$) is reconstructed from the vertical mean \citep{vancoppenolle_2009}. The diffusion of heat affects the vertical temperature profile, discretized on a unique layer of snow and multiple ice layers (typically 2-5) for each category, whereas thermal properties depend on local brine fraction. Growth and melt rates are computed, also for each ice category. The choice of the main thermodynamic constants  is described in Tab. \ref{PhysicalConstants_table}.
+
+
+
+%
+%--------------------------------------------------------------------------------------------------------------------
+%
+% TABLE x Global variables
+%
+%
+\begin{table}[ht]
+\begin{footnotesize}
+\caption{LIM global variables.}
+\begin{center}
+\begin{tabular}{@{}llcc}\hline
+Symbol   & Description & Units & Code name \\ \hline
+$\mathbf{u}$ & Sea ice velocity & [$m.s^{-1}$] & \textit{u\_ice, v\_ice (ji,jj)} \\
+$\mathbf{\sigma}$ & Stress tensor & [$Pa.m$] & \textit{stress1\_i, stress2\_i} \\
+ & & & \textit{stress12\_i (ji,jj)} \\
+$a_l$ & Concentration of sea ice in category $l$ & [-] & \textit{a\_i(ji,jj,jl)} \\
+$v^i_l$ & Volume of sea ice per unit area in category $l$ & [$m$] & \textit{v\_i(ji,jj,jl)} \\
+$v^s_l$ & Volume of snow per unit area in category $l$ & [$m$] & \textit{v\_s(ji,jj,jl)} \\
+$e^i_{kl}$ & Sea ice enthalpy per unit area in layer $k$ and category $l$ & [$J.m^{-2}$] & \textit{e\_i(ji,jj,jk,jl)} \\
+$e^s_{l}$ & Snow enthalpy per unit area in category $l$ & [$J.m^{-2}$] & \textit{e\_s(ji,jj,jl)} \\
+$M^s_l$ & Sea ice salt content in category $l$ & [$g/kg.m$] & \textit{smv\_i(ji,jj,jl)}\\
+%$O_l$ & Sea ice age content in category $l$ & $[days.m]$ \\
+\hline
+\end{tabular}
+\end{center}
+\label{GVariables_table}
+\end{footnotesize}
+\end{table}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+ Temperature, salinity, ice thickness, and snow depth are not extensive variables and therefore not conservative. Hence, conservative, extensive variables, must be introduced to ensure mass, salt and energy conservation. There are several back-and-forth conversions from extensive (conservative) state variables (see Table \ref{GVariables_table}) to intensive state variables of practical use (Table \ref{IVariables_table}).
+ 
+ %--------------------------------------------------------------------------------------------------------------------
+%
+% TABLE x Equivalent variables
+%
+%
+\begin{table}[ht]
+\begin{footnotesize}
+\caption{Intensive variables of practical use.}
+\begin{center}
+\begin{tabular}{@{}llcc}\hline
+Symbol   & Description & Units \\ \hline
+$h^i_l=v^i_l/g^i_l$ & Ice thickness & [$m$] \\
+$h^s_l=v^s_l/g^i_l$ & Snow depth & [$m$] \\
+$q^i_{m,kl}=e^i_{l,k}/(h^i_l/N)$ & Ice specific enthalpy & [$J.kg^{-1}$]\\
+$q^s_{m,l}=e^s_{l}/h^s_l$ & Snow specific enthalpy & [$J.kg^{-1}$] \\
+$T^i_{kl}=T(q^i_{kl})$ & Ice temperature & [$K$] \\
+$T^s_{l} =T(q^s_{l}) $ & Snow temperature & [$K$] \\
+$\overline S^i_{l}=M^s_l / v^i_l$ & Vertically-averaged bulk ice salinity & [g/kg] \\
+$S^*_{kl}$ & Depth-dependent ice salinity & [g/kg] \\
+$\phi_{kl}$ & Brine fraction & [-] \\
+%$o^i_{l}=O_l / g^i_l $ & Ice age & [$days$] \\
+\hline
+\end{tabular}
+\end{center}
+\label{IVariables_table}
+\end{footnotesize}
+\end{table}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+\subsection{Dynamic formulation}
+
+The formulation of ice dynamics is based on the continuum approach. The latter holds provided the drift ice particles are much larger than single ice floes, and much smaller than typical gradient scales. This compromise is rarely achieved in practice \citep{lepparanta_2011}. Yet the continuum approach generates a convenient momentum equation for the horizontal ice velocity vector $\mathbf{u}=(u,v)$, which can be solved with classical numerical methods (here, finite differences on the NEMO C-grid). The most important term in the momentum equation is internal stress. We follow the viscous-plastic (VP) rheological framework \citep{hibler_1979}, assuming that sea ice has no tensile strength but responds to compressive and shear deformations in a plastic way. In practice, the elastic-viscous-plastic (EVP) technique of  \citep{bouillon_2013} is used, more convient numerically than VP.  It is well accepted that the VP rheology and its relatives are the minimum complexity to get reasonable ice drift patterns \citep{kreyscher_2000}, but fail at generating the observed deformation patterns \citep{girard_2009}. This is a long-lasting problem: what is the ideal rheological model for sea ice and how it should be applied are still being debated \citep[see, e.g.][]{weiss_2013}. 
+
+%-------------------------------------------------------------------------------------------------------------------------
+%
+\section{Thickness distribution framework}
+%
+%-------------------------------------------------------------------------------------------------------------------------
+
+We first present the essentials of the thickness distribution framework \citep{thorndike_1975}. Consider a given region of area $R$ centered at spatial coordinates $(\mathbf{x})$ at a given time $t$. $R$ could be e.g. a model grid cell. The ice thickness distribution $g(\mathbf{x},t, h)$ is introduced as follows:
+\begin{linenomath}
+\begin{align}
+g(h) &= \lim_{dh \to 0} \frac{dA(h,h+dh)}{dh},
+\end{align}
+\end{linenomath}
+where $dA(h,h+dh)$ is the surface fraction of all parts of $R$ with ice thickness between $h$ and $h+dh$. Using this definition, the spatial structure of ice thickness is lost (see Fig. \ref{fig_g_h}), and $h$ becomes an extra independent variable, next to spatial coordinates and time, that can be thought as random. $g$ is by definition normalized to 1. The conservation of area, expressed in terms of $g(h)$, is given by \citep{thorndike_1975}: 
+\begin{linenomath}
+\begin{align}
+\frac{\partial g}{\partial t} = - \nabla .(g \mathbf{u}) - \frac{\partial}{\partial h} (f g) + \psi,
+\label{eq:gt}
+\end{align}
+\end{linenomath}
+where the terms on the right hand side refer to horizontal transport, thermodynamic transport in thickness space ($f$, m/s is the growth/melt rate), and mechanical redistribution rate, e.g. by ridging and rafting, where $\psi$ must conserve ice area and volume by construction.
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Ice thickness distribution
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=6cm,angle=-00]{g_h}
+\caption{Representation of the relation between real thickness profiles and the ice thickness distribution function $g(h)$}
+\label{fig_g_h}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+In numerical implementations, the thickness distribution is discretized into several thickness categories, with specific ice concentration $a_l$ and ice volume per area $v_l^i$:
+\begin{linenomath}
+\begin{align}
+a_l &= \int _{H^*_{l-1}}^{H^*_l} dh \cdot g(h) , \\
+v_l^i &= \int _{H^*_{l-1}}^{H^*_l} dh \cdot h \cdot g(h).
+\end{align}
+\end{linenomath}
+Ice volume per area is the extensive counterpart for ice thickness, connected with volume through $h_l^i = v_l^i / a_l$. Evolution equations for extensive variables can be readily derived from equation \ref{eq:gt} by integration between thickness boundaries of the $l^{th}$ category \citep{bitz_2001}. This applies to all model extensive variables (see Table \ref{GVariables_table}). For ice area, this reads:
+\begin{linenomath}
+\begin{align}
+\frac{\partial a_l}{\partial t} = - \mathbf{\nabla} \cdot (a_l \mathbf{u}) + \Theta^a_l + \int_{H^*_{l-1}}^{H^*_l} dh \psi.
+\label{eq:gt}
+\end{align}
+\end{linenomath}
+wher $\Theta^a_l$ refers to the effect of thermodynamics. Enthalpy is a particular case because it also has a vertical depth dependence $z$, which corresponds to $K$ vertical layers of equal thickness. The solution adopted here, following from \cite{zhang_2001}, is that enthalpy from the individual layers are conserved separately. This is a practical solution, for lack of better.
+
+One of the major actions of LIM is to resolve conservation equations for all extensive variables that characterize the ice state.  Let us now connect this detailed information with classical sea ice fields. The ice concentration $A$ and the ice volume per area\footnote{Ice volume per area is equivalent to the grid-cell averaged ice thickness.} $V_i$ (m) directly derive from $g$: 
+\begin{linenomath}
+\begin{align}
+ A(\mathbf{x},t) &=\int_{0^+}^{\infty} dh \cdot g(h,\mathbf{x},t) \sim A_{ij} = \sum_{l=1}^L a_{ijl}, & \\
+ V_i(\mathbf{x},t)&=\int_{0}^{\infty} dh \cdot g(h,\mathbf{x},t) \cdot h \sim V^i_{ij} = \sum_{l=1}^L v^i_{ijl}. & \\
+\end{align}
+\end{linenomath}
+where the $0^+$ boundary implies that the means exclude open water. The mean ice thicknesses $H_i$ (m) is:
+\begin{linenomath}
+\begin{align}
+H_i = V_i/A,
+\end{align}
+\end{linenomath}
+whereas the open water fraction is simply $1-A$.
+
+\section{Governing equations}
+
+Let us now readily present the set of the LIM "governing" equations in the framework of the assumptions developed above. The conservation of horizontal momentum reads:
+\begin{linenomath}
+\begin{align}
+m \frac{\partial \mathbf{u}} {\partial t} & = \mathbf{\nabla}\cdot\mathbf{\sigma} +A \left(\mathbf{\tau}_{a}+\mathbf{\tau}_{w}\right) - m f \mathbf{k} \times \mathbf{u} - m g \mathbf{\nabla}{\eta},
+\label{a}
+\end{align}
+\end{linenomath}
+where $m=\rho_i V_i + \rho_s V_s $ is the ice and snow mass per unit area, $\mathbf{u}$ is the ice velocity, $\mathbf{\sigma}$ is the internal stress tensor, $\mathbf{\tau}_a$ and $\mathbf{\tau}_w$ are the air and ocean stresses, respectively, $f$ is the Coriolis parameter, $\mathbf{k}$ is a unit vector pointing upwards, $g$ is the gravity acceleration and $\eta$ is the ocean surface elevation. The EVP approach used in LIM \citep{bouillon_2013} gives the stress tensor as a function of the strain rate tensor $\dot{\mathbf{\epsilon}}$ and some of the sea ice state variables:
+\begin{linenomath}
+\begin{align}
+\mathbf{\sigma} & = \mathbf{\sigma} (\dot{ \mathbf{\epsilon}}, \text{ice state}).
+\end{align}
+\end{linenomath}
+To the exception of velocity and internal stress, all extensive variables in Table \ref{GVariables_table} follow a conservation equation of the form:
+\begin{linenomath}
+\begin{align}
+\frac{\partial X}{\partial t} & = - \nabla .(\mathbf{u}X) + \Theta^X + \Psi^X,
+\label{eq:Xt}
+\end{align}
+\end{linenomath}
+including the effets of transport, thermodynamics ($\Theta^X$) and mechanical redistribution ($\Psi^X$). Solving these $jpl.(4+2.jpk)$ equations gives the temporal evolution of $\mathbf{u}$, $\mathbf{\sigma}$ and the rest of the global (extensive) variables listed in Table \ref{GVariables_table}.
+
+\section{Ice Dynamics}
+
+Dynamical processes include the conservation of momentum, rheology, transport and mechanical redistribution.
+To resolve the momentum equation, atmospheric stress is taken either as forcing or from an atmospheric model, oceanic stress and sea surface elevation from the ocean model, the Coriolis term is trivial. The last term, the divergence of the internal stress tensor $\sigma$, is the most critical term in the momentum equation and requires a rheological formulation. The EVP approach used in LIM gives the stress tensor components as \citep{bouillon_2013}:
+\begin{linenomath}
+\begin{align}
+\sigma_{ij} & = \frac{P}{2(\Delta + \Delta_{min}) }
+\biggr [ ( \dot{\epsilon}_{kk} - \Delta) \delta_{ij} + \frac{1}{e^2} ( 2 \dot{\epsilon}_{ij} - \dot{\epsilon}_{kk} \delta_{ij} ) \biggr ],
+\end{align}
+\end{linenomath}
+where $\Delta$ is a particular measure of the deformation rate, $\Delta_{min}$ a parameter determining a smooth transition from pure viscous vlow ($\Delta<<\Delta_{min}$) to pure plastic flow ($\Delta >> \Delta_{min}$), and $e$ is a parameter giving the ratio between the maximum compressive stress and twice the maximum shear stress. In the pure plastic regime, the stress principal components should lie on the edge of an elliptical yield curve (Fig. \ref{fig_yield}). In the viscous regime, they are within the ellipse. The ice strength $P$ determines the plastic failure criterion and connects the momentum equation with the state of the sea ice. $P$ is not well constrained and must be parameterized. The heuristic option of \cite{hibler_1979} was here adopted as a reference formulation:
+\begin{linenomath}
+\begin{align}
+P & = P^* V_i e^{-C(1-A)},
+\end{align}
+\end{linenomath}
+where $P^*$ and $C$ are empirical constants (see Table \ref{Modelparameters_table} for the values of the main model parameters).
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Ice thickness distribution
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=6cm,angle=-00]{yield_curve}
+\caption{Elliptical yield curve used in the VP rheologies, drawn in the space of the principal components of the stress tensor ($\sigma_1$ and $\sigma_2$).}
+\label{fig_yield}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+%
+%--------------------------------------------------------------------------------------------------------------------
+%
+% TABLE x Model parameters %
+%
+\begin{table}[ht]
+\begin{footnotesize}
+\caption{Main model parameters.}
+\begin{center}
+\begin{tabular}{@{}llccl}\hline
+ & Description & Value & Units & Ref \\ \hline
+ 
+% Parameters
+$P*$ (rn\_pstar) & ice strength thickness param. & 20000 & N/m2 & - \\
+$C$ (rn\_crhg) & ice strength concentration param. & 20 & - & \citep{hibler_1979} \\
+$H^*$ (rn\_hstar) & maximum ridged ice thickness param. & 25 & m & \citep{lipscomb_2007} \\
+$p$ (rn\_por\_rdg) & porosity of new ridges & 0.3 & - & \citep{lepparanta_1995} \\
+$amax$ (rn\_amax) & maximum ice concentration & 0.999 & - & -\\
+$h_0$ (rn\_hnewice) & thickness of newly formed ice & 0.1 & m & - \\
+ 
+\hline
+\end{tabular}
+\end{center}
+\label{Modelparameters_table}
+\end{footnotesize}
+\end{table}
+%
+%--------------------------------------------------------------------------------------------------------------------
+%
+
+
+Transport connects the horizontal velocity fields and the rest of the ice properties. LIM assumes that the ice properties in the different thickness categories are transported at the same velocity. The scheme of \cite{prather_1986}, based on the conservation of 0, 1$^{st}$ and 2$^{nd}$ order moments in $x-$ and $y-$directions,  is used, with some numerical diffusion if desired. Whereas this scheme is accurate, nearly conservative, it is also quite expensive since, for each advected field, five moments need to be advected, which proves CPU consuming, in particular when multiple categories are used. Other solutions are currently explored.
+
+The dissipation of energy associated with plastic failure under convergence and shear is accomplished by rafting (overriding of two ice plates) and ridging (breaking of an ice plate and subsequent piling of the broken ice blocks into pressure ridges). Thin ice preferentially rafts whereas thick ice preferentially ridges \citep{tuhkuri_2002}. Because observations of these processes are limited, their representation in LIM is rather heuristic. The amount of ice that rafts/ridges depends on the strain rate tensor invariants (shear and divergence) as in \citep{flato_1995}, while the ice categories involved are determined by a participation function favouring thin ice \citep{lipscomb_2007}. The thickness of ice being deformed ($h'$) determines whether ice rafts ($h'<$ 0.75 m) or ridges ($h'>$ 0.75 m), following \cite{haapala_2000}. The deformed ice thickness is $2h'$ after rafting, and is distributed between $2h'$ and $2 \sqrt{H^*h'}$ after ridging, where $H^* = 25$ m \citep{lipscomb_2007}. Newly ridged ice is highly porous, effectively trapping seawater. To represent this, a prescribed volume fraction (30\%) of newly ridged ice \citep{lepparanta_1995} incorporates mass, salt and heat are extracted from the ocean. Hence, in contrast with other models, the net thermodynamic ice production during convergence is not zero in LIM, since mass is added to sea ice during ridging. Consequently, simulated new ridges have high temperature and salinity as observed \citep{hoyland_2002}. A fraction of snow (50 \%) falls into the ocean during deformation.
+
+\section{Ice thermodynamics}
+In this section, we develop the underlying principles of the thermodynamic formulation, summarized in the term $\Theta^X$, where $X$ refers to all extensive state variables. $\Theta^X$ includes the contributions of transport in thickness space and thermodynamic source and sink terms.
+
+\subsection{Transport in thickness space}
+Transport in thickness space describes how vertical growth and melt moves ice state variables among the different thicknesses at a velocity $f(h)$, the net ice growth/melt rate, which needs to be first computed.  In discretized form, this term moves ice properties between neighbouring categories. The linear remapping scheme of \cite{lipscomb_2001} is used. This scheme is semi-lagrangian, second-order, is less diffusive and converges faster than other options.
+
+\subsection{Thermodynamic source and sink terms}
+
+Since heat, salt and mass are strongly inter-dependent for sea ice, the thermodynamic source and sink terms are treated together. They include the changes in extensive sea ice state associated with thermodynamic processes. The latter are separated in two main parts: (i) open water fraction processes, where atmosphere and ocean are in direct interaction; and (ii) vertical ice thermodynamic processes, driven by surface snow/ice-atmosphere and basal ice-ocean exchanges, for each thickness category. For each part, first, the energy available or lost is specified. Then the impact on mass exchanges is evaluated. The latter part requires to specify how sea ice and snow responds to energy supply or loss, which is achieved through the enthalpy formulation.
+
+%\subsubsection{Atmosphere-ice-ocean heat and mass exchanges}
+%
+%The atmosphere-ice heat exchanges are either specified in external files (forcing) or computed from an atmospheric model. The following heat and mass fluxes should be specified:
+%\begin{itemize}
+%\item Net solar flux, for open water ($Q^{sol}$) and ice categories ($Q^{sol,ice}_{l}$);
+%\item Net non-solar flux, for open water ($Q^{nsol}$) and ice categories ($Q^{nsol,ice}_{l}$);
+%\item Solid and liquid precipitation (kg/m$^2$/s).
+%\end{itemize}
+%
+%In terms of mass (freshwater), the ocean gets:
+%\begin{itemize}
+%\item All liquid precipitation;
+%\item The part of solid precipitation that is not intercepted by the ice, accounting for the part that is blown off the sea ice by winds;
+%\item The net melting minus freezing mass flux, as diagnosed from thermodynamic sea ice calculations.
+%\end{itemize}
+%
+%In terms of energy, the ocean gets:
+%\begin{itemize}
+%\item The net atmospheric solar flux, minus what is intercepted by the ice; plus what is transmitted below the ice; 
+%\item The net atmospheric non-solar heat flux, minus what is used by the sea ice; 
+%\item The sensible heat exchange associated with ice-ocean and atmosphere-ocean mass fluxes. 
+%\end{itemize}
+%
+%In terms of salt, the ocean gets the net salt release minus uptake associated with sea ice growth, melt and brine drainage. There is no atmosphere-ocean salt flux.
+
+\subsubsection{Enthalpy formulation}
+
+% Add snow and water
+
+A first overarching aspect of the thermodynamic calculations is the specification of the response of sea ice to energy supply. This is achieved by defining the internal energy (or enthalpy\footnote{Wording it internal energy or enthalpy is equivalent since pressure effects are not considered.}). This ultimately relies on the response of the phase composition to salinity and temperature changes. The enthalpy formulation used in LIM is based on the following assumptions:
+\begin{itemize}
+\item Sea ice is gas-free, composed solely of pure ice and saline brine, characterized by brine fraction $\phi$;
+\item brine and pure ice are in thermodynamic equilibrium;
+\item the salinity-dependence of the freezing point is linear (linear liquidus);
+\item the density of the sea ice (ice+brine) medium is constant ($\rho_i$).
+\end{itemize}
+%In this context, the bulk salinity of a small control sea ice volume is related to the salinity of brine ($S_{br}$):
+%\begin{linenomath}
+%\begin{align}
+%S = \phi S_{br}
+%\label{eq_S_Sbr}
+%\end{align}
+%\end{linenomath}
+%Because of thermal equilibrium and linear liquidus, brine salinity directly depends on local temperature: $T=-\mu S_{br}$. Hence, brine fraction is given by
+%\begin{linenomath}
+%\begin{align}
+%\phi = -\frac{\mu S}{T}.
+%\end{align}
+%\end{linenomath}
+%This equation relates brine fraction to bulk salinity and temperature, which therefore can be seen as the two main state variables in this linear mushy layer formulation for sea ice thermodynamics. 
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Thermal properties
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=8cm,angle=-00]{Thermal_properties}
+\caption{Thermal properties of sea ice vs temperature for different bulk salinities: brine fraction, specific enthalpy, thermal conductivity, and effective specific heat.}
+\label{fig_thermal_properties}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+Based on these, brine fraction reduces to $\phi = -\mu S/T$ (see Fig. \ref{fig_thermal_properties}), where $\mu$ relates the freezing point of brine to salinity, and one can derive the specific enthalpy $q_m(S,T)$, defined as the energy required to warm and melt a unit control volume of sea ice at temperature $T$ (in Celsius) and salinity $S$ until 0$^\circ$ C, taken as a reference zero-energy level \citep{bitz_1999,schmidt_2004}:
+\begin{linenomath}
+\begin{align}
+q_m(S,T) = \biggr [ c_i ( T + \mu S) - L \biggr ( 1 + \frac{\mu S}{T} \biggr ) - c_w \mu S \biggr ]
+\end{align}
+\end{linenomath}
+where $c_i$ is pure ice specific heat, $L$ is latent heat of fusion at 0$^\circ$C, and $c_w$ is water specific heat. The first term expresses the warming of solid ice. The second term expresses internal change in brine fraction, which is often the largest because the Stefan number  ($c_i T/L$) is generally small. The last term gives the warming of the remaining water from $T_{fr} = -\mu S$ until 0$^\circ$C. Similar, but simpler and linear expressions for snow and water can be derived.
+
+The second overarching aspect is that all growth and melt processes must be calculated consistently with the enthalpy formulation. Energetics of phase transitions are handled using the formalism of \cite{schmidt_2004}. For each phase transition, initial and final states (temperature and salinity) are defined, and the ice-to-ocean mass flux to the ice $F_m$ (kg/s) relates to the energy gain or loss $\Delta Q$ through:
+\begin{linenomath}
+\begin{align}
+\Delta Q / \Delta q_m = F_m,
+\label{eq_phasechange}
+\end{align}
+\end{linenomath}
+where $\Delta q_m$ is the change in specific enthalpy involved in the considered phase transition, from initial to final state.
+
+
+\subsubsection{Open water processes}
+
+As part of the sea ice thermodynamic calculations, a heat budget estimate for the uppermost ocean level ($B^{opw}$) must be included, to compute the rate of new ice formation or the contribution of sensible heat to bottom melting. $B^{opw}$ includes:
+\begin{itemize}
+\item the absorption of a fraction $f_1^{qsr}$ of solar radiation (given by radiative transfer component of the ocean model);
+\item the non-solar heat flux absorbed at the surface;
+\item the sensible heat content of precipitation
+\item the sensible heat flux from the ocean to the sea ice ($A.F_w$)
+\end{itemize}
+Other contributions are not assumed not to contribute. The ocean-to-ice sensible heat flux is formulated the bulk formula of \citep{mcphee_1992}.
+
+% Ice growth
+If $B^{opw}$ is such that the SST would decrease below the freezing point, the remainder of the heat is used to form new ice. The heat loss is converted into a volume of new ice $v_0$. The thickness $h_0$ of the new ice grown during a sea ice time step depends on unresolved small-scale currents and waves and is prescribed. The fraction $a_0=v_0/h_0$ is computed accordingly. The salinity of this new ice $S_0$ is given by the salinity-thickness empirical relationship of \cite{kovacs_1996}. The temperature assumed for this new ice is the local freezing point. If by contrast $B^{opw}$ is positive and there still is ice in the grid cell, then $B^{opw}$ is directly redirected to bottom melting. This argument follows from \cite{maykut_1995}, who found that most of solar heat absorbed in the surface waters is converted into melting. In practise, this prevents the SST to be above freezing as long ice is present.
+
+$B^{opw}$ can be seen as a predictor of the heat budget of the first ocean level. As such, it only helps to compute new ice formation and the extra bottom melt in summer, but is not part of the conservation of heat in the model. To ensure heat conservation, the heat effectively contributing to changing sea ice is removed from the non-solar flux sent to the ocean. This includes: (i) the heat loss used for ice formation, (ii) the heat gain used to melt ice, and (iii) the sensible heat given by the ocean to the ice. Finally, because ice dynamics are not able to maintain the small amount of open water that is observed, a maximum ice fraction ($amax, <1$) is prescribed.
+
+\subsubsection{Vertical ice thermodynamic processes}
+
+The second part of the computations regard the computation of purerly vertical processes in the ice-covered part of the grid cell, similarly for each ice category. 
+
+\textbf{Surface melt, basal growth and melt and diffusion of heat}. The surface melt rate, as well as the basal growth / melt rate depend on the energy budget at the upper and lower interfaces, respectively, between the external fluxes either from the atmosphere or the ocean, and the internal conduction fluxes. The internal conduction fluxes depend on the internal temperature profile, which is determined by solving the enthalpy equation:
+\begin{linenomath}
+\begin{align}
+\rho \frac{\partial q_m}{\partial t} = - \frac{\partial}{\partial z} (F_c + F_r ).
+\end{align}
+\end{linenomath}
+which state that the local change in enthalpy is given by the divergence of the vertical conduction ($F_c=-k(S,T) \partial T / \partial z$) and radiation ($F_r$) fluxes. $\rho$ is the density of ice or snow. Re-expressed as a function of temperature, this becomes the heat diffusion equation.  This equation is non-linear in $T$, because of $q$ and $k$, and its main specificity is that internal melting requires large amounts of energy near the freezing point. The thermal conductivity is formulated following \cite{pringle_2007}, empirically accounting for the reduction of thermal conductivity at large brine fractions. 
+
+At the ice base, we assume that the temperature is at the local freezing point.  Ice grows or melt if the heat balance between the oceanic sensible heat flux ($F_w$) and internal conduction is negative or positive.
+
+At the ice surface, the boundary condition on the heat diffusion equation is:
+\begin{linenomath}
+\begin{align}
+Q^{sr}  + Q^{ns}(T_{su})= F_c + Q^{sum}.
+\end{align}
+\end{linenomath}
+where $Q^{sr}$ and $Q^{ns}$ are the net downwelling atmospheric solar and non-solar flux components. If the solution of this equation without melting gives a surface temperature ($T_{su}$) below 0$^\circ$ C, then there is no melting and the heat available for surface melting $Q_{sum}=0$.  Otherwise $T_{su}$ is capped at 0$^\circ$ C and $Q_{sum}$ is calculated as a residual.
+
+\textbf{Radiation}. Radiation contributes to the surface and internal heat budget. The radiative transfer scheme is currently basic, composed of surface albedo, transmission through the ice interior and attenuation with vertical depth. The albedo is computed empirically as a function of ice thickness, snow depth and surface temperature, using a reformulation of the parameterization of \cite{shine_1985}. When snow is present, all the absorbed radiation is transformed into sensible heat available for conduction or melting. Over snow-free ice, a fraction of solar radiation is transmitted below the surface and attenuates exponentially with depth, until it reaches the base of the ice.
+
+\textbf{Growth and melt processes}.  Snow grows from precipitation and loses mass from melting and snow-ice conversion once the snow base is below sea level. Sea ice grows and melts by various means. Ice forms by congelation or melt at the base, can melt at the surface and form from snow-to-ice conversion at the snow-ice interface if the latter is below sea level. Some new ice is also added to the system when seawater is trapped into newly formed pressure ridges.
+
+\textbf{Salt dynamics}. Bulk salinity is empirically parameterized, as a function of salt uptake during growth, gravity drainage and flushing. The shape of the vertical profile depends on the bulk salinity \citep{vancoppenolle_2009}.
+
+\textbf{Single-category parameterizations}. If the single-category representation is adopted, then two parameterizations can be activated, following \citep{fichefet_1997}. First, the thermal conductivity of both ice and snow is multiplied by a factor $>1$ accounting for the unresolved thin ice, effectively increasing the ice growth rate. Second, to account for the loss of thin ice in summer, the ice concentration is reduced in proportion to the loss of ice thickness. Both parameterizations have been tuned to match the results in multi-category mode.
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_output_diagnostics.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_output_diagnostics.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_output_diagnostics.tex	(revision 14097)
@@ -0,0 +1,65 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 9 - Outputs and diagnostics
+% ================================================================
+
+\chapter{Output and diagnostics}
+\label{chap:DIA}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+\section{SIMIP diagnostics}
+
+The SIMIP protocol \citep{notz_2016} was designed for CMIP6, to standardize sea ice model outputs in climate simulations. We tried to follow the data request as closely as possible. Outputs are in most cases directly managed with XIOS2 in \textbf{limwri.F90}, but not always. In the code, output fields keep their native LIM reference name. 
+
+A corresponding entry exists in \textbf{field\_def\_nemo-lim.xml}, where fields are given their SIMIP specifications (standard name, long name, units). At the end of the file the fields are gathered in the field groups \textbf{SIday\_fields}, \textbf{SImon\_fields} and \textbf{SImon\_scalar} for separation of the daily (SIday) and monthly (SImon) requests. 
+
+In \textbf{file\_def\_nemo-lim.xml}, the daily, monthly and scalar output files are created.
+
+In the reference xml files, the largest possible SIMIP-based diagnostics with LIM are distributed among the field groups. If some fields are to be discarded, the best way to do so is to remove them from the field groups in  field\_def\_nemo-lim.xml.
+
+\subsection{Missing SIMIP fields}
+
+About 90\% of the SIMIP fields can be output. Below is the list of the missing fields and why they are missing. \\
+
+\textbf{1. Fields that are not part of the sea ice representation in LIM3.6}
+\begin{itemize}
+\item sisnconc (snow area fraction), siitdsnconc (snow area fractions in thickness categories);
+\item simpconc (meltpond area fraction), simpmass (melt pond mass per area), simprefrozen (thickness of refrozen ice on ponds);
+\item sirdgconc (ridged ice area fraction), sirdgmass (ridged ice thickness);
+\item sidmasslat (lateral sea ice melt rate);
+\item sndmasswindrif (snow mass change through wind drift of snow);
+\end{itemize}
+
+\textbf{2. Fields which value is trivial}
+\begin{itemize}
+\item sipr (rainfall over sea ice): all rain falls in open water;
+\item sidragtop (atmospheric drag over sea ice): namelist parameter;
+\item sidragbot (oceanic drag over sea ice): namelist parameter
+\end{itemize}
+
+\textbf{3. Fields that belong to the atmospheric component}
+\begin{itemize}
+\item siflswdtop, siflswutop, siflswdbot, sifllwdtop, sifllwutop, siflsenstop, sifllatstop (surface energy budget components)
+\end{itemize}
+
+Ice thickness and snow depth were masked below 5\% ice concentration, because below this value, they become meaninglessly large in LIM. This is notably because of the Prather advection scheme. We hope to fix these issues for our next release. For similar reasons, the ice age is masked below 15\% concentration.
+
+Fluxes through straits and passages were not directly implemented. Instead, ice mass, snow mass, and ice area transports were implemented as 2D arrays, for x- and y- directions. A python script is available to derive the fluxes through straits and passages from full 2D arrays for ORCA2 and eORCA1 grids.
+
+\subsection{Links}
+
+\begin{itemize}
+\item \textcolor{blue}{\href{http://www.geosci-model-dev.net/9/3427/2016/}{Paper of Notz et al}};
+\item \textcolor{blue}{\href{http://clipc-services.ceda.ac.uk/dreq/u/SIMIP.html}{SIMIP CMIP6 data request page}};
+\item \textcolor{blue}{\href{http://www.climate-cryosphere.org/activities/targeted/simip}{SIMIP description on CliC website}}.
+\end{itemize}
+
+\section{Conservation checks}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_radiative_transfer.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_radiative_transfer.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_radiative_transfer.tex	(revision 14097)
@@ -0,0 +1,210 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+
+
+
+% ================================================================
+% Chapter 6 Ñ Radiative transfer
+% ================================================================
+
+\chapter{Radiative transfer}
+\label{chap:RAD}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+Radiative transfer in SI$^3$ currently reduces to the parameterization of solar radiation partitionning through the snow/ice/open water system, treated using a single wavelength band. This will likely be improved in future versions of the code. In this chapter, we first explain how solar radiation is partionned in the snow-ice system, then describe how, solar radiation-wise, the snow-ice system is framed in the context of the atmosphere-ice-ocean boundary.
+
+\section{Solar radiation partitionning in the snow-ice system}
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Radiation balance %
+\begin{figure}[!ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=6cm,angle=-00]{radiative_transfer}
+\caption{Partitionning of solar radiation in the snow-ice system, as represented in SI$^3$.}
+\label{fig_radiative_transfer}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+Solar radiation in the snow-ice system is represented following the principles of \cite{maykut_1971}, see Fig.\ref{fig_radiative_transfer}, using a unique band of solar radiation. Incident solar radiation (W/m$^2$, counted per unit ice area - not per grid cell area) is specified in the SBC routines and is a priori category dependent, because multiple atmosphere-surface reflexions are frequent in polar regions imply that incident radiation depends on the surface albedo and therefore surface state. 
+
+Net solar radiation qsr\_ice(i,j,l) is obtained by substracting the reflected part of the incident radiation using the surface albedo $\alpha(i,j,l)$, parameterized as a function of environmental conditions. 
+
+The subsequent attenuation of solar radiation through the snow-ice system is represented assuming the presence of a highly diffusive surface scattering layer, absorbing a fraction $i_o$ of net solar radiation, which is transformed into sensible heat, contributing to the surface energy balance. 
+
+The remainder of solar radiation, qtr\_ice\_top(i,j,l), is transmitted below the surface and attenuates following Beer-Lambert law. The part of solar radiation that is absorbed on its path to the base of the ice is given as sensible heat to the snow/ice system, via a source term in the heat diffusion equation. The rest of solar radiation that reaches the ice base, qtr\_ice\_bot(i,j,l), is transmitted to the ocean. 
+
+In the rest of this section, we describe how the albedo, the surface transmission parameter $i_o$ and the attenuation of solar radiation are parameterized.
+
+\subsection{Surface albedo}
+
+The surface albedo determines the amount of solar radiation that is reflected by the ice surface, hence also net solar radiation. The philosophy of the parameterization of surface albedo is the following: each ice category has its own albedo value $\alpha(i,j,l)$, determined as a function of cloud fraction, ice thickness, snow depth, melt pond fraction and depth, using observation-based empirical fits. 
+
+The original \cite{shine_1985} parameterization had a few inconsistencies and flaws that the revisited parameterization described hereafter fixes. In particular, the dependencies of albedos on ice thickness, snow depth and cloud fraction have been revised in the light of recent observational constraints \citep{brandt_2005,grenfell_2004}. In addition, the asymptotic properties of albedo are better specified and now fully consistent with oceanic values. Finally, the effect of melt ponds has been included \citep{lecomte_2015}.
+
+The user has control on 5 reference namelist values, which describe the asymptotic values of albedo of snow and ice for dry and wet conditions, as well as the deep ponded-ice albedo. Observational surveys, in particular during SHEBA in the Arctic \citep{perovich_2002} and further additional experiments \citep{grenfell_2004}, as well as by \cite{brandt_2005} in the Antarctic, have provided relatively strong constraints on the surface albedo. In this context, the albedo can hardly be used as the main model tuning parameter, at least outside of these observation-based bounds (see namalb for reference values).
+
+\nlst{namalb}
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : cloud correction
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=10cm,angle=-00]{albedo_cloud_correction}
+\caption{Albedo correction $\Delta \alpha$ as a function of overcast sky (diffuse light) albedo $\alpha_os$, from field observations \cite[][their Table 3]{grenfell_2004} (squares) and 2nd-order fit (Eq. \ref{eq_albedo_cloud_correction}). Red squares represent the irrelevant data points excluded from the fit. For indication, the amplitude of the correction used in the ocean component is also depicted (blue circle).}
+% ocean uses 0.06 for overcast sky (Payne 74) and Briegleb and Ramanathan parameterization
+\label{fig_albedo_cloud_correction}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+Because the albedo is not an intrinsic optical property, it depends on the type of light (diffuse of direct), which is practically handled by weighting the clear (cs) and overcast (os) skies values by cloud fraction $c(i,j)$ \citep{fichefet_1997}:
+\begin{equation}
+\alpha(i,j,l) = [ 1 - c(i,j) ] \cdot \alpha_{cs} (i,j,l) + c (i,j) \cdot \alpha_{os}(i,j,l).
+\end{equation}
+For concision, we drop the spatial and category indices hereafter. \cite{grenfell_2004} observations at Point Barrow, on the Alaskan Coast, suggest that clear and overcast sky albedos are directly related through
+\begin{equation}
+\alpha_{cs} = \alpha_{os} - \Delta \alpha(\alpha_{os}).
+\end{equation}
+The relation between $\Delta \alpha$ and $ \alpha_{os}$ can well be handled using a 2$^{nd}$-order polynomial fit (Fig. \ref{fig_albedo_cloud_correction}):
+\begin{equation}
+\Delta \alpha =  ( -0.1010 \cdot \alpha_{os}^2 + 0.1933 \cdot \alpha_{os} - 0.0148 ).
+\label{eq_albedo_cloud_correction}
+\end{equation}
+Overcast sky surface albedo is used as a reference, from which the clear-sky value is derived.
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : thickness, snow depth, pond depth dependencies
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=4cm,angle=-00]{albedo_dependencies}
+\caption{Example albedo dependencies on ice thickness, snow depth and pond depth, as parameterized in SI$^3$.}
+\label{fig_albedo_dependencies}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+The second important parameter that controls surface albedo is surface type. In each category, we assume that three types of surfaces can coexist (bare, snow-covered and ponded ice), with respective fractions $f_{ice}$, $f_{snw}$ and $f_{pnd}$ summing to 1. Then the overcast albedo is expressed as
+\begin{equation}
+\alpha_{os}(i,j,l) = f_{ice} \cdot \alpha_{ice} + f_{snw} \cdot \alpha_{snw} + f_{pnd}\cdot \alpha_{pnd}
+\end{equation}
+with a specific albedo value for each surface type. 
+
+The surface fractions $f_{ice}$, $f_{snw}$ and $f_{pnd}$ are currently crudely parameterized: if snow is present ($h_s>0$), then $f_{snw}=1$ and $f_{ice}=f_{pnd}=0$. In the absence of snow, $f_{pnd}$ is either specified or calculated (depending on melt pond options in nampnd), and $f_{ice}=1.-f_{pnd}$. Admittedly, more refined parameterizations of $f_{snw}$ could improve the realism of the model. Note finally that the dependence of surface albedo on the presence of melt ponds can be included or not (namelist parameter ln\_pnd\_alb). If the latter is set to false, $f_{pnd}$ is always assumed zero in the albedo computations.
+
+Works by \cite{brandt_2005} and references therein, indicate that the dependence of the albedo of bare ice on ice thickness depends is linear/logarithmic/constant from thin to thick ice. Hence, the following expressions capture  the essence of their works:
+\begin{eqnarray}
+\alpha_{ice} = 
+\begin{cases}
+\alpha_{ice}^{\infty} & \text{ if } h_i > 1.5, \\
+\alpha_{ice}^{\infty} + ( 0.18 - \alpha_{ice}^{\infty} ) \cdot \frac{ln(1.5) - ln(h_i)}{ln(1.5) - ln(0.05)} & \text{ if } 0.05 < h_i ,<= 1.5 \\
+\alpha_{oce}  + ( 0.18 - \alpha_{oce} ) h_i /0.05 & \text{ if } h_i < 0.05.
+\end{cases}
+\end{eqnarray}
+The thick-ice constant albedo value depends on whether the surface is dry or melting:
+\begin{eqnarray}
+\alpha_{ice}^{\infty} =
+\begin{cases}
+\alpha_{i,dry} & \text{ if } T_{su} < T_{fr} \\
+\alpha_{i,mlt} & \text{ if } T_{su} = T_{fr},
+\end{cases}
+\end{eqnarray}
+values that are to be specified from the namelist.
+
+\cite{grenfell_2004} suggest that the dependence of surface albedo on snow depth is exponential,
+\begin{eqnarray}
+\alpha_{snw} = \alpha_{snw}^{\infty} - ( \alpha_{snw}^{\infty} - \alpha_{ice} ) * exp( -h_s / h_s^{ref} ),
+\end{eqnarray}
+where $h_s^{ref} = 0.02$ $(0.03)$ m for dry (wet) snow. As for bare ice, the deep-snow asymptotic albedo also depends on whether the surface is dry or melting:
+\begin{eqnarray}
+\alpha_{snw}^{\infty} =
+\begin{cases}
+\alpha_{s,dry} & \text{ if } T_{su} < T_{fr} \\
+\alpha_{s,mlt} & \text{ if } T_{su} = T_{fr},
+\end{cases}
+\end{eqnarray}
+values that are to be specified from the namelist.
+
+Based on ideas developed from melt ponds on continental ice \citep{zuo_1996}, the albedo of ponded ice was proposed to follow \citep{lecomte_2011}:
+\begin{eqnarray}
+\alpha_{pnd} = \alpha_{dpnd} - ( \alpha_{dpnd} -\alpha_{ice} ) \cdot exp( -h_{pnd} / 0.05 )
+\end{eqnarray}
+$\alpha_{dpnd}$ is a namelist parameter. \cite{ebert_1993} also use such dependency for their multi-spectral albedo.
+
+The dependencies of surface albedo on ice thickness, snow depth and pond depth are illustrated in Fig. \ref{fig_albedo_dependencies}.
+
+\subsection{Transmission below the snow/ice surface}
+
+The transmitted solar radiation below the surface is represented following \cite{fichefet_1997} and \cite{maykut_1971}:
+\begin{eqnarray}
+qtr\_ice\_top(i,j,l) = i_o(i,j) qsr\_ice(i,j,l),
+\end{eqnarray}
+where $i_o=0$ in presence of snow, and depends on cloud fraction otherwise, based on works of \cite{grenfell_1977}. This parameterization needs to be re-evaluated and likely updated.
+
+\subsection{Attenuation and transmission below the ice/ocean interface}
+
+Attenuation of solar radiation through the ice follows Beer-Lambert law. In practise, we assume that irradiance below layer $k$ is given by
+
+\begin{eqnarray}
+radtr\_i(i,j,k,l) = qtr\_ice\_top(i,j,l) \cdot exp(-\kappa_i z),
+\end{eqnarray}
+where $\kappa_i = 1$ m$^{-1}$ is the exponential attenuation coefficient (namelist parameter rn\_kappa\_i). Hence, at the ice base, remains below the $l^{th}$ category a transmitted flux: 
+\begin{eqnarray}
+qtr\_ice\_bot(i,j,l) = qtr\_ice\_top(i,j,l) \cdot exp(-\kappa_i h_i).
+\end{eqnarray}
+
+\section{Solar radiation: framing sea ice at the ocean-atmosphere boundary}
+
+How solar radiation transfer through sea ice is framed into the atmosphere-ice-ocean is nearly identical but not exactly the same in forced and coupled mode (see Fig. \ref{fig_radiative_transfer}.
+
+The basic principle of the computation is that the irradiant flux given to the ocean model (qsr) is computed as the average flux per grid cell area (qsr\_tot) minus what is given to the sea ice ($\sum a(l) qsr\_ice(l)$), plus what is transmitted below sea ice $\sum$ qtr\_ice\_bot(jl) (see at the base of Fig. \ref{fig_radiative_transfer}). Such formulation ensures heat conservation by construction.
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Radiation balance %
+\begin{figure}[!ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=8cm,angle=-00]{radiation_atm_ice_oce}
+\caption{Framing solar radiation transfer through sea ice into the atmosphere-ice-ocean context.}
+% ocean uses 0.06 for overcast sky (Payne 74) and Briegleb and Ramanathan parameterization
+\label{fig_radiative_transfer}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+\subsection{Forced mode}
+
+In forced-atmosphere mode, it is the incoming solar irradiance fluxes above the ocean and sea ice (categories) that are specified (from files) or computed (from bulk formulae), and constitute the basis of solar radiation transfer computations. Then the net solar fluxes above open water (qsr\_oce) and ice categories (qsr\_ice) are obtained by multiplication by $1-\alpha$. qsr\_tot is then diagnosed as a weighted sum of qsr\_oce and the qsr\_ice(jl)'s.
+
+\subsection{Coupled mode}
+
+In coupled-atmosphere mode, qsr\_tot and qsr\_ice have to be provided by the atmospheric model, whereas qsr\_oce is diagnosed from qsr\_ice and qsr\_tot.
+
+Some atmospheric models enable \textit{tiling} and can provide solar fluxes over individual ice categories. For such atmospheric models, net solar radiation fluxes are directly useable by SI$^3$ (nn\_flxdist =  -1). Other models cannot do tiling, being only able to provide a net solar flux above all ice categories, seen as a single surface type. For such models a first option is to give the net solar flux above sea ice identically to all sea ice categories (nn\_flxdist = 0). Yet a better option is to redistribute the mean solar flux above sea ice $< qsr_ice >$ above categories (nn\_flxdist = 2) using the following scaling, conserving heat by construction:
+
+\begin{eqnarray}
+qsr\_ice(jl) = < qsr\_ice > \frac{1 - \alpha(jl)}{1 - < \alpha >}
+\end{eqnarray}
+
+where $ < \alpha >$ is the albedo averaged over the ice categories. Note that for testing, the flux redistributor can be emulated in forced mode (nn\_flxdist = 1).
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_ridging_rafting.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_ridging_rafting.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_ridging_rafting.tex	(revision 14097)
@@ -0,0 +1,156 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 5 Ñ Ridging and rafting
+% ================================================================
+
+\chapter{Ridging and rafting}
+\label{chap:RDG}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+This chapter focuses on how LIM solves the red part of the general equation:
+\begin{equation}
+\frac{\partial X}{\partial t} = - \nabla .(\mathbf{u} X)  \color{black} \Theta^X  + \color{red} \Psi^X,
+\label{eq:Xt}
+\end{equation}
+where $X$ refers to any global sea ice state variable.
+
+Divergence and shear open the ice pack and create ice of zero thickness. Convergence and shear consumes thin ice and create thicker ice by mechanical deformation. The redistribution functions $\Psi^X$ describe how opening and mechanical deformation redistribute the global ice state variables into the various ice thickness categories. 
+
+The fundamental redistribution function is $\Psi^g$, which accounts for area redistribution. The other redistribution functions $\Psi^X$ associated with other state variables will derive naturally. The redistribution function $\Psi^g$ should first ensure area conservation. By integrating the evolution equation for $g(h)$ over all thicknesses, recalling that $\int_0^\infty g(h) = 1$, and that the total areal change due to thermodynamics must be zero, e.g. $\int_0^\infty \partial (fg) / \partial h=0$, then the area conservation reads: 
+\begin{equation}
+\int_0^\infty h \Psi^g dh = \nabla \cdot \mathbf{u}.
+\end{equation}
+
+Second, we must say something about volume conservation, and this will be done more specifically later. Following \cite{thorndike_1975}, we separate the $\Psi^X$'s into \textbf{(i)} \textit{dynamical inputs}, \textbf{(ii)} \textit{participation functions}, i.e., how much area of ice with a given thickness participates to mechanical deformation \textbf{(iii)} \textit{transfer functions}, i.e., where in thickness space the ice is transferred after deformation.
+
+\section{Dynamical inputs}
+
+A general expression of $\Psi^g$, the mechanical redistribution function associated to the ice concentration, was proposed by \cite{thorndike_1975}:
+\begin{equation}
+\Psi^g = \vert \dot{\epsilon} \vert [ \alpha_o(\theta) \delta(h) + \alpha_d(\theta) w_d(h,g) ],
+\label{eq:psi}
+\end{equation}
+which is convenient to separate the dependence in $\mathbf{u}$ from those in $g$ and $h$. The first and second terms on the right-hand side correspond to opening and deformation, respectively. $\vert \dot{\epsilon} \vert = (\dot{\epsilon}_{I}^2+ \dot{\epsilon}_{II}^2)^{1/2}$, where $\dot{\epsilon}_{I}=\nabla \cdot \mathbf{u}$ and $\dot{ \epsilon}_{II}$ are the strain rate tensor invariants; $\theta=\textrm{atan}(\dot{\epsilon_{II}} / \dot{\epsilon_{I}} )$. $w_d(h,g)$, the deformation mode will be discussed in the next section. $\vert \dot{\epsilon} \vert \alpha_o$ and $\vert \dot{\epsilon} \vert \alpha_d$ are called the lead opening and closing rates, respectively.
+
+The \textbf{dynamical} inputs of the mechanical redistribution in LIM are:
+\begin{itemize}
+\item $\vert \dot{\epsilon} \vert \alpha_o$, the opening rate,
+\item $\vert \dot{\epsilon} \vert \alpha_d$, the net closing rate.
+\end{itemize}
+Following \cite{thorndike_1975}, we choose $\int_0^\infty w_d(h,g) = - 1$. In order to satisfy area conservation, the relation $\vert \dot{\epsilon} \vert \alpha_o - \vert \dot{\epsilon} \vert \alpha_d = \nabla \cdot \mathbf{u}$ must be verified. In the model, there are two ways to compute the divergence of the velocity field. A first way is to use the velocity components ($\dot{\epsilon}_I = \nabla \cdot \mathbf{u}\vert^{rhg}$) as computed after the rheology (superscript $rhg$). Another way is to derive it from the horizontal transport of ice concentration and open water fraction. In principle, the equality $A^o + \sum_{l=1}^L g^i_L = 1$ should always be verified. However, after ice transport (superscript $trp$), this is not the case, and one can diagnose a velocity divergence using the departure from this equality: $\nabla \cdot \mathbf{u}\vert^{trp} = ( 1 - A^o - \sum_{l=1}^L g^i_L )/ \Delta t$. In general, we will use $\dot{\epsilon}_I$ unless otherwise stated.
+
+The \textbf{net closing rate} is written as a sum of two terms representing the energy dissipation by shear and convergence \citep{flato_1995}:
+\begin{equation}
+\vert \dot{\epsilon} \vert \alpha_d (\theta) = C_s \frac{1}{2} ( \Delta - \vert \dot{\epsilon}_I \vert) - \textrm{min} (\dot{\epsilon}_I,0),
+\end{equation}
+where $\Delta$ is a measure of deformation (defined in the rheology section). The factor $C_s=0.5$ (\textit{Cs} in \textit{namelist\_ice}) is added to allow for energy sinks other than ridge building (e.g., sliding friction) during shear. In case of convergence, the closing rate must be large enough to satisfy area conservation after ridging, so we take:
+\begin{equation}
+\vert \dot{\epsilon} \vert \alpha_d (\theta) = \text{max}(\vert \dot{\epsilon} \vert \alpha_d (\theta), - \nabla \cdot \mathbf{u} \vert^{trp}) \quad \text{if } \nabla \cdot \mathbf{u} < 0.
+\end{equation}
+
+The \textbf{opening rate} is obtained by taking the difference:
+\begin{equation}
+\vert \dot{\epsilon} \vert \alpha_o = \vert \dot{\epsilon} \vert \alpha_d = \nabla \cdot \mathbf{u}\vert^{trp}
+\end{equation}
+
+\section{The two deformation modes: ridging and rafting}
+
+The deformation mode is separated into ridging $w^{ri}$ and rafting $w^{ra}$ modes:
+\begin{equation}
+w^d(h,g) = w^{ri}(g,h) + w^{ra}(g,h).
+\end{equation}
+
+\textbf{Rafting} is the piling of two ice sheets on top of each other. Rafting doubles the participating ice thickness and is a volume-conserving process. \cite{babko_2002} concluded that rafting plays a significant role during initial ice growth in fall, therefore we included it into the model. 
+
+\textbf{Ridging} is the piling of a series of broken ice blocks into pressure ridges. Ridging redistributes participating ice on a various range of thicknesses. Ridging does not conserve ice volume, as pressure ridges are porous. Therefore, the volume of ridged ice is larger than the volume of new ice being ridged. In the model, newly ridged is has a prescribed porosity $p=30\%$ (\textit{ridge\_por} in \textit{namelist\_ice}), following observations \citep{lepparanta_1995,hoyland_2002}. The importance of ridging is now since the early works of \citep{thorndike_1975}.
+
+The deformation modes are formulated using \textbf{participation} and \textbf{transfer} functions with specific contributions from ridging and rafting:
+\begin{equation}
+w_d(h,g) = - [ b^{ra}(h) + b^{ri}(h) ] g(h) + n^{ra}(h)+n^{ri}(h).
+\label{eq:wd}
+\end{equation}
+$b^{ra}(h)$ and $b^{ri}(h)$ are the rafting and ridging participation functions. They determine which regions of the ice thickness space participate in the redistribution. $n^{ra}(h)$ and $n^{ri}(h)$, called transfer functions, specify how thin, deformation ice is redistributed onto thick, deformed ice. Participation and transfer functions are normalized in order to conserve area.
+
+\section{Participation functions}
+
+We assume that the participation of ice in redistribution does not depend upon whether the deformation process is rafting or ridging. Therefore, the participation functions can be written as follows:
+\begin{equation}
+b^{ra}(h)= \beta(h) b(h),
+\label{eq:bra}
+\end{equation}
+\begin{equation}
+b^{ri}(h) = [1-\beta(h)] b(h),
+\label{eq:bri}
+\end{equation}
+where $b(h)$ is an exponential weighting function with an e-folding scale $a*$ \citep{lipscomb_2007} (\textit{astar} in \textit{namelist\_ice}) which preferentially apportions the thinnest available ice to ice deformation:
+\begin{equation}
+b(h) = \frac{\text{exp} [ - G(h) / a^\star ]}{a^\star[1-\text{exp}(-1/a^\star)]} ,
+\end{equation}
+It is numerically more stable than the original version of \cite{thorndike_1975}. This scheme is still present in the code and can be activated using \textit{partfun\_swi} from \textit{namelist\_ice}, with the associated parameter \textit{Gstar}.
+
+$\beta(h)$ partitions deformation ice between rafted and ridged ice. $\beta(h)$ is formulated following \cite{haapala_2000}, using the \cite{parmerter_1975} law, which states that, under a critical participating ice thickness $h_P$, ice rafts, otherwise it ridges:
+\begin{equation}
+\beta(h)= \frac{ \textrm{tanh} [ -C_{ra} (h-h_P) ] + 1 } {2},
+\end{equation}
+where $C_{ra}=5$ m$^{-1}$ (\textit{Craft} in \textit{namelist\_ice})  and $h_P=0.75$ m (\textit{hparmeter} in \textit{namelist\_ice}) \citep{haapala_2000,babko_2002}. The $tanh$ function is used to smooth the transition between ridging and rafting.  If namelist parameter \textit{raftswi} is set to 0, ice only ridges and does not raft. 
+
+\section{Transfer functions}
+
+The rafting transfer function assumes a doubling of ice thickness :
+\begin{equation}
+n^{ra}(h)=\frac{1}{2}\int_0^\infty \delta(h-2h') b(h') g(h') dh,
+\end{equation}
+where $\delta$ is the Dirac delta function. 
+
+The ridging transfer function is :
+\begin{equation}
+n^{ri}(h)=\int_0^\infty \gamma(h',h) (1+p) b(h') g(h') dh.
+\label{eq:nri}
+\end{equation}
+The redistributor $\gamma(h',h)$ specifies how area of thickness $h'$ is redistributed on area of thickness $h$. We follow \citep{hibler_1980} who constructed a rule, based on observations, that forces all ice participating in ridging with thickness $h'$ to be linearly distributed between ice that is between $2h'$ and $2\sqrt{H^*h'}$ thick, where $H^\star=100$ m (\textit{Hstar} in \textit{namelist\_ice}). This in turn determines how to construct the ice volume redistribution function $\Psi^v$. Volumes equal to participating area times thickness are removed from thin ice. They are redistributed following Hibler's rule. The factor $(1+p)$ accounts for initial ridge porosity $p$ (\textit{ridge\_por} in \textit{namelist\_ice}, defined as the fractional volume of seawater initially included into ridges. In many previous models, the initial ridge porosity has been assumed to be 0, which is not the case in reality since newly formed ridges are porous, as indicated by in-situ observations \citep{lepparanta_1995,hoyland_2002}. In other words, LIM3 creates a higher volume of ridged ice with the same participating ice.
+
+For the numerical computation of the integrals, we have to compute several temporary values:
+\begin{itemize}
+\item The thickness of rafted ice $h^{ra}_l = 2 h^i_l$
+\item The mean thickness of ridged ice $h^{ri,mean}_l=\text{max} ( \sqrt{H^\star h^i_l} , h^i_l \cdot 1.1 )$
+\item The minimum thickness of ridged ice $h^{ri,min}_l = \text{min} [ 2*h^i_l, 0.5\cdot(h^{ri,mean}_l+h^i_l) ]$
+\item The maximum thickness of ridged ice $h^{ri,min}_l = 2 h^{ri,mean}_l - h^{ri,min}_l$
+\item The mean rate of thickening of ridged ice $k^{ri}_l = h^{ri,mean}_l / h^{i}_l$
+\end{itemize}
+
+\section{Ridging shift}
+
+%\textit{Subroutine}: \textbf{lim\_itd\_ridgeshift}
+
+The numerical computation of the impact of mechanical redistribution on ice concentration involves:
+\begin{itemize}
+\item A normalization factor that ensures volume conservation (\textit{aksum})
+\item The removal of ice participating in deformation (including the closing of open water)
+\item The addition of deformed ice
+\end{itemize}
+
+For ice concentrations, the numerical procedure reads:
+\begin{equation}
+\Delta g^i_l = C^{net} \Delta t \biggr [ - ( b^{ri}_l + b^{ra}_l) + \sum_{l_2=1}^L \biggr ( f^{ra}_{l,l_2}  \frac{b^{ra}_{l_2}}{k^{ra}} + f^{ri}_{l,l_2} \frac{ b^{ri}_{l_2} }{k^{ri}_{l_2}} \biggr ) \biggr ]
+\end{equation}
+\begin{itemize}
+\item $C^{net}$ is the normalized closing rate ($\vert \dot{\epsilon} \vert \alpha^d/\textit{aksum}$)
+\item $b^{ri}_l$ and $b^{ra}_l$ are the area participating into redistribution for category $l$
+\item $f^{ra}_{l,l_2}$ and $f^{ri}_{l,l_2}$ are the fractions of are of category $l$ being redistributed into category $l_2$
+\item $k^{ra}$ is the rate of thickening of rafted ice (=2)
+\end{itemize}
+
+Because of the nonlinearities involved in the integrals, the ridging procedure has to be iterated until $A^\star = A^{ow} + \sum_{l=1}^L g^i_l = 1$.
+
+\section{Mechanical redistribution for other global ice variables}
+
+The other global ice state variables redistribution functions $\Psi^X$ are computed based on $\Psi^g$ for the ice age content and on $\Psi^{v^i}$ for the remainder (ice enthalpy and salt content, snow volume and enthalpy). The general principles behind this derivation are described in Appendix A of \cite{bitz_2001}. A fraction $f_s=0.5$ (\textit{fsnowrdg} and \textit{fsnowrft} in \textit{namelist\_ice}) of the snow volume and enthalpy is assumed to be lost during ridging and rafting and transferred to the ocean. The contribution of the seawater trapped into the porous ridges is included in the computation of the redistribution of ice enthalpy and salt content (i.e., $\Psi^{e^i}$ and $\Psi^{M^s}$). During this computation, seawater is supposed to be in thermal equilibrium with the surrounding ice blocks. Ridged ice desalination induces an implicit decrease in internal brine volume, and heat supply to the ocean, which accounts for ridge consolidation as described by \cite{hoyland_2002}. The inclusion of seawater in ridges does not imply any net change in ocean salinity. The energy used to cool down the seawater trapped in porous ridges until the seawater freezing point is rejected into the ocean.
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_single_category_use.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_single_category_use.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_single_category_use.tex	(revision 14097)
@@ -0,0 +1,22 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 10 Ñ Single-category use
+% ================================================================
+
+\chapter{Using SI$^3$ with a single category}
+
+\label{chap:INT}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+\section{Enhanced conduction}
+\section{Virtual thin ice melting (fake lateral melting)}
+\section{Ridging and rafting with a single ice category}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_thermo.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_thermo.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_thermo.tex	(revision 14097)
@@ -0,0 +1,88 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 7 Ñ Ice thermodynamics
+% ================================================================
+
+\chapter{Ice thermodynamics}
+\label{chap:THD}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+
+% ================================================================
+% Thermodynamics % ================================================================
+
+Mass, energy and salt are intertwined for sea ice. Referred to as thermodynamics, or more exactly halo-thermodynamics. Mushy-layer theory.
+
+\section{Open water and new ice formation}
+
+% There is everything in here, but there are too much details.
+% Move things around into chapters and summarize.
+
+As part of the sea ice computations, a heat budget of the uppermost oceanic level is estimated. This heat budget is used if negative to compute the production of new ice or, if positive, for bottom melting. 
+
+%--------------------------------------------------------------------------------------------------------------------
+%
+% FIG x : Open water energy budget
+%
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[height=10cm,angle=-00]{Openwater_eb}
+\caption{Scheme of the estimate of the heat budget of the first ocean level.}
+\label{fig_yield}
+\end{center}
+\end{figure}
+%
+%--------------------------------------------------------------------------------------------------------------------
+
+We estimate the heat budget of the first ocean level ($B^{opw}$) assuming four contributions, namely:
+\begin{itemize}
+\item The absorption of a fraction $f_1^{qsr}$ of solar radiation (given by radiative transfer component of the ocean model);
+\item The non-solar heat flux absorbed at the surface;
+\item The sensible heat content of precipitation
+\item The sensible heat loss to the sea ice
+\end{itemize}
+The estimated heat budget thus reads:
+\begin{linenomath}
+\begin{align}
+B^{opw} = Q^{sr} ( 1 - A ) f_1^{qsr} + Q^{ns} ( 1 - A ) + Q^{emp} - A F_w,
+\end{align}
+\end{linenomath}
+Hence there is no consideration of the entrainment of heat at the base of the first ocean level, or of solar radiation transmitted below the ice. The ocean-to-ice turbulent sensible heat flux is formulated following \citep{mcphee_1992}
+\begin{linenomath}
+\begin{align}
+F_w = \rho_0 c_w C_h u^* ( SST - T_b )
+\end{align}
+\end{linenomath}
+where $\rho_0$ is the reference ocean density, $c_w$ is the seawater specific heat, $C_h = 7.5 \times 10^{-3}$ is a heat transfer coefficient, and $u^*=\sqrt{\tau_{iw}/\rho_0}$. There are two additional conditions, the oceanic heat flux cannot be negative. Second, $F_w$ cannot exceed the heat content of the first ocean level.
+
+% Ice growth
+If the $B^{opw}$ is such that the SST would decrease below the freezing point, the remainder of the heat is used to form new ice. The heat loss is converted into mass through [\ref{eq_phasechange}], giving by multiplication by density a volume of new ice $v_0$. The thickness $h_0$ of the new ice grown during a sea ice time step depends on unresolved small currents and waves and is prescribed. The fraction $a_0=v_0/h_0$ is computed accordingly. The salinity of this new ice $S_0$ is given by the S-h empirical relationship of \cite{kovacs_1996}. The temperature assumed for this new ice is the local freezing point.
+
+% Ice melt
+If there is ice in the grid cell and that the $B^{opw}$ is positive, it is directly given attributed to the heat available for bottom melting. This argument follows from \cite{maykut_1995}, who found that most of solar heat absorbed in the surface waters is converted into melting. In practise, this means that the SST cannot go above freezing as long ice is present.
+
+The heat loss used for ice formation, heat gain used to melt ice and the sensible heat given by the ocean to the ice, are all removed from the non-solar heat flux transmitted to the ocean.
+
+Because ice dynamics are not able to maintain the small amount of open water that is observed, a maximum ice fraction ($amax, <1$) is prescribed.
+
+\section{Diffusion of heat}
+
+\section{Vertical growth and melt}
+
+\section{Desalination}
+
+\section{Remapping}
+
+\section{Transport in thickness space}
+
+\section{True lateral melting}
+
+\end{document}
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_transport.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_transport.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/chap_transport.tex	(revision 14097)
@@ -0,0 +1,27 @@
+
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Chapter 4 Ñ Ice transport
+% ================================================================
+
+\chapter{Ice transport}
+\label{chap:TRP}
+\chaptertoc
+
+\newpage
+$\ $\newline    % force a new line
+
+As soon as ice dynamics are activated (\textit{ln\_dyn\_xxx}), all extensive state variables are to be advected following the horizontal velocity field.
+
+\section{Second order moments conserving (Prather 1986) scheme (\textit{ln\_adv\_Pra})}
+
+The scheme of  \cite{prather_1986} explicitly computes the conservation of second-order moments of the spatial distribution of global sea ice state variables. This scheme preserves positivity of the transported variables and is practically non-diffusive. It is also computationally expensive, however it allows to localize the ice edge quite accurately. As the scheme is conditionally stable, the time step is split into two parts if the ice drift is too fast, based on the CFL criterion. 
+
+State variables per unit grid cell area are first multiplied by grid cell area. Then, for each state variable, the 0$^{th}$ (mean), 1$^{st}$ (x, y) and 2$^{nd}$ (xx, xy, yy) order moments of the spatial distribution are transported. At 1st time step, all moments are zero (if prescribed initial state); or read from a restart file, and then evolve through the course of the run. Therefore, for each global variable, 5 additional tracers have to be kept into memory and written in the restart file, which significantly increases the required memory. Advection following x and y are computed independently. The succession order of x- and y- advection is reversed every day.
+
+\section{5$^{th}$ order flux-corrected transport scheme (UM5)}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/todolist.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/todolist.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/SI3/subfiles/todolist.tex	(revision 14097)
@@ -0,0 +1,56 @@
+\documentclass[../main/SI3_manual]{subfiles}
+
+\begin{document}
+
+% ================================================================
+% Dummy Chapter - To do list
+% ================================================================
+
+\chapter*{To-do-list for documentation}
+\label{chap:TDL}
+
+\begin{itemize}
+
+\item \textcolor{gray}{Documentation infrastructure ready by Jul 19, 2018.}
+
+\item \textcolor{gray}{Abstract: v1 written.}
+
+\item \textcolor{gray}{Disclaimer: v1 written.}
+
+\item Introduction: list of chapters and change between realeases to be written (1h)
+
+\item \textcolor{gray}{1. Model basics: v1 written.}
+
+\item \textcolor{gray}{Add namelist infrastructure as in NEMO doc (done)}
+
+\item \textcolor{gray}{2. Time, space and thickness space domain}
+
+\item 3. Ice dynamics: to be written (Clem \& Martin, 3h)
+
+\item 4. Ice transport: UM5 description to be written (Clem, 3h)
+
+\item 5. Ridging and rafting: V1 from previous doc. Should be refreshed. A bit too long. All namelist parameters are not explained (namdyn\_rdgrft).
+
+\item \textcolor{gray}{6. Radiative transfer: Full rewriting required (Martin \& Clem, 3-6h). Available elements from previous documentation, but mostly obsolete.}
+
+\item 7. Thermodynamics: Lots of rewriting required. Available elements from previous documentation, but mostly obsolete (Martin, 6h)
+
+\item 8. Interfaces: Full writing required 
+
+\item 9. Output and diagnostics: Full writing required
+
+\item 10. Single category (Martin, 3h). Full writing required.
+
+\item 11. BDY-AGRIF (Clem, 3h). Full writing required.
+
+\item 12. Miscellaneous. Full writing required.
+
+\item Melt ponds are not currently considered in the plan.
+
+\item Make sure all namelist parameters are properly described.
+
+\item Peer-review by SIWG members.
+
+\end{itemize}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/TOP_manual.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/TOP_manual.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/TOP_manual.tex	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../global/document.tex
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/abstract.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/abstract.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/abstract.tex	(revision 14097)
@@ -0,0 +1,26 @@
+%% ================================================================
+%% Abstract
+%% ================================================================
+
+%% Common part between NEMO-SI3-TOP
+``Tracers in Ocean Paradigm'' (\TOP) is the passive tracers engine of
+the \NEMO\ ocean model (``Nucleus for European Modelling of the Ocean'').
+It is intended to be a flexible tool for studying the on/offline oceanic tracers transport and
+the biogeochemical processes (``green ocean''),
+as well as its interactions with the other components of the Earth climate system over
+a wide range of space and time scales.
+\TOP\ is interfaced with the \NEMO\ ocean engine, and,
+via the \href{http://portal.enes.org/oasis}{OASIS} coupler,
+with several atmospheric general circulation models.
+%It also supports two-way grid embedding by means of the \href{http://agrif.imag.fr}{AGRIF} software.
+
+%% Specific part
+This component provides the physical constraints and boundaries conditions for
+oceanic tracers transport and represents a generalized, hardwired interface toward
+biogeochemical models to enable a seamless coupling.
+In particular, transport dynamics are supplied by the ocean dynamical core thus
+enabling the use of all available advection and diffusion schemes in both on- and off-line modes.
+\TOP\ is designed to handle multiple oceanic tracers through a modular approach and
+it includes different sub-modules: ocean water age, inorganic carbon (CFCs) \& radiocarbon (C14b),
+built-in biogeochemical model (PISCES), and prototype for user-defined cases or
+coupling with alternative biogeochemical models (\eg \href{http://www.bfm-community.eu}{BFM}).
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/authors.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/authors.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/authors.tex	(revision 14097)
@@ -0,0 +1,7 @@
+Olivier Aumont         \\
+Christian \'{E}th\'{e} \\
+Tomas Lovato           \\
+Anne Mouchet           \\
+Georges Nurser         \\
+Julien Palmi\'{e}ri    \\
+Andrew Yool
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/bibliography.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/bibliography.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/bibliography.bib	(revision 14097)
@@ -0,0 +1,619 @@
+
+@Article{	  ahn_2007,
+  author	= {Ahn, Jinho and Brook, Edward J.},
+  title		= {Atmospheric CO2and climate from 65 to 30 ka B.P.},
+  year		= 2007,
+  volume	= 34,
+  number	= 10,
+  month		= {May},
+  issn		= {0094-8276},
+  doi		= {10.1029/2007gl029551},
+  url		= {http://dx.doi.org/10.1029/2007GL029551},
+  journal	= {Geophysical Research Letters},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  ahn_2008,
+  author	= {Ahn, J. and Brook, E. J.},
+  title		= {Atmospheric CO2 and Climate on Millennial Time Scales
+		  During the Last Glacial Period},
+  year		= 2008,
+  volume	= 322,
+  number	= 5898,
+  month		= {Oct},
+  pages		= {83–85},
+  issn		= {1095-9203},
+  doi		= {10.1126/science.1160832},
+  url		= {http://dx.doi.org/10.1126/science.1160832},
+  journal	= {Science},
+  publisher	= {American Association for the Advancement of Science
+		  (AAAS)}
+}
+
+@Article{	  armstrong_2001,
+  author	= {Armstrong, Robert A. and Lee, Cindy and Hedges, John I.
+		  and Honjo, Susumu and Wakeham, Stuart G.},
+  title		= {A new, mechanistic model for organic carbon fluxes in the
+		  ocean based on the quantitative association of POC with
+		  ballast minerals},
+  year		= 2001,
+  volume	= 49,
+  number	= {1-3},
+  month		= {Jan},
+  pages		= {219–236},
+  issn		= {0967-0645},
+  doi		= {10.1016/s0967-0645(01)00101-1},
+  url		= {http://dx.doi.org/10.1016/S0967-0645(01)00101-1},
+  journal	= {Deep Sea Research Part II: Topical Studies in
+		  Oceanography},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  aumont_2015,
+  author	= {Aumont, O. and Ethé, C. and Tagliabue, A. and Bopp, L.
+		  and Gehlen, M.},
+  title		= {PISCES-v2: an ocean biogeochemical model for carbon and
+		  ecosystem studies},
+  year		= 2015,
+  volume	= 8,
+  number	= 8,
+  month		= {Aug},
+  pages		= {2465–2513},
+  issn		= {1991-9603},
+  doi		= {10.5194/gmd-8-2465-2015},
+  url		= {http://dx.doi.org/10.5194/gmd-8-2465-2015},
+  journal	= {Geoscientific Model Development},
+  publisher	= {Copernicus GmbH}
+}
+
+@Article{	  bacastow_1990,
+  author	= {Bacastow, R and Maier-Reimer, E},
+  title		= {Ocean-circulation model of the carbon cycle},
+  year		= 1990,
+  volume	= 4,
+  number	= 2,
+  month		= {Apr},
+  pages		= {95–125},
+  issn		= {1432-0894},
+  doi		= {10.1007/bf00208905},
+  url		= {http://dx.doi.org/10.1007/bf00208905},
+  journal	= {Climate Dynamics},
+  publisher	= {Springer Nature}
+}
+
+@Misc{		  bullister_2017,
+  author	= {Bullister, J.L.},
+  title		= {Atmospheric Histories (1765-2015) for CFC-11, CFC-12,
+		  CFC-113, CCl4, SF6 and N2O (NCEI Accession 0164584)},
+  year		= 2017,
+  doi		= {10.3334/cdiac/otg.cfc\_atm\_hist\_2015},
+  url		= {https://accession.nodc.noaa.gov/0164584},
+  publisher	= {NOAA National Centers for Environmental Information}
+}
+
+@Article{	  butzin_2005,
+  author	= {BUTZIN, M and PRANGE, M and LOHMANN, G},
+  title		= {Radiocarbon simulations for the glacial ocean: The effects
+		  of wind stress, Southern Ocean sea ice and Heinrich
+		  events},
+  year		= 2005,
+  volume	= 235,
+  number	= {1-2},
+  month		= {Jun},
+  pages		= {45–61},
+  issn		= {0012-821X},
+  doi		= {10.1016/j.epsl.2005.03.003},
+  url		= {http://dx.doi.org/10.1016/j.epsl.2005.03.003},
+  journal	= {Earth and Planetary Science Letters},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  danabasoglu_2014,
+  author	= {Danabasoglu, Gokhan and Yeager, Steve G. and Bailey, David
+		  and Behrens, Erik and Bentsen, Mats and Bi, Daohua and
+		  Biastoch, Arne and Böning, Claus and Bozec, Alexandra and
+		  Canuto, Vittorio M. and et al.},
+  title		= {North Atlantic simulations in Coordinated Ocean-ice
+		  Reference Experiments phase II (CORE-II). Part I: Mean
+		  states},
+  year		= 2014,
+  volume	= 73,
+  month		= {Jan},
+  pages		= {76–107},
+  issn		= {1463-5003},
+  doi		= {10.1016/j.ocemod.2013.10.005},
+  url		= {http://dx.doi.org/10.1016/j.ocemod.2013.10.005},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  dutay_2002,
+  author	= {Dutay, J.-C and Bullister, J.L and Doney, S.C and Orr, J.C
+		  and Najjar, R and Caldeira, K and Campin, J.-M and Drange,
+		  H and Follows, M and Gao, Y and et al.},
+  title		= {Evaluation of ocean model ventilation with CFC-11:
+		  comparison of 13 global ocean models},
+  year		= 2002,
+  volume	= 4,
+  number	= 2,
+  month		= {Jan},
+  pages		= {89–120},
+  issn		= {1463-5003},
+  doi		= {10.1016/s1463-5003(01)00013-0},
+  url		= {http://dx.doi.org/10.1016/S1463-5003(01)00013-0},
+  journal	= {Ocean Modelling},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  enting_1994,
+  author	= {G Enting, I and M L Wigley, T and Heimann, Martin},
+  year		= {1994},
+  month		= {01},
+  pages		= {},
+  title		= {Future Emissions and Concentrations of Carbon Dioxide: Key
+		  Ocean/Atmosphere/Land Analyses},
+  volume	= {31},
+  journal	= {CSIRO Division Atmospheric Research Technical Paper}
+}
+
+@Article{	  fiadeiro_1982,
+  author	= {Fiadeiro, M.E.},
+  year		= {1982},
+  month		= {01},
+  pages		= {537-550},
+  title		= {Three-dimensional modeling of tracers in the deep Pacific
+		  Ocean II. Radiocarbon and the circulation},
+  volume	= {40},
+  journal	= {J. Mar. Res.}
+}
+
+@Article{	  fluckiger_2002,
+  author	= {Flückiger, Jacqueline and Monnin, Eric and Stauffer,
+		  Bernhard and Schwander, Jakob and Stocker, Thomas F. and
+		  Chappellaz, Jérôme and Raynaud, Dominique and Barnola,
+		  Jean-Marc},
+  title		= {High-resolution Holocene N2O ice core record and its
+		  relationship with CH4and CO2},
+  year		= 2002,
+  volume	= 16,
+  number	= 1,
+  month		= {Feb},
+  pages		= {10–1–10–8},
+  issn		= {0886-6236},
+  doi		= {10.1029/2001gb001417},
+  url		= {http://dx.doi.org/10.1029/2001GB001417},
+  journal	= {Global Biogeochemical Cycles},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  haine_2006,
+  author	= {Haine, T. W. N.},
+  title		= {On tracer boundary conditions for geophysical reservoirs:
+		  How to find the boundary concentration from a mixed
+		  condition},
+  year		= 2006,
+  volume	= 111,
+  number	= {C5},
+  issn		= {0148-0227},
+  doi		= {10.1029/2005jc003215},
+  url		= {http://dx.doi.org/10.1029/2005JC003215},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Book{		  honjo_1996,
+  title		= {Fluxes of Particles to the Interior of the Open Oceans},
+  author	= {Honjo, S.},
+  url		= {https://books.google.fr/books?id=FwA6cgAACAAJ},
+  year		= {1996},
+  publisher	= {John Wiley \& Sons}
+}
+
+@Article{	  joos_1997,
+  author	= {Joos, Fortunat and Orr, James C. and Siegenthaler,
+		  Ulrich},
+  title		= {Ocean carbon transport in a box-diffusion versus a general
+		  circulation model},
+  year		= 1997,
+  volume	= 102,
+  number	= {C6},
+  month		= {Jun},
+  pages		= {12367–12388},
+  issn		= {0148-0227},
+  doi		= {10.1029/97jc00470},
+  url		= {http://dx.doi.org/10.1029/97JC00470},
+  journal	= {Journal of Geophysical Research: Oceans},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  key_2004,
+  author	= {Key, R. M. and Kozyr, A. and Sabine, C. L. and Lee, K. and
+		  Wanninkhof, R. and Bullister, J. L. and Feely, R. A. and
+		  Millero, F. J. and Mordy, C. and Peng, T.-H.},
+  title		= {A global ocean carbon climatology: Results from Global
+		  Data Analysis Project (GLODAP)},
+  year		= 2004,
+  volume	= 18,
+  number	= 4,
+  month		= {Dec},
+  pages		= {n/a–n/a},
+  issn		= {0886-6236},
+  doi		= {10.1029/2004gb002247},
+  url		= {http://dx.doi.org/10.1029/2004gb002247},
+  journal	= {Global Biogeochemical Cycles},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  kortzinger_2001,
+  author	= {Körtzinger, Arne and Hedges, John I. and Quay, Paul D.},
+  title		= {Redfield ratios revisited: Removing the biasing effect of
+		  anthropogenic CO2},
+  year		= 2001,
+  volume	= 46,
+  number	= 4,
+  month		= {Jun},
+  pages		= {964–970},
+  issn		= {0024-3590},
+  doi		= {10.4319/lo.2001.46.4.0964},
+  url		= {http://dx.doi.org/10.4319/lo.2001.46.4.0964},
+  journal	= {Limnology and Oceanography},
+  publisher	= {Wiley}
+}
+
+@Manual{	  nemo_manual,
+  author	= {Madec Gurvan and NEMO System Team},
+  title		= {NEMO ocean engine},
+  organization	= {NEMO Consortium},
+  journal	= {Notes du Pôle de modélisation de l\'Institut
+		  Pierre-Simon Laplace (IPSL)},
+  issn		= {1288-1619},
+  number	= {27},
+  publisher	= {Zenodo},
+  doi		= {10.5281/zenodo.1464816},
+  url		= {https://zenodo.org/record/1464816},
+  edition	= {TBD},
+  year		= {TBD}
+}
+
+@Article{	  meunier_2014,
+  author	= {Meunier, Cédric L. and Malzahn, Arne M. and Boersma,
+		  Maarten},
+  title		= {A New Approach to Homeostatic Regulation: Towards a
+		  Unified View of Physiological and Ecological Concepts},
+  year		= 2014,
+  editor	= {Munn, Adam J.Editor},
+  volume	= 9,
+  number	= 9,
+  month		= {Sep},
+  pages		= {e107737},
+  issn		= {1932-6203},
+  doi		= {10.1371/journal.pone.0107737},
+  url		= {http://dx.doi.org/10.1371/journal.pone.0107737},
+  journal	= {PLoS ONE},
+  publisher	= {Public Library of Science (PLoS)}
+}
+
+@Article{	  monnin_2001,
+  author	= {Monnin, E.},
+  title		= {Atmospheric CO2 Concentrations over the Last Glacial
+		  Termination},
+  year		= 2001,
+  volume	= 291,
+  number	= 5501,
+  month		= {Jan},
+  pages		= {112–114},
+  issn		= {1095-9203},
+  doi		= {10.1126/science.291.5501.112},
+  url		= {http://dx.doi.org/10.1126/science.291.5501.112},
+  journal	= {Science},
+  publisher	= {American Association for the Advancement of Science
+		  (AAAS)}
+}
+
+@Article{	  monnin_2004,
+  author	= {Monnin, Eric and Steig, Eric J and Siegenthaler, Urs and
+		  Kawamura, Kenji and Schwander, Jakob and Stauffer, Bernhard
+		  and Stocker, Thomas F and Morse, David L and Barnola,
+		  Jean-Marc and Bellier, Blandine and et al.},
+  title		= {Evidence for substantial accumulation rate variability in
+		  Antarctica during the Holocene, through synchronization of
+		  CO 2 in the Taylor Dome, Dome C and DML ice cores},
+  year		= 2004,
+  volume	= 224,
+  number	= {1-2},
+  month		= {Jul},
+  pages		= {45–54},
+  issn		= {0012-821X},
+  doi		= {10.1016/j.epsl.2004.05.007},
+  url		= {http://dx.doi.org/10.1016/j.epsl.2004.05.007},
+  journal	= {Earth and Planetary Science Letters},
+  publisher	= {Elsevier BV}
+}
+
+@Book{		  monod_1958,
+  title		= {Recherches sur la croissance des cultures
+		  bact{\'e}riennes},
+  author	= {Monod, J.},
+  lccn		= {nlm11031168},
+  series	= {Actualit{\'e}s scientifiques et industrielles},
+  url		= {https://books.google.fr/books?id=yhy6AAAAIAAJ},
+  year		= {1958},
+  publisher	= {Hermann}
+}
+
+@Article{	  mouchet_2013,
+  author	= {Mouchet, Anne},
+  title		= {The Ocean Bomb Radiocarbon Inventory Revisited},
+  year		= 2013,
+  volume	= 55,
+  number	= {3–4},
+  issn		= {0033-8222},
+  doi		= {10.2458/azu\_js\_rc.55.16402},
+  url		= {http://dx.doi.org/10.2458/azu\_js\_rc.55.16402},
+  journal	= {Radiocarbon},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  naegler_2009,
+  author	= {Naegler, Tobias},
+  title		= {Reconciliation of excess14C-constrained global CO2piston
+		  velocity estimates},
+  year		= 2009,
+  volume	= 61,
+  number	= 2,
+  month		= {Jan},
+  pages		= {372–384},
+  issn		= {1600-0889},
+  doi		= {10.1111/j.1600-0889.2008.00408.x},
+  url		= {http://dx.doi.org/10.1111/j.1600-0889.2008.00408.x},
+  journal	= {Tellus B: Chemical and Physical Meteorology},
+  publisher	= {Informa UK Limited}
+}
+
+@TechReport{	  orr_2000,
+  author	= {Orr, J. and Najjar, R. and Sabine, C. and Joos, F.},
+  title		= {Abiotic-HOWTO. Ocean-Carbon Cycle Model Intercomparison
+		  Project (OCMIP)},
+  url		= {http://ocmip5.ipsl.jussieu.fr/OCMIP/},
+  year		= {2000}
+}
+
+@Article{	  orr_2001,
+  author	= {Orr, James C. and Maier-Reimer, Ernst and Mikolajewicz,
+		  Uwe and Monfray, Patrick and Sarmiento, Jorge L. and
+		  Toggweiler, J. R. and Taylor, Nicholas K. and Palmer,
+		  Jonathan and Gruber, Nicolas and Sabine, Christopher L. and
+		  et al.},
+  title		= {Estimates of anthropogenic carbon uptake from four
+		  three-dimensional global ocean models},
+  year		= 2001,
+  volume	= 15,
+  number	= 1,
+  month		= {Mar},
+  pages		= {43–60},
+  issn		= {0886-6236},
+  doi		= {10.1029/2000gb001273},
+  url		= {http://dx.doi.org/10.1029/2000GB001273},
+  journal	= {Global Biogeochemical Cycles},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  orr_2017,
+  author	= {Orr, James C. and Najjar, Raymond G. and Aumont, Olivier
+		  and Bopp, Laurent and Bullister, John L. and Danabasoglu,
+		  Gokhan and Doney, Scott C. and Dunne, John P. and Dutay,
+		  Jean-Claude and Graven, Heather and et al.},
+  title		= {Biogeochemical protocols and diagnostics for the CMIP6
+		  Ocean Model Intercomparison Project (OMIP)},
+  year		= 2017,
+  volume	= 10,
+  number	= 6,
+  month		= {Jun},
+  pages		= {2169–2199},
+  issn		= {1991-9603},
+  doi		= {10.5194/gmd-10-2169-2017},
+  url		= {http://dx.doi.org/10.5194/gmd-10-2169-2017},
+  journal	= {Geoscientific Model Development},
+  publisher	= {Copernicus GmbH}
+}
+
+@Article{	  palmieri_2015,
+  author	= {Palmiéri, J. and Orr, J. C. and Dutay, J.-C. and
+		  Béranger, K. and Schneider, A. and Beuvier, J. and Somot,
+		  S.},
+  title		= {Simulated anthropogenic CO$_{2}$ storage
+		  and acidification of the Mediterranean Sea},
+  year		= 2015,
+  volume	= 12,
+  number	= 3,
+  month		= {Feb},
+  pages		= {781–802},
+  issn		= {1726-4189},
+  doi		= {10.5194/bg-12-781-2015},
+  url		= {http://dx.doi.org/10.5194/bg-12-781-2015},
+  journal	= {Biogeosciences},
+  publisher	= {Copernicus GmbH}
+}
+
+@Article{	  reimer_2013,
+  author	= {Reimer, Paula J and Bard, Edouard and Bayliss, Alex and
+		  Beck, J Warren and Blackwell, Paul G and Ramsey,
+		  Christopher Bronk and Buck, Caitlin E and Cheng, Hai and
+		  Edwards, R Lawrence and Friedrich, Michael and et al.},
+  title		= {IntCal13 and Marine13 Radiocarbon Age Calibration Curves
+		  0–50,000 Years cal BP},
+  year		= 2013,
+  volume	= 55,
+  number	= 4,
+  pages		= {1869–1887},
+  issn		= {1945-5755},
+  doi		= {10.2458/azu\_js\_rc.55.16947},
+  url		= {http://dx.doi.org/10.2458/azu\_js\_rc.55.16947},
+  journal	= {Radiocarbon},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  sterner_2003,
+  author	= {Sterner, Robert W. and Elser, James J.},
+  title		= {Ecological Stoichiometry},
+  year		= 2003,
+  month		= {Dec},
+  doi		= {10.1515/9781400885695},
+  url		= {http://dx.doi.org/10.1515/9781400885695},
+  isbn		= 9781400885695,
+  publisher	= {Princeton University Press}
+}
+
+@Article{	  stuiver_1977,
+  author	= {Stuiver, Minze and Polach, Henry A},
+  title		= {Discussion Reporting of 14C Data},
+  year		= 1977,
+  volume	= 19,
+  number	= 03,
+  pages		= {355–363},
+  issn		= {1945-5755},
+  doi		= {10.1017/s0033822200003672},
+  url		= {http://dx.doi.org/10.1017/s0033822200003672},
+  journal	= {Radiocarbon},
+  publisher	= {Cambridge University Press (CUP)}
+}
+
+@Article{	  takahashi_1985,
+  author	= {Takahashi, Taro and Broecker, Wallace S. and Langer,
+		  Sara},
+  title		= {Redfield ratio based on chemical data from isopycnal
+		  surfaces},
+  year		= 1985,
+  volume	= 90,
+  number	= {C4},
+  pages		= 6907,
+  issn		= {0148-0227},
+  doi		= {10.1029/jc090ic04p06907},
+  url		= {http://dx.doi.org/10.1029/jc090ic04p06907},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  toggweiler_1989a,
+  author	= {Toggweiler, J. R. and Dixon, K. and Bryan, K.},
+  title		= {Simulations of radiocarbon in a coarse-resolution world
+		  ocean model: 1. Steady state prebomb distributions},
+  year		= 1989,
+  volume	= 94,
+  number	= {C6},
+  pages		= 8217,
+  issn		= {0148-0227},
+  doi		= {10.1029/jc094ic06p08217},
+  url		= {http://dx.doi.org/10.1029/JC094iC06p08217},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  toggweiler_1989b,
+  author	= {Toggweiler, J. R. and Dixon, K. and Bryan, K.},
+  title		= {Simulations of radiocarbon in a coarse-resolution world
+		  ocean model: 2. Distributions of bomb-produced carbon 14},
+  year		= 1989,
+  volume	= 94,
+  number	= {C6},
+  pages		= 8243,
+  issn		= {0148-0227},
+  doi		= {10.1029/jc094ic06p08243},
+  url		= {http://dx.doi.org/10.1029/JC094iC06p08243},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  wanninkhof_1992,
+  author	= {Wanninkhof, Rik},
+  title		= {Relationship between wind speed and gas exchange over the
+		  ocean},
+  year		= 1992,
+  volume	= 97,
+  number	= {C5},
+  pages		= 7373,
+  issn		= {0148-0227},
+  doi		= {10.1029/92jc00188},
+  url		= {http://dx.doi.org/10.1029/92jc00188},
+  journal	= {Journal of Geophysical Research},
+  publisher	= {American Geophysical Union (AGU)}
+}
+
+@Article{	  wanninkhof_1996,
+  author	= {Wanninkhof, Rik and Knox, Molly},
+  title		= {Chemical enhancement of CO2exchange in natural waters},
+  year		= 1996,
+  volume	= 41,
+  number	= 4,
+  month		= {Jun},
+  pages		= {689–697},
+  issn		= {0024-3590},
+  doi		= {10.4319/lo.1996.41.4.0689},
+  url		= {http://dx.doi.org/10.4319/lo.1996.41.4.0689},
+  journal	= {Limnology and Oceanography},
+  publisher	= {Wiley}
+}
+
+@Article{	  wanninkhof_2014,
+  author	= {Wanninkhof, Rik},
+  title		= {Relationship between wind speed and gas exchange over the
+		  ocean revisited},
+  year		= 2014,
+  volume	= 12,
+  number	= 6,
+  month		= {Jun},
+  pages		= {351–362},
+  issn		= {1541-5856},
+  doi		= {10.4319/lom.2014.12.351},
+  url		= {http://dx.doi.org/10.4319/lom.2014.12.351},
+  journal	= {Limnology and Oceanography: Methods},
+  publisher	= {Wiley}
+}
+
+@Article{	  warner_1985,
+  author	= {Warner, M.J. and Weiss, R.F.},
+  title		= {Solubilities of chlorofluorocarbons 11 and 12 in water and
+		  seawater},
+  year		= 1985,
+  volume	= 32,
+  number	= 12,
+  month		= {Dec},
+  pages		= {1485–1497},
+  issn		= {0198-0149},
+  doi		= {10.1016/0198-0149(85)90099-8},
+  url		= {http://dx.doi.org/10.1016/0198-0149(85)90099-8},
+  journal	= {Deep Sea Research Part A. Oceanographic Research Papers},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  weiss_1974,
+  author	= {Weiss, R.F.},
+  title		= {Carbon dioxide in water and seawater: the solubility of a
+		  non-ideal gas},
+  year		= 1974,
+  volume	= 2,
+  number	= 3,
+  month		= {Nov},
+  pages		= {203–215},
+  issn		= {0304-4203},
+  doi		= {10.1016/0304-4203(74)90015-2},
+  url		= {http://dx.doi.org/10.1016/0304-4203(74)90015-2},
+  journal	= {Marine Chemistry},
+  publisher	= {Elsevier BV}
+}
+
+@Article{	  woods_2013,
+  author	= {Woods, H. Arthur and Wilson, J. Keaton},
+  title		= {An information hypothesis for the evolution of
+		  homeostasis},
+  year		= 2013,
+  volume	= 28,
+  number	= 5,
+  month		= {May},
+  pages		= {283–289},
+  issn		= {0169-5347},
+  doi		= {10.1016/j.tree.2012.10.021},
+  url		= {http://dx.doi.org/10.1016/j.tree.2012.10.021},
+  journal	= {Trends in Ecology \& Evolution},
+  publisher	= {Elsevier BV}
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/chapters.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/chapters.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/chapters.tex	(revision 14097)
@@ -0,0 +1,3 @@
+\subfile{../subfiles/model_description}
+\subfile{../subfiles/model_setup}
+\subfile{../subfiles/miscellaneous}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/introduction.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/introduction.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/introduction.tex	(revision 14097)
@@ -0,0 +1,42 @@
+% ================================================================
+% INTRODUCTION
+% ================================================================
+
+\chapter*{Introduction}
+
+TOP (Tracers in the Ocean Paradigm) handles oceanic passive tracers in NEMO. At present, this component provides the physical constraints and boundaries conditions for oceanic tracers transport and represents a generalized, hardwired interface toward biogeochemical models to enable a seamless coupling.
+
+It includes three independent components :
+
+\begin{itemize}
+        \item a transport code TRP sharing the same advection/diffusion routines with the dynamics, with specific treatment of some features like the surface boundary
+conditions, or the positivity of passive tracers concentrations
+        \item sources and sinks - SMS - models that can be typically biogeochemical, biological or radioactive
+        \item an offline option which is a simplified OPA 9 model using fields of physics variables that are previously stored to disk
+\end{itemize}
+
+There is two ways of coupling TOP to the dynamics :
+
+\begin{itemize}
+        \item \textit{online coupling} : the evolution of passive tracers is computed along with the dynamics
+        \item \textit{offline coupling} : the fields of physics variables are read from files and interpolated at each model time step, with no constraints on the time sampling in the input files
+\end{itemize}
+
+TOP is designed to handle multiple oceanic tracers through a modular approach and it includes different sub-modules :
+
+\begin{itemize}
+        \item the ocean water age module (AGE) tracks down the time-dependent spread of surface waters into the ocean interior
+        \item inorganic carbon (e.g. CFCs, SF6) and radiocarbon (C14) passive tracers can be modeled to assess ocean absorption timescales of anthropogenic emissions and further address water masses ventilation
+        \item a built-in biogeochemical model (PISCES) to simulate lower trophic levels ecosystem dynamics in the global ocean
+        \item a prototype tracer module (MY\_TRC) to enable user-defined cases or the coupling with alternative biogeochemical models ( e.g. BFM, MEDUSA, ERSEM, BFM, ECO3M)
+\end{itemize}
+
+\begin{figure}[ht]
+\begin{center}
+\vspace{0cm}
+\includegraphics[width=0.80\textwidth]{Fig_TOP_design}
+%\includegraphics[height=6cm,angle=-00]{Fig_TOP_design}
+\caption{A schematic view of NEMO-TOP component}
+\label{topdesign}
+\end{center}
+\end{figure}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/settings.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/settings.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/settings.tex	(revision 14097)
@@ -0,0 +1,20 @@
+%% Engine (folder name)
+\def \engine{TOP}
+
+%% Title and cover page settings
+\def \spacetop{  \vspace*{1.3cm} }
+\def \heading{Tracers in Ocean Paradigm (TOP)}
+\def \subheading{The NEMO passive tracers engine}
+\def \spacedown{ \vspace*{  1cm} }
+\def \authorswidth{0.15\linewidth}
+\def \rulelenght{110pt}
+\def \abstractwidth{0.7\linewidth}
+
+%% Color for document (frontpage banner, links and chapter boxes)
+\def \setmanualcolor{ \definecolor{manualcolor}{cmyk}{1, 0, 1, .4} }
+
+%% IPSL publication number
+\def \ipslnum{28}
+
+%% Zenodo ID, i.e. doi:10.5281/zenodo.\([0-9]*\)
+\def \zid{1471700}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/main/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/blocks.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/blocks.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/blocks.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/blocks.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/byrd-co2-2008.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/byrd-co2-2008.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/byrd-co2-2008.txt	(revision 14097)
@@ -0,0 +1,273 @@
+Byrd Ice Core CO2 Data for 20-90 KYrBP
+-----------------------------------------------------------------------
+               World Data Center for Paleoclimatology, Boulder
+                                  and
+                     NOAA Paleoclimatology Program
+-----------------------------------------------------------------------
+NOTE: PLEASE CITE ORIGINAL REFERENCE WHEN USING THIS DATA!!!!!
+
+
+NAME OF DATA SET: Byrd Ice Core CO2 Data for 20-90 KYrBP
+
+LAST UPDATE: 10/2008 (Original receipt by WDC Paleo)
+CONTRIBUTORS: Jinho Ahn and Edward J. Brook
+IGBP PAGES/WDCA CONTRIBUTION SERIES NUMBER: 2008-095
+
+WDC PALEO CONTRIBUTION SERIES CITATION: 
+Ahn, J. and E.J. Brook. 2008.
+Byrd Ice Core CO2 Data for 20-90 KYrBP. 
+IGBP PAGES/World Data Center for Paleoclimatology 
+Data Contribution Series # 2008-095. 
+NOAA/NCDC Paleoclimatology Program, Boulder CO, USA.
+
+
+ORIGINAL REFERENCES: 
+References for CO2 data: 
+ 
+Ahn, J. and E.J. Brook. 2008.
+Atmospheric CO2 and Climate on Millennial Time Scales During 
+the Last Glacial Period. 
+Science, 322, 83-85, doi: 10.1126/science.1160832.
+
+Ahn, J. and Brook, E.J.  2007.  
+Atmospheric CO2 and climate from 65 to 30 ka B.P.. 
+Geophysical Research Letters, 34, L10703, doi:10.1029/2007GL029551.
+
+ 
+References for CO2 age:	 
+  
+Blunier-01 age: 
+Blunier, T., and Brook, E.J.  2001. 
+Timing of millennial-scale climate change in Antarctica and Greenland 
+during the last glacial period.  
+Science, 291, 109-112.  
+	   
+Ahn-08 age: 
+Ahn, J. and E.J. Brook. 2008.
+Atmospheric CO2 and Climate on Millennial Time Scales During 
+the Last Glacial Period. 
+Science, 322, 83-85, doi: 10.1126/science.1160832.
+
+
+ABSTRACT (Ahn and Brook 2008):
+Reconstructions of ancient atmospheric carbon dioxide (CO2) variations 
+help us better understand how the global carbon cycle and climate are 
+linked.  We compared CO2 variations on millennial time scales between 
+20,000 and 90,000 years ago with an Antarctic temperature proxy and 
+records of abrupt climate change in the Northern Hemisphere. CO2 
+concentration and Antarctic temperature were positively correlated 
+over millennial-scale climate cycles, implying a strong connection 
+to Southern Ocean processes. Evidence from marine sediment proxies 
+indicates that CO2 concentration rose most rapidly when North Atlantic 
+Deep Water shoaled and stratification in the Southern Ocean was reduced. 
+These increases in CO2 concentration occurred during stadial (cold) 
+periods in the Northern Hemisphere, several thousand years before 
+abrupt warming events in Greenland.
+
+
+
+GEOGRAPHIC REGION: Antarctica
+PERIOD OF RECORD:  90 - 20 KYrBP
+
+FUNDING SOURCES: 
+Gary Comer Science and Education Foundation, and
+US National Science Foundation  grants OPP 0337891 and ATM 0602395.
+
+
+
+DESCRIPTION:  
+Byrd ice core carbon dioxide data for 20-90 KYrBP, analyzed at 
+Oregon State University.  
+
+Byrd Ice Core location: 
+80.01°S , 119.51°W; 1530 m elev. 
+  
+
+
+
+DATA:
+Byrd Ice Core CO2 Data for 20-90 KYrBP
+
+Column 1: Depth (m) 
+Column 2: Blunier 2001 Age (ka before 1950 AD)
+Column 3: Ahn 2008 Age (ka before 1950 AD)
+Column 4: Mean CO2 (ppm)
+Column 5: Number of replicates
+Column 6: Uncertainty (ppm)*
+Column 7: Reference
+
+*Uncertainty is estimated from the standard deviation of the mean for 2~5 ice samples
+
+Depth       Age Bl01  Age Ahn08   Mean CO2    Repl.  Uncert.    Ref.
+1315.91       19.460     19.286     194.36      2     0.97     AB-08
+1332.34       20.061     19.887     191.14      2     0.19     AB-08
+1334.20       20.152     19.978     192.54      2     0.09     AB-08
+1346.28       20.578     20.404     204.27      2     0.48     AB-08
+1353.02       20.759     20.585     195.37      2     0.02     AB-08
+1363.17       21.065     20.891     197.12      2     1.04     AB-08
+1381.14       21.731     21.557     195.81      2     1.66     AB-08
+1401.95       22.399     22.225     199.75      3     4.49     AB-08
+1410.30       22.729     22.555     194.62      2     0.31     AB-08
+1420.27       23.530     23.356     195.97      2     1.88     AB-08
+1430.78       24.824     24.650     194.74      2     1.94     AB-08
+1441.45       26.002     25.828     189.76      2     1.30     AB-08
+1460.20       26.711     26.537     192.21      2     1.28     AB-08
+1470.77       27.148     26.974     184.40      2     1.42     AB-08
+1480.48       27.619     27.445     188.07      2     1.48     AB-08
+1490.87       27.989     27.815     201.96      2     0.46     AB-08
+1496.52       28.135     27.961     204.98      2     1.71     AB-08
+1503.54       28.395     28.221     205.91      3     2.43     AB-08
+1512.46       28.660     28.486     207.48      2     1.73     AB-08
+1523.46       29.147     28.973     205.54      2     0.40     AB-08
+1533.76       29.568     29.396     201.49      2     1.84     AB-08
+1543.63       30.013     29.843     197.51      2     3.18     AB-08
+1552.76       30.412     30.245     195.36      2     0.89     AB-08
+1573.34       31.216     31.053     195.09      3     2.37     AB-08
+1581.93       31.738     31.577     202.29      2     0.38     AB-08
+1594.06       32.328     32.170     203.67      2     0.40     AB-08
+1615.15       33.450     33.297     208.11      2     0.11     AB-08
+1620.38       33.692     33.541     205.25      2     0.53     AB-08
+1631.11       34.183     34.033     201.53      2     1.67     AB-08
+1640.90       34.630     34.484     213.08      2     0.47     AB-08
+1650.56       35.097     34.953     206.62      2     1.72     AB-08
+1658.96       35.428     35.286     209.93      2     1.10     AB-08
+1677.79       36.249     36.111     207.76      2     0.00     AB-08
+1688.63       36.840     36.704     212.63      2     0.99     AB-08
+1693.68       37.167     37.033     213.98      2     1.37     AB-08
+1699.73       37.621     37.488     217.48      2     1.16     AB-08
+1708.70       38.122     37.992     216.21      2     1.03     AB-08
+1714.20       38.428     38.298     216.52      2     2.21     AB-08
+1717.20       38.545     38.415     212.50      2     1.51     AB-08
+1719.47       38.655     38.520     211.09      2     1.83     AB-08
+1723.22       38.850     38.708     214.78      2     2.64     AB-08
+1730.78       39.163     39.006     207.63      2     0.18     AB-08
+1740.51       39.539     39.364     214.06      2     0.14     AB-08
+1743.27       39.651     39.470     213.84      2     1.23     AB-08
+1747.69       39.811     39.621     203.03      2     1.03     AB-08
+1755.15       40.038     39.834     202.11      2     0.45     AB-08
+1760.29       40.172     39.958     203.78      2     2.59     AB-08
+1770.24       40.544     40.311     203.40      2     1.56     AB-08
+1779.99       40.966     40.714     201.30      2     1.46     AB-08
+1790.29       41.585     41.313     202.69      2     2.43     AB-08
+1802.03       42.320     42.025     204.64      2     0.56     AB-08
+1811.74       42.851     42.537     207.18      2     1.53     AB-08
+1821.19       43.591     43.259     210.31      2     0.60     AB-08
+1830.63       44.137     43.786     214.57      2     0.51     AB-08
+1840.93       44.598     44.228     216.83      3     2.50     AB-08
+1844.41       44.760     44.383     215.54      2     1.26     AB-08
+1847.46       44.899     44.516     219.62      2     0.94     AB-08
+1855.09       45.229     44.831     221.00      2     0.60     AB-08
+1859.57       45.526     45.120     217.56      2     0.82     AB-08
+1861.17       45.633     45.223     219.39      2     0.53     AB-08
+1862.59       45.725     45.313     218.62      2     2.56     AB-08
+1864.56       45.852     45.436     217.23      2     2.04     AB-08
+1867.90       46.075     45.654     211.58      2     0.64     AB-08
+1871.26       46.298     45.872     206.99      2     0.29     AB-08
+1873.26       46.431     46.002     209.25      2     1.24     AB-08
+1880.36       46.889     46.448     205.61      2     1.63     AB-08
+1884.88       47.187     46.740     204.28      2     1.02     AB-08
+1892.21       47.687     47.228     205.36      2     1.00     AB-08
+1894.8        47.865     47.402     205.51      2     1.63     AB-07
+1903.72       48.450     47.973     201.79      2     2.79     AB-07
+1909.75       48.874     48.388     211.47      4     1.09     AB-07
+1911.29       48.984     48.495     207.15      4     1.93     AB-07
+1914.31       49.191     48.697     212.35      2     0.57     AB-07
+1920.25       49.596     49.092     213.91      4     2.43     AB-07
+1929.4        50.230     49.712     216.76      2     0.28     AB-07
+1938.5        50.857     50.325     215.07      2     0.30     AB-07
+1943.09       51.175     50.636     218.12      5     2.35     AB-07
+1945.98       51.394     50.850     221.08      3     0.35     AB-07
+1953.17       51.894     51.339     216.69      4     2.96     AB-07
+1956.34       52.193     51.633     217.93      2     2.81     AB-07
+1959.23       52.505     51.941     218.83      2     1.55     AB-07
+1962.18       52.812     52.259     219.08      4     2.10     AB-07
+1963.62       52.963     52.423     215.70      2     1.94     AB-07
+1968.07       53.422     52.923     212.28      2     2.52     AB-07
+1972.66       53.926     53.470     213.25      2     0.74     AB-07
+1978.74       54.577     54.177     205.57      2     0.58     AB-07
+1981.61       54.859     54.486     212.48      4     2.46     AB-07
+1988.98       55.644     55.339     215.94      2     0.96     AB-07
+1995.01       56.317     56.068     215.25      2     0.38     AB-07
+2001.46       57.022     56.833     218.27      2     3.65     AB-07
+2003.23       57.222     57.049     223.09      2     0.30     AB-07
+2013.21       58.096     58.016     222.69      3     2.59     AB-07
+2017.71       58.467     58.421     224.99      2     0.97     AB-07
+2022.42       59.125     59.072     220.11      2     1.49     AB-07
+2026.9        59.806     59.746     224.21      3     1.18     AB-07
+2028.47       60.039     59.976     217.96      2     1.39     AB-07
+2031.5        60.526     60.459     218.85      2     3.26     AB-07
+2037.68       61.451     61.374     210.28      2     1.65     AB-07
+2042.43       62.186     62.102     212.26      2     0.85     AB-07
+2048.32       63.079     62.986     204.65      2     0.39     AB-07
+2051.4        63.526     63.429     206.76      2     2.20     AB-07
+2055.9        64.152     64.048     204.06      2     0.84     AB-07
+2066.85       65.565     65.444     208.22      2     2.01     AB-08
+2069.64       65.938     65.813     207.08      2     2.09     AB-08
+2072.65       66.333     66.204     217.67      2     2.07     AB-08
+2075.59       66.779     66.644     211.79      2     0.25     AB-08
+2075.745      66.818    66.6833     219.64      3     1.17     AB-08
+2076.02       66.890     66.755     222.40      2     0.47     AB-08
+2076.43       66.997     66.861     223.63      2     0.27     AB-08
+2077.02       67.151     67.014     220.43      2     3.79     AB-08
+2080.12       67.959     67.818     244.03      2     5.52     AB-08
+2080.61       68.086     67.944     240.28      2     0.28     AB-08
+2081.10       68.213     68.071     246.47      2     0.93     AB-08
+2081.59       68.340     68.197     247.22      2     2.42     AB-08
+2082.54       68.582     68.435     249.96      3     3.97     AB-08
+2082.64       68.608     68.460     248.32      2     2.08     AB-08
+2083.085      68.721    68.5708     238.70      4     4.19     AB-08
+2083.54       68.837     68.685     238.61      2     0.33     AB-08
+2083.82       68.908     68.755     238.78      2     1.42     AB-08
+2084.14       68.989     68.834     238.84      2     0.02     AB-08
+2084.52       69.086     68.929     231.99      3     4.59     AB-08
+2085.44       69.314     69.149     237.98      2     0.97     AB-08
+2087.02       69.706     69.527     237.26      3     0.40     AB-08
+2087.75       69.886     69.700     233.74      2     0.93     AB-08
+2089.24       70.246     70.048     234.85      2     0.19     AB-08
+2090.16       70.469     70.262     234.35      2     3.03     AB-08
+2093.50       71.337     71.101     237.17      2     0.49     AB-08
+2093.71       71.395     71.158     236.62      3     1.43     AB-08
+2095.46       71.875     71.622     240.58      2     3.79     AB-08
+2097.91       72.515     72.240     246.81      3     2.23     AB-08
+2099.29       72.885     72.598     244.19      1              AB-08
+2100.05       73.073     72.783     246.30      2     0.85     AB-08
+2100.69       73.230     72.937     236.93      2     0.88     AB-08
+2101.27       73.369     73.079     242.80      2     3.41     AB-08
+2101.80       73.492     73.209     241.26      2     0.14     AB-08
+2101.97       73.531     73.251     237.79      4     2.31     AB-08
+2103.15       73.805     73.542     240.63      3     0.85     AB-08
+2103.60       73.909     73.653     235.11      2     0.58     AB-08
+2104.68       74.184     73.944     231.11      2     0.89     AB-08
+2105.52       74.410     74.182     228.82      2     2.08     AB-08
+2106.32       74.656     74.440     223.79      2     1.22     AB-08
+2107.63       75.055     74.858     230.49      2     0.28     AB-08
+2109.17       75.518     75.343     228.85      2     0.25     AB-08
+2110.06       75.783     75.621     226.25      1              AB-08
+2111.20       76.120     75.975     229.45      2     2.14     AB-08
+2113.37       76.765     76.651     229.56      2     1.56     AB-08
+2116.08       77.586     77.513     232.82      3     1.97     AB-08
+2116.73       77.785     77.721     240.83      3     1.24     AB-08
+2120.16       78.809     78.795     235.51      2     0.11     AB-08
+2122.78       79.604     79.628     238.65      2     4.76     AB-08
+2125.62       80.449     80.515     240.08      3     1.03     AB-08
+2126.13       80.635     80.708     233.00      3     1.69     AB-08
+2130.20       82.116     82.248     250.22      2     4.72     AB-08
+2130.67       82.399     82.539     246.47      2     0.04     AB-08
+2130.78       82.466     82.607     244.08      2     2.06     AB-08
+2131.99       83.195     83.354     250.70      2     0.33     AB-08
+2132.50       83.503     83.669     248.75      2     2.37     AB-08
+2132.66       83.600     83.766     237.44      2     2.38     AB-08
+2134.46       84.687     84.855     240.19      2     1.00     AB-08
+2134.70       84.828     84.996     240.36      2     1.19     AB-08
+2135.22       85.133     85.301     233.84      2     0.20     AB-08
+2135.97       85.572     85.740     241.73      2     1.76     AB-08
+2136.25       85.734     85.902     220.23      2     5.01     AB-08
+2136.93       86.127     86.295     225.72      2     1.15     AB-08
+2137.57       86.498     86.666     228.99      3     1.73     AB-08
+2138.02       86.764     86.932     229.26      2     1.58     AB-08
+2138.32       86.942     87.110     218.37      2     0.94     AB-08
+2138.79       87.221     87.389     222.25      2     1.43     AB-08
+2143.57       90.075     90.266     236.19      5     2.31     AB-08
+2144.02       90.342     90.534     235.65      2     2.86     AB-08
+2144.72       90.759     90.953     242.07      3     4.54     AB-08
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/edc-co2.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/edc-co2.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/edc-co2.txt	(revision 14097)
@@ -0,0 +1,620 @@
+EPICA Dome C Ice Core High Resolution Holocene and Transition CO2 Data
+-----------------------------------------------------------------------
+               World Data Center for Paleoclimatology, Boulder
+                                  and
+                     NOAA Paleoclimatology Program
+-----------------------------------------------------------------------
+NOTE: PLEASE CITE CONTRIBUTORS WHEN USING THIS DATA!!!!!
+
+
+NAME OF DATA SET: 
+EPICA Dome C Ice Core High Resolution Holocene and Transition CO2 Data
+LAST UPDATE: 9/2004 (Original receipt by WDC Paleo)
+CONTRIBUTOR:  Eric Monnin, University of Bern
+IGBP PAGES/WDCA CONTRIBUTION SERIES NUMBER: 2004-055
+
+
+SUGGESTED DATA CITATION: Monnin, E., et al.. 2004. 
+EPICA Dome C Ice Core High Resolution Holocene and Transition CO2 Data. 
+IGBP PAGES/World Data Center for Paleoclimatology 
+Data Contribution Series # 2004-055.
+NOAA/NGDC Paleoclimatology Program, Boulder CO, USA.
+
+
+ORIGINAL REFERENCE:  
+Monnin, E., E.J. Steig, U. Siegenthaler, K. Kawamura, J. Schwander, B. Stauffer, 
+T.F. Stocker, D.L. Morse, J.-M. Barnola, B. Bellier, D. Raynaud, and H. Fischer. 2004.  
+Evidence for substantial accumulation rate variability in Antarctica during the Holocene, 
+through synchronization of CO2 in the Taylor Dome, Dome C and DML ice cores. 
+Earth and Planetary Science Letters, 224, 45-54, doi: 10.1016/j.epsl.2004.05.007. 
+
+
+ADDITIONAL REFERENCES FOR DATA:
+Flückiger, J.,  E. Monnin, B. Stauffer, J. Schwander, T. F. Stocker, J. Chappellaz, 
+D. Raynaud and J.-M. Barnola.  2002.
+High resolution Holocene N2O ice core record and its relationship with CH4 and CO2. 
+Global Biogeochemical Cycles, 16 (1), 1010, doi:10.1029/2001GB001417.
+
+Monnin, E., A. Indermühle, A. Dällenbach, J. Flückiger, B. Stauffer, T. F. Stocker, 
+D. Raynaud, and J.-M. Barnola.  2001. 
+Atmospheric CO2 concentrations over the last glacial termination. 
+Science 291, 112-114.
+
+ 
+ADDITIONAL REFERENCE FOR DATING:
+Schwander, J., J. Jouzel, C. U. Hammer, J.-R. Petit, R. Udisti, and E. Wolff. 2001.
+A tentative chronology for the EPICA Dome Concordia ice core. 
+Geophys. Res. Lett. Vol. 28, No. 22, p. 4243.
+
+
+ABSTRACT (Monnin et al. 2004):
+High resolution records of atmospheric CO2 concentration during the Holocene 
+are obtained from the Dome Concordia and Dronning Maud Land (Antarctica) ice cores. 
+These records confirm that the CO2 concentration varied between 260 and 280 ppmv in 
+the Holocene as measured in the Taylor Dome ice core. However, there are differences 
+in the CO2 records most likely caused by mismatches in timescales. Matching the 
+Taylor Dome timescale to the Dome C timescale by synchronization of CO2 indicates that 
+the accumulation rate at Taylor Dome increased through the Holocene by a factor of two 
+and bears little resemblance to the stable isotope record used as a proxy for temperature. 
+This result shows that different locations experienced substantially different 
+accumulation changes, and casts doubt on the often-used assumption that accumulation 
+rate scales with the saturation vapor pressure as a function of temperature, at least 
+for coastal locations. 
+
+
+GEOGRAPHIC REGION: Antarctica
+PERIOD OF RECORD:  22 KYrBP - present
+
+
+DESCRIPTION: High Resolution CO2 Data for the EPICA Dome C ice core, 
+and derived timescale for Taylor Dome Ice Core. 
+
+
+Core locations: 
+EPICA Dome C:  75° 06'S, 123° 21'E 
+Dronning Maud Land (DML): 75° 00'S, 00° 04'E 
+Taylor Dome:  77° 47'47" S,  158° 43'26" E
+
+
+
+
+Data:
+1. High-resolution EDC CO2 data
+
+Column 1: Depth (m)
+Column 2: Age (Years before 1950 AD, EDC1 Timescale)
+Column 3: CO2 mean (ppmv)
+Column 4: CO2 sigma mean (ppmv) sigma mean is one sigma of the mean value 
+          (of 6 neighboring samples)
+
+
+  Depth      Age    CO2      sigma
+  102.83     173   280.4     1.8
+ 106.885     311   274.9     0.7
+ 107.195     322   277.9     0.7
+ 110.245     427   279.1     1.3
+   110.5     435   281.9     1.1
+ 113.265     530   277.7     0.7
+  115.48     604   281.1     1.1
+ 118.615     709   282.2     0.5
+   121.5     806   280.1     0.6
+ 124.815     917   278.4     1.5
+ 127.015     991   276.6     1.4
+ 129.745    1083   279.1       1
+   132.5    1175   277.7     1.2
+ 134.715    1249   278.7     1.2
+ 138.015    1362   277.4     0.8
+ 141.295    1477   279.2     0.9
+  144.05    1574     280     0.8
+ 146.265    1653   278.9     0.8
+ 149.015    1751   278.7     0.7
+ 151.195    1830     278     1.2
+   154.5    1948   276.9     0.7
+ 157.815    2069   276.7     0.8
+  160.03    2150   276.7     0.8
+ 162.165    2228   277.6     1.3
+ 165.515    2352   277.9     0.5
+  168.28    2453   273.9     1.1
+     171    2550   278.9     0.6
+ 173.135    2625   275.3     1.6
+ 176.515    2743   274.7     1.2
+ 178.715    2820   276.3     0.9
+ 181.445    2918   274.6     0.8
+ 185.845    3078   276.3     1.5
+ 187.515    3138   273.1     1.1
+ 189.715    3219     274     0.3
+     193    3337     275     0.6
+ 196.295    3454   273.4     1.3
+ 198.515    3531     273     0.8
+  201.28    3628   271.5       1
+     204    3724   275.4     0.5
+ 206.195    3802   274.9     1.3
+ 209.515    3921   271.7       1
+ 212.265    4019   271.6     0.7
+     215    4117   272.8     0.8
+ 216.645    4176   271.5     0.9
+  221.05    4335   271.1     0.8
+ 222.715    4395   269.1     0.6
+  225.48    4496   269.8       1
+ 228.195    4596   271.5     0.8
+  232.05    4737   270.7     0.5
+ 233.715    4797   269.3       1
+ 236.465    4895   268.6     1.1
+ 240.265    5033   269.8     1.2
+   242.5    5114   267.6     0.6
+ 244.715    5196   265.3     1.7
+ 248.015    5318   265.2     0.8
+ 250.715    5419   267.6       2
+   253.5    5521   265.9     0.9
+ 256.265    5621   265.5     0.8
+ 259.015    5721   260.7     1.6
+ 260.645    5780   266.7     0.9
+   264.5    5921   265.5     0.8
+ 268.365    6064   263.2     0.6
+ 269.415    6102   262.7     0.9
+ 272.195    6205   261.2     0.7
+ 276.065    6349   261.1     0.4
+ 278.265    6430   259.4     0.6
+  280.53    6514   262.1     0.9
+ 283.715    6631   262.9     0.5
+ 285.965    6713   258.1     1.4
+ 288.165    6792   257.6     0.9
+     292    6930   262.3     0.9
+ 294.745    7031     263     0.7
+ 297.515    7132   260.7     0.6
+ 299.715    7211   258.4     0.8
+     303    7328   260.1     0.6
+ 305.745    7424   260.4     0.4
+ 308.515    7521   259.7     0.9
+  311.26    7617   259.2     0.7
+ 313.995    7714   260.8     1.4
+ 316.745    7813   259.6     0.5
+ 319.515    7915   259.3     0.9
+ 322.265    8017   258.3     1.2
+     325    8118   261.3     0.9
+ 326.545    8174   260.7     0.4
+   330.5    8315   261.8       1
+ 333.265    8412     259     1.1
+ 336.015    8508   260.9     0.7
+ 338.645    8599   260.4     0.6
+   341.5    8697   259.3       1
+ 343.715    8772     262     0.8
+ 347.015    8883   263.7     1.2
+ 349.745    8974   263.8     0.8
+  352.58    9067   265.2     0.9
+ 355.815    9171   260.6     1.7
+ 357.465    9224   260.9     0.6
+ 360.195    9310     263     0.4
+  362.98    9399   263.8     1.2
+ 369.545    9604   264.4     0.4
+  371.23    9657   264.2     0.9
+ 375.045    9776     264     0.3
+ 377.265    9846   263.4     0.1
+ 379.995    9931   265.7     0.5
+ 382.215   10001   264.9     0.4
+ 385.125   10093   267.5     0.4
+ 388.225   10192   266.9     0.6
+ 390.445   10263     266     1.1
+  393.78   10370   265.1     1.6
+ 396.495   10458   267.6     0.7
+  399.28   10550   264.8     0.6
+ 401.995   10640   264.8     0.4
+ 404.185   10712     265     0.8
+  404.78   10732   265.3     0.4
+ 406.385   10785   264.4     1.5
+ 407.495   10822   264.1     0.7
+   409.7   10896   264.2     1.1
+  411.38   10952   264.5     0.4
+  413.03   11008     264     0.5
+  414.75   11066     263     1.3
+  415.73   11099   265.2     0.8
+ 417.065   11144   258.8     0.7
+  418.53   11195   260.8     0.5
+ 420.485   11263   255.4     0.3
+ 421.795   11310   253.9     0.6
+   422.9   11349   253.8     0.8
+   426.1   11468   250.7     1.1
+  427.33   11515   249.7     0.4
+   428.3   11554   251.1     0.3
+ 429.495   11602   250.7     0.9
+  431.73   11695   245.3     1.1
+ 433.785   11784   245.3     0.6
+ 434.995   11838   246.6     0.5
+  437.23   11941   243.2     0.4
+  438.85   12017   240.3     0.3
+ 443.795   12258   237.5     0.5
+  446.03   12372   237.6     0.6
+ 448.745   12511   234.2     0.3
+  450.98   12625   238.3     1.1
+ 454.245   12789   237.3     0.5
+  457.03   12927   237.9     0.2
+ 459.895   13068   237.6     0.6
+  463.63   13252   236.4     0.9
+ 465.245   13332   239.2     0.5
+  467.45   13440   238.6     0.6
+ 470.195   13574   238.6     0.3
+ 473.055   13711   239.1     0.4
+ 479.705   14022   228.5     0.6
+   484.1   14230   228.4     0.7
+ 487.245   14387   226.1     0.6
+  490.03   14532   225.2     0.5
+ 492.195   14647   224.5     0.6
+  496.07   14855     222     0.8
+ 499.345   15037     221     0.8
+  501.58   15166   220.9     0.5
+ 504.195   15323   219.4     0.6
+  506.53   15466     214     0.8
+ 509.245   15637   207.5     0.9
+  512.03   15818   207.7     0.5
+ 514.745   16002   202.9     0.7
+  517.53   16199   200.8       1
+ 520.245   16400   195.2     0.3
+  523.03   16616   193.9     0.5
+ 526.295   16883     191     0.5
+  528.53   17073   188.5     0.7
+ 531.245   17311   188.5     0.7
+  532.93   17463   189.2     0.4
+ 536.745   17815     187     0.2
+  539.53   18074   188.6     0.5
+   542.9   18391   189.4     0.4
+ 543.345   18433   192.3     0.6
+  543.93   18487   188.3     0.6
+ 548.845   18948   188.7     0.2
+  550.51   19104   188.8     0.5
+ 553.245   19360     190     0.8
+  556.03   19621     188     0.9
+  557.89   19795   188.2     0.7
+ 558.195   19824     195     0.7
+  561.53   20137   187.8     0.4
+  564.26   20390   186.9     0.3
+  567.03   20646   186.5     0.3
+ 569.745   20897   184.7     1.2
+  572.53   21156   186.1     0.4
+ 576.325   21511   185.7     1.3
+ 578.105   21676   184.4     0.8
+
+
+2.  CO2 synchronization timescale for Taylor Dome Ice Core
+
+A. Gas age:
+
+ depth(m)    gas age (yr BP 1950)
+      86       94.5
+      90      149.2
+      94      205.2
+      98      260.9
+     102      316.2
+     106        372
+     110      427.9
+     114      483.7
+     118      540.1
+     122      598.1
+     126      658.4
+     130      722.7
+     134      790.3
+     138      860.5
+   142.1      929.8
+   146.1      995.5
+   150.1     1058.1
+   154.1     1119.4
+   158.1     1180.7
+   162.1     1243.2
+   166.1       1308
+   170.1     1377.6
+   174.1     1454.7
+   178.1     1539.6
+   182.1       1633
+   186.1     1731.9
+   190.1     1835.6
+   194.1       1940
+   198.1     2045.1
+   202.1       2150
+   206.1     2254.5
+   210.1     2361.9
+   214.1     2475.5
+   218.1     2594.6
+   222.1     2715.6
+   226.1     2835.7
+   230.1     2954.2
+   234.1     3070.8
+   238.1     3188.2
+   242.1       3308
+   246.1     3429.6
+   250.1     3550.6
+   254.2     3670.1
+   258.2     3787.9
+   262.2     3905.9
+   266.2     4026.1
+   270.2     4153.3
+   274.2     4295.3
+   278.2     4454.1
+   282.2     4629.4
+   286.2       4814
+   290.2     4998.6
+   294.2     5174.8
+   298.2     5342.8
+   302.2     5507.9
+   306.2     5674.9
+   310.2     5846.8
+   314.2     6031.1
+   318.2     6242.5
+   322.2       6502
+   326.2     6830.5
+   330.2     7238.7
+   334.2     7710.2
+   338.2     8215.9
+   342.2     8735.9
+   346.2     9226.8
+   350.2     9762.8
+   354.2    10289.2
+   358.2    10720.5
+   362.3    11224.1
+
+
+
+B. Ice age:
+
+ depth(m)    ice age (yr BP 1950)
+      86     730.1
+    87.3     746.9
+    88.5     763.6
+    89.7     780.4
+    90.9     797.2
+      92     813.9
+    93.2     830.5
+    94.4       847
+    95.5     863.4
+    96.7     879.7
+    97.8     895.9
+    98.9     912.1
+     100     928.3
+   101.2     944.6
+   102.3     961.1
+   103.4     977.6
+   104.6     994.2
+   105.7    1010.5
+   106.8    1026.6
+   107.9    1042.7
+     109      1059
+   110.1    1075.2
+   111.1    1091.5
+   112.2    1107.9
+   113.3    1124.3
+   114.4    1140.8
+   115.5    1157.4
+   116.5      1174
+   117.6    1190.8
+   118.6    1207.9
+   119.7      1225
+   120.8    1242.2
+   121.8    1259.8
+   122.9    1277.8
+   123.9    1295.9
+     125    1314.1
+     126    1332.7
+   127.1    1351.4
+   128.1      1370
+   129.2    1388.5
+   130.2    1407.3
+   131.2    1426.3
+   132.3      1445
+   133.3    1463.6
+   134.4    1482.2
+   135.4    1500.9
+   136.5    1519.5
+   137.5    1537.9
+   138.5      1556
+   139.6    1573.9
+   140.6    1591.7
+   141.6    1609.4
+   142.7    1626.8
+   143.7    1644.1
+   144.7    1661.2
+   145.7    1678.1
+   146.8    1694.6
+   147.8      1711
+   148.8    1727.5
+   149.8    1743.9
+   150.9    1760.3
+   151.9    1776.6
+   152.9    1793.1
+   153.9    1809.6
+   154.9    1826.2
+     156    1842.9
+     157    1859.6
+     158    1876.5
+     159    1893.5
+     160    1910.6
+     161    1927.7
+   162.1    1945.1
+   163.1    1962.8
+   164.1    1980.5
+   165.1    1998.3
+   166.1      2017
+   167.1    2036.8
+   168.1    2056.8
+   169.1    2077.2
+   170.2    2098.8
+   171.2    2121.7
+   172.2      2145
+   173.2    2168.6
+   174.2    2193.2
+   175.2      2219
+   176.2    2244.7
+   177.2    2270.3
+   178.2    2296.7
+   179.3    2323.9
+   180.3      2351
+   181.3    2378.2
+   182.3      2406
+   183.3    2434.1
+   184.3    2462.3
+   185.3    2490.5
+   186.3    2519.3
+   187.3    2548.5
+   188.3    2577.7
+   189.3    2606.7
+   190.4    2635.8
+   191.4      2665
+   192.4    2694.1
+   193.4    2723.2
+   194.4    2752.3
+   195.4    2781.6
+   196.4    2810.8
+   197.4    2839.9
+   198.4    2868.9
+   199.4    2897.8
+   200.4    2926.4
+   201.4    2954.9
+   202.4      2983
+   203.5    3010.9
+   204.5    3038.5
+   205.5      3066
+   206.5    3093.6
+   207.5    3121.2
+   208.5    3148.4
+   209.5    3175.7
+   210.5    3203.4
+   211.5    3231.3
+   212.5      3259
+   213.5    3286.9
+   214.5    3315.4
+   215.5    3344.4
+   216.5    3373.3
+   217.5    3402.5
+   218.6    3431.9
+   219.6    3461.4
+   220.6    3490.9
+   221.6    3520.3
+   222.6    3549.6
+   223.6      3579
+   224.6    3608.4
+   225.6    3637.6
+   226.6    3666.2
+   227.6    3694.6
+   228.6      3723
+   229.6      3751
+   230.6    3778.4
+   231.6    3805.5
+   232.6    3832.5
+   233.6    3859.3
+   234.6      3886
+   235.7    3912.7
+   236.7    3939.3
+   237.7      3966
+   238.7    3992.9
+   239.7    4020.1
+   240.7    4047.4
+   241.7    4074.9
+   242.7    4102.9
+   243.7    4130.9
+   244.7    4158.9
+   245.7    4186.9
+   246.7    4215.2
+   247.7    4243.7
+   248.7    4272.2
+   249.7    4300.6
+   250.8    4328.8
+   251.8    4357.3
+   252.8    4385.9
+   253.8    4414.9
+   254.8    4444.3
+   255.8    4474.3
+   256.8    4504.4
+   257.8    4534.8
+   258.8    4565.6
+   259.8    4596.7
+   260.8      4628
+   261.8    4659.4
+   262.8    4691.3
+   263.8    4723.4
+   264.8    4755.4
+   265.8    4788.2
+   266.8    4821.8
+   267.9    4855.7
+   268.9    4889.6
+   269.9    4924.9
+   270.9    4961.8
+   271.9    4999.1
+   272.9    5036.2
+   273.9    5074.7
+   274.9      5115
+   275.9    5155.8
+   276.9    5196.5
+   277.9    5238.6
+   278.9    5282.7
+   279.9    5327.3
+   280.9    5371.8
+   281.9    5417.1
+   282.9    5463.7
+   283.9    5510.6
+   284.9    5557.4
+   285.9    5604.1
+   286.9    5650.6
+     288    5697.3
+     289    5743.8
+     290    5789.3
+     291    5833.8
+     292    5878.1
+     293    5922.3
+     294    5965.5
+     295    6007.8
+     296    6050.3
+     297      6093
+     298    6135.2
+     299    6177.2
+     300    6219.5
+     301    6262.3
+     302    6305.5
+     303    6349.4
+     304    6393.8
+     305    6438.7
+     306    6484.6
+     307    6531.7
+     308    6579.1
+     309    6626.8
+     310    6676.5
+     311    6728.2
+     312    6780.3
+   313.1    6832.7
+   314.1    6888.4
+   315.1    6947.6
+   316.1    7007.4
+   317.1    7067.1
+   318.1    7132.1
+   319.1    7203.1
+   320.1    7274.9
+   321.1    7346.6
+   322.1      7426
+   323.1    7514.1
+   324.1    7603.5
+   325.1    7693.4
+   326.1    7792.7
+   327.1    7902.5
+   328.1    8013.9
+   329.1    8125.8
+   330.1    8245.7
+   331.1    8373.8
+   332.1    8502.4
+   333.1    8630.8
+   334.1    8761.6
+   335.1    8894.5
+   336.1    9026.4
+   337.1    9157.7
+   338.1    9290.6
+   339.1    9425.8
+   340.1    9561.1
+   341.2    9695.7
+   342.2    9826.2
+   343.2    9951.2
+   344.2   10075.6
+   345.2   10201.2
+   346.2   10331.7
+   347.2   10467.7
+   348.2   10603.6
+   349.2   10739.5
+   350.2   10873.8
+   351.2   11006.9
+   352.2   11139.9
+   353.2     11273
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/keys.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/keys.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/keys.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/keys.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/miscellaneous.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/miscellaneous.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/miscellaneous.tex	(revision 14097)
@@ -0,0 +1,70 @@
+\documentclass[../main/TOP_manual]{subfiles}
+
+\begin{document}
+
+\chapter{Miscellaneous}
+
+\section{TOP synthetic Workflow}
+
+\subsection{Model initialization}
+
+\subsection{Time marching procedure}
+
+\section{Coupling an external BGC model using NEMO framework}
+
+The coupling with an external BGC model through the NEMO compilation framework can be achieved in different ways according to the degree of coding complexity of the Biogeochemical model, like e.g., the whole code is made only by one file or it has multiple modules and interfaces spread across several subfolders.\\ \\
+Beside the 6 core files of MY\_TRC module, see (see \label{Mytrc}, let's assume an external BGC model named \textit{"MYBGC"} and constituted by a rather essential coding structure, likely few Fortran files. The new coupled configuration name is NEMO\_MYBGC. \\ \\
+The best solution is to have all files (the modified MY\_TRC routines and the BGC model ones) placed in a unique folder with root \path{<MYBGCPATH>} and to use the \textit{makenemo} external readdressing of MY\_SRC folder. \\ \\
+The coupled configuration listed in \textbf{cfg.txt}  will look like
+
+\begin{minted}{bash}
+   NEMO_MYBGC OPA_SRC TOP_SRC
+\end{minted}
+and the related cpp\_MYBGC.fcm content will be
+%
+\begin{minted}{bash}
+    bld::tool::fppkeys   key_iomput key_mpp_mpi key_top
+\end{minted}
+
+the compilation with \textit{makenemo} will be executed through the following syntax
+
+\begin{minted}{bash}
+   makenemo -n NEMO_MYBGC -m <arch_my_machine> -j 8 -e <MYBGCPATH>
+\end{minted}
+%The makenemo feature ?-e? was introduced to readdress at compilation time the standard MY_SRC folder (usually found in NEMO configurations) with a user defined external one.
+%
+%
+%The compilation of more articulated BGC model code & infrastructure, like in the case of BFM (?BFM-NEMO coupling manual), requires some additional features.
+%
+%As before, let?s assume a coupled configuration name NEMO_MYBGC, but in this case MYBGC model root becomes <MYBGCPATH> that contains 4 different subfolders for biogeochemistry, named initialization, pelagic, and benthic, and a separate one named nemo_coupling including the modified MY_SRC routines. The latter folder containing the modified NEMO coupling interface will be still linked using the makenemo ?-e? option.
+%
+%In order to include the BGC model subfolders in the compilation of NEMO code, it will be necessary to extend the configuration cpp_NEMO_MYBGC.fcm file to include the specific paths of MYBGC folders, as in the following example
+%
+\begin{minted}{bash}
+   bld::tool::fppkeys   key_iomput key_mpp_mpi key_top
+
+   src::MYBGC::initialization         <MYBGCPATH>/initialization
+   src::MYBGC::pelagic                <MYBGCPATH>/pelagic
+   src::MYBGC::benthic                <MYBGCPATH>/benthic
+
+   bld::pp::MYBGC      1
+   bld::tool::fppflags::MYBGC   %FPPFLAGS
+   bld::tool::fppkeys   %bld::tool::fppkeys MYBGC_MACROS
+\end{minted}
+
+%where MYBGC_MACROS is the space delimited list of macros used in MYBGC model for selecting/excluding specific parts of the code. The BGC model code will be preprocessed in the configuration BLD folder as for NEMO, but with an independent path, like NEMO_MYBGC/BLD/MYBGC/<subforlders>.
+%
+%The compilation will be performed similarly to in the previous case with the following
+%
+%makenemo -n NEMO_MYBGC -m <arch_my_machine> -j 8 -e <MYBGCPATH>/nemo_coupling
+%Note that, the additional lines specific for the BGC model source and build paths, can be written into a separate file, e.g. named MYBGC.fcm, and then simply included in the cpp_NEMO_MYBGC.fcm as follow
+%
+%bld::tool::fppkeys  key_zdftke key_dynspg_ts key_iomput key_mpp_mpi key_top
+%inc <MYBGCPATH>/MYBGC.fcm
+%This will enable a more portable compilation structure for all MYBGC related configurations.
+%
+%Important: the coupling interface contained in nemo_coupling cannot be added using the FCM syntax, as the same files already exists in NEMO and they are overridden only with the readdressing of MY_SRC contents to avoid compilation conflicts due to duplicate routines.
+%
+%All modifications illustrated above, can be easily implemented using shell or python scripting to edit the NEMO configuration cpp.fcm file and to create the BGC model specific FCM compilation file with code paths.
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_description.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_description.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_description.tex	(revision 14097)
@@ -0,0 +1,616 @@
+\documentclass[../main/TOP_manual]{subfiles}
+
+\newcommand{\cd}{\mathrm{CO_2}}
+\newcommand{\Ct}{\mathrm{C_T}}
+\newcommand{\pacd}{\mathrm{p^a_{CO_2}}}
+\newcommand{\cq}{\mathrm{^{14}C}}
+\newcommand{\Dcq}{\Delta ^{14}\mathrm{C}}
+\newcommand{\Rq}{\mathrm{^{14}{R}}}
+\newcommand{\CODE}[1]{\textsc{#1}}
+%\newcommand{\CODE}[1]{\textcolor{black}{\textsc{#1}}\xspace}
+
+\begin{document}
+
+\chapter{Model Description}
+\label{chap:ModDes}
+\chaptertoc
+
+\section{Basics}
+\label{sec:Bas}
+
+The time evolution of any passive tracer $C$ follows the transport equation, which is similar to that of active tracer - temperature or salinity :
+
+\begin{equation}
+\frac{\partial C}{\partial t} = {S(C)} -  \frac{1}{b_t} \left[   \frac{\partial e_{2u}\,e_{3u} \;  u\, C}{\partial i} +   \frac{\partial e_{1v}\,e_{3v} \;  uv, C}{\partial i}  \right] + \frac{1}{e_{3t}} \frac{\partial w\, C}{\partial k} + D^{lC} + D^{vC}
+\label{Eq_tracer}
+\end{equation}
+
+where expressions of $D^{lC}$ and $D^{vC}$ depend on the choice for the lateral and vertical subgrid scale parameterizations, see equations 5.10 and 5.11 in \citep{nemo_manual}
+
+{S(C)} , the first term on the right hand side of \ref{Eq_tracer}; is the SMS - Source Minus Sink - inherent to the tracer.  In the case of biological tracer such as phytoplankton, {S(C)} is the balance between phytoplankton growth and its decay through mortality and grazing. In the case of a tracer comprising carbon,  {S(C)} accounts for gas exchange, river discharge, flux to the sediments, gravitational sinking and other biological processes. In the case of a radioactive tracer, {S(C)} is simply loss due to radioactive decay.
+
+The second term (within brackets) represents the advection of the tracer in the three directions. It can be interpreted as the budget between the incoming and outgoing tracer fluxes in a volume $T$-cells $b_t= e_{1t}\,e_{2t}\,e_{3t}$
+
+The third term  represents the change due to lateral diffusion.
+
+The fourth term is change due to vertical diffusion, parameterized as eddy diffusion to represent vertical turbulent fluxes :
+
+\begin{equation}
+D^{vC} =  \frac{1}{e_{3t}} \frac{\partial}{\partial k} \left[  A^{vT} \frac{\partial C}{\partial k} \right]
+\label{Eq_trczdf}
+\end{equation}
+
+where $A^{vT}$ is the vertical eddy diffusivity coefficient of active tracers
+
+\section{The NEMO-TOP interface}
+\label{sec:TopInt}
+
+TOP is the NEMO hardwired interface toward biogeochemical models and provide the physical constraints/boundaries for oceanic tracers. It consists of a modular framework to handle multiple ocean tracers, including also a variety of built-in modules.
+
+This component of the NEMO framework allows one to exploit available modules  and further develop a range of applications, spanning from the implementation of a dye passive tracer to evaluate dispersion processes (by means of MY\_TRC), track water masses age (AGE module), assess the ocean interior penetration of persistent chemical compounds (e.g., gases like CFC or even PCBs), up to the full set of equations involving marine biogeochemical cycles.
+
+TOP interface has the following location in the code repository : \path{<repository>/src/TOP/}
+
+and the following modules are available:
+
+% -----------  tableau  ------------------------------------
+\begin{itemize}
+        \item \textbf{TRP}    	    :    Interface to NEMO physical core for computing tracers transport
+        \item \textbf{CFC}	    :    Inert carbon tracers (CFC11,CFC12, SF6)
+        \item \textbf{C14}	    :    Radiocarbon passive tracer
+        \item \textbf{AGE}	    :    Water age tracking
+        \item \textbf{MY\_TRC}  :	Template for creation of new modules and external BGC models coupling
+        \item \textbf{PISCES}    :	 Built in BGC model. See \citep{aumont_2015} for a throughout description.
+\end{itemize}
+%  ----------------------------------------------------------
+
+\section{The transport component : TRP}
+
+The passive tracer transport component  shares the same advection/diffusion routines with the dynamics, with specific treatment of some features like the surface boundary conditions, or the positivity of passive tracers concentrations.
+
+ \subsection{ Advection}
+%------------------------------------------namtrc_adv----------------------------------------------------
+\nlst{namtrc_adv}
+%-------------------------------------------------------------------------------------------------------------
+The advection schemes used for the passive tracers are the same than the ones for $T$ and $S$ and described in section 5.1 of \citep{nemo_manual}. The choice of an advection scheme  can be selected independently and  can differ from the ones used for active tracers. This choice is made in the \textit{namtrc\_adv} namelist, by  setting to \textit{true} one and only one of the logicals \textit{ln\_trcadv\_xxx}, the same way of what is done for dynamics.
+cen2, MUSCL2, and UBS are not \textit{positive} schemes meaning that negative values can appear in an initially strictly positive tracer field which is advected, implying that false extrema are permitted. Their use is not recommended on passive tracers
+
+ \subsection{ Lateral diffusion}
+%------------------------------------------namtrc_ldf----------------------------------------------------
+\nlst{namtrc_ldf}
+%-------------------------------------------------------------------------------------------------------------
+In NEMO v4.0, the passive tracer diffusion has necessarily the same form as the active tracer diffusion, meaning that the numerical scheme must be the same. However the passive tracer mixing coefficient can be chosen as a multiple of the active ones by changing the value of \textit{rn\_ldf\_multi} in namelist \textit{namtrc\_ldf}. The choice of numerical scheme is then set  in the \nam{namtra_ldf}{namtra\_ldf} namelist for the dynamic described in section 5.2 of \citep{nemo_manual}.
+
+
+%-----------------We also offers the possibility to increase zonal equatorial diffusion for passive tracers by introducing an enhanced zonal diffusivity coefficent in the equatorial domain which can be defined by the equation below :
+%-----------------\begin{equation} \label{eq:traqsr_iradiance}
+%-----------------Aht  = Aht *  rn_fact_lap * \exp( - \max( 0., z -1000  ) / 1000}  \quad \text{for $L=1$ to $N$}
+%-----------------\end{equation}
+
+ \subsection{ Tracer damping}
+
+%------------------------------------------namtrc_dmp----------------------------------------------------
+\nlst{namtrc_dmp}
+%-------------------------------------------------------------------------------------------------------------
+
+The use of newtonian damping  to climatological fields or observations is also coded, sharing the same routine dans active tracers. Boolean variables are defined in the namelist\_top\_ref to select the tracers on which restoring is applied
+Options are defined through the \nam{namtrc_dmp}{namtrc\_dmp} namelist variables. The restoring term is added when the namelist parameter \np{ln\_trcdmp} is set to true. The restoring coefficient is a three-dimensional array read in a file, which name is specified by the namelist variable \np{cn\_resto\_tr}. This netcdf file can be generated using the DMP\_TOOLS tool.
+
+ \subsection{ Tracer positivity}
+
+%------------------------------------------namtrc_rad----------------------------------------------------
+\nlst{namtrc_rad}
+%-------------------------------------------------------------------------------------------------------------
+
+Sometimes, numerical scheme can generates negative values of passive tracers concentration that must be positive. For exemple,  isopycnal diffusion can created extrema. The trcrad routine artificially corrects negative concentrations with a very crude solution that either sets negative concentration to zero without adjusting the tracer budget, or by removing negative concentration and keeping mass conservation.
+The treatment of negative concentrations is an option and can be selected in the namelist \nam{namtrc_rad}{namtrc\_rad} by setting the parameter \np{ln\_trcrad}  to true.
+
+\section{The SMS modules}
+
+\label{SMS_models}
+%------------------------------------------namtrc_sms----------------------------------------------------
+%\nlst{namtrc}
+%-------------------------------------------------------------------------------------------------------------
+
+\subsection{Ideal Age}
+%------------------------------------------namage----------------------------------------------------
+%
+\nlst{namage}
+%----------------------------------------------------------------------------------------------------------
+
+
+ An `ideal age' tracer is integrated online in TOP when \textit{ln\_age} = \texttt{.true.} in namelist \textit{namtrc}. This tracer marks the length of time in units of years that fluid has spent in the interior of the ocean, insulated from exposure to the atmosphere. Thus, away from the surface for $z<-H_{\mathrm{Age}}$ where $H_{\mathrm{Age}}$ is specified by the \textit{namage} namelist variable \textit{rn\_age\_depth}, whose default value is 10~m, there is a source $\mathrm{SMS_{\mathrm{Age}}}$ of the age tracer $A$:
+\begin{equation}
+  \label{eq:TOP-age-interior}
+  \mathrm{SMS_{\mathrm{Age}}} = 1 \mathrm{yr}\;^{-1} = 1/T_{\mathrm{year}},
+ \end{equation}
+ where the length of the current year $T_{\mathrm{year}} = 86400*N_{\mathrm{days\;in\;current\; year}}\;\mathrm{s}$, where $N_{\mathrm{days\;in\;current\; year}}$ may be 366 or 365 depending on whether the current year is a leap year or not.
+ Near the surface, for $z>-H_{\mathrm{Age}}$, ideal age is relaxed back to zero:
+\begin{equation}
+  \label{eq:TOP-age-surface}
+   \mathrm{SMS_{\mathrm{Age}}} = -\lambda_{\mathrm{Age}}A,
+ \end{equation}
+ where the relaxation rate $\lambda_{\mathrm{Age}}$  (units $\mathrm{s}\;^{-1}$) is specified by the \textit{namage} namelist variable \textit{rn\_age\_kill\_rate} and has a default value of 1/7200~s. Since this relaxation is applied explicitly, this relaxation rate in principle should not exceed $1/\Delta t$, where $\Delta t$ is the time step used to step forward passive tracers (2 * \textit{nn\_dttrc * rn\_rdt} when the default  leapfrog time-stepping scheme is employed).
+
+ Currently the 1-dimensional reference depth of the grid boxes is used rather than the dynamically evolving depth to determine whether the age tracer is incremented or relaxed to zero. This means that the tracer only works correctly in z-coordinates. To ensure that the forcing is independent of the level thicknesses, where the tracer cell at level $k$ has its upper face $z=-depw(k)$ above the depth $-H_{\mathrm{Age}}$, but its lower face $z=-depw(k+1)$ below that depth, then the age source
+ \begin{equation}
+  \label{eq:TOP-age-mixed}
+   \mathrm{SMS_{\mathrm{Age}}} = -f_{\mathrm{kill}}\lambda_{\mathrm{Age}}A +f_{\mathrm{add}}/T_{\mathrm{year}} ,
+ \end{equation}
+ where
+ \begin{align}
+    f_{\mathrm{kill}} &= e3t_k^{-1}(H_{\mathrm{Age}} - depw(k)) , \\
+    f_{\mathrm{add}} &= 1 - f_{\mathrm{kill}}.
+ \end{align}
+
+
+ This implementation was first used in the CORE-II intercomparison runs described e.g.\ in \citet{danabasoglu_2014}.
+
+\subsection{Inert carbons tracer}
+
+%------------------------------------------namage----------------------------------------------------
+%
+\nlst{namcfc}
+%----------------------------------------------------------------------------------------------------------
+
+Chlorofluorocarbons 11 and 12 (CFC-11 and CFC-12), and sulfur hexafluoride (SF6), are synthetic chemicals manufactured for industrial and domestic applications from the early 20th century onwards.
+CFC-11 (CCl$_{3}$F) is a volatile liquid at room temperature, and was widely used in refrigeration. CFC-12 (CCl$_{2}$F$_{2}$) is a gas at room temperature, and, like CFC-11, was widely used as a refrigerant,
+and additionally as an aerosol propellant. SF6 (SF$_{6}$) is also a gas at room temperature, with a range of applications based around its property as an excellent electrical insulator (often replacing more toxic alternatives).
+All three are relatively inert chemicals that are both non-toxic and non-flammable, and their wide use has led to their accumulation within the Earth's atmosphere. Large-scale production of CFC-11 and CFC-12 began in the 1930s, while production of SF6 began in the 1950s, and their atmospheric concentration time-histories are shown in Figure \ref{img_cfcatm}.
+As can be seen in the figure, while the concentration of SF6 continues to rise to the present  day, the concentrations of both CFC-11 and CFC-12 have levelled off and declined since around the 1990s.
+These declines have been driven by the Montreal Protocol (effective since August 1989), which has banned the production of CFC-11 and CFC-12 (as well as other CFCs) because of their role in the depletion of
+stratospheric ozone (O$_{3}$), critical in decreasing the flux of ultraviolet radiation to the Earth's surface. Separate to this role in ozone-depletion, all three chemicals are significantly more potent greenhouse gases
+than CO$_{2}$ (especially SF6), although their relatively low atmospheric concentrations limit their role in climate change. \\
+
+% Chlorofluorocarbons 11 and 12 (CFC-11 and CFC-12), and sulfur hexafluoride (SF6),
+% are greenhouse gases that have been released into the atmosphere by human activities.
+% In the case of CFC-11 and CFC-12, this release began in the 1930s, and atmospheric
+% concentrations increased until around the late 1990s afterwhich they began to decline in
+% response to the Montreal Protocol.
+% In the case of SF6, release began in the 1950s
+% This release began in the 1930s for CFC-11 and CFC-12, and the 1950s for SF6, and
+% regularly increasing their atmospheric concentration until the 1090s, 2000s for respectively CFC11, CFC12,
+% and is still increasing, and SF6 (see Figure \ref{img_cfcatm}).  \\
+
+The ocean is a notable sink for all three gases, and their relatively recent occurrence in the atmosphere, coupled to the ease of making high precision measurements of their dissolved concentrations, has made them
+valuable in oceanography. % for tracking interior ventilation and mixing.
+Because they only enter the ocean via surface air-sea exchange, and are almost completely chemically and biologically inert, their distribution within the ocean interior reveals its ventilation via transport and mixing.
+Measuring the dissolved concentrations of the gases -- as well as the mixing ratios between them -- shows circulation pathways within the ocean as well as water mass ages (i.e. the time since last contact with the
+atmosphere). This feature of the gases has made them valuable across a wide range of oceanographic problems. One use lies in ocean modelling, where they can be used to evaluate the realism of the circulation and
+ventilation of models, key for understanding the behaviour of wider modelled marine biogeochemistry (e.g. \citep{dutay_2002,palmieri_2015}). \\
+
+Modelling these gases (henceforth CFCs) in NEMO is done within the passive tracer transport module, TOP, using the conservation state equation \ref{Eq_tracer}
+
+Advection and diffusion of the CFCs in NEMO are calculated by the physical module, OPA,
+whereas sources and sinks are done by the CFC module within TOP.
+The only source for CFCs in the ocean is via air-sea gas exchange at its surface, and since CFCs are generally
+stable within the ocean, we assume that there are no sinks (i.e. no loss processes) within the ocean interior.
+Consequently, the sinks-minus-sources term for CFCs consists only of their air-sea fluxes, $F_{cfc}$, as
+described in the Ocean Model Inter-comparison Project (OMIP) protocol \citep{orr_2017}:
+
+% Because CFCs being stable in the ocean, we consider that there is no CFCs sink.
+% The only CFC source in the ocean is through the Air-Sea gas exchange at the surface.
+% These are calculated as air-sea fluxes (F$_{cfc}$), as described in the OMIP6 protocol \citep{artOMIP6}:
+
+\begin{eqnarray}
+F_{cfc} = K_{w} \, \cdot \, (C_{sat} - C_{surf}) \, \cdot  \, (1 - f_{i})
+\label{equ_CFC_flux}
+\end{eqnarray}
+
+Where $K_{w}$ is the piston velocity (in m~s$^{-1}$), as defined in Equation \ref{equ_Kw};
+$C_{sat}$ is the saturation concentration of the CFC tracer, as defined in Equation \ref{equ_C_sat};
+$C_{surf}$ is the local surface concentration of the CFC tracer within the model (in mol~m$^{-3}$);
+and $f_{i}$ is the fractional sea-ice cover of the local ocean (ranging between 0.0 for ice-free ocean,
+through to 1.0 for completely ice-covered ocean with no air-sea exchange).
+
+The saturation concentration of the CFC, $C_{sat}$, is calculated as follows:
+
+\begin{eqnarray}
+C_{sat} = Sol \, \cdot \, P_{cfc}
+\label{equ_C_sat}
+\end{eqnarray}
+
+Where $Sol$ is the gas solubility in mol~m$^{-3}$~pptv$^{-1}$, as defined in Equation \ref{equ_Sol_CFC};
+and $P_{cfc}$ is the atmosphere concentration of the CFC (in parts per trillion by volume, pptv).
+This latter concentration is provided to the model by the historical time-series of \citet{bullister_2017}.
+This includes bulk atmospheric concentrations of the CFCs for both hemispheres -- this is necessary because of
+the geographical asymmetry in the production and release of CFCs to the atmosphere.
+Within the model, hemispheric concentrations are uniform, with the exception of the region between
+10$^{\circ}$N and 10$^{\circ}$ in which they are linearly interpolated.
+
+The piston velocity $K_{w}$ is a function of 10~m wind speed (in m~s$^{-1}$) and sea surface temperature,
+$T$ (in $^{\circ}$C), and is calculated here following \citet{wanninkhof_1992}:
+
+\begin{eqnarray}
+K_{w} = X_{conv} \, \cdot \, a \, \cdot \, u^2 \, \cdot \, \sqrt{ \frac{Sc(T)}{660} }
+\label{equ_Kw}
+\end{eqnarray}
+
+Where $X_{conv}$ = $\frac{0.01}{3600}$, a conversion factor that changes the piston velocity
+from cm~h$^{-1}$ to m~s$^{-1}$;
+$a$ is a constant re-estimated by \citet{wanninkhof_2014} to 0.251 (in $\frac{cm~h^{-1}}{(m~s^{-1})^{2}}$);
+and $u$ is the 10~m wind speed in m~s$^{-1}$ from either an atmosphere model or reanalysis atmospheric forcing.
+$Sc$ is the Schmidt number, and is calculated as follow, using coefficients from \citet{wanninkhof_2014} (see Table \ref{tab_Sc}).
+
+\begin{eqnarray}
+Sc =  a0 + (a1 \, \cdot \, T) + (a2  \, \cdot \, T^2) + (a3 \, \cdot \, T^3) + (a4 \, \cdot \, T^4)
+\label{equ_Sc}
+\end{eqnarray}
+
+The solubility, $Sol$, used in Equation \ref{equ_C_sat} is calculated in mol~l$^{-1}$~atm$^{-1}$,
+and is specific for each gas.
+It has been experimentally estimated by \citet{warner_1985} as a function of temperature
+and salinity:
+
+% AXY: this equation looks both weird and possibly wrong; it doesn't look like the one in the
+% code version that I have to hand, although this might be out of date; in any case, I'dag
+% strongly suggest avoiding the use of the \frac{}{100}, and instead substitute a term that is
+% "degrees Kelvin divided by 100" (which is weird in itself); and make this term use Celcius
+% so that you're not using T twice in different ways
+
+\begin{eqnarray}
+\ln{(Sol)} = a_1 + \frac{a_2}{ T_{X}} + a_3 \, \cdot \, \ln{ T_{X} } + a_4 \, \cdot \, T_{X}^2 + S \, \cdot \, ( b_1 + b_2 \, \cdot \, T_{X} + b_3 \, \cdot \, T_{X}^2 )
+\label{equ_Sol_CFC}
+\end{eqnarray}
+
+% \begin{eqnarray}
+% \ln{(Sol)} = a1 + a2 \, \frac{100}{T} + a3 \, \ln{ (\frac{T}{100}) } + a4 \, \frac{T}{100}^2 + S \, ( b1 + b2 \, \frac{T}{100} + b3 \, \frac{T}{100}^2 )
+% \label{equ_Sol_CFC}
+% \end{eqnarray}
+
+Where $T_{X}$ is $\frac{T + 273.16}{100}$, a function of temperature;
+and the $a_{x}$ and $b_{x}$ coefficients are specific for each gas (see Table \ref{tab_ref_CFC}).
+This is then converted to mol~m$^{-3}$~pptv$^{-1}$ assuming a constant atmospheric surface pressure of 1~atm.
+The solubility of CFCs thus decreases with rising $T$ while being relatively insensitive to salinity changes.
+Consequently, this translates to a pattern of solubility where it is greatest in cold, polar regions (see Figure \ref{img_cfcsol}).
+
+% AXY: not 100% sure about the units below; they might be in nanomol, or in seconds or years
+
+The standard outputs of the CFC module are seawater CFC concentrations (in mol~m$^{-3}$), the net air-sea flux (in mol~m$^{-2}$~d$^{-1}$) and the cumulative net air-sea flux (in mol~m$^{-2}$).
+Using XIOS, it is possible to obtain outputs such as the vertical integral of CFC concentrations (in mol~m$^{-2}$; see Figure \ref{img_cfcinv}).
+This property, when divided by the surface CFC concentration, estimates the local penetration depth (in m) of the CFC.
+
+% AXY: not sure what's meant by some of the below; I've tried to reword it above
+% The standard outputs of the CFC module are the CFCs concentration in the sea water, and the records of the outputs-frequency-averaged as well as the total air-sea fluxes.
+% Using XIOS, it is also possible to ask for the CFCs vertical inventory in the output file (see Figure cfc inventory example ?).
+
+\subsubsection{Notes}
+
+In comparison to the OMIP protocol, the CFC module in NEMO has several differences:
+
+% AXY: consider an itemized list here if you've got a list of differences
+
+For instance, C$_{sat}$ is calculated for a fixed surface pressure of 1atm, what could be corrected in a further version of the module.
+
+
+\begin{table}[!t]
+\caption{Coefficients for fit of the CFCs solubility (Eq. \ref{equ_Sol_CFC}).}
+\vskip4mm
+\centering
+\begin{tabular}{l l l l l l l l l}
+\hline
+Gas   & & a1 & a2 & a3 & a4 & b1 & b2 & b3 \\
+\hline
+CFC-11 & & -218.0971 & 298.9702 & 113.8049 & -1.39165 & -0.143566  & 0.091015   & -0.0153924 \\
+CFC-12 & & -229.9261 & 319.6552 & 119.4471 & -1.39165 & -0.142382  & 0.091459   & -0.0157274 \\
+SF6    & & -80.0343  & 117.232  & 29.5817  & 0.0      & 0.0335183  & -0.0373942 & 0.00774862 \\
+\hline
+\end{tabular}
+\label{tab_ref_CFC}
+\end{table}
+
+
+\begin{table}[!t]
+\caption{Coefficients for fit of the CFCs Schmidt number (Eq. \ref{equ_Sc}). }
+\vskip4mm
+\centering
+\begin{tabular}{l l l l l l l }
+\hline
+Gas  & & a0 & a1 & a2 & a3 & a4 \\
+\hline
+CFC-11 & & 3579.2  & -222.63 & 7.5749 & -0.14595 & 0.0011874   \\
+CFC-12 & & 3828.1  & -249.86 & 8.7603 & -0.1716  & 0.001408    \\
+SF6    & & 3177.5  & -200.57 & 6.8865 & -0.13335 & 0.0010877   \\
+\hline
+\end{tabular}
+\label{tab_Sc}
+\end{table}
+
+%% -----------------------------------
+%% -----------------------------------
+%% Figures %%
+
+
+\begin{figure}[!h]
+\centering
+\includegraphics[width=0.80\textwidth]{CFC-atm-evol}
+  \caption{Atmospheric CFC11, CFC12 and SF6 partial pressure evolution in both hemispheres.}
+\label{img_cfcatm}
+\end{figure}
+
+\begin{figure}[!h]
+\centering
+\includegraphics[width=0.80\textwidth]{CFC_solub}
+  \caption{CFC11 solubility in mol m$^{-3}$ pptv$^{-1}$, calculated from the World Ocean Atlas 2013 temperature and salinity annual climatology.}
+\label{img_cfcsol}
+\end{figure}
+
+\begin{figure}[!h]
+\centering
+\includegraphics[width=0.80\textwidth]{CFC_inventory}
+  \caption{CFC11 vertical inventory in $\mu$mol m$^{-2}$, from one of the UK Earth System Model 1 model (UKESM1 - which uses NEMO as ocean component, with TOP for the passive tracers) historical run at year 2000.}
+\label{img_cfcinv}
+\end{figure}
+
+
+\subsection{Radiocarbon}
+
+%------------------------------------------namage----------------------------------------------------
+%
+\nlst{namc14_fcg}
+\nlst{namc14_typ}
+\nlst{namc14_sbc}
+%----------------------------------------------------------------------------------------------------------
+
+The C14 package implemented in NEMO by Anne Mouchet models ocean $\Dcq$. It offers several possibilities: $\Dcq$ as a physical tracer of the ocean ventilation (natural $\cq$), assessment of bomb radiocarbon uptake, as well as transient studies of paleo-historical ocean radiocarbon distributions.
+
+\subsubsection{Method}
+
+ Let  $\Rq$ represent the ratio of $\cq$ atoms to the total number of carbon atoms in the sample, i.e. $\cq/\mathrm{C}$. Then, radiocarbon anomalies are reported as
+\begin{equation}
+\Dcq = \left( \frac{\Rq}{\Rq_\mathrm{ref}} - 1 \right) 10^3, \label{eq:c14dcq}
+\end{equation}
+where $\Rq_{\textrm{ref}}$ is a reference ratio. For the purpose of ocean ventilation studies $\Rq_{\textrm{ref}}$ is set to one.
+
+Here we adopt the approach of \cite{fiadeiro_1982} and \cite{toggweiler_1989a,toggweiler_1989b} in which  the ratio $\Rq$ is transported rather than the individual concentrations C and $\cq$.
+This approach calls for a strong assumption, i.e., that of a homogeneous and constant dissolved inorganic carbon (DIC) field \citep{toggweiler_1989a,mouchet_2013}. While in terms of
+oceanic $\Dcq$, it yields similar results to approaches involving carbonate chemistry, it underestimates the bomb radiocarbon inventory because it assumes a constant air-sea $\cd$ disequilibrium (Mouchet, 2013). Yet, field reconstructions of the ocean bomb $\cq$ inventory are also biased low \citep{naegler_2009} since they assume that the anthropogenic perturbation did not affect ocean DIC since the pre-bomb epoch. For these reasons, bomb $\cq$ inventories obtained with the present method are directly comparable to reconstructions based on field measurements.
+
+This simplified approach also neglects the effects of fractionation (e.g.,  air-sea exchange) and of biological processes. Previous studies by \cite{bacastow_1990} and \cite{joos_1997} resulted in nearly identical $\Dcq$ distributions among experiments considering biology or not.
+Since observed $\Rq$ ratios are corrected for the isotopic fractionation when converted to the standard $\Dcq$ notation \citep{stuiver_1977} the model results are directly comparable to observations.
+
+Therefore the simplified approach is justified for the purpose of assessing the circulation and ventilation of OGCMs.
+
+The equation governing the transport of $\Rq$  in the ocean is
+\begin{equation}
+\frac{\partial}{\partial t} {\Rq} =  - \bigtriangledown \cdot ( \mathbf{u} \Rq - \mathbf{K} \cdot \bigtriangledown \Rq )  - \lambda \Rq, \label{eq:quick}
+\end{equation}
+where $\lambda$ is the radiocarbon decay rate, ${\mathbf{u}}$ the 3-D velocity field, and $\mathbf{K}$ the diffusivity tensor.
+
+At the air-sea interface a Robin boundary condition \citep{haine_2006} is applied to \eqref{eq:quick}, i.e., the flux
+through the interface is proportional to the difference in the ratios between
+the ocean and the atmosphere
+\begin{equation}
+\mathcal{\!F} =  \kappa_{R}  (\Rq  - \Rq_{a} ), \label{eq:BCR}
+\end{equation}
+where $\mathcal{\!F}$ is the flux out of the ocean, and $\Rq_{a}$ is the atmospheric $\cq/\mathrm{C}$ ratio. The transfer velocity $ \kappa_{R} $ for the radiocarbon ratio in \eqref{eq:BCR} is computed as
+\begin{equation}
+ \kappa_{R} =  \frac{\kappa_{\cd} K_0}{\overline{\Ct}} \, \pacd   \label{eq:Rspeed}
+\end{equation}
+with $\kappa_{\cd}$ the carbon dioxide transfer or piston velocity, $K_0$ the $\cd$ solubility in seawater, $\pacd$ the atmospheric $\cd$ pressure at sea level, and $\overline{\Ct}$ the average sea-surface dissolved inorganic carbon concentration.
+
+
+The $\cd$ transfer velocity is based on the empirical formulation of \cite{wanninkhof_1992} with chemical enhancement \citep{wanninkhof_1996,wanninkhof_2014}. The original formulation is modified to account for the reduction of the  air-sea exchange rate in the presence of sea ice. Hence
+\begin{equation}
+\kappa_\cd=\left( K_W\,\mathrm{w}^2 + b  \right)\, (1-f_\mathrm{ice})\,\sqrt{660/Sc}, \label{eq:wanc14}
+\end{equation}
+with $\mathrm{w}$ the wind magnitude, $f_\mathrm{ice}$ the fractional ice cover, and $Sc$ the Schmidt number.
+$K_W$ in \eqref{eq:wanc14} is an empirical coefficient with dimension of an inverse velocity.
+The chemical enhancement term $b$ is represented as a function of temperature $T$ \citep{wanninkhof_1992}
+\begin{equation}
+b=2.5 ( 0.5246 + 0.016256 T+ 0.00049946  * T^2 ). \label{eq:wanchem}
+\end{equation}
+
+%We compare the results of equilibrium and transient experiments obtained with both methods in section \ref{sec:UNDEU}.
+
+%
+\subsubsection{Model setup}
+\label{sec:setup}
+
+To activate the \texttt{C14} package, set the parameter \textit{ln\_c14} = \texttt{.true.} in namelist \textit{namtrc}.
+
+\paragraph{Parameters and formulations}
+\label{sec:param}
+ %
+The radiocarbon decay rate (\CODE{rlam14}; in \texttt{trcnam\_c14} module) is set to $\lambda=(1/8267)$ yr$^{-1}$ \citep{stuiver_1977}, which corresponds to a half-life of 5730 yr.\\[1pt]
+%
+The Schmidt number $Sc$, Eq. \eqref{eq:wanc14}, is calculated with the help of the formulation of \cite{wanninkhof_2014}. The $\cd$ solubility $K_0$ in \eqref{eq:Rspeed} is taken from \cite{weiss_1974}. $K_0$ and $Sc$ are computed with the OGCM temperature and salinity fields (\texttt{trcsms\_c14} module).\\[1pt]
+%
+The following parameters intervening in the air-sea exchange rate are set in \texttt{namelist\_c14}:
+\begin{itemize}
+\item The reference DIC concentration $\overline{\Ct}$ (\CODE{xdicsur}) intervening in \eqref{eq:Rspeed} is classically set to 2 mol m$^{-3}$ \citep{toggweiler_1989a,orr_2001,butzin_2005}.
+%
+\item The value of the empirical coefficient $K_W$ (\CODE{xkwind}) in \eqref{eq:wanc14} depends on the wind field and on the model upper ocean mixing rate \citep{toggweiler_1989a,wanninkhof_1992,naegler_2009,wanninkhof_2014}.
+It should be adjusted so that the globally averaged $\cd$ piston velocity is $\kappa_\cd = 16.5\pm 3.2$ cm/h \citep{naegler_2009}.
+%The sensitivity to this parametrization is discussed in section \ref{sec:result}.
+%
+\item Chemical enhancement (term $b$  in Eq. \ref{eq:wanchem}) may be set on/off by means of the logical variable \CODE{ln\_chemh}.
+\end{itemize}
+
+%
+\paragraph{Experiment type}
+The type of experiment is determined by the value given to \CODE{kc14typ} in \texttt{namelist\_c14}. There are three possibilities:
+\begin{enumerate}
+\item natural $\Dcq$: \CODE{kc14typ}=0
+\item bomb $\Dcq$: \CODE{kc14typ}=1
+\item transient paleo-historical $\Dcq$: \CODE{kc14typ}=2
+\end{enumerate}
+%
+\textbf{Natural or Equilibrium radiocarbon}
+\CODE{kc14typ}=0
+
+Unless otherwise specified in \texttt{namelist\_c14}, the atmospheric $\Rq_a$ (\CODE{rc14at}) is set to one, the atmospheric $\cd$ (\CODE{pco2at}) to 280 ppm, and the ocean $\Rq$ is initialized with \CODE{rc14init=0.85}, i.e., $\Dcq=$-150\textperthousand  \cite[typical for deep-ocean, Fig 6 in][]{key_2004}.
+
+Equilibrium experiment should last until 98\% of the ocean volume exhibit a drift of less than 0.001\textperthousand/year \citep{orr_2000}; this is usually achieved after few kyr (Fig. \ref{fig:drift}).
+%
+\begin{figure}[!h]
+\begin{center}
+\includegraphics[width=0.9\hsize]{drift-EXP06}
+\end{center}
+\vspace{-4ex}
+\caption{ Time evolution of $\Rq$ inventory anomaly for equilibrium run with homogeneous ocean initial state. The anomaly (or drift) is given in \%  change in total ocean inventory per 50 years. Time on x-axis is in simulation year.\label{fig:drift} }
+\end{figure}
+
+\textbf{Transient: Bomb}
+\label{sec:bomb}
+\CODE{kc14typ}=1
+
+\begin{figure}[!h]
+\begin{center}
+\includegraphics[width=0.9\hsize]{C14bombCO2-NB}
+\end{center}
+\vspace{-4ex}
+\caption{Atmospheric $\Dcq$ (solid; left axis) and $\cd$ (dashed; right axis)  forcing for the $\cq$-bomb experiments. The $\Dcq$ is illustrated for the three zonal bands (upper, middle, and lower curves correspond to latitudes $> 20$N, $\in [20\mathrm{S},20\mathrm{N}]$, and $< 20$S, respectively.} \label{fig:bomb}
+\end{figure}
+
+Performing this type of experiment requires that a pre-industrial equilibrium run be performed beforehand (\CODE{ln\_rsttr} should be set to \texttt{.TRUE.}).
+
+An exception to this rule is when wishing to perform a perturbation bomb experiment as was possible with the package \texttt{C14b}. It is still possible to easily set-up that type of transient experiment for which no previous run is needed.  In addition to the instructions as given in this section it is however necessary to adapt the \texttt{atmc14.dat} file so that it does no longer contain any negative $\Dcq$ values (Suess effect in the pre-bomb period).
+
+The model  is integrated from a given initial date following the observed records provided from 1765 AD on ( Fig. \ref{fig:bomb}).
+The file \texttt{atmc14.dat}  \cite[][\& I. Levin, personal comm.]{enting_1994} provides atmospheric $\Dcq$ for three latitudinal bands: 90S-20S,    20S-20N \&    20N-90N.
+Atmospheric $\cd$ in the file \texttt{splco2.dat} is obtained from a spline fit through ice core data and direct atmospheric measurements \cite[][\& J. Orr, personal comm.]{orr_2000}.
+Dates in these forcing files are expressed as yr AD.
+
+To ensure that the atmospheric forcing is applied properly as well as that output files contain consistent dates and inventories the experiment should be set up carefully:
+\begin{itemize}
+\item Specify the starting date of the experiment: \CODE{nn\_date0} in \texttt{namelist}.  \CODE{nn\_date0} is written as Year0101 where Year may take any positive value (AD).
+\item Then the parameters \CODE{nn\_rstctl} in  \texttt{namelist} (on-line) and \CODE{nn\_rsttr} in \texttt{namelist\_top} (off-line)  must be \textbf{set to 0} at the start of the experiment (force the date to \CODE{nn\_date0} for the \textbf{first} experiment year).
+\item These two parameters (\CODE{nn\_rstctl} and \CODE{nn\_rsttr}) have then to be \textbf{set to 2} for the following years (the date must be read in the restart file).
+\end{itemize}
+ If the experiment date is outside the data time span then the first or last atmospheric concentrations are prescribed depending on whether the date is earlier or later. Note that \CODE{tyrc14\_beg} (\texttt{namelist\_c14}) is not used in this context.
+
+%
+\textbf{Transient: Past}
+\CODE{kc14typ}=2
+%
+\begin{figure}[!h]
+\begin{center}
+\includegraphics[width=0.9\hsize]{PaleoCO2C14-NB}
+\end{center}
+\vspace{-4ex}
+\caption{Atmospheric $\Dcq$ (solid) and $\cd$ (dashed)  forcing for the Paleo experiments. The $\cd$ scale is given on the right axis.} \label{fig:paleo}
+\end{figure}
+
+This experiment type does not need a previous equilibrium run. It should start 5--6 kyr earlier than the period to be analyzed.
+Atmospheric $\Rq_a$ and $\cd$ are prescribed from forcing files. The ocean $\Rq$ is initialized with the value attributed to \CODE{rc14init} in \texttt{namelist\_c14}.
+
+The file \texttt{intcal13.14c} \citep{reimer_2013} contains atmospheric $\Dcq$ from 0 to 50 kyr cal BP\footnote{cal BP: number of years before 1950 AD}.
+The $\cd$ forcing is provided in file \texttt{ByrdEdcCO2.txt}. The content of this file is based on  the high resolution record from EPICA Dome C \citep{monnin_2004} for the Holocene and the Transition, and on Byrd Ice Core CO2 Data for 20--90 kyr BP  \citep{ahn_2008}. These atmospheric values are reproduced in Fig. \ref{fig:paleo}. Dates in these files are expressed as yr BP.
+
+To ensure that the atmospheric forcing is applied properly as well as that output files contain consistent dates and inventories the experiment should be set up carefully.
+The true experiment starting date is given by \CODE{tyrc14\_beg} (in yr BP) in \texttt{namelist\_c14}. In consequence, \CODE{nn\_date0} in \texttt{namelist} MUST be set to 00010101.\\
+Then the parameters \CODE{nn\_rstctl} in  \texttt{namelist} (on-line) and \CODE{nn\_rsttr} in \texttt{namelist\_top} (off-line)  must be set to 0 at the start of the experiment (force the date to \CODE{nn\_date0} for the first experiment year). These two parameters have then to be set to 2 for the following years (read the date in the restart file). \\
+ If the experiment date is outside the data time span then the first or last atmospheric concentrations are prescribed depending on whether the date is earlier or later.
+
+%
+\paragraph{Model output}
+\label{sec:output}
+All output fields in Table \ref{tab:out} are routinely computed. It depends on the actual settings in \texttt{iodef.xml} whether they are stored or not.
+%
+\begin{table}[!h]
+\begin{center}
+\caption{Standard output fields for the C14 package \label{tab:out}.
+}
+%\begin{small}
+\renewcommand{\arraystretch}{1.3}%
+\begin{tabular}[h]{|l*{3}{|c}|l|}
+\hline
+Field & Type & Dim & Units & Description \\ \hline
+RC14 & ptrc & 3-D & -        & Radiocarbon ratio \\
+DeltaC14 & diad & 3-D & \textperthousand & $\Dcq$\\
+C14Age & diad & 3-D & yr &   Radiocarbon age \\
+RAge & diad & 2-D & yr & Reservoir age\\
+qtr\_c14 &  diad & 2-D & m$^{-2}$ yr$^{-1}$ & Air-to-sea net $\Rq$ flux\\
+qint\_c14 & diad & 2-D &   m$^{-2}$ &  Cumulative air-to-sea $\Rq$ flux \\
+AtmCO2 & scalar & 0-D & ppm & Global atmospheric $\cd$ \\
+AtmC14 & scalar & 0-D & \textperthousand  & Global atmospheric $\Dcq$\\
+K\_CO2 & scalar & 0-D & cm h$^{-1}$  & Global $\cd$ piston velocity ($ \overline{\kappa_{\cd}}$) \\
+K\_C14 & scalar & 0-D &m yr$^{-1}$ & Global $\Rq$ transfer velocity  ($ \overline{\kappa_R}$)\\
+C14Inv & scalar & 0-D & $10^{26}$ atoms & Ocean radiocarbon inventory \\ \hline
+\end{tabular}
+%\end{small}
+\end{center}
+\end{table}
+%!   Standard ratio: 1.176E-12 ; Avogadro's nbr = 6.022E+23 at/mol ; bomb C14 traditionally reported as 1.E+26 atoms
+%   REAL(wp), PARAMETER            :: atomc14=1.176*6.022E-15   ! conversion factor
+% atomc14 * xdicsur * zdum
+
+The radiocarbon age is computed as  $(-1/\lambda) \ln{ \left( \Rq \right)}$, with zero age corresponding to $\Rq=1$.
+
+The reservoir age is the age difference between the ocean uppermost layer and the atmosphere. It is usually reported as conventional radiocarbon age; i.e., computed by means of the Libby radiocarbon mean life \cite[8033 yr;][]{stuiver_1977}
+\begin{align}
+{^{14}\tau_\mathrm{c}}= -8033 \; \ln \left(1 + \frac{\Dcq}{10^3}\right), \label{eq:convage}
+\end{align}
+where ${^{14}\tau_\mathrm{c}}$ is expressed in years B.P. Here we do not use that convention and compute reservoir ages with the mean lifetime $1/\lambda$. Conversion from one scale to the other is readily performed. The conventional radiocarbon age is lower than the radiocarbon age by $\simeq3\%$.
+
+The ocean radiocarbon  inventory is computed as
+\begin{equation}
+N_A \Rq_\mathrm{oxa} \overline{\Ct} \left( \int_\Omega \Rq d\Omega \right) /10^{26}, \label{eq:inv}
+\end{equation}
+where $N_A$ is the Avogadro's number ($N_A=6.022\times10^{23}$ at/mol), $\Rq_\mathrm{oxa}$ is the oxalic acid radiocarbon standard \cite[$\Rq_\mathrm{oxa}=1.176\times10^{-12}$;][]{stuiver_1977}, and $\Omega$ is the ocean volume.  Bomb $\cq$ inventories are traditionally reported in units of $10^{26}$ atoms, hence the denominator in \eqref{eq:inv}.
+
+All transformations from second to year, and inversely, are performed with the help of the physical constant \CODE{rsiyea} the sideral year length expressed in seconds\footnote{The variable (\CODE{nyear\_len}) which reports the length in days of the previous/current/future year (see \textrm{oce\_trc.F90}) is not a constant. }.
+
+The global transfer velocities represent time-averaged\footnote{the actual duration is set in \texttt{iodef.xml}} global integrals of the transfer rates:
+ \begin{equation}
+ \overline{\kappa_{\cd}}= \int_\mathcal{S} \kappa_{\cd} d\mathcal{S}  \text{ and } \overline{\kappa_R}= \int_\mathcal{S} \kappa_R d\mathcal{S}
+\end{equation}
+
+
+\subsection{PISCES biogeochemical model}
+
+PISCES is a biogeochemical model which simulates the lower trophic levels of marine ecosystem (phytoplankton, microzooplankton and mesozooplankton) and the biogeochemical cycles of carbonand of the main nutrients (P, N, Fe, and Si). The  model is intended to be used for both regional and global configurations at high or low spatial resolutions as well as for  short-term (seasonal, interannual) and long-term (climate change, paleoceanography) analyses.
+Two versions of PISCES are available in NEMO v4.0 :
+
+PISCES-v2, by setting in namelist\_pisces\_ref  \np{ln\_p4z} to true,  can be seen as one of the many Monod models \citep{monod_1958}. It assumes a constant Redfield ratio and phytoplankton growth depends on the external concentration in nutrients. There are twenty-four prognostic variables (tracers) including two phytoplankton compartments  (diatoms and nanophytoplankton), two zooplankton size-classes (microzooplankton and  mesozooplankton) and a description of the carbonate chemistry. Formulations in PISCES-v2 are based on a mixed Monod/Quota formalism: On one hand, stoichiometry of C/N/P is fixed and growth rate of phytoplankton is limited by the external availability in N, P and Si. On the other hand, the iron and silicium quotas are variable and growth rate of phytoplankton is limited by the internal availability in Fe. Various parameterizations can be activated in PISCES-v2, setting for instance the complexity of iron chemistry or the description of particulate organic materials.
+
+PISCES-QUOTA has been built on the PISCES-v2 model described in \citet{aumont_2015}. PISCES-QUOTA has thirty-nine prognostic compartments. Phytoplankton growth can be controlled by five modeled limiting nutrients: Nitrate and Ammonium, Phosphate, Silicate and Iron. Five living compartments are represented: Three phytoplankton size classes/groups corresponding to picophytoplankton, nanophytoplankton and diatoms, and two zooplankton size classes which are microzooplankton and mesozooplankton. For phytoplankton, the prognostic variables are the carbon, nitrogen, phosphorus,  iron, chlorophyll and silicon biomasses (the latter only for diatoms). This means that the N/C, P/C, Fe/C and Chl/C ratios of both phytoplankton groups as well as the Si/C ratio of diatoms are prognostically predicted  by the model. Zooplankton are assumed to be strictly homeostatic \citep[e.g.,][]{sterner_2003,woods_2013,meunier_2014}. As a consequence, the C/N/P/Fe ratios of these groups are maintained constant and are not allowed to vary. In PISCES, the Redfield ratios C/N/P are set to 122/16/1 \citep{takahashi_1985} and the -O/C ratio is set to 1.34 \citep{kortzinger_2001}. No silicified zooplankton is assumed. The bacterial pool is not yet explicitly modeled.
+
+There are three non-living compartments: Semi-labile dissolved organic matter, small sinking particles, and large sinking particles. As a consequence of the variable stoichiometric ratios of phytoplankton and of the stoichiometric regulation of zooplankton, elemental ratios in organic matter cannot be supposed constant anymore as that was the case in PISCES-v2. Indeed, the nitrogen, phosphorus, iron, silicon and calcite pools of the particles are now all explicitly modeled. The sinking speed of the particles is not altered by their content in calcite and biogenic silicate (''The ballast effect'', \citep{honjo_1996,armstrong_2001}). The latter particles are assumed to sink at the same speed as the large organic matter particles. All the non-living compartments experience aggregation due to turbulence and differential settling as well as Brownian coagulation for DOM.
+
+
+\subsection{MY\_TRC interface for coupling external BGC models}
+\label{Mytrc}
+
+The NEMO-TOP has only one built-in biogeochemical model - PISCES - but there are several BGC models - MEDUSA, ERSEM, BFM or ECO3M - which are meant to be coupled with the NEMO dynamics. Therefore it was necessary to provide to the users a framework for easily add their own BGCM model, that can be a single passive tracer.
+The generalized interface is pivoted on MY\_TRC module that contains template files to build the coupling between NEMO and any external BGC model. The call to MY\_TRC is activated by setting  \textit{ln\_my\_trc} = \texttt{.true.} in namelist \textit{namtrc}
+
+The following 6 fortran files are available in MY\_TRC with the specific purposes here described.
+
+\begin{itemize}
+   \item \textit{par\_my\_trc.F90} :  This module allows to define additional arrays and public variables to be used within the MY\_TRC interface
+   \item \textit{trcini\_my\_trc.F90} :  Here are initialized user defined namelists and the call to the external BGC model initialization procedures to populate general tracer array (trn and trb). Here are also likely to be defined suport arrays related to system metrics that could be needed by the BGC model.
+  \item \textit{trcnam\_my\_trc.F90} :  This routine is called at the beginning of trcini\_my\_trc and should contain the initialization of additional namelists for the BGC model or user-defined code.
+  \item \textit{trcsms\_my\_trc.F90} :  The routine performs the call to Boundary Conditions and its main purpose is to contain the Source-Minus-Sinks terms due to the biogeochemical processes of the external model. Be aware that lateral boundary conditions are applied in trcnxt routine. IMPORTANT: the routines to compute the light penetration along the water column and the tracer vertical sinking should be defined/called in here, as generalized modules are still missing in the code.
+ \item \textit{trcice\_my\_trc.F90} : Here it is possible to prescribe the tracers concentrations in the seaice that will be used as boundary conditions when ice melting occurs (nn\_ice\_tr =1 in namtrc\_ice). See e.g. the correspondent PISCES subroutine.
+ \item \textit{trcwri\_my\_trc.F90} : This routine performs the output of the model tracers using IOM module (see Manual Chapter Output and Diagnostics). It is possible to place here the output of additional variables produced by the model, if not done elsewhere in the code, using the call to \textit{iom\_put}.
+\end{itemize}
+
+
+\section{The Offline Option}
+\label{Offline}
+
+%------------------------------------------namtrc_sms----------------------------------------------------
+\nlst{namdta_dyn}
+%-------------------------------------------------------------------------------------------------------------
+
+Coupling passive tracers offline with NEMO requires precomputed  physical fields from OGCM. Those fields are read from files and interpolated on-the-fly at each model time step
+At least the following dynamical parameters should be absolutely passed to the transport : ocean velocities, temperature, salinity, mixed layer depth and for ecosystem models like PISCES, sea ice concentration, short wave radiation at the ocean surface, wind speed (or at least, wind stress).
+The so-called offline mode is useful since it has lower computational costs for example to perform very longer simulations - about 3000 years - to reach equilibrium of CO2 sinks for climate-carbon studies.
+
+The offline interface is located in the code repository : \path{<repository>/src/OFF/}. It is activated by adding the CPP key  \textit{key\_offline} to the CPP keys list. There are two specifics routines for the Offline code :
+
+\begin{itemize}
+   \item \textit{dtadyn.F90} :  this module allows to read and compute the dynamical fields at each model time-step
+   \item \textit{nemogcm.F90} :  a degraded version of the main nemogcm.F90 code of NEMO to manage the time-stepping
+\end{itemize}
+
+
+%-
+%-
+%-
+%-  Describes here the specifities of oflline : At least the dynamical variables needed - u/v/w transport T/S for isopycnal MLD for biogeo models etc ...
+%-  the specfities of vvl - ssh + runoffs and how to
+%-
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_setup.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_setup.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/model_setup.tex	(revision 14097)
@@ -0,0 +1,46 @@
+\documentclass[../main/TOP_manual]{subfiles}
+
+\begin{document}
+
+\chapter{ Model Setup}
+
+\section{ Setting up a passive tracer configuration}
+%------------------------------------------namtrc_int----------------------------------------------------
+\nlst{namtrc}
+%-------------------------------------------------------------------------------------------------------------
+
+The usage of TOP is activated
+
+\begin{itemize}
+         \item by including in the configuration definition the component TOP\_SRC
+         \item by adding the macro \textit{key\_top} in the configuration cpp file
+\end{itemize}
+
+As an example, the user can refer to already available configurations in the code, GYRE\_PISCES being the NEMO biogeochemical demonstrator and GYRE\_BFM to see the required configuration elements to couple with an external biogeochemical model (see also section \S\ref{SMS_models}) .
+
+Note that, since version 4.0, TOP interface core functionalities are activated by means of logical keys and all submodules preprocessing macros from previous versions were removed.
+
+There are only three specific keys remaining in TOP
+
+\begin{itemize}
+        \item \textit{key\_top} : to enables passive tracer module
+        \item \textit{key\_trdtrc} and \textit{key\_trdmxl\_trc} : trend computation for tracers
+\end{itemize}
+
+For a remind, the revisited structure of TOP interface now counts for five different modules handled in namelist\_top :
+
+\begin{itemize}
+        \item \textbf{PISCES}, default BGC model
+        \item \textbf{MY\_TRC}, template for creation of new modules couplings (maybe run a single passive tracer)
+        \item \textbf{CFC}, inert carbon tracers dynamics (CFC11,CFC12,SF6) Updated with OMIP-BGC guidelines (Orr et al, 2016)
+        \item \textbf{C14}, radiocarbon passive tracer
+        \item \textbf{AGE}, water age tracking revised implementation
+\end{itemize}
+
+The modular approach was implemented also in the definition of the total number of passive tracers (jptra). This results from to user setting from the namelist \textit{namtrc}
+
+\section{ TOP Tracer Initialisation}
+
+\section{ TOP Boundaries Conditions}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/modules.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/modules.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/modules.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/modules.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/parameters.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/parameters.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/parameters.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/parameters.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/subroutines.idx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/subroutines.idx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/TOP/subfiles/subroutines.idx	(revision 14097)
@@ -0,0 +1,1 @@
+link ../build/subroutines.idx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/ametsoc.bst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/ametsoc.bst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/ametsoc.bst	(revision 14097)
@@ -0,0 +1,1662 @@
+%%
+%% This is file `ametsoc7.bst',
+%% generated with the docstrip utility.
+%%
+%% The original source files were:
+%%
+%% merlin.mbs  (with options: `ay,nat,nm-rev1,ed-rev,jnrlst,nmdash,nmd-3,dt-beg,yr-com,yrp-col,thtit-a,vol-2bf,vnum-sp,volp-com,pgsep-s,num-xser,numser,ser-vol,bkpg-x,pg-bk,pre-edn,agu-doi,doi,edparc,bkedcap,edby,edbyy,blk-tit,in-x,pp,ed,abr,ednx,ord,jabr,eprint,url,url-nt,em-it,nfss,')
+%% ----------------------------------------
+%% *** Bibliography style file for ALL AMS Journals...version 1.0  ***
+%% *** Brian Papa - American Meteorological Society ***
+%%
+%% Copyright 1994-2004 Patrick W Daly
+ % ===============================================================
+ % IMPORTANT NOTICE:
+ % This bibliographic style (bst) file has been generated from one or
+ % more master bibliographic style (mbs) files, listed above.
+ %
+ % This generated file can be redistributed and/or modified under the terms
+ % of the LaTeX Project Public License Distributed from CTAN
+ % archives in directory macros/latex/base/lppl.txt; either
+ % version 1 of the License, or any later version.
+ % ===============================================================
+ % Name and version information of the main mbs file:
+ % \ProvidesFile{merlin.mbs}[2004/02/09 4.13 (PWD, AO, DPC)]
+ %   For use with BibTeX version 0.99a or later
+ %-------------------------------------------------------------------
+ % This bibliography style file is intended for texts in ENGLISH
+ % This is an author-year citation style bibliography. As such, it is
+ % non-standard LaTeX, and requires a special package file to function properly.
+ % Such a package is    natbib.sty   by Patrick W. Daly
+ % The form of the \bibitem entries is
+ %   \bibitem[Jones et al.(1990)]{key}...
+ %   \bibitem[Jones et al.(1990)Jones, Baker, and Smith]{key}...
+ % The essential feature is that the label (the part in brackets) consists
+ % of the author names, as they should appear in the citation, with the year
+ % in parentheses following. There must be no space before the opening
+ % parenthesis!
+ % With natbib v5.3, a full list of authors may also follow the year.
+ % In natbib.sty, it is possible to define the type of enclosures that is
+ % really wanted (brackets or parentheses), but in either case, there must
+ % be parentheses in the label.
+ % The \cite command functions as follows:
+ %   \citet{key} ==>>                Jones et al. (1990)
+ %   \citet*{key} ==>>               Jones, Baker, and Smith (1990)
+ %   \citep{key} ==>>                (Jones et al., 1990)
+ %   \citep*{key} ==>>               (Jones, Baker, and Smith, 1990)
+ %   \citep[chap. 2]{key} ==>>       (Jones et al., 1990, chap. 2)
+ %   \citep[e.g.][]{key} ==>>        (e.g. Jones et al., 1990)
+ %   \citep[e.g.][p. 32]{key} ==>>   (e.g. Jones et al., p. 32)
+ %   \citeauthor{key} ==>>           Jones et al.
+ %   \citeauthor*{key} ==>>          Jones, Baker, and Smith
+ %   \citeyear{key} ==>>             1990
+ %---------------------------------------------------------------------
+
+ENTRY
+  { address
+    archive
+    author
+    booktitle
+    chapter
+    doi
+    edition
+    editor
+    eid
+    eprint
+    howpublished
+    department
+    institution
+    journal
+    key
+    month
+    note
+    number
+    organization
+    pages
+    publisher
+    school
+    series
+    title
+    type
+    url
+    volume
+    year
+  }
+  {}
+  { label extra.label sort.label short.list }
+INTEGERS { output.state before.all mid.sentence after.sentence after.block }
+FUNCTION {init.state.consts}
+{ #0 'before.all :=
+  #1 'mid.sentence :=
+  #2 'after.sentence :=
+  #3 'after.block :=
+}
+STRINGS { s t}
+FUNCTION {output.nonnull}
+{ 's :=
+  output.state mid.sentence =
+    { ", " * write$ }
+    { output.state after.block =
+        { add.period$ write$
+          newline$
+          "\newblock " write$
+        }
+        { output.state before.all =
+            'write$
+            { add.period$ " " * write$ }
+          if$
+        }
+      if$
+      mid.sentence 'output.state :=
+    }
+  if$
+  s
+}
+FUNCTION {output}
+{ duplicate$ empty$
+    'pop$
+    'output.nonnull
+  if$
+}
+FUNCTION {output.check}
+{ 't :=
+  duplicate$ empty$
+    { pop$ "empty " t * " in " * cite$ * warning$ }
+    'output.nonnull
+  if$
+}
+FUNCTION {fin.entry}
+{ add.period$
+  write$
+  newline$
+}
+
+FUNCTION {new.block}
+{ output.state before.all =
+    'skip$
+    { after.block 'output.state := }
+  if$
+}
+FUNCTION {new.sentence}
+{ output.state after.block =
+    'skip$
+    { output.state before.all =
+        'skip$
+        { after.sentence 'output.state := }
+      if$
+    }
+  if$
+}
+FUNCTION {add.blank}
+{  " " * before.all 'output.state :=
+}
+
+FUNCTION {date.block}
+{
+  ":" *
+  add.blank
+}
+
+FUNCTION {not}
+{   { #0 }
+    { #1 }
+  if$
+}
+FUNCTION {and}
+{   'skip$
+    { pop$ #0 }
+  if$
+}
+FUNCTION {or}
+{   { pop$ #1 }
+    'skip$
+  if$
+}
+FUNCTION {new.block.checkb}
+{ empty$
+  swap$ empty$
+  and
+    'skip$
+    'new.block
+  if$
+}
+FUNCTION {field.or.null}
+{ duplicate$ empty$
+    { pop$ "" }
+    'skip$
+  if$
+}
+FUNCTION {emphasize}
+{ duplicate$ empty$
+    { pop$ "" }
+    { "\textit{" swap$ * "}" * }
+  if$
+}
+FUNCTION {bolden}
+{ duplicate$ empty$
+    { pop$ "" }
+    { "\textbf{" swap$ * "}" * }
+  if$
+}
+FUNCTION {tie.or.space.prefix}
+{ duplicate$ text.length$ #3 <
+    { "~" }
+    { " " }
+  if$
+  swap$
+}
+
+FUNCTION {capitalize}
+{ "u" change.case$ "t" change.case$ }
+
+FUNCTION {space.word}
+{ " " swap$ * " " * }
+ % Here are the language-specific definitions for explicit words.
+ % Each function has a name bbl.xxx where xxx is the English word.
+ % The language selected here is ENGLISH
+FUNCTION {bbl.and}
+{ "and"}
+
+FUNCTION {bbl.etal}
+{ "et~al." }
+
+FUNCTION {bbl.editors}
+{ "Eds." }
+
+FUNCTION {bbl.editor}
+{ "Ed." }
+
+FUNCTION {bbl.edby}
+{ "edited by" }
+
+FUNCTION {bbl.edition}
+{ "ed." }
+
+FUNCTION {bbl.volume}
+{ "Vol." }
+
+FUNCTION {bbl.of}
+{ "of" }
+
+FUNCTION {bbl.number}
+{ "No." }
+
+FUNCTION {bbl.nr}
+{ "No." }
+
+FUNCTION {bbl.in}
+{ "in" }
+
+FUNCTION {bbl.pages}
+{ "pp." }
+
+FUNCTION {bbl.page}
+{ "p." }
+
+FUNCTION {bbl.chapter}
+{ "chap." }
+
+FUNCTION {bbl.techrep}
+{ "Tech. Rep." }
+
+FUNCTION {bbl.mthesis}
+{ "Master's thesis" }
+
+FUNCTION {bbl.phdthesis}
+{ "Ph.D. thesis" }
+
+FUNCTION {bbl.first}
+{ "1st" }
+
+FUNCTION {bbl.second}
+{ "2d" }
+
+FUNCTION {bbl.third}
+{ "3d" }
+
+FUNCTION {bbl.fourth}
+{ "4th" }
+
+FUNCTION {bbl.fifth}
+{ "5th" }
+
+FUNCTION {bbl.st}
+{ "st" }
+
+FUNCTION {bbl.nd}
+{ "d" }
+
+FUNCTION {bbl.rd}
+{ "d" }
+
+FUNCTION {bbl.th}
+{ "th" }
+
+MACRO {jan} {"Jan."}
+
+MACRO {feb} {"Feb."}
+
+MACRO {mar} {"Mar."}
+
+MACRO {apr} {"Apr."}
+
+MACRO {may} {"May"}
+
+MACRO {jun} {"Jun."}
+
+MACRO {jul} {"Jul."}
+
+MACRO {aug} {"Aug."}
+
+MACRO {sep} {"Sep."}
+
+MACRO {oct} {"Oct."}
+
+MACRO {nov} {"Nov."}
+
+MACRO {dec} {"Dec."}
+
+FUNCTION {eng.ord}
+{ duplicate$ "1" swap$ *
+  #-2 #1 substring$ "1" =
+     { bbl.th * }
+     { duplicate$ #-1 #1 substring$
+       duplicate$ "1" =
+         { pop$ bbl.st * }
+         { duplicate$ "2" =
+             { pop$ bbl.nd * }
+             { "3" =
+                 { bbl.rd * }
+                 { bbl.th * }
+               if$
+             }
+           if$
+          }
+       if$
+     }
+   if$
+}
+
+MACRO {acmcs} {"ACM Comput. Surv."}
+
+MACRO {acta} {"Acta Inf."}
+
+MACRO {cacm} {"Commun. ACM"}
+
+MACRO {ibmjrd} {"IBM J. Res. Dev."}
+
+MACRO {ibmsj} {"IBM Syst.~J."}
+
+MACRO {ieeese} {"IEEE Trans. Software Eng."}
+
+MACRO {ieeetc} {"IEEE Trans. Comput."}
+
+MACRO {ieeetcad}
+ {"IEEE Trans. Comput. Aid. Des."}
+
+MACRO {ipl} {"Inf. Process. Lett."}
+
+MACRO {jacm} {"J.~ACM"}
+
+MACRO {jcss} {"J.~Comput. Syst. Sci."}
+
+MACRO {scp} {"Sci. Comput. Program."}
+
+MACRO {sicomp} {"SIAM J. Comput."}
+
+MACRO {tocs} {"ACM Trans. Comput. Syst."}
+
+MACRO {tods} {"ACM Trans. Database Syst."}
+
+MACRO {tog} {"ACM Trans. Graphic."}
+
+MACRO {toms} {"ACM Trans. Math. Software"}
+
+MACRO {toois} {"ACM Trans. Office Inf. Syst."}
+
+MACRO {toplas} {"ACM Trans. Progr. Lang. Syst."}
+
+MACRO {tcs} {"Theor. Comput. Sci."}
+
+FUNCTION {bibinfo.check}
+{ swap$
+  duplicate$ missing$
+    {
+      pop$ pop$
+      ""
+    }
+    { duplicate$ empty$
+        {
+          swap$ pop$
+        }
+        { swap$
+          pop$
+        }
+      if$
+    }
+  if$
+}
+FUNCTION {bibinfo.warn}
+{ swap$
+  duplicate$ missing$
+    {
+      swap$ "missing " swap$ * " in " * cite$ * warning$ pop$
+      ""
+    }
+    { duplicate$ empty$
+        {
+          swap$ "empty " swap$ * " in " * cite$ * warning$
+        }
+        { swap$
+          pop$
+        }
+      if$
+    }
+  if$
+}
+FUNCTION {format.eprint}
+{ eprint duplicate$ empty$
+    'skip$
+    { "\eprint"
+      archive empty$
+        'skip$
+        { "[" * archive * "]" * }
+      if$
+      "{" * swap$ * "}" *
+    }
+  if$
+}
+STRINGS  { bibinfo}
+INTEGERS { nameptr namesleft numnames }
+
+FUNCTION {format.names}
+{ 'bibinfo :=
+  duplicate$ empty$ 'skip$ {
+  's :=
+  "" 't :=
+  #1 'nameptr :=
+  s num.names$ 'numnames :=
+  numnames 'namesleft :=
+    { namesleft #0 > }
+    { s nameptr
+      duplicate$ #1 >
+        { "{f.~}{vv~}{ll}{, jj}" }
+        { "{vv~}{ll}{, f.}{, jj}" }
+      if$
+      format.name$
+      bibinfo bibinfo.check
+      't :=
+      nameptr #1 >
+        {
+          namesleft #1 >
+            { ", " * t * }
+            {
+              numnames #2 >
+                { "," * }
+                'skip$
+              if$
+              s nameptr "{ll}" format.name$ duplicate$ "others" =
+                { 't := }
+                { pop$ }
+              if$
+              t "others" =
+                {
+                  " " * bbl.etal *
+                }
+                {
+                  bbl.and
+                  space.word * t *
+                }
+              if$
+            }
+          if$
+        }
+        't
+      if$
+      nameptr #1 + 'nameptr :=
+      namesleft #1 - 'namesleft :=
+    }
+  while$
+  } if$
+}
+FUNCTION {format.names.ed}
+{
+  format.names
+}
+FUNCTION {format.key}
+{ empty$
+    { key field.or.null }
+    { "" }
+  if$
+}
+
+FUNCTION {format.authors}
+{ author "author" format.names
+}
+FUNCTION {get.bbl.editor}
+{ editor num.names$ #1 > 'bbl.editors 'bbl.editor if$ }
+
+FUNCTION {format.editors}
+{ editor "editor" format.names duplicate$ empty$ 'skip$
+    {
+      "," *
+      " " *
+      get.bbl.editor
+      capitalize
+   "(" swap$ * ")" *
+      *
+    }
+  if$
+}
+FUNCTION {format.book.pages}
+{ pages "pages" bibinfo.check
+  duplicate$ empty$ 'skip$
+    { " " * bbl.pages * }
+  if$
+}
+FUNCTION {format.doi}
+{ doi "doi" bibinfo.check
+  duplicate$ empty$ 'skip$
+    {
+      "\href{http://dx.doi.org/" swap$ * "}{\aiDoi}" *
+    }
+  if$
+}
+FUNCTION {format.note}
+{
+  url empty$
+    'skip$
+    { "\href{" url * "}{URL}" * output }
+  if$
+ note empty$
+    { "" }
+    { note #1 #1 substring$
+      duplicate$ "{" =
+        'skip$
+        { output.state mid.sentence =
+          { "l" }
+          { "u" }
+        if$
+        change.case$
+        }
+      if$
+      note #2 global.max$ substring$ * "note" bibinfo.check
+    }
+  if$
+}
+
+FUNCTION {format.title}
+{ title
+  duplicate$ empty$ 'skip$
+    { "t" change.case$ }
+  if$
+  "title" bibinfo.check
+}
+FUNCTION {format.full.names}
+{'s :=
+ "" 't :=
+  #1 'nameptr :=
+  s num.names$ 'numnames :=
+  numnames 'namesleft :=
+    { namesleft #0 > }
+    { s nameptr
+      "{vv~}{ll}" format.name$
+      't :=
+      nameptr #1 >
+        {
+          namesleft #1 >
+            { ", " * t * }
+            {
+              s nameptr "{ll}" format.name$ duplicate$ "others" =
+                { 't := }
+                { pop$ }
+              if$
+              t "others" =
+                {
+                  " " * bbl.etal *
+                }
+                {
+                  numnames #2 >
+                    { "," * }
+                    'skip$
+                  if$
+                  bbl.and
+                  space.word * t *
+                }
+              if$
+            }
+          if$
+        }
+        't
+      if$
+      nameptr #1 + 'nameptr :=
+      namesleft #1 - 'namesleft :=
+    }
+  while$
+}
+
+FUNCTION {author.editor.key.full}
+{ author empty$
+    { editor empty$
+        { key empty$
+            { cite$ #1 #3 substring$ }
+            'key
+          if$
+        }
+        { editor format.full.names }
+      if$
+    }
+    { author format.full.names }
+  if$
+}
+
+FUNCTION {author.key.full}
+{ author empty$
+    { key empty$
+         { cite$ #1 #3 substring$ }
+          'key
+      if$
+    }
+    { author format.full.names }
+  if$
+}
+
+FUNCTION {editor.key.full}
+{ editor empty$
+    { key empty$
+         { cite$ #1 #3 substring$ }
+          'key
+      if$
+    }
+    { editor format.full.names }
+  if$
+}
+
+FUNCTION {make.full.names}
+{ type$ "book" =
+  type$ "inbook" =
+  or
+    'author.editor.key.full
+    { type$ "proceedings" =
+        'editor.key.full
+        'author.key.full
+      if$
+    }
+  if$
+}
+
+FUNCTION {output.bibitem}
+{ newline$
+  "\bibitem[{" write$
+  label write$
+  ")" make.full.names duplicate$ short.list =
+     { pop$ }
+     { * }
+   if$
+  "}]{" * write$
+  cite$ write$
+  "}" write$
+  newline$
+  ""
+  before.all 'output.state :=
+}
+
+FUNCTION {if.digit}
+{ duplicate$ "0" =
+  swap$ duplicate$ "1" =
+  swap$ duplicate$ "2" =
+  swap$ duplicate$ "3" =
+  swap$ duplicate$ "4" =
+  swap$ duplicate$ "5" =
+  swap$ duplicate$ "6" =
+  swap$ duplicate$ "7" =
+  swap$ duplicate$ "8" =
+  swap$ "9" = or or or or or or or or or
+}
+FUNCTION {n.separate}
+{ 't :=
+  ""
+  #0 'numnames :=
+  { t empty$ not }
+  { t #-1 #1 substring$ if.digit
+      { numnames #1 + 'numnames := }
+      { #0 'numnames := }
+    if$
+    t #-1 #1 substring$ swap$ *
+    t #-2 global.max$ substring$ 't :=
+    numnames #5 =
+      { duplicate$ #1 #2 substring$ swap$
+        #3 global.max$ substring$
+        "\," swap$ * *
+      }
+      'skip$
+    if$
+  }
+  while$
+}
+FUNCTION {n.dashify}
+{
+  n.separate
+  't :=
+  ""
+    { t empty$ not }
+    { t #1 #1 substring$ "-" =
+        { t #1 #2 substring$ "--" = not
+            { "--" *
+              t #2 global.max$ substring$ 't :=
+            }
+            {   { t #1 #1 substring$ "-" = }
+                { "-" *
+                  t #2 global.max$ substring$ 't :=
+                }
+              while$
+            }
+          if$
+        }
+        { t #1 #1 substring$ *
+          t #2 global.max$ substring$ 't :=
+        }
+      if$
+    }
+  while$
+}
+
+FUNCTION {word.in}
+{ "" }
+
+FUNCTION {format.date}
+{ year "year" bibinfo.check duplicate$ empty$
+    {
+      "empty year in " cite$ * "; set to ????" * warning$
+       pop$ "????"
+    }
+    'skip$
+  if$
+  extra.label *
+  before.all 'output.state :=
+  ", " swap$ *
+}
+FUNCTION {format.btitle}
+{ title "title" bibinfo.check
+  duplicate$ empty$ 'skip$
+    {
+      emphasize
+    }
+  if$
+}
+FUNCTION {either.or.check}
+{ empty$
+    'pop$
+    { "can't use both " swap$ * " fields in " * cite$ * warning$ }
+  if$
+}
+FUNCTION {format.bvolume}
+{ volume empty$
+    { "" }
+    { bbl.volume volume tie.or.space.prefix
+      "volume" bibinfo.check * *
+      series "series" bibinfo.check
+      duplicate$ empty$ 'pop$
+%%% NO ITALIC SERIES        { emphasize ", " * swap$ * }
+      {", " * swap$ * }
+      if$
+      "volume and number" number either.or.check
+    }
+  if$
+}
+FUNCTION {format.number.series}
+{ volume empty$
+    { number empty$
+        { series field.or.null }
+        { series empty$
+            { number "number" bibinfo.check }
+            { output.state mid.sentence =
+                { bbl.number }
+                { bbl.number capitalize }
+              if$
+              number tie.or.space.prefix "number" bibinfo.check * *
+              bbl.in space.word *
+              series "series" bibinfo.check *
+            }
+          if$
+        }
+      if$
+    }
+    { "" }
+  if$
+}
+FUNCTION {is.num}
+{ chr.to.int$
+  duplicate$ "0" chr.to.int$ < not
+  swap$ "9" chr.to.int$ > not and
+}
+
+FUNCTION {extract.num}
+{ duplicate$ 't :=
+  "" 's :=
+  { t empty$ not }
+  { t #1 #1 substring$
+    t #2 global.max$ substring$ 't :=
+    duplicate$ is.num
+      { s swap$ * 's := }
+      { pop$ "" 't := }
+    if$
+  }
+  while$
+  s empty$
+    'skip$
+    { pop$ s }
+  if$
+}
+
+FUNCTION {convert.edition}
+{ extract.num "l" change.case$ 's :=
+  s "first" = s "1" = or
+    { bbl.first 't := }
+    { s "second" = s "2" = or
+        { bbl.second 't := }
+        { s "third" = s "3" = or
+            { bbl.third 't := }
+            { s "fourth" = s "4" = or
+                { bbl.fourth 't := }
+                { s "fifth" = s "5" = or
+                    { bbl.fifth 't := }
+                    { s #1 #1 substring$ is.num
+                        { s eng.ord 't := }
+                        { edition 't := }
+                      if$
+                    }
+                  if$
+                }
+              if$
+            }
+          if$
+        }
+      if$
+    }
+  if$
+  t
+}
+
+FUNCTION {format.edition}
+{ edition duplicate$ empty$ 'skip$
+    {
+      convert.edition
+      output.state mid.sentence =
+        { "l" }
+        { "t" }
+      if$ change.case$
+      "edition" bibinfo.check
+      " " * bbl.edition *
+    }
+  if$
+}
+INTEGERS { multiresult }
+FUNCTION {multi.page.check}
+{ 't :=
+  #0 'multiresult :=
+    { multiresult not
+      t empty$ not
+      and
+    }
+    { t #1 #1 substring$
+      duplicate$ "-" =
+      swap$ duplicate$ "," =
+      swap$ "+" =
+      or or
+        { #1 'multiresult := }
+        { t #2 global.max$ substring$ 't := }
+      if$
+    }
+  while$
+  multiresult
+}
+FUNCTION {format.pages}
+{ pages duplicate$ empty$ 'skip$
+    { duplicate$ multi.page.check
+        {
+          n.dashify
+        }
+        {
+        }
+      if$
+      "pages" bibinfo.check
+    }
+  if$
+}
+FUNCTION {format.journal.pages}
+{ pages duplicate$ empty$ 'pop$
+    { swap$ duplicate$ empty$
+        { pop$ pop$ format.pages }
+        {
+          ", " *
+          swap$
+          n.dashify
+          "pages" bibinfo.check
+          *
+        }
+      if$
+    }
+  if$
+}
+FUNCTION {format.journal.eid}
+{ eid "eid" bibinfo.check
+  duplicate$ empty$ 'pop$
+    { swap$ duplicate$ empty$ 'skip$
+      {
+          ", " *
+      }
+      if$
+      swap$ *
+    }
+  if$
+}
+FUNCTION {format.vol.num.pages}
+{ volume field.or.null
+  duplicate$ empty$ 'skip$
+    {
+      "volume" bibinfo.check
+    }
+  if$
+  number "number" bibinfo.check duplicate$ empty$ 'skip$
+    {
+      swap$ duplicate$ empty$
+        { "there's a number but no volume in " cite$ * warning$ }
+        'skip$
+      if$
+      swap$
+      "~(" swap$ * ")" *
+    }
+  if$ *
+  bolden
+  eid empty$
+    { format.journal.pages }
+    { format.journal.eid }
+  if$
+}
+
+FUNCTION {format.chapter.pages}
+{ chapter empty$
+    'format.pages
+    { type empty$
+        { bbl.chapter }
+        { type "l" change.case$
+          "type" bibinfo.check
+        }
+      if$
+      chapter tie.or.space.prefix
+      "chapter" bibinfo.check
+      * *
+      pages empty$
+        'skip$
+        { ", " * format.pages * }
+      if$
+    }
+  if$
+}
+
+FUNCTION {format.booktitle}
+{
+  booktitle "booktitle" bibinfo.check
+  emphasize
+}
+FUNCTION {format.in.ed.booktitle}
+{ format.booktitle duplicate$ empty$ 'skip$
+    {
+      editor "editor" format.names.ed duplicate$ empty$ 'pop$
+        {
+          get.bbl.editor
+          swap$ "," *
+          " " * swap$ *
+          swap$
+          "," *
+          " " * swap$
+          * }
+      if$
+      word.in swap$ *
+    }
+  if$
+}
+FUNCTION {format.thesis.type}
+{ type duplicate$ empty$
+    'pop$
+    { swap$ pop$
+      "t" change.case$ "type" bibinfo.check
+    }
+  if$
+}
+FUNCTION {format.tr.number}
+{ number "number" bibinfo.check
+  type duplicate$ empty$
+    { pop$ bbl.techrep }
+    'skip$
+  if$
+  "type" bibinfo.check
+  swap$ duplicate$ empty$
+    { pop$ "t" change.case$ }
+    { tie.or.space.prefix * * }
+  if$
+}
+FUNCTION {format.article.crossref}
+{
+  word.in
+  " \cite{" * crossref * "}" *
+}
+FUNCTION {format.book.crossref}
+{ volume duplicate$ empty$
+    { "empty volume in " cite$ * "'s crossref of " * crossref * warning$
+      pop$ word.in
+    }
+    { bbl.volume
+      capitalize
+      swap$ tie.or.space.prefix "volume" bibinfo.check * * bbl.of space.word *
+    }
+  if$
+  " \cite{" * crossref * "}" *
+}
+FUNCTION {format.incoll.inproc.crossref}
+{
+  word.in
+  " \cite{" * crossref * "}" *
+}
+FUNCTION {format.org.or.pub}
+{ 't :=
+  ""
+  address empty$ t empty$ and
+    'skip$
+    {
+      t empty$
+        { address "address" bibinfo.check *
+        }
+        { t *
+          address empty$
+            'skip$
+            { ", " * address "address" bibinfo.check * }
+          if$
+        }
+      if$
+    }
+  if$
+}
+FUNCTION {format.publisher.address}
+{ publisher "publisher" bibinfo.warn format.org.or.pub
+}
+
+FUNCTION {format.organization.address}
+{ organization "organization" bibinfo.check format.org.or.pub
+}
+
+STRINGS {oldname}
+
+FUNCTION {name.or.dash}
+{ 's :=
+   oldname empty$
+     { s 'oldname := s }
+     { s oldname =
+         { "---{}---{}---" }
+         { s 'oldname := s }
+       if$
+     }
+   if$
+}
+
+FUNCTION {article}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title "title" output.check
+  new.sentence
+  crossref missing$
+    {
+      journal
+      "journal" bibinfo.check
+      emphasize
+      "journal" output.check
+      format.vol.num.pages output
+  format.doi output
+    }
+    { format.article.crossref output.nonnull
+      format.pages output
+    }
+  if$
+  format.note output
+  format.eprint output
+  fin.entry
+}
+FUNCTION {book}
+{ output.bibitem
+  author empty$
+    { format.editors "author and editor" output.check
+      editor format.key output
+      add.blank
+      name.or.dash
+    }
+    { format.authors output.nonnull
+      name.or.dash
+      crossref missing$
+        { "author and editor" editor either.or.check }
+        'skip$
+      if$
+    }
+  if$
+  format.date "year" output.check
+  date.block
+  format.btitle "title" output.check
+  crossref missing$
+    { format.bvolume output
+  new.sentence
+      format.edition output
+      format.number.series output
+      format.publisher.address output
+    }
+    {
+  new.sentence
+      format.book.crossref output.nonnull
+    }
+  if$
+  format.book.pages output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+FUNCTION {booklet}
+{ output.bibitem
+  format.authors output
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title "title" output.check
+  new.sentence
+  howpublished "howpublished" bibinfo.check output
+  address "address" bibinfo.check output
+  format.book.pages output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {inbook}
+{ output.bibitem
+  author empty$
+    { format.editors "author and editor" output.check
+      editor format.key output
+      name.or.dash
+    }
+    { format.authors output.nonnull
+      name.or.dash
+      crossref missing$
+        { "author and editor" editor either.or.check }
+        'skip$
+      if$
+    }
+  if$
+  format.date "year" output.check
+  date.block
+  format.btitle "title" output.check
+  crossref missing$
+    {
+      format.bvolume output
+      format.chapter.pages "chapter and pages" output.check
+  new.sentence
+      format.edition output
+      format.number.series output
+      format.publisher.address output
+    }
+    {
+      format.chapter.pages "chapter and pages" output.check
+  new.sentence
+      format.book.crossref output.nonnull
+    }
+  if$
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {incollection}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title "title" output.check
+  new.sentence
+  crossref missing$
+    { format.in.ed.booktitle "booktitle" output.check
+      format.publisher.address output
+      format.bvolume output
+      format.number.series output
+      format.edition output
+      format.chapter.pages output
+    }
+    { format.incoll.inproc.crossref output.nonnull
+      format.chapter.pages output
+    }
+  if$
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+FUNCTION {inproceedings}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title "title" output.check
+  new.sentence
+  crossref missing$
+    { format.in.ed.booktitle "booktitle" output.check
+      publisher empty$
+        { format.organization.address output }
+        { organization "organization" bibinfo.check output
+          format.publisher.address output
+        }
+      if$
+      format.bvolume output
+      format.pages output
+      format.number.series output
+      howpublished "howpublished" bibinfo.check output
+    }
+    { format.incoll.inproc.crossref output.nonnull
+      format.pages output
+    }
+  if$
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+FUNCTION {conference} { inproceedings }
+FUNCTION {manual}
+{ output.bibitem
+  format.authors output
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.btitle "title" output.check
+  new.sentence
+  organization "organization" bibinfo.check output
+  address "address" bibinfo.check output
+  format.edition output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {mastersthesis}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title
+  "title" output.check
+  new.sentence
+  bbl.mthesis format.thesis.type output.nonnull
+  department "department" bibinfo.warn output
+  school "school" bibinfo.warn output
+  address "address" bibinfo.check output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {misc}
+{ output.bibitem
+  format.authors output
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title output
+  new.sentence
+  howpublished "howpublished" bibinfo.check output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+FUNCTION {phdthesis}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title
+  "title" output.check
+  new.sentence
+  bbl.phdthesis format.thesis.type output.nonnull
+  school "school" bibinfo.warn output
+  address "address" bibinfo.check output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {proceedings}
+{ output.bibitem
+  format.editors output
+  editor format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.btitle "title" output.check
+  format.bvolume output
+  format.number.series output
+  publisher empty$
+    { format.organization.address output }
+    { organization "organization" bibinfo.check output
+      format.publisher.address output
+    }
+  if$
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {techreport}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title
+  "title" output.check
+  new.sentence
+  format.tr.number output.nonnull
+  institution "institution" bibinfo.warn output
+  address "address" bibinfo.check output
+  format.doi output
+  format.note output
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {unpublished}
+{ output.bibitem
+  format.authors "author" output.check
+  author format.key output
+  name.or.dash
+  format.date "year" output.check
+  date.block
+  format.title "title" output.check
+  format.doi output
+  format.note "note" output.check
+  format.eprint output
+  fin.entry
+}
+
+FUNCTION {default.type} { misc }
+READ
+FUNCTION {sortify}
+{ purify$
+  "l" change.case$
+}
+INTEGERS { len }
+FUNCTION {chop.word}
+{ 's :=
+  'len :=
+  s #1 len substring$ =
+    { s len #1 + global.max$ substring$ }
+    's
+  if$
+}
+FUNCTION {format.lab.names}
+{ 's :=
+  "" 't :=
+  s #1 "{vv~}{ll}" format.name$
+  s num.names$ duplicate$
+  #2 >
+    { pop$
+      " " * bbl.etal *
+    }
+    { #2 <
+        'skip$
+        { s #2 "{ff }{vv }{ll}{ jj}" format.name$ "others" =
+            {
+              " " * bbl.etal *
+            }
+            { bbl.and space.word * s #2 "{vv~}{ll}" format.name$
+              * }
+          if$
+        }
+      if$
+    }
+  if$
+}
+
+FUNCTION {author.key.label}
+{ author empty$
+    { key empty$
+        { cite$ #1 #3 substring$ }
+        'key
+      if$
+    }
+    { author format.lab.names }
+  if$
+}
+
+FUNCTION {author.editor.key.label}
+{ author empty$
+    { editor empty$
+        { key empty$
+            { cite$ #1 #3 substring$ }
+            'key
+          if$
+        }
+        { editor format.lab.names }
+      if$
+    }
+    { author format.lab.names }
+  if$
+}
+
+FUNCTION {editor.key.label}
+{ editor empty$
+    { key empty$
+        { cite$ #1 #3 substring$ }
+        'key
+      if$
+    }
+    { editor format.lab.names }
+  if$
+}
+
+FUNCTION {calc.short.authors}
+{ type$ "book" =
+  type$ "inbook" =
+  or
+    'author.editor.key.label
+    { type$ "proceedings" =
+        'editor.key.label
+        'author.key.label
+      if$
+    }
+  if$
+  'short.list :=
+}
+
+FUNCTION {calc.label}
+{ calc.short.authors
+  short.list
+  "("
+  *
+  year duplicate$ empty$
+     { pop$ "????" }
+     { purify$ #-1 #4 substring$ }
+  if$
+  *
+  'label :=
+}
+
+FUNCTION {sort.format.names}
+{ 's :=
+  #1 'nameptr :=
+  ""
+  s num.names$ 'numnames :=
+  numnames 'namesleft :=
+    { namesleft #0 > }
+    { s nameptr
+      "{vv{ } }{ll{ }}{  f{ }}{  jj{ }}"
+      format.name$ 't :=
+      nameptr #1 >
+        {
+          "   "  *
+          namesleft #1 = t "others" = and
+            { "zzzzz" * }
+            { t sortify * }
+          if$
+        }
+        { t sortify * }
+      if$
+      nameptr #1 + 'nameptr :=
+      namesleft #1 - 'namesleft :=
+    }
+  while$
+}
+
+FUNCTION {sort.format.title}
+{ 't :=
+  "A " #2
+    "An " #3
+      "The " #4 t chop.word
+    chop.word
+  chop.word
+  sortify
+  #1 global.max$ substring$
+}
+FUNCTION {author.sort}
+{ author empty$
+    { key empty$
+        { "to sort, need author or key in " cite$ * warning$
+          ""
+        }
+        { key sortify }
+      if$
+    }
+    { author sort.format.names }
+  if$
+}
+FUNCTION {author.editor.sort}
+{ author empty$
+    { editor empty$
+        { key empty$
+            { "to sort, need author, editor, or key in " cite$ * warning$
+              ""
+            }
+            { key sortify }
+          if$
+        }
+        { editor sort.format.names }
+      if$
+    }
+    { author sort.format.names }
+  if$
+}
+FUNCTION {editor.sort}
+{ editor empty$
+    { key empty$
+        { "to sort, need editor or key in " cite$ * warning$
+          ""
+        }
+        { key sortify }
+      if$
+    }
+    { editor sort.format.names }
+  if$
+}
+FUNCTION {presort}
+{ calc.label
+  label sortify
+  "    "
+  *
+  type$ "book" =
+  type$ "inbook" =
+  or
+    'author.editor.sort
+    { type$ "proceedings" =
+        'editor.sort
+        'author.sort
+      if$
+    }
+  if$
+  #1 entry.max$ substring$
+  'sort.label :=
+  sort.label
+  *
+  "    "
+  *
+  title field.or.null
+  sort.format.title
+  *
+  #1 entry.max$ substring$
+  'sort.key$ :=
+}
+
+ITERATE {presort}
+SORT
+STRINGS { last.label next.extra }
+INTEGERS { last.extra.num number.label }
+FUNCTION {initialize.extra.label.stuff}
+{ #0 int.to.chr$ 'last.label :=
+  "" 'next.extra :=
+  #0 'last.extra.num :=
+  #0 'number.label :=
+}
+FUNCTION {forward.pass}
+{ last.label label =
+    { last.extra.num #1 + 'last.extra.num :=
+      last.extra.num int.to.chr$ 'extra.label :=
+    }
+    { "a" chr.to.int$ 'last.extra.num :=
+      "" 'extra.label :=
+      label 'last.label :=
+    }
+  if$
+  number.label #1 + 'number.label :=
+}
+FUNCTION {reverse.pass}
+{ next.extra "b" =
+    { "a" 'extra.label := }
+    'skip$
+  if$
+  extra.label 'next.extra :=
+  extra.label
+  duplicate$ empty$
+    'skip$
+    { "{\natexlab{" swap$ * "}}" * }
+  if$
+  'extra.label :=
+  label extra.label * 'label :=
+}
+EXECUTE {initialize.extra.label.stuff}
+ITERATE {forward.pass}
+REVERSE {reverse.pass}
+FUNCTION {bib.sort.order}
+{ sort.label
+  "    "
+  *
+  year field.or.null sortify
+  *
+  "    "
+  *
+  title field.or.null
+  sort.format.title
+  *
+  #1 entry.max$ substring$
+  'sort.key$ :=
+}
+ITERATE {bib.sort.order}
+SORT
+FUNCTION {begin.bib}
+{ preamble$ empty$
+    'skip$
+    { preamble$ write$ newline$ }
+  if$
+  "\begin{thebibliography}{" number.label int.to.str$ * "}" *
+  write$ newline$
+  "\providecommand{\natexlab}[1]{#1}"
+  write$ newline$
+%  "\providecommand{\url}[1]{\texttt{#1}}"
+%  write$ newline$
+%  "\providecommand{\urlprefix}{URL }"
+%  write$ newline$
+%  "\expandafter\ifx\csname urlstyle\endcsname\relax"
+%  write$ newline$
+%  "  \providecommand{\doi}[1]{doi:\discretionary{}{}{}#1}\else"
+%  write$ newline$
+%  "  \providecommand{\doi}{doi:\discretionary{}{}{}\begingroup \urlstyle{rm}\Url}\fi"
+%  write$ newline$
+%  "\providecommand{\eprint}[2][]{\url{#2}}"
+%  write$ newline$
+}
+EXECUTE {begin.bib}
+EXECUTE {init.state.consts}
+ITERATE {call.type$}
+FUNCTION {end.bib}
+{ newline$
+  "\end{thebibliography}" write$ newline$
+}
+EXECUTE {end.bib}
+%% End of customized bst file
+%%
+%% End of file `ametsoc7.bst'.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/annex_D.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/annex_D.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/annex_D.tex	(revision 14097)
@@ -0,0 +1,207 @@
+\documentclass[../main/NEMO_manual]{subfiles}
+
+\begin{document}
+% ================================================================
+% Appendix D Coding Rules
+% ================================================================
+\chapter{Coding Rules}
+\label{apdx:D}
+
+\minitoc
+
+\newpage
+
+A "model life" is more than ten years.
+Its software, composed of a few hundred modules, is used by many people who are scientists or students and
+do not necessarily know every aspect of computing very well.
+Moreover, a well thought-out program is easier to read and understand, less difficult to modify,
+produces fewer bugs and is easier to maintain.
+Therefore, it is essential that the model development follows some rules:
+
+- well planned and designed
+
+- well written
+
+- well documented (both on- and off-line)
+
+- maintainable
+
+- easily portable
+
+- flexible.
+
+To satisfy part of these aims, \NEMO\ is written with a coding standard which is close to the ECMWF rules,
+named DOCTOR \citep{gibson_rpt86}. 
+These rules present some advantages like:
+
+- to provide a well presented program
+
+- to use rules for variable names which allow recognition of their type
+(integer, real, parameter, local or shared variables, etc. ). 
+
+This facilitates both the understanding and the debugging of an algorithm.
+
+% ================================================================
+% The program structure
+% ================================================================
+\section{Program structure}
+\label{sec:D_structure}
+
+Each program begins with a set of headline comments containing:
+
+- the program title
+
+- the purpose of the routine
+
+- the method and algorithms used
+
+- the detail of input and output interfaces
+
+- the external routines and functions used (if they exist)
+
+- references (if they exist)
+
+- the author name(s), the date of creation and any updates.
+
+- Each program is split into several well separated sections and
+sub-sections with an underlined title and specific labelled statements.
+
+- A program has not more than 200 to 300 lines.
+
+A template of a module style can be found on the NEMO depository in the following file:
+NEMO/OPA\_SRC/module\_example.
+% ================================================================
+% Coding conventions
+% ================================================================
+\section{Coding conventions}
+\label{sec:D_coding}
+
+- Use of the universal language \fninety, and try to avoid obsolescent features like statement functions,
+do not use GO TO and EQUIVALENCE statements.
+
+- A continuation line begins with the character {\&} indented by three spaces compared to the previous line,
+while the previous line ended with the character {\&}.
+
+- All the variables must be declared.
+The code is usually compiled with implicit none.
+ 
+- Never use continuation lines in the declaration of a variable.
+When searching a variable in the code through a \textit{grep} command, the declaration line will be found.
+
+- In the declaration of a PUBLIC variable, the comment part at the end of the line should start with
+the two characters "\verb?!:?".
+The following UNIX command, \\
+\verb?grep var_name *90 \ grep \!: ? \\
+will display the module name and the line where the var\_name declaration is.
+
+- Always use a three spaces indentation in DO loop, CASE, or IF-ELSEIF-ELSE-ENDIF statements.
+
+- use a space after a comma, except when it appears to separate the indices of an array.
+
+- use call to ctl\_stop routine instead of just a STOP.
+
+\newpage
+
+% ================================================================
+% Naming Conventions
+% ================================================================
+\section{Naming conventions}
+\label{sec:D_naming}
+
+The purpose of the naming conventions is to use prefix letters to classify model variables.
+These conventions allow the variable type to be easily known and rapidly identified.
+The naming conventions are summarised in the Table below:
+
+
+%--------------------------------------------------TABLE--------------------------------------------------
+\begin{table}[htbp]
+  \label{tab:VarName}
+  \begin{center}
+    \begin{tabular}{|p{45pt}|p{35pt}|p{45pt}|p{40pt}|p{40pt}|p{40pt}|p{40pt}|p{40pt}|}
+      \hline
+      Type \par / Status
+      & integer
+      & real
+      & logical
+      & character
+      & structure
+      & double \par precision
+      & complex \\
+      \hline
+      public  \par or  \par module variable
+      & \textbf{m n} \par \textit{but not} \par \textbf{nn\_ np\_}
+      & \textbf{a b e f g h o q r} \par \textbf{t} \textit{to} \textbf{x} \par but not \par \textbf{fs rn\_}
+      & \textbf{l} \par \textit{but not} \par \textbf{lp ld} \par \textbf{ ll ln\_}
+      & \textbf{c} \par \textit{but not} \par \textbf{cp cd} \par \textbf{cl cn\_}
+      & \textbf{s} \par \textit{but not} \par \textbf{sd sd} \par \textbf{sl sn\_}
+      & \textbf{d} \par \textit{but not} \par \textbf{dp dd} \par \textbf{dl dn\_}
+      & \textbf{y} \par \textit{but not} \par \textbf{yp yd} \par \textbf{yl yn} \\
+      \hline
+      dummy \par argument
+      & \textbf{k} \par \textit{but not} \par \textbf{kf}
+      & \textbf{p} \par \textit{but not} \par \textbf{pp pf}
+      & \textbf{ld}
+      & \textbf{cd}
+      & \textbf{sd}
+      & \textbf{dd}
+      & \textbf{yd} \\
+      \hline
+      local \par variable
+      & \textbf{i}
+      & \textbf{z}
+      & \textbf{ll}
+      & \textbf{cl}
+      & \textbf{sl}
+      & \textbf{dl}
+      & \textbf{yl} \\
+      \hline
+      loop \par control
+      & \textbf{j} \par \textit{but not} \par \textbf{jp} &&&&&& \\
+      \hline
+      parameter
+      & \textbf{jp np\_}
+      & \textbf{pp}
+      & \textbf{lp}
+      & \textbf{cp}
+      & \textbf{sp}
+      & \textbf{dp}
+      & \textbf{yp} \\
+      \hline
+      namelist
+      & \textbf{nn\_}
+      & \textbf{rn\_}
+      & \textbf{ln\_}
+      & \textbf{cn\_}
+      & \textbf{sn\_}
+      & \textbf{dn\_}
+      & \textbf{yn\_}
+      \\
+      \hline
+      CPP \par macro
+      & \textbf{kf}
+      & \textbf{fs} \par &&&&& \\
+      \hline
+    \end{tabular}
+    \label{tab:tab1}
+  \end{center}
+\end{table}
+%--------------------------------------------------------------------------------------------------------------
+
+N.B. Parameter here, in not only parameter in the \fortran acceptation,
+it is also used for code variables that are read in namelist and should never been modified during a simulation. 
+It is the case, for example, for the size of a domain (jpi,jpj,jpk).
+
+\newpage
+
+% ================================================================
+% The program structure
+% ================================================================
+%\section{Program structure}
+%\label{sec:Apdx_D_structure}
+
+%To be done....
+\biblio
+
+\pindex
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/coding_rules.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/coding_rules.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/coding_rules.tex	(revision 14097)
@@ -0,0 +1,844 @@
+
+\chapter{Coding Rules}
+\label{apdx:CODING}
+
+\chaptertoc
+
+\newpage
+
+A "model life" is more than ten years.
+Its software, composed of a few hundred modules, is used by many people who are scientists or students and
+do not necessarily know every aspect of computing very well.
+Moreover, a well thought-out program is easier to read and understand, less difficult to modify,
+produces fewer bugs and is easier to maintain.
+Therefore, it is essential that the model development follows some rules:
+
+\begin{itemize}
+\item well planned and designed
+\item well written
+\item well documented (both on- and off-line)
+\item maintainable
+\item easily portable
+\item flexible.
+\end{itemize}
+
+To satisfy part of these aims, \NEMO\ is written with a coding standard which is close to the ECMWF rules,
+named DOCTOR \citep{gibson_rpt86}.
+These rules present some advantages like:
+
+\begin{itemize}
+\item to provide a well presented program
+\item to use rules for variable names which allow recognition of their type 	(integer, real, parameter, local or shared variables, etc. ).
+\end{itemize}
+
+This facilitates both the understanding and the debugging of an algorithm.
+
+\section{Introduction}
+
+This document describes conventions used in \NEMO\ coding and suggested for its development.
+The objectives are to offer a guide to all readers of the \NEMO\ code, and to facilitate the work of
+all the developers, including the validation of their developments, and
+eventually the implementation of these developments within the \NEMO\ platform.
+
+A first approach of these rules can be found in the code in \path{./src/OCE/module_example} where
+all the basics coding conventions are illustrated.
+More details can be found below.
+
+This work is based on the coding conventions in use for the Community Climate System Model
+\footnote {\href{http://www.cesm.ucar.edu/working_groups/Software/dev_guide/dev_guide/node7.html}{UCAR conventions}},
+the previous version of this document (``FORTRAN coding standard in the OPA System'') and
+the expertise of the \NEMO\ System Team.
+After a general overview below, this document will describe:
+
+\begin{itemize}
+\item The style rules, $i.e.$ the syntax, appearance and naming conventions chosen to improve readability of the code;
+\item The content rules, $i.e.$ the conventions to improve the reliability of the different parts of the code;
+\item The package rules to go a step further by improving the reliability of the whole and
+	interfaces between routines and modules.
+\end{itemize}
+
+\section{Overview and general conventions}
+
+\NEMO\ has 3 major components: ocean dynamics (\path{./src/OCE}), sea-ice (\path{./src/ICE}) and
+marine biogeochemistry (\path{./src/MBG}).
+%, linear-tangent and adjoint of the dynamics ($TAM$) each of them corresponding to a directory.
+In each directory, one will find some FORTRAN files and/or subdirectories, one per functionality of the code:
+\path{./src/OCE/BDY} (boundaries), \path{./src/OCE/DIA} (diagnostics), \path{./src/OCE/DOM} (domain),
+\path{./src/OCE/DYN} (dynamics), \path{./src/OCE/LDF} (lateral diffusion), etc... \\
+All name are chosen to be as self-explanatory as possible, in English, all prefixes are 3 digits. \\
+English is used for all variables names, comments, and documentation. \\
+Physical units are MKS. The only exception to this is the temperature, which is expressed in degrees Celsius,
+except in bulk formulae and part of SI$^3$ sea-ice model where it is in Kelvin.
+See \path{.src/OCE/DOM/phycst.F90} files for conversions.
+
+\section{Architecture}
+
+Within each directory, organisation of files is driven by orthogonality,
+$i.e.$ one functionality of the code is intended to be in one and only one directory, and
+one module and all its related routines are in one file.
+The functional modules are:
+
+\begin{itemize}
+\item \path{SBC}             surface module
+\item \path{IOM}             management of the I/O
+\item \path{NST}             interface to AGRIF (nesting model) for dynamics and biogeochemistry
+\item \path{OBC}, \path{BDY} management of structured and unstructured open boundaries
+\item \path{C1D}             1D (vertical) configuration for dynamics, sea-ice and biogeochemistry
+\item \path{OFF}             off-line module: passive tracer or biogeochemistry alone
+\item \path{...}
+\end{itemize}
+
+For example, the file \textit{domain.F90} contains the module \texttt{domain} and all the subroutines related to
+this module (\texttt{dom\_init, dom\_nam, dom\_ctl}).
+
+\section{Style rules}
+
+\subsection{Argument list format}
+
+Routine argument lists will contain a maximum 5 variables per line,
+whilst continuation lines can be used.
+This applies both to the calling routine and the dummy argument list in the routine being called.
+The purpose is to simplify matching up the arguments between caller and callee.
+
+\begin{forlines}
+SUBROUTINE tra_adv_eiv( kt, pun, pvn, pwn )
+
+      CALL tra_adv_eiv( kt, zun, zvn, zwn )
+\end{forlines}
+
+\subsection{Array syntax}
+
+Except for long loops (see below), array notation should be used if possible.
+To improve readability the array shape must be shown in brackets, $e.g.$:
+
+\begin{forlines}
+onedarraya(:)   = onedarrayb(:) + onedarrayc(:)
+twodarray (:,:) = scalar * anothertwodarray(:,:)
+\end{forlines}
+
+When accessing sections of arrays, for example in finite difference equations,
+do so by using the triplet notation on the full array, $e.g.$:
+
+\begin{forlines}
+twodarray(:,2:len2) =   scalar                      &
+   &                  * ( twodarray2(:,1:len2-1 )   &
+   &                  -   twodarray2(:,2:len2 ) )
+\end{forlines}
+
+For long, complicated loops, explicitly indexed loops should be preferred.
+In general when using this syntax, the order of the loops indices should reflect the following scheme
+(for best usage of data locality):
+
+\begin{forlines}
+DO jk = 1, jpk
+   DO jj = 1, jpj
+      DO ji = 1, jpi
+         threedarray(ji,jj,jk) = ...
+      END DO
+   END DO
+END DO
+\end{forlines}
+
+\subsection{Case}
+
+All FORTRAN keywords are in capital: \forcode{DIMENSION}, \forcode{WRITE}, \forcode{DO}, \forcode{END DO},
+\forcode{NAMELIST}, ... All other parts of the \NEMO\ code will be written in lower case.
+
+\subsection{Comments}
+
+Comments in the code are useful when reading the code and changing or developing it. \\
+The full documentation and detailed explanations are to be added in the reference manual
+(TeX files, aside from the code itself). \\
+In the code, the comments should explain variable content and describe each computational step. \\
+Comments in the header start with ``!!''.
+For more details on the content of the headers, see Content rules/Headers in this document. \\
+Comments in the code start with ``!''. \\
+All comments are indented (3, 6, or 9 blank spaces). \\
+Short comments may be included on the same line as executable code, and an additional line can be used with
+proper alignment.
+For example:
+
+\begin{forlines}
+zx = zx *zzy   ! Describe what is going on and if it is
+!              ! too long use another ! for proper
+!              ! alignment with automatic indentation
+\end{forlines}
+
+More in-depth comments should be written in the form:
+
+\begin{forlines}
+   !  Check of some namelist values
+\end{forlines}
+
+or
+
+\begin{forlines}
+!
+!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!     !  Bottom boundary condition on tke
+!     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!
+\end{forlines}
+
+Key features of this style are
+
+\begin{enumerate}
+\item it starts with a "!" in the column required for proper indentation,
+\item the text is offset above and below by a blank line or a content line built for underlying.
+\end{enumerate}
+
+\subsection{Continuation lines}
+
+Continuation lines can be used with precise alignment for readability. For example:
+
+\begin{forlines}
+avmu(ji,jj,jk) =   avmu(ji,jj,jk) * ( un(ji,jj,jk-1) - un(ji,jj,jk) )   &
+   &                              * ( ub(ji,jj,jk-1) - ub(ji,jj,jk) )   &
+   &             / (   fse3uw_n(ji,jj,jk)                               &
+   &                 * fse3uw_b(ji,jj,jk) )
+\end{forlines}
+
+Code lines, which are continuation lines of assignment statements, must begin to the right of the column of
+the assignment operator.
+Due to the possibility of automatic indentation in some editor (emacs for example),
+use a ``\&'' as first character of the continuing lines to maintain the alignment.
+
+\subsection{Declaration of arguments and local variables}
+
+In a routine, input arguments and local variables are declared 1 per line,
+with a comment field on the same line as the declaration.
+Multiple comment lines describing a single variable are acceptable if needed.
+For example:
+
+\begin{forlines}
+INTEGER             ::   kstp   ! ocean time-step index
+\end{forlines}
+
+\subsection{F90 Standard}
+
+\NEMO\ software adheres to the \fninety language standard and does not rely on any specific language or
+vendor extensions.
+
+\subsection{Free-Form Source}
+
+Free-form source will be used.
+The F90/95 standard allows lines of up to 132 characters, but a self-imposed limit of 80 should enhance readability,
+or print source files with two columns per page.
+Multi-line comments that extend to column 100 are unacceptable.
+
+\subsection{Indentation}
+
+Code as well as comment lines within loops, if-blocks, continuation lines, \forcode{MODULE} or
+\forcode{SUBROUTINE} statements will be indented 3 characters for readability
+(except for \forcode{CONTAINS} that remains at first column).
+
+\begin{forlines}
+MODULE mod1
+   REAL(wp) xx
+CONTAINS
+   SUBROUTINE sub76( px, py, pz, pw, pa,   &
+      &              pb, pc, pd, pe          )
+      <instruction>
+   END SUBROUTINE sub76
+END MODULE mod1
+\end{forlines}
+
+\subsection{Loops}
+
+Loops, if explicit, should be structured with the do-end do construct as opposed to numbered loops.
+Nevertheless non-numeric labels can be used for a big iterative loop of a recursive algorithm.
+In the case of a long loop, a self-descriptive label can be used ($i.e.$ not just a number).
+
+\subsection{Naming Conventions: files}
+
+A file containing a module will have the same name as the module it contains
+(because dependency rules used by "make" programs are based on file names).
+\footnote{
+  For example, if routine A "\forcode{USE}"s module B, then "make" must be told of the dependency relation which
+  requires B to be compiled before A.
+  If one can assume that module B resides in file B.o,
+  building a tool to generate this dependency rule ($e.g.$ A.o: B.o) is quite simple.
+  Put another way, it is difficult (to say nothing of CPU-intensive) to search an entire source tree to
+  find the file in which module B resides for each routine or module which "\forcode{USE}"s B.
+}
+
+\subsection{Naming Conventions: modules}
+
+Use a meaningful English name and the ``3 letters'' naming convention:
+first 3 letters for the code section, and last 3 to describe the module.
+For example, zdftke, where ``zdf'' stands for vertical diffusion, and ``tke'' for turbulent kinetic energy. \\
+Note that by implication multiple modules are not allowed in a single file.
+The use of common blocks is deprecated in \fortran 90 and their use in \NEMO\ is strongly discouraged.
+Modules are a better way to declare static data.
+Among the advantages of modules is the ability to freely mix data of various types, and
+to limit access to contained variables through the use of the \forcode{ONLY} and \forcode{PRIVATE} attributes.
+
+\subsection{Naming Conventions: variables}
+
+All variable should be named as explicitly as possible in English.
+The naming convention concerns prefix letters of these name, in order to identify the variable type and status. \\
+Never use a \fortran keyword as a routine or variable name. \\
+The table below lists the starting letter(s) to be used for variable naming, depending on their type and status:
+%--------------------------------------------------TABLE--------------------------------------------------
+\begin{table}[htbp]
+  \begin{center}
+    \begin{tabular}{|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|p{50pt}|}
+      \hline
+      Type \par / Status                                                                          &
+      integer                                                                                     &
+      real                                                                                        &
+      logical                                                                                     &
+      character                                                                                   &
+      double \par precision                                                                       &
+      complex                                                                                     \\
+      \hline
+      public \par or \par module variable                                                         &
+      \textbf{m n} \par \textit{but not} \par \textbf{nn\_}                                       &
+      \textbf{a b e f g h o} \textbf{q} \textit{to} \textbf{x} \par but not \par \textbf{fs rn\_} &
+      \textbf{l} \par \textit{but not} \par \textbf{lp ld ll ln\_}                                &
+      \textbf{c} \par \textit{but not} \par \textbf{cp cd cl cn\_}                                &
+      \textbf{d} \par \textit{but not} \par \textbf{dp dd dl dn\_}                                &
+      \textbf{y} \par \textit{but not} \par \textbf{yp yd yl}                                     \\
+      \hline
+      dummy \par argument                                                                         &
+      \textbf{k} \par \textit{but not} \par \textbf{kf}                                           &
+      \textbf{p} \par \textit{but not} \par \textbf{pp pf}                                        &
+      \textbf{ld}                                                                                 &
+      \textbf{cd}                                                                                 &
+      \textbf{dd}                                                                                 &
+      \textbf{yd}                                                                                 \\
+      \hline
+      local \par variable                                                                         &
+      \textbf{i}                                                                                  &
+      \textbf{z}                                                                                  &
+      \textbf{ll}                                                                                 &
+      \textbf{cl}                                                                                 &
+      \textbf{cd}                                                                                 &
+      \textbf{yl}                                                                                 \\
+      \hline
+      loop \par control                                                                           &
+      \textbf{j} \par \textit{but not} \par \textbf{jp}                                           &
+                                                                                                  &
+                                                                                                  &
+                                                                                                  &
+                                                                                                  &
+                                                                                                  \\
+      \hline
+      parameter                                                                                   &
+      \textbf{jp}                                                                                 &
+      \textbf{pp}                                                                                 &
+      \textbf{lp}                                                                                 &
+      \textbf{cp}                                                                                 &
+      \textbf{dp}                                                                                 &
+      \textbf{yp}                                                                                 \\
+      \hline
+      namelist                                                                                    &
+      \textbf{nn\_}                                                                               &
+      \textbf{rn\_}                                                                               &
+      \textbf{ln\_}                                                                               &
+      \textbf{cn\_}                                                                               &
+      \textbf{dn\_}                                                                               &
+                                                                                                  \\
+      \hline
+      CPP \par macro                                                                              &
+      \textbf{kf}                                                                                 &
+      \textbf{sf}                                                                                 &
+                                                                                                  &
+                                                                                                  &
+                                                                                                  &
+                                                                                                  \\
+      \hline
+    \end{tabular}
+    \label{tab1}
+  \end{center}
+\end{table}
+%--------------------------------------------------------------------------------------------------------------
+
+\subsection{Operators}
+
+Use of the operators \texttt{<, >, <=, >=, ==, /=} is strongly recommended instead of their deprecated counterparts
+(\texttt{.lt., .gt., .le., .ge., .eq., .ne.}).
+The motivation is readability.
+In general use the notation: \\
+$<Blank><Operator><Blank>$
+
+\subsection{Pre processor}
+
+Where the use of a language pre-processor is required, it will be the C pre-processor (cpp). \\
+The cpp key is the main feature used, allowing to ignore some useless parts of the code at compilation step. \\
+The advantage is to reduce the memory use; the drawback is that compilation of this part of the code isn't checked. \\
+The cpp key feature should only be used for a few limited options, if it reduces the memory usage.
+In all cases, a logical variable and a FORTRAN \forcode{IF} should be preferred.
+When using a cpp key \textit{key\_optionname},
+a corresponding logical variable \textit{lk\_optionname} should be declared to
+allow FORTRAN \forcode{IF} tests in the code and
+a FORTRAN module with the same name ($i.e.$ \textit{optionname.F90}) should be defined.
+This module is the only place where a \``\#if defined'' command appears, selecting either the whole FORTRAN code or
+a dummy module.
+For example, the TKE vertical physics, the module name is \textit{zdftke.F90},
+the CPP key is \textit{key\_zdftke} and the associated logical is \textit{lk\_zdftke}.
+
+The following syntax:
+
+\begin{forlines}
+#if defined key_optionname
+!! Part of code conditionally compiled if cpp key key_optionname is active
+#endif
+\end{forlines}
+
+Is to be used rather than the \#ifdef abbreviate form since it may have conflicts with some Unix scripts.
+
+Tests on cpp keys included in \NEMO\ at compilation step:
+
+\begin{itemize}
+\item
+  The CPP keys used are compared to the previous list of cpp keys
+  (the compilation will stop if trying to specify a non-existing key)
+\item
+  If a change occurs in the CPP keys used for a given experiment, the whole compilation phase is done again.
+\end{itemize}
+
+\section{Content rules}
+
+\subsection{Configurations}
+
+The configuration defines the domain and the grid on which \NEMO\ is running.
+It may be useful to associate a CPP key and some variables to a given configuration, although
+the part of the code changed under each of those keys should be minimized.
+As an example, the "ORCA2" configuration (global ocean, 2 degrees grid size) is associated with
+the cpp key \texttt{key\_orca2} for which
+
+\begin{forlines}
+cp_cfg = "orca"
+jp_cfg = 2
+\end{forlines}
+
+\subsection{Constants}
+
+Physical constants ($e.g.$ $\pi$, gas constants) must never be hard-wired into the executable portion of a code.
+Instead, a mnemonically named variable or parameter should be set to the appropriate value,
+in the setup routine for the package.
+We realize than many parameterizations rely on empirically derived constants or fudge factors,
+which are not easy to name.
+In these cases it is not forbidden to leave such factors coded as "magic numbers" buried in executable code, but
+comments should be included referring to the source of the empirical formula.
+Hard-coded numbers should never be passed through argument lists.
+
+\subsection{Declaration for variables and constants}
+
+\subsubsection{Rules}
+
+Variables used as constants should be declared with attribute \forcode{PARAMETER} and
+used always without copying to local variables, in order to
+prevent from using different values for the same constant or changing it accidentally.
+
+\begin{itemize}
+\item
+  Usage of the \forcode{DIMENSION} statement or attribute is required in declaration statements
+\item
+  The ``::'' notation is quite useful to show that this program unit declaration part is written in
+  standard FORTRAN syntax, even if there are no attributes to clarify the declaration section.
+  Always use the notation $<$blank$>$::$<$three blanks$>$ to improve readability.
+\item
+  Declare the length of a character variable using the \forcode{CHARACTER} (len=xxx) syntax
+  \footnote {
+    The len specifier is important because it is possible to have several kinds for characters
+    ($e.g.$ Unicode using two bytes per character, or there might be a different kind for Japanese $e.g.$ NEC).
+  }
+\item
+  For all global data (in contrast to module data, that is all data that can be access by other module)
+  must be accompanied with a comment field on the same line
+  \footnote {
+    This allows a easy research of where and how a variable is declared using the unix command:
+    ``grep var *90 | grep !:''.
+  }.
+  For example:
+  \begin{forlines}
+  REAL(wp), DIMENSION(jpi,jpj,jpk) ::  ua   ! i-horizontal velocity (m/s)
+  \end{forlines}
+\end{itemize}
+
+\subsubsection{Implicit None}
+
+All subroutines and functions will include an \forcode{IMPLICIT NONE} statement.
+Thus all variables must be explicitly typed.
+It also allows the compiler to detect typographical errors in variable names.
+For modules, one \forcode{IMPLICIT NONE} statement in the modules definition section is needed.
+This also removes the need to have \forcode{IMPLICIT NONE} statements in
+any routines that are \forcode{CONTAINS}'ed in the module.
+Improper data initialisation is another common source of errors
+\footnote{
+  A variable could contain an initial value you did not expect.
+  This can happen for several reasons, $e.g.$ the variable has never been assigned a value, its value is outdated,
+  memory has been allocated for a pointer but you have forgotten to initialise the variable pointed to.
+}.
+To avoid problems, initialise variables as close as possible to where they are first used.
+
+\subsubsection{Attributes}
+
+\forcode{PRIVATE} / \forcode{PUBLIC}:
+All resources of a module are \forcode{PUBLIC} by default.
+A reason to store multiple routines and their data in a single module is that
+the scope of the data defined in the module can be limited to the routines which are in the same module.
+This is accomplished with the \forcode{PRIVATE} attribute. \\
+\forcode{INTENT}:
+All dummy arguments of a routine must include the \forcode{INTENT} clause in their declaration in order to
+improve control of variables in routine calls.
+
+\subsection{Headers}
+
+Prologues are not used in \NEMO\ for now, although it may become an interesting tool in combination with
+ProTeX auto documentation script in the future.
+Rules to code the headers and layout of a module or a routine are illustrated in the example module available with
+the code: \path{./src/OCE/module_example}
+
+\subsection{Interface blocks}
+
+Explicit interface blocks are required between routines if optional or keyword arguments are to be used.
+They also allow the compiler to check that the type, shape and number of arguments specified in the \forcode{CALL}
+are the same as those specified in the subprogram itself.
+FORTRAN 95 compilers can automatically provide explicit interface blocks for routines contained in a module.
+
+\subsection{I/O Error Conditions}
+
+I/O statements which need to check an error condition will use the \texttt{iostat=<integer variable>} construct
+instead of the outmoded \texttt{end=} and \forcode{err=}. \\
+Note that a 0 value means success, a positive value means an error has occurred, and
+a negative value means the end of record or end of file was encountered.
+
+\subsection{PRINT - ASCII output files}
+
+Output listing and errors are directed to \texttt{numout} logical unit =6 and
+produces a file called \textit{ocean.output} (use \texttt{ln\_prt} to have one output per process in MPP).
+Logical \texttt{lwp} variable allows for less verbose outputs.
+To output an error from a routine, one can use the following template:
+
+\begin{forlines}
+IF( nstop /= 0 .AND. lwp ) THEN   ! error print
+   WRITE(numout,cform_err)
+   WRITE(numout,*) nstop, ' error have been found'
+ENDIF
+\end{forlines}
+
+\subsection{Precision}
+
+Parameterizations should not rely on vendor-supplied flags to supply a default floating point precision or
+integer size.
+The F95 \forcode{KIND} feature should be used instead.
+In order to improve portability between 32 and 64 bit platforms,
+it is necessary to make use of kinds by using a specific module \path{./src/OCE/par_kind.F90}
+declaring the "kind definitions" to obtain the required numerical precision and range as well as
+the size of \forcode{INTEGER}.
+It should be noted that numerical constants need to have a suffix of \texttt{\_kindvalue} to
+have the according size. \\
+Thus \forcode{wp} being the "working precision" as declared in \path{./src/OCE/par_kind.F90},
+declaring real array \forcode{zpc} will take the form:
+
+\begin{forlines}
+REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zpc      ! power consumption
+\end{forlines}
+
+\subsection{Structures}
+
+The \forcode{TYPE} structure allowing to declare some variables is more often used in \NEMO,
+especially in the modules dealing with reading fields, or interfaces.
+For example:
+
+\begin{forlines}
+! Definition of a tracer as a structure
+TYPE PTRACER
+   CHARACTER(len = 20)  :: sname  ! short name
+   CHARACTER(len = 80 ) :: lname  ! long name
+   CHARACTER(len = 20 ) :: unit   ! unit
+   LOGICAL              :: lini   ! read in a file or not
+   LOGICAL              :: lsav   ! ouput the tracer or not
+END TYPE PTRACER
+
+TYPE(PTRACER) , DIMENSION(jptra) :: tracer
+\end{forlines}
+
+Missing rule on structure name??
+
+\section{Packages coding rules}
+
+\subsection{Bounds checking}
+
+\NEMO\ is able to run when an array bounds checking option is enabled
+(provided the cpp key \texttt{key\_vectopt\_loop} is not defined). \\
+Thus, constructs of the following form are disallowed:
+
+\begin{forlines}
+REAL(wp) :: arr(1)
+\end{forlines}
+
+where "arr" is an input argument into which the user wishes to index beyond 1.
+Use of the (*) construct in array dimensioning is forbidden also because
+it effectively disables array bounds checking.
+
+\subsection{Communication}
+
+A package should refer only to its own modules and subprograms and to those intrinsic functions included in
+the Fortran standard. \\
+All communication with the package will be through the argument list or namelist input.
+\footnote{
+  The point behind this rule is that packages should not have to know details of
+  the surrounding model data structures, or the names of variables outside of the package.
+  A notable exception to this rule is model resolution parameters.
+  The reason for the exception is to allow compile-time array sizing inside the package.
+  This is often important for efficiency.
+}
+
+\subsection{Error conditions}
+
+When an error condition occurs inside a package, a message describing what went wrong will be printed
+(see PRINT - ASCII output files).
+The name of the routine in which the error occurred must be included.
+It is acceptable to terminate execution within a package, but
+the developer may instead wish to return an error flag through the argument list,
+see \textit{stpctl.F90}.
+
+\subsection{Memory management}
+
+The main action is to identify and declare which arrays are \forcode{PUBLIC} and which are \forcode{PRIVATE}. \\
+As of version 3.3.1 of \NEMO, the use of static arrays (size fixed at compile time) has been deprecated.
+All module arrays are now declared \forcode{ALLOCATABLE} and
+allocated in either the \texttt{<module\_name>\_alloc()} or \texttt{<module\_name>\_init()} routines.
+The success or otherwise of each \forcode{ALLOCATE} must be checked using
+the \texttt{stat=<integer\ variable>} optional argument. \\
+
+In addition to arrays contained within modules, many routines in \NEMO\ require local, ``workspace'' arrays to
+hold the intermediate results of calculations.
+In previous versions of \NEMO, these arrays were declared in such a way as to be automatically allocated on
+the stack when the routine was called.
+An example of an automatic array is:
+
+\begin{forlines}
+SUBROUTINE sub(n)
+   REAL :: a(n)
+   ...
+END SUBROUTINE sub
+\end{forlines}
+
+The downside of this approach is that the program will crash if it runs out of stack space and
+the reason for the crash might not be obvious to the user.
+
+Therefore, as of version 3.3.1, the use of automatic arrays is deprecated.
+Instead, a new module, \textit{wrk\_nemo.F90}, has been introduced which
+contains 1-,2-,3- and 4-dimensional workspace arrays for use in subroutines.
+These workspace arrays should be used in preference to declaring new, local (allocatable) arrays whenever possible.
+The only exceptions to this are when workspace arrays with lower bounds other than 1 and/or
+with extent(s) greater than those in the \textit{wrk\_nemo.F90} module are required. \\
+
+The 2D, 3D and 4D workspace arrays in \textit{wrk\_nemo.F90} have extents \texttt{jpi}, \texttt{jpj},
+\texttt{jpk} and \texttt{jpts} ($x$, $y$, $z$ and tracers) in the first, second, third and fourth dimensions,
+respectively.
+The 1D arrays are allocated with extent MAX($jpi \times jpj, jpk \times jpj, jpi \times jpk$). \\
+
+The \forcode{REAL (KIND = wp)} workspace arrays in \textit{wrk\_nemo.F90}
+are named $e.g.$ \texttt{wrk\_1d\_1, wrk\_4d\_2} etc. and
+should be accessed by USE'ing the \textit{wrk\_nemo.F90} module.
+Since these arrays are available to any routine,
+some care must be taken that a given workspace array is not already being used somewhere up the call stack.
+To help with this, \textit{wrk\_nemo.F90} also contains some utility routines;
+\texttt{wrk\_in\_use()} and \texttt{wrk\_not\_released()}.
+The former first checks that the requested arrays are not already in use and then sets internal flags to show that
+they are now in use.
+The \texttt{wrk\_not\_released()} routine un-sets those internal flags.
+A subroutine using this functionality for two, 3D workspace arrays named \texttt{zwrk1} and
+\texttt{zwrk2} will look something like:
+
+\begin{forlines}
+SUBROUTINE sub()
+   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
+   USE wrk_nemo, ONLY: zwrk1 => wrk_3d_5, zwrk2 => wrk_3d_6
+   !
+   IF(wrk_in_use(3, 5,6)THEN
+      CALL ctl_stop('sub: requested workspace arrays unavailable.')
+      RETURN
+   END IF
+   ...
+   ...
+   IF(wrk_not_released(3, 5,6)THEN
+      CALL ctl_stop('sub: failed to release workspace arrays.')
+   END IF
+   !
+END SUBROUTINE sub
+\end{forlines}
+
+The first argument to each of the utility routines is the dimensionality of the required workspace (1--4).
+Following this there must be one or more integers identifying which workspaces are to be used/released.
+Note that, in the interests of keeping the code as simple as possible,
+there is no use of \forcode{POINTER}s etc. in the \textit{wrk\_nemo.F90} module.
+Therefore it is the responsibility of the developer to ensure that the arguments to \texttt{wrk\_in\_use()} and
+\texttt{wrk\_not\_released()} match the workspace arrays actually being used by the subroutine. \\
+
+If a workspace array is required that has extent(s) less than those of the arrays in
+the \textit{wrk\_nemo.F90} module then the advantages of implicit loops and bounds checking may be retained by
+defining a pointer to a sub-array as follows:
+
+\begin{forlines}
+SUBROUTINE sub()
+   USE wrk_nemo, ONLY: wrk_in_use, wrk_not_released
+   USE wrk_nemo, ONLY: wrk_3d_5
+   !
+   REAL(wp), DIMENSION(:,:,:), POINTER :: zwrk1
+   !
+   IF(wrk_in_use(3, 5)THEN
+      CALL ctl_stop('sub: requested workspace arrays unavailable.')
+      RETURN
+   END IF
+   !
+   zwrk1 => wrk_3d_5(1:10,1:10,1:10)
+   ...
+END SUBROUTINE sub
+\end{forlines}
+
+Here, instead of ``use associating'' the variable \texttt{zwrk1} with the array \texttt{wrk\_3d\_5}
+(as in the first example), it is explicitly declared as a pointer to a 3D array.
+It is then associated with a sub-array of \texttt{wrk\_3d\_5} once the call to
+\texttt{wrk\_in\_use()} has completed successfully.
+Note that in F95 (to which \NEMO\ conforms) it is not possible for either the upper or lower array bounds of
+the pointer object to differ from those of the target array. \\
+
+In addition to the \forcode{REAL (KIND = wp)} workspace arrays,
+\textit{wrk\_nemo.F90} also contains 2D integer arrays and 2D REAL arrays with extent (\texttt{jpi}, \texttt{jpk}),
+$i.e.$ $xz$.
+The utility routines for the integer workspaces are \texttt{iwrk\_in\_use()} and \texttt{iwrk\_not\_released()} while
+those for the $xz$ workspaces are \texttt{wrk\_in\_use\_xz()} and \texttt{wrk\_not\_released\_xz()}.
+
+Should a call to one of the \texttt{wrk\_in\_use()} family of utilities fail,
+an error message is printed along with a table showing which of the workspace arrays are currently in use.
+This should enable the developer to choose alternatives for use in the subroutine being worked on. \\
+
+When compiling \NEMO\ for production runs,
+the calls to {\texttt{wrk\_in\_use()} / \texttt{wrk\_not\_released()} can be reduced to stubs that just
+return \forcode{.false.} by setting the cpp key \texttt{key\_no\_workspace\_check}.
+These stubs may then be in-lined (and thus effectively removed altogether) by setting appropriate compiler flags
+($e.g.$ ``-finline'' for the Intel compiler or ``-Q'' for the IBM compiler).
+
+\subsection{Optimisation}
+
+Considering the new computer architecture, optimisation cannot be considered independently from the computer type.
+In \NEMO, portability is a priority, before any too specific optimisation.
+
+Some tools are available to help: for vector computers, \texttt{key\_vectopt\_loop} allows to unroll a loop
+
+\subsection{Package attribute: \forcode{PRIVATE}, \forcode{PUBLIC}, \forcode{USE}, \forcode{ONLY}}
+
+Module variables and routines should be encapsulated by using the \forcode{PRIVATE} attribute.
+What shall be used outside the module can be declared \forcode{PUBLIC} instead.
+Use \forcode{USE} with the \forcode{ONLY} attribute to specify which of the variables, type definitions etc...
+defined in a module are to be made available to the using routine.
+
+\subsection{Parallelism using MPI}
+
+\NEMO\ is written in order to be able to run on one processor, or on one or more using MPI
+($i.e.$ activating the cpp key $key\_mpp\_mpi$).
+The domain decomposition divides the global domain in cubes (see \NEMO\ reference manual).
+Whilst coding a new development, the MPI compatibility has to be taken in account
+(see \path{./src/LBC/lib_mpp.F90}) and should be tested.
+By default, the $x$-$z$ part of the decomposition is chosen to be as square as possible.
+However, this may be overriden by specifying the number of sub-domains in latitude and longitude in
+the \texttt{nammpp} section of the namelist file.
+
+\section{Features to be avoided}
+
+The code must follow the current standards of FORTRAN and ANSI C.
+In particular, the code should not produce any WARNING at compiling phase, so that
+users can be easily alerted of potential bugs when some appear in their new developments.
+Below is a list of features to avoid:
+\begin{itemize}
+\item \forcode{COMMON} block
+  (use the declaration part of \forcode{MODULE} instead)
+\item \forcode{EQUIVALENCE}
+  (use \forcode{POINTER} or derived data type instead to form data structure)
+\item Assigned and computed \forcode{GOTO}
+  (use the \forcode{CASE} construct instead)
+\item Arithmetic \forcode{IF} statement
+  (use the block \forcode{IF}, \forcode{ELSE}, \forcode{ELSEIF}, \forcode{ENDIF} or
+  \forcode{SELECT CASE} construct instead)
+\item Labelled \forcode{DO} construct
+  (use unlabelled \forcode{END DO} instead)
+\item \forcode{FORMAT} statement
+  (use character parameters or
+  explicit format- specifiers inside the \forcode{READ} or \forcode{WRITE} statement instead)
+\item \forcode{GOTO} and \forcode{CONTINUE} statements
+  (use \forcode{IF}, \forcode{CASE}, \forcode{DO WHILE}, \forcode{EXIT} or \forcode{CYCLE} statements or
+  a contained ?)
+\item \forcode{PAUSE}
+\item \forcode{ENTRY} statement: a sub-program must only have one entry point.
+\item \forcode{RETURN} is obsolete and so not necessary at the end of program units
+\item \forcode{FUNCTION} statement
+\item Avoid functions with side effects.
+  \footnote{
+    First, the code is easier to understand, if you can rely on
+    the rule that functions don't change their arguments.
+    Second, some compilers generate more efficient code for PURE functions
+    (in FORTRAN 95 there are the attributes PURE and ELEMENTAL), because
+    they can store the arguments in different places.
+    This is especially important on massive parallel and as well on vector machines.
+  }
+\item \forcode{DATA} and \forcode{BLOCK DATA}
+  (use initialisers)
+\end{itemize}
+
+%% Imported from introduction
+%%gm    To be put somewhere else ....
+%%nm    We should consider creating a glossary for all this kind of stuff (terms, acronyms and symbols)
+%%      http://en.wikibooks.org/wiki/LaTeX/Glossary
+%\noindent CPP keys and namelists are used as inputs to the code.
+
+%\noindent \index{CPP keys} CPP keys
+
+%Some CPP keys are implemented in the \fortran code to allow code selection at compiling step.
+%This selection of code at compilation time reduces the reliability of the whole platform since
+%it changes the code from one set of CPP keys to the other.
+%It is used only when the addition/suppression of the part of code highly changes the amount of memory at run time.
+%Usual coding looks like:
+
+%\begin{forlines}
+%#if defined key_option1
+%	! This part of the \fortran code will be active
+%	! only if key_option1 is activated at compiling step
+%#endif
+%\end{forlines}
+
+%\noindent \index{Namelist} Namelists
+
+%The namelist allows to input variables (character, logical, real and integer) into the code.
+%There is one namelist file for each component of \NEMO\ (dynamics, sea-ice, biogeochemistry...)
+%containing all the \fortran namelists needed.
+%The implementation in \NEMO\ uses a 2-step process.
+%For each \fortran namelist, two files are read:
+
+%\begin{enumerate}
+%\item
+%  A reference namelist (in \path{./cfgs/SHARED/namelist_ref}) is read first.
+%  This file contains all the namelist variables which are initialised to default values
+%\item
+%  A configuration namelist (in \path{./cfgs/CFG_NAME/EXP00/namelist_cfg}) is read aferwards.
+%  This file contains only the namelist variables which are changed from default values, and overwrites those.
+%\end{enumerate}
+%A template can be found in \path{NEMO/OPA_SRC/module.example}.
+%The effective namelist, taken in account during the run, is stored at execution time in
+%an \texttt{output\_namelist\_dyn} (or \texttt{\_ice} or \texttt{\_top}) file.
+%%gm  end
+
+%%nm: Add some words on the \NEMO\ dependencies
+%The model is implemented in \fninety, with preprocessing (C pre-processor).
+%It runs under UNIX.
+%It is optimized for vector computers and parallelised by domain decomposition with MPI.
+%All input and output is done in NetCDF (Network Common Data Format) with a optional direct access format for output.
+%To ensure the clarity and readability of the code it is necessary to follow coding rules.
+%The coding rules for OPA include conventions for naming variables,
+%with different starting letters for different types of variables (real, integer, parameter\ldots).
+%Those rules are briefly presented in \autoref{apdx:coding} and a more complete document is available .
+
+%The model is organized with a high internal modularity based on physics.
+%For example, each trend (\ie, a term in the RHS of the prognostic equation) for momentum and tracers
+%is computed in a dedicated module.
+%To make it easier for the user to find his way around the code, the module names follow a three-letter rule.
+%For example, \mdl{traldf} is a module related to the TRAcers equation, computing the Lateral DiFfussion.
+%The complete list of module names is presented in \autoref{apdx:coding}.      %====>>>> to be done !
+%Furthermore, modules are organized in a few directories that correspond to their category,
+%as indicated by the first three letters of their name (\autoref{tab:chapters}).
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/document.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/document.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/document.tex	(revision 14097)
@@ -0,0 +1,88 @@
+
+%% =================================================================================================
+%% Template structure for reference manuals
+%% =================================================================================================
+
+%% NEMO release version
+\def \version{4.0-HEAD}
+
+%% Preamble
+%% =================================================================================================
+
+%% Document layout
+\documentclass[fontsize = 10pt, twoside, abstract]{scrreprt}
+
+%% Load manual configuration
+\input{../../global/prologue}
+
+%% End of common preamble between main and sub-files
+%% Override custom cmds for full manual compilation
+\newcommand{\subinc}[1]{#1}
+\newcommand{\subexc}[1]{}
+
+\begin{document}
+
+\renewcommand{\subinc}[1]{}
+\renewcommand{\subexc}[1]{#1}
+
+
+%% Frontmatter
+%% =================================================================================================
+
+\pagenumbering{gobble}   %% Disable page numbering temporarily
+
+%% Title page
+\input{../../global/frontpage}
+
+%% Footer for introductory parts (no header by cleaning default)
+\ofoot[]{\engine\ Reference Manual} \ifoot[]{\pagemark}
+
+%% Information page (2nd page)
+\input{../../global/info_page}
+
+\listoffigures
+\listoflistings
+\listoftables
+
+\clearpage
+
+\pagenumbering{roman}
+\ofoot[]{\engine\ Reference Manual} \ifoot[]{\pagemark}
+
+\input{introduction}
+
+%% Table of Contents
+\tableofcontents
+
+\clearpage
+
+
+%% Mainmatter
+%% =================================================================================================
+
+%% Headings for document body
+\pagenumbering{arabic}
+\lohead{Chap.\ \thechapter\ \leftmark} \rehead{Sect.\ \thesection\ \rightmark}
+\ifoot[]{Page\ \pagemark\ of \pageref*{LastPage}}
+
+\include{chapters}
+
+
+%% Appendix
+%% =================================================================================================
+
+\appendix   %% Chapter numbering with letters by now
+\lohead{Apdx\ \thechapter\ \leftmark}
+\include{appendices}
+
+%% Append coding rules for every manual
+\input{../../global/coding_rules}
+
+
+%% Backmatter
+%% =================================================================================================
+
+%% Bibliography and indexes
+\input{../../global/epilogue}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/epilogue.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/epilogue.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/epilogue.tex	(revision 14097)
@@ -0,0 +1,20 @@
+
+\clearpage
+
+%% Bibliography
+\phantomsection
+\addcontentsline{toc}{chapter}{Bibliography}
+\lohead{Bibliography} \rehead{Bibliography}
+\bibliography{../main/bibliography}
+
+\clearpage
+
+%% Indexes
+\phantomsection
+\addcontentsline{toc}{chapter}{Indexes}
+\lohead{Indexes} \rehead{Indexes}
+\printindex[blocks]
+\printindex[keys]
+\printindex[modules]
+\printindex[parameters]
+\printindex[subroutines]
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/frontpage.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/frontpage.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/frontpage.tex	(revision 14097)
@@ -0,0 +1,67 @@
+
+\begin{titlepage}
+%  \newgeometry{hmargin = 1.5cm, vmargin = 3cm}
+  \setlength{\parindent}{0pt}
+
+  \begin{center}
+    \begin{minipage}{0.3\textwidth}
+      \includegraphics[height=1.5cm]{logos/NEMO_grey}
+    \end{minipage}\begin{minipage}{0.6\textwidth}
+      \begin{center}
+      \Large\slshape
+      \textbf{N}ucleus for \textbf{E}uropean \textbf{M}odelling of the \textbf{O}cean \\
+      \medskip
+      \hyperref[resources]{\textcolor{black}{
+          \faWordpress \hspace{0.75cm} \faCodeFork      \hspace{0.75cm}
+          \faGithub    \hspace{0.75cm} \faCloudDownload \hspace{0.75cm} \faEnvelope
+        }
+      }
+      \end{center}
+    \end{minipage}
+  \end{center}
+
+  \spacetop
+  \textcolor{white}{\fontsize{0.8cm}{0.8cm}\selectfont\textbf{\heading}}
+  \ifdef{\subheading}{
+    \medskip
+    \par
+    \textcolor{white}{\Huge \subheading}
+  }{}
+  \spacedown
+
+  \begin{center}
+    \LARGE Version \version\ -\ \today \\
+%    \medskip
+%    \href{http://doi.org/10.5281/zenodo.\zid}{ \includegraphics{badges/zenodo.\zid} }
+  \end{center}
+
+  \vfill
+
+  \begin{minipage}{\authorswidth}
+    \raggedleft
+    \input{authors}
+  \end{minipage}\hspace{15pt}\begin{minipage}{0.02\linewidth}
+    \rule{1pt}{\rulelenght}
+  \end{minipage}\hspace{ 5pt}\begin{minipage}{\abstractwidth}
+    \begin{abstract}
+      \input{abstract}
+    \end{abstract}
+  \end{minipage}
+
+  \vfill
+
+  \begin{center}
+    \Large
+    \href{http://www.cmcc.it          }{ \includegraphics[height=1cm]{logos/CMCC} } \hspace{0.25cm}
+    \href{http://www.cnrs.fr          }{ \includegraphics[height=1cm]{logos/CNRS} } \hspace{0.25cm}
+    \href{http://www.mercator-ocean.fr}{ \includegraphics[height=1cm]{logos/MOI}  } \hspace{0.25cm}
+    \href{http://www.metoffice.gov.uk }{ \includegraphics[height=1cm]{logos/UKMO} } \hspace{0.25cm}
+    \href{http://nerc.ukri.org        }{ \includegraphics[height=1cm]{logos/NERC} } \\
+    \medskip
+    \slshape
+    {C}ommunity \hspace{1.5em} {O}cean \hspace{1.5em} {M}odel \\
+  \end{center}
+
+\end{titlepage}
+
+\restoregeometry
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/highlighting.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/highlighting.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/highlighting.tex	(revision 14097)
@@ -0,0 +1,32 @@
+%% Syntax highlighting configuration
+%% ==============================================================================
+
+\usepackage[outputdir=../build, chapter, newfloat]{minted}
+
+%% Global highlighting style
+\definecolor{bg}{HTML}{f8f8f8}
+\usemintedstyle{emacs}
+\setminted{bgcolor=bg, fontsize=\scriptsize, breaklines}
+\setminted[xml]{style=borland} %% Specific per language
+
+%% Oneliner
+\newmint[forline]{fortran}{}   % \forline|...|
+\newmint[xmlline]{xml}{}       % \xmlline|...|
+\newmint[cmd]{console}{}       % \cmd|...|
+
+%% Multi-lines
+\newminted[forlines]{fortran}{}   % \begin{forlines}
+\newminted[xmllines]{xml}{}       % \begin{xmllines}
+\newminted[cmds]{console}{}       % \begin{cmds}
+\newminted[clines]{c}{}           % \begin{clines}
+
+%% File
+\newmintedfile[forfile]{fortran}{}
+
+%% Inline
+\newmintinline[forcode]{fortran}{bgcolor=, fontsize=auto}   % \forcode{...}
+\newmintinline[xmlcode]{xml}{    bgcolor=, fontsize=auto}   % \xmlcode{...}
+\newmintinline[snippet]{console}{bgcolor=, fontsize=auto}   % \snippet{...}
+
+%% Namelists inclusion
+\newcommand{\nlst}[1]{\forfile{../../../namelists/#1}}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.ist
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.ist	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.ist	(revision 14097)
@@ -0,0 +1,4 @@
+headings_flag 1
+heading_prefix "\\medskip\\hfill\\textnormal{"
+heading_suffix "}\\hfill\\smallskip\n"
+delim_0 "\\dotfill~"
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/index.tex	(revision 14097)
@@ -0,0 +1,25 @@
+
+\usepackage{imakeidx}
+
+%% Naming customization
+\renewcommand{\listingname}{namelist}
+\renewcommand{\listlistingname}{List of Namelists}
+
+%% Index entries (italic font for files, preformat for code)
+\newcommand{\hf}[1]{   \index{h90 files!#1}             \textit{#1.h90}          }
+\newcommand{\ifile}[1]{\index{Input NetCDF files!#1.nc} \textit{#1.nc}           }
+\newcommand{\jp}[1]{   \index{Model parameters!#1}      \texttt{#1}              }
+\newcommand{\key}[1]{  \index[keys]{#1@\texttt{\textbf{key\_#1}}} \texttt{\textbf{key\_#1}}}
+\newcommand{\mdl}[1]{  \index[modules]{#1@\textit{#1.F90}}        \textit{#1.F90}          }
+\newcommand{\nam}[2]{  \index[blocks]{#1@\texttt{\&nam#2}}        \forcode{&nam#1} (\autoref{lst:nam#1})}
+\newcommand{\np}[3][]{ \index[parameters]{#3@\texttt{#3}}         \forcode{#2#1}           }
+\newcommand{\rou}[1]{  \index[subroutines]{#1@\texttt{#1}}        \texttt{#1}              }
+
+
+\indexsetup{toclevel=section, othercode=\small}
+
+\makeindex[intoc=true, name=blocks     , title=Namelist blocks      , columns=3]
+\makeindex[intoc=true, name=keys       , title=CPP keys                        ]
+\makeindex[intoc=true, name=modules    , title=\fortran\ modules    , columns=3]
+\makeindex[intoc=true, name=parameters , title=Namelist parameters  , columns=3]
+\makeindex[intoc=true, name=subroutines, title=\fortran\ subroutines           ]
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/info_page.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/info_page.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/info_page.tex	(revision 14097)
@@ -0,0 +1,76 @@
+
+\thispagestyle{plain}
+
+%% ================================================================
+%% Disclaimer
+%% ================================================================
+\subsubsection*{Disclaimer}
+
+Like all components of the modelling framework,
+the \engine\ core engine is developed under the \href{http://www.cecill.info}{CECILL license},
+which is a French adaptation of the GNU GPL (\textbf{G}eneral \textbf{P}ublic \textbf{L}icense).
+Anyone may use it freely for research purposes, and is encouraged to
+communicate back to the development team its own developments and improvements.
+
+The model and the present document have been made available as a service to the community.
+We cannot certify that the code and its manual are free of errors.
+Bugs are inevitable and some have undoubtedly survived the testing phase.
+Users are encouraged to bring them to our attention.
+
+The authors assume no responsibility for problems, errors, or incorrect usage of \NEMO.
+
+%% ================================================================
+%% External resources
+%% ================================================================
+\subsubsection*{Other resources}
+\label{resources}
+
+Additional information can be found on:
+\begin{itemize}
+\item \faWordpress\ the \href{http://www.nemo-ocean.eu}{website} of the project detailing several
+  associated applications and an exhaustive users bibliography
+\item \faCodeFork\ the \href{http://forge.ipsl.jussieu.fr/nemo}{development platform} of
+  the model with the code repository for the shared reference and some main resources
+  (wiki, ticket system, forums, \ldots) \\
+  \faGithub\ the \href{http://github.com/NEMO-ocean/NEMO-examples}
+  {repository of the demonstration cases} for research or training
+\item \faCloudDownload\ the \href{http://zenodo.org/communities/nemo-ocean}{online archive}
+  delivering the publications issued by the consortium (manuals, reports, datasets, \ldots)
+\item \faEnvelope\ two mailing lists:
+  the \href{http://listes.ipsl.fr/sympa/info/nemo-newsletter}{newsletter} for
+  top-down communications from the project
+  (announcements, calls, job opportunities, \ldots)
+  and the \href{http://listes.ipsl.fr/sympa/info/nemo-forge}{forge updates}
+  (commits, tickets and forums)
+\end{itemize}
+
+%% ================================================================
+%% Citation
+%% ================================================================
+\subsubsection*{Citation}
+
+Reference for papers and other publications is as follows:
+
+\medskip
+
+\begin{sloppypar}
+  ``{\bfseries \heading}\ifdef{\subheading}{ -- \subheading}{}'',
+  {\em Scientific Notes of Climate Modelling Center}, \textbf{\ipslnum} --- ISSN 1288-1619,
+  Institut Pierre-Simon Laplace (IPSL),
+  \href{https://doi.org/10.5281/zenodo.\zid}{doi:10.5281/zenodo.\zid}
+\end{sloppypar}
+
+\begin{figure}[b]
+  \begin{minipage}[c]{0.7\textwidth}
+    \small
+    \ttfamily{
+      Scientific Notes of Climate Modelling Center \\
+      ISSN 1288-1619                               \\
+      Institut Pierre-Simon Laplace (IPSL)
+    }
+  \end{minipage}
+  \hfill
+  \begin{minipage}[c]{0.25\textwidth}
+    \href{http://www.cmc.ipsl.fr}{\includegraphics[width=\textwidth]{logos/IPSL_upright}}
+  \end{minipage}
+\end{figure}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/latexmk.pl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/latexmk.pl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/latexmk.pl	(revision 14097)
@@ -0,0 +1,13 @@
+
+## Defaults
+$do_cd    = 1;   ## Change to the directory of the main source file
+$silent   = 1;   ## Less verbosity
+
+## Use of 'build' relative directory
+$ENV{'openout_any'}='a';
+$out_dir = '../build';
+
+## Global option
+set_tex_cmds( '-shell-escape' );
+
+$makeindex = "makeindex %O -s ../../global/index -o $out_dir/%D $out_dir/%S";
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/new_cmds.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/new_cmds.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/new_cmds.tex	(revision 14097)
@@ -0,0 +1,69 @@
+%% Global custom commands: \newcommand{<name>}[<args>][<first argument value>]{<code>}
+%% ==============================================================================
+
+%% Same slanted font for NEMO and its core engines
+\newcommand{\NEMO  }{\textsl{NEMO}}
+\newcommand{\OPA   }{\textsl{OPA}}
+\newcommand{\SIcube}{\textsl{SI$^3$}}
+\newcommand{\TOP   }{\textsl{TOP}}
+\newcommand{\PISCES}{\textsl{PISCES}}
+\newcommand{\NEMOVAR}{\textsl{NEMOVAR}}
+
+%% Links for external components
+\newcommand{\AGRIF}{\href{http://agrif.imag.fr}{AGRIF}}
+\newcommand{\CICE }{\href{http://github.com/CICE-Consortium/CICE}{CICE}}
+\newcommand{\OASIS}{\href{http://portal.enes.org/oasis}{OASIS}}
+\newcommand{\XIOS }{\href{http://forge.ipsl.jussieu.fr/ioserver}{XIOS}}
+
+%% Fortran in small capitals
+\newcommand{\fortran}{\textsc{Fortran}}
+\newcommand{\fninety}{\textsc{Fortran 90}}
+
+%% Common aliases
+\renewcommand{\deg}[1][]{\ensuremath{^{\circ}#1}}
+\newcommand{\zstar }{\ensuremath{z^\star}}
+\newcommand{\sstar }{\ensuremath{s^\star}}
+\newcommand{\ztilde}{\ensuremath{\tilde z}}
+\newcommand{\stilde}{\ensuremath{\tilde s}}
+\newcommand{\ie}{\ensuremath{i.e.}}
+\newcommand{\eg}{\ensuremath{e.g.}}
+
+%% Inline maths
+\newcommand{\fractext}[2]{\textstyle \frac{#1}{#2}}
+\newcommand{\rdt}{\Delta t}
+
+%% Gurvan's comments
+\newcommand{\cmtgm}[1]{}
+
+%% Maths
+\newcommand{\lt}{\left}
+\newcommand{\rt}{\right}
+\newcommand{\vect}[1]{\ensuremath{ \mathbf{#1} }}
+\newcommand{\pd}[2][]{\ensuremath{\frac{\partial #1}{\partial #2}}}
+
+%% Convert chapter/section headings to lowercase
+\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
+\renewcommand{\sectionmark}[1]{\markright{#1}{}}
+
+%% Retrieve month name
+\renewcommand{\today}{
+  \ifcase \month\or January\or February\or March\or
+                    April\or   May\or      June\or
+                    July\or    August\or   September\or
+                    October\or November\or December
+  \fi, \number \year
+}
+
+%% Link to orcid profile
+\newcommand{\orcid}[1]{\href{http://orcid.org/#1}{\textcolor{orcidcolor}\aiOrcidSquare}}
+
+%% Workaround for \listoffigures
+\DeclareRobustCommand{\triad}[6][]{\ensuremath{ {}_{#2}^{#3} { \mathbb{#4}_{#1} }_{#5}^{\,#6} }}
+
+%% New command for ToC
+\newcommand{\chaptertoc}[1][Table of contents]{%
+  \thispagestyle{empty}
+  \etocsettocstyle{\addsec*{#1}}{}%
+  \localtableofcontents%
+  \vfill
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/packages.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/packages.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/packages.tex	(revision 14097)
@@ -0,0 +1,44 @@
+
+%% LaTeX packages in use
+%% ==============================================================================
+
+%% 'hyperref' pkg is loaded at the end of the preamble for higher compatibility
+
+%% KOMA-script
+\usepackage[footsepline=0.25pt, headsepline=0.25pt]{scrlayer-scrpage}
+
+%% customization (layout, header/footer styles & contents, background)
+%\usepackage{draftwatermark}
+\usepackage[margin = 2cm]{geometry}
+\usepackage[pages = some]{background}   %% 'some' for title page
+\usepackage[Bjornstrup]{fncychap}
+
+%% Fonts
+\usepackage{fontspec}
+%% Issue with fontawesome pkg: path to FontAwesome.otf has to be hard-coded
+\defaultfontfeatures{
+    Path = /usr/local/texlive/2019/texmf-dist/fonts/opentype/public/fontawesome/
+}
+\usepackage{academicons, fontawesome, newtxtext}
+
+%% Formatting
+\usepackage[inline]{enumitem}
+\usepackage{etoc, tabularx, xcolor}
+
+%% Graphics
+\usepackage{caption, graphicx, grffile}
+
+%% Labels
+\usepackage{lastpage, natbib}
+
+%% Mathematics
+\usepackage{amsmath, amssymb, mathtools}
+
+%% Versatility
+\usepackage{subfiles}
+
+%% Configuration
+\graphicspath{ {../../../} {../figures/} }
+
+%% Missing utmr8a font
+\usepackage{times}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/prologue.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/prologue.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/prologue.tex	(revision 14097)
@@ -0,0 +1,25 @@
+
+%% Specific configuration
+\input{../main/settings}
+
+%% Global configuration
+\input{../../global/packages}
+\input{../../global/highlighting}
+\input{../../global/index}
+\input{../../global/styles}
+\input{../../global/new_cmds}
+%\input{../../global/todonotes}
+
+%% Load hyperref at the end of the preamble to make it work with other pkgs
+\usepackage{hyperref}   %% links
+\hypersetup{
+  colorlinks,
+  citecolor = manualcolor, linkcolor = manualcolor, urlcolor = manualcolor,
+  final   %% Links even in draft mode
+}
+
+%% `\autoref` uncapitalization
+\renewcommand{\appendixautorefname}{appendix}
+\renewcommand{\equationautorefname}{equation}
+\renewcommand{\figureautorefname}{figure}
+\renewcommand{\tableautorefname}{table}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/styles.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/styles.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/styles.tex	(revision 14097)
@@ -0,0 +1,85 @@
+
+%% Styles
+%% ==============================================================================
+
+%% Colors
+\setmanualcolor
+\colorlet{manualcolorshaded}{manualcolor!60}
+\definecolor{orcidcolor}{HTML}{A6CE39}
+
+%% Page layout
+\pagestyle{scrheadings}
+\addtokomafont{pagehead}{  \sffamily              }
+\addtokomafont{pagefoot}{  \sffamily \footnotesize}
+\addtokomafont{pagenumber}{\sffamily \slshape     }
+\addtokomafont{chapter}{\color{white}}
+\ohead{} \ofoot{}   %% Clear defaults
+
+%% Caption
+\captionsetup{font = footnotesize, justification = justified}
+
+%% Footnote
+\renewcommand{\thefootnote}{\fnsymbol{footnote}}
+
+%% Bibliography
+\bibliographystyle{../../global/ametsoc}
+\renewcommand{\bibfont}{\small}
+\renewcommand{\bibpreamble }{\begin{multicols}{2}}
+\renewcommand{\bibpostamble}{  \end{multicols}   }
+
+%% Catcodes
+\makeatletter
+
+%% Prevent error with tikz and namelist inclusion
+\global\let\tikz@ensure@dollar@catcode=\relax
+
+%% First page
+\backgroundsetup{
+  firstpage = true,
+  scale = 1, angle = 0, opacity = 1,
+  contents = {
+    \begin{tikzpicture}[remember picture, overlay]
+      \path [fill = manualcolor] (-0.5\paperwidth, 7) rectangle (0.5\paperwidth, 10);
+    \end{tikzpicture}
+  }
+}
+
+%% Apply engine color for chapter headings: tweaking snippets from fncychap.sty
+\renewcommand{\DOCH}{%
+  \settowidth{\py}{\CNoV\thechapter}
+  \addtolength{\py}{-10pt}      % Amount of space by which the
+%                                  % number is shifted right
+  \fboxsep=0pt%
+  \colorbox{manualcolor}{\rule{0pt}{40pt}\parbox[b]{\textwidth}{\hfill}}%
+  \kern-\py\raise20pt%
+  \hbox{\color{manualcolorshaded}\CNoV\thechapter}\\%
+}
+\renewcommand{\DOTI}[1]{%
+  \nointerlineskip\raggedright%
+  \fboxsep=\myhi%
+  \vskip-1ex%
+  \colorbox{manualcolor}{\parbox[t]{\mylen}{\color{white}\CTV\FmTi{#1}}}\par\nobreak%
+  \vskip 40\p@%
+}
+\renewcommand{\DOTIS}[1]{%
+  \fboxsep=0pt
+  \colorbox{manualcolor}{\rule{0pt}{40pt}\parbox[b]{\textwidth}{\hfill}}\\%
+  \nointerlineskip\raggedright%
+  \fboxsep=\myhi%
+  \vskip-1ex% Remove white 1pt line
+  \colorbox{manualcolor}{\parbox[t]{\mylen}{\color{white}\CTV\FmTi{#1}}}\par\nobreak%
+  \vskip 40\p@%
+}
+
+%% Temporary fix
+\def\set@curr@file#1{%
+  \begingroup
+    \escapechar\m@ne
+    \xdef\@curr@file{\expandafter\string\csname #1\endcsname}%
+  \endgroup
+}
+\def\quote@name#1{"\quote@@name#1\@gobble""}
+\def\quote@@name#1"{#1\quote@@name}
+\def\unquote@name#1{\quote@@name#1\@gobble"}
+
+\makeatother
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/todonotes.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/todonotes.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/latex/global/todonotes.tex	(revision 14097)
@@ -0,0 +1,40 @@
+\usepackage[]{todonotes}
+
+\newcounter{ubcomment}
+\newcommand{\ubcomment}[2][]{%
+\refstepcounter{ubcomment}%
+{%
+\todo[linecolor=black,backgroundcolor={green!40!},size=\footnotesize]{%
+\textbf{Fixme: UB [\uppercase{#1}\theubcomment]:}~#2}%
+}}
+\newcommand{\ubcommentinline}[2][]{%
+\refstepcounter{ubcomment}%
+{%
+\todo[linecolor=black,inline,backgroundcolor={green!40!},size=\footnotesize]{%
+\textbf{Fixme: UB [\uppercase{#1}\theubcomment]:}~#2}%
+}}
+
+\newcommand{\ubcommentmultiline}[2]{%
+\refstepcounter{ubcomment}%
+{%
+\todo[linecolor=black,inline,caption={\textbf{{Fixme: UB}
+    [\theubcomment] #1}} ,backgroundcolor={green!40!},size=\footnotesize]{%
+\textbf{Fixme: UB [\theubcomment]:}~#2}%
+}}
+
+% add support for todo in equations
+%\usepackage{marginnote}
+%\makeatletter
+%\renewcommand{\@todonotes@drawMarginNoteWithLine}{%
+%\begin{tikzpicture}[remember picture, overlay, baseline=-0.75ex]%
+%    \node [coordinate] (inText) {};%
+%\end{tikzpicture}%
+%\marginnote[{% Draw note in left margin
+%    \@todonotes@drawMarginNote%
+%    \@todonotes@drawLineToLeftMargin%
+%}]{% Draw note in right margin
+%    \@todonotes@drawMarginNote%
+%    \@todonotes@drawLineToRightMargin%
+%}%
+%}
+%\makeatother
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/manual_build.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/manual_build.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/manual_build.sh	(revision 14097)
@@ -0,0 +1,46 @@
+#!/bin/sh
+
+## Initialisation
+##---------------
+
+## Default selection for models
+if   [ "$1" = 'all' ]; then
+    models='NEMO SI3 TOP'
+elif [ "$1" =    '' ]; then
+    models='NEMO'
+else
+    models=$*
+fi
+
+# Source shared functions
+. tools/shr_func.sh
+
+
+## Check dependancies
+##-------------------
+
+## LaTeX installation, find latexmk should be enough
+[ -z $( which latexmk ) ] && { echo 'latexmk not installed => QUIT'; exit 2; }
+
+## Pygments package for syntax highlighting of source code (namelists & snippets)
+[ -n "$( ./tools/check_pkg.py pygments )" ] && { echo 'Python pygments is missing => QUIT'; exit 2; }
+
+## Retrieve figures if not already there
+#if [ ! -d latex/figures ]; then
+#    printf "Downloading of shared figures and logos\n\n"
+#    svn co http://forge.ipsl.jussieu.fr/nemo/svn/utils/figures latex/figures > /dev/null
+#fi
+
+
+## Loop on the models
+##-------------------
+
+for model in $models; do
+    echo $model
+#    clean $model
+    build $model
+    printf "\t¤ End of building run\n"
+    echo
+done
+
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_asminc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_asminc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_asminc	(revision 14097)
@@ -0,0 +1,18 @@
+!-----------------------------------------------------------------------
+&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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_dia25h
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_dia25h	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_dia25h	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&nam_dia25h    !  25h Mean Output                                       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dia25h   = .false.   ! Choose 25h mean output or not
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diadct
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diadct	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diadct	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&nam_diadct    !   transports through some sections                     (default: OFF)
+!-----------------------------------------------------------------------
+    ln_diadct  = .false.   ! Calculate transport thru sections or not
+       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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diaharm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diaharm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_diaharm	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents              (default: OFF)
+!-----------------------------------------------------------------------
+    ln_diaharm = .false.   ! Choose tidal harmonic output or not
+       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'   !              ---
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_tide
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_tide	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_tide	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters                                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tide     = .false.      ! Activate tides
+      ln_tide_pot   = .true.                !  use tidal potential forcing
+         ln_scal_load  = .false.               ! Use scalar approximation for
+            rn_scal_load = 0.094               !     load potential
+         ln_read_load  = .false.               ! Or read load potential from file
+            cn_tide_load = 'tide_LOAD_grid_T.nc'  ! filename for load potential
+            !      
+      ln_tide_ramp  = .false.               !  Use linear ramp for tides at startup
+         rdttideramp   =    0.                 !  ramp duration in days
+      clname(1)     = 'DUMMY'               !  name of constituent - all tidal components must be set in namelist_cfg
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_vvl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_vvl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nam_vvl	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+   ln_vvl_ztilde = .false.          !  z-tilde 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
+   ln_vvl_zstar_at_eqtor  = .false. !  ztilde near the equator
+   rn_ahe3       =  0.0             !  thickness diffusion coefficient
+   rn_rst_e3t    = 30.0             !  ztilde to zstar restoration timescale [days]
+   rn_lf_cutoff  =  5.0             !  cutoff frequency for low-pass filter  [days]
+   rn_zdef_max   =  0.9             !  maximum fractional e3t deformation
+   ln_vvl_dbg    = .true.           !  debug prints    (T/F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namage
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namage	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namage	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+   rn_age_depth      = 10            ! depth over which age tracer reset to zero
+   rn_age_kill_rate  = -0.000138888  !  = -1/7200 recip of relaxation timescale (s) for  age tracer shallower than age_depth
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namagrif
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namagrif	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namagrif	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   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]
+   ln_chk_bathy  = .false. !  =T  check the parent bathymetry
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namalb
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namalb	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namalb	(revision 14097)
@@ -0,0 +1,10 @@
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+   !                                  !                          !  obs range (cloud-sky)
+   rn_alb_sdry      =   0.85          !  dry snow albedo         :  0.85 -- 0.87
+   rn_alb_smlt      =   0.75          !  melting snow albedo     :  0.72 -- 0.82
+   rn_alb_idry      =   0.60          !  dry ice albedo          :  0.54 -- 0.65
+   rn_alb_imlt      =   0.50          !  bare puddled ice albedo :  0.49 -- 0.58
+   rn_alb_dpnd      =   0.27          !  ponded ice albedo       :  0.10 -- 0.30 
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbc	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .false.   !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx     = 2       !  geothermal heat flux: = 1 constant flux
+      !                       !                        = 2 read variable flux [mW/m2]
+      rn_geoflx_cst = 86.4e-3 !  Constant value of geothermal heat flux       [mW/m2]
+
+   cn_dir      = './'      !  root directory for the geothermal data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_qgh      ='geothermal_heating.nc'  ,       -12.        , 'heatflow',   .false.   , .true. , 'yearly'  ,   ''             ,   ''     ,   ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambbl	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .false.   !  Bottom Boundary Layer parameterisation flag
+      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]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy	(revision 14097)
@@ -0,0 +1,32 @@
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          (default: OFF)
+!-----------------------------------------------------------------------
+   ln_bdy         = .false.   !  Use unstructured open boundaries
+   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
+   cn_ice        =  'none'    !
+   nn_ice_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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_dta
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_dta	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_dta	(revision 14097)
@@ -0,0 +1,39 @@
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       (see nam_bdy)
+!-----------------------------------------------------------------------
+   ln_zinterp  = .false.      !  T if a vertical interpolation is required. Variables gdep[tuv] and e3[tuv] must exist in the file
+   !                          !  automatically defined to T if the number of vertical levels in bdy dta /= jpk
+   ln_full_vel = .false.      !  T if [uv]3d are "full" velocities and not only its baroclinic components
+   !                          !  in this case, baroclinic and barotropic velocities will be recomputed -> [uv]2d not needed
+   !
+   cn_dir      = 'bdydta/'    !  root directory for the BDY data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''            ,   ''     ,     ''
+!* for si3
+   bn_a_i      = 'amm12_bdyT_ice'        ,         24.       , 'siconc'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_h_i      = 'amm12_bdyT_ice'        ,         24.       , 'sithic'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_h_s      = 'amm12_bdyT_ice'        ,         24.       , 'snthic'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_t_i      = 'NOT USED'              ,         24.       , 'sitemp'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_t_s      = 'NOT USED'              ,         24.       , 'sntemp'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_tsu      = 'NOT USED'              ,         24.       , 'sittop'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_s_i      = 'NOT USED'              ,         24.       , 'sisalt'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   ! melt ponds (be careful, bn_aip is the pond concentration (not fraction), so it differs from rn_iceapnd)
+   bn_aip      = 'NOT USED'              ,         24.       , 'siapnd'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_hip      = 'NOT USED'              ,         24.       , 'sihpnd'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   bn_hil      = 'NOT USED'              ,         24.       , 'sihlid'  ,    .true.   , .false.,  'daily'  ,    ''            ,   ''     ,     ''
+   ! if bn_t_i etc are "not used", then define arbitrary temperatures and salinity and ponds
+   rn_ice_tem  = 270.         !  arbitrary temperature               of incoming sea ice
+   rn_ice_sal  = 10.          !       --   salinity                            --
+   rn_ice_age  = 30.          !       --   age                                 --
+   rn_ice_apnd = 0.2          !       --   pond fraction = a_ip/a_i            --
+   rn_ice_hpnd = 0.05         !       --   pond depth                          --
+   rn_ice_hlid = 0.0          !       --   pond lid depth                      --
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_tide
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_tide	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nambdy_tide	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries                      (default: OFF)
+!-----------------------------------------------------------------------
+   filtide          = 'bdydta/amm12_bdytide_'   !  file name root of tidal forcing files
+   ln_bdytide_2ddta = .false.                   !
+   ln_bdytide_conj  = .false.                   ! 
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namberg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namberg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namberg	(revision 14097)
@@ -0,0 +1,40 @@
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters                                   (default: OFF)
+!-----------------------------------------------------------------------
+   ln_icebergs = .false.      ! activate iceberg floats (force =F with "key_agrif")
+   !
+   !                          ! diagnostics:
+   ln_bergdia        = .true.        ! Calculate budgets
+   nn_verbose_level  = 0             ! 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
+   !
+   !                          ! iceberg setting:
+   !                                 ! 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
+   ln_use_calving          = .false. ! Use calving data even when nn_test_icebergs > 0
+   rn_speed_limit          = 0.      ! CFL speed limit for a berg
+
+   cn_dir      = './'      !  root directory for the calving data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_icb     =  'calving'              ,         -1.        ,'calvingmask',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_fcg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_fcg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_fcg	(revision 14097)
@@ -0,0 +1,12 @@
+!-----------------------------------------------------------------------
+&namc14_fcg     !  files & dates
+!               !  For Paleo-historical: specify tyrc14_beg in yr BP
+!               !  For Bomb: tyrc14_beg=0
+!-----------------------------------------------------------------------
+   cfileco2    = 'splco2.dat'  !  atmospheric co2 - Bomb
+   cfilec14    = 'atmc14.dat'  !  atmospheric c14 - Bomb
+   tyrc14_beg  = 0.00          !  starting year of experiment - Bomb
+!   cfileco2    = 'ByrdEdcCO2.txt' !  atmospheric co2 - Paleo
+!   cfilec14    = 'intcal13.14c'   !  atmospheric c14 - Paleo
+!   tyrc14_beg  =  35000.00        !  starting year of experiment - Paleo (yr BP)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_sbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_sbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_sbc	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namc14_sbc     !  C14 - surface BC
+!-----------------------------------------------------------------------
+   ln_chemh = .true.     ! Chemical enhancement in piston vel.: yes/no
+   xkwind   = 0.360      ! Coefficient for gas exchange velocity
+   xdicsur  = 2.0        ! Reference DIC surface concentration (mol/m3)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_typ
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_typ	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc14_typ	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namc14_typ     !  C14 - type of C14 tracer, default values of C14/C and pco2
+!-----------------------------------------------------------------------
+   kc14typ  = 0          ! Type of C14 tracer (0=equilibrium; 1=bomb transient; 2=past transient)
+   rc14at   = 1.0        ! Default value for atmospheric C14/C (used for equil run)
+   pco2at   = 280.0      ! Default value for atmospheric pcO2 [atm] (used for equil run)
+   rc14init = 0.85       ! Default value for initialization of ocean C14/C (when no restart)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d" default: PAPA station)
+!-----------------------------------------------------------------------
+   rn_lat1d    =      50   !  Column latitude
+   rn_lon1d    =    -145   !  Column longitude
+   ln_c1d_locpt =  .true.   ! Localization of 1D config in a grid (T) or independant point (F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_dyndmp
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_dyndmp	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_dyndmp	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_uvd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_uvd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namc1d_uvd	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d" default: OFF)
+!-----------------------------------------------------------------------
+   !                       !  =T read U-V fields for:
+   ln_uvd_init   = .false.       !  ocean initialisation
+   ln_uvd_dyndmp = .false.       !  U-V restoring
+
+   cn_dir      = './'      !  root directory for the U-V data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ucur     = 'ucurrent'              ,         -1.       ,'u_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Ume'   , ''
+   sn_vcur     = 'vcurrent'              ,         -1.       ,'v_current',   .false.   , .true. , 'monthly' ,  ''              ,  'Vme'   , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfc	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namcfc     !   CFC 
+!-----------------------------------------------------------------------
+   ndate_beg  = 300101    !  datedeb1
+   nyear_res  = 1932      !  iannee1
+   !
+   ! Formatted file of annual hemisperic CFCs concentration in the atmosphere (ppt)
+   clname     = 'CFCs_CDIAC.dat'
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcfg	(revision 14097)
@@ -0,0 +1,19 @@
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration           (F => create/check namusr_def)
+      cn_domcfg = "domain_cfg"  ! domain configuration filename
+      !
+      ln_closea    = .false.    !  T => keep closed seas (defined by closea_mask field) in the  
+      !                         !       domain and apply special treatment of freshwater fluxes.
+      !                         !  F => suppress closed seas (defined by closea_mask field) 
+      !                         !       from the bathymetry at runtime.
+      !                         !  If closea_mask field doesn't exist in the domain_cfg file
+      !                         !       then this logical does nothing.
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+      cn_domcfg_out = "domain_cfg_out" ! newly created domain configuration filename
+      !
+   ln_use_jattr = .false.  !  use (T) the file attribute: open_ocean_jstart, if present
+   !                       !  in netcdf input files, as the start j-row for reading
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcrs
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcrs	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namcrs	(revision 14097)
@@ -0,0 +1,15 @@
+!-----------------------------------------------------------------------
+&namcrs        !   coarsened grid (for outputs and/or TOP)              (ln_crs =T)
+!-----------------------------------------------------------------------
+   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.
+   ln_msh_crs  = .false.   ! =T create a mesh & mask file
+   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 )
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namctl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namctl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namctl	(revision 14097)
@@ -0,0 +1,25 @@
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ctl = .FALSE.                 ! Toggle all report printing on/off (T/F); Ignored if sn_cfctl%l_config is T
+     sn_cfctl%l_config = .TRUE.     ! IF .true. then control which reports are written with the following
+       sn_cfctl%l_runstat = .FALSE. ! switches and which areas produce reports with the proc integer settings.
+       sn_cfctl%l_trcstat = .FALSE. ! The default settings for the proc integers should ensure
+       sn_cfctl%l_oceout  = .FALSE. ! that  all areas report.
+       sn_cfctl%l_layout  = .FALSE. !
+       sn_cfctl%l_mppout  = .FALSE. !
+       sn_cfctl%l_mpptop  = .FALSE. !
+       sn_cfctl%procmin   = 0       ! Minimum area number for reporting [default:0]
+       sn_cfctl%procmax   = 1000000 ! Maximum area number for reporting [default:1000000]
+       sn_cfctl%procincr  = 1       ! Increment for optional subsetting of areas [default:1]
+       sn_cfctl%ptimincr  = 1       ! Timestep increment for writing time step progress info
+   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
+   ln_timing   = .false.   !  timing by routine write out in timing.output file
+   ln_diacfl   = .false.   !  CFL diagnostics write out in cfl_diagnostics.ascii
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdia
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdia	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdia	(revision 14097)
@@ -0,0 +1,12 @@
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+   ln_icediachk     = .false.         !  check online heat, mass & salt budgets
+      !                               !   rate of ice spuriously gained/lost at each time step => rn_icechk=1 <=> 1.e-6 m/hour
+      rn_icechk_cel =  100.           !     check at each gridcell          (1.e-4m/h)=> stops the code if violated (and writes a file)
+      rn_icechk_glo =  1.             !     check over the entire ice cover (1.e-6m/h)=> only prints warnings
+   ln_icediahsb     = .false.         !  output the heat, mass & salt budgets (T) or not (F)
+   ln_icectl        = .false.         !  ice points output for debug (T or F)
+      iiceprt       =  10             !     i-index for debug
+      jiceprt       =  10             !     j-index for debug
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdiu
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdiu	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdiu	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&namdiu        !   Cool skin and warm layer models                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diurnal      = .false.   !
+   ln_diurnal_only = .false.   !
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_isfhmin  =    1.00   !  treshold [m] to discriminate grounding ice from floating ice
+   !
+   rn_rdt      = 5400.     !  time step for the dynamics and tracer
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module      (T => fill namcrs)
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom_domcfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom_domcfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdom_domcfg	(revision 14097)
@@ -0,0 +1,39 @@
+!-----------------------------------------------------------------------
+&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      =    1      !  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_isfhmin  =    1.00   !  treshold (m) to discriminate grounding ice to floating ice
+   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)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   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 !
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF  = .false.   !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin      = .false.   !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin  = .false.   !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.   !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp   = .true.    !  implicit top/bottom friction flag
+      ln_drgice_imp = .false. ! implicit ice-ocean drag
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_bot
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_bot	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_bot	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                      (ln_drg_OFF =F)
+!-----------------------------------------------------------------------
+   rn_Cd0      =  1.e-3    !  drag coefficient [-]
+   rn_Uc0      =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax    =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0      =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0       =  3.e-3    !  roughness [m] (ln_loglayer=T)
+   ln_boost    = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_top
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_top	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdrg_top	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_drg_OFF =F & ln_isfcav=T)
+!-----------------------------------------------------------------------
+   rn_Cd0      =  1.e-3    !  drag coefficient [-]
+   rn_Uc0      =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax    =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0      =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0       =  3.0e-3   !  roughness [m] (ln_loglayer=T)
+   ln_boost    = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdta_dyn
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdta_dyn	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdta_dyn	(revision 14097)
@@ -0,0 +1,26 @@
+!-----------------------------------------------------------------------
+&namdta_dyn    !   offline ocean input files                            (OFF_SRC only)
+!-----------------------------------------------------------------------
+   ln_dynrnf       =  .false.    !  runoffs option enabled (T) or not (F)
+   ln_dynrnf_depth =  .false.    !  runoffs is spread in vertical (T) or not (F)
+!   fwbcorr        = 3.786e-06   !  annual global mean of empmr for ssh correction
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_tem      = 'dyna_grid_T'           ,       120.        , 'votemper'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_sal      = 'dyna_grid_T'           ,       120.        , 'vosaline'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_mld      = 'dyna_grid_T'           ,       120.        , 'somixhgt'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_emp      = 'dyna_grid_T'           ,       120.        , 'sowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_fmf      = 'dyna_grid_T'           ,       120.        , 'iowaflup'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ice      = 'dyna_grid_T'           ,       120.        , 'soicecov'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_qsr      = 'dyna_grid_T'           ,       120.        , 'soshfldo'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wnd      = 'dyna_grid_T'           ,       120.        , 'sowindsp'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_uwd      = 'dyna_grid_U'           ,       120.        , 'uocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vwd      = 'dyna_grid_V'           ,       120.        , 'vocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_wwd      = 'dyna_grid_W'           ,       120.        , 'wocetr_eff',  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_avt      = 'dyna_grid_W'           ,       120.        , 'voddmavs'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_ubl      = 'dyna_grid_U'           ,       120.        , 'sobblcox'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+   sn_vbl      = 'dyna_grid_V'           ,       120.        , 'sobblcoy'  ,  .true.   , .true. , 'yearly'  , ''               , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn	(revision 14097)
@@ -0,0 +1,17 @@
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .true.          !  dyn.: full ice dynamics                  (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections     (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   0.5           !        prescribed ice u-velocity
+      rn_vice       =   0.5           !        prescribed ice v-velocity
+   rn_ishlat        =   2.            !  lbc : free slip (0) ; partial slip (0-2) ; no slip (2) ; strong slip (>2)
+   ln_landfast_L16  = .false.         !  landfast: parameterization from Lemieux 2016
+      rn_lf_depfra  =   0.125         !        fraction of ocean depth that ice must reach to initiate landfast
+                                      !          recommended range: [0.1 ; 0.25]
+      rn_lf_bfr     =  15.            !        maximum bottom stress per unit volume [N/m3]
+      rn_lf_relax   =   1.e-5         !        relaxation time scale to reach static friction [s-1]
+      rn_lf_tensile =   0.05          !        isotropic tensile strength [0-0.5??]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_adv
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_adv	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_adv	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_hpg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_hpg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_hpg	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   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_isf  = .false.   !  s-coordinate (sco ) adapted to isf
+   ln_hpg_djc  = .false.   !  s-coordinate (Density Jacobian with Cubic polynomial)
+   ln_hpg_prj  = .false.   !  s-coordinate (Pressure Jacobian scheme)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_ldf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_ldf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_ldf	(revision 14097)
@@ -0,0 +1,32 @@
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF = .false.     !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap = .false.     !    laplacian operator
+   ln_dynldf_blp = .false.     !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev = .false.     !  iso-level
+   ln_dynldf_hor = .false.     !  horizontal  (geopotential)
+   ln_dynldf_iso = .false.     !  iso-neutral (lap only)
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coefficient :
+      !                             !  =-30  read in eddy_viscosity_3D.nc file
+      !                             !  =-20  read in eddy_viscosity_2D.nc file
+      !                             !  =  0  constant 
+      !                             !  = 10  F(k)=c1d
+      !                             !  = 20  F(i,j)=F(grid spacing)=c2d
+      !                             !  = 30  F(i,j,k)=c2d*c1d
+      !                             !  = 31  F(i,j,k)=F(grid spacing and local velocity)
+      !                             !  = 32  F(i,j,k)=F(local gridscale and deformation rate)
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            or  = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 0.1              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 10.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+      !                       !  Smagorinsky settings  (nn_ahm_ijk_t= 32) :
+      rn_csmc       = 3.5         !  Smagorinsky constant of proportionality
+      rn_minfac     = 1.0         !  multiplier of theorectical lower limit
+      rn_maxfac     = 1.0         !  multiplier of theorectical upper limit
+      !                       !  iso-neutral laplacian operator (ln_dynldf_iso=T) :
+      rn_ahm_b      = 0.0         !  background eddy viscosity  [m2/s]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rdgrft
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rdgrft	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rdgrft	(revision 14097)
@@ -0,0 +1,25 @@
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+          ! -- ice_rdgrft_strength -- !
+   ln_str_H79       = .true.          !  ice strength param.: Hibler_79   => P = pstar*<h>*exp(-c_rhg*A)                      
+      rn_pstar      =   2.0e+04       !     ice strength thickness parameter [N/m2]
+      rn_crhg       =   20.0          !     ice strength conc. parameter (-)
+                   ! -- ice_rdgrft -- !
+   rn_csrdg         =   0.5           !  fraction of shearing energy contributing to ridging
+              ! -- ice_rdgrft_prep -- !
+   ln_partf_lin     = .false.         !  Linear ridging participation function (Thorndike et al, 1975)
+      rn_gstar      =   0.15          !     fractional area of thin ice being ridged 
+   ln_partf_exp     = .true.          !  Exponential ridging participation function (Lipscomb, 2007)
+      rn_astar      =   0.03          !     exponential measure of ridging ice fraction [set to 0.05 if hstar=100]
+   ln_ridging       = .true.          !  ridging activated (T) or not (F)
+      rn_hstar      =  25.0           !     determines the maximum thickness of ridged ice [m] (Hibler, 1980)
+      rn_porordg    =   0.3           !     porosity of newly ridged ice (Lepparanta et al., 1995)
+      rn_fsnwrdg    =   0.5           !     snow volume fraction that survives in ridging
+      rn_fpndrdg    =   1.0           !     pond fraction that survives in ridging (small a priori)
+   ln_rafting       = .true.          !  rafting activated (T) or not (F)
+      rn_hraft      =   0.75          !     threshold thickness for rafting [m]
+      rn_craft      =   5.0           !     squeezing coefficient used in the rafting function
+      rn_fsnwrft    =   0.5           !     snow volume fraction that survives in rafting
+      rn_fpndrft    =   1.0           !     pond fraction that survives in rafting (0.5 a priori)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rhg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rhg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_rhg	(revision 14097)
@@ -0,0 +1,12 @@
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+   ln_rhg_EVP       = .true.          !  EVP rheology
+      ln_aEVP       = .false.         !     adaptive rheology (Kimmritz et al. 2016 & 2017)
+      rn_creepl     =   2.0e-9        !     creep limit [1/s]
+      rn_ecc        =   2.0           !     eccentricity of the elliptical yield curve          
+      nn_nevp       = 120             !     number of EVP subcycles                             
+      rn_relast     =   0.333         !     ratio of elastic timescale to ice time step: Telast = dt_ice * rn_relast 
+                                      !        advised value: 1/3 (rn_nevp=120) or 1/9 (rn_nevp=300)
+   ln_rhg_chkcvg    = .false.         !  check convergence of rheology (outputs: file ice_cvg.nc & variable uice_cvg)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_spg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_spg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_spg	(revision 14097)
@@ -0,0 +1,15 @@
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_exp  = .false.   ! explicit free surface
+   ln_dynspg_ts   = .false.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         rn_bt_cmax   =  0.8        ! =T : the Maximum Courant Number allowed
+         nn_baro      = 30          ! =F : the number of sub-step in rn_rdt seconds
+      rn_bt_alpha   = 0.         ! Temporal diffusion parameter (if ln_bt_av=F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_vor
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_vor	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namdyn_vor	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  energy    conserving scheme
+   ln_dynvor_ens = .false. !  enstrophy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_enT = .false. !  energy conserving scheme (T-point)
+   ln_dynvor_eeT = .false. !  energy conserving scheme (een using e3t)
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0  e3f = mi(mj(e3t))/4 
+      !                       ! =1  e3f = mi(mj(e3t))/mi(mj( tmask))
+   ln_dynvor_msk = .false. !  vorticity multiplied by fmask (=T)        ==>>> PLEASE DO NOT ACTIVATE
+      !                    !  (f-point vorticity schemes only)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nameos
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nameos	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nameos	(revision 14097)
@@ -0,0 +1,17 @@
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .false.         !  = Use TEOS-10
+   ln_eos80    = .false.         !  = Use EOS80
+   ln_seos     = .false.         !  = Use S-EOS (simplified Eq.)
+                                 !
+   !                     ! S-EOS coefficients (ln_seos=T):
+   !                             !  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
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient
+   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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namflo
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namflo	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namflo	(revision 14097)
@@ -0,0 +1,15 @@
+!-----------------------------------------------------------------------
+&namflo        !   float parameters                                     (default: OFF)
+!-----------------------------------------------------------------------
+   ln_floats   = .false.      ! activate floats or not
+      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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namhsb
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namhsb	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namhsb	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namhsb        !  Heat and salt budgets                                 (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diahsb   = .false.   !  output the heat and salt budgets (T) or not (F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namini
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namini	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namini	(revision 14097)
@@ -0,0 +1,42 @@
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =   0             !     0 = Initialise sea ice based on SSTs
+                                      !     1 = Initialise sea ice from single category netcdf file
+                                      !     2 = Initialise sea ice from multi category restart file
+   rn_thres_sst     =   2.0           !  max temp. above Tfreeze with initial ice = (sst - tfreeze)
+   rn_hti_ini_n     =   3.0           !  initial ice thickness       (m), North
+   rn_hti_ini_s     =   1.0           !        "            "             South
+   rn_hts_ini_n     =   0.3           !  initial snow thickness      (m), North
+   rn_hts_ini_s     =   0.3           !        "            "             South
+   rn_ati_ini_n     =   0.9           !  initial ice concentration   (-), North
+   rn_ati_ini_s     =   0.9           !        "            "             South
+   rn_smi_ini_n     =   6.3           !  initial ice salinity     (g/kg), North
+   rn_smi_ini_s     =   6.3           !        "            "             South
+   rn_tmi_ini_n     = 270.            !  initial ice temperature     (K), North
+   rn_tmi_ini_s     = 270.            !        "            "             South
+   rn_tsu_ini_n     = 270.            !  initial surface temperature (K), North
+   rn_tsu_ini_s     = 270.            !        "            "             South
+   rn_tms_ini_n     = 270.            !  initial snw temperature     (K), North
+   rn_tms_ini_s     = 270.            !        "            "             South
+   rn_apd_ini_n     =   0.2           !  initial pond fraction       (-), North
+   rn_apd_ini_s     =   0.2           !        "            "             South
+   rn_hpd_ini_n     =   0.05          !  initial pond depth          (m), North
+   rn_hpd_ini_s     =   0.05          !        "            "             South
+   rn_hld_ini_n     =   0.0           !  initial pond lid depth      (m), North
+   rn_hld_ini_s     =   0.0           !        "            "             South
+   ! -- for nn_iceini_file = 1
+   sn_hti = 'Ice_initialization'    , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'Ice_initialization'    , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'Ice_initialization'    , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'Ice_initialization'    , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'Ice_initialization'    , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'Ice_initialization'    , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tms = 'NOT USED'              , -12 ,'tms'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   !      melt ponds (be careful, sn_apd is the pond concentration (not fraction), so it differs from rn_apd)
+   sn_apd = 'NOT USED'              , -12 ,'apd'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hpd = 'NOT USED'              , -12 ,'hpd'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hld = 'NOT USED'              , -12 ,'hld'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namitd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namitd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namitd	(revision 14097)
@@ -0,0 +1,9 @@
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+   ln_cat_hfn       = .true.          !  ice categories are defined by a function following rn_himean**(-0.05)
+      rn_himean     =   2.0           !  expected domain-average ice thickness (m)
+   ln_cat_usr       = .false.         !  ice categories are defined by rn_catbnd below (m)
+      rn_catbnd     =   0.,0.45,1.1,2.1,3.7,6.0  
+   rn_himin         =   0.1           !  minimum ice thickness (m) used in remapping
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlbc	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  free slip  !   partial slip  !   no slip   ! strong slip
+   rn_shlat    =  -9999.   !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+   ln_vorlat   = .false.   !  consistency of vorticity boundary condition with analytical Eqs.
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdet
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdet	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdet	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+   taudn   = 5.80e-7    ! detritus breakdown rate                        [0.1/86400 s-1=10 days]
+   fdetlab = 0.         ! NH4 fraction of detritus dissolution           
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdom
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdom	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobdom	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+   taudomn = 6.43e-8    ! DOM breakdown rate                             [s-1] 
+!                       ! slow remineralization rate of semi-labile dom to nh4 (1 month)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobnut
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobnut	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobnut	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+   akno3   =  0.7       ! nitrate limitation half-saturation value     [mmol/m3]
+   aknh4   =  0.001     ! ammonium limitation half-saturation value    [mmol/m3]
+   taunn   =  5.80e-7   ! nitrification rate                           [s-1]  
+   psinut  =  3.        ! inhibition of nitrate uptake by ammonium
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobopt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobopt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobopt	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+   xkg0   = 0.0232     ! green absorption coefficient of water
+   xkr0   = 0.225      ! red absorption coefficent of water
+   xkgp   = 0.074      ! green absorption coefficient of chl
+   xkrp   = 0.037      ! red absorption coefficient of chl
+   xlg    = 0.674      ! green chl exposant for absorption
+   xlr    = 0.629      ! red chl exposant for absorption
+   rpig   = 0.7        ! chla/chla+pheo ratio
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobphy
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobphy	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobphy	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+   tmumax  =  1.21e-5   ! maximal phytoplankton growth rate            [s-1] 
+   rgamma  =  0.05      ! phytoplankton exudation fraction             [%]
+   fphylab =  0.75      ! NH4 fraction of phytoplankton exsudation     
+   tmminp  =  5.8e-7    ! minimal phytoplancton mortality rate         [0.05/86400 s-1=20 days] 
+   aki     =  33.       ! light photosynthesis half saturation constant[W/m2]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobrat
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobrat	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobrat	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+   rcchl   = 60.       ! Carbone/Chlorophyl ratio                     [mgC.mgChla-1]
+   redf    = 6.56       ! redfield ratio (C:N) for phyto
+   reddom  = 6.56       ! redfield ratio (C:N) for DOM
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobsed
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobsed	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobsed	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+   sedlam     = 3.86e-7    ! time coefficient of POC remineralization in sediments [s-1]
+   sedlostpoc = 0.         ! mass of POC lost in sediments
+   vsed       = 3.47e-5    ! detritus sedimentation speed                   [m/s]
+   xhr        = -0.858     ! coeff for martin''s remineralisation profile
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobzoo
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobzoo	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namlobzoo	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+   rppz    = 0.8        ! zooplankton nominal preference for phytoplancton food  [%]
+   taus    = 9.26E-6    ! specific zooplankton maximal grazing rate              [s-1] 
+!                       ! 0.75/86400 s-1=8.680555E-6    1/86400 = 1.15e-5
+   aks     = 1.         ! half-saturation constant for total zooplankton grazing [mmolN.m-3]
+   rpnaz   = 0.3        ! non-assimilated phytoplankton by zooplancton           [%]
+   rdnaz   = 0.3        ! non-assimilated detritus by zooplankton                [%] 
+   tauzn   = 8.1e-7     ! zooplancton specific excretion rate                    [0.1/86400 s-1=10 days] 
+   fzoolab = 0.5        ! NH4 fraction of zooplankton excretion
+   fdbod   = 0.5        ! zooplankton mortality fraction that goes to detritus
+   tmminz  = 2.31e-6    ! minimal zooplankton mortality rate                     [(mmolN/m3)-1 d-1]
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nammpp
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nammpp	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nammpp	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+   ln_listonly =  .false.  !  do nothing else than listing the best domain decompositions (with land domains suppression)
+   !                       !  if T: the largest number of cores tested is defined by max(mppsize, jpni*jpnj)
+   ln_nnogather =  .true.  !  activate code to avoid mpi_allgather use at the northfold
+   jpni        =   0       !  number of processors following i (set automatically if < 1), see also ln_listonly = T
+   jpnj        =   0       !  number of processors following j (set automatically if < 1), see also ln_listonly = T
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namnc4
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namnc4	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namnc4	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namobs
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namobs	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namobs	(revision 14097)
@@ -0,0 +1,57 @@
+!-----------------------------------------------------------------------
+&namobs        !  observation usage switch                              (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diaobs   = .false.             ! Logical switch for the observation operator
+   !
+   ln_t3d      = .false.             ! Logical switch for T profile observations
+   ln_s3d      = .false.             ! Logical switch for S profile observations
+   ln_sla      = .false.             ! Logical switch for SLA observations
+   ln_sst      = .false.             ! Logical switch for SST observations
+   ln_sss      = .false.             ! Logical swithc for SSS observations
+   ln_sic      = .false.             ! Logical switch for Sea Ice observations
+   ln_vel3d    = .false.             ! Logical switch for velocity observations
+   ln_altbias  = .false.             ! Logical switch for altimeter bias correction
+   ln_sstbias  = .false.             ! Logical switch for SST bias correction
+   ln_nea      = .false.             ! Logical switch for rejection of observations near land
+   ln_grid_global = .true.           ! Logical switch for global distribution of observations
+   ln_grid_search_lookup = .false.   ! Logical switch for obs grid search w/lookup table
+   ln_ignmis   = .true.              ! Logical switch for ignoring missing files
+   ln_s_at_t   = .false.             ! Logical switch for computing model S at T obs if not there
+   ln_sstnight = .false.             ! Logical switch for calculating night-time average for SST obs
+   ln_bound_reject  = .false.        ! Logical to remove obs near boundaries in LAMs.
+   ln_sla_fp_indegs = .true.         ! Logical for SLA: T=> averaging footprint is in degrees, F=> in metres
+   ln_sst_fp_indegs = .true.         ! Logical for SST: T=> averaging footprint is in degrees, F=> in metres
+   ln_sss_fp_indegs = .true.         ! Logical for SSS: T=> averaging footprint is in degrees, F=> in metres
+   ln_sic_fp_indegs = .true.         ! Logical for SIC: T=> averaging footprint is in degrees, F=> in metres
+! All of the *files* variables below are arrays. Use namelist_cfg to add more files
+   cn_profbfiles = 'profiles_01.nc'  ! Profile feedback input observation file names
+   cn_slafbfiles = 'sla_01.nc'       ! SLA feedback input observation file names
+   cn_sstfbfiles = 'sst_01.nc'       ! SST feedback input observation file names
+   cn_sssfbfiles = 'sss_01.nc'       ! SSS feedback input observation file names
+   cn_sicfbfiles = 'sic_01.nc'       ! SIC feedback input observation file names
+   cn_velfbfiles = 'vel_01.nc'       ! Velocity feedback input observation file names
+   cn_altbiasfile = 'altbias.nc'     ! Altimeter bias input file name
+   cn_sstbiasfiles = 'sstbias.nc'    ! SST bias input file name
+   cn_gridsearchfile ='gridsearch.nc' ! Grid search file name
+   rn_gridsearchres = 0.5            ! Grid search resolution
+   rn_mdtcorr  = 1.61                ! MDT  correction
+   rn_mdtcutoff = 65.0               ! MDT cutoff for computed correction
+   rn_dobsini  = 00010101.000000     ! Initial date in window YYYYMMDD.HHMMSS
+   rn_dobsend  = 00010102.000000     ! Final date in window YYYYMMDD.HHMMSS
+   rn_sla_avglamscl = 0.             ! E/W diameter of SLA observation footprint (metres/degrees)
+   rn_sla_avgphiscl = 0.             ! N/S diameter of SLA observation footprint (metres/degrees)
+   rn_sst_avglamscl = 0.             ! E/W diameter of SST observation footprint (metres/degrees)
+   rn_sst_avgphiscl = 0.             ! N/S diameter of SST observation footprint (metres/degrees)
+   rn_sss_avglamscl = 0.             ! E/W diameter of SSS observation footprint (metres/degrees)
+   rn_sss_avgphiscl = 0.             ! N/S diameter of SSS observation footprint (metres/degrees)
+   rn_sic_avglamscl = 0.             ! E/W diameter of SIC observation footprint (metres/degrees)
+   rn_sic_avgphiscl = 0.             ! N/S diameter of SIC observation footprint (metres/degrees)
+   nn_1dint = 0                      ! Type of vertical interpolation method
+   nn_2dint = 0                      ! Default horizontal interpolation method
+   nn_2dint_sla = 0                  ! Horizontal interpolation method for SLA
+   nn_2dint_sst = 0                  ! Horizontal interpolation method for SST
+   nn_2dint_sss = 0                  ! Horizontal interpolation method for SSS
+   nn_2dint_sic = 0                  ! Horizontal interpolation method for SIC
+   nn_msshc     = 0                  ! MSSH correction scheme
+   nn_profdavtypes = -1              ! Profile daily average types - array
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zlim
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zlim	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zlim	(revision 14097)
@@ -0,0 +1,24 @@
+!-----------------------------------------------------------------------
+&namp4zlim     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+   concnno3   =  1.e-6    ! Nitrate half saturation of nanophytoplankton
+   concdno3   =  3.E-6    ! Nitrate half saturation for diatoms
+   concnnh4   =  1.E-7    ! NH4 half saturation for phyto
+   concdnh4   =  3.E-7    ! NH4 half saturation for diatoms
+   concnfer   =  1.E-9    ! Iron half saturation for phyto
+   concdfer   =  3.E-9    ! Iron half saturation for diatoms
+   concbfe    =  1.E-11   ! Iron half-saturation for DOC remin.
+   concbnh4   =  2.E-8    ! NH4 half saturation for DOC remin.
+   concbno3   =  2.E-7    ! Nitrate half saturation for DOC remin.
+   xsizedia   =  1.E-6    ! Minimum size criteria for diatoms
+   xsizephy   =  1.E-6    ! Minimum size criteria for phyto
+   xsizern    =  3.0      ! Size ratio for nanophytoplankton
+   xsizerd    =  3.0      ! Size ratio for diatoms
+   xksi1      =  2.E-6    ! half saturation constant for Si uptake
+   xksi2      =  20E-6    ! half saturation constant for Si/C
+   xkdoc      =  417.E-6  ! half-saturation constant of DOC remineralization
+   qnfelim    =  7.E-6    ! Optimal quota of phyto
+   qdfelim    =  7.E-6    ! Optimal quota of diatoms
+   caco3r     =  0.3      ! mean rain ratio
+   oxymin     =  1.E-6    ! Half-saturation constant for anoxia
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmes
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmes	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmes	(revision 14097)
@@ -0,0 +1,23 @@
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+   part2      =  0.75     ! part of calcite not dissolved in mesozoo guts
+   grazrat2   =  0.75     ! maximal mesozoo grazing rate
+   resrat2    =  0.005    ! exsudation rate of mesozooplankton
+   mzrat2     =  0.03     ! mesozooplankton mortality rate
+   xpref2d    =  1.       ! mesozoo preference for diatoms
+   xpref2n    =  0.3      ! mesozoo preference for nanophyto.
+   xpref2z    =  1.       ! mesozoo preference for microzoo.
+   xpref2c    =  0.3      ! mesozoo preference for poc
+   xthresh2zoo = 1E-8     ! zoo feeding threshold for mesozooplankton 
+   xthresh2dia = 1E-8     ! diatoms feeding threshold for mesozooplankton 
+   xthresh2phy = 1E-8     ! nanophyto feeding threshold for mesozooplankton 
+   xthresh2poc = 1E-8     ! poc feeding threshold for mesozooplankton 
+   xthresh2   =  3E-7     ! Food threshold for grazing
+   xkgraz2    =  20.E-6   ! half saturation constant for meso grazing
+   epsher2    =  0.35     ! Efficicency of Mesozoo growth
+   epsher2min =  0.35     ! Minimum efficiency of mesozoo growth
+   sigma2     =  0.6      ! Fraction of mesozoo excretion as DOM
+   unass2     =  0.3      ! non assimilated fraction of P by mesozoo
+   grazflux   =  3.e3     ! flux-feeding rate
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmort
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmort	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zmort	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+   wchl       =  0.01     ! quadratic mortality of phytoplankton
+   wchld      =  0.01     ! maximum quadratic mortality of diatoms
+   wchldm     =  0.03     ! maximum quadratic mortality of diatoms
+   mprat      =  0.01     ! phytoplankton mortality rate
+   mprat2     =  0.01     ! Diatoms mortality rate
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zprod
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zprod	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zprod	(revision 14097)
@@ -0,0 +1,16 @@
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+   pislopen   =  2.       ! P-I slope
+   pisloped   =  2.       ! P-I slope  for diatoms
+   xadap      =  0.       ! Adaptation factor to low light
+   excretn    =  0.05     ! excretion ratio of phytoplankton
+   excretd    =  0.05     ! excretion ratio of diatoms
+   bresp      =  0.033    ! Basal respiration rate
+   chlcnm     =  0.033    ! Maximum Chl/C in nanophytoplankton
+   chlcdm     =  0.05     ! Maximum Chl/C in diatoms
+   chlcmin    =  0.004    ! Minimum Chl/c in phytoplankton
+   fecnm      =  40E-6    ! Maximum Fe/C in nanophytoplankton
+   fecdm      =  40E-6    ! Maximum Fe/C in diatoms
+   grosip     =  0.159    ! mean Si/C ratio
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zzoo
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zzoo	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp4zzoo	(revision 14097)
@@ -0,0 +1,20 @@
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+   part       =  0.5      ! part of calcite not dissolved in microzoo guts
+   grazrat    =  3.0      ! maximal zoo grazing rate
+   resrat     =  0.03     ! exsudation rate of zooplankton
+   mzrat      =  0.004    ! zooplankton mortality rate
+   xprefc     =  0.1      ! Microzoo preference for POM
+   xprefn     =  1.       ! Microzoo preference for Nanophyto
+   xprefd     =  0.6      ! Microzoo preference for Diatoms
+   xthreshdia =  1.E-8    ! Diatoms feeding threshold for microzooplankton 
+   xthreshphy =  1.E-8    ! Nanophyto feeding threshold for microzooplankton 
+   xthreshpoc =  1.E-8    ! POC feeding threshold for microzooplankton 
+   xthresh    =  3.E-7    ! Food threshold for feeding
+   xkgraz     =  20.E-6   ! half sturation constant for grazing
+   epsher     =  0.3      ! Efficiency of microzoo growth
+   epshermin  =  0.3      ! Minimum efficiency of microzoo growth
+   sigma1     =  0.6      ! Fraction of microzoo excretion as DOM
+   unass      =  0.3      ! non assimilated fraction of phyto by zoo
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zlim
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zlim	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zlim	(revision 14097)
@@ -0,0 +1,31 @@
+!-----------------------------------------------------------------------
+&namp5zlim     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+   concnno3   =  3e-6     ! Nitrate half saturation of nanophytoplankton
+   concpno3   =  1e-6
+   concdno3   =  4E-6     ! Phosphate half saturation for diatoms
+   concnnh4   =  1.5E-6   ! NH4 half saturation for phyto
+   concpnh4   =  4E-7
+   concdnh4   =  2E-6     ! NH4 half saturation for diatoms
+   concnpo4   =  3E-6     ! PO4 half saturation for phyto
+   concppo4   =  1.5E-6
+   concdpo4   =  4E-6     ! PO4 half saturation for diatoms
+   concnfer   =  3E-9   ! Iron half saturation for phyto
+   concpfer   =  1.5E-9
+   concdfer   =  4E-9   ! Iron half saturation for diatoms
+   concbfe    =  1.E-11   ! Half-saturation for Fe limitation of Bacteria
+   concbnh4   =  1.E-7    ! NH4 half saturation for phyto
+   concbno3   =  5.E-7    ! Phosphate half saturation for diatoms
+   concbpo4   =  1E-7     ! Phosphate half saturation for bacteria
+   xsizedia   =  1.E-6    ! Minimum size criteria for diatoms
+   xsizephy   =  1.E-6    ! Minimum size criteria for phyto
+   xsizepic   =  1.E-6
+   xsizern    =  1.0      ! Size ratio for nanophytoplankton
+   xsizerp    =  1.0
+   xsizerd    =  4.0      ! Size ratio for diatoms
+   xksi1      =  2.E-6    ! half saturation constant for Si uptake
+   xksi2      =  20E-6  ! half saturation constant for Si/C
+   xkdoc      =  417.E-6  ! half-saturation constant of DOC remineralization
+   caco3r     =  0.35     ! mean rain ratio
+   oxymin     =  1.E-6    ! Half-saturation constant for anoxia
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmes
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmes	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmes	(revision 14097)
@@ -0,0 +1,29 @@
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+   part2      =  0.75     ! part of calcite not dissolved in mesozoo guts
+   grazrat2   =  0.85     ! maximal mesozoo grazing rate
+   bmetexc2   =  .true.   ! Metabolic use of excess carbon 
+   resrat2    =  0.005    ! exsudation rate of mesozooplankton
+   mzrat2     =  0.02     ! mesozooplankton mortality rate
+   xpref2d    =  1.       ! zoo preference for phyto
+   xpref2p    =  1.       ! zoo preference for POC
+   xpref2z    =  1.       ! zoo preference for zoo
+   xpref2m    =  0.2      ! meso preference for zoo
+   xpref2c    =  0.3      ! zoo preference for poc
+   xthresh2zoo = 1E-8     ! zoo feeding threshold for mesozooplankton
+   xthresh2dia = 1E-8     ! diatoms feeding threshold for mesozooplankton
+   xthresh2phy = 1E-8     ! nanophyto feeding threshold for mesozooplankton
+   xthresh2mes = 1E-8     ! meso feeding threshold for mesozooplankton
+   xthresh2poc = 1E-8     ! poc feeding threshold for mesozooplankton
+   xthresh2    =  3E-7     ! Food threshold for grazing
+   xkgraz2     =  20.E-6   ! half sturation constant for meso grazing
+   epsher2     =  0.5      ! Efficicency of Mesozoo growth
+   epsher2min  =  0.2     ! Minimum efficiency of mesozoo growth
+   ssigma2     =  0.5     ! Fraction excreted as semi-labile DOM
+   srespir2    =  0.2     ! Active respiration
+   unass2c     =  0.3     ! non assimilated fraction of P by mesozoo
+   unass2n     =  0.3     ! non assimilated fraction of N by mesozoo
+   unass2p     =  0.3     ! non assimilated fraction of P by mesozoo
+   grazflux   =  3.e3     ! flux-feeding rate
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmort
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmort	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zmort	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+   wchln      =  0.01     ! quadratic mortality of nanophytoplankton
+   wchlp      =  0.01     ! quadratic mortality of picophytoplankton
+   wchld      =  0.01     ! maximum quadratic mortality of diatoms
+   wchldm     =  0.02     ! maximum quadratic mortality of diatoms
+   mpratn     =  0.01     ! nanophytoplankton mortality rate
+   mpratp     =  0.01     ! picophytoplankton mortality rate
+   mprat2     =  0.01     ! Diatoms mortality rate
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zprod
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zprod	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zprod	(revision 14097)
@@ -0,0 +1,17 @@
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+   pislopen   =  3.       ! P-I slope
+   pislopep   =  3.       ! P-I slope for picophytoplankton
+   pisloped   =  3.       ! P-I slope  for diatoms
+   excretn    =  0.05     ! excretion ratio of phytoplankton
+   excretp    =  0.05     ! excretion ratio of picophytoplankton
+   excretd    =  0.05     ! excretion ratio of diatoms
+   xadap      =  0.       ! Adaptation factor to low light
+   bresp      =  0.02     ! Basal respiration rate
+   thetannm   =  0.25     ! Maximum Chl/N in nanophytoplankton
+   thetanpm   =  0.25     ! Maximum Chl/N in picophytoplankton
+   thetandm   =  0.3      ! Maximum Chl/N in diatoms
+   chlcmin    =  0.004    ! Minimum Chl/c in phytoplankton
+   grosip     =  0.131    ! mean Si/C ratio
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zquota
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zquota	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zquota	(revision 14097)
@@ -0,0 +1,22 @@
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+   qfnopt     =  7.E-6    ! Optimal Fe quota of nanophyto
+   qfpopt     =  7.E-6    ! Optimal Fe quota of picophyto
+   qfdopt     =  7.E-6    ! Optimal quota of diatoms
+   qnnmin     =  0.29     ! Minimal N quota for nano
+   qnnmax     =  1.39     ! Maximal N quota for nano
+   qpnmin     =  0.28     ! Minimal P quota for nano
+   qpnmax     =  1.06     ! Maximal P quota for nano
+   qnpmin     =  0.42     ! Minimal N quota for pico
+   qnpmax     =  1.39     ! Maximal N quota for pico
+   qppmin     =  0.25     ! Minimal P quota for pico
+   qppmax     =  0.7      ! Maximal P quota for pico
+   qndmin     =  0.25     ! Minimal N quota for diatoms
+   qndmax     =  1.39     ! Maximal N quota for diatoms
+   qpdmin     =  0.29     ! Minimal P quota for diatoms
+   qpdmax     =  1.32     ! Maximal P quota for diatoms
+   qfnmax     =  40E-6    ! Maximal Fe quota for nano
+   qfpmax     =  40E-6    ! Maximal Fe quota for pico
+   qfdmax     =  40E-6    ! Maximal Fe quota for diatoms
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zzoo
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zzoo	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namp5zzoo	(revision 14097)
@@ -0,0 +1,28 @@
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+   part       =  0.5      ! part of calcite not dissolved in microzoo gutsa
+   grazrat    =  2.75     ! maximal zoo grazing rate
+   bmetexc    =  .true.   ! Metabolic use of excess carbon
+   resrat     =  0.03     ! exsudation rate of zooplankton
+   mzrat      =  0.005    ! zooplankton mortality rate
+   xprefc     =  0.1      ! Microzoo preference for POM
+   xprefn     =  1.       ! Microzoo preference for Nanophyto
+   xprefp     =  1.6      ! Microzoo preference for picophyto
+   xprefd     =  1.0      ! Microzoo preference for Diatoms
+   xprefz     =  0.3      ! Microzoo preference for microzooplankton
+   xthreshdia =  1.E-8    ! Diatoms feeding threshold for microzooplankton
+   xthreshphy =  1.E-8    ! Nanophyto feeding threshold for microzooplankton
+   xthreshpic =  1.E-8
+   xthreshzoo =  1.E-8    ! Nanophyto feeding threshold for microzooplankton
+   xthreshpoc =  1.E-8    ! POC feeding threshold for microzooplankton
+   xthresh    =  3.E-7    ! Food threshold for feeding
+   xkgraz     =  20.E-6   ! half sturation constant for grazing
+   epsher     =  0.5      ! Efficiency of microzoo growth
+   epshermin  =  0.2      ! Minimum efficiency of microzoo growth
+   ssigma     =  0.5      ! Fraction excreted as semi-labile DOM
+   srespir    =  0.2      ! Active respiration
+   unassc     =  0.3      ! non assimilated fraction of C by zoo
+   unassn     =  0.3      ! non assimilated fraction of C by zoo
+   unassp     =  0.3      ! non assimilated fraction of C by zoo
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampar
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampar	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampar	(revision 14097)
@@ -0,0 +1,17 @@
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   5             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   nlay_s           =   1             !  number of snow layers (only 1 is working)
+   ln_virtual_itd   =   .false.       !  virtual ITD mono-category parameterization (jpl=1 only)
+                                      !     i.e. enhanced thermal conductivity & virtual thin ice melting
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .true.          !  ice thermo   (T) or not (F)
+   rn_amax_n        =   0.997         !  maximum tolerated ice concentration NH
+   rn_amax_s        =   0.997         !  maximum tolerated ice concentration SH
+   cn_icerst_in     = "restart_ice"   !  suffix of ice restart name (input)
+   cn_icerst_out    = "restart_ice"   !  suffix of ice restart name (output)
+   cn_icerst_indir  = "."             !  directory to read   input ice restarts
+   cn_icerst_outdir = "."             !  directory to write output ice restarts
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisatm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisatm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisatm	(revision 14097)
@@ -0,0 +1,12 @@
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+!              !  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_patm     = 'presatm'    ,     -1.           , 'patm'    ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   sn_atmco2   = 'presatmco2' ,     -1.           , 'xco2'    ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   cn_dir      = './'     !  root directory for the location of the dynamical files
+!
+   ln_presatm    = .false.   ! constant atmopsheric pressure (F) or from a file (T)
+   ln_presatmco2 = .false.   ! Read spatialized atm co2 files [ppm] if TRUE
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisbio
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisbio	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisbio	(revision 14097)
@@ -0,0 +1,18 @@
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+   nrdttrc    =  1        ! time step frequency for biology
+   wsbio      =  2.       ! POC sinking speed
+   xkmort     =  2.E-7    ! half saturation constant for mortality
+   ferat3     =  10.E-6   ! Fe/C in zooplankton 
+   wsbio2     =  50.      ! Big particles sinking speed
+   wsbio2max  =  50.      ! Big particles maximum sinking speed
+   wsbio2scale =  5000.    ! Big particles length scale of sinking
+!                         !  ln_ligand enabled
+   ldocp      =  1.E-4    ! Phyto ligand production per unit doc 
+   ldocz      =  1.E-4    ! Zoo ligand production per unit doc 
+   lthet      =  1.0      ! Proportional loss of ligands due to Fe uptake 
+!                         !  ln_p5z enabled
+   no3rat3    =  0.182    ! N/C ratio in zooplankton
+   po4rat3    =  0.0094   ! P/C ratio in zooplankton
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampiscal
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampiscal	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampiscal	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+   kdca       =  6.       ! calcite dissolution rate constant (1/time)
+   nca        =  1.       ! order of dissolution reaction (dimensionless)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisdmp
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisdmp	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisdmp	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+   ln_pisdmp    =  .true.     !  Relaxation for some tracers to a mean value
+   nn_pisdmp    =  5475       !  Frequency of Relaxation 
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisext
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisext	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisext	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+   ln_co2int  =  .false. ! read atm pco2 from a file (T) or constant (F)
+   atcco2     =  280.    ! Constant value atmospheric pCO2 - ln_co2int = F
+   clname     =  'atcco2.txt'  ! Name of atm pCO2 file - ln_co2int = T
+   nn_offset  =  0       ! Offset model-data start year - ln_co2int = T
+!                        ! If your model year is iyy, nn_offset=(years(1)-iyy) 
+!                        ! then the first atmospheric CO2 record read is at years(1)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisfer
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisfer	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisfer	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+   ln_ligvar =  .false.    ! variable ligand concentration
+   xlam1     =  0.005     ! scavenging rate of Iron
+   xlamdust  =  150.0     ! Scavenging rate of dust
+   ligand    =  0.7E-9    ! Ligands concentration 
+   kfep      =  0.01      ! Nanoparticle formation rate constant
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisice
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisice	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisice	(revision 14097)
@@ -0,0 +1,44 @@
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+!========================================================================
+! constant ocean tracer concentrations are defined in trcice_pisces.F90 
+!                               (Global, Arctic, Antarctic and Baltic)
+! trc_ice_ratio  : >=0 & <=1 => prescribed ice/ocean tracer concentration ratio
+!                :  = -1     => the ice-ocean tracer concentration ratio
+!                               follows the ice-ocean salinity ratio
+!                :  = -2     => tracer concentration in sea ice is prescribed
+!                               and trc_ice_prescr is used
+! trc_ice_prescr : prescribed tracer concentration. used only if 
+!                  trc_ice_ratio = -2. equals -99 if not used.
+! cn_trc_o       :  = 'GL'   => use global ocean values making the Baltic 
+!                               distinction only
+!                :  = 'AA'   => use specific Arctic/Antarctic/Baltic values
+!========================================================================
+!    sn_tri_ ! trc_ice_ratio ! trc_ice_prescr !     cn_trc_o
+   sn_tri_dic =           -1.,           -99.,          'AA'
+   sn_tri_doc =            0.,           -99.,          'AA'
+   sn_tri_tal =           -1.,           -99.,          'AA'
+   sn_tri_oxy =           -1.,           -99.,          'AA'
+   sn_tri_cal =            0.,           -99.,          'AA'
+   sn_tri_po4 =           -1.,           -99.,          'AA'
+   sn_tri_poc =            0.,           -99.,          'AA'
+   sn_tri_goc =            0.,           -99.,          'AA'
+   sn_tri_bfe =            0.,           -99.,          'AA'
+   sn_tri_num =            0.,           -99.,          'AA'
+   sn_tri_sil =           -1.,           -99.,          'AA'
+   sn_tri_dsi =            0.,           -99.,          'AA'
+   sn_tri_gsi =            0.,           -99.,          'AA'
+   sn_tri_phy =            0.,           -99.,          'AA'
+   sn_tri_dia =            0.,           -99.,          'AA'
+   sn_tri_zoo =            0.,           -99.,          'AA'
+   sn_tri_mes =            0.,           -99.,          'AA'
+   sn_tri_fer =           -2.,          15E-9,          'AA'
+   sn_tri_sfe =            0.,           -99.,          'AA'
+   sn_tri_dfe =            0.,           -99.,          'AA'
+   sn_tri_nfe =            0.,           -99.,          'AA'
+   sn_tri_nch =            0.,           -99.,          'AA'
+   sn_tri_dch =            0.,           -99.,          'AA'
+   sn_tri_no3 =           -1.,           -99.,          'AA'
+   sn_tri_nh4 =            1.,           -99.,          'AA'
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampislig
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampislig	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampislig	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+   rlgw        =  100.     ! Lifetime (years) of weak ligands
+   rlig        =  1.E-4    ! Remin ligand production per unit C
+   prlgw       =  1.E-4    ! Photolysis of weak ligand
+   rlgs        =  1.       ! Lifetime (years) of strong ligands
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismass
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismass	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismass	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+   ln_check_mass =  .false.    !  Check mass conservation
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismod
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismod	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampismod	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+  ln_p2z    = .false.        !  LOBSTER model used
+  ln_p4z    = .true.         !  PISCES model used
+  ln_p5z    = .false.        !  PISCES QUOTA model used
+  ln_ligand = .false.        !  Enable  organic ligands
+  ln_sediment = .false.      !  Enable sediment module
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisopt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisopt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisopt	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+!              !  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_par      = 'par.orca'       ,     24.           , 'fr_par'  ,  .true.      , .true. , 'yearly'  , ''       , ''       , ''
+   cn_dir      = './'      !  root directory for the location of the dynamical files
+   ln_varpar   =  .true.   ! boolean for PAR variable
+   parlux      =  0.43      ! Fraction of shortwave as PAR
+/ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampispoc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampispoc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampispoc	(revision 14097)
@@ -0,0 +1,11 @@
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+   xremip    =  0.035     ! remineralisation rate of PON
+   jcpoc     =  15        ! Number of lability classes
+   rshape    =  1.0       ! Shape of the gamma function
+!                         ! ln_p5z
+   xremipc   =  0.02      ! remineralisation rate of POC
+   xremipn   =  0.025     ! remineralisation rate of PON
+   xremipp   =  0.03      ! remineralisation rate of POP
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisrem
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisrem	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampisrem	(revision 14097)
@@ -0,0 +1,17 @@
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+   xremik    =  0.3       ! remineralization rate of DOC
+   nitrif    =  0.05      ! NH4 nitrification rate
+   xsirem    =  0.003     ! remineralization rate of Si
+   xsiremlab =  0.03      ! fast remineralization rate of Si
+   xsilab    =  0.5       ! Fraction of labile biogenic silica
+   feratb    =  10.E-6    ! Fe/C quota in bacteria
+   xkferb    =  3E-10     ! Half-saturation constant for bacteria Fe/C
+!                         ! ln_p5z
+   xremikc   =  0.25      ! remineralization rate of DOC
+   xremikn   =  0.35      ! remineralization rate of DON
+   xremikp   =  0.4       ! remineralization rate of DOP
+!   feratb    =  20E-6     ! Bacterial Fe/C ratio
+!   xkferb    =  3E-10     ! Half-saturation constant for bact. Fe/C
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampissbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampissbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/nampissbc	(revision 14097)
@@ -0,0 +1,39 @@
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+!              !  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_dust     = 'dust.orca'       ,     -1.           , 'dust'        ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_solub    = 'solubility.orca' ,    -12.           , 'solubility1' ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdic = 'river.orca'      ,    120.           , 'riverdic'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdoc = 'river.orca'      ,    120.           , 'riverdoc'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdin = 'river.orca'      ,    120.           , 'riverdin'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdon = 'river.orca'      ,    120.           , 'riverdon'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdip = 'river.orca'      ,    120.           , 'riverdip'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdop = 'river.orca'      ,    120.           , 'riverdop'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_riverdsi = 'river.orca'      ,    120.           , 'riverdsi'    ,  .true.      , .true. , 'yearly'  , ''       , ''    , ''
+   sn_ndepo    = 'ndeposition.orca',    -12.           , 'ndep'        ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_ironsed  = 'bathy.orca'      ,    -12.           , 'bathy'       ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+   sn_hydrofe  = 'hydrofe.orca'    ,    -12.           , 'epsdb'       ,  .false.     , .true. , 'yearly'  , ''       , ''    , ''
+!
+   cn_dir      = './'      !  root directory for the location of the dynamical files
+   ln_dust     =  .true.   ! boolean for dust input from the atmosphere
+   ln_solub    =  .true.   ! boolean for variable solubility of atm. Iron
+   ln_river    =  .true.   ! boolean for river input of nutrients
+   ln_ndepo    =  .true.   ! boolean for atmospheric deposition of N
+   ln_ironsed  =  .true.   ! boolean for Fe input from sediments
+   ln_ironice  =  .true.   ! boolean for Fe input from sea ice
+   ln_hydrofe  =  .true.   ! boolean for from hydrothermal vents
+   sedfeinput  =  2.e-9    ! Coastal release of Iron
+   distcoast   =  5.e3     ! Distance off the coast for Iron from sediments
+   dustsolub   =  0.02     ! Solubility of the dusta
+   mfrac       =  0.035    ! Fe mineral fraction of dust
+   wdust       =  2.0      ! Dust sinking speed 
+   icefeinput  =  15.e-9   ! Iron concentration in sea ice
+   nitrfix     =  1.e-7    ! Nitrogen fixation rate
+   diazolight  =  50.      ! Diazotrophs sensitivity to light (W/m2)
+   concfediaz  =  1.e-10   ! Diazotrophs half-saturation Cste for Iron
+   hratio      =  1.e+7    ! Fe to 3He ratio assumed for vent iron supply 
+!                          ! ln_ligand
+   lgw_rath    =  0.5      ! Weak ligand ratio from sed hydro sources 
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namptr
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namptr	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namptr	(revision 14097)
@@ -0,0 +1,6 @@
+!-----------------------------------------------------------------------
+&namptr        !   Poleward Transport Diagnostic                        (default: OFF)
+!-----------------------------------------------------------------------
+   ln_diaptr   = .false.   !  Poleward heat and salt transport (T) or not (F)
+   ln_subbas   = .false.   !  Atlantic/Pacific/Indian basins computation (T) or not
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namrun
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namrun	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namrun	(revision 14097)
@@ -0,0 +1,37 @@
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  Assimilation cycle index
+   cn_exp      =  "ORCA2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    5840   !  last  time step (std 5840)
+   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 hhmm
+   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=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_indir = "."         !  directory from which to read input ocean restarts
+      cn_ocerst_out   = "restart"   !  suffix of ocean restart name (output)
+      cn_ocerst_outdir = "."        !  directory in which to write output ocean restarts
+   ln_iscpl    = .false.   !  cavity evolution forcing or coupling to ice sheet model
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   ln_rst_list = .false.   !  output restarts at list of times using nn_stocklist (T) or at set frequency with nn_stock (F)
+   nn_stock    =       0   !  used only if ln_rst_list = F: output restart freqeuncy (modulo referenced to 1)
+      !                          !    =  0 force to write restart files only at the end of the run
+      !                          !    = -1 do not do any restart
+   nn_stocklist = 0,0,0,0,0,0,0,0,0,0 ! List of timesteps when a restart file is to be written
+   nn_write    =       0   !  used only if key_iomput is not defined: output frequency (modulo referenced to nn_it000)
+      !                          !    =  0 force to write output files only at the end of the run
+      !                          !    = -1 do not do any output file
+   ln_mskland  = .false.   !  mask land points in NetCDF outputs
+   ln_cfmeta   = .false.   !  output additional data to netCDF files required for compliance with the CF metadata standard
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+   nn_chunksz  =       0   !  chunksize (bytes) for NetCDF file (works only with iom_nf90 routines)
+   ln_xios_read = .FALSE.  !  use XIOS to read restart file (only for a single file restart)
+   nn_wxios = 0      !  use XIOS to write restart file 0 - no, 1 - single file output, 2 - multiple file output
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc	(revision 14097)
@@ -0,0 +1,46 @@
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 2         !  frequency of SBC module call
+      !                    !  (control sea-ice & iceberg model call)
+                     ! Type of air-sea fluxes 
+   ln_usr      = .false.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_flx      = .false.   !  flux formulation                          (T => fill namsbc_flx )
+   ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+      !              ! Type of coupling (Ocean/Ice/Atmosphere) :
+   ln_cpl      = .false.   !  atmosphere coupled   formulation          ( requires key_oasis3 )
+   ln_mixcpl   = .false.   !  forced-coupled mixed formulation          ( requires key_oasis3 )
+   nn_components = 0       !  configuration of the opa-sas OASIS coupling
+      !                    !  =0 no opa-sas OASIS coupling: default single executable config.
+      !                    !  =1 opa-sas OASIS coupling: multi executable config., OPA component
+      !                    !  =2 opa-sas OASIS coupling: multi executable config., SAS component 
+                     ! Sea-ice :
+   nn_ice      = 0         !  =0 no ice boundary condition    
+      !                    !  =1 use observed ice-cover                 (  => fill namsbc_iif )
+      !                    !  =2 or 3 automatically for SI3 or CICE    ("key_si3" or "key_cice")
+      !                    !          except in AGRIF zoom where it has to be specified
+   ln_ice_embd = .false.   !  =T embedded sea-ice (pressure + mass and salt exchanges)
+      !                    !  =F levitating ice (no pressure, mass and salt exchanges)
+                     ! Misc. options of sbc : 
+   ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr)
+   ln_dm2dc    = .false.   !  daily mean to diurnal cycle on short wave
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   nn_fwb      = 0         !  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_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
+   ln_isf      = .false.   !  ice shelf                                 (T   => fill namsbc_isf & namsbc_iscpl)
+   ln_wave     = .false.   !  Activate coupling with wave  (T => fill namsbc_wave)
+   ln_cdgw     = .false.   !  Neutral drag coefficient read from wave model (T => ln_wave=.true. & fill namsbc_wave)
+   ln_sdw      = .false.   !  Read 2D Surf Stokes Drift & Computation of 3D stokes drift (T => ln_wave=.true. & fill namsbc_wave) 
+   nn_sdrift   =  0        !  Parameterization for the calculation of 3D-Stokes drift from the surface Stokes drift
+      !                    !   = 0 Breivik 2015 parameterization: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
+      !                    !   = 1 Phillips:                      v_z=v_o*[exp(2*k*z)-beta*sqrt(-2*k*pi*z)*erfc(sqrt(-2*k*z))]
+      !                    !   = 2 Phillips as (1) but using the wave frequency from a wave model
+   ln_tauwoc   = .false.   !  Activate ocean stress modified by external wave induced stress (T => ln_wave=.true. & fill namsbc_wave)
+   ln_tauw     = .false.   !  Activate ocean stress components from wave model
+   ln_stcor    = .false.   !  Activate Stokes Coriolis term (T => ln_wave=.true. & ln_sdw=.true. & fill namsbc_wave)
+   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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_apr
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_apr	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_apr	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing           (ln_apr_dyn =T)
+!-----------------------------------------------------------------------
+   rn_pref     = 101000.   !  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
+
+   cn_dir = './'        !  root directory for the Patm data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_apr      = 'patm'                  ,         -1.       ,'somslpre' ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,      ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_blk
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_blk	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_blk	(revision 14097)
@@ -0,0 +1,35 @@
+!-----------------------------------------------------------------------
+&namsbc_blk    !   namsbc_blk  generic Bulk formula                     (ln_blk =T)
+!-----------------------------------------------------------------------
+   !                    !  bulk algorithm :
+   ln_NCAR     = .false.   ! "NCAR"      algorithm   (Large and Yeager 2008)
+   ln_COARE_3p0 = .false.   ! "COARE 3.0" algorithm   (Fairall et al. 2003)
+   ln_COARE_3p5 = .false.   ! "COARE 3.5" algorithm   (Edson et al. 2013)
+   ln_ECMWF    = .false.   ! "ECMWF"     algorithm   (IFS cycle 31)
+      !
+      rn_zqt      = 10.       !  Air temperature & humidity reference height (m)
+      rn_zu       = 10.       !  Wind vector reference height (m)
+      ln_Cd_L12   = .false.   !  air-ice drags = F(ice concentration) (Lupkes et al. 2012)
+      ln_Cd_L15   = .false.   !  air-ice drags = F(ice concentration) (Lupkes et al. 2015)
+      ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
+      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 used to
+      !                       !  calculate the wind stress (0.=absolute or 1.=relative winds)
+
+   cn_dir      = './'      !  root directory for the bulk data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!______________________________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ !       weights filename               ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                                      ! pairing  !    filename   !
+   sn_wndi     = 'u_10.15JUNE2009_fill'       ,    6.        , 'U_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'       ,    6.        , 'V_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bicubic_noc.nc'  , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'SWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'   ,   24.        , 'LWDN_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'       ,    6.        , 'T_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'       ,    6.        , 'Q_10_MOD',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'PRC_MOD1',   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill',   -1.        , 'SNOW'    ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_slp      = 'slp.15JUNE2009_fill'        ,    6.        , 'SLP'     ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_cc       = 'NOT USED'                   ,   24         , 'CC'      ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+   sn_tdif     = 'taudif_core'                ,   24         , 'taudif'  ,   .false.   , .true. , 'yearly'  , 'weights_core_orca2_bilinear_noc.nc' , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_cpl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_cpl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_cpl	(revision 14097)
@@ -0,0 +1,53 @@
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_oasis3")
+!-----------------------------------------------------------------------
+   nn_cplmodel       =     1   !  Maximum number of models to/from which NEMO is potentially 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)
+   ln_scale_ice_flux = .false. !  use ice fluxes that are already "ice weighted" ( i.e. multiplied ice concentration)
+   nn_cats_cpl       =     5   !  Number of sea ice categories over which coupling is to be carried out (if not 1)
+   !_____________!__________________________!____________!_____________!______________________!________!
+   !             !        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'    ,     ''      ,         ''           ,   ''
+   sn_snd_crtw   =   'none'                 ,    'no'    ,     ''      ,         ''           , 'U,V'
+   sn_snd_ifrac  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_wlev   =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_cond   =   'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_thick1 =   'ice and snow'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_mpnd   =   'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_sstfrz =   'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_ttilyr =   'weighted ice'         ,    '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_hsig   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_iceflx =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_mslp   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_phioc  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_sdrfx  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_sdrfy  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wper   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wnum   =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wstrf  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_ts_ice =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_isf    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_icb    =   'none'                 ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_rcv_tauwoc =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_tauw   =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_wdrag  =   'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_flx
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_flx	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_flx	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation        (ln_flx =T)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the fluxes data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  , ''               , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iif
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iif	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iif	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namsbc_iif    !   Ice-IF : use observed ice cover                      (nn_ice = 1)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the ice cover data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_ice      ='ice_cover_clim.nc'      ,        -12.       ,'ice_cover',   .true.    , .true.  , 'yearly'  ,   ''            ,   ''     ,   ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iscpl
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iscpl	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_iscpl	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+   nn_drown    = 10        ! number of iteration of the extrapolation loop (fill the new wet cells)
+   ln_hsb      = .false.   ! activate conservation module (conservation exact after a time of rn_fiscpl)
+   nn_fiscpl   = 43800     ! (number of time step) conservation period (maybe should be fix to the coupling frequencey of restart frequency)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_isf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_isf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_isf	(revision 14097)
@@ -0,0 +1,34 @@
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+   !                 ! type of top boundary layer 
+   nn_isf      = 1         !  ice shelf melting/freezing
+                           !  1 = presence of ISF   ;  2 = bg03 parametrisation 
+                           !  3 = rnf file for ISF  ;  4 = ISF specified freshwater flux
+                           !  options 1 and 4 need ln_isfcav = .true. (domzgr)
+      !              !  nn_isf = 1 or 2 cases:
+      rn_gammat0  = 1.e-4     ! gammat coefficient used in blk formula
+      rn_gammas0  = 1.e-4     ! gammas coefficient used in blk formula
+      !              !  nn_isf = 1 or 4 cases:
+      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
+      !              ! nn_isf = 1 case
+      nn_isfblk   = 1         ! 1 ISOMIP  like: 2 equations formulation (Hunter et al., 2006)
+      !                       ! 2 ISOMIP+ like: 3 equations formulation (Asay-Davis et al., 2015)
+      nn_gammablk = 1         ! 0 = cst Gammat (= gammat/s)
+      !                       ! 1 = velocity dependend Gamma (u* * gammat/s)  (Jenkins et al. 2010)
+      !                       ! 2 = velocity and stability dependent Gamma    (Holland et al. 1999)
+
+   !___________!_____________!___________________!___________!_____________!_________!___________!__________!__________!_______________!
+   !           !  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      !
+!* nn_isf = 4 case
+   sn_fwfisf   = 'rnfisf'    ,         -12.      ,'sowflisf' ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 3 case
+   sn_rnfisf   = 'rnfisf'    ,         -12.      ,'sofwfisf' ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 2 and 3 cases 
+   sn_depmax_isf ='rnfisf'   ,         -12.      ,'sozisfmax',  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+   sn_depmin_isf ='rnfisf'   ,         -12.      ,'sozisfmin',  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+!* nn_isf = 2 case
+   sn_Leff_isf = 'rnfisf'    ,         -12.      ,'Leff'     ,  .false.    , .true.  , 'yearly'  ,    ''    ,   ''     ,    ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_rnf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_rnf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_rnf	(revision 14097)
@@ -0,0 +1,25 @@
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs                                              (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .false.   !  specific treatment at rivers mouths
+      rn_hrnf     =  15.e0    !  depth over which enhanced vertical mixing is used    (ln_rnf_mouth=T)
+      rn_avt_rnf  =   1.e-3   !  value of the additional vertical mixing coef. [m2/s] (ln_rnf_mouth=T)
+   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
+   ln_rnf_depth_ini = .false. ! compute depth at initialisation from runoff file
+      rn_rnf_max  = 5.735e-4  !  max value of the runoff climatologie over global domain ( ln_rnf_depth_ini = .true )
+      rn_dep_max  = 150.      !  depth over which runoffs is spread ( ln_rnf_depth_ini = .true )
+      nn_rnf_depth_file = 0   !  create (=1) a runoff depth file or not (=0)
+
+   cn_dir      = './'      !  root directory for the runoff data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  , ''               , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_sas
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_sas	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_sas	(revision 14097)
@@ -0,0 +1,19 @@
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .true.    !  =T Read in file ;  =F set all to 0. (see sbcssm)
+      ln_3d_uve   = .false.   !  specify whether we are supplying a 3D u,v and e3 field
+      ln_read_frq = .false.   !  specify whether we must read frq or not
+
+   cn_dir      = './'      !  root directory for the ocean data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_usp      = 'sas_grid_U'            ,       120.        , 'uos'     ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_vsp      = 'sas_grid_V'            ,       120.        , 'vos'     ,   .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'  ,    ''            ,    ''    ,    ''
+   sn_e3t      = 'sas_grid_T'            ,       120.        , 'e3t_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+   sn_frq      = 'sas_grid_T'            ,       120.        , 'frq_m'   ,   .true.    , .true. , 'yearly'  ,    ''            ,    ''    ,    ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_ssr
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_ssr	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_ssr	(revision 14097)
@@ -0,0 +1,18 @@
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sstr     =     0     !  add a retroaction term to the surface heat flux (=1) or not (=0)
+      rn_dqdt     = -40.      !  magnitude of the retroaction on temperature   [W/m2/K]
+   nn_sssr     =     0     !  add a damping term to the surface freshwater flux (=2)
+      !                    !  or to SSS only (=1) or no damping term (=0)
+      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]
+
+   cn_dir      = './'      !  root directory for the SST/SSS data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_sst      = 'sst_data'              ,        24.        ,  'sst'    ,    .false.  , .false., 'yearly'  ,    ''            ,    ''    ,     ''
+   sn_sss      = 'sss_data'              ,        -1.        ,  'sss'    ,    .true.   , .true. , 'yearly'  ,    ''            ,    ''    ,     ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_wave
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_wave	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsbc_wave	(revision 14097)
@@ -0,0 +1,18 @@
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model                        (ln_wave=T)
+!-----------------------------------------------------------------------
+   cn_dir      = './'      !  root directory for the waves data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_cdg      =  'sdw_ecwaves_orca2'    ,        6.         , 'drag_coeff' ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_usd      =  'sdw_ecwaves_orca2'    ,        6.         , 'u_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_vsd      =  'sdw_ecwaves_orca2'    ,        6.         , 'v_sd2d'     ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_hsw      =  'sdw_ecwaves_orca2'    ,        6.         , 'hs'         ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wmp      =  'sdw_ecwaves_orca2'    ,        6.         , 'wmp'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wfr      =  'sdw_ecwaves_orca2'    ,        6.         , 'wfr'        ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_wnum     =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_num'   ,  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwoc   =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwx    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+   sn_tauwy    =  'sdw_ecwaves_orca2'    ,        6.         , 'wave_stress',  .true.  , .true. , 'yearly'  ,  ''              , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsto
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsto	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namsto	(revision 14097)
@@ -0,0 +1,16 @@
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_sto_eos  = .false.   ! stochastic equation of state
+   nn_sto_eos  = 1         ! number of independent random walks
+   rn_eos_stdxy = 1.4       ! random walk horz. standard deviation (in grid points)
+   rn_eos_stdz = 0.7       ! random walk vert. standard deviation (in grid points)
+   rn_eos_tcor = 1440.     ! random walk time correlation (in timesteps)
+   nn_eos_ord  = 1         ! order of autoregressive processes
+   nn_eos_flt  = 0         ! passes of Laplacian filter
+   rn_eos_lim  = 2.0       ! limitation factor (default = 3.0)
+   ln_rststo   = .false.   ! start from mean parameter (F) or from restart file (T)
+   ln_rstseed  = .true.    ! read seed of RNG from restart file
+   cn_storst_in  = "restart_sto" !  suffix of stochastic parameter restart file (input)
+   cn_storst_out = "restart_sto" !  suffix of stochastic parameter restart file (output)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd	(revision 14097)
@@ -0,0 +1,10 @@
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+   ln_icedH         = .true.          !  activate ice thickness change from growing/melting (T) or not (F)
+   ln_icedA         = .true.          !  activate lateral melting param. (T) or not (F)
+   ln_icedO         = .true.          !  activate ice growth in open-water (T) or not (F)
+   ln_icedS         = .true.          !  activate brine drainage (T) or not (F)
+   !                                   
+   ln_leadhfx       = .true.          !  heat in the leads is used to melt sea-ice before warming the ocean
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_da
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_da	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_da	(revision 14097)
@@ -0,0 +1,11 @@
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+   rn_beta          =   1.0           !  coef. beta for lateral melting param. Recommended range=[0.8-1.2]
+                                      !   => decrease = more melt and melt peaks toward higher concentration (A~0.5 for beta=1 ; A~0.8 for beta=0.2)
+                                      !      0.3 = best fit for western Fram Strait and Antarctica
+                                      !      1.4 = best fit for eastern Fram Strait      
+   rn_dmin          =   8.            !  minimum floe diameter for lateral melting param. Recommended range=[6-10]
+                                      !   => 6  vs 8m = +40% melting at the peak (A~0.5)
+                                      !      10 vs 8m = -20% melting
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_do
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_do	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_do	(revision 14097)
@@ -0,0 +1,9 @@
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+   rn_hinew         =   0.1           !  thickness for new ice formation in open water (m), must be larger than rn_himin
+   ln_frazil        = .false.         !  Frazil ice parameterization (ice collection as a function of wind)
+      rn_maxfraz    =   1.0           !     maximum fraction of frazil ice collecting at the ice base
+      rn_vfraz      =   0.417         !     thresold drift speed for frazil ice collecting at the ice bottom (m/s)
+      rn_Cfraz      =   5.0           !     squeezing coefficient for frazil ice collecting at the ice bottom
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_pnd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_pnd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_pnd	(revision 14097)
@@ -0,0 +1,13 @@
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+   ln_pnd            = .false.        !  activate melt ponds or not
+      ln_pnd_LEV     = .false.        !  level ice melt ponds (from Flocco et al 2007,2010 & Holland et al 2012)
+         rn_apnd_min =   0.15         !     minimum ice fraction that contributes to melt pond. range: 0.0 -- 0.15 ??
+         rn_apnd_max =   0.85         !     maximum ice fraction that contributes to melt pond. range: 0.7 -- 0.85 ??
+      ln_pnd_CST     = .false.        !  constant  melt ponds
+         rn_apnd     =   0.2          !     prescribed pond fraction, at Tsu=0 degC
+         rn_hpnd     =   0.05         !     prescribed pond depth,    at Tsu=0 degC
+      ln_pnd_lids    = .true.         !  frozen lids on top of the ponds (only for ln_pnd_LEV)
+      ln_pnd_alb     = .true.         !  effect of melt ponds on ice albedo
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_sal
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_sal	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_sal	(revision 14097)
@@ -0,0 +1,15 @@
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+   nn_icesal        =   2             !  ice salinity option
+                                      !     1: constant ice salinity (S=rn_icesal)
+                                      !     2: varying salinity parameterization S(z,t)
+                                      !     3: prescribed salinity profile S(z) (Schwarzacher 1959)
+   rn_icesal        =   4.            !      (nn_icesal=1) ice salinity (g/kg)
+   rn_sal_gd        =   5.            !      (nn_icesal=2) restoring ice salinity, gravity drainage (g/kg)
+   rn_time_gd       =   1.73e+6       !      (nn_icesal=2) restoring time scale,   gravity drainage  (s)
+   rn_sal_fl        =   2.            !      (nn_icesal=2) restoring ice salinity, flushing (g/kg)
+   rn_time_fl       =   8.64e+5       !      (nn_icesal=2) restoring time scale,   flushing (s)
+   rn_simax         =  20.            !  maximum tolerated ice salinity (g/kg)
+   rn_simin         =   0.1           !  minimum tolerated ice salinity (g/kg)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_zdf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_zdf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namthd_zdf	(revision 14097)
@@ -0,0 +1,14 @@
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+   ln_zdf_BL99      = .true.          !  Heat diffusion follows Bitz and Lipscomb 1999
+   ln_cndi_U64      = .false.         !  sea ice thermal conductivity: k = k0 + beta.S/T            (Untersteiner, 1964)
+   ln_cndi_P07      = .true.          !  sea ice thermal conductivity: k = k0 + beta1.S/T - beta2.T (Pringle et al., 2007)
+   rn_cnd_s         =   0.31          !  thermal conductivity of the snow (0.31 W/m/K, Maykut and Untersteiner, 1971)
+                                      !     Obs: 0.1-0.5 (Lecomte et al, JAMES 2013)
+   rn_kappa_i       =   1.0           !  radiation attenuation coefficient in sea ice                     [1/m]
+   rn_kappa_s       =  10.0           !  nn_qtrice = 0: radiation attenuation coefficient in snow         [1/m]
+   rn_kappa_smlt    =   7.0           !  nn_qtrice = 1: radiation attenuation coefficient in melting snow [1/m]
+   rn_kappa_sdry    =  10.0           !                 radiation attenuation coefficient in dry snow     [1/m]
+   ln_zdf_chkcvg    = .false.         !  check convergence of heat diffusion scheme (output variable: tice_cvg)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_adv
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_adv	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_adv	(revision 14097)
@@ -0,0 +1,16 @@
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .false. !  No tracer advection
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .false. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order 
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_dmp
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_dmp	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_dmp	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping                      (default: OFF)
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .false.  !  add a damping term (using resto.nc coef.)
+      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)
+      cn_resto = 'resto.nc'   !  Name of file containing restoration coeff. field (use dmp_tools to create this)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_eiv
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_eiv	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_eiv	(revision 14097)
@@ -0,0 +1,19 @@
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .false.   ! use eddy induced velocity parameterization
+      !
+      !                        !  Coefficients:
+      nn_aei_ijk_t    = 0           !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_induced_velocity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                        !  time invariant coefficients:  aei0 = 1/2  Ue*Le 
+      rn_Ue        = 0.02           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Le        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+      !
+      ln_ldfeiv_dia =.false.   ! diagnose eiv stream function and velocities
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_ldf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_ldf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_ldf	(revision 14097)
@@ -0,0 +1,35 @@
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   = .false.   !  No explicit diffusion
+   ln_traldf_lap   = .false.   !    laplacian operator
+   ln_traldf_blp   = .false.   !  bilaplacian operator
+   !
+   !                       !  Direction of action:
+   ln_traldf_lev   = .false.   !  iso-level
+   ln_traldf_hor   = .false.   !  horizontal  (geopotential)
+   ln_traldf_iso   = .false.   !  iso-neutral (standard operator)
+   ln_traldf_triad = .false.   !  iso-neutral (triad    operator)
+   !
+   !		       	         !  iso-neutral options:        
+   ln_traldf_msc   = .false.   !  Method of Stabilizing Correction      (both operators)
+   rn_slpmax       =  0.01     !  slope limit                           (both operators)
+   ln_triad_iso    = .false.   !  pure horizontal mixing in ML              (triad only)
+   rn_sw_triad     = 1         !  =1 switching triad ; =0 all 4 triads used (triad only)
+   ln_botmix_triad = .false.   !  lateral mixing on bottom                  (triad only)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 0         !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_diffusivity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant 
+      !                             !   = 10 F(k)      =ldf_c1d 
+      !                             !   = 20 F(i,j)    =ldf_c2d 
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                             !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+      !                        !  time invariant coefficients:  aht0 = 1/2  Ud*Ld   (lap case) 
+      !                             !                           or   = 1/12 Ud*Ld^3 (blp case)
+      rn_Ud        = 0.01           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_mle
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_mle	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_mle	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .false.   ! (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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_qsr
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_qsr	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtra_qsr	(revision 14097)
@@ -0,0 +1,19 @@
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .false.      !  RGB light penetration (Red-Green-Blue)
+   ln_qsr_2bd  = .false.      !  2BD light penetration (two bands)
+   ln_qsr_bio  = .false.      !  bio-model light penetration
+   !                       !  RGB & 2BD choices:
+   rn_abs      =   0.58       !  RGB & 2BD: fraction absorbed in the very near surface
+   rn_si0      =   0.35       !  RGB & 2BD: shortess depth of extinction
+   nn_chldta   =      0       !  RGB : Chl data (=1) or cst value (=0)
+   rn_si1      =   23.0       !  2BD : longest depth of extinction
+   
+   cn_dir      = './'      !  root directory for the chlorophyl data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! pairing  !    filename   !
+   sn_chl      ='chlorophyll'            ,        -1.        , 'CHLA'    ,   .true.    , .true. , 'yearly'  , ''               , ''       , ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc	(revision 14097)
@@ -0,0 +1,23 @@
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  0           !  Number of passive tracers of the BGC model
+   !
+   ln_pisces     =  .false.     !  Run PISCES BGC model 
+   ln_my_trc     =  .false.     !  Run MY_TRC BGC model
+   ln_age        =  .false.     !  Run the sea water age tracer
+   ln_cfc11      =  .false.     !  Run the CFC11 passive tracer
+   ln_cfc12      =  .false.     !  Run the CFC12 passive tracer
+   ln_sf6        =  .false.     !  Run the SF6 passive tracer
+   ln_c14        =  .false.     !  Run the Radiocarbon passive tracer
+   !
+   ln_trcdta     =  .false.  !  Initialisation from data input file (T) or not (F)
+   ln_trcdmp     =  .false.  !  add a damping termn (T) or not (F)
+   ln_trcdmp_clo =  .false.  !  damping term (T) or not (F) on closed seas
+   !
+   jp_dia3d      = 0         ! Number of 3D diagnostic variables
+   jp_dia2d      = 0         ! Number of 2D diagnostic variables
+   !_____________!___________!_________________________________________!____________!________________!
+   !             !    name   !           title of the field            !   units    ! init from file ! 
+!  sn_tracer(1)  = 'tracer  ', 'Tracer  Concentration                 ',   ' - '    ,   .false.
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_adv
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_adv	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_adv	(revision 14097)
@@ -0,0 +1,16 @@
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_OFF =  .false.  !  No passive tracer advection
+   ln_trcadv_cen =  .false.  !  2nd order centered scheme
+      nn_cen_h   =  4               !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4               !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_trcadv_fct =  .false.  !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+   ln_trcadv_mus =  .false.  !  MUSCL scheme
+      ln_mus_ups =  .false.         !  use upstream scheme near river mouths
+   ln_trcadv_ubs =  .false.  !  UBS scheme
+      nn_ubs_v   =  2               !  =2  , vertical 2nd order FCT
+   ln_trcadv_qck =  .false.  !  QUICKEST scheme
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bc
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bc	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bc	(revision 14097)
@@ -0,0 +1,9 @@
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+   cn_dir_sbc    =  './'     !  root directory for the location of SURFACE data files
+   cn_dir_cbc    =  './'     !  root directory for the location of COASTAL data files
+   cn_dir_obc    =  './'     !  root directory for the location of OPEN data files
+   ln_rnf_ctl    = .false.   !  Remove runoff dilution on tracers with absent river load
+   rn_bc_time    =  86400.   !  Time scaling factor for SBC and CBC data (seconds in a day)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bdy
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bdy	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_bdy	(revision 14097)
@@ -0,0 +1,11 @@
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+   cn_trc_dflt   = 'neumann' !  OBC applied by default to all tracers
+   cn_trc        = 'none'    !  Boundary conditions used for tracers with data files (selected in namtrc)
+
+   nn_trcdmp_bdy = 0         !  Use damping timescales defined in nambdy of namelist
+                             !  = 0 NO damping of tracers at open boudaries
+                             !  = 1 Only for tracers forced with external data
+                             !  = 2 Damping applied to all tracers
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dmp
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dmp	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dmp	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping                   (ln_trcdmp=T)
+!-----------------------------------------------------------------------
+   nn_zdmp_tr    =    1      !  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)
+   cn_resto_tr   = 'resto_tr.nc'    !  create a damping.coeff NetCDF file (=1) or not (=0)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dta
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dta	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_dta	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!                !  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_trcdta(1)  = 'data_TRC_nomask' ,        -12.       ,  'TRC'    ,    .false.   , .true. , 'yearly'  , ''       , ''       , ''
+   !
+   cn_dir        =  './'     !  root directory for the location of the data files
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ice
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ice	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ice	(revision 14097)
@@ -0,0 +1,8 @@
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+   nn_ice_tr     =  -1       !  tracer concentration in sea ice 
+                             !    =-1 (no vvl: identical cc in ice and ocean / vvl: cc_ice = 0)
+                             !    = 0 (no vvl: cc_ice = zero / vvl: cc_ice = )
+                             !    = 1 prescribed to a namelist value (implemented in pisces only)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ldf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ldf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_ldf	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+!                            !  Type of the operator:
+   ln_trcldf_OFF   =  .false.    !  No explicit diffusion
+   ln_trcldf_tra   =  .false.    !  use active tracer setting
+   !                         !  Coefficient (defined with namtra_ldf coefficient)
+   rn_ldf_multi    = 1.          !  multiplier of aht for TRC mixing coefficient
+   rn_fact_lap     = 1.          !  Equatorial enhanced zonal eddy diffusivity (lap only)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_rad
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_rad	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_rad	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+   ln_trcrad     =  .true.   !  artificially correct negative concentrations (T) or not (F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_run
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_run	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_run	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   nn_dttrc      =  1        !  time step frequency for passive sn_tracers
+   ln_top_euler  = .false.   !  use Euler time-stepping for TOP
+   ln_rsttr      = .false.   !  start from a restart file (T) or not (F)
+   nn_rsttr      =   0       !  restart control = 0 initial time step is not compared to the restart file value
+                             !                  = 1 do not use the value in the restart file
+                             !                  = 2 calendar parameters read in the restart file
+   cn_trcrst_in  = "restart_trc"   !  suffix of pass. sn_tracer restart name (input)
+   cn_trcrst_indir = "."           !  directory from which to read input passive tracer restarts
+   cn_trcrst_out = "restart_trc"   !  suffix of pass. sn_tracer restart name (output)
+   cn_trcrst_outdir = "."          !  directory to which to write output passive tracer restarts
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_snk
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_snk	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_snk	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namtrc_snk      !  Sedimentation of particles
+!-----------------------------------------------------------------------
+   nitermax      =  2   !  number of iterations for sedimentation
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_trd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_trd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrc_trd	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!                          or mixed-layer trends                        ('key_trdmld_trc')
+!----------------------------------------------------------------------
+   nn_trd_trc    =  5475     !  time step frequency and tracers trends
+   nn_ctls_trc   =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
+   rn_ucf_trc    =   1       !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
+   ln_trdmld_trc_restart = .false. !  restart for ML diagnostics
+   ln_trdmld_trc_instant = .true.  !  flag to diagnose trends of instantantaneous or mean ML T/S
+   ln_trdtrc( 1) = .true.
+   ln_trdtrc( 2) = .true.
+   ln_trdtrc(23) = .true.
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtrd	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+   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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtsd
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtsd	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namtsd	(revision 14097)
@@ -0,0 +1,14 @@
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+   !                       ! =T  read T-S fields for:
+   ln_tsd_init = .false.         !  ocean initialisation
+   ln_tsd_dmp  = .false.         !  T-S restoring   (see namtra_dmp)
+   
+   cn_dir      = './'      !  root directory for the T-S data location
+   !___________!_________________________!___________________!___________!_____________!________!___________!__________________!__________!_______________!
+   !           !  file name              ! frequency (hours) ! variable  ! time interp.!  clim  ! 'yearly'/ ! weights filename ! rotation ! land/sea mask !
+   !           !                         !  (if <0  months)  !   name    !   (logical) !  (T/F) ! 'monthly' !                  ! 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'  ,    ''            ,    ''    ,    ''
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namwad
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namwad	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namwad	(revision 14097)
@@ -0,0 +1,15 @@
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+   ln_wd_il    = .false.   !  T/F activation of iterative   limiter
+   ln_wd_dl    = .false.   !  T/F activation of directional limiter
+   ln_wd_dl_bc = .false.   !  T/F Directional limiteer Baroclinic option
+   ln_wd_dl_rmp = .false.  !  T/F Turn on directional limiter ramp
+   rn_wdmin0   =  0.30     !  depth at which WaD starts
+   rn_wdmin1   =  0.2      !  Minimum wet depth on dried cells
+   rn_wdmin2   =  0.0001   !  Tolerance of min wet depth on dried cells
+   rn_wdld     =  2.5      !  Land elevation below which WaD is allowed
+   nn_wdit     =   20      !  Max iterations for WaD limiter
+   rn_wd_sbcdep =  5.0     !  Depth at which to taper sbc fluxes
+   rn_wd_sbcfra =  0.999   !  Fraction of SBC fluxes at taper depth (Must be <1)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf	(revision 14097)
@@ -0,0 +1,35 @@
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! adaptive-implicit vertical advection
+   ln_zad_Aimp = .false.      !  Courant number dependent scheme (Shchepetkin 2015)
+   !
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .false.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   ln_zdfosm   = .false.      !  OSMOSIS BL closure                     (T =>   fill namzdf_osm)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_gls
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_gls	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_gls	(revision 14097)
@@ -0,0 +1,24 @@
+!-----------------------------------------------------------------------
+&namzdf_gls    !   GLS vertical diffusion                               (ln_zdfgls =T)
+!-----------------------------------------------------------------------
+   rn_emin       = 1.e-7   !  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.267   !  galperin limit
+   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
+   rn_hsro       =  0.02   !  Minimum surface roughness
+   rn_frac_hs    =   1.3   !  Fraction of wave height as roughness (if nn_z0_met>1)
+   nn_z0_met     =     2   !  Method for surface roughness computation (0/1/2/3)
+   !                             ! =3 requires ln_wave=T
+   nn_z0_ice     =   1     !  attenutaion of surface wave breaking under ice
+   !                       !           = 0 no impact of ice cover
+   !                       !           = 1 roughness uses rn_hsri and is weigthed by 1-TANH(10*fr_i)
+   !                       !           = 2 roughness uses rn_hsri and is weighted by 1-fr_i
+   !                       !           = 3 roughness uses rn_hsri and is weighted by 1-MIN(1,4*fr_i)
+   nn_bc_surf    =     1   !  surface condition (0/1=Dir/Neum)
+   nn_bc_bot     =     1   !  bottom 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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_iwm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_iwm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_iwm	(revision 14097)
@@ -0,0 +1,7 @@
+!-----------------------------------------------------------------------
+&namzdf_iwm    !    internal wave-driven mixing parameterization        (ln_zdfiwm =T)
+!-----------------------------------------------------------------------
+   nn_zpyc     = 1         !  pycnocline-intensified dissipation scales as N (=1) or N^2 (=2)
+   ln_mevar    = .true.    !  variable (T) or constant (F) mixing efficiency
+   ln_tsdiff   = .true.    !  account for differential T/S mixing (T) or not (F)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_osm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_osm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_osm	(revision 14097)
@@ -0,0 +1,19 @@
+!-----------------------------------------------------------------------
+&namzdf_osm    !   OSM vertical diffusion                               (ln_zdfosm =T)
+!-----------------------------------------------------------------------
+   ln_use_osm_la = .false.      !  Use namelist  rn_osm_la
+   rn_osm_la     = 0.3         !  Turbulent Langmuir number
+   rn_osm_dstokes     = 5.     !  Depth scale of Stokes drift (m)
+   nn_ave = 0                  ! choice of horizontal averaging on avt, avmu, avmv
+   ln_dia_osm = .true.         ! output OSMOSIS-OBL variables
+   rn_osm_hbl0 = 10.           ! initial hbl value
+   ln_kpprimix = .true.        ! Use KPP-style Ri# mixing below BL
+   rn_riinfty  = 0.7           ! Highest local Ri_g permitting shear instability
+   rn_difri  =  0.005          ! max Ri# diffusivity at Ri_g = 0 (m^2/s)
+   ln_convmix  = .true.        ! Use convective instability mixing below BL
+   rn_difconv = 1.             ! diffusivity when unstable below BL  (m2/s)
+   nn_osm_wave = 0             ! Method used to calculate Stokes drift
+      !                        !  = 2: Use ECMWF wave fields
+      !                        !  = 1: Pierson Moskowitz wave spectrum
+      !                        !  = 0: Constant La# = 0.3
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_ric
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_ric	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_ric	(revision 14097)
@@ -0,0 +1,13 @@
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       (ln_zdfric =T)
+!-----------------------------------------------------------------------
+   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
+   ln_mldw     =  .false.  !  enhanced mixing in the Ekman layer
+      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
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_tke
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_tke	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzdf_tke	(revision 14097)
@@ -0,0 +1,32 @@
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   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_pdl      =   1       !  Prandtl number function of richarson number (=1, avt=pdl(Ri)*avm) or not (=0, avt=avm)
+   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 dissipative an mixing length scale
+   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 NIWs
+                              !        = 0 none ; = 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           (ln_cpl=T)
+      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
+   nn_eice     =   1       !  attenutaion of langmuir & surface wave breaking under ice
+   !                       !           = 0 no impact of ice cover on langmuir & surface wave breaking
+   !                       !           = 1 weigthed by 1-TANH(10*fr_i)
+   !                       !           = 2 weighted by 1-fr_i
+   !                       !           = 3 weighted by 1-MIN(1,4*fr_i)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_domcfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_domcfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_domcfg	(revision 14097)
@@ -0,0 +1,9 @@
+!-----------------------------------------------------------------------
+&namzgr        !   vertical coordinate                                  (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zco      = .false.   !  z-coordinate - full    steps
+   ln_zps      = .false.   !  z-coordinate - partial steps
+   ln_sco      = .false.   !  s- or hybrid z-s-coordinate
+   ln_isfcav   = .false.   !  ice shelf cavity
+   ln_linssh   = .false.   !  linear free surface
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_sco_domcfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_sco_domcfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/namelists/namzgr_sco_domcfg	(revision 14097)
@@ -0,0 +1,25 @@
+!-----------------------------------------------------------------------
+&namzgr_sco    !   s-coordinate or hybrid z-s-coordinate                (default F)
+!-----------------------------------------------------------------------
+   ln_s_sh94   = .false.    !  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)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/Makefile
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/Makefile	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/Makefile	(revision 14097)
@@ -0,0 +1,159 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS    =
+SPHINXBUILD   = sphinx-build
+PAPER         =
+BUILDDIR      = build
+
+# Internal variables.
+PAPEROPT_a4     = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
+
+.PHONY: help clean html dirhtml drafthtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
+
+help:
+	@echo "Please use \`make <target>' where <target> is one of"
+	@echo "  html       to make standalone HTML files"
+	@echo "  dirhtml    to make HTML files named index.html in directories"
+	@echo "  drafthtml  to make an autoupdate HTML export while editing (todo list included)"
+	@echo "  singlehtml to make a single large HTML file"
+	@echo "  pickle     to make pickle files"
+	@echo "  json       to make JSON files"
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
+	@echo "  qthelp     to make HTML files and a qthelp project"
+	@echo "  devhelp    to make HTML files and a Devhelp project"
+	@echo "  epub       to make an epub"
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
+	@echo "  text       to make text files"
+	@echo "  man        to make manual pages"
+	@echo "  texinfo    to make Texinfo files"
+	@echo "  info       to make Texinfo files and run them through makeinfo"
+	@echo "  gettext    to make PO message catalogs"
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
+	@echo "  linkcheck  to check all external links for integrity"
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+	-rm -rf $(BUILDDIR)/*
+
+html:
+	$(SPHINXBUILD)   -b html          $(ALLSPHINXOPTS) $(BUILDDIR)/html
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+	$(SPHINXBUILD)   -b dirhtml       $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+drafthtml:
+	sphinx-autobuild -b html -t draft $(ALLSPHINXOPTS) $(BUILDDIR)/drafthtml
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/drafthtml."
+
+singlehtml:
+	$(SPHINXBUILD)   -b singlehtml    $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+	@echo
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+	$(SPHINXBUILD)   -b pickle        $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+	@echo
+	@echo "Build finished; now you can process the pickle files."
+
+json:
+	$(SPHINXBUILD)   -b json          $(ALLSPHINXOPTS) $(BUILDDIR)/json
+	@echo
+	@echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+	$(SPHINXBUILD)   -b htmlhelp      $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+	@echo
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+	$(SPHINXBUILD)   -b qthelp        $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+	@echo
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/NEMO.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/NEMO.qhc"
+
+devhelp:
+	$(SPHINXBUILD)   -b devhelp       $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+	@echo
+	@echo "Build finished."
+	@echo "To view the help file:"
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/NEMO"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/NEMO"
+	@echo "# devhelp"
+
+epub:
+	$(SPHINXBUILD)   -b epub          $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+	@echo
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+	$(SPHINXBUILD)   -b latex         $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
+	      "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+	$(SPHINXBUILD)   -b latex         $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo "Running LaTeX files through pdflatex..."
+	$(MAKE) -C $(BUILDDIR)/latex all-pdf
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+	$(SPHINXBUILD)   -b text          $(ALLSPHINXOPTS) $(BUILDDIR)/text
+	@echo
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+	$(SPHINXBUILD)   -b man           $(ALLSPHINXOPTS) $(BUILDDIR)/man
+	@echo
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+	$(SPHINXBUILD)   -b texinfo       $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+	@echo
+	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+	@echo "Run \`make' in that directory to run these through makeinfo" \
+	      "(use \`make info' here to do that automatically)."
+
+info:
+	$(SPHINXBUILD)   -b texinfo       $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+	@echo "Running Texinfo files through makeinfo..."
+	make -C $(BUILDDIR)/texinfo info
+	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+	$(SPHINXBUILD)   -b gettext      $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+	@echo
+	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+	$(SPHINXBUILD)   -b changes       $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+	@echo
+	@echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+	$(SPHINXBUILD)   -b linkcheck     $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+	@echo
+	@echo "Link check complete; look for any errors in the above output " \
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+	$(SPHINXBUILD)   -b doctest       $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+	@echo "Testing of doctests in the sources finished, look at the " \
+	      "results in $(BUILDDIR)/doctest/output.txt."
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/README.rst	(revision 14097)
@@ -0,0 +1,56 @@
+**********************
+NEMO Quick Start Guide
+**********************
+
+| The NEMO guide is made up of several files written in
+  `ReStructuredText <http://docutils.sourceforge.net/rst.html>`_ (`.rst` extension),
+  a WYSIWYG markup language used in the Python community, and scattered all over the NEMO sources.
+| You can view them one by one in plain text from `./source` folder, or export all to a user-friendly guide under `./build` (only HTML format at the moment, PDF expected later).
+
+Build and export the guide in HTML
+==================================
+
+1.  Install Sphinx documentation generator, its BibTeX extension and "Read The Docs" theme thanks to `pip` packages tool
+
+    .. code-block:: console
+
+        $ pip install sphinx sphinxcontrib.bibtex sphinx_rtd_theme
+
+2.  Build the HTML export with `make` in `./build/html`
+
+    .. code-block:: console
+
+        $ make html
+
+3.  Finally browse the guide by opening `./build/html/NEMO_guide.html`
+
+
+Edit the sources and check the output in real time
+==================================================
+
+| To facilitate the update of the guide, editors can install a useful package that will automatically trigger a new build and the reload of the HTML page for every recorded change in the sources.
+| So the reviewer saves time by controlling on-line their modifications almost as it types and also by avoiding repeated interactive rebuilds.
+
+Install `sphinx-autobuild` package
+
+.. code-block:: console
+
+	$ pip install sphinx-autobuild
+
+Launch a local web server hosting a draft export of the guide (build this time in `./build/livehtml`)
+
+.. code-block:: console
+
+    $ make livehtml
+
+| Open in the same time the 2 formats of the content to review: the source file and the web page by browsing from the new guide hosted by your local server on `<http://127.0.0.1:8000/NEMO_guide.html>`_.
+| Start the update, save your changes and verify instantly the HTML export in your browser.
+
+.. warning::
+
+    | Your modifications are not taken into account?
+    | For symlink file, you will have to close it to update the HTML export. Otherwise look at the log of the Sphinx build, you probably made a typo!
+
+.. hint::
+
+    Are there broken links? Fix "Page not found" errors by running `make linkcheck`
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_crs_def.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_crs_def.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_crs_def.xml	(revision 14097)
@@ -0,0 +1,80 @@
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+ <file_definition type="multiple_file" name="PATH_OUT/@expname@_@freq@" sync_freq="1d" min_digits="4">
+
+    <file_group id="1d" output_freq="1d"  split_freq="1d" output_level="10" enabled=".TRUE."> <!-- 1d files -->
+
+       <file id="file1" name_suffix="_gcrsT" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"       />
+          <field field_ref="toce"         name="votemper"  operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+          <field field_ref="soce"         name="vosaline"  operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+          <field field_ref="mldkz5"       name="somixhgt"  />
+       </file>
+
+       <file id="file2" name_suffix="_gcrsU" description="ocean T grid variables" >
+          <field field_ref="e3u"       name="e3u"           />
+          <field field_ref="uoce"      name="uo"       operation="instant" freq_op="1d" > @uoce_e3u / @e3u </field>
+       </file>
+
+       <file id="file3" name_suffix="_gcrsV" description="ocean T grid variables" >
+          <field field_ref="e3v"       name="e3v"           />
+          <field field_ref="voce"      name="vo"       operation="instant" freq_op="1d" > @voce_e3v / @e3v </field>
+       </file>
+
+       <file id="file4" name_suffix="_gcrsW" description="ocean T grid variables" >
+          <field field_ref="woce"        name="woce"        />
+          <field field_ref="avt"         name="difvho"   />
+       </file>
+
+       <file id="file5" name_suffix="_gcrsC" description="ocean T grid variables" >
+          <field field_ref="Alkalini" operation="instant" freq_op="1d" > @Alkalini_E3T / @e3t </field>
+          <field field_ref="O2"       operation="instant" freq_op="1d" > @O2_E3T / @e3t </field>
+          <field field_ref="Si"       operation="instant" freq_op="1d" > @Si_E3T / @e3t </field>
+          <field field_ref="PHY"      operation="instant" freq_op="1d" > @PHY_E3T / @e3t </field>
+          <field field_ref="ZOO"      operation="instant" freq_op="1d" > @ZOO_E3T / @e3t </field>
+          <field field_ref="DOC"      operation="instant" freq_op="1d" > @DOC_E3T / @e3t </field>
+          <field field_ref="NCHL"     operation="instant" freq_op="1d" > @NCHL_E3T / @e3t </field>
+          <field field_ref="DCHL"     operation="instant" freq_op="1d" > @DCHL_E3T / @e3t </field>
+          <field field_ref="NO3"      operation="instant" freq_op="1d" > @NO3_E3T / @e3t </field>
+       </file>
+
+    </file_group>
+
+    <file_group id="1mo" output_freq="1mo"  split_freq="1mo" output_level="10" enabled=".TRUE."> <!-- 1d files -->
+
+       <file id="file6" name_suffix="_gcrsC" description="ocean T grid variables" >
+          <field field_ref="DIC"      operation="instant" freq_op="1mo" > @DIC_E3T / @e3t </field>
+          <field field_ref="Alkalini" operation="instant" freq_op="1mo" > @Alkalini_E3T / @e3t </field>
+          <field field_ref="O2"       operation="instant" freq_op="1mo" > @O2_E3T / @e3t </field>
+          <field field_ref="CaCO3"    operation="instant" freq_op="1mo" > @CaCO3_E3T / @e3t </field>
+          <field field_ref="PO4"      operation="instant" freq_op="1mo" > @PO4_E3T / @e3t </field>
+          <field field_ref="POC"      operation="instant" freq_op="1mo" > @POC_E3T / @e3t </field>
+          <field field_ref="Si"       operation="instant" freq_op="1mo" > @Si_E3T / @e3t </field>
+          <field field_ref="PHY"      operation="instant" freq_op="1mo" > @PHY_E3T / @e3t </field>
+          <field field_ref="ZOO"      operation="instant" freq_op="1mo" > @ZOO_E3T / @e3t </field>
+          <field field_ref="DOC"      operation="instant" freq_op="1mo" > @DOC_E3T / @e3t </field>
+          <field field_ref="PHY2"     operation="instant" freq_op="1mo" > @PHY2_E3T / @e3t </field>
+          <field field_ref="ZOO2"     operation="instant" freq_op="1mo" > @ZOO2_E3T / @e3t </field>
+          <field field_ref="DSi"      operation="instant" freq_op="1mo" > @DSi_E3T / @e3t </field>
+          <field field_ref="Fer"      operation="instant" freq_op="1mo" > @Fer_E3T / @e3t </field>
+          <field field_ref="BFe"      operation="instant" freq_op="1mo" > @BFe_E3T / @e3t </field>
+          <field field_ref="GOC"      operation="instant" freq_op="1mo" > @GOC_E3T / @e3t </field>
+          <field field_ref="SFe"      operation="instant" freq_op="1mo" > @SFe_E3T / @e3t </field>
+          <field field_ref="DFe"      operation="instant" freq_op="1mo" > @DFe_E3T / @e3t </field>
+          <field field_ref="GSi"      operation="instant" freq_op="1mo" > @GSi_E3T / @e3t </field>
+          <field field_ref="NFe"      operation="instant" freq_op="1mo" > @NFe_E3T / @e3t </field>
+          <field field_ref="NCHL"     operation="instant" freq_op="1mo" > @NCHL_E3T / @e3t </field>
+          <field field_ref="DCHL"     operation="instant" freq_op="1mo" > @DCHL_E3T / @e3t </field>
+          <field field_ref="NO3"      operation="instant" freq_op="1mo" > @NO3_E3T / @e3t </field>
+          <field field_ref="NH4"      operation="instant" freq_op="1mo" > @NH4_E3T / @e3t </field>
+       </file>
+
+    </file_group>
+
+
+ </file_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_def.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_def.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/file_def.xml	(revision 14097)
@@ -0,0 +1,111 @@
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files        default value="9.96921e+36"                                  =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="multiple_file" name="PATH_OUT/@expname@_@freq@" sync_freq="1d" min_digits="4" >
+    
+     
+      <file_group id="1d" output_freq="1d" split_freq="1d" output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_gridT" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"        />
+          <field field_ref="toce"         name="votemper"   operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+        </file>
+
+	<file id="file2" name_suffix="_gridS" description="ocean T grid variables" >
+          <field field_ref="soce"         name="vosaline"   operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+        </file>
+
+	<file id="file3" name_suffix="_grid2D" description="ocean T grid variables" >
+	  <field field_ref="mldkz5"       name="somixhgt"   /> 
+	  <field field_ref="empmr"        name="sowaflup"   />
+          <field field_ref="empbmr"       name="sowaflupb"  />
+	  <field field_ref="fmmflx"       name="iowaflup"   />
+	  <field field_ref="ice_cover"    name="soicecov"   />
+	  <field field_ref="qsr"          name="soceshwf"   />
+	  <field field_ref="taum"         name="sowindsp"   />
+          <field field_ref="runoffs"      name="runoffs"   />
+        </file>
+	
+	<file id="file4" name_suffix="_gridU" description="ocean U grid variables" >
+          <field field_ref="e3u"          name="e3u"        />
+          <field field_ref="uocetr_eff"   name="uocetr_eff" /> 
+          <field field_ref="utau"         name="tauuo"      />
+        </file>
+	
+	<file id="file5" name_suffix="_gridV" description="ocean V grid variables" >
+          <field field_ref="e3v"          name="e3v"        />
+          <field field_ref="vocetr_eff"   name="vocetr_eff" /> 
+          <field field_ref="vtau"         name="tauvo"      />
+        </file>
+
+        <file id="file6" name_suffix="_gridW" description="ocean W grid variables" >
+          <field field_ref="e3w"          name="e3w"        />
+          <field field_ref="wocetr_eff"   name="wocetr_eff" /> 
+        </file>
+
+        <file id="file7" name_suffix="_gridKZ" description="ocean W grid variables" >
+          <field field_ref="avt"          name="voddmavs"   />
+        </file>
+
+        <file id="file8" name_suffix="_gridH" description="ocean W grid variables" >
+          <field field_ref="hdiv"      name="hdivtr"  long_name="horizontal divergence transport"   operation="average"  freq_op="1d" > @hdiv * @e3t </field> 
+        </file>
+
+      </file_group>
+
+      <file_group id="1mo" output_freq="1mo" split_freq="1mo" output_level="10" enabled=".TRUE." >  <!-- 5d files -->
+
+        <file id="file10" name_suffix="_gridT" description="ocean T grid variables" >
+          <field field_ref="e3t"          name="e3t"        />
+          <field field_ref="toce"         name="votemper"   operation="instant" freq_op="1d" > @toce_e3t / @e3t </field>
+        </file>
+
+        <file id="file11" name_suffix="_gridS" description="ocean T grid variables" >
+          <field field_ref="soce"         name="vosaline"   operation="instant" freq_op="1d" > @soce_e3t / @e3t </field>
+        </file>
+
+        <file id="file12" name_suffix="_grid2D" description="ocean T grid variables" >
+          <field field_ref="mldkz5"       name="somixhgt"   />
+          <field field_ref="empmr"        name="sowaflup"   />
+          <field field_ref="empbmr"       name="sowaflupb"  />
+          <field field_ref="fmmflx"       name="iowaflup"   />
+          <field field_ref="ice_cover"    name="soicecov"   />
+          <field field_ref="qsr"          name="soceshwf"   />
+          <field field_ref="taum"         name="sowindsp"   />
+          <field field_ref="runoffs"      name="runoffs"   />
+        </file>
+
+        <file id="file13" name_suffix="_gridU" description="ocean U grid variables" >
+          <field field_ref="e3u"          name="e3u"        />
+          <field field_ref="uocetr_eff"   name="uocetr_eff" /> 
+          <field field_ref="utau"         name="tauuo"      />
+        </file>
+
+        <file id="file14" name_suffix="_gridV" description="ocean V grid variables" >
+          <field field_ref="e3v"          name="e3v"        />
+          <field field_ref="vocetr_eff"   name="vocetr_eff" /> 
+          <field field_ref="vtau"         name="tauvo"      />
+        </file>
+
+        <file id="file15" name_suffix="_gridW" description="ocean W grid variables" >
+          <field field_ref="e3w"          name="e3w"        />
+          <field field_ref="wocetr_eff"   name="wocetr_eff" /> 
+        </file>
+
+        <file id="file16" name_suffix="_gridKZ" description="ocean W grid variables" >
+          <field field_ref="avt"          name="voddmavs"   />
+        </file>
+
+        <file id="file17" name_suffix="_gridH" description="ocean W grid variables" >
+          <field field_ref="hdiv"      name="hdivtr"  long_name="horizontal divergence transport"   operation="average"  freq_op="1d" > @hdiv * @e3t </field> 
+        </file>
+
+
+      </file_group>
+      
+   </file_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/iodef.xml	(revision 14097)
@@ -0,0 +1,194 @@
+<?xml version="1.0"?>
+<simulation> 
+
+ <context id="nemo" >
+    
+    <!-- $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 src="./file_def.xml"/>
+
+    <!--
+ 
+============================================================================================================
+= 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="1"                 />
+      <axis id="icbcla"  long_name="Iceberg class"      unit="1"                 />
+      <axis id="ncatice" long_name="Ice category"       unit="1"                 />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"              />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"              />
+   </axis_definition> 
+    
+   <domain_definition src="./domain_def.xml"/>
+   
+   <grid_definition>    
+     <grid id="grid_T_2D" >
+       <domain id="grid_T" />
+     </grid>
+     <grid id="grid_T_3D" >
+       <domain id="grid_T" />
+       <axis id="deptht" />
+     </grid>
+     <grid id="grid_U_2D" >
+       <domain id="grid_U" />
+     </grid>
+     <grid id="grid_U_3D" >
+       <domain id="grid_U" />
+       <axis id="depthu" />
+     </grid>
+     <grid id="grid_V_2D" >
+       <domain id="grid_V" />
+     </grid>
+     <grid id="grid_V_3D" >
+       <domain id="grid_V" />
+       <axis id="depthv" />
+     </grid>
+     <grid id="grid_W_2D" >
+       <domain id="grid_W" />
+     </grid>
+     <grid id="grid_W_3D" >
+       <domain id="grid_W" />
+       <axis id="depthw" />
+     </grid>
+     <grid id="scalarpoint" />
+
+    </grid_definition> 
+
+  </context>
+  
+    <!-- 
+============================================================================================================
+============================================================================================================
+============================================================================================================
+=                                                    CRS context
+============================================================================================================
+============================================================================================================
+============================================================================================================
+    -->
+
+ <context id="nemo_crs" >
+
+    <!-- $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 src="./file_crs_def.xml"/>
+
+    <!--
+ 
+============================================================================================================
+= 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="1"                 />
+      <axis id="icbcla"  long_name="Iceberg class"      unit="1"                 />
+      <axis id="ncatice" long_name="Ice category"       unit="1"                 />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"              />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"              />
+   </axis_definition>
+
+   <domain_definition src="./domain_def.xml"/>
+
+   <grid_definition>
+     <grid id="grid_T_2D" >
+       <domain id="grid_T" />
+     </grid>
+     <grid id="grid_T_3D" >
+       <domain id="grid_T" />
+       <axis id="deptht" />
+     </grid>
+     <grid id="grid_U_2D" >
+       <domain id="grid_U" />
+     </grid>
+     <grid id="grid_U_3D" >
+       <domain id="grid_U" />
+       <axis id="depthu" />
+     </grid>
+     <grid id="grid_V_2D" >
+       <domain id="grid_V" />
+     </grid>
+     <grid id="grid_V_3D" >
+       <domain id="grid_V" />
+       <axis id="depthv" />
+     </grid>
+     <grid id="grid_W_2D" >
+       <domain id="grid_W" />
+     </grid>
+     <grid id="grid_W_3D" >
+       <domain id="grid_W" />
+       <axis id="depthw" />
+     </grid>
+     <grid id="scalarpoint" />
+
+    </grid_definition>
+
+  </context>
+
+    <!-- 
+============================================================================================================
+============================================================================================================
+============================================================================================================
+=                                                    XIOS context
+============================================================================================================
+============================================================================================================
+============================================================================================================
+    -->
+
+  <context id="xios">
+
+      <variable_definition>
+	
+     <!-- 
+        We must have buffer_size > jpi*jpj*jpk*8 (with jpi and jpj the subdomain size)
+-->
+	  <variable id="info_level"                type="int">0</variable>
+	  <variable id="using_server"              type="bool">true</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+               
+  </context>
+  
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/style.css
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/style.css	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_static/style.css	(revision 14097)
@@ -0,0 +1,5 @@
+.blue            { color: blue    ; }
+.grey , .greysup { color: grey    ; }
+.green           { color: seagreen; }
+
+.logo { filter: invert(1) !important; }
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_templates/layout.html
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_templates/layout.html	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/_templates/layout.html	(revision 14097)
@@ -0,0 +1,18 @@
+{% extends "!layout.html" %}
+{% block extrahead %}
+	<link href="{{ pathto("_static/style.css", True) }}" rel="stylesheet" type="text/css">
+{% endblock %}
+
+{% block sidebartitle %}
+
+	<a href="{{ pathto(master_doc) }}">
+		<img src="{{ pathto('_static/NEMO_grey.png', 1) }}" class="logo" alt="Logo"/>
+	</a>
+
+	<p>Community ocean model for multifarious space and time scales</p>
+
+	<div class="version">{{ version }}</div>
+
+	{% include "searchbox.html" %}
+
+{% endblock %}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/acro.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/acro.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/acro.rst	(revision 14097)
@@ -0,0 +1,39 @@
+********
+Acronyms
+********
+
+.. todo::
+
+
+
+.. glossary::
+
+   `AGRIF`_
+      *Adaptive Grid Refinement In Fortran*,
+      package for the integration of full adaptive mesh refinement features within
+      an existing multidimensional finite difference model
+
+   SI\ :sup:`3`\
+      *Sea Ice Integrated Initiative*,
+      unified sea ice model merging functionalities from CICE, GELATO and LIM into the NEMO framework
+
+   `OASIS`_
+      *Ocean Atmosphere Sea Ice Soil*,
+      coupling software to synchronise numerical codes representing different components of the climate system
+
+   PISCES
+      *Pelagic Interactions Scheme for Carbon and Ecosystem Studies*,
+      biogeochemical model simulating marine ecosystems, cycles of carbon and the main nutrients
+
+   TAM
+      *Tangent linear and Adjoint Model*,
+      tools to analyse and control the NEMO dynamical core for a wide range of applications such as
+      sensitivity analysis, parameter estimation, vectors computation or data assimilation.
+
+   TOP
+      *Tracers in Ocean Paradigm*,
+      on/off-line oceanic tracers transport and biogeochemistry models
+
+   `XIOS`_
+      *XML Input Output Server*,
+      library dedicated to input/output management of climate code
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.bib	(revision 14097)
@@ -0,0 +1,25 @@
+@article{ODEA2012,
+author = {E J O’Dea and A K Arnold and K P Edwards and R Furner and P Hyder and M J Martin and J R Siddorn and D Storkey and J While and J T Holt and H Liu},
+title = {An operational ocean forecast system incorporating NEMO and SST data assimilation for the tidally driven European North-West shelf},
+journal = {Journal of Operational Oceanography},
+volume = {5},
+number = {1},
+pages = {3-17},
+year  = {2012},
+publisher = {Taylor & Francis},
+doi = {10.1080/1755876X.2012.11020128},
+URL = {https://doi.org/10.1080/1755876X.2012.11020128},
+eprint = {https://doi.org/10.1080/1755876X.2012.11020128}
+}
+
+@Article{gmd-8-2465-2015,
+AUTHOR = {Aumont, O. and Eth\'e, C. and Tagliabue, A. and Bopp, L. and Gehlen, M.},
+TITLE = {PISCES-v2: an ocean biogeochemical model for carbon and ecosystem studies},
+JOURNAL = {Geoscientific Model Development},
+VOLUME = {8},
+YEAR = {2015},
+NUMBER = {8},
+PAGES = {2465--2513},
+URL = {https://www.geosci-model-dev.net/8/2465/2015/},
+DOI = {10.5194/gmd-8-2465-2015}
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cfgs.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/changes.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/changes.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/changes.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../CHANGES.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cite.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cite.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cite.rst	(revision 14097)
@@ -0,0 +1,48 @@
+***********
+How to cite
+***********
+
+.. todo::
+
+
+
+|NEMO-OCE|
+   :title:`NEMO ocean engine`,
+   NEMO System Team,
+   Scientific Notes of Climate Modelling Center, 27,
+   ISSN 1288-1619 Institut Pierre-Simon Laplace (IPSL),
+   :doi:`10.5281/zenodo.1464816`
+
+.. literalinclude:: ref.bib
+   :language: bibtex
+   :lines:    1-9
+   :caption:  BibTeX source for NEMO manual
+
+|NEMO-ICE|
+   :title:`Sea Ice modelling Integrated Initiative (SI`\ :sup:`3`\ :title:`) --
+   The NEMO sea ice engine`,
+   NEMO Sea Ice Working Group,
+   Scientific Notes of Climate Modelling Center, 31,
+   ISSN 1288-1619 Institut Pierre-Simon Laplace (IPSL),
+   :doi:`10.5281/zenodo.1471689`
+
+.. warning::  No official publication yet
+
+.. literalinclude:: ref.bib
+   :language: bibtex
+   :lines:    13-21
+   :caption:  BibTeX source for SI\ :sup:`3` manual
+
+|NEMO-MBG|
+   :title:`Tracer in Ocean Paradigm (TOP) -- The NEMO passive tracer engine`,
+   NEMO TOP Working Group,
+   Scientific Notes of Climate Modelling Center, 28,
+   ISSN 1288-1619 Institut Pierre-Simon Laplace (IPSL),
+   :doi:`10.5281/zenodo.1471700`
+
+.. warning::  No official publication yet
+
+.. literalinclude:: ref.bib
+   :language: bibtex
+   :lines:    25-33
+   :caption:  BibTeX source for TOP manual
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/conf.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/conf.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/conf.py	(revision 14097)
@@ -0,0 +1,280 @@
+# -*- coding: utf-8 -*-
+#
+# NEMO documentation build configuration file, created by
+# sphinx-quickstart on Tue Oct 15 20:13:55 2019.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.extlinks', 'sphinxcontrib.bibtex',
+              'sphinx.ext.todo'    , 'sphinx.ext.autosectionlabel']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'guide'
+
+# General information about the project.
+project = u'NEMO'
+copyright = u'2019, NEMO Consortium'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '4.0'
+# The full version, including alpha/beta/rc tags.
+release = '4.0-HEAD'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['global.rst', 'readme.rst']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'emacs'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+html_theme = 'sphinx_rtd_theme'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+html_favicon = '_static/ORCA.ico'
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'NEMOdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+  ('guide', 'guide.tex', u'NEMO Quick Start Guide',
+   u'NEMO Consortium', 'howto'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    ('guide', 'nemo', u'NEMO Documentation',
+     [u'NEMO System Team'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output ------------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+#  dir menu entry, description, category)
+texinfo_documents = [
+  ('guide', 'NEMO', u'NEMO Documentation',
+   u'NEMO System Team', 'NEMO', 'Community Ocean Model',
+   'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# -- Customisation -------------------------------------------------------------
+
+# Timestamping
+import datetime
+year = datetime.date.today().year
+copyright = '2008-' + str( year ) + ', NEMO Consortium'
+
+# Link aliases
+extlinks = {
+   'doi'    : ('https://doi.org/%s'                                                    , 'doi:'),
+   'manhtml': ('https://forge.ipsl.jussieu.fr/nemo/chrome/site/doc/NEMO/manual/html/%s', None  ),
+   'forge'  : ('https://forge.ipsl.jussieu.fr/nemo/%s'                                 , None  ),
+   'gmd'    : ('https://www.geosci-model-dev.net/%s'                                   , None  ),
+   'github' : ('https://github.com/NEMO-ocean/%s'                                      , None  ),
+   'xios'   : ('https://forge.ipsl.jussieu.fr/ioserver/%s'                             , None  ),
+   'website': ('https://www.nemo-ocean.eu/%s'                                          , None  ),
+   'zenodo' : ('https://zenodo.org/publication/%s'                                     , None  )
+}
+
+# Include common directives for every rst file
+rst_epilog = open('global.rst', 'r').read()
+
+# SVN revision
+import subprocess
+rev = subprocess.check_output("svnversion").decode("utf-8")
+rst_prolog = '.. |revision| replace:: %s' % rev
+
+# 'draft' build tag: DRAFT watermark and TODO list
+if tags.has('draft'):
+   todo_include_todos = True
+   todo_emit_warnings = True
+else:
+   exclude_patterns = ['global.rst', 'readme.rst', 'todos.rst', 'unpub*']
+
+# Default language to highlight set to fortran
+highlight_language = 'fortran'
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/contrib.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/contrib.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/contrib.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../CONTRIBUTING.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cplg.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cplg.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/cplg.rst	(revision 14097)
@@ -0,0 +1,21 @@
+********
+Coupling
+********
+
+.. todo::
+
+   The ‘Coupling’ chapter needs to be enriched
+
+NEMO currently exploits OASIS-3-MCT (versions 1 to 4) to implement a generalised coupled interface
+(:manhtml:`Coupled Formulation <node50.html>`).
+It can be used to interface with most of the European atmospheric GCM
+(ARPEGE, ECHAM, ECMWF, Ha- dAM, HadGAM, LMDz), as well as to regional atmospheric models
+(WRF, COSMO, Meso-NH, AROME).
+To implement the coupling of two independent NEMO components,
+ocean on one hand and sea-ice plus other surface processes on the other hand
+(:manhtml:`Standalone Surface Module - SAS <node46.html>`).
+
+To enable the OASIS interface the required compilation key is ``key_oasis3``.
+You must also add ``key_oasis3_v1v2`` if you use OASIS-3-MCT version 1 and 2.
+The parameters to set are in sections ``&namsbc_cpl`` and
+in case of using of SAS also in section ``&namsbc_sas``.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/da.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/da.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/da.rst	(revision 14097)
@@ -0,0 +1,68 @@
+*****************
+Data assimilation
+*****************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+The assimilation interface to NEMO is split into three modules.
+
+- ``OBS`` for the observation operator
+- ``ASM`` for the application of increments and model bias correction
+  (based on the assimilation increments).
+- ``TAM`` the tangent linear and adjoint model.
+
+Please see :doc:`NEMO manual <cite>` for more details including
+information about the input file formats and the namelist settings.
+
+Observation and model comparison (``OBS``)
+==========================================
+
+The observation and model comparison code (OBS) reads in observation files
+(profile temperature and salinity, sea surface temperature, sea level anomaly, sea ice concentration,
+and velocity) and calculates an interpolated model equivalent value at
+the observation location and nearest model timestep.
+The resulting data are saved in a feedback file (or files).
+The code was originally developed for use with the NEMOVAR data assimilation code, but
+can be used for validation or verification of model or any other data assimilation system.
+This is all controlled by the namelist.
+To build with the OBS code active ``key_diaobs`` must be set.
+
+More details in :manhtml:`"Observation and Model Comparison (OBS)" chapter <node83.html>`.
+
+Standalone observation operator (``SAO``)
+-----------------------------------------
+
+The OBS code can also be run after a model run using saved NEMO model data.
+This is accomplished using the standalone observation operator (SAO)
+(previously known the offline observation operator).
+
+To build the SAO use :file:`makenemo`.
+This means compiling NEMO once (in the normal way) for the chosen configuration.
+Then include ``SAO`` at the end of the relevant line in :file:`cfg.txt` file.
+Then recompile with the replacement main program in :file:`./src/SAO`.
+This is a special version of :file:`nemogcm.F90` (which doesn't run the model,
+but reads in the model fields, and observations and runs the OBS code.
+See :manhtml:`"Standalone observation operator (SAO)" section <node88.html>`.
+
+Apply assimilation increments (``ASM``)
+=======================================
+
+The ASM code adds the functionality to apply increments to the model variables:
+temperature, salinity, sea surface height, velocity and sea ice concentration.
+These are read into the model from a NetCDF file which
+may be produced by separate data assimilation code.
+The code can also output model background fields which are used as an input to data assimilation code.
+This is all controlled by the namelist ``&nam_asminc``.
+To build the ASM code ``key asminc`` must be set.
+
+More details in :manhtml:`"Apply Assimilation Increments (ASM)" chapter <node89.html>`.
+
+Tangent linear and adjoint (``TAM``)
+====================================
+
+This is the tangent linear and adjoint code of NEMO which is useful to 4D VAR assimilation.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/diags.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/diags.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/diags.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/docutils.conf
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/docutils.conf	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/docutils.conf	(revision 14097)
@@ -0,0 +1,2 @@
+[restructuredtext parser]
+syntax_highlight = short
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/global.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/global.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/global.rst	(revision 14097)
@@ -0,0 +1,79 @@
+.. Roles
+
+.. custom styles related to CSS classes in './_static/style.css'
+
+.. role:: blue
+.. role:: green
+.. role:: grey
+.. role:: greysup(sup)
+
+.. inline code snippets
+
+.. role:: python(code)
+   :language: python
+   :class: highlight
+
+.. role:: fortran(code)
+   :language: fortran
+   :class: highlight
+
+.. role:: console(code)
+   :language: console
+   :class: highlight
+
+.. Substitutions
+
+.. |NEMO-OCE| replace::  :blue:`NEMO-OCE (Ocean dynamics)`
+.. |OCE|      replace::  :blue:`NEMO-OCE`
+.. |NEMO-ICE| replace::  :grey:`NEMO-SI`\ :greysup:`3`  :grey:`(Sea Ice)`
+.. |ICE|      replace::  :grey:`NEMO-SI`\ :greysup:`3`
+.. |NEMO-MBG| replace:: :green:`NEMO-TOP/PISCES (Tracers)`
+.. |MBG|      replace:: :green:`NEMO-TOP/PISCES`
+
+.. External links
+
+   .. Consortium institutes
+
+.. _CMCC:       https://www.cmcc.it
+.. _CNRS:       https://www.cnrs.fr
+.. _Met Office: https://www.metoffice.gov.uk
+.. _MOI:        https://www.mercator-ocean.fr
+.. _NERC:       https://nerc.ukri.org
+
+   .. Models / Libraries / Dependencies
+
+.. _AGRIF:  http://agrif.imag.fr
+.. _BFM:    http://www.bfm-community.eu
+.. _FCM:    https://metomi.github.io/fcm
+.. _IOIPSL: https://forge.ipsl.jussieu.fr/igcmg/browser/IOIPSL
+.. _NEMO:   https://www.nemo-ocean.eu
+.. _OASIS:  https://portal.enes.org/oasis
+.. _XIOS:   https://forge.ipsl.jussieu.fr/ioserver
+
+   .. Misc.
+
+.. _EGU: http://www.egu.eu
+.. _Special Issue: https://www.geosci-model-dev.net/special_issue40.html
+.. _BFM man: https://cmcc-foundation.github.io/www.bfm-community.eu/files/bfm-nemo-manual_r1.0_201508.pdf
+.. _RST man: https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html
+.. _PAPA station: http://www.pmel.noaa.gov/OCS/Papa/index-Papa.shtml
+.. _ISOMIP: http://staff.acecrc.org.au/~bkgalton/ISOMIP/test_cavities.pdf
+
+.. DOI
+
+   .. Publications (`:samp:` to deactivate link for unpublished documents)
+
+.. _DOI man OCE:          https://doi.org/10.5281/zenodo.1464816
+.. _DOI man ICE:   :samp: https://doi.org/10.5281/zenodo.1471689
+.. _DOI man MBG:   :samp: https://doi.org/10.5281/zenodo.1471700
+.. _DOI qsg:       :samp: https://doi.org/10.5281/zenodo.1475325
+.. _DOI dev  stgy:        https://doi.org/10.5281/zenodo.1471663
+.. _DOI data:             https://doi.org/10.5281/zenodo.1472245
+
+   .. Badges (same labels as previously, substitution to link images)
+
+.. |DOI man OCE| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1464816.svg
+.. |DOI man ICE| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1471689.svg
+.. |DOI man MBG| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1471700.svg
+.. |DOI qsg|     image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1475325.svg
+.. |DOI data|    image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1472245.svg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/guide.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/guide.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/guide.rst	(revision 14097)
@@ -0,0 +1,76 @@
+#################
+Quick Start Guide
+#################
+
+.. For headings markup, this convention is recommended from Python’s Style Guide
+   # with overline, for parts
+   * with overline, for chapters
+   =, for sections
+   -, for subsections
+   ^, for subsubsections
+   ", for paragraphs
+
+   'global.rst' contains a list of roles, substitutions and URL links for the guide.
+   It is loaded for each file with the 'rst_epilog' setting in 'conf.py'
+
+.. toctree::
+   :hidden:
+
+   todos
+
+.. Only displayed with 'make drafthtml'
+
+.. toctree::
+   :hidden:
+   :caption: Unpublished READMEs
+   :glob:
+   :titlesonly:
+
+   unpub/*
+
+.. Only displayed with 'make drafthtml'
+
+.. toctree::
+   :hidden:
+   :caption: Getting started
+
+   install
+   cfgs
+   tests
+
+.. toctree::
+   :hidden:
+   :caption: Setup your configuration
+
+   setup
+   diags
+   tools
+
+.. toctree::
+   :hidden:
+   :caption: Advanced use
+
+   zooms
+   cplg
+   da
+   tracers
+
+.. toctree::
+   :hidden:
+   :caption: Miscellaneous
+
+   cite
+   contrib
+   changes
+   acro
+
+:Release:  |release|
+
+.. only:: draft
+
+   .. Only on draft
+
+   :*Date*:     |today|
+   :*SVN rev*:  |revision|
+
+.. include:: readme.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/install.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/install.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/install.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../INSTALL.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/readme.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/readme.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/readme.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/ref.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/ref.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/ref.bib	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../REFERENCES.bib
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/setup.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/setup.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/setup.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../src/OCE/USR/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.bib	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../tests/test_cases.bib
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tests.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../tests/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/todos.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/todos.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/todos.rst	(revision 14097)
@@ -0,0 +1,5 @@
+*********************
+List of editing tasks
+*********************
+
+.. todolist::
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tools.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tools.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tools.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../tools/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tracers.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tracers.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/tracers.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../src/TOP/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/crs.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/crs.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/crs.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../../src/OCE/CRS/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/doc.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/doc.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/doc.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/src.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/src.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/unpub/src.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../../src/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.bib	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/AGRIF_DEMO/zooms.bib
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/rst/source/zooms.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/AGRIF_DEMO/README.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/check_pkg.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/check_pkg.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/check_pkg.py	(revision 14097)
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+
+import sys, importlib
+
+for argv in sys.argv[1:]:
+	try:
+		importlib.import_module(argv)
+	except ImportError:
+		print("Package %s is missing in Python" % argv)
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/manuals_checking.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/manuals_checking.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/manuals_checking.sh	(revision 14097)
@@ -0,0 +1,80 @@
+#!/bin/sh
+
+#set -evx
+
+if [[ $* != '' ]]; then
+	 if [[ $1 = 'all' ]]; then models='NEMO SI3 TOP'; else models=$1; fi
+else
+	 models='NEMO'
+fi
+
+for model in $models; do
+	 [[ $model =~ ^(SI3|TOP)$ ]] && continue
+
+    files=$( find latex/$model -type f -name *.tex )
+
+	 echo '¤ Missing namelist groups in '$model' manual'
+
+	 for nlst in $( ls namelists ); do
+        [[ ! $( grep \\nlst{$nlst} $files ) ]] && printf '%s ' $nlst
+	 done
+
+    echo; echo
+	 echo '¤ Vanished index entries in '$model' manual (\{hf,jp,key,mdl,ngn,nlst,np,rou}{...})'
+
+    for file in $files; do
+
+        items=$( grep -Eho "(hf|jp|key|mdl|ngn|nlst|np|rou){[a-zA-Z0-9_\]*}" $file | sort -u )
+
+        if [[ $items == '' ]]; then
+            continue
+        else
+            printf ${file/latex\/*\/subfiles\/}': '
+        fi
+
+        for item in $items; do
+
+            arg=$( echo $item | sed 's/.*{\([^}]*\)}/\1/' | tr -d '\\' )
+
+		      if [[ ( $item =~ ^hf   && ! $( find ../src -type f -name   $arg.h90               ) ) || \
+                  ( $item =~ ^jp   && ! $( grep ":: *$arg"             ../src/OCE/par_oce.F90 ) ) || \
+                  ( $item =~ ^key  && ! $( grep -ri "#if .* $arg"      ../src                 ) ) || \
+		            ( $item =~ ^mdl  && ! $( find ../src -type f -name   $arg.[Ff]90            ) ) || \
+                  ( $item =~ ^ngn  && ! $( grep \&$arg                 namelists/*            ) ) || \
+                  ( $item =~ ^nlst && ! -f namelists/$arg                                       ) || \
+                  ( $item =~ ^np   && ! $( grep " $arg *="             namelists/*            ) ) || \
+                  ( $item =~ ^rou  && ! $( grep -ri "SUBROUTINE *$arg" ../src                 ) )      ]]; then
+                printf $item' '
+            fi
+
+        done
+
+        echo
+
+    done
+
+done
+
+echo
+echo '¤ Namelist parameters unfollowing naming conventions (^[cdlnr]n_* or uppercase somewhere)'
+
+for nlst in $( ls namelists ); do
+    np_list=$( sed '/^ *[!/&]/d; s|[!/&].*||' namelists/$nlst | tr -d ' ' | cut -d= -f1 )
+    array=()
+
+    for np in ${np_list}; do
+
+        if [[ ! ${np:0:3} =~ ^[cdlnr]n_$ || $( echo $np | grep [A-Z] ) ]]; then
+            array+=$np' '
+        fi
+
+    done
+
+	 if (( ${#array[@]} != 0 )); then
+        printf '%15s: ' $nlst
+        echo ${array[@]}
+    fi
+
+done
+
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_releases.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_releases.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_releases.sh	(revision 14097)
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+## Estimate changes in namelists between two releases
+#####################################################
+
+## Prerequisites: f90nml to parse Fortran namelists (http://f90nml.readthedocs.org)
+## Launch under ./doc, edit the path to previous namelists accordingly
+
+for nlst in ../../releases/release-3.6/DOC/Namelists/*; do
+
+    if [ -f namelists/$( basename $nlst ) ]; then
+        printf "%s: " $( basename $nlst )
+        f90nml namelists/$( basename $nlst ) | awk '/=/ { print $0 }' | sort > nlst_new.txt
+        f90nml                       $nlst   | awk '/=/ { print $0 }' | sort > nlst_old.txt
+
+        if [[ $( diff -q nlst_*.txt ) ]]; then
+            diff -y --suppress-common-lines nlst_*.txt | wc -l
+        else
+            echo 0
+        fi
+
+    fi
+
+done | sort -k2rn
+
+\rm nlst_*.txt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_update.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_update.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/nlsts_update.sh	(revision 14097)
@@ -0,0 +1,247 @@
+#! /bin/sh
+#
+#       usage for NEMO doc to create an update of the Namelists directory :
+# 1- delete the existing directory (You can also choose to save it somewhere) 
+#    rm -rf Namelists
+# 2- create the updated Namelists directory from the SHARED/namelist_ref :
+#    ./namelist_split.sh -i ../NEMOGCM/CONFIG/SHARED/namelist_ref -o Namelists
+#
+# .. _namelist_split.sh:
+#
+# =================
+# namelist_split.sh
+# =================
+#
+# ----------------
+# split a namelist
+# ----------------
+#
+# SYNOPSIS
+# ========
+#
+# .. code-block:: bash
+#
+#    namelist_split.sh -i namelist -o dirout [-n]
+#
+# DESCRIPTION
+# ===========
+#
+# Split a namelist file (NEMO convention syntax) given in parameter
+# into files in a given output directory.
+#
+# .. option:: -i <input file (namelist)>
+# .. option:: -o <output directory>
+# .. option:: -n <numbered output files>
+#
+# Each file of the output directory is named after the *block* it contains.
+#
+# We assume here that the input file is written with this pattern of block:
+#
+# .. parsed-literal::
+#
+#    !---------------
+#    &nameblock
+#    !---------------
+#    var1 = val1
+#    ...
+#    varn = valn
+#    /
+#
+# If ``-n`` option is used, files in the directory output are named after
+# the number of the block it contains and the name of this block. This might
+# be useful to recombine blocks in the same order.
+#
+# EXAMPLES
+# ========
+#
+# To split the namelist NEMO ORCA2_LIM experiment 00 if you are in NEMO
+# working space :
+#
+# .. code-block:: bash
+#
+#    namelist_split.sh -i CONFIG/ORCA2_LIM/EXP00/namelist -o /tmp/EXP00_namelist_split/
+#
+# To split the namelist under data directory with numbered files:
+#
+# .. code-block:: bash
+#
+#    namelist_split.sh -i ./data/namelist -o /tmp/EXP00_namelist_split/ -n
+#
+# Check can be made by concatenation of files in output directory if ``-n``
+# option have been used and comparison with original file :
+#
+# .. code-block:: bash
+#
+#    cat /tmp/EXP00_namelist_split/b???_* > /tmp/EXP00_namelist_rebuild
+#    sdiff -w80 ./data/namelist /tmp/EXP00_namelist_rebuild
+#
+# Output contains lines which are before the first block, after the last
+# block and lines between blocks.
+#
+# EVOLUTIONS
+# ==========
+#
+# $Id$
+#
+# - fplod 2008-08-11T08:56:44Z aedon.locean-ipsl.upmc.fr (Darwin)
+#
+#   * commentaires dans ce fichier en reStructuredText
+#     cf. reStructuredText_ and Docutils_
+#
+# .. _reStructuredText: http://docutils.sourceforge.net/rst.html
+# .. _Docutils: http://docutils.sourceforge.net/
+#
+# - fplod 2008-07-22T12:41:04Z aedon.locean-ipsl.upmc.fr (Darwin)
+#
+#   * creation with test on
+#     http://forge.ipsl.jussieu.fr/nemo/browser/trunk/CONFIG/ORCA2_LIM/EXP00/namelist revision 1151
+#-
+#
+system=$(uname)
+case "${system}" in
+    AIX|IRIX64)
+        echo " www : no specific posix checking"
+    ;;
+    *)
+        #set -o posix
+    ;;
+esac
+unset system
+#
+command=$(basename ${0})
+log_date=$(date -u +"%Y%m%dT%H%M%SZ")
+#
+usage=" Usage : ${command} -i namelist -o dirout [-n]"
+#
+# default
+blocknum=0
+#
+minargcount=4
+if [ ${#} -lt ${minargcount} ]
+then
+    echo "eee : not enough arguments"
+    echo "${usage}"
+    exit 1
+fi
+#
+while [ ${#} -gt 0 ]
+do
+    case ${1} in
+        -i)
+            filein=${2}
+            shift
+        ;;
+        -o)
+            dirout=${2}
+            shift
+        ;;
+        -h)
+            echo "${usage}"
+            exit 0
+        ;;
+        -n)
+            blocknum=1
+        ;;
+        *)
+            # anything else
+            echo "eee : unknown option ${1}"
+            echo "eee : ${usage}"
+            exit 1
+        ;;
+    esac
+    # next flag
+    shift
+done
+unset usage
+#
+set -u
+#
+# check for filein
+if [ ! -r ${filein} ]
+then
+    echo "eee : ${filein} not accessible"
+    exit 1
+fi
+#
+# check for dirout
+# the idea is to prevent unwanted overwrite
+if [ -d ${dirout} ]
+then
+    echo "eee : ${dirout} already exist"
+    exit 1
+else
+    mkdir -p ${dirout}
+    if [ ${?} -ne 0 ]
+    then
+        echo "eee : cannot create ${dirout}"
+        exit 1
+    fi
+fi
+#
+# loop on each line of ${filein} ie the namelist to be split
+fileout=/dev/null
+begin=0
+if [ ${blocknum} -eq 1 ]
+then
+    iblock=0
+fi
+nbline=$(wc -l ${filein} | awk '{print $1}')
+il=1
+while [ ${il} -le ${nbline} ]
+do
+    line=$(sed -ne "${il},${il}p" ${filein})
+    # if current line start with "&", we can establish the name of output file
+    echo ${line} | grep -q "^&"
+    if [ ${?} -eq 0 ]
+    then
+        begin=1
+        # the form of this line is "&block   !"
+        block=${line#&}
+        block=${block%% *}
+        echo "iii : detection of the beginning of ${block}"
+        if [ ${blocknum} -eq 1 ]
+        then
+            iblock=$(( ${iblock} + 1))
+            fileout=${dirout}/b$(echo ${iblock} | awk '{printf "%3.3d", $1}')_${block}
+        else
+            fileout="${dirout}/${block}"
+        fi
+        # check for ${fileout}
+        if [ -f ${fileout} ]
+        then
+            echo "eee : ${fileout} already exists"
+            exit 1
+        fi
+        # write the previous line and the current line
+        echo "${memoline}" > ${fileout}
+        echo "${line}" >> ${fileout}
+    fi
+    # if current line contains "/" there will be no more lines to put in fileout
+    echo ${line} | grep -q "^/$"
+    if [ ${?} -eq 0 ]
+    then
+        echo "iii : detection of the end of ${block}"
+        echo "${line}" >> ${fileout}
+        fileout="/dev/null"
+    fi
+    # if current line is between "&" and "/", it should be written in fileout
+    # if current line is before the first &, it won't be written
+    if [ "${fileout}" != "/dev/null" ]
+    then
+        if [ ${begin} -eq 0 ]
+        then
+            echo "${line}" >> ${fileout}
+        fi
+    fi
+    # keep memory of this current line to use it if the next one is the
+    # beginning of a block
+    memoline=${line}
+    begin=0
+    # next line
+    il=$(( ${il} + 1 ))
+done
+#
+echo "iii : ${filein} is split in ${dirout}"
+#
+# end
+exit 0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/shr_func.sh
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/shr_func.sh	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/doc/tools/shr_func.sh	(revision 14097)
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+clean() {
+    printf "\t¤ Clean previous build"
+    find latex/$1/build -mindepth 1 -delete
+
+    echo
+}
+
+build() {
+    printf "\t¤ Generation of the PDF format\n"
+    latexmk -r  ./latex/global/latexmk.pl -pdfxe ./latex/$1/main/$1_manual \
+#	1> /dev/null
+    [ -f ./latex/$1/build/$1_manual.pdf ] && mv ./latex/$1/build/$1_manual.pdf .
+    echo
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice.F90	(revision 14097)
@@ -0,0 +1,527 @@
+MODULE ice
+   !!======================================================================
+   !!                        ***  MODULE  ice  ***
+   !!   sea-ice:  ice variables defined in memory
+   !!======================================================================
+   !! History :  3.0  !  2008-03  (M. Vancoppenolle) Original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_alloc   ! called by icestp.F90
+
+   !!======================================================================
+   !!                                                                     |
+   !!              I C E   S T A T E   V A R I A B L E S                  |
+   !!                                                                     |
+   !! Introduction :                                                      |
+   !! --------------                                                      |
+   !! Every ice-covered grid cell is characterized by a series of state   |
+   !! variables. To account for unresolved spatial variability in ice     |
+   !! thickness, the ice cover in divided in ice thickness categories.    |
+   !!                                                                     |
+   !! Sea ice state variables depend on the ice thickness category        |
+   !!                                                                     |
+   !! Those variables are divided into two groups                         |
+   !! * Extensive (or global) variables.                                  |
+   !!   These are the variables that are transported by all means         |
+   !! * Intensive (or equivalent) variables.                              |
+   !!   These are the variables that are either physically more           |
+   !!   meaningful and/or used in ice thermodynamics                      |
+   !!                                                                     |
+   !! List of ice state variables :                                       |
+   !! -----------------------------                                       |
+   !!                                                                     |
+   !!-------------|-------------|---------------------------------|-------|
+   !!   name in   |   name in   |              meaning            | units |
+   !! 2D routines | 1D routines |                                 |       |
+   !!-------------|-------------|---------------------------------|-------|
+   !!                                                                     |
+   !! ******************************************************************* |
+   !! ***         Dynamical variables (prognostic)                    *** |
+   !! ******************************************************************* |
+   !!                                                                     |
+   !! u_ice       |      -      |    ice velocity in i-direction  | m/s   |
+   !! v_ice       |      -      |    ice velocity in j-direction  | m/s   |
+   !!                                                                     |
+   !! ******************************************************************* |
+   !! ***         Category dependent state variables (prognostic)     *** |
+   !! ******************************************************************* |
+   !!                                                                     |
+   !! ** Global variables                                                 |
+   !!-------------|-------------|---------------------------------|-------|
+   !! a_i         |   a_i_1d    |    Ice concentration            |       |
+   !! v_i         |      -      |    Ice volume per unit area     | m     |
+   !! v_s         |      -      |    Snow volume per unit area    | m     |
+   !! sv_i        |      -      |    Sea ice salt content         | pss.m |
+   !! oa_i        |      -      |    Sea ice areal age content    | s     |
+   !! e_i         |             |    Ice enthalpy                 | J/m2  | 
+   !!             |    e_i_1d   |    Ice enthalpy per unit vol.   | J/m3  | 
+   !! e_s         |             |    Snow enthalpy                | J/m2  | 
+   !!             |    e_s_1d   |    Snow enthalpy per unit vol.  | J/m3  | 
+   !! a_ip        |      -      |    Ice pond concentration       |       |
+   !! v_ip        |      -      |    Ice pond volume per unit area| m     |
+   !! v_il        |    v_il_1d  |    Ice pond lid volume per area | m     |
+   !!                                                                     |
+   !!-------------|-------------|---------------------------------|-------|
+   !!                                                                     |
+   !! ** Equivalent variables                                             |
+   !!-------------|-------------|---------------------------------|-------|
+   !!                                                                     |
+   !! h_i         | h_i_1d      |    Ice thickness                | m     |
+   !! h_s         ! h_s_1d      |    Snow depth                   | m     |
+   !! s_i         ! s_i_1d      |    Sea ice bulk salinity        ! pss   |
+   !! sz_i        ! sz_i_1d     |    Sea ice salinity profile     ! pss   |
+   !! o_i         !      -      |    Sea ice Age                  ! s     |
+   !! 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     |
+   !! h_ip        | h_ip_1d     |    Ice pond thickness           | m     |
+   !! h_il        | h_il_1d     |    Ice pond lid thickness       | m     |
+   !!                                                                     |
+   !! notes: the ice model only sees a bulk (i.e., vertically averaged)   |
+   !!        salinity, except in thermodynamic computations, for which    |
+   !!        the salinity profile is computed as a function of bulk       |
+   !!        salinity                                                     |
+   !!                                                                     |
+   !!        the sea ice surface temperature is not associated to any     |
+   !!        heat content. Therefore, it is not a state variable and      |
+   !!        does not have to be advected. Nevertheless, it has to be     |
+   !!        computed to determine whether the ice is melting or not      |
+   !!                                                                     |
+   !! ******************************************************************* |
+   !! ***         Category-summed state variables (diagnostic)        *** |
+   !! ******************************************************************* |
+   !! 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     |
+   !! st_i        |      -      |    Total Sea ice salt content   | pss.m |
+   !! sm_i        |      -      |    Mean sea ice salinity        | pss   |
+   !! tm_i        |      -      |    Mean sea ice temperature     | K     |
+   !! tm_s        |      -      |    Mean snow    temperature     | K     |
+   !! et_i        |      -      |    Total ice enthalpy           | J/m2  | 
+   !! et_s        |      -      |    Total snow enthalpy          | J/m2  | 
+   !! bv_i        |      -      |    relative brine volume        | ???   | 
+   !! at_ip       |      -      |    Total ice pond concentration |       |
+   !! hm_ip       |      -      |    Mean ice pond depth          | m     |
+   !! vt_ip       |      -      |    Total ice pond vol. per unit area| m |
+   !! hm_il       |      -      |    Mean ice pond lid depth      | m     |
+   !! vt_il       |      -      |    Total ice pond lid vol. per area | m |
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !! * Share Module variables
+   !!----------------------------------------------------------------------
+   !                                     !!** ice-generic parameters namelist (nampar) **
+   INTEGER           , PUBLIC ::   jpl              !: number of ice  categories 
+   INTEGER           , PUBLIC ::   nlay_i           !: number of ice  layers 
+   INTEGER           , PUBLIC ::   nlay_s           !: number of snow layers 
+   LOGICAL           , PUBLIC ::   ln_virtual_itd   !: virtual ITD mono-category parameterization (T) or not (F)
+   LOGICAL           , PUBLIC ::   ln_icedyn        !: flag for ice dynamics (T) or not (F)
+   LOGICAL           , PUBLIC ::   ln_icethd        !: flag for ice thermo   (T) or not (F)
+   REAL(wp)          , PUBLIC ::   rn_amax_n        !: maximum ice concentration Northern hemisphere
+   REAL(wp)          , PUBLIC ::   rn_amax_s        !: maximum ice concentration Southern hemisphere
+   CHARACTER(len=256), PUBLIC ::   cn_icerst_in     !: suffix of ice restart name (input)
+   CHARACTER(len=256), PUBLIC ::   cn_icerst_out    !: suffix of ice restart name (output)
+   CHARACTER(len=256), PUBLIC ::   cn_icerst_indir  !: ice restart input directory
+   CHARACTER(len=256), PUBLIC ::   cn_icerst_outdir !: ice restart output directory
+
+   !                                     !!** ice-itd namelist (namitd) **
+   REAL(wp), PUBLIC ::   rn_himin         !: minimum ice thickness
+   
+   !                                     !!** ice-dynamics namelist (namdyn) **
+   REAL(wp), PUBLIC ::   rn_ishlat        !: lateral boundary condition for sea-ice
+   LOGICAL , PUBLIC ::   ln_landfast_L16  !: landfast ice parameterizationfrom lemieux2016 
+   REAL(wp), PUBLIC ::   rn_lf_depfra     !:    fraction of ocean depth that ice must reach to initiate landfast ice
+   REAL(wp), PUBLIC ::   rn_lf_bfr        !:    maximum bottom stress per unit area of contact (lemieux2016) or per unit volume (home) 
+   REAL(wp), PUBLIC ::   rn_lf_relax      !:    relaxation time scale (s-1) to reach static friction
+   REAL(wp), PUBLIC ::   rn_lf_tensile    !:    isotropic tensile strength
+   !
+   !                                     !!** ice-ridging/rafting namelist (namdyn_rdgrft) **
+   REAL(wp), PUBLIC ::   rn_crhg          !: determines changes in ice strength (also used for landfast param)
+   !
+   !                                     !!** ice-rheology namelist (namdyn_rhg) **
+   LOGICAL , PUBLIC ::   ln_aEVP          !: using adaptive EVP (T or F) 
+   REAL(wp), PUBLIC ::   rn_creepl        !: creep limit : has to be under 1.0e-9
+   REAL(wp), PUBLIC ::   rn_ecc           !: eccentricity of the elliptical yield curve
+   INTEGER , PUBLIC ::   nn_nevp          !: number of iterations for subcycling
+   REAL(wp), PUBLIC ::   rn_relast        !: ratio => telast/rdt_ice (1/3 or 1/9 depending on nb of subcycling nevp) 
+   INTEGER , PUBLIC ::   nn_rhg_chkcvg    !: check ice rheology convergence 
+   !
+   !                                     !!** ice-advection namelist (namdyn_adv) **
+   LOGICAL , PUBLIC ::   ln_adv_Pra       !: Prather        advection scheme
+   LOGICAL , PUBLIC ::   ln_adv_UMx       !: Ultimate-Macho advection scheme
+   !
+   !                                     !!** ice-surface boundary conditions namelist (namsbc) **
+                                          ! -- icethd_dh -- !
+   REAL(wp), PUBLIC ::   rn_snwblow       !: coef. for partitioning of snowfall between leads and sea ice
+                                          ! -- icethd_zdf and icealb -- !
+   INTEGER , PUBLIC ::   nn_snwfra        !: calculate the fraction of ice covered by snow
+   !                                      !   = 0  fraction = 1 (if snow) or 0 (if no snow)
+   !                                      !   = 1  fraction = 1-exp(-0.2*rhos*hsnw) [MetO formulation]
+   !                                      !   = 2  fraction = hsnw / (hsnw+0.02)    [CICE formulation]
+                                          ! -- icethd -- !
+   REAL(wp), PUBLIC ::   rn_cio           !: drag coefficient for oceanic stress
+   INTEGER , PUBLIC ::   nn_flxdist       !: Redistribute heat flux over ice categories
+   !                                      !   =-1  Do nothing (needs N(cat) fluxes)
+   !                                      !   = 0  Average N(cat) fluxes then apply the average over the N(cat) ice 
+   !                                      !   = 1  Average N(cat) fluxes then redistribute over the N(cat) ice using T-ice and albedo sensitivity
+   !                                      !   = 2  Redistribute a single flux over categories
+                                          ! -- icethd_zdf -- !
+   LOGICAL , PUBLIC ::   ln_cndflx        !: use conduction flux as surface boundary condition (instead of qsr and qns) 
+   LOGICAL , PUBLIC ::   ln_cndemulate    !: emulate conduction flux (if not provided) 
+   !                                      ! Conduction flux as surface forcing or not
+   INTEGER, PUBLIC, PARAMETER ::   np_cnd_OFF = 0  !: no forcing from conduction flux (ice thermodynamics forced via qsr and qns)
+   INTEGER, PUBLIC, PARAMETER ::   np_cnd_ON  = 1  !: forcing from conduction flux (SM0L) (compute qcn and qsr_tr via sbcblk.F90 or sbccpl.F90)
+   INTEGER, PUBLIC, PARAMETER ::   np_cnd_EMU = 2  !: emulate conduction flux via icethd_zdf.F90 (BL99) (1st round compute qcn and qsr_tr, 2nd round use it)
+   INTEGER, PUBLIC ::   nn_qtrice         !: Solar flux transmitted thru the surface scattering layer:
+   !                                      !   = 0  Grenfell and Maykut 1977 (depends on cloudiness and is 0 when there is snow) 
+   !                                      !   = 1  Lebrun 2019 (equals 0.3 anytime with different melting/dry snw conductivities)
+   !
+   !                                     !!** ice-vertical diffusion namelist (namthd_zdf) **
+   LOGICAL , PUBLIC ::   ln_cndi_U64      !: thermal conductivity: Untersteiner (1964)
+   LOGICAL , PUBLIC ::   ln_cndi_P07      !: thermal conductivity: Pringle et al (2007)
+   REAL(wp), PUBLIC ::   rn_cnd_s         !: thermal conductivity of the snow [W/m/K]   
+   REAL(wp), PUBLIC ::   rn_kappa_i       !: coef. for the extinction of radiation in sea ice, Grenfell et al. (2006) [1/m]
+   REAL(wp), PUBLIC ::   rn_kappa_s       !: coef. for the extinction of radiation in snw (nn_qtrice=0) [1/m]
+   REAL(wp), PUBLIC ::   rn_kappa_smlt    !: coef. for the extinction of radiation in melt snw (nn_qtrice=1) [1/m]
+   REAL(wp), PUBLIC ::   rn_kappa_sdry    !: coef. for the extinction of radiation in dry  snw (nn_qtrice=1) [1/m]
+   LOGICAL , PUBLIC ::   ln_zdf_chkcvg    !: check convergence of heat diffusion scheme
+
+   !                                     !!** ice-salinity namelist (namthd_sal) **
+   INTEGER , PUBLIC ::   nn_icesal        !: 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
+   REAL(wp), PUBLIC ::   rn_icesal        !: bulk salinity (ppt) in case of constant salinity
+   REAL(wp), PUBLIC ::   rn_simax         !: maximum ice salinity [PSU]
+   REAL(wp), PUBLIC ::   rn_simin         !: minimum ice salinity [PSU]
+
+   !                                     !!** ice-ponds namelist (namthd_pnd)
+   LOGICAL , PUBLIC ::   ln_pnd           !: Melt ponds (T) or not (F)
+   LOGICAL , PUBLIC ::   ln_pnd_LEV       !: Melt ponds scheme from Holland et al (2012), Flocco et al (2007, 2010)
+   REAL(wp), PUBLIC ::   rn_apnd_min      !: Minimum ice fraction that contributes to melt ponds
+   REAL(wp), PUBLIC ::   rn_apnd_max      !: Maximum ice fraction that contributes to melt ponds
+   LOGICAL , PUBLIC ::   ln_pnd_CST       !: Melt ponds scheme with constant fraction and depth
+   REAL(wp), PUBLIC ::   rn_apnd          !: prescribed pond fraction (0<rn_apnd<1)
+   REAL(wp), PUBLIC ::   rn_hpnd          !: prescribed pond depth    (0<rn_hpnd<1)
+   LOGICAL,  PUBLIC ::   ln_pnd_lids      !: Allow ponds to have frozen lids
+   LOGICAL , PUBLIC ::   ln_pnd_alb       !: melt ponds affect albedo
+
+   !                                     !!** ice-diagnostics namelist (namdia) **
+   LOGICAL , PUBLIC ::   ln_icediachk     !: flag for ice diag (T) or not (F)
+   REAL(wp), PUBLIC ::   rn_icechk_cel    !: rate of ice spuriously gained/lost (at any gridcell)
+   REAL(wp), PUBLIC ::   rn_icechk_glo    !: rate of ice spuriously gained/lost (globally)
+   LOGICAL , PUBLIC ::   ln_icediahsb     !: flag for ice diag (T) or not (F)
+   LOGICAL , PUBLIC ::   ln_icectl        !: flag for sea-ice points output (T) or not (F)
+   INTEGER , PUBLIC ::   iiceprt          !: debug i-point
+   INTEGER , PUBLIC ::   jiceprt          !: debug j-point
+
+   !                                     !!** some other parameters 
+   INTEGER , PUBLIC ::   kt_ice           !: iteration number
+   REAL(wp), PUBLIC ::   rdt_ice          !: ice time step
+   REAL(wp), PUBLIC ::   r1_rdtice        !: = 1. / rdt_ice
+   REAL(wp), PUBLIC ::   r1_nlay_i        !: 1 / nlay_i
+   REAL(wp), PUBLIC ::   r1_nlay_s        !: 1 / nlay_s 
+   REAL(wp), PUBLIC ::   rswitch          !: switch for the presence of ice (1) or not (0)
+   REAL(wp), PUBLIC ::   rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft   !: conservation diagnostics
+   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 
+
+   !                                     !!** define arrays
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_oce,v_oce     !: surface ocean velocity used in ice dynamics
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ht_i_new        !: ice collection thickness accreted in leads
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   strength        !: ice strength
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   stress1_i, stress2_i, stress12_i   !: 1st, 2nd & diagonal stress tensor element
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   delta_i         !: ice rheology elta factor (Flato & Hibler 95) [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   divu_i          !: Divergence of the velocity field             [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   shear_i         !: Shear of the velocity field                  [s-1]
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   t_bo            !: Sea-Ice bottom temperature [Kelvin]     
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qlead           !: heat balance of the lead (or of the open ocean)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qsb_ice_bot     !: 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         !: mass flux from snow-ocean mass exchange             [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_snw_sni     !: mass flux from snow ice growth component of wfx_snw [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_snw_sum     !: mass flux from surface melt component of wfx_snw    [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_pnd         !: mass flux from melt pond-ocean mass exchange        [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_spr         !: mass flux from snow precipitation on ice            [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_sub         !: mass flux from sublimation of snow/ice              [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_snw_sub     !: mass flux from snow sublimation                     [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_ice_sub     !: mass flux from ice sublimation                      [kg.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_snw_dyn     !: mass flux from dynamical component of wfx_snw       [kg.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_ice         !: mass flux from ice-ocean mass exchange                   [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_sni         !: mass flux from snow ice growth component of wfx_ice      [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_opw         !: mass flux from lateral ice growth component of wfx_ice   [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_bog         !: mass flux from bottom ice growth component of wfx_ice    [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_dyn         !: mass flux from dynamical ice growth component of wfx_ice [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_bom         !: mass flux from bottom melt component of wfx_ice          [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_sum         !: mass flux from surface melt component of wfx_ice         [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_lam         !: mass flux from lateral melt component of wfx_ice         [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_res         !: mass flux from residual component of wfx_ice             [kg.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wfx_err_sub     !: mass flux error after sublimation                        [kg.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_bog         !: salt flux due to ice bottom growth                   [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_bom         !: salt flux due to ice bottom melt                     [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_lam         !: salt flux due to ice lateral melt                    [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_sum         !: salt flux due to ice surface melt                    [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_sni         !: salt flux due to snow-ice growth                     [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_opw         !: salt flux due to growth in open water                [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_bri         !: salt flux due to brine rejection                     [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_dyn         !: salt flux due to porous ridged ice formation         [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_res         !: salt flux due to correction on ice thick. (residual) [pss.kg.m-2.s-1 => g.m-2.s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sfx_sub         !: salt flux due to ice sublimation                     [pss.kg.m-2.s-1 => g.m-2.s-1]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_bog         !: total heat flux causing bottom ice growth           [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_bom         !: total heat flux causing bottom ice melt             [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_sum         !: total heat flux causing surface ice melt            [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_opw         !: total heat flux causing open water ice formation    [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_dif         !: total heat flux causing Temp change in the ice      [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_snw         !: heat flux for snow melt                             [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_err_dif     !: heat flux remaining due to change in non-solar flux [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qt_atm_oi       !: heat flux at the interface atm-[oce+ice]            [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qt_oce_ai       !: heat flux at the interface oce-[atm+ice]            [W.m-2]
+   
+   ! heat flux associated with ice-atmosphere mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_sub         !: heat flux for sublimation            [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_spr         !: heat flux of the snow precipitation  [W.m-2]
+
+   ! heat flux associated with ice-ocean mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_thd         !: ice-ocean heat flux from thermo processes (icethd_dh) [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_dyn         !: ice-ocean heat flux from ridging                      [W.m-2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hfx_res         !: heat flux due to correction on ice thick. (residual)  [W.m-2]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rn_amax_2d      !: maximum ice concentration 2d array
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qtr_ice_bot     !: transmitted solar radiation under ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   t1_ice          !: temperature of the first layer          (ln_cndflx=T) [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   cnd_ice         !: effective conductivity of the 1st layer (ln_cndflx=T) [W.m-2.K-1]
+
+   !!----------------------------------------------------------------------
+   !! * Ice global state variables
+   !!----------------------------------------------------------------------
+   !! Variables defined for each ice category
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   h_i           !: Ice thickness                           (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_i           !: Ice fractional areas (concentration)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_i           !: Ice volume per unit area                (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_s           !: Snow volume per unit area               (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   h_s           !: Snow thickness                          (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   t_su          !: Sea-Ice Surface Temperature             (K)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   s_i           !: Sea-Ice Bulk salinity                   (pss)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sv_i          !: Sea-Ice Bulk salinity * volume per area (pss.m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   o_i           !: Sea-Ice Age                             (s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   oa_i          !: Sea-Ice Age times ice area              (s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   bv_i          !: brine volume
+
+   !! Variables summed over all categories, or associated to all the ice in a single grid cell
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   u_ice, v_ice  !: components of the ice velocity                          (m/s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   vt_i , vt_s   !: ice and snow total volume per unit area                 (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   st_i          !: Total ice salinity content                              (pss.m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   at_i          !: ice total fractional area (ice concentration)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   ato_i         !: =1-at_i ; total open water fractional area
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   et_i , et_s   !: ice and snow total heat content                         (J/m2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   tm_i          !: mean ice temperature over all categories                (K)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   tm_s          !: mean snw temperature over all categories                (K)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   bvm_i         !: brine volume averaged over all categories
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   sm_i          !: mean sea ice salinity averaged over all categories      (pss)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   tm_su         !: mean surface temperature over all categories            (K)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   hm_i          !: mean ice  thickness over all categories                 (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   hm_s          !: mean snow thickness over all categories                 (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   om_i          !: mean ice age over all categories                        (s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   tau_icebfr    !: ice friction on ocean bottom (landfast param activated)
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   t_s           !: Snow temperatures     [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_s           !: Snow enthalpy         [J/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   t_i           !: ice temperatures      [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_i           !: ice enthalpy          [J/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   sz_i          !: ice salinity          [PSS]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_ip          !: melt pond concentration
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_ip          !: melt pond volume per grid cell area      [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_ip_frac     !: melt pond fraction (a_ip/a_i)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_ip_eff      !: melt pond effective fraction (not covered up by lid) (a_ip/a_i)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   h_ip          !: melt pond depth                          [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_il          !: melt pond lid volume                     [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   h_il          !: melt pond lid thickness                  [m]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   at_ip         !: total melt pond concentration
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   hm_ip         !: mean melt pond depth                     [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   vt_ip         !: total melt pond volume per gridcell area [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   hm_il         !: mean melt pond lid depth                     [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   vt_il         !: total melt pond lid volume per gridcell area [m]
+
+   !!----------------------------------------------------------------------
+   !! * Global variables at before time step
+   !!----------------------------------------------------------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_s_b, v_i_b, h_s_b, h_i_b !: snow and ice volumes/thickness
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_i_b, sv_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
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   at_i_b                     !: ice concentration (total)
+            
+   !!----------------------------------------------------------------------
+   !! * Ice thickness distribution variables
+   !!----------------------------------------------------------------------
+   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 
+   !
+   !!----------------------------------------------------------------------
+   !! * Ice diagnostics
+   !!----------------------------------------------------------------------
+   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_trp_sv       !: transport of salt content
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_heat         !: snw/ice heat content variation   [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_sice         !: ice salt content variation   [] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_vice         !: ice volume variation   [m/s] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_vsnw         !: snw volume variation   [m/s] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_aice         !: ice conc.  variation   [s-1] 
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_adv_mass     !: advection of mass (kg/m2/s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_adv_salt     !: advection of salt (g/m2/s)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_adv_heat     !: advection of heat (W/m2)
+   !
+   !!----------------------------------------------------------------------
+   !! * Ice conservation
+   !!----------------------------------------------------------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_v            !: conservation of ice volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_s            !: conservation of ice salt
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_t            !: conservation of ice heat
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_fv           !: conservation of ice volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_fs           !: conservation of ice salt
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   diag_ft           !: conservation of ice heat
+   !
+   !!----------------------------------------------------------------------
+   !! * SIMIP extra diagnostics
+   !!----------------------------------------------------------------------
+   ! Extra sea ice diagnostics to address the data request
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   t_si            !: Temperature at Snow-ice interface (K) 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   tm_si           !: mean temperature at the snow-ice interface (K) 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qcn_ice_bot     !: Bottom  conduction flux (W/m2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qcn_ice_top     !: Surface conduction flux (W/m2)
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION ice_alloc()
+      !!-----------------------------------------------------------------
+      !!               *** Routine ice_alloc ***
+      !!-----------------------------------------------------------------
+      INTEGER :: ice_alloc
+      !
+      INTEGER :: ierr(16), ii
+      !!-----------------------------------------------------------------
+      ierr(:) = 0
+
+      ii = 1
+      ALLOCATE( u_oce    (jpi,jpj) , v_oce    (jpi,jpj) , ht_i_new  (jpi,jpj) , strength(jpi,jpj) ,  &
+         &      stress1_i(jpi,jpj) , stress2_i(jpi,jpj) , stress12_i(jpi,jpj) ,                      &
+         &      delta_i  (jpi,jpj) , divu_i   (jpi,jpj) , shear_i   (jpi,jpj) , STAT=ierr(ii) )
+
+      ii = ii + 1
+      ALLOCATE( t_bo       (jpi,jpj) , wfx_snw_sni(jpi,jpj) ,                                                &
+         &      wfx_snw    (jpi,jpj) , wfx_snw_dyn(jpi,jpj) , wfx_snw_sum(jpi,jpj) , wfx_snw_sub(jpi,jpj) ,  &
+         &      wfx_ice    (jpi,jpj) , wfx_sub    (jpi,jpj) , wfx_ice_sub(jpi,jpj) , wfx_lam    (jpi,jpj) ,  &
+         &      wfx_pnd    (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) ,           &
+         &      rn_amax_2d (jpi,jpj) ,                                                                       &
+         &      qsb_ice_bot(jpi,jpj) , qlead     (jpi,jpj) ,                                                 &
+         &      sfx_res    (jpi,jpj) , sfx_bri   (jpi,jpj) , sfx_dyn(jpi,jpj) , sfx_sub(jpi,jpj) , sfx_lam(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) ,                        & 
+         &      qt_atm_oi  (jpi,jpj) , qt_oce_ai (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) ,     &
+         &      hfx_err_dif(jpi,jpj) , wfx_err_sub(jpi,jpj)                   , STAT=ierr(ii) )
+
+      ! * Ice global state variables
+      ii = ii + 1
+      ALLOCATE( qtr_ice_bot(jpi,jpj,jpl) , cnd_ice(jpi,jpj,jpl) , t1_ice(jpi,jpj,jpl) ,  &
+         &      h_i        (jpi,jpj,jpl) , a_i    (jpi,jpj,jpl) , v_i   (jpi,jpj,jpl) ,  &
+         &      v_s        (jpi,jpj,jpl) , h_s    (jpi,jpj,jpl) , t_su  (jpi,jpj,jpl) ,  &
+         &      s_i        (jpi,jpj,jpl) , sv_i   (jpi,jpj,jpl) , o_i   (jpi,jpj,jpl) ,  &
+         &      oa_i       (jpi,jpj,jpl) , bv_i   (jpi,jpj,jpl) , STAT=ierr(ii) )
+
+      ii = ii + 1
+      ALLOCATE( u_ice(jpi,jpj) , v_ice(jpi,jpj) ,                                   &
+         &      vt_i (jpi,jpj) , vt_s (jpi,jpj) , st_i(jpi,jpj) , at_i(jpi,jpj) , ato_i(jpi,jpj) ,  &
+         &      et_i (jpi,jpj) , et_s (jpi,jpj) , tm_i(jpi,jpj) , tm_s(jpi,jpj) ,  &
+         &      sm_i (jpi,jpj) , tm_su(jpi,jpj) , hm_i(jpi,jpj) , hm_s(jpi,jpj) ,  &
+         &      om_i (jpi,jpj) , bvm_i(jpi,jpj) , tau_icebfr(jpi,jpj)            , STAT=ierr(ii) )
+
+      ii = ii + 1
+      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,jpl) , e_i(jpi,jpj,nlay_i,jpl) , sz_i(jpi,jpj,nlay_i,jpl) , STAT=ierr(ii) )
+
+      ii = ii + 1
+      ALLOCATE( a_ip(jpi,jpj,jpl) , v_ip(jpi,jpj,jpl) , a_ip_frac(jpi,jpj,jpl) , h_ip(jpi,jpj,jpl),  &
+         &      v_il(jpi,jpj,jpl) , h_il(jpi,jpj,jpl) , a_ip_eff (jpi,jpj,jpl) , STAT = ierr(ii) )
+
+      ii = ii + 1
+      ALLOCATE( at_ip(jpi,jpj) , hm_ip(jpi,jpj) , vt_ip(jpi,jpj) , hm_il(jpi,jpj) , vt_il(jpi,jpj) , STAT = ierr(ii) )
+
+      ! * Old values of global variables
+      ii = ii + 1
+      ALLOCATE( v_s_b (jpi,jpj,jpl) , v_i_b (jpi,jpj,jpl) , h_s_b(jpi,jpj,jpl)        , h_i_b(jpi,jpj,jpl),         &
+         &      a_i_b (jpi,jpj,jpl) , sv_i_b(jpi,jpj,jpl) , e_i_b(jpi,jpj,nlay_i,jpl) , e_s_b(jpi,jpj,nlay_s,jpl) , &
+         &      STAT=ierr(ii) )
+
+      ii = ii + 1
+      ALLOCATE( u_ice_b(jpi,jpj) , v_ice_b(jpi,jpj) , at_i_b(jpi,jpj) , STAT=ierr(ii) )
+      
+      ! * Ice thickness distribution variables
+      ii = ii + 1
+      ALLOCATE( hi_max(0:jpl), hi_mean(jpl),  STAT=ierr(ii) )
+
+      ! * Ice diagnostics
+      ii = ii + 1
+      ALLOCATE( diag_trp_vi(jpi,jpj) , diag_trp_vs (jpi,jpj) , diag_trp_ei(jpi,jpj),                      & 
+         &      diag_trp_es(jpi,jpj) , diag_trp_sv (jpi,jpj) , diag_heat  (jpi,jpj),                      &
+         &      diag_sice  (jpi,jpj) , diag_vice   (jpi,jpj) , diag_vsnw  (jpi,jpj), diag_aice(jpi,jpj),  &
+         &      diag_adv_mass(jpi,jpj), diag_adv_salt(jpi,jpj), diag_adv_heat(jpi,jpj), STAT=ierr(ii) )
+
+      ! * Ice conservation
+      ii = ii + 1
+      ALLOCATE( diag_v (jpi,jpj) , diag_s (jpi,jpj) , diag_t (jpi,jpj),   & 
+         &      diag_fv(jpi,jpj) , diag_fs(jpi,jpj) , diag_ft(jpi,jpj), STAT=ierr(ii) )
+      
+      ! * SIMIP diagnostics
+      ii = ii + 1
+      ALLOCATE( t_si(jpi,jpj,jpl) , tm_si(jpi,jpj) , qcn_ice_bot(jpi,jpj,jpl) , qcn_ice_top(jpi,jpj,jpl) , STAT = ierr(ii) )
+
+      ice_alloc = MAXVAL( ierr(:) )
+      IF( ice_alloc /= 0 )   CALL ctl_stop( 'STOP', 'ice_alloc: failed to allocate arrays.' )
+      !
+
+   END FUNCTION ice_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE ice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice1d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice1d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/ice1d.F90	(revision 14097)
@@ -0,0 +1,254 @@
+MODULE ice1D
+   !!======================================================================
+   !!                       ***  MODULE ice1D  ***
+   !! sea-ice :   Ice thermodynamics variables in 1D
+   !!=====================================================================
+   !! History :  3.0  !  2002-11  (C. Ethe)          original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   USE ice     , ONLY :   nlay_i, nlay_s, jpl   ! number of ice/snow layers and categories
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice1D_alloc   ! called by icestp.F90
+
+   !!----------------------
+   !! * 1D Module variables
+   !!----------------------
+   !: In ice thermodynamics, to spare memory, the vectors are folded
+   !: from 1D to 2D vectors. The following variables, with ending _1d
+   !: are the variables corresponding to 2d vectors
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   nptidx !: selected points for ice thermo
+   INTEGER , PUBLIC                                  ::   npti   !  number of selected points
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qlead_1d     
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qtr_ice_bot_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qsr_ice_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(:) ::   rn_amax_1d
+   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qml_ice_1d     !: heat available for snow / ice surface melting [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qcn_ice_1d     !: heat available for snow / ice surface sublimation [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qtr_ice_top_1d !: solar flux transmitted below the ice surface [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t1_ice_1d      !: temperature of the 1st layer        (ln_cndflx=T) [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   cnd_ice_1d     !: conductivity at the top of ice/snow (ln_cndflx=T) [W/K/m2]
+
+   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_dyn_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_err_dif_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qt_oce_ai_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_sni_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_snw_sum_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_snw_dyn_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_sub_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_snw_sub_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_ice_sub_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_err_sub_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_lam_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(:) ::   wfx_dyn_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_pnd_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(:) ::   sfx_sub_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_lam_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_dyn_1d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sprecip_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   at_i_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ato_i_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qsb_ice_bot_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fhld_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dqns_ice_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   evap_ice_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qprec_ice_1d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_su_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_si_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   a_i_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   a_ib_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   h_i_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   h_ib_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   h_s_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_s_tot      !: Snow accretion/ablation        [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_sum      !: Ice surface ablation [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_itm      !: Ice internal ablation [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_bom      !: Ice bottom ablation  [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_bog      !: Ice bottom accretion  [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_sub      !: Ice surface sublimation [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_s_mlt      !: Snow melt [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_snowice    !: Snow ice formation             [m of ice]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   s_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(:) ::   v_i_1d        !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   v_s_1d        !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sv_i_1d       !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   oa_i_1d       !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   o_i_1d        !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   a_ip_1d       !: ice ponds
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   v_ip_1d       !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   h_ip_1d       !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   v_il_1d       !: Ice pond lid
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   h_il_1d       !:
+
+   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(:,:) ::   sz_i_1d     !: profiled ice salinity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   e_i_1d      !:    Ice  enthalpy per unit volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   e_s_1d      !:    Snow enthalpy per unit volume
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   eh_i_old    !: ice heat content (q*h, J.m-2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   h_i_old     !: ice thickness layer (m)
+
+   ! Conduction flux diagnostics (SIMIP)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qcn_ice_bot_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qcn_ice_top_1d
+
+   ! surface fields from the ocean
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sst_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sss_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   frq_m_1d
+
+   ! convergence check
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   tice_cvgerr_1d   !: convergence of ice/snow temp (dT)          [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   tice_cvgstp_1d   !: convergence of ice/snow temp (subtimestep) [-]
+   ! 
+   !!----------------------
+   !! * 2D Module variables
+   !!----------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   a_i_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   v_i_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   v_s_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   oa_i_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sv_i_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   a_ip_2d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   v_ip_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   v_il_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_su_2d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   h_i_2d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   a_ib_2d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   h_ib_2d
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION ice1D_alloc()
+      !!---------------------------------------------------------------------!
+      !!                ***  ROUTINE ice1D_alloc ***
+      !!---------------------------------------------------------------------!
+      INTEGER ::   ice1D_alloc   ! return value
+      INTEGER ::   ierr(8), ii
+      !!---------------------------------------------------------------------!
+      ierr(:) = 0
+
+      ii = 1
+      ALLOCATE( nptidx    (jpij) ,   &
+         &      qlead_1d  (jpij) , qtr_ice_bot_1d(jpij) , qsr_ice_1d(jpij) ,   &
+         &      qns_ice_1d(jpij) , qml_ice_1d    (jpij) , qcn_ice_1d(jpij) , qtr_ice_top_1d(jpij) , &
+         &      cnd_ice_1d(jpij) , t1_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_dyn_1d(jpij) ,   &
+         &      rn_amax_1d(jpij) ,                                             &
+         &      hfx_thd_1d(jpij) , hfx_spr_1d    (jpij) ,                      &
+         &      hfx_snw_1d(jpij) , hfx_sub_1d    (jpij) ,                      &
+         &      hfx_res_1d(jpij) , hfx_err_dif_1d(jpij) , qt_oce_ai_1d(jpij), STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( sprecip_1d    (jpij) , at_i_1d       (jpij) , ato_i_1d      (jpij) ,                         &
+         &      qsb_ice_bot_1d(jpij) , wfx_snw_sni_1d(jpij) , wfx_spr_1d    (jpij) , wfx_snw_sum_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) ,  &
+         &      wfx_snw_sub_1d(jpij) , wfx_snw_dyn_1d(jpij) , wfx_ice_sub_1d(jpij) , wfx_err_sub_1d(jpij) ,  &
+         &      wfx_lam_1d    (jpij) , wfx_dyn_1d    (jpij) , wfx_pnd_1d    (jpij) , dqns_ice_1d   (jpij) , evap_ice_1d (jpij) , &
+         &      qprec_ice_1d  (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) , sfx_sub_1d (jpij),  &
+         &      sfx_lam_1d    (jpij) , sfx_dyn_1d(jpij)  , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( t_su_1d (jpij) , t_si_1d (jpij) , a_i_1d    (jpij) , a_ib_1d (jpij) ,                   &
+         &      h_i_1d  (jpij) , h_ib_1d (jpij) , h_s_1d    (jpij) ,                                    &    
+         &      dh_s_tot(jpij) , dh_i_sum(jpij) , dh_i_itm  (jpij) , dh_i_bom(jpij) , dh_i_bog(jpij) ,  &    
+         &      dh_i_sub(jpij) , dh_s_mlt(jpij) , dh_snowice(jpij) , s_i_1d  (jpij) , s_i_new (jpij) ,  &
+         &      a_ip_1d (jpij) , v_ip_1d (jpij) , v_i_1d    (jpij) , v_s_1d  (jpij) , v_il_1d (jpij) ,  &
+         &      h_il_1d (jpij) , h_ip_1d (jpij) ,                                                       &
+         &      sv_i_1d (jpij) , oa_i_1d (jpij) , o_i_1d    (jpij) , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( t_s_1d  (jpij,nlay_s)     , t_i_1d (jpij,nlay_i)     , sz_i_1d(jpij,nlay_i) ,  &            
+         &      e_i_1d  (jpij,nlay_i)     , e_s_1d (jpij,nlay_s)     ,                         &
+         &      eh_i_old(jpij,0:nlay_i+1) , h_i_old(jpij,0:nlay_i+1) , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( qcn_ice_bot_1d(jpij) , qcn_ice_top_1d(jpij) , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( sst_1d(jpij) , sss_1d(jpij) , frq_m_1d(jpij) , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( tice_cvgerr_1d(jpij) , tice_cvgstp_1d(jpij) , STAT=ierr(ii) )
+      !
+      ii = ii + 1
+      ALLOCATE( a_i_2d (jpij,jpl) , a_ib_2d(jpij,jpl) , h_i_2d (jpij,jpl) , h_ib_2d(jpij,jpl) ,  &
+         &      v_i_2d (jpij,jpl) , v_s_2d (jpij,jpl) , oa_i_2d(jpij,jpl) , sv_i_2d(jpij,jpl) ,  &
+         &      a_ip_2d(jpij,jpl) , v_ip_2d(jpij,jpl) , t_su_2d(jpij,jpl) , v_il_2d(jpij,jpl) ,  &
+         &      STAT=ierr(ii) )
+
+      ice1D_alloc = MAXVAL( ierr(:) )
+      IF( ice1D_alloc /= 0 )   CALL ctl_stop( 'STOP',  'ice1D_alloc: failed to allocate arrays.'  )
+      !
+   END FUNCTION ice1D_alloc
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE ice1D_alloc          ! Empty routine
+   END SUBROUTINE ice1D_alloc
+#endif
+ 
+   !!======================================================================
+END MODULE ice1D
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icealb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icealb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icealb.F90	(revision 14097)
@@ -0,0 +1,225 @@
+MODULE icealb
+   !!======================================================================
+   !!                       ***  MODULE  icealb  ***
+   !! Atmospheric forcing:  Albedo over sea ice
+   !!=====================================================================
+   !! History :  4.0  !  2017-07  (C. Rousset)       Split ice and ocean albedos
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_alb        : albedo for ice (clear and overcast skies)
+   !!   ice_alb_init   : initialisation of albedo computation
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE dom_oce        ! domain: ocean
+   USE ice, ONLY: jpl ! sea-ice: number of categories
+   USE icevar         ! sea-ice: operations
+   !
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_alb_init   ! called in icestp
+   PUBLIC   ice_alb        ! called in icesbc.F90 and iceupdate.F90
+
+   REAL(wp), PUBLIC, PARAMETER ::   rn_alb_oce = 0.066   !: ocean or lead albedo (Pegau and Paulson, Ann. Glac. 2001)
+   !
+   !                             !!* albedo namelist (namalb)
+   REAL(wp) ::   rn_alb_sdry      ! dry snow albedo
+   REAL(wp) ::   rn_alb_smlt      ! melting snow albedo
+   REAL(wp) ::   rn_alb_idry      ! dry ice albedo
+   REAL(wp) ::   rn_alb_imlt      ! bare puddled ice albedo
+   REAL(wp) ::   rn_alb_dpnd      ! ponded ice albedo
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_alb( pt_su, ph_ice, ph_snw, ld_pnd_alb, pafrac_pnd, ph_pnd, pcloud_fra, palb_ice )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE ice_alb  ***
+      !!          
+      !! ** Purpose :   Computation of the albedo of the snow/ice system 
+      !!       
+      !! ** Method  :   The scheme is "home made" (for cloudy skies) and based on Brandt et al. (J. Climate 2005)
+      !!                                                                      and Grenfell & Perovich (JGR 2004)
+      !!                  1) Albedo dependency on ice thickness follows the findings from Brandt et al (2005)
+      !!                     which are an update of Allison et al. (JGR 1993) ; Brandt et al. 1999
+      !!                     0-5cm  : linear function of ice thickness
+      !!                     5-150cm: log    function of ice thickness
+      !!                     > 150cm: constant
+      !!                  2) Albedo dependency on snow thickness follows the findings from Grenfell & Perovich (2004)
+      !!                     i.e. it increases as -EXP(-snw_thick/0.02) during freezing and -EXP(-snw_thick/0.03) during melting
+      !!                  3) Albedo dependency on clouds is speculated from measurements of Grenfell and Perovich (2004)
+      !!                     i.e. cloudy-clear albedo depend on cloudy albedo following a 2d order polynomial law
+      !!                  4) The needed 4 parameters are: dry and melting snow, freezing ice and bare puddled ice
+      !!
+      !!                     compilation of values from literature (reference overcast sky values)
+      !!                        rn_alb_sdry = 0.85      ! dry snow
+      !!                        rn_alb_smlt = 0.75      ! melting snow
+      !!                        rn_alb_idry = 0.60      ! bare frozen ice
+      !!                        rn_alb_imlt = 0.50      ! bare puddled ice albedo
+      !!                        rn_alb_dpnd = 0.36      ! ponded-ice overcast albedo (Lecomte et al, 2015)
+      !!                                                ! early melt pnds 0.27, late melt ponds 0.14 Grenfell & Perovich
+      !!                     Perovich et al 2002 (Sheba) => the only dataset for which all types of ice/snow were retrieved
+      !!                        rn_alb_sdry = 0.85      ! dry snow
+      !!                        rn_alb_smlt = 0.72      ! melting snow
+      !!                        rn_alb_idry = 0.65      ! bare frozen ice
+      !!                     Brandt et al 2005 (East Antarctica)
+      !!                        rn_alb_sdry = 0.87      ! dry snow
+      !!                        rn_alb_smlt = 0.82      ! melting snow
+      !!                        rn_alb_idry = 0.54      ! bare frozen ice
+      !!
+      !! ** Note    :   The old parameterization from Shine & Henderson-Sellers (not here anymore) presented several misconstructions
+      !!                  1) ice albedo when ice thick. tends to 0 is different than ocean albedo
+      !!                  2) for small ice thick. covered with some snow (<3cm?), albedo is larger 
+      !!                     under melting conditions than under freezing conditions
+      !!                  3) the evolution of ice albedo as a function of ice thickness shows  
+      !!                     3 sharp inflexion points (at 5cm, 100cm and 150cm) that look highly unrealistic
+      !!
+      !! References :   Shine & Henderson-Sellers 1985, JGR, 90(D1), 2243-2250.
+      !!                Brandt et al. 2005, J. Climate, vol 18
+      !!                Grenfell & Perovich 2004, JGR, vol 109 
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   pt_su        !  ice surface temperature (Kelvin)
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   ph_ice       !  sea-ice thickness
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   ph_snw       !  snow depth
+      LOGICAL , INTENT(in   )                   ::   ld_pnd_alb   !  effect of melt ponds on albedo
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   pafrac_pnd   !  melt pond relative fraction (per unit ice area)
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:) ::   ph_pnd       !  melt pond depth
+      REAL(wp), INTENT(in   ), DIMENSION(:,:)   ::   pcloud_fra   !  cloud fraction
+      REAL(wp), INTENT(  out), DIMENSION(:,:,:) ::   palb_ice     !  albedo of ice
+      !
+      REAL(wp), DIMENSION(jpi,jpj,jpl) :: za_s_fra   ! ice fraction covered by snow
+      INTEGER  ::   ji, jj, jl                ! dummy loop indices
+      REAL(wp) ::   z1_c1, z1_c2,z1_c3, z1_c4 ! local scalar
+      REAL(wp) ::   z1_href_pnd               ! inverse of the characteristic length scale (Lecomte et al. 2015)
+      REAL(wp) ::   zalb_pnd, zafrac_pnd      ! ponded sea ice albedo & relative pound fraction
+      REAL(wp) ::   zalb_ice, zafrac_ice      ! bare sea ice albedo & relative ice fraction
+      REAL(wp) ::   zalb_snw, zafrac_snw      ! snow-covered sea ice albedo & relative snow fraction
+      REAL(wp) ::   zalb_cs, zalb_os          ! albedo of ice under clear/overcast sky
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('icealb')
+      !
+      z1_href_pnd = 1. / 0.05
+      z1_c1 = 1. / ( LOG(1.5) - LOG(0.05) ) 
+      z1_c2 = 1. / 0.05
+      z1_c3 = 1. / 0.02
+      z1_c4 = 1. / 0.03
+      !
+      CALL ice_var_snwfra( ph_snw, za_s_fra )   ! calculate ice fraction covered by snow
+      !
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !
+               !---------------------------------------------!
+               !--- Specific snow, ice and pond fractions ---!
+               !---------------------------------------------!               
+               zafrac_snw = za_s_fra(ji,jj,jl)
+               IF( ld_pnd_alb ) THEN
+                  zafrac_pnd = MIN( pafrac_pnd(ji,jj,jl), 1._wp - zafrac_snw ) ! make sure (a_ip_eff + a_s_fra) <= 1
+               ELSE
+                  zafrac_pnd = 0._wp
+               ENDIF
+               zafrac_ice = MAX( 0._wp, 1._wp - zafrac_pnd - zafrac_snw ) ! max for roundoff errors
+               !
+               !---------------!
+               !--- Albedos ---!
+               !---------------!               
+               !                       !--- Bare ice albedo (for hi > 150cm)
+               IF( ld_pnd_alb ) THEN
+                  zalb_ice = rn_alb_idry
+               ELSE
+                  IF( ph_snw(ji,jj,jl) == 0._wp .AND. pt_su(ji,jj,jl) >= rt0 ) THEN   ;   zalb_ice = rn_alb_imlt
+                  ELSE                                                                ;   zalb_ice = rn_alb_idry   ;   ENDIF
+               ENDIF
+               !                       !--- Bare ice albedo (for hi < 150cm)
+               IF( 0.05 < ph_ice(ji,jj,jl) .AND. ph_ice(ji,jj,jl) <= 1.5 ) THEN      ! 5cm < hi < 150cm
+                  zalb_ice = zalb_ice    + ( 0.18 - zalb_ice   ) * z1_c1 * ( LOG(1.5) - LOG(ph_ice(ji,jj,jl)) )
+               ELSEIF( ph_ice(ji,jj,jl) <= 0.05 ) THEN                               ! 0cm < hi < 5cm
+                  zalb_ice = rn_alb_oce  + ( 0.18 - rn_alb_oce ) * z1_c2 * ph_ice(ji,jj,jl)
+               ENDIF
+               !
+               !                       !--- Snow-covered ice albedo (freezing, melting cases)
+               IF( pt_su(ji,jj,jl) < rt0 ) THEN
+                  zalb_snw = rn_alb_sdry - ( rn_alb_sdry - zalb_ice ) * EXP( - ph_snw(ji,jj,jl) * z1_c3 )
+               ELSE
+                  zalb_snw = rn_alb_smlt - ( rn_alb_smlt - zalb_ice ) * EXP( - ph_snw(ji,jj,jl) * z1_c4 )
+               ENDIF
+               !                       !--- Ponded ice albedo
+               zalb_pnd = rn_alb_dpnd - ( rn_alb_dpnd - zalb_ice ) * EXP( - ph_pnd(ji,jj,jl) * z1_href_pnd ) 
+               !
+               !                       !--- Surface albedo is weighted mean of snow, ponds and bare ice contributions
+               zalb_os = ( zafrac_snw * zalb_snw + zafrac_pnd * zalb_pnd + zafrac_ice * zalb_ice ) * tmask(ji,jj,1)
+               !
+               zalb_cs = zalb_os - ( - 0.1010 * zalb_os * zalb_os  &
+                  &                  + 0.1933 * zalb_os - 0.0148 ) * tmask(ji,jj,1)
+               !
+               ! albedo depends on cloud fraction because of non-linear spectral effects
+               palb_ice(ji,jj,jl) = ( 1._wp - pcloud_fra(ji,jj) ) * zalb_cs + pcloud_fra(ji,jj) * zalb_os
+
+            END DO
+         END DO
+      END DO
+      !
+      !
+      IF( ln_timing )   CALL timing_stop('icealb')
+      !
+   END SUBROUTINE ice_alb
+
+
+   SUBROUTINE ice_alb_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE alb_init  ***
+      !!
+      !! ** Purpose :   initializations for the albedo parameters
+      !!
+      !! ** Method  :   Read the namelist namalb
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namalb/ rn_alb_sdry, rn_alb_smlt, rn_alb_idry, rn_alb_imlt, rn_alb_dpnd
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namalb in reference namelist : Albedo parameters
+      READ  ( numnam_ice_ref, namalb, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namalb in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namalb in configuration namelist : Albedo parameters
+      READ  ( numnam_ice_cfg, namalb, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namalb in configuration namelist' )
+      IF(lwm) WRITE( numoni, namalb )
+      !
+      IF(lwp) THEN                      ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_alb_init: set albedo parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namalb:'
+         WRITE(numout,*) '      albedo of dry snow                   rn_alb_sdry = ', rn_alb_sdry
+         WRITE(numout,*) '      albedo of melting snow               rn_alb_smlt = ', rn_alb_smlt
+         WRITE(numout,*) '      albedo of dry ice                    rn_alb_idry = ', rn_alb_idry
+         WRITE(numout,*) '      albedo of bare puddled ice           rn_alb_imlt = ', rn_alb_imlt
+         WRITE(numout,*) '      albedo of ponded ice                 rn_alb_dpnd = ', rn_alb_dpnd
+      ENDIF
+      !
+   END SUBROUTINE ice_alb_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icealb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icecor.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icecor.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icecor.F90	(revision 14097)
@@ -0,0 +1,142 @@
+MODULE icecor
+   !!======================================================================
+   !!                     ***  MODULE  icecor  ***
+   !!   sea-ice: Corrections on sea-ice variables at the end of the time step
+   !!======================================================================
+   !! History :  3.0  !  2006-04  (M. Vancoppenolle) Original code
+   !!            3.5  !  2014-06  (C. Rousset)       Complete rewriting/cleaning
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!    ice_cor      : corrections on sea-ice variables
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constants
+   USE ice            ! sea-ice: variable
+   USE ice1D          ! sea-ice: thermodynamic variables
+   USE iceitd         ! sea-ice: rebining
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: control prints
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_cor   ! called by icestp.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_cor( kt, kn )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE ice_cor  ***
+      !!               
+      !! ** Purpose :   Computes corrections on sea-ice global variables at 
+      !!              the end of the dynamics (kn=1) and thermodynamics (kn=2)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! number of iteration
+      INTEGER, INTENT(in) ::   kn    ! 1 = after dyn ; 2 = after thermo
+      !
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      REAL(wp) ::   zsal, zzc
+      !!----------------------------------------------------------------------
+      ! controls
+      IF( ln_timing    )   CALL timing_start('icecor')                                                             ! timing
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'icecor', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'icecor',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+      !
+      IF( kt == nit000 .AND. lwp .AND. kn == 2 ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_cor:  correct sea ice variables if out of bounds ' 
+         WRITE(numout,*) '~~~~~~~'
+      ENDIF
+      !                             !-----------------------------------------------------
+      !                             !  ice thickness must exceed himin (for temp. diff.) !
+      !                             !-----------------------------------------------------
+      WHERE( a_i(:,:,:) >= epsi20 )   ;   h_i(:,:,:) = v_i(:,:,:) / a_i(:,:,:)
+      ELSEWHERE                       ;   h_i(:,:,:) = 0._wp
+      END WHERE
+      WHERE( h_i(:,:,:) < rn_himin )      a_i(:,:,:) = a_i(:,:,:) * h_i(:,:,:) / rn_himin
+      !
+      !                             !-----------------------------------------------------
+      !                             !  ice concentration should not exceed amax          !
+      !                             !-----------------------------------------------------
+      at_i(:,:) = SUM( a_i(:,:,:), dim=3 )
+      DO jl = 1, jpl
+         WHERE( at_i(:,:) > rn_amax_2d(:,:) )   a_i(:,:,jl) = a_i(:,:,jl) * rn_amax_2d(:,:) / at_i(:,:)
+      END DO    
+      !                             !-----------------------------------------------------
+      !                             !  Rebin categories with thickness out of bounds     !
+      !                             !-----------------------------------------------------
+      IF ( jpl > 1 )   CALL ice_itd_reb( kt )
+      !
+      !                             !-----------------------------------------------------
+      IF ( nn_icesal == 2 ) THEN    !  salinity must stay in bounds [Simin,Simax]        !
+         !                          !-----------------------------------------------------
+         zzc = rhoi * r1_rdtice
+         DO jl = 1, jpl
+            DO jj = 1, jpj 
+               DO ji = 1, jpi
+                  zsal = sv_i(ji,jj,jl)
+                  sv_i(ji,jj,jl) = MIN(  MAX( rn_simin*v_i(ji,jj,jl) , sv_i(ji,jj,jl) ) , rn_simax*v_i(ji,jj,jl)  )
+                  IF( kn /= 0 ) & ! no ice-ocean exchanges if kn=0 (for bdy for instance) otherwise conservation diags will fail
+                     &   sfx_res(ji,jj) = sfx_res(ji,jj) - ( sv_i(ji,jj,jl) - zsal ) * zzc   ! associated salt flux
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      IF( kn /= 0 ) THEN   ! no zapsmall if kn=0 (for bdy for instance) because we do not want ice-ocean exchanges (wfx,sfx,hfx)
+         !                                                              otherwise conservation diags will fail
+         !                          !-----------------------------------------------------
+         CALL ice_var_zapsmall      !  Zap small values                                  !
+         !                          !-----------------------------------------------------
+      ENDIF
+      !                             !-----------------------------------------------------
+      IF( kn == 2 ) THEN            !  Ice drift case: Corrections to avoid wrong values !
+         DO jj = 2, jpjm1           !-----------------------------------------------------
+            DO ji = 2, jpim1
+               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
+         END DO
+         CALL lbc_lnk_multi( 'icecor', u_ice, 'U', -1._wp, v_ice, 'V', -1._wp )
+      ENDIF
+      !
+      ! controls
+      IF( ln_ctl       )   CALL ice_prt3D   ('icecor')                                                             ! prints
+      IF( ln_icectl .AND. kn == 2 ) &
+         &                 CALL ice_prt     ( kt, iiceprt, jiceprt, 2, ' - Final state - ' )                       ! prints
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icecor', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'icecor',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+      IF( ln_timing    )   CALL timing_stop ('icecor')                                                             ! timing
+      !
+   END SUBROUTINE ice_cor
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icecor
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icectl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icectl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icectl.F90	(revision 14097)
@@ -0,0 +1,901 @@
+MODULE icectl
+   !!======================================================================
+   !!                     ***  MODULE  icectl  ***
+   !!   sea-ice : controls and prints
+   !!======================================================================
+   !! History :  3.5  !  2015-01  (M. Vancoppenolle) Original code
+   !!            3.7  !  2016-10  (C. Rousset)       Add routine ice_prt3D
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!    ice_cons_hsm     : conservation tests on heat, salt and mass during a  time step (global) 
+   !!    ice_cons_final   : conservation tests on heat, salt and mass at end of time step (global)
+   !!    ice_cons2D       : conservation tests on heat, salt and mass at each gridcell
+   !!    ice_ctl          : control prints in case of crash
+   !!    ice_prt          : control prints at a given grid point
+   !!    ice_prt3D        : control prints of ice arrays
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbc_ice        ! Surface boundary condition: ice   fields
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_cons_hsm
+   PUBLIC   ice_cons_final
+   PUBLIC   ice_cons2D
+   PUBLIC   ice_ctl
+   PUBLIC   ice_prt
+   PUBLIC   ice_prt3D
+   PUBLIC   ice_drift_wri
+   PUBLIC   ice_drift_init
+
+   ! thresold rates for conservation
+   !    these values are changed by the namelist parameter rn_icechk, so that threshold = zchk * rn_icechk
+   REAL(wp), PARAMETER ::   zchk_m   = 2.5e-7   ! kg/m2/s <=> 1e-6 m of ice per hour spuriously gained/lost
+   REAL(wp), PARAMETER ::   zchk_s   = 2.5e-6   ! g/m2/s  <=> 1e-6 m of ice per hour spuriously gained/lost (considering s=10g/kg)
+   REAL(wp), PARAMETER ::   zchk_t   = 7.5e-2   ! W/m2    <=> 1e-6 m of ice per hour spuriously gained/lost (considering Lf=3e5J/kg)
+
+   ! for drift outputs
+   CHARACTER(LEN=50)   ::   clname="icedrift_diagnostics.ascii"   ! ascii filename
+   INTEGER             ::   numicedrift                           ! outfile unit
+   REAL(wp)            ::   rdiag_icemass, rdiag_icesalt, rdiag_iceheat 
+   REAL(wp)            ::   rdiag_adv_icemass, rdiag_adv_icesalt, rdiag_adv_iceheat 
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_cons_hsm( icount, cd_routine, pdiag_v, pdiag_s, pdiag_t, pdiag_fv, pdiag_fs, pdiag_ft )
+      !!-------------------------------------------------------------------
+      !!                       ***  ROUTINE ice_cons_hsm ***
+      !!
+      !! ** Purpose : Test the conservation of heat, salt and mass for each ice routine
+      !!                     + test if ice concentration and volume are > 0
+      !!
+      !! ** Method  : This is an online diagnostics which can be activated with ln_icediachk=true
+      !!              It prints in ocean.output if there is a violation of conservation at each time-step
+      !!              The thresholds (zchk_m, zchk_s, zchk_t) determine violations
+      !!              For salt and heat thresholds, ice is considered to have a salinity of 10 
+      !!              and a heat content of 3e5 J/kg (=latent heat of fusion) 
+      !!-------------------------------------------------------------------
+      INTEGER         , INTENT(in)    ::   icount        ! called at: =0 the begining of the routine, =1  the end
+      CHARACTER(len=*), INTENT(in)    ::   cd_routine    ! name of the routine
+      REAL(wp)        , INTENT(inout) ::   pdiag_v, pdiag_s, pdiag_t, pdiag_fv, pdiag_fs, pdiag_ft
+      !!
+      REAL(wp) ::   zdiag_mass, zdiag_salt, zdiag_heat, &
+         &          zdiag_vmin, zdiag_amin, zdiag_amax, zdiag_eimin, zdiag_esmin, zdiag_smin
+      REAL(wp) ::   zvtrp, zetrp
+      REAL(wp) ::   zarea
+      !!-------------------------------------------------------------------
+      !
+      IF( icount == 0 ) THEN
+
+         pdiag_v = glob_sum( 'icectl',   SUM( v_i * rhoi + v_s * rhos, dim=3 ) * e1e2t )
+         pdiag_s = glob_sum( 'icectl',   SUM( sv_i * rhoi            , dim=3 ) * e1e2t )
+         pdiag_t = glob_sum( 'icectl', ( SUM( SUM( e_i, dim=4 ), dim=3 ) + SUM( SUM( e_s, dim=4 ), dim=3 ) ) * e1e2t )
+
+         ! mass flux
+         pdiag_fv = glob_sum( 'icectl',  &
+            &                         ( wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn + wfx_lam + wfx_pnd + &
+            &                           wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + wfx_ice_sub + wfx_spr ) * e1e2t )
+         ! salt flux
+         pdiag_fs = glob_sum( 'icectl',  &
+            &                         ( sfx_bri + sfx_bog + sfx_bom + sfx_sum + sfx_sni + &
+            &                           sfx_opw + sfx_res + sfx_dyn + sfx_sub + sfx_lam ) * e1e2t )
+         ! heat flux
+         pdiag_ft = glob_sum( 'icectl',  &
+            &                         (   hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw  &
+            &                           - hfx_thd - hfx_dyn - hfx_res - hfx_sub - hfx_spr ) * e1e2t )
+
+      ELSEIF( icount == 1 ) THEN
+
+         ! -- mass diag -- !
+         zdiag_mass = ( glob_sum( 'icectl', SUM( v_i * rhoi + v_s * rhos, dim=3 ) * e1e2t ) - pdiag_v ) * r1_rdtice       &
+            &         + glob_sum( 'icectl', ( wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn +       &
+            &                                 wfx_lam + wfx_pnd + wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + &
+            &                                 wfx_ice_sub + wfx_spr ) * e1e2t )                                           &
+            &         - pdiag_fv
+         !
+         ! -- salt diag -- !
+         zdiag_salt = ( glob_sum( 'icectl', SUM( sv_i * rhoi , dim=3 ) * e1e2t ) - pdiag_s ) * r1_rdtice  &
+            &         + glob_sum( 'icectl', ( sfx_bri + sfx_bog + sfx_bom + sfx_sum + sfx_sni +           &
+            &                                 sfx_opw + sfx_res + sfx_dyn + sfx_sub + sfx_lam ) * e1e2t ) &
+            &         - pdiag_fs
+         !
+         ! -- heat diag -- !
+         zdiag_heat = ( glob_sum( 'icectl', ( SUM(SUM(e_i, dim=4), dim=3) + SUM(SUM(e_s, dim=4), dim=3) ) * e1e2t ) - pdiag_t &
+            &         ) * r1_rdtice                                                                                           &
+            &         + glob_sum( 'icectl', (  hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw                      &
+            &                                - hfx_thd - hfx_dyn - hfx_res - hfx_sub - hfx_spr ) * e1e2t )                    &
+            &         - pdiag_ft
+
+         ! -- min/max diag -- !
+         zdiag_amax  = glob_max( 'icectl', SUM( a_i, dim=3 ) )
+         zdiag_vmin  = glob_min( 'icectl', v_i )
+         zdiag_amin  = glob_min( 'icectl', a_i )
+         zdiag_smin  = glob_min( 'icectl', sv_i )
+         zdiag_eimin = glob_min( 'icectl', SUM( e_i, dim=3 ) )
+         zdiag_esmin = glob_min( 'icectl', SUM( e_s, dim=3 ) )
+
+         ! -- advection scheme is conservative? -- !
+         zvtrp = glob_sum( 'icectl', diag_adv_mass * e1e2t )
+         zetrp = glob_sum( 'icectl', diag_adv_heat * e1e2t )
+
+         ! ice area (+epsi10 to set a threshold > 0 when there is no ice) 
+         zarea = glob_sum( 'icectl', SUM( a_i + epsi10, dim=3 ) * e1e2t )
+
+         IF( lwp ) THEN
+            ! check conservation issues
+            IF( ABS(zdiag_mass) > zchk_m * rn_icechk_glo * zarea ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation mass cons. [kg] = ',zdiag_mass * rdt_ice
+            IF( ABS(zdiag_salt) > zchk_s * rn_icechk_glo * zarea ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation salt cons. [g]  = ',zdiag_salt * rdt_ice
+            IF( ABS(zdiag_heat) > zchk_t * rn_icechk_glo * zarea ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation heat cons. [J]  = ',zdiag_heat * rdt_ice
+            ! check negative values
+            IF( zdiag_vmin  < 0. ) WRITE(numout,*)   cd_routine,' : violation v_i < 0         = ',zdiag_vmin
+            IF( zdiag_amin  < 0. ) WRITE(numout,*)   cd_routine,' : violation a_i < 0         = ',zdiag_amin
+            IF( zdiag_smin  < 0. ) WRITE(numout,*)   cd_routine,' : violation s_i < 0         = ',zdiag_smin
+            IF( zdiag_eimin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_i < 0         = ',zdiag_eimin
+            IF( zdiag_esmin < 0. ) WRITE(numout,*)   cd_routine,' : violation e_s < 0         = ',zdiag_esmin
+            ! check maximum ice concentration
+            IF( zdiag_amax > MAX(rn_amax_n,rn_amax_s)+epsi10 .AND. cd_routine /= 'icedyn_adv' .AND. cd_routine /= 'icedyn_rdgrft' ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation a_i > amax      = ',zdiag_amax
+            ! check if advection scheme is conservative
+            IF( ABS(zvtrp) > zchk_m * rn_icechk_glo * zarea .AND. cd_routine == 'icedyn_adv' ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [kg] = ',zvtrp * rdt_ice
+            IF( ABS(zetrp) > zchk_t * rn_icechk_glo * zarea .AND. cd_routine == 'icedyn_adv' ) &
+               &                   WRITE(numout,*)   cd_routine,' : violation adv scheme [J]  = ',zetrp * rdt_ice
+         ENDIF
+         !
+      ENDIF
+
+   END SUBROUTINE ice_cons_hsm
+
+   SUBROUTINE ice_cons_final( cd_routine )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE ice_cons_final ***
+      !!
+      !! ** Purpose : Test the conservation of heat, salt and mass at the end of each ice time-step
+      !!
+      !! ** Method  : This is an online diagnostics which can be activated with ln_icediachk=true
+      !!              It prints in ocean.output if there is a violation of conservation at each time-step
+      !!              The thresholds (zchk_m, zchk_s, zchk_t) determine the violations
+      !!              For salt and heat thresholds, ice is considered to have a salinity of 10 
+      !!              and a heat content of 3e5 J/kg (=latent heat of fusion) 
+      !!-------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) ::   cd_routine    ! name of the routine
+      REAL(wp) ::   zdiag_mass, zdiag_salt, zdiag_heat
+      REAL(wp) ::   zarea
+      !!-------------------------------------------------------------------
+
+      ! water flux
+      ! -- mass diag -- !
+      zdiag_mass = glob_sum( 'icectl', (  wfx_ice   + wfx_snw   + wfx_spr + wfx_sub &
+         &                              + diag_vice + diag_vsnw - diag_adv_mass ) * e1e2t )
+
+      ! -- salt diag -- !
+      zdiag_salt = glob_sum( 'icectl', ( sfx + diag_sice - diag_adv_salt ) * e1e2t )
+
+      ! -- heat diag -- !
+      zdiag_heat  = glob_sum( 'icectl', ( qt_oce_ai - qt_atm_oi + diag_heat - diag_adv_heat ) * e1e2t )
+      ! equivalent to this:
+      !!zdiag_heat = glob_sum( 'icectl', ( -diag_heat + hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw &
+      !!   &                                          - hfx_thd - hfx_dyn - hfx_res - hfx_sub - hfx_spr &
+      !!   &                                          ) * e1e2t )
+
+      ! ice area (+epsi10 to set a threshold > 0 when there is no ice) 
+      zarea = glob_sum( 'icectl', SUM( a_i + epsi10, dim=3 ) * e1e2t )
+
+      IF( lwp ) THEN
+         IF( ABS(zdiag_mass) > zchk_m * rn_icechk_glo * zarea ) &
+            &                   WRITE(numout,*) cd_routine,' : violation mass cons. [kg] = ',zdiag_mass * rdt_ice
+         IF( ABS(zdiag_salt) > zchk_s * rn_icechk_glo * zarea ) &
+            &                   WRITE(numout,*) cd_routine,' : violation salt cons. [g]  = ',zdiag_salt * rdt_ice
+         IF( ABS(zdiag_heat) > zchk_t * rn_icechk_glo * zarea ) &
+            &                   WRITE(numout,*) cd_routine,' : violation heat cons. [J]  = ',zdiag_heat * rdt_ice
+      ENDIF
+      !
+   END SUBROUTINE ice_cons_final
+
+   SUBROUTINE ice_cons2D( icount, cd_routine, pdiag_v, pdiag_s, pdiag_t, pdiag_fv, pdiag_fs, pdiag_ft )
+      !!-------------------------------------------------------------------
+      !!                       ***  ROUTINE ice_cons2D ***
+      !!
+      !! ** Purpose : Test the conservation of heat, salt and mass for each ice routine
+      !!                     + test if ice concentration and volume are > 0
+      !!
+      !! ** Method  : This is an online diagnostics which can be activated with ln_icediachk=true
+      !!              It stops the code if there is a violation of conservation at any gridcell
+      !!-------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   icount        ! called at: =0 the begining of the routine, =1  the end
+      CHARACTER(len=*), INTENT(in) ::   cd_routine    ! name of the routine
+      REAL(wp)        , DIMENSION(jpi,jpj), INTENT(inout) ::   pdiag_v, pdiag_s, pdiag_t, pdiag_fv, pdiag_fs, pdiag_ft
+      !!
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdiag_mass, zdiag_salt, zdiag_heat, &
+         &                              zdiag_amin, zdiag_vmin, zdiag_smin, zdiag_emin !!, zdiag_amax  
+      INTEGER ::   jl, jk
+      LOGICAL ::   ll_stop_m = .FALSE.
+      LOGICAL ::   ll_stop_s = .FALSE.
+      LOGICAL ::   ll_stop_t = .FALSE.
+      CHARACTER(len=120) ::   clnam   ! filename for the output
+      !!-------------------------------------------------------------------
+      !
+      IF( icount == 0 ) THEN
+
+         pdiag_v = SUM( v_i  * rhoi + v_s * rhos, dim=3 )
+         pdiag_s = SUM( sv_i * rhoi             , dim=3 )
+         pdiag_t = SUM( SUM( e_i, dim=4 ), dim=3 ) + SUM( SUM( e_s, dim=4 ), dim=3 )
+
+         ! mass flux
+         pdiag_fv = wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn + wfx_lam + wfx_pnd  +  &
+            &       wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + wfx_ice_sub + wfx_spr
+         ! salt flux
+         pdiag_fs = sfx_bri + sfx_bog + sfx_bom + sfx_sum + sfx_sni + sfx_opw + sfx_res + sfx_dyn + sfx_sub + sfx_lam 
+         ! heat flux
+         pdiag_ft =   hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw  & 
+            &       - hfx_thd - hfx_dyn - hfx_res - hfx_sub - hfx_spr
+
+      ELSEIF( icount == 1 ) THEN
+
+         ! -- mass diag -- !
+         zdiag_mass =   ( SUM( v_i * rhoi + v_s * rhos, dim=3 ) - pdiag_v ) * r1_rdtice                             &
+            &         + ( wfx_bog + wfx_bom + wfx_sum + wfx_sni + wfx_opw + wfx_res + wfx_dyn + wfx_lam + wfx_pnd + &
+            &             wfx_snw_sni + wfx_snw_sum + wfx_snw_dyn + wfx_snw_sub + wfx_ice_sub + wfx_spr )           &
+            &         - pdiag_fv
+         IF( MAXVAL( ABS(zdiag_mass) ) > zchk_m * rn_icechk_cel )   ll_stop_m = .TRUE.
+         !
+         ! -- salt diag -- !
+         zdiag_salt =   ( SUM( sv_i * rhoi , dim=3 ) - pdiag_s ) * r1_rdtice                                                  &
+            &         + ( sfx_bri + sfx_bog + sfx_bom + sfx_sum + sfx_sni + sfx_opw + sfx_res + sfx_dyn + sfx_sub + sfx_lam ) &
+            &         - pdiag_fs
+         IF( MAXVAL( ABS(zdiag_salt) ) > zchk_s * rn_icechk_cel )   ll_stop_s = .TRUE.
+         !
+         ! -- heat diag -- !
+         zdiag_heat =   ( SUM( SUM( e_i, dim=4 ), dim=3 ) + SUM( SUM( e_s, dim=4 ), dim=3 ) - pdiag_t ) * r1_rdtice &
+            &         + (  hfx_sum + hfx_bom + hfx_bog + hfx_dif + hfx_opw + hfx_snw                                & 
+            &            - hfx_thd - hfx_dyn - hfx_res - hfx_sub - hfx_spr )                                        &
+            &         - pdiag_ft
+         IF( MAXVAL( ABS(zdiag_heat) ) > zchk_t * rn_icechk_cel )   ll_stop_t = .TRUE.
+         !
+         ! -- other diags -- !
+         ! a_i < 0
+         zdiag_amin(:,:) = 0._wp
+         DO jl = 1, jpl
+            WHERE( a_i(:,:,jl) < 0._wp )   zdiag_amin(:,:) = 1._wp
+         ENDDO
+         ! v_i < 0
+         zdiag_vmin(:,:) = 0._wp
+         DO jl = 1, jpl
+            WHERE( v_i(:,:,jl) < 0._wp )   zdiag_vmin(:,:) = 1._wp
+         ENDDO
+         ! s_i < 0
+         zdiag_smin(:,:) = 0._wp
+         DO jl = 1, jpl
+            WHERE( s_i(:,:,jl) < 0._wp )   zdiag_smin(:,:) = 1._wp
+         ENDDO
+         ! e_i < 0
+         zdiag_emin(:,:) = 0._wp
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               WHERE( e_i(:,:,jk,jl) < 0._wp )   zdiag_emin(:,:) = 1._wp
+            ENDDO
+         ENDDO
+         ! a_i > amax
+         !WHERE( SUM( a_i, dim=3 ) > ( MAX( rn_amax_n, rn_amax_s ) + epsi10 )   ;   zdiag_amax(:,:) = 1._wp
+         !ELSEWHERE                                                             ;   zdiag_amax(:,:) = 0._wp
+         !END WHERE
+
+         IF( ll_stop_m .OR. ll_stop_s .OR. ll_stop_t ) THEN
+            clnam = 'diag_ice_conservation_'//cd_routine
+            CALL ice_cons_wri( clnam, zdiag_mass, zdiag_salt, zdiag_heat, zdiag_amin, zdiag_vmin, zdiag_smin, zdiag_emin )
+         ENDIF
+
+         IF( ll_stop_m )   CALL ctl_stop( 'STOP', cd_routine//': ice mass conservation issue' )
+         IF( ll_stop_s )   CALL ctl_stop( 'STOP', cd_routine//': ice salt conservation issue' )
+         IF( ll_stop_t )   CALL ctl_stop( 'STOP', cd_routine//': ice heat conservation issue' )
+         
+      ENDIF
+
+   END SUBROUTINE ice_cons2D
+
+   SUBROUTINE ice_cons_wri( cdfile_name, pdiag_mass, pdiag_salt, pdiag_heat, pdiag_amin, pdiag_vmin, pdiag_smin, pdiag_emin )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE ice_cons_wri  ***
+      !!        
+      !! ** Purpose :   create a NetCDF file named cdfile_name which contains 
+      !!                the instantaneous fields when conservation issue occurs
+      !!
+      !! ** Method  :   NetCDF files using ioipsl
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT( in ) ::   cdfile_name      ! name of the file created
+      REAL(wp), DIMENSION(:,:), INTENT( in ) ::   pdiag_mass, pdiag_salt, pdiag_heat, &
+         &                                        pdiag_amin, pdiag_vmin, pdiag_smin, pdiag_emin !!, pdiag_amax  
+      !!
+      INTEGER ::   inum
+      !!----------------------------------------------------------------------
+      ! 
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'ice_cons_wri : single instantaneous ice state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~  named :', cdfile_name, '...nc'
+      IF(lwp) WRITE(numout,*)                
+
+      CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE., kdlev = jpl )
+      
+      CALL iom_rstput( 0, 0, inum, 'cons_mass', pdiag_mass(:,:) , ktype = jp_r8 )    ! ice mass spurious lost/gain
+      CALL iom_rstput( 0, 0, inum, 'cons_salt', pdiag_salt(:,:) , ktype = jp_r8 )    ! ice salt spurious lost/gain
+      CALL iom_rstput( 0, 0, inum, 'cons_heat', pdiag_heat(:,:) , ktype = jp_r8 )    ! ice heat spurious lost/gain
+      ! other diags
+      CALL iom_rstput( 0, 0, inum, 'aneg_count', pdiag_amin(:,:) , ktype = jp_r8 )    ! 
+      CALL iom_rstput( 0, 0, inum, 'vneg_count', pdiag_vmin(:,:) , ktype = jp_r8 )    ! 
+      CALL iom_rstput( 0, 0, inum, 'sneg_count', pdiag_smin(:,:) , ktype = jp_r8 )    ! 
+      CALL iom_rstput( 0, 0, inum, 'eneg_count', pdiag_emin(:,:) , ktype = jp_r8 )    ! 
+      
+      CALL iom_close( inum )
+
+   END SUBROUTINE ice_cons_wri
+   
+   SUBROUTINE ice_ctl( kt )
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_ctl *** 
+      !!                 
+      !! ** Purpose :   control checks
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt      ! ocean time step
+      INTEGER  ::   ja, ji, jj, jk, jl ! dummy loop indices
+      INTEGER  ::   ialert_id          ! number of the current alert
+      REAL(wp) ::   ztmelts            ! ice layer melting point
+      CHARACTER (len=30), DIMENSION(20) ::   cl_alname   ! name of alert
+      INTEGER           , DIMENSION(20) ::   inb_alp     ! number of alerts positive
+      !!-------------------------------------------------------------------
+      inb_alp(:) = 0
+      ialert_id = 0
+      
+      ! Alert if very high salinity
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very high salinity ' ! name of the alert
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( v_i(ji,jj,jl) > epsi10  ) THEN
+                  IF( sv_i(ji,jj,jl) / v_i(ji,jj,jl) > rn_simax ) THEN
+                     WRITE(numout,*) ' ALERTE :   Very high salinity ',sv_i(ji,jj,jl)/v_i(ji,jj,jl)
+                     WRITE(numout,*) ' at i,j,l = ',ji,jj,jl
+                     inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+                  ENDIF
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      ! Alert if very low salinity
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very low salinity ' ! name of the alert
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( v_i(ji,jj,jl) > epsi10  ) THEN
+                  IF( sv_i(ji,jj,jl) / v_i(ji,jj,jl) < rn_simin ) THEN
+                     WRITE(numout,*) ' ALERTE :   Very low salinity ',sv_i(ji,jj,jl),v_i(ji,jj,jl)
+                     WRITE(numout,*) ' at i,j,l = ',ji,jj,jl
+                     inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+                  ENDIF
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      ! Alert if very cold ice
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very cold ice ' ! name of the alert
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ztmelts    =  -rTmlt * sz_i(ji,jj,jk,jl) + rt0
+                  IF( t_i(ji,jj,jk,jl) < -50.+rt0  .AND.  v_i(ji,jj,jl) > epsi10 ) THEN
+                     WRITE(numout,*) ' ALERTE :   Very cold ice ',(t_i(ji,jj,jk,jl)-rt0)
+                     WRITE(numout,*) ' at i,j,k,l = ',ji,jj,jk,jl
+                    inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+  
+      ! Alert if very warm ice
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very warm ice ' ! name of the alert
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ztmelts    =  -rTmlt * sz_i(ji,jj,jk,jl) + rt0
+                  IF( t_i(ji,jj,jk,jl) > ztmelts  .AND.  v_i(ji,jj,jl) > epsi10 ) THEN
+                     WRITE(numout,*) ' ALERTE :   Very warm ice',(t_i(ji,jj,jk,jl)-rt0)
+                     WRITE(numout,*) ' at i,j,k,l = ',ji,jj,jk,jl
+                    inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+      
+      ! Alerte if very thick ice
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very thick ice ' ! name of the alert
+      jl = jpl 
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( h_i(ji,jj,jl) > 50._wp ) THEN
+               WRITE(numout,*) ' ALERTE :   Very thick ice ',h_i(ji,jj,jl)
+               WRITE(numout,*) ' at i,j,l = ',ji,jj,jl
+               inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+            ENDIF
+         END DO
+      END DO
+
+      ! Alerte if very thin ice
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very thin ice ' ! name of the alert
+      jl = 1 
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( h_i(ji,jj,jl) < rn_himin ) THEN
+               WRITE(numout,*) ' ALERTE :   Very thin ice ',h_i(ji,jj,jl)
+               WRITE(numout,*) ' at i,j,l = ',ji,jj,jl
+               inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+            ENDIF
+         END DO
+      END DO
+
+      ! Alert if very fast ice
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Very fast ice ' ! name of the alert
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( MAX( ABS( u_ice(ji,jj) ), ABS( v_ice(ji,jj) ) ) > 2. ) THEN
+               WRITE(numout,*) ' ALERTE :   Very fast ice ',MAX( ABS( u_ice(ji,jj) ), ABS( v_ice(ji,jj) ) )
+               WRITE(numout,*) ' at i,j = ',ji,jj
+               inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+            ENDIF
+         END DO
+      END DO
+
+      ! Alert if there is ice on continents
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Ice on continents ' ! name of the alert
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( tmask(ji,jj,1) == 0._wp .AND. ( at_i(ji,jj) > 0._wp .OR. vt_i(ji,jj) > 0._wp ) ) THEN 
+               WRITE(numout,*) ' ALERTE :   Ice on continents ',at_i(ji,jj),vt_i(ji,jj)
+               WRITE(numout,*) ' at i,j = ',ji,jj
+               inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+            ENDIF
+         END DO
+      END DO
+
+      ! Alert if incompatible ice concentration and volume
+      ialert_id = ialert_id + 1 ! reference number of this alert
+      cl_alname(ialert_id) = ' Incompatible ice conc and vol ' ! name of the alert
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF(  ( vt_i(ji,jj) == 0._wp .AND. at_i(ji,jj) >  0._wp ) .OR. &
+               & ( vt_i(ji,jj) >  0._wp .AND. at_i(ji,jj) == 0._wp ) ) THEN 
+               WRITE(numout,*) ' ALERTE :   Incompatible ice conc and vol ',at_i(ji,jj),vt_i(ji,jj)
+               WRITE(numout,*) ' at i,j = ',ji,jj
+               inb_alp(ialert_id) = inb_alp(ialert_id) + 1
+            ENDIF
+         END DO
+      END DO
+
+      ! sum of the alerts on all processors
+      IF( lk_mpp ) THEN
+         DO ja = 1, ialert_id
+            CALL mpp_sum('icectl', inb_alp(ja))
+         END DO
+      ENDIF
+
+      ! print alerts
+      IF( lwp ) THEN
+         WRITE(numout,*) ' time step ',kt
+         WRITE(numout,*) ' All alerts at the end of ice model '
+         DO ja = 1, ialert_id
+            WRITE(numout,*) ja, cl_alname(ja)//' : ', inb_alp(ja), ' times ! '
+         END DO
+      ENDIF
+     !
+   END SUBROUTINE ice_ctl
+ 
+   SUBROUTINE ice_prt( kt, ki, kj, kn, cd1 )
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_prt *** 
+      !!                 
+      !! ** Purpose :   Writes global ice state on the (i,j) point 
+      !!                in ocean.ouput 
+      !!                3 possibilities exist 
+      !!                n = 1/-1 -> simple ice state
+      !!                n = 2    -> exhaustive state
+      !!                n = 3    -> ice/ocean salt fluxes
+      !!
+      !! ** input   :   point coordinates (i,j) 
+      !!                n : number of the option
+      !!-------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt            ! ocean time step
+      INTEGER         , INTENT(in) ::   ki, kj, kn    ! ocean gridpoint indices
+      CHARACTER(len=*), INTENT(in) ::   cd1           !
+      !!
+      INTEGER :: jl, ji, jj
+      !!-------------------------------------------------------------------
+
+      DO ji = mi0(ki), mi1(ki)
+         DO jj = mj0(kj), mj1(kj)
+
+            WRITE(numout,*) ' time step ',kt,' ',cd1             ! print title
+
+            !----------------
+            !  Simple state
+            !----------------
+            
+            IF ( kn == 1 .OR. kn == -1 ) THEN
+               WRITE(numout,*) ' ice_prt - Point : ',ji,jj
+               WRITE(numout,*) ' ~~~~~~~~~~~~~~ '
+               WRITE(numout,*) ' Simple state '
+               WRITE(numout,*) ' masks s,u,v   : ', tmask(ji,jj,1), umask(ji,jj,1), vmask(ji,jj,1)
+               WRITE(numout,*) ' lat - long    : ', gphit(ji,jj), glamt(ji,jj)
+               WRITE(numout,*) ' - Ice drift   '
+               WRITE(numout,*) '   ~~~~~~~~~~~ '
+               WRITE(numout,*) ' u_ice(i-1,j)  : ', u_ice(ji-1,jj)
+               WRITE(numout,*) ' u_ice(i  ,j)  : ', u_ice(ji,jj)
+               WRITE(numout,*) ' v_ice(i  ,j-1): ', v_ice(ji,jj-1)
+               WRITE(numout,*) ' v_ice(i  ,j)  : ', v_ice(ji,jj)
+               WRITE(numout,*) ' strength      : ', strength(ji,jj)
+               WRITE(numout,*) ' - Cell values '
+               WRITE(numout,*) '   ~~~~~~~~~~~ '
+               WRITE(numout,*) ' at_i          : ', at_i(ji,jj)       
+               WRITE(numout,*) ' ato_i         : ', ato_i(ji,jj)       
+               WRITE(numout,*) ' vt_i          : ', vt_i(ji,jj)       
+               WRITE(numout,*) ' vt_s          : ', vt_s(ji,jj)       
+               DO jl = 1, jpl
+                  WRITE(numout,*) ' - Category (', jl,')'
+                  WRITE(numout,*) '   ~~~~~~~~~~~ '
+                  WRITE(numout,*) ' a_i           : ', a_i(ji,jj,jl)
+                  WRITE(numout,*) ' h_i           : ', h_i(ji,jj,jl)
+                  WRITE(numout,*) ' h_s           : ', h_s(ji,jj,jl)
+                  WRITE(numout,*) ' v_i           : ', v_i(ji,jj,jl)
+                  WRITE(numout,*) ' v_s           : ', v_s(ji,jj,jl)
+                  WRITE(numout,*) ' e_s           : ', e_s(ji,jj,1:nlay_s,jl)
+                  WRITE(numout,*) ' e_i           : ', e_i(ji,jj,1:nlay_i,jl)
+                  WRITE(numout,*) ' t_su          : ', t_su(ji,jj,jl)
+                  WRITE(numout,*) ' t_snow        : ', t_s(ji,jj,1:nlay_s,jl)
+                  WRITE(numout,*) ' t_i           : ', t_i(ji,jj,1:nlay_i,jl)
+                  WRITE(numout,*) ' s_i           : ', s_i(ji,jj,jl)
+                  WRITE(numout,*) ' sv_i          : ', sv_i(ji,jj,jl)
+                  WRITE(numout,*)
+               END DO
+            ENDIF
+
+            !--------------------
+            !  Exhaustive state
+            !--------------------
+            
+            IF ( kn .EQ. 2 ) THEN
+               WRITE(numout,*) ' ice_prt - Point : ',ji,jj
+               WRITE(numout,*) ' ~~~~~~~~~~~~~~ '
+               WRITE(numout,*) ' Exhaustive state '
+               WRITE(numout,*) ' lat - long ', gphit(ji,jj), glamt(ji,jj)
+               WRITE(numout,*) 
+               WRITE(numout,*) ' - Cell values '
+               WRITE(numout,*) '   ~~~~~~~~~~~ '
+               WRITE(numout,*) ' at_i          : ', at_i(ji,jj)       
+               WRITE(numout,*) ' vt_i          : ', vt_i(ji,jj)       
+               WRITE(numout,*) ' vt_s          : ', vt_s(ji,jj)       
+               WRITE(numout,*) ' u_ice(i-1,j)  : ', u_ice(ji-1,jj)
+               WRITE(numout,*) ' u_ice(i  ,j)  : ', u_ice(ji,jj)
+               WRITE(numout,*) ' v_ice(i  ,j-1): ', v_ice(ji,jj-1)
+               WRITE(numout,*) ' v_ice(i  ,j)  : ', v_ice(ji,jj)
+               WRITE(numout,*) ' strength      : ', strength(ji,jj)
+               WRITE(numout,*)
+               
+               DO jl = 1, jpl
+                  WRITE(numout,*) ' - Category (',jl,')'
+                  WRITE(numout,*) '   ~~~~~~~~         ' 
+                  WRITE(numout,*) ' h_i        : ', h_i(ji,jj,jl)              , ' h_s        : ', h_s(ji,jj,jl)
+                  WRITE(numout,*) ' t_i        : ', t_i(ji,jj,1:nlay_i,jl)
+                  WRITE(numout,*) ' t_su       : ', t_su(ji,jj,jl)             , ' t_s        : ', t_s(ji,jj,1:nlay_s,jl)
+                  WRITE(numout,*) ' s_i        : ', s_i(ji,jj,jl)              , ' o_i        : ', o_i(ji,jj,jl)
+                  WRITE(numout,*) ' a_i        : ', a_i(ji,jj,jl)              , ' a_i_b      : ', a_i_b(ji,jj,jl)   
+                  WRITE(numout,*) ' v_i        : ', v_i(ji,jj,jl)              , ' v_i_b      : ', v_i_b(ji,jj,jl)   
+                  WRITE(numout,*) ' v_s        : ', v_s(ji,jj,jl)              , ' v_s_b      : ', v_s_b(ji,jj,jl)  
+                  WRITE(numout,*) ' e_i1       : ', e_i(ji,jj,1,jl)            , ' ei1        : ', e_i_b(ji,jj,1,jl) 
+                  WRITE(numout,*) ' e_i2       : ', e_i(ji,jj,2,jl)            , ' ei2_b      : ', e_i_b(ji,jj,2,jl)  
+                  WRITE(numout,*) ' e_snow     : ', e_s(ji,jj,1,jl)            , ' e_snow_b   : ', e_s_b(ji,jj,1,jl) 
+                  WRITE(numout,*) ' sv_i       : ', sv_i(ji,jj,jl)             , ' sv_i_b     : ', sv_i_b(ji,jj,jl)   
+               END DO !jl
+               
+               WRITE(numout,*)
+               WRITE(numout,*) ' - Heat / FW fluxes '
+               WRITE(numout,*) '   ~~~~~~~~~~~~~~~~ '
+               WRITE(numout,*) ' - Heat fluxes in and out the ice ***'
+               WRITE(numout,*) ' qsr_ini       : ', (1._wp-at_i_b(ji,jj)) * qsr(ji,jj) + SUM( a_i_b(ji,jj,:) * qsr_ice(ji,jj,:) )
+               WRITE(numout,*) ' qns_ini       : ', (1._wp-at_i_b(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)  
+               WRITE(numout,*) ' sss        : ', sss_m(ji,jj)  
+               WRITE(numout,*) 
+               WRITE(numout,*) ' - Stresses '
+               WRITE(numout,*) '   ~~~~~~~~ '
+               WRITE(numout,*) ' utau_ice   : ', utau_ice(ji,jj) 
+               WRITE(numout,*) ' vtau_ice   : ', vtau_ice(ji,jj)
+               WRITE(numout,*) ' utau       : ', utau    (ji,jj) 
+               WRITE(numout,*) ' vtau       : ', vtau    (ji,jj)
+            ENDIF
+            
+            !---------------------
+            ! Salt / heat fluxes
+            !---------------------
+            
+            IF ( kn .EQ. 3 ) THEN
+               WRITE(numout,*) ' ice_prt - Point : ',ji,jj
+               WRITE(numout,*) ' ~~~~~~~~~~~~~~ '
+               WRITE(numout,*) ' - Salt / Heat Fluxes '
+               WRITE(numout,*) '   ~~~~~~~~~~~~~~~~ '
+               WRITE(numout,*) ' lat - long ', gphit(ji,jj), glamt(ji,jj)
+               WRITE(numout,*)
+               WRITE(numout,*) ' - Heat fluxes at bottom interface ***'
+               WRITE(numout,*) ' qsr       : ', qsr(ji,jj)
+               WRITE(numout,*) ' qns       : ', qns(ji,jj)
+               WRITE(numout,*)
+               WRITE(numout,*) ' hfx_mass     : ', hfx_thd(ji,jj) + hfx_dyn(ji,jj) + hfx_snw(ji,jj) + hfx_res(ji,jj)
+               WRITE(numout,*) ' qt_atm_oi    : ', qt_atm_oi(ji,jj)
+               WRITE(numout,*) ' qt_oce_ai    : ', qt_oce_ai(ji,jj)
+               WRITE(numout,*) ' dhc          : ', diag_heat(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,*) ' qsb_ice_bot  : ', qsb_ice_bot(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       : ', sfx    (ji,jj)
+               WRITE(numout,*) ' sfx_res   : ', sfx_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 
+            WRITE(numout,*) ' '
+            !
+         END DO
+      END DO
+      !
+   END SUBROUTINE ice_prt
+
+   SUBROUTINE ice_prt3D( cd_routine )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_prt3D ***
+      !!
+      !! ** Purpose : CTL prints of ice arrays in case ln_ctl is activated 
+      !!
+      !!-------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) ::   cd_routine    ! name of the routine
+      INTEGER                      ::   jk, jl        ! dummy loop indices
+      
+      CALL prt_ctl_info(' ========== ')
+      CALL prt_ctl_info( cd_routine )
+      CALL prt_ctl_info(' ========== ')
+      CALL prt_ctl_info(' - Cell values : ')
+      CALL prt_ctl_info('   ~~~~~~~~~~~~~ ')
+      CALL prt_ctl(tab2d_1=e1e2t      , clinfo1=' cell area   :')
+      CALL prt_ctl(tab2d_1=at_i       , clinfo1=' at_i        :')
+      CALL prt_ctl(tab2d_1=ato_i      , clinfo1=' ato_i       :')
+      CALL prt_ctl(tab2d_1=vt_i       , clinfo1=' vt_i        :')
+      CALL prt_ctl(tab2d_1=vt_s       , clinfo1=' vt_s        :')
+      CALL prt_ctl(tab2d_1=divu_i     , clinfo1=' divu_i      :')
+      CALL prt_ctl(tab2d_1=delta_i    , clinfo1=' delta_i     :')
+      CALL prt_ctl(tab2d_1=stress1_i  , clinfo1=' stress1_i   :')
+      CALL prt_ctl(tab2d_1=stress2_i  , clinfo1=' stress2_i   :')
+      CALL prt_ctl(tab2d_1=stress12_i , clinfo1=' stress12_i  :')
+      CALL prt_ctl(tab2d_1=strength   , clinfo1=' strength    :')
+      CALL prt_ctl(tab2d_1=delta_i    , clinfo1=' delta_i     :')
+      CALL prt_ctl(tab2d_1=u_ice      , clinfo1=' u_ice       :', tab2d_2=v_ice      , clinfo2=' v_ice       :')
+       
+      DO jl = 1, jpl
+         CALL prt_ctl_info(' ')
+         CALL prt_ctl_info(' - Category : ', ivar1=jl)
+         CALL prt_ctl_info('   ~~~~~~~~~~')
+         CALL prt_ctl(tab2d_1=h_i        (:,:,jl)        , clinfo1= ' h_i         : ')
+         CALL prt_ctl(tab2d_1=h_s        (:,:,jl)        , clinfo1= ' h_s         : ')
+         CALL prt_ctl(tab2d_1=t_su       (:,:,jl)        , clinfo1= ' t_su        : ')
+         CALL prt_ctl(tab2d_1=t_s        (:,:,1,jl)      , clinfo1= ' t_snow      : ')
+         CALL prt_ctl(tab2d_1=s_i        (:,:,jl)        , clinfo1= ' s_i         : ')
+         CALL prt_ctl(tab2d_1=o_i        (:,:,jl)        , clinfo1= ' o_i         : ')
+         CALL prt_ctl(tab2d_1=a_i        (:,:,jl)        , clinfo1= ' a_i         : ')
+         CALL prt_ctl(tab2d_1=v_i        (:,:,jl)        , clinfo1= ' v_i         : ')
+         CALL prt_ctl(tab2d_1=v_s        (:,:,jl)        , clinfo1= ' v_s         : ')
+         CALL prt_ctl(tab2d_1=e_s        (:,:,1,jl)      , clinfo1= ' e_snow      : ')
+         CALL prt_ctl(tab2d_1=sv_i       (:,:,jl)        , clinfo1= ' sv_i        : ')
+         CALL prt_ctl(tab2d_1=oa_i       (:,:,jl)        , clinfo1= ' oa_i        : ')
+         
+         DO jk = 1, nlay_i
+            CALL prt_ctl_info(' - Layer : ', ivar1=jk)
+            CALL prt_ctl(tab2d_1=t_i(:,:,jk,jl) , clinfo1= ' t_i       : ')
+            CALL prt_ctl(tab2d_1=e_i(:,:,jk,jl) , clinfo1= ' e_i       : ')
+         END DO
+      END DO
+      
+      CALL prt_ctl_info(' ')
+      CALL prt_ctl_info(' - Stresses : ')
+      CALL prt_ctl_info('   ~~~~~~~~~~ ')
+      CALL prt_ctl(tab2d_1=utau       , clinfo1= ' utau      : ', tab2d_2=vtau       , clinfo2= ' vtau      : ')
+      CALL prt_ctl(tab2d_1=utau_ice   , clinfo1= ' utau_ice  : ', tab2d_2=vtau_ice   , clinfo2= ' vtau_ice  : ')
+      
+   END SUBROUTINE ice_prt3D
+
+
+   SUBROUTINE ice_drift_wri( kt )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE ice_drift_wri ***
+      !!
+      !! ** Purpose : conservation of mass, salt and heat
+      !!              write the drift in a ascii file at each time step
+      !!              and the total run drifts
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ice time-step index
+      !
+      INTEGER  ::   ji, jj
+      REAL(wp) ::   zdiag_mass, zdiag_salt, zdiag_heat, zdiag_adv_mass, zdiag_adv_salt, zdiag_adv_heat
+      !!REAL(wp), DIMENSION(jpi,jpj) ::   zdiag_mass2D, zdiag_salt2D, zdiag_heat2D
+      !!-------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_drift_wri: sea-ice drifts'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      !clem: the following lines check the ice drift in 2D.
+      !      to use this check, uncomment those lines and add the 3 fields in field_def_ice.xml
+      !!! 2D budgets (must be close to 0)
+      !!IF( iom_use('icedrift_mass') .OR. iom_use('icedrift_salt') .OR. iom_use('icedrift_heat') ) THEN
+      !!   DO jj = 1, jpj
+      !!      DO ji = 1, jpi
+      !!         zdiag_mass2D(ji,jj) =   wfx_ice(ji,jj)   + wfx_snw(ji,jj)   + wfx_spr(ji,jj) + wfx_sub(ji,jj) &
+      !!            &                  + diag_vice(ji,jj) + diag_vsnw(ji,jj) - diag_adv_mass(ji,jj)
+      !!         zdiag_salt2D(ji,jj) = sfx(ji,jj) + diag_sice(ji,jj) - diag_adv_salt(ji,jj)
+      !!         zdiag_heat2D(ji,jj) = qt_oce_ai(ji,jj) - qt_atm_oi(ji,jj) + diag_heat(ji,jj) - diag_adv_heat(ji,jj)
+      !!      END DO
+      !!   END DO
+      !!   !
+      !!   ! write outputs
+      !!   CALL iom_put( 'icedrift_mass', zdiag_mass2D )
+      !!   CALL iom_put( 'icedrift_salt', zdiag_salt2D )
+      !!   CALL iom_put( 'icedrift_heat', zdiag_heat2D )
+      !!ENDIF
+
+      ! -- mass diag -- !
+      zdiag_mass     = glob_sum( 'icectl', (  wfx_ice   + wfx_snw   + wfx_spr + wfx_sub &
+         &                                  + diag_vice + diag_vsnw - diag_adv_mass ) * e1e2t ) * rdt_ice
+      zdiag_adv_mass = glob_sum( 'icectl', diag_adv_mass * e1e2t ) * rdt_ice
+
+      ! -- salt diag -- !
+      zdiag_salt     = glob_sum( 'icectl', ( sfx + diag_sice - diag_adv_salt ) * e1e2t ) * rdt_ice * 1.e-3
+      zdiag_adv_salt = glob_sum( 'icectl', diag_adv_salt * e1e2t ) * rdt_ice * 1.e-3
+
+      ! -- heat diag -- !
+      zdiag_heat     = glob_sum( 'icectl', ( qt_oce_ai - qt_atm_oi + diag_heat - diag_adv_heat ) * e1e2t )
+      zdiag_adv_heat = glob_sum( 'icectl', diag_adv_heat * e1e2t )
+
+      !                    ! write out to file
+      IF( lwp ) THEN
+         ! check global drift (must be close to 0)
+         WRITE(numicedrift,FMT='(2x,i6,3x,a19,4x,f25.5)') kt, 'mass drift     [kg]', zdiag_mass
+         WRITE(numicedrift,FMT='(11x,     a19,4x,f25.5)')     'salt drift     [kg]', zdiag_salt
+         WRITE(numicedrift,FMT='(11x,     a19,4x,f25.5)')     'heat drift     [W] ', zdiag_heat
+         ! check drift from advection scheme (can be /=0 with bdy but not sure why)
+         WRITE(numicedrift,FMT='(11x,     a19,4x,f25.5)')     'mass drift adv [kg]', zdiag_adv_mass
+         WRITE(numicedrift,FMT='(11x,     a19,4x,f25.5)')     'salt drift adv [kg]', zdiag_adv_salt
+         WRITE(numicedrift,FMT='(11x,     a19,4x,f25.5)')     'heat drift adv [W] ', zdiag_adv_heat
+      ENDIF
+      !                    ! drifts
+      rdiag_icemass = rdiag_icemass + zdiag_mass
+      rdiag_icesalt = rdiag_icesalt + zdiag_salt
+      rdiag_iceheat = rdiag_iceheat + zdiag_heat
+      rdiag_adv_icemass = rdiag_adv_icemass + zdiag_adv_mass
+      rdiag_adv_icesalt = rdiag_adv_icesalt + zdiag_adv_salt
+      rdiag_adv_iceheat = rdiag_adv_iceheat + zdiag_adv_heat
+      !
+      !                    ! output drifts and close ascii file
+      IF( kt == nitend - nn_fsbc + 1 .AND. lwp ) THEN
+         ! to ascii file
+         WRITE(numicedrift,*) '******************************************'
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run mass drift     [kg]', rdiag_icemass
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run mass drift adv [kg]', rdiag_adv_icemass
+         WRITE(numicedrift,*) '******************************************'
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run salt drift     [kg]', rdiag_icesalt
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run salt drift adv [kg]', rdiag_adv_icesalt
+         WRITE(numicedrift,*) '******************************************'
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run heat drift     [W] ', rdiag_iceheat
+         WRITE(numicedrift,FMT='(3x,a23,6x,E10.2)') 'Run heat drift adv [W] ', rdiag_adv_iceheat
+         CLOSE( numicedrift )
+         !
+         ! to ocean output
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_drift_wri: ice drifts information for the run '
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+         ! check global drift (must be close to 0)
+         WRITE(numout,*) '   sea-ice mass drift     [kg] = ', rdiag_icemass
+         WRITE(numout,*) '   sea-ice salt drift     [kg] = ', rdiag_icesalt
+         WRITE(numout,*) '   sea-ice heat drift     [W]  = ', rdiag_iceheat
+         ! check drift from advection scheme (can be /=0 with bdy but not sure why)
+         WRITE(numout,*) '   sea-ice mass drift adv [kg] = ', rdiag_adv_icemass
+         WRITE(numout,*) '   sea-ice salt drift adv [kg] = ', rdiag_adv_icesalt
+         WRITE(numout,*) '   sea-ice heat drift adv [W]  = ', rdiag_adv_iceheat
+      ENDIF
+      !
+   END SUBROUTINE ice_drift_wri
+
+   SUBROUTINE ice_drift_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_drift_init  ***
+      !!                   
+      !! ** Purpose :   create output file, initialise arrays
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_icediachk ) RETURN ! exit
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_drift_init: Output ice drifts to ',TRIM(clname), ' file'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+         WRITE(numout,*)
+         !
+         ! create output ascii file
+         CALL ctl_opn( numicedrift, clname, 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', 1, numout, lwp, narea )
+         WRITE(numicedrift,*) 'Timestep  Drifts'
+         WRITE(numicedrift,*) '******************************************'
+      ENDIF
+      !
+      rdiag_icemass = 0._wp
+      rdiag_icesalt = 0._wp
+      rdiag_iceheat = 0._wp
+      rdiag_adv_icemass = 0._wp
+      rdiag_adv_icesalt = 0._wp
+      rdiag_adv_iceheat = 0._wp
+      !
+   END SUBROUTINE ice_drift_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty Module           No SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icectl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedia.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedia.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedia.F90	(revision 14097)
@@ -0,0 +1,287 @@
+MODULE icedia
+   !!======================================================================
+   !!                       ***  MODULE icedia  ***
+   !!  Sea-Ice:   global budgets 
+   !!======================================================================
+   !! History :  3.4  !  2012-10  (C. Rousset)       original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!    ice_dia      : diagnostic of the sea-ice global heat content, salt content and volume conservation
+   !!    ice_dia_init : initialization of budget calculation
+   !!    ice_dia_rst  : read/write budgets restart
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constant
+   USE daymod         ! model calendar
+   USE sbc_oce , ONLY : sfx, nn_fsbc   ! surface boundary condition: ocean fields
+   USE ice            ! sea-ice: variables
+   USE icerst         ! sea-ice: restart
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dia        ! called by icestp.F90
+   PUBLIC   ice_dia_init   ! called in icestp.F90
+
+   REAL(wp), SAVE ::   z1_e1e2  ! inverse of the ocean area
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   vol_loc_ini, sal_loc_ini, tem_loc_ini                    ! initial volume, salt and heat contents
+   REAL(wp)                              ::   frc_sal, frc_voltop, frc_volbot, frc_temtop, frc_tembot  ! global forcing trends
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION ice_dia_alloc()
+      !!---------------------------------------------------------------------!
+      !!                ***  ROUTINE ice_dia_alloc ***
+      !!---------------------------------------------------------------------!
+      ALLOCATE( vol_loc_ini(jpi,jpj), sal_loc_ini(jpi,jpj), tem_loc_ini(jpi,jpj), STAT=ice_dia_alloc )
+
+      CALL mpp_sum ( 'icedia', ice_dia_alloc )
+      IF( ice_dia_alloc /= 0 )   CALL ctl_stop( 'STOP',  'ice_dia_alloc: failed to allocate arrays'  )
+      !
+   END FUNCTION ice_dia_alloc
+
+   SUBROUTINE ice_dia( kt )
+      !!---------------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dia  ***
+      !!     
+      !! ** Purpose:   Compute the sea-ice global heat content, salt content 
+      !!             and volume conservation
+      !!---------------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step 
+      !!
+      REAL(wp)   ::   zbg_ivol, zbg_item, zbg_area, zbg_isal
+      REAL(wp)   ::   zbg_svol, zbg_stem
+      REAL(wp)   ::   z_frc_voltop, z_frc_temtop, z_frc_sal
+      REAL(wp)   ::   z_frc_volbot, z_frc_tembot  
+      REAL(wp)   ::   zdiff_vol, zdiff_sal, zdiff_tem  
+      !!---------------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('ice_dia')
+
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'icedia: output ice diagnostics (integrated over the domain)'
+         WRITE(numout,*)'~~~~~~'
+      ENDIF
+
+      IF( kt == nit000 ) THEN
+         z1_e1e2 = 1._wp / glob_sum( 'icedia', e1e2t(:,:) )
+      ENDIF
+      
+      ! ----------------------- !
+      ! 1 -  Contents           !
+      ! ----------------------- !
+      IF(  iom_use('ibgvol_tot' ) .OR. iom_use('sbgvol_tot' ) .OR. iom_use('ibgarea_tot') .OR. &
+         & iom_use('ibgsalt_tot') .OR. iom_use('ibgheat_tot') .OR. iom_use('sbgheat_tot') ) THEN
+
+         zbg_ivol = glob_sum( 'icedia', vt_i(:,:) * e1e2t(:,:) ) * 1.e-9  ! ice volume (km3)
+         zbg_svol = glob_sum( 'icedia', vt_s(:,:) * e1e2t(:,:) ) * 1.e-9  ! snow volume (km3)
+         zbg_area = glob_sum( 'icedia', at_i(:,:) * e1e2t(:,:) ) * 1.e-6  ! area (km2)
+         zbg_isal = glob_sum( 'icedia', st_i(:,:) * e1e2t(:,:) ) * 1.e-9  ! salt content (pss*km3)
+         zbg_item = glob_sum( 'icedia', et_i(:,:) * e1e2t(:,:) ) * 1.e-20 ! heat content (1.e20 J)
+         zbg_stem = glob_sum( 'icedia', et_s(:,:) * e1e2t(:,:) ) * 1.e-20 ! heat content (1.e20 J)
+
+         CALL iom_put( 'ibgvol_tot'  , zbg_ivol ) 
+         CALL iom_put( 'sbgvol_tot'  , zbg_svol ) 
+         CALL iom_put( 'ibgarea_tot' , zbg_area ) 
+         CALL iom_put( 'ibgsalt_tot' , zbg_isal ) 
+         CALL iom_put( 'ibgheat_tot' , zbg_item ) 
+         CALL iom_put( 'sbgheat_tot' , zbg_stem ) 
+ 
+      ENDIF
+
+      ! ---------------------------!
+      ! 2 - Trends due to forcing  !
+      ! ---------------------------!
+      ! they must be kept outside an IF(iom_use) because of the call to dia_rst below
+      z_frc_volbot = r1_rau0 * glob_sum( 'icedia', -( wfx_ice(:,:) + wfx_snw(:,:) + wfx_err_sub(:,:) ) * e1e2t(:,:) ) * 1.e-9   ! freshwater flux ice/snow-ocean 
+      z_frc_voltop = r1_rau0 * glob_sum( 'icedia', -( wfx_sub(:,:) + wfx_spr(:,:) )                    * e1e2t(:,:) ) * 1.e-9   ! freshwater flux ice/snow-atm
+      z_frc_sal    = r1_rau0 * glob_sum( 'icedia', -      sfx(:,:)                                     * e1e2t(:,:) ) * 1.e-9   ! salt fluxes ice/snow-ocean
+      z_frc_tembot =           glob_sum( 'icedia',  qt_oce_ai(:,:)                                     * e1e2t(:,:) ) * 1.e-20  ! heat on top of ocean (and below ice)
+      z_frc_temtop =           glob_sum( 'icedia',  qt_atm_oi(:,:)                                     * e1e2t(:,:) ) * 1.e-20  ! heat on top of ice-coean
+      !
+      frc_voltop  = frc_voltop  + z_frc_voltop  * rdt_ice ! km3
+      frc_volbot  = frc_volbot  + z_frc_volbot  * rdt_ice ! km3
+      frc_sal     = frc_sal     + z_frc_sal     * rdt_ice ! km3*pss
+      frc_temtop  = frc_temtop  + z_frc_temtop  * rdt_ice ! 1.e20 J
+      frc_tembot  = frc_tembot  + z_frc_tembot  * rdt_ice ! 1.e20 J
+
+      CALL iom_put( 'ibgfrcvoltop' , frc_voltop )   ! vol  forcing ice/snw-atm          (km3 equivalent ocean water) 
+      CALL iom_put( 'ibgfrcvolbot' , frc_volbot )   ! vol  forcing ice/snw-ocean        (km3 equivalent ocean water) 
+      CALL iom_put( 'ibgfrcsal'    , frc_sal    )   ! sal - forcing                     (psu*km3 equivalent ocean water)   
+      CALL iom_put( 'ibgfrctemtop' , frc_temtop )   ! heat on top of ice/snw/ocean      (1.e20 J)   
+      CALL iom_put( 'ibgfrctembot' , frc_tembot )   ! heat on top of ocean(below ice)   (1.e20 J)   
+
+      IF(  iom_use('ibgfrchfxtop') .OR. iom_use('ibgfrchfxbot') ) THEN
+         CALL iom_put( 'ibgfrchfxtop' , frc_temtop * z1_e1e2 * 1.e-20 * kt*rdt ) ! heat on top of ice/snw/ocean      (W/m2)
+         CALL iom_put( 'ibgfrchfxbot' , frc_tembot * z1_e1e2 * 1.e-20 * kt*rdt ) ! heat on top of ocean(below ice)   (W/m2) 
+      ENDIF
+      
+      ! ---------------------------------- !
+      ! 3 -  Content variations and drifts !
+      ! ---------------------------------- !
+      IF(  iom_use('ibgvolume') .OR. iom_use('ibgsaltco') .OR. iom_use('ibgheatco') .OR. iom_use('ibgheatfx') ) THEN
+            
+         zdiff_vol = r1_rau0 * glob_sum( 'icedia', ( rhoi*vt_i(:,:) + rhos*vt_s(:,:) - vol_loc_ini(:,:) ) * e1e2t(:,:) ) * 1.e-9   ! freshwater trend (km3) 
+         zdiff_sal = r1_rau0 * glob_sum( 'icedia', ( rhoi*st_i(:,:)                  - sal_loc_ini(:,:) ) * e1e2t(:,:) ) * 1.e-9   ! salt content trend (km3*pss)
+         zdiff_tem =           glob_sum( 'icedia', ( et_i(:,:) + et_s(:,:)           - tem_loc_ini(:,:) ) * e1e2t(:,:) ) * 1.e-20  ! heat content trend (1.e20 J)
+         !                               + SUM( qevap_ice * a_i_b, dim=3 )       !! clem: I think this term should not be there (but needs a check)
+         
+         zdiff_vol = zdiff_vol - ( frc_voltop + frc_volbot )
+         zdiff_sal = zdiff_sal - frc_sal
+         zdiff_tem = zdiff_tem - ( frc_tembot - frc_temtop )
+         
+         CALL iom_put( 'ibgvolume' , zdiff_vol )   ! ice/snow volume  drift            (km3 equivalent ocean water)         
+         CALL iom_put( 'ibgsaltco' , zdiff_sal )   ! ice salt content drift            (psu*km3 equivalent ocean water)
+         CALL iom_put( 'ibgheatco' , zdiff_tem )   ! ice/snow heat content drift       (1.e20 J)
+         !
+      ENDIF
+      
+      IF( lrst_ice )   CALL ice_dia_rst( 'WRITE', kt_ice )
+      !
+      IF( ln_timing )   CALL timing_stop('ice_dia')
+      !
+   END SUBROUTINE ice_dia
+
+
+   SUBROUTINE ice_dia_init
+      !!---------------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dia_init  ***
+      !!     
+      !! ** 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            ::   ios, ierror   ! local integer
+      !!
+      NAMELIST/namdia/ ln_icediachk, rn_icechk_cel, rn_icechk_glo, ln_icediahsb, ln_icectl, iiceprt, jiceprt  
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )      ! Namelist namdia in reference namelist : Parameters for ice
+      READ  ( numnam_ice_ref, namdia, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdia in reference namelist' )
+      REWIND( numnam_ice_cfg )      ! Namelist namdia in configuration namelist : Parameters for ice
+      READ  ( numnam_ice_cfg, namdia, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdia in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namdia )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dia_init: ice diagnostics'
+         WRITE(numout,*) ' ~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdia:'
+         WRITE(numout,*) '      Diagnose online heat/mass/salt conservation ln_icediachk  = ', ln_icediachk
+         WRITE(numout,*) '         threshold for conservation (gridcell)    rn_icechk_cel = ', rn_icechk_cel
+         WRITE(numout,*) '         threshold for conservation (global)      rn_icechk_glo = ', rn_icechk_glo
+         WRITE(numout,*) '      Output          heat/mass/salt budget       ln_icediahsb  = ', ln_icediahsb
+         WRITE(numout,*) '      control prints for a given grid point       ln_icectl     = ', ln_icectl
+         WRITE(numout,*) '         chosen grid point position          (iiceprt,jiceprt)  = (', iiceprt,',', jiceprt,')'
+      ENDIF
+      !      
+      IF( ln_icediahsb ) THEN
+         IF( ice_dia_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'ice_dia_init : unable to allocate arrays' )   ! allocate tke arrays
+         CALL ice_dia_rst( 'READ' )   ! read or initialize all required files
+      ENDIF
+      !
+   END SUBROUTINE ice_dia_init
+
+
+   SUBROUTINE ice_dia_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE icedia_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write DIA file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter    ! local integer
+      REAL(wp) ::   ziter   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            CALL iom_get( numrir, 'kt_ice' , ziter )
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'ice_dia_rst read at time step = ', ziter
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            CALL iom_get( numrir, 'frc_voltop' , frc_voltop  )
+            CALL iom_get( numrir, 'frc_volbot' , frc_volbot  )
+            CALL iom_get( numrir, 'frc_temtop' , frc_temtop  )
+            CALL iom_get( numrir, 'frc_tembot' , frc_tembot  )
+            CALL iom_get( numrir, 'frc_sal'    , frc_sal     )
+            CALL iom_get( numrir, jpdom_autoglo, 'vol_loc_ini', vol_loc_ini )
+            CALL iom_get( numrir, jpdom_autoglo, 'tem_loc_ini', tem_loc_ini )
+            CALL iom_get( numrir, jpdom_autoglo, 'sal_loc_ini', sal_loc_ini )
+         ELSE
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) ' ice_dia at initial state '
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+            ! set trends to 0
+            frc_voltop  = 0._wp                                          
+            frc_volbot  = 0._wp                                          
+            frc_temtop  = 0._wp                                                 
+            frc_tembot  = 0._wp                                                 
+            frc_sal     = 0._wp                                                 
+            ! record initial ice volume, salt and temp
+            vol_loc_ini(:,:) = rhoi * vt_i(:,:) + rhos * vt_s(:,:)  ! ice/snow volume (kg/m2)
+            tem_loc_ini(:,:) = et_i(:,:) + et_s(:,:)                ! ice/snow heat content (J)
+            sal_loc_ini(:,:) = rhoi * st_i(:,:)                     ! ice salt content (pss*kg/m2)
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         iter = kt + nn_fsbc - 1   ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         IF( iter == nitrst ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'ice_dia_rst write at time step = ', kt
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         ENDIF
+         !
+         ! Write in numriw (if iter == nitrst)
+         ! ------------------ 
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_voltop' , frc_voltop  )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_volbot' , frc_volbot  )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_temtop' , frc_temtop  )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_tembot' , frc_tembot  )
+         CALL iom_rstput( iter, nitrst, numriw, 'frc_sal'    , frc_sal     )
+         CALL iom_rstput( iter, nitrst, numriw, 'vol_loc_ini', vol_loc_ini )
+         CALL iom_rstput( iter, nitrst, numriw, 'tem_loc_ini', tem_loc_ini )
+         CALL iom_rstput( iter, nitrst, numriw, 'sal_loc_ini', sal_loc_ini )
+         !
+      ENDIF
+      !
+   END SUBROUTINE ice_dia_rst
+ 
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icedia
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn.F90	(revision 14097)
@@ -0,0 +1,289 @@
+MODULE icedyn
+   !!======================================================================
+   !!                     ***  MODULE  icedyn  ***
+   !!   Sea-Ice dynamics : master routine for sea ice dynamics 
+   !!======================================================================
+   !! history :  4.0  ! 2018  (C. Rousset)  original code SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn       : dynamics of sea ice
+   !!   ice_dyn_init  : initialization and namelist read
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain
+   USE ice            ! sea-ice: variables
+   USE icedyn_rhg     ! sea-ice: rheology
+   USE icedyn_adv     ! sea-ice: advection
+   USE icedyn_rdgrft  ! sea-ice: ridging/rafting
+   USE icecor         ! sea-ice: corrections
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: control prints
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn        ! called by icestp.F90
+   PUBLIC   ice_dyn_init   ! called by icestp.F90
+   
+   INTEGER ::              nice_dyn   ! choice of the type of dynamics
+   !                                        ! associated indices:
+   INTEGER, PARAMETER ::   np_dynALL     = 1   ! full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   INTEGER, PARAMETER ::   np_dynRHGADV  = 2   ! pure dynamics                   (rheology + advection) 
+   INTEGER, PARAMETER ::   np_dynADV1D   = 3   ! only advection 1D - test case from Schar & Smolarkiewicz 1996
+   INTEGER, PARAMETER ::   np_dynADV2D   = 4   ! only advection 2D w prescribed vel.(rn_uvice + advection)
+   !
+   ! ** namelist (namdyn) **
+   LOGICAL  ::   ln_dynALL        ! full ice dynamics                      (rheology + advection + ridging/rafting + correction)
+   LOGICAL  ::   ln_dynRHGADV     ! no ridge/raft & no corrections         (rheology + advection)
+   LOGICAL  ::   ln_dynADV1D      ! only advection in 1D w ice convergence (test case from Schar & Smolarkiewicz 1996)
+   LOGICAL  ::   ln_dynADV2D      ! only advection in 2D w prescribed vel. (rn_uvice + advection)
+   REAL(wp) ::   rn_uice          !    prescribed u-vel (case np_dynADV1D & np_dynADV2D)
+   REAL(wp) ::   rn_vice          !    prescribed v-vel (case np_dynADV1D & np_dynADV2D)
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn( kt )
+      !!-------------------------------------------------------------------
+      !!               ***  ROUTINE ice_dyn  ***
+      !!               
+      !! ** Purpose :   this routine manages sea ice dynamics
+      !!
+      !! ** Action : - calculation of friction in case of landfast ice
+      !!             - call ice_dyn_rhg    = rheology
+      !!             - call ice_dyn_adv    = advection
+      !!             - call ice_dyn_rdgrft = ridging/rafting
+      !!             - call ice_cor        = corrections if fields are out of bounds
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ice time step
+      !!
+      INTEGER  ::   ji, jj        ! dummy loop indices
+      REAL(wp) ::   zcoefu, zcoefv
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdivu_i
+      !!--------------------------------------------------------------------
+      !
+      ! controls
+      IF( ln_timing )   CALL timing_start('icedyn')
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_dyn: sea-ice dynamics'
+         WRITE(numout,*)'~~~~~~~'
+      ENDIF
+      !                      
+      ! retrieve thickness from volume for landfast param. and UMx advection scheme
+      WHERE( a_i(:,:,:) >= epsi20 )
+         h_i(:,:,:) = v_i(:,:,:) / a_i_b(:,:,:)
+         h_s(:,:,:) = v_s(:,:,:) / a_i_b(:,:,:)
+      ELSEWHERE
+         h_i(:,:,:) = 0._wp
+         h_s(:,:,:) = 0._wp
+      END WHERE
+      !
+      WHERE( a_ip(:,:,:) >= epsi20 )
+         h_ip(:,:,:) = v_ip(:,:,:) / a_ip(:,:,:)
+         h_il(:,:,:) = v_il(:,:,:) / a_ip(:,:,:)
+      ELSEWHERE
+         h_ip(:,:,:) = 0._wp
+         h_il(:,:,:) = 0._wp
+      END WHERE
+      !
+      !
+      SELECT CASE( nice_dyn )          !-- Set which dynamics is running
+
+      CASE ( np_dynALL )           !==  all dynamical processes  ==!
+         !
+         CALL ice_dyn_rhg   ( kt )                                          ! -- rheology  
+         CALL ice_dyn_adv   ( kt )                                          ! -- advection of ice
+         CALL ice_dyn_rdgrft( kt )                                          ! -- ridging/rafting 
+         CALL ice_cor       ( kt , 1 )                                      ! -- Corrections
+         !
+      CASE ( np_dynRHGADV  )       !==  no ridge/raft & no corrections ==!
+         !
+         CALL ice_dyn_rhg   ( kt )                                          ! -- rheology  
+         CALL ice_dyn_adv   ( kt )                                          ! -- advection of ice
+         CALL Hpiling                                                       ! -- simple pile-up (replaces ridging/rafting)
+         CALL ice_var_zapsmall                                              ! -- zap small areas
+         !
+      CASE ( np_dynADV1D )         !==  pure advection ==!   (1D)
+         !
+         ! --- monotonicity test from Schar & Smolarkiewicz 1996 --- !
+         ! CFL = 0.5 at a distance from the bound of 1/6 of the basin length
+         ! Then for dx = 2m and dt = 1s => rn_uice = u (1/6th) = 1m/s 
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcoefu = ( REAL(jpiglo+1)*0.5 - REAL(ji+nimpp-1) ) / ( REAL(jpiglo+1)*0.5 - 1. )
+               zcoefv = ( REAL(jpjglo+1)*0.5 - REAL(jj+njmpp-1) ) / ( REAL(jpjglo+1)*0.5 - 1. )
+               u_ice(ji,jj) = rn_uice * 1.5 * SIGN( 1., zcoefu ) * ABS( zcoefu ) * umask(ji,jj,1)
+               v_ice(ji,jj) = rn_vice * 1.5 * SIGN( 1., zcoefv ) * ABS( zcoefv ) * vmask(ji,jj,1)
+            END DO
+         END DO
+         ! ---
+         CALL ice_dyn_adv   ( kt )                                          ! -- advection of ice
+         !
+      CASE ( np_dynADV2D )         !==  pure advection ==!   (2D w prescribed velocities)
+         !
+         u_ice(:,:) = rn_uice * umask(:,:,1)
+         v_ice(:,:) = rn_vice * vmask(:,:,1)
+         !CALL RANDOM_NUMBER(u_ice(:,:)) ; u_ice(:,:) = u_ice(:,:) * 0.1 + rn_uice * 0.9 * umask(:,:,1)
+         !CALL RANDOM_NUMBER(v_ice(:,:)) ; v_ice(:,:) = v_ice(:,:) * 0.1 + rn_vice * 0.9 * vmask(:,:,1)
+         ! ---
+         CALL ice_dyn_adv   ( kt )                                          ! -- advection of ice
+
+      END SELECT
+      !
+      !
+      ! diagnostics: divergence at T points 
+      IF( iom_use('icediv') ) THEN
+         !
+         SELECT CASE( nice_dyn )
+
+         CASE ( np_dynADV1D , np_dynADV2D )
+
+            ALLOCATE( zdivu_i(jpi,jpj) )
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  zdivu_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) ) * r1_e1e2t(ji,jj)
+               END DO
+            END DO
+            CALL lbc_lnk( 'icedyn', zdivu_i, 'T', 1. )
+            ! output
+            CALL iom_put( 'icediv' , zdivu_i )
+
+            DEALLOCATE( zdivu_i )
+
+         END SELECT
+         !
+      ENDIF
+      !
+      ! controls
+      IF( ln_timing )   CALL timing_stop ('icedyn')
+      !
+   END SUBROUTINE ice_dyn
+
+
+   SUBROUTINE Hpiling
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE Hpiling  ***
+      !!
+      !! ** Purpose : Simple conservative piling comparable with 1-cat models
+      !!
+      !! ** Method  : pile-up ice when no ridging/rafting
+      !!
+      !! ** input   : a_i
+      !!-------------------------------------------------------------------
+      INTEGER ::   jl         ! dummy loop indices
+      !!-------------------------------------------------------------------
+      ! controls
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'Hpiling', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      !
+      at_i(:,:) = SUM( a_i(:,:,:), dim=3 )
+      DO jl = 1, jpl
+         WHERE( at_i(:,:) > epsi20 )
+            a_i(:,:,jl) = a_i(:,:,jl) * (  1._wp + MIN( rn_amax_2d(:,:) - at_i(:,:) , 0._wp ) / at_i(:,:)  )
+         END WHERE
+      END DO
+      ! controls
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'Hpiling', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      !
+   END SUBROUTINE Hpiling
+
+
+   SUBROUTINE ice_dyn_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dyn_init  ***
+      !!
+      !! ** Purpose : Physical constants and parameters linked to the ice
+      !!      dynamics
+      !!
+      !! ** Method  :  Read the namdyn namelist and check the ice-dynamic
+      !!       parameter values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namdyn
+      !!-------------------------------------------------------------------
+      INTEGER ::   ios, ioptio   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namdyn/ ln_dynALL, ln_dynRHGADV, ln_dynADV1D, ln_dynADV2D, rn_uice, rn_vice,  &
+         &             rn_ishlat ,                                                           &
+         &             ln_landfast_L16, rn_lf_depfra, rn_lf_bfr, rn_lf_relax, rn_lf_tensile
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )         ! Namelist namdyn in reference namelist : Ice dynamics
+      READ  ( numnam_ice_ref, namdyn, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn in reference namelist' )
+      REWIND( numnam_ice_cfg )         ! Namelist namdyn in configuration namelist : Ice dynamics
+      READ  ( numnam_ice_cfg, namdyn, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn in configuration namelist' )
+      IF(lwm) WRITE( numoni, namdyn )
+      !
+      IF(lwp) THEN                     ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dyn_init: ice parameters for ice dynamics '
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn:'
+         WRITE(numout,*) '      Full ice dynamics      (rhg + adv + ridge/raft + corr) ln_dynALL       = ', ln_dynALL
+         WRITE(numout,*) '      No ridge/raft & No cor (rhg + adv)                     ln_dynRHGADV    = ', ln_dynRHGADV
+         WRITE(numout,*) '      Advection 1D only      (Schar & Smolarkiewicz 1996)    ln_dynADV1D     = ', ln_dynADV1D
+         WRITE(numout,*) '      Advection 2D only      (rn_uvice + adv)                ln_dynADV2D     = ', ln_dynADV2D
+         WRITE(numout,*) '         with prescribed velocity given by   (u,v)_ice = (rn_uice,rn_vice)   = (', rn_uice,',',rn_vice,')'
+         WRITE(numout,*) '      lateral boundary condition for sea ice dynamics        rn_ishlat       = ', rn_ishlat
+         WRITE(numout,*) '      Landfast: param from Lemieux 2016                      ln_landfast_L16 = ', ln_landfast_L16
+         WRITE(numout,*) '         fraction of ocean depth that ice must reach         rn_lf_depfra    = ', rn_lf_depfra
+         WRITE(numout,*) '         maximum bottom stress per unit area of contact      rn_lf_bfr       = ', rn_lf_bfr
+         WRITE(numout,*) '         relax time scale (s-1) to reach static friction     rn_lf_relax     = ', rn_lf_relax
+         WRITE(numout,*) '         isotropic tensile strength                          rn_lf_tensile   = ', rn_lf_tensile
+         WRITE(numout,*)
+      ENDIF
+      !                             !== set the choice of ice dynamics ==!
+      ioptio = 0 
+      !      !--- full dynamics                               (rheology + advection + ridging/rafting + correction)
+      IF( ln_dynALL    ) THEN   ;   ioptio = ioptio + 1   ;   nice_dyn = np_dynALL       ;   ENDIF
+      !      !--- dynamics without ridging/rafting and corr   (rheology + advection)
+      IF( ln_dynRHGADV ) THEN   ;   ioptio = ioptio + 1   ;   nice_dyn = np_dynRHGADV    ;   ENDIF
+      !      !--- advection 1D only - test case from Schar & Smolarkiewicz 1996
+      IF( ln_dynADV1D  ) THEN   ;   ioptio = ioptio + 1   ;   nice_dyn = np_dynADV1D     ;   ENDIF
+      !      !--- advection 2D only with prescribed ice velocities (from namelist)
+      IF( ln_dynADV2D  ) THEN   ;   ioptio = ioptio + 1   ;   nice_dyn = np_dynADV2D     ;   ENDIF
+      !
+      IF( ioptio /= 1 )    CALL ctl_stop( 'ice_dyn_init: one and only one ice dynamics option has to be defined ' )
+      !
+      !                                      !--- Lateral boundary conditions
+      IF     (      rn_ishlat == 0.                ) THEN   ;   IF(lwp) WRITE(numout,*) '   ===>>>   ice lateral  free-slip'
+      ELSEIF (      rn_ishlat == 2.                ) THEN   ;   IF(lwp) WRITE(numout,*) '   ===>>>   ice lateral  no-slip'
+      ELSEIF ( 0. < rn_ishlat .AND. rn_ishlat < 2. ) THEN   ;   IF(lwp) WRITE(numout,*) '   ===>>>   ice lateral  partial-slip'
+      ELSEIF ( 2. < rn_ishlat                      ) THEN   ;   IF(lwp) WRITE(numout,*) '   ===>>>   ice lateral  strong-slip'
+      ENDIF
+      !                                      !--- Landfast ice
+      IF( .NOT.ln_landfast_L16 )   tau_icebfr(:,:) = 0._wp
+      !
+      CALL ice_dyn_rdgrft_init          ! set ice ridging/rafting parameters
+      CALL ice_dyn_rhg_init             ! set ice rheology parameters
+      CALL ice_dyn_adv_init             ! set ice advection parameters
+      !
+   END SUBROUTINE ice_dyn_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif 
+
+   !!======================================================================
+END MODULE icedyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv.F90	(revision 14097)
@@ -0,0 +1,169 @@
+MODULE icedyn_adv
+   !!======================================================================
+   !!                       ***  MODULE icedyn_adv   ***
+   !!   sea-ice: advection
+   !!======================================================================
+   !! History :  4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_adv   : advection of sea ice variables
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constant
+   USE dom_oce        ! ocean domain
+   USE sbc_oce , ONLY : nn_fsbc   ! frequency of sea-ice call
+   USE ice            ! sea-ice: variables
+   USE icevar         ! sea-ice: operations
+   USE icedyn_adv_pra ! sea-ice: advection scheme (Prather)
+   USE icedyn_adv_umx ! sea-ice: advection scheme (ultimate-macho)
+   USE icectl         ! sea-ice: control prints
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_adv        ! called by icestp
+   PUBLIC   ice_dyn_adv_init   ! called by icedyn
+
+   INTEGER ::              nice_adv   ! choice of the type of advection scheme
+   !                                        ! associated indices:
+   INTEGER, PARAMETER ::   np_advPRA = 1   ! Prather scheme
+   INTEGER, PARAMETER ::   np_advUMx = 2   ! Ultimate-Macho scheme
+   !
+   ! ** namelist (namdyn_adv) **
+   INTEGER         ::   nn_UMx       ! order of the UMx advection scheme   
+   !
+   !! * Substitution
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_adv( kt ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_dyn_adv ***
+      !!                    
+      !! ** purpose : advection of sea ice
+      !!
+      !! ** method  : One can choose between 
+      !!     a) an Ultimate-Macho scheme (with order defined by nn_UMx) => ln_adv_UMx
+      !!     b) and a second order Prather scheme => ln_adv_Pra
+      !!
+      !! ** action :
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! number of iteration
+      !!---------------------------------------------------------------------
+      !
+      ! controls
+      IF( ln_timing    )   CALL timing_start('icedyn_adv')                                                             ! timing
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'icedyn_adv', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dyn_adv: sea-ice advection'
+         WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      !---------------!
+      !== Advection ==!
+      !---------------!
+      SELECT CASE( nice_adv )
+      !                                !-----------------------!
+      CASE( np_advUMx )                ! ULTIMATE-MACHO scheme !
+         !                             !-----------------------!
+         CALL ice_dyn_adv_umx( nn_UMx, kt, u_ice, v_ice, h_i, h_s, h_ip, &
+            &                          ato_i, v_i, v_s, sv_i, oa_i, a_i, a_ip, v_ip, v_il, e_s, e_i )
+         !                             !-----------------------!
+      CASE( np_advPRA )                ! PRATHER scheme        !
+         !                             !-----------------------!
+         CALL ice_dyn_adv_pra(         kt, u_ice, v_ice, h_i, h_s, h_ip, &
+            &                          ato_i, v_i, v_s, sv_i, oa_i, a_i, a_ip, v_ip, v_il, e_s, e_i )
+      END SELECT
+
+      !------------
+      ! diagnostics
+      !------------
+      diag_trp_ei(:,:) = SUM(SUM( e_i (:,:,1:nlay_i,:) - e_i_b (:,:,1:nlay_i,:), dim=4 ), dim=3 ) * r1_rdtice
+      diag_trp_es(:,:) = SUM(SUM( e_s (:,:,1:nlay_s,:) - e_s_b (:,:,1:nlay_s,:), dim=4 ), dim=3 ) * r1_rdtice
+      diag_trp_sv(:,:) = SUM(     sv_i(:,:,:)          - sv_i_b(:,:,:)                  , dim=3 ) * r1_rdtice
+      diag_trp_vi(:,:) = SUM(     v_i (:,:,:)          - v_i_b (:,:,:)                  , dim=3 ) * r1_rdtice
+      diag_trp_vs(:,:) = SUM(     v_s (:,:,:)          - v_s_b (:,:,:)                  , dim=3 ) * r1_rdtice
+      IF( iom_use('icemtrp') )   CALL iom_put( 'icemtrp' ,  diag_trp_vi * rhoi          )   ! ice mass transport
+      IF( iom_use('snwmtrp') )   CALL iom_put( 'snwmtrp' ,  diag_trp_vs * rhos          )   ! snw mass transport
+      IF( iom_use('salmtrp') )   CALL iom_put( 'salmtrp' ,  diag_trp_sv * rhoi * 1.e-03 )   ! salt mass transport (kg/m2/s)
+      IF( iom_use('dihctrp') )   CALL iom_put( 'dihctrp' , -diag_trp_ei                 )   ! advected ice heat content (W/m2)
+      IF( iom_use('dshctrp') )   CALL iom_put( 'dshctrp' , -diag_trp_es                 )   ! advected snw heat content (W/m2)
+
+      ! controls
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icedyn_adv', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icectl    )   CALL ice_prt     (kt, iiceprt, jiceprt,-1, ' - ice dyn & trp - ')                           ! prints
+      IF( ln_timing    )   CALL timing_stop ('icedyn_adv')                                                             ! timing
+      !
+   END SUBROUTINE ice_dyn_adv
+
+
+   SUBROUTINE ice_dyn_adv_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dyn_adv_init  ***
+      !!
+      !! ** Purpose :   Physical constants and parameters linked to the ice
+      !!                dynamics
+      !!
+      !! ** Method  :   Read the namdyn_adv namelist and check the ice-dynamic
+      !!                parameter values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namdyn_adv
+      !!-------------------------------------------------------------------
+      INTEGER ::   ios, ioptio   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namdyn_adv/ ln_adv_Pra, ln_adv_UMx, nn_UMx
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )         ! Namelist namdyn_adv in reference namelist : Ice dynamics
+      READ  ( numnam_ice_ref, namdyn_adv, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_adv in reference namelist' )
+      REWIND( numnam_ice_cfg )         ! Namelist namdyn_adv in configuration namelist : Ice dynamics
+      READ  ( numnam_ice_cfg, namdyn_adv, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_adv in configuration namelist' )
+      IF(lwm) WRITE( numoni, namdyn_adv )
+      !
+      IF(lwp) THEN                     ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dyn_adv_init: ice parameters for ice dynamics '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn_adv:'
+         WRITE(numout,*) '      type of advection scheme (Prather)             ln_adv_Pra = ', ln_adv_Pra 
+         WRITE(numout,*) '      type of advection scheme (Ulimate-Macho)       ln_adv_UMx = ', ln_adv_UMx 
+         WRITE(numout,*) '         order of the Ultimate-Macho scheme          nn_UMx     = ', nn_UMx
+      ENDIF
+      !
+      !                             !== set the choice of ice advection ==!
+      ioptio = 0 
+      IF( ln_adv_Pra ) THEN   ;   ioptio = ioptio + 1   ;   nice_adv = np_advPRA    ;   ENDIF
+      IF( ln_adv_UMx ) THEN   ;   ioptio = ioptio + 1   ;   nice_adv = np_advUMx    ;   ENDIF
+      IF( ioptio /= 1 )   CALL ctl_stop( 'ice_dyn_adv_init: choose one and only one ice adv. scheme (ln_adv_Pra or ln_adv_UMx)' )
+      !
+      IF( ln_adv_Pra )   CALL adv_pra_init  !* read or initialize all required files
+      !
+   END SUBROUTINE ice_dyn_adv_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty Module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icedyn_adv
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_pra.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_pra.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_pra.F90	(revision 14097)
@@ -0,0 +1,1223 @@
+MODULE icedyn_adv_pra 
+   !!======================================================================
+   !!                       ***  MODULE icedyn_adv_pra   ***
+   !!   sea-ice : advection => Prather scheme
+   !!======================================================================
+   !! History :       !  2008-03  (M. Vancoppenolle) original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!--------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_adv_pra : advection of sea ice using Prather scheme
+   !!   adv_x, adv_y    : Prather scheme applied in i- and j-direction, resp.
+   !!   adv_pra_init    : initialisation of the Prather scheme
+   !!   adv_pra_rst     : read/write Prather field in ice restart file, or initialized to zero
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constant
+   USE dom_oce        ! ocean domain
+   USE ice            ! sea-ice variables
+   USE sbc_oce , ONLY : nn_fsbc   ! frequency of sea-ice call
+   USE icevar         ! sea-ice: operations
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_adv_pra   ! called by icedyn_adv
+   PUBLIC   adv_pra_init      ! called by icedyn_adv
+
+   ! Moments for advection
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxice, syice, sxxice, syyice, sxyice   ! ice thickness 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxsn , sysn , sxxsn , syysn , sxysn    ! snow thickness
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxa  , sya  , sxxa  , syya  , sxya     ! ice concentration
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxsal, sysal, sxxsal, syysal, sxysal   ! ice salinity
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxage, syage, sxxage, syyage, sxyage   ! ice age
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   sxc0 , syc0 , sxxc0 , syyc0 , sxyc0    ! snow layers heat content
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   sxe  , sye  , sxxe  , syye  , sxye     ! ice layers heat content
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxap , syap , sxxap , syyap , sxyap    ! melt pond fraction
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxvp , syvp , sxxvp , syyvp , sxyvp    ! melt pond volume
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   sxvl , syvl , sxxvl , syyvl , sxyvl    ! melt pond lid volume
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_adv_pra(         kt, pu_ice, pv_ice, ph_i, ph_s, ph_ip,  &
+      &                        pato_i, pv_i, pv_s, psv_i, poa_i, pa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+      !!----------------------------------------------------------------------
+      !!                **  routine ice_dyn_adv_pra  **
+      !!  
+      !! ** purpose :   Computes and adds the advection trend to sea-ice
+      !!
+      !! ** method  :   Uses Prather second order scheme that advects tracers
+      !!                but also their quadratic forms. The method preserves
+      !!                tracer structures by conserving second order moments.
+      !!
+      !! Reference:  Prather, 1986, JGR, 91, D6. 6671-6681.
+      !!----------------------------------------------------------------------
+      INTEGER                     , INTENT(in   ) ::   kt         ! time step
+      REAL(wp), DIMENSION(:,:)    , INTENT(in   ) ::   pu_ice     ! ice i-velocity
+      REAL(wp), DIMENSION(:,:)    , INTENT(in   ) ::   pv_ice     ! ice j-velocity
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_i       ! ice thickness
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_s       ! snw thickness
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_ip      ! ice pond thickness
+      REAL(wp), DIMENSION(:,:)    , INTENT(inout) ::   pato_i     ! open water area
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i       ! ice volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_s       ! snw volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   psv_i      ! salt content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   poa_i      ! age content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_i       ! ice concentration
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_ip      ! melt pond fraction
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_ip      ! melt pond volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_il      ! melt pond lid thickness
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s       ! snw heat content
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_i       ! ice heat content
+      !
+      INTEGER  ::   ji, jj, jk, jl, jt      ! dummy loop indices
+      INTEGER  ::   icycle                  ! number of sub-timestep for the advection
+      REAL(wp) ::   zdt, z1_dt              !   -      -
+      REAL(wp), DIMENSION(1)                  ::   zcflprv, zcflnow   ! for global communication
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zati1, zati2
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zudy, zvdx
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   zhi_max, zhs_max, zhip_max, zs_i, zsi_max
+      REAL(wp), DIMENSION(jpi,jpj,nlay_i,jpl) ::   ze_i, zei_max
+      REAL(wp), DIMENSION(jpi,jpj,nlay_s,jpl) ::   ze_s, zes_max
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   zarea
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   z0ice, z0snw, z0ai, z0smi, z0oi
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   z0ap , z0vp, z0vl
+      REAL(wp), DIMENSION(jpi,jpj,nlay_s,jpl) ::   z0es
+      REAL(wp), DIMENSION(jpi,jpj,nlay_i,jpl) ::   z0ei
+      !! diagnostics
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zdiag_adv_mass, zdiag_adv_salt, zdiag_adv_heat      
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_adv_pra: Prather advection scheme'
+      !
+      ! --- Record max of the surrounding 9-pts (for call Hbig) --- !
+      ! thickness and salinity
+      WHERE( pv_i(:,:,:) >= epsi10 ) ; zs_i(:,:,:) = psv_i(:,:,:) / pv_i(:,:,:)
+      ELSEWHERE                      ; zs_i(:,:,:) = 0._wp
+      END WHERE
+      CALL icemax3D( ph_i , zhi_max )
+      CALL icemax3D( ph_s , zhs_max )
+      CALL icemax3D( ph_ip, zhip_max)
+      CALL icemax3D( zs_i , zsi_max )
+      CALL lbc_lnk_multi( 'icedyn_adv_pra', zhi_max, 'T', 1., zhs_max, 'T', 1., zhip_max, 'T', 1., zsi_max, 'T', 1. )
+
+      ! enthalpies
+      DO jk = 1, nlay_i
+         WHERE( pv_i(:,:,:) >= epsi10 ) ; ze_i(:,:,jk,:) = pe_i(:,:,jk,:) / pv_i(:,:,:)
+         ELSEWHERE                      ; ze_i(:,:,jk,:) = 0._wp
+         END WHERE
+      END DO
+      DO jk = 1, nlay_s
+         WHERE( pv_s(:,:,:) >= epsi10 ) ; ze_s(:,:,jk,:) = pe_s(:,:,jk,:) / pv_s(:,:,:)
+         ELSEWHERE                      ; ze_s(:,:,jk,:) = 0._wp
+         END WHERE
+      END DO   
+      CALL icemax4D( ze_i , zei_max )
+      CALL icemax4D( ze_s , zes_max )
+      CALL lbc_lnk( 'icedyn_adv_pra', zei_max, 'T', 1. )
+      CALL lbc_lnk( 'icedyn_adv_pra', zes_max, 'T', 1. )
+      !
+      !
+      ! --- If ice drift is too fast, use  subtime steps for advection (CFL test for stability) --- !
+      !        Note: the advection split is applied at the next time-step in order to avoid blocking global comm.
+      !              this should not affect too much the stability
+      zcflnow(1) =                  MAXVAL( ABS( pu_ice(:,:) ) * rdt_ice * r1_e1u(:,:) )
+      zcflnow(1) = MAX( zcflnow(1), MAXVAL( ABS( pv_ice(:,:) ) * rdt_ice * r1_e2v(:,:) ) )
+      
+      ! non-blocking global communication send zcflnow and receive zcflprv
+      CALL mpp_delay_max( 'icedyn_adv_pra', 'cflice', zcflnow(:), zcflprv(:), kt == nitend - nn_fsbc + 1 )
+
+      IF( zcflprv(1) > .5 ) THEN   ;   icycle = 2
+      ELSE                         ;   icycle = 1
+      ENDIF
+      zdt = rdt_ice / REAL(icycle)
+      z1_dt = 1._wp / zdt
+      
+      ! --- transport --- !
+      zudy(:,:) = pu_ice(:,:) * e2u(:,:)
+      zvdx(:,:) = pv_ice(:,:) * e1v(:,:)
+
+      DO jt = 1, icycle
+
+         ! diagnostics
+         zdiag_adv_mass(:,:) =   SUM(  pv_i(:,:,:) , dim=3 ) * rhoi + SUM(  pv_s(:,:,:) , dim=3 ) * rhos
+         zdiag_adv_salt(:,:) =   SUM( psv_i(:,:,:) , dim=3 ) * rhoi
+         zdiag_adv_heat(:,:) = - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
+            &                  - SUM(SUM( pe_s(:,:,1:nlay_s,:) , dim=4 ), dim=3 )
+
+         ! record at_i before advection (for open water)
+         zati1(:,:) = SUM( pa_i(:,:,:), dim=3 )
+         
+         ! --- transported fields --- !                                        
+         DO jl = 1, jpl
+            zarea(:,:,jl) = e1e2t(:,:)
+            z0snw(:,:,jl) = pv_s (:,:,jl) * e1e2t(:,:)        ! Snow volume
+            z0ice(:,:,jl) = pv_i (:,:,jl) * e1e2t(:,:)        ! Ice  volume
+            z0ai (:,:,jl) = pa_i (:,:,jl) * e1e2t(:,:)        ! Ice area
+            z0smi(:,:,jl) = psv_i(:,:,jl) * e1e2t(:,:)        ! Salt content
+            z0oi (:,:,jl) = poa_i(:,:,jl) * e1e2t(:,:)        ! Age content
+            DO jk = 1, nlay_s
+               z0es(:,:,jk,jl) = pe_s(:,:,jk,jl) * e1e2t(:,:) ! Snow heat content
+            END DO
+            DO jk = 1, nlay_i
+               z0ei(:,:,jk,jl) = pe_i(:,:,jk,jl) * e1e2t(:,:) ! Ice  heat content
+            END DO
+            IF ( ln_pnd_LEV ) THEN
+               z0ap(:,:,jl) = pa_ip(:,:,jl) * e1e2t(:,:)      ! Melt pond fraction
+               z0vp(:,:,jl) = pv_ip(:,:,jl) * e1e2t(:,:)      ! Melt pond volume
+               IF ( ln_pnd_lids ) THEN
+                  z0vl(:,:,jl) = pv_il(:,:,jl) * e1e2t(:,:)   ! Melt pond lid volume
+               ENDIF
+            ENDIF
+         END DO
+         !
+         !                                                                  !--------------------------------------------!
+         IF( MOD( (kt - 1) / nn_fsbc , 2 ) ==  MOD( (jt - 1) , 2 ) ) THEN   !==  odd ice time step:  adv_x then adv_y  ==!
+            !                                                               !--------------------------------------------!
+            CALL adv_x( zdt , zudy , 1._wp , zarea , z0ice , sxice , sxxice , syice , syyice , sxyice ) !--- ice volume
+            CALL adv_y( zdt , zvdx , 0._wp , zarea , z0ice , sxice , sxxice , syice , syyice , sxyice )
+            CALL adv_x( zdt , zudy , 1._wp , zarea , z0snw , sxsn  , sxxsn  , sysn  , syysn  , sxysn  ) !--- snow volume
+            CALL adv_y( zdt , zvdx , 0._wp , zarea , z0snw , sxsn  , sxxsn  , sysn  , syysn  , sxysn  )
+            CALL adv_x( zdt , zudy , 1._wp , zarea , z0smi , sxsal , sxxsal , sysal , syysal , sxysal ) !--- ice salinity
+            CALL adv_y( zdt , zvdx , 0._wp , zarea , z0smi , sxsal , sxxsal , sysal , syysal , sxysal )
+            CALL adv_x( zdt , zudy , 1._wp , zarea , z0ai  , sxa   , sxxa   , sya   , syya   , sxya   ) !--- ice concentration
+            CALL adv_y( zdt , zvdx , 0._wp , zarea , z0ai  , sxa   , sxxa   , sya   , syya   , sxya   )
+            CALL adv_x( zdt , zudy , 1._wp , zarea , z0oi  , sxage , sxxage , syage , syyage , sxyage ) !--- ice age
+            CALL adv_y( zdt , zvdx , 0._wp , zarea , z0oi  , sxage , sxxage , syage , syyage , sxyage )
+            !
+            DO jk = 1, nlay_s                                                                           !--- snow heat content
+               CALL adv_x( zdt, zudy, 1._wp, zarea, z0es (:,:,jk,:), sxc0(:,:,jk,:),   &
+                  &                                 sxxc0(:,:,jk,:), syc0(:,:,jk,:), syyc0(:,:,jk,:), sxyc0(:,:,jk,:) )
+               CALL adv_y( zdt, zvdx, 0._wp, zarea, z0es (:,:,jk,:), sxc0(:,:,jk,:),   &
+                  &                                 sxxc0(:,:,jk,:), syc0(:,:,jk,:), syyc0(:,:,jk,:), sxyc0(:,:,jk,:) )
+            END DO
+            DO jk = 1, nlay_i                                                                           !--- ice heat content
+               CALL adv_x( zdt, zudy, 1._wp, zarea, z0ei(:,:,jk,:), sxe(:,:,jk,:),   & 
+                  &                                 sxxe(:,:,jk,:), sye(:,:,jk,:), syye(:,:,jk,:), sxye(:,:,jk,:) )
+               CALL adv_y( zdt, zvdx, 0._wp, zarea, z0ei(:,:,jk,:), sxe(:,:,jk,:),   & 
+                  &                                 sxxe(:,:,jk,:), sye(:,:,jk,:), syye(:,:,jk,:), sxye(:,:,jk,:) )
+            END DO
+            !
+            IF ( ln_pnd_LEV ) THEN
+               CALL adv_x( zdt , zudy , 1._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )    !--- melt pond fraction
+               CALL adv_y( zdt , zvdx , 0._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap ) 
+               CALL adv_x( zdt , zudy , 1._wp , zarea , z0vp , sxvp , sxxvp , syvp , syyvp , sxyvp )    !--- melt pond volume
+               CALL adv_y( zdt , zvdx , 0._wp , zarea , z0vp , sxvp , sxxvp , syvp , syyvp , sxyvp ) 
+               IF ( ln_pnd_lids ) THEN
+                  CALL adv_x( zdt , zudy , 1._wp , zarea , z0vl , sxvl , sxxvl , syvl , syyvl , sxyvl ) !--- melt pond lid volume
+                  CALL adv_y( zdt , zvdx , 0._wp , zarea , z0vl , sxvl , sxxvl , syvl , syyvl , sxyvl ) 
+               ENDIF
+            ENDIF
+            !                                                               !--------------------------------------------!
+         ELSE                                                               !== even ice time step:  adv_y then adv_x  ==!
+            !                                                               !--------------------------------------------!
+            CALL adv_y( zdt , zvdx , 1._wp , zarea , z0ice , sxice , sxxice , syice , syyice , sxyice ) !--- ice volume
+            CALL adv_x( zdt , zudy , 0._wp , zarea , z0ice , sxice , sxxice , syice , syyice , sxyice )
+            CALL adv_y( zdt , zvdx , 1._wp , zarea , z0snw , sxsn  , sxxsn  , sysn  , syysn  , sxysn  ) !--- snow volume
+            CALL adv_x( zdt , zudy , 0._wp , zarea , z0snw , sxsn  , sxxsn  , sysn  , syysn  , sxysn  )
+            CALL adv_y( zdt , zvdx , 1._wp , zarea , z0smi , sxsal , sxxsal , sysal , syysal , sxysal ) !--- ice salinity
+            CALL adv_x( zdt , zudy , 0._wp , zarea , z0smi , sxsal , sxxsal , sysal , syysal , sxysal )
+            CALL adv_y( zdt , zvdx , 1._wp , zarea , z0ai  , sxa   , sxxa   , sya   , syya   , sxya   ) !--- ice concentration
+            CALL adv_x( zdt , zudy , 0._wp , zarea , z0ai  , sxa   , sxxa   , sya   , syya   , sxya   )
+            CALL adv_y( zdt , zvdx , 1._wp , zarea , z0oi  , sxage , sxxage , syage , syyage , sxyage ) !--- ice age
+            CALL adv_x( zdt , zudy , 0._wp , zarea , z0oi  , sxage , sxxage , syage , syyage , sxyage )
+            DO jk = 1, nlay_s                                                                           !--- snow heat content
+               CALL adv_y( zdt, zvdx, 1._wp, zarea, z0es (:,:,jk,:), sxc0(:,:,jk,:),   &
+                  &                                 sxxc0(:,:,jk,:), syc0(:,:,jk,:), syyc0(:,:,jk,:), sxyc0(:,:,jk,:) )
+               CALL adv_x( zdt, zudy, 0._wp, zarea, z0es (:,:,jk,:), sxc0(:,:,jk,:),   &
+                  &                                 sxxc0(:,:,jk,:), syc0(:,:,jk,:), syyc0(:,:,jk,:), sxyc0(:,:,jk,:) )
+            END DO
+            DO jk = 1, nlay_i                                                                           !--- ice heat content
+               CALL adv_y( zdt, zvdx, 1._wp, zarea, z0ei(:,:,jk,:), sxe(:,:,jk,:),   & 
+                  &                                 sxxe(:,:,jk,:), sye(:,:,jk,:), syye(:,:,jk,:), sxye(:,:,jk,:) )
+               CALL adv_x( zdt, zudy, 0._wp, zarea, z0ei(:,:,jk,:), sxe(:,:,jk,:),   & 
+                  &                                 sxxe(:,:,jk,:), sye(:,:,jk,:), syye(:,:,jk,:), sxye(:,:,jk,:) )
+            END DO
+            IF ( ln_pnd_LEV ) THEN
+               CALL adv_y( zdt , zvdx , 1._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )    !--- melt pond fraction
+               CALL adv_x( zdt , zudy , 0._wp , zarea , z0ap , sxap , sxxap , syap , syyap , sxyap )
+               CALL adv_y( zdt , zvdx , 1._wp , zarea , z0vp , sxvp , sxxvp , syvp , syyvp , sxyvp )    !--- melt pond volume
+               CALL adv_x( zdt , zudy , 0._wp , zarea , z0vp , sxvp , sxxvp , syvp , syyvp , sxyvp )
+               IF ( ln_pnd_lids ) THEN
+                  CALL adv_y( zdt , zvdx , 1._wp , zarea , z0vl , sxvl , sxxvl , syvl , syyvl , sxyvl ) !--- melt pond lid volume
+                  CALL adv_x( zdt , zudy , 0._wp , zarea , z0vl , sxvl , sxxvl , syvl , syyvl , sxyvl ) 
+               ENDIF
+            ENDIF
+            !
+         ENDIF
+        
+         ! --- Lateral boundary conditions --- !
+         !     caution: for gradients (sx and sy) the sign changes
+         CALL lbc_lnk_multi( 'icedyn_adv_pra', z0ice , 'T', 1._wp, sxice , 'T', -1._wp, syice , 'T', -1._wp  & ! ice volume
+            &                                , sxxice, 'T', 1._wp, syyice, 'T',  1._wp, sxyice, 'T',  1._wp  &
+            &                                , z0snw , 'T', 1._wp, sxsn  , 'T', -1._wp, sysn  , 'T', -1._wp  & ! snw volume
+            &                                , sxxsn , 'T', 1._wp, syysn , 'T',  1._wp, sxysn , 'T',  1._wp  )
+         CALL lbc_lnk_multi( 'icedyn_adv_pra', z0smi , 'T', 1._wp, sxsal , 'T', -1._wp, sysal , 'T', -1._wp  & ! ice salinity
+            &                                , sxxsal, 'T', 1._wp, syysal, 'T',  1._wp, sxysal, 'T',  1._wp  &
+            &                                , z0ai  , 'T', 1._wp, sxa   , 'T', -1._wp, sya   , 'T', -1._wp  & ! ice concentration
+            &                                , sxxa  , 'T', 1._wp, syya  , 'T',  1._wp, sxya  , 'T',  1._wp  )
+         CALL lbc_lnk_multi( 'icedyn_adv_pra', z0oi  , 'T', 1._wp, sxage , 'T', -1._wp, syage , 'T', -1._wp  & ! ice age
+            &                                , sxxage, 'T', 1._wp, syyage, 'T',  1._wp, sxyage, 'T',  1._wp  )
+         CALL lbc_lnk_multi( 'icedyn_adv_pra', z0es  , 'T', 1._wp, sxc0  , 'T', -1._wp, syc0  , 'T', -1._wp  & ! snw enthalpy
+            &                                , sxxc0 , 'T', 1._wp, syyc0 , 'T',  1._wp, sxyc0 , 'T',  1._wp  ) 
+         CALL lbc_lnk_multi( 'icedyn_adv_pra', z0ei  , 'T', 1._wp, sxe   , 'T', -1._wp, sye   , 'T', -1._wp  & ! ice enthalpy
+            &                                , sxxe  , 'T', 1._wp, syye  , 'T',  1._wp, sxye  , 'T',  1._wp  )
+         IF ( ln_pnd_LEV ) THEN
+            CALL lbc_lnk_multi( 'icedyn_adv_pra', z0ap , 'T', 1._wp, sxap , 'T', -1._wp, syap , 'T', -1._wp  & ! melt pond fraction
+               &                                , sxxap, 'T', 1._wp, syyap, 'T',  1._wp, sxyap, 'T',  1._wp  &
+               &                                , z0vp , 'T', 1._wp, sxvp , 'T', -1._wp, syvp , 'T', -1._wp  & ! melt pond volume
+               &                                , sxxvp, 'T', 1._wp, syyvp, 'T',  1._wp, sxyvp, 'T',  1._wp  ) 
+            IF ( ln_pnd_lids ) THEN
+               CALL lbc_lnk_multi( 'icedyn_adv_pra', z0vl ,'T', 1._wp, sxvl ,'T', -1._wp, syvl ,'T', -1._wp  & ! melt pond lid volume
+                  &                                , sxxvl,'T', 1._wp, syyvl,'T',  1._wp, sxyvl,'T',  1._wp  ) 
+            ENDIF
+         ENDIF
+         
+         ! --- Recover the properties from their contents --- !
+         DO jl = 1, jpl
+            pv_i (:,:,jl) = z0ice(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            pv_s (:,:,jl) = z0snw(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            psv_i(:,:,jl) = z0smi(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            poa_i(:,:,jl) = z0oi (:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            pa_i (:,:,jl) = z0ai (:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            DO jk = 1, nlay_s
+               pe_s(:,:,jk,jl) = z0es(:,:,jk,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            END DO
+            DO jk = 1, nlay_i
+               pe_i(:,:,jk,jl) = z0ei(:,:,jk,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+            END DO
+            IF ( ln_pnd_LEV ) THEN
+               pa_ip(:,:,jl) = z0ap(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+               pv_ip(:,:,jl) = z0vp(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+               IF ( ln_pnd_lids ) THEN
+                  pv_il(:,:,jl) = z0vl(:,:,jl) * r1_e1e2t(:,:) * tmask(:,:,1)
+               ENDIF
+            ENDIF
+         END DO
+         !
+         ! derive open water from ice concentration
+         zati2(:,:) = SUM( pa_i(:,:,:), dim=3 )
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pato_i(ji,jj) = pato_i(ji,jj) - ( zati2(ji,jj) - zati1(ji,jj) ) &                        !--- open water
+                  &                          - ( zudy(ji,jj) - zudy(ji-1,jj) + zvdx(ji,jj) - zvdx(ji,jj-1) ) * r1_e1e2t(ji,jj) * zdt
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_adv_pra', pato_i, 'T',  1. )
+         !
+         ! --- diagnostics --- !
+         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i(:,:,:) , dim=3 ) * rhoi + SUM( pv_s(:,:,:) , dim=3 ) * rhos &
+            &                                        - zdiag_adv_mass(:,:) ) * z1_dt
+         diag_adv_salt(:,:) = diag_adv_salt(:,:) + (   SUM( psv_i(:,:,:) , dim=3 ) * rhoi &
+            &                                        - zdiag_adv_salt(:,:) ) * z1_dt
+         diag_adv_heat(:,:) = diag_adv_heat(:,:) + ( - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
+            &                                        - SUM(SUM( pe_s(:,:,1:nlay_s,:) , dim=4 ), dim=3 ) &
+            &                                        - zdiag_adv_heat(:,:) ) * z1_dt
+         !
+         ! --- Ensure non-negative fields --- !
+         !     Remove negative values (conservation is ensured)
+         !     (because advected fields are not perfectly bounded and tiny negative values can occur, e.g. -1.e-20)
+         CALL ice_var_zapneg( zdt, pato_i, pv_i, pv_s, psv_i, poa_i, pa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+         !
+         ! --- Make sure ice thickness is not too big --- !
+         !     (because ice thickness can be too large where ice concentration is very small)
+         CALL Hbig( zdt, zhi_max, zhs_max, zhip_max, zsi_max, zes_max, zei_max, &
+            &            pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i, pe_s, pe_i )
+         !
+         ! --- Ensure snow load is not too big --- !
+         CALL Hsnow( zdt, pv_i, pv_s, pa_i, pa_ip, pe_s )
+         !
+      END DO
+      !
+      IF( lrst_ice )   CALL adv_pra_rst( 'WRITE', kt )   !* write Prather fields in the restart file
+      !
+   END SUBROUTINE ice_dyn_adv_pra
+   
+   
+   SUBROUTINE adv_x( pdt, put , pcrh, psm , ps0 ,   &
+      &              psx, psxx, psy , psyy, psxy )
+      !!----------------------------------------------------------------------
+      !!                **  routine adv_x  **
+      !!  
+      !! ** purpose :   Computes and adds the advection trend to sea-ice
+      !!                variable on x axis
+      !!----------------------------------------------------------------------
+      REAL(wp)                  , INTENT(in   ) ::   pdt                ! the time step
+      REAL(wp)                  , INTENT(in   ) ::   pcrh               ! call adv_x then adv_y (=1) or the opposite (=0)
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   put                ! i-direction ice velocity at U-point [m/s]
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psm                ! area
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ps0                ! field to be advected
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psx , psy          ! 1st moments 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psxx, psyy, psxy   ! 2nd moments
+      !! 
+      INTEGER  ::   ji, jj, jl, jcat                     ! dummy loop indices
+      INTEGER  ::   jjmin, jjmax                         ! dummy loop indices
+      REAL(wp) ::   zs1max, zslpmax, ztemp               ! local scalars
+      REAL(wp) ::   zs1new, zalf , zalfq , zbt           !   -      -
+      REAL(wp) ::   zs2new, zalf1, zalf1q, zbt1          !   -      -
+      REAL(wp) ::   zpsm, zps0
+      REAL(wp) ::   zpsx, zpsy, zpsxx, zpsyy, zpsxy
+      REAL(wp), DIMENSION(jpi,jpj) ::   zf0 , zfx  , zfy   , zbet   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfm , zfxx , zfyy  , zfxy   !  -      -
+      REAL(wp), DIMENSION(jpi,jpj) ::   zalg, zalg1, zalg1q         !  -      -
+      !-----------------------------------------------------------------------
+      ! in order to avoid lbc_lnk (communications):
+      !    jj loop must be 1:jpj   if adv_x is called first
+      !                and 2:jpj-1 if adv_x is called second
+      jjmin = 2     - NINT(pcrh)   ! 1   or 2
+      jjmax = jpjm1 + NINT(pcrh)   ! jpj or jpj-1
+      !
+      jcat = SIZE( ps0 , 3 )   ! size of input arrays
+      !
+      DO jl = 1, jcat   ! loop on categories
+         !
+         ! Limitation of moments.                                           
+         DO jj = jjmin, jjmax
+            
+            DO ji = 1, jpi
+
+               zpsm  = psm (ji,jj,jl) ! optimization
+               zps0  = ps0 (ji,jj,jl)
+               zpsx  = psx (ji,jj,jl)
+               zpsxx = psxx(ji,jj,jl)
+               zpsy  = psy (ji,jj,jl)
+               zpsyy = psyy(ji,jj,jl)
+               zpsxy = psxy(ji,jj,jl)
+
+               !  Initialize volumes of boxes  (=area if adv_x first called, =psm otherwise)                                     
+               zpsm = MAX( pcrh * e1e2t(ji,jj) + ( 1.0 - pcrh ) * zpsm , epsi20 )
+               !
+               zslpmax = MAX( 0._wp, zps0 )
+               zs1max  = 1.5 * zslpmax
+               zs1new  = MIN( zs1max, MAX( -zs1max, zpsx ) )
+               zs2new  = MIN( 2.0 * zslpmax - 0.3334 * ABS( zs1new ), MAX( ABS( zs1new ) - zslpmax, zpsxx ) )
+               rswitch = ( 1.0 - MAX( 0._wp, SIGN( 1._wp, -zslpmax) ) ) * tmask(ji,jj,1)   ! Case of empty boxes & Apply mask
+
+               zps0  = zslpmax  
+               zpsx  = zs1new  * rswitch
+               zpsxx = zs2new  * rswitch
+               zpsy  = zpsy    * rswitch
+               zpsyy = zpsyy   * rswitch
+               zpsxy = MIN( zslpmax, MAX( -zslpmax, zpsxy ) ) * rswitch
+
+               !  Calculate fluxes and moments between boxes i<-->i+1              
+               !                                !  Flux from i to i+1 WHEN u GT 0 
+               zbet(ji,jj)  =  MAX( 0._wp, SIGN( 1._wp, put(ji,jj) ) )
+               zalf         =  MAX( 0._wp, put(ji,jj) ) * pdt / zpsm
+               zalfq        =  zalf * zalf
+               zalf1        =  1.0 - zalf
+               zalf1q       =  zalf1 * zalf1
+               !
+               zfm (ji,jj)  =  zalf  *   zpsm 
+               zf0 (ji,jj)  =  zalf  * ( zps0  + zalf1 * ( zpsx + (zalf1 - zalf) * zpsxx ) )
+               zfx (ji,jj)  =  zalfq * ( zpsx  + 3.0 * zalf1 * zpsxx )
+               zfxx(ji,jj)  =  zalf  *   zpsxx * zalfq
+               zfy (ji,jj)  =  zalf  * ( zpsy  + zalf1 * zpsxy )
+               zfxy(ji,jj)  =  zalfq *   zpsxy
+               zfyy(ji,jj)  =  zalf  *   zpsyy
+
+               !                                !  Readjust moments remaining in the box.
+               zpsm  =  zpsm  - zfm(ji,jj)
+               zps0  =  zps0  - zf0(ji,jj)
+               zpsx  =  zalf1q * ( zpsx - 3.0 * zalf * zpsxx )
+               zpsxx =  zalf1  * zalf1q * zpsxx
+               zpsy  =  zpsy  - zfy (ji,jj)
+               zpsyy =  zpsyy - zfyy(ji,jj)
+               zpsxy =  zalf1q * zpsxy
+               !
+               psm (ji,jj,jl) = zpsm ! optimization
+               ps0 (ji,jj,jl) = zps0 
+               psx (ji,jj,jl) = zpsx 
+               psxx(ji,jj,jl) = zpsxx
+               psy (ji,jj,jl) = zpsy 
+               psyy(ji,jj,jl) = zpsyy
+               psxy(ji,jj,jl) = zpsxy
+               !
+            END DO
+
+            DO ji = 1, fs_jpim1
+               !                                !  Flux from i+1 to i when u LT 0.
+               zalf          = MAX( 0._wp, -put(ji,jj) ) * pdt / psm(ji+1,jj,jl) 
+               zalg  (ji,jj) = zalf
+               zalfq         = zalf * zalf
+               zalf1         = 1.0 - zalf
+               zalg1 (ji,jj) = zalf1
+               zalf1q        = zalf1 * zalf1
+               zalg1q(ji,jj) = zalf1q
+               !
+               zfm   (ji,jj) = zfm (ji,jj) + zalf  *    psm (ji+1,jj,jl)
+               zf0   (ji,jj) = zf0 (ji,jj) + zalf  * (  ps0 (ji+1,jj,jl) &
+                  &                                   - zalf1 * ( psx(ji+1,jj,jl) - (zalf1 - zalf ) * psxx(ji+1,jj,jl) ) )
+               zfx   (ji,jj) = zfx (ji,jj) + zalfq * (  psx (ji+1,jj,jl) - 3.0 * zalf1 * psxx(ji+1,jj,jl) )
+               zfxx  (ji,jj) = zfxx(ji,jj) + zalf  *    psxx(ji+1,jj,jl) * zalfq
+               zfy   (ji,jj) = zfy (ji,jj) + zalf  * (  psy (ji+1,jj,jl) - zalf1 * psxy(ji+1,jj,jl) )
+               zfxy  (ji,jj) = zfxy(ji,jj) + zalfq *    psxy(ji+1,jj,jl)
+               zfyy  (ji,jj) = zfyy(ji,jj) + zalf  *    psyy(ji+1,jj,jl)
+            END DO
+
+            DO ji = fs_2, fs_jpim1 
+               !
+               zpsm  = psm (ji,jj,jl) ! optimization
+               zps0  = ps0 (ji,jj,jl)
+               zpsx  = psx (ji,jj,jl)
+               zpsxx = psxx(ji,jj,jl)
+               zpsy  = psy (ji,jj,jl)
+               zpsyy = psyy(ji,jj,jl)
+               zpsxy = psxy(ji,jj,jl)
+               !                                !  Readjust moments remaining in the box.
+               zbt  =       zbet(ji-1,jj)
+               zbt1 = 1.0 - zbet(ji-1,jj)
+               !
+               zpsm  = zbt * zpsm + zbt1 * ( zpsm - zfm(ji-1,jj) )
+               zps0  = zbt * zps0 + zbt1 * ( zps0 - zf0(ji-1,jj) )
+               zpsx  = zalg1q(ji-1,jj) * ( zpsx + 3.0 * zalg(ji-1,jj) * zpsxx )
+               zpsxx = zalg1 (ji-1,jj) * zalg1q(ji-1,jj) * zpsxx
+               zpsy  = zbt * zpsy  + zbt1 * ( zpsy  - zfy (ji-1,jj) )
+               zpsyy = zbt * zpsyy + zbt1 * ( zpsyy - zfyy(ji-1,jj) )
+               zpsxy = zalg1q(ji-1,jj) * zpsxy
+
+               !   Put the temporary moments into appropriate neighboring boxes.    
+               !                                !   Flux from i to i+1 IF u GT 0.
+               zbt   =       zbet(ji-1,jj)
+               zbt1  = 1.0 - zbet(ji-1,jj)
+               zpsm  = zbt * ( zpsm + zfm(ji-1,jj) ) + zbt1 * zpsm
+               zalf  = zbt * zfm(ji-1,jj) / zpsm
+               zalf1 = 1.0 - zalf
+               ztemp = zalf * zps0 - zalf1 * zf0(ji-1,jj)
+               !
+               zps0  =  zbt  * ( zps0 + zf0(ji-1,jj) ) + zbt1 * zps0
+               zpsx  =  zbt  * ( zalf * zfx(ji-1,jj) + zalf1 * zpsx + 3.0 * ztemp ) + zbt1 * zpsx
+               zpsxx =  zbt  * ( zalf * zalf * zfxx(ji-1,jj) + zalf1 * zalf1 * zpsxx                            &
+                  &            + 5.0 * ( zalf * zalf1 * ( zpsx  - zfx(ji-1,jj) ) - ( zalf1 - zalf ) * ztemp ) ) &
+                  &            + zbt1 * zpsxx
+               zpsxy =  zbt  * ( zalf * zfxy(ji-1,jj) + zalf1 * zpsxy            &
+                  &            + 3.0 * (- zalf1*zfy(ji-1,jj)  + zalf * zpsy ) )  &
+                  &            + zbt1 * zpsxy
+               zpsy  =  zbt  * ( zpsy  + zfy (ji-1,jj) ) + zbt1 * zpsy 
+               zpsyy =  zbt  * ( zpsyy + zfyy(ji-1,jj) ) + zbt1 * zpsyy
+
+               !                                !  Flux from i+1 to i IF u LT 0.
+               zbt   =       zbet(ji,jj)
+               zbt1  = 1.0 - zbet(ji,jj)
+               zpsm  = zbt * zpsm + zbt1 * ( zpsm + zfm(ji,jj) )
+               zalf  = zbt1 * zfm(ji,jj) / zpsm
+               zalf1 = 1.0 - zalf
+               ztemp = - zalf * zps0 + zalf1 * zf0(ji,jj)
+               !
+               zps0  = zbt * zps0  + zbt1 * ( zps0 + zf0(ji,jj) )
+               zpsx  = zbt * zpsx  + zbt1 * ( zalf * zfx(ji,jj) + zalf1 * zpsx + 3.0 * ztemp )
+               zpsxx = zbt * zpsxx + zbt1 * ( zalf * zalf * zfxx(ji,jj) + zalf1 * zalf1 * zpsxx &
+                  &                         + 5.0 * ( zalf * zalf1 * ( - zpsx + zfx(ji,jj) )    &
+                  &                         + ( zalf1 - zalf ) * ztemp ) )
+               zpsxy = zbt * zpsxy + zbt1 * ( zalf * zfxy(ji,jj) + zalf1 * zpsxy  &
+                  &                         + 3.0 * ( zalf1 * zfy(ji,jj) - zalf * zpsy ) )
+               zpsy  = zbt * zpsy  + zbt1 * ( zpsy  + zfy (ji,jj) )
+               zpsyy = zbt * zpsyy + zbt1 * ( zpsyy + zfyy(ji,jj) )
+               !
+               psm (ji,jj,jl) = zpsm  ! optimization
+               ps0 (ji,jj,jl) = zps0 
+               psx (ji,jj,jl) = zpsx 
+               psxx(ji,jj,jl) = zpsxx
+               psy (ji,jj,jl) = zpsy 
+               psyy(ji,jj,jl) = zpsyy
+               psxy(ji,jj,jl) = zpsxy
+            END DO
+            
+         END DO
+
+      END DO
+      !
+   END SUBROUTINE adv_x
+
+
+   SUBROUTINE adv_y( pdt, pvt , pcrh, psm , ps0 ,   &
+      &              psx, psxx, psy , psyy, psxy )
+      !!---------------------------------------------------------------------
+      !!                **  routine adv_y  **
+      !!            
+      !! ** purpose :   Computes and adds the advection trend to sea-ice 
+      !!                variable on y axis
+      !!---------------------------------------------------------------------
+      REAL(wp)                  , INTENT(in   ) ::   pdt                ! time step
+      REAL(wp)                  , INTENT(in   ) ::   pcrh               ! call adv_x then adv_y (=1) or the opposite (=0)
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pvt                ! j-direction ice velocity at V-point [m/s]
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psm                ! area
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ps0                ! field to be advected
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psx , psy          ! 1st moments 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   psxx, psyy, psxy   ! 2nd moments
+      !!
+      INTEGER  ::   ji, jj, jl, jcat                     ! dummy loop indices
+      INTEGER  ::   jimin, jimax                         ! dummy loop indices
+      REAL(wp) ::   zs1max, zslpmax, ztemp               ! temporary scalars
+      REAL(wp) ::   zs1new, zalf , zalfq , zbt           !    -         -
+      REAL(wp) ::   zs2new, zalf1, zalf1q, zbt1          !    -         -
+      REAL(wp) ::   zpsm, zps0
+      REAL(wp) ::   zpsx, zpsy, zpsxx, zpsyy, zpsxy
+      REAL(wp), DIMENSION(jpi,jpj) ::   zf0, zfx , zfy , zbet   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfm, zfxx, zfyy, zfxy   !  -      -
+      REAL(wp), DIMENSION(jpi,jpj) ::   zalg, zalg1, zalg1q     !  -      -
+      !---------------------------------------------------------------------
+      ! in order to avoid lbc_lnk (communications):
+      !    ji loop must be 1:jpi   if adv_y is called first
+      !                and 2:jpi-1 if adv_y is called second
+      jimin = 2     - NINT(pcrh)   ! 1   or 2
+      jimax = jpim1 + NINT(pcrh)   ! jpi or jpi-1
+      !
+      jcat = SIZE( ps0 , 3 )   ! size of input arrays
+      !      
+      DO jl = 1, jcat   ! loop on categories
+         !
+         ! Limitation of moments.
+         DO jj = 1, jpj
+            DO ji = jimin, jimax
+               !
+               zpsm  = psm (ji,jj,jl) ! optimization
+               zps0  = ps0 (ji,jj,jl)
+               zpsx  = psx (ji,jj,jl)
+               zpsxx = psxx(ji,jj,jl)
+               zpsy  = psy (ji,jj,jl)
+               zpsyy = psyy(ji,jj,jl)
+               zpsxy = psxy(ji,jj,jl)
+               !
+               !  Initialize volumes of boxes (=area if adv_y first called, =psm otherwise)
+               zpsm = MAX(  pcrh * e1e2t(ji,jj) + ( 1.0 - pcrh ) * zpsm , epsi20  )
+               !
+               zslpmax = MAX( 0._wp, zps0 )
+               zs1max  = 1.5 * zslpmax
+               zs1new  = MIN( zs1max, MAX( -zs1max, zpsy ) )
+               zs2new  = MIN( ( 2.0 * zslpmax - 0.3334 * ABS( zs1new ) ), MAX( ABS( zs1new )-zslpmax, zpsyy ) )
+               rswitch = ( 1.0 - MAX( 0._wp, SIGN( 1._wp, -zslpmax) ) ) * tmask(ji,jj,1)   ! Case of empty boxes & Apply mask
+               !
+               zps0  = zslpmax  
+               zpsx  = zpsx  * rswitch
+               zpsxx = zpsxx * rswitch
+               zpsy  = zs1new         * rswitch
+               zpsyy = zs2new         * rswitch
+               zpsxy = MIN( zslpmax, MAX( -zslpmax, zpsxy ) ) * rswitch
+ 
+               !  Calculate fluxes and moments between boxes j<-->j+1              
+               !                                !  Flux from j to j+1 WHEN v GT 0   
+               zbet(ji,jj)  =  MAX( 0._wp, SIGN( 1._wp, pvt(ji,jj) ) )
+               zalf         =  MAX( 0._wp, pvt(ji,jj) ) * pdt / zpsm
+               zalfq        =  zalf * zalf
+               zalf1        =  1.0 - zalf
+               zalf1q       =  zalf1 * zalf1
+               !
+               zfm (ji,jj)  =  zalf  * zpsm
+               zf0 (ji,jj)  =  zalf  * ( zps0 + zalf1 * ( zpsy  + (zalf1-zalf) * zpsyy ) ) 
+               zfy (ji,jj)  =  zalfq *( zpsy + 3.0*zalf1*zpsyy )
+               zfyy(ji,jj)  =  zalf  * zalfq * zpsyy
+               zfx (ji,jj)  =  zalf  * ( zpsx + zalf1 * zpsxy )
+               zfxy(ji,jj)  =  zalfq * zpsxy
+               zfxx(ji,jj)  =  zalf  * zpsxx
+               !
+               !                                !  Readjust moments remaining in the box.
+               zpsm   =  zpsm  - zfm(ji,jj)
+               zps0   =  zps0  - zf0(ji,jj)
+               zpsy   =  zalf1q * ( zpsy -3.0 * zalf * zpsyy )
+               zpsyy  =  zalf1 * zalf1q * zpsyy
+               zpsx   =  zpsx  - zfx(ji,jj)
+               zpsxx  =  zpsxx - zfxx(ji,jj)
+               zpsxy  =  zalf1q * zpsxy
+               !
+               psm (ji,jj,jl) = zpsm ! optimization
+               ps0 (ji,jj,jl) = zps0 
+               psx (ji,jj,jl) = zpsx 
+               psxx(ji,jj,jl) = zpsxx
+               psy (ji,jj,jl) = zpsy 
+               psyy(ji,jj,jl) = zpsyy
+               psxy(ji,jj,jl) = zpsxy
+            END DO
+         END DO
+         !
+         DO jj = 1, jpjm1
+            DO ji = jimin, jimax
+               !                                !  Flux from j+1 to j when v LT 0.
+               zalf          = MAX( 0._wp, -pvt(ji,jj) ) * pdt / psm(ji,jj+1,jl) 
+               zalg  (ji,jj) = zalf
+               zalfq         = zalf * zalf
+               zalf1         = 1.0 - zalf
+               zalg1 (ji,jj) = zalf1
+               zalf1q        = zalf1 * zalf1
+               zalg1q(ji,jj) = zalf1q
+               !
+               zfm   (ji,jj) = zfm (ji,jj) + zalf  *    psm (ji,jj+1,jl)
+               zf0   (ji,jj) = zf0 (ji,jj) + zalf  * (  ps0 (ji,jj+1,jl) &
+                  &                                   - zalf1 * (psy(ji,jj+1,jl) - (zalf1 - zalf ) * psyy(ji,jj+1,jl) ) )
+               zfy   (ji,jj) = zfy (ji,jj) + zalfq * (  psy (ji,jj+1,jl) - 3.0 * zalf1 * psyy(ji,jj+1,jl) )
+               zfyy  (ji,jj) = zfyy(ji,jj) + zalf  *    psyy(ji,jj+1,jl) * zalfq
+               zfx   (ji,jj) = zfx (ji,jj) + zalf  * (  psx (ji,jj+1,jl) - zalf1 * psxy(ji,jj+1,jl) )
+               zfxy  (ji,jj) = zfxy(ji,jj) + zalfq *    psxy(ji,jj+1,jl)
+               zfxx  (ji,jj) = zfxx(ji,jj) + zalf  *    psxx(ji,jj+1,jl)
+            END DO
+         END DO
+
+         DO jj = 2, jpjm1
+            DO ji = jimin, jimax
+               !                                !  Readjust moments remaining in the box.
+               zbt  =         zbet(ji,jj-1)
+               zbt1 = ( 1.0 - zbet(ji,jj-1) )
+               !
+               zpsm  = psm (ji,jj,jl) ! optimization
+               zps0  = ps0 (ji,jj,jl)
+               zpsx  = psx (ji,jj,jl)
+               zpsxx = psxx(ji,jj,jl)
+               zpsy  = psy (ji,jj,jl)
+               zpsyy = psyy(ji,jj,jl)
+               zpsxy = psxy(ji,jj,jl)
+               !
+               zpsm  = zbt * zpsm + zbt1 * ( zpsm - zfm(ji,jj-1) )
+               zps0  = zbt * zps0 + zbt1 * ( zps0 - zf0(ji,jj-1) )
+               zpsy  = zalg1q(ji,jj-1) * ( zpsy + 3.0 * zalg(ji,jj-1) * zpsyy )
+               zpsyy = zalg1 (ji,jj-1) * zalg1q(ji,jj-1) * zpsyy
+               zpsx  = zbt * zpsx  + zbt1 * ( zpsx  - zfx (ji,jj-1) )
+               zpsxx = zbt * zpsxx + zbt1 * ( zpsxx - zfxx(ji,jj-1) )
+               zpsxy = zalg1q(ji,jj-1) * zpsxy
+
+               !   Put the temporary moments into appropriate neighboring boxes.    
+               !                                !   Flux from j to j+1 IF v GT 0.
+               zbt   =       zbet(ji,jj-1)
+               zbt1  = 1.0 - zbet(ji,jj-1)
+               zpsm  = zbt * ( zpsm + zfm(ji,jj-1) ) + zbt1 * zpsm 
+               zalf  = zbt * zfm(ji,jj-1) / zpsm 
+               zalf1 = 1.0 - zalf
+               ztemp = zalf * zps0 - zalf1 * zf0(ji,jj-1)
+               !
+               zps0  =   zbt  * ( zps0 + zf0(ji,jj-1) ) + zbt1 * zps0
+               zpsy  =   zbt  * ( zalf * zfy(ji,jj-1) + zalf1 * zpsy + 3.0 * ztemp )  &
+                  &             + zbt1 * zpsy  
+               zpsyy =   zbt  * ( zalf * zalf * zfyy(ji,jj-1) + zalf1 * zalf1 * zpsyy                           &
+                  &             + 5.0 * ( zalf * zalf1 * ( zpsy - zfy(ji,jj-1) ) - ( zalf1 - zalf ) * ztemp ) ) & 
+                  &             + zbt1 * zpsyy
+               zpsxy =   zbt  * ( zalf * zfxy(ji,jj-1) + zalf1 * zpsxy             &
+                  &             + 3.0 * (- zalf1 * zfx(ji,jj-1) + zalf * zpsx ) )  &
+                  &             + zbt1 * zpsxy
+               zpsx  =   zbt * ( zpsx  + zfx (ji,jj-1) ) + zbt1 * zpsx 
+               zpsxx =   zbt * ( zpsxx + zfxx(ji,jj-1) ) + zbt1 * zpsxx
+
+               !                                !  Flux from j+1 to j IF v LT 0.
+               zbt   =       zbet(ji,jj)
+               zbt1  = 1.0 - zbet(ji,jj)
+               zpsm  = zbt * zpsm + zbt1 * ( zpsm + zfm(ji,jj) )
+               zalf  = zbt1 * zfm(ji,jj) / zpsm
+               zalf1 = 1.0 - zalf
+               ztemp = - zalf * zps0 + zalf1 * zf0(ji,jj)
+               !
+               zps0  = zbt * zps0  + zbt1 * (  zps0 + zf0(ji,jj) )
+               zpsy  = zbt * zpsy  + zbt1 * (  zalf * zfy(ji,jj) + zalf1 * zpsy + 3.0 * ztemp )
+               zpsyy = zbt * zpsyy + zbt1 * (  zalf * zalf * zfyy(ji,jj) + zalf1 * zalf1 * zpsyy &
+                  &                         + 5.0 * ( zalf * zalf1 * ( - zpsy + zfy(ji,jj) )     &
+                  &                         + ( zalf1 - zalf ) * ztemp ) )
+               zpsxy = zbt * zpsxy + zbt1 * (  zalf * zfxy(ji,jj) + zalf1 * zpsxy  &
+                  &                         + 3.0 * ( zalf1 * zfx(ji,jj) - zalf * zpsx ) )
+               zpsx  = zbt * zpsx  + zbt1 * ( zpsx  + zfx (ji,jj) )
+               zpsxx = zbt * zpsxx + zbt1 * ( zpsxx + zfxx(ji,jj) )
+               !
+               psm (ji,jj,jl) = zpsm ! optimization
+               ps0 (ji,jj,jl) = zps0 
+               psx (ji,jj,jl) = zpsx 
+               psxx(ji,jj,jl) = zpsxx
+               psy (ji,jj,jl) = zpsy 
+               psyy(ji,jj,jl) = zpsyy
+               psxy(ji,jj,jl) = zpsxy
+            END DO
+         END DO
+
+      END DO
+      !
+   END SUBROUTINE adv_y
+
+
+   SUBROUTINE Hbig( pdt, phi_max, phs_max, phip_max, psi_max, pes_max, pei_max, &
+      &                  pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i, pe_s, pe_i )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE Hbig  ***
+      !!
+      !! ** Purpose : Thickness correction in case advection scheme creates
+      !!              abnormally tick ice or snow
+      !!
+      !! ** Method  : 1- check whether ice thickness is larger than the surrounding 9-points
+      !!                 (before advection) and reduce it by adapting ice concentration
+      !!              2- check whether snow thickness is larger than the surrounding 9-points
+      !!                 (before advection) and reduce it by sending the excess in the ocean
+      !!
+      !! ** input   : Max thickness of the surrounding 9-points
+      !!-------------------------------------------------------------------
+      REAL(wp)                    , INTENT(in   ) ::   pdt                                   ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   phi_max, phs_max, phip_max, psi_max   ! max ice thick from surrounding 9-pts
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pes_max
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pei_max
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_i
+      !
+      INTEGER  ::   ji, jj, jk, jl         ! dummy loop indices
+      REAL(wp) ::   z1_dt, zhip, zhi, zhs, zsi, zes, zei, zfra
+      !!-------------------------------------------------------------------
+      !
+      z1_dt = 1._wp / pdt
+      !
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                  !
+                  !                               ! -- check h_ip -- !
+                  ! if h_ip is larger than the surrounding 9 pts => reduce h_ip and increase a_ip
+                  IF( ln_pnd_LEV .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
+                     zhip = pv_ip(ji,jj,jl) / MAX( epsi20, pa_ip(ji,jj,jl) )
+                     IF( zhip > phip_max(ji,jj,jl) .AND. pa_ip(ji,jj,jl) < 0.15 ) THEN
+                        pa_ip(ji,jj,jl) = pv_ip(ji,jj,jl) / phip_max(ji,jj,jl)
+                     ENDIF
+                  ENDIF
+                  !
+                  !                               ! -- check h_i -- !
+                  ! if h_i is larger than the surrounding 9 pts => reduce h_i and increase a_i
+                  zhi = pv_i(ji,jj,jl) / pa_i(ji,jj,jl)
+                  IF( zhi > phi_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     pa_i(ji,jj,jl) = pv_i(ji,jj,jl) / MIN( phi_max(ji,jj,jl), hi_max(jpl) )   !-- bound h_i to hi_max (99 m)
+                  ENDIF
+                  !
+                  !                               ! -- check h_s -- !
+                  ! if h_s is larger than the surrounding 9 pts => put the snow excess in the ocean
+                  zhs = pv_s(ji,jj,jl) / pa_i(ji,jj,jl)
+                  IF( pv_s(ji,jj,jl) > 0._wp .AND. zhs > phs_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     zfra = phs_max(ji,jj,jl) / MAX( zhs, epsi20 )
+                     !
+                     wfx_res(ji,jj) = wfx_res(ji,jj) + ( pv_s(ji,jj,jl) - pa_i(ji,jj,jl) * phs_max(ji,jj,jl) ) * rhos * z1_dt
+                     hfx_res(ji,jj) = hfx_res(ji,jj) - SUM( pe_s(ji,jj,1:nlay_s,jl) ) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                     !
+                     pe_s(ji,jj,1:nlay_s,jl) = pe_s(ji,jj,1:nlay_s,jl) * zfra
+                     pv_s(ji,jj,jl)          = pa_i(ji,jj,jl) * phs_max(ji,jj,jl)
+                  ENDIF           
+                  !                  
+                  !                               ! -- check s_i -- !
+                  ! if s_i is larger than the surrounding 9 pts => put salt excess in the ocean
+                  zsi = psv_i(ji,jj,jl) / pv_i(ji,jj,jl)
+                  IF( zsi > psi_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     zfra = psi_max(ji,jj,jl) / zsi
+                     sfx_res(ji,jj) = sfx_res(ji,jj) + psv_i(ji,jj,jl) * ( 1._wp - zfra ) * rhoi * z1_dt
+                     psv_i(ji,jj,jl) = psv_i(ji,jj,jl) * zfra
+                  ENDIF
+                  !
+               ENDIF
+            END DO
+         END DO
+      END DO 
+      !
+      !                                           ! -- check e_i/v_i -- !
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                     ! if e_i/v_i is larger than the surrounding 9 pts => put the heat excess in the ocean
+                     zei = pe_i(ji,jj,jk,jl) / pv_i(ji,jj,jl)
+                     IF( zei > pei_max(ji,jj,jk,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                        zfra = pei_max(ji,jj,jk,jl) / zei
+                        hfx_res(ji,jj) = hfx_res(ji,jj) - pe_i(ji,jj,jk,jl) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                        pe_i(ji,jj,jk,jl) = pe_i(ji,jj,jk,jl) * zfra
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+      !                                           ! -- check e_s/v_s -- !
+      DO jl = 1, jpl
+         DO jk = 1, nlay_s
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF ( pv_s(ji,jj,jl) > 0._wp ) THEN
+                     ! if e_s/v_s is larger than the surrounding 9 pts => put the heat excess in the ocean
+                     zes = pe_s(ji,jj,jk,jl) / pv_s(ji,jj,jl)
+                     IF( zes > pes_max(ji,jj,jk,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                        zfra = pes_max(ji,jj,jk,jl) / zes
+                        hfx_res(ji,jj) = hfx_res(ji,jj) - pe_s(ji,jj,jk,jl) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                        pe_s(ji,jj,jk,jl) = pe_s(ji,jj,jk,jl) * zfra
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE Hbig
+
+
+   SUBROUTINE Hsnow( pdt, pv_i, pv_s, pa_i, pa_ip, pe_s )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE Hsnow  ***
+      !!
+      !! ** Purpose : 1- Check snow load after advection
+      !!              2- Correct pond concentration to avoid a_ip > a_i
+      !!
+      !! ** Method :  If snow load makes snow-ice interface to deplet below the ocean surface
+      !!              then put the snow excess in the ocean
+      !!
+      !! ** Notes :   This correction is crucial because of the call to routine icecor afterwards
+      !!              which imposes a mini of ice thick. (rn_himin). This imposed mini can artificially
+      !!              make the snow very thick (if concentration decreases drastically)
+      !!              This behavior has been seen in Ultimate-Macho and supposedly it can also be true for Prather
+      !!-------------------------------------------------------------------
+      REAL(wp)                    , INTENT(in   ) ::   pdt   ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i, pv_s, pa_i, pa_ip
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s
+      !
+      INTEGER  ::   ji, jj, jl   ! dummy loop indices
+      REAL(wp) ::   z1_dt, zvs_excess, zfra
+      !!-------------------------------------------------------------------
+      !
+      z1_dt = 1._wp / pdt
+      !
+      ! -- check snow load -- !
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                  !
+                  zvs_excess = MAX( 0._wp, pv_s(ji,jj,jl) - pv_i(ji,jj,jl) * (rau0-rhoi) * r1_rhos )
+                  !
+                  IF( zvs_excess > 0._wp ) THEN   ! snow-ice interface deplets below the ocean surface
+                     ! put snow excess in the ocean
+                     zfra = ( pv_s(ji,jj,jl) - zvs_excess ) / MAX( pv_s(ji,jj,jl), epsi20 )
+                     wfx_res(ji,jj) = wfx_res(ji,jj) + zvs_excess * rhos * z1_dt
+                     hfx_res(ji,jj) = hfx_res(ji,jj) - SUM( pe_s(ji,jj,1:nlay_s,jl) ) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                     ! correct snow volume and heat content
+                     pe_s(ji,jj,1:nlay_s,jl) = pe_s(ji,jj,1:nlay_s,jl) * zfra
+                     pv_s(ji,jj,jl)          = pv_s(ji,jj,jl) - zvs_excess
+                  ENDIF
+                  !
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      !-- correct pond concentration to avoid a_ip > a_i -- !
+      WHERE( pa_ip(:,:,:) > pa_i(:,:,:) )   pa_ip(:,:,:) = pa_i(:,:,:)
+      !
+   END SUBROUTINE Hsnow
+
+
+   SUBROUTINE adv_pra_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE adv_pra_init  ***
+      !!
+      !! ** Purpose :   allocate and initialize arrays for Prather advection 
+      !!-------------------------------------------------------------------
+      INTEGER ::   ierr
+      !!-------------------------------------------------------------------
+      !
+      !                             !* allocate prather fields
+      ALLOCATE( sxice(jpi,jpj,jpl) , syice(jpi,jpj,jpl) , sxxice(jpi,jpj,jpl) , syyice(jpi,jpj,jpl) , sxyice(jpi,jpj,jpl) ,   &
+         &      sxsn (jpi,jpj,jpl) , sysn (jpi,jpj,jpl) , sxxsn (jpi,jpj,jpl) , syysn (jpi,jpj,jpl) , sxysn (jpi,jpj,jpl) ,   &
+         &      sxa  (jpi,jpj,jpl) , sya  (jpi,jpj,jpl) , sxxa  (jpi,jpj,jpl) , syya  (jpi,jpj,jpl) , sxya  (jpi,jpj,jpl) ,   &
+         &      sxsal(jpi,jpj,jpl) , sysal(jpi,jpj,jpl) , sxxsal(jpi,jpj,jpl) , syysal(jpi,jpj,jpl) , sxysal(jpi,jpj,jpl) ,   &
+         &      sxage(jpi,jpj,jpl) , syage(jpi,jpj,jpl) , sxxage(jpi,jpj,jpl) , syyage(jpi,jpj,jpl) , sxyage(jpi,jpj,jpl) ,   &
+         &      sxap (jpi,jpj,jpl) , syap (jpi,jpj,jpl) , sxxap (jpi,jpj,jpl) , syyap (jpi,jpj,jpl) , sxyap (jpi,jpj,jpl) ,   &
+         &      sxvp (jpi,jpj,jpl) , syvp (jpi,jpj,jpl) , sxxvp (jpi,jpj,jpl) , syyvp (jpi,jpj,jpl) , sxyvp (jpi,jpj,jpl) ,   &
+         &      sxvl (jpi,jpj,jpl) , syvl (jpi,jpj,jpl) , sxxvl (jpi,jpj,jpl) , syyvl (jpi,jpj,jpl) , sxyvl (jpi,jpj,jpl) ,   &
+         !
+         &      sxc0 (jpi,jpj,nlay_s,jpl) , syc0 (jpi,jpj,nlay_s,jpl) , sxxc0(jpi,jpj,nlay_s,jpl) , &
+         &      syyc0(jpi,jpj,nlay_s,jpl) , sxyc0(jpi,jpj,nlay_s,jpl)                             , &
+         !
+         &      sxe  (jpi,jpj,nlay_i,jpl) , sye  (jpi,jpj,nlay_i,jpl) , sxxe (jpi,jpj,nlay_i,jpl) , &
+         &      syye (jpi,jpj,nlay_i,jpl) , sxye (jpi,jpj,nlay_i,jpl)                             , &
+         &      STAT = ierr )
+      !
+      CALL mpp_sum( 'icedyn_adv_pra', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop('STOP', 'adv_pra_init : unable to allocate ice arrays for Prather advection scheme')
+      !
+      CALL adv_pra_rst( 'READ' )    !* read or initialize all required files
+      !
+   END SUBROUTINE adv_pra_init
+
+
+   SUBROUTINE adv_pra_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE adv_pra_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER ::   jk, jl   ! dummy loop indices
+      INTEGER ::   iter     ! local integer
+      INTEGER ::   id1      ! local integer
+      CHARACTER(len=25) ::   znam
+      CHARACTER(len=2)  ::   zchar, zchar1
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z3d   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      !                                      !==========================!
+      IF( TRIM(cdrw) == 'READ' ) THEN        !==  Read or initialize  ==!
+         !                                   !==========================!
+         !
+         IF( ln_rstart ) THEN   ;   id1 = iom_varid( numrir, 'sxice' , ldstop = .FALSE. )    ! file exist: id1>0
+         ELSE                   ;   id1 = 0                                                  ! no restart: id1=0
+         ENDIF
+         !
+         IF( id1 > 0 ) THEN                     !**  Read the restart file  **!
+            !
+            !                                                        ! ice thickness
+            CALL iom_get( numrir, jpdom_autoglo, 'sxice' , sxice  )
+            CALL iom_get( numrir, jpdom_autoglo, 'syice' , syice  )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxxice', sxxice )
+            CALL iom_get( numrir, jpdom_autoglo, 'syyice', syyice )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxyice', sxyice )
+            !                                                        ! snow thickness
+            CALL iom_get( numrir, jpdom_autoglo, 'sxsn'  , sxsn   )
+            CALL iom_get( numrir, jpdom_autoglo, 'sysn'  , sysn   )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxxsn' , sxxsn  )
+            CALL iom_get( numrir, jpdom_autoglo, 'syysn' , syysn  )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxysn' , sxysn  )
+            !                                                        ! ice concentration
+            CALL iom_get( numrir, jpdom_autoglo, 'sxa'   , sxa    )
+            CALL iom_get( numrir, jpdom_autoglo, 'sya'   , sya    )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxxa'  , sxxa   )
+            CALL iom_get( numrir, jpdom_autoglo, 'syya'  , syya   )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxya'  , sxya   )
+            !                                                        ! ice salinity
+            CALL iom_get( numrir, jpdom_autoglo, 'sxsal' , sxsal  )
+            CALL iom_get( numrir, jpdom_autoglo, 'sysal' , sysal  )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxxsal', sxxsal )
+            CALL iom_get( numrir, jpdom_autoglo, 'syysal', syysal )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxysal', sxysal )
+            !                                                        ! ice age
+            CALL iom_get( numrir, jpdom_autoglo, 'sxage' , sxage  )
+            CALL iom_get( numrir, jpdom_autoglo, 'syage' , syage  )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxxage', sxxage )
+            CALL iom_get( numrir, jpdom_autoglo, 'syyage', syyage )
+            CALL iom_get( numrir, jpdom_autoglo, 'sxyage', sxyage )
+            !                                                        ! snow layers heat content
+            DO jk = 1, nlay_s
+               WRITE(zchar1,'(I2.2)') jk
+               znam = 'sxc0'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxc0 (:,:,jk,:) = z3d(:,:,:)
+               znam = 'syc0'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   syc0 (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxxc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxxc0(:,:,jk,:) = z3d(:,:,:)
+               znam = 'syyc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   syyc0(:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxyc0'//'_l'//zchar1 ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxyc0(:,:,jk,:) = z3d(:,:,:)
+            END DO
+            !                                                        ! ice layers heat content
+            DO jk = 1, nlay_i
+               WRITE(zchar1,'(I2.2)') jk
+               znam = 'sxe'//'_l'//zchar1   ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxe (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sye'//'_l'//zchar1   ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sye (:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxxe'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxxe(:,:,jk,:) = z3d(:,:,:)
+               znam = 'syye'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   syye(:,:,jk,:) = z3d(:,:,:)
+               znam = 'sxye'//'_l'//zchar1  ;   CALL iom_get( numrir, jpdom_autoglo, znam , z3d )   ;   sxye(:,:,jk,:) = z3d(:,:,:)
+            END DO
+            !
+            IF( ln_pnd_LEV ) THEN                                    ! melt pond fraction
+               IF( iom_varid( numrir, 'sxap', ldstop = .FALSE. ) > 0 ) THEN
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxap' , sxap  )
+                  CALL iom_get( numrir, jpdom_autoglo, 'syap' , syap  )
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxxap', sxxap )
+                  CALL iom_get( numrir, jpdom_autoglo, 'syyap', syyap )
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxyap', sxyap )
+                  !                                                     ! melt pond volume
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxvp' , sxvp  )
+                  CALL iom_get( numrir, jpdom_autoglo, 'syvp' , syvp  )
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxxvp', sxxvp )
+                  CALL iom_get( numrir, jpdom_autoglo, 'syyvp', syyvp )
+                  CALL iom_get( numrir, jpdom_autoglo, 'sxyvp', sxyvp )
+               ELSE
+                  sxap = 0._wp ;   syap = 0._wp    ;   sxxap = 0._wp    ;   syyap = 0._wp    ;   sxyap = 0._wp   ! melt pond fraction
+                  sxvp = 0._wp ;   syvp = 0._wp    ;   sxxvp = 0._wp    ;   syyvp = 0._wp    ;   sxyvp = 0._wp   ! melt pond volume
+               ENDIF
+                  !
+               IF ( ln_pnd_lids ) THEN                               ! melt pond lid volume
+                  IF( iom_varid( numrir, 'sxvl', ldstop = .FALSE. ) > 0 ) THEN
+                     CALL iom_get( numrir, jpdom_autoglo, 'sxvl' , sxvl  )
+                     CALL iom_get( numrir, jpdom_autoglo, 'syvl' , syvl  )
+                     CALL iom_get( numrir, jpdom_autoglo, 'sxxvl', sxxvl )
+                     CALL iom_get( numrir, jpdom_autoglo, 'syyvl', syyvl )
+                     CALL iom_get( numrir, jpdom_autoglo, 'sxyvl', sxyvl )
+                  ELSE
+                     sxvl = 0._wp; syvl = 0._wp    ;   sxxvl = 0._wp    ;   syyvl = 0._wp    ;   sxyvl = 0._wp   ! melt pond lid volume
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+         ELSE                                   !**  start rheology from rest  **!
+            !
+            IF(lwp) WRITE(numout,*) '   ==>>   start from rest OR previous run without Prather, set moments to 0'
+            !
+            sxice = 0._wp   ;   syice = 0._wp   ;   sxxice = 0._wp   ;   syyice = 0._wp   ;   sxyice = 0._wp      ! ice thickness
+            sxsn  = 0._wp   ;   sysn  = 0._wp   ;   sxxsn  = 0._wp   ;   syysn  = 0._wp   ;   sxysn  = 0._wp      ! snow thickness
+            sxa   = 0._wp   ;   sya   = 0._wp   ;   sxxa   = 0._wp   ;   syya   = 0._wp   ;   sxya   = 0._wp      ! ice concentration
+            sxsal = 0._wp   ;   sysal = 0._wp   ;   sxxsal = 0._wp   ;   syysal = 0._wp   ;   sxysal = 0._wp      ! ice salinity
+            sxage = 0._wp   ;   syage = 0._wp   ;   sxxage = 0._wp   ;   syyage = 0._wp   ;   sxyage = 0._wp      ! ice age
+            sxc0  = 0._wp   ;   syc0  = 0._wp   ;   sxxc0  = 0._wp   ;   syyc0  = 0._wp   ;   sxyc0  = 0._wp      ! snow layers heat content
+            sxe   = 0._wp   ;   sye   = 0._wp   ;   sxxe   = 0._wp   ;   syye   = 0._wp   ;   sxye   = 0._wp      ! ice layers heat content
+            IF( ln_pnd_LEV ) THEN
+               sxap = 0._wp ;   syap = 0._wp    ;   sxxap = 0._wp    ;   syyap = 0._wp    ;   sxyap = 0._wp       ! melt pond fraction
+               sxvp = 0._wp ;   syvp = 0._wp    ;   sxxvp = 0._wp    ;   syyvp = 0._wp    ;   sxyvp = 0._wp       ! melt pond volume
+               IF ( ln_pnd_lids ) THEN
+                  sxvl = 0._wp; syvl = 0._wp    ;   sxxvl = 0._wp    ;   syyvl = 0._wp    ;   sxyvl = 0._wp       ! melt pond lid volume
+               ENDIF
+            ENDIF
+         ENDIF
+         !
+         !                                   !=====================================!
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   !==  write in the ice restart file  ==!
+         !                                   !=====================================!
+         IF(lwp) WRITE(numout,*) '----  ice-adv-rst  ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         !
+         ! In case Prather scheme is used for advection, write second order moments
+         ! ------------------------------------------------------------------------
+         !
+         !                                                           ! ice thickness
+         CALL iom_rstput( iter, nitrst, numriw, 'sxice' , sxice  )
+         CALL iom_rstput( iter, nitrst, numriw, 'syice' , syice  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxice', sxxice )
+         CALL iom_rstput( iter, nitrst, numriw, 'syyice', syyice )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxyice', sxyice )
+         !                                                           ! snow thickness
+         CALL iom_rstput( iter, nitrst, numriw, 'sxsn'  , sxsn   )
+         CALL iom_rstput( iter, nitrst, numriw, 'sysn'  , sysn   )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxsn' , sxxsn  )
+         CALL iom_rstput( iter, nitrst, numriw, 'syysn' , syysn  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxysn' , sxysn  )
+         !                                                           ! ice concentration
+         CALL iom_rstput( iter, nitrst, numriw, 'sxa'   , sxa    )
+         CALL iom_rstput( iter, nitrst, numriw, 'sya'   , sya    )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxa'  , sxxa   )
+         CALL iom_rstput( iter, nitrst, numriw, 'syya'  , syya   )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxya'  , sxya   )
+         !                                                           ! ice salinity
+         CALL iom_rstput( iter, nitrst, numriw, 'sxsal' , sxsal  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sysal' , sysal  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxsal', sxxsal )
+         CALL iom_rstput( iter, nitrst, numriw, 'syysal', syysal )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxysal', sxysal )
+         !                                                           ! ice age
+         CALL iom_rstput( iter, nitrst, numriw, 'sxage' , sxage  )
+         CALL iom_rstput( iter, nitrst, numriw, 'syage' , syage  )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxxage', sxxage )
+         CALL iom_rstput( iter, nitrst, numriw, 'syyage', syyage )
+         CALL iom_rstput( iter, nitrst, numriw, 'sxyage', sxyage )
+         !                                                           ! snow layers heat content
+         DO jk = 1, nlay_s
+            WRITE(zchar1,'(I2.2)') jk
+            znam = 'sxc0'//'_l'//zchar1  ;   z3d(:,:,:) = sxc0 (:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'syc0'//'_l'//zchar1  ;   z3d(:,:,:) = syc0 (:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxxc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxxc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'syyc0'//'_l'//zchar1 ;   z3d(:,:,:) = syyc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxyc0'//'_l'//zchar1 ;   z3d(:,:,:) = sxyc0(:,:,jk,:)  ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+         END DO
+         !                                                           ! ice layers heat content
+         DO jk = 1, nlay_i
+            WRITE(zchar1,'(I2.2)') jk
+            znam = 'sxe'//'_l'//zchar1   ;   z3d(:,:,:) = sxe (:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sye'//'_l'//zchar1   ;   z3d(:,:,:) = sye (:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxxe'//'_l'//zchar1  ;   z3d(:,:,:) = sxxe(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'syye'//'_l'//zchar1  ;   z3d(:,:,:) = syye(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+            znam = 'sxye'//'_l'//zchar1  ;   z3d(:,:,:) = sxye(:,:,jk,:)   ;   CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+         END DO
+         !
+         IF( ln_pnd_LEV ) THEN                                       ! melt pond fraction
+            CALL iom_rstput( iter, nitrst, numriw, 'sxap' , sxap  )
+            CALL iom_rstput( iter, nitrst, numriw, 'syap' , syap  )
+            CALL iom_rstput( iter, nitrst, numriw, 'sxxap', sxxap )
+            CALL iom_rstput( iter, nitrst, numriw, 'syyap', syyap )
+            CALL iom_rstput( iter, nitrst, numriw, 'sxyap', sxyap )
+            !                                                        ! melt pond volume
+            CALL iom_rstput( iter, nitrst, numriw, 'sxvp' , sxvp  )
+            CALL iom_rstput( iter, nitrst, numriw, 'syvp' , syvp  )
+            CALL iom_rstput( iter, nitrst, numriw, 'sxxvp', sxxvp )
+            CALL iom_rstput( iter, nitrst, numriw, 'syyvp', syyvp )
+            CALL iom_rstput( iter, nitrst, numriw, 'sxyvp', sxyvp )
+            !
+            IF ( ln_pnd_lids ) THEN                                  ! melt pond lid volume
+               CALL iom_rstput( iter, nitrst, numriw, 'sxvl' , sxvl  )
+               CALL iom_rstput( iter, nitrst, numriw, 'syvl' , syvl  )
+               CALL iom_rstput( iter, nitrst, numriw, 'sxxvl', sxxvl )
+               CALL iom_rstput( iter, nitrst, numriw, 'syyvl', syyvl )
+               CALL iom_rstput( iter, nitrst, numriw, 'sxyvl', sxyvl )
+            ENDIF
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE adv_pra_rst
+
+   SUBROUTINE icemax3D( pice , pmax )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE icemax3D ***                     
+      !! ** Purpose :  compute the max of the 9 points around
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in ) ::   pice   ! input
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(out) ::   pmax   ! output
+      REAL(wp), DIMENSION(2:jpim1,jpj)              ::   zmax   ! temporary array
+      INTEGER  ::   ji, jj, jl   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 2, jpim1
+               zmax(ji,jj) = MAX( epsi20, pice(ji,jj,jl), pice(ji-1,jj,jl), pice(ji+1,jj,jl) )
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               pmax(ji,jj,jl) = MAX( epsi20, zmax(ji,jj), zmax(ji,jj-1), zmax(ji,jj+1) )
+            END DO
+         END DO
+      END DO
+   END SUBROUTINE icemax3D
+
+   SUBROUTINE icemax4D( pice , pmax )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE icemax4D ***                     
+      !! ** Purpose :  compute the max of the 9 points around
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:,:)    , INTENT(in ) ::   pice   ! input
+      REAL(wp), DIMENSION(:,:,:,:)    , INTENT(out) ::   pmax   ! output
+      REAL(wp), DIMENSION(2:jpim1,jpj)              ::   zmax   ! temporary array
+      INTEGER  ::   jlay, ji, jj, jk, jl   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      jlay = SIZE( pice , 3 )   ! size of input arrays
+      DO jl = 1, jpl
+         DO jk = 1, jlay
+            DO jj = 1, jpj
+               DO ji = 2, jpim1
+                  zmax(ji,jj) = MAX( epsi20, pice(ji,jj,jk,jl), pice(ji-1,jj,jk,jl), pice(ji+1,jj,jk,jl) )
+               END DO
+            END DO
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  pmax(ji,jj,jk,jl) = MAX( epsi20, zmax(ji,jj), zmax(ji,jj-1), zmax(ji,jj+1) )
+               END DO
+            END DO
+         END DO
+      END DO
+   END SUBROUTINE icemax4D
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option            Dummy module        NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icedyn_adv_pra
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_umx.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_umx.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_adv_umx.F90	(revision 14097)
@@ -0,0 +1,1805 @@
+MODULE icedyn_adv_umx
+   !!==============================================================================
+   !!                       ***  MODULE  icedyn_adv_umx  ***
+   !! sea-ice : advection using the ULTIMATE-MACHO scheme
+   !!==============================================================================
+   !! History :  3.6  !  2014-11  (C. Rousset, G. Madec)  Original code
+   !!            4.0  !  2018     (many people)           SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_adv_umx   : update the tracer fields
+   !!   ultimate_x(_y)    : compute a tracer value at velocity points using ULTIMATE scheme at various orders
+   !!   macho             : compute the fluxes
+   !!   nonosc_ice        : limit the fluxes using a non-oscillatory algorithm 
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constant
+   USE dom_oce        ! ocean domain
+   USE sbc_oce , ONLY : nn_fsbc   ! update frequency of surface boundary condition
+   USE ice            ! sea-ice variables
+   USE icevar         ! sea-ice: operations
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_adv_umx   ! called by icedyn_adv.F90
+   !
+   INTEGER, PARAMETER ::   np_advS = 1         ! advection for S and T:    dVS/dt = -div(      uVS     ) => np_advS = 1
+   !                                                                    or dVS/dt = -div( uA * uHS / u ) => np_advS = 2
+   !                                                                    or dVS/dt = -div( uV * uS  / u ) => np_advS = 3
+   INTEGER, PARAMETER ::   np_limiter = 1      ! limiter: 1 = nonosc
+   !                                                      2 = superbee
+   !                                                      3 = h3
+   LOGICAL            ::   ll_upsxy  = .TRUE.   ! alternate directions for upstream
+   LOGICAL            ::   ll_hoxy   = .TRUE.   ! alternate directions for high order
+   LOGICAL            ::   ll_neg    = .TRUE.   ! if T interpolated at u/v points is negative or v_i < 1.e-6
+   !                                                 then interpolate T at u/v points using the upstream scheme
+   LOGICAL            ::   ll_prelim = .FALSE.  ! prelimiter from: Zalesak(1979) eq. 14 => not well defined in 2D
+   !
+   REAL(wp)           ::   z1_6   = 1._wp /   6._wp   ! =1/6
+   REAL(wp)           ::   z1_120 = 1._wp / 120._wp   ! =1/120
+   !
+   INTEGER, ALLOCATABLE, DIMENSION(:,:,:) ::   imsk_small, jmsk_small
+   !
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_adv_umx( kn_umx, kt, pu_ice, pv_ice, ph_i, ph_s, ph_ip,  &
+      &                        pato_i, pv_i, pv_s, psv_i, poa_i, pa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dyn_adv_umx  ***
+      !! 
+      !! **  Purpose :   Compute the now trend due to total advection of 
+      !!                 tracers and add it to the general trend of tracer equations
+      !!                 using an "Ultimate-Macho" scheme
+      !!
+      !! Reference : Leonard, B.P., 1991, Comput. Methods Appl. Mech. Eng., 88, 17-74. 
+      !!----------------------------------------------------------------------
+      INTEGER                     , INTENT(in   ) ::   kn_umx     ! order of the scheme (1-5=UM or 20=CEN2)
+      INTEGER                     , INTENT(in   ) ::   kt         ! time step
+      REAL(wp), DIMENSION(:,:)    , INTENT(in   ) ::   pu_ice     ! ice i-velocity
+      REAL(wp), DIMENSION(:,:)    , INTENT(in   ) ::   pv_ice     ! ice j-velocity
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_i       ! ice thickness
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_s       ! snw thickness
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   ph_ip      ! ice pond thickness
+      REAL(wp), DIMENSION(:,:)    , INTENT(inout) ::   pato_i     ! open water area
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i       ! ice volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_s       ! snw volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   psv_i      ! salt content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   poa_i      ! age content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_i       ! ice concentration
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_ip      ! melt pond concentration
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_ip      ! melt pond volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_il      ! melt pond lid volume
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s       ! snw heat content
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_i       ! ice heat content
+      !
+      INTEGER  ::   ji, jj, jk, jl, jt      ! dummy loop indices
+      INTEGER  ::   icycle                  ! number of sub-timestep for the advection
+      REAL(wp) ::   zamsk                   ! 1 if advection of concentration, 0 if advection of other tracers
+      REAL(wp) ::   zdt, z1_dt, zvi_cen
+      REAL(wp), DIMENSION(1)                  ::   zcflprv, zcflnow   ! for global communication
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zudy, zvdx, zcu_box, zcv_box
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zati1, zati2
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   zu_cat, zv_cat
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   zua_ho, zva_ho, zua_ups, zva_ups
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   z1_ai , z1_aip, zhvar
+      REAL(wp), DIMENSION(jpi,jpj,jpl)        ::   zhi_max, zhs_max, zhip_max, zs_i, zsi_max
+      REAL(wp), DIMENSION(jpi,jpj,nlay_i,jpl) ::   ze_i, zei_max
+      REAL(wp), DIMENSION(jpi,jpj,nlay_s,jpl) ::   ze_s, zes_max
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zuv_ho, zvv_ho, zuv_ups, zvv_ups, z1_vi, z1_vs 
+      !! diagnostics
+      REAL(wp), DIMENSION(jpi,jpj)            ::   zdiag_adv_mass, zdiag_adv_salt, zdiag_adv_heat      
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_adv_umx: Ultimate-Macho advection scheme'
+      !
+      ! --- Record max of the surrounding 9-pts (for call Hbig) --- !
+      ! thickness and salinity
+      WHERE( pv_i(:,:,:) >= epsi10 ) ; zs_i(:,:,:) = psv_i(:,:,:) / pv_i(:,:,:)
+      ELSEWHERE                      ; zs_i(:,:,:) = 0._wp
+      END WHERE
+      CALL icemax3D( ph_i , zhi_max )
+      CALL icemax3D( ph_s , zhs_max )
+      CALL icemax3D( ph_ip, zhip_max)
+      CALL icemax3D( zs_i , zsi_max )
+      CALL lbc_lnk_multi( 'icedyn_adv_umx', zhi_max, 'T', 1., zhs_max, 'T', 1., zhip_max, 'T', 1., zsi_max, 'T', 1. )
+
+      ! enthalpies
+      DO jk = 1, nlay_i
+         WHERE( pv_i(:,:,:) >= epsi10 ) ; ze_i(:,:,jk,:) = pe_i(:,:,jk,:) / pv_i(:,:,:)
+         ELSEWHERE                      ; ze_i(:,:,jk,:) = 0._wp
+         END WHERE
+      END DO
+      DO jk = 1, nlay_s
+         WHERE( pv_s(:,:,:) >= epsi10 ) ; ze_s(:,:,jk,:) = pe_s(:,:,jk,:) / pv_s(:,:,:)
+         ELSEWHERE                      ; ze_s(:,:,jk,:) = 0._wp
+         END WHERE
+      END DO   
+      CALL icemax4D( ze_i , zei_max )
+      CALL icemax4D( ze_s , zes_max )
+      CALL lbc_lnk( 'icedyn_adv_umx', zei_max, 'T', 1. )
+      CALL lbc_lnk( 'icedyn_adv_umx', zes_max, 'T', 1. )
+      !
+      ! --- If ice drift is too fast, use  subtime steps for advection (CFL test for stability) --- !
+      !        Note: the advection split is applied at the next time-step in order to avoid blocking global comm.
+      !              this should not affect too much the stability
+      zcflnow(1) =                  MAXVAL( ABS( pu_ice(:,:) ) * rdt_ice * r1_e1u(:,:) )
+      zcflnow(1) = MAX( zcflnow(1), MAXVAL( ABS( pv_ice(:,:) ) * rdt_ice * r1_e2v(:,:) ) )
+      
+      ! non-blocking global communication send zcflnow and receive zcflprv
+      CALL mpp_delay_max( 'icedyn_adv_umx', 'cflice', zcflnow(:), zcflprv(:), kt == nitend - nn_fsbc + 1 )
+
+      IF( zcflprv(1) > .5 ) THEN   ;   icycle = 2
+      ELSE                         ;   icycle = 1
+      ENDIF
+      zdt = rdt_ice / REAL(icycle)
+      z1_dt = 1._wp / zdt
+      
+      ! --- transport --- !
+      zudy(:,:) = pu_ice(:,:) * e2u(:,:)
+      zvdx(:,:) = pv_ice(:,:) * e1v(:,:)
+      !
+      ! setup transport for each ice cat 
+      DO jl = 1, jpl
+         zu_cat(:,:,jl) = zudy(:,:)
+         zv_cat(:,:,jl) = zvdx(:,:)
+      END DO
+      !
+      ! --- define velocity for advection: u*grad(H) --- !
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1
+            IF    ( pu_ice(ji,jj) * pu_ice(ji-1,jj) <= 0._wp ) THEN   ;   zcu_box(ji,jj) = 0._wp
+            ELSEIF( pu_ice(ji,jj)                   >  0._wp ) THEN   ;   zcu_box(ji,jj) = pu_ice(ji-1,jj)
+            ELSE                                                      ;   zcu_box(ji,jj) = pu_ice(ji  ,jj)
+            ENDIF
+
+            IF    ( pv_ice(ji,jj) * pv_ice(ji,jj-1) <= 0._wp ) THEN   ;   zcv_box(ji,jj) = 0._wp
+            ELSEIF( pv_ice(ji,jj)                   >  0._wp ) THEN   ;   zcv_box(ji,jj) = pv_ice(ji,jj-1)
+            ELSE                                                      ;   zcv_box(ji,jj) = pv_ice(ji,jj  )
+            ENDIF
+         END DO
+      END DO
+
+      !---------------!
+      !== advection ==!
+      !---------------!
+      DO jt = 1, icycle
+
+         ! diagnostics
+         zdiag_adv_mass(:,:) =   SUM(  pv_i(:,:,:) , dim=3 ) * rhoi + SUM(  pv_s(:,:,:) , dim=3 ) * rhos
+         zdiag_adv_salt(:,:) =   SUM( psv_i(:,:,:) , dim=3 ) * rhoi
+         zdiag_adv_heat(:,:) = - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
+            &                  - SUM(SUM( pe_s(:,:,1:nlay_s,:) , dim=4 ), dim=3 )
+
+         ! record at_i before advection (for open water)
+         zati1(:,:) = SUM( pa_i(:,:,:), dim=3 )
+         
+         ! inverse of A and Ap
+         WHERE( pa_i(:,:,:) >= epsi20 )   ;   z1_ai(:,:,:) = 1._wp / pa_i(:,:,:)
+         ELSEWHERE                        ;   z1_ai(:,:,:) = 0.
+         END WHERE
+         WHERE( pa_ip(:,:,:) >= epsi20 )  ;   z1_aip(:,:,:) = 1._wp / pa_ip(:,:,:)
+         ELSEWHERE                        ;   z1_aip(:,:,:) = 0.
+         END WHERE
+         !
+         ! setup a mask where advection will be upstream
+         IF( ll_neg ) THEN
+            IF( .NOT. ALLOCATED(imsk_small) )   ALLOCATE( imsk_small(jpi,jpj,jpl) ) 
+            IF( .NOT. ALLOCATED(jmsk_small) )   ALLOCATE( jmsk_small(jpi,jpj,jpl) ) 
+            DO jl = 1, jpl
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zvi_cen = 0.5_wp * ( pv_i(ji+1,jj,jl) + pv_i(ji,jj,jl) )
+                     IF( zvi_cen < epsi06) THEN   ;   imsk_small(ji,jj,jl) = 0
+                     ELSE                         ;   imsk_small(ji,jj,jl) = 1   ;   ENDIF
+                     zvi_cen = 0.5_wp * ( pv_i(ji,jj+1,jl) + pv_i(ji,jj,jl) )
+                     IF( zvi_cen < epsi06) THEN   ;   jmsk_small(ji,jj,jl) = 0
+                     ELSE                         ;   jmsk_small(ji,jj,jl) = 1   ;   ENDIF
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         !
+         ! ----------------------- !
+         ! ==> start advection <== !
+         ! ----------------------- !
+         !
+         !== Ice area ==!
+         zamsk = 1._wp
+         CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy, zvdx, zu_cat , zv_cat , zcu_box, zcv_box, &
+            &                                      pa_i, pa_i, zua_ups, zva_ups, zua_ho , zva_ho )
+         !
+         !                             ! --------------------------------- !
+         IF( np_advS == 1 ) THEN       ! -- advection form: -div( uVS ) -- !
+            !                          ! --------------------------------- !
+            zamsk = 0._wp
+            !== Ice volume ==!
+            zhvar(:,:,:) = pv_i(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_i, zua_ups, zva_ups )
+            !== Snw volume ==!         
+            zhvar(:,:,:) = pv_s(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_s, zua_ups, zva_ups )
+            !
+            zamsk = 1._wp
+            !== Salt content ==!
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zu_cat, zv_cat, zcu_box, zcv_box, &
+               &                                      psv_i, psv_i )
+            !== Ice heat content ==!
+            DO jk = 1, nlay_i
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zu_cat, zv_cat, zcu_box, zcv_box, &
+                  &                                      pe_i(:,:,jk,:), pe_i(:,:,jk,:) )
+            END DO
+            !== Snw heat content ==!
+            DO jk = 1, nlay_s
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zu_cat, zv_cat, zcu_box, zcv_box, &
+                  &                                      pe_s(:,:,jk,:), pe_s(:,:,jk,:) )
+            END DO
+            !
+            !                          ! ------------------------------------------ !
+         ELSEIF( np_advS == 2 ) THEN   ! -- advection form: -div( uA * uHS / u ) -- !
+            !                          ! ------------------------------------------ !
+            zamsk = 0._wp
+            !== Ice volume ==!
+            zhvar(:,:,:) = pv_i(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_i, zua_ups, zva_ups )
+            !== Snw volume ==!         
+            zhvar(:,:,:) = pv_s(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_s, zua_ups, zva_ups )
+            !== Salt content ==!
+            zhvar(:,:,:) = psv_i(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, psv_i, zua_ups, zva_ups )
+            !== Ice heat content ==!
+            DO jk = 1, nlay_i
+               zhvar(:,:,:) = pe_i(:,:,jk,:) * z1_ai(:,:,:)
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho, zva_ho, zcu_box, zcv_box, &
+                  &                                      zhvar, pe_i(:,:,jk,:), zua_ups, zva_ups )
+            END DO
+            !== Snw heat content ==!
+            DO jk = 1, nlay_s
+               zhvar(:,:,:) = pe_s(:,:,jk,:) * z1_ai(:,:,:)
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho, zva_ho, zcu_box, zcv_box, &
+                  &                                      zhvar, pe_s(:,:,jk,:), zua_ups, zva_ups )
+            END DO
+            !
+            !                          ! ----------------------------------------- !
+         ELSEIF( np_advS == 3 ) THEN   ! -- advection form: -div( uV * uS / u ) -- !
+            !                          ! ----------------------------------------- !
+            zamsk = 0._wp
+            !
+            ALLOCATE( zuv_ho (jpi,jpj,jpl), zvv_ho (jpi,jpj,jpl),  &
+               &      zuv_ups(jpi,jpj,jpl), zvv_ups(jpi,jpj,jpl), z1_vi(jpi,jpj,jpl), z1_vs(jpi,jpj,jpl) )
+            !
+            ! inverse of Vi
+            WHERE( pv_i(:,:,:) >= epsi20 )   ;   z1_vi(:,:,:) = 1._wp / pv_i(:,:,:)
+            ELSEWHERE                        ;   z1_vi(:,:,:) = 0.
+            END WHERE
+            ! inverse of Vs
+            WHERE( pv_s(:,:,:) >= epsi20 )   ;   z1_vs(:,:,:) = 1._wp / pv_s(:,:,:)
+            ELSEWHERE                        ;   z1_vs(:,:,:) = 0.
+            END WHERE
+            !
+            ! It is important to first calculate the ice fields and then the snow fields (because we use the same arrays)
+            !
+            !== Ice volume ==!
+            zuv_ups = zua_ups
+            zvv_ups = zva_ups
+            zhvar(:,:,:) = pv_i(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_i, zuv_ups, zvv_ups, zuv_ho , zvv_ho )
+            !== Salt content ==!
+            zhvar(:,:,:) = psv_i(:,:,:) * z1_vi(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zuv_ho , zvv_ho , zcu_box, zcv_box, &
+               &                                      zhvar, psv_i, zuv_ups, zvv_ups )
+            !== Ice heat content ==!
+            DO jk = 1, nlay_i
+               zhvar(:,:,:) = pe_i(:,:,jk,:) * z1_vi(:,:,:)
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zuv_ho, zvv_ho, zcu_box, zcv_box, &
+                  &                                      zhvar, pe_i(:,:,jk,:), zuv_ups, zvv_ups )
+            END DO
+            !== Snow volume ==!         
+            zuv_ups = zua_ups
+            zvv_ups = zva_ups
+            zhvar(:,:,:) = pv_s(:,:,:) * z1_ai(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_s, zuv_ups, zvv_ups, zuv_ho , zvv_ho )
+            !== Snw heat content ==!
+            DO jk = 1, nlay_s
+               zhvar(:,:,:) = pe_s(:,:,jk,:) * z1_vs(:,:,:)
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx, zuv_ho, zvv_ho, zcu_box, zcv_box, &
+                  &                                      zhvar, pe_s(:,:,jk,:), zuv_ups, zvv_ups )
+            END DO
+            !
+            DEALLOCATE( zuv_ho, zvv_ho, zuv_ups, zvv_ups, z1_vi, z1_vs )
+            !
+         ENDIF
+         !
+         !== Ice age ==!
+         zamsk = 1._wp
+         CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zu_cat, zv_cat, zcu_box, zcv_box, &
+            &                                      poa_i, poa_i )
+         !
+         !== melt ponds ==!
+         IF ( ln_pnd_LEV ) THEN
+            ! concentration
+            zamsk = 1._wp
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zu_cat , zv_cat , zcu_box, zcv_box, &
+               &                                      pa_ip, pa_ip, zua_ups, zva_ups, zua_ho , zva_ho )
+            ! volume
+            zamsk = 0._wp
+            zhvar(:,:,:) = pv_ip(:,:,:) * z1_aip(:,:,:)
+            CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zua_ho , zva_ho , zcu_box, zcv_box, &
+               &                                      zhvar, pv_ip, zua_ups, zva_ups )
+            ! lid
+            IF ( ln_pnd_lids ) THEN
+               zamsk = 0._wp
+               zhvar(:,:,:) = pv_il(:,:,:) * z1_aip(:,:,:)
+               CALL adv_umx( zamsk, kn_umx, jt, kt, zdt, zudy , zvdx , zua_ho , zva_ho , zcu_box, zcv_box, &
+                  &                                      zhvar, pv_il, zua_ups, zva_ups )
+            ENDIF
+         ENDIF
+         !
+         ! --- Lateral boundary conditions --- !
+         IF    ( ln_pnd_LEV .AND. ln_pnd_lids ) THEN
+            CALL lbc_lnk_multi( 'icedyn_adv_umx', pa_i,'T',1._wp, pv_i,'T',1._wp, pv_s,'T',1._wp, psv_i,'T',1._wp, poa_i,'T',1._wp &
+               &                                , pa_ip,'T',1._wp, pv_ip,'T',1._wp, pv_il,'T',1._wp )
+         ELSEIF( ln_pnd_LEV .AND. .NOT.ln_pnd_lids ) THEN
+            CALL lbc_lnk_multi( 'icedyn_adv_umx', pa_i,'T',1._wp, pv_i,'T',1._wp, pv_s,'T',1._wp, psv_i,'T',1._wp, poa_i,'T',1._wp &
+               &                                , pa_ip,'T',1._wp, pv_ip,'T',1._wp )
+         ELSE
+            CALL lbc_lnk_multi( 'icedyn_adv_umx', pa_i,'T',1._wp, pv_i,'T',1._wp, pv_s,'T',1._wp, psv_i,'T',1._wp, poa_i,'T',1._wp )
+         ENDIF
+         CALL lbc_lnk( 'icedyn_adv_umx', pe_i, 'T', 1._wp )
+         CALL lbc_lnk( 'icedyn_adv_umx', pe_s, 'T', 1._wp )
+         !
+         !== Open water area ==!
+         zati2(:,:) = SUM( pa_i(:,:,:), dim=3 )
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pato_i(ji,jj) = pato_i(ji,jj) - ( zati2(ji,jj) - zati1(ji,jj) ) & 
+                  &                          - ( zudy(ji,jj) - zudy(ji-1,jj) + zvdx(ji,jj) - zvdx(ji,jj-1) ) * r1_e1e2t(ji,jj) * zdt
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_adv_umx', pato_i, 'T', 1._wp )
+         !
+         ! --- diagnostics --- !
+         diag_adv_mass(:,:) = diag_adv_mass(:,:) + (   SUM( pv_i(:,:,:) , dim=3 ) * rhoi + SUM( pv_s(:,:,:) , dim=3 ) * rhos &
+            &                                        - zdiag_adv_mass(:,:) ) * z1_dt
+         diag_adv_salt(:,:) = diag_adv_salt(:,:) + (   SUM( psv_i(:,:,:) , dim=3 ) * rhoi &
+            &                                        - zdiag_adv_salt(:,:) ) * z1_dt
+         diag_adv_heat(:,:) = diag_adv_heat(:,:) + ( - SUM(SUM( pe_i(:,:,1:nlay_i,:) , dim=4 ), dim=3 ) &
+            &                                        - SUM(SUM( pe_s(:,:,1:nlay_s,:) , dim=4 ), dim=3 ) &
+            &                                        - zdiag_adv_heat(:,:) ) * z1_dt
+         !
+         ! --- Ensure non-negative fields and in-bound thicknesses --- !
+         ! Remove negative values (conservation is ensured)
+         !    (because advected fields are not perfectly bounded and tiny negative values can occur, e.g. -1.e-20)
+         CALL ice_var_zapneg( zdt, pato_i, pv_i, pv_s, psv_i, poa_i, pa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+         !
+         ! --- Make sure ice thickness is not too big --- !
+         !     (because ice thickness can be too large where ice concentration is very small)
+         CALL Hbig( zdt, zhi_max, zhs_max, zhip_max, zsi_max, zes_max, zei_max, &
+            &            pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i, pe_s, pe_i )
+         !
+         ! --- Ensure snow load is not too big --- !
+         CALL Hsnow( zdt, pv_i, pv_s, pa_i, pa_ip, pe_s )
+         !
+      END DO
+      !
+   END SUBROUTINE ice_dyn_adv_umx
+
+   
+   SUBROUTINE adv_umx( pamsk, kn_umx, jt, kt, pdt, pu, pv, puc, pvc, pubox, pvbox,  &
+      &                                            pt, ptc, pua_ups, pva_ups, pua_ho, pva_ho )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE adv_umx  ***
+      !! 
+      !! **  Purpose :   Compute the now trend due to total advection of 
+      !!                 tracers and add it to the general trend of tracer equations
+      !!
+      !! **  Method  :   - calculate upstream fluxes and upstream solution for tracers V/A(=H) etc
+      !!                 - calculate tracer H at u and v points (Ultimate)
+      !!                 - calculate the high order fluxes using alterning directions (Macho)
+      !!                 - apply a limiter on the fluxes (nonosc_ice)
+      !!                 - convert this tracer flux to a "volume" flux (uH -> uV)
+      !!                 - apply a limiter a second time on the volumes fluxes (nonosc_ice)
+      !!                 - calculate the high order solution for V
+      !!
+      !! ** Action : solve 3 equations => a) dA/dt  = -div(uA)
+      !!                                  b) dV/dt  = -div(uV)  using dH/dt = -u.grad(H)
+      !!                                  c) dVS/dt = -div(uVS) using either dHS/dt = -u.grad(HS) or dS/dt = -u.grad(S)
+      !!
+      !!             in eq. b), - fluxes uH are evaluated (with UMx) and limited with nonosc_ice. This step is necessary to get a good H.
+      !!                        - then we convert this flux to a "volume" flux this way => uH * uA / u
+      !!                             where uA is the flux from eq. a)
+      !!                             this "volume" flux is also limited with nonosc_ice (otherwise overshoots can occur)
+      !!                        - at last we estimate dV/dt = -div(uH * uA / u)
+      !!
+      !!             in eq. c), one can solve the equation for  S (ln_advS=T), then dVS/dt = -div(uV * uS  / u)
+      !!                                                or for HS (ln_advS=F), then dVS/dt = -div(uA * uHS / u) 
+      !!
+      !! ** Note : - this method can lead to tiny negative V (-1.e-20) => set it to 0 while conserving mass etc.
+      !!           - At the ice edge, Ultimate scheme can lead to:
+      !!                              1) negative interpolated tracers at u-v points
+      !!                              2) non-zero interpolated tracers at u-v points eventhough there is no ice and velocity is outward
+      !!                              Solution for 1): apply an upstream scheme when it occurs. A better solution would be to degrade the order of
+      !!                                               the scheme automatically by applying a mask of the ice cover inside Ultimate (not done).
+      !!                              Solution for 2): we set it to 0 in this case
+      !!           - Eventhough 1D tests give very good results (typically the one from Schar & Smolarkiewiecz), the 2D is less good.
+      !!             Large values of H can appear for very small ice concentration, and when it does it messes the things up since we
+      !!             work on H (and not V). It is partly related to the multi-category approach
+      !!             Therefore, after advection we limit the thickness to the largest value of the 9-points around (only if ice
+      !!             concentration is small). We also limit S and T.
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   )           ::   pamsk            ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   )           ::   kn_umx           ! order of the scheme (1-5=UM or 20=CEN2)
+      INTEGER                         , INTENT(in   )           ::   jt               ! number of sub-iteration
+      INTEGER                         , INTENT(in   )           ::   kt               ! number of iteration
+      REAL(wp)                        , INTENT(in   )           ::   pdt              ! tracer time-step
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   )           ::   pu   , pv        ! 2 ice velocity components => u*e2
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   )           ::   puc  , pvc       ! 2 ice velocity components => u*e2 or u*a*e2u
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   )           ::   pubox, pvbox     ! upstream velocity
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(inout)           ::   pt               ! tracer field
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(inout)           ::   ptc              ! tracer content field
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(inout), OPTIONAL ::   pua_ups, pva_ups ! upstream u*a fluxes
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out), OPTIONAL ::   pua_ho, pva_ho   ! high order u*a fluxes
+      !
+      INTEGER  ::   ji, jj, jl       ! dummy loop indices  
+      REAL(wp) ::   ztra             ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zfu_ho , zfv_ho , zpt
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zfu_ups, zfv_ups, zt_ups
+      !!----------------------------------------------------------------------
+      !
+      ! Upstream (_ups) fluxes 
+      ! -----------------------
+      CALL upstream( pamsk, jt, kt, pdt, pt, pu, pv, zt_ups, zfu_ups, zfv_ups )
+      
+      ! High order (_ho) fluxes 
+      ! -----------------------
+      SELECT CASE( kn_umx )
+         !
+      CASE ( 20 )                          !== centered second order ==!
+         !
+         CALL cen2( pamsk, jt, kt, pdt, pt, pu, pv, zt_ups, zfu_ups, zfv_ups, zfu_ho, zfv_ho )
+         !
+      CASE ( 1:5 )                         !== 1st to 5th order ULTIMATE-MACHO scheme ==!
+         !
+         CALL macho( pamsk, kn_umx, jt, kt, pdt, pt, pu, pv, pubox, pvbox, zt_ups, zfu_ups, zfv_ups, zfu_ho, zfv_ho )
+         !
+      END SELECT
+      !
+      !              --ho    --ho
+      ! new fluxes = u*H  *  u*a / u
+      ! ----------------------------
+      IF( pamsk == 0._wp ) THEN
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1
+                  IF( ABS( pu(ji,jj) ) > epsi10 ) THEN
+                     zfu_ho (ji,jj,jl) = zfu_ho (ji,jj,jl) * puc    (ji,jj,jl) / pu(ji,jj)
+                     zfu_ups(ji,jj,jl) = zfu_ups(ji,jj,jl) * pua_ups(ji,jj,jl) / pu(ji,jj)
+                  ELSE
+                     zfu_ho (ji,jj,jl) = 0._wp
+                     zfu_ups(ji,jj,jl) = 0._wp
+                  ENDIF
+                  !
+               END DO
+            END DO
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  IF( ABS( pv(ji,jj) ) > epsi10 ) THEN
+                     zfv_ho (ji,jj,jl) = zfv_ho (ji,jj,jl) * pvc    (ji,jj,jl) / pv(ji,jj)
+                     zfv_ups(ji,jj,jl) = zfv_ups(ji,jj,jl) * pva_ups(ji,jj,jl) / pv(ji,jj)
+                  ELSE
+                     zfv_ho (ji,jj,jl) = 0._wp  
+                     zfv_ups(ji,jj,jl) = 0._wp  
+                  ENDIF
+               END DO
+            END DO
+         END DO
+
+         ! the new "volume" fluxes must also be "flux corrected"
+         ! thus we calculate the upstream solution and apply a limiter again
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  ztra = - ( zfu_ups(ji,jj,jl) - zfu_ups(ji-1,jj,jl) + zfv_ups(ji,jj,jl) - zfv_ups(ji,jj-1,jl) )
+                  !
+                  zt_ups(ji,jj,jl) = ( ptc(ji,jj,jl) + ztra * r1_e1e2t(ji,jj) * pdt ) * tmask(ji,jj,1)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_adv_umx', zt_ups, 'T',  1. )
+         !
+         IF    ( np_limiter == 1 ) THEN
+            CALL nonosc_ice( 1._wp, pdt, pu, pv, ptc, zt_ups, zfu_ups, zfv_ups, zfu_ho, zfv_ho )
+         ELSEIF( np_limiter == 2 .OR. np_limiter == 3 ) THEN
+            CALL limiter_x( pdt, pu, ptc, zfu_ups, zfu_ho )
+            CALL limiter_y( pdt, pv, ptc, zfv_ups, zfv_ho )
+         ENDIF
+         !
+      ENDIF
+      !                                   --ho    --ups
+      ! in case of advection of A: output u*a and u*a
+      ! -----------------------------------------------
+      IF( PRESENT( pua_ho ) ) THEN
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1
+                  pua_ho (ji,jj,jl) = zfu_ho (ji,jj,jl)
+                  pua_ups(ji,jj,jl) = zfu_ups(ji,jj,jl)
+              END DO
+            END DO
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  pva_ho (ji,jj,jl) = zfv_ho (ji,jj,jl)
+                  pva_ups(ji,jj,jl) = zfv_ups(ji,jj,jl)
+              END DO
+            END DO
+         END DO
+      ENDIF
+      !
+      ! final trend with corrected fluxes
+      ! ---------------------------------
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1 
+               ztra = - ( zfu_ho(ji,jj,jl) - zfu_ho(ji-1,jj,jl) + zfv_ho(ji,jj,jl) - zfv_ho(ji,jj-1,jl) )  
+               !
+               ptc(ji,jj,jl) = ( ptc(ji,jj,jl) + ztra * r1_e1e2t(ji,jj) * pdt ) * tmask(ji,jj,1)               
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE adv_umx
+
+
+   SUBROUTINE upstream( pamsk, jt, kt, pdt, pt, pu, pv, pt_ups, pfu_ups, pfv_ups )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE upstream  ***
+      !!     
+      !! **  Purpose :   compute the upstream fluxes and upstream guess of tracer
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   ) ::   pamsk            ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   ) ::   jt               ! number of sub-iteration
+      INTEGER                         , INTENT(in   ) ::   kt               ! number of iteration
+      REAL(wp)                        , INTENT(in   ) ::   pdt              ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt               ! tracer fields
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pu, pv           ! 2 ice velocity components
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pt_ups           ! upstream guess of tracer 
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pfu_ups, pfv_ups ! upstream fluxes 
+      !
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp) ::   ztra          ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zpt
+      !!----------------------------------------------------------------------
+
+      IF( .NOT. ll_upsxy ) THEN         !** no alternate directions **!
+         !
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1
+                  pfu_ups(ji,jj,jl) = MAX( pu(ji,jj), 0._wp ) * pt(ji,jj,jl) + MIN( pu(ji,jj), 0._wp ) * pt(ji+1,jj,jl)
+                  pfv_ups(ji,jj,jl) = MAX( pv(ji,jj), 0._wp ) * pt(ji,jj,jl) + MIN( pv(ji,jj), 0._wp ) * pt(ji,jj+1,jl)
+               END DO
+            END DO
+         END DO
+         !
+      ELSE                              !** alternate directions **!
+         !
+         IF( MOD( (kt - 1) / nn_fsbc , 2 ) ==  MOD( (jt - 1) , 2 ) ) THEN   !==  odd ice time step:  adv_x then adv_y  ==!
+            !
+            DO jl = 1, jpl              !-- flux in x-direction
+               DO jj = 1, jpj
+                  DO ji = 1, fs_jpim1
+                     pfu_ups(ji,jj,jl) = MAX( pu(ji,jj), 0._wp ) * pt(ji,jj,jl) + MIN( pu(ji,jj), 0._wp ) * pt(ji+1,jj,jl)
+                  END DO
+               END DO
+            END DO
+            !
+            DO jl = 1, jpl              !-- first guess of tracer from u-flux
+               DO jj = 1, jpj
+                  DO ji = fs_2, fs_jpim1
+                     ztra = - ( pfu_ups(ji,jj,jl) - pfu_ups(ji-1,jj,jl) )              &
+                        &   + ( pu     (ji,jj   ) - pu     (ji-1,jj   ) ) * pt(ji,jj,jl) * (1.-pamsk)
+                     !
+                     zpt(ji,jj,jl) = ( pt(ji,jj,jl) + ztra * pdt * r1_e1e2t(ji,jj) ) * tmask(ji,jj,1)
+                  END DO
+               END DO
+            END DO
+            !
+            DO jl = 1, jpl              !-- flux in y-direction
+               DO jj = 1, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     pfv_ups(ji,jj,jl) = MAX( pv(ji,jj), 0._wp ) * zpt(ji,jj,jl) + MIN( pv(ji,jj), 0._wp ) * zpt(ji,jj+1,jl)
+                  END DO
+               END DO
+            END DO
+            !
+         ELSE                                                               !==  even ice time step:  adv_y then adv_x  ==!
+            !
+            DO jl = 1, jpl              !-- flux in y-direction
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpi
+                     pfv_ups(ji,jj,jl) = MAX( pv(ji,jj), 0._wp ) * pt(ji,jj,jl) + MIN( pv(ji,jj), 0._wp ) * pt(ji,jj+1,jl)
+                  END DO
+               END DO
+            END DO
+            !
+            DO jl = 1, jpl              !-- first guess of tracer from v-flux
+               DO jj = 2, jpjm1
+                  DO ji = 1, jpi
+                     ztra = - ( pfv_ups(ji,jj,jl) - pfv_ups(ji,jj-1,jl) )  &
+                        &   + ( pv     (ji,jj   ) - pv     (ji,jj-1   ) ) * pt(ji,jj,jl) * (1.-pamsk)
+                     !
+                     zpt(ji,jj,jl) = ( pt(ji,jj,jl) + ztra * pdt * r1_e1e2t(ji,jj) ) * tmask(ji,jj,1)
+                  END DO
+               END DO
+            END DO
+            !
+            DO jl = 1, jpl              !-- flux in x-direction
+               DO jj = 2, jpjm1
+                  DO ji = 1, fs_jpim1
+                     pfu_ups(ji,jj,jl) = MAX( pu(ji,jj), 0._wp ) * zpt(ji,jj,jl) + MIN( pu(ji,jj), 0._wp ) * zpt(ji+1,jj,jl)
+                  END DO
+               END DO
+            END DO
+            !
+         ENDIF
+         
+      ENDIF
+      !
+      DO jl = 1, jpl                    !-- after tracer with upstream scheme
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ztra = - (   pfu_ups(ji,jj,jl) - pfu_ups(ji-1,jj  ,jl)   &
+                  &       + pfv_ups(ji,jj,jl) - pfv_ups(ji  ,jj-1,jl) ) &
+                  &   + (   pu     (ji,jj   ) - pu     (ji-1,jj     )   &
+                  &       + pv     (ji,jj   ) - pv     (ji  ,jj-1   ) ) * pt(ji,jj,jl) * (1.-pamsk)
+               !
+               pt_ups(ji,jj,jl) = ( pt(ji,jj,jl) + ztra * pdt * r1_e1e2t(ji,jj) ) * tmask(ji,jj,1)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', pt_ups, 'T', 1. )
+
+   END SUBROUTINE upstream
+
+   
+   SUBROUTINE cen2( pamsk, jt, kt, pdt, pt, pu, pv, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cen2  ***
+      !!     
+      !! **  Purpose :   compute the high order fluxes using a centered
+      !!                 second order scheme 
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   ) ::   pamsk            ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   ) ::   jt               ! number of sub-iteration
+      INTEGER                         , INTENT(in   ) ::   kt               ! number of iteration
+      REAL(wp)                        , INTENT(in   ) ::   pdt              ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt               ! tracer fields
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pu, pv           ! 2 ice velocity components
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt_ups           ! upstream guess of tracer 
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pfu_ups, pfv_ups ! upstream fluxes 
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pfu_ho, pfv_ho   ! high order fluxes 
+      !
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp) ::   ztra          ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zpt
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ll_hoxy ) THEN           !** no alternate directions **!
+         !
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, fs_jpim1
+                  pfu_ho(ji,jj,jl) = 0.5_wp * pu(ji,jj) * ( pt(ji,jj,jl) + pt(ji+1,jj  ,jl) )
+               END DO
+            END DO
+            DO jj = 1, jpjm1
+               DO ji = 1, jpi
+                  pfv_ho(ji,jj,jl) = 0.5_wp * pv(ji,jj) * ( pt(ji,jj,jl) + pt(ji  ,jj+1,jl) )
+               END DO
+            END DO
+         END DO
+         !
+         IF    ( np_limiter == 1 ) THEN
+            CALL nonosc_ice( pamsk, pdt, pu, pv, pt, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+         ELSEIF( np_limiter == 2 .OR. np_limiter == 3 ) THEN
+            CALL limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+            CALL limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+         ENDIF
+         !
+      ELSE                              !** alternate directions **!
+         !
+         IF( MOD( (kt - 1) / nn_fsbc , 2 ) ==  MOD( (jt - 1) , 2 ) ) THEN   !==  odd ice time step:  adv_x then adv_y  ==!
+            !
+            DO jl = 1, jpl              !-- flux in x-direction
+               DO jj = 1, jpj
+                  DO ji = 1, fs_jpim1
+                     pfu_ho(ji,jj,jl) = 0.5_wp * pu(ji,jj) * ( pt(ji,jj,jl) + pt(ji+1,jj,jl) )
+                  END DO
+               END DO
+            END DO
+            IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+
+            DO jl = 1, jpl              !-- first guess of tracer from u-flux
+               DO jj = 1, jpj
+                  DO ji = fs_2, fs_jpim1
+                     ztra = - ( pfu_ho(ji,jj,jl) - pfu_ho(ji-1,jj,jl) )              &
+                        &   + ( pu    (ji,jj   ) - pu    (ji-1,jj   ) ) * pt(ji,jj,jl) * (1.-pamsk)
+                     !
+                     zpt(ji,jj,jl) = ( pt(ji,jj,jl) + ztra * pdt * r1_e1e2t(ji,jj) ) * tmask(ji,jj,1)
+                  END DO
+               END DO
+            END DO
+
+            DO jl = 1, jpl              !-- flux in y-direction
+               DO jj = 1, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     pfv_ho(ji,jj,jl) = 0.5_wp * pv(ji,jj) * ( zpt(ji,jj,jl) + zpt(ji,jj+1,jl) )
+                  END DO
+               END DO
+            END DO
+            IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+
+         ELSE                                                               !==  even ice time step:  adv_y then adv_x  ==!
+            !
+            DO jl = 1, jpl              !-- flux in y-direction
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpi
+                     pfv_ho(ji,jj,jl) = 0.5_wp * pv(ji,jj) * ( pt(ji,jj,jl) + pt(ji,jj+1,jl) )
+                  END DO
+               END DO
+            END DO
+            IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+            !
+            DO jl = 1, jpl              !-- first guess of tracer from v-flux
+               DO jj = 2, jpjm1
+                  DO ji = 1, jpi
+                     ztra = - ( pfv_ho(ji,jj,jl) - pfv_ho(ji,jj-1,jl) )  &
+                        &   + ( pv    (ji,jj   ) - pv    (ji,jj-1   ) ) * pt(ji,jj,jl) * (1.-pamsk)
+                     !
+                     zpt(ji,jj,jl) = ( pt(ji,jj,jl) + ztra * pdt * r1_e1e2t(ji,jj) ) * tmask(ji,jj,1)
+                  END DO
+               END DO
+            END DO
+            !
+            DO jl = 1, jpl              !-- flux in x-direction
+               DO jj = 2, jpjm1
+                  DO ji = 1, fs_jpim1
+                     pfu_ho(ji,jj,jl) = 0.5_wp * pu(ji,jj) * ( zpt(ji,jj,jl) + zpt(ji+1,jj,jl) )
+                  END DO
+               END DO
+            END DO
+            IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+
+         ENDIF
+         IF( np_limiter == 1 )   CALL nonosc_ice( pamsk, pdt, pu, pv, pt, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+         
+      ENDIF
+   
+   END SUBROUTINE cen2
+
+   
+   SUBROUTINE macho( pamsk, kn_umx, jt, kt, pdt, pt, pu, pv, pubox, pvbox, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE macho  ***
+      !!     
+      !! **  Purpose :   compute the high order fluxes using Ultimate-Macho scheme  
+      !!
+      !! **  Method  :   ...
+      !!
+      !! Reference : Leonard, B.P., 1991, Comput. Methods Appl. Mech. Eng., 88, 17-74. 
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   ) ::   pamsk            ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   ) ::   kn_umx           ! order of the scheme (1-5=UM or 20=CEN2)
+      INTEGER                         , INTENT(in   ) ::   jt               ! number of sub-iteration
+      INTEGER                         , INTENT(in   ) ::   kt               ! number of iteration
+      REAL(wp)                        , INTENT(in   ) ::   pdt              ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt               ! tracer fields
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pu, pv           ! 2 ice velocity components
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pubox, pvbox     ! upstream velocity
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt_ups           ! upstream guess of tracer 
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pfu_ups, pfv_ups ! upstream fluxes 
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pfu_ho, pfv_ho   ! high order fluxes 
+      !
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zt_u, zt_v, zpt
+      !!----------------------------------------------------------------------
+      !
+      IF( MOD( (kt - 1) / nn_fsbc , 2 ) ==  MOD( (jt - 1) , 2 ) ) THEN   !==  odd ice time step:  adv_x then adv_y  ==!
+         !
+         !                                                        !--  ultimate interpolation of pt at u-point  --!
+         CALL ultimate_x( pamsk, kn_umx, pdt, pt, pu, zt_u, pfu_ho )
+         !                                                        !--  limiter in x --!
+         IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+         !                                                        !--  advective form update in zpt  --!
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zpt(ji,jj,jl) = ( pt(ji,jj,jl) - (  pubox(ji,jj   ) * ( zt_u(ji,jj,jl) - zt_u(ji-1,jj,jl) ) * r1_e1t  (ji,jj) &
+                     &                              + pt   (ji,jj,jl) * ( pu  (ji,jj   ) - pu  (ji-1,jj   ) ) * r1_e1e2t(ji,jj) &
+                     &                                                                                        * pamsk           &
+                     &                             ) * pdt ) * tmask(ji,jj,1)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_adv_umx', zpt, 'T', 1. )
+         !
+         !                                                        !--  ultimate interpolation of pt at v-point  --!
+         IF( ll_hoxy ) THEN
+            CALL ultimate_y( pamsk, kn_umx, pdt, zpt, pv, zt_v, pfv_ho )
+         ELSE
+            CALL ultimate_y( pamsk, kn_umx, pdt, pt , pv, zt_v, pfv_ho )
+         ENDIF
+         !                                                        !--  limiter in y --!
+         IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+         !         
+         !
+      ELSE                                                               !==  even ice time step:  adv_y then adv_x  ==!
+         !
+         !                                                        !--  ultimate interpolation of pt at v-point  --!
+         CALL ultimate_y( pamsk, kn_umx, pdt, pt, pv, zt_v, pfv_ho )
+         !                                                        !--  limiter in y --!
+         IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+         !                                                        !--  advective form update in zpt  --!
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zpt(ji,jj,jl) = ( pt(ji,jj,jl) - (  pvbox(ji,jj   ) * ( zt_v(ji,jj,jl) - zt_v(ji,jj-1,jl) ) * r1_e2t  (ji,jj) &
+                     &                              + pt   (ji,jj,jl) * ( pv  (ji,jj   ) - pv  (ji,jj-1   ) ) * r1_e1e2t(ji,jj) &
+                     &                                                                                        * pamsk           &
+                     &                             ) * pdt ) * tmask(ji,jj,1) 
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_adv_umx', zpt, 'T', 1. )
+         !
+         !                                                        !--  ultimate interpolation of pt at u-point  --!
+         IF( ll_hoxy ) THEN
+            CALL ultimate_x( pamsk, kn_umx, pdt, zpt, pu, zt_u, pfu_ho )
+         ELSE
+            CALL ultimate_x( pamsk, kn_umx, pdt, pt , pu, zt_u, pfu_ho )
+         ENDIF
+         !                                                        !--  limiter in x --!
+         IF( np_limiter == 2 .OR. np_limiter == 3 )   CALL limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+         !
+      ENDIF
+
+      IF( np_limiter == 1 )   CALL nonosc_ice( pamsk, pdt, pu, pv, pt, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+      !
+   END SUBROUTINE macho
+
+
+   SUBROUTINE ultimate_x( pamsk, kn_umx, pdt, pt, pu, pt_u, pfu_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE ultimate_x  ***
+      !!     
+      !! **  Purpose :   compute tracer at u-points 
+      !!
+      !! **  Method  :   ...
+      !!
+      !! Reference : Leonard, B.P., 1991, Comput. Methods Appl. Mech. Eng., 88, 17-74. 
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   ) ::   pamsk     ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   ) ::   kn_umx    ! order of the scheme (1-5=UM or 20=CEN2)
+      REAL(wp)                        , INTENT(in   ) ::   pdt       ! tracer time-step
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pu        ! ice i-velocity component
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt        ! tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pt_u      ! tracer at u-point 
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pfu_ho    ! high order flux 
+      !
+      INTEGER  ::   ji, jj, jl             ! dummy loop indices
+      REAL(wp) ::   zcu, zdx2, zdx4        !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   ztu1, ztu2, ztu3, ztu4
+      !!----------------------------------------------------------------------
+      !
+      !                                                     !--  Laplacian in i-direction  --!
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1         ! First derivative (gradient)
+            DO ji = 1, fs_jpim1
+               ztu1(ji,jj,jl) = ( pt(ji+1,jj,jl) - pt(ji,jj,jl) ) * r1_e1u(ji,jj) * umask(ji,jj,1)
+            END DO
+            !                     ! Second derivative (Laplacian)
+            DO ji = fs_2, fs_jpim1
+               ztu2(ji,jj,jl) = ( ztu1(ji,jj,jl) - ztu1(ji-1,jj,jl) ) * r1_e1t(ji,jj)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', ztu2, 'T', 1. )
+      !
+      !                                                     !--  BiLaplacian in i-direction  --!
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1         ! Third derivative
+            DO ji = 1, fs_jpim1
+               ztu3(ji,jj,jl) = ( ztu2(ji+1,jj,jl) - ztu2(ji,jj,jl) ) * r1_e1u(ji,jj) * umask(ji,jj,1)
+            END DO
+            !                     ! Fourth derivative
+            DO ji = fs_2, fs_jpim1
+               ztu4(ji,jj,jl) = ( ztu3(ji,jj,jl) - ztu3(ji-1,jj,jl) ) * r1_e1t(ji,jj)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', ztu4, 'T', 1. )
+      !
+      !
+      SELECT CASE (kn_umx )
+      !
+      CASE( 1 )                                                   !==  1st order central TIM  ==! (Eq. 21)
+         !        
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (                                pt(ji+1,jj,jl) + pt(ji,jj,jl)   &
+                     &                                         - SIGN( 1._wp, pu(ji,jj) ) * ( pt(ji+1,jj,jl) - pt(ji,jj,jl) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 2 )                                                   !==  2nd order central TIM  ==! (Eq. 23)
+         !
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zcu  = pu(ji,jj) * r1_e2u(ji,jj) * pdt * r1_e1u(ji,jj)
+                  pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (                                pt(ji+1,jj,jl) + pt(ji,jj,jl)   &
+                     &                                                            - zcu   * ( pt(ji+1,jj,jl) - pt(ji,jj,jl) ) ) 
+               END DO
+            END DO
+         END DO
+         !  
+      CASE( 3 )                                                   !==  3rd order central TIM  ==! (Eq. 24)
+         !
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zcu  = pu(ji,jj) * r1_e2u(ji,jj) * pdt * r1_e1u(ji,jj)
+                  zdx2 = e1u(ji,jj) * e1u(ji,jj)
+!!rachid          zdx2 = e1u(ji,jj) * e1t(ji,jj)
+                  pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (         (                      pt  (ji+1,jj,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcu   * ( pt  (ji+1,jj,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6 * zdx2 * ( zcu*zcu - 1._wp ) *    (                      ztu2(ji+1,jj,jl) + ztu2(ji,jj,jl)     &
+                     &                                               - SIGN( 1._wp, zcu ) * ( ztu2(ji+1,jj,jl) - ztu2(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 4 )                                                   !==  4th order central TIM  ==! (Eq. 27)
+         !
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zcu  = pu(ji,jj) * r1_e2u(ji,jj) * pdt * r1_e1u(ji,jj)
+                  zdx2 = e1u(ji,jj) * e1u(ji,jj)
+!!rachid          zdx2 = e1u(ji,jj) * e1t(ji,jj)
+                  pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (         (                      pt  (ji+1,jj,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcu   * ( pt  (ji+1,jj,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6 * zdx2 * ( zcu*zcu - 1._wp ) *    (                      ztu2(ji+1,jj,jl) + ztu2(ji,jj,jl)     &
+                     &                                                   - 0.5_wp * zcu   * ( ztu2(ji+1,jj,jl) - ztu2(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 5 )                                                   !==  5th order central TIM  ==! (Eq. 29)
+         !
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zcu  = pu(ji,jj) * r1_e2u(ji,jj) * pdt * r1_e1u(ji,jj)
+                  zdx2 = e1u(ji,jj) * e1u(ji,jj)
+!!rachid          zdx2 = e1u(ji,jj) * e1t(ji,jj)
+                  zdx4 = zdx2 * zdx2
+                  pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (        (                       pt  (ji+1,jj,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcu   * ( pt  (ji+1,jj,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6   * zdx2 * ( zcu*zcu - 1._wp ) * (                       ztu2(ji+1,jj,jl) + ztu2(ji,jj,jl)     &
+                     &                                                   - 0.5_wp * zcu   * ( ztu2(ji+1,jj,jl) - ztu2(ji,jj,jl) ) ) &
+                     &        + z1_120 * zdx4 * ( zcu*zcu - 1._wp ) * ( zcu*zcu - 4._wp ) * ( ztu4(ji+1,jj,jl) + ztu4(ji,jj,jl)     &
+                     &                                               - SIGN( 1._wp, zcu ) * ( ztu4(ji+1,jj,jl) - ztu4(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      ! if pt at u-point is negative then use the upstream value
+      !    this should not be necessary if a proper sea-ice mask is set in Ultimate
+      !    to degrade the order of the scheme when necessary (for ex. at the ice edge)
+      IF( ll_neg ) THEN
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = 1, fs_jpim1
+                  IF( pt_u(ji,jj,jl) < 0._wp .OR. ( imsk_small(ji,jj,jl) == 0 .AND. pamsk == 0. ) ) THEN
+                     pt_u(ji,jj,jl) = 0.5_wp * umask(ji,jj,1) * (                                pt(ji+1,jj,jl) + pt(ji,jj,jl)   &
+                        &                                         - SIGN( 1._wp, pu(ji,jj) ) * ( pt(ji+1,jj,jl) - pt(ji,jj,jl) ) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !                                                     !-- High order flux in i-direction  --!
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               pfu_ho(ji,jj,jl) = pu(ji,jj) * pt_u(ji,jj,jl)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE ultimate_x
+   
+ 
+   SUBROUTINE ultimate_y( pamsk, kn_umx, pdt, pt, pv, pt_v, pfv_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE ultimate_y  ***
+      !!     
+      !! **  Purpose :   compute tracer at v-points 
+      !!
+      !! **  Method  :   ...
+      !!
+      !! Reference : Leonard, B.P., 1991, Comput. Methods Appl. Mech. Eng., 88, 17-74. 
+      !!----------------------------------------------------------------------
+      REAL(wp)                        , INTENT(in   ) ::   pamsk     ! advection of concentration (1) or other tracers (0)
+      INTEGER                         , INTENT(in   ) ::   kn_umx    ! order of the scheme (1-5=UM or 20=CEN2)
+      REAL(wp)                        , INTENT(in   ) ::   pdt       ! tracer time-step
+      REAL(wp), DIMENSION(:,:  )      , INTENT(in   ) ::   pv        ! ice j-velocity component
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in   ) ::   pt        ! tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pt_v      ! tracer at v-point 
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   pfv_ho    ! high order flux 
+      !
+      INTEGER  ::   ji, jj, jl         ! dummy loop indices
+      REAL(wp) ::   zcv, zdy2, zdy4    !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   ztv1, ztv2, ztv3, ztv4
+      !!----------------------------------------------------------------------
+      !
+      !                                                     !--  Laplacian in j-direction  --!
+      DO jl = 1, jpl
+         DO jj = 1, jpjm1         ! First derivative (gradient)
+            DO ji = fs_2, fs_jpim1
+               ztv1(ji,jj,jl) = ( pt(ji,jj+1,jl) - pt(ji,jj,jl) ) * r1_e2v(ji,jj) * vmask(ji,jj,1)
+            END DO
+         END DO
+         DO jj = 2, jpjm1         ! Second derivative (Laplacian)
+            DO ji = fs_2, fs_jpim1
+               ztv2(ji,jj,jl) = ( ztv1(ji,jj,jl) - ztv1(ji,jj-1,jl) ) * r1_e2t(ji,jj)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', ztv2, 'T', 1. )
+      !
+      !                                                     !--  BiLaplacian in j-direction  --!
+      DO jl = 1, jpl
+         DO jj = 1, jpjm1         ! First derivative
+            DO ji = fs_2, fs_jpim1
+               ztv3(ji,jj,jl) = ( ztv2(ji,jj+1,jl) - ztv2(ji,jj,jl) ) * r1_e2v(ji,jj) * vmask(ji,jj,1)
+            END DO
+         END DO
+         DO jj = 2, jpjm1         ! Second derivative
+            DO ji = fs_2, fs_jpim1
+               ztv4(ji,jj,jl) = ( ztv3(ji,jj,jl) - ztv3(ji,jj-1,jl) ) * r1_e2t(ji,jj)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', ztv4, 'T', 1. )
+      !
+      !
+      SELECT CASE (kn_umx )
+         !
+      CASE( 1 )                                                !==  1st order central TIM  ==! (Eq. 21)
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (                                pt(ji,jj+1,jl) + pt(ji,jj,jl)   &
+                     &                                         - SIGN( 1._wp, pv(ji,jj) ) * ( pt(ji,jj+1,jl) - pt(ji,jj,jl) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 2 )                                                !==  2nd order central TIM  ==! (Eq. 23)
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zcv  = pv(ji,jj) * r1_e1v(ji,jj) * pdt * r1_e2v(ji,jj)
+                  pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (                                pt(ji,jj+1,jl) + pt(ji,jj,jl)   &
+                     &                                                            - zcv *   ( pt(ji,jj+1,jl) - pt(ji,jj,jl) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 3 )                                                !==  3rd order central TIM  ==! (Eq. 24)
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zcv  = pv(ji,jj) * r1_e1v(ji,jj) * pdt * r1_e2v(ji,jj)
+                  zdy2 = e2v(ji,jj) * e2v(ji,jj)
+!!rachid          zdy2 = e2v(ji,jj) * e2t(ji,jj)
+                  pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (      (                         pt  (ji,jj+1,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcv   * ( pt  (ji,jj+1,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6 * zdy2 * ( zcv*zcv - 1._wp ) * (                         ztv2(ji,jj+1,jl) + ztv2(ji,jj,jl)     &
+                     &                                               - SIGN( 1._wp, zcv ) * ( ztv2(ji,jj+1,jl) - ztv2(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 4 )                                                !==  4th order central TIM  ==! (Eq. 27)
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zcv  = pv(ji,jj) * r1_e1v(ji,jj) * pdt * r1_e2v(ji,jj)
+                  zdy2 = e2v(ji,jj) * e2v(ji,jj)
+!!rachid          zdy2 = e2v(ji,jj) * e2t(ji,jj)
+                  pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (      (                         pt  (ji,jj+1,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcv   * ( pt  (ji,jj+1,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6 * zdy2 * ( zcv*zcv - 1._wp ) * (                         ztv2(ji,jj+1,jl) + ztv2(ji,jj,jl)     &
+                     &                                                   - 0.5_wp * zcv   * ( ztv2(ji,jj+1,jl) - ztv2(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 5 )                                                !==  5th order central TIM  ==! (Eq. 29)
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zcv  = pv(ji,jj) * r1_e1v(ji,jj) * pdt * r1_e2v(ji,jj)
+                  zdy2 = e2v(ji,jj) * e2v(ji,jj)
+!!rachid          zdy2 = e2v(ji,jj) * e2t(ji,jj)
+                  zdy4 = zdy2 * zdy2
+                  pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (                              ( pt  (ji,jj+1,jl) + pt  (ji,jj,jl)     &
+                     &                                                            - zcv   * ( pt  (ji,jj+1,jl) - pt  (ji,jj,jl) ) ) &
+                     &        + z1_6   * zdy2 * ( zcv*zcv - 1._wp ) * (                       ztv2(ji,jj+1,jl) + ztv2(ji,jj,jl)     &
+                     &                                                   - 0.5_wp * zcv   * ( ztv2(ji,jj+1,jl) - ztv2(ji,jj,jl) ) ) &
+                     &        + z1_120 * zdy4 * ( zcv*zcv - 1._wp ) * ( zcv*zcv - 4._wp ) * ( ztv4(ji,jj+1,jl) + ztv4(ji,jj,jl)     &
+                     &                                               - SIGN( 1._wp, zcv ) * ( ztv4(ji,jj+1,jl) - ztv4(ji,jj,jl) ) ) )
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      ! if pt at v-point is negative then use the upstream value
+      !    this should not be necessary if a proper sea-ice mask is set in Ultimate
+      !    to degrade the order of the scheme when necessary (for ex. at the ice edge)
+      IF( ll_neg ) THEN
+         DO jl = 1, jpl
+            DO jj = 1, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  IF( pt_v(ji,jj,jl) < 0._wp .OR. ( jmsk_small(ji,jj,jl) == 0 .AND. pamsk == 0. ) ) THEN
+                     pt_v(ji,jj,jl) = 0.5_wp * vmask(ji,jj,1) * (                              ( pt(ji,jj+1,jl) + pt(ji,jj,jl) )  &
+                        &                                         - SIGN( 1._wp, pv(ji,jj) ) * ( pt(ji,jj+1,jl) - pt(ji,jj,jl) ) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !                                                     !-- High order flux in j-direction  --!
+      DO jl = 1, jpl
+         DO jj = 1, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pfv_ho(ji,jj,jl) = pv(ji,jj) * pt_v(ji,jj,jl)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE ultimate_y
+     
+
+   SUBROUTINE nonosc_ice( pamsk, pdt, pu, pv, pt, pt_ups, pfu_ups, pfv_ups, pfu_ho, pfv_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE nonosc_ice  ***
+      !!     
+      !! **  Purpose :   compute monotonic tracer fluxes from the upstream 
+      !!       scheme and the before field by a non-oscillatory algorithm 
+      !!
+      !! **  Method  :   ...
+      !!----------------------------------------------------------------------
+      REAL(wp)                   , INTENT(in   ) ::   pamsk            ! advection of concentration (1) or other tracers (0)
+      REAL(wp)                   , INTENT(in   ) ::   pdt              ! tracer time-step
+      REAL(wp), DIMENSION (:,:  ), INTENT(in   ) ::   pu               ! ice i-velocity => u*e2
+      REAL(wp), DIMENSION (:,:  ), INTENT(in   ) ::   pv               ! ice j-velocity => v*e1
+      REAL(wp), DIMENSION (:,:,:), INTENT(in   ) ::   pt, pt_ups       ! before field & upstream guess of after field
+      REAL(wp), DIMENSION (:,:,:), INTENT(in   ) ::   pfv_ups, pfu_ups ! upstream flux
+      REAL(wp), DIMENSION (:,:,:), INTENT(inout) ::   pfv_ho, pfu_ho   ! monotonic flux
+      !
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp) ::   zpos, zneg, zbig, zup, zdo, z1_dt              ! local scalars
+      REAL(wp) ::   zau, zbu, zcu, zav, zbv, zcv, zcoef, zzt       !   -      -
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zbup, zbdo
+      REAL(wp), DIMENSION(jpi,jpj,jpl) :: zbetup, zbetdo, zti_ups, ztj_ups
+      !!----------------------------------------------------------------------
+      zbig = 1.e+40_wp
+      
+      ! antidiffusive flux : high order minus low order
+      ! --------------------------------------------------
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               pfu_ho(ji,jj,jl) = pfu_ho(ji,jj,jl) - pfu_ups(ji,jj,jl)
+            END DO
+         END DO
+         DO jj = 1, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               pfv_ho(ji,jj,jl) = pfv_ho(ji,jj,jl) - pfv_ups(ji,jj,jl)
+            END DO
+         END DO
+      END DO
+
+      ! extreme case where pfu_ho has to be zero
+      ! ----------------------------------------
+      !                                    pfu_ho
+      !                           *         --->
+      !                        |      |  *   |        | 
+      !                        |      |      |    *   |    
+      !                        |      |      |        |    *
+      !            t_ups :       i-1     i       i+1       i+2   
+      IF( ll_prelim ) THEN
+         
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1 
+                  zti_ups(ji,jj,jl)= pt_ups(ji+1,jj  ,jl)
+                  ztj_ups(ji,jj,jl)= pt_ups(ji  ,jj+1,jl)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'icedyn_adv_umx', zti_ups, 'T', 1., ztj_ups, 'T', 1. )
+
+         DO jl = 1, jpl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  IF ( pfu_ho(ji,jj,jl) * ( pt_ups(ji+1,jj  ,jl) - pt_ups(ji,jj,jl) ) <= 0._wp .AND.  &
+                     & pfv_ho(ji,jj,jl) * ( pt_ups(ji  ,jj+1,jl) - pt_ups(ji,jj,jl) ) <= 0._wp ) THEN
+                     !
+                     IF(  pfu_ho(ji,jj,jl) * ( zti_ups(ji+1,jj  ,jl) - zti_ups(ji,jj,jl) ) <= 0._wp .AND.  &
+                        & pfv_ho(ji,jj,jl) * ( ztj_ups(ji  ,jj+1,jl) - ztj_ups(ji,jj,jl) ) <= 0._wp ) THEN
+                        pfu_ho(ji,jj,jl)=0._wp
+                        pfv_ho(ji,jj,jl)=0._wp
+                     ENDIF
+                     !
+                     IF(  pfu_ho(ji,jj,jl) * ( pt_ups(ji,jj,jl) - pt_ups(ji-1,jj  ,jl) ) <= 0._wp .AND.  &
+                        & pfv_ho(ji,jj,jl) * ( pt_ups(ji,jj,jl) - pt_ups(ji  ,jj-1,jl) ) <= 0._wp ) THEN
+                        pfu_ho(ji,jj,jl)=0._wp
+                        pfv_ho(ji,jj,jl)=0._wp
+                     ENDIF
+                     !
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'icedyn_adv_umx', pfu_ho, 'U', -1., pfv_ho, 'V', -1. )   ! lateral boundary cond.
+
+      ENDIF
+
+      ! Search local extrema
+      ! --------------------
+      ! max/min of pt & pt_ups with large negative/positive value (-/+zbig) outside ice cover
+      z1_dt = 1._wp / pdt
+      DO jl = 1, jpl
+         
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF    ( pt(ji,jj,jl) <= 0._wp .AND. pt_ups(ji,jj,jl) <= 0._wp ) THEN
+                  zbup(ji,jj) = -zbig
+                  zbdo(ji,jj) =  zbig
+               ELSEIF( pt(ji,jj,jl) <= 0._wp .AND. pt_ups(ji,jj,jl) > 0._wp ) THEN
+                  zbup(ji,jj) = pt_ups(ji,jj,jl)
+                  zbdo(ji,jj) = pt_ups(ji,jj,jl)
+               ELSEIF( pt(ji,jj,jl) > 0._wp .AND. pt_ups(ji,jj,jl) <= 0._wp ) THEN
+                  zbup(ji,jj) = pt(ji,jj,jl)
+                  zbdo(ji,jj) = pt(ji,jj,jl)
+               ELSE
+                  zbup(ji,jj) = MAX( pt(ji,jj,jl) , pt_ups(ji,jj,jl) )
+                  zbdo(ji,jj) = MIN( pt(ji,jj,jl) , pt_ups(ji,jj,jl) )
+               ENDIF
+            END DO
+         END DO
+
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               !
+               zup  = MAX( zbup(ji,jj), zbup(ji-1,jj), zbup(ji+1,jj), zbup(ji,jj-1), zbup(ji,jj+1) )  ! search max/min in neighbourhood
+               zdo  = MIN( zbdo(ji,jj), zbdo(ji-1,jj), zbdo(ji+1,jj), zbdo(ji,jj-1), zbdo(ji,jj+1) )
+               !
+               zpos = MAX( 0._wp, pfu_ho(ji-1,jj  ,jl) ) - MIN( 0._wp, pfu_ho(ji  ,jj  ,jl) ) &  ! positive/negative part of the flux
+                  & + MAX( 0._wp, pfv_ho(ji  ,jj-1,jl) ) - MIN( 0._wp, pfv_ho(ji  ,jj  ,jl) )
+               zneg = MAX( 0._wp, pfu_ho(ji  ,jj  ,jl) ) - MIN( 0._wp, pfu_ho(ji-1,jj  ,jl) ) &
+                  & + MAX( 0._wp, pfv_ho(ji  ,jj  ,jl) ) - MIN( 0._wp, pfv_ho(ji  ,jj-1,jl) )
+               !
+               zpos = zpos - (pt(ji,jj,jl) * MIN( 0., pu(ji,jj) - pu(ji-1,jj) ) + pt(ji,jj,jl) * MIN( 0., pv(ji,jj) - pv(ji,jj-1) ) &
+                  &          ) * ( 1. - pamsk )
+               zneg = zneg + (pt(ji,jj,jl) * MAX( 0., pu(ji,jj) - pu(ji-1,jj) ) + pt(ji,jj,jl) * MAX( 0., pv(ji,jj) - pv(ji,jj-1) ) &
+                  &          ) * ( 1. - pamsk )
+               !
+               !                                  ! up & down beta terms
+               ! clem: zbetup and zbetdo must be 0 for zpos>1.e-10 & zneg>1.e-10 (do not put 0 instead of 1.e-10 !!!)
+               IF( zpos > epsi10 ) THEN ; zbetup(ji,jj,jl) = MAX( 0._wp, zup - pt_ups(ji,jj,jl) ) / zpos * e1e2t(ji,jj) * z1_dt
+               ELSE                     ; zbetup(ji,jj,jl) = 0._wp ! zbig
+               ENDIF
+               !
+               IF( zneg > epsi10 ) THEN ; zbetdo(ji,jj,jl) = MAX( 0._wp, pt_ups(ji,jj,jl) - zdo ) / zneg * e1e2t(ji,jj) * z1_dt
+               ELSE                     ; zbetdo(ji,jj,jl) = 0._wp ! zbig
+               ENDIF
+               !
+               ! if all the points are outside ice cover
+               IF( zup == -zbig )   zbetup(ji,jj,jl) = 0._wp ! zbig
+               IF( zdo ==  zbig )   zbetdo(ji,jj,jl) = 0._wp ! zbig            
+               !
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'icedyn_adv_umx', zbetup, 'T', 1., zbetdo, 'T', 1. )   ! lateral boundary cond. (unchanged sign)
+
+      
+      ! monotonic flux in the y direction
+      ! ---------------------------------
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zau = MIN( 1._wp , zbetdo(ji,jj,jl) , zbetup(ji+1,jj,jl) )
+               zbu = MIN( 1._wp , zbetup(ji,jj,jl) , zbetdo(ji+1,jj,jl) )
+               zcu = 0.5_wp + SIGN( 0.5_wp , pfu_ho(ji,jj,jl) )
+               !
+               zcoef = ( zcu * zau + ( 1._wp - zcu ) * zbu )
+               !
+               pfu_ho(ji,jj,jl) = pfu_ho(ji,jj,jl) * zcoef + pfu_ups(ji,jj,jl)
+               !
+            END DO
+         END DO
+
+         DO jj = 1, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zav = MIN( 1._wp , zbetdo(ji,jj,jl) , zbetup(ji,jj+1,jl) )
+               zbv = MIN( 1._wp , zbetup(ji,jj,jl) , zbetdo(ji,jj+1,jl) )
+               zcv = 0.5_wp + SIGN( 0.5_wp , pfv_ho(ji,jj,jl) )
+               !
+               zcoef = ( zcv * zav + ( 1._wp - zcv ) * zbv )
+               !
+               pfv_ho(ji,jj,jl) = pfv_ho(ji,jj,jl) * zcoef + pfv_ups(ji,jj,jl)
+               !
+            END DO
+         END DO
+
+      END DO
+      !
+   END SUBROUTINE nonosc_ice
+
+   
+   SUBROUTINE limiter_x( pdt, pu, pt, pfu_ups, pfu_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE limiter_x  ***
+      !!     
+      !! **  Purpose :   compute flux limiter 
+      !!----------------------------------------------------------------------
+      REAL(wp)                  , INTENT(in   ) ::   pdt          ! tracer time-step
+      REAL(wp), DIMENSION(:,:  ), INTENT(in   ) ::   pu           ! ice i-velocity => u*e2
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pt           ! ice tracer
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pfu_ups      ! upstream flux
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pfu_ho       ! high order flux
+      !
+      REAL(wp) ::   Cr, Rjm, Rj, Rjp, uCFL, zpsi, zh3, zlimiter, Rr
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp), DIMENSION (jpi,jpj,jpl) ::   zslpx       ! tracer slopes 
+      !!----------------------------------------------------------------------
+      !
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zslpx(ji,jj,jl) = ( pt(ji+1,jj,jl) - pt(ji,jj,jl) ) * umask(ji,jj,1)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', zslpx, 'U', -1.)   ! lateral boundary cond.
+      
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               uCFL = pdt * ABS( pu(ji,jj) ) * r1_e1e2t(ji,jj)
+               
+               Rjm = zslpx(ji-1,jj,jl)
+               Rj  = zslpx(ji  ,jj,jl)
+               Rjp = zslpx(ji+1,jj,jl)
+
+               IF( np_limiter == 3 ) THEN
+
+                  IF( pu(ji,jj) > 0. ) THEN   ;   Rr = Rjm
+                  ELSE                        ;   Rr = Rjp
+                  ENDIF
+
+                  zh3 = pfu_ho(ji,jj,jl) - pfu_ups(ji,jj,jl)     
+                  IF( Rj > 0. ) THEN
+                     zlimiter =  MAX( 0., MIN( zh3, MAX(-Rr * 0.5 * ABS(pu(ji,jj)),  &
+                        &        MIN( 2. * Rr * 0.5 * ABS(pu(ji,jj)),  zh3,  1.5 * Rj * 0.5 * ABS(pu(ji,jj)) ) ) ) )
+                  ELSE
+                     zlimiter = -MAX( 0., MIN(-zh3, MAX( Rr * 0.5 * ABS(pu(ji,jj)),  &
+                        &        MIN(-2. * Rr * 0.5 * ABS(pu(ji,jj)), -zh3, -1.5 * Rj * 0.5 * ABS(pu(ji,jj)) ) ) ) )
+                  ENDIF
+                  pfu_ho(ji,jj,jl) = pfu_ups(ji,jj,jl) + zlimiter
+
+               ELSEIF( np_limiter == 2 ) THEN
+                  IF( Rj /= 0. ) THEN
+                     IF( pu(ji,jj) > 0. ) THEN   ;   Cr = Rjm / Rj
+                     ELSE                        ;   Cr = Rjp / Rj
+                     ENDIF
+                  ELSE
+                     Cr = 0.
+                  ENDIF
+
+                  ! -- superbee --
+                  zpsi = MAX( 0., MAX( MIN(1.,2.*Cr), MIN(2.,Cr) ) )
+                  ! -- van albada 2 --
+                  !!zpsi = 2.*Cr / (Cr*Cr+1.)
+                  ! -- sweby (with beta=1) --
+                  !!zpsi = MAX( 0., MAX( MIN(1.,1.*Cr), MIN(1.,Cr) ) )
+                  ! -- van Leer --
+                  !!zpsi = ( Cr + ABS(Cr) ) / ( 1. + ABS(Cr) )
+                  ! -- ospre --
+                  !!zpsi = 1.5 * ( Cr*Cr + Cr ) / ( Cr*Cr + Cr + 1. )
+                  ! -- koren --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( (1.+2*Cr)/3., 2. ) ) )
+                  ! -- charm --
+                  !IF( Cr > 0. ) THEN   ;   zpsi = Cr * (3.*Cr + 1.) / ( (Cr + 1.) * (Cr + 1.) )
+                  !ELSE                 ;   zpsi = 0.
+                  !ENDIF
+                  ! -- van albada 1 --
+                  !!zpsi = (Cr*Cr + Cr) / (Cr*Cr +1)
+                  ! -- smart --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( 0.25+0.75*Cr, 4. ) ) )
+                  ! -- umist --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( 0.25+0.75*Cr, MIN(0.75+0.25*Cr, 2. ) ) ) )
+
+                  ! high order flux corrected by the limiter
+                  pfu_ho(ji,jj,jl) = pfu_ho(ji,jj,jl) - ABS( pu(ji,jj) ) * ( (1.-zpsi) + uCFL*zpsi ) * Rj * 0.5
+
+               ENDIF
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', pfu_ho, 'U', -1.)   ! lateral boundary cond.
+      !
+   END SUBROUTINE limiter_x
+
+   
+   SUBROUTINE limiter_y( pdt, pv, pt, pfv_ups, pfv_ho )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE limiter_y  ***
+      !!     
+      !! **  Purpose :   compute flux limiter 
+      !!----------------------------------------------------------------------
+      REAL(wp)                   , INTENT(in   ) ::   pdt          ! tracer time-step
+      REAL(wp), DIMENSION (:,:  ), INTENT(in   ) ::   pv           ! ice i-velocity => u*e2
+      REAL(wp), DIMENSION (:,:,:), INTENT(in   ) ::   pt           ! ice tracer
+      REAL(wp), DIMENSION (:,:,:), INTENT(in   ) ::   pfv_ups      ! upstream flux
+      REAL(wp), DIMENSION (:,:,:), INTENT(inout) ::   pfv_ho       ! high order flux
+      !
+      REAL(wp) ::   Cr, Rjm, Rj, Rjp, vCFL, zpsi, zh3, zlimiter, Rr
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp), DIMENSION (jpi,jpj,jpl) ::   zslpy       ! tracer slopes 
+      !!----------------------------------------------------------------------
+      !
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zslpy(ji,jj,jl) = ( pt(ji,jj+1,jl) - pt(ji,jj,jl) ) * vmask(ji,jj,1)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', zslpy, 'V', -1.)   ! lateral boundary cond.
+
+      DO jl = 1, jpl
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               vCFL = pdt * ABS( pv(ji,jj) ) * r1_e1e2t(ji,jj)
+
+               Rjm = zslpy(ji,jj-1,jl)
+               Rj  = zslpy(ji,jj  ,jl)
+               Rjp = zslpy(ji,jj+1,jl)
+
+               IF( np_limiter == 3 ) THEN
+
+                  IF( pv(ji,jj) > 0. ) THEN   ;   Rr = Rjm
+                  ELSE                        ;   Rr = Rjp
+                  ENDIF
+
+                  zh3 = pfv_ho(ji,jj,jl) - pfv_ups(ji,jj,jl)     
+                  IF( Rj > 0. ) THEN
+                     zlimiter =  MAX( 0., MIN( zh3, MAX(-Rr * 0.5 * ABS(pv(ji,jj)),  &
+                        &        MIN( 2. * Rr * 0.5 * ABS(pv(ji,jj)),  zh3,  1.5 * Rj * 0.5 * ABS(pv(ji,jj)) ) ) ) )
+                  ELSE
+                     zlimiter = -MAX( 0., MIN(-zh3, MAX( Rr * 0.5 * ABS(pv(ji,jj)),  &
+                        &        MIN(-2. * Rr * 0.5 * ABS(pv(ji,jj)), -zh3, -1.5 * Rj * 0.5 * ABS(pv(ji,jj)) ) ) ) )
+                  ENDIF
+                  pfv_ho(ji,jj,jl) = pfv_ups(ji,jj,jl) + zlimiter
+
+               ELSEIF( np_limiter == 2 ) THEN
+
+                  IF( Rj /= 0. ) THEN
+                     IF( pv(ji,jj) > 0. ) THEN   ;   Cr = Rjm / Rj
+                     ELSE                        ;   Cr = Rjp / Rj
+                     ENDIF
+                  ELSE
+                     Cr = 0.
+                  ENDIF
+
+                  ! -- superbee --
+                  zpsi = MAX( 0., MAX( MIN(1.,2.*Cr), MIN(2.,Cr) ) )
+                  ! -- van albada 2 --
+                  !!zpsi = 2.*Cr / (Cr*Cr+1.)
+                  ! -- sweby (with beta=1) --
+                  !!zpsi = MAX( 0., MAX( MIN(1.,1.*Cr), MIN(1.,Cr) ) )
+                  ! -- van Leer --
+                  !!zpsi = ( Cr + ABS(Cr) ) / ( 1. + ABS(Cr) )
+                  ! -- ospre --
+                  !!zpsi = 1.5 * ( Cr*Cr + Cr ) / ( Cr*Cr + Cr + 1. )
+                  ! -- koren --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( (1.+2*Cr)/3., 2. ) ) )
+                  ! -- charm --
+                  !IF( Cr > 0. ) THEN   ;   zpsi = Cr * (3.*Cr + 1.) / ( (Cr + 1.) * (Cr + 1.) )
+                  !ELSE                 ;   zpsi = 0.
+                  !ENDIF
+                  ! -- van albada 1 --
+                  !!zpsi = (Cr*Cr + Cr) / (Cr*Cr +1)
+                  ! -- smart --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( 0.25+0.75*Cr, 4. ) ) )
+                  ! -- umist --
+                  !!zpsi = MAX( 0., MIN( 2.*Cr, MIN( 0.25+0.75*Cr, MIN(0.75+0.25*Cr, 2. ) ) ) )
+
+                  ! high order flux corrected by the limiter
+                  pfv_ho(ji,jj,jl) = pfv_ho(ji,jj,jl) - ABS( pv(ji,jj) ) * ( (1.-zpsi) + vCFL*zpsi ) * Rj * 0.5
+
+               ENDIF
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_adv_umx', pfv_ho, 'V', -1.)   ! lateral boundary cond.
+      !
+   END SUBROUTINE limiter_y
+
+
+   SUBROUTINE Hbig( pdt, phi_max, phs_max, phip_max, psi_max, pes_max, pei_max, &
+      &                  pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i, pe_s, pe_i )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE Hbig  ***
+      !!
+      !! ** Purpose : Thickness correction in case advection scheme creates
+      !!              abnormally tick ice or snow
+      !!
+      !! ** Method  : 1- check whether ice thickness is larger than the surrounding 9-points
+      !!                 (before advection) and reduce it by adapting ice concentration
+      !!              2- check whether snow thickness is larger than the surrounding 9-points
+      !!                 (before advection) and reduce it by sending the excess in the ocean
+      !!
+      !! ** input   : Max thickness of the surrounding 9-points
+      !!-------------------------------------------------------------------
+      REAL(wp)                    , INTENT(in   ) ::   pdt                                   ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   phi_max, phs_max, phip_max, psi_max   ! max ice thick from surrounding 9-pts
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pes_max
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pei_max
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i, pv_s, pa_i, pa_ip, pv_ip, psv_i
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_i
+      !
+      INTEGER  ::   ji, jj, jk, jl         ! dummy loop indices
+      REAL(wp) ::   z1_dt, zhip, zhi, zhs, zsi, zes, zei, zfra
+      !!-------------------------------------------------------------------
+      !
+      z1_dt = 1._wp / pdt
+      !
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                  !
+                  !                               ! -- check h_ip -- !
+                  ! if h_ip is larger than the surrounding 9 pts => reduce h_ip and increase a_ip
+                  IF( ln_pnd_LEV .AND. pv_ip(ji,jj,jl) > 0._wp ) THEN
+                     zhip = pv_ip(ji,jj,jl) / MAX( epsi20, pa_ip(ji,jj,jl) )
+                     IF( zhip > phip_max(ji,jj,jl) .AND. pa_ip(ji,jj,jl) < 0.15 ) THEN
+                        pa_ip(ji,jj,jl) = pv_ip(ji,jj,jl) / phip_max(ji,jj,jl)
+                     ENDIF
+                  ENDIF
+                  !
+                  !                               ! -- check h_i -- !
+                  ! if h_i is larger than the surrounding 9 pts => reduce h_i and increase a_i
+                  zhi = pv_i(ji,jj,jl) / pa_i(ji,jj,jl)
+                  IF( zhi > phi_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     pa_i(ji,jj,jl) = pv_i(ji,jj,jl) / MIN( phi_max(ji,jj,jl), hi_max(jpl) )   !-- bound h_i to hi_max (99 m)
+                  ENDIF
+                  !
+                  !                               ! -- check h_s -- !
+                  ! if h_s is larger than the surrounding 9 pts => put the snow excess in the ocean
+                  zhs = pv_s(ji,jj,jl) / pa_i(ji,jj,jl)
+                  IF( pv_s(ji,jj,jl) > 0._wp .AND. zhs > phs_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     zfra = phs_max(ji,jj,jl) / MAX( zhs, epsi20 )
+                     !
+                     wfx_res(ji,jj) = wfx_res(ji,jj) + ( pv_s(ji,jj,jl) - pa_i(ji,jj,jl) * phs_max(ji,jj,jl) ) * rhos * z1_dt
+                     hfx_res(ji,jj) = hfx_res(ji,jj) - SUM( pe_s(ji,jj,1:nlay_s,jl) ) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                     !
+                     pe_s(ji,jj,1:nlay_s,jl) = pe_s(ji,jj,1:nlay_s,jl) * zfra
+                     pv_s(ji,jj,jl)          = pa_i(ji,jj,jl) * phs_max(ji,jj,jl)
+                  ENDIF           
+                  !                  
+                  !                               ! -- check s_i -- !
+                  ! if s_i is larger than the surrounding 9 pts => put salt excess in the ocean
+                  zsi = psv_i(ji,jj,jl) / pv_i(ji,jj,jl)
+                  IF( zsi > psi_max(ji,jj,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                     zfra = psi_max(ji,jj,jl) / zsi
+                     sfx_res(ji,jj) = sfx_res(ji,jj) + psv_i(ji,jj,jl) * ( 1._wp - zfra ) * rhoi * z1_dt
+                     psv_i(ji,jj,jl) = psv_i(ji,jj,jl) * zfra
+                  ENDIF
+                  !
+               ENDIF
+            END DO
+         END DO
+      END DO 
+      !
+      !                                           ! -- check e_i/v_i -- !
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                     ! if e_i/v_i is larger than the surrounding 9 pts => put the heat excess in the ocean
+                     zei = pe_i(ji,jj,jk,jl) / pv_i(ji,jj,jl)
+                     IF( zei > pei_max(ji,jj,jk,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                        zfra = pei_max(ji,jj,jk,jl) / zei
+                        hfx_res(ji,jj) = hfx_res(ji,jj) - pe_i(ji,jj,jk,jl) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                        pe_i(ji,jj,jk,jl) = pe_i(ji,jj,jk,jl) * zfra
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+      !                                           ! -- check e_s/v_s -- !
+      DO jl = 1, jpl
+         DO jk = 1, nlay_s
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF ( pv_s(ji,jj,jl) > 0._wp ) THEN
+                     ! if e_s/v_s is larger than the surrounding 9 pts => put the heat excess in the ocean
+                     zes = pe_s(ji,jj,jk,jl) / pv_s(ji,jj,jl)
+                     IF( zes > pes_max(ji,jj,jk,jl) .AND. pa_i(ji,jj,jl) < 0.15 ) THEN
+                        zfra = pes_max(ji,jj,jk,jl) / zes
+                        hfx_res(ji,jj) = hfx_res(ji,jj) - pe_s(ji,jj,jk,jl) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                        pe_s(ji,jj,jk,jl) = pe_s(ji,jj,jk,jl) * zfra
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE Hbig
+
+
+   SUBROUTINE Hsnow( pdt, pv_i, pv_s, pa_i, pa_ip, pe_s )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE Hsnow  ***
+      !!
+      !! ** Purpose : 1- Check snow load after advection
+      !!              2- Correct pond concentration to avoid a_ip > a_i
+      !!
+      !! ** Method :  If snow load makes snow-ice interface to deplet below the ocean surface
+      !!              then put the snow excess in the ocean
+      !!
+      !! ** Notes :   This correction is crucial because of the call to routine icecor afterwards
+      !!              which imposes a mini of ice thick. (rn_himin). This imposed mini can artificially
+      !!              make the snow very thick (if concentration decreases drastically)
+      !!              This behavior has been seen in Ultimate-Macho and supposedly it can also be true for Prather
+      !!-------------------------------------------------------------------
+      REAL(wp)                    , INTENT(in   ) ::   pdt   ! tracer time-step
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i, pv_s, pa_i, pa_ip
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s
+      !
+      INTEGER  ::   ji, jj, jl   ! dummy loop indices
+      REAL(wp) ::   z1_dt, zvs_excess, zfra
+      !!-------------------------------------------------------------------
+      !
+      z1_dt = 1._wp / pdt
+      !
+      ! -- check snow load -- !
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( pv_i(ji,jj,jl) > 0._wp ) THEN
+                  !
+                  zvs_excess = MAX( 0._wp, pv_s(ji,jj,jl) - pv_i(ji,jj,jl) * (rau0-rhoi) * r1_rhos )
+                  !
+                  IF( zvs_excess > 0._wp ) THEN   ! snow-ice interface deplets below the ocean surface
+                     ! put snow excess in the ocean
+                     zfra = ( pv_s(ji,jj,jl) - zvs_excess ) / MAX( pv_s(ji,jj,jl), epsi20 )
+                     wfx_res(ji,jj) = wfx_res(ji,jj) + zvs_excess * rhos * z1_dt
+                     hfx_res(ji,jj) = hfx_res(ji,jj) - SUM( pe_s(ji,jj,1:nlay_s,jl) ) * ( 1._wp - zfra ) * z1_dt ! W.m-2 <0
+                     ! correct snow volume and heat content
+                     pe_s(ji,jj,1:nlay_s,jl) = pe_s(ji,jj,1:nlay_s,jl) * zfra
+                     pv_s(ji,jj,jl)          = pv_s(ji,jj,jl) - zvs_excess
+                  ENDIF
+                  !
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      !-- correct pond concentration to avoid a_ip > a_i -- !
+      WHERE( pa_ip(:,:,:) > pa_i(:,:,:) )   pa_ip(:,:,:) = pa_i(:,:,:)
+      !
+   END SUBROUTINE Hsnow
+
+   SUBROUTINE icemax3D( pice , pmax )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE icemax3D ***                     
+      !! ** Purpose :  compute the max of the 9 points around
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(in ) ::   pice   ! input
+      REAL(wp), DIMENSION(:,:,:)      , INTENT(out) ::   pmax   ! output
+      REAL(wp), DIMENSION(2:jpim1,jpj)              ::   zmax   ! temporary array
+      INTEGER  ::   ji, jj, jl   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 2, jpim1
+               zmax(ji,jj) = MAX( epsi20, pice(ji,jj,jl), pice(ji-1,jj,jl), pice(ji+1,jj,jl) )
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               pmax(ji,jj,jl) = MAX( epsi20, zmax(ji,jj), zmax(ji,jj-1), zmax(ji,jj+1) )
+            END DO
+         END DO
+      END DO
+   END SUBROUTINE icemax3D
+
+   SUBROUTINE icemax4D( pice , pmax )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE icemax4D ***                     
+      !! ** Purpose :  compute the max of the 9 points around
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:,:)    , INTENT(in ) ::   pice   ! input
+      REAL(wp), DIMENSION(:,:,:,:)    , INTENT(out) ::   pmax   ! output
+      REAL(wp), DIMENSION(2:jpim1,jpj)              ::   zmax   ! temporary array
+      INTEGER  ::   jlay, ji, jj, jk, jl   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      jlay = SIZE( pice , 3 )   ! size of input arrays
+      DO jl = 1, jpl
+         DO jk = 1, jlay
+            DO jj = 1, jpj
+               DO ji = 2, jpim1
+                  zmax(ji,jj) = MAX( epsi20, pice(ji,jj,jk,jl), pice(ji-1,jj,jk,jl), pice(ji+1,jj,jk,jl) )
+               END DO
+            END DO
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  pmax(ji,jj,jk,jl) = MAX( epsi20, zmax(ji,jj), zmax(ji,jj-1), zmax(ji,jj+1) )
+               END DO
+            END DO
+         END DO
+      END DO
+   END SUBROUTINE icemax4D
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icedyn_adv_umx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rdgrft.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rdgrft.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rdgrft.F90	(revision 14097)
@@ -0,0 +1,987 @@
+MODULE icedyn_rdgrft
+   !!======================================================================
+   !!                       ***  MODULE icedyn_rdgrft ***
+   !!    sea-ice : Mechanical impact on ice thickness distribution      
+   !!======================================================================
+   !! History :       !  2006-02  (M. Vancoppenolle) Original code 
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rdgrft       : ridging/rafting of sea ice
+   !!   ice_dyn_rdgrft_init  : initialization of ridging/rafting of sea ice
+   !!   ice_strength         : ice strength calculation
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constants (ocean directory) 
+   USE sbc_oce , ONLY : sss_m, sst_m   ! surface boundary condition: ocean fields
+   USE ice1D          ! sea-ice: thermodynamics
+   USE ice            ! sea-ice: variables
+   USE icetab         ! sea-ice: 1D <==> 2D transformation
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: control prints
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rdgrft        ! called by icestp
+   PUBLIC   ice_dyn_rdgrft_init   ! called by icedyn
+   PUBLIC   ice_strength          ! called by icedyn_rhg_evp
+
+   ! Variables shared among ridging subroutines
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   closing_net     ! net rate at which area is removed    (1/s)
+      !                                                               ! (ridging ice area - area of new ridges) / dt
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   opning          ! rate of opening due to divergence/shear
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   closing_gross   ! rate at which area removed, not counting area of new ridges
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   apartf          ! participation function; fraction of ridging/closing associated w/ category n
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hrmin           ! minimum ridge thickness
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hrmax           ! maximum ridge thickness
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hraft           ! thickness of rafted ice
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hi_hrdg         ! thickness of ridging ice / mean ridge thickness
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   aridge          ! participating ice ridging
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   araft           ! participating ice rafting
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ze_i_2d
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ze_s_2d
+   !
+   REAL(wp), PARAMETER ::   hrdg_hi_min = 1.1_wp    ! min ridge thickness multiplier: min(hrdg/hi)
+   REAL(wp), PARAMETER ::   hi_hrft     = 0.5_wp    ! rafting multipliyer: (hi/hraft)
+   !
+   ! ** namelist (namdyn_rdgrft) **
+   LOGICAL  ::   ln_str_H79       ! ice strength parameterization (Hibler79)
+   REAL(wp) ::   rn_pstar         ! determines ice strength, Hibler JPO79
+   REAL(wp) ::   rn_csrdg         ! fraction of shearing energy contributing to ridging            
+   LOGICAL  ::   ln_partf_lin     ! participation function linear (Thorndike et al. (1975))
+   REAL(wp) ::   rn_gstar         !    fractional area of young ice contributing to ridging
+   LOGICAL  ::   ln_partf_exp     ! participation function exponential (Lipscomb et al. (2007))
+   REAL(wp) ::   rn_astar         !    equivalent of G* for an exponential participation function
+   LOGICAL  ::   ln_ridging       ! ridging of ice or not                        
+   REAL(wp) ::   rn_hstar         !    thickness that determines the maximal thickness of ridged ice
+   REAL(wp) ::   rn_porordg       !    initial porosity of ridges (0.3 regular value)
+   REAL(wp) ::   rn_fsnwrdg       !    fractional snow loss to the ocean during ridging
+   REAL(wp) ::   rn_fpndrdg       !    fractional pond loss to the ocean during ridging
+   LOGICAL  ::   ln_rafting       ! rafting of ice or not                        
+   REAL(wp) ::   rn_hraft         !    threshold thickness (m) for rafting / ridging 
+   REAL(wp) ::   rn_craft         !    coefficient for smoothness of the hyperbolic tangent in rafting
+   REAL(wp) ::   rn_fsnwrft       !    fractional snow loss to the ocean during rafting
+   REAL(wp) ::   rn_fpndrft       !    fractional pond loss to the ocean during rafting
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION ice_dyn_rdgrft_alloc()
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_dyn_rdgrft_alloc ***
+      !!-------------------------------------------------------------------
+      ALLOCATE( closing_net(jpij)  , opning(jpij)      , closing_gross(jpij) ,               &
+         &      apartf(jpij,0:jpl) , hrmin  (jpij,jpl) , hraft(jpij,jpl) , aridge(jpij,jpl), &
+         &      hrmax (jpij,jpl)   , hi_hrdg(jpij,jpl) , araft(jpij,jpl) ,                   &
+         &      ze_i_2d(jpij,nlay_i,jpl), ze_s_2d(jpij,nlay_s,jpl), STAT=ice_dyn_rdgrft_alloc )
+
+      CALL mpp_sum ( 'icedyn_rdgrft', ice_dyn_rdgrft_alloc )
+      IF( ice_dyn_rdgrft_alloc /= 0 )   CALL ctl_stop( 'STOP',  'ice_dyn_rdgrft_alloc: failed to allocate arrays'  )
+      !
+   END FUNCTION ice_dyn_rdgrft_alloc
+
+
+   SUBROUTINE ice_dyn_rdgrft( kt )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_dyn_rdgrft ***
+      !!
+      !! ** Purpose :   computes the mechanical redistribution of ice thickness
+      !!
+      !! ** Method  :   Steps :
+      !!       0) Identify grid cells with ice
+      !!       1) Calculate closing rate, divergence and opening
+      !!       2) Identify grid cells with ridging
+      !!       3) Start ridging iterations
+      !!          - prep = ridged and rafted ice + closing_gross
+      !!          - shift = move ice from one category to another
+      !!
+      !! ** Details
+      !!    step1: The net rate of closing is due to convergence and shear, based on Flato and Hibler (1995).
+      !!           The energy dissipation rate is equal to the net closing rate times the ice strength.
+      !!
+      !!    step3: The gross closing rate is equal to the first two terms (open
+      !!           water closing and thin ice ridging) without the third term
+      !!           (thick, newly ridged ice).
+      !!
+      !! References :   Flato, G. M., and W. D. Hibler III, 1995, JGR, 100, 18,611-18,626.
+      !!                Hibler, W. D. III, 1980, MWR, 108, 1943-1973, 1980.
+      !!                Rothrock, D. A., 1975: JGR, 80, 4514-4519.
+      !!                Thorndike et al., 1975, JGR, 80, 4501-4513. 
+      !!                Bitz et al., JGR, 2001
+      !!                Amundrud and Melling, JGR 2005
+      !!                Babko et al., JGR 2002 
+      !!
+      !!     This routine is based on CICE code and authors William H. Lipscomb,
+      !!     and Elizabeth C. Hunke, LANL are gratefully acknowledged
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! number of iteration
+      !!
+      INTEGER  ::   ji, jj, jk, jl             ! dummy loop index
+      INTEGER  ::   iter, iterate_ridging      ! local integer 
+      INTEGER  ::   ipti                       ! local integer
+      REAL(wp) ::   zfac                       ! local scalar
+      INTEGER , DIMENSION(jpij) ::   iptidx        ! compute ridge/raft or not
+      REAL(wp), DIMENSION(jpij) ::   zdivu, zdelt  ! 1D divu_i & delta_i
+      !
+      INTEGER, PARAMETER ::   jp_itermax = 20    
+      !!-------------------------------------------------------------------
+      ! controls
+      IF( ln_timing    )   CALL timing_start('icedyn_rdgrft')                                                             ! timing
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'icedyn_rdgrft', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'icedyn_rdgrft',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*)'ice_dyn_rdgrft: ice ridging and rafting'
+         IF(lwp) WRITE(numout,*)'~~~~~~~~~~~~~~'
+      ENDIF      
+
+      !--------------------------------
+      ! 0) Identify grid cells with ice
+      !--------------------------------
+      at_i(:,:) = SUM( a_i, dim=3 )
+      !
+      npti = 0   ;   nptidx(:) = 0
+      ipti = 0   ;   iptidx(:) = 0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF ( at_i(ji,jj) > epsi10 ) THEN
+               npti           = npti + 1
+               nptidx( npti ) = (jj - 1) * jpi + ji
+            ENDIF
+         END DO
+      END DO
+      
+      !--------------------------------------------------------
+      ! 1) Dynamical inputs (closing rate, divergence, opening)
+      !--------------------------------------------------------
+      IF( npti > 0 ) THEN
+        
+         ! just needed here
+         CALL tab_2d_1d( npti, nptidx(1:npti), zdelt   (1:npti)      , delta_i )
+         ! needed here and in the iteration loop
+         CALL tab_2d_1d( npti, nptidx(1:npti), zdivu   (1:npti)      , divu_i) ! zdivu is used as a work array here (no change in divu_i)
+         CALL tab_3d_2d( npti, nptidx(1:npti), a_i_2d  (1:npti,1:jpl), a_i   )
+         CALL tab_3d_2d( npti, nptidx(1:npti), v_i_2d  (1:npti,1:jpl), v_i   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), ato_i_1d(1:npti)      , ato_i )
+
+         DO ji = 1, npti
+            ! closing_net = rate at which open water area is removed + ice area removed by ridging 
+            !                                                        - ice area added in new ridges
+            closing_net(ji) = rn_csrdg * 0.5_wp * ( zdelt(ji) - ABS( zdivu(ji) ) ) - MIN( zdivu(ji), 0._wp )
+            !
+            IF( zdivu(ji) < 0._wp )   closing_net(ji) = MAX( closing_net(ji), -zdivu(ji) )   ! make sure the closing rate is large enough
+            !                                                                                ! to give asum = 1.0 after ridging
+            ! Opening rate (non-negative) that will give asum = 1.0 after ridging.
+            opning(ji) = closing_net(ji) + zdivu(ji)
+         END DO
+         !
+         !------------------------------------
+         ! 2) Identify grid cells with ridging
+         !------------------------------------
+         CALL rdgrft_prep( a_i_2d, v_i_2d, ato_i_1d, closing_net )
+
+         DO ji = 1, npti
+            IF( SUM( apartf(ji,1:jpl) ) > 0._wp .AND. closing_gross(ji) > 0._wp ) THEN
+               ipti = ipti + 1
+               iptidx     (ipti)   = nptidx     (ji)
+               ! adjust to new indices
+               a_i_2d     (ipti,:) = a_i_2d     (ji,:)
+               v_i_2d     (ipti,:) = v_i_2d     (ji,:)
+               ato_i_1d   (ipti)   = ato_i_1d   (ji)
+               closing_net(ipti)   = closing_net(ji)
+               zdivu      (ipti)   = zdivu      (ji)
+               opning     (ipti)   = opning     (ji)
+            ENDIF
+         END DO
+
+      ENDIF
+
+      ! grid cells with ridging
+      nptidx(:) = iptidx(:)
+      npti      = ipti
+
+      !-----------------
+      ! 3) Start ridging
+      !-----------------
+      IF( npti > 0 ) THEN
+         
+         CALL ice_dyn_1d2d( 1 )            ! --- Move to 1D arrays --- !
+
+         iter            = 1
+         iterate_ridging = 1      
+         !                                                        !----------------------!
+         DO WHILE( iterate_ridging > 0 .AND. iter < jp_itermax )  !  ridging iterations  !
+            !                                                     !----------------------!
+            ! Calculate participation function (apartf)
+            !       and transfer      function
+            !       and closing_gross (+correction on opening)
+            CALL rdgrft_prep( a_i_2d, v_i_2d, ato_i_1d, closing_net )
+
+            ! Redistribute area, volume, and energy between categories
+            CALL rdgrft_shift
+
+            ! Do we keep on iterating?
+            !-------------------------
+            ! Check whether a_i + ato_i = 0
+            ! If not, because the closing and opening rates were reduced above, ridge again with new rates
+            iterate_ridging = 0
+            DO ji = 1, npti
+               zfac = 1._wp - ( ato_i_1d(ji) + SUM( a_i_2d(ji,:) ) )
+               IF( ABS( zfac ) < epsi10 ) THEN
+                  closing_net(ji) = 0._wp
+                  opning     (ji) = 0._wp
+                  ato_i_1d   (ji) = MAX( 0._wp, 1._wp - SUM( a_i_2d(ji,:) ) )
+               ELSE
+                  iterate_ridging  = 1
+                  zdivu      (ji) = zfac * r1_rdtice
+                  closing_net(ji) = MAX( 0._wp, -zdivu(ji) )
+                  opning     (ji) = MAX( 0._wp,  zdivu(ji) )
+               ENDIF
+            END DO
+            !
+            iter = iter + 1
+            IF( iter  >  jp_itermax )    CALL ctl_stop( 'STOP',  'icedyn_rdgrft: non-converging ridging scheme'  )
+            !
+         END DO
+
+         CALL ice_dyn_1d2d( 2 )            ! --- Move to 2D arrays --- !
+
+      ENDIF
+   
+      CALL ice_var_agg( 1 ) 
+
+      ! controls
+      IF( ln_ctl       )   CALL ice_prt3D   ('icedyn_rdgrft')                                                             ! prints
+      IF( ln_icectl    )   CALL ice_prt     (kt, iiceprt, jiceprt,-1, ' - ice dyn rdgrft - ')                             ! prints
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icedyn_rdgrft', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'icedyn_rdgrft',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+      IF( ln_timing    )   CALL timing_stop ('icedyn_rdgrft')                                                             ! timing
+      !
+   END SUBROUTINE ice_dyn_rdgrft
+
+
+   SUBROUTINE rdgrft_prep( pa_i, pv_i, pato_i, pclosing_net )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE rdgrft_prep ***
+      !!
+      !! ** Purpose :   preparation for ridging calculations
+      !!
+      !! ** Method  :   Compute the thickness distribution of the ice and open water 
+      !!                participating in ridging and of the resulting ridges.
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)  , INTENT(in) ::   pato_i, pclosing_net 
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pa_i, pv_i 
+      !!
+      INTEGER  ::   ji, jl                     ! dummy loop indices
+      REAL(wp) ::   z1_gstar, z1_astar, zhmean, zfac   ! local scalar
+      REAL(wp), DIMENSION(jpij)        ::   zasum, z1_asum, zaksum   ! sum of a_i+ato_i and reverse 
+      REAL(wp), DIMENSION(jpij,jpl)    ::   zhi                      ! ice thickness
+      REAL(wp), DIMENSION(jpij,-1:jpl) ::   zGsum                    ! zGsum(n) = sum of areas in categories 0 to n
+      !--------------------------------------------------------------------
+
+      z1_gstar = 1._wp / rn_gstar
+      z1_astar = 1._wp / rn_astar
+
+      !                       ! Ice thickness needed for rafting
+      WHERE( pa_i(1:npti,:) > epsi10 )   ;   zhi(1:npti,:) = pv_i(1:npti,:) / pa_i(1:npti,:)
+      ELSEWHERE                          ;   zhi(1:npti,:) = 0._wp
+      END WHERE
+
+      ! 1) Participation function (apartf): a(h) = b(h).g(h)
+      !-----------------------------------------------------------------
+      ! Compute the participation function = total area lost due to ridging/closing
+      ! This is analogous to
+      !   a(h) = b(h)g(h) as defined in Thorndike et al. (1975).
+      !   assuming b(h) = (2/Gstar) * (1 - G(h)/Gstar). 
+      !
+      ! apartf = integrating b(h)g(h) between the category boundaries
+      ! apartf is always >= 0 and SUM(apartf(0:jpl))=1
+      !-----------------------------------------------------------------
+      !
+      ! Compute total area of ice plus open water.
+      ! This is in general not equal to one because of divergence during transport
+      zasum(1:npti) = pato_i(1:npti) + SUM( pa_i(1:npti,:), dim=2 )
+      !
+      WHERE( zasum(1:npti) > epsi10 )   ;   z1_asum(1:npti) = 1._wp / zasum(1:npti)
+      ELSEWHERE                         ;   z1_asum(1:npti) = 0._wp
+      END WHERE
+      !
+      ! Compute cumulative thickness distribution function
+      ! Compute the cumulative thickness distribution function zGsum,
+      ! where zGsum(n) is the fractional area in categories 0 to n.
+      ! initial value (in h = 0) = open water area
+      zGsum(1:npti,-1) = 0._wp
+      zGsum(1:npti,0 ) = pato_i(1:npti) * z1_asum(1:npti)
+      DO jl = 1, jpl
+         zGsum(1:npti,jl) = ( pato_i(1:npti) + SUM( pa_i(1:npti,1:jl), dim=2 ) ) * z1_asum(1:npti)  ! sum(1:jl) is ok (and not jpl)
+      END DO
+      !
+      IF( ln_partf_lin ) THEN          !--- Linear formulation (Thorndike et al., 1975)
+         DO jl = 0, jpl    
+            DO ji = 1, npti
+               IF    ( zGsum(ji,jl)   < rn_gstar ) THEN
+                  apartf(ji,jl) = z1_gstar * ( zGsum(ji,jl) - zGsum(ji,jl-1) ) * &
+                     &                       ( 2._wp - ( zGsum(ji,jl-1) + zGsum(ji,jl) ) * z1_gstar )
+               ELSEIF( zGsum(ji,jl-1) < rn_gstar ) THEN
+                  apartf(ji,jl) = z1_gstar * ( rn_gstar     - zGsum(ji,jl-1) ) *  &
+                     &                       ( 2._wp - ( zGsum(ji,jl-1) + rn_gstar     ) * z1_gstar )
+               ELSE
+                  apartf(ji,jl) = 0._wp
+               ENDIF
+            END DO
+         END DO
+         !
+      ELSEIF( ln_partf_exp ) THEN      !--- Exponential, more stable formulation (Lipscomb et al, 2007)
+         !                        
+         zfac = 1._wp / ( 1._wp - EXP(-z1_astar) )
+         DO jl = -1, jpl
+            DO ji = 1, npti
+               zGsum(ji,jl) = EXP( -zGsum(ji,jl) * z1_astar ) * zfac
+            END DO
+         END DO
+         DO jl = 0, jpl
+            DO ji = 1, npti
+               apartf(ji,jl) = zGsum(ji,jl-1) - zGsum(ji,jl)
+            END DO
+         END DO
+         !
+      ENDIF
+
+      !                                !--- Ridging and rafting participation concentrations
+      IF( ln_rafting .AND. ln_ridging ) THEN             !- ridging & rafting
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               aridge(ji,jl) = ( 1._wp + TANH ( rn_craft * ( zhi(ji,jl) - rn_hraft ) ) ) * 0.5_wp * apartf(ji,jl)
+               araft (ji,jl) = apartf(ji,jl) - aridge(ji,jl)
+            END DO
+         END DO
+      ELSEIF( ln_ridging .AND. .NOT. ln_rafting ) THEN   !- ridging alone
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               aridge(ji,jl) = apartf(ji,jl)
+               araft (ji,jl) = 0._wp
+            END DO
+         END DO
+      ELSEIF( ln_rafting .AND. .NOT. ln_ridging ) THEN   !- rafting alone   
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               aridge(ji,jl) = 0._wp
+               araft (ji,jl) = apartf(ji,jl)
+            END DO
+         END DO
+      ELSE                                               !- no ridging & no rafting
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               aridge(ji,jl) = 0._wp
+               araft (ji,jl) = 0._wp         
+            END DO
+         END DO
+      ENDIF
+
+      ! 2) Transfer function
+      !-----------------------------------------------------------------
+      ! Compute max and min ridged ice thickness for each ridging category.
+      ! Assume ridged ice is uniformly distributed between hrmin and hrmax.
+      ! 
+      ! This parameterization is a modified version of Hibler (1980).
+      ! The mean ridging thickness, zhmean, is proportional to hi^(0.5)
+      !  and for very thick ridging ice must be >= hrdg_hi_min*hi
+      !
+      ! The minimum ridging thickness, hrmin, is equal to 2*hi 
+      !  (i.e., rafting) and for very thick ridging ice is
+      !  constrained by hrmin <= (zhmean + hi)/2.
+      ! 
+      ! The maximum ridging thickness, hrmax, is determined by zhmean and hrmin.
+      !
+      ! These modifications have the effect of reducing the ice strength
+      ! (relative to the Hibler formulation) when very thick ice is ridging.
+      !
+      ! zaksum = net area removed/ total area removed
+      ! where total area removed = area of ice that ridges
+      !         net area removed = total area removed - area of new ridges
+      !-----------------------------------------------------------------
+      zfac = 1._wp / hi_hrft
+      zaksum(1:npti) = apartf(1:npti,0)
+      !
+      DO jl = 1, jpl
+         DO ji = 1, npti
+            IF ( apartf(ji,jl) > 0._wp ) THEN
+               zhmean         = MAX( SQRT( rn_hstar * zhi(ji,jl) ), zhi(ji,jl) * hrdg_hi_min )
+               hrmin  (ji,jl) = MIN( 2._wp * zhi(ji,jl), 0.5_wp * ( zhmean + zhi(ji,jl) ) )
+               hrmax  (ji,jl) = 2._wp * zhmean - hrmin(ji,jl)
+               hraft  (ji,jl) = zhi(ji,jl) * zfac
+               hi_hrdg(ji,jl) = zhi(ji,jl) / MAX( zhmean, epsi20 )
+               !
+               ! Normalization factor : zaksum, ensures mass conservation
+               zaksum(ji) = zaksum(ji) + aridge(ji,jl) * ( 1._wp - hi_hrdg(ji,jl) )    &
+                  &                    + araft (ji,jl) * ( 1._wp - hi_hrft )
+            ELSE
+               hrmin  (ji,jl) = 0._wp 
+               hrmax  (ji,jl) = 0._wp 
+               hraft  (ji,jl) = 0._wp 
+               hi_hrdg(ji,jl) = 1._wp
+            ENDIF
+         END DO
+      END DO
+      !
+      ! 3) closing_gross
+      !-----------------
+      ! Based on the ITD of ridging and ridged ice, convert the net closing rate to a gross closing rate.  
+      ! NOTE: 0 < aksum <= 1
+      WHERE( zaksum(1:npti) > epsi10 )   ;   closing_gross(1:npti) = pclosing_net(1:npti) / zaksum(1:npti)
+      ELSEWHERE                          ;   closing_gross(1:npti) = 0._wp
+      END WHERE
+      
+      ! correction to closing rate if excessive ice removal
+      !----------------------------------------------------
+      ! Reduce the closing rate if more than 100% of any ice category would be removed
+      ! Reduce the opening rate in proportion
+      DO jl = 1, jpl
+         DO ji = 1, npti
+            zfac = apartf(ji,jl) * closing_gross(ji) * rdt_ice
+            IF( zfac > pa_i(ji,jl) .AND. apartf(ji,jl) /= 0._wp ) THEN
+               closing_gross(ji) = pa_i(ji,jl) / apartf(ji,jl) * r1_rdtice
+            ENDIF
+         END DO
+      END DO      
+
+      ! 4) correction to opening if excessive open water removal
+      !---------------------------------------------------------
+      ! Reduce the closing rate if more than 100% of the open water would be removed
+      ! Reduce the opening rate in proportion
+      DO ji = 1, npti  
+         zfac = pato_i(ji) + ( opning(ji) - apartf(ji,0) * closing_gross(ji) ) * rdt_ice
+         IF( zfac < 0._wp ) THEN           ! would lead to negative ato_i
+            opning(ji) = apartf(ji,0) * closing_gross(ji) - pato_i(ji) * r1_rdtice 
+         ELSEIF( zfac > zasum(ji) ) THEN   ! would lead to ato_i > asum
+            opning(ji) = apartf(ji,0) * closing_gross(ji) + ( zasum(ji) - pato_i(ji) ) * r1_rdtice 
+         ENDIF
+      END DO
+      !
+   END SUBROUTINE rdgrft_prep
+
+
+   SUBROUTINE rdgrft_shift
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE rdgrft_shift ***
+      !!
+      !! ** Purpose :   shift ridging ice among thickness categories of ice thickness
+      !!
+      !! ** Method  :   Remove area, volume, and energy from each ridging category
+      !!                and add to thicker ice categories.
+      !!-------------------------------------------------------------------
+      !
+      INTEGER  ::   ji, jj, jl, jl1, jl2, jk   ! dummy loop indices
+      REAL(wp) ::   hL, hR, farea              ! left and right limits of integration and new area going to jl2
+      REAL(wp) ::   vsw                        ! vol of water trapped into ridges
+      REAL(wp) ::   afrdg, afrft               ! fraction of category area ridged/rafted 
+      REAL(wp)                  ::   airdg1, oirdg1, aprdg1, virdg1, sirdg1
+      REAL(wp)                  ::   airft1, oirft1, aprft1
+      REAL(wp), DIMENSION(jpij) ::   airdg2, oirdg2, aprdg2, virdg2, sirdg2, vsrdg, vprdg, vlrdg  ! area etc of new ridges
+      REAL(wp), DIMENSION(jpij) ::   airft2, oirft2, aprft2, virft , sirft , vsrft, vprft, vlrft  ! area etc of rafted ice
+      !
+      REAL(wp), DIMENSION(jpij) ::   ersw             ! enth of water trapped into ridges
+      REAL(wp), DIMENSION(jpij) ::   zswitch, fvol    ! new ridge volume going to jl2
+      REAL(wp), DIMENSION(jpij) ::   z1_ai            ! 1 / a
+      REAL(wp), DIMENSION(jpij) ::   zvti             ! sum(v_i)
+      !
+      REAL(wp), DIMENSION(jpij,nlay_s) ::   esrft     ! snow energy of rafting ice
+      REAL(wp), DIMENSION(jpij,nlay_i) ::   eirft     ! ice  energy of rafting ice
+      REAL(wp), DIMENSION(jpij,nlay_s) ::   esrdg     ! enth*volume of new ridges      
+      REAL(wp), DIMENSION(jpij,nlay_i) ::   eirdg     ! enth*volume of new ridges
+      !
+      INTEGER , DIMENSION(jpij) ::   itest_rdg, itest_rft   ! test for conservation
+      !!-------------------------------------------------------------------
+      !
+      zvti(1:npti) = SUM( v_i_2d(1:npti,:), dim=2 )   ! total ice volume
+      !
+      ! 1) Change in open water area due to closing and opening
+      !--------------------------------------------------------
+      DO ji = 1, npti
+         ato_i_1d(ji) = MAX( 0._wp, ato_i_1d(ji) + ( opning(ji) - apartf(ji,0) * closing_gross(ji) ) * rdt_ice )
+      END DO
+      
+      ! 2) compute categories in which ice is removed (jl1) 
+      !----------------------------------------------------
+      DO jl1 = 1, jpl
+
+         IF( nn_icesal /= 2 )  THEN      
+            CALL tab_2d_1d( npti, nptidx(1:npti), s_i_1d(1:npti), s_i(:,:,jl1) )
+         ENDIF
+
+         DO ji = 1, npti
+
+            IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp ) THEN   ! only if ice is ridging
+
+               IF( a_i_2d(ji,jl1) > epsi10 ) THEN   ;   z1_ai(ji) = 1._wp / a_i_2d(ji,jl1)
+               ELSE                                 ;   z1_ai(ji) = 0._wp
+               ENDIF
+               
+               ! area of ridging / rafting ice (airdg1) and of new ridge (airdg2)
+               airdg1 = aridge(ji,jl1) * closing_gross(ji) * rdt_ice
+               airft1 = araft (ji,jl1) * closing_gross(ji) * rdt_ice
+
+               airdg2(ji) = airdg1 * hi_hrdg(ji,jl1)
+               airft2(ji) = airft1 * hi_hrft
+
+               ! ridging /rafting fractions
+               afrdg = airdg1 * z1_ai(ji)
+               afrft = airft1 * z1_ai(ji)
+
+               ! volume and enthalpy (J/m2, >0) of seawater trapped into ridges
+               IF    ( zvti(ji) <= 10. ) THEN ; vsw = v_i_2d(ji,jl1) * afrdg * rn_porordg                                           ! v <= 10m then porosity = rn_porordg
+               ELSEIF( zvti(ji) >= 20. ) THEN ; vsw = 0._wp                                                                         ! v >= 20m then porosity = 0
+               ELSE                           ; vsw = v_i_2d(ji,jl1) * afrdg * rn_porordg * MAX( 0._wp, 2._wp - 0.1_wp * zvti(ji) ) ! v > 10m and v < 20m then porosity = linear transition to 0
+               ENDIF
+               ersw(ji) = -rhoi * vsw * rcp * sst_1d(ji)   ! clem: if sst>0, then ersw <0 (is that possible?)
+
+               ! volume etc of ridging / rafting ice and new ridges (vi, vs, sm, oi, es, ei)
+               virdg1     = v_i_2d (ji,jl1)   * afrdg
+               virdg2(ji) = v_i_2d (ji,jl1)   * afrdg + vsw
+               vsrdg(ji)  = v_s_2d (ji,jl1)   * afrdg
+               sirdg1     = sv_i_2d(ji,jl1)   * afrdg
+               sirdg2(ji) = sv_i_2d(ji,jl1)   * afrdg + vsw * sss_1d(ji)
+               oirdg1     = oa_i_2d(ji,jl1)   * afrdg
+               oirdg2(ji) = oa_i_2d(ji,jl1)   * afrdg * hi_hrdg(ji,jl1) 
+
+               virft(ji)  = v_i_2d (ji,jl1)   * afrft
+               vsrft(ji)  = v_s_2d (ji,jl1)   * afrft
+               sirft(ji)  = sv_i_2d(ji,jl1)   * afrft 
+               oirft1     = oa_i_2d(ji,jl1)   * afrft 
+               oirft2(ji) = oa_i_2d(ji,jl1)   * afrft * hi_hrft 
+
+               IF ( ln_pnd_LEV ) THEN
+                  aprdg1     = a_ip_2d(ji,jl1) * afrdg
+                  aprdg2(ji) = a_ip_2d(ji,jl1) * afrdg * hi_hrdg(ji,jl1)
+                  vprdg (ji) = v_ip_2d(ji,jl1) * afrdg
+                  aprft1     = a_ip_2d(ji,jl1) * afrft
+                  aprft2(ji) = a_ip_2d(ji,jl1) * afrft * hi_hrft
+                  vprft (ji) = v_ip_2d(ji,jl1) * afrft
+                  IF ( ln_pnd_lids ) THEN
+                     vlrdg (ji) = v_il_2d(ji,jl1) * afrdg
+                     vlrft (ji) = v_il_2d(ji,jl1) * afrft
+                  ENDIF
+               ENDIF
+
+               ! Ice-ocean exchanges associated with ice porosity
+               wfx_dyn_1d(ji) = wfx_dyn_1d(ji) - vsw * rhoi * r1_rdtice   ! increase in ice volume due to seawater frozen in voids
+               sfx_dyn_1d(ji) = sfx_dyn_1d(ji) - vsw * sss_1d(ji) * rhoi * r1_rdtice
+               hfx_dyn_1d(ji) = hfx_dyn_1d(ji) + ersw(ji) * r1_rdtice          ! > 0 [W.m-2] 
+
+               ! Put the snow lost by ridging into the ocean
+               !  Note that esrdg > 0; the ocean must cool to melt snow. If the ocean temp = Tf already, new ice must grow.
+               wfx_snw_dyn_1d(ji) = wfx_snw_dyn_1d(ji) + ( rhos * vsrdg(ji) * ( 1._wp - rn_fsnwrdg )   &   ! fresh water source for ocean
+                  &                                      + rhos * vsrft(ji) * ( 1._wp - rn_fsnwrft ) ) * r1_rdtice
+
+               ! virtual salt flux to keep salinity constant
+               IF( nn_icesal /= 2 )  THEN
+                  sirdg2(ji)     = sirdg2(ji)     - vsw * ( sss_1d(ji) - s_i_1d(ji) )       ! ridge salinity = s_i
+                  sfx_bri_1d(ji) = sfx_bri_1d(ji) + sss_1d(ji) * vsw * rhoi * r1_rdtice  &  ! put back sss_m into the ocean
+                     &                            - s_i_1d(ji) * vsw * rhoi * r1_rdtice     ! and get  s_i  from the ocean 
+               ENDIF
+
+               ! Remove area, volume of new ridge to each category jl1
+               !------------------------------------------------------
+               a_i_2d (ji,jl1) = a_i_2d (ji,jl1) - airdg1    - airft1
+               v_i_2d (ji,jl1) = v_i_2d (ji,jl1) - virdg1    - virft(ji)
+               v_s_2d (ji,jl1) = v_s_2d (ji,jl1) - vsrdg(ji) - vsrft(ji)
+               sv_i_2d(ji,jl1) = sv_i_2d(ji,jl1) - sirdg1    - sirft(ji)
+               oa_i_2d(ji,jl1) = oa_i_2d(ji,jl1) - oirdg1    - oirft1
+               IF ( ln_pnd_LEV ) THEN
+                  a_ip_2d(ji,jl1) = a_ip_2d(ji,jl1) - aprdg1    - aprft1
+                  v_ip_2d(ji,jl1) = v_ip_2d(ji,jl1) - vprdg(ji) - vprft(ji)
+                  IF ( ln_pnd_lids ) THEN
+                     v_il_2d(ji,jl1) = v_il_2d(ji,jl1) - vlrdg(ji) - vlrft(ji)
+                  ENDIF
+               ENDIF
+            ENDIF
+
+         END DO ! ji
+
+         ! special loop for e_s because of layers jk
+         DO jk = 1, nlay_s
+            DO ji = 1, npti
+               IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp ) THEN
+                  ! Compute ridging /rafting fractions
+                  afrdg = aridge(ji,jl1) * closing_gross(ji) * rdt_ice * z1_ai(ji)
+                  afrft = araft (ji,jl1) * closing_gross(ji) * rdt_ice * z1_ai(ji)
+                  ! Compute ridging /rafting ice and new ridges for es
+                  esrdg(ji,jk) = ze_s_2d (ji,jk,jl1) * afrdg
+                  esrft(ji,jk) = ze_s_2d (ji,jk,jl1) * afrft
+                  ! Put the snow lost by ridging into the ocean
+                  hfx_dyn_1d(ji) = hfx_dyn_1d(ji) + ( - esrdg(ji,jk) * ( 1._wp - rn_fsnwrdg )   &                 ! heat sink for ocean (<0, W.m-2)
+                     &                                - esrft(ji,jk) * ( 1._wp - rn_fsnwrft ) ) * r1_rdtice
+                  !
+                  ! Remove energy of new ridge to each category jl1
+                  !-------------------------------------------------
+                  ze_s_2d(ji,jk,jl1) = ze_s_2d(ji,jk,jl1) * ( 1._wp - afrdg - afrft ) 
+               ENDIF
+            END DO
+         END DO
+                  
+         ! special loop for e_i because of layers jk
+         DO jk = 1, nlay_i
+            DO ji = 1, npti
+               IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp ) THEN
+                  ! Compute ridging /rafting fractions
+                  afrdg = aridge(ji,jl1) * closing_gross(ji) * rdt_ice * z1_ai(ji)
+                  afrft = araft (ji,jl1) * closing_gross(ji) * rdt_ice * z1_ai(ji)
+                  ! Compute ridging ice and new ridges for ei
+                  eirdg(ji,jk) = ze_i_2d (ji,jk,jl1) * afrdg + ersw(ji) * r1_nlay_i
+                  eirft(ji,jk) = ze_i_2d (ji,jk,jl1) * afrft
+                  !
+                  ! Remove energy of new ridge to each category jl1
+                  !-------------------------------------------------
+                  ze_i_2d(ji,jk,jl1) = ze_i_2d(ji,jk,jl1) * ( 1._wp - afrdg - afrft ) 
+               ENDIF
+            END DO
+         END DO
+         
+         ! 3) compute categories in which ice is added (jl2) 
+         !--------------------------------------------------
+         itest_rdg(1:npti) = 0
+         itest_rft(1:npti) = 0
+         DO jl2  = 1, jpl 
+            !
+            DO ji = 1, npti
+
+               IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp ) THEN
+
+                  ! Compute the fraction of ridged ice area and volume going to thickness category jl2
+                  IF( hrmin(ji,jl1) <= hi_max(jl2) .AND. hrmax(ji,jl1) > hi_max(jl2-1) ) THEN
+                     hL = MAX( hrmin(ji,jl1), hi_max(jl2-1) )
+                     hR = MIN( hrmax(ji,jl1), hi_max(jl2)   )
+                     farea    = ( hR      - hL      ) / ( hrmax(ji,jl1)                 - hrmin(ji,jl1)                 )
+                     fvol(ji) = ( hR * hR - hL * hL ) / ( hrmax(ji,jl1) * hrmax(ji,jl1) - hrmin(ji,jl1) * hrmin(ji,jl1) )
+                     !
+                     itest_rdg(ji) = 1   ! test for conservation
+                  ELSE
+                     farea    = 0._wp 
+                     fvol(ji) = 0._wp                  
+                  ENDIF
+
+                  ! Compute the fraction of rafted ice area and volume going to thickness category jl2
+                  IF( hraft(ji,jl1) <= hi_max(jl2) .AND. hraft(ji,jl1) >  hi_max(jl2-1) ) THEN
+                     zswitch(ji) = 1._wp
+                     !
+                     itest_rft(ji) = 1   ! test for conservation
+                  ELSE
+                     zswitch(ji) = 0._wp
+                  ENDIF
+                  !
+                  ! Patch to ensure perfect conservation if ice thickness goes mad
+                  ! Sometimes thickness is larger than hi_max(jpl) because of advection scheme (for very small areas)
+                  ! Then ice volume is removed from one category but the ridging/rafting scheme
+                  ! does not know where to move it, leading to a conservation issue.  
+                  IF( itest_rdg(ji) == 0 .AND. jl2 == jpl ) THEN   ;   farea = 1._wp   ;   fvol(ji) = 1._wp   ;   ENDIF
+                  IF( itest_rft(ji) == 0 .AND. jl2 == jpl )      zswitch(ji) = 1._wp
+                  !
+                  ! Add area, volume of new ridge to category jl2
+                  !----------------------------------------------
+                  a_i_2d (ji,jl2) = a_i_2d (ji,jl2) + ( airdg2(ji) * farea    + airft2(ji) * zswitch(ji) )
+                  oa_i_2d(ji,jl2) = oa_i_2d(ji,jl2) + ( oirdg2(ji) * farea    + oirft2(ji) * zswitch(ji) )
+                  v_i_2d (ji,jl2) = v_i_2d (ji,jl2) + ( virdg2(ji) * fvol(ji) + virft (ji) * zswitch(ji) )
+                  sv_i_2d(ji,jl2) = sv_i_2d(ji,jl2) + ( sirdg2(ji) * fvol(ji) + sirft (ji) * zswitch(ji) )
+                  v_s_2d (ji,jl2) = v_s_2d (ji,jl2) + ( vsrdg (ji) * rn_fsnwrdg * fvol(ji)  +  &
+                     &                                  vsrft (ji) * rn_fsnwrft * zswitch(ji) )
+                  IF ( ln_pnd_LEV ) THEN
+                     v_ip_2d (ji,jl2) = v_ip_2d(ji,jl2) + (   vprdg (ji) * rn_fpndrdg * fvol   (ji)   &
+                        &                                   + vprft (ji) * rn_fpndrft * zswitch(ji)   )
+                     a_ip_2d (ji,jl2) = a_ip_2d(ji,jl2) + (   aprdg2(ji) * rn_fpndrdg * farea         & 
+                        &                                   + aprft2(ji) * rn_fpndrft * zswitch(ji)   )
+                     IF ( ln_pnd_lids ) THEN
+                        v_il_2d (ji,jl2) = v_il_2d(ji,jl2) + (   vlrdg(ji) * rn_fpndrdg * fvol   (ji) &
+                           &                                   + vlrft(ji) * rn_fpndrft * zswitch(ji) )
+                     ENDIF
+                  ENDIF
+                  
+               ENDIF
+
+            END DO
+            ! Add snow energy of new ridge to category jl2
+            !---------------------------------------------
+            DO jk = 1, nlay_s
+               DO ji = 1, npti
+                  IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp )   &
+                     &   ze_s_2d(ji,jk,jl2) = ze_s_2d(ji,jk,jl2) + ( esrdg(ji,jk) * rn_fsnwrdg * fvol(ji)  +  &
+                     &                                               esrft(ji,jk) * rn_fsnwrft * zswitch(ji) )
+               END DO
+            END DO
+            ! Add ice energy of new ridge to category jl2
+            !--------------------------------------------
+            DO jk = 1, nlay_i
+               DO ji = 1, npti
+                  IF( apartf(ji,jl1) > 0._wp .AND. closing_gross(ji) > 0._wp )   &
+                     &   ze_i_2d(ji,jk,jl2) = ze_i_2d(ji,jk,jl2) + eirdg(ji,jk) * fvol(ji) + eirft(ji,jk) * zswitch(ji)                  
+               END DO
+            END DO
+            !
+         END DO ! jl2
+         !
+      END DO ! jl1
+      !
+      ! roundoff errors
+      !----------------
+      ! In case ridging/rafting lead to very small negative values (sometimes it happens)
+      CALL ice_var_roundoff( a_i_2d, v_i_2d, v_s_2d, sv_i_2d, oa_i_2d, a_ip_2d, v_ip_2d, v_il_2d, ze_s_2d, ze_i_2d )
+      !
+   END SUBROUTINE rdgrft_shift
+
+
+   SUBROUTINE ice_strength
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE ice_strength ***
+      !!
+      !! ** Purpose :   computes ice strength used in dynamics routines of ice thickness
+      !!
+      !! ** Method  :   Compute the strength of the ice pack, defined as the energy (J m-2) 
+      !!              dissipated per unit area removed from the ice pack under compression,
+      !!              and assumed proportional to the change in potential energy caused
+      !!              by ridging. Note that only Hibler's formulation is stable and that
+      !!              ice strength has to be smoothed
+      !!----------------------------------------------------------------------
+      INTEGER             ::   ji, jj, jl  ! dummy loop indices
+      INTEGER             ::   ismooth     ! smoothing the resistance to deformation
+      INTEGER             ::   itframe     ! number of time steps for the P smoothing
+      REAL(wp)            ::   zp, z1_3    ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zworka           ! temporary array used here
+      REAL(wp), DIMENSION(jpi,jpj) ::   zstrp1, zstrp2   ! strength at previous time steps
+      !!----------------------------------------------------------------------
+      !                              !--------------------------------------------------!
+      IF( ln_str_H79 ) THEN          ! Ice strength => Hibler (1979) method             !
+      !                              !--------------------------------------------------!
+         strength(:,:) = rn_pstar * SUM( v_i(:,:,:), dim=3 ) * EXP( -rn_crhg * ( 1._wp - SUM( a_i(:,:,:), dim=3 ) ) )
+         ismooth = 1
+         !                           !--------------------------------------------------!
+      ELSE                           ! Zero strength                                    !
+         !                           !--------------------------------------------------!
+         strength(:,:) = 0._wp
+         ismooth = 0
+      ENDIF
+      !                              !--------------------------------------------------!
+      SELECT CASE( ismooth )         ! Smoothing ice strength                           !
+      !                              !--------------------------------------------------!
+      CASE( 1 )               !--- Spatial smoothing
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF ( SUM( a_i(ji,jj,:) ) > 0._wp ) THEN 
+                  zworka(ji,jj) = ( 4.0 * strength(ji,jj)              &
+                     &                  + strength(ji-1,jj) * tmask(ji-1,jj,1) + strength(ji+1,jj) * tmask(ji+1,jj,1) &  
+                     &                  + strength(ji,jj-1) * tmask(ji,jj-1,1) + strength(ji,jj+1) * tmask(ji,jj+1,1) &
+                     &            ) / ( 4.0 + tmask(ji-1,jj,1) + tmask(ji+1,jj,1) + tmask(ji,jj-1,1) + tmask(ji,jj+1,1) )
+               ELSE
+                  zworka(ji,jj) = 0._wp
+               ENDIF
+            END DO
+         END DO
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               strength(ji,jj) = zworka(ji,jj)
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_rdgrft', strength, 'T', 1. )
+         !
+      CASE( 2 )               !--- Temporal smoothing
+         IF ( kt_ice == nit000 ) THEN
+            zstrp1(:,:) = 0._wp
+            zstrp2(:,:) = 0._wp
+         ENDIF
+         !
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF ( SUM( a_i(ji,jj,:) ) > 0._wp ) THEN 
+                  itframe = 1 ! number of time steps for the running mean
+                  IF ( zstrp1(ji,jj) > 0._wp ) itframe = itframe + 1
+                  IF ( zstrp2(ji,jj) > 0._wp ) itframe = itframe + 1
+                  zp = ( strength(ji,jj) + zstrp1(ji,jj) + zstrp2(ji,jj) ) / itframe
+                  zstrp2  (ji,jj) = zstrp1  (ji,jj)
+                  zstrp1  (ji,jj) = strength(ji,jj)
+                  strength(ji,jj) = zp
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_rdgrft', strength, 'T', 1. )
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_strength
+
+   
+   SUBROUTINE ice_dyn_1d2d( kn )
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_dyn_1d2d *** 
+      !!                 
+      !! ** Purpose :   move arrays from 1d to 2d and the reverse
+      !!-----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kn   ! 1= from 2D to 1D   ;   2= from 1D to 2D
+      !
+      INTEGER ::   jl, jk   ! dummy loop indices
+      !!-----------------------------------------------------------------------
+      !
+      SELECT CASE( kn )
+      !                    !---------------------!
+      CASE( 1 )            !==  from 2D to 1D  ==!
+         !                 !---------------------!
+         ! fields used but not modified
+         CALL tab_2d_1d( npti, nptidx(1:npti), sss_1d(1:npti), sss_m(:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sst_1d(1:npti), sst_m(:,:) )
+         ! the following fields are modified in this routine
+         !!CALL tab_2d_1d( npti, nptidx(1:npti), ato_i_1d(1:npti), ato_i(:,:) )
+         !!CALL tab_3d_2d( npti, nptidx(1:npti), a_i_2d(1:npti,1:jpl), a_i(:,:,:) )
+         !!CALL tab_3d_2d( npti, nptidx(1:npti), v_i_2d  (1:npti,1:jpl), v_i  (:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), v_s_2d (1:npti,1:jpl), v_s (:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i(:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), oa_i_2d(1:npti,1:jpl), oa_i(:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), a_ip_2d(1:npti,1:jpl), a_ip(:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), v_ip_2d(1:npti,1:jpl), v_ip(:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), v_il_2d(1:npti,1:jpl), v_il(:,:,:) )
+         DO jl = 1, jpl
+            DO jk = 1, nlay_s
+               CALL tab_2d_1d( npti, nptidx(1:npti), ze_s_2d(1:npti,jk,jl), e_s(:,:,jk,jl) )
+            END DO
+            DO jk = 1, nlay_i
+               CALL tab_2d_1d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+            END DO
+         END DO
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_dyn_1d    (1:npti), sfx_dyn    (:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_bri_1d    (1:npti), sfx_bri    (:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_dyn_1d    (1:npti), wfx_dyn    (:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_dyn_1d    (1:npti), hfx_dyn    (:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_snw_dyn_1d(1:npti), wfx_snw_dyn(:,:) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_pnd_1d    (1:npti), wfx_pnd    (:,:) )
+         !
+         !                 !---------------------!
+      CASE( 2 )            !==  from 1D to 2D  ==!
+         !                 !---------------------!
+         CALL tab_1d_2d( npti, nptidx(1:npti), ato_i_1d(1:npti), ato_i(:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i (:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), v_i_2d (1:npti,1:jpl), v_i (:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), v_s_2d (1:npti,1:jpl), v_s (:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i(:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), oa_i_2d(1:npti,1:jpl), oa_i(:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), a_ip_2d(1:npti,1:jpl), a_ip(:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), v_ip_2d(1:npti,1:jpl), v_ip(:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), v_il_2d(1:npti,1:jpl), v_il(:,:,:) )
+         DO jl = 1, jpl
+            DO jk = 1, nlay_s
+               CALL tab_1d_2d( npti, nptidx(1:npti), ze_s_2d(1:npti,jk,jl), e_s(:,:,jk,jl) )
+            END DO
+            DO jk = 1, nlay_i
+               CALL tab_1d_2d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+            END DO
+         END DO
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_dyn_1d    (1:npti), sfx_dyn    (:,:) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_bri_1d    (1:npti), sfx_bri    (:,:) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_dyn_1d    (1:npti), wfx_dyn    (:,:) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_dyn_1d    (1:npti), hfx_dyn    (:,:) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_snw_dyn_1d(1:npti), wfx_snw_dyn(:,:) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_pnd_1d    (1:npti), wfx_pnd    (:,:) )
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_dyn_1d2d
+   
+
+   SUBROUTINE ice_dyn_rdgrft_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dyn_rdgrft_init ***
+      !!
+      !! ** Purpose :   Physical constants and parameters linked 
+      !!                to the mechanical ice redistribution
+      !!
+      !! ** Method  :   Read the namdyn_rdgrft namelist 
+      !!                and check the parameters values 
+      !!                called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namdyn_rdgrft
+      !!-------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/namdyn_rdgrft/ ln_str_H79, rn_pstar, rn_crhg, &
+         &                    rn_csrdg  ,                    &
+         &                    ln_partf_lin, rn_gstar,        &
+         &                    ln_partf_exp, rn_astar,        & 
+         &                    ln_ridging, rn_hstar, rn_porordg, rn_fsnwrdg, rn_fpndrdg,  & 
+         &                    ln_rafting, rn_hraft, rn_craft  , rn_fsnwrft, rn_fpndrft
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namicetdme in reference namelist : Ice mechanical ice redistribution
+      READ  ( numnam_ice_ref, namdyn_rdgrft, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_rdgrft in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namdyn_rdgrft in configuration namelist : Ice mechanical ice redistribution
+      READ  ( numnam_ice_cfg, namdyn_rdgrft, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_rdgrft in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namdyn_rdgrft )
+      !
+      IF (lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dyn_rdgrft_init: ice parameters for ridging/rafting '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn_rdgrft:'
+         WRITE(numout,*) '      ice strength parameterization Hibler (1979)              ln_str_H79   = ', ln_str_H79 
+         WRITE(numout,*) '            1st bulk-rheology parameter                        rn_pstar     = ', rn_pstar
+         WRITE(numout,*) '            2nd bulk-rhelogy parameter                         rn_crhg      = ', rn_crhg
+         WRITE(numout,*) '      Fraction of shear energy contributing to ridging         rn_csrdg     = ', rn_csrdg 
+         WRITE(numout,*) '      linear ridging participation function                    ln_partf_lin = ', ln_partf_lin
+         WRITE(numout,*) '            Fraction of ice coverage contributing to ridging   rn_gstar     = ', rn_gstar
+         WRITE(numout,*) '      Exponential ridging participation function               ln_partf_exp = ', ln_partf_exp
+         WRITE(numout,*) '            Equivalent to G* for an exponential function       rn_astar     = ', rn_astar
+         WRITE(numout,*) '      Ridging of ice sheets or not                             ln_ridging   = ', ln_ridging
+         WRITE(numout,*) '            max ridged ice thickness                           rn_hstar     = ', rn_hstar
+         WRITE(numout,*) '            Initial porosity of ridges                         rn_porordg   = ', rn_porordg
+         WRITE(numout,*) '            Fraction of snow volume conserved during ridging   rn_fsnwrdg   = ', rn_fsnwrdg 
+         WRITE(numout,*) '            Fraction of pond volume conserved during ridging   rn_fpndrdg   = ', rn_fpndrdg 
+         WRITE(numout,*) '      Rafting of ice sheets or not                             ln_rafting   = ', ln_rafting
+         WRITE(numout,*) '            Parmeter thickness (threshold between ridge-raft)  rn_hraft     = ', rn_hraft
+         WRITE(numout,*) '            Rafting hyperbolic tangent coefficient             rn_craft     = ', rn_craft  
+         WRITE(numout,*) '            Fraction of snow volume conserved during rafting   rn_fsnwrft   = ', rn_fsnwrft 
+         WRITE(numout,*) '            Fraction of pond volume conserved during rafting   rn_fpndrft   = ', rn_fpndrft 
+      ENDIF
+      !
+      IF ( ( ln_partf_lin .AND. ln_partf_exp ) .OR. ( .NOT.ln_partf_lin .AND. .NOT.ln_partf_exp ) ) THEN
+         CALL ctl_stop( 'ice_dyn_rdgrft_init: choose one and only one participation function (ln_partf_lin or ln_partf_exp)' )
+      ENDIF
+      !
+      IF( .NOT. ln_icethd ) THEN
+         rn_porordg = 0._wp
+         rn_fsnwrdg = 1._wp ; rn_fsnwrft = 1._wp
+         rn_fpndrdg = 1._wp ; rn_fpndrft = 1._wp
+         IF( lwp ) THEN
+            WRITE(numout,*) '      ==> only ice dynamics is activated, thus some parameters must be changed'
+            WRITE(numout,*) '            rn_porordg   = ', rn_porordg
+            WRITE(numout,*) '            rn_fsnwrdg   = ', rn_fsnwrdg 
+            WRITE(numout,*) '            rn_fpndrdg   = ', rn_fpndrdg 
+            WRITE(numout,*) '            rn_fsnwrft   = ', rn_fsnwrft 
+            WRITE(numout,*) '            rn_fpndrft   = ', rn_fpndrft 
+         ENDIF
+      ENDIF
+      !                              ! allocate arrays
+      IF( ice_dyn_rdgrft_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'ice_dyn_rdgrft_init: unable to allocate arrays' )
+      !
+  END SUBROUTINE ice_dyn_rdgrft_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icedyn_rdgrft
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg.F90	(revision 14097)
@@ -0,0 +1,158 @@
+MODULE icedyn_rhg
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg  ***
+   !!   Sea-Ice dynamics : master routine for rheology 
+   !!======================================================================
+   !! history :  4.0  !  2018     (C. Rousset)      Original code
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!    ice_dyn_rhg      : computes ice velocities
+   !!    ice_dyn_rhg_init : initialization and namelist read
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain
+   USE ice            ! sea-ice: variables
+   USE icedyn_rhg_evp ! sea-ice: EVP rheology
+   USE icectl         ! sea-ice: control prints
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg        ! called by icestp.F90
+   PUBLIC   ice_dyn_rhg_init   ! called by icestp.F90
+
+   INTEGER ::              nice_rhg   ! choice of the type of rheology
+   !                                        ! associated indices:
+   INTEGER, PARAMETER ::   np_rhgEVP = 1   ! EVP rheology
+!! INTEGER, PARAMETER ::   np_rhgEAP = 2   ! EAP rheology
+
+   ! ** namelist (namrhg) **
+   LOGICAL ::   ln_rhg_EVP       ! EVP rheology
+   !
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg( kt )
+      !!-------------------------------------------------------------------
+      !!               ***  ROUTINE ice_dyn_rhg  ***
+      !!               
+      !! ** Purpose :   compute ice velocity
+      !!
+      !! ** Action  : comupte - ice velocity (u_ice, v_ice)
+      !!                      - 3 components of the stress tensor (stress1_i, stress2_i, stress12_i)
+      !!                      - shear, divergence and delta (shear_i, divu_i, delta_i)
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ice time step
+      !
+      INTEGER  ::   jl   ! dummy loop indices
+      !!--------------------------------------------------------------------
+      ! controls
+      IF( ln_timing    )   CALL timing_start('icedyn_rhg')                                                             ! timing
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'icedyn_rhg', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'icedyn_rhg',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_dyn_rhg: sea-ice rheology'
+         WRITE(numout,*)'~~~~~~~~~~~'
+      ENDIF
+      !
+      !--------------!
+      !== Rheology ==!
+      !--------------!   
+      SELECT CASE( nice_rhg )
+      !                                !------------------------!
+      CASE( np_rhgEVP )                ! Elasto-Viscous-Plastic !
+         !                             !------------------------!
+         CALL ice_dyn_rhg_evp( kt, stress1_i, stress2_i, stress12_i, shear_i, divu_i, delta_i )
+         !         
+      END SELECT
+      !
+      IF( lrst_ice ) THEN                       !* write EVP fields in the restart file
+         IF( ln_rhg_EVP )   CALL rhg_evp_rst( 'WRITE', kt )
+      ENDIF
+      !
+      ! controls
+      IF( ln_ctl       )   CALL ice_prt3D   ('icedyn_rhg')                                                             ! prints
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icedyn_rhg', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'icedyn_rhg',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+      IF( ln_timing    )   CALL timing_stop ('icedyn_rhg')                                                             ! timing
+      !
+   END SUBROUTINE ice_dyn_rhg
+
+
+   SUBROUTINE ice_dyn_rhg_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_dyn_rhg_init  ***
+      !!
+      !! ** Purpose : Physical constants and parameters linked to the ice
+      !!      dynamics
+      !!
+      !! ** Method  :  Read the namdyn_rhg namelist and check the ice-dynamic
+      !!       parameter values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namdyn_rhg
+      !!-------------------------------------------------------------------
+      INTEGER ::   ios, ioptio   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namdyn_rhg/  ln_rhg_EVP, ln_aEVP, rn_creepl, rn_ecc , nn_nevp, rn_relast, nn_rhg_chkcvg
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )         ! Namelist namdyn_rhg in reference namelist : Ice dynamics
+      READ  ( numnam_ice_ref, namdyn_rhg, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namdyn_rhg in reference namelist' )
+      REWIND( numnam_ice_cfg )         ! Namelist namdyn_rhg in configuration namelist : Ice dynamics
+      READ  ( numnam_ice_cfg, namdyn_rhg, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namdyn_rhg in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namdyn_rhg )
+      !
+      IF(lwp) THEN                     ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_dyn_rhg_init: ice parameters for ice dynamics '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist : namdyn_rhg:'
+         WRITE(numout,*) '      rheology EVP (icedyn_rhg_evp)                        ln_rhg_EVP    = ', ln_rhg_EVP
+         WRITE(numout,*) '         use adaptive EVP (aEVP)                           ln_aEVP       = ', ln_aEVP
+         WRITE(numout,*) '         creep limit                                       rn_creepl     = ', rn_creepl
+         WRITE(numout,*) '         eccentricity of the elliptical yield curve        rn_ecc        = ', rn_ecc
+         WRITE(numout,*) '         number of iterations for subcycling               nn_nevp       = ', nn_nevp
+         WRITE(numout,*) '         ratio of elastic timescale over ice time step     rn_relast     = ', rn_relast
+         WRITE(numout,*) '      check convergence of rheology                        nn_rhg_chkcvg = ', nn_rhg_chkcvg
+         IF    ( nn_rhg_chkcvg == 0 ) THEN   ;   WRITE(numout,*) '         no check'
+         ELSEIF( nn_rhg_chkcvg == 1 ) THEN   ;   WRITE(numout,*) '         check cvg at the main time step'
+         ELSEIF( nn_rhg_chkcvg == 2 ) THEN   ;   WRITE(numout,*) '         check cvg at both main and rheology time steps'
+         ENDIF
+      ENDIF
+      !
+      !                             !== set the choice of ice advection ==!
+      ioptio = 0 
+      IF( ln_rhg_EVP ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgEVP    ;   ENDIF
+!!    IF( ln_rhg_EAP ) THEN   ;   ioptio = ioptio + 1   ;   nice_rhg = np_rhgEAP    ;   ENDIF
+      IF( ioptio /= 1 )   CALL ctl_stop( 'ice_dyn_rhg_init: choose one and only one ice rheology' )
+      !
+      IF( ln_rhg_EVP  )   CALL rhg_evp_rst( 'READ' )  !* read or initialize all required files
+      !
+   END SUBROUTINE ice_dyn_rhg_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif 
+
+   !!======================================================================
+END MODULE icedyn_rhg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg_evp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg_evp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icedyn_rhg_evp.F90	(revision 14097)
@@ -0,0 +1,1097 @@
+MODULE icedyn_rhg_evp
+   !!======================================================================
+   !!                     ***  MODULE  icedyn_rhg_evp  ***
+   !!   Sea-Ice dynamics : rheology Elasto-Viscous-Plastic
+   !!======================================================================
+   !! History :   -   !  2007-03  (M.A. Morales Maqueda, S. Bouillon) Original code
+   !!            3.0  !  2008-03  (M. Vancoppenolle) adaptation to new model
+   !!             -   !  2008-11  (M. Vancoppenolle, S. Bouillon, Y. Aksenov) add surface tilt in ice rheolohy 
+   !!            3.3  !  2009-05  (G.Garric)    addition of the evp case
+   !!            3.4  !  2011-01  (A. Porter)   dynamical allocation 
+   !!            3.5  !  2012-08  (R. Benshila) AGRIF
+   !!            3.6  !  2016-06  (C. Rousset)  Rewriting + landfast ice + mEVP (Bouillon 2013)
+   !!            3.7  !  2017     (C. Rousset)  add aEVP (Kimmritz 2016-2017)
+   !!            4.0  !  2018     (many people) SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_dyn_rhg_evp : computes ice velocities from EVP rheology
+   !!   rhg_evp_rst     : read/write EVP fields in ice restart
+   !!----------------------------------------------------------------------
+   USE phycst         ! Physical constant
+   USE dom_oce        ! Ocean domain
+   USE sbc_oce , ONLY : ln_ice_embd, nn_fsbc, ssh_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice, snwice_mass, snwice_mass_b
+   USE ice            ! sea-ice: ice variables
+   USE icevar         ! ice_var_sshdyn
+   USE icedyn_rdgrft  ! sea-ice: ice strength
+   USE bdy_oce , ONLY : ln_bdy 
+   USE bdyice 
+#if defined key_agrif
+   USE agrif_ice_interp
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE prtctl         ! Print control
+
+   USE netcdf         ! NetCDF library for convergence test
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_dyn_rhg_evp   ! called by icedyn_rhg.F90
+   PUBLIC   rhg_evp_rst       ! called by icedyn_rhg.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+
+   !! for convergence tests
+   INTEGER ::   ncvgid   ! netcdf file id
+   INTEGER ::   nvarid   ! netcdf variable id
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zmsk00, zmsk15
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_dyn_rhg_evp( kt, pstress1_i, pstress2_i, pstress12_i, pshear_i, pdivu_i, pdelta_i )
+      !!-------------------------------------------------------------------
+      !!                 ***  SUBROUTINE ice_dyn_rhg_evp  ***
+      !!                             EVP-C-grid
+      !!
+      !! ** purpose : determines sea ice drift from wind stress, ice-ocean
+      !!  stress and sea-surface slope. Ice-ice interaction is described by 
+      !!  a non-linear elasto-viscous-plastic (EVP) law including shear 
+      !!  strength and a bulk rheology (Hunke and Dukowicz, 2002).	
+      !!
+      !!  The points in the C-grid look like this, dear reader
+      !!
+      !!                              (ji,jj)
+      !!                                 |
+      !!                                 |
+      !!                      (ji-1,jj)  |  (ji,jj)
+      !!                             ---------   
+      !!                            |         |
+      !!                            | (ji,jj) |------(ji,jj)
+      !!                            |         |
+      !!                             ---------   
+      !!                     (ji-1,jj-1)     (ji,jj-1)
+      !!
+      !! ** Inputs  : - wind forcing (stress), oceanic currents
+      !!                ice total volume (vt_i) per unit area
+      !!                snow total volume (vt_s) per unit area
+      !!
+      !! ** Action  : - compute u_ice, v_ice : the components of the 
+      !!                sea-ice velocity vector
+      !!              - compute delta_i, shear_i, divu_i, which are inputs
+      !!                of the ice thickness distribution
+      !!
+      !! ** Steps   : 0) compute mask at F point
+      !!              1) Compute ice snow mass, ice strength 
+      !!              2) Compute wind, oceanic stresses, mass terms and
+      !!                 coriolis terms of the momentum equation
+      !!              3) Solve the momentum equation (iterative procedure)
+      !!              4) Recompute delta, shear and divergence
+      !!                 (which are inputs of the ITD) & store stress
+      !!                 for the next time step
+      !!              5) Diagnostics including charge ellipse
+      !!
+      !! ** Notes   : There is the possibility to use aEVP from the nice work of Kimmritz et al. (2016 & 2017)
+      !!              by setting up ln_aEVP=T (i.e. changing alpha and beta parameters).
+      !!              This is an upgraded version of mEVP from Bouillon et al. 2013
+      !!              (i.e. more stable and better convergence)
+      !!
+      !! References : Hunke and Dukowicz, JPO97
+      !!              Bouillon et al., Ocean Modelling 2009
+      !!              Bouillon et al., Ocean Modelling 2013
+      !!              Kimmritz et al., Ocean Modelling 2016 & 2017
+      !!-------------------------------------------------------------------
+      INTEGER                 , INTENT(in   ) ::   kt                                    ! time step
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pstress1_i, pstress2_i, pstress12_i   !
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pshear_i  , pdivu_i   , pdelta_i      !
+      !!
+      INTEGER ::   ji, jj       ! dummy loop indices
+      INTEGER ::   jter         ! local integers
+      !
+      REAL(wp) ::   zrhoco                                              ! rau0 * rn_cio
+      REAL(wp) ::   zdtevp, z1_dtevp                                    ! time step for subcycling
+      REAL(wp) ::   ecc2, z1_ecc2                                       ! square of yield ellipse eccenticity
+      REAL(wp) ::   zalph1, z1_alph1, zalph2, z1_alph2                  ! alpha coef from Bouillon 2009 or Kimmritz 2017
+      REAl(wp) ::   zbetau, zbetav
+      REAL(wp) ::   zm1, zm2, zm3, zmassU, zmassV, zvU, zvV             ! ice/snow mass and volume
+      REAL(wp) ::   zp_delf, zds2, zdt, zdt2, zdiv, zdiv2               ! temporary scalars
+      REAL(wp) ::   zTauO, zTauB, zRHS, zvel                            ! temporary scalars
+      REAL(wp) ::   zkt                                                 ! isotropic tensile strength for landfast ice
+      REAL(wp) ::   zvCr                                                ! critical ice volume above which ice is landfast
+      !
+      REAL(wp) ::   zintb, zintn                                        ! dummy argument
+      REAL(wp) ::   zfac_x, zfac_y
+      REAL(wp) ::   zshear, zdum1, zdum2
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdelta, zp_delt                 ! delta and P/delta at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zten_i                          ! tension
+      REAL(wp), DIMENSION(jpi,jpj) ::   zbeta                           ! beta coef from Kimmritz 2017
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdt_m                           ! (dt / ice-snow_mass) on T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zaU  , zaV                      ! ice fraction on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmU_t, zmV_t                    ! (ice-snow_mass / dt) on U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmf                             ! coriolis parameter at T points
+      REAL(wp), DIMENSION(jpi,jpj) ::   v_oceU, u_oceV, v_iceU, u_iceV  ! ocean/ice u/v component on V/U points
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zds                             ! shear
+      REAL(wp), DIMENSION(jpi,jpj) ::   zs1, zs2, zs12                  ! stress tensor components
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsshdyn                         ! array used for the calculation of ice surface slope:
+      !                                                                 !    ocean surface (ssh_m) if ice is not embedded
+      !                                                                 !    ice bottom surface if ice is embedded   
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfU  , zfV                      ! internal stresses
+      REAL(wp), DIMENSION(jpi,jpj) ::   zspgU, zspgV                    ! surface pressure gradient at U/V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   zCorU, zCorV                    ! Coriolis stress array
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_ai, ztauy_ai              ! ice-atm. stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_oi, ztauy_oi              ! ice-ocean stress at U-V points
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_bi, ztauy_bi              ! ice-OceanBottom stress at U-V points (landfast)
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztaux_base, ztauy_base          ! ice-bottom stress at U-V points (landfast)
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk01x, zmsk01y                ! dummy arrays
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk00x, zmsk00y                ! mask for ice presence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfmask                          ! mask at F points for the ice
+
+      REAL(wp), PARAMETER          ::   zepsi  = 1.0e-20_wp             ! tolerance parameter
+      REAL(wp), PARAMETER          ::   zmmin  = 1._wp                  ! ice mass (kg/m2)  below which ice velocity becomes very small
+      REAL(wp), PARAMETER          ::   zamin  = 0.001_wp               ! ice concentration below which ice velocity becomes very small
+      !! --- check convergence
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_ice, zv_ice
+      !! --- diags
+      REAL(wp) ::   zsig1, zsig2, zsig12, zfac, z1_strength
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zsig_I, zsig_II, zsig1_p, zsig2_p         
+      !! --- SIMIP diags
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_ice ! X-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_ice ! Y-component of ice mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xmtrp_snw ! X-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_ymtrp_snw ! Y-component of snow mass transport (kg/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_xatrp     ! X-component of area transport (m2/s)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdiag_yatrp     ! Y-component of area transport (m2/s)      
+      !!-------------------------------------------------------------------
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_dyn_rhg_evp: EVP sea-ice rheology'
+      !
+      ! for diagnostics and convergence tests
+      ALLOCATE( zmsk00(jpi,jpj), zmsk15(jpi,jpj) )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+            zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+         END DO
+      END DO
+      !
+      !!gm for Clem:  OPTIMIZATION:  I think zfmask can be computed one for all at the initialization....
+      !------------------------------------------------------------------------------!
+      ! 0) mask at F points for the ice
+      !------------------------------------------------------------------------------!
+      ! ocean/land mask
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1      ! NO vector opt.
+            zfmask(ji,jj) = tmask(ji,jj,1) * tmask(ji+1,jj,1) * tmask(ji,jj+1,1) * tmask(ji+1,jj+1,1)
+         END DO
+      END DO
+      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp )
+
+      ! Lateral boundary conditions on velocity (modify zfmask)
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            IF( zfmask(ji,jj) == 0._wp ) THEN
+               zfmask(ji,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(ji,jj,1), umask(ji,jj+1,1), &
+                  &                                          vmask(ji,jj,1), vmask(ji+1,jj,1) ) )
+            ENDIF
+         END DO
+      END DO
+      DO jj = 2, jpjm1
+         IF( zfmask(1,jj) == 0._wp ) THEN
+            zfmask(1  ,jj) = rn_ishlat * MIN( 1._wp , MAX( vmask(2,jj,1), umask(1,jj+1,1), umask(1,jj,1) ) )
+         ENDIF
+         IF( zfmask(jpi,jj) == 0._wp ) THEN
+            zfmask(jpi,jj) = rn_ishlat * MIN( 1._wp , MAX( umask(jpi,jj+1,1), vmask(jpim1,jj,1), umask(jpi,jj-1,1) ) )
+        ENDIF
+      END DO
+      DO ji = 2, jpim1
+         IF( zfmask(ji,1) == 0._wp ) THEN
+            zfmask(ji, 1 ) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,1,1), umask(ji,2,1), vmask(ji,1,1) ) )
+         ENDIF
+         IF( zfmask(ji,jpj) == 0._wp ) THEN
+            zfmask(ji,jpj) = rn_ishlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,1), vmask(ji-1,jpj,1), umask(ji,jpjm1,1) ) )
+         ENDIF
+      END DO
+      CALL lbc_lnk( 'icedyn_rhg_evp', zfmask, 'F', 1._wp )
+
+      !------------------------------------------------------------------------------!
+      ! 1) define some variables and initialize arrays
+      !------------------------------------------------------------------------------!
+      zrhoco = rau0 * rn_cio 
+
+      ! ecc2: square of yield ellipse eccenticrity
+      ecc2    = rn_ecc * rn_ecc
+      z1_ecc2 = 1._wp / ecc2
+
+      ! alpha parameters (Bouillon 2009)
+      IF( .NOT. ln_aEVP ) THEN
+         zdtevp   = rdt_ice / REAL( nn_nevp )
+         zalph1 =   2._wp * rn_relast * REAL( nn_nevp )
+         zalph2 = zalph1 * z1_ecc2
+
+         z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+         z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+      ELSE
+         zdtevp   = rdt_ice
+         ! zalpha parameters set later on adaptatively
+      ENDIF
+      z1_dtevp = 1._wp / zdtevp
+         
+      ! Initialise stress tensor 
+      zs1 (:,:) = pstress1_i (:,:) 
+      zs2 (:,:) = pstress2_i (:,:)
+      zs12(:,:) = pstress12_i(:,:)
+
+      ! Ice strength
+      CALL ice_strength
+
+      ! landfast param from Lemieux(2016): add isotropic tensile strength (following Konig Beatty and Holland, 2010)
+      IF( ln_landfast_L16 ) THEN   ;   zkt = rn_lf_tensile
+      ELSE                         ;   zkt = 0._wp
+      ENDIF
+      !
+      !------------------------------------------------------------------------------!
+      ! 2) Wind / ocean stress, mass terms, coriolis terms
+      !------------------------------------------------------------------------------!
+      ! sea surface height
+      !    embedded sea ice: compute representative ice top surface
+      !    non-embedded sea ice: use ocean surface for slope calculation
+      zsshdyn(:,:) = ice_var_sshdyn( ssh_m, snwice_mass, snwice_mass_b)
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1
+
+            ! ice fraction at U-V points
+            zaU(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zaV(ji,jj) = 0.5_wp * ( at_i(ji,jj) * e1e2t(ji,jj) + at_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+            ! Ice/snow mass at U-V points
+            zm1 = ( rhos * vt_s(ji  ,jj  ) + rhoi * vt_i(ji  ,jj  ) )
+            zm2 = ( rhos * vt_s(ji+1,jj  ) + rhoi * vt_i(ji+1,jj  ) )
+            zm3 = ( rhos * vt_s(ji  ,jj+1) + rhoi * vt_i(ji  ,jj+1) )
+            zmassU = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm2 * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+            zmassV = 0.5_wp * ( zm1 * e1e2t(ji,jj) + zm3 * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+
+            ! Ocean currents at U-V points
+            v_oceU(ji,jj)   = 0.25_wp * ( v_oce(ji,jj) + v_oce(ji,jj-1) + v_oce(ji+1,jj) + v_oce(ji+1,jj-1) ) * umask(ji,jj,1)
+            u_oceV(ji,jj)   = 0.25_wp * ( u_oce(ji,jj) + u_oce(ji-1,jj) + u_oce(ji,jj+1) + u_oce(ji-1,jj+1) ) * vmask(ji,jj,1)
+
+            ! Coriolis at T points (m*f)
+            zmf(ji,jj)      = zm1 * ff_t(ji,jj)
+
+            ! dt/m at T points (for alpha and beta coefficients)
+            zdt_m(ji,jj)    = zdtevp / MAX( zm1, zmmin )
+            
+            ! m/dt
+            zmU_t(ji,jj)    = zmassU * z1_dtevp
+            zmV_t(ji,jj)    = zmassV * z1_dtevp
+            
+            ! Drag ice-atm.
+            ztaux_ai(ji,jj) = zaU(ji,jj) * utau_ice(ji,jj)
+            ztauy_ai(ji,jj) = zaV(ji,jj) * vtau_ice(ji,jj)
+
+            ! Surface pressure gradient (- m*g*GRAD(ssh)) at U-V points
+            zspgU(ji,jj)    = - zmassU * grav * ( zsshdyn(ji+1,jj) - zsshdyn(ji,jj) ) * r1_e1u(ji,jj)
+            zspgV(ji,jj)    = - zmassV * grav * ( zsshdyn(ji,jj+1) - zsshdyn(ji,jj) ) * r1_e2v(ji,jj)
+
+            ! masks
+            zmsk00x(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassU ) )  ! 0 if no ice
+            zmsk00y(ji,jj) = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zmassV ) )  ! 0 if no ice
+
+            ! switches
+            IF( zmassU <= zmmin .AND. zaU(ji,jj) <= zamin ) THEN   ;   zmsk01x(ji,jj) = 0._wp
+            ELSE                                                   ;   zmsk01x(ji,jj) = 1._wp   ;   ENDIF
+            IF( zmassV <= zmmin .AND. zaV(ji,jj) <= zamin ) THEN   ;   zmsk01y(ji,jj) = 0._wp
+            ELSE                                                   ;   zmsk01y(ji,jj) = 1._wp   ;   ENDIF
+
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'icedyn_rhg_evp', zmf, 'T', 1., zdt_m, 'T', 1. )
+      !
+      !                                  !== Landfast ice parameterization ==!
+      !
+      IF( ln_landfast_L16 ) THEN         !-- Lemieux 2016
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ! ice thickness at U-V points
+               zvU = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji+1,jj) * e1e2t(ji+1,jj) ) * r1_e1e2u(ji,jj) * umask(ji,jj,1)
+               zvV = 0.5_wp * ( vt_i(ji,jj) * e1e2t(ji,jj) + vt_i(ji,jj+1) * e1e2t(ji,jj+1) ) * r1_e1e2v(ji,jj) * vmask(ji,jj,1)
+               ! ice-bottom stress at U points
+               zvCr = zaU(ji,jj) * rn_lf_depfra * hu_n(ji,jj)
+               ztaux_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvU - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaU(ji,jj) ) )
+               ! ice-bottom stress at V points
+               zvCr = zaV(ji,jj) * rn_lf_depfra * hv_n(ji,jj)
+               ztauy_base(ji,jj) = - rn_lf_bfr * MAX( 0._wp, zvV - zvCr ) * EXP( -rn_crhg * ( 1._wp - zaV(ji,jj) ) )
+               ! ice_bottom stress at T points
+               zvCr = at_i(ji,jj) * rn_lf_depfra * ht_n(ji,jj)
+               tau_icebfr(ji,jj) = - rn_lf_bfr * MAX( 0._wp, vt_i(ji,jj) - zvCr ) * EXP( -rn_crhg * ( 1._wp - at_i(ji,jj) ) )
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_rhg_evp', tau_icebfr(:,:), 'T', 1. )
+         !
+      ELSE                               !-- no landfast
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ztaux_base(ji,jj) = 0._wp
+               ztauy_base(ji,jj) = 0._wp
+            END DO
+         END DO
+      ENDIF
+
+      !------------------------------------------------------------------------------!
+      ! 3) Solution of the momentum equation, iterative procedure
+      !------------------------------------------------------------------------------!
+      !
+      !                                               ! ==================== !
+      DO jter = 1 , nn_nevp                           !    loop over jter    !
+         !                                            ! ==================== !        
+         l_full_nf_update = jter == nn_nevp   ! false: disable full North fold update (performances) for iter = 1 to nn_nevp-1
+         !
+         ! convergence test
+         IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2  ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zu_ice(ji,jj) = u_ice(ji,jj) * umask(ji,jj,1) ! velocity at previous time step
+                  zv_ice(ji,jj) = v_ice(ji,jj) * vmask(ji,jj,1)
+               END DO
+            END DO
+         ENDIF
+
+         ! --- divergence, tension & shear (Appendix B of Hunke & Dukowicz, 2002) --- !
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+
+               ! shear at F points
+               zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+                  &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+                  &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+            END DO
+         END DO
+
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1 ! no vector loop
+
+               ! shear**2 at T points (doc eq. A16)
+               zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+                  &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+                  &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+              
+               ! divergence at T points
+               zdiv  = ( 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)   &
+                  &    ) * r1_e1e2t(ji,jj)
+               zdiv2 = zdiv * zdiv
+               
+               ! tension at T points
+               zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+                  &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+                  &   ) * r1_e1e2t(ji,jj)
+               zdt2 = zdt * zdt
+               
+               ! delta at T points
+               zdelta(ji,jj) = SQRT( zdiv2 + ( zdt2 + zds2 ) * z1_ecc2 )  
+
+            END DO
+         END DO
+         CALL lbc_lnk( 'icedyn_rhg_evp', zdelta, 'T', 1._wp )
+         
+         ! P/delta at T points
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zp_delt(ji,jj) = strength(ji,jj) / ( zdelta(ji,jj) + rn_creepl )
+            END DO
+         END DO
+
+         DO jj = 2, jpj    ! loop ends at jpi,jpj so that no lbc_lnk are needed for zs1 and zs2
+            DO ji = 2, jpi ! no vector loop
+
+               ! divergence at T points (duplication to avoid communications)
+               zdiv  = ( 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)   &
+                  &    ) * r1_e1e2t(ji,jj)
+               
+               ! tension at T points (duplication to avoid communications)
+               zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+                  &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+                  &   ) * r1_e1e2t(ji,jj)
+
+               ! alpha for aEVP
+               !   gamma = 0.5*P/(delta+creepl) * (c*pi)**2/Area * dt/m
+               !   alpha = beta = sqrt(4*gamma)
+               IF( ln_aEVP ) THEN
+                  zalph1   = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+                  z1_alph1 = 1._wp / ( zalph1 + 1._wp )
+                  zalph2   = zalph1
+                  z1_alph2 = z1_alph1
+                  ! explicit:
+                  ! z1_alph1 = 1._wp / zalph1
+                  ! z1_alph2 = 1._wp / zalph1
+                  ! zalph1 = zalph1 - 1._wp
+                  ! zalph2 = zalph1
+               ENDIF
+               
+               ! stress at T points (zkt/=0 if landfast)
+               zs1(ji,jj) = ( zs1(ji,jj)*zalph1 + zp_delt(ji,jj) * ( zdiv*(1._wp + zkt) - zdelta(ji,jj)*(1._wp - zkt) ) ) * z1_alph1
+               zs2(ji,jj) = ( zs2(ji,jj)*zalph2 + zp_delt(ji,jj) * ( zdt * z1_ecc2 * (1._wp + zkt) ) ) * z1_alph2
+             
+            END DO
+         END DO
+
+         ! Save beta at T-points for further computations
+         IF( ln_aEVP ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zbeta(ji,jj) = MAX( 50._wp, rpi * SQRT( 0.5_wp * zp_delt(ji,jj) * r1_e1e2t(ji,jj) * zdt_m(ji,jj) ) )
+               END DO
+            END DO
+         ENDIF
+         
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+
+               ! alpha for aEVP
+               IF( ln_aEVP ) THEN
+                  zalph2   = MAX( zbeta(ji,jj), zbeta(ji+1,jj), zbeta(ji,jj+1), zbeta(ji+1,jj+1) )
+                  z1_alph2 = 1._wp / ( zalph2 + 1._wp )
+                  ! explicit:
+                  ! z1_alph2 = 1._wp / zalph2
+                  ! zalph2 = zalph2 - 1._wp
+               ENDIF
+               
+               ! P/delta at F points
+               zp_delf = 0.25_wp * ( zp_delt(ji,jj) + zp_delt(ji+1,jj) + zp_delt(ji,jj+1) + zp_delt(ji+1,jj+1) )
+               
+               ! stress at F points (zkt/=0 if landfast)
+               zs12(ji,jj)= ( zs12(ji,jj) * zalph2 + zp_delf * ( zds(ji,jj) * z1_ecc2 * (1._wp + zkt) ) * 0.5_wp ) * z1_alph2
+
+            END DO
+         END DO
+
+         ! --- Ice internal stresses (Appendix C of Hunke and Dukowicz, 2002) --- !
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1               
+               !                   !--- U points
+               zfU(ji,jj) = 0.5_wp * ( ( zs1(ji+1,jj) - zs1(ji,jj) ) * e2u(ji,jj)                                             &
+                  &                  + ( zs2(ji+1,jj) * e2t(ji+1,jj) * e2t(ji+1,jj) - zs2(ji,jj) * e2t(ji,jj) * e2t(ji,jj)    &
+                  &                    ) * r1_e2u(ji,jj)                                                                      &
+                  &                  + ( zs12(ji,jj) * e1f(ji,jj) * e1f(ji,jj) - zs12(ji,jj-1) * e1f(ji,jj-1) * e1f(ji,jj-1)  &
+                  &                    ) * 2._wp * r1_e1u(ji,jj)                                                              &
+                  &                  ) * r1_e1e2u(ji,jj)
+               !
+               !                !--- V points
+               zfV(ji,jj) = 0.5_wp * ( ( zs1(ji,jj+1) - zs1(ji,jj) ) * e1v(ji,jj)                                             &
+                  &                  - ( zs2(ji,jj+1) * e1t(ji,jj+1) * e1t(ji,jj+1) - zs2(ji,jj) * e1t(ji,jj) * e1t(ji,jj)    &
+                  &                    ) * r1_e1v(ji,jj)                                                                      &
+                  &                  + ( zs12(ji,jj) * e2f(ji,jj) * e2f(ji,jj) - zs12(ji-1,jj) * e2f(ji-1,jj) * e2f(ji-1,jj)  &
+                  &                    ) * 2._wp * r1_e2v(ji,jj)                                                              &
+                  &                  ) * r1_e1e2v(ji,jj)
+               !
+               !                !--- ice currents at U-V point
+               v_iceU(ji,jj) = 0.25_wp * ( v_ice(ji,jj) + v_ice(ji,jj-1) + v_ice(ji+1,jj) + v_ice(ji+1,jj-1) ) * umask(ji,jj,1)
+               u_iceV(ji,jj) = 0.25_wp * ( u_ice(ji,jj) + u_ice(ji-1,jj) + u_ice(ji,jj+1) + u_ice(ji-1,jj+1) ) * vmask(ji,jj,1)
+               !
+            END DO
+         END DO
+         !
+         ! --- Computation of ice velocity --- !
+         !  Bouillon et al. 2013 (eq 47-48) => unstable unless alpha, beta vary as in Kimmritz 2016 & 2017
+         !  Bouillon et al. 2009 (eq 34-35) => stable
+         IF( MOD(jter,2) == 0 ) THEN ! even iterations
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  !                 !--- tau_io/(v_oce - v_ice)
+                  zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                     &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+                  !                 !--- Ocean-to-Ice stress
+                  ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+                  !
+                  !                 !--- tau_bottom/v_ice
+                  zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+                  zTauB = ztauy_base(ji,jj) / zvel
+                  !                 !--- OceanBottom-to-Ice stress
+                  ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+                  !
+                  !                 !--- Coriolis at V-points (energy conserving formulation)
+                  zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                     &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                     &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+                  !
+                  !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+                  zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+                  !
+                  !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+                  !                                         1 = sliding friction : TauB < RHS
+                  rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+                  !
+                  IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                     zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                     v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                        &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   & 
+                        &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                        &                                    ) / ( zbetav + 1._wp )                                              &
+                        &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                        &           )   * zmsk00y(ji,jj)
+                  ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                     v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * v_ice(ji,jj)                                       & ! previous velocity
+                        &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                        &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                        &            )  * zmsk00y(ji,jj)
+                  ENDIF
+               END DO
+            END DO
+            CALL lbc_lnk( 'icedyn_rhg_evp', v_ice, 'V', -1. )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1          
+                  !                 !--- tau_io/(u_oce - u_ice)
+                  zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                     &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+                  !                 !--- Ocean-to-Ice stress
+                  ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+                  !
+                  !                 !--- tau_bottom/u_ice
+                  zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+                  zTauB = ztaux_base(ji,jj) / zvel
+                  !                 !--- OceanBottom-to-Ice stress
+                  ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+                  !
+                  !                 !--- Coriolis at U-points (energy conserving formulation)
+                  zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                     &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                     &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+                  !
+                  !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+                  zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+                  !
+                  !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+                  !                                         1 = sliding friction : TauB < RHS
+                  rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+                  !
+                  IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                     zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                     u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                        &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                        &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                        &                                    ) / ( zbetau + 1._wp )                                              &
+                        &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                        &           )   * zmsk00x(ji,jj)
+                  ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                     u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * u_ice(ji,jj)                                       & ! previous velocity
+                        &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                        &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                        &           )   * zmsk00x(ji,jj)
+                  ENDIF
+               END DO
+            END DO
+            CALL lbc_lnk( 'icedyn_rhg_evp', u_ice, 'U', -1. )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+         ELSE ! odd iterations
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  !                 !--- tau_io/(u_oce - u_ice)
+                  zTauO = zaU(ji,jj) * zrhoco * SQRT( ( u_ice (ji,jj) - u_oce (ji,jj) ) * ( u_ice (ji,jj) - u_oce (ji,jj) )  &
+                     &                              + ( v_iceU(ji,jj) - v_oceU(ji,jj) ) * ( v_iceU(ji,jj) - v_oceU(ji,jj) ) )
+                  !                 !--- Ocean-to-Ice stress
+                  ztaux_oi(ji,jj) = zTauO * ( u_oce(ji,jj) - u_ice(ji,jj) )
+                  !
+                  !                 !--- tau_bottom/u_ice
+                  zvel  = 5.e-05_wp + SQRT( v_iceU(ji,jj) * v_iceU(ji,jj) + u_ice(ji,jj) * u_ice(ji,jj) )
+                  zTauB = ztaux_base(ji,jj) / zvel
+                  !                 !--- OceanBottom-to-Ice stress
+                  ztaux_bi(ji,jj) = zTauB * u_ice(ji,jj)
+                  !
+                  !                 !--- Coriolis at U-points (energy conserving formulation)
+                  zCorU(ji,jj)  =   0.25_wp * r1_e1u(ji,jj) *  &
+                     &    ( zmf(ji  ,jj) * ( e1v(ji  ,jj) * v_ice(ji  ,jj) + e1v(ji  ,jj-1) * v_ice(ji  ,jj-1) )  &
+                     &    + zmf(ji+1,jj) * ( e1v(ji+1,jj) * v_ice(ji+1,jj) + e1v(ji+1,jj-1) * v_ice(ji+1,jj-1) ) )
+                  !
+                  !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+                  zRHS = zfU(ji,jj) + ztaux_ai(ji,jj) + zCorU(ji,jj) + zspgU(ji,jj) + ztaux_oi(ji,jj)
+                  !
+                  !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+                  !                                         1 = sliding friction : TauB < RHS
+                  rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztaux_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+                  !
+                  IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                     zbetau = MAX( zbeta(ji,jj), zbeta(ji+1,jj) )
+                     u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * ( zbetau * u_ice(ji,jj) + u_ice_b(ji,jj) )         & ! previous velocity
+                        &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmU_t(ji,jj) * ( zbetau + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) * (  u_ice_b(ji,jj)                                                   &
+                        &                                     + u_ice  (ji,jj) * MAX( 0._wp, zbetau - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                        &                                    ) / ( zbetau + 1._wp )                                              &
+                        &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin 
+                        &           )   * zmsk00x(ji,jj)
+                  ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                     u_ice(ji,jj) = ( (          rswitch   * ( zmU_t(ji,jj) * u_ice(ji,jj)                                       & ! previous velocity
+                        &                                    + zRHS + zTauO * u_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmU_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) *   u_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                        &             ) * zmsk01x(ji,jj) + u_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01x(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                        &           )   * zmsk00x(ji,jj)
+                  ENDIF
+               END DO
+            END DO
+            CALL lbc_lnk( 'icedyn_rhg_evp', u_ice, 'U', -1. )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'U', jter, nn_nevp )
+            CALL agrif_interp_ice( 'U' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'U' )
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  !                 !--- tau_io/(v_oce - v_ice)
+                  zTauO = zaV(ji,jj) * zrhoco * SQRT( ( v_ice (ji,jj) - v_oce (ji,jj) ) * ( v_ice (ji,jj) - v_oce (ji,jj) )  &
+                     &                              + ( u_iceV(ji,jj) - u_oceV(ji,jj) ) * ( u_iceV(ji,jj) - u_oceV(ji,jj) ) )
+                  !                 !--- Ocean-to-Ice stress
+                  ztauy_oi(ji,jj) = zTauO * ( v_oce(ji,jj) - v_ice(ji,jj) )
+                  !
+                  !                 !--- tau_bottom/v_ice
+                  zvel  = 5.e-05_wp + SQRT( v_ice(ji,jj) * v_ice(ji,jj) + u_iceV(ji,jj) * u_iceV(ji,jj) )
+                  zTauB = ztauy_base(ji,jj) / zvel
+                  !                 !--- OceanBottom-to-Ice stress
+                  ztauy_bi(ji,jj) = zTauB * v_ice(ji,jj)
+                  !
+                  !                 !--- Coriolis at v-points (energy conserving formulation)
+                  zCorV(ji,jj)  = - 0.25_wp * r1_e2v(ji,jj) *  &
+                     &    ( zmf(ji,jj  ) * ( e2u(ji,jj  ) * u_ice(ji,jj  ) + e2u(ji-1,jj  ) * u_ice(ji-1,jj  ) )  &
+                     &    + zmf(ji,jj+1) * ( e2u(ji,jj+1) * u_ice(ji,jj+1) + e2u(ji-1,jj+1) * u_ice(ji-1,jj+1) ) )
+                  !
+                  !                 !--- Sum of external forces (explicit solution) = F + tau_ia + Coriolis + spg + tau_io
+                  zRHS = zfV(ji,jj) + ztauy_ai(ji,jj) + zCorV(ji,jj) + zspgV(ji,jj) + ztauy_oi(ji,jj)
+                  !
+                  !                 !--- landfast switch => 0 = static  friction : TauB > RHS & sign(TauB) /= sign(RHS)
+                  !                                         1 = sliding friction : TauB < RHS
+                  rswitch = 1._wp - MIN( 1._wp, ABS( SIGN( 1._wp, zRHS + ztauy_base(ji,jj) ) - SIGN( 1._wp, zRHS ) ) )
+                  !
+                  IF( ln_aEVP ) THEN !--- ice velocity using aEVP (Kimmritz et al 2016 & 2017)
+                     zbetav = MAX( zbeta(ji,jj), zbeta(ji,jj+1) )
+                     v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * ( zbetav * v_ice(ji,jj) + v_ice_b(ji,jj) )         & ! previous velocity
+                        &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmV_t(ji,jj) * ( zbetav + 1._wp ) + zTauO - zTauB ) & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) * (  v_ice_b(ji,jj)                                                   &
+                        &                                     + v_ice  (ji,jj) * MAX( 0._wp, zbetav - zdtevp * rn_lf_relax )     & ! static friction => slow decrease to v=0
+                        &                                    ) / ( zbetav + 1._wp )                                              & 
+                        &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                        &           )   * zmsk00y(ji,jj)
+                  ELSE               !--- ice velocity using EVP implicit formulation (cf Madec doc & Bouillon 2009)
+                     v_ice(ji,jj) = ( (          rswitch   * ( zmV_t(ji,jj) * v_ice(ji,jj)                                       & ! previous velocity
+                        &                                    + zRHS + zTauO * v_ice(ji,jj)                                       & ! F + tau_ia + Coriolis + spg + tau_io(only ocean part)
+                        &                                    ) / MAX( zepsi, zmV_t(ji,jj) + zTauO - zTauB )                      & ! m/dt + tau_io(only ice part) + landfast
+                        &            + ( 1._wp - rswitch ) *   v_ice(ji,jj) * MAX( 0._wp, 1._wp - zdtevp * rn_lf_relax )         & ! static friction => slow decrease to v=0
+                        &             ) * zmsk01y(ji,jj) + v_oce(ji,jj) * 0.01_wp * ( 1._wp - zmsk01y(ji,jj) )                   & ! v_ice = v_oce/100 if mass < zmmin & conc < zamin
+                        &           )   * zmsk00y(ji,jj)
+                  ENDIF
+               END DO
+            END DO
+            CALL lbc_lnk( 'icedyn_rhg_evp', v_ice, 'V', -1. )
+            !
+#if defined key_agrif
+!!            CALL agrif_interp_ice( 'V', jter, nn_nevp )
+            CALL agrif_interp_ice( 'V' )
+#endif
+            IF( ln_bdy )   CALL bdy_ice_dyn( 'V' )
+            !
+         ENDIF
+
+         ! convergence test
+         IF( nn_rhg_chkcvg == 2 )   CALL rhg_cvg( kt, jter, nn_nevp, u_ice, v_ice, zu_ice, zv_ice )
+         !
+         !                                                ! ==================== !
+      END DO                                              !  end loop over jter  !
+      !                                                   ! ==================== !
+      IF( ln_aEVP )   CALL iom_put( 'beta_evp' , zbeta )
+      !
+      !------------------------------------------------------------------------------!
+      ! 4) Recompute delta, shear and div (inputs for mechanical redistribution) 
+      !------------------------------------------------------------------------------!
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1
+
+            ! shear at F points
+            zds(ji,jj) = ( ( u_ice(ji,jj+1) * r1_e1u(ji,jj+1) - u_ice(ji,jj) * r1_e1u(ji,jj) ) * e1f(ji,jj) * e1f(ji,jj)   &
+               &         + ( v_ice(ji+1,jj) * r1_e2v(ji+1,jj) - v_ice(ji,jj) * r1_e2v(ji,jj) ) * e2f(ji,jj) * e2f(ji,jj)   &
+               &         ) * r1_e1e2f(ji,jj) * zfmask(ji,jj)
+
+         END DO
+      END DO           
+      
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1 ! no vector loop
+            
+            ! tension**2 at T points
+            zdt  = ( ( u_ice(ji,jj) * r1_e2u(ji,jj) - u_ice(ji-1,jj) * r1_e2u(ji-1,jj) ) * e2t(ji,jj) * e2t(ji,jj)   &
+               &   - ( v_ice(ji,jj) * r1_e1v(ji,jj) - v_ice(ji,jj-1) * r1_e1v(ji,jj-1) ) * e1t(ji,jj) * e1t(ji,jj)   &
+               &   ) * r1_e1e2t(ji,jj)
+            zdt2 = zdt * zdt
+            
+            zten_i(ji,jj) = zdt
+
+            ! shear**2 at T points (doc eq. A16)
+            zds2 = ( zds(ji,jj  ) * zds(ji,jj  ) * e1e2f(ji,jj  ) + zds(ji-1,jj  ) * zds(ji-1,jj  ) * e1e2f(ji-1,jj  )  &
+               &   + zds(ji,jj-1) * zds(ji,jj-1) * e1e2f(ji,jj-1) + zds(ji-1,jj-1) * zds(ji-1,jj-1) * e1e2f(ji-1,jj-1)  &
+               &   ) * 0.25_wp * r1_e1e2t(ji,jj)
+            
+            ! shear at T points
+            pshear_i(ji,jj) = SQRT( zdt2 + zds2 )
+
+            ! divergence at T points
+            pdivu_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)   &
+               &             ) * r1_e1e2t(ji,jj)
+            
+            ! delta at T points
+            zfac            = SQRT( pdivu_i(ji,jj) * pdivu_i(ji,jj) + ( zdt2 + zds2 ) * z1_ecc2 ) ! delta  
+            rswitch         = 1._wp - MAX( 0._wp, SIGN( 1._wp, -zfac ) ) ! 0 if delta=0
+            pdelta_i(ji,jj) = zfac + rn_creepl * rswitch ! delta+creepl
+
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'icedyn_rhg_evp', pshear_i, 'T', 1., pdivu_i, 'T', 1., pdelta_i, 'T', 1., zten_i, 'T', 1., &
+         &                                  zs1     , 'T', 1., zs2    , 'T', 1., zs12    , 'F', 1. )
+      
+      ! --- Store the stress tensor for the next time step --- !
+      pstress1_i (:,:) = zs1 (:,:)
+      pstress2_i (:,:) = zs2 (:,:)
+      pstress12_i(:,:) = zs12(:,:)
+      !
+
+      !------------------------------------------------------------------------------!
+      ! 5) diagnostics
+      !------------------------------------------------------------------------------!
+      ! --- ice-ocean, ice-atm. & ice-oceanbottom(landfast) stresses --- !
+      IF(  iom_use('utau_oi') .OR. iom_use('vtau_oi') .OR. iom_use('utau_ai') .OR. iom_use('vtau_ai') .OR. &
+         & iom_use('utau_bi') .OR. iom_use('vtau_bi') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', ztaux_oi, 'U', -1., ztauy_oi, 'V', -1., ztaux_ai, 'U', -1., ztauy_ai, 'V', -1., &
+            &                                  ztaux_bi, 'U', -1., ztauy_bi, 'V', -1. )
+         !
+         CALL iom_put( 'utau_oi' , ztaux_oi * zmsk00 )
+         CALL iom_put( 'vtau_oi' , ztauy_oi * zmsk00 )
+         CALL iom_put( 'utau_ai' , ztaux_ai * zmsk00 )
+         CALL iom_put( 'vtau_ai' , ztauy_ai * zmsk00 )
+         CALL iom_put( 'utau_bi' , ztaux_bi * zmsk00 )
+         CALL iom_put( 'vtau_bi' , ztauy_bi * zmsk00 )
+      ENDIF
+       
+      ! --- divergence, shear and strength --- !
+      IF( iom_use('icediv') )   CALL iom_put( 'icediv' , pdivu_i  * zmsk00 )   ! divergence
+      IF( iom_use('iceshe') )   CALL iom_put( 'iceshe' , pshear_i * zmsk00 )   ! shear
+      IF( iom_use('icestr') )   CALL iom_put( 'icestr' , strength * zmsk00 )   ! strength
+
+      ! --- Stress tensor invariants (SIMIP diags) --- !
+      IF( iom_use('normstr') .OR. iom_use('sheastr') ) THEN
+         !
+         ALLOCATE( zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )
+         !         
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+            
+               ! Ice stresses
+               ! sigma1, sigma2, sigma12 are some useful recombination of the stresses (Hunke and Dukowicz MWR 2002, Bouillon et al., OM2013)
+               ! These are NOT stress tensor components, neither stress invariants, neither stress principal components
+               ! I know, this can be confusing...
+               zfac             =   strength(ji,jj) / ( pdelta_i(ji,jj) + rn_creepl ) 
+               zsig1            =   zfac * ( pdivu_i(ji,jj) - pdelta_i(ji,jj) )
+               zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+               zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+               
+               ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008)
+               zsig_I (ji,jj)   =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+               zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+               
+            END DO
+         END DO         
+         !
+         ! Stress tensor invariants (normal and shear stress N/m) - SIMIP diags - definitions following Coon (1974) and Feltham (2008)
+         IF( iom_use('normstr') )   CALL iom_put( 'normstr', zsig_I (:,:) * zmsk00(:,:) ) ! Normal stress
+         IF( iom_use('sheastr') )   CALL iom_put( 'sheastr', zsig_II(:,:) * zmsk00(:,:) ) ! Maximum shear stress
+         
+         DEALLOCATE ( zsig_I, zsig_II )
+         
+      ENDIF
+
+      ! --- Normalized stress tensor principal components --- !
+      ! This are used to plot the normalized yield curve, see Lemieux & Dupont, 2020
+      ! Recommendation 1 : we use ice strength, not replacement pressure
+      ! Recommendation 2 : need to use deformations at PREVIOUS iterate for viscosities
+!!$      IF( iom_use('sig1_pnorm') .OR. iom_use('sig2_pnorm') ) THEN
+!!$         !
+!!$         ALLOCATE( zsig1_p(jpi,jpj) , zsig2_p(jpi,jpj) , zsig_I(jpi,jpj) , zsig_II(jpi,jpj) )         
+!!$         !         
+!!$         DO jj = 1, jpj
+!!$            DO ji = 1, jpi
+!!$            
+!!$               ! Ice stresses computed with **viscosities** (delta, p/delta) at **previous** iterates 
+!!$               !                        and **deformations** at current iterates
+!!$               !                        following Lemieux & Dupont (2020)
+!!$               zfac             =   zp_delt(ji,jj)
+!!$               zsig1            =   zfac * ( pdivu_i(ji,jj) - ( zdelta(ji,jj) + rn_creepl ) )
+!!$               zsig2            =   zfac * z1_ecc2 * zten_i(ji,jj)
+!!$               zsig12           =   zfac * z1_ecc2 * pshear_i(ji,jj)
+!!$               
+!!$               ! Stress invariants (sigma_I, sigma_II, Coon 1974, Feltham 2008), T-point
+!!$               zsig_I(ji,jj)    =   zsig1 * 0.5_wp                                           ! 1st stress invariant, aka average normal stress, aka negative pressure
+!!$               zsig_II(ji,jj)   =   SQRT ( MAX( 0._wp, zsig2 * zsig2 * 0.25_wp + zsig12 ) )  ! 2nd  ''       '', aka maximum shear stress
+!!$      
+!!$               ! Normalized  principal stresses (used to display the ellipse)
+!!$               z1_strength      =   1._wp / MAX( 1._wp, strength(ji,jj) )
+!!$               zsig1_p(ji,jj)   =   ( zsig_I(ji,jj) + zsig_II(ji,jj) ) * z1_strength
+!!$               zsig2_p(ji,jj)   =   ( zsig_I(ji,jj) - zsig_II(ji,jj) ) * z1_strength
+!!$            END DO
+!!$         END DO               
+!!$         !
+!!$         CALL iom_put( 'sig1_pnorm' , zsig1_p ) 
+!!$         CALL iom_put( 'sig2_pnorm' , zsig2_p ) 
+!!$      
+!!$         DEALLOCATE( zsig1_p , zsig2_p , zsig_I, zsig_II )
+!!$         
+!!$      ENDIF
+
+      ! --- SIMIP --- !
+      IF(  iom_use('dssh_dx') .OR. iom_use('dssh_dy') .OR. &
+         & iom_use('corstrx') .OR. iom_use('corstry') .OR. iom_use('intstrx') .OR. iom_use('intstry') ) THEN
+         !
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', zspgU, 'U', -1., zspgV, 'V', -1., &
+            &                                  zCorU, 'U', -1., zCorV, 'V', -1., zfU, 'U', -1., zfV, 'V', -1. )
+
+         CALL iom_put( 'dssh_dx' , zspgU * zmsk00 )   ! Sea-surface tilt term in force balance (x)
+         CALL iom_put( 'dssh_dy' , zspgV * zmsk00 )   ! Sea-surface tilt term in force balance (y)
+         CALL iom_put( 'corstrx' , zCorU * zmsk00 )   ! Coriolis force term in force balance (x)
+         CALL iom_put( 'corstry' , zCorV * zmsk00 )   ! Coriolis force term in force balance (y)
+         CALL iom_put( 'intstrx' , zfU   * zmsk00 )   ! Internal force term in force balance (x)
+         CALL iom_put( 'intstry' , zfV   * zmsk00 )   ! Internal force term in force balance (y)
+      ENDIF
+
+      IF(  iom_use('xmtrpice') .OR. iom_use('ymtrpice') .OR. &
+         & iom_use('xmtrpsnw') .OR. iom_use('ymtrpsnw') .OR. iom_use('xatrp') .OR. iom_use('yatrp') ) THEN
+         !
+         ALLOCATE( zdiag_xmtrp_ice(jpi,jpj) , zdiag_ymtrp_ice(jpi,jpj) , &
+            &      zdiag_xmtrp_snw(jpi,jpj) , zdiag_ymtrp_snw(jpi,jpj) , zdiag_xatrp(jpi,jpj) , zdiag_yatrp(jpi,jpj) )
+         !
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               ! 2D ice mass, snow mass, area transport arrays (X, Y)
+               zfac_x = 0.5 * u_ice(ji,jj) * e2u(ji,jj) * zmsk00(ji,jj)
+               zfac_y = 0.5 * v_ice(ji,jj) * e1v(ji,jj) * zmsk00(ji,jj)
+
+               zdiag_xmtrp_ice(ji,jj) = rhoi * zfac_x * ( vt_i(ji+1,jj) + vt_i(ji,jj) ) ! ice mass transport, X-component
+               zdiag_ymtrp_ice(ji,jj) = rhoi * zfac_y * ( vt_i(ji,jj+1) + vt_i(ji,jj) ) !        ''           Y-   ''
+
+               zdiag_xmtrp_snw(ji,jj) = rhos * zfac_x * ( vt_s(ji+1,jj) + vt_s(ji,jj) ) ! snow mass transport, X-component
+               zdiag_ymtrp_snw(ji,jj) = rhos * zfac_y * ( vt_s(ji,jj+1) + vt_s(ji,jj) ) !          ''          Y-   ''
+
+               zdiag_xatrp(ji,jj)     = zfac_x * ( at_i(ji+1,jj) + at_i(ji,jj) )        ! area transport,      X-component
+               zdiag_yatrp(ji,jj)     = zfac_y * ( at_i(ji,jj+1) + at_i(ji,jj) )        !        ''            Y-   ''
+
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'icedyn_rhg_evp', zdiag_xmtrp_ice, 'U', -1., zdiag_ymtrp_ice, 'V', -1., &
+            &                                  zdiag_xmtrp_snw, 'U', -1., zdiag_ymtrp_snw, 'V', -1., &
+            &                                  zdiag_xatrp    , 'U', -1., zdiag_yatrp    , 'V', -1. )
+
+         CALL iom_put( 'xmtrpice' , zdiag_xmtrp_ice )   ! X-component of sea-ice mass transport (kg/s)
+         CALL iom_put( 'ymtrpice' , zdiag_ymtrp_ice )   ! Y-component of sea-ice mass transport 
+         CALL iom_put( 'xmtrpsnw' , zdiag_xmtrp_snw )   ! X-component of snow mass transport (kg/s)
+         CALL iom_put( 'ymtrpsnw' , zdiag_ymtrp_snw )   ! Y-component of snow mass transport
+         CALL iom_put( 'xatrp'    , zdiag_xatrp     )   ! X-component of ice area transport
+         CALL iom_put( 'yatrp'    , zdiag_yatrp     )   ! Y-component of ice area transport
+
+         DEALLOCATE( zdiag_xmtrp_ice , zdiag_ymtrp_ice , &
+            &        zdiag_xmtrp_snw , zdiag_ymtrp_snw , zdiag_xatrp , zdiag_yatrp )
+
+      ENDIF
+      !
+      ! --- convergence tests --- !
+      IF( nn_rhg_chkcvg == 1 .OR. nn_rhg_chkcvg == 2 ) THEN
+         IF( iom_use('uice_cvg') ) THEN
+            IF( ln_aEVP ) THEN   ! output: beta * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * zbeta(:,:) * umask(:,:,1) , &
+                  &                           ABS( v_ice(:,:) - zv_ice(:,:) ) * zbeta(:,:) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ELSE                 ! output: nn_nevp * ( u(t=nn_nevp) - u(t=nn_nevp-1) )
+               CALL iom_put( 'uice_cvg', REAL( nn_nevp ) * MAX( ABS( u_ice(:,:) - zu_ice(:,:) ) * umask(:,:,1) , &
+                  &                                             ABS( v_ice(:,:) - zv_ice(:,:) ) * vmask(:,:,1) ) * zmsk15(:,:) )
+            ENDIF
+         ENDIF
+      ENDIF      
+      !
+      DEALLOCATE( zmsk00, zmsk15 )
+      !
+   END SUBROUTINE ice_dyn_rhg_evp
+
+
+   SUBROUTINE rhg_cvg( kt, kiter, kitermax, pu, pv, pub, pvb )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE rhg_cvg  ***
+      !!                     
+      !! ** Purpose :   check convergence of oce rheology
+      !!
+      !! ** Method  :   create a file ice_cvg.nc containing the convergence of ice velocity
+      !!                during the sub timestepping of rheology so as:
+      !!                  uice_cvg = MAX( u(t+1) - u(t) , v(t+1) - v(t) )
+      !!                This routine is called every sub-iteration, so it is cpu expensive
+      !!
+      !! ** Note    :   for the first sub-iteration, uice_cvg is set to 0 (too large otherwise)   
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in) ::   kt, kiter, kitermax       ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pu, pv, pub, pvb          ! now and before velocities
+      !!
+      INTEGER           ::   it, idtime, istatus
+      INTEGER           ::   ji, jj          ! dummy loop indices
+      REAL(wp)          ::   zresm           ! local real 
+      CHARACTER(len=20) ::   clname
+      REAL(wp), DIMENSION(jpi,jpj) ::   zres           ! check convergence
+      !!----------------------------------------------------------------------
+
+      ! create file
+      IF( kt == nit000 .AND. kiter == 1 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'rhg_cvg : ice rheology convergence control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !
+         IF( lwm ) THEN
+            clname = 'ice_cvg.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, ncvgid )
+            istatus = NF90_DEF_DIM( ncvgid, 'time'  , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( ncvgid, 'uice_cvg', NF90_DOUBLE   , (/ idtime /), nvarid )
+            istatus = NF90_ENDDEF(ncvgid)
+         ENDIF
+         !
+      ENDIF
+
+      ! time
+      it = ( kt - 1 ) * kitermax + kiter
+      
+      ! convergence
+      IF( kiter == 1 ) THEN ! remove the first iteration for calculations of convergence (always very large)
+         zresm = 0._wp
+      ELSE
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zres(ji,jj) = MAX( ABS( pu(ji,jj) - pub(ji,jj) ) * umask(ji,jj,1), &
+                  &               ABS( pv(ji,jj) - pvb(ji,jj) ) * vmask(ji,jj,1) ) * zmsk15(ji,jj)
+            END DO
+         END DO
+         zresm = MAXVAL( zres )
+         CALL mpp_max( 'icedyn_rhg_evp', zresm )   ! max over the global domain
+      ENDIF
+
+      IF( lwm ) THEN
+         ! write variables
+         istatus = NF90_PUT_VAR( ncvgid, nvarid, (/zresm/), (/it/), (/1/) )
+         ! close file
+         IF( kt == nitend - nn_fsbc + 1 )   istatus = NF90_CLOSE(ncvgid)
+      ENDIF
+      
+   END SUBROUTINE rhg_cvg
+
+
+   SUBROUTINE rhg_evp_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rhg_evp_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write RHG file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter            ! local integer
+      INTEGER  ::   id1, id2, id3   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialize
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            id1 = iom_varid( numrir, 'stress1_i' , ldstop = .FALSE. )
+            id2 = iom_varid( numrir, 'stress2_i' , ldstop = .FALSE. )
+            id3 = iom_varid( numrir, 'stress12_i', ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3 ) > 0 ) THEN      ! fields exist
+               CALL iom_get( numrir, jpdom_autoglo, 'stress1_i' , stress1_i  )
+               CALL iom_get( numrir, jpdom_autoglo, 'stress2_i' , stress2_i  )
+               CALL iom_get( numrir, jpdom_autoglo, 'stress12_i', stress12_i )
+            ELSE                                     ! start rheology from rest
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>>   previous run without rheology, set stresses to 0'
+               stress1_i (:,:) = 0._wp
+               stress2_i (:,:) = 0._wp
+               stress12_i(:,:) = 0._wp
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set stresses to 0'
+            stress1_i (:,:) = 0._wp
+            stress2_i (:,:) = 0._wp
+            stress12_i(:,:) = 0._wp
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- rhg-rst ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         CALL iom_rstput( iter, nitrst, numriw, 'stress1_i' , stress1_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress2_i' , stress2_i  )
+         CALL iom_rstput( iter, nitrst, numriw, 'stress12_i', stress12_i )
+         !
+      ENDIF
+      !
+   END SUBROUTINE rhg_evp_rst
+
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!==============================================================================
+END MODULE icedyn_rhg_evp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceistate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceistate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceistate.F90	(revision 14097)
@@ -0,0 +1,561 @@
+MODULE iceistate
+   !!======================================================================
+   !!                     ***  MODULE  iceistate  ***
+   !!   sea-ice : Initialization of ice variables
+   !!======================================================================
+   !! History :  2.0  !  2004-01  (C. Ethe, G. Madec) Original code
+   !!            3.0  !  2007     (M. Vancoppenolle)  Rewrite for ice cats
+   !!            4.0  !  2018     (many people)       SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_istate       :  initialization of diagnostics ice variables
+   !!   ice_istate_init  :  initialization of ice state and namelist read
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constant
+   USE oce            ! dynamics and tracers variables
+   USE dom_oce        ! ocean domain
+   USE sbc_oce , ONLY : sst_m, sss_m, ln_ice_embd 
+   USE sbc_ice , ONLY : tn_ice, snwice_mass, snwice_mass_b
+   USE eosbn2         ! equation of state
+   USE domvvl         ! Variable volume
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icetab         ! sea-ice: 1D <==> 2D transformation
+   USE icevar         ! sea-ice: operations
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE fldread        ! read input fields
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_istate        ! called by icestp.F90
+   PUBLIC   ice_istate_init   ! called by icestp.F90
+   !
+   !                             !! ** namelist (namini) **
+   LOGICAL, PUBLIC  ::   ln_iceini        !: Ice initialization or not
+   INTEGER, PUBLIC  ::   nn_iceini_file   !: Ice initialization:
+                                  !        0 = Initialise sea ice based on SSTs
+                                  !        1 = Initialise sea ice from single category netcdf file
+                                  !        2 = Initialise sea ice from multi category restart file
+   REAL(wp) ::   rn_thres_sst
+   REAL(wp) ::   rn_hti_ini_n, rn_hts_ini_n, rn_ati_ini_n, rn_smi_ini_n, rn_tmi_ini_n, rn_tsu_ini_n, rn_tms_ini_n
+   REAL(wp) ::   rn_hti_ini_s, rn_hts_ini_s, rn_ati_ini_s, rn_smi_ini_s, rn_tmi_ini_s, rn_tsu_ini_s, rn_tms_ini_s
+   REAL(wp) ::   rn_apd_ini_n, rn_hpd_ini_n, rn_hld_ini_n
+   REAL(wp) ::   rn_apd_ini_s, rn_hpd_ini_s, rn_hld_ini_s
+   !
+   !                              ! if nn_iceini_file = 1
+   INTEGER , PARAMETER ::   jpfldi = 10          ! maximum number of files to read
+   INTEGER , PARAMETER ::   jp_hti = 1           ! index of ice thickness    (m)
+   INTEGER , PARAMETER ::   jp_hts = 2           ! index of snw thickness    (m)
+   INTEGER , PARAMETER ::   jp_ati = 3           ! index of ice fraction     (-)
+   INTEGER , PARAMETER ::   jp_smi = 4           ! index of ice salinity     (g/kg)
+   INTEGER , PARAMETER ::   jp_tmi = 5           ! index of ice temperature  (K)
+   INTEGER , PARAMETER ::   jp_tsu = 6           ! index of ice surface temp (K)
+   INTEGER , PARAMETER ::   jp_tms = 7           ! index of snw temperature  (K)
+   INTEGER , PARAMETER ::   jp_apd = 8           ! index of pnd fraction     (-)
+   INTEGER , PARAMETER ::   jp_hpd = 9           ! index of pnd depth        (m)
+   INTEGER , PARAMETER ::   jp_hld = 10          ! index of pnd lid depth    (m)
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   si  ! structure of input fields (file informations, fields read)
+   !   
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_istate( kt )
+      !!-------------------------------------------------------------------
+      !!                    ***  ROUTINE ice_istate  ***
+      !!
+      !! ** Purpose :   defined the sea-ice initial state
+      !!
+      !! ** Method  :   This routine will put some ice where ocean
+      !!                is at the freezing point, then fill in ice 
+      !!                state variables using prescribed initial 
+      !!                values in the namelist            
+      !!
+      !! ** Steps   :   1) Set initial surface and basal temperatures
+      !!                2) Recompute or read sea ice state variables
+      !!                3) Fill in space-dependent arrays for state variables
+      !!                4) snow-ice mass computation
+      !!
+      !! ** Notes   : o_i, t_su, t_s, t_i, sz_i must be filled everywhere, even
+      !!              where there is no ice
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step 
+      !!
+      INTEGER  ::   ji, jj, jk, jl         ! dummy loop indices
+      REAL(wp) ::   ztmelts
+      INTEGER , DIMENSION(4)           ::   itest
+      REAL(wp), DIMENSION(jpi,jpj)     ::   z2d
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zswitch    ! ice indicator
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zht_i_ini, zat_i_ini, ztm_s_ini            !data from namelist or nc file
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zt_su_ini, zht_s_ini, zsm_i_ini, ztm_i_ini !data from namelist or nc file
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zapnd_ini, zhpnd_ini, zhlid_ini            !data from namelist or nc file
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zti_3d , zts_3d                            !temporary arrays
+      !!
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zhi_2d, zhs_2d, zai_2d, zti_2d, zts_2d, ztsu_2d, zsi_2d, zaip_2d, zhip_2d, zhil_2d
+      !--------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'ice_istate: sea-ice initialization '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+
+      !---------------------------
+      ! 1) 1st init. of the fields
+      !---------------------------
+      !
+      ! basal temperature (considered at freezing point)   [Kelvin]
+      CALL eos_fzp( sss_m(:,:), t_bo(:,:) )
+      t_bo(:,:) = ( t_bo(:,:) + rt0 ) * tmask(:,:,1) 
+      !
+      ! surface temperature and conductivity
+      DO jl = 1, jpl
+         t_su   (:,:,jl) = rt0 * tmask(:,:,1)  ! temp at the surface
+         cnd_ice(:,:,jl) = 0._wp               ! initialisation of the effective conductivity at the top of ice/snow (ln_cndflx=T)
+      END DO
+      !
+      ! ice and snw temperatures
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            t_i(:,:,jk,jl) = rt0 * tmask(:,:,1)
+         END DO
+         DO jk = 1, nlay_s
+            t_s(:,:,jk,jl) = rt0 * tmask(:,:,1)
+         END DO
+      END DO
+      !
+      ! specific temperatures for coupled runs
+      tn_ice (:,:,:) = t_i (:,:,1,:)
+      t1_ice (:,:,:) = t_i (:,:,1,:)
+
+      ! heat contents
+      e_i (:,:,:,:) = 0._wp
+      e_s (:,:,:,:) = 0._wp
+      
+      ! general fields
+      a_i (:,:,:) = 0._wp
+      v_i (:,:,:) = 0._wp
+      v_s (:,:,:) = 0._wp
+      sv_i(:,:,:) = 0._wp
+      oa_i(:,:,:) = 0._wp
+      !
+      h_i (:,:,:) = 0._wp
+      h_s (:,:,:) = 0._wp
+      s_i (:,:,:) = 0._wp
+      o_i (:,:,:) = 0._wp
+      !
+      ! melt ponds
+      a_ip     (:,:,:) = 0._wp
+      v_ip     (:,:,:) = 0._wp
+      v_il     (:,:,:) = 0._wp
+      a_ip_eff (:,:,:) = 0._wp
+      h_ip     (:,:,:) = 0._wp
+      h_il     (:,:,:) = 0._wp
+      !
+      ! ice velocities
+      u_ice (:,:) = 0._wp
+      v_ice (:,:) = 0._wp
+      !
+      !------------------------------------------------------------------------
+      ! 2) overwrite some of the fields with namelist parameters or netcdf file
+      !------------------------------------------------------------------------
+      IF( ln_iceini ) THEN
+         !                             !---------------!
+         IF( nn_iceini_file == 1 )THEN ! Read a file   !
+            !                          !---------------!
+            WHERE( ff_t(:,:) >= 0._wp )   ;   zswitch(:,:) = 1._wp
+            ELSEWHERE                     ;   zswitch(:,:) = 0._wp
+            END WHERE
+            !
+            CALL fld_read( kt, 1, si ) ! input fields provided at the current time-step
+            !
+            ! -- mandatory fields -- !
+            zht_i_ini(:,:) = si(jp_hti)%fnow(:,:,1) * tmask(:,:,1)
+            zht_s_ini(:,:) = si(jp_hts)%fnow(:,:,1) * tmask(:,:,1)
+            zat_i_ini(:,:) = si(jp_ati)%fnow(:,:,1) * tmask(:,:,1)
+
+            ! -- optional fields -- !
+            !    if fields do not exist then set them to the values present in the namelist (except for temperatures)
+            !
+            ! ice salinity
+            IF( TRIM(si(jp_smi)%clrootname) == 'NOT USED' ) &
+               &     si(jp_smi)%fnow(:,:,1) = ( rn_smi_ini_n * zswitch + rn_smi_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+            !
+            ! temperatures
+            IF    ( TRIM(si(jp_tmi)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tsu)%clrootname) == 'NOT USED' .AND. &
+               &    TRIM(si(jp_tms)%clrootname) == 'NOT USED' ) THEN
+               si(jp_tmi)%fnow(:,:,1) = ( rn_tmi_ini_n * zswitch + rn_tmi_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+               si(jp_tsu)%fnow(:,:,1) = ( rn_tsu_ini_n * zswitch + rn_tsu_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+               si(jp_tms)%fnow(:,:,1) = ( rn_tms_ini_n * zswitch + rn_tms_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+            ENDIF
+            IF( TRIM(si(jp_tmi)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tms)%clrootname) /= 'NOT USED' ) & ! if T_s is read and not T_i, set T_i = (T_s + T_freeze)/2
+               &     si(jp_tmi)%fnow(:,:,1) = 0.5_wp * ( si(jp_tms)%fnow(:,:,1) + 271.15 )
+            IF( TRIM(si(jp_tmi)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tsu)%clrootname) /= 'NOT USED' ) & ! if T_su is read and not T_i, set T_i = (T_su + T_freeze)/2
+               &     si(jp_tmi)%fnow(:,:,1) = 0.5_wp * ( si(jp_tsu)%fnow(:,:,1) + 271.15 )
+            IF( TRIM(si(jp_tsu)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tms)%clrootname) /= 'NOT USED' ) & ! if T_s is read and not T_su, set T_su = T_s
+               &     si(jp_tsu)%fnow(:,:,1) = si(jp_tms)%fnow(:,:,1)
+            IF( TRIM(si(jp_tsu)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tmi)%clrootname) /= 'NOT USED' ) & ! if T_i is read and not T_su, set T_su = T_i
+               &     si(jp_tsu)%fnow(:,:,1) = si(jp_tmi)%fnow(:,:,1)
+            IF( TRIM(si(jp_tms)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tsu)%clrootname) /= 'NOT USED' ) & ! if T_su is read and not T_s, set T_s = T_su
+               &     si(jp_tms)%fnow(:,:,1) = si(jp_tsu)%fnow(:,:,1)
+            IF( TRIM(si(jp_tms)%clrootname) == 'NOT USED' .AND. TRIM(si(jp_tmi)%clrootname) /= 'NOT USED' ) & ! if T_i is read and not T_s, set T_s = T_i
+               &     si(jp_tms)%fnow(:,:,1) = si(jp_tmi)%fnow(:,:,1)
+            !
+            ! pond concentration
+            IF( TRIM(si(jp_apd)%clrootname) == 'NOT USED' ) &
+               &     si(jp_apd)%fnow(:,:,1) = ( rn_apd_ini_n * zswitch + rn_apd_ini_s * (1._wp - zswitch) ) * tmask(:,:,1) & ! rn_apd = pond fraction => rn_apnd * a_i = pond conc.
+               &                              * si(jp_ati)%fnow(:,:,1) 
+            !
+            ! pond depth
+            IF( TRIM(si(jp_hpd)%clrootname) == 'NOT USED' ) &
+               &     si(jp_hpd)%fnow(:,:,1) = ( rn_hpd_ini_n * zswitch + rn_hpd_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+            !
+            ! pond lid depth
+            IF( TRIM(si(jp_hld)%clrootname) == 'NOT USED' ) &
+               &     si(jp_hld)%fnow(:,:,1) = ( rn_hld_ini_n * zswitch + rn_hld_ini_s * (1._wp - zswitch) ) * tmask(:,:,1)
+            !
+            zsm_i_ini(:,:) = si(jp_smi)%fnow(:,:,1) * tmask(:,:,1)
+            ztm_i_ini(:,:) = si(jp_tmi)%fnow(:,:,1) * tmask(:,:,1)
+            zt_su_ini(:,:) = si(jp_tsu)%fnow(:,:,1) * tmask(:,:,1)
+            ztm_s_ini(:,:) = si(jp_tms)%fnow(:,:,1) * tmask(:,:,1)
+            zapnd_ini(:,:) = si(jp_apd)%fnow(:,:,1) * tmask(:,:,1)
+            zhpnd_ini(:,:) = si(jp_hpd)%fnow(:,:,1) * tmask(:,:,1)
+            zhlid_ini(:,:) = si(jp_hld)%fnow(:,:,1) * tmask(:,:,1)
+            !
+            ! change the switch for the following
+            WHERE( zat_i_ini(:,:) > 0._wp )   ;   zswitch(:,:) = tmask(:,:,1) 
+            ELSEWHERE                         ;   zswitch(:,:) = 0._wp
+            END WHERE
+            !                          !---------------!
+         ELSE                          ! Read namelist !
+            !                          !---------------!
+            ! no ice if (sst - Tfreez) >= thresold
+            WHERE( ( sst_m(:,:) - (t_bo(:,:) - rt0) ) * tmask(:,:,1) >= rn_thres_sst )   ;   zswitch(:,:) = 0._wp 
+            ELSEWHERE                                                                    ;   zswitch(:,:) = tmask(:,:,1)
+            END WHERE
+            !
+            ! assign initial thickness, concentration, snow depth and salinity to an hemisphere-dependent array
+            WHERE( ff_t(:,:) >= 0._wp )
+               zht_i_ini(:,:) = rn_hti_ini_n * zswitch(:,:)
+               zht_s_ini(:,:) = rn_hts_ini_n * zswitch(:,:)
+               zat_i_ini(:,:) = rn_ati_ini_n * zswitch(:,:)
+               zsm_i_ini(:,:) = rn_smi_ini_n * zswitch(:,:)
+               ztm_i_ini(:,:) = rn_tmi_ini_n * zswitch(:,:)
+               zt_su_ini(:,:) = rn_tsu_ini_n * zswitch(:,:)
+               ztm_s_ini(:,:) = rn_tms_ini_n * zswitch(:,:)
+               zapnd_ini(:,:) = rn_apd_ini_n * zswitch(:,:) * zat_i_ini(:,:) ! rn_apd = pond fraction => rn_apd * a_i = pond conc. 
+               zhpnd_ini(:,:) = rn_hpd_ini_n * zswitch(:,:)
+               zhlid_ini(:,:) = rn_hld_ini_n * zswitch(:,:)
+            ELSEWHERE
+               zht_i_ini(:,:) = rn_hti_ini_s * zswitch(:,:)
+               zht_s_ini(:,:) = rn_hts_ini_s * zswitch(:,:)
+               zat_i_ini(:,:) = rn_ati_ini_s * zswitch(:,:)
+               zsm_i_ini(:,:) = rn_smi_ini_s * zswitch(:,:)
+               ztm_i_ini(:,:) = rn_tmi_ini_s * zswitch(:,:)
+               zt_su_ini(:,:) = rn_tsu_ini_s * zswitch(:,:)
+               ztm_s_ini(:,:) = rn_tms_ini_s * zswitch(:,:)
+               zapnd_ini(:,:) = rn_apd_ini_s * zswitch(:,:) * zat_i_ini(:,:) ! rn_apd = pond fraction => rn_apd * a_i = pond conc.
+               zhpnd_ini(:,:) = rn_hpd_ini_s * zswitch(:,:)
+               zhlid_ini(:,:) = rn_hld_ini_s * zswitch(:,:)
+            END WHERE
+            !
+         ENDIF
+
+         ! make sure ponds = 0 if no ponds scheme
+         IF ( .NOT.ln_pnd ) THEN
+            zapnd_ini(:,:) = 0._wp
+            zhpnd_ini(:,:) = 0._wp
+            zhlid_ini(:,:) = 0._wp
+         ENDIF
+
+         IF ( .NOT.ln_pnd_lids ) THEN
+            zhlid_ini(:,:) = 0._wp
+         ENDIF
+         
+         !----------------!
+         ! 3) fill fields !
+         !----------------!
+         ! select ice covered grid points
+         npti = 0 ; nptidx(:) = 0
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( zht_i_ini(ji,jj) > 0._wp ) THEN
+                  npti         = npti  + 1
+                  nptidx(npti) = (jj - 1) * jpi + ji
+               ENDIF
+            END DO
+         END DO
+
+         ! move to 1D arrays: (jpi,jpj) -> (jpi*jpj)
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d (1:npti)  , zht_i_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_s_1d (1:npti)  , zht_s_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), at_i_1d(1:npti)  , zat_i_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_i_1d (1:npti,1), ztm_i_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_s_1d (1:npti,1), ztm_s_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_su_1d(1:npti)  , zt_su_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), s_i_1d (1:npti)  , zsm_i_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d(1:npti)  , zapnd_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_ip_1d(1:npti)  , zhpnd_ini )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_il_1d(1:npti)  , zhlid_ini )
+
+         ! allocate temporary arrays
+         ALLOCATE( zhi_2d (npti,jpl), zhs_2d (npti,jpl), zai_2d (npti,jpl), &
+            &      zti_2d (npti,jpl), zts_2d (npti,jpl), ztsu_2d(npti,jpl), zsi_2d(npti,jpl), &
+            &      zaip_2d(npti,jpl), zhip_2d(npti,jpl), zhil_2d(npti,jpl) )
+         
+         ! distribute 1-cat into jpl-cat: (jpi*jpj) -> (jpi*jpj,jpl)
+         CALL ice_var_itd( h_i_1d(1:npti)  , h_s_1d(1:npti)  , at_i_1d(1:npti),                  &
+            &              zhi_2d          , zhs_2d          , zai_2d         ,                  &
+            &              t_i_1d(1:npti,1), t_s_1d(1:npti,1), t_su_1d(1:npti),                  &
+            &              s_i_1d(1:npti)  , a_ip_1d(1:npti) , h_ip_1d(1:npti), h_il_1d(1:npti), &
+            &              zti_2d          , zts_2d          , ztsu_2d        ,                  &
+            &              zsi_2d          , zaip_2d         , zhip_2d        , zhil_2d )
+
+         ! move to 3D arrays: (jpi*jpj,jpl) -> (jpi,jpj,jpl)
+         DO jl = 1, jpl
+            zti_3d(:,:,jl) = rt0 * tmask(:,:,1)
+            zts_3d(:,:,jl) = rt0 * tmask(:,:,1)
+         END DO
+         CALL tab_2d_3d( npti, nptidx(1:npti), zhi_2d   , h_i    )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zhs_2d   , h_s    )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zai_2d   , a_i    )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zti_2d   , zti_3d )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zts_2d   , zts_3d )
+         CALL tab_2d_3d( npti, nptidx(1:npti), ztsu_2d  , t_su   )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zsi_2d   , s_i    )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zaip_2d  , a_ip   )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zhip_2d  , h_ip   )
+         CALL tab_2d_3d( npti, nptidx(1:npti), zhil_2d  , h_il   )
+
+         ! deallocate temporary arrays
+         DEALLOCATE( zhi_2d, zhs_2d, zai_2d , &
+            &        zti_2d, zts_2d, ztsu_2d, zsi_2d, zaip_2d, zhip_2d, zhil_2d )
+
+         ! calculate extensive and intensive variables
+         CALL ice_var_salprof ! for sz_i
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  v_i (ji,jj,jl) = h_i(ji,jj,jl) * a_i(ji,jj,jl)
+                  v_s (ji,jj,jl) = h_s(ji,jj,jl) * a_i(ji,jj,jl)
+                  sv_i(ji,jj,jl) = MIN( MAX( rn_simin , s_i(ji,jj,jl) ) , rn_simax ) * v_i(ji,jj,jl)
+               END DO
+            END DO
+         END DO
+         !
+         DO jl = 1, jpl
+            DO jk = 1, nlay_s
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     t_s(ji,jj,jk,jl) = zts_3d(ji,jj,jl)
+                     e_s(ji,jj,jk,jl) = zswitch(ji,jj) * v_s(ji,jj,jl) * r1_nlay_s * &
+                        &               rhos * ( rcpi * ( rt0 - t_s(ji,jj,jk,jl) ) + rLfus )
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     t_i (ji,jj,jk,jl) = zti_3d(ji,jj,jl) 
+                     ztmelts          = - rTmlt * sz_i(ji,jj,jk,jl) + rt0 ! melting temperature in K
+                     e_i(ji,jj,jk,jl) = zswitch(ji,jj) * v_i(ji,jj,jl) * r1_nlay_i * &
+                        &               rhoi * (  rcpi  * ( ztmelts - t_i(ji,jj,jk,jl) ) + &
+                        &                         rLfus * ( 1._wp - (ztmelts-rt0) / MIN( (t_i(ji,jj,jk,jl)-rt0), -epsi20 ) ) &
+                        &                       - rcp   * ( ztmelts - rt0 ) )
+                  END DO
+               END DO
+            END DO
+         END DO
+
+         ! Melt ponds
+         WHERE( a_i > epsi10 )   ;   a_ip_eff(:,:,:) = a_ip(:,:,:) / a_i(:,:,:)
+         ELSEWHERE               ;   a_ip_eff(:,:,:) = 0._wp
+         END WHERE
+         v_ip(:,:,:) = h_ip(:,:,:) * a_ip(:,:,:)
+         v_il(:,:,:) = h_il(:,:,:) * a_ip(:,:,:)
+          
+         ! specific temperatures for coupled runs
+         tn_ice(:,:,:) = t_su(:,:,:)
+         t1_ice(:,:,:) = t_i (:,:,1,:)
+         !
+         ! ice concentration should not exceed amax
+         at_i(:,:) = SUM( a_i, dim=3 )
+         DO jl = 1, jpl
+            WHERE( at_i(:,:) > rn_amax_2d(:,:) )   a_i(:,:,jl) = a_i(:,:,jl) * rn_amax_2d(:,:) / at_i(:,:)
+         END DO
+         at_i(:,:) = SUM( a_i, dim=3 )
+         !
+      ENDIF ! ln_iceini
+      !
+      !----------------------------------------------
+      ! 4) Snow-ice mass (case ice is fully embedded)
+      !----------------------------------------------
+      snwice_mass  (:,:) = tmask(:,:,1) * SUM( rhos * v_s(:,:,:) + rhoi * v_i(:,:,:), dim=3  )   ! snow+ice mass
+      snwice_mass_b(:,:) = snwice_mass(:,:)
+      !
+      IF( ln_ice_embd ) THEN            ! embedded sea-ice: deplete the initial ssh below sea-ice area
+         !
+         sshn(:,:) = sshn(:,:) - snwice_mass(:,:) * r1_rau0
+         sshb(:,:) = sshb(:,:) - snwice_mass(:,:) * r1_rau0
+         !
+         IF( .NOT.ln_linssh ) THEN
+            !
+            WHERE( ht_0(:,:) > 0 )   ;   z2d(:,:) = 1._wp + sshn(:,:)*tmask(:,:,1) / ht_0(:,:)
+            ELSEWHERE                ;   z2d(:,:) = 1._wp   ;   END WHERE
+            !
+            DO jk = 1,jpkm1                     ! adjust initial vertical scale factors                
+               e3t_n(:,:,jk) = e3t_0(:,:,jk) * z2d(:,:)
+               e3t_b(:,:,jk) = e3t_n(:,:,jk)
+               e3t_a(:,:,jk) = e3t_n(:,:,jk)
+            END DO
+            !
+            ! Reconstruction of all vertical scale factors at now and before time-steps
+            ! =========================================================================
+            ! Horizontal scale factor interpolations
+            ! --------------------------------------
+            CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )
+            CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )
+            CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+            CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+            CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )
+            ! Vertical scale factor interpolations
+            ! ------------------------------------
+            CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )
+            CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+            CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+            CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+            CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+            ! t- and w- points depth
+            ! ----------------------
+            !!gm not sure of that....
+            gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+            gdepw_n(:,:,1) = 0.0_wp
+            gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+            DO jk = 2, jpk
+               gdept_n(:,:,jk) = gdept_n(:,:,jk-1) + e3w_n(:,:,jk  )
+               gdepw_n(:,:,jk) = gdepw_n(:,:,jk-1) + e3t_n(:,:,jk-1)
+               gde3w_n(:,:,jk) = gdept_n(:,:,jk  ) - sshn (:,:)
+            END DO
+         ENDIF
+      ENDIF
+
+!!clem: output of initial state should be written here but it is impossible because
+!!      the ocean and ice are in the same file
+!!      CALL dia_wri_state( 'output.init' )
+      !
+   END SUBROUTINE ice_istate
+
+
+   SUBROUTINE ice_istate_init
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_istate_init  ***
+      !!        
+      !! ** Purpose :   Definition of initial state of the ice 
+      !!
+      !! ** Method  :   Read the namini namelist and check the parameter 
+      !!              values called at the first timestep (nit000)
+      !!
+      !! ** input   :  Namelist namini
+      !!
+      !!-----------------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      INTEGER ::   ifpr, ierror
+      !
+      CHARACTER(len=256) ::  cn_dir          ! Root directory for location of ice files
+      TYPE(FLD_N)                    ::   sn_hti, sn_hts, sn_ati, sn_smi, sn_tmi, sn_tsu, sn_tms, sn_apd, sn_hpd, sn_hld
+      TYPE(FLD_N), DIMENSION(jpfldi) ::   slf_i                 ! array of namelist informations on the fields to read
+      !
+      NAMELIST/namini/ ln_iceini, nn_iceini_file, rn_thres_sst, &
+         &             rn_hti_ini_n, rn_hti_ini_s, rn_hts_ini_n, rn_hts_ini_s, &
+         &             rn_ati_ini_n, rn_ati_ini_s, rn_smi_ini_n, rn_smi_ini_s, &
+         &             rn_tmi_ini_n, rn_tmi_ini_s, rn_tsu_ini_n, rn_tsu_ini_s, rn_tms_ini_n, rn_tms_ini_s, &
+         &             rn_apd_ini_n, rn_apd_ini_s, rn_hpd_ini_n, rn_hpd_ini_s, rn_hld_ini_n, rn_hld_ini_s, &
+         &             sn_hti, sn_hts, sn_ati, sn_tsu, sn_tmi, sn_smi, sn_tms, sn_apd, sn_hpd, sn_hld, cn_dir
+      !!-----------------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namini in reference namelist : Ice initial state
+      READ  ( numnam_ice_ref, namini, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namini in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namini in configuration namelist : Ice initial state
+      READ  ( numnam_ice_cfg, namini, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namini in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namini )
+      !
+      slf_i(jp_hti) = sn_hti  ;  slf_i(jp_hts) = sn_hts
+      slf_i(jp_ati) = sn_ati  ;  slf_i(jp_smi) = sn_smi
+      slf_i(jp_tmi) = sn_tmi  ;  slf_i(jp_tsu) = sn_tsu   ;   slf_i(jp_tms) = sn_tms
+      slf_i(jp_apd) = sn_apd  ;  slf_i(jp_hpd) = sn_hpd   ;   slf_i(jp_hld) = sn_hld
+      !
+      IF(lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_istate_init: ice parameters inititialisation '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namini:'
+         WRITE(numout,*) '      ice initialization (T) or not (F)                ln_iceini      = ', ln_iceini
+         WRITE(numout,*) '      ice initialization from a netcdf file            nn_iceini_file = ', nn_iceini_file
+         WRITE(numout,*) '      max ocean temp. above Tfreeze with initial ice   rn_thres_sst   = ', rn_thres_sst
+         IF( ln_iceini .AND. nn_iceini_file == 0 ) THEN
+            WRITE(numout,*) '      initial snw thickness in the north-south         rn_hts_ini     = ', rn_hts_ini_n,rn_hts_ini_s 
+            WRITE(numout,*) '      initial ice thickness in the north-south         rn_hti_ini     = ', rn_hti_ini_n,rn_hti_ini_s
+            WRITE(numout,*) '      initial ice concentr  in the north-south         rn_ati_ini     = ', rn_ati_ini_n,rn_ati_ini_s
+            WRITE(numout,*) '      initial ice salinity  in the north-south         rn_smi_ini     = ', rn_smi_ini_n,rn_smi_ini_s
+            WRITE(numout,*) '      initial surf temperat in the north-south         rn_tsu_ini     = ', rn_tsu_ini_n,rn_tsu_ini_s
+            WRITE(numout,*) '      initial ice temperat  in the north-south         rn_tmi_ini     = ', rn_tmi_ini_n,rn_tmi_ini_s
+            WRITE(numout,*) '      initial snw temperat  in the north-south         rn_tms_ini     = ', rn_tms_ini_n,rn_tms_ini_s
+            WRITE(numout,*) '      initial pnd fraction  in the north-south         rn_apd_ini     = ', rn_apd_ini_n,rn_apd_ini_s
+            WRITE(numout,*) '      initial pnd depth     in the north-south         rn_hpd_ini     = ', rn_hpd_ini_n,rn_hpd_ini_s
+            WRITE(numout,*) '      initial pnd lid depth in the north-south         rn_hld_ini     = ', rn_hld_ini_n,rn_hld_ini_s
+         ENDIF
+      ENDIF
+      !
+      IF( nn_iceini_file == 1 ) THEN                      ! Ice initialization using input file
+         !
+         ! set si structure
+         ALLOCATE( si(jpfldi), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'ice_istate_ini in iceistate: unable to allocate si structure' )   ;   RETURN
+         ENDIF
+         !
+         DO ifpr = 1, jpfldi
+            ALLOCATE( si(ifpr)%fnow(jpi,jpj,1) )
+            IF( slf_i(ifpr)%ln_tint )  ALLOCATE( si(ifpr)%fdta(jpi,jpj,1,2) )
+         END DO
+         !
+         ! fill si with slf_i and control print
+         CALL fld_fill( si, slf_i, cn_dir, 'ice_istate_ini', 'initialization of sea ice fields', 'numnam_ice' )
+         !
+      ENDIF
+      !
+      IF( .NOT.ln_pnd ) THEN
+         rn_apd_ini_n = 0. ; rn_apd_ini_s = 0.
+         rn_hpd_ini_n = 0. ; rn_hpd_ini_s = 0.
+         rn_hld_ini_n = 0. ; rn_hld_ini_s = 0.
+         CALL ctl_warn( 'rn_apd_ini & rn_hpd_ini = 0 & rn_hld_ini = 0 when no ponds' )
+      ENDIF
+      !
+      IF( .NOT.ln_pnd_lids ) THEN
+         rn_hld_ini_n = 0. ; rn_hld_ini_s = 0.
+      ENDIF
+      !
+   END SUBROUTINE ice_istate_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE iceistate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceitd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceitd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceitd.F90	(revision 14097)
@@ -0,0 +1,769 @@
+MODULE iceitd
+   !!======================================================================
+   !!                       ***  MODULE iceitd ***
+   !!   sea-ice : ice thickness distribution
+   !!======================================================================
+   !! History :  3.0  !  2005-12  (M. Vancoppenolle) original code (based on CICE)
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_itd_rem   : redistribute ice thicknesses after thermo growth and melt
+   !!   itd_glinear   : build g(h) satisfying area and volume constraints
+   !!   itd_shiftice  : shift ice across category boundaries, conserving everything
+   !!   ice_itd_reb   : rebin ice thicknesses into bounded categories
+   !!   ice_itd_init  : read ice thicknesses mean and min from namelist
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constants 
+   USE ice1D          ! sea-ice: thermodynamic variables
+   USE ice            ! sea-ice: variables
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: conservation tests
+   USE icetab         ! sea-ice: convert 1D<=>2D
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_itd_init  ! called in icestp
+   PUBLIC   ice_itd_rem   ! called in icethd
+   PUBLIC   ice_itd_reb   ! called in icecor
+
+   INTEGER            ::   nice_catbnd     ! choice of the type of ice category function
+   !                                       ! associated indices:
+   INTEGER, PARAMETER ::   np_cathfn = 1   ! categories defined by a function
+   INTEGER, PARAMETER ::   np_catusr = 2   ! categories defined by the user
+   !
+   !                                           !! ** namelist (namitd) **
+   LOGICAL                    ::   ln_cat_hfn   ! ice categories are defined by function like rn_himean**(-0.05)
+   REAL(wp)                   ::   rn_himean    ! mean thickness of the domain
+   LOGICAL                    ::   ln_cat_usr   ! ice categories are defined by rn_catbnd
+   REAL(wp), DIMENSION(0:100) ::   rn_catbnd    ! ice categories bounds
+   REAL(wp)                   ::   rn_himax     ! maximum ice thickness allowed
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_itd_rem( kt )
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE ice_itd_rem ***
+      !!
+      !! ** Purpose :   computes the redistribution of ice thickness
+      !!                after thermodynamic growth of ice thickness
+      !!
+      !! ** Method  :   Linear remapping 
+      !!
+      !! References :   W.H. Lipscomb, JGR 2001
+      !!------------------------------------------------------------------
+      INTEGER , INTENT (in) ::   kt      ! Ocean time step 
+      !
+      INTEGER  ::   ji, jj, jl, jcat     ! dummy loop index
+      INTEGER  ::   ipti                 ! local integer
+      REAL(wp) ::   zx1, zwk1, zdh0, zetamin, zdamax   ! local scalars
+      REAL(wp) ::   zx2, zwk2, zda0, zetamax           !   -      -
+      REAL(wp) ::   zx3        
+      REAL(wp) ::   zslope          ! used to compute local thermodynamic "speeds"
+      !
+      INTEGER , DIMENSION(jpij)       ::   iptidx          ! compute remapping or not
+      INTEGER , DIMENSION(jpij,jpl-1) ::   jdonor          ! donor category index
+      REAL(wp), DIMENSION(jpij,jpl)   ::   zdhice          ! ice thickness increment
+      REAL(wp), DIMENSION(jpij,jpl)   ::   g0, g1          ! coefficients for fitting the line of the ITD
+      REAL(wp), DIMENSION(jpij,jpl)   ::   hL, hR          ! left and right boundary for the ITD for each thickness
+      REAL(wp), DIMENSION(jpij,jpl-1) ::   zdaice, zdvice  ! local increment of ice area and volume
+      REAL(wp), DIMENSION(jpij)       ::   zhb0, zhb1      ! category boundaries for thinnes categories
+      REAL(wp), DIMENSION(jpij,0:jpl) ::   zhbnew          ! new boundaries of ice categories
+      !!------------------------------------------------------------------
+
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_itd_rem: remapping ice thickness distribution' 
+
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'iceitd_rem', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'iceitd_rem',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+
+      !-----------------------------------------------------------------------------------------------
+      !  1) Identify grid cells with ice
+      !-----------------------------------------------------------------------------------------------
+      at_i(:,:) = SUM( a_i, dim=3 )
+      !
+      npti = 0   ;   nptidx(:) = 0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF ( at_i(ji,jj) > epsi10 ) THEN
+               npti = npti + 1
+               nptidx( npti ) = (jj - 1) * jpi + ji
+            ENDIF
+         END DO
+      END DO
+      
+      !-----------------------------------------------------------------------------------------------
+      !  2) Compute new category boundaries
+      !-----------------------------------------------------------------------------------------------
+      IF( npti > 0 ) THEN
+         !
+         zdhice(:,:) = 0._wp
+         zhbnew(:,:) = 0._wp
+         !
+         CALL tab_3d_2d( npti, nptidx(1:npti), h_i_2d (1:npti,1:jpl), h_i   )
+         CALL tab_3d_2d( npti, nptidx(1:npti), h_ib_2d(1:npti,1:jpl), h_i_b )
+         CALL tab_3d_2d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i   )
+         CALL tab_3d_2d( npti, nptidx(1:npti), a_ib_2d(1:npti,1:jpl), a_i_b )
+         !
+         DO jl = 1, jpl
+            ! Compute thickness change in each ice category
+            DO ji = 1, npti
+               IF( a_i_2d(ji,jl) > epsi10 )   zdhice(ji,jl) = h_i_2d(ji,jl) - h_ib_2d(ji,jl)
+            END DO
+         END DO
+         !
+         ! --- New boundaries for category 1:jpl-1 --- !
+         DO jl = 1, jpl - 1
+            !
+            DO ji = 1, npti
+               !
+               ! --- New boundary: Hn* = Hn + Fn*dt --- !
+               !     Fn*dt = ( fn + (fn+1 - fn)/(hn+1 - hn) * (Hn - hn) ) * dt = zdhice + zslope * (Hmax - h_i_b)
+               !
+               IF    ( a_ib_2d(ji,jl) >  epsi10 .AND. a_ib_2d(ji,jl+1) >  epsi10 ) THEN   ! a(jl+1) & a(jl) /= 0
+                  zslope        = ( zdhice(ji,jl+1) - zdhice(ji,jl) ) / ( h_ib_2d(ji,jl+1) - h_ib_2d(ji,jl) )
+                  zhbnew(ji,jl) = hi_max(jl) + zdhice(ji,jl) + zslope * ( hi_max(jl) - h_ib_2d(ji,jl) )
+               ELSEIF( a_ib_2d(ji,jl) >  epsi10 .AND. a_ib_2d(ji,jl+1) <= epsi10 ) THEN   ! a(jl+1)=0 => Hn* = Hn + fn*dt
+                  zhbnew(ji,jl) = hi_max(jl) + zdhice(ji,jl)
+               ELSEIF( a_ib_2d(ji,jl) <= epsi10 .AND. a_ib_2d(ji,jl+1) >  epsi10 ) THEN   ! a(jl)=0 => Hn* = Hn + fn+1*dt
+                  zhbnew(ji,jl) = hi_max(jl) + zdhice(ji,jl+1)
+               ELSE                                                                       ! a(jl+1) & a(jl) = 0 
+                  zhbnew(ji,jl) = hi_max(jl)
+               ENDIF
+               !
+               ! --- 2 conditions for remapping --- !
+               ! 1) hn(t+1)+espi < Hn* < hn+1(t+1)-epsi               
+               !    Note: hn(t+1) must not be too close to either HR or HL otherwise a division by nearly 0 is possible 
+               !          in itd_glinear in the case (HR-HL) = 3(Hice - HL) or = 3(HR - Hice)
+               IF( a_i_2d(ji,jl  ) > epsi10 .AND. h_i_2d(ji,jl  ) > ( zhbnew(ji,jl) - epsi10 ) )   nptidx(ji) = 0
+               IF( a_i_2d(ji,jl+1) > epsi10 .AND. h_i_2d(ji,jl+1) < ( zhbnew(ji,jl) + epsi10 ) )   nptidx(ji) = 0
+               !
+               ! 2) Hn-1 < Hn* < Hn+1  
+               IF( zhbnew(ji,jl) < hi_max(jl-1) )   nptidx(ji) = 0
+               IF( zhbnew(ji,jl) > hi_max(jl+1) )   nptidx(ji) = 0
+               !
+            END DO
+         END DO
+         !
+         ! --- New boundaries for category jpl --- !
+         DO ji = 1, npti
+            IF( a_i_2d(ji,jpl) > epsi10 ) THEN
+               zhbnew(ji,jpl) = MAX( hi_max(jpl-1), 3._wp * h_i_2d(ji,jpl) - 2._wp * zhbnew(ji,jpl-1) )
+            ELSE
+               zhbnew(ji,jpl) = hi_max(jpl)  
+            ENDIF
+            !
+            ! --- 1 additional condition for remapping (1st category) --- !
+            ! H0+epsi < h1(t) < H1-epsi 
+            !    h1(t) must not be too close to either HR or HL otherwise a division by nearly 0 is possible 
+            !    in itd_glinear in the case (HR-HL) = 3(Hice - HL) or = 3(HR - Hice)
+            IF( h_ib_2d(ji,1) < ( hi_max(0) + epsi10 ) )   nptidx(ji) = 0
+            IF( h_ib_2d(ji,1) > ( hi_max(1) - epsi10 ) )   nptidx(ji) = 0
+         END DO
+         !
+         !-----------------------------------------------------------------------------------------------
+         !  3) Identify cells where remapping
+         !-----------------------------------------------------------------------------------------------
+         ipti = 0   ;   iptidx(:) = 0
+         DO ji = 1, npti
+            IF( nptidx(ji) /= 0 ) THEN
+               ipti = ipti + 1
+               iptidx(ipti)   = nptidx(ji)
+               zhbnew(ipti,:) = zhbnew(ji,:)  ! adjust zhbnew to new indices
+            ENDIF
+         END DO
+         nptidx(:) = iptidx(:)
+         npti      = ipti
+         !
+      ENDIF
+   
+      !-----------------------------------------------------------------------------------------------
+      !  4) Compute g(h) 
+      !-----------------------------------------------------------------------------------------------
+      IF( npti > 0 ) THEN
+         !
+         zhb0(:) = hi_max(0)   ;   zhb1(:) = hi_max(1)
+         g0(:,:) = 0._wp       ;   g1(:,:) = 0._wp 
+         hL(:,:) = 0._wp       ;   hR(:,:) = 0._wp 
+         !
+         DO jl = 1, jpl
+            !
+            CALL tab_2d_1d( npti, nptidx(1:npti), h_ib_1d(1:npti), h_i_b(:,:,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d (1:npti), h_i  (:,:,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d (1:npti), a_i  (:,:,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), v_i_1d (1:npti), v_i  (:,:,jl) )
+            !
+            IF( jl == 1 ) THEN
+               !  
+               ! --- g(h) for category 1 --- !
+               CALL itd_glinear( zhb0(1:npti)  , zhb1(1:npti)  , h_ib_1d(1:npti)  , a_i_1d(1:npti)  ,  &   ! in
+                  &              g0  (1:npti,1), g1  (1:npti,1), hL     (1:npti,1), hR    (1:npti,1)   )   ! out
+               !
+               ! Area lost due to melting of thin ice
+               DO ji = 1, npti
+                  !
+                  IF( a_i_1d(ji) > epsi10 ) THEN
+                     !
+                     zdh0 =  h_i_1d(ji) - h_ib_1d(ji)                
+                     IF( zdh0 < 0.0 ) THEN      ! remove area from category 1
+                        zdh0 = MIN( -zdh0, hi_max(1) )
+                        !Integrate g(1) from 0 to dh0 to estimate area melted
+                        zetamax = MIN( zdh0, hR(ji,1) ) - hL(ji,1)
+                        !
+                        IF( zetamax > 0.0 ) THEN
+                           zx1    = zetamax
+                           zx2    = 0.5 * zetamax * zetamax 
+                           zda0   = g1(ji,1) * zx2 + g0(ji,1) * zx1                ! ice area removed
+                           zdamax = a_i_1d(ji) * (1.0 - h_i_1d(ji) / h_ib_1d(ji) ) ! Constrain new thickness <= h_i                
+                           zda0   = MIN( zda0, zdamax )                            ! ice area lost due to melting of thin ice (zdamax > 0)
+                           ! Remove area, conserving volume
+                           h_i_1d(ji) = h_i_1d(ji) * a_i_1d(ji) / ( a_i_1d(ji) - zda0 )
+                           a_i_1d(ji) = a_i_1d(ji) - zda0
+                           v_i_1d(ji) = a_i_1d(ji) * h_i_1d(ji) ! useless ?
+                        ENDIF
+                        !
+                     ELSE ! if ice accretion zdh0 > 0
+                        ! zhbnew was 0, and is shifted to the right to account for thin ice growth in openwater (F0 = f1)
+                        zhbnew(ji,0) = MIN( zdh0, hi_max(1) ) 
+                     ENDIF
+                     !
+                  ENDIF
+                  !
+               END DO
+               !
+               CALL tab_1d_2d( npti, nptidx(1:npti), h_i_1d(1:npti), h_i(:,:,jl) )
+               CALL tab_1d_2d( npti, nptidx(1:npti), a_i_1d(1:npti), a_i(:,:,jl) )
+               CALL tab_1d_2d( npti, nptidx(1:npti), v_i_1d(1:npti), v_i(:,:,jl) )
+               !
+            ENDIF ! jl=1
+            !
+            ! --- g(h) for each thickness category --- !  
+            CALL itd_glinear( zhbnew(1:npti,jl-1), zhbnew(1:npti,jl), h_i_1d(1:npti)   , a_i_1d(1:npti)   ,  &   ! in
+               &              g0    (1:npti,jl  ), g1    (1:npti,jl), hL    (1:npti,jl), hR    (1:npti,jl)   )   ! out
+            !
+         END DO
+         
+         !-----------------------------------------------------------------------------------------------
+         !  5) Compute area and volume to be shifted across each boundary (Eq. 18)
+         !-----------------------------------------------------------------------------------------------
+         DO jl = 1, jpl - 1
+            !
+            DO ji = 1, npti
+               !
+               ! left and right integration limits in eta space
+               IF (zhbnew(ji,jl) > hi_max(jl)) THEN ! Hn* > Hn => transfer from jl to jl+1
+                  zetamin = MAX( hi_max(jl)   , hL(ji,jl) ) - hL(ji,jl)   ! hi_max(jl) - hL 
+                  zetamax = MIN( zhbnew(ji,jl), hR(ji,jl) ) - hL(ji,jl)   ! hR - hL
+                  jdonor(ji,jl) = jl
+               ELSE                                 ! Hn* <= Hn => transfer from jl+1 to jl
+                  zetamin = 0.0
+                  zetamax = MIN( hi_max(jl), hR(ji,jl+1) ) - hL(ji,jl+1)  ! hi_max(jl) - hL
+                  jdonor(ji,jl) = jl + 1
+               ENDIF
+               zetamax = MAX( zetamax, zetamin ) ! no transfer if etamax < etamin
+               !
+               zx1  = zetamax - zetamin
+               zwk1 = zetamin * zetamin
+               zwk2 = zetamax * zetamax
+               zx2  = 0.5 * ( zwk2 - zwk1 )
+               zwk1 = zwk1 * zetamin
+               zwk2 = zwk2 * zetamax
+               zx3  = 1.0 / 3.0 * ( zwk2 - zwk1 )
+               jcat = jdonor(ji,jl)
+               zdaice(ji,jl) = g1(ji,jcat)*zx2 + g0(ji,jcat)*zx1
+               zdvice(ji,jl) = g1(ji,jcat)*zx3 + g0(ji,jcat)*zx2 + zdaice(ji,jl)*hL(ji,jcat)
+               !
+            END DO
+         END DO
+         
+         !----------------------------------------------------------------------------------------------
+         ! 6) Shift ice between categories
+         !----------------------------------------------------------------------------------------------
+         CALL itd_shiftice ( jdonor(1:npti,:), zdaice(1:npti,:), zdvice(1:npti,:) )
+         
+         !----------------------------------------------------------------------------------------------
+         ! 7) Make sure h_i >= minimum ice thickness hi_min
+         !----------------------------------------------------------------------------------------------
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d (1:npti), h_i (:,:,1) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d (1:npti), a_i (:,:,1) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d(1:npti), a_ip(:,:,1) )
+         !
+         DO ji = 1, npti
+            IF ( a_i_1d(ji) > epsi10 .AND. h_i_1d(ji) < rn_himin ) THEN
+               a_i_1d(ji) = a_i_1d(ji) * h_i_1d(ji) / rn_himin 
+               IF( ln_pnd_LEV )   a_ip_1d(ji) = a_ip_1d(ji) * h_i_1d(ji) / rn_himin
+               h_i_1d(ji) = rn_himin
+            ENDIF
+         END DO
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_i_1d (1:npti), h_i (:,:,1) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_i_1d (1:npti), a_i (:,:,1) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_ip_1d(1:npti), a_ip(:,:,1) )
+         !
+      ENDIF
+      !
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'iceitd_rem', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'iceitd_rem',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      !
+   END SUBROUTINE ice_itd_rem
+
+
+   SUBROUTINE itd_glinear( HbL, Hbr, phice, paice, pg0, pg1, phL, phR )
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE itd_glinear ***
+      !!
+      !! ** Purpose :   build g(h) satisfying area and volume constraints (Eq. 6 and 9)
+      !!
+      !! ** Method  :   g(h) is linear and written as: g(eta) = g1(eta) + g0
+      !!                with eta = h - HL
+      !!------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   HbL, HbR      ! left and right category boundaries
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   phice, paice  ! ice thickness and concentration
+      REAL(wp), DIMENSION(:), INTENT(inout) ::   pg0, pg1      ! coefficients in linear equation for g(eta)
+      REAL(wp), DIMENSION(:), INTENT(inout) ::   phL, phR      ! min and max value of range over which g(h) > 0
+      !
+      INTEGER  ::   ji           ! horizontal indices
+      REAL(wp) ::   z1_3 , z2_3  ! 1/3 , 2/3
+      REAL(wp) ::   zh13         ! HbL + 1/3 * (HbR - HbL)
+      REAL(wp) ::   zh23         ! HbL + 2/3 * (HbR - HbL)
+      REAL(wp) ::   zdhr         ! 1 / (hR - hL)
+      REAL(wp) ::   zwk1, zwk2   ! temporary variables
+      !!------------------------------------------------------------------
+      !
+      z1_3 = 1._wp / 3._wp
+      z2_3 = 2._wp / 3._wp
+      !
+      DO ji = 1, npti
+         !
+         IF( paice(ji) > epsi10  .AND. phice(ji) > epsi10 )  THEN
+            !
+            ! Initialize hL and hR
+            phL(ji) = HbL(ji)
+            phR(ji) = HbR(ji)
+            !
+            ! Change hL or hR if hice falls outside central third of range,
+            ! so that hice is in the central third of the range [HL HR]
+            zh13 = z1_3 * ( 2._wp * phL(ji) +         phR(ji) )
+            zh23 = z1_3 * (         phL(ji) + 2._wp * phR(ji) )
+            !
+            IF    ( phice(ji) < zh13 ) THEN   ;   phR(ji) = 3._wp * phice(ji) - 2._wp * phL(ji) ! move HR to the left
+            ELSEIF( phice(ji) > zh23 ) THEN   ;   phL(ji) = 3._wp * phice(ji) - 2._wp * phR(ji) ! move HL to the right
+            ENDIF
+            !
+            ! Compute coefficients of g(eta) = g0 + g1*eta
+            zdhr = 1._wp / (phR(ji) - phL(ji))
+            zwk1 = 6._wp * paice(ji) * zdhr
+            zwk2 = ( phice(ji) - phL(ji) ) * zdhr
+            pg0(ji) = zwk1 * ( z2_3 - zwk2 )                    ! Eq. 14
+            pg1(ji) = 2._wp * zdhr * zwk1 * ( zwk2 - 0.5_wp )   ! Eq. 14
+            !
+         ELSE  ! remap_flag = .false. or a_i < epsi10 
+            phL(ji) = 0._wp
+            phR(ji) = 0._wp
+            pg0(ji) = 0._wp
+            pg1(ji) = 0._wp
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE itd_glinear
+
+
+   SUBROUTINE itd_shiftice( kdonor, pdaice, pdvice )
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE itd_shiftice ***
+      !!
+      !! ** Purpose :   shift ice across category boundaries, conserving everything
+      !!              ( area, volume, energy, age*vol, and mass of salt )
+      !!------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(in) ::   kdonor   ! donor category index
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pdaice   ! ice area transferred across boundary
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pdvice   ! ice volume transferred across boundary
+      !
+      INTEGER  ::   ji, jl, jk         ! dummy loop indices
+      INTEGER  ::   jl2, jl1           ! local integers
+      REAL(wp) ::   ztrans             ! ice/snow transferred
+      REAL(wp), DIMENSION(jpij)            ::   zworka, zworkv   ! workspace
+      REAL(wp), DIMENSION(jpij,jpl)        ::   zaTsfn           !  -    -
+      REAL(wp), DIMENSION(jpij,nlay_i,jpl) ::   ze_i_2d
+      REAL(wp), DIMENSION(jpij,nlay_s,jpl) ::   ze_s_2d
+      !!------------------------------------------------------------------
+         
+      CALL tab_3d_2d( npti, nptidx(1:npti), h_i_2d (1:npti,1:jpl), h_i  )
+      CALL tab_3d_2d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i  )
+      CALL tab_3d_2d( npti, nptidx(1:npti), v_i_2d (1:npti,1:jpl), v_i  )
+      CALL tab_3d_2d( npti, nptidx(1:npti), v_s_2d (1:npti,1:jpl), v_s  )
+      CALL tab_3d_2d( npti, nptidx(1:npti), oa_i_2d(1:npti,1:jpl), oa_i )
+      CALL tab_3d_2d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i )
+      CALL tab_3d_2d( npti, nptidx(1:npti), a_ip_2d(1:npti,1:jpl), a_ip )
+      CALL tab_3d_2d( npti, nptidx(1:npti), v_ip_2d(1:npti,1:jpl), v_ip )
+      CALL tab_3d_2d( npti, nptidx(1:npti), v_il_2d(1:npti,1:jpl), v_il )
+      CALL tab_3d_2d( npti, nptidx(1:npti), t_su_2d(1:npti,1:jpl), t_su )
+      DO jl = 1, jpl
+         DO jk = 1, nlay_s
+            CALL tab_2d_1d( npti, nptidx(1:npti), ze_s_2d(1:npti,jk,jl), e_s(:,:,jk,jl) )
+         END DO
+         DO jk = 1, nlay_i
+            CALL tab_2d_1d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+         END DO
+      END DO
+      ! to correct roundoff errors on a_i
+      CALL tab_2d_1d( npti, nptidx(1:npti), rn_amax_1d(1:npti), rn_amax_2d )
+
+      !----------------------------------------------------------------------------------------------
+      ! 1) Define a variable equal to a_i*T_su
+      !----------------------------------------------------------------------------------------------
+      DO jl = 1, jpl
+         DO ji = 1, npti
+            zaTsfn(ji,jl) = a_i_2d(ji,jl) * t_su_2d(ji,jl)
+         END DO
+      END DO
+      
+      !-------------------------------------------------------------------------------
+      ! 2) Transfer volume and energy between categories
+      !-------------------------------------------------------------------------------
+      DO jl = 1, jpl - 1
+         DO ji = 1, npti
+            !
+            jl1 = kdonor(ji,jl)
+            !
+            IF( jl1 > 0 ) THEN
+               !
+               IF ( jl1 == jl  ) THEN   ;   jl2 = jl1+1
+               ELSE                     ;   jl2 = jl 
+               ENDIF
+               !
+               IF( v_i_2d(ji,jl1) >= epsi10 ) THEN   ;   zworkv(ji) = pdvice(ji,jl) / v_i_2d(ji,jl1)
+               ELSE                                  ;   zworkv(ji) = 0._wp
+               ENDIF
+               IF( a_i_2d(ji,jl1) >= epsi10 ) THEN   ;   zworka(ji) = pdaice(ji,jl) / a_i_2d(ji,jl1)
+               ELSE                                  ;   zworka(ji) = 0._wp
+               ENDIF
+               !
+               a_i_2d(ji,jl1) = a_i_2d(ji,jl1) - pdaice(ji,jl)       ! Ice areas
+               a_i_2d(ji,jl2) = a_i_2d(ji,jl2) + pdaice(ji,jl)
+               !
+               v_i_2d(ji,jl1) = v_i_2d(ji,jl1) - pdvice(ji,jl)       ! Ice volumes
+               v_i_2d(ji,jl2) = v_i_2d(ji,jl2) + pdvice(ji,jl)
+               !
+               ztrans         = v_s_2d(ji,jl1) * zworkv(ji)          ! Snow volumes
+               v_s_2d(ji,jl1) = v_s_2d(ji,jl1) - ztrans
+               v_s_2d(ji,jl2) = v_s_2d(ji,jl2) + ztrans 
+               !
+               ztrans          = oa_i_2d(ji,jl1) * zworka(ji)        ! Ice age
+               oa_i_2d(ji,jl1) = oa_i_2d(ji,jl1) - ztrans
+               oa_i_2d(ji,jl2) = oa_i_2d(ji,jl2) + ztrans
+               !
+               ztrans          = sv_i_2d(ji,jl1) * zworkv(ji)        ! Ice salinity
+               sv_i_2d(ji,jl1) = sv_i_2d(ji,jl1) - ztrans
+               sv_i_2d(ji,jl2) = sv_i_2d(ji,jl2) + ztrans
+               !
+               ztrans          = zaTsfn(ji,jl1) * zworka(ji)         ! Surface temperature
+               zaTsfn(ji,jl1)  = zaTsfn(ji,jl1) - ztrans
+               zaTsfn(ji,jl2)  = zaTsfn(ji,jl2) + ztrans
+               !  
+               IF ( ln_pnd_LEV ) THEN
+                  ztrans          = a_ip_2d(ji,jl1) * zworka(ji)     ! Pond fraction
+                  a_ip_2d(ji,jl1) = a_ip_2d(ji,jl1) - ztrans
+                  a_ip_2d(ji,jl2) = a_ip_2d(ji,jl2) + ztrans
+                  !                                              
+                  ztrans          = v_ip_2d(ji,jl1) * zworka(ji)     ! Pond volume (also proportional to da/a)
+                  v_ip_2d(ji,jl1) = v_ip_2d(ji,jl1) - ztrans
+                  v_ip_2d(ji,jl2) = v_ip_2d(ji,jl2) + ztrans
+                  !
+                  IF ( ln_pnd_lids ) THEN                            ! Pond lid volume
+                     ztrans          = v_il_2d(ji,jl1) * zworka(ji)
+                     v_il_2d(ji,jl1) = v_il_2d(ji,jl1) - ztrans
+                     v_il_2d(ji,jl2) = v_il_2d(ji,jl2) + ztrans
+                  ENDIF
+               ENDIF
+               !
+            ENDIF   ! jl1 >0
+         END DO
+         !
+         DO jk = 1, nlay_s         !--- Snow heat content
+            DO ji = 1, npti
+               !
+               jl1 = kdonor(ji,jl)
+               !
+               IF( jl1 > 0 ) THEN
+                  IF(jl1 == jl) THEN  ;  jl2 = jl+1
+                  ELSE                ;  jl2 = jl
+                  ENDIF
+                  ztrans             = ze_s_2d(ji,jk,jl1) * zworkv(ji)
+                  ze_s_2d(ji,jk,jl1) = ze_s_2d(ji,jk,jl1) - ztrans
+                  ze_s_2d(ji,jk,jl2) = ze_s_2d(ji,jk,jl2) + ztrans
+               ENDIF
+            END DO
+         END DO
+         !
+         DO jk = 1, nlay_i         !--- Ice heat content
+            DO ji = 1, npti
+               !
+               jl1 = kdonor(ji,jl)
+               !
+               IF( jl1 > 0 ) THEN
+                  IF(jl1 == jl) THEN  ;  jl2 = jl+1
+                  ELSE                ;  jl2 = jl
+                  ENDIF
+                  ztrans             = ze_i_2d(ji,jk,jl1) * zworkv(ji)
+                  ze_i_2d(ji,jk,jl1) = ze_i_2d(ji,jk,jl1) - ztrans
+                  ze_i_2d(ji,jk,jl2) = ze_i_2d(ji,jk,jl2) + ztrans
+               ENDIF
+            END DO
+         END DO
+         !
+      END DO                   ! boundaries, 1 to jpl-1
+
+      !-------------------
+      ! 3) roundoff errors
+      !-------------------
+      ! clem: The transfer between one category to another can lead to very small negative values (-1.e-20)
+      !       because of truncation error ( i.e. 1. - 1. /= 0 )
+      CALL ice_var_roundoff( a_i_2d, v_i_2d, v_s_2d, sv_i_2d, oa_i_2d, a_ip_2d, v_ip_2d, v_il_2d, ze_s_2d, ze_i_2d )
+
+      ! at_i must be <= rn_amax
+      zworka(1:npti) = SUM( a_i_2d(1:npti,:), dim=2 )
+      DO jl  = 1, jpl
+         WHERE( zworka(1:npti) > rn_amax_1d(1:npti) )   &
+            &   a_i_2d(1:npti,jl) = a_i_2d(1:npti,jl) * rn_amax_1d(1:npti) / zworka(1:npti)
+      END DO
+      
+      !-------------------------------------------------------------------------------
+      ! 4) Update ice thickness and temperature
+      !-------------------------------------------------------------------------------
+      WHERE( a_i_2d(1:npti,:) >= epsi20 )
+         h_i_2d (1:npti,:)  =  v_i_2d(1:npti,:) / a_i_2d(1:npti,:) 
+         t_su_2d(1:npti,:)  =  zaTsfn(1:npti,:) / a_i_2d(1:npti,:) 
+      ELSEWHERE
+         h_i_2d (1:npti,:)  = 0._wp
+         t_su_2d(1:npti,:)  = rt0
+      END WHERE
+      !
+      CALL tab_2d_3d( npti, nptidx(1:npti), h_i_2d (1:npti,1:jpl), h_i  )
+      CALL tab_2d_3d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i  )
+      CALL tab_2d_3d( npti, nptidx(1:npti), v_i_2d (1:npti,1:jpl), v_i  )
+      CALL tab_2d_3d( npti, nptidx(1:npti), v_s_2d (1:npti,1:jpl), v_s  )
+      CALL tab_2d_3d( npti, nptidx(1:npti), oa_i_2d(1:npti,1:jpl), oa_i )
+      CALL tab_2d_3d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i )
+      CALL tab_2d_3d( npti, nptidx(1:npti), a_ip_2d(1:npti,1:jpl), a_ip )
+      CALL tab_2d_3d( npti, nptidx(1:npti), v_ip_2d(1:npti,1:jpl), v_ip )
+      CALL tab_2d_3d( npti, nptidx(1:npti), v_il_2d(1:npti,1:jpl), v_il )
+      CALL tab_2d_3d( npti, nptidx(1:npti), t_su_2d(1:npti,1:jpl), t_su )
+      DO jl = 1, jpl
+         DO jk = 1, nlay_s
+            CALL tab_1d_2d( npti, nptidx(1:npti), ze_s_2d(1:npti,jk,jl), e_s(:,:,jk,jl) )
+         END DO
+         DO jk = 1, nlay_i
+            CALL tab_1d_2d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+         END DO
+      END DO
+      !
+   END SUBROUTINE itd_shiftice
+   
+
+   SUBROUTINE ice_itd_reb( kt )
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE ice_itd_reb ***
+      !!
+      !! ** Purpose : rebin - rebins thicknesses into defined categories
+      !!
+      !! ** Method  : If a category thickness is out of bounds, shift part (for down to top)
+      !!              or entire (for top to down) area, volume, and energy
+      !!              to the neighboring category
+      !!------------------------------------------------------------------
+      INTEGER , INTENT (in) ::   kt      ! Ocean time step 
+      INTEGER ::   ji, jj, jl   ! dummy loop indices
+      !
+      INTEGER , DIMENSION(jpij,jpl-1) ::   jdonor           ! donor category index
+      REAL(wp), DIMENSION(jpij,jpl-1) ::   zdaice, zdvice   ! ice area and volume transferred
+      !!------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp )   WRITE(numout,*) '-- ice_itd_reb: rebining ice thickness distribution' 
+      !
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'iceitd_reb', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'iceitd_reb',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      !
+      jdonor(:,:) = 0
+      zdaice(:,:) = 0._wp
+      zdvice(:,:) = 0._wp
+      !
+      !                       !---------------------------------------
+      DO jl = 1, jpl-1        ! identify thicknesses that are too big
+         !                    !---------------------------------------
+         npti = 0   ;   nptidx(:) = 0
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( a_i(ji,jj,jl) > 0._wp .AND. v_i(ji,jj,jl) > (a_i(ji,jj,jl) * hi_max(jl)) ) THEN
+                  npti = npti + 1
+                  nptidx( npti ) = (jj - 1) * jpi + ji                  
+               ENDIF
+            END DO
+         END DO
+         !
+         IF( npti > 0 ) THEN            
+            !!clem   CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d(1:npti), h_i(:,:,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d(1:npti), a_i(:,:,jl) )
+            CALL tab_2d_1d( npti, nptidx(1:npti), v_i_1d(1:npti), v_i(:,:,jl) )
+            !
+            DO ji = 1, npti
+               jdonor(ji,jl)  = jl 
+               ! how much of a_i you send in cat sup is somewhat arbitrary
+               !!clem: these do not work properly after a restart (I do not know why) => not sure it is still true
+               !!          zdaice(ji,jl)  = a_i_1d(ji) * ( h_i_1d(ji) - hi_max(jl) + epsi10 ) / h_i_1d(ji)  
+               !!          zdvice(ji,jl)  = v_i_1d(ji) - ( a_i_1d(ji) - zdaice(ji,jl) ) * ( hi_max(jl) - epsi10 )
+               !!clem: these do not work properly after a restart (I do not know why) => not sure it is still true
+               !!          zdaice(ji,jl)  = a_i_1d(ji)
+               !!          zdvice(ji,jl)  = v_i_1d(ji)
+               !!clem: these are from UCL and work ok
+               zdaice(ji,jl)  = a_i_1d(ji) * 0.5_wp
+               zdvice(ji,jl)  = v_i_1d(ji) - zdaice(ji,jl) * ( hi_max(jl) + hi_max(jl-1) ) * 0.5_wp
+            END DO
+            !
+            CALL itd_shiftice( jdonor(1:npti,:), zdaice(1:npti,:), zdvice(1:npti,:) )  ! Shift jl=>jl+1
+            ! Reset shift parameters
+            jdonor(1:npti,jl) = 0
+            zdaice(1:npti,jl) = 0._wp
+            zdvice(1:npti,jl) = 0._wp
+         ENDIF
+         !
+      END DO
+
+      !                       !-----------------------------------------
+      DO jl = jpl-1, 1, -1    ! Identify thicknesses that are too small
+         !                    !-----------------------------------------
+         npti = 0 ; nptidx(:) = 0
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( a_i(ji,jj,jl+1) > 0._wp .AND. v_i(ji,jj,jl+1) <= (a_i(ji,jj,jl+1) * hi_max(jl)) ) THEN
+                  npti = npti + 1
+                  nptidx( npti ) = (jj - 1) * jpi + ji                  
+               ENDIF
+            END DO
+         END DO
+         !
+         IF( npti > 0 ) THEN
+            CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d(1:npti), a_i(:,:,jl+1) ) ! jl+1 is ok
+            CALL tab_2d_1d( npti, nptidx(1:npti), v_i_1d(1:npti), v_i(:,:,jl+1) ) ! jl+1 is ok
+            !
+            DO ji = 1, npti
+               jdonor(ji,jl) = jl + 1
+               zdaice(ji,jl) = a_i_1d(ji) 
+               zdvice(ji,jl) = v_i_1d(ji)
+            END DO
+            !
+            CALL itd_shiftice( jdonor(1:npti,:), zdaice(1:npti,:), zdvice(1:npti,:) )  ! Shift jl+1=>jl
+            ! Reset shift parameters
+            jdonor(1:npti,jl) = 0
+            zdaice(1:npti,jl) = 0._wp
+            zdvice(1:npti,jl) = 0._wp
+         ENDIF
+         !
+      END DO
+      !
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'iceitd_reb', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'iceitd_reb',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      !
+   END SUBROUTINE ice_itd_reb
+
+
+   SUBROUTINE ice_itd_init
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE ice_itd_init ***
+      !!
+      !! ** Purpose :   Initializes the ice thickness distribution
+      !! ** Method  :   ...
+      !! ** input   :   Namelist namitd
+      !!-------------------------------------------------------------------
+      INTEGER  ::   jl            ! dummy loop index
+      INTEGER  ::   ios, ioptio   ! Local integer output status for namelist read
+      REAL(wp) ::   zhmax, znum, zden, zalpha   !   -      -
+      !
+      NAMELIST/namitd/ ln_cat_hfn, rn_himean, ln_cat_usr, rn_catbnd, rn_himin, rn_himax
+      !!------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )      ! Namelist namitd in reference namelist : Parameters for ice
+      READ  ( numnam_ice_ref, namitd, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namitd in reference namelist' )
+      REWIND( numnam_ice_cfg )      ! Namelist namitd in configuration namelist : Parameters for ice
+      READ  ( numnam_ice_cfg, namitd, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namitd in configuration namelist' )
+      IF(lwm) WRITE( numoni, namitd )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_itd_init: Initialization of ice cat distribution '
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namitd: '
+         WRITE(numout,*) '      Ice categories are defined by a function of rn_himean**(-0.05)    ln_cat_hfn = ', ln_cat_hfn
+         WRITE(numout,*) '         mean ice thickness in the domain                               rn_himean  = ', rn_himean
+         WRITE(numout,*) '      Ice categories are defined by rn_catbnd                           ln_cat_usr = ', ln_cat_usr
+         WRITE(numout,*) '      minimum ice thickness allowed                                     rn_himin   = ', rn_himin 
+         WRITE(numout,*) '      maximum ice thickness allowed                                     rn_himax   = ', rn_himax 
+      ENDIF
+      !
+      !-----------------------------------!
+      !  Thickness categories boundaries  !
+      !-----------------------------------!
+      !                             !== set the choice of ice categories ==!
+      ioptio = 0 
+      IF( ln_cat_hfn ) THEN   ;   ioptio = ioptio + 1   ;   nice_catbnd = np_cathfn    ;   ENDIF
+      IF( ln_cat_usr ) THEN   ;   ioptio = ioptio + 1   ;   nice_catbnd = np_catusr    ;   ENDIF
+      IF( ioptio /= 1 )   CALL ctl_stop( 'ice_itd_init: choose one and only one ice categories boundaries' )
+      !
+      SELECT CASE( nice_catbnd )
+      !                                !------------------------!
+      CASE( np_cathfn )                ! h^(-alpha) function
+         !                             !------------------------!
+         zalpha = 0.05_wp
+         zhmax  = 3._wp * rn_himean
+         hi_max(0) = 0._wp
+         DO jl = 1, jpl
+            znum = jpl * ( zhmax+1 )**zalpha
+            zden = REAL( jpl-jl , wp ) * ( zhmax + 1._wp )**zalpha + REAL( jl , wp )
+            hi_max(jl) = ( znum / zden )**(1./zalpha) - 1
+         END DO
+         !                             !------------------------!
+      CASE( np_catusr )                ! user defined
+         !                             !------------------------!
+         DO jl = 0, jpl
+            hi_max(jl) = rn_catbnd(jl)
+         END DO
+         !
+      END SELECT
+      !
+      DO jl = 1, jpl                ! mean thickness by category
+         hi_mean(jl) = ( hi_max(jl) + hi_max(jl-1) ) * 0.5_wp
+      END DO
+      !
+      hi_max(jpl) = rn_himax        ! set to a big value to ensure that all ice is thinner than hi_max(jpl)
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   ===>>>   resulting thickness category boundaries :'
+      IF(lwp) WRITE(numout,*) '            hi_max(:)= ', hi_max(0:jpl)
+      !
+      IF( hi_max(1) < rn_himin )   CALL ctl_stop('ice_itd_init: the upper bound of the 1st category must be bigger than rn_himin')
+      !
+   END SUBROUTINE ice_itd_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE iceitd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icerst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icerst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icerst.F90	(revision 14097)
@@ -0,0 +1,314 @@
+MODULE icerst
+   !!======================================================================
+   !!                     ***  MODULE  icerst  ***
+   !!   sea-ice :  write/read the ice restart file
+   !!======================================================================
+   !! History:   4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_rst_opn   : open  restart file
+   !!   ice_rst_write : write restart file 
+   !!   ice_rst_read  : read  restart file 
+   !!----------------------------------------------------------------------
+   USE ice            ! sea-ice: variables
+   USE dom_oce        ! ocean domain
+   USE phycst  , ONLY : rt0
+   USE sbc_oce , ONLY : nn_fsbc, ln_cpl
+   USE sbc_oce , ONLY : nn_components, jp_iam_sas   ! SAS ss[st]_m init
+   USE sbc_oce , ONLY : sst_m, sss_m                ! SAS ss[st]_m init
+   USE oce     , ONLY : tsn                         ! SAS ss[st]_m init
+   USE eosbn2  , ONLY : l_useCT, eos_pt_from_ct     ! SAS ss[st]_m init
+   USE iceistate      ! sea-ice: initial state
+   USE icectl         ! sea-ice: control
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_rst_opn     ! called by icestp
+   PUBLIC   ice_rst_write   ! called by icestp
+   PUBLIC   ice_rst_read    ! called by ice_init
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_rst_opn( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ice_rst_opn  ***
+      !!
+      !! ** purpose  :   open restart file
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      !
+      CHARACTER(len=20)   ::   clkt     ! ocean time-step define as a character
+      CHARACTER(len=50)   ::   clname   ! ice output restart file name
+      CHARACTER(len=256)  ::   clpath   ! full path to ice output restart file 
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 )   lrst_ice = .FALSE.   ! default definition
+
+      IF( ln_rst_list .OR. nn_stock /= -1 ) THEN
+      ! in order to get better performances with NetCDF format, we open and define the ice restart file 
+      ! one ice time step before writing the data (-> at nitrst - 2*nn_fsbc + 1), except if we write ice 
+      ! restart files every ice time step or if an ice restart file was writen at nitend - 2*nn_fsbc + 1
+      IF( kt == nitrst - 2*nn_fsbc + 1 .OR. nn_stock == nn_fsbc    &
+         &                             .OR. ( kt == nitend - nn_fsbc + 1 .AND. .NOT. lrst_ice ) ) THEN
+         IF( nitrst <= nitend .AND. nitrst > 0 ) THEN
+            ! beware of the format used to write kt (default is i8.8, that should be large enough...)
+            IF( nitrst > 99999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
+            ELSE                           ;   WRITE(clkt, '(i8.8)') nitrst
+            ENDIF
+            ! create the file
+            clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_icerst_out)
+            clpath = TRIM(cn_icerst_outdir) 
+            IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath)//'/'
+            IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) '             open ice restart NetCDF file: ',TRIM(clpath)//clname
+               IF( kt == nitrst - 2*nn_fsbc + 1 ) THEN
+                  WRITE(numout,*) '             kt = nitrst - 2*nn_fsbc + 1 = ', kt,' date= ', ndastp
+               ELSE
+                  WRITE(numout,*) '             kt = '                         , kt,' date= ', ndastp
+               ENDIF
+            ENDIF
+            !
+            CALL iom_open( TRIM(clpath)//TRIM(clname), numriw, ldwrt = .TRUE., kdlev = jpl )
+            lrst_ice = .TRUE.
+         ENDIF
+      ENDIF
+      ENDIF
+      !
+      IF( ln_icectl )   CALL ice_prt( kt, iiceprt, jiceprt, 1, ' - Beginning the time step - ' )   ! control print
+      !
+   END SUBROUTINE ice_rst_opn
+
+
+   SUBROUTINE ice_rst_write( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ice_rst_write  ***
+      !!
+      !! ** purpose  :   write restart file
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! number of iteration
+      !!
+      INTEGER ::   jk    ! dummy loop indices
+      INTEGER ::   iter
+      CHARACTER(len=25) ::   znam
+      CHARACTER(len=2)  ::   zchar, zchar1
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z3d   ! 3D workspace
+      !!----------------------------------------------------------------------
+
+      iter = kt + nn_fsbc - 1   ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+
+      IF( iter == nitrst ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'ice_rst_write : write ice restart file  kt =', kt
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'         
+      ENDIF
+
+      ! Write in numriw (if iter == nitrst)
+      ! ------------------ 
+      !                                                                        ! calendar control
+      CALL iom_rstput( iter, nitrst, numriw, 'nn_fsbc', REAL( nn_fsbc, wp ) )      ! time-step 
+      CALL iom_rstput( iter, nitrst, numriw, 'kt_ice' , REAL( iter   , wp ) )      ! date
+      CALL iom_delay_rst( 'WRITE', 'ICE', numriw )   ! save only ice delayed global communication variables
+
+      ! Prognostic variables
+      CALL iom_rstput( iter, nitrst, numriw, 'v_i'  , v_i   )
+      CALL iom_rstput( iter, nitrst, numriw, 'v_s'  , v_s   )
+      CALL iom_rstput( iter, nitrst, numriw, 'sv_i' , sv_i  )
+      CALL iom_rstput( iter, nitrst, numriw, 'a_i'  , a_i   )
+      CALL iom_rstput( iter, nitrst, numriw, 't_su' , t_su  )
+      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, 'oa_i' , oa_i  )
+      CALL iom_rstput( iter, nitrst, numriw, 'a_ip' , a_ip  )
+      CALL iom_rstput( iter, nitrst, numriw, 'v_ip' , v_ip  )
+      CALL iom_rstput( iter, nitrst, numriw, 'v_il' , v_il  )
+      ! Snow enthalpy
+      DO jk = 1, nlay_s 
+         WRITE(zchar1,'(I2.2)') jk
+         znam = 'e_s'//'_l'//zchar1
+         z3d(:,:,:) = e_s(:,:,jk,:)
+         CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+      END DO
+      ! Ice enthalpy
+      DO jk = 1, nlay_i 
+         WRITE(zchar1,'(I2.2)') jk
+         znam = 'e_i'//'_l'//zchar1
+         z3d(:,:,:) = e_i(:,:,jk,:)
+         CALL iom_rstput( iter, nitrst, numriw, znam , z3d )
+      END DO
+      ! fields needed for Met Office (Jules) coupling
+      IF( ln_cpl ) THEN
+         CALL iom_rstput( iter, nitrst, numriw, 'cnd_ice', cnd_ice )
+         CALL iom_rstput( iter, nitrst, numriw, 't1_ice' , t1_ice  )
+      ENDIF
+      !
+
+      ! close restart file
+      ! ------------------
+      IF( iter == nitrst ) THEN
+         CALL iom_close( numriw )
+         lrst_ice = .FALSE.
+      ENDIF
+      !
+   END SUBROUTINE ice_rst_write
+
+
+   SUBROUTINE ice_rst_read
+      !!----------------------------------------------------------------------
+      !!                    ***  ice_rst_read  ***
+      !!
+      !! ** purpose  :   read restart file
+      !!----------------------------------------------------------------------
+      INTEGER           ::   jk
+      LOGICAL           ::   llok
+      INTEGER           ::   id0, id1, id2, id3, id4, id5   ! local integer
+      CHARACTER(len=25) ::   znam
+      CHARACTER(len=2)  ::   zchar, zchar1
+      REAL(wp)          ::   zfice, ziter
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z3d   ! 3D workspace
+      !!----------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_rst_read: read ice NetCDF restart file'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+
+      CALL iom_open ( TRIM(cn_icerst_indir)//'/'//cn_icerst_in, numrir, kdlev = jpl )
+
+      ! test if v_i exists 
+      id0 = iom_varid( numrir, 'v_i' , ldstop = .FALSE. )
+
+      !                    ! ------------------------------ !
+      IF( id0 > 0 ) THEN   ! == case of a normal restart == !
+         !                 ! ------------------------------ !
+         
+         ! Time info
+         CALL iom_get( numrir, 'nn_fsbc', zfice )
+         CALL iom_get( numrir, 'kt_ice' , ziter )    
+         IF(lwp) WRITE(numout,*) '   read ice restart file at time step    : ', ziter
+         IF(lwp) WRITE(numout,*) '   in any case we force it to nit000 - 1 : ', nit000 - 1
+
+         ! Control of date
+         IF( ( nit000 - NINT(ziter) ) /= 1 .AND. ABS( nrstdt ) == 1 )   &
+            &     CALL ctl_stop( 'ice_rst_read ===>>>> : problem with nit000 in ice restart',  &
+            &                   '   verify the file or rerun with the value 0 for the',        &
+            &                   '   control of time parameter  nrstdt' )
+         IF( NINT(zfice) /= nn_fsbc          .AND. ABS( nrstdt ) == 1 )   &
+            &     CALL ctl_stop( 'ice_rst_read ===>>>> : problem with nn_fsbc in ice restart',  &
+            &                   '   verify the file or rerun with the value 0 for the',         &
+            &                   '   control of time parameter  nrstdt' )
+
+         ! --- mandatory fields --- ! 
+         CALL iom_get( numrir, jpdom_autoglo, 'v_i'  , v_i   )
+         CALL iom_get( numrir, jpdom_autoglo, 'v_s'  , v_s   )
+         CALL iom_get( numrir, jpdom_autoglo, 'sv_i' , sv_i  )
+         CALL iom_get( numrir, jpdom_autoglo, 'a_i'  , a_i   )
+         CALL iom_get( numrir, jpdom_autoglo, 't_su' , t_su  )
+         CALL iom_get( numrir, jpdom_autoglo, 'u_ice', u_ice )
+         CALL iom_get( numrir, jpdom_autoglo, 'v_ice', v_ice )
+         ! Snow enthalpy
+         DO jk = 1, nlay_s
+            WRITE(zchar1,'(I2.2)') jk
+            znam = 'e_s'//'_l'//zchar1
+            CALL iom_get( numrir, jpdom_autoglo, znam , z3d )
+            e_s(:,:,jk,:) = z3d(:,:,:)
+         END DO
+         ! Ice enthalpy
+         DO jk = 1, nlay_i
+            WRITE(zchar1,'(I2.2)') jk
+            znam = 'e_i'//'_l'//zchar1
+            CALL iom_get( numrir, jpdom_autoglo, znam , z3d )
+            e_i(:,:,jk,:) = z3d(:,:,:)
+         END DO
+         ! -- optional fields -- !
+         ! ice age
+         id1 = iom_varid( numrir, 'oa_i' , ldstop = .FALSE. )
+         IF( id1 > 0 ) THEN                       ! fields exist
+            CALL iom_get( numrir, jpdom_autoglo, 'oa_i', oa_i )
+         ELSE                                     ! start from rest
+            IF(lwp) WRITE(numout,*) '   ==>>   previous run without ice age output then set it to zero'
+            oa_i(:,:,:) = 0._wp
+         ENDIF
+         ! melt ponds
+         id2 = iom_varid( numrir, 'a_ip' , ldstop = .FALSE. )
+         IF( id2 > 0 ) THEN                       ! fields exist
+            CALL iom_get( numrir, jpdom_autoglo, 'a_ip' , a_ip )
+            CALL iom_get( numrir, jpdom_autoglo, 'v_ip' , v_ip )
+         ELSE                                     ! start from rest
+            IF(lwp) WRITE(numout,*) '   ==>>   previous run without melt ponds output then set it to zero'
+            a_ip(:,:,:) = 0._wp
+            v_ip(:,:,:) = 0._wp
+         ENDIF
+         ! melt pond lids
+         id3 = iom_varid( numrir, 'v_il' , ldstop = .FALSE. )
+         IF( id3 > 0 ) THEN
+            CALL iom_get( numrir, jpdom_autoglo, 'v_il', v_il)
+         ELSE
+            IF(lwp) WRITE(numout,*) '   ==>>   previous run without melt ponds lids output then set it to zero'
+            v_il(:,:,:) = 0._wp
+         ENDIF
+         ! fields needed for Met Office (Jules) coupling
+         IF( ln_cpl ) THEN
+            id4 = iom_varid( numrir, 'cnd_ice' , ldstop = .FALSE. )
+            id5 = iom_varid( numrir, 't1_ice'  , ldstop = .FALSE. )
+            IF( id4 > 0 .AND. id5 > 0 ) THEN         ! fields exist
+               CALL iom_get( numrir, jpdom_autoglo, 'cnd_ice', cnd_ice )
+               CALL iom_get( numrir, jpdom_autoglo, 't1_ice' , t1_ice  )
+            ELSE                                     ! start from rest
+               IF(lwp) WRITE(numout,*) '   ==>>   previous run without conductivity output then set it to zero'
+               cnd_ice(:,:,:) = 0._wp
+               t1_ice (:,:,:) = rt0
+            ENDIF
+         ENDIF
+
+         CALL iom_delay_rst( 'READ', 'ICE', numrir )   ! read only ice delayed global communication variables
+
+         !                 ! ---------------------------------- !
+      ELSE                 ! == case of a simplified restart == !
+         !                 ! ---------------------------------- !
+         CALL ctl_warn('ice_rst_read: you are attempting to use an unsuitable ice restart')
+         !
+         IF( .NOT. ln_iceini .OR. nn_iceini_file == 2 ) THEN
+            CALL ctl_stop('STOP', 'ice_rst_read: you need ln_ice_ini=T and nn_iceini_file=0 or 1')
+         ELSE
+            CALL ctl_warn('ice_rst_read: using ice_istate to set initial conditions instead')
+         ENDIF
+         !
+         IF( nn_components == jp_iam_sas ) THEN   ! SAS case: ss[st]_m were not initialized by sbc_ssm_init
+            !
+            IF(lwp) WRITE(numout,*) '  SAS: default initialisation of ss[st]_m arrays used in ice_istate'
+            IF( l_useCT )  THEN    ;   sst_m(:,:) = eos_pt_from_ct( tsn(:,:,1,jp_tem), tsn(:,:,1,jp_sal) )
+            ELSE                   ;   sst_m(:,:) = tsn(:,:,1,jp_tem)
+            ENDIF
+            sss_m(:,:) = tsn(:,:,1,jp_sal)
+         ENDIF
+         !
+         CALL ice_istate( nit000 )
+         !
+      ENDIF
+
+   END SUBROUTINE ice_rst_read
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :       Empty module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icerst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icesbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icesbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icesbc.F90	(revision 14097)
@@ -0,0 +1,330 @@
+MODULE icesbc
+   !!======================================================================
+   !!                       ***  MODULE  icesbc  ***
+   !! Sea-Ice :   air-ice sbc fields
+   !!=====================================================================
+   !! History :  4.0  !  2017-08  (C. Rousset)       Original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3' :                                     SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE ice            ! sea-ice: variables
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbc_ice        ! Surface boundary condition: ice   fields
+   USE usrdef_sbc     ! Surface boundary condition: user defined
+   USE sbcblk         ! Surface boundary condition: bulk
+   USE sbccpl         ! Surface boundary condition: coupled interface
+   USE icealb         ! sea-ice: albedo
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ice_sbc_tau   ! called by icestp.F90
+   PUBLIC ice_sbc_flx   ! called by icestp.F90
+   PUBLIC ice_sbc_init  ! called by icestp.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_sbc_tau( kt, ksbc, utau_ice, vtau_ice )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_sbc_tau  ***
+      !!
+      !! ** Purpose : provide surface boundary condition for sea ice (momentum)
+      !!
+      !! ** Action  : It provides the following fields:
+      !!              utau_ice, vtau_ice : surface ice stress (U- & V-points) [N/m2]
+      !!-------------------------------------------------------------------
+      INTEGER                     , INTENT(in   ) ::   kt                   ! ocean time step
+      INTEGER                     , INTENT(in   ) ::   ksbc                 ! type of sbc flux
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::   utau_ice, vtau_ice   ! air-ice stress   [N/m2]
+      !!
+      INTEGER  ::   ji, jj                 ! dummy loop index
+      REAL(wp), DIMENSION(jpi,jpj) ::   zutau_ice, zvtau_ice 
+      !!-------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ice_sbc')
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_sbc_tau: Surface boundary condition for sea ice (momentum)'
+         WRITE(numout,*)'~~~~~~~~~~~~~~~'
+      ENDIF
+      !
+      SELECT CASE( ksbc )
+         CASE( jp_usr     )   ;    CALL usrdef_sbc_ice_tau( kt )                 ! user defined formulation
+         CASE( jp_blk     )   ;    CALL blk_ice_tau                              ! Bulk         formulation
+         CASE( jp_purecpl )   ;    CALL sbc_cpl_ice_tau( utau_ice , vtau_ice )   ! Coupled      formulation
+      END SELECT
+      !
+      IF( ln_mixcpl) THEN                                                        ! Case of a mixed Bulk/Coupled formulation
+                                   CALL sbc_cpl_ice_tau( zutau_ice , zvtau_ice )
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               utau_ice(ji,jj) = utau_ice(ji,jj) * xcplmask(ji,jj,0) + zutau_ice(ji,jj) * ( 1. - xcplmask(ji,jj,0) )
+               vtau_ice(ji,jj) = vtau_ice(ji,jj) * xcplmask(ji,jj,0) + zvtau_ice(ji,jj) * ( 1. - xcplmask(ji,jj,0) )
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'icesbc', utau_ice, 'U', -1., vtau_ice, 'V', -1. )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('ice_sbc')
+      !
+   END SUBROUTINE ice_sbc_tau
+
+   
+   SUBROUTINE ice_sbc_flx( kt, ksbc )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_sbc_flx  ***
+      !!
+      !! ** Purpose : provide surface boundary condition for sea ice (flux)
+      !!
+      !! ** Action  : It provides the following fields used in sea ice model:
+      !!                emp_oce , emp_ice                        = E-P over ocean and sea ice                    [Kg/m2/s]
+      !!                sprecip                                  = solid precipitation                           [Kg/m2/s]
+      !!                evap_ice                                 = sublimation                                   [Kg/m2/s]
+      !!                qsr_tot , qns_tot                        = solar & non solar heat flux (total)           [W/m2]
+      !!                qsr_ice , qns_ice                        = solar & non solar heat flux over ice          [W/m2]
+      !!                dqns_ice                                 = non solar  heat sensistivity                  [W/m2]
+      !!                qemp_oce, qemp_ice, qprec_ice, qevap_ice = sensible heat (associated with evap & precip) [W/m2]
+      !!            + some fields that are not used outside this module: 
+      !!                qla_ice                                  = latent heat flux over ice                     [W/m2]
+      !!                dqla_ice                                 = latent heat sensistivity                      [W/m2]
+      !!                tprecip                                  = total  precipitation                          [Kg/m2/s]
+      !!                alb_ice                                  = albedo above sea ice
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ocean time step
+      INTEGER, INTENT(in) ::   ksbc   ! flux formulation (user defined, bulk or Pure Coupled)
+      !
+      INTEGER  ::   ji, jj, jl      ! dummy loop index
+      REAL(wp) ::   zmiss_val       ! missing value retrieved from xios 
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zalb, zmsk00      ! 2D workspace
+      !!--------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ice_sbc_flx')
+
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_sbc_flx: Surface boundary condition for sea ice (flux)'
+         WRITE(numout,*)'~~~~~~~~~~~~~~~'
+      ENDIF
+
+      ! get missing value from xml
+      CALL iom_miss_val( "icetemp", zmiss_val )
+
+      ! --- ice albedo --- !
+      CALL ice_alb( t_su, h_i, h_s, ln_pnd_alb, a_ip_eff, h_ip, cloud_fra, alb_ice )
+
+      !
+      SELECT CASE( ksbc )   !== fluxes over sea ice ==!
+      !
+      CASE( jp_usr )              !--- user defined formulation
+                                  CALL usrdef_sbc_ice_flx( kt, h_s, h_i )
+      CASE( jp_blk )              !--- bulk formulation
+                                  CALL blk_ice_flx    ( t_su, h_s, h_i, alb_ice )    ! 
+         IF( ln_mixcpl        )   CALL sbc_cpl_ice_flx( picefr=at_i_b, palbi=alb_ice, psst=sst_m, pist=t_su, phs=h_s, phi=h_i )
+         IF( nn_flxdist /= -1 )   CALL ice_flx_dist   ( t_su, alb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_flxdist )
+         !                        !    compute conduction flux and surface temperature (as in Jules surface module)
+         IF( ln_cndflx .AND. .NOT.ln_cndemulate ) &
+            &                     CALL blk_ice_qcn    ( ln_virtual_itd, t_su, t_bo, h_s, h_i )
+      CASE ( jp_purecpl )         !--- coupled formulation
+                                  CALL sbc_cpl_ice_flx( picefr=at_i_b, palbi=alb_ice, psst=sst_m, pist=t_su, phs=h_s, phi=h_i )
+         IF( nn_flxdist /= -1 )   CALL ice_flx_dist   ( t_su, alb_ice, qns_ice, qsr_ice, dqns_ice, evap_ice, devap_ice, nn_flxdist )
+      END SELECT
+
+      !--- output ice albedo and surface albedo ---!
+      IF( iom_use('icealb') .OR. iom_use('albedo') ) THEN
+
+         ALLOCATE( zalb(jpi,jpj), zmsk00(jpi,jpj) )
+
+         WHERE( at_i_b < 1.e-03 )
+            zmsk00(:,:) = 0._wp
+            zalb  (:,:) = rn_alb_oce
+         ELSEWHERE
+            zmsk00(:,:) = 1._wp            
+            zalb  (:,:) = SUM( alb_ice * a_i_b, dim=3 ) / at_i_b
+         END WHERE
+         ! ice albedo
+         CALL iom_put( 'icealb' , zalb * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) )
+         ! ice+ocean albedo
+         zalb(:,:) = SUM( alb_ice * a_i_b, dim=3 ) + rn_alb_oce * ( 1._wp - at_i_b )
+         CALL iom_put( 'albedo' , zalb )
+
+         DEALLOCATE( zalb, zmsk00 )
+
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('ice_sbc_flx')
+      !
+   END SUBROUTINE ice_sbc_flx
+
+
+   SUBROUTINE ice_flx_dist( ptn_ice, palb_ice, pqns_ice, pqsr_ice, pdqn_ice, pevap_ice, pdevap_ice, k_flxdist )
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_flx_dist  ***
+      !!
+      !! ** Purpose :   update the ice surface boundary condition by averaging 
+      !!              and/or redistributing fluxes on ice categories
+      !!
+      !! ** Method  :   average then redistribute
+      !!
+      !! ** Action  :   depends on k_flxdist
+      !!                = -1  Do nothing (needs N(cat) fluxes)
+      !!                =  0  Average N(cat) fluxes then apply the average over the N(cat) ice 
+      !!                =  1  Average N(cat) fluxes then redistribute over the N(cat) ice
+      !!                                                 using T-ice and albedo sensitivity
+      !!                =  2  Redistribute a single flux over categories
+      !!-------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   k_flxdist  ! redistributor
+      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) ::   pevap_ice  ! sublimation
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pdevap_ice ! sublimation sensitivity
+      !
+      INTEGER  ::   jl      ! dummy loop index
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z1_at_i   ! inverse of concentration
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z_qsr_m   ! Mean solar heat flux over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z_qns_m   ! Mean non solar heat flux over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z_evap_m  ! Mean sublimation over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z_dqn_m   ! Mean d(qns)/dT over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z_devap_m ! Mean d(evap)/dT over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zalb_m    ! Mean albedo over all categories
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   ztem_m    ! Mean temperature over all categories
+      !!----------------------------------------------------------------------
+      !
+      WHERE ( at_i (:,:) > 0._wp )   ; z1_at_i(:,:) = 1._wp / at_i (:,:)
+      ELSEWHERE                      ; z1_at_i(:,:) = 0._wp
+      END WHERE
+      
+      SELECT CASE( k_flxdist )       !==  averaged on all ice categories  ==!
+      !
+      CASE( 0 , 1 )
+         !
+         ALLOCATE( z_qns_m(jpi,jpj), z_qsr_m(jpi,jpj), z_dqn_m(jpi,jpj), z_evap_m(jpi,jpj), z_devap_m(jpi,jpj) )  
+         !
+         z_qns_m  (:,:) = SUM( a_i(:,:,:) * pqns_ice  (:,:,:) , dim=3 ) * z1_at_i(:,:)
+         z_qsr_m  (:,:) = SUM( a_i(:,:,:) * pqsr_ice  (:,:,:) , dim=3 ) * z1_at_i(:,:)
+         z_dqn_m  (:,:) = SUM( a_i(:,:,:) * pdqn_ice  (:,:,:) , dim=3 ) * z1_at_i(:,:)
+         z_evap_m (:,:) = SUM( a_i(:,:,:) * pevap_ice (:,:,:) , dim=3 ) * z1_at_i(:,:)
+         z_devap_m(:,:) = SUM( a_i(:,:,:) * pdevap_ice(:,:,:) , dim=3 ) * z1_at_i(:,:)
+         DO jl = 1, jpl
+            pqns_ice  (:,:,jl) = z_qns_m (:,:)
+            pqsr_ice  (:,:,jl) = z_qsr_m (:,:)
+            pdqn_ice  (:,:,jl) = z_dqn_m  (:,:)
+            pevap_ice (:,:,jl) = z_evap_m(:,:)
+            pdevap_ice(:,:,jl) = z_devap_m(:,:)
+         END DO
+         !
+         DEALLOCATE( z_qns_m, z_qsr_m, z_dqn_m, z_evap_m, z_devap_m )  
+         !
+      END SELECT
+      !
+      SELECT CASE( k_flxdist )       !==  redistribution on all ice categories  ==!
+      !
+      CASE( 1 , 2 )
+         !
+         ALLOCATE( zalb_m(jpi,jpj), ztem_m(jpi,jpj) )  
+         !
+         zalb_m(:,:) = SUM( a_i(:,:,:) * palb_ice(:,:,:) , dim=3 ) * z1_at_i(:,:)
+         ztem_m(:,:) = SUM( a_i(:,:,:) * ptn_ice (:,:,:) , dim=3 ) * z1_at_i(:,:)
+         DO jl = 1, jpl
+            pqns_ice (:,:,jl) = pqns_ice (:,:,jl) + pdqn_ice  (:,:,jl) * ( ptn_ice(:,:,jl) - ztem_m(:,:) )
+            pevap_ice(:,:,jl) = pevap_ice(:,:,jl) + pdevap_ice(:,:,jl) * ( ptn_ice(:,:,jl) - ztem_m(:,:) )
+            pqsr_ice (:,:,jl) = pqsr_ice (:,:,jl) * ( 1._wp - palb_ice(:,:,jl) ) / ( 1._wp - zalb_m(:,:) )
+         END DO
+         !
+         DEALLOCATE( zalb_m, ztem_m )  
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_flx_dist
+
+
+   SUBROUTINE ice_sbc_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_sbc_init  ***
+      !!
+      !! ** Purpose :   Physical constants and parameters linked to the ice dynamics
+      !!      
+      !! ** Method  :   Read the namsbc namelist and check the ice-dynamic
+      !!              parameter values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namsbc
+      !!-------------------------------------------------------------------
+      INTEGER ::   ios, ioptio   ! Local integer
+      !!
+      NAMELIST/namsbc/ rn_cio, nn_snwfra, rn_snwblow, nn_flxdist, ln_cndflx, ln_cndemulate, nn_qtrice
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )         ! Namelist namsbc in reference namelist : Ice dynamics
+      READ  ( numnam_ice_ref, namsbc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc in reference namelist' )
+      REWIND( numnam_ice_cfg )         ! Namelist namsbc in configuration namelist : Ice dynamics
+      READ  ( numnam_ice_cfg, namsbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc in configuration namelist' )
+      IF(lwm) WRITE( numoni, namsbc )
+      !
+      IF(lwp) THEN                     ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_sbc_init: ice parameters for ice dynamics '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namsbc:'
+         WRITE(numout,*) '      drag coefficient for oceanic stress                       rn_cio        = ', rn_cio
+         WRITE(numout,*) '      fraction of ice covered by snow (options 0,1,2)           nn_snwfra     = ', nn_snwfra
+         WRITE(numout,*) '      coefficient for ice-lead partition of snowfall            rn_snwblow    = ', rn_snwblow
+         WRITE(numout,*) '      Multicategory heat flux formulation                       nn_flxdist    = ', nn_flxdist
+         WRITE(numout,*) '      Use conduction flux as surface condition                  ln_cndflx     = ', ln_cndflx
+         WRITE(numout,*) '         emulate conduction flux                                ln_cndemulate = ', ln_cndemulate
+         WRITE(numout,*) '      solar flux transmitted thru the surface scattering layer  nn_qtrice     = ', nn_qtrice
+         WRITE(numout,*) '         = 0  Grenfell and Maykut 1977'
+         WRITE(numout,*) '         = 1  Lebrun 2019'
+      ENDIF
+      !
+      IF(lwp) WRITE(numout,*)
+      SELECT CASE( nn_flxdist )         ! SI3 Multi-category heat flux formulation
+      CASE( -1  )
+         IF(lwp) WRITE(numout,*) '   SI3: use per-category fluxes (nn_flxdist = -1) '
+      CASE(  0  )
+         IF(lwp) WRITE(numout,*) '   SI3: use average per-category fluxes (nn_flxdist = 0) '
+      CASE(  1  )
+         IF(lwp) WRITE(numout,*) '   SI3: use average then redistribute per-category fluxes (nn_flxdist = 1) '
+         IF( ln_cpl )         CALL ctl_stop( 'ice_thd_init: the chosen nn_flxdist for SI3 in coupled mode must be /=1' )
+      CASE(  2  )
+         IF(lwp) WRITE(numout,*) '   SI3: Redistribute a single flux over categories (nn_flxdist = 2) '
+         IF( .NOT. ln_cpl )   CALL ctl_stop( 'ice_thd_init: the chosen nn_flxdist for SI3 in forced mode must be /=2' )
+      CASE DEFAULT
+         CALL ctl_stop( 'ice_thd_init: SI3 option, nn_flxdist, should be between -1 and 2' )
+      END SELECT
+      !
+   END SUBROUTINE ice_sbc_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icesbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icestp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icestp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icestp.F90	(revision 14097)
@@ -0,0 +1,516 @@
+MODULE icestp
+   !!======================================================================
+   !!                       ***  MODULE  icestp  ***
+   !! sea ice : Master routine for all the sea ice model
+   !!=====================================================================
+   !!
+   !! The sea ice model SI3 (Sea Ice modelling Integrated Initiative),
+   !!                        aka Sea Ice cube for its nickname
+   !!
+   !!    is originally based on LIM3, developed in Louvain-la-Neuve by: 
+   !!       * Martin Vancoppenolle (UCL-ASTR, Belgium)
+   !!       * Sylvain Bouillon (UCL-ASTR, Belgium)
+   !!       * Miguel Angel Morales Maqueda (NOC-L, UK)
+   !!      thanks to valuable earlier work by
+   !!       * Thierry Fichefet
+   !!       * Hugues Goosse
+   !!      thanks also to the following persons who contributed
+   !!       * Gurvan Madec, Claude Talandier, Christian Ethe (LOCEAN, France)
+   !!       * Xavier Fettweis (UCL-ASTR), Ralph Timmermann (AWI, Germany)
+   !!       * Bill Lipscomb (LANL), Cecilia Bitz (UWa) and Elisabeth Hunke (LANL), USA.
+   !!
+   !! SI3 has been made possible by a handful of persons who met as working group
+   !!      (from France, Belgium, UK and Italy)
+   !!    * Clement Rousset, Martin Vancoppenolle & Gurvan Madec (LOCEAN, France)
+   !!    * Matthieu Chevalier & David Salas (Meteo France, France)
+   !!    * Gilles Garric (Mercator Ocean, France)
+   !!    * Thierry Fichefet & Francois Massonnet (UCL, Belgium)
+   !!    * Ed Blockley & Jeff Ridley (Met Office, UK)
+   !!    * Danny Feltham & David Schroeder (CPOM, UK)
+   !!    * Yevgeny Aksenov (NOC, UK)
+   !!    * Paul Holland (BAS, UK)
+   !!    * Dorotea Iovino (CMCC, Italy)
+   !!======================================================================
+   !! History :  4.0  !  2018     (C. Rousset)      Original code SI3
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_stp       : sea-ice model time-stepping and update ocean SBC over ice-covered area
+   !!   ice_init      : initialize sea-ice
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE c1d            ! 1D vertical configuration
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamical 1D variables
+   !
+   USE phycst         ! Define parameters for the routines
+   USE eosbn2         ! equation of state
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbc_ice        ! Surface boundary condition: ice   fields
+   !
+   USE icesbc         ! sea-ice: Surface boundary conditions
+   USE icedyn         ! sea-ice: dynamics
+   USE icethd         ! sea-ice: thermodynamics
+   USE iceupdate      ! sea-ice: sea surface boundary condition update
+   USE icedia         ! sea-ice: budget diagnostics
+   USE icewri         ! sea-ice: outputs
+   USE icerst         ! sea-ice: restarts
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: control
+   USE iceistate      ! sea-ice: initial state
+   USE iceitd         ! sea-ice: remapping thickness distribution
+   USE icealb         ! sea-ice: albedo
+   !
+   USE bdy_oce , ONLY : ln_bdy   ! flag for bdy
+   USE bdyice         ! unstructured open boundary data for sea-ice
+# if defined key_agrif
+   USE agrif_ice
+   USE agrif_ice_interp
+# endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_stp    ! called by sbcmod.F90
+   PUBLIC   ice_init   ! called by sbcmod.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_stp( kt, ksbc )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_stp  ***
+      !!
+      !! ** Purpose :   sea-ice model time-stepping and update ocean surface
+      !!              boundary condition over ice-covered area
+      !!
+      !! ** Method  :   ice model time stepping
+      !!              - call the ice dynamics routine
+      !!              - call the ice advection/diffusion routine
+      !!              - call the ice thermodynamics routine
+      !!              - call the routine that computes mass and
+      !!                heat fluxes at the ice/ocean interface
+      !!              - save the outputs
+      !!              - save the outputs for restart when necessary
+      !!
+      !! ** Action  : - time evolution of the LIM sea-ice model
+      !!              - update all sbc variables below sea-ice:
+      !!                utau, vtau, taum, wndm, qns , qsr, emp , sfx
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt      ! ocean time step
+      INTEGER, INTENT(in) ::   ksbc    ! flux formulation (user defined, bulk, or Pure Coupled)
+      !
+      INTEGER ::   jl   ! dummy loop index
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ice_stp')
+      !
+      !                                      !-----------------------!
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN   ! --- Ice time step --- !
+         !                                   !-----------------------!
+         !
+         kt_ice = kt                              ! -- Ice model time step
+         !
+         u_oce(:,:) = ssu_m(:,:)                  ! -- mean surface ocean current
+         v_oce(:,:) = ssv_m(:,:)
+         !
+         CALL eos_fzp( sss_m(:,:) , t_bo(:,:) )   ! -- freezing temperature [Kelvin] (set to rt0 over land)
+         t_bo(:,:) = ( t_bo(:,:) + rt0 ) * tmask(:,:,1) + rt0 * ( 1._wp - tmask(:,:,1) )
+         !
+         !                          !==  AGRIF Parent to Child  ==!
+#if defined key_agrif
+         !                              ! nbstep_ice ranges from 1 to the nb of child ocean steps inside one parent ice step
+         IF( .NOT. Agrif_Root() )       nbstep_ice = MOD( nbstep_ice, Agrif_irhot() * Agrif_Parent(nn_fsbc) / nn_fsbc ) + 1
+         !                              ! these calls must remain here for restartability purposes
+                                        CALL agrif_interp_ice( 'T' ) 
+                                        CALL agrif_interp_ice( 'U' )
+                                        CALL agrif_interp_ice( 'V' )
+#endif
+                                        CALL store_fields             ! Store now ice values
+         !
+         !------------------------------------------------!
+         ! --- Dynamical coupling with the atmosphere --- !
+         !------------------------------------------------!
+         ! It provides the following fields used in sea ice model:
+         !    utau_ice, vtau_ice = surface ice stress [N/m2]
+         !------------------------------------------------!
+                                        CALL ice_sbc_tau( kt, ksbc, utau_ice, vtau_ice )          
+         !-------------------------------------!
+         ! --- ice dynamics and advection  --- !
+         !-------------------------------------!
+                                        CALL diag_set0                ! set diag of mass, heat and salt fluxes to 0
+                                        CALL ice_rst_opn( kt )        ! Open Ice restart file (if necessary) 
+         !
+         IF( ln_icedyn .AND. .NOT.lk_c1d )   &
+            &                           CALL ice_dyn( kt )            ! -- Ice dynamics
+         !
+                                        CALL diag_trends( 1 )         ! record dyn trends
+         !
+         !                          !==  lateral boundary conditions  ==!
+         IF( ln_icethd .AND. ln_bdy )   CALL bdy_ice( kt )            ! -- bdy ice thermo
+         !
+         !                          !==  previous lead fraction and ice volume for flux calculations
+                                        CALL ice_var_glo2eqv          ! h_i and h_s for ice albedo calculation
+                                        CALL ice_var_agg(1)           ! at_i for coupling 
+                                        CALL store_fields             ! Store now ice values
+         !
+         !------------------------------------------------------!
+         ! --- Thermodynamical coupling with the atmosphere --- !
+         !------------------------------------------------------!
+         ! It provides the following fields used in sea ice model:
+         !    emp_oce , emp_ice    = E-P over ocean and sea ice                    [Kg/m2/s]
+         !    sprecip              = solid precipitation                           [Kg/m2/s]
+         !    evap_ice             = sublimation                                   [Kg/m2/s]
+         !    qsr_tot , qns_tot    = solar & non solar heat flux (total)           [W/m2]
+         !    qsr_ice , qns_ice    = solar & non solar heat flux over ice          [W/m2]
+         !    dqns_ice             = non solar  heat sensistivity                  [W/m2]
+         !    qemp_oce, qemp_ice,  = sensible heat (associated with evap & precip) [W/m2]
+         !    qprec_ice, qevap_ice
+         !------------------------------------------------------!
+                                        CALL ice_sbc_flx( kt, ksbc )
+         !----------------------------!
+         ! --- ice thermodynamics --- !
+         !----------------------------!
+         IF( ln_icethd )                CALL ice_thd( kt )            ! -- Ice thermodynamics      
+         !
+                                        CALL diag_trends( 2 )         ! record thermo trends
+                                        CALL ice_var_glo2eqv          ! necessary calls (at least for coupling)
+                                        CALL ice_var_agg( 2 )         ! necessary calls (at least for coupling)
+         !
+                                        CALL ice_update_flx( kt )     ! -- Update ocean surface mass, heat and salt fluxes
+         !
+         IF( ln_icediahsb )             CALL ice_dia( kt )            ! -- Diagnostics outputs 
+         !
+         IF( ln_icediachk )             CALL ice_drift_wri( kt )      ! -- Diagnostics outputs for conservation 
+         !
+                                        CALL ice_wri( kt )            ! -- Ice outputs 
+         !
+         IF( lrst_ice )                 CALL ice_rst_write( kt )      ! -- Ice restart file 
+         !
+         IF( ln_icectl )                CALL ice_ctl( kt )            ! -- Control checks
+         !
+      ENDIF   ! End sea-ice time step only
+
+      !-------------------------!
+      ! --- Ocean time step --- !
+      !-------------------------!
+      IF( ln_icedyn )                   CALL ice_update_tau( kt, ub(:,:,1), vb(:,:,1) )   ! -- update surface ocean stresses
+!!gm   remark, the ocean-ice stress is not saved in ice diag call above .....  find a solution!!!
+      !
+      IF( ln_timing )   CALL timing_stop('ice_stp')
+      !
+   END SUBROUTINE ice_stp
+
+
+   SUBROUTINE ice_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_init  ***
+      !!
+      !! ** purpose :   Initialize sea-ice parameters
+      !!----------------------------------------------------------------------
+      INTEGER :: jl, ierr
+      !!----------------------------------------------------------------------
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'Sea Ice Model: SI3 (Sea Ice modelling Integrated Initiative)' 
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'ice_init: Arrays allocation & Initialization of all routines & init state' 
+      IF(lwp) WRITE(numout,*) '~~~~~~~~'
+      !
+      !                                ! Open the reference and configuration namelist files and namelist output file
+      CALL ctl_opn( numnam_ice_ref, 'namelist_ice_ref',    'OLD',     'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+      CALL ctl_opn( numnam_ice_cfg, 'namelist_ice_cfg',    'OLD',     'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+      IF(lwm) CALL ctl_opn( numoni, 'output.namelist.ice', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, 1 )
+      !
+      CALL par_init                ! set some ice run parameters
+      !
+      !                                ! Allocate the ice arrays (sbc_ice already allocated in sbc_init)
+      ierr =        ice_alloc        ()      ! ice variables
+      ierr = ierr + sbc_ice_alloc    ()      ! surface boundary conditions 
+      ierr = ierr + ice1D_alloc      ()      ! thermodynamics
+      !
+      CALL mpp_sum( 'icestp', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop('STOP', 'ice_init : unable to allocate ice arrays')
+      !
+      !                                ! set max concentration in both hemispheres
+      WHERE( gphit(:,:) > 0._wp )   ;   rn_amax_2d(:,:) = rn_amax_n  ! NH
+      ELSEWHERE                     ;   rn_amax_2d(:,:) = rn_amax_s  ! SH
+      END WHERE
+      !
+      CALL diag_set0                   ! set diag of mass, heat and salt fluxes to 0: needed for Agrif child grids
+      !
+      CALL ice_itd_init                ! ice thickness distribution initialization
+      !
+      CALL ice_thd_init                ! set ice thermodynics parameters (clem: important to call it first for melt ponds)
+      !
+      CALL ice_sbc_init                ! set ice-ocean and ice-atm. coupling parameters
+      !
+      CALL ice_istate_init             ! Initial sea-ice state
+      IF ( ln_rstart .OR. nn_iceini_file == 2 ) THEN
+         CALL ice_rst_read                      ! start from a restart file
+      ELSE
+         CALL ice_istate( nit000 )              ! start from rest or read a file
+      ENDIF
+      CALL ice_var_glo2eqv
+      CALL ice_var_agg(1)
+      !
+      CALL ice_dyn_init                ! set ice dynamics parameters
+      !
+      CALL ice_update_init             ! ice surface boundary condition
+      !
+      CALL ice_alb_init                ! ice surface albedo
+      !
+      CALL ice_dia_init                ! initialization for diags
+      !
+      CALL ice_drift_init              ! initialization for diags of conservation
+      !
+      fr_i  (:,:)   = at_i(:,:)        ! initialisation of sea-ice fraction
+      tn_ice(:,:,:) = t_su(:,:,:)      ! initialisation of surface temp for coupled simu
+      !
+      IF( ln_rstart )   CALL iom_close( numrir )  ! close input ice restart file
+      !
+   END SUBROUTINE ice_init
+
+
+   SUBROUTINE par_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE par_init ***
+      !!
+      !! ** Purpose :   Definition generic parameters for ice model
+      !!
+      !! ** Method  :   Read namelist and check the parameter
+      !!                values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist nampar
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios                 ! Local integer
+      !!
+      NAMELIST/nampar/ jpl, nlay_i, nlay_s, ln_virtual_itd, ln_icedyn, ln_icethd, rn_amax_n, rn_amax_s,  &
+         &             cn_icerst_in, cn_icerst_indir, cn_icerst_out, cn_icerst_outdir
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )      ! Namelist nampar in reference namelist : Parameters for ice
+      READ  ( numnam_ice_ref, nampar, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampar in reference namelist' )
+      REWIND( numnam_ice_cfg )      ! Namelist nampar in configuration namelist : Parameters for ice
+      READ  ( numnam_ice_cfg, nampar, IOSTAT = ios, ERR = 902 )
+902   IF( ios > 0 )   CALL ctl_nam ( ios , 'nampar in configuration namelist' )
+      IF(lwm) WRITE( numoni, nampar )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   par_init: ice parameters shared among all the routines'
+         WRITE(numout,*) '   ~~~~~~~~'
+         WRITE(numout,*) '      Namelist nampar: '
+         WRITE(numout,*) '         number of ice  categories                           jpl       = ', jpl
+         WRITE(numout,*) '         number of ice  layers                               nlay_i    = ', nlay_i
+         WRITE(numout,*) '         number of snow layers                               nlay_s    = ', nlay_s
+         WRITE(numout,*) '         virtual ITD param for jpl=1 (T) or not (F)     ln_virtual_itd = ', ln_virtual_itd
+         WRITE(numout,*) '         Ice dynamics       (T) or not (F)                   ln_icedyn = ', ln_icedyn
+         WRITE(numout,*) '         Ice thermodynamics (T) or not (F)                   ln_icethd = ', ln_icethd
+         WRITE(numout,*) '         maximum ice concentration for NH                              = ', rn_amax_n 
+         WRITE(numout,*) '         maximum ice concentration for SH                              = ', rn_amax_s
+      ENDIF
+      !                                        !--- change max ice concentration for roundoff errors
+      rn_amax_n = MIN( rn_amax_n, 1._wp - epsi10 )
+      rn_amax_s = MIN( rn_amax_s, 1._wp - epsi10 )
+      !                                        !--- check consistency
+      IF ( jpl > 1 .AND. ln_virtual_itd ) THEN
+         ln_virtual_itd = .FALSE.
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ln_virtual_itd forced to false as jpl>1, no need with multiple categories to emulate them'
+      ENDIF
+      !
+      IF( ln_cpl .AND. nn_cats_cpl /= 1 .AND. nn_cats_cpl /= jpl ) THEN
+         CALL ctl_stop( 'STOP', 'par_init: in coupled mode, nn_cats_cpl should be either 1 or jpl' )
+      ENDIF
+      !
+      rdt_ice   = REAL(nn_fsbc) * rdt          !--- sea-ice timestep and its inverse
+      r1_rdtice = 1._wp / rdt_ice
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '      ice timestep rdt_ice = nn_fsbc*rdt = ', rdt_ice
+      !
+      r1_nlay_i = 1._wp / REAL( nlay_i, wp )   !--- inverse of nlay_i and nlay_s
+      r1_nlay_s = 1._wp / REAL( nlay_s, wp )
+      !
+   END SUBROUTINE par_init
+
+
+   SUBROUTINE store_fields
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE store_fields  ***
+      !!
+      !! ** purpose :  store ice variables at "before" time step
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jl      ! dummy loop index
+      !!----------------------------------------------------------------------
+      !
+      a_i_b (:,:,:)   = a_i (:,:,:)     ! ice area
+      v_i_b (:,:,:)   = v_i (:,:,:)     ! ice volume
+      v_s_b (:,:,:)   = v_s (:,:,:)     ! snow volume
+      sv_i_b(:,:,:)   = sv_i(:,:,:)     ! salt content
+      e_s_b (:,:,:,:) = e_s (:,:,:,:)   ! snow thermal energy
+      e_i_b (:,:,:,:) = e_i (:,:,:,:)   ! ice thermal energy
+      WHERE( a_i_b(:,:,:) >= epsi20 )
+         h_i_b(:,:,:) = v_i_b(:,:,:) / a_i_b(:,:,:)   ! ice thickness
+         h_s_b(:,:,:) = v_s_b(:,:,:) / a_i_b(:,:,:)   ! snw thickness
+      ELSEWHERE
+         h_i_b(:,:,:) = 0._wp
+         h_s_b(:,:,:) = 0._wp
+      END WHERE
+      !
+      ! ice velocities & total concentration
+      at_i_b(:,:)  = SUM( a_i_b(:,:,:), dim=3 )
+      u_ice_b(:,:) = u_ice(:,:)
+      v_ice_b(:,:) = v_ice(:,:)
+      !
+   END SUBROUTINE store_fields
+
+
+   SUBROUTINE diag_set0
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE diag_set0  ***
+      !!
+      !! ** purpose :  set ice-ocean and ice-atm. fluxes to zeros at the beggining
+      !!               of the time step
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jl      ! dummy loop index
+      !!----------------------------------------------------------------------
+
+      DO jj = 1, jpj 
+         DO ji = 1, jpi
+            sfx    (ji,jj) = 0._wp   ;
+            sfx_bri(ji,jj) = 0._wp   ;   sfx_lam(ji,jj) = 0._wp
+            sfx_sni(ji,jj) = 0._wp   ;   sfx_opw(ji,jj) = 0._wp
+            sfx_bog(ji,jj) = 0._wp   ;   sfx_dyn(ji,jj) = 0._wp
+            sfx_bom(ji,jj) = 0._wp   ;   sfx_sum(ji,jj) = 0._wp
+            sfx_res(ji,jj) = 0._wp   ;   sfx_sub(ji,jj) = 0._wp
+            !
+            wfx_snw(ji,jj) = 0._wp   ;   wfx_ice(ji,jj) = 0._wp
+            wfx_sni(ji,jj) = 0._wp   ;   wfx_opw(ji,jj) = 0._wp
+            wfx_bog(ji,jj) = 0._wp   ;   wfx_dyn(ji,jj) = 0._wp
+            wfx_bom(ji,jj) = 0._wp   ;   wfx_sum(ji,jj) = 0._wp
+            wfx_res(ji,jj) = 0._wp   ;   wfx_sub(ji,jj) = 0._wp
+            wfx_spr(ji,jj) = 0._wp   ;   wfx_lam(ji,jj) = 0._wp  
+            wfx_snw_dyn(ji,jj) = 0._wp ; wfx_snw_sum(ji,jj) = 0._wp
+            wfx_snw_sub(ji,jj) = 0._wp ; wfx_ice_sub(ji,jj) = 0._wp
+            wfx_snw_sni(ji,jj) = 0._wp 
+            wfx_pnd(ji,jj) = 0._wp
+
+            hfx_thd(ji,jj) = 0._wp   ;
+            hfx_snw(ji,jj) = 0._wp   ;   hfx_opw(ji,jj) = 0._wp
+            hfx_bog(ji,jj) = 0._wp   ;   hfx_dyn(ji,jj) = 0._wp
+            hfx_bom(ji,jj) = 0._wp   ;   hfx_sum(ji,jj) = 0._wp
+            hfx_res(ji,jj) = 0._wp   ;   hfx_sub(ji,jj) = 0._wp
+            hfx_spr(ji,jj) = 0._wp   ;   hfx_dif(ji,jj) = 0._wp
+            hfx_err_dif(ji,jj) = 0._wp
+            wfx_err_sub(ji,jj) = 0._wp
+            !
+            diag_heat(ji,jj) = 0._wp ;   diag_sice(ji,jj) = 0._wp
+            diag_vice(ji,jj) = 0._wp ;   diag_vsnw(ji,jj) = 0._wp
+            diag_aice(ji,jj) = 0._wp
+
+            tau_icebfr (ji,jj) = 0._wp   ! landfast ice param only (clem: important to keep the init here)
+            qsb_ice_bot(ji,jj) = 0._wp   ! (needed if ln_icethd=F)
+
+            fhld(ji,jj) = 0._wp   ! needed if ln_icethd=F
+
+            ! for control checks (ln_icediachk)
+            diag_trp_vi(ji,jj) = 0._wp   ;   diag_trp_vs(ji,jj) = 0._wp
+            diag_trp_ei(ji,jj) = 0._wp   ;   diag_trp_es(ji,jj) = 0._wp
+            diag_trp_sv(ji,jj) = 0._wp
+            !
+            diag_adv_mass(ji,jj) = 0._wp
+            diag_adv_salt(ji,jj) = 0._wp
+            diag_adv_heat(ji,jj) = 0._wp
+         END DO
+      END DO
+
+      DO jl = 1, jpl
+         DO jj = 1, jpj 
+            DO ji = 1, jpi
+               ! SIMIP diagnostics
+               t_si       (ji,jj,jl) = rt0     ! temp at the ice-snow interface
+               qcn_ice_bot(ji,jj,jl) = 0._wp
+               qcn_ice_top(ji,jj,jl) = 0._wp   ! conductive fluxes
+               cnd_ice    (ji,jj,jl) = 0._wp   ! effective conductivity at the top of ice/snow (ln_cndflx=T)
+               qcn_ice    (ji,jj,jl) = 0._wp   ! conductive flux (ln_cndflx=T & ln_cndemule=T)
+               qtr_ice_bot(ji,jj,jl) = 0._wp   ! part of solar radiation transmitted through the ice needed at least for outputs
+            END DO
+         END DO
+      END DO
+      
+   END SUBROUTINE diag_set0
+
+
+   SUBROUTINE diag_trends( kn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE diag_trends  ***
+      !!
+      !! ** purpose : diagnostics of the trends. Used for conservation purposes
+      !!              and outputs
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kn    ! 1 = after dyn ; 2 = after thermo
+      !!----------------------------------------------------------------------
+      !
+      ! --- trends of heat, salt, mass (used for conservation controls)
+      IF( ln_icediachk .OR. iom_use('hfxdhc') ) THEN
+         !
+         diag_heat(:,:) = diag_heat(:,:) &
+            &             - SUM(SUM( e_i (:,:,1:nlay_i,:) - e_i_b (:,:,1:nlay_i,:), dim=4 ), dim=3 ) * r1_rdtice &
+            &             - SUM(SUM( e_s (:,:,1:nlay_s,:) - e_s_b (:,:,1:nlay_s,:), dim=4 ), dim=3 ) * r1_rdtice
+         diag_sice(:,:) = diag_sice(:,:) &
+            &             + SUM(     sv_i(:,:,:)          - sv_i_b(:,:,:)                  , dim=3 ) * r1_rdtice * rhoi
+         diag_vice(:,:) = diag_vice(:,:) &
+            &             + SUM(     v_i (:,:,:)          - v_i_b (:,:,:)                  , dim=3 ) * r1_rdtice * rhoi
+         diag_vsnw(:,:) = diag_vsnw(:,:) &
+            &             + SUM(     v_s (:,:,:)          - v_s_b (:,:,:)                  , dim=3 ) * r1_rdtice * rhos
+         !
+         IF( kn == 2 )    CALL iom_put ( 'hfxdhc' , diag_heat )   ! output of heat trend
+         !
+      ENDIF
+      !
+      ! --- trends of concentration (used for simip outputs)
+      IF( iom_use('afxdyn') .OR. iom_use('afxthd') .OR. iom_use('afxtot') ) THEN
+         !
+         diag_aice(:,:) = diag_aice(:,:) + SUM( a_i(:,:,:) - a_i_b(:,:,:), dim=3 ) * r1_rdtice
+         !
+         IF( kn == 1 )   CALL iom_put( 'afxdyn' , diag_aice )                                           ! dyn trend
+         IF( kn == 2 )   CALL iom_put( 'afxthd' , SUM( a_i(:,:,:) - a_i_b(:,:,:), dim=3 ) * r1_rdtice ) ! thermo trend
+         IF( kn == 2 )   CALL iom_put( 'afxtot' , diag_aice )                                           ! total trend
+         !
+      ENDIF
+      !
+   END SUBROUTINE diag_trends
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE ice_stp ( kt, ksbc )     ! Dummy routine
+      INTEGER, INTENT(in) ::   kt, ksbc
+      WRITE(*,*) 'ice_stp: You should not have seen this print! error?', kt
+   END SUBROUTINE ice_stp
+   SUBROUTINE ice_init                 ! Dummy routine
+   END SUBROUTINE ice_init
+#endif
+
+   !!======================================================================
+END MODULE icestp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icetab.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icetab.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icetab.F90	(revision 14097)
@@ -0,0 +1,121 @@
+MODULE icetab
+   !!======================================================================
+   !!                       ***  MODULE icetab   ***
+   !!   sea-ice : transform 1D (2D) array to a 2D (1D) table
+   !!======================================================================
+   !! History :  4.0  !  2018     (C. Rousset)       Original code SI3
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   tab_3d_2d  : 3-D <==> 2-D
+   !!   tab_2d_3d  : 2-D <==> 3-D
+   !!   tab_2d_1d  : 2-D <==> 1-D
+   !!   tab_1d_2d  : 1-D <==> 2-D
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE ice, ONLY : jpl
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tab_3d_2d
+   PUBLIC   tab_2d_1d
+   PUBLIC   tab_2d_3d
+   PUBLIC   tab_1d_2d
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tab_3d_2d( ndim1d, tab_ind, tab1d, tab2d )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tab_2d_1d  ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   ndim1d   ! 1d size
+      INTEGER , DIMENSION(ndim1d)     , INTENT(in   ) ::   tab_ind  ! input index
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(in   ) ::   tab2d    ! input 2D field
+      REAL(wp), DIMENSION(ndim1d,jpl) , INTENT(  out) ::   tab1d    ! output 1D field
+      !
+      INTEGER ::   jl, jn, jid, jjd
+      !!----------------------------------------------------------------------
+      DO jl = 1, jpl
+         DO jn = 1, ndim1d
+            jid          = MOD( tab_ind(jn) - 1 , jpi ) + 1
+            jjd          =    ( tab_ind(jn) - 1 ) / jpi + 1
+            tab1d(jn,jl) = tab2d(jid,jjd,jl)
+         END DO
+      END DO
+   END SUBROUTINE tab_3d_2d
+
+
+   SUBROUTINE tab_2d_1d( ndim1d, tab_ind, tab1d, tab2d )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tab_2d_1d  ***
+      !!----------------------------------------------------------------------
+      INTEGER                     , INTENT(in   ) ::   ndim1d   ! 1d size
+      INTEGER , DIMENSION(ndim1d) , INTENT(in   ) ::   tab_ind  ! input index
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   tab2d    ! input 2D field
+      REAL(wp), DIMENSION(ndim1d) , INTENT(  out) ::   tab1d    ! output 1D field
+      !
+      INTEGER ::   jn , jid, jjd
+      !!----------------------------------------------------------------------
+      DO jn = 1, ndim1d
+         jid        = MOD( tab_ind(jn) - 1 , jpi ) + 1
+         jjd        =    ( tab_ind(jn) - 1 ) / jpi + 1
+         tab1d( jn) = tab2d( jid, jjd)
+      END DO
+   END SUBROUTINE tab_2d_1d
+
+
+   SUBROUTINE tab_2d_3d( ndim1d, tab_ind, tab1d, tab2d )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tab_2d_1d  ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   ndim1d    ! 1D size
+      INTEGER , DIMENSION(ndim1d)     , INTENT(in   ) ::   tab_ind   ! input index
+      REAL(wp), DIMENSION(ndim1d,jpl) , INTENT(in   ) ::   tab1d     ! input 1D field
+      REAL(wp), DIMENSION(jpi,jpj,jpl), INTENT(  out) ::   tab2d     ! output 2D field
+      !
+      INTEGER ::   jl, jn, jid, jjd
+      !!----------------------------------------------------------------------
+      DO jl = 1, jpl
+         DO jn = 1, ndim1d
+            jid               = MOD( tab_ind(jn) - 1 ,  jpi ) + 1
+            jjd               =    ( tab_ind(jn) - 1 ) / jpi  + 1
+            tab2d(jid,jjd,jl) = tab1d(jn,jl)
+         END DO
+      END DO
+   END SUBROUTINE tab_2d_3d
+
+
+   SUBROUTINE tab_1d_2d( ndim1d, tab_ind, tab1d, tab2d )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tab_2d_1d  ***
+      !!----------------------------------------------------------------------
+      INTEGER                     , INTENT(in   ) ::   ndim1d    ! 1D size
+      INTEGER , DIMENSION(ndim1d) , INTENT(in   ) ::   tab_ind   ! input index
+      REAL(wp), DIMENSION(ndim1d) , INTENT(in   ) ::   tab1d     ! input 1D field
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::   tab2d     ! output 2D field
+      !
+      INTEGER ::   jn , jid, jjd
+      !!----------------------------------------------------------------------
+      DO jn = 1, ndim1d
+         jid             = MOD( tab_ind(jn) - 1 ,  jpi ) + 1
+         jjd             =    ( tab_ind(jn) - 1 ) / jpi  + 1
+         tab2d(jid, jjd) = tab1d( jn)
+      END DO
+   END SUBROUTINE tab_1d_2d
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icetab
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd.F90	(revision 14097)
@@ -0,0 +1,612 @@
+MODULE icethd
+   !!======================================================================
+   !!                  ***  MODULE icethd   ***
+   !!   sea-ice : master routine for thermodynamics
+   !!======================================================================
+   !! History :  1.0  !  2000-01  (M.A. Morales Maqueda, H. Goosse, T. Fichefet) original code 1D
+   !!            4.0  !  2018     (many people)       SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd       : thermodynamics of sea ice
+   !!   ice_thd_init  : initialisation of sea-ice thermodynamics
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain variables
+   USE ice            ! sea-ice: variables
+!!gm list trop longue ==>>> why not passage en argument d'appel ?
+   USE sbc_oce , ONLY : sss_m, sst_m, e3t_m, utau, vtau, ssu_m, ssv_m, frq_m, sprecip, ln_cpl
+   USE sbc_ice , ONLY : qsr_oce, qns_oce, qemp_oce, qsr_ice, qns_ice, dqns_ice, evap_ice, qprec_ice, qevap_ice, &
+      &                 qml_ice, qcn_ice, qtr_ice_top
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icethd_zdf     ! sea-ice: vertical heat diffusion
+   USE icethd_dh      ! sea-ice: ice-snow growth and melt
+   USE icethd_da      ! sea-ice: lateral melting
+   USE icethd_sal     ! sea-ice: salinity
+   USE icethd_ent     ! sea-ice: enthalpy redistribution
+   USE icethd_do      ! sea-ice: growth in open water
+   USE icethd_pnd     ! sea-ice: melt ponds
+   USE iceitd         ! sea-ice: remapping thickness distribution
+   USE icecor         ! sea-ice: corrections
+   USE icetab         ! sea-ice: 1D <==> 2D transformation
+   USE icevar         ! sea-ice: operations
+   USE icectl         ! sea-ice: control print
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd         ! called by limstp module
+   PUBLIC   ice_thd_init    ! called by ice_init
+
+   !!** namelist (namthd) **
+   LOGICAL ::   ln_icedH         ! activate ice thickness change from growing/melting (T) or not (F)
+   LOGICAL ::   ln_icedA         ! activate lateral melting param. (T) or not (F)
+   LOGICAL ::   ln_icedO         ! activate ice growth in open-water (T) or not (F)
+   LOGICAL ::   ln_icedS         ! activate gravity drainage and flushing (T) or not (F)
+   LOGICAL ::   ln_leadhfx       ! heat in the leads is used to melt sea-ice before warming the ocean
+
+   !! for convergence tests
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztice_cvgerr, ztice_cvgstp
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd( kt )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd  ***       
+      !!  
+      !! ** Purpose : This routine manages ice thermodynamics
+      !!         
+      !! ** Action : - computation of oceanic sensible heat flux at the ice base
+      !!                              energy budget in the leads
+      !!                              net fluxes on top of ice and of ocean
+      !!             - selection of grid cells with ice
+      !!                - call ice_thd_zdf  for vertical heat diffusion
+      !!                - call ice_thd_dh   for vertical ice growth and melt
+      !!                - call ice_thd_pnd  for melt ponds
+      !!                - call ice_thd_ent  for enthalpy remapping
+      !!                - call ice_thd_sal  for ice desalination
+      !!                - call ice_thd_temp to  retrieve temperature from ice enthalpy
+      !!                - call ice_thd_mono for extra lateral ice melt if active virtual thickness distribution
+      !!                - call ice_thd_da   for lateral ice melt
+      !!             - back to the geographic grid
+      !!                - call ice_thd_rem  for remapping thickness distribution
+      !!                - call ice_thd_do   for ice growth in leads
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt    ! number of iteration
+      !
+      INTEGER  :: ji, jj, jk, jl   ! dummy loop indices
+      REAL(wp) :: zfric_u, zqld, zqfr, zqfr_neg, zqfr_pos
+      REAL(wp), PARAMETER :: zfric_umin = 0._wp       ! lower bound for the friction velocity (cice value=5.e-04)
+      REAL(wp), PARAMETER :: zch        = 0.0057_wp   ! heat transfer coefficient
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_io, zv_io, zfric, zvel   ! ice-ocean velocity (m/s) and frictional velocity (m2/s2)
+      !
+      !!-------------------------------------------------------------------
+      ! controls
+      IF( ln_timing    )   CALL timing_start('icethd')                                                             ! timing
+      IF( ln_icediachk )   CALL ice_cons_hsm(0, 'icethd', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft) ! conservation
+      IF( ln_icediachk )   CALL ice_cons2D  (0, 'icethd',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft) ! conservation
+
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd: sea-ice thermodynamics'
+         WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      ! convergence tests
+      IF( ln_zdf_chkcvg ) THEN
+         ALLOCATE( ztice_cvgerr(jpi,jpj,jpl) , ztice_cvgstp(jpi,jpj,jpl) )
+         ztice_cvgerr = 0._wp ; ztice_cvgstp = 0._wp
+      ENDIF
+      
+      !---------------------------------------------!
+      ! computation of friction velocity at T points
+      !---------------------------------------------!
+      IF( ln_icedyn ) THEN
+         zu_io(:,:) = u_ice(:,:) - ssu_m(:,:)
+         zv_io(:,:) = v_ice(:,:) - ssv_m(:,:)
+         DO jj = 2, jpjm1 
+            DO ji = fs_2, fs_jpim1
+               zfric(ji,jj) = rn_cio * ( 0.5_wp *  &
+                  &                    (  zu_io(ji,jj) * zu_io(ji,jj) + zu_io(ji-1,jj) * zu_io(ji-1,jj)   &
+                  &                     + zv_io(ji,jj) * zv_io(ji,jj) + zv_io(ji,jj-1) * zv_io(ji,jj-1) ) ) * tmask(ji,jj,1)
+               zvel(ji,jj) = 0.5_wp * SQRT( ( u_ice(ji-1,jj) + u_ice(ji,jj) ) * ( u_ice(ji-1,jj) + u_ice(ji,jj) ) + &
+                  &                         ( v_ice(ji,jj-1) + v_ice(ji,jj) ) * ( v_ice(ji,jj-1) + v_ice(ji,jj) ) )
+            END DO
+         END DO
+      ELSE      !  if no ice dynamics => transfer directly the atmospheric stress to the ocean
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zfric(ji,jj) = r1_rau0 * SQRT( 0.5_wp *  &
+                  &                         (  utau(ji,jj) * utau(ji,jj) + utau(ji-1,jj) * utau(ji-1,jj)   &
+                  &                          + vtau(ji,jj) * vtau(ji,jj) + vtau(ji,jj-1) * vtau(ji,jj-1) ) ) * tmask(ji,jj,1)
+               zvel(ji,jj) = 0._wp
+            END DO
+         END DO
+      ENDIF
+      CALL lbc_lnk_multi( 'icethd', zfric, 'T',  1._wp, zvel, 'T', 1._wp )
+      !
+      !--------------------------------------------------------------------!
+      ! Partial computation of forcing for the thermodynamic sea ice model
+      !--------------------------------------------------------------------!
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            rswitch  = tmask(ji,jj,1) * MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi10 ) ) ! 0 if no ice
+            !
+            ! --- Energy received in the lead from atm-oce exchanges, zqld is defined everywhere (J.m-2) --- !
+            zqld =  tmask(ji,jj,1) * rdt_ice *  &
+               &    ( ( 1._wp - at_i_b(ji,jj) ) * qsr_oce(ji,jj) * frq_m(ji,jj) +  &
+               &      ( 1._wp - at_i_b(ji,jj) ) * qns_oce(ji,jj) + qemp_oce(ji,jj) )
+
+            ! --- Energy needed to bring ocean surface layer until its freezing, zqfr is defined everywhere (J.m-2) --- !
+            !     (mostly<0 but >0 if supercooling)
+            zqfr     = rau0 * rcp * e3t_m(ji,jj) * ( t_bo(ji,jj) - ( sst_m(ji,jj) + rt0 ) ) * tmask(ji,jj,1)  ! both < 0 (t_bo < sst) and > 0 (t_bo > sst)
+            zqfr_neg = MIN( zqfr , 0._wp )                                                                    ! only < 0
+            zqfr_pos = MAX( zqfr , 0._wp )                                                                    ! only > 0
+
+            ! --- Sensible ocean-to-ice heat flux (W/m2) --- !
+            !     (mostly>0 but <0 if supercooling)
+            zfric_u            = MAX( SQRT( zfric(ji,jj) ), zfric_umin ) 
+            qsb_ice_bot(ji,jj) = rswitch * rau0 * rcp * zch * zfric_u * ( ( sst_m(ji,jj) + rt0 ) - t_bo(ji,jj) )
+
+            ! upper bound for qsb_ice_bot: the heat retrieved from the ocean must be smaller than the heat necessary to reach 
+            !                              the freezing point, so that we do not have SST < T_freeze
+            !                              This implies: qsb_ice_bot(ji,jj) * at_i(ji,jj) * rtdice <= - zqfr_neg
+            !                              The following formulation is ok for both normal conditions and supercooling
+            qsb_ice_bot(ji,jj) = rswitch * MIN( qsb_ice_bot(ji,jj), - zqfr_neg * r1_rdtice / MAX( at_i(ji,jj), epsi10 ) )
+
+            ! --- Energy Budget of the leads (qlead, J.m-2) --- !
+            !     qlead is the energy received from the atm. in the leads.
+            !     If warming (zqld >= 0), then the energy in the leads is used to melt ice (bottom melting) => fhld  (W/m2)
+            !     If cooling (zqld <  0), then the energy in the leads is used to grow ice in open water    => qlead (J.m-2)
+            IF( zqld >= 0._wp .AND. at_i(ji,jj) > 0._wp ) THEN
+               ! upper bound for fhld: fhld should be equal to zqld
+               !                        but we have to make sure that this heat will not make the sst drop below the freezing point
+               !                        so the max heat that can be pulled out of the ocean is zqld - qsb - zqfr_pos
+               !                        The following formulation is ok for both normal conditions and supercooling
+               fhld (ji,jj) = rswitch * MAX( 0._wp, ( zqld - zqfr_pos ) * r1_rdtice / MAX( at_i(ji,jj), epsi10 ) &  ! divided by at_i since this is (re)multiplied by a_i in icethd_dh.F90
+                  &                                 - qsb_ice_bot(ji,jj) )
+               qlead(ji,jj) = 0._wp
+            ELSE
+               fhld (ji,jj) = 0._wp
+               ! upper bound for qlead: qlead should be equal to zqld
+               !                        but before using this heat for ice formation, we suppose that the ocean cools down till the freezing point.
+               !                        The energy for this cooling down is zqfr. Also some heat will be removed from the ocean from turbulent fluxes (qsb)
+               !                        and freezing point is reached if zqfr = zqld - qsb*a/dt
+               !                        so the max heat that can be pulled out of the ocean is zqld - qsb - zqfr
+               !                        The following formulation is ok for both normal conditions and supercooling
+               qlead(ji,jj) = MIN( 0._wp , zqld - ( qsb_ice_bot(ji,jj) * at_i(ji,jj) * rdt_ice ) - zqfr )
+            ENDIF
+            !
+            ! If ice is landfast and ice concentration reaches its max
+            ! => stop ice formation in open water
+            IF(  zvel(ji,jj) <= 5.e-04_wp .AND. at_i(ji,jj) >= rn_amax_2d(ji,jj)-epsi06 )   qlead(ji,jj) = 0._wp
+            !
+            ! If the grid cell is almost fully covered by ice (no leads)
+            ! => stop ice formation in open water
+            IF( at_i(ji,jj) >= (1._wp - epsi10) )   qlead(ji,jj) = 0._wp
+            !
+            ! If ln_leadhfx is false
+            ! => do not use energy of the leads to melt sea-ice
+            IF( .NOT.ln_leadhfx )   fhld(ji,jj) = 0._wp
+            !
+         END DO
+      END DO
+      
+      ! In case we bypass open-water ice formation
+      IF( .NOT. ln_icedO )  qlead(:,:) = 0._wp
+      ! In case we bypass growing/melting from top and bottom
+      IF( .NOT. ln_icedH ) THEN
+         qsb_ice_bot(:,:) = 0._wp
+         fhld       (:,:) = 0._wp
+      ENDIF
+
+      !-------------------------------------------------------------------------------------------!
+      ! Thermodynamic computation (only on grid points covered by ice) => loop over ice categories
+      !-------------------------------------------------------------------------------------------!
+      DO jl = 1, jpl
+
+         ! select ice covered grid points
+         npti = 0 ; nptidx(:) = 0
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( a_i(ji,jj,jl) > epsi10 ) THEN     
+                  npti         = npti  + 1
+                  nptidx(npti) = (jj - 1) * jpi + ji
+               ENDIF
+            END DO
+         END DO
+
+         IF( npti > 0 ) THEN  ! If there is no ice, do nothing.
+            !                                                                
+                              CALL ice_thd_1d2d( jl, 1 )            ! --- Move to 1D arrays --- !
+            !                                                       ! --- & Change units of e_i, e_s from J/m2 to J/m3 --- !
+            !
+            s_i_new   (1:npti) = 0._wp ; dh_s_tot(1:npti) = 0._wp   ! --- some init --- !  (important to have them here) 
+            dh_i_sum  (1:npti) = 0._wp ; dh_i_bom(1:npti) = 0._wp ; dh_i_itm  (1:npti) = 0._wp 
+            dh_i_sub  (1:npti) = 0._wp ; dh_i_bog(1:npti) = 0._wp
+            dh_snowice(1:npti) = 0._wp ; dh_s_mlt(1:npti) = 0._wp
+            !                                      
+                              CALL ice_thd_zdf                      ! --- Ice-Snow temperature --- !
+            !
+            IF( ln_icedH ) THEN                                     ! --- Growing/Melting --- !
+                              CALL ice_thd_dh                           ! Ice-Snow thickness   
+                              CALL ice_thd_pnd                          ! Melt ponds formation
+                              CALL ice_thd_ent( e_i_1d(1:npti,:) )      ! Ice enthalpy remapping
+            ENDIF
+                              CALL ice_thd_sal( ln_icedS )          ! --- Ice salinity --- !    
+            !
+                              CALL ice_thd_temp                     ! --- Temperature update --- !
+            !
+            IF( ln_icedH .AND. ln_virtual_itd ) &
+               &              CALL ice_thd_mono                     ! --- Extra lateral melting if virtual_itd --- !
+            !
+            IF( ln_icedA )    CALL ice_thd_da                       ! --- Lateral melting --- !
+            !
+                              CALL ice_thd_1d2d( jl, 2 )            ! --- Change units of e_i, e_s from J/m3 to J/m2 --- !
+            !                                                       ! --- & Move to 2D arrays --- !
+         ENDIF
+         !
+      END DO
+      !
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icethd', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'icethd',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      !                   
+      IF( jpl > 1  )          CALL ice_itd_rem( kt )                ! --- Transport ice between thickness categories --- !
+      !
+      IF( ln_icedO )          CALL ice_thd_do                       ! --- Frazil ice growth in leads --- !
+      !
+                              CALL ice_cor( kt , 2 )                ! --- Corrections --- !
+      !
+      oa_i(:,:,:) = oa_i(:,:,:) + a_i(:,:,:) * rdt_ice              ! ice natural aging incrementation     
+      !
+      ! convergence tests
+      IF( ln_zdf_chkcvg ) THEN
+         CALL iom_put( 'tice_cvgerr', ztice_cvgerr ) ; DEALLOCATE( ztice_cvgerr )
+         CALL iom_put( 'tice_cvgstp', ztice_cvgstp ) ; DEALLOCATE( ztice_cvgstp )
+      ENDIF
+      !
+      ! controls
+      IF( ln_icectl )   CALL ice_prt    (kt, iiceprt, jiceprt, 1, ' - ice thermodyn. - ') ! prints
+      IF( ln_ctl    )   CALL ice_prt3D  ('icethd')                                        ! prints
+      IF( ln_timing )   CALL timing_stop('icethd')                                        ! timing
+      !
+   END SUBROUTINE ice_thd 
+
+ 
+   SUBROUTINE ice_thd_temp
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_temp *** 
+      !!                 
+      !! ** Purpose :   Computes sea ice temperature (Kelvin) from enthalpy
+      !!
+      !! ** Method  :   Formula (Bitz and Lipscomb, 1999)
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jk   ! dummy loop indices
+      REAL(wp) ::   ztmelts, zbbb, zccc  ! local scalar 
+      !!-------------------------------------------------------------------
+      ! Recover ice temperature
+      DO jk = 1, nlay_i
+         DO ji = 1, npti
+            ztmelts       = -rTmlt * sz_i_1d(ji,jk)
+            ! Conversion q(S,T) -> T (second order equation)
+            zbbb          = ( rcp - rcpi ) * ztmelts + e_i_1d(ji,jk) * r1_rhoi - rLfus
+            zccc          = SQRT( MAX( zbbb * zbbb - 4._wp * rcpi * rLfus * ztmelts, 0._wp ) )
+            t_i_1d(ji,jk) = rt0 - ( zbbb + zccc ) * 0.5_wp * r1_rcpi
+            
+            ! mask temperature
+            rswitch       = 1._wp - MAX( 0._wp , SIGN( 1._wp , - h_i_1d(ji) ) ) 
+            t_i_1d(ji,jk) = rswitch * t_i_1d(ji,jk) + ( 1._wp - rswitch ) * rt0
+         END DO 
+      END DO 
+      !
+   END SUBROUTINE ice_thd_temp
+
+
+   SUBROUTINE ice_thd_mono
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_mono *** 
+      !!                 
+      !! ** Purpose :   Lateral melting in case virtual_itd
+      !!                          ( dA = A/2h dh )
+      !!-----------------------------------------------------------------------
+      INTEGER  ::   ji                 ! dummy loop indices
+      REAL(wp) ::   zhi_bef            ! ice thickness before thermo
+      REAL(wp) ::   zdh_mel, zda_mel   ! net melting
+      REAL(wp) ::   zvi, zvs           ! ice/snow volumes 
+      !!-----------------------------------------------------------------------
+      !
+      DO ji = 1, npti
+         zdh_mel = MIN( 0._wp, dh_i_itm(ji) + dh_i_sum(ji) + dh_i_bom(ji) + dh_snowice(ji) + dh_i_sub(ji) )
+         IF( zdh_mel < 0._wp .AND. a_i_1d(ji) > 0._wp )  THEN
+            zvi          = a_i_1d(ji) * h_i_1d(ji)
+            zvs          = a_i_1d(ji) * h_s_1d(ji)
+            ! lateral melting = concentration change
+            zhi_bef     = h_i_1d(ji) - zdh_mel
+            rswitch     = MAX( 0._wp , SIGN( 1._wp , zhi_bef - epsi20 ) )
+            zda_mel     = rswitch * a_i_1d(ji) * zdh_mel / ( 2._wp * MAX( zhi_bef, epsi20 ) )
+            a_i_1d(ji)  = MAX( epsi20, a_i_1d(ji) + zda_mel ) 
+            ! adjust thickness
+            h_i_1d(ji) = zvi / a_i_1d(ji)            
+            h_s_1d(ji) = zvs / a_i_1d(ji)            
+            ! retrieve total concentration
+            at_i_1d(ji) = a_i_1d(ji)
+         END IF
+      END DO
+      !
+   END SUBROUTINE ice_thd_mono
+
+
+   SUBROUTINE ice_thd_1d2d( kl, kn )
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_1d2d *** 
+      !!                 
+      !! ** Purpose :   move arrays from 1d to 2d and the reverse
+      !!-----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kl   ! index of the ice category 
+      INTEGER, INTENT(in) ::   kn   ! 1= from 2D to 1D   ;   2= from 1D to 2D
+      !
+      INTEGER ::   jk   ! dummy loop indices
+      !!-----------------------------------------------------------------------
+      !
+      SELECT CASE( kn )
+      !                    !---------------------!
+      CASE( 1 )            !==  from 2D to 1D  ==!
+         !                 !---------------------!
+         CALL tab_2d_1d( npti, nptidx(1:npti), at_i_1d(1:npti), at_i             )
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_i_1d (1:npti), a_i (:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_i_1d (1:npti), h_i (:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_s_1d (1:npti), h_s (:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_su_1d(1:npti), t_su(:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), s_i_1d (1:npti), s_i (:,:,kl)     )
+         DO jk = 1, nlay_s
+            CALL tab_2d_1d( npti, nptidx(1:npti), t_s_1d(1:npti,jk), t_s(:,:,jk,kl)    )
+            CALL tab_2d_1d( npti, nptidx(1:npti), e_s_1d(1:npti,jk), e_s(:,:,jk,kl)    )
+         END DO
+         DO jk = 1, nlay_i
+            CALL tab_2d_1d( npti, nptidx(1:npti), t_i_1d (1:npti,jk), t_i (:,:,jk,kl)  )
+            CALL tab_2d_1d( npti, nptidx(1:npti), e_i_1d (1:npti,jk), e_i (:,:,jk,kl)  )
+            CALL tab_2d_1d( npti, nptidx(1:npti), sz_i_1d(1:npti,jk), sz_i(:,:,jk,kl)  )
+         END DO
+         CALL tab_2d_1d( npti, nptidx(1:npti), a_ip_1d     (1:npti), a_ip     (:,:,kl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_ip_1d     (1:npti), h_ip     (:,:,kl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), h_il_1d     (1:npti), h_il     (:,:,kl) )
+         !
+         CALL tab_2d_1d( npti, nptidx(1:npti), qprec_ice_1d  (1:npti), qprec_ice            )
+         CALL tab_2d_1d( npti, nptidx(1:npti), qsr_ice_1d    (1:npti), qsr_ice (:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), qns_ice_1d    (1:npti), qns_ice (:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), evap_ice_1d   (1:npti), evap_ice(:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), dqns_ice_1d   (1:npti), dqns_ice(:,:,kl)     )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_bo_1d       (1:npti), t_bo                 )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sprecip_1d    (1:npti), sprecip              ) 
+         CALL tab_2d_1d( npti, nptidx(1:npti), qsb_ice_bot_1d(1:npti), qsb_ice_bot          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), fhld_1d       (1:npti), fhld                 )
+         
+         CALL tab_2d_1d( npti, nptidx(1:npti), qml_ice_1d    (1:npti), qml_ice    (:,:,kl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), qcn_ice_1d    (1:npti), qcn_ice    (:,:,kl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), qtr_ice_top_1d(1:npti), qtr_ice_top(:,:,kl) )
+         !
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_snw_sni_1d(1:npti), wfx_snw_sni   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_snw_sum_1d(1:npti), wfx_snw_sum   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_sub_1d    (1:npti), wfx_sub       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_snw_sub_1d(1:npti), wfx_snw_sub   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_ice_sub_1d(1:npti), wfx_ice_sub   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_err_sub_1d(1:npti), wfx_err_sub   )
+         !
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_bog_1d (1:npti), wfx_bog          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_bom_1d (1:npti), wfx_bom          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_sum_1d (1:npti), wfx_sum          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_sni_1d (1:npti), wfx_sni          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_res_1d (1:npti), wfx_res          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_spr_1d (1:npti), wfx_spr          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_lam_1d (1:npti), wfx_lam          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_pnd_1d (1:npti), wfx_pnd          )
+         !
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_bog_1d (1:npti), sfx_bog          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_bom_1d (1:npti), sfx_bom          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_sum_1d (1:npti), sfx_sum          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_sni_1d (1:npti), sfx_sni          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_bri_1d (1:npti), sfx_bri          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_res_1d (1:npti), sfx_res          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_sub_1d (1:npti), sfx_sub          )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_lam_1d (1:npti), sfx_lam          )
+         !
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_thd_1d    (1:npti), hfx_thd       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_spr_1d    (1:npti), hfx_spr       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_sum_1d    (1:npti), hfx_sum       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_bom_1d    (1:npti), hfx_bom       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_bog_1d    (1:npti), hfx_bog       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_dif_1d    (1:npti), hfx_dif       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_opw_1d    (1:npti), hfx_opw       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_snw_1d    (1:npti), hfx_snw       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_sub_1d    (1:npti), hfx_sub       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_res_1d    (1:npti), hfx_res       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_err_dif_1d(1:npti), hfx_err_dif   )
+         !
+         ! ocean surface fields
+         CALL tab_2d_1d( npti, nptidx(1:npti), sst_1d(1:npti), sst_m )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sss_1d(1:npti), sss_m )
+         CALL tab_2d_1d( npti, nptidx(1:npti), frq_m_1d(1:npti), frq_m )
+         !
+         ! to update ice age
+         CALL tab_2d_1d( npti, nptidx(1:npti), o_i_1d (1:npti), o_i (:,:,kl) )
+         CALL tab_2d_1d( npti, nptidx(1:npti), oa_i_1d(1:npti), oa_i(:,:,kl) )
+         !
+         ! --- Change units of e_i, e_s from J/m2 to J/m3 --- !
+         DO jk = 1, nlay_i
+            WHERE( h_i_1d(1:npti)>0._wp ) e_i_1d(1:npti,jk) = e_i_1d(1:npti,jk) / (h_i_1d(1:npti) * a_i_1d(1:npti)) * nlay_i
+         END DO
+         DO jk = 1, nlay_s
+            WHERE( h_s_1d(1:npti)>0._wp ) e_s_1d(1:npti,jk) = e_s_1d(1:npti,jk) / (h_s_1d(1:npti) * a_i_1d(1:npti)) * nlay_s
+         END DO
+         !
+         !                 !---------------------!
+      CASE( 2 )            !==  from 1D to 2D  ==!
+         !                 !---------------------!
+         ! --- Change units of e_i, e_s from J/m3 to J/m2 --- !
+         DO jk = 1, nlay_i
+            e_i_1d(1:npti,jk) = e_i_1d(1:npti,jk) * h_i_1d(1:npti) * a_i_1d(1:npti) * r1_nlay_i
+         END DO
+         DO jk = 1, nlay_s
+            e_s_1d(1:npti,jk) = e_s_1d(1:npti,jk) * h_s_1d(1:npti) * a_i_1d(1:npti) * r1_nlay_s
+         END DO
+         !
+         ! Change thickness to volume (replaces routine ice_var_eqv2glo)
+         v_i_1d (1:npti) = h_i_1d (1:npti) * a_i_1d (1:npti)
+         v_s_1d (1:npti) = h_s_1d (1:npti) * a_i_1d (1:npti)
+         sv_i_1d(1:npti) = s_i_1d (1:npti) * v_i_1d (1:npti)
+         v_ip_1d(1:npti) = h_ip_1d(1:npti) * a_ip_1d(1:npti)
+         v_il_1d(1:npti) = h_il_1d(1:npti) * a_ip_1d(1:npti)
+         oa_i_1d(1:npti) = o_i_1d (1:npti) * a_i_1d (1:npti)
+         
+         CALL tab_1d_2d( npti, nptidx(1:npti), at_i_1d(1:npti), at_i             )
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_i_1d (1:npti), a_i (:,:,kl)     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_i_1d (1:npti), h_i (:,:,kl)     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_s_1d (1:npti), h_s (:,:,kl)     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), t_su_1d(1:npti), t_su(:,:,kl)     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), s_i_1d (1:npti), s_i (:,:,kl)     )
+         DO jk = 1, nlay_s
+            CALL tab_1d_2d( npti, nptidx(1:npti), t_s_1d(1:npti,jk), t_s(:,:,jk,kl)    )
+            CALL tab_1d_2d( npti, nptidx(1:npti), e_s_1d(1:npti,jk), e_s(:,:,jk,kl)    )
+         END DO
+         DO jk = 1, nlay_i
+            CALL tab_1d_2d( npti, nptidx(1:npti), t_i_1d (1:npti,jk), t_i (:,:,jk,kl)  )
+            CALL tab_1d_2d( npti, nptidx(1:npti), e_i_1d (1:npti,jk), e_i (:,:,jk,kl)  )
+            CALL tab_1d_2d( npti, nptidx(1:npti), sz_i_1d(1:npti,jk), sz_i(:,:,jk,kl)  )
+         END DO
+         CALL tab_1d_2d( npti, nptidx(1:npti), a_ip_1d     (1:npti), a_ip     (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_ip_1d     (1:npti), h_ip     (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), h_il_1d     (1:npti), h_il     (:,:,kl) )
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_snw_sni_1d(1:npti), wfx_snw_sni )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_snw_sum_1d(1:npti), wfx_snw_sum )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_sub_1d    (1:npti), wfx_sub     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_snw_sub_1d(1:npti), wfx_snw_sub )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_ice_sub_1d(1:npti), wfx_ice_sub )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_err_sub_1d(1:npti), wfx_err_sub )
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_bog_1d (1:npti), wfx_bog        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_bom_1d (1:npti), wfx_bom        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_sum_1d (1:npti), wfx_sum        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_sni_1d (1:npti), wfx_sni        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_res_1d (1:npti), wfx_res        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_spr_1d (1:npti), wfx_spr        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_lam_1d (1:npti), wfx_lam        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_pnd_1d (1:npti), wfx_pnd        )
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_bog_1d (1:npti), sfx_bog        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_bom_1d (1:npti), sfx_bom        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_sum_1d (1:npti), sfx_sum        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_sni_1d (1:npti), sfx_sni        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_bri_1d (1:npti), sfx_bri        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_res_1d (1:npti), sfx_res        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_sub_1d (1:npti), sfx_sub        )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_lam_1d (1:npti), sfx_lam        )
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_thd_1d    (1:npti), hfx_thd     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_spr_1d    (1:npti), hfx_spr     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_sum_1d    (1:npti), hfx_sum     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_bom_1d    (1:npti), hfx_bom     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_bog_1d    (1:npti), hfx_bog     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_dif_1d    (1:npti), hfx_dif     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_opw_1d    (1:npti), hfx_opw     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_snw_1d    (1:npti), hfx_snw     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_sub_1d    (1:npti), hfx_sub     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_res_1d    (1:npti), hfx_res     )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_err_dif_1d(1:npti), hfx_err_dif )
+         !
+         CALL tab_1d_2d( npti, nptidx(1:npti), qns_ice_1d    (1:npti), qns_ice    (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), qtr_ice_bot_1d(1:npti), qtr_ice_bot(:,:,kl) )
+         ! effective conductivity and 1st layer temperature (ln_cndflx=T)
+         CALL tab_1d_2d( npti, nptidx(1:npti), cnd_ice_1d(1:npti), cnd_ice(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), t1_ice_1d (1:npti), t1_ice (:,:,kl) )
+         ! SIMIP diagnostics         
+         CALL tab_1d_2d( npti, nptidx(1:npti), t_si_1d       (1:npti), t_si       (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), qcn_ice_bot_1d(1:npti), qcn_ice_bot(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), qcn_ice_top_1d(1:npti), qcn_ice_top(:,:,kl) )
+         ! extensive variables
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_i_1d (1:npti), v_i (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_s_1d (1:npti), v_s (:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), sv_i_1d(1:npti), sv_i(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_ip_1d(1:npti), v_ip(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), v_il_1d(1:npti), v_il(:,:,kl) )
+         CALL tab_1d_2d( npti, nptidx(1:npti), oa_i_1d(1:npti), oa_i(:,:,kl) )
+         ! check convergence of heat diffusion scheme
+         IF( ln_zdf_chkcvg ) THEN
+            CALL tab_1d_2d( npti, nptidx(1:npti), tice_cvgerr_1d(1:npti), ztice_cvgerr(:,:,kl) )
+            CALL tab_1d_2d( npti, nptidx(1:npti), tice_cvgstp_1d(1:npti), ztice_cvgstp(:,:,kl) )
+         ENDIF
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_thd_1d2d
+
+
+   SUBROUTINE ice_thd_init
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_init *** 
+      !!                 
+      !! ** Purpose :   Physical constants and parameters associated with
+      !!                ice thermodynamics
+      !!
+      !! ** Method  :   Read the namthd namelist and check the parameters
+      !!                called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namthd/ ln_icedH, ln_icedA, ln_icedO, ln_icedS, ln_leadhfx
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd in reference namelist : Ice thermodynamics
+      READ  ( numnam_ice_ref, namthd, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd in configuration namelist : Ice thermodynamics
+      READ  ( numnam_ice_cfg, namthd, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd in configuration namelist' )
+      IF(lwm) WRITE( numoni, namthd )
+      !
+      IF(lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_init: Ice Thermodynamics'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namthd:'
+         WRITE(numout,*) '      activate ice thick change from top/bot (T) or not (F)                ln_icedH   = ', ln_icedH
+         WRITE(numout,*) '      activate lateral melting (T) or not (F)                              ln_icedA   = ', ln_icedA
+         WRITE(numout,*) '      activate ice growth in open-water (T) or not (F)                     ln_icedO   = ', ln_icedO
+         WRITE(numout,*) '      activate gravity drainage and flushing (T) or not (F)                ln_icedS   = ', ln_icedS
+         WRITE(numout,*) '      heat in the leads is used to melt sea-ice before warming the ocean   ln_leadhfx = ', ln_leadhfx
+     ENDIF
+      !
+                       CALL ice_thd_zdf_init   ! set ice heat diffusion parameters
+      IF( ln_icedA )   CALL ice_thd_da_init    ! set ice lateral melting parameters
+      IF( ln_icedO )   CALL ice_thd_do_init    ! set ice growth in open water parameters
+                       CALL ice_thd_sal_init   ! set ice salinity parameters
+                       CALL ice_thd_pnd_init   ! set melt ponds parameters
+      !
+   END SUBROUTINE ice_thd_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Dummy module          NO  SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_da.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_da.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_da.F90	(revision 14097)
@@ -0,0 +1,205 @@
+MODULE icethd_da
+   !!======================================================================
+   !!                       ***  MODULE icethd_da ***
+   !!   sea-ice : lateral melting
+   !!======================================================================
+   !! History :  3.7  !  2016-03  (C. Rousset)       Original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!---------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_da      : sea ice lateral melting
+   !!   ice_thd_da_init : sea ice lateral melting initialization
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE phycst         ! physical constants (ocean directory)
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamic 1D variables
+   !
+   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)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_da        ! called by icethd.F90
+   PUBLIC   ice_thd_da_init   ! called by icestp.F90
+
+   !                      !!** namelist (namthd_da) **
+   REAL(wp) ::   rn_beta   ! coef. beta for lateral melting param.
+   REAL(wp) ::   rn_dmin   ! minimum floe diameter for lateral melting param.
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_da
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd_da  ***    
+      !!   
+      !! ** Purpose :   computes sea ice lateral melting
+      !!
+      !! ** Method  :   dA/dt = - P * W   [s-1]
+      !!                   W = melting velocity [m.s-1]
+      !!                   P = perimeter of ice-ocean lateral interface normalized by grid cell area [m.m-2]
+      !!
+      !!                   W = m1 * (Tw -Tf)**m2                    --- originally from Josberger 1979 ---
+      !!                      (Tw - Tf) = elevation of water temp above freezing
+      !!                      m1 and m2 = (1.6e-6 , 1.36) best fit from field experiment near the coast of Prince Patrick Island
+      !!                                                                                           (Perovich 1983) => static ice
+      !!                      m1 and m2 = (3.0e-6 , 1.36) best fit from MIZEX 84 experiment
+      !!                                                                                (Maykut and Perovich 1987) => moving ice
+      !!
+      !!                   P = N * pi * D                           --- from Rothrock and Thorndike 1984 ---
+      !!                      D = mean floe caliper diameter
+      !!                      N = number of floes = ice area / floe area(average) = A / (Cs * D**2)
+      !!                         A = ice concentration
+      !!                         Cs = deviation from a square (square:Cs=1 ; circle:Cs=pi/4 ; floe:Cs=0.66)
+      !!
+      !!                   D = Dmin * ( Astar / (Astar-A) )**beta   --- from Lupkes et al., 2012 (eq. 26-27) ---
+      !!                                                             
+      !!                      Astar = 1 / ( 1 - (Dmin/Dmax)**(1/beta) )
+      !!                      Dmin = minimum floe diameter (recommended to be 8m +- 20%)
+      !!                      Dmax = maximum floe diameter (recommended to be 300m,
+      !!                                                    but it does not impact melting much except for Dmax<100m)
+      !!                      beta = 1.0 +-20% (recommended value)
+      !!                           = 0.3 best fit for western Fram Strait and Antarctica
+      !!                           = 1.4 best fit for eastern Fram Strait
+      !!
+      !! ** Tunable parameters  :   We propose to tune the lateral melting via 2 parameters
+      !!                               Dmin [6-10m]   => 6  vs 8m = +40% melting at the peak (A~0.5)
+      !!                                                 10 vs 8m = -20% melting
+      !!                               beta [0.8-1.2] => decrease = more melt and melt peaks toward higher concentration
+      !!                                                                  (A~0.5 for beta=1 ; A~0.8 for beta=0.2)
+      !!                                                 0.3 = best fit for western Fram Strait and Antarctica
+      !!                                                 1.4 = best fit for eastern Fram Strait
+      !!
+      !! ** Note   :   Former and more simple formulations for floe diameters can be found in Mai (1995), 
+      !!               Birnbaum and Lupkes (2002), Lupkes and Birnbaum (2005). They are reviewed in Lupkes et al 2012
+      !!               A simpler implementation for CICE can be found in Bitz et al (2001) and Tsamados et al (2015)
+      !!
+      !! ** References
+      !!    Bitz, C. M., Holland, M. M., Weaver, A. J., & Eby, M. (2001).
+      !!              Simulating the ice‐thickness distribution in a coupled climate model.
+      !!              Journal of Geophysical Research: Oceans, 106(C2), 2441-2463.
+      !!    Josberger, E. G. (1979).
+      !!              Laminar and turbulent boundary layers adjacent to melting vertical ice walls in salt water
+      !!              (No. SCIENTIFIC-16). WASHINGTON UNIV SEATTLE DEPT OF ATMOSPHERIC SCIENCES.
+      !!    Lüpkes, C., Gryanik, V. M., Hartmann, J., & Andreas, E. L. (2012).
+      !!              A parametrization, based on sea ice morphology, of the neutral atmospheric drag coefficients
+      !!              for weather prediction and climate models.
+      !!              Journal of Geophysical Research: Atmospheres, 117(D13).
+      !!    Maykut, G. A., & Perovich, D. K. (1987).
+      !!              The role of shortwave radiation in the summer decay of a sea ice cover.
+      !!              Journal of Geophysical Research: Oceans, 92(C7), 7032-7044.
+      !!    Perovich, D. K. (1983).
+      !!              On the summer decay of a sea ice cover. (Doctoral dissertation, University of Washington).
+      !!    Rothrock, D. A., & Thorndike, A. S. (1984).
+      !!              Measuring the sea ice floe size distribution.
+      !!              Journal of Geophysical Research: Oceans, 89(C4), 6477-6486.
+      !!    Tsamados, M., Feltham, D., Petty, A., Schroeder, D., & Flocco, D. (2015).
+      !!              Processes controlling surface, bottom and lateral melt of Arctic sea ice in a state of the art sea ice model.
+      !!              Phil. Trans. R. Soc. A, 373(2052), 20140167.
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji     ! dummy loop indices
+      REAL(wp)            ::   zastar, zdfloe, zperi, zwlat, zda
+      REAL(wp), PARAMETER ::   zdmax = 300._wp
+      REAL(wp), PARAMETER ::   zcs   = 0.66_wp
+      REAL(wp), PARAMETER ::   zm1   = 3.e-6_wp
+      REAL(wp), PARAMETER ::   zm2   = 1.36_wp
+      !
+      REAL(wp), DIMENSION(jpij) ::   zda_tot
+      !!---------------------------------------------------------------------
+      !
+      zastar = 1._wp / ( 1._wp - (rn_dmin / zdmax)**(1._wp/rn_beta) )
+      !
+      DO ji = 1, npti   
+         ! --- Calculate reduction of total sea ice concentration --- !
+         zdfloe = rn_dmin * ( zastar / ( zastar - at_i_1d(ji) ) )**rn_beta         ! Mean floe caliper diameter [m]
+         !
+         zperi  = at_i_1d(ji) * rpi / ( zcs * zdfloe )                             ! Mean perimeter of the floe [m.m-2]
+         !                                                                         !    = N*pi*D = (A/cs*D^2)*pi*D
+         zwlat  = zm1 * ( MAX( 0._wp, sst_1d(ji) - ( t_bo_1d(ji) - rt0 ) ) )**zm2  ! Melt speed rate [m/s]
+         !
+         zda_tot(ji) = MIN( zwlat * zperi * rdt_ice, at_i_1d(ji) )                 ! sea ice concentration decrease (>0)
+      
+         ! --- Distribute reduction among ice categories and calculate associated ice-ocean fluxes --- !
+         IF( a_i_1d(ji) > 0._wp ) THEN
+            ! decrease of concentration for the category jl
+            !    each category contributes to melting in proportion to its concentration
+            zda = MIN( a_i_1d(ji), zda_tot(ji) * a_i_1d(ji) / at_i_1d(ji) )
+            
+            ! Contribution to salt flux
+            sfx_lam_1d(ji) = sfx_lam_1d(ji) + rhoi *  h_i_1d(ji) * zda * s_i_1d(ji) * r1_rdtice
+            
+            ! Contribution to heat flux into the ocean [W.m-2], (<0)  
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) - zda * r1_rdtice * ( h_i_1d(ji) * r1_nlay_i * SUM( e_i_1d(ji,1:nlay_i) )  &
+                                                                + h_s_1d(ji) * r1_nlay_s * SUM( e_s_1d(ji,1:nlay_s) ) ) 
+            
+            ! Contribution to mass flux
+            wfx_lam_1d(ji) =  wfx_lam_1d(ji) + zda * r1_rdtice * ( rhoi * h_i_1d(ji) + rhos * h_s_1d(ji) )
+            
+            ! new concentration
+            a_i_1d(ji) = a_i_1d(ji) - zda
+
+            ! ensure that h_i = 0 where a_i = 0
+            IF( a_i_1d(ji) == 0._wp ) THEN
+               h_i_1d(ji) = 0._wp
+               h_s_1d(ji) = 0._wp
+            ENDIF
+         ENDIF
+      END DO
+      !
+   END SUBROUTINE ice_thd_da
+
+
+   SUBROUTINE ice_thd_da_init
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_da_init *** 
+      !!                 
+      !! ** Purpose :   Physical constants and parameters associated with
+      !!                ice thermodynamics
+      !!
+      !! ** Method  :   Read the namthd_da namelist and check the parameters
+      !!                called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd_da
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer
+      !!
+      NAMELIST/namthd_da/ rn_beta, rn_dmin
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd_da in reference namelist : Ice thermodynamics
+      READ  ( numnam_ice_ref, namthd_da, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd_da in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd_da in configuration namelist : Ice thermodynamics
+      READ  ( numnam_ice_cfg, namthd_da, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd_da in configuration namelist' )
+      IF(lwm) WRITE( numoni, namthd_da )
+      !
+      IF(lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_da_init: Ice lateral melting'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namthd_da:'
+         WRITE(numout,*) '      Coef. beta for lateral melting param.               rn_beta = ', rn_beta
+         WRITE(numout,*) '      Minimum floe diameter for lateral melting param.    rn_dmin = ', rn_dmin
+      ENDIF
+      !
+   END SUBROUTINE ice_thd_da_init
+  
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Dummy Module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_da
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_dh.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_dh.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_dh.F90	(revision 14097)
@@ -0,0 +1,640 @@
+MODULE icethd_dh
+   !!======================================================================
+   !!                       ***  MODULE icethd_dh ***
+   !!   seaice : thermodynamic growth and melt 
+   !!======================================================================
+   !! History :       !  2003-05  (M. Vancoppenolle) Original code in 1D
+   !!                 !  2005-06  (M. Vancoppenolle) 3D version 
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_dh        : vertical sea-ice growth and melt
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icethd_sal     ! sea-ice: salinity profiles
+   USE icevar         ! for CALL ice_var_snwblow
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_dh        ! called by ice_thd
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_dh
+      !!------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd_dh  ***
+      !!
+      !! ** Purpose :   compute ice and snow thickness changes due to growth/melting
+      !!
+      !! ** Method  :   Ice/Snow surface melting arises from imbalance in surface fluxes
+      !!                Bottom accretion/ablation arises from flux budget
+      !!                Snow thickness can increase by precipitation and decrease by sublimation
+      !!                If snow load excesses Archmiede limit, snow-ice is formed by
+      !!                the flooding of sea-water in the snow
+      !!
+      !!                - Compute available flux of heat for surface ablation
+      !!                - Compute snow and sea ice enthalpies
+      !!                - Surface ablation and sublimation
+      !!                - Bottom accretion/ablation
+      !!                - Snow ice formation
+      !!
+      !! References : Bitz and Lipscomb, 1999, J. Geophys. Res.
+      !!              Fichefet T. and M. Maqueda 1997, J. Geophys. Res., 102(C6), 12609-12646   
+      !!              Vancoppenolle, Fichefet and Bitz, 2005, Geophys. Res. Let. 
+      !!              Vancoppenolle et al.,2009, Ocean Modelling
+      !!------------------------------------------------------------------
+      INTEGER  ::   ji, jk       ! dummy loop indices
+      INTEGER  ::   iter         ! local integer
+
+      REAL(wp) ::   ztmelts      ! local scalar
+      REAL(wp) ::   zdum       
+      REAL(wp) ::   zfracs       ! fractionation coefficient for bottom salt entrapment
+      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) ::   zt_i_new     ! bottom formation temperature
+      REAL(wp) ::   z1_rho       ! 1/(rhos+rau0-rhoi)
+
+      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), DIMENSION(jpij) ::   zqprec      ! energy of fallen snow                       (J.m-3)
+      REAL(wp), DIMENSION(jpij) ::   zq_top      ! heat for surface ablation                   (J.m-2)
+      REAL(wp), DIMENSION(jpij) ::   zq_bot      ! heat for bottom ablation                    (J.m-2)
+      REAL(wp), DIMENSION(jpij) ::   zq_rema     ! remaining heat at the end of the routine    (J.m-2)
+      REAL(wp), DIMENSION(jpij) ::   zf_tt       ! Heat budget to determine melting or freezing(W.m-2)
+      REAL(wp), DIMENSION(jpij) ::   zevap_rema  ! remaining mass flux from sublimation        (kg.m-2)
+
+      REAL(wp), DIMENSION(jpij) ::   zdh_s_mel   ! snow melt 
+      REAL(wp), DIMENSION(jpij) ::   zdh_s_pre   ! snow precipitation 
+      REAL(wp), DIMENSION(jpij) ::   zdh_s_sub   ! snow sublimation
+
+      REAL(wp), DIMENSION(jpij,nlay_s) ::   zh_s      ! snw layer thickness
+      REAL(wp), DIMENSION(jpij,nlay_i) ::   zh_i      ! ice layer thickness
+      REAL(wp), DIMENSION(jpij,nlay_i) ::   zdeltah
+      INTEGER , DIMENSION(jpij,nlay_i) ::   icount    ! number of layers vanished by melting 
+
+      REAL(wp), DIMENSION(jpij) ::   zsnw        ! distribution of snow after wind blowing
+
+      REAL(wp) ::   zswitch_sal
+
+      INTEGER  ::   num_iter_max      ! Heat conservation 
+      !!------------------------------------------------------------------
+
+      ! Discriminate between time varying salinity and constant
+      SELECT CASE( nn_icesal )                  ! varying salinity or not
+         CASE( 1 , 3 )   ;   zswitch_sal = 0._wp   ! prescribed salinity profile
+         CASE( 2 )       ;   zswitch_sal = 1._wp   ! varying salinity profile
+      END SELECT
+
+      ! initialize layer thicknesses and enthalpies
+      h_i_old (1:npti,0:nlay_i+1) = 0._wp
+      eh_i_old(1:npti,0:nlay_i+1) = 0._wp
+      DO jk = 1, nlay_i
+         DO ji = 1, npti
+            h_i_old (ji,jk) = h_i_1d(ji) * r1_nlay_i
+            eh_i_old(ji,jk) = e_i_1d(ji,jk) * h_i_old(ji,jk)
+         END DO
+      END DO
+      !
+      !                       ! ============================================== !
+      !                       ! Available heat for surface and bottom ablation !
+      !                       ! ============================================== !
+      !
+      IF( ln_cndflx .AND. .NOT.ln_cndemulate ) THEN
+         !
+         DO ji = 1, npti
+            zq_top(ji)     = MAX( 0._wp, qml_ice_1d(ji) * rdt_ice )
+         END DO
+         !
+      ELSE
+         !
+         DO ji = 1, npti
+            zdum           = qns_ice_1d(ji) + qsr_ice_1d(ji) - qtr_ice_top_1d(ji) - qcn_ice_top_1d(ji)
+            qml_ice_1d(ji) = zdum * MAX( 0._wp , SIGN( 1._wp, t_su_1d(ji) - rt0 ) )
+            zq_top(ji)     = MAX( 0._wp, qml_ice_1d(ji) * rdt_ice )
+         END DO
+         !
+      ENDIF
+      !
+      DO ji = 1, npti
+         zf_tt(ji)         = qcn_ice_bot_1d(ji) + qsb_ice_bot_1d(ji) + fhld_1d(ji) + qtr_ice_bot_1d(ji) * frq_m_1d(ji) 
+         zq_bot(ji)        = MAX( 0._wp, zf_tt(ji) * rdt_ice )
+      END DO
+
+      ! Ice and snow layer thicknesses
+      !-------------------------------
+      DO jk = 1, nlay_i
+         DO ji = 1, npti
+            zh_i(ji,jk) = h_i_1d(ji) * r1_nlay_i
+         END DO
+      END DO
+
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            zh_s(ji,jk) = h_s_1d(ji) * r1_nlay_s
+         END DO
+      END DO
+
+      !                       ! ============ !
+      !                       !     Snow     !
+      !                       ! ============ !
+      !
+      ! Internal melting
+      ! ----------------
+      ! IF snow temperature is above freezing point, THEN snow melts (should not happen but sometimes it does)
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            IF( t_s_1d(ji,jk) > rt0 ) THEN
+               hfx_res_1d    (ji) = hfx_res_1d    (ji) + e_s_1d(ji,jk) * zh_s(ji,jk) * a_i_1d(ji) * r1_rdtice   ! heat flux to the ocean [W.m-2], < 0
+               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) + rhos          * zh_s(ji,jk) * a_i_1d(ji) * r1_rdtice   ! mass flux
+               ! updates
+               dh_s_mlt(ji)    = dh_s_mlt(ji) - zh_s(ji,jk)
+               h_s_1d  (ji)    = h_s_1d(ji) - zh_s(ji,jk)
+               zh_s    (ji,jk) = 0._wp
+               e_s_1d  (ji,jk) = 0._wp
+               t_s_1d  (ji,jk) = rt0
+            END IF
+         END DO
+      END DO         
+
+      ! Snow precipitation
+      !-------------------
+      CALL ice_var_snwblow( 1. - at_i_1d(1:npti), zsnw(1:npti) )   ! snow distribution over ice after wind blowing
+
+      zdeltah(1:npti,:) = 0._wp
+      DO ji = 1, npti
+         IF( sprecip_1d(ji) > 0._wp ) THEN
+            !
+            ! --- precipitation ---
+            zdh_s_pre (ji) = zsnw(ji) * sprecip_1d(ji) * rdt_ice * r1_rhos / at_i_1d(ji)   ! thickness change
+            zqprec    (ji) = - qprec_ice_1d(ji)                                             ! enthalpy of the precip (>0, J.m-3)
+            !
+            hfx_spr_1d(ji) = hfx_spr_1d(ji) + zdh_s_pre(ji) * a_i_1d(ji) * zqprec(ji)    * r1_rdtice   ! heat flux from snow precip (>0, W.m-2)
+            wfx_spr_1d(ji) = wfx_spr_1d(ji) - rhos          * a_i_1d(ji) * zdh_s_pre(ji) * r1_rdtice   ! mass flux, <0
+            
+            ! --- melt of falling snow ---
+            rswitch              = MAX( 0._wp , SIGN( 1._wp , zqprec(ji) - epsi20 ) )
+            zdeltah       (ji,1) = - rswitch * zq_top(ji) / MAX( zqprec(ji) , epsi20 )   ! thickness change
+            zdeltah       (ji,1) = MAX( - zdh_s_pre(ji), zdeltah(ji,1) )                 ! bound melting 
+            hfx_snw_1d    (ji)   = hfx_snw_1d    (ji) - zdeltah(ji,1) * a_i_1d(ji) * zqprec(ji)    * r1_rdtice   ! heat used to melt snow (W.m-2, >0)
+            wfx_snw_sum_1d(ji)   = wfx_snw_sum_1d(ji) - rhos          * a_i_1d(ji) * zdeltah(ji,1) * r1_rdtice   ! snow melting only = water into the ocean (then without snow precip), >0
+            
+            ! updates available heat + precipitations after melting
+            dh_s_mlt (ji) = dh_s_mlt(ji) + zdeltah(ji,1)
+            zq_top   (ji) = MAX( 0._wp , zq_top (ji) + zdeltah(ji,1) * zqprec(ji) )      
+            zdh_s_pre(ji) = zdh_s_pre(ji) + zdeltah(ji,1)
+            
+            ! update thickness
+            h_s_1d(ji) = MAX( 0._wp , h_s_1d(ji) + zdh_s_pre(ji) )
+            !
+         ELSE
+            !
+            zdh_s_pre(ji) = 0._wp
+            zqprec   (ji) = 0._wp
+            !
+         ENDIF
+      END DO
+
+      ! recalculate snow layers
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            zh_s(ji,jk) = h_s_1d(ji) * r1_nlay_s
+         END DO
+      END DO
+
+      ! Snow melting
+      ! ------------
+      ! If heat still available (zq_top > 0), then melt more snow
+      zdeltah(1:npti,:) = 0._wp
+      zdh_s_mel(1:npti) = 0._wp
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            IF( zh_s(ji,jk) > 0._wp .AND. zq_top(ji) > 0._wp ) THEN
+               !
+               rswitch          = MAX( 0._wp, SIGN( 1._wp, e_s_1d(ji,jk) - epsi20 ) )
+               zdeltah  (ji,jk) = - rswitch * zq_top(ji) / MAX( e_s_1d(ji,jk), epsi20 )   ! thickness change
+               zdeltah  (ji,jk) = MAX( zdeltah(ji,jk) , - zh_s(ji,jk) )                   ! bound melting
+               zdh_s_mel(ji)    = zdh_s_mel(ji) + zdeltah(ji,jk)
+               
+               hfx_snw_1d(ji)     = hfx_snw_1d(ji)     - zdeltah(ji,jk) * a_i_1d(ji) * e_s_1d (ji,jk) * r1_rdtice   ! heat used to melt snow(W.m-2, >0)
+               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) - rhos           * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice   ! snow melting only = water into the ocean (then without snow precip)
+               
+               ! updates available heat + thickness
+               dh_s_mlt(ji)    = dh_s_mlt(ji) + zdeltah(ji,jk)
+               zq_top  (ji)    = MAX( 0._wp , zq_top(ji) + zdeltah(ji,jk) * e_s_1d(ji,jk) )
+               h_s_1d  (ji)    = MAX( 0._wp , h_s_1d(ji) + zdeltah(ji,jk) )
+               zh_s    (ji,jk) = MAX( 0._wp , zh_s(ji,jk) + zdeltah(ji,jk) )
+               !
+            ENDIF
+         END DO
+      END DO
+
+      ! Snow sublimation 
+      !-----------------
+      ! qla_ice is always >=0 (upwards), heat goes to the atmosphere, therefore snow sublimates
+      !    comment: not counted in mass/heat exchange in iceupdate.F90 since this is an exchange with atm. (not ocean)
+      zdeltah(1:npti,:) = 0._wp
+      DO ji = 1, npti
+         IF( evap_ice_1d(ji) > 0._wp ) THEN
+            !
+            zdh_s_sub (ji)   = MAX( - h_s_1d(ji) , - evap_ice_1d(ji) * r1_rhos * rdt_ice )
+            zevap_rema(ji)   = evap_ice_1d(ji) * rdt_ice + zdh_s_sub(ji) * rhos   ! remaining evap in kg.m-2 (used for ice melting later on)
+            zdeltah   (ji,1) = MAX( zdh_s_sub(ji), - zdh_s_pre(ji) )
+            
+            hfx_sub_1d    (ji) = hfx_sub_1d(ji) + &   ! Heat flux by sublimation [W.m-2], < 0 (sublimate snow that had fallen, then pre-existing snow)
+               &                 ( zdeltah(ji,1) * zqprec(ji) + ( zdh_s_sub(ji) - zdeltah(ji,1) ) * e_s_1d(ji,1) )  &
+               &                 * a_i_1d(ji) * r1_rdtice
+            wfx_snw_sub_1d(ji) = wfx_snw_sub_1d(ji) - rhos * a_i_1d(ji) * zdh_s_sub(ji) * r1_rdtice   ! Mass flux by sublimation
+            
+            ! new snow thickness
+            h_s_1d(ji)    =  MAX( 0._wp , h_s_1d(ji) + zdh_s_sub(ji) )
+            ! update precipitations after sublimation and correct sublimation
+            zdh_s_pre(ji) = zdh_s_pre(ji) + zdeltah(ji,1)
+            zdh_s_sub(ji) = zdh_s_sub(ji) - zdeltah(ji,1)
+            !
+         ELSE
+            !
+            zdh_s_sub (ji) = 0._wp
+            zevap_rema(ji) = 0._wp
+            !
+         ENDIF
+      END DO
+      
+      ! --- Update snow diags --- !
+      DO ji = 1, npti
+         dh_s_tot(ji) = zdh_s_mel(ji) + zdh_s_pre(ji) + zdh_s_sub(ji)
+      END DO
+
+      ! Update temperature, energy
+      !---------------------------
+      ! new temp and enthalpy of the snow (remaining snow precip + remaining pre-existing snow)
+      DO jk = 1, nlay_s
+         DO ji = 1,npti
+            rswitch       = MAX( 0._wp , SIGN( 1._wp, h_s_1d(ji) - epsi20 ) )
+            e_s_1d(ji,jk) = rswitch / MAX( h_s_1d(ji), epsi20 ) *            &
+              &             ( ( zdh_s_pre(ji)              ) * zqprec(ji) +  &
+              &               ( h_s_1d(ji) - zdh_s_pre(ji) ) * rhos * ( rcpi * ( rt0 - t_s_1d(ji,jk) ) + rLfus ) )
+         END DO
+      END DO
+      
+      !                       ! ============ !
+      !                       !     Ice      !
+      !                       ! ============ !
+
+      ! Surface ice melting 
+      !--------------------
+      zdeltah(1:npti,:) = 0._wp ! important
+      DO jk = 1, nlay_i
+         DO ji = 1, npti
+            ztmelts = - rTmlt * sz_i_1d(ji,jk)   ! Melting point of layer k [C]
+            
+            IF( t_i_1d(ji,jk) >= (ztmelts+rt0) ) THEN   !-- Internal melting
+
+               zEi            = - e_i_1d(ji,jk) * r1_rhoi             ! Specific enthalpy of layer k [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
+               zfmdt          = - zdeltah(ji,jk) * rhoi               ! Mass flux x time step > 0
+                         
+               dh_i_itm(ji)   = dh_i_itm(ji) + zdeltah(ji,jk)         ! Cumulate internal melting
+               
+               zfmdt          = - rhoi * zdeltah(ji,jk)               ! Recompute mass flux [kg/m2, >0]
+
+               hfx_res_1d(ji) = hfx_res_1d(ji) + zfmdt * a_i_1d(ji) * zEi * r1_rdtice                           ! Heat flux to the ocean [W.m-2], <0
+               !                                                                                                  ice enthalpy zEi is "sent" to the ocean
+               sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_rdtice    ! Salt flux
+               !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok
+               wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice                 ! Mass flux
+
+            ELSE                                        !-- Surface melting
+               
+               zEi            = - e_i_1d(ji,jk) * r1_rhoi             ! Specific enthalpy of layer k [J/kg, <0]
+               zEw            =    rcp * ztmelts                      ! Specific enthalpy of resulting meltwater [J/kg, <0]
+               zdE            =    zEi - zEw                          ! Specific enthalpy difference < 0
+               
+               zfmdt          = - zq_top(ji) / zdE                    ! Mass flux to the ocean [kg/m2, >0]
+               
+               zdeltah(ji,jk) = - zfmdt * r1_rhoi                     ! 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_top(ji)      = MAX( 0._wp , zq_top(ji) - zdeltah(ji,jk) * rhoi * zdE ) ! update available heat
+               
+               dh_i_sum(ji)   = dh_i_sum(ji) + zdeltah(ji,jk)         ! Cumulate surface melt
+               
+               zfmdt          = - rhoi * zdeltah(ji,jk)               ! Recompute mass flux [kg/m2, >0]
+               
+               zQm            = zfmdt * zEw                           ! Energy of the melt water sent to the ocean [J/m2, <0]
+               
+               sfx_sum_1d(ji) = sfx_sum_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_rdtice    ! Salt flux >0
+               !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok)
+               hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice                           ! Heat flux [W.m-2], < 0
+               hfx_sum_1d(ji) = hfx_sum_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice                           ! Heat flux used in this process [W.m-2], > 0  
+               ! 
+               wfx_sum_1d(ji) = wfx_sum_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice                 ! Mass flux
+               
+            END IF
+            
+            ! Ice sublimation
+            ! ---------------
+            zdum            = MAX( - ( zh_i(ji,jk) + zdeltah(ji,jk) ) , - zevap_rema(ji) * r1_rhoi )
+            zdeltah (ji,jk) = zdeltah (ji,jk) + zdum
+            dh_i_sub(ji)    = dh_i_sub(ji)    + zdum
+            
+            sfx_sub_1d(ji)     = sfx_sub_1d(ji) - rhoi * a_i_1d(ji) * zdum * s_i_1d(ji) * r1_rdtice  ! Salt flux >0
+            !                                                                                          clem: flux is sent to the ocean for simplicity
+            !                                                                                                but salt should remain in the ice except
+            !                                                                                                if all ice is melted. => must be corrected
+            hfx_sub_1d(ji)     = hfx_sub_1d(ji) + zdum * e_i_1d(ji,jk) * a_i_1d(ji) * r1_rdtice      ! Heat flux [W.m-2], < 0
+
+            wfx_ice_sub_1d(ji) = wfx_ice_sub_1d(ji) - rhoi * a_i_1d(ji) * zdum * r1_rdtice           ! Mass flux > 0
+
+            ! update remaining mass flux
+            zevap_rema(ji)  = zevap_rema(ji) + zdum * rhoi
+            
+            ! 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,jk) = 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
+            eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
+            h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
+         END DO
+      END DO
+      
+      ! update ice thickness
+      DO ji = 1, npti
+         h_i_1d(ji) =  MAX( 0._wp , h_i_1d(ji) + dh_i_sum(ji) + dh_i_itm(ji) + dh_i_sub(ji) )
+      END DO
+
+      ! remaining "potential" evap is sent to ocean
+      DO ji = 1, npti
+         wfx_err_sub_1d(ji) = wfx_err_sub_1d(ji) - zevap_rema(ji) * a_i_1d(ji) * r1_rdtice  ! <=0 (net evap for the ocean in kg.m-2.s-1)
+      END DO
+
+
+      ! Ice Basal growth 
+      !------------------
+      ! Basal growth is driven by heat imbalance at the ice-ocean interface,
+      ! between the inner conductive flux  (qcn_ice_bot), from the open water heat flux 
+      ! (fhld) and the sensible ice-ocean flux (qsb_ice_bot). 
+      ! qcn_ice_bot is positive downwards. qsb_ice_bot 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_bog) depends upon new ice specific enthalpy (zEi),
+      ! which depends on forming ice salinity (s_i_new), which depends on dh/dt (dh_i_bog)
+      ! -> need for an iterative procedure, which converges quickly
+
+      num_iter_max = 1
+      IF( nn_icesal == 2 )   num_iter_max = 5  ! salinity varying in time
+      
+      DO ji = 1, npti
+         IF(  zf_tt(ji) < 0._wp  ) THEN
+            DO iter = 1, num_iter_max   ! iterations
+
+               ! 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_bog(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 )
+
+               s_i_new(ji)   = zswitch_sal * zfracs * sss_1d(ji) + ( 1. - zswitch_sal ) * s_i_1d(ji)  ! New ice salinity
+
+               ztmelts       = - rTmlt * s_i_new(ji)                                                  ! New ice melting point (C)
+
+               zt_i_new      = zswitch_sal * t_bo_1d(ji) + ( 1. - zswitch_sal) * t_i_1d(ji, nlay_i)
+               
+               zEi           = rcpi * ( zt_i_new - (ztmelts+rt0) ) &                                  ! Specific enthalpy of forming ice (J/kg, <0)
+                  &            - rLfus * ( 1.0 - ztmelts / ( zt_i_new - rt0 ) ) + rcp  * ztmelts
+
+               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_bog(ji)  = rdt_ice * MAX( 0._wp , zf_tt(ji) / ( zdE * rhoi ) )
+               
+            END DO
+            ! Contribution to Energy and Salt Fluxes                                    
+            zfmdt          = - rhoi * dh_i_bog(ji)                                                   ! Mass flux x time step (kg/m2, < 0)
+            
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice                           ! Heat flux to the ocean [W.m-2], >0
+            hfx_bog_1d(ji) = hfx_bog_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice                           ! Heat flux used in this process [W.m-2], <0
+            
+            sfx_bog_1d(ji) = sfx_bog_1d(ji) - rhoi * a_i_1d(ji) * dh_i_bog(ji) * s_i_new(ji) * r1_rdtice     ! Salt flux, <0
+
+            wfx_bog_1d(ji) = wfx_bog_1d(ji) - rhoi * a_i_1d(ji) * dh_i_bog(ji) * r1_rdtice                   ! Mass flux, <0
+
+            ! update heat content (J.m-2) and layer thickness
+            eh_i_old(ji,nlay_i+1) = eh_i_old(ji,nlay_i+1) + dh_i_bog(ji) * (-zEi * rhoi)
+            h_i_old (ji,nlay_i+1) = h_i_old (ji,nlay_i+1) + dh_i_bog(ji)
+
+         ENDIF
+
+      END DO
+
+      ! Ice Basal melt
+      !---------------
+      zdeltah(1:npti,:) = 0._wp ! important
+      DO jk = nlay_i, 1, -1
+         DO ji = 1, npti
+            IF(  zf_tt(ji)  >  0._wp  .AND. jk > icount(ji,jk) ) THEN   ! do not calculate where layer has already disappeared by surface melting 
+
+               ztmelts = - rTmlt * sz_i_1d(ji,jk)  ! Melting point of layer jk (C)
+
+               IF( t_i_1d(ji,jk) >= (ztmelts+rt0) ) THEN   !-- Internal melting
+
+                  zEi               = - e_i_1d(ji,jk) * r1_rhoi     ! Specific enthalpy of melting ice (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_itm (ji)     = dh_i_itm(ji) + zdeltah(ji,jk)
+
+                  zfmdt             = - zdeltah(ji,jk) * rhoi      ! Mass flux x time step > 0
+
+                  hfx_res_1d(ji) = hfx_res_1d(ji) + zfmdt * a_i_1d(ji) * zEi * r1_rdtice                           ! Heat flux to the ocean [W.m-2], <0
+                  !                                                                                                  ice enthalpy zEi is "sent" to the ocean
+                  sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_rdtice    ! Salt flux
+                  !                                                                                                  using s_i_1d and not sz_i_1d(jk) is ok
+                  wfx_res_1d(ji) = wfx_res_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice                 ! Mass flux
+
+                  ! update heat content (J.m-2) and layer thickness
+                  eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
+                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
+
+               ELSE                                        !-- Basal melting
+
+                  zEi             = - e_i_1d(ji,jk) * r1_rhoi                                 ! Specific enthalpy of melting ice (J/kg, <0)
+                  zEw             = rcp * ztmelts                                             ! Specific enthalpy of meltwater (J/kg, <0)
+                  zdE             = zEi - zEw                                                 ! Specific enthalpy difference   (J/kg, <0)
+
+                  zfmdt           = - zq_bot(ji) / zdE                                        ! Mass flux x time step (kg/m2, >0)
+
+                  zdeltah(ji,jk)  = - zfmdt * r1_rhoi                                         ! Gross thickness change
+
+                  zdeltah(ji,jk)  = MIN( 0._wp , MAX( zdeltah(ji,jk), - zh_i(ji,jk) ) )       ! bound thickness change
+                  
+                  zq_bot(ji)      = MAX( 0._wp , zq_bot(ji) - zdeltah(ji,jk) * rhoi * zdE )   ! update available heat. MAX is necessary for roundup errors
+
+                  dh_i_bom(ji)    = dh_i_bom(ji) + zdeltah(ji,jk)                             ! Update basal melt
+
+                  zfmdt           = - zdeltah(ji,jk) * rhoi                                   ! Mass flux x time step > 0
+
+                  zQm             = zfmdt * zEw                                               ! Heat exchanged with ocean
+
+                  hfx_thd_1d(ji)  = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice                           ! Heat flux to the ocean [W.m-2], <0  
+                  hfx_bom_1d(ji)  = hfx_bom_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice                           ! Heat used in this process [W.m-2], >0  
+
+                  sfx_bom_1d(ji)  = sfx_bom_1d(ji) - rhoi *  a_i_1d(ji) * zdeltah(ji,jk) * s_i_1d(ji) * r1_rdtice   ! Salt flux
+                  !                                                                                                   using s_i_1d and not sz_i_1d(jk) is ok
+                  
+                  wfx_bom_1d(ji)  = wfx_bom_1d(ji) - rhoi * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice                 ! Mass flux
+
+                  ! update heat content (J.m-2) and layer thickness
+                  eh_i_old(ji,jk) = eh_i_old(ji,jk) + zdeltah(ji,jk) * e_i_1d(ji,jk)
+                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
+               ENDIF
+           
+            ENDIF
+         END DO
+      END DO
+
+      ! Update temperature, energy
+      ! --------------------------
+      DO ji = 1, npti
+         h_i_1d(ji) = MAX( 0._wp , h_i_1d(ji) + dh_i_bog(ji) + dh_i_bom(ji) )
+      END DO  
+
+      ! If heat still available then melt more snow
+      !-------------------------------------------
+      zdeltah(1:npti,:) = 0._wp ! important
+      DO ji = 1, npti
+         zq_rema (ji)   = zq_top(ji) + zq_bot(ji) 
+         rswitch        = 1._wp - MAX( 0._wp, SIGN( 1._wp, - h_s_1d(ji) ) )   ! =1 if snow
+         rswitch        = rswitch * MAX( 0._wp, SIGN( 1._wp, e_s_1d(ji,1) - epsi20 ) )
+         zdeltah (ji,1) = - rswitch * zq_rema(ji) / MAX( e_s_1d(ji,1), epsi20 )
+         zdeltah (ji,1) = MIN( 0._wp , MAX( zdeltah(ji,1) , - h_s_1d(ji) ) ) ! bound melting
+         dh_s_tot(ji)   = dh_s_tot(ji) + zdeltah(ji,1)
+         h_s_1d  (ji)   = h_s_1d  (ji) + zdeltah(ji,1)
+        
+         zq_rema(ji)        = zq_rema(ji) + zdeltah(ji,1) * e_s_1d(ji,1)                               ! update available heat (J.m-2)
+         hfx_snw_1d(ji)     = hfx_snw_1d(ji) - zdeltah(ji,1) * a_i_1d(ji) * e_s_1d(ji,1) * r1_rdtice   ! Heat used to melt snow, W.m-2 (>0)
+         wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) - rhos * a_i_1d(ji) * zdeltah(ji,1) * r1_rdtice       ! Mass flux
+         dh_s_mlt(ji)       = dh_s_mlt(ji) + zdeltah(ji,1)
+         !    
+         ! Remaining heat flux (W.m-2) is sent to the ocean heat budget
+         !!!hfx_res_1d(ji) = hfx_res_1d(ji) + ( zq_rema(ji) * a_i_1d(ji) ) * r1_rdtice
+
+         IF( ln_icectl .AND. zq_rema(ji) < 0. .AND. lwp ) WRITE(numout,*) 'ALERTE zq_rema <0 = ', zq_rema(ji)
+      END DO
+
+      !
+      ! Snow-Ice formation
+      ! ------------------
+      ! When snow load excesses Archimede's limit, snow-ice interface goes down under sea-level, 
+      ! flooding of seawater transforms snow into ice dh_snowice is positive for the ice
+      z1_rho = 1._wp / ( rhos+rau0-rhoi )
+      DO ji = 1, npti
+         !
+         dh_snowice(ji) = MAX(  0._wp , ( rhos * h_s_1d(ji) + (rhoi-rau0) * h_i_1d(ji) ) * z1_rho )
+
+         h_i_1d(ji)    = h_i_1d(ji) + dh_snowice(ji)
+         h_s_1d(ji)    = h_s_1d(ji) - dh_snowice(ji)
+
+         ! Contribution to energy flux to the ocean [J/m2], >0 (if sst<0)
+         zfmdt          = ( rhos - rhoi ) * dh_snowice(ji)    ! <0
+         zEw            = rcp * sst_1d(ji)
+         zQm            = zfmdt * zEw 
+         
+         hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice ! Heat flux
+
+         sfx_sni_1d(ji) = sfx_sni_1d(ji) + sss_1d(ji) * a_i_1d(ji) * zfmdt * r1_rdtice ! Salt flux
+
+         ! Case constant salinity in time: virtual salt flux to keep salinity constant
+         IF( nn_icesal /= 2 )  THEN
+            sfx_bri_1d(ji) = sfx_bri_1d(ji) - sss_1d (ji) * a_i_1d(ji) * zfmdt                  * r1_rdtice  & ! put back sss_m     into the ocean
+               &                            - s_i_1d(ji)  * a_i_1d(ji) * dh_snowice(ji) * rhoi * r1_rdtice     ! and get  rn_icesal from the ocean 
+         ENDIF
+
+         ! 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) * rhoi * r1_rdtice
+         wfx_snw_sni_1d(ji) = wfx_snw_sni_1d(ji) + a_i_1d(ji) * dh_snowice(ji) * rhos * r1_rdtice
+
+         ! update heat content (J.m-2) and layer thickness
+         eh_i_old(ji,0) = eh_i_old(ji,0) + dh_snowice(ji) * e_s_1d(ji,1) + zfmdt * zEw
+         h_i_old (ji,0) = h_i_old (ji,0) + dh_snowice(ji)
+         
+      END DO
+
+      !
+      ! Update temperature, energy
+      ! --------------------------
+      DO ji = 1, npti
+         rswitch     = 1._wp - MAX( 0._wp , SIGN( 1._wp , - h_i_1d(ji) ) ) 
+         t_su_1d(ji) = rswitch * t_su_1d(ji) + ( 1._wp - rswitch ) * rt0
+      END DO
+
+      DO jk = 1, nlay_s
+         DO ji = 1,npti
+            ! where there is no ice or no snow
+            rswitch = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, - h_s_1d(ji) ) ) ) * ( 1._wp - MAX( 0._wp, SIGN(1._wp, - h_i_1d(ji) ) ) )
+            ! mass & energy loss to the ocean
+            hfx_res_1d(ji) = hfx_res_1d(ji) + ( 1._wp - rswitch ) * &
+               &                              ( e_s_1d(ji,jk) * h_s_1d(ji) * r1_nlay_s * a_i_1d(ji) * r1_rdtice )  ! heat flux to the ocean [W.m-2], < 0
+            wfx_res_1d(ji) = wfx_res_1d(ji) + ( 1._wp - rswitch ) * &
+               &                              ( rhos          * h_s_1d(ji) * r1_nlay_s * a_i_1d(ji) * r1_rdtice )  ! mass flux
+            ! update energy (mass is updated in the next loop)
+            e_s_1d(ji,jk) = rswitch * e_s_1d(ji,jk)
+            ! recalculate t_s_1d from e_s_1d
+            t_s_1d(ji,jk) = rt0 + rswitch * ( - e_s_1d(ji,jk) * r1_rhos * r1_rcpi + rLfus * r1_rcpi )
+         END DO
+      END DO
+
+      ! --- ensure that a_i = 0 & h_s = 0 where h_i = 0 ---
+      WHERE( h_i_1d(1:npti) == 0._wp )   
+         a_i_1d(1:npti) = 0._wp
+         h_s_1d(1:npti) = 0._wp
+      END WHERE
+      !
+   END SUBROUTINE ice_thd_dh
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_dh
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_do.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_do.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_do.F90	(revision 14097)
@@ -0,0 +1,478 @@
+MODULE icethd_do
+   !!======================================================================
+   !!                       ***  MODULE icethd_do   ***
+   !!   sea-ice: sea ice growth in the leads (open water)  
+   !!======================================================================
+   !! History :       !  2005-12  (M. Vancoppenolle) Original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_do        : ice growth in open water (=lateral accretion of ice)
+   !!   ice_thd_do_init   : initialization
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE sbc_oce , ONLY : sss_m
+   USE sbc_ice , ONLY : utau_ice, vtau_ice
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE ice            ! sea-ice: variables
+   USE icetab         ! sea-ice: 2D <==> 1D
+   USE icectl         ! sea-ice: conservation
+   USE icethd_ent     ! sea-ice: thermodynamics, enthalpy
+   USE icevar         ! sea-ice: operations
+   USE icethd_sal     ! sea-ice: salinity profiles
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_do        ! called by ice_thd
+   PUBLIC   ice_thd_do_init   ! called by ice_stp
+
+   !                          !!** namelist (namthd_do) **
+   REAL(wp) ::   rn_hinew      ! thickness for new ice formation (m)
+   LOGICAL  ::   ln_frazil     ! use of frazil ice collection as function of wind (T) or not (F)
+   REAL(wp) ::   rn_maxfraz    ! maximum portion of frazil ice collecting at the ice bottom
+   REAL(wp) ::   rn_vfraz      ! threshold drift speed for collection of bottom frazil ice
+   REAL(wp) ::   rn_Cfraz      ! squeezing coefficient for collection of bottom frazil ice
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_do
+      !!-------------------------------------------------------------------
+      !!               ***   ROUTINE ice_thd_do  ***
+      !!  
+      !! ** Purpose : Computation of the evolution of the ice thickness and 
+      !!              concentration as a function of the heat balance in the leads
+      !!       
+      !! ** Method  : Ice is formed in the open water when ocean looses heat
+      !!              (heat budget of open water is negative) following
+      !!
+      !!       (dA/dt)acc = F[ (1-A)/(1-a) ] * [ Bl / (Li*h0) ]
+      !!          where - h0 is the thickness of ice created in the lead
+      !!                - a is a minimum fraction for leads
+      !!                - F is a monotonic non-increasing function defined as:
+      !!                  F(X)=( 1 - X**exld )**(1.0/exld)
+      !!                - exld is the exponent closure rate (=2 default val.)
+      !! 
+      !! ** Action : - Adjustment of snow and ice thicknesses and heat
+      !!                content in brine pockets
+      !!             - Updating ice internal temperature
+      !!             - Computation of variation of ice volume and mass
+      !!             - Computation of a_i after lateral accretion and 
+      !!               update h_s_1d, h_i_1d      
+      !!------------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      INTEGER  ::   iter             !   -       -
+      REAL(wp) ::   ztmelts, zfrazb, zweight, zde                               ! local scalars
+      REAL(wp) ::   zgamafr, zvfrx, zvgx, ztaux, ztwogp, zf                     !   -      -
+      REAL(wp) ::   ztenagm, zvfry, zvgy, ztauy, zvrel2, zfp, zsqcd , zhicrit   !   -      -
+      !
+      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 , DIMENSION(jpij) ::   jcat        ! indexes of categories where new ice grows
+      REAL(wp), DIMENSION(jpij) ::   zswinew     ! switch for new ice or not
+      !
+      REAL(wp), DIMENSION(jpij) ::   zv_newice   ! volume of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   za_newice   ! fractional area of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   zh_newice   ! thickness of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   ze_newice   ! heat content of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   zs_newice   ! salinity of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   zo_newice   ! age of accreted ice
+      REAL(wp), DIMENSION(jpij) ::   zdv_res     ! residual volume in case of excessive heat budget
+      REAL(wp), DIMENSION(jpij) ::   zda_res     ! residual area in case of excessive heat budget
+      REAL(wp), DIMENSION(jpij) ::   zv_frazb    ! accretion of frazil ice at the ice bottom
+      REAL(wp), DIMENSION(jpij) ::   zvrel_1d    ! relative ice / frazil velocity (1D vector)
+      !
+      REAL(wp), DIMENSION(jpij,jpl) ::   zv_b    ! old volume of ice in category jl
+      REAL(wp), DIMENSION(jpij,jpl) ::   za_b    ! old area of ice in category jl
+      !
+      REAL(wp), DIMENSION(jpij,nlay_i,jpl) ::   ze_i_2d !: 1-D version of e_i
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   zvrel    ! relative ice / frazil velocity
+      !
+      REAL(wp) :: zcai = 1.4e-3_wp               ! ice-air drag (clem: should be dependent on coupling/forcing used)
+      !!-----------------------------------------------------------------------!
+
+      IF( ln_icediachk )   CALL ice_cons_hsm( 0, 'icethd_do', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft )
+      IF( ln_icediachk )   CALL ice_cons2D  ( 0, 'icethd_do',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft )
+
+      at_i(:,:) = SUM( a_i, dim=3 )
+      !------------------------------------------------------------------------------!
+      ! 1) Collection thickness of ice formed in leads and polynyas
+      !------------------------------------------------------------------------------!    
+      ! ht_i_new is the thickness of new ice formed in open water
+      ! ht_i_new can be either prescribed (ln_frazil=F) or computed (ln_frazil=T)
+      ! Frazil ice forms in open water, is transported by wind
+      ! accumulates at the edge of the consolidated ice edge
+      ! where it forms aggregates of a specific thickness called
+      ! collection thickness.
+
+      zvrel(:,:) = 0._wp
+
+      ! Default new ice thickness
+      WHERE( qlead(:,:) < 0._wp ) ! cooling
+         ht_i_new(:,:) = rn_hinew
+      ELSEWHERE
+         ht_i_new(:,:) = 0._wp
+      END WHERE
+
+      IF( ln_frazil ) THEN
+         !
+         ht_i_new(:,:) = 0._wp
+         !
+         ! Physical constants
+         zhicrit = 0.04                                          ! frazil ice thickness
+         ztwogp  = 2. * rau0 / ( grav * 0.3 * ( rau0 - rhoi ) )  ! reduced grav
+         zsqcd   = 1.0 / SQRT( 1.3 * zcai )                      ! 1/SQRT(airdensity*drag)
+         zgamafr = 0.03
+         !
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF ( qlead(ji,jj) < 0._wp ) THEN ! cooling
+                  ! -- Wind stress -- !
+                  ztaux         = ( utau_ice(ji-1,jj  ) * umask(ji-1,jj  ,1)   &
+                     &          +   utau_ice(ji  ,jj  ) * umask(ji  ,jj  ,1) ) * 0.5_wp
+                  ztauy         = ( vtau_ice(ji  ,jj-1) * vmask(ji  ,jj-1,1)   &
+                     &          +   vtau_ice(ji  ,jj  ) * vmask(ji  ,jj  ,1) ) * 0.5_wp
+                  ! Square root of wind stress
+                  ztenagm       =  SQRT( SQRT( ztaux * ztaux + ztauy * ztauy ) )
+
+                  ! -- Frazil ice velocity -- !
+                  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 )
+
+                  ! -- Pack ice velocity -- !
+                  zvgx    = ( u_ice(ji-1,jj  ) * umask(ji-1,jj  ,1)  + u_ice(ji,jj) * umask(ji,jj,1) ) * 0.5_wp
+                  zvgy    = ( v_ice(ji  ,jj-1) * vmask(ji  ,jj-1,1)  + v_ice(ji,jj) * vmask(ji,jj,1) ) * 0.5_wp
+
+                  ! -- Relative frazil/pack ice velocity -- !
+                  rswitch      = MAX( 0._wp, SIGN( 1._wp , at_i(ji,jj) - epsi10 ) )
+                  zvrel2       = MAX(  ( zvfrx - zvgx ) * ( zvfrx - zvgx )   &
+                     &               + ( zvfry - zvgy ) * ( zvfry - zvgy ) , 0.15 * 0.15 ) * rswitch
+                  zvrel(ji,jj) = SQRT( zvrel2 )
+
+                  ! -- new ice thickness (iterative loop) -- !
+                  ht_i_new(ji,jj) = zhicrit +   ( zhicrit + 0.1 )    &
+                     &                   / ( ( zhicrit + 0.1 ) * ( zhicrit + 0.1 ) -  zhicrit * zhicrit ) * ztwogp * zvrel2
+
+                  iter = 1
+                  DO WHILE ( iter < 20 ) 
+                     zf  = ( ht_i_new(ji,jj) - zhicrit ) * ( ht_i_new(ji,jj) * ht_i_new(ji,jj) - zhicrit * zhicrit ) -   &
+                        &    ht_i_new(ji,jj) * zhicrit * ztwogp * zvrel2
+                     zfp = ( ht_i_new(ji,jj) - zhicrit ) * ( 3.0 * ht_i_new(ji,jj) + zhicrit ) - zhicrit * ztwogp * zvrel2
+
+                     ht_i_new(ji,jj) = ht_i_new(ji,jj) - zf / MAX( zfp, epsi20 )
+                     iter = iter + 1
+                  END DO
+                  !
+                  ! bound ht_i_new (though I don't see why it should be necessary)
+                  ht_i_new(ji,jj) = MAX( 0.01_wp, MIN( ht_i_new(ji,jj), hi_max(jpl) ) )
+                  !
+               ENDIF
+               !
+            END DO 
+         END DO 
+         ! 
+         CALL lbc_lnk_multi( 'icethd_do', zvrel, 'T', 1., ht_i_new, 'T', 1.  )
+
+      ENDIF
+
+      !------------------------------------------------------------------------------!
+      ! 2) Compute thickness, salinity, enthalpy, age, area and volume of new ice
+      !------------------------------------------------------------------------------!
+      ! it occurs if cooling
+
+      ! Identify grid points where new ice forms
+      npti = 0   ;   nptidx(:) = 0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF ( qlead(ji,jj) < 0._wp ) THEN
+               npti = npti + 1
+               nptidx( npti ) = (jj - 1) * jpi + ji
+            ENDIF
+         END DO
+      END DO
+
+      ! Move from 2-D to 1-D vectors
+      IF ( npti > 0 ) THEN
+
+         CALL tab_2d_1d( npti, nptidx(1:npti), at_i_1d(1:npti)      , at_i        )
+         CALL tab_3d_2d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i (:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), v_i_2d (1:npti,1:jpl), v_i (:,:,:) )
+         CALL tab_3d_2d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i(:,:,:) )
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               CALL tab_2d_1d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+            END DO
+         END DO
+         CALL tab_2d_1d( npti, nptidx(1:npti), qlead_1d  (1:npti) , qlead      )
+         CALL tab_2d_1d( npti, nptidx(1:npti), t_bo_1d   (1:npti) , t_bo       )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sfx_opw_1d(1:npti) , sfx_opw    )
+         CALL tab_2d_1d( npti, nptidx(1:npti), wfx_opw_1d(1:npti) , wfx_opw    )
+         CALL tab_2d_1d( npti, nptidx(1:npti), zh_newice (1:npti) , ht_i_new   )
+         CALL tab_2d_1d( npti, nptidx(1:npti), zvrel_1d  (1:npti) , zvrel      )
+
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_thd_1d(1:npti) , hfx_thd    )
+         CALL tab_2d_1d( npti, nptidx(1:npti), hfx_opw_1d(1:npti) , hfx_opw    )
+         CALL tab_2d_1d( npti, nptidx(1:npti), rn_amax_1d(1:npti) , rn_amax_2d )
+         CALL tab_2d_1d( npti, nptidx(1:npti), sss_1d    (1:npti) , sss_m      )
+
+         ! Convert units for ice internal energy
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i               
+               WHERE( v_i_2d(1:npti,jl) > 0._wp )
+                  ze_i_2d(1:npti,jk,jl) = ze_i_2d(1:npti,jk,jl) / v_i_2d(1:npti,jl) * REAL( nlay_i )
+               ELSEWHERE
+                  ze_i_2d(1:npti,jk,jl) = 0._wp
+               END WHERE
+            END DO
+         END DO
+
+         ! Keep old ice areas and volume in memory
+         zv_b(1:npti,:) = v_i_2d(1:npti,:) 
+         za_b(1:npti,:) = a_i_2d(1:npti,:)
+
+         ! --- Salinity of new ice --- ! 
+         SELECT CASE ( nn_icesal )
+         CASE ( 1 )                    ! Sice = constant 
+            zs_newice(1:npti) = rn_icesal
+         CASE ( 2 )                    ! Sice = F(z,t) [Vancoppenolle et al (2005)]
+            DO ji = 1, npti
+               zs_newice(ji) = MIN(  4.606 + 0.91 / zh_newice(ji) , rn_simax , 0.5 * sss_1d(ji) )
+            END DO
+         CASE ( 3 )                    ! Sice = F(z) [multiyear ice]
+            zs_newice(1:npti) =   2.3
+         END SELECT
+
+         ! --- Heat content of new ice --- !
+         ! We assume that new ice is formed at the seawater freezing point
+         DO ji = 1, npti
+            ztmelts       = - rTmlt * zs_newice(ji)                  ! Melting point (C)
+            ze_newice(ji) =   rhoi * (  rcpi  * ( ztmelts - ( t_bo_1d(ji) - rt0 ) )                     &
+               &                      + rLfus * ( 1.0 - ztmelts / MIN( t_bo_1d(ji) - rt0, -epsi10 ) )   &
+               &                      - rcp   *         ztmelts )
+         END DO
+
+         ! --- Age of new ice --- !
+         zo_newice(1:npti) = 0._wp
+
+         ! --- Volume of new ice --- !
+         DO ji = 1, npti
+
+            zEi           = - ze_newice(ji) * r1_rhoi              ! 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 (icethd) because we suppose we are at the freezing point   
+            zv_newice(ji) = - zfmdt * r1_rhoi
+
+            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) * rhoi * r1_rdtice
+            ! salt flux
+            sfx_opw_1d(ji) = sfx_opw_1d(ji) - zv_newice(ji) * rhoi * zs_newice(ji) * r1_rdtice
+         END DO
+         
+         zv_frazb(1:npti) = 0._wp
+         IF( ln_frazil ) THEN
+            ! A fraction zfrazb of frazil ice is accreted at the ice bottom
+            DO ji = 1, npti
+               rswitch       = 1._wp - MAX( 0._wp, SIGN( 1._wp , - at_i_1d(ji) ) )
+               zfrazb        = rswitch * ( TANH( rn_Cfraz * ( zvrel_1d(ji) - rn_vfraz ) ) + 1.0 ) * 0.5 * rn_maxfraz
+               zv_frazb(ji)  =         zfrazb   * zv_newice(ji)
+               zv_newice(ji) = ( 1.0 - zfrazb ) * zv_newice(ji)
+            END DO
+         END IF
+         
+         ! --- Area of new ice --- !
+         DO ji = 1, npti
+            za_newice(ji) = zv_newice(ji) / zh_newice(ji)
+         END DO
+
+         !------------------------------------------------------------------------------!
+         ! 3) Redistribute new ice area and volume into ice categories                  !
+         !------------------------------------------------------------------------------!
+
+         ! --- lateral ice growth --- !
+         ! If lateral ice growth gives an ice concentration > amax, then
+         ! we keep the excessive volume in memory and attribute it later to bottom accretion
+         DO ji = 1, npti
+            IF ( za_newice(ji) >  MAX( 0._wp, rn_amax_1d(ji) - at_i_1d(ji) ) ) THEN ! max is for roundoff error
+               zda_res(ji)   = za_newice(ji) - MAX( 0._wp, rn_amax_1d(ji) - at_i_1d(ji) )
+               zdv_res(ji)   = zda_res  (ji) * zh_newice(ji) 
+               za_newice(ji) = MAX( 0._wp, za_newice(ji) - zda_res  (ji) )
+               zv_newice(ji) = MAX( 0._wp, zv_newice(ji) - zdv_res  (ji) )
+            ELSE
+               zda_res(ji) = 0._wp
+               zdv_res(ji) = 0._wp
+            ENDIF
+         END DO
+
+         ! find which category to fill
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               IF( zh_newice(ji) > hi_max(jl-1) .AND. zh_newice(ji) <= hi_max(jl) ) THEN
+                  a_i_2d(ji,jl) = a_i_2d(ji,jl) + za_newice(ji)
+                  v_i_2d(ji,jl) = v_i_2d(ji,jl) + zv_newice(ji)
+                  jcat(ji) = jl
+               ENDIF
+            END DO
+         END DO
+         at_i_1d(1:npti) = SUM( a_i_2d(1:npti,:), dim=2 )
+
+         ! Heat content
+         DO ji = 1, npti
+            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, npti
+               jl = jcat(ji)
+               rswitch = MAX( 0._wp, SIGN( 1._wp , v_i_2d(ji,jl) - epsi20 ) )
+               ze_i_2d(ji,jk,jl) = zswinew(ji)   *   ze_newice(ji) +                                                    &
+                  &        ( 1.0 - zswinew(ji) ) * ( ze_newice(ji) * zv_newice(ji) + ze_i_2d(ji,jk,jl) * zv_b(ji,jl) )  &
+                  &        * rswitch / MAX( v_i_2d(ji,jl), epsi20 )
+            END DO
+         END DO
+
+         ! --- bottom ice growth + ice enthalpy remapping --- !
+         DO jl = 1, jpl
+
+            ! for remapping
+            h_i_old (1:npti,0:nlay_i+1) = 0._wp
+            eh_i_old(1:npti,0:nlay_i+1) = 0._wp
+            DO jk = 1, nlay_i
+               DO ji = 1, npti
+                  h_i_old (ji,jk) = v_i_2d(ji,jl) * r1_nlay_i
+                  eh_i_old(ji,jk) = ze_i_2d(ji,jk,jl) * h_i_old(ji,jk)
+               END DO
+            END DO
+
+            ! new volumes including lateral/bottom accretion + residual
+            DO ji = 1, npti
+               rswitch        = MAX( 0._wp, SIGN( 1._wp , at_i_1d(ji) - epsi20 ) )
+               zv_newfra     = rswitch * ( zdv_res(ji) + zv_frazb(ji) ) * a_i_2d(ji,jl) / MAX( at_i_1d(ji) , epsi20 )
+               a_i_2d(ji,jl) = rswitch * a_i_2d(ji,jl)               
+               v_i_2d(ji,jl) = v_i_2d(ji,jl) + zv_newfra
+               ! for remapping
+               h_i_old (ji,nlay_i+1) = zv_newfra
+               eh_i_old(ji,nlay_i+1) = ze_newice(ji) * zv_newfra
+            END DO
+            ! --- Ice enthalpy remapping --- !
+            CALL ice_thd_ent( ze_i_2d(1:npti,:,jl) ) 
+         END DO
+
+         ! --- Update salinity --- !
+         DO jl = 1, jpl
+            DO ji = 1, npti
+               sv_i_2d(ji,jl) = sv_i_2d(ji,jl) + zs_newice(ji) * ( v_i_2d(ji,jl) - zv_b(ji,jl) )
+            END DO
+         END DO
+
+         ! Change units for e_i
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               ze_i_2d(1:npti,jk,jl) = ze_i_2d(1:npti,jk,jl) * v_i_2d(1:npti,jl) * r1_nlay_i 
+            END DO
+         END DO
+
+         ! Move 2D vectors to 1D vectors 
+         CALL tab_2d_3d( npti, nptidx(1:npti), a_i_2d (1:npti,1:jpl), a_i (:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), v_i_2d (1:npti,1:jpl), v_i (:,:,:) )
+         CALL tab_2d_3d( npti, nptidx(1:npti), sv_i_2d(1:npti,1:jpl), sv_i(:,:,:) )
+          DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               CALL tab_1d_2d( npti, nptidx(1:npti), ze_i_2d(1:npti,jk,jl), e_i(:,:,jk,jl) )
+            END DO
+         END DO
+         CALL tab_1d_2d( npti, nptidx(1:npti), sfx_opw_1d(1:npti), sfx_opw )
+         CALL tab_1d_2d( npti, nptidx(1:npti), wfx_opw_1d(1:npti), wfx_opw )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_thd_1d(1:npti), hfx_thd )
+         CALL tab_1d_2d( npti, nptidx(1:npti), hfx_opw_1d(1:npti), hfx_opw )
+         !
+      ENDIF ! npti > 0
+      !
+      IF( ln_icediachk )   CALL ice_cons_hsm(1, 'icethd_do', rdiag_v, rdiag_s, rdiag_t, rdiag_fv, rdiag_fs, rdiag_ft)
+      IF( ln_icediachk )   CALL ice_cons2D  (1, 'icethd_do',  diag_v,  diag_s,  diag_t,  diag_fv,  diag_fs,  diag_ft)
+      !
+   END SUBROUTINE ice_thd_do
+
+
+   SUBROUTINE ice_thd_do_init
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_do_init *** 
+      !!                 
+      !! ** Purpose :   Physical constants and parameters associated with
+      !!                ice growth in the leads
+      !!
+      !! ** Method  :   Read the namthd_do namelist and check the parameters
+      !!                called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd_do
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer 
+      !!
+      NAMELIST/namthd_do/ rn_hinew, ln_frazil, rn_maxfraz, rn_vfraz, rn_Cfraz
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd_do in reference namelist : Ice thermodynamics
+      READ  ( numnam_ice_ref, namthd_do, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd_do in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd_do in configuration namelist : Ice thermodynamics
+      READ  ( numnam_ice_cfg, namthd_do, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd_do in configuration namelist' )
+      IF(lwm) WRITE( numoni, namthd_do )
+      !
+      IF(lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_do_init: Ice growth in open water'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namthd_do:'
+         WRITE(numout,*) '      ice thickness for lateral accretion                       rn_hinew   = ', rn_hinew
+         WRITE(numout,*) '      Frazil ice thickness as a function of wind or not         ln_frazil  = ', ln_frazil
+         WRITE(numout,*) '      Maximum proportion of frazil ice collecting at bottom     rn_maxfraz = ', rn_maxfraz
+         WRITE(numout,*) '      Threshold relative drift speed for collection of frazil   rn_vfraz   = ', rn_vfraz
+         WRITE(numout,*) '      Squeezing coefficient for collection of frazil            rn_Cfraz   = ', rn_Cfraz
+      ENDIF
+      !
+      IF ( rn_hinew < rn_himin )   CALL ctl_stop( 'ice_thd_do_init : rn_hinew should be >= rn_himin' )
+      !
+   END SUBROUTINE ice_thd_do_init
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_do
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_ent.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_ent.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_ent.F90	(revision 14097)
@@ -0,0 +1,144 @@
+MODULE icethd_ent
+   !!======================================================================
+   !!                       ***  MODULE icethd_ent   ***
+   !!   sea-ice: redistribution of enthalpy in the ice on the new vertical grid
+   !!                       after vertical growth/melt
+   !!======================================================================
+   !! History :       !  2003-05  (M. Vancoppenolle) Original code in 1D
+   !!                 !  2005-07  (M. Vancoppenolle) 3D version 
+   !!            3.6  !  2014-05  (C. Rousset)       New version
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_ent   : ice redistribution of enthalpy
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! domain variables
+   USE domain         !
+   USE phycst         ! physical constants
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   !
+   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)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_ent         ! called by icethd and icethd_do
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+ 
+   SUBROUTINE ice_thd_ent( qnew )
+      !!-------------------------------------------------------------------
+      !!               ***   ROUTINE ice_thd_ent  ***
+      !!
+      !! ** Purpose :
+      !!           This routine computes new vertical grids in the ice, 
+      !!           and consistently redistributes temperatures. 
+      !!           Redistribution is made so as to ensure to energy conservation
+      !!
+      !!
+      !! ** Method  : linear conservative remapping
+      !!           
+      !! ** 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
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   qnew             ! new enthlapies (J.m-3, remapped)
+      !
+      INTEGER  :: ji         !  dummy loop indices
+      INTEGER  :: jk0, jk1   !  old/new layer indices
+      !
+      REAL(wp), DIMENSION(jpij,0:nlay_i+2) ::   zeh_cum0, zh_cum0   ! old cumulative enthlapies and layers interfaces
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zeh_cum1, zh_cum1   ! new cumulative enthlapies and layers interfaces
+      REAL(wp), DIMENSION(jpij)            ::   zhnew               ! new layers thicknesses
+      !!-------------------------------------------------------------------
+
+      !--------------------------------------------------------------------------
+      !  1) Cumulative integral of old enthalpy * thickness and layers interfaces
+      !--------------------------------------------------------------------------
+      zeh_cum0(1:npti,0) = 0._wp 
+      zh_cum0 (1:npti,0) = 0._wp
+      DO jk0 = 1, nlay_i+2
+         DO ji = 1, npti
+            zeh_cum0(ji,jk0) = zeh_cum0(ji,jk0-1) + eh_i_old(ji,jk0-1)
+            zh_cum0 (ji,jk0) = zh_cum0 (ji,jk0-1) + h_i_old (ji,jk0-1)
+         END DO
+      END DO
+
+      !------------------------------------
+      !  2) Interpolation on the new layers
+      !------------------------------------
+      ! new layer thickesses
+      DO ji = 1, npti
+         zhnew(ji) = SUM( h_i_old(ji,0:nlay_i+1) ) * r1_nlay_i  
+      END DO
+
+      ! new layers interfaces
+      zh_cum1(1:npti,0) = 0._wp
+      DO jk1 = 1, nlay_i
+         DO ji = 1, npti
+            zh_cum1(ji,jk1) = zh_cum1(ji,jk1-1) + zhnew(ji)
+         END DO
+      END DO
+
+      zeh_cum1(1:npti,0:nlay_i) = 0._wp 
+      ! new cumulative q*h => linear interpolation
+      DO jk0 = 1, nlay_i+2
+         DO jk1 = 1, nlay_i-1
+            DO ji = 1, npti
+               IF( zh_cum1(ji,jk1) <= zh_cum0(ji,jk0) .AND. zh_cum1(ji,jk1) > zh_cum0(ji,jk0-1) ) THEN
+                  zeh_cum1(ji,jk1) = ( zeh_cum0(ji,jk0-1) * ( zh_cum0(ji,jk0) - zh_cum1(ji,jk1  ) ) +  &
+                     &                 zeh_cum0(ji,jk0  ) * ( zh_cum1(ji,jk1) - zh_cum0(ji,jk0-1) ) )  &
+                     &             / ( zh_cum0(ji,jk0) - zh_cum0(ji,jk0-1) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      ! to ensure that total heat content is strictly conserved, set:
+      zeh_cum1(1:npti,nlay_i) = zeh_cum0(1:npti,nlay_i+2) 
+
+      ! new enthalpies
+      DO jk1 = 1, nlay_i
+         DO ji = 1, npti
+            rswitch      = MAX( 0._wp , SIGN( 1._wp , zhnew(ji) - epsi20 ) ) 
+            qnew(ji,jk1) = rswitch * ( zeh_cum1(ji,jk1) - zeh_cum1(ji,jk1-1) ) / MAX( zhnew(ji), epsi20 )
+         END DO
+      END DO
+
+      ! --- diag error on heat remapping --- !
+      ! comment: if input h_i_old and eh_i_old are already multiplied by a_i (as in icethd_do), 
+      ! then we should not (* a_i) again but not important since this is just to check that remap error is ~0
+      !DO ji = 1, npti
+      !   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( eh_i_old(ji,0:nlay_i+1) ) ) 
+      !END DO
+      
+   END SUBROUTINE ice_thd_ent
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_ent
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_pnd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_pnd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_pnd.F90	(revision 14097)
@@ -0,0 +1,373 @@
+MODULE icethd_pnd 
+   !!======================================================================
+   !!                     ***  MODULE  icethd_pnd   ***
+   !!   sea-ice: Melt ponds on top of sea ice
+   !!======================================================================
+   !! history :       !  2012     (O. Lecomte)       Adaptation from Flocco and Turner
+   !!                 !  2017     (M. Vancoppenolle, O. Lecomte, C. Rousset) Implementation
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3' :                                     SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_pnd_init : some initialization and namelist read
+   !!   ice_thd_pnd      : main calling routine
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icetab         ! sea-ice: 1D <==> 2D transformation
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_pnd_init    ! routine called by icestp.F90
+   PUBLIC   ice_thd_pnd         ! routine called by icestp.F90
+
+   INTEGER ::              nice_pnd    ! choice of the type of pond scheme
+   !                                   ! associated indices:
+   INTEGER, PARAMETER ::   np_pndNO  = 0   ! No pond scheme
+   INTEGER, PARAMETER ::   np_pndCST = 1   ! Constant ice pond scheme
+   INTEGER, PARAMETER ::   np_pndLEV = 2   ! Level ice pond scheme
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_pnd
+      !!-------------------------------------------------------------------
+      !!               ***  ROUTINE ice_thd_pnd   ***
+      !!               
+      !! ** Purpose :   change melt pond fraction and thickness
+      !!                
+      !!-------------------------------------------------------------------
+      !
+      SELECT CASE ( nice_pnd )
+      !
+      CASE (np_pndCST)   ;   CALL pnd_CST    !==  Constant melt ponds  ==!
+         !
+      CASE (np_pndLEV)   ;   CALL pnd_LEV    !==  Level ice melt ponds  ==!
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_thd_pnd 
+
+
+   SUBROUTINE pnd_CST 
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE pnd_CST  ***
+      !!
+      !! ** Purpose :   Compute melt pond evolution
+      !!
+      !! ** Method  :   Melt pond fraction and thickness are prescribed 
+      !!                to non-zero values when t_su = 0C
+      !!
+      !! ** Tunable parameters : pond fraction (rn_apnd), pond depth (rn_hpnd)
+      !!                
+      !! ** Note   : Coupling with such melt ponds is only radiative
+      !!             Advection, ridging, rafting... are bypassed
+      !!
+      !! ** References : Bush, G.W., and Trump, D.J. (2017)
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji        ! loop indices
+      !!-------------------------------------------------------------------
+      DO ji = 1, npti
+         !
+         IF( a_i_1d(ji) > 0._wp .AND. t_su_1d(ji) >= rt0 ) THEN
+            h_ip_1d(ji)      = rn_hpnd    
+            a_ip_1d(ji)      = rn_apnd * a_i_1d(ji)
+            h_il_1d(ji)      = 0._wp    ! no pond lids whatsoever
+         ELSE
+            h_ip_1d(ji)      = 0._wp    
+            a_ip_1d(ji)      = 0._wp
+            h_il_1d(ji)      = 0._wp
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE pnd_CST
+
+
+   SUBROUTINE pnd_LEV
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE pnd_LEV  ***
+      !!
+      !! ** Purpose : Compute melt pond evolution
+      !!
+      !! ** Method  : A fraction of meltwater is accumulated in ponds and sent to ocean when surface is freezing
+      !!              We  work with volumes and then redistribute changes into thickness and concentration
+      !!              assuming linear relationship between the two. 
+      !!
+      !! ** Action  : - pond growth:      Vp = Vp + dVmelt                                          --- from Holland et al 2012 ---
+      !!                                     dVmelt = (1-r)/rhow * ( rhoi*dh_i + rhos*dh_s ) * a_i
+      !!                                        dh_i  = meltwater from ice surface melt
+      !!                                        dh_s  = meltwater from snow melt
+      !!                                        (1-r) = fraction of melt water that is not flushed
+      !!
+      !!              - limtations:       a_ip must not exceed (1-r)*a_i
+      !!                                  h_ip must not exceed 0.5*h_i
+      !!
+      !!              - pond shrinking:
+      !!                       if lids:   Vp = Vp -dH * a_ip
+      !!                                     dH = lid thickness change. Retrieved from this eq.:    --- from Flocco et al 2010 ---
+      !!
+      !!                                                                   rhoi * Lf * dH/dt = ki * MAX(Tp-Tsu,0) / H 
+      !!                                                                      H = lid thickness
+      !!                                                                      Lf = latent heat of fusion
+      !!                                                                      Tp = -2C
+      !!
+      !!                                                                And solved implicitely as:
+      !!                                                                   H(t+dt)**2 -H(t) * H(t+dt) -ki * (Tp-Tsu) * dt / (rhoi*Lf) = 0
+      !!
+      !!                    if no lids:   Vp = Vp * exp(0.01*MAX(Tp-Tsu,0)/Tp)                      --- from Holland et al 2012 ---
+      !!
+      !!              - Flushing:         w = -perm/visc * rho_oce * grav * Hp / Hi                 --- from Flocco et al 2007 ---
+      !!                                     perm = permability of sea-ice
+      !!                                     visc = water viscosity
+      !!                                     Hp   = height of top of the pond above sea-level
+      !!                                     Hi   = ice thickness thru which there is flushing
+      !!
+      !!              - Corrections:      remove melt ponds when lid thickness is 10 times the pond thickness
+      !!
+      !!              - pond thickness and area is retrieved from pond volume assuming a linear relationship between h_ip and a_ip:
+      !!                                  a_ip/a_i = a_ip_frac = h_ip / zaspect
+      !!
+      !! ** Tunable parameters : ln_pnd_lids, rn_apnd_max, rn_apnd_min
+      !! 
+      !! ** Note       :   mostly stolen from CICE
+      !!
+      !! ** References :   Flocco and Feltham (JGR, 2007)
+      !!                   Flocco et al       (JGR, 2010)
+      !!                   Holland et al      (J. Clim, 2012)
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(nlay_i) ::   ztmp           ! temporary array
+      !!
+      REAL(wp), PARAMETER ::   zaspect =  0.8_wp      ! pond aspect ratio
+      REAL(wp), PARAMETER ::   zTp     = -2._wp       ! reference temperature
+      REAL(wp), PARAMETER ::   zvisc   =  1.79e-3_wp  ! water viscosity
+      !!
+      REAL(wp) ::   zfr_mlt, zdv_mlt                  ! fraction and volume of available meltwater retained for melt ponding
+      REAL(wp) ::   zdv_frz, zdv_flush                ! Amount of melt pond that freezes, flushes
+      REAL(wp) ::   zhp                               ! heigh of top of pond lid wrt ssh
+      REAL(wp) ::   zv_ip_max                         ! max pond volume allowed
+      REAL(wp) ::   zdT                               ! zTp-t_su
+      REAL(wp) ::   zsbr                              ! Brine salinity
+      REAL(wp) ::   zperm                             ! permeability of sea ice
+      REAL(wp) ::   zfac, zdum                        ! temporary arrays
+      REAL(wp) ::   z1_rhow, z1_aspect, z1_Tp         ! inverse
+      !!
+      INTEGER  ::   ji, jk                            ! loop indices
+      !!-------------------------------------------------------------------
+      z1_rhow   = 1._wp / rhow 
+      z1_aspect = 1._wp / zaspect
+      z1_Tp     = 1._wp / zTp 
+
+      DO ji = 1, npti
+         !                                                            !----------------------------------------------------!
+         IF( h_i_1d(ji) < rn_himin .OR. a_i_1d(ji) < epsi10 ) THEN    ! Case ice thickness < rn_himin or tiny ice fraction !
+            !                                                         !----------------------------------------------------!
+            !--- Remove ponds on thin ice or tiny ice fractions
+            a_ip_1d(ji)      = 0._wp
+            h_ip_1d(ji)      = 0._wp
+            h_il_1d(ji)      = 0._wp
+            !                                                         !--------------------------------!
+         ELSE                                                         ! Case ice thickness >= rn_himin !
+            !                                                         !--------------------------------!
+            v_ip_1d(ji) = h_ip_1d(ji) * a_ip_1d(ji)   ! retrieve volume from thickness
+            v_il_1d(ji) = h_il_1d(ji) * a_ip_1d(ji)
+            !
+            !------------------!
+            ! case ice melting !
+            !------------------!
+            !
+            !--- available meltwater for melt ponding ---!
+            zdum    = -( dh_i_sum(ji)*rhoi + dh_s_mlt(ji)*rhos ) * z1_rhow * a_i_1d(ji)
+            zfr_mlt = rn_apnd_min + ( rn_apnd_max - rn_apnd_min ) * at_i_1d(ji) !  = ( 1 - r ) = fraction of melt water that is not flushed
+            zdv_mlt = MAX( 0._wp, zfr_mlt * zdum ) ! max for roundoff errors? 
+            !
+            !--- overflow ---!
+            ! If pond area exceeds zfr_mlt * a_i_1d(ji) then reduce the pond volume
+            !    a_ip_max = zfr_mlt * a_i
+            !    => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
+            zv_ip_max = zfr_mlt**2 * a_i_1d(ji) * zaspect
+            zdv_mlt = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
+
+            ! If pond depth exceeds half the ice thickness then reduce the pond volume
+            !    h_ip_max = 0.5 * h_i
+            !    => from zaspect = h_ip / (a_ip / a_i), set v_ip_max as: 
+            zv_ip_max = z1_aspect * a_i_1d(ji) * 0.25 * h_i_1d(ji) * h_i_1d(ji)
+            zdv_mlt = MAX( 0._wp, MIN( zdv_mlt, zv_ip_max - v_ip_1d(ji) ) )
+            
+            !--- Pond growing ---!
+            v_ip_1d(ji) = v_ip_1d(ji) + zdv_mlt
+            !
+            !--- Lid melting ---!
+            IF( ln_pnd_lids )   v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) - zdv_mlt ) ! must be bounded by 0
+            !
+            !--- mass flux ---!
+            IF( zdv_mlt > 0._wp ) THEN
+               zfac = zdv_mlt * rhow * r1_rdtice                        ! melt pond mass flux < 0 [kg.m-2.s-1]
+               wfx_pnd_1d(ji) = wfx_pnd_1d(ji) - zfac
+               !
+               zdum = zfac / ( wfx_snw_sum_1d(ji) + wfx_sum_1d(ji) )    ! adjust ice/snow melting flux > 0 to balance melt pond flux
+               wfx_snw_sum_1d(ji) = wfx_snw_sum_1d(ji) * (1._wp + zdum)
+               wfx_sum_1d(ji)     = wfx_sum_1d(ji)     * (1._wp + zdum)
+            ENDIF
+
+            !-------------------!
+            ! case ice freezing ! i.e. t_su_1d(ji) < (zTp+rt0)
+            !-------------------!
+            !
+            zdT = MAX( zTp+rt0 - t_su_1d(ji), 0._wp )
+            !
+            !--- Pond contraction (due to refreezing) ---!
+            IF( ln_pnd_lids ) THEN
+               !
+               !--- Lid growing and subsequent pond shrinking ---! 
+               zdv_frz = 0.5_wp * MAX( 0._wp, -v_il_1d(ji) + & ! Flocco 2010 (eq. 5) solved implicitly as aH**2 + bH + c = 0
+                  &                    SQRT( v_il_1d(ji)**2 + a_ip_1d(ji)**2 * 4._wp * rcnd_i * zdT * rdt_ice / (rLfus * rhow) ) ) ! max for roundoff errors
+               
+               ! Lid growing
+               v_il_1d(ji) = MAX( 0._wp, v_il_1d(ji) + zdv_frz )
+               
+               ! Pond shrinking
+               v_ip_1d(ji) = MAX( 0._wp, v_ip_1d(ji) - zdv_frz )
+
+            ELSE
+               ! Pond shrinking
+               v_ip_1d(ji) = v_ip_1d(ji) * EXP( 0.01_wp * zdT * z1_Tp ) ! Holland 2012 (eq. 6)
+            ENDIF
+            !
+            !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
+            ! v_ip     = h_ip * a_ip
+            ! a_ip/a_i = a_ip_frac = h_ip / zaspect (cf Holland 2012, fitting SHEBA so that knowing v_ip we can distribute it to a_ip and h_ip)
+            a_ip_1d(ji)      = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
+            h_ip_1d(ji)      = zaspect * a_ip_1d(ji) / a_i_1d(ji)
+
+            !---------------!            
+            ! Pond flushing !
+            !---------------!
+            ! height of top of the pond above sea-level
+            zhp = ( h_i_1d(ji) * ( rau0 - rhoi ) + h_ip_1d(ji) * ( rau0 - rhow * a_ip_1d(ji) / a_i_1d(ji) ) ) * r1_rau0
+            
+            ! Calculate the permeability of the ice (Assur 1958, see Flocco 2010)
+            DO jk = 1, nlay_i
+               zsbr = - 1.2_wp                                  &
+                  &   - 21.8_wp    * ( t_i_1d(ji,jk) - rt0 )    &
+                  &   - 0.919_wp   * ( t_i_1d(ji,jk) - rt0 )**2 &
+                  &   - 0.0178_wp  * ( t_i_1d(ji,jk) - rt0 )**3
+               ztmp(jk) = sz_i_1d(ji,jk) / zsbr
+            END DO
+            zperm = MAX( 0._wp, 3.e-08_wp * MINVAL(ztmp)**3 )
+            
+            ! Do the drainage using Darcy's law
+            zdv_flush   = -zperm * rau0 * grav * zhp * rdt_ice / (zvisc * h_i_1d(ji)) * a_ip_1d(ji)
+            zdv_flush   = MAX( zdv_flush, -v_ip_1d(ji) )
+            v_ip_1d(ji) = v_ip_1d(ji) + zdv_flush
+            
+            !--- Set new pond area and depth ---! assuming linear relation between h_ip and a_ip_frac
+            a_ip_1d(ji)      = MIN( a_i_1d(ji), SQRT( v_ip_1d(ji) * z1_aspect * a_i_1d(ji) ) ) ! make sure a_ip < a_i
+            h_ip_1d(ji)      = zaspect * a_ip_1d(ji) / a_i_1d(ji)
+
+            !--- Corrections and lid thickness ---!
+            IF( ln_pnd_lids ) THEN
+               !--- retrieve lid thickness from volume ---!
+               IF( a_ip_1d(ji) > epsi10 ) THEN   ;   h_il_1d(ji) = v_il_1d(ji) / a_ip_1d(ji)
+               ELSE                              ;   h_il_1d(ji) = 0._wp
+               ENDIF
+               !--- remove ponds if lids are much larger than ponds ---!
+               IF ( h_il_1d(ji) > h_ip_1d(ji) * 10._wp ) THEN
+                  a_ip_1d(ji)      = 0._wp
+                  h_ip_1d(ji)      = 0._wp
+                  h_il_1d(ji)      = 0._wp
+               ENDIF
+            ENDIF
+            !
+         ENDIF
+         
+      END DO
+      !
+   END SUBROUTINE pnd_LEV
+
+
+   SUBROUTINE ice_thd_pnd_init 
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_thd_pnd_init   ***
+      !!
+      !! ** Purpose : Physical constants and parameters linked to melt ponds
+      !!              over sea ice
+      !!
+      !! ** Method  :  Read the namthd_pnd  namelist and check the melt pond  
+      !!               parameter values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd_pnd  
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios, ioptio   ! Local integer
+      !!
+      NAMELIST/namthd_pnd/  ln_pnd, ln_pnd_LEV , rn_apnd_min, rn_apnd_max, &
+         &                          ln_pnd_CST , rn_apnd, rn_hpnd,         &
+         &                          ln_pnd_lids, ln_pnd_alb
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd_pnd  in reference namelist : Melt Ponds  
+      READ  ( numnam_ice_ref, namthd_pnd, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd_pnd  in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd_pnd  in configuration namelist : Melt Ponds
+      READ  ( numnam_ice_cfg, namthd_pnd, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd_pnd in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namthd_pnd )
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_pnd_init: ice parameters for melt ponds'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namicethd_pnd:'
+         WRITE(numout,*) '      Melt ponds activated or not                                 ln_pnd       = ', ln_pnd
+         WRITE(numout,*) '         Level ice melt pond scheme                               ln_pnd_LEV   = ', ln_pnd_LEV
+         WRITE(numout,*) '            Minimum ice fraction that contributes to melt ponds   rn_apnd_min  = ', rn_apnd_min
+         WRITE(numout,*) '            Maximum ice fraction that contributes to melt ponds   rn_apnd_max  = ', rn_apnd_max
+         WRITE(numout,*) '         Constant ice melt pond scheme                            ln_pnd_CST   = ', ln_pnd_CST
+         WRITE(numout,*) '            Prescribed pond fraction                              rn_apnd      = ', rn_apnd
+         WRITE(numout,*) '            Prescribed pond depth                                 rn_hpnd      = ', rn_hpnd
+         WRITE(numout,*) '         Frozen lids on top of melt ponds                         ln_pnd_lids  = ', ln_pnd_lids
+         WRITE(numout,*) '         Melt ponds affect albedo or not                          ln_pnd_alb   = ', ln_pnd_alb
+      ENDIF
+      !
+      !                             !== set the choice of ice pond scheme ==!
+      ioptio = 0
+      IF( .NOT.ln_pnd ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndNO     ;   ENDIF
+      IF( ln_pnd_CST  ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndCST    ;   ENDIF
+      IF( ln_pnd_LEV  ) THEN   ;   ioptio = ioptio + 1   ;   nice_pnd = np_pndLEV    ;   ENDIF
+      IF( ioptio /= 1 )   &
+         & CALL ctl_stop( 'ice_thd_pnd_init: choose either none (ln_pnd=F) or only one pond scheme (ln_pnd_LEV or ln_pnd_CST)' )
+      !
+      SELECT CASE( nice_pnd )
+      CASE( np_pndNO )         
+         IF( ln_pnd_alb  ) THEN ; ln_pnd_alb  = .FALSE. ; CALL ctl_warn( 'ln_pnd_alb=false when no ponds' )  ; ENDIF
+         IF( ln_pnd_lids ) THEN ; ln_pnd_lids = .FALSE. ; CALL ctl_warn( 'ln_pnd_lids=false when no ponds' ) ; ENDIF
+      CASE( np_pndCST )         
+         IF( ln_pnd_lids ) THEN ; ln_pnd_lids = .FALSE. ; CALL ctl_warn( 'ln_pnd_lids=false when constant ponds' ) ; ENDIF
+      END SELECT
+      !
+   END SUBROUTINE ice_thd_pnd_init
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option          Empty module          NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif 
+
+   !!======================================================================
+END MODULE icethd_pnd 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_sal.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_sal.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_sal.F90	(revision 14097)
@@ -0,0 +1,172 @@
+MODULE icethd_sal
+   !!======================================================================
+   !!                       ***  MODULE icethd_sal ***
+   !!   sea-ice : computation of salinity variations in the ice
+   !!======================================================================
+   !! History :   -   !  2003-05  (M. Vancoppenolle) original code 1-D
+   !!            3.0  !  2005-12  (M. Vancoppenolle) adapted to the 3-D version
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!---------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_thd_sal      : salinity variations in the ice
+   !!   ice_thd_sal_init : initialization
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icevar         ! sea-ice: operations
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_sal        ! called by icethd
+   PUBLIC   ice_thd_sal_init   ! called by ice_init
+   
+   ! ** namelist (namthd_sal) **
+   REAL(wp) ::   rn_sal_gd     ! restoring salinity for gravity drainage [PSU]
+   REAL(wp) ::   rn_time_gd    ! restoring time constant for gravity drainage (= 20 days) [s]
+   REAL(wp) ::   rn_sal_fl     ! restoring salinity for flushing [PSU]
+   REAL(wp) ::   rn_time_fl    ! restoring time constant for gravity drainage (= 10 days) [s]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_sal( ld_sal )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd_sal  ***    
+      !!   
+      !! ** Purpose :   computes new salinities in the ice
+      !!
+      !! ** Method  :  3 possibilities
+      !!               -> nn_icesal = 1 -> Sice = cst    [ice salinity constant in both time & space] 
+      !!               -> nn_icesal = 2 -> Sice = S(z,t) [Vancoppenolle et al. 2005]
+      !!               -> nn_icesal = 3 -> Sice = S(z)   [multiyear ice]
+      !!---------------------------------------------------------------------
+      LOGICAL, INTENT(in) ::   ld_sal          ! gravity drainage and flushing or not 
+      !
+      INTEGER  ::   ji                         ! dummy loop indices 
+      REAL(wp) ::   zs_sni, zds                ! local scalars
+      REAL(wp) ::   z1_time_gd, z1_time_fl
+      !!---------------------------------------------------------------------
+
+      SELECT CASE ( nn_icesal )
+      !
+      !               !---------------------------------------------!
+      CASE( 2 )       !  time varying salinity with linear profile  !
+         !            !---------------------------------------------!
+         z1_time_gd = rdt_ice / rn_time_gd
+         z1_time_fl = rdt_ice / rn_time_fl
+         !
+         DO ji = 1, npti
+            !
+            IF( h_i_1d(ji) > 0._wp ) THEN
+               !
+               ! --- Update ice salinity from snow-ice and bottom growth --- !
+               zs_sni = sss_1d(ji) * ( rhoi - rhos ) * r1_rhoi                           ! salinity of snow ice
+               zds    =       ( zs_sni      - s_i_1d(ji) ) * dh_snowice(ji) / h_i_1d(ji) ! snow-ice    
+               zds    = zds + ( s_i_new(ji) - s_i_1d(ji) ) * dh_i_bog  (ji) / h_i_1d(ji) ! bottom growth
+               ! update salinity (nb: salt flux already included in icethd_dh)
+               s_i_1d(ji) = s_i_1d(ji) + zds
+               !
+               ! --- Update ice salinity from brine drainage and flushing --- !
+               IF( ld_sal ) THEN
+                  IF( t_su_1d(ji) >= rt0 ) THEN             ! flushing (summer time)
+                     zds = - MAX( s_i_1d(ji) - rn_sal_fl , 0._wp ) * z1_time_fl
+                  ELSEIF( t_su_1d(ji) <= t_bo_1d(ji) ) THEN ! gravity drainage
+                     zds = - MAX( s_i_1d(ji) - rn_sal_gd , 0._wp ) * z1_time_gd
+                  ELSE
+                     zds = 0._wp
+                  ENDIF
+                  ! update salinity
+                  s_i_1d(ji) = s_i_1d(ji) + zds
+                  ! salt flux
+                  sfx_bri_1d(ji) = sfx_bri_1d(ji) - rhoi * a_i_1d(ji) * h_i_1d(ji) * zds * r1_rdtice
+               ENDIF
+               !
+               ! --- salinity must stay inbounds --- !
+               zds =       MAX( 0._wp, rn_simin - s_i_1d(ji) ) ! > 0 if s_i < simin
+               zds = zds + MIN( 0._wp, rn_simax - s_i_1d(ji) ) ! < 0 if s_i > simax
+               ! update salinity
+               s_i_1d(ji) = s_i_1d(ji) + zds
+               ! salt flux
+               sfx_res_1d(ji) = sfx_res_1d(ji) - rhoi * a_i_1d(ji) * h_i_1d(ji) * zds * r1_rdtice
+               !
+            ENDIF
+            !
+         END DO
+         !
+         ! Salinity profile
+         CALL ice_var_salprof1d
+         !
+         !             !----------------------------------------!
+      CASE( 3 )        ! constant salinity with a fixed profile ! (Schwarzacher (1959) multiyear salinity profile (mean = 2.30)
+         !             !----------------------------------------!
+         CALL ice_var_salprof1d
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_thd_sal
+
+
+   SUBROUTINE ice_thd_sal_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_thd_sal_init  ***
+      !!
+      !! ** Purpose :   initialization of ice salinity parameters
+      !!
+      !! ** Method  :   Read the namthd_sal namelist and check the parameter
+      !!                values called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd_sal
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer
+      !!
+      NAMELIST/namthd_sal/ nn_icesal, rn_icesal, rn_sal_gd, rn_time_gd,   &
+         &                 rn_sal_fl, rn_time_fl, rn_simax , rn_simin 
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd_sal in reference namelist : Ice salinity
+      READ  ( numnam_ice_ref, namthd_sal, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd_sal in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd_sal in configuration namelist : Ice salinity
+      READ  ( numnam_ice_cfg, namthd_sal, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd_sal in configuration namelist' )
+      IF(lwm) WRITE ( numoni, namthd_sal )
+      !
+      IF(lwp) THEN                           ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_sal_init : Ice parameters for salinity '
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namthd_sal:'
+         WRITE(numout,*) '      switch for salinity                                     nn_icesal  = ', nn_icesal
+         WRITE(numout,*) '      bulk salinity value if nn_icesal = 1                    rn_icesal  = ', rn_icesal
+         WRITE(numout,*) '      restoring salinity for gravity drainage                 rn_sal_gd  = ', rn_sal_gd
+         WRITE(numout,*) '      restoring time for for gravity drainage                 rn_time_gd = ', rn_time_gd
+         WRITE(numout,*) '      restoring salinity for flushing                         rn_sal_fl  = ', rn_sal_fl
+         WRITE(numout,*) '      restoring time for flushing                             rn_time_fl = ', rn_time_fl
+         WRITE(numout,*) '      Maximum tolerated ice salinity                          rn_simax   = ', rn_simax
+         WRITE(numout,*) '      Minimum tolerated ice salinity                          rn_simin   = ', rn_simin
+      ENDIF
+      !
+   END SUBROUTINE ice_thd_sal_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Dummy Module           No SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_sal
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf.F90	(revision 14097)
@@ -0,0 +1,133 @@
+MODULE icethd_zdf
+   !!======================================================================
+   !!                       ***  MODULE icethd_zdf ***
+   !!   sea-ice: master routine for vertical heat diffusion in sea ice 
+   !!======================================================================
+   !! History :  4.0  !  2018     (C. Rousset)      Original code SI3
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!  ice_thd_zdf      : select the appropriate routine for vertical heat diffusion calculation
+   !!  ice_thd_zdf_BL99 : heat diffusion from Bitz and Lipscomb 1999 
+   !!  ice_thd_zdf_init : initialization
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants (ocean directory) 
+   USE ice             ! sea-ice: variables
+   USE icethd_zdf_BL99 ! sea-ice: vertical diffusion (Bitz and Lipscomb, 1999) 
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   USE lib_fortran     ! fortran utilities (glob_sum + no signed zero)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_zdf        ! called by icethd
+   PUBLIC   ice_thd_zdf_init   ! called by icestp
+
+   INTEGER ::   nice_zdf       ! Choice of the type of vertical heat diffusion formulation
+   !                                 ! associated indices:
+   INTEGER, PARAMETER ::   np_BL99 = 1   ! Bitz and Lipscomb (1999)
+!! INTEGER, PARAMETER ::   np_XXXX = 2
+
+   !!** namelist (namthd_zdf) **
+   LOGICAL ::   ln_zdf_BL99    ! Heat diffusion follows Bitz and Lipscomb (1999)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_zdf
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd_zdf  ***
+      !!
+      !! ** Purpose :   select the appropriate routine for the computation
+      !!              of vertical diffusion
+      !!-------------------------------------------------------------------
+      !
+      SELECT CASE ( nice_zdf )      ! Choose the vertical heat diffusion solver
+      !
+      !                             !-------------!      
+      CASE( np_BL99 )               ! BL99 solver !
+         !                          !-------------!
+         IF( .NOT.ln_cndflx ) THEN                           ! No conduction flux ==> default option
+            CALL ice_thd_zdf_BL99( np_cnd_OFF )
+         ELSEIF( ln_cndflx .AND. .NOT.ln_cndemulate ) THEN   ! Conduction flux as surface boundary condition ==> Met Office default option
+            CALL ice_thd_zdf_BL99( np_cnd_ON  )
+         ELSEIF( ln_cndflx .AND.      ln_cndemulate ) THEN   ! Conduction flux is emulated 
+            CALL ice_thd_zdf_BL99( np_cnd_EMU )
+            CALL ice_thd_zdf_BL99( np_cnd_ON  )
+         ENDIF
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_thd_zdf
+   
+   
+   SUBROUTINE ice_thd_zdf_init
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_thd_zdf_init *** 
+      !!                 
+      !! ** Purpose :   Physical constants and parameters associated with
+      !!                ice thermodynamics
+      !!
+      !! ** Method  :   Read the namthd_zdf namelist and check the parameters
+      !!                called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namelist namthd_zdf
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ios, ioptio   ! Local integer
+      !!
+      NAMELIST/namthd_zdf/ ln_zdf_BL99, ln_cndi_U64, ln_cndi_P07, rn_cnd_s, &
+         &                 rn_kappa_i, rn_kappa_s, rn_kappa_smlt, rn_kappa_sdry, ln_zdf_chkcvg
+      !!-------------------------------------------------------------------
+      !
+      REWIND( numnam_ice_ref )              ! Namelist namthd_zdf in reference namelist : Ice thermodynamics
+      READ  ( numnam_ice_ref, namthd_zdf, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namthd_zdf in reference namelist' )
+      REWIND( numnam_ice_cfg )              ! Namelist namthd_zdf in configuration namelist : Ice thermodynamics
+      READ  ( numnam_ice_cfg, namthd_zdf, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namthd_zdf in configuration namelist' )
+      IF(lwm) WRITE( numoni, namthd_zdf )
+      !
+      IF(lwp) THEN                          ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ice_thd_zdf_init: Ice vertical heat diffusion'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namthd_zdf:'
+         WRITE(numout,*) '      Bitz and Lipscomb (1999) formulation                      ln_zdf_BL99   = ', ln_zdf_BL99
+         WRITE(numout,*) '      thermal conductivity in the ice (Untersteiner 1964)       ln_cndi_U64   = ', ln_cndi_U64
+         WRITE(numout,*) '      thermal conductivity in the ice (Pringle et al 2007)      ln_cndi_P07   = ', ln_cndi_P07
+         WRITE(numout,*) '      thermal conductivity in the snow                          rn_cnd_s      = ', rn_cnd_s
+         WRITE(numout,*) '      extinction radiation parameter in sea ice                 rn_kappa_i    = ', rn_kappa_i
+         WRITE(numout,*) '      extinction radiation parameter in snw      (nn_qtrice=0)  rn_kappa_s    = ', rn_kappa_s
+         WRITE(numout,*) '      extinction radiation parameter in melt snw (nn_qtrice=1)  rn_kappa_smlt = ', rn_kappa_smlt
+         WRITE(numout,*) '      extinction radiation parameter in dry  snw (nn_qtrice=1)  rn_kappa_sdry = ', rn_kappa_sdry
+         WRITE(numout,*) '      check convergence of heat diffusion scheme                ln_zdf_chkcvg = ', ln_zdf_chkcvg
+      ENDIF
+      !
+      IF ( ( ln_cndi_U64 .AND. ln_cndi_P07 ) .OR. ( .NOT. ln_cndi_U64 .AND. .NOT. ln_cndi_P07 ) ) THEN
+         CALL ctl_stop( 'ice_thd_zdf_init: choose 1 and only 1 formulation for thermal conduction (ln_cndi_U64 or ln_cndi_P07)' )
+      ENDIF
+      !                             !== set the choice of ice vertical thermodynamic formulation ==!
+      ioptio = 0 
+      IF( ln_zdf_BL99 ) THEN   ;   ioptio = ioptio + 1   ;   nice_zdf = np_BL99   ;   ENDIF   ! BL99 thermodynamics (linear liquidus + constant thermal properties)
+!!    IF( ln_zdf_XXXX ) THEN   ;   ioptio = ioptio + 1   ;   nice_zdf = np_XXXX   ;   ENDIF
+      IF( ioptio /= 1 )   CALL ctl_stop( 'ice_thd_init: one and only one ice thermo option has to be defined ' )
+      !
+   END SUBROUTINE ice_thd_zdf_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option       Dummy Module             No SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_zdf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf_bl99.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf_bl99.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icethd_zdf_bl99.F90	(revision 14097)
@@ -0,0 +1,943 @@
+MODULE icethd_zdf_BL99
+   !!======================================================================
+   !!                       ***  MODULE icethd_zdf_BL99 ***
+   !!   sea-ice: vertical heat diffusion in sea ice (computation of temperatures) 
+   !!======================================================================
+   !! History :       !  2003-02  (M. Vancoppenolle) original 1D code
+   !!                 !  2005-06  (M. Vancoppenolle) 3d version
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!  ice_thd_zdf_BL99 : vertical diffusion computation
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants (ocean directory) 
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   USE icevar         ! sea-ice: operations
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_thd_zdf_BL99   ! called by icethd_zdf
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_thd_zdf_BL99( k_cnd )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_thd_zdf_BL99  ***
+      !!
+      !! ** Purpose : computes the time evolution of snow and sea-ice temperature
+      !!              profiles, using the original Bitz and Lipscomb (1999) algorithm
+      !!
+      !! ** Method  : solves the heat equation diffusion with a Neumann boundary
+      !!              condition at the surface and a Dirichlet one at the bottom. 
+      !!              Solar radiation is partially absorbed into the ice.
+      !!              The specific heat and thermal conductivities depend on ice 
+      !!              salinity and temperature to take into account brine pocket   
+      !!              melting. The numerical scheme is an iterative Crank-Nicolson
+      !!              on a non-uniform multilayer grid in the ice and snow system.
+      !!
+      !!           The successive steps of this routine are
+      !!           1.  initialization of ice-snow layers thicknesses
+      !!           2.  Internal absorbed and transmitted radiation
+      !!           Then iterative procedure begins
+      !!           3.  Thermal conductivity
+      !!           4.  Kappa factors
+      !!           5.  specific heat in the ice
+      !!           6.  eta factors
+      !!           7.  surface flux computation
+      !!           8.  tridiagonal system terms
+      !!           9.  solving the tridiagonal system with Gauss elimination
+      !!           Iterative procedure ends according to a criterion on evolution
+      !!           of temperature
+      !!           10. Fluxes at the interfaces
+      !!
+      !! ** Inputs / Ouputs : (global commons)
+      !!           surface temperature              : t_su_1d
+      !!           ice/snow temperatures            : t_i_1d, t_s_1d
+      !!           ice salinities                   : sz_i_1d
+      !!           number of layers in the ice/snow : nlay_i, nlay_s
+      !!           total ice/snow thickness         : h_i_1d, h_s_1d
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   k_cnd     ! conduction flux (off, on, emulated)
+      !
+      INTEGER ::   ji, jk         ! spatial loop index
+      INTEGER ::   jm             ! current reference number of equation
+      INTEGER ::   jm_mint, jm_maxt
+      INTEGER ::   iconv          ! number of iterations in iterative procedure
+      INTEGER ::   iconv_max = 50 ! max number of iterations in iterative procedure
+      !
+      INTEGER, DIMENSION(jpij) ::   jm_min    ! reference number of top equation
+      INTEGER, DIMENSION(jpij) ::   jm_max    ! reference number of bottom equation
+
+      LOGICAL, DIMENSION(jpij) ::   l_T_converged   ! true when T converges (per grid point)
+      !
+      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) ::   zkimin    =  0.10_wp      ! minimum ice thermal conductivity
+      REAL(wp) ::   ztsu_err  =  1.e-5_wp     ! range around which t_su is considered at 0C 
+      REAL(wp) ::   zdti_bnd  =  1.e-4_wp     ! maximal authorized error on temperature 
+      REAL(wp) ::   zhs_ssl   =  0.03_wp      ! surface scattering layer in the snow 
+      REAL(wp) ::   zhi_ssl   =  0.10_wp      ! surface scattering layer in the ice
+      REAL(wp) ::   zh_min    =  1.e-3_wp     ! minimum ice/snow thickness for conduction
+      REAL(wp) ::   ztmelts                   ! ice melting temperature
+      REAL(wp) ::   zdti_max                  ! current maximal error on temperature 
+      REAL(wp) ::   zcpi                      ! Ice specific heat
+      REAL(wp) ::   zhfx_err, zdq             ! diag errors on heat
+      !
+      REAL(wp), DIMENSION(jpij) ::   zraext_s     ! extinction coefficient of radiation in the snow
+      REAL(wp), DIMENSION(jpij) ::   ztsub        ! surface temperature at previous iteration
+      REAL(wp), DIMENSION(jpij) ::   zh_i, z1_h_i ! ice layer thickness
+      REAL(wp), DIMENSION(jpij) ::   zh_s, z1_h_s ! snow layer thickness
+      REAL(wp), DIMENSION(jpij) ::   zqns_ice_b   ! solar radiation absorbed at the surface
+      REAL(wp), DIMENSION(jpij) ::   zfnet        ! surface flux function
+      REAL(wp), DIMENSION(jpij) ::   zdqns_ice_b  ! derivative of the surface flux function
+      !
+      REAL(wp), DIMENSION(jpij       )     ::   ztsuold     ! Old surface temperature in the ice
+      REAL(wp), DIMENSION(jpij,nlay_i)     ::   ztiold      ! Old temperature in the ice
+      REAL(wp), DIMENSION(jpij,nlay_s)     ::   ztsold      ! Old temperature in the snow
+      REAL(wp), DIMENSION(jpij,nlay_i)     ::   ztib        ! Temporary temperature in the ice to check the convergence
+      REAL(wp), DIMENSION(jpij,nlay_s)     ::   ztsb        ! Temporary temperature in the snow to check the convergence
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   ztcond_i    ! Ice thermal conductivity
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   ztcond_i_cp ! copy
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zradtr_i    ! Radiation transmitted through the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zradab_i    ! Radiation absorbed in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zkappa_i    ! Kappa factor in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_i)   ::   zeta_i      ! Eta factor in the ice
+      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zradtr_s    ! Radiation transmited through the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zradab_s    ! Radiation absorbed in the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zkappa_s    ! Kappa factor in the snow
+      REAL(wp), DIMENSION(jpij,0:nlay_s)   ::   zeta_s      ! Eta factor in the snow
+      REAL(wp), DIMENSION(jpij)            ::   zkappa_comb ! Combined snow and ice surface conductivity
+      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zindterm    ! 'Ind'ependent term
+      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zindtbis    ! Temporary 'ind'ependent term
+      REAL(wp), DIMENSION(jpij,nlay_i+3)   ::   zdiagbis    ! Temporary 'dia'gonal term
+      REAL(wp), DIMENSION(jpij,nlay_i+3,3) ::   ztrid       ! Tridiagonal system terms
+      REAL(wp), DIMENSION(jpij)            ::   zq_ini      ! diag errors on heat
+      REAL(wp), DIMENSION(jpij)            ::   zghe        ! G(he), th. conduct enhancement factor, mono-cat
+      REAL(wp), DIMENSION(jpij)            ::   za_s_fra    ! ice fraction covered by snow 
+      REAL(wp), DIMENSION(jpij)            ::   isnow       ! snow presence (1) or not (0) 
+      REAL(wp), DIMENSION(jpij)            ::   isnow_comb  ! snow presence for met-office 
+      !
+      ! Mono-category
+      REAL(wp) ::   zepsilon   ! determines thres. above which computation of G(h) is done
+      REAL(wp) ::   zhe        ! dummy factor
+      REAL(wp) ::   zcnd_i     ! mean sea ice thermal conductivity
+      !!------------------------------------------------------------------     
+
+      ! --- diag error on heat diffusion - PART 1 --- !
+      DO ji = 1, npti
+         zq_ini(ji) = ( SUM( e_i_1d(ji,1:nlay_i) ) * h_i_1d(ji) * r1_nlay_i +  &
+            &           SUM( e_s_1d(ji,1:nlay_s) ) * h_s_1d(ji) * r1_nlay_s ) 
+      END DO
+
+      ! calculate ice fraction covered by snow for radiation
+      CALL ice_var_snwfra( h_s_1d(1:npti), za_s_fra(1:npti) )
+      
+      !------------------
+      ! 1) Initialization
+      !------------------
+      !
+      ! extinction radiation in the snow
+      IF    ( nn_qtrice == 0 ) THEN   ! constant 
+         zraext_s(1:npti) = rn_kappa_s
+      ELSEIF( nn_qtrice == 1 ) THEN   ! depends on melting/freezing conditions
+         WHERE( t_su_1d(1:npti) < rt0 )   ;   zraext_s(1:npti) = rn_kappa_sdry   ! no surface melting
+         ELSEWHERE                        ;   zraext_s(1:npti) = rn_kappa_smlt   !    surface melting
+         END WHERE
+      ENDIF
+      !
+      ! thicknesses
+      DO ji = 1, npti
+         ! ice thickness
+         IF( h_i_1d(ji) > 0._wp ) THEN 
+            zh_i  (ji) = MAX( zh_min , h_i_1d(ji) ) * r1_nlay_i ! set a minimum thickness for conduction
+            z1_h_i(ji) = 1._wp / zh_i(ji)                       !       it must be very small
+         ELSE
+            zh_i  (ji) = 0._wp
+            z1_h_i(ji) = 0._wp
+         ENDIF
+         ! snow thickness
+         IF( h_s_1d(ji) > 0._wp ) THEN
+            zh_s  (ji) = MAX( zh_min , h_s_1d(ji) ) * r1_nlay_s ! set a minimum thickness for conduction
+            z1_h_s(ji) = 1._wp / zh_s(ji)                       !       it must be very small
+            isnow (ji) = 1._wp
+         ELSE
+            zh_s  (ji) = 0._wp
+            z1_h_s(ji) = 0._wp
+            isnow (ji) = 0._wp
+         ENDIF
+         ! for Met-Office
+         IF( h_s_1d(ji) < zh_min ) THEN
+            isnow_comb(ji) = h_s_1d(ji) / zh_min
+         ELSE
+            isnow_comb(ji) = 1._wp
+         ENDIF
+      END DO
+      ! clem: we should apply correction on snow thickness to take into account snow fraction
+      !       it must be a distribution, so it is a bit complicated
+      !
+      ! Store initial temperatures and non solar heat fluxes
+      IF( k_cnd == np_cnd_OFF .OR. k_cnd == np_cnd_EMU ) THEN
+         ztsub      (1:npti) = t_su_1d(1:npti)                          ! surface temperature at iteration n-1
+         ztsuold    (1:npti) = t_su_1d(1:npti)                          ! surface temperature initial value
+         t_su_1d    (1:npti) = MIN( t_su_1d(1:npti), rt0 - ztsu_err )   ! required to leave the choice between melting or not
+         zdqns_ice_b(1:npti) = dqns_ice_1d(1:npti)                      ! derivative of incoming nonsolar flux 
+         zqns_ice_b (1:npti) = qns_ice_1d(1:npti)                       ! store previous qns_ice_1d value
+         !
+      ENDIF
+      !
+      ztsold (1:npti,:) = t_s_1d(1:npti,:)   ! Old snow temperature
+      ztiold (1:npti,:) = t_i_1d(1:npti,:)   ! Old ice temperature
+
+      !-------------
+      ! 2) Radiation
+      !-------------
+      ! --- Transmission/absorption of solar radiation in the ice --- !
+      zradtr_s(1:npti,0) = qtr_ice_top_1d(1:npti)
+      DO jk = 1, nlay_s
+         DO ji = 1, npti
+            !                             ! radiation transmitted below the layer-th snow layer
+            zradtr_s(ji,jk) = zradtr_s(ji,0) * EXP( - zraext_s(ji) * MAX( 0._wp, zh_s(ji) * REAL(jk) - zhs_ssl ) )
+            !                             ! radiation absorbed by the layer-th snow layer
+            zradab_s(ji,jk) = zradtr_s(ji,jk-1) - zradtr_s(ji,jk)
+         END DO
+      END DO
+      !
+      zradtr_i(1:npti,0) = zradtr_s(1:npti,nlay_s) * za_s_fra(1:npti) + qtr_ice_top_1d(1:npti) * ( 1._wp - za_s_fra(1:npti) )
+      DO jk = 1, nlay_i 
+         DO ji = 1, npti
+            !                             ! radiation transmitted below the layer-th ice layer
+            zradtr_i(ji,jk) =           za_s_fra(ji)   * zradtr_s(ji,nlay_s)                       &   ! part covered by snow
+               &                                       * EXP( - rn_kappa_i * MAX( 0._wp, zh_i(ji) * REAL(jk) - zh_min  ) ) &
+               &            + ( 1._wp - za_s_fra(ji) ) * qtr_ice_top_1d(ji)                        &   ! part snow free
+               &                                       * EXP( - rn_kappa_i * MAX( 0._wp, zh_i(ji) * REAL(jk) - zhi_ssl ) )            
+            !                             ! radiation absorbed by the layer-th ice layer
+            zradab_i(ji,jk) = zradtr_i(ji,jk-1) - zradtr_i(ji,jk)
+         END DO
+      END DO
+      !
+      qtr_ice_bot_1d(1:npti) = zradtr_i(1:npti,nlay_i)   ! record radiation transmitted below the ice
+      !
+      iconv = 0          ! number of iterations
+      !
+      l_T_converged(:) = .FALSE.
+      ! Convergence calculated until all sub-domain grid points have converged
+      ! Calculations keep going for all grid points until sub-domain convergence (vectorisation optimisation)
+      ! but values are not taken into account (results independant of MPI partitioning)
+      !
+      !                                                                            !============================!
+      DO WHILE ( ( .NOT. ALL (l_T_converged(1:npti)) ) .AND. iconv < iconv_max )   ! Iterative procedure begins !
+         !                                                                         !============================!
+         iconv = iconv + 1
+         !
+         ztib(1:npti,:) = t_i_1d(1:npti,:)
+         ztsb(1:npti,:) = t_s_1d(1:npti,:)
+         !
+         !--------------------------------
+         ! 3) Sea ice thermal conductivity
+         !--------------------------------
+         IF( ln_cndi_U64 ) THEN         !-- Untersteiner (1964) formula: k = k0 + beta.S/T
+            !
+            DO ji = 1, npti
+               ztcond_i_cp(ji,0)      = rcnd_i + zbeta * sz_i_1d(ji,1)      / MIN( -epsi10, t_i_1d(ji,1) - rt0 )
+               ztcond_i_cp(ji,nlay_i) = rcnd_i + zbeta * sz_i_1d(ji,nlay_i) / MIN( -epsi10, t_bo_1d(ji)  - rt0 )
+            END DO
+            DO jk = 1, nlay_i-1
+               DO ji = 1, npti
+                  ztcond_i_cp(ji,jk) = rcnd_i + zbeta * 0.5_wp * ( sz_i_1d(ji,jk) + sz_i_1d(ji,jk+1) ) /  &
+                     &                    MIN( -epsi10, 0.5_wp * (  t_i_1d(ji,jk) +  t_i_1d(ji,jk+1) ) - rt0 )
+               END DO
+            END DO
+            !
+         ELSEIF( ln_cndi_P07 ) THEN     !-- Pringle et al formula: k = k0 + beta1.S/T - beta2.T
+            !
+            DO ji = 1, npti
+               ztcond_i_cp(ji,0)      = rcnd_i + 0.09_wp  *  sz_i_1d(ji,1)      / MIN( -epsi10, t_i_1d(ji,1) - rt0 )  &
+                  &                            - 0.011_wp * ( t_i_1d(ji,1) - rt0 )
+               ztcond_i_cp(ji,nlay_i) = rcnd_i + 0.09_wp  *  sz_i_1d(ji,nlay_i) / MIN( -epsi10, t_bo_1d(ji)  - rt0 )  &
+                  &                            - 0.011_wp * ( t_bo_1d(ji) - rt0 )
+            END DO
+            DO jk = 1, nlay_i-1
+               DO ji = 1, npti
+                  ztcond_i_cp(ji,jk) = rcnd_i + 0.09_wp  *   0.5_wp * ( sz_i_1d(ji,jk) + sz_i_1d(ji,jk+1) ) /       &
+                     &                         MIN( -epsi10, 0.5_wp * (  t_i_1d(ji,jk) +  t_i_1d(ji,jk+1) ) - rt0 ) &
+                     &                        - 0.011_wp * ( 0.5_wp * (  t_i_1d(ji,jk) +  t_i_1d(ji,jk+1) ) - rt0 )
+               END DO
+            END DO
+            !
+         ENDIF
+
+         ! Variable used after iterations
+         ! Value must be frozen after convergence for MPP independance reason
+         DO ji = 1, npti
+            IF ( .NOT. l_T_converged(ji) ) &
+               ztcond_i(ji,:) = MAX( zkimin, ztcond_i_cp(ji,:) )        
+         END DO
+         !
+         !--- G(he) : enhancement of thermal conductivity in mono-category case
+         ! Computation of effective thermal conductivity G(h)
+         ! Used in mono-category case only to simulate an ITD implicitly
+         ! Fichefet and Morales Maqueda, JGR 1997
+         zghe(1:npti) = 1._wp
+         !
+         IF( ln_virtual_itd ) THEN
+            !
+            zepsilon = 0.1_wp
+            DO ji = 1, npti
+               zcnd_i = SUM( ztcond_i(ji,:) ) / REAL( nlay_i+1, wp )                                ! Mean sea ice thermal conductivity
+               zhe = ( rn_cnd_s * h_i_1d(ji) + zcnd_i * h_s_1d(ji) ) / ( rn_cnd_s + zcnd_i )        ! Effective thickness he (zhe)
+               IF( zhe >=  zepsilon * 0.5_wp * EXP(1._wp) )  &
+                  &   zghe(ji) = MIN( 2._wp, 0.5_wp * ( 1._wp + LOG( 2._wp * zhe / zepsilon ) ) )   ! G(he)
+            END DO
+            !
+         ENDIF
+         !
+         !-----------------
+         ! 4) kappa factors
+         !-----------------
+         !--- Snow
+         ! Variable used after iterations
+         ! Value must be frozen after convergence for MPP independance reason
+         DO jk = 0, nlay_s-1
+            DO ji = 1, npti
+               IF ( .NOT. l_T_converged(ji) ) &
+                  zkappa_s(ji,jk) = zghe(ji) * rn_cnd_s * z1_h_s(ji)
+            END DO
+         END DO
+         DO ji = 1, npti   ! Snow-ice interface
+            IF ( .NOT. l_T_converged(ji) ) &
+               zkappa_s(ji,nlay_s) = isnow(ji) * zghe(ji) * rn_cnd_s * ztcond_i(ji,0) &
+                  &                            / ( 0.5_wp * ( ztcond_i(ji,0) * zh_s(ji) + rn_cnd_s * zh_i(ji) ) )
+         END DO
+
+         !--- Ice
+         ! Variable used after iterations
+         ! Value must be frozen after convergence for MPP independance reason
+         DO jk = 0, nlay_i
+            DO ji = 1, npti
+               IF ( .NOT. l_T_converged(ji) ) &
+                  zkappa_i(ji,jk) = zghe(ji) * ztcond_i(ji,jk) * z1_h_i(ji)
+            END DO
+         END DO
+         DO ji = 1, npti   ! Snow-ice interface
+            IF ( .NOT. l_T_converged(ji) ) THEN
+               ! Calculate combined surface snow and ice conductivity to pass through the coupler (met-office)
+               zkappa_comb(ji) = isnow_comb(ji) * zkappa_s(ji,0) + ( 1._wp - isnow_comb(ji) ) * zkappa_i(ji,0)
+               ! If there is snow then use the same snow-ice interface conductivity for the top layer of ice
+               IF( h_s_1d(ji) > 0._wp )   zkappa_i(ji,0) = zkappa_s(ji,nlay_s)
+           ENDIF
+         END DO
+         !
+         !--------------------------------------
+         ! 5) Sea ice specific heat, eta factors
+         !--------------------------------------
+         DO jk = 1, nlay_i
+            DO ji = 1, npti
+               zcpi = rcpi + zgamma * sz_i_1d(ji,jk) / MAX( ( t_i_1d(ji,jk) - rt0 ) * ( ztiold(ji,jk) - rt0 ), epsi10 )
+               zeta_i(ji,jk) = rdt_ice * r1_rhoi * z1_h_i(ji) / zcpi
+            END DO
+         END DO
+
+         DO jk = 1, nlay_s
+            DO ji = 1, npti
+               zeta_s(ji,jk) = rdt_ice * r1_rhos * r1_rcpi * z1_h_s(ji)
+            END DO
+         END DO
+         !
+         !----------------------------------------!
+         !                                        !
+         !   Conduction flux is off or emulated   !
+         !                                        !
+         !----------------------------------------!
+         !
+         IF( k_cnd == np_cnd_OFF .OR. k_cnd == np_cnd_EMU ) THEN
+            !
+            ! ==> The original BL99 temperature computation is used
+            !       (with qsr_ice, qns_ice and dqns_ice as inputs)
+            !
+            !----------------------------
+            ! 6) surface flux computation
+            !----------------------------
+            ! update of the non solar flux according to the update in T_su
+            DO ji = 1, npti
+               ! Variable used after iterations
+               ! Value must be frozen after convergence for MPP independance reason
+               IF ( .NOT. l_T_converged(ji) ) &
+                  qns_ice_1d(ji) = qns_ice_1d(ji) + dqns_ice_1d(ji) * ( t_su_1d(ji) - ztsub(ji) )
+            END DO
+
+            DO ji = 1, npti
+               zfnet(ji) = qsr_ice_1d(ji) - qtr_ice_top_1d(ji) + qns_ice_1d(ji) ! net heat flux = net - transmitted solar + non solar
+            END DO
+            !
+            !----------------------------
+            ! 7) tridiagonal system terms
+            !----------------------------
+            ! layer denotes the number of the layer in the snow or in the ice
+            ! jm denotes the reference number of the equation in the tridiagonal
+            ! system, terms of tridiagonal system are indexed as following :
+            ! 1 is subdiagonal term, 2 is diagonal and 3 is superdiagonal one
+
+            ! ice interior terms (top equation has the same form as the others)
+            ztrid   (1:npti,:,:) = 0._wp
+            zindterm(1:npti,:)   = 0._wp
+            zindtbis(1:npti,:)   = 0._wp
+            zdiagbis(1:npti,:)   = 0._wp
+
+            DO jm = nlay_s + 2, nlay_s + nlay_i 
+               DO ji = 1, npti
+                  jk = jm - nlay_s - 1
+                  ztrid   (ji,jm,1) =       - zeta_i(ji,jk) *   zkappa_i(ji,jk-1)
+                  ztrid   (ji,jm,2) = 1._wp + zeta_i(ji,jk) * ( zkappa_i(ji,jk-1) + zkappa_i(ji,jk) )
+                  ztrid   (ji,jm,3) =       - zeta_i(ji,jk) *                       zkappa_i(ji,jk)
+                  zindterm(ji,jm)   = ztiold(ji,jk) + zeta_i(ji,jk) * zradab_i(ji,jk)
+               END DO
+            END DO
+
+            jm =  nlay_s + nlay_i + 1
+            DO ji = 1, npti
+               ! ice bottom term
+               ztrid   (ji,jm,1) =       - zeta_i(ji,nlay_i) *   zkappa_i(ji,nlay_i-1)   
+               ztrid   (ji,jm,2) = 1._wp + zeta_i(ji,nlay_i) * ( zkappa_i(ji,nlay_i-1) + zkappa_i(ji,nlay_i) * zg1 )
+               ztrid   (ji,jm,3) = 0._wp
+               zindterm(ji,jm)   = ztiold(ji,nlay_i) + zeta_i(ji,nlay_i) *  &
+                  &              ( zradab_i(ji,nlay_i) + zkappa_i(ji,nlay_i) * zg1 * t_bo_1d(ji) ) 
+            END DO
+
+            DO ji = 1, npti
+               !                               !---------------------!
+               IF( h_s_1d(ji) > 0._wp ) THEN   !  snow-covered cells !
+                  !                            !---------------------!
+                  ! snow interior terms (bottom equation has the same form as the others)
+                  DO jm = 3, nlay_s + 1
+                     jk = jm - 1
+                     ztrid   (ji,jm,1) =       - zeta_s(ji,jk) *   zkappa_s(ji,jk-1)
+                     ztrid   (ji,jm,2) = 1._wp + zeta_s(ji,jk) * ( zkappa_s(ji,jk-1) + zkappa_s(ji,jk) )
+                     ztrid   (ji,jm,3) =       - zeta_s(ji,jk) *                       zkappa_s(ji,jk)
+                     zindterm(ji,jm)   = ztsold(ji,jk) + zeta_s(ji,jk) * zradab_s(ji,jk)
+                  END DO
+                  
+                  ! case of only one layer in the ice (ice equation is altered)
+                  IF( nlay_i == 1 ) THEN
+                     ztrid   (ji,nlay_s+2,3) = 0._wp
+                     zindterm(ji,nlay_s+2)   = zindterm(ji,nlay_s+2) + zeta_i(ji,1) * zkappa_i(ji,1) * t_bo_1d(ji) 
+                  ENDIF
+                  
+                  IF( t_su_1d(ji) < rt0 ) THEN   !--  case 1 : no surface melting
+                     
+                     jm_min(ji) = 1
+                     jm_max(ji) = nlay_i + nlay_s + 1
+                     
+                     ! surface equation
+                     ztrid   (ji,1,1) = 0._wp
+                     ztrid   (ji,1,2) = zdqns_ice_b(ji) - zg1s * zkappa_s(ji,0)
+                     ztrid   (ji,1,3) =                   zg1s * zkappa_s(ji,0)
+                     zindterm(ji,1)   = zdqns_ice_b(ji) * t_su_1d(ji) - zfnet(ji)
+                     
+                     ! first layer of snow equation
+                     ztrid   (ji,2,1) =       - zeta_s(ji,1) *                    zkappa_s(ji,0) * zg1s
+                     ztrid   (ji,2,2) = 1._wp + 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)
+                     
+                  ELSE                            !--  case 2 : surface is melting
+                     !
+                     jm_min(ji) = 2
+                     jm_max(ji) = nlay_i + nlay_s + 1
+                     
+                     ! first layer of snow equation
+                     ztrid   (ji,2,1) = 0._wp
+                     ztrid   (ji,2,2) = 1._wp + 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) + zkappa_s(ji,0) * zg1s * t_su_1d(ji) ) 
+                  ENDIF
+                  !                            !---------------------!
+               ELSE                            ! cells without snow  !
+                  !                            !---------------------!
+                  !
+                  IF( t_su_1d(ji) < rt0 ) THEN   !--  case 1 : no surface melting
+                     !
+                     jm_min(ji) = nlay_s + 1
+                     jm_max(ji) = nlay_i + nlay_s + 1
+                     
+                     ! surface equation	
+                     ztrid   (ji,jm_min(ji),1) = 0._wp
+                     ztrid   (ji,jm_min(ji),2) = zdqns_ice_b(ji) - zkappa_i(ji,0) * zg1    
+                     ztrid   (ji,jm_min(ji),3) =                   zkappa_i(ji,0) * zg1
+                     zindterm(ji,jm_min(ji))   = zdqns_ice_b(ji) * t_su_1d(ji) - zfnet(ji)
+                     
+                     ! first layer of ice equation
+                     ztrid   (ji,jm_min(ji)+1,1) =       - zeta_i(ji,1) *                    zkappa_i(ji,0) * zg1
+                     ztrid   (ji,jm_min(ji)+1,2) = 1._wp + zeta_i(ji,1) * ( zkappa_i(ji,1) + zkappa_i(ji,0) * zg1 )
+                     ztrid   (ji,jm_min(ji)+1,3) =       - zeta_i(ji,1) *   zkappa_i(ji,1)  
+                     zindterm(ji,jm_min(ji)+1)   = ztiold(ji,1) + zeta_i(ji,1) * zradab_i(ji,1)  
+                     
+                     ! case of only one layer in the ice (surface & ice equations are altered)
+                     IF( nlay_i == 1 ) THEN
+                        ztrid   (ji,jm_min(ji),1)   = 0._wp
+                        ztrid   (ji,jm_min(ji),2)   = zdqns_ice_b(ji)      -   zkappa_i(ji,0) * 2._wp
+                        ztrid   (ji,jm_min(ji),3)   =                          zkappa_i(ji,0) * 2._wp
+                        ztrid   (ji,jm_min(ji)+1,1) =       - zeta_i(ji,1) *   zkappa_i(ji,0) * 2._wp
+                        ztrid   (ji,jm_min(ji)+1,2) = 1._wp + zeta_i(ji,1) * ( zkappa_i(ji,0) * 2._wp + zkappa_i(ji,1) )
+                        ztrid   (ji,jm_min(ji)+1,3) = 0._wp
+                        zindterm(ji,jm_min(ji)+1)   = ztiold(ji,1) + zeta_i(ji,1) * (zradab_i(ji,1) + zkappa_i(ji,1) * t_bo_1d(ji))
+                     ENDIF
+                     
+                  ELSE                            !--  case 2 : surface is melting
+                     
+                     jm_min(ji) = nlay_s + 2
+                     jm_max(ji) = nlay_i + nlay_s + 1
+                     
+                     ! first layer of ice equation
+                     ztrid   (ji,jm_min(ji),1) = 0._wp
+                     ztrid   (ji,jm_min(ji),2) = 1._wp + zeta_i(ji,1) * ( zkappa_i(ji,1) + zkappa_i(ji,0) * zg1 )  
+                     ztrid   (ji,jm_min(ji),3) =       - zeta_i(ji,1) *   zkappa_i(ji,1)
+                     zindterm(ji,jm_min(ji))   = ztiold(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)
+                     IF( nlay_i == 1 ) THEN
+                        ztrid   (ji,jm_min(ji),1) = 0._wp
+                        ztrid   (ji,jm_min(ji),2) = 1._wp + zeta_i(ji,1) * ( zkappa_i(ji,0) * 2._wp + zkappa_i(ji,1) )
+                        ztrid   (ji,jm_min(ji),3) = 0._wp
+                        zindterm(ji,jm_min(ji))   = ztiold(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._wp
+                     ENDIF
+                     
+                  ENDIF
+               ENDIF
+               !
+               zindtbis(ji,jm_min(ji)) = zindterm(ji,jm_min(ji))
+               zdiagbis(ji,jm_min(ji)) = ztrid   (ji,jm_min(ji),2)
+               !
+            END DO
+            !
+            !------------------------------
+            ! 8) tridiagonal system solving
+            !------------------------------
+            ! Solve the tridiagonal system with Gauss elimination method.
+            ! Thomas algorithm, from Computational fluid Dynamics, J.D. ANDERSON, McGraw-Hill 1984
+            jm_maxt = 0
+            jm_mint = nlay_i+5
+            DO ji = 1, npti
+               jm_mint = MIN(jm_min(ji),jm_mint)
+               jm_maxt = MAX(jm_max(ji),jm_maxt)
+            END DO
+
+            DO jk = jm_mint+1, jm_maxt
+               DO ji = 1, npti
+                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+                  zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
+                  zindtbis(ji,jm) = zindterm(ji,jm  ) - ztrid(ji,jm,1) * zindtbis(ji,jm-1  ) / zdiagbis(ji,jm-1)
+               END DO
+            END DO
+
+            ! ice temperatures
+            DO ji = 1, npti
+               ! Variable used after iterations
+               ! Value must be frozen after convergence for MPP independance reason
+               IF ( .NOT. l_T_converged(ji) ) &
+                  t_i_1d(ji,nlay_i) = zindtbis(ji,jm_max(ji)) / zdiagbis(ji,jm_max(ji))
+            END DO
+
+            DO jm = nlay_i + nlay_s, nlay_s + 2, -1
+               DO ji = 1, npti
+                  jk = jm - nlay_s - 1
+                  IF ( .NOT. l_T_converged(ji) ) &
+                     t_i_1d(ji,jk) = ( zindtbis(ji,jm) - ztrid(ji,jm,3) * t_i_1d(ji,jk+1) ) / zdiagbis(ji,jm)
+               END DO
+            END DO
+
+            DO ji = 1, npti
+               ! Variables used after iterations
+               ! Value must be frozen after convergence for MPP independance reason
+               IF ( .NOT. l_T_converged(ji) ) THEN
+                  ! snow temperatures      
+                  IF( h_s_1d(ji) > 0._wp ) THEN
+                     t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
+                  ENDIF
+                  ! surface temperature
+                  ztsub(ji) = t_su_1d(ji)
+                  IF( t_su_1d(ji) < rt0 ) THEN
+                     t_su_1d(ji) = (  zindtbis(ji,jm_min(ji)) - ztrid(ji,jm_min(ji),3) *  &
+                        &           ( isnow(ji) * t_s_1d(ji,1) + ( 1._wp - isnow(ji) ) *  t_i_1d(ji,1) ) ) / zdiagbis(ji,jm_min(ji))
+                  ENDIF
+               ENDIF
+            END DO
+            !clem: in order to have several layers of snow, there is a missing loop here for t_s_1d(1:nlay_s-1)
+            !
+            !--------------------------------------------------------------
+            ! 9) Has the scheme converged?, end of the iterative procedure
+            !--------------------------------------------------------------
+            ! check that nowhere it has started to melt
+            ! zdti_max is a measure of error, it has to be under zdti_bnd
+
+            DO ji = 1, npti
+
+               zdti_max = 0._wp
+
+               IF ( .NOT. l_T_converged(ji) ) THEN
+
+                  t_su_1d(ji) = MAX( MIN( t_su_1d(ji) , rt0 ) , rt0 - 100._wp )
+                  zdti_max    = MAX( zdti_max, ABS( t_su_1d(ji) - ztsub(ji) ) )
+
+                  IF( h_s_1d(ji) > 0._wp ) THEN
+                     DO jk = 1, nlay_s
+                        t_s_1d(ji,jk) = MAX( MIN( t_s_1d(ji,jk), rt0 ), rt0 - 100._wp )
+                        zdti_max      = MAX ( zdti_max , ABS( t_s_1d(ji,jk) - ztsb(ji,jk) ) )
+                     END DO
+                  ENDIF
+
+                  DO jk = 1, nlay_i
+                     ztmelts       = -rTmlt * sz_i_1d(ji,jk) + rt0
+                     t_i_1d(ji,jk) =  MAX( MIN( t_i_1d(ji,jk), ztmelts ), rt0 - 100._wp )
+                     zdti_max      =  MAX( zdti_max, ABS( t_i_1d(ji,jk) - ztib(ji,jk) ) )
+                  END DO
+                  
+                  ! convergence test
+                  IF( ln_zdf_chkcvg ) THEN
+                     tice_cvgerr_1d(ji) = zdti_max
+                     tice_cvgstp_1d(ji) = REAL(iconv)
+                  ENDIF
+
+                  IF( zdti_max < zdti_bnd )   l_T_converged(ji) = .TRUE.
+
+               ENDIF
+
+            END DO
+
+         !----------------------------------------!
+         !                                        !
+         !      Conduction flux is on             !
+         !                                        !
+         !----------------------------------------!
+         !
+         ELSEIF( k_cnd == np_cnd_ON ) THEN
+            !
+            ! ==> we use a modified BL99 solver with conduction flux (qcn_ice) as forcing term
+            !
+            !----------------------------
+            ! 7) tridiagonal system terms
+            !----------------------------
+            ! layer denotes the number of the layer in the snow or in the ice
+            ! jm denotes the reference number of the equation in the tridiagonal
+            ! system, terms of tridiagonal system are indexed as following :
+            ! 1 is subdiagonal term, 2 is diagonal and 3 is superdiagonal one
+
+            ! ice interior terms (top equation has the same form as the others)
+            ztrid   (1:npti,:,:) = 0._wp
+            zindterm(1:npti,:)   = 0._wp
+            zindtbis(1:npti,:)   = 0._wp
+            zdiagbis(1:npti,:)   = 0._wp
+
+            DO jm = nlay_s + 2, nlay_s + nlay_i 
+               DO ji = 1, npti
+                  jk = jm - nlay_s - 1
+                  ztrid   (ji,jm,1) =       - zeta_i(ji,jk) *   zkappa_i(ji,jk-1)
+                  ztrid   (ji,jm,2) = 1._wp + zeta_i(ji,jk) * ( zkappa_i(ji,jk-1) + zkappa_i(ji,jk) )
+                  ztrid   (ji,jm,3) =       - zeta_i(ji,jk) *                       zkappa_i(ji,jk)
+                  zindterm(ji,jm)   = ztiold(ji,jk) + zeta_i(ji,jk) * zradab_i(ji,jk)
+               END DO
+            ENDDO
+
+            jm =  nlay_s + nlay_i + 1
+            DO ji = 1, npti
+               ! ice bottom term
+               ztrid   (ji,jm,1) =       - zeta_i(ji,nlay_i) *   zkappa_i(ji,nlay_i-1)   
+               ztrid   (ji,jm,2) = 1._wp + zeta_i(ji,nlay_i) * ( zkappa_i(ji,nlay_i-1) + zkappa_i(ji,nlay_i) * zg1 )
+               ztrid   (ji,jm,3) = 0._wp
+               zindterm(ji,jm)   = ztiold(ji,nlay_i) + zeta_i(ji,nlay_i) *  &
+                  &              ( zradab_i(ji,nlay_i) + zkappa_i(ji,nlay_i) * zg1 * t_bo_1d(ji) ) 
+            ENDDO
+
+            DO ji = 1, npti
+               !                               !---------------------!
+               IF( h_s_1d(ji) > 0._wp ) THEN   !  snow-covered cells !
+                  !                            !---------------------!
+                  ! snow interior terms (bottom equation has the same form as the others)
+                  DO jm = 3, nlay_s + 1
+                     jk = jm - 1
+                     ztrid   (ji,jm,1) =       - zeta_s(ji,jk) *   zkappa_s(ji,jk-1)
+                     ztrid   (ji,jm,2) = 1._wp + zeta_s(ji,jk) * ( zkappa_s(ji,jk-1) + zkappa_s(ji,jk) )
+                     ztrid   (ji,jm,3) =       - zeta_s(ji,jk) *                       zkappa_s(ji,jk)
+                     zindterm(ji,jm)   = ztsold(ji,jk) + zeta_s(ji,jk) * zradab_s(ji,jk)
+                  END DO
+                  
+                  ! case of only one layer in the ice (ice equation is altered)
+                  IF ( nlay_i == 1 ) THEN
+                     ztrid   (ji,nlay_s+2,3) = 0._wp
+                     zindterm(ji,nlay_s+2)   = zindterm(ji,nlay_s+2) + zeta_i(ji,1) * zkappa_i(ji,1) * t_bo_1d(ji) 
+                  ENDIF
+                  
+                  jm_min(ji) = 2
+                  jm_max(ji) = nlay_i + nlay_s + 1
+                  
+                  ! first layer of snow equation
+                  ztrid   (ji,2,1) = 0._wp
+                  ztrid   (ji,2,2) = 1._wp + zeta_s(ji,1) * zkappa_s(ji,1)
+                  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) + qcn_ice_1d(ji) ) 
+                  
+                  !                            !---------------------!
+               ELSE                            ! cells without snow  !
+                  !                            !---------------------!
+                  jm_min(ji) = nlay_s + 2
+                  jm_max(ji) = nlay_i + nlay_s + 1
+                  
+                  ! first layer of ice equation
+                  ztrid   (ji,jm_min(ji),1) = 0._wp
+                  ztrid   (ji,jm_min(ji),2) = 1._wp + zeta_i(ji,1) * zkappa_i(ji,1)  
+                  ztrid   (ji,jm_min(ji),3) =       - zeta_i(ji,1) * zkappa_i(ji,1)
+                  zindterm(ji,jm_min(ji))   = ztiold(ji,1) + zeta_i(ji,1) * ( zradab_i(ji,1) + qcn_ice_1d(ji) )
+                  
+                  ! case of only one layer in the ice (surface & ice equations are altered)
+                  IF( nlay_i == 1 ) THEN
+                     ztrid   (ji,jm_min(ji),1) = 0._wp
+                     ztrid   (ji,jm_min(ji),2) = 1._wp + zeta_i(ji,1) * zkappa_i(ji,1)
+                     ztrid   (ji,jm_min(ji),3) = 0._wp
+                     zindterm(ji,jm_min(ji))   = ztiold(ji,1) + zeta_i(ji,1) *  &
+                        &                                     ( zradab_i(ji,1) + zkappa_i(ji,1) * t_bo_1d(ji) + qcn_ice_1d(ji) )
+                  ENDIF
+                  
+               ENDIF
+               !
+               zindtbis(ji,jm_min(ji)) = zindterm(ji,jm_min(ji))
+               zdiagbis(ji,jm_min(ji)) = ztrid   (ji,jm_min(ji),2)
+               !
+            END DO
+            !
+            !------------------------------
+            ! 8) tridiagonal system solving
+            !------------------------------
+            ! Solve the tridiagonal system with Gauss elimination method.
+            ! Thomas algorithm, from Computational fluid Dynamics, J.D. ANDERSON, McGraw-Hill 1984
+            jm_maxt = 0
+            jm_mint = nlay_i+5
+            DO ji = 1, npti
+               jm_mint = MIN(jm_min(ji),jm_mint)
+               jm_maxt = MAX(jm_max(ji),jm_maxt)
+            END DO
+            
+            DO jk = jm_mint+1, jm_maxt
+               DO ji = 1, npti
+                  jm = MIN(MAX(jm_min(ji)+1,jk),jm_max(ji))
+                  zdiagbis(ji,jm) = ztrid   (ji,jm,2) - ztrid(ji,jm,1) * ztrid   (ji,jm-1,3) / zdiagbis(ji,jm-1)
+                  zindtbis(ji,jm) = zindterm(ji,jm)   - ztrid(ji,jm,1) * zindtbis(ji,jm-1)   / zdiagbis(ji,jm-1)
+               END DO
+            END DO
+            
+            ! ice temperatures
+            DO ji = 1, npti
+               ! Variable used after iterations
+               ! Value must be frozen after convergence for MPP independance reason
+               IF ( .NOT. l_T_converged(ji) ) &
+                  t_i_1d(ji,nlay_i) = zindtbis(ji,jm_max(ji)) / zdiagbis(ji,jm_max(ji))
+            END DO
+
+            DO jm = nlay_i + nlay_s, nlay_s + 2, -1
+               DO ji = 1, npti
+                  IF ( .NOT. l_T_converged(ji) ) THEN
+                     jk = jm - nlay_s - 1
+                     t_i_1d(ji,jk) = ( zindtbis(ji,jm) - ztrid(ji,jm,3) * t_i_1d(ji,jk+1) ) / zdiagbis(ji,jm)
+                  ENDIF
+               END DO
+            END DO
+            
+            ! snow temperatures      
+            DO ji = 1, npti
+               ! Variable used after iterations
+               ! Value must be frozen after convergence for MPP independance reason
+               IF ( .NOT. l_T_converged(ji) ) THEN
+                  IF( h_s_1d(ji) > 0._wp ) THEN
+                     t_s_1d(ji,nlay_s) = ( zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) * t_i_1d(ji,1) ) / zdiagbis(ji,nlay_s+1)
+                  ENDIF
+               ENDIF
+            END DO
+            !clem: in order to have several layers of snow, there is a missing loop here for t_s_1d(1:nlay_s-1)
+            !
+            !--------------------------------------------------------------
+            ! 9) Has the scheme converged?, end of the iterative procedure
+            !--------------------------------------------------------------
+            ! check that nowhere it has started to melt
+            ! zdti_max is a measure of error, it has to be under zdti_bnd
+
+            DO ji = 1, npti
+
+               zdti_max = 0._wp
+
+               IF ( .NOT. l_T_converged(ji) ) THEN
+
+                  IF( h_s_1d(ji) > 0._wp ) THEN
+                     DO jk = 1, nlay_s
+                        t_s_1d(ji,jk) = MAX( MIN( t_s_1d(ji,jk), rt0 ), rt0 - 100._wp )
+                        zdti_max      = MAX ( zdti_max , ABS( t_s_1d(ji,jk) - ztsb(ji,jk) ) )
+                     END DO
+                  ENDIF
+
+                  DO jk = 1, nlay_i
+                     ztmelts       = -rTmlt * sz_i_1d(ji,jk) + rt0 
+                     t_i_1d(ji,jk) =  MAX( MIN( t_i_1d(ji,jk), ztmelts ), rt0 - 100._wp )
+                     zdti_max      =  MAX ( zdti_max, ABS( t_i_1d(ji,jk) - ztib(ji,jk) ) )
+                  END DO
+
+                  ! convergence test
+                  IF( ln_zdf_chkcvg ) THEN
+                     tice_cvgerr_1d(ji) = zdti_max
+                     tice_cvgstp_1d(ji) = REAL(iconv)
+                  ENDIF
+
+                  IF( zdti_max < zdti_bnd )   l_T_converged(ji) = .TRUE.
+
+               ENDIF
+
+            END DO
+
+         ENDIF ! k_cnd
+
+      END DO  ! End of the do while iterative procedure
+      !
+      !-----------------------------
+      ! 10) Fluxes at the interfaces
+      !-----------------------------
+      !
+      ! --- calculate conduction fluxes (positive downward)
+      !     bottom ice conduction flux
+      DO ji = 1, npti
+         qcn_ice_bot_1d(ji) = - zkappa_i(ji,nlay_i) * zg1 * ( t_bo_1d(ji ) - t_i_1d (ji,nlay_i) )
+      END DO
+      !     surface ice conduction flux
+      IF( k_cnd == np_cnd_OFF .OR. k_cnd == np_cnd_EMU ) THEN
+         !
+         DO ji = 1, npti
+            qcn_ice_top_1d(ji) = -           isnow(ji)   * zkappa_s(ji,0) * zg1s * ( t_s_1d(ji,1) - t_su_1d(ji) ) &
+               &                 - ( 1._wp - isnow(ji) ) * zkappa_i(ji,0) * zg1  * ( t_i_1d(ji,1) - t_su_1d(ji) )
+         END DO
+         !
+      ELSEIF( k_cnd == np_cnd_ON ) THEN
+         !
+         DO ji = 1, npti
+            qcn_ice_top_1d(ji) = qcn_ice_1d(ji)
+         END DO
+         !
+      ENDIF
+      !     surface ice temperature
+      IF( k_cnd == np_cnd_ON .AND. ln_cndemulate ) THEN
+         !
+         DO ji = 1, npti
+            t_su_1d(ji) = ( qcn_ice_top_1d(ji) +          isnow(ji)   * zkappa_s(ji,0) * zg1s * t_s_1d(ji,1) + &
+               &                                ( 1._wp - isnow(ji) ) * zkappa_i(ji,0) * zg1  * t_i_1d(ji,1) ) &
+               &          / MAX( epsi10, isnow(ji) * zkappa_s(ji,0) * zg1s + ( 1._wp - isnow(ji) ) * zkappa_i(ji,0) * zg1 )
+            t_su_1d(ji) = MAX( MIN( t_su_1d(ji), rt0 ), rt0 - 100._wp )  ! cap t_su
+         END DO
+         !
+      ENDIF
+      !
+      ! --- Diagnose the heat loss due to changing non-solar / conduction flux --- !
+      !
+      IF( k_cnd == np_cnd_OFF .OR. k_cnd == np_cnd_EMU ) THEN
+         !
+         DO ji = 1, npti
+            hfx_err_dif_1d(ji) = hfx_err_dif_1d(ji) - ( qns_ice_1d(ji) - zqns_ice_b(ji) ) * a_i_1d(ji) 
+         END DO
+         !
+      ENDIF
+      !
+      ! --- Diagnose the heat loss due to non-fully converged temperature solution (should not be above 10-4 W-m2) --- !
+      !
+      IF( k_cnd == np_cnd_OFF .OR. k_cnd == np_cnd_ON ) THEN
+         
+         CALL ice_var_enthalpy       
+         
+         ! zhfx_err = correction on the diagnosed heat flux due to non-convergence of the algorithm used to solve heat equation
+         DO ji = 1, npti
+            zdq = - zq_ini(ji) + ( SUM( e_i_1d(ji,1:nlay_i) ) * h_i_1d(ji) * r1_nlay_i +  &
+               &                   SUM( e_s_1d(ji,1:nlay_s) ) * h_s_1d(ji) * r1_nlay_s )
+            
+            IF( k_cnd == np_cnd_OFF ) THEN
+               
+               IF( t_su_1d(ji) < rt0 ) THEN  ! case T_su < 0degC
+                  zhfx_err = ( qns_ice_1d(ji)     + qsr_ice_1d(ji)     - zradtr_i(ji,nlay_i) - qcn_ice_bot_1d(ji)  &
+                     &       + zdq * r1_rdtice ) * a_i_1d(ji)
+               ELSE                          ! case T_su = 0degC
+                  zhfx_err = ( qcn_ice_top_1d(ji) + qtr_ice_top_1d(ji) - zradtr_i(ji,nlay_i) - qcn_ice_bot_1d(ji)  &
+                     &       + zdq * r1_rdtice ) * a_i_1d(ji)
+               ENDIF
+               
+            ELSEIF( k_cnd == np_cnd_ON ) THEN
+            
+               zhfx_err    = ( qcn_ice_top_1d(ji) + qtr_ice_top_1d(ji) - zradtr_i(ji,nlay_i) - qcn_ice_bot_1d(ji)  &
+                  &          + zdq * r1_rdtice ) * a_i_1d(ji)
+            
+            ENDIF
+            !
+            ! total heat sink to be sent to the ocean
+            hfx_err_dif_1d(ji) = hfx_err_dif_1d(ji) + zhfx_err
+            !
+            ! hfx_dif = Heat flux diagnostic of sensible heat used to warm/cool ice in W.m-2   
+            hfx_dif_1d(ji) = hfx_dif_1d(ji) - zdq * r1_rdtice * a_i_1d(ji)
+            !
+         END DO
+         !
+      ENDIF
+      !
+      !--------------------------------------------------------------------
+      ! 11) reset inner snow and ice temperatures, update conduction fluxes
+      !--------------------------------------------------------------------
+      ! effective conductivity and 1st layer temperature (needed by Met Office)
+      ! this is a conductivity at mid-layer, hence the factor 2
+      DO ji = 1, npti
+         IF( h_i_1d(ji) >= zhi_ssl ) THEN
+            cnd_ice_1d(ji) = 2._wp * zkappa_comb(ji)
+            !!cnd_ice_1d(ji) = 2._wp * zkappa_i(ji,0)
+         ELSE
+            cnd_ice_1d(ji) = 2._wp * ztcond_i(ji,0) / zhi_ssl ! cnd_ice is capped by: cond_i/zhi_ssl
+         ENDIF
+         t1_ice_1d(ji) = isnow(ji) * t_s_1d(ji,1) + ( 1._wp - isnow(ji) ) * t_i_1d(ji,1)
+      END DO
+      !
+      IF( k_cnd == np_cnd_EMU ) THEN
+         ! Restore temperatures to their initial values
+         t_s_1d    (1:npti,:) = ztsold        (1:npti,:)
+         t_i_1d    (1:npti,:) = ztiold        (1:npti,:)
+         qcn_ice_1d(1:npti)   = qcn_ice_top_1d(1:npti)
+      ENDIF
+      !
+      ! --- SIMIP diagnostics
+      !
+      DO ji = 1, npti         
+         !--- Snow-ice interfacial temperature (diagnostic SIMIP)
+         IF( h_s_1d(ji) >= zhs_ssl ) THEN
+            t_si_1d(ji) = (   rn_cnd_s       * h_i_1d(ji) * r1_nlay_i * t_s_1d(ji,1)   &
+               &            + ztcond_i(ji,1) * h_s_1d(ji) * r1_nlay_s * t_i_1d(ji,1) ) &
+               &          / ( rn_cnd_s       * h_i_1d(ji) * r1_nlay_i &
+               &            + ztcond_i(ji,1) * h_s_1d(ji) * r1_nlay_s )
+         ELSE
+            t_si_1d(ji) = t_su_1d(ji)
+         ENDIF
+      END DO
+      !
+   END SUBROUTINE ice_thd_zdf_BL99
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option       Dummy Module             No SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icethd_zdf_BL99
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceupdate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceupdate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/iceupdate.F90	(revision 14097)
@@ -0,0 +1,468 @@
+MODULE iceupdate
+   !!======================================================================
+   !!                       ***  MODULE iceupdate   ***
+   !!  Sea-ice :   computation of the flux at the sea ice/ocean interface
+   !!======================================================================
+   !! History :  4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_update_alloc : allocate the iceupdate arrays
+   !!   ice_update_init  : initialisation
+   !!   ice_update_flx   : updates mass, heat and salt fluxes at the ocean surface
+   !!   ice_update_tau   : update i- and j-stresses, and its modulus at the ocean surface
+   !!----------------------------------------------------------------------
+   USE oce     , ONLY : sshn, sshb
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean domain
+   USE ice            ! sea-ice: variables
+   USE sbc_ice        ! Surface boundary condition: ice   fields
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbccpl         ! Surface boundary condition: coupled interface
+   USE icealb         ! sea-ice: albedo parameters
+   USE traqsr         ! add penetration of solar flux in the calculation of heat budget
+   USE icectl         ! sea-ice: control prints
+   USE zdfdrg  , ONLY : ln_drgice_imp
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_update_init   ! called by ice_init
+   PUBLIC   ice_update_flx    ! called by ice_stp
+   PUBLIC   ice_update_tau    ! called by ice_stp
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   utau_oce, vtau_oce   ! air-ocean surface i- & j-stress     [N/m2]
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tmod_io              ! modulus of the ice-ocean velocity   [m/s]
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION ice_update_alloc()
+      !!-------------------------------------------------------------------
+      !!             ***  ROUTINE ice_update_alloc ***
+      !!-------------------------------------------------------------------
+      ALLOCATE( utau_oce(jpi,jpj), vtau_oce(jpi,jpj), tmod_io(jpi,jpj), STAT=ice_update_alloc )
+      !
+      CALL mpp_sum( 'iceupdate', ice_update_alloc )
+      IF( ice_update_alloc /= 0 )   CALL ctl_stop( 'STOP', 'ice_update_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION ice_update_alloc
+
+
+   SUBROUTINE ice_update_flx( kt )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_update_flx ***
+      !!  
+      !! ** Purpose :   Update the surface ocean boundary condition for heat 
+      !!                salt and mass over areas where sea-ice is non-zero
+      !!         
+      !! ** Action  : - computes the heat and freshwater/salt fluxes
+      !!                at the ice-ocean interface.
+      !!              - Update the ocean sbc
+      !!     
+      !! ** Outputs : - qsr     : sea heat flux:     solar 
+      !!              - qns     : sea heat flux: non solar
+      !!              - emp     : freshwater budget: volume flux 
+      !!              - sfx     : salt flux 
+      !!              - fr_i    : ice fraction
+      !!              - tn_ice  : sea-ice surface temperature
+      !!              - alb_ice : sea-ice albedo (recomputed only for coupled mode)
+      !!
+      !! 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, jk   ! dummy loop indices
+      REAL(wp) ::   zqsr             ! New solar flux received by the ocean
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d                  ! 2D workspace
+      !!---------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('ice_update')
+
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_update_flx: update fluxes (mass, salt and heat) at the ice-ocean interface'
+         WRITE(numout,*)'~~~~~~~~~~~~~~'
+      ENDIF
+
+      ! Net heat flux on top of the ice-ocean (W.m-2)
+      !----------------------------------------------
+      qt_atm_oi(:,:) = qns_tot(:,:) + qsr_tot(:,:) 
+
+      ! --- case we bypass ice thermodynamics --- !
+      IF( .NOT. ln_icethd ) THEN   ! we suppose ice is impermeable => ocean is isolated from atmosphere
+         qt_atm_oi  (:,:)   = ( 1._wp - at_i_b(:,:) ) * ( qns_oce(:,:) + qsr_oce(:,:) ) + qemp_oce(:,:)
+         qt_oce_ai  (:,:)   = ( 1._wp - at_i_b(:,:) ) *   qns_oce(:,:)                  + qemp_oce(:,:)
+         emp_ice    (:,:)   = 0._wp
+         qemp_ice   (:,:)   = 0._wp
+         qevap_ice  (:,:,:) = 0._wp
+      ENDIF
+      
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+
+            ! Solar heat flux reaching the ocean (max) = zqsr (W.m-2) 
+            !---------------------------------------------------
+            zqsr = qsr_tot(ji,jj) - SUM( a_i_b(ji,jj,:) * ( qsr_ice(ji,jj,:) - qtr_ice_bot(ji,jj,:) ) )
+
+            ! Total heat flux reaching the ocean = qt_oce_ai (W.m-2) 
+            !---------------------------------------------------
+            qt_oce_ai(ji,jj) = qt_atm_oi(ji,jj) - hfx_sum(ji,jj) - hfx_bom(ji,jj) - hfx_bog(ji,jj) &
+               &                                - hfx_dif(ji,jj) - hfx_opw(ji,jj) - hfx_snw(ji,jj) &
+               &                                + hfx_thd(ji,jj) + hfx_dyn(ji,jj) + hfx_res(ji,jj) &
+               &                                + hfx_sub(ji,jj) - SUM( qevap_ice(ji,jj,:) * a_i_b(ji,jj,:) ) + hfx_spr(ji,jj)                 
+            
+            ! New qsr and qns used to compute the oceanic heat flux at the next time step
+            !----------------------------------------------------------------------------
+            ! if warming and some ice remains, then we suppose that the whole solar flux has been consumed to melt the ice
+            ! else ( cooling or no ice left ), then we suppose that     no    solar flux has been consumed
+            !
+            IF( fhld(ji,jj) > 0._wp .AND. at_i(ji,jj) > 0._wp ) THEN   !-- warming and some ice remains
+               !                                        solar flux transmitted thru the 1st level of the ocean (i.e. not used by sea-ice)
+               qsr(ji,jj) = ( 1._wp - at_i_b(ji,jj) ) * qsr_oce(ji,jj) * ( 1._wp - frq_m(ji,jj) ) &
+                  !                                   + solar flux transmitted thru ice and the 1st ocean level (also not used by sea-ice)
+                  &             + SUM( a_i_b(ji,jj,:) * qtr_ice_bot(ji,jj,:) ) * ( 1._wp - frq_m(ji,jj) )
+               !
+            ELSE                                                       !-- cooling or no ice left
+               qsr(ji,jj) = zqsr
+            ENDIF
+            !
+            ! the non-solar is simply derived from the solar flux
+            qns(ji,jj) = qt_oce_ai(ji,jj) - zqsr              
+
+            ! Mass flux at the atm. surface       
+            !-----------------------------------
+            wfx_sub(ji,jj) = wfx_snw_sub(ji,jj) + wfx_ice_sub(ji,jj)
+
+            ! Mass flux at the ocean surface      
+            !------------------------------------
+            ! ice-ocean  mass flux
+            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) + wfx_lam(ji,jj) + wfx_pnd(ji,jj)
+
+            ! snw-ocean mass flux
+            wfx_snw(ji,jj) = wfx_snw_sni(ji,jj) + wfx_snw_dyn(ji,jj) + wfx_snw_sum(ji,jj)
+
+            ! total mass flux at the ocean/ice interface
+            fmmflx(ji,jj) =                - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_err_sub(ji,jj)   ! ice-ocean mass flux saved at least for biogeochemical model
+            emp   (ji,jj) = emp_oce(ji,jj) - wfx_ice(ji,jj) - wfx_snw(ji,jj) - wfx_err_sub(ji,jj)   ! atm-ocean + ice-ocean mass flux
+
+            ! Salt flux at the ocean surface      
+            !------------------------------------------
+            sfx(ji,jj) = sfx_bog(ji,jj) + sfx_bom(ji,jj) + sfx_sum(ji,jj) + sfx_sni(ji,jj) + sfx_opw(ji,jj)   &
+               &       + sfx_res(ji,jj) + sfx_dyn(ji,jj) + sfx_bri(ji,jj) + sfx_sub(ji,jj) + sfx_lam(ji,jj)
+            
+            ! Mass of snow and ice per unit area   
+            !----------------------------------------
+            snwice_mass_b(ji,jj) = snwice_mass(ji,jj)       ! save mass from the previous ice time step
+            !                                               ! new mass per unit area
+            snwice_mass  (ji,jj) = tmask(ji,jj,1) * ( rhos * vt_s(ji,jj) + rhoi * vt_i(ji,jj)  ) 
+            !                                               ! time evolution of snow+ice mass
+            snwice_fmass (ji,jj) = ( snwice_mass(ji,jj) - snwice_mass_b(ji,jj) ) * r1_rdtice
+            
+         END DO
+      END DO
+
+      ! Storing the transmitted variables
+      !----------------------------------
+      fr_i  (:,:)   = at_i(:,:)             ! Sea-ice fraction            
+      tn_ice(:,:,:) = t_su(:,:,:)           ! Ice surface temperature                      
+
+      ! Snow/ice albedo (only if sent to coupler, useless in forced mode)
+      !------------------------------------------------------------------
+      CALL ice_alb( t_su, h_i, h_s, ln_pnd_alb, a_ip_eff, h_ip, cloud_fra, alb_ice ) ! ice albedo
+
+      !
+      IF( lrst_ice ) THEN                       !* write snwice_mass fields in the restart file
+         CALL update_rst( 'WRITE', kt )
+      ENDIF
+      !
+      ! output all fluxes
+      !------------------
+      !
+      ! --- salt fluxes [kg/m2/s] --- !
+      !                           ! sfxice =  sfxbog + sfxbom + sfxsum + sfxsni + sfxopw + sfxres + sfxdyn + sfxbri + sfxsub + sfxlam
+      IF( iom_use('sfxice'  ) )   CALL iom_put( 'sfxice', sfx     * 1.e-03 )   ! salt flux from total ice growth/melt
+      IF( iom_use('sfxbog'  ) )   CALL iom_put( 'sfxbog', sfx_bog * 1.e-03 )   ! salt flux from bottom growth
+      IF( iom_use('sfxbom'  ) )   CALL iom_put( 'sfxbom', sfx_bom * 1.e-03 )   ! salt flux from bottom melting
+      IF( iom_use('sfxsum'  ) )   CALL iom_put( 'sfxsum', sfx_sum * 1.e-03 )   ! salt flux from surface melting
+      IF( iom_use('sfxlam'  ) )   CALL iom_put( 'sfxlam', sfx_lam * 1.e-03 )   ! salt flux from lateral melting
+      IF( iom_use('sfxsni'  ) )   CALL iom_put( 'sfxsni', sfx_sni * 1.e-03 )   ! salt flux from snow ice formation
+      IF( iom_use('sfxopw'  ) )   CALL iom_put( 'sfxopw', sfx_opw * 1.e-03 )   ! salt flux from open water formation
+      IF( iom_use('sfxdyn'  ) )   CALL iom_put( 'sfxdyn', sfx_dyn * 1.e-03 )   ! salt flux from ridging rafting
+      IF( iom_use('sfxbri'  ) )   CALL iom_put( 'sfxbri', sfx_bri * 1.e-03 )   ! salt flux from brines
+      IF( iom_use('sfxres'  ) )   CALL iom_put( 'sfxres', sfx_res * 1.e-03 )   ! salt flux from undiagnosed processes
+      IF( iom_use('sfxsub'  ) )   CALL iom_put( 'sfxsub', sfx_sub * 1.e-03 )   ! salt flux from sublimation
+
+      ! --- mass fluxes [kg/m2/s] --- !
+      CALL iom_put( 'emp_oce', emp_oce )   ! emp over ocean (taking into account the snow blown away from the ice)
+      CALL iom_put( 'emp_ice', emp_ice )   ! emp over ice   (taking into account the snow blown away from the ice)
+
+      !                           ! vfxice = vfxbog + vfxbom + vfxsum + vfxsni + vfxopw + vfxdyn + vfxres + vfxlam + vfxpnd
+      CALL iom_put( 'vfxice'    , wfx_ice     )   ! mass flux from total ice growth/melt
+      CALL iom_put( 'vfxbog'    , wfx_bog     )   ! mass flux from bottom growth
+      CALL iom_put( 'vfxbom'    , wfx_bom     )   ! mass flux from bottom melt 
+      CALL iom_put( 'vfxsum'    , wfx_sum     )   ! mass flux from surface melt 
+      CALL iom_put( 'vfxlam'    , wfx_lam     )   ! mass flux from lateral melt 
+      CALL iom_put( 'vfxsni'    , wfx_sni     )   ! mass flux from snow-ice formation
+      CALL iom_put( 'vfxopw'    , wfx_opw     )   ! mass flux from growth in open water
+      CALL iom_put( 'vfxdyn'    , wfx_dyn     )   ! mass flux from dynamics (ridging)
+      CALL iom_put( 'vfxres'    , wfx_res     )   ! mass flux from undiagnosed processes 
+      CALL iom_put( 'vfxpnd'    , wfx_pnd     )   ! mass flux from melt ponds
+      CALL iom_put( 'vfxsub'    , wfx_ice_sub )   ! mass flux from ice sublimation (ice-atm.)
+      CALL iom_put( 'vfxsub_err', wfx_err_sub )   ! "excess" of sublimation sent to ocean      
+
+      IF ( iom_use( 'vfxthin' ) ) THEN   ! mass flux from ice growth in open water + thin ice (<20cm) => comparable to observations  
+         WHERE( hm_i(:,:) < 0.2 .AND. hm_i(:,:) > 0. ) ; z2d = wfx_bog
+         ELSEWHERE                                     ; z2d = 0._wp
+         END WHERE
+         CALL iom_put( 'vfxthin', wfx_opw + z2d )
+      ENDIF
+
+      !                            ! vfxsnw = vfxsnw_sni + vfxsnw_dyn + vfxsnw_sum
+      CALL iom_put( 'vfxsnw'     , wfx_snw     )   ! mass flux from total snow growth/melt
+      CALL iom_put( 'vfxsnw_sum' , wfx_snw_sum )   ! mass flux from snow melt at the surface
+      CALL iom_put( 'vfxsnw_sni' , wfx_snw_sni )   ! mass flux from snow melt during snow-ice formation 
+      CALL iom_put( 'vfxsnw_dyn' , wfx_snw_dyn )   ! mass flux from dynamics (ridging) 
+      CALL iom_put( 'vfxsnw_sub' , wfx_snw_sub )   ! mass flux from snow sublimation (ice-atm.) 
+      CALL iom_put( 'vfxsnw_pre' , wfx_spr     )   ! snow precip
+
+      ! --- heat fluxes [W/m2] --- !
+      !                              ! qt_atm_oi - qt_oce_ai = hfxdhc - ( dihctrp + dshctrp )
+      IF( iom_use('qsr_oce'    ) )   CALL iom_put( 'qsr_oce'    , qsr_oce * ( 1._wp - at_i_b )                               )   !     solar flux at ocean surface
+      IF( iom_use('qns_oce'    ) )   CALL iom_put( 'qns_oce'    , qns_oce * ( 1._wp - at_i_b ) + qemp_oce                    )   ! 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 ) + qemp_ice                   )   ! non-solar flux at ice surface
+      IF( iom_use('qtr_ice_bot') )   CALL iom_put( 'qtr_ice_bot', SUM( qtr_ice_bot * a_i_b, dim=3 )                          )   !     solar flux transmitted thru ice
+      IF( iom_use('qtr_ice_top') )   CALL iom_put( 'qtr_ice_top', SUM( qtr_ice_top * a_i_b, dim=3 )                          )   !     solar flux transmitted thru ice surface
+      IF( iom_use('qt_oce'     ) )   CALL iom_put( 'qt_oce'     ,      ( qsr_oce + qns_oce ) * ( 1._wp - at_i_b ) + qemp_oce )
+      IF( iom_use('qt_ice'     ) )   CALL iom_put( 'qt_ice'     , SUM( ( qns_ice + qsr_ice ) * a_i_b, dim=3 )     + qemp_ice )
+      IF( iom_use('qt_oce_ai'  ) )   CALL iom_put( 'qt_oce_ai'  , qt_oce_ai * tmask(:,:,1)                                   )   ! total heat flux at the ocean   surface: interface oce-(ice+atm) 
+      IF( iom_use('qt_atm_oi'  ) )   CALL iom_put( 'qt_atm_oi'  , qt_atm_oi * tmask(:,:,1)                                   )   ! total heat flux at the oce-ice surface: interface atm-(ice+oce) 
+      IF( iom_use('qemp_oce'   ) )   CALL iom_put( 'qemp_oce'   , qemp_oce                                                   )   ! Downward Heat Flux from E-P over ocean
+      IF( iom_use('qemp_ice'   ) )   CALL iom_put( 'qemp_ice'   , qemp_ice                                                   )   ! Downward Heat Flux from E-P over ice
+
+      ! heat fluxes from ice transformations
+      !                            ! hfxdhc = hfxbog + hfxbom + hfxsum + hfxopw + hfxdif + hfxsnw - ( hfxthd + hfxdyn + hfxres + hfxsub + hfxspr )
+      CALL iom_put ('hfxbog'     , hfx_bog     )   ! heat flux used for ice bottom growth 
+      CALL iom_put ('hfxbom'     , hfx_bom     )   ! heat flux used for ice bottom melt
+      CALL iom_put ('hfxsum'     , hfx_sum     )   ! heat flux used for ice surface melt
+      CALL iom_put ('hfxopw'     , hfx_opw     )   ! heat flux used for ice formation in open water
+      CALL iom_put ('hfxdif'     , hfx_dif     )   ! heat flux used for ice temperature change
+      CALL iom_put ('hfxsnw'     , hfx_snw     )   ! heat flux used for snow melt 
+      CALL iom_put ('hfxerr'     , hfx_err_dif )   ! heat flux error after heat diffusion
+
+      ! heat fluxes associated with mass exchange (freeze/melt/precip...)
+      CALL iom_put ('hfxthd'     , hfx_thd     )   !  
+      CALL iom_put ('hfxdyn'     , hfx_dyn     )   !  
+      CALL iom_put ('hfxres'     , hfx_res     )   !  
+      CALL iom_put ('hfxsub'     , hfx_sub     )   !  
+      CALL iom_put ('hfxspr'     , hfx_spr     )   ! Heat flux from snow precip heat content 
+
+      ! other heat fluxes
+      IF( iom_use('hfxsensib'  ) )   CALL iom_put( 'hfxsensib'  ,     -qsb_ice_bot * at_i_b         )   ! Sensible oceanic heat flux
+      IF( iom_use('hfxcndbot'  ) )   CALL iom_put( 'hfxcndbot'  , SUM( qcn_ice_bot * a_i_b, dim=3 ) )   ! Bottom conduction flux
+      IF( iom_use('hfxcndtop'  ) )   CALL iom_put( 'hfxcndtop'  , SUM( qcn_ice_top * a_i_b, dim=3 ) )   ! Surface conduction flux
+
+      ! controls
+      !---------
+#if ! defined key_agrif
+      IF( ln_icediachk )   CALL ice_cons_final('iceupdate')                                       ! conservation
+#endif
+      IF( ln_icectl    )   CALL ice_prt       (kt, iiceprt, jiceprt, 3, 'Final state ice_update') ! prints
+      IF( ln_ctl       )   CALL ice_prt3D     ('iceupdate')                                       ! prints
+      IF( ln_timing    )   CALL timing_stop   ('ice_update')                                      ! timing
+      !
+   END SUBROUTINE ice_update_flx
+
+
+   SUBROUTINE ice_update_tau( kt, pu_oce, pv_oce )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_update_tau ***
+      !!  
+      !! ** Purpose : Update the ocean surface stresses due to the ice
+      !!         
+      !! ** Action  : * at each ice time step (every nn_fsbc time step):
+      !!                - compute the modulus of ice-ocean relative velocity 
+      !!                  (*rho*Cd) at T-point (C-grid) or I-point (B-grid)
+      !!                      tmod_io = rhoco * | U_ice-U_oce |
+      !!                - update the modulus of stress at ocean surface
+      !!                      taum = (1-a) * taum + a * tmod_io * | U_ice-U_oce |
+      !!              * at each ocean time step (every kt): 
+      !!                  compute linearized ice-ocean stresses as
+      !!                      Utau = tmod_io * | U_ice - pU_oce |
+      !!                using instantaneous current ocean velocity (usually before)
+      !!
+      !!    NB: - ice-ocean rotation angle no more allowed
+      !!        - here we make an approximation: taum is only computed every ice time step
+      !!          This avoids mutiple average to pass from T -> U,V grids and next from U,V grids 
+      !!          to T grid. taum is used in TKE and GLS, which should not be too sensitive to this approximaton...
+      !!
+      !! ** Outputs : - utau, vtau   : surface ocean i- and j-stress (u- & v-pts) updated with ice-ocean fluxes
+      !!              - taum         : modulus of the surface ocean stress (T-point) updated with ice-ocean fluxes
+      !!---------------------------------------------------------------------
+      INTEGER ,                     INTENT(in) ::   kt               ! ocean time-step index
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pu_oce, pv_oce   ! surface ocean currents
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zat_u, zutau_ice, zu_t, zmodt   ! local scalar
+      REAL(wp) ::   zat_v, zvtau_ice, zv_t, zrhoco  !   -      -
+      REAL(wp) ::   zflagi                          !   -      -
+      !!---------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('ice_update_tau')
+
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'ice_update_tau: update stress at the ice-ocean interface'
+         WRITE(numout,*)'~~~~~~~~~~~~~~'
+      ENDIF
+
+      zrhoco = rau0 * rn_cio
+      !
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN     !==  Ice time-step only  ==!   (i.e. surface module time-step)
+         DO jj = 2, jpjm1                             !* update the modulus of stress at ocean surface (T-point)
+            DO ji = fs_2, fs_jpim1
+               !                                               ! 2*(U_ice-U_oce) at T-point
+               zu_t = u_ice(ji,jj) + u_ice(ji-1,jj) - u_oce(ji,jj) - u_oce(ji-1,jj)   
+               zv_t = v_ice(ji,jj) + v_ice(ji,jj-1) - v_oce(ji,jj) - v_oce(ji,jj-1) 
+               !                                              ! |U_ice-U_oce|^2
+               zmodt =  0.25_wp * (  zu_t * zu_t + zv_t * zv_t  )
+               !                                               ! update the ocean stress modulus
+               taum(ji,jj) = ( 1._wp - at_i(ji,jj) ) * taum(ji,jj) + at_i(ji,jj) * zrhoco * zmodt
+               tmod_io(ji,jj) = zrhoco * SQRT( zmodt )          ! rhoco * |U_ice-U_oce| at T-point
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'iceupdate', taum, 'T', 1., tmod_io, 'T', 1. )
+         !
+         utau_oce(:,:) = utau(:,:)                    !* save the air-ocean stresses at ice time-step
+         vtau_oce(:,:) = vtau(:,:)
+         !
+      ENDIF
+      !
+      !                                      !==  every ocean time-step  ==!
+      IF ( ln_drgice_imp ) THEN
+         ! Save drag with right sign to update top drag in the ocean implicit friction 
+         rCdU_ice(:,:) = -r1_rau0 * tmod_io(:,:) * at_i(:,:) * tmask(:,:,1) 
+         zflagi = 0._wp
+      ELSE
+         zflagi = 1._wp
+      ENDIF
+      !
+      DO jj = 2, jpjm1                                !* update the stress WITHOUT an ice-ocean rotation angle
+         DO ji = fs_2, fs_jpim1   ! Vect. Opt.   
+            ! ice area at u and v-points 
+            zat_u  = ( at_i(ji,jj) * tmask(ji,jj,1) + at_i (ji+1,jj    ) * tmask(ji+1,jj  ,1) )  &
+               &     / MAX( 1.0_wp , tmask(ji,jj,1) + tmask(ji+1,jj  ,1) )
+            zat_v  = ( at_i(ji,jj) * tmask(ji,jj,1) + at_i (ji  ,jj+1  ) * tmask(ji  ,jj+1,1) )  &
+               &     / MAX( 1.0_wp , tmask(ji,jj,1) + tmask(ji  ,jj+1,1) )
+            !                                                   ! linearized quadratic drag formulation
+            zutau_ice   = 0.5_wp * ( tmod_io(ji,jj) + tmod_io(ji+1,jj) ) * ( u_ice(ji,jj) - zflagi * pu_oce(ji,jj) )
+            zvtau_ice   = 0.5_wp * ( tmod_io(ji,jj) + tmod_io(ji,jj+1) ) * ( v_ice(ji,jj) - zflagi * pv_oce(ji,jj) )
+            !                                                   ! stresses at the ocean surface
+            utau(ji,jj) = ( 1._wp - zat_u ) * utau_oce(ji,jj) + zat_u * zutau_ice
+            vtau(ji,jj) = ( 1._wp - zat_v ) * vtau_oce(ji,jj) + zat_v * zvtau_ice
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'iceupdate', utau, 'U', -1., vtau, 'V', -1. )   ! lateral boundary condition
+      !
+      IF( ln_timing )   CALL timing_stop('ice_update_tau')
+      !  
+   END SUBROUTINE ice_update_tau
+
+
+   SUBROUTINE ice_update_init
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_update_init  ***
+      !!             
+      !! ** Purpose :   allocate ice-ocean stress fields and read restarts
+      !!                containing the snow & ice mass
+      !!
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk               ! dummy loop indices
+      REAL(wp) ::   zcoefu, zcoefv, zcoeff   ! local scalar
+      !!-------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'ice_update_init: ice-ocean stress init'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~~'
+      !
+      !                                      ! allocate ice_update array
+      IF( ice_update_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'ice_update_init : unable to allocate standard arrays' )
+      !
+      CALL update_rst( 'READ' )  !* read or initialize all required files
+      !
+   END SUBROUTINE ice_update_init
+
+
+   SUBROUTINE update_rst( cdrw, kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rhg_evp_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write RHG file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*) , INTENT(in) ::   cdrw   ! 'READ'/'WRITE' flag
+      INTEGER, OPTIONAL, INTENT(in) ::   kt     ! ice time-step
+      !
+      INTEGER  ::   iter   ! local integer
+      INTEGER  ::   id1    ! local integer
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialize
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            id1 = iom_varid( numrir, 'snwice_mass' , ldstop = .FALSE. )
+            !
+            IF( id1 > 0 ) THEN                       ! fields exist
+               CALL iom_get( numrir, jpdom_autoglo, 'snwice_mass'  , snwice_mass   )
+               CALL iom_get( numrir, jpdom_autoglo, 'snwice_mass_b', snwice_mass_b )
+            ELSE                                     ! start from rest
+               IF(lwp) WRITE(numout,*) '   ==>>   previous run without snow-ice mass output then set it'
+               snwice_mass  (:,:) = tmask(:,:,1) * ( rhos * vt_s(:,:) + rhoi * vt_i(:,:) )
+               snwice_mass_b(:,:) = snwice_mass(:,:)
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*) '   ==>>   start from rest: set the snow-ice mass'
+            snwice_mass  (:,:) = tmask(:,:,1) * ( rhos * vt_s(:,:) + rhoi * vt_i(:,:) )
+            snwice_mass_b(:,:) = snwice_mass(:,:)
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- update-rst ----'
+         iter = kt + nn_fsbc - 1             ! ice restarts are written at kt == nitrst - nn_fsbc + 1
+         !
+         CALL iom_rstput( iter, nitrst, numriw, 'snwice_mass'  , snwice_mass   )
+         CALL iom_rstput( iter, nitrst, numriw, 'snwice_mass_b', snwice_mass_b )
+         !
+      ENDIF
+      !
+   END SUBROUTINE update_rst
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Dummy module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif 
+
+   !!======================================================================
+END MODULE iceupdate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icevar.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icevar.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icevar.F90	(revision 14097)
@@ -0,0 +1,1376 @@
+MODULE icevar
+   !!======================================================================
+   !!                       ***  MODULE icevar ***
+   !!   sea-ice:  series of functions to transform or compute ice variables
+   !!======================================================================
+   !! History :   -   !  2006-01  (M. Vancoppenolle) Original code
+   !!            4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!
+   !!                 There are three sets of variables
+   !!                 VGLO : global variables of the model
+   !!                        - v_i (jpi,jpj,jpl)
+   !!                        - v_s (jpi,jpj,jpl)
+   !!                        - a_i (jpi,jpj,jpl)
+   !!                        - t_s (jpi,jpj,jpl)
+   !!                        - e_i (jpi,jpj,nlay_i,jpl)
+   !!                        - e_s (jpi,jpj,nlay_s,jpl)
+   !!                        - sv_i(jpi,jpj,jpl)
+   !!                        - oa_i(jpi,jpj,jpl)
+   !!                 VEQV : equivalent variables sometimes used in the model
+   !!                        - h_i(jpi,jpj,jpl)
+   !!                        - h_s(jpi,jpj,jpl)
+   !!                        - t_i(jpi,jpj,nlay_i,jpl)
+   !!                        ...
+   !!                 VAGG : aggregate variables, averaged/summed over all
+   !!                        thickness categories
+   !!                        - vt_i(jpi,jpj)
+   !!                        - vt_s(jpi,jpj)
+   !!                        - at_i(jpi,jpj)
+   !!                        - st_i(jpi,jpj)
+   !!                        - et_s(jpi,jpj)  total snow heat content
+   !!                        - et_i(jpi,jpj)  total ice thermal content 
+   !!                        - sm_i(jpi,jpj)  mean ice salinity
+   !!                        - tm_i(jpi,jpj)  mean ice temperature
+   !!                        - tm_s(jpi,jpj)  mean snw temperature
+   !!----------------------------------------------------------------------
+   !!   ice_var_agg       : integrate variables over layers and categories
+   !!   ice_var_glo2eqv   : transform from VGLO to VEQV
+   !!   ice_var_eqv2glo   : transform from VEQV to VGLO
+   !!   ice_var_salprof   : salinity profile in the ice
+   !!   ice_var_salprof1d : salinity profile in the ice 1D
+   !!   ice_var_zapsmall  : remove very small area and volume
+   !!   ice_var_zapneg    : remove negative ice fields
+   !!   ice_var_roundoff  : remove negative values arising from roundoff erros
+   !!   ice_var_bv        : brine volume
+   !!   ice_var_enthalpy  : compute ice and snow enthalpies from temperature
+   !!   ice_var_sshdyn    : compute equivalent ssh in lead
+   !!   ice_var_itd       : convert N-cat to M-cat
+   !!   ice_var_snwfra    : fraction of ice covered by snow
+   !!   ice_var_snwblow   : distribute snow fall between ice and ocean
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants (ocean directory) 
+   USE sbc_oce , ONLY : sss_m, ln_ice_embd, nn_fsbc
+   USE ice            ! sea-ice: variables
+   USE ice1D          ! sea-ice: thermodynamics variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ice_var_agg          
+   PUBLIC   ice_var_glo2eqv      
+   PUBLIC   ice_var_eqv2glo      
+   PUBLIC   ice_var_salprof      
+   PUBLIC   ice_var_salprof1d    
+   PUBLIC   ice_var_zapsmall
+   PUBLIC   ice_var_zapneg
+   PUBLIC   ice_var_roundoff
+   PUBLIC   ice_var_bv           
+   PUBLIC   ice_var_enthalpy           
+   PUBLIC   ice_var_sshdyn
+   PUBLIC   ice_var_itd
+   PUBLIC   ice_var_snwfra
+   PUBLIC   ice_var_snwblow
+
+   INTERFACE ice_var_itd
+      MODULE PROCEDURE ice_var_itd_1c1c, ice_var_itd_Nc1c, ice_var_itd_1cMc, ice_var_itd_NcMc
+   END INTERFACE
+
+   INTERFACE ice_var_snwfra
+      MODULE PROCEDURE ice_var_snwfra_1d, ice_var_snwfra_2d, ice_var_snwfra_3d
+   END INTERFACE
+
+   INTERFACE ice_var_snwblow
+      MODULE PROCEDURE ice_var_snwblow_1d, ice_var_snwblow_2d
+   END INTERFACE
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_var_agg( kn )
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_var_agg  ***
+      !!
+      !! ** Purpose :   aggregates ice-thickness-category variables to 
+      !!              all-ice variables, i.e. it turns VGLO into VAGG
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kn     ! =1 state variables only
+      !                                 ! >1 state variables + others
+      !
+      INTEGER ::   ji, jj, jk, jl   ! dummy loop indices
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   z1_at_i, z1_vt_i, z1_vt_s
+      !!-------------------------------------------------------------------
+      !
+      !                                      ! integrated values
+      vt_i(:,:) =       SUM( v_i (:,:,:)           , dim=3 )
+      vt_s(:,:) =       SUM( v_s (:,:,:)           , dim=3 )
+      st_i(:,:) =       SUM( sv_i(:,:,:)           , dim=3 )
+      at_i(:,:) =       SUM( a_i (:,:,:)           , dim=3 )
+      et_s(:,:)  = SUM( SUM( e_s (:,:,:,:), dim=4 ), dim=3 )
+      et_i(:,:)  = SUM( SUM( e_i (:,:,:,:), dim=4 ), dim=3 )
+      !
+      at_ip(:,:) = SUM( a_ip(:,:,:), dim=3 ) ! melt ponds
+      vt_ip(:,:) = SUM( v_ip(:,:,:), dim=3 )
+      vt_il(:,:) = SUM( v_il(:,:,:), dim=3 )
+      !
+      ato_i(:,:) = 1._wp - at_i(:,:)         ! open water fraction  
+
+      ! The following fields are calculated for diagnostics and outputs only
+      ! ==> Do not use them for other purposes
+      IF( kn > 1 ) THEN
+         !
+         ALLOCATE( z1_at_i(jpi,jpj) , z1_vt_i(jpi,jpj) , z1_vt_s(jpi,jpj) )
+         WHERE( at_i(:,:) > epsi20 )   ;   z1_at_i(:,:) = 1._wp / at_i(:,:)
+         ELSEWHERE                     ;   z1_at_i(:,:) = 0._wp
+         END WHERE
+         WHERE( vt_i(:,:) > epsi20 )   ;   z1_vt_i(:,:) = 1._wp / vt_i(:,:)
+         ELSEWHERE                     ;   z1_vt_i(:,:) = 0._wp
+         END WHERE
+         WHERE( vt_s(:,:) > epsi20 )   ;   z1_vt_s(:,:) = 1._wp / vt_s(:,:)
+         ELSEWHERE                     ;   z1_vt_s(:,:) = 0._wp
+         END WHERE
+         !
+         !                          ! mean ice/snow thickness
+         hm_i(:,:) = vt_i(:,:) * z1_at_i(:,:)
+         hm_s(:,:) = vt_s(:,:) * z1_at_i(:,:)
+         !         
+         !                          ! mean temperature (K), salinity and age
+         tm_su(:,:) = SUM( t_su(:,:,:) * a_i(:,:,:) , dim=3 ) * z1_at_i(:,:)
+         tm_si(:,:) = SUM( t_si(:,:,:) * a_i(:,:,:) , dim=3 ) * z1_at_i(:,:)
+         om_i (:,:) = SUM( oa_i(:,:,:)              , dim=3 ) * z1_at_i(:,:)
+         sm_i (:,:) =      st_i(:,:)                          * z1_vt_i(:,:)
+         !
+         tm_i(:,:) = 0._wp
+         tm_s(:,:) = 0._wp
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               tm_i(:,:) = tm_i(:,:) + r1_nlay_i * t_i (:,:,jk,jl) * v_i(:,:,jl) * z1_vt_i(:,:)
+            END DO
+            DO jk = 1, nlay_s
+               tm_s(:,:) = tm_s(:,:) + r1_nlay_s * t_s (:,:,jk,jl) * v_s(:,:,jl) * z1_vt_s(:,:)
+            END DO
+         END DO
+         !
+         !                           ! put rt0 where there is no ice
+         WHERE( at_i(:,:)<=epsi20 )
+            tm_su(:,:) = rt0
+            tm_si(:,:) = rt0
+            tm_i (:,:) = rt0
+            tm_s (:,:) = rt0
+         END WHERE
+         !
+         !                           ! mean melt pond depth
+         WHERE( at_ip(:,:) > epsi20 )   ;   hm_ip(:,:) = vt_ip(:,:) / at_ip(:,:)   ;   hm_il(:,:) = vt_il(:,:) / at_ip(:,:)
+         ELSEWHERE                      ;   hm_ip(:,:) = 0._wp                     ;   hm_il(:,:) = 0._wp
+         END WHERE         
+         !
+         DEALLOCATE( z1_at_i , z1_vt_i , z1_vt_s )
+         !
+      ENDIF
+      !
+   END SUBROUTINE ice_var_agg
+
+
+   SUBROUTINE ice_var_glo2eqv
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_var_glo2eqv ***
+      !!
+      !! ** Purpose :   computes equivalent variables as function of  
+      !!              global variables, i.e. it turns VGLO into VEQV
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      REAL(wp) ::   ze_i             ! local scalars
+      REAL(wp) ::   ze_s, ztmelts, zbbb, zccc       !   -      -
+      REAL(wp) ::   zhmax, z1_zhmax                 !   -      -
+      REAL(wp) ::   zlay_i, zlay_s                  !   -      -
+      REAL(wp), PARAMETER ::   zhl_max =  0.015_wp  ! pond lid thickness above which the ponds disappear from the albedo calculation
+      REAL(wp), PARAMETER ::   zhl_min =  0.005_wp  ! pond lid thickness below which the full pond area is used in the albedo calculation
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z1_a_i, z1_v_i, z1_a_ip, za_s_fra
+      !!-------------------------------------------------------------------
+
+!!gm Question 2:  It is possible to define existence of sea-ice in a common way between 
+!!                ice area and ice volume ?
+!!                the idea is to be able to define one for all at the begining of this routine
+!!                a criteria for icy area (i.e. a_i > epsi20 and v_i > epsi20 )
+
+      !---------------------------------------------------------------
+      ! Ice thickness, snow thickness, ice salinity, ice age and ponds
+      !---------------------------------------------------------------
+      !                                            !--- inverse of the ice area
+      WHERE( a_i(:,:,:) > epsi20 )   ;   z1_a_i(:,:,:) = 1._wp / a_i(:,:,:)
+      ELSEWHERE                      ;   z1_a_i(:,:,:) = 0._wp
+      END WHERE
+      !
+      WHERE( v_i(:,:,:) > epsi20 )   ;   z1_v_i(:,:,:) = 1._wp / v_i(:,:,:)
+      ELSEWHERE                      ;   z1_v_i(:,:,:) = 0._wp
+      END WHERE
+      !
+      WHERE( a_ip(:,:,:) > epsi20 )  ;   z1_a_ip(:,:,:) = 1._wp / a_ip(:,:,:)
+      ELSEWHERE                      ;   z1_a_ip(:,:,:) = 0._wp
+      END WHERE
+      !                                           !--- ice thickness
+      h_i(:,:,:) = v_i (:,:,:) * z1_a_i(:,:,:)
+
+      zhmax    =          hi_max(jpl)
+      z1_zhmax =  1._wp / hi_max(jpl)               
+      WHERE( h_i(:,:,jpl) > zhmax )   ! bound h_i by hi_max (i.e. 99 m) with associated update of ice area
+         h_i  (:,:,jpl) = zhmax
+         a_i   (:,:,jpl) = v_i(:,:,jpl) * z1_zhmax 
+         z1_a_i(:,:,jpl) = zhmax * z1_v_i(:,:,jpl)
+      END WHERE
+      !                                           !--- snow thickness
+      h_s(:,:,:) = v_s (:,:,:) * z1_a_i(:,:,:)
+      !                                           !--- ice age      
+      o_i(:,:,:) = oa_i(:,:,:) * z1_a_i(:,:,:)
+      !                                           !--- pond and lid thickness      
+      h_ip(:,:,:) = v_ip(:,:,:) * z1_a_ip(:,:,:)
+      h_il(:,:,:) = v_il(:,:,:) * z1_a_ip(:,:,:)
+      !                                           !--- melt pond effective area (used for albedo)
+      a_ip_frac(:,:,:) = a_ip(:,:,:) * z1_a_i(:,:,:)
+      WHERE    ( h_il(:,:,:) <= zhl_min )  ;   a_ip_eff(:,:,:) = a_ip_frac(:,:,:)       ! lid is very thin.  Expose all the pond
+      ELSEWHERE( h_il(:,:,:) >= zhl_max )  ;   a_ip_eff(:,:,:) = 0._wp                  ! lid is very thick. Cover all the pond up with ice and snow
+      ELSEWHERE                            ;   a_ip_eff(:,:,:) = a_ip_frac(:,:,:) * &   ! lid is in between. Expose part of the pond
+         &                                                       ( h_il(:,:,:) - zhl_min ) / ( zhl_max - zhl_min )
+      END WHERE
+      !
+      CALL ice_var_snwfra( h_s, za_s_fra )           ! calculate ice fraction covered by snow
+      a_ip_eff = MIN( a_ip_eff, 1._wp - za_s_fra )   ! make sure (a_ip_eff + a_s_fra) <= 1
+      !
+      !                                           !---  salinity (with a minimum value imposed everywhere)     
+      IF( nn_icesal == 2 ) THEN
+         WHERE( v_i(:,:,:) > epsi20 )   ;   s_i(:,:,:) = MAX( rn_simin , MIN( rn_simax, sv_i(:,:,:) * z1_v_i(:,:,:) ) )
+         ELSEWHERE                      ;   s_i(:,:,:) = rn_simin
+         END WHERE
+      ENDIF
+      CALL ice_var_salprof   ! salinity profile
+
+      !-------------------
+      ! Ice temperature   [K]   (with a minimum value (rt0 - 100.))
+      !-------------------
+      zlay_i   = REAL( nlay_i , wp )    ! number of layers
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF ( v_i(ji,jj,jl) > epsi20 ) THEN     !--- icy area 
+                     !
+                     ze_i             =   e_i (ji,jj,jk,jl) * z1_v_i(ji,jj,jl) * zlay_i             ! Energy of melting e(S,T) [J.m-3]
+                     ztmelts          = - sz_i(ji,jj,jk,jl) * rTmlt                                 ! Ice layer melt temperature [C]
+                     ! Conversion q(S,T) -> T (second order equation)
+                     zbbb             = ( rcp - rcpi ) * ztmelts + ze_i * r1_rhoi - rLfus
+                     zccc             = SQRT( MAX( zbbb * zbbb - 4._wp * rcpi * rLfus * ztmelts , 0._wp) )
+                     t_i(ji,jj,jk,jl) = MAX( -100._wp , MIN( -( zbbb + zccc ) * 0.5_wp * r1_rcpi , ztmelts ) ) + rt0   ! [K] with bounds: -100 < t_i < ztmelts
+                     !
+                  ELSE                                   !--- no ice
+                     t_i(ji,jj,jk,jl) = rt0
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+
+      !--------------------
+      ! Snow temperature   [K]   (with a minimum value (rt0 - 100.))
+      !--------------------
+      zlay_s = REAL( nlay_s , wp )
+      DO jk = 1, nlay_s
+         WHERE( v_s(:,:,:) > epsi20 )        !--- icy area
+            t_s(:,:,jk,:) = rt0 + MAX( -100._wp ,  &
+                 &                MIN( r1_rcpi * ( -r1_rhos * ( e_s(:,:,jk,:) / v_s(:,:,:) * zlay_s ) + rLfus ) , 0._wp ) )
+         ELSEWHERE                           !--- no ice
+            t_s(:,:,jk,:) = rt0
+         END WHERE
+      END DO
+      !
+      ! integrated values 
+      vt_i (:,:) = SUM( v_i , dim=3 )
+      vt_s (:,:) = SUM( v_s , dim=3 )
+      at_i (:,:) = SUM( a_i , dim=3 )
+      !
+   END SUBROUTINE ice_var_glo2eqv
+
+
+   SUBROUTINE ice_var_eqv2glo
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_var_eqv2glo ***
+      !!
+      !! ** Purpose :   computes global variables as function of 
+      !!              equivalent variables,  i.e. it turns VEQV into VGLO
+      !!-------------------------------------------------------------------
+      !
+      v_i (:,:,:) = h_i (:,:,:) * a_i (:,:,:)
+      v_s (:,:,:) = h_s (:,:,:) * a_i (:,:,:)
+      sv_i(:,:,:) = s_i (:,:,:) * v_i (:,:,:)
+      v_ip(:,:,:) = h_ip(:,:,:) * a_ip(:,:,:)
+      v_il(:,:,:) = h_il(:,:,:) * a_ip(:,:,:)
+      !
+   END SUBROUTINE ice_var_eqv2glo
+
+
+   SUBROUTINE ice_var_salprof
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_var_salprof ***
+      !!
+      !! ** Purpose :   computes salinity profile in function of bulk salinity     
+      !!
+      !! ** Method  : If bulk salinity greater than zsi1, 
+      !!              the profile is assumed to be constant (S_inf)
+      !!              If bulk salinity lower than zsi0,
+      !!              the profile is linear with 0 at the surface (S_zero)
+      !!              If it is between zsi0 and zsi1, it is a
+      !!              alpha-weighted linear combination of s_inf and s_zero
+      !!
+      !! ** References : Vancoppenolle et al., 2007
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop index
+      REAL(wp) ::   zsal, z1_dS
+      REAL(wp) ::   zargtemp , zs0, zs
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   z_slope_s, zalpha    ! case 2 only
+      REAL(wp), PARAMETER :: zsi0 = 3.5_wp
+      REAL(wp), PARAMETER :: zsi1 = 4.5_wp
+      !!-------------------------------------------------------------------
+
+!!gm Question: Remove the option 3 ?  How many years since it last use ? 
+
+      SELECT CASE ( nn_icesal )
+      !
+      !               !---------------------------------------!
+      CASE( 1 )       !  constant salinity in time and space  !
+         !            !---------------------------------------!
+         sz_i(:,:,:,:) = rn_icesal
+         s_i (:,:,:)   = rn_icesal
+         !
+         !            !---------------------------------------------!
+      CASE( 2 )       !  time varying salinity with linear profile  !
+         !            !---------------------------------------------!
+         !
+         ALLOCATE( z_slope_s(jpi,jpj,jpl) , zalpha(jpi,jpj,jpl) )
+         !
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               sz_i(:,:,jk,jl)  = s_i(:,:,jl)
+            END DO
+         END DO
+         !                                      ! Slope of the linear profile 
+         WHERE( h_i(:,:,:) > epsi20 )   ;   z_slope_s(:,:,:) = 2._wp * s_i(:,:,:) / h_i(:,:,:)
+         ELSEWHERE                      ;   z_slope_s(:,:,:) = 0._wp
+         END WHERE
+         !
+         z1_dS = 1._wp / ( zsi1 - zsi0 )
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zalpha(ji,jj,jl) = MAX(  0._wp , MIN( ( zsi1 - s_i(ji,jj,jl) ) * z1_dS , 1._wp )  )
+                  !                             ! force a constant profile when SSS too low (Baltic Sea)
+                  IF( 2._wp * s_i(ji,jj,jl) >= sss_m(ji,jj) )   zalpha(ji,jj,jl) = 0._wp  
+               END DO
+            END DO
+         END DO
+         !
+         ! Computation of the profile
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     !                          ! linear profile with 0 surface value
+                     zs0 = z_slope_s(ji,jj,jl) * ( REAL(jk,wp) - 0.5_wp ) * h_i(ji,jj,jl) * r1_nlay_i
+                     zs  = zalpha(ji,jj,jl) * zs0 + ( 1._wp - zalpha(ji,jj,jl) ) * s_i(ji,jj,jl)     ! weighting the profile
+                     sz_i(ji,jj,jk,jl) = MIN( rn_simax, MAX( zs, rn_simin ) )
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         DEALLOCATE( z_slope_s , zalpha )
+         !
+         !            !-------------------------------------------!
+      CASE( 3 )       ! constant salinity with a fix profile      ! (Schwarzacher (1959) multiyear salinity profile
+         !            !-------------------------------------------!                                   (mean = 2.30)
+         !
+         s_i(:,:,:) = 2.30_wp
+!!gm Remark: if we keep the case 3, then compute an store one for all time-step
+!!           a array  S_prof(1:nlay_i) containing the calculation and just do:
+!         DO jk = 1, nlay_i
+!            sz_i(:,:,jk,:) = S_prof(jk)
+!         END DO
+!!gm end
+         !
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               zargtemp  = ( REAL(jk,wp) - 0.5_wp ) * r1_nlay_i
+               sz_i(:,:,jk,jl) =  1.6_wp * (  1._wp - COS( rpi * zargtemp**(0.407_wp/(0.573_wp+zargtemp)) )  )
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_var_salprof
+
+
+   SUBROUTINE ice_var_salprof1d
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE ice_var_salprof1d  ***
+      !!
+      !! ** Purpose :   1d computation of the sea ice salinity profile
+      !!                Works with 1d vectors and is used by thermodynamic modules
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jk    ! dummy loop indices
+      REAL(wp) ::   zargtemp, zsal, z1_dS   ! local scalars
+      REAL(wp) ::   zs, zs0              !   -      -
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:) ::   z_slope_s, zalpha   !
+      REAL(wp), PARAMETER :: zsi0 = 3.5_wp
+      REAL(wp), PARAMETER :: zsi1 = 4.5_wp
+      !!-------------------------------------------------------------------
+      !
+      SELECT CASE ( nn_icesal )
+      !
+      !               !---------------------------------------!
+      CASE( 1 )       !  constant salinity in time and space  !
+         !            !---------------------------------------!
+         sz_i_1d(1:npti,:) = rn_icesal
+         !
+         !            !---------------------------------------------!
+      CASE( 2 )       !  time varying salinity with linear profile  !
+         !            !---------------------------------------------!
+         !
+         ALLOCATE( z_slope_s(jpij), zalpha(jpij) )
+         !
+         !                                      ! Slope of the linear profile 
+         WHERE( h_i_1d(1:npti) > epsi20 )   ;   z_slope_s(1:npti) = 2._wp * s_i_1d(1:npti) / h_i_1d(1:npti)
+         ELSEWHERE                          ;   z_slope_s(1:npti) = 0._wp
+         END WHERE
+         
+         z1_dS = 1._wp / ( zsi1 - zsi0 )
+         DO ji = 1, npti
+            zalpha(ji) = MAX(  0._wp , MIN(  ( zsi1 - s_i_1d(ji) ) * z1_dS , 1._wp  )  )
+            !                             ! force a constant profile when SSS too low (Baltic Sea)
+            IF( 2._wp * s_i_1d(ji) >= sss_1d(ji) )   zalpha(ji) = 0._wp
+         END DO
+         !
+         ! Computation of the profile
+         DO jk = 1, nlay_i
+            DO ji = 1, npti
+               !                          ! linear profile with 0 surface value
+               zs0 = z_slope_s(ji) * ( REAL(jk,wp) - 0.5_wp ) * h_i_1d(ji) * r1_nlay_i
+               zs  = zalpha(ji) * zs0 + ( 1._wp - zalpha(ji) ) * s_i_1d(ji)
+               sz_i_1d(ji,jk) = MIN( rn_simax , MAX( zs , rn_simin ) )
+            END DO
+         END DO
+         !
+         DEALLOCATE( z_slope_s, zalpha )
+
+         !            !-------------------------------------------!
+      CASE( 3 )       ! constant salinity with a fix profile      ! (Schwarzacher (1959) multiyear salinity profile
+         !            !-------------------------------------------!                                   (mean = 2.30)
+         !
+         s_i_1d(1:npti) = 2.30_wp
+         !
+!!gm cf remark in ice_var_salprof routine, CASE( 3 )
+         DO jk = 1, nlay_i
+            zargtemp  = ( REAL(jk,wp) - 0.5_wp ) * r1_nlay_i
+            zsal =  1.6_wp * ( 1._wp - COS( rpi * zargtemp**( 0.407_wp / ( 0.573_wp + zargtemp ) ) ) )
+            DO ji = 1, npti
+               sz_i_1d(ji,jk) = zsal
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+   END SUBROUTINE ice_var_salprof1d
+
+
+   SUBROUTINE ice_var_zapsmall
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_var_zapsmall ***
+      !!
+      !! ** Purpose :   Remove too small sea ice areas and correct fluxes
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jl, jk   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) ::   zswitch
+      !!-------------------------------------------------------------------
+      !
+      DO jl = 1, jpl       !==  loop over the categories  ==!
+         !
+         WHERE( a_i(:,:,jl) > epsi10 )   ;   h_i(:,:,jl) = v_i(:,:,jl) / a_i(:,:,jl)
+         ELSEWHERE                       ;   h_i(:,:,jl) = 0._wp
+         END WHERE
+         !
+         WHERE( a_i(:,:,jl) < epsi10 .OR. v_i(:,:,jl) < epsi10 .OR. h_i(:,:,jl) < epsi10 )   ;   zswitch(:,:) = 0._wp
+         ELSEWHERE                                                                           ;   zswitch(:,:) = 1._wp
+         END WHERE
+         !
+         !-----------------------------------------------------------------
+         ! Zap ice energy and use ocean heat to melt ice
+         !-----------------------------------------------------------------
+         DO jk = 1, nlay_i
+            DO jj = 1 , jpj
+               DO ji = 1 , jpi
+                  ! update exchanges with ocean
+                  hfx_res(ji,jj)   = hfx_res(ji,jj) - (1._wp - zswitch(ji,jj) ) * e_i(ji,jj,jk,jl) * r1_rdtice ! W.m-2 <0
+                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * zswitch(ji,jj)
+                  t_i(ji,jj,jk,jl) = t_i(ji,jj,jk,jl) * zswitch(ji,jj) + rt0 * ( 1._wp - zswitch(ji,jj) )
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, nlay_s
+            DO jj = 1 , jpj
+               DO ji = 1 , jpi
+                  ! update exchanges with ocean
+                  hfx_res(ji,jj)   = hfx_res(ji,jj) - (1._wp - zswitch(ji,jj) ) * e_s(ji,jj,jk,jl) * r1_rdtice ! W.m-2 <0
+                  e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) * zswitch(ji,jj)
+                  t_s(ji,jj,jk,jl) = t_s(ji,jj,jk,jl) * zswitch(ji,jj) + rt0 * ( 1._wp - zswitch(ji,jj) )
+               END DO
+            END DO
+         END DO
+         !
+         !-----------------------------------------------------------------
+         ! zap ice and snow volume, add water and salt to ocean
+         !-----------------------------------------------------------------
+         DO jj = 1 , jpj
+            DO ji = 1 , jpi
+               ! update exchanges with ocean
+               sfx_res(ji,jj)  = sfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * sv_i(ji,jj,jl)   * rhoi * r1_rdtice
+               wfx_res(ji,jj)  = wfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * v_i (ji,jj,jl)   * rhoi * r1_rdtice
+               wfx_res(ji,jj)  = wfx_res(ji,jj) + (1._wp - zswitch(ji,jj) ) * v_s (ji,jj,jl)   * rhos * r1_rdtice
+               !
+               a_i  (ji,jj,jl) = a_i (ji,jj,jl) * zswitch(ji,jj)
+               v_i  (ji,jj,jl) = v_i (ji,jj,jl) * zswitch(ji,jj)
+               v_s  (ji,jj,jl) = v_s (ji,jj,jl) * zswitch(ji,jj)
+               t_su (ji,jj,jl) = t_su(ji,jj,jl) * zswitch(ji,jj) + t_bo(ji,jj) * ( 1._wp - zswitch(ji,jj) )
+               oa_i (ji,jj,jl) = oa_i(ji,jj,jl) * zswitch(ji,jj)
+               sv_i (ji,jj,jl) = sv_i(ji,jj,jl) * zswitch(ji,jj)
+               !
+               h_i (ji,jj,jl) = h_i (ji,jj,jl) * zswitch(ji,jj)
+               h_s (ji,jj,jl) = h_s (ji,jj,jl) * zswitch(ji,jj)
+               !
+               a_ip (ji,jj,jl) = a_ip (ji,jj,jl) * zswitch(ji,jj)
+               v_ip (ji,jj,jl) = v_ip (ji,jj,jl) * zswitch(ji,jj)
+               v_il (ji,jj,jl) = v_il (ji,jj,jl) * zswitch(ji,jj)
+               !
+            END DO
+         END DO
+         !
+      END DO 
+
+      ! to be sure that at_i is the sum of a_i(jl)
+      at_i (:,:) = SUM( a_i (:,:,:), dim=3 )
+      vt_i (:,:) = SUM( v_i (:,:,:), dim=3 )
+!!clem add?
+!      vt_s (:,:) = SUM( v_s (:,:,:), dim=3 )
+!      st_i (:,:) = SUM( sv_i(:,:,:), dim=3 )
+!      et_s(:,:)  = SUM( SUM( e_s (:,:,:,:), dim=4 ), dim=3 )
+!      et_i(:,:)  = SUM( SUM( e_i (:,:,:,:), dim=4 ), dim=3 )
+!!clem
+
+      ! open water = 1 if at_i=0
+      WHERE( at_i(:,:) == 0._wp )   ato_i(:,:) = 1._wp
+      !
+   END SUBROUTINE ice_var_zapsmall
+
+
+   SUBROUTINE ice_var_zapneg( pdt, pato_i, pv_i, pv_s, psv_i, poa_i, pa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_var_zapneg ***
+      !!
+      !! ** Purpose :   Remove negative sea ice fields and correct fluxes
+      !!-------------------------------------------------------------------
+      REAL(wp)                    , INTENT(in   ) ::   pdt        ! tracer time-step
+      REAL(wp), DIMENSION(:,:)    , INTENT(inout) ::   pato_i     ! open water area
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_i       ! ice volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_s       ! snw volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   psv_i      ! salt content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   poa_i      ! age content
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_i       ! ice concentration
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pa_ip      ! melt pond fraction
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_ip      ! melt pond volume
+      REAL(wp), DIMENSION(:,:,:)  , INTENT(inout) ::   pv_il      ! melt pond lid volume
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_s       ! snw heat content
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(inout) ::   pe_i       ! ice heat content
+      !
+      INTEGER  ::   ji, jj, jl, jk   ! dummy loop indices
+      REAL(wp) ::   z1_dt
+      !!-------------------------------------------------------------------
+      !
+      z1_dt = 1._wp / pdt
+      !
+      DO jl = 1, jpl       !==  loop over the categories  ==!
+         !
+         ! make sure a_i=0 where v_i<=0
+         WHERE( pv_i(:,:,:) <= 0._wp )   pa_i(:,:,:) = 0._wp
+
+         !----------------------------------------
+         ! zap ice energy and send it to the ocean
+         !----------------------------------------
+         DO jk = 1, nlay_i
+            DO jj = 1 , jpj
+               DO ji = 1 , jpi
+                  IF( pe_i(ji,jj,jk,jl) < 0._wp .OR. pa_i(ji,jj,jl) <= 0._wp ) THEN
+                     hfx_res(ji,jj)   = hfx_res(ji,jj) - pe_i(ji,jj,jk,jl) * z1_dt ! W.m-2 >0
+                     pe_i(ji,jj,jk,jl) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, nlay_s
+            DO jj = 1 , jpj
+               DO ji = 1 , jpi
+                  IF( pe_s(ji,jj,jk,jl) < 0._wp .OR. pa_i(ji,jj,jl) <= 0._wp ) THEN
+                     hfx_res(ji,jj)   = hfx_res(ji,jj) - pe_s(ji,jj,jk,jl) * z1_dt ! W.m-2 <0
+                     pe_s(ji,jj,jk,jl) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         !-----------------------------------------------------
+         ! zap ice and snow volume, add water and salt to ocean
+         !-----------------------------------------------------
+         DO jj = 1 , jpj
+            DO ji = 1 , jpi
+               IF( pv_i(ji,jj,jl) < 0._wp .OR. pa_i(ji,jj,jl) <= 0._wp ) THEN
+                  wfx_res(ji,jj)    = wfx_res(ji,jj) + pv_i (ji,jj,jl) * rhoi * z1_dt
+                  pv_i   (ji,jj,jl) = 0._wp
+               ENDIF
+               IF( pv_s(ji,jj,jl) < 0._wp .OR. pa_i(ji,jj,jl) <= 0._wp ) THEN
+                  wfx_res(ji,jj)    = wfx_res(ji,jj) + pv_s (ji,jj,jl) * rhos * z1_dt
+                  pv_s   (ji,jj,jl) = 0._wp
+               ENDIF
+               IF( psv_i(ji,jj,jl) < 0._wp .OR. pa_i(ji,jj,jl) <= 0._wp .OR. pv_i(ji,jj,jl) <= 0._wp ) THEN
+                  sfx_res(ji,jj)    = sfx_res(ji,jj) + psv_i(ji,jj,jl) * rhoi * z1_dt
+                  psv_i  (ji,jj,jl) = 0._wp
+               ENDIF
+            END DO
+         END DO
+         !
+      END DO 
+      !
+      WHERE( pato_i(:,:)   < 0._wp )   pato_i(:,:)   = 0._wp
+      WHERE( poa_i (:,:,:) < 0._wp )   poa_i (:,:,:) = 0._wp
+      WHERE( pa_i  (:,:,:) < 0._wp )   pa_i  (:,:,:) = 0._wp
+      WHERE( pa_ip (:,:,:) < 0._wp )   pa_ip (:,:,:) = 0._wp
+      WHERE( pv_ip (:,:,:) < 0._wp )   pv_ip (:,:,:) = 0._wp ! in theory one should change wfx_pnd(-) and wfx_sum(+)
+      WHERE( pv_il (:,:,:) < 0._wp )   pv_il (:,:,:) = 0._wp !    but it does not change conservation, so keep it this way is ok
+      !
+   END SUBROUTINE ice_var_zapneg
+
+
+   SUBROUTINE ice_var_roundoff( pa_i, pv_i, pv_s, psv_i, poa_i, pa_ip, pv_ip, pv_il, pe_s, pe_i )
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_var_roundoff ***
+      !!
+      !! ** Purpose :   Remove negative sea ice values arising from roundoff errors
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pa_i       ! ice concentration
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pv_i       ! ice volume
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pv_s       ! snw volume
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   psv_i      ! salt content
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   poa_i      ! age content
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pa_ip      ! melt pond fraction
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pv_ip      ! melt pond volume
+      REAL(wp), DIMENSION(:,:)  , INTENT(inout) ::   pv_il      ! melt pond lid volume
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pe_s       ! snw heat content
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pe_i       ! ice heat content
+      !!-------------------------------------------------------------------
+      !
+      WHERE( pa_i (1:npti,:)   < 0._wp .AND. pa_i (1:npti,:)   > -epsi10 )   pa_i (1:npti,:)   = 0._wp   !  a_i must be >= 0
+      WHERE( pv_i (1:npti,:)   < 0._wp .AND. pv_i (1:npti,:)   > -epsi10 )   pv_i (1:npti,:)   = 0._wp   !  v_i must be >= 0
+      WHERE( pv_s (1:npti,:)   < 0._wp .AND. pv_s (1:npti,:)   > -epsi10 )   pv_s (1:npti,:)   = 0._wp   !  v_s must be >= 0
+      WHERE( psv_i(1:npti,:)   < 0._wp .AND. psv_i(1:npti,:)   > -epsi10 )   psv_i(1:npti,:)   = 0._wp   ! sv_i must be >= 0
+      WHERE( poa_i(1:npti,:)   < 0._wp .AND. poa_i(1:npti,:)   > -epsi10 )   poa_i(1:npti,:)   = 0._wp   ! oa_i must be >= 0
+      WHERE( pe_i (1:npti,:,:) < 0._wp .AND. pe_i (1:npti,:,:) > -epsi06 )   pe_i (1:npti,:,:) = 0._wp   !  e_i must be >= 0
+      WHERE( pe_s (1:npti,:,:) < 0._wp .AND. pe_s (1:npti,:,:) > -epsi06 )   pe_s (1:npti,:,:) = 0._wp   !  e_s must be >= 0
+      IF( ln_pnd_LEV ) THEN
+         WHERE( pa_ip(1:npti,:) < 0._wp .AND. pa_ip(1:npti,:) > -epsi10 )    pa_ip(1:npti,:)   = 0._wp   ! a_ip must be >= 0
+         WHERE( pv_ip(1:npti,:) < 0._wp .AND. pv_ip(1:npti,:) > -epsi10 )    pv_ip(1:npti,:)   = 0._wp   ! v_ip must be >= 0
+         IF( ln_pnd_lids ) THEN
+            WHERE( pv_il(1:npti,:) < 0._wp .AND. pv_il(1:npti,:) > -epsi10 ) pv_il(1:npti,:)   = 0._wp   ! v_il must be >= 0
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE ice_var_roundoff
+   
+
+   SUBROUTINE ice_var_bv
+      !!-------------------------------------------------------------------
+      !!                ***  ROUTINE ice_var_bv ***
+      !!
+      !! ** Purpose :   computes mean brine volume (%) in sea ice
+      !!
+      !! ** Method  : e = - 0.054 * S (ppt) / T (C)
+      !!
+      !! References : Vancoppenolle et al., JGR, 2007
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      !!-------------------------------------------------------------------
+      !
+!!gm I prefere to use WHERE / ELSEWHERE  to set it to zero only where needed   <<<=== to be done
+!!   instead of setting everything to zero as just below
+      bv_i (:,:,:) = 0._wp
+      DO jl = 1, jpl
+         DO jk = 1, nlay_i
+            WHERE( t_i(:,:,jk,jl) < rt0 - epsi10 )   
+               bv_i(:,:,jl) = bv_i(:,:,jl) - rTmlt * sz_i(:,:,jk,jl) * r1_nlay_i / ( t_i(:,:,jk,jl) - rt0 )
+            END WHERE
+         END DO
+      END DO
+      WHERE( vt_i(:,:) > epsi20 )   ;   bvm_i(:,:) = SUM( bv_i(:,:,:) * v_i(:,:,:) , dim=3 ) / vt_i(:,:)
+      ELSEWHERE                     ;   bvm_i(:,:) = 0._wp
+      END WHERE
+      !
+   END SUBROUTINE ice_var_bv
+
+
+   SUBROUTINE ice_var_enthalpy
+      !!-------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_var_enthalpy *** 
+      !!                 
+      !! ** Purpose :   Computes sea ice energy of melting q_i (J.m-3) from temperature
+      !!
+      !! ** Method  :   Formula (Bitz and Lipscomb, 1999)
+      !!-------------------------------------------------------------------
+      INTEGER  ::   ji, jk   ! dummy loop indices
+      REAL(wp) ::   ztmelts  ! local scalar 
+      !!-------------------------------------------------------------------
+      !
+      DO jk = 1, nlay_i             ! Sea ice energy of melting
+         DO ji = 1, npti
+            ztmelts      = - rTmlt  * sz_i_1d(ji,jk)
+            t_i_1d(ji,jk) = MIN( t_i_1d(ji,jk), ztmelts + rt0 ) ! Force t_i_1d to be lower than melting point => likely conservation issue
+                                                                !   (sometimes zdf scheme produces abnormally high temperatures)   
+            e_i_1d(ji,jk) = rhoi * ( rcpi  * ( ztmelts - ( t_i_1d(ji,jk) - rt0 ) )           &
+               &                   + rLfus * ( 1._wp - ztmelts / ( t_i_1d(ji,jk) - rt0 ) )   &
+               &                   - rcp   * ztmelts )
+         END DO
+      END DO
+      DO jk = 1, nlay_s             ! Snow energy of melting
+         DO ji = 1, npti
+            e_s_1d(ji,jk) = rhos * ( rcpi * ( rt0 - t_s_1d(ji,jk) ) + rLfus )
+         END DO
+      END DO
+      !
+   END SUBROUTINE ice_var_enthalpy
+
+   
+   FUNCTION ice_var_sshdyn(pssh, psnwice_mass, psnwice_mass_b)
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE ice_var_sshdyn  ***
+      !!                     
+      !! ** Purpose :  compute the equivalent ssh in lead when sea ice is embedded
+      !!
+      !! ** Method  :  ssh_lead = ssh + (Mice + Msnow) / rau0
+      !!
+      !! ** Reference : Jean-Michel Campin, John Marshall, David Ferreira,
+      !!                Sea ice-ocean coupling using a rescaled vertical coordinate z*, 
+      !!                Ocean Modelling, Volume 24, Issues 1-2, 2008
+      !!----------------------------------------------------------------------
+      !
+      ! input
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pssh            !: ssh [m]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: psnwice_mass    !: mass of snow and ice at current  ice time step [Kg/m2]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: psnwice_mass_b  !: mass of snow and ice at previous ice time step [Kg/m2]
+      !
+      ! output
+      REAL(wp), DIMENSION(jpi,jpj) :: ice_var_sshdyn  ! equivalent ssh in lead [m]
+      !
+      ! temporary
+      REAL(wp) :: zintn, zintb                     ! time interpolation weights []
+      REAL(wp), DIMENSION(jpi,jpj) :: zsnwiceload  ! snow and ice load [m]
+      !
+      ! compute ice load used to define the equivalent ssh in lead
+      IF( ln_ice_embd ) THEN
+         !                                            
+         ! average interpolation coeff as used in dynspg = (1/nn_fsbc)   * {SUM[n/nn_fsbc], n=0,nn_fsbc-1}
+         !                                               = (1/nn_fsbc)^2 * {SUM[n]        , n=0,nn_fsbc-1}
+         zintn = REAL( nn_fsbc - 1 ) / REAL( nn_fsbc ) * 0.5_wp
+         !
+         ! average interpolation coeff as used in dynspg = (1/nn_fsbc)   *    {SUM[1-n/nn_fsbc], n=0,nn_fsbc-1}
+         !                                               = (1/nn_fsbc)^2 * (nn_fsbc^2 - {SUM[n], n=0,nn_fsbc-1})
+         zintb = REAL( nn_fsbc + 1 ) / REAL( nn_fsbc ) * 0.5_wp
+         !
+         zsnwiceload(:,:) = ( zintn * psnwice_mass(:,:) + zintb * psnwice_mass_b(:,:) ) * r1_rau0
+         !
+      ELSE
+         zsnwiceload(:,:) = 0.0_wp
+      ENDIF
+      ! compute equivalent ssh in lead
+      ice_var_sshdyn(:,:) = pssh(:,:) + zsnwiceload(:,:)
+      !
+   END FUNCTION ice_var_sshdyn
+
+   
+   !!-------------------------------------------------------------------
+   !!                ***  INTERFACE ice_var_itd   ***
+   !!
+   !! ** Purpose :  converting N-cat ice to jpl ice categories
+   !!-------------------------------------------------------------------
+   SUBROUTINE ice_var_itd_1c1c( phti, phts, pati ,                             ph_i, ph_s, pa_i, &
+      &                         ptmi, ptms, ptmsu, psmi, patip, phtip, phtil,  pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il )
+      !!-------------------------------------------------------------------
+      !! ** Purpose :  converting 1-cat ice to 1 ice category
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(in)    ::   phti, phts, pati    ! input  ice/snow variables
+      REAL(wp), DIMENSION(:), INTENT(inout) ::   ph_i, ph_s, pa_i    ! output ice/snow variables
+      REAL(wp), DIMENSION(:), INTENT(in)    ::   ptmi, ptms, ptmsu, psmi, patip, phtip, phtil    ! input  ice/snow temp & sal & ponds
+      REAL(wp), DIMENSION(:), INTENT(inout) ::   pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il    ! output ice/snow temp & sal & ponds
+      !!-------------------------------------------------------------------
+      ! == thickness and concentration == !
+      ph_i(:) = phti(:)
+      ph_s(:) = phts(:)
+      pa_i(:) = pati(:)
+      !
+      ! == temperature and salinity and ponds == !
+      pt_i (:) = ptmi (:)
+      pt_s (:) = ptms (:)
+      pt_su(:) = ptmsu(:)
+      ps_i (:) = psmi (:)
+      pa_ip(:) = patip(:)
+      ph_ip(:) = phtip(:)
+      ph_il(:) = phtil(:)
+      
+   END SUBROUTINE ice_var_itd_1c1c
+
+   SUBROUTINE ice_var_itd_Nc1c( phti, phts, pati ,                             ph_i, ph_s, pa_i, &
+      &                         ptmi, ptms, ptmsu, psmi, patip, phtip, phtil,  pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il )
+      !!-------------------------------------------------------------------
+      !! ** Purpose :  converting N-cat ice to 1 ice category
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(in)    ::   phti, phts, pati    ! input  ice/snow variables
+      REAL(wp), DIMENSION(:)  , INTENT(inout) ::   ph_i, ph_s, pa_i    ! output ice/snow variables
+      REAL(wp), DIMENSION(:,:), INTENT(in)    ::   ptmi, ptms, ptmsu, psmi, patip, phtip, phtil    ! input  ice/snow temp & sal & ponds
+      REAL(wp), DIMENSION(:)  , INTENT(inout) ::   pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il    ! output ice/snow temp & sal & ponds
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:) ::   z1_ai, z1_vi, z1_vs
+      !
+      INTEGER ::   idim  
+      !!-------------------------------------------------------------------
+      !
+      idim = SIZE( phti, 1 )
+      !
+      ! == thickness and concentration == !
+      ALLOCATE( z1_ai(idim), z1_vi(idim), z1_vs(idim) )
+      !
+      pa_i(:) = SUM( pati(:,:), dim=2 )
+
+      WHERE( ( pa_i(:) ) /= 0._wp )   ;   z1_ai(:) = 1._wp / pa_i(:)
+      ELSEWHERE                       ;   z1_ai(:) = 0._wp
+      END WHERE
+
+      ph_i(:) = SUM( phti(:,:) * pati(:,:), dim=2 ) * z1_ai(:)
+      ph_s(:) = SUM( phts(:,:) * pati(:,:), dim=2 ) * z1_ai(:)
+      !
+      ! == temperature and salinity == !
+      WHERE( ( pa_i(:) * ph_i(:) ) /= 0._wp )   ;   z1_vi(:) = 1._wp / ( pa_i(:) * ph_i(:) )
+      ELSEWHERE                                 ;   z1_vi(:) = 0._wp
+      END WHERE
+      WHERE( ( pa_i(:) * ph_s(:) ) /= 0._wp )   ;   z1_vs(:) = 1._wp / ( pa_i(:) * ph_s(:) )
+      ELSEWHERE                                 ;   z1_vs(:) = 0._wp
+      END WHERE
+      pt_i (:) = SUM( ptmi (:,:) * pati(:,:) * phti(:,:), dim=2 ) * z1_vi(:)
+      pt_s (:) = SUM( ptms (:,:) * pati(:,:) * phts(:,:), dim=2 ) * z1_vs(:)
+      pt_su(:) = SUM( ptmsu(:,:) * pati(:,:)            , dim=2 ) * z1_ai(:)
+      ps_i (:) = SUM( psmi (:,:) * pati(:,:) * phti(:,:), dim=2 ) * z1_vi(:)
+
+      ! == ponds == !
+      pa_ip(:) = SUM( patip(:,:), dim=2 )
+      WHERE( pa_ip(:) /= 0._wp )
+         ph_ip(:) = SUM( phtip(:,:) * patip(:,:), dim=2 ) / pa_ip(:)
+         ph_il(:) = SUM( phtil(:,:) * patip(:,:), dim=2 ) / pa_ip(:)
+      ELSEWHERE
+         ph_ip(:) = 0._wp
+         ph_il(:) = 0._wp
+      END WHERE
+      !
+      DEALLOCATE( z1_ai, z1_vi, z1_vs )
+      !
+   END SUBROUTINE ice_var_itd_Nc1c
+   
+   SUBROUTINE ice_var_itd_1cMc( phti, phts, pati ,                             ph_i, ph_s, pa_i, &
+      &                         ptmi, ptms, ptmsu, psmi, patip, phtip, phtil,  pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il )
+      !!-------------------------------------------------------------------
+      !!
+      !! ** Purpose :  converting 1-cat ice to jpl ice categories
+      !!
+      !!
+      !! ** Method:   ice thickness distribution follows a gamma function from Abraham et al. (2015)
+      !!              it has the property of conserving total concentration and volume
+      !!              
+      !!
+      !! ** Arguments : phti: 1-cat ice thickness
+      !!                phts: 1-cat snow depth
+      !!                pati: 1-cat ice concentration
+      !!
+      !! ** Output    : jpl-cat 
+      !!
+      !!  Abraham, C., Steiner, N., Monahan, A. and Michel, C., 2015.
+      !!               Effects of subgrid‐scale snow thickness variability on radiative transfer in sea ice.
+      !!               Journal of Geophysical Research: Oceans, 120(8), pp.5597-5614 
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:),   INTENT(in)    ::   phti, phts, pati    ! input  ice/snow variables
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   ph_i, ph_s, pa_i    ! output ice/snow variables
+      REAL(wp), DIMENSION(:)  , INTENT(in)    ::   ptmi, ptms, ptmsu, psmi, patip, phtip, phtil    ! input  ice/snow temp & sal & ponds
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il    ! output ice/snow temp & sal & ponds
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:) ::   zfra, z1_hti
+      INTEGER  ::   ji, jk, jl
+      INTEGER  ::   idim
+      REAL(wp) ::   zv, zdh
+      !!-------------------------------------------------------------------
+      !
+      idim = SIZE( phti , 1 )
+      !
+      ph_i(1:idim,1:jpl) = 0._wp
+      ph_s(1:idim,1:jpl) = 0._wp
+      pa_i(1:idim,1:jpl) = 0._wp
+      !
+      ALLOCATE( z1_hti(idim) )
+      WHERE( phti(:) /= 0._wp )   ;   z1_hti(:) = 1._wp / phti(:)
+      ELSEWHERE                   ;   z1_hti(:) = 0._wp
+      END WHERE
+      !
+      ! == thickness and concentration == !
+      ! for categories 1:jpl-1, integrate the gamma function from hi_max(jl-1) to hi_max(jl)
+      DO jl = 1, jpl-1
+         DO ji = 1, idim
+            !
+            IF( phti(ji) > 0._wp ) THEN
+               ! concentration : integrate ((4A/H^2)xexp(-2x/H))dx from x=hi_max(jl-1) to hi_max(jl)
+               pa_i(ji,jl) = pati(ji) * z1_hti(ji) * (  ( phti(ji) + 2.*hi_max(jl-1) ) * EXP( -2.*hi_max(jl-1)*z1_hti(ji) ) &
+                  &                                   - ( phti(ji) + 2.*hi_max(jl  ) ) * EXP( -2.*hi_max(jl  )*z1_hti(ji) ) )
+               !
+               ! volume : integrate ((4A/H^2)x^2exp(-2x/H))dx from x=hi_max(jl-1) to hi_max(jl)
+               zv = pati(ji) * z1_hti(ji) * (  ( phti(ji)*phti(ji) + 2.*phti(ji)*hi_max(jl-1) + 2.*hi_max(jl-1)*hi_max(jl-1) ) &
+                  &                            * EXP( -2.*hi_max(jl-1)*z1_hti(ji) ) &
+                  &                          - ( phti(ji)*phti(ji) + 2.*phti(ji)*hi_max(jl) + 2.*hi_max(jl)*hi_max(jl) ) &
+                  &                            * EXP(-2.*hi_max(jl)*z1_hti(ji)) )
+               ! thickness
+               IF( pa_i(ji,jl) > epsi06 ) THEN
+                  ph_i(ji,jl) = zv / pa_i(ji,jl)
+               ELSE
+                  ph_i(ji,jl) = 0.
+                  pa_i(ji,jl) = 0.
+               ENDIF
+            ENDIF
+            !
+         ENDDO
+      ENDDO
+      !
+      ! for the last category (jpl), integrate the gamma function from hi_max(jpl-1) to infinity
+      DO ji = 1, idim
+         !
+         IF( phti(ji) > 0._wp ) THEN
+            ! concentration : integrate ((4A/H^2)xexp(-2x/H))dx from x=hi_max(jpl-1) to infinity
+            pa_i(ji,jpl) = pati(ji) * z1_hti(ji) * ( phti(ji) + 2.*hi_max(jpl-1) ) * EXP( -2.*hi_max(jpl-1)*z1_hti(ji) )
+
+            ! volume : integrate ((4A/H^2)x^2exp(-2x/H))dx from x=hi_max(jpl-1) to infinity
+            zv = pati(ji) * z1_hti(ji) * ( phti(ji)*phti(ji) + 2.*phti(ji)*hi_max(jpl-1) + 2.*hi_max(jpl-1)*hi_max(jpl-1) ) &
+               &                         * EXP( -2.*hi_max(jpl-1)*z1_hti(ji) )
+            ! thickness
+            IF( pa_i(ji,jpl) > epsi06 ) THEN
+               ph_i(ji,jpl) = zv / pa_i(ji,jpl)
+            else
+               ph_i(ji,jpl) = 0.
+               pa_i(ji,jpl) = 0.
+            ENDIF
+         ENDIF
+         !
+      ENDDO
+      !
+      ! Add Snow in each category where pa_i is not 0
+      DO jl = 1, jpl
+         DO ji = 1, idim
+            IF( pa_i(ji,jl) > 0._wp ) THEN
+               ph_s(ji,jl) = ph_i(ji,jl) * phts(ji) * z1_hti(ji)
+               ! In case snow load is in excess that would lead to transformation from snow to ice
+               ! Then, transfer the snow excess into the ice (different from icethd_dh)
+               zdh = MAX( 0._wp, ( rhos * ph_s(ji,jl) + ( rhoi - rau0 ) * ph_i(ji,jl) ) * r1_rau0 ) 
+               ! recompute h_i, h_s avoiding out of bounds values
+               ph_i(ji,jl) = MIN( hi_max(jl), ph_i(ji,jl) + zdh )
+               ph_s(ji,jl) = MAX( 0._wp, ph_s(ji,jl) - zdh * rhoi * r1_rhos )
+            ENDIF
+         END DO
+      END DO
+      !
+      DEALLOCATE( z1_hti )
+      !
+      ! == temperature and salinity == !
+      DO jl = 1, jpl
+         pt_i (:,jl) = ptmi (:)
+         pt_s (:,jl) = ptms (:)
+         pt_su(:,jl) = ptmsu(:)
+         ps_i (:,jl) = psmi (:)
+      END DO
+      !
+      ! == ponds == !
+      ALLOCATE( zfra(idim) )
+      ! keep the same pond fraction atip/ati for each category
+      WHERE( pati(:) /= 0._wp )   ;   zfra(:) = patip(:) / pati(:)
+      ELSEWHERE                   ;   zfra(:) = 0._wp
+      END WHERE
+      DO jl = 1, jpl
+         pa_ip(:,jl) = zfra(:) * pa_i(:,jl)
+      END DO
+      ! keep the same v_ip/v_i ratio for each category
+      WHERE( ( phti(:) * pati(:) ) /= 0._wp )   ;   zfra(:) = ( phtip(:) * patip(:) ) / ( phti(:) * pati(:) )
+      ELSEWHERE                                 ;   zfra(:) = 0._wp
+      END WHERE
+      DO jl = 1, jpl
+         WHERE( pa_ip(:,jl) /= 0._wp )   ;   ph_ip(:,jl) = zfra(:) * ( ph_i(:,jl) * pa_i(:,jl) ) / pa_ip(:,jl)
+         ELSEWHERE                       ;   ph_ip(:,jl) = 0._wp
+         END WHERE
+      END DO
+      ! keep the same v_il/v_i ratio for each category
+      WHERE( ( phti(:) * pati(:) ) /= 0._wp )   ;   zfra(:) = ( phtil(:) * patip(:) ) / ( phti(:) * pati(:) )
+      ELSEWHERE                                 ;   zfra(:) = 0._wp
+      END WHERE
+      DO jl = 1, jpl
+         WHERE( pa_ip(:,jl) /= 0._wp )   ;   ph_il(:,jl) = zfra(:) * ( ph_i(:,jl) * pa_i(:,jl) ) / pa_ip(:,jl)
+         ELSEWHERE                       ;   ph_il(:,jl) = 0._wp
+         END WHERE
+      END DO
+      DEALLOCATE( zfra )
+      !
+   END SUBROUTINE ice_var_itd_1cMc
+
+   SUBROUTINE ice_var_itd_NcMc( phti, phts, pati ,                             ph_i, ph_s, pa_i, &
+      &                         ptmi, ptms, ptmsu, psmi, patip, phtip, phtil,  pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il )
+      !!-------------------------------------------------------------------
+      !!
+      !! ** Purpose :  converting N-cat ice to jpl ice categories
+      !!
+      !!                  ice thickness distribution follows a gaussian law
+      !!               around the concentration of the most likely ice thickness
+      !!                           (similar as iceistate.F90)
+      !!
+      !! ** Method:   Iterative procedure
+      !!                
+      !!               1) Fill ice cat that correspond to input thicknesses
+      !!                  Find the lowest(jlmin) and highest(jlmax) cat that are filled
+      !!
+      !!               2) Expand the filling to the cat jlmin-1 and jlmax+1
+      !!                   by removing 25% ice area from jlmin and jlmax (resp.) 
+      !!              
+      !!               3) Expand the filling to the empty cat between jlmin and jlmax 
+      !!                   by a) removing 25% ice area from the lower cat (ascendant loop jlmin=>jlmax)
+      !!                      b) removing 25% ice area from the higher cat (descendant loop jlmax=>jlmin)
+      !!
+      !! ** Arguments : phti: N-cat ice thickness
+      !!                phts: N-cat snow depth
+      !!                pati: N-cat ice concentration
+      !!
+      !! ** Output    : jpl-cat 
+      !!
+      !!  (Example of application: BDY forcings when inputs have N-cat /= jpl)  
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(in)    ::   phti, phts, pati    ! input  ice/snow variables
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   ph_i, ph_s, pa_i    ! output ice/snow variables
+      REAL(wp), DIMENSION(:,:), INTENT(in)    ::   ptmi, ptms, ptmsu, psmi, patip, phtip, phtil    ! input  ice/snow temp & sal & ponds
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pt_i, pt_s, pt_su, ps_i, pa_ip, ph_ip, ph_il    ! output ice/snow temp & sal & ponds
+      !
+      INTEGER , ALLOCATABLE, DIMENSION(:,:) ::   jlfil, jlfil2
+      INTEGER , ALLOCATABLE, DIMENSION(:)   ::   jlmax, jlmin
+      REAL(wp), ALLOCATABLE, DIMENSION(:)   ::   z1_ai, z1_vi, z1_vs, ztmp, zfra
+      !
+      REAL(wp), PARAMETER ::   ztrans = 0.25_wp
+      INTEGER  ::   ji, jl, jl1, jl2
+      INTEGER  ::   idim, icat  
+      !!-------------------------------------------------------------------
+      !
+      idim = SIZE( phti, 1 )
+      icat = SIZE( phti, 2 )
+      !
+      ! == thickness and concentration == !
+      !                                 ! ---------------------- !
+      IF( icat == jpl ) THEN            ! input cat = output cat !
+         !                              ! ---------------------- !
+         ph_i(:,:) = phti(:,:)
+         ph_s(:,:) = phts(:,:)
+         pa_i(:,:) = pati(:,:)
+         !
+         ! == temperature and salinity and ponds == !
+         pt_i (:,:) = ptmi (:,:)
+         pt_s (:,:) = ptms (:,:)
+         pt_su(:,:) = ptmsu(:,:)
+         ps_i (:,:) = psmi (:,:)
+         pa_ip(:,:) = patip(:,:)
+         ph_ip(:,:) = phtip(:,:)
+         ph_il(:,:) = phtil(:,:)
+         !                              ! ---------------------- !
+      ELSEIF( icat == 1 ) THEN          ! input cat = 1          !
+         !                              ! ---------------------- !
+         CALL  ice_var_itd_1cMc( phti(:,1), phts(:,1), pati (:,1), &
+            &                    ph_i(:,:), ph_s(:,:), pa_i (:,:), &
+            &                    ptmi(:,1), ptms(:,1), ptmsu(:,1), psmi(:,1), patip(:,1), phtip(:,1), phtil(:,1), &
+            &                    pt_i(:,:), pt_s(:,:), pt_su(:,:), ps_i(:,:), pa_ip(:,:), ph_ip(:,:), ph_il(:,:)  )
+         !                              ! ---------------------- !
+      ELSEIF( jpl == 1 ) THEN           ! output cat = 1         !
+         !                              ! ---------------------- !
+         CALL  ice_var_itd_Nc1c( phti(:,:), phts(:,:), pati (:,:), &
+            &                    ph_i(:,1), ph_s(:,1), pa_i (:,1), &
+            &                    ptmi(:,:), ptms(:,:), ptmsu(:,:), psmi(:,:), patip(:,:), phtip(:,:), phtil(:,:), &
+            &                    pt_i(:,1), pt_s(:,1), pt_su(:,1), ps_i(:,1), pa_ip(:,1), ph_ip(:,1), ph_il(:,1)  )
+         !                              ! ----------------------- !
+      ELSE                              ! input cat /= output cat !
+         !                              ! ----------------------- !
+         
+         ALLOCATE( jlfil(idim,jpl), jlfil2(idim,jpl) )       ! allocate arrays
+         ALLOCATE( jlmin(idim), jlmax(idim) )
+
+         ! --- initialize output fields to 0 --- !
+         ph_i(1:idim,1:jpl) = 0._wp
+         ph_s(1:idim,1:jpl) = 0._wp
+         pa_i(1:idim,1:jpl) = 0._wp
+         !
+         ! --- fill the categories --- !
+         !     find where cat-input = cat-output and fill cat-output fields  
+         jlmax(:) = 0
+         jlmin(:) = 999
+         jlfil(:,:) = 0
+         DO jl1 = 1, jpl
+            DO jl2 = 1, icat
+               DO ji = 1, idim
+                  IF( hi_max(jl1-1) <= phti(ji,jl2) .AND. hi_max(jl1) > phti(ji,jl2) ) THEN
+                     ! fill the right category
+                     ph_i(ji,jl1) = phti(ji,jl2)
+                     ph_s(ji,jl1) = phts(ji,jl2)
+                     pa_i(ji,jl1) = pati(ji,jl2)
+                     ! record categories that are filled
+                     jlmax(ji) = MAX( jlmax(ji), jl1 )
+                     jlmin(ji) = MIN( jlmin(ji), jl1 )
+                     jlfil(ji,jl1) = jl1
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         ! --- fill the gaps between categories --- !  
+         !     transfer from categories filled at the previous step to the empty ones in between
+         DO ji = 1, idim
+            jl1 = jlmin(ji)
+            jl2 = jlmax(ji)
+            IF( jl1 > 1 ) THEN
+               ! fill the lower cat (jl1-1)
+               pa_i(ji,jl1-1) = ztrans * pa_i(ji,jl1)
+               ph_i(ji,jl1-1) = hi_mean(jl1-1)
+               ! remove from cat jl1
+               pa_i(ji,jl1  ) = ( 1._wp - ztrans ) * pa_i(ji,jl1)
+            ENDIF
+            IF( jl2 < jpl ) THEN
+               ! fill the upper cat (jl2+1)
+               pa_i(ji,jl2+1) = ztrans * pa_i(ji,jl2)
+               ph_i(ji,jl2+1) = hi_mean(jl2+1)
+               ! remove from cat jl2
+               pa_i(ji,jl2  ) = ( 1._wp - ztrans ) * pa_i(ji,jl2)
+            ENDIF
+         END DO
+         !
+         jlfil2(:,:) = jlfil(:,:) 
+         ! fill categories from low to high
+         DO jl = 2, jpl-1
+            DO ji = 1, idim
+               IF( jlfil(ji,jl-1) /= 0 .AND. jlfil(ji,jl) == 0 ) THEN
+                  ! fill high
+                  pa_i(ji,jl) = ztrans * pa_i(ji,jl-1)
+                  ph_i(ji,jl) = hi_mean(jl)
+                  jlfil(ji,jl) = jl
+                  ! remove low
+                  pa_i(ji,jl-1) = ( 1._wp - ztrans ) * pa_i(ji,jl-1)
+               ENDIF
+            END DO
+         END DO
+         !
+         ! fill categories from high to low
+         DO jl = jpl-1, 2, -1
+            DO ji = 1, idim
+               IF( jlfil2(ji,jl+1) /= 0 .AND. jlfil2(ji,jl) == 0 ) THEN
+                  ! fill low
+                  pa_i(ji,jl) = pa_i(ji,jl) + ztrans * pa_i(ji,jl+1)
+                  ph_i(ji,jl) = hi_mean(jl) 
+                  jlfil2(ji,jl) = jl
+                  ! remove high
+                  pa_i(ji,jl+1) = ( 1._wp - ztrans ) * pa_i(ji,jl+1)
+               ENDIF
+            END DO
+         END DO
+         !
+         DEALLOCATE( jlfil, jlfil2 )      ! deallocate arrays
+         DEALLOCATE( jlmin, jlmax )
+         !
+         ! == temperature and salinity == !
+         !
+         ALLOCATE( z1_ai(idim), z1_vi(idim), z1_vs(idim), ztmp(idim) )
+         !
+         WHERE( SUM( pa_i(:,:), dim=2 ) /= 0._wp )               ;   z1_ai(:) = 1._wp / SUM( pa_i(:,:), dim=2 )
+         ELSEWHERE                                               ;   z1_ai(:) = 0._wp
+         END WHERE
+         WHERE( SUM( pa_i(:,:) * ph_i(:,:), dim=2 ) /= 0._wp )   ;   z1_vi(:) = 1._wp / SUM( pa_i(:,:) * ph_i(:,:), dim=2 )
+         ELSEWHERE                                               ;   z1_vi(:) = 0._wp
+         END WHERE
+         WHERE( SUM( pa_i(:,:) * ph_s(:,:), dim=2 ) /= 0._wp )   ;   z1_vs(:) = 1._wp / SUM( pa_i(:,:) * ph_s(:,:), dim=2 )
+         ELSEWHERE                                               ;   z1_vs(:) = 0._wp
+         END WHERE
+         !
+         ! fill all the categories with the same value
+         ztmp(:) = SUM( ptmi (:,:) * pati(:,:) * phti(:,:), dim=2 ) * z1_vi(:)
+         DO jl = 1, jpl
+            pt_i (:,jl) = ztmp(:)
+         END DO
+         ztmp(:) = SUM( ptms (:,:) * pati(:,:) * phts(:,:), dim=2 ) * z1_vs(:)
+         DO jl = 1, jpl
+            pt_s (:,jl) = ztmp(:)
+         END DO
+         ztmp(:) = SUM( ptmsu(:,:) * pati(:,:)            , dim=2 ) * z1_ai(:)
+         DO jl = 1, jpl
+            pt_su(:,jl) = ztmp(:)
+         END DO
+         ztmp(:) = SUM( psmi (:,:) * pati(:,:) * phti(:,:), dim=2 ) * z1_vi(:)
+         DO jl = 1, jpl
+            ps_i (:,jl) = ztmp(:)
+         END DO
+         !
+         DEALLOCATE( z1_ai, z1_vi, z1_vs, ztmp )
+         !
+         ! == ponds == !
+         ALLOCATE( zfra(idim) )
+         ! keep the same pond fraction atip/ati for each category
+         WHERE( SUM( pati(:,:), dim=2 ) /= 0._wp )   ;   zfra(:) = SUM( patip(:,:), dim=2 ) / SUM( pati(:,:), dim=2 )
+         ELSEWHERE                                   ;   zfra(:) = 0._wp
+         END WHERE
+         DO jl = 1, jpl
+            pa_ip(:,jl) = zfra(:) * pa_i(:,jl)
+         END DO
+         ! keep the same v_ip/v_i ratio for each category
+         WHERE( SUM( phti(:,:) * pati(:,:), dim=2 ) /= 0._wp )
+            zfra(:) = SUM( phtip(:,:) * patip(:,:), dim=2 ) / SUM( phti(:,:) * pati(:,:), dim=2 )
+         ELSEWHERE
+            zfra(:) = 0._wp
+         END WHERE
+         DO jl = 1, jpl
+            WHERE( pa_ip(:,jl) /= 0._wp )   ;   ph_ip(:,jl) = zfra(:) * ( ph_i(:,jl) * pa_i(:,jl) ) / pa_ip(:,jl)
+            ELSEWHERE                       ;   ph_ip(:,jl) = 0._wp
+            END WHERE
+         END DO
+         ! keep the same v_il/v_i ratio for each category
+         WHERE( SUM( phti(:,:) * pati(:,:), dim=2 ) /= 0._wp )
+            zfra(:) = SUM( phtil(:,:) * patip(:,:), dim=2 ) / SUM( phti(:,:) * pati(:,:), dim=2 )
+         ELSEWHERE
+            zfra(:) = 0._wp
+         END WHERE
+         DO jl = 1, jpl
+            WHERE( pa_ip(:,jl) /= 0._wp )   ;   ph_il(:,jl) = zfra(:) * ( ph_i(:,jl) * pa_i(:,jl) ) / pa_ip(:,jl)
+            ELSEWHERE                       ;   ph_il(:,jl) = 0._wp
+            END WHERE
+         END DO
+         DEALLOCATE( zfra )
+         !
+      ENDIF
+      !
+   END SUBROUTINE ice_var_itd_NcMc
+
+   !!-------------------------------------------------------------------
+   !! INTERFACE ice_var_snwfra
+   !!
+   !! ** Purpose :  fraction of ice covered by snow
+   !!
+   !! ** Method  :  In absence of proper snow model on top of sea ice,
+   !!               we argue that snow does not cover the whole ice because
+   !!               of wind blowing...
+   !!                
+   !! ** Arguments : ph_s: snow thickness
+   !!                
+   !! ** Output    : pa_s_fra: fraction of ice covered by snow
+   !!
+   !!-------------------------------------------------------------------
+   SUBROUTINE ice_var_snwfra_3d( ph_s, pa_s_fra )
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   ph_s        ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pa_s_fra    ! ice fraction covered by snow
+      IF    ( nn_snwfra == 0 ) THEN   ! basic 0 or 1 snow cover
+         WHERE( ph_s > 0._wp ) ; pa_s_fra = 1._wp
+         ELSEWHERE             ; pa_s_fra = 0._wp
+         END WHERE
+      ELSEIF( nn_snwfra == 1 ) THEN   ! snow cover depends on hsnow (met-office style)
+         pa_s_fra = 1._wp - EXP( -0.2_wp * rhos * ph_s )
+      ELSEIF( nn_snwfra == 2 ) THEN   ! snow cover depends on hsnow (cice style)
+         pa_s_fra = ph_s / ( ph_s + 0.02_wp )
+      ENDIF
+   END SUBROUTINE ice_var_snwfra_3d
+
+   SUBROUTINE ice_var_snwfra_2d( ph_s, pa_s_fra )
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   ph_s        ! snow thickness
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pa_s_fra    ! ice fraction covered by snow
+      IF    ( nn_snwfra == 0 ) THEN   ! basic 0 or 1 snow cover
+         WHERE( ph_s > 0._wp ) ; pa_s_fra = 1._wp
+         ELSEWHERE             ; pa_s_fra = 0._wp
+         END WHERE
+      ELSEIF( nn_snwfra == 1 ) THEN   ! snow cover depends on hsnow (met-office style)
+         pa_s_fra = 1._wp - EXP( -0.2_wp * rhos * ph_s )
+      ELSEIF( nn_snwfra == 2 ) THEN   ! snow cover depends on hsnow (cice style)
+         pa_s_fra = ph_s / ( ph_s + 0.02_wp )
+      ENDIF
+   END SUBROUTINE ice_var_snwfra_2d
+
+   SUBROUTINE ice_var_snwfra_1d( ph_s, pa_s_fra )
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   ph_s        ! snow thickness
+      REAL(wp), DIMENSION(:), INTENT(  out) ::   pa_s_fra    ! ice fraction covered by snow
+      IF    ( nn_snwfra == 0 ) THEN   ! basic 0 or 1 snow cover
+         WHERE( ph_s > 0._wp ) ; pa_s_fra = 1._wp
+         ELSEWHERE             ; pa_s_fra = 0._wp
+         END WHERE
+      ELSEIF( nn_snwfra == 1 ) THEN   ! snow cover depends on hsnow (met-office style)
+         pa_s_fra = 1._wp - EXP( -0.2_wp * rhos * ph_s )
+      ELSEIF( nn_snwfra == 2 ) THEN   ! snow cover depends on hsnow (cice style)
+         pa_s_fra = ph_s / ( ph_s + 0.02_wp )
+      ENDIF
+   END SUBROUTINE ice_var_snwfra_1d
+   
+   !!--------------------------------------------------------------------------
+   !! INTERFACE ice_var_snwblow
+   !!
+   !! ** Purpose :   Compute distribution of precip over the ice
+   !!
+   !!                Snow accumulation in one thermodynamic time step
+   !!                snowfall is partitionned between leads and ice.
+   !!                If snow fall was uniform, a fraction (1-at_i) would fall into leads
+   !!                but because of the winds, more snow falls on leads than on sea ice
+   !!                and a greater fraction (1-at_i)^beta of the total mass of snow 
+   !!                (beta < 1) falls in leads.
+   !!                In reality, beta depends on wind speed, 
+   !!                and should decrease with increasing wind speed but here, it is 
+   !!                considered as a constant. an average value is 0.66
+   !!--------------------------------------------------------------------------
+!!gm  I think it can be usefull to set this as a FUNCTION, not a SUBROUTINE....
+   SUBROUTINE ice_var_snwblow_2d( pin, pout )
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) :: pin   ! previous fraction lead ( 1. - a_i_b )
+      REAL(wp), DIMENSION(:,:), INTENT(inout) :: pout
+      pout = ( 1._wp - ( pin )**rn_snwblow )
+   END SUBROUTINE ice_var_snwblow_2d
+
+   SUBROUTINE ice_var_snwblow_1d( pin, pout )
+      REAL(wp), DIMENSION(:), INTENT(in   ) :: pin
+      REAL(wp), DIMENSION(:), INTENT(inout) :: pout
+      pout = ( 1._wp - ( pin )**rn_snwblow )
+   END SUBROUTINE ice_var_snwblow_1d
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option         Dummy module           NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icevar
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icewri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icewri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/ICE/icewri.F90	(revision 14097)
@@ -0,0 +1,272 @@
+MODULE icewri
+   !!======================================================================
+   !!                     ***  MODULE  icewri  ***
+   !!   sea-ice : output ice variables
+   !!======================================================================
+   !! History :  4.0  !  2018     (many people)      SI3 [aka Sea Ice cube]
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   ice_wri       : write of the diagnostics variables in ouput file 
+   !!   ice_wri_state : write for initial state or/and abandon
+   !!----------------------------------------------------------------------
+   USE dianam         ! build name of file (routine)
+   USE phycst         ! physical constant
+   USE dom_oce        ! domain: ocean
+   USE sbc_oce        ! surf. boundary cond.: ocean
+   USE sbc_ice        ! Surface boundary condition: ice fields
+   USE ice            ! sea-ice: variables
+   USE icevar         ! sea-ice: operations
+   !
+   USE ioipsl         !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! fortran utilities (glob_sum + no signed zero)
+   USE lbclnk         ! lateral boundary conditions (or mpp links)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ice_wri        ! called by ice_stp
+   PUBLIC ice_wri_state  ! called by dia_wri_state 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/ICE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ice_wri( kt )
+      !!-------------------------------------------------------------------
+      !!  This routine ouputs some (most?) of the sea ice fields
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time-step
+      !
+      INTEGER  ::   ji, jj, jk, jl  ! dummy loop indices
+      REAL(wp) ::   z2da, z2db, zrho1, zrho2
+      REAL(wp) ::   zmiss_val       ! missing value retrieved from xios 
+      REAL(wp), DIMENSION(jpi,jpj)     ::   z2d, zfast                     ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zmsk00, zmsk05, zmsk15, zmsksn ! O%, 5% and 15% concentration mask and snow mask
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zmsk00l, zmsksnl               ! cat masks
+      !
+      ! Global ice diagnostics (SIMIP)
+      REAL(wp) ::   zdiag_area_nh, zdiag_extt_nh, zdiag_volu_nh   ! area, extent, volume
+      REAL(wp) ::   zdiag_area_sh, zdiag_extt_sh, zdiag_volu_sh 
+      !!-------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('icewri')
+
+      ! get missing value from xml
+      CALL iom_miss_val( 'icetemp', zmiss_val )
+
+      ! brine volume
+      CALL ice_var_bv
+
+      ! tresholds for outputs
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zmsk00(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06  ) ) ! 1 if ice    , 0 if no ice
+            zmsk05(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.05_wp ) ) ! 1 if 5% ice , 0 if less
+            zmsk15(ji,jj) = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - 0.15_wp ) ) ! 1 if 15% ice, 0 if less
+            zmsksn(ji,jj) = MAX( 0._wp , SIGN( 1._wp , vt_s(ji,jj) - epsi06  ) ) ! 1 if snow   , 0 if no snow
+         END DO
+      END DO
+      DO jl = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zmsk00l(ji,jj,jl)  = MAX( 0._wp , SIGN( 1._wp , a_i(ji,jj,jl) - epsi06 ) )
+               zmsksnl(ji,jj,jl)  = MAX( 0._wp , SIGN( 1._wp , v_s(ji,jj,jl) - epsi06 ) )
+            END DO
+         END DO
+      END DO
+
+      !-----------------
+      ! Standard outputs
+      !-----------------
+      zrho1 = ( rau0 - rhoi ) * r1_rau0 ; zrho2 = rhos * r1_rau0
+      ! masks
+      CALL iom_put( 'icemask'  , zmsk00 )   ! ice mask 0%
+      CALL iom_put( 'icemask05', zmsk05 )   ! ice mask 5%
+      CALL iom_put( 'icemask15', zmsk15 )   ! ice mask 15%
+      CALL iom_put( 'icepres'  , zmsk00 )   ! Ice presence (1 or 0) 
+      !
+      ! general fields
+      IF( iom_use('icemass' ) )   CALL iom_put( 'icemass', vt_i * rhoi * zmsk00 )                                           ! Ice mass per cell area 
+      IF( iom_use('snwmass' ) )   CALL iom_put( 'snwmass', vt_s * rhos * zmsksn )                                           ! Snow mass per cell area
+      IF( iom_use('iceconc' ) )   CALL iom_put( 'iceconc', at_i        * zmsk00 )                                           ! ice concentration
+      IF( iom_use('icevolu' ) )   CALL iom_put( 'icevolu', vt_i        * zmsk00 )                                           ! ice volume = mean ice thickness over the cell
+      IF( iom_use('icethic' ) )   CALL iom_put( 'icethic', hm_i        * zmsk00 )                                           ! ice thickness
+      IF( iom_use('snwthic' ) )   CALL iom_put( 'snwthic', hm_s        * zmsk00 )                                           ! snw thickness
+      IF( iom_use('icebrv'  ) )   CALL iom_put( 'icebrv' , bvm_i* 100. * zmsk00 )                                           ! brine volume
+      IF( iom_use('iceage'  ) )   CALL iom_put( 'iceage' , om_i / rday * zmsk15 + zmiss_val * ( 1._wp - zmsk15 ) )          ! ice age
+      IF( iom_use('icehnew' ) )   CALL iom_put( 'icehnew', ht_i_new             )                                           ! new ice thickness formed in the leads
+      IF( iom_use('snwvolu' ) )   CALL iom_put( 'snwvolu', vt_s        * zmsksn )                                           ! snow volume
+      IF( iom_use('icefrb'  ) ) THEN                                                                                        ! Ice freeboard
+         z2d(:,:) = ( zrho1 * hm_i(:,:) - zrho2 * hm_s(:,:) )                                         
+         WHERE( z2d < 0._wp )   z2d = 0._wp
+                                  CALL iom_put( 'icefrb' , z2d * zmsk00         )
+      ENDIF
+      ! melt ponds
+      IF( iom_use('iceapnd' ) )   CALL iom_put( 'iceapnd', at_ip  * zmsk00      )                                           ! melt pond total fraction
+      IF( iom_use('icehpnd' ) )   CALL iom_put( 'icehpnd', hm_ip  * zmsk00      )                                           ! melt pond depth
+      IF( iom_use('icevpnd' ) )   CALL iom_put( 'icevpnd', vt_ip  * zmsk00      )                                           ! melt pond total volume per unit area
+      IF( iom_use('icehlid' ) )   CALL iom_put( 'icehlid', hm_il  * zmsk00      )                                           ! melt pond lid depth
+      IF( iom_use('icevlid' ) )   CALL iom_put( 'icevlid', vt_il  * zmsk00      )                                           ! melt pond lid total volume per unit area
+      ! salt
+      IF( iom_use('icesalt' ) )   CALL iom_put( 'icesalt', sm_i                 * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) ) ! mean ice salinity
+      IF( iom_use('icesalm' ) )   CALL iom_put( 'icesalm', st_i * rhoi * 1.0e-3 * zmsk00 )                                  ! Mass of salt in sea ice per cell area
+      ! heat
+      IF( iom_use('icetemp' ) )   CALL iom_put( 'icetemp', ( tm_i  - rt0 ) * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) )      ! ice mean temperature
+      IF( iom_use('snwtemp' ) )   CALL iom_put( 'snwtemp', ( tm_s  - rt0 ) * zmsksn + zmiss_val * ( 1._wp - zmsksn ) )      ! snw mean temperature
+      IF( iom_use('icettop' ) )   CALL iom_put( 'icettop', ( tm_su - rt0 ) * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) )      ! temperature at the ice surface
+      IF( iom_use('icetbot' ) )   CALL iom_put( 'icetbot', ( t_bo  - rt0 ) * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) )      ! temperature at the ice bottom
+      IF( iom_use('icetsni' ) )   CALL iom_put( 'icetsni', ( tm_si - rt0 ) * zmsk00 + zmiss_val * ( 1._wp - zmsk00 ) )      ! temperature at the snow-ice interface
+      IF( iom_use('icehc'   ) )   CALL iom_put( 'icehc'  ,  -et_i          * zmsk00 )                                       ! ice heat content
+      IF( iom_use('snwhc'   ) )   CALL iom_put( 'snwhc'  ,  -et_s          * zmsksn )                                       ! snow heat content
+      ! momentum
+      IF( iom_use('uice'    ) )   CALL iom_put( 'uice'   , u_ice    )                                                       ! ice velocity u
+      IF( iom_use('vice'    ) )   CALL iom_put( 'vice'   , v_ice    )                                                       ! ice velocity v
+      !
+      IF( iom_use('icevel') .OR. iom_use('fasticepres') ) THEN                                                              ! module of ice velocity
+         DO jj = 2 , jpjm1
+            DO ji = 2 , jpim1
+               z2da  = u_ice(ji,jj) + u_ice(ji-1,jj)
+               z2db  = v_ice(ji,jj) + v_ice(ji,jj-1)
+               z2d(ji,jj) = 0.5_wp * SQRT( z2da * z2da + z2db * z2db )
+           END DO
+         END DO
+         CALL lbc_lnk( 'icewri', z2d, 'T', 1. )
+         CALL iom_put( 'icevel', z2d )
+
+         WHERE( z2d(:,:) < 5.e-04_wp .AND. zmsk15(:,:) == 1._wp ) ; zfast(:,:) = 1._wp                                      ! record presence of fast ice
+         ELSEWHERE                                                ; zfast(:,:) = 0._wp
+         END WHERE
+         CALL iom_put( 'fasticepres', zfast )
+      ENDIF
+
+      ! --- category-dependent fields --- !
+      IF( iom_use('icemask_cat' ) )   CALL iom_put( 'icemask_cat' ,                  zmsk00l                                   ) ! ice mask 0%
+      IF( iom_use('iceconc_cat' ) )   CALL iom_put( 'iceconc_cat' , a_i            * zmsk00l                                   ) ! area for categories
+      IF( iom_use('icethic_cat' ) )   CALL iom_put( 'icethic_cat' , h_i            * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! thickness for categories
+      IF( iom_use('snwthic_cat' ) )   CALL iom_put( 'snwthic_cat' , h_s            * zmsksnl + zmiss_val * ( 1._wp - zmsksnl ) ) ! snow depth for categories
+      IF( iom_use('icesalt_cat' ) )   CALL iom_put( 'icesalt_cat' , s_i            * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! salinity for categories
+      IF( iom_use('iceage_cat'  ) )   CALL iom_put( 'iceage_cat'  , o_i / rday     * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! ice age
+      IF( iom_use('icetemp_cat' ) )   CALL iom_put( 'icetemp_cat' , ( SUM( t_i, dim=3 ) * r1_nlay_i - rt0 ) &
+         &                                                                         * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! ice temperature
+      IF( iom_use('snwtemp_cat' ) )   CALL iom_put( 'snwtemp_cat' , ( SUM( t_s, dim=3 ) * r1_nlay_s - rt0 ) &
+         &                                                                         * zmsksnl + zmiss_val * ( 1._wp - zmsksnl ) ) ! snow temperature
+      IF( iom_use('icettop_cat' ) )   CALL iom_put( 'icettop_cat' , ( t_su - rt0 ) * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! surface temperature
+      IF( iom_use('icebrv_cat'  ) )   CALL iom_put( 'icebrv_cat'  ,   bv_i * 100.  * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! brine volume
+      IF( iom_use('iceapnd_cat' ) )   CALL iom_put( 'iceapnd_cat' ,   a_ip         * zmsk00l                                   ) ! melt pond frac for categories
+      IF( iom_use('icehpnd_cat' ) )   CALL iom_put( 'icehpnd_cat' ,   h_ip         * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! melt pond thickness for categories
+      IF( iom_use('icehlid_cat' ) )   CALL iom_put( 'icehlid_cat' ,   h_il         * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! melt pond lid thickness for categories
+      IF( iom_use('iceafpnd_cat') )   CALL iom_put( 'iceafpnd_cat',   a_ip_frac    * zmsk00l                                   ) ! melt pond frac for categories
+      IF( iom_use('iceaepnd_cat') )   CALL iom_put( 'iceaepnd_cat',   a_ip_eff     * zmsk00l                                   ) ! melt pond effective frac for categories
+      IF( iom_use('icealb_cat'  ) )   CALL iom_put( 'icealb_cat'  ,   alb_ice      * zmsk00l + zmiss_val * ( 1._wp - zmsk00l ) ) ! ice albedo for categories
+
+      !------------------
+      ! Add-ons for SIMIP
+      !------------------
+      ! trends
+      IF( iom_use('dmithd') )   CALL iom_put( 'dmithd', - wfx_bog - wfx_bom - wfx_sum - wfx_sni - wfx_opw - wfx_lam - wfx_res ) ! Sea-ice mass change from thermodynamics
+      IF( iom_use('dmidyn') )   CALL iom_put( 'dmidyn', - wfx_dyn + rhoi * diag_trp_vi                                        ) ! Sea-ice mass change from dynamics(kg/m2/s)
+      IF( iom_use('dmiopw') )   CALL iom_put( 'dmiopw', - wfx_opw                                                             ) ! Sea-ice mass change through growth in open water
+      IF( iom_use('dmibog') )   CALL iom_put( 'dmibog', - wfx_bog                                                             ) ! Sea-ice mass change through basal growth
+      IF( iom_use('dmisni') )   CALL iom_put( 'dmisni', - wfx_sni                                                             ) ! Sea-ice mass change through snow-to-ice conversion
+      IF( iom_use('dmisum') )   CALL iom_put( 'dmisum', - wfx_sum                                                             ) ! Sea-ice mass change through surface melting
+      IF( iom_use('dmibom') )   CALL iom_put( 'dmibom', - wfx_bom                                                             ) ! Sea-ice mass change through bottom melting
+      IF( iom_use('dmilam') )   CALL iom_put( 'dmilam', - wfx_lam                                                             ) ! Sea-ice mass change through lateral melting
+      IF( iom_use('dmtsub') )   CALL iom_put( 'dmtsub', - wfx_sub                                                             ) ! Sea-ice mass change through evaporation and sublimation
+      IF( iom_use('dmssub') )   CALL iom_put( 'dmssub', - wfx_snw_sub                                                         ) ! Snow mass change through sublimation
+      IF( iom_use('dmisub') )   CALL iom_put( 'dmisub', - wfx_ice_sub                                                         ) ! Sea-ice mass change through sublimation
+      IF( iom_use('dmsspr') )   CALL iom_put( 'dmsspr', - wfx_spr                                                             ) ! Snow mass change through snow fall
+      IF( iom_use('dmsssi') )   CALL iom_put( 'dmsssi',   wfx_sni*rhos*r1_rhoi                                                ) ! Snow mass change through snow-to-ice conversion
+      IF( iom_use('dmsmel') )   CALL iom_put( 'dmsmel', - wfx_snw_sum                                                         ) ! Snow mass change through melt
+      IF( iom_use('dmsdyn') )   CALL iom_put( 'dmsdyn', - wfx_snw_dyn + rhos * diag_trp_vs                                    ) ! Snow mass change through dynamics(kg/m2/s)
+      
+      ! Global ice diagnostics
+      IF(  iom_use('NH_icearea') .OR. iom_use('NH_icevolu') .OR. iom_use('NH_iceextt') .OR. &
+         & iom_use('SH_icearea') .OR. iom_use('SH_icevolu') .OR. iom_use('SH_iceextt') ) THEN
+         !
+         WHERE( ff_t(:,:) > 0._wp )   ;   z2d(:,:) = 1._wp
+         ELSEWHERE                    ;   z2d(:,:) = 0.
+         END WHERE
+         !
+         IF( iom_use('NH_icearea') )   zdiag_area_nh = glob_sum( 'icewri', at_i *           z2d   * e1e2t * 1.e-12 )
+         IF( iom_use('NH_icevolu') )   zdiag_volu_nh = glob_sum( 'icewri', vt_i *           z2d   * e1e2t * 1.e-12 )
+         IF( iom_use('NH_iceextt') )   zdiag_extt_nh = glob_sum( 'icewri',                  z2d   * e1e2t * 1.e-12 * zmsk15 )
+         !
+         IF( iom_use('SH_icearea') )   zdiag_area_sh = glob_sum( 'icewri', at_i * ( 1._wp - z2d ) * e1e2t * 1.e-12 )
+         IF( iom_use('SH_icevolu') )   zdiag_volu_sh = glob_sum( 'icewri', vt_i * ( 1._wp - z2d ) * e1e2t * 1.e-12 )
+         IF( iom_use('SH_iceextt') )   zdiag_extt_sh = glob_sum( 'icewri',        ( 1._wp - z2d ) * e1e2t * 1.e-12 * zmsk15 )
+         !
+         CALL iom_put( 'NH_icearea' , zdiag_area_nh )
+         CALL iom_put( 'NH_icevolu' , zdiag_volu_nh )
+         CALL iom_put( 'NH_iceextt' , zdiag_extt_nh )
+         CALL iom_put( 'SH_icearea' , zdiag_area_sh )
+         CALL iom_put( 'SH_icevolu' , zdiag_volu_sh )
+         CALL iom_put( 'SH_iceextt' , zdiag_extt_sh )
+         !
+      ENDIF
+      !
+!!CR      !     !  Create an output files (output.lim.abort.nc) if S < 0 or u > 20 m/s
+!!CR      !     IF( kindic < 0 )   CALL ice_wri_state( 'output.abort' )
+!!CR      !     not yet implemented
+!!gm  idem for the ocean...  Ask Seb how to get rid of ioipsl....
+      !
+      IF( ln_timing )  CALL timing_stop('icewri')
+      !
+   END SUBROUTINE ice_wri
+
+ 
+   SUBROUTINE ice_wri_state( kid )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE ice_wri_state  ***
+      !!        
+      !! ** Purpose :   create a NetCDF file named cdfile_name which contains 
+      !!      the instantaneous ice state and forcing fields for ice model
+      !!        Used to find errors in the initial state or save the last
+      !!      ocean state in case of abnormal end of a simulation
+      !!
+      !! History :   4.0  !  2013-06  (C. Rousset)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kid 
+      !!----------------------------------------------------------------------
+      !
+      !! The file is open in dia_wri_state (ocean routine)
+
+      CALL iom_rstput( 0, 0, kid, 'sithic', hm_i         )   ! Ice thickness
+      CALL iom_rstput( 0, 0, kid, 'siconc', at_i         )   ! Ice concentration
+      CALL iom_rstput( 0, 0, kid, 'sitemp', tm_i - rt0   )   ! Ice temperature
+      CALL iom_rstput( 0, 0, kid, 'sivelu', u_ice        )   ! i-Ice speed
+      CALL iom_rstput( 0, 0, kid, 'sivelv', v_ice        )   ! j-Ice speed
+      CALL iom_rstput( 0, 0, kid, 'sistru', utau_ice     )   ! i-Wind stress over ice
+      CALL iom_rstput( 0, 0, kid, 'sistrv', vtau_ice     )   ! i-Wind stress over ice
+      CALL iom_rstput( 0, 0, kid, 'sisflx', qsr          )   ! Solar flx over ocean
+      CALL iom_rstput( 0, 0, kid, 'sinflx', qns          )   ! NonSolar flx over ocean
+      CALL iom_rstput( 0, 0, kid, 'snwpre', sprecip      )   ! Snow precipitation
+      CALL iom_rstput( 0, 0, kid, 'sisali', sm_i         )   ! Ice salinity
+      CALL iom_rstput( 0, 0, kid, 'sivolu', vt_i         )   ! Ice volume
+      CALL iom_rstput( 0, 0, kid, 'sidive', divu_i*1.0e8 )   ! Ice divergence
+      CALL iom_rstput( 0, 0, kid, 'si_amp', at_ip        )   ! Melt pond fraction
+      CALL iom_rstput( 0, 0, kid, 'si_vmp', vt_ip        )   ! Melt pond volume
+      CALL iom_rstput( 0, 0, kid, 'sithicat', h_i        )   ! Ice thickness
+      CALL iom_rstput( 0, 0, kid, 'siconcat', a_i        )   ! Ice concentration
+      CALL iom_rstput( 0, 0, kid, 'sisalcat', s_i        )   ! Ice salinity
+      CALL iom_rstput( 0, 0, kid, 'snthicat', h_s        )   ! Snw thickness
+
+    END SUBROUTINE ice_wri_state
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :         Empty module         NO SI3 sea-ice model
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE icewri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif2model.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif2model.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif2model.F90	(revision 14097)
@@ -0,0 +1,89 @@
+#if defined key_agrif
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+SUBROUTINE Agrif2Model
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif2Model ***
+      !!--------------------------------------------- 
+END SUBROUTINE Agrif2model
+
+SUBROUTINE Agrif_Set_numberofcells(Agrif_Gr)
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Set_numberofcells ***
+      !!--------------------------------------------- 
+   USE Agrif_Grids
+   IMPLICIT NONE
+
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
+
+   IF ( ASSOCIATED(Agrif_Curgrid) )THEN
+#include "SetNumberofcells.h"
+   ENDIF
+
+END SUBROUTINE Agrif_Set_numberofcells
+
+SUBROUTINE Agrif_Get_numberofcells(Agrif_Gr)
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Get_numberofcells ***
+      !!--------------------------------------------- 
+   USE Agrif_Grids
+   IMPLICIT NONE
+
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
+
+   IF ( ASSOCIATED(Agrif_Curgrid) ) THEN
+#include "GetNumberofcells.h"
+   ENDIF
+
+END SUBROUTINE Agrif_Get_numberofcells
+
+SUBROUTINE Agrif_Allocationcalls(Agrif_Gr)
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Allocationscalls ***
+      !!--------------------------------------------- 
+   USE Agrif_Grids 
+#include "include_use_Alloc_agrif.h"
+   IMPLICIT NONE
+
+   TYPE(Agrif_Grid), POINTER :: Agrif_Gr
+
+#include "allocations_calls_agrif.h"
+
+END SUBROUTINE Agrif_Allocationcalls
+
+SUBROUTINE Agrif_probdim_modtype_def()
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_probdim_modtype_def ***
+      !!--------------------------------------------- 
+   USE Agrif_Types
+   IMPLICIT NONE
+
+#include "modtype_agrif.h"
+#include "probdim_agrif.h"
+#include "keys_agrif.h"
+
+   RETURN
+
+END SUBROUTINE Agrif_probdim_modtype_def
+
+SUBROUTINE Agrif_clustering_def()
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_clustering_def ***
+      !!--------------------------------------------- 
+   IMPLICIT NONE
+
+   RETURN
+
+END SUBROUTINE Agrif_clustering_def
+
+#else
+SUBROUTINE Agrif2Model
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif2Model ***
+      !!--------------------------------------------- 
+   WRITE(*,*) 'Impossible to bet here'
+END SUBROUTINE Agrif2model
+#endif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_all_update.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_all_update.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_all_update.F90	(revision 14097)
@@ -0,0 +1,84 @@
+#define TWO_WAY
+
+ MODULE agrif_all_update
+   !!======================================================================
+   !!                   ***  MODULE  agrif_all_update  ***
+   !! AGRIF: Main update driver for ocean, ice and passive tracers
+   !!======================================================================
+   !! History :  4.0  !  2018-06  (J. Chanut)  Original code 
+   !!----------------------------------------------------------------------
+#if defined key_agrif 
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!----------------------------------------------------------------------
+   USE dom_oce
+   USE agrif_oce
+   USE agrif_oce_update
+#if defined key_top
+   USE agrif_top_update
+#endif
+#if defined key_si3
+   USE agrif_ice_update
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   Agrif_Update_All
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_Update_All( )
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_Update_All ***
+      !!
+      !! ** Purpose :: Update nested grids for all components (Ocean, Sea Ice, TOP)
+      !!               Order of update matters here !
+      !!----------------------------------------------------------------------
+# if defined TWO_WAY
+      IF (Agrif_Root()) RETURN
+      !
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) ' --> START AGRIF UPDATE from grid Number',Agrif_Fixed()
+      !
+      CALL Agrif_Update_ssh()                      ! Update sea level
+      !
+      IF (.NOT.ln_linssh) CALL Agrif_Update_vvl()  ! Update scale factors
+      !
+      CALL Agrif_Update_tra()                      ! Update temperature/salinity
+      !
+#if defined key_top
+      CALL Agrif_Update_Trc()                      ! Update passive tracers
+#endif
+      !
+      CALL Agrif_Update_dyn()                      ! Update dynamics
+      !
+! JC remove update because this precludes from perfect restartability
+!!      CALL Agrif_Update_tke()                  ! Update tke 
+
+#if defined key_si3
+      CALL agrif_update_ice()                      ! Update sea ice
+#endif
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) ' <-- END AGRIF UPDATE from grid Number',Agrif_Fixed()
+      !
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+#endif
+    END SUBROUTINE agrif_Update_All
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                          no AGRIF zoom
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE Agrif_Update_all( )
+      WRITE(*,*)  'Agrif_Update_All : You should not have seen this print! error?'
+   END SUBROUTINE Agrif_Update_all
+#endif
+
+   !!======================================================================
+END MODULE agrif_all_update
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice.F90	(revision 14097)
@@ -0,0 +1,28 @@
+MODULE agrif_ice
+   !!======================================================================
+   !!                       ***  MODULE agrif_ice  ***
+   !! AGRIF :   define in memory AGRIF variables for sea-ice
+   !!----------------------------------------------------------------------
+   !! History :  3.4   !  2012-08  (R. Benshila)          Original code
+   !!            4.0   !  2018     (C. Rousset)           SI3 compatibility
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!   'key_si3'                                         SI3 sea-ice model
+   !!----------------------------------------------------------------------   
+   IMPLICIT NONE
+   PRIVATE 
+
+   INTEGER, PUBLIC ::  u_ice_id, v_ice_id, tra_ice_id
+   INTEGER, PUBLIC ::  nbstep_ice = 0    ! child time position in sea-ice model
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+#endif
+   !!======================================================================
+END MODULE agrif_ice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_interp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_interp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_interp.F90	(revision 14097)
@@ -0,0 +1,382 @@
+MODULE agrif_ice_interp
+   !!=====================================================================================
+   !!                       ***  MODULE agrif_ice_interp ***
+   !! Nesting module :  interp surface ice boundary condition from a parent grid
+   !!=====================================================================================
+   !! History :  2.0   !  04-2008  (F. Dupont)               initial version
+   !!            3.4   !  09-2012  (R. Benshila, C. Herbaut) update and EVP
+   !!            4.0   !  2018     (C. Rousset)              SI3 compatibility
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_si3 
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                         SI3 sea-ice model
+   !!   'key_agrif'                                       AGRIF library
+   !!----------------------------------------------------------------------
+   !!  agrif_interp_ice    : interpolation of ice at "after" sea-ice time step
+   !!  agrif_interp_u_ice   : atomic routine to interpolate u_ice 
+   !!  agrif_interp_v_ice   : atomic routine to interpolate v_ice 
+   !!  agrif_interp_tra_ice : atomic routine to interpolate ice properties 
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE dom_oce
+   USE sbc_oce
+   USE ice
+   USE agrif_ice
+   USE phycst , ONLY: rt0
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   agrif_interp_ice   ! called by agrif_user.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE agrif_interp_ice( cd_type, kiter, kitermax )
+      !!-----------------------------------------------------------------------
+      !!                 *** ROUTINE agrif_interp_ice  ***
+      !!
+      !!  ** Method  : simple call to atomic routines using stored values to
+      !!  fill the boundaries depending of the position of the point and
+      !!  computing factor for time interpolation
+      !!-----------------------------------------------------------------------
+      CHARACTER(len=1), INTENT(in   )           ::   cd_type
+      INTEGER         , INTENT(in   ), OPTIONAL ::   kiter, kitermax
+      !!
+      REAL(wp) ::   zbeta   ! local scalar
+      !!-----------------------------------------------------------------------
+      !
+      IF( Agrif_Root() .OR. nn_ice==0 )  RETURN   ! do not interpolate if inside Parent Grid or if child domain does not have ice
+      !
+      SELECT CASE( cd_type )
+      CASE('U','V')
+         IF( PRESENT( kiter ) ) THEN  ! interpolation at the child ice sub-time step (only for ice rheology)
+            zbeta = ( REAL(nbstep_ice) - REAL(kitermax - kiter) / REAL(kitermax) ) /  &
+               &    ( Agrif_Rhot() * REAL(Agrif_Parent(nn_fsbc)) / REAL(nn_fsbc) )
+         ELSE                         ! interpolation at the child ice time step
+            zbeta = REAL(nbstep_ice) / ( Agrif_Rhot() * REAL(Agrif_Parent(nn_fsbc)) / REAL(nn_fsbc) )
+         ENDIF
+      CASE('T')
+            zbeta = REAL(nbstep_ice) / ( Agrif_Rhot() * REAL(Agrif_Parent(nn_fsbc)) / REAL(nn_fsbc) )
+      END SELECT
+      !
+      Agrif_SpecialValue    = -9999.
+      Agrif_UseSpecialValue = .TRUE.
+      SELECT CASE( cd_type )
+      CASE('U')   ;   CALL Agrif_Bc_variable( u_ice_id  , procname=interp_u_ice  , calledweight=zbeta )
+      CASE('V')   ;   CALL Agrif_Bc_variable( v_ice_id  , procname=interp_v_ice  , calledweight=zbeta )
+      CASE('T')   ;   CALL Agrif_Bc_variable( tra_ice_id, procname=interp_tra_ice, calledweight=zbeta )
+      END SELECT
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE agrif_interp_ice
+
+
+   SUBROUTINE interp_u_ice( ptab, i1, i2, j1, j2, before )
+      !!-----------------------------------------------------------------------
+      !!                     *** ROUTINE interp_u_ice ***
+      !!
+      !! i1 i2 j1 j2 are the index of the boundaries parent(when before) and child (when after)
+      !! To solve issues when parent grid is "land" masked but not all the corresponding child 
+      !! grid points, put Agrif_SpecialValue WHERE the parent grid is masked. 
+      !! The child solution will be found in the 9(?) points around
+      !!-----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      REAL(wp) ::   zrhoy   ! local scalar
+      !!-----------------------------------------------------------------------
+      !
+      IF( before ) THEN  ! parent grid
+         ptab(:,:) = e2u(i1:i2,j1:j2) * u_ice(i1:i2,j1:j2)
+         WHERE( umask(i1:i2,j1:j2,1) == 0. )   ptab(i1:i2,j1:j2) = Agrif_SpecialValue
+      ELSE               ! child grid
+         zrhoy = Agrif_Rhoy()
+         u_ice(i1:i2,j1:j2) = ptab(i1:i2,j1:j2) / ( e2u(i1:i2,j1:j2) * zrhoy ) * umask(i1:i2,j1:j2,1)
+      ENDIF
+      !
+   END SUBROUTINE interp_u_ice
+
+
+   SUBROUTINE interp_v_ice( ptab, i1, i2, j1, j2, before )
+      !!-----------------------------------------------------------------------
+      !!                    *** ROUTINE interp_v_ice ***
+      !!
+      !! i1 i2 j1 j2 are the index of the boundaries parent(when before) and child (when after)
+      !! To solve issues when parent grid is "land" masked but not all the corresponding child 
+      !! grid points, put Agrif_SpecialValue WHERE the parent grid is masked. 
+      !! The child solution will be found in the 9(?) points around
+      !!-----------------------------------------------------------------------      
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      REAL(wp) ::   zrhox   ! local scalar
+      !!-----------------------------------------------------------------------
+      !
+      IF( before ) THEN  ! parent grid
+         ptab(:,:) = e1v(i1:i2,j1:j2) * v_ice(i1:i2,j1:j2)
+         WHERE( vmask(i1:i2,j1:j2,1) == 0. )   ptab(i1:i2,j1:j2) = Agrif_SpecialValue
+      ELSE               ! child grid
+         zrhox = Agrif_Rhox()
+         v_ice(i1:i2,j1:j2) = ptab(i1:i2,j1:j2) / ( e1v(i1:i2,j1:j2) * zrhox ) * vmask(i1:i2,j1:j2,1)
+      ENDIF
+      !
+   END SUBROUTINE interp_v_ice
+
+
+   SUBROUTINE interp_tra_ice( ptab, i1, i2, j1, j2, k1, k2, before, nb, ndir )
+      !!-----------------------------------------------------------------------
+      !!                    *** ROUTINE interp_tra_ice ***                           
+      !!
+      !! i1 i2 j1 j2 are the index of the boundaries parent(when before) and child (when after)
+      !! To solve issues when parent grid is "land" masked but not all the corresponding child 
+      !! grid points, put Agrif_SpecialValue WHERE the parent grid is masked. 
+      !! The child solution will be found in the 9(?) points around
+      !!-----------------------------------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      INTEGER                               , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      LOGICAL                               , INTENT(in   ) ::   before
+      INTEGER                               , INTENT(in   ) ::   nb, ndir
+      !!
+      INTEGER  ::   ji, jj, jk, jl, jm
+      INTEGER  ::   imin, imax, jmin, jmax
+      LOGICAL  ::   western_side, eastern_side, northern_side, southern_side
+      REAL(wp) ::   zrhox, z1, z2, z3, z4, z5, z6, z7
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztab
+      !!-----------------------------------------------------------------------
+      ! tracers are not multiplied by grid cell here => before: * e1e2t ; after: * r1_e1e2t / rhox / rhoy
+      ! and it is ok since we conserve tracers (same as in the ocean).
+      ALLOCATE( ztab(SIZE(a_i,1),SIZE(a_i,2),SIZE(ptab,3)) )
+     
+      IF( before ) THEN  ! parent grid
+         jm = 1
+         DO jl = 1, jpl
+            ptab(i1:i2,j1:j2,jm  ) = a_i (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+1) = v_i (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+2) = v_s (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+3) = sv_i(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+4) = oa_i(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+5) = a_ip(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+6) = v_ip(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+7) = v_il(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+8) = t_su(i1:i2,j1:j2,jl)
+            jm = jm + 9
+            DO jk = 1, nlay_s
+               ptab(i1:i2,j1:j2,jm) = e_s(i1:i2,j1:j2,jk,jl)   ;   jm = jm + 1
+            END DO
+            DO jk = 1, nlay_i
+               ptab(i1:i2,j1:j2,jm) = e_i(i1:i2,j1:j2,jk,jl)   ;   jm = jm + 1
+            END DO
+         END DO
+         
+         DO jk = k1, k2
+            WHERE( tmask(i1:i2,j1:j2,1) == 0._wp )   ptab(i1:i2,j1:j2,jk) = Agrif_SpecialValue
+         END DO
+         !
+      ELSE               ! child grid
+         !
+!         IF( nbghostcells > 1 ) THEN   ! ==> The easiest interpolation is used
+            !
+            jm = 1
+            DO jl = 1, jpl
+               !
+               DO jj = j1, j2
+                  DO ji = i1, i2
+                     a_i (ji,jj,jl) = ptab(ji,jj,jm  ) * tmask(ji,jj,1)
+                     v_i (ji,jj,jl) = ptab(ji,jj,jm+1) * tmask(ji,jj,1)
+                     v_s (ji,jj,jl) = ptab(ji,jj,jm+2) * tmask(ji,jj,1)
+                     sv_i(ji,jj,jl) = ptab(ji,jj,jm+3) * tmask(ji,jj,1)
+                     oa_i(ji,jj,jl) = ptab(ji,jj,jm+4) * tmask(ji,jj,1)
+                     a_ip(ji,jj,jl) = ptab(ji,jj,jm+5) * tmask(ji,jj,1)
+                     v_ip(ji,jj,jl) = ptab(ji,jj,jm+6) * tmask(ji,jj,1)
+                     v_il(ji,jj,jl) = ptab(ji,jj,jm+7) * tmask(ji,jj,1)
+                     t_su(ji,jj,jl) = ptab(ji,jj,jm+8) * tmask(ji,jj,1)
+                  END DO
+               END DO
+               jm = jm + 9
+               !
+               DO jk = 1, nlay_s
+                  e_s(i1:i2,j1:j2,jk,jl) = ptab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+                  jm = jm + 1
+               END DO
+               !
+               DO jk = 1, nlay_i
+                  e_i(i1:i2,j1:j2,jk,jl) = ptab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+                  jm = jm + 1
+               END DO
+               !
+            END DO
+            !
+!!==> clem: this interpolation does not work because it creates negative values, due
+!!          to negative coefficients when mixing points (for ex. z7)
+!!
+!         ELSE                          ! ==> complex interpolation (only one ghost cell available)
+!            !! Use a more complex interpolation since we mix solutions over a couple of grid points
+!            !! it is advised to use it for fields modified by high order schemes (e.g. advection UM5...)
+!            ! record ztab
+!            jm = 1
+!            DO jl = 1, jpl
+!               ztab(:,:,jm  ) = a_i (:,:,jl)
+!               ztab(:,:,jm+1) = v_i (:,:,jl)
+!               ztab(:,:,jm+2) = v_s (:,:,jl)
+!               ztab(:,:,jm+3) = sv_i(:,:,jl)
+!               ztab(:,:,jm+4) = oa_i(:,:,jl)
+!               ztab(:,:,jm+5) = a_ip(:,:,jl)
+!               ztab(:,:,jm+6) = v_ip(:,:,jl)
+!               ztab(:,:,jm+7) = v_il(:,:,jl)
+!               ztab(:,:,jm+8) = t_su(:,:,jl)
+!               jm = jm + 9
+!               DO jk = 1, nlay_s
+!                  ztab(:,:,jm) = e_s(:,:,jk,jl)
+!                  jm = jm + 1
+!               END DO
+!               DO jk = 1, nlay_i
+!                  ztab(:,:,jm) = e_i(:,:,jk,jl)
+!                  jm = jm + 1
+!               END DO
+!               !
+!            END DO
+!            !
+!            ! borders of the domain
+!            western_side  = (nb == 1).AND.(ndir == 1)  ;  eastern_side  = (nb == 1).AND.(ndir == 2)
+!            southern_side = (nb == 2).AND.(ndir == 1)  ;  northern_side = (nb == 2).AND.(ndir == 2)
+!            !
+!            ! spatial smoothing
+!            zrhox = Agrif_Rhox()
+!            z1 =      ( zrhox - 1. ) * 0.5 
+!            z3 =      ( zrhox - 1. ) / ( zrhox + 1. )
+!            z6 = 2. * ( zrhox - 1. ) / ( zrhox + 1. )
+!            z7 =    - ( zrhox - 1. ) / ( zrhox + 3. )
+!            z2 = 1. - z1
+!            z4 = 1. - z3
+!            z5 = 1. - z6 - z7
+!            !
+!            ! Remove corners
+!            imin = i1  ;  imax = i2  ;  jmin = j1  ;  jmax = j2
+!            IF( (nbondj == -1) .OR. (nbondj == 2) )   jmin = 3
+!            IF( (nbondj == +1) .OR. (nbondj == 2) )   jmax = nlcj-2
+!            IF( (nbondi == -1) .OR. (nbondi == 2) )   imin = 3
+!            IF( (nbondi == +1) .OR. (nbondi == 2) )   imax = nlci-2
+!
+!            ! smoothed fields
+!            IF( eastern_side ) THEN
+!               ztab(nlci,j1:j2,:) = z1 * ptab(nlci,j1:j2,:) + z2 * ptab(nlci-1,j1:j2,:)
+!               DO jj = jmin, jmax
+!                  rswitch = 0.
+!                  IF( u_ice(nlci-2,jj) > 0._wp ) rswitch = 1.
+!                  ztab(nlci-1,jj,:) = ( 1. - umask(nlci-2,jj,1) ) * ztab(nlci,jj,:)  &
+!                     &                +      umask(nlci-2,jj,1)   *  &
+!                     &                ( ( 1. - rswitch ) * ( z4 * ztab(nlci,jj,:)   + z3 * ztab(nlci-2,jj,:) )  &
+!                     &                  +      rswitch   * ( z6 * ztab(nlci-2,jj,:) + z5 * ztab(nlci,jj,:) + z7 * ztab(nlci-3,jj,:) ) )
+!                  ztab(nlci-1,jj,:) = ztab(nlci-1,jj,:) * tmask(nlci-1,jj,1)
+!               END DO
+!            ENDIF
+!            ! 
+!            IF( northern_side ) THEN
+!               ztab(i1:i2,nlcj,:) = z1 * ptab(i1:i2,nlcj,:) + z2 * ptab(i1:i2,nlcj-1,:)
+!               DO ji = imin, imax
+!                  rswitch = 0.
+!                  IF( v_ice(ji,nlcj-2) > 0._wp ) rswitch = 1.
+!                  ztab(ji,nlcj-1,:) = ( 1. - vmask(ji,nlcj-2,1) ) * ztab(ji,nlcj,:)  &
+!                     &                +      vmask(ji,nlcj-2,1)   *  &
+!                     &                ( ( 1. - rswitch ) * ( z4 * ztab(ji,nlcj,:)   + z3 * ztab(ji,nlcj-2,:) ) &
+!                     &                  +      rswitch   * ( z6 * ztab(ji,nlcj-2,:) + z5 * ztab(ji,nlcj,:) + z7 * ztab(ji,nlcj-3,:) ) )
+!                  ztab(ji,nlcj-1,:) = ztab(ji,nlcj-1,:) * tmask(ji,nlcj-1,1)
+!               END DO
+!            END IF
+!            !
+!            IF( western_side) THEN
+!               ztab(1,j1:j2,:) = z1 * ptab(1,j1:j2,:) + z2 * ptab(2,j1:j2,:)
+!               DO jj = jmin, jmax
+!                  rswitch = 0.
+!                  IF( u_ice(2,jj) < 0._wp ) rswitch = 1.
+!                  ztab(2,jj,:) = ( 1. - umask(2,jj,1) ) * ztab(1,jj,:)  &
+!                     &           +      umask(2,jj,1)   *   &
+!                     &           ( ( 1. - rswitch ) * ( z4 * ztab(1,jj,:) + z3 * ztab(3,jj,:) ) &
+!                     &             +      rswitch   * ( z6 * ztab(3,jj,:) + z5 * ztab(1,jj,:) + z7 * ztab(4,jj,:) ) )
+!                  ztab(2,jj,:) = ztab(2,jj,:) * tmask(2,jj,1)
+!               END DO
+!            ENDIF
+!            !
+!            IF( southern_side ) THEN
+!               ztab(i1:i2,1,:) = z1 * ptab(i1:i2,1,:) + z2 * ptab(i1:i2,2,:)
+!               DO ji = imin, imax
+!                  rswitch = 0.
+!                  IF( v_ice(ji,2) < 0._wp ) rswitch = 1.
+!                  ztab(ji,2,:) = ( 1. - vmask(ji,2,1) ) * ztab(ji,1,:)  &
+!                     &           +      vmask(ji,2,1)   *  &
+!                     &           ( ( 1. - rswitch ) * ( z4 * ztab(ji,1,:) + z3 * ztab(ji,3,:) ) &
+!                     &             +      rswitch   * ( z6 * ztab(ji,3,:) + z5 * ztab(ji,1,:) + z7 * ztab(ji,4,:) ) )
+!                  ztab(ji,2,:) = ztab(ji,2,:) * tmask(ji,2,1)
+!               END DO
+!            END IF
+!            !
+!            ! Treatment of corners
+!            IF( (eastern_side) .AND. ((nbondj == -1).OR.(nbondj == 2)) )  ztab(nlci-1,2,:)      = ptab(nlci-1,2,:)      ! East south
+!            IF( (eastern_side) .AND. ((nbondj ==  1).OR.(nbondj == 2)) )  ztab(nlci-1,nlcj-1,:) = ptab(nlci-1,nlcj-1,:) ! East north
+!            IF( (western_side) .AND. ((nbondj == -1).OR.(nbondj == 2)) )  ztab(2,2,:)           = ptab(2,2,:)           ! West south
+!            IF( (western_side) .AND. ((nbondj ==  1).OR.(nbondj == 2)) )  ztab(2,nlcj-1,:)      = ptab(2,nlcj-1,:)      ! West north
+!            
+!            ! retrieve ice tracers
+!            jm = 1
+!            DO jl = 1, jpl
+!               !
+!               DO jj = j1, j2
+!                  DO ji = i1, i2
+!                     a_i (ji,jj,jl) = ztab(ji,jj,jm  ) * tmask(ji,jj,1)
+!                     v_i (ji,jj,jl) = ztab(ji,jj,jm+1) * tmask(ji,jj,1)
+!                     v_s (ji,jj,jl) = ztab(ji,jj,jm+2) * tmask(ji,jj,1)
+!                     sv_i(ji,jj,jl) = ztab(ji,jj,jm+3) * tmask(ji,jj,1)
+!                     oa_i(ji,jj,jl) = ztab(ji,jj,jm+4) * tmask(ji,jj,1)
+!                     a_ip(ji,jj,jl) = ztab(ji,jj,jm+5) * tmask(ji,jj,1)
+!                     v_ip(ji,jj,jl) = ztab(ji,jj,jm+6) * tmask(ji,jj,1)
+!                     v_il(ji,jj,jl) = ztab(ji,jj,jm+7) * tmask(ji,jj,1)
+!                     t_su(ji,jj,jl) = ztab(ji,jj,jm+8) * tmask(ji,jj,1)
+!                  END DO
+!               END DO
+!               jm = jm + 9
+!               !
+!               DO jk = 1, nlay_s
+!                  e_s(i1:i2,j1:j2,jk,jl) = ztab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+!                  jm = jm + 1
+!               END DO
+!               !
+!               DO jk = 1, nlay_i
+!                  e_i(i1:i2,j1:j2,jk,jl) = ztab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+!                  jm = jm + 1
+!               END DO
+!               !
+!            END DO
+!          
+!         ENDIF  ! nbghostcells=1
+         
+         DO jl = 1, jpl
+            WHERE( tmask(i1:i2,j1:j2,1) == 0._wp )   t_su(i1:i2,j1:j2,jl) = rt0   ! to avoid a division by 0 in sbcblk.F90
+         END DO
+         !
+      ENDIF
+      
+      DEALLOCATE( ztab )
+      !
+   END SUBROUTINE interp_tra_ice
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                             no sea-ice
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_ice_interp_empty
+      WRITE(*,*)  'agrif_ice_interp : You should not have seen this print! error?'
+   END SUBROUTINE agrif_ice_interp_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_ice_interp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_update.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_update.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_ice_update.F90	(revision 14097)
@@ -0,0 +1,233 @@
+#define TWO_WAY
+!!#undef TWO_WAY
+#undef DECAL_FEEDBACK  /* SEPARATION of INTERFACES*/
+
+MODULE agrif_ice_update
+   !!=====================================================================================
+   !!                       ***  MODULE agrif_ice_update ***
+   !! Nesting module :  update surface ocean boundary condition over ice from a child grid
+   !!=====================================================================================
+   !! History :  2.0   !  04-2008  (F. Dupont)               initial version
+   !!            3.4   !  08-2012  (R. Benshila, C. Herbaut) update and EVP
+   !!            4.0   !  2018     (C. Rousset)              SI3 compatibility
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'  :                                      SI3 sea-ice model
+   !!   'key_agrif' :                                     AGRIF library 
+   !!----------------------------------------------------------------------
+   !!   agrif_update_ice  : update sea-ice on boundaries or total
+   !!                        child domain for velocities and ice properties
+   !!   update_tra_ice    : sea-ice properties
+   !!   update_u_ice      : zonal      ice velocity
+   !!   update_v_ice      : meridional ice velocity
+   !!----------------------------------------------------------------------
+   USE dom_oce
+   USE sbc_oce
+   USE agrif_oce
+   USE ice
+   USE agrif_ice 
+   USE phycst , ONLY: rt0
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   agrif_update_ice   ! called by agrif_user.F90 and icestp.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE agrif_update_ice( )
+      !!----------------------------------------------------------------------
+      !!                     *** ROUTINE agrif_update_ice ***
+      !! ** Method  :   Call the hydrostaticupdate pressure at the boundary or the entire domain 
+      !!
+      !! ** Action : - Update (u_ice,v_ice) and ice tracers
+      !!----------------------------------------------------------------------
+      !
+      IF( Agrif_Root() .OR. nn_ice == 0 ) RETURN   ! do not update if inside Parent Grid or if child domain does not have ice
+      !
+!      IF( ( MOD( (kt-nit000)/nn_fsbc + 1, Agrif_irhot() * Agrif_Parent(nn_fsbc)/nn_fsbc ) /=0 ) .AND. (kt /= 0) ) RETURN   ! update only at the parent ice time step
+      IF ( MOD(Agrif_parent_nb_step(), Agrif_Parent(nn_fsbc)) /=0 ) RETURN   ! Update only at the parent ice time step
+                                                                             ! It is assumed that at such a time, there is a child ice step which is true
+                                                                             ! as long as MOD( Agrif_irhot() * Agrif_Parent(nn_fsbc), nn_fsbc )==0. 
+                                                                             ! (This condition is checked in agrif_user, Agrif_InitValues_cont_ice subroutine)
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update sea ice from grid Number',Agrif_Fixed(), agrif_nb_step()
+      !
+      !
+      Agrif_SpecialValueFineGrid    = -9999.
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+
+# if defined TWO_WAY
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable( tra_ice_id , procname = update_tra_ice  )
+#else
+      CALL Agrif_Update_Variable( tra_ice_id , locupdate=(/1,0/), procname = update_tra_ice  )
+#endif
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable( u_ice_id   , procname = update_u_ice    )
+      CALL Agrif_Update_Variable( v_ice_id   , procname = update_v_ice    )
+#else
+      CALL Agrif_Update_Variable( u_ice_id   , locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname=update_u_ice) 
+      CALL Agrif_Update_Variable( v_ice_id   , locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname=update_v_ice)
+#endif
+!      CALL Agrif_Update_Variable( tra_ice_id , locupdate=(/0,2/), procname = update_tra_ice  )
+!      CALL Agrif_Update_Variable( u_ice_id   , locupdate=(/0,1/), procname = update_u_ice    )
+!      CALL Agrif_Update_Variable( v_ice_id   , locupdate=(/0,1/), procname = update_v_ice    )
+# endif
+      Agrif_SpecialValueFineGrid    = 0.
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      !
+   END SUBROUTINE agrif_update_ice
+
+
+   SUBROUTINE update_tra_ice( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!-----------------------------------------------------------------------
+      !!                        *** ROUTINE update_tra_ice ***
+      !! ** Method  : Compute the mass properties on the fine grid and recover
+      !!              the properties per mass on the coarse grid
+      !!-----------------------------------------------------------------------
+      INTEGER                               , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                               , INTENT(in   ) ::   before
+      !!
+      INTEGER  :: ji, jj, jk, jl, jm
+      !!-----------------------------------------------------------------------
+      ! it is ok not to multiply by e1*e2 since we conserve tracers here (same as in the ocean).
+      IF( before ) THEN
+         jm = 1
+         DO jl = 1, jpl
+            ptab(i1:i2,j1:j2,jm  ) = a_i (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+1) = v_i (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+2) = v_s (i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+3) = sv_i(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+4) = oa_i(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+5) = a_ip(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+6) = v_ip(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+7) = v_il(i1:i2,j1:j2,jl)
+            ptab(i1:i2,j1:j2,jm+8) = t_su(i1:i2,j1:j2,jl)
+            jm = jm + 9
+            DO jk = 1, nlay_s
+               ptab(i1:i2,j1:j2,jm) = e_s(i1:i2,j1:j2,jk,jl)   ;   jm = jm + 1
+            END DO
+            DO jk = 1, nlay_i
+               ptab(i1:i2,j1:j2,jm) = e_i(i1:i2,j1:j2,jk,jl)   ;   jm = jm + 1
+            END DO
+         END DO
+         !
+         DO jk = k1, k2
+            WHERE( tmask(i1:i2,j1:j2,1) == 0. )   ptab(i1:i2,j1:j2,jk) = Agrif_SpecialValueFineGrid 
+         END DO
+         !
+      ELSE
+         !
+         jm = 1
+         DO jl = 1, jpl
+            !
+            DO jj = j1, j2
+               DO ji = i1, i2
+                  IF( ptab(ji,jj,jm) /= Agrif_SpecialValueFineGrid ) THEN
+                     a_i (ji,jj,jl) = ptab(ji,jj,jm  ) * tmask(ji,jj,1)
+                     v_i (ji,jj,jl) = ptab(ji,jj,jm+1) * tmask(ji,jj,1)
+                     v_s (ji,jj,jl) = ptab(ji,jj,jm+2) * tmask(ji,jj,1)
+                     sv_i(ji,jj,jl) = ptab(ji,jj,jm+3) * tmask(ji,jj,1)
+                     oa_i(ji,jj,jl) = ptab(ji,jj,jm+4) * tmask(ji,jj,1)
+                     a_ip(ji,jj,jl) = ptab(ji,jj,jm+5) * tmask(ji,jj,1)
+                     v_ip(ji,jj,jl) = ptab(ji,jj,jm+6) * tmask(ji,jj,1)
+                     v_il(ji,jj,jl) = ptab(ji,jj,jm+7) * tmask(ji,jj,1)
+                     t_su(ji,jj,jl) = ptab(ji,jj,jm+8) * tmask(ji,jj,1)
+                  ENDIF
+               END DO
+            END DO
+            jm = jm + 9
+            !
+            DO jk = 1, nlay_s
+               WHERE( ptab(i1:i2,j1:j2,jm) /= Agrif_SpecialValueFineGrid )
+                  e_s(i1:i2,j1:j2,jk,jl) = ptab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+               ENDWHERE
+               jm = jm + 1
+            END DO
+            !
+            DO jk = 1, nlay_i
+               WHERE( ptab(i1:i2,j1:j2,jm) /= Agrif_SpecialValueFineGrid )
+                  e_i(i1:i2,j1:j2,jk,jl) = ptab(i1:i2,j1:j2,jm) * tmask(i1:i2,j1:j2,1)
+               ENDWHERE
+               jm = jm + 1
+            END DO
+            !
+         END DO
+         !
+         DO jl = 1, jpl
+            WHERE( tmask(i1:i2,j1:j2,1) == 0._wp )   t_su(i1:i2,j1:j2,jl) = rt0   ! to avoid a division by 0 in sbcblk.F90
+         END DO
+         
+      ENDIF
+      !
+   END SUBROUTINE update_tra_ice
+
+
+   SUBROUTINE update_u_ice( ptab, i1, i2, j1, j2, before )
+      !!-----------------------------------------------------------------------
+      !!                        *** ROUTINE update_u_ice ***
+      !! ** Method  : Update the fluxes and recover the properties (C-grid)
+      !!-----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      REAL(wp) ::   zrhoy   ! local scalar
+      !!-----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         zrhoy = Agrif_Rhoy()
+         ptab(:,:) = e2u(i1:i2,j1:j2) * u_ice(i1:i2,j1:j2) * zrhoy
+         WHERE( umask(i1:i2,j1:j2,1) == 0._wp )   ptab(:,:) = Agrif_SpecialValueFineGrid
+      ELSE
+         WHERE( ptab(i1:i2,j1:j2) /= Agrif_SpecialValueFineGrid )
+            u_ice(i1:i2,j1:j2) = ptab(i1:i2,j1:j2) / e2u(i1:i2,j1:j2) * umask(i1:i2,j1:j2,1)
+         ENDWHERE
+      ENDIF
+      ! 
+   END SUBROUTINE update_u_ice
+
+
+   SUBROUTINE update_v_ice( ptab, i1, i2, j1, j2, before )
+      !!-----------------------------------------------------------------------
+      !!                    *** ROUTINE update_v_ice ***
+      !! ** Method  : Update the fluxes and recover the properties (C-grid)
+      !!-----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      REAL(wp) ::   zrhox   ! local scalar
+      !!-----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         zrhox = Agrif_Rhox()
+         ptab(:,:) = e1v(i1:i2,j1:j2) * v_ice(i1:i2,j1:j2) * zrhox
+         WHERE( vmask(i1:i2,j1:j2,1) == 0._wp )   ptab(:,:) = Agrif_SpecialValueFineGrid
+      ELSE
+         WHERE( ptab(i1:i2,j1:j2) /= Agrif_SpecialValueFineGrid )
+            v_ice(i1:i2,j1:j2) = ptab(i1:i2,j1:j2) / e1v(i1:i2,j1:j2) * vmask(i1:i2,j1:j2,1)
+         ENDWHERE
+      ENDIF
+      !
+   END SUBROUTINE update_v_ice
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                             no sea-ice
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_ice_update_empty
+      WRITE(*,*)  'agrif_ice_update : You should not have seen this print! error?'
+   END SUBROUTINE agrif_ice_update_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_ice_update
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce.F90	(revision 14097)
@@ -0,0 +1,322 @@
+MODULE agrif_oce
+   !!======================================================================
+   !!                       ***  MODULE agrif_oce  ***
+   !! AGRIF :   define in memory AGRIF variables
+   !!----------------------------------------------------------------------
+   !! History :  2.0  ! 2007-12  (R. Benshila)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_agrif
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!----------------------------------------------------------------------
+   USE par_oce      ! ocean parameters
+   USE dom_oce      ! domain parameters
+
+   IMPLICIT NONE
+   PRIVATE 
+
+   PUBLIC agrif_oce_alloc ! routine called by nemo_init in nemogcm.F90
+#if defined key_vertical
+   PUBLIC reconstructandremap ! remapping routine
+#endif   
+   !                                              !!* Namelist namagrif: AGRIF parameters
+   LOGICAL , PUBLIC ::   ln_spc_dyn    = .FALSE.   !:
+   INTEGER , PUBLIC, PARAMETER ::   nn_sponge_len = 2  !: Sponge width (in number of parent grid points)
+   REAL(wp), PUBLIC ::   rn_sponge_tra = 2800.     !: sponge coeff. for tracers
+   REAL(wp), PUBLIC ::   rn_sponge_dyn = 2800.     !: sponge coeff. for dynamics
+   LOGICAL , PUBLIC ::   ln_chk_bathy  = .FALSE.   !: check of parent bathymetry 
+   LOGICAL , PUBLIC ::   lk_agrif_clp  = .FALSE.   !: Force clamped bcs
+   !                                              !!! OLD namelist names
+   REAL(wp), PUBLIC ::   visc_tra                  !: sponge coeff. for tracers
+   REAL(wp), PUBLIC ::   visc_dyn                  !: sponge coeff. for dynamics
+
+   LOGICAL , PUBLIC :: spongedoneT = .FALSE.       !: tracer   sponge layer indicator
+   LOGICAL , PUBLIC :: spongedoneU = .FALSE.       !: dynamics sponge layer indicator
+   LOGICAL , PUBLIC :: lk_agrif_fstep = .TRUE.     !: if true: first step
+   LOGICAL , PUBLIC :: lk_agrif_debug = .FALSE.    !: if true: print debugging info
+
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_tsn
+# if defined key_top
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_trn
+# endif
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_u
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: tabspongedone_v
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: fsaht_spu, fsaht_spv !: sponge diffusivities
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: fsahm_spt, fsahm_spf !: sponge viscosities
+
+   ! Barotropic arrays used to store open boundary data during time-splitting loop:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  ubdy_w, vbdy_w, hbdy_w
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  ubdy_e, vbdy_e, hbdy_e
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  ubdy_n, vbdy_n, hbdy_n
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  ubdy_s, vbdy_s, hbdy_s
+
+
+   INTEGER, PUBLIC :: tsn_id                                                  ! AGRIF profile for tracers interpolation and update
+   INTEGER, PUBLIC :: un_interp_id, vn_interp_id                              ! AGRIF profiles for interpolations
+   INTEGER, PUBLIC :: un_update_id, vn_update_id                              ! AGRIF profiles for udpates
+   INTEGER, PUBLIC :: tsn_sponge_id, un_sponge_id, vn_sponge_id               ! AGRIF profiles for sponge layers
+# if defined key_top
+   INTEGER, PUBLIC :: trn_id, trn_sponge_id
+# endif  
+   INTEGER, PUBLIC :: unb_id, vnb_id, ub2b_interp_id, vb2b_interp_id
+   INTEGER, PUBLIC :: ub2b_update_id, vb2b_update_id
+   INTEGER, PUBLIC :: e3t_id, e1u_id, e2v_id, sshn_id
+   INTEGER, PUBLIC :: scales_t_id
+   INTEGER, PUBLIC :: avt_id, avm_id, en_id                ! TKE related identificators
+   INTEGER, PUBLIC :: umsk_id, vmsk_id
+   INTEGER, PUBLIC :: kindic_agr
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS 
+
+   INTEGER FUNCTION agrif_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION agrif_oce_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(2) :: ierr
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( fsaht_spu(jpi,jpj), fsaht_spv(jpi,jpj),   &
+         &      fsahm_spt(jpi,jpj), fsahm_spf(jpi,jpj),   &
+         &      tabspongedone_tsn(jpi,jpj),           &
+# if defined key_top         
+         &      tabspongedone_trn(jpi,jpj),           &
+# endif         
+         &      tabspongedone_u  (jpi,jpj),           &
+         &      tabspongedone_v  (jpi,jpj), STAT = ierr(1) )
+
+      ALLOCATE( ubdy_w(nbghostcells,jpj), vbdy_w(nbghostcells,jpj), hbdy_w(nbghostcells,jpj),   &
+         &      ubdy_e(nbghostcells,jpj), vbdy_e(nbghostcells,jpj), hbdy_e(nbghostcells,jpj),   & 
+         &      ubdy_n(jpi,nbghostcells), vbdy_n(jpi,nbghostcells), hbdy_n(jpi,nbghostcells),   & 
+         &      ubdy_s(jpi,nbghostcells), vbdy_s(jpi,nbghostcells), hbdy_s(jpi,nbghostcells), STAT = ierr(2) )
+
+      agrif_oce_alloc = MAXVAL(ierr)
+      !
+   END FUNCTION agrif_oce_alloc
+
+#if defined key_vertical
+   SUBROUTINE reconstructandremap(tabin,hin,tabout,hout,N,Nout)      
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION reconstructandremap  ***
+      !!----------------------------------------------------------------------
+      IMPLICIT NONE
+      INTEGER N, Nout
+      REAL(wp) tabin(N), tabout(Nout)
+      REAL(wp) hin(N), hout(Nout)
+      REAL(wp) coeffremap(N,3),zwork(N,3)
+      REAL(wp) zwork2(N+1,3)
+      INTEGER jk
+      DOUBLE PRECISION, PARAMETER :: dsmll=1.0d-8  
+      REAL(wp) q,q01,q02,q001,q002,q0
+      REAL(wp) z_win(1:N+1), z_wout(1:Nout+1)
+      REAL(wp),PARAMETER :: dpthin = 1.D-3
+      INTEGER :: k1, kbox, ktop, ka, kbot
+      REAL(wp) :: tsum, qbot, rpsum, zbox, ztop, zthk, zbot, offset, qtop
+
+      z_win(1)=0.; z_wout(1)= 0.
+      DO jk=1,N
+         z_win(jk+1)=z_win(jk)+hin(jk)
+      ENDDO 
+      
+      DO jk=1,Nout
+         z_wout(jk+1)=z_wout(jk)+hout(jk)       
+      ENDDO       
+
+      DO jk=2,N
+         zwork(jk,1)=1./(hin(jk-1)+hin(jk))
+      ENDDO
+        
+      DO jk=2,N-1
+         q0 = 1./(hin(jk-1)+hin(jk)+hin(jk+1))
+         zwork(jk,2)=hin(jk-1)+2.*hin(jk)+hin(jk+1)
+         zwork(jk,3)=q0
+      ENDDO       
+     
+      DO jk= 2,N
+         zwork2(jk,1)=zwork(jk,1)*(tabin(jk)-tabin(jk-1))
+      ENDDO
+        
+      coeffremap(:,1) = tabin(:)
+ 
+      DO jk=2,N-1
+         q001 = hin(jk)*zwork2(jk+1,1)
+         q002 = hin(jk)*zwork2(jk,1)        
+         IF (q001*q002 < 0) then
+            q001 = 0.
+            q002 = 0.
+         ENDIF
+         q=zwork(jk,2)
+         q01=q*zwork2(jk+1,1)
+         q02=q*zwork2(jk,1)
+         IF (abs(q001) > abs(q02)) q001 = q02
+         IF (abs(q002) > abs(q01)) q002 = q01
+        
+         q=(q001-q002)*zwork(jk,3)
+         q001=q001-q*hin(jk+1)
+         q002=q002+q*hin(jk-1)
+        
+         coeffremap(jk,3)=coeffremap(jk,1)+q001
+         coeffremap(jk,2)=coeffremap(jk,1)-q002
+        
+         zwork2(jk,1)=(2.*q001-q002)**2
+         zwork2(jk,2)=(2.*q002-q001)**2
+      ENDDO
+        
+      DO jk=1,N
+         IF(jk.EQ.1 .OR. jk.EQ.N .OR. hin(jk).LE.dpthin) THEN
+            coeffremap(jk,3) = coeffremap(jk,1)
+            coeffremap(jk,2) = coeffremap(jk,1)
+            zwork2(jk,1) = 0.
+            zwork2(jk,2) = 0.
+         ENDIF
+      ENDDO
+        
+      DO jk=2,N
+         q002=max(zwork2(jk-1,2),dsmll)
+         q001=max(zwork2(jk,1),dsmll)
+         zwork2(jk,3)=(q001*coeffremap(jk-1,3)+q002*coeffremap(jk,2))/(q001+q002)
+      ENDDO
+        
+      zwork2(1,3) = 2*coeffremap(1,1)-zwork2(2,3)
+      zwork2(N+1,3)=2*coeffremap(N,1)-zwork2(N,3)
+ 
+      DO jk=1,N
+         q01=zwork2(jk+1,3)-coeffremap(jk,1)
+         q02=coeffremap(jk,1)-zwork2(jk,3)
+         q001=2.*q01
+         q002=2.*q02
+         IF (q01*q02<0) then
+            q01=0.
+            q02=0.
+         ELSEIF (abs(q01)>abs(q002)) then
+            q01=q002
+         ELSEIF (abs(q02)>abs(q001)) then
+            q02=q001
+         ENDIF
+         coeffremap(jk,2)=coeffremap(jk,1)-q02
+         coeffremap(jk,3)=coeffremap(jk,1)+q01
+      ENDDO
+
+      zbot=0.0
+      kbot=1
+      DO jk=1,Nout
+         ztop=zbot  !top is bottom of previous layer
+         ktop=kbot
+         IF     (ztop.GE.z_win(ktop+1)) then
+            ktop=ktop+1
+         ENDIF
+        
+         zbot=z_wout(jk+1)
+         zthk=zbot-ztop
+
+         IF(zthk.GT.dpthin .AND. ztop.LT.z_wout(Nout+1)) THEN
+
+            kbot=ktop
+            DO while (z_win(kbot+1).lt.zbot.and.kbot.lt.N)
+               kbot=kbot+1
+            ENDDO
+            zbox=zbot
+            DO k1= jk+1,Nout
+               IF     (z_wout(k1+1)-z_wout(k1).GT.dpthin) THEN
+                  exit !thick layer
+               ELSE
+                  zbox=z_wout(k1+1)  !include thin adjacent layers
+                  IF(zbox.EQ.z_wout(Nout+1)) THEN
+                     exit !at bottom
+                  ENDIF
+               ENDIF
+            ENDDO
+            zthk=zbox-ztop
+
+            kbox=ktop
+            DO while (z_win(kbox+1).lt.zbox.and.kbox.lt.N)
+               kbox=kbox+1
+            ENDDO
+          
+            IF(ktop.EQ.kbox) THEN
+               IF(z_wout(jk).NE.z_win(kbox).OR.z_wout(jk+1).NE.z_win(kbox+1)) THEN
+                  IF(hin(kbox).GT.dpthin) THEN
+                     q001 = (zbox-z_win(kbox))/hin(kbox)
+                     q002 = (ztop-z_win(kbox))/hin(kbox)
+                     q01=q001**2+q002**2+q001*q002+1.-2.*(q001+q002)
+                     q02=q01-1.+(q001+q002)
+                     q0=1.-q01-q02
+                  ELSE
+                     q0 = 1.0
+                     q01 = 0.
+                     q02 = 0.
+                  ENDIF
+                  tabout(jk)=q0*coeffremap(kbox,1)+q01*coeffremap(kbox,2)+q02*coeffremap(kbox,3)
+               ELSE
+                  tabout(jk) = tabin(kbox)
+               ENDIF 
+            ELSE
+               IF(ktop.LE.jk .AND. kbox.GE.jk) THEN
+                  ka = jk
+               ELSEIF (kbox-ktop.GE.3) THEN
+                  ka = (kbox+ktop)/2
+               ELSEIF (hin(ktop).GE.hin(kbox)) THEN
+                  ka = ktop
+               ELSE
+                  ka = kbox
+               ENDIF !choose ka
+    
+               offset=coeffremap(ka,1)
+    
+               qtop = z_win(ktop+1)-ztop !partial layer thickness
+               IF(hin(ktop).GT.dpthin) THEN
+                  q=(ztop-z_win(ktop))/hin(ktop)
+                  q01=q*(q-1.)
+                  q02=q01+q
+                  q0=1-q01-q02            
+               ELSE
+                  q0 = 1.
+                  q01 = 0.
+                  q02 = 0.
+               ENDIF
+               
+               tsum =((q0*coeffremap(ktop,1)+q01*coeffremap(ktop,2)+q02*coeffremap(ktop,3))-offset)*qtop
+    
+               DO k1= ktop+1,kbox-1
+                  tsum =tsum +(coeffremap(k1,1)-offset)*hin(k1)
+               ENDDO !k1
+               
+               qbot = zbox-z_win(kbox) !partial layer thickness
+               IF(hin(kbox).GT.dpthin) THEN
+                  q=qbot/hin(kbox)
+                  q01=(q-1.)**2
+                  q02=q01-1.+q
+                  q0=1-q01-q02                            
+               ELSE
+                  q0 = 1.0
+                  q01 = 0.
+                  q02 = 0.
+               ENDIF
+              
+               tsum = tsum +((q0*coeffremap(kbox,1)+q01*coeffremap(kbox,2)+q02*coeffremap(kbox,3))-offset)*qbot
+               
+               rpsum=1.0d0/zthk
+               tabout(jk)=offset+tsum*rpsum
+                 
+            ENDIF !single or multiple layers
+         ELSE
+            IF (jk==1) THEN
+               write(*,'(a7,i4,i4,3f12.5)')'problem = ',N,Nout,zthk,z_wout(jk+1),hout(1)
+            ENDIF
+            tabout(jk) = tabout(jk-1)
+             
+         ENDIF !normal:thin layer
+      ENDDO !jk
+            
+      return
+      end subroutine reconstructandremap
+#endif
+
+#endif
+   !!======================================================================
+END MODULE agrif_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_interp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_interp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_interp.F90	(revision 14097)
@@ -0,0 +1,1442 @@
+MODULE agrif_oce_interp
+   !!======================================================================
+   !!                   ***  MODULE  agrif_oce_interp  ***
+   !! AGRIF: interpolation package for the ocean dynamics (OPA)
+   !!======================================================================
+   !! History :  2.0  !  2002-06  (L. Debreu)  Original cade
+   !!            3.2  !  2009-04  (R. Benshila) 
+   !!            3.6  !  2014-09  (R. Benshila) 
+   !!----------------------------------------------------------------------
+#if defined key_agrif
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!----------------------------------------------------------------------
+   !!   Agrif_tra     :
+   !!   Agrif_dyn     : 
+   !!   Agrif_ssh     :
+   !!   Agrif_dyn_ts  :
+   !!   Agrif_dta_ts  :
+   !!   Agrif_ssh_ts  :
+   !!   Agrif_avm     : 
+   !!   interpu       :
+   !!   interpv       :
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE oce
+   USE dom_oce      
+   USE zdf_oce
+   USE agrif_oce
+   USE phycst
+   USE dynspg_ts, ONLY: un_adv, vn_adv
+   !
+   USE in_out_manager
+   USE agrif_oce_sponge
+   USE lib_mpp
+ 
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   Agrif_dyn, Agrif_ssh, Agrif_dyn_ts, Agrif_ssh_ts, Agrif_dta_ts
+   PUBLIC   Agrif_tra, Agrif_avm
+   PUBLIC   interpun , interpvn
+   PUBLIC   interptsn, interpsshn, interpavm
+   PUBLIC   interpunb, interpvnb , interpub2b, interpvb2b
+   PUBLIC   interpe3t, interpumsk, interpvmsk
+
+   INTEGER ::   bdy_tinterp = 0
+
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_tra
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_tra  ***
+      !!----------------------------------------------------------------------
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .TRUE.
+      !
+      CALL Agrif_Bc_variable( tsn_id, procname=interptsn )
+      !
+      Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE Agrif_tra
+
+
+   SUBROUTINE Agrif_dyn( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_DYN  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   kt
+      !
+      INTEGER ::   ji, jj, jk       ! dummy loop indices
+      INTEGER ::   j1, j2, i1, i2
+      INTEGER ::   ibdy1, jbdy1, ibdy2, jbdy2
+      REAL(wp), DIMENSION(jpi,jpj) ::   zub, zvb
+      !!----------------------------------------------------------------------  
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = ln_spc_dyn
+      !
+      CALL Agrif_Bc_variable( un_interp_id, procname=interpun )
+      CALL Agrif_Bc_variable( vn_interp_id, procname=interpvn )
+      !
+      Agrif_UseSpecialValue = .FALSE.
+      !
+      ! prevent smoothing in ghost cells
+      i1 =  1   ;   i2 = nlci
+      j1 =  1   ;   j2 = nlcj
+      IF( l_Southedge )   j1 = 2 + nbghostcells
+      IF( l_Northedge )   j2 = nlcj - nbghostcells - 1
+      IF( l_Westedge )    i1 = 2 + nbghostcells 
+      IF( l_Eastedge )    i2 = nlci - nbghostcells - 1
+
+      ! --- West --- !
+      IF( l_Westedge ) THEN
+         ibdy1 = 2
+         ibdy2 = 1+nbghostcells 
+         !
+         IF( .NOT.ln_dynspg_ts ) THEN  ! Store transport
+            ua_b(ibdy1:ibdy2,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  ua_b(ibdy1:ibdy2,jj) = ua_b(ibdy1:ibdy2,jj) & 
+                      & + e3u_a(ibdy1:ibdy2,jj,jk) * ua(ibdy1:ibdy2,jj,jk) * umask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+            DO jj = 1, jpj
+               ua_b(ibdy1:ibdy2,jj) = ua_b(ibdy1:ibdy2,jj) * r1_hu_a(ibdy1:ibdy2,jj)
+            END DO
+         ENDIF
+         !
+         IF( .NOT.lk_agrif_clp ) THEN
+            DO jk=1,jpkm1              ! Smooth
+               DO jj=j1,j2
+                  ua(ibdy2,jj,jk) = 0.25_wp*(ua(ibdy2-1,jj,jk)+2._wp*ua(ibdy2,jj,jk)+ua(ibdy2+1,jj,jk))
+               END DO
+            END DO
+         ENDIF
+         !
+         zub(ibdy1:ibdy2,:) = 0._wp    ! Correct transport
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               zub(ibdy1:ibdy2,jj) = zub(ibdy1:ibdy2,jj) & 
+                  & + e3u_a(ibdy1:ibdy2,jj,jk)  * ua(ibdy1:ibdy2,jj,jk)*umask(ibdy1:ibdy2,jj,jk)
+            END DO
+         END DO
+         DO jj=1,jpj
+            zub(ibdy1:ibdy2,jj) = zub(ibdy1:ibdy2,jj) * r1_hu_a(ibdy1:ibdy2,jj)
+         END DO
+            
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               ua(ibdy1:ibdy2,jj,jk) = ( ua(ibdy1:ibdy2,jj,jk) &
+                 & + ua_b(ibdy1:ibdy2,jj)-zub(ibdy1:ibdy2,jj)) * umask(ibdy1:ibdy2,jj,jk)
+            END DO
+         END DO
+            
+         IF( ln_dynspg_ts ) THEN       ! Set tangential velocities to time splitting estimate
+            zvb(ibdy1:ibdy2,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  zvb(ibdy1:ibdy2,jj) = zvb(ibdy1:ibdy2,jj) & 
+                     & + e3v_a(ibdy1:ibdy2,jj,jk) * va(ibdy1:ibdy2,jj,jk) * vmask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+            DO jj = 1, jpj
+               zvb(ibdy1:ibdy2,jj) = zvb(ibdy1:ibdy2,jj) * r1_hv_a(ibdy1:ibdy2,jj)
+            END DO
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  va(ibdy1:ibdy2,jj,jk) = ( va(ibdy1:ibdy2,jj,jk) & 
+                    & + va_b(ibdy1:ibdy2,jj)-zvb(ibdy1:ibdy2,jj))*vmask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jk = 1, jpkm1              ! Mask domain edges
+            DO jj = 1, jpj
+               ua(1,jj,jk) = 0._wp
+               va(1,jj,jk) = 0._wp
+            END DO
+         END DO 
+      ENDIF
+
+      ! --- East --- !
+      IF( l_Eastedge ) THEN
+         ibdy1 = nlci-1-nbghostcells
+         ibdy2 = nlci-2 
+         !
+         IF( .NOT.ln_dynspg_ts ) THEN  ! Store transport
+            ua_b(ibdy1:ibdy2,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  ua_b(ibdy1:ibdy2,jj) = ua_b(ibdy1:ibdy2,jj) & 
+                      & + e3u_a(ibdy1:ibdy2,jj,jk) * ua(ibdy1:ibdy2,jj,jk) * umask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+            DO jj = 1, jpj
+               ua_b(ibdy1:ibdy2,jj) = ua_b(ibdy1:ibdy2,jj) * r1_hu_a(ibdy1:ibdy2,jj)
+            END DO
+         ENDIF
+         !
+         IF( .NOT.lk_agrif_clp ) THEN
+            DO jk=1,jpkm1              ! Smooth
+               DO jj=j1,j2
+                  ua(ibdy1,jj,jk) = 0.25_wp*(ua(ibdy1-1,jj,jk)+2._wp*ua(ibdy1,jj,jk)+ua(ibdy1+1,jj,jk))
+               END DO
+            END DO
+         ENDIF
+         !
+         zub(ibdy1:ibdy2,:) = 0._wp    ! Correct transport
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               zub(ibdy1:ibdy2,jj) = zub(ibdy1:ibdy2,jj) & 
+                  & + e3u_a(ibdy1:ibdy2,jj,jk)  * ua(ibdy1:ibdy2,jj,jk) * umask(ibdy1:ibdy2,jj,jk)
+            END DO
+         END DO
+         DO jj=1,jpj
+            zub(ibdy1:ibdy2,jj) = zub(ibdy1:ibdy2,jj) * r1_hu_a(ibdy1:ibdy2,jj)
+         END DO
+            
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               ua(ibdy1:ibdy2,jj,jk) = ( ua(ibdy1:ibdy2,jj,jk) & 
+                 & + ua_b(ibdy1:ibdy2,jj)-zub(ibdy1:ibdy2,jj))*umask(ibdy1:ibdy2,jj,jk)
+            END DO
+         END DO
+            
+         IF( ln_dynspg_ts ) THEN       ! Set tangential velocities to time splitting estimate
+            ibdy1 = ibdy1 + 1
+            ibdy2 = ibdy2 + 1 
+            zvb(ibdy1:ibdy2,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  zvb(ibdy1:ibdy2,jj) = zvb(ibdy1:ibdy2,jj) &
+                     & + e3v_a(ibdy1:ibdy2,jj,jk) * va(ibdy1:ibdy2,jj,jk) * vmask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+            DO jj = 1, jpj
+               zvb(ibdy1:ibdy2,jj) = zvb(ibdy1:ibdy2,jj) * r1_hv_a(ibdy1:ibdy2,jj)
+            END DO
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  va(ibdy1:ibdy2,jj,jk) = ( va(ibdy1:ibdy2,jj,jk) & 
+                      & + va_b(ibdy1:ibdy2,jj)-zvb(ibdy1:ibdy2,jj)) * vmask(ibdy1:ibdy2,jj,jk)
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jk = 1, jpkm1              ! Mask domain edges
+            DO jj = 1, jpj
+               ua(nlci-1,jj,jk) = 0._wp
+               va(nlci  ,jj,jk) = 0._wp
+            END DO
+         END DO 
+      ENDIF
+
+      ! --- South --- !
+      IF ( l_Southedge ) THEN
+         jbdy1 = 2
+         jbdy2 = 1+nbghostcells 
+         !
+         IF( .NOT.ln_dynspg_ts ) THEN  ! Store transport
+            va_b(:,jbdy1:jbdy2) = 0._wp
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  va_b(ji,jbdy1:jbdy2) = va_b(ji,jbdy1:jbdy2) & 
+                      & + e3v_a(ji,jbdy1:jbdy2,jk) * va(ji,jbdy1:jbdy2,jk) * vmask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+            DO ji=1,jpi
+               va_b(ji,jbdy1:jbdy2) = va_b(ji,jbdy1:jbdy2) * r1_hv_a(ji,jbdy1:jbdy2)
+            END DO
+         ENDIF
+         !
+         IF ( .NOT.lk_agrif_clp ) THEN
+            DO jk = 1, jpkm1           ! Smooth
+               DO ji = i1, i2
+                  va(ji,jbdy2,jk) = 0.25_wp*(va(ji,jbdy2-1,jk)+2._wp*va(ji,jbdy2,jk)+va(ji,jbdy2+1,jk))
+               END DO
+            END DO
+         ENDIF
+         !
+         zvb(:,jbdy1:jbdy2) = 0._wp    ! Correct transport
+         DO jk=1,jpkm1
+            DO ji=1,jpi
+               zvb(ji,jbdy1:jbdy2) = zvb(ji,jbdy1:jbdy2) & 
+                  & + e3v_a(ji,jbdy1:jbdy2,jk) * va(ji,jbdy1:jbdy2,jk) * vmask(ji,jbdy1:jbdy2,jk)
+            END DO
+         END DO
+         DO ji = 1, jpi
+            zvb(ji,jbdy1:jbdy2) = zvb(ji,jbdy1:jbdy2) * r1_hv_a(ji,jbdy1:jbdy2)
+         END DO
+
+         DO jk = 1, jpkm1
+            DO ji = 1, jpi
+               va(ji,jbdy1:jbdy2,jk) = ( va(ji,jbdy1:jbdy2,jk) & 
+                 & + va_b(ji,jbdy1:jbdy2) - zvb(ji,jbdy1:jbdy2) ) * vmask(ji,jbdy1:jbdy2,jk)
+            END DO
+         END DO
+            
+         IF( ln_dynspg_ts ) THEN       ! Set tangential velocities to time splitting estimate
+            zub(:,jbdy1:jbdy2) = 0._wp
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  zub(ji,jbdy1:jbdy2) = zub(ji,jbdy1:jbdy2) & 
+                     & + e3u_a(ji,jbdy1:jbdy2,jk) * ua(ji,jbdy1:jbdy2,jk) * umask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+            DO ji = 1, jpi
+               zub(ji,jbdy1:jbdy2) = zub(ji,jbdy1:jbdy2) * r1_hu_a(ji,jbdy1:jbdy2)
+            END DO
+               
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  ua(ji,jbdy1:jbdy2,jk) = ( ua(ji,jbdy1:jbdy2,jk) & 
+                    & + ua_b(ji,jbdy1:jbdy2) - zub(ji,jbdy1:jbdy2) ) * umask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jk = 1, jpkm1              ! Mask domain edges
+            DO ji = 1, jpi
+               ua(ji,1,jk) = 0._wp
+               va(ji,1,jk) = 0._wp
+            END DO
+         END DO 
+      ENDIF
+
+      ! --- North --- !
+      IF( l_Northedge ) THEN
+         jbdy1 = nlcj-1-nbghostcells
+         jbdy2 = nlcj-2 
+         !
+         IF( .NOT.ln_dynspg_ts ) THEN  ! Store transport
+            va_b(:,jbdy1:jbdy2) = 0._wp
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  va_b(ji,jbdy1:jbdy2) = va_b(ji,jbdy1:jbdy2) & 
+                      & + e3v_a(ji,jbdy1:jbdy2,jk) * va(ji,jbdy1:jbdy2,jk) * vmask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+            DO ji=1,jpi
+               va_b(ji,jbdy1:jbdy2) = va_b(ji,jbdy1:jbdy2) * r1_hv_a(ji,jbdy1:jbdy2)
+            END DO
+         ENDIF
+         !
+         IF ( .NOT.lk_agrif_clp ) THEN
+            DO jk = 1, jpkm1           ! Smooth
+               DO ji = i1, i2
+                  va(ji,jbdy1,jk) = 0.25_wp*(va(ji,jbdy1-1,jk)+2._wp*va(ji,jbdy1,jk)+va(ji,jbdy1+1,jk))
+               END DO
+            END DO
+         ENDIF
+         !
+         zvb(:,jbdy1:jbdy2) = 0._wp    ! Correct transport
+         DO jk=1,jpkm1
+            DO ji=1,jpi
+               zvb(ji,jbdy1:jbdy2) = zvb(ji,jbdy1:jbdy2) & 
+                  & + e3v_a(ji,jbdy1:jbdy2,jk) * va(ji,jbdy1:jbdy2,jk) * vmask(ji,jbdy1:jbdy2,jk)
+            END DO
+         END DO
+         DO ji = 1, jpi
+            zvb(ji,jbdy1:jbdy2) = zvb(ji,jbdy1:jbdy2) * r1_hv_a(ji,jbdy1:jbdy2)
+         END DO
+
+         DO jk = 1, jpkm1
+            DO ji = 1, jpi
+               va(ji,jbdy1:jbdy2,jk) = ( va(ji,jbdy1:jbdy2,jk) & 
+                 & + va_b(ji,jbdy1:jbdy2) - zvb(ji,jbdy1:jbdy2) ) * vmask(ji,jbdy1:jbdy2,jk)
+            END DO
+         END DO
+            
+         IF( ln_dynspg_ts ) THEN       ! Set tangential velocities to time splitting estimate
+            jbdy1 = jbdy1 + 1
+            jbdy2 = jbdy2 + 1 
+            zub(:,jbdy1:jbdy2) = 0._wp
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  zub(ji,jbdy1:jbdy2) = zub(ji,jbdy1:jbdy2) & 
+                     & + e3u_a(ji,jbdy1:jbdy2,jk) * ua(ji,jbdy1:jbdy2,jk) * umask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+            DO ji = 1, jpi
+               zub(ji,jbdy1:jbdy2) = zub(ji,jbdy1:jbdy2) * r1_hu_a(ji,jbdy1:jbdy2)
+            END DO
+               
+            DO jk = 1, jpkm1
+               DO ji = 1, jpi
+                  ua(ji,jbdy1:jbdy2,jk) = ( ua(ji,jbdy1:jbdy2,jk) & 
+                    & + ua_b(ji,jbdy1:jbdy2) - zub(ji,jbdy1:jbdy2) ) * umask(ji,jbdy1:jbdy2,jk)
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jk = 1, jpkm1              ! Mask domain edges
+            DO ji = 1, jpi
+               ua(ji,nlcj  ,jk) = 0._wp
+               va(ji,nlcj-1,jk) = 0._wp
+            END DO
+         END DO 
+      ENDIF
+      !
+   END SUBROUTINE Agrif_dyn
+
+
+   SUBROUTINE Agrif_dyn_ts( jn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_dyn_ts  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   jn
+      !!
+      INTEGER :: ji, jj
+      !!----------------------------------------------------------------------  
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      IF( l_Westedge ) THEN
+         DO jj=1,jpj
+            va_e(2:nbghostcells+1,jj) = vbdy_w(1:nbghostcells,jj) * hvr_e(2:nbghostcells+1,jj)
+            ! Specified fluxes:
+            ua_e(2:nbghostcells+1,jj) = ubdy_w(1:nbghostcells,jj) * hur_e(2:nbghostcells+1,jj)
+            ! Characteristics method (only if ghostcells=1):
+            !alt            ua_e(2,jj) = 0.5_wp * ( ubdy_w(jj) * hur_e(2,jj) + ua_e(3,jj) &
+            !alt                       &           - sqrt(grav * hur_e(2,jj)) * (sshn_e(3,jj) - hbdy_w(jj)) )
+         END DO
+      ENDIF
+      !
+      IF( l_Eastedge ) THEN
+         DO jj=1,jpj
+            va_e(nlci-nbghostcells:nlci-1,jj)   = vbdy_e(1:nbghostcells,jj) * hvr_e(nlci-nbghostcells:nlci-1,jj)
+            ! Specified fluxes:
+            ua_e(nlci-nbghostcells-1:nlci-2,jj) = ubdy_e(1:nbghostcells,jj) * hur_e(nlci-nbghostcells-1:nlci-2,jj)
+            ! Characteristics method (only if ghostcells=1):
+            !alt            ua_e(nlci-2,jj) = 0.5_wp * ( ubdy_e(jj) * hur_e(nlci-2,jj) + ua_e(nlci-3,jj) &
+            !alt                            &           + sqrt(grav * hur_e(nlci-2,jj)) * (sshn_e(nlci-2,jj) - hbdy_e(jj)) )
+         END DO
+      ENDIF
+      !
+      IF ( l_Southedge ) THEN
+         DO ji=1,jpi
+            ua_e(ji,2:nbghostcells+1) = ubdy_s(ji,1:nbghostcells) * hur_e(ji,2:nbghostcells+1)
+            ! Specified fluxes:
+            va_e(ji,2:nbghostcells+1) = vbdy_s(ji,1:nbghostcells) * hvr_e(ji,2:nbghostcells+1)
+            ! Characteristics method (only if ghostcells=1):
+            !alt            va_e(ji,2) = 0.5_wp * ( vbdy_s(ji) * hvr_e(ji,2) + va_e(ji,3) &
+            !alt                       &           - sqrt(grav * hvr_e(ji,2)) * (sshn_e(ji,3) - hbdy_s(ji)) )
+         END DO
+      ENDIF
+      !
+      IF ( l_Northedge ) THEN
+         DO ji=1,jpi
+            ua_e(ji,nlcj-nbghostcells:nlcj-1)   = ubdy_n(ji,1:nbghostcells) * hur_e(ji,nlcj-nbghostcells:nlcj-1)
+            ! Specified fluxes:
+            va_e(ji,nlcj-nbghostcells-1:nlcj-2) = vbdy_n(ji,1:nbghostcells) * hvr_e(ji,nlcj-nbghostcells-1:nlcj-2)
+            ! Characteristics method (only if ghostcells=1):
+            !alt            va_e(ji,nlcj-2) = 0.5_wp * ( vbdy_n(ji) * hvr_e(ji,nlcj-2)  + va_e(ji,nlcj-3) &
+            !alt                            &           + sqrt(grav * hvr_e(ji,nlcj-2)) * (sshn_e(ji,nlcj-2) - hbdy_n(ji)) )
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE Agrif_dyn_ts
+
+
+   SUBROUTINE Agrif_dta_ts( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_dta_ts  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   kt
+      !!
+      INTEGER :: ji, jj
+      LOGICAL :: ll_int_cons
+      !!----------------------------------------------------------------------  
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      ll_int_cons = ln_bt_fw ! Assume conservative temporal integration in the forward case only
+      !
+      ! Enforce volume conservation if no time refinement:  
+      IF ( Agrif_rhot()==1 ) ll_int_cons=.TRUE.  
+      !
+      ! Interpolate barotropic fluxes
+      Agrif_SpecialValue=0._wp
+      Agrif_UseSpecialValue = ln_spc_dyn
+      !
+      IF( ll_int_cons ) THEN  ! Conservative interpolation
+         ! order matters here !!!!!!
+         CALL Agrif_Bc_variable( ub2b_interp_id, calledweight=1._wp, procname=interpub2b ) ! Time integrated
+         CALL Agrif_Bc_variable( vb2b_interp_id, calledweight=1._wp, procname=interpvb2b )
+         bdy_tinterp = 1
+         CALL Agrif_Bc_variable( unb_id        , calledweight=1._wp, procname=interpunb  ) ! After
+         CALL Agrif_Bc_variable( vnb_id        , calledweight=1._wp, procname=interpvnb  )
+         bdy_tinterp = 2
+         CALL Agrif_Bc_variable( unb_id        , calledweight=0._wp, procname=interpunb  ) ! Before
+         CALL Agrif_Bc_variable( vnb_id        , calledweight=0._wp, procname=interpvnb  )         
+      ELSE ! Linear interpolation
+         bdy_tinterp = 0
+         ubdy_w(:,:) = 0._wp   ;   vbdy_w(:,:) = 0._wp 
+         ubdy_e(:,:) = 0._wp   ;   vbdy_e(:,:) = 0._wp 
+         ubdy_n(:,:) = 0._wp   ;   vbdy_n(:,:) = 0._wp 
+         ubdy_s(:,:) = 0._wp   ;   vbdy_s(:,:) = 0._wp
+         CALL Agrif_Bc_variable( unb_id, procname=interpunb )
+         CALL Agrif_Bc_variable( vnb_id, procname=interpvnb )
+      ENDIF
+      Agrif_UseSpecialValue = .FALSE.
+      ! 
+   END SUBROUTINE Agrif_dta_ts
+
+
+   SUBROUTINE Agrif_ssh( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_ssh  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   kt
+      !
+      INTEGER  :: ji, jj, indx, indy
+      !!----------------------------------------------------------------------  
+      !
+      IF( Agrif_Root() )   RETURN
+      !      
+      ! Linear time interpolation of sea level
+      !
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .TRUE.
+      CALL Agrif_Bc_variable(sshn_id, procname=interpsshn )
+      Agrif_UseSpecialValue = .FALSE.
+      !
+      ! --- West --- !
+      IF( l_Westedge ) THEN
+         indx = 1+nbghostcells
+         DO jj = 1, jpj
+            DO ji = 2, indx
+               ssha(ji,jj) = hbdy_w(ji-1,jj)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- East --- !
+      IF( l_Eastedge ) THEN
+         indx = nlci-nbghostcells
+         DO jj = 1, jpj
+            DO ji = indx, nlci-1
+               ssha(ji,jj) = hbdy_e(ji-indx+1,jj)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- South --- !
+      IF ( l_Southedge ) THEN
+         indy = 1+nbghostcells
+         DO jj = 2, indy
+            DO ji = 1, jpi
+               ssha(ji,jj) = hbdy_s(ji,jj-1)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- North --- !
+      IF ( l_Northedge ) THEN
+         indy = nlcj-nbghostcells
+         DO jj = indy, nlcj-1
+            DO ji = 1, jpi
+               ssha(ji,jj) = hbdy_n(ji,jj-indy+1)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+   END SUBROUTINE Agrif_ssh
+
+
+   SUBROUTINE Agrif_ssh_ts( jn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_ssh_ts  ***
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT(in) ::   jn
+      !!
+      INTEGER :: ji, jj, indx, indy
+      !!----------------------------------------------------------------------  
+      !! clem ghost (starting at i,j=1 is important I think otherwise you introduce a grad(ssh)/=0 at point 2)
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      ! --- West --- !
+      IF( l_Westedge ) THEN
+         indx = 1+nbghostcells
+         DO jj = 1, jpj
+            DO ji = 2, indx
+               ssha_e(ji,jj) = hbdy_w(ji-1,jj)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- East --- !
+      IF( l_Eastedge ) THEN
+         indx = nlci-nbghostcells
+         DO jj = 1, jpj
+            DO ji = indx, nlci-1
+               ssha_e(ji,jj) = hbdy_e(ji-indx+1,jj)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- South --- !
+      IF( l_Southedge ) THEN
+         indy = 1+nbghostcells
+         DO jj = 2, indy
+            DO ji = 1, jpi
+               ssha_e(ji,jj) = hbdy_s(ji,jj-1)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+      ! --- North --- !
+      IF( l_Northedge ) THEN
+         indy = nlcj-nbghostcells
+         DO jj = indy, nlcj-1
+            DO ji = 1, jpi
+               ssha_e(ji,jj) = hbdy_n(ji,jj-indy+1)
+            ENDDO
+         ENDDO
+      ENDIF
+      !
+   END SUBROUTINE Agrif_ssh_ts
+
+   SUBROUTINE Agrif_avm
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE Agrif_avm  ***
+      !!----------------------------------------------------------------------  
+      REAL(wp) ::   zalpha
+      !!----------------------------------------------------------------------  
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      zalpha = 1._wp ! JC: proper time interpolation impossible  
+                     ! => use last available value from parent 
+      !
+      Agrif_SpecialValue    = 0.e0
+      Agrif_UseSpecialValue = .TRUE.
+      !
+      CALL Agrif_Bc_variable( avm_id, calledweight=zalpha, procname=interpavm )       
+      !
+      Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE Agrif_avm
+   
+
+   SUBROUTINE interptsn( ptab, i1, i2, j1, j2, k1, k2, n1, n2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  *** ROUTINE interptsn ***
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   ptab
+      INTEGER                                     , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      LOGICAL                                     , INTENT(in   ) ::   before
+      INTEGER                                     , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER  ::   ji, jj, jk, jn, iref, jref, ibdy, jbdy   ! dummy loop indices
+      INTEGER  ::   imin, imax, jmin, jmax, N_in, N_out
+      REAL(wp) ::   zrho, z1, z2, z3, z4, z5, z6, z7
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk,n1:n2) :: ptab_child
+      REAL(wp), DIMENSION(k1:k2,n1:n2-1) :: tabin
+      REAL(wp), DIMENSION(k1:k2) :: h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      REAL(wp) :: h_diff
+
+      IF( before ) THEN         
+         DO jn = 1,jpts
+            DO jk=k1,k2
+               DO jj=j1,j2
+                 DO ji=i1,i2
+                       ptab(ji,jj,jk,jn) = tsn(ji,jj,jk,jn)
+                 END DO
+              END DO
+           END DO
+        END DO
+
+# if defined key_vertical
+        DO jk=k1,k2
+           DO jj=j1,j2
+              DO ji=i1,i2
+                 ptab(ji,jj,jk,jpts+1) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) 
+              END DO
+           END DO
+        END DO
+# endif
+      ELSE 
+
+         western_side  = (nb == 1).AND.(ndir == 1)   ;   eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)   ;   northern_side = (nb == 2).AND.(ndir == 2)
+
+# if defined key_vertical              
+         DO jj=j1,j2
+            DO ji=i1,i2
+               iref = ji
+               jref = jj
+               if(western_side) iref=MAX(2,ji)
+               if(eastern_side) iref=MIN(nlci-1,ji)
+               if(southern_side) jref=MAX(2,jj)
+               if(northern_side) jref=MIN(nlcj-1,jj)
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of parent grid
+                  IF (ptab(ji,jj,jk,n2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = ptab(ji,jj,jk,n1:n2-1)
+                  h_in(N_in) = ptab(ji,jj,jk,n2)
+               END DO
+               N_out = 0
+               DO jk=1,jpk ! jpk of child grid
+                  IF (tmask(iref,jref,jk) == 0) EXIT 
+                  N_out = N_out + 1
+                  h_out(jk) = e3t_n(iref,jref,jk)
+               ENDDO
+               IF (N_in > 0) THEN
+                  DO jn=1,jpts
+                     call reconstructandremap(tabin(1:N_in,jn),h_in,ptab_child(ji,jj,1:N_out,jn),h_out,N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+# else
+         ptab_child(i1:i2,j1:j2,1:jpk,1:jpts) = ptab(i1:i2,j1:j2,1:jpk,1:jpts)
+# endif
+         !
+         DO jn=1, jpts
+            tsa(i1:i2,j1:j2,1:jpk,jn)=ptab_child(i1:i2,j1:j2,1:jpk,jn)*tmask(i1:i2,j1:j2,1:jpk) 
+         END DO
+
+         IF ( .NOT.lk_agrif_clp ) THEN 
+            !
+            imin = i1 ; imax = i2
+            jmin = j1 ; jmax = j2
+            ! 
+            ! Remove CORNERS
+            IF( l_Southedge ) jmin = 2 + nbghostcells
+            IF( l_Northedge ) jmax = nlcj - nbghostcells - 1
+            IF( l_Westedge )  imin = 2 + nbghostcells
+            IF( l_Eastedge )  imax = nlci - nbghostcells - 1      
+            !
+            IF( eastern_side ) THEN
+               zrho = Agrif_Rhox()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !
+               ibdy = nlci-nbghostcells
+               DO jn = 1, jpts
+                  tsa(ibdy+1,jmin:jmax,1:jpkm1,jn) = z1 * ptab_child(ibdy+1,jmin:jmax,1:jpkm1,jn) + z2 * ptab_child(ibdy,jmin:jmax,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO jj = jmin,jmax
+                        IF( umask(ibdy-1,jj,jk) == 0._wp ) THEN
+                           tsa(ibdy,jj,jk,jn) = tsa(ibdy+1,jj,jk,jn) * tmask(ibdy,jj,jk)
+                        ELSE
+                           tsa(ibdy,jj,jk,jn)=(z4*tsa(ibdy+1,jj,jk,jn)+z3*tsa(ibdy-1,jj,jk,jn))*tmask(ibdy,jj,jk)
+                           IF( un(ibdy-1,jj,jk) > 0._wp ) THEN
+                              tsa(ibdy,jj,jk,jn)=( z6*tsa(ibdy-1,jj,jk,jn)+z5*tsa(ibdy+1,jj,jk,jn) & 
+                                                 + z7*tsa(ibdy-2,jj,jk,jn) ) * tmask(ibdy,jj,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tsa(ibdy+1,jmin:jmax,1:jpkm1,jn) = ptab_child(ibdy+1,jmin:jmax,1:jpkm1,jn) * tmask(ibdy+1,jmin:jmax,1:jpkm1)
+               END DO
+            ENDIF
+            ! 
+            IF( northern_side ) THEN
+               zrho = Agrif_Rhoy()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !
+               jbdy = nlcj-nbghostcells         
+               DO jn = 1, jpts
+                  tsa(imin:imax,jbdy+1,1:jpkm1,jn) = z1 * ptab_child(imin:imax,jbdy+1,1:jpkm1,jn) + z2 * ptab_child(imin:imax,jbdy,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO ji = imin,imax
+                        IF( vmask(ji,jbdy-1,jk) == 0._wp ) THEN
+                           tsa(ji,jbdy,jk,jn) = tsa(ji,jbdy+1,jk,jn) * tmask(ji,jbdy,jk)
+                        ELSE
+                           tsa(ji,jbdy,jk,jn)=(z4*tsa(ji,jbdy+1,jk,jn)+z3*tsa(ji,jbdy-1,jk,jn))*tmask(ji,jbdy,jk)        
+                           IF (vn(ji,jbdy-1,jk) > 0._wp ) THEN
+                              tsa(ji,jbdy,jk,jn)=( z6*tsa(ji,jbdy-1,jk,jn)+z5*tsa(ji,jbdy+1,jk,jn)  &
+                                                 + z7*tsa(ji,jbdy-2,jk,jn) ) * tmask(ji,jbdy,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tsa(imin:imax,jbdy+1,1:jpkm1,jn) = ptab_child(imin:imax,jbdy+1,1:jpkm1,jn) * tmask(imin:imax,jbdy+1,1:jpkm1)
+               END DO
+            ENDIF
+            !
+            IF( western_side ) THEN
+               zrho = Agrif_Rhox()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !    
+               ibdy = 1+nbghostcells       
+               DO jn = 1, jpts
+                  tsa(ibdy-1,jmin:jmax,1:jpkm1,jn) = z1 * ptab_child(ibdy-1,jmin:jmax,1:jpkm1,jn) + z2 * ptab_child(ibdy,jmin:jmax,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO jj = jmin,jmax
+                        IF( umask(ibdy,jj,jk) == 0._wp ) THEN
+                           tsa(ibdy,jj,jk,jn) = tsa(ibdy-1,jj,jk,jn) * tmask(ibdy,jj,jk)
+                        ELSE
+                           tsa(ibdy,jj,jk,jn)=(z4*tsa(ibdy-1,jj,jk,jn)+z3*tsa(ibdy+1,jj,jk,jn))*tmask(ibdy,jj,jk)        
+                           IF( un(ibdy,jj,jk) < 0._wp ) THEN
+                              tsa(ibdy,jj,jk,jn)=( z6*tsa(ibdy+1,jj,jk,jn)+z5*tsa(ibdy-1,jj,jk,jn) &
+                                                 + z7*tsa(ibdy+2,jj,jk,jn) ) * tmask(ibdy,jj,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tsa(ibdy-1,jmin:jmax,1:jpkm1,jn) = ptab_child(ibdy-1,jmin:jmax,1:jpkm1,jn) * tmask(ibdy-1,jmin:jmax,1:jpkm1)
+               END DO
+            ENDIF
+            !
+            IF( southern_side ) THEN
+               zrho = Agrif_Rhoy()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !  
+               jbdy=1+nbghostcells        
+               DO jn = 1, jpts
+                  tsa(imin:imax,jbdy-1,1:jpkm1,jn) = z1 * ptab_child(imin:imax,jbdy-1,1:jpkm1,jn) + z2 * ptab_child(imin:imax,jbdy,1:jpkm1,jn)
+                  DO jk = 1, jpkm1      
+                     DO ji = imin,imax
+                        IF( vmask(ji,jbdy,jk) == 0._wp ) THEN
+                           tsa(ji,jbdy,jk,jn)=tsa(ji,jbdy-1,jk,jn) * tmask(ji,jbdy,jk)
+                        ELSE
+                           tsa(ji,jbdy,jk,jn)=(z4*tsa(ji,jbdy-1,jk,jn)+z3*tsa(ji,jbdy+1,jk,jn))*tmask(ji,jbdy,jk)
+                           IF( vn(ji,jbdy,jk) < 0._wp ) THEN
+                              tsa(ji,jbdy,jk,jn)=( z6*tsa(ji,jbdy+1,jk,jn)+z5*tsa(ji,jbdy-1,jk,jn) & 
+                                                 + z7*tsa(ji,jbdy+2,jk,jn) ) * tmask(ji,jbdy,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tsa(imin:imax,jbdy-1,1:jpkm1,jn) = ptab_child(imin:imax,jbdy-1,1:jpkm1,jn) * tmask(imin:imax,jbdy-1,1:jpkm1)
+               END DO
+            ENDIF
+            !
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE interptsn
+
+   SUBROUTINE interpsshn( ptab, i1, i2, j1, j2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpsshn  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      INTEGER                         , INTENT(in   ) ::   nb , ndir
+      !
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF( before) THEN
+         ptab(i1:i2,j1:j2) = sshn(i1:i2,j1:j2)
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !! clem ghost
+         IF(western_side)  hbdy_w(1:nbghostcells,j1:j2) = ptab(i1:i2,j1:j2) * tmask(i1:i2,j1:j2,1)
+         IF(eastern_side)  hbdy_e(1:nbghostcells,j1:j2) = ptab(i1:i2,j1:j2) * tmask(i1:i2,j1:j2,1)
+         IF(southern_side) hbdy_s(i1:i2,1:nbghostcells) = ptab(i1:i2,j1:j2) * tmask(i1:i2,j1:j2,1) 
+         IF(northern_side) hbdy_n(i1:i2,1:nbghostcells) = ptab(i1:i2,j1:j2) * tmask(i1:i2,j1:j2,1)
+      ENDIF
+      !
+   END SUBROUTINE interpsshn
+
+   SUBROUTINE interpun( ptab, i1, i2, j1, j2, k1, k2, m1, m2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  *** ROUTINE interpun ***
+      !!---------------------------------------------    
+      !!
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,m1,m2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,m1:m2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !!
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: zrhoy
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(k1:k2) :: tabin, h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER  :: N_in, N_out, iref
+      REAL(wp) :: h_diff
+      LOGICAL  :: western_side, eastern_side
+      !!---------------------------------------------    
+      !
+      IF (before) THEN 
+         DO jk=1,jpk
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk,1) = (e2u(ji,jj) * e3u_n(ji,jj,jk) * un(ji,jj,jk)*umask(ji,jj,jk)) 
+# if defined key_vertical
+                  ptab(ji,jj,jk,2) = (umask(ji,jj,jk) * e2u(ji,jj) * e3u_n(ji,jj,jk))
+# endif
+               END DO
+            END DO
+         END DO
+      ELSE
+         zrhoy = Agrif_rhoy()
+# if defined key_vertical
+! VERTICAL REFINEMENT BEGIN
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+
+         DO ji=i1,i2
+            iref = ji
+            IF (western_side) iref = MAX(2,ji)
+            IF (eastern_side) iref = MIN(nlci-2,ji)
+            DO jj=j1,j2
+               N_in = 0
+               DO jk=k1,k2
+                  IF (ptab(ji,jj,jk,2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = ptab(ji,jj,jk,1)/ptab(ji,jj,jk,2)
+                  h_in(N_in) = ptab(ji,jj,jk,2)/(e2u(ji,jj)*zrhoy) 
+              ENDDO
+         
+              IF (N_in == 0) THEN
+                 ua(ji,jj,:) = 0._wp
+                 CYCLE
+              ENDIF
+         
+              N_out = 0
+              DO jk=1,jpk
+                 if (umask(iref,jj,jk) == 0) EXIT
+                 N_out = N_out + 1
+                 h_out(N_out) = e3u_a(iref,jj,jk)
+              ENDDO
+         
+              IF (N_out == 0) THEN
+                 ua(ji,jj,:) = 0._wp
+                 CYCLE
+              ENDIF
+         
+              IF (N_in * N_out > 0) THEN
+                 h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+! Should be able to remove the next IF/ELSEIF statement once scale factors are dealt with properly
+                 if (h_diff < -1.e4) then
+                    print *,'CHECK YOUR BATHY ...', h_diff, sum(h_out(1:N_out)), sum(h_in(1:N_in))
+!                    stop
+                 endif
+              ENDIF
+              call reconstructandremap(tabin(1:N_in),h_in(1:N_in),ua(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+            ENDDO
+         ENDDO
+
+# else
+         DO jk = 1, jpkm1
+            DO jj=j1,j2
+               ua(i1:i2,jj,jk) = ptab(i1:i2,jj,jk,1) / ( zrhoy * e2u(i1:i2,jj) * e3u_a(i1:i2,jj,jk) )
+            END DO
+         END DO
+# endif
+
+      ENDIF
+      ! 
+   END SUBROUTINE interpun
+
+   SUBROUTINE interpvn( ptab, i1, i2, j1, j2, k1, k2, m1, m2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  *** ROUTINE interpvn ***
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,m1,m2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,m1:m2), INTENT(inout) :: ptab
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: zrhox
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(k1:k2) :: tabin, h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER  :: N_in, N_out, jref
+      REAL(wp) :: h_diff
+      LOGICAL  :: northern_side,southern_side
+      !!---------------------------------------------    
+      !      
+      IF (before) THEN          
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk,1) = (e1v(ji,jj) * e3v_n(ji,jj,jk) * vn(ji,jj,jk)*vmask(ji,jj,jk))
+# if defined key_vertical
+                  ptab(ji,jj,jk,2) = vmask(ji,jj,jk) * e1v(ji,jj) * e3v_n(ji,jj,jk)
+# endif
+               END DO
+            END DO
+         END DO
+      ELSE       
+         zrhox = Agrif_rhox()
+# if defined key_vertical
+
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+
+         DO jj=j1,j2
+            jref = jj
+            IF (southern_side) jref = MAX(2,jj)
+            IF (northern_side) jref = MIN(nlcj-2,jj)
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2
+                  if (ptab(ji,jj,jk,2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = ptab(ji,jj,jk,1)/ptab(ji,jj,jk,2)
+                  h_in(N_in) = ptab(ji,jj,jk,2)/(e1v(ji,jj)*zrhox)
+               END DO
+               IF (N_in == 0) THEN
+                  va(ji,jj,:) = 0._wp
+                  CYCLE
+               ENDIF
+         
+               N_out = 0
+               DO jk=1,jpk
+                  if (vmask(ji,jref,jk) == 0) EXIT
+                  N_out = N_out + 1
+                  h_out(N_out) = e3v_a(ji,jref,jk)
+               END DO
+               IF (N_out == 0) THEN
+                 va(ji,jj,:) = 0._wp
+                 CYCLE
+               ENDIF
+               call reconstructandremap(tabin(1:N_in),h_in(1:N_in),va(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+            END DO
+         END DO
+# else
+         DO jk = 1, jpkm1
+            va(i1:i2,j1:j2,jk) = ptab(i1:i2,j1:j2,jk,1) / ( zrhox * e1v(i1:i2,j1:j2) * e3v_a(i1:i2,j1:j2,jk) )
+         END DO
+# endif
+      ENDIF
+      !        
+   END SUBROUTINE interpvn
+
+   SUBROUTINE interpunb( ptab, i1, i2, j1, j2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpunb  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      INTEGER                         , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER  ::   ji, jj
+      REAL(wp) ::   zrhoy, zrhot, zt0, zt1, ztcoeff
+      LOGICAL  ::   western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF( before ) THEN 
+         ptab(i1:i2,j1:j2) = e2u(i1:i2,j1:j2) * hu_n(i1:i2,j1:j2) * un_b(i1:i2,j1:j2)
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhoy = Agrif_Rhoy()
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot      
+         ! Polynomial interpolation coefficients:
+         IF( bdy_tinterp == 1 ) THEN
+            ztcoeff = zrhot * (  zt1**2._wp * (       zt1 - 1._wp)        &
+               &               - zt0**2._wp * (       zt0 - 1._wp)        )
+         ELSEIF( bdy_tinterp == 2 ) THEN
+            ztcoeff = zrhot * (  zt1        * (       zt1 - 1._wp)**2._wp &
+               &               - zt0        * (       zt0 - 1._wp)**2._wp )
+         ELSE
+            ztcoeff = 1
+         ENDIF
+         !   
+         IF(western_side)   ubdy_w(1:nbghostcells,j1:j2) = ubdy_w(1:nbghostcells,j1:j2) + ztcoeff * ptab(i1:i2,j1:j2)  
+         IF(eastern_side)   ubdy_e(1:nbghostcells,j1:j2) = ubdy_e(1:nbghostcells,j1:j2) + ztcoeff * ptab(i1:i2,j1:j2)  
+         IF(southern_side)  ubdy_s(i1:i2,1:nbghostcells) = ubdy_s(i1:i2,1:nbghostcells) + ztcoeff * ptab(i1:i2,j1:j2)
+         IF(northern_side)  ubdy_n(i1:i2,1:nbghostcells) = ubdy_n(i1:i2,1:nbghostcells) + ztcoeff * ptab(i1:i2,j1:j2) 
+         !            
+         IF( bdy_tinterp == 0 .OR. bdy_tinterp == 2) THEN
+            IF(western_side)   ubdy_w(1:nbghostcells,j1:j2) = ubdy_w(1:nbghostcells,j1:j2) / (zrhoy*e2u(i1:i2,j1:j2)) * umask(i1:i2,j1:j2,1)
+            IF(eastern_side)   ubdy_e(1:nbghostcells,j1:j2) = ubdy_e(1:nbghostcells,j1:j2) / (zrhoy*e2u(i1:i2,j1:j2)) * umask(i1:i2,j1:j2,1)
+            IF(southern_side)  ubdy_s(i1:i2,1:nbghostcells) = ubdy_s(i1:i2,1:nbghostcells) / (zrhoy*e2u(i1:i2,j1:j2)) * umask(i1:i2,j1:j2,1)
+            IF(northern_side)  ubdy_n(i1:i2,1:nbghostcells) = ubdy_n(i1:i2,1:nbghostcells) / (zrhoy*e2u(i1:i2,j1:j2)) * umask(i1:i2,j1:j2,1)
+         ENDIF
+      ENDIF
+      ! 
+   END SUBROUTINE interpunb
+
+
+   SUBROUTINE interpvnb( ptab, i1, i2, j1, j2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvnb  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      INTEGER                         , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER  ::   ji,jj
+      REAL(wp) ::   zrhox, zrhot, zt0, zt1, ztcoeff   
+      LOGICAL  ::   western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      ! 
+      IF( before ) THEN 
+         ptab(i1:i2,j1:j2) = e1v(i1:i2,j1:j2) * hv_n(i1:i2,j1:j2) * vn_b(i1:i2,j1:j2)
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhox = Agrif_Rhox()
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot      
+         IF( bdy_tinterp == 1 ) THEN
+            ztcoeff = zrhot * (  zt1**2._wp * (       zt1 - 1._wp)        &
+               &               - zt0**2._wp * (       zt0 - 1._wp)        )
+         ELSEIF( bdy_tinterp == 2 ) THEN
+            ztcoeff = zrhot * (  zt1        * (       zt1 - 1._wp)**2._wp &
+               &               - zt0        * (       zt0 - 1._wp)**2._wp ) 
+         ELSE
+            ztcoeff = 1
+         ENDIF
+         !! clem ghost
+         IF(western_side)   vbdy_w(1:nbghostcells,j1:j2) = vbdy_w(1:nbghostcells,j1:j2) + ztcoeff * ptab(i1:i2,j1:j2)  
+         IF(eastern_side)   vbdy_e(1:nbghostcells,j1:j2) = vbdy_e(1:nbghostcells,j1:j2) + ztcoeff * ptab(i1:i2,j1:j2)   
+         IF(southern_side)  vbdy_s(i1:i2,1:nbghostcells) = vbdy_s(i1:i2,1:nbghostcells) + ztcoeff * ptab(i1:i2,j1:j2)
+         IF(northern_side)  vbdy_n(i1:i2,1:nbghostcells) = vbdy_n(i1:i2,1:nbghostcells) + ztcoeff * ptab(i1:i2,j1:j2) 
+         !            
+         IF( bdy_tinterp == 0 .OR. bdy_tinterp == 2) THEN
+            IF(western_side)   vbdy_w(1:nbghostcells,j1:j2) = vbdy_w(1:nbghostcells,j1:j2) / (zrhox*e1v(i1:i2,j1:j2)) * vmask(i1:i2,j1:j2,1)
+            IF(eastern_side)   vbdy_e(1:nbghostcells,j1:j2) = vbdy_e(1:nbghostcells,j1:j2) / (zrhox*e1v(i1:i2,j1:j2)) * vmask(i1:i2,j1:j2,1)
+            IF(southern_side)  vbdy_s(i1:i2,1:nbghostcells) = vbdy_s(i1:i2,1:nbghostcells) / (zrhox*e1v(i1:i2,j1:j2)) * vmask(i1:i2,j1:j2,1)
+            IF(northern_side)  vbdy_n(i1:i2,1:nbghostcells) = vbdy_n(i1:i2,1:nbghostcells) / (zrhox*e1v(i1:i2,j1:j2)) * vmask(i1:i2,j1:j2,1)
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE interpvnb
+
+
+   SUBROUTINE interpub2b( ptab, i1, i2, j1, j2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpub2b  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      INTEGER                         , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER  ::   ji,jj
+      REAL(wp) ::   zrhot, zt0, zt1,zat
+      LOGICAL  ::   western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      IF( before ) THEN
+         IF ( ln_bt_fw ) THEN
+            ptab(i1:i2,j1:j2) = e2u(i1:i2,j1:j2) * ub2_b(i1:i2,j1:j2)
+         ELSE
+            ptab(i1:i2,j1:j2) = e2u(i1:i2,j1:j2) * un_adv(i1:i2,j1:j2)
+         ENDIF
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot
+         ! Polynomial interpolation coefficients:
+         zat = zrhot * (  zt1**2._wp * (-2._wp*zt1 + 3._wp)    &
+            &           - zt0**2._wp * (-2._wp*zt0 + 3._wp)    ) 
+         !! clem ghost
+         IF(western_side ) ubdy_w(1:nbghostcells,j1:j2) = zat * ptab(i1:i2,j1:j2)  
+         IF(eastern_side ) ubdy_e(1:nbghostcells,j1:j2) = zat * ptab(i1:i2,j1:j2)  
+         IF(southern_side) ubdy_s(i1:i2,1:nbghostcells) = zat * ptab(i1:i2,j1:j2)
+         IF(northern_side) ubdy_n(i1:i2,1:nbghostcells) = zat * ptab(i1:i2,j1:j2) 
+      ENDIF
+      ! 
+   END SUBROUTINE interpub2b
+   
+
+   SUBROUTINE interpvb2b( ptab, i1, i2, j1, j2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvb2b  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   ptab
+      LOGICAL                         , INTENT(in   ) ::   before
+      INTEGER                         , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER ::   ji,jj
+      REAL(wp) ::   zrhot, zt0, zt1,zat
+      LOGICAL ::   western_side, eastern_side,northern_side,southern_side
+      !!----------------------------------------------------------------------  
+      !
+      IF( before ) THEN
+         IF ( ln_bt_fw ) THEN
+            ptab(i1:i2,j1:j2) = e1v(i1:i2,j1:j2) * vb2_b(i1:i2,j1:j2)
+         ELSE
+            ptab(i1:i2,j1:j2) = e1v(i1:i2,j1:j2) * vn_adv(i1:i2,j1:j2)
+         ENDIF
+      ELSE      
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         zrhot = Agrif_rhot()
+         ! Time indexes bounds for integration
+         zt0 = REAL(Agrif_NbStepint()  , wp) / zrhot
+         zt1 = REAL(Agrif_NbStepint()+1, wp) / zrhot
+         ! Polynomial interpolation coefficients:
+         zat = zrhot * (  zt1**2._wp * (-2._wp*zt1 + 3._wp)    &
+            &           - zt0**2._wp * (-2._wp*zt0 + 3._wp)    ) 
+         !
+         IF(western_side )   vbdy_w(1:nbghostcells,j1:j2) = zat * ptab(i1:i2,j1:j2)  
+         IF(eastern_side )   vbdy_e(1:nbghostcells,j1:j2) = zat * ptab(i1:i2,j1:j2)  
+         IF(southern_side)   vbdy_s(i1:i2,1:nbghostcells) = zat * ptab(i1:i2,j1:j2)
+         IF(northern_side)   vbdy_n(i1:i2,1:nbghostcells) = zat * ptab(i1:i2,j1:j2) 
+      ENDIF
+      !      
+   END SUBROUTINE interpvb2b
+
+
+   SUBROUTINE interpe3t( ptab, i1, i2, j1, j2, k1, k2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpe3t  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                              , INTENT(in   ) :: i1, i2, j1, j2, k1, k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) :: ptab
+      LOGICAL                              , INTENT(in   ) :: before
+      INTEGER                              , INTENT(in   ) :: nb , ndir
+      !
+      INTEGER :: ji, jj, jk
+      LOGICAL :: western_side, eastern_side, northern_side, southern_side
+      !!----------------------------------------------------------------------  
+      !    
+      IF( before ) THEN
+         ptab(i1:i2,j1:j2,k1:k2) = tmask(i1:i2,j1:j2,k1:k2) * e3t_0(i1:i2,j1:j2,k1:k2)
+      ELSE
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !
+         DO jk = k1, k2
+            DO jj = j1, j2
+               DO ji = i1, i2
+                  !
+                  IF( ABS( ptab(ji,jj,jk) - tmask(ji,jj,jk) * e3t_0(ji,jj,jk) ) > 1.D-2) THEN
+                     IF (western_side.AND.(ptab(i1+nbghostcells-1,jj,jk)>0._wp)) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the western border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*)  ptab(ji,jj,jk), e3t_0(ji,jj,jk) 
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (eastern_side.AND.(ptab(i2-nbghostcells+1,jj,jk)>0._wp)) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the eastern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*)  ptab(ji,jj,jk), e3t_0(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (southern_side.AND.(ptab(ji,j1+nbghostcells-1,jk)>0._wp)) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the southern border ji,jj,jk', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*)  ptab(ji,jj,jk), e3t_0(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (northern_side.AND.(ptab(ji,j2-nbghostcells+1,jk)>0._wp)) THEN
+                        WRITE(numout,*) 'ERROR bathymetry merge at the northen border ji,jj,jk', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*)  ptab(ji,jj,jk), e3t_0(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE interpe3t
+
+
+   SUBROUTINE interpumsk( ptab, i1, i2, j1, j2, k1, k2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpumsk  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                              , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                              , INTENT(in   ) ::   before
+      INTEGER                              , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER ::   ji, jj, jk
+      LOGICAL ::   western_side, eastern_side   
+      !!----------------------------------------------------------------------  
+      !    
+      IF( before ) THEN
+         ptab(i1:i2,j1:j2,k1:k2) = umask(i1:i2,j1:j2,k1:k2)
+      ELSE
+         western_side = (nb == 1).AND.(ndir == 1)
+         eastern_side = (nb == 1).AND.(ndir == 2)
+         DO jk = k1, k2
+            DO jj = j1, j2
+               DO ji = i1, i2
+                   ! Velocity mask at boundary edge points:
+                  IF (ABS(ptab(ji,jj,jk) - umask(ji,jj,jk)) > 1.D-2) THEN
+                     IF (western_side) THEN
+                        WRITE(numout,*) 'ERROR with umask at the western border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), umask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (eastern_side) THEN
+                        WRITE(numout,*) 'ERROR with umask at the eastern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), umask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE interpumsk
+
+
+   SUBROUTINE interpvmsk( ptab, i1, i2, j1, j2, k1, k2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interpvmsk  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                              , INTENT(in   ) ::   i1,i2,j1,j2,k1,k2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                              , INTENT(in   ) ::   before
+      INTEGER                              , INTENT(in   ) :: nb , ndir
+      !
+      INTEGER ::   ji, jj, jk
+      LOGICAL ::   northern_side, southern_side     
+      !!----------------------------------------------------------------------  
+      !    
+      IF( before ) THEN
+         ptab(i1:i2,j1:j2,k1:k2) = vmask(i1:i2,j1:j2,k1:k2)
+      ELSE
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         DO jk = k1, k2
+            DO jj = j1, j2
+               DO ji = i1, i2
+                   ! Velocity mask at boundary edge points:
+                  IF (ABS(ptab(ji,jj,jk) - vmask(ji,jj,jk)) > 1.D-2) THEN
+                     IF (southern_side) THEN
+                        WRITE(numout,*) 'ERROR with vmask at the southern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), vmask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ELSEIF (northern_side) THEN
+                        WRITE(numout,*) 'ERROR with vmask at the northern border ji,jj,jk ', ji+nimpp-1,jj+njmpp-1,jk
+                        WRITE(numout,*) '      masks: parent, child ', ptab(ji,jj,jk), vmask(ji,jj,jk)
+                        kindic_agr = kindic_agr + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE interpvmsk
+
+
+   SUBROUTINE interpavm( ptab, i1, i2, j1, j2, k1, k2, m1, m2, before )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interavm  ***
+      !!----------------------------------------------------------------------  
+      INTEGER                                    , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, m1, m2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,m1:m2), INTENT(inout) ::   ptab
+      LOGICAL                                    , INTENT(in   ) ::   before
+      REAL(wp), DIMENSION(k1:k2) :: tabin, h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER  :: N_in, N_out, ji, jj, jk
+      !!----------------------------------------------------------------------  
+      !      
+      IF (before) THEN         
+         DO jk=k1,k2
+            DO jj=j1,j2
+              DO ji=i1,i2
+                    ptab(ji,jj,jk,1) = avm_k(ji,jj,jk)
+              END DO
+           END DO
+        END DO
+#ifdef key_vertical         
+        DO jk=k1,k2
+           DO jj=j1,j2
+              DO ji=i1,i2
+                 ptab(ji,jj,jk,2) = wmask(ji,jj,jk) * e3w_n(ji,jj,jk) 
+              END DO
+           END DO
+        END DO
+#endif
+      ELSE 
+#ifdef key_vertical         
+         avm_k(i1:i2,j1:j2,1:jpk) = 0.
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of parent grid
+                  IF (ptab(ji,jj,jk,2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = ptab(ji,jj,jk,1)
+                  h_in(N_in) = ptab(ji,jj,jk,2)
+               END DO
+               N_out = 0
+               DO jk=1,jpk ! jpk of child grid
+                  IF (wmask(ji,jj,jk) == 0) EXIT 
+                  N_out = N_out + 1
+                  h_out(jk) = e3t_n(ji,jj,jk)
+               ENDDO
+               IF (N_in > 0) THEN
+                  CALL reconstructandremap(tabin(1:N_in),h_in,avm_k(ji,jj,1:N_out),h_out,N_in,N_out)
+               ENDIF
+            ENDDO
+         ENDDO
+#else
+         avm_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2,1)
+#endif
+      ENDIF
+      !
+   END SUBROUTINE interpavm
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                          no AGRIF zoom
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE Agrif_OCE_Interp_empty
+      WRITE(*,*)  'agrif_oce_interp : You should not have seen this print! error?'
+   END SUBROUTINE Agrif_OCE_Interp_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_oce_interp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_sponge.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_sponge.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_sponge.F90	(revision 14097)
@@ -0,0 +1,625 @@
+#define SPONGE && define SPONGE_TOP
+
+MODULE agrif_oce_sponge
+   !!======================================================================
+   !!                   ***  MODULE  agrif_oce_interp  ***
+   !! AGRIF: sponge package for the ocean dynamics (OPA)
+   !!======================================================================
+   !! History :  2.0  !  2002-06  (XXX)  Original cade
+   !!             -   !  2005-11  (XXX) 
+   !!            3.2  !  2009-04  (R. Benshila) 
+   !!            3.6  !  2014-09  (R. Benshila) 
+   !!----------------------------------------------------------------------
+#if defined key_agrif
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE oce
+   USE dom_oce
+   !
+   USE in_out_manager
+   USE agrif_oce
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC Agrif_Sponge, Agrif_Sponge_Tra, Agrif_Sponge_Dyn
+   PUBLIC interptsn_sponge, interpun_sponge, interpvn_sponge
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_Sponge_Tra
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_Sponge_Tra ***
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zcoef   ! local scalar
+      
+      !!----------------------------------------------------------------------
+      !
+#if defined SPONGE
+      !! Assume persistence:
+      zcoef = REAL(Agrif_rhot()-1,wp)/REAL(Agrif_rhot())
+
+      CALL Agrif_Sponge
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .TRUE.
+      tabspongedone_tsn     = .FALSE.
+      !
+      CALL Agrif_Bc_Variable( tsn_sponge_id, calledweight=zcoef, procname=interptsn_sponge )
+      !
+      Agrif_UseSpecialValue = .FALSE.
+#endif
+      !
+   END SUBROUTINE Agrif_Sponge_Tra
+
+
+   SUBROUTINE Agrif_Sponge_dyn
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_Sponge_dyn ***
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zcoef   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+#if defined SPONGE
+      zcoef = REAL(Agrif_rhot()-1,wp)/REAL(Agrif_rhot())
+
+      Agrif_SpecialValue=0.
+      Agrif_UseSpecialValue = ln_spc_dyn
+      !
+      tabspongedone_u = .FALSE.
+      tabspongedone_v = .FALSE.         
+      CALL Agrif_Bc_Variable( un_sponge_id, calledweight=zcoef, procname=interpun_sponge )
+      !
+      tabspongedone_u = .FALSE.
+      tabspongedone_v = .FALSE.
+      CALL Agrif_Bc_Variable( vn_sponge_id, calledweight=zcoef, procname=interpvn_sponge )
+      !
+      Agrif_UseSpecialValue = .FALSE.
+#endif
+      !
+   END SUBROUTINE Agrif_Sponge_dyn
+
+
+   SUBROUTINE Agrif_Sponge
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE  Agrif_Sponge ***
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, ind1, ind2
+      INTEGER  ::   ispongearea
+      REAL(wp) ::   z1_spongearea
+      REAL(wp), DIMENSION(jpi,jpj) :: ztabramp
+      !!----------------------------------------------------------------------
+      !
+#if defined SPONGE || defined SPONGE_TOP
+      IF (( .NOT. spongedoneT ).OR.( .NOT. spongedoneU )) THEN
+         ! Define ramp from boundaries towards domain interior at T-points
+         ! Store it in ztabramp
+
+         ispongearea  = 1 + nn_sponge_len * Agrif_irhox()
+         z1_spongearea = 1._wp / REAL( ispongearea )
+         
+         ztabramp(:,:) = 0._wp
+
+         ! --- West --- !
+         IF( l_Westedge ) THEN
+            ind1 = 1+nbghostcells
+            ind2 = 1+nbghostcells + ispongearea 
+            DO jj = 1, jpj
+               DO ji = ind1, ind2                
+                  ztabramp(ji,jj) = REAL( ind2 - ji ) * z1_spongearea * umask(ind1,jj,1)
+               END DO
+            ENDDO
+         ENDIF
+
+         ! --- East --- !
+         IF( l_Eastedge ) THEN
+            ind1 = nlci - nbghostcells - ispongearea
+            ind2 = nlci - nbghostcells
+            DO jj = 1, jpj
+               DO ji = ind1, ind2
+                  ztabramp(ji,jj) = MAX( ztabramp(ji,jj), REAL( ji - ind1 ) * z1_spongearea * umask(ind2-1,jj,1) )
+               ENDDO
+            ENDDO
+         ENDIF
+
+         ! --- South --- !
+         IF( l_Southedge ) THEN
+            ind1 = 1+nbghostcells
+            ind2 = 1+nbghostcells + ispongearea
+            DO jj = ind1, ind2 
+               DO ji = 1, jpi
+                  ztabramp(ji,jj) = MAX( ztabramp(ji,jj), REAL( ind2 - jj ) * z1_spongearea * vmask(ji,ind1,1) )
+               END DO
+            ENDDO
+         ENDIF
+
+         ! --- North --- !
+         IF( l_Northedge ) THEN
+            ind1 = nlcj - nbghostcells - ispongearea
+            ind2 = nlcj - nbghostcells
+            DO jj = ind1, ind2
+               DO ji = 1, jpi
+                  ztabramp(ji,jj) = MAX( ztabramp(ji,jj), REAL( jj - ind1 ) * z1_spongearea * vmask(ji,ind2-1,1) )
+               END DO
+            ENDDO
+         ENDIF
+
+      ENDIF
+
+      ! Tracers
+      IF( .NOT. spongedoneT ) THEN
+         fsaht_spu(:,:) = 0._wp
+         fsaht_spv(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! vector opt.
+               fsaht_spu(ji,jj) = 0.5_wp * visc_tra * ( ztabramp(ji,jj) + ztabramp(ji+1,jj  ) )
+               fsaht_spv(ji,jj) = 0.5_wp * visc_tra * ( ztabramp(ji,jj) + ztabramp(ji  ,jj+1) )
+            END DO
+         END DO
+         CALL lbc_lnk( 'agrif_oce_sponge', fsaht_spu, 'U', 1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( 'agrif_oce_sponge', fsaht_spv, 'V', 1. )
+         
+         spongedoneT = .TRUE.
+      ENDIF
+
+      ! Dynamics
+      IF( .NOT. spongedoneU ) THEN
+         fsahm_spt(:,:) = 0._wp
+         fsahm_spf(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! vector opt.
+               fsahm_spt(ji,jj) = visc_dyn * ztabramp(ji,jj)
+               fsahm_spf(ji,jj) = 0.25_wp * visc_dyn * ( ztabramp(ji  ,jj  ) + ztabramp(ji  ,jj+1) &
+                                                     &  +ztabramp(ji+1,jj+1) + ztabramp(ji+1,jj  ) )
+            END DO
+         END DO
+         CALL lbc_lnk( 'agrif_oce_sponge', fsahm_spt, 'T', 1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( 'agrif_oce_sponge', fsahm_spf, 'F', 1. )
+         
+         spongedoneU = .TRUE.
+      ENDIF
+      !
+#endif
+      !
+   END SUBROUTINE Agrif_Sponge
+
+   SUBROUTINE interptsn_sponge( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE interptsn_sponge ***
+      !!----------------------------------------------------------------------
+      INTEGER                                     , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   tabres
+      LOGICAL                                     , INTENT(in   ) ::   before
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::   iku, ikv
+      REAL(wp) :: ztsa, zabe1, zabe2, zbtr
+      REAL(wp), DIMENSION(i1:i2,j1:j2,jpk) :: ztu, ztv
+      REAL(wp), DIMENSION(i1:i2,j1:j2,jpk,n1:n2) ::tsbdiff
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,jpk,n1:n2) ::tabres_child
+      REAL(wp), DIMENSION(k1:k2,n1:n2-1) :: tabin
+      REAL(wp), DIMENSION(k1:k2) :: h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER :: N_in, N_out
+      REAL(wp) :: h_diff
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         DO jn = 1, jpts
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     tabres(ji,jj,jk,jn) = tsb(ji,jj,jk,jn)
+                  END DO
+               END DO
+            END DO
+         END DO
+
+# if defined key_vertical
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,jpts+1) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) 
+               END DO
+            END DO
+         END DO
+# endif
+
+      ELSE   
+         !
+# if defined key_vertical
+         tabres_child(:,:,:,:) = 0.
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of parent grid
+                  IF (tabres(ji,jj,jk,n2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = tabres(ji,jj,jk,n1:n2-1)
+                  h_in(N_in) = tabres(ji,jj,jk,n2)
+               END DO
+               N_out = 0
+               DO jk=1,jpk ! jpk of child grid
+                  IF (tmask(ji,jj,jk) == 0) EXIT 
+                  N_out = N_out + 1
+                  h_out(jk) = e3t_n(ji,jj,jk) !Child grid scale factors. Could multiply by e1e2t here instead of division above
+               ENDDO
+               IF (N_in > 0) THEN
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  tabres(ji,jj,k2,:) = tabres(ji,jj,k2-1,:) !what is this line for?????
+                  DO jn=1,jpts
+                     call reconstructandremap(tabin(1:N_in,jn),h_in,tabres_child(ji,jj,1:N_out,jn),h_out,N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+# endif
+
+         DO jj=j1,j2
+            DO ji=i1,i2
+               DO jk=1,jpkm1
+# if defined key_vertical
+                  tsbdiff(ji,jj,jk,1:jpts) = tsb(ji,jj,jk,1:jpts) - tabres_child(ji,jj,jk,1:jpts)
+# else
+                  tsbdiff(ji,jj,jk,1:jpts) = tsb(ji,jj,jk,1:jpts) - tabres(ji,jj,jk,1:jpts)
+# endif
+               ENDDO
+            ENDDO
+         ENDDO
+
+         DO jn = 1, jpts            
+            DO jk = 1, jpkm1
+               ztu(i1:i2,j1:j2,jk) = 0._wp
+               DO jj = j1,j2
+                  DO ji = i1,i2-1
+                     zabe1 = fsaht_spu(ji,jj) * umask(ji,jj,jk) * e2_e1u(ji,jj) * e3u_n(ji,jj,jk)
+                     ztu(ji,jj,jk) = zabe1 * ( tsbdiff(ji+1,jj  ,jk,jn) - tsbdiff(ji,jj,jk,jn) ) 
+                  END DO
+               END DO
+               ztv(i1:i2,j1:j2,jk) = 0._wp
+               DO ji = i1,i2
+                  DO jj = j1,j2-1
+                     zabe2 = fsaht_spv(ji,jj) * vmask(ji,jj,jk) * e1_e2v(ji,jj) * e3v_n(ji,jj,jk)
+                     ztv(ji,jj,jk) = zabe2 * ( tsbdiff(ji  ,jj+1,jk,jn) - tsbdiff(ji,jj,jk,jn) )
+                  END DO
+               END DO
+               !
+               IF( ln_zps ) THEN      ! set gradient at partial step level
+                  DO jj = j1,j2
+                     DO ji = i1,i2
+                        ! last level
+                        iku = mbku(ji,jj)
+                        ikv = mbkv(ji,jj)
+                        IF( iku == jk )   ztu(ji,jj,jk) = 0._wp
+                        IF( ikv == jk )   ztv(ji,jj,jk) = 0._wp
+                     END DO
+                  END DO
+               ENDIF
+            END DO
+            !
+            DO jk = 1, jpkm1
+               DO jj = j1+1,j2-1
+                  DO ji = i1+1,i2-1
+                     IF (.NOT. tabspongedone_tsn(ji,jj)) THEN 
+                        zbtr = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                        ! horizontal diffusive trends
+                        ztsa = zbtr * (  ztu(ji,jj,jk) - ztu(ji-1,jj,jk) + ztv(ji,jj,jk) - ztv(ji,jj-1,jk)  )
+                        ! add it to the general tracer trends
+                        tsa(ji,jj,jk,jn) = tsa(ji,jj,jk,jn) + ztsa
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+            !
+         END DO
+         !
+         tabspongedone_tsn(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+         !
+      ENDIF
+      !
+   END SUBROUTINE interptsn_sponge
+
+   SUBROUTINE interpun_sponge(tabres,i1,i2,j1,j2,k1,k2,m1,m2, before)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpun_sponge ***
+      !!---------------------------------------------    
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,m1,m2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,m1:m2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+
+      INTEGER :: ji,jj,jk,jmax
+
+      ! sponge parameters 
+      REAL(wp) :: ze2u, ze1v, zua, zva, zbtr, h_diff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: ubdiff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: rotdiff, hdivdiff
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: tabres_child
+      REAL(wp), DIMENSION(k1:k2) :: tabin, h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER ::N_in,N_out
+      !!---------------------------------------------    
+      !
+      IF( before ) THEN
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,m1) = ub(ji,jj,jk)
+# if defined key_vertical
+                  tabres(ji,jj,jk,m2) = e3u_n(ji,jj,jk)*umask(ji,jj,jk)
+# endif
+               END DO
+            END DO
+         END DO
+
+      ELSE
+
+# if defined key_vertical
+         tabres_child(:,:,:) = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2
+                  IF (tabres(ji,jj,jk,m2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = tabres(ji,jj,jk,m1)
+                  h_in(N_in) = tabres(ji,jj,jk,m2)
+              ENDDO
+              !
+              IF (N_in == 0) THEN
+                 tabres_child(ji,jj,:) = 0.
+                 CYCLE
+              ENDIF
+         
+              N_out = 0
+              DO jk=1,jpk
+                 if (umask(ji,jj,jk) == 0) EXIT
+                 N_out = N_out + 1
+                 h_out(N_out) = e3u_n(ji,jj,jk)
+              ENDDO
+         
+              IF (N_out == 0) THEN
+                 tabres_child(ji,jj,:) = 0.
+                 CYCLE
+              ENDIF
+         
+              IF (N_in * N_out > 0) THEN
+                 h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                 if (h_diff < -1.e4) then
+                    print *,'CHECK YOUR BATHY ...', h_diff, sum(h_out(1:N_out)), sum(h_in(1:N_in))
+                 endif
+              ENDIF
+              call reconstructandremap(tabin(1:N_in),h_in(1:N_in),tabres_child(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+         
+            ENDDO
+         ENDDO
+
+         ubdiff(i1:i2,j1:j2,:) = (ub(i1:i2,j1:j2,:) - tabres_child(i1:i2,j1:j2,:))*umask(i1:i2,j1:j2,:)
+#else
+         ubdiff(i1:i2,j1:j2,:) = (ub(i1:i2,j1:j2,:) - tabres(i1:i2,j1:j2,:,1))*umask(i1:i2,j1:j2,:)
+#endif
+         !
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            !                                             ! ===============
+
+            !                                             ! --------
+            ! Horizontal divergence                       !   div
+            !                                             ! --------
+            DO jj = j1,j2
+               DO ji = i1+1,i2   ! vector opt.
+                  zbtr = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk) * fsahm_spt(ji,jj)
+                  hdivdiff(ji,jj,jk) = (  e2u(ji  ,jj)*e3u_n(ji  ,jj,jk) * ubdiff(ji  ,jj,jk) &
+                                     &   -e2u(ji-1,jj)*e3u_n(ji-1,jj,jk) * ubdiff(ji-1,jj,jk) ) * zbtr
+               END DO
+            END DO
+
+            DO jj = j1,j2-1
+               DO ji = i1,i2   ! vector opt.
+                  zbtr = r1_e1e2f(ji,jj) * e3f_n(ji,jj,jk) * fsahm_spf(ji,jj)
+                  rotdiff(ji,jj,jk) = ( -e1u(ji,jj+1) * ubdiff(ji,jj+1,jk)   &
+                                    &   +e1u(ji,jj  ) * ubdiff(ji,jj  ,jk) ) * fmask(ji,jj,jk) * zbtr 
+               END DO
+            END DO
+         END DO
+         !
+         DO jj = j1+1, j2-1
+            DO ji = i1+1, i2-1   ! vector opt.
+
+               IF (.NOT. tabspongedone_u(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+                     ! horizontal diffusive trends
+                     zua = - ( ze2u - rotdiff (ji,jj-1,jk) ) / ( e2u(ji,jj) * e3u_n(ji,jj,jk) )   &
+                           + ( hdivdiff(ji+1,jj,jk) - ze1v ) * r1_e1u(ji,jj)
+
+                     ! add it to the general momentum trends
+                     ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+
+                  END DO
+               ENDIF
+
+            END DO
+         END DO
+
+         tabspongedone_u(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+
+         jmax = j2-1
+         IF ( l_Northedge ) jmax = MIN(jmax,nlcj-nbghostcells-2)   ! North
+
+         DO jj = j1+1, jmax
+            DO ji = i1+1, i2   ! vector opt.
+
+               IF (.NOT. tabspongedone_v(ji,jj)) THEN
+                  DO jk = 1, jpkm1                                 ! Horizontal slab
+                     ze2u = rotdiff (ji,jj,jk)
+                     ze1v = hdivdiff(ji,jj,jk)
+
+                     ! horizontal diffusive trends
+                     zva = + ( ze2u - rotdiff (ji-1,jj,jk) ) / ( e1v(ji,jj) * e3v_n(ji,jj,jk) )   &
+                           + ( hdivdiff(ji,jj+1,jk) - ze1v ) * r1_e2v(ji,jj)
+
+                     ! add it to the general momentum trends
+                     va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  END DO
+               ENDIF
+               !
+            END DO
+         END DO
+         !
+         tabspongedone_v(i1+1:i2,j1+1:jmax) = .TRUE.
+         !
+      ENDIF
+      !
+   END SUBROUTINE interpun_sponge
+
+   SUBROUTINE interpvn_sponge(tabres,i1,i2,j1,j2,k1,k2,m1,m2, before,nb,ndir)
+      !!---------------------------------------------
+      !!   *** ROUTINE interpvn_sponge ***
+      !!--------------------------------------------- 
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,m1,m2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,m1:m2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb , ndir
+      !
+      INTEGER  ::   ji, jj, jk, imax
+      REAL(wp) ::   ze2u, ze1v, zua, zva, zbtr, h_diff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: vbdiff
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: rotdiff, hdivdiff
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: tabres_child
+      REAL(wp), DIMENSION(k1:k2) :: tabin, h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER :: N_in, N_out
+      !!--------------------------------------------- 
+      
+      IF( before ) THEN 
+         DO jk=1,jpkm1
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,m1) = vb(ji,jj,jk)
+# if defined key_vertical
+                  tabres(ji,jj,jk,m2) = vmask(ji,jj,jk) * e3v_n(ji,jj,jk)
+# endif
+               END DO
+            END DO
+         END DO
+      ELSE
+
+# if defined key_vertical
+         tabres_child(:,:,:) = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2
+                  IF (tabres(ji,jj,jk,m2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = tabres(ji,jj,jk,m1)
+                  h_in(N_in) = tabres(ji,jj,jk,m2)
+              ENDDO
+         
+              IF (N_in == 0) THEN
+                 tabres_child(ji,jj,:) = 0.
+                 CYCLE
+              ENDIF
+         
+              N_out = 0
+              DO jk=1,jpk
+                 if (vmask(ji,jj,jk) == 0) EXIT
+                 N_out = N_out + 1
+                 h_out(N_out) = e3v_n(ji,jj,jk)
+              ENDDO
+         
+              IF (N_in * N_out > 0) THEN
+                 h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                 if (h_diff < -1.e4) then
+                    print *,'CHECK YOUR BATHY ...', h_diff, sum(h_out(1:N_out)), sum(h_in(1:N_in))
+                 endif
+              ENDIF
+              call reconstructandremap(tabin(1:N_in),h_in(1:N_in),tabres_child(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+            ENDDO
+         ENDDO
+
+         vbdiff(i1:i2,j1:j2,:) = (vb(i1:i2,j1:j2,:) - tabres_child(i1:i2,j1:j2,:))*vmask(i1:i2,j1:j2,:)  
+# else
+         vbdiff(i1:i2,j1:j2,:) = (vb(i1:i2,j1:j2,:) - tabres(i1:i2,j1:j2,:,1))*vmask(i1:i2,j1:j2,:)
+# endif
+         !
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            !                                             ! ===============
+
+            !                                             ! --------
+            ! Horizontal divergence                       !   div
+            !                                             ! --------
+            DO jj = j1+1,j2
+               DO ji = i1,i2   ! vector opt.
+                  zbtr = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk) * fsahm_spt(ji,jj)
+                  hdivdiff(ji,jj,jk) = ( e1v(ji,jj  ) * e3v_n(ji,jj  ,jk) * vbdiff(ji,jj  ,jk)  &
+                                     &  -e1v(ji,jj-1) * e3v_n(ji,jj-1,jk) * vbdiff(ji,jj-1,jk)  ) * zbtr
+               END DO
+            END DO
+            DO jj = j1,j2
+               DO ji = i1,i2-1   ! vector opt.
+                  zbtr = r1_e1e2f(ji,jj) * e3f_n(ji,jj,jk) * fsahm_spf(ji,jj)
+                  rotdiff(ji,jj,jk) = ( e2v(ji+1,jj) * vbdiff(ji+1,jj,jk) & 
+                                    &  -e2v(ji  ,jj) * vbdiff(ji  ,jj,jk)  ) * fmask(ji,jj,jk) * zbtr
+               END DO
+            END DO
+         END DO
+
+         !                                                ! ===============
+         !                                                
+
+         imax = i2 - 1
+         IF ( l_Eastedge )   imax = MIN(imax,nlci-nbghostcells-2)   ! East
+
+         DO jj = j1+1, j2
+            DO ji = i1+1, imax   ! vector opt.
+               IF( .NOT. tabspongedone_u(ji,jj) ) THEN
+                  DO jk = 1, jpkm1
+                     ua(ji,jj,jk) = ua(ji,jj,jk)                                                               &
+                        & - ( rotdiff (ji  ,jj,jk) - rotdiff (ji,jj-1,jk)) / ( e2u(ji,jj) * e3u_n(ji,jj,jk) )  &
+                        & + ( hdivdiff(ji+1,jj,jk) - hdivdiff(ji,jj  ,jk)) * r1_e1u(ji,jj)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+         !
+         tabspongedone_u(i1+1:imax,j1+1:j2) = .TRUE.
+         !
+         DO jj = j1+1, j2-1
+            DO ji = i1+1, i2-1   ! vector opt.
+               IF( .NOT. tabspongedone_v(ji,jj) ) THEN
+                  DO jk = 1, jpkm1
+                     va(ji,jj,jk) = va(ji,jj,jk)                                                                  &
+                        &  + ( rotdiff (ji,jj  ,jk) - rotdiff (ji-1,jj,jk) ) / ( e1v(ji,jj) * e3v_n(ji,jj,jk) )   &
+                        &  + ( hdivdiff(ji,jj+1,jk) - hdivdiff(ji  ,jj,jk) ) * r1_e2v(ji,jj)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+         tabspongedone_v(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+      ENDIF
+      !
+   END SUBROUTINE interpvn_sponge
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                          no AGRIF zoom
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_oce_sponge_empty
+      WRITE(*,*)  'agrif_oce_sponge : You should not have seen this print! error?'
+   END SUBROUTINE agrif_oce_sponge_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_oce_sponge
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_update.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_update.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_oce_update.F90	(revision 14097)
@@ -0,0 +1,1424 @@
+#define TWO_WAY        /* TWO WAY NESTING */
+#undef DECAL_FEEDBACK  /* SEPARATION of INTERFACES*/
+#undef VOL_REFLUX      /* VOLUME REFLUXING*/
+ 
+MODULE agrif_oce_update
+   !!======================================================================
+   !!                   ***  MODULE  agrif_oce_interp  ***
+   !! AGRIF: update package for the ocean dynamics (OPA)
+   !!======================================================================
+   !! History :  2.0  !  2002-06  (L. Debreu)  Original code
+   !!            3.2  !  2009-04  (R. Benshila) 
+   !!            3.6  !  2014-09  (R. Benshila) 
+   !!----------------------------------------------------------------------
+#if defined key_agrif 
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE oce
+   USE dom_oce
+   USE zdf_oce        ! vertical physics: ocean variables 
+   USE agrif_oce
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE domvvl         ! Need interpolation routines 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   Agrif_Update_Tra, Agrif_Update_Dyn, Agrif_Update_vvl, Agrif_Update_ssh
+   PUBLIC   Update_Scales
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_Update_Tra( )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE Agrif_Update_Tra ***
+      !!----------------------------------------------------------------------
+      ! 
+      IF (Agrif_Root()) RETURN
+      !
+#if defined TWO_WAY  
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update tracers  from grid Number',Agrif_Fixed()
+
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid    = 0._wp
+      ! 
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(tsn_id, procname=updateTS)
+! near boundary update:
+!      CALL Agrif_Update_Variable(tsn_id,locupdate=(/0,2/), procname=updateTS)
+# else
+      CALL Agrif_Update_Variable(tsn_id, locupdate=(/1,0/),procname=updateTS)
+! near boundary update:
+!      CALL Agrif_Update_Variable(tsn_id,locupdate=(/1,2/), procname=updateTS)
+# endif
+      !
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      !
+#endif
+      !
+   END SUBROUTINE Agrif_Update_Tra
+
+   SUBROUTINE Agrif_Update_Dyn( )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE Agrif_Update_Dyn ***
+      !!----------------------------------------------------------------------
+      ! 
+      IF (Agrif_Root()) RETURN
+      !
+#if defined TWO_WAY
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update momentum from grid Number',Agrif_Fixed()
+
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      Agrif_SpecialValueFineGrid = 0.
+      !     
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(un_update_id,procname = updateU)
+      CALL Agrif_Update_Variable(vn_update_id,procname = updateV)
+! near boundary update:
+!      CALL Agrif_Update_Variable(un_update_id,locupdate=(/0,1/),procname = updateU)
+!      CALL Agrif_Update_Variable(vn_update_id,locupdate=(/0,1/),procname = updateV)
+# else
+      CALL Agrif_Update_Variable(un_update_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateU)
+      CALL Agrif_Update_Variable(vn_update_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updateV)
+! near boundary update:
+!      CALL Agrif_Update_Variable(un_update_id,locupdate1=(/0,1/),locupdate2=(/1,1/),procname = updateU)
+!      CALL Agrif_Update_Variable(vn_update_id,locupdate1=(/1,1/),locupdate2=(/0,1/),procname = updateV)
+# endif
+
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(e1u_id,procname = updateU2d)
+      CALL Agrif_Update_Variable(e2v_id,procname = updateV2d)  
+# else
+      CALL Agrif_Update_Variable(e1u_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateU2d)
+      CALL Agrif_Update_Variable(e2v_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updateV2d)  
+# endif
+      !
+# if ! defined DECAL_FEEDBACK
+      ! Account for updated thicknesses at boundary edges
+      IF (.NOT.ln_linssh) THEN
+!         CALL Agrif_Update_Variable(un_update_id,locupdate1=(/0,0/),locupdate2=(/0,0/),procname = correct_u_bdy)
+!         CALL Agrif_Update_Variable(vn_update_id,locupdate1=(/0,0/),locupdate2=(/0,0/),procname = correct_v_bdy)
+      ENDIF
+# endif
+      ! 
+      IF ( ln_dynspg_ts .AND. ln_bt_fw ) THEN
+         ! Update time integrated transports
+#  if ! defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(ub2b_update_id,procname = updateub2b)
+         CALL Agrif_Update_Variable(vb2b_update_id,procname = updatevb2b)
+#  else
+         CALL Agrif_Update_Variable(ub2b_update_id,locupdate1=(/0,-1/),locupdate2=(/1,-2/),procname = updateub2b)
+         CALL Agrif_Update_Variable(vb2b_update_id,locupdate1=(/1,-2/),locupdate2=(/0,-1/),procname = updatevb2b)
+#  endif
+      END IF
+#endif
+      !
+   END SUBROUTINE Agrif_Update_Dyn
+
+   SUBROUTINE Agrif_Update_ssh( )
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Update_ssh ***
+      !!---------------------------------------------
+      ! 
+      IF (Agrif_Root()) RETURN
+      !
+#if defined TWO_WAY
+      !
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid = 0.
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(sshn_id,procname = updateSSH)
+# else
+      CALL Agrif_Update_Variable(sshn_id,locupdate=(/1,0/),procname = updateSSH)
+# endif
+      !
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      !
+#  if defined VOL_REFLUX
+      IF ( ln_dynspg_ts.AND.ln_bt_fw ) THEN
+         ! Refluxing on ssh:
+#  if defined DECAL_FEEDBACK
+         CALL Agrif_Update_Variable(ub2b_update_id,locupdate1=(/0, 0/),locupdate2=(/1, 1/),procname = reflux_sshu)
+         CALL Agrif_Update_Variable(vb2b_update_id,locupdate1=(/1, 1/),locupdate2=(/0, 0/),procname = reflux_sshv)
+#  else
+         CALL Agrif_Update_Variable(ub2b_update_id,locupdate1=(/-1,-1/),locupdate2=(/ 0, 0/),procname = reflux_sshu)
+         CALL Agrif_Update_Variable(vb2b_update_id,locupdate1=(/ 0, 0/),locupdate2=(/-1,-1/),procname = reflux_sshv)
+#  endif
+      END IF
+#  endif
+      !
+#endif
+      !
+   END SUBROUTINE Agrif_Update_ssh
+
+
+   SUBROUTINE Agrif_Update_Tke( )
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Update_Tke ***
+      !!---------------------------------------------
+      !!
+      ! 
+      IF (Agrif_Root()) RETURN
+      !       
+#  if defined TWO_WAY
+
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid = 0.
+
+      CALL Agrif_Update_Variable( en_id, locupdate=(/0,0/), procname=updateEN  )
+      CALL Agrif_Update_Variable(avt_id, locupdate=(/0,0/), procname=updateAVT )
+      CALL Agrif_Update_Variable(avm_id, locupdate=(/0,0/), procname=updateAVM )
+
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+
+#  endif
+      
+   END SUBROUTINE Agrif_Update_Tke
+
+
+   SUBROUTINE Agrif_Update_vvl( )
+      !!---------------------------------------------
+      !!   *** ROUTINE Agrif_Update_vvl ***
+      !!---------------------------------------------
+      !
+      IF (Agrif_Root()) RETURN
+      !
+#if defined TWO_WAY  
+      !
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Update e3 from grid Number',Agrif_Fixed(), 'Step', Agrif_Nb_Step()
+      !
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid = 0.
+      ! 
+      ! No interface separation here, update vertical grid at T points 
+      ! everywhere over the overlapping regions (one account for refluxing in that case):
+      CALL Agrif_Update_Variable(e3t_id, procname=updatee3t) 
+      !
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      !
+      CALL Agrif_ChildGrid_To_ParentGrid()
+      CALL dom_vvl_update_UVF
+      CALL Agrif_ParentGrid_To_ChildGrid()
+      !
+#endif
+      !
+   END SUBROUTINE Agrif_Update_vvl
+
+   SUBROUTINE dom_vvl_update_UVF
+      !!---------------------------------------------
+      !!       *** ROUTINE dom_vvl_update_UVF ***
+      !!---------------------------------------------
+      !!
+      INTEGER :: jk
+      REAL(wp):: zcoef
+      !!---------------------------------------------
+
+      IF (lwp.AND.lk_agrif_debug) Write(*,*) 'Finalize e3 on grid Number', &
+                  & Agrif_Fixed(), 'Step', Agrif_Nb_Step()
+
+      ! Save "old" scale factor (prior update) for subsequent asselin correction
+      ! of prognostic variables
+      ! -----------------------
+      !
+      e3u_a(:,:,:) = e3u_n(:,:,:)
+      e3v_a(:,:,:) = e3v_n(:,:,:)
+!      ua(:,:,:) = e3u_b(:,:,:)
+!      va(:,:,:) = e3v_b(:,:,:)
+      hu_a(:,:) = hu_n(:,:)
+      hv_a(:,:) = hv_n(:,:)
+
+      ! 1) NOW fields
+      !--------------
+      
+         ! Vertical scale factor interpolations
+         ! ------------------------------------
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:) ,  'U' )
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:) ,  'V' )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:) ,  'F' )
+
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+
+         ! Update total depths:
+         ! --------------------
+      hu_n(:,:) = 0._wp                        ! Ocean depth at U-points
+      hv_n(:,:) = 0._wp                        ! Ocean depth at V-points
+      DO jk = 1, jpkm1
+         hu_n(:,:) = hu_n(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+         hv_n(:,:) = hv_n(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !                                        ! Inverse of the local depth
+      r1_hu_n(:,:) = ssumask(:,:) / ( hu_n(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_n(:,:) = ssvmask(:,:) / ( hv_n(:,:) + 1._wp - ssvmask(:,:) )
+
+
+      ! 2) BEFORE fields:
+      !------------------
+      IF (.NOT.(lk_agrif_fstep.AND.(neuler==0) )) THEN
+         !
+         ! Vertical scale factor interpolations
+         ! ------------------------------------
+         CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:),  'U'  )
+         CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:),  'V'  )
+
+         CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+         CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+         ! Update total depths:
+         ! --------------------
+         hu_b(:,:) = 0._wp                     ! Ocean depth at U-points
+         hv_b(:,:) = 0._wp                     ! Ocean depth at V-points
+         DO jk = 1, jpkm1
+            hu_b(:,:) = hu_b(:,:) + e3u_b(:,:,jk) * umask(:,:,jk)
+            hv_b(:,:) = hv_b(:,:) + e3v_b(:,:,jk) * vmask(:,:,jk)
+         END DO
+         !                                     ! Inverse of the local depth
+         r1_hu_b(:,:) = ssumask(:,:) / ( hu_b(:,:) + 1._wp - ssumask(:,:) )
+         r1_hv_b(:,:) = ssvmask(:,:) / ( hv_b(:,:) + 1._wp - ssvmask(:,:) )
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_update_UVF
+
+#if defined key_vertical
+
+   SUBROUTINE updateTS( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!----------------------------------------------------------------------
+      !!           *** ROUTINE updateT ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      !!
+      INTEGER :: ji,jj,jk,jn
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk,n1:n2) :: tabres_child
+      REAL(wp) :: h_in(k1:k2)
+      REAL(wp) :: h_out(1:jpk)
+      INTEGER  :: N_in, N_out
+      REAL(wp) :: zrho_xy, h_diff
+      REAL(wp) :: tabin(k1:k2,n1:n2)
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         AGRIF_SpecialValue = -999._wp
+         zrho_xy = Agrif_rhox() * Agrif_rhoy() 
+         DO jn = n1,n2-1
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     tabres(ji,jj,jk,jn) = (tsn(ji,jj,jk,jn) * e3t_n(ji,jj,jk) ) &
+                                           * tmask(ji,jj,jk) + (tmask(ji,jj,jk)-1)*999._wp
+                  END DO
+               END DO
+            END DO
+         END DO
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,n2) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) &
+                                           + (tmask(ji,jj,jk)-1)*999._wp
+               END DO
+            END DO
+         END DO
+      ELSE
+         tabres_child(:,:,:,:) = 0.
+         AGRIF_SpecialValue = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of child grid
+                  IF (tabres(ji,jj,jk,n2) == 0  ) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = tabres(ji,jj,jk,n1:n2-1)/tabres(ji,jj,jk,n2)
+                  h_in(N_in) = tabres(ji,jj,jk,n2)
+               ENDDO
+               N_out = 0
+               DO jk=1,jpk ! jpk of parent grid
+                  IF (tmask(ji,jj,jk) < -900) EXIT ! TODO: Will not work with ISF
+                  N_out = N_out + 1
+                  h_out(N_out) = e3t_n(ji,jj,jk) 
+               ENDDO
+               IF (N_in > 0) THEN !Remove this?
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  IF (h_diff < -1.e-4) THEN
+                     print *,'CHECK YOUR bathy T points ...',ji,jj,h_diff,sum(h_in(1:N_in)),sum(h_out(1:N_out))
+                     print *,h_in(1:N_in)
+                     print *,h_out(1:N_out)
+                     STOP
+                  ENDIF
+                  DO jn=n1,n2-1
+                     CALL reconstructandremap(tabin(1:N_in,jn),h_in(1:N_in),tabres_child(ji,jj,1:N_out,jn),h_out(1:N_out),N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+            ! Add asselin part
+            DO jn = n1,n2-1
+               DO jk=1,jpk
+                  DO jj=j1,j2
+                     DO ji=i1,i2
+                        IF( tabres_child(ji,jj,jk,jn) .NE. 0. ) THEN
+                           tsb(ji,jj,jk,jn) = tsb(ji,jj,jk,jn) & 
+                                 & + atfp * ( tabres_child(ji,jj,jk,jn) &
+                                 &          - tsn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDIF
+         DO jn = n1,n2-1
+            DO jk=1,jpk
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     IF( tabres_child(ji,jj,jk,jn) .NE. 0. ) THEN 
+                        tsn(ji,jj,jk,jn) = tabres_child(ji,jj,jk,jn) * tmask(ji,jj,jk)
+                     END IF
+                  END DO
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE updateTS
+
+# else
+
+   SUBROUTINE updateTS( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateT ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      !!
+      INTEGER :: ji,jj,jk,jn
+      REAL(wp) :: ztb, ztnu, ztno
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         DO jn = 1,jpts
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+!> jc tmp
+                     tabres(ji,jj,jk,jn) = tsn(ji,jj,jk,jn)  * e3t_n(ji,jj,jk) / e3t_0(ji,jj,jk)
+!                     tabres(ji,jj,jk,jn) = tsn(ji,jj,jk,jn)  * e3t_n(ji,jj,jk)
+!< jc tmp
+                  END DO
+               END DO
+            END DO
+         END DO
+      ELSE
+!> jc tmp
+         DO jn = 1,jpts
+            tabres(i1:i2,j1:j2,k1:k2,jn) =  tabres(i1:i2,j1:j2,k1:k2,jn) * e3t_0(i1:i2,j1:j2,k1:k2) &
+                                         & * tmask(i1:i2,j1:j2,k1:k2)
+         ENDDO
+!< jc tmp
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+            ! Add asselin part
+            DO jn = 1,jpts
+               DO jk = k1, k2
+                  DO jj = j1, j2
+                     DO ji = i1, i2
+                        IF( tabres(ji,jj,jk,jn) /= 0._wp ) THEN
+                           ztb  = tsb(ji,jj,jk,jn) * e3t_b(ji,jj,jk) ! fse3t_b prior update should be used
+                           ztnu = tabres(ji,jj,jk,jn)
+                           ztno = tsn(ji,jj,jk,jn) * e3t_a(ji,jj,jk)
+                           tsb(ji,jj,jk,jn) = ( ztb + atfp * ( ztnu - ztno) )  & 
+                                     &        * tmask(ji,jj,jk) / e3t_b(ji,jj,jk)
+                        ENDIF
+                     END DO
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         DO jn = 1,jpts
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     IF( tabres(ji,jj,jk,jn) /= 0._wp ) THEN 
+                        tsn(ji,jj,jk,jn) = tabres(ji,jj,jk,jn) / e3t_n(ji,jj,jk)
+                     END IF
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            tsb(i1:i2,j1:j2,k1:k2,1:jpts)  = tsn(i1:i2,j1:j2,k1:k2,1:jpts)
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE updateTS
+
+# endif
+
+# if defined key_vertical
+
+   SUBROUTINE updateu( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateu ***
+      !!---------------------------------------------
+      INTEGER                                     , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      !
+      INTEGER ::   ji, jj, jk
+      REAL(wp)::   zrhoy
+! VERTICAL REFINEMENT BEGIN
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: tabres_child
+      REAL(wp) :: h_in(k1:k2)
+      REAL(wp) :: h_out(1:jpk)
+      INTEGER  :: N_in, N_out
+      REAL(wp) :: h_diff, excess, thick
+      REAL(wp) :: tabin(k1:k2)
+! VERTICAL REFINEMENT END
+      !!---------------------------------------------
+      ! 
+      IF( before ) THEN
+         zrhoy = Agrif_Rhoy()
+         AGRIF_SpecialValue = -999._wp
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = zrhoy * e2u(ji,jj) * e3u_n(ji,jj,jk) * umask(ji,jj,jk) * un(ji,jj,jk)  &
+                                       + (umask(ji,jj,jk)-1)*999._wp
+                  tabres(ji,jj,jk,2) = zrhoy * umask(ji,jj,jk) * e2u(ji,jj) * e3u_n(ji,jj,jk)  &
+                                       + (umask(ji,jj,jk)-1)*999._wp
+               END DO
+            END DO
+         END DO
+      ELSE
+         tabres_child(:,:,:) = 0.
+         AGRIF_SpecialValue = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               h_in(:) = 0._wp
+               tabin(:) = 0._wp
+               DO jk=k1,k2 !k2=jpk of child grid
+                  IF( tabres(ji,jj,jk,2) < -900) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = tabres(ji,jj,jk,1)/tabres(ji,jj,jk,2)
+                  h_in(N_in) = tabres(ji,jj,jk,2)/e2u(ji,jj)
+               ENDDO
+               N_out = 0
+               DO jk=1,jpk
+                  IF (umask(ji,jj,jk) == 0) EXIT
+                  N_out = N_out + 1
+                  h_out(N_out) = e3u_n(ji,jj,jk)
+               ENDDO
+               IF (N_in * N_out > 0) THEN
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  IF (h_diff < -1.e-4) THEN
+!Even if bathy at T points match it's possible for the U points to be deeper in the child grid. 
+!In this case we need to move transport from the child grid cells below bed of parent grid into the bottom cell.
+                     excess = 0._wp
+                     DO jk=N_in,1,-1
+                        thick = MIN(-1*h_diff, h_in(jk))
+                        excess = excess + tabin(jk)*thick*e2u(ji,jj)
+                        tabin(jk) = tabin(jk)*(1. - thick/h_in(jk))
+                        h_diff = h_diff + thick
+                        IF ( h_diff == 0) THEN
+                           N_in = jk
+                           h_in(jk) = h_in(jk) - thick
+                           EXIT
+                        ENDIF
+                     ENDDO
+                  ENDIF
+                  CALL reconstructandremap(tabin(1:N_in),h_in(1:N_in),tabres_child(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+                  tabres_child(ji,jj,N_out) = tabres_child(ji,jj,N_out) + excess/(e2u(ji,jj)*h_out(N_out))
+               ENDIF
+            ENDDO
+         ENDDO
+
+         DO jk=1,jpk
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
+                     ub(ji,jj,jk) = ub(ji,jj,jk) & 
+                           & + atfp * ( tabres_child(ji,jj,jk) - un(ji,jj,jk) ) * umask(ji,jj,jk)
+                  ENDIF
+                  !
+                  un(ji,jj,jk) = tabres_child(ji,jj,jk) * umask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE updateu
+
+#else
+
+   SUBROUTINE updateu( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateu ***
+      !!---------------------------------------------
+      INTEGER                               , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      !
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zrhoy, zub, zunu, zuno
+      !!---------------------------------------------
+      ! 
+      IF( before ) THEN
+         zrhoy = Agrif_Rhoy()
+         DO jk = k1, k2
+            tabres(i1:i2,j1:j2,jk,1) = zrhoy * e2u(i1:i2,j1:j2) * e3u_n(i1:i2,j1:j2,jk) * un(i1:i2,j1:j2,jk)
+         END DO
+      ELSE
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = tabres(ji,jj,jk,1) * r1_e2u(ji,jj) 
+                  !
+                  IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
+                     zub  = ub(ji,jj,jk) * e3u_b(ji,jj,jk)  ! fse3t_b prior update should be used
+                     zuno = un(ji,jj,jk) * e3u_a(ji,jj,jk)
+                     zunu = tabres(ji,jj,jk,1)
+                     ub(ji,jj,jk) = ( zub + atfp * ( zunu - zuno) ) &      
+                                    & * umask(ji,jj,jk) / e3u_b(ji,jj,jk)
+                  ENDIF
+                  !
+                  un(ji,jj,jk) = tabres(ji,jj,jk,1) * umask(ji,jj,jk) / e3u_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            ub(i1:i2,j1:j2,k1:k2)  = un(i1:i2,j1:j2,k1:k2)
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE updateu
+
+# endif
+
+   SUBROUTINE correct_u_bdy( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before, nb, ndir )
+      !!---------------------------------------------
+      !!           *** ROUTINE correct_u_bdy ***
+      !!---------------------------------------------
+      INTEGER                                     , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      INTEGER                                     , INTENT(in)    :: nb, ndir
+      !!
+      LOGICAL :: western_side, eastern_side 
+      !
+      INTEGER  :: jj, jk
+      REAL(wp) :: zcor
+      !!---------------------------------------------
+      ! 
+      IF( .NOT.before ) THEN
+         !
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         !
+         IF (western_side) THEN
+            DO jj=j1,j2
+               zcor = un_b(i1-1,jj) * hu_a(i1-1,jj) * r1_hu_n(i1-1,jj) - un_b(i1-1,jj)
+               un_b(i1-1,jj) = un_b(i1-1,jj) + zcor
+               DO jk=1,jpkm1
+                  un(i1-1,jj,jk) = un(i1-1,jj,jk) + zcor * umask(i1-1,jj,jk)
+               END DO 
+            END DO
+         ENDIF
+         !
+         IF (eastern_side) THEN
+            DO jj=j1,j2
+               zcor = un_b(i2+1,jj) * hu_a(i2+1,jj) * r1_hu_n(i2+1,jj) - un_b(i2+1,jj)
+               un_b(i2+1,jj) = un_b(i2+1,jj) + zcor
+               DO jk=1,jpkm1
+                  un(i2+1,jj,jk) = un(i2+1,jj,jk) + zcor * umask(i2+1,jj,jk)
+               END DO 
+            END DO
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE correct_u_bdy
+
+# if  defined key_vertical
+
+   SUBROUTINE updatev( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updatev ***
+      !!---------------------------------------------
+      INTEGER                                     , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zrhox
+! VERTICAL REFINEMENT BEGIN
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk) :: tabres_child
+      REAL(wp) :: h_in(k1:k2)
+      REAL(wp) :: h_out(1:jpk)
+      INTEGER :: N_in, N_out
+      REAL(wp) :: h_diff, excess, thick
+      REAL(wp) :: tabin(k1:k2)
+! VERTICAL REFINEMENT END
+      !!---------------------------------------------      
+      !
+      IF( before ) THEN
+         zrhox = Agrif_Rhox()
+         AGRIF_SpecialValue = -999._wp
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = zrhox * e1v(ji,jj) * e3v_n(ji,jj,jk) * vmask(ji,jj,jk) * vn(ji,jj,jk) &
+                                       + (vmask(ji,jj,jk)-1)*999._wp
+                  tabres(ji,jj,jk,2) = vmask(ji,jj,jk) * zrhox * e1v(ji,jj) * e3v_n(ji,jj,jk) &
+                                       + (vmask(ji,jj,jk)-1)*999._wp
+               END DO
+            END DO
+         END DO
+      ELSE
+         tabres_child(:,:,:) = 0.
+         AGRIF_SpecialValue = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2
+                  IF (tabres(ji,jj,jk,2) < -900) EXIT
+                  N_in = N_in + 1
+                  tabin(jk) = tabres(ji,jj,jk,1)/tabres(ji,jj,jk,2)
+                  h_in(N_in) = tabres(ji,jj,jk,2)/e1v(ji,jj)
+               ENDDO
+               N_out = 0
+               DO jk=1,jpk
+                  IF (vmask(ji,jj,jk) == 0) EXIT
+                  N_out = N_out + 1
+                  h_out(N_out) = e3v_n(ji,jj,jk)
+               ENDDO
+               IF (N_in * N_out > 0) THEN
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  IF (h_diff < -1.e-4) then
+!Even if bathy at T points match it's possible for the U points to be deeper in the child grid. 
+!In this case we need to move transport from the child grid cells below bed of parent grid into the bottom cell.
+                     excess = 0._wp
+                     DO jk=N_in,1,-1
+                        thick = MIN(-1*h_diff, h_in(jk))
+                        excess = excess + tabin(jk)*thick*e2u(ji,jj)
+                        tabin(jk) = tabin(jk)*(1. - thick/h_in(jk))
+                        h_diff = h_diff + thick
+                        IF ( h_diff == 0) THEN
+                           N_in = jk
+                           h_in(jk) = h_in(jk) - thick
+                           EXIT
+                        ENDIF
+                     ENDDO
+                  ENDIF
+                  CALL reconstructandremap(tabin(1:N_in),h_in(1:N_in),tabres_child(ji,jj,1:N_out),h_out(1:N_out),N_in,N_out)
+                  tabres_child(ji,jj,N_out) = tabres_child(ji,jj,N_out) + excess/(e1v(ji,jj)*h_out(N_out))
+               ENDIF
+            ENDDO
+         ENDDO
+
+         DO jk=1,jpk
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  !
+                  IF( .NOT.(lk_agrif_fstep.AND.(neuler==0)) ) THEN ! Add asselin part
+                     vb(ji,jj,jk) = vb(ji,jj,jk) & 
+                           & + atfp * ( tabres_child(ji,jj,jk) - vn(ji,jj,jk) ) * vmask(ji,jj,jk)
+                  ENDIF
+                  !
+                  vn(ji,jj,jk) = tabres_child(ji,jj,jk) * vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE updatev
+
+# else
+
+   SUBROUTINE updatev( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before)
+      !!---------------------------------------------
+      !!           *** ROUTINE updatev ***
+      !!---------------------------------------------
+      INTEGER                                     , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      !
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zrhox, zvb, zvnu, zvno
+      !!---------------------------------------------      
+      !
+      IF (before) THEN
+         zrhox = Agrif_Rhox()
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = zrhox * e1v(ji,jj) * e3v_n(ji,jj,jk) * vn(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = tabres(ji,jj,jk,1) * r1_e1v(ji,jj)
+                  !
+                  IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
+                     zvb  = vb(ji,jj,jk) * e3v_b(ji,jj,jk) ! fse3t_b prior update should be used
+                     zvno = vn(ji,jj,jk) * e3v_a(ji,jj,jk)
+                     zvnu = tabres(ji,jj,jk,1)
+                     vb(ji,jj,jk) = ( zvb + atfp * ( zvnu - zvno) ) &      
+                                    & * vmask(ji,jj,jk) / e3v_b(ji,jj,jk)
+                  ENDIF
+                  !
+                  vn(ji,jj,jk) = tabres(ji,jj,jk,1) * vmask(ji,jj,jk) / e3v_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            vb(i1:i2,j1:j2,k1:k2)  = vn(i1:i2,j1:j2,k1:k2)
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE updatev
+
+# endif
+
+   SUBROUTINE correct_v_bdy( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before, nb, ndir )
+      !!---------------------------------------------
+      !!           *** ROUTINE correct_u_bdy ***
+      !!---------------------------------------------
+      INTEGER                                     , INTENT(in   ) :: i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL                                     , INTENT(in   ) :: before
+      INTEGER                                     , INTENT(in)    :: nb, ndir
+      !!
+      LOGICAL :: southern_side, northern_side 
+      !
+      INTEGER  :: ji, jk
+      REAL(wp) :: zcor
+      !!---------------------------------------------
+      ! 
+      IF( .NOT.before ) THEN
+         !
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !
+         IF (southern_side) THEN
+            DO ji=i1,i2
+               zcor = vn_b(ji,j1-1) * hv_a(ji,j1-1) * r1_hv_n(ji,j1-1) - vn_b(ji,j1-1)
+               vn_b(ji,j1-1) = vn_b(ji,j1-1) + zcor
+               DO jk=1,jpkm1
+                  vn(ji,j1-1,jk) = vn(ji,j1-1,jk) + zcor * vmask(ji,j1-1,jk)
+               END DO 
+            END DO
+         ENDIF
+         !
+         IF (northern_side) THEN
+            DO ji=i1,i2
+               zcor = vn_b(ji,j2+1) * hv_a(ji,j2+1) * r1_hv_n(ji,j2+1) - vn_b(ji,j2+1)
+               vn_b(ji,j2+1) = vn_b(ji,j2+1) + zcor
+               DO jk=1,jpkm1
+                  vn(ji,j2+1,jk) = vn(ji,j2+1,jk) + zcor * vmask(ji,j2+1,jk)
+               END DO 
+            END DO
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE correct_v_bdy
+
+
+   SUBROUTINE updateu2d( tabres, i1, i2, j1, j2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateu2d ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   tabres
+      LOGICAL                         , INTENT(in   ) ::   before
+      !! 
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zrhoy
+      REAL(wp) :: zcorr
+      !!---------------------------------------------
+      !
+      IF( before ) THEN
+         zrhoy = Agrif_Rhoy()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = zrhoy * un_b(ji,jj) * hu_n(ji,jj) * e2u(ji,jj)
+            END DO
+         END DO
+      ELSE
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) =  tabres(ji,jj) * r1_e2u(ji,jj)  
+               !    
+               ! Update "now" 3d velocities:
+               spgu(ji,jj) = 0._wp
+               DO jk=1,jpkm1
+                  spgu(ji,jj) = spgu(ji,jj) + e3u_n(ji,jj,jk) * un(ji,jj,jk)
+               END DO
+               !
+               zcorr = (tabres(ji,jj) - spgu(ji,jj)) * r1_hu_n(ji,jj)
+               DO jk=1,jpkm1              
+                  un(ji,jj,jk) = un(ji,jj,jk) + zcorr * umask(ji,jj,jk)           
+               END DO
+               !
+               ! Update barotropic velocities:
+               IF ( .NOT.ln_dynspg_ts .OR. (ln_dynspg_ts.AND.(.NOT.ln_bt_fw)) ) THEN
+                  IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
+                     zcorr = (tabres(ji,jj) - un_b(ji,jj) * hu_a(ji,jj)) * r1_hu_b(ji,jj)
+                     ub_b(ji,jj) = ub_b(ji,jj) + atfp * zcorr * umask(ji,jj,1)
+                  END IF
+               ENDIF    
+               un_b(ji,jj) = tabres(ji,jj) * r1_hu_n(ji,jj) * umask(ji,jj,1)
+               !       
+               ! Correct "before" velocities to hold correct bt component:
+               spgu(ji,jj) = 0.e0
+               DO jk=1,jpkm1
+                  spgu(ji,jj) = spgu(ji,jj) + e3u_b(ji,jj,jk) * ub(ji,jj,jk)
+               END DO
+               !
+               zcorr = ub_b(ji,jj) - spgu(ji,jj) * r1_hu_b(ji,jj)
+               DO jk=1,jpkm1              
+                  ub(ji,jj,jk) = ub(ji,jj,jk) + zcorr * umask(ji,jj,jk)           
+               END DO
+               !
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            ub_b(i1:i2,j1:j2)  = un_b(i1:i2,j1:j2)
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE updateu2d
+
+
+   SUBROUTINE updatev2d( tabres, i1, i2, j1, j2, before )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE updatev2d ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   tabres
+      LOGICAL                         , INTENT(in   ) ::   before
+      ! 
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zrhox, zcorr
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         zrhox = Agrif_Rhox()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = zrhox * vn_b(ji,jj) * hv_n(ji,jj) * e1v(ji,jj) 
+            END DO
+         END DO
+      ELSE
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) =  tabres(ji,jj) * r1_e1v(ji,jj)  
+               !    
+               ! Update "now" 3d velocities:
+               spgv(ji,jj) = 0.e0
+               DO jk=1,jpkm1
+                  spgv(ji,jj) = spgv(ji,jj) + e3v_n(ji,jj,jk) * vn(ji,jj,jk)
+               END DO
+               !
+               zcorr = (tabres(ji,jj) - spgv(ji,jj)) * r1_hv_n(ji,jj)
+               DO jk=1,jpkm1              
+                  vn(ji,jj,jk) = vn(ji,jj,jk) + zcorr * vmask(ji,jj,jk)           
+               END DO
+               !
+               ! Update barotropic velocities:
+               IF ( .NOT.ln_dynspg_ts .OR. (ln_dynspg_ts.AND.(.NOT.ln_bt_fw)) ) THEN
+                  IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN ! Add asselin part
+                     zcorr = (tabres(ji,jj) - vn_b(ji,jj) * hv_a(ji,jj)) * r1_hv_b(ji,jj)
+                     vb_b(ji,jj) = vb_b(ji,jj) + atfp * zcorr * vmask(ji,jj,1)
+                  END IF
+               ENDIF              
+               vn_b(ji,jj) = tabres(ji,jj) * r1_hv_n(ji,jj) * vmask(ji,jj,1)
+               !       
+               ! Correct "before" velocities to hold correct bt component:
+               spgv(ji,jj) = 0.e0
+               DO jk=1,jpkm1
+                  spgv(ji,jj) = spgv(ji,jj) + e3v_b(ji,jj,jk) * vb(ji,jj,jk)
+               END DO
+               !
+               zcorr = vb_b(ji,jj) - spgv(ji,jj) * r1_hv_b(ji,jj)
+               DO jk=1,jpkm1              
+                  vb(ji,jj,jk) = vb(ji,jj,jk) + zcorr * vmask(ji,jj,jk)           
+               END DO
+               !
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            vb_b(i1:i2,j1:j2)  = vn_b(i1:i2,j1:j2)
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE updatev2d
+
+
+   SUBROUTINE updateSSH( tabres, i1, i2, j1, j2, before )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE updateSSH ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   tabres
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      INTEGER :: ji, jj
+      !!----------------------------------------------------------------------
+      ! 
+      IF( before ) THEN
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = sshn(ji,jj)
+            END DO
+         END DO
+      ELSE
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  sshb(ji,jj) =   sshb(ji,jj) &
+                        & + atfp * ( tabres(ji,jj) - sshn(ji,jj) ) * tmask(ji,jj,1)
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jj=j1,j2
+            DO ji=i1,i2
+               sshn(ji,jj) = tabres(ji,jj) * tmask(ji,jj,1)
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            sshb(i1:i2,j1:j2)  = sshn(i1:i2,j1:j2)
+         ENDIF
+         !
+
+      ENDIF
+      !
+   END SUBROUTINE updateSSH
+
+
+   SUBROUTINE updateub2b( tabres, i1, i2, j1, j2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateub2b ***
+      !!----------------------------------------------------------------------
+      INTEGER                            , INTENT(in) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   tabres
+      LOGICAL                            , INTENT(in) ::   before
+      !!
+      INTEGER :: ji, jj
+      REAL(wp) :: zrhoy, za1, zcor
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         zrhoy = Agrif_Rhoy()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = ub2_i_b(ji,jj) * e2u(ji,jj)
+            END DO
+         END DO
+         tabres = zrhoy * tabres
+      ELSE
+         ! 
+         tabres(i1:i2,j1:j2) = tabres(i1:i2,j1:j2) * r1_e2u(i1:i2,j1:j2)
+         !
+         za1 = 1._wp / REAL(Agrif_rhot(), wp)
+         DO jj=j1,j2
+            DO ji=i1,i2
+               zcor=tabres(ji,jj) - ub2_b(ji,jj)
+               ! Update time integrated fluxes also in case of multiply nested grids:
+               ub2_i_b(ji,jj) = ub2_i_b(ji,jj) + za1 * zcor 
+               ! Update corrective fluxes:
+               un_bf(ji,jj)  = un_bf(ji,jj) + zcor
+               ! Update half step back fluxes:
+               ub2_b(ji,jj) = tabres(ji,jj)
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE updateub2b
+
+   SUBROUTINE reflux_sshu( tabres, i1, i2, j1, j2, before, nb, ndir )
+      !!---------------------------------------------
+      !!          *** ROUTINE reflux_sshu ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb, ndir
+      !!
+      LOGICAL :: western_side, eastern_side 
+      INTEGER :: ji, jj
+      REAL(wp) :: zrhoy, za1, zcor
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         zrhoy = Agrif_Rhoy()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = ub2_i_b(ji,jj) * e2u(ji,jj)
+            END DO
+         END DO
+         tabres = zrhoy * tabres
+      ELSE
+         ! 
+         tabres(i1:i2,j1:j2) = tabres(i1:i2,j1:j2) * r1_e2u(i1:i2,j1:j2)
+         !
+         western_side  = (nb == 1).AND.(ndir == 1)
+         eastern_side  = (nb == 1).AND.(ndir == 2)
+         !
+         IF (western_side) THEN
+            DO jj=j1,j2
+               zcor = rdt * r1_e1e2t(i1  ,jj) * e2u(i1,jj) * (ub2_b(i1,jj)-tabres(i1,jj)) 
+               sshn(i1  ,jj) = sshn(i1  ,jj) + zcor
+               IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) sshb(i1  ,jj) = sshb(i1  ,jj) + atfp * zcor
+            END DO
+         ENDIF
+         IF (eastern_side) THEN
+            DO jj=j1,j2
+               zcor = - rdt * r1_e1e2t(i2+1,jj) * e2u(i2,jj) * (ub2_b(i2,jj)-tabres(i2,jj))
+               sshn(i2+1,jj) = sshn(i2+1,jj) + zcor
+               IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) sshb(i2+1,jj) = sshb(i2+1,jj) + atfp * zcor
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE reflux_sshu
+
+   SUBROUTINE updatevb2b( tabres, i1, i2, j1, j2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updatevb2b ***
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) ::   tabres
+      LOGICAL                         , INTENT(in   ) ::   before
+      !!
+      INTEGER :: ji, jj
+      REAL(wp) :: zrhox, za1, zcor
+      !!---------------------------------------------
+      !
+      IF( before ) THEN
+         zrhox = Agrif_Rhox()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = vb2_i_b(ji,jj) * e1v(ji,jj) 
+            END DO
+         END DO
+         tabres = zrhox * tabres
+      ELSE
+         ! 
+         tabres(i1:i2,j1:j2) = tabres(i1:i2,j1:j2) * r1_e1v(i1:i2,j1:j2)
+         !
+         za1 = 1._wp / REAL(Agrif_rhot(), wp)
+         DO jj=j1,j2
+            DO ji=i1,i2
+               zcor=tabres(ji,jj) - vb2_b(ji,jj)
+               ! Update time integrated fluxes also in case of multiply nested grids:
+               vb2_i_b(ji,jj) = vb2_i_b(ji,jj) + za1 * zcor 
+               ! Update corrective fluxes:
+               vn_bf(ji,jj)  = vn_bf(ji,jj) + zcor
+               ! Update half step back fluxes:
+               vb2_b(ji,jj) = tabres(ji,jj)
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE updatevb2b
+
+   SUBROUTINE reflux_sshv( tabres, i1, i2, j1, j2, before, nb, ndir )
+      !!---------------------------------------------
+      !!          *** ROUTINE reflux_sshv ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1, i2, j1, j2
+      REAL(wp), DIMENSION(i1:i2,j1:j2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      INTEGER, INTENT(in) :: nb, ndir
+      !!
+      LOGICAL :: southern_side, northern_side 
+      INTEGER :: ji, jj
+      REAL(wp) :: zrhox, za1, zcor
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         zrhox = Agrif_Rhox()
+         DO jj=j1,j2
+            DO ji=i1,i2
+               tabres(ji,jj) = vb2_i_b(ji,jj) * e1v(ji,jj) 
+            END DO
+         END DO
+         tabres = zrhox * tabres
+      ELSE
+         ! 
+         tabres(i1:i2,j1:j2) = tabres(i1:i2,j1:j2) * r1_e1v(i1:i2,j1:j2)
+         !
+         southern_side = (nb == 2).AND.(ndir == 1)
+         northern_side = (nb == 2).AND.(ndir == 2)
+         !
+         IF (southern_side) THEN
+            DO ji=i1,i2
+               zcor = rdt * r1_e1e2t(ji,j1  ) * e1v(ji,j1  ) * (vb2_b(ji,j1)-tabres(ji,j1))
+               sshn(ji,j1  ) = sshn(ji,j1  ) + zcor
+               IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) sshb(ji,j1  ) = sshb(ji,j1) + atfp * zcor
+            END DO
+         ENDIF
+         IF (northern_side) THEN               
+            DO ji=i1,i2
+               zcor = - rdt * r1_e1e2t(ji,j2+1) * e1v(ji,j2  ) * (vb2_b(ji,j2)-tabres(ji,j2))
+               sshn(ji,j2+1) = sshn(ji,j2+1) + zcor
+               IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) sshb(ji,j2+1) = sshb(ji,j2+1) + atfp * zcor
+            END DO
+         ENDIF
+         ! 
+      ENDIF
+      !
+   END SUBROUTINE reflux_sshv
+
+   SUBROUTINE update_scales( tabres, i1, i2, j1, j2, k1, k2, n1,n2, before )
+      !
+      ! ====>>>>>>>>>>    currently not used
+      !
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateT ***
+      !!----------------------------------------------------------------------
+      INTEGER                                    , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   tabres
+      LOGICAL                                    , INTENT(in   ) ::   before
+      !!
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: ztemp
+      !!----------------------------------------------------------------------
+
+      IF (before) THEN
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,1) = e1t(ji,jj)*e2t(ji,jj)*tmask(ji,jj,jk)
+                  tabres(ji,jj,jk,2) = e1t(ji,jj)*tmask(ji,jj,jk)
+                  tabres(ji,jj,jk,3) = e2t(ji,jj)*tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         tabres(:,:,:,1)=tabres(:,:,:,1)*Agrif_Rhox()*Agrif_Rhoy()
+         tabres(:,:,:,2)=tabres(:,:,:,2)*Agrif_Rhox()
+         tabres(:,:,:,3)=tabres(:,:,:,3)*Agrif_Rhoy()
+      ELSE
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  IF( tabres(ji,jj,jk,1) .NE. 0. ) THEN 
+                     print *,'VAL = ',ji,jj,jk,tabres(ji,jj,jk,1),e1t(ji,jj)*e2t(ji,jj)*tmask(ji,jj,jk)
+                     print *,'VAL2 = ',ji,jj,jk,tabres(ji,jj,jk,2),e1t(ji,jj)*tmask(ji,jj,jk)
+                     print *,'VAL3 = ',ji,jj,jk,tabres(ji,jj,jk,3),e2t(ji,jj)*tmask(ji,jj,jk)
+                     ztemp = sqrt(tabres(ji,jj,jk,1)/(tabres(ji,jj,jk,2)*tabres(ji,jj,jk,3)))
+                     print *,'CORR = ',ztemp-1.
+                     print *,'NEW VALS = ',tabres(ji,jj,jk,2)*ztemp,tabres(ji,jj,jk,3)*ztemp, &
+                           tabres(ji,jj,jk,2)*ztemp*tabres(ji,jj,jk,3)*ztemp
+                     e1t(ji,jj) = tabres(ji,jj,jk,2)*ztemp
+                     e2t(ji,jj) = tabres(ji,jj,jk,3)*ztemp
+                  END IF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE update_scales
+
+
+   SUBROUTINE updateEN( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateen ***
+      !!----------------------------------------------------------------------
+      INTEGER                               , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                               , INTENT(in   ) ::   before
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         ptab (i1:i2,j1:j2,k1:k2) = en(i1:i2,j1:j2,k1:k2)
+      ELSE
+         en(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateEN
+
+
+   SUBROUTINE updateAVT( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateavt ***
+      !!----------------------------------------------------------------------
+      INTEGER                               , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                               , INTENT(in   ) ::   before
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN   ;   ptab (i1:i2,j1:j2,k1:k2) = avt_k(i1:i2,j1:j2,k1:k2)
+      ELSE                ;   avt_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateAVT
+
+
+   SUBROUTINE updateAVM( ptab, i1, i2, j1, j2, k1, k2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateavm ***
+      !!----------------------------------------------------------------------
+      INTEGER                               , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2), INTENT(inout) ::   ptab
+      LOGICAL                               , INTENT(in   ) ::   before
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN   ;   ptab (i1:i2,j1:j2,k1:k2) = avm_k(i1:i2,j1:j2,k1:k2)
+      ELSE                ;   avm_k(i1:i2,j1:j2,k1:k2) = ptab (i1:i2,j1:j2,k1:k2) 
+      ENDIF
+      !
+   END SUBROUTINE updateAVM
+
+   SUBROUTINE updatee3t(ptab_dum, i1, i2, j1, j2, k1, k2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updatee3t ***
+      !!---------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2) :: ptab_dum
+      INTEGER, INTENT(in) :: i1, i2, j1, j2, k1, k2
+      LOGICAL, INTENT(in) :: before
+      !
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: ptab
+      INTEGER :: ji,jj,jk
+      REAL(wp) :: zcoef
+      !!---------------------------------------------
+      !
+      IF (.NOT.before) THEN
+         !
+         ALLOCATE(ptab(i1:i2,j1:j2,1:jpk)) 
+         !
+         ! Update e3t from ssh (z* case only)
+         DO jk = 1, jpkm1
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  ptab(ji,jj,jk) = e3t_0(ji,jj,jk) * (1._wp + sshn(ji,jj) &
+                                     & *ssmask(ji,jj)/(ht_0(ji,jj)-1._wp + ssmask(ji,jj)))
+               END DO
+            END DO
+         END DO
+         !
+         ! 1) Updates at BEFORE time step:
+         ! -------------------------------
+         !
+         ! Save "old" scale factor (prior update) for subsequent asselin correction
+         ! of prognostic variables
+         e3t_a(i1:i2,j1:j2,1:jpkm1) = e3t_n(i1:i2,j1:j2,1:jpkm1)
+
+         ! One should also save e3t_b, but lacking of workspace...
+!         hdivn(i1:i2,j1:j2,1:jpkm1)   = e3t_b(i1:i2,j1:j2,1:jpkm1)
+
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0) )) THEN
+            DO jk = 1, jpkm1
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     e3t_b(ji,jj,jk) =  e3t_b(ji,jj,jk) &
+                           & + atfp * ( ptab(ji,jj,jk) - e3t_n(ji,jj,jk) )
+                  END DO
+               END DO
+            END DO
+            !
+            e3w_b  (i1:i2,j1:j2,1) = e3w_0(i1:i2,j1:j2,1) + e3t_b(i1:i2,j1:j2,1) - e3t_0(i1:i2,j1:j2,1)
+            gdepw_b(i1:i2,j1:j2,1) = 0.0_wp
+            gdept_b(i1:i2,j1:j2,1) = 0.5_wp * e3w_b(i1:i2,j1:j2,1)
+            !
+            DO jk = 2, jpk
+               DO jj = j1,j2
+                  DO ji = i1,i2            
+                     zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+                     e3w_b(ji,jj,jk)  = e3w_0(ji,jj,jk) + ( 1.0_wp - 0.5_wp * tmask(ji,jj,jk) ) *        & 
+                     &                                        ( e3t_b(ji,jj,jk-1) - e3t_0(ji,jj,jk-1) )  &
+                     &                                  +            0.5_wp * tmask(ji,jj,jk)   *        &
+                     &                                        ( e3t_b(ji,jj,jk  ) - e3t_0(ji,jj,jk  ) )
+                     gdepw_b(ji,jj,jk) = gdepw_b(ji,jj,jk-1) + e3t_b(ji,jj,jk-1)
+                     gdept_b(ji,jj,jk) =      zcoef  * ( gdepw_b(ji,jj,jk  ) + 0.5 * e3w_b(ji,jj,jk))  &
+                         &               + (1-zcoef) * ( gdept_b(ji,jj,jk-1) +       e3w_b(ji,jj,jk)) 
+                  END DO
+               END DO
+            END DO
+            !
+         ENDIF        
+         !
+         ! 2) Updates at NOW time step:
+         ! ----------------------------
+         !
+         ! Update vertical scale factor at T-points:
+         e3t_n(i1:i2,j1:j2,1:jpkm1) = ptab(i1:i2,j1:j2,1:jpkm1)
+         !
+         ! Update total depth:
+         ht_n(i1:i2,j1:j2) = 0._wp
+         DO jk = 1, jpkm1
+            ht_n(i1:i2,j1:j2) = ht_n(i1:i2,j1:j2) + e3t_n(i1:i2,j1:j2,jk) * tmask(i1:i2,j1:j2,jk)
+         END DO
+         !
+         ! Update vertical scale factor at W-points and depths:
+         e3w_n (i1:i2,j1:j2,1) = e3w_0(i1:i2,j1:j2,1) + e3t_n(i1:i2,j1:j2,1) - e3t_0(i1:i2,j1:j2,1)
+         gdept_n(i1:i2,j1:j2,1) = 0.5_wp * e3w_n(i1:i2,j1:j2,1)
+         gdepw_n(i1:i2,j1:j2,1) = 0.0_wp
+         gde3w_n(i1:i2,j1:j2,1) = gdept_n(i1:i2,j1:j2,1) - (ht_n(i1:i2,j1:j2)-ht_0(i1:i2,j1:j2)) ! Last term in the rhs is ssh
+         !
+         DO jk = 2, jpk
+            DO jj = j1,j2
+               DO ji = i1,i2            
+               zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+               e3w_n(ji,jj,jk)  = e3w_0(ji,jj,jk) + ( 1.0_wp - 0.5_wp * tmask(ji,jj,jk) ) * ( e3t_n(ji,jj,jk-1) - e3t_0(ji,jj,jk-1) )   &
+               &                                  +            0.5_wp * tmask(ji,jj,jk)   * ( e3t_n(ji,jj,jk  ) - e3t_0(ji,jj,jk  ) )
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                   &               + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk)) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - (ht_n(ji,jj)-ht_0(ji,jj)) ! Last term in the rhs is ssh
+               END DO
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            e3t_b (i1:i2,j1:j2,1:jpk)  = e3t_n (i1:i2,j1:j2,1:jpk)
+            e3w_b (i1:i2,j1:j2,1:jpk)  = e3w_n (i1:i2,j1:j2,1:jpk)
+            gdepw_b(i1:i2,j1:j2,1:jpk) = gdepw_n(i1:i2,j1:j2,1:jpk)
+            gdept_b(i1:i2,j1:j2,1:jpk) = gdept_n(i1:i2,j1:j2,1:jpk)
+         ENDIF
+         !
+         DEALLOCATE(ptab)
+      ENDIF
+      !
+   END SUBROUTINE updatee3t
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                          no AGRIF zoom
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_oce_update_empty
+      WRITE(*,*)  'agrif_oce_update : You should not have seen this print! error?'
+   END SUBROUTINE agrif_oce_update_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_oce_update
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_interp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_interp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_interp.F90	(revision 14097)
@@ -0,0 +1,279 @@
+MODULE agrif_top_interp
+   !!======================================================================
+   !!                   ***  MODULE  agrif_top_interp  ***
+   !! AGRIF: interpolation package for TOP
+   !!======================================================================
+   !! History :  2.0  !  ??? 
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!   'key_top'                                           on-line tracers
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE oce
+   USE dom_oce      
+   USE agrif_oce
+   USE agrif_top_sponge
+   USE par_trc
+   USE trc
+   !
+   USE lib_mpp     ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC Agrif_trc, interptrn
+
+  !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_trc
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE Agrif_trc  ***
+      !!----------------------------------------------------------------------
+      !
+      IF( Agrif_Root() )   RETURN
+      !
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .TRUE.
+      !
+      CALL Agrif_Bc_variable( trn_id, procname=interptrn )
+      Agrif_UseSpecialValue = .FALSE.
+      !
+   END SUBROUTINE Agrif_trc
+
+   SUBROUTINE interptrn( ptab, i1, i2, j1, j2, k1, k2, n1, n2, before, nb, ndir )
+      !!----------------------------------------------------------------------
+      !!                  *** ROUTINE interptrn ***
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   ptab
+      INTEGER                                     , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      LOGICAL                                     , INTENT(in   ) ::   before
+      INTEGER                                     , INTENT(in   ) ::   nb , ndir
+      !
+      INTEGER  ::   ji, jj, jk, jn, iref, jref, ibdy, jbdy   ! dummy loop indices
+      INTEGER  ::   imin, imax, jmin, jmax, N_in, N_out
+      REAL(wp) ::   zrho, z1, z2, z3, z4, z5, z6, z7
+      LOGICAL :: western_side, eastern_side,northern_side,southern_side
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk,n1:n2) :: ptab_child
+      REAL(wp), DIMENSION(k1:k2,n1:n2-1) :: tabin
+      REAL(wp), DIMENSION(k1:k2) :: h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      REAL(wp) :: h_diff
+
+      IF( before ) THEN         
+         DO jn = 1,jptra
+            DO jk=k1,k2
+               DO jj=j1,j2
+                 DO ji=i1,i2
+                       ptab(ji,jj,jk,jn) = trn(ji,jj,jk,jn)
+                 END DO
+              END DO
+           END DO
+        END DO
+
+# if defined key_vertical
+        DO jk=k1,k2
+           DO jj=j1,j2
+              DO ji=i1,i2
+                 ptab(ji,jj,jk,jptra+1) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) 
+              END DO
+           END DO
+        END DO
+# endif
+      ELSE 
+
+         western_side  = (nb == 1).AND.(ndir == 1)   ;   eastern_side  = (nb == 1).AND.(ndir == 2)
+         southern_side = (nb == 2).AND.(ndir == 1)   ;   northern_side = (nb == 2).AND.(ndir == 2)
+
+# if defined key_vertical              
+         DO jj=j1,j2
+            DO ji=i1,i2
+               iref = ji
+               jref = jj
+               if(western_side) iref=MAX(2,ji)
+               if(eastern_side) iref=MIN(nlci-1,ji)
+               if(southern_side) jref=MAX(2,jj)
+               if(northern_side) jref=MIN(nlcj-1,jj)
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of parent grid
+                  IF (ptab(ji,jj,jk,n2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = ptab(ji,jj,jk,n1:n2-1)
+                  h_in(N_in) = ptab(ji,jj,jk,n2)
+               END DO
+               N_out = 0
+               DO jk=1,jpk ! jpk of child grid
+                  IF (tmask(iref,jref,jk) == 0) EXIT 
+                  N_out = N_out + 1
+                  h_out(jk) = e3t_n(iref,jref,jk)
+               ENDDO
+               IF (N_in > 0) THEN
+                  DO jn=1,jptra
+                     call reconstructandremap(tabin(1:N_in,jn),h_in,ptab_child(ji,jj,1:N_out,jn),h_out,N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+# else
+         ptab_child(i1:i2,j1:j2,1:jpk,1:jptra) = ptab(i1:i2,j1:j2,1:jpk,1:jptra)
+# endif
+         !
+         DO jn=1, jptra
+            tra(i1:i2,j1:j2,1:jpk,jn)=ptab_child(i1:i2,j1:j2,1:jpk,jn)*tmask(i1:i2,j1:j2,1:jpk) 
+         END DO
+
+         IF ( .NOT.lk_agrif_clp ) THEN 
+            !
+            imin = i1 ; imax = i2
+            jmin = j1 ; jmax = j2
+            ! 
+            ! Remove CORNERS
+            IF( l_Southedge ) jmin = 2 + nbghostcells
+            IF( l_Northedge ) jmax = nlcj - nbghostcells - 1
+            IF( l_Westedge )  imin = 2 + nbghostcells
+            IF( l_Eastedge )  imax = nlci - nbghostcells - 1      
+            !
+            IF( eastern_side ) THEN
+               zrho = Agrif_Rhox()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !
+               ibdy = nlci-nbghostcells
+               DO jn = 1, jptra
+                  tra(ibdy+1,jmin:jmax,1:jpkm1,jn) = z1 * ptab_child(ibdy+1,jmin:jmax,1:jpkm1,jn) + z2 * ptab_child(ibdy,jmin:jmax,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO jj = jmin,jmax
+                        IF( umask(ibdy-1,jj,jk) == 0._wp ) THEN
+                           tra(ibdy,jj,jk,jn) = tra(ibdy+1,jj,jk,jn) * tmask(ibdy,jj,jk)
+                        ELSE
+                           tra(ibdy,jj,jk,jn)=(z4*tra(ibdy+1,jj,jk,jn)+z3*tra(ibdy-1,jj,jk,jn))*tmask(ibdy,jj,jk)
+                           IF( un(ibdy-1,jj,jk) > 0._wp ) THEN
+                              tra(ibdy,jj,jk,jn)=( z6*tra(ibdy-1,jj,jk,jn)+z5*tra(ibdy+1,jj,jk,jn) & 
+                                                 + z7*tra(ibdy-2,jj,jk,jn) ) * tmask(ibdy,jj,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tra(ibdy+1,jmin:jmax,1:jpkm1,jn) = ptab_child(ibdy+1,jmin:jmax,1:jpkm1,jn) * tmask(ibdy+1,jmin:jmax,1:jpkm1)
+               END DO
+            ENDIF
+            ! 
+            IF( northern_side ) THEN
+               zrho = Agrif_Rhoy()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !
+               jbdy = nlcj-nbghostcells         
+               DO jn = 1, jptra
+                  tra(imin:imax,jbdy+1,1:jpkm1,jn) = z1 * ptab_child(imin:imax,jbdy+1,1:jpkm1,jn) + z2 * ptab_child(imin:imax,jbdy,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO ji = imin,imax
+                        IF( vmask(ji,jbdy-1,jk) == 0._wp ) THEN
+                           tra(ji,jbdy,jk,jn) = tra(ji,jbdy+1,jk,jn) * tmask(ji,jbdy,jk)
+                        ELSE
+                           tra(ji,jbdy,jk,jn)=(z4*tra(ji,jbdy+1,jk,jn)+z3*tra(ji,jbdy-1,jk,jn))*tmask(ji,jbdy,jk)        
+                           IF (vn(ji,jbdy-1,jk) > 0._wp ) THEN
+                              tra(ji,jbdy,jk,jn)=( z6*tra(ji,jbdy-1,jk,jn)+z5*tra(ji,jbdy+1,jk,jn)  &
+                                                 + z7*tra(ji,jbdy-2,jk,jn) ) * tmask(ji,jbdy,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tra(imin:imax,jbdy+1,1:jpkm1,jn) = ptab_child(imin:imax,jbdy+1,1:jpkm1,jn) * tmask(imin:imax,jbdy+1,1:jpkm1)
+               END DO
+            ENDIF
+            !
+            IF( western_side ) THEN
+               zrho = Agrif_Rhox()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !    
+               ibdy = 1+nbghostcells       
+               DO jn = 1, jptra
+                  tra(ibdy-1,jmin:jmax,1:jpkm1,jn) = z1 * ptab_child(ibdy-1,jmin:jmax,1:jpkm1,jn) + z2 * ptab_child(ibdy,jmin:jmax,1:jpkm1,jn)
+                  DO jk = 1, jpkm1
+                     DO jj = jmin,jmax
+                        IF( umask(ibdy,jj,jk) == 0._wp ) THEN
+                           tra(ibdy,jj,jk,jn) = tra(ibdy-1,jj,jk,jn) * tmask(ibdy,jj,jk)
+                        ELSE
+                           tra(ibdy,jj,jk,jn)=(z4*tra(ibdy-1,jj,jk,jn)+z3*tra(ibdy+1,jj,jk,jn))*tmask(ibdy,jj,jk)        
+                           IF( un(ibdy,jj,jk) < 0._wp ) THEN
+                              tra(ibdy,jj,jk,jn)=( z6*tra(ibdy+1,jj,jk,jn)+z5*tra(ibdy-1,jj,jk,jn) &
+                                                 + z7*tra(ibdy+2,jj,jk,jn) ) * tmask(ibdy,jj,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tra(ibdy-1,jmin:jmax,1:jpkm1,jn) = ptab_child(ibdy-1,jmin:jmax,1:jpkm1,jn) * tmask(ibdy-1,jmin:jmax,1:jpkm1)
+               END DO
+            ENDIF
+            !
+            IF( southern_side ) THEN
+               zrho = Agrif_Rhoy()
+               z1 = ( zrho - 1._wp ) * 0.5_wp                    
+               z3 = ( zrho - 1._wp ) / ( zrho + 1._wp )         
+               z6 = 2._wp * ( zrho - 1._wp ) / ( zrho + 1._wp )
+               z7 =       - ( zrho - 1._wp ) / ( zrho + 3._wp )
+               z2 = 1._wp - z1 ; z4 = 1._wp - z3 ; z5 = 1._wp - z6 - z7
+               !  
+               jbdy=1+nbghostcells        
+               DO jn = 1, jptra
+                  tra(imin:imax,jbdy-1,1:jpkm1,jn) = z1 * ptab_child(imin:imax,jbdy-1,1:jpkm1,jn) + z2 * ptab_child(imin:imax,jbdy,1:jpkm1,jn)
+                  DO jk = 1, jpkm1      
+                     DO ji = imin,imax
+                        IF( vmask(ji,jbdy,jk) == 0._wp ) THEN
+                           tra(ji,jbdy,jk,jn)=tra(ji,jbdy-1,jk,jn) * tmask(ji,jbdy,jk)
+                        ELSE
+                           tra(ji,jbdy,jk,jn)=(z4*tra(ji,jbdy-1,jk,jn)+z3*tra(ji,jbdy+1,jk,jn))*tmask(ji,jbdy,jk)
+                           IF( vn(ji,jbdy,jk) < 0._wp ) THEN
+                              tra(ji,jbdy,jk,jn)=( z6*tra(ji,jbdy+1,jk,jn)+z5*tra(ji,jbdy-1,jk,jn) & 
+                                                 + z7*tra(ji,jbdy+2,jk,jn) ) * tmask(ji,jbdy,jk)
+                           ENDIF
+                        ENDIF
+                     END DO
+                  END DO
+                  ! Restore ghost points:
+                  tra(imin:imax,jbdy-1,1:jpkm1,jn) = ptab_child(imin:imax,jbdy-1,1:jpkm1,jn) * tmask(imin:imax,jbdy-1,1:jpkm1)
+               END DO
+            ENDIF
+            !
+         ENDIF
+
+      ENDIF
+      !
+   END SUBROUTINE interptrn
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                           no TOP AGRIF
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE Agrif_TOP_Interp_empty
+      !!---------------------------------------------
+      !!   *** ROUTINE agrif_Top_Interp_empty ***
+      !!---------------------------------------------
+      WRITE(*,*)  'agrif_top_interp : You should not have seen this print! error?'
+   END SUBROUTINE Agrif_TOP_Interp_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_top_interp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_sponge.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_sponge.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_sponge.F90	(revision 14097)
@@ -0,0 +1,181 @@
+#define SPONGE_TOP
+
+MODULE agrif_top_sponge
+   !!======================================================================
+   !!                ***  MODULE agrif_top_sponge  ***
+   !! AGRIF :   sponge layer pakage for passive tracers (TOP)
+   !!======================================================================
+   !! History :  2.0  ! 2006-08  (R. Benshila, L. Debreu)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_top
+   !!----------------------------------------------------------------------
+   !!   Agrif_Sponge_trc : 
+   !!   interptrn_sponge :  
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE par_trc
+   USE oce
+   USE trc
+   USE dom_oce
+   USE agrif_oce
+   USE agrif_oce_sponge
+   !
+   USE in_out_manager
+   USE lib_mpp
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC Agrif_Sponge_trc, interptrn_sponge
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_Sponge_trc
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE Agrif_Sponge_Trc ***
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zcoef   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+#if defined SPONGE_TOP
+!! Assume persistence 
+      zcoef = REAL(Agrif_rhot()-1,wp)/REAL(Agrif_rhot())
+      CALL Agrif_sponge
+      Agrif_SpecialValue    = 0._wp
+      Agrif_UseSpecialValue = .TRUE.
+      tabspongedone_trn     = .FALSE.
+      CALL Agrif_Bc_Variable( trn_sponge_id, calledweight=zcoef, procname=interptrn_sponge )
+      Agrif_UseSpecialValue = .FALSE.
+#endif
+      !
+   END SUBROUTINE Agrif_Sponge_Trc
+
+
+   SUBROUTINE interptrn_sponge( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE interptrn_sponge ***
+      !!----------------------------------------------------------------------
+      INTEGER                                     , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   tabres
+      LOGICAL                                     , INTENT(in   ) ::   before
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   zabe1, zabe2
+      REAL(wp), DIMENSION(i1:i2,j1:j2)             ::   ztu, ztv
+      REAL(wp), DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2) ::   trbdiff
+      ! vertical interpolation:
+      REAL(wp), DIMENSION(i1:i2,j1:j2,jpk,n1:n2) ::tabres_child
+      REAL(wp), DIMENSION(k1:k2,n1:n2-1) :: tabin
+      REAL(wp), DIMENSION(k1:k2) :: h_in
+      REAL(wp), DIMENSION(1:jpk) :: h_out
+      INTEGER :: N_in, N_out
+      REAL(wp) :: h_diff
+      !!----------------------------------------------------------------------
+      !
+      IF( before ) THEN
+         DO jn = 1, jptra
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     tabres(ji,jj,jk,jn) = trb(ji,jj,jk,jn)
+                  END DO
+               END DO
+            END DO
+         END DO
+
+# if defined key_vertical
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,jpts+1) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) 
+               END DO
+            END DO
+         END DO
+# endif
+      ELSE      
+# if defined key_vertical
+         tabres_child(:,:,:,:) = 0.
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of parent grid
+                  IF (tabres(ji,jj,jk,n2) == 0) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = tabres(ji,jj,jk,n1:n2-1)
+                  h_in(N_in) = tabres(ji,jj,jk,n2)
+               END DO
+               N_out = 0
+               DO jk=1,jpk ! jpk of child grid
+                  IF (tmask(ji,jj,jk) == 0) EXIT 
+                  N_out = N_out + 1
+                  h_out(jk) = e3t_n(ji,jj,jk) !Child grid scale factors. Could multiply by e1e2t here instead of division above
+               ENDDO
+               IF (N_in > 0) THEN
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  tabres(ji,jj,k2,:) = tabres(ji,jj,k2-1,:) !what is this line for?????
+                  DO jn=1,jptra
+                     call reconstructandremap(tabin(1:N_in,jn),h_in,tabres_child(ji,jj,1:N_out,jn),h_out,N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+# endif
+
+         DO jj=j1,j2
+            DO ji=i1,i2
+               DO jk=1,jpkm1
+# if defined key_vertical
+                  trbdiff(ji,jj,jk,1:jptra) = trb(ji,jj,jk,1:jptra) - tabres_child(ji,jj,jk,1:jptra)
+# else
+                  trbdiff(ji,jj,jk,1:jptra) = trb(ji,jj,jk,1:jptra) - tabres(ji,jj,jk,1:jptra)
+# endif
+               ENDDO
+            ENDDO
+         ENDDO
+
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+               DO jj = j1,j2-1
+                  DO ji = i1,i2-1
+                     zabe1 = fsaht_spu(ji,jj) * e2_e1u(ji,jj) * e3u_n(ji,jj,jk) * umask(ji,jj,jk)
+                     zabe2 = fsaht_spv(ji,jj) * e1_e2v(ji,jj) * e3v_n(ji,jj,jk) * vmask(ji,jj,jk)
+                     ztu(ji,jj) = zabe1 * ( trbdiff(ji+1,jj  ,jk,jn) - trbdiff(ji,jj,jk,jn) )
+                     ztv(ji,jj) = zabe2 * ( trbdiff(ji  ,jj+1,jk,jn) - trbdiff(ji,jj,jk,jn) )
+                  END DO
+               END DO
+               !
+               DO jj = j1+1,j2-1
+                  DO ji = i1+1,i2-1
+                     IF( .NOT. tabspongedone_trn(ji,jj) ) THEN 
+                        tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + (  ztu(ji,jj) - ztu(ji-1,jj  )     &
+                           &                                   + ztv(ji,jj) - ztv(ji  ,jj-1)  )  &
+                           &                                * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+            !
+         END DO
+         !
+         tabspongedone_trn(i1+1:i2-1,j1+1:j2-1) = .TRUE.
+      ENDIF
+      !                 
+   END SUBROUTINE interptrn_sponge
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                           no TOP AGRIF
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_top_sponge_empty
+      WRITE(*,*)  'agrif_top_sponge : You should not have seen this print! error?'
+   END SUBROUTINE agrif_top_sponge_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_top_sponge
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_update.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_update.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_top_update.F90	(revision 14097)
@@ -0,0 +1,249 @@
+#define TWO_WAY
+#undef DECAL_FEEDBACK
+
+MODULE agrif_top_update
+   !!======================================================================
+   !!                ***  MODULE agrif_top_update  ***
+   !! AGRIF :   update package for passive tracers (TOP) 
+   !!======================================================================
+   !! History :  
+   !!----------------------------------------------------------------------
+#if defined key_agrif && defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_agrif'                                              AGRIF zoom
+   !!   'key_TOP'                                           on-line tracers
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE oce
+   USE dom_oce
+   USE agrif_oce
+   USE par_trc
+   USE trc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC Agrif_Update_Trc
+
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE Agrif_Update_Trc( )
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE Agrif_Update_Trc ***
+      !!----------------------------------------------------------------------
+      ! 
+      IF (Agrif_Root()) RETURN 
+      !
+#if defined TWO_WAY   
+      Agrif_UseSpecialValueInUpdate = .TRUE.
+      Agrif_SpecialValueFineGrid    = 0._wp
+      ! 
+# if ! defined DECAL_FEEDBACK
+      CALL Agrif_Update_Variable(trn_id, procname=updateTRC )
+!      CALL Agrif_Update_Variable( trn_id, locupdate=(/0,2/), procname=updateTRC )
+# else
+      CALL Agrif_Update_Variable(trn_id, locupdate=(/1,0/),procname=updateTRC )
+!      CALL Agrif_Update_Variable( trn_id, locupdate=(/1,2/), procname=updateTRC )
+# endif
+      !
+      Agrif_UseSpecialValueInUpdate = .FALSE.
+      !
+#endif
+      !
+   END SUBROUTINE Agrif_Update_Trc
+
+#ifdef key_vertical
+   SUBROUTINE updateTRC( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!---------------------------------------------
+      !!           *** ROUTINE updateT ***
+      !!---------------------------------------------
+      INTEGER, INTENT(in) :: i1,i2,j1,j2,k1,k2,n1,n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) :: tabres
+      LOGICAL, INTENT(in) :: before
+      !!
+      INTEGER :: ji,jj,jk,jn
+      REAL(wp), DIMENSION(i1:i2,j1:j2,1:jpk,n1:n2) :: tabres_child
+      REAL(wp) :: h_in(k1:k2)
+      REAL(wp) :: h_out(1:jpk)
+      INTEGER  :: N_in, N_out
+      REAL(wp) :: h_diff
+      REAL(wp) :: zrho_xy
+      REAL(wp) :: tabin(k1:k2,n1:n2)
+      !!---------------------------------------------
+      !
+      IF (before) THEN
+         AGRIF_SpecialValue = -999._wp
+         zrho_xy = Agrif_rhox() * Agrif_rhoy() 
+         DO jn = n1,n2-1
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     tabres(ji,jj,jk,jn) = (trn(ji,jj,jk,jn) * e3t_n(ji,jj,jk) ) &
+                                           * tmask(ji,jj,jk) + (tmask(ji,jj,jk)-1)*999._wp
+                  END DO
+               END DO
+            END DO
+         END DO
+         DO jk=k1,k2
+            DO jj=j1,j2
+               DO ji=i1,i2
+                  tabres(ji,jj,jk,n2) = tmask(ji,jj,jk) * e3t_n(ji,jj,jk) &
+                                           + (tmask(ji,jj,jk)-1)*999._wp
+               END DO
+            END DO
+         END DO
+      ELSE
+         tabres_child(:,:,:,:) = 0.
+         AGRIF_SpecialValue = 0._wp
+         DO jj=j1,j2
+            DO ji=i1,i2
+               N_in = 0
+               DO jk=k1,k2 !k2 = jpk of child grid
+                  IF (tabres(ji,jj,jk,n2) == 0  ) EXIT
+                  N_in = N_in + 1
+                  tabin(jk,:) = tabres(ji,jj,jk,n1:n2-1)/tabres(ji,jj,jk,n2)
+                  h_in(N_in) = tabres(ji,jj,jk,n2)
+               ENDDO
+               N_out = 0
+               DO jk=1,jpk ! jpk of parent grid
+                  IF (tmask(ji,jj,jk) < -900) EXIT ! TODO: Will not work with ISF
+                  N_out = N_out + 1
+                  h_out(N_out) = e3t_n(ji,jj,jk) !Parent grid scale factors. Could multiply by e1e2t here instead of division above
+               ENDDO
+               IF (N_in > 0) THEN !Remove this?
+                  h_diff = sum(h_out(1:N_out))-sum(h_in(1:N_in))
+                  IF (h_diff < -1.e-4) THEN
+                     print *,'CHECK YOUR bathy T points ...',ji,jj,h_diff,sum(h_in(1:N_in)),sum(h_out(1:N_out))
+                     print *,h_in(1:N_in)
+                     print *,h_out(1:N_out)
+                     STOP
+                  ENDIF
+                  DO jn=1,jptra
+                     CALL reconstructandremap(tabin(1:N_in,jn),h_in(1:N_in),tabres_child(ji,jj,1:N_out,jn),h_out(1:N_out),N_in,N_out)
+                  ENDDO
+               ENDIF
+            ENDDO
+         ENDDO
+
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+            ! Add asselin part
+            DO jn = 1,jptra
+               DO jk=1,jpk
+                  DO jj=j1,j2
+                     DO ji=i1,i2
+                        IF( tabres_child(ji,jj,jk,jn) .NE. 0. ) THEN
+                           trb(ji,jj,jk,jn) = trb(ji,jj,jk,jn) & 
+                                 & + atfp * ( tabres_child(ji,jj,jk,jn) &
+                                 &          - trn(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDIF
+         DO jn = 1,jptra
+            DO jk=1,jpk
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     IF( tabres_child(ji,jj,jk,jn) .NE. 0. ) THEN 
+                        trn(ji,jj,jk,jn) = tabres_child(ji,jj,jk,jn) * tmask(ji,jj,jk)
+                     END IF
+                  END DO
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ! 
+   END SUBROUTINE updateTRC
+
+
+#else
+   SUBROUTINE updateTRC( tabres, i1, i2, j1, j2, k1, k2, n1, n2, before )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE updateTRC ***
+      !!----------------------------------------------------------------------
+      INTEGER                                    , INTENT(in   ) ::   i1, i2, j1, j2, k1, k2, n1, n2
+      REAL(wp),DIMENSION(i1:i2,j1:j2,k1:k2,n1:n2), INTENT(inout) ::   tabres
+      LOGICAL                                    , INTENT(in   ) ::   before
+      !!
+      INTEGER :: ji,jj,jk,jn
+      REAL(wp) :: ztb, ztnu, ztno
+      !!----------------------------------------------------------------------
+      !
+      !
+      IF (before) THEN
+         DO jn = n1,n2
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+!> jc tmp
+                     tabres(ji,jj,jk,jn) = trn(ji,jj,jk,jn)  * e3t_n(ji,jj,jk) / e3t_0(ji,jj,jk)
+!                     tabres(ji,jj,jk,jn) = trn(ji,jj,jk,jn)  * e3t_n(ji,jj,jk)
+!< jc tmp
+                  END DO
+               END DO
+            END DO
+         END DO
+      ELSE
+!> jc tmp
+         DO jn = n1,n2
+            tabres(i1:i2,j1:j2,k1:k2,jn) =  tabres(i1:i2,j1:j2,k1:k2,jn) * e3t_0(i1:i2,j1:j2,k1:k2) &
+                                         & * tmask(i1:i2,j1:j2,k1:k2)
+         ENDDO
+!< jc tmp
+         IF (.NOT.(lk_agrif_fstep.AND.(neuler==0))) THEN
+            ! Add asselin part
+            DO jn = n1,n2
+               DO jk=k1,k2
+                  DO jj=j1,j2
+                     DO ji=i1,i2
+                        IF( tabres(ji,jj,jk,jn) .NE. 0. ) THEN
+                           ztb  = trb(ji,jj,jk,jn) * e3t_b(ji,jj,jk) ! fse3t_b prior update should be used
+                           ztnu = tabres(ji,jj,jk,jn)
+                           ztno = trn(ji,jj,jk,jn) * e3t_a(ji,jj,jk)
+                           trb(ji,jj,jk,jn) = ( ztb + atfp * ( ztnu - ztno) )  & 
+                                     &        * tmask(ji,jj,jk) / e3t_b(ji,jj,jk)
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDIF
+         DO jn = n1,n2
+            DO jk=k1,k2
+               DO jj=j1,j2
+                  DO ji=i1,i2
+                     IF( tabres(ji,jj,jk,jn) .NE. 0. ) THEN 
+                        trn(ji,jj,jk,jn) = tabres(ji,jj,jk,jn) / e3t_n(ji,jj,jk)
+                     END IF
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         IF  ((neuler==0).AND.(Agrif_Nb_Step()==0) ) THEN
+            trb(i1:i2,j1:j2,k1:k2,n1:n2)  = trn(i1:i2,j1:j2,k1:k2,n1:n2)
+         ENDIF
+         !
+      ENDIF
+      ! 
+   END SUBROUTINE updateTRC
+#endif
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Empty module                                           no TOP AGRIF
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE agrif_top_update_empty
+      WRITE(*,*)  'agrif_top_update : You should not have seen this print! error?'
+   END SUBROUTINE agrif_top_update_empty
+#endif
+
+   !!======================================================================
+END MODULE agrif_top_update
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_user.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_user.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/NST/agrif_user.F90	(revision 14097)
@@ -0,0 +1,816 @@
+#undef UPD_HIGH   /* MIX HIGH UPDATE */
+#if defined key_agrif
+   !!----------------------------------------------------------------------
+   !! NEMO/NST 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+SUBROUTINE agrif_user
+END SUBROUTINE agrif_user
+
+SUBROUTINE agrif_before_regridding
+END SUBROUTINE agrif_before_regridding
+
+SUBROUTINE Agrif_InitWorkspace
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitWorkspace ***
+      !!----------------------------------------------------------------------
+   USE par_oce
+   USE dom_oce
+   USE nemogcm
+   USE mppini
+      !!
+   IMPLICIT NONE
+      !!----------------------------------------------------------------------
+   !
+   IF( .NOT. Agrif_Root() ) THEN
+      ! no more static variables
+!!$! JC: change to allow for different vertical levels
+!!$!     jpk is already set
+!!$!     keep it jpk possibly different from jpkglo which 
+!!$!     hold parent grid vertical levels number (set earlier)
+!!$!      jpk     = jpkglo 
+   ENDIF
+   !
+END SUBROUTINE Agrif_InitWorkspace
+
+
+SUBROUTINE Agrif_InitValues
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitValues ***
+      !!
+      !! ** Purpose :: Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE Agrif_Util
+   USE oce 
+   USE dom_oce
+   USE nemogcm
+   USE tradmp
+   USE bdy_oce   , ONLY: ln_bdy
+   !!
+   IMPLICIT NONE
+      !!----------------------------------------------------------------------
+   !
+   CALL nemo_init       !* Initializations of each fine grid
+
+   !                    !* Agrif initialization
+   CALL agrif_nemo_init
+   CALL Agrif_InitValues_cont_dom
+   CALL Agrif_InitValues_cont
+# if defined key_top
+   CALL Agrif_InitValues_cont_top
+# endif
+# if defined key_si3
+   CALL Agrif_InitValues_cont_ice
+# endif
+   !    
+END SUBROUTINE Agrif_initvalues
+
+
+SUBROUTINE Agrif_InitValues_cont_dom
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitValues_cont ***
+      !!
+      !! ** Purpose ::   Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE Agrif_Util
+   USE oce 
+   USE dom_oce
+   USE nemogcm
+   USE in_out_manager
+   USE agrif_oce_update
+   USE agrif_oce_interp
+   USE agrif_oce_sponge
+   !
+   IMPLICIT NONE
+      !!----------------------------------------------------------------------
+   !
+   ! Declaration of the type of variable which have to be interpolated
+   !
+   CALL agrif_declare_var_dom
+   !
+END SUBROUTINE Agrif_InitValues_cont_dom
+
+
+SUBROUTINE agrif_declare_var_dom
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE agrif_declare_var ***
+      !!
+      !! ** Purpose :: Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE agrif_util
+   USE par_oce       
+   USE oce
+   !
+   IMPLICIT NONE
+   !
+   INTEGER :: ind1, ind2, ind3
+      !!----------------------------------------------------------------------
+
+      ! 1. Declaration of the type of variable which have to be interpolated
+      !---------------------------------------------------------------------
+   ind1 =     nbghostcells
+   ind2 = 1 + nbghostcells
+   ind3 = 2 + nbghostcells
+   CALL agrif_declare_variable((/1,2/),(/ind2,ind3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),e1u_id)
+   CALL agrif_declare_variable((/2,1/),(/ind3,ind2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),e2v_id)
+
+      ! 2. Type of interpolation
+      !-------------------------
+   CALL Agrif_Set_bcinterp( e1u_id, interp1=Agrif_linear, interp2=AGRIF_ppm    )
+   CALL Agrif_Set_bcinterp( e2v_id, interp1=AGRIF_ppm   , interp2=Agrif_linear )
+
+      ! 3. Location of interpolation
+      !-----------------------------
+   CALL Agrif_Set_bc(e1u_id,(/0,ind1-1/))
+   CALL Agrif_Set_bc(e2v_id,(/0,ind1-1/))
+
+      ! 4. Update type
+      !--------------- 
+# if defined UPD_HIGH
+   CALL Agrif_Set_Updatetype(e1u_id,update1 = Agrif_Update_Average, update2=Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(e2v_id,update1 = Agrif_Update_Full_Weighting, update2=Agrif_Update_Average)
+#else
+   CALL Agrif_Set_Updatetype(e1u_id,update1 = Agrif_Update_Copy, update2=Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(e2v_id,update1 = Agrif_Update_Average, update2=Agrif_Update_Copy)
+#endif
+
+END SUBROUTINE agrif_declare_var_dom
+
+
+SUBROUTINE Agrif_InitValues_cont
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitValues_cont ***
+      !!
+      !! ** Purpose ::   Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE agrif_oce_update
+   USE agrif_oce_interp
+   USE agrif_oce_sponge
+   USE Agrif_Util
+   USE oce 
+   USE dom_oce
+   USE zdf_oce
+   USE nemogcm
+   !
+   USE lib_mpp
+   USE in_out_manager
+   !
+   IMPLICIT NONE
+   !
+   LOGICAL :: check_namelist
+   CHARACTER(len=15) :: cl_check1, cl_check2, cl_check3, cl_check4 
+      !!----------------------------------------------------------------------
+
+   ! 1. Declaration of the type of variable which have to be interpolated
+   !---------------------------------------------------------------------
+   CALL agrif_declare_var
+
+   ! 2. First interpolations of potentially non zero fields
+   !-------------------------------------------------------
+   Agrif_SpecialValue    = 0._wp
+   Agrif_UseSpecialValue = .TRUE.
+   CALL Agrif_Bc_variable(tsn_id,calledweight=1.,procname=interptsn)
+   CALL Agrif_Sponge
+   tabspongedone_tsn = .FALSE.
+   CALL Agrif_Bc_variable(tsn_sponge_id,calledweight=1.,procname=interptsn_sponge)
+   ! reset tsa to zero
+   tsa(:,:,:,:) = 0.
+
+   Agrif_UseSpecialValue = ln_spc_dyn
+   CALL Agrif_Bc_variable(un_interp_id,calledweight=1.,procname=interpun)
+   CALL Agrif_Bc_variable(vn_interp_id,calledweight=1.,procname=interpvn)
+   tabspongedone_u = .FALSE.
+   tabspongedone_v = .FALSE.
+   CALL Agrif_Bc_variable(un_sponge_id,calledweight=1.,procname=interpun_sponge)
+   tabspongedone_u = .FALSE.
+   tabspongedone_v = .FALSE.
+   CALL Agrif_Bc_variable(vn_sponge_id,calledweight=1.,procname=interpvn_sponge)
+
+   Agrif_UseSpecialValue = .TRUE.
+   CALL Agrif_Bc_variable(sshn_id,calledweight=1., procname=interpsshn )
+   hbdy_w(:,:) = 0.e0 ; hbdy_e(:,:) = 0.e0 ; hbdy_n(:,:) = 0.e0 ; hbdy_s(:,:) = 0.e0
+   ssha(:,:) = 0.e0
+
+   IF ( ln_dynspg_ts ) THEN
+      Agrif_UseSpecialValue = ln_spc_dyn
+      CALL Agrif_Bc_variable(unb_id,calledweight=1.,procname=interpunb)
+      CALL Agrif_Bc_variable(vnb_id,calledweight=1.,procname=interpvnb)
+      CALL Agrif_Bc_variable(ub2b_interp_id,calledweight=1.,procname=interpub2b)
+      CALL Agrif_Bc_variable(vb2b_interp_id,calledweight=1.,procname=interpvb2b)
+      ubdy_w(:,:) = 0.e0 ; vbdy_w(:,:) = 0.e0
+      ubdy_e(:,:) = 0.e0 ; vbdy_e(:,:) = 0.e0
+      ubdy_n(:,:) = 0.e0 ; vbdy_n(:,:) = 0.e0
+      ubdy_s(:,:) = 0.e0 ; vbdy_s(:,:) = 0.e0
+   ENDIF
+
+   Agrif_UseSpecialValue = .FALSE. 
+   ! reset velocities to zero
+   ua(:,:,:) = 0.
+   va(:,:,:) = 0.
+
+   ! 3. Some controls
+   !-----------------
+   check_namelist = .TRUE.
+
+   IF( check_namelist ) THEN 
+
+      ! Check time steps           
+      IF( NINT(Agrif_Rhot()) * NINT(rdt) .NE. Agrif_Parent(rdt) ) THEN
+         WRITE(cl_check1,*)  NINT(Agrif_Parent(rdt))
+         WRITE(cl_check2,*)  NINT(rdt)
+         WRITE(cl_check3,*)  NINT(Agrif_Parent(rdt)/Agrif_Rhot())
+         CALL ctl_stop( 'Incompatible time step between ocean grids',   &
+               &               'parent grid value : '//cl_check1    ,   & 
+               &               'child  grid value : '//cl_check2    ,   & 
+               &               'value on child grid should be changed to : '//cl_check3 )
+      ENDIF
+
+      ! Check run length
+      IF( Agrif_IRhot() * (Agrif_Parent(nitend)- &
+            Agrif_Parent(nit000)+1) .NE. (nitend-nit000+1) ) THEN
+         WRITE(cl_check1,*)  (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         WRITE(cl_check2,*)   Agrif_Parent(nitend)   *Agrif_IRhot()
+         CALL ctl_warn( 'Incompatible run length between grids'                      ,   &
+               &               'nit000 on fine grid will be changed to : '//cl_check1,   &
+               &               'nitend on fine grid will be changed to : '//cl_check2    )
+         nit000 = (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         nitend =  Agrif_Parent(nitend)   *Agrif_IRhot()
+      ENDIF
+
+      ! Check free surface scheme
+      IF ( ( Agrif_Parent(ln_dynspg_ts ).AND.ln_dynspg_exp ).OR.&
+         & ( Agrif_Parent(ln_dynspg_exp).AND.ln_dynspg_ts ) ) THEN
+         WRITE(cl_check1,*)  Agrif_Parent( ln_dynspg_ts )
+         WRITE(cl_check2,*)  ln_dynspg_ts
+         WRITE(cl_check3,*)  Agrif_Parent( ln_dynspg_exp )
+         WRITE(cl_check4,*)  ln_dynspg_exp
+         CALL ctl_stop( 'Incompatible free surface scheme between grids' ,  &
+               &               'parent grid ln_dynspg_ts  :'//cl_check1  ,  & 
+               &               'child  grid ln_dynspg_ts  :'//cl_check2  ,  &
+               &               'parent grid ln_dynspg_exp :'//cl_check3  ,  &
+               &               'child  grid ln_dynspg_exp :'//cl_check4  ,  &
+               &               'those logicals should be identical' )                 
+         STOP
+      ENDIF
+
+      ! Check if identical linear free surface option
+      IF ( ( Agrif_Parent(ln_linssh ).AND.(.NOT.ln_linssh )).OR.&
+         & ( (.NOT.Agrif_Parent(ln_linssh)).AND.ln_linssh ) ) THEN
+         WRITE(cl_check1,*)  Agrif_Parent(ln_linssh )
+         WRITE(cl_check2,*)  ln_linssh
+         CALL ctl_stop( 'Incompatible linearized fs option between grids',  &
+               &               'parent grid ln_linssh  :'//cl_check1     ,  &
+               &               'child  grid ln_linssh  :'//cl_check2     ,  &
+               &               'those logicals should be identical' )                  
+         STOP
+      ENDIF
+
+      ! check if masks and bathymetries match
+      IF(ln_chk_bathy) THEN
+         !
+         IF(lwp) WRITE(numout,*) 'AGRIF: Check Bathymetry and masks near bdys. Level: ', Agrif_Level()
+         !
+         kindic_agr = 0
+         ! check if umask agree with parent along western and eastern boundaries:
+         CALL Agrif_Bc_variable(umsk_id,calledweight=1.,procname=interpumsk)
+         ! check if vmask agree with parent along northern and southern boundaries:
+         CALL Agrif_Bc_variable(vmsk_id,calledweight=1.,procname=interpvmsk)
+         ! check if tmask and vertical scale factors agree with parent over first two coarse grid points:
+         CALL Agrif_Bc_variable(e3t_id,calledweight=1.,procname=interpe3t)
+         !
+         CALL mpp_sum( 'agrif_user', kindic_agr )
+         IF( kindic_agr /= 0 ) THEN
+            CALL ctl_stop('Child Bathymetry is not correct near boundaries.')
+         ELSE
+            IF(lwp) WRITE(numout,*) 'Child Bathymetry is ok near boundaries.'
+         END IF
+      ENDIF
+      !
+   ENDIF
+   ! 
+END SUBROUTINE Agrif_InitValues_cont
+
+SUBROUTINE agrif_declare_var
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE agrif_declarE_var ***
+      !!
+      !! ** Purpose :: Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE agrif_util
+   USE agrif_oce
+   USE par_oce       ! ocean parameters
+   USE zdf_oce       ! vertical physics
+   USE oce
+   !
+   IMPLICIT NONE
+   !
+   INTEGER :: ind1, ind2, ind3
+      !!----------------------------------------------------------------------
+
+   ! 1. Declaration of the type of variable which have to be interpolated
+   !---------------------------------------------------------------------
+   ind1 =     nbghostcells
+   ind2 = 1 + nbghostcells
+   ind3 = 2 + nbghostcells
+# if defined key_vertical
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts+1/),tsn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts+1/),tsn_sponge_id)
+
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),un_interp_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),vn_interp_id)
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),un_update_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),vn_update_id)
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),un_sponge_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),vn_sponge_id)
+# else
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts/),tsn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jpts/),tsn_sponge_id)
+
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),un_interp_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),vn_interp_id)
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),un_update_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),vn_update_id)
+   CALL agrif_declare_variable((/1,2,0,0/),(/ind2,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),un_sponge_id)
+   CALL agrif_declare_variable((/2,1,0,0/),(/ind3,ind2,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),vn_sponge_id)
+# endif
+
+   CALL agrif_declare_variable((/2,2,0/),(/ind3,ind3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),e3t_id)
+   CALL agrif_declare_variable((/1,2,0/),(/ind2,ind3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),umsk_id)
+   CALL agrif_declare_variable((/2,1,0/),(/ind3,ind2,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),vmsk_id)
+
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,3/),scales_t_id)
+
+   CALL agrif_declare_variable((/1,2/),(/ind2,ind3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),unb_id)
+   CALL agrif_declare_variable((/2,1/),(/ind3,ind2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vnb_id)
+   CALL agrif_declare_variable((/1,2/),(/ind2,ind3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),ub2b_interp_id)
+   CALL agrif_declare_variable((/2,1/),(/ind3,ind2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vb2b_interp_id)
+   CALL agrif_declare_variable((/1,2/),(/ind2,ind3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),ub2b_update_id)
+   CALL agrif_declare_variable((/2,1/),(/ind3,ind2/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),vb2b_update_id)
+
+   CALL agrif_declare_variable((/2,2/),(/ind3,ind3/),(/'x','y'/),(/1,1/),(/nlci,nlcj/),sshn_id)
+
+   IF( ln_zdftke.OR.ln_zdfgls ) THEN
+!      CALL agrif_declare_variable((/2,2,0/),(/ind3,ind3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/), en_id)
+!      CALL agrif_declare_variable((/2,2,0/),(/ind3,ind3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpk/),avt_id)
+# if defined key_vertical
+      CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,2/),avm_id)
+# else
+      CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,1/),avm_id)
+# endif
+   ENDIF
+
+   ! 2. Type of interpolation
+   !-------------------------
+   CALL Agrif_Set_bcinterp(tsn_id,interp=AGRIF_linear)
+
+   CALL Agrif_Set_bcinterp(un_interp_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vn_interp_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+   CALL Agrif_Set_bcinterp(tsn_sponge_id,interp=AGRIF_linear)
+
+   CALL Agrif_Set_bcinterp(sshn_id,interp=AGRIF_linear)
+   CALL Agrif_Set_bcinterp(unb_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vnb_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+   CALL Agrif_Set_bcinterp(ub2b_interp_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vb2b_interp_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+
+   CALL Agrif_Set_bcinterp(un_sponge_id,interp1=Agrif_linear,interp2=AGRIF_ppm)
+   CALL Agrif_Set_bcinterp(vn_sponge_id,interp1=AGRIF_ppm,interp2=Agrif_linear)
+
+   CALL Agrif_Set_bcinterp(e3t_id,interp=AGRIF_constant)
+   CALL Agrif_Set_bcinterp(umsk_id,interp=AGRIF_constant)
+   CALL Agrif_Set_bcinterp(vmsk_id,interp=AGRIF_constant)
+
+   IF( ln_zdftke.OR.ln_zdfgls )   CALL Agrif_Set_bcinterp( avm_id, interp=AGRIF_linear )
+
+   ! 3. Location of interpolation
+   !-----------------------------
+   CALL Agrif_Set_bc(       tsn_id, (/0,ind1/) )
+   CALL Agrif_Set_bc( un_interp_id, (/0,ind1/) )
+   CALL Agrif_Set_bc( vn_interp_id, (/0,ind1/) )
+
+   CALL Agrif_Set_bc( tsn_sponge_id, (/-nn_sponge_len*Agrif_irhox()-1,0/) )  ! if west and rhox=3 and sponge=2 and ghost=1: columns 2 to 9 
+   CALL Agrif_Set_bc(  un_sponge_id, (/-nn_sponge_len*Agrif_irhox()-1,0/) )
+   CALL Agrif_Set_bc(  vn_sponge_id, (/-nn_sponge_len*Agrif_irhox()-1,0/) )
+
+   CALL Agrif_Set_bc(        sshn_id, (/0,ind1-1/) )
+   CALL Agrif_Set_bc(         unb_id, (/0,ind1-1/) )
+   CALL Agrif_Set_bc(         vnb_id, (/0,ind1-1/) )
+   CALL Agrif_Set_bc( ub2b_interp_id, (/0,ind1-1/) )
+   CALL Agrif_Set_bc( vb2b_interp_id, (/0,ind1-1/) )
+
+   CALL Agrif_Set_bc(  e3t_id, (/-nn_sponge_len*Agrif_irhox(),ind1-1/) )   ! if west and rhox=3 and ghost=1: column 2 to 6 
+   CALL Agrif_Set_bc( umsk_id, (/0,0/) )
+   CALL Agrif_Set_bc( vmsk_id, (/0,0/) )
+
+
+   IF( ln_zdftke.OR.ln_zdfgls )   CALL Agrif_Set_bc( avm_id, (/0,ind1/) )
+
+   ! 4. Update type
+   !--------------- 
+   CALL Agrif_Set_Updatetype(scales_t_id, update = AGRIF_Update_Average)
+
+# if defined UPD_HIGH
+   CALL Agrif_Set_Updatetype(tsn_id, update = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(un_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(vn_update_id,update1 = Agrif_Update_Full_Weighting, update2 = Agrif_Update_Average)
+
+   CALL Agrif_Set_Updatetype(ub2b_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(vb2b_update_id,update1 = Agrif_Update_Full_Weighting, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(sshn_id, update = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(e3t_id, update = Agrif_Update_Full_Weighting)
+
+   IF( ln_zdftke.OR.ln_zdfgls ) THEN
+!      CALL Agrif_Set_Updatetype( en_id, update = AGRIF_Update_Full_Weighting)
+!      CALL Agrif_Set_Updatetype(avt_id, update = AGRIF_Update_Full_Weighting)
+!      CALL Agrif_Set_Updatetype(avm_id, update = AGRIF_Update_Full_Weighting)
+   ENDIF
+
+#else
+   CALL Agrif_Set_Updatetype(tsn_id, update = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(un_update_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(vn_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
+
+   CALL Agrif_Set_Updatetype(ub2b_update_id,update1 = Agrif_Update_Copy, update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(vb2b_update_id,update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy)
+   CALL Agrif_Set_Updatetype(sshn_id, update = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(e3t_id, update = AGRIF_Update_Average)
+
+   IF( ln_zdftke.OR.ln_zdfgls ) THEN
+!      CALL Agrif_Set_Updatetype( en_id, update = AGRIF_Update_Average)
+!      CALL Agrif_Set_Updatetype(avt_id, update = AGRIF_Update_Average)
+!      CALL Agrif_Set_Updatetype(avm_id, update = AGRIF_Update_Average)
+   ENDIF
+
+#endif
+   !
+END SUBROUTINE agrif_declare_var
+
+#if defined key_si3
+SUBROUTINE Agrif_InitValues_cont_ice
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitValues_cont_ice ***
+      !!
+      !! ** Purpose :: Initialisation of variables to be interpolated for ice
+      !!----------------------------------------------------------------------
+   USE Agrif_Util
+   USE sbc_oce, ONLY : nn_fsbc  ! clem: necessary otherwise Agrif_Parent(nn_fsbc) = nn_fsbc
+   USE ice
+   USE agrif_ice
+   USE in_out_manager
+   USE agrif_ice_interp
+   USE lib_mpp
+   !
+   IMPLICIT NONE
+      !!----------------------------------------------------------------------
+   !
+   ! Declaration of the type of variable which have to be interpolated (parent=>child)
+   !----------------------------------------------------------------------------------
+   CALL agrif_declare_var_ice
+
+   ! Controls
+
+   ! clem: For some reason, nn_fsbc(child)/=1 does not work properly (signal can be largely degraded by the agrif zoom)
+   !          the run must satisfy CFL=Uice/(dx/dt) < 0.6/nn_fsbc(child)
+   !          therefore, if nn_fsbc(child)>1 one must reduce the time-step in proportion to nn_fsbc(child), which is not acceptable
+   !       If a solution is found, the following stop could be removed because the rest of the code take nn_fsbc(child) into account
+   IF( nn_fsbc > 1 )  CALL ctl_stop('nn_fsbc(child) must be set to 1 otherwise agrif and sea-ice may not work properly')
+
+   ! stop if rhot * nn_fsbc(parent) /= N * nn_fsbc(child) with N being integer
+   IF( MOD( Agrif_irhot() * Agrif_Parent(nn_fsbc), nn_fsbc ) /= 0 )  THEN
+      CALL ctl_stop('rhot * nn_fsbc(parent) /= N * nn_fsbc(child), therefore nn_fsbc(child) should be set to 1 or nn_fsbc(parent)')
+   ENDIF
+   ! First Interpolations (using "after" ice subtime step => nbstep_ice=1)
+   !----------------------------------------------------------------------
+   nbstep_ice = ( Agrif_irhot() * Agrif_Parent(nn_fsbc) / nn_fsbc ) ! clem: to have calledweight=1 in interp (otherwise the western border of the zoom is wrong)
+   CALL agrif_interp_ice('U') ! interpolation of ice velocities
+   CALL agrif_interp_ice('V') ! interpolation of ice velocities
+   CALL agrif_interp_ice('T') ! interpolation of ice tracers 
+   nbstep_ice = 0
+   
+   !
+END SUBROUTINE Agrif_InitValues_cont_ice
+
+SUBROUTINE agrif_declare_var_ice
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE agrif_declare_var_ice ***
+      !!
+      !! ** Purpose :: Declaration of variables to be interpolated for ice
+      !!----------------------------------------------------------------------
+   USE Agrif_Util
+   USE ice
+   USE par_oce, ONLY : nbghostcells
+   !
+   IMPLICIT NONE
+   !
+   INTEGER :: ind1, ind2, ind3
+      !!----------------------------------------------------------------------
+   !
+   ! 1. Declaration of the type of variable which have to be interpolated (parent=>child)
+   !       agrif_declare_variable(position,1st point index,--,--,dimensions,name)
+   !           ex.:  position=> 1,1 = not-centered (in i and j)
+   !                            2,2 =     centered (    -     )
+   !                 index   => 1,1 = one ghost line
+   !                            2,2 = two ghost lines
+   !-------------------------------------------------------------------------------------
+   ind1 =     nbghostcells
+   ind2 = 1 + nbghostcells
+   ind3 = 2 + nbghostcells
+   CALL agrif_declare_variable((/2,2,0/),(/ind3,ind3,0/),(/'x','y','N'/),(/1,1,1/),(/nlci,nlcj,jpl*(9+nlay_s+nlay_i)/),tra_ice_id)
+   CALL agrif_declare_variable((/1,2/)  ,(/ind2,ind3/)  ,(/'x','y'/)    ,(/1,1/)  ,(/nlci,nlcj/)                      ,u_ice_id  )
+   CALL agrif_declare_variable((/2,1/)  ,(/ind3,ind2/)  ,(/'x','y'/)    ,(/1,1/)  ,(/nlci,nlcj/)                      ,v_ice_id  )
+
+   ! 2. Set interpolations (normal & tangent to the grid cell for velocities)
+   !-----------------------------------
+   CALL Agrif_Set_bcinterp(tra_ice_id, interp  = AGRIF_linear)
+   CALL Agrif_Set_bcinterp(u_ice_id  , interp1 = Agrif_linear,interp2 = AGRIF_ppm   )
+   CALL Agrif_Set_bcinterp(v_ice_id  , interp1 = AGRIF_ppm   ,interp2 = Agrif_linear)
+
+   ! 3. Set location of interpolations
+   !----------------------------------
+   CALL Agrif_Set_bc(tra_ice_id,(/0,ind1/))
+   CALL Agrif_Set_bc(u_ice_id  ,(/0,ind1/))
+   CALL Agrif_Set_bc(v_ice_id  ,(/0,ind1/))
+
+   ! 4. Set update type in case 2 ways (child=>parent) (normal & tangent to the grid cell for velocities)
+   !--------------------------------------------------
+# if defined UPD_HIGH
+   CALL Agrif_Set_Updatetype(tra_ice_id, update  = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(u_ice_id  , update1 = Agrif_Update_Average       , update2 = Agrif_Update_Full_Weighting)
+   CALL Agrif_Set_Updatetype(v_ice_id  , update1 = Agrif_Update_Full_Weighting, update2 = Agrif_Update_Average       )
+#else
+   CALL Agrif_Set_Updatetype(tra_ice_id, update  = AGRIF_Update_Average)
+   CALL Agrif_Set_Updatetype(u_ice_id  , update1 = Agrif_Update_Copy   , update2 = Agrif_Update_Average)
+   CALL Agrif_Set_Updatetype(v_ice_id  , update1 = Agrif_Update_Average, update2 = Agrif_Update_Copy   )
+#endif
+
+END SUBROUTINE agrif_declare_var_ice
+#endif
+
+
+# if defined key_top
+SUBROUTINE Agrif_InitValues_cont_top
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_InitValues_cont_top ***
+      !!
+      !! ** Purpose :: Declaration of variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE Agrif_Util
+   USE oce 
+   USE dom_oce
+   USE nemogcm
+   USE par_trc
+   USE lib_mpp
+   USE trc
+   USE in_out_manager
+   USE agrif_oce_sponge
+   USE agrif_top_update
+   USE agrif_top_interp
+   USE agrif_top_sponge
+   !!
+   IMPLICIT NONE
+   !
+   CHARACTER(len=10) :: cl_check1, cl_check2, cl_check3
+   LOGICAL :: check_namelist
+      !!----------------------------------------------------------------------
+
+
+   ! 1. Declaration of the type of variable which have to be interpolated
+   !---------------------------------------------------------------------
+   CALL agrif_declare_var_top
+
+   ! 2. First interpolations of potentially non zero fields
+   !-------------------------------------------------------
+   Agrif_SpecialValue=0.
+   Agrif_UseSpecialValue = .TRUE.
+   CALL Agrif_Bc_variable(trn_id,calledweight=1.,procname=interptrn)
+   Agrif_UseSpecialValue = .FALSE.
+   CALL Agrif_Sponge
+   tabspongedone_trn = .FALSE.
+   CALL Agrif_Bc_variable(trn_sponge_id,calledweight=1.,procname=interptrn_sponge)
+   ! reset tsa to zero
+   tra(:,:,:,:) = 0.
+
+
+   ! 3. Some controls
+   !-----------------
+   check_namelist = .TRUE.
+
+   IF( check_namelist ) THEN
+      ! Check time steps
+      IF( NINT(Agrif_Rhot()) * NINT(rdt) .NE. Agrif_Parent(rdt) ) THEN
+         WRITE(cl_check1,*)  Agrif_Parent(rdt)
+         WRITE(cl_check2,*)  rdt
+         WRITE(cl_check3,*)  rdt*Agrif_Rhot()
+         CALL ctl_stop( 'incompatible time step between grids',   &
+               &               'parent grid value : '//cl_check1    ,   & 
+               &               'child  grid value : '//cl_check2    ,   & 
+               &               'value on child grid should be changed to  &
+               &               :'//cl_check3  )
+      ENDIF
+
+      ! Check run length
+      IF( Agrif_IRhot() * (Agrif_Parent(nitend)- &
+            Agrif_Parent(nit000)+1) .NE. (nitend-nit000+1) ) THEN
+         WRITE(cl_check1,*)  (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         WRITE(cl_check2,*)   Agrif_Parent(nitend)   *Agrif_IRhot()
+         CALL ctl_warn( 'incompatible run length between grids'               ,   &
+               &              ' nit000 on fine grid will be change to : '//cl_check1,   &
+               &              ' nitend on fine grid will be change to : '//cl_check2    )
+         nit000 = (Agrif_Parent(nit000)-1)*Agrif_IRhot() + 1
+         nitend =  Agrif_Parent(nitend)   *Agrif_IRhot()
+      ENDIF
+
+      ! Check passive tracer cell
+      IF( nn_dttrc .NE. 1 ) THEN
+         WRITE(*,*) 'nn_dttrc should be equal to 1'
+      ENDIF
+   ENDIF
+   !
+END SUBROUTINE Agrif_InitValues_cont_top
+
+
+SUBROUTINE agrif_declare_var_top
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE agrif_declare_var_top ***
+      !!
+      !! ** Purpose :: Declaration of TOP variables to be interpolated
+      !!----------------------------------------------------------------------
+   USE agrif_util
+   USE agrif_oce
+   USE dom_oce
+   USE trc
+   !!
+   IMPLICIT NONE
+   !
+   INTEGER :: ind1, ind2, ind3
+      !!----------------------------------------------------------------------
+
+   ! 1. Declaration of the type of variable which have to be interpolated
+   !---------------------------------------------------------------------
+   ind1 =     nbghostcells
+   ind2 = 1 + nbghostcells
+   ind3 = 2 + nbghostcells
+# if defined key_vertical
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra+1/),trn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/ind3,ind3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra+1/),trn_sponge_id)
+# else
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra/),trn_id)
+   CALL agrif_declare_variable((/2,2,0,0/),(/3,3,0,0/),(/'x','y','N','N'/),(/1,1,1,1/),(/nlci,nlcj,jpk,jptra/),trn_sponge_id)
+# endif
+
+   ! 2. Type of interpolation
+   !-------------------------
+   CALL Agrif_Set_bcinterp(trn_id,interp=AGRIF_linear)
+   CALL Agrif_Set_bcinterp(trn_sponge_id,interp=AGRIF_linear)
+
+   ! 3. Location of interpolation
+   !-----------------------------
+   CALL Agrif_Set_bc(trn_id,(/0,ind1/))
+   CALL Agrif_Set_bc(trn_sponge_id,(/-nn_sponge_len*Agrif_irhox()-1,0/))
+
+   ! 4. Update type
+   !--------------- 
+# if defined UPD_HIGH
+   CALL Agrif_Set_Updatetype(trn_id, update = Agrif_Update_Full_Weighting)
+#else
+   CALL Agrif_Set_Updatetype(trn_id, update = AGRIF_Update_Average)
+#endif
+   !
+END SUBROUTINE agrif_declare_var_top
+# endif
+
+SUBROUTINE Agrif_detect( kg, ksizex )
+      !!----------------------------------------------------------------------
+      !!                      *** ROUTINE Agrif_detect ***
+      !!----------------------------------------------------------------------
+   INTEGER, DIMENSION(2) :: ksizex
+   INTEGER, DIMENSION(ksizex(1),ksizex(2)) :: kg 
+      !!----------------------------------------------------------------------
+   !
+   RETURN
+   !
+END SUBROUTINE Agrif_detect
+
+
+SUBROUTINE agrif_nemo_init
+      !!----------------------------------------------------------------------
+      !!                     *** ROUTINE agrif_init ***
+      !!----------------------------------------------------------------------
+   USE agrif_oce 
+   USE agrif_ice
+   USE in_out_manager
+   USE lib_mpp
+   !!
+   IMPLICIT NONE
+   !
+   INTEGER  ::   ios                 ! Local integer output status for namelist read
+   INTEGER  ::   iminspon
+   NAMELIST/namagrif/ rn_sponge_tra, rn_sponge_dyn, ln_spc_dyn, ln_chk_bathy
+      !!--------------------------------------------------------------------------------------
+   !
+   REWIND( numnam_ref )              ! Namelist namagrif in reference namelist : AGRIF zoom
+   READ  ( numnam_ref, namagrif, IOSTAT = ios, ERR = 901)
+901 IF( ios /= 0 )   CALL ctl_nam ( ios , 'namagrif in reference namelist' )
+   REWIND( numnam_cfg )              ! Namelist namagrif in configuration namelist : AGRIF zoom
+   READ  ( numnam_cfg, namagrif, IOSTAT = ios, ERR = 902 )
+902 IF( ios >  0 )   CALL ctl_nam ( ios , 'namagrif in configuration namelist' )
+   IF(lwm) WRITE ( numond, namagrif )
+   !
+   IF(lwp) THEN                    ! control print
+      WRITE(numout,*)
+      WRITE(numout,*) 'agrif_nemo_init : AGRIF parameters'
+      WRITE(numout,*) '~~~~~~~~~~~~~~~'
+      WRITE(numout,*) '   Namelist namagrif : set AGRIF parameters'
+      WRITE(numout,*) '      sponge coefficient for tracers    rn_sponge_tra = ', rn_sponge_tra, ' s'
+      WRITE(numout,*) '      sponge coefficient for dynamics   rn_sponge_tra = ', rn_sponge_dyn, ' s'
+      WRITE(numout,*) '      use special values for dynamics   ln_spc_dyn    = ', ln_spc_dyn
+      WRITE(numout,*) '      check bathymetry                  ln_chk_bathy  = ', ln_chk_bathy
+   ENDIF
+   !
+   ! convert DOCTOR namelist name into OLD names
+   visc_tra      = rn_sponge_tra
+   visc_dyn      = rn_sponge_dyn
+   !
+   ! Check sponge length:
+   IF(     MIN(jpi   ,jpj   ) <=     1 + nbghostcells + (nn_sponge_len * Agrif_irhox() + 1)     &
+      .OR. MIN(jpiglo,jpjglo) <= 2* (1 + nbghostcells + (nn_sponge_len * Agrif_irhox() + 1) ) ) &
+      &     CALL ctl_stop('STOP','agrif sponge length is too large')
+   !
+   IF( agrif_oce_alloc()  > 0 )   CALL ctl_warn('agrif agrif_oce_alloc: allocation of arrays failed')
+   !
+END SUBROUTINE agrif_nemo_init
+
+# if defined key_mpp_mpi
+
+SUBROUTINE Agrif_InvLoc( indloc, nprocloc, i, indglob )
+      !!----------------------------------------------------------------------
+      !!                     *** ROUTINE Agrif_InvLoc ***
+      !!----------------------------------------------------------------------
+   USE dom_oce
+   !!
+   IMPLICIT NONE
+   !
+   INTEGER :: indglob, indloc, nprocloc, i
+      !!----------------------------------------------------------------------
+   !
+   SELECT CASE( i )
+   CASE(1)   ;   indglob = indloc + nimppt(nprocloc+1) - 1
+   CASE(2)   ;   indglob = indloc + njmppt(nprocloc+1) - 1
+   CASE DEFAULT
+      indglob = indloc
+   END SELECT
+   !
+END SUBROUTINE Agrif_InvLoc
+
+
+SUBROUTINE Agrif_get_proc_info( imin, imax, jmin, jmax )
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_get_proc_info ***
+      !!----------------------------------------------------------------------
+   USE par_oce
+   !!
+   IMPLICIT NONE
+   !
+   INTEGER, INTENT(out) :: imin, imax
+   INTEGER, INTENT(out) :: jmin, jmax
+      !!----------------------------------------------------------------------
+   !
+   imin = nimppt(Agrif_Procrank+1)  ! ?????
+   jmin = njmppt(Agrif_Procrank+1)  ! ?????
+   imax = imin + jpi - 1
+   jmax = jmin + jpj - 1
+   ! 
+END SUBROUTINE Agrif_get_proc_info
+
+
+SUBROUTINE Agrif_estimate_parallel_cost(imin, imax,jmin, jmax, nbprocs, grid_cost)
+      !!----------------------------------------------------------------------
+      !!                 *** ROUTINE Agrif_estimate_parallel_cost ***
+      !!----------------------------------------------------------------------
+   USE par_oce
+   !!
+   IMPLICIT NONE
+   !
+   INTEGER,  INTENT(in)  :: imin, imax
+   INTEGER,  INTENT(in)  :: jmin, jmax
+   INTEGER,  INTENT(in)  :: nbprocs
+   REAL(wp), INTENT(out) :: grid_cost
+      !!----------------------------------------------------------------------
+   !
+   grid_cost = REAL(imax-imin+1,wp)*REAL(jmax-jmin+1,wp) / REAL(nbprocs,wp)
+   !
+END SUBROUTINE Agrif_estimate_parallel_cost
+
+# endif
+
+#else
+SUBROUTINE Subcalledbyagrif
+      !!----------------------------------------------------------------------
+      !!                   *** ROUTINE Subcalledbyagrif ***
+      !!----------------------------------------------------------------------
+   WRITE(*,*) 'Impossible to be here'
+END SUBROUTINE Subcalledbyagrif
+#endif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/README.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../doc/rst/source/data_assimilation.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmbkg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmbkg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmbkg.F90	(revision 14097)
@@ -0,0 +1,160 @@
+MODULE asmbkg
+   !!======================================================================
+   !!                       ***  MODULE asmtrj -> asmbkg  ***
+   !! Assimilation trajectory interface: Write to file the background state and the model state trajectory
+   !!======================================================================
+   !! History :       ! 2007-03 (M. Martin)  Met. Office version
+   !!                 ! 2007-04 (A. Weaver)  asm_trj_wri, original code
+   !!                 ! 2007-03 (K. Mogensen)  Adapt to NEMOVAR and use IOM instead of IOIPSL
+   !!                 ! 2007-04 (A. Weaver)  Name change (formally asmbkg.F90). Distinguish
+   !!                                        background states in Jb term and at analysis time.
+   !!                                        Include state trajectory routine (currently empty)
+   !!                 ! 2007-07 (A. Weaver)  Add tke_rst and flt_rst for case nitbkg=0 
+   !!                 ! 2009-03 (F. Vigilant)  Add hmlp (zdfmxl) for no tracer nmldp=2 
+   !!                 ! 2009-06 (F. Vigilant) asm_trj_wri: special case when kt=nit000-1
+   !!                 ! 2009-07 (F. Vigilant) asm_trj_wri: add computation of eiv at restart
+   !!                 ! 2010-01 (A. Vidard) split asm_trj_wri into tam_trj_wri and asm_bkg_wri
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   asm_bkg_wri  : Write out the background state
+   !!   asm_trj_wri  : Write out the model state trajectory (used with 4D-Var)
+   !!----------------------------------------------------------------------
+   USE oce                ! Dynamics and active tracers defined in memory
+   USE sbc_oce            ! Ocean surface boundary conditions
+   USE zdf_oce            ! Vertical mixing variables
+   USE zdfddm             ! Double diffusion mixing parameterization
+   USE ldftra             ! Lateral diffusion: eddy diffusivity coefficients
+   USE ldfslp             ! Lateral diffusion: slopes of neutral surfaces
+   USE tradmp             ! Tracer damping
+   USE zdftke             ! TKE vertical physics
+   USE eosbn2             ! Equation of state (eos_bn2 routine)
+   USE zdfmxl             ! Mixed layer depth
+   USE dom_oce     , ONLY :   ndastp
+   USE in_out_manager     ! I/O manager
+   USE iom                ! I/O module
+   USE asmpar             ! Parameters for the assmilation interface
+   USE zdfmxl             ! mixed layer depth
+#if defined key_si3
+   USE ice
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   asm_bkg_wri   !: Write out the background state
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE asm_bkg_wri( kt )
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE asm_bkg_wri ***
+      !!
+      !! ** Purpose : Write to file the background state for later use in the
+      !!              inner loop of data assimilation or for direct initialization
+      !!              in the outer loop.
+      !!
+      !! ** Method  : Write out the background state for use in the Jb term
+      !!              in the cost function and for use with direct initialization
+      !!              at analysis time.
+      !!-----------------------------------------------------------------------
+      INTEGER, INTENT( IN ) :: kt               ! Current time-step
+      !
+      CHARACTER (LEN=50) :: cl_asmbkg
+      CHARACTER (LEN=50) :: cl_asmdin
+      LOGICAL :: llok          ! Check if file exists
+      INTEGER :: inum          ! File unit number
+      REAL(wp) :: zdate        ! Date
+      !!-----------------------------------------------------------------------
+
+      !                                !-------------------------------------------
+      IF( kt == nitbkg_r ) THEN        ! Write out background at time step nitbkg_r
+         !                             !-----------------------------------========
+         !
+         WRITE(cl_asmbkg, FMT='(A,".nc")' ) TRIM( c_asmbkg )
+         cl_asmbkg = TRIM( cl_asmbkg )
+         INQUIRE( FILE = cl_asmbkg, EXIST = llok )
+         !
+         IF( .NOT. llok ) THEN
+            IF(lwp) WRITE(numout,*) ' Setting up assimilation background file '// TRIM( c_asmbkg )
+            !
+            !                                      ! Define the output file        
+            CALL iom_open( c_asmbkg, inum, ldwrt = .TRUE. )
+            !
+            IF( nitbkg_r == nit000 - 1 ) THEN      ! Treat special case when nitbkg = 0
+               zdate = REAL( ndastp )
+               IF( ln_zdftke ) THEN                   ! read turbulent kinetic energy ( en )
+                  IF(lwp) WRITE(numout,*) ' Reading TKE (en) from restart...'
+                  CALL tke_rst( nit000, 'READ' )
+               ENDIF
+            ELSE
+               zdate = REAL( ndastp )
+            ENDIF
+            !
+            !                                      ! Write the information
+            CALL iom_rstput( kt, nitbkg_r, inum, 'rdastp' , zdate             )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'un'     , un                )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'vn'     , vn                )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'tn'     , tsn(:,:,:,jp_tem) )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'sn'     , tsn(:,:,:,jp_sal) )
+            CALL iom_rstput( kt, nitbkg_r, inum, 'sshn'   , sshn              )
+            IF( ln_zdftke )   CALL iom_rstput( kt, nitbkg_r, inum, 'en'     , en                )
+            !
+            CALL iom_close( inum )
+         ENDIF
+         !
+      ENDIF
+
+      !                                !-------------------------------------------
+      IF( kt == nitdin_r ) THEN        ! Write out background at time step nitdin_r
+         !                             !-----------------------------------========
+         !
+         WRITE(cl_asmdin, FMT='(A,".nc")' ) TRIM( c_asmdin )
+         cl_asmdin = TRIM( cl_asmdin )
+         INQUIRE( FILE = cl_asmdin, EXIST = llok )
+         !
+         IF( .NOT. llok ) THEN
+            IF(lwp) WRITE(numout,*) ' Setting up assimilation background file '// TRIM( c_asmdin )
+            !
+            !                                      ! Define the output file        
+            CALL iom_open( c_asmdin, inum, ldwrt = .TRUE. )
+            !
+            IF( nitdin_r == nit000 - 1 ) THEN      ! Treat special case when nitbkg = 0
+
+               zdate = REAL( ndastp )
+            ELSE
+               zdate = REAL( ndastp )
+            ENDIF
+            !
+            !                                      ! Write the information
+            CALL iom_rstput( kt, nitdin_r, inum, 'rdastp' , zdate             )
+            CALL iom_rstput( kt, nitdin_r, inum, 'un'     , un                )
+            CALL iom_rstput( kt, nitdin_r, inum, 'vn'     , vn                )
+            CALL iom_rstput( kt, nitdin_r, inum, 'tn'     , tsn(:,:,:,jp_tem) )
+            CALL iom_rstput( kt, nitdin_r, inum, 'sn'     , tsn(:,:,:,jp_sal) )
+            CALL iom_rstput( kt, nitdin_r, inum, 'sshn'   , sshn              )
+#if defined key_si3
+            IF( nn_ice == 2 ) THEN
+	            IF( ALLOCATED(at_i) ) THEN
+                  CALL iom_rstput( kt, nitdin_r, inum, 'iceconc', at_i(:,:)   )
+               ELSE
+		            CALL ctl_warn('asm_bkg_wri: Ice concentration not written to background ',   &
+		               &          'as ice variable at_i not allocated on this timestep')
+	            ENDIF
+            ENDIF
+#endif
+            !
+            CALL iom_close( inum )
+         ENDIF
+         !
+      ENDIF
+      !                    
+   END SUBROUTINE asm_bkg_wri
+
+   !!======================================================================
+END MODULE asmbkg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asminc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asminc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asminc.F90	(revision 14097)
@@ -0,0 +1,1020 @@
+MODULE asminc
+   !!======================================================================
+   !!                       ***  MODULE asminc  ***
+   !! Assimilation increment : Apply an increment generated by data
+   !!                          assimilation
+   !!======================================================================
+   !! History :       ! 2007-03  (M. Martin)  Met Office version
+   !!                 ! 2007-04  (A. Weaver)  calc_date original code
+   !!                 ! 2007-04  (A. Weaver)  Merge with OPAVAR/NEMOVAR
+   !!   NEMO     3.3  ! 2010-05  (D. Lea)  Update to work with NEMO v3.2
+   !!             -   ! 2010-05  (D. Lea)  add calc_month_len routine based on day_init 
+   !!            3.4  ! 2012-10  (A. Weaver and K. Mogensen) Fix for direct initialization
+   !!                 ! 2014-09  (D. Lea)  Local calc_date removed use routine from OBS
+   !!                 ! 2015-11  (D. Lea)  Handle non-zero initial time of day
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   asm_inc_init   : Initialize the increment arrays and IAU weights
+   !!   tra_asm_inc    : Apply the tracer (T and S) increments
+   !!   dyn_asm_inc    : Apply the dynamic (u and v) increments
+   !!   ssh_asm_inc    : Apply the SSH increment
+   !!   ssh_asm_div    : Apply divergence associated with SSH increment
+   !!   seaice_asm_inc : Apply the seaice increment
+   !!----------------------------------------------------------------------
+   USE oce             ! Dynamics and active tracers defined in memory
+   USE par_oce         ! Ocean space and time domain variables
+   USE dom_oce         ! Ocean space and time domain
+   USE domvvl          ! domain: variable volume level
+   USE ldfdyn          ! lateral diffusion: eddy viscosity coefficients
+   USE eosbn2          ! Equation of state - in situ and potential density
+   USE zpshde          ! Partial step : Horizontal Derivative
+   USE asmpar          ! Parameters for the assmilation interface
+   USE asmbkg          ! 
+   USE c1d             ! 1D initialization
+   USE sbc_oce         ! Surface boundary condition variables.
+   USE diaobs   , ONLY : calc_date     ! Compute the calendar date on a given step
+#if defined key_si3
+   USE ice      , ONLY : hm_i, at_i, at_i_b
+#endif
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! Library to read input files
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   asm_inc_init   !: Initialize the increment arrays and IAU weights
+   PUBLIC   tra_asm_inc    !: Apply the tracer (T and S) increments
+   PUBLIC   dyn_asm_inc    !: Apply the dynamic (u and v) increments
+   PUBLIC   ssh_asm_inc    !: Apply the SSH increment
+   PUBLIC   ssh_asm_div    !: Apply the SSH divergence
+   PUBLIC   seaice_asm_inc !: Apply the seaice increment
+
+#if defined key_asminc
+    LOGICAL, PUBLIC, PARAMETER :: lk_asminc = .TRUE.   !: Logical switch for assimilation increment interface
+#else
+    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_temnofreeze = .FALSE. !: Don't allow the temperature to drop below freezing
+   INTEGER, PUBLIC :: nn_divdmp     !: Apply divergence damping filter nn_divdmp times
+
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   t_bkg   , s_bkg      !: Background temperature and salinity
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   u_bkg   , v_bkg      !: Background u- & v- velocity components
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   t_bkginc, s_bkginc   !: Increment to the background T & S
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   u_bkginc, v_bkginc   !: Increment to the u- & v-components 
+   REAL(wp), PUBLIC, DIMENSION(:)    , ALLOCATABLE ::   wgtiau               !: IAU weights for each time step
+#if defined key_asminc
+   REAL(wp), PUBLIC, DIMENSION(:,:)  , ALLOCATABLE ::   ssh_iau              !: IAU-weighted sea surface height increment
+#endif
+   !                                !!! time steps relative to the cycle interval [0,nitend-nit000-1]
+   INTEGER , PUBLIC ::   nitbkg      !: Time step of the background state used in the Jb term
+   INTEGER , PUBLIC ::   nitdin      !: Time step of the background state for direct initialization
+   INTEGER , PUBLIC ::   nitiaustr   !: Time step of the start of the IAU interval 
+   INTEGER , PUBLIC ::   nitiaufin   !: Time step of the end of the IAU interval
+   ! 
+   INTEGER , PUBLIC ::   niaufn      !: Type of IAU weighing function: = 0   Constant weighting
+   !                                 !: = 1   Linear hat-like, centred in middle of IAU interval 
+   REAL(wp), PUBLIC ::   salfixmin   !: Ensure that the salinity is larger than this  value if (ln_salfix)
+
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   ssh_bkg, ssh_bkginc   ! Background sea surface height and its increment
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   seaice_bkginc         ! Increment to the background sea ice conc
+#if defined key_cice && defined key_asminc
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   ndaice_da             ! ice increment tendency into CICE
+#endif
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE asm_inc_init
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE asm_inc_init  ***
+      !!          
+      !! ** Purpose : Initialize the assimilation increment and IAU weights.
+      !!
+      !! ** Method  : Initialize the assimilation increment and IAU weights.
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      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
+      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
+      REAL(KIND=dp) :: ditdin_date     ! Date YYYYMMDD.HHMMSS of background time step for DI
+      REAL(KIND=dp) :: ditiaustr_date  ! Date YYYYMMDD.HHMMSS of IAU interval start time step
+      REAL(KIND=dp) :: ditiaufin_date  ! Date YYYYMMDD.HHMMSS of IAU interval final time step
+
+      REAL(wp) :: znorm        ! Normalization factor for IAU weights
+      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), ALLOCATABLE, DIMENSION(:,:) ::   zhdiv   ! 2D workspace
+      !!
+      NAMELIST/nam_asminc/ ln_bkgwri,                                      &
+         &                 ln_trainc, ln_dyninc, ln_sshinc,                &
+         &                 ln_asmdin, ln_asmiau,                           &
+         &                 nitbkg, nitdin, nitiaustr, nitiaufin, niaufn,   &
+         &                 ln_salfix, salfixmin, nn_divdmp
+      !!----------------------------------------------------------------------
+
+      !-----------------------------------------------------------------------
+      ! Read Namelist nam_asminc : assimilation increment interface
+      !-----------------------------------------------------------------------
+      ln_seaiceinc   = .FALSE.
+      ln_temnofreeze = .FALSE.
+
+      REWIND( numnam_ref )              ! Namelist nam_asminc in reference namelist : Assimilation increment
+      READ  ( numnam_ref, nam_asminc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_asminc in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_asminc in configuration namelist : Assimilation increment
+      READ  ( numnam_cfg, nam_asminc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nam_asminc in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_asminc )
+
+      ! Control print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'asm_inc_init : Assimilation increment initialization :'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namasm : set assimilation increment parameters'
+         WRITE(numout,*) '      Logical switch for writing out background state          ln_bkgwri = ', ln_bkgwri
+         WRITE(numout,*) '      Logical switch for applying tracer increments            ln_trainc = ', ln_trainc
+         WRITE(numout,*) '      Logical switch for applying velocity increments          ln_dyninc = ', ln_dyninc
+         WRITE(numout,*) '      Logical switch for applying SSH increments               ln_sshinc = ', ln_sshinc
+         WRITE(numout,*) '      Logical switch for Direct Initialization (DI)            ln_asmdin = ', ln_asmdin
+         WRITE(numout,*) '      Logical switch for applying sea ice increments        ln_seaiceinc = ', ln_seaiceinc
+         WRITE(numout,*) '      Logical switch for Incremental Analysis Updating (IAU)   ln_asmiau = ', ln_asmiau
+         WRITE(numout,*) '      Timestep of background in [0,nitend-nit000-1]            nitbkg    = ', nitbkg
+         WRITE(numout,*) '      Timestep of background for DI in [0,nitend-nit000-1]     nitdin    = ', nitdin
+         WRITE(numout,*) '      Timestep of start of IAU interval in [0,nitend-nit000-1] nitiaustr = ', nitiaustr
+         WRITE(numout,*) '      Timestep of end of IAU interval in [0,nitend-nit000-1]   nitiaufin = ', nitiaufin
+         WRITE(numout,*) '      Type of IAU weighting function                           niaufn    = ', niaufn
+         WRITE(numout,*) '      Logical switch for ensuring that the sa > salfixmin      ln_salfix = ', ln_salfix
+         WRITE(numout,*) '      Minimum salinity after applying the increments           salfixmin = ', salfixmin
+      ENDIF
+
+      nitbkg_r    = nitbkg    + nit000 - 1            ! Background time referenced to nit000
+      nitdin_r    = nitdin    + nit000 - 1            ! Background time for DI referenced to nit000
+      nitiaustr_r = nitiaustr + nit000 - 1            ! Start of IAU interval referenced to nit000
+      nitiaufin_r = nitiaufin + nit000 - 1            ! End of IAU interval referenced to nit000
+
+      iiauper     = nitiaufin_r - nitiaustr_r + 1     ! IAU interval length
+      icycper     = nitend      - nit000      + 1     ! Cycle interval length
+
+      CALL calc_date( nitend     , ditend_date    )   ! Date of final time step
+      CALL calc_date( nitbkg_r   , ditbkg_date    )   ! Background time for Jb referenced to ndate0
+      CALL calc_date( nitdin_r   , ditdin_date    )   ! Background time for DI referenced to ndate0
+      CALL calc_date( nitiaustr_r, ditiaustr_date )   ! IAU start time referenced to ndate0
+      CALL calc_date( nitiaufin_r, ditiaufin_date )   ! IAU end time referenced to ndate0
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   Time steps referenced to current cycle:'
+         WRITE(numout,*) '       iitrst      = ', nit000 - 1
+         WRITE(numout,*) '       nit000      = ', nit000
+         WRITE(numout,*) '       nitend      = ', nitend
+         WRITE(numout,*) '       nitbkg_r    = ', nitbkg_r
+         WRITE(numout,*) '       nitdin_r    = ', nitdin_r
+         WRITE(numout,*) '       nitiaustr_r = ', nitiaustr_r
+         WRITE(numout,*) '       nitiaufin_r = ', nitiaufin_r
+         WRITE(numout,*)
+         WRITE(numout,*) '   Dates referenced to current cycle:'
+         WRITE(numout,*) '       ndastp         = ', ndastp
+         WRITE(numout,*) '       ndate0         = ', ndate0
+         WRITE(numout,*) '       nn_time0       = ', nn_time0
+         WRITE(numout,*) '       ditend_date    = ', ditend_date
+         WRITE(numout,*) '       ditbkg_date    = ', ditbkg_date
+         WRITE(numout,*) '       ditdin_date    = ', ditdin_date
+         WRITE(numout,*) '       ditiaustr_date = ', ditiaustr_date
+         WRITE(numout,*) '       ditiaufin_date = ', ditiaufin_date
+      ENDIF
+
+
+      IF ( ( ln_asmdin ).AND.( ln_asmiau ) )   &
+         & CALL ctl_stop( ' ln_asmdin and ln_asmiau :', &
+         &                ' Choose Direct Initialization OR Incremental Analysis Updating')
+
+      IF (      ( ( .NOT. ln_asmdin ).AND.( .NOT. ln_asmiau ) ) &
+           .AND.( ( ln_trainc ).OR.( ln_dyninc ).OR.( ln_sshinc ) .OR. ( ln_seaiceinc) )) &
+         & CALL ctl_stop( ' One or more of ln_trainc, ln_dyninc, ln_sshinc and ln_seaiceinc is set to .true.', &
+         &                ' but ln_asmdin and ln_asmiau are both set to .false. :', &
+         &                ' Inconsistent options')
+
+      IF ( ( niaufn /= 0 ).AND.( niaufn /= 1 ) ) &
+         & CALL ctl_stop( ' niaufn /= 0 or niaufn /=1 :',  &
+         &                ' Type IAU weighting function is invalid')
+
+      IF ( ( .NOT. ln_trainc ).AND.( .NOT. ln_dyninc ).AND.( .NOT. ln_sshinc ).AND.( .NOT. ln_seaiceinc ) &
+         &                     )  &
+         & CALL ctl_warn( ' ln_trainc, ln_dyninc, ln_sshinc and ln_seaiceinc are set to .false. :', &
+         &                ' The assimilation increments are not applied')
+
+      IF ( ( ln_asmiau ).AND.( nitiaustr == nitiaufin ) ) &
+         & CALL ctl_stop( ' nitiaustr = nitiaufin :',  &
+         &                ' IAU interval is of zero length')
+
+      IF ( ( ln_asmiau ).AND.( ( nitiaustr_r < nit000 ).OR.( nitiaufin_r > nitend ) ) ) &
+         & CALL ctl_stop( ' nitiaustr or nitiaufin :',  &
+         &                ' IAU starting or final time step is outside the cycle interval', &
+         &                 ' Valid range nit000 to nitend')
+
+      IF ( ( nitbkg_r < nit000 - 1 ).OR.( nitbkg_r > nitend ) ) &
+         & CALL ctl_stop( ' nitbkg :',  &
+         &                ' Background time step is outside the cycle interval')
+
+      IF ( ( nitdin_r < nit000 - 1 ).OR.( nitdin_r > nitend ) ) &
+         & CALL ctl_stop( ' nitdin :',  &
+         &                ' Background time step for Direct Initialization is outside', &
+         &                ' the cycle interval')
+
+      IF ( nstop > 0 ) RETURN       ! if there are any errors then go no further
+
+      !--------------------------------------------------------------------
+      ! Initialize the Incremental Analysis Updating weighting function
+      !--------------------------------------------------------------------
+
+      IF( ln_asmiau ) THEN
+         !
+         ALLOCATE( wgtiau( icycper ) )
+         !
+         wgtiau(:) = 0._wp
+         !
+         !                                !---------------------------------------------------------
+         IF( niaufn == 0 ) THEN           ! Constant IAU forcing 
+            !                             !---------------------------------------------------------
+            DO jt = 1, iiauper
+               wgtiau(jt+nitiaustr-1) = 1.0 / REAL( iiauper )
+            END DO
+            !                             !---------------------------------------------------------
+         ELSEIF ( niaufn == 1 ) THEN      ! Linear hat-like, centred in middle of IAU interval 
+            !                             !---------------------------------------------------------
+            ! Compute the normalization factor
+            znorm = 0._wp
+            IF( MOD( iiauper, 2 ) == 0 ) THEN   ! Even number of time steps in IAU interval
+               imid = iiauper / 2 
+               DO jt = 1, imid
+                  znorm = znorm + REAL( jt )
+               END DO
+               znorm = 2.0 * znorm
+            ELSE                                ! Odd number of time steps in IAU interval
+               imid = ( iiauper + 1 ) / 2        
+               DO jt = 1, imid - 1
+                  znorm = znorm + REAL( jt )
+               END DO
+               znorm = 2.0 * znorm + REAL( imid )
+            ENDIF
+            znorm = 1.0 / znorm
+            !
+            DO jt = 1, imid - 1
+               wgtiau(jt+nitiaustr-1) = REAL( jt ) * znorm
+            END DO
+            DO jt = imid, iiauper
+               wgtiau(jt+nitiaustr-1) = REAL( iiauper - jt + 1 ) * znorm
+            END DO
+            !
+         ENDIF
+
+         ! Test that the integral of the weights over the weighting interval equals 1
+          IF(lwp) THEN
+             WRITE(numout,*)
+             WRITE(numout,*) 'asm_inc_init : IAU weights'
+             WRITE(numout,*) '~~~~~~~~~~~~'
+             WRITE(numout,*) '             time step         IAU  weight'
+             WRITE(numout,*) '             =========     ====================='
+             ztotwgt = 0.0
+             DO jt = 1, icycper
+                ztotwgt = ztotwgt + wgtiau(jt)
+                WRITE(numout,*) '         ', jt, '       ', wgtiau(jt) 
+             END DO   
+             WRITE(numout,*) '         ==================================='
+             WRITE(numout,*) '         Time-integrated weight = ', ztotwgt
+             WRITE(numout,*) '         ==================================='
+          ENDIF
+         
+      ENDIF
+
+      !--------------------------------------------------------------------
+      ! Allocate and initialize the increment arrays
+      !--------------------------------------------------------------------
+
+      ALLOCATE( t_bkginc     (jpi,jpj,jpk) )   ;   t_bkginc     (:,:,:) = 0._wp
+      ALLOCATE( s_bkginc     (jpi,jpj,jpk) )   ;   s_bkginc     (:,:,:) = 0._wp
+      ALLOCATE( u_bkginc     (jpi,jpj,jpk) )   ;   u_bkginc     (:,:,:) = 0._wp
+      ALLOCATE( v_bkginc     (jpi,jpj,jpk) )   ;   v_bkginc     (:,:,:) = 0._wp
+      ALLOCATE( ssh_bkginc   (jpi,jpj)     )   ;   ssh_bkginc   (:,:)   = 0._wp
+      ALLOCATE( seaice_bkginc(jpi,jpj)     )   ;   seaice_bkginc(:,:)   = 0._wp
+#if defined key_asminc
+      ALLOCATE( ssh_iau      (jpi,jpj)     )   ;   ssh_iau      (:,:)   = 0._wp
+#endif
+#if defined key_cice && defined key_asminc
+      ALLOCATE( ndaice_da    (jpi,jpj)     )   ;   ndaice_da    (:,:)   = 0._wp
+#endif
+      !
+      IF ( ln_trainc .OR. ln_dyninc .OR.   &       !--------------------------------------
+         & ln_sshinc .OR. ln_seaiceinc   ) THEN    ! Read the increments from file
+         !                                         !--------------------------------------
+         CALL iom_open( c_asminc, inum )
+         !
+         CALL iom_get( inum, 'time'       , zdate_inc   ) 
+         CALL iom_get( inum, 'z_inc_dateb', z_inc_dateb )
+         CALL iom_get( inum, 'z_inc_datef', z_inc_datef )
+         z_inc_dateb = zdate_inc
+         z_inc_datef = zdate_inc
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) 
+            WRITE(numout,*) 'asm_inc_init : Assimilation increments valid between dates ', z_inc_dateb,' and ', z_inc_datef
+            WRITE(numout,*) '~~~~~~~~~~~~'
+         ENDIF
+         !
+         IF ( ( z_inc_dateb < ndastp + nn_time0*0.0001_wp ) .OR.   &
+            & ( z_inc_datef > ditend_date ) ) &
+            &    CALL ctl_warn( ' Validity time of assimilation increments is ', &
+            &                   ' outside the assimilation interval' )
+
+         IF ( ( ln_asmdin ).AND.( zdate_inc /= ditdin_date ) ) &
+            & CALL ctl_warn( ' Validity time of assimilation increments does ', &
+            &                ' not agree with Direct Initialization time' )
+
+         IF ( ln_trainc ) THEN   
+            CALL iom_get( inum, jpdom_autoglo, 'bckint', t_bkginc, 1 )
+            CALL iom_get( inum, jpdom_autoglo, 'bckins', s_bkginc, 1 )
+            ! Apply the masks
+            t_bkginc(:,:,:) = t_bkginc(:,:,:) * tmask(:,:,:)
+            s_bkginc(:,:,:) = s_bkginc(:,:,:) * tmask(:,:,:)
+            ! Set missing increments to 0.0 rather than 1e+20
+            ! to allow for differences in masks
+            WHERE( ABS( t_bkginc(:,:,:) ) > 1.0e+10 ) t_bkginc(:,:,:) = 0.0
+            WHERE( ABS( s_bkginc(:,:,:) ) > 1.0e+10 ) s_bkginc(:,:,:) = 0.0
+         ENDIF
+
+         IF ( ln_dyninc ) THEN   
+            CALL iom_get( inum, jpdom_autoglo, 'bckinu', u_bkginc, 1 )              
+            CALL iom_get( inum, jpdom_autoglo, 'bckinv', v_bkginc, 1 )              
+            ! Apply the masks
+            u_bkginc(:,:,:) = u_bkginc(:,:,:) * umask(:,:,:)
+            v_bkginc(:,:,:) = v_bkginc(:,:,:) * vmask(:,:,:)
+            ! Set missing increments to 0.0 rather than 1e+20
+            ! to allow for differences in masks
+            WHERE( ABS( u_bkginc(:,:,:) ) > 1.0e+10 ) u_bkginc(:,:,:) = 0.0
+            WHERE( ABS( v_bkginc(:,:,:) ) > 1.0e+10 ) v_bkginc(:,:,:) = 0.0
+         ENDIF
+        
+         IF ( ln_sshinc ) THEN
+            CALL iom_get( inum, jpdom_autoglo, 'bckineta', ssh_bkginc, 1 )
+            ! Apply the masks
+            ssh_bkginc(:,:) = ssh_bkginc(:,:) * tmask(:,:,1)
+            ! Set missing increments to 0.0 rather than 1e+20
+            ! to allow for differences in masks
+            WHERE( ABS( ssh_bkginc(:,:) ) > 1.0e+10 ) ssh_bkginc(:,:) = 0.0
+         ENDIF
+
+         IF ( ln_seaiceinc ) THEN
+            CALL iom_get( inum, jpdom_autoglo, 'bckinseaice', seaice_bkginc, 1 )
+            ! Apply the masks
+            seaice_bkginc(:,:) = seaice_bkginc(:,:) * tmask(:,:,1)
+            ! Set missing increments to 0.0 rather than 1e+20
+            ! to allow for differences in masks
+            WHERE( ABS( seaice_bkginc(:,:) ) > 1.0e+10 ) seaice_bkginc(:,:) = 0.0
+         ENDIF
+         !
+         CALL iom_close( inum )
+         !
+      ENDIF
+      !
+      !                                            !--------------------------------------
+      IF ( ln_dyninc .AND. nn_divdmp > 0 ) THEN    ! Apply divergence damping filter
+         !                                         !--------------------------------------
+         ALLOCATE( zhdiv(jpi,jpj) ) 
+         !
+         DO jt = 1, nn_divdmp
+            !
+            DO jk = 1, jpkm1           ! zhdiv = e1e1 * div
+               zhdiv(:,:) = 0._wp
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zhdiv(ji,jj) = (  e2u(ji  ,jj) * e3u_n(ji  ,jj,jk) * u_bkginc(ji  ,jj,jk)    &
+                        &            - e2u(ji-1,jj) * e3u_n(ji-1,jj,jk) * u_bkginc(ji-1,jj,jk)    &
+                        &            + e1v(ji,jj  ) * e3v_n(ji,jj  ,jk) * v_bkginc(ji,jj  ,jk)    &
+                        &            - e1v(ji,jj-1) * e3v_n(ji,jj-1,jk) * v_bkginc(ji,jj-1,jk)  ) / e3t_n(ji,jj,jk)
+                  END DO
+               END DO
+               CALL lbc_lnk( 'asminc', zhdiv, 'T', 1. )   ! lateral boundary cond. (no sign change)
+               !
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     u_bkginc(ji,jj,jk) = u_bkginc(ji,jj,jk)                         &
+                        &               + 0.2_wp * ( zhdiv(ji+1,jj) - zhdiv(ji  ,jj) ) * r1_e1u(ji,jj) * umask(ji,jj,jk)
+                     v_bkginc(ji,jj,jk) = v_bkginc(ji,jj,jk)                         &
+                        &               + 0.2_wp * ( zhdiv(ji,jj+1) - zhdiv(ji,jj  ) ) * r1_e2v(ji,jj) * vmask(ji,jj,jk) 
+                  END DO
+               END DO
+            END DO
+            !
+         END DO
+         !
+         DEALLOCATE( zhdiv ) 
+         !
+      ENDIF
+      !
+      !                             !-----------------------------------------------------
+      IF ( ln_asmdin ) THEN         ! Allocate and initialize the background state arrays
+         !                          !-----------------------------------------------------
+         !
+         ALLOCATE( t_bkg  (jpi,jpj,jpk) )   ;   t_bkg  (:,:,:) = 0._wp
+         ALLOCATE( s_bkg  (jpi,jpj,jpk) )   ;   s_bkg  (:,:,:) = 0._wp
+         ALLOCATE( u_bkg  (jpi,jpj,jpk) )   ;   u_bkg  (:,:,:) = 0._wp
+         ALLOCATE( v_bkg  (jpi,jpj,jpk) )   ;   v_bkg  (:,:,:) = 0._wp
+         ALLOCATE( ssh_bkg(jpi,jpj)     )   ;   ssh_bkg(:,:)   = 0._wp
+         !
+         !
+         !--------------------------------------------------------------------
+         ! Read from file the background state at analysis time
+         !--------------------------------------------------------------------
+         !
+         CALL iom_open( c_asmdin, inum )
+         !
+         CALL iom_get( inum, 'rdastp', zdate_bkg ) 
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) 
+            WRITE(numout,*) '   ==>>>  Assimilation background state valid at : ', zdate_bkg
+            WRITE(numout,*)
+         ENDIF
+         !
+         IF ( zdate_bkg /= ditdin_date )   &
+            & CALL ctl_warn( ' Validity time of assimilation background state does', &
+            &                ' not agree with Direct Initialization time' )
+         !
+         IF ( ln_trainc ) THEN   
+            CALL iom_get( inum, jpdom_autoglo, 'tn', t_bkg )
+            CALL iom_get( inum, jpdom_autoglo, 'sn', s_bkg )
+            t_bkg(:,:,:) = t_bkg(:,:,:) * tmask(:,:,:)
+            s_bkg(:,:,:) = s_bkg(:,:,:) * tmask(:,:,:)
+         ENDIF
+         !
+         IF ( ln_dyninc ) THEN   
+            CALL iom_get( inum, jpdom_autoglo, 'un', u_bkg )
+            CALL iom_get( inum, jpdom_autoglo, 'vn', v_bkg )
+            u_bkg(:,:,:) = u_bkg(:,:,:) * umask(:,:,:)
+            v_bkg(:,:,:) = v_bkg(:,:,:) * vmask(:,:,:)
+         ENDIF
+         !
+         IF ( ln_sshinc ) THEN
+            CALL iom_get( inum, jpdom_autoglo, 'sshn', ssh_bkg )
+            ssh_bkg(:,:) = ssh_bkg(:,:) * tmask(:,:,1)
+         ENDIF
+         !
+         CALL iom_close( inum )
+         !
+      ENDIF
+      !
+      IF(lwp) WRITE(numout,*) '   ==>>>   Euler time step switch is ', neuler
+      !
+      IF( lk_asminc ) THEN                            !==  data assimilation  ==!
+         IF( ln_bkgwri )   CALL asm_bkg_wri( nit000 - 1 )      ! Output background fields
+         IF( ln_asmdin ) THEN                                  ! Direct initialization
+            IF( ln_trainc )   CALL tra_asm_inc( nit000 - 1 )      ! Tracers
+            IF( ln_dyninc )   CALL dyn_asm_inc( nit000 - 1 )      ! Dynamics
+            IF( ln_sshinc )   CALL ssh_asm_inc( nit000 - 1 )      ! SSH
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE asm_inc_init
+   
+   
+   SUBROUTINE tra_asm_inc( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE tra_asm_inc  ***
+      !!          
+      !! ** Purpose : Apply the tracer (T and S) assimilation increments
+      !!
+      !! ** Method  : Direct initialization or Incremental Analysis Updating
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) ::   kt   ! Current time step
+      !
+      INTEGER  :: ji, jj, jk
+      INTEGER  :: it
+      REAL(wp) :: zincwgt  ! IAU weight for current time step
+      REAL (wp), DIMENSION(jpi,jpj,jpk) :: fzptnz ! 3d freezing point values
+      !!----------------------------------------------------------------------
+      !
+      ! freezing point calculation taken from oc_fz_pt (but calculated for all depths) 
+      ! used to prevent the applied increments taking the temperature below the local freezing point 
+      DO jk = 1, jpkm1
+        CALL eos_fzp( tsn(:,:,jk,jp_sal), fzptnz(:,:,jk), gdept_n(:,:,jk) )
+      END DO
+         !
+         !                             !--------------------------------------
+      IF ( ln_asmiau ) THEN            ! Incremental Analysis Updating
+         !                             !--------------------------------------
+         !
+         IF ( ( kt >= nitiaustr_r ).AND.( kt <= nitiaufin_r ) ) THEN
+            !
+            it = kt - nit000 + 1
+            zincwgt = wgtiau(it) / rdt   ! IAU weight for the current time step
+            !
+            IF(lwp) THEN
+               WRITE(numout,*) 
+               WRITE(numout,*) 'tra_asm_inc : Tracer IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
+               WRITE(numout,*) '~~~~~~~~~~~~'
+            ENDIF
+            !
+            ! Update the tracer tendencies
+            DO jk = 1, jpkm1
+               IF (ln_temnofreeze) THEN
+                  ! Do not apply negative increments if the temperature will fall below freezing
+                  WHERE(t_bkginc(:,:,jk) > 0.0_wp .OR. &
+                     &   tsn(:,:,jk,jp_tem) + tsa(:,:,jk,jp_tem) + t_bkginc(:,:,jk) * wgtiau(it) > fzptnz(:,:,jk) ) 
+                     tsa(:,:,jk,jp_tem) = tsa(:,:,jk,jp_tem) + t_bkginc(:,:,jk) * zincwgt  
+                  END WHERE
+               ELSE
+                  tsa(:,:,jk,jp_tem) = tsa(:,:,jk,jp_tem) + t_bkginc(:,:,jk) * zincwgt  
+               ENDIF
+               IF (ln_salfix) THEN
+                  ! Do not apply negative increments if the salinity will fall below a specified
+                  ! minimum value salfixmin
+                  WHERE(s_bkginc(:,:,jk) > 0.0_wp .OR. &
+                     &   tsn(:,:,jk,jp_sal) + tsa(:,:,jk,jp_sal) + s_bkginc(:,:,jk) * wgtiau(it) > salfixmin ) 
+                     tsa(:,:,jk,jp_sal) = tsa(:,:,jk,jp_sal) + s_bkginc(:,:,jk) * zincwgt
+                  END WHERE
+               ELSE
+                  tsa(:,:,jk,jp_sal) = tsa(:,:,jk,jp_sal) + s_bkginc(:,:,jk) * zincwgt
+               ENDIF
+            END DO
+            !
+         ENDIF
+         !
+         IF ( kt == nitiaufin_r + 1  ) THEN   ! For bias crcn to work
+            DEALLOCATE( t_bkginc )
+            DEALLOCATE( s_bkginc )
+         ENDIF
+         !                             !--------------------------------------
+      ELSEIF ( ln_asmdin ) THEN        ! Direct Initialization
+         !                             !--------------------------------------
+         !            
+         IF ( kt == nitdin_r ) THEN
+            !
+            neuler = 0  ! Force Euler forward step
+            !
+            ! Initialize the now fields with the background + increment
+            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(:,:,:) ) 
+                  tsn(:,:,:,jp_tem) = t_bkg(:,:,:) + t_bkginc(:,:,:)   
+               END WHERE
+            ELSE
+               tsn(:,:,:,jp_tem) = t_bkg(:,:,:) + t_bkginc(:,:,:)   
+            ENDIF
+            IF (ln_salfix) THEN
+               ! 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 ) 
+                  tsn(:,:,:,jp_sal) = s_bkg(:,:,:) + s_bkginc(:,:,:)   
+               END WHERE
+            ELSE
+               tsn(:,:,:,jp_sal) = s_bkg(:,:,:) + s_bkginc(:,:,:)   
+            ENDIF
+
+            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 .AND. .NOT. ln_isfcav)      &
+               &  CALL zps_hde    ( kt, jpts, tsb, gtsu, gtsv,        &  ! Partial steps: before horizontal gradient
+               &                              rhd, gru , grv          )  ! of t, s, rd at the last ocean level
+            IF( ln_zps .AND. .NOT. lk_c1d .AND.       ln_isfcav)      &
+               &  CALL zps_hde_isf( nit000, jpts, tsb, gtsu, gtsv, gtui, gtvi,    &    ! Partial steps for top cell (ISF)
+               &                                  rhd, gru , grv , grui, grvi     )    ! of t, s, rd at the last ocean level
+
+            DEALLOCATE( t_bkginc )
+            DEALLOCATE( s_bkginc )
+            DEALLOCATE( t_bkg    )
+            DEALLOCATE( s_bkg    )
+         ENDIF
+         !  
+      ENDIF
+      ! Perhaps the following call should be in step
+      IF ( ln_seaiceinc  )   CALL seaice_asm_inc ( kt )   ! apply sea ice concentration increment
+      !
+   END SUBROUTINE tra_asm_inc
+
+
+   SUBROUTINE dyn_asm_inc( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dyn_asm_inc  ***
+      !!          
+      !! ** Purpose : Apply the dynamics (u and v) assimilation increments.
+      !!
+      !! ** Method  : Direct initialization or Incremental Analysis Updating.
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) :: kt   ! Current time step
+      !
+      INTEGER :: jk
+      INTEGER :: it
+      REAL(wp) :: zincwgt  ! IAU weight for current time step
+      !!----------------------------------------------------------------------
+      !
+      !                          !--------------------------------------------
+      IF ( ln_asmiau ) THEN      ! Incremental Analysis Updating
+         !                       !--------------------------------------------
+         !
+         IF ( ( kt >= nitiaustr_r ).AND.( kt <= nitiaufin_r ) ) THEN
+            !
+            it = kt - nit000 + 1
+            zincwgt = wgtiau(it) / rdt   ! IAU weight for the current time step
+            !
+            IF(lwp) THEN
+               WRITE(numout,*) 
+               WRITE(numout,*) 'dyn_asm_inc : Dynamics IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
+               WRITE(numout,*) '~~~~~~~~~~~~'
+            ENDIF
+            !
+            ! Update the dynamic tendencies
+            DO jk = 1, jpkm1
+               ua(:,:,jk) = ua(:,:,jk) + u_bkginc(:,:,jk) * zincwgt
+               va(:,:,jk) = va(:,:,jk) + v_bkginc(:,:,jk) * zincwgt
+            END DO
+            !
+            IF ( kt == nitiaufin_r ) THEN
+               DEALLOCATE( u_bkginc )
+               DEALLOCATE( v_bkginc )
+            ENDIF
+            !
+         ENDIF
+         !                          !-----------------------------------------
+      ELSEIF ( ln_asmdin ) THEN     ! Direct Initialization
+         !                          !-----------------------------------------
+         !         
+         IF ( kt == nitdin_r ) THEN
+            !
+            neuler = 0                    ! Force Euler forward step
+            !
+            ! Initialize the now fields with the background + increment
+            un(:,:,:) = u_bkg(:,:,:) + u_bkginc(:,:,:)
+            vn(:,:,:) = v_bkg(:,:,:) + v_bkginc(:,:,:)  
+            !
+            ub(:,:,:) = un(:,:,:)         ! Update before fields
+            vb(:,:,:) = vn(:,:,:)
+            !
+            DEALLOCATE( u_bkg    )
+            DEALLOCATE( v_bkg    )
+            DEALLOCATE( u_bkginc )
+            DEALLOCATE( v_bkginc )
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE dyn_asm_inc
+
+
+   SUBROUTINE ssh_asm_inc( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ssh_asm_inc  ***
+      !!          
+      !! ** Purpose : Apply the sea surface height assimilation increment.
+      !!
+      !! ** Method  : Direct initialization or Incremental Analysis Updating.
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) :: kt   ! Current time step
+      !
+      INTEGER :: it
+      INTEGER :: jk
+      REAL(wp) :: zincwgt  ! IAU weight for current time step
+      !!----------------------------------------------------------------------
+      !
+      !                             !-----------------------------------------
+      IF ( ln_asmiau ) THEN         ! Incremental Analysis Updating
+         !                          !-----------------------------------------
+         !
+         IF ( ( kt >= nitiaustr_r ).AND.( kt <= nitiaufin_r ) ) THEN
+            !
+            it = kt - nit000 + 1
+            zincwgt = wgtiau(it) / rdt   ! IAU weight for the current time step
+            !
+            IF(lwp) THEN
+               WRITE(numout,*) 
+               WRITE(numout,*) 'ssh_asm_inc : SSH IAU at time step = ', &
+                  &  kt,' with IAU weight = ', wgtiau(it)
+               WRITE(numout,*) '~~~~~~~~~~~~'
+            ENDIF
+            !
+            ! Save the tendency associated with the IAU weighted SSH increment
+            ! (applied in dynspg.*)
+#if defined key_asminc
+            ssh_iau(:,:) = ssh_bkginc(:,:) * zincwgt
+#endif
+            !
+         ELSE IF( kt == nitiaufin_r+1 ) THEN
+            !
+            ! test on ssh_bkginc needed as ssh_asm_inc is called twice by time step
+            IF (ALLOCATED(ssh_bkginc)) DEALLOCATE( ssh_bkginc )
+            !
+#if defined key_asminc
+            ssh_iau(:,:) = 0._wp
+#endif
+            !
+         ENDIF
+         !                          !-----------------------------------------
+      ELSEIF ( ln_asmdin ) THEN     ! Direct Initialization
+         !                          !-----------------------------------------
+         !
+         IF ( kt == nitdin_r ) THEN
+            !
+            neuler = 0                                   ! Force Euler forward step
+            !
+            sshn(:,:) = ssh_bkg(:,:) + ssh_bkginc(:,:)   ! Initialize the now fields the background + increment
+            !
+            sshb(:,:) = sshn(:,:)                        ! Update before fields
+            e3t_b(:,:,:) = e3t_n(:,:,:)
+!!gm why not e3u_b, e3v_b, gdept_b ????
+            !
+            DEALLOCATE( ssh_bkg    )
+            DEALLOCATE( ssh_bkginc )
+            !
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE ssh_asm_inc
+
+
+   SUBROUTINE ssh_asm_div( kt, phdivn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ssh_asm_div  ***
+      !!
+      !! ** Purpose :   ssh increment with z* is incorporated via a correction of the local divergence          
+      !!                across all the water column
+      !!
+      !! ** Method  :
+      !!                CAUTION : sshiau is positive (inflow) decreasing the
+      !!                          divergence and expressed in m/s
+      !!
+      !! ** Action  :   phdivn   decreased by the ssh increment
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) :: kt                               ! ocean time-step index
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   phdivn   ! horizontal divergence
+      !!
+      INTEGER  ::   jk                                        ! dummy loop index
+      REAL(wp), DIMENSION(:,:)  , POINTER       ::   ztim     ! local array
+      !!----------------------------------------------------------------------
+      ! 
+#if defined key_asminc
+      CALL ssh_asm_inc( kt ) !==   (calculate increments)
+      !
+      IF( ln_linssh ) THEN 
+         phdivn(:,:,1) = phdivn(:,:,1) - ssh_iau(:,:) / e3t_n(:,:,1) * tmask(:,:,1)
+      ELSE 
+         ALLOCATE( ztim(jpi,jpj) )
+         ztim(:,:) = ssh_iau(:,:) / ( ht_n(:,:) + 1.0 - ssmask(:,:) )
+         DO jk = 1, jpkm1                                 
+            phdivn(:,:,jk) = phdivn(:,:,jk) - ztim(:,:) * tmask(:,:,jk) 
+         END DO
+         !
+         DEALLOCATE(ztim)
+      ENDIF
+#endif
+      !
+   END SUBROUTINE ssh_asm_div
+
+
+   SUBROUTINE seaice_asm_inc( kt, kindic )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE seaice_asm_inc  ***
+      !!          
+      !! ** Purpose : Apply the sea ice assimilation increment.
+      !!
+      !! ** Method  : Direct initialization or Incremental Analysis Updating.
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in)           ::   kt       ! Current time step
+      INTEGER, INTENT(in), OPTIONAL ::   kindic   ! flag for disabling the deallocation
+      !
+      INTEGER  ::   it
+      REAL(wp) ::   zincwgt   ! IAU weight for current time step
+#if defined key_si3
+      REAL(wp), DIMENSION(jpi,jpj) ::   zofrld, zohicif, zseaicendg, zhicifinc
+      REAL(wp) ::   zhicifmin = 0.5_wp      ! ice minimum depth in metres
+#endif
+      !!----------------------------------------------------------------------
+      !
+      !                             !-----------------------------------------
+      IF ( ln_asmiau ) THEN         ! Incremental Analysis Updating
+         !                          !-----------------------------------------
+         !
+         IF ( ( kt >= nitiaustr_r ).AND.( kt <= nitiaufin_r ) ) THEN
+            !
+            it = kt - nit000 + 1
+            zincwgt = wgtiau(it)      ! IAU weight for the current time step 
+            ! note this is not a tendency so should not be divided by rdt (as with the tracer and other increments)
+            !
+            IF(lwp) THEN
+               WRITE(numout,*) 
+               WRITE(numout,*) 'seaice_asm_inc : sea ice conc IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
+               WRITE(numout,*) '~~~~~~~~~~~~'
+            ENDIF
+            !
+            ! Sea-ice : SI3 case
+            !
+#if defined key_si3
+            zofrld (:,:) = 1._wp - at_i(:,:)
+            zohicif(:,:) = hm_i(:,:)
+            !
+            at_i  (:,:) = 1. - MIN( MAX( 1.-at_i  (:,:) - seaice_bkginc(:,:) * zincwgt, 0.0_wp), 1.0_wp)
+            at_i_b(:,:) = 1. - MIN( MAX( 1.-at_i_b(:,:) - seaice_bkginc(:,:) * zincwgt, 0.0_wp), 1.0_wp)
+            fr_i(:,:) = at_i(:,:)        ! adjust ice fraction
+            !
+            zseaicendg(:,:) = zofrld(:,:) - (1. - at_i(:,:))   ! find out actual sea ice nudge applied
+            !
+            ! Nudge sea ice depth to bring it up to a required minimum depth
+            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(:,:) < zhicifmin ) 
+               zhicifinc(:,:) = (zhicifmin - hm_i(:,:)) * zincwgt    
+            ELSEWHERE
+               zhicifinc(:,:) = 0.0_wp
+            END WHERE
+            !
+            ! nudge ice depth
+            hm_i (:,:) = hm_i (:,:) + zhicifinc(:,:)
+            !
+            ! seaice salinity balancing (to add)
+#endif
+            !
+#if defined key_cice && defined key_asminc
+            ! Sea-ice : CICE case. Pass ice increment tendency into CICE
+            ndaice_da(:,:) = seaice_bkginc(:,:) * zincwgt / rdt
+#endif
+            !
+            IF ( kt == nitiaufin_r ) THEN
+               DEALLOCATE( seaice_bkginc )
+            ENDIF
+            !
+         ELSE
+            !
+#if defined key_cice && defined key_asminc
+            ndaice_da(:,:) = 0._wp        ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+#endif
+            !
+         ENDIF
+         !                          !-----------------------------------------
+      ELSEIF ( ln_asmdin ) THEN     ! Direct Initialization
+         !                          !-----------------------------------------
+         !
+         IF ( kt == nitdin_r ) THEN
+            !
+            neuler = 0                    ! Force Euler forward step
+            !
+            ! Sea-ice : SI3 case
+            !
+#if defined key_si3
+            zofrld (:,:) = 1._wp - at_i(:,:)
+            zohicif(:,:) = hm_i(:,:)
+            ! 
+            ! Initialize the now fields the background + increment
+            at_i(:,:) = 1. - MIN( MAX( 1.-at_i(:,:) - seaice_bkginc(:,:), 0.0_wp), 1.0_wp)
+            at_i_b(:,:) = at_i(:,:) 
+            fr_i(:,:) = at_i(:,:)        ! adjust ice fraction
+            !
+            zseaicendg(:,:) = zofrld(:,:) - (1. - at_i(:,:))   ! find out actual sea ice nudge applied
+            !
+            ! Nudge sea ice depth to bring it up to a required minimum depth
+            WHERE( zseaicendg(:,:) > 0.0_wp .AND. hm_i(:,:) < zhicifmin ) 
+               zhicifinc(:,:) = zhicifmin - hm_i(:,:)
+            ELSEWHERE
+               zhicifinc(:,:) = 0.0_wp
+            END WHERE
+            !
+            ! nudge ice depth
+            hm_i (:,:) = hm_i (:,:) + zhicifinc(:,:)
+            !
+            ! seaice salinity balancing (to add)
+#endif
+            !
+#if defined key_cice && defined key_asminc
+            ! Sea-ice : CICE case. Pass ice increment tendency into CICE
+           ndaice_da(:,:) = seaice_bkginc(:,:) / rdt
+#endif
+            IF ( .NOT. PRESENT(kindic) ) THEN
+               DEALLOCATE( seaice_bkginc )
+            END IF
+            !
+         ELSE
+            !
+#if defined key_cice && defined key_asminc
+            ndaice_da(:,:) = 0._wp     ! Sea-ice : CICE case. Zero ice increment tendency into CICE
+#endif
+            !
+         ENDIF
+
+!#if defined defined key_si3 || defined key_cice
+!
+!            IF (ln_seaicebal ) THEN       
+!             !! balancing salinity increments
+!             !! simple case from limflx.F90 (doesn't include a mass flux)
+!             !! assumption is that as ice concentration is reduced or increased
+!             !! the snow and ice depths remain constant
+!             !! note that snow is being created where ice concentration is being increased
+!             !! - could be more sophisticated and
+!             !! not do this (but would need to alter h_snow)
+!
+!             usave(:,:,:)=sb(:,:,:)   ! use array as a temporary store
+!
+!             DO jj = 1, jpj
+!               DO ji = 1, jpi 
+!           ! calculate change in ice and snow mass per unit area
+!           ! positive values imply adding salt to the ocean (results from ice formation)
+!           ! fwf : ice formation and melting
+!
+!                 zfons = ( -nfresh_da(ji,jj)*soce + nfsalt_da(ji,jj) )*rdt
+!
+!           ! change salinity down to mixed layer depth
+!                 mld=hmld_kara(ji,jj)
+!
+!           ! prevent small mld
+!           ! less than 10m can cause salinity instability 
+!                 IF (mld < 10) mld=10
+!
+!           ! set to bottom of a level 
+!                 DO jk = jpk-1, 2, -1
+!                   IF ((mld > gdepw(ji,jj,jk)) .and. (mld < gdepw(ji,jj,jk+1))) THEN 
+!                     mld=gdepw(ji,jj,jk+1)
+!                     jkmax=jk
+!                   ENDIF
+!                 ENDDO
+!
+!            ! avoid applying salinity balancing in shallow water or on land
+!            ! 
+!
+!            ! dsal_ocn (psu kg m^-2) / (kg m^-3 * m)
+!
+!                 dsal_ocn=0.0_wp
+!                 sal_thresh=5.0_wp        ! minimum salinity threshold for salinity balancing
+!
+!                 if (tmask(ji,jj,1) > 0 .AND. tmask(ji,jj,jkmax) > 0 ) &
+!                              dsal_ocn = zfons / (rhop(ji,jj,1) * mld)
+!
+!           ! put increments in for levels in the mixed layer
+!           ! but prevent salinity below a threshold value 
+!
+!                   DO jk = 1, jkmax              
+!
+!                     IF (dsal_ocn > 0.0_wp .or. sb(ji,jj,jk)+dsal_ocn > sal_thresh) THEN 
+!                           sb(ji,jj,jk) = sb(ji,jj,jk) + dsal_ocn
+!                           sn(ji,jj,jk) = sn(ji,jj,jk) + dsal_ocn
+!                     ENDIF
+!
+!                   ENDDO
+!
+!      !            !  salt exchanges at the ice/ocean interface
+!      !            zpmess         = zfons / rdt_ice    ! rdt_ice is ice timestep
+!      !
+!      !! Adjust fsalt. A +ve fsalt means adding salt to ocean
+!      !!           fsalt(ji,jj) =  fsalt(ji,jj) + zpmess     ! adjust fsalt  
+!      !!               
+!      !!           emps(ji,jj) = emps(ji,jj) + zpmess        ! or adjust emps (see icestp1d) 
+!      !!                                                     ! E-P (kg m-2 s-2)
+!      !            emp(ji,jj) = emp(ji,jj) + zpmess          ! E-P (kg m-2 s-2)
+!               ENDDO !ji
+!             ENDDO !jj!
+!
+!            ENDIF !ln_seaicebal
+!
+!#endif
+         !
+      ENDIF
+      !
+   END SUBROUTINE seaice_asm_inc
+   
+   !!======================================================================
+END MODULE asminc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmpar.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmpar.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ASM/asmpar.F90	(revision 14097)
@@ -0,0 +1,29 @@
+MODULE asmpar
+   !!======================================================================
+   !!                       ***  MODULE asmpar  ***
+   !! Assimilation increment : Parameters for assimilation interface
+   !!======================================================================
+
+   IMPLICIT NONE
+   PRIVATE
+
+   CHARACTER(LEN=40), PUBLIC, PARAMETER ::   c_asmbkg = 'assim_background_state_Jb'   !: Filename for storing the background state
+   !                                                                                  !  for use in the Jb term
+   CHARACTER(LEN=40), PUBLIC, PARAMETER ::   c_asmdin = 'assim_background_state_DI'   !: Filename for storing the background state
+   !                                                                                  !  for direct initialization
+   CHARACTER(LEN=40), PUBLIC, PARAMETER ::   c_asmtrj = 'assim_trj'                   !: Filename for storing the reference trajectory
+   CHARACTER(LEN=40), PUBLIC, PARAMETER ::   c_asminc = 'assim_background_increments' !: Filename for storing the increments 
+   !                                                                                  !  to the background state
+
+   INTEGER, PUBLIC ::   nitbkg_r      !: Background time step referenced to nit000
+   INTEGER, PUBLIC ::   nitdin_r      !: Direct Initialization time step referenced to nit000
+   INTEGER, PUBLIC ::   nitiaustr_r   !: IAU starting time step referenced to nit000
+   INTEGER, PUBLIC ::   nitiaufin_r   !: IAU final time step referenced to nit000
+   INTEGER, PUBLIC ::   nittrjfrq     !: Frequency of trajectory output for 4D-VAR
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE asmpar
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdy_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdy_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdy_oce.F90	(revision 14097)
@@ -0,0 +1,174 @@
+MODULE bdy_oce
+   !!======================================================================
+   !!                       ***  MODULE bdy_oce   ***
+   !! Unstructured Open Boundary Cond. :   define related variables
+   !!======================================================================
+   !! History :  1.0  !  2001-05  (J. Chanut, A. Sellar)  Original code
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version     
+   !!            3.3  !  2010-09  (D. Storkey) add ice boundary conditions
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            3.6  !  2014-01  (C. Rousset) add ice boundary conditions for new model
+   !!            4.0  !  2018     (C. Rousset) SI3 compatibility
+   !!----------------------------------------------------------------------
+   USE par_oce         ! ocean parameters
+
+   IMPLICIT NONE
+   PUBLIC
+
+   INTEGER, PUBLIC, PARAMETER ::   jp_bdy  = 10       !: Maximum number of bdy sets
+   INTEGER, PUBLIC, PARAMETER ::   jpbgrd  = 3        !: Number of horizontal grid types used  (T, U, V)
+
+   TYPE, PUBLIC ::   OBC_INDEX    !: Indices and weights which define the open boundary
+      INTEGER ,          DIMENSION(jpbgrd) ::  nblen
+      INTEGER ,          DIMENSION(jpbgrd) ::  nblenrim
+      INTEGER ,          DIMENSION(jpbgrd) ::  nblenrim0
+      INTEGER , POINTER, DIMENSION(:,:)    ::  nbi
+      INTEGER , POINTER, DIMENSION(:,:)    ::  nbj
+      INTEGER , POINTER, DIMENSION(:,:)    ::  nbr
+      INTEGER , POINTER, DIMENSION(:,:)    ::  nbmap
+      INTEGER , POINTER, DIMENSION(:,:)    ::  ntreat
+      REAL(wp), POINTER, DIMENSION(:,:)    ::  nbw
+      REAL(wp), POINTER, DIMENSION(:,:)    ::  nbd
+      REAL(wp), POINTER, DIMENSION(:,:)    ::  nbdout
+      REAL(wp), POINTER, DIMENSION(:,:)    ::  flagu
+      REAL(wp), POINTER, DIMENSION(:,:)    ::  flagv
+   END TYPE OBC_INDEX
+
+   !! Logicals in OBC_DATA structure are true if the chosen algorithm requires this
+   !! field as external data. If true the data can come from external files
+   !! or model initial conditions. If false then no "external" data array
+   !! is required for this field. 
+
+   TYPE, PUBLIC ::   OBC_DATA     !: Storage for external data
+      INTEGER          , DIMENSION(2)   ::  nread
+      LOGICAL                           ::  lneed_ssh
+      LOGICAL                           ::  lneed_dyn2d
+      LOGICAL                           ::  lneed_dyn3d
+      LOGICAL                           ::  lneed_tra
+      LOGICAL                           ::  lneed_ice
+      REAL(wp), POINTER, DIMENSION(:)   ::  ssh
+      REAL(wp), POINTER, DIMENSION(:)   ::  u2d
+      REAL(wp), POINTER, DIMENSION(:)   ::  v2d
+      REAL(wp), POINTER, DIMENSION(:,:) ::  u3d
+      REAL(wp), POINTER, DIMENSION(:,:) ::  v3d
+      REAL(wp), POINTER, DIMENSION(:,:) ::  tem
+      REAL(wp), POINTER, DIMENSION(:,:) ::  sal
+      REAL(wp), POINTER, DIMENSION(:,:) ::  a_i    !: now ice leads fraction climatology
+      REAL(wp), POINTER, DIMENSION(:,:) ::  h_i    !: Now ice  thickness climatology
+      REAL(wp), POINTER, DIMENSION(:,:) ::  h_s    !: now snow thickness
+      REAL(wp), POINTER, DIMENSION(:,:) ::  t_i    !: now ice  temperature
+      REAL(wp), POINTER, DIMENSION(:,:) ::  t_s    !: now snow temperature
+      REAL(wp), POINTER, DIMENSION(:,:) ::  tsu    !: now surf temperature
+      REAL(wp), POINTER, DIMENSION(:,:) ::  s_i    !: now ice  salinity
+      REAL(wp), POINTER, DIMENSION(:,:) ::  aip    !: now ice  pond concentration
+      REAL(wp), POINTER, DIMENSION(:,:) ::  hip    !: now ice  pond depth
+      REAL(wp), POINTER, DIMENSION(:,:) ::  hil    !: now ice  pond lid depth
+#if defined key_top
+      CHARACTER(LEN=20)                   :: cn_obc  !: type of boundary condition to apply
+      REAL(wp)                            :: rn_fac  !: multiplicative scaling factor
+      REAL(wp), POINTER, DIMENSION(:,:)   :: trc     !: now field of the tracer
+      LOGICAL                             :: dmp     !: obc damping term
+#endif
+   END TYPE OBC_DATA
+
+   !!----------------------------------------------------------------------
+   !! Namelist variables
+   !!----------------------------------------------------------------------
+   !                                                   !!** nambdy **
+   LOGICAL, PUBLIC            ::   ln_bdy                   !: Unstructured Ocean Boundary Condition
+
+   CHARACTER(len=80), DIMENSION(jp_bdy) ::   cn_coords_file !: Name of bdy coordinates file
+   CHARACTER(len=80)                    ::   cn_mask_file   !: Name of bdy mask file
+   !
+   LOGICAL, DIMENSION(jp_bdy) ::   ln_coords_file           !: =T read bdy coordinates from file; 
+   !                                                        !: =F read bdy coordinates from namelist
+   LOGICAL                    ::   ln_mask_file             !: =T read bdymask from file
+   LOGICAL                    ::   ln_vol                   !: =T volume correction             
+   !
+   INTEGER                    ::   nb_bdy                   !: number of open boundary sets
+   INTEGER, DIMENSION(jp_bdy) ::   nn_rimwidth              !: boundary rim width for Flow Relaxation Scheme
+   INTEGER                    ::   nn_volctl                !: = 0 the total volume will have the variability of the surface Flux E-P 
+   !                                                        !  = 1 the volume will be constant during all the integration.
+   CHARACTER(len=20), DIMENSION(jp_bdy) ::   cn_dyn2d       ! Choice of boundary condition for barotropic variables (U,V,SSH)
+   INTEGER, DIMENSION(jp_bdy)           ::   nn_dyn2d_dta   !: = 0 use the initial state as bdy dta ; 
+                                                            !: = 1 read it in a NetCDF file
+                                                            !: = 2 read tidal harmonic forcing from a NetCDF file
+                                                            !: = 3 read external data AND tidal harmonic forcing from NetCDF files
+   CHARACTER(len=20), DIMENSION(jp_bdy) ::   cn_dyn3d       ! Choice of boundary condition for baroclinic velocities 
+   INTEGER, DIMENSION(jp_bdy)           ::   nn_dyn3d_dta   !: = 0 use the initial state as bdy dta ; 
+                                                            !: = 1 read it in a NetCDF file
+   CHARACTER(len=20), DIMENSION(jp_bdy) ::   cn_tra         ! Choice of boundary condition for active tracers (T and S)
+   INTEGER, DIMENSION(jp_bdy)           ::   nn_tra_dta     !: = 0 use the initial state as bdy dta ; 
+                                                            !: = 1 read it in a NetCDF file
+   LOGICAL , DIMENSION(jp_bdy) ::   ln_tra_dmp              !: =T Tracer damping
+   LOGICAL , DIMENSION(jp_bdy) ::   ln_dyn3d_dmp            !: =T Baroclinic velocity damping
+   REAL(wp), DIMENSION(jp_bdy) ::   rn_time_dmp             !: Damping time scale in days
+   REAL(wp), DIMENSION(jp_bdy) ::   rn_time_dmp_out         !: Damping time scale in days at radiation outflow points
+
+   CHARACTER(len=20), DIMENSION(jp_bdy) ::   cn_ice         ! Choice of boundary condition for sea ice variables 
+   INTEGER , DIMENSION(jp_bdy)          ::   nn_ice_dta     !: = 0 use the initial state as bdy dta ; 
+                                                            !: = 1 read it in a NetCDF file
+   ! 
+   !                                                   !!** nambdy_dta **
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_tem                !: temperature of incoming sea ice
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_sal                !: salinity    of incoming sea ice
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_age                !: age         of incoming sea ice
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_apnd               !: pond conc.  of incoming sea ice
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_hpnd               !: pond thick. of incoming sea ice
+   REAL(wp), DIMENSION(jp_bdy) ::   rice_hlid               !: pond lid thick. of incoming sea ice
+   !
+   !!----------------------------------------------------------------------
+   !! Global variables
+   !!----------------------------------------------------------------------
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), TARGET ::   bdytmask   !: Mask defining computational domain at T-points
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), TARGET ::   bdyumask   !: Mask defining computational domain at U-points
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), TARGET ::   bdyvmask   !: Mask defining computational domain at V-points
+
+   REAL(wp)                                    ::   bdysurftot !: Lateral surface of unstructured open boundary
+
+   !!----------------------------------------------------------------------
+   !! open boundary data variables
+   !!----------------------------------------------------------------------
+
+   INTEGER,  DIMENSION(jp_bdy)                     ::   nn_dta            !: =0 => *all* data is set to initial conditions
+                                                                          !: =1 => some data to be read in from data files
+!$AGRIF_DO_NOT_TREAT
+   TYPE(OBC_INDEX), DIMENSION(jp_bdy), TARGET      ::   idx_bdy           !: bdy indices (local process)
+   TYPE(OBC_DATA) , DIMENSION(jp_bdy), TARGET      ::   dta_bdy           !: bdy external data (local process)
+!$AGRIF_END_DO_NOT_TREAT
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lsend_bdy      !: mark needed communication for given boundary, grid and neighbour
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lrecv_bdy      !:  when searching in any direction
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lsend_bdyint   !: mark needed communication for given boundary, grid and neighbour
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lrecv_bdyint   !:  when searching towards the interior of the computational domain
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lsend_bdyext   !: mark needed communication for given boundary, grid and neighbour
+   LOGICAL, ALLOCATABLE, DIMENSION(:,:,:,:) ::   lrecv_bdyext   !:  when searching towards the exterior of the computational domain
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION bdy_oce_alloc()
+      !!----------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop, mpp_sum
+      !
+      INTEGER :: bdy_oce_alloc
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( bdytmask(jpi,jpj) , bdyumask(jpi,jpj), bdyvmask(jpi,jpj),     &  
+         &      STAT=bdy_oce_alloc )
+      !
+      ! Initialize masks 
+      bdytmask(:,:) = 1._wp
+      bdyumask(:,:) = 1._wp
+      bdyvmask(:,:) = 1._wp
+      ! 
+      CALL mpp_sum ( 'bdy_oce', bdy_oce_alloc )
+      IF( bdy_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'bdy_oce_alloc: failed to allocate arrays.' )
+      !
+   END FUNCTION bdy_oce_alloc
+
+   !!======================================================================
+END MODULE bdy_oce
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydta.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydta.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydta.F90	(revision 14097)
@@ -0,0 +1,719 @@
+MODULE bdydta
+   !!======================================================================
+   !!                       ***  MODULE bdydta  ***
+   !! Open boundary data : read the data for the unstructured open boundaries.
+   !!======================================================================
+   !! History :  1.0  !  2005-01  (J. Chanut, A. Sellar)  Original code
+   !!             -   !  2007-01  (D. Storkey) Update to use IOM module
+   !!             -   !  2007-07  (D. Storkey) add bdy_dta_fla
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.3  !  2010-09  (E.O'Dea) modifications for Shelf configurations 
+   !!            3.3  !  2010-09  (D.Storkey) add ice boundary conditions
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            3.6  !  2012-01  (C. Rousset) add ice boundary conditions for sea ice
+   !!            4.0  !  2018     (C. Rousset) SI3 compatibility
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!    bdy_dta      : read external data along open boundaries from file
+   !!    bdy_dta_init : initialise arrays etc for reading of external data
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE sbcapr         ! atmospheric pressure forcing
+   USE sbctide        ! Tidal forcing or not
+   USE bdy_oce        ! ocean open boundary conditions  
+   USE bdytides       ! tidal forcing at boundaries
+#if defined key_si3
+   USE ice            ! sea-ice variables
+   USE icevar         ! redistribute ice input into categories
+#endif
+   !
+   USE lib_mpp, ONLY: ctl_stop, ctl_nam
+   USE fldread        ! read input fields
+   USE iom            ! IOM library
+   USE in_out_manager ! I/O logical units
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_dta          ! routine called by step.F90 and dynspg_ts.F90
+   PUBLIC   bdy_dta_init     ! routine called by nemogcm.F90
+
+   INTEGER , PARAMETER ::   jpbdyfld  = 17    ! maximum number of files to read 
+   INTEGER , PARAMETER ::   jp_bdyssh = 1     ! 
+   INTEGER , PARAMETER ::   jp_bdyu2d = 2     ! 
+   INTEGER , PARAMETER ::   jp_bdyv2d = 3     !
+   INTEGER , PARAMETER ::   jp_bdyu3d = 4     !
+   INTEGER , PARAMETER ::   jp_bdyv3d = 5     !
+   INTEGER , PARAMETER ::   jp_bdytem = 6     ! 
+   INTEGER , PARAMETER ::   jp_bdysal = 7     ! 
+   INTEGER , PARAMETER ::   jp_bdya_i = 8     ! 
+   INTEGER , PARAMETER ::   jp_bdyh_i = 9     ! 
+   INTEGER , PARAMETER ::   jp_bdyh_s = 10    ! 
+   INTEGER , PARAMETER ::   jp_bdyt_i = 11    ! 
+   INTEGER , PARAMETER ::   jp_bdyt_s = 12    ! 
+   INTEGER , PARAMETER ::   jp_bdytsu = 13    ! 
+   INTEGER , PARAMETER ::   jp_bdys_i = 14    ! 
+   INTEGER , PARAMETER ::   jp_bdyaip = 15    ! 
+   INTEGER , PARAMETER ::   jp_bdyhip = 16    ! 
+   INTEGER , PARAMETER ::   jp_bdyhil = 17    ! 
+#if ! defined key_si3
+   INTEGER , PARAMETER ::   jpl = 1
+#endif
+
+!$AGRIF_DO_NOT_TREAT
+   TYPE(FLD), PUBLIC, ALLOCATABLE, DIMENSION(:,:), TARGET ::   bf   ! structure of input fields (file informations, fields read)
+!$AGRIF_END_DO_NOT_TREAT
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_dta( kt, kit, kt_offset )
+      !!----------------------------------------------------------------------
+      !!                   ***  SUBROUTINE bdy_dta  ***
+      !!                    
+      !! ** Purpose :   Update external data for open boundary conditions
+      !!
+      !! ** Method  :   Use fldread.F90
+      !!                
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in)           ::   kt           ! ocean time-step index 
+      INTEGER, INTENT(in), OPTIONAL ::   kit          ! subcycle time-step index (for timesplitting option)
+      INTEGER, INTENT(in), OPTIONAL ::   kt_offset    ! time offset in units of timesteps. NB. if kit
+      !                                               ! is present then units = subcycle timesteps.
+      !                                               ! kt_offset = 0 => get data at "now" time level
+      !                                               ! kt_offset = -1 => get data at "before" time level
+      !                                               ! kt_offset = +1 => get data at "after" time level
+      !                                               ! etc.
+      !
+      INTEGER ::  jbdy, jfld, jstart, jend, ib, jl    ! dummy loop indices
+      INTEGER ::  ii, ij, ik, igrd, ipl               ! local integers
+      TYPE(OBC_DATA)         , POINTER ::   dta_alias        ! short cut
+      TYPE(FLD), DIMENSION(:), POINTER ::   bf_alias
+      !!---------------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('bdy_dta')
+      !
+      ! Initialise data arrays once for all from initial conditions where required
+      !---------------------------------------------------------------------------
+      IF( kt == nit000 .AND. .NOT.PRESENT(kit) ) THEN
+
+         ! Calculate depth-mean currents
+         !-----------------------------
+
+         DO jbdy = 1, nb_bdy
+            !
+            IF( nn_dyn2d_dta(jbdy) == 0 ) THEN 
+               IF( dta_bdy(jbdy)%lneed_ssh ) THEN 
+                  igrd = 1
+                  DO ib = 1, idx_bdy(jbdy)%nblenrim(igrd)   ! ssh is allocated and used only on the rim
+                     ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                     ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                     dta_bdy(jbdy)%ssh(ib) = sshn(ii,ij) * tmask(ii,ij,1)         
+                  END DO
+               ENDIF
+               IF( ASSOCIATED(dta_bdy(jbdy)%u2d) ) THEN   ! no SIZE with a unassociated pointer. v2d and u2d can differ on subdomain
+                  igrd = 2
+                  DO ib = 1, SIZE(dta_bdy(jbdy)%u2d)      ! u2d is used either over the whole bdy or only on the rim
+                     ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                     ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                     dta_bdy(jbdy)%u2d(ib) = un_b(ii,ij) * umask(ii,ij,1)         
+                  END DO
+               ENDIF
+               IF( ASSOCIATED(dta_bdy(jbdy)%v2d) ) THEN   ! no SIZE with a unassociated pointer. v2d and u2d can differ on subdomain
+                  igrd = 3
+                  DO ib = 1, SIZE(dta_bdy(jbdy)%v2d)      ! v2d is used either over the whole bdy or only on the rim
+                     ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                     ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                     dta_bdy(jbdy)%v2d(ib) = vn_b(ii,ij) * vmask(ii,ij,1)         
+                  END DO
+               ENDIF
+            ENDIF
+            !
+            IF( nn_dyn3d_dta(jbdy) == 0 ) THEN 
+               IF( dta_bdy(jbdy)%lneed_dyn3d ) THEN 
+                  igrd = 2 
+                  DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+                     DO ik = 1, jpkm1
+                        ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                        ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                        dta_bdy(jbdy)%u3d(ib,ik) =  ( un(ii,ij,ik) - un_b(ii,ij) ) * umask(ii,ij,ik)         
+                     END DO
+                  END DO
+                  igrd = 3 
+                  DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+                     DO ik = 1, jpkm1
+                        ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                        ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                        dta_bdy(jbdy)%v3d(ib,ik) =  ( vn(ii,ij,ik) - vn_b(ii,ij) ) * vmask(ii,ij,ik)         
+                     END DO
+                  END DO
+               ENDIF
+            ENDIF
+
+            IF( nn_tra_dta(jbdy) == 0 ) THEN 
+               IF( dta_bdy(jbdy)%lneed_tra ) THEN
+                  igrd = 1 
+                  DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+                     DO ik = 1, jpkm1
+                        ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                        ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                        dta_bdy(jbdy)%tem(ib,ik) = tsn(ii,ij,ik,jp_tem) * tmask(ii,ij,ik)         
+                        dta_bdy(jbdy)%sal(ib,ik) = tsn(ii,ij,ik,jp_sal) * tmask(ii,ij,ik)         
+                     END DO
+                  END DO
+               ENDIF
+            ENDIF
+
+#if defined key_si3
+            IF( nn_ice_dta(jbdy) == 0 ) THEN    ! set ice to initial values
+               IF( dta_bdy(jbdy)%lneed_ice ) THEN
+                  igrd = 1   
+                  DO jl = 1, jpl
+                     DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+                        ii = idx_bdy(jbdy)%nbi(ib,igrd)
+                        ij = idx_bdy(jbdy)%nbj(ib,igrd)
+                        dta_bdy(jbdy)%a_i(ib,jl) =  a_i (ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%h_i(ib,jl) =  h_i (ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%h_s(ib,jl) =  h_s (ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%t_i(ib,jl) =  SUM(t_i (ii,ij,:,jl)) * r1_nlay_i * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%t_s(ib,jl) =  SUM(t_s (ii,ij,:,jl)) * r1_nlay_s * tmask(ii,ij,1)
+                        dta_bdy(jbdy)%tsu(ib,jl) =  t_su(ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%s_i(ib,jl) =  s_i (ii,ij,jl) * tmask(ii,ij,1)
+                        ! melt ponds
+                        dta_bdy(jbdy)%aip(ib,jl) =  a_ip(ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%hip(ib,jl) =  h_ip(ii,ij,jl) * tmask(ii,ij,1) 
+                        dta_bdy(jbdy)%hil(ib,jl) =  h_il(ii,ij,jl) * tmask(ii,ij,1) 
+                     END DO
+                  END DO
+               ENDIF
+            ENDIF
+#endif
+         END DO ! jbdy
+         !
+      ENDIF ! kt == nit000
+
+      ! update external data from files
+      !--------------------------------
+
+      DO jbdy = 1, nb_bdy
+
+         dta_alias => dta_bdy(jbdy)
+         bf_alias  => bf(:,jbdy)
+
+         ! read/update all bdy data
+         ! ------------------------
+         CALL fld_read( kt, 1, bf_alias, kit = kit, kt_offset = kt_offset )
+
+         ! apply some corrections in some specific cases...
+         ! --------------------------------------------------
+         !
+         ! if runoff condition: change river flow we read (in m3/s) into barotropic velocity (m/s)
+         IF( cn_tra(jbdy) == 'runoff' ) THEN   ! runoff
+            !
+            IF( ASSOCIATED(dta_bdy(jbdy)%u2d) ) THEN   ! no SIZE with a unassociated pointer. v2d and u2d can differ on subdomain
+               igrd = 2                         ! zonal flow (m3/s) to barotropic zonal velocity (m/s)
+               DO ib = 1, SIZE(dta_alias%u2d)   ! u2d is used either over the whole bdy or only on the rim
+                  ii   = idx_bdy(jbdy)%nbi(ib,igrd)
+                  ij   = idx_bdy(jbdy)%nbj(ib,igrd)
+                  dta_alias%u2d(ib) = dta_alias%u2d(ib) / ( e2u(ii,ij) * hu_0(ii,ij) )
+               END DO
+            ENDIF
+            IF( ASSOCIATED(dta_bdy(jbdy)%v2d) ) THEN   ! no SIZE with a unassociated pointer. v2d and u2d can differ on subdomain
+               igrd = 3                         ! meridional flow (m3/s) to barotropic meridional velocity (m/s)
+               DO ib = 1, SIZE(dta_alias%v2d)   ! v2d is used either over the whole bdy or only on the rim
+                  ii   = idx_bdy(jbdy)%nbi(ib,igrd)
+                  ij   = idx_bdy(jbdy)%nbj(ib,igrd)
+                  dta_alias%v2d(ib) = dta_alias%v2d(ib) / ( e1v(ii,ij) * hv_0(ii,ij) )
+               END DO
+            ENDIF
+         ENDIF
+
+         ! tidal harmonic forcing ONLY: initialise arrays
+         IF( nn_dyn2d_dta(jbdy) == 2 ) THEN   ! we did not read ssh, u/v2d 
+            IF( ASSOCIATED(dta_alias%ssh) ) dta_alias%ssh(:) = 0._wp
+            IF( ASSOCIATED(dta_alias%u2d) ) dta_alias%u2d(:) = 0._wp
+            IF( ASSOCIATED(dta_alias%v2d) ) dta_alias%v2d(:) = 0._wp
+         ENDIF
+
+         ! If full velocities in boundary data, then split it into barotropic and baroclinic component
+         IF( bf_alias(jp_bdyu3d)%ltotvel ) THEN     ! if we read 3D total velocity (can be true only if u3d was read)
+            !
+            igrd = 2                       ! zonal velocity
+            DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+               ii   = idx_bdy(jbdy)%nbi(ib,igrd)
+               ij   = idx_bdy(jbdy)%nbj(ib,igrd)
+               dta_alias%u2d(ib) = 0._wp   ! compute barotrope zonal velocity and put it in u2d
+               DO ik = 1, jpkm1
+                  dta_alias%u2d(ib) = dta_alias%u2d(ib) + e3u_n(ii,ij,ik) * umask(ii,ij,ik) * dta_alias%u3d(ib,ik)
+               END DO
+               dta_alias%u2d(ib) =  dta_alias%u2d(ib) * r1_hu_n(ii,ij)
+               DO ik = 1, jpkm1            ! compute barocline zonal velocity and put it in u3d
+                  dta_alias%u3d(ib,ik) = dta_alias%u3d(ib,ik) - dta_alias%u2d(ib)
+               END DO
+            END DO
+            igrd = 3                       ! meridional velocity
+            DO ib = 1, idx_bdy(jbdy)%nblen(igrd)
+               ii   = idx_bdy(jbdy)%nbi(ib,igrd)
+               ij   = idx_bdy(jbdy)%nbj(ib,igrd)
+               dta_alias%v2d(ib) = 0._wp   ! compute barotrope meridional velocity and put it in v2d
+               DO ik = 1, jpkm1
+                  dta_alias%v2d(ib) = dta_alias%v2d(ib) + e3v_n(ii,ij,ik) * vmask(ii,ij,ik) * dta_alias%v3d(ib,ik)
+               END DO
+               dta_alias%v2d(ib) =  dta_alias%v2d(ib) * r1_hv_n(ii,ij)
+               DO ik = 1, jpkm1            ! compute barocline meridional velocity and put it in v3d
+                  dta_alias%v3d(ib,ik) = dta_alias%v3d(ib,ik) - dta_alias%v2d(ib)
+               END DO
+            END DO
+         ENDIF   ! ltotvel
+
+         ! update tidal harmonic forcing
+         IF( PRESENT(kit) .AND. nn_dyn2d_dta(jbdy) .GE. 2 ) THEN
+            CALL bdytide_update( kt = kt, idx = idx_bdy(jbdy), dta = dta_alias, td = tides(jbdy),   & 
+               &                 kit = kit, kt_offset = kt_offset )
+         ENDIF
+
+         !  atm surface pressure : add inverted barometer effect to ssh if it was read
+         IF ( ln_apr_obc .AND. TRIM(bf_alias(jp_bdyssh)%clrootname) /= 'NOT USED' ) THEN
+            igrd = 1
+            DO ib = 1, idx_bdy(jbdy)%nblenrim(igrd)   ! ssh is used only on the rim
+               ii   = idx_bdy(jbdy)%nbi(ib,igrd)
+               ij   = idx_bdy(jbdy)%nbj(ib,igrd)
+               dta_alias%ssh(ib) = dta_alias%ssh(ib) + ssh_ib(ii,ij)
+            END DO
+         ENDIF
+
+#if defined key_si3
+         IF( dta_alias%lneed_ice .AND. idx_bdy(jbdy)%nblen(1) > 0 ) THEN
+            ! fill temperature and salinity arrays
+            IF( TRIM(bf_alias(jp_bdyt_i)%clrootname) == 'NOT USED' )   bf_alias(jp_bdyt_i)%fnow(:,1,:) = rice_tem (jbdy)
+            IF( TRIM(bf_alias(jp_bdyt_s)%clrootname) == 'NOT USED' )   bf_alias(jp_bdyt_s)%fnow(:,1,:) = rice_tem (jbdy)
+            IF( TRIM(bf_alias(jp_bdytsu)%clrootname) == 'NOT USED' )   bf_alias(jp_bdytsu)%fnow(:,1,:) = rice_tem (jbdy)
+            IF( TRIM(bf_alias(jp_bdys_i)%clrootname) == 'NOT USED' )   bf_alias(jp_bdys_i)%fnow(:,1,:) = rice_sal (jbdy)
+            IF( TRIM(bf_alias(jp_bdyaip)%clrootname) == 'NOT USED' )   bf_alias(jp_bdyaip)%fnow(:,1,:) = rice_apnd(jbdy) * & ! rice_apnd is the pond fraction
+               &                                                                         bf_alias(jp_bdya_i)%fnow(:,1,:)     !   ( a_ip = rice_apnd * a_i )
+            IF( TRIM(bf_alias(jp_bdyhip)%clrootname) == 'NOT USED' )   bf_alias(jp_bdyhip)%fnow(:,1,:) = rice_hpnd(jbdy)
+            IF( TRIM(bf_alias(jp_bdyhil)%clrootname) == 'NOT USED' )   bf_alias(jp_bdyhil)%fnow(:,1,:) = rice_hlid(jbdy)
+
+            ! if T_i is read and not T_su, set T_su = T_i
+            IF( TRIM(bf_alias(jp_bdyt_i)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdytsu)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdytsu)%fnow(:,1,:) = bf_alias(jp_bdyt_i)%fnow(:,1,:)
+            ! if T_s is read and not T_su, set T_su = T_s
+            IF( TRIM(bf_alias(jp_bdyt_s)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdytsu)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdytsu)%fnow(:,1,:) = bf_alias(jp_bdyt_s)%fnow(:,1,:)
+            ! if T_i is read and not T_s, set T_s = T_i
+            IF( TRIM(bf_alias(jp_bdyt_i)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdyt_s)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdyt_s)%fnow(:,1,:) = bf_alias(jp_bdyt_i)%fnow(:,1,:)
+            ! if T_su is read and not T_s, set T_s = T_su
+            IF( TRIM(bf_alias(jp_bdytsu)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdyt_s)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdyt_s)%fnow(:,1,:) = bf_alias(jp_bdytsu)%fnow(:,1,:)
+            ! if T_su is read and not T_i, set T_i = (T_su + T_freeze)/2
+            IF( TRIM(bf_alias(jp_bdytsu)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdyt_i)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdyt_i)%fnow(:,1,:) = 0.5_wp * ( bf_alias(jp_bdytsu)%fnow(:,1,:) + 271.15 )
+            ! if T_s is read and not T_i, set T_i = (T_s + T_freeze)/2
+            IF( TRIM(bf_alias(jp_bdyt_s)%clrootname) /= 'NOT USED' .AND. TRIM(bf_alias(jp_bdyt_i)%clrootname) == 'NOT USED' ) &
+               &   bf_alias(jp_bdyt_i)%fnow(:,1,:) = 0.5_wp * ( bf_alias(jp_bdyt_s)%fnow(:,1,:) + 271.15 )
+
+            ! make sure ponds = 0 if no ponds scheme
+            IF ( .NOT.ln_pnd ) THEN
+               bf_alias(jp_bdyaip)%fnow(:,1,:) = 0._wp
+               bf_alias(jp_bdyhip)%fnow(:,1,:) = 0._wp
+               bf_alias(jp_bdyhil)%fnow(:,1,:) = 0._wp
+            ENDIF
+            IF ( .NOT.ln_pnd_lids ) THEN
+               bf_alias(jp_bdyhil)%fnow(:,1,:) = 0._wp
+            ENDIF
+            
+            ! convert N-cat fields (input) into jpl-cat (output)
+            ipl = SIZE(bf_alias(jp_bdya_i)%fnow, 3)            
+            IF( ipl /= jpl ) THEN      ! ice: convert N-cat fields (input) into jpl-cat (output)
+               CALL ice_var_itd( bf_alias(jp_bdyh_i)%fnow(:,1,:), bf_alias(jp_bdyh_s)%fnow(:,1,:), bf_alias(jp_bdya_i)%fnow(:,1,:), & ! in
+                  &              dta_alias%h_i                  , dta_alias%h_s                  , dta_alias%a_i                  , & ! out
+                  &              bf_alias(jp_bdyt_i)%fnow(:,1,:), bf_alias(jp_bdyt_s)%fnow(:,1,:), &                                  ! in (optional)
+                  &              bf_alias(jp_bdytsu)%fnow(:,1,:), bf_alias(jp_bdys_i)%fnow(:,1,:), &                                  ! in     -
+                  &              bf_alias(jp_bdyaip)%fnow(:,1,:), bf_alias(jp_bdyhip)%fnow(:,1,:), bf_alias(jp_bdyhil)%fnow(:,1,:), & ! in     -
+                  &              dta_alias%t_i                  , dta_alias%t_s                  , &                                  ! out    -
+                  &              dta_alias%tsu                  , dta_alias%s_i                  , &                                  ! out    -
+                  &              dta_alias%aip                  , dta_alias%hip                  , dta_alias%hil )                    ! out    -
+            ENDIF
+         ENDIF
+#endif
+      END DO  ! jbdy
+
+      IF ( ln_tide ) THEN
+         IF (ln_dynspg_ts) THEN      ! Fill temporary arrays with slow-varying bdy data                           
+            DO jbdy = 1, nb_bdy      ! Tidal component added in ts loop
+               IF ( nn_dyn2d_dta(jbdy) .GE. 2 ) THEN
+                  IF( ASSOCIATED(dta_bdy(jbdy)%ssh) ) dta_bdy_s(jbdy)%ssh(:) = dta_bdy(jbdy)%ssh(:)
+                  IF( ASSOCIATED(dta_bdy(jbdy)%u2d) ) dta_bdy_s(jbdy)%u2d(:) = dta_bdy(jbdy)%u2d(:)
+                  IF( ASSOCIATED(dta_bdy(jbdy)%v2d) ) dta_bdy_s(jbdy)%v2d(:) = dta_bdy(jbdy)%v2d(:)
+               ENDIF
+            END DO
+         ELSE ! Add tides if not split-explicit free surface else this is done in ts loop
+            !
+            CALL bdy_dta_tides( kt=kt, kt_offset=kt_offset )
+         ENDIF
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('bdy_dta')
+      !
+   END SUBROUTINE bdy_dta
+   
+
+   SUBROUTINE bdy_dta_init
+      !!----------------------------------------------------------------------
+      !!                   ***  SUBROUTINE bdy_dta_init  ***
+      !!                    
+      !! ** Purpose :   Initialise arrays for reading of external data 
+      !!                for open boundary conditions
+      !!
+      !! ** Method  :   
+      !!                
+      !!----------------------------------------------------------------------
+      INTEGER ::   jbdy, jfld    ! Local integers
+      INTEGER ::   ierror, ios     ! 
+      !
+      CHARACTER(len=3)                       ::   cl3           ! 
+      CHARACTER(len=100)                     ::   cn_dir        ! Root directory for location of data files
+      LOGICAL                                ::   ln_full_vel   ! =T => full velocities in 3D boundary data
+      !                                                         ! =F => baroclinic velocities in 3D boundary data
+      LOGICAL                                ::   ln_zinterp    ! =T => requires a vertical interpolation of the bdydta
+      REAL(wp)                               ::   rn_ice_tem, rn_ice_sal, rn_ice_age, rn_ice_apnd, rn_ice_hpnd, rn_ice_hlid
+      INTEGER                                ::   ipk,ipl       !
+      INTEGER                                ::   idvar         ! variable ID
+      INTEGER                                ::   indims        ! number of dimensions of the variable
+      INTEGER                                ::   iszdim        ! number of dimensions of the variable
+      INTEGER, DIMENSION(4)                  ::   i4dimsz       ! size of variable dimensions 
+      INTEGER                                ::   igrd          ! index for grid type (1,2,3 = T,U,V)
+      LOGICAL                                ::   lluld         ! is the variable using the unlimited dimension
+      LOGICAL                                ::   llneed        !
+      LOGICAL                                ::   llread        !
+      LOGICAL                                ::   llfullbdy     !
+      TYPE(FLD_N), DIMENSION(1), TARGET  ::   bn_tem, bn_sal, bn_u3d, bn_v3d   ! must be an array to be used with fld_fill
+      TYPE(FLD_N), DIMENSION(1), TARGET  ::   bn_ssh, bn_u2d, bn_v2d           ! informations about the fields to be read
+      TYPE(FLD_N), DIMENSION(1), TARGET  ::   bn_a_i, bn_h_i, bn_h_s, bn_t_i, bn_t_s, bn_tsu, bn_s_i, bn_aip, bn_hip, bn_hil       
+      TYPE(FLD_N), DIMENSION(:), POINTER ::   bn_alias                        ! must be an array to be used with fld_fill
+      TYPE(FLD  ), DIMENSION(:), POINTER ::   bf_alias
+      !
+      NAMELIST/nambdy_dta/ cn_dir, bn_tem, bn_sal, bn_u3d, bn_v3d, bn_ssh, bn_u2d, bn_v2d,                 &
+                         & bn_a_i, bn_h_i, bn_h_s, bn_t_i, bn_t_s, bn_tsu, bn_s_i, bn_aip, bn_hip, bn_hil, &
+                         & rn_ice_tem, rn_ice_sal, rn_ice_age, rn_ice_apnd, rn_ice_hpnd, rn_ice_hlid,      &
+                         & ln_full_vel, ln_zinterp
+      !!---------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'bdy_dta_ini : initialization of data at the open boundaries'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) ''
+
+      ALLOCATE( bf(jpbdyfld,nb_bdy), STAT=ierror )
+      IF( ierror > 0 ) THEN   
+         CALL ctl_stop( 'bdy_dta: unable to allocate bf structure' )   ;   RETURN  
+      ENDIF
+      bf(:,:)%clrootname = 'NOT USED'   ! default definition used as a flag in fld_read to do nothing.
+      bf(:,:)%lzint      = .FALSE.      ! default definition
+      bf(:,:)%ltotvel    = .FALSE.      ! default definition
+ 
+      ! Read namelists
+      ! --------------
+      REWIND(numnam_cfg)
+      DO jbdy = 1, nb_bdy
+
+         WRITE(ctmp1, '(a,i2)') 'BDY number ', jbdy
+         WRITE(ctmp2, '(a,i2)') 'block nambdy_dta number ', jbdy
+
+         ! There is only one nambdy_dta block in namelist_ref -> use it for each bdy so we do a rewind 
+         REWIND(numnam_ref)
+         READ  ( numnam_ref, nambdy_dta, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy_dta in reference namelist' )
+
+         !   by-pass nambdy_dta reading if no input data used in this bdy   
+         IF(       ( dta_bdy(jbdy)%lneed_dyn2d .AND. MOD(nn_dyn2d_dta(jbdy),2) == 1 )   &
+            & .OR. ( dta_bdy(jbdy)%lneed_dyn3d .AND.     nn_dyn3d_dta(jbdy)    == 1 )   &
+            & .OR. ( dta_bdy(jbdy)%lneed_tra   .AND.       nn_tra_dta(jbdy)    == 1 )   &
+            & .OR. ( dta_bdy(jbdy)%lneed_ice   .AND.       nn_ice_dta(jbdy)    == 1 )   )   THEN
+            ! WARNING: we don't do a rewind here, each bdy reads its own nambdy_dta block one after another
+            READ  ( numnam_cfg, nambdy_dta, IOSTAT = ios, ERR = 902 )
+902         IF( ios >  0 )   CALL ctl_nam ( ios , 'nambdy_dta in configuration namelist' )
+            IF(lwm) WRITE( numond, nambdy_dta )           
+         ENDIF
+
+         ! get the number of ice categories in bdy data file (use a_i information to do this)
+         ipl = jpl   ! default definition
+         IF( dta_bdy(jbdy)%lneed_ice ) THEN    ! if we need ice bdy data
+            IF( nn_ice_dta(jbdy) == 1 ) THEN   ! if we get ice bdy data from netcdf file
+               CALL fld_fill(  bf(jp_bdya_i,jbdy:jbdy), bn_a_i, cn_dir, 'bdy_dta', 'a_i'//' '//ctmp1, ctmp2 )   ! use namelist info
+               CALL fld_clopn( bf(jp_bdya_i,jbdy), nyear, nmonth, nday )   ! not a problem when we call it again after
+               idvar = iom_varid( bf(jp_bdya_i,jbdy)%num, bf(jp_bdya_i,jbdy)%clvar, kndims=indims, kdimsz=i4dimsz, lduld=lluld )
+               IF( indims == 4 .OR. ( indims == 3 .AND. .NOT. lluld ) ) THEN   ;   ipl = i4dimsz(3)   ! xylt or xyl
+               ELSE                                                            ;   ipl = 1            ! xy or xyt
+               ENDIF
+               bf(jp_bdya_i,jbdy)%clrootname = 'NOT USED'   ! reset to default value as this subdomain may not need to read this bdy
+            ENDIF
+         ENDIF
+
+#if defined key_si3
+         IF( .NOT.ln_pnd ) THEN
+            rn_ice_apnd = 0. ; rn_ice_hpnd = 0. ; rn_ice_hlid = 0.
+            CALL ctl_warn( 'rn_ice_apnd & rn_ice_hpnd = 0 & rn_ice_hlid = 0 when no ponds' )
+         ENDIF
+         IF( .NOT.ln_pnd_lids ) THEN
+            rn_ice_hlid = 0.
+         ENDIF
+#endif
+
+         ! temp, salt, age and ponds of incoming ice
+         rice_tem (jbdy) = rn_ice_tem
+         rice_sal (jbdy) = rn_ice_sal
+         rice_age (jbdy) = rn_ice_age
+         rice_apnd(jbdy) = rn_ice_apnd
+         rice_hpnd(jbdy) = rn_ice_hpnd
+         rice_hlid(jbdy) = rn_ice_hlid
+
+         
+         DO jfld = 1, jpbdyfld
+
+            ! =====================
+            !          ssh 
+            ! =====================
+            IF( jfld == jp_bdyssh ) THEN
+               cl3 = 'ssh'
+               igrd = 1                                                    ! T point
+               ipk = 1                                                     ! surface data
+               llneed = dta_bdy(jbdy)%lneed_ssh                            ! dta_bdy(jbdy)%ssh will be needed
+               llread = MOD(nn_dyn2d_dta(jbdy),2) == 1                     ! get data from NetCDF file
+               bf_alias => bf(jp_bdyssh,jbdy:jbdy)                         ! alias for ssh structure of bdy number jbdy
+               bn_alias => bn_ssh                                          ! alias for ssh structure of nambdy_dta 
+               iszdim = idx_bdy(jbdy)%nblenrim(igrd)                       ! length of this bdy on this MPI processus : used only on the rim
+            ENDIF
+            ! =====================
+            !         dyn2d
+            ! =====================
+            IF( jfld == jp_bdyu2d ) THEN
+               cl3 = 'u2d'
+               igrd = 2                                                    ! U point
+               ipk = 1                                                     ! surface data
+               llneed = dta_bdy(jbdy)%lneed_dyn2d                          ! dta_bdy(jbdy)%u2d will be needed
+               llread = .NOT. ln_full_vel .AND. MOD(nn_dyn2d_dta(jbdy),2) == 1   ! don't get u2d from u3d and read NetCDF file
+               bf_alias => bf(jp_bdyu2d,jbdy:jbdy)                         ! alias for u2d structure of bdy number jbdy
+               bn_alias => bn_u2d                                          ! alias for u2d structure of nambdy_dta
+               llfullbdy = ln_full_vel .OR. cn_dyn2d(jbdy) == 'frs'        ! need u2d over the whole bdy or only over the rim?
+               IF( llfullbdy ) THEN  ;   iszdim = idx_bdy(jbdy)%nblen(igrd)
+               ELSE                  ;   iszdim = idx_bdy(jbdy)%nblenrim(igrd)
+               ENDIF
+            ENDIF
+            IF( jfld == jp_bdyv2d ) THEN
+               cl3 = 'v2d'
+               igrd = 3                                                    ! V point
+               ipk = 1                                                     ! surface data
+               llneed = dta_bdy(jbdy)%lneed_dyn2d                          ! dta_bdy(jbdy)%v2d will be needed
+               llread = .NOT. ln_full_vel .AND. MOD(nn_dyn2d_dta(jbdy),2) == 1   ! don't get v2d from v3d and read NetCDF file
+               bf_alias => bf(jp_bdyv2d,jbdy:jbdy)                         ! alias for v2d structure of bdy number jbdy
+               bn_alias => bn_v2d                                          ! alias for v2d structure of nambdy_dta 
+               llfullbdy = ln_full_vel .OR. cn_dyn2d(jbdy) == 'frs'        ! need v2d over the whole bdy or only over the rim?
+               IF( llfullbdy ) THEN  ;   iszdim = idx_bdy(jbdy)%nblen(igrd)
+               ELSE                  ;   iszdim = idx_bdy(jbdy)%nblenrim(igrd)
+               ENDIF
+            ENDIF
+            ! =====================
+            !         dyn3d
+            ! =====================
+            IF( jfld == jp_bdyu3d ) THEN
+               cl3 = 'u3d'
+               igrd = 2                                                    ! U point
+               ipk = jpk                                                   ! 3d data
+               llneed = dta_bdy(jbdy)%lneed_dyn3d .OR.               &     ! dta_bdy(jbdy)%u3d will be needed
+                  &   ( dta_bdy(jbdy)%lneed_dyn2d .AND. ln_full_vel )      !   u3d needed to compute u2d
+               llread = nn_dyn3d_dta(jbdy) == 1                            ! get data from NetCDF file
+               bf_alias => bf(jp_bdyu3d,jbdy:jbdy)                         ! alias for u3d structure of bdy number jbdy
+               bn_alias => bn_u3d                                          ! alias for u3d structure of nambdy_dta 
+               iszdim = idx_bdy(jbdy)%nblen(igrd)                          ! length of this bdy on this MPI processus
+           ENDIF
+            IF( jfld == jp_bdyv3d ) THEN
+               cl3 = 'v3d'
+               igrd = 3                                                    ! V point
+               ipk = jpk                                                   ! 3d data
+               llneed = dta_bdy(jbdy)%lneed_dyn3d .OR.               &     ! dta_bdy(jbdy)%v3d will be needed
+                  &   ( dta_bdy(jbdy)%lneed_dyn2d .AND. ln_full_vel )      !   v3d needed to compute v2d
+               llread = nn_dyn3d_dta(jbdy) == 1                            ! get data from NetCDF file
+               bf_alias => bf(jp_bdyv3d,jbdy:jbdy)                         ! alias for v3d structure of bdy number jbdy
+               bn_alias => bn_v3d                                          ! alias for v3d structure of nambdy_dta 
+               iszdim = idx_bdy(jbdy)%nblen(igrd)                          ! length of this bdy on this MPI processus
+           ENDIF
+
+            ! =====================
+            !          tra
+            ! =====================
+            IF( jfld == jp_bdytem ) THEN
+               cl3 = 'tem'
+               igrd = 1                                                    ! T point
+               ipk = jpk                                                   ! 3d data
+               llneed = dta_bdy(jbdy)%lneed_tra                            ! dta_bdy(jbdy)%tem will be needed
+               llread = nn_tra_dta(jbdy) == 1                              ! get data from NetCDF file
+               bf_alias => bf(jp_bdytem,jbdy:jbdy)                         ! alias for ssh structure of bdy number jbdy
+               bn_alias => bn_tem                                          ! alias for ssh structure of nambdy_dta 
+               iszdim = idx_bdy(jbdy)%nblen(igrd)                          ! length of this bdy on this MPI processus
+            ENDIF
+            IF( jfld == jp_bdysal ) THEN
+               cl3 = 'sal'
+               igrd = 1                                                    ! T point
+               ipk = jpk                                                   ! 3d data
+               llneed = dta_bdy(jbdy)%lneed_tra                            ! dta_bdy(jbdy)%sal will be needed
+               llread = nn_tra_dta(jbdy) == 1                              ! get data from NetCDF file
+               bf_alias => bf(jp_bdysal,jbdy:jbdy)                         ! alias for ssh structure of bdy number jbdy
+               bn_alias => bn_sal                                          ! alias for ssh structure of nambdy_dta 
+               iszdim = idx_bdy(jbdy)%nblen(igrd)                          ! length of this bdy on this MPI processus
+            ENDIF
+
+            ! =====================
+            !          ice
+            ! =====================
+            IF(  jfld == jp_bdya_i .OR. jfld == jp_bdyh_i .OR. jfld == jp_bdyh_s .OR. &
+               & jfld == jp_bdyt_i .OR. jfld == jp_bdyt_s .OR. jfld == jp_bdytsu .OR. &
+               & jfld == jp_bdys_i .OR. jfld == jp_bdyaip .OR. jfld == jp_bdyhip .OR. jfld == jp_bdyhil ) THEN
+               igrd = 1                                                    ! T point
+               ipk = ipl                                                   ! jpl-cat data
+               llneed = dta_bdy(jbdy)%lneed_ice                            ! ice will be needed
+               llread = nn_ice_dta(jbdy) == 1                              ! get data from NetCDF file
+               iszdim = idx_bdy(jbdy)%nblen(igrd)                          ! length of this bdy on this MPI processus
+            ENDIF
+            IF( jfld == jp_bdya_i ) THEN
+               cl3 = 'a_i'
+               bf_alias => bf(jp_bdya_i,jbdy:jbdy)                         ! alias for a_i structure of bdy number jbdy
+               bn_alias => bn_a_i                                          ! alias for a_i structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyh_i ) THEN
+               cl3 = 'h_i'
+               bf_alias => bf(jp_bdyh_i,jbdy:jbdy)                         ! alias for h_i structure of bdy number jbdy
+               bn_alias => bn_h_i                                          ! alias for h_i structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyh_s ) THEN
+               cl3 = 'h_s'
+               bf_alias => bf(jp_bdyh_s,jbdy:jbdy)                         ! alias for h_s structure of bdy number jbdy
+               bn_alias => bn_h_s                                          ! alias for h_s structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyt_i ) THEN
+               cl3 = 't_i'
+               bf_alias => bf(jp_bdyt_i,jbdy:jbdy)                         ! alias for t_i structure of bdy number jbdy
+               bn_alias => bn_t_i                                          ! alias for t_i structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyt_s ) THEN
+               cl3 = 't_s'
+               bf_alias => bf(jp_bdyt_s,jbdy:jbdy)                         ! alias for t_s structure of bdy number jbdy
+               bn_alias => bn_t_s                                          ! alias for t_s structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdytsu ) THEN
+               cl3 = 'tsu'
+               bf_alias => bf(jp_bdytsu,jbdy:jbdy)                         ! alias for tsu structure of bdy number jbdy
+               bn_alias => bn_tsu                                          ! alias for tsu structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdys_i ) THEN
+               cl3 = 's_i'
+               bf_alias => bf(jp_bdys_i,jbdy:jbdy)                         ! alias for s_i structure of bdy number jbdy
+               bn_alias => bn_s_i                                          ! alias for s_i structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyaip ) THEN
+               cl3 = 'aip'
+               bf_alias => bf(jp_bdyaip,jbdy:jbdy)                         ! alias for aip structure of bdy number jbdy
+               bn_alias => bn_aip                                          ! alias for aip structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyhip ) THEN
+               cl3 = 'hip'
+               bf_alias => bf(jp_bdyhip,jbdy:jbdy)                         ! alias for hip structure of bdy number jbdy
+               bn_alias => bn_hip                                          ! alias for hip structure of nambdy_dta 
+            ENDIF
+            IF( jfld == jp_bdyhil ) THEN
+               cl3 = 'hil'
+               bf_alias => bf(jp_bdyhil,jbdy:jbdy)                         ! alias for hil structure of bdy number jbdy
+               bn_alias => bn_hil                                          ! alias for hil structure of nambdy_dta 
+            ENDIF
+
+            IF( llneed .AND. iszdim > 0 ) THEN                             ! dta_bdy(jbdy)%xxx will be needed
+               !                                                           !   -> must be associated with an allocated target
+               ALLOCATE( bf_alias(1)%fnow( iszdim, 1, ipk ) )              ! allocate the target
+               !
+               IF( llread ) THEN                                           ! get data from NetCDF file
+                  CALL fld_fill( bf_alias, bn_alias, cn_dir, 'bdy_dta', cl3//' '//ctmp1, ctmp2 )   ! use namelist info
+                  IF( bf_alias(1)%ln_tint ) ALLOCATE( bf_alias(1)%fdta( iszdim, 1, ipk, 2 ) )
+                  bf_alias(1)%imap    => idx_bdy(jbdy)%nbmap(1:iszdim,igrd)   ! associate the mapping used for this bdy
+                  bf_alias(1)%igrd    = igrd                                  ! used only for vertical integration of 3D arrays
+                  bf_alias(1)%ibdy    = jbdy                                  !  "    "    "     "          "      "  "    "    
+                  bf_alias(1)%ltotvel = ln_full_vel                           ! T if u3d is full velocity
+                  bf_alias(1)%lzint   = ln_zinterp                            ! T if it requires a vertical interpolation
+               ENDIF
+
+               ! associate the pointer and get rid of the dimensions with a size equal to 1
+               IF( jfld == jp_bdyssh )        dta_bdy(jbdy)%ssh => bf_alias(1)%fnow(:,1,1)
+               IF( jfld == jp_bdyu2d )        dta_bdy(jbdy)%u2d => bf_alias(1)%fnow(:,1,1)
+               IF( jfld == jp_bdyv2d )        dta_bdy(jbdy)%v2d => bf_alias(1)%fnow(:,1,1)
+               IF( jfld == jp_bdyu3d )        dta_bdy(jbdy)%u3d => bf_alias(1)%fnow(:,1,:)
+               IF( jfld == jp_bdyv3d )        dta_bdy(jbdy)%v3d => bf_alias(1)%fnow(:,1,:)
+               IF( jfld == jp_bdytem )        dta_bdy(jbdy)%tem => bf_alias(1)%fnow(:,1,:)
+               IF( jfld == jp_bdysal )        dta_bdy(jbdy)%sal => bf_alias(1)%fnow(:,1,:)
+               IF( jfld == jp_bdya_i ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%a_i => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%a_i(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyh_i ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%h_i => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%h_i(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyh_s ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%h_s => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%h_s(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyt_i ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%t_i => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%t_i(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyt_s ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%t_s => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%t_s(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdytsu ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%tsu => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%tsu(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdys_i ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%s_i => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%s_i(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyaip ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%aip => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%aip(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyhip ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%hip => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%hip(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+               IF( jfld == jp_bdyhil ) THEN
+                  IF( ipk == jpl ) THEN   ;   dta_bdy(jbdy)%hil => bf_alias(1)%fnow(:,1,:)
+                  ELSE                    ;   ALLOCATE( dta_bdy(jbdy)%hil(iszdim,jpl) )
+                  ENDIF
+               ENDIF
+            ENDIF
+
+         END DO   ! jpbdyfld
+         !
+      END DO ! jbdy 
+      !
+   END SUBROUTINE bdy_dta_init
+   
+   !!==============================================================================
+END MODULE bdydta
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn.F90	(revision 14097)
@@ -0,0 +1,122 @@
+MODULE bdydyn
+   !!======================================================================
+   !!                       ***  MODULE  bdydyn  ***
+   !! Unstructured Open Boundary Cond. :   Apply boundary conditions to velocities
+   !!======================================================================
+   !! History :  1.0  !  2005-02  (J. Chanut, A. Sellar)  Original code
+   !!             -   !  2007-07  (D. Storkey) Move Flather implementation to separate routine.
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.2  !  2008-04  (R. Benshila) consider velocity instead of transport 
+   !!            3.3  !  2010-09  (E.O'Dea) modifications for Shelf configurations 
+   !!            3.3  !  2010-09  (D.Storkey) add ice boundary conditions
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!----------------------------------------------------------------------
+   !!   bdy_dyn        : split velocities into barotropic and baroclinic parts
+   !!                    and call bdy_dyn2d and bdy_dyn3d to apply boundary
+   !!                    conditions
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE bdy_oce         ! ocean open boundary conditions
+   USE bdydyn2d        ! open boundary conditions for barotropic solution
+   USE bdydyn3d        ! open boundary conditions for baroclinic velocities
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  !
+   USE domvvl          ! variable volume
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_dyn    ! routine called in dyn_nxt
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_dyn( kt, dyn3d_only )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn  ***
+      !!
+      !! ** Purpose : - Wrapper routine for bdy_dyn2d and bdy_dyn3d.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in)           ::   kt           ! Main time step counter
+      LOGICAL, INTENT(in), OPTIONAL ::   dyn3d_only   ! T => only update baroclinic velocities
+      !
+      INTEGER ::   jk, ii, ij, ib_bdy, ib, igrd     ! Loop counter
+      LOGICAL ::   ll_dyn2d, ll_dyn3d, ll_orlanski
+      REAL(wp), DIMENSION(jpi,jpj) :: pua2d, pva2d     ! after barotropic velocities
+      !!----------------------------------------------------------------------
+      !
+      ll_dyn2d = .true.
+      ll_dyn3d = .true.
+      !
+      IF( PRESENT(dyn3d_only) ) THEN
+         IF( dyn3d_only )   ll_dyn2d = .false.
+      ENDIF
+      !
+      ll_orlanski = .false.
+      DO ib_bdy = 1, nb_bdy
+         IF ( cn_dyn2d(ib_bdy) == 'orlanski' .OR. cn_dyn2d(ib_bdy) == 'orlanski_npo' &
+     &   .OR. cn_dyn3d(ib_bdy) == 'orlanski' .OR. cn_dyn3d(ib_bdy) == 'orlanski_npo')   ll_orlanski = .true.
+      END DO
+
+      !-------------------------------------------------------
+      ! Split velocities into barotropic and baroclinic parts
+      !-------------------------------------------------------
+
+      !                          ! "After" velocities: 
+      pua2d(:,:) = 0._wp
+      pva2d(:,:) = 0._wp     
+      DO jk = 1, jpkm1
+         pua2d(:,:) = pua2d(:,:) + e3u_a(:,:,jk) * ua(:,:,jk) * umask(:,:,jk)
+         pva2d(:,:) = pva2d(:,:) + e3v_a(:,:,jk) * va(:,:,jk) * vmask(:,:,jk)
+      END DO
+      pua2d(:,:) = pua2d(:,:) * r1_hu_a(:,:)
+      pva2d(:,:) = pva2d(:,:) * r1_hv_a(:,:)
+
+      DO jk = 1 , jpkm1
+         ua(:,:,jk) = ( ua(:,:,jk) - pua2d(:,:) ) * umask(:,:,jk)
+         va(:,:,jk) = ( va(:,:,jk) - pva2d(:,:) ) * vmask(:,:,jk)
+      END DO
+
+
+      IF( ll_orlanski ) THEN     ! "Before" velocities (Orlanski condition only) 
+         DO jk = 1 , jpkm1
+            ub(:,:,jk) = ( ub(:,:,jk) - ub_b(:,:) ) * umask(:,:,jk)
+            vb(:,:,jk) = ( vb(:,:,jk) - vb_b(:,:) ) * vmask(:,:,jk)
+         END DO
+      ENDIF
+
+      !-------------------------------------------------------
+      ! Apply boundary conditions to barotropic and baroclinic
+      ! parts separately
+      !-------------------------------------------------------
+
+      IF( ll_dyn2d )   CALL bdy_dyn2d( kt, pua2d, pva2d, ub_b, vb_b, r1_hu_a(:,:), r1_hv_a(:,:), ssha )
+
+      IF( ll_dyn3d )   CALL bdy_dyn3d( kt )
+
+      !-------------------------------------------------------
+      ! Recombine velocities
+      !-------------------------------------------------------
+      !
+      DO jk = 1 , jpkm1
+         ua(:,:,jk) = ( ua(:,:,jk) + pua2d(:,:) ) * umask(:,:,jk)
+         va(:,:,jk) = ( va(:,:,jk) + pva2d(:,:) ) * vmask(:,:,jk)
+      END DO
+      !
+      IF ( ll_orlanski ) THEN
+         DO jk = 1 , jpkm1
+            ub(:,:,jk) = ( ub(:,:,jk) + ub_b(:,:) ) * umask(:,:,jk)
+            vb(:,:,jk) = ( vb(:,:,jk) + vb_b(:,:) ) * vmask(:,:,jk)
+         END DO
+      END IF
+      !
+   END SUBROUTINE bdy_dyn
+
+   !!======================================================================
+END MODULE bdydyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn2d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn2d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn2d.F90	(revision 14097)
@@ -0,0 +1,334 @@
+MODULE bdydyn2d
+   !!======================================================================
+   !!                       ***  MODULE  bdydyn  ***
+   !! Unstructured Open Boundary Cond. :   Apply boundary conditions to barotropic solution
+   !!======================================================================
+   !! History :  3.4  !  2011     (D. Storkey) new module as part of BDY rewrite
+   !!            3.5  !  2012     (S. Mocavero, I. Epicoco) Optimization of BDY communications
+   !!            3.5  !  2013-07  (J. Chanut) Compliant with time splitting changes
+   !!----------------------------------------------------------------------
+   !!   bdy_dyn2d          : Apply open boundary conditions to barotropic variables.
+   !!   bdy_dyn2d_frs      : Apply Flow Relaxation Scheme 
+   !!   bdy_dyn2d_fla      : Apply Flather condition
+   !!   bdy_dyn2d_orlanski : Orlanski Radiation
+   !!   bdy_ssh            : Duplicate sea level across open boundaries
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE bdy_oce         ! ocean open boundary conditions
+   USE bdylib          ! BDY library routines
+   USE phycst          ! physical constants
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE wet_dry         ! Use wet dry to get reference ssh level
+   USE in_out_manager  !
+   USE lib_mpp, ONLY: ctl_stop
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_dyn2d   ! routine called in dynspg_ts and bdy_dyn
+   PUBLIC   bdy_ssh       ! routine called in dynspg_ts or sshwzv
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_dyn2d( kt, pua2d, pva2d, pub2d, pvb2d, phur, phvr, pssh  )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn2d  ***
+      !!
+      !! ** Purpose : - Apply open boundary conditions for barotropic variables
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER,                      INTENT(in) ::   kt   ! Main time step counter
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d 
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: pub2d, pvb2d
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: phur, phvr
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: pssh
+      !!
+      INTEGER  ::   ib_bdy, ir     ! BDY set index, rim index
+      LOGICAL  ::   llrim0         ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4) :: llsend2, llrecv2, llsend3, llrecv3  ! indicate how communications are to be carried out
+      
+      llsend2(:) = .false.   ;   llrecv2(:) = .false.
+      llsend3(:) = .false.   ;   llrecv3(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            SELECT CASE( cn_dyn2d(ib_bdy) )
+            CASE('none')
+               CYCLE
+            CASE('frs')   ! treat the whole boundary at once
+               IF( llrim0 )   CALL bdy_dyn2d_frs( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, pua2d, pva2d )
+            CASE('flather')
+               CALL bdy_dyn2d_fla( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, pua2d, pva2d, pssh, phur, phvr, llrim0 )
+            CASE('orlanski')
+               CALL bdy_dyn2d_orlanski( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, &
+                    & pua2d, pva2d, pub2d, pvb2d, llrim0, ll_npo=.false. )
+            CASE('orlanski_npo')
+               CALL bdy_dyn2d_orlanski( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, &
+                    & pua2d, pva2d, pub2d, pvb2d, llrim0, ll_npo=.true.  )
+            CASE DEFAULT
+               CALL ctl_stop( 'bdy_dyn2d : unrecognised option for open boundaries for barotropic variables' )
+            END SELECT
+         ENDDO
+         !
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN
+            llsend2(:) = .false.   ;   llrecv2(:) = .false.
+            llsend3(:) = .false.   ;   llrecv3(:) = .false.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            SELECT CASE( cn_dyn2d(ib_bdy) )
+            CASE('flather')
+               llsend2(1:2) = llsend2(1:2) .OR. lsend_bdyint(ib_bdy,2,1:2,ir)   ! west/east, U points
+               llsend2(1)   = llsend2(1)   .OR. lsend_bdyext(ib_bdy,2,1,ir)     ! neighbour might search point towards its east bdy
+               llrecv2(1:2) = llrecv2(1:2) .OR. lrecv_bdyint(ib_bdy,2,1:2,ir)   ! west/east, U points
+               llrecv2(2)   = llrecv2(2)   .OR. lrecv_bdyext(ib_bdy,2,2,ir)     ! might search point towards bdy on the east
+               llsend3(3:4) = llsend3(3:4) .OR. lsend_bdyint(ib_bdy,3,3:4,ir)   ! north/south, V points
+               llsend3(3)   = llsend3(3)   .OR. lsend_bdyext(ib_bdy,3,3,ir)     ! neighbour might search point towards its north bdy 
+               llrecv3(3:4) = llrecv3(3:4) .OR. lrecv_bdyint(ib_bdy,3,3:4,ir)   ! north/south, V points
+               llrecv3(4)   = llrecv3(4)   .OR. lrecv_bdyext(ib_bdy,3,4,ir)     ! might search point towards bdy on the north
+            CASE('orlanski', 'orlanski_npo')
+               llsend2(:) = llsend2(:) .OR. lsend_bdy(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llrecv2(:) = llrecv2(:) .OR. lrecv_bdy(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llsend3(:) = llsend3(:) .OR. lsend_bdy(ib_bdy,3,:,ir)   ! possibly every direction, V points
+               llrecv3(:) = llrecv3(:) .OR. lrecv_bdy(ib_bdy,3,:,ir)   ! possibly every direction, V points
+            END SELECT
+         END DO
+         IF( ANY(llsend2) .OR. ANY(llrecv2) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdydyn2d', pua2d, 'U', -1., kfillmode=jpfillnothing ,lsend=llsend2, lrecv=llrecv2 )
+         END IF
+         IF( ANY(llsend3) .OR. ANY(llrecv3) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdydyn2d', pva2d, 'V', -1., kfillmode=jpfillnothing ,lsend=llsend3, lrecv=llrecv3 )
+         END IF
+         !
+      END DO   ! ir
+      !
+   END SUBROUTINE bdy_dyn2d
+
+   SUBROUTINE bdy_dyn2d_frs( idx, dta, ib_bdy, pua2d, pva2d )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn2d_frs  ***
+      !!
+      !! ** Purpose : - Apply the Flow Relaxation Scheme for barotropic velocities
+      !!                at open boundaries.
+      !!
+      !! References :- Engedahl H., 1995: Use of the flow relaxation scheme in 
+      !!               a three-dimensional baroclinic ocean model with realistic
+      !!               topography. Tellus, 365-382.
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX), INTENT(in) ::   idx  ! OBC indices
+      TYPE(OBC_DATA),  INTENT(in) ::   dta  ! OBC external data
+      INTEGER,         INTENT(in) ::   ib_bdy  ! BDY set index
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d 
+      !!
+      INTEGER  ::   jb             ! dummy loop indices
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      REAL(wp) ::   zwgt           ! boundary weight
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2                      ! Relaxation of zonal velocity
+      DO jb = 1, idx%nblen(igrd)
+         ii   = idx%nbi(jb,igrd)
+         ij   = idx%nbj(jb,igrd)
+         zwgt = idx%nbw(jb,igrd)
+         pua2d(ii,ij) = ( pua2d(ii,ij) + zwgt * ( dta%u2d(jb) - pua2d(ii,ij) ) ) * umask(ii,ij,1)
+      END DO
+      !
+      igrd = 3                      ! Relaxation of meridional velocity
+      DO jb = 1, idx%nblen(igrd)
+         ii   = idx%nbi(jb,igrd)
+         ij   = idx%nbj(jb,igrd)
+         zwgt = idx%nbw(jb,igrd)
+         pva2d(ii,ij) = ( pva2d(ii,ij) + zwgt * ( dta%v2d(jb) - pva2d(ii,ij) ) ) * vmask(ii,ij,1)
+      END DO 
+      !
+   END SUBROUTINE bdy_dyn2d_frs
+
+
+   SUBROUTINE bdy_dyn2d_fla( idx, dta, ib_bdy, pua2d, pva2d, pssh, phur, phvr, llrim0 )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_dyn2d_fla  ***
+      !!             
+      !!              - Apply Flather boundary conditions on normal barotropic velocities 
+      !!
+      !! ** WARNINGS about FLATHER implementation:
+      !!1. According to Palma and Matano, 1998 "after ssh" is used. 
+      !!   In ROMS and POM implementations, it is "now ssh". In the current 
+      !!   implementation (tested only in the EEL-R5 conf.), both cases were unstable. 
+      !!   So I use "before ssh" in the following.
+      !!
+      !!2. We assume that the normal ssh gradient at the bdy is zero. As a matter of 
+      !!   fact, the model ssh just inside the dynamical boundary is used (the outside  
+      !!   ssh in the code is not updated).
+      !!
+      !! References:  Flather, R. A., 1976: A tidal model of the northwest European
+      !!              continental shelf. Mem. Soc. R. Sci. Liege, Ser. 6,10, 141-164.     
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),              INTENT(in) ::   idx  ! OBC indices
+      TYPE(OBC_DATA),               INTENT(in) ::   dta  ! OBC external data
+      INTEGER,                      INTENT(in) ::   ib_bdy  ! BDY set index
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pssh, phur, phvr
+      LOGICAL                     , INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      INTEGER  ::   ibeg, iend                       ! length of rim to be treated (rim 0 or rim 1)
+      INTEGER  ::   jb, igrd                         ! dummy loop indices
+      INTEGER  ::   ii, ij                           ! 2D addresses
+      INTEGER  ::   iiTrim, ijTrim                   ! T pts i/j-indice on the rim
+      INTEGER  ::   iiToce, ijToce, iiUoce, ijVoce   ! T, U and V pts i/j-indice of the ocean next to the rim
+      REAL(wp) ::   flagu, flagv                     ! short cuts
+      REAL(wp) ::   zfla                             ! Flather correction
+      REAL(wp) ::   z1_2                             ! 
+      REAL(wp), DIMENSION(jpi,jpj) ::   sshdta       ! 2D version of dta%ssh
+      !!----------------------------------------------------------------------
+
+      z1_2 = 0.5_wp
+
+      ! ---------------------------------!
+      ! Flather boundary conditions     :!
+      ! ---------------------------------!
+
+      ! Fill temporary array with ssh data (here we use spgu with the alias sshdta):
+      igrd = 1
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)
+      ELSE                ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)
+      END IF
+      !
+      DO jb = ibeg, iend
+         ii = idx%nbi(jb,igrd)
+         ij = idx%nbj(jb,igrd)
+         IF( ll_wd ) THEN   ;   sshdta(ii, ij) = dta%ssh(jb) - ssh_ref 
+         ELSE               ;   sshdta(ii, ij) = dta%ssh(jb)
+         ENDIF
+      END DO
+      !
+      igrd = 2      ! Flather bc on u-velocity
+      !             ! remember that flagu=-1 if normal velocity direction is outward
+      !             ! I think we should rather use after ssh ?
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)
+      ELSE                ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)
+      END IF
+      DO jb = ibeg, iend
+         ii    = idx%nbi(jb,igrd)
+         ij    = idx%nbj(jb,igrd)
+         flagu = idx%flagu(jb,igrd)
+         IF( flagu == 0. ) THEN
+            pua2d(ii,ij) = dta%u2d(jb)
+         ELSE      ! T pts j-indice       on the rim          on the ocean next to the rim on T and U points
+            IF( flagu ==  1. ) THEN   ;   iiTrim = ii     ;   iiToce = ii+1   ;   iiUoce = ii+1   ;   ENDIF
+            IF( flagu == -1. ) THEN   ;   iiTrim = ii+1   ;   iiToce = ii     ;   iiUoce = ii-1   ;   ENDIF
+            !
+            ! Rare case : rim is parallel to the mpi subdomain border and on the halo : point will be received
+            IF( iiTrim > jpi .OR. iiToce > jpi .OR. iiUoce > jpi .OR. iiUoce < 1 )   CYCLE   
+            !
+            zfla = dta%u2d(jb) - flagu * SQRT( grav * phur(ii, ij) ) * ( pssh(iiToce,ij) - sshdta(iiTrim,ij) )
+            !
+            ! jchanut tschanges, use characteristics method (Blayo et Debreu, 2005) :
+            ! mix Flather scheme with velocity of the ocean next to the rim
+            pua2d(ii,ij) =  z1_2 * ( pua2d(iiUoce,ij) + zfla )
+         END IF
+      END DO
+      !
+      igrd = 3      ! Flather bc on v-velocity
+      !             ! remember that flagv=-1 if normal velocity direction is outward
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)
+      ELSE                ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)
+      END IF
+      DO jb = ibeg, iend
+         ii    = idx%nbi(jb,igrd)
+         ij    = idx%nbj(jb,igrd)
+         flagv = idx%flagv(jb,igrd)
+         IF( flagv == 0. ) THEN
+            pva2d(ii,ij) = dta%v2d(jb)
+         ELSE      ! T pts j-indice       on the rim          on the ocean next to the rim on T and V points
+            IF( flagv ==  1. ) THEN   ;   ijTrim = ij     ;   ijToce = ij+1   ;   ijVoce = ij+1   ;   ENDIF
+            IF( flagv == -1. ) THEN   ;   ijTrim = ij+1   ;   ijToce = ij     ;   ijVoce = ij-1   ;   ENDIF
+            !
+            ! Rare case : rim is parallel to the mpi subdomain border and on the halo : point will be received
+            IF( ijTrim > jpj .OR. ijToce > jpj .OR. ijVoce > jpj .OR. ijVoce < 1 )   CYCLE
+            !
+            zfla = dta%v2d(jb) - flagv * SQRT( grav * phvr(ii, ij) ) * ( pssh(ii,ijToce) - sshdta(ii,ijTrim) )
+            !
+            ! jchanut tschanges, use characteristics method (Blayo et Debreu, 2005) :
+            ! mix Flather scheme with velocity of the ocean next to the rim
+            pva2d(ii,ij) =  z1_2 * ( pva2d(ii,ijVoce) + zfla )
+         END IF
+      END DO
+      !
+   END SUBROUTINE bdy_dyn2d_fla
+
+
+   SUBROUTINE bdy_dyn2d_orlanski( idx, dta, ib_bdy, pua2d, pva2d, pub2d, pvb2d, llrim0, ll_npo )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_dyn2d_orlanski  ***
+      !!             
+      !!              - Apply Orlanski radiation condition adaptively:
+      !!                  - radiation plus weak nudging at outflow points
+      !!                  - no radiation and strong nudging at inflow points
+      !! 
+      !!
+      !! References:  Marchesiello, McWilliams and Shchepetkin, Ocean Modelling vol. 3 (2001)    
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),              INTENT(in) ::   idx  ! OBC indices
+      TYPE(OBC_DATA),               INTENT(in) ::   dta  ! OBC external data
+      INTEGER,                      INTENT(in) ::   ib_bdy  ! number of current open boundary set
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pub2d, pvb2d 
+      LOGICAL,                      INTENT(in) ::   ll_npo  ! flag for NPO version
+      LOGICAL,                      INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      INTEGER  ::   ib, igrd                               ! dummy loop indices
+      INTEGER  ::   ii, ij, iibm1, ijbm1                   ! indices
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2      ! Orlanski bc on u-velocity; 
+      !            
+      CALL bdy_orlanski_2d( idx, igrd, pub2d, pua2d, dta%u2d, llrim0, ll_npo )
+
+      igrd = 3      ! Orlanski bc on v-velocity
+      !  
+      CALL bdy_orlanski_2d( idx, igrd, pvb2d, pva2d, dta%v2d, llrim0, ll_npo )
+      !
+   END SUBROUTINE bdy_dyn2d_orlanski
+
+
+   SUBROUTINE bdy_ssh( zssh )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_ssh  ***
+      !!
+      !! ** Purpose : Duplicate sea level across open boundaries
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,1), INTENT(inout) ::   zssh ! Sea level, need 3 dimensions to be used by bdy_nmn
+      !!
+      INTEGER ::   ib_bdy, ir      ! bdy index, rim index
+      INTEGER ::   ibeg, iend      ! length of rim to be treated (rim 0 or rim 1)
+      LOGICAL ::   llrim0          ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4) :: llsend1, llrecv1  ! indicate how communications are to be carried out
+      !!----------------------------------------------------------------------
+      llsend1(:) = .false.   ;   llrecv1(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend1(:) = .false.   ;   llrecv1(:) = .false.   ;   END IF
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO ib_bdy = 1, nb_bdy
+            CALL bdy_nmn( idx_bdy(ib_bdy), 1, zssh, llrim0 )   ! zssh is masked
+            llsend1(:) = llsend1(:) .OR. lsend_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+            llrecv1(:) = llrecv1(:) .OR. lrecv_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+         END DO
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( ANY(llsend1) .OR. ANY(llrecv1) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdydyn2d', zssh(:,:,1), 'T',  1., kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+         END IF
+      END DO
+      !
+   END SUBROUTINE bdy_ssh
+
+   !!======================================================================
+END MODULE bdydyn2d
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn3d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn3d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdydyn3d.F90	(revision 14097)
@@ -0,0 +1,398 @@
+MODULE bdydyn3d
+   !!======================================================================
+   !!                       ***  MODULE  bdydyn3d  ***
+   !! Unstructured Open Boundary Cond. :   Flow relaxation scheme on baroclinic velocities
+   !!======================================================================
+   !! History :  3.4  !  2011     (D. Storkey) new module as part of BDY rewrite 
+   !!            3.5  !  2012     (S. Mocavero, I. Epicoco) Optimization of BDY communications
+   !!----------------------------------------------------------------------
+   !!   bdy_dyn3d        : apply open boundary conditions to baroclinic velocities
+   !!   bdy_dyn3d_frs    : apply Flow Relaxation Scheme
+   !!----------------------------------------------------------------------
+   USE timing          ! Timing
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE bdy_oce         ! ocean open boundary conditions
+   USE bdylib          ! for orlanski library routines
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  !
+   USE lib_mpp, ONLY: ctl_stop
+   Use phycst
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_dyn3d     ! routine called by bdy_dyn
+   PUBLIC   bdy_dyn3d_dmp ! routine called by step
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_dyn3d( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d  ***
+      !!
+      !! ** Purpose : - Apply open boundary conditions for baroclinic velocities
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! Main time step counter
+      !
+      INTEGER  ::   ib_bdy, ir     ! BDY set index, rim index
+      LOGICAL  ::   llrim0         ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4) :: llsend2, llrecv2, llsend3, llrecv3  ! indicate how communications are to be carried out
+
+      !!----------------------------------------------------------------------
+      llsend2(:) = .false.   ;   llrecv2(:) = .false.
+      llsend3(:) = .false.   ;   llrecv3(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            !
+            SELECT CASE( cn_dyn3d(ib_bdy) )
+            CASE('none')        ;   CYCLE
+            CASE('frs' )        ! treat the whole boundary at once
+               IF( ir == 0) CALL bdy_dyn3d_frs( idx_bdy(ib_bdy), dta_bdy(ib_bdy), kt, ib_bdy )
+            CASE('specified')   ! treat the whole rim      at once
+               IF( ir == 0) CALL bdy_dyn3d_spe( idx_bdy(ib_bdy), dta_bdy(ib_bdy), kt, ib_bdy )
+            CASE('zero')        ! treat the whole rim      at once
+               IF( ir == 0) CALL bdy_dyn3d_zro( idx_bdy(ib_bdy), dta_bdy(ib_bdy), kt, ib_bdy )
+            CASE('orlanski' )   ;   CALL bdy_dyn3d_orlanski( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, llrim0, ll_npo=.false. )
+            CASE('orlanski_npo');   CALL bdy_dyn3d_orlanski( idx_bdy(ib_bdy), dta_bdy(ib_bdy), ib_bdy, llrim0, ll_npo=.true.  )
+            CASE('zerograd')    ;   CALL bdy_dyn3d_zgrad( idx_bdy(ib_bdy), dta_bdy(ib_bdy), kt, ib_bdy, llrim0 )
+            CASE('neumann')     ;   CALL bdy_dyn3d_nmn( idx_bdy(ib_bdy), ib_bdy, llrim0 )
+            CASE DEFAULT        ;   CALL ctl_stop( 'bdy_dyn3d : unrecognised option for open boundaries for baroclinic velocities' )
+            END SELECT
+         END DO
+         !
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN
+            llsend2(:) = .false.   ;   llrecv2(:) = .false.
+            llsend3(:) = .false.   ;   llrecv3(:) = .false.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            SELECT CASE( cn_dyn3d(ib_bdy) )
+            CASE('orlanski', 'orlanski_npo')
+               llsend2(:) = llsend2(:) .OR. lsend_bdy(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llrecv2(:) = llrecv2(:) .OR. lrecv_bdy(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llsend3(:) = llsend3(:) .OR. lsend_bdy(ib_bdy,3,:,ir)   ! possibly every direction, V points
+               llrecv3(:) = llrecv3(:) .OR. lrecv_bdy(ib_bdy,3,:,ir)   ! possibly every direction, V points
+            CASE('zerograd')
+               llsend2(3:4) = llsend2(3:4) .OR. lsend_bdyint(ib_bdy,2,3:4,ir)   ! north/south, U points
+               llrecv2(3:4) = llrecv2(3:4) .OR. lrecv_bdyint(ib_bdy,2,3:4,ir)   ! north/south, U points
+               llsend3(1:2) = llsend3(1:2) .OR. lsend_bdyint(ib_bdy,3,1:2,ir)   ! west/east, V points
+               llrecv3(1:2) = llrecv3(1:2) .OR. lrecv_bdyint(ib_bdy,3,1:2,ir)   ! west/east, V points
+            CASE('neumann')
+               llsend2(:) = llsend2(:) .OR. lsend_bdyint(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llrecv2(:) = llrecv2(:) .OR. lrecv_bdyint(ib_bdy,2,:,ir)   ! possibly every direction, U points
+               llsend3(:) = llsend3(:) .OR. lsend_bdyint(ib_bdy,3,:,ir)   ! possibly every direction, V points
+               llrecv3(:) = llrecv3(:) .OR. lrecv_bdyint(ib_bdy,3,:,ir)   ! possibly every direction, V points
+            END SELECT
+         END DO
+         !
+         IF( ANY(llsend2) .OR. ANY(llrecv2) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdydyn2d', ua, 'U', -1., kfillmode=jpfillnothing ,lsend=llsend2, lrecv=llrecv2 )
+         END IF
+         IF( ANY(llsend3) .OR. ANY(llrecv3) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdydyn2d', va, 'V', -1., kfillmode=jpfillnothing ,lsend=llsend3, lrecv=llrecv3 )
+         END IF
+      END DO   ! ir
+      !
+   END SUBROUTINE bdy_dyn3d
+
+
+   SUBROUTINE bdy_dyn3d_spe( idx, dta, kt , ib_bdy )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d_spe  ***
+      !!
+      !! ** Purpose : - Apply a specified value for baroclinic velocities
+      !!                at open boundaries.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER        , INTENT(in) ::   kt      ! time step index
+      TYPE(OBC_INDEX), INTENT(in) ::   idx     ! OBC indices
+      TYPE(OBC_DATA) , INTENT(in) ::   dta     ! OBC external data
+      INTEGER        , INTENT(in) ::   ib_bdy  ! BDY set index
+      !
+      INTEGER  ::   jb, jk         ! dummy loop indices
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2                      ! Relaxation of zonal velocity
+      DO jb = 1, idx%nblenrim(igrd)
+         DO jk = 1, jpkm1
+            ii   = idx%nbi(jb,igrd)
+            ij   = idx%nbj(jb,igrd)
+            ua(ii,ij,jk) = dta%u3d(jb,jk) * umask(ii,ij,jk)
+         END DO
+      END DO
+      !
+      igrd = 3                      ! Relaxation of meridional velocity
+      DO jb = 1, idx%nblenrim(igrd)
+         DO jk = 1, jpkm1
+            ii   = idx%nbi(jb,igrd)
+            ij   = idx%nbj(jb,igrd)
+            va(ii,ij,jk) = dta%v3d(jb,jk) * vmask(ii,ij,jk)
+         END DO
+      END DO
+      !
+   END SUBROUTINE bdy_dyn3d_spe
+
+
+   SUBROUTINE bdy_dyn3d_zgrad( idx, dta, kt, ib_bdy, llrim0 )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d_zgrad  ***
+      !!
+      !! ** Purpose : - Enforce a zero gradient of normal velocity
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                     ::   kt
+      TYPE(OBC_INDEX), INTENT(in) ::   idx      ! OBC indices
+      TYPE(OBC_DATA),  INTENT(in) ::   dta      ! OBC external data
+      INTEGER,         INTENT(in) ::   ib_bdy   ! BDY set index
+      LOGICAL,         INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      !!
+      INTEGER  ::   jb, jk         ! dummy loop indices
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      INTEGER  ::   flagu, flagv           ! short cuts
+      INTEGER  ::   ibeg, iend     ! length of rim to be treated (rim 0 or rim 1 or both)
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2                      ! Copying tangential velocity into bdy points
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)
+      ELSE                ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)
+      ENDIF
+      DO jb = ibeg, iend
+         ii    = idx%nbi(jb,igrd)
+         ij    = idx%nbj(jb,igrd)
+         flagu = NINT(idx%flagu(jb,igrd))
+         flagv = NINT(idx%flagv(jb,igrd))
+         !
+         IF( flagu == 0 )   THEN              ! north/south bdy
+            IF( ij+flagv > jpj .OR. ij+flagv < 1 )   CYCLE      
+            !
+            DO jk = 1, jpkm1
+               ua(ii,ij,jk) = ua(ii,ij+flagv,jk) * umask(ii,ij+flagv,jk)
+            END DO
+            !
+         END IF
+      END DO
+      !
+      igrd = 3                      ! Copying tangential velocity into bdy points
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)
+      ELSE                ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)
+      ENDIF
+      DO jb = ibeg, iend
+         ii    = idx%nbi(jb,igrd)
+         ij    = idx%nbj(jb,igrd)
+         flagu = NINT(idx%flagu(jb,igrd))
+         flagv = NINT(idx%flagv(jb,igrd))
+         !
+         IF( flagv == 0 )   THEN              !  west/east  bdy
+            IF( ii+flagu > jpi .OR. ii+flagu < 1 )   CYCLE      
+            !
+            DO jk = 1, jpkm1
+               va(ii,ij,jk) = va(ii+flagu,ij,jk) * vmask(ii+flagu,ij,jk)
+            END DO
+            !
+         END IF
+      END DO
+      !
+   END SUBROUTINE bdy_dyn3d_zgrad
+
+
+   SUBROUTINE bdy_dyn3d_zro( idx, dta, kt, ib_bdy )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d_zro  ***
+      !!
+      !! ** Purpose : - baroclinic velocities = 0. at open boundaries.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER        , INTENT(in) ::   kt      ! time step index
+      TYPE(OBC_INDEX), INTENT(in) ::   idx     ! OBC indices
+      TYPE(OBC_DATA) , INTENT(in) ::   dta     ! OBC external data
+      INTEGER,         INTENT(in) ::   ib_bdy  ! BDY set index
+      !
+      INTEGER  ::   ib, ik         ! dummy loop indices
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2                       ! Everything is at T-points here
+      DO ib = 1, idx%nblenrim(igrd)
+         ii = idx%nbi(ib,igrd)
+         ij = idx%nbj(ib,igrd)
+         DO ik = 1, jpkm1
+            ua(ii,ij,ik) = 0._wp
+         END DO
+      END DO
+      !
+      igrd = 3                       ! Everything is at T-points here
+      DO ib = 1, idx%nblenrim(igrd)
+         ii = idx%nbi(ib,igrd)
+         ij = idx%nbj(ib,igrd)
+         DO ik = 1, jpkm1
+            va(ii,ij,ik) = 0._wp
+         END DO
+      END DO
+      !
+   END SUBROUTINE bdy_dyn3d_zro
+
+
+   SUBROUTINE bdy_dyn3d_frs( idx, dta, kt, ib_bdy )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d_frs  ***
+      !!
+      !! ** Purpose : - Apply the Flow Relaxation Scheme for baroclinic velocities
+      !!                at open boundaries.
+      !!
+      !! References :- Engedahl H., 1995: Use of the flow relaxation scheme in 
+      !!               a three-dimensional baroclinic ocean model with realistic
+      !!               topography. Tellus, 365-382.
+      !!----------------------------------------------------------------------
+      INTEGER        , INTENT(in) ::   kt      ! time step index
+      TYPE(OBC_INDEX), INTENT(in) ::   idx     ! OBC indices
+      TYPE(OBC_DATA) , INTENT(in) ::   dta     ! OBC external data
+      INTEGER,         INTENT(in) ::   ib_bdy  ! BDY set index
+      !
+      INTEGER  ::   jb, jk         ! dummy loop indices
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      REAL(wp) ::   zwgt           ! boundary weight
+      !!----------------------------------------------------------------------
+      !
+      igrd = 2                      ! Relaxation of zonal velocity
+      DO jb = 1, idx%nblen(igrd)
+         DO jk = 1, jpkm1
+            ii   = idx%nbi(jb,igrd)
+            ij   = idx%nbj(jb,igrd)
+            zwgt = idx%nbw(jb,igrd)
+            ua(ii,ij,jk) = ( ua(ii,ij,jk) + zwgt * ( dta%u3d(jb,jk) - ua(ii,ij,jk) ) ) * umask(ii,ij,jk)
+         END DO
+      END DO
+      !
+      igrd = 3                      ! Relaxation of meridional velocity
+      DO jb = 1, idx%nblen(igrd)
+         DO jk = 1, jpkm1
+            ii   = idx%nbi(jb,igrd)
+            ij   = idx%nbj(jb,igrd)
+            zwgt = idx%nbw(jb,igrd)
+            va(ii,ij,jk) = ( va(ii,ij,jk) + zwgt * ( dta%v3d(jb,jk) - va(ii,ij,jk) ) ) * vmask(ii,ij,jk)
+         END DO
+      END DO   
+      !
+   END SUBROUTINE bdy_dyn3d_frs
+
+
+   SUBROUTINE bdy_dyn3d_orlanski( idx, dta, ib_bdy, llrim0, ll_npo )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_dyn3d_orlanski  ***
+      !!             
+      !!              - Apply Orlanski radiation to baroclinic velocities. 
+      !!              - Wrapper routine for bdy_orlanski_3d
+      !! 
+      !!
+      !! References:  Marchesiello, McWilliams and Shchepetkin, Ocean Modelling vol. 3 (2001)    
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),              INTENT(in) ::   idx  ! OBC indices
+      TYPE(OBC_DATA),               INTENT(in) ::   dta  ! OBC external data
+      INTEGER,                      INTENT(in) ::   ib_bdy   ! BDY set index
+      LOGICAL,                      INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      LOGICAL,                      INTENT(in) ::   ll_npo   ! switch for NPO version
+
+      INTEGER  ::   jb, igrd                               ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      !! Note that at this stage the ub and ua arrays contain the baroclinic velocities. 
+      !
+      igrd = 2      ! Orlanski bc on u-velocity; 
+      !            
+      CALL bdy_orlanski_3d( idx, igrd, ub, ua, dta%u3d, ll_npo, llrim0 )
+
+      igrd = 3      ! Orlanski bc on v-velocity
+      !  
+      CALL bdy_orlanski_3d( idx, igrd, vb, va, dta%v3d, ll_npo, llrim0 )
+      !
+   END SUBROUTINE bdy_dyn3d_orlanski
+
+
+   SUBROUTINE bdy_dyn3d_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_dyn3d_dmp  ***
+      !!
+      !! ** Purpose : Apply damping for baroclinic velocities at open boundaries.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step index
+      !
+      INTEGER  ::   jb, jk         ! dummy loop indices
+      INTEGER  ::   ib_bdy         ! loop index
+      INTEGER  ::   ii, ij, igrd   ! local integers
+      REAL(wp) ::   zwgt           ! boundary weight
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('bdy_dyn3d_dmp')
+      !
+      DO ib_bdy=1, nb_bdy
+         IF ( ln_dyn3d_dmp(ib_bdy) .and. cn_dyn3d(ib_bdy) /= 'none' ) THEN
+            igrd = 2                      ! Relaxation of zonal velocity
+            DO jb = 1, idx_bdy(ib_bdy)%nblen(igrd)
+               ii   = idx_bdy(ib_bdy)%nbi(jb,igrd)
+               ij   = idx_bdy(ib_bdy)%nbj(jb,igrd)
+               zwgt = idx_bdy(ib_bdy)%nbd(jb,igrd)
+               DO jk = 1, jpkm1
+                  ua(ii,ij,jk) = ( ua(ii,ij,jk) + zwgt * ( dta_bdy(ib_bdy)%u3d(jb,jk) - &
+                                   ub(ii,ij,jk) + ub_b(ii,ij)) ) * umask(ii,ij,jk)
+               END DO
+            END DO
+            !
+            igrd = 3                      ! Relaxation of meridional velocity
+            DO jb = 1, idx_bdy(ib_bdy)%nblen(igrd)
+               ii   = idx_bdy(ib_bdy)%nbi(jb,igrd)
+               ij   = idx_bdy(ib_bdy)%nbj(jb,igrd)
+               zwgt = idx_bdy(ib_bdy)%nbd(jb,igrd)
+               DO jk = 1, jpkm1
+                  va(ii,ij,jk) = ( va(ii,ij,jk) + zwgt * ( dta_bdy(ib_bdy)%v3d(jb,jk) -  &
+                                   vb(ii,ij,jk) + vb_b(ii,ij)) ) * vmask(ii,ij,jk)
+               END DO
+            END DO
+         ENDIF
+      END DO
+      !
+      IF( ln_timing )   CALL timing_stop('bdy_dyn3d_dmp')
+      !
+   END SUBROUTINE bdy_dyn3d_dmp
+
+
+   SUBROUTINE bdy_dyn3d_nmn( idx, ib_bdy, llrim0 )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_dyn3d_nmn  ***
+      !!             
+      !!              - Apply Neumann condition to baroclinic velocities. 
+      !!              - Wrapper routine for bdy_nmn
+      !! 
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX), INTENT(in) ::   idx      ! OBC indices
+      INTEGER,         INTENT(in) ::   ib_bdy   ! BDY set index
+      LOGICAL,         INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      INTEGER  ::   igrd                        ! dummy indice
+      !!----------------------------------------------------------------------
+      !
+      !! Note that at this stage the ub and ua arrays contain the baroclinic velocities. 
+      !
+      igrd = 2      ! Neumann bc on u-velocity; 
+      !            
+      CALL bdy_nmn( idx, igrd, ua, llrim0 )   ! ua is masked
+
+      igrd = 3      ! Neumann bc on v-velocity
+      !  
+      CALL bdy_nmn( idx, igrd, va, llrim0 )   ! va is masked
+      !
+   END SUBROUTINE bdy_dyn3d_nmn
+
+   !!======================================================================
+END MODULE bdydyn3d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyice.F90	(revision 14097)
@@ -0,0 +1,475 @@
+MODULE bdyice
+   !!======================================================================
+   !!                       ***  MODULE  bdyice  ***
+   !! Unstructured Open Boundary Cond. :  Open boundary conditions for sea-ice (SI3)
+   !!======================================================================
+   !!  History :  3.3  !  2010-09 (D. Storkey)  Original code
+   !!             3.4  !  2012-01 (C. Rousset)  add new sea ice model 
+   !!             4.0  !  2018    (C. Rousset)  SI3 compatibility 
+   !!----------------------------------------------------------------------
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                          SI3 sea ice model
+   !!----------------------------------------------------------------------
+   !!   bdy_ice        : Application of open boundaries to ice
+   !!   bdy_ice_frs    : Application of Flow Relaxation Scheme
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE ice             ! sea-ice: variables
+   USE icevar          ! sea-ice: operations
+   USE icecor          ! sea-ice: corrections
+   USE icectl          ! sea-ice: control prints
+   USE phycst          ! physical constant
+   USE eosbn2          ! equation of state
+   USE par_oce         ! ocean parameters
+   USE dom_oce         ! ocean space and time domain variables 
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE bdy_oce         ! ocean open boundary conditions
+   !
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  ! write to numout file
+   USE lib_mpp         ! distributed memory computing
+   USE lib_fortran     ! to use key_nosignedzero
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_ice     ! routine called in sbcmod
+   PUBLIC   bdy_ice_dyn ! routine called in icedyn_rhg_evp
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_ice( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_ice  ***
+      !!
+      !! ** Purpose : Apply open boundary conditions for sea ice
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! Main time step counter
+      !
+      INTEGER ::   jbdy, ir                             ! BDY set index, rim index
+      INTEGER ::   ibeg, iend                           ! length of rim to be treated (rim 0 or rim 1)
+      LOGICAL ::   llrim0                               ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4)  :: llsend1, llrecv1        ! indicate how communications are to be carried out
+      !!----------------------------------------------------------------------
+      ! controls
+      IF( ln_timing )   CALL timing_start('bdy_ice_thd')   ! timing
+      !
+      CALL ice_var_glo2eqv
+      !
+      llsend1(:) = .false.   ;   llrecv1(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO jbdy = 1, nb_bdy
+            !
+            SELECT CASE( cn_ice(jbdy) )
+            CASE('none')   ;   CYCLE
+            CASE('frs' )   ;   CALL bdy_ice_frs( idx_bdy(jbdy), dta_bdy(jbdy), kt, jbdy, llrim0 )
+            CASE DEFAULT
+               CALL ctl_stop( 'bdy_ice : unrecognised option for open boundaries for ice fields' )
+            END SELECT
+            !
+         END DO
+         !
+         ! Update bdy points        
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend1(:) = .false.   ;   llrecv1(:) = .false.   ;   END IF
+         DO jbdy = 1, nb_bdy
+            IF( cn_ice(jbdy) == 'frs' ) THEN
+               llsend1(:) = llsend1(:) .OR. lsend_bdyint(jbdy,1,:,ir)   ! possibly every direction, T points
+               llrecv1(:) = llrecv1(:) .OR. lrecv_bdyint(jbdy,1,:,ir)   ! possibly every direction, T points
+            END IF
+         END DO   ! jbdy
+         IF( ANY(llsend1) .OR. ANY(llrecv1) ) THEN   ! if need to send/recv in at least one direction
+            ! exchange 3d arrays
+            CALL lbc_lnk_multi( 'bdyice', a_i , 'T', 1., h_i , 'T', 1., h_s , 'T', 1., oa_i, 'T', 1.                 &
+               &                        , s_i , 'T', 1., t_su, 'T', 1., v_i , 'T', 1., v_s , 'T', 1., sv_i, 'T', 1.  &
+               &                        , a_ip, 'T', 1., v_ip, 'T', 1., v_il, 'T', 1.                                &
+               &                        , kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+            ! exchange 4d arrays :   third dimension = 1   and then   third dimension = jpk
+            CALL lbc_lnk_multi( 'bdyice', t_s , 'T', 1., e_s , 'T', 1., kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+            CALL lbc_lnk_multi( 'bdyice', t_i , 'T', 1., e_i , 'T', 1., kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+         END IF
+      END DO   ! ir
+      !
+      CALL ice_cor( kt , 0 )      ! -- In case categories are out of bounds, do a remapping
+      !                           !    i.e. inputs have not the same ice thickness distribution (set by rn_himean)
+      !                           !         than the regional simulation
+      CALL ice_var_agg(1)
+      !
+      ! controls
+      IF( ln_icectl )   CALL ice_prt     ( kt, iiceprt, jiceprt, 1, ' - ice thermo bdy - ' )   ! prints
+      IF( ln_timing )   CALL timing_stop ('bdy_ice_thd')                                       ! timing
+      !
+   END SUBROUTINE bdy_ice
+
+
+   SUBROUTINE bdy_ice_frs( idx, dta, kt, jbdy, llrim0 )
+      !!------------------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_ice_frs  ***
+      !!                    
+      !! ** Purpose : Apply the Flow Relaxation Scheme for sea-ice fields
+      !! 
+      !! Reference : Engedahl H., 1995: Use of the flow relaxation scheme in a three-
+      !!             dimensional baroclinic ocean model with realistic topography. Tellus, 365-382.
+      !!------------------------------------------------------------------------------
+      TYPE(OBC_INDEX), INTENT(in) ::   idx      ! OBC indices
+      TYPE(OBC_DATA),  INTENT(in) ::   dta      ! OBC external data
+      INTEGER,         INTENT(in) ::   kt       ! main time-step counter
+      INTEGER,         INTENT(in) ::   jbdy     ! BDY set index
+      LOGICAL,         INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      !
+      INTEGER  ::   jpbound            ! 0 = incoming ice
+      !                                ! 1 = outgoing ice
+      INTEGER  ::   ibeg, iend         ! length of rim to be treated (rim 0 or rim 1)
+      INTEGER  ::   i_bdy, jgrd        ! dummy loop indices
+      INTEGER  ::   ji, jj, jk, jl, ib, jb
+      REAL(wp) ::   zwgt, zwgt1        ! local scalar
+      REAL(wp) ::   ztmelts, zdh
+      REAL(wp), POINTER  :: flagu, flagv              ! short cuts
+      !!------------------------------------------------------------------------------
+      !
+      jgrd = 1      ! Everything is at T-points here
+      IF( llrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(jgrd)
+      ELSE                ;   ibeg = idx%nblenrim0(jgrd)+1   ;   iend = idx%nblenrim(jgrd)
+      END IF
+      !
+      DO jl = 1, jpl
+         DO i_bdy = ibeg, iend
+            ji    = idx%nbi(i_bdy,jgrd)
+            jj    = idx%nbj(i_bdy,jgrd)
+            zwgt  = idx%nbw(i_bdy,jgrd)
+            zwgt1 = 1.e0 - idx%nbw(i_bdy,jgrd)
+            a_i (ji,jj,  jl) = ( a_i (ji,jj,  jl) * zwgt1 + dta%a_i(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  concentration 
+            h_i (ji,jj,  jl) = ( h_i (ji,jj,  jl) * zwgt1 + dta%h_i(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  depth 
+            h_s (ji,jj,  jl) = ( h_s (ji,jj,  jl) * zwgt1 + dta%h_s(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Snow depth
+            t_i (ji,jj,:,jl) = ( t_i (ji,jj,:,jl) * zwgt1 + dta%t_i(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  temperature
+            t_s (ji,jj,:,jl) = ( t_s (ji,jj,:,jl) * zwgt1 + dta%t_s(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Snow temperature
+            t_su(ji,jj,  jl) = ( t_su(ji,jj,  jl) * zwgt1 + dta%tsu(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Surf temperature
+            s_i (ji,jj,  jl) = ( s_i (ji,jj,  jl) * zwgt1 + dta%s_i(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  salinity
+            a_ip(ji,jj,  jl) = ( a_ip(ji,jj,  jl) * zwgt1 + dta%aip(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  pond concentration
+            h_ip(ji,jj,  jl) = ( h_ip(ji,jj,  jl) * zwgt1 + dta%hip(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  pond depth
+            h_il(ji,jj,  jl) = ( h_il(ji,jj,  jl) * zwgt1 + dta%hil(i_bdy,jl) * zwgt ) * tmask(ji,jj,1)  ! Ice  pond lid depth
+            !
+            sz_i(ji,jj,:,jl) = s_i(ji,jj,jl)
+            !
+            ! make sure ponds = 0 if no ponds scheme
+            IF( .NOT.ln_pnd ) THEN
+               a_ip(ji,jj,jl) = 0._wp
+               h_ip(ji,jj,jl) = 0._wp
+               h_il(ji,jj,jl) = 0._wp
+            ENDIF
+
+            IF( .NOT.ln_pnd_lids ) THEN
+               h_il(ji,jj,jl) = 0._wp
+            ENDIF
+            !
+            ! -----------------
+            ! Pathological case
+            ! -----------------
+            ! In case a) snow load would be in excess or b) ice is coming into a warmer environment that would lead to 
+            ! very large transformation from snow to ice (see icethd_dh.F90)
+
+            ! Then, a) transfer the snow excess into the ice (different from icethd_dh)
+            zdh = MAX( 0._wp, ( rhos * h_s(ji,jj,jl) + ( rhoi - rau0 ) * h_i(ji,jj,jl) ) * r1_rau0 )
+            ! Or, b) transfer all the snow into ice (if incoming ice is likely to melt as it comes into a warmer environment)
+            !zdh = MAX( 0._wp, h_s(ji,jj,jl) * rhos / rhoi )
+
+            ! recompute h_i, h_s
+            h_i(ji,jj,jl) = MIN( hi_max(jl), h_i(ji,jj,jl) + zdh )
+            h_s(ji,jj,jl) = MAX( 0._wp, h_s(ji,jj,jl) - zdh * rhoi / rhos ) 
+            !
+         ENDDO
+      ENDDO
+
+      DO jl = 1, jpl
+         DO i_bdy = ibeg, iend
+            ji = idx%nbi(i_bdy,jgrd)
+            jj = idx%nbj(i_bdy,jgrd)
+            flagu => idx%flagu(i_bdy,jgrd)
+            flagv => idx%flagv(i_bdy,jgrd)
+            ! condition on ice thickness depends on the ice velocity
+            ! if velocity is outward (strictly), then ice thickness, volume... must be equal to adjacent values
+            jpbound = 0   ;   ib = ji   ;   jb = jj
+            !
+            IF( flagu ==  1. )   THEN
+               IF( ji+1 > jpi )   CYCLE
+               IF( u_ice(ji  ,jj  ) < 0. )   jpbound = 1 ; ib = ji+1
+            END IF
+            IF( flagu == -1. )   THEN
+               IF( ji-1 < 1   )   CYCLE
+               IF( u_ice(ji-1,jj  ) < 0. )   jpbound = 1 ; ib = ji-1
+            END IF
+            IF( flagv ==  1. )   THEN
+               IF( jj+1 > jpj )   CYCLE
+               IF( v_ice(ji  ,jj  ) < 0. )   jpbound = 1 ; jb = jj+1
+            END IF
+            IF( flagv == -1. )   THEN
+               IF( jj-1 < 1   )   CYCLE
+               IF( v_ice(ji  ,jj-1) < 0. )   jpbound = 1 ; jb = jj-1
+            END IF
+            !
+            IF( nn_ice_dta(jbdy) == 0 )   jpbound = 0 ; ib = ji ; jb = jj   ! case ice boundaries = initial conditions
+            !                                                               !      do not make state variables dependent on velocity
+            !
+            IF( a_i(ib,jb,jl) > 0._wp ) THEN   ! there is ice at the boundary
+               !
+               a_i (ji,jj,  jl) = a_i (ib,jb,  jl)
+               h_i (ji,jj,  jl) = h_i (ib,jb,  jl)
+               h_s (ji,jj,  jl) = h_s (ib,jb,  jl)
+               t_i (ji,jj,:,jl) = t_i (ib,jb,:,jl)
+               t_s (ji,jj,:,jl) = t_s (ib,jb,:,jl)
+               t_su(ji,jj,  jl) = t_su(ib,jb,  jl)
+               s_i (ji,jj,  jl) = s_i (ib,jb,  jl)
+               a_ip(ji,jj,  jl) = a_ip(ib,jb,  jl)
+               h_ip(ji,jj,  jl) = h_ip(ib,jb,  jl)
+               h_il(ji,jj,  jl) = h_il(ib,jb,  jl)
+               !
+               sz_i(ji,jj,:,jl) = sz_i(ib,jb,:,jl)
+               !
+               ! ice age
+               IF    ( jpbound == 0 ) THEN  ! velocity is inward
+                  oa_i(ji,jj,jl) = rice_age(jbdy) * a_i(ji,jj,jl)
+               ELSEIF( jpbound == 1 ) THEN  ! velocity is outward
+                  oa_i(ji,jj,jl) = oa_i(ib,jb,jl)
+               ENDIF
+               !
+               IF( nn_icesal == 1 ) THEN     ! if constant salinity
+                  s_i (ji,jj  ,jl) = rn_icesal
+                  sz_i(ji,jj,:,jl) = rn_icesal
+               ENDIF
+               !
+               ! global fields
+               v_i (ji,jj,jl) = h_i(ji,jj,jl) * a_i(ji,jj,jl)                          ! volume ice
+               v_s (ji,jj,jl) = h_s(ji,jj,jl) * a_i(ji,jj,jl)                          ! volume snw
+               sv_i(ji,jj,jl) = MIN( s_i(ji,jj,jl) , sss_m(ji,jj) ) * v_i(ji,jj,jl)    ! salt content
+               DO jk = 1, nlay_s
+                  t_s(ji,jj,jk,jl) = MIN( t_s(ji,jj,jk,jl), -0.15_wp + rt0 )           ! Force t_s to be lower than -0.15deg (arbitrary) => likely conservation issue
+                  !                                                                    !       otherwise instant melting can occur
+                  e_s(ji,jj,jk,jl) = rhos * ( rcpi * ( rt0 - t_s(ji,jj,jk,jl) ) + rLfus )   ! enthalpy in J/m3
+                  e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) * v_s(ji,jj,jl) * r1_nlay_s           ! enthalpy in J/m2
+               END DO
+               t_su(ji,jj,jl) = MIN( t_su(ji,jj,jl), -0.15_wp + rt0 )                  ! Force t_su to be lower than -0.15deg (arbitrary)
+               DO jk = 1, nlay_i
+                  ztmelts          = - rTmlt  * sz_i(ji,jj,jk,jl)                      ! Melting temperature in C
+                  t_i(ji,jj,jk,jl) = MIN( t_i(ji,jj,jk,jl), (ztmelts-0.15_wp) + rt0 )  ! Force t_i to be lower than melting point (-0.15) => likely conservation issue
+                  !                                                                    !       otherwise instant melting can occur 
+                  e_i(ji,jj,jk,jl) = rhoi * ( rcpi  * ( ztmelts - ( t_i(ji,jj,jk,jl) - rt0 ) )           &   ! enthalpy in J/m3
+                     &                      + rLfus * ( 1._wp - ztmelts / ( t_i(ji,jj,jk,jl) - rt0 ) )   &
+                     &                      - rcp   *   ztmelts )                  
+                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * v_i(ji,jj,jl) * r1_nlay_i                            ! enthalpy in J/m2
+               END DO
+               !
+               ! melt ponds
+               v_ip(ji,jj,jl) = h_ip(ji,jj,jl) * a_ip(ji,jj,jl)
+               v_il(ji,jj,jl) = h_il(ji,jj,jl) * a_ip(ji,jj,jl)
+               !
+            ELSE   ! no ice at the boundary
+               !
+               a_i (ji,jj,  jl) = 0._wp
+               h_i (ji,jj,  jl) = 0._wp
+               h_s (ji,jj,  jl) = 0._wp
+               oa_i(ji,jj,  jl) = 0._wp
+               t_su(ji,jj,  jl) = rt0
+               t_s (ji,jj,:,jl) = rt0
+               t_i (ji,jj,:,jl) = rt0 
+
+               a_ip(ji,jj,jl) = 0._wp
+               h_ip(ji,jj,jl) = 0._wp
+               h_il(ji,jj,jl) = 0._wp
+               
+               IF( nn_icesal == 1 ) THEN     ! if constant salinity
+                  s_i (ji,jj  ,jl) = rn_icesal
+                  sz_i(ji,jj,:,jl) = rn_icesal
+               ELSE                          ! if variable salinity
+                  s_i (ji,jj,jl)   = rn_simin
+                  sz_i(ji,jj,:,jl) = rn_simin
+               ENDIF
+               !
+               ! global fields
+               v_i (ji,jj,  jl) = 0._wp
+               v_s (ji,jj,  jl) = 0._wp
+               sv_i(ji,jj,  jl) = 0._wp
+               e_s (ji,jj,:,jl) = 0._wp
+               e_i (ji,jj,:,jl) = 0._wp
+               v_ip(ji,jj,  jl) = 0._wp
+               v_il(ji,jj,  jl) = 0._wp
+
+            ENDIF
+                        
+         END DO
+         !
+      END DO ! jl
+      !      
+   END SUBROUTINE bdy_ice_frs
+
+
+   SUBROUTINE bdy_ice_dyn( cd_type )
+      !!------------------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_ice_dyn  ***
+      !!                    
+      !! ** Purpose : Apply dynamics boundary conditions for sea-ice.
+      !!
+      !! ** Method :  if this adjacent grid point is not ice free, then u_ice and v_ice take its value
+      !!              if                          is     ice free, then u_ice and v_ice are unchanged by BDY
+      !!                                                           they keep values calculated in rheology
+      !!
+      !!------------------------------------------------------------------------------
+      CHARACTER(len=1), INTENT(in)  ::   cd_type   ! nature of velocity grid-points
+      !
+      INTEGER  ::   i_bdy, jgrd       ! dummy loop indices
+      INTEGER  ::   ji, jj            ! local scalar
+      INTEGER  ::   jbdy, ir     ! BDY set index, rim index
+      INTEGER  ::   ibeg, iend   ! length of rim to be treated (rim 0 or rim 1)
+      REAL(wp) ::   zmsk1, zmsk2, zflag
+      LOGICAL, DIMENSION(4) :: llsend2, llrecv2, llsend3, llrecv3  ! indicate how communications are to be carried out
+      !!------------------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('bdy_ice_dyn')
+      !
+      llsend2(:) = .false.   ;   llrecv2(:) = .false.
+      llsend3(:) = .false.   ;   llrecv3(:) = .false.
+      DO ir = 1, 0, -1
+         DO jbdy = 1, nb_bdy
+            !
+            SELECT CASE( cn_ice(jbdy) )
+               !
+            CASE('none')
+               CYCLE
+               !
+            CASE('frs')
+               !
+               IF( nn_ice_dta(jbdy) == 0 ) CYCLE            ! case ice boundaries = initial conditions 
+               !                                            !      do not change ice velocity (it is only computed by rheology)
+               SELECT CASE ( cd_type )
+                  !     
+               CASE ( 'U' )  
+                  jgrd = 2      ! u velocity
+                  IF( ir == 0 ) THEN   ;   ibeg = 1                                 ;   iend = idx_bdy(jbdy)%nblenrim0(jgrd)
+                  ELSE                 ;   ibeg = idx_bdy(jbdy)%nblenrim0(jgrd)+1   ;   iend = idx_bdy(jbdy)%nblenrim(jgrd)
+                  END IF
+                  DO i_bdy = ibeg, iend
+                     ji    = idx_bdy(jbdy)%nbi(i_bdy,jgrd)
+                     jj    = idx_bdy(jbdy)%nbj(i_bdy,jgrd)
+                     zflag = idx_bdy(jbdy)%flagu(i_bdy,jgrd)
+                     !     i-1  i   i    |  !        i  i i+1 |  !          i  i i+1 |
+                     !      >  ice  >    |  !        o  > ice |  !          o  >  o  |      
+                     ! => set at u_ice(i-1) !  => set to O       !  => unchanged
+                     IF( zflag == -1. .AND. ji > 1 .AND. ji < jpi )   THEN  
+                        IF    ( vt_i(ji  ,jj) > 0. )   THEN   ;   u_ice(ji,jj) = u_ice(ji-1,jj) 
+                        ELSEIF( vt_i(ji+1,jj) > 0. )   THEN   ;   u_ice(ji,jj) = 0._wp
+                        END IF
+                     END IF
+                     ! |    i  i+1 i+1        !  |  i   i i+1        !  | i  i i+1
+                     ! |    >  ice  >         !  | ice  >  o         !  | o  >  o   
+                     ! => set at u_ice(i+1)   !     => set to O      !     =>  unchanged
+                     IF( zflag ==  1. .AND. ji+1 < jpi+1 )   THEN
+                        IF    ( vt_i(ji+1,jj) > 0. )   THEN   ;   u_ice(ji,jj) = u_ice(ji+1,jj)
+                        ELSEIF( vt_i(ji  ,jj) > 0. )   THEN   ;   u_ice(ji,jj) = 0._wp
+                        END IF
+                     END IF
+                     !
+                     IF( zflag ==  0. )   u_ice(ji,jj) = 0._wp   ! u_ice = 0  if north/south bdy  
+                     !
+                  END DO
+                  !
+               CASE ( 'V' )
+                  jgrd = 3      ! v velocity
+                  IF( ir == 0 ) THEN   ;   ibeg = 1                                 ;   iend = idx_bdy(jbdy)%nblenrim0(jgrd)
+                  ELSE                 ;   ibeg = idx_bdy(jbdy)%nblenrim0(jgrd)+1   ;   iend = idx_bdy(jbdy)%nblenrim(jgrd)
+                  END IF
+                  DO i_bdy = ibeg, iend
+                     ji    = idx_bdy(jbdy)%nbi(i_bdy,jgrd)
+                     jj    = idx_bdy(jbdy)%nbj(i_bdy,jgrd)
+                     zflag = idx_bdy(jbdy)%flagv(i_bdy,jgrd)
+                     !                         !      ice   (jj+1)       !       o    (jj+1)
+                     !       ^    (jj  )       !       ^    (jj  )       !       ^    (jj  )       
+                     !      ice   (jj  )       !       o    (jj  )       !       o    (jj  )       
+                     !       ^    (jj-1)       !                         !
+                     ! => set to u_ice(jj-1)   !  =>   set to 0          !   => unchanged        
+                     IF( zflag == -1. .AND. jj > 1 .AND. jj < jpj )   THEN                 
+                        IF    ( vt_i(ji,jj  ) > 0. )   THEN   ;   v_ice(ji,jj) = v_ice(ji,jj-1)
+                        ELSEIF( vt_i(ji,jj+1) > 0. )   THEN   ;   v_ice(ji,jj) = 0._wp
+                        END IF
+                     END IF
+                     !       ^    (jj+1)       !                         !              
+                     !      ice   (jj+1)       !       o    (jj+1)       !       o    (jj+1)       
+                     !       ^    (jj  )       !       ^    (jj  )       !       ^    (jj  )
+                     !   ________________      !  ____ice___(jj  )_      !  _____o____(jj  ) 
+                     ! => set to u_ice(jj+1)   !    => set to 0          !    => unchanged  
+                     IF( zflag ==  1. .AND. jj < jpj )   THEN              
+                        IF    ( vt_i(ji,jj+1) > 0. )   THEN   ;   v_ice(ji,jj) = v_ice(ji,jj+1)
+                        ELSEIF( vt_i(ji,jj  ) > 0. )   THEN   ;   v_ice(ji,jj) = 0._wp
+                        END IF
+                     END IF
+                     !
+                     IF( zflag ==  0. )   v_ice(ji,jj) = 0._wp   ! v_ice = 0  if west/east bdy  
+                     !
+                  END DO
+                  !
+               END SELECT
+               !
+            CASE DEFAULT
+               CALL ctl_stop( 'bdy_ice_dyn : unrecognised option for open boundaries for ice fields' )
+            END SELECT
+            !
+         END DO    ! jbdy
+         !
+         SELECT CASE ( cd_type )        
+         CASE ( 'U' ) 
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend2(:) = .false.   ;   llrecv2(:) = .false.   ;   END IF
+            DO jbdy = 1, nb_bdy
+               IF( cn_ice(jbdy) == 'frs' .AND. nn_ice_dta(jbdy) /= 0 ) THEN
+                  llsend2(:) = llsend2(:) .OR. lsend_bdyint(jbdy,2,:,ir)   ! possibly every direction, U points
+                  llsend2(1) = llsend2(1) .OR. lsend_bdyext(jbdy,2,1,ir)   ! neighbour might search point towards its west bdy
+                  llrecv2(:) = llrecv2(:) .OR. lrecv_bdyint(jbdy,2,:,ir)   ! possibly every direction, U points
+                  llrecv2(2) = llrecv2(2) .OR. lrecv_bdyext(jbdy,2,2,ir)   ! might search point towards east bdy
+               END IF
+            END DO
+            IF( ANY(llsend2) .OR. ANY(llrecv2) ) THEN   ! if need to send/recv in at least one direction
+               CALL lbc_lnk( 'bdyice', u_ice, 'U', -1., kfillmode=jpfillnothing ,lsend=llsend2, lrecv=llrecv2 )
+            END IF
+         CASE ( 'V' )
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend3(:) = .false.   ;   llrecv3(:) = .false.   ;   END IF
+            DO jbdy = 1, nb_bdy
+               IF( cn_ice(jbdy) == 'frs' .AND. nn_ice_dta(jbdy) /= 0 ) THEN
+                  llsend3(:) = llsend3(:) .OR. lsend_bdyint(jbdy,3,:,ir)   ! possibly every direction, V points
+                  llsend3(3) = llsend3(3) .OR. lsend_bdyext(jbdy,3,3,ir)   ! neighbour might search point towards its south bdy
+                  llrecv3(:) = llrecv3(:) .OR. lrecv_bdyint(jbdy,3,:,ir)   ! possibly every direction, V points
+                  llrecv3(4) = llrecv3(4) .OR. lrecv_bdyext(jbdy,3,4,ir)   ! might search point towards north bdy
+               END IF
+            END DO
+            IF( ANY(llsend3) .OR. ANY(llrecv3) ) THEN   ! if need to send/recv in at least one direction
+               CALL lbc_lnk( 'bdyice', v_ice, 'V', -1., kfillmode=jpfillnothing ,lsend=llsend3, lrecv=llrecv3 )
+            END IF
+         END SELECT
+      END DO   ! ir
+      !
+      IF( ln_timing )   CALL timing_stop('bdy_ice_dyn')
+      !
+    END SUBROUTINE bdy_ice_dyn
+
+#else
+   !!---------------------------------------------------------------------------------
+   !!   Default option                                                    Empty module
+   !!---------------------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE bdy_ice( kt )      ! Empty routine
+      IMPLICIT NONE
+      INTEGER, INTENT( in ) :: kt
+      WRITE(*,*) 'bdy_ice: You should not have seen this print! error?', kt
+   END SUBROUTINE bdy_ice
+#endif
+
+   !!=================================================================================
+END MODULE bdyice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyini.F90	(revision 14097)
@@ -0,0 +1,1793 @@
+MODULE bdyini
+   !!======================================================================
+   !!                       ***  MODULE  bdyini  ***
+   !! Unstructured open boundaries : initialisation
+   !!======================================================================
+   !! History :  1.0  !  2005-01  (J. Chanut, A. Sellar)  Original code
+   !!             -   !  2007-01  (D. Storkey) Update to use IOM module
+   !!             -   !  2007-01  (D. Storkey) Tidal forcing
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.3  !  2010-09  (E.O'Dea) updates for Shelf configurations
+   !!            3.3  !  2010-09  (D.Storkey) add ice boundary conditions
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            3.4  !  2012     (J. Chanut) straight open boundary case update
+   !!            3.5  !  2012     (S. Mocavero, I. Epicoco) optimization of BDY communications
+   !!            3.7  !  2016     (T. Lovato) Remove bdy macro, call here init for dta and tides
+   !!----------------------------------------------------------------------
+   !!   bdy_init      : Initialization of unstructured open boundaries
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain
+   USE bdy_oce        ! unstructured open boundary conditions
+   USE bdydta         ! open boundary cond. setting   (bdy_dta_init routine)
+   USE bdytides       ! open boundary cond. setting   (bdytide_init routine)
+   USE sbctide        ! Tidal forcing or not
+   USE phycst   , ONLY: rday
+   !
+   USE in_out_manager ! I/O units
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! for mpp_sum  
+   USE iom            ! I/O
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_init    ! routine called in nemo_init
+   PUBLIC   find_neib   ! routine called in bdy_nmn
+
+   INTEGER, PARAMETER ::   jp_nseg = 100   ! 
+   ! Straight open boundary segment parameters:
+   INTEGER  ::   nbdysege, nbdysegw, nbdysegn, nbdysegs 
+   INTEGER, DIMENSION(jp_nseg) ::   jpieob, jpjedt, jpjeft, npckge   !
+   INTEGER, DIMENSION(jp_nseg) ::   jpiwob, jpjwdt, jpjwft, npckgw   !
+   INTEGER, DIMENSION(jp_nseg) ::   jpjnob, jpindt, jpinft, npckgn   !
+   INTEGER, DIMENSION(jp_nseg) ::   jpjsob, jpisdt, jpisft, npckgs   !
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_init  ***
+      !!
+      !! ** Purpose :   Initialization of the dynamics and tracer fields with
+      !!              unstructured open boundaries.
+      !!
+      !! ** Method  :   Read initialization arrays (mask, indices) to identify
+      !!              an unstructured open boundary
+      !!
+      !! ** Input   :  bdy_init.nc, input file for unstructured open boundaries
+      !!----------------------------------------------------------------------
+      NAMELIST/nambdy/ ln_bdy, nb_bdy, ln_coords_file, cn_coords_file,         &
+         &             ln_mask_file, cn_mask_file, cn_dyn2d, nn_dyn2d_dta,     &
+         &             cn_dyn3d, nn_dyn3d_dta, cn_tra, nn_tra_dta,             &
+         &             ln_tra_dmp, ln_dyn3d_dmp, rn_time_dmp, rn_time_dmp_out, &
+         &             cn_ice, nn_ice_dta,                                     &
+         &             ln_vol, nn_volctl, nn_rimwidth
+         !
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      !!----------------------------------------------------------------------
+
+      ! ------------------------
+      ! Read namelist parameters
+      ! ------------------------
+      REWIND( numnam_ref )              ! Namelist nambdy in reference namelist :Unstructured open boundaries
+      READ  ( numnam_ref, nambdy, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy in reference namelist' )
+      ! make sur that all elements of the namelist variables have a default definition from namelist_ref
+      ln_coords_file (2:jp_bdy) = ln_coords_file (1)
+      cn_coords_file (2:jp_bdy) = cn_coords_file (1)
+      cn_dyn2d       (2:jp_bdy) = cn_dyn2d       (1)
+      nn_dyn2d_dta   (2:jp_bdy) = nn_dyn2d_dta   (1)
+      cn_dyn3d       (2:jp_bdy) = cn_dyn3d       (1)
+      nn_dyn3d_dta   (2:jp_bdy) = nn_dyn3d_dta   (1)
+      cn_tra         (2:jp_bdy) = cn_tra         (1)
+      nn_tra_dta     (2:jp_bdy) = nn_tra_dta     (1)    
+      ln_tra_dmp     (2:jp_bdy) = ln_tra_dmp     (1)
+      ln_dyn3d_dmp   (2:jp_bdy) = ln_dyn3d_dmp   (1)
+      rn_time_dmp    (2:jp_bdy) = rn_time_dmp    (1)
+      rn_time_dmp_out(2:jp_bdy) = rn_time_dmp_out(1)
+      cn_ice         (2:jp_bdy) = cn_ice         (1)
+      nn_ice_dta     (2:jp_bdy) = nn_ice_dta     (1)
+      REWIND( numnam_cfg )              ! Namelist nambdy in configuration namelist :Unstructured open boundaries
+      READ  ( numnam_cfg, nambdy, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nambdy in configuration namelist' )
+      IF(lwm) WRITE ( numond, nambdy )
+
+      IF( .NOT. Agrif_Root() ) ln_bdy = .FALSE.   ! forced for Agrif children
+
+      IF( nb_bdy == 0 ) ln_bdy = .FALSE.
+      
+      ! -----------------------------------------
+      ! unstructured open boundaries use control
+      ! -----------------------------------------
+      IF ( ln_bdy ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'bdy_init : initialization of open boundaries'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~'
+         !
+         ! Open boundaries definition (arrays and masks)
+         CALL bdy_def
+         IF( ln_meshmask )   CALL bdy_meshwri()
+         !
+         ! Open boundaries initialisation of external data arrays
+         CALL bdy_dta_init
+         !
+         ! Open boundaries initialisation of tidal harmonic forcing
+         IF( ln_tide ) CALL bdytide_init
+         !
+      ELSE
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'bdy_init : open boundaries not used (ln_bdy = F)'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~'
+         !
+      ENDIF
+      !
+   END SUBROUTINE bdy_init
+
+
+   SUBROUTINE bdy_def
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_init  ***
+      !!         
+      !! ** Purpose :   Definition of unstructured open boundaries.
+      !!
+      !! ** Method  :   Read initialization arrays (mask, indices) to identify 
+      !!              an unstructured open boundary
+      !!
+      !! ** Input   :  bdy_init.nc, input file for unstructured open boundaries
+      !!----------------------------------------------------------------------      
+      INTEGER  ::   ib_bdy, ii, ij, igrd, ib, ir, iseg     ! dummy loop indices
+      INTEGER  ::   icount, icountr, icountr0, ibr_max     ! local integers
+      INTEGER  ::   ilen1                                  !   -       -
+      INTEGER  ::   iwe, ies, iso, ino, inum, id_dummy     !   -       -
+      INTEGER  ::   jpbdta                                 !   -       -
+      INTEGER  ::   ib_bdy1, ib_bdy2, ib1, ib2             !   -       -
+      INTEGER  ::   ii1, ii2, ii3, ij1, ij2, ij3           !   -       -
+      INTEGER  ::   iibe, ijbe, iibi, ijbi                 !   -       -
+      INTEGER  ::   flagu, flagv                           ! short cuts
+      INTEGER  ::   nbdyind, nbdybeg, nbdyend
+      INTEGER              , DIMENSION(4)             ::   kdimsz
+      INTEGER              , DIMENSION(jpbgrd,jp_bdy) ::   nblendta          ! Length of index arrays 
+      INTEGER,  ALLOCATABLE, DIMENSION(:,:,:)         ::   nbidta, nbjdta    ! Index arrays: i and j indices of bdy dta
+      INTEGER,  ALLOCATABLE, DIMENSION(:,:,:)         ::   nbrdta            ! Discrete distance from rim points
+      CHARACTER(LEN=1)     , DIMENSION(jpbgrd)        ::   cgrid
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     ::   zz_read                 ! work space for 2D global boundary data
+      REAL(wp), POINTER    , DIMENSION(:,:)     ::   zmask                   ! pointer to 2D mask fields
+      REAL(wp)             , DIMENSION(jpi,jpj) ::   zfmask   ! temporary fmask array excluding coastal boundary condition (shlat)
+      REAL(wp)             , DIMENSION(jpi,jpj) ::   ztmask, zumask, zvmask  ! temporary u/v mask array
+      !!----------------------------------------------------------------------
+      !
+      cgrid = (/'t','u','v'/)
+
+      ! -----------------------------------------
+      ! Check and write out namelist parameters
+      ! -----------------------------------------
+      IF( jperio /= 0 )   CALL ctl_stop( 'bdy_segs: Cyclic or symmetric,',   &
+         &                               ' and general open boundary condition are not compatible' )
+
+      IF(lwp) WRITE(numout,*) 'Number of open boundary sets : ', nb_bdy
+
+      DO ib_bdy = 1,nb_bdy
+
+         IF(lwp) THEN
+            WRITE(numout,*) ' ' 
+            WRITE(numout,*) '------ Open boundary data set ',ib_bdy,' ------' 
+            IF( ln_coords_file(ib_bdy) ) THEN
+               WRITE(numout,*) 'Boundary definition read from file '//TRIM(cn_coords_file(ib_bdy))
+            ELSE
+               WRITE(numout,*) 'Boundary defined in namelist.'
+            ENDIF
+            WRITE(numout,*)
+         ENDIF
+
+         ! barotropic bdy
+         !----------------
+         IF(lwp) THEN
+            WRITE(numout,*) 'Boundary conditions for barotropic solution:  '
+            SELECT CASE( cn_dyn2d(ib_bdy) )                  
+            CASE( 'none' )           ;   WRITE(numout,*) '      no open boundary condition'        
+            CASE( 'frs' )            ;   WRITE(numout,*) '      Flow Relaxation Scheme'
+            CASE( 'flather' )        ;   WRITE(numout,*) '      Flather radiation condition'
+            CASE( 'orlanski' )       ;   WRITE(numout,*) '      Orlanski (fully oblique) radiation condition with adaptive nudging'
+            CASE( 'orlanski_npo' )   ;   WRITE(numout,*) '      Orlanski (NPO) radiation condition with adaptive nudging'
+            CASE DEFAULT             ;   CALL ctl_stop( 'unrecognised value for cn_dyn2d' )
+            END SELECT
+         ENDIF
+
+         dta_bdy(ib_bdy)%lneed_ssh   = cn_dyn2d(ib_bdy) == 'flather'
+         dta_bdy(ib_bdy)%lneed_dyn2d = cn_dyn2d(ib_bdy) /= 'none'
+
+         IF( lwp .AND. dta_bdy(ib_bdy)%lneed_dyn2d ) THEN
+            SELECT CASE( nn_dyn2d_dta(ib_bdy) )                   ! 
+            CASE( 0 )      ;   WRITE(numout,*) '      initial state used for bdy data'        
+            CASE( 1 )      ;   WRITE(numout,*) '      boundary data taken from file'
+            CASE( 2 )      ;   WRITE(numout,*) '      tidal harmonic forcing taken from file'
+            CASE( 3 )      ;   WRITE(numout,*) '      boundary data AND tidal harmonic forcing taken from files'
+            CASE DEFAULT   ;   CALL ctl_stop( 'nn_dyn2d_dta must be between 0 and 3' )
+            END SELECT
+         ENDIF
+         IF ( dta_bdy(ib_bdy)%lneed_dyn2d .AND. nn_dyn2d_dta(ib_bdy) .GE. 2  .AND. .NOT.ln_tide ) THEN
+            CALL ctl_stop( 'You must activate with ln_tide to add tidal forcing at open boundaries' )
+         ENDIF
+         IF(lwp) WRITE(numout,*)
+
+         ! baroclinic bdy
+         !----------------
+         IF(lwp) THEN
+            WRITE(numout,*) 'Boundary conditions for baroclinic velocities:  '
+            SELECT CASE( cn_dyn3d(ib_bdy) )                  
+            CASE('none')           ;   WRITE(numout,*) '      no open boundary condition'        
+            CASE('frs')            ;   WRITE(numout,*) '      Flow Relaxation Scheme'
+            CASE('specified')      ;   WRITE(numout,*) '      Specified value'
+            CASE('neumann')        ;   WRITE(numout,*) '      Neumann conditions'
+            CASE('zerograd')       ;   WRITE(numout,*) '      Zero gradient for baroclinic velocities'
+            CASE('zero')           ;   WRITE(numout,*) '      Zero baroclinic velocities (runoff case)'
+            CASE('orlanski')       ;   WRITE(numout,*) '      Orlanski (fully oblique) radiation condition with adaptive nudging'
+            CASE('orlanski_npo')   ;   WRITE(numout,*) '      Orlanski (NPO) radiation condition with adaptive nudging'
+            CASE DEFAULT   ;   CALL ctl_stop( 'unrecognised value for cn_dyn3d' )
+            END SELECT
+         ENDIF
+
+         dta_bdy(ib_bdy)%lneed_dyn3d = cn_dyn3d(ib_bdy) == 'frs'      .OR. cn_dyn3d(ib_bdy) == 'specified'   &
+            &                     .OR. cn_dyn3d(ib_bdy) == 'orlanski' .OR. cn_dyn3d(ib_bdy) == 'orlanski_npo'
+
+         IF( lwp .AND. dta_bdy(ib_bdy)%lneed_dyn3d ) THEN
+            SELECT CASE( nn_dyn3d_dta(ib_bdy) )                   ! 
+            CASE( 0 )      ;   WRITE(numout,*) '      initial state used for bdy data'        
+            CASE( 1 )      ;   WRITE(numout,*) '      boundary data taken from file'
+            CASE DEFAULT   ;   CALL ctl_stop( 'nn_dyn3d_dta must be 0 or 1' )
+            END SELECT
+         END IF
+
+         IF ( ln_dyn3d_dmp(ib_bdy) ) THEN
+            IF ( cn_dyn3d(ib_bdy) == 'none' ) THEN
+               IF(lwp) WRITE(numout,*) 'No open boundary condition for baroclinic velocities: ln_dyn3d_dmp is set to .false.'
+               ln_dyn3d_dmp(ib_bdy) = .false.
+            ELSEIF ( cn_dyn3d(ib_bdy) == 'frs' ) THEN
+               CALL ctl_stop( 'Use FRS OR relaxation' )
+            ELSE
+               IF(lwp) WRITE(numout,*) '      + baroclinic velocities relaxation zone'
+               IF(lwp) WRITE(numout,*) '      Damping time scale: ',rn_time_dmp(ib_bdy),' days'
+               IF(rn_time_dmp(ib_bdy)<0) CALL ctl_stop( 'Time scale must be positive' )
+               dta_bdy(ib_bdy)%lneed_dyn3d = .TRUE.
+            ENDIF
+         ELSE
+            IF(lwp) WRITE(numout,*) '      NO relaxation on baroclinic velocities'
+         ENDIF
+         IF(lwp) WRITE(numout,*)
+
+         !    tra bdy
+         !----------------
+         IF(lwp) THEN
+            WRITE(numout,*) 'Boundary conditions for temperature and salinity:  '
+            SELECT CASE( cn_tra(ib_bdy) )                  
+            CASE('none')           ;   WRITE(numout,*) '      no open boundary condition'        
+            CASE('frs')            ;   WRITE(numout,*) '      Flow Relaxation Scheme'
+            CASE('specified')      ;   WRITE(numout,*) '      Specified value'
+            CASE('neumann')        ;   WRITE(numout,*) '      Neumann conditions'
+            CASE('runoff')         ;   WRITE(numout,*) '      Runoff conditions : Neumann for T and specified to 0.1 for salinity'
+            CASE('orlanski')       ;   WRITE(numout,*) '      Orlanski (fully oblique) radiation condition with adaptive nudging'
+            CASE('orlanski_npo')   ;   WRITE(numout,*) '      Orlanski (NPO) radiation condition with adaptive nudging'
+            CASE DEFAULT           ;   CALL ctl_stop( 'unrecognised value for cn_tra' )
+            END SELECT
+         ENDIF
+
+         dta_bdy(ib_bdy)%lneed_tra = cn_tra(ib_bdy) == 'frs'       .OR. cn_tra(ib_bdy) == 'specified'   &
+            &                   .OR. cn_tra(ib_bdy) == 'orlanski'  .OR. cn_tra(ib_bdy) == 'orlanski_npo' 
+
+         IF( lwp .AND. dta_bdy(ib_bdy)%lneed_tra ) THEN
+            SELECT CASE( nn_tra_dta(ib_bdy) )                   ! 
+            CASE( 0 )      ;   WRITE(numout,*) '      initial state used for bdy data'        
+            CASE( 1 )      ;   WRITE(numout,*) '      boundary data taken from file'
+            CASE DEFAULT   ;   CALL ctl_stop( 'nn_tra_dta must be 0 or 1' )
+            END SELECT
+         ENDIF
+
+         IF ( ln_tra_dmp(ib_bdy) ) THEN
+            IF ( cn_tra(ib_bdy) == 'none' ) THEN
+               IF(lwp) WRITE(numout,*) 'No open boundary condition for tracers: ln_tra_dmp is set to .false.'
+               ln_tra_dmp(ib_bdy) = .false.
+            ELSEIF ( cn_tra(ib_bdy) == 'frs' ) THEN
+               CALL ctl_stop( 'Use FRS OR relaxation' )
+            ELSE
+               IF(lwp) WRITE(numout,*) '      + T/S relaxation zone'
+               IF(lwp) WRITE(numout,*) '      Damping time scale: ',rn_time_dmp(ib_bdy),' days'
+               IF(lwp) WRITE(numout,*) '      Outflow damping time scale: ',rn_time_dmp_out(ib_bdy),' days'
+               IF(lwp.AND.rn_time_dmp(ib_bdy)<0) CALL ctl_stop( 'Time scale must be positive' )
+               dta_bdy(ib_bdy)%lneed_tra = .TRUE.
+            ENDIF
+         ELSE
+            IF(lwp) WRITE(numout,*) '      NO T/S relaxation'
+         ENDIF
+         IF(lwp) WRITE(numout,*)
+
+#if defined key_si3
+         IF(lwp) THEN
+            WRITE(numout,*) 'Boundary conditions for sea ice:  '
+            SELECT CASE( cn_ice(ib_bdy) )                  
+            CASE('none')   ;   WRITE(numout,*) '      no open boundary condition'        
+            CASE('frs')    ;   WRITE(numout,*) '      Flow Relaxation Scheme'
+            CASE DEFAULT   ;   CALL ctl_stop( 'unrecognised value for cn_ice' )
+            END SELECT
+         ENDIF
+
+         dta_bdy(ib_bdy)%lneed_ice = cn_ice(ib_bdy) /= 'none'
+
+         IF( lwp .AND. dta_bdy(ib_bdy)%lneed_ice ) THEN 
+            SELECT CASE( nn_ice_dta(ib_bdy) )                   ! 
+            CASE( 0 )      ;   WRITE(numout,*) '      initial state used for bdy data'        
+            CASE( 1 )      ;   WRITE(numout,*) '      boundary data taken from file'
+            CASE DEFAULT   ;   CALL ctl_stop( 'nn_ice_dta must be 0 or 1' )
+            END SELECT
+         ENDIF
+#else
+         dta_bdy(ib_bdy)%lneed_ice = .FALSE.
+#endif
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '      Width of relaxation zone = ', nn_rimwidth(ib_bdy)
+         IF(lwp) WRITE(numout,*)
+         !
+      END DO   ! nb_bdy
+
+      IF( lwp ) THEN
+         IF( ln_vol ) THEN                     ! check volume conservation (nn_volctl value)
+            WRITE(numout,*) 'Volume correction applied at open boundaries'
+            WRITE(numout,*)
+            SELECT CASE ( nn_volctl )
+            CASE( 1 )      ;   WRITE(numout,*) '      The total volume will be constant'
+            CASE( 0 )      ;   WRITE(numout,*) '      The total volume will vary according to the surface E-P flux'
+            CASE DEFAULT   ;   CALL ctl_stop( 'nn_volctl must be 0 or 1' )
+            END SELECT
+            WRITE(numout,*)
+            !
+            ! sanity check if used with tides        
+            IF( ln_tide ) THEN 
+               WRITE(numout,*) ' The total volume correction is not working with tides. '
+               WRITE(numout,*) ' Set ln_vol to .FALSE. '
+               WRITE(numout,*) ' or '
+               WRITE(numout,*) ' equilibriate your bdy input files '
+               CALL ctl_stop( 'The total volume correction is not working with tides.' )
+            END IF
+         ELSE
+            WRITE(numout,*) 'No volume correction applied at open boundaries'
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+
+      ! -------------------------------------------------
+      ! Initialise indices arrays for open boundaries
+      ! -------------------------------------------------
+
+      REWIND( numnam_cfg )     
+      nblendta(:,:) = 0
+      nbdysege = 0
+      nbdysegw = 0
+      nbdysegn = 0
+      nbdysegs = 0
+
+      ! Define all boundaries 
+      ! ---------------------
+      DO ib_bdy = 1, nb_bdy
+         !
+         IF( .NOT. ln_coords_file(ib_bdy) ) THEN     ! build bdy coordinates with segments defined in namelist
+
+            CALL bdy_read_seg( ib_bdy, nblendta(:,ib_bdy) )
+
+         ELSE                                        ! Read size of arrays in boundary coordinates file.
+            
+            CALL iom_open( cn_coords_file(ib_bdy), inum )
+            DO igrd = 1, jpbgrd
+               id_dummy = iom_varid( inum, 'nbi'//cgrid(igrd), kdimsz=kdimsz )  
+               nblendta(igrd,ib_bdy) = MAXVAL(kdimsz)
+            END DO
+            CALL iom_close( inum )
+         ENDIF
+         !
+      END DO ! ib_bdy
+
+      ! Now look for crossings in user (namelist) defined open boundary segments:
+      IF( nbdysege > 0 .OR. nbdysegw > 0 .OR. nbdysegn > 0 .OR. nbdysegs > 0)   CALL bdy_ctl_seg
+      
+      ! Allocate arrays
+      !---------------
+      jpbdta = MAXVAL(nblendta(1:jpbgrd,1:nb_bdy))
+      ALLOCATE( nbidta(jpbdta, jpbgrd, nb_bdy), nbjdta(jpbdta, jpbgrd, nb_bdy), nbrdta(jpbdta, jpbgrd, nb_bdy) )
+      nbrdta(:,:,:) = 0   ! initialize nbrdta as it may not be completely defined for each bdy
+      
+      ! Calculate global boundary index arrays or read in from file
+      !------------------------------------------------------------               
+      ! 1. Read global index arrays from boundary coordinates file.
+      DO ib_bdy = 1, nb_bdy
+         !
+         IF( ln_coords_file(ib_bdy) ) THEN
+            !
+            ALLOCATE( zz_read( MAXVAL(nblendta), 1 ) )          
+            CALL iom_open( cn_coords_file(ib_bdy), inum )
+            !
+            DO igrd = 1, jpbgrd
+               CALL iom_get( inum, jpdom_unknown, 'nbi'//cgrid(igrd), zz_read(1:nblendta(igrd,ib_bdy),:) )
+               DO ii = 1,nblendta(igrd,ib_bdy)
+                  nbidta(ii,igrd,ib_bdy) = NINT( zz_read(ii,1) )
+               END DO
+               CALL iom_get( inum, jpdom_unknown, 'nbj'//cgrid(igrd), zz_read(1:nblendta(igrd,ib_bdy),:) )
+               DO ii = 1,nblendta(igrd,ib_bdy)
+                  nbjdta(ii,igrd,ib_bdy) = NINT( zz_read(ii,1) )
+               END DO
+               CALL iom_get( inum, jpdom_unknown, 'nbr'//cgrid(igrd), zz_read(1:nblendta(igrd,ib_bdy),:) )
+               DO ii = 1,nblendta(igrd,ib_bdy)
+                  nbrdta(ii,igrd,ib_bdy) = NINT( zz_read(ii,1) )
+               END DO
+               !
+               ibr_max = MAXVAL( nbrdta(:,igrd,ib_bdy) )
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) ' Maximum rimwidth in file is ', ibr_max
+               IF(lwp) WRITE(numout,*) ' nn_rimwidth from namelist is ', nn_rimwidth(ib_bdy)
+               IF (ibr_max < nn_rimwidth(ib_bdy))   &
+                  CALL ctl_stop( 'nn_rimwidth is larger than maximum rimwidth in file',cn_coords_file(ib_bdy) )
+            END DO
+            !
+            CALL iom_close( inum )
+            DEALLOCATE( zz_read )
+            !
+         ENDIF
+         !
+      END DO
+
+      ! 2. Now fill indices corresponding to straight open boundary arrays:
+      CALL bdy_coords_seg( nbidta, nbjdta, nbrdta )
+
+      !  Deal with duplicated points
+      !-----------------------------
+      ! We assign negative indices to duplicated points (to remove them from bdy points to be updated)
+      ! if their distance to the bdy is greater than the other
+      ! If their distance are the same, just keep only one to avoid updating a point twice
+      DO igrd = 1, jpbgrd
+         DO ib_bdy1 = 1, nb_bdy
+            DO ib_bdy2 = 1, nb_bdy
+               IF (ib_bdy1/=ib_bdy2) THEN
+                  DO ib1 = 1, nblendta(igrd,ib_bdy1)
+                     DO ib2 = 1, nblendta(igrd,ib_bdy2)
+                        IF ((nbidta(ib1, igrd, ib_bdy1)==nbidta(ib2, igrd, ib_bdy2)).AND. &
+                           &   (nbjdta(ib1, igrd, ib_bdy1)==nbjdta(ib2, igrd, ib_bdy2))) THEN
+                           !                           IF ((lwp).AND.(igrd==1)) WRITE(numout,*) ' found coincident point ji, jj:', & 
+                           !                                                       &              nbidta(ib1, igrd, ib_bdy1),      & 
+                           !                                                       &              nbjdta(ib2, igrd, ib_bdy2)
+                           ! keep only points with the lowest distance to boundary:
+                           IF (nbrdta(ib1, igrd, ib_bdy1)<nbrdta(ib2, igrd, ib_bdy2)) THEN
+                              nbidta(ib2, igrd, ib_bdy2) =-ib_bdy2
+                              nbjdta(ib2, igrd, ib_bdy2) =-ib_bdy2
+                           ELSEIF (nbrdta(ib1, igrd, ib_bdy1)>nbrdta(ib2, igrd, ib_bdy2)) THEN
+                              nbidta(ib1, igrd, ib_bdy1) =-ib_bdy1
+                              nbjdta(ib1, igrd, ib_bdy1) =-ib_bdy1
+                              ! Arbitrary choice if distances are the same:
+                           ELSE
+                              nbidta(ib1, igrd, ib_bdy1) =-ib_bdy1
+                              nbjdta(ib1, igrd, ib_bdy1) =-ib_bdy1
+                           ENDIF
+                        END IF
+                     END DO
+                  END DO
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      ! Find lenght of boundaries and rim on local mpi domain
+      !------------------------------------------------------
+      !
+      iwe = mig(1)
+      ies = mig(jpi)
+      iso = mjg(1) 
+      ino = mjg(jpj) 
+      !
+      DO ib_bdy = 1, nb_bdy
+         DO igrd = 1, jpbgrd
+            icount   = 0   ! initialization of local bdy length
+            icountr  = 0   ! initialization of local rim 0 and rim 1 bdy length
+            icountr0 = 0   ! initialization of local rim 0 bdy length
+            idx_bdy(ib_bdy)%nblen(igrd)     = 0
+            idx_bdy(ib_bdy)%nblenrim(igrd)  = 0
+            idx_bdy(ib_bdy)%nblenrim0(igrd) = 0
+            DO ib = 1, nblendta(igrd,ib_bdy)
+               ! check that data is in correct order in file
+               IF( ib > 1 ) THEN
+                  IF( nbrdta(ib,igrd,ib_bdy) < nbrdta(ib-1,igrd,ib_bdy) ) THEN
+                     CALL ctl_stop('bdy_segs : ERROR : boundary data in file must be defined ', &
+                        &        ' in order of distance from edge nbr A utility for re-ordering ', &
+                        &        ' boundary coordinates and data files exists in the TOOLS/OBC directory')
+                  ENDIF
+               ENDIF
+               ! check if point is in local domain
+               IF(  nbidta(ib,igrd,ib_bdy) >= iwe .AND. nbidta(ib,igrd,ib_bdy) <= ies .AND.   &
+                  & nbjdta(ib,igrd,ib_bdy) >= iso .AND. nbjdta(ib,igrd,ib_bdy) <= ino      ) THEN
+                  !
+                  icount = icount + 1
+                  IF( nbrdta(ib,igrd,ib_bdy) == 1 .OR. nbrdta(ib,igrd,ib_bdy) == 0 )   icountr = icountr + 1
+                  IF( nbrdta(ib,igrd,ib_bdy) == 0 )   icountr0 = icountr0 + 1
+               ENDIF
+            END DO
+            idx_bdy(ib_bdy)%nblen    (igrd) = icount   !: length of boundary data on each proc
+            idx_bdy(ib_bdy)%nblenrim (igrd) = icountr  !: length of rim 0 and rim 1 boundary data on each proc   
+            idx_bdy(ib_bdy)%nblenrim0(igrd) = icountr0 !: length of rim 0 boundary data on each proc     
+         END DO   ! igrd
+
+         ! Allocate index arrays for this boundary set
+         !--------------------------------------------
+         ilen1 = MAXVAL( idx_bdy(ib_bdy)%nblen(:) )
+         ALLOCATE( idx_bdy(ib_bdy)%nbi   (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbj   (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbr   (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbd   (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbdout(ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%ntreat(ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbmap (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%nbw   (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%flagu (ilen1,jpbgrd) ,   &
+            &      idx_bdy(ib_bdy)%flagv (ilen1,jpbgrd) )
+
+         ! Dispatch mapping indices and discrete distances on each processor
+         ! -----------------------------------------------------------------
+         DO igrd = 1, jpbgrd
+            icount  = 0
+            ! Outer loop on rimwidth to ensure outermost points come first in the local arrays.
+            DO ir = 0, nn_rimwidth(ib_bdy)
+               DO ib = 1, nblendta(igrd,ib_bdy)
+                  ! check if point is in local domain and equals ir
+                  IF(  nbidta(ib,igrd,ib_bdy) >= iwe .AND. nbidta(ib,igrd,ib_bdy) <= ies .AND.   &
+                     & nbjdta(ib,igrd,ib_bdy) >= iso .AND. nbjdta(ib,igrd,ib_bdy) <= ino .AND.   &
+                     & nbrdta(ib,igrd,ib_bdy) == ir  ) THEN
+                     !
+                     icount = icount  + 1
+                     idx_bdy(ib_bdy)%nbi(icount,igrd)   = nbidta(ib,igrd,ib_bdy)- mig(1)+1   ! global to local indexes
+                     idx_bdy(ib_bdy)%nbj(icount,igrd)   = nbjdta(ib,igrd,ib_bdy)- mjg(1)+1   ! global to local indexes
+                     idx_bdy(ib_bdy)%nbr(icount,igrd)   = nbrdta(ib,igrd,ib_bdy)
+                     idx_bdy(ib_bdy)%nbmap(icount,igrd) = ib
+                  ENDIF
+               END DO
+            END DO
+         END DO   ! igrd
+
+      END DO   ! ib_bdy
+
+      ! Initialize array indicating communications in bdy
+      ! -------------------------------------------------
+      ALLOCATE( lsend_bdy(nb_bdy,jpbgrd,4,0:1), lrecv_bdy(nb_bdy,jpbgrd,4,0:1) )
+      lsend_bdy(:,:,:,:) = .false.
+      lrecv_bdy(:,:,:,:) = .false. 
+
+      DO ib_bdy = 1, nb_bdy
+         DO igrd = 1, jpbgrd
+            DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)   ! only the rim triggers communications, see bdy routines
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               IF( ib .LE. idx_bdy(ib_bdy)%nblenrim0(igrd) ) THEN   ;   ir = 0
+               ELSE                                                 ;   ir = 1
+               END IF
+               !
+               ! check if point has to be sent     to   a neighbour
+               ! W neighbour and on the inner left  side
+               IF( ii == 2     .and. (nbondi == 0 .or. nbondi ==  1) )   lsend_bdy(ib_bdy,igrd,1,ir) = .true.
+               ! E neighbour and on the inner right side
+               IF( ii == jpi-1 .and. (nbondi == 0 .or. nbondi == -1) )   lsend_bdy(ib_bdy,igrd,2,ir) = .true.
+               ! S neighbour and on the inner down side
+               IF( ij == 2     .and. (nbondj == 0 .or. nbondj ==  1) )   lsend_bdy(ib_bdy,igrd,3,ir) = .true.
+               ! N neighbour and on the inner up   side
+               IF( ij == jpj-1 .and. (nbondj == 0 .or. nbondj == -1) )   lsend_bdy(ib_bdy,igrd,4,ir) = .true.
+               !
+               ! check if point has to be received from a neighbour
+               ! W neighbour and on the outter left  side
+               IF( ii == 1     .and. (nbondi == 0 .or. nbondi ==  1) )   lrecv_bdy(ib_bdy,igrd,1,ir) = .true.
+               ! E neighbour and on the outter right side
+               IF( ii == jpi   .and. (nbondi == 0 .or. nbondi == -1) )   lrecv_bdy(ib_bdy,igrd,2,ir) = .true.
+               ! S neighbour and on the outter down side
+               IF( ij == 1     .and. (nbondj == 0 .or. nbondj ==  1) )   lrecv_bdy(ib_bdy,igrd,3,ir) = .true.
+               ! N neighbour and on the outter up   side
+               IF( ij == jpj   .and. (nbondj == 0 .or. nbondj == -1) )   lrecv_bdy(ib_bdy,igrd,4,ir) = .true.
+               !
+            END DO
+         END DO  ! igrd
+
+         ! Compute rim weights for FRS scheme
+         ! ----------------------------------
+         DO igrd = 1, jpbgrd
+            DO ib = 1, idx_bdy(ib_bdy)%nblen(igrd)
+               ir = MAX( 1, idx_bdy(ib_bdy)%nbr(ib,igrd) )   ! both rim 0 and rim 1 have the same weights
+               idx_bdy(ib_bdy)%nbw(ib,igrd) = 1.- TANH( REAL( ir - 1 ) *0.5 )      ! tanh formulation
+               !               idx_bdy(ib_bdy)%nbw(ib,igrd) = (REAL(nn_rimwidth(ib_bdy)+1-ir)/REAL(nn_rimwidth(ib_bdy)))**2.  ! quadratic
+               !               idx_bdy(ib_bdy)%nbw(ib,igrd) =  REAL(nn_rimwidth(ib_bdy)+1-ir)/REAL(nn_rimwidth(ib_bdy))       ! linear
+            END DO
+         END DO
+
+         ! Compute damping coefficients
+         ! ----------------------------
+         DO igrd = 1, jpbgrd
+            DO ib = 1, idx_bdy(ib_bdy)%nblen(igrd)
+               ir = MAX( 1, idx_bdy(ib_bdy)%nbr(ib,igrd) )   ! both rim 0 and rim 1 have the same damping coefficients
+               idx_bdy(ib_bdy)%nbd(ib,igrd) = 1. / ( rn_time_dmp(ib_bdy) * rday ) & 
+                  & *(REAL(nn_rimwidth(ib_bdy)+1-ir)/REAL(nn_rimwidth(ib_bdy)))**2.   ! quadratic
+               idx_bdy(ib_bdy)%nbdout(ib,igrd) = 1. / ( rn_time_dmp_out(ib_bdy) * rday ) & 
+                  & *(REAL(nn_rimwidth(ib_bdy)+1-ir)/REAL(nn_rimwidth(ib_bdy)))**2.   ! quadratic
+            END DO
+         END DO
+
+      END DO ! ib_bdy
+
+      ! ------------------------------------------------------
+      ! Initialise masks and find normal/tangential directions
+      ! ------------------------------------------------------
+
+      ! ------------------------------------------
+      ! handle rim0, do as if rim 1 was free ocean
+      ! ------------------------------------------
+
+      ztmask(:,:) = tmask(:,:,1)   ;   zumask(:,:) = umask(:,:,1)   ;   zvmask(:,:) = vmask(:,:,1)
+      ! For the flagu/flagv calculation below we require a version of fmask without
+      ! the land boundary condition (shlat) included:
+      DO ij = 1, jpjm1
+         DO ii = 1, jpim1
+            zfmask(ii,ij) =  ztmask(ii,ij  ) * ztmask(ii+1,ij  )   &
+               &           * ztmask(ii,ij+1) * ztmask(ii+1,ij+1)
+         END DO
+      END DO
+      CALL lbc_lnk( 'bdyini', zfmask, 'F', 1. )
+
+      ! Read global 2D mask at T-points: bdytmask
+      ! -----------------------------------------
+      ! bdytmask = 1  on the computational domain AND on open boundaries
+      !          = 0  elsewhere   
+
+      bdytmask(:,:) = ssmask(:,:)
+
+      ! Derive mask on U and V grid from mask on T grid
+      DO ij = 1, jpjm1
+         DO ii = 1, jpim1
+            bdyumask(ii,ij) = bdytmask(ii,ij) * bdytmask(ii+1,ij  )
+            bdyvmask(ii,ij) = bdytmask(ii,ij) * bdytmask(ii  ,ij+1)  
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'bdyini', bdyumask, 'U', 1., bdyvmask, 'V', 1. )   ! Lateral boundary cond.
+
+      ! bdy masks are now set to zero on rim 0 points:
+      DO ib_bdy = 1, nb_bdy
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(1)   ! extent of rim 0
+            bdytmask(idx_bdy(ib_bdy)%nbi(ib,1), idx_bdy(ib_bdy)%nbj(ib,1)) = 0._wp
+         END DO
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(2)   ! extent of rim 0
+            bdyumask(idx_bdy(ib_bdy)%nbi(ib,2), idx_bdy(ib_bdy)%nbj(ib,2)) = 0._wp
+         END DO
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(3)   ! extent of rim 0
+            bdyvmask(idx_bdy(ib_bdy)%nbi(ib,3), idx_bdy(ib_bdy)%nbj(ib,3)) = 0._wp
+         END DO
+      END DO
+
+      CALL bdy_rim_treat( zumask, zvmask, zfmask, .true. )   ! compute flagu, flagv, ntreat on rim 0
+
+      ! ------------------------------------
+      ! handle rim1, do as if rim 0 was land
+      ! ------------------------------------
+      
+      ! z[tuv]mask are now set to zero on rim 0 points:
+      DO ib_bdy = 1, nb_bdy
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(1)   ! extent of rim 0
+            ztmask(idx_bdy(ib_bdy)%nbi(ib,1), idx_bdy(ib_bdy)%nbj(ib,1)) = 0._wp
+         END DO
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(2)   ! extent of rim 0
+            zumask(idx_bdy(ib_bdy)%nbi(ib,2), idx_bdy(ib_bdy)%nbj(ib,2)) = 0._wp
+         END DO
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim0(3)   ! extent of rim 0
+            zvmask(idx_bdy(ib_bdy)%nbi(ib,3), idx_bdy(ib_bdy)%nbj(ib,3)) = 0._wp
+         END DO
+      END DO
+
+      ! Recompute zfmask
+      DO ij = 1, jpjm1
+         DO ii = 1, jpim1
+            zfmask(ii,ij) =  ztmask(ii,ij  ) * ztmask(ii+1,ij  )   &
+               &           * ztmask(ii,ij+1) * ztmask(ii+1,ij+1)
+         END DO
+      END DO
+      CALL lbc_lnk( 'bdyini', zfmask, 'F', 1. )
+
+      ! bdy masks are now set to zero on rim1 points:
+      DO ib_bdy = 1, nb_bdy
+         DO ib = idx_bdy(ib_bdy)%nblenrim0(1) + 1,  idx_bdy(ib_bdy)%nblenrim(1)   ! extent of rim 1
+            bdytmask(idx_bdy(ib_bdy)%nbi(ib,1), idx_bdy(ib_bdy)%nbj(ib,1)) = 0._wp
+         END DO
+         DO ib = idx_bdy(ib_bdy)%nblenrim0(2) + 1,  idx_bdy(ib_bdy)%nblenrim(2)   ! extent of rim 1
+            bdyumask(idx_bdy(ib_bdy)%nbi(ib,2), idx_bdy(ib_bdy)%nbj(ib,2)) = 0._wp
+         END DO
+         DO ib = idx_bdy(ib_bdy)%nblenrim0(3) + 1,  idx_bdy(ib_bdy)%nblenrim(3)   ! extent of rim 1
+            bdyvmask(idx_bdy(ib_bdy)%nbi(ib,3), idx_bdy(ib_bdy)%nbj(ib,3)) = 0._wp
+         END DO
+      END DO
+
+      CALL bdy_rim_treat( zumask, zvmask, zfmask, .false. )   ! compute flagu, flagv, ntreat on rim 1
+      !
+      ! Check which boundaries might need communication
+      ALLOCATE( lsend_bdyint(nb_bdy,jpbgrd,4,0:1), lrecv_bdyint(nb_bdy,jpbgrd,4,0:1) )
+      lsend_bdyint(:,:,:,:) = .false.
+      lrecv_bdyint(:,:,:,:) = .false. 
+      ALLOCATE( lsend_bdyext(nb_bdy,jpbgrd,4,0:1), lrecv_bdyext(nb_bdy,jpbgrd,4,0:1) )
+      lsend_bdyext(:,:,:,:) = .false.
+      lrecv_bdyext(:,:,:,:) = .false.
+      !
+      DO igrd = 1, jpbgrd
+         DO ib_bdy = 1, nb_bdy
+            DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)
+               IF( idx_bdy(ib_bdy)%ntreat(ib,igrd) == -1 ) CYCLE
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               ir = idx_bdy(ib_bdy)%nbr(ib,igrd)
+               flagu = NINT(idx_bdy(ib_bdy)%flagu(ib,igrd))
+               flagv = NINT(idx_bdy(ib_bdy)%flagv(ib,igrd))
+               iibe = ii - flagu   ! neighbouring point towards the exterior of the computational domain
+               ijbe = ij - flagv
+               iibi = ii + flagu   ! neighbouring point towards the interior of the computational domain
+               ijbi = ij + flagv
+               CALL find_neib( ii, ij, idx_bdy(ib_bdy)%ntreat(ib,igrd), ii1, ij1, ii2, ij2, ii3, ij3 )   ! free ocean neighbours
+               !
+               ! search neighbour in the  west/east  direction
+               ! Rim is on the halo and computed ocean is towards exterior of mpi domain  
+               !      <--    (o exterior)     -->  
+               ! (1)  o|x         OR    (2)   x|o
+               !       |___                 ___| 
+               IF( iibi == 0     .OR. ii1 == 0     .OR. ii2 == 0     .OR. ii3 == 0     )   lrecv_bdyint(ib_bdy,igrd,1,ir) = .true.
+               IF( iibi == jpi+1 .OR. ii1 == jpi+1 .OR. ii2 == jpi+1 .OR. ii3 == jpi+1 )   lrecv_bdyint(ib_bdy,igrd,2,ir) = .true.  
+               IF( iibe == 0                                                           )   lrecv_bdyext(ib_bdy,igrd,1,ir) = .true.
+               IF( iibe == jpi+1                                                       )   lrecv_bdyext(ib_bdy,igrd,2,ir) = .true.  
+               ! Check if neighbour has its rim parallel to its mpi subdomain border and located next to its halo
+               ! :¨¨¨¨¨|¨¨-->    |                                             |    <--¨¨|¨¨¨¨¨: 
+               ! :     |  x:o    |    neighbour limited by ... would need o    |    o:x  |     :
+               ! :.....|_._:_____|   (1) W neighbour         E neighbour (2)   |_____:_._|.....:
+               IF( ii == 2     .AND. ( nbondi ==  1 .OR. nbondi == 0 ) .AND. &
+                  & ( iibi == 3     .OR. ii1 == 3     .OR. ii2 == 3     .OR. ii3 == 3    ) )   lsend_bdyint(ib_bdy,igrd,1,ir)=.true.
+               IF( ii == jpi-1 .AND. ( nbondi == -1 .OR. nbondi == 0 ) .AND. &
+                  & ( iibi == jpi-2 .OR. ii1 == jpi-2 .OR. ii2 == jpi-2 .OR. ii3 == jpi-2) )   lsend_bdyint(ib_bdy,igrd,2,ir)=.true.
+               IF( ii == 2     .AND. ( nbondi ==  1 .OR. nbondi == 0 ) .AND. iibe == 3     )   lsend_bdyext(ib_bdy,igrd,1,ir)=.true.
+               IF( ii == jpi-1 .AND. ( nbondi == -1 .OR. nbondi == 0 ) .AND. iibe == jpi-2 )   lsend_bdyext(ib_bdy,igrd,2,ir)=.true.
+               !
+               ! search neighbour in the north/south direction   
+               ! Rim is on the halo and computed ocean is towards exterior of mpi domain
+               !(3)   |       |         ^   ___o___     
+               !  |   |___x___|   OR    |  |   x   |
+               !  v       o           (4)  |       |
+               IF( ijbi == 0     .OR. ij1 == 0     .OR. ij2 == 0     .OR. ij3 == 0     )   lrecv_bdyint(ib_bdy,igrd,3,ir) = .true.
+               IF( ijbi == jpj+1 .OR. ij1 == jpj+1 .OR. ij2 == jpj+1 .OR. ij3 == jpj+1 )   lrecv_bdyint(ib_bdy,igrd,4,ir) = .true.
+               IF( ijbe == 0                                                           )   lrecv_bdyext(ib_bdy,igrd,3,ir) = .true.
+               IF( ijbe == jpj+1                                                       )   lrecv_bdyext(ib_bdy,igrd,4,ir) = .true.
+               ! Check if neighbour has its rim parallel to its mpi subdomain     _________  border and next to its halo
+               !   ^  |    o    |                                                :         : 
+               !   |  |¨¨¨¨x¨¨¨¨|   neighbour limited by ... would need o     |  |....x....|
+               !      :_________:  (3) S neighbour          N neighbour (4)   v  |    o    |   
+               IF( ij == 2     .AND. ( nbondj ==  1 .OR. nbondj == 0 ) .AND. &
+                  & ( ijbi == 3     .OR. ij1 == 3     .OR. ij2 == 3     .OR. ij3 == 3    ) )   lsend_bdyint(ib_bdy,igrd,3,ir)=.true.
+               IF( ij == jpj-1 .AND. ( nbondj == -1 .OR. nbondj == 0 ) .AND. &
+                  & ( ijbi == jpj-2 .OR. ij1 == jpj-2 .OR. ij2 == jpj-2 .OR. ij3 == jpj-2) )   lsend_bdyint(ib_bdy,igrd,4,ir)=.true.
+               IF( ij == 2     .AND. ( nbondj ==  1 .OR. nbondj == 0 ) .AND. ijbe == 3     )   lsend_bdyext(ib_bdy,igrd,3,ir)=.true.
+               IF( ij == jpj-1 .AND. ( nbondj == -1 .OR. nbondj == 0 ) .AND. ijbe == jpj-2 )   lsend_bdyext(ib_bdy,igrd,4,ir)=.true.
+            END DO
+         END DO
+      END DO
+
+      DO ib_bdy = 1,nb_bdy
+         IF(  cn_dyn2d(ib_bdy) == 'orlanski' .OR. cn_dyn2d(ib_bdy) == 'orlanski_npo' .OR. &
+            & cn_dyn3d(ib_bdy) == 'orlanski' .OR. cn_dyn3d(ib_bdy) == 'orlanski_npo' .OR. &
+            & cn_tra(ib_bdy)   == 'orlanski' .OR. cn_tra(ib_bdy)   == 'orlanski_npo'      ) THEN
+            DO igrd = 1, jpbgrd
+               DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)
+                  ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+                  ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+                  IF(  mig(ii) > 2 .AND. mig(ii) < jpiglo-2 .AND. mjg(ij) > 2 .AND. mjg(ij) < jpjglo-2  ) THEN
+                     WRITE(ctmp1,*) ' Orlanski is not safe when the open boundaries are on the interior of the computational domain'
+                     CALL ctl_stop( ctmp1 )
+                  END IF
+               END DO
+            END DO
+         END IF
+      END DO
+      !
+      DEALLOCATE( nbidta, nbjdta, nbrdta )
+      !
+   END SUBROUTINE bdy_def
+
+
+   SUBROUTINE bdy_rim_treat( pumask, pvmask, pfmask, lrim0 )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_rim_treat  ***
+      !!
+      !! ** Purpose :   Initialize structures ( flagu, flagv, ntreat ) indicating how rim points
+      !!                  are to be handled in the boundary condition treatment
+      !!
+      !! ** Method  :   - to handle rim 0 zmasks must indicate ocean points      (set at one on rim 0 and rim 1 and interior)
+      !!                            and bdymasks must be set at 0 on rim 0       (set at one on rim 1 and interior)
+      !!                    (as if rim 1 was free ocean)
+      !!                - to handle rim 1 zmasks must be set at 0 on rim 0       (set at one on rim 1 and interior)
+      !!                            and bdymasks must indicate free ocean points (set at one on interior)
+      !!                    (as if rim 0 was land)
+      !!                - we can then check in which direction the interior of the computational domain is with the difference
+      !!                         mask array values on both sides to compute flagu and flagv
+      !!                - and look at the ocean neighbours to compute ntreat
+      !!----------------------------------------------------------------------
+      REAL(wp), TARGET, DIMENSION(jpi,jpj), INTENT (in   ) :: pfmask   ! temporary fmask excluding coastal boundary condition (shlat)
+      REAL(wp), TARGET, DIMENSION(jpi,jpj), INTENT (in   ) :: pumask, pvmask   ! temporary t/u/v mask array
+      LOGICAL                             , INTENT (in   ) :: lrim0    ! .true. -> rim 0   .false. -> rim 1
+      INTEGER  ::   ib_bdy, ii, ij, igrd, ib, icount       ! dummy loop indices
+      INTEGER  ::   i_offset, j_offset, inn                ! local integer
+      INTEGER  ::   ibeg, iend                             ! local integer
+      LOGICAL  ::   llnon, llson, llean, llwen             ! local logicals indicating the presence of a ocean neighbour
+      REAL(wp), POINTER, DIMENSION(:,:)       ::   zmask   ! pointer to 2D mask fields
+      REAL(wp) ::   zefl, zwfl, znfl, zsfl                 ! local scalars
+      CHARACTER(LEN=1), DIMENSION(jpbgrd)     ::   cgrid
+      REAL(wp)        , DIMENSION(jpi,jpj)    ::   ztmp
+      !!----------------------------------------------------------------------
+
+      cgrid = (/'t','u','v'/)
+
+      DO ib_bdy = 1, nb_bdy       ! Indices and directions of rim velocity components
+
+         ! Calculate relationship of U direction to the local orientation of the boundary
+         ! flagu = -1 : u component is normal to the dynamical boundary and its direction is outward
+         ! flagu =  0 : u is tangential
+         ! flagu =  1 : u is normal to the boundary and is direction is inward
+         DO igrd = 1, jpbgrd 
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   zmask => pumask     ;   i_offset = 0
+               CASE( 2 )   ;   zmask => bdytmask   ;   i_offset = 1
+               CASE( 3 )   ;   zmask => pfmask     ;   i_offset = 0
+            END SELECT 
+            icount = 0
+            ztmp(:,:) = -999._wp
+            IF( lrim0 ) THEN   ! extent of rim 0
+               ibeg = 1                                     ;   iend = idx_bdy(ib_bdy)%nblenrim0(igrd)
+            ELSE               ! extent of rim 1
+               ibeg = idx_bdy(ib_bdy)%nblenrim0(igrd) + 1   ;   iend = idx_bdy(ib_bdy)%nblenrim(igrd)
+            END IF
+            DO ib = ibeg, iend 
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE
+               zwfl = zmask(ii+i_offset-1,ij)
+               zefl = zmask(ii+i_offset  ,ij)
+               ! This error check only works if you are using the bdyXmask arrays
+               IF( i_offset == 1 .and. zefl + zwfl == 2. ) THEN
+                  icount = icount + 1
+                  IF(lwp) WRITE(numout,*) 'Problem with igrd = ',igrd,' at (global) nbi, nbj : ',mig(ii),mjg(ij)
+               ELSE
+                  ztmp(ii,ij) = -zwfl + zefl
+               ENDIF
+            END DO
+            IF( icount /= 0 ) THEN
+               WRITE(ctmp1,*) 'Some ',cgrid(igrd),' grid points,',   &
+                  ' are not boundary points (flagu calculation). Check nbi, nbj, indices for boundary set ',ib_bdy
+               CALL ctl_stop( ctmp1 )
+            ENDIF 
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'T', 1. ) 
+               CASE( 2 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'U', 1. ) 
+               CASE( 3 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'V', 1. ) 
+            END SELECT 
+            DO ib = ibeg, iend
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               idx_bdy(ib_bdy)%flagu(ib,igrd) = ztmp(ii,ij)
+            END DO
+         END DO
+
+         ! Calculate relationship of V direction to the local orientation of the boundary
+         ! flagv = -1 : v component is normal to the dynamical boundary but its direction is outward
+         ! flagv =  0 : v is tangential
+         ! flagv =  1 : v is normal to the boundary and is direction is inward
+         DO igrd = 1, jpbgrd 
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   zmask => pvmask     ;   j_offset = 0
+               CASE( 2 )   ;   zmask => pfmask     ;   j_offset = 0
+               CASE( 3 )   ;   zmask => bdytmask   ;   j_offset = 1
+            END SELECT 
+            icount = 0
+            ztmp(:,:) = -999._wp
+            IF( lrim0 ) THEN   ! extent of rim 0
+               ibeg = 1                                     ;   iend = idx_bdy(ib_bdy)%nblenrim0(igrd)
+            ELSE               ! extent of rim 1
+               ibeg = idx_bdy(ib_bdy)%nblenrim0(igrd) + 1   ;   iend = idx_bdy(ib_bdy)%nblenrim(igrd)
+            END IF
+            DO ib = ibeg, iend
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE
+               zsfl = zmask(ii,ij+j_offset-1)
+               znfl = zmask(ii,ij+j_offset  )
+               ! This error check only works if you are using the bdyXmask arrays
+               IF( j_offset == 1 .and. znfl + zsfl == 2. ) THEN
+                  IF(lwp) WRITE(numout,*) 'Problem with igrd = ',igrd,' at (global) nbi, nbj : ',mig(ii),mjg(ij)
+                  icount = icount + 1
+               ELSE
+                  ztmp(ii,ij) = -zsfl + znfl
+               END IF
+            END DO
+            IF( icount /= 0 ) THEN
+               WRITE(ctmp1,*) 'Some ',cgrid(igrd),' grid points,',   &
+                  ' are not boundary points (flagv calculation). Check nbi, nbj, indices for boundary set ',ib_bdy
+               CALL ctl_stop( ctmp1 )
+            ENDIF
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'T', 1. ) 
+               CASE( 2 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'U', 1. ) 
+               CASE( 3 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'V', 1. ) 
+            END SELECT 
+            DO ib = ibeg, iend
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               idx_bdy(ib_bdy)%flagv(ib,igrd) = ztmp(ii,ij)
+            END DO
+         END DO
+         !
+      END DO ! ib_bdy
+      
+      DO ib_bdy = 1, nb_bdy
+         DO igrd = 1, jpbgrd
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   zmask => bdytmask 
+               CASE( 2 )   ;   zmask => bdyumask 
+               CASE( 3 )   ;   zmask => bdyvmask 
+            END SELECT
+            ztmp(:,:) = -999._wp
+            IF( lrim0 ) THEN   ! extent of rim 0
+               ibeg = 1                                     ;   iend = idx_bdy(ib_bdy)%nblenrim0(igrd)
+            ELSE               ! extent of rim 1
+               ibeg = idx_bdy(ib_bdy)%nblenrim0(igrd) + 1   ;   iend = idx_bdy(ib_bdy)%nblenrim(igrd)
+            END IF
+            DO ib = ibeg, iend
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )   CYCLE
+               llnon = zmask(ii  ,ij+1) == 1.  
+               llson = zmask(ii  ,ij-1) == 1. 
+               llean = zmask(ii+1,ij  ) == 1. 
+               llwen = zmask(ii-1,ij  ) == 1. 
+               inn  = COUNT( (/ llnon, llson, llean, llwen /) )
+               IF( inn == 0 ) THEN   ! no neighbours -> interior of a corner  or  cluster of rim points
+                  !               !              !     _____     !     _____    !    __     __
+                  !  1 |   o      !  2  o   |    !  3 | x        !  4     x |   !      |   |   -> error
+                  !    |_x_ _     !    _ _x_|    !    |   o      !      o   |   !      |x_x|
+                  IF(     zmask(ii+1,ij+1) == 1. ) THEN   ;   ztmp(ii,ij) = 1.
+                  ELSEIF( zmask(ii-1,ij+1) == 1. ) THEN   ;   ztmp(ii,ij) = 2.
+                  ELSEIF( zmask(ii+1,ij-1) == 1. ) THEN   ;   ztmp(ii,ij) = 3.
+                  ELSEIF( zmask(ii-1,ij-1) == 1. ) THEN   ;   ztmp(ii,ij) = 4.
+                  ELSE                                    ;   ztmp(ii,ij) = -1.
+                     WRITE(ctmp1,*) 'Problem with  ',cgrid(igrd) ,' grid point', ii, ij,   &
+                       ' on boundary set ', ib_bdy, ' has no free ocean neighbour'
+                     IF( lrim0 ) THEN
+                        WRITE(ctmp2,*) ' There seems to be a cluster of rim 0 points.'
+                     ELSE
+                        WRITE(ctmp2,*) ' There seems to be a cluster of rim 1 points.'
+                     END IF
+                     CALL ctl_warn( ctmp1, ctmp2 )
+                  END IF
+               END IF
+               IF( inn == 1 ) THEN   ! middle of linear bdy  or incomplete corner  ! ___ o
+                  !    |         !         |   !      o     !    ______            !    |x___
+                  ! 5  | x o     ! 6   o x |   ! 7  __x__   ! 8    x
+                  !    |         !         |   !            !      o
+                  IF( llean )   ztmp(ii,ij) = 5.
+                  IF( llwen )   ztmp(ii,ij) = 6.
+                  IF( llnon )   ztmp(ii,ij) = 7.
+                  IF( llson )   ztmp(ii,ij) = 8.
+               END IF
+               IF( inn == 2 ) THEN   ! exterior of a corner
+                  !        o      !        o      !    _____|       !       |_____  
+                  !  9 ____x o    ! 10   o x___   ! 11     x o      ! 12   o x      
+                  !         |     !       |       !        o        !        o 
+                  IF( llnon .AND. llean )   ztmp(ii,ij) =  9.
+                  IF( llnon .AND. llwen )   ztmp(ii,ij) = 10.
+                  IF( llson .AND. llean )   ztmp(ii,ij) = 11.
+                  IF( llson .AND. llwen )   ztmp(ii,ij) = 12.
+               END IF
+               IF( inn == 3 ) THEN   ! 3 neighbours     __   __
+                  !    |_  o      !        o  _|  !       |_|     !       o         
+                  ! 13  _| x o    ! 14   o x |_   ! 15   o x o    ! 16  o x o       
+                  !    |   o      !        o   |  !        o      !    __|¨|__    
+                  IF( llnon .AND. llean .AND. llson )   ztmp(ii,ij) = 13.
+                  IF( llnon .AND. llwen .AND. llson )   ztmp(ii,ij) = 14.
+                  IF( llwen .AND. llson .AND. llean )   ztmp(ii,ij) = 15.
+                  IF( llwen .AND. llnon .AND. llean )   ztmp(ii,ij) = 16.
+               END IF
+               IF( inn == 4 ) THEN
+                  WRITE(ctmp1,*)  'Problem with  ',cgrid(igrd) ,' grid point', ii, ij,   &
+                       ' on boundary set ', ib_bdy, ' have 4 neighbours'
+                  CALL ctl_stop( ctmp1 )
+               END IF
+            END DO
+            SELECT CASE( igrd )
+               CASE( 1 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'T', 1. ) 
+               CASE( 2 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'U', 1. ) 
+               CASE( 3 )   ;   CALL lbc_lnk( 'bdyini', ztmp, 'V', 1. ) 
+            END SELECT 
+            DO ib = ibeg, iend
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               idx_bdy(ib_bdy)%ntreat(ib,igrd) = NINT(ztmp(ii,ij))
+            END DO
+         END DO
+      END DO
+
+    END SUBROUTINE bdy_rim_treat
+
+   
+    SUBROUTINE find_neib( ii, ij, itreat, ii1, ij1, ii2, ij2, ii3, ij3 )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE find_neib  ***
+      !!
+      !! ** Purpose :   get ii1, ij1, ii2, ij2, ii3, ij3, the indices of
+      !!               the free ocean neighbours of (ii,ij) for bdy treatment
+      !!
+      !! ** Method  :  use itreat input to select a case
+      !!               N.B. ntreat is defined for all bdy points in routine bdy_rim_treat
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   )      ::   ii, ij, itreat
+      INTEGER, INTENT(  out)      ::   ii1, ij1, ii2, ij2, ii3, ij3
+      !!----------------------------------------------------------------------
+      SELECT CASE( itreat )   ! points that will be used by bdy routines, -1 will be discarded
+         !               !               !     _____     !     _____     
+         !  1 |   o      !  2  o   |     !  3 | x        !  4     x |    
+         !    |_x_ _     !    _ _x_|     !    |   o      !      o   |
+      CASE( 1 )    ;   ii1 = ii+1   ;   ij1 = ij+1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 2 )    ;   ii1 = ii-1   ;   ij1 = ij+1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 3 )    ;   ii1 = ii+1   ;   ij1 = ij-1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 4 )    ;   ii1 = ii-1   ;   ij1 = ij-1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+         !    |          !         |     !      o        !    ______                   ! or incomplete corner
+         ! 5  | x o      ! 6   o x |     ! 7  __x__      ! 8    x                      !  7  ____ o
+         !    |          !         |     !               !      o                      !         |x___
+      CASE( 5 )    ;   ii1 = ii+1   ;   ij1 = ij     ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 6 )    ;   ii1 = ii-1   ;   ij1 = ij     ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 7 )    ;   ii1 = ii     ;   ij1 = ij+1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 8 )    ;   ii1 = ii     ;   ij1 = ij-1   ;   ii2 = -1     ;   ij2 = -1     ;   ii3 = -1     ;   ij3 = -1
+         !        o      !        o      !    _____|     !       |_____  
+         !  9 ____x o    ! 10   o x___   ! 11     x o    ! 12   o x      
+         !         |     !       |       !        o      !        o      
+      CASE( 9  )   ;   ii1 = ii     ;   ij1 = ij+1   ;   ii2 = ii+1   ;   ij2 = ij     ;   ii3 = -1     ;   ij3 = -1 
+      CASE( 10 )   ;   ii1 = ii     ;   ij1 = ij+1   ;   ii2 = ii-1   ;   ij2 = ij     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 11 )   ;   ii1 = ii     ;   ij1 = ij-1   ;   ii2 = ii+1   ;   ij2 = ij     ;   ii3 = -1     ;   ij3 = -1
+      CASE( 12 )   ;   ii1 = ii     ;   ij1 = ij-1   ;   ii2 = ii-1   ;   ij2 = ij     ;   ii3 = -1     ;   ij3 = -1
+         !    |_  o      !        o  _|  !     ¨¨|_|¨¨   !       o         
+         ! 13  _| x o    !  14  o x |_   !  15  o x o    ! 16  o x o       
+         !    |   o      !        o   |  !        o      !    __|¨|__ 
+      CASE( 13 )   ;   ii1 = ii     ;   ij1 = ij+1   ;   ii2 = ii+1   ;   ij2 = ij     ;   ii3 = ii     ;   ij3 = ij-1   
+      CASE( 14 )   ;   ii1 = ii     ;   ij1 = ij+1   ;   ii2 = ii-1   ;   ij2 = ij     ;   ii3 = ii     ;   ij3 = ij-1 
+      CASE( 15 )   ;   ii1 = ii-1   ;   ij1 = ij     ;   ii2 = ii     ;   ij2 = ij-1   ;   ii3 = ii+1   ;   ij3 = ij   
+      CASE( 16 )   ;   ii1 = ii-1   ;   ij1 = ij     ;   ii2 = ii     ;   ij2 = ij+1   ;   ii3 = ii+1   ;   ij3 = ij
+      END SELECT
+   END SUBROUTINE find_neib
+    
+
+   SUBROUTINE bdy_read_seg( kb_bdy, knblendta ) 
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_coords_seg  ***
+      !!
+      !! ** Purpose :  build bdy coordinates with segments defined in namelist
+      !!
+      !! ** Method  :  read namelist nambdy_index blocks
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT (in   ) ::   kb_bdy           ! bdy number
+      INTEGER, DIMENSION(jpbgrd), INTENT (  out) ::   knblendta        ! length of index arrays 
+      !!
+      INTEGER          ::   ios                 ! Local integer output status for namelist read
+      INTEGER          ::   nbdyind, nbdybeg, nbdyend
+      CHARACTER(LEN=1) ::   ctypebdy   !     -        - 
+      NAMELIST/nambdy_index/ ctypebdy, nbdyind, nbdybeg, nbdyend
+      !!----------------------------------------------------------------------
+
+      ! No REWIND here because may need to read more than one nambdy_index namelist.
+      ! Read only namelist_cfg to avoid unseccessfull overwrite 
+      ! keep full control of the configuration namelist
+      READ  ( numnam_cfg, nambdy_index, IOSTAT = ios, ERR = 904 )
+904   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy_index in configuration namelist' )
+      IF(lwm) WRITE ( numond, nambdy_index )
+      
+      SELECT CASE ( TRIM(ctypebdy) )
+      CASE( 'N' )
+         IF( nbdyind == -1 ) THEN  ! Automatic boundary definition: if nbdysegX = -1
+            nbdyind  = jpjglo - 2  ! set boundary to whole side of model domain.
+            nbdybeg  = 2
+            nbdyend  = jpiglo - 1
+         ENDIF
+         nbdysegn = nbdysegn + 1
+         npckgn(nbdysegn) = kb_bdy ! Save bdy package number
+         jpjnob(nbdysegn) = nbdyind
+         jpindt(nbdysegn) = nbdybeg
+         jpinft(nbdysegn) = nbdyend
+         !
+      CASE( 'S' )
+         IF( nbdyind == -1 ) THEN  ! Automatic boundary definition: if nbdysegX = -1
+            nbdyind  = 2           ! set boundary to whole side of model domain.
+            nbdybeg  = 2
+            nbdyend  = jpiglo - 1
+         ENDIF
+         nbdysegs = nbdysegs + 1
+         npckgs(nbdysegs) = kb_bdy ! Save bdy package number
+         jpjsob(nbdysegs) = nbdyind
+         jpisdt(nbdysegs) = nbdybeg
+         jpisft(nbdysegs) = nbdyend
+         !
+      CASE( 'E' )
+         IF( nbdyind == -1 ) THEN  ! Automatic boundary definition: if nbdysegX = -1
+            nbdyind  = jpiglo - 2  ! set boundary to whole side of model domain.
+            nbdybeg  = 2
+            nbdyend  = jpjglo - 1
+         ENDIF
+         nbdysege = nbdysege + 1 
+         npckge(nbdysege) = kb_bdy ! Save bdy package number
+         jpieob(nbdysege) = nbdyind
+         jpjedt(nbdysege) = nbdybeg
+         jpjeft(nbdysege) = nbdyend
+         !
+      CASE( 'W' )
+         IF( nbdyind == -1 ) THEN  ! Automatic boundary definition: if nbdysegX = -1
+            nbdyind  = 2           ! set boundary to whole side of model domain.
+            nbdybeg  = 2
+            nbdyend  = jpjglo - 1
+         ENDIF
+         nbdysegw = nbdysegw + 1
+         npckgw(nbdysegw) = kb_bdy ! Save bdy package number
+         jpiwob(nbdysegw) = nbdyind
+         jpjwdt(nbdysegw) = nbdybeg
+         jpjwft(nbdysegw) = nbdyend
+         !
+      CASE DEFAULT   ;   CALL ctl_stop( 'ctypebdy must be N, S, E or W' )
+      END SELECT
+      
+      ! For simplicity we assume that in case of straight bdy, arrays have the same length
+      ! (even if it is true that last tangential velocity points
+      ! are useless). This simplifies a little bit boundary data format (and agrees with format
+      ! used so far in obc package)
+      
+      knblendta(1:jpbgrd) =  (nbdyend - nbdybeg + 1) * nn_rimwidth(kb_bdy)
+      
+   END SUBROUTINE bdy_read_seg
+
+   
+   SUBROUTINE bdy_ctl_seg
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_ctl_seg  ***
+      !!
+      !! ** Purpose :   Check straight open boundary segments location
+      !!
+      !! ** Method  :   - Look for open boundary corners
+      !!                - Check that segments start or end on land 
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ib, ib1, ib2, ji ,jj, itest  
+      INTEGER, DIMENSION(jp_nseg,2) :: icorne, icornw, icornn, icorns  
+      REAL(wp), DIMENSION(2) ::   ztestmask
+      !!----------------------------------------------------------------------
+      !
+      IF (lwp) WRITE(numout,*) ' '
+      IF (lwp) WRITE(numout,*) 'bdy_ctl_seg: Check analytical segments'
+      IF (lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      !
+      IF(lwp) WRITE(numout,*) 'Number of east  segments     : ', nbdysege
+      IF(lwp) WRITE(numout,*) 'Number of west  segments     : ', nbdysegw
+      IF(lwp) WRITE(numout,*) 'Number of north segments     : ', nbdysegn
+      IF(lwp) WRITE(numout,*) 'Number of south segments     : ', nbdysegs
+      ! 1. Check bounds
+      !----------------
+      DO ib = 1, nbdysegn
+         IF (lwp) WRITE(numout,*) '**check north seg bounds pckg: ', npckgn(ib)
+         IF ((jpjnob(ib).ge.jpjglo-1).or.& 
+            &(jpjnob(ib).le.1))        CALL ctl_stop( 'nbdyind out of domain' )
+         IF (jpindt(ib).ge.jpinft(ib)) CALL ctl_stop( 'Bdy start index is greater than end index' )
+         IF (jpindt(ib).lt.1     )     CALL ctl_stop( 'Start index out of domain' )
+         IF (jpinft(ib).gt.jpiglo)     CALL ctl_stop( 'End index out of domain' )
+      END DO
+      !
+      DO ib = 1, nbdysegs
+         IF (lwp) WRITE(numout,*) '**check south seg bounds pckg: ', npckgs(ib)
+         IF ((jpjsob(ib).ge.jpjglo-1).or.& 
+            &(jpjsob(ib).le.1))        CALL ctl_stop( 'nbdyind out of domain' )
+         IF (jpisdt(ib).ge.jpisft(ib)) CALL ctl_stop( 'Bdy start index is greater than end index' )
+         IF (jpisdt(ib).lt.1     )     CALL ctl_stop( 'Start index out of domain' )
+         IF (jpisft(ib).gt.jpiglo)     CALL ctl_stop( 'End index out of domain' )
+      END DO
+      !
+      DO ib = 1, nbdysege
+         IF (lwp) WRITE(numout,*) '**check east  seg bounds pckg: ', npckge(ib)
+         IF ((jpieob(ib).ge.jpiglo-1).or.& 
+            &(jpieob(ib).le.1))        CALL ctl_stop( 'nbdyind out of domain' )
+         IF (jpjedt(ib).ge.jpjeft(ib)) CALL ctl_stop( 'Bdy start index is greater than end index' )
+         IF (jpjedt(ib).lt.1     )     CALL ctl_stop( 'Start index out of domain' )
+         IF (jpjeft(ib).gt.jpjglo)     CALL ctl_stop( 'End index out of domain' )
+      END DO
+      !
+      DO ib = 1, nbdysegw
+         IF (lwp) WRITE(numout,*) '**check west  seg bounds pckg: ', npckgw(ib)
+         IF ((jpiwob(ib).ge.jpiglo-1).or.& 
+            &(jpiwob(ib).le.1))        CALL ctl_stop( 'nbdyind out of domain' )
+         IF (jpjwdt(ib).ge.jpjwft(ib)) CALL ctl_stop( 'Bdy start index is greater than end index' )
+         IF (jpjwdt(ib).lt.1     )     CALL ctl_stop( 'Start index out of domain' )
+         IF (jpjwft(ib).gt.jpjglo)     CALL ctl_stop( 'End index out of domain' )
+      ENDDO
+      !
+      !      
+      ! 2. Look for segment crossings
+      !------------------------------ 
+      IF (lwp) WRITE(numout,*) '**Look for segments corners  :'
+      !
+      itest = 0 ! corner number
+      !
+      ! flag to detect if start or end of open boundary belongs to a corner
+      ! if not (=0), it must be on land.
+      ! if a corner is detected, save bdy package number for further tests
+      icorne(:,:)=0. ; icornw(:,:)=0. ; icornn(:,:)=0. ; icorns(:,:)=0.
+      ! South/West crossings
+      IF ((nbdysegw > 0).AND.(nbdysegs > 0)) THEN
+         DO ib1 = 1, nbdysegw        
+            DO ib2 = 1, nbdysegs
+               IF (( jpisdt(ib2)<=jpiwob(ib1)).AND. &
+                &  ( jpisft(ib2)>=jpiwob(ib1)).AND. &
+                &  ( jpjwdt(ib1)<=jpjsob(ib2)).AND. &
+                &  ( jpjwft(ib1)>=jpjsob(ib2))) THEN
+                  IF ((jpjwdt(ib1)==jpjsob(ib2)).AND.(jpisdt(ib2)==jpiwob(ib1))) THEN 
+                     ! We have a possible South-West corner                      
+!                     WRITE(numout,*) ' Found a South-West corner at (i,j): ', jpisdt(ib2), jpjwdt(ib1) 
+!                     WRITE(numout,*) ' between segments: ', npckgw(ib1), npckgs(ib2)
+                     icornw(ib1,1) = npckgs(ib2)
+                     icorns(ib2,1) = npckgw(ib1)
+                  ELSEIF ((jpisft(ib2)==jpiwob(ib1)).AND.(jpjwft(ib1)==jpjsob(ib2))) THEN
+                     WRITE(ctmp1,*) ' Found an acute open boundary corner at point (i,j)= ', &
+                        &                                     jpisft(ib2), jpjwft(ib1)
+                     WRITE(ctmp2,*) ' Not allowed yet'
+                     WRITE(ctmp3,*) ' Crossing problem with West segment: ',npckgw(ib1), & 
+                        &                            ' and South segment: ',npckgs(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2, ctmp3 )
+                  ELSE
+                     WRITE(ctmp1,*) ' Check South and West Open boundary indices'
+                     WRITE(ctmp2,*) ' Crossing problem with West segment: ',npckgw(ib1) , &
+                        &                            ' and South segment: ',npckgs(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2 )
+                  END IF
+               END IF
+            END DO
+         END DO
+      END IF
+      !
+      ! South/East crossings
+      IF ((nbdysege > 0).AND.(nbdysegs > 0)) THEN
+         DO ib1 = 1, nbdysege
+            DO ib2 = 1, nbdysegs
+               IF (( jpisdt(ib2)<=jpieob(ib1)+1).AND. &
+                &  ( jpisft(ib2)>=jpieob(ib1)+1).AND. &
+                &  ( jpjedt(ib1)<=jpjsob(ib2)  ).AND. &
+                &  ( jpjeft(ib1)>=jpjsob(ib2)  )) THEN
+                  IF ((jpjedt(ib1)==jpjsob(ib2)).AND.(jpisft(ib2)==jpieob(ib1)+1)) THEN
+                     ! We have a possible South-East corner 
+!                     WRITE(numout,*) ' Found a South-East corner at (i,j): ', jpisft(ib2), jpjedt(ib1) 
+!                     WRITE(numout,*) ' between segments: ', npckge(ib1), npckgs(ib2)
+                     icorne(ib1,1) = npckgs(ib2)
+                     icorns(ib2,2) = npckge(ib1)
+                  ELSEIF ((jpjeft(ib1)==jpjsob(ib2)).AND.(jpisdt(ib2)==jpieob(ib1)+1)) THEN
+                     WRITE(ctmp1,*) ' Found an acute open boundary corner at point (i,j)= ', &
+                        &                                     jpisdt(ib2), jpjeft(ib1)
+                     WRITE(ctmp2,*) ' Not allowed yet'
+                     WRITE(ctmp3,*) ' Crossing problem with East segment: ',npckge(ib1), &
+                        &                            ' and South segment: ',npckgs(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2, ctmp3 )
+                  ELSE
+                     WRITE(ctmp1,*) ' Check South and East Open boundary indices'
+                     WRITE(ctmp2,*) ' Crossing problem with East segment: ',npckge(ib1), &
+                     &                               ' and South segment: ',npckgs(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2 )
+                  END IF
+               END IF
+            END DO
+         END DO
+      END IF
+      !
+      ! North/West crossings
+      IF ((nbdysegn > 0).AND.(nbdysegw > 0)) THEN
+         DO ib1 = 1, nbdysegw        
+            DO ib2 = 1, nbdysegn
+               IF (( jpindt(ib2)<=jpiwob(ib1)  ).AND. &
+                &  ( jpinft(ib2)>=jpiwob(ib1)  ).AND. &
+                &  ( jpjwdt(ib1)<=jpjnob(ib2)+1).AND. &
+                &  ( jpjwft(ib1)>=jpjnob(ib2)+1)) THEN
+                  IF ((jpjwft(ib1)==jpjnob(ib2)+1).AND.(jpindt(ib2)==jpiwob(ib1))) THEN
+                     ! We have a possible North-West corner 
+!                     WRITE(numout,*) ' Found a North-West corner at (i,j): ', jpindt(ib2), jpjwft(ib1) 
+!                     WRITE(numout,*) ' between segments: ', npckgw(ib1), npckgn(ib2)
+                     icornw(ib1,2) = npckgn(ib2)
+                     icornn(ib2,1) = npckgw(ib1)
+                  ELSEIF ((jpjwdt(ib1)==jpjnob(ib2)+1).AND.(jpinft(ib2)==jpiwob(ib1))) THEN
+                     WRITE(ctmp1,*) ' Found an acute open boundary corner at point (i,j)= ', &
+                     &                                     jpinft(ib2), jpjwdt(ib1)
+                     WRITE(ctmp2,*) ' Not allowed yet'
+                     WRITE(ctmp3,*) ' Crossing problem with West segment: ',npckgw(ib1), &
+                     &                               ' and North segment: ',npckgn(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2, ctmp3 )
+                  ELSE
+                     WRITE(ctmp1,*) ' Check North and West Open boundary indices'
+                     WRITE(ctmp2,*) ' Crossing problem with West segment: ',npckgw(ib1), &
+                     &                               ' and North segment: ',npckgn(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2 )
+                  END IF
+               END IF
+            END DO
+         END DO
+      END IF
+      !
+      ! North/East crossings
+      IF ((nbdysegn > 0).AND.(nbdysege > 0)) THEN
+         DO ib1 = 1, nbdysege        
+            DO ib2 = 1, nbdysegn
+               IF (( jpindt(ib2)<=jpieob(ib1)+1).AND. &
+                &  ( jpinft(ib2)>=jpieob(ib1)+1).AND. &
+                &  ( jpjedt(ib1)<=jpjnob(ib2)+1).AND. &
+                &  ( jpjeft(ib1)>=jpjnob(ib2)+1)) THEN
+                  IF ((jpjeft(ib1)==jpjnob(ib2)+1).AND.(jpinft(ib2)==jpieob(ib1)+1)) THEN
+                     ! We have a possible North-East corner 
+!                     WRITE(numout,*) ' Found a North-East corner at (i,j): ', jpinft(ib2), jpjeft(ib1)
+!                     WRITE(numout,*) ' between segments: ', npckge(ib1), npckgn(ib2)
+                     icorne(ib1,2) = npckgn(ib2)
+                     icornn(ib2,2) = npckge(ib1)
+                  ELSEIF ((jpjedt(ib1)==jpjnob(ib2)+1).AND.(jpindt(ib2)==jpieob(ib1)+1)) THEN
+                     WRITE(ctmp1,*) ' Found an acute open boundary corner at point (i,j)= ', &
+                     &                                     jpindt(ib2), jpjedt(ib1)
+                     WRITE(ctmp2,*) ' Not allowed yet'
+                     WRITE(ctmp3,*) ' Crossing problem with East segment: ',npckge(ib1), &
+                     &                               ' and North segment: ',npckgn(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2, ctmp3 )
+                  ELSE
+                     WRITE(ctmp1,*) ' Check North and East Open boundary indices'
+                     WRITE(ctmp2,*) ' Crossing problem with East segment: ',npckge(ib1), &
+                     &                               ' and North segment: ',npckgn(ib2)
+                     CALL ctl_stop( ctmp1, ctmp2 )
+                  END IF
+               END IF
+            END DO
+         END DO
+      END IF
+      !
+      ! 3. Check if segment extremities are on land
+      !-------------------------------------------- 
+      !
+      ! West segments
+      DO ib = 1, nbdysegw
+         ! get mask at boundary extremities:
+         ztestmask(1:2)=0.
+         DO ji = 1, jpi
+            DO jj = 1, jpj             
+              IF (((ji + nimpp - 1) == jpiwob(ib)).AND. & 
+               &  ((jj + njmpp - 1) == jpjwdt(ib))) ztestmask(1)=tmask(ji,jj,1)
+              IF (((ji + nimpp - 1) == jpiwob(ib)).AND. & 
+               &  ((jj + njmpp - 1) == jpjwft(ib))) ztestmask(2)=tmask(ji,jj,1)  
+            END DO
+         END DO
+         CALL mpp_sum( 'bdyini', ztestmask, 2 )   ! sum over the global domain
+
+         IF (ztestmask(1)==1) THEN 
+            IF (icornw(ib,1)==0) THEN
+               WRITE(ctmp1,*) ' Open boundary segment ', npckgw(ib)
+               CALL ctl_stop( ctmp1, ' does not start on land or on a corner' )
+            ELSE
+               ! This is a corner
+               IF(lwp) WRITE(numout,*) 'Found a South-West corner at (i,j): ', jpiwob(ib), jpjwdt(ib)
+               CALL bdy_ctl_corn(npckgw(ib), icornw(ib,1))
+               itest=itest+1
+            ENDIF
+         ENDIF
+         IF (ztestmask(2)==1) THEN
+            IF (icornw(ib,2)==0) THEN
+               WRITE(ctmp1,*) ' Open boundary segment ', npckgw(ib)
+               CALL ctl_stop( ' ', ctmp1, ' does not end on land or on a corner' )
+            ELSE
+               ! This is a corner
+               IF(lwp) WRITE(numout,*) 'Found a North-West corner at (i,j): ', jpiwob(ib), jpjwft(ib)
+               CALL bdy_ctl_corn(npckgw(ib), icornw(ib,2))
+               itest=itest+1
+            ENDIF
+         ENDIF
+      END DO
+      !
+      ! East segments
+      DO ib = 1, nbdysege
+         ! get mask at boundary extremities:
+         ztestmask(1:2)=0.
+         DO ji = 1, jpi
+            DO jj = 1, jpj             
+              IF (((ji + nimpp - 1) == jpieob(ib)+1).AND. & 
+               &  ((jj + njmpp - 1) == jpjedt(ib))) ztestmask(1)=tmask(ji,jj,1)
+              IF (((ji + nimpp - 1) == jpieob(ib)+1).AND. & 
+               &  ((jj + njmpp - 1) == jpjeft(ib))) ztestmask(2)=tmask(ji,jj,1)  
+            END DO
+         END DO
+         CALL mpp_sum( 'bdyini', ztestmask, 2 )   ! sum over the global domain
+
+         IF (ztestmask(1)==1) THEN
+            IF (icorne(ib,1)==0) THEN
+               WRITE(ctmp1,*) ' Open boundary segment ', npckge(ib)
+               CALL ctl_stop( ctmp1, ' does not start on land or on a corner' )
+            ELSE
+               ! This is a corner
+               IF(lwp) WRITE(numout,*) 'Found a South-East corner at (i,j): ', jpieob(ib)+1, jpjedt(ib)
+               CALL bdy_ctl_corn(npckge(ib), icorne(ib,1))
+               itest=itest+1
+            ENDIF
+         ENDIF
+         IF (ztestmask(2)==1) THEN
+            IF (icorne(ib,2)==0) THEN
+               WRITE(ctmp1,*) ' Open boundary segment ', npckge(ib)
+               CALL ctl_stop( ctmp1, ' does not end on land or on a corner' )
+            ELSE
+               ! This is a corner
+               IF(lwp) WRITE(numout,*) 'Found a North-East corner at (i,j): ', jpieob(ib)+1, jpjeft(ib)
+               CALL bdy_ctl_corn(npckge(ib), icorne(ib,2))
+               itest=itest+1
+            ENDIF
+         ENDIF
+      END DO
+      !
+      ! South segments
+      DO ib = 1, nbdysegs
+         ! get mask at boundary extremities:
+         ztestmask(1:2)=0.
+         DO ji = 1, jpi
+            DO jj = 1, jpj             
+              IF (((jj + njmpp - 1) == jpjsob(ib)).AND. & 
+               &  ((ji + nimpp - 1) == jpisdt(ib))) ztestmask(1)=tmask(ji,jj,1)
+              IF (((jj + njmpp - 1) == jpjsob(ib)).AND. & 
+               &  ((ji + nimpp - 1) == jpisft(ib))) ztestmask(2)=tmask(ji,jj,1)  
+            END DO
+         END DO
+         CALL mpp_sum( 'bdyini', ztestmask, 2 )   ! sum over the global domain
+
+         IF ((ztestmask(1)==1).AND.(icorns(ib,1)==0)) THEN
+            WRITE(ctmp1,*) ' Open boundary segment ', npckgs(ib)
+            CALL ctl_stop( ctmp1, ' does not start on land or on a corner' )
+         ENDIF
+         IF ((ztestmask(2)==1).AND.(icorns(ib,2)==0)) THEN
+            WRITE(ctmp1,*) ' Open boundary segment ', npckgs(ib)
+            CALL ctl_stop( ctmp1, ' does not end on land or on a corner' )
+         ENDIF
+      END DO
+      !
+      ! North segments
+      DO ib = 1, nbdysegn
+         ! get mask at boundary extremities:
+         ztestmask(1:2)=0.
+         DO ji = 1, jpi
+            DO jj = 1, jpj             
+              IF (((jj + njmpp - 1) == jpjnob(ib)+1).AND. & 
+               &  ((ji + nimpp - 1) == jpindt(ib))) ztestmask(1)=tmask(ji,jj,1)
+              IF (((jj + njmpp - 1) == jpjnob(ib)+1).AND. & 
+               &  ((ji + nimpp - 1) == jpinft(ib))) ztestmask(2)=tmask(ji,jj,1)  
+            END DO
+         END DO
+         CALL mpp_sum( 'bdyini', ztestmask, 2 )   ! sum over the global domain
+
+         IF ((ztestmask(1)==1).AND.(icornn(ib,1)==0)) THEN
+            WRITE(ctmp1,*) ' Open boundary segment ', npckgn(ib)
+            CALL ctl_stop( ctmp1, ' does not start on land' )
+         ENDIF
+         IF ((ztestmask(2)==1).AND.(icornn(ib,2)==0)) THEN
+            WRITE(ctmp1,*) ' Open boundary segment ', npckgn(ib)
+            CALL ctl_stop( ctmp1, ' does not end on land' )
+         ENDIF
+      END DO
+      !
+      IF ((itest==0).AND.(lwp)) WRITE(numout,*) 'NO open boundary corner found'
+      !
+      ! Other tests TBD: 
+      ! segments completly on land
+      ! optimized open boundary array length according to landmask
+      ! Nudging layers that overlap with interior domain
+      !
+   END SUBROUTINE bdy_ctl_seg
+
+   
+   SUBROUTINE bdy_coords_seg( nbidta, nbjdta, nbrdta ) 
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_coords_seg  ***
+      !!
+      !! ** Purpose :  build nbidta, nbidta, nbrdta for bdy built with segments
+      !!
+      !! ** Method  :  
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:,:,:), intent(  out)  ::   nbidta, nbjdta, nbrdta   ! Index arrays: i and j indices of bdy dta
+      !!
+      INTEGER  ::   ii, ij, ir, iseg
+      INTEGER  ::   igrd         ! grid type (t=1, u=2, v=3)
+      INTEGER  ::   icount       ! 
+      INTEGER  ::   ib_bdy       ! bdy number
+      !!----------------------------------------------------------------------
+
+      ! East
+      !-----
+      DO iseg = 1, nbdysege
+         ib_bdy = npckge(iseg)
+         !
+         ! ------------ T points -------------
+         igrd=1
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ij = jpjedt(iseg), jpjeft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpieob(iseg) + 2 - ir
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ U points -------------
+         igrd=2
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ij = jpjedt(iseg), jpjeft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpieob(iseg) + 1 - ir
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ V points -------------
+         igrd=3
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            !            DO ij = jpjedt(iseg), jpjeft(iseg) - 1
+            DO ij = jpjedt(iseg), jpjeft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpieob(iseg) + 2 - ir
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+            nbidta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+            nbjdta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+         ENDDO
+      ENDDO
+      !
+      ! West
+      !-----
+      DO iseg = 1, nbdysegw
+         ib_bdy = npckgw(iseg)
+         !
+         ! ------------ T points -------------
+         igrd=1
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ij = jpjwdt(iseg), jpjwft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpiwob(iseg) + ir - 1
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ U points -------------
+         igrd=2
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ij = jpjwdt(iseg), jpjwft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpiwob(iseg) + ir - 1
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ V points -------------
+         igrd=3
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            !            DO ij = jpjwdt(iseg), jpjwft(iseg) - 1
+            DO ij = jpjwdt(iseg), jpjwft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = jpiwob(iseg) + ir - 1
+               nbjdta(icount, igrd, ib_bdy) = ij
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+            nbidta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+            nbjdta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+         ENDDO
+      ENDDO
+      !
+      ! North
+      !-----
+      DO iseg = 1, nbdysegn
+         ib_bdy = npckgn(iseg)
+         !
+         ! ------------ T points -------------
+         igrd=1
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ii = jpindt(iseg), jpinft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjnob(iseg) + 2 - ir 
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ U points -------------
+         igrd=2
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            !            DO ii = jpindt(iseg), jpinft(iseg) - 1
+            DO ii = jpindt(iseg), jpinft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjnob(iseg) + 2 - ir
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+            nbidta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+            nbjdta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+         ENDDO
+         !
+         ! ------------ V points -------------
+         igrd=3
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ii = jpindt(iseg), jpinft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjnob(iseg) + 1 - ir
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+      ENDDO
+      !
+      ! South
+      !-----
+      DO iseg = 1, nbdysegs
+         ib_bdy = npckgs(iseg)
+         !
+         ! ------------ T points -------------
+         igrd=1
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ii = jpisdt(iseg), jpisft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjsob(iseg) + ir - 1
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+         !
+         ! ------------ U points -------------
+         igrd=2
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            !            DO ii = jpisdt(iseg), jpisft(iseg) - 1
+            DO ii = jpisdt(iseg), jpisft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjsob(iseg) + ir - 1
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+            nbidta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+            nbjdta(icount, igrd, ib_bdy) = -ib_bdy ! Discount this point
+         ENDDO
+         !
+         ! ------------ V points -------------
+         igrd=3
+         icount=0
+         DO ir = 1, nn_rimwidth(ib_bdy)
+            DO ii = jpisdt(iseg), jpisft(iseg)
+               icount = icount + 1
+               nbidta(icount, igrd, ib_bdy) = ii
+               nbjdta(icount, igrd, ib_bdy) = jpjsob(iseg) + ir - 1
+               nbrdta(icount, igrd, ib_bdy) = ir
+            ENDDO
+         ENDDO
+      ENDDO
+
+      
+   END SUBROUTINE bdy_coords_seg
+   
+   
+   SUBROUTINE bdy_ctl_corn( ib1, ib2 )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_ctl_corn  ***
+      !!
+      !! ** Purpose :   Check numerical schemes consistency between
+      !!                segments having a common corner
+      !!
+      !! ** Method  :   
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in)  ::   ib1, ib2
+      INTEGER :: itest
+      !!----------------------------------------------------------------------
+      itest = 0
+
+      IF( cn_dyn2d(ib1) /= cn_dyn2d(ib2) )   itest = itest + 1
+      IF( cn_dyn3d(ib1) /= cn_dyn3d(ib2) )   itest = itest + 1
+      IF( cn_tra  (ib1) /= cn_tra  (ib2) )   itest = itest + 1
+      !
+      IF( nn_dyn2d_dta(ib1) /= nn_dyn2d_dta(ib2) )   itest = itest + 1
+      IF( nn_dyn3d_dta(ib1) /= nn_dyn3d_dta(ib2) )   itest = itest + 1
+      IF( nn_tra_dta  (ib1) /= nn_tra_dta  (ib2) )   itest = itest + 1
+      !
+      IF( nn_rimwidth(ib1) /= nn_rimwidth(ib2) )   itest = itest + 1   
+      !
+      IF( itest>0 ) THEN
+         WRITE(ctmp1,*) ' Segments ', ib1, 'and ', ib2
+         CALL ctl_stop( ctmp1, ' have different open bdy schemes' )
+      ENDIF
+      !
+   END SUBROUTINE bdy_ctl_corn
+
+
+   SUBROUTINE bdy_meshwri()
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_meshwri  ***
+      !!         
+      !! ** Purpose :   write netcdf file with nbr, flagu, flagv, ntreat for T, U 
+      !!                and V points in 2D arrays for easier visualisation/control
+      !!
+      !! ** Method  :   use iom_rstput as in domwri.F
+      !!----------------------------------------------------------------------      
+      INTEGER  ::   ib_bdy, ii, ij, igrd, ib     ! dummy loop indices
+      INTEGER  ::   inum                                   !   -       -
+      REAL(wp), POINTER, DIMENSION(:,:)     ::   zmask                   ! pointer to 2D mask fields
+      REAL(wp)         , DIMENSION(jpi,jpj) ::   ztmp
+      CHARACTER(LEN=1) , DIMENSION(jpbgrd)  ::   cgrid
+      !!----------------------------------------------------------------------      
+      cgrid = (/'t','u','v'/)
+      CALL iom_open( 'bdy_mesh', inum, ldwrt = .TRUE. )
+      DO igrd = 1, jpbgrd
+         SELECT CASE( igrd )
+         CASE( 1 )   ;   zmask => tmask(:,:,1)
+         CASE( 2 )   ;   zmask => umask(:,:,1)
+         CASE( 3 )   ;   zmask => vmask(:,:,1)
+         END SELECT
+         ztmp(:,:) = zmask(:,:)
+         DO ib_bdy = 1, nb_bdy
+            DO ib = 1, idx_bdy(ib_bdy)%nblen(igrd)      ! nbr deined for all rims
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               ztmp(ii,ij) = REAL(idx_bdy(ib_bdy)%nbr(ib,igrd), wp) + 10.
+               IF( zmask(ii,ij) == 0. ) ztmp(ii,ij) = - ztmp(ii,ij)
+            END DO
+         END DO
+         CALL iom_rstput( 0, 0, inum, 'bdy_nbr_'//cgrid(igrd), ztmp(:,:), ktype = jp_i4 )
+         ztmp(:,:) = zmask(:,:)
+         DO ib_bdy = 1, nb_bdy
+            DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)   ! flagu defined only for rims 0 and 1
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               ztmp(ii,ij) = REAL(idx_bdy(ib_bdy)%flagu(ib,igrd), wp) + 10.
+               IF( zmask(ii,ij) == 0. ) ztmp(ii,ij) = - ztmp(ii,ij)
+            END DO
+         END DO
+         CALL iom_rstput( 0, 0, inum, 'flagu_'//cgrid(igrd), ztmp(:,:), ktype = jp_i4 )
+         ztmp(:,:) = zmask(:,:)
+         DO ib_bdy = 1, nb_bdy
+            DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)   ! flagv defined only for rims 0 and 1
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               ztmp(ii,ij) = REAL(idx_bdy(ib_bdy)%flagv(ib,igrd), wp) + 10.
+               IF( zmask(ii,ij) == 0. ) ztmp(ii,ij) = - ztmp(ii,ij)
+            END DO
+         END DO
+         CALL iom_rstput( 0, 0, inum, 'flagv_'//cgrid(igrd), ztmp(:,:), ktype = jp_i4 )
+         ztmp(:,:) = zmask(:,:)
+         DO ib_bdy = 1, nb_bdy
+            DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)   ! ntreat defined only for rims 0 and 1
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               ztmp(ii,ij) = REAL(idx_bdy(ib_bdy)%ntreat(ib,igrd), wp) + 10.
+               IF( zmask(ii,ij) == 0. ) ztmp(ii,ij) = - ztmp(ii,ij)
+            END DO
+         END DO
+         CALL iom_rstput( 0, 0, inum, 'ntreat_'//cgrid(igrd), ztmp(:,:), ktype = jp_i4 )
+      END DO
+      CALL iom_close( inum )
+
+   END SUBROUTINE bdy_meshwri
+   
+   !!=================================================================================
+END MODULE bdyini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdylib.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdylib.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdylib.F90	(revision 14097)
@@ -0,0 +1,527 @@
+MODULE bdylib
+   !!======================================================================
+   !!                       ***  MODULE  bdylib  ***
+   !! Unstructured Open Boundary Cond. :  Library module of generic boundary algorithms.
+   !!======================================================================
+   !! History :  3.6  !  2013     (D. Storkey) original code
+   !!            4.0  !  2014     (T. Lovato) Generalize OBC structure
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   bdy_orlanski_2d
+   !!   bdy_orlanski_3d
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE bdy_oce        ! ocean open boundary conditions
+   USE phycst         ! physical constants
+   USE bdyini
+   !
+   USE in_out_manager !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp, ONLY: ctl_stop
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_frs, bdy_spe, bdy_nmn, bdy_orl
+   PUBLIC   bdy_orlanski_2d
+   PUBLIC   bdy_orlanski_3d
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_frs( idx, pta, dta )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_frs  ***
+      !!
+      !! ** Purpose : Apply the Flow Relaxation Scheme for tracers at open boundaries.
+      !!
+      !! Reference : Engedahl H., 1995, Tellus, 365-382.
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),                     INTENT(in) ::   idx  ! OBC indices
+      REAL(wp), DIMENSION(:,:),            INTENT(in) ::   dta  ! OBC external data
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pta  ! tracer trend
+      !!
+      REAL(wp) ::   zwgt           ! boundary weight
+      INTEGER  ::   ib, ik, igrd   ! dummy loop indices
+      INTEGER  ::   ii, ij         ! 2D addresses
+      !!----------------------------------------------------------------------
+      !
+      igrd = 1                       ! Everything is at T-points here
+      DO ib = 1, idx%nblen(igrd)
+         DO ik = 1, jpkm1
+            ii = idx%nbi(ib,igrd) 
+            ij = idx%nbj(ib,igrd)
+            zwgt = idx%nbw(ib,igrd)
+            pta(ii,ij,ik) = ( pta(ii,ij,ik) + zwgt * (dta(ib,ik) - pta(ii,ij,ik) ) ) * tmask(ii,ij,ik)
+         END DO
+      END DO
+      !
+   END SUBROUTINE bdy_frs
+
+
+   SUBROUTINE bdy_spe( idx, pta, dta )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_spe  ***
+      !!
+      !! ** Purpose : Apply a specified value for tracers at open boundaries.
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),                     INTENT(in) ::   idx  ! OBC indices
+      REAL(wp), DIMENSION(:,:),            INTENT(in) ::   dta  ! OBC external data
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pta  ! tracer trend
+      !!
+      INTEGER  ::   ib, ik, igrd   ! dummy loop indices
+      INTEGER  ::   ii, ij         ! 2D addresses
+      !!----------------------------------------------------------------------
+      !
+      igrd = 1                       ! Everything is at T-points here
+      DO ib = 1, idx%nblenrim(igrd)
+         ii = idx%nbi(ib,igrd)
+         ij = idx%nbj(ib,igrd)
+         DO ik = 1, jpkm1
+            pta(ii,ij,ik) = dta(ib,ik) * tmask(ii,ij,ik)
+         END DO
+      END DO
+      !
+   END SUBROUTINE bdy_spe
+
+
+   SUBROUTINE bdy_orl( idx, ptb, pta, dta, lrim0, ll_npo )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_orl  ***
+      !!
+      !! ** Purpose : Apply Orlanski radiation for tracers at open boundaries.
+      !!              This is a wrapper routine for bdy_orlanski_3d below
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),                     INTENT(in) ::   idx  ! OBC indices
+      REAL(wp), DIMENSION(:,:),            INTENT(in) ::   dta  ! OBC external data
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   ptb  ! before tracer field
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pta  ! tracer trend
+      LOGICAL                 , OPTIONAL,  INTENT(in) ::   lrim0   ! indicate if rim 0 is treated
+      LOGICAL,                             INTENT(in) ::   ll_npo  ! switch for NPO version
+      !!
+      INTEGER  ::   igrd                                    ! grid index
+      !!----------------------------------------------------------------------
+      !
+      igrd = 1                       ! Everything is at T-points here
+      !
+      CALL bdy_orlanski_3d( idx, igrd, ptb(:,:,:), pta(:,:,:), dta, lrim0, ll_npo )
+      !
+   END SUBROUTINE bdy_orl
+
+
+   SUBROUTINE bdy_orlanski_2d( idx, igrd, phib, phia, phi_ext, lrim0, ll_npo )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_orlanski_2d  ***
+      !!             
+      !!              - Apply Orlanski radiation condition adaptively to 2D fields:
+      !!                  - radiation plus weak nudging at outflow points
+      !!                  - no radiation and strong nudging at inflow points
+      !! 
+      !!
+      !! References:  Marchesiello, McWilliams and Shchepetkin, Ocean Modelling vol. 3 (2001)    
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),          INTENT(in   ) ::   idx      ! BDY indices
+      INTEGER ,                 INTENT(in   ) ::   igrd     ! grid index
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   phib     ! model before 2D field
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   phia     ! model after 2D field (to be updated)
+      REAL(wp), DIMENSION(:)  , INTENT(in   ) ::   phi_ext  ! external forcing data
+      LOGICAL, OPTIONAL,        INTENT(in   ) ::   lrim0    ! indicate if rim 0 is treated
+      LOGICAL ,                 INTENT(in   ) ::   ll_npo   ! switch for NPO version
+      !
+      INTEGER  ::   jb                                     ! dummy loop indices
+      INTEGER  ::   ii, ij, iibm1, iibm2, ijbm1, ijbm2     ! 2D addresses
+      INTEGER  ::   iijm1, iijp1, ijjm1, ijjp1             ! 2D addresses
+      INTEGER  ::   iibm1jp1, iibm1jm1, ijbm1jp1, ijbm1jm1 ! 2D addresses
+      INTEGER  ::   ii_offset, ij_offset                   ! offsets for mask indices
+      INTEGER  ::   flagu, flagv                           ! short cuts
+      INTEGER  ::   ibeg, iend                             ! length of rim to be treated (rim 0 or rim 1 or both)
+      REAL(wp) ::   zmask_x, zmask_y1, zmask_y2
+      REAL(wp) ::   zex1, zex2, zey, zey1, zey2
+      REAL(wp) ::   zdt, zdx, zdy, znor2, zrx, zry         ! intermediate calculations
+      REAL(wp) ::   zout, zwgt, zdy_centred
+      REAL(wp) ::   zdy_1, zdy_2, zsign_ups
+      REAL(wp), PARAMETER :: zepsilon = 1.e-30                 ! local small value
+      REAL(wp), POINTER, DIMENSION(:,:)          :: zmask      ! land/sea mask for field
+      REAL(wp), POINTER, DIMENSION(:,:)          :: zmask_xdif ! land/sea mask for x-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:)          :: zmask_ydif ! land/sea mask for y-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:)          :: pe_xdif    ! scale factors for x-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:)          :: pe_ydif    ! scale factors for y-derivatives
+      !!----------------------------------------------------------------------
+      !
+      ! ----------------------------------!
+      ! Orlanski boundary conditions     :!
+      ! ----------------------------------! 
+     
+      SELECT CASE(igrd)
+         CASE(1)
+            zmask      => tmask(:,:,1)
+            zmask_xdif => umask(:,:,1)
+            zmask_ydif => vmask(:,:,1)
+            pe_xdif    => e1u(:,:)
+            pe_ydif    => e2v(:,:)
+            ii_offset = 0
+            ij_offset = 0
+         CASE(2)
+            zmask      => umask(:,:,1)
+            zmask_xdif => tmask(:,:,1)
+            zmask_ydif => fmask(:,:,1)
+            pe_xdif    => e1t(:,:)
+            pe_ydif    => e2f(:,:)
+            ii_offset = 1
+            ij_offset = 0
+         CASE(3)
+            zmask      => vmask(:,:,1)
+            zmask_xdif => fmask(:,:,1)
+            zmask_ydif => tmask(:,:,1)
+            pe_xdif    => e1f(:,:)
+            pe_ydif    => e2t(:,:)
+            ii_offset = 0
+            ij_offset = 1
+         CASE DEFAULT ;   CALL ctl_stop( 'unrecognised value for igrd in bdy_orlanksi_2d' )
+      END SELECT
+      !
+      IF( PRESENT(lrim0) ) THEN
+         IF( lrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)   ! rim 0
+         ELSE               ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)    ! rim 1
+         END IF
+      ELSE                  ;   ibeg = 1                       ;   iend = idx%nblenrim(igrd)    ! both
+      END IF
+      !
+      DO jb = ibeg, iend
+         ii  = idx%nbi(jb,igrd)
+         ij  = idx%nbj(jb,igrd) 
+         IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )   CYCLE
+         flagu = int( idx%flagu(jb,igrd) )
+         flagv = int( idx%flagv(jb,igrd) )
+         !
+         ! Calculate positions of b-1 and b-2 points for this rim point
+         ! also (b-1,j-1) and (b-1,j+1) points
+         iibm1 = ii + flagu ; iibm2 = ii + 2*flagu 
+         ijbm1 = ij + flagv ; ijbm2 = ij + 2*flagv
+          !
+         iijm1 = ii - abs(flagv) ; iijp1 = ii + abs(flagv) 
+         ijjm1 = ij - abs(flagu) ; ijjp1 = ij + abs(flagu)
+         !
+         iibm1jm1 = ii + flagu - abs(flagv) ; iibm1jp1 = ii + flagu + abs(flagv) 
+         ijbm1jm1 = ij + flagv - abs(flagu) ; ijbm1jp1 = ij + flagv + abs(flagu) 
+         !
+         ! Calculate scale factors for calculation of spatial derivatives.        
+         zex1 = ( abs(iibm1-iibm2) * pe_xdif(iibm1   +ii_offset,ijbm1             )   &
+        &       + abs(ijbm1-ijbm2) * pe_ydif(iibm1             ,ijbm1   +ij_offset) ) 
+         zex2 = ( abs(iibm1-iibm2) * pe_xdif(iibm2   +ii_offset,ijbm2             )   &
+        &       + abs(ijbm1-ijbm2) * pe_ydif(iibm2             ,ijbm2   +ij_offset) ) 
+         zey1 = ( (iibm1-iibm1jm1) * pe_xdif(iibm1jm1+ii_offset,ijbm1jm1          )   & 
+        &      +  (ijbm1-ijbm1jm1) * pe_ydif(iibm1jm1          ,ijbm1jm1+ij_offset) ) 
+         zey2 = ( (iibm1jp1-iibm1) * pe_xdif(iibm1   +ii_offset,ijbm1             )   &
+        &      +  (ijbm1jp1-ijbm1) * pe_ydif(iibm1             ,ijbm1   +ij_offset) ) 
+         ! make sure scale factors are nonzero
+         if( zey1 .lt. rsmall ) zey1 = zey2
+         if( zey2 .lt. rsmall ) zey2 = zey1
+         zex1 = max(zex1,rsmall); zex2 = max(zex2,rsmall)
+         zey1 = max(zey1,rsmall); zey2 = max(zey2,rsmall); 
+         !
+         ! Calculate masks for calculation of spatial derivatives.
+         zmask_x  = ( abs(iibm1-iibm2) * zmask_xdif(iibm2   +ii_offset,ijbm2               )   &
+        &           + abs(ijbm1-ijbm2) * zmask_ydif(iibm2             ,ijbm2   +ij_offset) ) 
+         zmask_y1 = ( (iibm1-iibm1jm1) * zmask_xdif(iibm1jm1+ii_offset,ijbm1jm1            )   & 
+        &          +  (ijbm1-ijbm1jm1) * zmask_ydif(iibm1jm1          ,ijbm1jm1+ij_offset) ) 
+         zmask_y2 = ( (iibm1jp1-iibm1) * zmask_xdif(iibm1   +ii_offset,ijbm1               )   &
+        &          +  (ijbm1jp1-ijbm1) * zmask_ydif(iibm1             ,ijbm1   +ij_offset) ) 
+
+         ! Calculation of terms required for both versions of the scheme. 
+         ! Mask derivatives to ensure correct land boundary conditions for each variable.
+         ! Centred derivative is calculated as average of "left" and "right" derivatives for 
+         ! this reason. 
+         ! Note no rdt factor in expression for zdt because it cancels in the expressions for 
+         ! zrx and zry.
+         zdt   =     phia(iibm1   ,ijbm1   ) - phib(iibm1   ,ijbm1   )
+         zdx   = ( ( phia(iibm1   ,ijbm1   ) - phia(iibm2   ,ijbm2   ) ) / zex2 ) * zmask_x 
+         zdy_1 = ( ( phib(iibm1   ,ijbm1   ) - phib(iibm1jm1,ijbm1jm1) ) / zey1 ) * zmask_y1    
+         zdy_2 = ( ( phib(iibm1jp1,ijbm1jp1) - phib(iibm1   ,ijbm1   ) ) / zey2 ) * zmask_y2 
+         zdy_centred = 0.5 * ( zdy_1 + zdy_2 )
+!!$         zdy_centred = phib(iibm1jp1,ijbm1jp1) - phib(iibm1jm1,ijbm1jm1)
+         ! upstream differencing for tangential derivatives
+         zsign_ups = sign( 1., zdt * zdy_centred )
+         zsign_ups = 0.5*( zsign_ups + abs(zsign_ups) )
+         zdy = zsign_ups * zdy_1 + (1. - zsign_ups) * zdy_2
+         znor2 = zdx * zdx + zdy * zdy
+         znor2 = max(znor2,zepsilon)
+         !
+         zrx = zdt * zdx / ( zex1 * znor2 ) 
+!!$         zrx = min(zrx,2.0_wp)
+         zout = sign( 1., zrx )
+         zout = 0.5*( zout + abs(zout) )
+         zwgt = 2.*rdt*( (1.-zout) * idx%nbd(jb,igrd) + zout * idx%nbdout(jb,igrd) )
+         ! only apply radiation on outflow points 
+         if( ll_npo ) then     !! NPO version !!
+            phia(ii,ij) = (1.-zout) * ( phib(ii,ij) + zwgt * ( phi_ext(jb) - phib(ii,ij) ) )        &
+           &            + zout      * ( phib(ii,ij) + zrx*phia(iibm1,ijbm1)                         &
+           &                            + zwgt * ( phi_ext(jb) - phib(ii,ij) ) ) / ( 1. + zrx ) 
+         else                  !! full oblique radiation !!
+            zsign_ups = sign( 1., zdt * zdy )
+            zsign_ups = 0.5*( zsign_ups + abs(zsign_ups) )
+            zey = zsign_ups * zey1 + (1.-zsign_ups) * zey2 
+            zry = zdt * zdy / ( zey * znor2 ) 
+            phia(ii,ij) = (1.-zout) * ( phib(ii,ij) + zwgt * ( phi_ext(jb) - phib(ii,ij) ) )        &
+           &            + zout      * ( phib(ii,ij) + zrx*phia(iibm1,ijbm1)                         &
+           &                    - zsign_ups      * zry * ( phib(ii   ,ij   ) - phib(iijm1,ijjm1 ) ) &
+           &                    - (1.-zsign_ups) * zry * ( phib(iijp1,ijjp1) - phib(ii   ,ij    ) ) &
+           &                    + zwgt * ( phi_ext(jb) - phib(ii,ij) ) ) / ( 1. + zrx ) 
+         end if
+         phia(ii,ij) = phia(ii,ij) * zmask(ii,ij)
+      END DO
+      !
+   END SUBROUTINE bdy_orlanski_2d
+
+
+   SUBROUTINE bdy_orlanski_3d( idx, igrd, phib, phia, phi_ext, lrim0, ll_npo )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_orlanski_3d  ***
+      !!             
+      !!              - Apply Orlanski radiation condition adaptively to 3D fields:
+      !!                  - radiation plus weak nudging at outflow points
+      !!                  - no radiation and strong nudging at inflow points
+      !! 
+      !!
+      !! References:  Marchesiello, McWilliams and Shchepetkin, Ocean Modelling vol. 3 (2001)    
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),            INTENT(in   ) ::   idx      ! BDY indices
+      INTEGER ,                   INTENT(in   ) ::   igrd     ! grid index
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   phib     ! model before 3D field
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   phia     ! model after 3D field (to be updated)
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   phi_ext  ! external forcing data
+      LOGICAL, OPTIONAL,          INTENT(in   ) ::   lrim0    ! indicate if rim 0 is treated
+      LOGICAL ,                   INTENT(in   ) ::   ll_npo   ! switch for NPO version
+      !
+      INTEGER  ::   jb, jk                                 ! dummy loop indices
+      INTEGER  ::   ii, ij, iibm1, iibm2, ijbm1, ijbm2     ! 2D addresses
+      INTEGER  ::   iijm1, iijp1, ijjm1, ijjp1             ! 2D addresses
+      INTEGER  ::   iibm1jp1, iibm1jm1, ijbm1jp1, ijbm1jm1 ! 2D addresses
+      INTEGER  ::   ii_offset, ij_offset                   ! offsets for mask indices
+      INTEGER  ::   flagu, flagv                           ! short cuts
+      INTEGER  ::   ibeg, iend                             ! length of rim to be treated (rim 0 or rim 1 or both)
+      REAL(wp) ::   zmask_x, zmask_y1, zmask_y2
+      REAL(wp) ::   zex1, zex2, zey, zey1, zey2
+      REAL(wp) ::   zdt, zdx, zdy, znor2, zrx, zry         ! intermediate calculations
+      REAL(wp) ::   zout, zwgt, zdy_centred
+      REAL(wp) ::   zdy_1, zdy_2,  zsign_ups
+      REAL(wp), PARAMETER :: zepsilon = 1.e-30                 ! local small value
+      REAL(wp), POINTER, DIMENSION(:,:,:)        :: zmask      ! land/sea mask for field
+      REAL(wp), POINTER, DIMENSION(:,:,:)        :: zmask_xdif ! land/sea mask for x-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:,:)        :: zmask_ydif ! land/sea mask for y-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:)          :: pe_xdif    ! scale factors for x-derivatives
+      REAL(wp), POINTER, DIMENSION(:,:)          :: pe_ydif    ! scale factors for y-derivatives
+      !!----------------------------------------------------------------------
+      !
+      ! ----------------------------------!
+      ! Orlanski boundary conditions     :!
+      ! ----------------------------------! 
+      !
+      SELECT CASE(igrd)
+         CASE(1)
+            zmask      => tmask(:,:,:)
+            zmask_xdif => umask(:,:,:)
+            zmask_ydif => vmask(:,:,:)
+            pe_xdif    => e1u(:,:)
+            pe_ydif    => e2v(:,:)
+            ii_offset = 0
+            ij_offset = 0
+         CASE(2)
+            zmask      => umask(:,:,:)
+            zmask_xdif => tmask(:,:,:)
+            zmask_ydif => fmask(:,:,:)
+            pe_xdif    => e1t(:,:)
+            pe_ydif    => e2f(:,:)
+            ii_offset = 1
+            ij_offset = 0
+         CASE(3)
+            zmask      => vmask(:,:,:)
+            zmask_xdif => fmask(:,:,:)
+            zmask_ydif => tmask(:,:,:)
+            pe_xdif    => e1f(:,:)
+            pe_ydif    => e2t(:,:)
+            ii_offset = 0
+            ij_offset = 1
+         CASE DEFAULT ;   CALL ctl_stop( 'unrecognised value for igrd in bdy_orlanksi_2d' )
+      END SELECT
+      !
+      IF( PRESENT(lrim0) ) THEN
+         IF( lrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)   ! rim 0
+         ELSE               ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)    ! rim 1
+         END IF
+      ELSE                  ;   ibeg = 1                       ;   iend = idx%nblenrim(igrd)    ! both
+      END IF
+      !
+      DO jk = 1, jpk
+         !            
+         DO jb = ibeg, iend
+            ii  = idx%nbi(jb,igrd)
+            ij  = idx%nbj(jb,igrd) 
+            IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )   CYCLE
+            flagu = int( idx%flagu(jb,igrd) )
+            flagv = int( idx%flagv(jb,igrd) )
+            !
+            ! calculate positions of b-1 and b-2 points for this rim point
+            ! also (b-1,j-1) and (b-1,j+1) points
+            iibm1 = ii + flagu ; iibm2 = ii + 2*flagu 
+            ijbm1 = ij + flagv ; ijbm2 = ij + 2*flagv
+            !
+            iijm1 = ii - abs(flagv) ; iijp1 = ii + abs(flagv) 
+            ijjm1 = ij - abs(flagu) ; ijjp1 = ij + abs(flagu)
+            !
+            iibm1jm1 = ii + flagu - abs(flagv) ; iibm1jp1 = ii + flagu + abs(flagv) 
+            ijbm1jm1 = ij + flagv - abs(flagu) ; ijbm1jp1 = ij + flagv + abs(flagu) 
+            !
+            ! Calculate scale factors for calculation of spatial derivatives.        
+            zex1 = ( abs(iibm1-iibm2) * pe_xdif(iibm1   +ii_offset,ijbm1             )   &
+           &       + abs(ijbm1-ijbm2) * pe_ydif(iibm1             ,ijbm1+ij_offset   ) ) 
+            zex2 = ( abs(iibm1-iibm2) * pe_xdif(iibm2   +ii_offset,ijbm2             )   &
+           &       + abs(ijbm1-ijbm2) * pe_ydif(iibm2             ,ijbm2+ij_offset   ) ) 
+            zey1 = ( (iibm1-iibm1jm1) * pe_xdif(iibm1jm1+ii_offset,ijbm1jm1          )   & 
+           &      +  (ijbm1-ijbm1jm1) * pe_ydif(iibm1jm1          ,ijbm1jm1+ij_offset) ) 
+            zey2 = ( (iibm1jp1-iibm1) * pe_xdif(iibm1   +ii_offset,ijbm1             )   &
+           &      +  (ijbm1jp1-ijbm1) * pe_ydif(iibm1             ,ijbm1+ij_offset   ) ) 
+            ! make sure scale factors are nonzero
+            if( zey1 .lt. rsmall ) zey1 = zey2
+            if( zey2 .lt. rsmall ) zey2 = zey1
+            zex1 = max(zex1,rsmall); zex2 = max(zex2,rsmall); 
+            zey1 = max(zey1,rsmall); zey2 = max(zey2,rsmall); 
+            !
+            ! Calculate masks for calculation of spatial derivatives.        
+            zmask_x  = ( abs(iibm1-iibm2) * zmask_xdif(iibm2   +ii_offset,ijbm2             ,jk)   &
+           &           + abs(ijbm1-ijbm2) * zmask_ydif(iibm2             ,ijbm2   +ij_offset,jk) ) 
+            zmask_y1 = ( (iibm1-iibm1jm1) * zmask_xdif(iibm1jm1+ii_offset,ijbm1jm1          ,jk)   & 
+           &          +  (ijbm1-ijbm1jm1) * zmask_ydif(iibm1jm1          ,ijbm1jm1+ij_offset,jk) ) 
+            zmask_y2 = ( (iibm1jp1-iibm1) * zmask_xdif(iibm1   +ii_offset,ijbm1             ,jk)   &
+           &          +  (ijbm1jp1-ijbm1) * zmask_ydif(iibm1             ,ijbm1   +ij_offset,jk) ) 
+            !
+            ! Calculate normal (zrx) and tangential (zry) components of radiation velocities.
+            ! Mask derivatives to ensure correct land boundary conditions for each variable.
+            ! Centred derivative is calculated as average of "left" and "right" derivatives for 
+            ! this reason. 
+            zdt   =     phia(iibm1   ,ijbm1   ,jk) - phib(iibm1   ,ijbm1   ,jk)
+            zdx   = ( ( phia(iibm1   ,ijbm1   ,jk) - phia(iibm2   ,ijbm2   ,jk) ) / zex2 ) * zmask_x                  
+            zdy_1 = ( ( phib(iibm1   ,ijbm1   ,jk) - phib(iibm1jm1,ijbm1jm1,jk) ) / zey1 ) * zmask_y1  
+            zdy_2 = ( ( phib(iibm1jp1,ijbm1jp1,jk) - phib(iibm1   ,ijbm1   ,jk) ) / zey2 ) * zmask_y2      
+            zdy_centred = 0.5 * ( zdy_1 + zdy_2 )
+!!$            zdy_centred = phib(iibm1jp1,ijbm1jp1,jk) - phib(iibm1jm1,ijbm1jm1,jk)
+            ! upstream differencing for tangential derivatives
+            zsign_ups = sign( 1., zdt * zdy_centred )
+            zsign_ups = 0.5*( zsign_ups + abs(zsign_ups) )
+            zdy = zsign_ups * zdy_1 + (1. - zsign_ups) * zdy_2
+            znor2 = zdx * zdx + zdy * zdy
+            znor2 = max(znor2,zepsilon)
+            !
+            ! update boundary value:
+            zrx = zdt * zdx / ( zex1 * znor2 )
+!!$            zrx = min(zrx,2.0_wp)
+            zout = sign( 1., zrx )
+            zout = 0.5*( zout + abs(zout) )
+            zwgt = 2.*rdt*( (1.-zout) * idx%nbd(jb,igrd) + zout * idx%nbdout(jb,igrd) )
+            ! only apply radiation on outflow points 
+            if( ll_npo ) then     !! NPO version !!
+               phia(ii,ij,jk) = (1.-zout) * ( phib(ii,ij,jk) + zwgt * ( phi_ext(jb,jk) - phib(ii,ij,jk) ) ) &
+              &               + zout      * ( phib(ii,ij,jk) + zrx*phia(iibm1,ijbm1,jk)                     &
+              &                            + zwgt * ( phi_ext(jb,jk) - phib(ii,ij,jk) ) ) / ( 1. + zrx ) 
+            else                  !! full oblique radiation !!
+               zsign_ups = sign( 1., zdt * zdy )
+               zsign_ups = 0.5*( zsign_ups + abs(zsign_ups) )
+               zey = zsign_ups * zey1 + (1.-zsign_ups) * zey2 
+               zry = zdt * zdy / ( zey * znor2 ) 
+               phia(ii,ij,jk) = (1.-zout) * ( phib(ii,ij,jk) + zwgt * ( phi_ext(jb,jk) - phib(ii,ij,jk) ) )    &
+              &               + zout      * ( phib(ii,ij,jk) + zrx*phia(iibm1,ijbm1,jk)                        &
+              &                       - zsign_ups      * zry * ( phib(ii   ,ij   ,jk) - phib(iijm1,ijjm1,jk) ) &
+              &                       - (1.-zsign_ups) * zry * ( phib(iijp1,ijjp1,jk) - phib(ii   ,ij   ,jk) ) &
+              &                       + zwgt * ( phi_ext(jb,jk) - phib(ii,ij,jk) ) ) / ( 1. + zrx ) 
+            end if
+            phia(ii,ij,jk) = phia(ii,ij,jk) * zmask(ii,ij,jk)
+         END DO
+         !
+      END DO
+      !
+   END SUBROUTINE bdy_orlanski_3d
+
+   SUBROUTINE bdy_nmn( idx, igrd, phia, lrim0 )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_nmn  ***
+      !!                    
+      !! ** Purpose : Duplicate the value at open boundaries, zero gradient.
+      !! 
+      !!
+      !! ** Method  : - take the average of free ocean neighbours
+      !!
+      !!      ___   !   |_____|   !   ___|    !   __|x o   !   |_   _|     ! |      
+      !!   __|x     !      x      !     x o   !      o     !     |_|       ! |x o   
+      !!      o     !      o      !     o     !            !    o x o      ! |x_x_ 
+      !!                                                   !      o      
+      !!----------------------------------------------------------------------
+      INTEGER,                    INTENT(in   )  ::   igrd     ! grid index
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout)  ::   phia     ! model after 3D field (to be updated), must be masked
+      TYPE(OBC_INDEX),            INTENT(in   )  ::   idx      ! OBC indices
+      LOGICAL, OPTIONAL,          INTENT(in   )  ::   lrim0    ! indicate if rim 0 is treated
+      !! 
+      REAL(wp) ::   zweight
+      REAL(wp), POINTER, DIMENSION(:,:,:)      :: zmask         ! land/sea mask for field
+      INTEGER  ::   ib, ik   ! dummy loop indices
+      INTEGER  ::   ii, ij   ! 2D addresses
+      INTEGER  ::   ipkm1    ! size of phia third dimension minus 1
+      INTEGER  ::   ibeg, iend                          ! length of rim to be treated (rim 0 or rim 1 or both)
+      INTEGER  ::   ii1, ii2, ii3, ij1, ij2, ij3, itreat
+      !!----------------------------------------------------------------------
+      !
+      ipkm1 = MAX( SIZE(phia,3) - 1, 1 ) 
+      !
+      SELECT CASE(igrd)
+         CASE(1)   ;   zmask => tmask(:,:,:)
+         CASE(2)   ;   zmask => umask(:,:,:)
+         CASE(3)   ;   zmask => vmask(:,:,:)
+         CASE DEFAULT ;   CALL ctl_stop( 'unrecognised value for igrd in bdy_nmn' )
+      END SELECT
+      !
+      IF( PRESENT(lrim0) ) THEN
+         IF( lrim0 ) THEN   ;   ibeg = 1                       ;   iend = idx%nblenrim0(igrd)   ! rim 0
+         ELSE               ;   ibeg = idx%nblenrim0(igrd)+1   ;   iend = idx%nblenrim(igrd)    ! rim 1
+         END IF
+      ELSE                  ;   ibeg = 1                       ;   iend = idx%nblenrim(igrd)    ! both
+      END IF
+      !
+      DO ib = ibeg, iend
+         ii = idx%nbi(ib,igrd)
+         ij = idx%nbj(ib,igrd)
+         itreat = idx%ntreat(ib,igrd)
+         CALL find_neib( ii, ij, itreat, ii1, ij1, ii2, ij2, ii3, ij3 )   ! find free ocean neighbours
+         SELECT CASE( itreat )
+         CASE( 1:8 )
+            IF( ii1 < 1 .OR. ii1 > jpi .OR. ij1 < 1 .OR. ij1 > jpj )   CYCLE
+            DO ik = 1, ipkm1
+               IF( zmask(ii1,ij1,ik) /= 0. )   phia(ii,ij,ik) = phia(ii1,ij1,ik)  
+            END DO
+         CASE( 9:12 )
+            IF( ii1 < 1 .OR. ii1 > jpi .OR. ij1 < 1 .OR. ij1 > jpj )   CYCLE
+            IF( ii2 < 1 .OR. ii2 > jpi .OR. ij2 < 1 .OR. ij2 > jpj )   CYCLE
+            DO ik = 1, ipkm1
+               zweight = zmask(ii1,ij1,ik) + zmask(ii2,ij2,ik)
+               IF( zweight /= 0. )   phia(ii,ij,ik) = ( phia(ii1,ij1,ik) + phia(ii2,ij2,ik) ) / zweight
+            END DO
+         CASE( 13:16 )
+            IF( ii1 < 1 .OR. ii1 > jpi .OR. ij1 < 1 .OR. ij1 > jpj )   CYCLE
+            IF( ii2 < 1 .OR. ii2 > jpi .OR. ij2 < 1 .OR. ij2 > jpj )   CYCLE
+            IF( ii3 < 1 .OR. ii3 > jpi .OR. ij3 < 1 .OR. ij3 > jpj )   CYCLE
+            DO ik = 1, ipkm1
+               zweight = zmask(ii1,ij1,ik) + zmask(ii2,ij2,ik) + zmask(ii3,ij3,ik)
+               IF( zweight /= 0. )   phia(ii,ij,ik) = ( phia(ii1,ij1,ik) + phia(ii2,ij2,ik) + phia(ii3,ij3,ik) ) / zweight
+            END DO
+         END SELECT
+      END DO
+      !
+   END SUBROUTINE bdy_nmn
+
+   !!======================================================================
+END MODULE bdylib
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytides.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytides.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytides.F90	(revision 14097)
@@ -0,0 +1,567 @@
+MODULE bdytides
+   !!======================================================================
+   !!                       ***  MODULE  bdytides  ***
+   !! Ocean dynamics:   Tidal forcing at open boundaries
+   !!======================================================================
+   !! History :  2.0  !  2007-01  (D.Storkey)  Original code
+   !!            2.3  !  2008-01  (J.Holt)  Add date correction. Origins POLCOMS v6.3 2007
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.3  !  2010-09  (D.Storkey and E.O'Dea)  bug fixes
+   !!            3.4  !  2012-09  (G. Reffray and J. Chanut) New inputs + mods
+   !!            3.5  !  2013-07  (J. Chanut) Compliant with time splitting changes
+   !!----------------------------------------------------------------------
+   !!   bdytide_init  : read of namelist and initialisation of tidal harmonics data
+   !!   tide_update   : calculation of tidal forcing at each timestep
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE bdy_oce        ! ocean open boundary conditions
+   USE tideini        ! 
+   USE daymod         ! calendar
+   !
+   USE in_out_manager ! I/O units
+   USE iom            ! xIO server
+   USE fldread        !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdytide_init     ! routine called in bdy_init
+   PUBLIC   bdytide_update   ! routine called in bdy_dta
+   PUBLIC   bdy_dta_tides    ! routine called in dyn_spg_ts
+
+   TYPE, PUBLIC ::   TIDES_DATA     !: Storage for external tidal harmonics data
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   ssh0     !: Tidal constituents : SSH0   (read in file)
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   u0, v0   !: Tidal constituents : U0, V0 (read in file)
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   ssh      !: Tidal constituents : SSH    (after nodal cor.)
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   u , v    !: Tidal constituents : U , V  (after nodal cor.)
+   END TYPE TIDES_DATA
+
+!$AGRIF_DO_NOT_TREAT
+   TYPE(TIDES_DATA), PUBLIC, DIMENSION(jp_bdy), TARGET :: tides  !: External tidal harmonics data
+!$AGRIF_END_DO_NOT_TREAT
+   TYPE(OBC_DATA)  , PUBLIC, DIMENSION(jp_bdy) :: dta_bdy_s  !: bdy external data (slow component)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdytide_init
+      !!----------------------------------------------------------------------
+      !!                    ***  SUBROUTINE bdytide_init  ***
+      !!                     
+      !! ** Purpose : - Read in namelist for tides and initialise external
+      !!                tidal harmonics data
+      !!
+      !!----------------------------------------------------------------------
+      !! namelist variables
+      !!-------------------
+      CHARACTER(len=80)                         ::   filtide             ! Filename root for tidal input files
+      LOGICAL                                   ::   ln_bdytide_2ddta    ! If true, read 2d harmonic data
+      LOGICAL                                   ::   ln_bdytide_conj     ! If true, assume complex conjugate tidal data
+      !!
+      INTEGER                                   ::   ib_bdy, itide, ib   ! dummy loop indices
+      INTEGER                                   ::   ii, ij              ! dummy loop indices
+      INTEGER                                   ::   inum, igrd
+      INTEGER                                   ::   isz                 ! bdy data size
+      INTEGER                                   ::   ios                 ! Local integer output status for namelist read
+      CHARACTER(len=80)                         ::   clfile              ! full file name for tidal input file 
+      REAL(wp),ALLOCATABLE, DIMENSION(:,:,:)    ::   dta_read            ! work space to read in tidal harmonics data
+      REAL(wp),ALLOCATABLE, DIMENSION(:,:)      ::   ztr, zti            !  "     "    "   "   "   "        "      " 
+      !!
+      TYPE(TIDES_DATA), POINTER                 ::   td                  ! local short cut   
+      TYPE(  OBC_DATA), POINTER                 ::   dta                 ! local short cut
+      !!
+      NAMELIST/nambdy_tide/filtide, ln_bdytide_2ddta, ln_bdytide_conj
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'bdytide_init : initialization of tidal harmonic forcing at open boundaries'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+
+      REWIND(numnam_cfg)
+
+      DO ib_bdy = 1, nb_bdy
+         IF( nn_dyn2d_dta(ib_bdy) >= 2 ) THEN
+            !
+            td  => tides(ib_bdy)
+            dta => dta_bdy(ib_bdy)
+         
+            ! Namelist nambdy_tide : tidal harmonic forcing at open boundaries
+            filtide(:) = ''
+
+            REWIND( numnam_ref )
+            READ  ( numnam_ref, nambdy_tide, IOSTAT = ios, ERR = 901)
+901         IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy_tide in reference namelist' )
+            ! Don't REWIND here - may need to read more than one of these namelists. 
+            READ  ( numnam_cfg, nambdy_tide, IOSTAT = ios, ERR = 902 )
+902         IF( ios >  0 )   CALL ctl_nam ( ios , 'nambdy_tide in configuration namelist' )
+            IF(lwm) WRITE ( numond, nambdy_tide )
+            !                                               ! Parameter control and print
+            IF(lwp) WRITE(numout,*) '  '
+            IF(lwp) WRITE(numout,*) '          Namelist nambdy_tide : tidal harmonic forcing at open boundaries'
+            IF(lwp) WRITE(numout,*) '             read tidal data in 2d files: ', ln_bdytide_2ddta
+            IF(lwp) WRITE(numout,*) '             assume complex conjugate   : ', ln_bdytide_conj
+            IF(lwp) WRITE(numout,*) '             Number of tidal components to read: ', nb_harmo
+            IF(lwp) THEN 
+                    WRITE(numout,*) '             Tidal components: ' 
+               DO itide = 1, nb_harmo
+                  WRITE(numout,*)  '                 ', Wave(ntide(itide))%cname_tide 
+               END DO
+            ENDIF 
+            IF(lwp) WRITE(numout,*) ' '
+
+            ! Allocate space for tidal harmonics data - get size from BDY data arrays
+            ! Allocate also slow varying data in the case of time splitting:
+            ! Do it anyway because at this stage knowledge of free surface scheme is unknown
+            ! -----------------------------------------------------------------------
+            IF( ASSOCIATED(dta%ssh) ) THEN   ! we use bdy ssh on this mpi subdomain
+               isz = SIZE(dta%ssh)
+               ALLOCATE( td%ssh0( isz, nb_harmo, 2 ), td%ssh( isz, nb_harmo, 2 ), dta_bdy_s(ib_bdy)%ssh( isz ) )
+               dta_bdy_s(ib_bdy)%ssh(:) = 0._wp   ! needed?
+            ENDIF
+            IF( ASSOCIATED(dta%u2d) ) THEN   ! we use bdy u2d on this mpi subdomain
+               isz = SIZE(dta%u2d)
+               ALLOCATE( td%u0  ( isz, nb_harmo, 2 ), td%u  ( isz, nb_harmo, 2 ), dta_bdy_s(ib_bdy)%u2d( isz ) )
+               dta_bdy_s(ib_bdy)%u2d(:) = 0._wp   ! needed?
+            ENDIF
+            IF( ASSOCIATED(dta%v2d) ) THEN   ! we use bdy v2d on this mpi subdomain
+               isz = SIZE(dta%v2d)
+               ALLOCATE( td%v0  ( isz, nb_harmo, 2 ), td%v  ( isz, nb_harmo, 2 ), dta_bdy_s(ib_bdy)%v2d( isz ) )
+               dta_bdy_s(ib_bdy)%v2d(:) = 0._wp   ! needed?
+            ENDIF
+
+            ! fill td%ssh0, td%u0, td%v0
+            ! -----------------------------------------------------------------------
+            IF( ln_bdytide_2ddta ) THEN
+               !
+               ! It is assumed that each data file contains all complex harmonic amplitudes
+               ! given on the global domain (ie global, jpiglo x jpjglo)
+               !
+               ALLOCATE( zti(jpi,jpj), ztr(jpi,jpj) )
+               !
+               ! SSH fields
+               IF( ASSOCIATED(dta%ssh) ) THEN   ! we use bdy ssh on this mpi subdomain
+                  clfile = TRIM(filtide)//'_grid_T.nc'
+                  CALL iom_open( clfile , inum ) 
+                  igrd = 1                       ! Everything is at T-points here
+                  DO itide = 1, nb_harmo
+                     CALL iom_get( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_z1', ztr(:,:) )
+                     CALL iom_get( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_z2', zti(:,:) ) 
+                     DO ib = 1, SIZE(dta%ssh)
+                        ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+                        ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+                        td%ssh0(ib,itide,1) = ztr(ii,ij)
+                        td%ssh0(ib,itide,2) = zti(ii,ij)
+                     END DO
+                  END DO
+                  CALL iom_close( inum )
+               END IF
+               !
+               ! U fields
+               IF( ASSOCIATED(dta%u2d) ) THEN   ! we use bdy u2d on this mpi subdomain
+                  clfile = TRIM(filtide)//'_grid_U.nc'
+                  CALL iom_open( clfile , inum ) 
+                  igrd = 2                       ! Everything is at U-points here
+                  DO itide = 1, nb_harmo
+                     CALL iom_get  ( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_u1', ztr(:,:) )
+                     CALL iom_get  ( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_u2', zti(:,:) )
+                     DO ib = 1, SIZE(dta%u2d)
+                        ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+                        ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+                        td%u0(ib,itide,1) = ztr(ii,ij)
+                        td%u0(ib,itide,2) = zti(ii,ij)
+                     END DO
+                  END DO
+                  CALL iom_close( inum )
+               END IF
+               !
+               ! V fields
+               IF( ASSOCIATED(dta%v2d) ) THEN   ! we use bdy v2d on this mpi subdomain
+                  clfile = TRIM(filtide)//'_grid_V.nc'
+                  CALL iom_open( clfile , inum ) 
+                  igrd = 3                       ! Everything is at V-points here
+                  DO itide = 1, nb_harmo
+                     CALL iom_get  ( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_v1', ztr(:,:) )
+                     CALL iom_get  ( inum, jpdom_autoglo, TRIM(Wave(ntide(itide))%cname_tide)//'_v2', zti(:,:) )
+                     DO ib = 1, SIZE(dta%v2d)
+                        ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+                        ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+                        td%v0(ib,itide,1) = ztr(ii,ij)
+                        td%v0(ib,itide,2) = zti(ii,ij)
+                     END DO
+                  END DO
+                  CALL iom_close( inum )
+               END IF
+               !
+               DEALLOCATE( ztr, zti ) 
+               !
+            ELSE            
+               !
+               ! Read tidal data only on bdy segments
+               ! 
+               ALLOCATE( dta_read( MAXVAL( idx_bdy(ib_bdy)%nblen(:) ), 1, 1 ) )
+               !
+               ! Open files and read in tidal forcing data
+               ! -----------------------------------------
+
+               DO itide = 1, nb_harmo
+                  !                                                              ! SSH fields
+                  IF( ASSOCIATED(dta%ssh) ) THEN   ! we use bdy ssh on this mpi subdomain
+                     isz = SIZE(dta%ssh)
+                     clfile = TRIM(filtide)//TRIM(Wave(ntide(itide))%cname_tide)//'_grid_T.nc'
+                     CALL iom_open( clfile, inum )
+                     CALL fld_map( inum, 'z1', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,1) )
+                     td%ssh0(:,itide,1) = dta_read(1:isz,1,1)
+                     CALL fld_map( inum, 'z2', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,1) )
+                     td%ssh0(:,itide,2) = dta_read(1:isz,1,1)
+                     CALL iom_close( inum )
+                  ENDIF
+                  !                                                              ! U fields
+                  IF( ASSOCIATED(dta%u2d) ) THEN   ! we use bdy u2d on this mpi subdomain
+                     isz = SIZE(dta%u2d)
+                     clfile = TRIM(filtide)//TRIM(Wave(ntide(itide))%cname_tide)//'_grid_U.nc'
+                     CALL iom_open( clfile, inum )
+                     CALL fld_map( inum, 'u1', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,2) )
+                     td%u0(:,itide,1) = dta_read(1:isz,1,1)
+                     CALL fld_map( inum, 'u2', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,2) )
+                     td%u0(:,itide,2) = dta_read(1:isz,1,1)
+                     CALL iom_close( inum )
+                  ENDIF
+                  !                                                              ! V fields
+                  IF( ASSOCIATED(dta%v2d) ) THEN   ! we use bdy v2d on this mpi subdomain
+                     isz = SIZE(dta%v2d)
+                     clfile = TRIM(filtide)//TRIM(Wave(ntide(itide))%cname_tide)//'_grid_V.nc'
+                     CALL iom_open( clfile, inum )
+                     CALL fld_map( inum, 'v1', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,3) )
+                     td%v0(:,itide,1) = dta_read(1:isz,1,1)
+                     CALL fld_map( inum, 'v2', dta_read(1:isz,1:1,1:1) , 1, idx_bdy(ib_bdy)%nbmap(:,3) )
+                     td%v0(:,itide,2) = dta_read(1:isz,1,1)
+                     CALL iom_close( inum )
+                  ENDIF
+                  !
+               END DO ! end loop on tidal components
+               !
+               DEALLOCATE( dta_read )
+               !
+            ENDIF ! ln_bdytide_2ddta=.true.
+            !
+            IF( ln_bdytide_conj ) THEN    ! assume complex conjugate in data files
+               IF( ASSOCIATED(dta%ssh) )   td%ssh0(:,:,2) = - td%ssh0(:,:,2)
+               IF( ASSOCIATED(dta%u2d) )   td%u0  (:,:,2) = - td%u0  (:,:,2)
+               IF( ASSOCIATED(dta%v2d) )   td%v0  (:,:,2) = - td%v0  (:,:,2)
+            ENDIF
+            !
+         ENDIF ! nn_dyn2d_dta(ib_bdy) >= 2
+         !
+      END DO ! loop on ib_bdy
+      !
+   END SUBROUTINE bdytide_init
+
+
+   SUBROUTINE bdytide_update( kt, idx, dta, td, kit, kt_offset )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdytide_update  ***
+      !!                
+      !! ** Purpose : - Add tidal forcing to ssh, u2d and v2d OBC data arrays. 
+      !!                
+      !!----------------------------------------------------------------------
+      INTEGER          , INTENT(in   ) ::   kt          ! Main timestep counter
+      TYPE(OBC_INDEX)  , INTENT(in   ) ::   idx         ! OBC indices
+      TYPE(OBC_DATA)   , INTENT(inout) ::   dta         ! OBC external data
+      TYPE(TIDES_DATA) , INTENT(inout) ::   td          ! tidal harmonics data
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kit         ! Barotropic timestep counter (for timesplitting option)
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kt_offset   ! time offset in units of timesteps. NB. if kit
+      !                                                 ! is present then units = subcycle timesteps.
+      !                                                 ! kt_offset = 0  => get data at "now"    time level
+      !                                                 ! kt_offset = -1 => get data at "before" time level
+      !                                                 ! kt_offset = +1 => get data at "after"  time level
+      !                                                 ! etc.
+      !
+      INTEGER  ::   itide, ib             ! dummy loop indices
+      INTEGER  ::   time_add              ! time offset in units of timesteps
+      INTEGER  ::   isz                   ! bdy data size
+      REAL(wp) ::   z_arg, z_sarg, zflag, zramp   ! local scalars    
+      REAL(wp), DIMENSION(jpmax_harmo) :: z_sist, z_cost
+      !!----------------------------------------------------------------------
+      !
+      zflag=1
+      IF ( PRESENT(kit) ) THEN
+        IF ( kit /= 1 ) zflag=0
+      ENDIF
+      !
+      IF ( (nsec_day == NINT(0.5_wp * rdt) .OR. kt==nit000) .AND. zflag==1 ) THEN
+        !
+        kt_tide = kt - (nsec_day - 0.5_wp * rdt)/rdt
+        !
+        IF(lwp) THEN
+           WRITE(numout,*)
+           WRITE(numout,*) 'bdytide_update : (re)Initialization of the tidal bdy forcing at kt=',kt
+           WRITE(numout,*) '~~~~~~~~~~~~~~ '
+        ENDIF
+        !
+        CALL tide_init_elevation ( idx, td )
+        CALL tide_init_velocities( idx, td )
+        !
+      ENDIF 
+
+      time_add = 0
+      IF( PRESENT(kt_offset) ) THEN
+         time_add = kt_offset
+      ENDIF
+         
+      IF( PRESENT(kit) ) THEN  
+         z_arg = ((kt-kt_tide) * rdt + (kit+0.5_wp*(time_add-1)) * rdt / REAL(nn_baro,wp) )
+      ELSE                              
+         z_arg = ((kt-kt_tide)+time_add) * rdt
+      ENDIF
+
+      ! Linear ramp on tidal component at open boundaries 
+      zramp = 1._wp
+      IF (ln_tide_ramp) zramp = MIN(MAX( (z_arg + (kt_tide-nit000)*rdt)/(rdttideramp*rday),0._wp),1._wp)
+
+      DO itide = 1, nb_harmo
+         z_sarg = z_arg * omega_tide(itide)
+         z_cost(itide) = COS( z_sarg )
+         z_sist(itide) = SIN( z_sarg )
+      END DO
+
+      DO itide = 1, nb_harmo
+         ! SSH on tracer grid
+         IF( ASSOCIATED(dta%ssh) ) THEN   ! we use bdy ssh on this mpi subdomain
+           DO ib = 1, SIZE(dta%ssh)
+               dta%ssh(ib) = dta%ssh(ib) + zramp*(td%ssh(ib,itide,1)*z_cost(itide) + td%ssh(ib,itide,2)*z_sist(itide))
+            END DO
+         ENDIF
+         ! U grid
+         IF( ASSOCIATED(dta%u2d) ) THEN   ! we use bdy u2d on this mpi subdomain
+            DO ib = 1, SIZE(dta%u2d)
+               dta%u2d(ib) = dta%u2d(ib) + zramp*(td%u  (ib,itide,1)*z_cost(itide) + td%u  (ib,itide,2)*z_sist(itide))
+            END DO
+         ENDIF
+         ! V grid
+         IF( ASSOCIATED(dta%v2d) ) THEN   ! we use bdy v2d on this mpi subdomain
+            DO ib = 1, SIZE(dta%v2d) 
+               dta%v2d(ib) = dta%v2d(ib) + zramp*(td%v  (ib,itide,1)*z_cost(itide) + td%v  (ib,itide,2)*z_sist(itide))
+            END DO
+         ENDIF
+      END DO
+      !
+   END SUBROUTINE bdytide_update
+
+
+   SUBROUTINE bdy_dta_tides( kt, kit, kt_offset )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_dta_tides  ***
+      !!                
+      !! ** Purpose : - Add tidal forcing to ssh, u2d and v2d OBC data arrays. 
+      !!                
+      !!----------------------------------------------------------------------
+      INTEGER,           INTENT(in) ::   kt          ! Main timestep counter
+      INTEGER, OPTIONAL, INTENT(in) ::   kit         ! Barotropic timestep counter (for timesplitting option)
+      INTEGER, OPTIONAL, INTENT(in) ::   kt_offset   ! time offset in units of timesteps. NB. if kit
+      !                                              ! is present then units = subcycle timesteps.
+      !                                              ! kt_offset = 0  => get data at "now"    time level
+      !                                              ! kt_offset = -1 => get data at "before" time level
+      !                                              ! kt_offset = +1 => get data at "after"  time level
+      !                                              ! etc.
+      !
+      LOGICAL  ::   lk_first_btstp            ! =.TRUE. if time splitting and first barotropic step
+      INTEGER  ::   itide, ib_bdy, ib         ! loop indices
+      INTEGER  ::   time_add                  ! time offset in units of timesteps
+      REAL(wp) ::   z_arg, z_sarg, zramp, zoff, z_cost, z_sist      
+      !!----------------------------------------------------------------------
+      !
+      lk_first_btstp=.TRUE.
+      IF ( PRESENT(kit).AND.( kit /= 1 ) ) THEN ; lk_first_btstp=.FALSE. ; ENDIF
+
+      time_add = 0
+      IF( PRESENT(kt_offset) ) THEN
+         time_add = kt_offset
+      ENDIF
+      
+      ! Absolute time from model initialization:   
+      IF( PRESENT(kit) ) THEN  
+         z_arg = ( kt + (kit+time_add-1) / REAL(nn_baro,wp) ) * rdt
+      ELSE                              
+         z_arg = ( kt + time_add ) * rdt
+      ENDIF
+
+      ! Linear ramp on tidal component at open boundaries 
+      zramp = 1.
+      IF (ln_tide_ramp) zramp = MIN(MAX( (z_arg - nit000*rdt)/(rdttideramp*rday),0.),1.)
+
+      DO ib_bdy = 1,nb_bdy
+         !
+         IF( nn_dyn2d_dta(ib_bdy) >= 2 ) THEN
+            !
+            ! We refresh nodal factors every day below
+            ! This should be done somewhere else
+            IF ( ( nsec_day == NINT(0.5_wp * rdt) .OR. kt==nit000 ) .AND. lk_first_btstp ) THEN
+               !
+               kt_tide = kt - (nsec_day - 0.5_wp * rdt)/rdt
+               !
+               IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'bdy_tide_dta : Refresh nodal factors for tidal open bdy data at kt=',kt
+               WRITE(numout,*) '~~~~~~~~~~~~~~ '
+               ENDIF
+               !
+               CALL tide_init_elevation ( idx=idx_bdy(ib_bdy), td=tides(ib_bdy) )
+               CALL tide_init_velocities( idx=idx_bdy(ib_bdy), td=tides(ib_bdy) )
+               !
+            ENDIF
+            zoff = -kt_tide * rdt ! time offset relative to nodal factor computation time
+            !
+            ! If time splitting, initialize arrays from slow varying open boundary data:
+            IF ( PRESENT(kit) ) THEN           
+               IF ( ASSOCIATED(dta_bdy(ib_bdy)%ssh) ) dta_bdy(ib_bdy)%ssh(:) = dta_bdy_s(ib_bdy)%ssh(:)
+               IF ( ASSOCIATED(dta_bdy(ib_bdy)%u2d) ) dta_bdy(ib_bdy)%u2d(:) = dta_bdy_s(ib_bdy)%u2d(:)
+               IF ( ASSOCIATED(dta_bdy(ib_bdy)%v2d) ) dta_bdy(ib_bdy)%v2d(:) = dta_bdy_s(ib_bdy)%v2d(:)
+            ENDIF
+            !
+            ! Update open boundary data arrays:
+            DO itide = 1, nb_harmo
+               !
+               z_sarg = (z_arg + zoff) * omega_tide(itide)
+               z_cost = zramp * COS( z_sarg )
+               z_sist = zramp * SIN( z_sarg )
+               !
+               IF ( ASSOCIATED(dta_bdy(ib_bdy)%ssh) ) THEN   ! SSH on tracer grid
+                  DO ib = 1, SIZE(dta_bdy(ib_bdy)%ssh)
+                     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 ( ASSOCIATED(dta_bdy(ib_bdy)%u2d) ) THEN  ! U grid
+                  DO ib = 1, SIZE(dta_bdy(ib_bdy)%u2d)
+                     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 ( ASSOCIATED(dta_bdy(ib_bdy)%v2d) ) THEN   ! V grid
+                  DO ib = 1, SIZE(dta_bdy(ib_bdy)%v2d)
+                     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
+      !
+   END SUBROUTINE bdy_dta_tides
+
+
+   SUBROUTINE tide_init_elevation( idx, td )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tide_init_elevation  ***
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX) , INTENT(in   ) ::   idx   ! OBC indices
+      TYPE(TIDES_DATA), INTENT(inout) ::   td    ! tidal harmonics data
+      !
+      INTEGER ::   itide, isz, ib       ! dummy loop indices
+      REAL(wp),ALLOCATABLE, DIMENSION(:) ::   mod_tide, phi_tide
+      !!----------------------------------------------------------------------
+      !
+      IF( ASSOCIATED(td%ssh0) ) THEN   ! SSH on tracer grid.
+         !
+         isz = SIZE( td%ssh0, dim = 1 )
+         ALLOCATE( mod_tide(isz), phi_tide(isz) )
+         !
+         DO itide = 1, nb_harmo
+            DO ib = 1, isz
+               mod_tide(ib)=SQRT( td%ssh0(ib,itide,1)*td%ssh0(ib,itide,1) + td%ssh0(ib,itide,2)*td%ssh0(ib,itide,2) )
+               phi_tide(ib)=ATAN2(-td%ssh0(ib,itide,2),td%ssh0(ib,itide,1))
+            END DO
+            DO ib = 1, isz
+               mod_tide(ib)=mod_tide(ib)*ftide(itide)
+               phi_tide(ib)=phi_tide(ib)+v0tide(itide)+utide(itide)
+            END DO
+            DO ib = 1, isz
+               td%ssh(ib,itide,1)= mod_tide(ib)*COS(phi_tide(ib))
+               td%ssh(ib,itide,2)=-mod_tide(ib)*SIN(phi_tide(ib))
+            END DO
+         END DO
+         !
+         DEALLOCATE( mod_tide, phi_tide )
+         !
+      ENDIF
+      !
+   END SUBROUTINE tide_init_elevation
+
+
+   SUBROUTINE tide_init_velocities( idx, td )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tide_init_elevation  ***
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX) , INTENT(in   ) ::   idx   ! OBC indices
+      TYPE(TIDES_DATA), INTENT(inout) ::   td    ! tidal harmonics data
+      !
+      INTEGER ::   itide, isz, ib        ! dummy loop indices
+      REAL(wp),ALLOCATABLE, DIMENSION(:) ::   mod_tide, phi_tide
+      !!----------------------------------------------------------------------
+      !
+      IF( ASSOCIATED(td%u0) ) THEN   ! U grid. we use bdy u2d on this mpi subdomain
+         !
+         isz = SIZE( td%u0, dim = 1 )
+         ALLOCATE( mod_tide(isz), phi_tide(isz) )
+         !
+         DO itide = 1, nb_harmo
+            DO ib = 1, isz
+               mod_tide(ib)=SQRT( td%u0(ib,itide,1)*td%u0(ib,itide,1) + td%u0(ib,itide,2)*td%u0(ib,itide,2) )
+               phi_tide(ib)=ATAN2(-td%u0(ib,itide,2),td%u0(ib,itide,1))
+            END DO
+            DO ib = 1, isz
+               mod_tide(ib)=mod_tide(ib)*ftide(itide)
+               phi_tide(ib)=phi_tide(ib)+v0tide(itide)+utide(itide)
+            END DO
+            DO ib = 1, isz
+               td%u(ib,itide,1)= mod_tide(ib)*COS(phi_tide(ib))
+               td%u(ib,itide,2)=-mod_tide(ib)*SIN(phi_tide(ib))
+            END DO
+         END DO
+         !
+         DEALLOCATE( mod_tide, phi_tide )
+         !
+      ENDIF
+      !
+      IF( ASSOCIATED(td%v0) ) THEN   ! V grid. we use bdy u2d on this mpi subdomain
+         !
+         isz = SIZE( td%v0, dim = 1 )
+         ALLOCATE( mod_tide(isz), phi_tide(isz) )
+         !
+         DO itide = 1, nb_harmo
+            DO ib = 1, isz
+               mod_tide(ib)=SQRT( td%v0(ib,itide,1)*td%v0(ib,itide,1) + td%v0(ib,itide,2)*td%v0(ib,itide,2) )
+               phi_tide(ib)=ATAN2(-td%v0(ib,itide,2),td%v0(ib,itide,1))
+            END DO
+            DO ib = 1, isz
+               mod_tide(ib)=mod_tide(ib)*ftide(itide)
+               phi_tide(ib)=phi_tide(ib)+v0tide(itide)+utide(itide)
+            END DO
+            DO ib = 1, isz
+               td%v(ib,itide,1)= mod_tide(ib)*COS(phi_tide(ib))
+               td%v(ib,itide,2)=-mod_tide(ib)*SIN(phi_tide(ib))
+            END DO
+         END DO
+         !
+         DEALLOCATE( mod_tide, phi_tide )
+         !
+      ENDIF
+      !
+   END SUBROUTINE tide_init_velocities
+
+   !!======================================================================
+END MODULE bdytides
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytra.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytra.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdytra.F90	(revision 14097)
@@ -0,0 +1,181 @@
+MODULE bdytra
+   !!======================================================================
+   !!                       ***  MODULE  bdytra  ***
+   !! Ocean tracers:   Apply boundary conditions for tracers
+   !!======================================================================
+   !! History :  1.0  !  2005-01  (J. Chanut, A. Sellar)  Original code
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            3.5  !  2012     (S. Mocavero, I. Epicoco) Optimization of BDY communications
+   !!            4.0  !  2016     (T. Lovato) Generalize OBC structure
+   !!----------------------------------------------------------------------
+   !!   bdy_tra       : Apply open boundary conditions & damping to T and S
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables 
+   USE bdy_oce        ! ocean open boundary conditions
+   USE bdylib         ! for orlanski library routines
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp, ONLY: ctl_stop
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   ! Local structure to rearrange tracers data
+   TYPE, PUBLIC ::   ztrabdy
+      REAL(wp), POINTER, DIMENSION(:,:) ::  tra
+   END TYPE
+
+   PUBLIC   bdy_tra      ! called in tranxt.F90 
+   PUBLIC   bdy_tra_dmp  ! called in step.F90 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_tra( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE bdy_tra  ***
+      !!
+      !! ** Purpose : - Apply open boundary conditions for temperature and salinity
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! Main time step counter
+      !
+      INTEGER                        :: ib_bdy, jn, igrd, ir   ! Loop indeces
+      TYPE(ztrabdy), DIMENSION(jpts) :: zdta                   ! Temporary data structure
+      LOGICAL                        :: llrim0                 ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4)          :: llsend1, llrecv1       ! indicate how communications are to be carried out
+      !!----------------------------------------------------------------------
+      igrd = 1 
+      llsend1(:) = .false.  ;   llrecv1(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            !
+            zdta(1)%tra => dta_bdy(ib_bdy)%tem
+            zdta(2)%tra => dta_bdy(ib_bdy)%sal
+            !
+            DO jn = 1, jpts
+               !
+               SELECT CASE( TRIM(cn_tra(ib_bdy)) )
+               CASE('none'        )   ;   CYCLE
+               CASE('frs'         )   ! treat the whole boundary at once
+                  IF( ir == 0 ) CALL bdy_frs ( idx_bdy(ib_bdy),                tsa(:,:,:,jn), zdta(jn)%tra )
+               CASE('specified'   )   ! treat the whole rim      at once
+                  IF( ir == 0 ) CALL bdy_spe ( idx_bdy(ib_bdy),                tsa(:,:,:,jn), zdta(jn)%tra )
+               CASE('neumann'     )   ;   CALL bdy_nmn ( idx_bdy(ib_bdy), igrd         , tsa(:,:,:,jn), llrim0 )   ! tsa masked
+               CASE('orlanski'    )   ;   CALL bdy_orl ( idx_bdy(ib_bdy), tsb(:,:,:,jn), tsa(:,:,:,jn), &
+                    & zdta(jn)%tra, llrim0, ll_npo=.false. )
+               CASE('orlanski_npo')   ;   CALL bdy_orl ( idx_bdy(ib_bdy), tsb(:,:,:,jn), tsa(:,:,:,jn), &
+                    & zdta(jn)%tra, llrim0, ll_npo=.true.  )
+               CASE('runoff'      )   ;   CALL bdy_rnf ( idx_bdy(ib_bdy),                tsa(:,:,:,jn), jn, llrim0 )
+               CASE DEFAULT           ;   CALL ctl_stop( 'bdy_tra : unrecognised option for open boundaries for T and S' )
+               END SELECT
+               ! 
+            END DO
+         END DO
+         !
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend1(:) = .false.   ;   llrecv1(:) = .false.   ;   END IF
+         DO ib_bdy=1, nb_bdy
+            SELECT CASE( TRIM(cn_tra(ib_bdy)) )
+            CASE('neumann','runoff')
+               llsend1(:) = llsend1(:) .OR. lsend_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+               llrecv1(:) = llrecv1(:) .OR. lrecv_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+            CASE('orlanski', 'orlanski_npo')
+               llsend1(:) = llsend1(:) .OR. lsend_bdy(ib_bdy,1,:,ir)   ! possibly every direction, T points
+               llrecv1(:) = llrecv1(:) .OR. lrecv_bdy(ib_bdy,1,:,ir)   ! possibly every direction, T points
+            END SELECT
+         END DO
+         IF( ANY(llsend1) .OR. ANY(llrecv1) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'bdytra', tsa, 'T',  1., kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+         END IF
+         !
+      END DO   ! ir
+      !
+   END SUBROUTINE bdy_tra
+
+
+   SUBROUTINE bdy_rnf( idx, pta, jpa, llrim0 )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_rnf  ***
+      !!                    
+      !! ** Purpose : Specialized routine to apply TRA runoff values at OBs:
+      !!                  - duplicate the neighbour value for the temperature
+      !!                  - specified to 0.1 PSU for the salinity
+      !! 
+      !!----------------------------------------------------------------------
+      TYPE(OBC_INDEX),                     INTENT(in) ::   idx      ! OBC indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pta      ! tracer trend
+      INTEGER,                             INTENT(in) ::   jpa      ! TRA index
+      LOGICAL,                             INTENT(in) ::   llrim0   ! indicate if rim 0 is treated
+      !
+      INTEGER  ::   ib, ii, ij, igrd   ! dummy loop indices
+      INTEGER  ::   ik, ip, jp ! 2D addresses
+      !!----------------------------------------------------------------------
+      !
+      igrd = 1                       ! Everything is at T-points here
+      IF(      jpa == jp_tem ) THEN
+         CALL bdy_nmn( idx, igrd, pta, llrim0 )
+      ELSE IF( jpa == jp_sal ) THEN
+         IF( .NOT. llrim0 )   RETURN
+         DO ib = 1, idx%nblenrim(igrd)   ! if llrim0 then treat the whole rim
+            ii = idx%nbi(ib,igrd)
+            ij = idx%nbj(ib,igrd)
+            pta(ii,ij,1:jpkm1) = 0.1 * tmask(ii,ij,1:jpkm1)
+         END DO
+      END IF
+      !
+   END SUBROUTINE bdy_rnf
+
+
+   SUBROUTINE bdy_tra_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE bdy_tra_dmp  ***
+      !!                    
+      !! ** Purpose : Apply damping for tracers at open boundaries.
+      !! 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   !
+      !
+      REAL(wp) ::   zwgt           ! boundary weight
+      REAL(wp) ::   zta, zsa, ztime
+      INTEGER  ::   ib, ik, igrd   ! dummy loop indices
+      INTEGER  ::   ii, ij         ! 2D addresses
+      INTEGER  ::   ib_bdy         ! Loop index
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('bdy_tra_dmp')
+      !
+      DO ib_bdy = 1, nb_bdy
+         IF( ln_tra_dmp(ib_bdy) ) THEN
+            igrd = 1                       ! Everything is at T-points here
+            DO ib = 1, idx_bdy(ib_bdy)%nblen(igrd)
+               ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+               ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+               zwgt = idx_bdy(ib_bdy)%nbd(ib,igrd)
+               DO ik = 1, jpkm1
+                  zta = zwgt * ( dta_bdy(ib_bdy)%tem(ib,ik) - tsb(ii,ij,ik,jp_tem) ) * tmask(ii,ij,ik)
+                  zsa = zwgt * ( dta_bdy(ib_bdy)%sal(ib,ik) - tsb(ii,ij,ik,jp_sal) ) * tmask(ii,ij,ik)
+                  tsa(ii,ij,ik,jp_tem) = tsa(ii,ij,ik,jp_tem) + zta
+                  tsa(ii,ij,ik,jp_sal) = tsa(ii,ij,ik,jp_sal) + zsa
+               END DO
+            END DO
+         ENDIF
+      END DO
+      !
+      IF( ln_timing )   CALL timing_stop('bdy_tra_dmp')
+      !
+   END SUBROUTINE bdy_tra_dmp
+ 
+   !!======================================================================
+END MODULE bdytra
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyvol.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyvol.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/BDY/bdyvol.F90	(revision 14097)
@@ -0,0 +1,229 @@
+MODULE bdyvol
+   !!======================================================================
+   !!                       ***  MODULE  bdyvol  ***
+   !! Ocean dynamic :  Volume constraint when unstructured boundary 
+   !!                  and filtered free surface are used
+   !!======================================================================
+   !! History :  1.0  !  2005-01  (J. Chanut, A. Sellar)  Original code
+   !!             -   !  2006-01  (J. Chanut) Bug correction
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            4.0  !  2019-01  (P. Mathiot) adapted to time splitting     
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers 
+   USE bdy_oce        ! ocean open boundary conditions
+   USE sbc_oce        ! ocean surface boundary conditions
+   USE dom_oce        ! ocean space and time domain 
+   USE phycst         ! physical constants
+   USE sbcisf         ! ice shelf
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! for mppsum
+   USE lib_fortran    ! Fortran routines library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   bdy_vol2d    ! called by dynspg_ts
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE bdy_vol2d( kt, kc, pua2d, pva2d, phu, phv )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE bdyvol  ***
+      !!
+      !! ** Purpose :   This routine controls the volume of the system. 
+      !!      A correction velocity is calculated to correct the total transport 
+      !!      through the unstructured OBC. 
+      !!
+      !! ** Method  :   The correction velocity (zubtpecor here) is defined calculating
+      !!      the total transport through all open boundaries (trans_bdy) minus
+      !!      the cumulate E-P flux (z_cflxemp) divided by the total lateral 
+      !!      surface (bdysurftot) of the unstructured boundary. 
+      !!         zubtpecor = [trans_bdy - z_cflxemp ]*(1./bdysurftot)
+      !!      with z_cflxemp => sum of (Evaporation minus Precipitation)
+      !!                       over all the domain in m3/s at each time step.
+      !!      z_cflxemp < 0 when precipitation dominate
+      !!      z_cflxemp > 0 when evaporation dominate
+      !!
+      !!      There are 2 options (user's desiderata): 
+      !!         1/ The volume changes according to E-P, this is the default
+      !!            option. In this case the cumulate E-P flux are setting to
+      !!            zero (z_cflxemp=0) to calculate the correction velocity. So
+      !!            it will only balance the flux through open boundaries.
+      !!            (set nn_volctl to 0 in tne namelist for this option)
+      !!         2/ The volume is constant even with E-P flux. In this case
+      !!            the correction velocity must balance both the flux 
+      !!            through open boundaries and the ones through the free
+      !!            surface. 
+      !!            (set nn_volctl to 1 in tne namelist for this option)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, kc   ! ocean time-step index, cycle time-step
+      !
+      INTEGER  ::   ji, jj, jk, jb, jgrd
+      INTEGER  ::   ib_bdy, ii, ij
+      REAL(wp) ::   zubtpecor, ztranst
+      REAL(wp), SAVE :: z_cflxemp                                  ! cumulated emp flux
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: pua2d, pva2d  ! Barotropic velocities
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: phu, phv         ! Ocean depth at U- and V-points
+      TYPE(OBC_INDEX), POINTER :: idx
+      !!-----------------------------------------------------------------------------
+      !
+      ! Calculate the cumulate surface Flux z_cflxemp (m3/s) over all the domain
+      ! -----------------------------------------------------------------------
+      IF ( kc == 1 ) z_cflxemp = glob_sum( 'bdyvol', ( emp(:,:) - rnf(:,:) + fwfisf(:,:) ) * bdytmask(:,:) * e1e2t(:,:)  ) / rau0
+
+      ! Compute bdy surface each cycle if non linear free surface
+      ! ---------------------------------------------------------
+      IF ( .NOT. ln_linssh ) THEN
+         ! compute area each time step
+         bdysurftot = bdy_segs_surf( phu, phv )
+      ELSE
+         ! compute area only the first time
+         IF ( ( kt == nit000 ) .AND. ( kc == 1 ) ) bdysurftot = bdy_segs_surf( phu, phv )
+      END IF
+
+      ! Transport through the unstructured open boundary
+      ! ------------------------------------------------
+      zubtpecor = 0._wp
+      DO ib_bdy = 1, nb_bdy
+         idx => idx_bdy(ib_bdy)
+         !
+         jgrd = 2                               ! cumulate u component contribution first 
+         DO jb = 1, idx%nblenrim(jgrd)
+            ii = idx%nbi(jb,jgrd)
+            ij = idx%nbj(jb,jgrd)
+            IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE   ! sum : else halo couted twice
+            zubtpecor = zubtpecor + idx%flagu(jb,jgrd) * pua2d(ii,ij) * e2u(ii,ij) * phu(ii,ij) * tmask_i(ii,ij) * tmask_i(ii+1,ij)
+         END DO
+         jgrd = 3                               ! then add v component contribution
+         DO jb = 1, idx%nblenrim(jgrd)
+            ii = idx%nbi(jb,jgrd)
+            ij = idx%nbj(jb,jgrd)
+            IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE   ! sum : else halo couted twice
+            zubtpecor = zubtpecor + idx%flagv(jb,jgrd) * pva2d(ii,ij) * e1v(ii,ij) * phv(ii,ij) * tmask_i(ii,ij) * tmask_i(ii,ij+1)
+         END DO
+         !
+      END DO
+      IF( lk_mpp )   CALL mpp_sum( 'bdyvol', zubtpecor )   ! sum over the global domain
+
+      ! The normal velocity correction
+      ! ------------------------------
+      IF( nn_volctl==1 ) THEN   ;   zubtpecor = ( zubtpecor - z_cflxemp ) / bdysurftot  ! maybe should be apply only once at the end
+      ELSE                      ;   zubtpecor =   zubtpecor               / bdysurftot
+      END IF
+
+      ! Correction of the total velocity on the unstructured boundary to respect the mass flux conservation
+      ! -------------------------------------------------------------
+      DO ib_bdy = 1, nb_bdy
+         idx => idx_bdy(ib_bdy)
+         !
+         jgrd = 2                               ! correct u component
+         DO jb = 1, idx%nblenrim(jgrd)
+               ii = idx%nbi(jb,jgrd)
+               ij = idx%nbj(jb,jgrd)
+               !IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE   ! to remove ?
+               pua2d(ii,ij) = pua2d(ii,ij) - idx%flagu(jb,jgrd) * zubtpecor * tmask_i(ii,ij) * tmask_i(ii+1,ij)
+         END DO
+         jgrd = 3                              ! correct v component
+         DO jb = 1, idx%nblenrim(jgrd)
+               ii = idx%nbi(jb,jgrd)
+               ij = idx%nbj(jb,jgrd)
+               !IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE   ! to remove ?
+               pva2d(ii,ij) = pva2d(ii,ij) - idx%flagv(jb,jgrd) * zubtpecor * tmask_i(ii,ij) * tmask_i(ii,ij+1)
+         END DO
+         !
+      END DO
+      ! 
+      ! Check the cumulated transport through unstructured OBC once barotropic velocities corrected
+      ! ------------------------------------------------------
+      IF( MOD( kt, MAX(nn_write,1) ) == 0 .AND. ( kc == 1 ) ) THEN
+         !
+         ! compute residual transport across boundary
+         ztranst = 0._wp
+         DO ib_bdy = 1, nb_bdy
+            idx => idx_bdy(ib_bdy)
+            !
+            jgrd = 2                               ! correct u component
+            DO jb = 1, idx%nblenrim(jgrd)
+                  ii = idx%nbi(jb,jgrd)
+                  ij = idx%nbj(jb,jgrd)
+                  IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE
+                  ztranst = ztranst + idx%flagu(jb,jgrd) * pua2d(ii,ij) * e2u(ii,ij) * phu(ii,ij) * tmask_i(ii,ij) * tmask_i(ii+1,ij)
+            END DO
+            jgrd = 3                              ! correct v component
+            DO jb = 1, idx%nblenrim(jgrd)
+                  ii = idx%nbi(jb,jgrd)
+                  ij = idx%nbj(jb,jgrd)
+                  IF( ii == 1 .OR. ii == jpi .OR. ij == 1 .OR. ij == jpj )  CYCLE
+                  ztranst = ztranst + idx%flagv(jb,jgrd) * pva2d(ii,ij) * e1v(ii,ij) * phv(ii,ij) * tmask_i(ii,ij) * tmask_i(ii,ij+1)
+            END DO
+            !
+         END DO
+         IF( lk_mpp )   CALL mpp_sum('bdyvol', ztranst )   ! sum over the global domain
+
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*)'bdy_vol : time step :', kt
+         IF(lwp) WRITE(numout,*)'~~~~~~~ '
+         IF(lwp) WRITE(numout,*)'          cumulate flux EMP             =', z_cflxemp  , ' (m3/s)'
+         IF(lwp) WRITE(numout,*)'          total lateral surface of OBC  =', bdysurftot, '(m2)'
+         IF(lwp) WRITE(numout,*)'          correction velocity zubtpecor =', zubtpecor , '(m/s)'
+         IF(lwp) WRITE(numout,*)'          cumulated transport ztranst   =', ztranst   , '(m3/s)'
+      END IF 
+      !
+   END SUBROUTINE bdy_vol2d
+   !
+   REAL(wp) FUNCTION bdy_segs_surf(phu, phv)
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE bdy_ctl_seg  ***
+      !!
+      !! ** Purpose :   Compute total lateral surface for volume correction
+      !!
+      !!----------------------------------------------------------------------
+
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: phu, phv ! water column thickness at U and V points
+      INTEGER            ::  igrd, ib_bdy, ib                ! loop indexes
+      INTEGER , POINTER  ::  nbi, nbj                        ! short cuts
+      REAL(wp), POINTER  ::  zflagu, zflagv                  !    -   -
+
+      ! Compute total lateral surface for volume correction:
+      ! ----------------------------------------------------
+      bdy_segs_surf = 0._wp
+      igrd = 2      ! Lateral surface at U-points
+      DO ib_bdy = 1, nb_bdy
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)
+            nbi => idx_bdy(ib_bdy)%nbi(ib,igrd)
+            nbj => idx_bdy(ib_bdy)%nbj(ib,igrd)
+            IF( nbi == 1 .OR. nbi == jpi .OR. nbj == 1 .OR. nbj == jpj )  CYCLE
+            zflagu => idx_bdy(ib_bdy)%flagu(ib,igrd)
+            bdy_segs_surf = bdy_segs_surf + phu(nbi, nbj)                              &
+               &                            * e2u(nbi, nbj) * ABS( zflagu )            &
+               &                            * tmask_i(nbi, nbj) * tmask_i(nbi+1, nbj)
+         END DO
+      END DO
+
+      igrd=3 ! Add lateral surface at V-points
+      DO ib_bdy = 1, nb_bdy
+         DO ib = 1, idx_bdy(ib_bdy)%nblenrim(igrd)
+            nbi => idx_bdy(ib_bdy)%nbi(ib,igrd)
+            nbj => idx_bdy(ib_bdy)%nbj(ib,igrd)
+            IF( nbi == 1 .OR. nbi == jpi .OR. nbj == 1 .OR. nbj == jpj )  CYCLE
+            zflagv => idx_bdy(ib_bdy)%flagv(ib,igrd)
+            bdy_segs_surf = bdy_segs_surf + phv(nbi, nbj)                              &
+               &                            * e1v(nbi, nbj) * ABS( zflagv )            &
+               &                            * tmask_i(nbi, nbj) * tmask_i(nbi, nbj+1)
+         END DO
+      END DO
+      !
+      ! redirect the time to bdyvol as this variable is only used by bdyvol
+      IF( lk_mpp )   CALL mpp_sum( 'bdyvol', bdy_segs_surf ) ! sum over the global domain
+      !
+   END FUNCTION bdy_segs_surf
+   !!======================================================================
+END MODULE bdyvol
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/c1d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/c1d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/c1d.F90	(revision 14097)
@@ -0,0 +1,87 @@
+MODULE c1d
+   !!======================================================================
+   !!                     ***  MODULE  c1d  ***
+   !! Ocean domain  :  1D configuration
+   !!=====================================================================
+   !! History :  2.0  !  2004-09 (C. Ethe)     Original code
+   !!            3.0  !  2008-04 (G. Madec)    adaptation to SBC
+   !!            3.5  !  2013-10 (D. Calvert)  add namelist
+   !!----------------------------------------------------------------------
+#if defined key_c1d
+   !!----------------------------------------------------------------------
+   !!   'key_c1d'                                   1D column configuration
+   !!----------------------------------------------------------------------
+   !!   c1d_init      : read in the C1D namelist
+   !!----------------------------------------------------------------------
+   USE par_kind       ! kind parameters
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   c1d_init   ! called by nemogcm.F90
+
+   LOGICAL , PUBLIC, PARAMETER ::  lk_c1d = .TRUE.   ! 1D config. flag
+
+   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
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+CONTAINS
+
+   SUBROUTINE c1d_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE c1d_init  ***
+      !! 
+      !! ** Purpose :   Initialization of C1D options
+      !!
+      !! ** Method  :   Read namelist namc1d 
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namc1d/ rn_lat1d, rn_lon1d , ln_c1d_locpt
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namc1d in reference namelist : Tracer advection scheme
+      READ  ( numnam_ref, namc1d, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc1d in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namtra_adv in configuration namelist : Tracer advection scheme
+      READ  ( numnam_cfg, namc1d, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc1d in configuration namelist' )
+      IF(lwm) WRITE ( numond, namc1d )
+      !
+      IF(lwp) THEN                    ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'c1d_init : Initialize 1D model configuration options'
+         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 localization in a grid   ln_c1d_locpt = ', ln_c1d_locpt
+      ENDIF
+      !
+   END SUBROUTINE c1d_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module :                           No use of 1D configuration
+   !!----------------------------------------------------------------------
+   USE par_kind         ! kind parameters
+   LOGICAL, PUBLIC, PARAMETER ::   lk_c1d = .FALSE.   !: 1D config. flag de-activated
+   REAL(wp)                   ::   rn_lat1d, rn_lon1d
+   LOGICAL , PUBLIC           ::   ln_c1d_locpt = .FALSE. 
+CONTAINS
+   SUBROUTINE c1d_init               ! Dummy routine
+   END SUBROUTINE c1d_init
+#endif
+
+   !!======================================================================
+END MODULE c1d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dtauvd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dtauvd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dtauvd.F90	(revision 14097)
@@ -0,0 +1,225 @@
+MODULE dtauvd
+   !!======================================================================
+   !!                     ***  MODULE  dtauvd  ***
+   !! Ocean data  :  read ocean U & V current data from gridded data
+   !!======================================================================
+   !! History :  3.5  ! 2013-08  (D. Calvert)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dta_uvd_init  : read namelist and allocate data structures
+   !!   dta_uvd       : read and time-interpolate ocean U & V current data
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain
+   !
+   USE in_out_manager ! I/O manager
+   USE fldread        ! read input fields
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dta_uvd_init   ! called by nemogcm.F90
+   PUBLIC   dta_uvd        ! called by istate.F90 and dyndmp.90
+
+   LOGICAL , PUBLIC ::   ln_uvd_init     ! Flag to initialise with U & V current data
+   LOGICAL , PUBLIC ::   ln_uvd_dyndmp   ! Flag for Newtonian damping toward U & V current data
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_uvd   ! structure for input U & V current (file information and data)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dta_uvd_init( ld_dyndmp )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dta_uvd_init  ***
+      !!                    
+      !! ** Purpose :   initialization of U & V current input data 
+      !! 
+      !! ** Method  : - read namc1d_uvd namelist
+      !!              - allocate U & V current data structure
+      !!              - fld_fill data structure with namelist information
+      !!----------------------------------------------------------------------
+      LOGICAL, INTENT(in), OPTIONAL ::   ld_dyndmp   ! force the initialization when dyndmp is used
+      !
+      INTEGER ::   ios, ierr0, ierr1, ierr2, ierr3     ! local integers
+      CHARACTER(len=100)        ::   cn_dir            ! Root directory for location of files to be used
+      TYPE(FLD_N), DIMENSION(2) ::   suv_i             ! Combined U & V namelist information
+      TYPE(FLD_N)               ::   sn_ucur, sn_vcur  ! U & V data namelist information
+      !!
+      NAMELIST/namc1d_uvd/ ln_uvd_init, ln_uvd_dyndmp, cn_dir, sn_ucur, sn_vcur
+      !!----------------------------------------------------------------------
+      !
+      ierr0 = 0   ;   ierr1 = 0   ;   ierr2 = 0  ;   ierr3 = 0
+
+      REWIND( numnam_ref )              ! Namelist namc1d_uvd in reference namelist : 
+      READ  ( numnam_ref, namc1d_uvd, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc1d_uvd in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namc1d_uvd in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namc1d_uvd, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc1d_uvd in configuration namelist' )
+      IF(lwm) WRITE ( numond, namc1d_uvd )
+
+      !                             ! force the initialization when dyndmp is used
+      IF( PRESENT( ld_dyndmp ) )   ln_uvd_dyndmp = .TRUE.
+      
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dta_uvd_init : U & V current data '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namc1d_uvd : Set flags'
+         WRITE(numout,*) '      Initialization of ocean U & V current with input data   ln_uvd_init   = ', ln_uvd_init
+         WRITE(numout,*) '      Damping of ocean U & V current toward input data        ln_uvd_dyndmp = ', ln_uvd_dyndmp
+         WRITE(numout,*)
+         IF( .NOT. ln_uvd_init .AND. .NOT. ln_uvd_dyndmp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   U & V current data not used'
+         ENDIF
+      ENDIF
+      !                             ! no initialization when restarting
+      IF( ln_rstart .AND. ln_uvd_init ) THEN
+         CALL ctl_warn( 'dta_uvd_init: ocean restart and U & V current data initialization, ',   &
+            &           'we keep the restart U & V current values and set ln_uvd_init to FALSE' )
+         ln_uvd_init = .FALSE.
+      ENDIF
+
+      !
+      IF(  ln_uvd_init .OR. ln_uvd_dyndmp  ) THEN
+         !                          !==   allocate the data arrays   ==!
+         ALLOCATE( sf_uvd(2), STAT=ierr0 )
+         IF( ierr0 > 0 ) THEN
+            CALL ctl_stop( 'dta_uvd_init: unable to allocate sf_uvd structure' )             ;   RETURN
+         ENDIF
+         !
+                                 ALLOCATE( sf_uvd(1)%fnow(jpi,jpj,jpk)   , STAT=ierr0 )
+         IF( sn_ucur%ln_tint )   ALLOCATE( sf_uvd(1)%fdta(jpi,jpj,jpk,2) , STAT=ierr1 )
+                                 ALLOCATE( sf_uvd(2)%fnow(jpi,jpj,jpk)   , STAT=ierr2 )
+         IF( sn_vcur%ln_tint )   ALLOCATE( sf_uvd(2)%fdta(jpi,jpj,jpk,2) , STAT=ierr3 )
+         !
+         IF( ierr0 + ierr1 + ierr2 + ierr3 > 0 ) THEN
+            CALL ctl_stop( 'dta_uvd_init : unable to allocate U & V current data arrays' )   ;   RETURN
+         ENDIF
+         !                          !==   fill sf_uvd with sn_ucur, sn_vcur and control print   ==!
+         suv_i(1) = sn_ucur   ;   suv_i(2) = sn_vcur
+         CALL fld_fill( sf_uvd, suv_i, cn_dir, 'dta_uvd', 'U & V current data', 'namc1d_uvd' )
+         !
+      ENDIF
+      !
+   END SUBROUTINE dta_uvd_init
+
+
+   SUBROUTINE dta_uvd( kt, puvd )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dta_uvd  ***
+      !!                    
+      !! ** Purpose :   provides U & V current data at time step kt
+      !! 
+      !! ** Method  : - call fldread routine
+      !!              - ORCA_R2: make some hand made alterations to the data (EMPTY)
+      !!              - s- or mixed s-zps coordinate: vertical interpolation onto model mesh
+      !!              - zps coordinate: vertical interpolation onto last partial level
+      !!              - ln_uvd_dyndmp=False: deallocate the U & V current data structure,
+      !!                                     as the data is no longer used
+      !!
+      !! ** Action  :   puvd,  U & V current data interpolated onto model mesh at time-step kt
+      !!----------------------------------------------------------------------
+      INTEGER                           , INTENT(in   ) ::   kt     ! ocean time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2), INTENT(  out) ::   puvd   ! U & V current data
+      !
+      INTEGER ::   ji, jj, jk, jl, jkk               ! dummy loop indicies
+      INTEGER ::   ik, il0, il1, ii0, ii1, ij0, ij1  ! local integers
+      REAL(wp)::   zl, zi                            ! local floats
+      REAL(wp), ALLOCATABLE, DIMENSION(:) ::  zup, zvp   ! 1D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dta_uvd')
+      !
+      CALL fld_read( kt, 1, sf_uvd )      !==   read U & V current data at time step kt   ==!
+      !
+      puvd(:,:,:,1) = sf_uvd(1)%fnow(:,:,:)                 ! NO mask
+      puvd(:,:,:,2) = sf_uvd(2)%fnow(:,:,:) 
+      !
+      IF( ln_sco ) THEN                   !==   s- or mixed s-zps-coordinate   ==!
+         !
+         ALLOCATE( zup(jpk), zvp(jpk) )
+         !
+         IF( kt == nit000 .AND. lwp )THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'dta_uvd: interpolate U & V current data onto the s- or mixed s-z-coordinate mesh'
+         ENDIF
+         !
+         DO jj = 1, jpj                   ! vertical interpolation of U & V current:
+            DO ji = 1, jpi                ! determines the interpolated U & V current profiles at each (i,j) point
+               DO jk = 1, jpk
+                  zl = gdept_n(ji,jj,jk)
+                  IF    ( zl < gdept_1d(1  ) ) THEN          ! extrapolate above the first level of data
+                     zup(jk) =  puvd(ji,jj,1    ,1)
+                     zvp(jk) =  puvd(ji,jj,1    ,2)
+                  ELSEIF( zl > gdept_1d(jpk) ) THEN          ! extrapolate below the last level of data
+                     zup(jk) =  puvd(ji,jj,jpkm1,1)
+                     zvp(jk) =  puvd(ji,jj,jpkm1,2)
+                  ELSE                                      ! inbetween : vertical interpolation between jkk & jkk+1
+                     DO jkk = 1, jpkm1                      ! when  gdept(jkk) < zl < gdept(jkk+1)
+                        IF( (zl-gdept_1d(jkk)) * (zl-gdept_1d(jkk+1)) <= 0._wp ) THEN
+                           zi = ( zl - gdept_1d(jkk) ) / (gdept_1d(jkk+1)-gdept_1d(jkk))
+                           zup(jk) = puvd(ji,jj,jkk,1) + ( puvd(ji,jj,jkk+1,1 ) - puvd(ji,jj,jkk,1) ) * zi 
+                           zvp(jk) = puvd(ji,jj,jkk,2) + ( puvd(ji,jj,jkk+1,2 ) - puvd(ji,jj,jkk,2) ) * zi
+                        ENDIF
+                     END DO
+                  ENDIF
+               END DO
+               DO jk = 1, jpkm1           ! apply mask
+                  puvd(ji,jj,jk,1) = zup(jk) * umask(ji,jj,jk)
+                  puvd(ji,jj,jk,2) = zvp(jk) * vmask(ji,jj,jk)
+               END DO
+               puvd(ji,jj,jpk,1) = 0._wp
+               puvd(ji,jj,jpk,2) = 0._wp
+            END DO
+         END DO
+         ! 
+         DEALLOCATE( zup, zvp )
+         ! 
+      ELSE                                !==   z- or zps- coordinate   ==!
+         !                             
+         puvd(:,:,:,1) = puvd(:,:,:,1) * umask(:,:,:)       ! apply mask
+         puvd(:,:,:,2) = puvd(:,:,:,2) * vmask(:,:,:)
+         !
+         IF( ln_zps ) THEN                ! zps-coordinate (partial steps) interpolation at the last ocean level
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ik = mbkt(ji,jj) 
+                  IF( ik > 1 ) THEN
+                     zl = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+                     puvd(ji,jj,ik,1) = (1.-zl) * puvd(ji,jj,ik,1) + zl * puvd(ji,jj,ik-1,1)
+                     puvd(ji,jj,ik,2) = (1.-zl) * puvd(ji,jj,ik,2) + zl * puvd(ji,jj,ik-1,2)
+                  ENDIF
+               END DO
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( .NOT. ln_uvd_dyndmp    ) THEN   !==   deallocate U & V current structure   ==! 
+         !                                !==   (data used only for initialization)  ==!
+         IF(lwp) WRITE(numout,*) 'dta_uvd: deallocate U & V current arrays as they are only used to initialize the run'
+                                   DEALLOCATE( sf_uvd(1)%fnow )     ! U current arrays in the structure
+         IF( sf_uvd(1)%ln_tint )   DEALLOCATE( sf_uvd(1)%fdta )
+                                   DEALLOCATE( sf_uvd(2)%fnow )     ! V current arrays in the structure
+         IF( sf_uvd(2)%ln_tint )   DEALLOCATE( sf_uvd(2)%fdta )
+                                   DEALLOCATE( sf_uvd         )     ! the structure itself
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dta_uvd')
+      !
+   END SUBROUTINE dta_uvd
+
+   !!======================================================================
+END MODULE dtauvd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyncor_c1d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyncor_c1d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyncor_c1d.F90	(revision 14097)
@@ -0,0 +1,118 @@
+MODULE dyncor_c1d
+   !!======================================================================
+   !!                     ***  MODULE  dyncor_c1d  ***
+   !! Ocean Dynamics :   Coriolis term in 1D configuration
+   !!=====================================================================
+   !! History :  2.0  !  2004-09  (C. Ethe)  Original code
+   !!            3.0  !  2008-04  (G. Madec)  style only
+   !!----------------------------------------------------------------------
+#if defined key_c1d
+   !!----------------------------------------------------------------------
+   !!   'key_c1d'                                          1D Configuration
+   !!----------------------------------------------------------------------
+   !!   cor_c1d       : Coriolis factor at T-point (1D configuration)
+   !!   dyn_cor_c1d   : vorticity trend due to Coriolis at T-point
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+
+   USE sbcwave        ! Surface Waves (add Stokes-Coriolis force)
+   USE sbc_oce , ONLY : ln_stcor    ! use Stoke-Coriolis force
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   cor_c1d      ! called by nemogcm.F90
+   PUBLIC   dyn_cor_c1d  ! called by step1d.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE cor_c1d
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE cor_c1d  ***
+      !! 
+      !! ** Purpose : set the Coriolis factor at T-point
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zphi0, zbeta, zf0   ! local scalars
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'cor_c1d : Coriolis factor at T-point'
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+
+      !
+   END SUBROUTINE cor_c1d
+
+
+   SUBROUTINE dyn_cor_c1d( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_cor_c1d  ***
+      !! 
+      !! ** Purpose :   Compute the now Coriolis trend and add it to 
+      !!               the general trend of the momentum equation in 1D case.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !!
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_cor_c1d : total vorticity trend in 1D'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+      ENDIF
+      !
+      IF( ln_stcor ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + ff_t(ji,jj) * (vn(ji,jj,jk) + vsd(ji,jj,jk))
+                  va(ji,jj,jk) = va(ji,jj,jk) - ff_t(ji,jj) * (un(ji,jj,jk) + usd(ji,jj,jk))
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + ff_t(ji,jj) * vn(ji,jj,jk)
+                  va(ji,jj,jk) = va(ji,jj,jk) - ff_t(ji,jj) * un(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      END IF
+      
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' cor  - Ua: ', mask1=umask,  &
+         &                       tab3d_2=va, clinfo2=' Va: '       , mask2=vmask )
+      !
+   END SUBROUTINE dyn_cor_c1d
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default key                                     NO 1D Configuration
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE cor_c1d              ! Empty routine
+       IMPLICIT NONE
+   END SUBROUTINE cor_c1d   
+   SUBROUTINE dyn_cor_c1d ( kt )      ! Empty routine
+      IMPLICIT NONE
+      INTEGER, INTENT( in ) :: kt
+      WRITE(*,*) 'dyn_cor_c1d: You should not have seen this print! error?', kt
+   END SUBROUTINE dyn_cor_c1d
+#endif
+
+   !!=====================================================================
+END MODULE dyncor_c1d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyndmp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyndmp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/dyndmp.F90	(revision 14097)
@@ -0,0 +1,230 @@
+MODULE dyndmp
+   !!======================================================================
+   !!                       ***  MODULE  dyndmp  ***
+   !! Ocean dynamics: internal restoring trend on momentum (U and V current)
+   !!                 This should only be used for C1D case in current form
+   !!======================================================================
+   !! History :  3.5  ! 2013-08  (D. Calvert)  Original code
+   !!            3.6  ! 2014-08  (T. Graham) Modified to use netcdf file of
+   !!                             restoration coefficients supplied to tradmp
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_dmp_alloc : allocate dyndmp arrays
+   !!   dyn_dmp_init  : namelist read, parameter control and resto coeff.
+   !!   dyn_dmp       : update the momentum trend with the internal damping
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean: variables
+   USE dom_oce        ! ocean: domain variables
+   USE c1d            ! 1D vertical configuration
+   USE tradmp         ! ocean: internal damping
+   USE zdf_oce        ! ocean: vertical physics
+   USE phycst         ! physical constants
+   USE dtauvd         ! data: U & V current
+   USE zdfmxl         ! vertical physics: mixed layer depth
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE prtctl         ! Print control
+   USE timing         ! Timing
+   USE iom            ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_dmp_init ! routine called by nemogcm.F90
+   PUBLIC   dyn_dmp      ! routine called by step_c1d.F90
+
+   LOGICAL, PUBLIC ::   ln_dyndmp   !: Flag for Newtonian damping
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  utrdmp    !: damping U current trend (m/s2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  vtrdmp    !: damping V current trend (m/s2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  resto_uv  !: restoring coeff. on U & V current
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dyn_dmp_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION dyn_dmp_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( utrdmp(jpi,jpj,jpk), vtrdmp(jpi,jpj,jpk), resto_uv(jpi,jpj,jpk), STAT= dyn_dmp_alloc )
+      !
+      CALL mpp_sum ( 'dyndmp', dyn_dmp_alloc )
+      IF( dyn_dmp_alloc > 0 )   CALL ctl_warn('dyn_dmp_alloc: allocation of arrays failed')
+      !
+   END FUNCTION dyn_dmp_alloc
+
+
+   SUBROUTINE dyn_dmp_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_dmp_init  ***
+      !! 
+      !! ** Purpose :   Initialization for the Newtonian damping 
+      !!
+      !! ** Method  : - read the ln_dyndmp parameter from the namc1d_dyndmp namelist
+      !!              - allocate damping arrays
+      !!              - check the parameters of the namtra_dmp namelist
+      !!              - calculate damping coefficient
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, imask   ! local integers
+      !!
+      NAMELIST/namc1d_dyndmp/ ln_dyndmp
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namc1d_dyndmp in reference namelist : 
+      READ  ( numnam_ref, namc1d_dyndmp, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc1d_dyndmp in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namc1d_dyndmp in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namc1d_dyndmp, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc1d_dyndmp in configuration namelist' )
+      IF(lwm) WRITE ( numond, namc1d_dyndmp )
+      !
+      IF(lwp) THEN                           ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_dmp_init : U and V current Newtonian damping'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namc1d_dyndmp : Set damping flag'
+         WRITE(numout,*) '      add a damping term or not       ln_dyndmp = ', ln_dyndmp
+         WRITE(numout,*) '   Namelist namtra_dmp    : Set damping parameters'
+         WRITE(numout,*) '      Apply relaxation   or not       ln_tradmp = ', ln_tradmp
+         WRITE(numout,*) '      mixed layer damping option      nn_zdmp   = ', nn_zdmp
+         WRITE(numout,*) '      Damping file name               cn_resto  = ', cn_resto
+         WRITE(numout,*)
+      ENDIF
+      !
+      IF( ln_dyndmp ) THEN
+         !                                   !==   allocate the data arrays   ==!
+         IF( dyn_dmp_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dyn_dmp_init: unable to allocate arrays' )
+         !
+         SELECT CASE ( nn_zdmp )             !==   control print of vertical option   ==!
+         CASE ( 0    )   ;   IF(lwp) WRITE(numout,*) '   momentum damping throughout the water column'
+         CASE ( 1    )   ;   IF(lwp) WRITE(numout,*) '   no momentum damping in the turbocline (avt > 5 cm2/s)'
+         CASE ( 2    )   ;   IF(lwp) WRITE(numout,*) '   no momentum damping in the mixed layer'
+         CASE DEFAULT
+            WRITE(ctmp1,*) '          bad flag value for nn_zdmp = ', nn_zdmp
+            CALL ctl_stop(ctmp1)
+         END SELECT
+         !
+         IF( .NOT. ln_uvd_dyndmp ) THEN      ! force the initialization of U & V current data for damping
+            CALL ctl_warn( 'dyn_dmp_init: U & V current read data not initialized, we force ln_uvd_dyndmp=T' )
+            CALL dta_uvd_init( ld_dyndmp=ln_dyndmp )
+         ENDIF
+         !
+         utrdmp(:,:,:) = 0._wp               ! internal damping trends
+         vtrdmp(:,:,:) = 0._wp
+         !
+         !Read in mask from file
+         CALL iom_open ( cn_resto, imask)
+         CALL iom_get  ( imask, jpdom_autoglo, 'resto', resto)
+         CALL iom_close( imask )
+      ENDIF
+      !
+   END SUBROUTINE dyn_dmp_init
+
+
+   SUBROUTINE dyn_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_dmp  ***
+      !!                  
+      !! ** Purpose :   Compute the momentum trends due to a newtonian damping
+      !!      of the ocean velocities towards the given data and add it to the 
+      !!      general momentum trends.
+      !!
+      !! ** Method  :   Compute Newtonian damping towards u_dta and v_dta 
+      !!      and add to the general momentum trends:
+      !!                     ua = ua + resto_uv * (u_dta - ub)
+      !!                     va = va + resto_uv * (v_dta - vb)
+      !!      The trend is computed either throughout the water column
+      !!      (nn_zdmp=0), where the vertical mixing is weak (nn_zdmp=1) or
+      !!      below the well mixed layer (nn_zdmp=2)
+      !!
+      !! ** Action  : - (ua,va)   momentum trends updated with the damping trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zua, zva     ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2) ::   zuv_dta   ! Read in data 
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'dyn_dmp' )
+      !
+      !
+      !                           !==   read and interpolate U & V current data at kt   ==!
+      CALL dta_uvd( kt, zuv_dta ) !!! NOTE: This subroutine must be altered for use outside
+                                  !!!       the C1D context (use of U,V grid variables)
+      !
+      SELECT CASE ( nn_zdmp )     !==   Calculate/add Newtonian damping to the momentum trend   ==!
+      !
+      CASE( 0 )                   ! Newtonian damping throughout the water column
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zua = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,1) - ub(ji,jj,jk) )
+                  zva = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,2) - vb(ji,jj,jk) )
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+                  va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  utrdmp(ji,jj,jk) = zua           ! save the trends
+                  vtrdmp(ji,jj,jk) = zva      
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 1 )                  ! no damping above the turbocline (avt > 5 cm2/s)
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( avt(ji,jj,jk) <= avt_c ) THEN
+                     zua = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,1) - ub(ji,jj,jk) )
+                     zva = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,2) - vb(ji,jj,jk) )
+                  ELSE
+                     zua = 0._wp
+                     zva = 0._wp  
+                  ENDIF
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+                  va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  utrdmp(ji,jj,jk) = zua           ! save the trends
+                  vtrdmp(ji,jj,jk) = zva
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 2 )                  ! no damping in the mixed layer
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( gdept_n(ji,jj,jk) >= hmlp (ji,jj) ) THEN
+                     zua = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,1) - ub(ji,jj,jk) )
+                     zva = resto_uv(ji,jj,jk) * ( zuv_dta(ji,jj,jk,2) - vb(ji,jj,jk) )
+                  ELSE
+                     zua = 0._wp
+                     zva = 0._wp  
+                  ENDIF
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + zua
+                  va(ji,jj,jk) = va(ji,jj,jk) + zva
+                  utrdmp(ji,jj,jk) = zua           ! save the trends
+                  vtrdmp(ji,jj,jk) = zva
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      !                           ! Control print
+      IF( ln_ctl   )   CALL prt_ctl( tab3d_1=ua(:,:,:), clinfo1=' dmp  - Ua: ', mask1=umask,   &
+         &                           tab3d_2=va(:,:,:), clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      !
+      IF( ln_timing )   CALL timing_stop( 'dyn_dmp')
+      !
+   END SUBROUTINE dyn_dmp
+
+   !!======================================================================
+END MODULE dyndmp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/step_c1d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/step_c1d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/C1D/step_c1d.F90	(revision 14097)
@@ -0,0 +1,153 @@
+MODULE step_c1d
+   !!======================================================================
+   !!                       ***  MODULE step_c1d  ***
+   !! Time-stepping    : manager of the ocean, tracer and ice time stepping - c1d case
+   !!======================================================================
+   !! History :   2.0  !  2004-04  (C. Ethe)  adapted from step.F90 for C1D
+   !!             3.0  !  2008-04  (G. Madec)  redo the adaptation to include SBC
+   !!----------------------------------------------------------------------
+#if defined key_c1d
+   !!----------------------------------------------------------------------
+   !!   'key_c1d'                                       1D Configuration
+   !!----------------------------------------------------------------------  
+   !!   stp_c1d        : NEMO system time-stepping in c1d case
+   !!----------------------------------------------------------------------
+   USE step_oce        ! time stepping definition modules 
+#if defined key_top
+   USE trcstp          ! passive tracer time-stepping      (trc_stp routine)
+#endif
+   USE dyncor_c1d      ! Coriolis term (c1d case)         (dyn_cor_1d     )
+   USE dynnxt          ! time-stepping                    (dyn_nxt routine)
+   USE dyndmp          ! U & V momentum damping           (dyn_dmp routine)
+   USE restart         ! restart 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC stp_c1d      ! called by opa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE stp_c1d( kstp )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE stp_c1d  ***
+      !!                      
+      !! ** Purpose :  - Time stepping of SBC including sea ice (dynamic and thermodynamic eqs.)
+      !!               - Time stepping of OPA (momentum and active tracer eqs.)
+      !!               - Time stepping of TOP (passive tracer eqs.)
+      !! 
+      !! ** Method  : -1- Update forcings and data  
+      !!              -2- Update vertical ocean physics 
+      !!              -3- Compute the t and s trends 
+      !!              -4- Update t and s 
+      !!              -5- Compute the momentum trends
+      !!              -6- Update the horizontal velocity
+      !!              -7- Compute the diagnostics variables (rd,N2, div,cur,w)
+      !!              -8- Outputs and diagnostics
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kstp   ! ocean time-step index
+      !
+      INTEGER ::   jk       ! dummy loop indice
+      !! ---------------------------------------------------------------------
+      IF( kstp == nit000 )   CALL iom_init( "nemo")   ! iom_put initialization (must be done after nemo_init for AGRIF+XIOS+OASIS)
+      IF( kstp /= nit000 )   CALL day( kstp )         ! Calendar (day was already called at nit000 in day_init)
+                             CALL iom_setkt( kstp - nit000 + 1, "nemo" )   ! say to iom that we are at time step kstp
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Update data, open boundaries, surface boundary condition (including sea-ice)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         CALL sbc    ( kstp )         ! Sea Boundary Condition (including sea-ice)
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Ocean physics update                (ua, va, ta, sa used as workspace)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         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
+                         CALL zdf_phy( kstp )         ! vertical physics update (bfr, avt, avs, avm + MLD)
+
+      IF(.NOT.ln_linssh )   CALL ssh_nxt       ( kstp )  ! after ssh (includes call to div_hor)
+      IF(.NOT.ln_linssh )   CALL dom_vvl_sf_nxt( kstp )  ! after vertical scale factors 
+
+      IF(.NOT.ln_linssh )   CALL wzv           ( kstp )  ! now cross-level velocity 
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! diagnostics and outputs             (ua, va, ta, sa used as workspace)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         CALL dia_wri( kstp )       ! ocean model: outputs
+                         CALL dia_hth( kstp )       ! Thermocline depth (20 degres isotherm depth)
+
+
+#if defined key_top
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Passive Tracer Model
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                        CALL trc_stp( kstp )       ! time-stepping
+#endif
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Active tracers                              (ua, va used as workspace)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                        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(.NOT.ln_linssh)CALL tra_adv( kstp )       ! horizontal & vertical advection
+      IF( ln_zdfosm  )  CALL tra_osm( kstp )       ! OSMOSIS 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._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
+      IF( ln_zdfosm  )  CALL dyn_osm    ( kstp )   ! OSMOSIS non-local velocity fluxes
+                        CALL dyn_zdf    ( kstp )   ! vertical diffusion
+                        CALL dyn_nxt    ( kstp )   ! lateral velocity at next time step
+      IF(.NOT.ln_linssh)CALL ssh_swp    ( kstp )   ! swap of sea surface height
+
+      IF(.NOT.ln_linssh)CALL dom_vvl_sf_swp( kstp )! swap of vertical scale factors
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Control and restarts
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                             CALL stp_ctl( kstp )
+      IF( kstp == nit000 )   CALL iom_close( numror )      ! close input  ocean restart file
+      IF( lrst_oce       )   CALL rst_write( kstp )        ! write output ocean restart file
+      !
+#if defined key_iomput
+      IF( kstp == nitend .OR. nstop > 0 )   CALL xios_context_finalize()   ! needed for XIOS
+      !
+#endif
+   END SUBROUTINE stp_c1d
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default key                                            NO 1D Config
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE stp_c1d ( kt )      ! dummy routine
+      IMPLICIT NONE
+      INTEGER, INTENT( in ) :: kt
+      WRITE(*,*) 'stp_c1d: You should not have seen this print! error?', kt
+   END SUBROUTINE stp_c1d
+#endif
+
+   !!======================================================================
+END MODULE step_c1d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/README.rst	(revision 14097)
@@ -0,0 +1,153 @@
+**********************************
+On line biogeochemistry coarsening
+**********************************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Presentation
+============
+
+A capacity of coarsening physics to force a BGC model coupled to NEMO has been developed.
+This capacity allow to run 'online' a BGC model coupled to OCE-SI3 with a lower resolution,
+to reduce the CPU cost of the BGC model, while preserving the effective resolution of the dynamics.
+
+A presentation is available [attachment:crs_wiki_1.1.pdf​ here], where the methodology is presented.
+
+What is available and working for now in this version
+=====================================================
+
+[To be completed]
+
+Description of the successful validation tests
+==============================================
+
+[To be completed]
+
+What is not working yet with on line coarsening of biogeochemistry
+==================================================================
+
+[To be completed]
+
+''should include precise explanation on MPI decomposition problems too''
+
+How to set up and use on line biogeochemistry
+=============================================
+
+Extract the on line biogeochemistry branch
+------------------------------------------
+
+To get the appropriate source code with the on line coarsening of biogeochemistry feature:
+
+.. code-block:: console
+
+	$ svn co https://forge.ipsl.jussieu.fr/nemo/browser/NEMO/branches/2018/dev_r5003_MERCATOR6_CRS
+
+
+How to activate coarsening?
+---------------------------
+
+To activate the coarsening, ``key_crs`` should be added to list of CPP keys.
+This key will only activate the coarsening of dynamics.
+
+Some parameters are available in the namelist_cfg:
+
+.. code-block:: fortran
+
+	               !   passive tracer coarsened online simulations
+	!-----------------------------------------------------------------------
+	   nn_factx    = 3         !  Reduction factor of x-direction
+	   nn_facty    = 3         !  Reduction factor of y-direction
+	   nn_msh_crs  = 0         !  create (=1) a mesh file or not (=0)
+	   nn_crs_kz   = 3         ! 0, volume-weighted MEAN of KZ
+	                           ! 1, MAX of KZ
+	                           ! 2, MIN of KZ
+	                           ! 3, 10^(MEAN(LOG(KZ))
+	                           ! 4, MEDIANE of KZ
+	   ln_crs_wn   = .false.   ! wn coarsened (T) or computed using horizontal divergence ( F )
+	                           !                           !
+	   ln_crs_top = .true.     !coarsening online for the bio
+	/
+
+- Only ``nn_factx = 3`` is available and the coarsening only works for grids with a T-pivot point for
+  the north-fold lateral boundary condition (ORCA025, ORCA12, ORCA36, ...).
+- ``nn_msh_crs = 1`` will activate the generation of the coarsened grid meshmask.
+- ``nn_crs_kz`` is the operator to coarsen the vertical mixing coefficient.
+- ``ln_crs_wn``
+
+  - when ``key_vvl`` is activated, this logical has no effect;
+    the coarsened vertical velocities are computed using horizontal divergence.
+  - when ``key_vvl`` is not activated,
+
+    - coarsened vertical velocities are computed using horizontal divergence (``ln_crs_wn = .false.``)
+    - or coarsened vertical velocities are computed with an average operator (``ln_crs_wn = .true.``)
+- ``ln_crs_top = .true.``: should be activated to run BCG model in coarsened space;
+  so only works when ``key_top`` is in the cpp list and eventually ``key_pisces`` or ``key_my_trc``.
+
+Choice of operator to coarsene KZ
+---------------------------------
+
+A sensiblity test has been done with an Age tracer to compare the different operators.
+The 3 and 4 options seems to provide the best results.
+
+Some results can be found [xxx here]
+
+Example of xml files to output coarsened variables with XIOS
+------------------------------------------------------------
+
+In the [attachment:iodef.xml iodef.xml]  file, a "nemo" context is defined and
+some variable defined in [attachment:file_def.xml file_def.xml] are writted on the ocean-dynamic grid.
+To write variables on the coarsened grid, and in particular the passive tracers,
+a "nemo_crs" context should be defined in [attachment:iodef.xml iodef.xml] and
+the associated variable are listed in [attachment:file_crs_def.xml file_crs_def.xml ].
+
+Passive tracers tracers initial conditions
+------------------------------------------
+
+When initial conditions are provided in NetCDF files, the field might be:
+
+- on the coarsened grid
+- or they can be on another grid and
+  interpolated `on-the-fly <http://forge.ipsl.jussieu.fr/nemo/wiki/Users/SetupNewConfiguration/Weight-creator>`_.
+  Example of namelist for PISCES :
+
+	.. code-block:: fortran
+
+		!-----------------------------------------------------------------------
+		&namtrc_dta      !    Initialisation from data input file
+		!-----------------------------------------------------------------------
+		!
+		   sn_trcdta(1)  = 'DIC_REG1'        ,        -12        ,  'DIC'     ,    .false.   , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(2)  = 'ALK_REG1'        ,        -12        ,  'ALK'     ,    .false.   , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(3)  = 'O2_REG1'         ,        -1         ,  'O2'      ,    .true.    , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(5)  = 'PO4_REG1'        ,        -1         ,  'PO4'     ,    .true.    , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(7)  = 'Si_REG1'         ,        -1         ,  'Si'      ,    .true.    , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+	   	sn_trcdta(10) = 'DOC_REG1'        ,        -12        ,  'DOC'     ,    .false.   , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(14) = 'Fe_REG1'         ,        -12        ,  'Fe'      ,    .false.   , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+		   sn_trcdta(23) = 'NO3_REG1'        ,        -1         ,  'NO3'     ,    .true.    , .true. , 'yearly'  , 'reshape_REG1toeORCA075_bilin.nc'       , ''   , ''
+	   	rn_trfac(1)   =   1.0e-06  !  multiplicative factor
+		   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+		   rn_trfac(3)   =  44.6e-06  !  -      -      -     -
+	   	rn_trfac(5)   = 122.0e-06  !  -      -      -     -
+		   rn_trfac(7)   =   1.0e-06  !  -      -      -     -
+		   rn_trfac(10)  =   1.0e-06  !  -      -      -     -
+	   	rn_trfac(14)  =   1.0e-06  !  -      -      -     -
+		   rn_trfac(23)  =   7.6e-06  !  -      -      -     -
+
+	   	cn_dir        =  './'      !  root directory for the location of the data files
+
+PISCES forcing files
+--------------------
+
+They might be on the coarsened grid.
+
+Perspectives
+============
+
+For the future, a few options are on the table to implement coarsening for biogeochemistry in 4.0 and
+future releases.
+Those will be discussed in Autumn 2018
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crs.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crs.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crs.F90	(revision 14097)
@@ -0,0 +1,346 @@
+MODULE crs   
+   !!======================================================================
+   !!                         ***  MODULE crs_dom  ***
+   !!        Declare the coarse grid domain and other public variables 
+   !!        then allocate them if needed.
+   !!======================================================================
+   !!  History     2012-06  Editing  (J. Simeon, G. Madec, C. Ethe, C. Calone) Original code
+   !!----------------------------------------------------------------------
+   USE par_oce  
+   USE dom_oce
+   USE in_out_manager
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC crs_dom_alloc  ! Called from crsini.F90
+   PUBLIC crs_dom_alloc2  ! Called from crsini.F90
+   PUBLIC dom_grid_glo   
+   PUBLIC dom_grid_crs 
+
+      ! Domain variables
+      INTEGER  ::  jpiglo_crs ,   &             !: 1st dimension of global coarse grid domain
+                   jpjglo_crs                   !: 2nd dimension of global coarse grid domain
+      INTEGER  ::  jpi_crs ,   &                !: 1st dimension of local coarse grid domain
+                   jpj_crs                      !: 2nd dimension of local coarse grid domain
+      INTEGER  ::  jpi_full ,  &                !: 1st dimension of local parent grid domain
+                   jpj_full                     !: 2nd dimension of local parent grid domain
+
+      INTEGER  ::  nistr , njstr
+      INTEGER  ::  niend , njend
+
+      INTEGER  ::  jpi_crsm1, jpj_crsm1         !: loop indices      
+      INTEGER  ::  jpiglo_crsm1, jpjglo_crsm1   !: loop indices      
+      INTEGER  ::  nperio_full, nperio_crs      !: jperio of parent and coarse grids
+      INTEGER  ::  npolj_full, npolj_crs        !: north fold mark
+      INTEGER  ::  jpiglo_full, jpjglo_full     !: jpiglo / jpjglo
+      INTEGER  ::  npiglo, npjglo               !: jpjglo
+      INTEGER  ::  nlci_full, nlcj_full         !: i-, j-dimension of local or sub domain on parent grid
+      INTEGER  ::  nldi_full, nldj_full         !: starting indices of internal sub-domain on parent grid
+      INTEGER  ::  nlei_full, nlej_full         !: ending indices of internal sub-domain on parent grid
+      INTEGER  ::  nlci_crs, nlcj_crs           !: i-, j-dimension of local or sub domain on coarse grid
+      INTEGER  ::  nldi_crs, nldj_crs           !: starting indices of internal sub-domain on coarse grid
+      INTEGER  ::  nlei_crs, nlej_crs           !: ending indices of internal sub-domain on coarse grid
+
+      INTEGER  ::  narea_full, narea_crs        !: node
+      INTEGER  ::  jpnij_full, jpnij_crs        !: =jpni*jpnj, the pe decomposition
+      INTEGER  ::  jpim1_full, jpjm1_full       !: 
+      INTEGER  ::  nimpp_full, njmpp_full       !: global position of point (1,1) of subdomain on parent grid
+      INTEGER  ::  nimpp_crs, njmpp_crs         !: set to 1,1 for now .  Valid only for monoproc
+      INTEGER  ::  nreci_full, nrecj_full
+      INTEGER  ::  nreci_crs, nrecj_crs
+      !cc
+      INTEGER ::   noea_full, nowe_full        !: index of the local neighboring processors in
+      INTEGER ::   noso_full, nono_full        !: east, west, south and north directions
+      INTEGER ::   npne_full, npnw_full        !: index of north east and north west processor
+      INTEGER ::   npse_full, npsw_full        !: index of south east and south west processor
+      INTEGER ::   nbne_full, nbnw_full        !: logical of north east & north west processor
+      INTEGER ::   nbse_full, nbsw_full        !: logical of south east & south west processor
+      INTEGER ::   nidom_full                  !: ???
+      INTEGER ::   nproc_full                  !:number for local processor
+      INTEGER ::   nbondi_full, nbondj_full    !: mark of i- and j-direction local boundaries
+      INTEGER ::   noea_crs, nowe_crs          !: index of the local neighboring processors in
+      INTEGER ::   noso_crs, nono_crs          !: east, west, south and north directions
+      INTEGER ::   npne_crs, npnw_crs          !: index of north east and north west processor
+      INTEGER ::   npse_crs, npsw_crs          !: index of south east and south west processor
+      INTEGER ::   nbne_crs, nbnw_crs          !: logical of north east & north west processor
+      INTEGER ::   nbse_crs, nbsw_crs          !: logical of south east & south west processor
+      INTEGER ::   nidom_crs                   !: ???
+      INTEGER ::   nproc_crs                   !:number for local processor
+      INTEGER ::   nbondi_crs, nbondj_crs      !: mark of i- and j-direction local boundaries
+      
+
+      INTEGER, DIMENSION(:), ALLOCATABLE :: mis_crs, mie_crs, mis2_crs, mie2_crs  ! starting and ending i-indices of parent subset
+      INTEGER, DIMENSION(:), ALLOCATABLE :: mjs_crs, mje_crs, mjs2_crs, mje2_crs ! starting and ending  j-indices of parent subset
+      INTEGER, DIMENSION(:), ALLOCATABLE :: mjg_crs, mig_crs
+      INTEGER, DIMENSION(:), ALLOCATABLE :: mi0_crs, mi1_crs, mj0_crs, mj1_crs
+      INTEGER  :: mxbinctr, mybinctr            ! central point in grid box
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nlcit_crs, nlcit_full  !: dimensions of every subdomain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nldit_crs, nldit_full     !: first, last indoor index for each i-domain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nleit_crs, nleit_full    !: first, last indoor index for each j-domain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nimppt_crs, nimppt_full    !: first, last indoor index for each j-domain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nlcjt_crs, nlcjt_full  !: dimensions of every subdomain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nldjt_crs, nldjt_full     !: first, last indoor index for each i-domain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   nlejt_crs, nlejt_full    !: first, last indoor index for each j-domain
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   njmppt_crs, njmppt_full    !: first, last indoor index for each j-domain
+
+ 
+      ! Masks
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: tmask_crs, umask_crs, vmask_crs, fmask_crs
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE :: tmask_i_crs, rnfmsk_crs, tpol_crs, fpol_crs
+      
+  !    REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: tmask_i_crs, tpol, fpol      
+
+      ! Scale factors
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: e1t_crs, e2t_crs, e1e2t_crs ! horizontal scale factors grid type T
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: e1u_crs, e2u_crs ! horizontal scale factors grid type U
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: e1v_crs, e2v_crs ! horizontal scale factors grid type V
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: e1f_crs, e2f_crs ! horizontal scale factors grid type F
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3t_crs, e3u_crs, e3v_crs, e3f_crs, e3w_crs
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e3t_max_crs, e3u_max_crs, e3v_max_crs, e3f_max_crs, e3w_max_crs
+      
+      ! Surface
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e1e2w_crs, e2e3u_crs, e1e3v_crs
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: e1e2w_msk, e2e3u_msk, e1e3v_msk
+                                                                  ! vertical scale factors 
+      ! Coordinates
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: gphit_crs, glamt_crs, gphif_crs, glamf_crs 
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: gphiu_crs, glamu_crs, gphiv_crs, glamv_crs 
+      REAL(wp), DIMENSION(:,:),   ALLOCATABLE :: ff_crs
+      INTEGER,  DIMENSION(:,:),   ALLOCATABLE :: mbathy_crs, mbkt_crs, mbku_crs, mbkv_crs
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: gdept_crs, gdepu_crs, gdepv_crs, gdepw_crs
+
+      ! Weights
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: facsurfv, facsurfu, facvol_t, facvol_w
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: ocean_volume_crs_t, ocean_volume_crs_w, bt_crs, r1_bt_crs
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: crs_surfu_wgt, crs_surfv_wgt, crs_surfw_wgt, crs_volt_wgt
+
+      ! CRS Namelist
+      INTEGER           :: nn_factx   = 3       !: reduction factor of x-dimension of the parent grid
+      INTEGER           :: nn_facty   = 3       !: reduction factor of y-dimension of the parent grid
+      INTEGER           :: nn_binref  = 0       !: 0 = binning starts north fold (equator could be asymmetric)
+                                                !: 1 = binning centers at equator (north fold my have artifacts)     
+                                                !:    for even reduction factors, equator placed in bin biased south
+      LOGICAL           :: ln_msh_crs   = .TRUE.   !: =T Create a meshmask file for CRS
+      INTEGER           :: nn_crs_kz    =    0     !: type of Kz coarsening ( =0->VOL ; =1->MAX ; =2->MIN) 
+      LOGICAL           :: ln_crs_wn    = .FALSE.  !: coarsening wn or computation using horizontal divergence 
+      !
+      INTEGER           :: nrestx, nresty       !: for determining odd or even reduction factor
+
+
+      ! Grid reduction factors
+      REAL(wp)     ::  rfactx_r                !: inverse of x-dim reduction factor
+      REAL(wp)     ::  rfacty_r                !: inverse of y-dim reduction factor
+      REAL(wp)     ::  rfactxy 
+
+      ! Physical and dynamical ocean fields for output or passing to TOP, time-mean fields
+      REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE      :: tsn_crs
+      REAL(wp), DIMENSION(:,:,:)  , ALLOCATABLE      :: un_crs, vn_crs, wn_crs
+      REAL(wp), DIMENSION(:,:,:)  , ALLOCATABLE      :: hdivn_crs    
+      REAL(wp), DIMENSION(:,:)    , ALLOCATABLE      :: sshn_crs    
+      ! 
+      ! Surface fluxes to pass to TOP
+      REAL(wp), PUBLIC, DIMENSION(:,:)  , ALLOCATABLE :: qsr_crs, fr_i_crs, wndm_crs
+      REAL(wp), PUBLIC, DIMENSION(:,:)  , ALLOCATABLE :: emp_crs, emp_b_crs, sfx_crs
+      REAL(wp), PUBLIC, DIMENSION(:,:)  , ALLOCATABLE :: utau_crs, vtau_crs
+      REAL(wp), PUBLIC, DIMENSION(:,:)  , ALLOCATABLE :: rnf_crs
+
+      ! Vertical diffusion
+      REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:)  ::  avt_crs           !: temperature vertical diffusivity coeff. [m2/s] at w-point
+      REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:)  ::  avs_crs           !: salinity    vertical diffusivity coeff. [m2/s] at w-point
+
+      ! Mixing and Mixed Layer Depth
+      INTEGER,  PUBLIC, ALLOCATABLE, DIMENSION(:,:)    ::  nmln_crs, hmld_crs, hmlp_crs, hmlpt_crs                       
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   INTEGER FUNCTION crs_dom_alloc()
+      !!-------------------------------------------------------------------
+      !!                     *** FUNCTION crs_dom_alloc ***
+      !!  ** Purpose :   Allocate public crs arrays  
+      !!-------------------------------------------------------------------
+      !! Local variables
+      INTEGER, DIMENSION(17) :: ierr
+
+      ierr(:) = 0
+
+      ! Set up bins for coarse grid, horizontal only.
+     ALLOCATE( mis2_crs(jpiglo_crs), mie2_crs(jpiglo_crs),  &
+       &       mjs2_crs(jpjglo_crs), mje2_crs(jpjglo_crs),  &
+       &       mi0_crs (jpiglo_crs), mi1_crs (jpiglo_crs),  &
+       &       mj0_crs (jpjglo_crs), mj1_crs (jpjglo_crs),  &
+       &       mig_crs (jpi_crs)   , mjg_crs (jpj_crs)   ,  STAT=ierr(1) ) 
+
+
+      ! Set up Mask and Mesh
+      ALLOCATE( tmask_crs(jpi_crs,jpj_crs,jpk) , fmask_crs(jpi_crs,jpj_crs,jpk) ,  &
+         &      umask_crs(jpi_crs,jpj_crs,jpk) , vmask_crs(jpi_crs,jpj_crs,jpk) , STAT=ierr(2))
+
+      ALLOCATE( tmask_i_crs(jpi_crs,jpj_crs)   , rnfmsk_crs(jpi_crs,jpj_crs), &
+      &         tpol_crs(jpiglo_crs,jpjglo_crs), fpol_crs(jpiglo_crs,jpjglo_crs), STAT=ierr(3) )
+
+      ALLOCATE( gphit_crs(jpi_crs,jpj_crs) , glamt_crs(jpi_crs,jpj_crs) , & 
+         &      gphiu_crs(jpi_crs,jpj_crs) , glamu_crs(jpi_crs,jpj_crs) , &
+         &      gphiv_crs(jpi_crs,jpj_crs) , glamv_crs(jpi_crs,jpj_crs) , &
+         &      gphif_crs(jpi_crs,jpj_crs) , glamf_crs(jpi_crs,jpj_crs) , &
+         &      ff_crs(jpi_crs,jpj_crs)    , STAT=ierr(4))
+
+      ALLOCATE( e1t_crs(jpi_crs,jpj_crs) , e2t_crs(jpi_crs,jpj_crs) , & 
+         &      e1u_crs(jpi_crs,jpj_crs) , e2u_crs(jpi_crs,jpj_crs) , & 
+         &      e1v_crs(jpi_crs,jpj_crs) , e2v_crs(jpi_crs,jpj_crs) , &
+         &      e1f_crs(jpi_crs,jpj_crs) , e2f_crs(jpi_crs,jpj_crs) , &
+         &      e1e2t_crs(jpi_crs,jpj_crs), STAT=ierr(5))
+
+      ALLOCATE( e3t_crs(jpi_crs,jpj_crs,jpk)    , e3w_crs(jpi_crs,jpj_crs,jpk)    , & 
+         &      e3u_crs(jpi_crs,jpj_crs,jpk)    , e3v_crs(jpi_crs,jpj_crs,jpk)    , &
+         &      e3f_crs(jpi_crs,jpj_crs,jpk)    , e1e2w_msk(jpi_crs,jpj_crs,jpk)  , & 
+         &      e2e3u_msk(jpi_crs,jpj_crs,jpk)  , e1e3v_msk(jpi_crs,jpj_crs,jpk)  , &
+         &      e1e2w_crs(jpi_crs,jpj_crs,jpk)  , e2e3u_crs(jpi_crs,jpj_crs,jpk)  , &
+         &      e1e3v_crs(jpi_crs,jpj_crs,jpk)  , e3t_max_crs(jpi_crs,jpj_crs,jpk), &
+         &      e3w_max_crs(jpi_crs,jpj_crs,jpk), e3u_max_crs(jpi_crs,jpj_crs,jpk), &
+         &      e3v_max_crs(jpi_crs,jpj_crs,jpk), STAT=ierr(6))
+
+
+      ALLOCATE( facsurfv(jpi_crs,jpj_crs,jpk), facsurfu(jpi_crs,jpj_crs,jpk) , & 
+         &      facvol_t(jpi_crs,jpj_crs,jpk), facvol_w(jpi_crs,jpj_crs,jpk) , &
+         &      ocean_volume_crs_t(jpi_crs,jpj_crs,jpk), ocean_volume_crs_w(jpi_crs,jpj_crs,jpk), &
+         &      bt_crs(jpi_crs,jpj_crs,jpk)  , r1_bt_crs(jpi_crs,jpj_crs,jpk) , STAT=ierr(7))
+
+
+      ALLOCATE( crs_surfu_wgt(jpi_crs,jpj_crs,jpk), crs_surfv_wgt(jpi_crs,jpj_crs,jpk) , & 
+         &      crs_surfw_wgt(jpi_crs,jpj_crs,jpk), crs_volt_wgt(jpi_crs,jpj_crs,jpk) , STAT=ierr(8))
+
+
+      ALLOCATE( mbathy_crs(jpi_crs,jpj_crs), mbkt_crs(jpi_crs,jpj_crs) , &
+         &      mbku_crs(jpi_crs,jpj_crs)  , mbkv_crs(jpi_crs,jpj_crs) , STAT=ierr(9))
+
+      ALLOCATE( gdept_crs(jpi_crs,jpj_crs,jpk), gdepu_crs(jpi_crs,jpj_crs,jpk) , &
+         &      gdepv_crs(jpi_crs,jpj_crs,jpk), gdepw_crs(jpi_crs,jpj_crs,jpk) , STAT=ierr(10) )
+
+
+      ALLOCATE( un_crs(jpi_crs,jpj_crs,jpk) , vn_crs   (jpi_crs,jpj_crs,jpk) ,     &
+         &      wn_crs(jpi_crs,jpj_crs,jpk) , hdivn_crs(jpi_crs,jpj_crs,jpk) , STAT=ierr(11))
+
+     ALLOCATE( sshn_crs(jpi_crs,jpj_crs), emp_crs (jpi_crs,jpj_crs), emp_b_crs(jpi_crs,jpj_crs), &
+         &     qsr_crs(jpi_crs ,jpj_crs), wndm_crs(jpi_crs,jpj_crs), utau_crs(jpi_crs,jpj_crs) , &
+         &     vtau_crs(jpi_crs,jpj_crs), rnf_crs(jpi_crs ,jpj_crs), &
+         &     fr_i_crs(jpi_crs,jpj_crs), sfx_crs(jpi_crs ,jpj_crs),  STAT=ierr(12)  )
+
+     ALLOCATE( tsn_crs(jpi_crs,jpj_crs,jpk,jpts), avt_crs(jpi_crs,jpj_crs,jpk),   &
+         &                                        avs_crs(jpi_crs,jpj_crs,jpk), STAT=ierr(13) )
+
+      ALLOCATE( nmln_crs(jpi_crs,jpj_crs) , hmld_crs(jpi_crs,jpj_crs) , &
+         &      hmlp_crs(jpi_crs,jpj_crs) , hmlpt_crs(jpi_crs,jpj_crs) , STAT=ierr(14) )
+         
+      ALLOCATE( nimppt_crs (jpnij) , nlcit_crs (jpnij) , nldit_crs (jpnij) , nleit_crs (jpnij),   &
+         &      nimppt_full(jpnij) , nlcit_full(jpnij) , nldit_full(jpnij) , nleit_full(jpnij),   &
+                njmppt_crs (jpnij) , nlcjt_crs (jpnij) , nldjt_crs (jpnij) , nlejt_crs (jpnij),   &
+         &      njmppt_full(jpnij) , nlcjt_full(jpnij) , nldjt_full(jpnij) , nlejt_full(jpnij)  , STAT=ierr(15) )
+   
+      crs_dom_alloc = MAXVAL(ierr)
+      !
+   END FUNCTION crs_dom_alloc
+
+
+   INTEGER FUNCTION crs_dom_alloc2()
+      !!-------------------------------------------------------------------
+      !!                     *** FUNCTION crs_dom_alloc ***
+      !!  ** Purpose :   Allocate public crs arrays  
+      !!-------------------------------------------------------------------
+      !! Local variables
+      INTEGER, DIMENSION(1) :: ierr
+
+      ierr(:) = 0
+      
+      ALLOCATE( mjs_crs(nlej_crs) , mje_crs(nlej_crs), mis_crs(nlei_crs) , mie_crs(nlei_crs), STAT=ierr(1) )
+      crs_dom_alloc2 = MAXVAL(ierr)
+
+   END FUNCTION crs_dom_alloc2
+
+
+   SUBROUTINE dom_grid_glo
+      !!--------------------------------------------------------------------
+      !!                       ***  MODULE dom_grid_glo  ***
+      !!
+      !! ** Purpose : +Return back to parent grid domain 
+      !!---------------------------------------------------------------------
+
+      !                         Return to parent grid domain
+      jpi    = jpi_full
+      jpj    = jpj_full
+      jpim1  = jpim1_full
+      jpjm1  = jpjm1_full
+      jperio = nperio_full
+
+      npolj  = npolj_full
+      jpiglo = jpiglo_full
+      jpjglo = jpjglo_full
+
+      nlci   = nlci_full
+      nlcj   = nlcj_full
+      nldi   = nldi_full
+      nldj   = nldj_full
+      nlei   = nlei_full
+      nlej   = nlej_full
+      nimpp  = nimpp_full
+      njmpp  = njmpp_full
+      
+      nlcit(:)  = nlcit_full(:)
+      nldit(:)  = nldit_full(:)
+      nleit(:)  = nleit_full(:)
+      nimppt(:) = nimppt_full(:)
+      nlcjt(:)  = nlcjt_full(:)
+      nldjt(:)  = nldjt_full(:)
+      nlejt(:)  = nlejt_full(:)
+      njmppt(:) = njmppt_full(:)
+
+   END SUBROUTINE dom_grid_glo
+
+
+   SUBROUTINE dom_grid_crs
+      !!--------------------------------------------------------------------
+      !!                       ***  MODULE dom_grid_crs  ***
+      !!
+      !! ** Purpose :  Save the parent grid information & Switch to coarse grid domain
+      !!---------------------------------------------------------------------
+      !
+      !                        Switch to coarse grid domain
+      jpi    = jpi_crs
+      jpj    = jpj_crs
+      jpim1  = jpi_crsm1
+      jpjm1  = jpj_crsm1
+      jperio = nperio_crs
+
+      npolj  = npolj_crs
+      jpiglo = jpiglo_crs
+      jpjglo = jpjglo_crs
+
+
+      nlci   = nlci_crs
+      nlcj   = nlcj_crs
+      nldi   = nldi_crs
+      nlei   = nlei_crs
+      nlej   = nlej_crs
+      nldj   = nldj_crs
+      nimpp  = nimpp_crs
+      njmpp  = njmpp_crs
+      
+      nlcit(:)  = nlcit_crs(:)
+      nldit(:)  = nldit_crs(:)
+      nleit(:)  = nleit_crs(:)
+      nimppt(:) = nimppt_crs(:)
+      nlcjt(:)  = nlcjt_crs(:)
+      nldjt(:)  = nldjt_crs(:)
+      nlejt(:)  = nlejt_crs(:)
+      njmppt(:) = njmppt_crs(:)
+      !
+   END SUBROUTINE dom_grid_crs
+   
+   !!======================================================================
+END MODULE crs
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdom.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdom.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdom.F90	(revision 14097)
@@ -0,0 +1,2274 @@
+MODULE crsdom
+   !!===================================================================
+   !!                  ***  crs.F90 ***
+   !!  Purpose: Interface for calculating quantities from a  
+   !!           higher-resolution grid for the coarse grid.
+   !!
+   !!  Method:  Given the user-defined reduction factor, 
+   !!           the averaging bins are set: 
+   !!           - nn_binref = 0, starting from the north 
+   !!           to the south in the model interior domain, 
+   !!           in this way the north fold and redundant halo cells  
+   !!           could be handled in a consistent manner and 
+   !!           the irregularities of bin size can be handled
+   !!           more naturally by the presence of land
+   !!           in the southern boundary.  Thus the southernmost bin 
+   !!           could be of an irregular bin size.
+   !!           Information on the parent grid is retained, specifically,
+   !!           each coarse grid cell's volume and ocean surface 
+   !!           at the faces, relative to the parent grid.
+   !!           - nn_binref = 1 (not yet available), starting
+   !!           at a centralized bin at the equator, being only
+   !!           truly centered for odd-numbered j-direction reduction 
+   !!           factors.
+   !!  References:  Aumont, O., J.C. Orr, D. Jamous, P. Monfray
+   !!               O. Marti and G. Madec, 1998. A degradation 
+   !!               approach to accelerate simulations to steady-state 
+   !!               in a 3-D tracer transport model of the global ocean.
+   !!               Climate Dynamics, 14:101-116.
+   !!  History: 
+   !!       Original.   May 2012.  (J. Simeon, C. Calone, G. Madec, C. Ethe)
+   !!===================================================================
+   USE dom_oce        ! ocean space and time domain and to get jperio
+   USE crs            ! domain for coarse grid
+   !
+   USE in_out_manager 
+   USE par_kind
+   USE crslbclnk
+   USE lib_mpp
+
+   IMPLICIT NONE
+
+   PRIVATE 
+
+   PUBLIC crs_dom_ope
+   PUBLIC crs_dom_e3, crs_dom_sfc, crs_dom_msk, crs_dom_hgr, crs_dom_coordinates
+   PUBLIC crs_dom_facvol, crs_dom_def, crs_dom_bat
+
+   INTERFACE crs_dom_ope
+      MODULE PROCEDURE crs_dom_ope_3d, crs_dom_ope_2d
+   END INTERFACE
+
+   REAL(wp) :: r_inf = 1e+36
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE crs_dom_msk
+      
+      INTEGER  ::  ji, jj, jk                   ! dummy loop indices
+      INTEGER  ::  ijie,ijis,ijje,ijjs,ij,je_2
+      REAL(wp) ::  zmask
+      
+      ! Initialize
+
+      tmask_crs(:,:,:) = 0.0
+      vmask_crs(:,:,:) = 0.0
+      umask_crs(:,:,:) = 0.0
+      fmask_crs(:,:,:) = 0.0
+  
+            
+      IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+         IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+            je_2 = mje_crs(2)   ;  ij = je_2
+         ENDIF
+      ELSE
+         je_2 = mje_crs(2)      ;  ij = mjs_crs(2) 
+      ENDIF
+      DO jk = 1, jpkm1
+         DO ji = 2, nlei_crs  
+            ijis = mis_crs(ji)  ;  ijie = mie_crs(ji)    
+            !          
+            zmask = 0.0
+            zmask = SUM( tmask(ijis:ijie,ij:je_2,jk) ) 
+            IF ( zmask > 0.0 ) tmask_crs(ji,2,jk) = 1.0
+               
+            zmask = 0.0
+            zmask = SUM( vmask(ijis:ijie,je_2     ,jk) )  
+            IF ( zmask > 0.0 ) vmask_crs(ji,2,jk) = 1.0
+               
+            zmask = 0.0
+            zmask = SUM(umask(ijie,ij:je_2,jk))   
+            IF ( zmask > 0.0 ) umask_crs(ji,2,jk) = 1.0
+               
+            fmask_crs(ji,je_2,jk) = fmask(ijie,2,jk)
+         ENDDO
+      ENDDO
+      !
+      DO jk = 1, jpkm1
+         DO ji = 2, nlei_crs  
+            ijis = mis_crs(ji)     ;   ijie = mie_crs(ji)       
+            DO jj = 3, nlej_crs
+               ijjs = mjs_crs(jj)  ;   ijje = mje_crs(jj)
+                          
+               zmask = 0.0
+               zmask = SUM( tmask(ijis:ijie,ijjs:ijje,jk) ) 
+               IF ( zmask > 0.0 ) tmask_crs(ji,jj,jk) = 1.0
+               
+               zmask = 0.0
+               zmask = SUM( vmask(ijis:ijie,ijje     ,jk) )  
+               IF ( zmask > 0.0 ) vmask_crs(ji,jj,jk) = 1.0
+               
+               zmask = 0.0
+               zmask = SUM( umask(ijie     ,ijjs:ijje,jk) )  
+               IF ( zmask > 0.0 ) umask_crs(ji,jj,jk) = 1.0
+               
+               fmask_crs(ji,jj,jk) = fmask(ijie,ijje,jk)  
+            ENDDO
+         ENDDO
+      ENDDO
+
+      !
+      CALL crs_lbc_lnk( tmask_crs, 'T', 1.0 )
+      CALL crs_lbc_lnk( vmask_crs, 'V', 1.0 )
+      CALL crs_lbc_lnk( umask_crs, 'U', 1.0 )
+      CALL crs_lbc_lnk( fmask_crs, 'F', 1.0 )
+      !
+   END SUBROUTINE crs_dom_msk
+
+
+   SUBROUTINE crs_dom_coordinates( p_gphi, p_glam, cd_type, p_gphi_crs, p_glam_crs )
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crs_coordinates ***
+      !! ** Purpose :  Determine the coordinates for the coarse grid
+      !! 
+      !! ** Method  :  From the parent grid subset, search for the central
+      !!               point.  For an odd-numbered reduction factor,
+      !!               the coordinate will be that of the central T-cell.
+      !!               For an even-numbered reduction factor, of a non-square
+      !!               coarse grid box, the coordinate will be that of 
+      !!               the east or north face or more likely.  For a square
+      !!               coarse grid box, the coordinate will be that of
+      !!               the central f-corner.
+      !!
+      !! ** Input   :  p_gphi = parent grid gphi[t|u|v|f]
+      !!               p_glam = parent grid glam[t|u|v|f]
+      !!               cd_type  = grid type (T,U,V,F)
+      !! ** Output  :  p_gphi_crs = coarse grid gphi[t|u|v|f]
+      !!               p_glam_crs = coarse grid glam[t|u|v|f]
+      !!              
+      !! History. 1 Jun.
+      !!----------------------------------------------------------------
+      !! Arguments
+      REAL(wp), DIMENSION(jpi,jpj)        , INTENT(in)  :: p_gphi  ! Parent grid latitude
+      REAL(wp), DIMENSION(jpi,jpj)        , INTENT(in)  :: p_glam  ! Parent grid longitude
+      CHARACTER(len=1),                     INTENT(in)  :: cd_type   ! grid type (T,U,V,F) 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs), INTENT(out) :: p_gphi_crs  ! Coarse grid latitude
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs), INTENT(out) :: p_glam_crs  ! Coarse grid longitude
+
+      !! Local variables
+      INTEGER :: ji, jj, jk                   ! dummy loop indices
+      INTEGER :: ijis, ijjs
+
+  
+      SELECT CASE ( cd_type )
+         CASE ( 'T' )
+            DO jj =  nldj_crs, nlej_crs
+               ijjs = mjs_crs(jj) + mybinctr
+               DO ji = 2, nlei_crs
+                  ijis = mis_crs(ji) + mxbinctr 
+                  p_gphi_crs(ji,jj) = p_gphi(ijis,ijjs)
+                  p_glam_crs(ji,jj) = p_glam(ijis,ijjs)
+               ENDDO
+            ENDDO
+         CASE ( 'U' )
+            DO jj =  nldj_crs, nlej_crs
+               ijjs = mjs_crs(jj) + mybinctr                  
+               DO ji = 2, nlei_crs
+                  ijis = mis_crs(ji)
+                  p_gphi_crs(ji,jj) = p_gphi(ijis,ijjs)
+                  p_glam_crs(ji,jj) = p_glam(ijis,ijjs)
+               ENDDO
+            ENDDO
+         CASE ( 'V' )
+            DO jj =  nldj_crs, nlej_crs
+               ijjs = mjs_crs(jj)
+               DO ji = 2, nlei_crs
+                  ijis = mis_crs(ji) + mxbinctr 
+                  p_gphi_crs(ji,jj) = p_gphi(ijis,ijjs)
+                  p_glam_crs(ji,jj) = p_glam(ijis,ijjs)
+               ENDDO
+            ENDDO
+         CASE ( 'F' )
+            DO jj =  nldj_crs, nlej_crs
+               ijjs = mjs_crs(jj)
+               DO ji = 2, nlei_crs
+                  ijis = mis_crs(ji)
+                  p_gphi_crs(ji,jj) = p_gphi(ijis,ijjs)
+                  p_glam_crs(ji,jj) = p_glam(ijis,ijjs)
+               ENDDO
+            ENDDO
+      END SELECT
+
+      ! Retroactively add back the boundary halo cells.
+      CALL crs_lbc_lnk( p_gphi_crs, cd_type, 1.0 )
+      CALL crs_lbc_lnk( p_glam_crs, cd_type, 1.0 )
+         
+      ! Fill up jrow=1 which is zeroed out or not handled by lbc_lnk and lbc_nfd
+      SELECT CASE ( cd_type )
+         CASE ( 'T', 'V' )
+            DO ji = 2, nlei_crs
+               ijis = mis_crs(ji) + mxbinctr 
+               p_gphi_crs(ji,1) = p_gphi(ijis,1)
+               p_glam_crs(ji,1) = p_glam(ijis,1)
+            ENDDO
+         CASE ( 'U', 'F' )
+            DO ji = 2, nlei_crs
+               ijis = mis_crs(ji) 
+               p_gphi_crs(ji,1) = p_gphi(ijis,1)
+               p_glam_crs(ji,1) = p_glam(ijis,1)
+            ENDDO
+      END SELECT
+      !
+   END SUBROUTINE crs_dom_coordinates
+
+  SUBROUTINE crs_dom_hgr( p_e1, p_e2, cd_type, p_e1_crs, p_e2_crs )
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crs_dom_hgr ***
+      !!
+      !! ** Purpose :  Get coarse grid horizontal scale factors and unmasked fraction
+      !!
+      !! ** Method  :  For grid types T,U,V,Fthe 2D scale factors of 
+      !!               the coarse grid are the sum of the east or north faces of the 
+      !!               parent grid subset comprising the coarse grid box.     
+      !!               - e1,e2 Scale factors
+      !!                 Valid arguments: 
+      !! ** Inputs  : p_e1, p_e2  = parent grid e1 or e2 (t,u,v,f)
+      !!              cd_type     = grid type (T,U,V,F) for scale factors; for velocities (U or V)
+      !! ** Outputs : p_e1_crs, p_e2_crs  = parent grid e1 or e2 (t,u,v,f)
+      !!
+      !! History.     4 Jun.  Write for WGT and scale factors only
+      !!----------------------------------------------------------------
+      !! 
+      !!  Arguments
+      REAL(wp), DIMENSION(jpi,jpj)        , INTENT(in)  :: p_e1     ! Parent grid U,V scale factors (e1)
+      REAL(wp), DIMENSION(jpi,jpj)        , INTENT(in)  :: p_e2     ! Parent grid U,V scale factors (e2)
+      CHARACTER(len=1)                    , INTENT(in)  :: cd_type  ! grid type U,V 
+
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs), INTENT(out) :: p_e1_crs ! Coarse grid box 2D quantity
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs), INTENT(out) :: p_e2_crs ! Coarse grid box 2D quantity
+
+      !! Local variables
+      INTEGER :: ji, jj, jk     ! dummy loop indices
+      INTEGER :: ijie,ijje,ijrs
+  
+      !!----------------------------------------------------------------  
+      ! Initialize      
+
+      DO jk = 1, jpk    
+         DO ji = 2, nlei_crs
+            ijie = mie_crs(ji)
+            DO jj = nldj_crs, nlej_crs
+               ijje = mje_crs(jj)   ;   ijrs =  mje_crs(jj) - mjs_crs(jj)
+               ! Only for a factro 3 coarsening
+               SELECT CASE ( cd_type )
+                   CASE ( 'T' )
+                      IF( ijrs == 0 .OR. ijrs == 1 ) THEN
+                        ! Si à la frontière sud on a pas assez de maille de la grille mère
+                         p_e1_crs(ji,jj) = p_e1(ijie-1,ijje) * nn_factx
+                         p_e2_crs(ji,jj) = p_e2(ijie-1,ijje) * nn_facty
+                      ELSE
+                         p_e1_crs(ji,jj) = p_e1(ijie-1,ijje-1) * nn_factx
+                         p_e2_crs(ji,jj) = p_e2(ijie-1,ijje-1) * nn_facty
+                      ENDIF
+                   CASE ( 'U' )
+                      IF( ijrs == 0 .OR. ijrs == 1 ) THEN
+                         ! Si à la frontière sud on a pas assez de maille de la grille mère
+                         p_e1_crs(ji,jj) = p_e1(ijie,ijje) * nn_factx                            
+                         p_e2_crs(ji,jj) = p_e2(ijie,ijje) * nn_facty
+                      ELSE
+                         p_e1_crs(ji,jj) = p_e1(ijie,ijje-1) * nn_factx
+                         p_e2_crs(ji,jj) = p_e2(ijie,ijje-1) * nn_facty
+                      ENDIF
+                   CASE ( 'V' )
+                         p_e1_crs(ji,jj) = p_e1(ijie-1,ijje) * nn_factx                            
+                         p_e2_crs(ji,jj) = p_e2(ijie-1,ijje) * nn_facty
+                   CASE ( 'F' )
+                         p_e1_crs(ji,jj) = p_e1(ijie,ijje) * nn_factx                            
+                         p_e2_crs(ji,jj) = p_e2(ijie,ijje) * nn_facty
+               END SELECT
+            ENDDO
+         ENDDO
+      ENDDO
+
+      CALL crs_lbc_lnk( p_e1_crs, cd_type, 1.0, pfillval=1.0 )
+      CALL crs_lbc_lnk( p_e2_crs, cd_type, 1.0, pfillval=1.0 )
+
+   END SUBROUTINE crs_dom_hgr
+
+
+   SUBROUTINE crs_dom_facvol( p_mask, cd_type, p_e1, p_e2, p_e3, p_fld1_crs, p_fld2_crs )
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crsfun_wgt ***
+      !! ** Purpose :  Three applications.
+      !!               1) SUM. Get coarse grid horizontal scale factors and unmasked fraction
+      !!               2) VOL. Get coarse grid box volumes
+      !!               3) WGT. Weighting multiplier for volume-weighted and/or
+      !!                       area-weighted averages.
+      !!                       Weights (i.e. the denominator) calculated here 
+      !!                       to avoid IF-tests and division.
+      !! ** Method  :  1) SUM.  For grid types T,U,V,F (and W) the 2D scale factors of 
+      !!               the coarse grid are the sum of the east or north faces of the 
+      !!               parent grid subset comprising the coarse grid box.  
+      !!               The fractions of masked:total surface (3D) on the east, 
+      !!               north and top faces is, optionally, also output.
+      !!               - Top face area sum
+      !!                 Valid arguments: cd_type, cd_op='W', p_pmask, p_e1, p_e2 
+      !!               - Top face ocean surface fraction
+      !!                 Valid arguments: cd_type, cd_op='W', p_pmask, p_e1, p_e2       
+      !!               - e1,e2 Scale factors
+      !!                 Valid arguments: 
+      !!               2) VOL.  For grid types W and T, the coarse grid box
+      !!               volumes are output. Also optionally, the fraction of  
+      !!               masked:total volume of the parent grid subset is output (i.e. facvol).
+      !!               3) WGT. Based on the grid type, the denominator is pre-determined here to  
+      !!               perform area- or volume- weighted averages, 
+      !!               to avoid IF-tests and divisions.
+      !! ** Inputs  : p_e1, p_e2  = parent grid e1 or e2 (t,u,v,f)
+      !!              p_pmask     = parent grid mask (T,U,V,F) 
+      !!              cd_type     = grid type (T,U,V,F) for scale factors; for velocities (U or V)
+      !!              cd_op       = applied operation (SUM, VOL, WGT)
+      !!              p_e3      = (Optional) parent grid vertical level thickness (e3u or e3v)
+      !! ** Outputs : p_cfield2d_1 = (Optional) 2D field on coarse grid
+      !!              p_cfield2d_2 = (Optional) 2D field on coarse grid
+      !!              p_cfield3d_1 = (Optional) 3D field on coarse grid
+      !!              p_cfield3d_2 = (Optional) 3D field on coarse grid
+      !!
+      !! History.     4 Jun.  Write for WGT and scale factors only
+      !!----------------------------------------------------------------
+      CHARACTER(len=1),                         INTENT(in   ) ::   cd_type    ! grid type U,V 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        , INTENT(in   ) ::   p_mask     ! Parent grid U,V mask
+      REAL(wp), DIMENSION(jpi,jpj)            , INTENT(in   ) ::   p_e1       ! Parent grid U,V scale factors (e1)
+      REAL(wp), DIMENSION(jpi,jpj)            , INTENT(in   ) ::   p_e2       ! Parent grid U,V scale factors (e2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        , INTENT(in   ) ::   p_e3       ! Parent grid vertical level thickness (e3u, e3v)
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(  out) ::   p_fld1_crs ! Coarse grid box 3D quantity 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(  out) ::   p_fld2_crs ! Coarse grid box 3D quantity 
+      !
+      INTEGER  ::   ji, jj, jk , ii, ij, je_2
+      REAL(wp) ::   zdAm
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zvol, zmask      
+      !!----------------------------------------------------------------  
+      !
+      !
+      p_fld1_crs(:,:,:) = 0._wp
+      p_fld2_crs(:,:,:) = 0._wp
+
+      DO jk = 1, jpk
+         zvol(:,:,jk) =  p_e1(:,:) * p_e2(:,:) * p_e3(:,:,jk) 
+      END DO
+
+      zmask(:,:,:) = 0._wp
+      IF( cd_type == 'W' ) THEN
+         zmask(:,:,1) = p_mask(:,:,1) 
+         DO jk = 2, jpk
+            zmask(:,:,jk) = p_mask(:,:,jk-1) 
+         ENDDO
+      ELSE
+         DO jk = 1, jpk
+             zmask(:,:,jk) = p_mask(:,:,jk) 
+         ENDDO
+      ENDIF
+
+      IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+         IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+            je_2 = mje_crs(2)
+            DO jk = 1, jpk           
+               DO ji = nistr, niend, nn_factx
+                  ii   = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                  p_fld1_crs(ii,2,jk) =  zvol(ji,je_2  ,jk) + zvol(ji+1,je_2  ,jk) + zvol(ji+2,je_2  ,jk)  &
+                     &                 + zvol(ji,je_2-1,jk) + zvol(ji+1,je_2-1,jk) + zvol(ji+2,je_2-1,jk) 
+                  !
+                  zdAm =  zvol(ji  ,je_2,jk) * zmask(ji  ,je_2,jk)  &
+                    &   + zvol(ji+1,je_2,jk) * zmask(ji+1,je_2,jk)  &
+                    &   + zvol(ji+2,je_2,jk) * zmask(ji+2,je_2,jk) 
+                  ! 
+                  p_fld2_crs(ii,2,jk) = zdAm / p_fld1_crs(ii,2,jk) 
+               ENDDO
+            ENDDO
+         ENDIF
+      ELSE
+         je_2 = mjs_crs(2)
+         DO jk = 1, jpk           
+            DO ji = nistr, niend, nn_factx
+               ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+               p_fld1_crs(ii,2,jk) =  zvol(ji,je_2  ,jk) + zvol(ji+1,je_2  ,jk) + zvol(ji+2,je_2  ,jk)  &
+                   &                + zvol(ji,je_2+1,jk) + zvol(ji+1,je_2+1,jk) + zvol(ji+2,je_2+1,jk)  &
+                   &                + zvol(ji,je_2+2,jk) + zvol(ji+1,je_2+2,jk) + zvol(ji+2,je_2+2,jk)  
+              !
+               zdAm = zvol(ji  ,je_2  ,jk) * zmask(ji  ,je_2  ,jk)  &
+                 &  + zvol(ji+1,je_2  ,jk) * zmask(ji+1,je_2  ,jk)  &
+                 &  + zvol(ji+2,je_2  ,jk) * zmask(ji+2,je_2  ,jk)  &
+                 &  + zvol(ji  ,je_2+1,jk) * zmask(ji  ,je_2+1,jk)  &
+                 &  + zvol(ji+1,je_2+1,jk) * zmask(ji+1,je_2+1,jk)  &
+                 &  + zvol(ji+2,je_2+1,jk) * zmask(ji+2,je_2+1,jk)  &
+                 &  + zvol(ji  ,je_2+2,jk) * zmask(ji  ,je_2+2,jk)  &
+                 &  + zvol(ji+1,je_2+2,jk) * zmask(ji+1,je_2+2,jk)  &
+                 &  + zvol(ji+2,je_2+2,jk) * zmask(ji+2,je_2+2,jk)
+                 ! 
+                 p_fld2_crs(ii,2,jk) = zdAm / p_fld1_crs(ii,2,jk) 
+            ENDDO
+         ENDDO
+      ENDIF
+
+      DO jk = 1, jpk           
+         DO jj  = njstr, njend, nn_facty
+            DO ji = nistr, niend, nn_factx
+               ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+               ij  = ( jj - njstr ) * rfacty_r + 3
+               !
+               p_fld1_crs(ii,ij,jk) =  zvol(ji,jj  ,jk) + zvol(ji+1,jj  ,jk) + zvol(ji+2,jj  ,jk)  &
+                   &                 + zvol(ji,jj+1,jk) + zvol(ji+1,jj+1,jk) + zvol(ji+2,jj+1,jk)  &
+                   &                 + zvol(ji,jj+2,jk) + zvol(ji+1,jj+2,jk) + zvol(ji+2,jj+2,jk) 
+               !
+               zdAm =  zvol(ji  ,jj  ,jk) * zmask(ji  ,jj  ,jk)  &
+                 &   + zvol(ji+1,jj  ,jk) * zmask(ji+1,jj  ,jk)  &
+                 &   + zvol(ji+2,jj  ,jk) * zmask(ji+2,jj  ,jk)  &
+                 &   + zvol(ji  ,jj+1,jk) * zmask(ji  ,jj+1,jk)  &
+                 &   + zvol(ji+1,jj+1,jk) * zmask(ji+1,jj+1,jk)  &
+                 &   + zvol(ji+2,jj+1,jk) * zmask(ji+2,jj+1,jk)  &
+                 &   + zvol(ji  ,jj+2,jk) * zmask(ji  ,jj+2,jk)  &
+                 &   + zvol(ji+1,jj+2,jk) * zmask(ji+1,jj+2,jk)  &
+                 &   + zvol(ji+2,jj+2,jk) * zmask(ji+2,jj+2,jk)
+                 ! 
+                p_fld2_crs(ii,ij,jk) = zdAm / p_fld1_crs(ii,ij,jk) 
+            ENDDO
+         ENDDO
+      ENDDO
+      !                                             !  Retroactively add back the boundary halo cells.
+      CALL crs_lbc_lnk( p_fld1_crs, cd_type, 1.0 ) 
+      CALL crs_lbc_lnk( p_fld2_crs, cd_type, 1.0 ) 
+      !
+      !
+   END SUBROUTINE crs_dom_facvol
+
+
+   SUBROUTINE crs_dom_ope_3d( p_fld, cd_op, cd_type, p_mask, p_fld_crs, p_e12, p_e3, p_surf_crs, p_mask_crs, psgn )
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crsfun_UV ***
+      !! ** Purpose :  Average, area-weighted, of U or V on the east and north faces 
+      !!
+      !! ** Method  :  The U and V velocities (3D) are determined as the area-weighted averages
+      !!               on the east and north faces, respectively,
+      !!               of the parent grid subset comprising the coarse grid box. 
+      !!               In the case of the V and F grid, the last jrow minus 1 is spurious.
+      !! ** Inputs  : p_e1_e2     = parent grid e1 or e2 (t,u,v,f)
+      !!              cd_type     = grid type (T,U,V,F) for scale factors; for velocities (U or V)
+      !!              psgn        = sign change over north fold (See lbclnk.F90)
+      !!              p_pmask     = parent grid mask (T,U,V,F) for scale factors; 
+      !!                                       for velocities (U or V)
+      !!              p_e3      = parent grid vertical level thickness (e3u or e3v)
+      !!              p_pfield    = U or V on the parent grid
+      !!              p_surf_crs  = (Optional) Coarse grid weight for averaging
+      !! ** Outputs : p_cfield3d = 3D field on coarse grid
+      !!
+      !! History.  29 May.  completed draft.
+      !!            4 Jun.  Revision for WGT
+      !!            5 Jun.  Streamline for area-weighted average only ; separate scale factor and weights.
+      !!----------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in)           :: p_fld      ! T, U, V or W on parent grid
+      CHARACTER(len=3),                         INTENT(in)           :: cd_op      ! Operation SUM, MAX or MIN
+      CHARACTER(len=1),                         INTENT(in)           :: cd_type    ! grid type U,V 
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in)           :: p_mask     ! Parent grid T,U,V mask
+      REAL(wp), DIMENSION(jpi,jpj),             INTENT(in), OPTIONAL :: p_e12      ! Parent grid T,U,V scale factors (e1 or e2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in), OPTIONAL :: p_e3       ! Parent grid vertical level thickness (e3u, e3v)
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(in), OPTIONAL :: p_surf_crs ! Coarse grid area-weighting denominator    
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(in), OPTIONAL :: p_mask_crs ! Coarse grid T,U,V maska
+      REAL(wp),                                 INTENT(in)           :: psgn       ! sign 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(  out)        :: p_fld_crs  ! Coarse grid box 3D quantity 
+      !
+      INTEGER  ::   ji, jj, jk 
+      INTEGER  ::   ii, ij, ijie, ijje, je_2
+      REAL(wp) ::   zflcrs, zsfcrs   
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zsurf, zsurfmsk, zmask  
+      !!----------------------------------------------------------------  
+      !
+      p_fld_crs(:,:,:) = 0._wp
+      !
+      SELECT CASE ( cd_op )
+      !
+      CASE ( 'VOL' )
+         !
+         ALLOCATE( zsurf(jpi,jpj,jpk), zsurfmsk(jpi,jpj,jpk) )
+         !   
+         SELECT CASE ( cd_type )
+         !   
+         CASE( 'T', 'W' )
+               IF( cd_type == 'T' ) THEN
+                     DO jk = 1, jpk
+                        zsurf   (:,:,jk) =  p_e12(:,:) * p_e3(:,:,jk) *  p_mask(:,:,jk) 
+                        zsurfmsk(:,:,jk) =  zsurf(:,:,jk) 
+                    ENDDO
+                  ELSE
+                     zsurf   (:,:,1) =  p_e12(:,:) * p_e3(:,:,1)
+                     zsurfmsk(:,:,1) =  zsurf(:,:,1) *  p_mask(:,:,1) 
+                     DO jk = 2, jpk
+                        zsurf   (:,:,jk) =  p_e12(:,:) * p_e3(:,:,jk)
+                        zsurfmsk(:,:,jk) =  zsurf(:,:,jk) * p_mask(:,:,jk-1) 
+                     ENDDO
+                  ENDIF
+         
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2       
+                              zflcrs =  p_fld(ji  ,je_2,jk) * zsurfmsk(ji  ,je_2,jk)   &
+                                &     + p_fld(ji+1,je_2,jk) * zsurfmsk(ji+1,je_2,jk)   &
+                                &     + p_fld(ji+2,je_2,jk) * zsurfmsk(ji+2,je_2,jk) 
+ 
+                              zsfcrs =  zsurf(ji,je_2,jk) + zsurf(ji+1,je_2,jk) + zsurf(ji+2,je_2,jk) 
+                              !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                              IF( zsfcrs /= 0.0 )  p_fld_crs(ii,2,jk) = zflcrs / zsfcrs
+                           ENDDO
+                        ENDDO
+                     ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           zflcrs =  p_fld(ji  ,je_2  ,jk) * zsurfmsk(ji  ,je_2  ,jk) &
+                             &     + p_fld(ji+1,je_2  ,jk) * zsurfmsk(ji+1,je_2  ,jk) &
+                             &     + p_fld(ji+2,je_2  ,jk) * zsurfmsk(ji+2,je_2  ,jk) &
+                             &     + p_fld(ji  ,je_2+1,jk) * zsurfmsk(ji  ,je_2+1,jk) &
+                             &     + p_fld(ji+1,je_2+1,jk) * zsurfmsk(ji+1,je_2+1,jk) &
+                             &     + p_fld(ji+2,je_2+1,jk) * zsurfmsk(ji+2,je_2+1,jk) &
+                             &     + p_fld(ji  ,je_2+2,jk) * zsurfmsk(ji  ,je_2+2,jk) &
+                             &     + p_fld(ji+1,je_2+2,jk) * zsurfmsk(ji+1,je_2+2,jk) &
+                             &     + p_fld(ji+2,je_2+2,jk) * zsurfmsk(ji+2,je_2+2,jk) 
+
+                           zsfcrs =  zsurf(ji,je_2  ,jk) + zsurf(ji+1,je_2  ,jk) + zsurf(ji+2,je_2  ,jk) &
+                             &     + zsurf(ji,je_2+1,jk) + zsurf(ji+1,je_2+1,jk) + zsurf(ji+2,je_2+1,jk) &
+                             &     + zsurf(ji,je_2+2,jk) + zsurf(ji+1,je_2+2,jk) + zsurf(ji+2,je_2+2,jk) 
+                            !
+                            p_fld_crs(ii,2,jk) = zflcrs
+                            IF( zsfcrs /= 0.0 )  p_fld_crs(ii,2,jk) = zflcrs / zsfcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij = ( jj - njstr ) * rfacty_r + 3
+                           zflcrs =  p_fld(ji  ,jj  ,jk) * zsurfmsk(ji  ,jj  ,jk) &
+                             &     + p_fld(ji+1,jj  ,jk) * zsurfmsk(ji+1,jj  ,jk) &
+                             &     + p_fld(ji+2,jj  ,jk) * zsurfmsk(ji+2,jj  ,jk) &
+                             &     + p_fld(ji  ,jj+1,jk) * zsurfmsk(ji  ,jj+1,jk) &
+                             &     + p_fld(ji+1,jj+1,jk) * zsurfmsk(ji+1,jj+1,jk) &
+                             &     + p_fld(ji+2,jj+1,jk) * zsurfmsk(ji+2,jj+1,jk) &
+                             &     + p_fld(ji  ,jj+2,jk) * zsurfmsk(ji  ,jj+2,jk) &
+                             &     + p_fld(ji+1,jj+2,jk) * zsurfmsk(ji+1,jj+2,jk) &
+                             &     + p_fld(ji+2,jj+2,jk) * zsurfmsk(ji+2,jj+2,jk) 
+
+                           zsfcrs =  zsurf(ji,jj  ,jk) + zsurf(ji+1,jj  ,jk) + zsurf(ji+2,jj  ,jk) &
+                             &     + zsurf(ji,jj+1,jk) + zsurf(ji+1,jj+1,jk) + zsurf(ji+2,jj+1,jk) &
+                             &     + zsurf(ji,jj+2,jk) + zsurf(ji+1,jj+2,jk) + zsurf(ji+2,jj+2,jk) 
+                            !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           IF( zsfcrs /= 0.0 )  p_fld_crs(ii,ij,jk) = zflcrs / zsfcrs
+                        ENDDO      
+                     ENDDO
+                  ENDDO  
+               CASE DEFAULT
+                  CALL ctl_stop( 'STOP', 'error from crs_dom_ope_3d, you should not be there...' )
+               END SELECT
+
+              DEALLOCATE( zsurf, zsurfmsk )
+
+         CASE ( 'SUM' )
+         
+            ALLOCATE( zsurfmsk(jpi,jpj,jpk) )
+
+            SELECT CASE ( cd_type )
+              CASE( 'W' )
+                  IF( PRESENT( p_e3 ) ) THEN
+                    zsurfmsk(:,:,1) =  p_e12(:,:) * p_e3(:,:,1) * p_mask(:,:,1) 
+                    DO jk = 2, jpk
+                      zsurfmsk(:,:,jk) =  p_e12(:,:) * p_e3(:,:,jk) * p_mask(:,:,jk-1) 
+                    ENDDO
+                 ELSE
+                    zsurfmsk(:,:,1) =  p_e12(:,:) * p_mask(:,:,1) 
+                    DO jk = 2, jpk
+                      zsurfmsk(:,:,jk) =  p_e12(:,:) * p_mask(:,:,jk-1) 
+                    ENDDO
+                 ENDIF
+              CASE DEFAULT
+                 IF( PRESENT( p_e3 ) ) THEN
+                    DO jk = 1, jpk
+                      zsurfmsk(:,:,jk) =  p_e12(:,:) * p_e3(:,:,jk) * p_mask(:,:,jk) 
+                    ENDDO
+                 ELSE
+                    DO jk = 1, jpk
+                      zsurfmsk(:,:,jk) =  p_e12(:,:) * p_mask(:,:,jk) 
+                    ENDDO
+                 ENDIF
+              END SELECT
+
+            SELECT CASE ( cd_type )
+            
+               CASE( 'T', 'W' )
+         
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2          
+                              zflcrs  =  p_fld(ji  ,je_2,jk) * zsurfmsk(ji  ,je_2,jk) &
+                                &      + p_fld(ji+1,je_2,jk) * zsurfmsk(ji+1,je_2,jk) &
+                                &      + p_fld(ji+2,je_2,jk) * zsurfmsk(ji+2,je_2,jk) 
+                               !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                           ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           zflcrs  =  p_fld(ji  ,je_2  ,jk) * zsurfmsk(ji  ,je_2  ,jk)  &
+                             &      + p_fld(ji+1,je_2  ,jk) * zsurfmsk(ji+1,je_2  ,jk)  &
+                             &      + p_fld(ji+2,je_2  ,jk) * zsurfmsk(ji+2,je_2  ,jk)  &
+                             &      + p_fld(ji  ,je_2+1,jk) * zsurfmsk(ji  ,je_2+1,jk)  &
+                             &      + p_fld(ji+1,je_2+1,jk) * zsurfmsk(ji+1,je_2+1,jk)  &
+                             &      + p_fld(ji+2,je_2+1,jk) * zsurfmsk(ji+2,je_2+1,jk)  &
+                             &      + p_fld(ji  ,je_2+2,jk) * zsurfmsk(ji  ,je_2+2,jk)  &
+                             &      + p_fld(ji+1,je_2+2,jk) * zsurfmsk(ji+1,je_2+2,jk)  &
+                             &      + p_fld(ji+2,je_2+2,jk) * zsurfmsk(ji+2,je_2+2,jk)  
+                            !
+                            p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij  = ( jj - njstr ) * rfacty_r + 3
+                           zflcrs  =  p_fld(ji  ,jj  ,jk) * zsurfmsk(ji  ,jj  ,jk)  &
+                             &      + p_fld(ji+1,jj  ,jk) * zsurfmsk(ji+1,jj  ,jk)  &
+                             &      + p_fld(ji+2,jj  ,jk) * zsurfmsk(ji+2,jj  ,jk)  &
+                             &      + p_fld(ji  ,jj+1,jk) * zsurfmsk(ji  ,jj+1,jk)  &
+                             &      + p_fld(ji+1,jj+1,jk) * zsurfmsk(ji+1,jj+1,jk)  &
+                             &      + p_fld(ji+2,jj+1,jk) * zsurfmsk(ji+2,jj+1,jk)  &
+                             &      + p_fld(ji  ,jj+2,jk) * zsurfmsk(ji  ,jj+2,jk)  &
+                             &      + p_fld(ji+1,jj+2,jk) * zsurfmsk(ji+1,jj+2,jk)  &
+                             &      + p_fld(ji+2,jj+2,jk) * zsurfmsk(ji+2,jj+2,jk)  
+                            !
+                            p_fld_crs(ii,ij,jk) = zflcrs
+                            ! 
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+            
+               CASE( 'V' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                     ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        zflcrs  =  p_fld(ji  ,ijje,jk) * zsurfmsk(ji  ,ijje,jk) &
+                          &      + p_fld(ji+1,ijje,jk) * zsurfmsk(ji+1,ijje,jk) &
+                          &      + p_fld(ji+2,ijje,jk) * zsurfmsk(ji+2,ijje,jk) 
+                          !
+                        p_fld_crs(ii,2,jk) = zflcrs
+                     ENDDO
+                  ENDDO
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij   = ( jj - njstr ) * rfacty_r + 3
+                           ijje = mje_crs(ij)
+                           zflcrs  =  p_fld(ji  ,ijje,jk) * zsurfmsk(ji  ,ijje,jk) &
+                             &      + p_fld(ji+1,ijje,jk) * zsurfmsk(ji+1,ijje,jk) &
+                             &      + p_fld(ji+2,ijje,jk) * zsurfmsk(ji+2,ijje,jk) 
+                             !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           ! 
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+            
+               CASE( 'U' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2  
+                              ijie = mie_crs(ii)
+                              zflcrs  =  p_fld(ijie,je_2,jk) * zsurfmsk(ijie,je_2,jk)  
+                              p_fld_crs(ii,2,jk) = zflcrs
+                           ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           ijie = mie_crs(ii)
+                           zflcrs =  p_fld(ijie,je_2  ,jk) * zsurfmsk(ijie,je_2  ,jk)  &
+                             &     + p_fld(ijie,je_2+1,jk) * zsurfmsk(ijie,je_2+1,jk)  &
+                             &     + p_fld(ijie,je_2+2,jk) * zsurfmsk(ijie,je_2+2,jk) 
+
+                           p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                           ij   = ( jj - njstr ) * rfacty_r + 3
+                           ijie = mie_crs(ii)
+                           zflcrs =  p_fld(ijie,jj  ,jk) * zsurfmsk(ijie,jj  ,jk)  &
+                              &    + p_fld(ijie,jj+1,jk) * zsurfmsk(ijie,jj+1,jk)  &
+                              &    + p_fld(ijie,jj+2,jk) * zsurfmsk(ijie,jj+2,jk) 
+                             !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           ! 
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+
+              END SELECT
+
+              IF( PRESENT( p_surf_crs ) ) THEN
+                 WHERE ( p_surf_crs /= 0.0 ) p_fld_crs(:,:,:) = p_fld_crs(:,:,:) / p_surf_crs(:,:,:)
+              ENDIF
+
+              DEALLOCATE( zsurfmsk )
+
+         CASE ( 'MAX' )    !  search the max of unmasked grid cells
+
+            ALLOCATE( zmask(jpi,jpj,jpk) )
+
+            SELECT CASE ( cd_type )
+              CASE( 'W' )
+                  zmask(:,:,1) = p_mask(:,:,1) 
+                  DO jk = 2, jpk
+                     zmask(:,:,jk) = p_mask(:,:,jk-1) 
+                  ENDDO
+              CASE ( 'T' )
+                  DO jk = 1, jpk
+                     zmask(:,:,jk) = p_mask(:,:,jk) 
+                  ENDDO
+            END SELECT
+
+            SELECT CASE ( cd_type )
+            
+               CASE( 'T', 'W' )
+         
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2        
+                              zflcrs =  &
+                                & MAX( p_fld(ji  ,je_2,jk) * zmask(ji  ,je_2,jk) - ( 1.- zmask(ji  ,je_2,jk) ) * r_inf ,  &
+                                &      p_fld(ji+1,je_2,jk) * zmask(ji+1,je_2,jk) - ( 1.- zmask(ji+1,je_2,jk) ) * r_inf ,  &
+                                &      p_fld(ji+2,je_2,jk) * zmask(ji+2,je_2,jk) - ( 1.- zmask(ji+2,je_2,jk) ) * r_inf  )
+                              !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                           ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           zflcrs =  &
+                             & MAX( p_fld(ji  ,je_2  ,jk) * zmask(ji  ,je_2  ,jk) - ( 1.- zmask(ji  ,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2  ,jk) * zmask(ji+1,je_2  ,jk) - ( 1.- zmask(ji+1,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2  ,jk) * zmask(ji+2,je_2  ,jk) - ( 1.- zmask(ji+2,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,je_2+1,jk) * zmask(ji  ,je_2+1,jk) - ( 1.- zmask(ji  ,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2+1,jk) * zmask(ji+1,je_2+1,jk) - ( 1.- zmask(ji+1,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2+1,jk) * zmask(ji+2,je_2+1,jk) - ( 1.- zmask(ji+2,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,je_2+2,jk) * zmask(ji  ,je_2+2,jk) - ( 1.- zmask(ji  ,je_2+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2+2,jk) * zmask(ji+1,je_2+2,jk) - ( 1.- zmask(ji+1,je_2+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2+2,jk) * zmask(ji+2,je_2+2,jk) - ( 1.- zmask(ji+2,je_2+2,jk) ) * r_inf   )
+                           !
+                           p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij  = ( jj - njstr ) * rfacty_r + 3
+                           zflcrs =  &
+                             & MAX( p_fld(ji  ,jj  ,jk) * zmask(ji  ,jj  ,jk) - ( 1.- zmask(ji  ,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj  ,jk) * zmask(ji+1,jj  ,jk) - ( 1.- zmask(ji+1,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj  ,jk) * zmask(ji+2,jj  ,jk) - ( 1.- zmask(ji+2,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,jj+1,jk) * zmask(ji  ,jj+1,jk) - ( 1.- zmask(ji  ,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj+1,jk) * zmask(ji+1,jj+1,jk) - ( 1.- zmask(ji+1,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj+1,jk) * zmask(ji+2,jj+1,jk) - ( 1.- zmask(ji+2,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,jj+2,jk) * zmask(ji  ,jj+2,jk) - ( 1.- zmask(ji  ,jj+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj+2,jk) * zmask(ji+1,jj+2,jk) - ( 1.- zmask(ji+1,jj+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj+2,jk) * zmask(ji+2,jj+2,jk) - ( 1.- zmask(ji+2,jj+2,jk) ) * r_inf   )
+                           !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           !
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+            
+               CASE( 'V' )
+
+                 IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                      ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+
+                  DO jk = 1, jpk
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                        zflcrs = &
+                          & MAX( p_fld(ji  ,ijje,jk) * p_mask(ji  ,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                          &      p_fld(ji+1,ijje,jk) * p_mask(ji+1,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                          &      p_fld(ji+2,ijje,jk) * p_mask(ji+2,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf )
+                          !
+                        p_fld_crs(ii,2,jk) = zflcrs
+                     ENDDO
+                  ENDDO
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij  = ( jj - njstr ) * rfacty_r + 3
+                           ijje = mje_crs(ij)
+                           !                  
+                           zflcrs = &
+                             & MAX( p_fld(ji  ,ijje,jk) * p_mask(ji  ,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,ijje,jk) * p_mask(ji+1,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,ijje,jk) * p_mask(ji+2,ijje,jk) - ( 1.- p_mask(ji,ijje,jk) ) * r_inf )
+                           !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           !
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+
+            
+               CASE( 'U' )
+
+                 IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2  
+                              ijie = mie_crs(ii)
+                              zflcrs = p_fld(ijie,je_2,jk) * p_mask(ijie,je_2,jk) - ( 1.- p_mask(ijie,je_2,jk) ) * r_inf 
+                              !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                            ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           ijie = mie_crs(ii)
+                           zflcrs = &
+                             & MAX( p_fld(ijie,je_2  ,jk) * p_mask(ijie,je_2  ,jk) - ( 1.- p_mask(ijie,je_2,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,je_2+1,jk) * p_mask(ijie,je_2+1,jk) - ( 1.- p_mask(ijie,je_2,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,je_2+2,jk) * p_mask(ijie,je_2+2,jk) - ( 1.- p_mask(ijie,je_2,jk) ) * r_inf  )
+                            !
+                           p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                           ij   = ( jj - njstr ) * rfacty_r + 3
+                           ijie = mie_crs(ii)
+                           zflcrs =  &
+                             & MAX( p_fld(ijie,jj  ,jk) * p_mask(ijie,jj  ,jk) - ( 1.- p_mask(ijie,jj,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,jj+1,jk) * p_mask(ijie,jj+1,jk) - ( 1.- p_mask(ijie,jj,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,jj+2,jk) * p_mask(ijie,jj+2,jk) - ( 1.- p_mask(ijie,jj,jk) ) * r_inf  )
+                           ! 
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           ! 
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+
+              END SELECT
+
+              DEALLOCATE( zmask )
+
+         CASE ( 'MIN' )      !   Search the min of unmasked grid cells
+
+            ALLOCATE( zmask(jpi,jpj,jpk) )
+
+            SELECT CASE ( cd_type )
+              CASE( 'W' )
+                  zmask(:,:,1) = p_mask(:,:,1) 
+                  DO jk = 2, jpk
+                     zmask(:,:,jk) = p_mask(:,:,jk-1) 
+                  ENDDO
+              CASE ( 'T' )
+                  DO jk = 1, jpk
+                     zmask(:,:,jk) = p_mask(:,:,jk) 
+                  ENDDO
+            END SELECT
+
+            SELECT CASE ( cd_type )
+
+               CASE( 'T', 'W' )
+         
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2        
+                              zflcrs =  &
+                                & MIN( p_fld(ji  ,je_2,jk) * zmask(ji  ,je_2,jk) + ( 1.- zmask(ji  ,je_2,jk) ) * r_inf ,  &
+                                &      p_fld(ji+1,je_2,jk) * zmask(ji+1,je_2,jk) + ( 1.- zmask(ji+1,je_2,jk) ) * r_inf ,  &
+                                &      p_fld(ji+2,je_2,jk) * zmask(ji+2,je_2,jk) + ( 1.- zmask(ji+2,je_2,jk) ) * r_inf  )
+                              !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                           ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           zflcrs =  &
+                             & MIN( p_fld(ji  ,je_2  ,jk) * zmask(ji  ,je_2  ,jk) + ( 1.- zmask(ji  ,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2  ,jk) * zmask(ji+1,je_2  ,jk) + ( 1.- zmask(ji+1,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2  ,jk) * zmask(ji+2,je_2  ,jk) + ( 1.- zmask(ji+2,je_2  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,je_2+1,jk) * zmask(ji  ,je_2+1,jk) + ( 1.- zmask(ji  ,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2+1,jk) * zmask(ji+1,je_2+1,jk) + ( 1.- zmask(ji+1,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2+1,jk) * zmask(ji+2,je_2+1,jk) + ( 1.- zmask(ji+2,je_2+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,je_2+2,jk) * zmask(ji  ,je_2+2,jk) + ( 1.- zmask(ji  ,je_2+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,je_2+2,jk) * zmask(ji+1,je_2+2,jk) + ( 1.- zmask(ji+1,je_2+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,je_2+2,jk) * zmask(ji+2,je_2+2,jk) + ( 1.- zmask(ji+2,je_2+2,jk) ) * r_inf   )
+                           !
+                           p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij  = ( jj - njstr ) * rfacty_r + 3
+                           zflcrs =  &
+                             & MIN( p_fld(ji  ,jj  ,jk) * zmask(ji  ,jj  ,jk) + ( 1.- zmask(ji  ,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj  ,jk) * zmask(ji+1,jj  ,jk) + ( 1.- zmask(ji+1,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj  ,jk) * zmask(ji+2,jj  ,jk) + ( 1.- zmask(ji+2,jj  ,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,jj+1,jk) * zmask(ji  ,jj+1,jk) + ( 1.- zmask(ji  ,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj+1,jk) * zmask(ji+1,jj+1,jk) + ( 1.- zmask(ji+1,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj+1,jk) * zmask(ji+2,jj+1,jk) + ( 1.- zmask(ji+2,jj+1,jk) ) * r_inf ,  &
+                             &      p_fld(ji  ,jj+2,jk) * zmask(ji  ,jj+2,jk) + ( 1.- zmask(ji  ,jj+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,jj+2,jk) * zmask(ji+1,jj+2,jk) + ( 1.- zmask(ji+1,jj+2,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,jj+2,jk) * zmask(ji+2,jj+2,jk) + ( 1.- zmask(ji+2,jj+2,jk) ) * r_inf   )
+                           !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           !
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+            
+               CASE( 'V' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                      ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+
+                  DO jk = 1, jpk
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                        zflcrs = &
+                          & MIN( p_fld(ji  ,ijje,jk) * p_mask(ji  ,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                          &      p_fld(ji+1,ijje,jk) * p_mask(ji+1,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                          &      p_fld(ji+2,ijje,jk) * p_mask(ji+2,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf )
+                          !
+                        p_fld_crs(ii,2,jk) = zflcrs
+                     ENDDO
+                  ENDDO
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                           ij  = ( jj - njstr ) * rfacty_r + 3
+                           ijje = mje_crs(ij)
+                           zflcrs = &
+                             & MIN( p_fld(ji  ,ijje,jk) * p_mask(ji  ,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                             &      p_fld(ji+1,ijje,jk) * p_mask(ji+1,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf ,  &
+                             &      p_fld(ji+2,ijje,jk) * p_mask(ji+2,ijje,jk) + ( 1.- p_mask(ji,ijje,jk) ) * r_inf )
+                           !
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           !
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+
+            
+               CASE( 'U' )
+
+                 IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO jk = 1, jpk           
+                           DO ji = nistr, niend, nn_factx
+                              ii   = ( ji - mis_crs(2) ) * rfactx_r + 2  
+                              ijie = mie_crs(ii)
+                              zflcrs = p_fld(ijie,je_2,jk) * p_mask(ijie,je_2,jk) + ( 1.- p_mask(ijie,je_2,jk) ) * r_inf 
+                              !
+                              p_fld_crs(ii,2,jk) = zflcrs
+                            ENDDO
+                        ENDDO
+                      ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO jk = 1, jpk           
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                           ijie = mie_crs(ii)
+                           zflcrs = &
+                             & MIN( p_fld(ijie,je_2  ,jk) * p_mask(ijie,je_2  ,jk) + ( 1.- p_mask(ijie,je_2,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,je_2+1,jk) * p_mask(ijie,je_2+1,jk) + ( 1.- p_mask(ijie,je_2,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,je_2+2,jk) * p_mask(ijie,je_2+2,jk) + ( 1.- p_mask(ijie,je_2,jk) ) * r_inf  )
+                            !
+                           p_fld_crs(ii,2,jk) = zflcrs
+                        ENDDO
+                     ENDDO
+                  ENDIF
+                  !
+                  DO jk = 1, jpk           
+                     DO jj  = njstr, njend, nn_facty
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                           ij   = ( jj - njstr ) * rfacty_r + 3
+                           ijie = mie_crs(ii)
+                           zflcrs = &
+                             & MIN( p_fld(ijie,jj  ,jk) * p_mask(ijie,jj  ,jk) + ( 1.- p_mask(ijie,jj,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,jj+1,jk) * p_mask(ijie,jj+1,jk) + ( 1.- p_mask(ijie,jj,jk) ) * r_inf ,  &
+                             &      p_fld(ijie,jj+2,jk) * p_mask(ijie,jj+2,jk) + ( 1.- p_mask(ijie,jj,jk) ) * r_inf  )
+                           ! 
+                           p_fld_crs(ii,ij,jk) = zflcrs
+                           ! 
+                        ENDDO      
+                     ENDDO
+                  ENDDO   
+          
+            END SELECT
+            !
+            DEALLOCATE( zmask )
+            !
+         END SELECT
+         !
+         CALL crs_lbc_lnk( p_fld_crs, cd_type, psgn )
+         !
+    END SUBROUTINE crs_dom_ope_3d
+
+    SUBROUTINE crs_dom_ope_2d( p_fld, cd_op, cd_type, p_mask, p_fld_crs, p_e12, p_e3, p_surf_crs, p_mask_crs, psgn )
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crsfun_UV ***
+      !! ** Purpose :  Average, area-weighted, of U or V on the east and north faces 
+      !!
+      !! ** Method  :  The U and V velocities (3D) are determined as the area-weighted averages
+      !!               on the east and north faces, respectively,
+      !!               of the parent grid subset comprising the coarse grid box. 
+      !!               In the case of the V and F grid, the last jrow minus 1 is spurious.
+      !! ** Inputs  : p_e1_e2     = parent grid e1 or e2 (t,u,v,f)
+      !!              cd_type     = grid type (T,U,V,F) for scale factors; for velocities (U or V)
+      !!              psgn        = sign change over north fold (See lbclnk.F90)
+      !!              p_pmask     = parent grid mask (T,U,V,F) for scale factors; 
+      !!                                       for velocities (U or V)
+      !!              p_e3      = parent grid vertical level thickness (e3u or e3v)
+      !!              p_pfield    = U or V on the parent grid
+      !!              p_surf_crs  = (Optional) Coarse grid weight for averaging
+      !! ** Outputs : p_cfield3d = 3D field on coarse grid
+      !!
+      !! History.  29 May.  completed draft.
+      !!            4 Jun.  Revision for WGT
+      !!            5 Jun.  Streamline for area-weighted average only ; separate scale factor and weights.
+      !!----------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj),             INTENT(in)           :: p_fld   ! T, U, V or W on parent grid
+      CHARACTER(len=3),                         INTENT(in)           :: cd_op    ! Operation SUM, MAX or MIN
+      CHARACTER(len=1),                         INTENT(in)           :: cd_type    ! grid type U,V 
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in)           :: p_mask    ! Parent grid T,U,V mask
+      REAL(wp), DIMENSION(jpi,jpj),             INTENT(in), OPTIONAL :: p_e12    ! Parent grid T,U,V scale factors (e1 or e2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in), OPTIONAL :: p_e3     ! Parent grid vertical level thickness (e3u, e3v)
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs)    , INTENT(in), OPTIONAL :: p_surf_crs ! Coarse grid area-weighting denominator    
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(in), OPTIONAL :: p_mask_crs    ! Coarse grid T,U,V mask
+      REAL(wp),                                 INTENT(in)           :: psgn   
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs)    , INTENT(out)          :: p_fld_crs ! Coarse grid box 3D quantity 
+      !
+      INTEGER  :: ji, jj, jk                 ! dummy loop indices
+      INTEGER  :: ijie, ijje, ii, ij, je_2
+      REAL(wp) :: zflcrs, zsfcrs   
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE :: zsurfmsk   
+      !!----------------------------------------------------------------  
+      !
+      p_fld_crs(:,:) = 0._wp
+      !
+      SELECT CASE ( cd_op )
+      
+        CASE ( 'VOL' )
+      
+            ALLOCATE( zsurfmsk(jpi,jpj) )
+            zsurfmsk(:,:) =  p_e12(:,:) * p_e3(:,:,1) * p_mask(:,:,1)
+
+            IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+               IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                  je_2 = mje_crs(2)
+                  DO ji = nistr, niend, nn_factx
+                     ii   = ( ji - mis_crs(2) ) * rfactx_r + 2       
+                     zflcrs =  p_fld(ji  ,je_2) * zsurfmsk(ji  ,je_2)   &
+                       &     + p_fld(ji+1,je_2) * zsurfmsk(ji+1,je_2)   &
+                       &     + p_fld(ji+2,je_2) * zsurfmsk(ji+2,je_2) 
+
+                     zsfcrs =  zsurfmsk(ji,je_2) + zsurfmsk(ji+1,je_2) + zsurfmsk(ji+2,je_2) 
+                     !
+                     p_fld_crs(ii,2) = zflcrs
+                     IF( zsfcrs /= 0.0 )  p_fld_crs(ii,2) = zflcrs / zsfcrs
+                  ENDDO
+               ENDIF
+            ELSE
+               je_2 = mjs_crs(2)
+               DO ji = nistr, niend, nn_factx
+                  ii   = ( ji - mis_crs(2) ) * rfactx_r + 2   
+                  zflcrs =  p_fld(ji  ,je_2  ) * zsurfmsk(ji  ,je_2  ) &
+                    &     + p_fld(ji+1,je_2  ) * zsurfmsk(ji+1,je_2  ) &
+                    &     + p_fld(ji+2,je_2  ) * zsurfmsk(ji+2,je_2  ) &
+                    &     + p_fld(ji  ,je_2+1) * zsurfmsk(ji  ,je_2+1) &
+                    &     + p_fld(ji+1,je_2+1) * zsurfmsk(ji+1,je_2+1) &
+                    &     + p_fld(ji+2,je_2+1) * zsurfmsk(ji+2,je_2+1) &
+                    &     + p_fld(ji  ,je_2+2) * zsurfmsk(ji  ,je_2+2) &
+                    &     + p_fld(ji+1,je_2+2) * zsurfmsk(ji+1,je_2+2) &
+                    &     + p_fld(ji+2,je_2+2) * zsurfmsk(ji+2,je_2+2) 
+
+                   zsfcrs =  zsurfmsk(ji,je_2  ) + zsurfmsk(ji+1,je_2  ) + zsurfmsk(ji+2,je_2  ) &
+                     &     + zsurfmsk(ji,je_2+1) + zsurfmsk(ji+1,je_2+1) + zsurfmsk(ji+2,je_2+1) &
+                     &     + zsurfmsk(ji,je_2+2) + zsurfmsk(ji+1,je_2+2) + zsurfmsk(ji+2,je_2+2) 
+                    !
+                    p_fld_crs(ii,2) = zflcrs
+                    IF( zsfcrs /= 0.0 )  p_fld_crs(ii,2) = zflcrs / zsfcrs
+                ENDDO
+            ENDIF
+                  !
+            DO jj  = njstr, njend, nn_facty
+               DO ji = nistr, niend, nn_factx
+                  ii  = ( ji - mis_crs(2) ) * rfactx_r + 2                 ! cordinate in parent grid
+                  ij  = ( jj - njstr ) * rfacty_r + 3
+                  zflcrs =  p_fld(ji  ,jj  ) * zsurfmsk(ji  ,jj  ) &
+                    &     + p_fld(ji+1,jj  ) * zsurfmsk(ji+1,jj  ) &
+                    &     + p_fld(ji+2,jj  ) * zsurfmsk(ji+2,jj  ) &
+                    &     + p_fld(ji  ,jj+1) * zsurfmsk(ji  ,jj+1) &
+                    &     + p_fld(ji+1,jj+1) * zsurfmsk(ji+1,jj+1) &
+                    &     + p_fld(ji+2,jj+1) * zsurfmsk(ji+2,jj+1) &
+                    &     + p_fld(ji  ,jj+2) * zsurfmsk(ji  ,jj+2) &
+                    &     + p_fld(ji+1,jj+2) * zsurfmsk(ji+1,jj+2) &
+                    &     + p_fld(ji+2,jj+2) * zsurfmsk(ji+2,jj+2) 
+  
+                  zsfcrs =  zsurfmsk(ji,jj  ) + zsurfmsk(ji+1,jj  ) + zsurfmsk(ji+2,jj  ) &
+                    &     + zsurfmsk(ji,jj+1) + zsurfmsk(ji+1,jj+1) + zsurfmsk(ji+2,jj+1) &
+                    &     + zsurfmsk(ji,jj+2) + zsurfmsk(ji+1,jj+2) + zsurfmsk(ji+2,jj+2) 
+                   !
+                  p_fld_crs(ii,ij) = zflcrs
+                  IF( zsfcrs /= 0.0 )  p_fld_crs(ii,ij) = zflcrs / zsfcrs
+               ENDDO      
+            ENDDO
+
+            DEALLOCATE( zsurfmsk )
+
+         CASE ( 'SUM' )
+         
+            ALLOCATE( zsurfmsk(jpi,jpj) )
+            IF( PRESENT( p_e3 ) ) THEN
+               zsurfmsk(:,:) =  p_e12(:,:) * p_e3(:,:,1) * p_mask(:,:,1)
+            ELSE
+               zsurfmsk(:,:) =  p_e12(:,:) * p_mask(:,:,1)
+            ENDIF
+
+            SELECT CASE ( cd_type )
+
+               CASE( 'T', 'W' )
+
+                   IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                      IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                         je_2 = mje_crs(2)
+                         DO ji = nistr, niend, nn_factx
+                            ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                            zflcrs  =  p_fld(ji  ,je_2) * zsurfmsk(ji  ,je_2) &
+                              &      + p_fld(ji+1,je_2) * zsurfmsk(ji+1,je_2) &
+                              &      + p_fld(ji+2,je_2) * zsurfmsk(ji+2,je_2) 
+                              !
+                             p_fld_crs(ii,2) = zflcrs
+                         ENDDO
+                      ENDIF
+                   ELSE
+                      je_2 = mjs_crs(2)
+                      DO ji = nistr, niend, nn_factx
+                         ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                         zflcrs  =  p_fld(ji  ,je_2  ) * zsurfmsk(ji  ,je_2  )  &
+                           &      + p_fld(ji+1,je_2  ) * zsurfmsk(ji+1,je_2  )  &
+                           &      + p_fld(ji+2,je_2  ) * zsurfmsk(ji+2,je_2  )  &
+                           &      + p_fld(ji  ,je_2+1) * zsurfmsk(ji  ,je_2+1)  &
+                           &      + p_fld(ji+1,je_2+1) * zsurfmsk(ji+1,je_2+1)  &
+                           &      + p_fld(ji+2,je_2+1) * zsurfmsk(ji+2,je_2+1)  &
+                           &      + p_fld(ji  ,je_2+2) * zsurfmsk(ji  ,je_2+2)  &
+                           &      + p_fld(ji+1,je_2+2) * zsurfmsk(ji+1,je_2+2)  &
+                           &      + p_fld(ji+2,je_2+2) * zsurfmsk(ji+2,je_2+2)  
+                            !
+                            p_fld_crs(ii,2) = zflcrs
+                      ENDDO
+                   ENDIF
+                     !
+                   DO jj = njstr, njend, nn_facty
+                      DO ji = nistr, niend, nn_factx
+                         ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                         ij   = ( jj - njstr ) * rfacty_r + 3
+                         zflcrs  =  p_fld(ji  ,jj  ) * zsurfmsk(ji  ,jj  )  &
+                           &      + p_fld(ji+1,jj  ) * zsurfmsk(ji+1,jj  )  &
+                           &      + p_fld(ji+2,jj  ) * zsurfmsk(ji+2,jj  )  &
+                           &      + p_fld(ji  ,jj+1) * zsurfmsk(ji  ,jj+1)  &
+                           &      + p_fld(ji+1,jj+1) * zsurfmsk(ji+1,jj+1)  &
+                           &      + p_fld(ji+2,jj+1) * zsurfmsk(ji+2,jj+1)  &
+                           &      + p_fld(ji  ,jj+2) * zsurfmsk(ji  ,jj+2)  &
+                           &      + p_fld(ji+1,jj+2) * zsurfmsk(ji+1,jj+2)  &
+                           &      + p_fld(ji+2,jj+2) * zsurfmsk(ji+2,jj+2)  
+                           !
+                          p_fld_crs(ii,ij) = zflcrs
+                          ! 
+                      ENDDO      
+                   ENDDO
+            
+               CASE( 'V' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                      ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+
+                  DO ji = nistr, niend, nn_factx
+                     ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                     zflcrs  =  p_fld(ji  ,ijje) * zsurfmsk(ji  ,ijje) &
+                       &      + p_fld(ji+1,ijje) * zsurfmsk(ji+1,ijje) &
+                       &      + p_fld(ji+2,ijje) * zsurfmsk(ji+2,ijje) 
+                            !
+                     p_fld_crs(ii,2) = zflcrs
+                  ENDDO
+
+                  DO jj = njstr, njend, nn_facty
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                        ij   = ( jj - njstr ) * rfacty_r + 3
+                        ijje = mje_crs(ij)
+                        zflcrs  =  p_fld(ji  ,ijje) * zsurfmsk(ji  ,ijje) &
+                          &      + p_fld(ji+1,ijje) * zsurfmsk(ji+1,ijje) &
+                          &      + p_fld(ji+2,ijje) * zsurfmsk(ji+2,ijje) 
+                          !
+                        p_fld_crs(ii,ij) = zflcrs
+                        ! 
+                     ENDDO      
+                  ENDDO
+            
+               CASE( 'U' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                           ijie = mie_crs(ii)
+                           zflcrs  =  p_fld(ijie,je_2) * zsurfmsk(ijie,je_2)  
+                           p_fld_crs(ii,2) = zflcrs
+                        ENDDO
+                     ENDIF
+                  ELSE
+                     je_2 = mjs_crs(2)
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        ijie = mie_crs(ii)
+                        zflcrs =  p_fld(ijie,je_2  ) * zsurfmsk(ijie,je_2  )  &
+                          &     + p_fld(ijie,je_2+1) * zsurfmsk(ijie,je_2+1)  &
+                          &     + p_fld(ijie,je_2+2) * zsurfmsk(ijie,je_2+2) 
+   
+                        p_fld_crs(ii,2) = zflcrs
+                     ENDDO
+                 ENDIF
+
+                 DO jj = njstr, njend, nn_facty
+                    DO ji = nistr, niend, nn_factx
+                       ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                       ij   = ( jj - njstr ) * rfacty_r + 3
+                       ijie = mie_crs(ii)
+                       zflcrs =  p_fld(ijie,jj  ) * zsurfmsk(ijie,jj  )  &
+                          &    + p_fld(ijie,jj+1) * zsurfmsk(ijie,jj+1)  &
+                          &    + p_fld(ijie,jj+2) * zsurfmsk(ijie,jj+2) 
+                         !
+                       p_fld_crs(ii,ij) = zflcrs
+                       ! 
+                    ENDDO      
+                 ENDDO
+
+              END SELECT
+
+              IF( PRESENT( p_surf_crs ) ) THEN
+                 WHERE ( p_surf_crs /= 0.0 ) p_fld_crs(:,:) = p_fld_crs(:,:) / p_surf_crs(:,:)
+              ENDIF
+
+              DEALLOCATE( zsurfmsk )
+
+         CASE ( 'MAX' )
+
+            SELECT CASE ( cd_type )
+            
+               CASE( 'T', 'W' )
+  
+                   IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                      IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                         je_2 = mje_crs(2)
+                         DO ji = nistr, niend, nn_factx
+                            ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                            zflcrs =  &
+                              & MAX( p_fld(ji  ,je_2) * p_mask(ji  ,je_2,1) - ( 1.- p_mask(ji  ,je_2,1) ) * r_inf ,  &
+                             &       p_fld(ji+1,je_2) * p_mask(ji+1,je_2,1) - ( 1.- p_mask(ji+1,je_2,1) ) * r_inf ,  &
+                             &       p_fld(ji+2,je_2) * p_mask(ji+2,je_2,1) - ( 1.- p_mask(ji+2,je_2,1) ) * r_inf  )
+                            !
+                            p_fld_crs(ii,2) = zflcrs
+                         ENDDO
+                      ENDIF
+                   ELSE
+                      je_2 = mjs_crs(2) 
+                      zflcrs =  &
+                        &  MAX( p_fld(ji  ,je_2  ) * p_mask(ji  ,je_2  ,1) - ( 1.- p_mask(ji  ,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2  ) * p_mask(ji+1,je_2  ,1) - ( 1.- p_mask(ji+1,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2  ) * p_mask(ji+2,je_2  ,1) - ( 1.- p_mask(ji+2,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji  ,je_2+1) * p_mask(ji  ,je_2+1,1) - ( 1.- p_mask(ji  ,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2+1) * p_mask(ji+1,je_2+1,1) - ( 1.- p_mask(ji+1,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2+1) * p_mask(ji+2,je_2+1,1) - ( 1.- p_mask(ji+2,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji  ,je_2+2) * p_mask(ji  ,je_2+2,1) - ( 1.- p_mask(ji  ,je_2+2,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2+2) * p_mask(ji+1,je_2+2,1) - ( 1.- p_mask(ji+1,je_2+2,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2+2) * p_mask(ji+2,je_2+2,1) - ( 1.- p_mask(ji+2,je_2+2,1) ) * r_inf   )
+                      !
+                      p_fld_crs(ii,2) = zflcrs
+                   ENDIF
+
+                   DO jj = njstr, njend, nn_facty
+                      DO ji = nistr, niend, nn_factx
+                         ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                         ij   = ( jj - njstr ) * rfacty_r + 3
+                         zflcrs = &
+                          &  MAX( p_fld(ji  ,jj  ) * p_mask(ji  ,jj  ,1) - ( 1.- p_mask(ji  ,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj  ) * p_mask(ji+1,jj  ,1) - ( 1.- p_mask(ji+1,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj  ) * p_mask(ji+2,jj  ,1) - ( 1.- p_mask(ji+2,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji  ,jj+1) * p_mask(ji  ,jj+1,1) - ( 1.- p_mask(ji  ,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj+1) * p_mask(ji+1,jj+1,1) - ( 1.- p_mask(ji+1,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj+1) * p_mask(ji+2,jj+1,1) - ( 1.- p_mask(ji+2,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji  ,jj+2) * p_mask(ji  ,jj+2,1) - ( 1.- p_mask(ji  ,jj+2,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj+2) * p_mask(ji+1,jj+2,1) - ( 1.- p_mask(ji+1,jj+2,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj+2) * p_mask(ji+2,jj+2,1) - ( 1.- p_mask(ji+2,jj+2,1) ) * r_inf   )
+                         !
+                         p_fld_crs(ii,ij) = zflcrs
+                         !
+                      ENDDO      
+                   ENDDO
+            
+               CASE( 'V' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                      ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+
+                  DO ji = nistr, niend, nn_factx
+                     ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                     zflcrs = MAX( p_fld(ji  ,ijje) * p_mask(ji  ,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                       &           p_fld(ji+1,ijje) * p_mask(ji+1,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                       &           p_fld(ji+2,ijje) * p_mask(ji+2,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf )
+                       !
+                     p_fld_crs(ii,2) = zflcrs
+                  ENDDO      
+                  DO jj = njstr, njend, nn_facty
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        ij   = ( jj - njstr ) * rfacty_r + 3               
+                        ijje = mje_crs(ij) 
+                        !                  
+                        zflcrs = MAX( p_fld(ji  ,ijje) * p_mask(ji  ,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                          &           p_fld(ji+1,ijje) * p_mask(ji+1,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                          &           p_fld(ji+2,ijje) * p_mask(ji+2,ijje,1) - ( 1.- p_mask(ji,ijje,1) ) * r_inf )
+                        !
+                        p_fld_crs(ii,ij) = zflcrs
+                        !
+                     ENDDO      
+                  ENDDO
+            
+               CASE( 'U' )
+
+                 IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                           ijie = mie_crs(ii)
+                           zflcrs  =  p_fld(ijie,je_2) * p_mask(ijie,je_2,1) - ( 1.- p_mask(ijie,je_2,1) ) * r_inf 
+                           p_fld_crs(ii,2) = zflcrs
+                        ENDDO
+                     ENDIF
+                 ELSE
+                     je_2 = mjs_crs(2)
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        ijie = mie_crs(ii)
+                        zflcrs =  &
+                          &  MAX( p_fld(ijie,je_2  ) * p_mask(ijie,je_2  ,1) - ( 1.- p_mask(ijie,je_2,1) ) * r_inf ,  &
+                          &       p_fld(ijie,je_2+1) * p_mask(ijie,je_2+1,1) - ( 1.- p_mask(ijie,je_2,1) ) * r_inf ,  &
+                          &       p_fld(ijie,je_2+2) * p_mask(ijie,je_2+2,1) - ( 1.- p_mask(ijie,je_2,1) ) * r_inf  )
+                        p_fld_crs(ii,2) = zflcrs
+                     ENDDO
+                 ENDIF
+                 DO jj = njstr, njend, nn_facty
+                    DO ji = nistr, niend, nn_factx
+                       ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                       ij   = ( jj - njstr ) * rfacty_r + 3
+                       ijie = mie_crs(ii)
+                       zflcrs =  &
+                         &  MAX( p_fld(ijie,jj  ) * p_mask(ijie,jj  ,1) - ( 1.- p_mask(ijie,jj,1) ) * r_inf ,  &
+                         &       p_fld(ijie,jj+1) * p_mask(ijie,jj+1,1) - ( 1.- p_mask(ijie,jj,1) ) * r_inf ,  &
+                          &      p_fld(ijie,jj+2) * p_mask(ijie,jj+2,1) - ( 1.- p_mask(ijie,jj,1) ) * r_inf  )
+                        p_fld_crs(ii,ij) = zflcrs
+                        ! 
+                     ENDDO      
+                  ENDDO
+
+              END SELECT
+
+         CASE ( 'MIN' )      !   Search the min of unmasked grid cells
+
+           SELECT CASE ( cd_type )
+
+              CASE( 'T', 'W' )
+  
+                   IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                      IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                         je_2 = mje_crs(2)
+                         DO ji = nistr, niend, nn_factx
+                            ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                            zflcrs =  &
+                              & MIN( p_fld(ji  ,je_2) * p_mask(ji  ,je_2,1) + ( 1.- p_mask(ji  ,je_2,1) ) * r_inf ,  &
+                             &       p_fld(ji+1,je_2) * p_mask(ji+1,je_2,1) + ( 1.- p_mask(ji+1,je_2,1) ) * r_inf ,  &
+                             &       p_fld(ji+2,je_2) * p_mask(ji+2,je_2,1) + ( 1.- p_mask(ji+2,je_2,1) ) * r_inf  )
+                            !
+                            p_fld_crs(ii,2) = zflcrs
+                         ENDDO
+                      ENDIF
+                   ELSE
+                      je_2 = mjs_crs(2) 
+                      zflcrs =  &
+                        &  MIN( p_fld(ji  ,je_2  ) * p_mask(ji  ,je_2  ,1) + ( 1.- p_mask(ji  ,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2  ) * p_mask(ji+1,je_2  ,1) + ( 1.- p_mask(ji+1,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2  ) * p_mask(ji+2,je_2  ,1) + ( 1.- p_mask(ji+2,je_2  ,1) ) * r_inf ,  &
+                        &       p_fld(ji  ,je_2+1) * p_mask(ji  ,je_2+1,1) + ( 1.- p_mask(ji  ,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2+1) * p_mask(ji+1,je_2+1,1) + ( 1.- p_mask(ji+1,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2+1) * p_mask(ji+2,je_2+1,1) + ( 1.- p_mask(ji+2,je_2+1,1) ) * r_inf ,  &
+                        &       p_fld(ji  ,je_2+2) * p_mask(ji  ,je_2+2,1) + ( 1.- p_mask(ji  ,je_2+2,1) ) * r_inf ,  &
+                        &       p_fld(ji+1,je_2+2) * p_mask(ji+1,je_2+2,1) + ( 1.- p_mask(ji+1,je_2+2,1) ) * r_inf ,  &
+                        &       p_fld(ji+2,je_2+2) * p_mask(ji+2,je_2+2,1) + ( 1.- p_mask(ji+2,je_2+2,1) ) * r_inf   )
+                      !
+                      p_fld_crs(ii,2) = zflcrs
+                   ENDIF
+
+                   DO jj = njstr, njend, nn_facty
+                      DO ji = nistr, niend, nn_factx
+                         ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                         ij   = ( jj - njstr ) * rfacty_r + 3
+                         zflcrs = &
+                          &  MIN( p_fld(ji  ,jj  ) * p_mask(ji  ,jj  ,1) + ( 1.- p_mask(ji  ,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj  ) * p_mask(ji+1,jj  ,1) + ( 1.- p_mask(ji+1,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj  ) * p_mask(ji+2,jj  ,1) + ( 1.- p_mask(ji+2,jj  ,1) ) * r_inf ,  &
+                          &       p_fld(ji  ,jj+1) * p_mask(ji  ,jj+1,1) + ( 1.- p_mask(ji  ,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj+1) * p_mask(ji+1,jj+1,1) + ( 1.- p_mask(ji+1,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj+1) * p_mask(ji+2,jj+1,1) + ( 1.- p_mask(ji+2,jj+1,1) ) * r_inf ,  &
+                          &       p_fld(ji  ,jj+2) * p_mask(ji  ,jj+2,1) + ( 1.- p_mask(ji  ,jj+2,1) ) * r_inf ,  &
+                          &       p_fld(ji+1,jj+2) * p_mask(ji+1,jj+2,1) + ( 1.- p_mask(ji+1,jj+2,1) ) * r_inf ,  &
+                          &       p_fld(ji+2,jj+2) * p_mask(ji+2,jj+2,1) + ( 1.- p_mask(ji+2,jj+2,1) ) * r_inf   )
+                         !
+                         p_fld_crs(ii,ij) = zflcrs
+                         !
+                      ENDDO      
+                   ENDDO
+            
+               CASE( 'V' )
+
+                  IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        ijje = mje_crs(2)
+                      ENDIF
+                  ELSE
+                     ijje = mjs_crs(2)
+                  ENDIF
+
+                  DO ji = nistr, niend, nn_factx
+                     ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                     zflcrs = MIN( p_fld(ji  ,ijje) * p_mask(ji  ,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                       &           p_fld(ji+1,ijje) * p_mask(ji+1,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                       &           p_fld(ji+2,ijje) * p_mask(ji+2,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf )
+                       !
+                     p_fld_crs(ii,2) = zflcrs
+                  ENDDO      
+                  DO jj = njstr, njend, nn_facty
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        ij   = ( jj - njstr ) * rfacty_r + 3               
+                        ijje = mje_crs(ij) 
+                        !                  
+                        zflcrs = MIN( p_fld(ji  ,ijje) * p_mask(ji  ,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                          &           p_fld(ji+1,ijje) * p_mask(ji+1,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf ,  &
+                          &           p_fld(ji+2,ijje) * p_mask(ji+2,ijje,1) + ( 1.- p_mask(ji,ijje,1) ) * r_inf )
+                        !
+                        p_fld_crs(ii,ij) = zflcrs
+                        !
+                     ENDDO      
+                  ENDDO
+            
+               CASE( 'U' )
+
+                 IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+                     IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+                        je_2 = mje_crs(2)
+                        DO ji = nistr, niend, nn_factx
+                           ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                           ijie = mie_crs(ii)
+                           zflcrs  =  p_fld(ijie,je_2) * p_mask(ijie,je_2,1) + ( 1.- p_mask(ijie,je_2,1) ) * r_inf 
+ 
+                           p_fld_crs(ii,2) = zflcrs
+                        ENDDO
+                     ENDIF
+                 ELSE
+                     je_2 = mjs_crs(2)
+                     DO ji = nistr, niend, nn_factx
+                        ii   = ( ji - mis_crs(2) ) * rfactx_r + 2    
+                        ijie = mie_crs(ii)
+                        zflcrs =  &
+                          &  MIN( p_fld(ijie,je_2  ) * p_mask(ijie,je_2  ,1) + ( 1.- p_mask(ijie,je_2,1) ) * r_inf ,  &
+                          &       p_fld(ijie,je_2+1) * p_mask(ijie,je_2+1,1) + ( 1.- p_mask(ijie,je_2,1) ) * r_inf ,  &
+                          &       p_fld(ijie,je_2+2) * p_mask(ijie,je_2+2,1) + ( 1.- p_mask(ijie,je_2,1) ) * r_inf  )
+                        p_fld_crs(ii,2) = zflcrs
+                     ENDDO
+                 ENDIF
+                 DO jj = njstr, njend, nn_facty
+                    DO ji = nistr, niend, nn_factx
+                       ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                       ij   = ( jj - njstr ) * rfacty_r + 3
+                       ijie = mie_crs(ii)
+                       zflcrs =  &
+                         &  MIN( p_fld(ijie,jj  ) * p_mask(ijie,jj  ,1) + ( 1.- p_mask(ijie,jj,1) ) * r_inf ,  &
+                         &       p_fld(ijie,jj+1) * p_mask(ijie,jj+1,1) + ( 1.- p_mask(ijie,jj,1) ) * r_inf ,  &
+                          &      p_fld(ijie,jj+2) * p_mask(ijie,jj+2,1) + ( 1.- p_mask(ijie,jj,1) ) * r_inf  )
+                        p_fld_crs(ii,ij) = zflcrs
+                        ! 
+                     ENDDO      
+                  ENDDO
+
+              END SELECT
+             !
+         END SELECT
+         !
+         CALL crs_lbc_lnk( p_fld_crs, cd_type, psgn )
+         !
+   END SUBROUTINE crs_dom_ope_2d
+
+   SUBROUTINE crs_dom_e3( p_e1, p_e2, p_e3, p_sfc_crs, cd_type, p_mask, p_e3_crs, p_e3_max_crs)
+      !!----------------------------------------------------------------  
+      !!  Arguments
+      CHARACTER(len=1),                         INTENT(in) :: cd_type      ! grid type T, W ( U, V, F)
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in) :: p_mask       ! Parent grid T mask
+      REAL(wp), DIMENSION(jpi,jpj)    ,         INTENT(in) :: p_e1, p_e2   ! 2D tracer T or W on parent grid
+      REAL(wp), DIMENSION(jpi,jpj,jpk),         INTENT(in) :: p_e3         ! 3D tracer T or W on parent grid
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(in) :: p_sfc_crs ! Coarse grid box east or north face quantity
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(inout) :: p_e3_crs ! Coarse grid box east or north face quantity 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(inout) :: p_e3_max_crs ! Coarse grid box east or north face quantity 
+
+      !! Local variables
+      INTEGER ::  ji, jj, jk                   ! dummy loop indices
+      INTEGER ::  ijie, ijje, ii, ij, je_2
+      REAL(wp) :: ze3crs  
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zmask, zsurf   
+
+      !!----------------------------------------------------------------  
+
+       p_e3_crs    (:,:,:) = 0.
+       p_e3_max_crs(:,:,:) = 1.
+   
+
+       SELECT CASE ( cd_type )
+          CASE( 'W' )
+              zmask(:,:,1) = p_mask(:,:,1) 
+              DO jk = 2, jpk
+                 zmask(:,:,jk) = p_mask(:,:,jk-1) 
+              ENDDO
+           CASE DEFAULT
+              DO jk = 1, jpk
+                 zmask(:,:,jk) = p_mask(:,:,jk) 
+              ENDDO
+       END SELECT
+
+       DO jk = 1, jpk
+          zsurf(:,:,jk) = p_e1(:,:) * p_e2(:,:) * p_e3(:,:,jk) 
+       ENDDO
+
+       IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+          IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+             je_2 = mje_crs(2)
+             DO jk = 1 , jpk
+                DO ji = nistr, niend, nn_factx
+                   ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                   ze3crs =   zsurf(ji  ,je_2,jk) * zmask(ji  ,je_2,jk)   &
+                        &   + zsurf(ji+1,je_2,jk) * zmask(ji+1,je_2,jk)   &
+                        &   + zsurf(ji+2,je_2,jk) * zmask(ji+2,je_2,jk) 
+
+                   p_e3_crs(ii,2,jk) = ze3crs / p_sfc_crs(ii,ij,jk)
+                   !
+                   ze3crs = MAX( p_e3(ji  ,je_2,jk) * zmask(ji  ,je_2,jk),  &
+                      &          p_e3(ji+1,je_2,jk) * zmask(ji+1,je_2,jk),  &
+                      &          p_e3(ji+2,je_2,jk) * zmask(ji+2,je_2,jk)  )
+                   !
+                   p_e3_max_crs(ii,2,jk) = ze3crs
+                ENDDO
+             ENDDO
+          ENDIF
+       ELSE
+          je_2 = mjs_crs(2)
+          DO jk = 1 , jpk
+             DO ji = nistr, niend, nn_factx
+                ii   = ( ji - mis_crs(2) ) * rfactx_r + 2     
+                ze3crs =  zsurf(ji  ,je_2  ,jk) * zmask(ji  ,je_2  ,jk)   &
+                   &    + zsurf(ji+1,je_2  ,jk) * zmask(ji+1,je_2  ,jk)   &
+                   &    + zsurf(ji+2,je_2  ,jk) * zmask(ji+2,je_2  ,jk)   &
+                   &    + zsurf(ji  ,je_2+1,jk) * zmask(ji  ,je_2+1,jk)   &
+                   &    + zsurf(ji+1,je_2+1,jk) * zmask(ji+1,je_2+1,jk)   &
+                   &    + zsurf(ji+2,je_2+1,jk) * zmask(ji+2,je_2+1,jk)   &
+                   &    + zsurf(ji  ,je_2+2,jk) * zmask(ji  ,je_2+2,jk)   &
+                   &    + zsurf(ji+1,je_2+2,jk) * zmask(ji+1,je_2+2,jk)   &
+                   &    + zsurf(ji+2,je_2+2,jk) * zmask(ji+2,je_2+2,jk)
+
+                p_e3_crs(ii,2,jk) = ze3crs / p_sfc_crs(ii,2,jk)
+                !
+                ze3crs = MAX( p_e3(ji  ,je_2  ,jk) * zmask(ji  ,je_2  ,jk),  &
+                   &          p_e3(ji+1,je_2  ,jk) * zmask(ji+1,je_2  ,jk),  &
+                   &          p_e3(ji+2,je_2  ,jk) * zmask(ji+2,je_2  ,jk),  &
+                   &          p_e3(ji  ,je_2+1,jk) * zmask(ji  ,je_2+1,jk),  &
+                   &          p_e3(ji+1,je_2+1,jk) * zmask(ji+1,je_2+1,jk),  &
+                   &          p_e3(ji+2,je_2+1,jk) * zmask(ji+2,je_2+1,jk),  &
+                   &          p_e3(ji  ,je_2+2,jk) * zmask(ji  ,je_2+2,jk),  &
+                   &          p_e3(ji+1,je_2+2,jk) * zmask(ji+1,je_2+2,jk),  &
+                   &          p_e3(ji+2,je_2+2,jk) * zmask(ji+2,je_2+2,jk) )
+               
+                p_e3_max_crs(ii,2,jk) = ze3crs
+                ENDDO
+             ENDDO
+          ENDIF
+          DO jk = 1 , jpk
+             DO jj = njstr, njend, nn_facty
+                DO ji = nistr, niend, nn_factx
+                   ii   = ( ji - mis_crs(2) ) * rfactx_r + 2          
+                   ij   = ( jj - njstr ) * rfacty_r + 3
+                   ze3crs =   zsurf(ji  ,jj  ,jk) * zmask(ji  ,jj  ,jk)   &
+                   &        + zsurf(ji+1,jj  ,jk) * zmask(ji+1,jj  ,jk)   &
+                   &        + zsurf(ji+2,jj  ,jk) * zmask(ji+2,jj  ,jk)   &
+                   &        + zsurf(ji  ,jj+1,jk) * zmask(ji  ,jj+1,jk)   &
+                   &        + zsurf(ji+1,jj+1,jk) * zmask(ji+1,jj+1,jk)   &
+                   &        + zsurf(ji+2,jj+1,jk) * zmask(ji+2,jj+1,jk)   &
+                   &        + zsurf(ji  ,jj+2,jk) * zmask(ji  ,jj+2,jk)   &
+                   &        + zsurf(ji+1,jj+2,jk) * zmask(ji+1,jj+2,jk)   &
+                   &        + zsurf(ji+2,jj+2,jk) * zmask(ji+2,jj+2,jk)
+
+                p_e3_crs(ii,ij,jk) = ze3crs / p_sfc_crs(ii,ij,jk)
+                !
+                ze3crs = MAX( p_e3(ji  ,jj  ,jk) * zmask(ji  ,jj  ,jk),  &
+                   &          p_e3(ji+1,jj  ,jk) * zmask(ji+1,jj  ,jk),  &
+                   &          p_e3(ji+2,jj  ,jk) * zmask(ji+2,jj  ,jk),  &
+                   &          p_e3(ji  ,jj+1,jk) * zmask(ji  ,jj+1,jk),  &
+                   &          p_e3(ji+1,jj+1,jk) * zmask(ji+1,jj+1,jk),  &
+                   &          p_e3(ji+2,jj+1,jk) * zmask(ji+2,jj+1,jk),  &
+                   &          p_e3(ji  ,jj+2,jk) * zmask(ji  ,jj+2,jk),  &
+                   &          p_e3(ji+1,jj+2,jk) * zmask(ji+1,jj+2,jk),  &
+                   &          p_e3(ji+2,jj+2,jk) * zmask(ji+2,jj+2,jk) )
+               
+                p_e3_max_crs(ii,ij,jk) = ze3crs
+             ENDDO
+          ENDDO
+       ENDDO
+                  
+       CALL crs_lbc_lnk( p_e3_crs    , cd_type, 1.0, pfillval=1.0 )  
+       CALL crs_lbc_lnk( p_e3_max_crs, cd_type, 1.0, pfillval=1.0 )  
+       !              
+       !
+   END SUBROUTINE crs_dom_e3
+
+   SUBROUTINE crs_dom_sfc( p_mask, cd_type, p_surf_crs, p_surf_crs_msk,  p_e1, p_e2, p_e3 )
+
+      !!  Arguments
+      CHARACTER(len=1),                         INTENT(in)           :: cd_type      ! grid type T, W ( U, V, F)
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        , INTENT(in)           :: p_mask       ! Parent grid T mask
+      REAL(wp), DIMENSION(jpi,jpj)            , INTENT(in), OPTIONAL :: p_e1, p_e2         ! 3D tracer T or W on parent grid
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        , INTENT(in), OPTIONAL :: p_e3         ! 3D tracer T or W on parent grid
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(out)          :: p_surf_crs ! Coarse grid box east or north face quantity 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(out)          :: p_surf_crs_msk ! Coarse grid box east or north face quantity 
+
+      !! Local variables
+      INTEGER  :: ji, jj, jk                   ! dummy loop indices
+      INTEGER  :: ii, ij, je_2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zsurf, zsurfmsk   
+      !!----------------------------------------------------------------  
+      ! Initialize
+
+      !
+      SELECT CASE ( cd_type )
+      
+         CASE ('W')    
+            DO jk = 1, jpk
+               zsurf(:,:,jk) = p_e1(:,:) * p_e2(:,:) 
+            ENDDO
+            zsurfmsk(:,:,1) = zsurf(:,:,1) * p_mask(:,:,1) 
+            DO jk = 2, jpk
+               zsurfmsk(:,:,jk) = zsurf(:,:,jk) * p_mask(:,:,jk-1) 
+            ENDDO
+
+         CASE ('V')     
+            DO jk = 1, jpk
+               zsurf(:,:,jk) = p_e1(:,:) * p_e3(:,:,jk) 
+            ENDDO
+            DO jk = 1, jpk
+               zsurfmsk(:,:,jk) = zsurf(:,:,jk) * p_mask(:,:,jk) 
+            ENDDO
+
+         CASE ('U')     
+            DO jk = 1, jpk
+               zsurf(:,:,jk) = p_e2(:,:) * p_e3(:,:,jk) 
+            ENDDO
+            DO jk = 1, jpk
+               zsurfmsk(:,:,jk) = zsurf(:,:,jk) * p_mask(:,:,jk) 
+            ENDDO
+
+         CASE DEFAULT
+            DO jk = 1, jpk
+               zsurf(:,:,jk) = p_e1(:,:) * p_e2(:,:) 
+            ENDDO
+            DO jk = 1, jpk
+               zsurfmsk(:,:,jk) = zsurf(:,:,jk) * p_mask(:,:,jk) 
+            ENDDO
+      END SELECT
+
+      IF( nldj_crs == 1 .AND. ( ( mje_crs(2) - mjs_crs(2) ) < 2 ) ) THEN     !!cc bande du sud style ORCA2
+         IF( mje_crs(2) - mjs_crs(2) == 1 ) THEN
+            je_2 = mje_crs(2)
+            DO jk = 1, jpk
+               DO ji = nistr, niend, nn_factx
+                  ii   = ( ji - mis_crs(2) ) * rfactx_r + 2 
+                  !    
+                  p_surf_crs    (ii,2,jk) =  zsurf(ji,je_2  ,jk) + zsurf(ji+1,je_2  ,jk) + zsurf(ji+2,je_2  ,jk) &
+                    &                      + zsurf(ji,je_2-1,jk) + zsurf(ji+1,je_2-1,jk) + zsurf(ji+2,je_2-1,jk)  ! Why ?????
+                  !
+                  p_surf_crs_msk(ii,2,jk) =  zsurfmsk(ji,je_2,jk) + zsurfmsk(ji+1,je_2,jk) + zsurfmsk(ji+2,je_2,jk) 
+                  !
+               ENDDO
+            ENDDO
+         ENDIF
+      ELSE
+         je_2 = mjs_crs(2)
+         DO jk = 1, jpk
+            DO ji = nistr, niend, nn_factx
+               ii   = ( ji - mis_crs(2) ) * rfactx_r + 2 
+               !  
+               p_surf_crs    (ii,2,jk) =  zsurf(ji,je_2  ,jk) + zsurf(ji+1,je_2  ,jk) + zsurf(ji+2,je_2  ,jk)  &
+                    &                   + zsurf(ji,je_2+1,jk) + zsurf(ji+1,je_2+1,jk) + zsurf(ji+2,je_2+1,jk)  &
+                    &                   + zsurf(ji,je_2+2,jk) + zsurf(ji+1,je_2+2,jk) + zsurf(ji+2,je_2+2,jk)  
+
+               p_surf_crs_msk(ii,2,jk) =  zsurfmsk(ji,je_2  ,jk) + zsurfmsk(ji+1,je_2  ,jk) + zsurfmsk(ji+2,je_2  ,jk)  &
+                    &                   + zsurfmsk(ji,je_2+1,jk) + zsurfmsk(ji+1,je_2+1,jk) + zsurfmsk(ji+2,je_2+1,jk)  &
+                    &                   + zsurfmsk(ji,je_2+2,jk) + zsurfmsk(ji+1,je_2+2,jk) + zsurfmsk(ji+2,je_2+2,jk)  
+                ENDDO
+            ENDDO
+      ENDIF
+         
+      DO jk = 1, jpk
+         DO jj = njstr, njend, nn_facty
+            DO ji = nistr, niend, nn_factx
+               ii = ( ji - mis_crs(2) ) * rfactx_r + 2  
+               ij = ( jj - njstr ) * rfacty_r + 3
+               !
+               p_surf_crs    (ii,ij,jk) =  zsurf(ji,jj  ,jk) + zsurf(ji+1,jj  ,jk) + zsurf(ji+2,jj  ,jk)  &
+                    &                    + zsurf(ji,jj+1,jk) + zsurf(ji+1,jj+1,jk) + zsurf(ji+2,jj+1,jk)  &
+                    &                    + zsurf(ji,jj+2,jk) + zsurf(ji+1,jj+2,jk) + zsurf(ji+2,jj+2,jk)  
+
+               p_surf_crs_msk(ii,ij,jk) =  zsurfmsk(ji,jj  ,jk) + zsurfmsk(ji+1,jj  ,jk) + zsurfmsk(ji+2,jj  ,jk)  &
+                    &                    + zsurfmsk(ji,jj+1,jk) + zsurfmsk(ji+1,jj+1,jk) + zsurfmsk(ji+2,jj+1,jk)  &
+                    &                    + zsurfmsk(ji,jj+2,jk) + zsurfmsk(ji+1,jj+2,jk) + zsurfmsk(ji+2,jj+2,jk)  
+            ENDDO      
+         ENDDO
+      ENDDO   
+
+      CALL crs_lbc_lnk( p_surf_crs    , cd_type, 1.0, pfillval=1.0 )
+      CALL crs_lbc_lnk( p_surf_crs_msk, cd_type, 1.0, pfillval=1.0 )
+
+   END SUBROUTINE crs_dom_sfc
+   
+   SUBROUTINE crs_dom_def
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crs_dom_def ***
+      !! ** Purpose :  Three applications.
+      !!               1) Define global domain indice of the croasening grid
+      !!               2) Define local domain indice of the croasening grid
+      !!               3) Define the processor domain indice for a croasening grid
+      !!----------------------------------------------------------------
+      !! 
+      !!  local variables
+   
+      INTEGER  :: ji,jj,jk,ijjgloT,ijis,ijie,ijjs,ijje,jn      ! dummy indices
+      INTEGER  :: ierr                                ! allocation error status
+ 
+  
+     ! 1.a. Define global domain indices  : take into account the interior domain only ( removes i/j=1 , i/j=jpiglo/jpjglo ) then add 2/3 grid points 
+      jpiglo_crs   = INT( (jpiglo - 2) / nn_factx ) + 2
+  !    jpjglo_crs   = INT( (jpjglo - 2) / nn_facty ) + 2  ! the -2 removes j=1, j=jpj
+  !    jpjglo_crs   = INT( (jpjglo - 2) / nn_facty ) + 3
+      jpjglo_crs   = INT( (jpjglo - MOD(jpjglo, nn_facty)) / nn_facty ) + 3
+      jpiglo_crsm1 = jpiglo_crs - 1
+      jpjglo_crsm1 = jpjglo_crs - 1  
+
+      jpi_crs = ( jpiglo_crs   - 2 * nn_hls + (jpni-1) ) / jpni + 2 * nn_hls
+      jpj_crs = ( jpjglo_crsm1 - 2 * nn_hls + (jpnj-1) ) / jpnj + 2 * nn_hls   
+              
+      IF( noso < 0 ) jpj_crs = jpj_crs + 1    ! add a local band on southern processors  
+       
+      jpi_crsm1   = jpi_crs - 1
+      jpj_crsm1   = jpj_crs - 1
+      nperio_crs  = jperio
+      npolj_crs   = npolj
+      
+      ierr = crs_dom_alloc()          ! allocate most coarse grid arrays
+
+      ! 2.a Define processor domain
+      IF( .NOT. lk_mpp ) THEN
+         nimpp_crs  = 1
+         njmpp_crs  = 1
+         nlci_crs   = jpi_crs
+         nlcj_crs   = jpj_crs
+         nldi_crs   = 1
+         nldj_crs   = 1
+         nlei_crs   = jpi_crs
+         nlej_crs   = jpj_crs
+      ELSE
+         ! Initialisation of most local variables -
+         nimpp_crs  = 1
+         njmpp_crs  = 1
+         nlci_crs   = jpi_crs
+         nlcj_crs   = jpj_crs
+         nldi_crs   = 1
+         nldj_crs   = 1
+         nlei_crs   = jpi_crs
+         nlej_crs   = jpj_crs
+         
+        ! Calculs suivant une découpage en j
+        DO jn = 1, jpnij, jpni
+           IF( jn < ( jpnij - jpni + 1 ) ) THEN
+              nlejt_crs(jn) = AINT( REAL( ( jpjglo - (njmppt(jn     ) - 1) ) / nn_facty, wp ) ) &
+                       &    - AINT( REAL( ( jpjglo - (njmppt(jn+jpni) - 1) ) / nn_facty, wp ) )
+           ELSE                                             
+              nlejt_crs(jn) = AINT( REAL(  nlejt(jn) / nn_facty, wp ) ) + 1            
+           ENDIF
+           IF( noso < 0 ) nlejt_crs(jn) = nlejt_crs(jn) + 1             
+           SELECT CASE( ibonjt(jn) )
+              CASE ( -1 )
+                IF( MOD( jpjglo - njmppt(jn), nn_facty) > 0 )  nlejt_crs(jn) = nlejt_crs(jn) + 1
+                nlcjt_crs(jn) = nlejt_crs(jn) + nn_hls
+                nldjt_crs(jn) = nldjt(jn)
+              
+              CASE ( 0 )
+              
+                nldjt_crs(jn) = nldjt(jn)
+                IF( nldjt(jn) == 1 )  nlejt_crs(jn) = nlejt_crs(jn) + 1
+                nlejt_crs(jn) = nlejt_crs(jn) + nn_hls
+                nlcjt_crs(jn) = nlejt_crs(jn) + nn_hls
+                
+              CASE ( 1, 2 )
+              
+                nlejt_crs(jn) = nlejt_crs(jn) + nn_hls
+                nlcjt_crs(jn) = nlejt_crs(jn)
+                nldjt_crs(jn) = nldjt(jn)
+                
+              CASE DEFAULT
+                 CALL ctl_stop( 'STOP', 'error from crs_dom_def, you should not be there (1) ...' )
+           END SELECT
+           IF( nlcjt_crs(jn) > jpj_crs )     jpj_crs = jpj_crs + 1
+
+           IF(nldjt_crs(jn) == 1 ) THEN
+              njmppt_crs(jn) = 1
+           ELSE
+              njmppt_crs(jn) = 2 + ANINT(REAL((njmppt(jn) + 1 - MOD( jpjglo , nn_facty )) / nn_facty, wp ) )
+           ENDIF           
+           
+           DO jj = jn + 1, jn + jpni - 1
+              nlejt_crs(jj) = nlejt_crs(jn) 
+              nlcjt_crs(jj) = nlcjt_crs(jn)
+              nldjt_crs(jj) = nldjt_crs(jn)
+              njmppt_crs(jj)= njmppt_crs(jn)
+           ENDDO
+        ENDDO 
+        nlej_crs  = nlejt_crs(nproc + 1) 
+        nlcj_crs  = nlcjt_crs(nproc + 1)
+        nldj_crs  = nldjt_crs(nproc + 1)
+        njmpp_crs = njmppt_crs(nproc + 1)
+
+        ! Calcul suivant un decoupage en i
+        DO jn = 1, jpni
+           IF( jn == 1 ) THEN          
+              nleit_crs(jn) = AINT( REAL( ( nimppt(jn  ) - 1 + nlcit(jn  ) )  / nn_factx, wp) )
+           ELSE
+              nleit_crs(jn) = AINT( REAL( ( nimppt(jn  ) - 1 + nlcit(jn  ) )  / nn_factx, wp) ) &
+                 &          - AINT( REAL( ( nimppt(jn-1) - 1 + nlcit(jn-1) )  / nn_factx, wp) )
+           ENDIF
+
+           SELECT CASE( ibonit(jn) )
+              CASE ( -1 )
+                 nleit_crs(jn) = nleit_crs(jn) + nn_hls           
+                 nlcit_crs(jn) = nleit_crs(jn) + nn_hls
+                 nldit_crs(jn) = nldit(jn) 
+              
+              CASE ( 0 )
+                 nleit_crs(jn) = nleit_crs(jn) + nn_hls
+                 nlcit_crs(jn) = nleit_crs(jn) + nn_hls
+                 nldit_crs(jn) = nldit(jn) 
+                
+              CASE ( 1, 2 )
+                 IF( MOD( jpiglo - nimppt(jn), nn_factx) > 0 )  nleit_crs(jn) = nleit_crs(jn) + 1
+                 nleit_crs(jn) = nleit_crs(jn) + nn_hls
+                 nlcit_crs(jn) = nleit_crs(jn)
+                 nldit_crs(jn) = nldit(jn) 
+
+              CASE DEFAULT
+                 CALL ctl_stop( 'STOP', 'error from crs_dom_def, you should not be there (2) ...' )
+           END SELECT
+
+           nimppt_crs(jn) = ANINT( REAL( (nimppt(jn) + 1 ) / nn_factx, wp ) ) + 1
+           DO jj = jn + jpni , jpnij, jpni
+              nleit_crs(jj) = nleit_crs(jn) 
+              nlcit_crs(jj) = nlcit_crs(jn)
+              nldit_crs(jj) = nldit_crs(jn)
+              nimppt_crs(jj)= nimppt_crs(jn)
+           ENDDO
+         ENDDO 
+        
+         nlei_crs  = nleit_crs(nproc + 1) 
+         nlci_crs  = nlcit_crs(nproc + 1)
+         nldi_crs  = nldit_crs(nproc + 1)
+         nimpp_crs = nimppt_crs(nproc + 1)
+
+         DO ji = 1, jpi_crs
+            mig_crs(ji) = ji + nimpp_crs - 1
+         ENDDO
+         DO jj = 1, jpj_crs
+            mjg_crs(jj) = jj + njmpp_crs - 1!
+         ENDDO
+       
+         DO ji = 1, jpiglo_crs
+            mi0_crs(ji) = MAX( 1, MIN( ji - nimpp_crs + 1 , jpi_crs + 1 ) )
+            mi1_crs(ji) = MAX( 0, MIN( ji - nimpp_crs + 1 , jpi_crs     ) )
+         ENDDO
+         
+         DO jj = 1, jpjglo_crs
+            mj0_crs(jj) = MAX( 1, MIN( jj - njmpp_crs + 1 , jpj_crs + 1 ) )
+            mj1_crs(jj) = MAX( 0, MIN( jj - njmpp_crs + 1 , jpj_crs     ) )
+         ENDDO
+
+      ENDIF
+      
+      !                         Save the parent grid information
+      jpi_full    = jpi
+      jpj_full    = jpj
+      jpim1_full  = jpim1
+      jpjm1_full  = jpjm1
+      nperio_full = jperio
+
+      npolj_full  = npolj
+      jpiglo_full = jpiglo
+      jpjglo_full = jpjglo
+
+      nlcj_full   = nlcj
+      nlci_full   = nlci
+      nldi_full   = nldi
+      nldj_full   = nldj
+      nlei_full   = nlei
+      nlej_full   = nlej
+      nimpp_full  = nimpp     
+      njmpp_full  = njmpp
+      
+      nlcit_full(:)  = nlcit(:)
+      nldit_full(:)  = nldit(:)
+      nleit_full(:)  = nleit(:)
+      nimppt_full(:) = nimppt(:)
+      nlcjt_full(:)  = nlcjt(:)
+      nldjt_full(:)  = nldjt(:)
+      nlejt_full(:)  = nlejt(:)
+      njmppt_full(:) = njmppt(:)
+      
+      CALL dom_grid_crs  !swich de grille
+     
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'crs_init : coarse grid dimensions'
+         WRITE(numout,*) '~~~~~~~   coarse domain global j-dimension           jpjglo = ', jpjglo
+         WRITE(numout,*) '~~~~~~~   coarse domain global i-dimension           jpiglo = ', jpiglo
+         WRITE(numout,*) '~~~~~~~   coarse domain local  i-dimension              jpi = ', jpi
+         WRITE(numout,*) '~~~~~~~   coarse domain local  j-dimension              jpj = ', jpj
+         WRITE(numout,*)
+         WRITE(numout,*) ' nproc  = '     , nproc
+         WRITE(numout,*) ' nlci   = '     , nlci
+         WRITE(numout,*) ' nlcj   = '     , nlcj
+         WRITE(numout,*) ' nldi   = '     , nldi
+         WRITE(numout,*) ' nldj   = '     , nldj
+         WRITE(numout,*) ' nlei   = '     , nlei
+         WRITE(numout,*) ' nlej   = '     , nlej
+         WRITE(numout,*) ' nlei_full='    , nlei_full
+         WRITE(numout,*) ' nldi_full='    , nldi_full
+         WRITE(numout,*) ' nimpp  = '     , nimpp
+         WRITE(numout,*) ' njmpp  = '     , njmpp
+         WRITE(numout,*) ' njmpp_full  = ', njmpp_full
+         WRITE(numout,*)
+      ENDIF
+      
+      CALL dom_grid_glo
+      
+      mxbinctr   = INT( nn_factx * 0.5 )
+      mybinctr   = INT( nn_facty * 0.5 )
+
+      nrestx = MOD( nn_factx, 2 )   ! check if even- or odd- numbered reduction factor
+      nresty = MOD( nn_facty, 2 )
+
+      IF ( nrestx == 0 ) THEN
+         mxbinctr = mxbinctr - 1
+      ENDIF
+
+      IF ( nresty == 0 ) THEN
+         mybinctr = mybinctr - 1
+         IF ( jperio == 3 .OR. jperio == 4 )  nperio_crs = jperio + 2
+         IF ( jperio == 5 .OR. jperio == 6 )  nperio_crs = jperio - 2 
+
+         IF ( npolj == 3 ) npolj_crs = 5
+         IF ( npolj == 5 ) npolj_crs = 3
+      ENDIF     
+      
+      rfactxy = nn_factx * nn_facty
+      
+      ! 2.b. Set up bins for coarse grid, horizontal only.
+      ierr = crs_dom_alloc2()
+     
+      mis2_crs(:) = 0      ;      mie2_crs(:) = 0
+      mjs2_crs(:) = 0      ;      mje2_crs(:) = 0
+
+      
+      SELECT CASE ( nn_binref )
+
+      CASE ( 0 ) 
+
+         SELECT CASE ( jperio )
+     
+ 
+        CASE ( 0, 1, 3, 4 )    !   3, 4 : T-Pivot at North Fold
+        
+            DO ji = 2, jpiglo_crsm1
+               ijie = ( ji * nn_factx ) - nn_factx   !cc
+               ijis = ijie - nn_factx + 1
+               mis2_crs(ji) = ijis
+               mie2_crs(ji) = ijie
+            ENDDO
+            IF ( jpiglo - 1 - mie2_crs(jpiglo_crsm1) <= nn_factx ) mie2_crs(jpiglo_crsm1) = jpiglo - 2  
+
+            ! Handle first the northernmost bin
+            IF ( nn_facty == 2 ) THEN   ;    ijjgloT = jpjglo - 1 
+            ELSE                        ;    ijjgloT = jpjglo
+            ENDIF
+
+            DO jj = 2, jpjglo_crs
+                ijje = ijjgloT - nn_facty * ( jj - 3 )
+                ijjs = ijje - nn_facty + 1                   
+                mjs2_crs(jpjglo_crs-jj+2) = ijjs
+                mje2_crs(jpjglo_crs-jj+2) = ijje
+            ENDDO
+
+         CASE ( 2 ) 
+            WRITE(numout,*)  'crs_init, jperio=2 not supported' 
+        
+         CASE ( 5, 6 )    ! F-pivot at North Fold
+
+            DO ji = 2, jpiglo_crsm1
+               ijie = ( ji * nn_factx ) - nn_factx 
+               ijis = ijie - nn_factx + 1
+               mis2_crs(ji) = ijis
+               mie2_crs(ji) = ijie
+            ENDDO
+            IF ( jpiglo - 1 - mie2_crs(jpiglo_crsm1) <= nn_factx ) mie_crs(jpiglo_crsm1)  = jpiglo - 2 
+
+            ! Treat the northernmost bin separately.
+            jj = 2
+            ijje = jpj - nn_facty * ( jj - 2 )
+            IF ( nn_facty == 3 ) THEN   ;  ijjs = ijje - 1 
+            ELSE                        ;  ijjs = ijje - nn_facty + 1
+            ENDIF
+            mjs2_crs(jpj_crs-jj+1) = ijjs
+            mje2_crs(jpj_crs-jj+1) = ijje
+
+            ! Now bin the rest, any remainder at the south is lumped in the southern bin
+            DO jj = 3, jpjglo_crsm1
+                ijje = jpjglo - nn_facty * ( jj - 2 )
+                ijjs = ijje - nn_facty + 1                  
+                IF ( ijjs <= nn_facty )  ijjs = 2
+                mjs2_crs(jpj_crs-jj+1)   = ijjs
+                mje2_crs(jpj_crs-jj+1)   = ijje
+            ENDDO
+
+         CASE DEFAULT
+            WRITE(numout,*) 'crs_init. Only jperio = 0, 1, 3, 4, 5, 6 supported' 
+ 
+         END SELECT
+
+      CASE (1 )
+         WRITE(numout,*) 'crs_init.  Equator-centered bins option not yet available' 
+
+      END SELECT
+
+     ! Pad the boundaries, do not know if it is necessary
+      mis2_crs(2) = 1             ;  mis2_crs(jpiglo_crs) = mie2_crs(jpiglo_crs - 1) + 1   
+      mie2_crs(2) = nn_factx      ;  mie2_crs(jpiglo_crs) = jpiglo                         
+      !
+      mjs2_crs(1) = 1
+      mje2_crs(1) = 1
+      !
+      mje2_crs(2) = mjs2_crs(3)-1 ;  mje2_crs(jpjglo_crs) = jpjglo
+      mjs2_crs(2) = 1             ;  mjs2_crs(jpjglo_crs) = mje2_crs(jpjglo_crs) - nn_facty + 1 
+ 
+      IF( .NOT. lk_mpp ) THEN     
+        mis_crs(:) = mis2_crs(:) 
+        mie_crs(:) = mie2_crs(:)
+        mjs_crs(:) = mjs2_crs(:) 
+        mje_crs(:) = mje2_crs(:) 
+      ELSE
+        DO jj = 1, nlej_crs
+           mjs_crs(jj) = mjs2_crs(mjg_crs(jj)) - njmpp + 1
+           mje_crs(jj) = mje2_crs(mjg_crs(jj)) - njmpp + 1
+        ENDDO
+        DO ji = 1, nlei_crs
+           mis_crs(ji) = mis2_crs(mig_crs(ji)) - nimpp + 1
+           mie_crs(ji) = mie2_crs(mig_crs(ji)) - nimpp + 1
+        ENDDO
+      ENDIF
+      !
+      nistr = mis_crs(2)  ;   niend = mis_crs(nlci_crs - 1)
+      njstr = mjs_crs(3)  ;   njend = mjs_crs(nlcj_crs - 1)
+      !
+   END SUBROUTINE crs_dom_def
+   
+   SUBROUTINE crs_dom_bat
+      !!----------------------------------------------------------------
+      !!               *** SUBROUTINE crs_dom_bat ***
+      !! ** Purpose :  coarsenig bathy
+      !!----------------------------------------------------------------
+      !! 
+      !!  local variables
+      INTEGER  :: ji,jj,jk      ! dummy indices
+      REAL(wp), DIMENSION(jpi_crs, jpj_crs) :: zmbk
+      !!----------------------------------------------------------------
+   
+      mbathy_crs(:,:) = jpkm1
+      mbkt_crs(:,:) = 1
+      mbku_crs(:,:) = 1
+      mbkv_crs(:,:) = 1
+
+
+      DO jj = 1, jpj_crs
+         DO ji = 1, jpi_crs
+            jk = 0
+            DO WHILE( tmask_crs(ji,jj,jk+1) > 0.)
+               jk = jk + 1
+            ENDDO
+            mbathy_crs(ji,jj) = float( jk )
+         ENDDO
+      ENDDO
+     
+      zmbk(:,:) = 0.0
+      zmbk(:,:) = REAL( mbathy_crs(:,:), wp ) ;   CALL crs_lbc_lnk(zmbk,'T',1.0)   ;   mbathy_crs(:,:) = NINT( zmbk(:,:) )
+
+
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    crsini : mbkt is ocean bottom k-index of T-, U-, V- and W-levels '
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~~~'
+      !
+      mbkt_crs(:,:) = MAX( mbathy_crs(:,:) , 1 )    ! bottom k-index of T-level (=1 over land)
+      !                                     ! bottom k-index of W-level = mbkt+1
+
+      DO jj = 1, jpj_crsm1                      ! bottom k-index of u- (v-) level
+         DO ji = 1, jpi_crsm1
+            mbku_crs(ji,jj) = MIN(  mbkt_crs(ji+1,jj  ) , mbkt_crs(ji,jj)  )
+            mbkv_crs(ji,jj) = MIN(  mbkt_crs(ji  ,jj+1) , mbkt_crs(ji,jj)  )
+         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
+      zmbk(:,:) = 1.e0;    
+      zmbk(:,:) = REAL( mbku_crs(:,:), wp )   ;   CALL crs_lbc_lnk(zmbk,'U',1.0) ; mbku_crs  (:,:) = MAX( NINT( zmbk(:,:) ), 1 ) 
+      zmbk(:,:) = REAL( mbkv_crs(:,:), wp )   ;   CALL crs_lbc_lnk(zmbk,'V',1.0) ; mbkv_crs  (:,:) = MAX( NINT( zmbk(:,:) ), 1 ) 
+      !
+   END SUBROUTINE crs_dom_bat
+
+
+END MODULE crsdom
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdomwri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdomwri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsdomwri.F90	(revision 14097)
@@ -0,0 +1,237 @@
+MODULE crsdomwri
+   !!======================================================================
+   !! Coarse Ocean initialization : write the coarse ocean domain mesh and mask files
+   !!======================================================================
+   !! History :  3.6   ! 2012-06  (J. Simeon, C. Calone, C Ethe )  from domwri, reduced and modified for coarse grid
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   crs_dom_wri    : create and write mesh and mask file(s)
+   !!----------------------------------------------------------------------
+   USE timing          ! Timing
+   USE dom_oce         ! ocean space and time domain
+   USE in_out_manager  ! I/O manager
+   USE par_kind, ONLY: wp
+   USE lib_mpp         ! MPP library
+   USE iom_def
+   USE iom
+   USE crs         ! coarse grid domain
+   USE crsdom         ! coarse grid domain
+   USE crslbclnk       ! crs mediator to lbclnk
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC crs_dom_wri        ! routine called by crsini.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE crs_dom_wri
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE crs_dom_wri  ***
+      !!
+      !! ** Purpose :   Create the NetCDF file(s) which contain(s) all the
+      !!      ocean domain informations (mesh and mask arrays). This (these)
+      !!      file(s) is (are) used for visualisation (SAXO software) and
+      !!      diagnostic computation.
+      !!
+      !! ** Method  :   Write in a file all the arrays generated in routines
+      !!      crsini for meshes and mask. In three separate files: 
+      !!      domain size, horizontal grid-point position,
+      !!      masks, depth and vertical scale factors
+      !!      
+      !! ** Output files :   mesh_hgr_crs.nc, mesh_zgr_crs.nc, mesh_mask.nc
+      !!----------------------------------------------------------------------
+      INTEGER           ::   ji, jj, jk   ! dummy loop indices
+      INTEGER           ::   inum         ! local units for 'mesh_mask.nc' file
+      INTEGER           ::   iif, iil, ijf, ijl
+      CHARACTER(len=21) ::   clnam        ! filename (mesh and mask informations)
+      !                                   !  workspace
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs    ) ::   zprt, zprw 
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk) ::   zdepu, zdepv
+      !!----------------------------------------------------------------------
+      !
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'crs_dom_wri : create NetCDF mesh and mask file'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      
+      clnam = 'mesh_mask_crs'  ! filename (mesh and mask informations)
+      
+
+      !                            ! ============================
+      !                            !  create 'mesh_mask.nc' file
+      !                            ! ============================
+      !
+      CALL iom_open( TRIM(clnam), inum, ldwrt = .TRUE. )
+ 
+      CALL iom_rstput( 0, 0, inum, 'tmask', tmask_crs, ktype = jp_i1 )    ! land-sea mask
+      CALL iom_rstput( 0, 0, inum, 'umask', umask_crs, ktype = jp_i1 )
+      CALL iom_rstput( 0, 0, inum, 'vmask', vmask_crs, ktype = jp_i1 )
+      CALL iom_rstput( 0, 0, inum, 'fmask', fmask_crs, ktype = jp_i1 )
+      
+      
+      tmask_i_crs(:,:) = tmask_crs(:,:,1)
+      iif = nn_hls
+      iil = nlci_crs - nn_hls + 1
+      ijf = nn_hls
+      ijl = nlcj_crs - nn_hls + 1
+     
+      tmask_i_crs( 1:iif ,    :  ) = 0._wp
+      tmask_i_crs(iil:jpi_crs,    :  ) = 0._wp
+      tmask_i_crs(   :   , 1:ijf ) = 0._wp
+      tmask_i_crs(   :   ,ijl:jpj_crs) = 0._wp
+      
+      
+      tpol_crs(1:jpiglo_crs,:) = 1._wp
+      fpol_crs(1:jpiglo_crs,:) = 1._wp
+      IF( jperio == 3 .OR. jperio == 4 ) THEN
+         tpol_crs(jpiglo_crs/2+1:jpiglo_crs,:) = 0._wp
+         fpol_crs(       1      :jpiglo_crs,:) = 0._wp
+         IF( mjg_crs(nlej_crs) == jpiglo_crs ) THEN
+            DO ji = iif+1, iil-1
+               tmask_i_crs(ji,nlej_crs-1) = tmask_i_crs(ji,nlej_crs-1) &
+               & * tpol_crs(mig_crs(ji),1)
+            ENDDO
+         ENDIF
+      ENDIF
+      IF( jperio == 5 .OR. jperio == 6 ) THEN
+         tpol_crs(      1       :jpiglo_crs,:)=0._wp
+         fpol_crs(jpiglo_crs/2+1:jpiglo_crs,:)=0._wp
+      ENDIF
+      
+      CALL iom_rstput( 0, 0, inum, 'tmaskutil', tmask_i_crs, ktype = jp_i1 )
+                                   !    ! unique point mask
+      CALL dom_uniq_crs( zprw, 'U' )
+      zprt = umask_crs(:,:,1) * zprw
+      CALL iom_rstput( 0, 0, inum, 'umaskutil', zprt, ktype = jp_i1 )  
+      CALL dom_uniq_crs( zprw, 'V' )
+      zprt = vmask_crs(:,:,1) * zprw
+      CALL iom_rstput( 0, 0, inum, 'vmaskutil', zprt, ktype = jp_i1 )  
+      CALL dom_uniq_crs( zprw, 'F' )
+      zprt = fmask_crs(:,:,1) * zprw
+      CALL iom_rstput( 0, 0, inum, 'fmaskutil', zprt, ktype = jp_i1 )  
+      !========================================================
+      !                                                         ! horizontal mesh
+      CALL iom_rstput( 0, 0, inum, 'glamt', glamt_crs, ktype = jp_r4 )     !    ! latitude
+      CALL iom_rstput( 0, 0, inum, 'glamu', glamu_crs, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'glamv', glamv_crs, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'glamf', glamf_crs, ktype = jp_r4 )
+      
+      CALL iom_rstput( 0, 0, inum, 'gphit', gphit_crs, ktype = jp_r4 )     !    ! longitude
+      CALL iom_rstput( 0, 0, inum, 'gphiu', gphiu_crs, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'gphiv', gphiv_crs, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'gphif', gphif_crs, ktype = jp_r4 )
+      
+      CALL iom_rstput( 0, 0, inum, 'e1t', e1t_crs, ktype = jp_r8 )         !    ! e1 scale factors
+      CALL iom_rstput( 0, 0, inum, 'e1u', e1u_crs, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1v', e1v_crs, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1f', e1f_crs, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'e2t', e2t_crs, ktype = jp_r8 )         !    ! e2 scale factors
+      CALL iom_rstput( 0, 0, inum, 'e2u', e2u_crs, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2v', e2v_crs, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2f', e2f_crs, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'ff', ff_crs, ktype = jp_r8 )           !    ! coriolis factor
+
+      !========================================================
+      !                                                         ! vertical mesh
+!     ! note that mbkt is set to 1 over land ==> use surface tmask_crs
+      zprt(:,:) = tmask_crs(:,:,1) * REAL( mbkt_crs(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum, 'mbathy', zprt, ktype = jp_i2 )     !    ! nb of ocean T-points
+      !
+      CALL iom_rstput( 0, 0, inum, 'e3t', e3t_crs )      
+      CALL iom_rstput( 0, 0, inum, 'e3w', e3w_crs )      
+      CALL iom_rstput( 0, 0, inum, 'e3u', e3u_crs )      
+      CALL iom_rstput( 0, 0, inum, 'e3v', e3v_crs )      
+      !
+      CALL iom_rstput( 0, 0, inum, 'gdept', gdept_crs, ktype = jp_r4 ) 
+      DO jk = 1,jpk   
+         DO jj = 1, jpj_crsm1   
+            DO ji = 1, jpi_crsm1  ! jes what to do for fs_jpim1??vector opt.
+               zdepu(ji,jj,jk) = MIN( gdept_crs(ji,jj,jk) , gdept_crs(ji+1,jj  ,jk) ) * umask_crs(ji,jj,jk)
+               zdepv(ji,jj,jk) = MIN( gdept_crs(ji,jj,jk) , gdept_crs(ji  ,jj+1,jk) ) * vmask_crs(ji,jj,jk)
+            END DO   
+         END DO   
+      END DO
+      CALL crs_lbc_lnk( zdepu,'U', 1. )   ;   CALL crs_lbc_lnk( zdepv,'V', 1. ) 
+      !
+      CALL iom_rstput( 0, 0, inum, 'gdepu', zdepu, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'gdepv', zdepv, ktype = jp_r4 )
+      CALL iom_rstput( 0, 0, inum, 'gdepw', gdepw_crs, ktype = jp_r4 )
+      !
+      CALL iom_rstput( 0, 0, inum, 'gdept_1d', gdept_1d )     !    ! reference z-coord.
+      CALL iom_rstput( 0, 0, inum, 'gdepw_1d', gdepw_1d )
+      CALL iom_rstput( 0, 0, inum, 'e3t_1d'  , e3t_1d   )
+      CALL iom_rstput( 0, 0, inum, 'e3w_1d'  , e3w_1d   )
+      !
+      CALL iom_rstput(  0, 0, inum, 'ocean_volume_t', ocean_volume_crs_t ) 
+      CALL iom_rstput(  0, 0, inum, 'facvol_t' , facvol_t  ) 
+      CALL iom_rstput(  0, 0, inum, 'facvol_w' , facvol_w  ) 
+      CALL iom_rstput(  0, 0, inum, 'facsurfu' , facsurfu  ) 
+      CALL iom_rstput(  0, 0, inum, 'facsurfv' , facsurfv  ) 
+      CALL iom_rstput(  0, 0, inum, 'e1e2w_msk', e1e2w_msk ) 
+      CALL iom_rstput(  0, 0, inum, 'e2e3u_msk', e2e3u_msk ) 
+      CALL iom_rstput(  0, 0, inum, 'e1e3v_msk', e1e3v_msk )
+      CALL iom_rstput(  0, 0, inum, 'e1e2w'    , e1e2w_crs ) 
+      CALL iom_rstput(  0, 0, inum, 'e2e3u'    , e2e3u_crs ) 
+      CALL iom_rstput(  0, 0, inum, 'e1e3v'    , e1e3v_crs )
+      CALL iom_rstput(  0, 0, inum, 'bt'       , bt_crs    )
+      CALL iom_rstput(  0, 0, inum, 'r1_bt'    , r1_bt_crs )
+      !
+      CALL iom_rstput(  0, 0, inum, 'crs_surfu_wgt', crs_surfu_wgt ) 
+      CALL iom_rstput(  0, 0, inum, 'crs_surfv_wgt', crs_surfv_wgt ) 
+      CALL iom_rstput(  0, 0, inum, 'crs_volt_wgt' , crs_volt_wgt  ) 
+      !                                     ! ============================
+      !                                     !        close the files 
+      !                                     ! ============================
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE crs_dom_wri
+
+
+   SUBROUTINE dom_uniq_crs( puniq, cdgrd )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE crs_dom_uniq_crs  ***
+      !!                   
+      !! ** Purpose :   identify unique point of a grid (TUVF)
+      !!
+      !! ** Method  :   1) apply crs_lbc_lnk on an array with different values for each element
+      !!                2) check which elements have been changed
+      !!----------------------------------------------------------------------
+      CHARACTER(len=1)        , INTENT(in   ) ::   cdgrd   ! 
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   puniq   ! 
+      !
+      REAL(wp) ::  zshift   ! shift value link to the process number
+      INTEGER  ::  ji       ! dummy loop indices
+      LOGICAL, DIMENSION(SIZE(puniq,1),SIZE(puniq,2),1) ::  lldbl  ! store whether each point is unique or not
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs) :: ztstref
+      !!----------------------------------------------------------------------
+      !
+      ! build an array with different values for each element 
+      ! in mpp: make sure that these values are different even between process
+      ! -> apply a shift value according to the process number
+      zshift = jpi_crs * jpj_crs * ( narea - 1 )
+      ztstref(:,:) = RESHAPE( (/ (zshift + REAL(ji,wp), ji = 1, jpi_crs*jpj_crs) /), (/ jpi_crs, jpj_crs /) )
+      !
+      puniq(:,:) = ztstref(:,:)                   ! default definition
+      CALL crs_lbc_lnk( puniq,cdgrd, 1. )            ! apply boundary conditions
+      lldbl(:,:,1) = puniq(:,:) == ztstref(:,:)   ! check which values have been changed 
+      !
+      puniq(:,:) = 1.                             ! default definition
+      ! fill only the inner part of the cpu with llbl converted into real 
+      puniq(nldi_crs:nlei_crs,nldj_crs:nlej_crs) = REAL( COUNT( lldbl(nldi_crs:nlei_crs,nldj_crs:nlej_crs,:), dim = 3 ) , wp )
+      !
+   END SUBROUTINE dom_uniq_crs
+
+   !!======================================================================
+
+END MODULE crsdomwri
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsfld.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsfld.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsfld.F90	(revision 14097)
@@ -0,0 +1,250 @@
+MODULE crsfld
+   !!======================================================================
+   !!                     ***  MODULE  crsdfld  ***
+   !!  Ocean coarsening :  coarse ocean fields
+   !!=====================================================================
+   !!   2012-07  (J. Simeon, C. Calone, G. Madec, C. Ethe)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   crs_fld       : create the standard output files for coarse grid and prep
+   !!                       other variables needed to be passed to TOP
+   !!----------------------------------------------------------------------
+   USE crs
+   USE crsdom
+   USE crslbclnk
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE zdf_oce         ! vertical  physics: ocean fields
+   USE ldftra          ! ocean active tracers: lateral diffusivity & EIV coefficients
+   USE zdfddm          ! vertical  physics: double diffusion
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! 
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   crs_fld                 ! routines called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE crs_fld( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE crs_fld  ***
+      !!                   
+      !! ** Purpose :   Basic output of coarsened dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!      1. Accumulate in time the dimensionally-weighted fields
+      !!      2. At time of output, rescale [1] by dimension and time
+      !!         to yield the spatial and temporal average.
+      !!  See. sbcmod.F90
+      !!
+      !! ** Method  :  
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk        ! dummy loop indices
+      REAL(wp) ::   z2dcrsu, z2dcrsv  ! local scalars
+      REAL(wp) ::   zztmp             !   -      -
+      !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ze3t, ze3u, ze3v, ze3w   ! 3D workspace for e3
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zt  , zs  , z3d
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk) ::   zt_crs, zs_crs  
+      !!----------------------------------------------------------------------
+      ! 
+      IF( ln_timing )   CALL timing_start('crs_fld')
+
+      ! Depth work arrrays
+      ze3t(:,:,:) = e3t_n(:,:,:)
+      ze3u(:,:,:) = e3u_n(:,:,:)
+      ze3v(:,:,:) = e3v_n(:,:,:)
+      ze3w(:,:,:) = e3w_n(:,:,:)
+
+      IF( kt == nit000  ) THEN
+         tsn_crs  (:,:,:,:) = 0._wp    ! temp/sal  array, now 
+         un_crs   (:,:,:  ) = 0._wp    ! u-velocity
+         vn_crs   (:,:,:  ) = 0._wp    ! v-velocity
+         wn_crs   (:,:,:  ) = 0._wp    ! w
+         avs_crs  (:,:,:  ) = 0._wp    ! avt
+         hdivn_crs(:,:,:  ) = 0._wp    ! hdiv
+         sshn_crs (:,:    ) = 0._wp    ! ssh
+         utau_crs (:,:    ) = 0._wp    ! taux
+         vtau_crs (:,:    ) = 0._wp    ! tauy
+         wndm_crs (:,:    ) = 0._wp    ! wind speed
+         qsr_crs  (:,:    ) = 0._wp    ! qsr
+         emp_crs  (:,:    ) = 0._wp    ! emp
+         emp_b_crs(:,:    ) = 0._wp    ! emp
+         rnf_crs  (:,:    ) = 0._wp    ! runoff
+         fr_i_crs (:,:    ) = 0._wp    ! ice cover
+      ENDIF
+
+      CALL iom_swap( "nemo_crs" )    ! swap on the coarse grid
+
+      ! 2. Coarsen fields at each time step
+      ! --------------------------------------------------------
+
+      !  Temperature
+      zt(:,:,:) = tsn(:,:,:,jp_tem)  ;      zt_crs(:,:,:) = 0._wp
+      CALL crs_dom_ope( zt, 'VOL', 'T', tmask, zt_crs, p_e12=e1e2t, p_e3=ze3t, psgn=1.0 )
+      tsn_crs(:,:,:,jp_tem) = zt_crs(:,:,:)
+
+      CALL iom_put( "toce", tsn_crs(:,:,:,jp_tem) )    ! temp
+      CALL iom_put( "sst" , tsn_crs(:,:,1,jp_tem) )    ! sst
+
+      
+      !  Salinity
+      zs(:,:,:) = tsn(:,:,:,jp_sal)  ;      zs_crs(:,:,:) = 0._wp
+      CALL crs_dom_ope( zs, 'VOL', 'T', tmask, zs_crs, p_e12=e1e2t, p_e3=ze3t, psgn=1.0 )
+      tsn_crs(:,:,:,jp_sal) = zt_crs(:,:,:)
+
+      CALL iom_put( "soce" , tsn_crs(:,:,:,jp_sal) )    ! sal
+      CALL iom_put( "sss"  , tsn_crs(:,:,1,jp_sal) )    ! sss
+
+      !  U-velocity
+      CALL crs_dom_ope( un, 'SUM', 'U', umask, un_crs, p_e12=e2u, p_e3=ze3u, p_surf_crs=e2e3u_msk, psgn=-1.0 )
+      !
+      zt(:,:,:) = 0._wp     ;    zs(:,:,:) = 0._wp  ;   zt_crs(:,:,:) = 0._wp   ;    zs_crs(:,:,:) = 0._wp
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   
+               zt(ji,jj,jk)  = un(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_tem) + tsn(ji+1,jj,jk,jp_tem) ) 
+               zs(ji,jj,jk)  = un(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) ) 
+            END DO
+         END DO
+      END DO
+      CALL crs_dom_ope( zt, 'SUM', 'U', umask, zt_crs, p_e12=e2u, p_e3=ze3u, p_surf_crs=e2e3u_msk, psgn=-1.0 )
+      CALL crs_dom_ope( zs, 'SUM', 'U', umask, zs_crs, p_e12=e2u, p_e3=ze3u, p_surf_crs=e2e3u_msk, psgn=-1.0 )
+
+      CALL iom_put( "uoce"  , un_crs )   ! i-current 
+      CALL iom_put( "uocet" , zt_crs )   ! uT
+      CALL iom_put( "uoces" , zs_crs )   ! uS
+
+      !  V-velocity
+      CALL crs_dom_ope( vn, 'SUM', 'V', vmask, vn_crs, p_e12=e1v, p_e3=ze3v, p_surf_crs=e1e3v_msk, psgn=-1.0 )
+      !                                                                                 
+      zt(:,:,:) = 0._wp     ;    zs(:,:,:) = 0._wp  ;   zt_crs(:,:,:) = 0._wp   ;    zs_crs(:,:,:) = 0._wp
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   
+               zt(ji,jj,jk)  = vn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj+1,jk,jp_tem) ) 
+               zs(ji,jj,jk)  = vn(ji,jj,jk) * 0.5 * ( tsn(ji,jj,jk,jp_sal) + tsn(ji,jj+1,jk,jp_sal) ) 
+            END DO
+         END DO
+      END DO
+      CALL crs_dom_ope( zt, 'SUM', 'V', vmask, zt_crs, p_e12=e1v, p_e3=ze3v, p_surf_crs=e1e3v_msk, psgn=-1.0 )
+      CALL crs_dom_ope( zs, 'SUM', 'V', vmask, zs_crs, p_e12=e1v, p_e3=ze3v, p_surf_crs=e1e3v_msk, psgn=-1.0 )
+ 
+      CALL iom_put( "voce"  , vn_crs )   ! i-current 
+      CALL iom_put( "vocet" , zt_crs )   ! vT
+      CALL iom_put( "voces" , zs_crs )   ! vS
+
+      IF( iom_use( "eken") ) THEN     !      kinetic energy
+         z3d(:,:,jk) = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zztmp  = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  z3d(ji,jj,jk) = 0.25_wp * zztmp * (                                    &
+                     &            un(ji-1,jj,jk)**2 * e2u(ji-1,jj) * e3u_n(ji-1,jj,jk)   &
+                     &          + un(ji  ,jj,jk)**2 * e2u(ji  ,jj) * e3u_n(ji  ,jj,jk)   &
+                     &          + vn(ji,jj-1,jk)**2 * e1v(ji,jj-1) * e3v_n(ji,jj-1,jk)   &
+                     &          + vn(ji,jj  ,jk)**2 * e1v(ji,jj  ) * e3v_n(ji,jj  ,jk)   )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'crsfld', z3d, 'T', 1. )
+         !
+         CALL crs_dom_ope( z3d, 'VOL', 'T', tmask, zt_crs, p_e12=e1e2t, p_e3=ze3t, psgn=1.0 )
+         CALL iom_put( "eken", zt_crs )
+      ENDIF
+      !  Horizontal divergence ( following OCE/DYN/divhor.F90 ) 
+      DO jk = 1, jpkm1
+         DO ji = 2, jpi_crsm1
+            DO jj = 2, jpj_crsm1
+               IF( tmask_crs(ji,jj,jk ) > 0 ) THEN
+                   z2dcrsu =  ( un_crs(ji  ,jj  ,jk) * crs_surfu_wgt(ji  ,jj  ,jk) ) &
+                      &     - ( un_crs(ji-1,jj  ,jk) * crs_surfu_wgt(ji-1,jj  ,jk) )
+                   z2dcrsv =  ( vn_crs(ji  ,jj  ,jk) * crs_surfv_wgt(ji  ,jj  ,jk) ) &
+                      &     - ( vn_crs(ji  ,jj-1,jk) * crs_surfv_wgt(ji  ,jj-1,jk) )
+                   !
+                   hdivn_crs(ji,jj,jk) = ( z2dcrsu + z2dcrsv ) / crs_volt_wgt(ji,jj,jk) 
+               ENDIF
+            END DO
+         END DO
+      END DO
+      CALL crs_lbc_lnk( hdivn_crs, 'T', 1.0 )
+      !
+      CALL iom_put( "hdiv", hdivn_crs )  
+
+
+      !  W-velocity
+      IF( ln_crs_wn ) THEN
+         CALL crs_dom_ope( wn, 'SUM', 'W', tmask, wn_crs, p_e12=e1e2t, p_surf_crs=e1e2w_msk, psgn=1.0 )
+       !  CALL crs_dom_ope( wn, 'VOL', 'W', tmask, wn_crs, p_e12=e1e2t, p_e3=ze3w )
+      ELSE
+        wn_crs(:,:,jpk) = 0._wp
+        DO jk = jpkm1, 1, -1
+           wn_crs(:,:,jk) = wn_crs(:,:,jk+1) - e3t_crs(:,:,jk) * hdivn_crs(:,:,jk)
+        ENDDO
+      ENDIF
+      CALL iom_put( "woce", wn_crs  )   ! vertical velocity
+      !  free memory
+
+      !  avs
+      SELECT CASE ( nn_crs_kz )
+         CASE ( 0 )
+            CALL crs_dom_ope( avt, 'VOL', 'W', tmask, avt_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+            CALL crs_dom_ope( avs, 'VOL', 'W', tmask, avs_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+         CASE ( 1 )
+            CALL crs_dom_ope( avt, 'MAX', 'W', tmask, avt_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+            CALL crs_dom_ope( avs, 'MAX', 'W', tmask, avs_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+         CASE ( 2 )
+            CALL crs_dom_ope( avt, 'MIN', 'W', tmask, avt_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+            CALL crs_dom_ope( avs, 'MIN', 'W', tmask, avs_crs, p_e12=e1e2t, p_e3=ze3w, psgn=1.0 )
+      END SELECT
+      !
+      CALL iom_put( "avt", avt_crs )   !  Kz on T
+      CALL iom_put( "avs", avs_crs )   !  Kz on S
+      
+      !  sbc fields  
+      CALL crs_dom_ope( sshn , 'VOL', 'T', tmask, sshn_crs , p_e12=e1e2t, p_e3=ze3t           , psgn=1.0 )  
+      CALL crs_dom_ope( utau , 'SUM', 'U', umask, utau_crs , p_e12=e2u  , p_surf_crs=e2u_crs  , psgn=1.0 )
+      CALL crs_dom_ope( vtau , 'SUM', 'V', vmask, vtau_crs , p_e12=e1v  , p_surf_crs=e1v_crs  , psgn=1.0 )
+      CALL crs_dom_ope( wndm , 'SUM', 'T', tmask, wndm_crs , p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+      CALL crs_dom_ope( rnf  , 'MAX', 'T', tmask, rnf_crs                                     , psgn=1.0 )
+      CALL crs_dom_ope( qsr  , 'SUM', 'T', tmask, qsr_crs  , p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+      CALL crs_dom_ope( emp_b, 'SUM', 'T', tmask, emp_b_crs, p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+      CALL crs_dom_ope( emp  , 'SUM', 'T', tmask, emp_crs  , p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+      CALL crs_dom_ope( sfx  , 'SUM', 'T', tmask, sfx_crs  , p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+      CALL crs_dom_ope( fr_i , 'SUM', 'T', tmask, fr_i_crs , p_e12=e1e2t, p_surf_crs=e1e2t_crs, psgn=1.0 )
+
+      CALL iom_put( "ssh"      , sshn_crs )   ! ssh output 
+      CALL iom_put( "utau"     , utau_crs )   ! i-tau output 
+      CALL iom_put( "vtau"     , vtau_crs )   ! j-tau output 
+      CALL iom_put( "wspd"     , wndm_crs )   ! wind speed output 
+      CALL iom_put( "runoffs"  , rnf_crs  )   ! runoff output 
+      CALL iom_put( "qsr"      , qsr_crs  )   ! qsr output 
+      CALL iom_put( "empmr"    , emp_crs  )   ! water flux output 
+      CALL iom_put( "saltflx"  , sfx_crs  )   ! salt flux output 
+      CALL iom_put( "ice_cover", fr_i_crs )   ! ice cover output 
+
+      !
+      CALL iom_swap( "nemo" )     ! return back on high-resolution grid
+      !
+      IF( ln_timing )   CALL timing_stop('crs_fld')
+      !
+   END SUBROUTINE crs_fld
+
+   !!======================================================================
+END MODULE crsfld
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crsini.F90	(revision 14097)
@@ -0,0 +1,243 @@
+MODULE crsini   
+   !!======================================================================
+   !!                         ***  MODULE crsini  ***
+   !!            Manage the grid coarsening module initialization
+   !!======================================================================
+   !!  History     2012-05   (J. Simeon, G. Madec, C. Ethe, C. Calone) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  crs_init    : 
+   !!----------------------------------------------------------------------
+   USE par_kind, ONLY: wp
+   USE par_oce                  ! For parameter jpi,jpj
+   USE dom_oce                  ! For parameters in par_oce
+   USE crs                      ! Coarse grid domain
+   USE phycst, ONLY: omega, rad ! physical constants
+   USE crsdom
+   USE crsdomwri
+   USE crslbclnk
+   !
+   USE iom
+   USE in_out_manager
+   USE lib_mpp
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   crs_init   ! called by nemogcm.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE crs_init 
+      !!-------------------------------------------------------------------
+      !!                     *** SUBROUTINE crs_init
+      !!  ** Purpose : Initialization of the grid coarsening module  
+      !!               1. Read namelist
+      !!               X2. MOVE TO crs_dom.F90 Set the domain definitions for coarse grid
+      !!                 a. Define the coarse grid starting/ending indices on parent grid
+      !!                    Here is where the T-pivot or F-pivot grids are discerned
+      !!                 b. TODO.  Include option for north-centric or equator-centric binning.
+      !!                 (centered only for odd reduction factors; even reduction bins bias equator to the south)
+      !!               3. Mask and mesh creation. => calls to crsfun
+      !!                  a. Use crsfun_mask to generate tmask,umask, vmask, fmask.
+      !!                  b. Use crsfun_coordinates to get coordinates
+      !!                  c. Use crsfun_UV to get horizontal scale factors
+      !!                  d. Use crsfun_TW to get initial vertical scale factors   
+      !!               4. Volumes and weights jes.... TODO. Updates for vvl? Where to do this? crsstp.F90?
+      !!                  a. Calculate initial coarse grid box volumes: pvol_T, pvol_W
+      !!                  b. Calculate initial coarse grid surface-averaging weights
+      !!                  c. Calculate initial coarse grid volume-averaging weights
+      !!                  
+      !!               X5. MOVE TO crs_dom_wri.F90 Using iom_rstput output the initial meshmask.
+      !!               ?. Another set of "masks" to generate
+      !!                  are the u- and v- surface areas for U- and V- area-weighted means.
+      !!                  Need to put this somewhere in section 3?
+      !! jes. What do to about the vvl?  GM.  could separate the weighting (denominator), so
+      !! output C*dA or C*dV as summation not mran, then do mean (division) at moment of output.
+      !! As is, crsfun takes into account vvl.   
+      !!      Talked about pre-setting the surface array to avoid IF/ENDIF and division.
+      !!      But have then to make that preset array here and elsewhere.
+      !!      that is called every timestep...
+      !! 
+      !!               - Read in pertinent data ?
+      !!-------------------------------------------------------------------
+      INTEGER  :: ji,jj,jk      ! dummy indices
+      INTEGER  :: ierr                                ! allocation error status
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: ze3t, ze3u, ze3v, ze3w
+
+      NAMELIST/namcrs/ nn_factx, nn_facty, nn_binref, ln_msh_crs, nn_crs_kz, ln_crs_wn
+      !!----------------------------------------------------------------------
+      !
+     !---------------------------------------------------------
+     ! 1. Read Namelist file
+     !---------------------------------------------------------
+     !
+      REWIND( numnam_ref )              ! Namelist namrun in reference namelist : Parameters of the run
+      READ  ( numnam_ref, namcrs, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcrs in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namrun in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namcrs, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcrs in configuration namelist' )
+      IF(lwm) WRITE ( numond, namcrs )
+
+     IF(lwp) THEN
+        WRITE(numout,*)
+        WRITE(numout,*) 'crs_init : Initializing the grid coarsening module'
+        WRITE(numout,*) '~~~~~~~~'
+        WRITE(numout,*) '   Namelist namcrs '
+        WRITE(numout,*) '      coarsening factor in i-direction      nn_factx   = ', nn_factx
+        WRITE(numout,*) '      coarsening factor in j-direction      nn_facty   = ', nn_facty
+        WRITE(numout,*) '      bin centering preference              nn_binref  = ', nn_binref
+        WRITE(numout,*) '      create a mesh file (=T)               ln_msh_crs = ', ln_msh_crs
+        WRITE(numout,*) '      type of Kz coarsening (0,1,2)         nn_crs_kz  = ', nn_crs_kz
+        WRITE(numout,*) '      wn coarsened or computed using hdivn  ln_crs_wn  = ', ln_crs_wn
+     ENDIF
+              
+     rfactx_r = 1. / nn_factx
+     rfacty_r = 1. / nn_facty
+
+     !---------------------------------------------------------
+     ! 2. Define Global Dimensions of the coarsened grid
+     !---------------------------------------------------------
+     CALL crs_dom_def      
+
+     !---------------------------------------------------------
+     ! 3. Mask and Mesh
+     !---------------------------------------------------------
+
+     !     Set up the masks and meshes     
+
+     !  3.a. Get the masks   
+ 
+     CALL crs_dom_msk
+
+
+     !  3.b. Get the coordinates
+     !      Odd-numbered reduction factor, center coordinate on T-cell
+     !      Even-numbered reduction factor, center coordinate on U-,V- faces or f-corner.
+     !      
+     IF ( nresty /= 0 .AND. nrestx /= 0 ) THEN
+        CALL crs_dom_coordinates( gphit, glamt, 'T', gphit_crs, glamt_crs ) 
+        CALL crs_dom_coordinates( gphiu, glamu, 'U', gphiu_crs, glamu_crs )       
+        CALL crs_dom_coordinates( gphiv, glamv, 'V', gphiv_crs, glamv_crs ) 
+        CALL crs_dom_coordinates( gphif, glamf, 'F', gphif_crs, glamf_crs ) 
+     ELSEIF ( nresty /= 0 .AND. nrestx == 0 ) THEN
+        CALL crs_dom_coordinates( gphiu, glamu, 'T', gphit_crs, glamt_crs )
+        CALL crs_dom_coordinates( gphiu, glamu, 'U', gphiu_crs, glamu_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'V', gphiv_crs, glamv_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'F', gphif_crs, glamf_crs )
+     ELSEIF ( nresty == 0 .AND. nrestx /= 0 ) THEN
+        CALL crs_dom_coordinates( gphiv, glamv, 'T', gphit_crs, glamt_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'U', gphiu_crs, glamu_crs )
+        CALL crs_dom_coordinates( gphiv, glamv, 'V', gphiv_crs, glamv_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'F', gphif_crs, glamf_crs )
+     ELSE 
+        CALL crs_dom_coordinates( gphif, glamf, 'T', gphit_crs, glamt_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'U', gphiu_crs, glamu_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'V', gphiv_crs, glamv_crs )
+        CALL crs_dom_coordinates( gphif, glamf, 'F', gphif_crs, glamf_crs )
+     ENDIF
+
+
+     !  3.c. Get the horizontal mesh
+
+     !      3.c.1 Horizontal scale factors
+
+     CALL crs_dom_hgr( e1t, e2t, 'T', e1t_crs, e2t_crs )
+     CALL crs_dom_hgr( e1u, e2u, 'U', e1u_crs, e2u_crs )
+     CALL crs_dom_hgr( e1v, e2v, 'V', e1v_crs, e2v_crs )
+     CALL crs_dom_hgr( e1f, e2f, 'F', e1f_crs, e2f_crs )
+
+     e1e2t_crs(:,:) = e1t_crs(:,:) * e2t_crs(:,:)
+     
+     
+     !      3.c.2 Coriolis factor  
+
+!!gm  Not sure CRS needs Coriolis parameter....
+!!gm  If needed, then update this to have Coriolis at both f- and t-points
+
+      ff_crs(:,:) = 2. * omega * SIN( rad * gphif_crs(:,:) )
+
+      CALL ctl_warn( 'crsini: CAUTION, CRS only designed for Coriolis defined on the sphere' ) 
+ 
+
+     !    3.d.1 mbathy ( vertical k-levels of bathymetry )     
+
+     CALL crs_dom_bat
+     
+     !
+     ze3t(:,:,:) = e3t_n(:,:,:)
+     ze3u(:,:,:) = e3u_n(:,:,:)
+     ze3v(:,:,:) = e3v_n(:,:,:)
+     ze3w(:,:,:) = e3w_n(:,:,:)
+
+     !    3.d.2   Surfaces 
+     CALL crs_dom_sfc( tmask, 'W', e1e2w_crs, e1e2w_msk, p_e1=e1t, p_e2=e2t  )
+     CALL crs_dom_sfc( umask, 'U', e2e3u_crs, e2e3u_msk, p_e2=e2u, p_e3=ze3u )
+     CALL crs_dom_sfc( vmask, 'V', e1e3v_crs, e1e3v_msk, p_e1=e1v, p_e3=ze3v )
+   
+     facsurfu(:,:,:) = umask_crs(:,:,:) * e2e3u_msk(:,:,:) / e2e3u_crs(:,:,:)
+     facsurfv(:,:,:) = vmask_crs(:,:,:) * e1e3v_msk(:,:,:) / e1e3v_crs(:,:,:)
+
+     !    3.d.3   Vertical scale factors
+     !
+     CALL crs_dom_e3( e1t, e2t, ze3t, e1e2w_crs, 'T', tmask, e3t_crs, e3t_max_crs)
+     CALL crs_dom_e3( e1u, e2u, ze3u, e2e3u_crs, 'U', umask, e3u_crs, e3u_max_crs)
+     CALL crs_dom_e3( e1v, e2v, ze3v, e1e3v_crs, 'V', vmask, e3v_crs, e3v_max_crs)
+     CALL crs_dom_e3( e1t, e2t, ze3w, e1e2w_crs, 'W', tmask, e3w_crs, e3w_max_crs)
+
+     ! Replace 0 by e3t_0 or e3w_0
+     DO jk = 1, jpk
+        DO ji = 1, jpi_crs
+           DO jj = 1, jpj_crs
+              IF( e3t_crs(ji,jj,jk) == 0._wp ) e3t_crs(ji,jj,jk) = e3t_1d(jk)
+              IF( e3w_crs(ji,jj,jk) == 0._wp ) e3w_crs(ji,jj,jk) = e3w_1d(jk)
+              IF( e3u_crs(ji,jj,jk) == 0._wp ) e3u_crs(ji,jj,jk) = e3t_1d(jk)
+              IF( e3v_crs(ji,jj,jk) == 0._wp ) e3v_crs(ji,jj,jk) = e3t_1d(jk)
+           ENDDO
+        ENDDO
+     ENDDO
+
+     !    3.d.3   Vertical depth (meters)
+     CALL crs_dom_ope( gdept_0, 'MAX', 'T', tmask, gdept_crs, p_e3=ze3t, psgn=1.0 ) 
+     CALL crs_dom_ope( gdepw_0, 'MAX', 'W', tmask, gdepw_crs, p_e3=ze3w, psgn=1.0 )
+
+
+     !---------------------------------------------------------
+     ! 4.  Coarse grid ocean volume and averaging weights
+     !---------------------------------------------------------
+     ! 4.a. Ocean volume or area unmasked and masked
+     CALL crs_dom_facvol( tmask, 'T', e1t, e2t, ze3t, ocean_volume_crs_t, facvol_t )
+     !
+     bt_crs(:,:,:) = ocean_volume_crs_t(:,:,:) * facvol_t(:,:,:)
+     !
+     r1_bt_crs(:,:,:) = 0._wp 
+     WHERE( bt_crs /= 0._wp ) r1_bt_crs(:,:,:) = 1._wp / bt_crs(:,:,:)
+
+     CALL crs_dom_facvol( tmask, 'W', e1t, e2t, ze3w, ocean_volume_crs_w, facvol_w )
+     !
+     !---------------------------------------------------------
+     ! 5.  Write out coarse meshmask  (see OCE/DOM/domwri.F90 for ideas later)
+     !---------------------------------------------------------
+
+     IF( ln_msh_crs ) THEN 
+        CALL dom_grid_crs   ! Save the parent grid information  & Switch to coarse grid domain
+        CALL crs_dom_wri     
+        CALL dom_grid_glo   ! Return to parent grid domain
+     ENDIF
+     
+      !---------------------------------------------------------
+      ! 7. Finish and clean-up
+      !---------------------------------------------------------
+      !
+   END SUBROUTINE crs_init
+    
+   !!======================================================================
+END MODULE crsini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crslbclnk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crslbclnk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/CRS/crslbclnk.F90	(revision 14097)
@@ -0,0 +1,89 @@
+MODULE crslbclnk
+   !!======================================================================
+   !!                       ***  MODULE  crslbclnk  ***
+   !!               A temporary solution for lbclnk for coarsened grid.
+   !! Ocean        : lateral boundary conditions for grid coarsening
+   !!=====================================================================
+   !! History :   ! 2012-06  (J. Simeon, G. Madec, C. Ethe, C. Calone)     Original code
+   !!----------------------------------------------------------------------
+   USE par_kind, ONLY: wp
+   USE dom_oce
+   USE crs
+   !
+   USE lbclnk
+   USE in_out_manager
+   
+   INTERFACE crs_lbc_lnk
+      MODULE PROCEDURE crs_lbc_lnk_3d, crs_lbc_lnk_2d
+   END INTERFACE
+   
+   PUBLIC crs_lbc_lnk
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE crs_lbc_lnk_3d( pt3d1, cd_type1, psgn, kfillmode, pfillval  )
+      !!---------------------------------------------------------------------
+      !!                  ***  SUBROUTINE crs_lbc_lnk  ***
+      !!
+      !! ** Purpose :   set lateral boundary conditions for coarsened grid
+      !!
+      !! ** Method  :   Swap domain indices from full to coarse domain
+      !!                before arguments are passed directly to lbc_lnk.
+      !!                Upon exiting, switch back to full domain indices.
+      !!----------------------------------------------------------------------
+      CHARACTER(len=1)                        , INTENT(in   ) ::   cd_type1 ! grid type
+      REAL(wp)                                , INTENT(in   ) ::   psgn     ! control of the sign
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs,jpk), INTENT(inout) ::   pt3d1    ! 3D array on which the lbc is applied
+      INTEGER                     , OPTIONAL  , INTENT(in   ) ::   kfillmode   ! filling method for halo over land (default = cst)
+      REAL(wp)                    , OPTIONAL  , INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
+      !
+      LOGICAL  ::   ll_grid_crs
+      !!----------------------------------------------------------------------
+      !
+      ll_grid_crs = ( jpi == jpi_crs )
+      !
+      IF( .NOT.ll_grid_crs )   CALL dom_grid_crs   ! Save the parent grid information  & Switch to coarse grid domain
+      !
+      CALL lbc_lnk( 'crslbclnk', pt3d1, cd_type1, psgn, kfillmode, pfillval )
+      !
+      IF( .NOT.ll_grid_crs )   CALL dom_grid_glo   ! Return to parent grid domain
+      !
+   END SUBROUTINE crs_lbc_lnk_3d
+   
+   
+   SUBROUTINE crs_lbc_lnk_2d(pt2d, cd_type, psgn, kfillmode, pfillval )
+      !!---------------------------------------------------------------------
+      !!                  ***  SUBROUTINE crs_lbc_lnk  ***
+      !!
+      !! ** Purpose :   set lateral boundary conditions for coarsened grid
+      !!
+      !! ** Method  :   Swap domain indices from full to coarse domain
+      !!                before arguments are passed directly to lbc_lnk.
+      !!                Upon exiting, switch back to full domain indices.
+      !!----------------------------------------------------------------------
+      CHARACTER(len=1)                    , INTENT(in   ) ::   cd_type  ! grid type
+      REAL(wp)                            , INTENT(in   ) ::   psgn     ! control of the sign
+      REAL(wp), DIMENSION(jpi_crs,jpj_crs), INTENT(inout) ::   pt2d     ! 2D array on which the lbc is applied
+      INTEGER                 , OPTIONAL  , INTENT(in   ) ::   kfillmode   ! filling method for halo over land (default = constant)
+      REAL(wp)                , OPTIONAL  , INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
+      !      
+      LOGICAL  ::   ll_grid_crs
+      !!----------------------------------------------------------------------
+      !
+      ll_grid_crs = ( jpi == jpi_crs )
+      !
+      IF( .NOT.ll_grid_crs )   CALL dom_grid_crs   ! Save the parent grid information  & Switch to coarse grid domain
+      !
+      CALL lbc_lnk( 'crslbclnk', pt2d, cd_type, psgn, kfillmode, pfillval )
+      !
+      IF( .NOT.ll_grid_crs )   CALL dom_grid_glo   ! Return to parent grid domain
+      !
+   END SUBROUTINE crs_lbc_lnk_2d
+
+   !!======================================================================
+END MODULE crslbclnk
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dia25h.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dia25h.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dia25h.F90	(revision 14097)
@@ -0,0 +1,270 @@
+MODULE dia25h 
+   !!======================================================================
+   !!                       ***  MODULE  diaharm  ***
+   !! Harmonic analysis of tidal constituents 
+   !!======================================================================
+   !! History :  3.6  !  2014  (E O'Dea)  Original code
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain
+   USE zdf_oce         ! ocean vertical physics    
+   USE zdfgls   , ONLY : hmxl_n
+   !
+   USE in_out_manager  ! I/O units
+   USE iom             ! I/0 library
+   USE wet_dry
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_25h_init               ! routine called by nemogcm.F90
+   PUBLIC   dia_25h                    ! routine called by diawri.F90
+
+   LOGICAL, PUBLIC ::   ln_dia25h      !:  25h mean output
+
+   ! variables for calculating 25-hourly means
+   INTEGER , SAVE ::   cnt_25h           ! Counter for 25 hour means
+   REAL(wp), SAVE ::   r1_25 = 0.04_wp   ! =1/25 
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   tn_25h  , sn_25h
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   sshn_25h 
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   un_25h  , vn_25h  , wn_25h
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avt_25h , avm_25h
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   en_25h  , rmxln_25h
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_25h_init 
+      !!---------------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_25h_init  ***
+      !!     
+      !! ** Purpose: Initialization of 25h mean namelist 
+      !!        
+      !! ** Method : Read namelist
+      !!---------------------------------------------------------------------------
+      INTEGER ::   ios                 ! Local integer output status for namelist read
+      INTEGER ::   ierror              ! Local integer for memory allocation
+      !
+      NAMELIST/nam_dia25h/ ln_dia25h
+      !!----------------------------------------------------------------------
+      !
+      REWIND ( numnam_ref )              ! Read Namelist nam_dia25h in reference namelist : 25hour mean diagnostics
+      READ   ( numnam_ref, nam_dia25h, IOSTAT=ios, ERR= 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_dia25h in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_dia25h in configuration namelist  25hour diagnostics
+      READ  ( numnam_cfg, nam_dia25h, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nam_dia25h in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_dia25h )
+
+      IF(lwp) THEN                   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_25h_init : Output 25 hour mean diagnostics'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist nam_dia25h : set 25h outputs '
+         WRITE(numout,*) '      Switch for 25h diagnostics (T) or not (F)  ln_dia25h  = ', ln_dia25h
+      ENDIF
+      IF( .NOT. ln_dia25h )   RETURN
+      ! ------------------- !
+      ! 1 - Allocate memory !
+      ! ------------------- !
+      !                                ! ocean arrays
+      ALLOCATE( tn_25h (jpi,jpj,jpk), sn_25h (jpi,jpj,jpk), sshn_25h(jpi,jpj)  ,     &
+         &      un_25h (jpi,jpj,jpk), vn_25h (jpi,jpj,jpk), wn_25h(jpi,jpj,jpk),     &
+         &      avt_25h(jpi,jpj,jpk), avm_25h(jpi,jpj,jpk),                      STAT=ierror )
+      IF( ierror > 0 ) THEN
+         CALL ctl_stop( 'dia_25h: unable to allocate ocean arrays' )   ;   RETURN
+      ENDIF
+      IF( ln_zdftke ) THEN             ! TKE physics
+         ALLOCATE( en_25h(jpi,jpj,jpk), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'dia_25h: unable to allocate en_25h' )   ;   RETURN
+         ENDIF
+      ENDIF
+      IF( ln_zdfgls ) THEN             ! GLS physics
+         ALLOCATE( en_25h(jpi,jpj,jpk), rmxln_25h(jpi,jpj,jpk), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'dia_25h: unable to allocate en_25h and rmxln_25h' )   ;   RETURN
+         ENDIF
+      ENDIF
+      ! ------------------------- !
+      ! 2 - Assign Initial Values !
+      ! ------------------------- !
+      cnt_25h = 1  ! sets the first value of sum at timestep 1 (note - should strictly be at timestep zero so before values used where possible) 
+      tn_25h  (:,:,:) = tsb (:,:,:,jp_tem)
+      sn_25h  (:,:,:) = tsb (:,:,:,jp_sal)
+      sshn_25h(:,:)   = sshb(:,:)
+      un_25h  (:,:,:) = ub  (:,:,:)
+      vn_25h  (:,:,:) = vb  (:,:,:)
+      avt_25h (:,:,:) = avt (:,:,:)
+      avm_25h (:,:,:) = avm (:,:,:)
+      IF( ln_zdftke ) THEN
+         en_25h(:,:,:) = en(:,:,:)
+      ENDIF
+      IF( ln_zdfgls ) THEN
+         en_25h   (:,:,:) = en    (:,:,:)
+         rmxln_25h(:,:,:) = hmxl_n(:,:,:)
+      ENDIF
+#if defined key_si3
+      CALL ctl_stop('STOP', 'dia_25h not setup yet to do tidemean ice')
+#endif 
+      !
+   END SUBROUTINE dia_25h_init
+
+
+   SUBROUTINE dia_25h( kt )  
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_25h  ***
+      !!         
+      !! ** Purpose :   Write diagnostics with M2/S2 tide removed
+      !!
+      !! ** Method  :   25hr mean outputs for shelf seas
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !!
+      INTEGER ::   ji, jj, jk
+      INTEGER                          ::   iyear0, nimonth0,iday0            ! start year,imonth,day
+      LOGICAL ::   ll_print = .FALSE.    ! =T print and flush numout
+      REAL(wp)                         ::   zsto, zout, zmax, zjulian, zmdi   ! local scalars
+      INTEGER                          ::   i_steps                           ! no of timesteps per hour
+      REAL(wp), DIMENSION(jpi,jpj    ) ::   zw2d, un_dm, vn_dm                ! workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zw3d                              ! workspace
+      REAL(wp), DIMENSION(jpi,jpj,3)   ::   zwtmb                             ! workspace
+      !!----------------------------------------------------------------------
+
+      ! 0. Initialisation
+      ! -----------------
+      ! Define frequency of summing to create 25 h mean
+      IF( MOD( 3600,NINT(rdt) ) == 0 ) THEN
+         i_steps = 3600/NINT(rdt)
+      ELSE
+         CALL ctl_stop('STOP', 'dia_wri_tide: timestep must give MOD(3600,rdt) = 0 otherwise no hourly values are possible')
+      ENDIF
+
+      ! local variable for debugging
+      ll_print = ll_print .AND. lwp
+
+      ! wn_25h could not be initialised in dia_25h_init, so we do it here instead
+      IF( kt == nn_it000 ) THEN
+         wn_25h(:,:,:) = wn(:,:,:)
+      ENDIF
+
+      ! Sum of 25 hourly instantaneous values to give a 25h mean from 24hours every day
+      IF( MOD( kt, i_steps ) == 0  .AND. kt /= nn_it000 ) THEN
+
+         IF (lwp) THEN
+              WRITE(numout,*) 'dia_wri_tide : Summing instantaneous hourly diagnostics at timestep ',kt
+              WRITE(numout,*) '~~~~~~~~~~~~ '
+         ENDIF
+
+         tn_25h  (:,:,:)     = tn_25h  (:,:,:) + tsn (:,:,:,jp_tem)
+         sn_25h  (:,:,:)     = sn_25h  (:,:,:) + tsn (:,:,:,jp_sal)
+         sshn_25h(:,:)       = sshn_25h(:,:)   + sshn(:,:)
+         un_25h  (:,:,:)     = un_25h  (:,:,:) + un  (:,:,:)
+         vn_25h  (:,:,:)     = vn_25h  (:,:,:) + vn  (:,:,:)
+         wn_25h  (:,:,:)     = wn_25h  (:,:,:) + wn  (:,:,:)
+         avt_25h (:,:,:)     = avt_25h (:,:,:) + avt (:,:,:)
+         avm_25h (:,:,:)     = avm_25h (:,:,:) + avm (:,:,:)
+         IF( ln_zdftke ) THEN
+            en_25h(:,:,:)    = en_25h  (:,:,:) + en(:,:,:)
+         ENDIF
+         IF( ln_zdfgls ) THEN
+            en_25h   (:,:,:) = en_25h   (:,:,:) + en    (:,:,:)
+            rmxln_25h(:,:,:) = rmxln_25h(:,:,:) + hmxl_n(:,:,:)
+         ENDIF
+         cnt_25h = cnt_25h + 1
+         !
+         IF (lwp) THEN
+            WRITE(numout,*) 'dia_tide : Summed the following number of hourly values so far',cnt_25h
+         ENDIF
+         !
+      ENDIF ! MOD( kt, i_steps ) == 0
+
+      ! Write data for 25 hour mean output streams
+      IF( cnt_25h == 25 .AND.  MOD( kt, i_steps*24) == 0 .AND. kt /= nn_it000 ) THEN
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) 'dia_wri_tide : Writing 25 hour mean tide diagnostics at timestep', kt
+            WRITE(numout,*) '~~~~~~~~~~~~ '
+         ENDIF
+         !
+         tn_25h  (:,:,:) = tn_25h  (:,:,:) * r1_25
+         sn_25h  (:,:,:) = sn_25h  (:,:,:) * r1_25
+         sshn_25h(:,:)   = sshn_25h(:,:)   * r1_25
+         un_25h  (:,:,:) = un_25h  (:,:,:) * r1_25
+         vn_25h  (:,:,:) = vn_25h  (:,:,:) * r1_25
+         wn_25h  (:,:,:) = wn_25h  (:,:,:) * r1_25
+         avt_25h (:,:,:) = avt_25h (:,:,:) * r1_25
+         avm_25h (:,:,:) = avm_25h (:,:,:) * r1_25
+         IF( ln_zdftke ) THEN
+            en_25h(:,:,:) = en_25h(:,:,:) * r1_25
+         ENDIF
+         IF( ln_zdfgls ) THEN
+            en_25h   (:,:,:) = en_25h   (:,:,:) * r1_25
+            rmxln_25h(:,:,:) = rmxln_25h(:,:,:) * r1_25
+         ENDIF
+         !
+         IF(lwp)  WRITE(numout,*) 'dia_wri_tide : Mean calculated by dividing 25 hour sums and writing output'
+         zmdi=1.e+20 !missing data indicator for masking
+         ! write tracers (instantaneous)
+         zw3d(:,:,:) = tn_25h(:,:,:)*tmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+         CALL iom_put("temper25h", zw3d)   ! potential temperature
+         zw3d(:,:,:) = sn_25h(:,:,:)*tmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+         CALL iom_put( "salin25h", zw3d  )   ! salinity
+         zw2d(:,:) = sshn_25h(:,:)*tmask(:,:,1) + zmdi*(1.0-tmask(:,:,1))
+         IF( ll_wd ) THEN
+            CALL iom_put( "ssh25h", zw2d+ssh_ref )   ! sea surface 
+         ELSE
+            CALL iom_put( "ssh25h", zw2d )   ! sea surface
+         ENDIF
+         ! Write velocities (instantaneous)
+         zw3d(:,:,:) = un_25h(:,:,:)*umask(:,:,:) + zmdi*(1.0-umask(:,:,:))
+         CALL iom_put("vozocrtx25h", zw3d)    ! i-current
+         zw3d(:,:,:) = vn_25h(:,:,:)*vmask(:,:,:) + zmdi*(1.0-vmask(:,:,:))
+         CALL iom_put("vomecrty25h", zw3d  )   ! j-current
+         zw3d(:,:,:) = wn_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+         CALL iom_put("vovecrtz25h", zw3d )   ! k-current
+         ! Write vertical physics
+         zw3d(:,:,:) = avt_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+         CALL iom_put("avt25h", zw3d )   ! diffusivity
+         zw3d(:,:,:) = avm_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+         CALL iom_put("avm25h", zw3d)   ! viscosity
+         IF( ln_zdftke ) THEN
+            zw3d(:,:,:) = en_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+            CALL iom_put("tke25h", zw3d)   ! tke
+         ENDIF
+         IF( ln_zdfgls ) THEN
+            zw3d(:,:,:) = en_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+            CALL iom_put("tke25h", zw3d)   ! tke
+            zw3d(:,:,:) = rmxln_25h(:,:,:)*wmask(:,:,:) + zmdi*(1.0-tmask(:,:,:))
+            CALL iom_put( "mxln25h",zw3d)
+         ENDIF
+         !
+         ! After the write reset the values to cnt=1 and sum values equal current value 
+         tn_25h  (:,:,:) = tsn (:,:,:,jp_tem)
+         sn_25h  (:,:,:) = tsn (:,:,:,jp_sal)
+         sshn_25h(:,:)   = sshn(:,:)
+         un_25h  (:,:,:) = un  (:,:,:)
+         vn_25h  (:,:,:) = vn  (:,:,:)
+         wn_25h  (:,:,:) = wn  (:,:,:)
+         avt_25h (:,:,:) = avt (:,:,:)
+         avm_25h (:,:,:) = avm (:,:,:)
+         IF( ln_zdftke ) THEN
+            en_25h(:,:,:) = en(:,:,:)
+         ENDIF
+         IF( ln_zdfgls ) THEN
+            en_25h   (:,:,:) = en    (:,:,:)
+            rmxln_25h(:,:,:) = hmxl_n(:,:,:)
+         ENDIF
+         cnt_25h = 1
+         IF(lwp)  WRITE(numout,*) 'dia_wri_tide :   &
+            &    After 25hr mean write, reset sum to current value and cnt_25h to one for overlapping average', cnt_25h
+      ENDIF !  cnt_25h .EQ. 25 .AND.  MOD( kt, i_steps * 24) == 0 .AND. kt .NE. nn_it000
+      !
+   END SUBROUTINE dia_25h 
+
+   !!======================================================================
+END MODULE dia25h
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaar5.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaar5.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaar5.F90	(revision 14097)
@@ -0,0 +1,444 @@
+MODULE diaar5
+   !!======================================================================
+   !!                       ***  MODULE  diaar5  ***
+   !! AR5 diagnostics
+   !!======================================================================
+   !! History :  3.2  !  2009-11  (S. Masson)  Original code
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase + merge TRC-TRA
+   !!----------------------------------------------------------------------
+   !!   dia_ar5       : AR5 diagnostics
+   !!   dia_ar5_init  : initialisation of AR5 diagnostics
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE eosbn2         ! equation of state                (eos_bn2 routine)
+   USE phycst         ! physical constant
+   USE in_out_manager  ! I/O manager
+   USE zdfddm
+   USE zdf_oce
+   !
+   USE lib_mpp        ! distribued memory computing library
+   USE iom            ! I/O manager library
+   USE fldread        ! type FLD_N
+   USE timing         ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_ar5        ! routine called in step.F90 module
+   PUBLIC   dia_ar5_alloc  ! routine called in nemogcm.F90 module
+   PUBLIC   dia_ar5_hst    ! heat/salt transport
+
+   REAL(wp)                         ::   vol0         ! ocean volume (interior domain)
+   REAL(wp)                         ::   area_tot     ! total ocean surface (interior domain)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:  ) ::   thick0       ! ocean thickness (interior domain)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sn0          ! initial salinity
+
+   LOGICAL  :: l_ar5
+      
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION dia_ar5_alloc()
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ar5_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: dia_ar5_alloc
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( thick0(jpi,jpj) , sn0(jpi,jpj,jpk) , STAT=dia_ar5_alloc )
+      !
+      CALL mpp_sum ( 'diaar5', dia_ar5_alloc )
+      IF( dia_ar5_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dia_ar5_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION dia_ar5_alloc
+
+
+   SUBROUTINE dia_ar5( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ar5  ***
+      !!
+      !! ** Purpose :   compute and output some AR5 diagnostics
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk, iks, ikb                      ! dummy loop arguments
+      REAL(wp) ::   zvolssh, zvol, zssh_steric, zztmp, zarho, ztemp, zsal, zmass, zsst
+      REAL(wp) ::   zaw, zbw, zrw
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     :: zarea_ssh , zbotpres       ! 2D workspace 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     :: zpe, z2d                   ! 2D workspace 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   :: zrhd , ztpot               ! 3D workspace
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) :: ztsn                       ! 4D workspace
+
+      !!--------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('dia_ar5')
+ 
+      IF( kt == nit000 )     CALL dia_ar5_init
+
+      IF( l_ar5 ) THEN 
+         ALLOCATE( zarea_ssh(jpi,jpj), zbotpres(jpi,jpj), z2d(jpi,jpj) )
+         ALLOCATE( zrhd(jpi,jpj,jpk) )
+         ALLOCATE( ztsn(jpi,jpj,jpk,jpts) )
+         zarea_ssh(:,:) = e1e2t(:,:) * sshn(:,:)
+      ENDIF
+      !
+      CALL iom_put( 'e2u'      , e2u  (:,:) )
+      CALL iom_put( 'e1v'      , e1v  (:,:) )
+      CALL iom_put( 'areacello', e1e2t(:,:) )
+      !
+      IF( iom_use( 'volcello' ) .OR. iom_use( 'masscello' )  ) THEN  
+         zrhd(:,:,jpk) = 0._wp        ! ocean volume ; rhd is used as workspace
+         DO jk = 1, jpkm1
+            zrhd(:,:,jk) = e1e2t(:,:) * e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         CALL iom_put( 'volcello'  , zrhd(:,:,:)  )  ! WARNING not consistent with CMIP DR where volcello is at ca. 2000
+         CALL iom_put( 'masscello' , rau0 * e3t_n(:,:,:) * tmask(:,:,:) )  ! ocean mass
+      ENDIF 
+      !
+      IF( iom_use( 'e3tb' ) )  THEN    ! bottom layer thickness
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikb = mbkt(ji,jj)
+               z2d(ji,jj) = e3t_n(ji,jj,ikb)
+            END DO
+         END DO
+         CALL iom_put( 'e3tb', z2d )
+      ENDIF 
+      !
+      IF( iom_use( 'voltot' ) .OR. iom_use( 'sshtot' )  .OR. iom_use( 'sshdyn' )  ) THEN    
+         !                                         ! total volume of liquid seawater
+         zvolssh = glob_sum( 'diaar5', zarea_ssh(:,:) ) 
+         zvol    = vol0 + zvolssh
+      
+         CALL iom_put( 'voltot', zvol               )
+         CALL iom_put( 'sshtot', zvolssh / area_tot )
+         CALL iom_put( 'sshdyn', sshn(:,:) - (zvolssh / area_tot) )
+         !
+      ENDIF
+
+      IF( iom_use( 'botpres' ) .OR. iom_use( 'sshthster' )  .OR. iom_use( 'sshsteric' )  ) THEN    
+         !                     
+         ztsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem)                    ! thermosteric ssh
+         ztsn(:,:,:,jp_sal) = sn0(:,:,:)
+         CALL eos( ztsn, zrhd, gdept_n(:,:,:) )                       ! now in situ density using initial salinity
+         !
+         zbotpres(:,:) = 0._wp                        ! no atmospheric surface pressure, levitating sea-ice
+         DO jk = 1, jpkm1
+            zbotpres(:,:) = zbotpres(:,:) + e3t_n(:,:,jk) * zrhd(:,:,jk)
+         END DO
+         IF( ln_linssh ) THEN
+            IF( ln_isfcav ) THEN
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     iks = mikt(ji,jj)
+                     zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * zrhd(ji,jj,iks) + riceload(ji,jj)
+                  END DO
+               END DO
+            ELSE
+               zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * zrhd(:,:,1)
+            END IF
+!!gm
+!!gm   riceload should be added in both ln_linssh=T or F, no?
+!!gm
+         END IF
+         !                                         
+         zarho = glob_sum( 'diaar5', e1e2t(:,:) * zbotpres(:,:) ) 
+         zssh_steric = - zarho / area_tot
+         CALL iom_put( 'sshthster', zssh_steric )
+      
+         !                                         ! steric sea surface height
+         zbotpres(:,:) = 0._wp                        ! no atmospheric surface pressure, levitating sea-ice
+         DO jk = 1, jpkm1
+            zbotpres(:,:) = zbotpres(:,:) + e3t_n(:,:,jk) * rhd(:,:,jk)
+         END DO
+         IF( ln_linssh ) THEN
+            IF ( ln_isfcav ) THEN
+               DO ji = 1,jpi
+                  DO jj = 1,jpj
+                     iks = mikt(ji,jj)
+                     zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * rhd(ji,jj,iks) + riceload(ji,jj)
+                  END DO
+               END DO
+            ELSE
+               zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * rhd(:,:,1)
+            END IF
+         END IF
+         !    
+         zarho = glob_sum( 'diaar5', e1e2t(:,:) * zbotpres(:,:) ) 
+         zssh_steric = - zarho / area_tot
+         CALL iom_put( 'sshsteric', zssh_steric )
+         !                                         ! ocean bottom pressure
+         zztmp = rau0 * grav * 1.e-4_wp               ! recover pressure from pressure anomaly and cover to dbar = 1.e4 Pa
+         zbotpres(:,:) = zztmp * ( zbotpres(:,:) + sshn(:,:) + thick0(:,:) )
+         CALL iom_put( 'botpres', zbotpres )
+         !
+      ENDIF
+
+      IF( iom_use( 'masstot' ) .OR. iom_use( 'temptot' )  .OR. iom_use( 'saltot' )  ) THEN    
+          !                                         ! Mean density anomalie, temperature and salinity
+          ztsn(:,:,:,:) = 0._wp                    ! ztsn(:,:,1,jp_tem/sal) is used here as 2D Workspace for temperature & salinity
+          DO jk = 1, jpkm1
+             DO jj = 1, jpj
+                DO ji = 1, jpi
+                   zztmp = e1e2t(ji,jj) * e3t_n(ji,jj,jk)
+                   ztsn(ji,jj,1,jp_tem) = ztsn(ji,jj,1,jp_tem) + zztmp * tsn(ji,jj,jk,jp_tem)
+                   ztsn(ji,jj,1,jp_sal) = ztsn(ji,jj,1,jp_sal) + zztmp * tsn(ji,jj,jk,jp_sal)
+                ENDDO
+             ENDDO
+          ENDDO
+
+          IF( ln_linssh ) THEN
+            IF( ln_isfcav ) THEN
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     iks = mikt(ji,jj)
+                     ztsn(ji,jj,1,jp_tem) = ztsn(ji,jj,1,jp_tem) + zarea_ssh(ji,jj) * tsn(ji,jj,iks,jp_tem) 
+                     ztsn(ji,jj,1,jp_sal) = ztsn(ji,jj,1,jp_sal) + zarea_ssh(ji,jj) * tsn(ji,jj,iks,jp_sal) 
+                  END DO
+               END DO
+            ELSE
+               ztsn(:,:,1,jp_tem) = ztsn(:,:,1,jp_tem) + zarea_ssh(:,:) * tsn(:,:,1,jp_tem) 
+               ztsn(:,:,1,jp_sal) = ztsn(:,:,1,jp_sal) + zarea_ssh(:,:) * tsn(:,:,1,jp_sal) 
+            END IF
+         ENDIF
+         !
+         ztemp = glob_sum( 'diaar5', ztsn(:,:,1,jp_tem) )
+         zsal  = glob_sum( 'diaar5', ztsn(:,:,1,jp_sal) )
+         zmass = rau0 * ( zarho + zvol )      
+         !
+         CALL iom_put( 'masstot', zmass )
+         CALL iom_put( 'temptot', ztemp / zvol )
+         CALL iom_put( 'saltot' , zsal  / zvol )
+         !
+      ENDIF     
+
+      IF( ln_teos10 ) THEN        ! ! potential temperature (TEOS-10 case)
+         IF( iom_use( 'toce_pot') .OR. iom_use( 'temptot_pot' ) .OR. iom_use( 'sst_pot' )  &
+                                  .OR. iom_use( 'ssttot' ) .OR.  iom_use( 'tosmint_pot' ) ) THEN
+            !
+            ALLOCATE( ztpot(jpi,jpj,jpk) )
+            ztpot(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1
+               ztpot(:,:,jk) = eos_pt_from_ct( tsn(:,:,jk,jp_tem), tsn(:,:,jk,jp_sal) )
+            END DO
+            !
+            CALL iom_put( 'toce_pot', ztpot(:,:,:) )  ! potential temperature (TEOS-10 case)
+            CALL iom_put( 'sst_pot' , ztpot(:,:,1) )  ! surface temperature
+            !
+            IF( iom_use( 'temptot_pot' ) ) THEN   ! Output potential temperature in case we use TEOS-10
+               z2d(:,:) = 0._wp
+               DO jk = 1, jpkm1
+                 z2d(:,:) = z2d(:,:) + e1e2t(:,:) * e3t_n(:,:,jk) * ztpot(:,:,jk)
+               END DO
+               ztemp = glob_sum( 'diaar5', z2d(:,:)  ) 
+               CALL iom_put( 'temptot_pot', ztemp / zvol )
+             ENDIF
+             !
+             IF( iom_use( 'ssttot' ) ) THEN   ! Output potential temperature in case we use TEOS-10
+               zsst = glob_sum( 'diaar5',  e1e2t(:,:) * ztpot(:,:,1)  ) 
+               CALL iom_put( 'ssttot', zsst / area_tot )
+             ENDIF
+             ! Vertical integral of temperature
+             IF( iom_use( 'tosmint_pot') ) THEN
+               z2d(:,:) = 0._wp
+               DO jk = 1, jpkm1
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi   ! vector opt.
+                        z2d(ji,jj) = z2d(ji,jj) + rau0 * e3t_n(ji,jj,jk) *  ztpot(ji,jj,jk)
+                     END DO
+                  END DO
+               END DO
+               CALL iom_put( 'tosmint_pot', z2d ) 
+            ENDIF
+            DEALLOCATE( ztpot )
+        ENDIF
+      ELSE       
+         IF( iom_use('ssttot') ) THEN   ! Output sst in case we use EOS-80
+            zsst  = glob_sum( 'diaar5', e1e2t(:,:) * tsn(:,:,1,jp_tem) )
+            CALL iom_put('ssttot', zsst / area_tot )
+         ENDIF
+      ENDIF
+
+      IF( iom_use( 'tnpeo' )) THEN    
+        ! Work done against stratification by vertical mixing
+        ! Exclude points where rn2 is negative as convection kicks in here and
+        ! work is not being done against stratification
+         ALLOCATE( zpe(jpi,jpj) )
+         zpe(:,:) = 0._wp
+         IF( ln_zdfddm ) THEN
+            DO jk = 2, jpk
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( rn2(ji,jj,jk) > 0._wp ) THEN
+                        zrw = ( gdept_n(ji,jj,jk) - gdepw_n(ji,jj,jk) ) / e3w_n(ji,jj,jk)
+                        !
+                        zaw = rab_n(ji,jj,jk,jp_tem) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_tem)* zrw
+                        zbw = rab_n(ji,jj,jk,jp_sal) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_sal)* zrw
+                        !
+                        zpe(ji, jj) = zpe(ji,jj)   &
+                           &        -  grav * (  avt(ji,jj,jk) * zaw * (tsn(ji,jj,jk-1,jp_tem) - tsn(ji,jj,jk,jp_tem) )  &
+                           &                   - avs(ji,jj,jk) * zbw * (tsn(ji,jj,jk-1,jp_sal) - tsn(ji,jj,jk,jp_sal) ) )
+                     ENDIF
+                  END DO
+               END DO
+             END DO
+          ELSE
+            DO jk = 1, jpk
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     zpe(ji,jj) = zpe(ji,jj) + avt(ji,jj,jk) * MIN(0._wp,rn2(ji,jj,jk)) * rau0 * e3w_n(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+         ENDIF
+          CALL iom_put( 'tnpeo', zpe )
+          DEALLOCATE( zpe )
+      ENDIF
+
+      IF( l_ar5 ) THEN
+        DEALLOCATE( zarea_ssh , zbotpres, z2d )
+        DEALLOCATE( zrhd      )
+        DEALLOCATE( ztsn      )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_ar5')
+      !
+   END SUBROUTINE dia_ar5
+
+
+   SUBROUTINE dia_ar5_hst( ktra, cptr, pua, pva ) 
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ar5_htr ***
+      !!----------------------------------------------------------------------
+      !! Wrapper for heat transport calculations
+      !! Called from all advection and/or diffusion routines
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in )  :: ktra  ! tracer index
+      CHARACTER(len=3)                , INTENT(in)   :: cptr  ! transport type  'adv'/'ldf'
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pua   ! 3D input array of advection/diffusion
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pva   ! 3D input array of advection/diffusion
+      !
+      INTEGER    ::  ji, jj, jk
+      REAL(wp), DIMENSION(jpi,jpj)  :: z2d
+
+    
+      z2d(:,:) = pua(:,:,1) 
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               z2d(ji,jj) = z2d(ji,jj) + pua(ji,jj,jk) 
+            END DO
+         END DO
+       END DO
+       CALL lbc_lnk( 'diaar5', z2d, 'U', -1. )
+       IF( cptr == 'adv' ) THEN
+          IF( ktra == jp_tem ) CALL iom_put( 'uadv_heattr' , rau0_rcp * z2d )  ! advective heat transport in i-direction
+          IF( ktra == jp_sal ) CALL iom_put( 'uadv_salttr' , rau0     * z2d )  ! advective salt transport in i-direction
+       ENDIF
+       IF( cptr == 'ldf' ) THEN
+          IF( ktra == jp_tem ) CALL iom_put( 'udiff_heattr' , rau0_rcp * z2d ) ! diffusive heat transport in i-direction
+          IF( ktra == jp_sal ) CALL iom_put( 'udiff_salttr' , rau0     * z2d ) ! diffusive salt transport in i-direction
+       ENDIF
+       !
+       z2d(:,:) = pva(:,:,1) 
+       DO jk = 1, jpkm1
+          DO jj = 2, jpjm1
+             DO ji = fs_2, fs_jpim1   ! vector opt.
+                z2d(ji,jj) = z2d(ji,jj) + pva(ji,jj,jk) 
+             END DO
+          END DO
+       END DO
+       CALL lbc_lnk( 'diaar5', z2d, 'V', -1. )
+       IF( cptr == 'adv' ) THEN
+          IF( ktra == jp_tem ) CALL iom_put( 'vadv_heattr' , rau0_rcp * z2d )  ! advective heat transport in j-direction
+          IF( ktra == jp_sal ) CALL iom_put( 'vadv_salttr' , rau0     * z2d )  ! advective salt transport in j-direction
+       ENDIF
+       IF( cptr == 'ldf' ) THEN
+          IF( ktra == jp_tem ) CALL iom_put( 'vdiff_heattr' , rau0_rcp * z2d ) ! diffusive heat transport in j-direction
+          IF( ktra == jp_sal ) CALL iom_put( 'vdiff_salttr' , rau0     * z2d ) ! diffusive salt transport in j-direction
+       ENDIF
+          
+   END SUBROUTINE dia_ar5_hst
+
+
+   SUBROUTINE dia_ar5_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_ar5_init  ***
+      !!                   
+      !! ** Purpose :   initialization for AR5 diagnostic computation
+      !!----------------------------------------------------------------------
+      INTEGER  ::   inum
+      INTEGER  ::   ik, idep
+      INTEGER  ::   ji, jj, jk  ! dummy loop indices
+      REAL(wp) ::   zztmp  
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   zsaldta   ! Jan/Dec levitus salinity
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     ::   zvol0     
+      !
+      !!----------------------------------------------------------------------
+      !
+      l_ar5 = .FALSE.
+      IF(   iom_use( 'voltot'  ) .OR. iom_use( 'sshtot'    )  .OR. iom_use( 'sshdyn' )  .OR.  & 
+         &  iom_use( 'masstot' ) .OR. iom_use( 'temptot'   )  .OR. iom_use( 'saltot' ) .OR.  &    
+         &  iom_use( 'botpres' ) .OR. iom_use( 'sshthster' )  .OR. iom_use( 'sshsteric' ) .OR. &
+         &  iom_use( 'rhop' )  ) L_ar5 = .TRUE.
+  
+      IF( l_ar5 ) THEN
+         !
+         !                                      ! allocate dia_ar5 arrays
+         IF( dia_ar5_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dia_ar5_init : unable to allocate arrays' )
+
+         area_tot  = glob_sum( 'diaar5', e1e2t(:,:) )
+
+         ALLOCATE( zvol0(jpi,jpj) )
+         zvol0 (:,:) = 0._wp
+         thick0(:,:) = 0._wp
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj               ! interpolation of salinity at the last ocean level (i.e. the partial step)
+               DO ji = 1, jpi
+                  idep = tmask(ji,jj,jk) * e3t_0(ji,jj,jk)
+                  zvol0 (ji,jj) = zvol0 (ji,jj) +  idep * e1e2t(ji,jj)
+                  thick0(ji,jj) = thick0(ji,jj) +  idep    
+               END DO
+            END DO
+         END DO
+         vol0 = glob_sum( 'diaar5', zvol0 )
+         DEALLOCATE( zvol0 )
+
+         IF( iom_use( 'sshthster' ) ) THEN
+            ALLOCATE( zsaldta(jpi,jpj,jpk,jpts) )
+            CALL iom_open ( 'sali_ref_clim_monthly', inum )
+            CALL iom_get  ( inum, jpdom_data, 'vosaline' , zsaldta(:,:,:,1), 1  )
+            CALL iom_get  ( inum, jpdom_data, 'vosaline' , zsaldta(:,:,:,2), 12 )
+            CALL iom_close( inum )
+
+            sn0(:,:,:) = 0.5_wp * ( zsaldta(:,:,:,1) + zsaldta(:,:,:,2) )        
+            sn0(:,:,:) = sn0(:,:,:) * tmask(:,:,:)
+            IF( ln_zps ) THEN               ! z-coord. partial steps
+               DO jj = 1, jpj               ! interpolation of salinity at the last ocean level (i.e. the partial step)
+                  DO ji = 1, jpi
+                     ik = mbkt(ji,jj)
+                     IF( ik > 1 ) THEN
+                        zztmp = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+                        sn0(ji,jj,ik) = ( 1._wp - zztmp ) * sn0(ji,jj,ik) + zztmp * sn0(ji,jj,ik-1)
+                     ENDIF
+                  END DO
+               END DO
+            ENDIF
+            !
+            DEALLOCATE( zsaldta )
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE dia_ar5_init
+
+   !!======================================================================
+END MODULE diaar5
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diacfl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diacfl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diacfl.F90	(revision 14097)
@@ -0,0 +1,172 @@
+MODULE diacfl
+   !!======================================================================
+   !!                       ***  MODULE  diacfl  ***
+   !! Output CFL diagnostics to ascii file
+   !!======================================================================
+   !! History :  3.4  !  2010-03  (E. Blockley)  Original code
+   !!            3.6  !  2014-06  (T. Graham)  Removed CPP key & Updated to vn3.6
+   !!            4.0  !  2017-09  (G. Madec)  style + comments
+   !!----------------------------------------------------------------------
+   !!   dia_cfl        : Compute and output Courant numbers at each timestep
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and active tracers
+   USE dom_oce         ! ocean space and time domain
+   USE domvvl          ! 
+   !
+   USE lib_mpp         ! distribued memory computing
+   USE lbclnk          ! ocean lateral boundary condition (or mpp link)
+   USE in_out_manager  ! I/O manager
+   USE iom             ! 
+   USE timing          ! Performance output
+
+   IMPLICIT NONE
+   PRIVATE
+
+   CHARACTER(LEN=50) :: clname="cfl_diagnostics.ascii"    ! ascii filename
+   INTEGER           :: numcfl                            ! outfile unit
+   !
+   INTEGER, DIMENSION(3) ::   nCu_loc, nCv_loc, nCw_loc   ! U, V, and W run max locations in the global domain
+   REAL(wp)              ::   rCu_max, rCv_max, rCw_max   ! associated run max Courant number 
+
+   PUBLIC   dia_cfl       ! routine called by step.F90
+   PUBLIC   dia_cfl_init  ! routine called by nemogcm
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_cfl ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_cfl  ***
+      !!
+      !! ** Purpose :  Compute the Courant numbers Cu=u*dt/dx and Cv=v*dt/dy
+      !!               and output to ascii file 'cfl_diagnostics.ascii'
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER                          ::   ji, jj, jk                       ! dummy loop indices
+      REAL(wp)                         ::   z2dt, zCu_max, zCv_max, zCw_max  ! local scalars
+      INTEGER , DIMENSION(3)           ::   iloc_u , iloc_v , iloc_w , iloc  ! workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zCu_cfl, zCv_cfl, zCw_cfl        ! workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dia_cfl')
+      !
+      !                       ! setup timestep multiplier to account for initial Eulerian timestep
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;    z2dt = rdt
+      ELSE                                        ;    z2dt = rdt * 2._wp
+      ENDIF
+      !
+      !                
+      DO jk = 1, jpk       ! calculate Courant numbers
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zCu_cfl(ji,jj,jk) = ABS( un(ji,jj,jk) ) * z2dt / e1u  (ji,jj)      ! for i-direction
+               zCv_cfl(ji,jj,jk) = ABS( vn(ji,jj,jk) ) * z2dt / e2v  (ji,jj)      ! for j-direction
+               zCw_cfl(ji,jj,jk) = ABS( wn(ji,jj,jk) ) * z2dt / e3w_n(ji,jj,jk)   ! for k-direction
+            END DO
+         END DO         
+      END DO
+      !
+      ! write outputs
+      IF( iom_use('cfl_cu') )   CALL iom_put( 'cfl_cu', MAXVAL( zCu_cfl, dim=3 ) )
+      IF( iom_use('cfl_cv') )   CALL iom_put( 'cfl_cv', MAXVAL( zCv_cfl, dim=3 ) )
+      IF( iom_use('cfl_cw') )   CALL iom_put( 'cfl_cw', MAXVAL( zCw_cfl, dim=3 ) )
+
+      !                    ! calculate maximum values and locations
+      IF( lk_mpp ) THEN
+         CALL mpp_maxloc( 'diacfl', zCu_cfl, umask, zCu_max, iloc_u )
+         CALL mpp_maxloc( 'diacfl', zCv_cfl, vmask, zCv_max, iloc_v )
+         CALL mpp_maxloc( 'diacfl', zCw_cfl, wmask, zCw_max, iloc_w )
+      ELSE
+         iloc = MAXLOC( ABS( zcu_cfl(:,:,:) ) )
+         iloc_u(1) = iloc(1) + nimpp - 1
+         iloc_u(2) = iloc(2) + njmpp - 1
+         iloc_u(3) = iloc(3)
+         zCu_max = zCu_cfl(iloc(1),iloc(2),iloc(3))
+         !
+         iloc = MAXLOC( ABS( zcv_cfl(:,:,:) ) )
+         iloc_v(1) = iloc(1) + nimpp - 1
+         iloc_v(2) = iloc(2) + njmpp - 1
+         iloc_v(3) = iloc(3)
+         zCv_max = zCv_cfl(iloc(1),iloc(2),iloc(3))
+         !
+         iloc = MAXLOC( ABS( zcw_cfl(:,:,:) ) )
+         iloc_w(1) = iloc(1) + nimpp - 1
+         iloc_w(2) = iloc(2) + njmpp - 1
+         iloc_w(3) = iloc(3)
+         zCw_max = zCw_cfl(iloc(1),iloc(2),iloc(3))
+      ENDIF
+      !
+      !                    ! write out to file
+      IF( lwp ) THEN
+         WRITE(numcfl,FMT='(2x,i6,3x,a6,4x,f7.4,1x,i4,1x,i4,1x,i4)') kt, 'Max Cu', zCu_max, iloc_u(1), iloc_u(2), iloc_u(3)
+         WRITE(numcfl,FMT='(11x,     a6,4x,f7.4,1x,i4,1x,i4,1x,i4)')     'Max Cv', zCv_max, iloc_v(1), iloc_v(2), iloc_v(3)
+         WRITE(numcfl,FMT='(11x,     a6,4x,f7.4,1x,i4,1x,i4,1x,i4)')     'Max Cw', zCw_max, iloc_w(1), iloc_w(2), iloc_w(3)
+      ENDIF
+      !
+      !                    ! update maximum Courant numbers from whole run if applicable
+      IF( zCu_max > rCu_max ) THEN   ;   rCu_max = zCu_max   ;   nCu_loc(:) = iloc_u(:)   ;   ENDIF
+      IF( zCv_max > rCv_max ) THEN   ;   rCv_max = zCv_max   ;   nCv_loc(:) = iloc_v(:)   ;   ENDIF
+      IF( zCw_max > rCw_max ) THEN   ;   rCw_max = zCw_max   ;   nCw_loc(:) = iloc_w(:)   ;   ENDIF
+
+      !                    ! at end of run output max Cu and Cv and close ascii file
+      IF( kt == nitend .AND. lwp ) THEN
+         ! to ascii file
+         WRITE(numcfl,*) '******************************************'
+         WRITE(numcfl,FMT='(3x,a12,6x,f7.4,1x,i4,1x,i4,1x,i4)') 'Run Max Cu', rCu_max, nCu_loc(1), nCu_loc(2), nCu_loc(3)
+         WRITE(numcfl,FMT='(3x,a8,11x,f15.1)') ' => dt/C', z2dt/rCu_max
+         WRITE(numcfl,*) '******************************************'
+         WRITE(numcfl,FMT='(3x,a12,6x,f7.4,1x,i4,1x,i4,1x,i4)') 'Run Max Cv', rCv_max, nCv_loc(1), nCv_loc(2), nCv_loc(3)
+         WRITE(numcfl,FMT='(3x,a8,11x,f15.1)') ' => dt/C', z2dt/rCv_max
+         WRITE(numcfl,*) '******************************************'
+         WRITE(numcfl,FMT='(3x,a12,6x,f7.4,1x,i4,1x,i4,1x,i4)') 'Run Max Cw', rCw_max, nCw_loc(1), nCw_loc(2), nCw_loc(3)
+         WRITE(numcfl,FMT='(3x,a8,11x,f15.1)') ' => dt/C', z2dt/rCw_max
+         CLOSE( numcfl ) 
+         !
+         ! to ocean output
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_cfl : Maximum Courant number information for the run '
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,*) '   Max Cu = ', rCu_max, ' at (i,j,k) = (',nCu_loc(1),nCu_loc(2),nCu_loc(3),') => dt/C = ', z2dt/rCu_max
+         WRITE(numout,*) '   Max Cv = ', rCv_max, ' at (i,j,k) = (',nCv_loc(1),nCv_loc(2),nCv_loc(3),') => dt/C = ', z2dt/rCv_max
+         WRITE(numout,*) '   Max Cw = ', rCw_max, ' at (i,j,k) = (',nCw_loc(1),nCw_loc(2),nCw_loc(3),') => dt/C = ', z2dt/rCw_max
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_cfl')
+      !
+   END SUBROUTINE dia_cfl
+
+
+   SUBROUTINE dia_cfl_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_cfl_init  ***
+      !!                   
+      !! ** Purpose :   create output file, initialise arrays
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_cfl : Outputting CFL diagnostics to ',TRIM(clname), ' file'
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,*)
+         !
+         ! create output ascii file
+         CALL ctl_opn( numcfl, clname, 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', 1, numout, lwp, 1 )
+         WRITE(numcfl,*) 'Timestep  Direction  Max C     i    j    k'
+         WRITE(numcfl,*) '******************************************'
+      ENDIF
+      !
+      rCu_max = 0._wp
+      rCv_max = 0._wp
+      rCw_max = 0._wp
+      !
+   END SUBROUTINE dia_cfl_init
+
+   !!======================================================================
+END MODULE diacfl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diadct.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diadct.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diadct.F90	(revision 14097)
@@ -0,0 +1,1255 @@
+MODULE diadct
+   !!======================================================================
+   !!                       ***  MODULE  diadct  ***
+   !! Ocean diagnostics: Compute the transport trough a sec.
+   !!======================================================================
+   !! History :  OPA  ! 02/1999 (Y Drillet)  original code
+   !!                 ! 10/2001 (Y Drillet, R Bourdalle Badie)
+   !!   NEMO     1.0  ! 10/2005 (M Laborie) F90
+   !!            3.0  ! 04/2007 (G Garric) Ice sections
+   !!             -   ! 04/2007 (C Bricaud) test on sec%nb_point, initialisation of ztransp1,ztransp2,...
+   !!            3.4  ! 09/2011 (C Bricaud)
+   !!----------------------------------------------------------------------
+   !! does not work with agrif
+#if ! defined key_agrif
+   !!----------------------------------------------------------------------
+   !!   dia_dct      :  Compute the transport through a sec.
+   !!   dia_dct_init :  Read namelist.
+   !!   readsec      :  Read sections description and pathway
+   !!   removepoints :  Remove points which are common to 2 procs
+   !!   transport    :  Compute transport for each sections
+   !!   dia_dct_wri  :  Write tranports results in ascii files
+   !!   interp       :  Compute temperature/salinity/density at U-point or V-point
+   !!   
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE in_out_manager  ! I/O manager
+   USE daymod          ! calendar
+   USE dianam          ! build name of file
+   USE lib_mpp         ! distributed memory computing library
+#if defined key_si3
+   USE ice
+#endif
+   USE domvvl
+   USE timing          ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_dct      ! routine called by step.F90
+   PUBLIC   dia_dct_init ! routine called by nemogcm.F90
+
+   !                         !!** namelist variables **
+   LOGICAL, PUBLIC ::   ln_diadct     !: Calculate transport thru a section or not
+   INTEGER         ::   nn_dct        !  Frequency of computation
+   INTEGER         ::   nn_dctwri     !  Frequency of output
+   INTEGER         ::   nn_secdebug   !  Number of the section to debug
+   
+   INTEGER, PARAMETER :: nb_class_max  = 10
+   INTEGER, PARAMETER :: nb_sec_max    = 150
+   INTEGER, PARAMETER :: nb_point_max  = 2000
+   INTEGER, PARAMETER :: nb_type_class = 10
+   INTEGER, PARAMETER :: nb_3d_vars    = 3 
+   INTEGER, PARAMETER :: nb_2d_vars    = 2 
+   INTEGER            :: nb_sec 
+
+   TYPE POINT_SECTION
+      INTEGER :: I,J
+   END TYPE POINT_SECTION
+
+   TYPE COORD_SECTION
+      REAL(wp) :: lon,lat
+   END TYPE COORD_SECTION
+
+   TYPE SECTION
+      CHARACTER(len=60)                            :: name              ! name of the sec
+      LOGICAL                                      :: llstrpond         ! true if you want the computation of salt and
+                                                                       ! heat transports
+      LOGICAL                                      :: ll_ice_section    ! ice surface and ice volume computation
+      LOGICAL                                      :: ll_date_line      ! = T if the section crosses the date-line
+      TYPE(COORD_SECTION), DIMENSION(2)            :: coordSec          ! longitude and latitude of the extremities of the sec
+      INTEGER                                      :: nb_class          ! number of boundaries for density classes
+      INTEGER, DIMENSION(nb_point_max)             :: direction         ! vector direction of the point in the section
+      CHARACTER(len=40),DIMENSION(nb_class_max)    :: classname         ! characteristics of the class
+      REAL(wp), DIMENSION(nb_class_max)            :: zsigi           ,&! in-situ   density classes    (99 if you don't want)
+                                                      zsigp           ,&! potential density classes    (99 if you don't want)
+                                                      zsal            ,&! salinity classes   (99 if you don't want)
+                                                      ztem            ,&! temperature classes(99 if you don't want)
+                                                      zlay              ! level classes      (99 if you don't want)
+      REAL(wp), DIMENSION(nb_type_class,nb_class_max)  :: transport     ! transport output
+      REAL(wp)                                         :: slopeSection  ! slope of the section
+      INTEGER                                          :: nb_point      ! number of points in the section
+      TYPE(POINT_SECTION),DIMENSION(nb_point_max)      :: listPoint     ! list of points in the sections
+   END TYPE SECTION
+
+   TYPE(SECTION),DIMENSION(nb_sec_max) :: secs ! Array of sections
+ 
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::  transports_3d 
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::  transports_2d  
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+ 
+   INTEGER FUNCTION diadct_alloc() 
+      !!---------------------------------------------------------------------- 
+      !!                   ***  FUNCTION diadct_alloc  *** 
+      !!---------------------------------------------------------------------- 
+
+      ALLOCATE( transports_3d(nb_3d_vars,nb_sec_max,nb_point_max,jpk), &
+         &      transports_2d(nb_2d_vars,nb_sec_max,nb_point_max)    , STAT=diadct_alloc ) 
+
+      CALL mpp_sum( 'diadct', diadct_alloc ) 
+      IF( diadct_alloc /= 0 )   CALL ctl_stop( 'STOP', 'diadct_alloc: failed to allocate arrays' ) 
+
+   END FUNCTION diadct_alloc
+
+   SUBROUTINE dia_dct_init
+      !!---------------------------------------------------------------------
+      !!               ***  ROUTINE diadct  ***  
+      !!
+      !!  ** Purpose: Read the namelist parameters
+      !!              Open output files
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/nam_diadct/ln_diadct, nn_dct, nn_dctwri, nn_secdebug
+      !!---------------------------------------------------------------------
+
+     REWIND( numnam_ref )              ! Namelist nam_diadct in reference namelist : Diagnostic: transport through sections
+     READ  ( numnam_ref, nam_diadct, IOSTAT = ios, ERR = 901)
+901  IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_diadct in reference namelist' )
+
+     REWIND( numnam_cfg )              ! Namelist nam_diadct in configuration namelist : Diagnostic: transport through sections
+     READ  ( numnam_cfg, nam_diadct, IOSTAT = ios, ERR = 902 )
+902  IF( ios >  0 ) CALL ctl_nam ( ios , 'nam_diadct in configuration namelist' )
+     IF(lwm) WRITE ( numond, nam_diadct )
+
+     IF( lwp ) THEN
+        WRITE(numout,*) " "
+        WRITE(numout,*) "diadct_init: compute transports through sections "
+        WRITE(numout,*) "~~~~~~~~~~~~~~~~~~~~~"
+        WRITE(numout,*) "       Calculate transport thru sections: ln_diadct = ", ln_diadct
+        WRITE(numout,*) "       Frequency of computation:          nn_dct    = ", nn_dct
+        WRITE(numout,*) "       Frequency of write:                nn_dctwri = ", nn_dctwri
+
+        IF      ( nn_secdebug .GE. 1 .AND. nn_secdebug .LE. nb_sec_max )THEN
+                                            WRITE(numout,*)"       Debug section number: ", nn_secdebug 
+        ELSE IF ( nn_secdebug ==  0 )THEN ; WRITE(numout,*)"       No section to debug"
+        ELSE IF ( nn_secdebug == -1 )THEN ; WRITE(numout,*)"       Debug all sections"
+        ELSE                              ; WRITE(numout,*)"       Wrong value for nn_secdebug : ",nn_secdebug
+        ENDIF
+     ENDIF
+
+     IF( ln_diadct ) THEN
+        ! control
+        IF(nn_dct .GE. nn_dctwri .AND. MOD(nn_dct,nn_dctwri) .NE. 0)  &
+           &  CALL ctl_stop( 'diadct: nn_dct should be smaller and a multiple of nn_dctwri' )
+
+        ! allocate dia_dct arrays
+        IF( diadct_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'diadct_alloc: failed to allocate arrays' )
+
+        !Read section_ijglobal.diadct
+        CALL readsec
+
+        !open output file
+        IF( lwm ) THEN
+           CALL ctl_opn( numdct_vol,  'volume_transport', 'NEW', 'FORMATTED', 'SEQUENTIAL', -1, numout,  .FALSE. )
+           CALL ctl_opn( numdct_heat, 'heat_transport'  , 'NEW', 'FORMATTED', 'SEQUENTIAL', -1, numout,  .FALSE. )
+           CALL ctl_opn( numdct_salt, 'salt_transport'  , 'NEW', 'FORMATTED', 'SEQUENTIAL', -1, numout,  .FALSE. )
+        ENDIF
+
+        ! Initialise arrays to zero 
+        transports_3d(:,:,:,:)=0.0 
+        transports_2d(:,:,:)  =0.0 
+        !
+     ENDIF
+     !
+  END SUBROUTINE dia_dct_init
+ 
+ 
+  SUBROUTINE dia_dct( kt )
+     !!---------------------------------------------------------------------
+     !!               ***  ROUTINE diadct  ***  
+     !!
+     !!  Purpose :: Compute section transports and write it in numdct files 
+     !!   
+     !!  Method  :: All arrays initialised to zero in dct_init 
+     !!             Each nn_dct time step call subroutine 'transports' for 
+     !!               each section to sum the transports over each grid cell. 
+     !!             Each nn_dctwri time step: 
+     !!               Divide the arrays by the number of summations to gain 
+     !!               an average value 
+     !!               Call dia_dct_sum to sum relevant grid boxes to obtain 
+     !!               totals for each class (density, depth, temp or sal) 
+     !!               Call dia_dct_wri to write the transports into file 
+     !!               Reinitialise all relevant arrays to zero 
+     !!---------------------------------------------------------------------
+     INTEGER, INTENT(in) ::   kt
+     !
+     INTEGER ::   jsec              ! loop on sections
+     INTEGER ::   itotal            ! nb_sec_max*nb_type_class*nb_class_max
+     LOGICAL ::   lldebug =.FALSE.  ! debug a section  
+     INTEGER              , DIMENSION(1)    ::   ish     ! work array for mpp_sum
+     INTEGER              , DIMENSION(3)    ::   ish2    !   "
+     REAL(wp), ALLOCATABLE, DIMENSION(:)    ::   zwork   !   "  
+     REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)::   zsum    !   "
+     !!---------------------------------------------------------------------    
+     !
+     IF( ln_timing )   CALL timing_start('dia_dct')
+
+     IF( lk_mpp )THEN
+        itotal = nb_sec_max*nb_type_class*nb_class_max
+        ALLOCATE( zwork(itotal) , zsum(nb_sec_max,nb_type_class,nb_class_max) )
+     ENDIF    
+ 
+     ! Initialise arrays
+     zwork(:) = 0.0 
+     zsum(:,:,:) = 0.0
+
+     IF( lwp .AND. kt==nit000+nn_dct-1 ) THEN
+         WRITE(numout,*) " "
+         WRITE(numout,*) "diadct: compute transport"
+         WRITE(numout,*) "~~~~~~~~~~~~~~~~~~~~~~~~~"
+         WRITE(numout,*) "nb_sec = ",nb_sec
+     ENDIF
+
+ 
+     ! Compute transport and write only at nn_dctwri
+     IF( MOD(kt,nn_dct)==0 ) THEN 
+
+        DO jsec=1,nb_sec
+
+           !debug this section computing ?
+           lldebug=.FALSE.
+           IF( (jsec==nn_secdebug .OR. nn_secdebug==-1) .AND.  kt==nit000+nn_dct-1 ) lldebug=.TRUE. 
+
+           !Compute transport through section  
+           CALL transport(secs(jsec),lldebug,jsec) 
+
+        ENDDO
+             
+        IF( MOD(kt,nn_dctwri)==0 )THEN
+
+           IF( kt==nit000+nn_dctwri-1 )WRITE(numout,*)"      diadct: average transports and write at kt = ",kt         
+  
+           !! divide arrays by nn_dctwri/nn_dct to obtain average 
+           transports_3d(:,:,:,:)=transports_3d(:,:,:,:)/(nn_dctwri/nn_dct) 
+           transports_2d(:,:,:)  =transports_2d(:,:,:)  /(nn_dctwri/nn_dct) 
+ 
+           ! Sum over each class 
+           DO jsec=1,nb_sec 
+              CALL dia_dct_sum(secs(jsec),jsec) 
+           ENDDO 
+
+           !Sum on all procs 
+           IF( lk_mpp )THEN
+              ish(1)  =  nb_sec_max*nb_type_class*nb_class_max 
+              ish2    = (/nb_sec_max,nb_type_class,nb_class_max/)
+              DO jsec=1,nb_sec ; zsum(jsec,:,:) = secs(jsec)%transport(:,:) ; ENDDO
+              zwork(:)= RESHAPE(zsum(:,:,:), ish )
+              CALL mpp_sum('diadct', zwork, ish(1))
+              zsum(:,:,:)= RESHAPE(zwork,ish2)
+              DO jsec=1,nb_sec ; secs(jsec)%transport(:,:) = zsum(jsec,:,:) ; ENDDO
+           ENDIF
+
+           !Write the transport
+           DO jsec=1,nb_sec
+
+              IF( lwm )CALL dia_dct_wri(kt,jsec,secs(jsec))
+            
+              !nullify transports values after writing
+              transports_3d(:,jsec,:,:)=0.
+              transports_2d(:,jsec,:  )=0.
+              secs(jsec)%transport(:,:)=0.  
+
+           ENDDO
+
+        ENDIF 
+
+     ENDIF
+
+     IF( lk_mpp )THEN
+        itotal = nb_sec_max*nb_type_class*nb_class_max
+        DEALLOCATE( zwork , zsum  )
+     ENDIF    
+
+     IF( ln_timing )   CALL timing_stop('dia_dct')
+     !
+  END SUBROUTINE dia_dct
+
+
+  SUBROUTINE readsec 
+     !!---------------------------------------------------------------------
+     !!               ***  ROUTINE readsec  ***
+     !!
+     !!  ** Purpose:
+     !!            Read a binary file(section_ijglobal.diadct) 
+     !!            generated by the tools "NEMOGCM/TOOLS/SECTIONS_DIADCT"
+     !!
+     !!
+     !!---------------------------------------------------------------------
+     INTEGER :: iptglo , iptloc                               ! Global and local number of points for a section
+     INTEGER :: isec, iiglo, ijglo, iiloc, ijloc,iost,i1 ,i2  ! temporary  integer
+     INTEGER :: jsec, jpt                                     ! dummy loop indices
+     INTEGER, DIMENSION(2) :: icoord 
+     LOGICAL               :: llbon, lldebug   ! local logical
+     CHARACTER(len=160)    :: clname           ! filename
+     CHARACTER(len=200)    :: cltmp
+     CHARACTER(len=200)    :: clformat                          !automatic format
+     TYPE(POINT_SECTION),DIMENSION(nb_point_max)  ::coordtemp   !contains listpoints coordinates read in the file
+     INTEGER, DIMENSION(nb_point_max) :: directemp              !contains listpoints directions read in the files
+     !!-------------------------------------------------------------------------------------
+
+     !open input file
+     !---------------
+     CALL ctl_opn( numdct_in, 'section_ijglobal.diadct', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+ 
+     !---------------
+     !Read input file
+     !---------------
+     
+     DO jsec=1,nb_sec_max      !loop on the nb_sec sections
+
+        IF (  jsec==nn_secdebug .OR. nn_secdebug==-1  ) &
+           & WRITE(numout,*)'debuging for section number: ',jsec 
+
+        !initialization
+        !---------------
+        secs(jsec)%name=''
+        secs(jsec)%llstrpond    = .FALSE.  ; secs(jsec)%ll_ice_section = .FALSE.
+        secs(jsec)%ll_date_line = .FALSE.  ; secs(jsec)%nb_class       = 0
+        secs(jsec)%zsigi        = 99._wp   ; secs(jsec)%zsigp          = 99._wp
+        secs(jsec)%zsal         = 99._wp   ; secs(jsec)%ztem           = 99._wp
+        secs(jsec)%zlay         = 99._wp         
+        secs(jsec)%transport    =  0._wp   ; secs(jsec)%nb_point       = 0
+
+        !read section's number / name / computing choices / classes / slopeSection / points number
+        !-----------------------------------------------------------------------------------------
+        READ(numdct_in,iostat=iost)isec
+        IF (iost .NE. 0 )EXIT !end of file 
+        WRITE(cltmp,'(a,i4.4,a,i4.4)')'diadct: read sections : Problem of section number: isec= ',isec,' and jsec= ',jsec
+        IF( jsec .NE. isec )  CALL ctl_stop( cltmp )
+
+        IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )WRITE(numout,*)"isec ",isec 
+
+        READ(numdct_in)secs(jsec)%name
+        READ(numdct_in)secs(jsec)%llstrpond
+        READ(numdct_in)secs(jsec)%ll_ice_section
+        READ(numdct_in)secs(jsec)%ll_date_line
+        READ(numdct_in)secs(jsec)%coordSec
+        READ(numdct_in)secs(jsec)%nb_class
+        READ(numdct_in)secs(jsec)%zsigi
+        READ(numdct_in)secs(jsec)%zsigp
+        READ(numdct_in)secs(jsec)%zsal
+        READ(numdct_in)secs(jsec)%ztem
+        READ(numdct_in)secs(jsec)%zlay
+        READ(numdct_in)secs(jsec)%slopeSection
+        READ(numdct_in)iptglo
+
+        !debug
+        !-----
+
+        IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )THEN
+          
+            WRITE(clformat,'(a,i2,a)') '(A40,', nb_class_max,'(f8.3,1X))' 
+
+            WRITE(numout,*)       "   Section name :                       ",TRIM(secs(jsec)%name)
+            WRITE(numout,*)       "      Compute heat and salt transport ? ",secs(jsec)%llstrpond
+            WRITE(numout,*)       "      Compute ice transport ?           ",secs(jsec)%ll_ice_section
+            WRITE(numout,*)       "      Section crosses date-line ?       ",secs(jsec)%ll_date_line
+            WRITE(numout,*)       "      Slope section :                   ",secs(jsec)%slopeSection
+            WRITE(numout,*)       "      Number of points in the section:  ",iptglo
+            WRITE(numout,*)       "      Number of classes                 ",secs(jsec)%nb_class
+            WRITE(numout,clformat)"      Insitu density classes :          ",secs(jsec)%zsigi
+            WRITE(numout,clformat)"      Potential density classes :       ",secs(jsec)%zsigp
+            WRITE(numout,clformat)"      Salinity classes :                ",secs(jsec)%zsal
+            WRITE(numout,clformat)"      Temperature classes :             ",secs(jsec)%ztem
+            WRITE(numout,clformat)"      Depth classes :                   ",secs(jsec)%zlay
+        ENDIF               
+
+        IF( iptglo /= 0 )THEN
+             
+           !read points'coordinates and directions 
+           !--------------------------------------
+           coordtemp(:) = POINT_SECTION(0,0) !list of points read
+           directemp(:) = 0                  !value of directions of each points
+           DO jpt=1,iptglo
+              READ(numdct_in) i1, i2
+              coordtemp(jpt)%I = i1 
+              coordtemp(jpt)%J = i2
+           ENDDO
+           READ(numdct_in) directemp(1:iptglo)
+    
+           !debug
+           !-----
+           IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )THEN
+              WRITE(numout,*)"      List of points in global domain:"
+              DO jpt=1,iptglo
+                 WRITE(numout,*)'        # I J ',jpt,coordtemp(jpt),directemp(jpt)
+              ENDDO                  
+           ENDIF
+ 
+           !Now each proc selects only points that are in its domain:
+           !--------------------------------------------------------
+           iptloc = 0                    ! initialize number of points selected
+           DO jpt = 1, iptglo            ! loop on listpoint read in the file
+              !      
+              iiglo=coordtemp(jpt)%I          ! global coordinates of the point
+              ijglo=coordtemp(jpt)%J          !  " 
+
+              IF( iiglo==jpiglo .AND. nimpp==1 )   iiglo = 2         !!gm BUG: Hard coded periodicity !
+
+              iiloc=iiglo-nimpp+1   ! local coordinates of the point
+              ijloc=ijglo-njmpp+1   !  "
+
+              !verify if the point is on the local domain:(1,nlei)*(1,nlej)
+              IF( iiloc >= 1 .AND. iiloc <= nlei .AND. &
+                  ijloc >= 1 .AND. ijloc <= nlej       )THEN
+                 iptloc = iptloc + 1                                                 ! count local points
+                 secs(jsec)%listPoint(iptloc) = POINT_SECTION(mi0(iiglo),mj0(ijglo)) ! store local coordinates
+                 secs(jsec)%direction(iptloc) = directemp(jpt)                       ! store local direction
+              ENDIF
+              !
+           END DO
+     
+           secs(jsec)%nb_point=iptloc !store number of section's points
+
+           !debug
+           !-----
+           IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )THEN
+              WRITE(numout,*)"      List of points selected by the proc:"
+              DO jpt = 1,iptloc
+                 iiglo = secs(jsec)%listPoint(jpt)%I + nimpp - 1
+                 ijglo = secs(jsec)%listPoint(jpt)%J + njmpp - 1
+                 WRITE(numout,*)'         # I J : ',iiglo,ijglo
+              ENDDO
+           ENDIF
+
+              IF(jsec==nn_secdebug .AND. secs(jsec)%nb_point .NE. 0)THEN
+              DO jpt = 1,iptloc
+                 iiglo = secs(jsec)%listPoint(jpt)%I + nimpp - 1
+                 ijglo = secs(jsec)%listPoint(jpt)%J + njmpp - 1
+              ENDDO
+              ENDIF
+
+           !remove redundant points between processors
+           !------------------------------------------
+           lldebug = .FALSE. ; IF ( jsec==nn_secdebug .OR. nn_secdebug==-1 ) lldebug = .TRUE.
+           IF( iptloc .NE. 0 )THEN
+              CALL removepoints(secs(jsec),'I','top_list',lldebug)
+              CALL removepoints(secs(jsec),'I','bot_list',lldebug)
+              CALL removepoints(secs(jsec),'J','top_list',lldebug)
+              CALL removepoints(secs(jsec),'J','bot_list',lldebug)
+           ENDIF
+           IF(jsec==nn_secdebug .AND. secs(jsec)%nb_point .NE. 0)THEN
+              DO jpt = 1,secs(jsec)%nb_point
+                 iiglo = secs(jsec)%listPoint(jpt)%I + nimpp - 1
+                 ijglo = secs(jsec)%listPoint(jpt)%J + njmpp - 1
+              ENDDO
+           ENDIF
+
+           !debug
+           !-----
+           IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )THEN
+              WRITE(numout,*)"      List of points after removepoints:"
+              iptloc = secs(jsec)%nb_point
+              DO jpt = 1,iptloc
+                 iiglo = secs(jsec)%listPoint(jpt)%I + nimpp - 1
+                 ijglo = secs(jsec)%listPoint(jpt)%J + njmpp - 1
+                 WRITE(numout,*)'         # I J : ',iiglo,ijglo
+                 CALL FLUSH(numout)
+              ENDDO
+           ENDIF
+
+        ELSE  ! iptglo = 0
+           IF( jsec==nn_secdebug .OR. nn_secdebug==-1 )&
+              WRITE(numout,*)'   No points for this section.'
+        ENDIF
+
+     ENDDO !end of the loop on jsec
+ 
+     nb_sec = jsec-1   !number of section read in the file
+     !
+  END SUBROUTINE readsec
+
+
+  SUBROUTINE removepoints(sec,cdind,cdextr,ld_debug)
+     !!---------------------------------------------------------------------------
+     !!             *** function removepoints
+     !!
+     !!   ** Purpose :: Remove points which are common to 2 procs
+     !!
+     !----------------------------------------------------------------------------
+     !! * arguments
+     TYPE(SECTION),INTENT(INOUT) :: sec
+     CHARACTER(len=1),INTENT(IN) :: cdind   ! = 'I'/'J'
+     CHARACTER(len=8),INTENT(IN) :: cdextr  ! = 'top_list'/'bot_list'
+     LOGICAL,INTENT(IN)          :: ld_debug                     
+
+     !! * Local variables
+     INTEGER :: iextr         ,& !extremity of listpoint that we verify
+                iind          ,& !coord     of listpoint that we verify
+                itest         ,& !indice value of the side of the domain 
+                                 !where points could be redundant
+                isgn          ,& ! isgn= 1 : scan listpoint from start to end
+                                 ! isgn=-1 : scan listpoint from end to start 
+                istart,iend      !first and last points selected in listpoint
+     INTEGER :: jpoint           !loop on list points
+     INTEGER, DIMENSION(nb_point_max)   :: idirec !contains temporary sec%direction
+     INTEGER, DIMENSION(2,nb_point_max) :: icoord !contains temporary sec%listpoint
+     !----------------------------------------------------------------------------
+     !
+     IF( ld_debug )WRITE(numout,*)'      -------------------------'
+     IF( ld_debug )WRITE(numout,*)'      removepoints in listpoint'
+
+     !iextr=extremity of list_point that we verify
+     IF      ( cdextr=='bot_list' )THEN ; iextr=1            ; isgn=1
+     ELSE IF ( cdextr=='top_list' )THEN ; iextr=sec%nb_point ; isgn=-1
+     ELSE    ; CALL ctl_stop("removepoints :Wrong value for cdextr")
+     ENDIF
+ 
+     !which coordinate shall we verify ?
+     IF      ( cdind=='I' )THEN   ; itest=nlei ; iind=1
+     ELSE IF ( cdind=='J' )THEN   ; itest=nlej ; iind=2
+     ELSE    ; CALL ctl_stop("removepoints :Wrong value for cdind") 
+     ENDIF
+
+     IF( ld_debug )THEN
+        WRITE(numout,*)'      case: coord/list extr/domain side'
+        WRITE(numout,*)'      ', cdind,' ',cdextr,' ',itest
+        WRITE(numout,*)'      Actual number of points: ',sec%nb_point
+     ENDIF
+
+     icoord(1,1:nb_point_max) = sec%listPoint%I
+     icoord(2,1:nb_point_max) = sec%listPoint%J
+     idirec                   = sec%direction
+     sec%listPoint            = POINT_SECTION(0,0)
+     sec%direction            = 0
+
+     jpoint=iextr+isgn
+     DO WHILE( jpoint .GE. 1 .AND. jpoint .LE. sec%nb_point )
+         IF( icoord( iind,jpoint-isgn ) == itest .AND. icoord( iind,jpoint ) == itest )THEN ; jpoint=jpoint+isgn
+         ELSE                                                                               ; EXIT
+         ENDIF
+     ENDDO 
+
+     IF( cdextr=='bot_list')THEN ; istart=jpoint-1 ; iend=sec%nb_point
+     ELSE                        ; istart=1        ; iend=jpoint+1
+     ENDIF
+
+     sec%listPoint(1:1+iend-istart)%I = icoord(1,istart:iend)
+     sec%listPoint(1:1+iend-istart)%J = icoord(2,istart:iend)
+     sec%direction(1:1+iend-istart)   = idirec(istart:iend)
+     sec%nb_point                     = iend-istart+1
+     
+     IF( ld_debug )THEN
+        WRITE(numout,*)'      Number of points after removepoints :',sec%nb_point
+        WRITE(numout,*)'      sec%direction after removepoints :',sec%direction(1:sec%nb_point)
+     ENDIF
+      !
+   END SUBROUTINE removepoints
+
+
+   SUBROUTINE transport(sec,ld_debug,jsec)
+     !!-------------------------------------------------------------------------------------------
+     !!                     ***  ROUTINE transport  ***
+     !!
+     !!  Purpose ::  Compute the transport for each point in a section 
+     !! 
+     !!  Method  ::  Loop over each segment, and each vertical level and add the transport 
+     !!              Be aware :           
+     !!              One section is a sum of segments 
+     !!              One segment is defined by 2 consecutive points in sec%listPoint 
+     !!              All points of sec%listPoint are positioned on the F-point of the cell 
+     !! 
+     !!              There are two loops:                  
+     !!              loop on the segment between 2 nodes 
+     !!              loop on the level jk !!
+     !! 
+     !!  Output  ::  Arrays containing the volume,density,heat,salt transports for each i
+     !!              point in a section, summed over each nn_dct. 
+     !!
+     !!-------------------------------------------------------------------------------------------
+     TYPE(SECTION),INTENT(INOUT) :: sec
+     LOGICAL      ,INTENT(IN)    :: ld_debug
+     INTEGER      ,INTENT(IN)    :: jsec        ! numeric identifier of section
+     !
+     INTEGER ::   jk, jseg, jclass,jl, isgnu, isgnv    ! loop on level/segment/classes/ice categories
+     REAL(wp)::   zumid, zvmid, zumid_ice, zvmid_ice   ! U/V ocean & ice velocity on a cell segment 
+     REAL(wp)::   zTnorm                               ! transport of velocity through one cell's sides 
+     REAL(wp)::   ztn, zsn, zrhoi, zrhop, zsshn, zdep  ! temperature/salinity/potential density/ssh/depth at u/v point
+     TYPE(POINT_SECTION) ::   k
+      !!--------------------------------------------------------
+      !
+      IF( ld_debug )WRITE(numout,*)'      Compute transport'
+
+      !---------------------------!
+      !  COMPUTE TRANSPORT        !
+      !---------------------------!
+      IF(sec%nb_point .NE. 0)THEN   
+
+         !----------------------------------------------------------------------------------------------------
+         !Compute sign for velocities:
+         !
+         !convention:
+         !   non horizontal section: direction + is toward left hand of section
+         !       horizontal section: direction + is toward north of section
+         !
+         !
+         !       slopeSection < 0     slopeSection > 0       slopeSection=inf            slopeSection=0
+         !       ----------------      -----------------     ---------------             --------------
+         !
+         !   isgnv=1         direction +      
+         !  ______         _____             ______                                                   
+         !        |           //|            |                  |                         direction +   
+         !        | isgnu=1  // |            |isgnu=1           |isgnu=1                     /|\
+         !        |_______  //         ______|    \\            | ---\                        |
+         !               |             | isgnv=-1  \\ |         | ---/ direction +       ____________
+         !               |             |          __\\|         |                    
+         !               |             |     direction +        |                      isgnv=1                                 
+         !                                                      
+         !----------------------------------------------------------------------------------------------------
+         isgnu = 1
+         IF( sec%slopeSection .GT. 0 ) THEN  ; isgnv = -1 
+         ELSE                                ; isgnv =  1
+         ENDIF
+         IF( sec%slopeSection .GE. 9999. )     isgnv =  1
+
+         IF( ld_debug )write(numout,*)"sec%slopeSection isgnu isgnv ",sec%slopeSection,isgnu,isgnv
+
+         !--------------------------------------!
+         ! LOOP ON THE SEGMENT BETWEEN 2 NODES  !
+         !--------------------------------------!
+         DO jseg=1,MAX(sec%nb_point-1,0)
+              
+            !-------------------------------------------------------------------------------------------
+            ! Select the appropriate coordinate for computing the velocity of the segment
+            !
+            !                      CASE(0)                                    Case (2)
+            !                      -------                                    --------
+            !  listPoint(jseg)                 listPoint(jseg+1)       listPoint(jseg)  F(i,j)      
+            !      F(i,j)----------V(i+1,j)-------F(i+1,j)                               |
+            !                                                                            |
+            !                                                                            |
+            !                                                                            |
+            !                      Case (3)                                            U(i,j)
+            !                      --------                                              |
+            !                                                                            |
+            !  listPoint(jseg+1) F(i,j+1)                                                |
+            !                        |                                                   |
+            !                        |                                                   |
+            !                        |                                 listPoint(jseg+1) F(i,j-1)
+            !                        |                                            
+            !                        |                                            
+            !                     U(i,j+1)                                            
+            !                        |                                       Case(1)     
+            !                        |                                       ------      
+            !                        |                                            
+            !                        |                 listPoint(jseg+1)             listPoint(jseg)                           
+            !                        |                 F(i-1,j)-----------V(i,j) -------f(jseg)                           
+            ! listPoint(jseg)     F(i,j)
+            ! 
+            !-------------------------------------------------------------------------------------------
+
+            SELECT CASE( sec%direction(jseg) )
+            CASE(0)   ;    k = sec%listPoint(jseg)
+            CASE(1)   ;    k = POINT_SECTION(sec%listPoint(jseg)%I+1,sec%listPoint(jseg)%J)
+            CASE(2)   ;    k = sec%listPoint(jseg)
+            CASE(3)   ;    k = POINT_SECTION(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J+1)
+            END SELECT
+
+            !---------------------------| 
+            !     LOOP ON THE LEVEL     | 
+            !---------------------------| 
+            DO jk = 1, mbkt(k%I,k%J)            !Sum of the transport on the vertical
+            !           ! compute temperature, salinity, insitu & potential density, ssh and depth at U/V point 
+            SELECT CASE( sec%direction(jseg) )
+               CASE(0,1) 
+                  ztn   = interp(k%I,k%J,jk,'V',tsn(:,:,:,jp_tem) ) 
+                  zsn   = interp(k%I,k%J,jk,'V',tsn(:,:,:,jp_sal) ) 
+                  zrhop = interp(k%I,k%J,jk,'V',rhop) 
+                  zrhoi = interp(k%I,k%J,jk,'V',rhd*rau0+rau0) 
+                  zsshn =  0.5*( sshn(k%I,k%J) + sshn(k%I,k%J+1)    ) * vmask(k%I,k%J,1) 
+               CASE(2,3) 
+                  ztn   = interp(k%I,k%J,jk,'U',tsn(:,:,:,jp_tem) ) 
+                  zsn   = interp(k%I,k%J,jk,'U',tsn(:,:,:,jp_sal) ) 
+                  zrhop = interp(k%I,k%J,jk,'U',rhop) 
+                  zrhoi = interp(k%I,k%J,jk,'U',rhd*rau0+rau0) 
+                  zsshn =  0.5*( sshn(k%I,k%J) + sshn(k%I+1,k%J)    ) * umask(k%I,k%J,1)  
+               END SELECT 
+               !
+               zdep= gdept_n(k%I,k%J,jk) 
+  
+               SELECT CASE( sec%direction(jseg) )                !compute velocity with the correct direction 
+               CASE(0,1)   
+                  zumid=0._wp
+                  zvmid=isgnv*vn(k%I,k%J,jk)*vmask(k%I,k%J,jk) 
+               CASE(2,3) 
+                  zumid=isgnu*un(k%I,k%J,jk)*umask(k%I,k%J,jk) 
+                  zvmid=0._wp
+               END SELECT 
+ 
+               !zTnorm=transport through one cell; 
+               !velocity* cell's length * cell's thickness 
+               zTnorm = zumid*e2u(k%I,k%J) * e3u_n(k%I,k%J,jk)     & 
+                  &   + zvmid*e1v(k%I,k%J) * e3v_n(k%I,k%J,jk) 
+
+!!gm  THIS is WRONG  no transport due to ssh in linear free surface case !!!!!
+               IF( ln_linssh ) THEN              !add transport due to free surface 
+                  IF( jk==1 ) THEN 
+                     zTnorm = zTnorm + zumid* e2u(k%I,k%J) * zsshn * umask(k%I,k%J,jk)   & 
+                        &            + zvmid* e1v(k%I,k%J) * zsshn * vmask(k%I,k%J,jk) 
+                  ENDIF 
+               ENDIF
+!!gm end
+              !COMPUTE TRANSPORT  
+ 
+              transports_3d(1,jsec,jseg,jk) = transports_3d(1,jsec,jseg,jk) + zTnorm 
+  
+              IF( sec%llstrpond ) THEN 
+                 transports_3d(2,jsec,jseg,jk) = transports_3d(2,jsec,jseg,jk)  + zTnorm * ztn * zrhop * rcp
+                 transports_3d(3,jsec,jseg,jk) = transports_3d(3,jsec,jseg,jk)  + zTnorm * zsn * zrhop * 0.001
+              ENDIF
+   
+           END DO !end of loop on the level
+
+#if defined key_si3
+
+           !ICE CASE    
+           !------------
+           IF( sec%ll_ice_section )THEN
+              SELECT CASE (sec%direction(jseg))
+              CASE(0)
+                 zumid_ice = 0
+                 zvmid_ice =  isgnv*0.5*(v_ice(k%I,k%J+1)+v_ice(k%I+1,k%J+1))
+              CASE(1)
+                 zumid_ice = 0
+                 zvmid_ice =  isgnv*0.5*(v_ice(k%I,k%J+1)+v_ice(k%I+1,k%J+1))
+              CASE(2)
+                 zvmid_ice = 0
+                 zumid_ice =  isgnu*0.5*(u_ice(k%I+1,k%J)+u_ice(k%I+1,k%J+1))
+              CASE(3)
+                 zvmid_ice = 0
+                 zumid_ice =  isgnu*0.5*(u_ice(k%I+1,k%J)+u_ice(k%I+1,k%J+1))
+              END SELECT
+   
+              zTnorm=zumid_ice*e2u(k%I,k%J)+zvmid_ice*e1v(k%I,k%J)
+
+#if defined key_si3
+              DO jl=1,jpl
+                 transports_2d(1,jsec,jseg) = transports_2d(1,jsec,jseg) + (zTnorm)*       &
+                                    a_i(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J,jl) *  &
+                                  ( h_i(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J,jl) +  &
+                                    h_s(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J,jl) )
+                                   
+                 transports_2d(2,jsec,jseg) = transports_2d(2,jsec,jseg) + (zTnorm)*   &
+                                    a_i(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J,jl)
+              END DO
+#endif
+   
+           ENDIF !end of ice case
+#endif
+ 
+        END DO !end of loop on the segment
+
+     ENDIF !end of sec%nb_point =0 case
+     !
+  END SUBROUTINE transport
+
+
+  SUBROUTINE dia_dct_sum(sec,jsec) 
+     !!------------------------------------------------------------- 
+     !! Purpose: Average the transport over nn_dctwri time steps  
+     !! and sum over the density/salinity/temperature/depth classes 
+     !! 
+     !! Method:   Sum over relevant grid cells to obtain values  
+     !!           for each class
+     !!              There are several loops:                  
+     !!              loop on the segment between 2 nodes 
+     !!              loop on the level jk 
+     !!              loop on the density/temperature/salinity/level classes 
+     !!              test on the density/temperature/salinity/level 
+     !! 
+     !!  Note:    Transport through a given section is equal to the sum of transports 
+     !!           computed on each proc. 
+     !!           On each proc,transport is equal to the sum of transport computed through 
+     !!           segments linking each point of sec%listPoint  with the next one.    
+     !! 
+     !!------------------------------------------------------------- 
+     TYPE(SECTION),INTENT(INOUT) :: sec 
+     INTEGER      ,INTENT(IN)    :: jsec        ! numeric identifier of section 
+ 
+     TYPE(POINT_SECTION) :: k 
+     INTEGER  :: jk,jseg,jclass                        ! dummy variables for looping on level/segment/classes  
+     REAL(wp) :: ztn, zsn, zrhoi, zrhop, zsshn, zdep ! temperature/salinity/ssh/potential density /depth at u/v point 
+     !!------------------------------------------------------------- 
+ 
+     !! Sum the relevant segments to obtain values for each class 
+     IF(sec%nb_point .NE. 0)THEN    
+ 
+        !--------------------------------------! 
+        ! LOOP ON THE SEGMENT BETWEEN 2 NODES  ! 
+        !--------------------------------------! 
+        DO jseg=1,MAX(sec%nb_point-1,0) 
+            
+           !------------------------------------------------------------------------------------------- 
+           ! Select the appropriate coordinate for computing the velocity of the segment 
+           ! 
+           !                      CASE(0)                                    Case (2) 
+           !                      -------                                    -------- 
+           !  listPoint(jseg)                 listPoint(jseg+1)       listPoint(jseg)  F(i,j)       
+           !      F(i,j)----------V(i+1,j)-------F(i+1,j)                               | 
+           !                                                                            | 
+           !                                                                            | 
+           !                                                                            | 
+           !                      Case (3)                                            U(i,j) 
+           !                      --------                                              | 
+           !                                                                            | 
+           !  listPoint(jseg+1) F(i,j+1)                                                | 
+           !                        |                                                   | 
+           !                        |                                                   | 
+           !                        |                                 listPoint(jseg+1) F(i,j-1) 
+           !                        |                                             
+           !                        |                                             
+           !                     U(i,j+1)                                             
+           !                        |                                       Case(1)      
+           !                        |                                       ------       
+           !                        |                                             
+           !                        |                 listPoint(jseg+1)             listPoint(jseg)                            
+           !                        |                 F(i-1,j)-----------V(i,j) -------f(jseg)                            
+           ! listPoint(jseg)     F(i,j) 
+           !  
+           !------------------------------------------------------------------------------------------- 
+ 
+           SELECT CASE( sec%direction(jseg) ) 
+           CASE(0)  ;   k = sec%listPoint(jseg) 
+           CASE(1)  ;   k = POINT_SECTION(sec%listPoint(jseg)%I+1,sec%listPoint(jseg)%J) 
+           CASE(2)  ;   k = sec%listPoint(jseg) 
+           CASE(3)  ;   k = POINT_SECTION(sec%listPoint(jseg)%I,sec%listPoint(jseg)%J+1) 
+           END SELECT 
+ 
+           !---------------------------| 
+           !     LOOP ON THE LEVEL     | 
+           !---------------------------| 
+           !Sum of the transport on the vertical  
+           DO jk=1,mbkt(k%I,k%J) 
+ 
+              ! compute temperature, salinity, insitu & potential density, ssh and depth at U/V point 
+              SELECT CASE( sec%direction(jseg) ) 
+              CASE(0,1) 
+                 ztn   = interp(k%I,k%J,jk,'V',tsn(:,:,:,jp_tem) ) 
+                 zsn   = interp(k%I,k%J,jk,'V',tsn(:,:,:,jp_sal) ) 
+                 zrhop = interp(k%I,k%J,jk,'V',rhop) 
+                 zrhoi = interp(k%I,k%J,jk,'V',rhd*rau0+rau0) 
+
+              CASE(2,3) 
+                 ztn   = interp(k%I,k%J,jk,'U',tsn(:,:,:,jp_tem) ) 
+                 zsn   = interp(k%I,k%J,jk,'U',tsn(:,:,:,jp_sal) ) 
+                 zrhop = interp(k%I,k%J,jk,'U',rhop) 
+                 zrhoi = interp(k%I,k%J,jk,'U',rhd*rau0+rau0) 
+                 zsshn =  0.5*( sshn(k%I,k%J)    + sshn(k%I+1,k%J)    ) * umask(k%I,k%J,1)  
+              END SELECT 
+ 
+              zdep= gdept_n(k%I,k%J,jk) 
+  
+              !------------------------------- 
+              !  LOOP ON THE DENSITY CLASSES | 
+              !------------------------------- 
+              !The computation is made for each density/temperature/salinity/depth class 
+              DO jclass=1,MAX(1,sec%nb_class-1) 
+ 
+                 !----------------------------------------------! 
+                 !TEST ON THE DENSITY/SALINITY/TEMPERATURE/LEVEL!  
+                 !----------------------------------------------! 
+
+                 IF ( (                                                    & 
+                    ((( zrhop .GE. (sec%zsigp(jclass)+1000.  )) .AND.      & 
+                    (   zrhop .LE. (sec%zsigp(jclass+1)+1000. ))) .OR.     & 
+                    ( sec%zsigp(jclass) .EQ. 99.)) .AND.                   & 
+ 
+                    ((( zrhoi .GE. (sec%zsigi(jclass) + 1000.  )) .AND.    & 
+                    (   zrhoi .LE. (sec%zsigi(jclass+1)+1000. ))) .OR.     & 
+                    ( sec%zsigi(jclass) .EQ. 99.)) .AND.                   & 
+ 
+                    ((( zsn .GT. sec%zsal(jclass)) .AND.                   & 
+                    (   zsn .LE. sec%zsal(jclass+1))) .OR.                 & 
+                    ( sec%zsal(jclass) .EQ. 99.)) .AND.                    & 
+ 
+                    ((( ztn .GE. sec%ztem(jclass)) .AND.                   & 
+                    (   ztn .LE. sec%ztem(jclass+1))) .OR.                 & 
+                    ( sec%ztem(jclass) .EQ.99.)) .AND.                     & 
+ 
+                    ((( zdep .GE. sec%zlay(jclass)) .AND.                & 
+                    (   zdep .LE. sec%zlay(jclass+1))) .OR.              & 
+                    ( sec%zlay(jclass) .EQ. 99. ))                         & 
+                                                                   ))   THEN 
+ 
+                    !SUM THE TRANSPORTS FOR EACH CLASSES FOR THE POSITIVE AND NEGATIVE DIRECTIONS 
+                    !---------------------------------------------------------------------------- 
+                    IF (transports_3d(1,jsec,jseg,jk) .GE. 0.0) THEN  
+                       sec%transport(1,jclass) = sec%transport(1,jclass)+transports_3d(1,jsec,jseg,jk)*1.E-6 
+                    ELSE 
+                       sec%transport(2,jclass) = sec%transport(2,jclass)+transports_3d(1,jsec,jseg,jk)*1.E-6 
+                    ENDIF 
+                    IF( sec%llstrpond )THEN 
+ 
+                       IF ( transports_3d(2,jsec,jseg,jk) .GE. 0.0 ) THEN 
+                          sec%transport(3,jclass) = sec%transport(3,jclass)+transports_3d(2,jsec,jseg,jk) 
+                       ELSE 
+                          sec%transport(4,jclass) = sec%transport(4,jclass)+transports_3d(2,jsec,jseg,jk) 
+                       ENDIF 
+ 
+                       IF ( transports_3d(3,jsec,jseg,jk) .GE. 0.0 ) THEN 
+                          sec%transport(5,jclass) = sec%transport(5,jclass)+transports_3d(3,jsec,jseg,jk) 
+                       ELSE 
+                          sec%transport(6,jclass) = sec%transport(6,jclass)+transports_3d(3,jsec,jseg,jk) 
+                       ENDIF 
+ 
+                    ELSE 
+                       sec%transport( 3,jclass) = 0._wp 
+                       sec%transport( 4,jclass) = 0._wp 
+                       sec%transport( 5,jclass) = 0._wp 
+                       sec%transport( 6,jclass) = 0._wp 
+                    ENDIF 
+ 
+                 ENDIF ! end of test if point is in class 
+    
+              END DO ! end of loop on the classes 
+ 
+           END DO ! loop over jk 
+ 
+#if defined key_si3 
+ 
+           !ICE CASE     
+           IF( sec%ll_ice_section )THEN 
+ 
+              IF ( transports_2d(1,jsec,jseg) .GE. 0.0 ) THEN 
+                 sec%transport( 7,1) = sec%transport( 7,1)+transports_2d(1,jsec,jseg)*1.E-6 
+              ELSE 
+                 sec%transport( 8,1) = sec%transport( 8,1)+transports_2d(1,jsec,jseg)*1.E-6 
+              ENDIF 
+ 
+              IF ( transports_2d(3,jsec,jseg) .GE. 0.0 ) THEN 
+                 sec%transport( 9,1) = sec%transport( 9,1)+transports_2d(2,jsec,jseg)*1.E-6 
+              ELSE 
+                 sec%transport(10,1) = sec%transport(10,1)+transports_2d(2,jsec,jseg)*1.E-6 
+              ENDIF 
+ 
+           ENDIF !end of ice case 
+#endif 
+  
+        END DO !end of loop on the segment 
+ 
+     ELSE  !if sec%nb_point =0 
+        sec%transport(1:2,:)=0. 
+        IF (sec%llstrpond) sec%transport(3:6,:)=0. 
+        IF (sec%ll_ice_section) sec%transport(7:10,:)=0. 
+     ENDIF !end of sec%nb_point =0 case 
+ 
+  END SUBROUTINE dia_dct_sum 
+
+
+  SUBROUTINE dia_dct_wri(kt,ksec,sec)
+     !!-------------------------------------------------------------
+     !! Write transport output in numdct 
+     !! 
+     !! Purpose: Write  transports in ascii files
+     !! 
+     !! Method:
+     !!        1. Write volume transports in "volume_transport"
+     !!           Unit: Sv : area * Velocity / 1.e6 
+     !! 
+     !!        2. Write heat transports in "heat_transport"
+     !!           Unit: Peta W : area * Velocity * T * rhop * Cp * 1.e-15
+     !! 
+     !!        3. Write salt transports in "salt_transport"
+     !!           Unit: 10^9 Kg/m^2/s : area * Velocity * S * rhop * 1.e-9 
+     !!
+     !!------------------------------------------------------------- 
+     !!arguments
+     INTEGER, INTENT(IN)          :: kt          ! time-step
+     TYPE(SECTION), INTENT(INOUT) :: sec         ! section to write   
+     INTEGER ,INTENT(IN)          :: ksec        ! section number
+
+     !!local declarations
+     INTEGER               :: jclass             ! Dummy loop
+     CHARACTER(len=2)      :: classe             ! Classname 
+     REAL(wp)              :: zbnd1,zbnd2        ! Class bounds
+     REAL(wp)              :: zslope             ! section's slope coeff
+     !
+     REAL(wp), DIMENSION(nb_type_class)::   zsumclasses   ! 1D workspace 
+     !!------------------------------------------------------------- 
+
+     zsumclasses(:)=0._wp
+     zslope = sec%slopeSection       
+
+ 
+     DO jclass=1,MAX(1,sec%nb_class-1)
+
+        classe   = 'N       '
+        zbnd1   = 0._wp
+        zbnd2   = 0._wp
+        zsumclasses(1:nb_type_class)=zsumclasses(1:nb_type_class)+sec%transport(1:nb_type_class,jclass)
+
+   
+        !insitu density classes transports
+        IF( ( sec%zsigi(jclass)   .NE. 99._wp ) .AND. &
+            ( sec%zsigi(jclass+1) .NE. 99._wp )       )THEN
+           classe = 'DI       '
+           zbnd1 = sec%zsigi(jclass)
+           zbnd2 = sec%zsigi(jclass+1)
+        ENDIF
+        !potential density classes transports
+        IF( ( sec%zsigp(jclass)   .NE. 99._wp ) .AND. &
+            ( sec%zsigp(jclass+1) .NE. 99._wp )       )THEN
+           classe = 'DP      '
+           zbnd1 = sec%zsigp(jclass)
+           zbnd2 = sec%zsigp(jclass+1)
+        ENDIF
+        !depth classes transports
+        IF( ( sec%zlay(jclass)    .NE. 99._wp ) .AND. &
+            ( sec%zlay(jclass+1)  .NE. 99._wp )       )THEN 
+           classe = 'Z       '
+           zbnd1 = sec%zlay(jclass)
+           zbnd2 = sec%zlay(jclass+1)
+        ENDIF
+        !salinity classes transports
+        IF( ( sec%zsal(jclass) .NE. 99._wp    ) .AND. &
+            ( sec%zsal(jclass+1) .NE. 99._wp  )       )THEN
+           classe = 'S       '
+           zbnd1 = sec%zsal(jclass)
+           zbnd2 = sec%zsal(jclass+1)   
+        ENDIF
+        !temperature classes transports
+        IF( ( sec%ztem(jclass) .NE. 99._wp     ) .AND. &
+            ( sec%ztem(jclass+1) .NE. 99._wp     )       ) THEN
+           classe = 'T       '
+           zbnd1 = sec%ztem(jclass)
+           zbnd2 = sec%ztem(jclass+1)
+        ENDIF
+                  
+        !write volume transport per class
+        WRITE(numdct_vol,118) ndastp,kt,ksec,sec%name,zslope, &
+                              jclass,classe,zbnd1,zbnd2,&
+                              sec%transport(1,jclass),sec%transport(2,jclass), &
+                              sec%transport(1,jclass)+sec%transport(2,jclass)
+
+        IF( sec%llstrpond )THEN
+
+           !write heat transport per class:
+           WRITE(numdct_heat,119) ndastp,kt,ksec,sec%name,zslope,  &
+                              jclass,classe,zbnd1,zbnd2,&
+                              sec%transport(3,jclass)*1.e-15,sec%transport(4,jclass)*1.e-15, &
+                              ( sec%transport(3,jclass)+sec%transport(4,jclass) )*1.e-15
+           !write salt transport per class
+           WRITE(numdct_salt,119) ndastp,kt,ksec,sec%name,zslope,  &
+                              jclass,classe,zbnd1,zbnd2,&
+                              sec%transport(5,jclass)*1.e-9,sec%transport(6,jclass)*1.e-9,&
+                              (sec%transport(5,jclass)+sec%transport(6,jclass))*1.e-9
+        ENDIF
+
+     ENDDO
+
+     zbnd1 = 0._wp
+     zbnd2 = 0._wp
+     jclass=0
+
+     !write total volume transport
+     WRITE(numdct_vol,118) ndastp,kt,ksec,sec%name,zslope, &
+                           jclass,"total",zbnd1,zbnd2,&
+                           zsumclasses(1),zsumclasses(2),zsumclasses(1)+zsumclasses(2)
+
+     IF( sec%llstrpond )THEN
+
+        !write total heat transport
+        WRITE(numdct_heat,119) ndastp,kt,ksec,sec%name,zslope, &
+                           jclass,"total",zbnd1,zbnd2,&
+                           zsumclasses(3)*1.e-15,zsumclasses(4)*1.e-15,&
+                           (zsumclasses(3)+zsumclasses(4) )*1.e-15
+        !write total salt transport
+        WRITE(numdct_salt,119) ndastp,kt,ksec,sec%name,zslope, &
+                           jclass,"total",zbnd1,zbnd2,&
+                           zsumclasses(5)*1.e-9,zsumclasses(6)*1.e-9,&
+                           (zsumclasses(5)+zsumclasses(6))*1.e-9
+     ENDIF
+
+      
+     IF ( sec%ll_ice_section) THEN
+        !write total ice volume transport
+        WRITE(numdct_vol,118) ndastp,kt,ksec,sec%name,zslope,&
+                              jclass,"ice_vol",zbnd1,zbnd2,&
+                              sec%transport(7,1),sec%transport(8,1),&
+                              sec%transport(7,1)+sec%transport(8,1)
+        !write total ice surface transport
+        WRITE(numdct_vol,118) ndastp,kt,ksec,sec%name,zslope,&
+                              jclass,"ice_surf",zbnd1,zbnd2,&
+                              sec%transport(9,1),sec%transport(10,1), &
+                              sec%transport(9,1)+sec%transport(10,1) 
+      ENDIF
+                                              
+118   FORMAT(I8,1X,I8,1X,I4,1X,A30,1X,f9.2,1X,I4,3X,A8,1X,2F12.4,5X,3F12.4)
+119   FORMAT(I8,1X,I8,1X,I4,1X,A30,1X,f9.2,1X,I4,3X,A8,1X,2F12.4,5X,3E15.6)
+      !
+   END SUBROUTINE dia_dct_wri
+
+
+   FUNCTION interp(ki, kj, kk, cd_point, ptab)
+  !!----------------------------------------------------------------------
+  !!
+  !!   Purpose: compute temperature/salinity/density at U-point or V-point
+  !!   --------
+  !!
+  !!   Method:
+  !!   ------
+  !!
+  !!   ====> full step and partial step
+  !! 
+  !!
+  !!    |    I          |    I+1           |    Z=temperature/salinity/density at U-poinT
+  !!    |               |                  |
+  !!  ----------------------------------------  1. Veritcal interpolation: compute zbis
+  !!    |               |                  |       interpolation between ptab(I,J,K) and ptab(I,J,K+1)
+  !!    |               |                  |       zbis = 
+  !!    |               |                  |      [ e3w(I+1,J,K)*ptab(I,J,K) + ( e3w(I,J,K) - e3w(I+1,J,K) ) * ptab(I,J,K-1) ]
+  !!    |               |                  |      /[ e3w(I+1,J,K) + e3w(I,J,K) - e3w(I+1,J,K) ] 
+  !!    |               |                  | 
+  !!    |               |                  |    2. Horizontal interpolation: compute value at U/V point
+  !!K-1 | ptab(I,J,K-1) |                  |       interpolation between zbis and ptab(I+1,J,K)  
+  !!    |     .         |                  |
+  !!    |     .         |                  |       interp = ( 0.5*zet2*zbis + 0.5*zet1*ptab(I+1,J,K) )/(0.5*zet2+0.5*zet1) 
+  !!    |     .         |                  |
+  !!  ------------------------------------------
+  !!    |     .         |                  |
+  !!    |     .         |                  |
+  !!    |     .         |                  |
+  !!K   |    zbis.......U...ptab(I+1,J,K)  |
+  !!    |     .         |                  |
+  !!    | ptab(I,J,K)   |                  |
+  !!    |               |------------------|
+  !!    |               | partials         |
+  !!    |               |  steps           |
+  !!  -------------------------------------------
+  !!    <----zet1------><----zet2--------->
+  !!
+  !!
+  !!   ====>  s-coordinate
+  !!     
+  !!    |                |                  |   1. Compute distance between T1 and U points: SQRT( zdep1^2 + (0.5 * zet1 )^2
+  !!    |                |                  |      Compute distance between T2 and U points: SQRT( zdep2^2 + (0.5 * zet2 )^2
+  !!    |                | ptab(I+1,J,K)    | 
+  !!    |                |      T2          |   2. Interpolation between  T1 and T2 values at U point 
+  !!    |                |      ^           |    
+  !!    |                |      | zdep2     |    
+  !!    |                |      |           |    
+  !!    |       ^        U      v           |
+  !!    |       |        |                  |
+  !!    |       | zdep1  |                  |    
+  !!    |       v        |                  |
+  !!    |      T1        |                  |
+  !!    | ptab(I,J,K)    |                  | 
+  !!    |                |                  | 
+  !!    |                |                  | 
+  !!
+  !!    <----zet1--------><----zet2--------->
+  !!
+  !!----------------------------------------------------------------------
+  !*arguments
+  INTEGER, INTENT(IN)                          :: ki, kj, kk   ! coordinate of point
+  CHARACTER(len=1), INTENT(IN)                 :: cd_point     ! type of point (U, V)
+  REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(IN) :: ptab         ! variable to compute at (ki, kj, kk )
+  REAL(wp)                                     :: interp       ! interpolated variable 
+
+  !*local declations
+  INTEGER :: ii1, ij1, ii2, ij2                                ! local integer
+  REAL(wp):: ze3t, ze3, zwgt1, zwgt2, zbis, zdepu            ! local real
+  REAL(wp):: zet1, zet2                                        ! weight for interpolation 
+  REAL(wp):: zdep1,zdep2                                       ! differences of depth
+  REAL(wp):: zmsk                                              ! mask value
+  !!----------------------------------------------------------------------
+
+  IF( cd_point=='U' )THEN 
+     ii1 = ki    ; ij1 = kj 
+     ii2 = ki+1  ; ij2 = kj 
+
+     zet1=e1t(ii1,ij1)
+     zet2=e1t(ii2,ij2)
+     zmsk=umask(ii1,ij1,kk)
+  
+
+  ELSE ! cd_point=='V' 
+     ii1 = ki    ; ij1 = kj 
+     ii2 = ki    ; ij2 = kj+1  
+
+     zet1=e2t(ii1,ij1)
+     zet2=e2t(ii2,ij2)
+     zmsk=vmask(ii1,ij1,kk)
+
+  ENDIF
+
+  IF( ln_sco )THEN   ! s-coordinate case
+
+     zdepu = ( gdept_n(ii1,ij1,kk) +  gdept_n(ii2,ij2,kk) ) * 0.5_wp 
+     zdep1 = gdept_n(ii1,ij1,kk) - zdepu
+     zdep2 = gdept_n(ii2,ij2,kk) - zdepu
+
+     ! weights
+     zwgt1 = SQRT( ( 0.5 * zet1 ) * ( 0.5 * zet1 ) + ( zdep1 * zdep1 ) )
+     zwgt2 = SQRT( ( 0.5 * zet2 ) * ( 0.5 * zet2 ) + ( zdep2 * zdep2 ) )
+  
+     ! result
+     interp = zmsk * ( zwgt2 *  ptab(ii1,ij1,kk) + zwgt1 *  ptab(ii1,ij1,kk) ) / ( zwgt2 + zwgt1 )   
+
+
+  ELSE       ! full step or partial step case 
+
+     ze3t  = e3t_n(ii2,ij2,kk) - e3t_n(ii1,ij1,kk) 
+     zwgt1 = ( e3w_n(ii2,ij2,kk) - e3w_n(ii1,ij1,kk) ) / e3w_n(ii2,ij2,kk)
+     zwgt2 = ( e3w_n(ii1,ij1,kk) - e3w_n(ii2,ij2,kk) ) / e3w_n(ii1,ij1,kk)
+
+     IF(kk .NE. 1)THEN
+
+        IF( ze3t >= 0. )THEN 
+           ! zbis
+           zbis = ptab(ii2,ij2,kk) + zwgt1 * ( ptab(ii2,ij2,kk-1) - ptab(ii2,ij2,kk) ) 
+           ! result
+            interp = zmsk * ( zet2 * ptab(ii1,ij1,kk) + zet1 * zbis )/( zet1 + zet2 )
+        ELSE
+           ! zbis
+           zbis = ptab(ii1,ij1,kk) + zwgt2 * ( ptab(ii1,ij1,kk-1) - ptab(ii1,ij2,kk) )
+           ! result
+           interp = zmsk * ( zet2 * zbis + zet1 * ptab(ii2,ij2,kk) )/( zet1 + zet2 )
+        ENDIF    
+
+     ELSE
+        interp = zmsk * (  zet2 * ptab(ii1,ij1,kk) + zet1 * ptab(ii2,ij2,kk) )/( zet1 + zet2 )
+     ENDIF
+
+  ENDIF
+      !
+   END FUNCTION interp
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                             
+   !!----------------------------------------------------------------------
+   LOGICAL, PUBLIC ::   ln_diadct = .FALSE.
+CONTAINS
+   SUBROUTINE dia_dct_init
+      IMPLICIT NONE
+   END SUBROUTINE dia_dct_init
+   SUBROUTINE dia_dct( kt )
+      IMPLICIT NONE
+      INTEGER, INTENT(in) ::   kt
+   END SUBROUTINE dia_dct
+   !
+#endif
+
+   !!======================================================================
+END MODULE diadct
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaharm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaharm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaharm.F90	(revision 14097)
@@ -0,0 +1,467 @@
+MODULE diaharm 
+   !!======================================================================
+   !!                       ***  MODULE  diaharm  ***
+   !! Harmonic analysis of tidal constituents 
+   !!======================================================================
+   !! History :  3.1  !  2007  (O. Le Galloudec, J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain
+   USE phycst
+   USE daymod
+   USE tide_mod
+   USE sbctide         ! Tidal forcing or not
+   !
+   USE in_out_manager  ! I/O units
+   USE iom             ! I/0 library
+   USE ioipsl          ! NetCDF IPSL library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! preformance summary
+   USE lib_mpp           ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   INTEGER, PARAMETER :: jpincomax    = 2.*jpmax_harmo
+   INTEGER, PARAMETER :: jpdimsparse  = jpincomax*366*24*2 ! 30min for a 1yr-long run
+
+   !                         !!** namelist variables **
+   LOGICAL, PUBLIC ::   ln_diaharm    ! Choose tidal harmonic output or not
+   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 , ALLOCATABLE, DIMENSION(:)       ::   name
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ana_temp
+   REAL(wp), ALLOCATABLE, DIMENSION(:)       ::   ana_freq, ut, vt, ft
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   out_eta, out_u, out_v
+
+   INTEGER  ::   ninco, nsparse
+   REAL(wp) ::   z1_tmp3
+   INTEGER ,       DIMENSION(jpdimsparse)         ::   njsparse, nisparse
+   INTEGER , SAVE, DIMENSION(jpincomax)           ::   ipos1
+   REAL(wp),       DIMENSION(jpdimsparse)         ::   valuesparse
+   REAL(wp),       DIMENSION(jpincomax)           ::   ztmp4 , ztmp7, z1_pivot
+   REAL(wp), SAVE, DIMENSION(jpincomax,jpincomax) ::   ztmp3 , zpilier
+
+   CHARACTER (LEN=4), DIMENSION(jpmax_harmo) ::   tname   ! Names of tidal constituents ('M2', 'K1',...)
+
+   PUBLIC   dia_harm        ! routine called by step.F90
+   PUBLIC   dia_harm_init   ! routine called by nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_harm_init 
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_harm_init  ***
+      !!         
+      !! ** Purpose :   Initialization of tidal harmonic analysis
+      !!
+      !! ** Method  :   Initialize frequency array and  nodal factor for nit000_han
+      !!
+      !!--------------------------------------------------------------------
+      INTEGER ::   jh, nhan, ji
+      INTEGER ::   ios                 ! Local integer output status for namelist read
+
+      NAMELIST/nam_diaharm/ ln_diaharm, nit000_han, nitend_han, nstep_han, tname
+      !!----------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_harm_init: Tidal harmonic analysis initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~~ '
+      ENDIF
+      !
+      REWIND( numnam_ref )              ! Namelist nam_diaharm in reference namelist : Tidal harmonic analysis
+      READ  ( numnam_ref, nam_diaharm, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_diaharm in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_diaharm in configuration namelist : Tidal harmonic analysis
+      READ  ( numnam_cfg, nam_diaharm, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nam_diaharm in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_diaharm )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) 'Tidal diagnostics = ', ln_diaharm
+         WRITE(numout,*) '   First time step used for analysis:         nit000_han= ', nit000_han
+         WRITE(numout,*) '   Last  time step used for analysis:         nitend_han= ', nitend_han
+         WRITE(numout,*) '   Time step frequency for harmonic analysis: nstep_han = ', nstep_han
+      ENDIF
+
+      IF( ln_diaharm .AND. .NOT.ln_tide )   CALL ctl_stop( 'dia_harm_init : ln_tide must be true for harmonic analysis')
+
+      IF( ln_diaharm ) THEN
+
+         CALL tide_init_Wave
+         !
+         ! Basic checks on harmonic analysis time window:
+         ! ----------------------------------------------
+         IF( nit000 > nit000_han )   CALL ctl_stop( 'dia_harm_init : nit000_han must be greater than nit000',   &
+            &                                       ' restart capability not implemented' )
+         IF( nitend < nitend_han )   CALL ctl_stop( 'dia_harm_init : nitend_han must be lower than nitend',   &
+            &                                       'restart capability not implemented' )
+
+         IF( MOD( nitend_han-nit000_han+1 , nstep_han ) /= 0 )   &
+            &                        CALL ctl_stop( 'dia_harm_init : analysis time span must be a multiple of nstep_han' )
+         !
+         nb_ana = 0
+         DO jh=1,jpmax_harmo
+            DO ji=1,jpmax_harmo
+               IF(TRIM(tname(jh)) == Wave(ji)%cname_tide) THEN
+                  nb_ana=nb_ana+1
+               ENDIF
+            END DO
+         END DO
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) '        Namelist nam_diaharm'
+            WRITE(numout,*) '        nb_ana    = ', nb_ana
+            CALL flush(numout)
+         ENDIF
+         !
+         IF (nb_ana > jpmax_harmo) THEN
+            WRITE(ctmp1,*) ' nb_ana must be lower than jpmax_harmo'
+            WRITE(ctmp2,*) ' jpmax_harmo= ', jpmax_harmo
+            CALL ctl_stop( 'dia_harm_init', ctmp1, ctmp2 )
+         ENDIF
+
+         ALLOCATE(name(nb_ana))
+         DO jh=1,nb_ana
+            DO ji=1,jpmax_harmo
+               IF (TRIM(tname(jh)) ==  Wave(ji)%cname_tide) THEN
+                  name(jh) = ji
+                  EXIT
+               END IF
+            END DO
+         END DO
+
+         ! Initialize frequency array:
+         ! ---------------------------
+         ALLOCATE( ana_freq(nb_ana), ut(nb_ana), vt(nb_ana), ft(nb_ana) )
+
+         CALL tide_harmo( ana_freq, vt, ut, ft, name, nb_ana )
+
+         IF(lwp) WRITE(numout,*) 'Analysed frequency  : ',nb_ana ,'Frequency '
+
+         DO jh = 1, nb_ana
+            IF(lwp) WRITE(numout,*) '                    : ',tname(jh),' ',ana_freq(jh)
+         END DO
+
+         ! Initialize temporary arrays:
+         ! ----------------------------
+         ALLOCATE( ana_temp(jpi,jpj,2*nb_ana,3) )
+         ana_temp(:,:,:,:) = 0._wp
+
+      ENDIF
+
+   END SUBROUTINE dia_harm_init
+
+
+   SUBROUTINE dia_harm( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_harm  ***
+      !!         
+      !! ** Purpose :   Tidal harmonic analysis main routine
+      !!
+      !! ** Action  :   Sums ssh/u/v over time analysis [nit000_han,nitend_han]
+      !!
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt
+      !
+      INTEGER  ::   ji, jj, jh, jc, nhc
+      REAL(wp) ::   ztime, ztemp
+      !!--------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('dia_harm')
+      !
+      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 = 2, jpjm1
+                  DO ji = 2, jpim1
+                     ana_temp(ji,jj,nhc,1) = ana_temp(ji,jj,nhc,1) + ztemp * sshn(ji,jj) * ssmask (ji,jj) ! elevation      
+                     ana_temp(ji,jj,nhc,2) = ana_temp(ji,jj,nhc,2) + ztemp * un_b(ji,jj) * ssumask(ji,jj) ! u-vel
+                     ana_temp(ji,jj,nhc,3) = ana_temp(ji,jj,nhc,3) + ztemp * vn_b(ji,jj) * ssvmask(ji,jj) ! v-vel
+                  END DO
+               END DO
+            END DO
+         END DO
+      END IF
+      !
+      IF( kt == nitend_han )   CALL dia_harm_end
+      !
+      IF( ln_timing )   CALL timing_stop('dia_harm')
+      !
+   END SUBROUTINE dia_harm
+
+
+   SUBROUTINE dia_harm_end
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE diaharm_end  ***
+      !!         
+      !! ** Purpose :  Compute the Real and Imaginary part of tidal constituents
+      !!
+      !! ** Action  :  Decompose the signal on the harmonic constituents 
+      !!
+      !!--------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jh, jc, jn, nhan
+      INTEGER  ::   ksp, kun, keq
+      REAL(wp) ::   ztime, ztime_ini, ztime_end, z1_han
+      !!--------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dia_harm_end: kt=nitend_han: Perform harmonic analysis'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      
+      ALLOCATE( out_eta(jpi,jpj,2*nb_ana), out_u(jpi,jpj,2*nb_ana), out_v(jpi,jpj,2*nb_ana) )
+
+      ztime_ini = nit000_han*rdt                 ! Initial time in seconds at the beginning of analysis
+      ztime_end = nitend_han*rdt                 ! Final time in seconds at the end of analysis
+      nhan = (nitend_han-nit000_han+1)/nstep_han ! Number of dumps used for analysis
+      z1_han = 1._wp / REAL(nhan-1) 
+      
+      ninco = 2*nb_ana
+
+      ksp = 0
+      keq = 0        
+      DO jn = 1, nhan
+         ztime=( (nhan-jn)*ztime_ini + (jn-1)*ztime_end ) * z1_han
+         keq = keq + 1
+         kun = 0
+         DO jh = 1, nb_ana
+            DO jc = 1, 2
+               kun = kun + 1
+               ksp = ksp + 1
+               nisparse(ksp) = keq
+               njsparse(ksp) = kun
+               valuesparse(ksp) = (   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)) )
+            END DO
+         END DO
+      END DO
+
+      nsparse = ksp
+
+      IF( nsparse > jpdimsparse )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : nsparse .GT. jpdimsparse')
+      IF( ninco   > jpincomax   )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : ninco .GT. jpincomax')
+
+      CALL SUR_DETERMINE_INIT
+
+      ! Elevation:
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+
+            ! Fill input array
+            ztmp4(1:nb_ana*2) = ana_temp(ji,jj,1:nb_ana*2,1)
+            CALL SUR_DETERMINE
+            
+            ! Fill output array
+            DO jh = 1, nb_ana
+               out_eta(ji,jj,jh       ) =  ztmp7((jh-1)*2+1) * ssmask(ji,jj)
+               out_eta(ji,jj,jh+nb_ana) = -ztmp7((jh-1)*2+2) * ssmask(ji,jj)
+            END DO
+         END DO
+      END DO
+
+      ! ubar:
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+
+            ! Fill input array
+            ztmp4(1:nb_ana*2) = ana_temp(ji,jj,1:nb_ana*2,2)
+            CALL SUR_DETERMINE
+
+            ! Fill output array
+            DO jh = 1, nb_ana
+               out_u(ji,jj,       jh) =  ztmp7((jh-1)*2+1) * ssumask(ji,jj)
+               out_u(ji,jj,nb_ana+jh) = -ztmp7((jh-1)*2+2) * ssumask(ji,jj)
+            END DO
+
+        END DO
+      END DO
+
+      ! vbar:
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+
+            ! Fill input array
+            ztmp4(1:nb_ana*2) = ana_temp(ji,jj,1:nb_ana*2,3)
+            CALL SUR_DETERMINE
+
+            ! Fill output array
+            DO jh = 1, nb_ana
+               out_v(ji,jj,       jh) =  ztmp7((jh-1)*2+1) * ssvmask(ji,jj)
+               out_v(ji,jj,nb_ana+jh) = -ztmp7((jh-1)*2+2) * ssvmask(ji,jj)
+            END DO
+
+         END DO
+      END DO
+      !
+      ! clem: we could avoid this call if all the loops were from 1:jpi and 1:jpj
+      !       but I think this is the most efficient
+      CALL lbc_lnk_multi( 'dia_harm_end', out_eta, 'T', 1., out_u, 'U', -1. , out_v, 'V', -1. )
+      !
+      CALL dia_wri_harm ! Write results in files
+      !
+      DEALLOCATE( out_eta, out_u, out_v )
+      !
+   END SUBROUTINE dia_harm_end
+
+
+   SUBROUTINE dia_wri_harm
+      !!--------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_wri_harm  ***
+      !!         
+      !! ** Purpose : Write tidal harmonic analysis results in a netcdf file
+      !!--------------------------------------------------------------------
+      INTEGER  ::   jh
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*) '  '
+      IF(lwp) WRITE(numout,*) 'dia_wri_harm : Write harmonic analysis results'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+
+      ! A) Elevation
+      !/////////////
+      DO jh = 1, nb_ana
+      CALL iom_put( TRIM(tname(jh))//'x', out_eta(:,:,jh) )
+      CALL iom_put( TRIM(tname(jh))//'y', out_eta(:,:,jh+nb_ana) )
+      END DO
+
+      ! B) ubar
+      !/////////
+      DO jh = 1, nb_ana
+      CALL iom_put( TRIM(tname(jh))//'x_u', out_u(:,:,jh) )
+      CALL iom_put( TRIM(tname(jh))//'y_u', out_u(:,:,jh+nb_ana) )
+      END DO
+
+      ! C) vbar
+      !/////////
+      DO jh = 1, nb_ana
+         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
+      !
+   END SUBROUTINE dia_wri_harm
+
+
+   SUBROUTINE SUR_DETERMINE_INIT
+      !!---------------------------------------------------------------------------------
+      !!                      *** ROUTINE SUR_DETERMINE_INIT ***
+      !!       
+      !!---------------------------------------------------------------------------------
+      INTEGER                        :: ji_sd, jj_sd, ji1_sd, ji2_sd, jh1_sd, jh2_sd
+      INTEGER                        :: ipivot
+      REAL(wp)                       :: zval1, zval2, zcol1, zcol2
+      INTEGER , DIMENSION(jpincomax) :: ipos2
+      !!---------------------------------------------------------------------------------
+      !            
+      !
+      ztmp3(:,:) = 0._wp
+      !
+      DO jh1_sd = 1, nsparse
+         DO jh2_sd = 1, nsparse
+            IF( nisparse(jh2_sd) == nisparse(jh1_sd) ) THEN
+               ztmp3(njsparse(jh1_sd),njsparse(jh2_sd)) = ztmp3(njsparse(jh1_sd),njsparse(jh2_sd))  &
+                  &                                     + valuesparse(jh1_sd)*valuesparse(jh2_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
+         DO jj_sd = ji_sd, ninco
+            zval2 = ABS(ztmp3(ji_sd,jj_sd))
+            IF( zval2 >= zval1 )THEN
+               ipivot = jj_sd
+               zval1  = zval2
+            ENDIF
+         END DO
+         !
+         DO ji1_sd = 1, ninco
+            zcol1                = ztmp3(ji1_sd,ji_sd)
+            zcol2                = ztmp3(ji1_sd,ipivot)
+            ztmp3(ji1_sd,ji_sd)  = zcol2
+            ztmp3(ji1_sd,ipivot) = zcol1
+         END DO
+         !
+         ipos2(ji_sd)    = ipos1(ipivot)
+         ipos2(ipivot)   = ipos1(ji_sd)
+         ipos1(ji_sd)    = ipos2(ji_sd)
+         ipos1(ipivot)   = ipos2(ipivot)
+         z1_pivot(ji_sd) = 1._wp / ztmp3(ji_sd,ji_sd)
+         DO jj_sd = 1, ninco
+            ztmp3(ji_sd,jj_sd) = ztmp3(ji_sd,jj_sd) * z1_pivot(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
+      !
+      z1_tmp3 = 1._wp / ztmp3(ninco,ninco)
+      !
+   END SUBROUTINE SUR_DETERMINE_INIT
+
+   
+   SUBROUTINE SUR_DETERMINE
+      !!---------------------------------------------------------------------------------
+      !!                      *** ROUTINE SUR_DETERMINE ***
+      !!    
+      !!---------------------------------------------------------------------------------
+      INTEGER                        :: ji_sd, jj_sd, ji1_sd, ji2_sd
+      REAL(wp)                       :: zx1
+      REAL(wp), DIMENSION(jpincomax) :: ztmpx
+      !!---------------------------------------------------------------------------------
+      !            
+      DO ji_sd = 1, ninco
+         ztmp4(ji_sd) = ztmp4(ji_sd) * z1_pivot(ji_sd)
+         DO ji2_sd = ji_sd+1, ninco
+            ztmp4(ji2_sd) = ztmp4(ji2_sd) - ztmp4(ji_sd) * zpilier(ji2_sd,ji_sd)
+         END DO
+      END DO
+
+      !system solving: 
+      ztmpx(ninco) = ztmp4(ninco) * z1_tmp3
+      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
+      !
+   END SUBROUTINE SUR_DETERMINE
+
+   
+   !!======================================================================
+END MODULE diaharm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahsb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahsb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahsb.F90	(revision 14097)
@@ -0,0 +1,424 @@
+MODULE diahsb
+   !!======================================================================
+   !!                       ***  MODULE  diahsb  ***
+   !! Ocean diagnostics: Heat, salt and volume budgets
+   !!======================================================================
+   !! History :  3.3  ! 2010-09  (M. Leclair)  Original code 
+   !!                 ! 2012-10  (C. Rousset)  add iom_put
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   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 sbcrnf         ! river runoff
+   USE sbcisf         ! ice shelves
+   USE domvvl         ! vertical scale factors
+   USE traqsr         ! penetrative solar radiation
+   USE trabbc         ! bottom boundary condition 
+   USE trabbc         ! bottom boundary condition
+   USE restart        ! ocean restart
+   USE bdy_oce , ONLY : ln_bdy
+   !
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_hsb        ! routine called by step.F90
+   PUBLIC   dia_hsb_init   ! routine called by nemogcm.F90
+
+   LOGICAL, PUBLIC ::   ln_diahsb   !: check the heat and salt budgets
+
+   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 
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   surf_ini      , 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 "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_hsb( kt )
+      !!---------------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_hsb  ***
+      !!     
+      !! ** Purpose: Compute the ocean global heat content, salt content and volume conservation
+      !!	
+      !! ** Method : - Compute the deviation of heat content, salt content and volume
+      !!	            at the current time step from their values at nit000
+      !!	            - Compute the contribution of forcing and remove it from these deviations
+      !!
+      !!---------------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      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(jpi,jpj)       ::   z2d0, z2d1   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpkm1) ::   zwrk         ! 3D workspace
+      !!---------------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('dia_hsb')      
+      !
+      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( 'diahsb', - ( emp(:,:) - rnf(:,:) + fwfisf(:,:) ) * surf(:,:) )   ! volume fluxes
+      z_frc_trd_t =           glob_sum( 'diahsb', sbc_tsc(:,:,jp_tem) * surf(:,:) )                       ! heat fluxes
+      z_frc_trd_s =           glob_sum( 'diahsb', 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( 'diahsb', rnf_tsc(:,:,jp_tem) * surf(:,:) )
+      IF( ln_rnf_sal)   z_frc_trd_s = z_frc_trd_s + glob_sum( 'diahsb', rnf_tsc(:,:,jp_sal) * surf(:,:) )
+      !                    ! Add ice shelf heat & salt input
+      IF( ln_isf    )   z_frc_trd_t = z_frc_trd_t + glob_sum( 'diahsb', risf_tsc(:,:,jp_tem) * surf(:,:) )
+      !                    ! Add penetrative solar radiation
+      IF( ln_traqsr )   z_frc_trd_t = z_frc_trd_t + r1_rau0_rcp * glob_sum( 'diahsb', qsr     (:,:) * surf(:,:) )
+      !                    ! Add geothermal heat flux
+      IF( ln_trabbc )   z_frc_trd_t = z_frc_trd_t +               glob_sum( 'diahsb', qgh_trd0(:,:) * surf(:,:) )
+      !
+      IF( ln_linssh ) THEN
+         IF( ln_isfcav ) THEN
+            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)
+               END DO
+            END DO
+         ELSE
+            z2d0(:,:) = surf(:,:) * wn(:,:,1) * tsb(:,:,1,jp_tem)
+            z2d1(:,:) = surf(:,:) * wn(:,:,1) * tsb(:,:,1,jp_sal)
+         END IF
+         z_wn_trd_t = - glob_sum( 'diahsb', z2d0 ) 
+         z_wn_trd_s = - glob_sum( 'diahsb', z2d1 )
+      ENDIF
+
+      frc_v = frc_v + z_frc_trd_v * rdt
+      frc_t = frc_t + z_frc_trd_t * rdt
+      frc_s = frc_s + z_frc_trd_s * rdt
+      !                                          ! Advection flux through fixed surface (z=0)
+      IF( ln_linssh ) THEN
+         frc_wn_t = frc_wn_t + z_wn_trd_t * rdt
+         frc_wn_s = frc_wn_s + z_wn_trd_s * rdt
+      ENDIF
+
+      ! ------------------------ !
+      ! 2 -  Content variations  !
+      ! ------------------------ !
+      ! glob_sum_full is needed because you keep the full interior domain to compute the sum (iscpl)
+
+      !                    ! volume variation (calculated with ssh)
+      zdiff_v1 = glob_sum_full( 'diahsb', surf(:,:)*sshn(:,:) - surf_ini(:,:)*ssh_ini(:,:) )
+
+      !                    ! heat & salt content variation (associated with ssh)
+      IF( ln_linssh ) THEN       ! linear free surface case
+         IF( ln_isfcav ) THEN          ! ISF case
+            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
+         ELSE                          ! no under ice-shelf seas
+            z2d0(:,:) = surf(:,:) * ( tsn(:,:,1,jp_tem) * sshn(:,:) - ssh_hc_loc_ini(:,:) ) 
+            z2d1(:,:) = surf(:,:) * ( tsn(:,:,1,jp_sal) * sshn(:,:) - ssh_sc_loc_ini(:,:) ) 
+         END IF
+         z_ssh_hc = glob_sum_full( 'diahsb', z2d0 ) 
+         z_ssh_sc = glob_sum_full( 'diahsb', z2d1 ) 
+      ENDIF
+      !
+      DO jk = 1, jpkm1           ! volume variation (calculated with scale factors)
+         zwrk(:,:,jk) = ( surf(:,:)*e3t_n(:,:,jk) - surf_ini(:,:)*e3t_ini(:,:,jk) ) * tmask(:,:,jk)
+      END DO
+      zdiff_v2 = glob_sum_full( 'diahsb', zwrk(:,:,:) )
+      DO jk = 1, jpkm1           ! heat content variation
+         zwrk(:,:,jk) = ( surf(:,:)*e3t_n(:,:,jk)*tsn(:,:,jk,jp_tem) - surf_ini(:,:)*hc_loc_ini(:,:,jk) ) * tmask(:,:,jk)
+      END DO
+      zdiff_hc = glob_sum_full( 'diahsb', zwrk(:,:,:) )
+      DO jk = 1, jpkm1           ! salt content variation
+         zwrk(:,:,jk) = ( surf(:,:)*e3t_n(:,:,jk)*tsn(:,:,jk,jp_sal) - surf_ini(:,:)*sc_loc_ini(:,:,jk) ) * tmask(:,:,jk)
+      END DO
+      zdiff_sc = glob_sum_full( 'diahsb', zwrk(:,:,:) )
+
+      ! ------------------------ !
+      ! 3 -  Drifts              !
+      ! ------------------------ !
+      zdiff_v1 = zdiff_v1 - frc_v
+      IF( .NOT.ln_linssh )   zdiff_v2 = zdiff_v2 - frc_v
+      zdiff_hc = zdiff_hc - frc_t
+      zdiff_sc = zdiff_sc - frc_s
+      IF( ln_linssh ) THEN
+         zdiff_hc1 = zdiff_hc + z_ssh_hc 
+         zdiff_sc1 = zdiff_sc + z_ssh_sc
+         zerr_hc1  = z_ssh_hc - frc_wn_t
+         zerr_sc1  = z_ssh_sc - frc_wn_s
+      ENDIF
+
+      ! ----------------------- !
+      ! 4 - Diagnostics writing !
+      ! ----------------------- !
+      DO jk = 1, jpkm1           ! total ocean volume (calculated with scale factors)
+         zwrk(:,:,jk) = surf(:,:) * e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+      zvol_tot = glob_sum_full( 'diahsb', zwrk(:,:,:) )
+
+!!gm to be added ?
+!      IF( ln_linssh ) THEN            ! fixed volume, add the ssh contribution
+!        zvol_tot = zvol_tot + glob_sum( 'diahsb', surf(:,:) * sshn(:,:) )
+!      ENDIF
+!!gm end
+
+      CALL iom_put(   'bgfrcvol' , frc_v    * 1.e-9    )              ! vol - surface forcing (km3) 
+      CALL iom_put(   'bgfrctem' , frc_t    * rau0 * rcp * 1.e-20 )   ! hc  - surface forcing (1.e20 J) 
+      CALL iom_put(   'bgfrchfx' , frc_t    * rau0 * rcp /  &         ! hc  - surface forcing (W/m2) 
+         &                       ( surf_tot * kt * rdt )        )
+      CALL iom_put(   'bgfrcsal' , frc_s    * 1.e-9    )              ! sc  - surface forcing (psu*km3) 
+
+      IF( .NOT. ln_linssh ) THEN
+         CALL iom_put( 'bgtemper' , zdiff_hc / zvol_tot )              ! Temperature drift     (C) 
+         CALL iom_put( 'bgsaline' , zdiff_sc / zvol_tot )              ! Salinity    drift     (PSU)
+         CALL iom_put( 'bgheatco' , zdiff_hc * 1.e-20 * rau0 * rcp )   ! Heat content drift    (1.e20 J) 
+         CALL iom_put( 'bgheatfx' , zdiff_hc * rau0 * rcp /  &         ! Heat flux drift       (W/m2) 
+            &                       ( surf_tot * kt * rdt )        )
+         CALL iom_put( 'bgsaltco' , zdiff_sc * 1.e-9    )              ! Salt content drift    (psu*km3)
+         CALL iom_put( 'bgvolssh' , zdiff_v1 * 1.e-9    )              ! volume ssh drift      (km3)  
+         CALL iom_put( 'bgvole3t' , zdiff_v2 * 1.e-9    )              ! volume e3t drift      (km3)  
+         !
+         IF( kt == nitend .AND. lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'dia_hsb : last time step hsb diagnostics: at it= ', kt,' date= ', ndastp
+            WRITE(numout,*) '~~~~~~~'
+            WRITE(numout,*) '   Temperature drift = ', zdiff_hc / zvol_tot, ' C'
+            WRITE(numout,*) '   Salinity    drift = ', zdiff_sc / zvol_tot, ' PSU'
+            WRITE(numout,*) '   volume ssh  drift = ', zdiff_v1 * 1.e-9   , ' km^3'
+            WRITE(numout,*) '   volume e3t  drift = ', zdiff_v2 * 1.e-9   , ' km^3'
+         ENDIF
+         !
+      ELSE
+         CALL iom_put( 'bgtemper' , zdiff_hc1 / zvol_tot)              ! Heat content drift    (C) 
+         CALL iom_put( 'bgsaline' , zdiff_sc1 / zvol_tot)              ! Salt content drift    (PSU)
+         CALL iom_put( 'bgheatco' , zdiff_hc1 * 1.e-20 * rau0 * rcp )  ! Heat content drift    (1.e20 J) 
+         CALL iom_put( 'bgheatfx' , zdiff_hc1 * rau0 * rcp /  &        ! Heat flux drift       (W/m2) 
+            &                       ( surf_tot * kt * rdt )         )
+         CALL iom_put( 'bgsaltco' , zdiff_sc1 * 1.e-9    )             ! Salt content drift    (psu*km3)
+         CALL iom_put( 'bgvolssh' , zdiff_v1 * 1.e-9    )              ! volume ssh drift      (km3)  
+         CALL iom_put( 'bgmistem' , zerr_hc1 / zvol_tot )              ! hc  - error due to free surface (C)
+         CALL iom_put( 'bgmissal' , zerr_sc1 / zvol_tot )              ! sc  - error due to free surface (psu)
+      ENDIF
+      !
+      IF( lrst_oce )   CALL dia_hsb_rst( kt, 'WRITE' )
+      !
+      IF( ln_timing )   CALL timing_stop('dia_hsb')
+      !
+   END SUBROUTINE dia_hsb
+
+
+   SUBROUTINE dia_hsb_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dia_hsb_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write DIA file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   dia_hsb_rst : read hsb restart at it= ', kt,' date= ', ndastp
+            IF(lwp) WRITE(numout,*)
+            CALL iom_get( numror, 'frc_v', frc_v, ldxios = lrxios )
+            CALL iom_get( numror, 'frc_t', frc_t, ldxios = lrxios )
+            CALL iom_get( numror, 'frc_s', frc_s, ldxios = lrxios )
+            IF( ln_linssh ) THEN
+               CALL iom_get( numror, 'frc_wn_t', frc_wn_t, ldxios = lrxios )
+               CALL iom_get( numror, 'frc_wn_s', frc_wn_s, ldxios = lrxios )
+            ENDIF
+            CALL iom_get( numror, jpdom_autoglo, 'surf_ini'  , surf_ini  , ldxios = lrxios ) ! ice sheet coupling
+            CALL iom_get( numror, jpdom_autoglo, 'ssh_ini'   , ssh_ini   , ldxios = lrxios )
+            CALL iom_get( numror, jpdom_autoglo, 'e3t_ini'   , e3t_ini   , ldxios = lrxios )
+            CALL iom_get( numror, jpdom_autoglo, 'hc_loc_ini', hc_loc_ini, ldxios = lrxios )
+            CALL iom_get( numror, jpdom_autoglo, 'sc_loc_ini', sc_loc_ini, ldxios = lrxios )
+            IF( ln_linssh ) THEN
+               CALL iom_get( numror, jpdom_autoglo, 'ssh_hc_loc_ini', ssh_hc_loc_ini, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'ssh_sc_loc_ini', ssh_sc_loc_ini, ldxios = lrxios )
+            ENDIF
+         ELSE
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   dia_hsb_rst : initialise hsb at initial state '
+            IF(lwp) WRITE(numout,*)
+            surf_ini(:,:) = e1e2t(:,:) * tmask_i(:,:)         ! initial ocean surface
+            ssh_ini(:,:) = sshn(:,:)                          ! initial ssh
+            DO jk = 1, jpk
+              ! if ice sheet/oceqn coupling, need to mask ini variables here (mask could change at the next NEMO instance).
+               e3t_ini   (:,:,jk) = e3t_n(:,:,jk)                      * tmask(:,:,jk)  ! initial vertical scale factors
+               hc_loc_ini(:,:,jk) = tsn(:,:,jk,jp_tem) * e3t_n(:,:,jk) * tmask(:,:,jk)  ! initial heat content
+               sc_loc_ini(:,:,jk) = tsn(:,:,jk,jp_sal) * e3t_n(:,:,jk) * tmask(:,:,jk)  ! initial salt content
+            END DO
+            frc_v = 0._wp                                           ! volume       trend due to forcing
+            frc_t = 0._wp                                           ! heat content   -    -   -    -   
+            frc_s = 0._wp                                           ! salt content   -    -   -    -        
+            IF( ln_linssh ) THEN
+               IF( ln_isfcav ) THEN
+                  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
+                     END DO
+                   END DO
+                ELSE
+                  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
+               END IF
+               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
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   dia_hsb_rst : write restart at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*)
+         !
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_v', frc_v, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_t', frc_t, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'frc_s', frc_s, ldxios = lwxios )
+         IF( ln_linssh ) THEN
+            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_t', frc_wn_t, ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'frc_wn_s', frc_wn_s, ldxios = lwxios )
+         ENDIF
+         CALL iom_rstput( kt, nitrst, numrow, 'surf_ini'  , surf_ini  , ldxios = lwxios )      ! ice sheet coupling
+         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ini'   , ssh_ini   , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_ini'   , e3t_ini   , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'hc_loc_ini', hc_loc_ini, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'sc_loc_ini', sc_loc_ini, ldxios = lwxios )
+         IF( ln_linssh ) THEN
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_hc_loc_ini', ssh_hc_loc_ini, ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_sc_loc_ini', ssh_sc_loc_ini, ldxios = lwxios )
+         ENDIF
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         !
+      ENDIF
+      !
+   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 ::   ierror, ios   ! local integer
+      !!
+      NAMELIST/namhsb/ ln_diahsb
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_hsb_init : heat and salt budgets diagnostics'
+         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' )
+      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' )
+      IF(lwm) WRITE( numond, namhsb )
+
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist  namhsb :'
+         WRITE(numout,*) '      check the heat and salt budgets (T) or not (F)       ln_diahsb = ', ln_diahsb
+      ENDIF
+      !
+      IF( .NOT. ln_diahsb )   RETURN
+
+      IF(lwxios) THEN
+! define variables in restart file when writing with XIOS
+        CALL iom_set_rstw_var_active('frc_v')
+        CALL iom_set_rstw_var_active('frc_t')
+        CALL iom_set_rstw_var_active('frc_s')
+        CALL iom_set_rstw_var_active('surf_ini')
+        CALL iom_set_rstw_var_active('ssh_ini')
+        CALL iom_set_rstw_var_active('e3t_ini')
+        CALL iom_set_rstw_var_active('hc_loc_ini')
+        CALL iom_set_rstw_var_active('sc_loc_ini')
+        IF( ln_linssh ) THEN
+           CALL iom_set_rstw_var_active('ssh_hc_loc_ini')
+           CALL iom_set_rstw_var_active('ssh_sc_loc_ini')
+           CALL iom_set_rstw_var_active('frc_wn_t')
+           CALL iom_set_rstw_var_active('frc_wn_s')
+        ENDIF
+      ENDIF
+      ! ------------------- !
+      ! 1 - Allocate memory !
+      ! ------------------- !
+      ALLOCATE( hc_loc_ini(jpi,jpj,jpk), sc_loc_ini(jpi,jpj,jpk), surf_ini(jpi,jpj), &
+         &      e3t_ini(jpi,jpj,jpk), surf(jpi,jpj),  ssh_ini(jpi,jpj), STAT=ierror  )
+      IF( ierror > 0 ) THEN
+         CALL ctl_stop( 'dia_hsb_init: unable to allocate hc_loc_ini' )   ;   RETURN
+      ENDIF
+
+      IF( ln_linssh )   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 ssh_hc_loc_ini' )   ;   RETURN
+      ENDIF
+
+      ! ----------------------------------------------- !
+      ! 2 - Time independant variables and file opening !
+      ! ----------------------------------------------- !
+      surf(:,:) = e1e2t(:,:) * tmask_i(:,:)               ! masked surface grid cell area
+      surf_tot  = glob_sum( 'diahsb', surf(:,:) )         ! total ocean surface area
+
+      IF( ln_bdy ) CALL ctl_warn( 'dia_hsb_init: heat/salt budget does not consider open boundary fluxes' )         
+      !
+      ! ---------------------------------- !
+      ! 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahth.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahth.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diahth.F90	(revision 14097)
@@ -0,0 +1,392 @@
+MODULE diahth
+   !!======================================================================
+   !!                       ***  MODULE  diahth  ***
+   !! Ocean diagnostics: thermocline and 20 degree depth
+   !!======================================================================
+   !! History :  OPA  !  1994-09  (J.-P. Boulanger)  Original code
+   !!                 !  1996-11  (E. Guilyardi)  OPA8 
+   !!                 !  1997-08  (G. Madec)  optimization
+   !!                 !  1999-07  (E. Guilyardi)  hd28 + heat content 
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  !  2009-07  (S. Masson) hc300 bugfix + cleaning + add new diag
+   !!----------------------------------------------------------------------
+   !!   dia_hth      : Compute varius diagnostics associated with the mixed layer
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   USE iom             ! I/O library
+   USE timing          ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_hth       ! routine called by step.F90
+   PUBLIC   dia_hth_alloc ! routine called by nemogcm.F90
+
+   LOGICAL, SAVE  ::   l_hth     !: thermocline-20d depths flag
+   
+   ! note: following variables should move to local variables once iom_put is always used 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hth    !: depth of the max vertical temperature gradient [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hd20   !: depth of 20 C isotherm                         [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hd26   !: depth of 26 C isotherm                         [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hd28   !: depth of 28 C isotherm                         [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   htc3   !: heat content of first 300 m                    [W]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   htc7   !: heat content of first 700 m                    [W]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   htc20  !: heat content of first 2000 m                   [W]
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION dia_hth_alloc()
+      !!---------------------------------------------------------------------
+      INTEGER :: dia_hth_alloc
+      !!---------------------------------------------------------------------
+      !
+      ALLOCATE( hth(jpi,jpj), hd20(jpi,jpj), hd26(jpi,jpj), hd28(jpi,jpj), &
+         &      htc3(jpi,jpj), htc7(jpi,jpj), htc20(jpi,jpj), STAT=dia_hth_alloc )
+      !
+      CALL mpp_sum ( 'diahth', dia_hth_alloc )
+      IF(dia_hth_alloc /= 0)   CALL ctl_stop( 'STOP', 'dia_hth_alloc: failed to allocate arrays.' )
+      !
+   END FUNCTION dia_hth_alloc
+
+
+   SUBROUTINE dia_hth( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_hth  ***
+      !!
+      !! ** Purpose : Computes
+      !!      the mixing layer depth (turbocline): avt = 5.e-4
+      !!      the depth of strongest vertical temperature gradient
+      !!      the mixed layer depth with density     criteria: rho = rho(10m or surf) + 0.03(or 0.01)
+      !!      the mixed layer depth with temperature criteria: abs( tn - tn(10m) ) = 0.2       
+      !!      the top of the thermochine: tn = tn(10m) - ztem2 
+      !!      the pycnocline depth with density criteria equivalent to a temperature variation 
+      !!                rho = rho10m + (dr/dT)(T,S,10m)*(-0.2 degC) 
+      !!      the barrier layer thickness
+      !!      the maximal verical inversion of temperature and its depth max( 0, max of tn - tn(10m) )
+      !!      the depth of the 20 degree isotherm (linear interpolation)
+      !!      the depth of the 28 degree isotherm (linear interpolation)
+      !!      the heat content of first 300 m
+      !!
+      !! ** Method : 
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!
+      INTEGER                      ::   ji, jj, jk            ! dummy loop arguments
+      REAL(wp)                     ::   zrho3 = 0.03_wp       ! density     criterion for mixed layer depth
+      REAL(wp)                     ::   zrho1 = 0.01_wp       ! density     criterion for mixed layer depth
+      REAL(wp)                     ::   ztem2 = 0.2_wp        ! temperature criterion for mixed layer depth
+      REAL(wp)                     ::   zztmp, zzdep          ! temporary scalars inside do loop
+      REAL(wp)                     ::   zu, zv, zw, zut, zvt  ! temporary workspace
+      REAL(wp), DIMENSION(jpi,jpj) ::   zabs2      ! MLD: abs( tn - tn(10m) ) = ztem2 
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztm2       ! Top of thermocline: tn = tn(10m) - ztem2     
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrho10_3   ! MLD: rho = rho10m + zrho3      
+      REAL(wp), DIMENSION(jpi,jpj) ::   zpycn      ! pycnocline: rho = rho10m + (dr/dT)(T,S,10m)*(-0.2 degC)
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztinv      ! max of temperature inversion
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdepinv    ! depth of temperature inversion
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrho0_3    ! MLD rho = rho(surf) = 0.03
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrho0_1    ! MLD rho = rho(surf) = 0.01
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmaxdzT    ! max of dT/dz
+      REAL(wp), DIMENSION(jpi,jpj) ::   zdelr      ! delta rho equivalent to deltaT = 0.2
+      !!----------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('dia_hth')
+
+      IF( kt == nit000 ) THEN
+         l_hth = .FALSE.
+         IF(   iom_use( 'mlddzt'   ) .OR. iom_use( 'mldr0_3'  ) .OR. iom_use( 'mldr0_1'  )    .OR.  & 
+            &  iom_use( 'mld_dt02' ) .OR. iom_use( 'topthdep' ) .OR. iom_use( 'mldr10_3' )    .OR.  &    
+            &  iom_use( '20d'      ) .OR. iom_use( '26d'      ) .OR. iom_use( '28d'      )    .OR.  &    
+            &  iom_use( 'hc300'    ) .OR. iom_use( 'hc700'    ) .OR. iom_use( 'hc2000'   )    .OR.  &    
+            &  iom_use( 'pycndep'  ) .OR. iom_use( 'tinv'     ) .OR. iom_use( 'depti'    )  ) l_hth = .TRUE.
+         !                                      ! allocate dia_hth array
+         IF( l_hth ) THEN 
+            IF( dia_hth_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dia_hth : unable to allocate standard arrays' )
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'dia_hth : diagnostics of the thermocline depth'
+            IF(lwp) WRITE(numout,*) '~~~~~~~ '
+            IF(lwp) WRITE(numout,*)
+         ENDIF
+      ENDIF
+
+      IF( l_hth ) THEN
+         !
+         IF( iom_use( 'mlddzt' ) .OR. iom_use( 'mldr0_3' ) .OR. iom_use( 'mldr0_1' ) ) THEN
+            ! initialization
+            ztinv  (:,:) = 0._wp  
+            zdepinv(:,:) = 0._wp  
+            zmaxdzT(:,:) = 0._wp  
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zztmp = gdepw_n(ji,jj,mbkt(ji,jj)+1) 
+                  hth     (ji,jj) = zztmp
+                  zabs2   (ji,jj) = zztmp
+                  ztm2    (ji,jj) = zztmp
+                  zrho10_3(ji,jj) = zztmp
+                  zpycn   (ji,jj) = zztmp
+                 END DO
+            END DO
+            IF( nla10 > 1 ) THEN 
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zztmp = gdepw_n(ji,jj,mbkt(ji,jj)+1) 
+                     zrho0_3(ji,jj) = zztmp
+                     zrho0_1(ji,jj) = zztmp
+                  END DO
+               END DO
+            ENDIF
+      
+            ! Preliminary computation
+            ! computation of zdelr = (dr/dT)(T,S,10m)*(-0.2 degC)
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( tmask(ji,jj,nla10) == 1. ) THEN
+                     zu  =  1779.50 + 11.250 * tsn(ji,jj,nla10,jp_tem) - 3.80   * tsn(ji,jj,nla10,jp_sal)  &
+                        &           - 0.0745 * tsn(ji,jj,nla10,jp_tem) * tsn(ji,jj,nla10,jp_tem)   &
+                        &           - 0.0100 * tsn(ji,jj,nla10,jp_tem) * tsn(ji,jj,nla10,jp_sal)
+                     zv  =  5891.00 + 38.000 * tsn(ji,jj,nla10,jp_tem) + 3.00   * tsn(ji,jj,nla10,jp_sal)  &
+                        &           - 0.3750 * tsn(ji,jj,nla10,jp_tem) * tsn(ji,jj,nla10,jp_tem)
+                     zut =    11.25 -  0.149 * tsn(ji,jj,nla10,jp_tem) - 0.01   * tsn(ji,jj,nla10,jp_sal)
+                     zvt =    38.00 -  0.750 * tsn(ji,jj,nla10,jp_tem)
+                     zw  = (zu + 0.698*zv) * (zu + 0.698*zv)
+                     zdelr(ji,jj) = ztem2 * (1000.*(zut*zv - zvt*zu)/zw)
+                  ELSE
+                     zdelr(ji,jj) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+
+            ! ------------------------------------------------------------- !
+            ! thermocline depth: strongest vertical gradient of temperature !
+            ! turbocline depth (mixing layer depth): avt = zavt5            !
+            ! MLD: rho = rho(1) + zrho3                                     !
+            ! MLD: rho = rho(1) + zrho1                                     !
+            ! ------------------------------------------------------------- !
+            DO jk = jpkm1, 2, -1   ! loop from bottom to 2
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     !
+                     zzdep = gdepw_n(ji,jj,jk)
+                     zztmp = ( tsn(ji,jj,jk-1,jp_tem) - tsn(ji,jj,jk,jp_tem) ) &
+                            & / zzdep * tmask(ji,jj,jk)   ! vertical gradient of temperature (dT/dz)
+                     zzdep = zzdep * tmask(ji,jj,1)
+
+                     IF( zztmp > zmaxdzT(ji,jj) ) THEN                        
+                         zmaxdzT(ji,jj) = zztmp   
+                         hth    (ji,jj) = zzdep                ! max and depth of dT/dz
+                     ENDIF
+               
+                     IF( nla10 > 1 ) THEN 
+                        zztmp = rhop(ji,jj,jk) - rhop(ji,jj,1)                       ! delta rho(1)
+                        IF( zztmp > zrho3 )   zrho0_3(ji,jj) = zzdep                ! > 0.03
+                        IF( zztmp > zrho1 )   zrho0_1(ji,jj) = zzdep                ! > 0.01
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+         
+            CALL iom_put( 'mlddzt', hth )            ! depth of the thermocline
+            IF( nla10 > 1 ) THEN 
+               CALL iom_put( 'mldr0_3', zrho0_3 )   ! MLD delta rho(surf) = 0.03
+               CALL iom_put( 'mldr0_1', zrho0_1 )   ! MLD delta rho(surf) = 0.01
+            ENDIF
+            !
+         ENDIF
+         !
+         IF(  iom_use( 'mld_dt02' ) .OR. iom_use( 'topthdep' ) .OR. iom_use( 'mldr10_3' ) .OR.  &    
+            &  iom_use( 'pycndep' ) .OR. iom_use( 'tinv'     ) .OR. iom_use( 'depti'    )  ) THEN
+            ! ------------------------------------------------------------- !
+            ! MLD: abs( tn - tn(10m) ) = ztem2                              !
+            ! Top of thermocline: tn = tn(10m) - ztem2                      !
+            ! MLD: rho = rho10m + zrho3                                     !
+            ! pycnocline: rho = rho10m + (dr/dT)(T,S,10m)*(-0.2 degC)       !
+            ! temperature inversion: max( 0, max of tn - tn(10m) )          !
+            ! depth of temperature inversion                                !
+            ! ------------------------------------------------------------- !
+            DO jk = jpkm1, nlb10, -1   ! loop from bottom to nlb10
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     !
+                     zzdep = gdepw_n(ji,jj,jk) * tmask(ji,jj,1)
+                     !
+                     zztmp = tsn(ji,jj,nla10,jp_tem) - tsn(ji,jj,jk,jp_tem)  ! - delta T(10m)
+                     IF( ABS(zztmp) > ztem2 )      zabs2   (ji,jj) = zzdep   ! abs > 0.2
+                     IF(     zztmp  > ztem2 )      ztm2    (ji,jj) = zzdep   ! > 0.2
+                     zztmp = -zztmp                                          ! delta T(10m)
+                     IF( zztmp >  ztinv(ji,jj) ) THEN                        ! temperature inversion
+                        ztinv(ji,jj) = zztmp   
+                        zdepinv (ji,jj) = zzdep   ! max value and depth
+                     ENDIF
+
+                     zztmp = rhop(ji,jj,jk) - rhop(ji,jj,nla10)              ! delta rho(10m)
+                     IF( zztmp > zrho3        )    zrho10_3(ji,jj) = zzdep   ! > 0.03
+                     IF( zztmp > zdelr(ji,jj) )    zpycn   (ji,jj) = zzdep   ! > equi. delta T(10m) - 0.2
+                     !
+                  END DO
+               END DO
+            END DO
+
+            CALL iom_put( 'mld_dt02', zabs2    )   ! MLD abs(delta t) - 0.2
+            CALL iom_put( 'topthdep', ztm2     )   ! T(10) - 0.2
+            CALL iom_put( 'mldr10_3', zrho10_3 )   ! MLD delta rho(10m) = 0.03
+            CALL iom_put( 'pycndep' , zpycn    )   ! MLD delta rho equi. delta T(10m) = 0.2
+            CALL iom_put( 'tinv'    , ztinv    )   ! max. temp. inv. (t10 ref) 
+            CALL iom_put( 'depti'   , zdepinv  )   ! depth of max. temp. inv. (t10 ref) 
+            !
+         ENDIF
+ 
+         ! ------------------------------- !
+         !  Depth of 20C/26C/28C isotherm  !
+         ! ------------------------------- !
+         IF( iom_use ('20d') ) THEN  ! depth of the 20 isotherm
+            ztem2 = 20.
+            CALL dia_hth_dep( ztem2, hd20 )  
+            CALL iom_put( '20d', hd20 )    
+         ENDIF
+         !
+         IF( iom_use ('26d') ) THEN  ! depth of the 26 isotherm
+            ztem2 = 26.
+            CALL dia_hth_dep( ztem2, hd26 )  
+            CALL iom_put( '26d', hd26 )    
+         ENDIF
+         !
+         IF( iom_use ('28d') ) THEN  ! depth of the 28 isotherm
+            ztem2 = 28.
+            CALL dia_hth_dep( ztem2, hd28 )  
+            CALL iom_put( '28d', hd28 )    
+         ENDIF
+        
+         ! ----------------------------- !
+         !  Heat content of first 300 m  !
+         ! ----------------------------- !
+         IF( iom_use ('hc300') ) THEN  
+            zzdep = 300.
+            CALL  dia_hth_htc( zzdep, tsn(:,:,:,jp_tem), htc3 )
+            CALL iom_put( 'hc300', rau0_rcp * htc3 )  ! vertically integrated heat content (J/m2)
+         ENDIF
+         !
+         ! ----------------------------- !
+         !  Heat content of first 700 m  !
+         ! ----------------------------- !
+         IF( iom_use ('hc700') ) THEN  
+            zzdep = 700.
+            CALL  dia_hth_htc( zzdep, tsn(:,:,:,jp_tem), htc7 )
+            CALL iom_put( 'hc700', rau0_rcp * htc7 )  ! vertically integrated heat content (J/m2)
+  
+         ENDIF
+         !
+         ! ----------------------------- !
+         !  Heat content of first 2000 m  !
+         ! ----------------------------- !
+         IF( iom_use ('hc2000') ) THEN  
+            zzdep = 2000.
+            CALL  dia_hth_htc( zzdep, tsn(:,:,:,jp_tem), htc20 )
+            CALL iom_put( 'hc2000', rau0_rcp * htc20 )  ! vertically integrated heat content (J/m2)  
+         ENDIF
+         !
+      ENDIF
+
+      !
+      IF( ln_timing )   CALL timing_stop('dia_hth')
+      !
+   END SUBROUTINE dia_hth
+
+   SUBROUTINE dia_hth_dep( ptem, pdept )
+      !
+      REAL(wp), INTENT(in) :: ptem
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(out) :: pdept     
+      !
+      INTEGER  :: ji, jj, jk, iid
+      REAL(wp) :: zztmp, zzdep
+      INTEGER, DIMENSION(jpi,jpj) :: iktem
+      
+      ! --------------------------------------- !
+      ! search deepest level above ptem         !
+      ! --------------------------------------- !
+      iktem(:,:) = 1
+      DO jk = 1, jpkm1   ! beware temperature is not always decreasing with depth => loop from top to bottom
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zztmp = tsn(ji,jj,jk,jp_tem)
+               IF( zztmp >= ptem )   iktem(ji,jj) = jk
+            END DO
+         END DO
+      END DO
+
+      ! ------------------------------- !
+      !  Depth of ptem isotherm         !
+      ! ------------------------------- !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zzdep = gdepw_n(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean bottom
+            !
+            iid = iktem(ji,jj)
+            IF( iid /= 1 ) THEN 
+                zztmp =     gdept_n(ji,jj,iid  )   &                     ! linear interpolation
+                  &  + (    gdept_n(ji,jj,iid+1) - gdept_n(ji,jj,iid)                       )   &
+                  &  * ( 20.*tmask(ji,jj,iid+1) - tsn(ji,jj,iid,jp_tem)                       )   &
+                  &  / ( tsn(ji,jj,iid+1,jp_tem) - tsn(ji,jj,iid,jp_tem) + (1.-tmask(ji,jj,1)) )
+               pdept(ji,jj) = MIN( zztmp , zzdep) * tmask(ji,jj,1)       ! bound by the ocean depth
+            ELSE 
+               pdept(ji,jj) = 0._wp
+            ENDIF
+         END DO
+      END DO
+      !
+   END SUBROUTINE dia_hth_dep
+
+
+   SUBROUTINE dia_hth_htc( pdep, ptn, phtc )
+      !
+      REAL(wp), INTENT(in) :: pdep     ! depth over the heat content
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in) :: ptn   
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: phtc  
+      !
+      INTEGER  :: ji, jj, jk, ik
+      REAL(wp), DIMENSION(jpi,jpj) :: zthick
+      INTEGER , DIMENSION(jpi,jpj) :: ilevel
+
+
+      ! surface boundary condition
+      
+      IF( .NOT. ln_linssh ) THEN   ;   zthick(:,:) = 0._wp       ;   phtc(:,:) = 0._wp                                   
+      ELSE                         ;   zthick(:,:) = sshn(:,:)   ;   phtc(:,:) = ptn(:,:,1) * sshn(:,:) * tmask(:,:,1)   
+      ENDIF
+      !
+      ilevel(:,:) = 1
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( ( gdept_n(ji,jj,jk) < pdep ) .AND. ( tmask(ji,jj,jk) == 1 ) ) THEN
+                   ilevel(ji,jj) = jk
+                   zthick(ji,jj) = zthick(ji,jj) + e3t_n(ji,jj,jk)
+                   phtc  (ji,jj) = phtc  (ji,jj) + e3t_n(ji,jj,jk) * ptn(ji,jj,jk)
+               ENDIF
+            ENDDO
+         ENDDO
+      ENDDO
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ik = ilevel(ji,jj)
+            zthick(ji,jj) = pdep - zthick(ji,jj)   !   remaining thickness to reach depht pdep
+            phtc(ji,jj)   = phtc(ji,jj) + ptn(ji,jj,ik+1) * MIN( e3t_n(ji,jj,ik+1), zthick(ji,jj) ) &
+                                                          * tmask(ji,jj,ik+1)
+         END DO
+      ENDDO
+      !
+      !
+   END SUBROUTINE dia_hth_htc
+
+   !!======================================================================
+END MODULE diahth
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dianam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dianam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/dianam.F90	(revision 14097)
@@ -0,0 +1,136 @@
+MODULE dianam
+   !!======================================================================
+   !!                       ***  MODULE  dianam  ***
+   !! Ocean diagnostics:  Builds output file name
+   !!=====================================================================
+   !! History :  OPA  ! 1999-02  (E. Guilyardi)  Creation for 30 days/month
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  ! 2009-11  (S. Masson) complete rewriting, works for all calendars...
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_nam       : Builds output file name
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE in_out_manager  ! I/O manager
+   USE ioipsl, ONLY :  ju2ymds    ! for calendar
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dia_nam
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE dia_nam( cdfnam, kfreq, cdsuff, ldfsec )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_nam  ***
+      !!                   
+      !! ** Purpose :   Builds output file name
+      !!
+      !! ** Method  :   File name is a function of date and output frequency
+      !!      cdfnam=<cexper>_<clave>_<idtbeg>_<idtend>_<cdsuff>
+      !!      <clave> = averaging frequency (DA, MO, etc...)
+      !!      <idtbeg>,<idtend> date of beginning and end of run
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER (len=*), INTENT(  out)           ::   cdfnam   ! file name
+      CHARACTER (len=*), INTENT(in   )           ::   cdsuff   ! to be added at the end of the file name
+      INTEGER          , INTENT(in   )           ::   kfreq    ! output frequency: > 0 in time-step (or seconds see ldfsec)
+      !                                                                            < 0 in months
+      !                                                                            = 0 no frequency
+      LOGICAL          , INTENT(in   ), OPTIONAL ::   ldfsec   ! kfreq in second(in time-step) if .true.(.false. default)
+      !
+      CHARACTER (len=20) ::   clfmt, clfmt0                    ! writing format
+      CHARACTER (len=20) ::   clave                            ! name for output frequency
+      CHARACTER (len=20) ::   cldate1                          ! date of the beginning of run
+      CHARACTER (len=20) ::   cldate2                          ! date of the end       of run
+      LOGICAL            ::   llfsec                           ! local value of ldfsec
+      INTEGER            ::   iyear1, imonth1, iday1           ! year, month, day of the first day of the run
+      INTEGER            ::   iyear2, imonth2, iday2           ! year, month, day of the last  day of the run
+      INTEGER            ::   indg                             ! number of digits needed to write a number     
+      INTEGER            ::   inbsec, inbmn, inbhr             ! output frequency in seconds, minutes and hours
+      INTEGER            ::   inbday, inbmo, inbyr             ! output frequency in days, months and years
+      INTEGER            ::   iyyss, iddss, ihhss, immss       ! number of seconds in 1 year, 1 day, 1 hour and 1 minute
+      INTEGER            ::   iyymo                            ! number of months in 1 year
+      REAL(wp)           ::   zsec1, zsec2                     ! not used
+      REAL(wp)           ::   zdrun, zjul                      ! temporary scalars
+      !!----------------------------------------------------------------------
+
+      ! name for output frequency
+
+      IF( PRESENT(ldfsec) ) THEN   ;   llfsec = ldfsec
+      ELSE                         ;   llfsec = .FALSE.
+      ENDIF
+
+      IF( llfsec .OR. kfreq < 0 ) THEN   ;   inbsec = kfreq                       ! output frequency already in seconds
+      ELSE                               ;   inbsec = kfreq * NINT( rdt )   ! from time-step to seconds
+      ENDIF
+      iddss = NINT( rday          )                                         ! number of seconds in 1 day
+      ihhss = NINT( rmmss * rhhmm )                                         ! number of seconds in 1 hour
+      immss = NINT( rmmss         )                                         ! number of seconds in 1 minute
+      iyymo = NINT( raamo         )                                         ! number of months  in 1 year
+      iyyss = iddss * nyear_len(1)                                          ! seconds in 1 year (not good: multi years with leap)
+      clfmt0 = "('(a,i',i1,',a)')"                                          ! format '(a,ix,a)' with x to be defined
+      ! 
+      IF(          inbsec == 0           ) THEN   ;   clave = ''            ! no frequency
+      ELSEIF(      inbsec <  0           ) THEN        
+         inbmo = -inbsec                                                    ! frequency in month
+         IF( MOD( inbmo, iyymo  ) == 0 ) THEN                               ! frequency in years
+            inbyr  = inbmo / iyymo
+            indg   = INT(LOG10(REAL(inbyr,wp))) + 1                         ! number of digits needed to write years   frequency
+            WRITE(clfmt, clfmt0) indg             ;   WRITE(clave, clfmt) '_', inbyr , 'y'
+         ELSE                                                               ! frequency in month
+            indg   = INT(LOG10(REAL(inbmo,wp))) + 1                         ! number of digits needed to write months  frequency
+            WRITE(clfmt, clfmt0) indg             ;   WRITE(clave, clfmt) '_', inbmo, 'm'
+         ENDIF
+      ELSEIF( MOD( inbsec, iyyss  ) == 0 ) THEN                             ! frequency in years
+         inbyr  = inbsec / iyyss
+         indg   = INT(LOG10(REAL(inbyr ,wp))) + 1                           ! number of digits needed to write years   frequency
+         WRITE(clfmt, clfmt0) indg                ;   WRITE(clave, clfmt) '_', inbyr , 'y'
+      ELSEIF( MOD( inbsec, iddss  ) == 0 ) THEN                             ! frequency in days
+         inbday = inbsec / iddss
+         indg   = INT(LOG10(REAL(inbday,wp))) + 1                           ! number of digits needed to write days    frequency
+         WRITE(clfmt, clfmt0) indg                ;   WRITE(clave, clfmt) '_', inbday, 'd'
+         IF( inbday == nmonth_len(nmonth) )           clave = '_1m'
+      ELSEIF( MOD( inbsec, ihhss ) == 0 ) THEN                              ! frequency in hours
+         inbhr  = inbsec / ihhss
+         indg   = INT(LOG10(REAL(inbhr ,wp))) + 1                           ! number of digits needed to write hours   frequency
+         WRITE(clfmt, clfmt0) indg                ;   WRITE(clave, clfmt) '_', inbhr , 'h'
+      ELSEIF( MOD( inbsec, immss ) == 0 ) THEN                              ! frequency in minutes
+         inbmn  = inbsec / immss
+         indg   = INT(LOG10(REAL(inbmn ,wp))) + 1                           ! number of digits needed to write minutes frequency
+         WRITE(clfmt, clfmt0) indg                ;   WRITE(clave, clfmt) '_', inbmn , 'mn'
+      ELSE                                                                  ! frequency in seconds
+         indg   = INT(LOG10(REAL(inbsec,wp))) + 1                           ! number of digits needed to write seconds frequency
+         WRITE(clfmt, clfmt0) indg                ;   WRITE(clave, clfmt) '_', inbsec, 's'
+      ENDIF
+
+      ! date of the beginning and the end of the run
+
+      zdrun = rdt / rday * REAL( nitend - nit000, wp )                ! length of the run in days
+      zjul  = fjulday - rdt / rday
+      CALL ju2ymds( zjul        , iyear1, imonth1, iday1, zsec1 )           ! year/month/day of the beginning of run
+      CALL ju2ymds( zjul + zdrun, iyear2, imonth2, iday2, zsec2 )           ! year/month/day of the end       of run
+
+      IF( iyear2 < 10000 ) THEN   ;   clfmt = "(i4.4,2i2.2)"                ! format used to write the date 
+      ELSE                        ;   WRITE(clfmt, "('(i',i1,',2i2.2)')") INT(LOG10(REAL(iyear2,wp))) + 1
+      ENDIF
+
+      WRITE(cldate1, clfmt) iyear1, imonth1, iday1                          ! date of the beginning of run
+      WRITE(cldate2, clfmt) iyear2, imonth2, iday2                          ! date of the end       of run
+ 
+      cdfnam = TRIM(cexper)//TRIM(clave)//"_"//TRIM(cldate1)//"_"//TRIM(cldate2)//"_"//TRIM(cdsuff)
+      IF( .NOT. Agrif_Root() ) cdfnam = TRIM(Agrif_CFixed())//'_'//TRIM(cdfnam)
+
+   END SUBROUTINE dia_nam
+
+   !!======================================================================
+END MODULE dianam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaptr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaptr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diaptr.F90	(revision 14097)
@@ -0,0 +1,640 @@
+MODULE diaptr
+   !!======================================================================
+   !!                       ***  MODULE  diaptr  ***
+   !! Ocean physics:  Computes meridonal transports and zonal means
+   !!=====================================================================
+   !! History :  1.0  ! 2003-09  (C. Talandier, G. Madec)  Original code
+   !!            2.0  ! 2006-01  (A. Biastoch)  Allow sub-basins computation
+   !!            3.2  ! 2010-03  (O. Marti, S. Flavoni) Add fields
+   !!            3.3  ! 2010-10  (G. Madec)  dynamical allocation
+   !!            3.6  ! 2014-12  (C. Ethe) use of IOM
+   !!            3.6  ! 2016-06  (T. Graham) Addition of diagnostics for CMIP6
+   !!            4.0  ! 2010-08  ( C. Ethe, J. Deshayes ) Improvment
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_ptr      : Poleward Transport Diagnostics module
+   !!   dia_ptr_init : Initialization, namelist read
+   !!   ptr_sjk      : "zonal" mean computation of a field - tracer or flux array
+   !!   ptr_sj       : "zonal" and vertical sum computation of a "meridional" flux array
+   !!                   (Generic interface to ptr_sj_3d, ptr_sj_2d)
+   !!----------------------------------------------------------------------
+   USE oce              ! ocean dynamics and active tracers
+   USE dom_oce          ! ocean space and time domain
+   USE phycst           ! physical constants
+   !
+   USE iom              ! IOM library
+   USE in_out_manager   ! I/O manager
+   USE lib_mpp          ! MPP library
+   USE timing           ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE ptr_sj
+      MODULE PROCEDURE ptr_sj_3d, ptr_sj_2d
+   END INTERFACE
+
+   PUBLIC   ptr_sj         ! call by tra_ldf & tra_adv routines
+   PUBLIC   ptr_sjk        ! 
+   PUBLIC   dia_ptr_init   ! call in memogcm
+   PUBLIC   dia_ptr        ! call in step module
+   PUBLIC   dia_ptr_hst    ! called from tra_ldf/tra_adv routines
+
+   !                                  !!** namelist  namptr  **
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hstr_adv, hstr_ldf, hstr_eiv   !: Heat/Salt TRansports(adv, diff, Bolus.)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hstr_ove, hstr_btr, hstr_vtr   !: heat Salt TRansports(overturn, baro, merional)
+
+   LOGICAL, PUBLIC ::   ln_diaptr   !  Poleward transport flag (T) or not (F)
+   LOGICAL, PUBLIC ::   ln_subbas   !  Atlantic/Pacific/Indian basins calculation
+   INTEGER, PARAMETER, PUBLIC ::   nptr = 5  ! (glo, atl, pac, ind, ipc)
+
+   REAL(wp) ::   rc_sv    = 1.e-6_wp   ! conversion from m3/s to Sverdrup
+   REAL(wp) ::   rc_pwatt = 1.e-15_wp  ! conversion from W    to PW (further x rau0 x Cp)
+   REAL(wp) ::   rc_ggram = 1.e-9_wp   ! conversion from g    to Gg  (further x rau0)
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: btmsk   ! T-point basin interior masks
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: btmsk34 ! mask out Southern Ocean (=0 south of 34°S)
+
+   REAL(wp), TARGET, ALLOCATABLE, SAVE, DIMENSION(:)   :: p_fval1d
+   REAL(wp), TARGET, ALLOCATABLE, SAVE, DIMENSION(:,:) :: p_fval2d
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_ptr( pvtr )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_ptr  ***
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::   pvtr   ! j-effective transport
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   zsfc,zvfc               ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj)     ::  z2d   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zmask   ! 3D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  z3d    ! 3D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) ::  zts   ! 3D workspace
+      REAL(wp), DIMENSION(jpj)      ::  zvsum, ztsum, zssum   ! 1D workspace
+      !
+      !overturning calculation
+      REAL(wp), DIMENSION(jpj,jpk,nptr) :: sjk, r1_sjk, v_msf  ! i-mean i-k-surface and its inverse
+      REAL(wp), DIMENSION(jpj,jpk,nptr) :: zt_jk, zs_jk ! i-mean T and S, j-Stream-Function
+
+      REAL(wp), DIMENSION(jpi,jpj,jpk,nptr)  :: z4d1, z4d2
+      REAL(wp), DIMENSION(jpi,jpj,nptr)      :: z3dtr ! i-mean T and S, j-Stream-Function
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dia_ptr')
+      !
+      IF( PRESENT( pvtr ) ) THEN
+         IF( iom_use( 'zomsf' ) ) THEN    ! effective MSF
+            DO jn = 1, nptr                                    ! by sub-basins
+               z4d1(1,:,:,jn) =  ptr_sjk( pvtr(:,:,:), btmsk34(:,:,jn) )  ! zonal cumulative effective transport excluding closed seas
+               DO jk = jpkm1, 1, -1 
+                  z4d1(1,:,jk,jn) = z4d1(1,:,jk+1,jn) - z4d1(1,:,jk,jn)    ! effective j-Stream-Function (MSF)
+               END DO
+               DO ji = 1, jpi
+                  z4d1(ji,:,:,jn) = z4d1(1,:,:,jn)
+               ENDDO
+            END DO
+            CALL iom_put( 'zomsf', z4d1 * rc_sv )
+         ENDIF
+         IF(  iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) .OR.   &
+            & iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) ) THEN
+            ! define fields multiplied by scalar
+            zmask(:,:,:) = 0._wp
+            zts(:,:,:,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpi
+                     zvfc = e1v(ji,jj) * e3v_n(ji,jj,jk)
+                     zmask(ji,jj,jk)      = vmask(ji,jj,jk)      * zvfc
+                     zts(ji,jj,jk,jp_tem) = (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) * 0.5 * zvfc  !Tracers averaged onto V grid
+                     zts(ji,jj,jk,jp_sal) = (tsn(ji,jj,jk,jp_sal)+tsn(ji,jj+1,jk,jp_sal)) * 0.5 * zvfc
+                  ENDDO
+               ENDDO
+             ENDDO
+         ENDIF
+         IF( iom_use( 'sopstove' ) .OR. iom_use( 'sophtove' ) ) THEN
+            DO jn = 1, nptr
+               sjk(:,:,jn) = ptr_sjk( zmask(:,:,:), btmsk(:,:,jn) )
+               r1_sjk(:,:,jn) = 0._wp
+               WHERE( sjk(:,:,jn) /= 0._wp )   r1_sjk(:,:,jn) = 1._wp / sjk(:,:,jn)
+               ! i-mean T and S, j-Stream-Function, basin
+               zt_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
+               zs_jk(:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) ) * r1_sjk(:,:,jn)
+               v_msf(:,:,jn) = ptr_sjk( pvtr(:,:,:), btmsk34(:,:,jn) ) 
+               hstr_ove(:,jp_tem,jn) = SUM( v_msf(:,:,jn)*zt_jk(:,:,jn), 2 )
+               hstr_ove(:,jp_sal,jn) = SUM( v_msf(:,:,jn)*zs_jk(:,:,jn), 2 )
+               !
+            ENDDO
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_ove(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtove', z3dtr )
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_ove(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstove', z3dtr )
+         ENDIF
+
+         IF( iom_use( 'sopstbtr' ) .OR. iom_use( 'sophtbtr' ) ) THEN
+            ! Calculate barotropic heat and salt transport here 
+            DO jn = 1, nptr
+               sjk(:,1,jn) = ptr_sj( zmask(:,:,:), btmsk(:,:,jn) )
+               r1_sjk(:,1,jn) = 0._wp
+               WHERE( sjk(:,1,jn) /= 0._wp )   r1_sjk(:,1,jn) = 1._wp / sjk(:,1,jn)
+               !
+               zvsum(:) = ptr_sj( pvtr(:,:,:), btmsk34(:,:,jn) )
+               ztsum(:) = ptr_sj( zts(:,:,:,jp_tem), btmsk(:,:,jn) )
+               zssum(:) = ptr_sj( zts(:,:,:,jp_sal), btmsk(:,:,jn) )
+               hstr_btr(:,jp_tem,jn) = zvsum(:) * ztsum(:) * r1_sjk(:,1,jn)
+               hstr_btr(:,jp_sal,jn) = zvsum(:) * zssum(:) * r1_sjk(:,1,jn)
+               !
+            ENDDO
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_btr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtbtr', z3dtr )
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_btr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstbtr', z3dtr )
+         ENDIF 
+         !
+      ELSE
+         !
+         zmask(:,:,:) = 0._wp
+         zts(:,:,:,:) = 0._wp
+         IF( iom_use( 'zotem' ) .OR. iom_use( 'zosal' ) .OR. iom_use( 'zosrf' )  ) THEN    ! i-mean i-k-surface 
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zsfc = e1t(ji,jj) * e3t_n(ji,jj,jk)
+                     zmask(ji,jj,jk)      = tmask(ji,jj,jk)      * zsfc
+                     zts(ji,jj,jk,jp_tem) = tsn(ji,jj,jk,jp_tem) * zsfc
+                     zts(ji,jj,jk,jp_sal) = tsn(ji,jj,jk,jp_sal) * zsfc
+                  END DO
+               END DO
+            END DO
+            !
+            DO jn = 1, nptr
+               zmask(1,:,:) = ptr_sjk( zmask(:,:,:), btmsk(:,:,jn) )
+               z4d1(:,:,:,jn) = zmask(:,:,:)
+            ENDDO
+            CALL iom_put( 'zosrf', z4d1 )
+            !
+            DO jn = 1, nptr
+               z4d2(1,:,:,jn) = ptr_sjk( zts(:,:,:,jp_tem), btmsk(:,:,jn) ) &
+                  &            / MAX( z4d1(1,:,:,jn), 10.e-15 )
+               DO ji = 1, jpi
+                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'zotem', z4d2 )
+            !
+            DO jn = 1, nptr
+               z4d2(1,:,:,jn) = ptr_sjk( zts(:,:,:,jp_sal), btmsk(:,:,jn) ) &
+                  &            / MAX( z4d1(1,:,:,jn), 10.e-15 )
+               DO ji = 1, jpi
+                  z4d2(ji,:,:,jn) = z4d2(1,:,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'zosal', z4d2 )
+            !
+         ENDIF
+         !
+         !                                ! Advective and diffusive heat and salt transport
+         IF( iom_use( 'sophtadv' ) .OR. iom_use( 'sopstadv' ) ) THEN  
+            ! 
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_adv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtadv', z3dtr )
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_adv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstadv', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sophtldf' ) .OR. iom_use( 'sopstldf' ) ) THEN  
+            ! 
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_ldf(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophtldf', z3dtr )
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_ldf(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstldf', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sophteiv' ) .OR. iom_use( 'sopsteiv' ) ) THEN  
+            ! 
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_eiv(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sophteiv', z3dtr )
+            DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_eiv(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopsteiv', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'sopstvtr' ) .OR. iom_use( 'sophtvtr' ) ) THEN
+            zts(:,:,:,:) = 0._wp
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpi
+                     zvfc = e1v(ji,jj) * e3v_n(ji,jj,jk)
+                     zts(ji,jj,jk,jp_tem) = (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) * 0.5 * zvfc  !Tracers averaged onto V grid
+                     zts(ji,jj,jk,jp_sal) = (tsn(ji,jj,jk,jp_sal)+tsn(ji,jj+1,jk,jp_sal)) * 0.5 * zvfc
+                  ENDDO
+               ENDDO
+             ENDDO
+             CALL dia_ptr_hst( jp_tem, 'vtr', zts(:,:,:,jp_tem) )
+             CALL dia_ptr_hst( jp_sal, 'vtr', zts(:,:,:,jp_sal) )
+             DO jn = 1, nptr
+                z3dtr(1,:,jn) = hstr_vtr(:,jp_tem,jn) * rc_pwatt  !  (conversion in PW)
+                DO ji = 1, jpi
+                   z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+                ENDDO
+             ENDDO
+             CALL iom_put( 'sophtvtr', z3dtr )
+             DO jn = 1, nptr
+               z3dtr(1,:,jn) = hstr_vtr(:,jp_sal,jn) * rc_ggram !  (conversion in Gg)
+               DO ji = 1, jpi
+                  z3dtr(ji,:,jn) = z3dtr(1,:,jn)
+               ENDDO
+            ENDDO
+            CALL iom_put( 'sopstvtr', z3dtr )
+         ENDIF
+         !
+         IF( iom_use( 'uocetr_vsum_cumul' ) ) THEN
+            CALL iom_get_var(  'uocetr_vsum_op', z2d ) ! get uocetr_vsum_op from xml
+            z2d(:,:) = ptr_ci_2d( z2d(:,:) )  
+            CALL iom_put( 'uocetr_vsum_cumul', z2d )
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_ptr')
+      !
+   END SUBROUTINE dia_ptr
+
+
+   SUBROUTINE dia_ptr_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_ptr_init  ***
+      !!                   
+      !! ** Purpose :   Initialization, namelist read
+      !!----------------------------------------------------------------------
+      INTEGER ::  inum, jn, ios, ierr           ! local integers
+      !!
+      NAMELIST/namptr/ ln_diaptr, ln_subbas
+      REAL(wp), DIMENSION(jpi,jpj) :: zmsk
+      !!----------------------------------------------------------------------
+
+
+      REWIND( numnam_ref )              ! Namelist namptr in reference namelist : Poleward transport
+      READ  ( numnam_ref, namptr, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namptr in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namptr in configuration namelist : Poleward transport
+      READ  ( numnam_cfg, namptr, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namptr in configuration namelist' )
+      IF(lwm) WRITE ( numond, namptr )
+
+      IF(lwp) THEN                     ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_ptr_init : poleward transport and msf initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namptr : set ptr parameters'
+         WRITE(numout,*) '      Poleward heat & salt transport (T) or not (F)      ln_diaptr  = ', ln_diaptr
+      ENDIF
+
+      IF( ln_diaptr ) THEN  
+         !
+         IF( dia_ptr_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dia_ptr_init : unable to allocate arrays' )
+
+         rc_pwatt = rc_pwatt * rau0_rcp          ! conversion from K.s-1 to PetaWatt
+         rc_ggram = rc_ggram * rau0              ! conversion from m3/s to Gg/s
+
+         IF( lk_mpp )   CALL mpp_ini_znl( numout )     ! Define MPI communicator for zonal sum
+
+         btmsk(:,:,1) = tmask_i(:,:)                 
+         CALL iom_open( 'subbasins', inum,  ldstop = .FALSE.  )
+         CALL iom_get( inum, jpdom_data, 'atlmsk', btmsk(:,:,2) )   ! Atlantic basin
+         CALL iom_get( inum, jpdom_data, 'pacmsk', btmsk(:,:,3) )   ! Pacific  basin
+         CALL iom_get( inum, jpdom_data, 'indmsk', btmsk(:,:,4) )   ! Indian   basin
+         CALL iom_close( inum )
+         btmsk(:,:,5) = MAX ( btmsk(:,:,3), btmsk(:,:,4) )          ! Indo-Pacific basin
+         DO jn = 2, nptr
+            btmsk(:,:,jn) = btmsk(:,:,jn) * tmask_i(:,:)               ! interior domain only
+         END DO
+         ! JD : modification so that overturning streamfunction is available in Atlantic at 34S to compare with observations
+         WHERE( gphit(:,:)*tmask_i(:,:) < -34._wp)
+           zmsk(:,:) = 0._wp      ! mask out Southern Ocean
+         ELSE WHERE                  
+           zmsk(:,:) = ssmask(:,:)
+         END WHERE
+         btmsk34(:,:,1) = btmsk(:,:,1)                 
+         DO jn = 2, nptr
+            btmsk34(:,:,jn) = btmsk(:,:,jn) * zmsk(:,:)               ! interior domain only
+         ENDDO
+
+         ! Initialise arrays to zero because diatpr is called before they are first calculated
+         ! Note that this means diagnostics will not be exactly correct when model run is restarted.
+         hstr_adv(:,:,:) = 0._wp           
+         hstr_ldf(:,:,:) = 0._wp           
+         hstr_eiv(:,:,:) = 0._wp           
+         hstr_ove(:,:,:) = 0._wp           
+         hstr_btr(:,:,:) = 0._wp           !
+         hstr_vtr(:,:,:) = 0._wp           !
+         !
+      ENDIF 
+      ! 
+   END SUBROUTINE dia_ptr_init
+
+
+   SUBROUTINE dia_ptr_hst( ktra, cptr, pva ) 
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ptr_hst ***
+      !!----------------------------------------------------------------------
+      !! Wrapper for heat and salt transport calculations to calculate them for each basin
+      !! Called from all advection and/or diffusion routines
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in )  :: ktra  ! tracer index
+      CHARACTER(len=3)                , INTENT(in)   :: cptr  ! transport type  'adv'/'ldf'/'eiv'
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)   :: pva   ! 3D input array of advection/diffusion
+      INTEGER                                        :: jn    !
+
+      !
+      IF( cptr == 'adv' ) THEN
+         IF( ktra == jp_tem )  THEN
+             DO jn = 1, nptr
+                hstr_adv(:,jp_tem,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+         IF( ktra == jp_sal )  THEN
+             DO jn = 1, nptr
+                hstr_adv(:,jp_sal,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+      ENDIF
+      !
+      IF( cptr == 'ldf' ) THEN
+         IF( ktra == jp_tem )  THEN
+             DO jn = 1, nptr
+                hstr_ldf(:,jp_tem,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+         IF( ktra == jp_sal )  THEN
+             DO jn = 1, nptr
+                hstr_ldf(:,jp_sal,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+      ENDIF
+      !
+      IF( cptr == 'eiv' ) THEN
+         IF( ktra == jp_tem )  THEN
+             DO jn = 1, nptr
+                hstr_eiv(:,jp_tem,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+         IF( ktra == jp_sal )  THEN
+             DO jn = 1, nptr
+                hstr_eiv(:,jp_sal,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+      ENDIF
+      !
+      IF( cptr == 'vtr' ) THEN
+         IF( ktra == jp_tem )  THEN
+             DO jn = 1, nptr
+                hstr_vtr(:,jp_tem,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+         IF( ktra == jp_sal )  THEN
+             DO jn = 1, nptr
+                hstr_vtr(:,jp_sal,jn) = ptr_sj( pva(:,:,:), btmsk(:,:,jn) )
+             ENDDO
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE dia_ptr_hst
+
+
+   FUNCTION dia_ptr_alloc()
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_ptr_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER               ::   dia_ptr_alloc   ! return value
+      INTEGER, DIMENSION(3) ::   ierr
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      IF( .NOT. ALLOCATED( btmsk ) ) THEN
+         ALLOCATE( btmsk(jpi,jpj,nptr)    , btmsk34(jpi,jpj,nptr),   &
+            &      hstr_adv(jpj,jpts,nptr), hstr_eiv(jpj,jpts,nptr), &
+            &      hstr_ove(jpj,jpts,nptr), hstr_btr(jpj,jpts,nptr), &
+            &      hstr_ldf(jpj,jpts,nptr), hstr_vtr(jpj,jpts,nptr), STAT=ierr(1)  )
+            !
+         ALLOCATE( p_fval1d(jpj), p_fval2d(jpj,jpk), Stat=ierr(2))
+         !
+         dia_ptr_alloc = MAXVAL( ierr )
+         CALL mpp_sum( 'diaptr', dia_ptr_alloc )
+      ENDIF
+      !
+   END FUNCTION dia_ptr_alloc
+
+
+   FUNCTION ptr_sj_3d( pva, pmsk )   RESULT ( p_fval )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_sj_3d  ***
+      !!
+      !! ** Purpose :   i-k sum computation of a j-flux array
+      !!
+      !! ** Method  : - i-k sum of pva using the interior 2D vmask (vmask_i).
+      !!              pva is supposed to be a masked flux (i.e. * vmask*e1v*e3v)
+      !!
+      !! ** Action  : - p_fval: i-k-mean poleward flux of pva
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in), DIMENSION(jpi,jpj,jpk)  ::   pva   ! mask flux array at V-point
+      REAL(wp), INTENT(in), DIMENSION(jpi,jpj)      ::   pmsk   ! Optional 2D basin mask
+      !
+      INTEGER                  ::   ji, jj, jk   ! dummy loop arguments
+      INTEGER                  ::   ijpj         ! ???
+      REAL(wp), POINTER, DIMENSION(:) :: p_fval  ! function value
+      !!--------------------------------------------------------------------
+      !
+      p_fval => p_fval1d
+
+      ijpj = jpj
+      p_fval(:) = 0._wp
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! Vector opt.
+               p_fval(jj) = p_fval(jj) + pva(ji,jj,jk) * pmsk(ji,jj) * tmask_i(ji,jj)
+            END DO
+         END DO
+      END DO
+#if defined key_mpp_mpi
+      CALL mpp_sum( 'diaptr', p_fval, ijpj, ncomm_znl)
+#endif
+      !
+   END FUNCTION ptr_sj_3d
+
+
+   FUNCTION ptr_sj_2d( pva, pmsk )   RESULT ( p_fval )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_sj_2d  ***
+      !!
+      !! ** Purpose :   "zonal" and vertical sum computation of a i-flux array
+      !!
+      !! ** Method  : - i-k sum of pva using the interior 2D vmask (vmask_i).
+      !!      pva is supposed to be a masked flux (i.e. * vmask*e1v*e3v)
+      !!
+      !! ** Action  : - p_fval: i-k-mean poleward flux of pva
+      !!----------------------------------------------------------------------
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj) ::   pva   ! mask flux array at V-point
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj) ::   pmsk   ! Optional 2D basin mask
+      !
+      INTEGER                  ::   ji,jj       ! dummy loop arguments
+      INTEGER                  ::   ijpj        ! ???
+      REAL(wp), POINTER, DIMENSION(:) :: p_fval ! function value
+      !!--------------------------------------------------------------------
+      ! 
+      p_fval => p_fval1d
+
+      ijpj = jpj
+      p_fval(:) = 0._wp
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! Vector opt.
+            p_fval(jj) = p_fval(jj) + pva(ji,jj) * pmsk(ji,jj) * tmask_i(ji,jj)
+         END DO
+      END DO
+#if defined key_mpp_mpi
+      CALL mpp_sum( 'diaptr', p_fval, ijpj, ncomm_znl )
+#endif
+      ! 
+   END FUNCTION ptr_sj_2d
+
+   FUNCTION ptr_ci_2d( pva )   RESULT ( p_fval )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_ci_2d  ***
+      !!
+      !! ** Purpose :   "meridional" cumulated sum computation of a j-flux array
+      !!
+      !! ** Method  : - j cumulated sum of pva using the interior 2D vmask (umask_i).
+      !!
+      !! ** Action  : - p_fval: j-cumulated sum of pva
+      !!----------------------------------------------------------------------
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj)  ::   pva   ! mask flux array at V-point
+      !
+      INTEGER                  ::   ji,jj,jc       ! dummy loop arguments
+      INTEGER                  ::   ijpj        ! ??? 
+      REAL(wp), DIMENSION(jpi,jpj) :: p_fval ! function value
+      !!--------------------------------------------------------------------
+      ! 
+      ijpj = jpj  ! ???
+      p_fval(:,:) = 0._wp
+      DO jc = 1, jpnj ! looping over all processors in j axis
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! Vector opt.
+               p_fval(ji,jj) = p_fval(ji,jj-1) + pva(ji,jj) * tmask_i(ji,jj)
+            END DO
+         END DO
+         CALL lbc_lnk( 'diaptr', p_fval, 'U', -1. )
+      END DO
+      ! 
+   END FUNCTION ptr_ci_2d
+
+
+
+   FUNCTION ptr_sjk( pta, pmsk )   RESULT ( p_fval )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ptr_sjk  ***
+      !!
+      !! ** Purpose :   i-sum computation of an array
+      !!
+      !! ** Method  : - i-sum of pva using the interior 2D vmask (vmask_i).
+      !!
+      !! ** Action  : - p_fval: i-mean poleward flux of pva
+      !!----------------------------------------------------------------------
+      !!
+      IMPLICIT none
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj,jpk) ::   pta    ! mask flux array at V-point
+      REAL(wp) , INTENT(in), DIMENSION(jpi,jpj)     ::   pmsk   ! Optional 2D basin mask
+      !!
+      INTEGER                           :: ji, jj, jk ! dummy loop arguments
+      REAL(wp), POINTER, DIMENSION(:,:) :: p_fval     ! return function value
+#if defined key_mpp_mpi
+      INTEGER, DIMENSION(1) ::   ish
+      INTEGER, DIMENSION(2) ::   ish2
+      INTEGER               ::   ijpjjpk
+      REAL(wp), DIMENSION(jpj*jpk) ::   zwork    ! mask flux array at V-point
+#endif
+      !!--------------------------------------------------------------------
+      !
+      p_fval => p_fval2d
+
+      p_fval(:,:) = 0._wp
+      !
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! Vector opt.
+               p_fval(jj,jk) = p_fval(jj,jk) + pta(ji,jj,jk) * pmsk(ji,jj) * tmask_i(ji,jj)
+            END DO
+         END DO
+      END DO
+      !
+#if defined key_mpp_mpi
+      ijpjjpk = jpj*jpk
+      ish(1) = ijpjjpk  ;   ish2(1) = jpj   ;   ish2(2) = jpk
+      zwork(1:ijpjjpk) = RESHAPE( p_fval, ish )
+      CALL mpp_sum( 'diaptr', zwork, ijpjjpk, ncomm_znl )
+      p_fval(:,:) = RESHAPE( zwork, ish2 )
+#endif
+      !
+   END FUNCTION ptr_sjk
+
+
+   !!======================================================================
+END MODULE diaptr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diawri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diawri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIA/diawri.F90	(revision 14097)
@@ -0,0 +1,944 @@
+MODULE diawri
+   !!======================================================================
+   !!                     ***  MODULE  diawri  ***
+   !! Ocean diagnostics :  write ocean output files
+   !!=====================================================================
+   !! History :  OPA  ! 1991-03  (M.-A. Foujols)  Original code
+   !!            4.0  ! 1991-11  (G. Madec)
+   !!                 ! 1992-06  (M. Imbard)  correction restart file
+   !!                 ! 1992-07  (M. Imbard)  split into diawri and rstwri
+   !!                 ! 1993-03  (M. Imbard)  suppress writibm
+   !!                 ! 1998-01  (C. Levy)  NETCDF format using ioipsl INTERFACE
+   !!                 ! 1999-02  (E. Guilyardi)  name of netCDF files + variables
+   !!            8.2  ! 2000-06  (M. Imbard)  Original code (diabort.F)
+   !!   NEMO     1.0  ! 2002-06  (A.Bozec, E. Durand)  Original code (diainit.F)
+   !!             -   ! 2002-09  (G. Madec)  F90: Free form and module
+   !!             -   ! 2002-12  (G. Madec)  merge of diabort and diainit, F90
+   !!                 ! 2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            3.2  ! 2008-11  (B. Lemaire) creation from old diawri
+   !!            3.7  ! 2014-01  (G. Madec) remove eddy induced velocity from no-IOM output
+   !!                 !                     change name of output variables in dia_wri_state
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_wri       : create the standart output files
+   !!   dia_wri_state : create an output NetCDF file for a single instantaeous ocean state and forcing fields
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE dianam         ! build name of file (routine)
+   USE diahth         ! thermocline diagnostics
+   USE dynadv   , ONLY: ln_dynadv_vec
+   USE icb_oce        ! Icebergs
+   USE icbdia         ! Iceberg budgets
+   USE ldftra         ! lateral physics: eddy diffusivity coef.
+   USE ldfdyn         ! lateral physics: eddy viscosity   coef.
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbc_ice        ! Surface boundary condition: ice fields
+   USE sbcssr         ! restoring term toward SST/SSS climatology
+   USE sbcwave        ! wave parameters
+   USE wet_dry        ! wetting and drying
+   USE zdf_oce        ! ocean vertical physics
+   USE zdfdrg         ! ocean vertical physics: top/bottom friction
+   USE zdfmxl         ! mixed layer
+   !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager ! I/O manager
+   USE dia25h         ! 25h Mean output
+   USE iom            ! 
+   USE ioipsl         ! 
+
+#if defined key_si3
+   USE ice 
+   USE icewri 
+#endif
+   USE lib_mpp         ! MPP library
+   USE timing          ! preformance summary
+   USE diurnal_bulk    ! diurnal warm layer
+   USE cool_skin       ! Cool skin
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_wri                 ! routines called by step.F90
+   PUBLIC   dia_wri_state
+   PUBLIC   dia_wri_alloc           ! Called by nemogcm module
+
+   INTEGER ::   nid_T, nz_T, nh_T, ndim_T, ndim_hT   ! grid_T file
+   INTEGER ::          nb_T              , ndim_bT   ! grid_T file
+   INTEGER ::   nid_U, nz_U, nh_U, ndim_U, ndim_hU   ! grid_U file
+   INTEGER ::   nid_V, nz_V, nh_V, ndim_V, ndim_hV   ! grid_V file
+   INTEGER ::   nid_W, nz_W, nh_W                    ! grid_W file
+   INTEGER ::   ndex(1)                              ! ???
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_hT, ndex_hU, ndex_hV
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_T, ndex_U, ndex_V
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_bT
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_iomput'                                        use IOM library
+   !!----------------------------------------------------------------------
+   INTEGER FUNCTION dia_wri_alloc()
+      !
+      dia_wri_alloc = 0
+      !
+   END FUNCTION dia_wri_alloc
+
+   
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!
+      !! ** Method  :  use iom_put
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!
+      INTEGER ::   ji, jj, jk       ! dummy loop indices
+      INTEGER ::   ikbot            ! local integer
+      REAL(wp)::   zztmp , zztmpx   ! local scalar
+      REAL(wp)::   zztmp2, zztmpy   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj)     ::   z2d   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   z3d   ! 3D workspace
+      !!----------------------------------------------------------------------
+      ! 
+      IF( ln_timing )   CALL timing_start('dia_wri')
+      ! 
+      ! Output the initial state and forcings
+      IF( ninist == 1 ) THEN                       
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+
+      ! Output of initial vertical scale factor
+      CALL iom_put("e3t_0", e3t_0(:,:,:) )
+      CALL iom_put("e3u_0", e3u_0(:,:,:) )
+      CALL iom_put("e3v_0", e3v_0(:,:,:) )
+      !
+      CALL iom_put( "e3t" , e3t_n(:,:,:) )
+      CALL iom_put( "e3u" , e3u_n(:,:,:) )
+      CALL iom_put( "e3v" , e3v_n(:,:,:) )
+      CALL iom_put( "e3w" , e3w_n(:,:,:) )
+      IF( iom_use("e3tdef") )   &
+         CALL iom_put( "e3tdef"  , ( ( e3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2 )
+
+      IF( ll_wd ) THEN
+         CALL iom_put( "ssh" , (sshn+ssh_ref)*tmask(:,:,1) )   ! sea surface height (brought back to the reference used for wetting and drying)
+      ELSE
+         CALL iom_put( "ssh" , sshn )              ! sea surface height
+      ENDIF
+
+      IF( iom_use("wetdep") )   &                  ! wet depth
+         CALL iom_put( "wetdep" , ht_0(:,:) + sshn(:,:) )
+      
+      CALL iom_put( "toce", tsn(:,:,:,jp_tem) )    ! 3D temperature
+      CALL iom_put(  "sst", tsn(:,:,1,jp_tem) )    ! surface temperature
+      IF ( iom_use("sbt") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkt(ji,jj)
+               z2d(ji,jj) = tsn(ji,jj,ikbot,jp_tem)
+            END DO
+         END DO
+         CALL iom_put( "sbt", z2d )                ! bottom temperature
+      ENDIF
+      
+      CALL iom_put( "soce", tsn(:,:,:,jp_sal) )    ! 3D salinity
+      CALL iom_put(  "sss", tsn(:,:,1,jp_sal) )    ! surface salinity
+      IF ( iom_use("sbs") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkt(ji,jj)
+               z2d(ji,jj) = tsn(ji,jj,ikbot,jp_sal)
+            END DO
+         END DO
+         CALL iom_put( "sbs", z2d )                ! bottom salinity
+      ENDIF
+
+      CALL iom_put( "rhop", rhop(:,:,:) )          ! 3D potential density (sigma0)
+
+      IF ( iom_use("taubot") ) THEN                ! bottom stress
+         zztmp = rau0 * 0.25
+         z2d(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zztmp2 = (  ( rCdU_bot(ji+1,jj)+rCdU_bot(ji  ,jj) ) * un(ji  ,jj,mbku(ji  ,jj))  )**2   &
+                  &   + (  ( rCdU_bot(ji  ,jj)+rCdU_bot(ji-1,jj) ) * un(ji-1,jj,mbku(ji-1,jj))  )**2   &
+                  &   + (  ( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj  ) ) * vn(ji,jj  ,mbkv(ji,jj  ))  )**2   &
+                  &   + (  ( rCdU_bot(ji,jj  )+rCdU_bot(ji,jj-1) ) * vn(ji,jj-1,mbkv(ji,jj-1))  )**2
+               z2d(ji,jj) = zztmp * SQRT( zztmp2 ) * tmask(ji,jj,1) 
+               !
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', 1. )
+         CALL iom_put( "taubot", z2d )           
+      ENDIF
+         
+      CALL iom_put( "uoce", un(:,:,:) )            ! 3D i-current
+      CALL iom_put(  "ssu", un(:,:,1) )            ! surface i-current
+      IF ( iom_use("sbu") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbku(ji,jj)
+               z2d(ji,jj) = un(ji,jj,ikbot)
+            END DO
+         END DO
+         CALL iom_put( "sbu", z2d )                ! bottom i-current
+      ENDIF
+      
+      CALL iom_put( "voce", vn(:,:,:) )            ! 3D j-current
+      CALL iom_put(  "ssv", vn(:,:,1) )            ! surface j-current
+      IF ( iom_use("sbv") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkv(ji,jj)
+               z2d(ji,jj) = vn(ji,jj,ikbot)
+            END DO
+         END DO
+         CALL iom_put( "sbv", z2d )                ! bottom j-current
+      ENDIF
+
+      IF( ln_zad_Aimp ) wn = wn + wi               ! Recombine explicit and implicit parts of vertical velocity for diagnostic output
+      !
+      CALL iom_put( "woce", wn )                   ! vertical velocity
+      IF( iom_use('w_masstr') .OR. iom_use('w_masstr2') ) THEN   ! vertical mass transport & its square value
+         ! Caution: in the VVL case, it only correponds to the baroclinic mass transport.
+         z2d(:,:) = rau0 * e1e2t(:,:)
+         DO jk = 1, jpk
+            z3d(:,:,jk) = wn(:,:,jk) * z2d(:,:)
+         END DO
+         CALL iom_put( "w_masstr" , z3d )  
+         IF( iom_use('w_masstr2') )   CALL iom_put( "w_masstr2", z3d(:,:,:) * z3d(:,:,:) )
+      ENDIF
+      !
+      IF( ln_zad_Aimp ) wn = wn - wi               ! Remove implicit part of vertical velocity that was added for diagnostic output
+
+      CALL iom_put( "avt" , avt )                  ! T vert. eddy diff. coef.
+      CALL iom_put( "avs" , avs )                  ! S vert. eddy diff. coef.
+      CALL iom_put( "avm" , avm )                  ! T vert. eddy visc. coef.
+
+      IF( iom_use('logavt') )   CALL iom_put( "logavt", LOG( MAX( 1.e-20_wp, avt(:,:,:) ) ) )
+      IF( iom_use('logavs') )   CALL iom_put( "logavs", LOG( MAX( 1.e-20_wp, avs(:,:,:) ) ) )
+
+      IF ( iom_use("sstgrad") .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 ) * r1_e1u(ji,jj) + ( zztmp - tsn(ji-1,jj  ,1,jp_tem) ) * r1_e1u(ji-1,jj)
+               zztmpy = ( tsn(ji,jj+1,1,jp_tem) - zztmp ) * r1_e2v(ji,jj) + ( zztmp - tsn(ji  ,jj-1,1,jp_tem) ) * r1_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( 'diawri', z2d, 'T', 1. )
+         CALL iom_put( "sstgrad2",  z2d )          ! square of module of sst gradient
+         z2d(:,:) = SQRT( z2d(:,:) )
+         CALL iom_put( "sstgrad" ,  z2d )          ! module of sst gradient
+      ENDIF
+         
+      ! heat and salt contents
+      IF( iom_use("heatc") ) THEN
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         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 = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "saltc", rau0 * z2d )          ! vertically integrated salt content (PSU*kg/m2)
+      ENDIF
+      !
+      IF ( iom_use("eken") ) THEN
+         z3d(:,:,jpk) = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zztmp  = 0.25_wp * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  z3d(ji,jj,jk) = zztmp * (  un(ji-1,jj,jk)**2 * e2u(ji-1,jj) * e3u_n(ji-1,jj,jk)   &
+                     &                     + un(ji  ,jj,jk)**2 * e2u(ji  ,jj) * e3u_n(ji  ,jj,jk)   &
+                     &                     + vn(ji,jj-1,jk)**2 * e1v(ji,jj-1) * e3v_n(ji,jj-1,jk)   &
+                     &                     + vn(ji,jj  ,jk)**2 * e1v(ji,jj  ) * e3v_n(ji,jj  ,jk)   )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z3d, 'T', 1. )
+         CALL iom_put( "eken", z3d )                 ! kinetic energy
+      ENDIF
+      !
+      CALL iom_put( "hdiv", hdivn )                  ! Horizontal divergence
+      !
+      IF( iom_use("u_masstr") .OR. iom_use("u_masstr_vint") .OR. iom_use("u_heattr") .OR. iom_use("u_salttr") ) THEN
+         z3d(:,:,jpk) = 0.e0
+         z2d(:,:) = 0.e0
+         DO jk = 1, jpkm1
+            z3d(:,:,jk) = rau0 * un(:,:,jk) * e2u(:,:) * e3u_n(:,:,jk) * umask(:,:,jk)
+            z2d(:,:) = z2d(:,:) + z3d(:,:,jk)
+         END DO
+         CALL iom_put( "u_masstr"     , z3d )         ! mass transport in i-direction
+         CALL iom_put( "u_masstr_vint", z2d )         ! mass transport in i-direction vertical sum
+      ENDIF
+      
+      IF( iom_use("u_heattr") ) 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) + 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( 'diawri', z2d, 'U', -1. )
+         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) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', 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(:,:) * e3v_n(:,:,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( 'diawri', z2d, 'V', -1. )
+         CALL iom_put( "v_heattr", 0.5*rcp * z2d )    !  heat transport in j-direction
+      ENDIF
+
+      IF( iom_use("v_salttr") ) 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) + 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( 'diawri', z2d, 'V', -1. )
+         CALL iom_put( "v_salttr", 0.5 * z2d )        !  heat transport in j-direction
+      ENDIF
+
+      IF( iom_use("tosmint") ) 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) + e3t_n(ji,jj,jk) *  tsn(ji,jj,jk,jp_tem)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', -1. )
+         CALL iom_put( "tosmint", rau0 * z2d )        ! Vertical integral of temperature
+      ENDIF
+      IF( iom_use("somint") ) 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) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_sal)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', -1. )
+         CALL iom_put( "somint", rau0 * z2d )         ! Vertical integral of salinity
+      ENDIF
+
+      CALL iom_put( "bn2", rn2 )                      ! Brunt-Vaisala buoyancy frequency (N^2)
+      !
+          
+      IF (ln_dia25h)   CALL dia_25h( kt )             ! 25h averaging
+
+      IF( ln_timing )   CALL timing_stop('dia_wri')
+      !
+   END SUBROUTINE dia_wri
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                  use IOIPSL  library
+   !!----------------------------------------------------------------------
+
+   INTEGER FUNCTION dia_wri_alloc()
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(2) :: ierr
+      !!----------------------------------------------------------------------
+      IF( nn_write == -1 ) THEN
+         dia_wri_alloc = 0
+      ELSE    
+         ierr = 0
+         ALLOCATE( ndex_hT(jpi*jpj) , ndex_T(jpi*jpj*jpk) ,     &
+            &      ndex_hU(jpi*jpj) , ndex_U(jpi*jpj*jpk) ,     &
+            &      ndex_hV(jpi*jpj) , ndex_V(jpi*jpj*jpk) , STAT=ierr(1) )
+         !
+         dia_wri_alloc = MAXVAL(ierr)
+         CALL mpp_sum( 'diawri', dia_wri_alloc )
+         !
+      ENDIF
+      !
+   END FUNCTION dia_wri_alloc
+
+   
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!
+      !! ** Method  :   At the beginning of the first time step (nit000), 
+      !!      define all the NETCDF files and fields
+      !!      At each time step call histdef to compute the mean if ncessary
+      !!      Each nn_write time step, output the instantaneous or mean fields
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      LOGICAL ::   ll_print = .FALSE.                        ! =T print and flush numout
+      CHARACTER (len=40) ::   clhstnam, clop, clmx           ! local names
+      INTEGER  ::   inum = 11                                ! temporary logical unit
+      INTEGER  ::   ji, jj, jk                               ! dummy loop indices
+      INTEGER  ::   ierr                                     ! error code return from allocation
+      INTEGER  ::   iimi, iima, ipk, it, itmod, ijmi, ijma   ! local integers
+      INTEGER  ::   jn, ierror                               ! local integers
+      REAL(wp) ::   zsto, zout, zmax, zjulian                ! local scalars
+      !
+      REAL(wp), DIMENSION(jpi,jpj)   :: zw2d       ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zw3d       ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ninist == 1 ) THEN     !==  Output the initial state and forcings  ==!
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+      !
+      IF( nn_write == -1 )   RETURN   ! we will never do any output
+      ! 
+      IF( ln_timing )   CALL timing_start('dia_wri')
+      !
+      ! 0. Initialisation
+      ! -----------------
+
+      ll_print = .FALSE.                  ! local variable for debugging
+      ll_print = ll_print .AND. lwp
+
+      ! Define frequency of output and means
+      clop = "x"         ! no use of the mask value (require less cpu time and otherwise the model crashes)
+#if defined key_diainstant
+      zsto = nn_write * rdt
+      clop = "inst("//TRIM(clop)//")"
+#else
+      zsto=rdt
+      clop = "ave("//TRIM(clop)//")"
+#endif
+      zout = nn_write * rdt
+      zmax = ( nitend - nit000 + 1 ) * rdt
+
+      ! Define indices of the horizontal output zoom and vertical limit storage
+      iimi = 1      ;      iima = jpi
+      ijmi = 1      ;      ijma = jpj
+      ipk = jpk
+
+      ! define time axis
+      it = kt
+      itmod = kt - nit000 + 1
+
+
+      ! 1. Define NETCDF files and fields at beginning of first time step
+      ! -----------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+
+         ! Define the NETCDF files (one per grid)
+
+         ! 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
+         IF(lwp)WRITE(numout,*) ' indexes of zoom = ', iimi, iima, ijmi, ijma,   &
+                                 ' limit storage in depth = ', ipk
+
+         ! WRITE root name in date.file for use by postpro
+         IF(lwp) THEN
+            CALL dia_nam( clhstnam, nn_write,' ' )
+            CALL ctl_opn( inum, 'date.file', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            WRITE(inum,*) clhstnam
+            CLOSE(inum)
+         ENDIF
+
+         ! Define the T grid FILE ( nid_T )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_T' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_T, nid_T, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_T, "deptht", "Vertical T levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_T, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, tmask, 1, 1., ndex_T , ndim_T  )      ! volume
+         CALL wheneq( jpi*jpj    , tmask, 1, 1., ndex_hT, ndim_hT )      ! surface
+         !
+         IF( ln_icebergs ) THEN
+            !
+            !! allocation cant go in dia_wri_alloc because ln_icebergs is only set after 
+            !! that routine is called from nemogcm, so do it here immediately before its needed
+            ALLOCATE( ndex_bT(jpi*jpj*nclasses), STAT=ierror )
+            CALL mpp_sum( 'diawri', ierror )
+            IF( ierror /= 0 ) THEN
+               CALL ctl_stop('dia_wri: failed to allocate iceberg diagnostic array')
+               RETURN
+            ENDIF
+            !
+            !! iceberg vertical coordinate is class number
+            CALL histvert( nid_T, "class", "Iceberg class",      &  ! Vertical grid: class
+               &           "number", nclasses, class_num, nb_T )
+            !
+            !! each class just needs the surface index pattern
+            ndim_bT = 3
+            DO jn = 1,nclasses
+               ndex_bT((jn-1)*jpi*jpj+1:jn*jpi*jpj) = ndex_hT(1:jpi*jpj)
+            ENDDO
+            !
+         ENDIF
+
+         ! Define the U grid FILE ( nid_U )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_U' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamu, jpj, gphiu,           &  ! Horizontal grid: glamu and gphiu
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_U, nid_U, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_U, "depthu", "Vertical U levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_U, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, umask, 1, 1., ndex_U , ndim_U  )      ! volume
+         CALL wheneq( jpi*jpj    , umask, 1, 1., ndex_hU, ndim_hU )      ! surface
+
+         ! Define the V grid FILE ( nid_V )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_V' )                   ! filename
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam
+         CALL histbeg( clhstnam, jpi, glamv, jpj, gphiv,           &  ! Horizontal grid: glamv and gphiv
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_V, nid_V, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_V, "depthv", "Vertical V levels",      &  ! Vertical grid : gdept
+            &          "m", ipk, gdept_1d, nz_V, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, vmask, 1, 1., ndex_V , ndim_V  )      ! volume
+         CALL wheneq( jpi*jpj    , vmask, 1, 1., ndex_hV, ndim_hV )      ! surface
+
+         ! Define the W grid FILE ( nid_W )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_W' )                   ! filename
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam
+         CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_W, nid_W, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_W, "depthw", "Vertical W levels",      &  ! Vertical grid: gdepw
+            &          "m", ipk, gdepw_1d, nz_W, "down" )
+
+
+         ! Declare all the output fields as NETCDF variables
+
+         !                                                                                      !!! nid_T : 3D
+         CALL histdef( nid_T, "votemper", "Temperature"                        , "C"      ,   &  ! tn
+            &          jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         CALL histdef( nid_T, "vosaline", "Salinity"                           , "PSU"    ,   &  ! sn
+            &          jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         IF(  .NOT.ln_linssh  ) THEN
+            CALL histdef( nid_T, "vovvle3t", "Level thickness"                    , "m"      ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+            CALL histdef( nid_T, "vovvldep", "T point depth"                      , "m"      ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+            CALL histdef( nid_T, "vovvldef", "Squared level deformation"          , "%^2"    ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_T : 2D
+         CALL histdef( nid_T, "sosstsst", "Sea Surface temperature"            , "C"      ,   &  ! sst
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sosaline", "Sea Surface Salinity"               , "PSU"    ,   &  ! sss
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sossheig", "Sea Surface Height"                 , "m"      ,   &  ! ssh
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowaflup", "Net Upward Water Flux"              , "Kg/m2/s",   &  ! (emp-rnf)
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sorunoff", "River runoffs"                      , "Kg/m2/s",   &  ! runoffs
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sosfldow", "downward salt flux"                 , "PSU/m2/s",  &  ! sfx
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         IF(  ln_linssh  ) THEN
+            CALL histdef( nid_T, "sosst_cd", "Concentration/Dilution term on temperature"     &  ! emp * tsn(:,:,1,jp_tem)
+            &                                                                  , "KgC/m2/s",  &  ! sosst_cd
+            &             jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sosss_cd", "Concentration/Dilution term on salinity"        &  ! emp * tsn(:,:,1,jp_sal)
+            &                                                                  , "KgPSU/m2/s",&  ! sosss_cd
+            &             jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         ENDIF
+         CALL histdef( nid_T, "sohefldo", "Net Downward Heat Flux"             , "W/m2"   ,   &  ! qns + qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soshfldo", "Shortwave Radiation"                , "W/m2"   ,   &  ! qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "somixhgt", "Turbocline Depth"                   , "m"      ,   &  ! hmld
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "somxl010", "Mixed Layer Depth 0.01"             , "m"      ,   &  ! hmlp
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soicecov", "Ice fraction"                       , "[0,1]"  ,   &  ! fr_i
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowindsp", "wind speed at 10m"                  , "m/s"    ,   &  ! wndm
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+!
+         IF( ln_icebergs ) THEN
+            CALL histdef( nid_T, "calving"             , "calving mass input"                       , "kg/s"   , &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "calving_heat"        , "calving heat flux"                        , "XXXX"   , &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "berg_floating_melt"  , "Melt rate of icebergs + bits"             , "kg/m2/s", &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "berg_stored_ice"     , "Accumulated ice mass by class"            , "kg"     , &
+               &          jpi, jpj, nh_T, nclasses  , 1, nclasses  , nb_T , 32, clop, zsto, zout )
+            IF( ln_bergdia ) THEN
+               CALL histdef( nid_T, "berg_melt"           , "Melt rate of icebergs"                    , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_buoy_melt"      , "Buoyancy component of iceberg melt rate"  , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_eros_melt"      , "Erosion component of iceberg melt rate"   , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_conv_melt"      , "Convective component of iceberg melt rate", "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_virtual_area"   , "Virtual coverage by icebergs"             , "m2"     , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_src"           , "Mass source of bergy bits"                , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_melt"          , "Melt rate of bergy bits"                  , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_mass"          , "Bergy bit density field"                  , "kg/m2"  , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_mass"           , "Iceberg density field"                    , "kg/m2"  , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_real_calving"   , "Calving into iceberg class"               , "kg/s"   , &
+                  &          jpi, jpj, nh_T, nclasses  , 1, nclasses  , nb_T , 32, clop, zsto, zout )
+            ENDIF
+         ENDIF
+
+         IF( ln_ssr ) 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 
+!            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clmx, zsto, zout )
+#if defined key_diahth
+         CALL histdef( nid_T, "sothedep", "Thermocline Depth"                  , "m"      ,   & ! hth
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "so20chgt", "Depth of 20C isotherm"              , "m"      ,   & ! hd20
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "so28chgt", "Depth of 28C isotherm"              , "m"      ,   & ! hd28
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sohtc300", "Heat content 300 m"                 , "J/m2"   ,   & ! htc3
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+#endif
+
+         CALL histend( nid_T, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_U : 3D
+         CALL histdef( nid_U, "vozocrtx", "Zonal Current"                      , "m/s"    ,   &  ! un
+            &          jpi, jpj, nh_U, ipk, 1, ipk, nz_U, 32, clop, zsto, zout )
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_U, "sdzocrtx", "Stokes Drift Zonal Current"         , "m/s"    ,   &  ! usd
+               &          jpi, jpj, nh_U, ipk, 1, ipk, nz_U, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_U : 2D
+         CALL histdef( nid_U, "sozotaux", "Wind Stress along i-axis"           , "N/m2"   ,   &  ! utau
+            &          jpi, jpj, nh_U, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_U, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_V : 3D
+         CALL histdef( nid_V, "vomecrty", "Meridional Current"                 , "m/s"    ,   &  ! vn
+            &          jpi, jpj, nh_V, ipk, 1, ipk, nz_V, 32, clop, zsto, zout )
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_V, "sdmecrty", "Stokes Drift Meridional Current"    , "m/s"    ,   &  ! vsd
+               &          jpi, jpj, nh_V, ipk, 1, ipk, nz_V, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_V : 2D
+         CALL histdef( nid_V, "sometauy", "Wind Stress along j-axis"           , "N/m2"   ,   &  ! vtau
+            &          jpi, jpj, nh_V, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_V, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_W : 3D
+         CALL histdef( nid_W, "vovecrtz", "Vertical Velocity"                  , "m/s"    ,   &  ! wn
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         CALL histdef( nid_W, "votkeavt", "Vertical Eddy Diffusivity"          , "m2/s"   ,   &  ! avt
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         CALL histdef( nid_W, "votkeavm", "Vertical Eddy Viscosity"             , "m2/s"  ,   &  ! avm
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+
+         IF( ln_zdfddm ) THEN
+            CALL histdef( nid_W,"voddmavs","Salt Vertical Eddy Diffusivity"    , "m2/s"   ,   &  ! avs
+               &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         ENDIF
+         
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_W, "sdvecrtz", "Stokes Drift Vertical Current"   , "m/s"    ,   &  ! wsd
+               &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_W : 2D
+         CALL histend( nid_W, snc4chunks=snc4set )
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'End of NetCDF Initialization'
+         IF(ll_print) CALL FLUSH(numout )
+
+      ENDIF
+
+      ! 2. Start writing data
+      ! ---------------------
+
+      ! ndex(1) est utilise ssi l'avant dernier argument est different de 
+      ! la taille du tableau en sortie. Dans ce cas , l'avant dernier argument
+      ! donne le nombre d'elements, et ndex la liste des indices a sortir
+
+      IF( lwp .AND. MOD( itmod, nn_write ) == 0 ) THEN 
+         WRITE(numout,*) 'dia_wri : write model outputs in NetCDF files at ', kt, 'time-step'
+         WRITE(numout,*) '~~~~~~ '
+      ENDIF
+
+      IF( .NOT.ln_linssh ) THEN
+         CALL histwrite( nid_T, "votemper", it, tsn(:,:,:,jp_tem) * e3t_n(:,:,:) , ndim_T , ndex_T  )   ! heat content
+         CALL histwrite( nid_T, "vosaline", it, tsn(:,:,:,jp_sal) * e3t_n(:,:,:) , ndim_T , ndex_T  )   ! salt content
+         CALL histwrite( nid_T, "sosstsst", it, tsn(:,:,1,jp_tem) * e3t_n(:,:,1) , ndim_hT, ndex_hT )   ! sea surface heat content
+         CALL histwrite( nid_T, "sosaline", it, tsn(:,:,1,jp_sal) * e3t_n(:,:,1) , ndim_hT, ndex_hT )   ! sea surface salinity content
+      ELSE
+         CALL histwrite( nid_T, "votemper", it, tsn(:,:,:,jp_tem) , ndim_T , ndex_T  )   ! temperature
+         CALL histwrite( nid_T, "vosaline", it, tsn(:,:,:,jp_sal) , ndim_T , ndex_T  )   ! salinity
+         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( .NOT.ln_linssh ) THEN
+         zw3d(:,:,:) = ( ( e3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2
+         CALL histwrite( nid_T, "vovvle3t", it, e3t_n (:,:,:) , ndim_T , ndex_T  )   ! level thickness
+         CALL histwrite( nid_T, "vovvldep", it, gdept_n(:,:,:) , ndim_T , ndex_T  )   ! t-point depth
+         CALL histwrite( nid_T, "vovvldef", it, zw3d             , ndim_T , ndex_T  )   ! level thickness deformation
+      ENDIF
+      CALL histwrite( nid_T, "sossheig", it, sshn          , ndim_hT, ndex_hT )   ! sea surface height
+      CALL histwrite( nid_T, "sowaflup", it, ( emp-rnf )   , ndim_hT, ndex_hT )   ! upward water flux
+      CALL histwrite( nid_T, "sorunoff", it, rnf           , ndim_hT, ndex_hT )   ! river runoffs
+      CALL histwrite( nid_T, "sosfldow", it, sfx           , ndim_hT, ndex_hT )   ! downward salt flux 
+                                                                                  ! (includes virtual salt flux beneath ice 
+                                                                                  ! in linear free surface case)
+      IF( ln_linssh ) THEN
+         zw2d(:,:) = emp (:,:) * tsn(:,:,1,jp_tem)
+         CALL histwrite( nid_T, "sosst_cd", it, zw2d, ndim_hT, ndex_hT )          ! c/d term on sst
+         zw2d(:,:) = emp (:,:) * tsn(:,:,1,jp_sal)
+         CALL histwrite( nid_T, "sosss_cd", it, zw2d, ndim_hT, ndex_hT )          ! c/d term on sss
+      ENDIF
+      CALL histwrite( nid_T, "sohefldo", it, qns + qsr     , ndim_hT, ndex_hT )   ! total heat flux
+      CALL histwrite( nid_T, "soshfldo", it, qsr           , ndim_hT, ndex_hT )   ! solar heat flux
+      CALL histwrite( nid_T, "somixhgt", it, hmld          , ndim_hT, ndex_hT )   ! turbocline depth
+      CALL histwrite( nid_T, "somxl010", it, hmlp          , ndim_hT, ndex_hT )   ! mixed layer depth
+      CALL histwrite( nid_T, "soicecov", it, fr_i          , ndim_hT, ndex_hT )   ! ice fraction   
+      CALL histwrite( nid_T, "sowindsp", it, wndm          , ndim_hT, ndex_hT )   ! wind speed   
+!
+      IF( ln_icebergs ) THEN
+         !
+         CALL histwrite( nid_T, "calving"             , it, berg_grid%calving      , ndim_hT, ndex_hT )  
+         CALL histwrite( nid_T, "calving_heat"        , it, berg_grid%calving_hflx , ndim_hT, ndex_hT )         
+         CALL histwrite( nid_T, "berg_floating_melt"  , it, berg_grid%floating_melt, ndim_hT, ndex_hT )  
+         !
+         CALL histwrite( nid_T, "berg_stored_ice"     , it, berg_grid%stored_ice   , ndim_bT, ndex_bT )
+         !
+         IF( ln_bergdia ) THEN
+            CALL histwrite( nid_T, "berg_melt"           , it, berg_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_buoy_melt"      , it, buoy_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_eros_melt"      , it, eros_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_conv_melt"      , it, conv_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_virtual_area"   , it, virtual_area     , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_src"            , it, bits_src         , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_melt"           , it, bits_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_mass"           , it, bits_mass        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_mass"           , it, berg_mass        , ndim_hT, ndex_hT   )  
+            !
+            CALL histwrite( nid_T, "berg_real_calving"   , it, real_calving     , ndim_bT, ndex_bT   )
+         ENDIF
+      ENDIF
+
+      IF( ln_ssr ) 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
+         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
+      CALL histwrite( nid_T, "sothedep", it, hth           , ndim_hT, ndex_hT )   ! depth of the thermocline
+      CALL histwrite( nid_T, "so20chgt", it, hd20          , ndim_hT, ndex_hT )   ! depth of the 20 isotherm
+      CALL histwrite( nid_T, "so28chgt", it, hd28          , ndim_hT, ndex_hT )   ! depth of the 28 isotherm
+      CALL histwrite( nid_T, "sohtc300", it, htc3          , ndim_hT, ndex_hT )   ! first 300m heaat content
+#endif
+
+      CALL histwrite( nid_U, "vozocrtx", it, un            , ndim_U , ndex_U )    ! i-current
+      CALL histwrite( nid_U, "sozotaux", it, utau          , ndim_hU, ndex_hU )   ! i-wind stress
+
+      CALL histwrite( nid_V, "vomecrty", it, vn            , ndim_V , ndex_V  )   ! j-current
+      CALL histwrite( nid_V, "sometauy", it, vtau          , ndim_hV, ndex_hV )   ! j-wind stress
+
+      IF( ln_zad_Aimp ) THEN
+         CALL histwrite( nid_W, "vovecrtz", it, wn + wi     , ndim_T, ndex_T )    ! vert. current
+      ELSE
+         CALL histwrite( nid_W, "vovecrtz", it, wn          , ndim_T, ndex_T )    ! vert. current
+      ENDIF
+      CALL histwrite( nid_W, "votkeavt", it, avt            , ndim_T, ndex_T )    ! T vert. eddy diff. coef.
+      CALL histwrite( nid_W, "votkeavm", it, avm            , ndim_T, ndex_T )    ! T vert. eddy visc. coef.
+      IF( ln_zdfddm ) THEN
+         CALL histwrite( nid_W, "voddmavs", it, avs         , ndim_T, ndex_T )    ! S vert. eddy diff. coef.
+      ENDIF
+
+      IF( ln_wave .AND. ln_sdw ) THEN
+         CALL histwrite( nid_U, "sdzocrtx", it, usd         , ndim_U , ndex_U )    ! i-StokesDrift-current
+         CALL histwrite( nid_V, "sdmecrty", it, vsd         , ndim_V , ndex_V )    ! j-StokesDrift-current
+         CALL histwrite( nid_W, "sdvecrtz", it, wsd         , ndim_T , ndex_T )    ! StokesDrift vert. current
+      ENDIF
+
+      ! 3. Close all files
+      ! ---------------------------------------
+      IF( kt == nitend ) THEN
+         CALL histclo( nid_T )
+         CALL histclo( nid_U )
+         CALL histclo( nid_V )
+         CALL histclo( nid_W )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_wri')
+      !
+   END SUBROUTINE dia_wri
+#endif
+
+   SUBROUTINE dia_wri_state( cdfile_name )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_wri_state  ***
+      !!        
+      !! ** Purpose :   create a NetCDF file named cdfile_name which contains 
+      !!      the instantaneous ocean state and forcing fields.
+      !!        Used to find errors in the initial state or save the last
+      !!      ocean state in case of abnormal end of a simulation
+      !!
+      !! ** Method  :   NetCDF files using ioipsl
+      !!      File 'output.init.nc'  is created if ninist = 1 (namelist)
+      !!      File 'output.abort.nc' is created in case of abnormal job end
+      !!----------------------------------------------------------------------
+      CHARACTER (len=* ), INTENT( in ) ::   cdfile_name      ! name of the file created
+      !!
+      INTEGER :: inum
+      !!----------------------------------------------------------------------
+      ! 
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dia_wri_state : single instantaneous ocean state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~   and forcing fields file created '
+      IF(lwp) WRITE(numout,*) '                and named :', cdfile_name, '...nc'
+
+#if defined key_si3
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE., kdlev = jpl )
+#else
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE. )
+#endif
+
+      CALL iom_rstput( 0, 0, inum, 'votemper', tsn(:,:,:,jp_tem) )    ! now temperature
+      CALL iom_rstput( 0, 0, inum, 'vosaline', tsn(:,:,:,jp_sal) )    ! now salinity
+      CALL iom_rstput( 0, 0, inum, 'sossheig', sshn              )    ! sea surface height
+      CALL iom_rstput( 0, 0, inum, 'vozocrtx', un                )    ! now i-velocity
+      CALL iom_rstput( 0, 0, inum, 'vomecrty', vn                )    ! now j-velocity
+      IF( ln_zad_Aimp ) THEN
+         CALL iom_rstput( 0, 0, inum, 'vovecrtz', wn + wi        )    ! now k-velocity
+      ELSE
+         CALL iom_rstput( 0, 0, inum, 'vovecrtz', wn             )    ! now k-velocity
+      ENDIF
+      IF( ALLOCATED(ahtu) ) THEN
+         CALL iom_rstput( 0, 0, inum,  'ahtu', ahtu              )    ! aht at u-point
+         CALL iom_rstput( 0, 0, inum,  'ahtv', ahtv              )    ! aht at v-point
+      ENDIF
+      IF( ALLOCATED(ahmt) ) THEN
+         CALL iom_rstput( 0, 0, inum,  'ahmt', ahmt              )    ! ahmt at u-point
+         CALL iom_rstput( 0, 0, inum,  'ahmf', ahmf              )    ! ahmf at v-point
+      ENDIF
+      CALL iom_rstput( 0, 0, inum, 'sowaflup', emp - rnf         )    ! freshwater budget
+      CALL iom_rstput( 0, 0, inum, 'sohefldo', qsr + qns         )    ! total heat flux
+      CALL iom_rstput( 0, 0, inum, 'soshfldo', qsr               )    ! solar heat flux
+      CALL iom_rstput( 0, 0, inum, 'soicecov', fr_i              )    ! ice fraction
+      CALL iom_rstput( 0, 0, inum, 'sozotaux', utau              )    ! i-wind stress
+      CALL iom_rstput( 0, 0, inum, 'sometauy', vtau              )    ! j-wind stress
+      IF(  .NOT.ln_linssh  ) THEN             
+         CALL iom_rstput( 0, 0, inum, 'vovvldep', gdept_n        )    !  T-cell depth 
+         CALL iom_rstput( 0, 0, inum, 'vovvle3t', e3t_n          )    !  T-cell thickness  
+      END IF
+      IF( ln_wave .AND. ln_sdw ) THEN
+         CALL iom_rstput( 0, 0, inum, 'sdzocrtx', usd            )    ! now StokesDrift i-velocity
+         CALL iom_rstput( 0, 0, inum, 'sdmecrty', vsd            )    ! now StokesDrift j-velocity
+         CALL iom_rstput( 0, 0, inum, 'sdvecrtz', wsd            )    ! now StokesDrift k-velocity
+      ENDIF
+ 
+#if defined key_si3
+      IF( nn_ice == 2 ) THEN   ! condition needed in case agrif + ice-model but no-ice in child grid
+         CALL ice_wri_state( inum )
+      ENDIF
+#endif
+      !
+      CALL iom_close( inum )
+      ! 
+   END SUBROUTINE dia_wri_state
+
+   !!======================================================================
+END MODULE diawri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/cool_skin.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/cool_skin.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/cool_skin.F90	(revision 14097)
@@ -0,0 +1,146 @@
+MODULE cool_skin
+   !!======================================================================
+   !!                    ***  MODULE  cool_skin  ***
+   !!     Cool skin thickness and delta T correction using Artele et al. (2002)
+   !!     [see also Tu and Tsuang (2005)]
+   !!
+   !!=====================================================================
+   !! History :        !  2012-01  (P. Sykes)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   diurnal_sst_coolskin_init : initialisation of the cool skin
+   !!   diurnal_sst_coolskin_step : time-stepping  of the cool skin corrections
+   !!----------------------------------------------------------------------
+   USE par_kind
+   USE phycst
+   USE dom_oce
+   USE in_out_manager
+   USE sbc_oce
+   USE lib_mpp
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   ! Namelist parameters
+
+   ! Parameters
+   REAL(wp), PRIVATE, PARAMETER :: pp_k = 0.596_wp          ! Thermal conductivity of seawater
+   REAL(wp), PRIVATE, PARAMETER :: pp_v = 1.05e-6_wp        ! Kinematic viscosity of seawater
+   REAL(wp), PRIVATE, PARAMETER :: pp_C = 86400             ! seconds [see Tu and Tsuang (2005)]
+   REAL(wp), PRIVATE, PARAMETER :: pp_cw = 3993._wp         ! specific heat capacity of seawater
+   REAL(wp), PRIVATE, PARAMETER :: pp_h = 10._wp            ! reference depth [using 10m from Artale et al. (2002)]
+   REAL(wp), PRIVATE, PARAMETER :: pp_rhoa = 1.20421_wp     ! density of air (at 20C)
+   REAL(wp), PRIVATE, PARAMETER :: pp_cda = 1.45e-3_wp      ! assumed air-sea drag coefficient for calculating wind speed
+   
+   ! Key variables
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) :: x_csdsst    ! Cool skin delta SST
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) :: x_csthick   ! Cool skin thickness
+
+   PUBLIC diurnal_sst_coolskin_step, diurnal_sst_coolskin_init
+
+      !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------   
+   CONTAINS 
+   
+   SUBROUTINE diurnal_sst_coolskin_init
+      !!----------------------------------------------------------------------
+      !! *** ROUTINE diurnal_sst_coolskin_init ***
+      !!
+      !! ** Purpose :   initialise the cool skin model
+      !!
+      !! ** Method : 
+      !!
+      !! ** Reference :
+      !! 
+      !!----------------------------------------------------------------------
+      ALLOCATE( x_csdsst(jpi,jpj), x_csthick(jpi,jpj) )
+      x_csdsst = 0.
+      x_csthick = 0.
+      !
+   END SUBROUTINE diurnal_sst_coolskin_init
+
+
+   SUBROUTINE diurnal_sst_coolskin_step(psqflux, pstauflux, psrho, rdt)
+      !!----------------------------------------------------------------------
+      !! *** ROUTINE diurnal_sst_takaya_step ***
+      !!
+      !! ** Purpose :   Time-step the Artale cool skin model
+      !!
+      !! ** Method : 
+      !!
+      !! ** Reference : 
+      !!----------------------------------------------------------------------
+      ! Dummy variables
+      REAL(wp), INTENT(IN), DIMENSION(jpi,jpj) :: psqflux     ! Heat (non-solar)(Watts)
+      REAL(wp), INTENT(IN), DIMENSION(jpi,jpj) :: pstauflux   ! Wind stress (kg/ m s^2)
+      REAL(wp), INTENT(IN), DIMENSION(jpi,jpj) :: psrho       ! Water density (kg/m^3)
+      REAL(wp), INTENT(IN) :: rdt                             ! Time-step
+     
+      ! Local variables
+      REAL(wp), DIMENSION(jpi,jpj) :: z_fv                    ! Friction velocity     
+      REAL(wp), DIMENSION(jpi,jpj) :: z_gamma                 ! Dimensionless function of wind speed
+      REAL(wp), DIMENSION(jpi,jpj) :: z_lamda                 ! Sauders (dimensionless) proportionality constant
+      REAL(wp), DIMENSION(jpi,jpj) :: z_wspd                  ! Wind speed (m/s)
+      REAL(wp) :: z_ztx                                       ! Temporary u wind stress
+      REAL(wp) :: z_zty                                       ! Temporary v wind stress
+      REAL(wp) :: z_zmod                                      ! Temporary total wind stress
+     
+      INTEGER :: ji,jj
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT. ln_blk )   CALL ctl_stop("cool_skin.f90: diurnal flux processing only implemented for bulk forcing")
+      !
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+            !
+            ! Calcualte wind speed from wind stress and friction velocity
+            IF( tmask(ji,jj,1) == 1. .AND. pstauflux(ji,jj) /= 0 .AND. psrho(ji,jj) /=0 ) THEN
+               z_fv(ji,jj) = SQRT( pstauflux(ji,jj) / psrho(ji,jj) )
+               z_wspd(ji,jj) = SQRT( pstauflux(ji,jj) / ( pp_cda * pp_rhoa ) )
+            ELSE
+               z_fv(ji,jj) = 0.
+               z_wspd(ji,jj) = 0.     
+            ENDIF
+            !
+            ! Calculate gamma function which is dependent upon wind speed
+            IF( tmask(ji,jj,1) == 1. ) THEN
+               IF( ( z_wspd(ji,jj) <= 7.5 ) ) z_gamma(ji,jj) = ( 0.2 * z_wspd(ji,jj) ) + 0.5
+               IF( ( z_wspd(ji,jj) > 7.5 ) .AND. ( z_wspd(ji,jj) < 10. ) ) z_gamma(ji,jj) = ( 1.6 * z_wspd(ji,jj) ) - 10.
+               IF( ( z_wspd(ji,jj) >= 10. ) ) z_gamma(ji,jj) = 6.
+            ENDIF
+            !
+            ! Calculate lamda function
+            IF( tmask(ji,jj,1) == 1. .AND. z_fv(ji,jj) /= 0 ) THEN
+               z_lamda(ji,jj) = ( z_fv(ji,jj) * pp_k * pp_C ) / ( z_gamma(ji,jj) * psrho(ji,jj) * pp_cw * pp_h * pp_v )
+            ELSE
+               z_lamda(ji,jj) = 0.
+            ENDIF
+            !
+            ! Calculate the cool skin thickness - only when heat flux is out of the ocean
+            IF( tmask(ji,jj,1) == 1. .AND. z_fv(ji,jj) /= 0 .AND. psqflux(ji,jj) < 0 ) THEN
+               x_csthick(ji,jj) = ( z_lamda(ji,jj) * pp_v ) / z_fv(ji,jj)
+            ELSE
+               x_csthick(ji,jj) = 0.
+            ENDIF
+            !
+            ! Calculate the cool skin correction - only when the heat flux is out of the ocean
+            IF( tmask(ji,jj,1) == 1. .AND. x_csthick(ji,jj) /= 0. .AND. psqflux(ji,jj) < 0. ) THEN
+               x_csdsst(ji,jj) = ( psqflux(ji,jj) * x_csthick(ji,jj) ) / pp_k
+             ELSE
+               x_csdsst(ji,jj) = 0.
+            ENDIF
+            !
+         END DO
+      END DO
+      !
+   END SUBROUTINE diurnal_sst_coolskin_step
+
+   !!======================================================================
+END MODULE cool_skin
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/diurnal_bulk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/diurnal_bulk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/diurnal_bulk.F90	(revision 14097)
@@ -0,0 +1,267 @@
+MODULE diurnal_bulk
+   !!======================================================================
+   !!                    ***  MODULE  diurnal_bulk  ***
+   !!     Takaya model of diurnal warming (Takaya, 2010)
+   !!=====================================================================
+   !! History :        !  11-10  (J. While)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   diurnal_sst_bulk_init  : initialise diurnal model
+   !!   diurnal_sst_bulk_step  : time-step the diurnal model
+   !!----------------------------------------------------------------------
+   USE par_kind
+   USE phycst
+   USE dom_oce
+   USE lib_mpp
+   USE solfrac_mod
+   USE in_out_manager
+   
+   IMPLICIT NONE
+   PRIVATE
+   
+   ! Namelist parameters
+   LOGICAL, PUBLIC :: ln_diurnal
+   LOGICAL, PUBLIC :: ln_diurnal_only
+
+   ! Parameters
+   REAL(wp), PRIVATE, PARAMETER :: pp_alpha = 2.0e-4_wp
+   REAL(wp), PRIVATE, PARAMETER :: pp_veltol = 0._wp
+   REAL(wp), PRIVATE, PARAMETER :: pp_min_fvel = 1.e-10_wp 
+   
+   ! Key variables
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) :: x_dsst     ! Delta SST
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) :: x_solfrac  ! Fraction of 
+   !                                                           ! absorbed radiation
+
+   PUBLIC diurnal_sst_bulk_init, diurnal_sst_takaya_step
+   
+   !!----------------------------------------------------------------------
+CONTAINS 
+   
+   SUBROUTINE diurnal_sst_bulk_init
+      !!----------------------------------------------------------------------
+      !! *** ROUTINE diurnal_sst_init ***
+      !!
+      !! ** Purpose : Initialise the Takaya diurnal model   
+      !!----------------------------------------------------------------------      
+      INTEGER ::   ios   ! local integer
+      !!
+      NAMELIST /namdiu/ ln_diurnal, ln_diurnal_only
+      !!----------------------------------------------------------------------      
+
+      ! Read the namelist
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, namdiu, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdiu in reference namelist' )
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, namdiu, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdiu in configuration namelist' )      
+      !
+      IF( ln_diurnal_only .AND. ( .NOT. ln_diurnal ) ) THEN
+         CALL ctl_stop( "ln_diurnal_only set, but ln_diurnal = FALSE !" )
+      ENDIF
+      
+      IF( ln_diurnal ) THEN      
+         !         
+         ALLOCATE( x_dsst(jpi,jpj), x_solfrac(jpi,jpj) )
+         !
+         x_solfrac = 0._wp         ! Initialise the solar fraction
+         x_dsst    = 0._wp
+         !
+         IF( ln_diurnal_only ) THEN
+            CALL ctl_warn( "ln_diurnal_only set; only the diurnal component of SST will be calculated" )
+         ENDIF
+      ENDIF
+      
+   END SUBROUTINE diurnal_sst_bulk_init
+
+
+   SUBROUTINE diurnal_sst_takaya_step(kt, psolflux, pqflux, ptauflux, prho, p_rdt,   &
+            &                  pla, pthick, pcoolthick, pmu, &
+            &                  p_fvel_bkginc, p_hflux_bkginc)
+      !!----------------------------------------------------------------------
+      !! *** ROUTINE diurnal_sst_takaya_step ***
+      !!
+      !! ** Purpose :   Time-step the Takaya diurnal model
+      !!
+      !! ** Method :    1) Calculate the Obukhov length
+      !!                2) Calculate the Similarity function
+      !!                2) Calculate the increment to dsst
+      !!                3) Apply the increment
+      !! ** Reference : Refinements to a prognostic scheme of skin sea surface
+      !!                temperature, Takaya et al, JGR, 2010 
+      !!----------------------------------------------------------------------
+      INTEGER                               , INTENT(in) ::   kt             ! time step
+      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(in) ::   psolflux       ! solar flux (Watts)
+      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(in) ::   pqflux         ! heat (non-solar) flux (Watts)
+      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(in) ::   ptauflux       ! wind stress  (kg/ m s^2)
+      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(in) ::   prho           ! water density  (kg/m^3)
+      REAL(wp)                              , INTENT(in) ::   p_rdt          ! time-step
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   pLa            ! Langmuir number
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   pthick         ! warm layer thickness (m)
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   pcoolthick     ! cool skin thickness (m)
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   pmu            ! mu parameter
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   p_hflux_bkginc ! increment to the heat flux
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) ::   p_fvel_bkginc  ! increment to the friction velocity
+      !
+      INTEGER :: ji,jj
+      LOGICAL  :: ll_calcfrac
+      REAL(wp), DIMENSION(jpi,jpj) :: z_fvel              ! friction velocity     
+      REAL(wp), DIMENSION(jpi,jpj) :: zthick, zcoolthick, zmu, zla
+      REAL(wp), DIMENSION(jpi,jpj) :: z_abflux            ! absorbed flux           
+      REAL(wp), DIMENSION(jpi,jpj) :: z_fla               ! Langmuir function value 
+      !!----------------------------------------------------------------------
+
+      ! Set optional arguments to their defaults
+      IF( .NOT. PRESENT( pthick )   ) THEN   ;   zthick(:,:) = 3._wp
+      ELSE                                   ;   zthick(:,:) = pthick(:,:)
+      ENDIF
+      IF( .NOT. PRESENT(pcoolthick) ) THEN   ;   zcoolthick(:,:) = 0._wp
+      ELSE                                   ;   zcoolthick(:,:) = pcoolthick(:,:)
+      ENDIF
+      IF( .NOT. PRESENT( pmu )      ) THEN   ;   zmu(:,:) = 0.3_wp
+      ELSE                                   ;   zmu(:,:) = pmu(:,:)
+      ENDIF
+      IF( .NOT. PRESENT(pla) ) THEN          ;   zla(:,:) = 0.3_wp
+      ELSE                                   ;   zla(:,:) = pla(:,:)
+      ENDIF
+      
+      ! If not done already, calculate the solar fraction
+      IF ( kt==nit000 ) THEN
+         DO jj = 1,jpj
+            DO ji = 1, jpi
+               IF(  ( x_solfrac(ji,jj) == 0._wp ) .AND. ( tmask(ji,jj,1) == 1._wp ) ) &
+                  &   x_solfrac(ji,jj) = solfrac( zcoolthick(ji,jj),zthick(ji,jj) )
+            END DO
+         END DO   
+      ENDIF   
+
+      ! convert solar flux and heat flux to absorbed flux   
+      WHERE ( tmask(:,:,1) == 1._wp) 
+         z_abflux(:,:) = (  x_solfrac(:,:) *  psolflux (:,:)) + pqflux(:,:)     
+      ELSEWHERE
+         z_abflux(:,:) = 0._wp
+      ENDWHERE
+      IF( PRESENT(p_hflux_bkginc) ) z_abflux(:,:) = z_abflux(:,:) + p_hflux_bkginc   ! Optional increment
+      WHERE ( ABS( z_abflux(:,:) ) < rsmall )
+         z_abflux(:,:) = rsmall
+      ENDWHERE 
+      
+      ! Calculate the friction velocity
+      WHERE ( (ptauflux /= 0) .AND. ( tmask(:,:,1) == 1.) )   
+         z_fvel(:,:) = SQRT( ptauflux(:,:) / prho(:,:) )
+      ELSEWHERE
+         z_fvel(:,:) = 0._wp
+      ENDWHERE
+      IF( PRESENT(p_fvel_bkginc) ) z_fvel(:,:) = z_fvel(:,:) + p_fvel_bkginc   ! Optional increment
+      
+       
+       
+      ! Calculate the Langmuir function value
+      WHERE ( tmask(:,:,1) == 1.)
+         z_fla(:,:) = MAX( 1._wp, zla(:,:)**( -2._wp / 3._wp ) )  
+      ELSEWHERE
+         z_fla(:,:) = 0._wp
+      ENDWHERE     
+      
+      ! Increment the temperature using the implicit solution
+      x_dsst(:,:) = t_imp( x_dsst(:,:), p_rdt, z_abflux(:,:), z_fvel(:,:),   &
+         &                       z_fla(:,:), zmu(:,:), zthick(:,:), prho(:,:) )
+      !
+   END SUBROUTINE diurnal_sst_takaya_step
+
+   
+   FUNCTION t_imp(p_dsst, p_rdt, p_abflux, p_fvel, &
+                          p_fla, pmu, pthick, prho )
+                          
+      IMPLICIT NONE
+      
+      ! Function definition
+      REAL(wp), DIMENSION(jpi,jpj) :: t_imp
+      ! Dummy variables
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: p_dsst     ! Delta SST
+      REAL(wp), INTENT(IN)                     :: p_rdt      ! Time-step
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: p_abflux   ! Heat forcing
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: p_fvel     ! Friction velocity
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: p_fla      ! Langmuir number
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: pmu        ! Structure parameter
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: pthick     ! Layer thickness
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(IN) :: prho       ! Water density
+   
+      ! Local variables
+      REAL(wp) :: z_olength          ! Obukhov length
+      REAL(wp) :: z_sigma, z_sigma2
+      REAL(wp) :: z_term1, z_term2     
+      REAL(wp) :: z_stabfunc         ! stability function value
+      REAL(wp) :: z_fvel      
+      
+      CHARACTER(200) :: warn_string
+       
+      INTEGER :: ji,jj
+                     
+      DO jj = 1, jpj
+         DO ji = 1, jpi   
+            
+            ! Only calculate outside tmask
+            IF ( tmask(ji,jj,1) /= 1._wp ) THEN
+               t_imp(ji,jj) = 0._wp
+               CYCLE   
+            END IF
+            
+            IF (p_fvel(ji,jj) < pp_min_fvel) THEN
+               z_fvel = pp_min_fvel
+               WRITE(warn_string,*) "diurnal_sst_takaya step: "&
+               &//"friction velocity < minimum\n" &
+               &//"Setting friction velocity =",pp_min_fvel
+               CALL ctl_warn(warn_string)
+               
+            ELSE
+               z_fvel = p_fvel(ji,jj)
+            ENDIF
+                 
+            ! Calculate the Obukhov length
+            IF ( (z_fvel < pp_veltol ) .AND. &
+            &    (p_dsst(ji,jj) > 0._wp) ) THEN
+               z_olength =  z_fvel  / &
+               &     SQRT( p_dsst(ji,jj) * vkarmn * grav * &
+               &             pp_alpha / ( 5._wp * pthick(ji,jj) ) )
+            ELSE
+               z_olength = &
+               &   ( prho(ji,jj) * rcp * z_fvel**3._wp ) / &
+               &   ( vkarmn * grav * pp_alpha *&
+               &     p_abflux(ji,jj) )
+            ENDIF
+             
+            ! Calculate the stability function          
+            z_sigma = pthick(ji,jj) / z_olength
+            z_sigma2 = z_sigma * z_sigma
+  
+            IF ( z_sigma >= 0. ) THEN
+               z_stabfunc = 1._wp + &
+               &  ( ( 5._wp * z_sigma + 4._wp * z_sigma2 ) / &
+               &  ( 1._wp + 3._wp * z_sigma + 0.25_wp * &
+               &    z_sigma2 ) )
+            ELSE
+               z_stabfunc = 1._wp / &
+               &                   SQRT( 1._wp - 16._wp * z_sigma )
+            ENDIF
+
+            ! Calculate the T increment
+            z_term1 = ( p_abflux(ji,jj) * ( pmu(ji,jj) + 1._wp)  / &
+            & ( pmu(ji,jj) * pthick(ji,jj) * prho(ji,jj) * rcp ) )
+            
+             
+            z_term2 = -( ( pmu(ji,jj) + 1._wp) * &
+            &                       ( vkarmn * z_fvel * p_fla(ji,jj) ) / &
+            &      ( pthick(ji,jj) * z_stabfunc ) )     
+          
+            t_imp(ji,jj) = ( p_dsst(ji,jj) + p_rdt * z_term1 ) / &
+                           ( 1._wp - p_rdt * z_term2 )
+
+         END DO
+      END DO
+      
+      END FUNCTION t_imp
+
+END MODULE diurnal_bulk
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/solfrac_mod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/solfrac_mod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/solfrac_mod.F90	(revision 14097)
@@ -0,0 +1,56 @@
+MODULE solfrac_mod
+   !!======================================================================
+   !!                    ***  MODULE  solfrac  ***
+   !!     POSH representation of solar absorption (Gntermann, 2009)
+   !!=====================================================================
+   !! History :        !  11-10  (J. While)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   solfrac  : function to calculate the solar fraction
+   !!----------------------------------------------------------------------
+   
+   USE par_kind
+   IMPLICIT NONE
+     
+   ! Parameters 
+   REAL(wp), PRIVATE, PARAMETER, DIMENSION(9) :: &
+   &                                     pp_wgt = (/0.2370, 0.36,  0.1790, &
+   &                                                0.087,  0.08,  0.025,  &
+   &                                                0.025,  0.007, 0.0004/)
+   REAL(wp), PRIVATE, PARAMETER, DIMENSION(9) :: &
+   &                                    pp_len = (/34.84,   2.266,   0.0315,  &
+   &                                               0.0055,  8.32e-4, 1.26e-4, &
+   &                                                3.13e-4, 7.82e-4, 1.44e-5/)
+   
+   PUBLIC solfrac
+                                                   
+CONTAINS
+
+   REAL(dp) FUNCTION solfrac(ptop,pbottom)
+       !!----------------------------------------------------------------------
+      !! *** ROUTINE solfrac ***
+      !!
+      !! ** Purpose :   Calculate the solar fraction absorbed between two 
+      !!                layers
+      !!
+      !! ** Reference : POSH a model of diurnal warming, Gentemann et al, 
+      !!                 JGR, 2009 
+      !!----------------------------------------------------------------------
+      
+      ! Dummy variabes
+      REAL(wp), INTENT(IN) :: ptop, pbottom   ! Top and bottom of layer
+      
+      ! local variables
+      INTEGER :: jt
+      
+      ! Calculate the solar fraction absorbed between the two layers
+      solfrac = 0._wp
+      DO jt = 1, 9
+           solfrac = solfrac + pp_wgt(jt) * ( exp ( -ptop / pp_len(jt) ) &
+            &                                 - exp ( -pbottom / pp_len(jt) ) )
+      END DO
+      
+   END FUNCTION
+   
+END MODULE solfrac_mod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/step_diu.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/step_diu.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DIU/step_diu.F90	(revision 14097)
@@ -0,0 +1,93 @@
+MODULE step_diu
+   !!======================================================================
+   !!                       ***  MODULE stp_diu  ***
+   !! Time-stepping of diurnal cycle models
+   !!======================================================================
+   !! History :  3.7  ! 2015-11  (J. While)  Original code
+
+   USE diurnal_bulk    ! diurnal SST bulk routines  (diurnal_sst_takaya routine) 
+   USE cool_skin       ! diurnal cool skin correction (diurnal_sst_coolskin routine)   
+   USE iom
+   USE sbc_oce
+   USE sbcmod           ! surface boundary condition       (sbc     routine)
+   USE diaobs           ! Observation operator
+   USE oce
+   USE daymod
+   USE restart          ! ocean restart                    (rst_wri routine)
+   USE timing           ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   stp_diurnal   ! called by nemogcm.F90 or step.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   CONTAINS
+
+   SUBROUTINE stp_diurnal( kstp ) 
+      INTEGER, INTENT(in) ::   kstp   ! ocean time-step index 
+      !!---------------------------------------------------------------------- 
+      !!                     ***  ROUTINE stp_diurnal  *** 
+      !!                       
+      !! ** Purpose : - Time stepping of diurnal SST model only 
+      !!   
+      !! ** Method  : -1- Update forcings and data   
+      !!              -2- Update ocean physics   
+      !!              -3- Compute the t and s trends   
+      !!              -4- Update t and s   
+      !!              -5- Compute the momentum trends 
+      !!              -6- Update the horizontal velocity 
+      !!              -7- Compute the diagnostics variables (rd,N2, div,cur,w) 
+      !!              -8- Outputs and diagnostics 
+      !!---------------------------------------------------------------------- 
+      INTEGER ::   jk       ! dummy loop indices
+      INTEGER ::   indic    ! error indicator if < 0 
+      REAL(wp), DIMENSION(jpi,jpj) :: z_fvel_bkginc, z_hflux_bkginc     
+      !! --------------------------------------------------------------------- 
+      
+      IF(ln_diurnal_only) THEN
+         indic = 0                                 ! reset to no error condition 
+         IF( kstp /= nit000 )   CALL day( kstp )   ! Calendar (day was already called at nit000 in day_init) 
+ 
+         CALL iom_setkt( kstp - nit000 + 1, cxios_context )   ! tell iom we are at time step kstp
+         IF( ln_crs ) THEN
+            CALL iom_setkt( kstp - nit000 + 1, TRIM(cxios_context)//"_crs" ) ! tell iom we are at time step kstp
+         ENDIF
+       
+            CALL sbc    ( kstp )                      ! Sea Boundary Conditions 
+      ENDIF
+     
+      ! Cool skin
+      IF( .NOT.ln_diurnal )   CALL ctl_stop( "stp_diurnal: ln_diurnal not set" )
+         
+      IF( .NOT. ln_blk    )   CALL ctl_stop( "stp_diurnal: diurnal flux processing only implemented for bulk forcing" ) 
+
+      CALL diurnal_sst_coolskin_step( qns, taum, rhop(:,:,1), rdt)
+
+      CALL iom_put( "sst_wl"   , x_dsst               )    ! warm layer (write out before update below).
+      CALL iom_put( "sst_cs"   , x_csdsst             )    ! cool skin
+
+      ! Diurnal warm layer model       
+      CALL diurnal_sst_takaya_step( kstp, & 
+      &    qsr, qns, taum, rhop(:,:,1), rdt) 
+
+      IF( ln_diurnal_only ) THEN
+         IF( ln_diaobs )         CALL dia_obs( kstp )         ! obs-minus-model (assimilation) diagnostics (call after dynamics update)
+     
+         !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
+         ! Control and restarts 
+         !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 
+         IF( kstp == nit000   )   CALL iom_close( numror )     ! close input  ocean restart file 
+         IF( lrst_oce         )   CALL rst_write    ( kstp )   ! write output ocean restart file
+     
+         IF( ln_timing .AND.  kstp == nit000  )   CALL timing_reset 
+      ENDIF
+       
+   END SUBROUTINE stp_diurnal  
+   
+END MODULE step_diu
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/closea.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/closea.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/closea.F90	(revision 14097)
@@ -0,0 +1,488 @@
+MODULE closea
+   !!======================================================================
+   !!                   ***  MODULE  closea  ***
+   !!
+   !! User define : specific treatments associated with closed seas
+   !!======================================================================
+   !! History :   8.2  !  2000-05  (O. Marti)  Original code
+   !!   NEMO      1.0  !  2002-06  (E. Durand, G. Madec)  F90
+   !!             3.0  !  2006-07  (G. Madec)  add clo_rnf, clo_ups, clo_bat
+   !!             3.4  !  2014-12  (P.G. Fogli) sbc_clo bug fix & mpp reproducibility
+   !!             4.0  !  2016-06  (G. Madec)  move to usrdef_closea, remove clo_ups
+   !!             4.0  !  2017-12  (D. Storkey) new formulation based on masks read from file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_clo    : read in masks which define closed seas and runoff areas
+   !!   sbc_clo    : Special handling of freshwater fluxes over closed seas
+   !!   clo_rnf    : set close sea outflows as river mouths (see sbcrnf)
+   !!   clo_bat    : set to zero a field over closed sea (see domzgr)
+   !!----------------------------------------------------------------------
+   USE oce             ! dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE sbc_oce         ! ocean surface boundary conditions
+   USE iom             ! I/O routines
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_fortran,    ONLY: glob_sum
+   USE lbclnk          ! lateral boundary condition - MPP exchanges
+   USE lib_mpp         ! MPP library
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dom_clo      ! called by domain module
+   PUBLIC sbc_clo      ! called by sbcmod module
+   PUBLIC clo_rnf      ! called by sbcrnf module
+   PUBLIC clo_bat      ! called in domzgr module
+
+   LOGICAL, PUBLIC :: ln_closea  !:  T => keep closed seas (defined by closea_mask field) in the domain and apply
+                                 !:       special treatment of freshwater fluxes.
+                                 !:  F => suppress closed seas (defined by closea_mask field) from the bathymetry
+                                 !:       at runtime.
+                                 !:  If there is no closea_mask field in the domain_cfg file or we do not use
+                                 !:  a domain_cfg file then this logical does nothing.
+                                 !:
+   LOGICAL, PUBLIC :: l_sbc_clo  !: T => Closed seas defined, apply special treatment of freshwater fluxes.
+                                 !: F => No closed seas defined (closea_mask field not found).
+   LOGICAL, PUBLIC :: l_clo_rnf  !: T => Some closed seas output freshwater (RNF or EMPMR) to specified runoff points.
+   INTEGER, PUBLIC :: jncs       !: number of closed seas (inferred from closea_mask field)
+   INTEGER, PUBLIC :: jncsr      !: number of closed seas rnf mappings (inferred from closea_mask_rnf field)
+   INTEGER, PUBLIC :: jncse      !: number of closed seas empmr mappings (inferred from closea_mask_empmr field)
+   
+   INTEGER, PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::  closea_mask       !: mask of integers defining closed seas
+   INTEGER, PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::  closea_mask_rnf   !: mask of integers defining closed seas rnf mappings
+   INTEGER, PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::  closea_mask_empmr !: mask of integers defining closed seas empmr mappings
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:)  ::   surf         !: closed sea surface areas 
+                                                                  !: (and residual global surface area) 
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:)  ::   surfr        !: closed sea target rnf surface areas 
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:)  ::   surfe        !: closed sea target empmr surface areas 
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_clo()
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_clo  ***
+      !!        
+      !! ** Purpose :   Closed sea domain initialization
+      !!
+      !! ** Method  :   if a closed sea is located only in a model grid point
+      !!                just the thermodynamic processes are applied.
+      !!
+      !! ** Action  :   Read closea_mask* fields (if they exist) from domain_cfg file and infer
+      !!                number of closed seas from closea_mask field.
+      !!                closea_mask       : integer values defining closed seas (or groups of closed seas)
+      !!                closea_mask_rnf   : integer values defining mappings from closed seas or groups of
+      !!                                    closed seas to a runoff area for downwards flux only.
+      !!                closea_mask_empmr : integer values defining mappings from closed seas or groups of
+      !!                                    closed seas to a runoff area for net fluxes.
+      !!
+      !!                Python code to generate the closea_masks* fields from the old-style indices
+      !!                definitions is available at TOOLS/DOMAINcfg/make_closea_masks.py
+      !!----------------------------------------------------------------------
+      INTEGER ::   inum    ! input file identifier
+      INTEGER ::   ierr    ! error code
+      INTEGER ::   id      ! netcdf variable ID
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zdata_in ! temporary real array for input
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*)'dom_clo : read in masks to define closed seas '
+      IF(lwp) WRITE(numout,*)'~~~~~~~'
+      !
+      ! read the closed seas masks (if they exist) from domain_cfg file (if it exists)
+      ! ------------------------------------------------------------------------------
+      !
+      IF( ln_read_cfg) THEN
+         !
+         CALL iom_open( cn_domcfg, inum )
+         !
+         id = iom_varid(inum, 'closea_mask', ldstop = .false.)
+         IF( id > 0 ) THEN 
+            l_sbc_clo = .true.
+            ALLOCATE( closea_mask(jpi,jpj) , STAT=ierr )
+            IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'dom_clo: failed to allocate closea_mask array')
+            zdata_in(:,:) = 0.0
+            CALL iom_get ( inum, jpdom_data, 'closea_mask', zdata_in )
+            closea_mask(:,:) = NINT(zdata_in(:,:)) * tmask(:,:,1)
+            ! number of closed seas = global maximum value in closea_mask field
+            jncs = maxval(closea_mask(:,:))
+            CALL mpp_max('closea', jncs)
+            IF( jncs > 0 ) THEN
+               IF( lwp ) WRITE(numout,*) 'Number of closed seas : ',jncs
+            ELSE
+               CALL ctl_stop( 'Problem with closea_mask field in domain_cfg file. Has no values > 0 so no closed seas defined.')
+            ENDIF
+         ELSE 
+            IF( lwp ) WRITE(numout,*)
+            IF( lwp ) WRITE(numout,*) '   ==>>>   closea_mask field not found in domain_cfg file.'
+            IF( lwp ) WRITE(numout,*) '           No closed seas defined.'
+            IF( lwp ) WRITE(numout,*)
+            l_sbc_clo = .false.
+            jncs = 0 
+         ENDIF
+
+         l_clo_rnf = .false.
+
+         IF( l_sbc_clo ) THEN ! No point reading in closea_mask_rnf or closea_mask_empmr fields if no closed seas defined.
+
+            id = iom_varid(inum, 'closea_mask_rnf', ldstop = .false.)
+            IF( id > 0 ) THEN 
+               l_clo_rnf = .true.            
+               ALLOCATE( closea_mask_rnf(jpi,jpj) , STAT=ierr )
+               IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'dom_clo: failed to allocate closea_mask_rnf array')
+               CALL iom_get ( inum, jpdom_data, 'closea_mask_rnf', zdata_in )
+               closea_mask_rnf(:,:) = NINT(zdata_in(:,:)) * tmask(:,:,1)
+               ! number of closed seas rnf mappings = global maximum in closea_mask_rnf field
+               jncsr = maxval(closea_mask_rnf(:,:))
+               CALL mpp_max('closea', jncsr)
+               IF( jncsr > 0 ) THEN
+                  IF( lwp ) WRITE(numout,*) 'Number of closed seas rnf mappings : ',jncsr
+               ELSE
+                  CALL ctl_stop( 'Problem with closea_mask_rnf field in domain_cfg file. Has no values > 0 so no closed seas rnf mappings defined.')
+               ENDIF
+            ELSE 
+               IF( lwp ) WRITE(numout,*) 'closea_mask_rnf field not found in domain_cfg file. No closed seas rnf mappings defined.'
+               jncsr = 0
+            ENDIF
+ 
+            id = iom_varid(inum, 'closea_mask_empmr', ldstop = .false.)
+            IF( id > 0 ) THEN 
+               l_clo_rnf = .true.            
+               ALLOCATE( closea_mask_empmr(jpi,jpj) , STAT=ierr )
+               IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'dom_clo: failed to allocate closea_mask_empmr array')
+               CALL iom_get ( inum, jpdom_data, 'closea_mask_empmr', zdata_in )
+               closea_mask_empmr(:,:) = NINT(zdata_in(:,:)) * tmask(:,:,1)
+               ! number of closed seas empmr mappings = global maximum value in closea_mask_empmr field
+               jncse = maxval(closea_mask_empmr(:,:))
+               CALL mpp_max('closea', jncse)
+               IF( jncse > 0 ) THEN 
+                  IF( lwp ) WRITE(numout,*) 'Number of closed seas empmr mappings : ',jncse
+               ELSE
+                  CALL ctl_stop( 'Problem with closea_mask_empmr field in domain_cfg file. Has no values > 0 so no closed seas empmr mappings defined.')
+               ENDIF
+            ELSE 
+               IF( lwp ) WRITE(numout,*) 'closea_mask_empmr field not found in domain_cfg file. No closed seas empmr mappings defined.'
+               jncse = 0
+            ENDIF
+
+         ENDIF ! l_sbc_clo
+         !
+         CALL iom_close( inum )
+         !
+      ELSE ! ln_read_cfg = .false. so no domain_cfg file
+         IF( lwp ) WRITE(numout,*) 'No domain_cfg file so no closed seas defined.'
+         l_sbc_clo = .false.
+         l_clo_rnf = .false.
+      ENDIF
+      !
+   END SUBROUTINE dom_clo
+
+
+   SUBROUTINE sbc_clo( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_clo  ***
+      !!                    
+      !! ** Purpose :   Special handling of closed seas
+      !!
+      !! ** Method  :   Water flux is forced to zero over closed sea
+      !!      Excess is shared between remaining ocean, or
+      !!      put as run-off in open ocean.
+      !!
+      !! ** Action  :   emp updated surface freshwater fluxes and associated heat content at kt
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in   ) ::   kt       ! ocean model time step
+      !
+      INTEGER             ::   ierr
+      INTEGER             ::   jc, jcr, jce   ! dummy loop indices
+      REAL(wp), PARAMETER ::   rsmall = 1.e-20_wp    ! Closed sea correction epsilon
+      REAL(wp)            ::   zfwf_total, zcoef, zcoef1         ! 
+      REAL(wp), DIMENSION(jncs)    ::   zfwf      !:
+      REAL(wp), DIMENSION(jncsr+1) ::   zfwfr     !: freshwater fluxes over closed seas
+      REAL(wp), DIMENSION(jncse+1) ::   zfwfe     !: 
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztmp2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('sbc_clo')
+      !
+      !                                                   !------------------! 
+      IF( kt == nit000 ) THEN                             !  Initialisation  !
+         !                                                !------------------!
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*)'sbc_clo : closed seas '
+         IF(lwp) WRITE(numout,*)'~~~~~~~'
+
+         ALLOCATE( surf(jncs+1) , STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'sbc_clo: failed to allocate surf array')
+         surf(:) = 0.e0_wp
+         !
+         ! jncsr can be zero so add 1 to avoid allocating zero-length array
+         ALLOCATE( surfr(jncsr+1) , STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'sbc_clo: failed to allocate surfr array')
+         surfr(:) = 0.e0_wp
+         !
+         ! jncse can be zero so add 1 to avoid allocating zero-length array
+         ALLOCATE( surfe(jncse+1) , STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'sbc_clo: failed to allocate surfe array')
+         surfe(:) = 0.e0_wp
+         !
+         surf(jncs+1) = glob_sum( 'closea', e1e2t(:,:) )   ! surface of the global ocean
+         !
+         !                                        ! surface areas of closed seas 
+         DO jc = 1, jncs
+            ztmp2d(:,:) = 0.e0_wp
+            WHERE( closea_mask(:,:) == jc ) ztmp2d(:,:) = e1e2t(:,:) * tmask_i(:,:)
+            surf(jc) = glob_sum( 'closea', ztmp2d(:,:) )
+         END DO
+         !
+         ! jncs+1 : surface area of global ocean, closed seas excluded
+         surf(jncs+1) = surf(jncs+1) - SUM(surf(1:jncs))
+         !
+         !                                        ! surface areas of rnf target areas
+         IF( jncsr > 0 ) THEN
+            DO jcr = 1, jncsr
+               ztmp2d(:,:) = 0.e0_wp
+               WHERE( closea_mask_rnf(:,:) == jcr .and. closea_mask(:,:) == 0 ) ztmp2d(:,:) = e1e2t(:,:) * tmask_i(:,:)
+               surfr(jcr) = glob_sum( 'closea', ztmp2d(:,:) )
+            END DO
+         ENDIF
+         !
+         !                                        ! surface areas of empmr target areas
+         IF( jncse > 0 ) THEN
+            DO jce = 1, jncse
+               ztmp2d(:,:) = 0.e0_wp
+               WHERE( closea_mask_empmr(:,:) == jce .and. closea_mask(:,:) == 0 ) ztmp2d(:,:) = e1e2t(:,:) * tmask_i(:,:)
+               surfe(jce) = glob_sum( 'closea', ztmp2d(:,:) )
+            END DO
+         ENDIF
+         !
+         IF(lwp) WRITE(numout,*)'     Closed sea surface areas (km2)'
+         DO jc = 1, jncs
+            IF(lwp) WRITE(numout,FMT='(1I3,5X,ES12.2)') jc, surf(jc) * 1.0e-6
+         END DO
+         IF(lwp) WRITE(numout,FMT='(A,ES12.2)') 'Global surface area excluding closed seas (km2): ', surf(jncs+1) * 1.0e-6
+         !
+         IF(jncsr > 0) THEN
+            IF(lwp) WRITE(numout,*)'     Closed sea target rnf surface areas (km2)'
+            DO jcr = 1, jncsr
+               IF(lwp) WRITE(numout,FMT='(1I3,5X,ES12.2)') jcr, surfr(jcr) * 1.0e-6
+            END DO
+         ENDIF
+         !
+         IF(jncse > 0) THEN
+            IF(lwp) WRITE(numout,*)'     Closed sea target empmr surface areas (km2)'
+            DO jce = 1, jncse
+               IF(lwp) WRITE(numout,FMT='(1I3,5X,ES12.2)') jce, surfe(jce) * 1.0e-6
+            END DO
+         ENDIF
+      ENDIF
+      !
+      !                                                      !--------------------!
+      !                                                      !  update emp        !
+      !                                                      !--------------------!
+
+      zfwf_total = 0._wp
+
+      !
+      ! 1. Work out total freshwater fluxes over closed seas from EMP - RNF.
+      !
+      zfwf(:) = 0.e0_wp           
+      DO jc = 1, jncs
+         ztmp2d(:,:) = 0.e0_wp
+         WHERE( closea_mask(:,:) == jc ) ztmp2d(:,:) = e1e2t(:,:) * ( emp(:,:)-rnf(:,:) ) * tmask_i(:,:)
+         zfwf(jc) = glob_sum( 'closea', ztmp2d(:,:) )
+      END DO
+      zfwf_total = SUM(zfwf)
+
+      zfwfr(:) = 0.e0_wp           
+      IF( jncsr > 0 ) THEN
+         !
+         ! 2. Work out total FW fluxes over rnf source areas and add to rnf target areas. 
+         !    Where zfwf is negative add flux at specified runoff points and subtract from fluxes for global redistribution.
+         !    Where positive leave in global redistribution total.
+         !
+         DO jcr = 1, jncsr
+            !
+            ztmp2d(:,:) = 0.e0_wp
+            WHERE( closea_mask_rnf(:,:) == jcr .and. closea_mask(:,:) > 0 ) ztmp2d(:,:) = e1e2t(:,:) * ( emp(:,:)-rnf(:,:) ) * tmask_i(:,:)
+            zfwfr(jcr) = glob_sum( 'closea', ztmp2d(:,:) )
+            !
+            ! The following if avoids the redistribution of the round off
+            IF ( ABS(zfwfr(jcr) / surf(jncs+1) ) > rsmall) THEN
+               !
+               ! Add residuals to target runoff points if negative and subtract from total to be added globally
+               IF( zfwfr(jcr) < 0.0 ) THEN 
+                  zfwf_total = zfwf_total - zfwfr(jcr)
+                  zcoef    = zfwfr(jcr) / surfr(jcr)
+                  zcoef1   = rcp * zcoef
+                  WHERE( closea_mask_rnf(:,:) == jcr .and. closea_mask(:,:) == 0.0)
+                     emp(:,:) = emp(:,:) + zcoef
+                     qns(:,:) = qns(:,:) - zcoef1 * sst_m(:,:)
+                  ENDWHERE
+               ENDIF
+               !
+            ENDIF
+         END DO
+      ENDIF  ! jncsr > 0    
+      !
+      zfwfe(:) = 0.e0_wp           
+      IF( jncse > 0 ) THEN
+         !
+         ! 3. Work out total fluxes over empmr source areas and add to empmr target areas. 
+         !
+         DO jce = 1, jncse
+            !
+            ztmp2d(:,:) = 0.e0_wp
+            WHERE( closea_mask_empmr(:,:) == jce .and. closea_mask(:,:) > 0 ) ztmp2d(:,:) = e1e2t(:,:) * ( emp(:,:)-rnf(:,:) ) * tmask_i(:,:)
+            zfwfe(jce) = glob_sum( 'closea', ztmp2d(:,:) )
+            !
+            ! The following if avoids the redistribution of the round off
+            IF ( ABS( zfwfe(jce) / surf(jncs+1) ) > rsmall ) THEN
+               !
+               ! Add residuals to runoff points and subtract from total to be added globally
+               zfwf_total = zfwf_total - zfwfe(jce)
+               zcoef    = zfwfe(jce) / surfe(jce)
+               zcoef1   = rcp * zcoef
+               WHERE( closea_mask_empmr(:,:) == jce .and. closea_mask(:,:) == 0.0)
+                  emp(:,:) = emp(:,:) + zcoef
+                  qns(:,:) = qns(:,:) - zcoef1 * sst_m(:,:)
+               ENDWHERE
+               !
+            ENDIF
+         END DO
+      ENDIF ! jncse > 0    
+
+      !
+      ! 4. Spread residual flux over global ocean. 
+      !
+      ! The following if avoids the redistribution of the round off
+      IF ( ABS(zfwf_total / surf(jncs+1) ) > rsmall) THEN
+         zcoef    = zfwf_total / surf(jncs+1)
+         zcoef1   = rcp * zcoef
+         WHERE( closea_mask(:,:) == 0 )
+            emp(:,:) = emp(:,:) + zcoef
+            qns(:,:) = qns(:,:) - zcoef1 * sst_m(:,:)
+         ENDWHERE
+      ENDIF
+
+      !
+      ! 5. Subtract area means from emp (and qns) over closed seas to give zero mean FW flux over each sea.
+      !
+      DO jc = 1, jncs
+         ! The following if avoids the redistribution of the round off
+         IF ( ABS(zfwf(jc) / surf(jncs+1) ) > rsmall) THEN
+            !
+            ! Subtract residuals from fluxes over closed sea
+            zcoef    = zfwf(jc) / surf(jc)
+            zcoef1   = rcp * zcoef
+            WHERE( closea_mask(:,:) == jc )
+               emp(:,:) = emp(:,:) - zcoef
+               qns(:,:) = qns(:,:) + zcoef1 * sst_m(:,:)
+            ENDWHERE
+            !
+         ENDIF
+      END DO
+      !
+      emp (:,:) = emp (:,:) * tmask(:,:,1)
+      !
+      CALL lbc_lnk( 'closea', emp , 'T', 1._wp )
+      !
+   END SUBROUTINE sbc_clo
+
+   SUBROUTINE clo_rnf( p_rnfmsk )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_rnf  ***
+      !!                    
+      !! ** Purpose :   allow the treatment of closed sea outflow grid-points
+      !!                to be the same as river mouth grid-points
+      !!
+      !! ** Method  :   set to 1 the runoff mask (mskrnf, see sbcrnf module)
+      !!                at the closed sea outflow grid-point.
+      !!
+      !! ** Action  :   update (p_)mskrnf (set 1 at closed sea outflow)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   p_rnfmsk   ! river runoff mask (rnfmsk array)
+      !!----------------------------------------------------------------------
+      !
+      IF( jncsr > 0 ) THEN
+         WHERE( closea_mask_rnf(:,:) > 0 .and. closea_mask(:,:) == 0 )
+            p_rnfmsk(:,:) = MAX( p_rnfmsk(:,:), 1.0_wp )
+         ENDWHERE
+      ENDIF
+      !
+      IF( jncse > 0 ) THEN
+         WHERE( closea_mask_empmr(:,:) > 0 .and. closea_mask(:,:) == 0 )
+            p_rnfmsk(:,:) = MAX( p_rnfmsk(:,:), 1.0_wp )
+         ENDWHERE
+      ENDIF
+      !
+   END SUBROUTINE clo_rnf
+   
+      
+   SUBROUTINE clo_bat( k_top, k_bot )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE clo_bat  ***
+      !!                    
+      !! ** Purpose :   Suppress closed sea from the domain
+      !!
+      !! ** Method  :   Read in closea_mask field (if it exists) from domain_cfg file.
+      !!                Where closea_mask > 0 set first and last ocean level to 0
+      !!                (As currently coded you can't define a closea_mask field in 
+      !!                usr_def_zgr).
+      !!
+      !! ** Action  :   set k_top=0 and k_bot=0 over closed seas
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:,:), INTENT(inout) ::   k_top, k_bot   ! ocean first and last level indices
+      INTEGER                           :: inum, id
+      INTEGER,  DIMENSION(jpi,jpj) :: closea_mask ! closea_mask field
+      REAL(wp), DIMENSION(jpi,jpj) :: zdata_in ! temporary real array for input
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                     ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'clo_bat : suppression of closed seas'
+         WRITE(numout,*) '~~~~~~~'
+      ENDIF
+      !
+      IF( ln_read_cfg ) THEN
+         !
+         CALL iom_open( cn_domcfg, inum )
+         !
+         id = iom_varid(inum, 'closea_mask', ldstop = .false.)      
+         IF( id > 0 ) THEN
+            IF( lwp ) WRITE(numout,*) 'Suppressing closed seas in bathymetry based on closea_mask field,'
+            CALL iom_get ( inum, jpdom_data, 'closea_mask', zdata_in )
+            closea_mask(:,:) = NINT(zdata_in(:,:))
+            WHERE( closea_mask(:,:) > 0 )
+               k_top(:,:) = 0   
+               k_bot(:,:) = 0   
+            ENDWHERE
+         ELSE
+            IF( lwp ) WRITE(numout,*) 'No closea_mask field found in domain_cfg file. No suppression of closed seas.'
+         ENDIF
+         !
+         CALL iom_close(inum)
+         !
+      ELSE
+         IF( lwp ) WRITE(numout,*) 'No domain_cfg file => no suppression of closed seas.'
+      ENDIF
+      !
+      ! Initialise l_sbc_clo and l_clo_rnf for this case (ln_closea=.false.)
+      l_sbc_clo = .false.
+      l_clo_rnf = .false.
+      !
+   END SUBROUTINE clo_bat
+
+   !!======================================================================
+END MODULE closea
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/daymod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/daymod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/daymod.F90	(revision 14097)
@@ -0,0 +1,421 @@
+MODULE daymod
+   !!======================================================================
+   !!                       ***  MODULE  daymod  ***
+   !! Ocean :   management of the model calendar
+   !!=====================================================================
+   !! History :  OPA  ! 1994-09  (M. Pontaud M. Imbard)  Original code
+   !!                 ! 1997-03  (O. Marti)
+   !!                 ! 1997-05  (G. Madec)
+   !!                 ! 1997-08  (M. Imbard)
+   !!   NEMO     1.0  ! 2003-09  (G. Madec)  F90 + nyear, nmonth, nday
+   !!                 ! 2004-01  (A.M. Treguier) new calculation based on adatrj
+   !!                 ! 2006-08  (G. Madec)  surface module major update
+   !!                 ! 2015-11  (D. Lea) Allow non-zero initial time of day
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   day        : calendar
+   !!----------------------------------------------------------------------
+   !!                    ----------- WARNING -----------
+   !!                    -------------------------------
+   !!   sbcmod assume that the time step is dividing the number of second of 
+   !!   in a day, i.e. ===> MOD( rday, rdt ) == 0 
+   !!   except when user defined forcing is used (see sbcmod.F90)
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ioipsl  , ONLY :   ymds2ju      ! for calendar
+   USE trc_oce , ONLY :   l_offline   ! offline flag
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE iom            !
+   USE timing         ! Timing
+   USE restart        ! restart
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   day        ! called by step.F90
+   PUBLIC   day_init   ! called by istate.F90
+   PUBLIC   day_mth    ! Needed by TAM
+
+   INTEGER, PUBLIC ::   nsecd, nsecd05, ndt, ndt05   !: (PUBLIC for TAM)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE day_init
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE day_init  ***
+      !!
+      !! ** Purpose :   Initialization of the calendar values to their values 1 time step before nit000
+      !!                because day will be called at the beginning of step
+      !!
+      !! ** Action  : - nyear        : current year
+      !!              - nmonth       : current month of the year nyear
+      !!              - nday         : current day of the month nmonth
+      !!              - nday_year    : current day of the year nyear
+      !!              - nsec_year    : current time step counted in second since 00h jan 1st of the current year
+      !!              - nsec_month   : current time step counted in second since 00h 1st day of the current month
+      !!              - nsec_day     : current time step counted in second since 00h of the current day
+      !!              - nsec1jan000  : second since Jan. 1st 00h of nit000 year and Jan. 1st 00h of the current year
+      !!              - nmonth_len, nyear_len, nmonth_half, nmonth_end through day_mth
+      !!----------------------------------------------------------------------
+      INTEGER  ::   inbday, idweek   ! local integers
+      REAL(wp) ::   zjul             ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      ! max number of seconds between each restart
+      IF( REAL( nitend - nit000 + 1 ) * rdt > REAL( HUGE( nsec1jan000 ) ) ) THEN
+         CALL ctl_stop( 'The number of seconds between each restart exceeds the integer 4 max value: 2^31-1. ',   &
+            &           'You must do a restart at higher frequency (or remove this stop and recompile the code in I8)' )
+      ENDIF
+      nsecd   = NINT( rday       )
+      nsecd05 = NINT( 0.5 * rday )
+      ndt     = NINT(       rdt  )
+      ndt05   = NINT( 0.5 * rdt  )
+
+      IF( .NOT. l_offline )   CALL day_rst( nit000, 'READ' )
+
+      ! set the calandar from ndastp (read in restart file and namelist)
+      nyear   =   ndastp / 10000
+      nmonth  = ( ndastp - (nyear * 10000) ) / 100
+      nday    =   ndastp - (nyear * 10000) - ( nmonth * 100 )
+
+      nhour   =   nn_time0 / 100
+      nminute = ( nn_time0 - nhour * 100 )
+
+      CALL ymds2ju( nyear, nmonth, nday, nhour*3600._wp+nminute*60._wp, fjulday )  
+      IF( ABS(fjulday - REAL(NINT(fjulday),wp)) < 0.1 / rday )   fjulday = REAL(NINT(fjulday),wp)   ! avoid truncation error
+      IF( nhour*3600 + nminute*60 - ndt05 .lt. 0 ) fjulday = fjulday + 1.                    ! move back to the day at nit000 (and not at nit000 - 1)
+      
+      nsec1jan000 = 0
+      CALL day_mth
+
+      IF ( nday == 0 ) THEN     !   for ex if ndastp = ndate0 - 1
+         nmonth = nmonth - 1
+         nday = nmonth_len(nmonth)
+      ENDIF
+      IF ( nmonth == 0 ) THEN   ! go at the end of previous year
+         nmonth = 12
+         nyear = nyear - 1
+         nsec1jan000 = nsec1jan000 - nsecd * nyear_len(0)
+         IF( nleapy == 1 )   CALL day_mth
+      ENDIF
+
+      ! day since january 1st
+      nday_year = nday + SUM( nmonth_len(1:nmonth - 1) )
+
+      !compute number of days between last monday and today
+      CALL ymds2ju( 1900, 01, 01, 0.0, zjul )  ! compute julian day value of 01.01.1900 (our reference that was a Monday)
+      inbday = FLOOR(fjulday - zjul)            ! compute nb day between  01.01.1900 and start of current day
+      idweek = MOD(inbday, 7)                  ! compute nb day between last monday and current day
+      IF (idweek .lt. 0) idweek=idweek+7       ! Avoid negative values for dates before 01.01.1900
+
+      ! number of seconds since the beginning of current year/month/week/day at the middle of the time-step
+      IF (nhour*3600+nminute*60-ndt05 .gt. 0) THEN
+         ! 1 timestep before current middle of first time step is still the same day
+         nsec_year  = (nday_year-1) * nsecd + nhour*3600+nminute*60 - ndt05 
+         nsec_month = (nday-1)      * nsecd + nhour*3600+nminute*60 - ndt05    
+      ELSE
+         ! 1 time step before the middle of the first time step is the previous day 
+         nsec_year  = nday_year * nsecd + nhour*3600+nminute*60 - ndt05 
+         nsec_month = nday      * nsecd + nhour*3600+nminute*60 - ndt05   
+      ENDIF
+      nsec_week  = idweek    * nsecd + nhour*3600+nminute*60 - ndt05
+      nsec_day   =             nhour*3600+nminute*60 - ndt05 
+      IF( nsec_day .lt. 0 ) nsec_day = nsec_day + nsecd
+      IF( nsec_week .lt. 0 ) nsec_week = nsec_week + nsecd*7
+
+      ! control print
+      IF(lwp) WRITE(numout,'(a,i6,a,i2,a,i2,a,i8,a,i8,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, '  &
+           &                   nsec_month:', nsec_month , '  nsec_year:' , nsec_year
+
+      ! Up to now, calendar parameters are related to the end of previous run (nit000-1)
+      ! call day to set the calendar parameters at the begining of the current simulaton. needed by iom_init
+      CALL day( nit000 )
+      !
+      IF( lwxios ) THEN
+! define variables in restart file when writing with XIOS
+          CALL iom_set_rstw_var_active('kt')
+          CALL iom_set_rstw_var_active('ndastp')
+          CALL iom_set_rstw_var_active('adatrj')
+          CALL iom_set_rstw_var_active('ntime')
+      ENDIF
+
+   END SUBROUTINE day_init
+
+
+   SUBROUTINE day_mth
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE day_init  ***
+      !!
+      !! ** Purpose :   calendar values related to the months
+      !!
+      !! ** Action  : - nmonth_len    : length in days of the months of the current year
+      !!              - nyear_len     : length in days of the previous/current year
+      !!              - nmonth_half   : second since the beginning of the year and the halft of the months
+      !!              - nmonth_end    : second since the beginning of the year and the end of the months
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jm               ! dummy loop indice
+      !!----------------------------------------------------------------------
+
+      ! length of the month of the current year (from nleapy, read in namelist)
+      IF ( nleapy < 2 ) THEN
+         nmonth_len(:) = (/ 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31 /)
+         nyear_len(:) = 365
+         IF ( nleapy == 1 ) THEN   ! we are using calandar with leap years
+            IF ( MOD(nyear-1, 4) == 0 .AND. ( MOD(nyear-1, 400) == 0 .OR. MOD(nyear-1, 100) /= 0 ) ) THEN
+               nyear_len(0)  = 366
+            ENDIF
+            IF ( MOD(nyear  , 4) == 0 .AND. ( MOD(nyear  , 400) == 0 .OR. MOD(nyear  , 100) /= 0 ) ) THEN
+               nmonth_len(2) = 29
+               nyear_len(1)  = 366
+            ENDIF
+            IF ( MOD(nyear+1, 4) == 0 .AND. ( MOD(nyear+1, 400) == 0 .OR. MOD(nyear+1, 100) /= 0 ) ) THEN
+               nyear_len(2)  = 366
+            ENDIF
+         ENDIF
+      ELSE
+         nmonth_len(:) = nleapy   ! all months with nleapy days per year
+         nyear_len(:) = 12 * nleapy
+      ENDIF
+
+      ! half month in second since the begining of the year:
+      ! time since Jan 1st   0     1     2    ...    11    12    13
+      !          ---------*--|--*--|--*--| ... |--*--|--*--|--*--|--------------------------------------
+      !                 <---> <---> <--->  ...  <---> <---> <--->
+      ! month number      0     1     2    ...    11    12    13
+      !
+      ! nmonth_half(jm) = rday * REAL( 0.5 * nmonth_len(jm) + SUM(nmonth_len(1:jm-1)) )
+      nmonth_half(0) = - nsecd05 * nmonth_len(0)
+      DO jm = 1, 13
+         nmonth_half(jm) = nmonth_half(jm-1) + nsecd05 * ( nmonth_len(jm-1) + nmonth_len(jm) )
+      END DO
+
+      nmonth_end(0) = 0
+      DO jm = 1, 13
+         nmonth_end(jm) = nmonth_end(jm-1) + nsecd * nmonth_len(jm)
+      END DO
+      !
+   END SUBROUTINE
+
+
+   SUBROUTINE day( kt )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE day  ***
+      !!
+      !! ** Purpose :   Compute the date with a day iteration IF necessary.
+      !!
+      !! ** Method  : - ???
+      !!
+      !! ** Action  : - nyear     : current year
+      !!              - nmonth    : current month of the year nyear
+      !!              - nday      : current day of the month nmonth
+      !!              - nday_year : current day of the year nyear
+      !!              - ndastp    : = nyear*10000 + nmonth*100 + nday
+      !!              - adatrj    : date in days since the beginning of the run
+      !!              - nsec_year : current time of the year (in second since 00h, jan 1st)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt        ! ocean time-step indices
+      !
+      CHARACTER (len=25) ::   charout
+      REAL(wp)           ::   zprec      ! fraction of day corresponding to 0.1 second
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('day')
+      !
+      zprec = 0.1 / rday
+      !                                                 ! New time-step
+      nsec_year  = nsec_year  + ndt
+      nsec_month = nsec_month + ndt
+      nsec_week  = nsec_week  + ndt
+      nsec_day   = nsec_day   + ndt
+      adatrj  = adatrj  + rdt / rday
+      fjulday = fjulday + rdt / rday
+      IF( ABS(fjulday - REAL(NINT(fjulday),wp)) < zprec )   fjulday = REAL(NINT(fjulday),wp)   ! avoid truncation error
+      IF( ABS(adatrj  - REAL(NINT(adatrj ),wp)) < zprec )   adatrj  = REAL(NINT(adatrj ),wp)   ! avoid truncation error
+
+      IF( nsec_day > nsecd ) THEN                       ! New day
+         !
+         nday      = nday + 1
+         nday_year = nday_year + 1
+         nsec_day  = ndt05
+         !
+         IF( nday == nmonth_len(nmonth) + 1 ) THEN      ! New month
+            nday   = 1
+            nmonth = nmonth + 1
+            nsec_month = ndt05
+            IF( nmonth == 13 ) THEN                     ! New year
+               nyear     = nyear + 1
+               nmonth    = 1
+               nday_year = 1
+               nsec_year = ndt05
+               nsec1jan000 = nsec1jan000 + nsecd * nyear_len(1)
+               IF( nleapy == 1 )   CALL day_mth
+            ENDIF
+         ENDIF
+         !
+         ndastp = nyear * 10000 + nmonth * 100 + nday   ! New date
+         !
+         !compute first day of the year in julian days
+         CALL ymds2ju( nyear, 01, 01, 0.0, fjulstartyear )
+         !
+         IF(lwp) WRITE(numout,'(a,i8,a,i4.4,a,i2.2,a,i2.2,a,i3.3)') '======>> time-step =', kt,   &
+              &   '      New day, DATE Y/M/D = ', nyear, '/', nmonth, '/', nday, '      nday_year = ', nday_year
+         IF(lwp) WRITE(numout,'(a,i8,a,i7,a,i5)') '         nsec_year = ', nsec_year,   &
+              &   '   nsec_month = ', nsec_month, '   nsec_day = ', nsec_day, '   nsec_week = ', nsec_week
+      ENDIF
+
+      IF( nsec_week > 7*nsecd )   nsec_week = ndt05     ! New week
+
+      IF(ln_ctl) THEN
+         WRITE(charout,FMT="('kt =', I4,'  d/m/y =',I2,I2,I4)") kt, nday, nmonth, nyear
+         CALL prt_ctl_info(charout)
+      ENDIF
+
+      IF( .NOT. l_offline ) CALL rst_opn( kt )               ! Open the restart file if needed and control lrst_oce
+      IF( lrst_oce         ) CALL day_rst( kt, 'WRITE' )      ! write day restart information
+      !
+      IF( ln_timing )   CALL timing_stop('day')
+      !
+   END SUBROUTINE day
+
+
+   SUBROUTINE day_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE day_rst  ***
+      !!
+      !!  ** Purpose : Read or write calendar in restart file:
+      !!
+      !!  WRITE(READ) mode:
+      !!       kt        : number of time step since the begining of the experiment at the
+      !!                   end of the current(previous) run
+      !!       adatrj(0) : number of elapsed days since the begining of the experiment at the
+      !!                   end of the current(previous) run (REAL -> keep fractions of day)
+      !!       ndastp    : date at the end of the current(previous) run (coded as yyyymmdd integer)
+      !!
+      !!   According to namelist parameter nrstdt,
+      !!       nrstdt = 0  no control on the date (nit000 is  arbitrary).
+      !!       nrstdt = 1  we verify that nit000 is equal to the last
+      !!                   time step of previous run + 1.
+      !!       In both those options, the  exact duration of the experiment
+      !!       since the beginning (cumulated duration of all previous restart runs)
+      !!       is not stored in the restart and is assumed to be (nit000-1)*rdt.
+      !!       This is valid is the time step has remained constant.
+      !!
+      !!       nrstdt = 2  the duration of the experiment in days (adatrj)
+      !!                    has been stored in the restart file.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      !
+      REAL(wp) ::   zkt, zndastp, zdayfrac, ksecs, ktime
+      INTEGER  ::   ihour, iminute
+      !!----------------------------------------------------------------------
+
+      IF( TRIM(cdrw) == 'READ' ) THEN
+
+         IF( iom_varid( numror, 'kt', ldstop = .FALSE. ) > 0 ) THEN
+            ! Get Calendar informations
+            CALL iom_get( numror, 'kt', zkt, ldxios = lrxios )   ! last time-step of previous run
+            IF(lwp) THEN
+               WRITE(numout,*) ' *** Info read in restart : '
+               WRITE(numout,*) '   previous time-step                               : ', NINT( zkt )
+               WRITE(numout,*) ' *** restart option'
+               SELECT CASE ( nrstdt )
+               CASE ( 0 )   ;   WRITE(numout,*) ' nrstdt = 0 : no control of nit000'
+               CASE ( 1 )   ;   WRITE(numout,*) ' nrstdt = 1 : no control the date at nit000 (use ndate0 read in the namelist)'
+               CASE ( 2 )   ;   WRITE(numout,*) ' nrstdt = 2 : calendar parameters read in restart'
+               END SELECT
+               WRITE(numout,*)
+            ENDIF
+            ! Control of date
+            IF( nit000 - NINT( zkt ) /= 1 .AND. nrstdt /= 0 )                                         &
+                 &   CALL ctl_stop( ' ===>>>> : problem with nit000 for the restart',                 &
+                 &                  ' verify the restart file or rerun with nrstdt = 0 (namelist)' )
+            ! define ndastp and adatrj
+            IF ( nrstdt == 2 ) THEN
+               ! read the parameters corresponding to nit000 - 1 (last time step of previous run)
+               CALL iom_get( numror, 'ndastp', zndastp, ldxios = lrxios )
+               ndastp = NINT( zndastp )
+               CALL iom_get( numror, 'adatrj', adatrj , ldxios = lrxios )
+	       CALL iom_get( numror, 'ntime' , ktime  , ldxios = lrxios )
+	       nn_time0=INT(ktime)
+               ! calculate start time in hours and minutes
+	       zdayfrac=adatrj-INT(adatrj)
+	       ksecs = NINT(zdayfrac*86400)	       ! Nearest second to catch rounding errors in adatrj	       
+	       ihour = INT(ksecs/3600)
+	       iminute = ksecs/60-ihour*60
+ 	        
+               ! Add to nn_time0
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+	       nminute=nminute+iminute
+	       
+	       IF( nminute >= 60 ) THEN
+	          nminute=nminute-60
+		  nhour=nhour+1
+	       ENDIF
+	       nhour=nhour+ihour
+	       IF( nhour >= 24 ) THEN
+		  nhour=nhour-24
+	          adatrj=adatrj+1
+	       ENDIF	       
+	       nn_time0 = nhour * 100 + nminute
+	       adatrj = INT(adatrj)                    ! adatrj set to integer as nn_time0 updated	       
+            ELSE
+               ! parameters corresponding to nit000 - 1 (as we start the step loop with a call to day)
+               ndastp = ndate0        ! ndate0 read in the namelist in dom_nam
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+               IF( nhour*3600+nminute*60-ndt05 .lt. 0 )  ndastp=ndastp-1      ! Start hour is specified in the namelist (default 0)
+               adatrj = ( REAL( nit000-1, wp ) * rdt ) / rday
+               ! note this is wrong if time step has changed during run
+            ENDIF
+         ELSE
+            ! parameters corresponding to nit000 - 1 (as we start the step loop with a call to day)
+            ndastp = ndate0           ! ndate0 read in the namelist in dom_nam
+            nhour   =   nn_time0 / 100
+	    nminute = ( nn_time0 - nhour * 100 )
+            IF( nhour*3600+nminute*60-ndt05 .lt. 0 )  ndastp=ndastp-1      ! Start hour is specified in the namelist (default 0)
+            adatrj = ( REAL( nit000-1, wp ) * rdt ) / rday
+         ENDIF
+         IF( ABS(adatrj  - REAL(NINT(adatrj),wp)) < 0.1 / rday )   adatrj = REAL(NINT(adatrj),wp)   ! avoid truncation error
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) ' *** Info used values : '
+            WRITE(numout,*) '   date ndastp                                      : ', ndastp
+            WRITE(numout,*) '   number of elapsed days since the begining of run : ', adatrj
+	    WRITE(numout,*) '   nn_time0                                         : ',nn_time0
+            WRITE(numout,*)
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
+         !
+         IF( kt == nitrst ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'rst_write : write oce restart file  kt =', kt
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         ! calendar control
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'kt'     , REAL( kt    , wp)  , ldxios = lwxios )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrow, 'ndastp' , REAL( ndastp, wp)  , ldxios = lwxios )   ! date
+         CALL iom_rstput( kt, nitrst, numrow, 'adatrj' , adatrj             , ldxios = lwxios            )   ! number of elapsed days since
+         !                                                                                                   ! the begining of the run [s]
+         CALL iom_rstput( kt, nitrst, numrow, 'ntime'  , REAL( nn_time0, wp), ldxios = lwxios ) ! time
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE day_rst
+
+   !!======================================================================
+END MODULE daymod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/depth_e3.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/depth_e3.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/depth_e3.F90	(revision 14097)
@@ -0,0 +1,164 @@
+MODULE depth_e3
+   !!======================================================================
+   !!                       ***  MODULE  depth_e3  ***
+   !!
+   !! zgr : vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-11  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   depth_to_e3   : use the depth of t- and w-points to calculate e3t & e3w
+   !!                   (generic interface for 1D and 3D fields)
+   !!   e3_to_depth   : use e3t & e3w to calculate the depth of t- and w-points
+   !!                   (generic interface for 1D and 3D fields)
+   !!---------------------------------------------------------------------
+   USE oce               ! ocean variables
+   USE dom_oce           ! ocean domain
+   !
+   USE in_out_manager    ! I/O manager
+   USE lbclnk            ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp           ! distributed memory computing library
+   USE timing            ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+  
+   INTERFACE depth_to_e3
+      MODULE PROCEDURE depth_to_e3_1d, depth_to_e3_3d
+   END INTERFACE
+
+   INTERFACE e3_to_depth
+      MODULE PROCEDURE e3_to_depth_1d, e3_to_depth_3d
+   END INTERFACE
+
+   PUBLIC   depth_to_e3        ! called by usrdef_zgr
+   PUBLIC   e3_to_depth        ! called by domzgr.F90
+      
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE depth_to_e3_1d( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE depth_to_e3_1d  ***
+      !!
+      !! ** Purpose :   compute e3t & e3w scale factors from t- & w-depths of model levels
+      !!
+      !! ** Method  :   The scale factors are given by the discrete derivative 
+      !!              of the depth:
+      !!                               e3w(jk) = dk[ dept_1d ] 
+      !!                               e3t(jk) = dk[ depw_1d ]
+      !!              with, at top and bottom :
+      !!                      e3w( 1 ) = 2 * ( dept( 1 ) - depw( 1 ) )
+      !!                      e3t(jpk) = 2 * ( dept(jpk) - depw(jpk) )   
+      !!
+      !! ** Action  : - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   pdept_1d, pdepw_1d   ! depths          [m]
+      REAL(wp), DIMENSION(:), INTENT(  out) ::   pe3t_1d , pe3w_1d    ! e3.=dk[depth]   [m]
+      !
+      INTEGER  ::   jk           ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      ! use pdep. at w- and t-points to compute e3. (e3. = dk[depth])
+      !
+      pe3w_1d( 1 ) = 2._wp * ( pdept_1d(1) - pdepw_1d(1) ) 
+      DO jk = 1, jpkm1
+         pe3w_1d(jk+1) = pdept_1d(jk+1) - pdept_1d(jk) 
+         pe3t_1d(jk  ) = pdepw_1d(jk+1) - pdepw_1d(jk) 
+      END DO
+      pe3t_1d(jpk) = 2._wp * ( pdept_1d(jpk) - pdepw_1d(jpk) )
+      !
+   END SUBROUTINE depth_to_e3_1d
+   
+      
+   SUBROUTINE depth_to_e3_3d( pdept_3d, pdepw_3d, pe3t_3d, pe3w_3d )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE depth_to_e3_3d  ***
+      !!
+      !! ** Purpose :   compute e3t & e3w scale factors from t- & w-depths of model levels
+      !!
+      !! ** Method  :   The scale factors are given by the discrete derivative 
+      !!              of the depth:
+      !!                               e3w(jk) = dk[ dept_1d ] 
+      !!                               e3t(jk) = dk[ depw_1d ]
+      !!              with, at top and bottom :
+      !!                      e3w( 1 ) = 2 * ( dept( 1 ) - depw( 1 ) )
+      !!                      e3t(jpk) = 2 * ( dept(jpk) - depw(jpk) )   
+      !!
+      !! ** Action  : - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdept_3d, pdepw_3d   ! depth           [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t_3d , pe3w_3d    ! e3.=dk[depth]   [m]
+      !
+      INTEGER  ::   jk           ! dummy loop indices
+      !!----------------------------------------------------------------------      
+      pe3w_3d(:,:, 1 ) = 2._wp * ( pdept_3d(:,:,1) - pdepw_3d(:,:,1) ) 
+      DO jk = 1, jpkm1
+         pe3w_3d(:,:,jk+1) = pdept_3d(:,:,jk+1) - pdept_3d(:,:,jk) 
+         pe3t_3d(:,:,jk  ) = pdepw_3d(:,:,jk+1) - pdepw_3d(:,:,jk) 
+      END DO
+      pe3t_3d(:,:,jpk) = 2._wp * ( pdept_3d(:,:,jpk) - pdepw_3d(:,:,jpk) )   
+      !
+   END SUBROUTINE depth_to_e3_3d
+
+
+   SUBROUTINE e3_to_depth_1d( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE e3_to_depth_1d  ***
+      !!
+      !! ** Purpose :   compute t- & w-depths of model levels from e3t & e3w scale factors
+      !!
+      !! ** Method  :   The t- & w-depth are given by the summation of e3w & e3t, resp. 
+      !!
+      !! ** Action  : - pe3t_1d, pe3w_1d : scale factor of t- and w-point (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(in   ) ::   pe3t_1d , pe3w_1d    ! vert. scale factors   [m]
+      REAL(wp), DIMENSION(:), INTENT(  out) ::   pdept_1d, pdepw_1d   ! depth = SUM( e3 )     [m]
+      !
+      INTEGER  ::   jk           ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      pdepw_1d(1) = 0.0_wp
+      pdept_1d(1) = 0.5_wp * pe3w_1d(1)
+      DO jk = 2, jpk
+         pdepw_1d(jk) = pdepw_1d(jk-1) + pe3t_1d(jk-1) 
+         pdept_1d(jk) = pdept_1d(jk-1) + pe3w_1d(jk  ) 
+      END DO
+      !
+   END SUBROUTINE e3_to_depth_1d
+   
+      
+   SUBROUTINE e3_to_depth_3d( pe3t_3d, pe3w_3d, pdept_3d, pdepw_3d )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE e3_to_depth_3d  ***
+      !!
+      !! ** Purpose :   compute t- & w-depths of model levels from e3t & e3w scale factors
+      !!
+      !! ** Method  :   The t- & w-depth are given by the summation of e3w & e3t, resp. 
+      !!
+      !! ** Action  : - pe3t_1d, pe3w_1d : scale factor of t- and w-point (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pe3t_3d , pe3w_3d    ! vert. scale factors   [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept_3d, pdepw_3d   ! depth = SUM( e3 )     [m]
+      !
+      INTEGER  ::   jk           ! dummy loop indices
+      !!----------------------------------------------------------------------      
+      !
+      pdepw_3d(:,:,1) = 0.0_wp
+      pdept_3d(:,:,1) = 0.5_wp * pe3w_3d(:,:,1)
+      DO jk = 2, jpk
+         pdepw_3d(:,:,jk) = pdepw_3d(:,:,jk-1) + pe3t_3d(:,:,jk-1) 
+         pdept_3d(:,:,jk) = pdept_3d(:,:,jk-1) + pe3w_3d(:,:,jk  ) 
+      END DO
+      !
+   END SUBROUTINE e3_to_depth_3d
+
+   !!======================================================================
+END MODULE depth_e3
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dom_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dom_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dom_oce.F90	(revision 14097)
@@ -0,0 +1,302 @@
+MODULE dom_oce
+   !!======================================================================
+   !!                       ***  MODULE dom_oce  ***
+   !!       
+   !! ** Purpose :   Define in memory all the ocean space domain variables
+   !!======================================================================
+   !! History :  1.0  ! 2005-10  (A. Beckmann, G. Madec)  reactivate s-coordinate 
+   !!            3.3  ! 2010-11  (G. Madec) add mbk. arrays associated to the deepest ocean level
+   !!            3.4  ! 2011-01  (A. R. Porter, STFC Daresbury) dynamical allocation
+   !!            3.5  ! 2012     (S. Mocavero, I. Epicoco) Add arrays associated
+   !!                             to the optimization of BDY communications
+   !!            3.7  ! 2015-11  (G. Madec) introduce surface and scale factor ratio
+   !!             -   ! 2015-11  (G. Madec, A. Coward)  time varying zgr by default
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   Agrif_Root    : dummy function used when lk_agrif=F
+   !!   Agrif_CFixed  : dummy function used when lk_agrif=F
+   !!   dom_oce_alloc : dynamical allocation of dom_oce arrays
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+
+   IMPLICIT NONE
+   PUBLIC             ! allows the acces to par_oce when dom_oce is used (exception to coding rules)
+
+   PUBLIC dom_oce_alloc  ! Called from nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! time & space domain namelist
+   !! ----------------------------
+   !                                   !!* Namelist namdom : time & space domain *
+   LOGICAL , PUBLIC ::   ln_linssh      !: =T  linear free surface ==>> model level are fixed in time
+   LOGICAL , PUBLIC ::   ln_meshmask    !: =T  create a mesh-mask file (mesh_mask.nc)
+   REAL(wp), PUBLIC ::   rn_isfhmin     !: threshold to discriminate grounded ice to floating ice
+   REAL(wp), PUBLIC ::   rn_rdt         !: time step for the dynamics and tracer
+   REAL(wp), PUBLIC ::   rn_atfp        !: asselin time filter parameter
+   INTEGER , PUBLIC ::   nn_euler       !: =0 start with forward time step or not (=1)
+   LOGICAL , PUBLIC ::   ln_iscpl       !: coupling with ice sheet
+   LOGICAL , PUBLIC ::   ln_crs         !: Apply grid coarsening to dynamical model output or online passive tracers
+
+   !! Free surface parameters
+   !! =======================
+   LOGICAL , PUBLIC :: ln_dynspg_exp    !: Explicit free surface flag
+   LOGICAL , PUBLIC :: ln_dynspg_ts     !: Split-Explicit free surface flag
+
+   !! Time splitting parameters
+   !! =========================
+   LOGICAL,  PUBLIC :: ln_bt_fw         !: Forward integration of barotropic sub-stepping
+   LOGICAL,  PUBLIC :: ln_bt_av         !: Time averaging of barotropic variables
+   LOGICAL,  PUBLIC :: ln_bt_auto       !: Set number of barotropic iterations automatically
+   INTEGER,  PUBLIC :: nn_bt_flt        !: Filter choice
+   INTEGER,  PUBLIC :: nn_baro          !: Number of barotropic iterations during one baroclinic step (rdt)
+   REAL(wp), PUBLIC :: rn_bt_cmax       !: Maximum allowed courant number (used if ln_bt_auto=T)
+   REAL(wp), PUBLIC :: rn_bt_alpha      !: Time stepping diffusion parameter
+
+
+   !                                   !! old non-DOCTOR names still used in the model
+   REAL(wp), PUBLIC ::   atfp           !: asselin time filter parameter
+   REAL(wp), PUBLIC ::   rdt            !: time step for the dynamics and tracer
+
+   !                                   !!! associated variables
+   INTEGER , PUBLIC ::   neuler         !: restart euler forward option (0=Euler)
+   REAL(wp), PUBLIC ::   r2dt           !: = 2*rdt except at nit000 (=rdt) if neuler=0
+
+   !!----------------------------------------------------------------------
+   !! space domain parameters
+   !!----------------------------------------------------------------------
+   INTEGER, PUBLIC ::   jperio   !: Global domain lateral boundary type (between 0 and 7)
+   !                                !  = 0 closed                 ;   = 1 cyclic East-West
+   !                                !  = 2 cyclic North-South     ;   = 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
+   !                                !  = 7 bi-cyclic East-West AND North-South
+   LOGICAL, PUBLIC ::   l_Iperio, l_Jperio   !   should we explicitely take care I/J periodicity 
+   LOGICAL, PUBLIC ::   l_Westedge, l_Eastedge, l_Northedge, l_Southedge ! flag to detect global domain edges
+                                                                         ! on local domain (needed for AGRIF)
+
+   !                                 !  domain MPP decomposition parameters
+   INTEGER             , PUBLIC ::   nimpp, njmpp     !: i- & j-indexes for mpp-subdomain left bottom
+   INTEGER             , PUBLIC ::   nreci, nrecj     !: overlap region in i and j
+   INTEGER             , PUBLIC ::   nproc            !: number for local processor
+   INTEGER             , PUBLIC ::   narea            !: number for local area
+   INTEGER             , PUBLIC ::   nbondi, nbondj   !: mark of i- and j-direction local boundaries
+   INTEGER, ALLOCATABLE, PUBLIC ::   nbondi_bdy(:)    !: mark i-direction local boundaries for BDY open boundaries
+   INTEGER, ALLOCATABLE, PUBLIC ::   nbondj_bdy(:)    !: mark j-direction local boundaries for BDY open boundaries
+   INTEGER, ALLOCATABLE, PUBLIC ::   nbondi_bdy_b(:)  !: mark i-direction of neighbours local boundaries for BDY open boundaries  
+   INTEGER, ALLOCATABLE, PUBLIC ::   nbondj_bdy_b(:)  !: mark j-direction of neighbours local boundaries for BDY open boundaries  
+
+   INTEGER, PUBLIC ::   npolj             !: north fold mark (0, 3 or 4)
+   INTEGER, PUBLIC ::   nlci, nldi, nlei  !: i-dimensions of the local subdomain and its first and last indoor indices
+   INTEGER, PUBLIC ::   nlcj, nldj, nlej  !: i-dimensions of the local subdomain and its first and last indoor indices
+   INTEGER, PUBLIC ::   noea, nowe        !: index of the local neighboring processors in
+   INTEGER, PUBLIC ::   noso, nono        !: east, west, south and north directions
+   INTEGER, PUBLIC ::   nidom             !: ???
+
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   mig        !: local  ==> global domain i-index
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   mjg        !: local  ==> global domain j-index
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   mi0, mi1   !: global ==> local  domain i-index (mi0=1 and mi1=0 if the global index
+   !                                                                !                                             is not in the local domain)
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   mj0, mj1   !: global ==> local  domain j-index (mj0=1 and mj1=0 if the global index
+   !                                                                !                                             is not in the local domain)
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   nimppt, njmppt   !: i-, j-indexes for each processor
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ibonit, ibonjt   !: i-, j- processor neighbour existence
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   nlcit , nlcjt    !: dimensions of every subdomain
+   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
+
+   !!----------------------------------------------------------------------
+   !! horizontal curvilinear coordinate and scale factors
+   !! ---------------------------------------------------------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   glamt , glamu, glamv , glamf    !: longitude at t, u, v, f-points [degree]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   gphit , gphiu, gphiv , gphif    !: latitude  at t, u, v, f-points [degree]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, TARGET, DIMENSION(:,:) ::   e1t   , e2t  , r1_e1t, r1_e2t   !: t-point horizontal scale factors    [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, TARGET, DIMENSION(:,:) ::   e1u   , e2u  , r1_e1u, r1_e2u   !: horizontal scale factors at u-point [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, TARGET, DIMENSION(:,:) ::   e1v   , e2v  , r1_e1v, r1_e2v   !: horizontal scale factors at v-point [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, TARGET, DIMENSION(:,:) ::   e1f   , e2f  , r1_e1f, r1_e2f   !: horizontal scale factors at f-point [m]
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   e1e2t , r1_e1e2t                !: associated metrics at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   e1e2u , r1_e1e2u , e2_e1u       !: associated metrics at u-point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   e1e2v , r1_e1e2v , e1_e2v       !: associated metrics at v-point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   e1e2f , r1_e1e2f                !: associated metrics at f-point
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE        , DIMENSION(:,:) ::   ff_f  , ff_t                    !: Coriolis factor at f- & t-points  [1/s]
+   !!----------------------------------------------------------------------
+   !! vertical coordinate and scale factors
+   !! ---------------------------------------------------------------------
+   LOGICAL, PUBLIC ::   ln_zco       !: z-coordinate - full step
+   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 
+   !                                                        !  ref.   ! before  !   now   ! after  !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::     e3t_0 ,   e3t_b ,   e3t_n ,  e3t_a   !: t- vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::     e3u_0 ,   e3u_b ,   e3u_n ,  e3u_a   !: u- vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::     e3v_0 ,   e3v_b ,   e3v_n ,  e3v_a   !: v- vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::     e3f_0           ,   e3f_n            !: f- vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::     e3w_0 ,   e3w_b ,   e3w_n            !: w- vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::    e3uw_0 ,  e3uw_b ,  e3uw_n            !: uw-vert. scale factor [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::    e3vw_0 ,  e3vw_b ,  e3vw_n            !: vw-vert. scale factor [m]
+
+   !                                                        !  ref.   ! before  !   now   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gdept_0 , gdept_b , gdept_n   !: t- depth              [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gdepw_0 , gdepw_b , gdepw_n   !: w- depth              [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gde3w_0           , gde3w_n   !: w- depth (sum of e3w) [m]
+   
+   !                                                      !  ref. ! before  !   now   !  after  !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ht_0            ,    ht_n             !: t-depth              [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hu_0  ,    hu_b ,    hu_n ,    hu_a   !: u-depth              [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hv_0  ,    hv_b ,    hv_n ,    hv_a   !: v-depth              [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::           r1_hu_b , r1_hu_n , r1_hu_a   !: inverse of u-depth [1/m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::           r1_hv_b , r1_hv_n , r1_hv_a   !: inverse of v-depth [1/m]
+
+   INTEGER, PUBLIC ::   nla10              !: deepest    W level Above  ~10m (nlb10 - 1)
+   INTEGER, PUBLIC ::   nlb10              !: shallowest W level Bellow ~10m (nla10 + 1) 
+
+   !! 1D reference  vertical coordinate
+   !! =-----------------====------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   gdept_1d, gdepw_1d !: reference depth of t- and w-points (m)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   e3t_1d  , e3w_1d   !: reference vertical scale factors at T- and W-pts (m)
+
+
+   !!----------------------------------------------------------------------
+   !! masks, top and bottom ocean point position
+   !! ---------------------------------------------------------------------
+!!gm Proposition of new name for top/bottom vertical indices
+!   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mtk_t, mtk_u, mtk_v   !: top first wet T-, U-, V-, F-level (ISF)
+!   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mbk_t, mbk_u, mbk_v   !: bottom last wet T-, U- and V-level
+!!gm
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mbkt, mbku, mbkv   !: bottom last wet T-, U- and V-level
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tmask_i            !: interior domain T-point mask
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tmask_h            !: internal domain T-point mask (Figure 8.5 NEMO book)
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   misfdep                 !: top first ocean level             (ISF)
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mikt, miku, mikv, mikf  !: top first wet T-, U-, V-, F-level (ISF)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   risfdep                 !: Iceshelf draft                    (ISF)
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ssmask, ssumask, ssvmask             !: surface mask at T-,U-, V- and F-pts
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:), TARGET :: tmask, umask, vmask, fmask   !: land/ocean mask at T-, U-, V- and F-pts
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:), TARGET :: wmask, wumask, wvmask        !: land/ocean mask at WT-, WU- and WV-pts
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   tpol, fpol          !: north fold mask (jperio= 3 or 4)
+
+   !!----------------------------------------------------------------------
+   !! calendar variables
+   !! ---------------------------------------------------------------------
+   INTEGER , PUBLIC ::   nyear         !: current year
+   INTEGER , PUBLIC ::   nmonth        !: current month
+   INTEGER , PUBLIC ::   nday          !: current day of the month
+   INTEGER , PUBLIC ::   nhour         !: current hour
+   INTEGER , PUBLIC ::   nminute       !: current minute
+   INTEGER , PUBLIC ::   ndastp        !: time step date in yyyymmdd format
+   INTEGER , PUBLIC ::   nday_year     !: current day counted from jan 1st of the current year
+   INTEGER , PUBLIC ::   nsec_year     !: current time step counted in second since 00h jan 1st of the current year
+   INTEGER , PUBLIC ::   nsec_month    !: current time step counted in second since 00h 1st day of the current month
+   INTEGER , PUBLIC ::   nsec_week     !: current time step counted in second since 00h of last monday
+   INTEGER , PUBLIC ::   nsec_day      !: current time step counted in second since 00h of the current day
+   REAL(wp), PUBLIC ::   fjulday       !: current julian day 
+   REAL(wp), PUBLIC ::   fjulstartyear !: first day of the current year in julian days
+   REAL(wp), PUBLIC ::   adatrj        !: number of elapsed days since the begining of the whole simulation
+   !                                   !: (cumulative duration of previous runs that may have used different time-step size)
+   INTEGER , PUBLIC, DIMENSION(0: 2) ::   nyear_len     !: length in days of the previous/current/next year
+   INTEGER , PUBLIC, DIMENSION(0:13) ::   nmonth_len    !: length in days of the months of the current year
+   INTEGER , PUBLIC, DIMENSION(0:13) ::   nmonth_half   !: second since Jan 1st 0h of the current year and the half of the months
+   INTEGER , PUBLIC, DIMENSION(0:13) ::   nmonth_end    !: second since Jan 1st 0h of the current year and the end of the months
+   INTEGER , PUBLIC                  ::   nsec1jan000   !: second since Jan 1st 0h of nit000 year and Jan 1st 0h the current year
+
+   !!----------------------------------------------------------------------
+   !! agrif domain
+   !!----------------------------------------------------------------------
+#if defined key_agrif
+   LOGICAL, PUBLIC, PARAMETER ::   lk_agrif = .TRUE.    !: agrif flag
+#else
+   LOGICAL, PUBLIC, PARAMETER ::   lk_agrif = .FALSE.   !: agrif flag
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if ! defined key_agrif
+   !!----------------------------------------------------------------------
+   !! NOT 'key_agrif'      dummy function                     No AGRIF zoom
+   !!----------------------------------------------------------------------
+   LOGICAL FUNCTION Agrif_Root()
+      Agrif_Root = .TRUE.
+   END FUNCTION Agrif_Root
+
+   CHARACTER(len=3) FUNCTION Agrif_CFixed()
+      Agrif_CFixed = '0' 
+   END FUNCTION Agrif_CFixed
+
+   INTEGER FUNCTION Agrif_Fixed()
+      Agrif_Fixed = 0 
+   END FUNCTION Agrif_Fixed
+#endif
+
+   INTEGER FUNCTION dom_oce_alloc()
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(12) :: ierr
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( mig(jpi), mjg(jpj), STAT=ierr(1) )
+         !
+      ALLOCATE( mi0(jpiglo)   , mi1 (jpiglo),  mj0(jpjglo)   , mj1 (jpjglo) ,     &
+         &      tpol(jpiglo)  , fpol(jpiglo)                                , STAT=ierr(2) )
+         !
+      ALLOCATE( glamt(jpi,jpj) ,    glamu(jpi,jpj) ,  glamv(jpi,jpj) ,  glamf(jpi,jpj) ,     &
+         &      gphit(jpi,jpj) ,    gphiu(jpi,jpj) ,  gphiv(jpi,jpj) ,  gphif(jpi,jpj) ,     &
+         &       e1t (jpi,jpj) ,     e2t (jpi,jpj) , r1_e1t(jpi,jpj) , r1_e2t(jpi,jpj) ,     &
+         &       e1u (jpi,jpj) ,     e2u (jpi,jpj) , r1_e1u(jpi,jpj) , r1_e2u(jpi,jpj) ,     &
+         &       e1v (jpi,jpj) ,     e2v (jpi,jpj) , r1_e1v(jpi,jpj) , r1_e2v(jpi,jpj) ,     &
+         &       e1f (jpi,jpj) ,     e2f (jpi,jpj) , r1_e1f(jpi,jpj) , r1_e2f(jpi,jpj) ,     &
+         &      e1e2t(jpi,jpj) , r1_e1e2t(jpi,jpj)                                     ,     &
+         &      e1e2u(jpi,jpj) , r1_e1e2u(jpi,jpj) , e2_e1u(jpi,jpj)                   ,     &
+         &      e1e2v(jpi,jpj) , r1_e1e2v(jpi,jpj) , e1_e2v(jpi,jpj)                   ,     &
+         &      e1e2f(jpi,jpj) , r1_e1e2f(jpi,jpj)                                     ,     &
+         &      ff_f (jpi,jpj) ,    ff_t (jpi,jpj)                                     , STAT=ierr(3) )
+         !
+      ALLOCATE( gdept_0(jpi,jpj,jpk) , gdepw_0(jpi,jpj,jpk) , gde3w_0(jpi,jpj,jpk) ,      &
+         &      gdept_b(jpi,jpj,jpk) , gdepw_b(jpi,jpj,jpk) ,                             &
+         &      gdept_n(jpi,jpj,jpk) , gdepw_n(jpi,jpj,jpk) , gde3w_n(jpi,jpj,jpk) , STAT=ierr(4) )
+         !
+      ALLOCATE( e3t_0(jpi,jpj,jpk) , e3u_0(jpi,jpj,jpk) , e3v_0(jpi,jpj,jpk) , e3f_0(jpi,jpj,jpk) , e3w_0(jpi,jpj,jpk) ,   &
+         &      e3t_b(jpi,jpj,jpk) , e3u_b(jpi,jpj,jpk) , e3v_b(jpi,jpj,jpk) ,                      e3w_b(jpi,jpj,jpk) ,   & 
+         &      e3t_n(jpi,jpj,jpk) , e3u_n(jpi,jpj,jpk) , e3v_n(jpi,jpj,jpk) , e3f_n(jpi,jpj,jpk) , e3w_n(jpi,jpj,jpk) ,   & 
+         &      e3t_a(jpi,jpj,jpk) , e3u_a(jpi,jpj,jpk) , e3v_a(jpi,jpj,jpk) ,                                             &
+         !                                                          !
+         &      e3uw_0(jpi,jpj,jpk) , e3vw_0(jpi,jpj,jpk) ,         &
+         &      e3uw_b(jpi,jpj,jpk) , e3vw_b(jpi,jpj,jpk) ,         &               
+         &      e3uw_n(jpi,jpj,jpk) , e3vw_n(jpi,jpj,jpk) ,     STAT=ierr(5) )                       
+         !
+      ALLOCATE( ht_0(jpi,jpj) , hu_0(jpi,jpj) , hv_0(jpi,jpj) ,                                           &
+         &                      hu_b(jpi,jpj) , hv_b(jpi,jpj) , r1_hu_b(jpi,jpj) , r1_hv_b(jpi,jpj) ,     &
+         &      ht_n(jpi,jpj) , hu_n(jpi,jpj) , hv_n(jpi,jpj) , r1_hu_n(jpi,jpj) , r1_hv_n(jpi,jpj) ,     &
+         &                      hu_a(jpi,jpj) , hv_a(jpi,jpj) , r1_hu_a(jpi,jpj) , r1_hv_a(jpi,jpj) , STAT=ierr(6)  )
+         !
+         !
+      ALLOCATE( gdept_1d(jpk) , gdepw_1d(jpk) , e3t_1d(jpk) , e3w_1d(jpk) , STAT=ierr(7) )
+         !
+      ALLOCATE( tmask_i(jpi,jpj) , tmask_h(jpi,jpj) ,                        & 
+         &      ssmask (jpi,jpj) , ssumask(jpi,jpj) , ssvmask(jpi,jpj) ,     &
+         &      mbkt   (jpi,jpj) , mbku   (jpi,jpj) , mbkv   (jpi,jpj) , STAT=ierr(9) )
+         !
+      ALLOCATE( misfdep(jpi,jpj) , mikt(jpi,jpj) , miku(jpi,jpj) ,     &
+         &      risfdep(jpi,jpj) , mikv(jpi,jpj) , mikf(jpi,jpj) , STAT=ierr(10) )
+         !
+      ALLOCATE( tmask(jpi,jpj,jpk) , umask(jpi,jpj,jpk) ,     & 
+         &      vmask(jpi,jpj,jpk) , fmask(jpi,jpj,jpk) , STAT=ierr(11) )
+         !
+      ALLOCATE( wmask(jpi,jpj,jpk) , wumask(jpi,jpj,jpk), wvmask(jpi,jpj,jpk) , STAT=ierr(12) )
+      !
+      dom_oce_alloc = MAXVAL(ierr)
+      !
+   END FUNCTION dom_oce_alloc
+
+   !!======================================================================
+END MODULE dom_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domain.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domain.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domain.F90	(revision 14097)
@@ -0,0 +1,715 @@
+MODULE domain
+   !!==============================================================================
+   !!                       ***  MODULE domain   ***
+   !! Ocean initialization : domain initialization
+   !!==============================================================================
+   !! History :  OPA  !  1990-10  (C. Levy - G. Madec)  Original code
+   !!                 !  1992-01  (M. Imbard) insert time step initialization
+   !!                 !  1996-06  (G. Madec) generalized vertical coordinate 
+   !!                 !  1997-02  (G. Madec) creation of domwri.F
+   !!                 !  2001-05  (E.Durand - G. Madec) insert closed sea
+   !!   NEMO     1.0  !  2002-08  (G. Madec)  F90: Free form and module
+   !!            2.0  !  2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            3.3  !  2010-11  (G. Madec)  initialisation in C1D configuration
+   !!            3.6  !  2013     ( J. Simeon, C. Calone, G. Madec, C. Ethe ) Online coarsening of outputs
+   !!            3.7  !  2015-11  (G. Madec, A. Coward)  time varying zgr by default
+   !!            4.0  !  2016-10  (G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+   
+   !!----------------------------------------------------------------------
+   !!   dom_init      : initialize the space and time domain
+   !!   dom_glo       : initialize global domain <--> local domain indices
+   !!   dom_nam       : read and contral domain namelists
+   !!   dom_ctl       : control print for the ocean domain
+   !!   domain_cfg    : read the global domain size in domain configuration file
+   !!   cfg_write     : create the domain configuration file
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! domain: ocean
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE trc_oce        ! shared ocean & passive tracers variab
+   USE phycst         ! physical constants
+   USE closea         ! closed seas
+   USE domhgr         ! domain: set the horizontal mesh
+   USE domzgr         ! domain: set the vertical mesh
+   USE dommsk         ! domain: set the mask system
+   USE domwri         ! domain: write the meshmask file
+   USE domvvl         ! variable volume
+   USE c1d            ! 1D configuration
+   USE dyncor_c1d     ! 1D configuration: Coriolis term    (cor_c1d routine)
+   USE wet_dry,  ONLY : ll_wd
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_init     ! called by nemogcm.F90
+   PUBLIC   domain_cfg   ! called by nemogcm.F90
+
+   !!-------------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!-------------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_init(cdstr)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_init  ***
+      !!                    
+      !! ** Purpose :   Domain initialization. Call the routines that are 
+      !!              required to create the arrays which define the space 
+      !!              and time domain of the ocean model.
+      !!
+      !! ** Method  : - dom_msk: compute the masks from the bathymetry file
+      !!              - dom_hgr: compute or read the horizontal grid-point position
+      !!                         and scale factors, and the coriolis factor
+      !!              - dom_zgr: define the vertical coordinate and the bathymetry
+      !!              - dom_wri: create the meshmask file (ln_meshmask=T)
+      !!              - 1D configuration, move Coriolis, u and v at T-point
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk, ik   ! dummy loop indices
+      INTEGER ::   iconf = 0    ! local integers
+      CHARACTER (len=64) ::   cform = "(A12, 3(A13, I7))" 
+      CHARACTER (len=*), INTENT(IN) :: cdstr                  ! model: NEMO or SAS. Determines core restart variables
+      INTEGER , DIMENSION(jpi,jpj) ::   ik_top , ik_bot       ! top and bottom ocean level
+      REAL(wp), DIMENSION(jpi,jpj) ::   z1_hu_0, z1_hv_0
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN         ! Ocean domain Parameters (control print)
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_init : domain initialization'
+         WRITE(numout,*) '~~~~~~~~'
+         !
+         WRITE(numout,*)     '   Domain info'
+         WRITE(numout,*)     '      dimension of model:'
+         WRITE(numout,*)     '             Local domain      Global domain       Data domain '
+         WRITE(numout,cform) '        ','   jpi     : ', jpi, '   jpiglo  : ', jpiglo
+         WRITE(numout,cform) '        ','   jpj     : ', jpj, '   jpjglo  : ', jpjglo
+         WRITE(numout,cform) '        ','   jpk     : ', jpk, '   jpkglo  : ', jpkglo
+         WRITE(numout,cform) '       ' ,'   jpij    : ', jpij
+         WRITE(numout,*)     '      mpp local domain info (mpp):'
+         WRITE(numout,*)     '              jpni    : ', jpni, '   nn_hls  : ', nn_hls
+         WRITE(numout,*)     '              jpnj    : ', jpnj, '   nn_hls  : ', nn_hls
+         WRITE(numout,*)     '              jpnij   : ', jpnij
+         WRITE(numout,*)     '      lateral boundary of the Global domain : jperio  = ', jperio
+         SELECT CASE ( jperio )
+         CASE( 0 )   ;   WRITE(numout,*) '         (i.e. closed)'
+         CASE( 1 )   ;   WRITE(numout,*) '         (i.e. cyclic east-west)'
+         CASE( 2 )   ;   WRITE(numout,*) '         (i.e. cyclic north-south)'
+         CASE( 3 )   ;   WRITE(numout,*) '         (i.e. north fold with T-point pivot)'
+         CASE( 4 )   ;   WRITE(numout,*) '         (i.e. cyclic east-west and north fold with T-point pivot)'
+         CASE( 5 )   ;   WRITE(numout,*) '         (i.e. north fold with F-point pivot)'
+         CASE( 6 )   ;   WRITE(numout,*) '         (i.e. cyclic east-west and north fold with F-point pivot)'
+         CASE( 7 )   ;   WRITE(numout,*) '         (i.e. cyclic east-west and north-south)'
+         CASE DEFAULT
+            CALL ctl_stop( 'jperio is out of range' )
+         END SELECT
+         WRITE(numout,*)     '      Ocean model configuration used:'
+         WRITE(numout,*)     '         cn_cfg = ', TRIM( cn_cfg ), '   nn_cfg = ', nn_cfg
+      ENDIF
+      nn_wxios = 0
+      ln_xios_read = .FALSE.
+      !
+      !           !==  Reference coordinate system  ==!
+      !
+      CALL dom_glo                     ! global domain versus local domain
+      CALL dom_nam                     ! read namelist ( namrun, namdom )
+      !
+      IF( lwxios ) THEN
+!define names for restart write and set core output (restart.F90)
+         CALL iom_set_rst_vars(rst_wfields)
+         CALL iom_set_rstw_core(cdstr)
+      ENDIF
+!reset namelist for SAS
+      IF(cdstr == 'SAS') THEN
+         IF(lrxios) THEN
+               IF(lwp) write(numout,*) 'Disable reading restart file using XIOS for SAS'
+               lrxios = .FALSE.
+         ENDIF
+      ENDIF
+      !
+      CALL dom_hgr                     ! Horizontal mesh
+      CALL dom_zgr( ik_top, ik_bot )   ! Vertical mesh and bathymetry
+      CALL dom_msk( ik_top, ik_bot )   ! Masks
+      IF( ln_closea )   CALL dom_clo   ! ln_closea=T : closed seas included in the simulation
+                                       ! Read in masks to define closed seas and lakes 
+      !
+      DO jj = 1, jpj                   ! depth of the iceshelves
+         DO ji = 1, jpi
+            ik = mikt(ji,jj)
+            risfdep(ji,jj) = gdepw_0(ji,jj,ik)
+         END DO
+      END DO
+      !
+      ht_0(:,:) = 0._wp  ! Reference ocean thickness
+      hu_0(:,:) = 0._wp
+      hv_0(:,:) = 0._wp
+      DO jk = 1, jpk
+         ht_0(:,:) = ht_0(:,:) + e3t_0(:,:,jk) * tmask(:,:,jk)
+         hu_0(:,:) = hu_0(:,:) + e3u_0(:,:,jk) * umask(:,:,jk)
+         hv_0(:,:) = hv_0(:,:) + e3v_0(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !
+      !           !==  time varying part of coordinate system  ==!
+      !
+      IF( ln_linssh ) THEN       != Fix in time : set to the reference one for all
+      !
+         !       before        !          now          !       after         !
+            gdept_b = gdept_0  ;   gdept_n = gdept_0   !        ---          ! depth of grid-points
+            gdepw_b = gdepw_0  ;   gdepw_n = gdepw_0   !        ---          !
+                                   gde3w_n = gde3w_0   !        ---          !
+         !                                                                  
+              e3t_b =   e3t_0  ;     e3t_n =   e3t_0   ;   e3t_a =  e3t_0    ! scale factors
+              e3u_b =   e3u_0  ;     e3u_n =   e3u_0   ;   e3u_a =  e3u_0    !
+              e3v_b =   e3v_0  ;     e3v_n =   e3v_0   ;   e3v_a =  e3v_0    !
+                                     e3f_n =   e3f_0   !        ---          !
+              e3w_b =   e3w_0  ;     e3w_n =   e3w_0   !        ---          !
+             e3uw_b =  e3uw_0  ;    e3uw_n =  e3uw_0   !        ---          !
+             e3vw_b =  e3vw_0  ;    e3vw_n =  e3vw_0   !        ---          !
+         !
+         z1_hu_0(:,:) = ssumask(:,:) / ( hu_0(:,:) + 1._wp - ssumask(:,:) )     ! _i mask due to ISF
+         z1_hv_0(:,:) = ssvmask(:,:) / ( hv_0(:,:) + 1._wp - ssvmask(:,:) )
+         !
+         !        before       !          now          !       after         !
+                                      ht_n =    ht_0   !                     ! water column thickness
+               hu_b =    hu_0  ;      hu_n =    hu_0   ;    hu_a =    hu_0   ! 
+               hv_b =    hv_0  ;      hv_n =    hv_0   ;    hv_a =    hv_0   !
+            r1_hu_b = z1_hu_0  ;   r1_hu_n = z1_hu_0   ; r1_hu_a = z1_hu_0   ! inverse of water column thickness
+            r1_hv_b = z1_hv_0  ;   r1_hv_n = z1_hv_0   ; r1_hv_a = z1_hv_0   !
+         !
+         !
+      ELSE                       != time varying : initialize before/now/after variables
+         !
+         IF( .NOT.l_offline )  CALL dom_vvl_init 
+         !
+      ENDIF
+      !
+      IF( lk_c1d         )   CALL cor_c1d       ! 1D configuration: Coriolis set at T-point
+      !
+      IF( ln_meshmask .AND. .NOT.ln_iscpl )                        CALL dom_wri     ! Create a domain file
+      IF( ln_meshmask .AND.      ln_iscpl .AND. .NOT.ln_rstart )   CALL dom_wri     ! Create a domain file
+      IF(                                       .NOT.ln_rstart )   CALL dom_ctl     ! Domain control
+      !
+      IF( ln_write_cfg )   CALL cfg_write         ! create the configuration file
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_init :   ==>>>   END of domain initialization'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) 
+      ENDIF
+      !
+   END SUBROUTINE dom_init
+
+
+   SUBROUTINE dom_glo
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_glo  ***
+      !!
+      !! ** Purpose :   initialization of global domain <--> local domain indices
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : - mig , mjg : local  domain indices ==> global domain indices
+      !!              - mi0 , mi1 : global domain indices ==> local  domain indices
+      !!              - mj0,, mj1   (global point not in the local domain ==> mi0>mi1 and/or mj0>mj1)
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj   ! dummy loop argument
+      !!----------------------------------------------------------------------
+      !
+      DO ji = 1, jpi                 ! local domain indices ==> global domain indices
+        mig(ji) = ji + nimpp - 1
+      END DO
+      DO jj = 1, jpj
+        mjg(jj) = jj + njmpp - 1
+      END DO
+      !                              ! global domain indices ==> local domain indices
+      !                                   ! (return (m.0,m.1)=(1,0) if data domain gridpoint is to the west/south of the 
+      !                                   ! local domain, or (m.0,m.1)=(jp.+1,jp.) to the east/north of local domain. 
+      DO ji = 1, jpiglo
+        mi0(ji) = MAX( 1 , MIN( ji - nimpp + 1, jpi+1 ) )
+        mi1(ji) = MAX( 0 , MIN( ji - nimpp + 1, jpi   ) )
+      END DO
+      DO jj = 1, jpjglo
+        mj0(jj) = MAX( 1 , MIN( jj - njmpp + 1, jpj+1 ) )
+        mj1(jj) = MAX( 0 , MIN( jj - njmpp + 1, jpj   ) )
+      END DO
+      IF(lwp) THEN                   ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_glo : domain: global <<==>> local '
+         WRITE(numout,*) '~~~~~~~ '
+         WRITE(numout,*) '   global domain:   jpiglo = ', jpiglo, ' jpjglo = ', jpjglo, ' jpkglo = ', jpkglo
+         WRITE(numout,*) '   local  domain:   jpi    = ', jpi   , ' jpj    = ', jpj   , ' jpk    = ', jpk
+         WRITE(numout,*)
+         WRITE(numout,*) '   conversion from local to global domain indices (and vise versa) done'
+         IF( nn_print >= 1 ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '          conversion local  ==> global i-index domain (mig)'
+            WRITE(numout,25)              (mig(ji),ji = 1,jpi)
+            WRITE(numout,*)
+            WRITE(numout,*) '          conversion global ==> local  i-index domain'
+            WRITE(numout,*) '             starting index (mi0)'
+            WRITE(numout,25)              (mi0(ji),ji = 1,jpiglo)
+            WRITE(numout,*) '             ending index (mi1)'
+            WRITE(numout,25)              (mi1(ji),ji = 1,jpiglo)
+            WRITE(numout,*)
+            WRITE(numout,*) '          conversion local  ==> global j-index domain (mjg)'
+            WRITE(numout,25)              (mjg(jj),jj = 1,jpj)
+            WRITE(numout,*)
+            WRITE(numout,*) '          conversion global ==> local  j-index domain'
+            WRITE(numout,*) '             starting index (mj0)'
+            WRITE(numout,25)              (mj0(jj),jj = 1,jpjglo)
+            WRITE(numout,*) '             ending index (mj1)'
+            WRITE(numout,25)              (mj1(jj),jj = 1,jpjglo)
+         ENDIF
+      ENDIF
+ 25   FORMAT( 100(10x,19i4,/) )
+      !
+   END SUBROUTINE dom_glo
+
+
+   SUBROUTINE dom_nam
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read domaine namelists and print the variables.
+      !!
+      !! ** input   : - namrun namelist
+      !!              - namdom namelist
+      !!              - namnc4 namelist   ! "key_netcdf4" only
+      !!----------------------------------------------------------------------
+      USE ioipsl
+      !!
+      INTEGER  ::   ios   ! Local integer
+      !
+      NAMELIST/namrun/ cn_ocerst_indir, cn_ocerst_outdir, nn_stocklist, ln_rst_list,                 &
+         &             nn_no   , cn_exp   , cn_ocerst_in, cn_ocerst_out, ln_rstart , nn_rstctl ,     &
+         &             nn_it000, nn_itend , nn_date0    , nn_time0     , nn_leapy  , nn_istate ,     &
+         &             nn_stock, nn_write , ln_mskland  , ln_clobber   , nn_chunksz, nn_euler  ,     &
+         &             ln_cfmeta, ln_iscpl, ln_xios_read, nn_wxios
+      NAMELIST/namdom/ ln_linssh, rn_isfhmin, rn_rdt, rn_atfp, ln_crs, ln_meshmask
+#if defined key_netcdf4
+      NAMELIST/namnc4/ nn_nchunks_i, nn_nchunks_j, nn_nchunks_k, ln_nc4zip
+#endif
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_nam : domain initialization through namelist read'
+         WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      !
+      REWIND( numnam_ref )              ! Namelist namrun in reference namelist : Parameters of the run
+      READ  ( numnam_ref, namrun, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namrun in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namrun in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namrun, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namrun in configuration namelist' )
+      IF(lwm) WRITE ( numond, namrun )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist : namrun   ---   run parameters'
+         WRITE(numout,*) '      Assimilation cycle              nn_no           = ', nn_no
+         WRITE(numout,*) '      experiment name for output      cn_exp          = ', TRIM( cn_exp           )
+         WRITE(numout,*) '      file prefix restart input       cn_ocerst_in    = ', TRIM( cn_ocerst_in     )
+         WRITE(numout,*) '      restart input directory         cn_ocerst_indir = ', TRIM( cn_ocerst_indir  )
+         WRITE(numout,*) '      file prefix restart output      cn_ocerst_out   = ', TRIM( cn_ocerst_out    )
+         WRITE(numout,*) '      restart output directory        cn_ocerst_outdir= ', TRIM( cn_ocerst_outdir )
+         WRITE(numout,*) '      restart logical                 ln_rstart       = ', ln_rstart
+         WRITE(numout,*) '      start with forward time step    nn_euler        = ', nn_euler
+         WRITE(numout,*) '      control of time step            nn_rstctl       = ', nn_rstctl
+         WRITE(numout,*) '      number of the first time step   nn_it000        = ', nn_it000
+         WRITE(numout,*) '      number of the last time step    nn_itend        = ', nn_itend
+         WRITE(numout,*) '      initial calendar date aammjj    nn_date0        = ', nn_date0
+         WRITE(numout,*) '      initial time of day in hhmm     nn_time0        = ', nn_time0
+         WRITE(numout,*) '      leap year calendar (0/1)        nn_leapy        = ', nn_leapy
+         WRITE(numout,*) '      initial state output            nn_istate       = ', nn_istate
+         IF( ln_rst_list ) THEN
+            WRITE(numout,*) '      list of restart dump times      nn_stocklist    =', nn_stocklist
+         ELSE
+            WRITE(numout,*) '      frequency of restart file       nn_stock        = ', nn_stock
+         ENDIF
+#if ! defined key_iomput
+         WRITE(numout,*) '      frequency of output file        nn_write        = ', nn_write
+#endif
+         WRITE(numout,*) '      mask land points                ln_mskland      = ', ln_mskland
+         WRITE(numout,*) '      additional CF standard metadata ln_cfmeta       = ', ln_cfmeta
+         WRITE(numout,*) '      overwrite an existing file      ln_clobber      = ', ln_clobber
+         WRITE(numout,*) '      NetCDF chunksize (bytes)        nn_chunksz      = ', nn_chunksz
+         WRITE(numout,*) '      IS coupling at the restart step ln_iscpl        = ', ln_iscpl
+         IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+            WRITE(numout,*) '      READ restart for a single file using XIOS ln_xios_read =', ln_xios_read
+            WRITE(numout,*) '      Write restart using XIOS        nn_wxios   = ', nn_wxios
+         ELSE
+            WRITE(numout,*) "      AGRIF: nn_wxios will be ingored. See setting for parent"
+            WRITE(numout,*) "      AGRIF: ln_xios_read will be ingored. See setting for parent"
+         ENDIF
+      ENDIF
+
+      cexper = cn_exp         ! conversion DOCTOR names into model names (this should disappear soon)
+      nrstdt = nn_rstctl
+      nit000 = nn_it000
+      nitend = nn_itend
+      ndate0 = nn_date0
+      nleapy = nn_leapy
+      ninist = nn_istate
+      neuler = nn_euler
+      IF( neuler == 1 .AND. .NOT. ln_rstart ) THEN
+         IF(lwp) WRITE(numout,*)  
+         IF(lwp) WRITE(numout,*)'   ==>>>   Start from rest (ln_rstart=F)'
+         IF(lwp) WRITE(numout,*)'           an Euler initial time step is used : nn_euler is forced to 0 '   
+         neuler = 0
+      ENDIF
+      !                             ! control of output frequency
+      IF( .NOT. ln_rst_list ) THEN     ! we use nn_stock
+         IF( nn_stock == -1 )   CALL ctl_warn( 'nn_stock = -1 --> no restart will be done' )
+         IF( nn_stock == 0 .OR. nn_stock > nitend ) THEN
+            WRITE(ctmp1,*) 'nn_stock = ', nn_stock, ' it is forced to ', nitend
+            CALL ctl_warn( ctmp1 )
+            nn_stock = nitend
+         ENDIF
+      ENDIF
+#if ! defined key_iomput
+      IF( nn_write == -1 )   CALL ctl_warn( 'nn_write = -1 --> no output files will be done' )
+      IF ( nn_write == 0 ) THEN
+         WRITE(ctmp1,*) 'nn_write = ', nn_write, ' it is forced to ', nitend
+         CALL ctl_warn( ctmp1 )
+         nn_write = nitend
+      ENDIF
+#endif
+
+#if defined key_agrif
+      IF( Agrif_Root() ) THEN
+#endif
+      IF(lwp) WRITE(numout,*)
+      SELECT CASE ( nleapy )        ! Choose calendar for IOIPSL
+      CASE (  1 ) 
+         CALL ioconf_calendar('gregorian')
+         IF(lwp) WRITE(numout,*) '   ==>>>   The IOIPSL calendar is "gregorian", i.e. leap year'
+      CASE (  0 )
+         CALL ioconf_calendar('noleap')
+         IF(lwp) WRITE(numout,*) '   ==>>>   The IOIPSL calendar is "noleap", i.e. no leap year'
+      CASE ( 30 )
+         CALL ioconf_calendar('360d')
+         IF(lwp) WRITE(numout,*) '   ==>>>   The IOIPSL calendar is "360d", i.e. 360 days in a year'
+      END SELECT
+#if defined key_agrif
+      ENDIF
+#endif
+
+      REWIND( numnam_ref )              ! Namelist namdom in reference namelist : space & time domain (bathymetry, mesh, timestep)
+      READ  ( numnam_ref, namdom, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdom in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namdom in configuration namelist : space & time domain (bathymetry, mesh, timestep)
+      READ  ( numnam_cfg, namdom, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdom in configuration namelist' )
+      IF(lwm) WRITE( numond, namdom )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist : namdom   ---   space & time domain'
+         WRITE(numout,*) '      linear free surface (=T)                ln_linssh   = ', ln_linssh
+         WRITE(numout,*) '      create mesh/mask file                   ln_meshmask = ', ln_meshmask
+         WRITE(numout,*) '      treshold to open the isf cavity         rn_isfhmin  = ', rn_isfhmin, ' [m]'
+         WRITE(numout,*) '      ocean time step                         rn_rdt      = ', rn_rdt
+         WRITE(numout,*) '      asselin time filter parameter           rn_atfp     = ', rn_atfp
+         WRITE(numout,*) '      online coarsening of dynamical fields   ln_crs      = ', ln_crs
+      ENDIF
+      !
+      !          ! conversion DOCTOR names into model names (this should disappear soon)
+      atfp = rn_atfp
+      rdt  = rn_rdt
+
+      IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+         lrxios = ln_xios_read.AND.ln_rstart
+!set output file type for XIOS based on NEMO namelist 
+         IF (nn_wxios > 0) lwxios = .TRUE. 
+         nxioso = nn_wxios
+      ENDIF
+
+#if defined key_netcdf4
+      !                             ! NetCDF 4 case   ("key_netcdf4" defined)
+      REWIND( numnam_ref )              ! Namelist namnc4 in reference namelist : NETCDF
+      READ  ( numnam_ref, namnc4, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namnc4 in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namnc4 in configuration namelist : NETCDF
+      READ  ( numnam_cfg, namnc4, IOSTAT = ios, ERR = 908 )
+908   IF( ios >  0 )   CALL ctl_nam ( ios , 'namnc4 in configuration namelist' )
+      IF(lwm) WRITE( numond, namnc4 )
+
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namnc4 - Netcdf4 chunking parameters'
+         WRITE(numout,*) '      number of chunks in i-dimension             nn_nchunks_i = ', nn_nchunks_i
+         WRITE(numout,*) '      number of chunks in j-dimension             nn_nchunks_j = ', nn_nchunks_j
+         WRITE(numout,*) '      number of chunks in k-dimension             nn_nchunks_k = ', nn_nchunks_k
+         WRITE(numout,*) '      apply netcdf4/hdf5 chunking & compression   ln_nc4zip    = ', ln_nc4zip
+      ENDIF
+
+      ! Put the netcdf4 settings into a simple structure (snc4set, defined in in_out_manager module)
+      ! Note the chunk size in the unlimited (time) dimension will be fixed at 1
+      snc4set%ni   = nn_nchunks_i
+      snc4set%nj   = nn_nchunks_j
+      snc4set%nk   = nn_nchunks_k
+      snc4set%luse = ln_nc4zip
+#else
+      snc4set%luse = .FALSE.        ! No NetCDF 4 case
+#endif
+      !
+   END SUBROUTINE dom_nam
+
+
+   SUBROUTINE dom_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_ctl  ***
+      !!
+      !! ** Purpose :   Domain control.
+      !!
+      !! ** Method  :   compute and print extrema of masked scale factors
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(2) ::   imi1, imi2, ima1, ima2
+      INTEGER, DIMENSION(2) ::   iloc   ! 
+      REAL(wp) ::   ze1min, ze1max, ze2min, ze2max
+      !!----------------------------------------------------------------------
+      !
+      IF(lk_mpp) THEN
+         CALL mpp_minloc( 'domain', e1t(:,:), tmask_i(:,:), ze1min, imi1 )
+         CALL mpp_minloc( 'domain', e2t(:,:), tmask_i(:,:), ze2min, imi2 )
+         CALL mpp_maxloc( 'domain', e1t(:,:), tmask_i(:,:), ze1max, ima1 )
+         CALL mpp_maxloc( 'domain', e2t(:,:), tmask_i(:,:), ze2max, ima2 )
+      ELSE
+         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 )
+         imi1(1) = iloc(1) + nimpp - 1
+         imi1(2) = iloc(2) + njmpp - 1
+         iloc  = MINLOC( e2t(:,:), mask = tmask_i(:,:) == 1._wp )
+         imi2(1) = iloc(1) + nimpp - 1
+         imi2(2) = iloc(2) + njmpp - 1
+         iloc  = MAXLOC( e1t(:,:), mask = tmask_i(:,:) == 1._wp )
+         ima1(1) = iloc(1) + nimpp - 1
+         ima1(2) = iloc(2) + njmpp - 1
+         iloc  = MAXLOC( e2t(:,:), mask = tmask_i(:,:) == 1._wp )
+         ima2(1) = iloc(1) + nimpp - 1
+         ima2(2) = iloc(2) + njmpp - 1
+      ENDIF
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_ctl : extrema of the masked scale factors'
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,"(14x,'e1t maxi: ',1f10.2,' at i = ',i5,' j= ',i5)") ze1max, ima1(1), ima1(2)
+         WRITE(numout,"(14x,'e1t mini: ',1f10.2,' at i = ',i5,' j= ',i5)") ze1min, imi1(1), imi1(2)
+         WRITE(numout,"(14x,'e2t maxi: ',1f10.2,' at i = ',i5,' j= ',i5)") ze2max, ima2(1), ima2(2)
+         WRITE(numout,"(14x,'e2t mini: ',1f10.2,' at i = ',i5,' j= ',i5)") ze2min, imi2(1), imi2(2)
+      ENDIF
+      !
+   END SUBROUTINE dom_ctl
+
+
+   SUBROUTINE domain_cfg( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read the domain size in domain configuration file
+      !!
+      !! ** Method  :   read the cn_domcfg NetCDF file
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   inum   ! local integer
+      REAL(wp) ::   zorca_res                     ! local scalars
+      REAL(wp) ::   zperio                        !   -      -
+      INTEGER, DIMENSION(4) ::   idvar, idimsz    ! size   of dimensions
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) '           '
+         WRITE(numout,*) 'domain_cfg : domain size read in ', TRIM( cn_domcfg ), ' file'
+         WRITE(numout,*) '~~~~~~~~~~ '
+      ENDIF
+      !
+      CALL iom_open( cn_domcfg, inum )
+      !
+      !                                   !- ORCA family specificity
+      IF(  iom_varid( inum, 'ORCA'       , ldstop = .FALSE. ) > 0  .AND.  &
+         & iom_varid( inum, 'ORCA_index' , ldstop = .FALSE. ) > 0    ) THEN
+         !
+         cd_cfg = 'ORCA'
+         CALL iom_get( inum, 'ORCA_index', zorca_res )   ;   kk_cfg = NINT( zorca_res )
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) '   .'
+            WRITE(numout,*) '   ==>>>   ORCA configuration '
+            WRITE(numout,*) '   .'
+         ENDIF
+         !
+      ELSE                                !- cd_cfg & k_cfg are not used
+         cd_cfg = 'UNKNOWN'
+         kk_cfg = -9999999
+                                          !- or they may be present as global attributes 
+                                          !- (netcdf only)  
+         CALL iom_getatt( inum, 'cn_cfg', cd_cfg )  ! returns   !  if not found
+         CALL iom_getatt( inum, 'nn_cfg', kk_cfg )  ! returns -999 if not found
+         IF( TRIM(cd_cfg) == '!') cd_cfg = 'UNKNOWN'
+         IF( kk_cfg == -999     ) kk_cfg = -9999999
+         !
+      ENDIF
+       !
+      idvar = iom_varid( inum, 'e3t_0', kdimsz = idimsz )   ! use e3t_0, that must exist, to get jp(ijk)glo
+      kpi = idimsz(1)
+      kpj = idimsz(2)
+      kpk = idimsz(3)
+      CALL iom_get( inum, 'jperio', zperio )   ;   kperio = NINT( zperio )
+      CALL iom_close( inum )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) '      cn_cfg = ', TRIM(cd_cfg), '   nn_cfg = ', kk_cfg
+         WRITE(numout,*) '      jpiglo = ', kpi
+         WRITE(numout,*) '      jpjglo = ', kpj
+         WRITE(numout,*) '      jpkglo = ', kpk
+         WRITE(numout,*) '      type of global domain lateral boundary   jperio = ', kperio
+      ENDIF
+      !        
+   END SUBROUTINE domain_cfg
+   
+   
+   SUBROUTINE cfg_write
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE cfg_write  ***
+      !!                   
+      !! ** Purpose :   Create the "cn_domcfg_out" file, a NetCDF file which 
+      !!              contains all the ocean domain informations required to 
+      !!              define an ocean configuration.
+      !!
+      !! ** Method  :   Write in a file all the arrays required to set up an
+      !!              ocean configuration.
+      !!
+      !! ** output file :   domcfg_out.nc : domain size, characteristics, horizontal 
+      !!                       mesh, Coriolis parameter, and vertical scale factors
+      !!                    NB: also contain ORCA family information
+      !!----------------------------------------------------------------------
+      INTEGER           ::   ji, jj, jk   ! dummy loop indices
+      INTEGER           ::   izco, izps, isco, icav
+      INTEGER           ::   inum     ! local units
+      CHARACTER(len=21) ::   clnam    ! filename (mesh and mask informations)
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'cfg_write : create the domain configuration file (', TRIM(cn_domcfg_out),'.nc)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~'
+      !
+      !                       ! ============================= !
+      !                       !  create 'domcfg_out.nc' file  !
+      !                       ! ============================= !
+      !         
+      clnam = cn_domcfg_out  ! filename (configuration information)
+      CALL iom_open( TRIM(clnam), inum, ldwrt = .TRUE. )
+      
+      !
+      !                             !==  ORCA family specificities  ==!
+      IF( TRIM(cn_cfg) == "orca" .OR. TRIM(cn_cfg) == "ORCA" ) THEN
+         CALL iom_rstput( 0, 0, inum, 'ORCA'      , 1._wp            , ktype = jp_i4 )
+         CALL iom_rstput( 0, 0, inum, 'ORCA_index', REAL( nn_cfg, wp), ktype = jp_i4 )         
+      ENDIF
+      !
+      !                             !==  global domain size  ==!
+      !
+      CALL iom_rstput( 0, 0, inum, 'jpiglo', REAL( jpiglo, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'jpjglo', REAL( jpjglo, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'jpkglo', REAL( jpk   , wp), ktype = jp_i4 )
+      !
+      !                             !==  domain characteristics  ==!
+      !
+      !                                   ! lateral boundary of the global domain
+      CALL iom_rstput( 0, 0, inum, 'jperio', REAL( jperio, wp), ktype = jp_i4 )
+      !
+      !                                   ! type of vertical coordinate
+      IF( ln_zco    ) THEN   ;   izco = 1   ;   ELSE   ;   izco = 0   ;   ENDIF
+      IF( ln_zps    ) THEN   ;   izps = 1   ;   ELSE   ;   izps = 0   ;   ENDIF
+      IF( ln_sco    ) THEN   ;   isco = 1   ;   ELSE   ;   isco = 0   ;   ENDIF
+      CALL iom_rstput( 0, 0, inum, 'ln_zco'   , REAL( izco, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'ln_zps'   , REAL( izps, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'ln_sco'   , REAL( isco, wp), ktype = jp_i4 )
+      !
+      !                                   ! ocean cavities under iceshelves
+      IF( ln_isfcav ) THEN   ;   icav = 1   ;   ELSE   ;   icav = 0   ;   ENDIF
+      CALL iom_rstput( 0, 0, inum, 'ln_isfcav', REAL( icav, wp), ktype = jp_i4 )
+      !
+      !                             !==  horizontal mesh  !
+      !
+      CALL iom_rstput( 0, 0, inum, 'glamt', glamt, ktype = jp_r8 )   ! latitude
+      CALL iom_rstput( 0, 0, inum, 'glamu', glamu, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'glamv', glamv, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'glamf', glamf, ktype = jp_r8 )
+      !                                
+      CALL iom_rstput( 0, 0, inum, 'gphit', gphit, ktype = jp_r8 )   ! longitude
+      CALL iom_rstput( 0, 0, inum, 'gphiu', gphiu, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gphiv', gphiv, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gphif', gphif, ktype = jp_r8 )
+      !                                
+      CALL iom_rstput( 0, 0, inum, 'e1t'  , e1t  , ktype = jp_r8 )   ! i-scale factors (e1.)
+      CALL iom_rstput( 0, 0, inum, 'e1u'  , e1u  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1v'  , e1v  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1f'  , e1f  , ktype = jp_r8 )
+      !
+      CALL iom_rstput( 0, 0, inum, 'e2t'  , e2t  , ktype = jp_r8 )   ! j-scale factors (e2.)
+      CALL iom_rstput( 0, 0, inum, 'e2u'  , e2u  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2v'  , e2v  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2f'  , e2f  , ktype = jp_r8 )
+      !
+      CALL iom_rstput( 0, 0, inum, 'ff_f' , ff_f , ktype = jp_r8 )   ! coriolis factor
+      CALL iom_rstput( 0, 0, inum, 'ff_t' , ff_t , ktype = jp_r8 )
+      !
+      !                             !==  vertical mesh  ==!
+      !                                                     
+      CALL iom_rstput( 0, 0, inum, 'e3t_1d'  , e3t_1d , ktype = jp_r8 )   ! reference 1D-coordinate
+      CALL iom_rstput( 0, 0, inum, 'e3w_1d'  , e3w_1d , ktype = jp_r8 )
+      !
+      CALL iom_rstput( 0, 0, inum, 'e3t_0'   , e3t_0  , ktype = jp_r8 )   ! vertical scale factors
+      CALL iom_rstput( 0, 0, inum, 'e3u_0'   , e3u_0  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e3v_0'   , e3v_0  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e3f_0'   , e3f_0  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e3w_0'   , e3w_0  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e3uw_0'  , e3uw_0 , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e3vw_0'  , e3vw_0 , ktype = jp_r8 )
+      !                                         
+      !                             !==  wet top and bottom level  ==!   (caution: multiplied by ssmask)
+      !
+      CALL iom_rstput( 0, 0, inum, 'top_level'    , REAL( mikt, wp )*ssmask , ktype = jp_i4 )   ! nb of ocean T-points (ISF)
+      CALL iom_rstput( 0, 0, inum, 'bottom_level' , REAL( mbkt, wp )*ssmask , ktype = jp_i4 )   ! nb of ocean T-points
+      !
+      IF( ln_sco ) THEN             ! s-coordinate: store grid stiffness ratio  (Not required anyway)
+         CALL dom_stiff( z2d )
+         CALL iom_rstput( 0, 0, inum, 'stiffness', z2d )        !    ! Max. grid stiffness ratio
+      ENDIF
+      !
+      IF( ll_wd ) THEN              ! wetting and drying domain
+         CALL iom_rstput( 0, 0, inum, 'ht_0'   , ht_0   , ktype = jp_r8 )
+      ENDIF
+      !
+      ! Add some global attributes ( netcdf only )
+      CALL iom_putatt( inum, 'nn_cfg', nn_cfg )
+      CALL iom_putatt( inum, 'cn_cfg', TRIM(cn_cfg) )
+      !
+      !                                ! ============================
+      !                                !        close the files 
+      !                                ! ============================
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE cfg_write
+
+   !!======================================================================
+END MODULE domain
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domhgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domhgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domhgr.F90	(revision 14097)
@@ -0,0 +1,235 @@
+MODULE domhgr
+   !!==============================================================================
+   !!                       ***  MODULE domhgr   ***
+   !! Ocean initialization : domain initialization
+   !!==============================================================================
+   !! History :  OPA  ! 1988-03  (G. Madec) Original code
+   !!            7.0  ! 1996-01  (G. Madec)  terrain following coordinates
+   !!            8.0  ! 1997-02  (G. Madec)  print mesh informations
+   !!            8.1  ! 1999-11  (M. Imbard) NetCDF format with IO-IPSL
+   !!            8.2  ! 2000-08  (D. Ludicone) Reduced section at Bab el Mandeb
+   !!             -   ! 2001-09  (M. Levy)  eel config: grid in km, beta-plane
+   !!  NEMO      1.0  ! 2002-08  (G. Madec)  F90: Free form and module, namelist
+   !!             -   ! 2004-01  (A.M. Treguier, J.M. Molines) Case 4 (Mercator mesh)
+   !!                            use of parameters in par_CONFIG-Rxx.h90, not in namelist
+   !!             -   ! 2004-05  (A. Koch-Larrouy) Add Gyre configuration 
+   !!            3.7  ! 2015-09  (G. Madec, S. Flavoni) add cell surface and their inverse
+   !!                                       add optional read of e1e2u & e1e2v
+   !!             -   ! 2016-04  (S. Flavoni, G. Madec) new configuration interface: read or usrdef.F90
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_hgr       : initialize the horizontal mesh 
+   !!   hgr_read      : read horizontal information in the domain configuration file 
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE usrdef_hgr     ! User defined routine
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_hgr   ! called by domain.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_hgr
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_hgr  ***
+      !!
+      !! ** Purpose :   Read or compute the geographical position (in degrees)  
+      !!      of the model grid-points, the horizontal scale factors (in meters), 
+      !!      the associated horizontal metrics, and the Coriolis factor (in s-1).
+      !!
+      !! ** Method  :   Controlled by ln_read_cfg logical
+      !!              =T : all needed arrays are read in mesh_mask.nc file 
+      !!              =F : user-defined configuration, all needed arrays 
+      !!                   are computed in usr-def_hgr subroutine 
+      !!
+      !!                If Coriolis factor is neither read nor computed (iff=0)
+      !!              it is computed from gphit assuming that the mesh is
+      !!              defined on the sphere :
+      !!                   ff = 2.*omega*sin(gphif)      (in s-1)
+      !!    
+      !!                If u- & v-surfaces are neither read nor computed (ie1e2u_v=0)
+      !!              (i.e. no use of reduced scale factors in some straits)
+      !!              they are computed from e1u, e2u, e1v and e2v as:
+      !!                   e1e2u = e1u*e2u   and   e1e2v = e1v*e2v  
+      !!    
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees)
+      !!              - define Coriolis parameter at f-point                   (in 1/s)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define associated horizontal metrics at t-, u-, v- and f-points
+      !!                (inverse of scale factors 1/e1 & 1/e2, surface e1*e2, ratios e1/e2 & e2/e1)
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj     ! dummy loop indices
+      INTEGER ::   ie1e2u_v   ! flag for u- & v-surfaces 
+      INTEGER ::   iff        ! flag for Coriolis parameter
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dom_hgr')
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_hgr : define the horizontal mesh from ithe following par_oce parameters '
+         WRITE(numout,*) '~~~~~~~   '
+         WRITE(numout,*) '   namcfg : read (=T) or user defined (=F) configuration    ln_read_cfg  = ', ln_read_cfg
+      ENDIF
+      !
+      !
+      IF( ln_read_cfg ) THEN        !==  read in mesh_mask.nc file  ==!
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   read horizontal mesh in ', TRIM( cn_domcfg ), ' file'
+         !
+         CALL hgr_read   ( glamt , glamu , glamv , glamf ,   &    ! geographic position (required)
+            &              gphit , gphiu , gphiv , gphif ,   &    !     -        -
+            &              iff   , ff_f  , ff_t  ,           &    ! Coriolis parameter (if not on the sphere)
+            &              e1t   , e1u   , e1v   , e1f   ,   &    ! scale factors (required)
+            &              e2t   , e2u   , e2v   , e2f   ,   &    !    -     -        -
+            &              ie1e2u_v      , e1e2u , e1e2v     )    ! u- & v-surfaces (if gridsize reduction in some straits)
+         !
+      ELSE                          !==  User defined configuration  ==! 
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '          User defined horizontal mesh (usr_def_hgr)'
+         !
+         CALL usr_def_hgr( glamt , glamu , glamv , glamf ,   &    ! geographic position (required)
+            &              gphit , gphiu , gphiv , gphif ,   &    !
+            &              iff   , ff_f  , ff_t  ,           &    ! Coriolis parameter  (if domain not on the sphere)
+            &              e1t   , e1u   , e1v   , e1f   ,   &    ! scale factors       (required)
+            &              e2t   , e2u   , e2v   , e2f   ,   &    !
+            &              ie1e2u_v      , e1e2u , e1e2v     )    ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+         !
+      ENDIF
+      !
+      !                             !==  Coriolis parameter  ==!   (if necessary)
+      !
+      IF( iff == 0 ) THEN                 ! Coriolis parameter has not been defined 
+         IF(lwp) WRITE(numout,*) '          Coriolis parameter calculated on the sphere from gphif & gphit'
+         ff_f(:,:) = 2. * omega * SIN( rad * gphif(:,:) )     ! compute it on the sphere at f-point
+         ff_t(:,:) = 2. * omega * SIN( rad * gphit(:,:) )     !    -        -       -    at t-point
+      ELSE
+         IF( ln_read_cfg ) THEN
+            IF(lwp) WRITE(numout,*) '          Coriolis parameter have been read in ', TRIM( cn_domcfg ), ' file'
+         ELSE
+            IF(lwp) WRITE(numout,*) '          Coriolis parameter have been set in usr_def_hgr routine'
+         ENDIF
+      ENDIF
+
+      !
+      !                             !==  associated horizontal metrics  ==!
+      !
+      r1_e1t(:,:) = 1._wp / e1t(:,:)   ;   r1_e2t (:,:) = 1._wp / e2t(:,:)
+      r1_e1u(:,:) = 1._wp / e1u(:,:)   ;   r1_e2u (:,:) = 1._wp / e2u(:,:)
+      r1_e1v(:,:) = 1._wp / e1v(:,:)   ;   r1_e2v (:,:) = 1._wp / e2v(:,:)
+      r1_e1f(:,:) = 1._wp / e1f(:,:)   ;   r1_e2f (:,:) = 1._wp / e2f(:,:)
+      !
+      e1e2t (:,:) = e1t(:,:) * e2t(:,:)   ;   r1_e1e2t(:,:) = 1._wp / e1e2t(:,:)
+      e1e2f (:,:) = e1f(:,:) * e2f(:,:)   ;   r1_e1e2f(:,:) = 1._wp / e1e2f(:,:)
+      IF( ie1e2u_v == 0 ) THEN               ! u- & v-surfaces have not been defined
+         IF(lwp) WRITE(numout,*) '          u- & v-surfaces calculated as e1 e2 product'
+         e1e2u (:,:) = e1u(:,:) * e2u(:,:)         ! compute them
+         e1e2v (:,:) = e1v(:,:) * e2v(:,:) 
+      ELSE
+         IF(lwp) WRITE(numout,*) '          u- & v-surfaces have been read in "mesh_mask" file:'
+         IF(lwp) WRITE(numout,*) '                     grid size reduction in strait(s) is used'
+      ENDIF
+      r1_e1e2u(:,:) = 1._wp / e1e2u(:,:)     ! compute their invert in any cases
+      r1_e1e2v(:,:) = 1._wp / e1e2v(:,:)
+      !   
+      e2_e1u(:,:) = e2u(:,:) / e1u(:,:)
+      e1_e2v(:,:) = e1v(:,:) / e2v(:,:)
+      !
+      !
+      IF( ln_timing )   CALL timing_stop('dom_hgr')
+      !
+   END SUBROUTINE dom_hgr
+
+
+   SUBROUTINE hgr_read( plamt , plamu , plamv  , plamf  ,   &    ! gridpoints position (required)
+      &                 pphit , pphiu , pphiv  , pphif  ,   &     
+      &                 kff   , pff_f , pff_t  ,            &    ! Coriolis parameter  (if not on the sphere)
+      &                 pe1t  , pe1u  , pe1v   , pe1f   ,   &    ! scale factors       (required)
+      &                 pe2t  , pe2u  , pe2v   , pe2f   ,   &
+      &                 ke1e2u_v      , pe1e2u , pe1e2v     )    ! u- & v-surfaces (if gridsize reduction in some straits)
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE hgr_read  ***
+      !!
+      !! ** Purpose :   Read a mesh_mask file in NetCDF format using IOM
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter read here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point (if found in file)
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces read here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v              ! u- & v-surfaces (if found in file)
+      !
+      INTEGER  ::   inum                  ! logical unit
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   hgr_read : read the horizontal coordinates in mesh_mask'
+         WRITE(numout,*) '   ~~~~~~~~      jpiglo = ', jpiglo, ' jpjglo = ', jpjglo, ' jpk = ', jpk
+      ENDIF
+      !
+      CALL iom_open( cn_domcfg, inum )
+      !
+      CALL iom_get( inum, jpdom_data, 'glamt', plamt, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'glamu', plamu, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'glamv', plamv, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'glamf', plamf, lrowattr=ln_use_jattr )
+      !
+      CALL iom_get( inum, jpdom_data, 'gphit', pphit, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'gphiu', pphiu, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'gphiv', pphiv, lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'gphif', pphif, lrowattr=ln_use_jattr )
+      !
+      CALL iom_get( inum, jpdom_data, 'e1t'  , pe1t  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e1u'  , pe1u  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e1v'  , pe1v  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e1f'  , pe1f  , lrowattr=ln_use_jattr )
+      !
+      CALL iom_get( inum, jpdom_data, 'e2t'  , pe2t  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e2u'  , pe2u  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e2v'  , pe2v  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e2f'  , pe2f  , lrowattr=ln_use_jattr )
+      !
+      IF(  iom_varid( inum, 'ff_f', ldstop = .FALSE. ) > 0  .AND.  &
+         & iom_varid( inum, 'ff_t', ldstop = .FALSE. ) > 0    ) THEN
+         IF(lwp) WRITE(numout,*) '           Coriolis factor at f- and t-points read in ', TRIM( cn_domcfg ), ' file'
+         CALL iom_get( inum, jpdom_data, 'ff_f'  , pff_f  , lrowattr=ln_use_jattr )
+         CALL iom_get( inum, jpdom_data, 'ff_t'  , pff_t  , lrowattr=ln_use_jattr )
+         kff = 1
+      ELSE
+         kff = 0
+      ENDIF
+      !
+      IF( iom_varid( inum, 'e1e2u', ldstop = .FALSE. ) > 0 ) THEN
+         IF(lwp) WRITE(numout,*) '           e1e2u & e1e2v read in ', TRIM( cn_domcfg ), ' file'
+         CALL iom_get( inum, jpdom_data, 'e1e2u'  , pe1e2u  , lrowattr=ln_use_jattr )
+         CALL iom_get( inum, jpdom_data, 'e1e2v'  , pe1e2v  , lrowattr=ln_use_jattr )
+         ke1e2u_v = 1
+      ELSE
+         ke1e2u_v = 0
+      ENDIF
+      !
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE hgr_read
+    
+   !!======================================================================
+END MODULE domhgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dommsk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dommsk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dommsk.F90	(revision 14097)
@@ -0,0 +1,293 @@
+MODULE dommsk
+   !!======================================================================
+   !!                       ***  MODULE dommsk   ***
+   !! Ocean initialization : domain land/sea mask 
+   !!======================================================================
+   !! History :  OPA  ! 1987-07  (G. Madec)  Original code
+   !!            6.0  ! 1993-03  (M. Guyon)  symetrical conditions (M. Guyon)
+   !!            7.0  ! 1996-01  (G. Madec)  suppression of common work arrays
+   !!             -   ! 1996-05  (G. Madec)  mask computed from tmask
+   !!            8.0  ! 1997-02  (G. Madec)  mesh information put in domhgr.F
+   !!            8.1  ! 1997-07  (G. Madec)  modification of kbat and fmask
+   !!             -   ! 1998-05  (G. Roullet)  free surface
+   !!            8.2  ! 2000-03  (G. Madec)  no slip accurate
+   !!             -   ! 2001-09  (J.-M. Molines)  Open boundaries
+   !!   NEMO     1.0  ! 2002-08  (G. Madec)  F90: Free form and module
+   !!             -   ! 2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            3.2  ! 2009-07  (R. Benshila) Suppression of rigid-lid option
+   !!            3.6  ! 2015-05  (P. Mathiot) ISF: add wmask,wumask and wvmask
+   !!            4.0  ! 2016-06  (G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_msk       : compute land/ocean mask
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE usrdef_fmask   ! user defined fmask
+   USE bdy_oce        ! open boundary
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! IOM library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! Massively Parallel Processing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_msk    ! routine called by inidom.F90
+
+   !                            !!* Namelist namlbc : lateral boundary condition *
+   REAL(wp)        :: rn_shlat   ! type of lateral boundary condition on velocity
+   LOGICAL, PUBLIC :: ln_vorlat  !  consistency of vorticity boundary condition 
+   !                                            with analytical eqs.
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_msk( k_top, k_bot )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE dom_msk  ***
+      !!
+      !! ** Purpose :   Compute land/ocean mask arrays at tracer points, hori-
+      !!      zontal velocity points (u & v), vorticity points (f) points.
+      !!
+      !! ** Method  :   The ocean/land mask  at t-point is deduced from ko_top 
+      !!      and ko_bot, the indices of the fist and last ocean t-levels which 
+      !!      are either defined in usrdef_zgr or read in zgr_read.
+      !!                The velocity masks (umask, vmask, wmask, wumask, wvmask) 
+      !!      are deduced from a product of the two neighboring tmask.
+      !!                The vorticity mask (fmask) is deduced from tmask taking
+      !!      into account the choice of lateral boundary condition (rn_shlat) :
+      !!         rn_shlat = 0, free slip  (no shear along the coast)
+      !!         rn_shlat = 2, no slip  (specified zero velocity at the coast)
+      !!         0 < rn_shlat < 2, partial slip   | non-linear velocity profile
+      !!         2 < rn_shlat, strong slip        | in the lateral boundary layer
+      !!
+      !!      tmask_i : interior ocean mask at t-point, i.e. excluding duplicated
+      !!                rows/lines due to cyclic or North Fold boundaries as well
+      !!                as MPP halos.
+      !!      tmask_h : halo mask at t-point, i.e. excluding duplicated rows/lines
+      !!                due to cyclic or North Fold boundaries as well as MPP halos.
+      !!
+      !! ** Action :   tmask, umask, vmask, wmask, wumask, wvmask : land/ocean mask 
+      !!                         at t-, u-, v- w, wu-, and wv-points (=0. or 1.)
+      !!               fmask   : land/ocean mask at f-point (=0., or =1., or 
+      !!                         =rn_shlat along lateral boundaries)
+      !!               tmask_i : interior ocean mask 
+      !!               tmask_h : halo mask
+      !!               ssmask , ssumask, ssvmask, ssfmask : 2D ocean mask
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:,:), INTENT(in) ::   k_top, k_bot   ! first and last ocean level
+      !
+      INTEGER  ::   ji, jj, jk     ! dummy loop indices
+      INTEGER  ::   iif, iil       ! local integers
+      INTEGER  ::   ijf, ijl       !   -       -
+      INTEGER  ::   iktop, ikbot   !   -       -
+      INTEGER  ::   ios, inum
+      !!
+      NAMELIST/namlbc/ rn_shlat, ln_vorlat
+      NAMELIST/nambdy/ ln_bdy ,nb_bdy, ln_coords_file, cn_coords_file,         &
+         &             ln_mask_file, cn_mask_file, cn_dyn2d, nn_dyn2d_dta,     &
+         &             cn_dyn3d, nn_dyn3d_dta, cn_tra, nn_tra_dta,             &
+         &             ln_tra_dmp, ln_dyn3d_dmp, rn_time_dmp, rn_time_dmp_out, &
+         &             cn_ice, nn_ice_dta,                                     &
+         &             ln_vol, nn_volctl, nn_rimwidth
+      !!---------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namlbc in reference namelist : Lateral momentum boundary condition
+      READ  ( numnam_ref, namlbc, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlbc in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namlbc in configuration namelist : Lateral momentum boundary condition
+      READ  ( numnam_cfg, namlbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlbc in configuration namelist' )
+      IF(lwm) WRITE ( numond, namlbc )
+      
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dommsk : ocean mask '
+         WRITE(numout,*) '~~~~~~'
+         WRITE(numout,*) '   Namelist namlbc'
+         WRITE(numout,*) '      lateral momentum boundary cond.    rn_shlat  = ',rn_shlat
+         WRITE(numout,*) '      consistency with analytical form   ln_vorlat = ',ln_vorlat 
+      ENDIF
+      !
+      IF(lwp) WRITE(numout,*)
+      IF     (      rn_shlat == 0.               ) THEN   ;   IF(lwp) WRITE(numout,*) '   ==>>>   ocean lateral  free-slip'
+      ELSEIF (      rn_shlat == 2.               ) THEN   ;   IF(lwp) WRITE(numout,*) '   ==>>>   ocean lateral  no-slip'
+      ELSEIF ( 0. < rn_shlat .AND. rn_shlat < 2. ) THEN   ;   IF(lwp) WRITE(numout,*) '   ==>>>   ocean lateral  partial-slip'
+      ELSEIF ( 2. < rn_shlat                     ) THEN   ;   IF(lwp) WRITE(numout,*) '   ==>>>   ocean lateral  strong-slip'
+      ELSE
+         CALL ctl_stop( 'dom_msk: wrong value for rn_shlat (i.e. a negalive value). We stop.' )
+      ENDIF
+
+      !  Ocean/land mask at t-point  (computed from ko_top and ko_bot)
+      ! ----------------------------
+      !
+      tmask(:,:,:) = 0._wp
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            iktop = k_top(ji,jj)
+            ikbot = k_bot(ji,jj)
+            IF( iktop /= 0 ) THEN       ! water in the column
+               tmask(ji,jj,iktop:ikbot  ) = 1._wp
+            ENDIF
+         END DO  
+      END DO
+      !
+      ! the following call is mandatory
+      ! it masks boundaries (bathy=0) where needed depending on the configuration (closed, periodic...)  
+      CALL lbc_lnk( 'dommsk', tmask  , 'T', 1._wp )      ! Lateral boundary conditions
+
+     ! Mask corrections for bdy (read in mppini2)
+      REWIND( numnam_ref )              ! Namelist nambdy in reference namelist :Unstructured open boundaries
+      READ  ( numnam_ref, nambdy, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nambdy in configuration namelist :Unstructured open boundaries
+      READ  ( numnam_cfg, nambdy, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'nambdy in configuration namelist' )
+      ! ------------------------
+      IF ( ln_bdy .AND. ln_mask_file ) THEN
+         CALL iom_open( cn_mask_file, inum )
+         CALL iom_get ( inum, jpdom_data, 'bdy_msk', bdytmask(:,:) )
+         CALL iom_close( inum )
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  tmask(ji,jj,jk) = tmask(ji,jj,jk) * bdytmask(ji,jj)
+               END DO
+            END DO
+         END DO
+      ENDIF
+         
+      !  Ocean/land mask at u-, v-, and f-points   (computed from tmask)
+      ! ----------------------------------------
+      ! NB: at this point, fmask is designed for free slip lateral boundary condition
+      DO jk = 1, jpk
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector loop
+               umask(ji,jj,jk) = tmask(ji,jj  ,jk) * tmask(ji+1,jj  ,jk)
+               vmask(ji,jj,jk) = tmask(ji,jj  ,jk) * tmask(ji  ,jj+1,jk)
+            END DO
+            DO ji = 1, jpim1      ! NO vector opt.
+               fmask(ji,jj,jk) = tmask(ji,jj  ,jk) * tmask(ji+1,jj  ,jk)   &
+                  &            * tmask(ji,jj+1,jk) * tmask(ji+1,jj+1,jk)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'dommsk', umask, 'U', 1., vmask, 'V', 1., fmask, 'F', 1. )      ! Lateral boundary conditions
+ 
+      ! Ocean/land mask at wu-, wv- and w points    (computed from tmask)
+      !-----------------------------------------
+      wmask (:,:,1) = tmask(:,:,1)     ! surface
+      wumask(:,:,1) = umask(:,:,1)
+      wvmask(:,:,1) = vmask(:,:,1)
+      DO jk = 2, jpk                   ! interior values
+         wmask (:,:,jk) = tmask(:,:,jk) * tmask(:,:,jk-1)
+         wumask(:,:,jk) = umask(:,:,jk) * umask(:,:,jk-1)   
+         wvmask(:,:,jk) = vmask(:,:,jk) * vmask(:,:,jk-1)
+      END DO
+
+
+      ! Ocean/land column mask at t-, u-, and v-points   (i.e. at least 1 wet cell in the vertical)
+      ! ----------------------------------------------
+      ssmask (:,:) = MAXVAL( tmask(:,:,:), DIM=3 )
+      ssumask(:,:) = MAXVAL( umask(:,:,:), DIM=3 )
+      ssvmask(:,:) = MAXVAL( vmask(:,:,:), DIM=3 )
+
+
+      ! Interior domain mask  (used for global sum)
+      ! --------------------
+      !
+      iif = nn_hls   ;   iil = nlci - nn_hls + 1
+      ijf = nn_hls   ;   ijl = nlcj - nn_hls + 1
+      !
+      !                          ! halo mask : 0 on the halo and 1 elsewhere
+      tmask_h(:,:) = 1._wp                  
+      tmask_h( 1 :iif,   :   ) = 0._wp      ! first columns
+      tmask_h(iil:jpi,   :   ) = 0._wp      ! last  columns (including mpp extra columns)
+      tmask_h(   :   , 1 :ijf) = 0._wp      ! first rows
+      tmask_h(   :   ,ijl:jpj) = 0._wp      ! last  rows (including mpp extra rows)
+      !
+      !                          ! north fold mask
+      tpol(1:jpiglo) = 1._wp 
+      fpol(1:jpiglo) = 1._wp
+      IF( jperio == 3 .OR. jperio == 4 ) THEN      ! T-point pivot
+         tpol(jpiglo/2+1:jpiglo) = 0._wp
+         fpol(     1    :jpiglo) = 0._wp
+         IF( mjg(nlej) == jpjglo ) THEN                  ! only half of the nlcj-1 row for tmask_h
+            DO ji = iif+1, iil-1
+               tmask_h(ji,nlej-1) = tmask_h(ji,nlej-1) * tpol(mig(ji))
+            END DO
+         ENDIF
+      ENDIF
+      !
+      IF( jperio == 5 .OR. jperio == 6 ) THEN      ! F-point pivot
+         tpol(     1    :jpiglo) = 0._wp
+         fpol(jpiglo/2+1:jpiglo) = 0._wp
+      ENDIF
+      !
+      !                          ! interior mask : 2D ocean mask x halo mask 
+      tmask_i(:,:) = ssmask(:,:) * tmask_h(:,:)
+
+
+      ! Lateral boundary conditions on velocity (modify fmask)
+      ! ---------------------------------------  
+      IF( rn_shlat /= 0 ) THEN      ! Not free-slip lateral boundary condition
+         !
+         DO jk = 1, jpk
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( fmask(ji,jj,jk) == 0._wp ) THEN
+                     fmask(ji,jj,jk) = rn_shlat * MIN( 1._wp , MAX( umask(ji,jj,jk), umask(ji,jj+1,jk), &
+                        &                                           vmask(ji,jj,jk), vmask(ji+1,jj,jk) ) )
+                  ENDIF
+               END DO
+            END DO
+            DO jj = 2, jpjm1
+               IF( fmask(1,jj,jk) == 0._wp ) THEN
+                  fmask(1  ,jj,jk) = rn_shlat * MIN( 1._wp , MAX( vmask(2,jj,jk), umask(1,jj+1,jk), umask(1,jj,jk) ) )
+               ENDIF
+               IF( fmask(jpi,jj,jk) == 0._wp ) THEN
+                  fmask(jpi,jj,jk) = rn_shlat * MIN( 1._wp , MAX( umask(jpi,jj+1,jk), vmask(jpim1,jj,jk), umask(jpi,jj-1,jk) ) )
+               ENDIF
+            END DO         
+            DO ji = 2, jpim1
+               IF( fmask(ji,1,jk) == 0._wp ) THEN
+                  fmask(ji, 1 ,jk) = rn_shlat * MIN( 1._wp , MAX( vmask(ji+1,1,jk), umask(ji,2,jk), vmask(ji,1,jk) ) )
+               ENDIF
+               IF( fmask(ji,jpj,jk) == 0._wp ) THEN
+                  fmask(ji,jpj,jk) = rn_shlat * MIN( 1._wp , MAX( vmask(ji+1,jpj,jk), vmask(ji-1,jpj,jk), umask(ji,jpjm1,jk) ) )
+               ENDIF
+            END DO
+#if defined key_agrif 
+            IF( .NOT. AGRIF_Root() ) THEN 
+               IF ( l_Eastedge )  fmask(nlci-1 , :     ,jk) = 0.e0      ! east 
+               IF ( l_Westedge )  fmask(1      , :     ,jk) = 0.e0      ! west 
+               IF ( l_Northedge ) fmask(:      ,nlcj-1 ,jk) = 0.e0      ! north 
+               IF ( l_Southedge ) fmask(:      ,1      ,jk) = 0.e0      ! south 
+            ENDIF 
+#endif 
+         END DO
+         !
+         CALL lbc_lnk( 'dommsk', fmask, 'F', 1._wp )      ! Lateral boundary conditions on fmask
+         !
+         ! CAUTION : The fmask may be further modified in dyn_vor_init ( dynvor.F90 ) depending on ln_vorlat
+         !
+      ENDIF
+      
+      ! User defined alteration of fmask (use to reduce ocean transport in specified straits)
+      ! -------------------------------- 
+      !
+      CALL usr_def_fmask( cn_cfg, nn_cfg, fmask )
+      !
+   END SUBROUTINE dom_msk
+   
+   !!======================================================================
+END MODULE dommsk
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domngb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domngb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domngb.F90	(revision 14097)
@@ -0,0 +1,80 @@
+MODULE domngb
+   !!======================================================================
+   !!                       ***  MODULE  domngb  ***
+   !! Grid search:  find the closest grid point from a given on/lat position
+   !!======================================================================
+   !! History : 3.2  !  2009-11  (S. Masson)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_ngb       : find the closest grid point from a given lon/lat position
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! for mppsum
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_ngb   ! routine called in iom.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_ngb( plon, plat, kii, kjj, cdgrid, kkk )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dom_ngb  ***
+      !!
+      !! ** Purpose :   find the closest grid point from a given lon/lat position
+      !!
+      !! ** Method  :   look for minimum distance in cylindrical projection 
+      !!                -> not good if located at too high latitude...
+      !!----------------------------------------------------------------------
+      REAL(wp)        , INTENT(in   ) ::   plon, plat   ! longitude,latitude of the point
+      INTEGER         , INTENT(  out) ::   kii, kjj     ! i-,j-index of the closes grid point
+      INTEGER         , INTENT(in   ), OPTIONAL :: kkk  ! k-index of the mask level used
+      CHARACTER(len=1), INTENT(in   ) ::   cdgrid       ! grid name 'T', 'U', 'V', 'W'
+      !
+      INTEGER :: ik         ! working level
+      INTEGER , DIMENSION(2) ::   iloc
+      REAL(wp)               ::   zlon, zmini
+      REAL(wp), DIMENSION(jpi,jpj) ::   zglam, zgphi, zmask, zdist
+      !!--------------------------------------------------------------------
+      !
+      zmask(:,:) = 0._wp
+      ik = 1
+      IF ( PRESENT(kkk) ) ik=kkk
+      SELECT CASE( cdgrid )
+      CASE( 'U' )  ; zglam(:,:) = glamu(:,:) ; zgphi(:,:) = gphiu(:,:) ; zmask(nldi:nlei,nldj:nlej) = umask(nldi:nlei,nldj:nlej,ik)
+      CASE( 'V' )  ; zglam(:,:) = glamv(:,:) ; zgphi(:,:) = gphiv(:,:) ; zmask(nldi:nlei,nldj:nlej) = vmask(nldi:nlei,nldj:nlej,ik)
+      CASE( 'F' )  ; zglam(:,:) = glamf(:,:) ; zgphi(:,:) = gphif(:,:) ; zmask(nldi:nlei,nldj:nlej) = fmask(nldi:nlei,nldj:nlej,ik)
+      CASE DEFAULT ; zglam(:,:) = glamt(:,:) ; zgphi(:,:) = gphit(:,:) ; zmask(nldi:nlei,nldj:nlej) = tmask(nldi:nlei,nldj:nlej,ik)
+      END SELECT
+
+      zlon       = MOD( plon       + 720., 360. )                                     ! plon between    0 and 360
+      zglam(:,:) = MOD( zglam(:,:) + 720., 360. )                                     ! glam between    0 and 360
+      IF( zlon > 270. )   zlon = zlon - 360.                                          ! zlon between  -90 and 270
+      IF( zlon <  90. )   WHERE( zglam(:,:) > 180. ) zglam(:,:) = zglam(:,:) - 360.   ! glam between -180 and 180
+      zglam(:,:) = zglam(:,:) - zlon
+
+      zgphi(:,:) = zgphi(:,:) - plat
+      zdist(:,:) = zglam(:,:) * zglam(:,:) + zgphi(:,:) * zgphi(:,:)
+      
+      IF( lk_mpp ) THEN  
+         CALL mpp_minloc( 'domngb', zdist(:,:), zmask, zmini, iloc)
+         kii = iloc(1) ; kjj = iloc(2)
+      ELSE
+         iloc(:) = MINLOC( zdist(:,:), mask = zmask(:,:) == 1.e0 )
+         kii = iloc(1) + nimpp - 1
+         kjj = iloc(2) + njmpp - 1
+      ENDIF
+      !
+   END SUBROUTINE dom_ngb
+
+   !!======================================================================
+END MODULE domngb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domvvl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domvvl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domvvl.F90	(revision 14097)
@@ -0,0 +1,1052 @@
+MODULE domvvl
+   !!======================================================================
+   !!                       ***  MODULE domvvl   ***
+   !! Ocean : 
+   !!======================================================================
+   !! History :  2.0  !  2006-06  (B. Levier, L. Marie)  original code
+   !!            3.1  !  2009-02  (G. Madec, M. Leclair, R. Benshila)  pure z* coordinate
+   !!            3.3  !  2011-10  (M. Leclair) totally rewrote domvvl: vvl option includes z_star and z_tilde coordinates
+   !!            3.6  !  2014-11  (P. Mathiot) add ice shelf capability
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_vvl_init     : define initial vertical scale factors, depths and column thickness
+   !!   dom_vvl_sf_nxt   : Compute next vertical scale factors
+   !!   dom_vvl_sf_swp   : Swap vertical scale factors and update the vertical grid
+   !!   dom_vvl_interpol : Interpolate vertical scale factors from one grid point to another
+   !!   dom_vvl_rst      : read/write restart file
+   !!   dom_vvl_ctl      : Check the vvl options
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE phycst          ! physical constant
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! ocean surface boundary condition
+   USE wet_dry         ! wetting and drying
+   USE usrdef_istate   ! user defined initial state (wad only)
+   USE restart         ! ocean restart
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distributed memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC  dom_vvl_init       ! called by domain.F90
+   PUBLIC  dom_vvl_sf_nxt     ! called by step.F90
+   PUBLIC  dom_vvl_sf_swp     ! called by step.F90
+   PUBLIC  dom_vvl_interpol   ! called by dynnxt.F90
+
+   !                                                      !!* Namelist nam_vvl
+   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 = .FALSE.                ! debug control prints
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: un_td, vn_td                ! thickness diffusion transport
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: hdiv_lf                     ! low frequency part of hz divergence
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_b, tilde_e3t_n    ! baroclinic scale factors
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_a, dtilde_e3t_a   ! baroclinic scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_e3t                 ! retoring period for scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_hdv                 ! retoring period for low freq. divergence
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dom_vvl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION dom_vvl_alloc  ***
+      !!----------------------------------------------------------------------
+      IF( ln_vvl_zstar )   dom_vvl_alloc = 0
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         ALLOCATE( tilde_e3t_b(jpi,jpj,jpk)  , tilde_e3t_n(jpi,jpj,jpk) , tilde_e3t_a(jpi,jpj,jpk) ,   &
+            &      dtilde_e3t_a(jpi,jpj,jpk) , un_td  (jpi,jpj,jpk)     , vn_td  (jpi,jpj,jpk)     ,   &
+            &      STAT = dom_vvl_alloc        )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+         un_td = 0._wp
+         vn_td = 0._wp
+      ENDIF
+      IF( ln_vvl_ztilde ) THEN
+         ALLOCATE( frq_rst_e3t(jpi,jpj) , frq_rst_hdv(jpi,jpj) , hdiv_lf(jpi,jpj,jpk) , STAT= dom_vvl_alloc )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+      ENDIF
+      !
+   END FUNCTION dom_vvl_alloc
+
+
+   SUBROUTINE dom_vvl_init
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_init  ***
+      !!                   
+      !! ** Purpose :  Initialization of all scale factors, depths
+      !!               and water column heights
+      !!
+      !! ** Method  :  - use restart file and/or initialize
+      !!               - interpolate scale factors
+      !!
+      !! ** Action  : - e3t_(n/b) and tilde_e3t_(n/b)
+      !!              - Regrid: e3(u/v)_n
+      !!                        e3(u/v)_b       
+      !!                        e3w_n           
+      !!                        e3(u/v)w_b      
+      !!                        e3(u/v)w_n      
+      !!                        gdept_n, gdepw_n and gde3w_n
+      !!              - h(t/u/v)_0
+      !!              - frq_rst_e3t and frq_rst_hdv
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   ii0, ii1, ij0, ij1
+      REAL(wp)::   zcoef
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dom_vvl_init : Variable volume activated'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      !
+      CALL dom_vvl_ctl     ! choose vertical coordinate (z_star, z_tilde or layer)
+      !
+      !                    ! Allocate module arrays
+      IF( dom_vvl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_init : unable to allocate arrays' )
+      !
+      !                    ! Read or initialize e3t_(b/n), tilde_e3t_(b/n) and hdiv_lf
+      CALL dom_vvl_rst( nit000, 'READ' )
+      e3t_a(:,:,jpk) = e3t_0(:,:,jpk)  ! last level always inside the sea floor set one for all
+      !
+      !                    !== Set of all other vertical scale factors  ==!  (now and before)
+      !                                ! Horizontal interpolation of e3t
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )    ! from T to U
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )    ! from T to V 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )    ! from U to F
+      !                                ! Vertical interpolation of e3t,u,v 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )  ! from T to W
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3w_b (:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )  ! from U to UW
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )  ! from V to UW
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! We need to define e3[tuv]_a for AGRIF initialisation (should not be a problem for the restartability...)
+      e3t_a(:,:,:) = e3t_n(:,:,:)
+      e3u_a(:,:,:) = e3u_n(:,:,:)
+      e3v_a(:,:,:) = e3v_n(:,:,:)
+      !
+      !                    !==  depth of t and w-point  ==!   (set the isf depth as it is in the initial timestep)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)       ! reference to the ocean surface (used for MLD and light penetration)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)  ! reference to a common level z=0 for hpg
+      gdept_b(:,:,1) = 0.5_wp * e3w_b(:,:,1)
+      gdepw_b(:,:,1) = 0.0_wp
+      DO jk = 2, jpk                               ! vertical sum
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               !    zcoef = tmask - wmask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+               !                             ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
+               !                             ! 0.5 where jk = mikt     
+!!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
+               zcoef = ( tmask(ji,jj,jk) - wmask(ji,jj,jk) )
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk)) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+               gdepw_b(ji,jj,jk) = gdepw_b(ji,jj,jk-1) + e3t_b(ji,jj,jk-1)
+               gdept_b(ji,jj,jk) =      zcoef  * ( gdepw_b(ji,jj,jk  ) + 0.5 * e3w_b(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_b(ji,jj,jk-1) +       e3w_b(ji,jj,jk)) 
+            END DO
+         END DO
+      END DO
+      !
+      !                    !==  thickness of the water column  !!   (ocean portion only)
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)   !!gm  BUG  :  this should be 1/2 * e3w(k=1) ....
+      hu_b(:,:) = e3u_b(:,:,1) * umask(:,:,1)
+      hu_n(:,:) = e3u_n(:,:,1) * umask(:,:,1)
+      hv_b(:,:) = e3v_b(:,:,1) * vmask(:,:,1)
+      hv_n(:,:) = e3v_n(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         hu_b(:,:) = hu_b(:,:) + e3u_b(:,:,jk) * umask(:,:,jk)
+         hu_n(:,:) = hu_n(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+         hv_b(:,:) = hv_b(:,:) + e3v_b(:,:,jk) * vmask(:,:,jk)
+         hv_n(:,:) = hv_n(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !
+      !                    !==  inverse of water column thickness   ==!   (u- and v- points)
+      r1_hu_b(:,:) = ssumask(:,:) / ( hu_b(:,:) + 1._wp - ssumask(:,:) )    ! _i mask due to ISF
+      r1_hu_n(:,:) = ssumask(:,:) / ( hu_n(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_b(:,:) = ssvmask(:,:) / ( hv_b(:,:) + 1._wp - ssvmask(:,:) )
+      r1_hv_n(:,:) = ssvmask(:,:) / ( hv_n(:,:) + 1._wp - ssvmask(:,:) )
+
+      !                    !==   z_tilde coordinate case  ==!   (Restoring frequencies)
+      IF( ln_vvl_ztilde ) THEN
+!!gm : idea: add here a READ in a file of custumized restoring frequency
+         !                                   ! Values in days provided via the namelist
+         !                                   ! use rsmall to avoid possible division by zero errors with faulty settings
+         frq_rst_e3t(:,:) = 2._wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.0_wp )
+         frq_rst_hdv(:,:) = 2._wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.0_wp )
+         !
+         IF( ln_vvl_ztilde_as_zstar ) THEN   ! z-star emulation using z-tile
+            frq_rst_e3t(:,:) = 0._wp               !Ignore namelist settings
+            frq_rst_hdv(:,:) = 1._wp / rdt
+         ENDIF
+         IF ( ln_vvl_zstar_at_eqtor ) THEN   ! use z-star in vicinity of the Equator
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+!!gm  case |gphi| >= 6 degrees is useless   initialized just above by default
+                  IF( ABS(gphit(ji,jj)) >= 6.) THEN
+                     ! values outside the equatorial band and transition zone (ztilde)
+                     frq_rst_e3t(ji,jj) =  2.0_wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.e0_wp )
+                     frq_rst_hdv(ji,jj) =  2.0_wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.e0_wp )
+                  ELSEIF( ABS(gphit(ji,jj)) <= 2.5) THEN    ! Equator strip ==> z-star
+                     ! values inside the equatorial band (ztilde as zstar)
+                     frq_rst_e3t(ji,jj) =  0.0_wp
+                     frq_rst_hdv(ji,jj) =  1.0_wp / rdt
+                  ELSE                                      ! transition band (2.5 to 6 degrees N/S)
+                     !                                      ! (linearly transition from z-tilde to z-star)
+                     frq_rst_e3t(ji,jj) = 0.0_wp + (frq_rst_e3t(ji,jj)-0.0_wp)*0.5_wp   &
+                        &            * (  1.0_wp - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                     frq_rst_hdv(ji,jj) = (1.0_wp / rdt)                                &
+                        &            + (  frq_rst_hdv(ji,jj)-(1.e0_wp / rdt) )*0.5_wp   &
+                        &            * (  1._wp  - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                  ENDIF
+               END DO
+            END DO
+            IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
+               IF( nn_cfg == 3 ) THEN   ! ORCA2: Suppress ztilde in the Foxe Basin for ORCA2
+                  ii0 = 103   ;   ii1 = 111       
+                  ij0 = 128   ;   ij1 = 135   ;   
+                  frq_rst_e3t( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  0.0_wp
+                  frq_rst_hdv( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  1.e0_wp / rdt
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF(lwxios) THEN
+! define variables in restart file when writing with XIOS
+         CALL iom_set_rstw_var_active('e3t_b')
+         CALL iom_set_rstw_var_active('e3t_n')
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_set_rstw_var_active('tilde_e3t_b')
+            CALL iom_set_rstw_var_active('tilde_e3t_n')
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_set_rstw_var_active('hdiv_lf')
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_init
+
+
+   SUBROUTINE dom_vvl_sf_nxt( kt, kcall ) 
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_nxt  ***
+      !!                   
+      !! ** Purpose :  - compute the after scale factors used in tra_zdf, dynnxt,
+      !!                 tranxt and dynspg routines
+      !!
+      !! ** Method  :  - z_star case:  Repartition of ssh INCREMENT proportionnaly to the level thickness.
+      !!               - z_tilde_case: after scale factor increment = 
+      !!                                    high frequency part of horizontal divergence
+      !!                                  + retsoring towards the background grid
+      !!                                  + thickness difusion
+      !!                               Then repartition of ssh INCREMENT proportionnaly
+      !!                               to the "baroclinic" level thickness.
+      !!
+      !! ** Action  :  - hdiv_lf    : restoring towards full baroclinic divergence in z_tilde case
+      !!               - tilde_e3t_a: after increment of vertical scale factor 
+      !!                              in z_tilde case
+      !!               - e3(t/u/v)_a
+      !!
+      !! Reference  : Leclair, M., and Madec, G. 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )           ::   kt      ! time step
+      INTEGER, INTENT( in ), OPTIONAL ::   kcall   ! optional argument indicating call sequence
+      !
+      INTEGER                ::   ji, jj, jk            ! dummy loop indices
+      INTEGER , DIMENSION(3) ::   ijk_max, ijk_min      ! temporary integers
+      REAL(wp)               ::   z2dt, z_tmin, z_tmax  ! local scalars
+      LOGICAL                ::   ll_do_bclinic         ! local logical
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zht, z_scale, zwu, zwv, zhdiv
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ze3t
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_nxt')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_nxt : compute after scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'
+      ENDIF
+
+      ll_do_bclinic = .TRUE.
+      IF( PRESENT(kcall) ) THEN
+         IF( kcall == 2 .AND. ln_vvl_ztilde )   ll_do_bclinic = .FALSE.
+      ENDIF
+
+      ! ******************************* !
+      ! After acale factors at t-points !
+      ! ******************************* !
+      !                                                ! --------------------------------------------- !
+      !                                                ! z_star coordinate and barotropic z-tilde part !
+      !                                                ! --------------------------------------------- !
+      !
+      z_scale(:,:) = ( ssha(:,:) - sshb(:,:) ) * ssmask(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+      DO jk = 1, jpkm1
+         ! formally this is the same as e3t_a = e3t_0*(1+ssha/ht_0)
+         e3t_a(:,:,jk) = e3t_b(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+      END DO
+      !
+      IF( (ln_vvl_ztilde .OR. ln_vvl_layer) .AND. ll_do_bclinic ) THEN   ! z_tilde or layer coordinate !
+         !                                                               ! ------baroclinic part------ !
+         ! I - initialization
+         ! ==================
+
+         ! 1 - barotropic divergence
+         ! -------------------------
+         zhdiv(:,:) = 0._wp
+         zht(:,:)   = 0._wp
+         DO jk = 1, jpkm1
+            zhdiv(:,:) = zhdiv(:,:) + e3t_n(:,:,jk) * hdivn(:,:,jk)
+            zht  (:,:) = zht  (:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         zhdiv(:,:) = zhdiv(:,:) / ( zht(:,:) + 1. - tmask_i(:,:) )
+
+         ! 2 - Low frequency baroclinic horizontal divergence  (z-tilde case only)
+         ! --------------------------------------------------
+         IF( ln_vvl_ztilde ) THEN
+            IF( kt > nit000 ) THEN
+               DO jk = 1, jpkm1
+                  hdiv_lf(:,:,jk) = hdiv_lf(:,:,jk) - rdt * frq_rst_hdv(:,:)   &
+                     &          * ( hdiv_lf(:,:,jk) - e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) )
+               END DO
+            ENDIF
+         ENDIF
+
+         ! II - after z_tilde increments of vertical scale factors
+         ! =======================================================
+         tilde_e3t_a(:,:,:) = 0._wp  ! tilde_e3t_a used to store tendency terms
+
+         ! 1 - High frequency divergence term
+         ! ----------------------------------
+         IF( ln_vvl_ztilde ) THEN     ! z_tilde case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - ( e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) - hdiv_lf(:,:,jk) )
+            END DO
+         ELSE                         ! layer case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) -   e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) * tmask(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 2 - Restoring term (z-tilde case only)
+         ! ------------------
+         IF( ln_vvl_ztilde ) THEN
+            DO jk = 1, jpk
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - frq_rst_e3t(:,:) * tilde_e3t_b(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 3 - Thickness diffusion term
+         ! ----------------------------
+         zwu(:,:) = 0._wp
+         zwv(:,:) = 0._wp
+         DO jk = 1, jpkm1        ! a - first derivative: diffusive fluxes
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  un_td(ji,jj,jk) = rn_ahe3 * umask(ji,jj,jk) * e2_e1u(ji,jj)           &
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji+1,jj  ,jk) )
+                  vn_td(ji,jj,jk) = rn_ahe3 * vmask(ji,jj,jk) * e1_e2v(ji,jj)           & 
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji  ,jj+1,jk) )
+                  zwu(ji,jj) = zwu(ji,jj) + un_td(ji,jj,jk)
+                  zwv(ji,jj) = zwv(ji,jj) + vn_td(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         DO jj = 1, jpj          ! b - correction for last oceanic u-v points
+            DO ji = 1, jpi
+               un_td(ji,jj,mbku(ji,jj)) = un_td(ji,jj,mbku(ji,jj)) - zwu(ji,jj)
+               vn_td(ji,jj,mbkv(ji,jj)) = vn_td(ji,jj,mbkv(ji,jj)) - zwv(ji,jj)
+            END DO
+         END DO
+         DO jk = 1, jpkm1        ! c - second derivative: divergence of diffusive fluxes
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  tilde_e3t_a(ji,jj,jk) = tilde_e3t_a(ji,jj,jk) + (   un_td(ji-1,jj  ,jk) - un_td(ji,jj,jk)    &
+                     &                                          +     vn_td(ji  ,jj-1,jk) - vn_td(ji,jj,jk)    &
+                     &                                            ) * r1_e1e2t(ji,jj)
+               END DO
+            END DO
+         END DO
+         !                       ! d - thickness diffusion transport: boundary conditions
+         !                             (stored for tracer advction and continuity equation)
+         CALL lbc_lnk_multi( 'domvvl', un_td , 'U' , -1._wp, vn_td , 'V' , -1._wp)
+
+         ! 4 - Time stepping of baroclinic scale factors
+         ! ---------------------------------------------
+         ! Leapfrog time stepping
+         ! ~~~~~~~~~~~~~~~~~~~~~~
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            z2dt =  rdt
+         ELSE
+            z2dt = 2.0_wp * rdt
+         ENDIF
+         CALL lbc_lnk( 'domvvl', tilde_e3t_a(:,:,:), 'T', 1._wp )
+         tilde_e3t_a(:,:,:) = tilde_e3t_b(:,:,:) + z2dt * tmask(:,:,:) * tilde_e3t_a(:,:,:)
+
+         ! Maximum deformation control
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         ze3t(:,:,jpk) = 0._wp
+         DO jk = 1, jpkm1
+            ze3t(:,:,jk) = tilde_e3t_a(:,:,jk) / e3t_0(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:)
+         END DO
+         z_tmax = MAXVAL( ze3t(:,:,:) )
+         CALL mpp_max( 'domvvl', z_tmax )                 ! max over the global domain
+         z_tmin = MINVAL( ze3t(:,:,:) )
+         CALL mpp_min( 'domvvl', z_tmin )                 ! min over the global domain
+         ! - ML - test: for the moment, stop simulation for too large e3_t variations
+         IF( ( z_tmax >  rn_zdef_max ) .OR. ( z_tmin < - rn_zdef_max ) ) THEN
+            IF( lk_mpp ) THEN
+               CALL mpp_maxloc( 'domvvl', ze3t, tmask, z_tmax, ijk_max )
+               CALL mpp_minloc( 'domvvl', ze3t, tmask, z_tmin, ijk_min )
+            ELSE
+               ijk_max = MAXLOC( ze3t(:,:,:) )
+               ijk_max(1) = ijk_max(1) + nimpp - 1
+               ijk_max(2) = ijk_max(2) + njmpp - 1
+               ijk_min = MINLOC( ze3t(:,:,:) )
+               ijk_min(1) = ijk_min(1) + nimpp - 1
+               ijk_min(2) = ijk_min(2) + njmpp - 1
+            ENDIF
+            IF (lwp) THEN
+               WRITE(numout, *) 'MAX( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmax
+               WRITE(numout, *) 'at i, j, k=', ijk_max
+               WRITE(numout, *) 'MIN( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmin
+               WRITE(numout, *) 'at i, j, k=', ijk_min            
+               CALL ctl_stop( 'STOP', 'MAX( ABS( tilde_e3t_a(:,:,: ) ) / e3t_0(:,:,:) ) too high')
+            ENDIF
+         ENDIF
+         ! - ML - end test
+         ! - ML - Imposing these limits will cause a baroclinicity error which is corrected for below
+         tilde_e3t_a(:,:,:) = MIN( tilde_e3t_a(:,:,:),   rn_zdef_max * e3t_0(:,:,:) )
+         tilde_e3t_a(:,:,:) = MAX( tilde_e3t_a(:,:,:), - rn_zdef_max * e3t_0(:,:,:) )
+
+         !
+         ! "tilda" change in the after scale factor
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - tilde_e3t_b(:,:,jk)
+         END DO
+         ! III - Barotropic repartition of the sea surface height over the baroclinic profile
+         ! ==================================================================================
+         ! add ( ssh increment + "baroclinicity error" ) proportionly to e3t(n)
+         ! - ML - baroclinicity error should be better treated in the future
+         !        i.e. locally and not spread over the water column.
+         !        (keep in mind that the idea is to reduce Eulerian velocity as much as possible)
+         zht(:,:) = 0.
+         DO jk = 1, jpkm1
+            zht(:,:)  = zht(:,:) + tilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_scale(:,:) =  - zht(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = dtilde_e3t_a(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+         END DO
+
+      ENDIF
+
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer )  THEN   ! z_tilde or layer coordinate !
+      !                                           ! ---baroclinic part--------- !
+         DO jk = 1, jpkm1
+            e3t_a(:,:,jk) = e3t_a(:,:,jk) + dtilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+      ENDIF
+
+      IF( ln_vvl_dbg .AND. .NOT. ll_do_bclinic ) THEN   ! - ML - test: control prints for debuging
+         !
+         IF( lwp ) WRITE(numout, *) 'kt =', kt
+         IF ( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+            z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( zht(:,:) ) )
+            CALL mpp_max( 'domvvl', z_tmax )                             ! max over the global domain
+            IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(SUM(tilde_e3t_a))) =', z_tmax
+         END IF
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshn(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshn-SUM(e3t_n))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + ssha(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+ssha-SUM(e3t_a))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_b(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshb(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshb-SUM(e3t_b))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshb(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshb))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshn(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshn))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( ssha(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ssha))) =', z_tmax
+      END IF
+
+      ! *********************************** !
+      ! After scale factors at u- v- points !
+      ! *********************************** !
+
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3u_a(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3v_a(:,:,:), 'V' )
+
+      ! *********************************** !
+      ! After depths at u- v points         !
+      ! *********************************** !
+
+      hu_a(:,:) = e3u_a(:,:,1) * umask(:,:,1)
+      hv_a(:,:) = e3v_a(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         hu_a(:,:) = hu_a(:,:) + e3u_a(:,:,jk) * umask(:,:,jk)
+         hv_a(:,:) = hv_a(:,:) + e3v_a(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !                                        ! Inverse of the local depth
+!!gm BUG ?  don't understand the use of umask_i here .....
+      r1_hu_a(:,:) = ssumask(:,:) / ( hu_a(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_a(:,:) = ssvmask(:,:) / ( hv_a(:,:) + 1._wp - ssvmask(:,:) )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_nxt')
+      !
+   END SUBROUTINE dom_vvl_sf_nxt
+
+
+   SUBROUTINE dom_vvl_sf_swp( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_swp  ***
+      !!                   
+      !! ** Purpose :  compute time filter and swap of scale factors 
+      !!               compute all depths and related variables for next time step
+      !!               write outputs and restart file
+      !!
+      !! ** Method  :  - swap of e3t with trick for volume/tracer conservation
+      !!               - reconstruct scale factor at other grid points (interpolate)
+      !!               - recompute depths and water height fields
+      !!
+      !! ** Action  :  - e3t_(b/n), tilde_e3t_(b/n) and e3(u/v)_n ready for next time step
+      !!               - Recompute:
+      !!                    e3(u/v)_b       
+      !!                    e3w_n           
+      !!                    e3(u/v)w_b      
+      !!                    e3(u/v)w_n      
+      !!                    gdept_n, gdepw_n  and gde3w_n
+      !!                    h(u/v) and h(u/v)r
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!              Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcoef        ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_swp')
+      !
+      IF( kt == nit000 )   THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_swp : - time filter and swap of scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   - interpolate scale factors and compute depths for next time step'
+      ENDIF
+      !
+      ! Time filter and swap of scale factors
+      ! =====================================
+      ! - ML - e3(t/u/v)_b are allready computed in dynnxt.
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:)
+         ELSE
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:) & 
+            &         + atfp * ( tilde_e3t_b(:,:,:) - 2.0_wp * tilde_e3t_n(:,:,:) + tilde_e3t_a(:,:,:) )
+         ENDIF
+         tilde_e3t_n(:,:,:) = tilde_e3t_a(:,:,:)
+      ENDIF
+      gdept_b(:,:,:) = gdept_n(:,:,:)
+      gdepw_b(:,:,:) = gdepw_n(:,:,:)
+
+      e3t_n(:,:,:) = e3t_a(:,:,:)
+      e3u_n(:,:,:) = e3u_a(:,:,:)
+      e3v_n(:,:,:) = e3v_a(:,:,:)
+
+      ! Compute all missing vertical scale factor and depths
+      ! ====================================================
+      ! Horizontal scale factor interpolations
+      ! --------------------------------------
+      ! - ML - e3u_b and e3v_b are allready computed in dynnxt
+      ! - JC - hu_b, hv_b, hur_b, hvr_b also
+      
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F'  )
+      
+      ! Vertical scale factor interpolations
+      CALL dom_vvl_interpol( e3t_n(:,:,:),  e3w_n(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:),  e3w_b(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! t- and w- points depth (set the isf depth as it is in the initial step)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+      DO jk = 2, jpk
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+              !    zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))   ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+                                                                 ! 1 for jk = mikt
+               zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =    zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk) )  &
+                   &             + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk) ) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+            END DO
+         END DO
+      END DO
+
+      ! Local depth and Inverse of the local depth of the water
+      ! -------------------------------------------------------
+      hu_n(:,:) = hu_a(:,:)   ;   r1_hu_n(:,:) = r1_hu_a(:,:)
+      hv_n(:,:) = hv_a(:,:)   ;   r1_hv_n(:,:) = r1_hv_a(:,:)
+      !
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+
+      ! write restart file
+      ! ==================
+      IF( lrst_oce  )   CALL dom_vvl_rst( kt, 'WRITE' )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_swp')
+      !
+   END SUBROUTINE dom_vvl_sf_swp
+
+
+   SUBROUTINE dom_vvl_interpol( pe3_in, pe3_out, pout )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl__interpol  ***
+      !!
+      !! ** Purpose :   interpolate scale factors from one grid point to another
+      !!
+      !! ** Method  :   e3_out = e3_0 + interpolation(e3_in - e3_0)
+      !!                - horizontal interpolation: grid cell surface averaging
+      !!                - vertical interpolation: simple averaging
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::  pe3_in    ! input e3 to be interpolated
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::  pe3_out   ! output interpolated e3
+      CHARACTER(LEN=*)                , INTENT(in   ) ::  pout      ! grid point of out scale factors
+      !                                                             !   =  'U', 'V', 'W, 'F', 'UW' or 'VW'
+      !
+      INTEGER ::   ji, jj, jk                                       ! dummy loop indices
+      REAL(wp) ::  zlnwd                                            ! =1./0. when ln_wd_il = T/F
+      !!----------------------------------------------------------------------
+      !
+      IF(ln_wd_il) THEN
+        zlnwd = 1.0_wp
+      ELSE
+        zlnwd = 0.0_wp
+      END IF
+      !
+      SELECT CASE ( pout )    !==  type of interpolation  ==!
+         !
+      CASE( 'U' )                   !* from T- to U-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2u(ji,jj)   &
+                     &                       * (   e1e2t(ji  ,jj) * ( pe3_in(ji  ,jj,jk) - e3t_0(ji  ,jj,jk) )     &
+                     &                           + e1e2t(ji+1,jj) * ( pe3_in(ji+1,jj,jk) - e3t_0(ji+1,jj,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'U', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3u_0(:,:,:)
+         !
+      CASE( 'V' )                   !* from T- to V-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * ( vmask(ji,jj,jk)  * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2v(ji,jj)   &
+                     &                       * (   e1e2t(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3t_0(ji,jj  ,jk) )     &
+                     &                           + e1e2t(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3t_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'V', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3v_0(:,:,:)
+         !
+      CASE( 'F' )                   !* from U-point to F-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * umask(ji,jj+1,jk) * (1.0_wp - zlnwd) + zlnwd ) &
+                     &                       *    r1_e1e2f(ji,jj)                                                  &
+                     &                       * (   e1e2u(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3u_0(ji,jj  ,jk) )     &
+                     &                           + e1e2u(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3u_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'F', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3f_0(:,:,:)
+         !
+      CASE( 'W' )                   !* from T- to W-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3w_0(:,:,1) + pe3_in(:,:,1) - e3t_0(:,:,1)
+         ! - ML - The use of mask in this formulea enables the special treatment of the last w-point without indirect adressing
+!!gm BUG? use here wmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3w_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )   &
+               &                            * ( pe3_in(:,:,jk-1) - e3t_0(:,:,jk-1) )                               &
+               &                            +            0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )     &
+               &                            * ( pe3_in(:,:,jk  ) - e3t_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'UW' )                  !* from U- to UW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3uw_0(:,:,1) + pe3_in(:,:,1) - e3u_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wumask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3uw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3u_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3u_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'VW' )                  !* from V- to VW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3vw_0(:,:,1) + pe3_in(:,:,1) - e3v_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wvmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3vw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3v_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3v_0(:,:,jk  ) )
+         END DO
+      END SELECT
+      !
+   END SUBROUTINE dom_vvl_interpol
+
+
+   SUBROUTINE dom_vvl_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dom_vvl_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write VVL file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain vertical scale factors,
+      !!                they are set to the _0 values
+      !!                if the restart does not contain vertical scale factors increments (z_tilde),
+      !!                they are set to 0.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   id1, id2, id3, id4, id5     ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ===============
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            CALL rst_read_open                  !  open the restart file if necessary
+            CALL iom_get( numror, jpdom_autoglo, 'sshn'   , sshn, ldxios = lrxios    )
+            !
+            id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'e3t_n', ldstop = .FALSE. )
+            id3 = iom_varid( numror, 'tilde_e3t_b', ldstop = .FALSE. )
+            id4 = iom_varid( numror, 'tilde_e3t_n', ldstop = .FALSE. )
+            id5 = iom_varid( numror, 'hdiv_lf', ldstop = .FALSE. )
+            !                             ! --------- !
+            !                             ! all cases !
+            !                             ! --------- !
+            IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               ! needed to restart if land processor not computed 
+               IF(lwp) write(numout,*) 'dom_vvl_rst : e3t_b and e3t_n found in restart files'
+               WHERE ( tmask(:,:,:) == 0.0_wp ) 
+                  e3t_n(:,:,:) = e3t_0(:,:,:)
+                  e3t_b(:,:,:) = e3t_0(:,:,:)
+               END WHERE
+               IF( neuler == 0 ) THEN
+                  e3t_b(:,:,:) = e3t_n(:,:,:)
+               ENDIF
+            ELSE IF( id1 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               e3t_n(:,:,:) = e3t_b(:,:,:)
+               neuler = 0
+            ELSE IF( id2 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_b not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ELSE
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart file'
+               IF(lwp) write(numout,*) 'Compute scale factor from sshn'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:) ) &
+                      &                          / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                      &          + e3t_0(:,:,jk)                               * (1._wp -tmask(:,:,jk))
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ENDIF
+            !                             ! ----------- !
+            IF( ln_vvl_zstar ) THEN       ! z_star case !
+               !                          ! ----------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN
+                  CALL ctl_stop( 'dom_vvl_rst: z_star cannot restart from a z_tilde or layer run' )
+               ENDIF
+               !                          ! ----------------------- !
+            ELSE                          ! z_tilde and layer cases !
+               !                          ! ----------------------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+               ELSE                            ! one at least array is missing
+                  tilde_e3t_b(:,:,:) = 0.0_wp
+                  tilde_e3t_n(:,:,:) = 0.0_wp
+               ENDIF
+               !                          ! ------------ !
+               IF( ln_vvl_ztilde ) THEN   ! z_tilde case !
+                  !                       ! ------------ !
+                  IF( id5 > 0 ) THEN  ! required array exists
+                     CALL iom_get( numror, jpdom_autoglo, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                  ELSE                ! array is missing
+                     hdiv_lf(:,:,:) = 0.0_wp
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+         ELSE                                   !* Initialize at "rest"
+            !
+
+            IF( ll_wd ) THEN   ! MJB ll_wd edits start here - these are essential 
+               !
+               IF( cn_cfg == 'wad' ) THEN
+                  ! Wetting and drying test case
+                  CALL usr_def_istate( gdept_b, tmask, tsb, ub, vb, sshb  )
+                  tsn  (:,:,:,:) = tsb (:,:,:,:)       ! set now values from to before ones
+                  sshn (:,:)     = sshb(:,:)
+                  un   (:,:,:)   = ub  (:,:,:)
+                  vn   (:,:,:)   = vb  (:,:,:)
+               ELSE
+                  ! if not test case
+                  sshn(:,:) = -ssh_ref
+                  sshb(:,:) = -ssh_ref
+
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        IF( ht_0(ji,jj)-ssh_ref <  rn_wdmin1 ) THEN ! if total depth is less than min depth
+
+                           sshb(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           sshn(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           ssha(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDIF !If test case else
+
+               ! Adjust vertical metrics for all wad
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:)  ) &
+                    &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                    &            + e3t_0(:,:,jk) * ( 1._wp - tmask(:,:,jk) )
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     IF ( ht_0(ji,jj) .LE. 0.0 .AND. NINT( ssmask(ji,jj) ) .EQ. 1) THEN
+                       CALL ctl_stop( 'dom_vvl_rst: ht_0 must be positive at potentially wet points' )
+                     ENDIF
+                  END DO 
+               END DO 
+               !
+            ELSE
+               !
+               ! Just to read set ssh in fact, called latter once vertical grid
+               ! is set up:
+!               CALL usr_def_istate( gdept_0, tmask, tsb, ub, vb, sshb  )
+!               !
+!               DO jk=1,jpk
+!                  e3t_b(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshb(:,:) ) &
+!                     &            / ( ht_0(:,:) + 1._wp -ssmask(:,:) ) * tmask(:,:,jk)
+!               END DO
+!               e3t_n(:,:,:) = e3t_b(:,:,:)
+                sshn(:,:)=0._wp
+                e3t_n(:,:,:)=e3t_0(:,:,:)
+                e3t_b(:,:,:)=e3t_0(:,:,:)
+               !
+            END IF           ! end of ll_wd edits
+
+            IF( ln_vvl_ztilde .OR. ln_vvl_layer) THEN
+               tilde_e3t_b(:,:,:) = 0._wp
+               tilde_e3t_n(:,:,:) = 0._wp
+               IF( ln_vvl_ztilde ) hdiv_lf(:,:,:) = 0._wp
+            END IF
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! ===================
+         IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         !                                           ! --------- !
+         !                                           ! all cases !
+         !                                           ! --------- !
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t_b(:,:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t_n(:,:,:), ldxios = lwxios )
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+         ENDIF
+         !
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_rst
+
+
+   SUBROUTINE dom_vvl_ctl
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl_ctl  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options
+      !!                for vertical coordinate
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios
+      !!
+      NAMELIST/nam_vvl/ ln_vvl_zstar, ln_vvl_ztilde, ln_vvl_layer, ln_vvl_ztilde_as_zstar, &
+         &              ln_vvl_zstar_at_eqtor      , rn_ahe3     , rn_rst_e3t            , &
+         &              rn_lf_cutoff               , rn_zdef_max , ln_vvl_dbg                ! not yet implemented: ln_vvl_kepe
+      !!---------------------------------------------------------------------- 
+      !
+      REWIND( numnam_ref )              ! Namelist nam_vvl in reference namelist : 
+      READ  ( numnam_ref, nam_vvl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_vvl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_vvl in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, nam_vvl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'nam_vvl in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_vvl )
+      !
+      IF(lwp) THEN                    ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_vvl_ctl : choice/control of the variable vertical coordinate'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist nam_vvl : chose a vertical coordinate'
+         WRITE(numout,*) '      zstar                      ln_vvl_zstar   = ', ln_vvl_zstar
+         WRITE(numout,*) '      ztilde                     ln_vvl_ztilde  = ', ln_vvl_ztilde
+         WRITE(numout,*) '      layer                      ln_vvl_layer   = ', ln_vvl_layer
+         WRITE(numout,*) '      ztilde as zstar   ln_vvl_ztilde_as_zstar  = ', ln_vvl_ztilde_as_zstar
+         WRITE(numout,*) '      ztilde near the equator    ln_vvl_zstar_at_eqtor  = ', ln_vvl_zstar_at_eqtor
+         WRITE(numout,*) '      !'
+         WRITE(numout,*) '      thickness diffusion coefficient                      rn_ahe3      = ', rn_ahe3
+         WRITE(numout,*) '      maximum e3t deformation fractional change            rn_zdef_max  = ', rn_zdef_max
+         IF( ln_vvl_ztilde_as_zstar ) THEN
+            WRITE(numout,*) '      ztilde running in zstar emulation mode (ln_vvl_ztilde_as_zstar=T) '
+            WRITE(numout,*) '         ignoring namelist timescale parameters and using:'
+            WRITE(numout,*) '            hard-wired : z-tilde to zstar restoration timescale (days)'
+            WRITE(numout,*) '                         rn_rst_e3t     = 0.e0'
+            WRITE(numout,*) '            hard-wired : z-tilde cutoff frequency of low-pass filter (days)'
+            WRITE(numout,*) '                         rn_lf_cutoff   = 1.0/rdt'
+         ELSE
+            WRITE(numout,*) '      z-tilde to zstar restoration timescale (days)        rn_rst_e3t   = ', rn_rst_e3t
+            WRITE(numout,*) '      z-tilde cutoff frequency of low-pass filter (days)   rn_lf_cutoff = ', rn_lf_cutoff
+         ENDIF
+         WRITE(numout,*) '         debug prints flag                                 ln_vvl_dbg   = ', ln_vvl_dbg
+      ENDIF
+      !
+      ioptio = 0                      ! Parameter control
+      IF( ln_vvl_ztilde_as_zstar )   ln_vvl_ztilde = .true.
+      IF( ln_vvl_zstar           )   ioptio = ioptio + 1
+      IF( ln_vvl_ztilde          )   ioptio = ioptio + 1
+      IF( ln_vvl_layer           )   ioptio = ioptio + 1
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE vertical coordinate in namelist nam_vvl' )
+      IF( .NOT. ln_vvl_zstar .AND. ln_isf ) CALL ctl_stop( 'Only vvl_zstar has been tested with ice shelf cavity' )
+      !
+      IF(lwp) THEN                   ! Print the choice
+         WRITE(numout,*)
+         IF( ln_vvl_zstar           ) WRITE(numout,*) '      ==>>>   zstar vertical coordinate is used'
+         IF( ln_vvl_ztilde          ) WRITE(numout,*) '      ==>>>   ztilde vertical coordinate is used'
+         IF( ln_vvl_layer           ) WRITE(numout,*) '      ==>>>   layer vertical coordinate is used'
+         IF( ln_vvl_ztilde_as_zstar ) WRITE(numout,*) '      ==>>>   to emulate a zstar coordinate'
+      ENDIF
+      !
+#if defined key_agrif
+      IF( (.NOT.Agrif_Root()).AND.(.NOT.ln_vvl_zstar) )   CALL ctl_stop( 'AGRIF is implemented with zstar coordinate only' )
+#endif
+      !
+   END SUBROUTINE dom_vvl_ctl
+
+   !!======================================================================
+END MODULE domvvl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domwri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domwri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domwri.F90	(revision 14097)
@@ -0,0 +1,296 @@
+MODULE domwri
+   !!======================================================================
+   !!                       ***  MODULE domwri  ***
+   !! Ocean initialization : write the ocean domain mesh file(s)
+   !!======================================================================
+   !! History :  OPA  ! 1997-02  (G. Madec)  Original code
+   !!            8.1  ! 1999-11  (M. Imbard)  NetCDF FORMAT with IOIPSL
+   !!   NEMO     1.0  ! 2002-08  (G. Madec)  F90 and several file
+   !!            3.0  ! 2008-01  (S. Masson)  add dom_uniq 
+   !!            4.0  ! 2016-01  (G. Madec)  simplified mesh_mask.nc file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_wri        : create and write mesh and mask file(s)
+   !!   dom_uniq       : identify unique point of a grid (TUVF)
+   !!   dom_stiff      : diagnose maximum grid stiffness/hydrostatic consistency (s-coordinate)
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE phycst ,   ONLY :   rsmall
+   USE wet_dry,   ONLY :   ll_wd  ! Wetting and drying
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O library
+   USE lbclnk          ! lateral boundary conditions - mpp exchanges
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_wri              ! routine called by inidom.F90
+   PUBLIC   dom_stiff            ! routine called by inidom.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dom_wri
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_wri  ***
+      !!                   
+      !! ** Purpose :   Create the NetCDF file(s) which contain(s) all the
+      !!      ocean domain informations (mesh and mask arrays). This (these)
+      !!      file(s) is (are) used for visualisation (SAXO software) and
+      !!      diagnostic computation.
+      !!
+      !! ** Method  :   create a file with all domain related arrays
+      !!
+      !! ** output file :   meshmask.nc  : domain size, horizontal grid-point position,
+      !!                                   masks, depth and vertical scale factors
+      !!----------------------------------------------------------------------
+      INTEGER           ::   inum    ! temprary units for 'mesh_mask.nc' file
+      CHARACTER(len=21) ::   clnam   ! filename (mesh and mask informations)
+      INTEGER           ::   ji, jj, jk   ! dummy loop indices
+      INTEGER           ::   izco, izps, isco, icav
+      !                               
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zprt, zprw     ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdepu, zdepv   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dom_wri : create NetCDF mesh and mask information file(s)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+      
+      clnam = 'mesh_mask'  ! filename (mesh and mask informations)
+      
+      !                                  ! ============================
+      !                                  !  create 'mesh_mask.nc' file
+      !                                  ! ============================
+      CALL iom_open( TRIM(clnam), inum, ldwrt = .TRUE. )
+      !
+      !                                                         ! global domain size
+      CALL iom_rstput( 0, 0, inum, 'jpiglo', REAL( jpiglo, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'jpjglo', REAL( jpjglo, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'jpkglo', REAL( jpkglo, wp), ktype = jp_i4 )
+
+      !                                                         ! domain characteristics
+      CALL iom_rstput( 0, 0, inum, 'jperio', REAL( jperio, wp), ktype = jp_i4 )
+      !                                                         ! type of vertical coordinate
+      IF( ln_zco    ) THEN   ;   izco = 1   ;   ELSE   ;   izco = 0   ;   ENDIF
+      IF( ln_zps    ) THEN   ;   izps = 1   ;   ELSE   ;   izps = 0   ;   ENDIF
+      IF( ln_sco    ) THEN   ;   isco = 1   ;   ELSE   ;   isco = 0   ;   ENDIF
+      CALL iom_rstput( 0, 0, inum, 'ln_zco'   , REAL( izco, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'ln_zps'   , REAL( izps, wp), ktype = jp_i4 )
+      CALL iom_rstput( 0, 0, inum, 'ln_sco'   , REAL( isco, wp), ktype = jp_i4 )
+      !                                                         ! ocean cavities under iceshelves
+      IF( ln_isfcav ) THEN   ;   icav = 1   ;   ELSE   ;   icav = 0   ;   ENDIF
+      CALL iom_rstput( 0, 0, inum, 'ln_isfcav', REAL( icav, wp), ktype = jp_i4 )
+  
+      !                                                         ! masks
+      CALL iom_rstput( 0, 0, inum, 'tmask', tmask, ktype = jp_i1 )     !    ! land-sea mask
+      CALL iom_rstput( 0, 0, inum, 'umask', umask, ktype = jp_i1 )
+      CALL iom_rstput( 0, 0, inum, 'vmask', vmask, ktype = jp_i1 )
+      CALL iom_rstput( 0, 0, inum, 'fmask', fmask, ktype = jp_i1 )
+      
+      CALL dom_uniq( zprw, 'T' )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zprt(ji,jj) = ssmask(ji,jj) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO                             !    ! unique point mask
+      CALL iom_rstput( 0, 0, inum, 'tmaskutil', zprt, ktype = jp_i1 )  
+      CALL dom_uniq( zprw, 'U' )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zprt(ji,jj) = ssumask(ji,jj) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO
+      CALL iom_rstput( 0, 0, inum, 'umaskutil', zprt, ktype = jp_i1 )  
+      CALL dom_uniq( zprw, 'V' )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zprt(ji,jj) = ssvmask(ji,jj) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO
+      CALL iom_rstput( 0, 0, inum, 'vmaskutil', zprt, ktype = jp_i1 )  
+!!gm  ssfmask has been removed  ==>> find another solution to defined fmaskutil
+!!    Here we just remove the output of fmaskutil.
+!      CALL dom_uniq( zprw, 'F' )
+!      DO jj = 1, jpj
+!         DO ji = 1, jpi
+!            zprt(ji,jj) = ssfmask(ji,jj) * zprw(ji,jj)                        !    ! unique point mask
+!         END DO
+!      END DO
+!      CALL iom_rstput( 0, 0, inum, 'fmaskutil', zprt, ktype = jp_i1 )  
+!!gm
+
+      !                                                         ! horizontal mesh (inum3)
+      CALL iom_rstput( 0, 0, inum, 'glamt', glamt, ktype = jp_r8 )     !    ! latitude
+      CALL iom_rstput( 0, 0, inum, 'glamu', glamu, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'glamv', glamv, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'glamf', glamf, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'gphit', gphit, ktype = jp_r8 )     !    ! longitude
+      CALL iom_rstput( 0, 0, inum, 'gphiu', gphiu, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gphiv', gphiv, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gphif', gphif, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'e1t', e1t, ktype = jp_r8 )         !    ! e1 scale factors
+      CALL iom_rstput( 0, 0, inum, 'e1u', e1u, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1v', e1v, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e1f', e1f, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'e2t', e2t, ktype = jp_r8 )         !    ! e2 scale factors
+      CALL iom_rstput( 0, 0, inum, 'e2u', e2u, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2v', e2v, ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'e2f', e2f, ktype = jp_r8 )
+      
+      CALL iom_rstput( 0, 0, inum, 'ff_f', ff_f, ktype = jp_r8 )       !    ! coriolis factor
+      CALL iom_rstput( 0, 0, inum, 'ff_t', ff_t, ktype = jp_r8 )
+      
+      ! note that mbkt is set to 1 over land ==> use surface tmask
+      zprt(:,:) = ssmask(:,:) * REAL( mbkt(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum, 'mbathy', zprt, ktype = jp_i4 )     !    ! nb of ocean T-points
+      zprt(:,:) = ssmask(:,:) * REAL( mikt(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum, 'misf', zprt, ktype = jp_i4 )       !    ! nb of ocean T-points
+      zprt(:,:) = ssmask(:,:) * REAL( risfdep(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum, 'isfdraft', zprt, ktype = jp_r8 )   !    ! nb of ocean T-points
+      !															             ! vertical mesh
+      CALL iom_rstput( 0, 0, inum, 'e3t_1d', e3t_1d, ktype = jp_r8  )    !    ! scale factors
+      CALL iom_rstput( 0, 0, inum, 'e3w_1d', e3w_1d, ktype = jp_r8  )
+      
+      CALL iom_rstput( 0, 0, inum, 'e3t_0' , e3t_0 , ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3u_0' , e3u_0 , ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3v_0' , e3v_0 , ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3f_0' , e3f_0 , ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3w_0' , e3w_0 , ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3uw_0', e3uw_0, ktype = jp_r8  )
+      CALL iom_rstput( 0, 0, inum, 'e3vw_0', e3vw_0, ktype = jp_r8  )
+      !
+      CALL iom_rstput( 0, 0, inum, 'gdept_1d' , gdept_1d , ktype = jp_r8 )  ! stretched system
+      CALL iom_rstput( 0, 0, inum, 'gdepw_1d' , gdepw_1d , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gdept_0'  , gdept_0  , ktype = jp_r8 )
+      CALL iom_rstput( 0, 0, inum, 'gdepw_0'  , gdepw_0  , ktype = jp_r8 )
+      !
+      IF( ln_sco ) THEN                                         ! s-coordinate stiffness
+         CALL dom_stiff( zprt )
+         CALL iom_rstput( 0, 0, inum, 'stiffness', zprt )       ! Max. grid stiffness ratio
+      ENDIF
+      !
+      IF( ll_wd ) CALL iom_rstput( 0, 0, inum, 'ht_0'   , ht_0   , ktype = jp_r8 )
+
+      !                                     ! ============================
+      CALL iom_close( inum )                !        close the files 
+      !                                     ! ============================
+   END SUBROUTINE dom_wri
+
+
+   SUBROUTINE dom_uniq( puniq, cdgrd )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_uniq  ***
+      !!                   
+      !! ** Purpose :   identify unique point of a grid (TUVF)
+      !!
+      !! ** Method  :   1) aplly lbc_lnk on an array with different values for each element
+      !!                2) check which elements have been changed
+      !!----------------------------------------------------------------------
+      CHARACTER(len=1)        , INTENT(in   ) ::   cdgrd   ! 
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   puniq   ! 
+      !
+      REAL(wp) ::  zshift   ! shift value link to the process number
+      INTEGER  ::  ji       ! dummy loop indices
+      LOGICAL, DIMENSION(SIZE(puniq,1),SIZE(puniq,2),1) ::  lldbl  ! store whether each point is unique or not
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztstref
+      !!----------------------------------------------------------------------
+      !
+      ! build an array with different values for each element 
+      ! in mpp: make sure that these values are different even between process
+      ! -> apply a shift value according to the process number
+      zshift = jpi * jpj * ( narea - 1 )
+      ztstref(:,:) = RESHAPE( (/ (zshift + REAL(ji,wp), ji = 1, jpi*jpj) /), (/ jpi, jpj /) )
+      !
+      puniq(:,:) = ztstref(:,:)                   ! default definition
+      CALL lbc_lnk( 'domwri', puniq, cdgrd, 1. )            ! apply boundary conditions
+      lldbl(:,:,1) = puniq(:,:) == ztstref(:,:)   ! check which values have been changed 
+      !
+      puniq(:,:) = 1.                             ! default definition
+      ! fill only the inner part of the cpu with llbl converted into real 
+      puniq(nldi:nlei,nldj:nlej) = REAL( COUNT( lldbl(nldi:nlei,nldj:nlej,:), dim = 3 ) , wp )
+      !
+   END SUBROUTINE dom_uniq
+
+
+   SUBROUTINE dom_stiff( px1 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_stiff  ***
+      !!                     
+      !! ** Purpose :   Diagnose maximum grid stiffness/hydrostatic consistency
+      !!
+      !! ** Method  :   Compute Haney (1991) hydrostatic condition ratio
+      !!                Save the maximum in the vertical direction
+      !!                (this number is only relevant in s-coordinates)
+      !!
+      !!                Haney, 1991, J. Phys. Oceanogr., 21, 610-619.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out), OPTIONAL ::   px1   ! stiffness
+      !
+      INTEGER  ::   ji, jj, jk 
+      REAL(wp) ::   zrxmax
+      REAL(wp), DIMENSION(4) ::   zr1
+      REAL(wp), DIMENSION(jpi,jpj) ::   zx1
+      !!----------------------------------------------------------------------
+      zx1(:,:) = 0._wp
+      zrxmax   = 0._wp
+      zr1(:)   = 0._wp
+      !
+      DO ji = 2, jpim1
+         DO jj = 2, jpjm1
+            DO jk = 1, jpkm1
+!!gm   remark: dk(gdepw) = e3t   ===>>>  possible simplification of the following calculation....
+!!             especially since it is gde3w which is used to compute the pressure gradient
+!!             furthermore, I think gdept_0 should be used below instead of w point in the numerator
+!!             so that the ratio is computed at the same point (i.e. uw and vw) ....
+               zr1(1) = ABS(  ( gdepw_0(ji  ,jj,jk  )-gdepw_0(ji-1,jj,jk  )               & 
+                    &          +gdepw_0(ji  ,jj,jk+1)-gdepw_0(ji-1,jj,jk+1) )             &
+                    &       / ( gdepw_0(ji  ,jj,jk  )+gdepw_0(ji-1,jj,jk  )               &
+                    &          -gdepw_0(ji  ,jj,jk+1)-gdepw_0(ji-1,jj,jk+1) + rsmall )  ) * umask(ji-1,jj,jk)
+               zr1(2) = ABS(  ( gdepw_0(ji+1,jj,jk  )-gdepw_0(ji  ,jj,jk  )               &
+                    &          +gdepw_0(ji+1,jj,jk+1)-gdepw_0(ji  ,jj,jk+1) )             &
+                    &       / ( gdepw_0(ji+1,jj,jk  )+gdepw_0(ji  ,jj,jk  )               &
+                    &          -gdepw_0(ji+1,jj,jk+1)-gdepw_0(ji  ,jj,jk+1) + rsmall )  ) * umask(ji  ,jj,jk)
+               zr1(3) = ABS(  ( gdepw_0(ji,jj+1,jk  )-gdepw_0(ji,jj  ,jk  )               &
+                    &          +gdepw_0(ji,jj+1,jk+1)-gdepw_0(ji,jj  ,jk+1) )             &
+                    &       / ( gdepw_0(ji,jj+1,jk  )+gdepw_0(ji,jj  ,jk  )               &
+                    &          -gdepw_0(ji,jj+1,jk+1)-gdepw_0(ji,jj  ,jk+1) + rsmall )  ) * vmask(ji,jj  ,jk)
+               zr1(4) = ABS(  ( gdepw_0(ji,jj  ,jk  )-gdepw_0(ji,jj-1,jk  )               &
+                    &          +gdepw_0(ji,jj  ,jk+1)-gdepw_0(ji,jj-1,jk+1) )             &
+                    &       / ( gdepw_0(ji,jj  ,jk  )+gdepw_0(ji,jj-1,jk  )               &
+                    &          -gdepw_0(ji,jj  ,jk+1)-gdepw_0(ji,jj-1,jk+1) + rsmall )  ) * vmask(ji,jj-1,jk)
+               zrxmax = MAXVAL( zr1(1:4) )
+               zx1(ji,jj) = MAX( zx1(ji,jj) , zrxmax )
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'domwri', zx1, 'T', 1. )
+      !
+      IF( PRESENT( px1 ) )    px1 = zx1
+      !
+      zrxmax = MAXVAL( zx1 )
+      !
+      CALL mpp_max( 'domwri', zrxmax ) ! max over the global domain
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_stiff : maximum grid stiffness ratio: ', zrxmax
+         WRITE(numout,*) '~~~~~~~~~'
+      ENDIF
+      !
+   END SUBROUTINE dom_stiff
+
+   !!======================================================================
+END MODULE domwri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domzgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domzgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/domzgr.F90	(revision 14097)
@@ -0,0 +1,319 @@
+MODULE domzgr
+   !!==============================================================================
+   !!                       ***  MODULE domzgr   ***
+   !! Ocean domain : definition of the vertical coordinate system
+   !!==============================================================================
+   !! History :  OPA  ! 1995-12  (G. Madec)  Original code : s vertical coordinate
+   !!                 ! 1997-07  (G. Madec)  lbc_lnk call
+   !!                 ! 1997-04  (J.-O. Beismann) 
+   !!            8.5  ! 2002-09  (A. Bozec, G. Madec)  F90: Free form and module
+   !!             -   ! 2002-09  (A. de Miranda)  rigid-lid + islands
+   !!  NEMO      1.0  ! 2003-08  (G. Madec)  F90: Free form and module
+   !!             -   ! 2005-10  (A. Beckmann)  modifications for hybrid s-ccordinates & new stretching function
+   !!            2.0  ! 2006-04  (R. Benshila, G. Madec)  add zgr_zco
+   !!            3.0  ! 2008-06  (G. Madec)  insertion of domzgr_zps.h90 & conding style
+   !!            3.2  ! 2009-07  (R. Benshila) Suppression of rigid-lid option
+   !!            3.3  ! 2010-11  (G. Madec) add mbk. arrays associated to the deepest ocean level
+   !!            3.4  ! 2012-08  (J. Siddorn) added Siddorn and Furner stretching function
+   !!            3.4  ! 2012-12  (R. Bourdalle-Badie and G. Reffray)  modify C1D case  
+   !!            3.6  ! 2014-11  (P. Mathiot and C. Harris) add ice shelf capabilitye  
+   !!            3.?  ! 2015-11  (H. Liu) Modifications for Wetting/Drying
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_zgr       : read or set the ocean vertical coordinate system
+   !!   zgr_read      : read the vertical information in the domain configuration file
+   !!   zgr_top_bot   : ocean top and bottom level for t-, u, and v-points with 1 as minimum value
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE usrdef_zgr     ! user defined vertical coordinate system
+   USE closea         ! closed seas
+   USE depth_e3       ! depth <=> e3
+   USE wet_dry,   ONLY: ll_wd, ssh_ref  ! Wetting and drying
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dom_zgr        ! called by dom_init.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS       
+
+   SUBROUTINE dom_zgr( k_top, k_bot )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_zgr  ***
+      !!                   
+      !! ** Purpose :   set the depth of model levels and the resulting 
+      !!              vertical scale factors.
+      !!
+      !! ** Method  : - reference 1D vertical coordinate (gdep._1d, e3._1d)
+      !!              - read/set ocean depth and ocean levels (bathy, mbathy)
+      !!              - vertical coordinate (gdep., e3.) depending on the 
+      !!                coordinate chosen :
+      !!                   ln_zco=T   z-coordinate   
+      !!                   ln_zps=T   z-coordinate with partial steps
+      !!                   ln_zco=T   s-coordinate 
+      !!
+      !! ** Action  :   define gdep., e3., mbathy and bathy
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:,:), INTENT(out) ::   k_top, k_bot   ! ocean first and last level indices
+      !
+      INTEGER  ::   jk                  ! dummy loop index
+      INTEGER  ::   ioptio, ibat, ios   ! local integer
+      REAL(wp) ::   zrefdep             ! depth of the reference level (~10m)
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                     ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_zgr : vertical coordinate'
+         WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      IF( ln_linssh .AND. lwp) WRITE(numout,*) '   linear free surface: the vertical mesh does not change in time'
+
+
+      IF( ln_read_cfg ) THEN        !==  read in mesh_mask.nc file  ==!
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   Read vertical mesh in ', TRIM( cn_domcfg ), ' file'
+         !
+         CALL zgr_read   ( ln_zco  , ln_zps  , ln_sco, ln_isfcav,   & 
+            &              gdept_1d, gdepw_1d, e3t_1d, e3w_1d   ,   &    ! 1D gridpoints depth
+            &              gdept_0 , gdepw_0                    ,   &    ! gridpoints depth 
+            &              e3t_0   , e3u_0   , e3v_0 , e3f_0    ,   &    ! vertical scale factors
+            &              e3w_0   , e3uw_0  , e3vw_0           ,   &    ! vertical scale factors
+            &              k_top   , k_bot            )                  ! 1st & last ocean level
+            !
+      ELSE                          !==  User defined configuration  ==!
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '          User defined vertical mesh (usr_def_zgr)'
+         !
+         CALL usr_def_zgr( ln_zco  , ln_zps  , ln_sco, ln_isfcav,   & 
+            &              gdept_1d, gdepw_1d, e3t_1d, e3w_1d   ,   &    ! 1D gridpoints depth
+            &              gdept_0 , gdepw_0                    ,   &    ! gridpoints depth 
+            &              e3t_0   , e3u_0   , e3v_0 , e3f_0    ,   &    ! vertical scale factors
+            &              e3w_0   , e3uw_0  , e3vw_0           ,   &    ! vertical scale factors
+            &              k_top   , k_bot            )                  ! 1st & last ocean level
+         !
+      ENDIF
+      !
+!!gm to be remove when removing the OLD definition of e3 scale factors so that gde3w disappears
+      ! Compute gde3w_0 (vertical sum of e3w)
+      gde3w_0(:,:,1) = 0.5_wp * e3w_0(:,:,1)
+      DO jk = 2, jpk
+         gde3w_0(:,:,jk) = gde3w_0(:,:,jk-1) + e3w_0(:,:,jk)
+      END DO
+      !
+      ! Any closed seas (defined by closea_mask > 0 in domain_cfg file) to be filled 
+      ! in at runtime if ln_closea=.false.
+      IF( .NOT.ln_closea )   CALL clo_bat( k_top, k_bot )
+      !
+      IF(lwp) THEN                     ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Type of vertical coordinate (read in ', TRIM( cn_domcfg ), ' file or set in userdef_nam) :'
+         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
+
+      ioptio = 0                       ! Check Vertical coordinate options
+      IF( ln_zco      )   ioptio = ioptio + 1
+      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' )
+
+
+      !                                ! top/bottom ocean level indices for t-, u- and v-points (f-point also for top)
+      CALL zgr_top_bot( k_top, k_bot )      ! with a minimum value set to 1
+      
+
+      !                                ! deepest/shallowest W level Above/Below ~10m
+!!gm BUG in s-coordinate this does not work!
+      zrefdep = 10._wp - 0.1_wp * MINVAL( e3w_1d )                   ! ref. depth with tolerance (10% of minimum layer thickness)
+      nlb10 = MINLOC( gdepw_1d, mask = gdepw_1d > zrefdep, dim = 1 ) ! shallowest W level Below ~10m
+      nla10 = nlb10 - 1                                              ! deepest    W level Above ~10m
+!!gm end bug
+      !
+      IF( nprint == 1 .AND. lwp )   THEN
+         WRITE(numout,*) ' MIN val k_top   ', MINVAL(   k_top(:,:) ), ' MAX ', MAXVAL( k_top(:,:) )
+         WRITE(numout,*) ' MIN val k_bot   ', MINVAL(   k_bot(:,:) ), ' MAX ', MAXVAL( k_bot(:,:) )
+         WRITE(numout,*) ' MIN val depth t ', MINVAL( gdept_0(:,:,:) ),   &
+            &                          ' w ', MINVAL( gdepw_0(:,:,:) ), '3w ', MINVAL( gde3w_0(:,:,:) )
+         WRITE(numout,*) ' MIN val e3    t ', MINVAL(   e3t_0(:,:,:) ), ' f ', MINVAL(   e3f_0(:,:,:) ),  &
+            &                          ' u ', MINVAL(   e3u_0(:,:,:) ), ' u ', MINVAL(   e3v_0(:,:,:) ),  &
+            &                          ' uw', MINVAL(  e3uw_0(:,:,:) ), ' vw', MINVAL(  e3vw_0(:,:,:)),   &
+            &                          ' w ', MINVAL(   e3w_0(:,:,:) )
+
+         WRITE(numout,*) ' MAX val depth t ', MAXVAL( gdept_0(:,:,:) ),   &
+            &                          ' w ', MAXVAL( gdepw_0(:,:,:) ), '3w ', MAXVAL( gde3w_0(:,:,:) )
+         WRITE(numout,*) ' MAX val e3    t ', MAXVAL(   e3t_0(:,:,:) ), ' f ', MAXVAL(   e3f_0(:,:,:) ),  &
+            &                          ' u ', MAXVAL(   e3u_0(:,:,:) ), ' u ', MAXVAL(   e3v_0(:,:,:) ),  &
+            &                          ' uw', MAXVAL(  e3uw_0(:,:,:) ), ' vw', MAXVAL(  e3vw_0(:,:,:) ),  &
+            &                          ' w ', MAXVAL(   e3w_0(:,:,:) )
+      ENDIF
+      !
+   END SUBROUTINE dom_zgr
+
+
+   SUBROUTINE zgr_read( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,   &   ! type of vertical coordinate
+      &                 pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,   &   ! 1D reference vertical coordinate
+      &                 pdept , pdepw ,                            &   ! 3D t & w-points depth
+      &                 pe3t  , pe3u  , pe3v   , pe3f ,            &   ! vertical scale factors
+      &                 pe3w  , pe3uw , pe3vw         ,            &   !     -      -      -
+      &                 k_top  , k_bot    )                            ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE zgr_read  ***
+      !!
+      !! ** Purpose :   Read the vertical information in the domain configuration file
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth       [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D vertical scale factors [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth          [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors    [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         !    -       -      -
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top , k_bot               ! first & last ocean level
+      !
+      INTEGER  ::   jk     ! dummy loop index
+      INTEGER  ::   inum   ! local logical unit
+      REAL(WP) ::   z_zco, z_zps, z_sco, z_cav
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   zgr_read : read the vertical coordinates in ', TRIM( cn_domcfg ), ' file'
+         WRITE(numout,*) '   ~~~~~~~~'
+      ENDIF
+      !
+      CALL iom_open( cn_domcfg, inum )
+      !
+      !                          !* type of vertical coordinate
+      CALL iom_get( inum, 'ln_zco'   , z_zco )
+      CALL iom_get( inum, 'ln_zps'   , z_zps )
+      CALL iom_get( inum, 'ln_sco'   , z_sco )
+      IF( z_zco == 0._wp ) THEN   ;   ld_zco = .false.   ;   ELSE   ;   ld_zco = .true.   ;   ENDIF
+      IF( z_zps == 0._wp ) THEN   ;   ld_zps = .false.   ;   ELSE   ;   ld_zps = .true.   ;   ENDIF
+      IF( z_sco == 0._wp ) THEN   ;   ld_sco = .false.   ;   ELSE   ;   ld_sco = .true.   ;   ENDIF
+      !
+      !                          !* ocean cavities under iceshelves
+      CALL iom_get( inum, 'ln_isfcav', z_cav )
+      IF( z_cav == 0._wp ) THEN   ;   ld_isfcav = .false.   ;   ELSE   ;   ld_isfcav = .true.   ;   ENDIF
+      !
+      !                          !* vertical scale factors
+      CALL iom_get( inum, jpdom_unknown, 'e3t_1d'  , pe3t_1d  )                     ! 1D reference coordinate
+      CALL iom_get( inum, jpdom_unknown, 'e3w_1d'  , pe3w_1d  )
+      !
+      CALL iom_get( inum, jpdom_data, 'e3t_0'  , pe3t  , lrowattr=ln_use_jattr )    ! 3D coordinate
+      CALL iom_get( inum, jpdom_data, 'e3u_0'  , pe3u  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e3v_0'  , pe3v  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e3f_0'  , pe3f  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e3w_0'  , pe3w  , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e3uw_0' , pe3uw , lrowattr=ln_use_jattr )
+      CALL iom_get( inum, jpdom_data, 'e3vw_0' , pe3vw , lrowattr=ln_use_jattr )
+      !
+      !                          !* depths
+      !                                   !- old depth definition (obsolescent feature)
+      IF(  iom_varid( inum, 'gdept_1d', ldstop = .FALSE. ) > 0  .AND.  &
+         & iom_varid( inum, 'gdepw_1d', ldstop = .FALSE. ) > 0  .AND.  &
+         & iom_varid( inum, 'gdept_0' , ldstop = .FALSE. ) > 0  .AND.  &
+         & iom_varid( inum, 'gdepw_0' , ldstop = .FALSE. ) > 0    ) THEN
+         CALL ctl_warn( 'zgr_read : old definition of depths and scale factors used ', & 
+            &           '           depths at t- and w-points read in the domain configuration file')
+         CALL iom_get( inum, jpdom_unknown, 'gdept_1d', pdept_1d )   
+         CALL iom_get( inum, jpdom_unknown, 'gdepw_1d', pdepw_1d )
+         CALL iom_get( inum, jpdom_data   , 'gdept_0' , pdept , lrowattr=ln_use_jattr )
+         CALL iom_get( inum, jpdom_data   , 'gdepw_0' , pdepw , lrowattr=ln_use_jattr )
+         !
+      ELSE                                !- depths computed from e3. scale factors
+         CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d )    ! 1D reference depth
+         CALL e3_to_depth( pe3t   , pe3w   , pdept   , pdepw    )    ! 3D depths
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+            WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+            WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+         ENDIF
+      ENDIF
+      !
+      !                          !* ocean top and bottom level
+      CALL iom_get( inum, jpdom_data, 'top_level'    , z2d  , lrowattr=ln_use_jattr )   ! 1st wet T-points (ISF)
+      k_top(:,:) = NINT( z2d(:,:) )
+      CALL iom_get( inum, jpdom_data, 'bottom_level' , z2d  , lrowattr=ln_use_jattr )   ! last wet T-points
+      k_bot(:,:) = NINT( z2d(:,:) )
+      !
+      ! reference depth for negative bathy (wetting and drying only)
+      IF( ll_wd )  CALL iom_get( inum,  'rn_wd_ref_depth' , ssh_ref   )
+      !
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE zgr_read
+
+
+   SUBROUTINE zgr_top_bot( k_top, k_bot )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_top_bot  ***
+      !!
+      !! ** Purpose :   defines the vertical index of ocean bottom (mbk. arrays)
+      !!
+      !! ** Method  :   computes from k_top and k_bot with a minimum value of 1 over land
+      !!
+      !! ** Action  :   mikt, miku, mikv :   vertical indices of the shallowest 
+      !!                                     ocean level at t-, u- & v-points
+      !!                                     (min value = 1)
+      !! ** Action  :   mbkt, mbku, mbkv :   vertical indices of the deeptest 
+      !!                                     ocean level at t-, u- & v-points
+      !!                                     (min value = 1 over land)
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(in) ::   k_top, k_bot   ! top & bottom ocean level indices
+      !
+      INTEGER ::   ji, jj   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) ::   zk   ! workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_bot : ocean top and bottom k-index of T-, U-, V- and W-levels '
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~'
+      !
+      mikt(:,:) = MAX( k_top(:,:) , 1 )    ! top    ocean k-index of T-level (=1 over land)
+      !
+      mbkt(:,:) = MAX( k_bot(:,:) , 1 )    ! bottom ocean k-index of T-level (=1 over land)
+ 
+      !                                    ! N.B.  top     k-index of W-level = mikt
+      !                                    !       bottom  k-index of W-level = mbkt+1
+      DO jj = 1, jpjm1
+         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)  )
+            !
+            mbku(ji,jj) = MIN(  mbkt(ji+1,jj  ) , mbkt(ji,jj)  )
+            mbkv(ji,jj) = MIN(  mbkt(ji  ,jj+1) , mbkt(ji,jj)  )
+         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 
+      zk(:,:) = REAL( miku(:,:), wp )   ;   CALL lbc_lnk( 'domzgr', zk, 'U', 1. )   ;   miku(:,:) = MAX( NINT( zk(:,:) ), 1 )
+      zk(:,:) = REAL( mikv(:,:), wp )   ;   CALL lbc_lnk( 'domzgr', zk, 'V', 1. )   ;   mikv(:,:) = MAX( NINT( zk(:,:) ), 1 )
+      zk(:,:) = REAL( mikf(:,:), wp )   ;   CALL lbc_lnk( 'domzgr', zk, 'F', 1. )   ;   mikf(:,:) = MAX( NINT( zk(:,:) ), 1 )
+      !
+      zk(:,:) = REAL( mbku(:,:), wp )   ;   CALL lbc_lnk( 'domzgr', zk, 'U', 1. )   ;   mbku(:,:) = MAX( NINT( zk(:,:) ), 1 )
+      zk(:,:) = REAL( mbkv(:,:), wp )   ;   CALL lbc_lnk( 'domzgr', zk, 'V', 1. )   ;   mbkv(:,:) = MAX( NINT( zk(:,:) ), 1 )
+      !
+   END SUBROUTINE zgr_top_bot
+
+   !!======================================================================
+END MODULE domzgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dtatsd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dtatsd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/dtatsd.F90	(revision 14097)
@@ -0,0 +1,256 @@
+MODULE dtatsd
+   !!======================================================================
+   !!                     ***  MODULE  dtatsd  ***
+   !! Ocean data  :  read ocean Temperature & Salinity Data from gridded data
+   !!======================================================================
+   !! History :  OPA  ! 1991-03  ()  Original code
+   !!             -   ! 1992-07  (M. Imbard)
+   !!            8.0  ! 1999-10  (M.A. Foujols, M. Imbard)  NetCDF FORMAT 
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module 
+   !!            3.3  ! 2010-10  (C. Bricaud, S. Masson)  use of fldread
+   !!            3.4  ! 2010-11  (G. Madec, C. Ethe) Merge of dtatem and dtasal + remove CPP keys
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dta_tsd      : read and time interpolated ocean Temperature & Salinity Data
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE phycst          ! physical constants
+   USE dom_oce         ! ocean space and time domain
+   USE fldread         ! read input fields
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dta_tsd_init   ! called by opa.F90
+   PUBLIC   dta_tsd        ! called by istate.F90 and tradmp.90
+
+   !                                  !!* namtsd  namelist : Temperature & Salinity Data *
+   LOGICAL , PUBLIC ::   ln_tsd_init   !: T & S data flag
+   LOGICAL , PUBLIC ::   ln_tsd_dmp    !: internal damping toward input data flag
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tsd   ! structure of input SST (file informations, fields read)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dta_tsd_init( ld_tradmp )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dta_tsd_init  ***
+      !!                    
+      !! ** Purpose :   initialisation of T & S input data 
+      !! 
+      !! ** Method  : - Read namtsd namelist
+      !!              - allocates T & S data structure 
+      !!----------------------------------------------------------------------
+      LOGICAL, INTENT(in), OPTIONAL ::   ld_tradmp   ! force the initialization when tradp is used
+      !
+      INTEGER ::   ios, ierr0, ierr1, ierr2, ierr3   ! local integers
+      !!
+      CHARACTER(len=100)            ::   cn_dir          ! Root directory for location of ssr files
+      TYPE(FLD_N), DIMENSION( jpts) ::   slf_i           ! array of namelist informations on the fields to read
+      TYPE(FLD_N)                   ::   sn_tem, sn_sal
+      !!
+      NAMELIST/namtsd/   ln_tsd_init, ln_tsd_dmp, cn_dir, sn_tem, sn_sal
+      !!----------------------------------------------------------------------
+      !
+      !  Initialisation
+      ierr0 = 0  ;  ierr1 = 0  ;  ierr2 = 0  ;  ierr3 = 0
+      !
+      REWIND( numnam_ref )              ! Namelist namtsd in reference namelist : 
+      READ  ( numnam_ref, namtsd, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtsd in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namtsd in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namtsd, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtsd in configuration namelist' )
+      IF(lwm) WRITE ( numond, namtsd )
+
+      IF( PRESENT( ld_tradmp ) )   ln_tsd_dmp = .TRUE.     ! forces the initialization when tradmp is used
+      
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dta_tsd_init : Temperature & Salinity data '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namtsd'
+         WRITE(numout,*) '      Initialisation of ocean T & S with T &S input data   ln_tsd_init = ', ln_tsd_init
+         WRITE(numout,*) '      damping of ocean T & S toward T &S input data        ln_tsd_dmp  = ', ln_tsd_dmp
+         WRITE(numout,*)
+         IF( .NOT.ln_tsd_init .AND. .NOT.ln_tsd_dmp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ===>>   T & S data not used'
+         ENDIF
+      ENDIF
+      !
+      IF( ln_rstart .AND. ln_tsd_init ) THEN
+         CALL ctl_warn( 'dta_tsd_init: ocean restart and T & S data intialisation, ',   &
+            &           'we keep the restart T & S values and set ln_tsd_init to FALSE' )
+         ln_tsd_init = .FALSE.
+      ENDIF
+      !
+      !                             ! allocate the arrays (if necessary)
+      IF( ln_tsd_init .OR. ln_tsd_dmp ) THEN
+         !
+         ALLOCATE( sf_tsd(jpts), STAT=ierr0 )
+         IF( ierr0 > 0 ) THEN
+            CALL ctl_stop( 'dta_tsd_init: unable to allocate sf_tsd structure' )   ;   RETURN
+         ENDIF
+         !
+                                ALLOCATE( sf_tsd(jp_tem)%fnow(jpi,jpj,jpk)   , STAT=ierr0 )
+         IF( sn_tem%ln_tint )   ALLOCATE( sf_tsd(jp_tem)%fdta(jpi,jpj,jpk,2) , STAT=ierr1 )
+                                ALLOCATE( sf_tsd(jp_sal)%fnow(jpi,jpj,jpk)   , STAT=ierr2 )
+         IF( sn_sal%ln_tint )   ALLOCATE( sf_tsd(jp_sal)%fdta(jpi,jpj,jpk,2) , STAT=ierr3 )
+         !
+         IF( ierr0 + ierr1 + ierr2 + ierr3 > 0 ) THEN
+            CALL ctl_stop( 'dta_tsd : unable to allocate T & S data arrays' )   ;   RETURN
+         ENDIF
+         !                         ! fill sf_tsd with sn_tem & sn_sal and control print
+         slf_i(jp_tem) = sn_tem   ;   slf_i(jp_sal) = sn_sal
+         CALL fld_fill( sf_tsd, slf_i, cn_dir, 'dta_tsd', 'Temperature & Salinity data', 'namtsd', no_print )
+         !
+      ENDIF
+      !
+   END SUBROUTINE dta_tsd_init
+
+
+   SUBROUTINE dta_tsd( kt, ptsd )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE dta_tsd  ***
+      !!                    
+      !! ** Purpose :   provides T and S data at kt
+      !! 
+      !! ** Method  : - call fldread routine
+      !!              - ORCA_R2: add some hand made alteration to read data  
+      !!              - 'key_orca_lev10' interpolates on 10 times more levels
+      !!              - s- or mixed z-s coordinate: vertical interpolation on model mesh
+      !!              - ln_tsd_dmp=F: deallocates the T-S data structure
+      !!                as T-S data are no are used
+      !!
+      !! ** Action  :   ptsd   T-S data on medl mesh and interpolated at time-step kt
+      !!----------------------------------------------------------------------
+      INTEGER                              , INTENT(in   ) ::   kt     ! ocean time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   ptsd   ! T & S data
+      !
+      INTEGER ::   ji, jj, jk, jl, jkk   ! dummy loop indicies
+      INTEGER ::   ik, il0, il1, ii0, ii1, ij0, ij1   ! local integers
+      REAL(wp)::   zl, zi                             ! local scalars
+      REAL(wp), DIMENSION(jpk) ::  ztp, zsp   ! 1D workspace
+      !!----------------------------------------------------------------------
+      !
+      CALL fld_read( kt, 1, sf_tsd )      !==   read T & S data at kt time step   ==!
+      !
+      !
+!!gm  This should be removed from the code   ===>>>>  T & S files has to be changed
+      !
+      !                                   !==   ORCA_R2 configuration and T & S damping   ==! 
+      IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
+         IF( nn_cfg == 2 .AND. ln_tsd_dmp ) THEN    ! some hand made alterations
+            !
+            ij0 = 101   ;   ij1 = 109                       ! Reduced T & S in the Alboran Sea
+            ii0 = 141   ;   ii1 = 155
+            DO jj = mj0(ij0), mj1(ij1)
+               DO ji = mi0(ii0), mi1(ii1)
+                  sf_tsd(jp_tem)%fnow(ji,jj,13:13) = sf_tsd(jp_tem)%fnow(ji,jj,13:13) - 0.20_wp
+                  sf_tsd(jp_tem)%fnow(ji,jj,14:15) = sf_tsd(jp_tem)%fnow(ji,jj,14:15) - 0.35_wp
+                  sf_tsd(jp_tem)%fnow(ji,jj,16:25) = sf_tsd(jp_tem)%fnow(ji,jj,16:25) - 0.40_wp
+                  !
+                  sf_tsd(jp_sal)%fnow(ji,jj,13:13) = sf_tsd(jp_sal)%fnow(ji,jj,13:13) - 0.15_wp
+                  sf_tsd(jp_sal)%fnow(ji,jj,14:15) = sf_tsd(jp_sal)%fnow(ji,jj,14:15) - 0.25_wp
+                  sf_tsd(jp_sal)%fnow(ji,jj,16:17) = sf_tsd(jp_sal)%fnow(ji,jj,16:17) - 0.30_wp
+                  sf_tsd(jp_sal)%fnow(ji,jj,18:25) = sf_tsd(jp_sal)%fnow(ji,jj,18:25) - 0.35_wp
+               END DO
+            END DO
+            ij0 =  87   ;   ij1 =  96                          ! Reduced temperature in Red Sea
+            ii0 = 148   ;   ii1 = 160
+            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ,  4:10 ) = 7.0_wp
+            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 11:13 ) = 6.5_wp
+            sf_tsd(jp_tem)%fnow( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 14:20 ) = 6.0_wp
+         ENDIF
+      ENDIF
+!!gm end
+      !
+      ptsd(:,:,:,jp_tem) = sf_tsd(jp_tem)%fnow(:,:,:)    ! NO mask
+      ptsd(:,:,:,jp_sal) = sf_tsd(jp_sal)%fnow(:,:,:) 
+      !
+      IF( ln_sco ) THEN                   !==   s- or mixed s-zps-coordinate   ==!
+         !
+         IF( kt == nit000 .AND. lwp )THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'dta_tsd: interpolates T & S data onto the s- or mixed s-z-coordinate mesh'
+         ENDIF
+         !
+         DO jj = 1, jpj                         ! vertical interpolation of T & S
+            DO ji = 1, jpi
+               DO jk = 1, jpk                        ! determines the intepolated T-S profiles at each (i,j) points
+                  zl = gdept_0(ji,jj,jk)
+                  IF(     zl < gdept_1d(1  ) ) THEN          ! above the first level of data
+                     ztp(jk) =  ptsd(ji,jj,1    ,jp_tem)
+                     zsp(jk) =  ptsd(ji,jj,1    ,jp_sal)
+                  ELSEIF( zl > gdept_1d(jpk) ) THEN          ! below the last level of data
+                     ztp(jk) =  ptsd(ji,jj,jpkm1,jp_tem)
+                     zsp(jk) =  ptsd(ji,jj,jpkm1,jp_sal)
+                  ELSE                                      ! inbetween : vertical interpolation between jkk & jkk+1
+                     DO jkk = 1, jpkm1                                  ! when  gdept(jkk) < zl < gdept(jkk+1)
+                        IF( (zl-gdept_1d(jkk)) * (zl-gdept_1d(jkk+1)) <= 0._wp ) THEN
+                           zi = ( zl - gdept_1d(jkk) ) / (gdept_1d(jkk+1)-gdept_1d(jkk))
+                           ztp(jk) = ptsd(ji,jj,jkk,jp_tem) + ( ptsd(ji,jj,jkk+1,jp_tem) - ptsd(ji,jj,jkk,jp_tem) ) * zi 
+                           zsp(jk) = ptsd(ji,jj,jkk,jp_sal) + ( ptsd(ji,jj,jkk+1,jp_sal) - ptsd(ji,jj,jkk,jp_sal) ) * zi
+                        ENDIF
+                     END DO
+                  ENDIF
+               END DO
+               DO jk = 1, jpkm1
+                  ptsd(ji,jj,jk,jp_tem) = ztp(jk) * tmask(ji,jj,jk)     ! mask required for mixed zps-s-coord
+                  ptsd(ji,jj,jk,jp_sal) = zsp(jk) * tmask(ji,jj,jk)
+               END DO
+               ptsd(ji,jj,jpk,jp_tem) = 0._wp
+               ptsd(ji,jj,jpk,jp_sal) = 0._wp
+            END DO
+         END DO
+         ! 
+      ELSE                                !==   z- or zps- coordinate   ==!
+         !                             
+         ptsd(:,:,:,jp_tem) = ptsd(:,:,:,jp_tem) * tmask(:,:,:)    ! Mask
+         ptsd(:,:,:,jp_sal) = ptsd(:,:,:,jp_sal) * tmask(:,:,:)
+         !
+         IF( ln_zps ) THEN                      ! zps-coordinate (partial steps) interpolation at the last ocean level
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ik = mbkt(ji,jj) 
+                  IF( ik > 1 ) THEN
+                     zl = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+                     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)
+                  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
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( .NOT.ln_tsd_dmp ) THEN                   !==   deallocate T & S structure   ==! 
+         !                                              (data used only for initialisation)
+         IF(lwp) WRITE(numout,*) 'dta_tsd: deallocte T & S arrays as they are only use to initialize the run'
+                                        DEALLOCATE( sf_tsd(jp_tem)%fnow )     ! T arrays in the structure
+         IF( sf_tsd(jp_tem)%ln_tint )   DEALLOCATE( sf_tsd(jp_tem)%fdta )
+                                        DEALLOCATE( sf_tsd(jp_sal)%fnow )     ! S arrays in the structure
+         IF( sf_tsd(jp_sal)%ln_tint )   DEALLOCATE( sf_tsd(jp_sal)%fdta )
+                                        DEALLOCATE( sf_tsd              )     ! the structure itself
+      ENDIF
+      !
+   END SUBROUTINE dta_tsd
+
+   !!======================================================================
+END MODULE dtatsd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplhsb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplhsb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplhsb.F90	(revision 14097)
@@ -0,0 +1,324 @@
+MODULE iscplhsb
+   !!======================================================================
+   !!                       ***  MODULE  iscplhsb  ***
+   !! Ocean forcing: ice sheet/ocean coupling (conservation)
+   !!=====================================================================
+   !! History :  NEMO  ! 2015-01 P. Mathiot: original 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   iscpl_alloc    : variable allocation
+   !!   iscpl_hsb      : compute and store the input of heat/salt/volume 
+   !!                    into the system due to the coupling process
+   !!   iscpl_div      : correction of divergence to keep volume conservation
+   !!----------------------------------------------------------------------
+   USE oce             ! global tra/dyn variable
+   USE dom_oce         ! ocean space and time domain
+   USE domwri          ! ocean space and time domain
+   USE domngb          ! 
+   USE phycst          ! physical constants
+   USE sbc_oce         ! surface boundary condition variables
+   USE iscplini        ! 
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   USE lib_fortran     ! MPP library
+   USE lbclnk          !
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   iscpl_div   
+   PUBLIC   iscpl_cons       
+   !! * Substitutions  
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE iscpl_cons(ptmask_b, psmask_b, pe3t_b, pts_flx, pvol_flx, prdt_iscpl)
+      !!---------------------------------------------------------------------- 
+      !!                   ***  ROUTINE iscpl_cons  ***
+      !! 
+      !! ** Purpose :   compute input into the system during the coupling step
+      !!                compute the correction term
+      !!                compute where the correction have to be applied
+      !! 
+      !! ** Method  :   compute tsn*e3t-tsb*e3tb and e3t-e3t_b
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(in ) :: ptmask_b    !! mask before
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(in ) :: pe3t_b      !! scale factor before
+      REAL(wp), DIMENSION(:,:    ), INTENT(in ) :: psmask_b    !! mask before
+      REAL(wp), DIMENSION(:,:,:,:), INTENT(out) :: pts_flx     !! corrective flux to have tracer conservation
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(out) :: pvol_flx    !! corrective flux to have volume conservation
+      REAL(wp),                     INTENT(in ) :: prdt_iscpl  !! coupling period 
+      !
+      INTEGER  ::   ji  , jj  , jk           ! loop index
+      INTEGER  ::   jip1, jim1, jjp1, jjm1
+      REAL(wp) ::   summsk, zsum , zsumn, zjip1_ratio  , zjim1_ratio, zdtem, zde3t, z1_rdtiscpl
+      REAL(wp) ::   zarea , zsum1, zsumb, zjjp1_ratio  , zjjm1_ratio, zdsal
+      REAL(wp), DIMENSION(jpi,jpj)        ::   zdssh   ! workspace
+      REAL(wp), DIMENSION(:), ALLOCATABLE ::   zlon, zlat
+      REAL(wp), DIMENSION(:), ALLOCATABLE ::   zcorr_vol, zcorr_tem, zcorr_sal
+      INTEGER , DIMENSION(:), ALLOCATABLE ::   ixpts, iypts, izpts, inpts
+      INTEGER :: jpts, npts
+      !!----------------------------------------------------------------------
+
+      ! get imbalance (volume heat and salt)
+      ! initialisation difference
+      zde3t = 0._wp   ;   zdsal = 0._wp   ;   zdtem = 0._wp
+
+      ! initialisation correction term
+      pvol_flx(:,:,:  ) = 0._wp
+      pts_flx (:,:,:,:) = 0._wp
+      
+      z1_rdtiscpl = 1._wp / prdt_iscpl 
+
+      ! mask tsn and tsb 
+      tsb(:,:,:,jp_tem) = tsb(:,:,:,jp_tem) * ptmask_b(:,:,:)
+      tsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem) *  tmask  (:,:,:)
+      tsb(:,:,:,jp_sal) = tsb(:,:,:,jp_sal) * ptmask_b(:,:,:)
+      tsn(:,:,:,jp_sal) = tsn(:,:,:,jp_sal) *  tmask  (:,:,:)
+
+      !==============================================================================
+      ! diagnose the heat, salt and volume input and compute the correction variable
+      !==============================================================================
+
+      ! 
+      zdssh(:,:) = sshn(:,:) * ssmask(:,:) - sshb(:,:) * psmask_b(:,:)
+      IF (.NOT. ln_linssh ) zdssh = 0.0_wp ! already included in the levels by definition
+      
+      DO jk = 1,jpk-1
+         DO jj = 2,jpj-1
+            DO ji = fs_2,fs_jpim1
+               IF (tmask_h(ji,jj) == 1._wp) THEN
+
+                  ! volume differences
+                  zde3t = e3t_n(ji,jj,jk) * tmask(ji,jj,jk) - pe3t_b(ji,jj,jk) * ptmask_b(ji,jj,jk)
+
+                  ! heat diff
+                  zdtem = tsn(ji,jj,jk,jp_tem) * e3t_n(ji,jj,jk) *  tmask  (ji,jj,jk)   &
+                        - tsb(ji,jj,jk,jp_tem) * pe3t_b (ji,jj,jk) * ptmask_b(ji,jj,jk)
+                  ! salt diff
+                  zdsal = tsn(ji,jj,jk,jp_sal) * e3t_n(ji,jj,jk) *  tmask  (ji,jj,jk)   &
+                        - tsb(ji,jj,jk,jp_sal) * pe3t_b (ji,jj,jk) * ptmask_b(ji,jj,jk)
+               
+                  ! shh changes
+                  IF ( ptmask_b(ji,jj,jk) == 1._wp .OR. tmask(ji,jj,jk) == 1._wp ) THEN 
+                     zde3t = zde3t + zdssh(ji,jj) ! zdssh = 0 if vvl
+                     zdssh(ji,jj) = 0._wp
+                  END IF
+
+                  ! volume, heat and salt differences in each cell 
+                  pvol_flx(ji,jj,jk)       =   pvol_flx(ji,jj,jk)        + zde3t * z1_rdtiscpl
+                  pts_flx (ji,jj,jk,jp_sal)=   pts_flx (ji,jj,jk,jp_sal) + zdsal * z1_rdtiscpl 
+                  pts_flx (ji,jj,jk,jp_tem)=   pts_flx (ji,jj,jk,jp_tem) + zdtem * z1_rdtiscpl
+
+                  ! case where we close a cell: check if the neighbour cells are wet 
+                  IF ( tmask(ji,jj,jk) == 0._wp .AND. ptmask_b(ji,jj,jk) == 1._wp ) THEN
+
+                     jip1=ji+1 ; jim1=ji-1 ; jjp1=jj+1 ; jjm1=jj-1 ;
+
+                     zsum =   e1e2t(ji  ,jjp1) * tmask(ji  ,jjp1,jk) + e1e2t(ji  ,jjm1) * tmask(ji  ,jjm1,jk) &
+                       &    + e1e2t(jim1,jj  ) * tmask(jim1,jj  ,jk) + e1e2t(jip1,jj  ) * tmask(jip1,jj  ,jk)
+
+                     IF ( zsum /= 0._wp ) THEN
+                        zjip1_ratio   = e1e2t(jip1,jj  ) * tmask(jip1,jj  ,jk) / zsum
+                        zjim1_ratio   = e1e2t(jim1,jj  ) * tmask(jim1,jj  ,jk) / zsum
+                        zjjp1_ratio   = e1e2t(ji  ,jjp1) * tmask(ji  ,jjp1,jk) / zsum
+                        zjjm1_ratio   = e1e2t(ji  ,jjm1) * tmask(ji  ,jjm1,jk) / zsum
+
+                        pvol_flx(ji  ,jjp1,jk       ) = pvol_flx(ji  ,jjp1,jk       ) + pvol_flx(ji,jj,jk       ) * zjjp1_ratio
+                        pvol_flx(ji  ,jjm1,jk       ) = pvol_flx(ji  ,jjm1,jk       ) + pvol_flx(ji,jj,jk       ) * zjjm1_ratio
+                        pvol_flx(jip1,jj  ,jk       ) = pvol_flx(jip1,jj  ,jk       ) + pvol_flx(ji,jj,jk       ) * zjip1_ratio
+                        pvol_flx(jim1,jj  ,jk       ) = pvol_flx(jim1,jj  ,jk       ) + pvol_flx(ji,jj,jk       ) * zjim1_ratio
+                        pts_flx (ji  ,jjp1,jk,jp_sal) = pts_flx (ji  ,jjp1,jk,jp_sal) + pts_flx (ji,jj,jk,jp_sal) * zjjp1_ratio
+                        pts_flx (ji  ,jjm1,jk,jp_sal) = pts_flx (ji  ,jjm1,jk,jp_sal) + pts_flx (ji,jj,jk,jp_sal) * zjjm1_ratio
+                        pts_flx (jip1,jj  ,jk,jp_sal) = pts_flx (jip1,jj  ,jk,jp_sal) + pts_flx (ji,jj,jk,jp_sal) * zjip1_ratio
+                        pts_flx (jim1,jj  ,jk,jp_sal) = pts_flx (jim1,jj  ,jk,jp_sal) + pts_flx (ji,jj,jk,jp_sal) * zjim1_ratio
+                        pts_flx (ji  ,jjp1,jk,jp_tem) = pts_flx (ji  ,jjp1,jk,jp_tem) + pts_flx (ji,jj,jk,jp_tem) * zjjp1_ratio
+                        pts_flx (ji  ,jjm1,jk,jp_tem) = pts_flx (ji  ,jjm1,jk,jp_tem) + pts_flx (ji,jj,jk,jp_tem) * zjjm1_ratio
+                        pts_flx (jip1,jj  ,jk,jp_tem) = pts_flx (jip1,jj  ,jk,jp_tem) + pts_flx (ji,jj,jk,jp_tem) * zjip1_ratio
+                        pts_flx (jim1,jj  ,jk,jp_tem) = pts_flx (jim1,jj  ,jk,jp_tem) + pts_flx (ji,jj,jk,jp_tem) * zjim1_ratio
+
+                        ! set to 0 the cell we distributed over neigbourg cells
+                        pvol_flx(ji,jj,jk       ) = 0._wp
+                        pts_flx (ji,jj,jk,jp_sal) = 0._wp
+                        pts_flx (ji,jj,jk,jp_tem) = 0._wp
+
+                     ELSE IF (zsum == 0._wp ) THEN
+                        ! case where we close a cell and no adjacent cell open
+                        ! check if the cell beneath is wet
+                        IF ( tmask(ji,jj,jk+1) == 1._wp ) THEN
+                           pvol_flx(ji,jj,jk+1)       =  pvol_flx(ji,jj,jk+1)        + pvol_flx(ji,jj,jk)
+                           pts_flx (ji,jj,jk+1,jp_sal)=  pts_flx (ji,jj,jk+1,jp_sal) + pts_flx (ji,jj,jk,jp_sal)
+                           pts_flx (ji,jj,jk+1,jp_tem)=  pts_flx (ji,jj,jk+1,jp_tem) + pts_flx (ji,jj,jk,jp_tem)
+
+                           ! set to 0 the cell we distributed over neigbourg cells
+                           pvol_flx(ji,jj,jk       ) = 0._wp
+                           pts_flx (ji,jj,jk,jp_sal) = 0._wp
+                           pts_flx (ji,jj,jk,jp_tem) = 0._wp
+                        ELSE
+                        ! case no adjacent cell on the horizontal and on the vertical
+                           IF ( lwp ) THEN   ! JMM : cAution this warning may occur on any mpp subdomain but numout is only
+                                             ! open for narea== 1 (lwp=T)
+                           WRITE(numout,*) 'W A R N I N G iscpl: no adjacent cell on the vertical and horizontal'
+                           WRITE(numout,*) '                     ',mig(ji),' ',mjg(jj),' ',jk
+                           WRITE(numout,*) '                     ',ji,' ',jj,' ',jk,' ',narea
+                           WRITE(numout,*) ' we are now looking for the closest wet cell on the horizontal '
+                           ENDIF
+                        ! We deal with these points later.
+                        END IF
+                     END IF
+                  END IF
+               END IF
+            END DO
+         END DO
+      END DO
+
+!!gm  ERROR !!!!
+!!    juste use tmask_i  or in case of ISF smask_i (to be created to compute the sum without halos)
+!
+!      CALL lbc_sum(pvol_flx(:,:,:       ),'T',1.)
+!      CALL lbc_sum(pts_flx (:,:,:,jp_sal),'T',1.)
+!      CALL lbc_sum(pts_flx (:,:,:,jp_tem),'T',1.)
+      CALL ctl_stop( 'STOP', ' iscpl_cons:   please modify this MODULE !' )
+!!gm end
+      ! if no neighbour wet cell in case of 2close a cell", need to find the nearest wet point 
+      ! allocation and initialisation of the list of problematic point
+      ALLOCATE( inpts(jpnij) )
+      inpts(:) = 0
+
+      ! fill narea location with the number of problematic point
+      DO jk = 1,jpk-1
+         DO jj = 2,jpj-1
+            DO ji = fs_2,fs_jpim1
+               IF (     ptmask_b(ji,jj,jk) == 1._wp .AND. tmask(ji,jj,jk+1)  == 0._wp .AND. tmask_h(ji,jj) == 1._wp  &
+                  .AND. SUM(tmask(ji-1:ji+1,jj,jk)) + SUM(tmask(ji,jj-1:jj+1,jk)) == 0._wp) THEN
+                  inpts(narea) = inpts(narea) + 1 
+               END IF
+            END DO
+         END DO
+      END DO
+
+      ! build array of total problematic point on each cpu (share to each cpu)
+      CALL mpp_max('iscplhsb', inpts,jpnij) 
+
+      ! size of the new variable
+      npts  = SUM(inpts)    
+      
+      ! allocation of the coordinates, correction, index vector for the problematic points 
+      ALLOCATE(ixpts(npts), iypts(npts), izpts(npts), zcorr_vol(npts), zcorr_sal(npts), zcorr_tem(npts), zlon(npts), zlat(npts))
+      ixpts(:) = -9999 ; iypts(:) = -9999 ; izpts(:) = -9999 ; zlon(:) = -1.0e20_wp ; zlat(:) = -1.0e20_wp
+      zcorr_vol(:) = -1.0e20_wp
+      zcorr_sal(:) = -1.0e20_wp
+      zcorr_tem(:) = -1.0e20_wp
+
+      ! fill new variable
+      jpts = SUM(inpts(1:narea-1))
+      DO jk = 1,jpk-1
+         DO jj = 2,jpj-1
+            DO ji = fs_2,fs_jpim1
+               IF (     ptmask_b(ji,jj,jk) == 1._wp .AND. tmask(ji,jj,jk+1)  == 0._wp .AND. tmask_h(ji,jj) == 1._wp  &
+                  .AND. SUM(tmask(ji-1:ji+1,jj,jk)) + SUM(tmask(ji,jj-1:jj+1,jk)) == 0._wp) THEN
+                  jpts = jpts + 1  ! positioning in the inpts vector for the area narea
+                  ixpts(jpts) = ji           ; iypts(jpts) = jj ; izpts(jpts) = jk
+                  zlon (jpts) = glamt(ji,jj) ; zlat (jpts) = gphit(ji,jj)
+                  zcorr_vol(jpts) = pvol_flx(ji,jj,jk)
+                  zcorr_sal(jpts) = pts_flx (ji,jj,jk,jp_sal)
+                  zcorr_tem(jpts) = pts_flx (ji,jj,jk,jp_tem)
+
+                  ! set flx to 0 (safer)
+                  pvol_flx(ji,jj,jk       ) = 0.0_wp
+                  pts_flx (ji,jj,jk,jp_sal) = 0.0_wp
+                  pts_flx (ji,jj,jk,jp_tem) = 0.0_wp
+               END IF
+            END DO
+         END DO
+      END DO
+
+      ! build array of total problematic point on each cpu (share to each cpu)
+      ! point coordinates
+      CALL mpp_max('iscplhsb', zlat ,npts)
+      CALL mpp_max('iscplhsb', zlon ,npts)
+      CALL mpp_max('iscplhsb', izpts,npts)
+
+      ! correction values 
+      CALL mpp_max('iscplhsb', zcorr_vol,npts)
+      CALL mpp_max('iscplhsb', zcorr_sal,npts)
+      CALL mpp_max('iscplhsb', zcorr_tem,npts)
+
+      ! put correction term in the closest cell          
+      DO jpts = 1,npts
+         CALL dom_ngb(zlon(jpts), zlat(jpts), ixpts(jpts), iypts(jpts),'T', izpts(jpts))
+         DO jj = mj0(iypts(jpts)),mj1(iypts(jpts))
+            DO ji = mi0(ixpts(jpts)),mi1(ixpts(jpts))
+               jk = izpts(jpts)
+
+               IF (tmask_h(ji,jj) == 1._wp) THEN
+                  ! correct the vol_flx in the closest cell
+                  pvol_flx(ji,jj,jk)        =  pvol_flx(ji,jj,jk       ) + zcorr_vol(jpts)
+                  pts_flx (ji,jj,jk,jp_sal) =  pts_flx (ji,jj,jk,jp_sal) + zcorr_sal(jpts)
+                  pts_flx (ji,jj,jk,jp_tem) =  pts_flx (ji,jj,jk,jp_tem) + zcorr_tem(jpts)
+
+                  ! set correction to 0
+                  zcorr_vol(jpts) = 0.0_wp
+                  zcorr_sal(jpts) = 0.0_wp
+                  zcorr_tem(jpts) = 0.0_wp
+               END IF
+            END DO
+         END DO
+      END DO
+
+      ! deallocate variables 
+      DEALLOCATE(inpts)
+      DEALLOCATE(ixpts, iypts, izpts, zcorr_vol, zcorr_sal, zcorr_tem, zlon, zlat)
+    
+      ! add contribution store on the hallo (lbclnk remove one of the contribution)
+      pvol_flx(:,:,:       ) = pvol_flx(:,:,:       ) * tmask(:,:,:)
+      pts_flx (:,:,:,jp_sal) = pts_flx (:,:,:,jp_sal) * tmask(:,:,:)
+      pts_flx (:,:,:,jp_tem) = pts_flx (:,:,:,jp_tem) * tmask(:,:,:)
+
+!!gm  ERROR !!!!
+!!    juste use tmask_i  or in case of ISF smask_i (to be created to compute the sum without halos)
+!
+!      ! compute sum over the halo and set it to 0.
+!      CALL lbc_sum(pvol_flx(:,:,:       ),'T',1._wp)
+!      CALL lbc_sum(pts_flx (:,:,:,jp_sal),'T',1._wp)
+!      CALL lbc_sum(pts_flx (:,:,:,jp_tem),'T',1._wp)
+!!gm end
+
+      !
+   END SUBROUTINE iscpl_cons
+
+
+   SUBROUTINE iscpl_div( phdivn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE iscpl_div  ***
+      !!
+      !! ** Purpose :   update the horizontal divergenc
+      !!
+      !! ** Method  :
+      !!                CAUTION : iscpl is positive (inflow) and expressed in m/s
+      !!
+      !! ** Action  :   phdivn   increase by the iscpl correction term
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   phdivn   ! horizontal divergence
+      !!
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               phdivn(ji,jj,jk) = phdivn(ji,jj,jk) + hdiv_iscpl(ji,jj,jk) / e3t_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE iscpl_div
+
+END MODULE iscplhsb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplini.F90	(revision 14097)
@@ -0,0 +1,90 @@
+MODULE iscplini
+   !!======================================================================
+   !!                       ***  MODULE  sbciscpl  ***
+   !! Ocean forcing:  ?????
+   !!=====================================================================
+   !! History :  NEMO  ! 2015-01 P. Mathiot: original 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   iscpl_init     : initialisation routine (namelist)
+   !!   iscpl_alloc    : allocation of correction variables
+   !!----------------------------------------------------------------------
+   USE oce             ! global tra/dyn variable
+   USE dom_oce         ! ocean space and time domain
+   !
+   USE lib_mpp         ! MPP library
+   USE lib_fortran     ! MPP library
+   USE in_out_manager  ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   iscpl_init      
+   PUBLIC   iscpl_alloc 
+   
+   !                                 !!* namsbc_iscpl namelist *
+   LOGICAL , PUBLIC ::   ln_hsb       !:
+   INTEGER , PUBLIC ::   nn_fiscpl    !:
+   INTEGER , PUBLIC ::   nn_drown     !:
+   
+   INTEGER , PUBLIC ::   nstp_iscpl   !:
+   REAL(wp), PUBLIC ::   rdt_iscpl    !: 
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   hdiv_iscpl   !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   htsc_iscpl   !:
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION iscpl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE sbc_iscpl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( htsc_iscpl(jpi,jpj,jpk,jpts) , hdiv_iscpl(jpi,jpj,jpk) , STAT=iscpl_alloc )
+         !
+      CALL mpp_sum ( 'iscplini', iscpl_alloc )
+      IF( iscpl_alloc > 0 )   CALL ctl_warn('iscpl_alloc: allocation of arrays failed')
+   END FUNCTION iscpl_alloc
+
+
+   SUBROUTINE iscpl_init()
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios           ! Local integer output status for namelist read
+      NAMELIST/namsbc_iscpl/ nn_fiscpl, ln_hsb, nn_drown
+      !!----------------------------------------------------------------------
+      !
+      nn_fiscpl = 0
+      ln_hsb    = .FALSE.
+      REWIND( numnam_ref )              ! Namelist namsbc_iscpl in reference namelist : Ice sheet coupling
+      READ  ( numnam_ref, namsbc_iscpl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_iscpl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namsbc_iscpl in configuration namelist : Ice Sheet coupling
+      READ  ( numnam_cfg, namsbc_iscpl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_iscpl in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_iscpl )
+      !
+      nstp_iscpl=MIN( nn_fiscpl, nitend-nit000+1 ) ! the coupling period have to be less or egal than the total number of time step
+      rdt_iscpl = nstp_iscpl * rn_rdt
+      !
+      IF (lwp) THEN
+         WRITE(numout,*) 'iscpl_rst:'
+         WRITE(numout,*) '~~~~~~~~~'
+         WRITE(numout,*) ' coupling     flag (ln_iscpl )            = ', ln_iscpl
+         WRITE(numout,*) ' conservation flag (ln_hsb   )            = ', ln_hsb
+         WRITE(numout,*) ' nb of stp for cons (rn_fiscpl)           = ', nstp_iscpl
+         IF (nstp_iscpl .NE. nn_fiscpl) WRITE(numout,*) 'W A R N I N G: nb of stp for cons has been modified &
+            &                                           (larger than run length)'
+         WRITE(numout,*) ' coupling time step                       = ', rdt_iscpl
+         WRITE(numout,*) ' number of call of the extrapolation loop = ', nn_drown
+      ENDIF
+      !
+   END SUBROUTINE iscpl_init
+
+   !!======================================================================
+END MODULE iscplini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplrst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplrst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/iscplrst.F90	(revision 14097)
@@ -0,0 +1,407 @@
+MODULE iscplrst
+   !!======================================================================
+   !!                       ***  MODULE  iscplrst  ***
+   !! Ocean forcing: update the restart file in case of ice sheet/ocean coupling
+   !!=====================================================================
+   !! History :  NEMO  ! 2015-01 P. Mathiot: original 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   iscpl_stp          : step management
+   !!   iscpl_rst_interpol : restart interpolation in case of coupling with ice sheet
+   !!----------------------------------------------------------------------
+   USE oce             ! global tra/dyn variable
+   USE dom_oce         ! ocean space and time domain
+   USE domwri          ! ocean space and time domain
+   USE domvvl   , ONLY : dom_vvl_interpol
+   USE phycst          ! physical constants
+   USE sbc_oce         ! surface boundary condition variables
+   USE iscplini        ! ice sheet coupling: initialisation
+   USE iscplhsb        ! ice sheet coupling: conservation
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module
+   USE lib_mpp         ! MPP library
+   USE lib_fortran     ! MPP library
+   USE lbclnk          ! communication
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   iscpl_stp          ! step management 
+   !!
+   !! * Substitutions  
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE iscpl_stp
+      !!---------------------------------------------------------------------- 
+      !!                   ***  ROUTINE iscpl_stp  ***
+      !! 
+      !! ** Purpose : compute initialisation
+      !!              compute extrapolation of restart variable un, vn, tsn, sshn (wetting/drying)   
+      !!              compute correction term if needed
+      !! 
+      !!----------------------------------------------------------------------
+      INTEGER  ::   inum0
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zsmask_b
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztmask_b, zumask_b, zvmask_b
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ze3t_b  , ze3u_b  , ze3v_b  
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdepw_b
+      CHARACTER(20) :: cfile
+      !!----------------------------------------------------------------------
+      !
+      !                       ! get restart variable
+      CALL iom_get( numror, jpdom_autoglo, 'tmask'  , ztmask_b, ldxios = lrxios   ) ! need to extrapolate T/S
+      CALL iom_get( numror, jpdom_autoglo, 'umask'  , zumask_b, ldxios = lrxios   ) ! need to correct barotropic velocity
+      CALL iom_get( numror, jpdom_autoglo, 'vmask'  , zvmask_b, ldxios = lrxios   ) ! need to correct barotropic velocity
+      CALL iom_get( numror, jpdom_autoglo, 'smask'  , zsmask_b, ldxios = lrxios   ) ! need to correct barotropic velocity
+      CALL iom_get( numror, jpdom_autoglo, 'e3t_n'  , ze3t_b(:,:,:), ldxios = lrxios )  ! need to compute temperature correction
+      CALL iom_get( numror, jpdom_autoglo, 'e3u_n'  , ze3u_b(:,:,:), ldxios = lrxios )  ! need to correct barotropic velocity
+      CALL iom_get( numror, jpdom_autoglo, 'e3v_n'  , ze3v_b(:,:,:), ldxios = lrxios )  ! need to correct barotropic velocity
+      CALL iom_get( numror, jpdom_autoglo, 'gdepw_n', zdepw_b(:,:,:), ldxios = lrxios ) ! need to interpol vertical profile (vvl)
+      !
+      CALL iscpl_init()       ! read namelist
+      !                       ! Extrapolation/interpolation of modify cell and new cells ... (maybe do it later after domvvl)
+      CALL iscpl_rst_interpol( ztmask_b, zumask_b, zvmask_b, zsmask_b, ze3t_b, ze3u_b, ze3v_b, zdepw_b )
+      !
+      IF ( ln_hsb ) THEN      ! compute correction if conservation needed
+         IF( iscpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'rst_iscpl : unable to allocate rst_iscpl arrays' )
+         CALL iscpl_cons(ztmask_b, zsmask_b, ze3t_b, htsc_iscpl, hdiv_iscpl, rdt_iscpl)
+      END IF
+         
+      !                       ! create  a domain file
+      IF( ln_meshmask .AND. ln_iscpl )   CALL dom_wri
+      !
+      IF ( ln_hsb ) THEN
+         cfile='correction'
+         cfile = TRIM( cfile )
+         CALL iom_open  ( cfile, inum0, ldwrt = .TRUE. )
+         CALL iom_rstput( 0, 0, inum0, 'vol_cor', hdiv_iscpl(:,:,:) )
+         CALL iom_rstput( 0, 0, inum0, 'tem_cor', htsc_iscpl(:,:,:,jp_tem) )
+         CALL iom_rstput( 0, 0, inum0, 'sal_cor', htsc_iscpl(:,:,:,jp_sal) )
+         CALL iom_close ( inum0 )
+      END IF
+      !
+      neuler = 0              ! next step is an euler time step
+      !
+      !                       ! set _b and _n variables equal
+      tsb (:,:,:,:) = tsn (:,:,:,:)
+      ub  (:,:,:)   = un  (:,:,:)
+      vb  (:,:,:)   = vn  (:,:,:)
+      sshb(:,:)     = sshn(:,:)
+      !
+      !                       ! set _b and _n vertical scale factor equal
+      e3t_b (:,:,:) = e3t_n (:,:,:)
+      e3u_b (:,:,:) = e3u_n (:,:,:)
+      e3v_b (:,:,:) = e3v_n (:,:,:)
+      !
+      e3uw_b (:,:,:) = e3uw_n (:,:,:)
+      e3vw_b (:,:,:) = e3vw_n (:,:,:)
+      gdept_b(:,:,:) = gdept_n(:,:,:)
+      gdepw_b(:,:,:) = gdepw_n(:,:,:)
+      hu_b   (:,:)   = hu_n   (:,:)
+      hv_b   (:,:)   = hv_n   (:,:)
+      r1_hu_b(:,:)   = r1_hu_n(:,:)
+      r1_hv_b(:,:)   = r1_hv_n(:,:)
+      !
+   END SUBROUTINE iscpl_stp
+
+
+   SUBROUTINE iscpl_rst_interpol (ptmask_b, pumask_b, pvmask_b, psmask_b, pe3t_b, pe3u_b, pe3v_b, pdepw_b)
+      !!---------------------------------------------------------------------- 
+      !!                   ***  ROUTINE iscpl_rst_interpol  ***
+      !! 
+      !! ** Purpose :   compute new tn, sn, un, vn and sshn in case of evolving geometry of ice shelves 
+      !!                compute 2d fields of heat, salt and volume correction
+      !! 
+      !! ** Method  :   tn, sn : extrapolation from neigbourg cells
+      !!                un, vn : fill with 0 velocity and keep barotropic transport by modifing surface velocity or adjacent velocity
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(in ) :: ptmask_b, pumask_b, pvmask_b    !! mask before
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(in ) :: pe3t_b  , pe3u_b  , pe3v_b      !! scale factor before
+      REAL(wp), DIMENSION(:,:,:  ), INTENT(in ) :: pdepw_b                         !! depth w before
+      REAL(wp), DIMENSION(:,:    ), INTENT(in ) :: psmask_b                        !! mask before
+      !!
+      INTEGER :: ji, jj, jk, iz          !! loop index
+      INTEGER :: jip1, jim1, jjp1, jjm1, jkp1, jkm1
+      !!
+      REAL(wp):: summsk, zsum, zsum1, zarea, zsumn, zsumb
+      REAL(wp):: zdz, zdzm1, zdzp1
+      !!
+      REAL(wp), DIMENSION(jpi,jpj)          :: zdmask , zsmask0, zucorr, zbub, zbun, zssh0, zhu1, zde3t
+      REAL(wp), DIMENSION(jpi,jpj)          :: zdsmask, zsmask1, zvcorr, zbvb, zbvn, zssh1, zhv1
+      REAL(wp), DIMENSION(jpi,jpj,jpk)      :: ztmask0, zwmaskn, ztrp
+      REAL(wp), DIMENSION(jpi,jpj,jpk)      :: ztmask1, zwmaskb, ztmp3d
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) :: zts0
+      !!----------------------------------------------------------------------
+      !
+      !                 ! mask value to be sure
+      tsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem) * ptmask_b(:,:,:)
+      tsn(:,:,:,jp_sal) = tsn(:,:,:,jp_sal) * ptmask_b(:,:,:)
+      !
+      !                 ! compute wmask
+      zwmaskn(:,:,1) = tmask   (:,:,1)
+      zwmaskb(:,:,1) = ptmask_b(:,:,1)
+      DO jk = 2,jpk
+         zwmaskn(:,:,jk) =  tmask  (:,:,jk) *  tmask  (:,:,jk-1)
+         zwmaskb(:,:,jk) = ptmask_b(:,:,jk) * ptmask_b(:,:,jk-1)
+      END DO
+      !    
+      !                 ! compute new ssh if we open a full water column (average of the closest neigbourgs)  
+      sshb (:,:)=sshn(:,:)
+      zssh0(:,:)=sshn(:,:)
+      zsmask0(:,:) = psmask_b(:,:)
+      zsmask1(:,:) = psmask_b(:,:)
+      DO iz = 1, 10                 ! need to be tuned (configuration dependent) (OK for ISOMIP+)
+         zdsmask(:,:) = ssmask(:,:)-zsmask0(:,:)
+         DO jj = 2,jpj-1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               jip1=ji+1; jim1=ji-1;
+               jjp1=jj+1; jjm1=jj-1;
+               summsk=(zsmask0(jip1,jj)+zsmask0(jim1,jj)+zsmask0(ji,jjp1)+zsmask0(ji,jjm1))
+               IF (zdsmask(ji,jj) == 1._wp .AND. summsk /= 0._wp) THEN
+                  sshn(ji,jj)=( zssh0(jip1,jj)*zsmask0(jip1,jj)     &
+                  &           + zssh0(jim1,jj)*zsmask0(jim1,jj)     &
+                  &           + zssh0(ji,jjp1)*zsmask0(ji,jjp1)     &
+                  &           + zssh0(ji,jjm1)*zsmask0(ji,jjm1))/summsk
+                  zsmask1(ji,jj)=1._wp
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'iscplrst', sshn, 'T', 1., zsmask1, 'T', 1. )
+         zssh0   = sshn
+         zsmask0 = zsmask1
+      END DO
+      sshn(:,:) = sshn(:,:) * ssmask(:,:)
+
+!=============================================================================
+!PM: Is this needed since introduction of VVL by default?
+      IF ( .NOT.ln_linssh ) THEN
+      ! Reconstruction of all vertical scale factors at now time steps
+      ! =============================================================================
+      ! Horizontal scale factor interpolations
+      ! --------------------------------------
+         DO jk = 1,jpk
+            DO jj=1,jpj
+               DO ji=1,jpi
+                  IF (tmask(ji,jj,1) == 0._wp .OR. ptmask_b(ji,jj,1) == 0._wp) THEN
+                     e3t_n(ji,jj,jk) = e3t_0(ji,jj,jk) * ( 1._wp + sshn(ji,jj) /   &
+                     &   ( ht_0(ji,jj) + 1._wp - ssmask(ji,jj) ) * tmask(ji,jj,jk) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+         CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+         CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )
+
+         ! Vertical scale factor interpolations
+         ! ------------------------------------
+         CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )
+         CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+         CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+         
+         ! t- and w- points depth
+         ! ----------------------
+         gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+         gdepw_n(:,:,1) = 0.0_wp
+         gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               DO jk = 2,mikt(ji,jj)-1
+                  gdept_n(ji,jj,jk) = gdept_0(ji,jj,jk)
+                  gdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+                  gde3w_n(ji,jj,jk) = gdept_0(ji,jj,jk) - sshn(ji,jj)
+               END DO
+               IF (mikt(ji,jj) > 1) THEN
+                  jk = mikt(ji,jj)
+                  gdept_n(ji,jj,jk) = gdepw_0(ji,jj,jk) + 0.5_wp * e3w_n(ji,jj,jk)
+                  gdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+                  gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk  ) - sshn   (ji,jj)
+               END IF
+               DO jk = mikt(ji,jj)+1, jpk
+                  gdept_n(ji,jj,jk) = gdept_n(ji,jj,jk-1) + e3w_n(ji,jj,jk)
+                  gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+                  gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk  ) - sshn (ji,jj)
+               END DO
+            END DO
+         END DO
+
+      ! t-, u- and v- water column thickness
+      ! ------------------------------------
+         ht_n(:,:) = 0._wp ; hu_n(:,:) = 0._wp ; hv_n(:,:) = 0._wp
+         DO jk = 1, jpkm1
+            hu_n(:,:) = hu_n(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+            hv_n(:,:) = hv_n(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+            ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         !                                        ! Inverse of the local depth
+         r1_hu_n(:,:) = 1._wp / ( hu_n(:,:) + 1._wp - ssumask(:,:) ) * ssumask(:,:)
+         r1_hv_n(:,:) = 1._wp / ( hv_n(:,:) + 1._wp - ssvmask(:,:) ) * ssvmask(:,:)
+
+      END IF
+
+!=============================================================================
+! compute velocity
+! compute velocity in order to conserve barotropic velocity (modification by poderation of the scale factor).
+      ub(:,:,:)=un(:,:,:)
+      vb(:,:,:)=vn(:,:,:)
+      DO jk = 1,jpk
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               un(ji,jj,jk) = ub(ji,jj,jk)*pe3u_b(ji,jj,jk)*pumask_b(ji,jj,jk)/e3u_n(ji,jj,jk)*umask(ji,jj,jk);
+               vn(ji,jj,jk) = vb(ji,jj,jk)*pe3v_b(ji,jj,jk)*pvmask_b(ji,jj,jk)/e3v_n(ji,jj,jk)*vmask(ji,jj,jk);
+            END DO
+         END DO
+      END DO
+
+! compute new velocity if we close a cell (check barotropic velocity and change velocity over the water column)
+! compute barotropic velocity now and after 
+      ztrp(:,:,:) = ub(:,:,:)*pe3u_b(:,:,:); 
+      zbub(:,:)   = SUM(ztrp,DIM=3)
+      ztrp(:,:,:) = vb(:,:,:)*pe3v_b(:,:,:); 
+      zbvb(:,:)   = SUM(ztrp,DIM=3)
+      ztrp(:,:,:) = un(:,:,:)*e3u_n(:,:,:); 
+      zbun(:,:)   = SUM(ztrp,DIM=3)
+      ztrp(:,:,:) = vn(:,:,:)*e3v_n(:,:,:); 
+      zbvn(:,:)   = SUM(ztrp,DIM=3)
+
+      ! new water column
+      zhu1=0.0_wp ;
+      zhv1=0.0_wp ;
+      DO jk  = 1,jpk
+        zhu1(:,:) = zhu1(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+        zhv1(:,:) = zhv1(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+      END DO
+      
+      ! compute correction      
+      zucorr = 0._wp
+      zvcorr = 0._wp
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+            IF (zbun(ji,jj) /= zbub(ji,jj) .AND. zhu1(ji,jj) /= 0._wp ) THEN
+               zucorr(ji,jj) = (zbun(ji,jj) - zbub(ji,jj))/zhu1(ji,jj)
+            END IF
+            IF (zbvn(ji,jj) /= zbvb(ji,jj) .AND. zhv1(ji,jj) /= 0._wp ) THEN
+               zvcorr(ji,jj) = (zbvn(ji,jj) - zbvb(ji,jj))/zhv1(ji,jj)
+            END IF
+         END DO
+      END DO 
+      
+      ! update velocity
+      DO jk  = 1,jpk
+         un(:,:,jk)=(un(:,:,jk) - zucorr(:,:))*umask(:,:,jk)
+         vn(:,:,jk)=(vn(:,:,jk) - zvcorr(:,:))*vmask(:,:,jk)
+      END DO
+
+!=============================================================================
+      ! compute temp and salt
+      ! compute new tn and sn if we open a new cell
+      tsb (:,:,:,:) = tsn(:,:,:,:)
+      zts0(:,:,:,:) = tsn(:,:,:,:)
+      ztmask1(:,:,:) = ptmask_b(:,:,:)
+      ztmask0(:,:,:) = ptmask_b(:,:,:)
+      DO iz = 1,nn_drown ! resolution dependent (OK for ISOMIP+ case)
+          DO jk = 1,jpk-1
+              zdmask=tmask(:,:,jk)-ztmask0(:,:,jk);
+              DO jj = 2,jpj-1
+                 DO ji = fs_2,fs_jpim1
+                      jip1=ji+1; jim1=ji-1;
+                      jjp1=jj+1; jjm1=jj-1;
+                      summsk= (ztmask0(jip1,jj  ,jk)+ztmask0(jim1,jj  ,jk)+ztmask0(ji  ,jjp1,jk)+ztmask0(ji  ,jjm1,jk))
+                      IF (zdmask(ji,jj) == 1._wp .AND. summsk /= 0._wp) THEN
+                      !! horizontal basic extrapolation
+                         tsn(ji,jj,jk,1)=( zts0(jip1,jj  ,jk,1)*ztmask0(jip1,jj  ,jk) &
+                         &                +zts0(jim1,jj  ,jk,1)*ztmask0(jim1,jj  ,jk) &
+                         &                +zts0(ji  ,jjp1,jk,1)*ztmask0(ji  ,jjp1,jk) &
+                         &                +zts0(ji  ,jjm1,jk,1)*ztmask0(ji  ,jjm1,jk) ) / summsk
+                         tsn(ji,jj,jk,2)=( zts0(jip1,jj  ,jk,2)*ztmask0(jip1,jj  ,jk) &
+                         &                +zts0(jim1,jj  ,jk,2)*ztmask0(jim1,jj  ,jk) &
+                         &                +zts0(ji  ,jjp1,jk,2)*ztmask0(ji  ,jjp1,jk) &
+                         &                +zts0(ji  ,jjm1,jk,2)*ztmask0(ji  ,jjm1,jk) ) / summsk
+                         ztmask1(ji,jj,jk)=1
+                      ELSEIF (zdmask(ji,jj) == 1._wp .AND. summsk == 0._wp) THEN
+                      !! vertical extrapolation if horizontal extrapolation failed
+                         jkm1=max(1,jk-1) ; jkp1=min(jpk,jk+1)
+                         summsk=(ztmask0(ji,jj,jkm1)+ztmask0(ji,jj,jkp1))
+                         IF (zdmask(ji,jj) == 1._wp .AND. summsk /= 0._wp ) THEN
+                            tsn(ji,jj,jk,1)=( zts0(ji,jj,jkp1,1)*ztmask0(ji,jj,jkp1)     &
+                            &                +zts0(ji,jj,jkm1,1)*ztmask0(ji,jj,jkm1))/summsk
+                            tsn(ji,jj,jk,2)=( zts0(ji,jj,jkp1,2)*ztmask0(ji,jj,jkp1)     &
+                            &                +zts0(ji,jj,jkm1,2)*ztmask0(ji,jj,jkm1))/summsk
+                            ztmask1(ji,jj,jk)=1._wp
+                         END IF
+                      END IF
+                  END DO
+              END DO
+          END DO
+          
+          CALL lbc_lnk_multi( 'iscplrst', tsn(:,:,:,jp_tem), 'T', 1., tsn(:,:,:,jp_sal), 'T', 1., ztmask1, 'T', 1.)
+
+          ! update
+          zts0(:,:,:,:) = tsn(:,:,:,:)
+          ztmask0 = ztmask1
+
+      END DO
+
+      ! mask new tsn field
+      tsn(:,:,:,jp_tem) = tsn(:,:,:,jp_tem) * tmask(:,:,:)
+      tsn(:,:,:,jp_sal) = tsn(:,:,:,jp_sal) * tmask(:,:,:)
+
+      ! compute new T/S (interpolation) if vvl only for common wet cell in before and after wmask
+      !PM: Is this IF needed since change to VVL by default
+      IF (.NOT.ln_linssh) THEN
+         DO jk = 2,jpk-1
+            DO jj = 1,jpj
+               DO ji = 1,jpi
+                  IF (zwmaskn(ji,jj,jk) * zwmaskb(ji,jj,jk) == 1._wp .AND.   &
+                  &      (tmask(ji,jj,1)==0._wp .OR. ptmask_b(ji,jj,1)==0._wp) ) THEN
+                     !compute weight
+                     zdzp1 = MAX(0._wp,gdepw_n(ji,jj,jk+1) - pdepw_b(ji,jj,jk+1))
+                     zdz   =           gdepw_n(ji,jj,jk+1) - pdepw_b(ji,jj,jk  ) 
+                     zdzm1 = MAX(0._wp,pdepw_b(ji,jj,jk  ) - gdepw_n(ji,jj,jk  ))
+                     IF (zdz .LT. 0._wp) THEN 
+                        CALL ctl_stop( 'STOP', 'rst_iscpl : unable to compute the interpolation' )
+                     END IF
+                     tsn(ji,jj,jk,jp_tem) = ( zdzp1*tsb(ji,jj,jk+1,jp_tem)      &
+                        &                   + zdz  *tsb(ji,jj,jk  ,jp_tem)      &
+                        &                   + zdzm1*tsb(ji,jj,jk-1,jp_tem)      )/e3t_n(ji,jj,jk)
+                     tsn(ji,jj,jk,jp_sal) = ( zdzp1*tsb(ji,jj,jk+1,jp_sal)      &
+                        &                   + zdz  *tsb(ji,jj,jk  ,jp_sal)      &
+                        &                   + zdzm1*tsb(ji,jj,jk-1,jp_sal)      )/e3t_n(ji,jj,jk)
+                  END IF
+               END DO
+            END DO
+         END DO               
+      END IF
+
+      ! closed pool
+      ! -----------------------------------------------------------------------------------------
+      ! case we open a cell but no neigbour cells available to get an estimate of T and S
+      WHERE (tmask(:,:,:) == 1._wp .AND. tsn(:,:,:,2) == 0._wp) 
+         tsn(:,:,:,2) = -99._wp  ! Special value for closed pool (checking purpose in output.init)
+         tmask(:,:,:) = 0._wp    ! set mask to 0 to run
+         umask(:,:,:) = 0._wp
+         vmask(:,:,:) = 0._wp
+      END WHERE
+      
+      ! set mbkt and mikt to 1 in thiese location
+      WHERE (SUM(tmask,dim=3) == 0)
+         mbkt(:,:)=1 ; mbku(:,:)=1 ; mbkv(:,:)=1
+         mikt(:,:)=1 ; miku(:,:)=1 ; mikv(:,:)=1
+      END WHERE
+      ! -------------------------------------------------------------------------------------------
+      ! compute new tn and sn if we close cell 
+      ! nothing to do
+      ! 
+   END SUBROUTINE iscpl_rst_interpol
+
+   !!======================================================================
+END MODULE iscplrst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/istate.F90	(revision 14097)
@@ -0,0 +1,180 @@
+MODULE istate
+   !!======================================================================
+   !!                     ***  MODULE  istate  ***
+   !! Ocean state   :  initial state setting
+   !!=====================================================================
+   !! History :  OPA  !  1989-12  (P. Andrich)  Original code
+   !!            5.0  !  1991-11  (G. Madec)  rewritting
+   !!            6.0  !  1996-01  (G. Madec)  terrain following coordinates
+   !!            8.0  !  2001-09  (M. Levy, M. Ben Jelloul)  istate_eel
+   !!            8.0  !  2001-09  (M. Levy, M. Ben Jelloul)  istate_uvg
+   !!   NEMO     1.0  !  2003-08  (G. Madec, C. Talandier)  F90: Free form, modules + EEL R5
+   !!             -   !  2004-05  (A. Koch-Larrouy)  istate_gyre 
+   !!            2.0  !  2006-07  (S. Masson)  distributed restart using iom
+   !!            3.3  !  2010-10  (C. Ethe) merge TRC-TRA
+   !!            3.4  !  2011-04  (G. Madec) Merge of dtatem and dtasal & suppression of tb,tn/sb,sn 
+   !!            3.7  !  2016-04  (S. Flavoni) introduce user defined initial state 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   istate_init   : initial state setting
+   !!   istate_uvg    : initial velocity in geostropic balance
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers 
+   USE dom_oce        ! ocean space and time domain 
+   USE daymod         ! calendar
+   USE dtatsd         ! data temperature and salinity   (dta_tsd routine)
+   USE dtauvd         ! data: U & V current             (dta_uvd routine)
+   USE domvvl          ! varying vertical mesh
+   USE iscplrst        ! ice sheet coupling
+   USE wet_dry         ! wetting and drying (needed for wad_istate)
+   USE usrdef_istate   ! User defined initial state
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O library
+   USE lib_mpp         ! MPP library
+   USE restart         ! restart
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   istate_init   ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE istate_init
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE istate_init  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracer fields.
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+!!gm see comment further down
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   zuvd    ! U & V data workspace
+!!gm end
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'istate_init : Initialization of the dynamics and tracers'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+
+!!gm  Why not include in the first call of dta_tsd ?  
+!!gm  probably associated with the use of internal damping...
+                     CALL dta_tsd_init        ! Initialisation of T & S input data
+!!gm to be moved in usrdef of C1D case
+!      IF( lk_c1d )   CALL dta_uvd_init        ! Initialization of U & V input data
+!!gm
+
+      rhd  (:,:,:  ) = 0._wp   ;   rhop (:,:,:  ) = 0._wp      ! set one for all to 0 at level jpk
+      rn2b (:,:,:  ) = 0._wp   ;   rn2  (:,:,:  ) = 0._wp      ! set one for all to 0 at levels 1 and jpk
+      tsa  (:,:,:,:) = 0._wp                                   ! set one for all to 0 at level jpk
+      rab_b(:,:,:,:) = 0._wp   ;   rab_n(:,:,:,:) = 0._wp      ! set one for all to 0 at level jpk
+#if defined key_agrif
+      ua   (:,:,:  ) = 0._wp   ! used in agrif_oce_sponge at initialization
+      va   (:,:,:  ) = 0._wp   ! used in agrif_oce_sponge at initialization    
+#endif
+
+      IF( ln_rstart ) THEN                    ! Restart from a file
+         !                                    ! -------------------
+         CALL rst_read                        ! Read the restart file
+         IF (ln_iscpl)       CALL iscpl_stp   ! extrapolate restart to wet and dry
+         CALL day_init                        ! model calendar (using both namelist and restart infos)
+         !
+      ELSE                                    ! Start from rest
+         !                                    ! ---------------
+         numror = 0                           ! define numror = 0 -> no restart file to read
+         neuler = 0                           ! Set time-step indicator at nit000 (euler forward)
+         CALL day_init                        ! model calendar (using both namelist and restart infos)
+         !                                    ! Initialization of ocean to zero
+         !
+         IF( ln_tsd_init ) THEN               
+            CALL dta_tsd( nit000, tsb )       ! read 3D T and S data at nit000
+            !
+            sshb(:,:)   = 0._wp               ! set the ocean at rest
+            IF( ll_wd ) THEN
+               sshb(:,:) =  -ssh_ref  ! Added in 30 here for bathy that adds 30 as Iterative test CEOD 
+               !
+               ! Apply minimum wetdepth criterion
+               !
+               DO jj = 1,jpj
+                  DO ji = 1,jpi
+                     IF( ht_0(ji,jj) + sshb(ji,jj)  < rn_wdmin1 ) THEN
+                        sshb(ji,jj) = tmask(ji,jj,1)*( rn_wdmin1 - (ht_0(ji,jj)) )
+                     ENDIF
+                  END DO
+               END DO 
+            ENDIF 
+            ub  (:,:,:) = 0._wp
+            vb  (:,:,:) = 0._wp  
+            !
+         ELSE                                 ! user defined initial T and S
+            CALL usr_def_istate( gdept_b, tmask, tsb, ub, vb, sshb  )         
+         ENDIF
+         tsn  (:,:,:,:) = tsb (:,:,:,:)       ! set now values from to before ones
+         sshn (:,:)     = sshb(:,:)   
+         un   (:,:,:)   = ub  (:,:,:)
+         vn   (:,:,:)   = vb  (:,:,:)
+
+!!gm POTENTIAL BUG :
+!!gm  ISSUE :  if sshb /= 0  then, in non linear free surface, the e3._n, e3._b should be recomputed
+!!             as well as gdept and gdepw....   !!!!! 
+!!      ===>>>>   probably a call to domvvl initialisation here....
+
+
+         !
+!!gm to be moved in usrdef of C1D case
+!         IF ( ln_uvd_init .AND. lk_c1d ) THEN ! read 3D U and V data at nit000
+!            ALLOCATE( zuvd(jpi,jpj,jpk,2) )
+!            CALL dta_uvd( nit000, zuvd )
+!            ub(:,:,:) = zuvd(:,:,:,1) ;  un(:,:,:) = ub(:,:,:)
+!            vb(:,:,:) = zuvd(:,:,:,2) ;  vn(:,:,:) = vb(:,:,:)
+!            DEALLOCATE( zuvd )
+!         ENDIF
+         !
+!!gm This is to be changed !!!!
+!         ! - ML - sshn could be modified by istate_eel, so that initialization of e3t_b is done here
+!         IF( .NOT.ln_linssh ) THEN
+!            DO jk = 1, jpk
+!               e3t_b(:,:,jk) = e3t_n(:,:,jk)
+!            END DO
+!         ENDIF
+!!gm 
+         ! 
+      ENDIF 
+      ! 
+      ! Initialize "now" and "before" barotropic velocities:
+      ! Do it whatever the free surface method, these arrays being eventually used
+      !
+      un_b(:,:) = 0._wp   ;   vn_b(:,:) = 0._wp
+      ub_b(:,:) = 0._wp   ;   vb_b(:,:) = 0._wp
+      !
+!!gm  the use of umsak & vmask is not necessary below as un, vn, ub, vb are always masked
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               un_b(ji,jj) = un_b(ji,jj) + e3u_n(ji,jj,jk) * un(ji,jj,jk) * umask(ji,jj,jk)
+               vn_b(ji,jj) = vn_b(ji,jj) + e3v_n(ji,jj,jk) * vn(ji,jj,jk) * vmask(ji,jj,jk)
+               !
+               ub_b(ji,jj) = ub_b(ji,jj) + e3u_b(ji,jj,jk) * ub(ji,jj,jk) * umask(ji,jj,jk)
+               vb_b(ji,jj) = vb_b(ji,jj) + e3v_b(ji,jj,jk) * vb(ji,jj,jk) * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      un_b(:,:) = un_b(:,:) * r1_hu_n(:,:)
+      vn_b(:,:) = vn_b(:,:) * r1_hv_n(:,:)
+      !
+      ub_b(:,:) = ub_b(:,:) * r1_hu_b(:,:)
+      vb_b(:,:) = vb_b(:,:) * r1_hv_b(:,:)
+      !
+   END SUBROUTINE istate_init
+
+   !!======================================================================
+END MODULE istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/phycst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/phycst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DOM/phycst.F90	(revision 14097)
@@ -0,0 +1,139 @@
+MODULE phycst
+   !!======================================================================
+   !!                    ***  MODULE  phycst  ***
+   !!     Definition of of both ocean and ice parameters used in the code
+   !!=====================================================================
+   !! History :   OPA  !  1990-10  (C. Levy - G. Madec)  Original code
+   !!             8.1  !  1991-11  (G. Madec, M. Imbard)  cosmetic changes
+   !!   NEMO      1.0  !  2002-08  (G. Madec, C. Ethe)  F90, add ice constants
+   !!              -   !  2006-08  (G. Madec)  style 
+   !!             3.2  !  2006-08  (S. Masson, G. Madec)  suppress useless variables + style 
+   !!             3.4  !  2011-11  (C. Harris)  minor changes for CICE constants 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   phy_cst  : define and print physical constant and domain parameters
+   !!----------------------------------------------------------------------
+   USE par_oce          ! ocean parameters
+   USE in_out_manager   ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   phy_cst     ! routine called by inipar.F90
+
+   REAL(wp), PUBLIC ::   rpi      = 3.141592653589793_wp             !: pi
+   REAL(wp), PUBLIC ::   rad      = 3.141592653589793_wp / 180._wp   !: conversion from degre into radian
+   REAL(wp), PUBLIC ::   rsmall   = 0.5 * EPSILON( 1.e0 )            !: smallest real computer value
+   
+   REAL(wp), PUBLIC ::   rday     = 24.*60.*60.      !: day                                [s]
+   REAL(wp), PUBLIC ::   rsiyea                      !: sideral year                       [s]
+   REAL(wp), PUBLIC ::   rsiday                      !: sideral day                        [s]
+   REAL(wp), PUBLIC ::   raamo    =  12._wp          !: number of months in one year
+   REAL(wp), PUBLIC ::   rjjhh    =  24._wp          !: number of hours in one day
+   REAL(wp), PUBLIC ::   rhhmm    =  60._wp          !: number of minutes in one hour
+   REAL(wp), PUBLIC ::   rmmss    =  60._wp          !: number of seconds in one minute
+   REAL(wp), PUBLIC ::   omega                       !: earth rotation parameter           [s-1]
+   REAL(wp), PUBLIC ::   ra       = 6371229._wp      !: earth radius                       [m]
+   REAL(wp), PUBLIC ::   grav     = 9.80665_wp       !: gravity                            [m/s2]   
+   REAL(wp), PUBLIC ::   rt0      = 273.15_wp        !: freezing point of fresh water [Kelvin]
+
+   REAL(wp), PUBLIC ::   rau0                        !: volumic mass of reference     [kg/m3]
+   REAL(wp), PUBLIC ::   r1_rau0                     !: = 1. / rau0                   [m3/kg]
+   REAL(wp), PUBLIC ::   rcp                         !: ocean specific heat           [J/Kelvin]
+   REAL(wp), PUBLIC ::   r1_rcp                      !: = 1. / rcp                    [Kelvin/J]
+   REAL(wp), PUBLIC ::   rau0_rcp                    !: = rau0 * rcp 
+   REAL(wp), PUBLIC ::   r1_rau0_rcp                 !: = 1. / ( rau0 * rcp )
+
+   REAL(wp), PUBLIC ::   emic     =    0.97_wp       !: emissivity of snow or ice (not used?)
+
+   REAL(wp), PUBLIC ::   sice     =    6.0_wp        !: salinity of ice (for pisces)          [psu]
+   REAL(wp), PUBLIC ::   soce     =   34.7_wp        !: salinity of sea (for pisces and isf)  [psu]
+   REAL(wp), PUBLIC ::   rLevap   =    2.5e+6_wp     !: latent heat of evaporation (water)
+   REAL(wp), PUBLIC ::   vkarmn   =    0.4_wp        !: von Karman constant
+   REAL(wp), PUBLIC ::   stefan   =    5.67e-8_wp    !: Stefan-Boltzmann constant 
+
+   REAL(wp), PUBLIC ::   rhos     =  330._wp         !: volumic mass of snow                                  [kg/m3]
+   REAL(wp), PUBLIC ::   rhoi     =  917._wp         !: volumic mass of sea ice                               [kg/m3]
+   REAL(wp), PUBLIC ::   rhow     = 1000._wp         !: volumic mass of freshwater in melt ponds              [kg/m3]
+   REAL(wp), PUBLIC ::   rcnd_i   =    2.034396_wp   !: thermal conductivity of fresh ice                     [W/m/K]
+   REAL(wp), PUBLIC ::   rcpi     = 2067.0_wp        !: specific heat of fresh ice                            [J/kg/K]
+   REAL(wp), PUBLIC ::   rLsub    =    2.834e+6_wp   !: pure ice latent heat of sublimation                   [J/kg]
+   REAL(wp), PUBLIC ::   rLfus    =    0.334e+6_wp   !: latent heat of fusion of fresh ice                    [J/kg]
+   REAL(wp), PUBLIC ::   rTmlt    =    0.054_wp      !: decrease of seawater meltpoint with salinity
+
+   REAL(wp), PUBLIC ::   r1_rhoi                     !: 1 / rhoi
+   REAL(wp), PUBLIC ::   r1_rhos                     !: 1 / rhos
+   REAL(wp), PUBLIC ::   r1_rcpi                     !: 1 / rcpi
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+   
+CONTAINS
+   
+   SUBROUTINE phy_cst
+      !!----------------------------------------------------------------------
+      !!                       ***  ROUTINE phy_cst  ***
+      !!
+      !! ** Purpose :   set and print the constants
+      !!----------------------------------------------------------------------
+
+      rsiyea = 365.25_wp * rday * 2._wp * rpi / 6.283076_wp
+      rsiday = rday / ( 1._wp + rday / rsiyea )
+#if defined key_cice
+      omega  = 7.292116e-05
+#else
+      omega  = 2._wp * rpi / rsiday 
+#endif
+
+      r1_rhoi = 1._wp / rhoi
+      r1_rhos = 1._wp / rhos
+      r1_rcpi = 1._wp / rcpi
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'phy_cst : initialization of ocean parameters and constants'
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,*) '      mathematical constant                 rpi = ', rpi
+         WRITE(numout,*) '      day                                rday   = ', rday,   ' s'
+         WRITE(numout,*) '      sideral year                       rsiyea = ', rsiyea, ' s'
+         WRITE(numout,*) '      sideral day                        rsiday = ', rsiday, ' s'
+         WRITE(numout,*) '      omega                              omega  = ', omega,  ' s^-1'
+         WRITE(numout,*)
+         WRITE(numout,*) '      nb of months per year               raamo = ', raamo, ' months'
+         WRITE(numout,*) '      nb of hours per day                 rjjhh = ', rjjhh, ' hours'
+         WRITE(numout,*) '      nb of minutes per hour              rhhmm = ', rhhmm, ' mn'
+         WRITE(numout,*) '      nb of seconds per minute            rmmss = ', rmmss, ' s'
+         WRITE(numout,*)
+         WRITE(numout,*) '      earth radius                         ra   = ', ra   , ' m'
+         WRITE(numout,*) '      gravity                              grav = ', grav , ' m/s^2'
+         WRITE(numout,*)
+         WRITE(numout,*) '      freezing point of water              rt0  = ', rt0  , ' K'
+         WRITE(numout,*)
+         WRITE(numout,*) '   reference density and heat capacity now defined in eosbn2.f90'
+         WRITE(numout,*)
+         WRITE(numout,*) '      thermal conductivity of pure ice          = ', rcnd_i  , ' J/s/m/K'
+         WRITE(numout,*) '      thermal conductivity of snow is defined in a namelist '
+         WRITE(numout,*) '      fresh ice specific heat                   = ', rcpi    , ' J/kg/K'
+         WRITE(numout,*) '      latent heat of fusion of fresh ice / snow = ', rLfus   , ' J/kg'
+         WRITE(numout,*) '      latent heat of subl.  of fresh ice / snow = ', rLsub   , ' J/kg'
+         WRITE(numout,*) '      density of sea ice                        = ', rhoi    , ' kg/m^3'
+         WRITE(numout,*) '      density of snow                           = ', rhos    , ' kg/m^3'
+         WRITE(numout,*) '      density of freshwater (in melt ponds)     = ', rhow    , ' kg/m^3'
+         WRITE(numout,*) '      salinity of ice (for pisces)              = ', sice    , ' psu'
+         WRITE(numout,*) '      salinity of sea (for pisces and isf)      = ', soce    , ' psu'
+         WRITE(numout,*) '      latent heat of evaporation (water)        = ', rLevap  , ' J/m^3' 
+         WRITE(numout,*) '      von Karman constant                       = ', vkarmn 
+         WRITE(numout,*) '      Stefan-Boltzmann constant                 = ', stefan  , ' J/s/m^2/K^4'
+         WRITE(numout,*)
+         WRITE(numout,*) '      conversion: degre ==> radian          rad = ', rad
+         WRITE(numout,*)
+         WRITE(numout,*) '      smallest real computer value       rsmall = ', rsmall
+      ENDIF
+
+   END SUBROUTINE phy_cst
+
+   !!======================================================================
+END MODULE phycst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/divhor.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/divhor.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/divhor.F90	(revision 14097)
@@ -0,0 +1,114 @@
+MODULE divhor
+   !!==============================================================================
+   !!                       ***  MODULE  divhor  ***
+   !! Ocean diagnostic variable : now horizontal divergence
+   !!==============================================================================
+   !! History :  1.0  ! 2002-09  (G. Madec, E. Durand)  Free form, F90
+   !!             -   ! 2005-01  (J. Chanut) Unstructured open boundaries
+   !!             -   ! 2003-08  (G. Madec)  merged of cur and div, free form, F90
+   !!             -   ! 2005-01  (J. Chanut, A. Sellar) unstructured open boundaries
+   !!            3.3  ! 2010-09  (D.Storkey and E.O'Dea) bug fixes for BDY module
+   !!             -   ! 2010-10  (R. Furner, G. Madec) runoff and cla added directly here
+   !!            3.7  ! 2014-01  (G. Madec) suppression of velocity curl from in-core memory
+   !!             -   ! 2014-12  (G. Madec) suppression of cross land advection option
+   !!             -   ! 2015-10  (G. Madec) add velocity and rnf flag in argument of div_hor
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   div_hor    : Compute the horizontal divergence field
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce, ONLY : ln_rnf, ln_isf ! surface boundary condition: ocean
+   USE sbcrnf          ! river runoff 
+   USE sbcisf          ! ice shelf
+   USE iscplhsb        ! ice sheet / ocean coupling
+   USE iscplini        ! ice sheet / ocean coupling
+#if defined key_asminc   
+   USE asminc          ! Assimilation increment
+#endif
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! MPP library
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   div_hor    ! routine called by step.F90 and istate.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE div_hor( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE div_hor  ***
+      !!                    
+      !! ** Purpose :   compute the horizontal divergence at now time-step
+      !!
+      !! ** Method  :   the now divergence is computed as :
+      !!         hdivn = 1/(e1e2t*e3t) ( di[e2u*e3u un] + dj[e1v*e3v vn] )
+      !!      and correct with runoff inflow (div_rnf) and cross land flow (div_cla) 
+      !!
+      !! ** Action  : - update hdivn, the now horizontal divergence
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk    ! dummy loop indices
+      REAL(wp) ::   zraur, zdep   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('div_hor')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'div_hor : horizontal velocity divergence '
+         IF(lwp) WRITE(numout,*) '~~~~~~~   '
+         hdivn(:,:,:) = 0._wp    ! initialize hdivn for the halos at the first time step
+      ENDIF
+      !
+      DO jk = 1, jpkm1                                      !==  Horizontal divergence  ==!
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               hdivn(ji,jj,jk) = (  e2u(ji  ,jj) * e3u_n(ji  ,jj,jk) * un(ji  ,jj,jk)      &
+                  &               - e2u(ji-1,jj) * e3u_n(ji-1,jj,jk) * un(ji-1,jj,jk)      &
+                  &               + e1v(ji,jj  ) * e3v_n(ji,jj  ,jk) * vn(ji,jj  ,jk)      &
+                  &               - e1v(ji,jj-1) * e3v_n(ji,jj-1,jk) * vn(ji,jj-1,jk)  )   &
+                  &            * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+            END DO  
+         END DO  
+      END DO
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() ) THEN
+         IF( l_Westedge )   hdivn(   2   ,  :   ,:) = 0._wp      ! west
+         IF( l_Eastedge )   hdivn( nlci-1,  :   ,:) = 0._wp      ! east
+         IF( l_Southedge )  hdivn(   :   ,  2   ,:) = 0._wp      ! south
+         IF( l_Northedge )  hdivn(   :   ,nlcj-1,:) = 0._wp      ! north
+      ENDIF
+#endif
+      !
+      IF( ln_rnf )   CALL sbc_rnf_div( hdivn )              !==  runoffs    ==!   (update hdivn field)
+      !
+#if defined key_asminc 
+      IF( ln_sshinc .AND. ln_asmiau )   CALL ssh_asm_div( kt, hdivn )   !==  SSH assimilation  ==!   (update hdivn field)
+      ! 
+#endif
+      IF( ln_isf )   CALL sbc_isf_div( hdivn )      !==  ice shelf  ==!   (update hdivn field)
+      !
+      IF( ln_iscpl .AND. ln_hsb )   CALL iscpl_div( hdivn ) !==  ice sheet  ==!   (update hdivn field)
+      !
+      CALL lbc_lnk( 'divhor', hdivn, 'T', 1. )   !   (no sign change)
+      !
+      IF( ln_timing )   CALL timing_stop('div_hor')
+      !
+   END SUBROUTINE div_hor
+   
+   !!======================================================================
+END MODULE divhor
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv.F90	(revision 14097)
@@ -0,0 +1,148 @@
+MODULE dynadv
+   !!==============================================================================
+   !!                       ***  MODULE  dynadv  ***
+   !! Ocean active tracers:  advection scheme control
+   !!==============================================================================
+   !! History :  1.0  !  2006-11  (G. Madec)  Original code
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec)  reorganisation of initialisation phase
+   !!            3.6  !  2015-05  (N. Ducousso, G. Madec)  add Hollingsworth scheme as an option 
+   !!            4.0  !  2017-07  (G. Madec)  add a linear dynamics option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_adv      : compute the momentum advection trend 
+   !!   dyn_adv_init : control the different options of advection scheme
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE dynadv_cen2     ! centred flux form advection      (dyn_adv_cen2 routine)
+   USE dynadv_ubs      ! UBS flux form advection          (dyn_adv_ubs  routine)
+   USE dynkeg          ! kinetic energy gradient          (dyn_keg      routine)
+   USE dynzad          ! vertical advection               (dyn_zad      routine)
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dyn_adv       ! routine called by step module
+   PUBLIC dyn_adv_init  ! routine called by opa  module
+ 
+   !                                   !!* namdyn_adv namelist *
+   LOGICAL, PUBLIC ::   ln_dynadv_OFF   !: linear dynamics (no momentum advection)
+   LOGICAL, PUBLIC ::   ln_dynadv_vec   !: vector form
+   INTEGER, PUBLIC ::      nn_dynkeg       !: scheme of grad(KE): =0 C2 ; =1 Hollingsworth
+   LOGICAL, PUBLIC ::   ln_dynadv_cen2  !: flux form - 2nd order centered scheme flag
+   LOGICAL, PUBLIC ::   ln_dynadv_ubs   !: flux form - 3rd order UBS scheme flag
+   
+   INTEGER, PUBLIC ::   n_dynadv   !: choice of the formulation and scheme for momentum advection
+   !                               !  associated indices:
+   INTEGER, PUBLIC, PARAMETER ::   np_LIN_dyn = 0   ! no advection: linear dynamics
+   INTEGER, PUBLIC, PARAMETER ::   np_VEC_c2  = 1   ! vector form : 2nd order centered scheme
+   INTEGER, PUBLIC, PARAMETER ::   np_FLX_c2  = 2   ! flux   form : 2nd order centered scheme
+   INTEGER, PUBLIC, PARAMETER ::   np_FLX_ubs = 3   ! flux   form : 3rd order Upstream Biased Scheme
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_adv( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_adv  ***
+      !!                
+      !! ** Purpose :   compute the ocean momentum advection trend.
+      !!
+      !! ** Method  : - Update (ua,va) with the advection term following n_dynadv
+      !!
+      !!      NB: in flux form advection (ln_dynadv_cen2 or ln_dynadv_ubs=T) 
+      !!      a metric term is add to the coriolis term while in vector form 
+      !!      it is the relative vorticity which is added to coriolis term
+      !!      (see dynvor module).
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'dyn_adv' )
+      !
+      SELECT CASE( n_dynadv )    !==  compute advection trend and add it to general trend  ==!
+      CASE( np_VEC_c2  )     
+         CALL dyn_keg     ( kt, nn_dynkeg )    ! vector form : horizontal gradient of kinetic energy
+         CALL dyn_zad     ( kt )               ! vector form : vertical advection
+      CASE( np_FLX_c2  ) 
+         CALL dyn_adv_cen2( kt )               ! 2nd order centered scheme
+      CASE( np_FLX_ubs )   
+         CALL dyn_adv_ubs ( kt )               ! 3rd order UBS      scheme (UP3)
+      END SELECT
+      !
+      IF( ln_timing )   CALL timing_stop( 'dyn_adv' )
+      !
+   END SUBROUTINE dyn_adv
+
+   
+   SUBROUTINE dyn_adv_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_adv_init  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options for 
+      !!              momentum advection formulation & scheme and set n_dynadv
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios   ! Local integer
+      !
+      NAMELIST/namdyn_adv/ ln_dynadv_OFF, ln_dynadv_vec, nn_dynkeg, ln_dynadv_cen2, ln_dynadv_ubs
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_adv_init : choice/control of the momentum advection scheme'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnam_ref )              ! Namelist namdyn_adv in reference namelist : Momentum advection scheme
+      READ  ( numnam_ref, namdyn_adv, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_adv in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namdyn_adv in configuration namelist : Momentum advection scheme
+      READ  ( numnam_cfg, namdyn_adv, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_adv in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdyn_adv )
+
+      IF(lwp) THEN                    ! Namelist print
+         WRITE(numout,*) '   Namelist namdyn_adv : chose a advection formulation & scheme for momentum'
+         WRITE(numout,*) '      linear dynamics : no momentum advection          ln_dynadv_OFF  = ', ln_dynadv_OFF
+         WRITE(numout,*) '      Vector form: 2nd order centered scheme           ln_dynadv_vec  = ', ln_dynadv_vec
+         WRITE(numout,*) '         with Hollingsworth scheme (=1) or not (=0)       nn_dynkeg   = ', nn_dynkeg
+         WRITE(numout,*) '      flux form: 2nd order centred scheme              ln_dynadv_cen2 = ', ln_dynadv_cen2
+         WRITE(numout,*) '                 3rd order UBS scheme                  ln_dynadv_ubs  = ', ln_dynadv_ubs
+      ENDIF
+
+      ioptio = 0                      ! parameter control and set n_dynadv
+      IF( ln_dynadv_OFF  ) THEN   ;   ioptio = ioptio + 1   ;   n_dynadv = np_LIN_dyn   ;   ENDIF
+      IF( ln_dynadv_vec  ) THEN   ;   ioptio = ioptio + 1   ;   n_dynadv = np_VEC_c2    ;   ENDIF
+      IF( ln_dynadv_cen2 ) THEN   ;   ioptio = ioptio + 1   ;   n_dynadv = np_FLX_c2    ;   ENDIF
+      IF( ln_dynadv_ubs  ) THEN   ;   ioptio = ioptio + 1   ;   n_dynadv = np_FLX_ubs   ;   ENDIF
+
+      IF( ioptio /= 1 )   CALL ctl_stop( 'choose ONE and only ONE advection scheme' )
+      IF( nn_dynkeg /= nkeg_C2 .AND. nn_dynkeg /= nkeg_HW )   CALL ctl_stop( 'KEG scheme wrong value of nn_dynkeg' )
+
+
+      IF(lwp) THEN                    ! Print the choice
+         WRITE(numout,*)
+         SELECT CASE( n_dynadv )
+         CASE( np_LIN_dyn )   ;   WRITE(numout,*) '   ==>>>   linear dynamics : no momentum advection used'
+         CASE( np_VEC_c2  )   ;   WRITE(numout,*) '   ==>>>   vector form : keg + zad + vor is used' 
+            IF( nn_dynkeg == nkeg_C2  )   WRITE(numout,*) '              with Centered standard keg scheme'
+            IF( nn_dynkeg == nkeg_HW  )   WRITE(numout,*) '              with Hollingsworth keg scheme'
+         CASE( np_FLX_c2  )   ;   WRITE(numout,*) '   ==>>>   flux form   : 2nd order scheme is used'
+         CASE( np_FLX_ubs )   ;   WRITE(numout,*) '   ==>>>   flux form   : UBS       scheme is used'
+         END SELECT
+      ENDIF
+      !
+   END SUBROUTINE dyn_adv_init
+
+  !!======================================================================
+END MODULE dynadv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_cen2.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_cen2.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_cen2.F90	(revision 14097)
@@ -0,0 +1,147 @@
+MODULE dynadv_cen2
+   !!======================================================================
+   !!                       ***  MODULE  dynadv  ***
+   !! Ocean dynamics: Update the momentum trend with the flux form advection
+   !!                 using a 2nd order centred scheme
+   !!======================================================================
+   !! History :  2.0  ! 2006-08  (G. Madec, S. Theetten)  Original code
+   !!            3.2  ! 2009-07  (R. Benshila)  Suppression of rigid-lid option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_adv_cen2  : flux form momentum advection (ln_dynadv_cen2=T) using a 2nd order centred scheme  
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_adv_cen2   ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_adv_cen2( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_adv_cen2  ***
+      !!
+      !! ** Purpose :   Compute the now momentum advection trend in flux form
+      !!              and the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time) 
+      !!
+      !! ** Action  :   (ua,va) updated with the now vorticity term trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zfu_t, zfu_f, zfu_uw, zfu
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zfv_t, zfv_f, zfv_vw, zfv, zfw
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_adv_cen2 : 2nd order flux form momentum advection'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      IF( l_trddyn ) THEN           ! trends: store the input trends
+         zfu_uw(:,:,:) = ua(:,:,:)
+         zfv_vw(:,:,:) = va(:,:,:)
+      ENDIF
+      !
+      !                             !==  Horizontal advection  ==!
+      !
+      DO jk = 1, jpkm1                    ! horizontal transport
+         zfu(:,:,jk) = 0.25_wp * e2u(:,:) * e3u_n(:,:,jk) * un(:,:,jk)
+         zfv(:,:,jk) = 0.25_wp * e1v(:,:) * e3v_n(:,:,jk) * vn(:,:,jk)
+         DO jj = 1, jpjm1                 ! horizontal momentum fluxes (at T- and F-point)
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zfu_t(ji+1,jj  ,jk) = ( zfu(ji,jj,jk) + zfu(ji+1,jj,jk) ) * ( un(ji,jj,jk) + un(ji+1,jj  ,jk) )
+               zfv_f(ji  ,jj  ,jk) = ( zfv(ji,jj,jk) + zfv(ji+1,jj,jk) ) * ( un(ji,jj,jk) + un(ji  ,jj+1,jk) )
+               zfu_f(ji  ,jj  ,jk) = ( zfu(ji,jj,jk) + zfu(ji,jj+1,jk) ) * ( vn(ji,jj,jk) + vn(ji+1,jj  ,jk) )
+               zfv_t(ji  ,jj+1,jk) = ( zfv(ji,jj,jk) + zfv(ji,jj+1,jk) ) * ( vn(ji,jj,jk) + vn(ji  ,jj+1,jk) )
+            END DO
+         END DO
+         DO jj = 2, jpjm1                 ! divergence of horizontal momentum fluxes
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ua(ji,jj,jk) = ua(ji,jj,jk) - (  zfu_t(ji+1,jj,jk) - zfu_t(ji,jj  ,jk)    &
+                  &                           + zfv_f(ji  ,jj,jk) - zfv_f(ji,jj-1,jk)  ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) - (  zfu_f(ji,jj  ,jk) - zfu_f(ji-1,jj,jk)    &
+                  &                           + zfv_t(ji,jj+1,jk) - zfv_t(ji  ,jj,jk)  ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF( l_trddyn ) THEN           ! trends: send trend to trddyn for diagnostic
+         zfu_uw(:,:,:) = ua(:,:,:) - zfu_uw(:,:,:)
+         zfv_vw(:,:,:) = va(:,:,:) - zfv_vw(:,:,:)
+         CALL trd_dyn( zfu_uw, zfv_vw, jpdyn_keg, kt )
+         zfu_t(:,:,:) = ua(:,:,:)
+         zfv_t(:,:,:) = va(:,:,:)
+      ENDIF
+      !
+      !                             !==  Vertical advection  ==!
+      !
+      DO jj = 2, jpjm1                    ! surface/bottom advective fluxes set to zero
+         DO ji = fs_2, fs_jpim1
+            zfu_uw(ji,jj,jpk) = 0._wp   ;   zfv_vw(ji,jj,jpk) = 0._wp
+            zfu_uw(ji,jj, 1 ) = 0._wp   ;   zfv_vw(ji,jj, 1 ) = 0._wp
+         END DO
+      END DO
+      IF( ln_linssh ) THEN                ! linear free surface: advection through the surface
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zfu_uw(ji,jj,1) = 0.5_wp * ( e1e2t(ji,jj) * wn(ji,jj,1) + e1e2t(ji+1,jj) * wn(ji+1,jj,1) ) * un(ji,jj,1)
+               zfv_vw(ji,jj,1) = 0.5_wp * ( e1e2t(ji,jj) * wn(ji,jj,1) + e1e2t(ji,jj+1) * wn(ji,jj+1,1) ) * vn(ji,jj,1)
+            END DO
+         END DO
+      ENDIF
+      DO jk = 2, jpkm1                    ! interior advective fluxes
+         DO jj = 2, jpj                       ! 1/4 * Vertical transport
+            DO ji = 2, jpi
+               zfw(ji,jj,jk) = 0.25_wp * e1e2t(ji,jj) * wn(ji,jj,jk)
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zfu_uw(ji,jj,jk) = ( zfw(ji,jj,jk) + zfw(ji+1,jj  ,jk) ) * ( un(ji,jj,jk) + un(ji,jj,jk-1) )
+               zfv_vw(ji,jj,jk) = ( zfw(ji,jj,jk) + zfw(ji  ,jj+1,jk) ) * ( vn(ji,jj,jk) + vn(ji,jj,jk-1) )
+            END DO
+         END DO
+      END DO
+      DO jk = 1, jpkm1                    ! divergence of vertical momentum flux divergence
+         DO jj = 2, jpjm1 
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ua(ji,jj,jk) = ua(ji,jj,jk) - ( zfu_uw(ji,jj,jk) - zfu_uw(ji,jj,jk+1) ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) - ( zfv_vw(ji,jj,jk) - zfv_vw(ji,jj,jk+1) ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF( l_trddyn ) THEN                 ! trends: send trend to trddyn for diagnostic
+         zfu_t(:,:,:) = ua(:,:,:) - zfu_t(:,:,:)
+         zfv_t(:,:,:) = va(:,:,:) - zfv_t(:,:,:)
+         CALL trd_dyn( zfu_t, zfv_t, jpdyn_zad, kt )
+      ENDIF
+      !                                   ! Control print
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' cen2 adv - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=           ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+   END SUBROUTINE dyn_adv_cen2
+
+   !!==============================================================================
+END MODULE dynadv_cen2
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_ubs.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_ubs.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynadv_ubs.F90	(revision 14097)
@@ -0,0 +1,240 @@
+MODULE dynadv_ubs
+   !!======================================================================
+   !!                       ***  MODULE  dynadv_ubs  ***
+   !! Ocean dynamics: Update the momentum trend with the flux form advection
+   !!                 trend using a 3rd order upstream biased scheme
+   !!======================================================================
+   !! History :  2.0  ! 2006-08  (R. Benshila, L. Debreu)  Original code
+   !!            3.2  ! 2009-07  (R. Benshila)  Suppression of rigid-lid option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_adv_ubs   : flux form momentum advection using    (ln_dynadv=T)
+   !!                   an 3rd order Upstream Biased Scheme or Quick scheme
+   !!                   combined with 2nd or 4th order finite differences 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   REAL(wp), PARAMETER :: gamma1 = 1._wp/3._wp  ! =1/4 quick      ; =1/3  3rd order UBS
+   REAL(wp), PARAMETER :: gamma2 = 1._wp/32._wp ! =0   2nd order  ; =1/32 4th order centred
+
+   PUBLIC   dyn_adv_ubs   ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_adv_ubs( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_adv_ubs  ***
+      !!
+      !! ** Purpose :   Compute the now momentum advection trend in flux form
+      !!              and the general trend of the momentum equation.
+      !!
+      !! ** Method  :   The scheme is the one implemeted in ROMS. It depends 
+      !!      on two parameter gamma1 and gamma2. The former control the 
+      !!      upstream baised part of the scheme and the later the centred 
+      !!      part:     gamma1 = 0    pure centered  (no diffusive part)
+      !!                       = 1/4  Quick scheme
+      !!                       = 1/3  3rd order Upstream biased scheme
+      !!                gamma2 = 0    2nd order finite differencing 
+      !!                       = 1/32 4th order finite differencing
+      !!      For stability reasons, the first term of the fluxes which cor-
+      !!      responds to a second order centered scheme is evaluated using  
+      !!      the now velocity (centered in time) while the second term which  
+      !!      is the diffusive part of the scheme, is evaluated using the 
+      !!      before velocity (forward in time). 
+      !!      Default value (hard coded in the begining of the module) are 
+      !!      gamma1=1/3 and gamma2=1/32.
+      !!
+      !! ** Action : - (ua,va) updated with the 3D advective momentum trends
+      !!
+      !! Reference : Shchepetkin & McWilliams, 2005, Ocean Modelling. 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zui, zvj, zfuj, zfvi, zl_u, zl_v   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk)   ::   zfu_t, zfu_f, zfu_uw, zfu
+      REAL(wp), DIMENSION(jpi,jpj,jpk)   ::   zfv_t, zfv_f, zfv_vw, zfv, zfw
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2) ::   zlu_uu, zlu_uv
+      REAL(wp), DIMENSION(jpi,jpj,jpk,2) ::   zlv_vv, zlv_vu
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_adv_ubs : UBS flux form momentum advection'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      zfu_t(:,:,:) = 0._wp
+      zfv_t(:,:,:) = 0._wp
+      zfu_f(:,:,:) = 0._wp
+      zfv_f(:,:,:) = 0._wp
+      !
+      zlu_uu(:,:,:,:) = 0._wp
+      zlv_vv(:,:,:,:) = 0._wp 
+      zlu_uv(:,:,:,:) = 0._wp 
+      zlv_vu(:,:,:,:) = 0._wp 
+      !
+      IF( l_trddyn ) THEN           ! trends: store the input trends
+         zfu_uw(:,:,:) = ua(:,:,:)
+         zfv_vw(:,:,:) = va(:,:,:)
+      ENDIF
+      !                                      ! =========================== !
+      DO jk = 1, jpkm1                       !  Laplacian of the velocity  !
+         !                                   ! =========================== !
+         !                                         ! horizontal volume fluxes
+         zfu(:,:,jk) = e2u(:,:) * e3u_n(:,:,jk) * un(:,:,jk)
+         zfv(:,:,jk) = e1v(:,:) * e3v_n(:,:,jk) * vn(:,:,jk)
+         !            
+         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) - 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_multi( 'dynadv_ubs', zlu_uu(:,:,:,1), 'U', 1. , zlu_uv(:,:,:,1), 'U', 1.,  &
+                      &   zlu_uu(:,:,:,2), 'U', 1. , zlu_uv(:,:,:,2), 'U', 1.,  & 
+                      &   zlv_vv(:,:,:,1), 'V', 1. , zlv_vu(:,:,:,1), 'V', 1.,  &
+                      &   zlv_vv(:,:,:,2), 'V', 1. , zlv_vu(:,:,:,2), 'V', 1.   )
+      !
+      !                                      ! ====================== !
+      !                                      !  Horizontal advection  !
+      DO jk = 1, jpkm1                       ! ====================== !
+         !                                         ! horizontal volume fluxes
+         zfu(:,:,jk) = 0.25_wp * e2u(:,:) * e3u_n(:,:,jk) * un(:,:,jk)
+         zfv(:,:,jk) = 0.25_wp * e1v(:,:) * e3v_n(:,:,jk) * vn(:,:,jk)
+         !
+         DO jj = 1, jpjm1                          ! horizontal momentum fluxes at T- and F-point
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zui = ( un(ji,jj,jk) + un(ji+1,jj  ,jk) )
+               zvj = ( vn(ji,jj,jk) + vn(ji  ,jj+1,jk) )
+               !
+               IF( zui > 0 ) THEN   ;   zl_u = zlu_uu(ji  ,jj,jk,1)
+               ELSE                 ;   zl_u = zlu_uu(ji+1,jj,jk,1)
+               ENDIF
+               IF( zvj > 0 ) THEN   ;   zl_v = zlv_vv(ji,jj  ,jk,1)
+               ELSE                 ;   zl_v = zlv_vv(ji,jj+1,jk,1)
+               ENDIF
+               !
+               zfu_t(ji+1,jj  ,jk) = ( zfu(ji,jj,jk) + zfu(ji+1,jj  ,jk)                               &
+                  &                    - gamma2 * ( zlu_uu(ji,jj,jk,2) + zlu_uu(ji+1,jj  ,jk,2) )  )   &
+                  &                * ( zui - gamma1 * zl_u)
+               zfv_t(ji  ,jj+1,jk) = ( zfv(ji,jj,jk) + zfv(ji  ,jj+1,jk)                               &
+                  &                    - gamma2 * ( zlv_vv(ji,jj,jk,2) + zlv_vv(ji  ,jj+1,jk,2) )  )   &
+                  &                * ( zvj - gamma1 * zl_v)
+               !
+               zfuj = ( zfu(ji,jj,jk) + zfu(ji  ,jj+1,jk) )
+               zfvi = ( zfv(ji,jj,jk) + zfv(ji+1,jj  ,jk) )
+               IF( zfuj > 0 ) THEN   ;    zl_v = zlv_vu( ji  ,jj  ,jk,1)
+               ELSE                  ;    zl_v = zlv_vu( ji+1,jj,jk,1)
+               ENDIF
+               IF( zfvi > 0 ) THEN   ;    zl_u = zlu_uv( ji,jj  ,jk,1)
+               ELSE                  ;    zl_u = zlu_uv( ji,jj+1,jk,1)
+               ENDIF
+               !
+               zfv_f(ji  ,jj  ,jk) = ( zfvi - gamma2 * ( zlv_vu(ji,jj,jk,2) + zlv_vu(ji+1,jj  ,jk,2) )  )   &
+                  &                * ( un(ji,jj,jk) + un(ji  ,jj+1,jk) - gamma1 * zl_u )
+               zfu_f(ji  ,jj  ,jk) = ( zfuj - gamma2 * ( zlu_uv(ji,jj,jk,2) + zlu_uv(ji  ,jj+1,jk,2) )  )   &
+                  &                * ( vn(ji,jj,jk) + vn(ji+1,jj  ,jk) - gamma1 * zl_v )
+            END DO
+         END DO
+         DO jj = 2, jpjm1                          ! divergence of horizontal momentum fluxes
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ua(ji,jj,jk) = ua(ji,jj,jk) - (  zfu_t(ji+1,jj,jk) - zfu_t(ji,jj  ,jk)    &
+                  &                           + zfv_f(ji  ,jj,jk) - zfv_f(ji,jj-1,jk)  ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) - (  zfu_f(ji,jj  ,jk) - zfu_f(ji-1,jj,jk)    &
+                  &                           + zfv_t(ji,jj+1,jk) - zfv_t(ji  ,jj,jk)  ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      IF( l_trddyn ) THEN                          ! trends: send trends to trddyn for diagnostic
+         zfu_uw(:,:,:) = ua(:,:,:) - zfu_uw(:,:,:)
+         zfv_vw(:,:,:) = va(:,:,:) - zfv_vw(:,:,:)
+         CALL trd_dyn( zfu_uw, zfv_vw, jpdyn_keg, kt )
+         zfu_t(:,:,:) = ua(:,:,:)
+         zfv_t(:,:,:) = va(:,:,:)
+      ENDIF
+      !                                      ! ==================== !
+      !                                      !  Vertical advection  !
+      !                                      ! ==================== !
+      DO jj = 2, jpjm1                             ! surface/bottom advective fluxes set to zero                  
+         DO ji = fs_2, fs_jpim1
+            zfu_uw(ji,jj,jpk) = 0._wp
+            zfv_vw(ji,jj,jpk) = 0._wp
+            zfu_uw(ji,jj, 1 ) = 0._wp
+            zfv_vw(ji,jj, 1 ) = 0._wp
+         END DO
+      END DO
+      IF( ln_linssh ) THEN                         ! constant volume : advection through the surface
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zfu_uw(ji,jj,1) = 0.5_wp * ( e1e2t(ji,jj) * wn(ji,jj,1) + e1e2t(ji+1,jj) * wn(ji+1,jj,1) ) * un(ji,jj,1)
+               zfv_vw(ji,jj,1) = 0.5_wp * ( e1e2t(ji,jj) * wn(ji,jj,1) + e1e2t(ji,jj+1) * wn(ji,jj+1,1) ) * vn(ji,jj,1)
+            END DO
+         END DO
+      ENDIF
+      DO jk = 2, jpkm1                          ! interior fluxes
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               zfw(ji,jj,jk) = 0.25_wp * e1e2t(ji,jj) * wn(ji,jj,jk)
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zfu_uw(ji,jj,jk) = ( zfw(ji,jj,jk)+ zfw(ji+1,jj,jk) ) * ( un(ji,jj,jk) + un(ji,jj,jk-1) )
+               zfv_vw(ji,jj,jk) = ( zfw(ji,jj,jk)+ zfw(ji,jj+1,jk) ) * ( vn(ji,jj,jk) + vn(ji,jj,jk-1) )
+            END DO
+         END DO
+      END DO
+      DO jk = 1, jpkm1                          ! divergence of vertical momentum flux divergence
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ua(ji,jj,jk) =  ua(ji,jj,jk) - ( zfu_uw(ji,jj,jk) - zfu_uw(ji,jj,jk+1) ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) =  va(ji,jj,jk) - ( zfv_vw(ji,jj,jk) - zfv_vw(ji,jj,jk+1) ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF( l_trddyn ) THEN                       ! save the vertical advection trend for diagnostic
+         zfu_t(:,:,:) = ua(:,:,:) - zfu_t(:,:,:)
+         zfv_t(:,:,:) = va(:,:,:) - zfv_t(:,:,:)
+         CALL trd_dyn( zfu_t, zfv_t, jpdyn_zad, kt )
+      ENDIF
+      !                                         ! Control print
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' ubs2 adv - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=           ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+   END SUBROUTINE dyn_adv_ubs
+
+   !!==============================================================================
+END MODULE dynadv_ubs
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynhpg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynhpg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynhpg.F90	(revision 14097)
@@ -0,0 +1,1470 @@
+MODULE dynhpg
+   !!======================================================================
+   !!                       ***  MODULE  dynhpg  ***
+   !! Ocean dynamics:  hydrostatic pressure gradient trend
+   !!======================================================================
+   !! History :  OPA  !  1987-09  (P. Andrich, M.-A. Foujols)  hpg_zco: Original code
+   !!            5.0  !  1991-11  (G. Madec)
+   !!            7.0  !  1996-01  (G. Madec)  hpg_sco: Original code for s-coordinates
+   !!            8.0  !  1997-05  (G. Madec)  split dynber into dynkeg and dynhpg
+   !!            8.5  !  2002-07  (G. Madec)  F90: Free form and module
+   !!            8.5  !  2002-08  (A. Bozec)  hpg_zps: Original code
+   !!   NEMO     1.0  !  2005-10  (A. Beckmann, B.W. An)  various s-coordinate options
+   !!                 !         Original code for hpg_ctl, hpg_hel hpg_wdj, hpg_djc, hpg_rot
+   !!             -   !  2005-11  (G. Madec) style & small optimisation
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.4  !  2011-11  (H. Liu) hpg_prj: Original code for s-coordinates
+   !!                 !           (A. Coward) suppression of hel, wdj and rot options
+   !!            3.6  !  2014-11  (P. Mathiot) hpg_isf: original code for ice shelf cavity
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_hpg      : update the momentum trend with the now horizontal
+   !!                  gradient of the hydrostatic pressure
+   !!   dyn_hpg_init : initialisation and control of options
+   !!       hpg_zco  : z-coordinate scheme
+   !!       hpg_zps  : z-coordinate plus partial steps (interpolation)
+   !!       hpg_sco  : s-coordinate (standard jacobian formulation)
+   !!       hpg_isf  : s-coordinate (sco formulation) adapted to ice shelf
+   !!       hpg_djc  : s-coordinate (Density Jacobian with Cubic polynomial)
+   !!       hpg_prj  : s-coordinate (Pressure Jacobian with Cubic polynomial)
+   !!----------------------------------------------------------------------
+   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 wet_dry         ! wetting and drying
+   USE phycst          ! physical constants
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   USE zpshde          ! partial step: hor. derivative     (zps_hde routine)
+   !
+   USE in_out_manager  ! I/O manager
+   USE prtctl          ! Print control
+   USE lbclnk          ! lateral boundary condition 
+   USE lib_mpp         ! MPP library
+   USE eosbn2          ! compute density
+   USE timing          ! Timing
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_hpg        ! routine called by step module
+   PUBLIC   dyn_hpg_init   ! routine called by opa module
+
+   !                                !!* Namelist namdyn_hpg : hydrostatic pressure gradient
+   LOGICAL, PUBLIC ::   ln_hpg_zco   !: z-coordinate - full steps
+   LOGICAL, PUBLIC ::   ln_hpg_zps   !: z-coordinate - partial steps (interpolation)
+   LOGICAL, PUBLIC ::   ln_hpg_sco   !: s-coordinate (standard jacobian formulation)
+   LOGICAL, PUBLIC ::   ln_hpg_djc   !: s-coordinate (Density Jacobian with Cubic polynomial)
+   LOGICAL, PUBLIC ::   ln_hpg_prj   !: s-coordinate (Pressure Jacobian scheme)
+   LOGICAL, PUBLIC ::   ln_hpg_isf   !: s-coordinate similar to sco modify for isf
+
+   !                                !! Flag to control the type of hydrostatic pressure gradient
+   INTEGER, PARAMETER ::   np_ERROR  =-10   ! error in specification of lateral diffusion
+   INTEGER, PARAMETER ::   np_zco    =  0   ! z-coordinate - full steps
+   INTEGER, PARAMETER ::   np_zps    =  1   ! z-coordinate - partial steps (interpolation)
+   INTEGER, PARAMETER ::   np_sco    =  2   ! s-coordinate (standard jacobian formulation)
+   INTEGER, PARAMETER ::   np_djc    =  3   ! s-coordinate (Density Jacobian with Cubic polynomial)
+   INTEGER, PARAMETER ::   np_prj    =  4   ! s-coordinate (Pressure Jacobian scheme)
+   INTEGER, PARAMETER ::   np_isf    =  5   ! s-coordinate similar to sco modify for isf
+   !
+   INTEGER, PUBLIC ::   nhpg         !: type of pressure gradient scheme used ! (deduced from ln_hpg_... flags) (PUBLIC for TAM)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_hpg( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_hpg  ***
+      !!
+      !! ** Method  :   Call the hydrostatic pressure gradient routine
+      !!              using the scheme defined in the namelist
+      !!
+      !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
+      !!             - send trends to trd_dyn for futher diagnostics (l_trddyn=T)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdu, ztrdv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_hpg')
+      !
+      IF( l_trddyn ) THEN                    ! Temporary saving of ua and va trends (l_trddyn)
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) )
+         ztrdu(:,:,:) = ua(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:)
+      ENDIF
+      !
+      SELECT CASE ( nhpg )      ! Hydrostatic pressure gradient computation
+      CASE ( np_zco )   ;   CALL hpg_zco    ( kt )      ! z-coordinate
+      CASE ( np_zps )   ;   CALL hpg_zps    ( kt )      ! z-coordinate plus partial steps (interpolation)
+      CASE ( np_sco )   ;   CALL hpg_sco    ( kt )      ! s-coordinate (standard jacobian formulation)
+      CASE ( np_djc )   ;   CALL hpg_djc    ( kt )      ! s-coordinate (Density Jacobian with Cubic polynomial)
+      CASE ( np_prj )   ;   CALL hpg_prj    ( kt )      ! s-coordinate (Pressure Jacobian scheme)
+      CASE ( np_isf )   ;   CALL hpg_isf    ( kt )      ! s-coordinate similar to sco modify for ice shelf
+      END SELECT
+      !
+      IF( l_trddyn ) THEN      ! save the hydrostatic pressure gradient trends for momentum trend diagnostics
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_hpg, kt )
+         DEALLOCATE( ztrdu , ztrdv )
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' hpg  - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_hpg')
+      !
+   END SUBROUTINE dyn_hpg
+
+
+   SUBROUTINE dyn_hpg_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE dyn_hpg_init  ***
+      !!
+      !! ** Purpose :   initializations for the hydrostatic pressure gradient
+      !!              computation and consistency control
+      !!
+      !! ** Action  :   Read the namelist namdyn_hpg and check the consistency
+      !!      with the type of vertical coordinate used (zco, zps, sco)
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio = 0      ! temporary integer
+      INTEGER ::   ios             ! Local integer output status for namelist read
+      !!
+      INTEGER  ::   ji, jj, jk, ikt    ! dummy loop indices      ISF
+      REAL(wp) ::   znad
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  zts_top, zrhd   ! hypothesys on isf density
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::  zrhdtop_isf    ! density at bottom of ISF
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::  ziceload       ! density at bottom of ISF
+      !!
+      NAMELIST/namdyn_hpg/ ln_hpg_zco, ln_hpg_zps, ln_hpg_sco,     &
+         &                 ln_hpg_djc, ln_hpg_prj, ln_hpg_isf
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namdyn_hpg in reference namelist : Hydrostatic pressure gradient
+      READ  ( numnam_ref, namdyn_hpg, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_hpg in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namdyn_hpg in configuration namelist : Hydrostatic pressure gradient
+      READ  ( numnam_cfg, namdyn_hpg, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_hpg in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdyn_hpg )
+      !
+      IF(lwp) THEN                   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_hpg_init : hydrostatic pressure gradient initialisation'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn_hpg : choice of hpg scheme'
+         WRITE(numout,*) '      z-coord. - full steps                             ln_hpg_zco    = ', ln_hpg_zco
+         WRITE(numout,*) '      z-coord. - partial steps (interpolation)          ln_hpg_zps    = ', ln_hpg_zps
+         WRITE(numout,*) '      s-coord. (standard jacobian formulation)          ln_hpg_sco    = ', ln_hpg_sco
+         WRITE(numout,*) '      s-coord. (standard jacobian formulation) for isf  ln_hpg_isf    = ', ln_hpg_isf
+         WRITE(numout,*) '      s-coord. (Density Jacobian: Cubic polynomial)     ln_hpg_djc    = ', ln_hpg_djc
+         WRITE(numout,*) '      s-coord. (Pressure Jacobian: Cubic polynomial)    ln_hpg_prj    = ', ln_hpg_prj
+      ENDIF
+      !
+      IF( ln_hpg_djc )   &
+         &   CALL ctl_stop('dyn_hpg_init : Density Jacobian: Cubic polynominal method',   &
+         &                 '   currently disabled (bugs under investigation).'        ,   &
+         &                 '   Please select either  ln_hpg_sco or  ln_hpg_prj instead' )
+         !
+      IF( .NOT.ln_linssh .AND. .NOT.(ln_hpg_sco.OR.ln_hpg_prj.OR.ln_hpg_isf) )          &
+         &   CALL ctl_stop('dyn_hpg_init : non-linear free surface requires either ',   &
+         &                 '   the standard jacobian formulation hpg_sco    or '    ,   &
+         &                 '   the pressure jacobian formulation hpg_prj'             )
+         !
+      IF( ln_hpg_isf ) THEN
+         IF( .NOT. ln_isfcav )   CALL ctl_stop( ' hpg_isf not available if ln_isfcav = false ' )
+       ELSE
+         IF(       ln_isfcav )   CALL ctl_stop( 'Only hpg_isf has been corrected to work with ice shelf cavity.' )
+      ENDIF
+      !
+      !                               ! Set nhpg from ln_hpg_... flags & consistency check
+      nhpg   = np_ERROR
+      ioptio = 0
+      IF( ln_hpg_zco ) THEN   ;   nhpg = np_zco   ;   ioptio = ioptio +1   ;   ENDIF
+      IF( ln_hpg_zps ) THEN   ;   nhpg = np_zps   ;   ioptio = ioptio +1   ;   ENDIF
+      IF( ln_hpg_sco ) THEN   ;   nhpg = np_sco   ;   ioptio = ioptio +1   ;   ENDIF
+      IF( ln_hpg_djc ) THEN   ;   nhpg = np_djc   ;   ioptio = ioptio +1   ;   ENDIF
+      IF( ln_hpg_prj ) THEN   ;   nhpg = np_prj   ;   ioptio = ioptio +1   ;   ENDIF
+      IF( ln_hpg_isf ) THEN   ;   nhpg = np_isf   ;   ioptio = ioptio +1   ;   ENDIF
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'NO or several hydrostatic pressure gradient options used' )
+      ! 
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE( nhpg )
+         CASE( np_zco )   ;   WRITE(numout,*) '   ==>>>   z-coord. - full steps '
+         CASE( np_zps )   ;   WRITE(numout,*) '   ==>>>   z-coord. - partial steps (interpolation)'
+         CASE( np_sco )   ;   WRITE(numout,*) '   ==>>>   s-coord. (standard jacobian formulation)'
+         CASE( np_djc )   ;   WRITE(numout,*) '   ==>>>   s-coord. (Density Jacobian: Cubic polynomial)'
+         CASE( np_prj )   ;   WRITE(numout,*) '   ==>>>   s-coord. (Pressure Jacobian: Cubic polynomial)'
+         CASE( np_isf )   ;   WRITE(numout,*) '   ==>>>   s-coord. (standard jacobian formulation) for isf'
+         END SELECT
+         WRITE(numout,*)
+      ENDIF
+      !                          
+      IF ( .NOT. ln_isfcav ) THEN     !--- no ice shelf load
+         riceload(:,:) = 0._wp
+         !
+      ELSE                            !--- set an ice shelf load
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ice shelf case: set the ice-shelf load'
+         ALLOCATE( zts_top(jpi,jpj,jpts) , zrhd(jpi,jpj,jpk) , zrhdtop_isf(jpi,jpj) , ziceload(jpi,jpj) ) 
+         !
+         znad = 1._wp                     !- To use density and not density anomaly
+         !
+         !                                !- assume water displaced by the ice shelf is at T=-1.9 and S=34.4 (rude)
+         zts_top(:,:,jp_tem) = -1.9_wp   ;   zts_top(:,:,jp_sal) = 34.4_wp
+         !
+         DO jk = 1, jpk                   !- compute density of the water displaced by the ice shelf 
+            CALL eos( zts_top(:,:,:), gdept_n(:,:,jk), zrhd(:,:,jk) )
+         END DO
+         !
+         !                                !- compute rhd at the ice/oce interface (ice shelf side)
+         CALL eos( zts_top , risfdep, zrhdtop_isf )
+         !
+         !                                !- Surface value + ice shelf gradient
+         ziceload = 0._wp                       ! compute pressure due to ice shelf load 
+         DO jj = 1, jpj                         ! (used to compute hpgi/j for all the level from 1 to miku/v)
+            DO ji = 1, jpi                      ! divided by 2 later
+               ikt = mikt(ji,jj)
+               ziceload(ji,jj) = ziceload(ji,jj) + (znad + zrhd(ji,jj,1) ) * e3w_n(ji,jj,1) * (1._wp - tmask(ji,jj,1))
+               DO jk = 2, ikt-1
+                  ziceload(ji,jj) = ziceload(ji,jj) + (2._wp * znad + zrhd(ji,jj,jk-1) + zrhd(ji,jj,jk)) * e3w_n(ji,jj,jk) &
+                     &                              * (1._wp - tmask(ji,jj,jk))
+               END DO
+               IF (ikt  >=  2) ziceload(ji,jj) = ziceload(ji,jj) + (2._wp * znad + zrhdtop_isf(ji,jj) + zrhd(ji,jj,ikt-1)) &
+                  &                                              * ( risfdep(ji,jj) - gdept_n(ji,jj,ikt-1) )
+            END DO
+         END DO
+         riceload(:,:) = ziceload(:,:)  ! need to be saved for diaar5
+         !
+         DEALLOCATE( zts_top , zrhd , zrhdtop_isf , ziceload ) 
+      ENDIF
+      !
+   END SUBROUTINE dyn_hpg_init
+
+
+   SUBROUTINE hpg_zco( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE hpg_zco  ***
+      !!
+      !! ** Method  :   z-coordinate case, levels are horizontal surfaces.
+      !!      The now hydrostatic pressure gradient at a given level, jk,
+      !!      is computed by taking the vertical integral of the in-situ
+      !!      density gradient along the model level from the suface to that
+      !!      level:    zhpi = grav .....
+      !!                zhpj = grav .....
+      !!      add it to the general momentum trend (ua,va).
+      !!            ua = ua - 1/e1u * zhpi
+      !!            va = va - 1/e2v * zhpj
+      !!
+      !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk       ! dummy loop indices
+      REAL(wp) ::   zcoef0, zcoef1   ! temporary scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zhpi, zhpj
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:hpg_zco : hydrostatic pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   z-coordinate case '
+      ENDIF
+
+      zcoef0 = - grav * 0.5_wp      ! Local constant initialization
+
+      ! Surface value
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zcoef1 = zcoef0 * e3w_n(ji,jj,1)
+            ! hydrostatic pressure gradient
+            zhpi(ji,jj,1) = zcoef1 * ( rhd(ji+1,jj,1) - rhd(ji,jj,1) ) * r1_e1u(ji,jj)
+            zhpj(ji,jj,1) = zcoef1 * ( rhd(ji,jj+1,1) - rhd(ji,jj,1) ) * r1_e2v(ji,jj)
+            ! add to the general momentum trend
+            ua(ji,jj,1) = ua(ji,jj,1) + zhpi(ji,jj,1)
+            va(ji,jj,1) = va(ji,jj,1) + zhpj(ji,jj,1)
+         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.
+               zcoef1 = zcoef0 * e3w_n(ji,jj,jk)
+               ! hydrostatic pressure gradient
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1)   &
+                  &           + zcoef1 * (  ( rhd(ji+1,jj,jk)+rhd(ji+1,jj,jk-1) )    &
+                  &                       - ( rhd(ji  ,jj,jk)+rhd(ji  ,jj,jk-1) )  ) * r1_e1u(ji,jj)
+
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1)   &
+                  &           + zcoef1 * (  ( rhd(ji,jj+1,jk)+rhd(ji,jj+1,jk-1) )    &
+                  &                       - ( rhd(ji,jj,  jk)+rhd(ji,jj  ,jk-1) )  ) * r1_e2v(ji,jj)
+               ! add to the general momentum trend
+               ua(ji,jj,jk) = ua(ji,jj,jk) + zhpi(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + zhpj(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE hpg_zco
+
+
+   SUBROUTINE hpg_zps( kt )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE hpg_zps  ***
+      !!
+      !! ** Method  :   z-coordinate plus partial steps case.  blahblah...
+      !!
+      !! ** Action  : - Update (ua,va) with the now hydrastatic pressure trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk                       ! dummy loop indices
+      INTEGER  ::   iku, ikv                         ! temporary integers
+      REAL(wp) ::   zcoef0, zcoef1, zcoef2, zcoef3   ! temporary scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zhpi, zhpj
+      REAL(wp), DIMENSION(jpi,jpj) :: zgtsu, zgtsv, zgru, zgrv
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:hpg_zps : hydrostatic pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   z-coordinate with partial steps - vector optimization'
+      ENDIF
+
+      ! Partial steps: Compute NOW horizontal gradient of t, s, rd at the last ocean level
+      CALL zps_hde( kt, jpts, tsn, zgtsu, zgtsv, rhd, zgru , zgrv )
+
+      ! Local constant initialization
+      zcoef0 = - grav * 0.5_wp
+
+      !  Surface value (also valid in partial step case)
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zcoef1 = zcoef0 * e3w_n(ji,jj,1)
+            ! hydrostatic pressure gradient
+            zhpi(ji,jj,1) = zcoef1 * ( rhd(ji+1,jj  ,1) - rhd(ji,jj,1) ) * r1_e1u(ji,jj)
+            zhpj(ji,jj,1) = zcoef1 * ( rhd(ji  ,jj+1,1) - rhd(ji,jj,1) ) * r1_e2v(ji,jj)
+            ! add to the general momentum trend
+            ua(ji,jj,1) = ua(ji,jj,1) + zhpi(ji,jj,1)
+            va(ji,jj,1) = va(ji,jj,1) + zhpj(ji,jj,1)
+         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.
+               zcoef1 = zcoef0 * e3w_n(ji,jj,jk)
+               ! hydrostatic pressure gradient
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1)   &
+                  &           + zcoef1 * (  ( rhd(ji+1,jj,jk) + rhd(ji+1,jj,jk-1) )   &
+                  &                       - ( rhd(ji  ,jj,jk) + rhd(ji  ,jj,jk-1) )  ) * r1_e1u(ji,jj)
+
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1)   &
+                  &           + zcoef1 * (  ( rhd(ji,jj+1,jk) + rhd(ji,jj+1,jk-1) )   &
+                  &                       - ( rhd(ji,jj,  jk) + rhd(ji,jj  ,jk-1) )  ) * r1_e2v(ji,jj)
+               ! add to the general momentum trend
+               ua(ji,jj,jk) = ua(ji,jj,jk) + zhpi(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + zhpj(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      ! partial steps correction at the last level  (use zgru & zgrv computed in zpshde.F90)
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            iku = mbku(ji,jj)
+            ikv = mbkv(ji,jj)
+            zcoef2 = zcoef0 * MIN( e3w_n(ji,jj,iku), e3w_n(ji+1,jj  ,iku) )
+            zcoef3 = zcoef0 * MIN( e3w_n(ji,jj,ikv), e3w_n(ji  ,jj+1,ikv) )
+            IF( iku > 1 ) THEN            ! on i-direction (level 2 or more)
+               ua  (ji,jj,iku) = ua(ji,jj,iku) - zhpi(ji,jj,iku)         ! subtract old value
+               zhpi(ji,jj,iku) = zhpi(ji,jj,iku-1)                   &   ! compute the new one
+                  &            + zcoef2 * ( rhd(ji+1,jj,iku-1) - rhd(ji,jj,iku-1) + zgru(ji,jj) ) * r1_e1u(ji,jj)
+               ua  (ji,jj,iku) = ua(ji,jj,iku) + zhpi(ji,jj,iku)         ! add the new one to the general momentum trend
+            ENDIF
+            IF( ikv > 1 ) THEN            ! on j-direction (level 2 or more)
+               va  (ji,jj,ikv) = va(ji,jj,ikv) - zhpj(ji,jj,ikv)         ! subtract old value
+               zhpj(ji,jj,ikv) = zhpj(ji,jj,ikv-1)                   &   ! compute the new one
+                  &            + zcoef3 * ( rhd(ji,jj+1,ikv-1) - rhd(ji,jj,ikv-1) + zgrv(ji,jj) ) * r1_e2v(ji,jj)
+               va  (ji,jj,ikv) = va(ji,jj,ikv) + zhpj(ji,jj,ikv)         ! add the new one to the general momentum trend
+            ENDIF
+         END DO
+      END DO
+      !
+   END SUBROUTINE hpg_zps
+
+
+   SUBROUTINE hpg_sco( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE hpg_sco  ***
+      !!
+      !! ** Method  :   s-coordinate case. Jacobian scheme.
+      !!      The now hydrostatic pressure gradient at a given level, jk,
+      !!      is computed by taking the vertical integral of the in-situ
+      !!      density gradient along the model level from the suface to that
+      !!      level. s-coordinates (ln_sco): a corrective term is added
+      !!      to the horizontal pressure gradient :
+      !!         zhpi = grav .....  + 1/e1u mi(rhd) di[ grav dep3w ]
+      !!         zhpj = grav .....  + 1/e2v mj(rhd) dj[ grav dep3w ]
+      !!      add it to the general momentum trend (ua,va).
+      !!         ua = ua - 1/e1u * zhpi
+      !!         va = va - 1/e2v * zhpj
+      !!
+      !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk, jii, jjj                 ! dummy loop indices
+      REAL(wp) ::   zcoef0, zuap, zvap, znad, ztmp       ! temporary scalars
+      LOGICAL  ::   ll_tmp1, ll_tmp2                     ! local logical variables
+      REAL(wp), DIMENSION(jpi,jpj,jpk)      ::   zhpi, zhpj
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zcpx, zcpy   !W/D pressure filter
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_wd_il ) ALLOCATE(zcpx(jpi,jpj), zcpy(jpi,jpj))
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:hpg_sco : hydrostatic pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   s-coordinate case, OPA original scheme used'
+      ENDIF
+      !
+      zcoef0 = - grav * 0.5_wp
+      IF ( ln_linssh ) THEN   ;   znad = 0._wp         ! Fixed    volume: density anomaly
+      ELSE                    ;   znad = 1._wp         ! Variable volume: density
+      ENDIF
+      !
+      IF( ln_wd_il ) THEN
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1 
+             ll_tmp1 = MIN(  sshn(ji,jj)               ,  sshn(ji+1,jj) ) >                &
+                  &    MAX( -ht_0(ji,jj)               , -ht_0(ji+1,jj) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) +  ht_0(ji,jj),  sshn(ji+1,jj) + ht_0(ji+1,jj) )  &
+                  &                                                       > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)              -  sshn(ji+1,jj) ) > 1.E-12 ) .AND. (       &
+                  &    MAX(   sshn(ji,jj)              ,  sshn(ji+1,jj) ) >                &
+                  &    MAX(  -ht_0(ji,jj)              , -ht_0(ji+1,jj) ) + rn_wdmin1 + rn_wdmin2 )
+
+             IF(ll_tmp1) THEN
+               zcpx(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji+1,jj) -  sshn(ji  ,jj) = 0, it won't happen ! here
+               zcpx(ji,jj) = ABS( (sshn(ji+1,jj) + ht_0(ji+1,jj) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji+1,jj) - sshn(ji  ,jj)) )
+             ELSE
+               zcpx(ji,jj) = 0._wp
+             END IF
+      
+             ll_tmp1 = MIN(  sshn(ji,jj)              ,  sshn(ji,jj+1) ) >                &
+                  &    MAX( -ht_0(ji,jj)              , -ht_0(ji,jj+1) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) + ht_0(ji,jj),  sshn(ji,jj+1) + ht_0(ji,jj+1) )  &
+                  &                                                      > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)             -  sshn(ji,jj+1) ) > 1.E-12 ) .AND. (        &
+                  &    MAX(   sshn(ji,jj)             ,  sshn(ji,jj+1) ) >                &
+                  &    MAX(  -ht_0(ji,jj)             , -ht_0(ji,jj+1) ) + rn_wdmin1 + rn_wdmin2 )
+
+             IF(ll_tmp1) THEN
+               zcpy(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji,jj+1) -  sshn(ji,jj  ) = 0, it won't happen ! here
+               zcpy(ji,jj) = ABS( (sshn(ji,jj+1) + ht_0(ji,jj+1) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji,jj+1) - sshn(ji,jj  )) )
+             ELSE
+               zcpy(ji,jj) = 0._wp
+             END IF
+           END DO
+        END DO
+        CALL lbc_lnk_multi( 'dynhpg', zcpx, 'U', 1., zcpy, 'V', 1. )
+      END IF
+
+      ! Surface value
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            ! hydrostatic pressure gradient along s-surfaces
+            zhpi(ji,jj,1) = zcoef0 * (  e3w_n(ji+1,jj  ,1) * ( znad + rhd(ji+1,jj  ,1) )    &
+               &                      - e3w_n(ji  ,jj  ,1) * ( znad + rhd(ji  ,jj  ,1) )  ) * r1_e1u(ji,jj)
+            zhpj(ji,jj,1) = zcoef0 * (  e3w_n(ji  ,jj+1,1) * ( znad + rhd(ji  ,jj+1,1) )    &
+               &                      - e3w_n(ji  ,jj  ,1) * ( znad + rhd(ji  ,jj  ,1) )  ) * r1_e2v(ji,jj)
+            ! s-coordinate pressure gradient correction
+            zuap = -zcoef0 * ( rhd    (ji+1,jj,1) + rhd    (ji,jj,1) + 2._wp * znad )   &
+               &           * ( gde3w_n(ji+1,jj,1) - gde3w_n(ji,jj,1) ) * r1_e1u(ji,jj)
+            zvap = -zcoef0 * ( rhd    (ji,jj+1,1) + rhd    (ji,jj,1) + 2._wp * znad )   &
+               &           * ( gde3w_n(ji,jj+1,1) - gde3w_n(ji,jj,1) ) * r1_e2v(ji,jj)
+            !
+            IF( ln_wd_il ) THEN
+               zhpi(ji,jj,1) = zhpi(ji,jj,1) * zcpx(ji,jj)
+               zhpj(ji,jj,1) = zhpj(ji,jj,1) * zcpy(ji,jj) 
+               zuap = zuap * zcpx(ji,jj)
+               zvap = zvap * zcpy(ji,jj)
+            ENDIF
+            !
+            ! 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.
+               ! hydrostatic pressure gradient along s-surfaces
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1) + zcoef0 * r1_e1u(ji,jj)   &
+                  &           * (  e3w_n(ji+1,jj,jk) * ( rhd(ji+1,jj,jk) + rhd(ji+1,jj,jk-1) + 2*znad )   &
+                  &              - e3w_n(ji  ,jj,jk) * ( rhd(ji  ,jj,jk) + rhd(ji  ,jj,jk-1) + 2*znad )  )
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1) + zcoef0 * r1_e2v(ji,jj)   &
+                  &           * (  e3w_n(ji,jj+1,jk) * ( rhd(ji,jj+1,jk) + rhd(ji,jj+1,jk-1) + 2*znad )   &
+                  &              - e3w_n(ji,jj  ,jk) * ( rhd(ji,jj,  jk) + rhd(ji,jj  ,jk-1) + 2*znad )  )
+               ! s-coordinate pressure gradient correction
+               zuap = -zcoef0 * ( rhd    (ji+1,jj  ,jk) + rhd    (ji,jj,jk) + 2._wp * znad )   &
+                  &           * ( gde3w_n(ji+1,jj  ,jk) - gde3w_n(ji,jj,jk) ) * r1_e1u(ji,jj)
+               zvap = -zcoef0 * ( rhd    (ji  ,jj+1,jk) + rhd    (ji,jj,jk) + 2._wp * znad )   &
+                  &           * ( gde3w_n(ji  ,jj+1,jk) - gde3w_n(ji,jj,jk) ) * r1_e2v(ji,jj)
+               !
+               IF( ln_wd_il ) THEN
+                  zhpi(ji,jj,jk) = zhpi(ji,jj,jk) * zcpx(ji,jj)
+                  zhpj(ji,jj,jk) = zhpj(ji,jj,jk) * zcpy(ji,jj) 
+                  zuap = zuap * zcpx(ji,jj)
+                  zvap = zvap * zcpy(ji,jj)
+               ENDIF
+               !
+               ! 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
+            END DO
+         END DO
+      END DO
+      !
+      IF( ln_wd_il )  DEALLOCATE( zcpx , zcpy )
+      !
+   END SUBROUTINE hpg_sco
+
+
+   SUBROUTINE hpg_isf( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE hpg_isf  ***
+      !!
+      !! ** Method  :   s-coordinate case. Jacobian scheme.
+      !!      The now hydrostatic pressure gradient at a given level, jk,
+      !!      is computed by taking the vertical integral of the in-situ
+      !!      density gradient along the model level from the suface to that
+      !!      level. s-coordinates (ln_sco): a corrective term is added
+      !!      to the horizontal pressure gradient :
+      !!         zhpi = grav .....  + 1/e1u mi(rhd) di[ grav dep3w ]
+      !!         zhpj = grav .....  + 1/e2v mj(rhd) dj[ grav dep3w ]
+      !!      add it to the general momentum trend (ua,va).
+      !!         ua = ua - 1/e1u * zhpi
+      !!         va = va - 1/e2v * zhpj
+      !!      iceload is added and partial cell case are added to the top and bottom
+      !!      
+      !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk, ikt, iktp1i, iktp1j   ! dummy loop indices
+      REAL(wp) ::   zcoef0, zuap, zvap, znad          ! temporary scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk ) ::  zhpi, zhpj
+      REAL(wp), DIMENSION(jpi,jpj,jpts) ::  zts_top
+      REAL(wp), DIMENSION(jpi,jpj)      ::  zrhdtop_oce
+      !!----------------------------------------------------------------------
+      !
+      zcoef0 = - grav * 0.5_wp   ! Local constant initialization
+      !
+      znad=1._wp                 ! To use density and not density anomaly
+      !
+      !                          ! iniitialised to 0. zhpi zhpi 
+      zhpi(:,:,:) = 0._wp   ;   zhpj(:,:,:) = 0._wp
+
+      ! compute rhd at the ice/oce interface (ocean side)
+      ! usefull to reduce residual current in the test case ISOMIP with no melting
+      DO ji = 1, jpi
+        DO jj = 1, jpj
+          ikt = mikt(ji,jj)
+          zts_top(ji,jj,1) = tsn(ji,jj,ikt,1)
+          zts_top(ji,jj,2) = tsn(ji,jj,ikt,2)
+        END DO
+      END DO
+      CALL eos( zts_top, risfdep, zrhdtop_oce )
+
+!==================================================================================     
+!===== Compute surface value ===================================================== 
+!==================================================================================
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            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 * e3w_n(ji+1,jj,iktp1i)                                    &
+               &                                    * ( 2._wp * znad + rhd(ji+1,jj,iktp1i) + zrhdtop_oce(ji+1,jj) )   &
+               &                                  - 0.5_wp * e3w_n(ji,jj,ikt)                                         &
+               &                                    * ( 2._wp * znad + rhd(ji,jj,ikt) + zrhdtop_oce(ji,jj) )          &
+               &                                  + ( riceload(ji+1,jj) - riceload(ji,jj))                            ) 
+            zhpj(ji,jj,1) = zcoef0 / e2v(ji,jj) * ( 0.5_wp * e3w_n(ji,jj+1,iktp1j)                                    &
+               &                                    * ( 2._wp * znad + rhd(ji,jj+1,iktp1j) + zrhdtop_oce(ji,jj+1) )   &
+               &                                  - 0.5_wp * e3w_n(ji,jj,ikt)                                         & 
+               &                                    * ( 2._wp * znad + rhd(ji,jj,ikt) + zrhdtop_oce(ji,jj) )          &
+               &                                  + ( riceload(ji,jj+1) - riceload(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 )   &
+               &           * ( gde3w_n(ji+1,jj,1) - gde3w_n(ji,jj,1) ) * r1_e1u(ji,jj)
+            zvap = -zcoef0 * ( rhd    (ji,jj+1,1) + rhd    (ji,jj,1) + 2._wp * znad )   &
+               &           * ( gde3w_n(ji,jj+1,1) - gde3w_n(ji,jj,1) ) * r1_e2v(ji,jj)
+            ! add to the general momentum trend
+            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 interior value ===================================================== 
+!==================================================================================
+      ! interior value (2=<jk=<jpkm1)
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ! hydrostatic pressure gradient along s-surfaces
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1) + zcoef0 / e1u(ji,jj)   &
+                  &           * (  e3w_n(ji+1,jj,jk) * ( rhd(ji+1,jj,jk) + rhd(ji+1,jj,jk-1) + 2*znad ) * wmask(ji+1,jj,jk)   &
+                  &              - e3w_n(ji  ,jj,jk) * ( rhd(ji  ,jj,jk) + rhd(ji  ,jj,jk-1) + 2*znad ) * wmask(ji  ,jj,jk)   )
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1) + zcoef0 / e2v(ji,jj)   &
+                  &           * (  e3w_n(ji,jj+1,jk) * ( rhd(ji,jj+1,jk) + rhd(ji,jj+1,jk-1) + 2*znad ) * wmask(ji,jj+1,jk)   &
+                  &              - e3w_n(ji,jj  ,jk) * ( rhd(ji,jj,  jk) + rhd(ji,jj  ,jk-1) + 2*znad ) * wmask(ji,jj  ,jk)   )
+               ! s-coordinate pressure gradient correction
+               zuap = -zcoef0 * ( rhd   (ji+1,jj  ,jk) + rhd   (ji,jj,jk) + 2._wp * znad )   &
+                  &           * ( gde3w_n(ji+1,jj  ,jk) - gde3w_n(ji,jj,jk) ) / e1u(ji,jj)
+               zvap = -zcoef0 * ( rhd   (ji  ,jj+1,jk) + rhd   (ji,jj,jk) + 2._wp * znad )   &
+                  &           * ( gde3w_n(ji  ,jj+1,jk) - gde3w_n(ji,jj,jk) ) / e2v(ji,jj)
+               ! add to the general momentum trend
+               ua(ji,jj,jk) = ua(ji,jj,jk) + (zhpi(ji,jj,jk) + zuap) * umask(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + (zhpj(ji,jj,jk) + zvap) * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE hpg_isf
+
+
+   SUBROUTINE hpg_djc( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE hpg_djc  ***
+      !!
+      !! ** Method  :   Density Jacobian with Cubic polynomial scheme
+      !!
+      !! Reference: Shchepetkin and McWilliams, J. Geophys. Res., 108(C3), 3090, 2003
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk          ! dummy loop indices
+      REAL(wp) ::   zcoef0, zep, cffw   ! temporary scalars
+      REAL(wp) ::   z1_10, cffu, cffx   !    "         "
+      REAL(wp) ::   z1_12, cffv, cffy   !    "         "
+      LOGICAL  ::   ll_tmp1, ll_tmp2    ! local logical variables
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zhpi, zhpj
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   dzx, dzy, dzz, dzu, dzv, dzw
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   drhox, drhoy, drhoz, drhou, drhov, drhow
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   rho_i, rho_j, rho_k
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zcpx, zcpy   !W/D pressure filter
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_wd_il ) THEN
+         ALLOCATE( zcpx(jpi,jpj) , zcpy(jpi,jpj) )
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1 
+             ll_tmp1 = MIN(  sshn(ji,jj)              ,  sshn(ji+1,jj) ) >                &
+                  &    MAX( -ht_0(ji,jj)              , -ht_0(ji+1,jj) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) + ht_0(ji,jj),  sshn(ji+1,jj) + ht_0(ji+1,jj) )  &
+                  &                                                      > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)             -  sshn(ji+1,jj) ) > 1.E-12 ) .AND. (        &
+                  &    MAX(   sshn(ji,jj)             ,  sshn(ji+1,jj) ) >                &
+                  &    MAX(  -ht_0(ji,jj)             , -ht_0(ji+1,jj) ) + rn_wdmin1 + rn_wdmin2 )
+             IF(ll_tmp1) THEN
+               zcpx(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji+1,jj) -  sshn(ji  ,jj) = 0, it won't happen ! here
+               zcpx(ji,jj) = ABS( (sshn(ji+1,jj) + ht_0(ji+1,jj) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji+1,jj) - sshn(ji  ,jj)) )
+             ELSE
+               zcpx(ji,jj) = 0._wp
+             END IF
+      
+             ll_tmp1 = MIN(  sshn(ji,jj)              ,  sshn(ji,jj+1) ) >                &
+                  &    MAX( -ht_0(ji,jj)              , -ht_0(ji,jj+1) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) + ht_0(ji,jj),  sshn(ji,jj+1) + ht_0(ji,jj+1) )  &
+                  &                                                      > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)             -  sshn(ji,jj+1) ) > 1.E-12 ) .AND. (        &
+                  &    MAX(   sshn(ji,jj)             ,  sshn(ji,jj+1) ) >                &
+                  &    MAX(  -ht_0(ji,jj)             , -ht_0(ji,jj+1) ) + rn_wdmin1 + rn_wdmin2 )
+
+             IF(ll_tmp1) THEN
+               zcpy(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji,jj+1) -  sshn(ji,jj  ) = 0, it won't happen ! here
+               zcpy(ji,jj) = ABS( (sshn(ji,jj+1) + ht_0(ji,jj+1) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji,jj+1) - sshn(ji,jj  )) )
+             ELSE
+               zcpy(ji,jj) = 0._wp
+             END IF
+           END DO
+        END DO
+        CALL lbc_lnk_multi( 'dynhpg', zcpx, 'U', 1., zcpy, 'V', 1. )
+      END IF
+
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:hpg_djc : hydrostatic pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   s-coordinate case, density Jacobian with cubic polynomial scheme'
+      ENDIF
+
+      ! Local constant initialization
+      zcoef0 = - grav * 0.5_wp
+      z1_10  = 1._wp / 10._wp
+      z1_12  = 1._wp / 12._wp
+
+      !----------------------------------------------------------------------------------------
+      !  compute and store in provisional arrays elementary vertical and horizontal differences
+      !----------------------------------------------------------------------------------------
+
+!!bug gm   Not a true bug, but... dzz=e3w  for dzx, dzy verify what it is really
+
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               drhoz(ji,jj,jk) = rhd    (ji  ,jj  ,jk) - rhd    (ji,jj,jk-1)
+               dzz  (ji,jj,jk) = gde3w_n(ji  ,jj  ,jk) - gde3w_n(ji,jj,jk-1)
+               drhox(ji,jj,jk) = rhd    (ji+1,jj  ,jk) - rhd    (ji,jj,jk  )
+               dzx  (ji,jj,jk) = gde3w_n(ji+1,jj  ,jk) - gde3w_n(ji,jj,jk  )
+               drhoy(ji,jj,jk) = rhd    (ji  ,jj+1,jk) - rhd    (ji,jj,jk  )
+               dzy  (ji,jj,jk) = gde3w_n(ji  ,jj+1,jk) - gde3w_n(ji,jj,jk  )
+            END DO
+         END DO
+      END DO
+
+      !-------------------------------------------------------------------------
+      ! compute harmonic averages using eq. 5.18
+      !-------------------------------------------------------------------------
+      zep = 1.e-15
+
+!!bug  gm  drhoz not defined at level 1 and used (jk-1 with jk=2)
+!!bug  gm  idem for drhox, drhoy et ji=jpi and jj=jpj
+
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               cffw = 2._wp * drhoz(ji  ,jj  ,jk) * drhoz(ji,jj,jk-1)
+
+               cffu = 2._wp * drhox(ji+1,jj  ,jk) * drhox(ji,jj,jk  )
+               cffx = 2._wp * dzx  (ji+1,jj  ,jk) * dzx  (ji,jj,jk  )
+
+               cffv = 2._wp * drhoy(ji  ,jj+1,jk) * drhoy(ji,jj,jk  )
+               cffy = 2._wp * dzy  (ji  ,jj+1,jk) * dzy  (ji,jj,jk  )
+
+               IF( cffw > zep) THEN
+                  drhow(ji,jj,jk) = 2._wp *   drhoz(ji,jj,jk) * drhoz(ji,jj,jk-1)   &
+                     &                    / ( drhoz(ji,jj,jk) + drhoz(ji,jj,jk-1) )
+               ELSE
+                  drhow(ji,jj,jk) = 0._wp
+               ENDIF
+
+               dzw(ji,jj,jk) = 2._wp *   dzz(ji,jj,jk) * dzz(ji,jj,jk-1)   &
+                  &                  / ( dzz(ji,jj,jk) + dzz(ji,jj,jk-1) )
+
+               IF( cffu > zep ) THEN
+                  drhou(ji,jj,jk) = 2._wp *   drhox(ji+1,jj,jk) * drhox(ji,jj,jk)   &
+                     &                    / ( drhox(ji+1,jj,jk) + drhox(ji,jj,jk) )
+               ELSE
+                  drhou(ji,jj,jk ) = 0._wp
+               ENDIF
+
+               IF( cffx > zep ) THEN
+                  dzu(ji,jj,jk) = 2._wp *   dzx(ji+1,jj,jk) * dzx(ji,jj,jk)   &
+                     &                  / ( dzx(ji+1,jj,jk) + dzx(ji,jj,jk) )
+               ELSE
+                  dzu(ji,jj,jk) = 0._wp
+               ENDIF
+
+               IF( cffv > zep ) THEN
+                  drhov(ji,jj,jk) = 2._wp *   drhoy(ji,jj+1,jk) * drhoy(ji,jj,jk)   &
+                     &                    / ( drhoy(ji,jj+1,jk) + drhoy(ji,jj,jk) )
+               ELSE
+                  drhov(ji,jj,jk) = 0._wp
+               ENDIF
+
+               IF( cffy > zep ) THEN
+                  dzv(ji,jj,jk) = 2._wp *   dzy(ji,jj+1,jk) * dzy(ji,jj,jk)   &
+                     &                  / ( dzy(ji,jj+1,jk) + dzy(ji,jj,jk) )
+               ELSE
+                  dzv(ji,jj,jk) = 0._wp
+               ENDIF
+
+            END DO
+         END DO
+      END DO
+
+      !----------------------------------------------------------------------------------
+      ! apply boundary conditions at top and bottom using 5.36-5.37
+      !----------------------------------------------------------------------------------
+      drhow(:,:, 1 ) = 1.5_wp * ( drhoz(:,:, 2 ) - drhoz(:,:,  1  ) ) - 0.5_wp * drhow(:,:,  2  )
+      drhou(:,:, 1 ) = 1.5_wp * ( drhox(:,:, 2 ) - drhox(:,:,  1  ) ) - 0.5_wp * drhou(:,:,  2  )
+      drhov(:,:, 1 ) = 1.5_wp * ( drhoy(:,:, 2 ) - drhoy(:,:,  1  ) ) - 0.5_wp * drhov(:,:,  2  )
+
+      drhow(:,:,jpk) = 1.5_wp * ( drhoz(:,:,jpk) - drhoz(:,:,jpkm1) ) - 0.5_wp * drhow(:,:,jpkm1)
+      drhou(:,:,jpk) = 1.5_wp * ( drhox(:,:,jpk) - drhox(:,:,jpkm1) ) - 0.5_wp * drhou(:,:,jpkm1)
+      drhov(:,:,jpk) = 1.5_wp * ( drhoy(:,:,jpk) - drhoy(:,:,jpkm1) ) - 0.5_wp * drhov(:,:,jpkm1)
+
+
+      !--------------------------------------------------------------
+      ! Upper half of top-most grid box, compute and store
+      !-------------------------------------------------------------
+
+!!bug gm   :  e3w-gde3w = 0.5*e3w  ....  and gde3w(2)-gde3w(1)=e3w(2) ....   to be verified
+!          true if gde3w is really defined as the sum of the e3w scale factors as, it seems to me, it should be
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            rho_k(ji,jj,1) = -grav * ( e3w_n(ji,jj,1) - gde3w_n(ji,jj,1) )               &
+               &                   * (  rhd(ji,jj,1)                                     &
+               &                     + 0.5_wp * ( rhd    (ji,jj,2) - rhd    (ji,jj,1) )  &
+               &                              * ( e3w_n  (ji,jj,1) - gde3w_n(ji,jj,1) )  &
+               &                              / ( gde3w_n(ji,jj,2) - gde3w_n(ji,jj,1) )  )
+         END DO
+      END DO
+
+!!bug gm    : here also, simplification is possible
+!!bug gm    : optimisation: 1/10 and 1/12 the division should be done before the loop
+
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+
+               rho_k(ji,jj,jk) = zcoef0 * ( rhd    (ji,jj,jk) + rhd    (ji,jj,jk-1) )                                   &
+                  &                     * ( gde3w_n(ji,jj,jk) - gde3w_n(ji,jj,jk-1) )                                   &
+                  &            - grav * z1_10 * (                                                                   &
+                  &     ( drhow  (ji,jj,jk) - drhow  (ji,jj,jk-1) )                                                     &
+                  &   * ( gde3w_n(ji,jj,jk) - gde3w_n(ji,jj,jk-1) - z1_12 * ( dzw  (ji,jj,jk) + dzw  (ji,jj,jk-1) ) )   &
+                  &   - ( dzw    (ji,jj,jk) - dzw    (ji,jj,jk-1) )                                                     &
+                  &   * ( rhd    (ji,jj,jk) - rhd    (ji,jj,jk-1) - z1_12 * ( drhow(ji,jj,jk) + drhow(ji,jj,jk-1) ) )   &
+                  &                             )
+
+               rho_i(ji,jj,jk) = zcoef0 * ( rhd    (ji+1,jj,jk) + rhd    (ji,jj,jk) )                                   &
+                  &                     * ( gde3w_n(ji+1,jj,jk) - gde3w_n(ji,jj,jk) )                                   &
+                  &            - grav* z1_10 * (                                                                    &
+                  &     ( drhou  (ji+1,jj,jk) - drhou  (ji,jj,jk) )                                                     &
+                  &   * ( gde3w_n(ji+1,jj,jk) - gde3w_n(ji,jj,jk) - z1_12 * ( dzu  (ji+1,jj,jk) + dzu  (ji,jj,jk) ) )   &
+                  &   - ( dzu    (ji+1,jj,jk) - dzu    (ji,jj,jk) )                                                     &
+                  &   * ( rhd    (ji+1,jj,jk) - rhd    (ji,jj,jk) - z1_12 * ( drhou(ji+1,jj,jk) + drhou(ji,jj,jk) ) )   &
+                  &                            )
+
+               rho_j(ji,jj,jk) = zcoef0 * ( rhd    (ji,jj+1,jk) + rhd    (ji,jj,jk) )                                 &
+                  &                     * ( gde3w_n(ji,jj+1,jk) - gde3w_n(ji,jj,jk) )                                   &
+                  &            - grav* z1_10 * (                                                                    &
+                  &     ( drhov  (ji,jj+1,jk) - drhov  (ji,jj,jk) )                                                     &
+                  &   * ( gde3w_n(ji,jj+1,jk) - gde3w_n(ji,jj,jk) - z1_12 * ( dzv  (ji,jj+1,jk) + dzv  (ji,jj,jk) ) )   &
+                  &   - ( dzv    (ji,jj+1,jk) - dzv    (ji,jj,jk) )                                                     &
+                  &   * ( rhd    (ji,jj+1,jk) - rhd    (ji,jj,jk) - z1_12 * ( drhov(ji,jj+1,jk) + drhov(ji,jj,jk) ) )   &
+                  &                            )
+
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'dynhpg', rho_k, 'W', 1., rho_i, 'U', 1., rho_j, 'V', 1. )
+
+      ! ---------------
+      !  Surface value
+      ! ---------------
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zhpi(ji,jj,1) = ( rho_k(ji+1,jj  ,1) - rho_k(ji,jj,1) - rho_i(ji,jj,1) ) * r1_e1u(ji,jj)
+            zhpj(ji,jj,1) = ( rho_k(ji  ,jj+1,1) - rho_k(ji,jj,1) - rho_j(ji,jj,1) ) * r1_e2v(ji,jj)
+            IF( ln_wd_il ) THEN
+              zhpi(ji,jj,1) = zhpi(ji,jj,1) * zcpx(ji,jj)
+              zhpj(ji,jj,1) = zhpj(ji,jj,1) * zcpy(ji,jj) 
+            ENDIF
+            ! add to the general momentum trend
+            ua(ji,jj,1) = ua(ji,jj,1) + zhpi(ji,jj,1)
+            va(ji,jj,1) = va(ji,jj,1) + zhpj(ji,jj,1)
+         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.
+               ! hydrostatic pressure gradient along s-surfaces
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1)                                &
+                  &           + (  ( rho_k(ji+1,jj,jk) - rho_k(ji,jj,jk  ) )    &
+                  &              - ( rho_i(ji  ,jj,jk) - rho_i(ji,jj,jk-1) )  ) * r1_e1u(ji,jj)
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1)                                &
+                  &           + (  ( rho_k(ji,jj+1,jk) - rho_k(ji,jj,jk  ) )    &
+                  &               -( rho_j(ji,jj  ,jk) - rho_j(ji,jj,jk-1) )  ) * r1_e2v(ji,jj)
+               IF( ln_wd_il ) THEN
+                 zhpi(ji,jj,jk) = zhpi(ji,jj,jk) * zcpx(ji,jj)
+                 zhpj(ji,jj,jk) = zhpj(ji,jj,jk) * zcpy(ji,jj) 
+               ENDIF
+               ! add to the general momentum trend
+               ua(ji,jj,jk) = ua(ji,jj,jk) + zhpi(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + zhpj(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF( ln_wd_il )   DEALLOCATE( zcpx, zcpy )
+      !
+   END SUBROUTINE hpg_djc
+
+
+   SUBROUTINE hpg_prj( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE hpg_prj  ***
+      !!
+      !! ** Method  :   s-coordinate case.
+      !!      A Pressure-Jacobian horizontal pressure gradient method
+      !!      based on the constrained cubic-spline interpolation for
+      !!      all vertical coordinate systems
+      !!
+      !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
+      !!----------------------------------------------------------------------
+      INTEGER, PARAMETER  :: polynomial_type = 1    ! 1: cubic spline, 2: linear
+      INTEGER, INTENT(in) ::   kt                   ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk, jkk                 ! dummy loop indices
+      REAL(wp) ::   zcoef0, znad                    ! local scalars
+      !
+      !! The local variables for the correction term
+      INTEGER  :: jk1, jis, jid, jjs, jjd
+      LOGICAL  :: ll_tmp1, ll_tmp2                  ! local logical variables
+      REAL(wp) :: zuijk, zvijk, zpwes, zpwed, zpnss, zpnsd, zdeps
+      REAL(wp) :: zrhdt1
+      REAL(wp) :: zdpdx1, zdpdx2, zdpdy1, zdpdy2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdept, zrhh
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zhpi, zu, zv, fsp, xsp, asp, bsp, csp, dsp
+      REAL(wp), DIMENSION(jpi,jpj)   ::   zsshu_n, zsshv_n
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zcpx, zcpy   !W/D pressure filter
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:hpg_prj : hydrostatic pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   s-coordinate case, cubic spline pressure Jacobian'
+      ENDIF
+
+      ! Local constant initialization
+      zcoef0 = - grav
+      znad = 1._wp
+      IF( ln_linssh )   znad = 0._wp
+
+      IF( ln_wd_il ) THEN
+         ALLOCATE( zcpx(jpi,jpj) , zcpy(jpi,jpj) )
+         DO jj = 2, jpjm1
+           DO ji = 2, jpim1 
+             ll_tmp1 = MIN(  sshn(ji,jj)              ,  sshn(ji+1,jj) ) >                &
+                  &    MAX( -ht_0(ji,jj)              , -ht_0(ji+1,jj) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) + ht_0(ji,jj),  sshn(ji+1,jj) + ht_0(ji+1,jj) )  &
+                  &                                                      > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)             -  sshn(ji+1,jj) ) > 1.E-12 ) .AND. (         &
+                  &    MAX(   sshn(ji,jj)             ,  sshn(ji+1,jj) ) >                &
+                  &    MAX(  -ht_0(ji,jj)             , -ht_0(ji+1,jj) ) + rn_wdmin1 + rn_wdmin2 )
+
+             IF(ll_tmp1) THEN
+               zcpx(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji+1,jj) -  sshn(ji  ,jj) = 0, it won't happen ! here
+               zcpx(ji,jj) = ABS( (sshn(ji+1,jj) + ht_0(ji+1,jj) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji+1,jj) -  sshn(ji  ,jj)) )
+              
+                zcpx(ji,jj) = max(min( zcpx(ji,jj) , 1.0_wp),0.0_wp)
+             ELSE
+               zcpx(ji,jj) = 0._wp
+             END IF
+      
+             ll_tmp1 = MIN(  sshn(ji,jj)              ,  sshn(ji,jj+1) ) >                &
+                  &    MAX( -ht_0(ji,jj)              , -ht_0(ji,jj+1) ) .AND.            &
+                  &    MAX(  sshn(ji,jj) + ht_0(ji,jj),  sshn(ji,jj+1) + ht_0(ji,jj+1) )  &
+                  &                                                      > rn_wdmin1 + rn_wdmin2
+             ll_tmp2 = ( ABS( sshn(ji,jj)             -  sshn(ji,jj+1) ) > 1.E-12 ) .AND. (      &
+                  &    MAX(   sshn(ji,jj)             ,  sshn(ji,jj+1) ) >                &
+                  &    MAX(  -ht_0(ji,jj)             , -ht_0(ji,jj+1) ) + rn_wdmin1 + rn_wdmin2 )
+
+             IF(ll_tmp1) THEN
+               zcpy(ji,jj) = 1.0_wp
+             ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji,jj+1) -  sshn(ji,jj  ) = 0, it won't happen ! here
+               zcpy(ji,jj) = ABS( (sshn(ji,jj+1) + ht_0(ji,jj+1) - sshn(ji,jj) - ht_0(ji,jj)) &
+                           &    / (sshn(ji,jj+1) - sshn(ji,jj  )) )
+                zcpy(ji,jj) = max(min( zcpy(ji,jj) , 1.0_wp),0.0_wp)
+
+               ELSE
+                  zcpy(ji,jj) = 0._wp
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'dynhpg', zcpx, 'U', 1., zcpy, 'V', 1. )
+      ENDIF
+
+      ! Clean 3-D work arrays
+      zhpi(:,:,:) = 0._wp
+      zrhh(:,:,:) = rhd(:,:,:)
+
+      ! Preparing vertical density profile "zrhh(:,:,:)" for hybrid-sco coordinate
+      DO jj = 1, jpj
+        DO ji = 1, jpi
+          jk = mbkt(ji,jj)
+          IF(     jk <=  1   ) THEN   ;   zrhh(ji,jj,    :   ) = 0._wp
+          ELSEIF( jk ==  2   ) THEN   ;   zrhh(ji,jj,jk+1:jpk) = rhd(ji,jj,jk)
+          ELSEIF( jk < jpkm1 ) THEN
+             DO jkk = jk+1, jpk
+                zrhh(ji,jj,jkk) = interp1(gde3w_n(ji,jj,jkk  ), gde3w_n(ji,jj,jkk-1),   &
+                   &                      gde3w_n(ji,jj,jkk-2), zrhh    (ji,jj,jkk-1), zrhh(ji,jj,jkk-2))
+             END DO
+          ENDIF
+        END DO
+      END DO
+
+      ! Transfer the depth of "T(:,:,:)" to vertical coordinate "zdept(:,:,:)"
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zdept(ji,jj,1) = 0.5_wp * e3w_n(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) + e3w_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      fsp(:,:,:) = zrhh (:,:,:)
+      xsp(:,:,:) = zdept(:,:,:)
+
+      ! Construct the vertical density profile with the
+      ! constrained cubic spline interpolation
+      ! rho(z) = asp + bsp*z + csp*z^2 + dsp*z^3
+      CALL cspline( fsp, xsp, asp, bsp, csp, dsp, polynomial_type )
+
+      ! Integrate the hydrostatic pressure "zhpi(:,:,:)" at "T(ji,jj,1)"
+      DO jj = 2, jpj
+        DO ji = 2, jpi
+          zrhdt1 = zrhh(ji,jj,1) - interp3( zdept(ji,jj,1), asp(ji,jj,1), bsp(ji,jj,1),  &
+             &                                              csp(ji,jj,1), dsp(ji,jj,1) ) * 0.25_wp * e3w_n(ji,jj,1)
+
+          ! assuming linear profile across the top half surface layer
+          zhpi(ji,jj,1) =  0.5_wp * e3w_n(ji,jj,1) * zrhdt1
+        END DO
+      END DO
+
+      ! Calculate the pressure "zhpi(:,:,:)" at "T(ji,jj,2:jpkm1)"
+      DO jk = 2, jpkm1
+        DO jj = 2, jpj
+          DO ji = 2, jpi
+            zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1) +                                  &
+               &             integ_spline( zdept(ji,jj,jk-1), zdept(ji,jj,jk),   &
+               &                           asp  (ji,jj,jk-1), bsp  (ji,jj,jk-1), &
+               &                           csp  (ji,jj,jk-1), dsp  (ji,jj,jk-1)  )
+          END DO
+        END DO
+      END DO
+
+      ! Z coordinate of U(ji,jj,1:jpkm1) and V(ji,jj,1:jpkm1)
+
+      ! Prepare zsshu_n and zsshv_n
+      DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+!!gm BUG ?    if it is ssh at u- & v-point then it should be:
+!          zsshu_n(ji,jj) = (e1e2t(ji,jj) * sshn(ji,jj) + e1e2t(ji+1,jj) * sshn(ji+1,jj)) * &
+!                         & r1_e1e2u(ji,jj) * umask(ji,jj,1) * 0.5_wp 
+!          zsshv_n(ji,jj) = (e1e2t(ji,jj) * sshn(ji,jj) + e1e2t(ji,jj+1) * sshn(ji,jj+1)) * &
+!                         & r1_e1e2v(ji,jj) * vmask(ji,jj,1) * 0.5_wp 
+!!gm not this:
+          zsshu_n(ji,jj) = (e1e2u(ji,jj) * sshn(ji,jj) + e1e2u(ji+1, jj) * sshn(ji+1,jj)) * &
+                         & r1_e1e2u(ji,jj) * umask(ji,jj,1) * 0.5_wp 
+          zsshv_n(ji,jj) = (e1e2v(ji,jj) * sshn(ji,jj) + e1e2v(ji+1, jj) * sshn(ji,jj+1)) * &
+                         & r1_e1e2v(ji,jj) * vmask(ji,jj,1) * 0.5_wp 
+        END DO
+      END DO
+
+      CALL lbc_lnk_multi ('dynhpg', zsshu_n, 'U', 1., zsshv_n, 'V', 1. )
+
+      DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+          zu(ji,jj,1) = - ( e3u_n(ji,jj,1) - zsshu_n(ji,jj) * znad) 
+          zv(ji,jj,1) = - ( e3v_n(ji,jj,1) - zsshv_n(ji,jj) * znad)
+        END DO
+      END DO
+
+      DO jk = 2, jpkm1
+        DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            zu(ji,jj,jk) = zu(ji,jj,jk-1) - e3u_n(ji,jj,jk)
+            zv(ji,jj,jk) = zv(ji,jj,jk-1) - e3v_n(ji,jj,jk)
+          END DO
+        END DO
+      END DO
+
+      DO jk = 1, jpkm1
+        DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            zu(ji,jj,jk) = zu(ji,jj,jk) + 0.5_wp * e3u_n(ji,jj,jk)
+            zv(ji,jj,jk) = zv(ji,jj,jk) + 0.5_wp * e3v_n(ji,jj,jk)
+          END DO
+        END DO
+      END DO
+
+      DO jk = 1, jpkm1
+        DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            zu(ji,jj,jk) = MIN(  zu(ji,jj,jk) , MAX( -zdept(ji,jj,jk) , -zdept(ji+1,jj,jk) )  )
+            zu(ji,jj,jk) = MAX(  zu(ji,jj,jk) , MIN( -zdept(ji,jj,jk) , -zdept(ji+1,jj,jk) )  )
+            zv(ji,jj,jk) = MIN(  zv(ji,jj,jk) , MAX( -zdept(ji,jj,jk) , -zdept(ji,jj+1,jk) )  )
+            zv(ji,jj,jk) = MAX(  zv(ji,jj,jk) , MIN( -zdept(ji,jj,jk) , -zdept(ji,jj+1,jk) )  )
+          END DO
+        END DO
+      END DO
+
+
+      DO jk = 1, jpkm1
+        DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            zpwes = 0._wp; zpwed = 0._wp
+            zpnss = 0._wp; zpnsd = 0._wp
+            zuijk = zu(ji,jj,jk)
+            zvijk = zv(ji,jj,jk)
+
+            !!!!!     for u equation
+            IF( jk <= mbku(ji,jj) ) THEN
+               IF( -zdept(ji+1,jj,jk) >= -zdept(ji,jj,jk) ) THEN
+                 jis = ji + 1; jid = ji
+               ELSE
+                 jis = ji;     jid = ji +1
+               ENDIF
+
+               ! integrate the pressure on the shallow side
+               jk1 = jk
+               DO WHILE ( -zdept(jis,jj,jk1) > zuijk )
+                 IF( jk1 == mbku(ji,jj) ) THEN
+                   zuijk = -zdept(jis,jj,jk1)
+                   EXIT
+                 ENDIF
+                 zdeps = MIN(zdept(jis,jj,jk1+1), -zuijk)
+                 zpwes = zpwes +                                    &
+                      integ_spline(zdept(jis,jj,jk1), zdeps,            &
+                             asp(jis,jj,jk1),    bsp(jis,jj,jk1), &
+                             csp(jis,jj,jk1),    dsp(jis,jj,jk1))
+                 jk1 = jk1 + 1
+               END DO
+
+               ! integrate the pressure on the deep side
+               jk1 = jk
+               DO WHILE ( -zdept(jid,jj,jk1) < zuijk )
+                 IF( jk1 == 1 ) THEN
+                   zdeps = zdept(jid,jj,1) + MIN(zuijk, sshn(jid,jj)*znad)
+                   zrhdt1 = zrhh(jid,jj,1) - interp3(zdept(jid,jj,1), asp(jid,jj,1), &
+                                                     bsp(jid,jj,1),   csp(jid,jj,1), &
+                                                     dsp(jid,jj,1)) * zdeps
+                   zpwed  = zpwed + 0.5_wp * (zrhh(jid,jj,1) + zrhdt1) * zdeps
+                   EXIT
+                 ENDIF
+                 zdeps = MAX(zdept(jid,jj,jk1-1), -zuijk)
+                 zpwed = zpwed +                                        &
+                        integ_spline(zdeps,              zdept(jid,jj,jk1), &
+                               asp(jid,jj,jk1-1), bsp(jid,jj,jk1-1),  &
+                               csp(jid,jj,jk1-1), dsp(jid,jj,jk1-1) )
+                 jk1 = jk1 - 1
+               END DO
+
+               ! update the momentum trends in u direction
+
+               zdpdx1 = zcoef0 * r1_e1u(ji,jj) * ( zhpi(ji+1,jj,jk) - zhpi(ji,jj,jk) )
+               IF( .NOT.ln_linssh ) THEN
+                 zdpdx2 = zcoef0 * r1_e1u(ji,jj) * &
+                    &    ( REAL(jis-jid, wp) * (zpwes + zpwed) + (sshn(ji+1,jj)-sshn(ji,jj)) )
+                ELSE
+                 zdpdx2 = zcoef0 * r1_e1u(ji,jj) * REAL(jis-jid, wp) * (zpwes + zpwed)
+               ENDIF
+               IF( ln_wd_il ) THEN
+                  zdpdx1 = zdpdx1 * zcpx(ji,jj) * wdrampu(ji,jj)
+                  zdpdx2 = zdpdx2 * zcpx(ji,jj) * wdrampu(ji,jj)
+               ENDIF
+               ua(ji,jj,jk) = ua(ji,jj,jk) + (zdpdx1 + zdpdx2) * umask(ji,jj,jk) 
+            ENDIF
+
+            !!!!!     for v equation
+            IF( jk <= mbkv(ji,jj) ) THEN
+               IF( -zdept(ji,jj+1,jk) >= -zdept(ji,jj,jk) ) THEN
+                 jjs = jj + 1; jjd = jj
+               ELSE
+                 jjs = jj    ; jjd = jj + 1
+               ENDIF
+
+               ! integrate the pressure on the shallow side
+               jk1 = jk
+               DO WHILE ( -zdept(ji,jjs,jk1) > zvijk )
+                 IF( jk1 == mbkv(ji,jj) ) THEN
+                   zvijk = -zdept(ji,jjs,jk1)
+                   EXIT
+                 ENDIF
+                 zdeps = MIN(zdept(ji,jjs,jk1+1), -zvijk)
+                 zpnss = zpnss +                                      &
+                        integ_spline(zdept(ji,jjs,jk1), zdeps,            &
+                               asp(ji,jjs,jk1),    bsp(ji,jjs,jk1), &
+                               csp(ji,jjs,jk1),    dsp(ji,jjs,jk1) )
+                 jk1 = jk1 + 1
+               END DO
+
+               ! integrate the pressure on the deep side
+               jk1 = jk
+               DO WHILE ( -zdept(ji,jjd,jk1) < zvijk )
+                 IF( jk1 == 1 ) THEN
+                   zdeps = zdept(ji,jjd,1) + MIN(zvijk, sshn(ji,jjd)*znad)
+                   zrhdt1 = zrhh(ji,jjd,1) - interp3(zdept(ji,jjd,1), asp(ji,jjd,1), &
+                                                     bsp(ji,jjd,1),   csp(ji,jjd,1), &
+                                                     dsp(ji,jjd,1) ) * zdeps
+                   zpnsd  = zpnsd + 0.5_wp * (zrhh(ji,jjd,1) + zrhdt1) * zdeps
+                   EXIT
+                 ENDIF
+                 zdeps = MAX(zdept(ji,jjd,jk1-1), -zvijk)
+                 zpnsd = zpnsd +                                        &
+                        integ_spline(zdeps,              zdept(ji,jjd,jk1), &
+                               asp(ji,jjd,jk1-1), bsp(ji,jjd,jk1-1), &
+                               csp(ji,jjd,jk1-1), dsp(ji,jjd,jk1-1) )
+                 jk1 = jk1 - 1
+               END DO
+
+
+               ! update the momentum trends in v direction
+
+               zdpdy1 = zcoef0 * r1_e2v(ji,jj) * ( zhpi(ji,jj+1,jk) - zhpi(ji,jj,jk) )
+               IF( .NOT.ln_linssh ) THEN
+                  zdpdy2 = zcoef0 * r1_e2v(ji,jj) * &
+                          ( REAL(jjs-jjd, wp) * (zpnss + zpnsd) + (sshn(ji,jj+1)-sshn(ji,jj)) )
+               ELSE
+                  zdpdy2 = zcoef0 * r1_e2v(ji,jj) * REAL(jjs-jjd, wp) * (zpnss + zpnsd )
+               ENDIF
+               IF( ln_wd_il ) THEN
+                  zdpdy1 = zdpdy1 * zcpy(ji,jj) * wdrampv(ji,jj) 
+                  zdpdy2 = zdpdy2 * zcpy(ji,jj) * wdrampv(ji,jj) 
+               ENDIF
+
+               va(ji,jj,jk) = va(ji,jj,jk) + (zdpdy1 + zdpdy2) * vmask(ji,jj,jk)
+            ENDIF
+               !
+            END DO
+         END DO
+      END DO
+      !
+      IF( ln_wd_il )   DEALLOCATE( zcpx, zcpy )
+      !
+   END SUBROUTINE hpg_prj
+
+
+   SUBROUTINE cspline( fsp, xsp, asp, bsp, csp, dsp, polynomial_type )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE cspline  ***
+      !!
+      !! ** Purpose :   constrained cubic spline interpolation
+      !!
+      !! ** Method  :   f(x) = asp + bsp*x + csp*x^2 + dsp*x^3
+      !!
+      !! Reference: CJC Kruger, Constrained Cubic Spline Interpoltation
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   fsp, xsp           ! value and coordinate
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   asp, bsp, csp, dsp ! coefficients of the interpoated function
+      INTEGER                   , INTENT(in   ) ::   polynomial_type    ! 1: cubic spline   ;   2: Linear
+      !
+      INTEGER  ::   ji, jj, jk                 ! dummy loop indices
+      INTEGER  ::   jpi, jpj, jpkm1
+      REAL(wp) ::   zdf1, zdf2, zddf1, zddf2, ztmp1, ztmp2, zdxtmp
+      REAL(wp) ::   zdxtmp1, zdxtmp2, zalpha
+      REAL(wp) ::   zdf(size(fsp,3))
+      !!----------------------------------------------------------------------
+      !
+!!gm  WHAT !!!!!   THIS IS VERY DANGEROUS !!!!!  
+      jpi   = size(fsp,1)
+      jpj   = size(fsp,2)
+      jpkm1 = MAX( 1, size(fsp,3) - 1 )
+      !
+      IF (polynomial_type == 1) THEN     ! Constrained Cubic Spline
+         DO ji = 1, jpi
+            DO jj = 1, jpj
+           !!Fritsch&Butland's method, 1984 (preferred, but more computation)
+           !    DO jk = 2, jpkm1-1
+           !       zdxtmp1 = xsp(ji,jj,jk)   - xsp(ji,jj,jk-1)
+           !       zdxtmp2 = xsp(ji,jj,jk+1) - xsp(ji,jj,jk)
+           !       zdf1    = ( fsp(ji,jj,jk)   - fsp(ji,jj,jk-1) ) / zdxtmp1
+           !       zdf2    = ( fsp(ji,jj,jk+1) - fsp(ji,jj,jk)   ) / zdxtmp2
+           !
+           !       zalpha = ( zdxtmp1 + 2._wp * zdxtmp2 ) / ( zdxtmp1 + zdxtmp2 ) / 3._wp
+           !
+           !       IF(zdf1 * zdf2 <= 0._wp) THEN
+           !           zdf(jk) = 0._wp
+           !       ELSE
+           !         zdf(jk) = zdf1 * zdf2 / ( ( 1._wp - zalpha ) * zdf1 + zalpha * zdf2 )
+           !       ENDIF
+           !    END DO
+
+           !!Simply geometric average
+               DO jk = 2, jpkm1-1
+                  zdf1 = (fsp(ji,jj,jk  ) - fsp(ji,jj,jk-1)) / (xsp(ji,jj,jk  ) - xsp(ji,jj,jk-1))
+                  zdf2 = (fsp(ji,jj,jk+1) - fsp(ji,jj,jk  )) / (xsp(ji,jj,jk+1) - xsp(ji,jj,jk  ))
+
+                  IF(zdf1 * zdf2 <= 0._wp) THEN
+                     zdf(jk) = 0._wp
+                  ELSE
+                     zdf(jk) = 2._wp * zdf1 * zdf2 / (zdf1 + zdf2)
+                  ENDIF
+               END DO
+
+               zdf(1)     = 1.5_wp * ( fsp(ji,jj,2) - fsp(ji,jj,1) ) / &
+                          &          ( xsp(ji,jj,2) - xsp(ji,jj,1) )           -  0.5_wp * zdf(2)
+               zdf(jpkm1) = 1.5_wp * ( fsp(ji,jj,jpkm1) - fsp(ji,jj,jpkm1-1) ) / &
+                          &          ( xsp(ji,jj,jpkm1) - xsp(ji,jj,jpkm1-1) ) - 0.5_wp * zdf(jpkm1 - 1)
+
+               DO jk = 1, jpkm1 - 1
+                 zdxtmp = xsp(ji,jj,jk+1) - xsp(ji,jj,jk)
+                 ztmp1  = (zdf(jk+1) + 2._wp * zdf(jk)) / zdxtmp
+                 ztmp2  =  6._wp * (fsp(ji,jj,jk+1) - fsp(ji,jj,jk)) / zdxtmp / zdxtmp
+                 zddf1  = -2._wp * ztmp1 + ztmp2
+                 ztmp1  = (2._wp * zdf(jk+1) + zdf(jk)) / zdxtmp
+                 zddf2  =  2._wp * ztmp1 - ztmp2
+
+                 dsp(ji,jj,jk) = (zddf2 - zddf1) / 6._wp / zdxtmp
+                 csp(ji,jj,jk) = ( xsp(ji,jj,jk+1) * zddf1 - xsp(ji,jj,jk)*zddf2 ) / 2._wp / zdxtmp
+                 bsp(ji,jj,jk) = ( fsp(ji,jj,jk+1) - fsp(ji,jj,jk) ) / zdxtmp - &
+                               & csp(ji,jj,jk) * ( xsp(ji,jj,jk+1) + xsp(ji,jj,jk) ) - &
+                               & dsp(ji,jj,jk) * ((xsp(ji,jj,jk+1) + xsp(ji,jj,jk))**2 - &
+                               &                   xsp(ji,jj,jk+1) * xsp(ji,jj,jk))
+                 asp(ji,jj,jk) = fsp(ji,jj,jk) - xsp(ji,jj,jk) * (bsp(ji,jj,jk) + &
+                               &                (xsp(ji,jj,jk) * (csp(ji,jj,jk) + &
+                               &                 dsp(ji,jj,jk) * xsp(ji,jj,jk))))
+               END DO
+            END DO
+         END DO
+
+      ELSEIF ( polynomial_type == 2 ) THEN     ! Linear
+         DO ji = 1, jpi
+            DO jj = 1, jpj
+               DO jk = 1, jpkm1-1
+                  zdxtmp =xsp(ji,jj,jk+1) - xsp(ji,jj,jk)
+                  ztmp1 = fsp(ji,jj,jk+1) - fsp(ji,jj,jk)
+
+                  dsp(ji,jj,jk) = 0._wp
+                  csp(ji,jj,jk) = 0._wp
+                  bsp(ji,jj,jk) = ztmp1 / zdxtmp
+                  asp(ji,jj,jk) = fsp(ji,jj,jk) - bsp(ji,jj,jk) * xsp(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      ELSE
+         CALL ctl_stop( 'invalid polynomial type in cspline' )
+      ENDIF
+      !
+   END SUBROUTINE cspline
+
+
+   FUNCTION interp1(x, xl, xr, fl, fr)  RESULT(f)
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE interp1  ***
+      !!
+      !! ** Purpose :   1-d linear interpolation
+      !!
+      !! ** Method  :   interpolation is straight forward
+      !!                extrapolation is also permitted (no value limit)
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::  x, xl, xr, fl, fr
+      REAL(wp)             ::  f ! result of the interpolation (extrapolation)
+      REAL(wp)             ::  zdeltx
+      !!----------------------------------------------------------------------
+      !
+      zdeltx = xr - xl
+      IF( abs(zdeltx) <= 10._wp * EPSILON(x) ) THEN
+         f = 0.5_wp * (fl + fr)
+      ELSE
+         f = ( (x - xl ) * fr - ( x - xr ) * fl ) / zdeltx
+      ENDIF
+      !
+   END FUNCTION interp1
+
+
+   FUNCTION interp2( x, a, b, c, d )  RESULT(f)
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE interp1  ***
+      !!
+      !! ** Purpose :   1-d constrained cubic spline interpolation
+      !!
+      !! ** Method  :  cubic spline interpolation
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::  x, a, b, c, d
+      REAL(wp)             ::  f ! value from the interpolation
+      !!----------------------------------------------------------------------
+      !
+      f = a + x* ( b + x * ( c + d * x ) )
+      !
+   END FUNCTION interp2
+
+
+   FUNCTION interp3( x, a, b, c, d )  RESULT(f)
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE interp1  ***
+      !!
+      !! ** Purpose :   Calculate the first order of derivative of
+      !!                a cubic spline function y=a+b*x+c*x^2+d*x^3
+      !!
+      !! ** Method  :   f=dy/dx=b+2*c*x+3*d*x^2
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::  x, a, b, c, d
+      REAL(wp)             ::  f ! value from the interpolation
+      !!----------------------------------------------------------------------
+      !
+      f = b + x * ( 2._wp * c + 3._wp * d * x)
+      !
+   END FUNCTION interp3
+
+
+   FUNCTION integ_spline( xl, xr, a, b, c, d )  RESULT(f)
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE interp1  ***
+      !!
+      !! ** Purpose :   1-d constrained cubic spline integration
+      !!
+      !! ** Method  :  integrate polynomial a+bx+cx^2+dx^3 from xl to xr
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::  xl, xr, a, b, c, d
+      REAL(wp)             ::  za1, za2, za3
+      REAL(wp)             ::  f                   ! integration result
+      !!----------------------------------------------------------------------
+      !
+      za1 = 0.5_wp * b
+      za2 = c / 3.0_wp
+      za3 = 0.25_wp * d
+      !
+      f  = xr * ( a + xr * ( za1 + xr * ( za2 + za3 * xr ) ) ) - &
+         & xl * ( a + xl * ( za1 + xl * ( za2 + za3 * xl ) ) )
+      !
+   END FUNCTION integ_spline
+
+   !!======================================================================
+END MODULE dynhpg
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynkeg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynkeg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynkeg.F90	(revision 14097)
@@ -0,0 +1,157 @@
+MODULE dynkeg
+   !!======================================================================
+   !!                       ***  MODULE  dynkeg  ***
+   !! Ocean dynamics:  kinetic energy gradient trend
+   !!======================================================================
+   !! History :  1.0  !  1987-09  (P. Andrich, M.-A. Foujols)  Original code
+   !!            7.0  !  1997-05  (G. Madec)  Split dynber into dynkeg and dynhpg
+   !!  NEMO      1.0  !  2002-07  (G. Madec)  F90: Free form and module
+   !!            3.6  !  2015-05  (N. Ducousso, G. Madec)  add Hollingsworth scheme as an option 
+   !!----------------------------------------------------------------------
+   
+   !!----------------------------------------------------------------------
+   !!   dyn_keg      : update the momentum trend with the horizontal tke
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! MPP library
+   USE prtctl          ! Print control
+   USE timing          ! Timing
+   USE bdy_oce         ! ocean open boundary conditions
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_keg    ! routine called by step module
+   
+   INTEGER, PARAMETER, PUBLIC  ::   nkeg_C2  = 0   !: 2nd order centered scheme (standard scheme)
+   INTEGER, PARAMETER, PUBLIC  ::   nkeg_HW  = 1   !: Hollingsworth et al., QJRMS, 1983
+   !
+   REAL(wp) ::   r1_48 = 1._wp / 48._wp   !: =1/(4*2*6)
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_keg( kt, kscheme )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_keg  ***
+      !!
+      !! ** Purpose :   Compute the now momentum trend due to the horizontal
+      !!      gradient of the horizontal kinetic energy and add it to the 
+      !!      general momentum trend.
+      !!
+      !! ** Method  : * kscheme = nkeg_C2 : 2nd order centered scheme that 
+      !!      conserve kinetic energy. Compute the now horizontal kinetic energy 
+      !!         zhke = 1/2 [ mi-1( un^2 ) + mj-1( vn^2 ) ]
+      !!              * kscheme = nkeg_HW : Hollingsworth correction following
+      !!      Arakawa (2001). The now horizontal kinetic energy is given by:
+      !!         zhke = 1/6 [ mi-1(  2 * un^2 + ((un(j+1)+un(j-1))/2)^2  )
+      !!                    + mj-1(  2 * vn^2 + ((vn(i+1)+vn(i-1))/2)^2  ) ]
+      !!      
+      !!      Take its horizontal gradient and add it to the general momentum
+      !!      trend (ua,va).
+      !!         ua = ua - 1/e1u di[ zhke ]
+      !!         va = va - 1/e2v dj[ zhke ]
+      !!
+      !! ** Action : - Update the (ua, va) with the hor. ke gradient trend
+      !!             - send this trends to trd_dyn (l_trddyn=T) for post-processing
+      !!
+      !! ** References : Arakawa, A., International Geophysics 2001.
+      !!                 Hollingsworth et al., Quart. J. Roy. Meteor. Soc., 1983.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt        ! ocean time-step index
+      INTEGER, INTENT( in ) ::   kscheme   ! =0/1   type of KEG scheme 
+      !
+      INTEGER  ::   ji, jj, jk             ! dummy loop indices
+      REAL(wp) ::   zu, zv                   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        ::   zhke
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdu, ztrdv 
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_keg')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_keg : kinetic energy gradient trend, scheme number=', kscheme
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      IF( l_trddyn ) THEN           ! Save the input trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) )
+         ztrdu(:,:,:) = ua(:,:,:) 
+         ztrdv(:,:,:) = va(:,:,:) 
+      ENDIF
+      
+      zhke(:,:,jpk) = 0._wp
+
+      SELECT CASE ( kscheme )             !== Horizontal kinetic energy at T-point  ==!
+      !
+      CASE ( nkeg_C2 )                          !--  Standard scheme  --!
+         DO jk = 1, jpkm1
+            DO jj = 2, jpj
+               DO ji = fs_2, jpi   ! vector opt.
+                  zu =    un(ji-1,jj  ,jk) * un(ji-1,jj  ,jk)   &
+                     &  + un(ji  ,jj  ,jk) * un(ji  ,jj  ,jk)
+                  zv =    vn(ji  ,jj-1,jk) * vn(ji  ,jj-1,jk)   &
+                     &  + vn(ji  ,jj  ,jk) * vn(ji  ,jj  ,jk)
+                  zhke(ji,jj,jk) = 0.25_wp * ( zv + zu )
+               END DO  
+            END DO
+         END DO
+      CASE ( nkeg_HW )                          !--  Hollingsworth scheme  --!
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1       
+               DO ji = fs_2, jpim1   ! vector opt.
+                  zu = 8._wp * ( un(ji-1,jj  ,jk) * un(ji-1,jj  ,jk)    &
+                     &         + un(ji  ,jj  ,jk) * un(ji  ,jj  ,jk) )  &
+                     &   +     ( un(ji-1,jj-1,jk) + un(ji-1,jj+1,jk) ) * ( un(ji-1,jj-1,jk) + un(ji-1,jj+1,jk) )   &
+                     &   +     ( un(ji  ,jj-1,jk) + un(ji  ,jj+1,jk) ) * ( un(ji  ,jj-1,jk) + un(ji  ,jj+1,jk) )
+                     !
+                  zv = 8._wp * ( vn(ji  ,jj-1,jk) * vn(ji  ,jj-1,jk)    &
+                     &         + vn(ji  ,jj  ,jk) * vn(ji  ,jj  ,jk) )  &
+                     &  +      ( vn(ji-1,jj-1,jk) + vn(ji+1,jj-1,jk) ) * ( vn(ji-1,jj-1,jk) + vn(ji+1,jj-1,jk) )   &
+                     &  +      ( vn(ji-1,jj  ,jk) + vn(ji+1,jj  ,jk) ) * ( vn(ji-1,jj  ,jk) + vn(ji+1,jj  ,jk) )
+                  zhke(ji,jj,jk) = r1_48 * ( zv + zu )
+               END DO  
+            END DO
+         END DO
+         CALL lbc_lnk( 'dynkeg', zhke, 'T', 1. )
+         !
+      END SELECT 
+      !
+      DO jk = 1, jpkm1                    !==  grad( KE ) added to the general momentum trends  ==!
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ua(ji,jj,jk) = ua(ji,jj,jk) - ( zhke(ji+1,jj  ,jk) - zhke(ji,jj,jk) ) / e1u(ji,jj)
+               va(ji,jj,jk) = va(ji,jj,jk) - ( zhke(ji  ,jj+1,jk) - zhke(ji,jj,jk) ) / e2v(ji,jj)
+            END DO 
+         END DO
+      END DO
+      !
+      IF( l_trddyn ) THEN                 ! save the Kinetic Energy trends for diagnostic
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_keg, kt )
+         DEALLOCATE( ztrdu , ztrdv )
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' keg  - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_keg')
+      !
+   END SUBROUTINE dyn_keg
+
+   !!======================================================================
+END MODULE dynkeg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf.F90	(revision 14097)
@@ -0,0 +1,113 @@
+MODULE dynldf
+   !!======================================================================
+   !!                       ***  MODULE  dynldf  ***
+   !! Ocean physics:  lateral diffusivity trends 
+   !!=====================================================================
+   !! History :  2.0  ! 2005-11  (G. Madec)  Original code (new step architecture)
+   !!            3.7  ! 2014-01  (F. Lemarie, G. Madec)  restructuration/simplification of ahm specification,
+   !!                 !                                  add velocity dependent coefficient and optional read in file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_ldf      : update the dynamics trend with the lateral diffusion
+   !!   dyn_ldf_init : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ldfdyn         ! lateral diffusion: eddy viscosity coef.
+   USE dynldf_lap_blp ! lateral mixing   (dyn_ldf_lap & dyn_ldf_blp routines)
+   USE dynldf_iso     ! lateral mixing                 (dyn_ldf_iso routine )
+   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
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_ldf       ! called by step module 
+   PUBLIC   dyn_ldf_init  ! called by opa  module 
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_ldf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_ldf  ***
+      !! 
+      !! ** Purpose :   compute the lateral ocean dynamics physics.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdu, ztrdv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_ldf')
+      !
+      IF( l_trddyn )   THEN                      ! temporary save of momentum trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) )
+         ztrdu(:,:,:) = ua(:,:,:) 
+         ztrdv(:,:,:) = va(:,:,:) 
+      ENDIF
+
+      SELECT CASE ( nldf_dyn )                   ! compute lateral mixing trend and add it to the general trend
+      !
+      CASE ( np_lap   )    ;   CALL dyn_ldf_lap( kt, ub, vb, ua, va, 1 )      ! iso-level    laplacian
+      CASE ( np_lap_i )    ;   CALL dyn_ldf_iso( kt )                         ! rotated      laplacian
+      CASE ( np_blp   )    ;   CALL dyn_ldf_blp( kt, ub, vb, ua, va    )      ! iso-level bi-laplacian
+      !
+      END SELECT
+
+      IF( l_trddyn ) THEN                        ! save the horizontal diffusive trends for further diagnostics
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_ldf, kt )
+         DEALLOCATE ( ztrdu , ztrdv )
+      ENDIF
+      !                                          ! print sum trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' ldf  - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_ldf')
+      !
+   END SUBROUTINE dyn_ldf
+
+
+   SUBROUTINE dyn_ldf_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_ldf_init  ***
+      !! 
+      !! ** Purpose :   initializations of the horizontal ocean dynamics physics
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                     !==  Namelist print  ==!
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_ldf_init : Choice of the lateral diffusive operator on dynamics'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn_ldf: already read in ldfdyn module'
+         WRITE(numout,*) '      see ldf_dyn_init report for lateral mixing parameters'
+         WRITE(numout,*)
+         !
+         SELECT CASE( nldf_dyn )             ! print the choice of operator
+         CASE( np_no_ldf )   ;   WRITE(numout,*) '   ==>>>   NO lateral viscosity'
+         CASE( np_lap    )   ;   WRITE(numout,*) '   ==>>>   iso-level laplacian operator'
+         CASE( np_lap_i  )   ;   WRITE(numout,*) '   ==>>>   rotated laplacian operator with iso-level background'
+         CASE( np_blp    )   ;   WRITE(numout,*) '   ==>>>   iso-level bi-laplacian operator'
+         END SELECT
+      ENDIF
+      !
+   END SUBROUTINE dyn_ldf_init
+
+   !!======================================================================
+END MODULE dynldf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_iso.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_iso.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_iso.F90	(revision 14097)
@@ -0,0 +1,403 @@
+MODULE dynldf_iso
+   !!======================================================================
+   !!                     ***  MODULE  dynldf_iso  ***
+   !! Ocean dynamics:   lateral viscosity trend (rotated laplacian operator)
+   !!======================================================================
+   !! History :  OPA  !  97-07  (G. Madec)  Original code
+   !!  NEMO      1.0  !  2002-08  (G. Madec)  F90: Free form and module
+   !!             -   !  2004-08  (C. Talandier) New trends organization
+   !!            2.0  !  2005-11  (G. Madec)  s-coordinate: horizontal diffusion
+   !!            3.7  !  2014-01  (F. Lemarie, G. Madec)  restructuration/simplification of ahm specification,
+   !!                 !                                   add velocity dependent coefficient and optional read in file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_ldf_iso  : update the momentum trend with the horizontal part
+   !!                  of the lateral diffusion using isopycnal or horizon-
+   !!                  tal s-coordinate laplacian operator.
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE ldfdyn          ! lateral diffusion: eddy viscosity coef.
+   USE ldftra          ! lateral physics: eddy diffusivity
+   USE zdf_oce         ! ocean vertical physics
+   USE ldfslp          ! iso-neutral slopes 
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl          ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_ldf_iso           ! called by step.F90
+   PUBLIC   dyn_ldf_iso_alloc     ! called by nemogcm.F90
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   akzu, akzv   !: vertical component of rotated lateral viscosity
+   
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) :: zfuw, zdiu, zdju, zdj1u   ! 2D workspace (dyn_ldf_iso) 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) :: zfvw, zdiv, zdjv, zdj1v   !  -      -
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dyn_ldf_iso_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_ldf_iso_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( akzu(jpi,jpj,jpk) , zfuw(jpi,jpk) , zdiu(jpi,jpk) , zdju(jpi,jpk) , zdj1u(jpi,jpk) ,     & 
+         &      akzv(jpi,jpj,jpk) , zfvw(jpi,jpk) , zdiv(jpi,jpk) , zdjv(jpi,jpk) , zdj1v(jpi,jpk) , STAT=dyn_ldf_iso_alloc )
+         !
+      IF( dyn_ldf_iso_alloc /= 0 )   CALL ctl_warn('dyn_ldf_iso_alloc: array allocate failed.')
+   END FUNCTION dyn_ldf_iso_alloc
+
+
+   SUBROUTINE dyn_ldf_iso( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dyn_ldf_iso  ***
+      !!                       
+      !! ** Purpose :   Compute the before trend of the rotated laplacian
+      !!      operator of lateral momentum diffusion except the diagonal
+      !!      vertical term that will be computed in dynzdf module. Add it
+      !!      to the general trend of momentum equation.
+      !!
+      !! ** Method :
+      !!        The momentum lateral diffusive trend is provided by a 2nd
+      !!      order operator rotated along neutral or geopotential surfaces
+      !!      (in s-coordinates).
+      !!      It is computed using before fields (forward in time) and isopyc-
+      !!      nal or geopotential slopes computed in routine ldfslp.
+      !!      Here, u and v components are considered as 2 independent scalar
+      !!      fields. Therefore, the property of splitting divergent and rota-
+      !!      tional part of the flow of the standard, z-coordinate laplacian
+      !!      momentum diffusion is lost.
+      !!      horizontal fluxes associated with the rotated lateral mixing:
+      !!      u-component:
+      !!         ziut = ( ahmt + rn_ahm_b ) e2t * e3t / e1t  di[ ub ]
+      !!               -  ahmt              e2t * mi-1(uslp) dk[ mi(mk(ub)) ]
+      !!         zjuf = ( ahmf + rn_ahm_b ) e1f * e3f / e2f  dj[ ub ]
+      !!               -  ahmf              e1f * mi(vslp)   dk[ mj(mk(ub)) ]
+      !!      v-component:
+      !!         zivf = ( ahmf + rn_ahm_b ) e2t * e3t / e1t  di[ vb ]
+      !!               -  ahmf              e2t * mj(uslp)   dk[ mi(mk(vb)) ]
+      !!         zjvt = ( ahmt + rn_ahm_b ) e1f * e3f / e2f  dj[ ub ]
+      !!               -  ahmt              e1f * mj-1(vslp) dk[ mj(mk(vb)) ]
+      !!      take the horizontal divergence of the fluxes:
+      !!         diffu = 1/(e1u*e2u*e3u) {  di  [ ziut ] + dj-1[ zjuf ]  }
+      !!         diffv = 1/(e1v*e2v*e3v) {  di-1[ zivf ] + dj  [ zjvt ]  }
+      !!      Add this trend to the general trend (ua,va):
+      !!         ua = ua + diffu
+      !!      CAUTION: here the isopycnal part is with a coeff. of aht. This
+      !!      should be modified for applications others than orca_r2 (!!bug)
+      !!
+      !! ** Action :
+      !!       -(ua,va) updated with the before geopotential harmonic mixing trend
+      !!       -(akzu,akzv) to accompt for the diagonal vertical component
+      !!                    of the rotated operator in dynzdf module
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zabe1, zmskt, zmkt, zuav, zuwslpi, zuwslpj   ! local scalars
+      REAL(wp) ::   zabe2, zmskf, zmkf, zvav, zvwslpi, zvwslpj   !   -      -
+      REAL(wp) ::   zcof0, zcof1, zcof2, zcof3, zcof4, zaht_0    !   -      -
+      REAL(wp), DIMENSION(jpi,jpj) ::   ziut, zivf, zdku, zdk1u  ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj) ::   zjuf, zjvt, zdkv, zdk1v  !  -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_ldf_iso : iso-neutral laplacian diffusive operator or '
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   s-coordinate horizontal diffusive operator'
+         !                                      ! allocate dyn_ldf_bilap arrays
+         IF( dyn_ldf_iso_alloc() /= 0 )   CALL ctl_stop('STOP', 'dyn_ldf_iso: failed to allocate arrays')
+      ENDIF
+
+!!gm bug is dyn_ldf_iso called before tra_ldf_iso ....   <<<<<===== TO BE CHECKED
+      ! s-coordinate: Iso-level diffusion on momentum but not on tracer
+      IF( ln_dynldf_hor .AND. ln_traldf_iso ) THEN
+         !
+         DO jk = 1, jpk         ! set the slopes of iso-level
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  uslp (ji,jj,jk) = - ( gdept_b(ji+1,jj,jk) - gdept_b(ji ,jj ,jk) ) * r1_e1u(ji,jj) * umask(ji,jj,jk)
+                  vslp (ji,jj,jk) = - ( gdept_b(ji,jj+1,jk) - gdept_b(ji ,jj ,jk) ) * r1_e2v(ji,jj) * vmask(ji,jj,jk)
+                  wslpi(ji,jj,jk) = - ( gdepw_b(ji+1,jj,jk) - gdepw_b(ji-1,jj,jk) ) * r1_e1t(ji,jj) * tmask(ji,jj,jk) * 0.5
+                  wslpj(ji,jj,jk) = - ( gdepw_b(ji,jj+1,jk) - gdepw_b(ji,jj-1,jk) ) * r1_e2t(ji,jj) * tmask(ji,jj,jk) * 0.5
+               END DO
+            END DO
+         END DO
+         ! Lateral boundary conditions on the slopes
+         CALL lbc_lnk_multi( 'dynldf_iso', uslp , 'U', -1., vslp , 'V', -1., wslpi, 'W', -1., wslpj, 'W', -1. )
+         !
+       ENDIF
+         
+      zaht_0 = 0.5_wp * rn_Ud * rn_Ld                  ! aht_0 from namtra_ldf = zaht_max
+      
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+
+         ! Vertical u- and v-shears at level jk and jk+1
+         ! ---------------------------------------------
+         ! surface boundary condition: zdku(jk=1)=zdku(jk=2)
+         !                             zdkv(jk=1)=zdkv(jk=2)
+
+         zdk1u(:,:) = ( ub(:,:,jk) -ub(:,:,jk+1) ) * umask(:,:,jk+1)
+         zdk1v(:,:) = ( vb(:,:,jk) -vb(:,:,jk+1) ) * vmask(:,:,jk+1)
+
+         IF( jk == 1 ) THEN
+            zdku(:,:) = zdk1u(:,:)
+            zdkv(:,:) = zdk1v(:,:)
+         ELSE
+            zdku(:,:) = ( ub(:,:,jk-1) - ub(:,:,jk) ) * umask(:,:,jk)
+            zdkv(:,:) = ( vb(:,:,jk-1) - vb(:,:,jk) ) * vmask(:,:,jk)
+         ENDIF
+
+         !                               -----f-----
+         ! Horizontal fluxes on U             |  
+         ! --------------------===        t   u   t
+         !                                    |  
+         ! i-flux at t-point             -----f-----
+
+         IF( ln_zps ) THEN      ! z-coordinate - partial steps : min(e3u)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, jpi   ! vector opt.
+                  zabe1 = ( ahmt(ji,jj,jk)+rn_ahm_b ) * e2t(ji,jj) * MIN( e3u_n(ji,jj,jk), e3u_n(ji-1,jj,jk) ) * r1_e1t(ji,jj)
+
+                  zmskt = 1._wp / MAX(   umask(ji-1,jj,jk  )+umask(ji,jj,jk+1)     &
+                     &                 + umask(ji-1,jj,jk+1)+umask(ji,jj,jk  ) , 1._wp )
+
+                  zcof1 = - zaht_0 * e2t(ji,jj) * zmskt * 0.5  * ( uslp(ji-1,jj,jk) + uslp(ji,jj,jk) )
+   
+                  ziut(ji,jj) = (  zabe1 * ( ub(ji,jj,jk) - ub(ji-1,jj,jk) )    &
+                     &           + zcof1 * ( zdku (ji,jj) + zdk1u(ji-1,jj)      &
+                     &                      +zdk1u(ji,jj) + zdku (ji-1,jj) )  ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         ELSE                   ! other coordinate system (zco or sco) : e3t
+            DO jj = 2, jpjm1
+               DO ji = fs_2, jpi   ! vector opt.
+                  zabe1 = ( ahmt(ji,jj,jk)+rn_ahm_b ) * e2t(ji,jj) * e3t_n(ji,jj,jk) * r1_e1t(ji,jj)
+
+                  zmskt = 1._wp / MAX(   umask(ji-1,jj,jk  ) + umask(ji,jj,jk+1)     &
+                     &                 + umask(ji-1,jj,jk+1) + umask(ji,jj,jk  ) , 1._wp )
+
+                  zcof1 = - zaht_0 * e2t(ji,jj) * zmskt * 0.5  * ( uslp(ji-1,jj,jk) + uslp(ji,jj,jk) )
+
+                  ziut(ji,jj) = (  zabe1 * ( ub(ji,jj,jk) - ub(ji-1,jj,jk) )   &
+                     &           + zcof1 * ( zdku (ji,jj) + zdk1u(ji-1,jj)     &
+                     &                      +zdk1u(ji,jj) + zdku (ji-1,jj) )  ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+
+         ! j-flux at f-point
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zabe2 = ( ahmf(ji,jj,jk) + rn_ahm_b ) * e1f(ji,jj) * e3f_n(ji,jj,jk) * r1_e2f(ji,jj)
+
+               zmskf = 1._wp / MAX(   umask(ji,jj+1,jk  )+umask(ji,jj,jk+1)     &
+                  &                 + umask(ji,jj+1,jk+1)+umask(ji,jj,jk  ) , 1._wp )
+
+               zcof2 = - zaht_0 * e1f(ji,jj) * zmskf * 0.5  * ( vslp(ji+1,jj,jk) + vslp(ji,jj,jk) )
+
+               zjuf(ji,jj) = (  zabe2 * ( ub(ji,jj+1,jk) - ub(ji,jj,jk) )   &
+                  &           + zcof2 * ( zdku (ji,jj+1) + zdk1u(ji,jj)     &
+                  &                      +zdk1u(ji,jj+1) + zdku (ji,jj) )  ) * fmask(ji,jj,jk)
+            END DO
+         END DO
+
+         !                                |   t   |
+         ! Horizontal fluxes on V         |       |
+         ! --------------------===        f---v---f
+         !                                |       |
+         ! i-flux at f-point              |   t   |
+
+         DO jj = 2, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zabe1 = ( ahmf(ji,jj,jk) + rn_ahm_b ) * e2f(ji,jj) * e3f_n(ji,jj,jk) * r1_e1f(ji,jj)
+
+               zmskf = 1._wp / MAX(  vmask(ji+1,jj,jk  )+vmask(ji,jj,jk+1)     &
+                  &                + vmask(ji+1,jj,jk+1)+vmask(ji,jj,jk  ) , 1._wp )
+
+               zcof1 = - zaht_0 * e2f(ji,jj) * zmskf * 0.5 * ( uslp(ji,jj+1,jk) + uslp(ji,jj,jk) )
+
+               zivf(ji,jj) = (  zabe1 * ( vb(ji+1,jj,jk) - vb(ji,jj,jk) )    &
+                  &           + zcof1 * (  zdkv (ji,jj) + zdk1v(ji+1,jj)      &
+                  &                      + zdk1v(ji,jj) + zdkv (ji+1,jj) )  ) * fmask(ji,jj,jk)
+            END DO
+         END DO
+
+         ! j-flux at t-point
+         IF( ln_zps ) THEN      ! z-coordinate - partial steps : min(e3u)
+            DO jj = 2, jpj
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zabe2 = ( ahmt(ji,jj,jk)+rn_ahm_b ) * e1t(ji,jj) * MIN( e3v_n(ji,jj,jk), e3v_n(ji,jj-1,jk) ) * r1_e2t(ji,jj)
+
+                  zmskt = 1._wp / MAX(  vmask(ji,jj-1,jk  )+vmask(ji,jj,jk+1)     &
+                     &                + vmask(ji,jj-1,jk+1)+vmask(ji,jj,jk  ) , 1._wp )
+
+                  zcof2 = - zaht_0 * e1t(ji,jj) * zmskt * 0.5 * ( vslp(ji,jj-1,jk) + vslp(ji,jj,jk) )
+
+                  zjvt(ji,jj) = (  zabe2 * ( vb(ji,jj,jk) - vb(ji,jj-1,jk) )    &
+                     &           + zcof2 * ( zdkv (ji,jj-1) + zdk1v(ji,jj)      &
+                     &                      +zdk1v(ji,jj-1) + zdkv (ji,jj) )  ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         ELSE                   ! other coordinate system (zco or sco) : e3t
+            DO jj = 2, jpj
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zabe2 = ( ahmt(ji,jj,jk)+rn_ahm_b ) * e1t(ji,jj) * e3t_n(ji,jj,jk) * r1_e2t(ji,jj)
+
+                  zmskt = 1./MAX(  vmask(ji,jj-1,jk  )+vmask(ji,jj,jk+1)   &
+                     &           + vmask(ji,jj-1,jk+1)+vmask(ji,jj,jk  ), 1. )
+
+                  zcof2 = - zaht_0 * e1t(ji,jj) * zmskt * 0.5 * ( vslp(ji,jj-1,jk) + vslp(ji,jj,jk) )
+
+                  zjvt(ji,jj) = (  zabe2 * ( vb(ji,jj,jk) - vb(ji,jj-1,jk) )   &
+                     &           + zcof2 * ( zdkv (ji,jj-1) + zdk1v(ji,jj)     &
+                     &                      +zdk1v(ji,jj-1) + zdkv (ji,jj) )  ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+
+
+         ! Second derivative (divergence) and add to the general trend
+         ! -----------------------------------------------------------
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1          !!gm Question vectop possible??? !!bug
+               ua(ji,jj,jk) = ua(ji,jj,jk) + (  ziut(ji+1,jj) - ziut(ji,jj  )    &
+                  &                           + zjuf(ji  ,jj) - zjuf(ji,jj-1)  ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + (  zivf(ji,jj  ) - zivf(ji-1,jj)    &
+                  &                           + zjvt(ji,jj+1) - zjvt(ji,jj  )  ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+
+      ! print sum trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' ldfh - Ua: ', mask1=umask, &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+
+
+      !                                                ! ===============
+      DO jj = 2, jpjm1                                 !  Vertical slab
+         !                                             ! ===============
+
+ 
+         ! I. vertical trends associated with the lateral mixing
+         ! =====================================================
+         !  (excluding the vertical flux proportional to dk[t]
+
+
+         ! I.1 horizontal momentum gradient
+         ! --------------------------------
+
+         DO jk = 1, jpk
+            DO ji = 2, jpi
+               ! i-gradient of u at jj
+               zdiu (ji,jk) = tmask(ji,jj  ,jk) * ( ub(ji,jj  ,jk) - ub(ji-1,jj  ,jk) )
+               ! j-gradient of u and v at jj
+               zdju (ji,jk) = fmask(ji,jj  ,jk) * ( ub(ji,jj+1,jk) - ub(ji  ,jj  ,jk) )
+               zdjv (ji,jk) = tmask(ji,jj  ,jk) * ( vb(ji,jj  ,jk) - vb(ji  ,jj-1,jk) )
+               ! j-gradient of u and v at jj+1
+               zdj1u(ji,jk) = fmask(ji,jj-1,jk) * ( ub(ji,jj  ,jk) - ub(ji  ,jj-1,jk) )
+               zdj1v(ji,jk) = tmask(ji,jj+1,jk) * ( vb(ji,jj+1,jk) - vb(ji  ,jj  ,jk) )
+            END DO
+         END DO
+         DO jk = 1, jpk
+            DO ji = 1, jpim1
+               ! i-gradient of v at jj
+               zdiv (ji,jk) = fmask(ji,jj  ,jk) * ( vb(ji+1,jj,jk) - vb(ji  ,jj  ,jk) )
+            END DO
+         END DO
+
+
+         ! I.2 Vertical fluxes
+         ! -------------------
+
+         ! Surface and bottom vertical fluxes set to zero
+         DO ji = 1, jpi
+            zfuw(ji, 1 ) = 0.e0
+            zfvw(ji, 1 ) = 0.e0
+            zfuw(ji,jpk) = 0.e0
+            zfvw(ji,jpk) = 0.e0
+         END DO
+
+         ! interior (2=<jk=<jpk-1) on U field
+         DO jk = 2, jpkm1
+            DO ji = 2, jpim1
+               zcof0 = 0.5_wp * zaht_0 * umask(ji,jj,jk)
+               !
+               zuwslpi = zcof0 * ( wslpi(ji+1,jj,jk) + wslpi(ji,jj,jk) )
+               zuwslpj = zcof0 * ( wslpj(ji+1,jj,jk) + wslpj(ji,jj,jk) )
+               !
+               zmkt = 1./MAX(  tmask(ji,jj,jk-1)+tmask(ji+1,jj,jk-1)      &
+                             + tmask(ji,jj,jk  )+tmask(ji+1,jj,jk  ) , 1. )
+               zmkf = 1./MAX(  fmask(ji,jj-1,jk-1) + fmask(ji,jj,jk-1)      &
+                             + fmask(ji,jj-1,jk  ) + fmask(ji,jj,jk  ) , 1. )
+
+               zcof3 = - e2u(ji,jj) * zmkt * zuwslpi
+               zcof4 = - e1u(ji,jj) * zmkf * zuwslpj
+               ! vertical flux on u field
+               zfuw(ji,jk) = zcof3 * (  zdiu (ji,jk-1) + zdiu (ji+1,jk-1)      &
+                  &                   + zdiu (ji,jk  ) + zdiu (ji+1,jk  )  )   &
+                  &        + zcof4 * (  zdj1u(ji,jk-1) + zdju (ji  ,jk-1)      &
+                  &                   + zdj1u(ji,jk  ) + zdju (ji  ,jk  )  )
+               ! vertical mixing coefficient (akzu)
+               ! Note: zcof0 include zaht_0, so divided by zaht_0 to obtain slp^2 * zaht_0
+               akzu(ji,jj,jk) = ( zuwslpi * zuwslpi + zuwslpj * zuwslpj ) / zaht_0
+            END DO
+         END DO
+
+         ! interior (2=<jk=<jpk-1) on V field
+         DO jk = 2, jpkm1
+            DO ji = 2, jpim1
+               zcof0 = 0.5_wp * zaht_0 * vmask(ji,jj,jk)
+               !
+               zvwslpi = zcof0 * ( wslpi(ji,jj+1,jk) + wslpi(ji,jj,jk) )
+               zvwslpj = zcof0 * ( wslpj(ji,jj+1,jk) + wslpj(ji,jj,jk) )
+               !
+               zmkf = 1./MAX(  fmask(ji-1,jj,jk-1)+fmask(ji,jj,jk-1)      &
+                  &          + fmask(ji-1,jj,jk  )+fmask(ji,jj,jk  ) , 1. )
+               zmkt = 1./MAX(  tmask(ji,jj,jk-1)+tmask(ji,jj+1,jk-1)      &
+                  &          + tmask(ji,jj,jk  )+tmask(ji,jj+1,jk  ) , 1. )
+
+               zcof3 = - e2v(ji,jj) * zmkf * zvwslpi
+               zcof4 = - e1v(ji,jj) * zmkt * zvwslpj
+               ! vertical flux on v field
+               zfvw(ji,jk) = zcof3 * (  zdiv (ji,jk-1) + zdiv (ji-1,jk-1)      &
+                  &                   + zdiv (ji,jk  ) + zdiv (ji-1,jk  )  )   &
+                  &        + zcof4 * (  zdjv (ji,jk-1) + zdj1v(ji  ,jk-1)      &
+                  &                   + zdjv (ji,jk  ) + zdj1v(ji  ,jk  )  )
+               ! vertical mixing coefficient (akzv)
+               ! Note: zcof0 include zaht_0, so divided by zaht_0 to obtain slp^2 * zaht_0
+               akzv(ji,jj,jk) = ( zvwslpi * zvwslpi + zvwslpj * zvwslpj ) / zaht_0
+            END DO
+         END DO
+
+
+         ! I.3 Divergence of vertical fluxes added to the general tracer trend
+         ! -------------------------------------------------------------------
+         DO jk = 1, jpkm1
+            DO ji = 2, jpim1
+               ua(ji,jj,jk) = ua(ji,jj,jk) + ( zfuw(ji,jk) - zfuw(ji,jk+1) ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) + ( zfvw(ji,jk) - zfvw(ji,jk+1) ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE dyn_ldf_iso
+
+   !!======================================================================
+END MODULE dynldf_iso
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_lap_blp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_lap_blp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynldf_lap_blp.F90	(revision 14097)
@@ -0,0 +1,142 @@
+MODULE dynldf_lap_blp
+   !!======================================================================
+   !!                   ***  MODULE  dynldf_lap_blp  ***
+   !! Ocean dynamics:  lateral viscosity trend (laplacian and bilaplacian)
+   !!======================================================================
+   !! History : 3.7  ! 2014-01  (G. Madec, S. Masson)  Original code, re-entrant laplacian
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_ldf_lap   : update the momentum trend with the lateral viscosity using an iso-level   laplacian operator
+   !!   dyn_ldf_blp   : update the momentum trend with the lateral viscosity using an iso-level bilaplacian operator
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE ldfdyn         ! lateral diffusion: eddy viscosity coef.
+   USE ldfslp         ! iso-neutral slopes 
+   USE zdf_oce        ! ocean vertical physics
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dyn_ldf_lap  ! called by dynldf.F90
+   PUBLIC dyn_ldf_blp  ! called by dynldf.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_ldf_lap( kt, pub, pvb, pua, pva, kpass )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dyn_ldf_lap  ***
+      !!                       
+      !! ** Purpose :   Compute the before horizontal momentum diffusive 
+      !!      trend and add it to the general trend of momentum equation.
+      !!
+      !! ** Method  :   The Laplacian operator apply on horizontal velocity is 
+      !!      writen as :   grad_h( ahmt div_h(U )) - curl_h( ahmf curl_z(U) ) 
+      !!
+      !! ** Action : - pua, pva increased by the harmonic operator applied on pub, pvb.
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt         ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pub, pvb   ! before velocity  [m/s]
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva   ! velocity trend   [m/s2]
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zsign        ! local scalars
+      REAL(wp) ::   zua, zva     ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zcur, zdiv
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_ldf : iso-level harmonic (laplacian) operator, pass=', kpass
+         WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      IF( kpass == 1 ) THEN   ;   zsign =  1._wp      ! bilaplacian operator require a minus sign
+      ELSE                    ;   zsign = -1._wp      !  (eddy viscosity coef. >0)
+      ENDIF
+      !
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         DO jj = 2, jpj
+            DO ji = fs_2, jpi   ! vector opt.
+               !                                      ! ahm * e3 * curl  (computed from 1 to jpim1/jpjm1)
+               zcur(ji-1,jj-1) = ahmf(ji-1,jj-1,jk) * e3f_n(ji-1,jj-1,jk) * r1_e1e2f(ji-1,jj-1)       &   ! ahmf already * by fmask
+                  &     * (  e2v(ji  ,jj-1) * pvb(ji  ,jj-1,jk) - e2v(ji-1,jj-1) * pvb(ji-1,jj-1,jk)  &
+                  &        - e1u(ji-1,jj  ) * pub(ji-1,jj  ,jk) + e1u(ji-1,jj-1) * pub(ji-1,jj-1,jk)  )
+               !                                      ! ahm * div        (computed from 2 to jpi/jpj)
+               zdiv(ji,jj)     = ahmt(ji,jj,jk) * r1_e1e2t(ji,jj) / e3t_b(ji,jj,jk)                   &   ! ahmt already * by tmask
+                  &     * (  e2u(ji,jj)*e3u_b(ji,jj,jk) * pub(ji,jj,jk) - e2u(ji-1,jj)*e3u_b(ji-1,jj,jk) * pub(ji-1,jj,jk)  &
+                  &        + e1v(ji,jj)*e3v_b(ji,jj,jk) * pvb(ji,jj,jk) - e1v(ji,jj-1)*e3v_b(ji,jj-1,jk) * pvb(ji,jj-1,jk)  )
+            END DO  
+         END DO  
+         !
+         DO jj = 2, jpjm1                             ! - curl( curl) + grad( div )
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               pua(ji,jj,jk) = pua(ji,jj,jk) + zsign * umask(ji,jj,jk) * (       &    ! * by umask is mandatory for dyn_ldf_blp use
+                  &              - ( zcur(ji  ,jj) - zcur(ji,jj-1) ) * r1_e2u(ji,jj) / e3u_n(ji,jj,jk)   &
+                  &              + ( zdiv(ji+1,jj) - zdiv(ji,jj  ) ) * r1_e1u(ji,jj)                     )
+                  !
+               pva(ji,jj,jk) = pva(ji,jj,jk) + zsign * vmask(ji,jj,jk) * (       &    ! * by vmask is mandatory for dyn_ldf_blp use
+                  &                ( zcur(ji,jj  ) - zcur(ji-1,jj) ) * r1_e1v(ji,jj) / e3v_n(ji,jj,jk)   &
+                  &              + ( zdiv(ji,jj+1) - zdiv(ji  ,jj) ) * r1_e2v(ji,jj)                     )
+            END DO
+         END DO
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+      !
+   END SUBROUTINE dyn_ldf_lap
+
+
+   SUBROUTINE dyn_ldf_blp( kt, pub, pvb, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE dyn_ldf_blp  ***
+      !!                    
+      !! ** Purpose :   Compute the before lateral momentum viscous trend 
+      !!              and add it to the general trend of momentum equation.
+      !!
+      !! ** Method  :   The lateral viscous trends is provided by a bilaplacian
+      !!      operator applied to before field (forward in time).
+      !!      It is computed by two successive calls to dyn_ldf_lap routine
+      !!
+      !! ** Action :   pta   updated with the before rotated bilaplacian diffusion
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt         ! ocean time-step index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pub, pvb   ! before velocity fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva   ! momentum trend
+      !
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zulap, zvlap   ! laplacian at u- and v-point
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_ldf_blp : bilaplacian operator momentum '
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      zulap(:,:,:) = 0._wp
+      zvlap(:,:,:) = 0._wp
+      !
+      CALL dyn_ldf_lap( kt, pub, pvb, zulap, zvlap, 1 )   ! rotated laplacian applied to ptb (output in zlap)
+      !
+      CALL lbc_lnk_multi( 'dynldf_lap_blp', zulap, 'U', -1., zvlap, 'V', -1. )             ! Lateral boundary conditions
+      !
+      CALL dyn_ldf_lap( kt, zulap, zvlap, pua, pva, 2 )   ! rotated laplacian applied to zlap (output in pta)
+      !
+   END SUBROUTINE dyn_ldf_blp
+
+   !!======================================================================
+END MODULE dynldf_lap_blp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynnxt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynnxt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynnxt.F90	(revision 14097)
@@ -0,0 +1,404 @@
+MODULE dynnxt
+   !!=========================================================================
+   !!                       ***  MODULE  dynnxt  ***
+   !! Ocean dynamics: time stepping
+   !!=========================================================================
+   !! History :  OPA  !  1987-02  (P. Andrich, D. L Hostis)  Original code
+   !!                 !  1990-10  (C. Levy, G. Madec)
+   !!            7.0  !  1993-03  (M. Guyon)  symetrical conditions
+   !!            8.0  !  1997-02  (G. Madec & M. Imbard)  opa, release 8.0
+   !!            8.2  !  1997-04  (A. Weaver)  Euler forward step
+   !!             -   !  1997-06  (G. Madec)  lateral boudary cond., lbc routine
+   !!    NEMO    1.0  !  2002-08  (G. Madec)  F90: Free form and module
+   !!             -   !  2002-10  (C. Talandier, A-M. Treguier) Open boundary cond.
+   !!            2.0  !  2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            2.3  !  2007-07  (D. Storkey) Calls to BDY routines. 
+   !!            3.2  !  2009-06  (G. Madec, R.Benshila)  re-introduce the vvl option
+   !!            3.3  !  2010-09  (D. Storkey, E.O'Dea) Bug fix for BDY module
+   !!            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.6  !  2014-04  (G. Madec) add the diagnostic of the time filter trends
+   !!            3.7  !  2015-11  (J. Chanut) Free surface simplification
+   !!-------------------------------------------------------------------------
+  
+   !!-------------------------------------------------------------------------
+   !!   dyn_nxt       : obtain the next (after) horizontal velocity
+   !!-------------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbcrnf         ! river runoffs
+   USE sbcisf         ! ice shelf
+   USE phycst         ! physical constants
+   USE dynadv         ! dynamics: vector invariant versus flux form
+   USE dynspg_ts      ! surface pressure gradient: split-explicit scheme
+   USE domvvl         ! variable volume
+   USE bdy_oce , ONLY : ln_bdy
+   USE bdydta         ! ocean open boundary conditions
+   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 prtctl         ! Print control
+   USE timing         ! Timing
+   USE zdfdrg ,  ONLY : ln_drgice_imp, rCdU_top
+#if defined key_agrif
+   USE agrif_oce_interp
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC    dyn_nxt   ! routine called by step.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_nxt ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_nxt  ***
+      !!                   
+      !! ** Purpose :   Finalize after horizontal velocity. Apply the boundary 
+      !!             condition on the after velocity, achieve the time stepping 
+      !!             by applying the Asselin filter on now fields and swapping 
+      !!             the fields.
+      !!
+      !! ** Method  : * Ensure after velocities transport matches time splitting
+      !!             estimate (ln_dynspg_ts=T)
+      !!
+      !!              * Apply lateral boundary conditions on after velocity 
+      !!             at the local domain boundaries through lbc_lnk call,
+      !!             at the one-way open boundaries (ln_bdy=T),
+      !!             at the AGRIF zoom   boundaries (lk_agrif=T)
+      !!
+      !!              * Apply the time filter applied and swap of the dynamics
+      !!             arrays to start the next time step:
+      !!                (ub,vb) = (un,vn) + atfp [ (ub,vb) + (ua,va) - 2 (un,vn) ]
+      !!                (un,vn) = (ua,va).
+      !!             Note that with flux form advection and non linear free surface,
+      !!             the time filter is applied on thickness weighted velocity.
+      !!             As a result, dyn_nxt MUST be called after tra_nxt.
+      !!
+      !! ** Action :   ub,vb   filtered before horizontal velocity of next time-step
+      !!               un,vn   now horizontal velocity of next time-step
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ikt          ! local integers
+      REAL(wp) ::   zue3a, zue3n, zue3b, zuf, zcoef    ! local scalars
+      REAL(wp) ::   zve3a, zve3n, zve3b, zvf, z1_2dt   !   -      -
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   zue, zve
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   zutau, zvtau
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ze3u_f, ze3v_f, zua, zva 
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing    )   CALL timing_start('dyn_nxt')
+      IF( ln_dynspg_ts )   ALLOCATE( zue(jpi,jpj)     , zve(jpi,jpj)     )
+      IF( l_trddyn     )   ALLOCATE( zua(jpi,jpj,jpk) , zva(jpi,jpj,jpk) )
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_nxt : time stepping'
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      IF ( ln_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
+         zue(:,:) = e3u_a(:,:,1) * ua(:,:,1) * umask(:,:,1)
+         zve(:,:) = e3v_a(:,:,1) * va(:,:,1) * vmask(:,:,1)
+         DO jk = 2, jpkm1
+            zue(:,:) = zue(:,:) + e3u_a(:,:,jk) * ua(:,:,jk) * umask(:,:,jk)
+            zve(:,:) = zve(:,:) + e3v_a(:,:,jk) * va(:,:,jk) * vmask(:,:,jk)
+         END DO
+         DO jk = 1, jpkm1
+            ua(:,:,jk) = ( ua(:,:,jk) - zue(:,:) * r1_hu_a(:,:) + ua_b(:,:) ) * umask(:,:,jk)
+            va(:,:,jk) = ( va(:,:,jk) - zve(:,:) * r1_hv_a(:,:) + va_b(:,:) ) * vmask(:,:,jk)
+         END DO
+         !
+         IF( .NOT.ln_bt_fw ) THEN
+            ! Remove advective velocity from "now velocities" 
+            ! prior to asselin filtering     
+            ! In the forward case, this is done below after asselin filtering   
+            ! so that asselin contribution is removed at the same time 
+            DO jk = 1, jpkm1
+               un(:,:,jk) = ( un(:,:,jk) - un_adv(:,:)*r1_hu_n(:,:) + un_b(:,:) )*umask(:,:,jk)
+               vn(:,:,jk) = ( vn(:,:,jk) - vn_adv(:,:)*r1_hv_n(:,:) + vn_b(:,:) )*vmask(:,:,jk)
+            END DO  
+         ENDIF
+      ENDIF
+
+      ! Update after velocity on domain lateral boundaries
+      ! --------------------------------------------------      
+# if defined key_agrif
+      CALL Agrif_dyn( kt )             !* AGRIF zoom boundaries
+# endif
+      !
+      CALL lbc_lnk_multi( 'dynnxt', ua, 'U', -1., va, 'V', -1. )     !* local domain boundaries
+      !
+      !                                !* BDY open boundaries
+      IF( ln_bdy .AND. ln_dynspg_exp )   CALL bdy_dyn( kt )
+      IF( ln_bdy .AND. ln_dynspg_ts  )   CALL bdy_dyn( kt, dyn3d_only=.true. )
+
+!!$   Do we need a call to bdy_vol here??
+      !
+      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
+      ! ------------------------------------------
+      IF( neuler == 0 .AND. kt == nit000 ) THEN        !* Euler at first time-step: only swap
+         DO jk = 1, jpkm1
+            ub(:,:,jk) = un(:,:,jk)                         ! ub <-- un
+            vb(:,:,jk) = vn(:,:,jk)
+            un(:,:,jk) = ua(:,:,jk)                         ! un <-- ua
+            vn(:,:,jk) = va(:,:,jk)
+         END DO
+         IF( .NOT.ln_linssh ) THEN                          ! e3._b <-- e3._n
+!!gm BUG ????    I don't understand why it is not : e3._n <-- e3._a  
+            DO jk = 1, jpkm1
+!               e3t_b(:,:,jk) = e3t_n(:,:,jk)
+!               e3u_b(:,:,jk) = e3u_n(:,:,jk)
+!               e3v_b(:,:,jk) = e3v_n(:,:,jk)
+               !
+               e3t_n(:,:,jk) = e3t_a(:,:,jk)
+               e3u_n(:,:,jk) = e3u_a(:,:,jk)
+               e3v_n(:,:,jk) = e3v_a(:,:,jk)
+            END DO
+!!gm BUG end
+         ENDIF
+                                                            ! 
+         
+      ELSE                                             !* Leap-Frog : Asselin filter and swap
+         !                                ! =============!
+         IF( ln_linssh ) THEN             ! Fixed volume !
+            !                             ! =============!
+            DO jk = 1, jpkm1                              
+               DO jj = 1, jpj
+                  DO ji = 1, jpi    
+                     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
+                     vb(ji,jj,jk) = zvf
+                     un(ji,jj,jk) = ua(ji,jj,jk)             ! un <-- ua
+                     vn(ji,jj,jk) = va(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !                             ! ================!
+         ELSE                             ! Variable volume !
+            !                             ! ================!
+            ! Before scale factor at t-points
+            ! (used as a now filtered scale factor until the swap)
+            ! ----------------------------------------------------
+            DO jk = 1, jpkm1
+               e3t_b(:,:,jk) = e3t_n(:,:,jk) + atfp * ( e3t_b(:,:,jk) - 2._wp * e3t_n(:,:,jk) + e3t_a(:,:,jk) )
+            END DO
+            ! Add volume filter correction: compatibility with tracer advection scheme
+            ! => time filter + conservation correction (only at the first level)
+            zcoef = atfp * rdt * r1_rau0
+
+            DO jk = 1, jpkm1
+               e3t_b(:,:,jk) = e3t_b(:,:,jk) - zcoef * ( emp_b(:,:) - emp(:,:) ) * tmask(:,:,jk) & 
+                             &                       * e3t_n(:,:,jk) /  ( ht_n(:,:) + 1._wp - ssmask(:,:) )
+            END DO
+
+            IF ( ln_rnf ) THEN
+               DO jk = 1, jpkm1
+                  e3t_b(:,:,jk) = e3t_b(:,:,jk) + zcoef * ( rnf_b(:,:) - rnf(:,:) ) * tmask(:,:,jk) & 
+                                &                       * e3t_n(:,:,jk) /  ( ht_n(:,:) + 1._wp - ssmask(:,:) )
+               END DO
+            ENDIF
+
+            IF ( ln_isf ) THEN
+               DO jk = 1, jpkm1
+                  e3t_b(:,:,jk) = e3t_b(:,:,jk) - zcoef * ( fwfisf_b(:,:) - fwfisf(:,:) ) * tmask(:,:,jk) & 
+                                &                       * e3t_n(:,:,jk) /  ( ht_n(:,:) + 1._wp - ssmask(:,:) )
+               END DO
+            ENDIF
+            !
+            IF( ln_dynadv_vec ) THEN      ! Asselin filter applied on velocity
+               ! Before filtered scale factor at (u/v)-points
+               CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )
+               CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )
+               DO jk = 1, jpkm1
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        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
+                        vb(ji,jj,jk) = zvf
+                        un(ji,jj,jk) = ua(ji,jj,jk)             ! un <-- ua
+                        vn(ji,jj,jk) = va(ji,jj,jk)
+                     END DO
+                  END DO
+               END DO
+               !
+            ELSE                          ! Asselin filter applied on thickness weighted velocity
+               !
+               ALLOCATE( ze3u_f(jpi,jpj,jpk) , ze3v_f(jpi,jpj,jpk) )
+               ! Before filtered scale factor at (u/v)-points stored in ze3u_f, ze3v_f
+               CALL dom_vvl_interpol( e3t_b(:,:,:), ze3u_f, 'U' )
+               CALL dom_vvl_interpol( e3t_b(:,:,:), ze3v_f, 'V' )
+               DO jk = 1, jpkm1
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi                  
+                        zue3a = e3u_a(ji,jj,jk) * ua(ji,jj,jk)
+                        zve3a = e3v_a(ji,jj,jk) * va(ji,jj,jk)
+                        zue3n = e3u_n(ji,jj,jk) * un(ji,jj,jk)
+                        zve3n = e3v_n(ji,jj,jk) * vn(ji,jj,jk)
+                        zue3b = e3u_b(ji,jj,jk) * ub(ji,jj,jk)
+                        zve3b = e3v_b(ji,jj,jk) * vb(ji,jj,jk)
+                        !
+                        zuf = ( zue3n + atfp * ( zue3b - 2._wp * zue3n  + zue3a ) ) / ze3u_f(ji,jj,jk)
+                        zvf = ( zve3n + atfp * ( zve3b - 2._wp * zve3n  + zve3a ) ) / ze3v_f(ji,jj,jk)
+                        !
+                        ub(ji,jj,jk) = zuf                     ! ub <-- filtered velocity
+                        vb(ji,jj,jk) = zvf
+                        un(ji,jj,jk) = ua(ji,jj,jk)            ! un <-- ua
+                        vn(ji,jj,jk) = va(ji,jj,jk)
+                     END DO
+                  END DO
+               END DO
+               e3u_b(:,:,1:jpkm1) = ze3u_f(:,:,1:jpkm1)        ! e3u_b <-- filtered scale factor
+               e3v_b(:,:,1:jpkm1) = ze3v_f(:,:,1:jpkm1)
+               !
+               DEALLOCATE( ze3u_f , ze3v_f )
+            ENDIF
+            !
+         ENDIF
+         !
+         IF( ln_dynspg_ts .AND. ln_bt_fw ) THEN
+            ! Revert "before" velocities to time split estimate
+            ! Doing it here also means that asselin filter contribution is removed  
+            zue(:,:) = e3u_b(:,:,1) * ub(:,:,1) * umask(:,:,1)
+            zve(:,:) = e3v_b(:,:,1) * vb(:,:,1) * vmask(:,:,1)    
+            DO jk = 2, jpkm1
+               zue(:,:) = zue(:,:) + e3u_b(:,:,jk) * ub(:,:,jk) * umask(:,:,jk)
+               zve(:,:) = zve(:,:) + e3v_b(:,:,jk) * vb(:,:,jk) * vmask(:,:,jk)    
+            END DO
+            DO jk = 1, jpkm1
+               ub(:,:,jk) = ub(:,:,jk) - (zue(:,:) * r1_hu_n(:,:) - un_b(:,:)) * umask(:,:,jk)
+               vb(:,:,jk) = vb(:,:,jk) - (zve(:,:) * r1_hv_n(:,:) - vn_b(:,:)) * vmask(:,:,jk)
+            END DO
+         ENDIF
+         !
+      ENDIF ! neuler =/0
+      !
+      ! Set "now" and "before" barotropic velocities for next time step:
+      ! JC: Would be more clever to swap variables than to make a full vertical
+      ! integration
+      !
+      !
+      IF(.NOT.ln_linssh ) THEN
+         hu_b(:,:) = e3u_b(:,:,1) * umask(:,:,1)
+         hv_b(:,:) = e3v_b(:,:,1) * vmask(:,:,1)
+         DO jk = 2, jpkm1
+            hu_b(:,:) = hu_b(:,:) + e3u_b(:,:,jk) * umask(:,:,jk)
+            hv_b(:,:) = hv_b(:,:) + e3v_b(:,:,jk) * vmask(:,:,jk)
+         END DO
+         r1_hu_b(:,:) = ssumask(:,:) / ( hu_b(:,:) + 1._wp - ssumask(:,:) )
+         r1_hv_b(:,:) = ssvmask(:,:) / ( hv_b(:,:) + 1._wp - ssvmask(:,:) )
+      ENDIF
+      !
+      un_b(:,:) = e3u_a(:,:,1) * un(:,:,1) * umask(:,:,1)
+      ub_b(:,:) = e3u_b(:,:,1) * ub(:,:,1) * umask(:,:,1)
+      vn_b(:,:) = e3v_a(:,:,1) * vn(:,:,1) * vmask(:,:,1)
+      vb_b(:,:) = e3v_b(:,:,1) * vb(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         un_b(:,:) = un_b(:,:) + e3u_a(:,:,jk) * un(:,:,jk) * umask(:,:,jk)
+         ub_b(:,:) = ub_b(:,:) + e3u_b(:,:,jk) * ub(:,:,jk) * umask(:,:,jk)
+         vn_b(:,:) = vn_b(:,:) + e3v_a(:,:,jk) * vn(:,:,jk) * vmask(:,:,jk)
+         vb_b(:,:) = vb_b(:,:) + e3v_b(:,:,jk) * vb(:,:,jk) * vmask(:,:,jk)
+      END DO
+      un_b(:,:) = un_b(:,:) * r1_hu_a(:,:)
+      vn_b(:,:) = vn_b(:,:) * r1_hv_a(:,:)
+      ub_b(:,:) = ub_b(:,:) * r1_hu_b(:,:)
+      vb_b(:,:) = vb_b(:,:) * r1_hv_b(:,:)
+      !
+      IF( .NOT.ln_dynspg_ts ) THEN        ! output the barotropic currents
+         CALL iom_put(  "ubar", un_b(:,:) )
+         CALL iom_put(  "vbar", vn_b(:,:) )
+      ENDIF
+      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 ( iom_use("utau") ) THEN
+         IF ( ln_drgice_imp.OR.ln_isfcav ) THEN
+            ALLOCATE(zutau(jpi,jpj)) 
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  jk = miku(ji,jj) 
+                  zutau(ji,jj) = utau(ji,jj) & 
+                  &  + 0.5_wp * rau0 * (rCdU_top(ji+1,jj)+rCdU_top(ji,jj)) * ua(ji,jj,jk) 
+               END DO
+            END DO
+            CALL lbc_lnk( 'dynnxt' , zutau, 'U', -1.)
+            CALL iom_put(  "utau", zutau(:,:) )
+            DEALLOCATE(zutau)
+         ELSE
+            CALL iom_put(  "utau", utau(:,:) )
+         ENDIF
+      ENDIF
+      !
+      IF ( iom_use("vtau") ) THEN
+         IF ( ln_drgice_imp.OR.ln_isfcav ) THEN
+            ALLOCATE(zvtau(jpi,jpj))
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  jk = mikv(ji,jj)
+                  zvtau(ji,jj) = vtau(ji,jj) &
+                  &  + 0.5_wp * rau0 * (rCdU_top(ji,jj+1)+rCdU_top(ji,jj)) * va(ji,jj,jk)
+               END DO
+            END DO
+            CALL lbc_lnk( 'dynnxt' , zvtau, 'V', -1.)
+            CALL iom_put(  "vtau", zvtau(:,:) )
+            DEALLOCATE(zvtau)
+         ELSE
+            CALL iom_put(  "vtau", vtau(:,:) )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=un, clinfo1=' nxt  - Un: ', mask1=umask,   &
+         &                       tab3d_2=vn, clinfo2=' Vn: '       , mask2=vmask )
+      ! 
+      IF( ln_dynspg_ts )   DEALLOCATE( zue, zve )
+      IF( l_trddyn     )   DEALLOCATE( zua, zva )
+      IF( ln_timing    )   CALL timing_stop('dyn_nxt')
+      !
+   END SUBROUTINE dyn_nxt
+
+   !!=========================================================================
+END MODULE dynnxt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg.F90	(revision 14097)
@@ -0,0 +1,240 @@
+MODULE dynspg
+   !!======================================================================
+   !!                       ***  MODULE  dynspg  ***
+   !! Ocean dynamics:  surface pressure gradient control
+   !!======================================================================
+   !! History :  1.0  ! 2005-12  (C. Talandier, G. Madec, V. Garnier)  Original code
+   !!            3.2  ! 2009-07  (R. Benshila)  Suppression of rigid-lid option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_spg     : update the dynamics trend with surface pressure gradient 
+   !!   dyn_spg_init: initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE c1d            ! 1D vertical configuration
+   USE phycst         ! physical constants
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE sbc_ice , ONLY : snwice_mass, snwice_mass_b
+   USE sbcapr         ! surface boundary condition: atmospheric pressure
+   USE dynspg_exp     ! surface pressure gradient     (dyn_spg_exp routine)
+   USE dynspg_ts      ! surface pressure gradient     (dyn_spg_ts  routine)
+   USE sbctide        ! 
+   USE updtide        ! 
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_spg        ! routine called by step module
+   PUBLIC   dyn_spg_init   ! routine called by opa module
+
+   INTEGER ::   nspg = 0   ! type of surface pressure gradient scheme defined from lk_dynspg_... 
+
+   !                       ! Parameter to control the surface pressure gradient scheme
+   INTEGER, PARAMETER ::   np_TS  = 1   ! split-explicit time stepping (Time-Splitting)
+   INTEGER, PARAMETER ::   np_EXP = 0   !       explicit time stepping
+   INTEGER, PARAMETER ::   np_NO  =-1   ! no surface pressure gradient, no scheme
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_spg( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_spg  ***
+      !!
+      !! ** Purpose :   compute surface pressure gradient including the 
+      !!              atmospheric pressure forcing (ln_apr_dyn=T).
+      !!
+      !! ** Method  :   Two schemes:
+      !!              - explicit       : the spg is evaluated at now
+      !!              - split-explicit : a time splitting technique is used
+      !!
+      !!              ln_apr_dyn=T : the atmospheric pressure forcing is applied 
+      !!             as the gradient of the inverse barometer ssh:
+      !!                apgu = - 1/rau0 di[apr] = 0.5*grav di[ssh_ib+ssh_ibb]
+      !!                apgv = - 1/rau0 dj[apr] = 0.5*grav dj[ssh_ib+ssh_ibb]
+      !!             Note that as all external forcing a time averaging over a two rdt
+      !!             period is used to prevent the divergence of odd and even time step.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk                   ! dummy loop indices
+      REAL(wp) ::   z2dt, zg_2, zintp, zgrau0r, zld   ! local scalars
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   zpice
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdu, ztrdv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_spg')
+      !
+      IF( l_trddyn )   THEN                      ! temporary save of ta and sa trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) ) 
+         ztrdu(:,:,:) = ua(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:)
+      ENDIF
+      !
+      IF(      ln_apr_dyn                                                &   ! atmos. pressure
+         .OR.  ( .NOT.ln_dynspg_ts .AND. (ln_tide_pot .AND. ln_tide) )   &   ! tide potential (no time slitting)
+         .OR.  ln_ice_embd ) THEN                                            ! embedded sea-ice
+         !
+         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         
+         !
+         IF( ln_apr_dyn .AND. .NOT.ln_dynspg_ts ) THEN   !==  Atmospheric pressure gradient (added later in time-split case) ==!
+            zg_2 = grav * 0.5
+            DO jj = 2, jpjm1                          ! gradient of Patm using inverse barometer ssh
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  spgu(ji,jj) = spgu(ji,jj) + zg_2 * (  ssh_ib (ji+1,jj) - ssh_ib (ji,jj)    &
+                     &                                + ssh_ibb(ji+1,jj) - ssh_ibb(ji,jj)  ) * r1_e1u(ji,jj)
+                  spgv(ji,jj) = spgv(ji,jj) + zg_2 * (  ssh_ib (ji,jj+1) - ssh_ib (ji,jj)    &
+                     &                                + ssh_ibb(ji,jj+1) - ssh_ibb(ji,jj)  ) * r1_e2v(ji,jj)
+               END DO
+            END DO
+         ENDIF
+         !
+         !                                    !==  tide potential forcing term  ==!
+         IF( .NOT.ln_dynspg_ts .AND. ( ln_tide_pot .AND. ln_tide )  ) THEN   ! N.B. added directly at sub-time-step in ts-case
+            !
+            CALL upd_tide( kt )                      ! update tide potential
+            !
+            DO jj = 2, jpjm1                         ! add tide potential forcing
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  spgu(ji,jj) = spgu(ji,jj) + grav * ( pot_astro(ji+1,jj) - pot_astro(ji,jj) ) * r1_e1u(ji,jj)
+                  spgv(ji,jj) = spgv(ji,jj) + grav * ( pot_astro(ji,jj+1) - pot_astro(ji,jj) ) * r1_e2v(ji,jj)
+               END DO 
+            END DO
+            !
+            IF (ln_scal_load) THEN
+               zld = rn_scal_load * grav
+               DO jj = 2, jpjm1                    ! add scalar approximation for load potential
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     spgu(ji,jj) = spgu(ji,jj) + zld * ( sshn(ji+1,jj) - sshn(ji,jj) ) * r1_e1u(ji,jj)
+                     spgv(ji,jj) = spgv(ji,jj) + zld * ( sshn(ji,jj+1) - sshn(ji,jj) ) * r1_e2v(ji,jj)
+                  END DO 
+               END DO
+            ENDIF
+         ENDIF
+         !
+         IF( ln_ice_embd ) THEN              !== embedded sea ice: Pressure gradient due to snow-ice mass ==!
+            ALLOCATE( zpice(jpi,jpj) )
+            zintp = REAL( MOD( kt-1, nn_fsbc ) ) / REAL( nn_fsbc )
+            zgrau0r     = - grav * r1_rau0
+            zpice(:,:) = (  zintp * snwice_mass(:,:) + ( 1.- zintp ) * snwice_mass_b(:,:)  ) * zgrau0r
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  spgu(ji,jj) = spgu(ji,jj) + ( zpice(ji+1,jj) - zpice(ji,jj) ) * r1_e1u(ji,jj)
+                  spgv(ji,jj) = spgv(ji,jj) + ( zpice(ji,jj+1) - zpice(ji,jj) ) * r1_e2v(ji,jj)
+               END DO
+            END DO
+            DEALLOCATE( zpice )         
+         ENDIF
+         !
+         DO jk = 1, jpkm1                    !== Add all terms to the general trend
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + spgu(ji,jj)
+                  va(ji,jj,jk) = va(ji,jj,jk) + spgv(ji,jj)
+               END DO
+            END DO
+         END DO    
+         !
+!!gm add here a call to dyn_trd for ice pressure gradient, the surf pressure trends ????
+         !    
+      ENDIF
+      !
+      SELECT CASE ( nspg )                   !== surface pressure gradient computed and add to the general trend ==!
+      CASE ( np_EXP )   ;   CALL dyn_spg_exp( kt )              ! explicit
+      CASE ( np_TS  )   ;   CALL dyn_spg_ts ( kt )              ! time-splitting
+      END SELECT
+      !                    
+      IF( l_trddyn )   THEN                  ! save the surface pressure gradient trends for further diagnostics
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_spg, kt )
+         DEALLOCATE( ztrdu , ztrdv ) 
+      ENDIF
+      !                                      ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' spg  - Ua: ', mask1=umask, &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_spg')
+      !
+   END SUBROUTINE dyn_spg
+
+
+   SUBROUTINE dyn_spg_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_spg_init  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options for 
+      !!              surface pressure gradient schemes
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios   ! local integers
+      !
+      NAMELIST/namdyn_spg/ ln_dynspg_exp       , ln_dynspg_ts,   &
+      &                    ln_bt_fw, ln_bt_av  , ln_bt_auto  ,   &
+      &                    nn_baro , rn_bt_cmax, nn_bt_flt, rn_bt_alpha
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_spg_init : choice of the surface pressure gradient scheme'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnam_ref )              ! Namelist namdyn_spg in reference namelist : Free surface
+      READ  ( numnam_ref, namdyn_spg, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_spg in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namdyn_spg in configuration namelist : Free surface
+      READ  ( numnam_cfg, namdyn_spg, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_spg in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdyn_spg )
+      !
+      IF(lwp) THEN             ! Namelist print
+         WRITE(numout,*) '   Namelist : namdyn_spg                    '
+         WRITE(numout,*) '      Explicit free surface                  ln_dynspg_exp = ', ln_dynspg_exp
+         WRITE(numout,*) '      Free surface with time splitting       ln_dynspg_ts  = ', ln_dynspg_ts
+      ENDIF
+      !                          ! Control of surface pressure gradient scheme options
+                                     nspg =  np_NO    ;   ioptio = 0
+      IF( ln_dynspg_exp ) THEN   ;   nspg =  np_EXP   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_dynspg_ts  ) THEN   ;   nspg =  np_TS    ;   ioptio = ioptio + 1   ;   ENDIF
+      !
+      IF( ioptio  > 1 )   CALL ctl_stop( 'Choose only one surface pressure gradient scheme' )
+      IF( ioptio == 0 )   CALL ctl_warn( 'NO surface pressure gradient trend in momentum Eqs.' )
+      IF( ln_dynspg_exp .AND. ln_isfcav )   &
+           &   CALL ctl_stop( ' dynspg_exp not tested with ice shelf cavity ' )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         IF( nspg == np_EXP )   WRITE(numout,*) '   ==>>>   explicit free surface'
+         IF( nspg == np_TS  )   WRITE(numout,*) '   ==>>>   free surface with time splitting scheme'
+         IF( nspg == np_NO  )   WRITE(numout,*) '   ==>>>   No surface surface pressure gradient trend in momentum Eqs.'
+      ENDIF
+      !
+      IF( nspg == np_TS ) THEN   ! split-explicit scheme initialisation
+         CALL dyn_spg_ts_init          ! do it first: set nn_baro used to allocate some arrays later on
+      ENDIF
+      !
+   END SUBROUTINE dyn_spg_init
+
+  !!======================================================================
+END MODULE dynspg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_exp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_exp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_exp.F90	(revision 14097)
@@ -0,0 +1,95 @@
+MODULE dynspg_exp
+   !!======================================================================
+   !!                   ***  MODULE  dynspg_exp  ***
+   !! Ocean dynamics:  surface pressure gradient trend, explicit scheme
+   !!======================================================================
+   !! History :  2.0  !  2005-11  (V. Garnier, G. Madec, L. Bessieres) Original code
+   !!            3.2  !  2009-06  (G. Madec, M. Leclair, R. Benshila) introduce sshwzv module
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_spg_exp  : update the momentum trend with the surface 
+   !!                      pressure gradient in the free surface constant  
+   !!                      volume case with vector optimization
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain 
+   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
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl          ! Print control
+   USE iom             ! I/O library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_spg_exp   ! called in dynspg.F90 
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_spg_exp( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine dyn_spg_exp  ***
+      !!
+      !! ** Purpose :   Compute the now trend due to the surface pressure
+      !!              gradient in case of explicit free surface formulation and 
+      !!              add it to the general trend of momentum equation.
+      !!
+      !! ** Method  :   Explicit free surface formulation. Add to the general
+      !!              momentum trend the surface pressure gradient :
+      !!                      (ua,va) = (ua,va) + (spgu,spgv)
+      !!              where spgu = -1/rau0 d/dx(ps) = -g/e1u di( sshn )
+      !!                    spgv = -1/rau0 d/dy(ps) = -g/e2v dj( sshn )
+      !!
+      !! ** Action :   (ua,va)   trend of horizontal velocity increased by 
+      !!                         the surf. pressure gradient trend
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in)  ::   kt   ! ocean time-step index
+      !!
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_spg_exp : surface pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   (explicit free surface)'
+         !
+         spgu(:,:) = 0._wp   ;   spgv(:,:) = 0._wp
+         !
+         IF( .NOT.ln_linssh .AND. lwp ) WRITE(numout,*) '      non linear free surface: spg is included in dynhpg'
+      ENDIF
+
+      IF( ln_linssh ) THEN          !* linear free surface : add the surface pressure gradient trend
+         !
+         DO jj = 2, jpjm1                    ! now surface pressure gradient
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               spgu(ji,jj) = - grav * ( sshn(ji+1,jj) - sshn(ji,jj) ) * r1_e1u(ji,jj)
+               spgv(ji,jj) = - grav * ( sshn(ji,jj+1) - sshn(ji,jj) ) * r1_e2v(ji,jj)
+            END DO 
+         END DO
+         !
+         DO jk = 1, jpkm1                    ! Add it to the general trend
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ua(ji,jj,jk) = ua(ji,jj,jk) + spgu(ji,jj)
+                  va(ji,jj,jk) = va(ji,jj,jk) + spgv(ji,jj)
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+   END SUBROUTINE dyn_spg_exp
+
+   !!======================================================================
+END MODULE dynspg_exp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_ts.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_ts.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynspg_ts.F90	(revision 14097)
@@ -0,0 +1,1606 @@
+MODULE dynspg_ts
+
+   !! Includes ROMS wd scheme with diagnostic outputs ; un and ua updates are commented out ! 
+
+   !!======================================================================
+   !!                   ***  MODULE  dynspg_ts  ***
+   !! Ocean dynamics:  surface pressure gradient trend, split-explicit scheme
+   !!======================================================================
+   !! History :   1.0  ! 2004-12  (L. Bessieres, G. Madec)  Original code
+   !!              -   ! 2005-11  (V. Garnier, G. Madec)  optimization
+   !!              -   ! 2006-08  (S. Masson)  distributed restart using iom
+   !!             2.0  ! 2007-07  (D. Storkey) calls to BDY routines
+   !!              -   ! 2008-01  (R. Benshila)  change averaging method
+   !!             3.2  ! 2009-07  (R. Benshila, G. Madec) Complete revisit associated to vvl reactivation
+   !!             3.3  ! 2010-09  (D. Storkey, E. O'Dea) update for BDY for Shelf configurations
+   !!             3.3  ! 2011-03  (R. Benshila, R. Hordoir, P. Oddo) update calculation of ub_b
+   !!             3.5  ! 2013-07  (J. Chanut) Switch to Forward-backward time stepping
+   !!             3.6  ! 2013-11  (A. Coward) Update for z-tilde compatibility
+   !!             3.7  ! 2015-11  (J. Chanut) free surface simplification
+   !!              -   ! 2016-12  (G. Madec, E. Clementi) update for Stoke-Drift divergence
+   !!             4.0  ! 2017-05  (G. Madec)  drag coef. defined at t-point (zdfdrg.F90)
+   !!---------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_spg_ts     : compute surface pressure gradient trend using a time-splitting scheme 
+   !!   dyn_spg_ts_init: initialisation of the time-splitting scheme
+   !!   ts_wgt         : set time-splitting weights for temporal averaging (or not)
+   !!   ts_rst         : read/write time-splitting fields in restart file
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE zdf_oce         ! vertical physics: variables
+   USE zdfdrg          ! vertical physics: top/bottom drag coef.
+   USE sbcisf          ! ice shelf variable (fwfisf)
+   USE sbcapr          ! surface boundary condition: atmospheric pressure
+   USE dynadv    , ONLY: ln_dynadv_vec
+   USE dynvor          ! vortivity scheme indicators
+   USE phycst          ! physical constants
+   USE dynvor          ! vorticity term
+   USE wet_dry         ! wetting/drying flux limter
+   USE bdy_oce         ! open boundary
+   USE bdyvol          ! open boundary volume conservation
+   USE bdytides        ! open boundary condition data
+   USE bdydyn2d        ! open boundary conditions on barotropic variables
+   USE sbctide         ! tides
+   USE updtide         ! tide potential
+   USE sbcwave         ! surface wave
+#if defined key_agrif
+   USE agrif_oce_interp ! agrif
+   USE agrif_oce
+#endif
+#if defined key_asminc   
+   USE asminc          ! Assimilation increment
+#endif
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distributed memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl          ! Print control
+   USE iom             ! IOM library
+   USE restart         ! only for lrst_oce
+
+   USE iom   ! to remove
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dyn_spg_ts        ! called by dyn_spg 
+   PUBLIC dyn_spg_ts_init   !    -    - dyn_spg_init
+
+   !! Time filtered arrays at baroclinic time step:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   un_adv , vn_adv   !: Advection vel. at "now" barocl. step
+   !
+   INTEGER, SAVE :: icycle      ! Number of barotropic sub-steps for each internal step nn_baro <= 2.5 nn_baro
+   REAL(wp),SAVE :: rdtbt       ! Barotropic time step
+   !
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)   ::   wgtbtp1, wgtbtp2   ! 1st & 2nd weights used in time filtering of barotropic fields
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   zwz                ! ff_f/h at F points
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ftnw, ftne         ! triad of coriolis parameter
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ftsw, ftse         ! (only used with een vorticity scheme)
+
+   REAL(wp) ::   r1_12 = 1._wp / 12._wp   ! local ratios
+   REAL(wp) ::   r1_8  = 0.125_wp         !
+   REAL(wp) ::   r1_4  = 0.25_wp          !
+   REAL(wp) ::   r1_2  = 0.5_wp           !
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dyn_spg_ts_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  routine dyn_spg_ts_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(3)
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( wgtbtp1(3*nn_baro), wgtbtp2(3*nn_baro), zwz(jpi,jpj), STAT=ierr(1) )
+      IF( ln_dynvor_een .OR. ln_dynvor_eeT )   &
+         &     ALLOCATE( ftnw(jpi,jpj) , ftne(jpi,jpj) , ftsw(jpi,jpj) , ftse(jpi,jpj), STAT=ierr(2)   )
+         !
+      ALLOCATE( un_adv(jpi,jpj), vn_adv(jpi,jpj)                    , STAT=ierr(3) )
+      !
+      dyn_spg_ts_alloc = MAXVAL( ierr(:) )
+      !
+      CALL mpp_sum( 'dynspg_ts', dyn_spg_ts_alloc )
+      IF( dyn_spg_ts_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dyn_spg_ts_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION dyn_spg_ts_alloc
+
+
+   SUBROUTINE dyn_spg_ts( kt )
+      !!----------------------------------------------------------------------
+      !!
+      !! ** Purpose : - Compute the now trend due to the explicit time stepping
+      !!              of the quasi-linear barotropic system, and add it to the
+      !!              general momentum trend. 
+      !!
+      !! ** Method  : - split-explicit schem (time splitting) :
+      !!      Barotropic variables are advanced from internal time steps
+      !!      "n"   to "n+1" if ln_bt_fw=T
+      !!      or from 
+      !!      "n-1" to "n+1" if ln_bt_fw=F
+      !!      thanks to a generalized forward-backward time stepping (see ref. below).
+      !!
+      !! ** Action :
+      !!      -Update the filtered free surface at step "n+1"      : ssha
+      !!      -Update filtered barotropic velocities at step "n+1" : ua_b, va_b
+      !!      -Compute barotropic advective fluxes at step "n"     : un_adv, vn_adv
+      !!      These are used to advect tracers and are compliant with discrete
+      !!      continuity equation taken at the baroclinic time steps. This 
+      !!      ensures tracers conservation.
+      !!      - (ua, va) momentum trend updated with barotropic component.
+      !!
+      !! References : Shchepetkin and McWilliams, Ocean Modelling, 2005. 
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in)  ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk, jn        ! dummy loop indices
+      LOGICAL  ::   ll_fw_start           ! =T : forward integration 
+      LOGICAL  ::   ll_init               ! =T : special startup of 2d equations
+      INTEGER  ::   noffset               ! local integers  : time offset for bdy update
+      REAL(wp) ::   r1_2dt_b, z1_hu, z1_hv          ! local scalars
+      REAL(wp) ::   za0, za1, za2, za3              !   -      -
+      REAL(wp) ::   zztmp, zldg               !   -      -
+      REAL(wp) ::   zhu_bck, zhv_bck, zhdiv         !   -      -
+      REAL(wp) ::   zun_save, zvn_save              !   -      -
+      REAL(wp), DIMENSION(jpi,jpj) :: zu_trd, zu_frc, zu_spg, zssh_frc
+      REAL(wp), DIMENSION(jpi,jpj) :: zv_trd, zv_frc, zv_spg
+      REAL(wp), DIMENSION(jpi,jpj) :: zsshu_a, zhup2_e, zhtp2_e
+      REAL(wp), DIMENSION(jpi,jpj) :: zsshv_a, zhvp2_e, zsshp2_e
+      REAL(wp), DIMENSION(jpi,jpj) :: zCdU_u, zCdU_v   ! top/bottom stress at u- & v-points
+      REAL(wp), DIMENSION(jpi,jpj) :: zhU, zhV         ! fluxes
+      !
+      REAL(wp) ::   zwdramp                     ! local scalar - only used if ln_wd_dl = .True. 
+
+      INTEGER  :: iwdg, jwdg, kwdg   ! short-hand values for the indices of the output point
+
+      REAL(wp) ::   zepsilon, zgamma            !   -      -
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zcpx, zcpy   ! Wetting/Dying gravity filter coef.
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: ztwdmask, zuwdmask, zvwdmask ! ROMS wetting and drying masks at t,u,v points
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zuwdav2, zvwdav2    ! averages over the sub-steps of zuwdmask and zvwdmask
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_wd_il ) ALLOCATE( zcpx(jpi,jpj), zcpy(jpi,jpj) )
+      !                                         !* Allocate temporary arrays
+      IF( ln_wd_dl ) ALLOCATE( ztwdmask(jpi,jpj), zuwdmask(jpi,jpj), zvwdmask(jpi,jpj), zuwdav2(jpi,jpj), zvwdav2(jpi,jpj))
+      !
+      zwdramp = r_rn_wdmin1               ! simplest ramp 
+!     zwdramp = 1._wp / (rn_wdmin2 - rn_wdmin1) ! more general ramp
+      !                                         ! inverse of baroclinic time step 
+      IF( kt == nit000 .AND. neuler == 0 ) THEN   ;   r1_2dt_b = 1._wp / (         rdt )
+      ELSE                                        ;   r1_2dt_b = 1._wp / ( 2._wp * rdt )
+      ENDIF
+      !
+      ll_init     = ln_bt_av                    ! if no time averaging, then no specific restart 
+      ll_fw_start = .FALSE.
+      !                                         ! time offset in steps for bdy data update
+      IF( .NOT.ln_bt_fw ) THEN   ;   noffset = - nn_baro
+      ELSE                       ;   noffset =   0 
+      ENDIF
+      !
+      IF( kt == nit000 ) THEN                   !* initialisation
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_spg_ts : surface pressure gradient trend'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~   free surface with time splitting'
+         IF(lwp) WRITE(numout,*)
+         !
+         IF( neuler == 0 )   ll_init=.TRUE.
+         !
+         IF( ln_bt_fw .OR. neuler == 0 ) THEN
+            ll_fw_start =.TRUE.
+            noffset     = 0
+         ELSE
+            ll_fw_start =.FALSE.
+         ENDIF
+         !                    ! Set averaging weights and cycle length:
+         CALL ts_wgt( ln_bt_av, ll_fw_start, icycle, wgtbtp1, wgtbtp2 )
+         !
+      ENDIF
+      !
+      ! If forward start at previous time step, and centered integration, 
+      ! then update averaging weights:
+      IF (.NOT.ln_bt_fw .AND.( neuler==0 .AND. kt==nit000+1 ) ) THEN
+         ll_fw_start=.FALSE.
+         CALL ts_wgt( ln_bt_av, ll_fw_start, icycle, wgtbtp1, wgtbtp2 )
+      ENDIF
+      !
+                          
+      ! -----------------------------------------------------------------------------
+      !  Phase 1 : Coupling between general trend and barotropic estimates (1st step)
+      ! -----------------------------------------------------------------------------
+      !      
+      !
+      !                                   !=  zu_frc =  1/H e3*d/dt(Ua)  =!  (Vertical mean of Ua, the 3D trends)
+      !                                   !  ---------------------------  !
+      zu_frc(:,:) = SUM( e3u_n(:,:,:) * ua(:,:,:) * umask(:,:,:) , DIM=3 ) * r1_hu_n(:,:)
+      zv_frc(:,:) = SUM( e3v_n(:,:,:) * va(:,:,:) * vmask(:,:,:) , DIM=3 ) * r1_hv_n(:,:)
+      !
+      !
+      !                                   !=  Ua => baroclinic trend  =!   (remove its vertical mean)
+      DO jk = 1, jpkm1                    !  ------------------------  !
+         ua(:,:,jk) = ( ua(:,:,jk) - zu_frc(:,:) ) * umask(:,:,jk)
+         va(:,:,jk) = ( va(:,:,jk) - zv_frc(:,:) ) * vmask(:,:,jk)
+      END DO
+      
+!!gm  Question here when removing the Vertically integrated trends, we remove the vertically integrated NL trends on momentum....
+!!gm  Is it correct to do so ?   I think so...
+      
+      !                                   !=  remove 2D Coriolis and pressure gradient trends  =!
+      !                                   !  -------------------------------------------------  !
+      !
+      IF( kt == nit000 .OR. .NOT. ln_linssh )   CALL dyn_cor_2D_init   ! Set zwz, the barotropic Coriolis force coefficient
+      !       ! recompute zwz = f/depth  at every time step for (.NOT.ln_linssh) as the water colomn height changes
+      !
+      !                                         !* 2D Coriolis trends
+      zhU(:,:) = un_b(:,:) * hu_n(:,:) * e2u(:,:)        ! now fluxes 
+      zhV(:,:) = vn_b(:,:) * hv_n(:,:) * e1v(:,:)        ! NB: FULL domain : put a value in last row and column
+      !
+      CALL dyn_cor_2d( hu_n, hv_n, un_b, vn_b, zhU, zhV,  &   ! <<== in
+         &                               zu_trd, zv_trd   )   ! ==>> out
+      !
+      IF( .NOT.ln_linssh ) THEN                 !* surface pressure gradient   (variable volume only)
+         !
+         IF( ln_wd_il ) THEN                       ! W/D : limiter applied to spgspg
+            CALL wad_spg( sshn, zcpx, zcpy )          ! Calculating W/D gravity filters, zcpx and zcpy
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1                ! SPG with the application of W/D gravity filters
+                  zu_trd(ji,jj) = zu_trd(ji,jj) - grav * ( sshn(ji+1,jj  ) - sshn(ji  ,jj ) )   &
+                     &                          * r1_e1u(ji,jj) * zcpx(ji,jj)  * wdrampu(ji,jj)  !jth
+                  zv_trd(ji,jj) = zv_trd(ji,jj) - grav * ( sshn(ji  ,jj+1) - sshn(ji  ,jj ) )   &
+                     &                          * r1_e2v(ji,jj) * zcpy(ji,jj)  * wdrampv(ji,jj)  !jth
+               END DO
+            END DO
+         ELSE                                      ! now suface pressure gradient
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zu_trd(ji,jj) = zu_trd(ji,jj) - grav * (  sshn(ji+1,jj  ) - sshn(ji  ,jj  )  ) * r1_e1u(ji,jj)
+                  zv_trd(ji,jj) = zv_trd(ji,jj) - grav * (  sshn(ji  ,jj+1) - sshn(ji  ,jj  )  ) * r1_e2v(ji,jj) 
+               END DO
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+      DO jj = 2, jpjm1                          ! Remove coriolis term (and possibly spg) from barotropic trend
+         DO ji = fs_2, fs_jpim1
+             zu_frc(ji,jj) = zu_frc(ji,jj) - zu_trd(ji,jj) * ssumask(ji,jj)
+             zv_frc(ji,jj) = zv_frc(ji,jj) - zv_trd(ji,jj) * ssvmask(ji,jj)
+          END DO
+      END DO 
+      !
+      !                                   !=  Add bottom stress contribution from baroclinic velocities  =!
+      !                                   !  -----------------------------------------------------------  !
+      CALL dyn_drg_init( zu_frc, zv_frc,  zCdU_u, zCdU_v )      ! also provide the barotropic drag coefficients
+      !
+      !                                   !=  Add atmospheric pressure forcing  =!
+      !                                   !  ----------------------------------  !
+      IF( ln_apr_dyn ) THEN
+         IF( ln_bt_fw ) THEN                          ! FORWARD integration: use kt+1/2 pressure (NOW+1/2)
+            DO jj = 2, jpjm1              
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zu_frc(ji,jj) = zu_frc(ji,jj) + grav * (  ssh_ib (ji+1,jj  ) - ssh_ib (ji,jj) ) * r1_e1u(ji,jj)
+                  zv_frc(ji,jj) = zv_frc(ji,jj) + grav * (  ssh_ib (ji  ,jj+1) - ssh_ib (ji,jj) ) * r1_e2v(ji,jj)
+               END DO
+            END DO
+         ELSE                                         ! CENTRED integration: use kt-1/2 + kt+1/2 pressure (NOW)
+            zztmp = grav * r1_2
+            DO jj = 2, jpjm1              
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zu_frc(ji,jj) = zu_frc(ji,jj) + zztmp * (  ssh_ib (ji+1,jj  ) - ssh_ib (ji,jj)  &
+                       &                                   + ssh_ibb(ji+1,jj  ) - ssh_ibb(ji,jj)  ) * r1_e1u(ji,jj)
+                  zv_frc(ji,jj) = zv_frc(ji,jj) + zztmp * (  ssh_ib (ji  ,jj+1) - ssh_ib (ji,jj)  &
+                       &                                   + ssh_ibb(ji  ,jj+1) - ssh_ibb(ji,jj)  ) * r1_e2v(ji,jj)
+               END DO
+            END DO
+         ENDIF 
+      ENDIF
+      !
+      !                                   !=  Add atmospheric pressure forcing  =!
+      !                                   !  ----------------------------------  !
+      IF( ln_bt_fw ) THEN                        ! Add wind forcing
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zu_frc(ji,jj) =  zu_frc(ji,jj) + r1_rau0 * utau(ji,jj) * r1_hu_n(ji,jj)
+               zv_frc(ji,jj) =  zv_frc(ji,jj) + r1_rau0 * vtau(ji,jj) * r1_hv_n(ji,jj)
+            END DO
+         END DO
+      ELSE
+         zztmp = r1_rau0 * r1_2
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zu_frc(ji,jj) =  zu_frc(ji,jj) + zztmp * ( utau_b(ji,jj) + utau(ji,jj) ) * r1_hu_n(ji,jj)
+               zv_frc(ji,jj) =  zv_frc(ji,jj) + zztmp * ( vtau_b(ji,jj) + vtau(ji,jj) ) * r1_hv_n(ji,jj)
+            END DO
+         END DO
+      ENDIF  
+      !
+      !              !----------------!
+      !              !==  sssh_frc  ==!   Right-Hand-Side of the barotropic ssh equation   (over the FULL domain)
+      !              !----------------!
+      !                                   !=  Net water flux forcing applied to a water column  =!
+      !                                   ! ---------------------------------------------------  !
+      IF (ln_bt_fw) THEN                          ! FORWARD integration: use kt+1/2 fluxes (NOW+1/2)
+         zssh_frc(:,:) = r1_rau0 * ( emp(:,:)             - rnf(:,:)              + fwfisf(:,:)                  )
+      ELSE                                        ! CENTRED integration: use kt-1/2 + kt+1/2 fluxes (NOW)
+         zztmp = r1_rau0 * r1_2
+         zssh_frc(:,:) = zztmp * (  emp(:,:) + emp_b(:,:) - rnf(:,:) - rnf_b(:,:) + fwfisf(:,:) + fwfisf_b(:,:)  )
+      ENDIF
+      !                                   !=  Add Stokes drift divergence  =!   (if exist)
+      IF( ln_sdw ) THEN                   !  -----------------------------  !
+         zssh_frc(:,:) = zssh_frc(:,:) + div_sd(:,:)
+      ENDIF
+      !
+#if defined key_asminc
+      !                                   !=  Add the IAU weighted SSH increment  =!
+      !                                   !  ------------------------------------  !
+      IF( lk_asminc .AND. ln_sshinc .AND. ln_asmiau ) THEN
+         zssh_frc(:,:) = zssh_frc(:,:) - ssh_iau(:,:)
+      ENDIF
+#endif
+      !                                   != Fill boundary data arrays for AGRIF
+      !                                   ! ------------------------------------
+#if defined key_agrif
+         IF( .NOT.Agrif_Root() ) CALL agrif_dta_ts( kt )
+#endif
+      !
+      ! -----------------------------------------------------------------------
+      !  Phase 2 : Integration of the barotropic equations 
+      ! -----------------------------------------------------------------------
+      !
+      !                                             ! ==================== !
+      !                                             !    Initialisations   !
+      !                                             ! ==================== !  
+      ! 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_linssh ) THEN    ! mid-step ocean depth is fixed (hup2_e=hu_n=hu_0)
+         zhup2_e(:,:) = hu_n(:,:)
+         zhvp2_e(:,:) = hv_n(:,:)
+         zhtp2_e(:,:) = ht_n(:,:)
+      ENDIF
+      !
+      IF (ln_bt_fw) THEN                  ! FORWARD integration: start from NOW fields                    
+         sshn_e(:,:) =    sshn(:,:)            
+         un_e  (:,:) =    un_b(:,:)            
+         vn_e  (:,:) =    vn_b(:,:)
+         !
+         hu_e  (:,:) =    hu_n(:,:)       
+         hv_e  (:,:) =    hv_n(:,:) 
+         hur_e (:,:) = r1_hu_n(:,:)    
+         hvr_e (:,:) = r1_hv_n(:,:)
+      ELSE                                ! CENTRED integration: start from BEFORE fields
+         sshn_e(:,:) =    sshb(:,:)
+         un_e  (:,:) =    ub_b(:,:)         
+         vn_e  (:,:) =    vb_b(:,:)
+         !
+         hu_e  (:,:) =    hu_b(:,:)       
+         hv_e  (:,:) =    hv_b(:,:) 
+         hur_e (:,:) = r1_hu_b(:,:)    
+         hvr_e (:,:) = r1_hv_b(:,:)
+      ENDIF
+      !
+      ! Initialize sums:
+      ua_b  (:,:) = 0._wp       ! After barotropic velocities (or transport if flux form)          
+      va_b  (:,:) = 0._wp
+      ssha  (:,:) = 0._wp       ! Sum for after averaged sea level
+      un_adv(:,:) = 0._wp       ! Sum for now transport issued from ts loop
+      vn_adv(:,:) = 0._wp
+      !
+      IF( ln_wd_dl ) THEN
+         zuwdmask(:,:) = 0._wp  ! set to zero for definiteness (not sure this is necessary) 
+         zvwdmask(:,:) = 0._wp  ! 
+         zuwdav2 (:,:) = 0._wp 
+         zvwdav2 (:,:) = 0._wp   
+      END IF 
+
+      !                                             ! ==================== !
+      DO jn = 1, icycle                             !  sub-time-step loop  !
+         !                                          ! ==================== !
+         !
+         l_full_nf_update = jn == icycle   ! false: disable full North fold update (performances) for jn = 1 to icycle-1
+         !
+         !                    !==  Update the forcing ==! (BDY and tides)
+         !
+         IF( ln_bdy      .AND. ln_tide )   CALL bdy_dta_tides( kt, kit=jn, kt_offset= noffset+1 )
+         IF( ln_tide_pot .AND. ln_tide )   CALL upd_tide     ( kt, kit=jn, kt_offset= noffset   )
+         !
+         !                    !==  extrapolation at mid-step  ==!   (jn+1/2)
+         !
+         !                       !* Set extrapolation coefficients for predictor step:
+         IF ((jn<3).AND.ll_init) THEN      ! Forward           
+           za1 = 1._wp                                          
+           za2 = 0._wp                        
+           za3 = 0._wp                        
+         ELSE                              ! AB3-AM4 Coefficients: bet=0.281105 
+           za1 =  1.781105_wp              ! za1 =   3/2 +   bet
+           za2 = -1.06221_wp               ! za2 = -(1/2 + 2*bet)
+           za3 =  0.281105_wp              ! za3 = bet
+         ENDIF
+         !
+         !                       !* Extrapolate barotropic velocities at mid-step (jn+1/2)
+         !--        m+1/2               m                m-1           m-2       --!
+         !--       u      = (3/2+beta) u   -(1/2+2beta) u      + beta u          --!
+         !-------------------------------------------------------------------------!
+         ua_e(:,:) = za1 * un_e(:,:) + za2 * ub_e(:,:) + za3 * ubb_e(:,:)
+         va_e(:,:) = za1 * vn_e(:,:) + za2 * vb_e(:,:) + za3 * vbb_e(:,:)
+
+         IF( .NOT.ln_linssh ) THEN                        !* Update ocean depth (variable volume case only)
+            !                                             !  ------------------
+            ! Extrapolate Sea Level at step jit+0.5:
+            !--         m+1/2                 m                  m-1             m-2       --!
+            !--      ssh      = (3/2+beta) ssh   -(1/2+2beta) ssh      + beta ssh          --!
+            !--------------------------------------------------------------------------------!
+            zsshp2_e(:,:) = za1 * sshn_e(:,:)  + za2 * sshb_e(:,:) + za3 * sshbb_e(:,:)
+            
+            ! set wetting & drying mask at tracer points for this barotropic mid-step
+            IF( ln_wd_dl )   CALL wad_tmsk( zsshp2_e, ztwdmask )
+            !
+            !                          ! ocean t-depth at mid-step
+            zhtp2_e(:,:) = ht_0(:,:) + zsshp2_e(:,:)
+            !
+            !                          ! ocean u- and v-depth at mid-step   (separate DO-loops remove the need of a lbc_lnk)
+            DO jj = 1, jpj
+               DO ji = 1, jpim1   ! not jpi-column
+                  zhup2_e(ji,jj) = hu_0(ji,jj) + r1_2 * r1_e1e2u(ji,jj)                        &
+                       &                              * (  e1e2t(ji  ,jj) * zsshp2_e(ji  ,jj)  &
+                       &                                 + e1e2t(ji+1,jj) * zsshp2_e(ji+1,jj)  ) * ssumask(ji,jj)
+               END DO
+            END DO
+            DO jj = 1, jpjm1        ! not jpj-row
+               DO ji = 1, jpi
+                  zhvp2_e(ji,jj) = hv_0(ji,jj) + r1_2 * r1_e1e2v(ji,jj)                        &
+                       &                              * (  e1e2t(ji,jj  ) * zsshp2_e(ji,jj  )  &
+                       &                                 + e1e2t(ji,jj+1) * zsshp2_e(ji,jj+1)  ) * ssvmask(ji,jj)
+               END DO
+            END DO
+            !
+         ENDIF
+         !
+         !                    !==  after SSH  ==!   (jn+1)
+         !
+         !                             ! update (ua_e,va_e) to enforce volume conservation at open boundaries
+         !                             ! values of zhup2_e and zhvp2_e on the halo are not needed in bdy_vol2d
+         IF( ln_bdy .AND. ln_vol ) CALL bdy_vol2d( kt, jn, ua_e, va_e, zhup2_e, zhvp2_e )
+         !
+         !                             ! resulting flux at mid-step (not over the full domain)
+         zhU(1:jpim1,1:jpj  ) = e2u(1:jpim1,1:jpj  ) * ua_e(1:jpim1,1:jpj  ) * zhup2_e(1:jpim1,1:jpj  )   ! not jpi-column
+         zhV(1:jpi  ,1:jpjm1) = e1v(1:jpi  ,1:jpjm1) * va_e(1:jpi  ,1:jpjm1) * zhvp2_e(1:jpi  ,1:jpjm1)   ! not jpj-row
+         !
+#if defined key_agrif
+         ! Set fluxes during predictor step to ensure volume conservation
+         IF( .NOT.Agrif_Root() .AND. ln_bt_fw ) THEN
+            IF( l_Westedge ) THEN
+               DO jj = 1, jpj
+                  zhU(2:nbghostcells+1,jj) = ubdy_w(1:nbghostcells,jj) * e2u(2:nbghostcells+1,jj)
+                  zhV(2:nbghostcells+1,jj) = vbdy_w(1:nbghostcells,jj) * e1v(2:nbghostcells+1,jj)
+               END DO
+            ENDIF
+            IF( l_Eastedge ) THEN
+               DO jj=1,jpj
+                  zhU(nlci-nbghostcells-1:nlci-2,jj) = ubdy_e(1:nbghostcells,jj) * e2u(nlci-nbghostcells-1:nlci-2,jj)
+                  zhV(nlci-nbghostcells  :nlci-1,jj) = vbdy_e(1:nbghostcells,jj) * e1v(nlci-nbghostcells  :nlci-1,jj)
+               END DO
+            ENDIF
+            IF( l_Southedge ) THEN
+               DO ji=1,jpi
+                  zhV(ji,2:nbghostcells+1) = vbdy_s(ji,1:nbghostcells) * e1v(ji,2:nbghostcells+1)
+                  zhU(ji,2:nbghostcells+1) = ubdy_s(ji,1:nbghostcells) * e2u(ji,2:nbghostcells+1)
+               END DO
+            ENDIF
+            IF( l_Northedge ) THEN
+               DO ji=1,jpi
+                  zhV(ji,nlcj-nbghostcells-1:nlcj-2) = vbdy_n(ji,1:nbghostcells) * e1v(ji,nlcj-nbghostcells-1:nlcj-2)
+                  zhU(ji,nlcj-nbghostcells  :nlcj-1) = ubdy_n(ji,1:nbghostcells) * e2u(ji,nlcj-nbghostcells  :nlcj-1)
+               END DO
+            ENDIF
+         ENDIF
+#endif
+         IF( ln_wd_il )   CALL wad_lmt_bt(zhU, zhV, sshn_e, zssh_frc, rdtbt)    !!gm wad_lmt_bt use of lbc_lnk on zhU, zhV
+
+         IF( ln_wd_dl ) THEN           ! un_e and vn_e are set to zero at faces where 
+            !                          ! the direction of the flow is from dry cells
+            CALL wad_Umsk( ztwdmask, zhU, zhV, un_e, vn_e, zuwdmask, zvwdmask )   ! not jpi colomn for U, not jpj row for V
+            !
+         ENDIF    
+         !
+         !
+         !     Compute Sea Level at step jit+1
+         !--           m+1        m                               m+1/2          --!
+         !--        ssh    =  ssh   - delta_t' * [ frc + div( flux      ) ]      --!
+         !-------------------------------------------------------------------------!
+         DO jj = 2, jpjm1        ! INNER domain                             
+            DO ji = 2, jpim1
+               zhdiv = (   zhU(ji,jj) - zhU(ji-1,jj) + zhV(ji,jj) - zhV(ji,jj-1)   ) * r1_e1e2t(ji,jj)
+               ssha_e(ji,jj) = (  sshn_e(ji,jj) - rdtbt * ( zssh_frc(ji,jj) + zhdiv )  ) * ssmask(ji,jj)
+            END DO
+         END DO
+         !
+         CALL lbc_lnk_multi( 'dynspg_ts', ssha_e, 'T', 1._wp,  zhU, 'U', -1._wp,  zhV, 'V', -1._wp )
+         !
+         !                             ! Sum over sub-time-steps to compute advective velocities
+         za2 = wgtbtp2(jn)             ! zhU, zhV hold fluxes extrapolated at jn+0.5
+         un_adv(:,:) = un_adv(:,:) + za2 * zhU(:,:) * r1_e2u(:,:)
+         vn_adv(:,:) = vn_adv(:,:) + za2 * zhV(:,:) * r1_e1v(:,:)
+         ! sum over sub-time-steps to decide which baroclinic velocities to set to zero (zuwdav2 is only used when ln_wd_dl_bc=True) 
+         IF ( ln_wd_dl_bc ) THEN
+            zuwdav2(1:jpim1,1:jpj  ) = zuwdav2(1:jpim1,1:jpj  ) + za2 * zuwdmask(1:jpim1,1:jpj  )   ! not jpi-column
+            zvwdav2(1:jpi  ,1:jpjm1) = zvwdav2(1:jpi  ,1:jpjm1) + za2 * zvwdmask(1:jpi  ,1:jpjm1)   ! not jpj-row
+         END IF
+         !
+         ! Duplicate sea level across open boundaries (this is only cosmetic if linssh=T)
+         IF( ln_bdy )   CALL bdy_ssh( ssha_e )
+#if defined key_agrif
+         IF( .NOT.Agrif_Root() )   CALL agrif_ssh_ts( jn )
+#endif
+         !  
+         ! Sea Surface Height at u-,v-points (vvl case only)
+         IF( .NOT.ln_linssh ) THEN                                
+            DO jj = 2, jpjm1   ! INNER domain, will be extended to whole domain later
+               DO ji = 2, jpim1      ! NO Vector Opt.
+                  zsshu_a(ji,jj) = r1_2 * ssumask(ji,jj) * r1_e1e2u(ji,jj)    &
+                     &              * ( e1e2t(ji  ,jj  )  * ssha_e(ji  ,jj  ) &
+                     &              +   e1e2t(ji+1,jj  )  * ssha_e(ji+1,jj  ) )
+                  zsshv_a(ji,jj) = r1_2 * ssvmask(ji,jj) * r1_e1e2v(ji,jj)    &
+                     &              * ( e1e2t(ji  ,jj  )  * ssha_e(ji  ,jj  ) &
+                     &              +   e1e2t(ji  ,jj+1)  * ssha_e(ji  ,jj+1) )
+               END DO
+            END DO
+         ENDIF   
+         !         
+         ! Half-step back interpolation of SSH for surface pressure computation at step jit+1/2
+         !--            m+1/2           m+1              m               m-1              m-2     --!
+         !--        ssh'    =  za0 * ssh     +  za1 * ssh   +  za2 * ssh      +  za3 * ssh        --!
+         !------------------------------------------------------------------------------------------!
+         CALL ts_bck_interp( jn, ll_init, za0, za1, za2, za3 )   ! coeficients of the interpolation
+         zsshp2_e(:,:) = za0 *  ssha_e(:,:) + za1 *  sshn_e (:,:)   &
+            &          + za2 *  sshb_e(:,:) + za3 *  sshbb_e(:,:)
+         !
+         !                             ! Surface pressure gradient
+         zldg = ( 1._wp - rn_scal_load ) * grav    ! local factor
+         DO jj = 2, jpjm1                            
+            DO ji = 2, jpim1
+               zu_spg(ji,jj) = - zldg * ( zsshp2_e(ji+1,jj) - zsshp2_e(ji,jj) ) * r1_e1u(ji,jj)
+               zv_spg(ji,jj) = - zldg * ( zsshp2_e(ji,jj+1) - zsshp2_e(ji,jj) ) * r1_e2v(ji,jj)
+            END DO
+         END DO
+         IF( ln_wd_il ) THEN        ! W/D : gravity filters applied on pressure gradient
+            CALL wad_spg( zsshp2_e, zcpx, zcpy )   ! Calculating W/D gravity filters
+            zu_spg(2:jpim1,2:jpjm1) = zu_spg(2:jpim1,2:jpjm1) * zcpx(2:jpim1,2:jpjm1)
+            zv_spg(2:jpim1,2:jpjm1) = zv_spg(2:jpim1,2:jpjm1) * zcpy(2:jpim1,2:jpjm1)
+         ENDIF
+         !
+         ! Add Coriolis trend:
+         ! zwz array below or triads normally depend on sea level with ln_linssh=F and should be updated
+         ! at each time step. We however keep them constant here for optimization.
+         ! Recall that zhU and zhV hold fluxes at jn+0.5 (extrapolated not backward interpolated)
+         CALL dyn_cor_2d( zhup2_e, zhvp2_e, ua_e, va_e, zhU, zhV,    zu_trd, zv_trd   )
+         !
+         ! Add tidal astronomical forcing if defined
+         IF ( ln_tide .AND. ln_tide_pot ) THEN
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zu_trd(ji,jj) = zu_trd(ji,jj) + grav * ( pot_astro(ji+1,jj) - pot_astro(ji,jj) ) * r1_e1u(ji,jj)
+                  zv_trd(ji,jj) = zv_trd(ji,jj) + grav * ( pot_astro(ji,jj+1) - pot_astro(ji,jj) ) * r1_e2v(ji,jj)
+               END DO
+            END DO
+         ENDIF
+         !
+         ! Add bottom stresses:
+!jth do implicitly instead
+         IF ( .NOT. ll_wd ) THEN ! Revert to explicit for bit comparison tests in non wad runs
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zu_trd(ji,jj) = zu_trd(ji,jj) + zCdU_u(ji,jj) * un_e(ji,jj) * hur_e(ji,jj)
+                  zv_trd(ji,jj) = zv_trd(ji,jj) + zCdU_v(ji,jj) * vn_e(ji,jj) * hvr_e(ji,jj)
+               END DO
+            END DO
+         ENDIF
+         !
+         ! Set next velocities:
+         !     Compute barotropic speeds at step jit+1    (h : total height of the water colomn)
+         !--                              VECTOR FORM
+         !--   m+1                 m               /                                                       m+1/2           \    --!
+         !--  u     =             u   + delta_t' * \         (1-r)*g * grad_x( ssh') -         f * k vect u      +     frc /    --!
+         !--                                                                                                                    --!
+         !--                             FLUX FORM                                                                              --!
+         !--  m+1   __1__  /  m    m               /  m+1/2                             m+1/2              m+1/2    n      \ \  --!
+         !-- u    =   m+1 |  h  * u   + delta_t' * \ h     * (1-r)*g * grad_x( ssh') - h     * f * k vect u      + h * frc /  | --!
+         !--         h     \                                                                                                 /  --!
+         !------------------------------------------------------------------------------------------------------------------------!
+         IF( ln_dynadv_vec .OR. ln_linssh ) THEN      !* Vector form
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ua_e(ji,jj) = (                                 un_e(ji,jj)   & 
+                            &     + rdtbt * (                   zu_spg(ji,jj)   &
+                            &                                 + zu_trd(ji,jj)   &
+                            &                                 + zu_frc(ji,jj) ) & 
+                            &   ) * ssumask(ji,jj)
+
+                  va_e(ji,jj) = (                                 vn_e(ji,jj)   &
+                            &     + rdtbt * (                   zv_spg(ji,jj)   &
+                            &                                 + zv_trd(ji,jj)   &
+                            &                                 + zv_frc(ji,jj) ) &
+                            &   ) * ssvmask(ji,jj)
+               END DO
+            END DO
+            !
+         ELSE                           !* Flux form
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  !                    ! hu_e, hv_e hold depth at jn,  zhup2_e, zhvp2_e hold extrapolated depth at jn+1/2
+                  !                    ! backward interpolated depth used in spg terms at jn+1/2
+                  zhu_bck = hu_0(ji,jj) + r1_2*r1_e1e2u(ji,jj) * (  e1e2t(ji  ,jj) * zsshp2_e(ji  ,jj)    &
+                       &                                          + e1e2t(ji+1,jj) * zsshp2_e(ji+1,jj)  ) * ssumask(ji,jj)
+                  zhv_bck = hv_0(ji,jj) + r1_2*r1_e1e2v(ji,jj) * (  e1e2t(ji,jj  ) * zsshp2_e(ji,jj  )    &
+                       &                                          + e1e2t(ji,jj+1) * zsshp2_e(ji,jj+1)  ) * ssvmask(ji,jj)
+                  !                    ! inverse depth at jn+1
+                  z1_hu = ssumask(ji,jj) / ( hu_0(ji,jj) + zsshu_a(ji,jj) + 1._wp - ssumask(ji,jj) )
+                  z1_hv = ssvmask(ji,jj) / ( hv_0(ji,jj) + zsshv_a(ji,jj) + 1._wp - ssvmask(ji,jj) )
+                  !
+                  ua_e(ji,jj) = (               hu_e  (ji,jj) *   un_e (ji,jj)      & 
+                       &            + rdtbt * (  zhu_bck        * zu_spg (ji,jj)  &   !
+                       &                       + zhup2_e(ji,jj) * zu_trd (ji,jj)  &   !
+                       &                       +  hu_n  (ji,jj) * zu_frc (ji,jj)  )   ) * z1_hu
+                  !
+                  va_e(ji,jj) = (               hv_e  (ji,jj) *   vn_e (ji,jj)      &
+                       &            + rdtbt * (  zhv_bck        * zv_spg (ji,jj)  &   !
+                       &                       + zhvp2_e(ji,jj) * zv_trd (ji,jj)  &   !
+                       &                       +  hv_n  (ji,jj) * zv_frc (ji,jj)  )   ) * z1_hv
+               END DO
+            END DO
+         ENDIF
+!jth implicit bottom friction:
+         IF ( ll_wd ) THEN ! revert to explicit for bit comparison tests in non wad runs
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ua_e(ji,jj) =  ua_e(ji,jj) /(1.0 -   rdtbt * zCdU_u(ji,jj) * hur_e(ji,jj))
+                     va_e(ji,jj) =  va_e(ji,jj) /(1.0 -   rdtbt * zCdU_v(ji,jj) * hvr_e(ji,jj))
+               END DO
+            END DO
+         ENDIF
+       
+         IF( .NOT.ln_linssh ) THEN   !* Update ocean depth (variable volume case only)
+            hu_e (2:jpim1,2:jpjm1) = hu_0(2:jpim1,2:jpjm1) + zsshu_a(2:jpim1,2:jpjm1)
+            hur_e(2:jpim1,2:jpjm1) = ssumask(2:jpim1,2:jpjm1) / ( hu_e(2:jpim1,2:jpjm1) + 1._wp - ssumask(2:jpim1,2:jpjm1) )
+            hv_e (2:jpim1,2:jpjm1) = hv_0(2:jpim1,2:jpjm1) + zsshv_a(2:jpim1,2:jpjm1)
+            hvr_e(2:jpim1,2:jpjm1) = ssvmask(2:jpim1,2:jpjm1) / ( hv_e(2:jpim1,2:jpjm1) + 1._wp - ssvmask(2:jpim1,2:jpjm1) )
+            CALL lbc_lnk_multi( 'dynspg_ts', ua_e , 'U', -1._wp, va_e , 'V', -1._wp  &
+                 &                         , hu_e , 'U',  1._wp, hv_e , 'V',  1._wp  &
+                 &                         , hur_e, 'U',  1._wp, hvr_e, 'V',  1._wp  )
+         ELSE
+            CALL lbc_lnk_multi( 'dynspg_ts', ua_e , 'U', -1._wp, va_e , 'V', -1._wp  )
+         ENDIF
+         !
+         !
+         !                                                 ! open boundaries
+         IF( ln_bdy )   CALL bdy_dyn2d( jn, ua_e, va_e, un_e, vn_e, hur_e, hvr_e, ssha_e )
+#if defined key_agrif                                                           
+         IF( .NOT.Agrif_Root() )  CALL agrif_dyn_ts( jn )  ! Agrif
+#endif
+         !                                             !* Swap
+         !                                             !  ----
+         ubb_e  (:,:) = ub_e  (:,:)
+         ub_e   (:,:) = un_e  (:,:)
+         un_e   (:,:) = ua_e  (:,:)
+         !
+         vbb_e  (:,:) = vb_e  (:,:)
+         vb_e   (:,:) = vn_e  (:,:)
+         vn_e   (:,:) = va_e  (:,:)
+         !
+         sshbb_e(:,:) = sshb_e(:,:)
+         sshb_e (:,:) = sshn_e(:,:)
+         sshn_e (:,:) = ssha_e(:,:)
+
+         !                                             !* Sum over whole bt loop
+         !                                             !  ----------------------
+         za1 = wgtbtp1(jn)                                    
+         IF( ln_dynadv_vec .OR. ln_linssh ) THEN    ! Sum velocities
+            ua_b  (:,:) = ua_b  (:,:) + za1 * ua_e  (:,:) 
+            va_b  (:,:) = va_b  (:,:) + za1 * va_e  (:,:) 
+         ELSE                                       ! Sum transports
+            IF ( .NOT.ln_wd_dl ) THEN  
+               ua_b  (:,:) = ua_b  (:,:) + za1 * ua_e  (:,:) * hu_e (:,:)
+               va_b  (:,:) = va_b  (:,:) + za1 * va_e  (:,:) * hv_e (:,:)
+            ELSE 
+               ua_b  (:,:) = ua_b  (:,:) + za1 * ua_e  (:,:) * hu_e (:,:) * zuwdmask(:,:)
+               va_b  (:,:) = va_b  (:,:) + za1 * va_e  (:,:) * hv_e (:,:) * zvwdmask(:,:)
+            END IF 
+         ENDIF
+         !                                          ! Sum sea level
+         ssha(:,:) = ssha(:,:) + za1 * ssha_e(:,:)
+
+         !                                                 ! ==================== !
+      END DO                                               !        end loop      !
+      !                                                    ! ==================== !
+      ! -----------------------------------------------------------------------------
+      ! Phase 3. update the general trend with the barotropic trend
+      ! -----------------------------------------------------------------------------
+      !
+      ! Set advection velocity correction:
+      IF (ln_bt_fw) THEN
+         IF( .NOT.( kt == nit000 .AND. neuler==0 ) ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zun_save = un_adv(ji,jj)
+                  zvn_save = vn_adv(ji,jj)
+                  !                          ! apply the previously computed correction 
+                  un_adv(ji,jj) = r1_2 * ( ub2_b(ji,jj) + zun_save - atfp * un_bf(ji,jj) )
+                  vn_adv(ji,jj) = r1_2 * ( vb2_b(ji,jj) + zvn_save - atfp * vn_bf(ji,jj) )
+                  !                          ! Update corrective fluxes for next time step
+                  un_bf(ji,jj)  = atfp * un_bf(ji,jj) + ( zun_save - ub2_b(ji,jj) )
+                  vn_bf(ji,jj)  = atfp * vn_bf(ji,jj) + ( zvn_save - vb2_b(ji,jj) )
+                  !                          ! Save integrated transport for next computation
+                  ub2_b(ji,jj) = zun_save
+                  vb2_b(ji,jj) = zvn_save
+               END DO
+            END DO
+         ELSE
+            un_bf(:,:) = 0._wp            ! corrective fluxes for next time step set to zero
+            vn_bf(:,:) = 0._wp
+            ub2_b(:,:) = un_adv(:,:)      ! Save integrated transport for next computation
+            vb2_b(:,:) = vn_adv(:,:)
+         END IF
+      ENDIF
+
+
+      !
+      ! Update barotropic trend:
+      IF( ln_dynadv_vec .OR. ln_linssh ) THEN
+         DO jk=1,jpkm1
+            ua(:,:,jk) = ua(:,:,jk) + ( ua_b(:,:) - ub_b(:,:) ) * r1_2dt_b
+            va(:,:,jk) = va(:,:,jk) + ( va_b(:,:) - vb_b(:,:) ) * r1_2dt_b
+         END DO
+      ELSE
+         ! At this stage, ssha has been corrected: compute new depths at velocity points
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1      ! NO Vector Opt.
+               zsshu_a(ji,jj) = r1_2 * ssumask(ji,jj)  * r1_e1e2u(ji,jj) &
+                  &              * ( e1e2t(ji  ,jj) * ssha(ji  ,jj)      &
+                  &              +   e1e2t(ji+1,jj) * ssha(ji+1,jj) )
+               zsshv_a(ji,jj) = r1_2 * ssvmask(ji,jj)  * r1_e1e2v(ji,jj) &
+                  &              * ( e1e2t(ji,jj  ) * ssha(ji,jj  )      &
+                  &              +   e1e2t(ji,jj+1) * ssha(ji,jj+1) )
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'dynspg_ts', zsshu_a, 'U', 1._wp, zsshv_a, 'V', 1._wp ) ! Boundary conditions
+         !
+         DO jk=1,jpkm1
+            ua(:,:,jk) = ua(:,:,jk) + r1_hu_n(:,:) * ( ua_b(:,:) - ub_b(:,:) * hu_b(:,:) ) * r1_2dt_b
+            va(:,:,jk) = va(:,:,jk) + r1_hv_n(:,:) * ( va_b(:,:) - vb_b(:,:) * hv_b(:,:) ) * r1_2dt_b
+         END DO
+         ! Save barotropic velocities not transport:
+         ua_b(:,:) =  ua_b(:,:) / ( hu_0(:,:) + zsshu_a(:,:) + 1._wp - ssumask(:,:) )
+         va_b(:,:) =  va_b(:,:) / ( hv_0(:,:) + zsshv_a(:,:) + 1._wp - ssvmask(:,:) )
+      ENDIF
+
+
+      ! Correct velocities so that the barotropic velocity equals (un_adv, vn_adv) (in all cases)  
+      DO jk = 1, jpkm1
+         un(:,:,jk) = ( un(:,:,jk) + un_adv(:,:)*r1_hu_n(:,:) - un_b(:,:) ) * umask(:,:,jk)
+         vn(:,:,jk) = ( vn(:,:,jk) + vn_adv(:,:)*r1_hv_n(:,:) - vn_b(:,:) ) * vmask(:,:,jk)
+      END DO
+
+      IF ( ln_wd_dl .and. ln_wd_dl_bc) THEN 
+         ! need to set lbc here because not done prior time averaging
+         CALL lbc_lnk_multi( 'dynspg_ts', zuwdav2, 'U', 1._wp, zvwdav2, 'V', 1._wp)
+         DO jk = 1, jpkm1
+            un(:,:,jk) = ( un_adv(:,:)*r1_hu_n(:,:) &
+                       & + zuwdav2(:,:)*(un(:,:,jk) - un_adv(:,:)*r1_hu_n(:,:)) ) * umask(:,:,jk) 
+            vn(:,:,jk) = ( vn_adv(:,:)*r1_hv_n(:,:) & 
+                       & + zvwdav2(:,:)*(vn(:,:,jk) - vn_adv(:,:)*r1_hv_n(:,:)) ) * vmask(:,:,jk)  
+         END DO
+      END IF 
+
+      
+      CALL iom_put(  "ubar", un_adv(:,:)*r1_hu_n(:,:) )    ! barotropic i-current
+      CALL iom_put(  "vbar", vn_adv(:,:)*r1_hv_n(:,:) )    ! barotropic i-current
+      !
+#if defined key_agrif
+      ! Save time integrated fluxes during child grid integration
+      ! (used to update coarse grid transports at next time step)
+      !
+      IF( .NOT.Agrif_Root() .AND. ln_bt_fw ) THEN
+         IF( Agrif_NbStepint() == 0 ) THEN
+            ub2_i_b(:,:) = 0._wp
+            vb2_i_b(:,:) = 0._wp
+         END IF
+         !
+         za1 = 1._wp / REAL(Agrif_rhot(), wp)
+         ub2_i_b(:,:) = ub2_i_b(:,:) + za1 * ub2_b(:,:)
+         vb2_i_b(:,:) = vb2_i_b(:,:) + za1 * vb2_b(:,:)
+      ENDIF
+#endif      
+      !                                   !* write time-spliting arrays in the restart
+      IF( lrst_oce .AND.ln_bt_fw )   CALL ts_rst( kt, 'WRITE' )
+      !
+      IF( ln_wd_il )   DEALLOCATE( zcpx, zcpy )
+      IF( ln_wd_dl )   DEALLOCATE( ztwdmask, zuwdmask, zvwdmask, zuwdav2, zvwdav2 )
+      !
+      CALL iom_put( "baro_u" , un_b )  ! Barotropic  U Velocity
+      CALL iom_put( "baro_v" , vn_b )  ! Barotropic  V Velocity
+      !
+   END SUBROUTINE dyn_spg_ts
+
+
+   SUBROUTINE ts_wgt( ll_av, ll_fw, jpit, zwgt1, zwgt2)
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE ts_wgt  ***
+      !!
+      !! ** Purpose : Set time-splitting weights for temporal averaging (or not)
+      !!----------------------------------------------------------------------
+      LOGICAL, INTENT(in) ::   ll_av      ! temporal averaging=.true.
+      LOGICAL, INTENT(in) ::   ll_fw      ! forward time splitting =.true.
+      INTEGER, INTENT(inout) :: jpit      ! cycle length    
+      REAL(wp), DIMENSION(3*nn_baro), INTENT(inout) ::   zwgt1, & ! Primary weights
+                                                         zwgt2    ! Secondary weights
+      
+      INTEGER ::  jic, jn, ji                      ! temporary integers
+      REAL(wp) :: za1, za2
+      !!----------------------------------------------------------------------
+
+      zwgt1(:) = 0._wp
+      zwgt2(:) = 0._wp
+
+      ! Set time index when averaged value is requested
+      IF (ll_fw) THEN 
+         jic = nn_baro
+      ELSE
+         jic = 2 * nn_baro
+      ENDIF
+
+      ! Set primary weights:
+      IF (ll_av) THEN
+           ! Define simple boxcar window for primary weights 
+           ! (width = nn_baro, centered around jic)     
+         SELECT CASE ( nn_bt_flt )
+              CASE( 0 )  ! No averaging
+                 zwgt1(jic) = 1._wp
+                 jpit = jic
+
+              CASE( 1 )  ! Boxcar, width = nn_baro
+                 DO jn = 1, 3*nn_baro
+                    za1 = ABS(float(jn-jic))/float(nn_baro) 
+                    IF (za1 < 0.5_wp) THEN
+                      zwgt1(jn) = 1._wp
+                      jpit = jn
+                    ENDIF
+                 ENDDO
+
+              CASE( 2 )  ! Boxcar, width = 2 * nn_baro
+                 DO jn = 1, 3*nn_baro
+                    za1 = ABS(float(jn-jic))/float(nn_baro) 
+                    IF (za1 < 1._wp) THEN
+                      zwgt1(jn) = 1._wp
+                      jpit = jn
+                    ENDIF
+                 ENDDO
+              CASE DEFAULT   ;   CALL ctl_stop( 'unrecognised value for nn_bt_flt' )
+         END SELECT
+
+      ELSE ! No time averaging
+         zwgt1(jic) = 1._wp
+         jpit = jic
+      ENDIF
+    
+      ! Set secondary weights
+      DO jn = 1, jpit
+        DO ji = jn, jpit
+             zwgt2(jn) = zwgt2(jn) + zwgt1(ji)
+        END DO
+      END DO
+
+      ! Normalize weigths:
+      za1 = 1._wp / SUM(zwgt1(1:jpit))
+      za2 = 1._wp / SUM(zwgt2(1:jpit))
+      DO jn = 1, jpit
+        zwgt1(jn) = zwgt1(jn) * za1
+        zwgt2(jn) = zwgt2(jn) * za2
+      END DO
+      !
+   END SUBROUTINE ts_wgt
+
+
+   SUBROUTINE ts_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE ts_rst  ***
+      !!
+      !! ** Purpose : Read or write time-splitting arrays in restart file
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ---------------
+         IF( ln_rstart .AND. ln_bt_fw .AND. (neuler/=0) ) THEN    !* Read the restart file
+            CALL iom_get( numror, jpdom_autoglo, 'ub2_b'  , ub2_b  (:,:), ldxios = lrxios )   
+            CALL iom_get( numror, jpdom_autoglo, 'vb2_b'  , vb2_b  (:,:), ldxios = lrxios ) 
+            CALL iom_get( numror, jpdom_autoglo, 'un_bf'  , un_bf  (:,:), ldxios = lrxios )   
+            CALL iom_get( numror, jpdom_autoglo, 'vn_bf'  , vn_bf  (:,:), ldxios = lrxios ) 
+            IF( .NOT.ln_bt_av ) THEN
+               CALL iom_get( numror, jpdom_autoglo, 'sshbb_e'  , sshbb_e(:,:), ldxios = lrxios )   
+               CALL iom_get( numror, jpdom_autoglo, 'ubb_e'    ,   ubb_e(:,:), ldxios = lrxios )   
+               CALL iom_get( numror, jpdom_autoglo, 'vbb_e'    ,   vbb_e(:,:), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'sshb_e'   ,  sshb_e(:,:), ldxios = lrxios ) 
+               CALL iom_get( numror, jpdom_autoglo, 'ub_e'     ,    ub_e(:,:), ldxios = lrxios )   
+               CALL iom_get( numror, jpdom_autoglo, 'vb_e'     ,    vb_e(:,:), ldxios = lrxios )
+            ENDIF
+#if defined key_agrif
+            ! Read time integrated fluxes
+            IF ( .NOT.Agrif_Root() ) THEN
+               CALL iom_get( numror, jpdom_autoglo, 'ub2_i_b'  , ub2_i_b(:,:), ldxios = lrxios )   
+               CALL iom_get( numror, jpdom_autoglo, 'vb2_i_b'  , vb2_i_b(:,:), ldxios = lrxios )
+            ENDIF
+#endif
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set barotropic values to 0'
+            ub2_b (:,:) = 0._wp   ;   vb2_b (:,:) = 0._wp   ! used in the 1st interpol of agrif
+            un_adv(:,:) = 0._wp   ;   vn_adv(:,:) = 0._wp   ! used in the 1st interpol of agrif
+            un_bf (:,:) = 0._wp   ;   vn_bf (:,:) = 0._wp   ! used in the 1st update   of agrif
+#if defined key_agrif
+            IF ( .NOT.Agrif_Root() ) THEN
+               ub2_i_b(:,:) = 0._wp   ;   vb2_i_b(:,:) = 0._wp   ! used in the 1st update of agrif
+            ENDIF
+#endif
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- ts_rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'ub2_b'   , ub2_b  (:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'vb2_b'   , vb2_b  (:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'un_bf'   , un_bf  (:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'vn_bf'   , vn_bf  (:,:), ldxios = lwxios )
+         !
+         IF (.NOT.ln_bt_av) THEN
+            CALL iom_rstput( kt, nitrst, numrow, 'sshbb_e'  , sshbb_e(:,:), ldxios = lwxios ) 
+            CALL iom_rstput( kt, nitrst, numrow, 'ubb_e'    ,   ubb_e(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'vbb_e'    ,   vbb_e(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'sshb_e'   ,  sshb_e(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'ub_e'     ,    ub_e(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'vb_e'     ,    vb_e(:,:), ldxios = lwxios )
+         ENDIF
+#if defined key_agrif
+         ! Save time integrated fluxes
+         IF ( .NOT.Agrif_Root() ) THEN
+            CALL iom_rstput( kt, nitrst, numrow, 'ub2_i_b'  , ub2_i_b(:,:), ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'vb2_i_b'  , vb2_i_b(:,:), ldxios = lwxios )
+         ENDIF
+#endif
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE ts_rst
+
+
+   SUBROUTINE dyn_spg_ts_init
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_spg_ts_init  ***
+      !!
+      !! ** Purpose : Set time splitting options
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji ,jj              ! dummy loop indices
+      REAL(wp) ::   zxr2, zyr2, zcmax   ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj) ::   zcu
+      INTEGER  :: inum
+      !!----------------------------------------------------------------------
+      !
+      ! Max courant number for ext. grav. waves
+      !
+      DO jj = 1, jpj
+         DO ji =1, jpi
+            zxr2 = r1_e1t(ji,jj) * r1_e1t(ji,jj)
+            zyr2 = r1_e2t(ji,jj) * r1_e2t(ji,jj)
+            zcu(ji,jj) = SQRT( grav * MAX(ht_0(ji,jj),0._wp) * (zxr2 + zyr2) )
+         END DO
+      END DO
+      !
+      zcmax = MAXVAL( zcu(:,:) )
+      CALL mpp_max( 'dynspg_ts', zcmax )
+
+      ! Estimate number of iterations to satisfy a max courant number= rn_bt_cmax
+      IF( ln_bt_auto )   nn_baro = CEILING( rdt / rn_bt_cmax * zcmax)
+      
+      rdtbt = rdt / REAL( nn_baro , wp )
+      zcmax = zcmax * rdtbt
+      ! Print results
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dyn_spg_ts_init : split-explicit free surface'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~~'
+      IF( ln_bt_auto ) THEN
+         IF(lwp) WRITE(numout,*) '     ln_ts_auto =.true. Automatically set nn_baro '
+         IF(lwp) WRITE(numout,*) '     Max. courant number allowed: ', rn_bt_cmax
+      ELSE
+         IF(lwp) WRITE(numout,*) '     ln_ts_auto=.false.: Use nn_baro in namelist   nn_baro = ', nn_baro
+      ENDIF
+
+      IF(ln_bt_av) THEN
+         IF(lwp) WRITE(numout,*) '     ln_bt_av =.true.  ==> Time averaging over nn_baro time steps is on '
+      ELSE
+         IF(lwp) WRITE(numout,*) '     ln_bt_av =.false. => No time averaging of barotropic variables '
+      ENDIF
+      !
+      !
+      IF(ln_bt_fw) THEN
+         IF(lwp) WRITE(numout,*) '     ln_bt_fw=.true.  => Forward integration of barotropic variables '
+      ELSE
+         IF(lwp) WRITE(numout,*) '     ln_bt_fw =.false.=> Centred integration of barotropic variables '
+      ENDIF
+      !
+#if defined key_agrif
+      ! Restrict the use of Agrif to the forward case only
+!!!      IF( .NOT.ln_bt_fw .AND. .NOT.Agrif_Root() )   CALL ctl_stop( 'AGRIF not implemented if ln_bt_fw=.FALSE.' )
+#endif
+      !
+      IF(lwp) WRITE(numout,*)    '     Time filter choice, nn_bt_flt: ', nn_bt_flt
+      SELECT CASE ( nn_bt_flt )
+         CASE( 0 )      ;   IF(lwp) WRITE(numout,*) '           Dirac'
+         CASE( 1 )      ;   IF(lwp) WRITE(numout,*) '           Boxcar: width = nn_baro'
+         CASE( 2 )      ;   IF(lwp) WRITE(numout,*) '           Boxcar: width = 2*nn_baro' 
+         CASE DEFAULT   ;   CALL ctl_stop( 'unrecognised value for nn_bt_flt: should 0,1, or 2' )
+      END SELECT
+      !
+      IF(lwp) WRITE(numout,*) ' '
+      IF(lwp) WRITE(numout,*) '     nn_baro = ', nn_baro
+      IF(lwp) WRITE(numout,*) '     Barotropic time step [s] is :', rdtbt
+      IF(lwp) WRITE(numout,*) '     Maximum Courant number is   :', zcmax
+      !
+      IF(lwp) WRITE(numout,*)    '     Time diffusion parameter rn_bt_alpha: ', rn_bt_alpha
+      IF ((ln_bt_av.AND.nn_bt_flt/=0).AND.(rn_bt_alpha>0._wp)) THEN
+         CALL ctl_stop( 'dynspg_ts ERROR: if rn_bt_alpha > 0, remove temporal averaging' )
+      ENDIF
+      !
+      IF( .NOT.ln_bt_av .AND. .NOT.ln_bt_fw ) THEN
+         CALL ctl_stop( 'dynspg_ts ERROR: No time averaging => only forward integration is possible' )
+      ENDIF
+      IF( zcmax>0.9_wp ) THEN
+         CALL ctl_stop( 'dynspg_ts ERROR: Maximum Courant number is greater than 0.9: Inc. nn_baro !' )          
+      ENDIF
+      !
+      !                             ! Allocate time-splitting arrays
+      IF( dyn_spg_ts_alloc() /= 0    )   CALL ctl_stop('STOP', 'dyn_spg_init: failed to allocate dynspg_ts  arrays' )
+      !
+      !                             ! read restart when needed
+      CALL ts_rst( nit000, 'READ' )
+      !
+      IF( lwxios ) THEN
+! define variables in restart file when writing with XIOS
+         CALL iom_set_rstw_var_active('ub2_b')
+         CALL iom_set_rstw_var_active('vb2_b')
+         CALL iom_set_rstw_var_active('un_bf')
+         CALL iom_set_rstw_var_active('vn_bf')
+         !
+         IF (.NOT.ln_bt_av) THEN
+            CALL iom_set_rstw_var_active('sshbb_e')
+            CALL iom_set_rstw_var_active('ubb_e')
+            CALL iom_set_rstw_var_active('vbb_e')
+            CALL iom_set_rstw_var_active('sshb_e')
+            CALL iom_set_rstw_var_active('ub_e')
+            CALL iom_set_rstw_var_active('vb_e')
+         ENDIF
+#if defined key_agrif
+         ! Save time integrated fluxes
+         IF ( .NOT.Agrif_Root() ) THEN
+            CALL iom_set_rstw_var_active('ub2_i_b')
+            CALL iom_set_rstw_var_active('vb2_i_b')
+         ENDIF
+#endif
+      ENDIF
+      !
+   END SUBROUTINE dyn_spg_ts_init
+
+   
+   SUBROUTINE dyn_cor_2d_init
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_cor_2d_init  ***
+      !!
+      !! ** Purpose : Set time splitting options
+      !! Set arrays to remove/compute coriolis trend.
+      !! Do it once during initialization if volume is fixed, else at each long time step.
+      !! Note that these arrays are also used during barotropic loop. These are however frozen
+      !! although they should be updated in the variable volume case. Not a big approximation.
+      !! To remove this approximation, copy lines below inside barotropic loop
+      !! and update depths at T-F points (ht and zhf resp.) at each barotropic time step
+      !!
+      !! Compute zwz = f / ( height of the water colomn )
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji ,jj, jk              ! dummy loop indices
+      REAL(wp) ::   z1_ht
+      REAL(wp), DIMENSION(jpi,jpj) :: zhf
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE( nvor_scheme )
+      CASE( np_EEN )                != EEN scheme using e3f (energy & enstrophy scheme)
+         SELECT CASE( nn_een_e3f )              !* ff_f/e3 at F-point
+         CASE ( 0 )                                   ! original formulation  (masked averaging of e3t divided by 4)
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zwz(ji,jj) =   ( ht_n(ji  ,jj+1) + ht_n(ji+1,jj+1) +                    &
+                       &             ht_n(ji  ,jj  ) + ht_n(ji+1,jj  )   ) * 0.25_wp  
+                  IF( zwz(ji,jj) /= 0._wp )   zwz(ji,jj) = ff_f(ji,jj) / zwz(ji,jj)
+               END DO
+            END DO
+         CASE ( 1 )                                   ! new formulation  (masked averaging of e3t divided by the sum of mask)
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zwz(ji,jj) =             (  ht_n  (ji  ,jj+1) + ht_n  (ji+1,jj+1)      &
+                       &                      + ht_n  (ji  ,jj  ) + ht_n  (ji+1,jj  )  )   &
+                       &       / ( MAX( 1._wp,  ssmask(ji  ,jj+1) + ssmask(ji+1,jj+1)      &
+                       &                      + ssmask(ji  ,jj  ) + ssmask(ji+1,jj  )  )   )
+                  IF( zwz(ji,jj) /= 0._wp )   zwz(ji,jj) = ff_f(ji,jj) / zwz(ji,jj)
+               END DO
+            END DO
+         END SELECT
+         CALL lbc_lnk( 'dynspg_ts', zwz, 'F', 1._wp )
+         !
+         ftne(1,:) = 0._wp ; ftnw(1,:) = 0._wp ; ftse(1,:) = 0._wp ; ftsw(1,:) = 0._wp
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               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
+         !
+      CASE( np_EET )                  != EEN scheme using e3t (energy conserving scheme)
+         ftne(1,:) = 0._wp ; ftnw(1,:) = 0._wp ; ftse(1,:) = 0._wp ; ftsw(1,:) = 0._wp
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               z1_ht = ssmask(ji,jj) / ( ht_n(ji,jj) + 1._wp - ssmask(ji,jj) )
+               ftne(ji,jj) = ( ff_f(ji-1,jj  ) + ff_f(ji  ,jj  ) + ff_f(ji  ,jj-1) ) * z1_ht
+               ftnw(ji,jj) = ( ff_f(ji-1,jj-1) + ff_f(ji-1,jj  ) + ff_f(ji  ,jj  ) ) * z1_ht
+               ftse(ji,jj) = ( ff_f(ji  ,jj  ) + ff_f(ji  ,jj-1) + ff_f(ji-1,jj-1) ) * z1_ht
+               ftsw(ji,jj) = ( ff_f(ji  ,jj-1) + ff_f(ji-1,jj-1) + ff_f(ji-1,jj  ) ) * z1_ht
+            END DO
+         END DO
+         !
+      CASE( np_ENE, np_ENS , np_MIX )  != all other schemes (ENE, ENS, MIX) except ENT !
+         !
+         zwz(:,:) = 0._wp
+         zhf(:,:) = 0._wp
+         
+         !!gm  assume 0 in both cases (which is almost surely WRONG ! ) as hvatf has been removed 
+!!gm    A priori a better value should be something like :
+!!gm          zhf(i,j) = masked sum of  ht(i,j) , ht(i+1,j) , ht(i,j+1) , (i+1,j+1) 
+!!gm                     divided by the sum of the corresponding mask 
+!!gm 
+!!            
+         IF( .NOT.ln_sco ) THEN
+  
+   !!gm  agree the JC comment  : this should be done in a much clear way
+  
+   ! JC: It not clear yet what should be the depth at f-points over land in z-coordinate case
+   !     Set it to zero for the time being 
+   !              IF( rn_hmin < 0._wp ) THEN    ;   jk = - INT( rn_hmin )                                      ! from a nb of level
+   !              ELSE                          ;   jk = MINLOC( gdepw_0, mask = gdepw_0 > rn_hmin, dim = 1 )  ! from a depth
+   !              ENDIF
+   !              zhf(:,:) = gdepw_0(:,:,jk+1)
+            !
+         ELSE
+            !
+            !zhf(:,:) = hbatf(:,:)
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zhf(ji,jj) =    (   ht_0  (ji,jj  ) + ht_0  (ji+1,jj  )          &
+                       &            + ht_0  (ji,jj+1) + ht_0  (ji+1,jj+1)   )      &
+                       &     / MAX(   ssmask(ji,jj  ) + ssmask(ji+1,jj  )          &
+                       &            + ssmask(ji,jj+1) + ssmask(ji+1,jj+1) , 1._wp  )
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jj = 1, jpjm1
+            zhf(:,jj) = zhf(:,jj) * (1._wp- umask(:,jj,1) * umask(:,jj+1,1))
+         END DO
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               zhf(:,jj) = zhf(:,jj) + e3f_n(:,jj,jk) * umask(:,jj,jk) * umask(:,jj+1,jk)
+            END DO
+         END DO
+         CALL lbc_lnk( 'dynspg_ts', zhf, 'F', 1._wp )
+         ! JC: TBC. hf should be greater than 0 
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zhf(ji,jj) /= 0._wp )   zwz(ji,jj) = 1._wp / zhf(ji,jj)
+            END DO
+         END DO
+         zwz(:,:) = ff_f(:,:) * zwz(:,:)
+      END SELECT
+      
+   END SUBROUTINE dyn_cor_2d_init
+
+
+
+   SUBROUTINE dyn_cor_2d( hu_n, hv_n, un_b, vn_b, zhU, zhV,    zu_trd, zv_trd   )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dyn_cor_2d  ***
+      !!
+      !! ** Purpose : Compute u and v coriolis trends
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji ,jj                             ! dummy loop indices
+      REAL(wp) ::   zx1, zx2, zy1, zy2, z1_hu, z1_hv   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: hu_n, hv_n, un_b, vn_b, zhU, zhV
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) :: zu_trd, zv_trd
+      !!----------------------------------------------------------------------
+      SELECT CASE( nvor_scheme )
+      CASE( np_ENT )                ! enstrophy conserving scheme (f-point)
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               z1_hu = ssumask(ji,jj) / ( hu_n(ji,jj) + 1._wp - ssumask(ji,jj) )
+               z1_hv = ssvmask(ji,jj) / ( hv_n(ji,jj) + 1._wp - ssvmask(ji,jj) )
+               zu_trd(ji,jj) = + r1_4 * r1_e1e2u(ji,jj) * z1_hu                    &
+                  &               * (  e1e2t(ji+1,jj)*ht_n(ji+1,jj)*ff_t(ji+1,jj) * ( vn_b(ji+1,jj) + vn_b(ji+1,jj-1) )   &
+                  &                  + e1e2t(ji  ,jj)*ht_n(ji  ,jj)*ff_t(ji  ,jj) * ( vn_b(ji  ,jj) + vn_b(ji  ,jj-1) )   )
+                  !
+               zv_trd(ji,jj) = - r1_4 * r1_e1e2v(ji,jj) * z1_hv                    &
+                  &               * (  e1e2t(ji,jj+1)*ht_n(ji,jj+1)*ff_t(ji,jj+1) * ( un_b(ji,jj+1) + un_b(ji-1,jj+1) )   & 
+                  &                  + e1e2t(ji,jj  )*ht_n(ji,jj  )*ff_t(ji,jj  ) * ( un_b(ji,jj  ) + un_b(ji-1,jj  ) )   ) 
+            END DO  
+         END DO  
+         !         
+      CASE( np_ENE , np_MIX )        ! energy conserving scheme (t-point) ENE or MIX
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zy1 = ( zhV(ji,jj-1) + zhV(ji+1,jj-1) ) * r1_e1u(ji,jj)
+               zy2 = ( zhV(ji,jj  ) + zhV(ji+1,jj  ) ) * r1_e1u(ji,jj)
+               zx1 = ( zhU(ji-1,jj) + zhU(ji-1,jj+1) ) * r1_e2v(ji,jj)
+               zx2 = ( zhU(ji  ,jj) + zhU(ji  ,jj+1) ) * r1_e2v(ji,jj)
+               ! energy conserving formulation for planetary vorticity term
+               zu_trd(ji,jj) =   r1_4 * ( zwz(ji  ,jj-1) * zy1 + zwz(ji,jj) * zy2 )
+               zv_trd(ji,jj) = - r1_4 * ( zwz(ji-1,jj  ) * zx1 + zwz(ji,jj) * zx2 )
+            END DO
+         END DO
+         !
+      CASE( np_ENS )                ! enstrophy conserving scheme (f-point)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zy1 =   r1_8 * ( zhV(ji  ,jj-1) + zhV(ji+1,jj-1) &
+                 &            + zhV(ji  ,jj  ) + zhV(ji+1,jj  ) ) * r1_e1u(ji,jj)
+               zx1 = - r1_8 * ( zhU(ji-1,jj  ) + zhU(ji-1,jj+1) &
+                 &            + zhU(ji  ,jj  ) + zhU(ji  ,jj+1) ) * r1_e2v(ji,jj)
+               zu_trd(ji,jj)  = zy1 * ( zwz(ji  ,jj-1) + zwz(ji,jj) )
+               zv_trd(ji,jj)  = zx1 * ( zwz(ji-1,jj  ) + zwz(ji,jj) )
+            END DO
+         END DO
+         !
+      CASE( np_EET , np_EEN )      ! energy & enstrophy scheme (using e3t or e3f)         
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zu_trd(ji,jj) = + r1_12 * r1_e1u(ji,jj) * (  ftne(ji,jj  ) * zhV(ji  ,jj  ) &
+                &                                         + ftnw(ji+1,jj) * zhV(ji+1,jj  ) &
+                &                                         + ftse(ji,jj  ) * zhV(ji  ,jj-1) &
+                &                                         + ftsw(ji+1,jj) * zhV(ji+1,jj-1) )
+               zv_trd(ji,jj) = - r1_12 * r1_e2v(ji,jj) * (  ftsw(ji,jj+1) * zhU(ji-1,jj+1) &
+                &                                         + ftse(ji,jj+1) * zhU(ji  ,jj+1) &
+                &                                         + ftnw(ji,jj  ) * zhU(ji-1,jj  ) &
+                &                                         + ftne(ji,jj  ) * zhU(ji  ,jj  ) )
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+   END SUBROUTINE dyn_cor_2D
+
+
+   SUBROUTINE wad_tmsk( pssh, ptmsk )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE wad_lmt  ***
+      !!                    
+      !! ** Purpose :   set wetting & drying mask at tracer points 
+      !!              for the current barotropic sub-step 
+      !!
+      !! ** Method  :   ??? 
+      !!
+      !! ** Action  :  ptmsk : wetting & drying t-mask
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   pssh    !
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::   ptmsk   !
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_wd_dl_rmp ) THEN     
+         DO jj = 1, jpj
+            DO ji = 1, jpi                    
+               IF    ( pssh(ji,jj) + ht_0(ji,jj) >  2._wp * rn_wdmin1 ) THEN 
+                  !           IF    ( pssh(ji,jj) + ht_0(ji,jj) >          rn_wdmin2 ) THEN 
+                  ptmsk(ji,jj) = 1._wp
+               ELSEIF( pssh(ji,jj) + ht_0(ji,jj) >          rn_wdmin1 ) THEN
+                  ptmsk(ji,jj) = TANH( 50._wp*( ( pssh(ji,jj) + ht_0(ji,jj) -  rn_wdmin1 )*r_rn_wdmin1) )
+               ELSE 
+                  ptmsk(ji,jj) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      ELSE  
+         DO jj = 1, jpj
+            DO ji = 1, jpi                              
+               IF ( pssh(ji,jj) + ht_0(ji,jj) >  rn_wdmin1 ) THEN   ;   ptmsk(ji,jj) = 1._wp
+               ELSE                                                 ;   ptmsk(ji,jj) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE wad_tmsk
+
+
+   SUBROUTINE wad_Umsk( pTmsk, phU, phV, pu, pv, pUmsk, pVmsk )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE wad_lmt  ***
+      !!                    
+      !! ** Purpose :   set wetting & drying mask at tracer points 
+      !!              for the current barotropic sub-step 
+      !!
+      !! ** Method  :   ??? 
+      !!
+      !! ** Action  :  ptmsk : wetting & drying t-mask
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   pTmsk              ! W & D t-mask
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   phU, phV, pu, pv   ! ocean velocities and transports
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   pUmsk, pVmsk       ! W & D u- and v-mask
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpim1   ! not jpi-column
+            IF ( phU(ji,jj) > 0._wp ) THEN   ;   pUmsk(ji,jj) = pTmsk(ji  ,jj) 
+            ELSE                             ;   pUmsk(ji,jj) = pTmsk(ji+1,jj)  
+            ENDIF
+            phU(ji,jj) = pUmsk(ji,jj)*phU(ji,jj)
+            pu (ji,jj) = pUmsk(ji,jj)*pu (ji,jj)
+         END DO
+      END DO
+      !
+      DO jj = 1, jpjm1   ! not jpj-row
+         DO ji = 1, jpi
+            IF ( phV(ji,jj) > 0._wp ) THEN   ;   pVmsk(ji,jj) = pTmsk(ji,jj  )
+            ELSE                             ;   pVmsk(ji,jj) = pTmsk(ji,jj+1)  
+            ENDIF
+            phV(ji,jj) = pVmsk(ji,jj)*phV(ji,jj) 
+            pv (ji,jj) = pVmsk(ji,jj)*pv (ji,jj)
+         END DO
+      END DO
+      !
+   END SUBROUTINE wad_Umsk
+
+
+   SUBROUTINE wad_spg( sshn, zcpx, zcpy )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE  wad_sp  ***
+      !!
+      !! ** Purpose : 
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji ,jj               ! dummy loop indices
+      LOGICAL  ::   ll_tmp1, ll_tmp2
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: sshn
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) :: zcpx, zcpy
+      !!----------------------------------------------------------------------
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1 
+            ll_tmp1 = MIN(  sshn(ji,jj)               ,  sshn(ji+1,jj) ) >                &
+                 &      MAX( -ht_0(ji,jj)               , -ht_0(ji+1,jj) ) .AND.            &
+                 &      MAX(  sshn(ji,jj) + ht_0(ji,jj) ,  sshn(ji+1,jj) + ht_0(ji+1,jj) )  &
+                 &                                                         > rn_wdmin1 + rn_wdmin2
+            ll_tmp2 = ( ABS( sshn(ji+1,jj)            -  sshn(ji  ,jj))  > 1.E-12 ).AND.( &
+                 &      MAX(   sshn(ji,jj)              ,  sshn(ji+1,jj) ) >                &
+                 &      MAX(  -ht_0(ji,jj)              , -ht_0(ji+1,jj) ) + rn_wdmin1 + rn_wdmin2 )
+            IF(ll_tmp1) THEN
+               zcpx(ji,jj) = 1.0_wp
+            ELSEIF(ll_tmp2) THEN
+               ! no worries about  sshn(ji+1,jj) -  sshn(ji  ,jj) = 0, it won't happen ! here
+               zcpx(ji,jj) = ABS( (sshn(ji+1,jj) + ht_0(ji+1,jj) - sshn(ji,jj) - ht_0(ji,jj)) &
+                    &    / (sshn(ji+1,jj) - sshn(ji  ,jj)) )
+               zcpx(ji,jj) = max(min( zcpx(ji,jj) , 1.0_wp),0.0_wp)
+            ELSE
+               zcpx(ji,jj) = 0._wp
+            ENDIF
+            !
+            ll_tmp1 = MIN(  sshn(ji,jj)               ,  sshn(ji,jj+1) ) >                &
+                 &      MAX( -ht_0(ji,jj)               , -ht_0(ji,jj+1) ) .AND.            &
+                 &      MAX(  sshn(ji,jj) + ht_0(ji,jj) ,  sshn(ji,jj+1) + ht_0(ji,jj+1) )  &
+                 &                                                       > rn_wdmin1 + rn_wdmin2
+            ll_tmp2 = ( ABS( sshn(ji,jj)              -  sshn(ji,jj+1))  > 1.E-12 ).AND.( &
+                 &      MAX(   sshn(ji,jj)              ,  sshn(ji,jj+1) ) >                &
+                 &      MAX(  -ht_0(ji,jj)              , -ht_0(ji,jj+1) ) + rn_wdmin1 + rn_wdmin2 )
+            
+            IF(ll_tmp1) THEN
+               zcpy(ji,jj) = 1.0_wp
+            ELSE IF(ll_tmp2) THEN
+               ! no worries about  sshn(ji,jj+1) -  sshn(ji,jj  ) = 0, it won't happen ! here
+               zcpy(ji,jj) = ABS( (sshn(ji,jj+1) + ht_0(ji,jj+1) - sshn(ji,jj) - ht_0(ji,jj)) &
+                    &             / (sshn(ji,jj+1) - sshn(ji,jj  )) )
+               zcpy(ji,jj) = MAX(  0._wp , MIN( zcpy(ji,jj) , 1.0_wp )  )
+            ELSE
+               zcpy(ji,jj) = 0._wp
+            ENDIF
+         END DO
+      END DO
+            
+   END SUBROUTINE wad_spg
+     
+
+
+   SUBROUTINE dyn_drg_init( pu_RHSi, pv_RHSi, pCdU_u, pCdU_v )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_drg_init  ***
+      !!                    
+      !! ** Purpose : - add the baroclinic top/bottom drag contribution to 
+      !!              the baroclinic part of the barotropic RHS
+      !!              - compute the barotropic drag coefficients
+      !!
+      !! ** Method  :   computation done over the INNER domain only 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   pu_RHSi, pv_RHSi   ! baroclinic part of the barotropic RHS
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::   pCdU_u , pCdU_v    ! barotropic drag coefficients
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      INTEGER  ::   ikbu, ikbv, iktu, iktv
+      REAL(wp) ::   zztmp
+      REAL(wp), DIMENSION(jpi,jpj) ::   zu_i, zv_i
+      !!----------------------------------------------------------------------
+      !
+      !                    !==  Set the barotropic drag coef.  ==!
+      !
+      IF( ln_isfcav.OR.ln_drgice_imp ) THEN          ! top+bottom friction (ocean cavities)
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1     ! INNER domain
+               pCdU_u(ji,jj) = r1_2*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) + rCdU_top(ji+1,jj)+rCdU_top(ji,jj) )
+               pCdU_v(ji,jj) = r1_2*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) + rCdU_top(ji,jj+1)+rCdU_top(ji,jj) )
+            END DO
+         END DO
+      ELSE                          ! bottom friction only
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1  ! INNER domain
+               pCdU_u(ji,jj) = r1_2*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) )
+               pCdU_v(ji,jj) = r1_2*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) )
+            END DO
+         END DO
+      ENDIF
+      !
+      !                    !==  BOTTOM stress contribution from baroclinic velocities  ==!
+      !
+      IF( ln_bt_fw ) THEN                 ! FORWARD integration: use NOW bottom baroclinic velocities
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1  ! INNER domain
+               ikbu = mbku(ji,jj)       
+               ikbv = mbkv(ji,jj)    
+               zu_i(ji,jj) = un(ji,jj,ikbu) - un_b(ji,jj)
+               zv_i(ji,jj) = vn(ji,jj,ikbv) - vn_b(ji,jj)
+            END DO
+         END DO
+      ELSE                                ! CENTRED integration: use BEFORE bottom baroclinic velocities
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! INNER domain
+               ikbu = mbku(ji,jj)       
+               ikbv = mbkv(ji,jj)    
+               zu_i(ji,jj) = ub(ji,jj,ikbu) - ub_b(ji,jj)
+               zv_i(ji,jj) = vb(ji,jj,ikbv) - vb_b(ji,jj)
+            END DO
+         END DO
+      ENDIF
+      !
+      IF( ln_wd_il ) THEN      ! W/D : use the "clipped" bottom friction   !!gm   explain WHY, please !
+         zztmp = -1._wp / rdtbt
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1    ! INNER domain
+               pu_RHSi(ji,jj) = pu_RHSi(ji,jj) + zu_i(ji,jj) *  wdrampu(ji,jj) * MAX(                                 & 
+                    &                              r1_hu_n(ji,jj) * r1_2*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) , zztmp  )
+               pv_RHSi(ji,jj) = pv_RHSi(ji,jj) + zv_i(ji,jj) *  wdrampv(ji,jj) * MAX(                                 & 
+                    &                              r1_hv_n(ji,jj) * r1_2*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) , zztmp  )
+            END DO
+         END DO
+      ELSE                    ! use "unclipped" drag (even if explicit friction is used in 3D calculation)
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1    ! INNER domain
+               pu_RHSi(ji,jj) = pu_RHSi(ji,jj) + r1_hu_n(ji,jj) * r1_2*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) * zu_i(ji,jj)
+               pv_RHSi(ji,jj) = pv_RHSi(ji,jj) + r1_hv_n(ji,jj) * r1_2*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) * zv_i(ji,jj)
+            END DO
+         END DO
+      END IF
+      !
+      !                    !==  TOP stress contribution from baroclinic velocities  ==!   (no W/D case)
+      !
+      IF( ln_isfcav.OR.ln_drgice_imp ) THEN
+         !
+         IF( ln_bt_fw ) THEN                ! FORWARD integration: use NOW top baroclinic velocity
+            
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1   ! INNER domain
+                  iktu = miku(ji,jj)
+                  iktv = mikv(ji,jj)
+                  zu_i(ji,jj) = un(ji,jj,iktu) - un_b(ji,jj)
+                  zv_i(ji,jj) = vn(ji,jj,iktv) - vn_b(ji,jj)
+               END DO
+            END DO
+         ELSE                                ! CENTRED integration: use BEFORE top baroclinic velocity
+            
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1      ! INNER domain
+                  iktu = miku(ji,jj)
+                  iktv = mikv(ji,jj)
+                  zu_i(ji,jj) = ub(ji,jj,iktu) - ub_b(ji,jj)
+                  zv_i(ji,jj) = vb(ji,jj,iktv) - vb_b(ji,jj)
+               END DO
+            END DO
+         ENDIF
+         !
+         !                    ! use "unclipped" top drag (even if explicit friction is used in 3D calculation)
+         
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1    ! INNER domain
+               pu_RHSi(ji,jj) = pu_RHSi(ji,jj) + r1_hu_n(ji,jj) * r1_2*( rCdU_top(ji+1,jj)+rCdU_top(ji,jj) ) * zu_i(ji,jj)
+               pv_RHSi(ji,jj) = pv_RHSi(ji,jj) + r1_hv_n(ji,jj) * r1_2*( rCdU_top(ji,jj+1)+rCdU_top(ji,jj) ) * zv_i(ji,jj)
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+   END SUBROUTINE dyn_drg_init
+
+   SUBROUTINE ts_bck_interp( jn, ll_init,       &   ! <== in
+      &                      za0, za1, za2, za3 )   ! ==> out
+      !!----------------------------------------------------------------------
+      INTEGER ,INTENT(in   ) ::   jn                   ! index of sub time step
+      LOGICAL ,INTENT(in   ) ::   ll_init              !
+      REAL(wp),INTENT(  out) ::   za0, za1, za2, za3   ! Half-step back interpolation coefficient
+      !
+      REAL(wp) ::   zepsilon, zgamma                   !   -      -
+      !!----------------------------------------------------------------------
+      !                             ! set Half-step back interpolation coefficient
+      IF    ( jn==1 .AND. ll_init ) THEN   !* Forward-backward
+         za0 = 1._wp                        
+         za1 = 0._wp                           
+         za2 = 0._wp
+         za3 = 0._wp
+      ELSEIF( jn==2 .AND. ll_init ) THEN   !* AB2-AM3 Coefficients; bet=0 ; gam=-1/6 ; eps=1/12
+         za0 = 1.0833333333333_wp                 ! za0 = 1-gam-eps
+         za1 =-0.1666666666666_wp                 ! za1 = gam
+         za2 = 0.0833333333333_wp                 ! za2 = eps
+         za3 = 0._wp              
+      ELSE                                 !* AB3-AM4 Coefficients; bet=0.281105 ; eps=0.013 ; gam=0.0880 
+         IF( rn_bt_alpha == 0._wp ) THEN      ! Time diffusion  
+            za0 = 0.614_wp                        ! za0 = 1/2 +   gam + 2*eps
+            za1 = 0.285_wp                        ! za1 = 1/2 - 2*gam - 3*eps
+            za2 = 0.088_wp                        ! za2 = gam
+            za3 = 0.013_wp                        ! za3 = eps
+         ELSE                                 ! no time diffusion
+            zepsilon = 0.00976186_wp - 0.13451357_wp * rn_bt_alpha
+            zgamma   = 0.08344500_wp - 0.51358400_wp * rn_bt_alpha
+            za0 = 0.5_wp + zgamma + 2._wp * rn_bt_alpha + 2._wp * zepsilon
+            za1 = 1._wp - za0 - zgamma - zepsilon
+            za2 = zgamma
+            za3 = zepsilon
+         ENDIF 
+      ENDIF
+   END SUBROUTINE ts_bck_interp
+
+
+   !!======================================================================
+END MODULE dynspg_ts
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynvor.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynvor.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynvor.F90	(revision 14097)
@@ -0,0 +1,958 @@
+MODULE dynvor
+   !!======================================================================
+   !!                       ***  MODULE  dynvor  ***
+   !! Ocean dynamics: Update the momentum trend with the relative and
+   !!                 planetary vorticity trends
+   !!======================================================================
+   !! History :  OPA  ! 1989-12  (P. Andrich)  vor_ens: Original code
+   !!            5.0  ! 1991-11  (G. Madec)  vor_ene, vor_mix: Original code
+   !!            6.0  ! 1996-01  (G. Madec)  s-coord, suppress work arrays
+   !!   NEMO     0.5  ! 2002-08  (G. Madec)  F90: Free form and module
+   !!            1.0  ! 2004-02  (G. Madec)  vor_een: Original code
+   !!             -   ! 2003-08  (G. Madec)  add vor_ctl
+   !!             -   ! 2005-11  (G. Madec)  add dyn_vor (new step architecture)
+   !!            2.0  ! 2006-11  (G. Madec)  flux form advection: add metric term
+   !!            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 
+   !!             -   ! 2014-06  (G. Madec)  suppression of velocity curl from in-core memory
+   !!             -   ! 2016-12  (G. Madec, E. Clementi) add Stokes-Coriolis trends (ln_stcor=T)
+   !!            4.0  ! 2017-07  (G. Madec)  linear dynamics + trends diag. with Stokes-Coriolis
+   !!             -   ! 2018-03  (G. Madec)  add two new schemes (ln_dynvor_enT and ln_dynvor_eet)
+   !!             -   ! 2018-04  (G. Madec)  add pre-computed gradient for metric term calculation
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_vor       : Update the momentum trend with the vorticity trend
+   !!       vor_ens   : enstrophy conserving scheme       (ln_dynvor_ens=T)
+   !!       vor_ene   : energy conserving scheme          (ln_dynvor_ene=T)
+   !!       vor_een   : energy and enstrophy conserving   (ln_dynvor_een=T)
+   !!   dyn_vor_init  : set and control of the different vorticity option
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE dommsk         ! ocean mask
+   USE dynadv         ! momentum advection
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   USE sbcwave        ! Surface Waves (add Stokes-Coriolis force)
+   USE sbc_oce , ONLY : ln_stcor    ! use Stoke-Coriolis force
+   !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_vor        ! routine called by step.F90
+   PUBLIC   dyn_vor_init   ! routine called by nemogcm.F90
+
+   !                                   !!* Namelist namdyn_vor: vorticity term
+   LOGICAL, PUBLIC ::   ln_dynvor_ens   !: enstrophy conserving scheme          (ENS)
+   LOGICAL, PUBLIC ::   ln_dynvor_ene   !: f-point energy conserving scheme     (ENE)
+   LOGICAL, PUBLIC ::   ln_dynvor_enT   !: t-point energy conserving scheme     (ENT)
+   LOGICAL, PUBLIC ::   ln_dynvor_eeT   !: t-point energy conserving scheme     (EET)
+   LOGICAL, PUBLIC ::   ln_dynvor_een   !: energy & enstrophy conserving scheme (EEN)
+   INTEGER, PUBLIC ::      nn_een_e3f      !: e3f=masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+   LOGICAL, PUBLIC ::   ln_dynvor_mix   !: mixed scheme                         (MIX)
+   LOGICAL, PUBLIC ::   ln_dynvor_msk   !: vorticity multiplied by fmask (=T) or not (=F) (all vorticity schemes)
+
+   INTEGER, PUBLIC ::   nvor_scheme     !: choice of the type of advection scheme
+   !                                       ! associated indices:
+   INTEGER, PUBLIC, PARAMETER ::   np_ENS = 0   ! ENS scheme
+   INTEGER, PUBLIC, PARAMETER ::   np_ENE = 1   ! ENE scheme
+   INTEGER, PUBLIC, PARAMETER ::   np_ENT = 2   ! ENT scheme (t-point vorticity)
+   INTEGER, PUBLIC, PARAMETER ::   np_EET = 3   ! EET scheme (EEN using e3t)
+   INTEGER, PUBLIC, PARAMETER ::   np_EEN = 4   ! EEN scheme
+   INTEGER, PUBLIC, PARAMETER ::   np_MIX = 5   ! MIX scheme
+
+   INTEGER ::   ncor, nrvm, ntot   ! choice of calculated vorticity 
+   !                               ! associated indices:
+   INTEGER, PUBLIC, PARAMETER ::   np_COR = 1         ! Coriolis (planetary)
+   INTEGER, PUBLIC, PARAMETER ::   np_RVO = 2         ! relative vorticity
+   INTEGER, PUBLIC, PARAMETER ::   np_MET = 3         ! metric term
+   INTEGER, PUBLIC, PARAMETER ::   np_CRV = 4         ! relative + planetary (total vorticity)
+   INTEGER, PUBLIC, PARAMETER ::   np_CME = 5         ! Coriolis + metric term
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   di_e2u_2        ! = di(e2u)/2          used in T-point metric term calculation
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   dj_e1v_2        ! = dj(e1v)/2           -        -      -       - 
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   di_e2v_2e1e2f   ! = di(e2u)/(2*e1e2f)  used in F-point metric term calculation
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   dj_e1u_2e1e2f   ! = dj(e1v)/(2*e1e2f)   -        -      -       - 
+   
+   REAL(wp) ::   r1_4  = 0.250_wp         ! =1/4
+   REAL(wp) ::   r1_8  = 0.125_wp         ! =1/8
+   REAL(wp) ::   r1_12 = 1._wp / 12._wp   ! 1/12
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_vor( kt )
+      !!----------------------------------------------------------------------
+      !!
+      !! ** Purpose :   compute the lateral ocean tracer physics.
+      !!
+      !! ** Action : - Update (ua,va) with the now vorticity term trend
+      !!             - save the trends in (ztrdu,ztrdv) in 2 parts (relative
+      !!               and planetary vorticity trends) and send them to trd_dyn 
+      !!               for futher diagnostics (l_trddyn=T)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  ztrdu, ztrdv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_vor')
+      !
+      IF( l_trddyn ) THEN     !==  trend diagnostics case : split the added trend in two parts  ==!
+         !
+         ALLOCATE( ztrdu(jpi,jpj,jpk), ztrdv(jpi,jpj,jpk) )
+         !
+         ztrdu(:,:,:) = ua(:,:,:)            !* planetary vorticity trend (including Stokes-Coriolis force)
+         ztrdv(:,:,:) = va(:,:,:)
+         SELECT CASE( nvor_scheme )
+         CASE( np_ENS )           ;   CALL vor_ens( kt, ncor, un , vn , ua, va )   ! enstrophy conserving scheme
+            IF( ln_stcor )            CALL vor_ens( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_ENE, np_MIX )   ;   CALL vor_ene( kt, ncor, un , vn , ua, va )   ! energy conserving scheme
+            IF( ln_stcor )            CALL vor_ene( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_ENT )           ;   CALL vor_enT( kt, ncor, un , vn , ua, va )   ! energy conserving scheme (T-pts)
+            IF( ln_stcor )            CALL vor_enT( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_EET )           ;   CALL vor_eeT( kt, ncor, un , vn , ua, va )   ! energy conserving scheme (een with e3t)
+            IF( ln_stcor )            CALL vor_eeT( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_EEN )           ;   CALL vor_een( kt, ncor, un , vn , ua, va )   ! energy & enstrophy scheme
+            IF( ln_stcor )            CALL vor_een( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         END SELECT
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_pvo, kt )
+         !
+         IF( n_dynadv /= np_LIN_dyn ) THEN   !* relative vorticity or metric trend (only in non-linear case)
+            ztrdu(:,:,:) = ua(:,:,:)
+            ztrdv(:,:,:) = va(:,:,:)
+            SELECT CASE( nvor_scheme )
+            CASE( np_ENT )           ;   CALL vor_enT( kt, nrvm, un , vn , ua, va )  ! energy conserving scheme (T-pts)
+            CASE( np_EET )           ;   CALL vor_eeT( kt, nrvm, un , vn , ua, va )  ! energy conserving scheme (een with e3t)
+            CASE( np_ENE )           ;   CALL vor_ene( kt, nrvm, un , vn , ua, va )  ! energy conserving scheme
+            CASE( np_ENS, np_MIX )   ;   CALL vor_ens( kt, nrvm, un , vn , ua, va )  ! enstrophy conserving scheme
+            CASE( np_EEN )           ;   CALL vor_een( kt, nrvm, un , vn , ua, va )  ! energy & enstrophy scheme
+            END SELECT
+            ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+            ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_rvo, kt )
+         ENDIF
+         !
+         DEALLOCATE( ztrdu, ztrdv )
+         !
+      ELSE              !==  total vorticity trend added to the general trend  ==!
+         !
+         SELECT CASE ( nvor_scheme )      !==  vorticity trend added to the general trend  ==!
+         CASE( np_ENT )                        !* energy conserving scheme  (T-pts)
+                             CALL vor_enT( kt, ntot, un , vn , ua, va )   ! total vorticity trend
+            IF( ln_stcor )   CALL vor_enT( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_EET )                        !* energy conserving scheme (een scheme using e3t)
+                             CALL vor_eeT( kt, ntot, un , vn , ua, va )   ! total vorticity trend
+            IF( ln_stcor )   CALL vor_eeT( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_ENE )                        !* energy conserving scheme
+                             CALL vor_ene( kt, ntot, un , vn , ua, va )   ! total vorticity trend
+            IF( ln_stcor )   CALL vor_ene( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_ENS )                        !* enstrophy conserving scheme
+                             CALL vor_ens( kt, ntot, un , vn , ua, va )  ! total vorticity trend
+            IF( ln_stcor )   CALL vor_ens( kt, ncor, usd, vsd, ua, va )  ! add the Stokes-Coriolis trend
+         CASE( np_MIX )                        !* mixed ene-ens scheme
+                             CALL vor_ens( kt, nrvm, un , vn , ua, va )   ! relative vorticity or metric trend (ens)
+                             CALL vor_ene( kt, ncor, un , vn , ua, va )   ! planetary vorticity trend (ene)
+            IF( ln_stcor )   CALL vor_ene( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         CASE( np_EEN )                        !* energy and enstrophy conserving scheme
+                             CALL vor_een( kt, ntot, un , vn , ua, va )   ! total vorticity trend
+            IF( ln_stcor )   CALL vor_een( kt, ncor, usd, vsd, ua, va )   ! add the Stokes-Coriolis trend
+         END SELECT
+         !
+      ENDIF
+      !
+      !                       ! print sum trends (used for debugging)
+      IF(ln_ctl) CALL prt_ctl( tab3d_1=ua, clinfo1=' vor  - Ua: ', mask1=umask,               &
+         &                     tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_vor')
+      !
+   END SUBROUTINE dyn_vor
+
+
+   SUBROUTINE vor_enT( kt, kvor, pu, pv, pu_rhs, pv_rhs )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE vor_enT  ***
+      !!
+      !! ** Purpose :   Compute the now total vorticity trend and add it to 
+      !!      the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time) 
+      !!       and t-point evaluation of vorticity (planetary and relative).
+      !!       conserves the horizontal kinetic energy.
+      !!         The general trend of momentum is increased due to the vorticity 
+      !!       term which is given by:
+      !!          voru = 1/bu  mj[ ( mi(mj(bf*rvor))+bt*f_t)/e3t  mj[vn] ]
+      !!          vorv = 1/bv  mi[ ( mi(mj(bf*rvor))+bt*f_t)/e3f  mj[un] ]
+      !!       where rvor is the relative vorticity at f-point
+      !!
+      !! ** Action : - Update (ua,va) with the now vorticity term trend
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt               ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kvor             ! total, planetary, relative, or metric
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pu, pv           ! now velocities
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pu_rhs, pv_rhs   ! total v-trend
+      !
+      INTEGER  ::   ji, jj, jk           ! dummy loop indices
+      REAL(wp) ::   zx1, zy1, zx2, zy2   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zwx, zwy, zwt   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz             ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:vor_enT : vorticity term: t-point energy conserving scheme'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      !
+      SELECT CASE( kvor )                 !==  volume weighted vorticity considered  ==!
+      CASE ( np_RVO )                           !* relative vorticity
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zwz(ji,jj,jk) = (  e2v(ji+1,jj) * pv(ji+1,jj,jk) - e2v(ji,jj) * pv(ji,jj,jk)  &
+                     &             - e1u(ji,jj+1) * pu(ji,jj+1,jk) + e1u(ji,jj) * pu(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+            IF( ln_dynvor_msk ) THEN                     ! mask/unmask relative vorticity 
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zwz(ji,jj,jk) = zwz(ji,jj,jk) * fmask(ji,jj,jk)
+                  END DO
+               END DO
+            ENDIF
+         END DO
+
+         CALL lbc_lnk( 'dynvor', zwz, 'F', 1. )
+
+      CASE ( np_CRV )                           !* Coriolis + relative vorticity
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1                          ! relative vorticity
+                  zwz(ji,jj,jk) = (   e2v(ji+1,jj) * pv(ji+1,jj,jk) - e2v(ji,jj) * pv(ji,jj,jk)   &
+                     &              - e1u(ji,jj+1) * pu(ji,jj+1,jk) + e1u(ji,jj) * pu(ji,jj,jk)   ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+            IF( ln_dynvor_msk ) THEN                     ! mask/unmask relative vorticity 
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zwz(ji,jj,jk) = zwz(ji,jj,jk) * fmask(ji,jj,jk)
+                  END DO
+               END DO
+            ENDIF
+         END DO
+
+         CALL lbc_lnk( 'dynvor', zwz, 'F', 1. )
+
+      END SELECT
+
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+      !                                                ! ===============
+
+         SELECT CASE( kvor )                 !==  volume weighted vorticity considered  ==!
+         CASE ( np_COR )                           !* Coriolis (planetary vorticity)
+            zwt(:,:) = ff_t(:,:) * e1e2t(:,:)*e3t_n(:,:,jk)
+         CASE ( np_RVO )                           !* relative vorticity
+            DO jj = 2, jpj
+               DO ji = 2, jpi   ! vector opt.
+                  zwt(ji,jj) = r1_4 * (   zwz(ji-1,jj  ,jk) + zwz(ji,jj  ,jk)   &
+                     &                  + zwz(ji-1,jj-1,jk) + zwz(ji,jj-1,jk) ) * e1e2t(ji,jj)*e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         CASE ( np_MET )                           !* metric term
+            DO jj = 2, jpj
+               DO ji = 2, jpi
+                  zwt(ji,jj) = (   ( pv(ji,jj,jk) + pv(ji,jj-1,jk) ) * di_e2u_2(ji,jj)   &
+                     &           - ( pu(ji,jj,jk) + pu(ji-1,jj,jk) ) * dj_e1v_2(ji,jj)   ) * e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         CASE ( np_CRV )                           !* Coriolis + relative vorticity
+            DO jj = 2, jpj
+               DO ji = 2, jpi   ! vector opt.
+                  zwt(ji,jj) = (  ff_t(ji,jj) + r1_4 * ( zwz(ji-1,jj  ,jk) + zwz(ji,jj  ,jk)    &
+                     &                                 + zwz(ji-1,jj-1,jk) + zwz(ji,jj-1,jk) )  ) * e1e2t(ji,jj)*e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         CASE ( np_CME )                           !* Coriolis + metric
+            DO jj = 2, jpj
+               DO ji = 2, jpi   ! vector opt.
+                  zwt(ji,jj) = (  ff_t(ji,jj) * e1e2t(ji,jj)                           &
+                       &        + ( pv(ji,jj,jk) + pv(ji,jj-1,jk) ) * di_e2u_2(ji,jj)  &
+                       &        - ( pu(ji,jj,jk) + pu(ji-1,jj,jk) ) * dj_e1v_2(ji,jj)  ) * e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         CASE DEFAULT                                             ! error
+            CALL ctl_stop('STOP','dyn_vor: wrong value for kvor'  )
+         END SELECT
+         !
+         !                                   !==  compute and add the vorticity term trend  =!
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1   ! vector opt.
+               pu_rhs(ji,jj,jk) = pu_rhs(ji,jj,jk) + r1_4 * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)                    &
+                  &                                * (  zwt(ji+1,jj) * ( pv(ji+1,jj,jk) + pv(ji+1,jj-1,jk) )   &
+                  &                                   + zwt(ji  ,jj) * ( pv(ji  ,jj,jk) + pv(ji  ,jj-1,jk) )   )
+                  !
+               pv_rhs(ji,jj,jk) = pv_rhs(ji,jj,jk) - r1_4 * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)                    &
+                  &                                * (  zwt(ji,jj+1) * ( pu(ji,jj+1,jk) + pu(ji-1,jj+1,jk) )   & 
+                  &                                   + zwt(ji,jj  ) * ( pu(ji,jj  ,jk) + pu(ji-1,jj  ,jk) )   ) 
+            END DO  
+         END DO  
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE vor_enT
+
+
+   SUBROUTINE vor_ene( kt, kvor, pun, pvn, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE vor_ene  ***
+      !!
+      !! ** Purpose :   Compute the now total vorticity trend and add it to 
+      !!      the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time) 
+      !!       and the Sadourny (1975) flux form formulation : conserves the
+      !!       horizontal kinetic energy.
+      !!         The general trend of momentum is increased due to the vorticity 
+      !!       term which is given by:
+      !!          voru = 1/e1u  mj-1[ (rvor+f)/e3f  mi(e1v*e3v vn) ]
+      !!          vorv = 1/e2v  mi-1[ (rvor+f)/e3f  mj(e2u*e3u un) ]
+      !!       where rvor is the relative vorticity
+      !!
+      !! ** Action : - Update (ua,va) with the now vorticity term trend
+      !!
+      !! References : Sadourny, r., 1975, j. atmos. sciences, 32, 680-689.
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt          ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kvor        ! total, planetary, relative, or metric
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pun, pvn    ! now velocities
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva    ! total v-trend
+      !
+      INTEGER  ::   ji, jj, jk           ! dummy loop indices
+      REAL(wp) ::   zx1, zy1, zx2, zy2   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwx, zwy, zwz   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:vor_ene : vorticity term: energy conserving scheme'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         !
+         SELECT CASE( kvor )                 !==  vorticity considered  ==!
+         CASE ( np_COR )                           !* Coriolis (planetary vorticity)
+            zwz(:,:) = ff_f(:,:) 
+         CASE ( np_RVO )                           !* relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = (  e2v(ji+1,jj  ) * pvn(ji+1,jj  ,jk) - e2v(ji,jj) * pvn(ji,jj,jk)    &
+                     &          - e1u(ji  ,jj+1) * pun(ji  ,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_MET )                           !* metric term
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &       - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CRV )                           !* Coriolis + relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ff_f(ji,jj) + (  e2v(ji+1,jj) * pvn(ji+1,jj,jk) - e2v(ji,jj) * pvn(ji,jj,jk)      &
+                     &                        - e1u(ji,jj+1) * pun(ji,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CME )                           !* Coriolis + metric
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ff_f(ji,jj) + ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &                     - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE DEFAULT                                             ! error
+            CALL ctl_stop('STOP','dyn_vor: wrong value for kvor'  )
+         END SELECT
+         !
+         IF( ln_dynvor_msk ) THEN          !==  mask/unmask vorticity ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = zwz(ji,jj) * fmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+
+         IF( ln_sco ) THEN
+            zwz(:,:) = zwz(:,:) / e3f_n(:,:,jk)
+            zwx(:,:) = e2u(:,:) * e3u_n(:,:,jk) * pun(:,:,jk)
+            zwy(:,:) = e1v(:,:) * e3v_n(:,:,jk) * pvn(:,:,jk)
+         ELSE
+            zwx(:,:) = e2u(:,:) * pun(:,:,jk)
+            zwy(:,:) = e1v(:,:) * pvn(:,:,jk)
+         ENDIF
+         !                                   !==  compute and add the vorticity term trend  =!
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zy1 = zwy(ji,jj-1) + zwy(ji+1,jj-1)
+               zy2 = zwy(ji,jj  ) + zwy(ji+1,jj  )
+               zx1 = zwx(ji-1,jj) + zwx(ji-1,jj+1)
+               zx2 = zwx(ji  ,jj) + zwx(ji  ,jj+1)
+               pua(ji,jj,jk) = pua(ji,jj,jk) + r1_4 * r1_e1u(ji,jj) * ( zwz(ji  ,jj-1) * zy1 + zwz(ji,jj) * zy2 )
+               pva(ji,jj,jk) = pva(ji,jj,jk) - r1_4 * r1_e2v(ji,jj) * ( zwz(ji-1,jj  ) * zx1 + zwz(ji,jj) * zx2 ) 
+            END DO  
+         END DO  
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE vor_ene
+
+
+   SUBROUTINE vor_ens( kt, kvor, pun, pvn, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE vor_ens  ***
+      !!
+      !! ** Purpose :   Compute the now total vorticity trend and add it to
+      !!      the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time)
+      !!      and the Sadourny (1975) flux FORM formulation : conserves the
+      !!      potential enstrophy of a horizontally non-divergent flow. the
+      !!      trend of the vorticity term is given by:
+      !!          voru = 1/e1u  mj-1[ (rvor+f)/e3f ]  mj-1[ mi(e1v*e3v vn) ]
+      !!          vorv = 1/e2v  mi-1[ (rvor+f)/e3f ]  mi-1[ mj(e2u*e3u un) ]
+      !!      Add this trend to the general momentum trend (ua,va):
+      !!          (ua,va) = (ua,va) + ( voru , vorv )
+      !!
+      !! ** Action : - Update (ua,va) arrays with the now vorticity term trend
+      !!
+      !! References : Sadourny, r., 1975, j. atmos. sciences, 32, 680-689.
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt          ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kvor        ! total, planetary, relative, or metric
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pun, pvn    ! now velocities
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva    ! total v-trend
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zuav, zvau   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwx, zwy, zwz, zww   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:vor_ens : vorticity term: enstrophy conserving scheme'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         !
+         SELECT CASE( kvor )                 !==  vorticity considered  ==!
+         CASE ( np_COR )                           !* Coriolis (planetary vorticity)
+            zwz(:,:) = ff_f(:,:) 
+         CASE ( np_RVO )                           !* relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = (  e2v(ji+1,jj  ) * pvn(ji+1,jj  ,jk) - e2v(ji,jj) * pvn(ji,jj,jk)    &
+                     &          - e1u(ji  ,jj+1) * pun(ji  ,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_MET )                           !* metric term
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &       - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CRV )                           !* Coriolis + relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ff_f(ji,jj) + (  e2v(ji+1,jj  ) * pvn(ji+1,jj  ,jk) - e2v(ji,jj) * pvn(ji,jj,jk)  &
+                     &                        - e1u(ji  ,jj+1) * pun(ji  ,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CME )                           !* Coriolis + metric
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = ff_f(ji,jj) + ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &                     - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE DEFAULT                                             ! error
+            CALL ctl_stop('STOP','dyn_vor: wrong value for kvor'  )
+         END SELECT
+         !
+         IF( ln_dynvor_msk ) THEN           !==  mask/unmask vorticity ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj) = zwz(ji,jj) * fmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+         !
+         IF( ln_sco ) THEN                   !==  horizontal fluxes  ==!
+            zwz(:,:) = zwz(:,:) / e3f_n(:,:,jk)
+            zwx(:,:) = e2u(:,:) * e3u_n(:,:,jk) * pun(:,:,jk)
+            zwy(:,:) = e1v(:,:) * e3v_n(:,:,jk) * pvn(:,:,jk)
+         ELSE
+            zwx(:,:) = e2u(:,:) * pun(:,:,jk)
+            zwy(:,:) = e1v(:,:) * pvn(:,:,jk)
+         ENDIF
+         !                                   !==  compute and add the vorticity term trend  =!
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zuav = r1_8 * r1_e1u(ji,jj) * (  zwy(ji  ,jj-1) + zwy(ji+1,jj-1)  &
+                  &                           + zwy(ji  ,jj  ) + zwy(ji+1,jj  )  )
+               zvau =-r1_8 * r1_e2v(ji,jj) * (  zwx(ji-1,jj  ) + zwx(ji-1,jj+1)  &
+                  &                           + zwx(ji  ,jj  ) + zwx(ji  ,jj+1)  )
+               pua(ji,jj,jk) = pua(ji,jj,jk) + zuav * ( zwz(ji  ,jj-1) + zwz(ji,jj) )
+               pva(ji,jj,jk) = pva(ji,jj,jk) + zvau * ( zwz(ji-1,jj  ) + zwz(ji,jj) )
+            END DO  
+         END DO  
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE vor_ens
+
+
+   SUBROUTINE vor_een( kt, kvor, pun, pvn, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE vor_een  ***
+      !!
+      !! ** Purpose :   Compute the now total vorticity trend and add it to 
+      !!      the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time) 
+      !!      and the Arakawa and Lamb (1980) flux form formulation : conserves 
+      !!      both the horizontal kinetic energy and the potential enstrophy
+      !!      when horizontal divergence is zero (see the NEMO documentation)
+      !!      Add this trend to the general momentum trend (ua,va).
+      !!
+      !! ** Action : - Update (ua,va) with the now vorticity term trend
+      !!
+      !! References : Arakawa and Lamb 1980, Mon. Wea. Rev., 109, 18-36
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt          ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kvor        ! total, planetary, relative, or metric
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pun, pvn    ! now velocities
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva    ! total v-trend
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ierr         ! local integer
+      REAL(wp) ::   zua, zva     ! local scalars
+      REAL(wp) ::   zmsk, ze3f   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zwx , zwy , z1_e3f
+      REAL(wp), DIMENSION(jpi,jpj)     ::   ztnw, ztne, ztsw, ztse
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:vor_een : vorticity term: energy and enstrophy conserving scheme'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         !
+         SELECT CASE( nn_een_e3f )           ! == reciprocal of e3 at F-point
+         CASE ( 0 )                                   ! original formulation  (masked averaging of e3t divided by 4)
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  ze3f = (  e3t_n(ji,jj+1,jk)*tmask(ji,jj+1,jk) + e3t_n(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
+                     &    + e3t_n(ji,jj  ,jk)*tmask(ji,jj  ,jk) + e3t_n(ji+1,jj  ,jk)*tmask(ji+1,jj  ,jk)  )
+                  IF( ze3f /= 0._wp ) THEN   ;   z1_e3f(ji,jj) = 4._wp / ze3f
+                  ELSE                       ;   z1_e3f(ji,jj) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         CASE ( 1 )                                   ! new formulation  (masked averaging of e3t divided by the sum of mask)
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  ze3f = (  e3t_n(ji,jj+1,jk)*tmask(ji,jj+1,jk) + e3t_n(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
+                     &    + e3t_n(ji,jj  ,jk)*tmask(ji,jj  ,jk) + e3t_n(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( ze3f /= 0._wp ) THEN   ;   z1_e3f(ji,jj) = zmsk / ze3f
+                  ELSE                       ;   z1_e3f(ji,jj) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END SELECT
+         !
+         SELECT CASE( kvor )                 !==  vorticity considered  ==!
+         CASE ( np_COR )                           !* Coriolis (planetary vorticity)
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = ff_f(ji,jj) * z1_e3f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_RVO )                           !* relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = ( e2v(ji+1,jj  ) * pvn(ji+1,jj,jk) - e2v(ji,jj) * pvn(ji,jj,jk)  &
+                     &            - e1u(ji  ,jj+1) * pun(ji,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) * r1_e1e2f(ji,jj)*z1_e3f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_MET )                           !* metric term
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = (   ( pvn(ji+1,jj,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &              - ( pun(ji,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)   ) * z1_e3f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CRV )                           !* Coriolis + relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = (  ff_f(ji,jj) + (  e2v(ji+1,jj  ) * pvn(ji+1,jj,jk) - e2v(ji,jj) * pvn(ji,jj,jk)      &
+                     &                              - e1u(ji  ,jj+1) * pun(ji,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  )   &
+                     &                           * r1_e1e2f(ji,jj)   ) * z1_e3f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CME )                           !* Coriolis + metric
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = (   ff_f(ji,jj) + ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &                            - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)   ) * z1_e3f(ji,jj)
+               END DO
+            END DO
+         CASE DEFAULT                                             ! error
+            CALL ctl_stop('STOP','dyn_vor: wrong value for kvor'  )
+         END SELECT
+         !
+         IF( ln_dynvor_msk ) THEN          !==  mask/unmask vorticity ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = zwz(ji,jj,jk) * fmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+      END DO                                           !   End of slab
+         !
+      CALL lbc_lnk( 'dynvor', zwz, 'F', 1. )
+
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !
+         !                                   !==  horizontal fluxes  ==!
+         zwx(:,:) = e2u(:,:) * e3u_n(:,:,jk) * pun(:,:,jk)
+         zwy(:,:) = e1v(:,:) * e3v_n(:,:,jk) * pvn(:,:,jk)
+
+         !                                   !==  compute and add the vorticity term trend  =!
+         jj = 2
+         ztne(1,:) = 0   ;   ztnw(1,:) = 0   ;   ztse(1,:) = 0   ;   ztsw(1,:) = 0
+         DO ji = 2, jpi          ! split in 2 parts due to vector opt.
+               ztne(ji,jj) = zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk)
+               ztnw(ji,jj) = zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk)
+               ztse(ji,jj) = zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk)
+               ztsw(ji,jj) = zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk)
+         END DO
+         DO jj = 3, jpj
+            DO ji = fs_2, jpi   ! vector opt. ok because we start at jj = 3
+               ztne(ji,jj) = zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk)
+               ztnw(ji,jj) = zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk)
+               ztse(ji,jj) = zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk)
+               ztsw(ji,jj) = zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk)
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zua = + r1_12 * r1_e1u(ji,jj) * (  ztne(ji,jj  ) * zwy(ji  ,jj  ) + ztnw(ji+1,jj) * zwy(ji+1,jj  )   &
+                  &                             + ztse(ji,jj  ) * zwy(ji  ,jj-1) + ztsw(ji+1,jj) * zwy(ji+1,jj-1) )
+               zva = - r1_12 * r1_e2v(ji,jj) * (  ztsw(ji,jj+1) * zwx(ji-1,jj+1) + ztse(ji,jj+1) * zwx(ji  ,jj+1)   &
+                  &                             + ztnw(ji,jj  ) * zwx(ji-1,jj  ) + ztne(ji,jj  ) * zwx(ji  ,jj  ) )
+               pua(ji,jj,jk) = pua(ji,jj,jk) + zua
+               pva(ji,jj,jk) = pva(ji,jj,jk) + zva
+            END DO  
+         END DO  
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE vor_een
+
+
+
+   SUBROUTINE vor_eeT( kt, kvor, pun, pvn, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE vor_eeT  ***
+      !!
+      !! ** Purpose :   Compute the now total vorticity trend and add it to 
+      !!      the general trend of the momentum equation.
+      !!
+      !! ** Method  :   Trend evaluated using now fields (centered in time) 
+      !!      and the Arakawa and Lamb (1980) vector form formulation using 
+      !!      a modified version of Arakawa and Lamb (1980) scheme (see vor_een).
+      !!      The change consists in 
+      !!      Add this trend to the general momentum trend (ua,va).
+      !!
+      !! ** Action : - Update (ua,va) with the now vorticity term trend
+      !!
+      !! References : Arakawa and Lamb 1980, Mon. Wea. Rev., 109, 18-36
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt          ! ocean time-step index
+      INTEGER                         , INTENT(in   ) ::   kvor        ! total, planetary, relative, or metric
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pun, pvn    ! now velocities
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva    ! total v-trend
+      !
+      INTEGER  ::   ji, jj, jk     ! dummy loop indices
+      INTEGER  ::   ierr           ! local integer
+      REAL(wp) ::   zua, zva       ! local scalars
+      REAL(wp) ::   zmsk, z1_e3t   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zwx , zwy 
+      REAL(wp), DIMENSION(jpi,jpj)     ::   ztnw, ztne, ztsw, ztse
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn:vor_een : vorticity term: energy and enstrophy conserving scheme'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      !                                                ! ===============
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         !
+         !
+         SELECT CASE( kvor )                 !==  vorticity considered  ==!
+         CASE ( np_COR )                           !* Coriolis (planetary vorticity)
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = ff_f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_RVO )                           !* relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = (  e2v(ji+1,jj  ) * pvn(ji+1,jj  ,jk) - e2v(ji,jj) * pvn(ji,jj,jk)    &
+                     &             - e1u(ji  ,jj+1) * pun(ji  ,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) &
+                     &          * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_MET )                           !* metric term
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &          - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE ( np_CRV )                           !* Coriolis + relative vorticity
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = (  ff_f(ji,jj) + (  e2v(ji+1,jj  ) * pvn(ji+1,jj  ,jk) - e2v(ji,jj) * pvn(ji,jj,jk)    &
+                     &                              - e1u(ji  ,jj+1) * pun(ji  ,jj+1,jk) + e1u(ji,jj) * pun(ji,jj,jk)  ) &
+                     &                         * r1_e1e2f(ji,jj)    )
+               END DO
+            END DO
+         CASE ( np_CME )                           !* Coriolis + metric
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = ff_f(ji,jj) + ( pvn(ji+1,jj  ,jk) + pvn(ji,jj,jk) ) * di_e2v_2e1e2f(ji,jj)   &
+                     &                        - ( pun(ji  ,jj+1,jk) + pun(ji,jj,jk) ) * dj_e1u_2e1e2f(ji,jj)
+               END DO
+            END DO
+         CASE DEFAULT                                             ! error
+            CALL ctl_stop('STOP','dyn_vor: wrong value for kvor'  )
+         END SELECT
+         !
+         IF( ln_dynvor_msk ) THEN          !==  mask/unmask vorticity ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = zwz(ji,jj,jk) * fmask(ji,jj,jk)
+               END DO
+            END DO
+         ENDIF
+      END DO
+      !
+      CALL lbc_lnk( 'dynvor', zwz, 'F', 1. )
+      !
+      DO jk = 1, jpkm1                                 ! Horizontal slab
+
+      !                                   !==  horizontal fluxes  ==!
+         zwx(:,:) = e2u(:,:) * e3u_n(:,:,jk) * pun(:,:,jk)
+         zwy(:,:) = e1v(:,:) * e3v_n(:,:,jk) * pvn(:,:,jk)
+
+         !                                   !==  compute and add the vorticity term trend  =!
+         jj = 2
+         ztne(1,:) = 0   ;   ztnw(1,:) = 0   ;   ztse(1,:) = 0   ;   ztsw(1,:) = 0
+         DO ji = 2, jpi          ! split in 2 parts due to vector opt.
+               z1_e3t = 1._wp / e3t_n(ji,jj,jk)
+               ztne(ji,jj) = ( zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) ) * z1_e3t
+               ztnw(ji,jj) = ( zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) ) * z1_e3t
+               ztse(ji,jj) = ( zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) ) * z1_e3t
+               ztsw(ji,jj) = ( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) ) * z1_e3t
+         END DO
+         DO jj = 3, jpj
+            DO ji = fs_2, jpi   ! vector opt. ok because we start at jj = 3
+               z1_e3t = 1._wp / e3t_n(ji,jj,jk)
+               ztne(ji,jj) = ( zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) ) * z1_e3t
+               ztnw(ji,jj) = ( zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) + zwz(ji  ,jj  ,jk) ) * z1_e3t
+               ztse(ji,jj) = ( zwz(ji  ,jj  ,jk) + zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) ) * z1_e3t
+               ztsw(ji,jj) = ( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj-1,jk) + zwz(ji-1,jj  ,jk) ) * z1_e3t
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zua = + r1_12 * r1_e1u(ji,jj) * (  ztne(ji,jj  ) * zwy(ji  ,jj  ) + ztnw(ji+1,jj) * zwy(ji+1,jj  )   &
+                  &                             + ztse(ji,jj  ) * zwy(ji  ,jj-1) + ztsw(ji+1,jj) * zwy(ji+1,jj-1) )
+               zva = - r1_12 * r1_e2v(ji,jj) * (  ztsw(ji,jj+1) * zwx(ji-1,jj+1) + ztse(ji,jj+1) * zwx(ji  ,jj+1)   &
+                  &                             + ztnw(ji,jj  ) * zwx(ji-1,jj  ) + ztne(ji,jj  ) * zwx(ji  ,jj  ) )
+               pua(ji,jj,jk) = pua(ji,jj,jk) + zua
+               pva(ji,jj,jk) = pva(ji,jj,jk) + zva
+            END DO  
+         END DO  
+         !                                             ! ===============
+      END DO                                           !   End of slab
+      !                                                ! ===============
+   END SUBROUTINE vor_eeT
+
+
+   SUBROUTINE dyn_vor_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_vor_init  ***
+      !!
+      !! ** Purpose :   Control the consistency between cpp options for
+      !!              tracer advection schemes
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk    ! dummy loop indices
+      INTEGER ::   ioptio, ios   ! local integer
+      !!
+      NAMELIST/namdyn_vor/ ln_dynvor_ens, ln_dynvor_ene, ln_dynvor_enT, ln_dynvor_eeT,   &
+         &                 ln_dynvor_een, nn_een_e3f   , ln_dynvor_mix, ln_dynvor_msk
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dyn_vor_init : vorticity term : read namelist and control the consistency'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnam_ref )              ! Namelist namdyn_vor in reference namelist : Vorticity scheme options
+      READ  ( numnam_ref, namdyn_vor, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_vor in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namdyn_vor in configuration namelist : Vorticity scheme options
+      READ  ( numnam_cfg, namdyn_vor, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_vor in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdyn_vor )
+      !
+      IF(lwp) THEN                    ! Namelist print
+         WRITE(numout,*) '   Namelist namdyn_vor : choice of the vorticity term scheme'
+         WRITE(numout,*) '      enstrophy conserving scheme                    ln_dynvor_ens = ', ln_dynvor_ens
+         WRITE(numout,*) '      f-point energy conserving scheme               ln_dynvor_ene = ', ln_dynvor_ene
+         WRITE(numout,*) '      t-point energy conserving scheme               ln_dynvor_enT = ', ln_dynvor_enT
+         WRITE(numout,*) '      energy conserving scheme  (een using e3t)      ln_dynvor_eeT = ', ln_dynvor_eeT
+         WRITE(numout,*) '      enstrophy and energy conserving scheme         ln_dynvor_een = ', ln_dynvor_een
+         WRITE(numout,*) '         e3f = averaging /4 (=0) or /sum(tmask) (=1)    nn_een_e3f = ', nn_een_e3f
+         WRITE(numout,*) '      mixed enstrophy/energy conserving scheme       ln_dynvor_mix = ', ln_dynvor_mix
+         WRITE(numout,*) '      masked (=T) or unmasked(=F) vorticity          ln_dynvor_msk = ', ln_dynvor_msk
+      ENDIF
+
+      IF( ln_dynvor_msk )   CALL ctl_stop( 'dyn_vor_init:   masked vorticity is not currently not available')
+
+!!gm  this should be removed when choosing a unique strategy for fmask at the coast
+      ! If energy, enstrophy or mixed advection of momentum in vector form change the value for masks
+      ! at angles with three ocean points and one land point
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '      change fmask value in the angles (T)           ln_vorlat = ', ln_vorlat
+      IF( ln_vorlat .AND. ( ln_dynvor_ene .OR. ln_dynvor_ens .OR. ln_dynvor_mix ) ) THEN
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  IF(    tmask(ji,jj+1,jk) + tmask(ji+1,jj+1,jk)              &
+                     & + tmask(ji,jj  ,jk) + tmask(ji+1,jj  ,jk) == 3._wp )   fmask(ji,jj,jk) = 1._wp
+               END DO
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( 'dynvor', fmask, 'F', 1._wp )      ! Lateral boundary conditions on fmask
+         !
+      ENDIF
+!!gm end
+
+      ioptio = 0                     ! type of scheme for vorticity (set nvor_scheme)
+      IF( ln_dynvor_ens ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_ENS   ;   ENDIF
+      IF( ln_dynvor_ene ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_ENE   ;   ENDIF
+      IF( ln_dynvor_enT ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_ENT   ;   ENDIF
+      IF( ln_dynvor_eeT ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_EET   ;   ENDIF
+      IF( ln_dynvor_een ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_EEN   ;   ENDIF
+      IF( ln_dynvor_mix ) THEN   ;   ioptio = ioptio + 1   ;   nvor_scheme = np_MIX   ;   ENDIF
+      !
+      IF( ioptio /= 1 ) CALL ctl_stop( ' use ONE and ONLY one vorticity scheme' )
+      !                      
+      IF(lwp) WRITE(numout,*)        ! type of calculated vorticity (set ncor, nrvm, ntot)
+      ncor = np_COR                       ! planetary vorticity
+      SELECT CASE( n_dynadv )
+      CASE( np_LIN_dyn )
+         IF(lwp) WRITE(numout,*) '   ==>>>   linear dynamics : total vorticity = Coriolis'
+         nrvm = np_COR        ! planetary vorticity
+         ntot = np_COR        !     -         -
+      CASE( np_VEC_c2  )
+         IF(lwp) WRITE(numout,*) '   ==>>>   vector form dynamics : total vorticity = Coriolis + relative vorticity' 
+         nrvm = np_RVO        ! relative vorticity
+         ntot = np_CRV        ! relative + planetary vorticity         
+      CASE( np_FLX_c2 , np_FLX_ubs  )
+         IF(lwp) WRITE(numout,*) '   ==>>>   flux form dynamics : total vorticity = Coriolis + metric term'
+         nrvm = np_MET        ! metric term
+         ntot = np_CME        ! Coriolis + metric term
+         !
+         SELECT CASE( nvor_scheme )    ! pre-computed gradients for the metric term:
+         CASE( np_ENT )                      !* T-point metric term :   pre-compute di(e2u)/2 and dj(e1v)/2
+            ALLOCATE( di_e2u_2(jpi,jpj), dj_e1v_2(jpi,jpj) )
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  di_e2u_2(ji,jj) = ( e2u(ji,jj) - e2u(ji-1,jj  ) ) * 0.5_wp
+                  dj_e1v_2(ji,jj) = ( e1v(ji,jj) - e1v(ji  ,jj-1) ) * 0.5_wp
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'dynvor', di_e2u_2, 'T', -1. , dj_e1v_2, 'T', -1. )   ! Lateral boundary conditions
+            !
+         CASE DEFAULT                        !* F-point metric term :   pre-compute di(e2u)/(2*e1e2f) and dj(e1v)/(2*e1e2f)
+            ALLOCATE( di_e2v_2e1e2f(jpi,jpj), dj_e1u_2e1e2f(jpi,jpj) )
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  di_e2v_2e1e2f(ji,jj) = ( e2v(ji+1,jj  ) - e2v(ji,jj) )  * 0.5 * r1_e1e2f(ji,jj)
+                  dj_e1u_2e1e2f(ji,jj) = ( e1u(ji  ,jj+1) - e1u(ji,jj) )  * 0.5 * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'dynvor', di_e2v_2e1e2f, 'F', -1. , dj_e1u_2e1e2f, 'F', -1. )   ! Lateral boundary conditions
+         END SELECT
+         !
+      END SELECT
+      
+      IF(lwp) THEN                   ! Print the choice
+         WRITE(numout,*)
+         SELECT CASE( nvor_scheme )
+         CASE( np_ENS )   ;   WRITE(numout,*) '   ==>>>   enstrophy conserving scheme (ENS)'
+         CASE( np_ENE )   ;   WRITE(numout,*) '   ==>>>   energy conserving scheme (Coriolis at F-points) (ENE)'
+         CASE( np_ENT )   ;   WRITE(numout,*) '   ==>>>   energy conserving scheme (Coriolis at T-points) (ENT)'
+         CASE( np_EET )   ;   WRITE(numout,*) '   ==>>>   energy conserving scheme (EEN scheme using e3t) (EET)'
+         CASE( np_EEN )   ;   WRITE(numout,*) '   ==>>>   energy and enstrophy conserving scheme (EEN)'
+         CASE( np_MIX )   ;   WRITE(numout,*) '   ==>>>   mixed enstrophy/energy conserving scheme (MIX)'
+         END SELECT         
+      ENDIF
+      !
+   END SUBROUTINE dyn_vor_init
+
+   !!==============================================================================
+END MODULE dynvor
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzad.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzad.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzad.F90	(revision 14097)
@@ -0,0 +1,124 @@
+MODULE dynzad
+   !!======================================================================
+   !!                       ***  MODULE  dynzad  ***
+   !! Ocean dynamics : vertical advection trend
+   !!======================================================================
+   !! History :  OPA  ! 1991-01  (G. Madec) Original code
+   !!   NEMO     0.5  ! 2002-07  (G. Madec) Free form, F90
+   !!----------------------------------------------------------------------
+   
+   !!----------------------------------------------------------------------
+   !!   dyn_zad       : vertical advection momentum trend
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! surface boundary condition: ocean
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   dyn_zad       ! routine called by dynadv.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dyn_zad ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dynzad  ***
+      !! 
+      !! ** Purpose :   Compute the now vertical momentum advection trend and 
+      !!      add it to the general trend of momentum equation.
+      !!
+      !! ** Method  :   The now vertical advection of momentum is given by:
+      !!         w dz(u) = ua + 1/(e1e2u*e3u) mk+1[ mi(e1e2t*wn) dk(un) ]
+      !!         w dz(v) = va + 1/(e1e2v*e3v) mk+1[ mj(e1e2t*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
+      !!              - Send the trends to trddyn for diagnostics (l_trddyn=T)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step inedx
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zua, zva     ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zww
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwuw, zwvw
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdu, ztrdv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_zad')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_zad : 2nd order vertical advection scheme'
+      ENDIF
+
+      IF( l_trddyn )   THEN         ! Save ua and va trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) ) 
+         ztrdu(:,:,:) = ua(:,:,:) 
+         ztrdv(:,:,:) = va(:,:,:) 
+      ENDIF
+      
+      DO jk = 2, jpkm1              ! Vertical momentum advection at level w and u- and v- vertical
+         DO jj = 2, jpj                   ! vertical fluxes 
+            DO ji = fs_2, jpi             ! vector opt.
+               zww(ji,jj) = 0.25_wp * e1e2t(ji,jj) * wn(ji,jj,jk)
+            END DO
+         END DO
+         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  ) + zww(ji,jj) ) * ( un(ji,jj,jk-1) - un(ji,jj,jk) )
+               zwvw(ji,jj,jk) = ( zww(ji  ,jj+1) + zww(ji,jj) ) * ( vn(ji,jj,jk-1) - vn(ji,jj,jk) )
+            END DO  
+         END DO   
+      END DO
+      !
+      ! Surface and bottom advective fluxes set to zero
+      DO jj = 2, jpjm1        
+         DO ji = fs_2, fs_jpim1           ! vector opt.
+            zwuw(ji,jj, 1 ) = 0._wp
+            zwvw(ji,jj, 1 ) = 0._wp
+            zwuw(ji,jj,jpk) = 0._wp
+            zwvw(ji,jj,jpk) = 0._wp
+         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.
+               ua(ji,jj,jk) = ua(ji,jj,jk) - ( zwuw(ji,jj,jk) + zwuw(ji,jj,jk+1) ) * r1_e1e2u(ji,jj) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) = va(ji,jj,jk) - ( zwvw(ji,jj,jk) + zwvw(ji,jj,jk+1) ) * r1_e1e2v(ji,jj) / e3v_n(ji,jj,jk)
+            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 )
+         DEALLOCATE( 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' )
+      !
+      IF( ln_timing )   CALL timing_stop('dyn_zad')
+      !
+   END SUBROUTINE dyn_zad
+
+   !!======================================================================
+END MODULE dynzad
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzdf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzdf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/dynzdf.F90	(revision 14097)
@@ -0,0 +1,502 @@
+MODULE dynzdf
+   !!==============================================================================
+   !!                 ***  MODULE  dynzdf  ***
+   !! Ocean dynamics :  vertical component of the momentum mixing trend
+   !!==============================================================================
+   !! History :  1.0  !  2005-11  (G. Madec)  Original code
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            4.0  !  2017-06  (G. Madec) remove the explicit time-stepping option + avm at t-point
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dyn_zdf       : compute the after velocity through implicit calculation of vertical mixing
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain variables 
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdf_oce        ! ocean vertical physics variables
+   USE zdfdrg         ! vertical physics: top/bottom drag coef.
+   USE dynadv    ,ONLY: ln_dynadv_vec    ! dynamics: advection form
+   USE dynldf_iso,ONLY: akzu, akzv       ! dynamics: vertical component of rotated lateral mixing 
+   USE ldfdyn         ! lateral diffusion: eddy viscosity coef. and type of operator
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dyn_zdf   !  routine called by step.F90
+
+   REAL(wp) ::  r_vvl     ! non-linear free surface indicator: =0 if ln_linssh=T, =1 otherwise 
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE dyn_zdf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_zdf  ***
+      !!
+      !! ** Purpose :   compute the trend due to the vert. momentum diffusion
+      !!              together with the Leap-Frog time stepping using an 
+      !!              implicit scheme.
+      !!
+      !! ** Method  :  - Leap-Frog time stepping on all trends but the vertical mixing
+      !!         ua =         ub + 2*dt *       ua             vector form or linear free surf.
+      !!         ua = ( e3u_b*ub + 2*dt * e3u_n*ua ) / e3u_a   otherwise
+      !!               - update the after velocity with the implicit vertical mixing.
+      !!      This requires to solver the following system: 
+      !!         ua = ua + 1/e3u_a dk+1[ mi(avm) / e3uw_a dk[ua] ]
+      !!      with the following surface/top/bottom boundary condition:
+      !!      surface: wind stress input (averaged over kt-1/2 & kt+1/2)
+      !!      top & bottom : top stress (iceshelf-ocean) & bottom stress (cf zdfdrg.F90)
+      !!
+      !! ** Action :   (ua,va)   after velocity 
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk         ! dummy loop indices
+      INTEGER  ::   iku, ikv           ! local integers
+      REAL(wp) ::   zzwi, ze3ua, zdt   ! local scalars
+      REAL(wp) ::   zzws, ze3va        !   -      -
+      REAL(wp) ::   z1_e3ua, z1_e3va   !   -      -
+      REAL(wp) ::   zWu , zWv          !   -      -
+      REAL(wp) ::   zWui, zWvi         !   -      -
+      REAL(wp) ::   zWus, zWvs         !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        ::  zwi, zwd, zws   ! 3D workspace 
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdu, ztrdv   !  -      -
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('dyn_zdf')
+      !
+      IF( kt == nit000 ) THEN       !* initialization
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_zdf_imp : vertical momentum diffusion implicit operator'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~ '
+         !
+         If( ln_linssh ) THEN   ;    r_vvl = 0._wp    ! non-linear free surface indicator
+         ELSE                   ;    r_vvl = 1._wp
+         ENDIF
+      ENDIF
+      !                             !* set time step
+      IF( neuler == 0 .AND. kt == nit000     ) THEN   ;   r2dt =      rdt   ! = rdt (restart with Euler time stepping)
+      ELSEIF(               kt <= nit000 + 1 ) THEN   ;   r2dt = 2. * rdt   ! = 2 rdt (leapfrog)
+      ENDIF
+      !
+      !                             !* explicit top/bottom drag case
+      IF( .NOT.ln_drgimp )   CALL zdf_drg_exp( kt, ub, vb, ua, va )  ! add top/bottom friction trend to (ua,va)
+      !
+      !
+      IF( l_trddyn )   THEN         !* temporary save of ta and sa trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk), ztrdv(jpi,jpj,jpk) ) 
+         ztrdu(:,:,:) = ua(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:)
+      ENDIF
+      !
+      !              !==  RHS: Leap-Frog time stepping on all trends but the vertical mixing  ==!   (put in ua,va)
+      !
+      !                    ! time stepping except vertical diffusion
+      IF( ln_dynadv_vec .OR. ln_linssh ) THEN   ! applied on velocity
+         DO jk = 1, jpkm1
+            ua(:,:,jk) = ( ub(:,:,jk) + r2dt * ua(:,:,jk) ) * umask(:,:,jk)
+            va(:,:,jk) = ( vb(:,:,jk) + r2dt * va(:,:,jk) ) * vmask(:,:,jk)
+         END DO
+      ELSE                                      ! applied on thickness weighted velocity
+         DO jk = 1, jpkm1
+            ua(:,:,jk) = (         e3u_b(:,:,jk) * ub(:,:,jk)  &
+               &          + r2dt * e3u_n(:,:,jk) * ua(:,:,jk)  ) / e3u_a(:,:,jk) * umask(:,:,jk)
+            va(:,:,jk) = (         e3v_b(:,:,jk) * vb(:,:,jk)  &
+               &          + r2dt * e3v_n(:,:,jk) * va(:,:,jk)  ) / e3v_a(:,:,jk) * vmask(:,:,jk)
+         END DO
+      ENDIF
+      !                    ! add top/bottom friction 
+      !     With split-explicit free surface, barotropic stress is treated explicitly Update velocities at the bottom.
+      !     J. Chanut: The bottom stress is computed considering after barotropic velocities, which does 
+      !                not lead to the effective stress seen over the whole barotropic loop. 
+      !     G. Madec : in linear free surface, e3u_a = e3u_n = e3u_0, so systematic use of e3u_a
+      IF( ln_drgimp .AND. ln_dynspg_ts ) THEN
+         DO jk = 1, jpkm1        ! remove barotropic velocities
+            ua(:,:,jk) = ( ua(:,:,jk) - ua_b(:,:) ) * umask(:,:,jk)
+            va(:,:,jk) = ( va(:,:,jk) - va_b(:,:) ) * vmask(:,:,jk)
+         END DO
+         DO jj = 2, jpjm1        ! Add bottom/top stress due to barotropic component only
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               iku = mbku(ji,jj)         ! ocean bottom level at u- and v-points 
+               ikv = mbkv(ji,jj)         ! (deepest ocean u- and v-points)
+               ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,iku) + r_vvl * e3u_a(ji,jj,iku)
+               ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,ikv) + r_vvl * e3v_a(ji,jj,ikv)
+               ua(ji,jj,iku) = ua(ji,jj,iku) + r2dt * 0.5*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) * ua_b(ji,jj) / ze3ua
+               va(ji,jj,ikv) = va(ji,jj,ikv) + r2dt * 0.5*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) * va_b(ji,jj) / ze3va
+            END DO
+         END DO
+         IF( ln_isfcav.OR.ln_drgice_imp ) THEN    ! Ocean cavities (ISF)
+            DO jj = 2, jpjm1        
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  iku = miku(ji,jj)         ! top ocean level at u- and v-points 
+                  ikv = mikv(ji,jj)         ! (first wet ocean u- and v-points)
+                  ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,iku) + r_vvl * e3u_a(ji,jj,iku)
+                  ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,ikv) + r_vvl * e3v_a(ji,jj,ikv)
+                  ua(ji,jj,iku) = ua(ji,jj,iku) + r2dt * 0.5*( rCdU_top(ji+1,jj)+rCdU_top(ji,jj) ) * ua_b(ji,jj) / ze3ua
+                  va(ji,jj,ikv) = va(ji,jj,ikv) + r2dt * 0.5*( rCdU_top(ji,jj+1)+rCdU_top(ji,jj) ) * va_b(ji,jj) / ze3va
+               END DO
+            END DO
+         END IF
+      ENDIF
+      !
+      !              !==  Vertical diffusion on u  ==!
+      !
+      !                    !* Matrix construction
+      zdt = r2dt * 0.5
+      IF( ln_zad_Aimp ) THEN   !!
+         SELECT CASE( nldf_dyn )
+         CASE( np_lap_i )           ! rotated lateral mixing: add its vertical mixing (akzu)
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,jk) + r_vvl * e3u_a(ji,jj,jk)   ! after scale factor at U-point
+                     zzwi = - zdt * ( avm(ji+1,jj,jk  ) + avm(ji,jj,jk  ) + akzu(ji,jj,jk  ) )   &
+                        &         / ( ze3ua * e3uw_n(ji,jj,jk  ) ) * wumask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji+1,jj,jk+1) + avm(ji,jj,jk+1) + akzu(ji,jj,jk+1) )   &
+                        &         / ( ze3ua * e3uw_n(ji,jj,jk+1) ) * wumask(ji,jj,jk+1)
+                     zWui = ( wi(ji,jj,jk  ) + wi(ji+1,jj,jk  ) ) / ze3ua
+                     zWus = ( wi(ji,jj,jk+1) + wi(ji+1,jj,jk+1) ) / ze3ua
+                     zwi(ji,jj,jk) = zzwi + zdt * MIN( zWui, 0._wp ) 
+                     zws(ji,jj,jk) = zzws - zdt * MAX( zWus, 0._wp )
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws + zdt * ( MAX( zWui, 0._wp ) - MIN( zWus, 0._wp ) )
+                  END DO
+               END DO
+            END DO
+         CASE DEFAULT               ! iso-level lateral mixing
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,jk) + r_vvl * e3u_a(ji,jj,jk)   ! after scale factor at U-point
+                     zzwi = - zdt * ( avm(ji+1,jj,jk  ) + avm(ji,jj,jk  ) ) / ( ze3ua * e3uw_n(ji,jj,jk  ) ) * wumask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji+1,jj,jk+1) + avm(ji,jj,jk+1) ) / ( ze3ua * e3uw_n(ji,jj,jk+1) ) * wumask(ji,jj,jk+1)
+                     zWui = ( wi(ji,jj,jk  ) + wi(ji+1,jj,jk  ) ) / ze3ua
+                     zWus = ( wi(ji,jj,jk+1) + wi(ji+1,jj,jk+1) ) / ze3ua
+                     zwi(ji,jj,jk) = zzwi + zdt * MIN( zWui, 0._wp )
+                     zws(ji,jj,jk) = zzws - zdt * MAX( zWus, 0._wp )
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws + zdt * ( MAX( zWui, 0._wp ) - MIN( zWus, 0._wp ) )
+                  END DO
+               END DO
+            END DO
+         END SELECT
+         DO jj = 2, jpjm1     !* Surface boundary conditions
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zwi(ji,jj,1) = 0._wp
+               ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,1) + r_vvl * e3u_a(ji,jj,1)
+               zzws = - zdt * ( avm(ji+1,jj,2) + avm(ji  ,jj,2) ) / ( ze3ua * e3uw_n(ji,jj,2) ) * wumask(ji,jj,2)
+               zWus = ( wi(ji  ,jj,2) +  wi(ji+1,jj,2) ) / ze3ua
+               zws(ji,jj,1 ) = zzws - zdt * MAX( zWus, 0._wp )
+               zwd(ji,jj,1 ) = 1._wp - zzws - zdt * ( MIN( zWus, 0._wp ) )
+            END DO
+         END DO
+      ELSE
+         SELECT CASE( nldf_dyn )
+         CASE( np_lap_i )           ! rotated lateral mixing: add its vertical mixing (akzu)
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,jk) + r_vvl * e3u_a(ji,jj,jk)   ! after scale factor at U-point
+                     zzwi = - zdt * ( avm(ji+1,jj,jk  ) + avm(ji,jj,jk  ) + akzu(ji,jj,jk  ) )   &
+                        &         / ( ze3ua * e3uw_n(ji,jj,jk  ) ) * wumask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji+1,jj,jk+1) + avm(ji,jj,jk+1) + akzu(ji,jj,jk+1) )   &
+                        &         / ( ze3ua * e3uw_n(ji,jj,jk+1) ) * wumask(ji,jj,jk+1)
+                     zwi(ji,jj,jk) = zzwi
+                     zws(ji,jj,jk) = zzws
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws
+                  END DO
+               END DO
+            END DO
+         CASE DEFAULT               ! iso-level lateral mixing
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,jk) + r_vvl * e3u_a(ji,jj,jk)   ! after scale factor at U-point
+                     zzwi = - zdt * ( avm(ji+1,jj,jk  ) + avm(ji,jj,jk  ) ) / ( ze3ua * e3uw_n(ji,jj,jk  ) ) * wumask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji+1,jj,jk+1) + avm(ji,jj,jk+1) ) / ( ze3ua * e3uw_n(ji,jj,jk+1) ) * wumask(ji,jj,jk+1)
+                     zwi(ji,jj,jk) = zzwi
+                     zws(ji,jj,jk) = zzws
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws
+                  END DO
+               END DO
+            END DO
+         END SELECT
+         DO jj = 2, jpjm1     !* Surface boundary conditions
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zwi(ji,jj,1) = 0._wp
+               zwd(ji,jj,1) = 1._wp - zws(ji,jj,1)
+            END DO
+         END DO
+      ENDIF
+      !
+      !
+      !              !==  Apply semi-implicit bottom friction  ==!
+      !
+      !     Only needed for semi-implicit bottom friction setup. The explicit
+      !     bottom friction has been included in "u(v)a" which act as the R.H.S
+      !     column vector of the tri-diagonal matrix equation
+      !
+      IF ( ln_drgimp ) THEN      ! implicit bottom friction
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               iku = mbku(ji,jj)       ! ocean bottom level at u- and v-points
+               ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,iku) + r_vvl * e3u_a(ji,jj,iku)   ! after scale factor at T-point
+               zwd(ji,jj,iku) = zwd(ji,jj,iku) - r2dt * 0.5*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) / ze3ua
+            END DO
+         END DO
+         IF ( ln_isfcav.OR.ln_drgice_imp ) THEN   ! top friction (always implicit)
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  !!gm   top Cd is masked (=0 outside cavities) no need of test on mik>=2  ==>> it has been suppressed
+                  iku = miku(ji,jj)       ! ocean top level at u- and v-points 
+                  ze3ua =  ( 1._wp - r_vvl ) * e3u_n(ji,jj,iku) + r_vvl * e3u_a(ji,jj,iku)   ! after scale factor at T-point
+                  zwd(ji,jj,iku) = zwd(ji,jj,iku) - r2dt * 0.5*( rCdU_top(ji+1,jj)+rCdU_top(ji,jj) ) / ze3ua
+               END DO
+            END DO
+         END IF
+      ENDIF
+      !
+      ! Matrix inversion starting from the first level
+      !-----------------------------------------------------------------------
+      !   solve m.x = y  where m is a tri diagonal matrix ( jpk*jpk )
+      !
+      !        ( zwd1 zws1   0    0    0  )( zwx1 ) ( zwy1 )
+      !        ( zwi2 zwd2 zws2   0    0  )( zwx2 ) ( zwy2 )
+      !        (  0   zwi3 zwd3 zws3   0  )( zwx3 )=( zwy3 )
+      !        (        ...               )( ...  ) ( ...  )
+      !        (  0    0    0   zwik zwdk )( zwxk ) ( zwyk )
+      !
+      !   m is decomposed in the product of an upper and a lower triangular matrix
+      !   The 3 diagonal terms are in 2d arrays: zwd, zws, zwi
+      !   The solution (the after velocity) is in ua
+      !-----------------------------------------------------------------------
+      !
+      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.
+               zwd(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwd(ji,jj,jk-1)
+            END DO
+         END DO
+      END DO
+      !
+      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 ) * e3u_n(ji,jj,1) + r_vvl * e3u_a(ji,jj,1) 
+            ua(ji,jj,1) = ua(ji,jj,1) + r2dt * 0.5_wp * ( utau_b(ji,jj) + utau(ji,jj) )   &
+               &                                      / ( ze3ua * rau0 ) * umask(ji,jj,1) 
+         END DO
+      END DO
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ua(ji,jj,jk) = ua(ji,jj,jk) - zwi(ji,jj,jk) / zwd(ji,jj,jk-1) * ua(ji,jj,jk-1)
+            END DO
+         END DO
+      END DO
+      !
+      DO jj = 2, jpjm1        !==  thrid recurrence : SOLk = ( Lk - Uk * Ek+1 ) / Dk  ==!
+         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
+               ua(ji,jj,jk) = ( ua(ji,jj,jk) - zws(ji,jj,jk) * ua(ji,jj,jk+1) ) / zwd(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      !              !==  Vertical diffusion on v  ==!
+      !
+      !                       !* Matrix construction
+      zdt = r2dt * 0.5
+      IF( ln_zad_Aimp ) THEN   !!
+         SELECT CASE( nldf_dyn )
+         CASE( np_lap_i )           ! rotated lateral mixing: add its vertical mixing (akzv)
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,jk) + r_vvl * e3v_a(ji,jj,jk)   ! after scale factor at V-point
+                     zzwi = - zdt * ( avm(ji,jj+1,jk  ) + avm(ji,jj,jk  ) + akzv(ji,jj,jk  ) )   &
+                        &         / ( ze3va * e3vw_n(ji,jj,jk  ) ) * wvmask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji,jj+1,jk+1) + avm(ji,jj,jk+1) + akzv(ji,jj,jk+1) )   &
+                        &         / ( ze3va * e3vw_n(ji,jj,jk+1) ) * wvmask(ji,jj,jk+1)
+                     zWvi = ( wi(ji,jj,jk  ) + wi(ji,jj+1,jk  ) ) / ze3va
+                     zWvs = ( wi(ji,jj,jk+1) + wi(ji,jj+1,jk+1) ) / ze3va
+                     zwi(ji,jj,jk) = zzwi + zdt * MIN( zWvi, 0._wp )
+                     zws(ji,jj,jk) = zzws - zdt * MAX( zWvs, 0._wp )
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws - zdt * ( - MAX( zWvi, 0._wp ) + MIN( zWvs, 0._wp ) )
+                  END DO
+               END DO
+            END DO
+         CASE DEFAULT               ! iso-level lateral mixing
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1 
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,jk) + r_vvl * e3v_a(ji,jj,jk)   ! after scale factor at V-point
+                     zzwi = - zdt * ( avm(ji,jj+1,jk  ) + avm(ji,jj,jk  ) ) / ( ze3va * e3vw_n(ji,jj,jk  ) ) * wvmask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji,jj+1,jk+1) + avm(ji,jj,jk+1) ) / ( ze3va * e3vw_n(ji,jj,jk+1) ) * wvmask(ji,jj,jk+1)
+                     zWvi = ( wi(ji,jj,jk  ) + wi(ji,jj+1,jk  ) ) / ze3va
+                     zWvs = ( wi(ji,jj,jk+1) + wi(ji,jj+1,jk+1) ) / ze3va
+                     zwi(ji,jj,jk) = zzwi  + zdt * MIN( zWvi, 0._wp )
+                     zws(ji,jj,jk) = zzws  - zdt * MAX( zWvs, 0._wp )
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws - zdt * ( - MAX( zWvi, 0._wp ) + MIN( zWvs, 0._wp ) )
+                  END DO
+               END DO
+            END DO
+         END SELECT
+         DO jj = 2, jpjm1     !* Surface boundary conditions
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zwi(ji,jj,1) = 0._wp
+               ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,1) + r_vvl * e3v_a(ji,jj,1)
+               zzws = - zdt * ( avm(ji,jj+1,2) + avm(ji,jj,2) ) / ( ze3va * e3vw_n(ji,jj,2) ) * wvmask(ji,jj,2)
+               zWvs = ( wi(ji,jj  ,2) +  wi(ji,jj+1,2) ) / ze3va
+               zws(ji,jj,1 ) = zzws - zdt * MAX( zWvs, 0._wp )
+               zwd(ji,jj,1 ) = 1._wp - zzws - zdt * ( MIN( zWvs, 0._wp ) )
+            END DO
+         END DO
+      ELSE
+         SELECT CASE( nldf_dyn )
+         CASE( np_lap_i )           ! rotated lateral mixing: add its vertical mixing (akzu)
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1   
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,jk) + r_vvl * e3v_a(ji,jj,jk)   ! after scale factor at V-point
+                     zzwi = - zdt * ( avm(ji,jj+1,jk  ) + avm(ji,jj,jk  ) + akzv(ji,jj,jk  ) )   &
+                        &         / ( ze3va * e3vw_n(ji,jj,jk  ) ) * wvmask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji,jj+1,jk+1) + avm(ji,jj,jk+1) + akzv(ji,jj,jk+1) )   &
+                        &         / ( ze3va * e3vw_n(ji,jj,jk+1) ) * wvmask(ji,jj,jk+1)
+                     zwi(ji,jj,jk) = zzwi
+                     zws(ji,jj,jk) = zzws
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws
+                  END DO
+               END DO
+            END DO
+         CASE DEFAULT               ! iso-level lateral mixing
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1   
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,jk) + r_vvl * e3v_a(ji,jj,jk)   ! after scale factor at V-point
+                     zzwi = - zdt * ( avm(ji,jj+1,jk  ) + avm(ji,jj,jk  ) ) / ( ze3va * e3vw_n(ji,jj,jk  ) ) * wvmask(ji,jj,jk  )
+                     zzws = - zdt * ( avm(ji,jj+1,jk+1) + avm(ji,jj,jk+1) ) / ( ze3va * e3vw_n(ji,jj,jk+1) ) * wvmask(ji,jj,jk+1)
+                     zwi(ji,jj,jk) = zzwi
+                     zws(ji,jj,jk) = zzws
+                     zwd(ji,jj,jk) = 1._wp - zzwi - zzws
+                  END DO
+               END DO
+            END DO
+         END SELECT
+         DO jj = 2, jpjm1        !* Surface boundary conditions
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zwi(ji,jj,1) = 0._wp
+               zwd(ji,jj,1) = 1._wp - zws(ji,jj,1)
+            END DO
+         END DO
+      ENDIF
+      !
+      !              !==  Apply semi-implicit top/bottom friction  ==!
+      !
+      !     Only needed for semi-implicit bottom friction setup. The explicit
+      !     bottom friction has been included in "u(v)a" which act as the R.H.S
+      !     column vector of the tri-diagonal matrix equation
+      !
+      IF( ln_drgimp ) THEN
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               ikv = mbkv(ji,jj)       ! (deepest ocean u- and v-points)
+               ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,ikv) + r_vvl * e3v_a(ji,jj,ikv)   ! after scale factor at T-point
+               zwd(ji,jj,ikv) = zwd(ji,jj,ikv) - r2dt * 0.5*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) / ze3va           
+            END DO
+         END DO
+         IF ( ln_isfcav.OR.ln_drgice_imp ) THEN
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  ikv = mikv(ji,jj)       ! (first wet ocean u- and v-points)
+                  ze3va =  ( 1._wp - r_vvl ) * e3v_n(ji,jj,ikv) + r_vvl * e3v_a(ji,jj,ikv)   ! after scale factor at T-point
+                  zwd(ji,jj,ikv) = zwd(ji,jj,ikv) - r2dt * 0.5*( rCdU_top(ji,jj+1)+rCdU_top(ji,jj) ) / ze3va
+               END DO
+            END DO
+         ENDIF
+      ENDIF
+
+      ! Matrix inversion
+      !-----------------------------------------------------------------------
+      !   solve m.x = y  where m is a tri diagonal matrix ( jpk*jpk )
+      !
+      !        ( zwd1 zws1   0    0    0  )( zwx1 ) ( zwy1 )
+      !        ( zwi2 zwd2 zws2   0    0  )( zwx2 ) ( zwy2 )
+      !        (  0   zwi3 zwd3 zws3   0  )( zwx3 )=( zwy3 )
+      !        (        ...               )( ...  ) ( ...  )
+      !        (  0    0    0   zwik zwdk )( zwxk ) ( zwyk )
+      !
+      !   m is decomposed in the product of an upper and lower triangular matrix
+      !   The 3 diagonal terms are in 2d arrays: zwd, zws, zwi
+      !   The solution (after velocity) is in 2d array va
+      !-----------------------------------------------------------------------
+      !
+      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.
+               zwd(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwd(ji,jj,jk-1)
+            END DO
+         END DO
+      END DO
+      !
+      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 ) * e3v_n(ji,jj,1) + r_vvl * e3v_a(ji,jj,1) 
+            va(ji,jj,1) = va(ji,jj,1) + r2dt * 0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
+               &                                      / ( ze3va * rau0 ) * vmask(ji,jj,1) 
+         END DO
+      END DO
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               va(ji,jj,jk) = va(ji,jj,jk) - zwi(ji,jj,jk) / zwd(ji,jj,jk-1) * va(ji,jj,jk-1)
+            END DO
+         END DO
+      END DO
+      !
+      DO jj = 2, jpjm1        !==  third recurrence : SOLk = ( Lk - Uk * SOLk+1 ) / Dk  ==!
+         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
+               va(ji,jj,jk) = ( va(ji,jj,jk) - zws(ji,jj,jk) * va(ji,jj,jk+1) ) / zwd(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF( l_trddyn )   THEN                      ! save the vertical diffusive trends for further diagnostics
+         ztrdu(:,:,:) = ( ua(:,:,:) - ub(:,:,:) ) / r2dt - ztrdu(:,:,:)
+         ztrdv(:,:,:) = ( va(:,:,:) - vb(:,:,:) ) / r2dt - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_zdf, kt )
+         DEALLOCATE( ztrdu, ztrdv ) 
+      ENDIF
+      !                                          ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' zdf  - Ua: ', mask1=umask,               &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+         !
+      IF( ln_timing )   CALL timing_stop('dyn_zdf')
+      !
+   END SUBROUTINE dyn_zdf
+
+   !!==============================================================================
+END MODULE dynzdf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/sshwzv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/sshwzv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/sshwzv.F90	(revision 14097)
@@ -0,0 +1,389 @@
+MODULE sshwzv   
+   !!==============================================================================
+   !!                       ***  MODULE  sshwzv  ***
+   !! Ocean dynamics : sea surface height and vertical velocity
+   !!==============================================================================
+   !! History :  3.1  !  2009-02  (G. Madec, M. Leclair)  Original code
+   !!            3.3  !  2010-04  (M. Leclair, G. Madec)  modified LF-RA 
+   !!             -   !  2010-05  (K. Mogensen, A. Weaver, M. Martin, D. Lea) Assimilation interface
+   !!             -   !  2010-09  (D.Storkey and E.O'Dea) bug fixes for BDY module
+   !!            3.3  !  2011-10  (M. Leclair) split former ssh_wzv routine and remove all vvl related work
+   !!            4.0  !  2018-12  (A. Coward) add mixed implicit/explicit advection
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ssh_nxt       : after ssh
+   !!   ssh_swp       : filter ans swap the ssh arrays
+   !!   wzv           : compute now vertical velocity
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables 
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE domvvl         ! Variable volume
+   USE divhor         ! horizontal divergence
+   USE phycst         ! physical constants
+   USE bdy_oce , ONLY : ln_bdy, bdytmask   ! Open BounDarY
+   USE bdydyn2d       ! bdy_ssh routine
+#if defined key_agrif
+   USE agrif_oce_interp
+#endif
+   !
+   USE iom 
+   USE in_out_manager ! I/O manager
+   USE restart        ! only for lrst_oce
+   USE prtctl         ! Print control
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link)
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   USE wet_dry        ! Wetting/Drying flux limiting
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ssh_nxt    ! called by step.F90
+   PUBLIC   wzv        ! called by step.F90
+   PUBLIC   wAimp      ! called by step.F90
+   PUBLIC   ssh_swp    ! called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ssh_nxt( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE ssh_nxt  ***
+      !!                   
+      !! ** Purpose :   compute the after ssh (ssha)
+      !!
+      !! ** Method  : - Using the incompressibility hypothesis, the ssh increment
+      !!      is computed by integrating the horizontal divergence and multiply by
+      !!      by the time step.
+      !!
+      !! ** action  :   ssha, after sea surface height
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step
+      ! 
+      INTEGER  ::   jk            ! dummy loop indice
+      REAL(wp) ::   z2dt, zcoef   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zhdiv   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ssh_nxt')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'ssh_nxt : after sea surface height'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      z2dt = 2._wp * rdt                          ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == nit000 )   z2dt = rdt
+      zcoef = 0.5_wp * r1_rau0
+
+      !                                           !------------------------------!
+      !                                           !   After Sea Surface Height   !
+      !                                           !------------------------------!
+      IF(ln_wd_il) THEN
+         CALL wad_lmt(sshb, zcoef * (emp_b(:,:) + emp(:,:)), z2dt)
+      ENDIF
+
+      CALL div_hor( kt )                               ! Horizontal divergence
+      !
+      zhdiv(:,:) = 0._wp
+      DO jk = 1, jpkm1                                 ! Horizontal divergence of barotropic transports
+        zhdiv(:,:) = zhdiv(:,:) + e3t_n(:,:,jk) * hdivn(:,:,jk)
+      END DO
+      !                                                ! Sea surface elevation time stepping
+      ! In time-split case we need a first guess of the ssh after (using the baroclinic timestep) in order to
+      ! compute the vertical velocity which can be used to compute the non-linear terms of the momentum equations.
+      ! 
+      ssha(:,:) = (  sshb(:,:) - z2dt * ( zcoef * ( emp_b(:,:) + emp(:,:) ) + zhdiv(:,:) )  ) * ssmask(:,:)
+      !
+#if defined key_agrif
+      CALL agrif_ssh( kt )
+#endif
+      !
+      IF ( .NOT.ln_dynspg_ts ) THEN
+         IF( ln_bdy ) THEN
+            CALL lbc_lnk( 'sshwzv', ssha, 'T', 1. )    ! Not sure that's necessary
+            CALL bdy_ssh( ssha )             ! Duplicate sea level across open boundaries
+         ENDIF
+      ENDIF
+      !                                           !------------------------------!
+      !                                           !           outputs            !
+      !                                           !------------------------------!
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=ssha, clinfo1=' ssha  - : ', mask1=tmask )
+      !
+      IF( ln_timing )   CALL timing_stop('ssh_nxt')
+      !
+   END SUBROUTINE ssh_nxt
+
+   
+   SUBROUTINE wzv( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE wzv  ***
+      !!                   
+      !! ** Purpose :   compute the now vertical velocity
+      !!
+      !! ** Method  : - Using the incompressibility hypothesis, the vertical 
+      !!      velocity is computed by integrating the horizontal divergence  
+      !!      from the bottom to the surface minus the scale factor evolution.
+      !!        The boundary conditions are w=0 at the bottom (no flux) and.
+      !!
+      !! ** action  :   wn      : now vertical velocity
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   z1_2dt       ! local scalars
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zhdiv
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('wzv')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'wzv : now vertical velocity '
+         IF(lwp) WRITE(numout,*) '~~~~~ '
+         !
+         wn(:,:,jpk) = 0._wp                  ! bottom boundary condition: w=0 (set once for all)
+      ENDIF
+      !                                           !------------------------------!
+      !                                           !     Now Vertical Velocity    !
+      !                                           !------------------------------!
+      z1_2dt = 1. / ( 2. * rdt )                         ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == nit000 )   z1_2dt = 1. / rdt
+      !
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN      ! z_tilde and layer cases
+         ALLOCATE( zhdiv(jpi,jpj,jpk) ) 
+         !
+         DO jk = 1, jpkm1
+            ! horizontal divergence of thickness diffusion transport ( velocity multiplied by e3t)
+            ! - ML - note: computation already done in dom_vvl_sf_nxt. Could be optimized (not critical and clearer this way)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zhdiv(ji,jj,jk) = r1_e1e2t(ji,jj) * ( un_td(ji,jj,jk) - un_td(ji-1,jj,jk) + vn_td(ji,jj,jk) - vn_td(ji,jj-1,jk) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk('sshwzv', zhdiv, 'T', 1.)  ! - ML - Perhaps not necessary: not used for horizontal "connexions"
+         !                             ! Is it problematic to have a wrong vertical velocity in boundary cells?
+         !                             ! Same question holds for hdivn. Perhaps just for security
+         DO jk = jpkm1, 1, -1                       ! integrate from the bottom the hor. divergence
+            ! computation of w
+            wn(:,:,jk) = wn(:,:,jk+1) - (  e3t_n(:,:,jk) * hdivn(:,:,jk) + zhdiv(:,:,jk)    &
+               &                         + z1_2dt * ( e3t_a(:,:,jk) - e3t_b(:,:,jk) )     ) * tmask(:,:,jk)
+         END DO
+         !          IF( ln_vvl_layer ) wn(:,:,:) = 0.e0
+         DEALLOCATE( zhdiv ) 
+      ELSE   ! z_star and linear free surface cases
+         DO jk = jpkm1, 1, -1                       ! integrate from the bottom the hor. divergence
+            ! computation of w
+            wn(:,:,jk) = wn(:,:,jk+1) - (  e3t_n(:,:,jk) * hdivn(:,:,jk)                 &
+               &                         + z1_2dt * ( e3t_a(:,:,jk) - e3t_b(:,:,jk) )  ) * tmask(:,:,jk)
+         END DO
+      ENDIF
+
+      IF( ln_bdy ) THEN
+         DO jk = 1, jpkm1
+            wn(:,:,jk) = wn(:,:,jk) * bdytmask(:,:)
+         END DO
+      ENDIF
+      !
+#if defined key_agrif 
+      IF( .NOT. AGRIF_Root() ) THEN 
+         IF ( l_Eastedge )  wn(nlci-1 , :     ,:) = 0.e0      ! east 
+         IF ( l_Westedge )  wn(2      , :     ,:) = 0.e0      ! west 
+         IF ( l_Northedge ) wn(:      ,nlcj-1 ,:) = 0.e0      ! north 
+         IF ( l_Southedge ) wn(:      ,2      ,:) = 0.e0      ! south 
+      ENDIF 
+#endif 
+      !
+      IF( ln_timing )   CALL timing_stop('wzv')
+      !
+   END SUBROUTINE wzv
+
+
+   SUBROUTINE ssh_swp( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ssh_nxt  ***
+      !!
+      !! ** Purpose :   achieve the sea surface  height time stepping by 
+      !!              applying Asselin time filter and swapping the arrays
+      !!              ssha  already computed in ssh_nxt  
+      !!
+      !! ** Method  : - apply Asselin time fiter to now ssh (excluding the forcing
+      !!              from the filter, see Leclair and Madec 2010) and swap :
+      !!                sshn = ssha + atfp * ( sshb -2 sshn + ssha )
+      !!                            - atfp * rdt * ( emp_b - emp ) / rau0
+      !!                sshn = ssha
+      !!
+      !! ** action  : - sshb, sshn   : before & now sea surface height
+      !!                               ready for the next time step
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      REAL(wp) ::   zcoef   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ssh_swp')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'ssh_swp : Asselin time filter and swap of sea surface height'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !              !==  Euler time-stepping: no filter, just swap  ==!
+      IF ( neuler == 0 .AND. kt == nit000 ) THEN
+         sshn(:,:) = ssha(:,:)                              ! now    <-- after  (before already = now)
+         !
+      ELSE           !==  Leap-Frog time-stepping: Asselin filter + swap  ==!
+         !                                                  ! before <-- now filtered
+         sshb(:,:) = sshn(:,:) + atfp * ( sshb(:,:) - 2 * sshn(:,:) + ssha(:,:) )
+         IF( .NOT.ln_linssh ) THEN                          ! before <-- with forcing removed
+            zcoef = atfp * rdt * r1_rau0
+            sshb(:,:) = sshb(:,:) - zcoef * (     emp_b(:,:) - emp   (:,:)   &
+               &                             -    rnf_b(:,:) + rnf   (:,:)   &
+               &                             + fwfisf_b(:,:) - fwfisf(:,:)   ) * ssmask(:,:)
+         ENDIF
+         sshn(:,:) = ssha(:,:)                              ! now <-- after
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=sshb, clinfo1=' sshb  - : ', mask1=tmask )
+      !
+      IF( ln_timing )   CALL timing_stop('ssh_swp')
+      !
+   END SUBROUTINE ssh_swp
+
+   SUBROUTINE wAimp( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE wAimp  ***
+      !!                   
+      !! ** Purpose :   compute the Courant number and partition vertical velocity
+      !!                if a proportion needs to be treated implicitly
+      !!
+      !! ** Method  : - 
+      !!
+      !! ** action  :   wn      : now vertical velocity (to be handled explicitly)
+      !!            :   wi      : now vertical velocity (for implicit treatment)
+      !!
+      !! Reference  : Shchepetkin, A. F. (2015): An adaptive, Courant-number-dependent
+      !!              implicit scheme for vertical advection in oceanic modeling. 
+      !!              Ocean Modelling, 91, 38-69.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp)             ::   zCu, zcff, z1_e3t                     ! local scalars
+      REAL(wp) , PARAMETER ::   Cu_min = 0.15_wp                      ! local parameters
+      REAL(wp) , PARAMETER ::   Cu_max = 0.30_wp                      ! local parameters
+      REAL(wp) , PARAMETER ::   Cu_cut = 2._wp*Cu_max - Cu_min        ! local parameters
+      REAL(wp) , PARAMETER ::   Fcu    = 4._wp*Cu_max*(Cu_max-Cu_min) ! local parameters
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('wAimp')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'wAimp : Courant number-based partitioning of now vertical velocity '
+         IF(lwp) WRITE(numout,*) '~~~~~ '
+         wi(:,:,:) = 0._wp
+      ENDIF
+      !
+      ! Calculate Courant numbers
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, fs_jpim1   ! vector opt.
+                  z1_e3t = 1._wp / e3t_n(ji,jj,jk)
+                  ! 2*rdt and not r2dt (for restartability)
+                  Cu_adv(ji,jj,jk) = 2._wp * rdt * ( ( MAX( wn(ji,jj,jk) , 0._wp ) - MIN( wn(ji,jj,jk+1) , 0._wp ) )                       &  
+                     &                             + ( MAX( e2u(ji  ,jj)*e3u_n(ji  ,jj,jk)*un(ji  ,jj,jk) + un_td(ji  ,jj,jk), 0._wp ) -   &
+                     &                                 MIN( e2u(ji-1,jj)*e3u_n(ji-1,jj,jk)*un(ji-1,jj,jk) + un_td(ji-1,jj,jk), 0._wp ) )   &
+                     &                               * r1_e1e2t(ji,jj)                                                                     &
+                     &                             + ( MAX( e1v(ji,jj  )*e3v_n(ji,jj  ,jk)*vn(ji,jj  ,jk) + vn_td(ji,jj  ,jk), 0._wp ) -   &
+                     &                                 MIN( e1v(ji,jj-1)*e3v_n(ji,jj-1,jk)*vn(ji,jj-1,jk) + vn_td(ji,jj-1,jk), 0._wp ) )   &
+                     &                               * r1_e1e2t(ji,jj)                                                                     &
+                     &                             ) * z1_e3t
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, fs_jpim1   ! vector opt.
+                  z1_e3t = 1._wp / e3t_n(ji,jj,jk)
+                  ! 2*rdt and not r2dt (for restartability)
+                  Cu_adv(ji,jj,jk) = 2._wp * rdt * ( ( MAX( wn(ji,jj,jk) , 0._wp ) - MIN( wn(ji,jj,jk+1) , 0._wp ) )   & 
+                     &                             + ( MAX( e2u(ji  ,jj)*e3u_n(ji  ,jj,jk)*un(ji  ,jj,jk), 0._wp ) -   &
+                     &                                 MIN( e2u(ji-1,jj)*e3u_n(ji-1,jj,jk)*un(ji-1,jj,jk), 0._wp ) )   &
+                     &                               * r1_e1e2t(ji,jj)                                                 &
+                     &                             + ( MAX( e1v(ji,jj  )*e3v_n(ji,jj  ,jk)*vn(ji,jj  ,jk), 0._wp ) -   &
+                     &                                 MIN( e1v(ji,jj-1)*e3v_n(ji,jj-1,jk)*vn(ji,jj-1,jk), 0._wp ) )   &
+                     &                               * r1_e1e2t(ji,jj)                                                 &
+                     &                             ) * z1_e3t
+               END DO
+            END DO
+         END DO
+      ENDIF
+      CALL lbc_lnk( 'sshwzv', Cu_adv, 'T', 1. )
+      !
+      CALL iom_put("Courant",Cu_adv)
+      !
+      IF( MAXVAL( Cu_adv(:,:,:) ) > Cu_min ) THEN       ! Quick check if any breaches anywhere
+         DO jk = jpkm1, 2, -1                           ! or scan Courant criterion and partition
+            DO jj = 1, jpj                              ! w where necessary
+               DO ji = 1, jpi
+                  !
+                  zCu = MAX( Cu_adv(ji,jj,jk) , Cu_adv(ji,jj,jk-1) )
+! alt:
+!                  IF ( wn(ji,jj,jk) > 0._wp ) THEN 
+!                     zCu =  Cu_adv(ji,jj,jk) 
+!                  ELSE
+!                     zCu =  Cu_adv(ji,jj,jk-1)
+!                  ENDIF 
+                  !
+                  IF( zCu <= Cu_min ) THEN              !<-- Fully explicit
+                     zcff = 0._wp
+                  ELSEIF( zCu < Cu_cut ) THEN           !<-- Mixed explicit
+                     zcff = ( zCu - Cu_min )**2
+                     zcff = zcff / ( Fcu + zcff )
+                  ELSE                                  !<-- Mostly implicit
+                     zcff = ( zCu - Cu_max )/ zCu
+                  ENDIF
+                  zcff = MIN(1._wp, zcff)
+                  !
+                  wi(ji,jj,jk) =           zcff   * wn(ji,jj,jk)
+                  wn(ji,jj,jk) = ( 1._wp - zcff ) * wn(ji,jj,jk)
+                  !
+                  Cu_adv(ji,jj,jk) = zcff               ! Reuse array to output coefficient below and in stp_ctl
+               END DO
+            END DO
+         END DO
+         Cu_adv(:,:,1) = 0._wp 
+      ELSE
+         ! Fully explicit everywhere
+         Cu_adv(:,:,:) = 0._wp                          ! Reuse array to output coefficient below and in stp_ctl
+         wi    (:,:,:) = 0._wp
+      ENDIF
+      CALL iom_put("wimp",wi) 
+      CALL iom_put("wi_cff",Cu_adv)
+      CALL iom_put("wexp",wn)
+      !
+      IF( ln_timing )   CALL timing_stop('wAimp')
+      !
+   END SUBROUTINE wAimp
+   !!======================================================================
+END MODULE sshwzv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/wet_dry.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/wet_dry.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/DYN/wet_dry.F90	(revision 14097)
@@ -0,0 +1,401 @@
+MODULE wet_dry
+
+   !! includes updates to namelist namwad for diagnostic outputs of ROMS wetting and drying
+
+   !!==============================================================================
+   !!                       ***  MODULE  wet_dry  ***
+   !! Wetting and drying includes initialisation routine and routines to
+   !! compute and apply flux limiters and preserve water depth positivity
+   !! only effects if wetting/drying is on (ln_wd_il == .true. or ln_wd_dl==.true. )
+   !!==============================================================================
+   !! History :  3.6  ! 2014-09  ((H.Liu)  Original code
+   !!                 ! will add the runoff and periodic BC case later
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   wad_init      : initialisation of wetting and drying
+   !!   wad_lmt       : horizontal flux limiter and limited velocity when wetting and drying happens
+   !!   wad_lmt_bt    : same as wad_lmt for the barotropic stepping (dynspg_ts)
+   !!----------------------------------------------------------------------
+   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 sbcrnf         ! river runoff 
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! MPP library
+   USE timing         ! timing of the main modules
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !!----------------------------------------------------------------------
+   !! critical depths,filters, limiters,and masks for  Wetting and Drying
+   !! ---------------------------------------------------------------------
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::   wdmask   !: u- and v- limiter 
+   !                                                           !  (can include negative depths)
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::   wdramp, wdrampu, wdrampv !: for hpg limiting
+
+   LOGICAL,  PUBLIC  ::   ln_wd_il    !: Wetting/drying il activation switch (T:on,F:off)
+   LOGICAL,  PUBLIC  ::   ln_wd_dl    !: Wetting/drying dl activation switch (T:on,F:off)
+   REAL(wp), PUBLIC  ::   rn_wdmin0   !: depth at which wetting/drying starts
+   REAL(wp), PUBLIC  ::   rn_wdmin1   !: minimum water depth on dried cells
+   REAL(wp), PUBLIC  ::   r_rn_wdmin1 !: 1/minimum water depth on dried cells 
+   REAL(wp), PUBLIC  ::   rn_wdmin2   !: tolerance of minimum water depth on dried cells
+   REAL(wp), PUBLIC  ::   rn_wd_sbcdep   !: Depth at which to taper sbc fluxes
+   REAL(wp), PUBLIC  ::   rn_wd_sbcfra   !: Fraction of SBC at taper depth
+   REAL(wp), PUBLIC  ::   rn_wdld     !: land elevation below which wetting/drying will be considered
+   INTEGER , PUBLIC  ::   nn_wdit     !: maximum number of iteration for W/D limiter
+   LOGICAL,  PUBLIC  ::   ln_wd_dl_bc !: DL scheme: True implies 3D velocities are set to the barotropic values at points 
+                                      !: where the flow is from wet points on less than half the barotropic sub-steps  
+   LOGICAL,  PUBLIC  ::  ln_wd_dl_rmp !: use a ramp for the dl flux limiter between 2 rn_wdmin1 and rn_wdmin1 (rather than a cut-off at rn_wdmin1)      
+   REAL(wp), PUBLIC  ::   ssh_ref     !: height of z=0 with respect to the geoid; 
+
+   LOGICAL,  PUBLIC  ::   ll_wd       !: Wetting/drying activation switch if either ln_wd_il or ln_wd_dl
+
+   PUBLIC   wad_init                  ! initialisation routine called by step.F90
+   PUBLIC   wad_lmt                   ! routine called by sshwzv.F90
+   PUBLIC   wad_lmt_bt                ! routine called by dynspg_ts.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE wad_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE wad_init  ***
+      !!                    
+      !! ** Purpose :   read wetting and drying namelist and print the variables.
+      !!
+      !! ** input   : - namwad namelist
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ios, ierr   ! Local integer
+      !!
+      NAMELIST/namwad/ ln_wd_il, ln_wd_dl   , rn_wdmin0, rn_wdmin1, rn_wdmin2, rn_wdld,   &
+         &             nn_wdit , ln_wd_dl_bc, ln_wd_dl_rmp, rn_wd_sbcdep,rn_wd_sbcfra
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namwad in reference namelist : Parameters for Wetting/Drying
+      READ  ( numnam_ref, namwad, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namwad in reference namelist' ) 
+      REWIND( numnam_cfg )              ! Namelist namwad in configuration namelist : Parameters for Wetting/Drying
+      READ  ( numnam_cfg, namwad, IOSTAT = ios, ERR = 906)
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'namwad in configuration namelist' )
+      IF(lwm) WRITE ( numond, namwad )
+      !
+      IF( rn_wd_sbcfra>=1 )   CALL ctl_stop( 'STOP', 'rn_wd_sbcfra >=1 : must be < 1' )
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'wad_init : Wetting and drying initialization through namelist read'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist namwad'
+         WRITE(numout,*) '      Logical for Iter Lim wd option   ln_wd_il     = ', ln_wd_il
+         WRITE(numout,*) '      Logical for Dir. Lim wd option   ln_wd_dl     = ', ln_wd_dl
+         WRITE(numout,*) '      Depth at which wet/drying starts rn_wdmin0    = ', rn_wdmin0
+         WRITE(numout,*) '      Minimum wet depth on dried cells rn_wdmin1    = ', rn_wdmin1
+         WRITE(numout,*) '      Tolerance of min wet depth       rn_wdmin2    = ', rn_wdmin2
+         WRITE(numout,*) '      land elevation threshold         rn_wdld      = ', rn_wdld
+         WRITE(numout,*) '      Max iteration for W/D limiter    nn_wdit      = ', nn_wdit
+         WRITE(numout,*) '      T => baroclinic u,v=0 at dry pts: ln_wd_dl_bc = ', ln_wd_dl_bc     
+         WRITE(numout,*) '      use a ramp for rwd limiter:  ln_wd_dl_rwd_rmp = ', ln_wd_dl_rmp
+         WRITE(numout,*) '      cut off depth sbc for wd   rn_wd_sbcdep       = ', rn_wd_sbcdep
+         WRITE(numout,*) '      fraction to start sbc wgt rn_wd_sbcfra        = ', rn_wd_sbcfra
+      ENDIF
+      IF( .NOT. ln_read_cfg ) THEN
+         IF(lwp) WRITE(numout,*) '      No configuration file so seting ssh_ref to zero  '
+         ssh_ref=0._wp
+      ENDIF
+
+      r_rn_wdmin1 = 1 / rn_wdmin1
+      ll_wd = .FALSE.
+      IF( ln_wd_il .OR. ln_wd_dl ) THEN
+         ll_wd = .TRUE.
+         ALLOCATE( wdmask(jpi,jpj),   STAT=ierr )
+         ALLOCATE( wdramp(jpi,jpj), wdrampu(jpi,jpj), wdrampv(jpi,jpj), STAT=ierr ) 
+         IF( ierr /= 0 ) CALL ctl_stop('STOP', 'wad_init : Array allocation error')
+      ENDIF
+      !
+   END SUBROUTINE wad_init
+
+
+   SUBROUTINE wad_lmt( sshb1, sshemp, z2dt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE wad_lmt  ***
+      !!                    
+      !! ** Purpose :   generate flux limiters for wetting/drying
+      !!
+      !! ** Method  : - Prevent negative depth occurring (Not ready for Agrif) 
+      !!
+      !! ** Action  : - calculate flux limiter and W/D flag
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   sshb1        !!gm DOCTOR names: should start with p !
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   sshemp
+      REAL(wp)                , INTENT(in   ) ::   z2dt
+      !
+      INTEGER  ::   ji, jj, jk, jk1     ! dummy loop indices
+      INTEGER  ::   jflag               ! local scalar
+      REAL(wp) ::   zcoef, zdep1, zdep2 ! local scalars
+      REAL(wp) ::   zzflxp, zzflxn      ! local scalars
+      REAL(wp) ::   zdepwd              ! local scalar, always wet cell depth
+      REAL(wp) ::   ztmp                ! local scalars
+      REAL(wp),  DIMENSION(jpi,jpj) ::   zwdlmtu, zwdlmtv   ! W/D flux limiters
+      REAL(wp),  DIMENSION(jpi,jpj) ::   zflxp  ,  zflxn    ! local 2D workspace
+      REAL(wp),  DIMENSION(jpi,jpj) ::   zflxu  ,  zflxv    ! local 2D workspace
+      REAL(wp),  DIMENSION(jpi,jpj) ::   zflxu1 , zflxv1    ! local 2D workspace
+      !!----------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('wad_lmt')      !
+      !
+      DO jk = 1, jpkm1
+         un(:,:,jk) = un(:,:,jk) * zwdlmtu(:,:) 
+         vn(:,:,jk) = vn(:,:,jk) * zwdlmtv(:,:) 
+      END DO
+      jflag  = 0
+      zdepwd = 50._wp      ! maximum depth on which that W/D could possibly happen
+      !
+      zflxp(:,:)   = 0._wp
+      zflxn(:,:)   = 0._wp
+      zflxu(:,:)   = 0._wp
+      zflxv(:,:)   = 0._wp
+      !
+      zwdlmtu(:,:) = 1._wp
+      zwdlmtv(:,:) = 1._wp
+      !
+      DO jk = 1, jpkm1     ! Horizontal Flux in u and v direction
+         zflxu(:,:) = zflxu(:,:) + e3u_n(:,:,jk) * un(:,:,jk) * umask(:,:,jk)
+         zflxv(:,:) = zflxv(:,:) + e3v_n(:,:,jk) * vn(:,:,jk) * vmask(:,:,jk)
+      END DO
+      zflxu(:,:) = zflxu(:,:) * e2u(:,:)
+      zflxv(:,:) = zflxv(:,:) * e1v(:,:)
+      !
+      wdmask(:,:) = 1._wp
+      DO jj = 2, jpj
+         DO ji = 2, jpi 
+            !
+            IF( tmask(ji,jj,1)        < 0.5_wp )   CYCLE    ! we don't care about land cells
+            IF( ht_0(ji,jj) - ssh_ref > zdepwd )   CYCLE    ! and cells which are unlikely to dry
+            !
+            zflxp(ji,jj) = MAX( zflxu(ji,jj) , 0._wp ) - MIN( zflxu(ji-1,jj  ) , 0._wp )   &
+               &         + MAX( zflxv(ji,jj) , 0._wp ) - MIN( zflxv(ji,  jj-1) , 0._wp ) 
+            zflxn(ji,jj) = MIN( zflxu(ji,jj) , 0._wp ) - MAX( zflxu(ji-1,jj  ) , 0._wp )   &
+               &         + MIN( zflxv(ji,jj) , 0._wp ) - MAX( zflxv(ji,  jj-1) , 0._wp ) 
+            !
+            zdep2 = ht_0(ji,jj) + sshb1(ji,jj) - rn_wdmin1
+            IF( zdep2 <= 0._wp ) THEN     ! add more safty, but not necessary
+               sshb1(ji,jj) = rn_wdmin1 - ht_0(ji,jj)
+               IF(zflxu(ji,  jj) > 0._wp) zwdlmtu(ji  ,jj) = 0._wp
+               IF(zflxu(ji-1,jj) < 0._wp) zwdlmtu(ji-1,jj) = 0._wp
+               IF(zflxv(ji,  jj) > 0._wp) zwdlmtv(ji  ,jj) = 0._wp
+               IF(zflxv(ji,jj-1) < 0._wp) zwdlmtv(ji,jj-1) = 0._wp 
+               wdmask(ji,jj) = 0._wp
+            END IF
+         END DO
+      END DO
+      !
+      !           ! HPG limiter from jholt
+      wdramp(:,:) = min((ht_0(:,:) + sshb1(:,:) - rn_wdmin1)/(rn_wdmin0 - rn_wdmin1),1.0_wp)
+      !jth assume don't need a lbc_lnk here
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1
+            wdrampu(ji,jj) = MIN( wdramp(ji,jj) , wdramp(ji+1,jj) )
+            wdrampv(ji,jj) = MIN( wdramp(ji,jj) , wdramp(ji,jj+1) )
+         END DO
+      END DO
+      !           ! end HPG limiter
+      !
+      !
+      DO jk1 = 1, nn_wdit + 1      !==  start limiter iterations  ==!
+         !
+         zflxu1(:,:) = zflxu(:,:) * zwdlmtu(:,:)
+         zflxv1(:,:) = zflxv(:,:) * zwdlmtv(:,:)
+         jflag = 0     ! flag indicating if any further iterations are needed
+         !
+         DO jj = 2, jpj
+            DO ji = 2, jpi 
+               IF( tmask(ji, jj, 1) < 0.5_wp )   CYCLE 
+               IF( ht_0(ji,jj)      > zdepwd )   CYCLE
+               !
+               ztmp = e1e2t(ji,jj)
+               !
+               zzflxp = MAX( zflxu1(ji,jj) , 0._wp ) - MIN( zflxu1(ji-1,jj  ) , 0._wp)   &
+                  &   + MAX( zflxv1(ji,jj) , 0._wp ) - MIN( zflxv1(ji,  jj-1) , 0._wp) 
+               zzflxn = MIN( zflxu1(ji,jj) , 0._wp ) - MAX( zflxu1(ji-1,jj  ) , 0._wp)   &
+                  &   + MIN( zflxv1(ji,jj) , 0._wp ) - MAX( zflxv1(ji,  jj-1) , 0._wp) 
+               !
+               zdep1 = (zzflxp + zzflxn) * z2dt / ztmp
+               zdep2 = ht_0(ji,jj) + sshb1(ji,jj) - rn_wdmin1 - z2dt * sshemp(ji,jj)
+               !
+               IF( zdep1 > zdep2 ) THEN
+                  wdmask(ji, jj) = 0._wp
+                  zcoef = ( ( zdep2 - rn_wdmin2 ) * ztmp - zzflxn * z2dt ) / ( zflxp(ji,jj) * z2dt )
+                  !zcoef = ( ( zdep2 - rn_wdmin2 ) * ztmp - zzflxn * z2dt ) / ( zzflxp * z2dt )
+                  ! flag if the limiter has been used but stop flagging if the only
+                  ! changes have zeroed the coefficient since further iterations will
+                  ! not change anything
+                  IF( zcoef > 0._wp ) THEN   ;   jflag = 1 
+                  ELSE                       ;   zcoef = 0._wp
+                  ENDIF
+                  IF( jk1 > nn_wdit )   zcoef = 0._wp
+                  IF( zflxu1(ji  ,jj  ) > 0._wp )   zwdlmtu(ji  ,jj  ) = zcoef
+                  IF( zflxu1(ji-1,jj  ) < 0._wp )   zwdlmtu(ji-1,jj  ) = zcoef
+                  IF( zflxv1(ji  ,jj  ) > 0._wp )   zwdlmtv(ji  ,jj  ) = zcoef
+                  IF( zflxv1(ji  ,jj-1) < 0._wp )   zwdlmtv(ji  ,jj-1) = zcoef
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'wet_dry', zwdlmtu, 'U', 1., zwdlmtv, 'V', 1. )
+         !
+         CALL mpp_max('wet_dry', jflag)   !max over the global domain
+         !
+         IF( jflag == 0 )   EXIT
+         !
+      END DO  ! jk1 loop
+      !
+      DO jk = 1, jpkm1
+         un(:,:,jk) = un(:,:,jk) * zwdlmtu(:,:) 
+         vn(:,:,jk) = vn(:,:,jk) * zwdlmtv(:,:) 
+      END DO
+      un_b(:,:) = un_b(:,:) * zwdlmtu(:, :)
+      vn_b(:,:) = vn_b(:,:) * zwdlmtv(:, :)
+      !
+!!gm TO BE SUPPRESSED ?  these lbc_lnk are useless since zwdlmtu and zwdlmtv are defined everywhere !
+      CALL lbc_lnk_multi( 'wet_dry', un  , 'U', -1., vn  , 'V', -1. )
+      CALL lbc_lnk_multi( 'wet_dry', un_b, 'U', -1., vn_b, 'V', -1. )
+!!gm
+      !
+      IF(jflag == 1 .AND. lwp)   WRITE(numout,*) 'Need more iterations in wad_lmt!!!'
+      !
+      !IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )          ! runoffs (update hdivn field)
+      !
+      IF( ln_timing )   CALL timing_stop('wad_lmt')      !
+      !
+   END SUBROUTINE wad_lmt
+
+
+   SUBROUTINE wad_lmt_bt( zflxu, zflxv, sshn_e, zssh_frc, rdtbt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE wad_lmt  ***
+      !!                    
+      !! ** Purpose :   limiting flux in the barotropic stepping (dynspg_ts)
+      !!
+      !! ** Method  : - Prevent negative depth occurring (Not ready for Agrif) 
+      !!
+      !! ** Action  : - calculate flux limiter and W/D flag
+      !!----------------------------------------------------------------------
+      REAL(wp)                , INTENT(in   ) ::   rdtbt    ! ocean time-step index
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   zflxu,  zflxv, sshn_e, zssh_frc  
+      !
+      INTEGER  ::   ji, jj, jk, jk1     ! dummy loop indices
+      INTEGER  ::   jflag               ! local integer
+      REAL(wp) ::   z2dt
+      REAL(wp) ::   zcoef, zdep1, zdep2 ! local scalars
+      REAL(wp) ::   zzflxp, zzflxn      ! local scalars
+      REAL(wp) ::   zdepwd              ! local scalar, always wet cell depth
+      REAL(wp) ::   ztmp                ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwdlmtu, zwdlmtv         !: W/D flux limiters
+      REAL(wp), DIMENSION(jpi,jpj) ::   zflxp,  zflxn            ! local 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj) ::   zflxu1, zflxv1           ! local 2D workspace
+      !!----------------------------------------------------------------------
+      IF( ln_timing )   CALL timing_start('wad_lmt_bt')      !
+      !
+      jflag  = 0
+      zdepwd = 50._wp   ! maximum depth that ocean cells can have W/D processes
+      !
+      z2dt = rdtbt   
+      !
+      zflxp(:,:)   = 0._wp
+      zflxn(:,:)   = 0._wp
+      zwdlmtu(:,:) = 1._wp
+      zwdlmtv(:,:) = 1._wp
+      !
+      DO jj = 2, jpj      ! Horizontal Flux in u and v direction
+         DO ji = 2, jpi 
+            !
+            IF( tmask(ji, jj, 1 ) < 0.5_wp) CYCLE   ! we don't care about land cells
+            IF( ht_0(ji,jj) > zdepwd )      CYCLE   ! and cells which are unlikely to dry
+            !
+            zflxp(ji,jj) = MAX( zflxu(ji,jj) , 0._wp ) - MIN( zflxu(ji-1,jj  ) , 0._wp )   &
+               &         + MAX( zflxv(ji,jj) , 0._wp ) - MIN( zflxv(ji,  jj-1) , 0._wp ) 
+            zflxn(ji,jj) = MIN( zflxu(ji,jj) , 0._wp ) - MAX( zflxu(ji-1,jj  ) , 0._wp )   &
+               &         + MIN( zflxv(ji,jj) , 0._wp ) - MAX( zflxv(ji,  jj-1) , 0._wp ) 
+            !
+            zdep2 = ht_0(ji,jj) + sshn_e(ji,jj) - rn_wdmin1
+            IF( zdep2 <= 0._wp ) THEN  !add more safety, but not necessary
+              sshn_e(ji,jj) = rn_wdmin1 - ht_0(ji,jj)
+              IF( zflxu(ji  ,jj  ) > 0._wp)   zwdlmtu(ji  ,jj  ) = 0._wp
+              IF( zflxu(ji-1,jj  ) < 0._wp)   zwdlmtu(ji-1,jj  ) = 0._wp
+              IF( zflxv(ji  ,jj  ) > 0._wp)   zwdlmtv(ji  ,jj  ) = 0._wp
+              IF( zflxv(ji  ,jj-1) < 0._wp)   zwdlmtv(ji  ,jj-1) = 0._wp 
+            ENDIF
+         END DO
+      END DO
+      !
+      DO jk1 = 1, nn_wdit + 1      !! start limiter iterations 
+         !
+         zflxu1(:,:) = zflxu(:,:) * zwdlmtu(:,:)
+         zflxv1(:,:) = zflxv(:,:) * zwdlmtv(:,:)
+         jflag = 0     ! flag indicating if any further iterations are needed
+         !
+         DO jj = 2, jpj
+            DO ji = 2, jpi 
+               !
+               IF( tmask(ji, jj, 1 ) < 0.5_wp )   CYCLE 
+               IF( ht_0(ji,jj)       > zdepwd )   CYCLE
+               !
+               ztmp = e1e2t(ji,jj)
+               !
+               zzflxp = max(zflxu1(ji,jj), 0._wp) - min(zflxu1(ji-1,jj),   0._wp)   &
+                  &   + max(zflxv1(ji,jj), 0._wp) - min(zflxv1(ji,  jj-1), 0._wp) 
+               zzflxn = min(zflxu1(ji,jj), 0._wp) - max(zflxu1(ji-1,jj),   0._wp)   &
+                  &   + min(zflxv1(ji,jj), 0._wp) - max(zflxv1(ji,  jj-1), 0._wp) 
+          
+               zdep1 = (zzflxp + zzflxn) * z2dt / ztmp
+               zdep2 = ht_0(ji,jj) + sshn_e(ji,jj) - rn_wdmin1 - z2dt * zssh_frc(ji,jj)
+          
+               IF(zdep1 > zdep2) THEN
+                 zcoef = ( ( zdep2 - rn_wdmin2 ) * ztmp - zzflxn * z2dt ) / ( zflxp(ji,jj) * z2dt )
+                 !zcoef = ( ( zdep2 - rn_wdmin2 ) * ztmp - zzflxn * z2dt ) / ( zzflxp * z2dt )
+                 ! flag if the limiter has been used but stop flagging if the only
+                 ! changes have zeroed the coefficient since further iterations will
+                 ! not change anything
+                 IF( zcoef > 0._wp ) THEN
+                    jflag = 1 
+                 ELSE
+                    zcoef = 0._wp
+                 ENDIF
+                 IF(jk1 > nn_wdit) zcoef = 0._wp
+                 IF(zflxu1(ji,  jj) > 0._wp) zwdlmtu(ji  ,jj) = zcoef
+                 IF(zflxu1(ji-1,jj) < 0._wp) zwdlmtu(ji-1,jj) = zcoef
+                 IF(zflxv1(ji,  jj) > 0._wp) zwdlmtv(ji  ,jj) = zcoef
+                 IF(zflxv1(ji,jj-1) < 0._wp) zwdlmtv(ji,jj-1) = zcoef
+               END IF
+            END DO ! ji loop
+         END DO  ! jj loop
+         !
+         CALL lbc_lnk_multi( 'wet_dry', zwdlmtu, 'U', 1., zwdlmtv, 'V', 1. )
+         !
+         CALL mpp_max('wet_dry', jflag)   !max over the global domain
+         !
+         IF(jflag == 0)   EXIT
+         !
+      END DO  ! jk1 loop
+      !
+      zflxu(:,:) = zflxu(:,:) * zwdlmtu(:, :) 
+      zflxv(:,:) = zflxv(:,:) * zwdlmtv(:, :) 
+      !
+!!gm THIS lbc_lnk is useless since it is already done at the end of the jk1-loop
+      CALL lbc_lnk_multi( 'wet_dry', zflxu, 'U', -1., zflxv, 'V', -1. )
+!!gm end
+      !
+      IF( jflag == 1 .AND. lwp )   WRITE(numout,*) 'Need more iterations in wad_lmt_bt!!!'
+      !
+      !IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )          ! runoffs (update hdivn field)
+      !
+      IF( ln_timing )   CALL timing_stop('wad_lmt_bt')      !
+      !
+   END SUBROUTINE wad_lmt_bt
+
+   !!==============================================================================
+END MODULE wet_dry
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo4rk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo4rk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo4rk.F90	(revision 14097)
@@ -0,0 +1,446 @@
+MODULE flo4rk
+   !!======================================================================
+   !!                    ***  MODULE  flo4rk  ***
+   !! Ocean floats :   trajectory computation using a 4th order Runge-Kutta
+   !!======================================================================
+   !!
+   !!----------------------------------------------------------------------
+   !!   flo_4rk        : Compute the geographical position of floats
+   !!   flo_interp     : interpolation
+   !!----------------------------------------------------------------------
+   USE flo_oce         ! ocean drifting floats
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE in_out_manager  ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   flo_4rk    ! routine called by floats.F90
+
+   !                                   ! RK4 and Lagrange interpolation coefficients
+   REAL(wp), DIMENSION (4) ::   tcoef1 = (/  1.0  ,  0.5  ,  0.5  ,  0.0  /)   ! 
+   REAL(wp), DIMENSION (4) ::   tcoef2 = (/  0.0  ,  0.5  ,  0.5  ,  1.0  /)   !
+   REAL(wp), DIMENSION (4) ::   scoef2 = (/  1.0  ,  2.0  ,  2.0  ,  1.0  /)   !
+   REAL(wp), DIMENSION (4) ::   rcoef  = (/-1./6. , 1./2. ,-1./2. , 1./6. /)   !
+   REAL(wp), DIMENSION (3) ::   scoef1 = (/  0.5  ,  0.5  ,  1.0  /)           !
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE flo_4rk( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE flo_4rk  ***
+      !!
+      !!  ** Purpose :   Compute the geographical position (lat,lon,depth)
+      !!       of each float at each time step.
+      !! 
+      !!  ** Method  :   The position of a float is computed with a 4th order
+      !!       Runge-Kutta scheme and and Lagrange interpolation.
+      !!         We need to know the velocity field, the old positions of the
+      !!       floats and the grid defined on the domain.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !!
+      INTEGER ::  jfl, jind           ! dummy loop indices
+      INTEGER ::  ierror              ! error value
+
+      REAL(wp), DIMENSION(jpnfl)   ::   zgifl , zgjfl , zgkfl    ! index RK  positions
+      REAL(wp), DIMENSION(jpnfl)   ::   zufl  , zvfl  , zwfl     ! interpolated velocity at the float position 
+      REAL(wp), DIMENSION(jpnfl,4) ::   zrkxfl, zrkyfl, zrkzfl   ! RK coefficients
+      !!---------------------------------------------------------------------
+      !
+      IF( ierror /= 0 ) THEN
+         WRITE(numout,*) 'flo_4rk: allocation of workspace arrays failed'
+      ENDIF
+
+    
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'flo_4rk : compute Runge Kutta trajectories for floats '
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      ! Verification of the floats positions. If one of them leave the domain
+      ! domain we replace the float near the border.
+      DO jfl = 1, jpnfl
+         ! i-direction
+         IF( tpifl(jfl) <= 1.5 ) THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the WEST border.'
+            tpifl(jfl) = tpifl(jfl) + 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at i=',tpifl(jfl)
+         ENDIF
+          
+         IF( tpifl(jfl) >= jpi-.5 ) THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the EAST border.'
+            tpifl(jfl) = tpifl(jfl) - 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at i=', tpifl(jfl)
+         ENDIF
+         ! j-direction
+         IF( tpjfl(jfl) <= 1.5 ) THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the SOUTH border.'
+            tpjfl(jfl) = tpjfl(jfl) + 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at j=', tpjfl(jfl)
+         ENDIF
+           
+         IF( tpjfl(jfl) >= jpj-.5 ) THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the NORTH border.'
+            tpjfl(jfl) = tpjfl(jfl) - 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at j=', tpjfl(jfl)
+         ENDIF
+         ! k-direction
+         IF( tpkfl(jfl) <= .5 ) THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the TOP border.'
+            tpkfl(jfl) = tpkfl(jfl) + 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at k=', tpkfl(jfl)
+         ENDIF
+         
+         IF( tpkfl(jfl) >= jpk-.5 )  THEN
+            IF(lwp)WRITE(numout,*)'!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!'
+            IF(lwp)WRITE(numout,*)'The float',jfl,'is out of the domain at the BOTTOM border.'
+            tpkfl(jfl) = tpkfl(jfl) - 1.
+            IF(lwp)WRITE(numout,*)'New initialisation for this float at k=', tpkfl(jfl)
+         ENDIF
+      END DO
+      
+      ! 4 steps of Runge-Kutta algorithme
+      ! initialisation of the positions 
+      
+      DO jfl = 1, jpnfl
+         zgifl(jfl) = tpifl(jfl)
+         zgjfl(jfl) = tpjfl(jfl)
+         zgkfl(jfl) = tpkfl(jfl)
+      END DO
+       
+      DO  jind = 1, 4         
+      
+         ! for each step we compute the compute the velocity with Lagrange interpolation
+         CALL flo_interp( zgifl, zgjfl, zgkfl, zufl, zvfl, zwfl, jind )
+         
+         ! computation of Runge-Kutta factor
+         DO jfl = 1, jpnfl
+            zrkxfl(jfl,jind) = rdt*zufl(jfl)
+            zrkyfl(jfl,jind) = rdt*zvfl(jfl)
+            zrkzfl(jfl,jind) = rdt*zwfl(jfl)
+         END DO
+         IF( jind /= 4 ) THEN
+            DO jfl = 1, jpnfl
+               zgifl(jfl) = (tpifl(jfl)) + scoef1(jind)*zrkxfl(jfl,jind)
+               zgjfl(jfl) = (tpjfl(jfl)) + scoef1(jind)*zrkyfl(jfl,jind)
+               zgkfl(jfl) = (tpkfl(jfl)) + scoef1(jind)*zrkzfl(jfl,jind)
+            END DO
+         ENDIF
+      END DO
+      DO jind = 1, 4
+         DO jfl = 1, jpnfl
+            tpifl(jfl) = tpifl(jfl) + scoef2(jind)*zrkxfl(jfl,jind)/6.
+            tpjfl(jfl) = tpjfl(jfl) + scoef2(jind)*zrkyfl(jfl,jind)/6.
+            tpkfl(jfl) = tpkfl(jfl) + scoef2(jind)*zrkzfl(jfl,jind)/6.
+         END DO
+      END DO
+      !
+      !
+   END SUBROUTINE flo_4rk
+
+
+   SUBROUTINE flo_interp( pxt , pyt , pzt ,      &
+      &                   pufl, pvfl, pwfl, ki )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE flointerp  ***
+      !!
+      !! ** Purpose :   Interpolation of the velocity on the float position
+      !! 
+      !! ** Method  :   Lagrange interpolation with the 64 neighboring
+      !!      points. This routine is call 4 time at each time step to
+      !!      compute velocity at the date and the position we need to
+      !!      integrated with RK method.
+      !!----------------------------------------------------------------------
+      REAL(wp) , DIMENSION(jpnfl), INTENT(in   ) ::   pxt , pyt , pzt    ! position of the float
+      REAL(wp) , DIMENSION(jpnfl), INTENT(  out) ::   pufl, pvfl, pwfl   ! velocity at this position
+      INTEGER                    , INTENT(in   ) ::   ki                 !
+      !!
+      INTEGER  ::   jfl, jind1, jind2, jind3   ! dummy loop indices
+      REAL(wp) ::   zsumu, zsumv, zsumw        ! local scalar
+      INTEGER  , DIMENSION(jpnfl)       ::   iilu, ijlu, iklu   ! nearest neighbour INDEX-u
+      INTEGER  , DIMENSION(jpnfl)       ::   iilv, ijlv, iklv   ! nearest neighbour INDEX-v
+      INTEGER  , DIMENSION(jpnfl)       ::   iilw, ijlw, iklw   ! nearest neighbour INDEX-w
+      INTEGER  , DIMENSION(jpnfl,4)     ::   iidu, ijdu, ikdu   ! 64 nearest neighbour INDEX-u
+      INTEGER  , DIMENSION(jpnfl,4)     ::   iidv, ijdv, ikdv   ! 64 nearest neighbour INDEX-v
+      INTEGER  , DIMENSION(jpnfl,4)     ::   iidw, ijdw, ikdw   ! 64 nearest neighbour INDEX-w
+      REAL(wp) , DIMENSION(jpnfl,4)     ::   zlagxu, zlagyu, zlagzu   ! Lagrange  coefficients
+      REAL(wp) , DIMENSION(jpnfl,4)     ::   zlagxv, zlagyv, zlagzv   !    -           -
+      REAL(wp) , DIMENSION(jpnfl,4)     ::   zlagxw, zlagyw, zlagzw   !    -           -
+      REAL(wp) , DIMENSION(jpnfl,4,4,4) ::   ztufl , ztvfl , ztwfl   ! velocity at choosen time step
+      !!---------------------------------------------------------------------
+ 
+      ! Interpolation of U velocity
+
+      ! nearest neightboring point for computation of u       
+      DO jfl = 1, jpnfl
+         iilu(jfl) = INT(pxt(jfl)-.5)
+         ijlu(jfl) = INT(pyt(jfl)-.5)
+         iklu(jfl) = INT(pzt(jfl))
+      END DO
+      
+      !  64 neightboring points for computation of u 
+      DO jind1 = 1, 4
+         DO jfl = 1, jpnfl
+            !  i-direction
+            IF( iilu(jfl) <= 2 ) THEN          ;   iidu(jfl,jind1) = jind1
+            ELSE
+               IF( iilu(jfl) >= jpi-1 ) THEN   ;   iidu(jfl,jind1) = jpi       + jind1 - 4
+               ELSE                            ;   iidu(jfl,jind1) = iilu(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            !  j-direction
+            IF( ijlu(jfl) <= 2 ) THEN          ;   ijdu(jfl,jind1) = jind1
+            ELSE
+               IF( ijlu(jfl) >= jpj-1 ) THEN   ;   ijdu(jfl,jind1) = jpj       + jind1 - 4
+               ELSE                            ;   ijdu(jfl,jind1) = ijlu(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            ! k-direction
+            IF( iklu(jfl) <= 2 ) THEN          ;   ikdu(jfl,jind1) = jind1
+            ELSE
+               IF( iklu(jfl) >= jpk-1 ) THEN   ;   ikdu(jfl,jind1) = jpk + jind1 - 4
+               ELSE                            ;   ikdu(jfl,jind1) = iklu(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+      
+      ! Lagrange coefficients
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            zlagxu(jfl,jind1) = 1.
+            zlagyu(jfl,jind1) = 1.
+            zlagzu(jfl,jind1) = 1.
+         END DO
+      END DO
+      DO jind1 = 1, 4
+         DO jind2 = 1, 4
+            DO jfl= 1, jpnfl
+               IF( jind1 /= jind2 ) THEN
+                  zlagxu(jfl,jind1) = zlagxu(jfl,jind1) * ( pxt(jfl)-(float(iidu(jfl,jind2))+.5) )
+                  zlagyu(jfl,jind1) = zlagyu(jfl,jind1) * ( pyt(jfl)-(float(ijdu(jfl,jind2))) )
+                  zlagzu(jfl,jind1) = zlagzu(jfl,jind1) * ( pzt(jfl)-(float(ikdu(jfl,jind2))) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      
+      ! velocity when we compute at middle time step
+      
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1, 4
+                  ztufl(jfl,jind1,jind2,jind3) =   &
+                     &   (  tcoef1(ki) * ub(iidu(jfl,jind1),ijdu(jfl,jind2),ikdu(jfl,jind3)) +   &
+                     &      tcoef2(ki) * un(iidu(jfl,jind1),ijdu(jfl,jind2),ikdu(jfl,jind3)) )   &
+                     &      / e1u(iidu(jfl,jind1),ijdu(jfl,jind2)) 
+               END DO
+            END DO
+         END DO
+         
+         zsumu = 0.
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1, 4
+                  zsumu = zsumu + ztufl(jfl,jind1,jind2,jind3) * zlagxu(jfl,jind1) * zlagyu(jfl,jind2)   &
+                     &  * zlagzu(jfl,jind3) * rcoef(jind1)*rcoef(jind2)*rcoef(jind3) 
+               END DO
+            END DO
+         END DO
+         pufl(jfl) = zsumu
+      END DO
+      
+      ! Interpolation of V velocity 
+
+      ! nearest neightboring point for computation of v 
+      DO jfl = 1, jpnfl
+         iilv(jfl) = INT(pxt(jfl)-.5)
+         ijlv(jfl) = INT(pyt(jfl)-.5)
+         iklv(jfl) = INT(pzt(jfl))
+      END DO
+      
+      ! 64 neightboring points for computation of v 
+      DO jind1 = 1, 4
+         DO jfl = 1, jpnfl
+            ! i-direction
+            IF( iilv(jfl) <= 2 ) THEN          ;   iidv(jfl,jind1) = jind1
+            ELSE
+               IF( iilv(jfl) >= jpi-1 ) THEN   ;   iidv(jfl,jind1) = jpi       + jind1 - 4
+               ELSE                            ;   iidv(jfl,jind1) = iilv(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            ! j-direction
+            IF( ijlv(jfl) <= 2 ) THEN          ;   ijdv(jfl,jind1) = jind1
+            ELSE
+               IF( ijlv(jfl) >= jpj-1 ) THEN   ;   ijdv(jfl,jind1) = jpj       + jind1 - 4
+               ELSE                            ;   ijdv(jfl,jind1) = ijlv(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            ! k-direction
+            IF( iklv(jfl) <= 2 ) THEN          ;   ikdv(jfl,jind1) = jind1
+            ELSE
+               IF( iklv(jfl) >= jpk-1 ) THEN   ;   ikdv(jfl,jind1) = jpk + jind1 - 4
+               ELSE                            ;   ikdv(jfl,jind1) = iklv(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+      
+      ! Lagrange coefficients
+      
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            zlagxv(jfl,jind1) = 1.
+            zlagyv(jfl,jind1) = 1.
+            zlagzv(jfl,jind1) = 1.
+         END DO
+      END DO
+      
+      DO jind1 = 1, 4
+         DO jind2 = 1, 4
+            DO jfl = 1, jpnfl
+               IF( jind1 /= jind2 ) THEN
+                  zlagxv(jfl,jind1)= zlagxv(jfl,jind1)*(pxt(jfl) - (float(iidv(jfl,jind2))   ) )
+                  zlagyv(jfl,jind1)= zlagyv(jfl,jind1)*(pyt(jfl) - (float(ijdv(jfl,jind2))+.5) )
+                  zlagzv(jfl,jind1)= zlagzv(jfl,jind1)*(pzt(jfl) - (float(ikdv(jfl,jind2))   ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      
+      ! velocity when we compute at middle time step
+      
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1 ,4
+                  ztvfl(jfl,jind1,jind2,jind3)=   &
+                     &   ( tcoef1(ki) * vb(iidv(jfl,jind1),ijdv(jfl,jind2),ikdv(jfl,jind3))  +   &
+                     &     tcoef2(ki) * vn(iidv(jfl,jind1),ijdv(jfl,jind2),ikdv(jfl,jind3)) )    & 
+                     &     / e2v(iidv(jfl,jind1),ijdv(jfl,jind2))
+               END DO
+            END DO
+         END DO
+         
+         zsumv=0.
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1, 4
+                  zsumv = zsumv + ztvfl(jfl,jind1,jind2,jind3) * zlagxv(jfl,jind1) * zlagyv(jfl,jind2)   &
+                     &  * zlagzv(jfl,jind3) * rcoef(jind1)*rcoef(jind2)*rcoef(jind3)
+               END DO
+            END DO
+         END DO
+         pvfl(jfl) = zsumv
+      END DO
+      
+      ! Interpolation of W velocity
+
+      ! nearest neightboring point for computation of w 
+      DO jfl = 1, jpnfl
+         iilw(jfl) = INT( pxt(jfl)   )
+         ijlw(jfl) = INT( pyt(jfl)   )
+         iklw(jfl) = INT( pzt(jfl)+.5)
+      END DO
+      
+      ! 64 neightboring points for computation of w 
+      DO jind1 = 1, 4
+         DO jfl = 1, jpnfl
+            ! i-direction
+            IF( iilw(jfl) <= 2 ) THEN          ;   iidw(jfl,jind1) = jind1
+            ELSE
+               IF( iilw(jfl) >= jpi-1 ) THEN   ;   iidw(jfl,jind1) = jpi       + jind1 - 4
+               ELSE                            ;   iidw(jfl,jind1) = iilw(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            ! j-direction
+            IF( ijlw(jfl) <= 2 ) THEN          ;   ijdw(jfl,jind1) = jind1
+            ELSE
+               IF( ijlw(jfl) >= jpj-1 ) THEN   ;   ijdw(jfl,jind1) = jpj       + jind1 - 4
+               ELSE                            ;   ijdw(jfl,jind1) = ijlw(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+            ! k-direction
+            IF( iklw(jfl) <= 2 ) THEN          ;   ikdw(jfl,jind1) = jind1
+            ELSE
+               IF( iklw(jfl) >= jpk-1 ) THEN   ;   ikdw(jfl,jind1) = jpk       + jind1 - 4
+               ELSE                            ;   ikdw(jfl,jind1) = iklw(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+      DO jind1 = 1, 4
+         DO jfl = 1, jpnfl
+            IF( iklw(jfl) <= 2 ) THEN          ;   ikdw(jfl,jind1) = jind1
+            ELSE
+               IF( iklw(jfl) >= jpk-1 ) THEN   ;   ikdw(jfl,jind1) = jpk       + jind1 - 4
+               ELSE                            ;   ikdw(jfl,jind1) = iklw(jfl) + jind1 - 2
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+      
+      ! Lagrange coefficients  for w interpolation
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            zlagxw(jfl,jind1) = 1.
+            zlagyw(jfl,jind1) = 1.
+            zlagzw(jfl,jind1) = 1.
+         END DO
+      END DO
+      DO jind1 = 1, 4
+         DO jind2 = 1, 4
+            DO jfl = 1, jpnfl
+               IF( jind1 /= jind2 ) THEN
+                  zlagxw(jfl,jind1) = zlagxw(jfl,jind1) * (pxt(jfl) - (float(iidw(jfl,jind2))   ) )
+                  zlagyw(jfl,jind1) = zlagyw(jfl,jind1) * (pyt(jfl) - (float(ijdw(jfl,jind2))   ) )
+                  zlagzw(jfl,jind1) = zlagzw(jfl,jind1) * (pzt(jfl) - (float(ikdw(jfl,jind2))-.5) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      
+      ! velocity w  when we compute at middle time step
+      DO jfl = 1, jpnfl
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1, 4
+                  ztwfl(jfl,jind1,jind2,jind3)=   &
+                     &   ( tcoef1(ki) * wb(iidw(jfl,jind1),ijdw(jfl,jind2),ikdw(jfl,jind3))+   &
+                     &     tcoef2(ki) * wn(iidw(jfl,jind1),ijdw(jfl,jind2),ikdw(jfl,jind3)) )  &
+                     &   / e3w_n(iidw(jfl,jind1),ijdw(jfl,jind2),ikdw(jfl,jind3))
+               END DO
+            END DO
+         END DO
+         
+         zsumw = 0.e0
+         DO jind1 = 1, 4
+            DO jind2 = 1, 4
+               DO jind3 = 1, 4
+                  zsumw = zsumw + ztwfl(jfl,jind1,jind2,jind3) * zlagxw(jfl,jind1) * zlagyw(jfl,jind2)   &
+                     &  * zlagzw(jfl,jind3) * rcoef(jind1)*rcoef(jind2)*rcoef(jind3)
+               END DO
+            END DO
+         END DO
+         pwfl(jfl) = zsumw
+      END DO
+      !   
+      !   
+   END SUBROUTINE flo_interp
+
+   !!======================================================================
+END MODULE flo4rk
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flo_oce.F90	(revision 14097)
@@ -0,0 +1,66 @@
+MODULE flo_oce
+   !!======================================================================
+   !!                     ***  MODULE flo_oce  ***
+   !! lagrangian floats :   define in memory all floats parameters and variables
+   !!======================================================================
+   !! History :   OPA  ! 1999-10  (CLIPPER projet)
+   !!   NEMO      1.0  ! 2002-11  (G. Madec, A. Bozec)  F90: Free form and module
+   !!----------------------------------------------------------------------
+   USE par_oce         ! ocean parameters
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC   flo_oce_alloc   ! Routine called in floats.F90
+
+   !! float parameters
+   !! ----------------
+   LOGICAL, PUBLIC ::   ln_floats   !: Activate floats or not
+   INTEGER, PUBLIC ::   jpnfl       !: total number of floats during the run
+   INTEGER, PUBLIC ::   jpnnewflo   !: number of floats added in a new run
+   INTEGER, PUBLIC ::   jpnrstflo   !: number of floats for the restart
+
+   !! float variables
+   !! ---------------
+   INTEGER , PUBLIC, ALLOCATABLE, DIMENSION(:) ::   nisobfl   !: =0 for a isobar float , =1 for a float following the w velocity
+   INTEGER , PUBLIC, ALLOCATABLE, DIMENSION(:) ::   ngrpfl    !: number to identify searcher group
+   INTEGER , PUBLIC, ALLOCATABLE, DIMENSION(:) ::   nfloat    !: number to identify searcher group
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   flxx , flyy , flzz    !: long, lat, depth of float (decimal degree, m >0)
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   tpifl, tpjfl, tpkfl   !: (i,j,k) indices of float position
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   wb   !: vertical velocity at previous time step (m s-1).
+   
+   !                                   !! * namelist namflo : langrangian floats *
+   LOGICAL, PUBLIC  ::   ln_rstflo      !: T/F float restart 
+   LOGICAL, PUBLIC  ::   ln_argo        !: T/F argo type floats
+   LOGICAL, PUBLIC  ::   ln_flork4      !: T/F 4th order Runge-Kutta
+   LOGICAL, PUBLIC  ::   ln_ariane      !: handle ariane input/output convention
+   LOGICAL, PUBLIC  ::   ln_flo_ascii   !: write in ascii (T) or in Netcdf (F)
+
+   INTEGER, PUBLIC  ::   nn_writefl     !: frequency of float output file 
+   INTEGER, PUBLIC  ::   nn_stockfl     !: frequency of float restart file
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION flo_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION flo_oce_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( wb(jpi,jpj,jpk) , nfloat(jpnfl) , nisobfl(jpnfl) , ngrpfl(jpnfl) , &
+         &      flxx(jpnfl)     , flyy(jpnfl)   , flzz(jpnfl)    ,                 & 
+         &      tpifl(jpnfl)    , tpjfl(jpnfl)  , tpkfl(jpnfl)   , STAT=flo_oce_alloc )
+      !
+      CALL mpp_sum ( 'flo_oce', flo_oce_alloc )
+      IF( flo_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'flo_oce_alloc: failed to allocate arrays' )
+   END FUNCTION flo_oce_alloc
+
+   !!======================================================================
+END MODULE flo_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floats.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floats.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floats.F90	(revision 14097)
@@ -0,0 +1,141 @@
+MODULE floats
+   !!======================================================================
+   !!                       ***  MODULE  floats  ***
+   !! Ocean floats : floats
+   !!======================================================================
+   !! History :  OPA  !          (CLIPPER)   original Code
+   !!   NEMO     1.0  ! 2002-06  (A. Bozec)  F90, Free form and module
+   !!----------------------------------------------------------------------
+   !!
+   !!----------------------------------------------------------------------
+   !!   flo_stp   : float trajectories computation
+   !!   flo_init  : initialization of float trajectories computation
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean variables
+   USE flo_oce         ! floats variables
+   USE lib_mpp         ! distributed memory computing
+   USE flodom          ! initialisation Module 
+   USE flowri          ! float output                     (flo_wri routine)
+   USE florst          ! float restart                    (flo_rst routine)
+   USE flo4rk          ! Trajectories, Runge Kutta scheme (flo_4rk routine)
+   USE floblk          ! Trajectories, Blanke scheme      (flo_blk routine)
+   !
+   USE in_out_manager  ! I/O manager
+   USE timing          ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE  
+
+   PUBLIC   flo_stp    ! routine called by step.F90
+   PUBLIC   flo_init   ! routine called by nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE flo_stp( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE flo_stp  ***
+      !!                    
+      !! ** Purpose :   Compute the geographical position (lat., long., depth)
+      !!      of each float at each time step with one of the algorithm.
+      !! 
+      !! ** Method  :   The position of a float is computed with Bruno Blanke 
+      !!        algorithm by default and with a 4th order Runge-Kutta scheme
+      !!        if ln_flork4 =T
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('flo_stp')
+      !
+      IF( ln_flork4 ) THEN   ;   CALL flo_4rk( kt )        ! Trajectories using a 4th order Runge Kutta scheme
+      ELSE                   ;   CALL flo_blk( kt )        ! Trajectories using Blanke' algorithme
+      ENDIF
+      !
+      IF( lk_mpp )   CALL mppsync   ! synchronization of all the processor
+      !
+      CALL flo_wri( kt )      ! trajectories ouput 
+      !
+      CALL flo_rst( kt )      ! trajectories restart
+      !
+      wb(:,:,:) = wn(:,:,:)         ! Save the old vertical velocity field
+      !
+      IF( ln_timing )   CALL timing_stop('flo_stp')
+      !
+   END SUBROUTINE flo_stp
+
+
+   SUBROUTINE flo_init
+      !!----------------------------------------------------------------
+      !!                 ***  ROUTINE flo_init  ***
+      !!                   
+      !! ** Purpose :   Read the namelist of floats
+      !!----------------------------------------------------------------------
+      INTEGER ::   jfl
+      INTEGER ::   ios                 ! Local integer output status for namelist read
+      !
+      NAMELIST/namflo/ ln_floats, jpnfl, jpnnewflo, ln_rstflo, nn_writefl, nn_stockfl, ln_argo, ln_flork4, ln_ariane, ln_flo_ascii
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'flo_stp : call floats routine '
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+
+      REWIND( numnam_ref )              ! Namelist namflo in reference namelist : Floats
+      READ  ( numnam_ref, namflo, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namflo in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namflo in configuration namelist : Floats
+      READ  ( numnam_cfg, namflo, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namflo in configuration namelist' )
+      IF(lwm) WRITE ( numond, namflo )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '         Namelist floats :'
+         WRITE(numout,*) '            Activate floats or not                   ln_floats    = ', ln_floats
+         WRITE(numout,*) '               number of floats                      jpnfl        = ', jpnfl
+         WRITE(numout,*) '               number of new floats                  jpnflnewflo  = ', jpnnewflo
+         WRITE(numout,*) '               restart                               ln_rstflo    = ', ln_rstflo
+         WRITE(numout,*) '               frequency of float output file        nn_writefl   = ', nn_writefl
+         WRITE(numout,*) '               frequency of float restart file       nn_stockfl   = ', nn_stockfl
+         WRITE(numout,*) '               Argo type floats                      ln_argo      = ', ln_argo
+         WRITE(numout,*) '               Computation of T trajectories         ln_flork4    = ', ln_flork4
+         WRITE(numout,*) '               Use of ariane convention              ln_ariane    = ', ln_ariane
+         WRITE(numout,*) '               ascii output (T) or netcdf output (F) ln_flo_ascii = ', ln_flo_ascii
+
+      ENDIF
+      !
+      IF( ln_floats ) THEN
+         !                             ! allocate floats arrays
+         IF( flo_oce_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'flo_init : unable to allocate arrays' )
+         !
+         !                             ! allocate flodom arrays
+         IF( flo_dom_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'flo_dom : unable to allocate arrays' )
+         !
+         !                             ! allocate flowri arrays
+         IF( flo_wri_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'flo_wri : unable to allocate arrays' )
+         !
+         !                             ! allocate florst arrays
+         IF( flo_rst_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'flo_rst : unable to allocate arrays' )
+         !
+         jpnrstflo = jpnfl-jpnnewflo   ! memory allocation 
+         !
+         DO jfl = 1, jpnfl             ! vertical axe for netcdf IOM ouput
+            nfloat(jfl) = jfl 
+         END DO
+         !
+         CALL flo_dom                  ! compute/read initial position of floats
+         !
+         wb(:,:,:) = wn(:,:,:)         ! set wb for computation of floats trajectories at the first time step
+         !
+      ENDIF
+      !
+   END SUBROUTINE flo_init
+
+   !!======================================================================
+ END MODULE floats
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floblk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floblk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/floblk.F90	(revision 14097)
@@ -0,0 +1,370 @@
+MODULE floblk
+   !!======================================================================
+   !!                     ***  MODULE  floblk  ***
+   !! Ocean floats :   trajectory computation
+   !!======================================================================
+   !!
+   !!----------------------------------------------------------------------
+   !!    flotblk     : compute float trajectories with Blanke algorithme
+   !!----------------------------------------------------------------------
+   USE flo_oce         ! ocean drifting floats
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   flo_blk    ! routine called by floats.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE flo_blk( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE flo_blk  ***
+      !!           
+      !! ** Purpose :   Compute the geographical position,latitude, longitude
+      !!      and depth of each float at each time step.
+      !! 
+      !! ** Method  :   The position of a float is computed with Bruno Blanke
+      !!      algorithm. We need to know the velocity field, the old positions
+      !!      of the floats and the grid defined on the domain.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in  ) ::   kt ! ocean time step
+      !!
+      INTEGER :: jfl              ! dummy loop arguments
+      INTEGER :: ind, ifin, iloop
+      REAL(wp)   ::       &
+         zuinfl,zvinfl,zwinfl,      &     ! transport across the input face
+         zuoutfl,zvoutfl,zwoutfl,   &     ! transport across the ouput face
+         zvol,                      &     ! volume of the mesh
+         zsurfz,                    &     ! surface of the face of the mesh 
+         zind
+
+      REAL(wp), DIMENSION ( 2 )  ::   zsurfx, zsurfy   ! surface of the face of the mesh
+
+      INTEGER  , DIMENSION ( jpnfl )  ::   iil, ijl, ikl                   ! index of nearest mesh
+      INTEGER  , DIMENSION ( jpnfl )  ::   iiloc , ijloc              
+      INTEGER  , DIMENSION ( jpnfl )  ::   iiinfl, ijinfl, ikinfl          ! index of input mesh of the float.
+      INTEGER  , DIMENSION ( jpnfl )  ::   iioutfl, ijoutfl, ikoutfl       ! index of output mesh of the float.
+      REAL(wp) , DIMENSION ( jpnfl )  ::   zgifl, zgjfl, zgkfl             ! position of floats, index on 
+      !                                                                         ! velocity mesh.
+      REAL(wp) , DIMENSION ( jpnfl )  ::    ztxfl, ztyfl, ztzfl            ! time for a float to quit the mesh
+      !                                                                         ! across one of the face x,y and z 
+      REAL(wp) , DIMENSION ( jpnfl )  ::    zttfl                          ! time for a float to quit the mesh 
+      REAL(wp) , DIMENSION ( jpnfl )  ::    zagefl                         ! time during which, trajectorie of 
+      !                                                                         ! the float has been computed
+      REAL(wp) , DIMENSION ( jpnfl )  ::   zagenewfl                       ! new age of float after calculation 
+      !                                                                         ! of new position
+      REAL(wp) , DIMENSION ( jpnfl )  ::   zufl, zvfl, zwfl                ! interpolated vel. at float position
+      REAL(wp) , DIMENSION ( jpnfl )  ::   zudfl, zvdfl, zwdfl             ! velocity diff input/output of mesh
+      REAL(wp) , DIMENSION ( jpnfl )  ::   zgidfl, zgjdfl, zgkdfl          ! direction index of float
+      !!---------------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'flo_blk : compute Blanke trajectories for floats '
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+
+      ! Initialisation of parameters
+      
+      DO jfl = 1, jpnfl
+         ! ages of floats are put at zero
+         zagefl(jfl) = 0.
+         ! index on the velocity grid 
+         ! We considere k coordinate negative, with this transformation 
+         ! the computation in the 3 direction is the same. 
+         zgifl(jfl) = tpifl(jfl) - 0.5
+         zgjfl(jfl) = tpjfl(jfl) - 0.5
+         zgkfl(jfl) = MIN(-1.,-(tpkfl(jfl)))
+         ! surface drift every 10 days 
+         IF( ln_argo ) THEN
+            IF( MOD(kt,150) >= 146 .OR. MOD(kt,150) == 0 )  zgkfl(jfl) = -1.
+         ENDIF
+         ! index of T mesh
+         iil(jfl) = 1 + INT(zgifl(jfl))
+         ijl(jfl) = 1 + INT(zgjfl(jfl))
+         ikl(jfl) =     INT(zgkfl(jfl))
+      END DO
+       
+      iloop = 0
+222   DO jfl = 1, jpnfl
+# if   defined key_mpp_mpi
+         IF( iil(jfl) >= mig(nldi) .AND. iil(jfl) <= mig(nlei) .AND.   &
+             ijl(jfl) >= mjg(nldj) .AND. ijl(jfl) <= mjg(nlej)   ) THEN
+            iiloc(jfl) = iil(jfl) - mig(1) + 1
+            ijloc(jfl) = ijl(jfl) - mjg(1) + 1
+# else 
+            iiloc(jfl) = iil(jfl)
+            ijloc(jfl) = ijl(jfl)
+# endif
+            
+            ! compute the transport across the mesh where the float is.            
+!!bug (gm) change e3t into e3. but never checked 
+            zsurfx(1) = e2u(iiloc(jfl)-1,ijloc(jfl)  ) * e3u_n(iiloc(jfl)-1,ijloc(jfl)  ,-ikl(jfl))
+            zsurfx(2) = e2u(iiloc(jfl)  ,ijloc(jfl)  ) * e3u_n(iiloc(jfl)  ,ijloc(jfl)  ,-ikl(jfl))
+            zsurfy(1) = e1v(iiloc(jfl)  ,ijloc(jfl)-1) * e3v_n(iiloc(jfl)  ,ijloc(jfl)-1,-ikl(jfl))
+            zsurfy(2) = e1v(iiloc(jfl)  ,ijloc(jfl)  ) * e3v_n(iiloc(jfl)  ,ijloc(jfl)  ,-ikl(jfl))
+
+            ! for a isobar float zsurfz is put to zero. The vertical velocity will be zero too.
+            zsurfz =          e1e2t(iiloc(jfl),ijloc(jfl))
+            zvol   = zsurfz * e3t_n(iiloc(jfl),ijloc(jfl),-ikl(jfl))
+
+            !
+            zuinfl =( ub(iiloc(jfl)-1,ijloc(jfl),-ikl(jfl)) + un(iiloc(jfl)-1,ijloc(jfl),-ikl(jfl)) )/2.*zsurfx(1)
+            zuoutfl=( ub(iiloc(jfl)  ,ijloc(jfl),-ikl(jfl)) + un(iiloc(jfl)  ,ijloc(jfl),-ikl(jfl)) )/2.*zsurfx(2)
+            zvinfl =( vb(iiloc(jfl),ijloc(jfl)-1,-ikl(jfl)) + vn(iiloc(jfl),ijloc(jfl)-1,-ikl(jfl)) )/2.*zsurfy(1)
+            zvoutfl=( vb(iiloc(jfl),ijloc(jfl)  ,-ikl(jfl)) + vn(iiloc(jfl),ijloc(jfl)  ,-ikl(jfl)) )/2.*zsurfy(2)
+            zwinfl =-(wb(iiloc(jfl),ijloc(jfl),-(ikl(jfl)-1))    &
+               &   +  wn(iiloc(jfl),ijloc(jfl),-(ikl(jfl)-1)) )/2. *  zsurfz*nisobfl(jfl)
+            zwoutfl=-(wb(iiloc(jfl),ijloc(jfl),- ikl(jfl)   )   &
+               &   +  wn(iiloc(jfl),ijloc(jfl),- ikl(jfl)   ) )/2. *  zsurfz*nisobfl(jfl)
+            
+            ! interpolation of velocity field on the float initial position            
+            zufl(jfl)=  zuinfl  + ( zgifl(jfl) - float(iil(jfl)-1) ) * ( zuoutfl - zuinfl)
+            zvfl(jfl)=  zvinfl  + ( zgjfl(jfl) - float(ijl(jfl)-1) ) * ( zvoutfl - zvinfl)
+            zwfl(jfl)=  zwinfl  + ( zgkfl(jfl) - float(ikl(jfl)-1) ) * ( zwoutfl - zwinfl)
+            
+            ! faces of input and output
+            ! u-direction
+            IF( zufl(jfl) < 0. ) THEN
+               iioutfl(jfl) = iil(jfl) - 1.
+               iiinfl (jfl) = iil(jfl)
+               zind   = zuinfl
+               zuinfl = zuoutfl
+               zuoutfl= zind
+            ELSE
+               iioutfl(jfl) = iil(jfl)
+               iiinfl (jfl) = iil(jfl) - 1
+            ENDIF
+            ! v-direction       
+            IF( zvfl(jfl) < 0. ) THEN
+               ijoutfl(jfl) = ijl(jfl) - 1.
+               ijinfl (jfl) = ijl(jfl)
+               zind    = zvinfl
+               zvinfl  = zvoutfl
+               zvoutfl = zind
+            ELSE
+               ijoutfl(jfl) = ijl(jfl)
+               ijinfl (jfl) = ijl(jfl) - 1.
+            ENDIF
+            ! w-direction
+            IF( zwfl(jfl) < 0. ) THEN
+               ikoutfl(jfl) = ikl(jfl) - 1.
+               ikinfl (jfl) = ikl(jfl)
+               zind    = zwinfl
+               zwinfl  = zwoutfl
+               zwoutfl = zind
+            ELSE
+               ikoutfl(jfl) = ikl(jfl)
+               ikinfl (jfl) = ikl(jfl) - 1.
+            ENDIF
+            
+            ! compute the time to go out the mesh across a face
+            ! u-direction
+            zudfl (jfl) = zuoutfl - zuinfl
+            zgidfl(jfl) = float(iioutfl(jfl) - iiinfl(jfl))
+            IF( zufl(jfl)*zuoutfl <= 0. ) THEN
+               ztxfl(jfl) = 1.E99
+            ELSE
+               IF( ABS(zudfl(jfl)) >= 1.E-5 ) THEN
+                  ztxfl(jfl)= zgidfl(jfl)/zudfl(jfl) * LOG(zuoutfl/zufl (jfl))
+               ELSE
+                  ztxfl(jfl)=(float(iioutfl(jfl))-zgifl(jfl))/zufl(jfl)
+               ENDIF
+               IF( (ABS(zgifl(jfl)-float(iiinfl (jfl))) <=  1.E-7) .OR.   &
+                   (ABS(zgifl(jfl)-float(iioutfl(jfl))) <=  1.E-7) ) THEN
+                  ztxfl(jfl)=(zgidfl(jfl))/zufl(jfl)
+               ENDIF
+            ENDIF
+            ! v-direction
+            zvdfl (jfl) = zvoutfl - zvinfl
+            zgjdfl(jfl) = float(ijoutfl(jfl)-ijinfl(jfl))
+            IF( zvfl(jfl)*zvoutfl <= 0. ) THEN
+               ztyfl(jfl) = 1.E99
+            ELSE
+               IF( ABS(zvdfl(jfl)) >= 1.E-5 ) THEN
+                  ztyfl(jfl) = zgjdfl(jfl)/zvdfl(jfl) * LOG(zvoutfl/zvfl (jfl))
+               ELSE
+                  ztyfl(jfl) = (float(ijoutfl(jfl)) - zgjfl(jfl))/zvfl(jfl)
+               ENDIF
+               IF( (ABS(zgjfl(jfl)-float(ijinfl (jfl))) <= 1.E-7) .OR.   &
+                   (ABS(zgjfl(jfl)-float(ijoutfl(jfl))) <=  1.E-7) ) THEN
+                  ztyfl(jfl) = (zgjdfl(jfl)) / zvfl(jfl)
+               ENDIF
+            ENDIF
+            ! w-direction        
+            IF( nisobfl(jfl) == 1. ) THEN 
+               zwdfl (jfl) = zwoutfl - zwinfl
+               zgkdfl(jfl) = float(ikoutfl(jfl) - ikinfl(jfl))
+               IF( zwfl(jfl)*zwoutfl <= 0. ) THEN
+                  ztzfl(jfl) = 1.E99
+               ELSE
+                  IF( ABS(zwdfl(jfl)) >= 1.E-5 ) THEN
+                     ztzfl(jfl) = zgkdfl(jfl)/zwdfl(jfl) * LOG(zwoutfl/zwfl (jfl))
+                  ELSE
+                     ztzfl(jfl) = (float(ikoutfl(jfl)) - zgkfl(jfl))/zwfl(jfl)
+                  ENDIF
+                  IF( (ABS(zgkfl(jfl)-float(ikinfl (jfl))) <=  1.E-7) .OR.   &
+                      (ABS(zgkfl(jfl)-float(ikoutfl(jfl))) <= 1.E-7) ) THEN
+                     ztzfl(jfl) = (zgkdfl(jfl)) / zwfl(jfl)
+                  ENDIF
+               ENDIF
+            ENDIF
+            
+            ! the time to go leave the mesh is the smallest time
+                   
+            IF( nisobfl(jfl) == 1. ) THEN 
+               zttfl(jfl) = MIN(ztxfl(jfl),ztyfl(jfl),ztzfl(jfl))
+            ELSE
+               zttfl(jfl) = MIN(ztxfl(jfl),ztyfl(jfl))
+            ENDIF
+            ! new age of the FLOAT
+            zagenewfl(jfl) = zagefl(jfl) + zttfl(jfl)*zvol
+            ! test to know if the "age" of the float is not bigger than the 
+            ! time step
+            IF( zagenewfl(jfl) > rdt ) THEN
+               zttfl(jfl) = (rdt-zagefl(jfl)) / zvol
+               zagenewfl(jfl) = rdt
+            ENDIF
+            
+            ! In the "minimal" direction we compute the index of new mesh
+            ! on i-direction
+            IF( ztxfl(jfl) <=  zttfl(jfl) ) THEN
+               zgifl(jfl) = float(iioutfl(jfl))
+               ind = iioutfl(jfl)
+               IF( iioutfl(jfl) >= iiinfl(jfl) ) THEN
+                  iioutfl(jfl) = iioutfl(jfl) + 1
+               ELSE
+                  iioutfl(jfl) = iioutfl(jfl) - 1
+               ENDIF
+               iiinfl(jfl) = ind
+            ELSE
+               IF( ABS(zudfl(jfl)) >= 1.E-5 ) THEN 
+                  zgifl(jfl) = zgifl(jfl) + zgidfl(jfl)*zufl(jfl)    &
+                     &       * ( EXP( zudfl(jfl)/zgidfl(jfl)*zttfl(jfl) ) - 1. ) /  zudfl(jfl)
+               ELSE
+                  zgifl(jfl) = zgifl(jfl) + zufl(jfl) * zttfl(jfl)
+               ENDIF
+            ENDIF
+            ! on j-direction
+            IF( ztyfl(jfl) <= zttfl(jfl) ) THEN
+               zgjfl(jfl) = float(ijoutfl(jfl))
+               ind = ijoutfl(jfl)
+               IF( ijoutfl(jfl) >= ijinfl(jfl) ) THEN
+                  ijoutfl(jfl) = ijoutfl(jfl) + 1
+               ELSE
+                  ijoutfl(jfl) = ijoutfl(jfl) - 1
+               ENDIF
+               ijinfl(jfl) = ind
+            ELSE
+               IF( ABS(zvdfl(jfl)) >= 1.E-5 ) THEN 
+                  zgjfl(jfl) = zgjfl(jfl)+zgjdfl(jfl)*zvfl(jfl)   &
+                     &       * ( EXP(zvdfl(jfl)/zgjdfl(jfl)*zttfl(jfl)) - 1. ) /  zvdfl(jfl)
+               ELSE
+                  zgjfl(jfl) = zgjfl(jfl)+zvfl(jfl)*zttfl(jfl)
+               ENDIF
+            ENDIF
+            ! on k-direction
+            IF( nisobfl(jfl) == 1. ) THEN
+               IF( ztzfl(jfl) <= zttfl(jfl) ) THEN
+                  zgkfl(jfl) = float(ikoutfl(jfl))
+                  ind = ikoutfl(jfl)
+                  IF( ikoutfl(jfl) >= ikinfl(jfl) ) THEN
+                     ikoutfl(jfl) = ikoutfl(jfl)+1
+                  ELSE
+                     ikoutfl(jfl) = ikoutfl(jfl)-1
+                  ENDIF
+                  ikinfl(jfl) = ind
+               ELSE
+                  IF( ABS(zwdfl(jfl)) >= 1.E-5 ) THEN 
+                     zgkfl(jfl) = zgkfl(jfl)+zgkdfl(jfl)*zwfl(jfl)    &
+                        &       * ( EXP(zwdfl(jfl)/zgkdfl(jfl)*zttfl(jfl)) - 1. ) /  zwdfl(jfl)
+                  ELSE
+                     zgkfl(jfl) = zgkfl(jfl)+zwfl(jfl)*zttfl(jfl)
+                  ENDIF
+               ENDIF
+            ENDIF
+            
+            ! coordinate of the new point on the temperature grid
+            
+            iil(jfl) = MAX(iiinfl(jfl),iioutfl(jfl))
+            ijl(jfl) = MAX(ijinfl(jfl),ijoutfl(jfl))
+            IF( nisobfl(jfl) ==  1 ) ikl(jfl) = MAX(ikinfl(jfl),ikoutfl(jfl))
+!!Alexcadm	 write(*,*)'PE ',narea,
+!!Alexcadm     .    iiinfl(jfl),iioutfl(jfl),ijinfl(jfl)
+!!Alexcadm     .		,ijoutfl(jfl),ikinfl(jfl),
+!!Alexcadm     .	  ikoutfl(jfl),ztxfl(jfl),ztyfl(jfl)
+!!Alexcadm     .		,ztzfl(jfl),zgifl(jfl),
+!!Alexcadm     .  zgjfl(jfl) 
+!!Alexcadm	IF (jfl == 910) write(*,*)'Flotteur 910',
+!!Alexcadm     .    iiinfl(jfl),iioutfl(jfl),ijinfl(jfl)
+!!Alexcadm     .		,ijoutfl(jfl),ikinfl(jfl),
+!!Alexcadm     .	  ikoutfl(jfl),ztxfl(jfl),ztyfl(jfl)
+!!Alexcadm     .		,ztzfl(jfl),zgifl(jfl),
+!!Alexcadm     .  zgjfl(jfl) 
+            ! reinitialisation of the age of FLOAT
+            zagefl(jfl) = zagenewfl(jfl)
+# if   defined key_mpp_mpi
+         ELSE
+            ! we put zgifl, zgjfl, zgkfl, zagefl
+            zgifl (jfl) = 0.
+            zgjfl (jfl) = 0.
+            zgkfl (jfl) = 0.
+            zagefl(jfl) = 0.
+            iil(jfl) = 0
+            ijl(jfl) = 0
+         ENDIF
+# endif
+      END DO
+      
+      ! synchronisation
+      CALL mpp_sum( 'floblk', zgifl , jpnfl )   ! sums over the global domain
+      CALL mpp_sum( 'floblk', zgjfl , jpnfl )
+      CALL mpp_sum( 'floblk', zgkfl , jpnfl )
+      CALL mpp_sum( 'floblk', zagefl, jpnfl )
+      CALL mpp_sum( 'floblk', iil   , jpnfl )
+      CALL mpp_sum( 'floblk', ijl   , jpnfl )
+      
+      ! Test to know if a  float hasn't integrated enought time
+      IF( ln_argo ) THEN
+         ifin = 1
+         DO jfl = 1, jpnfl
+            IF( zagefl(jfl) < rdt )   ifin = 0
+            tpifl(jfl) = zgifl(jfl) + 0.5
+            tpjfl(jfl) = zgjfl(jfl) + 0.5
+         END DO
+      ELSE
+         ifin = 1
+         DO jfl = 1, jpnfl
+            IF( zagefl(jfl) < rdt )   ifin = 0
+            tpifl(jfl) = zgifl(jfl) + 0.5
+            tpjfl(jfl) = zgjfl(jfl) + 0.5
+            IF( nisobfl(jfl) == 1 ) tpkfl(jfl) = -(zgkfl(jfl))
+         END DO
+      ENDIF
+!!Alexcadm	IF (lwp) write(numout,*) '---------'
+!!Alexcadm	IF (lwp) write(numout,*) 'before Erika:',tpifl(880),tpjfl(880),
+!!Alexcadm     .       tpkfl(880),zufl(880),zvfl(880),zwfl(880)
+!!Alexcadm	IF (lwp) write(numout,*) 'first Erika:',tpifl(900),tpjfl(900),
+!!Alexcadm     .       tpkfl(900),zufl(900),zvfl(900),zwfl(900)
+!!Alexcadm	IF (lwp) write(numout,*) 'last Erika:',tpifl(jpnfl),tpjfl(jpnfl),
+!!Alexcadm     .       tpkfl(jpnfl),zufl(jpnfl),zvfl(jpnfl),zwfl(jpnfl)
+      IF( ifin == 0 ) THEN
+         iloop = iloop + 1 
+         GO TO 222
+      ENDIF
+      !
+      !
+   END SUBROUTINE flo_blk
+
+   !!======================================================================
+END MODULE floblk 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flodom.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flodom.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flodom.F90	(revision 14097)
@@ -0,0 +1,454 @@
+MODULE flodom
+   !!======================================================================
+   !!                       ***  MODULE  flodom  ***
+   !! Ocean floats :   domain
+   !!======================================================================
+   !! History :  OPA  ! 1998-07 (Y.Drillet, CLIPPER)  Original code
+   !!  NEMO      3.3  ! 2011-09 (C.Bricaud,S.Law-Chune Mercator-Ocean): add ARIANE convention + comsecitc changes
+   !!----------------------------------------------------------------------
+   !!   flo_dom               : initialization of floats
+   !!   add_new_floats        : add new floats (long/lat/depth)
+   !!   add_new_ariane_floats : add new floats with araine convention (i/j/k)
+   !!   findmesh              : compute index of position 
+   !!   dstnce                : compute distance between face mesh and floats 
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE flo_oce         ! ocean drifting floats
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   flo_dom         ! routine called by floats.F90
+   PUBLIC   flo_dom_alloc   ! Routine called in floats.F90
+
+   CHARACTER (len=21) ::  clname1 = 'init_float'              ! floats initialisation filename
+   CHARACTER (len=21) ::  clname2 = 'init_float_ariane'       ! ariane floats initialisation filename
+
+
+   INTEGER , ALLOCATABLE, DIMENSION(:) ::   iimfl, ijmfl, ikmfl       ! index mesh of floats
+   INTEGER , ALLOCATABLE, DIMENSION(:) ::   idomfl, ivtest, ihtest    !   -     
+   REAL(wp), ALLOCATABLE, DIMENSION(:) ::   zgifl, zgjfl,  zgkfl      ! distances in indexes
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE flo_dom
+      !! ---------------------------------------------------------------------
+      !!                  ***  ROUTINE flo_dom  ***
+      !!                 
+      !!  ** Purpose :   Initialisation of floats
+      !!
+      !!  ** Method  :   We put the floats  in the domain with the latitude,
+      !!               the longitude (degree) and the depth (m).
+      !!----------------------------------------------------------------------      
+      INTEGER            ::   jfl    ! dummy loop  
+      INTEGER            ::   inum   ! logical unit for file read
+      !!---------------------------------------------------------------------
+      
+      ! Initialisation with the geographical position or restart
+      
+      IF(lwp) WRITE(numout,*) 'flo_dom : compute initial position of floats'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '           jpnfl = ',jpnfl
+      
+      !-------------------------!
+      ! FLOAT RESTART FILE READ !
+      !-------------------------!
+      IF( ln_rstflo )THEN
+
+         IF(lwp) WRITE(numout,*) '        float restart file read'
+         
+         ! open the restart file 
+         !----------------------
+         CALL ctl_opn( inum, 'restart_float', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+
+         ! read of the restart file
+         READ(inum,*)   ( tpifl  (jfl), jfl=1, jpnrstflo),   & 
+                        ( tpjfl  (jfl), jfl=1, jpnrstflo),   &
+                        ( tpkfl  (jfl), jfl=1, jpnrstflo),   &
+                        ( nisobfl(jfl), jfl=1, jpnrstflo),   &
+                        ( ngrpfl (jfl), jfl=1, jpnrstflo)    
+         CLOSE(inum)
+
+         ! if we want a  surface drift  ( like PROVOR floats )
+         IF( ln_argo ) nisobfl(1:jpnrstflo) = 0
+         
+         ! It is possible to add new floats.          
+         !---------------------------------
+         IF( jpnfl > jpnrstflo )THEN
+
+            IF(lwp) WRITE(numout,*) '        add new floats'
+
+            IF( ln_ariane )THEN  !Add new floats with ariane convention
+                CALL flo_add_new_ariane_floats(jpnrstflo+1,jpnfl) 
+            ELSE                 !Add new floats with long/lat convention
+                CALL flo_add_new_floats(jpnrstflo+1,jpnfl)
+            ENDIF
+         ENDIF
+
+      !--------------------------------------!
+      ! FLOAT INITILISATION: NO RESTART FILE !
+      !--------------------------------------!
+      ELSE    !ln_rstflo
+
+         IF( ln_ariane )THEN       !Add new floats with ariane convention
+            CALL flo_add_new_ariane_floats(1,jpnfl)
+         ELSE                      !Add new floats with long/lat convention
+            CALL flo_add_new_floats(1,jpnfl)
+         ENDIF
+
+      ENDIF
+            
+   END SUBROUTINE flo_dom
+
+   SUBROUTINE flo_add_new_floats(kfl_start, kfl_end)
+      !! -------------------------------------------------------------
+      !!                 ***  SUBROUTINE add_new_arianefloats  ***
+      !!          
+      !! ** Purpose :   
+      !!
+      !!       First initialisation of floats
+      !!       the initials positions of floats are written in a file
+      !!       with a variable to know if it is a isobar float a number 
+      !!       to identified who want the trajectories of this float and 
+      !!       an index for the number of the float         
+      !!       open the init file 
+      !!               
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kfl_start, kfl_end
+      !!
+      INTEGER           :: inum ! file unit
+      INTEGER           :: jfl,ji, jj, jk ! dummy loop indices
+      INTEGER           :: itrash         ! trash var for reading
+      INTEGER           :: ifl            ! number of floats to read
+      REAL(wp)          :: zdxab, zdyad
+      LOGICAL           :: llinmesh
+      CHARACTER(len=80) :: cltmp
+      !!---------------------------------------------------------------------
+      ifl = kfl_end-kfl_start+1
+
+      ! we get the init values 
+      !-----------------------
+      CALL ctl_opn( inum , clname1, 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+      DO jfl = kfl_start,kfl_end
+         READ(inum,*) flxx(jfl),flyy(jfl),flzz(jfl), nisobfl(jfl),ngrpfl(jfl),itrash
+         if(lwp)write(numout,*)'read:',jfl,flxx(jfl),flyy(jfl),flzz(jfl), nisobfl(jfl),ngrpfl(jfl),itrash ; call flush(numout)
+      END DO
+      CLOSE(inum)
+            
+      ! Test to find the grid point coordonate with the geographical position            
+      !----------------------------------------------------------------------
+      DO jfl = kfl_start,kfl_end
+         ihtest(jfl) = 0
+         ivtest(jfl) = 0
+         ikmfl(jfl) = 0
+# if   defined key_mpp_mpi
+         DO ji = MAX(nldi,2), nlei
+            DO jj = MAX(nldj,2), nlej   ! NO vector opt.
+# else         
+         DO ji = 2, jpi
+            DO jj = 2, jpj   ! NO vector opt.
+# endif                     
+               ! For each float we find the indexes of the mesh                      
+               CALL flo_findmesh(glamf(ji-1,jj-1),gphif(ji-1,jj-1),   &
+                                 glamf(ji-1,jj  ),gphif(ji-1,jj  ),   &
+                                 glamf(ji  ,jj  ),gphif(ji  ,jj  ),   &
+                                 glamf(ji  ,jj-1),gphif(ji  ,jj-1),   &
+                                 flxx(jfl)       ,flyy(jfl)       ,   &
+                                 glamt(ji  ,jj  ),gphit(ji  ,jj  ), llinmesh)
+               IF( llinmesh )THEN
+                  iimfl(jfl) = ji
+                  ijmfl(jfl) = jj
+                  ihtest(jfl) = ihtest(jfl)+1
+                  DO jk = 1, jpk-1
+                     IF( (gdepw_n(ji,jj,jk) <= flzz(jfl)) .AND. (gdepw_n(ji,jj,jk+1) > flzz(jfl)) ) THEN
+                        ikmfl(jfl) = jk
+                        ivtest(jfl) = ivtest(jfl) + 1
+                     ENDIF
+                  END DO
+               ENDIF
+            END DO
+         END DO
+
+         ! If the float is in a mesh computed by an other processor we put iimfl=ijmfl=-1               
+         IF( ihtest(jfl) ==  0 ) THEN
+            iimfl(jfl) = -1
+            ijmfl(jfl) = -1
+         ENDIF
+      END DO
+
+      !Test if each float is in one and only one proc
+      !----------------------------------------------
+      IF( lk_mpp )   THEN 
+         CALL mpp_sum('flodom', ihtest,jpnfl)
+         CALL mpp_sum('flodom', ivtest,jpnfl)
+      ENDIF
+      DO jfl = kfl_start,kfl_end
+
+         IF( (ihtest(jfl) > 1 ) .OR. ( ivtest(jfl) > 1) ) THEN
+             WRITE(cltmp,'(A10,i4.4,A20)' )'THE FLOAT',jfl,' IS NOT IN ONLY ONE MESH'
+             CALL ctl_stop('STOP',TRIM(cltmp) )
+         ENDIF
+         IF( (ihtest(jfl) == 0) ) THEN
+             WRITE(cltmp,'(A10,i4.4,A20)' )'THE FLOAT',jfl,' IS IN NO MESH'
+             CALL ctl_stop('STOP',TRIM(cltmp) )
+         ENDIF
+      END DO
+
+      ! We compute the distance between the float and the face of the mesh            
+      !-------------------------------------------------------------------
+      DO jfl = kfl_start,kfl_end
+
+         ! Made only if the float is in the domain of the processor              
+         IF( (iimfl(jfl) >= 0) .AND. (ijmfl(jfl) >= 0) ) THEN
+
+            ! TEST TO KNOW IF THE FLOAT IS NOT INITIALISED IN THE COAST
+            idomfl(jfl) = 0
+            IF( tmask(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)) == 0. ) idomfl(jfl) = 1
+
+            ! Computation of the distance between the float and the faces of the mesh
+            !            zdxab
+            !             .
+            !        B----.---------C
+            !        |    .         |
+            !        |<------>flo   |
+            !        |        ^     |
+            !        |        |.....|....zdyad
+            !        |        |     |
+            !        A--------|-----D
+            !
+            zdxab = flo_dstnce( flxx(jfl), flyy(jfl), glamf(iimfl(jfl)-1,ijmfl(jfl)-1), flyy(jfl) )
+            zdyad = flo_dstnce( flxx(jfl), flyy(jfl), flxx(jfl), gphif(iimfl(jfl)-1,ijmfl(jfl)-1) )
+
+            ! Translation of this distances (in meter) in indexes
+            zgifl(jfl)= (iimfl(jfl)-0.5) + zdxab/e1u(iimfl(jfl)-1,ijmfl(jfl)) + (mig(1)-1)
+            zgjfl(jfl)= (ijmfl(jfl)-0.5) + zdyad/e2v(iimfl(jfl),ijmfl(jfl)-1) + (mjg(1)-1)
+            zgkfl(jfl) = (( gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)+1) - flzz(jfl) )* ikmfl(jfl))   &
+               &                 / (  gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)+1)                              &
+               &                    - gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl) ) )                             &
+               &                 + (( flzz(jfl)-gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)) ) *(ikmfl(jfl)+1))   &
+               &                 / (  gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)+1)                              &
+               &                    - gdepw_n(iimfl(jfl),ijmfl(jfl),ikmfl(jfl)) )
+         ELSE
+            zgifl(jfl) = 0.e0
+            zgjfl(jfl) = 0.e0
+            zgkfl(jfl) = 0.e0
+         ENDIF
+
+      END DO
+                  
+      ! The sum of all the arrays zgifl, zgjfl, zgkfl give 3 arrays with the positions of all the floats.
+      IF( lk_mpp )   THEN 
+         CALL mpp_sum( 'flodom', zgjfl, ifl )   ! sums over the global domain
+         CALL mpp_sum( 'flodom', zgkfl, ifl )
+      ENDIF
+            
+      DO jfl = kfl_start,kfl_end
+         tpifl(jfl) = zgifl(jfl)
+         tpjfl(jfl) = zgjfl(jfl)
+         tpkfl(jfl) = zgkfl(jfl)
+      END DO
+
+      ! WARNING : initial position not in the sea         
+      IF( .NOT. ln_rstflo ) THEN 
+         DO jfl =  kfl_start,kfl_end
+            IF( idomfl(jfl) == 1 ) THEN
+               IF(lwp) WRITE(numout,*)'*****************************'
+               IF(lwp) WRITE(numout,*)'!!!!!!!  WARNING   !!!!!!!!!!'
+               IF(lwp) WRITE(numout,*)'*****************************'
+               IF(lwp) WRITE(numout,*)'The float number',jfl,'is out of the sea.'
+               IF(lwp) WRITE(numout,*)'geographical position',flxx(jfl),flyy(jfl),flzz(jfl)
+               IF(lwp) WRITE(numout,*)'index position',tpifl(jfl),tpjfl(jfl),tpkfl(jfl)
+            ENDIF
+         END DO
+      ENDIF
+
+   END SUBROUTINE flo_add_new_floats
+
+   SUBROUTINE flo_add_new_ariane_floats(kfl_start, kfl_end)
+      !! -------------------------------------------------------------
+      !!                 ***  SUBROUTINE add_new_arianefloats  ***
+      !!          
+      !! ** Purpose :   
+      !!       First initialisation of floats with ariane convention
+      !!       
+      !!       The indexes are read directly from file (warning ariane
+      !!       convention, are refered to 
+      !!       U,V,W grids - and not T-) 
+      !!       The isobar advection is managed with the sign of tpkfl ( >0 -> 3D
+      !!       advection, <0 -> 2D) 
+      !!       Some variables are not read, as - gl         : time index; 4th
+      !!       column        
+      !!                                       - transport  : transport ; 5th
+      !!                                       column
+      !!       and paste in the jtrash var
+      !!       At the end, ones need to replace the indexes on T grid
+      !!       RMQ : there is no float groups identification !
+      !!
+      !!               
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kfl_start, kfl_end
+      !!
+      INTEGER  :: inum         ! file unit
+      INTEGER  :: ierr, ifl
+      INTEGER  :: jfl, jfl1    ! dummy loop indices
+      INTEGER  :: itrash       ! trash var for reading  
+      CHARACTER(len=80) :: cltmp
+
+      !!----------------------------------------------------------------------
+      nisobfl(kfl_start:kfl_end) = 1 ! we assume that by default we want 3D advection
+
+      ifl = kfl_end - kfl_start + 1  ! number of floats to read  
+
+      ! we check that the number of floats in the init_file are consistant with the namelist
+      IF( lwp ) THEN
+
+         jfl1=0
+         ierr=0
+         CALL ctl_opn( inum, clname2, 'OLD', 'FORMATTED', 'SEQUENTIAL',  1, numout, .TRUE., 1 )
+         DO WHILE (ierr .EQ. 0)
+            jfl1=jfl1+1
+            READ(inum,*, iostat=ierr)
+         END DO
+         CLOSE(inum)
+         IF( (jfl1-1) .NE. ifl )THEN 
+            WRITE(cltmp,'(A25,A20,A3,i4.4,A10,i4.4)')"the number of floats in ",TRIM(clname2), &
+                                                     " = ",jfl1," is not equal to jfl= ",ifl
+            CALL ctl_stop('STOP',TRIM(cltmp) )
+         ENDIF
+
+      ENDIF
+            
+      ! we get the init values 
+      CALL ctl_opn( inum, clname2, 'OLD', 'FORMATTED', 'SEQUENTIAL', 1, numout, .TRUE., 1 )
+      DO jfl = kfl_start, kfl_end
+          READ(inum,*) tpifl(jfl),tpjfl(jfl),tpkfl(jfl),itrash, itrash
+              
+          IF ( tpkfl(jfl) .LT. 0. ) nisobfl(jfl) = 0 !set the 2D advection according to init_float
+          ngrpfl(jfl)=jfl
+      END DO
+
+      ! conversion from ariane index to T grid index
+      tpkfl(kfl_start:kfl_end) = abs(tpkfl)-0.5 ! reversed vertical axis
+      tpifl(kfl_start:kfl_end) = tpifl+0.5
+      tpjfl(kfl_start:kfl_end) = tpjfl+0.5
+
+
+   END SUBROUTINE flo_add_new_ariane_floats
+
+
+   SUBROUTINE flo_findmesh( pax, pay, pbx, pby,   &
+                            pcx, pcy, pdx, pdy,   &
+                            px  ,py  ,ptx, pty, ldinmesh )
+      !! -------------------------------------------------------------
+      !!                ***  ROUTINE findmesh  ***
+      !!      
+      !! ** Purpose :   Find the index of mesh for the point spx spy
+      !!
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   &
+         pax, pay, pbx, pby,    &     ! ???
+         pcx, pcy, pdx, pdy,    &     ! ???
+         px, py,                &     ! longitude and latitude
+         ptx, pty                     ! ???
+      LOGICAL ::  ldinmesh            ! ???
+      !!
+      REAL(wp) ::   zabt, zbct, zcdt, zdat, zabpt, zbcpt, zcdpt, zdapt
+      !!---------------------------------------------------------------------
+      !! Statement function
+      REAL(wp) ::   fsline
+      REAL(wp) ::   psax, psay, psbx, psby, psx, psy
+      fsline( psax, psay, psbx, psby, psx, psy ) = psy  * ( psbx - psax )   &
+         &                                       - psx  * ( psby - psay )   &
+         &                                       + psax *   psby - psay * psbx
+      !!---------------------------------------------------------------------
+      
+      ! 4 semi plane defined by the 4 points and including the T point
+      zabt = fsline(pax,pay,pbx,pby,ptx,pty)
+      zbct = fsline(pbx,pby,pcx,pcy,ptx,pty)
+      zcdt = fsline(pcx,pcy,pdx,pdy,ptx,pty)
+      zdat = fsline(pdx,pdy,pax,pay,ptx,pty)
+      
+      ! 4 semi plane defined by the 4 points and including the extrememity
+      zabpt = fsline(pax,pay,pbx,pby,px,py)
+      zbcpt = fsline(pbx,pby,pcx,pcy,px,py)
+      zcdpt = fsline(pcx,pcy,pdx,pdy,px,py)
+      zdapt = fsline(pdx,pdy,pax,pay,px,py)
+       
+      ! We compare the semi plane T with the semi plane including the point
+      ! to know if it is in this  mesh.
+      ! For numerical reasons it is possible that for a point which is on
+      ! the line we don't have exactly zero with fsline function. We want 
+      ! that a point can't be in 2 mesh in the same time, so we put the 
+      ! coefficient to zero if it is smaller than 1.E-12
+      
+      IF( ABS(zabpt) <= 1.E-12 ) zabpt = 0.
+      IF( ABS(zbcpt) <= 1.E-12 ) zbcpt = 0.
+      IF( ABS(zcdpt) <= 1.E-12 ) zcdpt = 0.
+      IF( ABS(zdapt) <= 1.E-12 ) zdapt = 0.
+      IF( (zabt*zabpt >  0.) .AND. (zbct*zbcpt >= 0. ) .AND. ( zcdt*zcdpt >= 0. ) .AND. ( zdat*zdapt > 0. )   &
+         .AND. ( px <= MAX(pcx,pdx) ) .AND. ( px >= MIN(pax,pbx) )    &
+         .AND. ( py <= MAX(pby,pcy) ) .AND. ( py >= MIN(pay,pdy) ) ) THEN
+         ldinmesh=.TRUE.
+      ELSE
+         ldinmesh=.FALSE.
+      ENDIF
+      !
+   END SUBROUTINE flo_findmesh
+
+
+   FUNCTION flo_dstnce( pla1, phi1, pla2, phi2 )
+      !! -------------------------------------------------------------
+      !!                 ***  Function dstnce  ***
+      !!          
+      !! ** Purpose :   returns distance (in m) between two geographical
+      !!                points
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::   pla1, phi1, pla2, phi2   ! ???
+      !!
+      REAL(wp) :: dly1, dly2, dlx1, dlx2, dlx, dls, dld, dpi
+      REAL(wp) :: flo_dstnce
+      !!---------------------------------------------------------------------
+      !
+      dpi  = 2._wp * ASIN(1._wp)
+      dls  = dpi / 180._wp
+      dly1 = phi1 * dls
+      dly2 = phi2 * dls
+      dlx1 = pla1 * dls
+      dlx2 = pla2 * dls
+      !
+      dlx = SIN(dly1) * SIN(dly2) + COS(dly1) * COS(dly2) * COS(dlx2-dlx1)
+      !
+      IF( ABS(dlx) > 1.0_wp ) dlx = 1.0_wp
+      !
+      dld = ATAN(SQRT( 1._wp * ( 1._wp-dlx )/( 1._wp+dlx ) )) * 222.24_wp / dls
+      flo_dstnce = dld * 1000._wp
+      !
+   END FUNCTION flo_dstnce
+
+   INTEGER FUNCTION flo_dom_alloc()
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION flo_dom_alloc  ***
+      !!----------------------------------------------------------------------
+
+      ALLOCATE( iimfl(jpnfl) , ijmfl(jpnfl) , ikmfl(jpnfl) ,                          &  
+                idomfl(jpnfl), ivtest(jpnfl), ihtest(jpnfl),                 &
+                zgifl(jpnfl) , zgjfl(jpnfl) , zgkfl(jpnfl)   , STAT=flo_dom_alloc )
+      !
+      CALL mpp_sum ( 'flodom', flo_dom_alloc )
+      IF( flo_dom_alloc /= 0 )   CALL ctl_stop( 'STOP', 'flo_dom_alloc: failed to allocate arrays' )
+   END FUNCTION flo_dom_alloc
+
+   !!======================================================================
+END MODULE flodom
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/florst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/florst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/florst.F90	(revision 14097)
@@ -0,0 +1,124 @@
+MODULE florst
+   !!======================================================================
+   !!                       ***  MODULE  florst  ***
+   !! Ocean floats : write floats restart files
+   !!======================================================================
+   !!  History :  OPA  !  1999-09  (Y. Drillet)    : Original code
+   !!              -   !  2000-06  (J.-M. Molines) : Profiling floats for CLS 
+   !!   NEMO      1.0  !  2002-10  (A. Bozec)  F90 : Free form and module
+   !!             3.2  !  2010-08  (slaw, cbricaud): netcdf outputs and others 
+   !!----------------------------------------------------------------------
+   USE flo_oce         ! ocean drifting floats
+   USE dom_oce         ! ocean space and time domain
+   USE lib_mpp         ! distribued memory computing library
+   USE in_out_manager  ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC flo_rst         ! routine called by floats.F90
+   PUBLIC flo_rst_alloc   ! routine called by floats.F90
+
+   INTEGER, ALLOCATABLE, DIMENSION(:) :: iperproc   ! 1D workspace
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION flo_rst_alloc()
+      !!-------------------------------------------------------------------
+      !!                ***  FUNCTION flo_rst_alloc  ***
+      !!-------------------------------------------------------------------
+      ALLOCATE( iperproc(jpnij), STAT=flo_rst_alloc )
+      !  
+      CALL mpp_sum ( 'florst', flo_rst_alloc )
+      IF( flo_rst_alloc /= 0 )   CALL ctl_stop( 'STOP', 'flo_rst_alloc: failed to allocate arrays.' )
+   END FUNCTION flo_rst_alloc
+
+
+   SUBROUTINE flo_rst( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE flo_rst ***
+      !!             
+      !! ** Purpose :  
+      !!             
+      !!      
+      !! ** Method  :   The frequency of  ??? is nwritefl
+      !!      
+      !!----------------------------------------------------------------------
+      INTEGER  :: kt                            ! time step
+      !
+      CHARACTER (len=80)       :: clname             ! restart filename
+      INTEGER                  :: ic , jc , jpn ,jfl ! temporary integer
+      INTEGER                  :: inum               ! temporary logical unit for restart file
+      !!----------------------------------------------------------------------
+
+      IF(  ( MOD(kt,nn_stockfl) == 0 ) .OR. ( kt == nitend )  )THEN      
+
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'flo_rst : write in  restart_float file '
+            WRITE(numout,*) '~~~~~~~    '
+         ENDIF
+
+         ! file is opened and closed every time it is used.
+
+         clname = 'restart.float.'
+         ic = 1
+         DO jc = 1, 16
+            IF( cexper(jc:jc) /= ' ' ) ic = jc
+         END DO
+         clname = clname(1:14)//cexper(1:ic)
+         ic = 1
+         DO jc = 1, 48
+            IF( clname(jc:jc) /= ' ' ) ic = jc
+         END DO
+
+         inum=0
+         IF( lwp )THEN
+            CALL ctl_opn( inum, clname, 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+            REWIND inum
+         ENDIF
+         !
+         DO jpn = 1, jpnij
+            iperproc(jpn) = 0
+         END DO
+         !
+         IF(lwp) THEN
+            REWIND(inum)
+            WRITE (inum,*) tpifl,tpjfl,tpkfl,nisobfl,ngrpfl
+            CLOSE (inum)
+         ENDIF
+         !
+         ! Compute the number of trajectories for each processor
+         !
+         IF( lk_mpp ) THEN
+            DO jfl = 1, jpnfl
+               IF( (INT(tpifl(jfl)) >= mig(nldi)) .AND.   &
+                  &(INT(tpifl(jfl)) <= mig(nlei)) .AND.   &
+                  &(INT(tpjfl(jfl)) >= mjg(nldj)) .AND.   &
+                  &(INT(tpjfl(jfl)) <= mjg(nlej)) ) THEN
+                  iperproc(narea) = iperproc(narea)+1
+               ENDIF
+            END DO
+            CALL mpp_sum( 'florst', iperproc, jpnij )
+            !
+            IF(lwp) THEN
+               WRITE(numout,*) 'DATE',adatrj
+               DO jpn = 1, jpnij
+                  IF( iperproc(jpn) /= 0 ) THEN
+                     WRITE(numout,*)'PROCESSOR',jpn-1,'compute',iperproc(jpn), 'trajectories.'
+                  ENDIF
+               END DO
+            ENDIF
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE flo_rst
+
+   !!=======================================================================
+END MODULE florst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flowri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flowri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/FLO/flowri.F90	(revision 14097)
@@ -0,0 +1,275 @@
+MODULE flowri
+   !!======================================================================
+   !!                       ***  MODULE  flowri  ***
+   !!
+   !! Ocean floats: write floats trajectory in ascii                    ln_flo_ascii = T
+   !!                                    or in netcdf ( IOM or IOSPSL ) ln_flo_ascii = F           
+   !!======================================================================
+   !!  History :  OPA  !  1999-09  (Y. Drillet)    : Original code
+   !!              -   !  2000-06  (J.-M. Molines) : Profiling floats for CLS 
+   !!   NEMO      1.0  !  2002-10  (A. Bozec)  F90 : Free form and module
+   !!             3.2  !  2010-08  (slaw, cbricaud): netcdf outputs and others 
+   !!----------------------------------------------------------------------
+   USE flo_oce         ! ocean drifting floats
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE lib_mpp         ! distribued memory computing library
+   USE in_out_manager  ! I/O manager
+   USE phycst          ! physic constants
+   USE dianam          ! build name of file (routine)
+   USE ioipsl
+   USE iom             ! I/O library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC flo_wri         ! routine called by floats.F90
+   PUBLIC flo_wri_alloc   ! routine called by floats.F90
+
+   INTEGER :: jfl                            ! number of floats
+   CHARACTER (len=80)  :: clname             ! netcdf output filename
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:) ::   zlon , zlat, zdep   ! 2D workspace
+   REAL(wp), ALLOCATABLE, DIMENSION(:) ::   ztem , zsal, zrho   ! 2D workspace
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION flo_wri_alloc()
+      !!-------------------------------------------------------------------
+      !!                ***  FUNCTION flo_wri_alloc  ***
+      !!-------------------------------------------------------------------
+      ALLOCATE( ztem(jpnfl) , zsal(jpnfl) , zrho(jpnfl) , &
+                zlon(jpnfl) , zlat(jpnfl) , zdep(jpnfl) , STAT=flo_wri_alloc)
+      !  
+      CALL mpp_sum ( 'flowri', flo_wri_alloc )
+      IF( flo_wri_alloc /= 0 )   CALL ctl_stop( 'STOP', 'flo_wri_alloc: failed to allocate arrays.' )
+   END FUNCTION flo_wri_alloc
+
+   SUBROUTINE flo_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE flo_wri ***
+      !!             
+      !! ** Purpose :   Write position of floats in "trajec_float.nc",according
+      !!                to ARIANE TOOLS (http://stockage.univ-brest.fr/~grima/Ariane/ )  n
+      !!                nomenclature
+      !!    
+      !!      
+      !! ** Method  :   The frequency of  ??? is nwritefl
+      !!      
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER  :: kt                               ! time step
+
+      !! * Local declarations
+      INTEGER  :: iafl , ibfl , icfl             ! temporary integer
+      INTEGER  :: ia1fl, ib1fl, ic1fl            !   "
+      INTEGER  :: iafloc,ibfloc,ia1floc,ib1floc  !   "
+      INTEGER  :: irec, irecflo
+
+      REAL(wp) :: zafl,zbfl,zcfl                 ! temporary real
+      REAL(wp) :: ztime                          !   "
+
+      INTEGER, DIMENSION(2)          :: icount
+      INTEGER, DIMENSION(2)          :: istart
+      INTEGER, DIMENSION(1)          :: ish
+      INTEGER, DIMENSION(2)          :: ish2
+      !!----------------------------------------------------------------------
+      
+      !-----------------------------------------------------
+      ! I- Save positions, temperature, salinty and density 
+      !-----------------------------------------------------
+      zlon(:)=0.0 ; zlat(:)=0.0 ; zdep(:)=0.0 
+      ztem(:)=0.0 ; zsal(:)=0.0 ; zrho(:)=0.0 
+
+      DO jfl = 1, jpnfl
+
+         iafl  = INT (tpifl(jfl))            ! I-index of the nearest point before
+         ibfl  = INT (tpjfl(jfl))            ! J-index of the nearest point before
+         icfl  = INT (tpkfl(jfl))            ! K-index of the nearest point before
+         ia1fl = iafl + 1                    ! I-index of the nearest point after
+         ib1fl = ibfl + 1                    ! J-index of the nearest point after
+         ic1fl = icfl + 1                    ! K-index of the nearest point after
+         zafl  = tpifl(jfl) - REAL(iafl,wp)  ! distance  ?????
+         zbfl  = tpjfl(jfl) - REAL(ibfl,wp)  ! distance  ?????
+         zcfl  = tpkfl(jfl) - REAL(icfl,wp)  ! distance  ?????
+
+         IF( lk_mpp ) THEN
+               
+            iafloc = mi1( iafl )
+            ibfloc = mj1( ibfl )
+ 
+            IF( nldi <= iafloc .AND. iafloc <= nlei .AND. &
+              & nldj <= ibfloc .AND. ibfloc <= nlej       ) THEN 
+
+               !the float is inside of current proc's area
+               ia1floc = iafloc + 1
+               ib1floc = ibfloc + 1
+     
+               !save position of the float
+               zlat(jfl) = (1.-zafl)*(1.-zbfl)*gphit(iafloc ,ibfloc ) + (1.-zafl) * zbfl * gphit(iafloc ,ib1floc)   &
+                     +     zafl *(1.-zbfl)*gphit(ia1floc,ibfloc ) +     zafl  * zbfl * gphit(ia1floc,ib1floc)   
+               zlon(jfl) = (1.-zafl)*(1.-zbfl)*glamt(iafloc ,ibfloc ) + (1.-zafl) * zbfl * glamt(iafloc ,ib1floc)   &
+                     +     zafl *(1.-zbfl)*glamt(ia1floc,ibfloc ) +     zafl  * zbfl * glamt(ia1floc,ib1floc)
+               zdep(jfl) = (1.-zcfl)*gdepw_n(iafloc,ibfloc,icfl ) + zcfl * gdepw_n(iafloc,ibfloc,ic1fl)     
+
+               !save temperature, salinity and density at this position
+               ztem(jfl) = tsn(iafloc,ibfloc,icfl,jp_tem)
+               zsal (jfl) = tsn(iafloc,ibfloc,icfl,jp_sal)
+               zrho (jfl) = (rhd(iafloc,ibfloc,icfl)+1)*rau0
+
+            ENDIF
+
+         ELSE  ! mono proc case  
+
+            iafloc  = iafl
+            ibfloc  = ibfl
+            ia1floc = iafloc + 1
+            ib1floc = ibfloc + 1
+
+            !save position of the float               
+            zlat(jfl) = (1.-zafl)*(1.-zbfl)*gphit(iafloc ,ibfloc ) + (1.-zafl) * zbfl * gphit(iafloc ,ib1floc)   &
+                      +     zafl *(1.-zbfl)*gphit(ia1floc,ibfloc ) +     zafl  * zbfl * gphit(ia1floc,ib1floc)
+            zlon(jfl) = (1.-zafl)*(1.-zbfl)*glamt(iafloc ,ibfloc ) + (1.-zafl) * zbfl * glamt(iafloc ,ib1floc)   &
+                      +     zafl *(1.-zbfl)*glamt(ia1floc,ibfloc ) +     zafl  * zbfl * glamt(ia1floc,ib1floc)
+            zdep(jfl) = (1.-zcfl)*gdepw_n(iafloc,ibfloc,icfl ) + zcfl * gdepw_n(iafloc,ibfloc,ic1fl)
+
+            ztem(jfl) = tsn(iafloc,ibfloc,icfl,jp_tem)
+            zsal(jfl) = tsn(iafloc,ibfloc,icfl,jp_sal)
+            zrho(jfl) = (rhd(iafloc,ibfloc,icfl)+1)*rau0
+          
+         ENDIF
+
+      END DO ! loop on float
+
+      !Only proc 0 writes all positions : SUM of positions on all procs
+      IF( lk_mpp ) THEN
+         CALL mpp_sum( 'flowri', zlon, jpnfl )   ! sums over the global domain
+         CALL mpp_sum( 'flowri', zlat, jpnfl )   ! sums over the global domain
+         CALL mpp_sum( 'flowri', zdep, jpnfl )   ! sums over the global domain
+         CALL mpp_sum( 'flowri', ztem, jpnfl )   ! sums over the global domain
+         CALL mpp_sum( 'flowri', zsal, jpnfl )   ! sums over the global domain
+         CALL mpp_sum( 'flowri', zrho, jpnfl )   ! sums over the global domain
+      ENDIF
+
+
+      !-------------------------------------!
+      ! II- WRITE WRITE WRITE WRITE WRITE   !
+      !-------------------------------------!
+
+      !--------------------------!
+      ! II-1 Write in ascii file !
+      !--------------------------!
+
+      IF( ln_flo_ascii )THEN
+
+         IF( ( kt == nn_it000 .OR. MOD( kt,nn_writefl)== 0 ) .AND. lwp )THEN
+
+            !II-1-a Open ascii file
+            !----------------------
+            IF( kt == nn_it000 ) THEN
+               CALL ctl_opn( numflo, 'trajec_float', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+               irecflo = NINT( (nitend-nn_it000) / FLOAT(nn_writefl) )
+               WRITE(numflo,*) cexper, irecflo, jpnfl, nn_writefl
+            ENDIF
+
+            !II-1-b Write in ascii file
+            !-----------------------------
+            WRITE(numflo,*) zlon,zlat,zdep,nisobfl,ngrpfl,ztem,zsal, FLOAT(ndastp)
+
+
+            !II-1-c Close netcdf file
+            !-------------------------
+            IF( kt == nitend )   CLOSE( numflo )
+
+         ENDIF
+
+      !-----------------------------------------------------
+      ! II-2 Write in netcdf file
+      !-----------------------------------------------------
+
+      ELSE
+
+      !II-2-a Write with IOM
+      !----------------------
+
+#if defined key_iomput
+         CALL iom_put( "traj_lon"     , zlon )
+         CALL iom_put( "traj_lat"     , zlat )
+         CALL iom_put( "traj_dep"     , zdep )
+         CALL iom_put( "traj_temp"    , ztem )
+         CALL iom_put( "traj_salt"    , zsal  )
+         CALL iom_put( "traj_dens"    , zrho )
+         CALL iom_put( "traj_group"   , REAL(ngrpfl,wp) )
+#else
+
+      !II-2-b Write with IOIPSL
+      !------------------------
+
+         IF( ( kt == nn_it000 .OR. MOD( kt,nn_writefl)== 0 ) .AND. lwp )THEN
+
+
+            !II-2-b-1 Open netcdf file
+            !-------------------------
+            IF( kt==nn_it000 )THEN   ! Create and open
+
+               CALL dia_nam( clname, nn_writefl, 'trajec_float' )
+               clname=TRIM(clname)//".nc"
+
+               CALL fliocrfd( clname , (/'ntraj' , '    t' /), (/ jpnfl , -1/) , numflo )
+   
+               CALL fliodefv( numflo, 'traj_lon'    , (/1,2/), v_t=flio_r8, long_name="Longitude"           , units="degrees_east"  )
+               CALL fliodefv( numflo, 'traj_lat'    , (/1,2/), v_t=flio_r8, long_name="Latitude"            , units="degrees_north" )
+               CALL fliodefv( numflo, 'traj_depth'  , (/1,2/), v_t=flio_r8, long_name="Depth"               , units="meters" )
+               CALL fliodefv( numflo, 'time_counter', (/2/)  , v_t=flio_r8, long_name="Time axis"           & 
+                         & , units="seconds since start of the run " )
+               CALL fliodefv( numflo, 'traj_temp'   , (/1,2/), v_t=flio_r8, long_name="Temperature"         , units="C" )
+               CALL fliodefv( numflo, 'traj_salt'   , (/1,2/), v_t=flio_r8, long_name="Salinity"            , units="PSU" )
+               CALL fliodefv( numflo, 'traj_dens'   , (/1,2/), v_t=flio_r8, long_name="Density"             , units="kg/m3" )
+               CALL fliodefv( numflo, 'traj_group'  , (/1/)  , v_t=flio_r8, long_name="number of the group" , units="no unit" )
+
+               CALL flioputv( numflo , 'traj_group' , REAL(ngrpfl,wp) )
+  
+            ELSE  ! Re-open
+       
+               CALL flioopfd( TRIM(clname), numflo , "WRITE" )
+
+            ENDIF
+
+            !II-2-b-2 Write in  netcdf file
+            !-------------------------------
+            irec =  INT( (kt-nn_it000+1)/nn_writefl ) +1
+            ztime = ( kt-nn_it000 + 1 ) * rdt
+
+            CALL flioputv( numflo , 'time_counter', ztime , start=(/irec/) )
+
+            DO jfl = 1, jpnfl
+
+               istart = (/jfl,irec/)
+
+               CALL flioputv( numflo , 'traj_lon'    , zlon(jfl), start=istart )
+               CALL flioputv( numflo , 'traj_lat'    , zlat(jfl), start=istart )  
+               CALL flioputv( numflo , 'traj_depth'  , zdep(jfl), start=istart )  
+               CALL flioputv( numflo , 'traj_temp'   , ztem(jfl), start=istart )  
+               CALL flioputv( numflo , 'traj_salt'   , zsal(jfl), start=istart )  
+               CALL flioputv( numflo , 'traj_dens'   , zrho(jfl), start=istart )  
+
+            ENDDO
+
+            !II-2-b-3 Close netcdf file
+            !---------------------------
+            CALL flioclo( numflo )
+
+         ENDIF
+
+#endif
+      ENDIF ! netcdf writing
+   
+   END SUBROUTINE flo_wri
+
+   !!=======================================================================
+END MODULE flowri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icb_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icb_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icb_oce.F90	(revision 14097)
@@ -0,0 +1,203 @@
+MODULE icb_oce
+   !!======================================================================
+   !!                       ***  MODULE  icb_oce  ***
+   !! Icebergs:  declare variables for iceberg tracking
+   !!======================================================================
+   !! History :  3.3  !  2010-01  (T. Martin & A. Adcroft)  Original code
+   !!             -   !  2011-03  (G. Madec)  Part conversion to NEMO form
+   !!             -   !                       Removal of mapping from another grid
+   !!             -   !  2011-04  (S. Alderson) Extensive rewrite ; Split into separate modules
+   !!----------------------------------------------------------------------
+   !!
+   !! Track Icebergs as Lagrangian objects within the model domain
+   !! Interaction with the other model variables through 'icebergs_gridded'
+   !!
+   !! A single iceberg is held as an instance of type 'iceberg'
+   !! This type defines a linked list, so each instance contains a pointer 
+   !! to the previous and next icebergs in the list
+   !!
+   !! Type 'icebergs' is a convenience container for all relevant arrays
+   !! It contains one pointer to an 'iceberg' instance representing all icebergs in the processor
+   !!
+   !! Each iceberg has a position represented as a real cartesian coordinate which is 
+   !! fractional grid cell, centred on T-points; so an iceberg position of (1.0,1.0) lies 
+   !! exactly on the first T-point and the T-cell spans 0.5 to 1.5 in each direction
+   !!
+   !! Each iceberg is assigned a unique id even in MPI
+   !! This consists of an array of integers: the first element is used to label, the second
+   !! and subsequent elements are used to count the number of times the first element wraps
+   !! around all possible values within the valid size for this datatype.
+   !! Labelling is done by starting the first label in each processor (even when only one)
+   !! as narea, and then incrementing by jpnij (i.e. the total number of processors.
+   !! This means that the source processor for each iceberg can be identified by arithmetic
+   !! modulo jpnij.
+   !! 
+   !!----------------------------------------------------------------------
+   USE par_oce   ! ocean parameters
+   USE lib_mpp   ! MPP library
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC   icb_alloc   ! routine called by icb_init in icbini.F90 module
+
+   INTEGER, PUBLIC, PARAMETER ::   nclasses = 10   !: Number of icebergs classes   
+   INTEGER, PUBLIC, PARAMETER ::   nkounts  =  3   !: Number of integers combined for unique naming
+
+   TYPE, PUBLIC ::   icebergs_gridded   !: various icebergs properties on model grid
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   calving         ! Calving mass rate  (into stored ice)         [kg/s]
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   calving_hflx    ! Calving heat flux [heat content of calving]  [W/m2]
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   floating_melt   ! Net melting rate to icebergs + bits      [kg/s/m^2]
+      INTEGER , DIMENSION(:,:)  , ALLOCATABLE ::   maxclass        ! maximum class number at calving source point
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   tmp             ! Temporary work space
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   stored_ice      ! Accumulated ice mass flux at calving locations [kg]
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   stored_heat     ! Heat content of stored ice                      [J]
+   END TYPE icebergs_gridded
+
+   TYPE, PUBLIC ::   point              !: properties of an individual iceberg (position, mass, size, etc...)
+      INTEGER  ::   year
+      REAL(wp) ::   xi , yj                                                   ! iceberg coordinates in the (i,j) referential (global)
+      REAL(wp) ::   e1 , e2                                                   ! horizontal scale factors at the iceberg position
+      REAL(wp) ::   lon, lat, day                                             ! geographic position
+      REAL(wp) ::   mass, thickness, width, length, uvel, vvel                ! iceberg physical properties
+      REAL(wp) ::   uo, vo, ui, vi, ua, va, ssh_x, ssh_y, sst, cn, hi, sss    ! properties of iceberg environment 
+      REAL(wp) ::   mass_of_bits, heat_density
+   END TYPE point
+
+   TYPE, PUBLIC ::   iceberg            !: linked list defining all the icebergs present in the model domain
+      TYPE(iceberg), POINTER      ::   prev=>NULL(), next=>NULL()   ! pointers to previous and next unique icebergs in linked list
+      INTEGER, DIMENSION(nkounts) ::   number                       ! variables which do not change for this iceberg
+      REAL(wp)                    ::   mass_scaling                 !    -        -            -                -  
+      TYPE(point), POINTER        ::   current_point => NULL()      ! variables which change with time are held in a separate type
+   END TYPE iceberg
+
+
+   TYPE(icebergs_gridded), POINTER ::   berg_grid                 !: master instance of gridded iceberg type
+   TYPE(iceberg)         , POINTER ::   first_berg => NULL()      !: master instance of linked list iceberg type
+
+   !                                                             !!! parameters controlling iceberg characteristics and modelling
+   REAL(wp)                            ::   berg_dt                   !: Time-step between iceberg CALLs (should make adaptive?)
+   REAL(wp), DIMENSION(:), ALLOCATABLE ::   first_width, first_length !: 
+   LOGICAL                             ::   l_restarted_bergs=.FALSE.  ! Indicate whether we read state from a restart or not
+   !                                                               ! arbitrary numbers for diawri entry
+   REAL(wp), DIMENSION(nclasses), PUBLIC ::   class_num=(/ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /)
+
+   ! Extra arrays with bigger halo, needed when interpolating forcing onto iceberg position
+   ! 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, tt_e, fr_e, ss_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ua_e, va_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ssh_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   tmask_e, umask_e, vmask_e
+#if defined key_si3 || defined key_cice
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   hi_e, ui_e, vi_e
+#endif
+
+   !!gm almost all those PARAM ARE defined in NEMO
+   REAL(wp), PUBLIC, PARAMETER :: pp_rho_ice      = 916.7_wp   !: Density of fresh ice   @ 0oC [kg/m^3]
+   REAL(wp), PUBLIC, PARAMETER :: pp_rho_water    = 999.8_wp   !: Density of fresh water @ 0oC [kg/m^3]
+   REAL(wp), PUBLIC, PARAMETER :: pp_rho_air      = 1.1_wp     !: Density of air         @ 0oC [kg/m^3]
+   REAL(wp), PUBLIC, PARAMETER :: pp_rho_seawater = 1025._wp   !: Approx. density of surface sea water @ 0oC [kg/m^3]
+   !!gm end
+   REAL(wp), PUBLIC, PARAMETER :: pp_Cd_av = 1.3_wp      !: (Vertical) Drag coefficient between bergs and atmos 
+   REAL(wp), PUBLIC, PARAMETER :: pp_Cd_ah = 0.0055_wp   !: (lateral ) Drag coefficient between bergs and atmos 
+   REAL(wp), PUBLIC, PARAMETER :: pp_Cd_wv = 0.9_wp      !: (Vertical) Drag coefficient between bergs and ocean
+   REAL(wp), PUBLIC, PARAMETER :: pp_Cd_wh = 0.0012_wp   !: (lateral ) Drag coefficient between bergs and ocean 
+   REAL(wp), PUBLIC, PARAMETER :: pp_Cd_iv = 0.9_wp      !: (Vertical) Drag coefficient between bergs and sea-ice
+!TOM> no horizontal drag for sea ice! real, PARAMETER :: pp_Cd_ih=0.0012 ! (lateral) Drag coeff. between bergs and sea-ice
+
+   !                                                         !!* namberg namelist parameters (and defaults) **
+   LOGICAL , PUBLIC ::   ln_bergdia                      !: Calculate budgets
+   INTEGER , PUBLIC ::   nn_verbose_level                !: Turn on debugging when level > 0
+   INTEGER , PUBLIC ::   nn_test_icebergs                !: Create icebergs in absence of a restart file from the supplied class nb
+   REAL(wp), PUBLIC, DIMENSION(4) ::   rn_test_box       !: lon1,lon2,lat1,lat2 box to create them in
+   LOGICAL , PUBLIC ::   ln_use_calving                  !: Force use of calving data even with nn_test_icebergs > 0 
+                                                         !  (default is not to use calving data with test bergs)
+   INTEGER , PUBLIC ::   nn_sample_rate                  !: Timesteps between sampling of position for trajectory storage
+   INTEGER , PUBLIC ::   nn_verbose_write                !: timesteps between verbose messages
+   REAL(wp), PUBLIC ::   rn_rho_bergs                    !: Density of icebergs
+   REAL(wp), PUBLIC ::   rn_LoW_ratio                    !: Initial ratio L/W for newly calved icebergs
+   REAL(wp), PUBLIC ::   rn_bits_erosion_fraction        !: Fraction of erosion melt flux to divert to bergy bits
+   REAL(wp), PUBLIC ::   rn_sicn_shift                   !: Shift of sea-ice concentration in erosion flux modulation (0<sicn_shift<1)
+   LOGICAL , PUBLIC ::   ln_operator_splitting           !: Use first order operator splitting for thermodynamics
+   LOGICAL , PUBLIC ::   ln_passive_mode                 !: iceberg - ocean decoupling
+   REAL(wp), PUBLIC ::   rn_speed_limit                  !: CFL speed limit for a berg
+   !
+   !                                     ! Mass thresholds between iceberg classes [kg]
+   REAL(wp), DIMENSION(nclasses), PUBLIC ::   rn_initial_mass      ! Fraction of calving to apply to this class [non-dim]
+   REAL(wp), DIMENSION(nclasses), PUBLIC ::   rn_distribution      ! Ratio between effective and real iceberg mass (non-dim)
+   REAL(wp), DIMENSION(nclasses), PUBLIC ::   rn_mass_scaling      ! Total thickness of newly calved bergs [m]
+   REAL(wp), DIMENSION(nclasses), PUBLIC ::   rn_initial_thickness !  Single instance of an icebergs type initialised in icebergs_init and updated in icebergs_run
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   src_calving, src_calving_hflx    !: accumulate input ice
+   INTEGER , PUBLIC             , SAVE                     ::   numicb                           !: iceberg IO
+   INTEGER , PUBLIC             , SAVE, DIMENSION(nkounts) ::   num_bergs                        !: iceberg counter
+   INTEGER , PUBLIC             , SAVE                     ::   nicbdi, nicbei, nicbdj, nicbej   !: processor bounds
+   REAL(wp), PUBLIC             , SAVE                     ::   ricb_left, ricb_right            !: cyclical bounds
+   INTEGER , PUBLIC             , SAVE                     ::   nicbpack                         !: packing integer
+   INTEGER , PUBLIC             , SAVE                     ::   nktberg, nknberg                 !: helpers
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbfldpts                       !: nfold packed points
+   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
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   INTEGER FUNCTION icb_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE icb_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER ::   ill
+      !!----------------------------------------------------------------------
+      !
+      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)          ,   &
+         &      berg_grid%maxclass   (jpi,jpj) , berg_grid%stored_ice   (jpi,jpj,nclasses) ,   &
+         &      berg_grid%tmp        (jpi,jpj) , STAT=ill)
+      icb_alloc = icb_alloc + ill
+      !
+      ! expanded arrays for bilinear interpolation
+      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_si3 || defined key_cice
+         &      ui_e(0:jpi+1,0:jpj+1) ,                            &
+         &      vi_e(0:jpi+1,0:jpj+1) ,                            &
+         &      hi_e(0:jpi+1,0:jpj+1) ,                            &
+#endif
+         &      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) ,   &
+         &      ss_e(0:jpi+1,0:jpj+1) ,                            & 
+         &      first_width(nclasses) , first_length(nclasses) ,   &
+         &      src_calving (jpi,jpj) ,                            &
+         &      src_calving_hflx(jpi,jpj) , STAT=ill)
+      icb_alloc = icb_alloc + ill
+
+      ALLOCATE( tmask_e(0:jpi+1,0:jpj+1), umask_e(0:jpi+1,0:jpj+1), vmask_e(0:jpi+1,0:jpj+1), &
+         &      STAT=ill)
+      icb_alloc = icb_alloc + ill
+
+      ALLOCATE( nicbfldpts(jpi) , nicbflddest(jpi) , nicbfldproc(jpni) , &
+         &      nicbfldnsend(jpni), nicbfldexpect(jpni) , nicbfldreq(jpni), STAT=ill)
+      icb_alloc = icb_alloc + ill
+
+      ALLOCATE( griddata(jpi,jpj,1), STAT=ill )
+      icb_alloc = icb_alloc + ill
+
+      CALL mpp_sum ( 'icb_oce', icb_alloc )
+      IF( icb_alloc > 0 )   CALL ctl_warn('icb_alloc: allocation of arrays failed')
+      !
+   END FUNCTION icb_alloc
+
+   !!======================================================================
+END MODULE icb_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbclv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbclv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbclv.F90	(revision 14097)
@@ -0,0 +1,186 @@
+MODULE icbclv
+   !!======================================================================
+   !!                       ***  MODULE  icbclv  ***
+   !! Icebergs:  calving routines for iceberg calving
+   !!======================================================================
+   !! History : 3.3.1 !  2010-01  (Martin&Adcroft) Original code
+   !!            -    !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -    !                            Removal of mapping from another grid
+   !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!            -    !  2011-05  (Alderson)       budgets into separate module
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_clv_flx   : transfer input flux of ice into iceberg classes
+   !!   icb_clv       : calve icebergs from stored ice
+   !!----------------------------------------------------------------------
+   USE par_oce        ! NEMO parameters
+   USE dom_oce        ! NEMO ocean domain
+   USE phycst         ! NEMO physical constants
+   USE lib_mpp        ! NEMO MPI library, lk_mpp in particular
+   USE lbclnk         ! NEMO boundary exchanges for gridded data
+
+   USE icb_oce        ! iceberg variables
+   USE icbdia         ! iceberg diagnostics
+   USE icbutl         ! iceberg utility routines
+   USE icb_oce        ! iceberg parameters 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_clv_flx  ! routine called in icbstp.F90 module
+   PUBLIC   icb_clv      ! routine called in icbstp.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_clv_flx( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_clv_flx  ***
+      !!
+      !! ** Purpose :   accumulate ice available for calving into class arrays
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt
+      !
+      REAL(wp)      ::   zcalving_used, zdist, zfact
+      INTEGER       ::   jn, ji, jj                    ! loop counters
+      INTEGER       ::   imx                           ! temporary integer for max berg class
+      LOGICAL, SAVE ::   ll_first_call = .TRUE.
+      !!----------------------------------------------------------------------
+      !
+      ! Adapt calving flux and calving heat flux from coupler for use here
+      ! Use interior mask: so no bergs in overlap areas and convert from km^3/year to kg/s
+      ! this assumes that input is given as equivalent water flux so that pure water density is appropriate
+
+      zfact = ( (1000._wp)**3 / ( NINT(rday) * nyear_len(1) ) ) * rn_rho_bergs
+      berg_grid%calving(:,:) = src_calving(:,:) * zfact * tmask_i(:,:) * tmask(:,:,1)
+
+      ! Heat in units of W/m2, and mask (just in case)
+      berg_grid%calving_hflx(:,:) = src_calving_hflx(:,:) * tmask_i(:,:) * tmask(:,:,1)
+
+      IF( ll_first_call .AND. .NOT. l_restarted_bergs ) THEN      ! This is a hack to simplify initialization
+         ll_first_call = .FALSE.
+         !do jn=1, nclasses
+         !  where (berg_grid%calving==0.) berg_grid%stored_ice(:,:,jn)=0.
+         !end do
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF( berg_grid%calving(ji,jj) /= 0._wp )                                          &    ! Need units of J
+                  berg_grid%stored_heat(ji,jj) = SUM( berg_grid%stored_ice(ji,jj,:) ) *         &    ! initial stored ice in kg
+                     &                   berg_grid%calving_hflx(ji,jj) * e1e2t(ji,jj) / berg_grid%calving(ji,jj)   ! J/s/m2 x m^2 
+                     !                                                                                             ! = J/s/calving in kg/s
+            END DO
+         END DO
+      ENDIF
+
+      ! assume that all calving flux must be distributed even if distribution array does not sum
+      ! to one - this may not be what is intended, but it's what you've got
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            imx = berg_grid%maxclass(ji,jj)
+            zdist = SUM( rn_distribution(1:nclasses) ) / SUM( rn_distribution(1:imx) )
+            DO jn = 1, imx
+               berg_grid%stored_ice(ji,jj,jn) = berg_grid%stored_ice(ji,jj,jn)     &
+                  &                           + berg_dt * berg_grid%calving(ji,jj) * rn_distribution(jn) * zdist
+            END DO
+         END DO
+      END DO
+
+      ! before changing the calving, save the amount we're about to use and do budget
+      zcalving_used = SUM( berg_grid%calving(:,:) )
+      berg_grid%tmp(:,:) = berg_dt * berg_grid%calving_hflx(:,:) * e1e2t(:,:) * tmask_i(:,:)
+      berg_grid%stored_heat (:,:) = berg_grid%stored_heat (:,:) + berg_grid%tmp(:,:)
+      CALL icb_dia_income( kt,  zcalving_used, berg_grid%tmp )
+      !
+   END SUBROUTINE icb_clv_flx
+
+
+   SUBROUTINE icb_clv( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_clv  ***
+      !!
+      !! ** Purpose :   This routine takes a stored ice field and calves to the ocean,
+      !!                so the gridded array stored_ice has only non-zero entries at selected
+      !!                wet points adjacent to known land based calving points
+      !!
+      !! ** method  : - Look at each grid point and see if there's enough for each size class to calve
+      !!                If there is, a new iceberg is calved.  This happens in the order determined by
+      !!                the class definition arrays (which in the default case is smallest first)
+      !!                Note that only the non-overlapping part of the processor where icebergs are allowed
+      !!                is considered
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt
+      INTEGER       ::   ji, jj, jn   ! dummy loop indices
+      INTEGER       ::   icnt, icntmax
+      TYPE(iceberg) ::   newberg
+      TYPE(point)   ::   newpt
+      REAL(wp)      ::   zday, zcalved_to_berg, zheat_to_berg
+      !!----------------------------------------------------------------------
+      !
+      icntmax = 0
+      zday    = REAL(nday_year,wp) + REAL(nsec_day,wp)/86400.0_wp
+      !
+      DO jn = 1, nclasses
+         DO jj = nicbdj, nicbej
+            DO ji = nicbdi, nicbei
+               !
+               icnt = 0
+               !
+               DO WHILE (berg_grid%stored_ice(ji,jj,jn) >= rn_initial_mass(jn) * rn_mass_scaling(jn) )
+                  !
+                  newpt%lon = glamt(ji,jj)         ! at t-point (centre of the cell)
+                  newpt%lat = gphit(ji,jj)
+                  newpt%xi  = REAL( mig(ji), wp )
+                  newpt%yj  = REAL( mjg(jj), wp )
+                  !
+                  newpt%uvel = 0._wp               ! initially at rest
+                  newpt%vvel = 0._wp
+                  !                                ! set berg characteristics
+                  newpt%mass           = rn_initial_mass     (jn)
+                  newpt%thickness      = rn_initial_thickness(jn)
+                  newpt%width          = first_width         (jn)
+                  newpt%length         = first_length        (jn)
+                  newberg%mass_scaling = rn_mass_scaling     (jn)
+                  newpt%mass_of_bits   = 0._wp                          ! no bergy
+                  !
+                  newpt%year   = nyear
+                  newpt%day    = zday
+                  newpt%heat_density = berg_grid%stored_heat(ji,jj) / berg_grid%stored_ice(ji,jj,jn)   ! This is in J/kg
+                  !
+                  CALL icb_utl_incr()
+                  newberg%number(:) = num_bergs(:)
+                  !
+                  CALL icb_utl_add( newberg, newpt )
+                  !
+                  zcalved_to_berg = rn_initial_mass(jn) * rn_mass_scaling(jn)           ! Units of kg
+                  !                                ! Heat content
+                  zheat_to_berg           = zcalved_to_berg * newpt%heat_density             ! Units of J
+                  berg_grid%stored_heat(ji,jj) = berg_grid%stored_heat(ji,jj) - zheat_to_berg
+                  !                                ! Stored mass
+                  berg_grid%stored_ice(ji,jj,jn) = berg_grid%stored_ice(ji,jj,jn) - zcalved_to_berg
+                  !
+                  icnt = icnt + 1
+                  !
+                  CALL icb_dia_calve(ji, jj, jn,  zcalved_to_berg, zheat_to_berg )
+               END DO
+               icntmax = MAX( icntmax, icnt )
+            END DO
+         END DO
+      END DO
+      !
+      DO jn = 1, nclasses
+         CALL lbc_lnk( 'icbclv', berg_grid%stored_ice(:,:,jn), 'T', 1._wp )
+      END DO
+      CALL lbc_lnk( 'icbclv', berg_grid%stored_heat, 'T', 1._wp )
+      !
+      IF( nn_verbose_level > 0 .AND. icntmax > 1 )   WRITE(numicb,*) 'icb_clv: icnt=', icnt,' on', narea
+      !
+   END SUBROUTINE  icb_clv
+
+   !!======================================================================
+END MODULE icbclv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdia.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdia.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdia.F90	(revision 14097)
@@ -0,0 +1,616 @@
+MODULE icbdia
+   !!======================================================================
+   !!                       ***  MODULE  icbdia  ***
+   !! Icebergs:  initialise variables for iceberg budgets and diagnostics
+   !!======================================================================
+   !! History : 3.3 !  2010-01  (Martin, Adcroft) Original code
+   !!            -  !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -  !                            Removal of mapping from another grid
+   !!            -  !  2011-04  (Alderson)       Split into separate modules
+   !!            -  !  2011-05  (Alderson)       Budgets are now all here with lots
+   !!            -  !                            of silly routines to call to get values in
+   !!            -  !                            from the right points in the code
+   !!----------------------------------------------------------------------
+ 
+   !!----------------------------------------------------------------------
+   !!   icb_dia_init  : initialise iceberg budgeting
+   !!   icb_dia       : global iceberg diagnostics
+   !!   icb_dia_step  : reset at the beginning of each timestep
+   !!   icb_dia_put   : output (via iom_put) iceberg fields
+   !!   icb_dia_calve : 
+   !!   icb_dia_income: 
+   !!   icb_dia_size  : 
+   !!   icb_dia_speed : 
+   !!   icb_dia_melt  : 
+   !!   report_state  : 
+   !!   report_consistant : 
+   !!   report_budget : 
+   !!   report_istate : 
+   !!   report_ibudget: 
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE dom_oce        ! ocean domain
+   USE in_out_manager ! nemo IO
+   USE lib_mpp        ! MPP library
+   USE iom            ! I/O library
+   USE icb_oce        ! iceberg variables
+   USE icbutl         ! iceberg utility routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_dia_init      ! routine called in icbini.F90 module
+   PUBLIC   icb_dia           ! routine called in icbstp.F90 module
+   PUBLIC   icb_dia_step      ! routine called in icbstp.F90 module
+   PUBLIC   icb_dia_put       ! routine called in icbstp.F90 module
+   PUBLIC   icb_dia_melt      ! routine called in icbthm.F90 module
+   PUBLIC   icb_dia_size      ! routine called in icbthm.F90 module
+   PUBLIC   icb_dia_speed     ! routine called in icbdyn.F90 module
+   PUBLIC   icb_dia_calve     ! routine called in icbclv.F90 module
+   PUBLIC   icb_dia_income    ! routine called in icbclv.F90 module
+
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   berg_melt       ! Melting+erosion rate of icebergs     [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   berg_melt_hcflx ! Heat flux to ocean due to heat content of melting icebergs [J/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   berg_melt_qlat  ! Heat flux to ocean due to latent heat of melting icebergs [J/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   buoy_melt       ! Buoyancy component of melting rate   [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   eros_melt       ! Erosion component of melting rate    [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   conv_melt       ! Convective component of melting rate [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   bits_src        ! Mass flux from berg erosion into bergy bits [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   bits_melt       ! Melting rate of bergy bits           [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   bits_mass       ! Mass distribution of bergy bits      [kg/s/m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   virtual_area    ! Virtual surface coverage by icebergs [m2]
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE, PUBLIC  ::   berg_mass       ! Mass distribution                    [kg/m2]
+   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, PUBLIC  ::   real_calving    ! Calving rate into iceberg class at
+   !                                                                          ! calving locations                    [kg/s]
+   
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   tmpc                     ! Temporary work space
+   REAL(wp), DIMENSION(:)    , ALLOCATABLE ::   rsumbuf                  ! Temporary work space to reduce mpp exchanges
+   INTEGER , DIMENSION(:)    , ALLOCATABLE ::   nsumbuf                  ! Temporary work space to reduce mpp exchanges
+
+   REAL(wp)                      ::  berg_melt_net
+   REAL(wp)                      ::  bits_src_net
+   REAL(wp)                      ::  bits_melt_net
+   REAL(wp)                      ::  bits_mass_start     , bits_mass_end
+   REAL(wp)                      ::  floating_heat_start , floating_heat_end
+   REAL(wp)                      ::  floating_mass_start , floating_mass_end
+   REAL(wp)                      ::  bergs_mass_start    , bergs_mass_end
+   REAL(wp)                      ::  stored_start        , stored_heat_start
+   REAL(wp)                      ::  stored_end          , stored_heat_end
+   REAL(wp)                      ::  calving_src_net     , calving_out_net
+   REAL(wp)                      ::  calving_src_heat_net, calving_out_heat_net
+   REAL(wp)                      ::  calving_src_heat_used_net
+   REAL(wp)                      ::  calving_rcv_net  , calving_ret_net  , calving_used_net
+   REAL(wp)                      ::  heat_to_bergs_net, heat_to_ocean_net, melt_net
+   REAL(wp)                      ::  calving_to_bergs_net
+
+   INTEGER                       ::  nbergs_start, nbergs_end, nbergs_calved
+   INTEGER                       ::  nbergs_melted
+   INTEGER                       ::  nspeeding_tickets
+   INTEGER , DIMENSION(nclasses) ::  nbergs_calved_by_class
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_dia_init( )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+
+      ALLOCATE( berg_melt    (jpi,jpj)   )           ;   berg_melt   (:,:)   = 0._wp
+      ALLOCATE( berg_melt_hcflx(jpi,jpj) )           ;   berg_melt_hcflx(:,:)   = 0._wp
+      ALLOCATE( berg_melt_qlat(jpi,jpj)  )           ;   berg_melt_qlat(:,:)   = 0._wp
+      ALLOCATE( buoy_melt    (jpi,jpj)   )           ;   buoy_melt   (:,:)   = 0._wp
+      ALLOCATE( eros_melt    (jpi,jpj)   )           ;   eros_melt   (:,:)   = 0._wp
+      ALLOCATE( conv_melt    (jpi,jpj)   )           ;   conv_melt   (:,:)   = 0._wp
+      ALLOCATE( bits_src     (jpi,jpj)   )           ;   bits_src    (:,:)   = 0._wp
+      ALLOCATE( bits_melt    (jpi,jpj)   )           ;   bits_melt   (:,:)   = 0._wp
+      ALLOCATE( bits_mass    (jpi,jpj)   )           ;   bits_mass   (:,:)   = 0._wp
+      ALLOCATE( virtual_area (jpi,jpj)   )           ;   virtual_area(:,:)   = 0._wp
+      ALLOCATE( berg_mass    (jpi,jpj)   )           ;   berg_mass   (:,:)   = 0._wp
+      ALLOCATE( real_calving (jpi,jpj,nclasses) )    ;   real_calving(:,:,:) = 0._wp
+      ALLOCATE( tmpc(jpi,jpj) )                      ;   tmpc        (:,:)   = 0._wp
+
+      nbergs_start              = 0
+      nbergs_end                = 0
+      stored_end                = 0._wp
+      nbergs_start              = 0._wp
+      stored_start              = 0._wp
+      nbergs_melted             = 0
+      nbergs_calved             = 0
+      nbergs_calved_by_class(:) = 0
+      nspeeding_tickets         = 0
+      stored_heat_end           = 0._wp
+      floating_heat_end         = 0._wp
+      floating_mass_end         = 0._wp
+      bergs_mass_end            = 0._wp
+      bits_mass_end             = 0._wp
+      stored_heat_start         = 0._wp
+      floating_heat_start       = 0._wp
+      floating_mass_start       = 0._wp
+      bergs_mass_start          = 0._wp
+      bits_mass_start           = 0._wp
+      bits_mass_end             = 0._wp
+      calving_used_net          = 0._wp
+      calving_to_bergs_net      = 0._wp
+      heat_to_bergs_net         = 0._wp
+      heat_to_ocean_net         = 0._wp
+      calving_rcv_net           = 0._wp
+      calving_ret_net           = 0._wp
+      calving_src_net           = 0._wp
+      calving_out_net           = 0._wp
+      calving_src_heat_net      = 0._wp
+      calving_src_heat_used_net = 0._wp
+      calving_out_heat_net      = 0._wp
+      melt_net                  = 0._wp
+      berg_melt_net             = 0._wp
+      bits_melt_net             = 0._wp
+      bits_src_net              = 0._wp
+
+      floating_mass_start       = icb_utl_mass( first_berg )
+      bergs_mass_start          = icb_utl_mass( first_berg, justbergs=.TRUE. )
+      bits_mass_start           = icb_utl_mass( first_berg, justbits =.TRUE. )
+      IF( lk_mpp ) THEN
+         ALLOCATE( rsumbuf(23) )          ; rsumbuf(:) = 0._wp
+         ALLOCATE( nsumbuf(4+nclasses) )  ; nsumbuf(:) = 0
+         rsumbuf(1) = floating_mass_start
+         rsumbuf(2) = bergs_mass_start
+         rsumbuf(3) = bits_mass_start
+         CALL mpp_sum( 'icbdia', rsumbuf(1:3), 3 )
+         floating_mass_start = rsumbuf(1)
+         bergs_mass_start = rsumbuf(2)
+         bits_mass_start = rsumbuf(3)
+      ENDIF
+      !
+   END SUBROUTINE icb_dia_init
+
+
+   SUBROUTINE icb_dia( ld_budge )
+      !!----------------------------------------------------------------------
+      !! sum all the things we've accumulated so far in the current processor
+      !! in MPP case then add these sums across all processors
+      !! for this we pack variables into buffer so we only need one mpp_sum
+      !!----------------------------------------------------------------------
+      LOGICAL, INTENT(in) ::   ld_budge   !
+      !
+      INTEGER ::   ik
+      REAL(wp)::   zunused_calving, ztmpsum, zgrdd_berg_mass, zgrdd_bits_mass
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+
+      zunused_calving      = SUM( berg_grid%calving(:,:) )
+      ztmpsum              = SUM( berg_grid%floating_melt(:,:) * e1e2t(:,:) * tmask_i(:,:) )
+      melt_net             = melt_net + ztmpsum * berg_dt
+      calving_out_net      = calving_out_net + ( zunused_calving + ztmpsum ) * berg_dt
+      ztmpsum              = SUM( berg_melt(:,:) * e1e2t(:,:) * tmask_i(:,:) )
+      berg_melt_net        = berg_melt_net + ztmpsum * berg_dt
+      ztmpsum              = SUM( bits_src(:,:) * e1e2t(:,:) * tmask_i(:,:) )
+      bits_src_net         = bits_src_net + ztmpsum * berg_dt
+      ztmpsum              = SUM( bits_melt(:,:) * e1e2t(:,:) * tmask_i(:,:) )
+      bits_melt_net        = bits_melt_net + ztmpsum * berg_dt
+      ztmpsum              = SUM( src_calving(:,:) * tmask_i(:,:) )
+      calving_ret_net      = calving_ret_net + ztmpsum * berg_dt
+      ztmpsum              = SUM( berg_grid%calving_hflx(:,:) * e1e2t(:,:) * tmask_i(:,:) )
+      calving_out_heat_net = calving_out_heat_net + ztmpsum * berg_dt   ! Units of J
+      !
+      IF( ld_budge ) THEN
+         stored_end        = SUM( berg_grid%stored_ice(:,:,:) )
+         stored_heat_end   = SUM( berg_grid%stored_heat(:,:) )
+         floating_mass_end = icb_utl_mass( first_berg )
+         bergs_mass_end    = icb_utl_mass( first_berg,justbergs=.TRUE. )
+         bits_mass_end     = icb_utl_mass( first_berg,justbits =.TRUE. )
+         floating_heat_end = icb_utl_heat( first_berg )
+         !
+         nbergs_end        = icb_utl_count()
+         zgrdd_berg_mass   = SUM( berg_mass(:,:)*e1e2t(:,:)*tmask_i(:,:) )
+         zgrdd_bits_mass   = SUM( bits_mass(:,:)*e1e2t(:,:)*tmask_i(:,:) )
+         !
+         IF( lk_mpp ) THEN
+            rsumbuf( 1) = stored_end
+            rsumbuf( 2) = stored_heat_end
+            rsumbuf( 3) = floating_mass_end
+            rsumbuf( 4) = bergs_mass_end
+            rsumbuf( 5) = bits_mass_end
+            rsumbuf( 6) = floating_heat_end
+            rsumbuf( 7) = calving_ret_net
+            rsumbuf( 8) = calving_out_net
+            rsumbuf( 9) = calving_rcv_net
+            rsumbuf(10) = calving_src_net
+            rsumbuf(11) = calving_src_heat_net
+            rsumbuf(12) = calving_src_heat_used_net
+            rsumbuf(13) = calving_out_heat_net
+            rsumbuf(14) = calving_used_net
+            rsumbuf(15) = calving_to_bergs_net
+            rsumbuf(16) = heat_to_bergs_net
+            rsumbuf(17) = heat_to_ocean_net
+            rsumbuf(18) = melt_net
+            rsumbuf(19) = berg_melt_net
+            rsumbuf(20) = bits_src_net
+            rsumbuf(21) = bits_melt_net
+            rsumbuf(22) = zgrdd_berg_mass
+            rsumbuf(23) = zgrdd_bits_mass
+            !
+            CALL mpp_sum( 'icbdia', rsumbuf(1:23), 23)
+            !
+            stored_end                = rsumbuf( 1)
+            stored_heat_end           = rsumbuf( 2)
+            floating_mass_end         = rsumbuf( 3)
+            bergs_mass_end            = rsumbuf( 4)
+            bits_mass_end             = rsumbuf( 5)
+            floating_heat_end         = rsumbuf( 6)
+            calving_ret_net           = rsumbuf( 7)
+            calving_out_net           = rsumbuf( 8)
+            calving_rcv_net           = rsumbuf( 9)
+            calving_src_net           = rsumbuf(10)
+            calving_src_heat_net      = rsumbuf(11)
+            calving_src_heat_used_net = rsumbuf(12)
+            calving_out_heat_net      = rsumbuf(13)
+            calving_used_net          = rsumbuf(14)
+            calving_to_bergs_net      = rsumbuf(15)
+            heat_to_bergs_net         = rsumbuf(16)
+            heat_to_ocean_net         = rsumbuf(17)
+            melt_net                  = rsumbuf(18)
+            berg_melt_net             = rsumbuf(19)
+            bits_src_net              = rsumbuf(20)
+            bits_melt_net             = rsumbuf(21)
+            zgrdd_berg_mass           = rsumbuf(22)
+            zgrdd_bits_mass           = rsumbuf(23)
+            !
+            nsumbuf(1) = nbergs_end
+            nsumbuf(2) = nbergs_calved
+            nsumbuf(3) = nbergs_melted
+            nsumbuf(4) = nspeeding_tickets
+            DO ik = 1, nclasses
+               nsumbuf(4+ik) = nbergs_calved_by_class(ik)
+            END DO
+            CALL mpp_sum( 'icbdia', nsumbuf(1:nclasses+4), nclasses+4 )
+            !
+            nbergs_end        = nsumbuf(1)
+            nbergs_calved     = nsumbuf(2)
+            nbergs_melted     = nsumbuf(3)
+            nspeeding_tickets = nsumbuf(4)
+            DO ik = 1,nclasses
+               nbergs_calved_by_class(ik)= nsumbuf(4+ik)
+            END DO
+            !
+         ENDIF
+         !
+         CALL report_state  ( 'stored ice','kg','',stored_start,'',stored_end,'')
+         CALL report_state  ( 'floating','kg','',floating_mass_start,'',floating_mass_end,'',nbergs_end )
+         CALL report_state  ( 'icebergs','kg','',bergs_mass_start,'',bergs_mass_end,'')
+         CALL report_state  ( 'bits','kg','',bits_mass_start,'',bits_mass_end,'')
+         CALL report_istate ( 'berg #','',nbergs_start,'',nbergs_end,'')
+         CALL report_ibudget( 'berg #','calved',nbergs_calved, &
+            &                          'melted',nbergs_melted, &
+            &                          '#',nbergs_start,nbergs_end)
+         CALL report_budget( 'stored mass','kg','calving used',calving_used_net, &
+            &                              'bergs',calving_to_bergs_net, &
+            &                              'stored mass',stored_start,stored_end)
+         CALL report_budget( 'floating mass','kg','calving used',calving_to_bergs_net, &
+            &                                'bergs',melt_net, &
+            &                                'stored mass',floating_mass_start,floating_mass_end)
+         CALL report_budget( 'berg mass','kg','calving',calving_to_bergs_net, &
+            &                                 'melt+eros',berg_melt_net, &
+            &                                 'berg mass',bergs_mass_start,bergs_mass_end)
+         CALL report_budget( 'bits mass','kg','eros used',bits_src_net, &
+            &                                 'bergs',bits_melt_net, &
+            &                                 'stored mass',bits_mass_start,bits_mass_end)
+         CALL report_budget( 'net mass','kg','recvd',calving_rcv_net, &
+            &                                'rtrnd',calving_ret_net, &
+            &                                'net mass',stored_start+floating_mass_start, &
+            &                                           stored_end+floating_mass_end)
+         CALL report_consistant( 'iceberg mass','kg','gridded',zgrdd_berg_mass,'bergs',bergs_mass_end)
+         CALL report_consistant( 'bits mass','kg','gridded',zgrdd_bits_mass,'bits',bits_mass_end)
+         CALL report_state( 'net heat','J','',stored_heat_start+floating_heat_start,'', &
+            &                                 stored_heat_end+floating_heat_end,'')
+         CALL report_state( 'stored heat','J','',stored_heat_start,'',stored_heat_end,'')
+         CALL report_state( 'floating heat','J','',floating_heat_start,'',floating_heat_end,'')
+         CALL report_budget( 'net heat','J','net heat',calving_src_heat_net, &
+            &                               'net heat',calving_out_heat_net, &
+            &                               'net heat',stored_heat_start+floating_heat_start, &
+            &                                          stored_heat_end+floating_heat_end)
+         CALL report_budget( 'stored heat','J','calving used',calving_src_heat_used_net, &
+            &                                  'bergs',heat_to_bergs_net, &
+            &                                  'net heat',stored_heat_start,stored_heat_end)
+         CALL report_budget( 'flting heat','J','calved',heat_to_bergs_net, &
+            &                                  'melt',heat_to_ocean_net, &
+            &                                  'net heat',floating_heat_start,floating_heat_end)
+         IF (nn_verbose_level >= 1) THEN
+            CALL report_consistant( 'top interface','kg','from SIS',calving_src_net, &
+               &                    'received',calving_rcv_net)
+            CALL report_consistant( 'bot interface','kg','sent',calving_out_net, &
+               &                    'returned',calving_ret_net)
+         ENDIF
+         IF (nn_verbose_level > 0) THEN
+            WRITE( numicb, '("calved by class = ",i6,20(",",i6))') (nbergs_calved_by_class(ik),ik=1,nclasses)
+            IF( nspeeding_tickets > 0 )   WRITE( numicb, '("speeding tickets issued = ",i6)') nspeeding_tickets
+         ENDIF
+         !
+         nbergs_start              = nbergs_end
+         stored_start              = stored_end
+         nbergs_melted             = 0
+         nbergs_calved             = 0
+         nbergs_calved_by_class(:) = 0
+         nspeeding_tickets         = 0
+         stored_heat_start         = stored_heat_end
+         floating_heat_start       = floating_heat_end
+         floating_mass_start       = floating_mass_end
+         bergs_mass_start          = bergs_mass_end
+         bits_mass_start           = bits_mass_end
+         calving_used_net          = 0._wp
+         calving_to_bergs_net      = 0._wp
+         heat_to_bergs_net         = 0._wp
+         heat_to_ocean_net         = 0._wp
+         calving_rcv_net           = 0._wp
+         calving_ret_net           = 0._wp
+         calving_src_net           = 0._wp
+         calving_out_net           = 0._wp
+         calving_src_heat_net      = 0._wp
+         calving_src_heat_used_net = 0._wp
+         calving_out_heat_net      = 0._wp
+         melt_net                  = 0._wp
+         berg_melt_net             = 0._wp
+         bits_melt_net             = 0._wp
+         bits_src_net              = 0._wp
+      ENDIF
+      !
+   END SUBROUTINE icb_dia
+
+
+   SUBROUTINE icb_dia_step
+      !!----------------------------------------------------------------------
+      !! things to reset at the beginning of each timestep
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+      berg_melt   (:,:)   = 0._wp
+      berg_melt_hcflx(:,:)   = 0._wp
+      berg_melt_qlat(:,:)   = 0._wp
+      buoy_melt   (:,:)   = 0._wp
+      eros_melt   (:,:)   = 0._wp
+      conv_melt   (:,:)   = 0._wp
+      bits_src    (:,:)   = 0._wp
+      bits_melt   (:,:)   = 0._wp
+      bits_mass   (:,:)   = 0._wp
+      berg_mass   (:,:)   = 0._wp
+      virtual_area(:,:)   = 0._wp
+      real_calving(:,:,:) = 0._wp
+      !
+   END SUBROUTINE icb_dia_step
+
+
+   SUBROUTINE icb_dia_put
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN            !!gm useless iom will control whether it is output or not
+      !
+      CALL iom_put( "berg_melt"        , berg_melt   (:,:)   )   ! Melt rate of icebergs                     [kg/m2/s]
+      !! NB. The berg_melt_hcflx field is currently always zero - see comment in icbthm.F90
+      CALL iom_put( "berg_melt_hcflx"  , berg_melt_hcflx(:,:))   ! Heat flux to ocean due to heat content of melting icebergs [J/m2/s]
+      CALL iom_put( "berg_melt_qlat"   , berg_melt_qlat(:,:) )   ! Heat flux to ocean due to latent heat of melting icebergs [J/m2/s]
+      CALL iom_put( "berg_buoy_melt"   , buoy_melt   (:,:)   )   ! Buoyancy component of iceberg melt rate   [kg/m2/s]
+      CALL iom_put( "berg_eros_melt"   , eros_melt   (:,:)   )   ! Erosion component of iceberg melt rate    [kg/m2/s]
+      CALL iom_put( "berg_conv_melt"   , conv_melt   (:,:)   )   ! Convective component of iceberg melt rate [kg/m2/s]
+      CALL iom_put( "berg_virtual_area", virtual_area(:,:)   )   ! Virtual coverage by icebergs              [m2]
+      CALL iom_put( "bits_src"         , bits_src    (:,:)   )   ! Mass source of bergy bits                 [kg/m2/s]
+      CALL iom_put( "bits_melt"        , bits_melt   (:,:)   )   ! Melt rate of bergy bits                   [kg/m2/s]
+      CALL iom_put( "bits_mass"        , bits_mass   (:,:)   )   ! Bergy bit density field                   [kg/m2]
+      CALL iom_put( "berg_mass"        , berg_mass   (:,:)   )   ! Iceberg density field                     [kg/m2]
+      CALL iom_put( "berg_real_calving", real_calving(:,:,:) )   ! Calving into iceberg class                [kg/s]
+      !
+   END SUBROUTINE icb_dia_put
+
+
+   SUBROUTINE icb_dia_calve( ki, kj, kn, pcalved, pheated )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in)  ::   ki, kj, kn
+      REAL(wp), INTENT(in)  ::   pcalved
+      REAL(wp), INTENT(in)  ::   pheated
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT. ln_bergdia ) RETURN
+      real_calving(ki,kj,kn)     = real_calving(ki,kj,kn) + pcalved / berg_dt
+      nbergs_calved              = nbergs_calved              + 1
+      nbergs_calved_by_class(kn) = nbergs_calved_by_class(kn) + 1
+      calving_to_bergs_net       = calving_to_bergs_net + pcalved
+      heat_to_bergs_net          = heat_to_bergs_net    + pheated
+      !
+   END SUBROUTINE icb_dia_calve
+
+
+   SUBROUTINE icb_dia_income( kt,  pcalving_used, pheat_used )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER ,                 INTENT(in)  :: kt
+      REAL(wp),                 INTENT(in)  :: pcalving_used
+      REAL(wp), DIMENSION(:,:), INTENT(in)  :: pheat_used
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+      !
+      IF( kt == nit000 ) THEN
+         stored_start = SUM( berg_grid%stored_ice(:,:,:) )
+         CALL mpp_sum( 'icbdia', stored_start )
+         !
+         stored_heat_start = SUM( berg_grid%stored_heat(:,:) )
+         CALL mpp_sum( 'icbdia', stored_heat_start )
+         IF (nn_verbose_level > 0) THEN
+            WRITE(numicb,'(a,es13.6,a)')   'icb_dia_income: initial stored mass=',stored_start,' kg'
+            WRITE(numicb,'(a,es13.6,a)')   'icb_dia_income: initial stored heat=',stored_heat_start,' J'
+         ENDIF
+      ENDIF
+      !
+      calving_rcv_net = calving_rcv_net + SUM( berg_grid%calving(:,:) ) * berg_dt
+      calving_src_net = calving_rcv_net
+      calving_src_heat_net = calving_src_heat_net +  &
+         &                      SUM( berg_grid%calving_hflx(:,:) * e1e2t(:,:) ) * berg_dt   ! Units of J
+      calving_used_net = calving_used_net + pcalving_used * berg_dt
+      calving_src_heat_used_net = calving_src_heat_used_net + SUM( pheat_used(:,:) )
+      !
+   END SUBROUTINE icb_dia_income
+
+
+   SUBROUTINE icb_dia_size(ki, kj, pWn, pLn, pAbits,   &
+      &                    pmass_scale, pMnew, pnMbits, pz1_e1e2)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in) ::   ki, kj
+      REAL(wp), INTENT(in) ::   pWn, pLn, pAbits, pmass_scale, pMnew, pnMbits, pz1_e1e2
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+      virtual_area(ki,kj) = virtual_area(ki,kj) + ( pWn * pLn + pAbits ) * pmass_scale      ! m^2
+      berg_mass(ki,kj)    = berg_mass(ki,kj) + pMnew * pz1_e1e2                             ! kg/m2
+      bits_mass(ki,kj)    = bits_mass(ki,kj) + pnMbits * pz1_e1e2                           ! kg/m2
+      !
+   END SUBROUTINE icb_dia_size
+
+
+   SUBROUTINE icb_dia_speed()
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+      nspeeding_tickets = nspeeding_tickets + 1
+      !
+   END SUBROUTINE icb_dia_speed
+
+
+   SUBROUTINE icb_dia_melt(ki, kj, pmnew, pheat_hcflux, pheat_latent, pmass_scale,     &
+      &                    pdM, pdMbitsE, pdMbitsM, pdMb, pdMe,   &
+      &                    pdMv, pz1_dt_e1e2 )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in) ::   ki, kj
+      REAL(wp), INTENT(in) ::   pmnew, pheat_hcflux, pheat_latent, pmass_scale
+      REAL(wp), INTENT(in) ::   pdM, pdMbitsE, pdMbitsM, pdMb, pdMe, pdMv, pz1_dt_e1e2
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ln_bergdia )   RETURN
+      !
+      berg_melt (ki,kj) = berg_melt (ki,kj) + pdM      * pz1_dt_e1e2   ! kg/m2/s
+      berg_melt_hcflx (ki,kj) = berg_melt_hcflx (ki,kj) + pheat_hcflux * pz1_dt_e1e2   ! J/m2/s
+      berg_melt_qlat (ki,kj) = berg_melt_qlat (ki,kj) + pheat_latent * pz1_dt_e1e2   ! J/m2/s
+      bits_src  (ki,kj) = bits_src  (ki,kj) + pdMbitsE * pz1_dt_e1e2   ! mass flux into bergy bitskg/m2/s
+      bits_melt (ki,kj) = bits_melt (ki,kj) + pdMbitsM * pz1_dt_e1e2   ! melt rate of bergy bits kg/m2/s
+      buoy_melt (ki,kj) = buoy_melt (ki,kj) + pdMb     * pz1_dt_e1e2   ! kg/m2/s
+      eros_melt (ki,kj) = eros_melt (ki,kj) + pdMe     * pz1_dt_e1e2   ! erosion rate kg/m2/s
+      conv_melt (ki,kj) = conv_melt (ki,kj) + pdMv     * pz1_dt_e1e2   ! kg/m2/s
+      heat_to_ocean_net = heat_to_ocean_net + (pheat_hcflux + pheat_latent) * pmass_scale * berg_dt         ! J
+      IF( pmnew <= 0._wp ) nbergs_melted = nbergs_melted + 1                        ! Delete the berg if completely melted
+      !
+   END SUBROUTINE icb_dia_melt
+
+
+   SUBROUTINE report_state( cd_budgetstr, cd_budgetunits, cd_startstr, pstartval, cd_endstr,   &
+      &                     pendval, cd_delstr, kbergs )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER*(*), INTENT(in)           :: cd_budgetstr, cd_budgetunits, cd_startstr, cd_endstr, cd_delstr
+      REAL(wp),      INTENT(in)           :: pstartval, pendval
+      INTEGER,       INTENT(in), OPTIONAL :: kbergs
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      IF( PRESENT(kbergs) ) THEN
+         WRITE(numicb,100) cd_budgetstr // ' state:',                                    &
+            &              cd_startstr  // ' start',  pstartval,         cd_budgetunits, &
+            &              cd_endstr    // ' end',    pendval,           cd_budgetunits, &
+            &              'Delta '     // cd_delstr, pendval-pstartval, cd_budgetunits, &
+            &              '# of bergs', kbergs
+      ELSE
+         WRITE(numicb,100) cd_budgetstr // ' state:',                                   &
+            &              cd_startstr  // ' start', pstartval,         cd_budgetunits, &
+            &              cd_endstr    // ' end',   pendval,           cd_budgetunits, &
+            &              cd_delstr    // 'Delta',  pendval-pstartval, cd_budgetunits
+      ENDIF
+100   FORMAT(a19,3(a18,"=",es14.7,x,a2,:,","),a12,i8)
+      !
+   END SUBROUTINE report_state
+
+
+   SUBROUTINE report_consistant( cd_budgetstr, cd_budgetunits, cd_startstr, pstartval, cd_endstr, pendval)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER*(*), INTENT(in) :: cd_budgetstr, cd_budgetunits, cd_startstr, cd_endstr
+      REAL(wp),      INTENT(in) :: pstartval, pendval
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      WRITE(numicb,200) cd_budgetstr // ' check:',                 &
+         &              cd_startstr,    pstartval, cd_budgetunits, &
+         &              cd_endstr,      pendval,   cd_budgetunits, &
+         &              'error',        (pendval-pstartval)/((pendval+pstartval)+1e-30), 'nd'
+200   FORMAT(a19,10(a18,"=",es14.7,x,a2,:,","))
+      !
+   END SUBROUTINE report_consistant
+
+
+   SUBROUTINE report_budget( cd_budgetstr, cd_budgetunits, cd_instr, pinval, cd_outstr,   &
+      &                      poutval, cd_delstr, pstartval, pendval)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER*(*), INTENT(in) :: cd_budgetstr, cd_budgetunits, cd_instr, cd_outstr, cd_delstr
+      REAL(wp),      INTENT(in) :: pinval, poutval, pstartval, pendval
+      !
+      REAL(wp) ::   zval
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      zval = ( ( pendval - pstartval ) - ( pinval - poutval ) ) /   &
+         &   MAX( 1.e-30, MAX( ABS( pendval - pstartval ) , ABS( pinval - poutval ) ) )
+         !
+      WRITE(numicb,200) cd_budgetstr // ' budget:', &
+         &              cd_instr     // ' in',      pinval,         cd_budgetunits, &
+         &              cd_outstr    // ' out',     poutval,        cd_budgetunits, &
+         &              'Delta '     // cd_delstr,  pinval-poutval, cd_budgetunits, &
+         &              'error',        zval,                       'nd'
+  200 FORMAT(a19,3(a18,"=",es14.7,x,a2,:,","),a8,"=",es10.3,x,a2)
+      !
+   END SUBROUTINE report_budget
+
+
+   SUBROUTINE report_istate( cd_budgetstr, cd_startstr, pstartval, cd_endstr, pendval, cd_delstr)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER*(*), INTENT(in) ::   cd_budgetstr, cd_startstr, cd_endstr, cd_delstr
+      INTEGER      , INTENT(in) ::   pstartval, pendval
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      WRITE(numicb,100) cd_budgetstr // ' state:',           &
+         &              cd_startstr  // ' start', pstartval, &
+         &              cd_endstr    // ' end',   pendval,   &
+         &              cd_delstr    // 'Delta',  pendval-pstartval
+  100 FORMAT(a19,3(a18,"=",i14,x,:,","))
+      !
+   END SUBROUTINE report_istate
+
+
+   SUBROUTINE report_ibudget( cd_budgetstr, cd_instr, pinval, cd_outstr, poutval,   &
+      &                       cd_delstr, pstartval, pendval)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER*(*), INTENT(in) :: cd_budgetstr, cd_instr, cd_outstr, cd_delstr
+      INTEGER,       INTENT(in) :: pinval, poutval, pstartval, pendval
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      WRITE(numicb,200) cd_budgetstr // ' budget:', &
+         &              cd_instr     // ' in',      pinval, &
+         &              cd_outstr    // ' out',     poutval, &
+         &              'Delta '     // cd_delstr,  pinval-poutval, &
+         &              'error',                    ( ( pendval - pstartval ) - ( pinval - poutval ) )
+200   FORMAT(a19,10(a18,"=",i14,x,:,","))
+      !
+   END SUBROUTINE report_ibudget
+
+   !!======================================================================
+END MODULE icbdia
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbdyn.F90	(revision 14097)
@@ -0,0 +1,383 @@
+MODULE icbdyn
+   !!======================================================================
+   !!                       ***  MODULE  icbdyn  ***
+   !! Iceberg:  time stepping routine for iceberg tracking
+   !!======================================================================
+   !! History :  3.3  !  2010-01  (Martin&Adcroft)  Original code
+   !!             -   !  2011-03  (Madec)  Part conversion to NEMO form
+   !!             -   !                    Removal of mapping from another grid
+   !!             -   !  2011-04  (Alderson)  Split into separate modules
+   !!             -   !  2011-05  (Alderson)  Replace broken grounding routine with one of
+   !!             -   !                       Gurvan's suggestions (just like the broken one)
+   !!----------------------------------------------------------------------
+   USE par_oce        ! NEMO parameters
+   USE dom_oce        ! NEMO ocean domain
+   USE phycst         ! NEMO physical constants
+   !
+   USE icb_oce        ! define iceberg arrays
+   USE icbutl         ! iceberg utility routines
+   USE icbdia         ! iceberg budget routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_dyn  ! routine called in icbstp.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_dyn( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_dyn  ***
+      !!
+      !! ** Purpose :   iceberg evolution.
+      !!
+      !! ** Method  : - See Martin & Adcroft, Ocean Modelling 34, 2010
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   !
+      !
+      LOGICAL  ::   ll_bounced
+      REAL(wp) ::   zuvel1 , zvvel1 , zu1, zv1, zax1, zay1, zxi1 , zyj1
+      REAL(wp) ::   zuvel2 , zvvel2 , zu2, zv2, zax2, zay2, zxi2 , zyj2
+      REAL(wp) ::   zuvel3 , zvvel3 , zu3, zv3, zax3, zay3, zxi3 , zyj3
+      REAL(wp) ::   zuvel4 , zvvel4 , zu4, zv4, zax4, zay4, zxi4 , zyj4
+      REAL(wp) ::   zuvel_n, zvvel_n, zxi_n   , zyj_n
+      REAL(wp) ::   zdt, zdt_2, zdt_6, ze1, ze2
+      TYPE(iceberg), POINTER ::   berg
+      TYPE(point)  , POINTER ::   pt
+      !!----------------------------------------------------------------------
+      !
+      ! 4th order Runge-Kutta to solve:   d/dt X = V,  d/dt V = A
+      !                    with I.C.'s:   X=X1 and V=V1
+      !
+      !                                    ; A1=A(X1,V1)
+      !  X2 = X1+dt/2*V1 ; V2 = V1+dt/2*A1 ; A2=A(X2,V2)
+      !  X3 = X1+dt/2*V2 ; V3 = V1+dt/2*A2 ; A3=A(X3,V3)
+      !  X4 = X1+  dt*V3 ; V4 = V1+  dt*A3 ; A4=A(X4,V4)
+      !
+      !  Xn = X1+dt*(V1+2*V2+2*V3+V4)/6
+      !  Vn = V1+dt*(A1+2*A2+2*A3+A4)/6
+
+      ! time steps
+      zdt   = berg_dt
+      zdt_2 = zdt * 0.5_wp
+      zdt_6 = zdt / 6._wp
+
+      berg => first_berg                    ! start from the first berg
+      !
+      DO WHILE ( ASSOCIATED(berg) )          !==  loop over all bergs  ==!
+         !
+         pt => berg%current_point
+
+         ll_bounced = .FALSE.
+
+
+         ! STEP 1 !
+         ! ====== !
+         zxi1 = pt%xi   ;   zuvel1 = pt%uvel     !**   X1 in (i,j)  ;  V1 in m/s
+         zyj1 = pt%yj   ;   zvvel1 = pt%vvel
+
+
+         !                                         !**   A1 = A(X1,V1)
+         CALL icb_accel( berg , zxi1, ze1, zuvel1, zuvel1, zax1,     &
+            &                   zyj1, ze2, zvvel1, zvvel1, zay1, zdt_2 )
+         !
+         zu1 = zuvel1 / ze1                           !**   V1 in d(i,j)/dt
+         zv1 = zvvel1 / ze2
+
+         ! STEP 2 !
+         ! ====== !
+         !                                         !**   X2 = X1+dt/2*V1   ;   V2 = V1+dt/2*A1
+         ! position using di/dt & djdt   !   V2  in m/s
+         zxi2 = zxi1 + zdt_2 * zu1          ;   zuvel2 = zuvel1 + zdt_2 * zax1
+         zyj2 = zyj1 + zdt_2 * zv1          ;   zvvel2 = zvvel1 + zdt_2 * zay1
+         !
+         CALL icb_ground( zxi2, zxi1, zu1,   &
+            &             zyj2, zyj1, zv1, ll_bounced )
+
+         !                                         !**   A2 = A(X2,V2)
+         CALL icb_accel( berg , zxi2, ze1, zuvel2, zuvel1, zax2,    &
+            &                   zyj2, ze2, zvvel2, zvvel1, zay2, zdt_2 )
+         !
+         zu2 = zuvel2 / ze1                           !**   V2 in d(i,j)/dt
+         zv2 = zvvel2 / ze2
+         !
+         ! STEP 3 !
+         ! ====== !
+         !                                         !**  X3 = X1+dt/2*V2  ;   V3 = V1+dt/2*A2; A3=A(X3)
+         zxi3  = zxi1  + zdt_2 * zu2   ;   zuvel3 = zuvel1 + zdt_2 * zax2
+         zyj3  = zyj1  + zdt_2 * zv2   ;   zvvel3 = zvvel1 + zdt_2 * zay2
+         !
+         CALL icb_ground( zxi3, zxi1, zu3,   &
+            &                zyj3, zyj1, zv3, ll_bounced )
+
+         !                                         !**   A3 = A(X3,V3)
+         CALL icb_accel( berg , zxi3, ze1, zuvel3, zuvel1, zax3,    &
+            &                   zyj3, ze2, zvvel3, zvvel1, zay3, zdt )
+         !
+         zu3 = zuvel3 / ze1                           !**   V3 in d(i,j)/dt
+         zv3 = zvvel3 / ze2
+
+         ! STEP 4 !
+         ! ====== !
+         !                                         !**   X4 = X1+dt*V3   ;   V4 = V1+dt*A3
+         zxi4 = zxi1 + zdt * zu3   ;   zuvel4 = zuvel1 + zdt * zax3
+         zyj4 = zyj1 + zdt * zv3   ;   zvvel4 = zvvel1 + zdt * zay3
+
+         CALL icb_ground( zxi4, zxi1, zu4,   &
+            &             zyj4, zyj1, zv4, ll_bounced )
+
+         !                                         !**   A4 = A(X4,V4)
+         CALL icb_accel( berg , zxi4, ze1, zuvel4, zuvel1, zax4,    &
+            &                   zyj4, ze2, zvvel4, zvvel1, zay4, zdt )
+
+         zu4 = zuvel4 / ze1                           !**   V4 in d(i,j)/dt
+         zv4 = zvvel4 / ze2
+
+         ! FINAL STEP !
+         ! ========== !
+         !                                         !**   Xn = X1+dt*(V1+2*V2+2*V3+V4)/6
+         !                                         !**   Vn = V1+dt*(A1+2*A2+2*A3+A4)/6
+         zxi_n   = pt%xi   + zdt_6 * (  zu1  + 2.*(zu2  + zu3 ) + zu4  )
+         zyj_n   = pt%yj   + zdt_6 * (  zv1  + 2.*(zv2  + zv3 ) + zv4  )
+         zuvel_n = pt%uvel + zdt_6 * (  zax1 + 2.*(zax2 + zax3) + zax4 )
+         zvvel_n = pt%vvel + zdt_6 * (  zay1 + 2.*(zay2 + zay3) + zay4 )
+
+         CALL icb_ground( zxi_n, zxi1, zuvel_n,   &
+            &             zyj_n, zyj1, zvvel_n, ll_bounced )
+
+         pt%uvel = zuvel_n                        !** save in berg structure
+         pt%vvel = zvvel_n
+         pt%xi   = zxi_n
+         pt%yj   = zyj_n
+
+         ! update actual position
+         pt%lon  = icb_utl_bilin_x(glamt, pt%xi, pt%yj )
+         pt%lat  = icb_utl_bilin(gphit, pt%xi, pt%yj, 'T' )
+
+         berg => berg%next                         ! switch to the next berg
+         !
+      END DO                                  !==  end loop over all bergs  ==!
+      !
+   END SUBROUTINE icb_dyn
+
+
+   SUBROUTINE icb_ground( pi, pi0, pu,   &
+      &                   pj, pj0, pv, ld_bounced )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_ground  ***
+      !!
+      !! ** Purpose :   iceberg grounding.
+      !!
+      !! ** Method  : - adjust velocity and then put iceberg back to start position
+      !!                NB two possibilities available one of which is hard-coded here
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(inout) ::   pi , pj      ! current iceberg position
+      REAL(wp), INTENT(in   ) ::   pi0, pj0     ! previous iceberg position
+      REAL(wp), INTENT(inout) ::   pu  , pv     ! current iceberg velocities
+      LOGICAL , INTENT(  out) ::   ld_bounced   ! bounced indicator
+      !
+      INTEGER  ::   ii, ii0
+      INTEGER  ::   ij, ij0
+      INTEGER  ::   ibounce_method
+      !!----------------------------------------------------------------------
+      !
+      ld_bounced = .FALSE.
+      !
+      ii0 = INT( pi0+0.5 )   ;   ij0 = INT( pj0+0.5 )       ! initial gridpoint position (T-cell)
+      ii  = INT( pi +0.5 )   ;   ij  = INT( pj +0.5 )       ! current     -         -
+      !
+      IF( ii == ii0  .AND.  ij == ij0  )   RETURN           ! berg remains in the same cell
+      !
+      ! map into current processor
+      ii0 = mi1( ii0 )
+      ij0 = mj1( ij0 )
+      ii  = mi1( ii  )
+      ij  = mj1( ij  )
+      !
+      IF(  tmask(ii,ij,1)  /=   0._wp  )   RETURN           ! berg reach a new t-cell, but an ocean one
+      !
+      ! From here, berg have reach land: treat grounding/bouncing
+      ! -------------------------------
+      ld_bounced = .TRUE.
+
+      !! not obvious what should happen now
+      !! if berg tries to enter a land box, the only location we can return it to is the start 
+      !! position (pi0,pj0), since it has to be in a wet box to do any melting;
+      !! first option is simply to set whole velocity to zero and move back to start point
+      !! second option (suggested by gm) is only to set the velocity component in the (i,j) direction
+      !! of travel to zero; at a coastal boundary this has the effect of sliding the berg along the coast
+
+      ibounce_method = 2
+      SELECT CASE ( ibounce_method )
+      CASE ( 1 )
+         pi = pi0
+         pj = pj0
+         pu = 0._wp
+         pv = 0._wp
+      CASE ( 2 )
+         IF( ii0 /= ii ) THEN
+            pi = pi0                   ! return back to the initial position
+            pu = 0._wp                 ! zeroing of velocity in the direction of the grounding
+         ENDIF
+         IF( ij0 /= ij ) THEN
+            pj = pj0                   ! return back to the initial position
+            pv = 0._wp                 ! zeroing of velocity in the direction of the grounding
+         ENDIF
+      END SELECT
+      !
+   END SUBROUTINE icb_ground
+
+
+   SUBROUTINE icb_accel( berg , pxi, pe1, puvel, puvel0, pax,                &
+      &                         pyj, pe2, pvvel, pvvel0, pay, pdt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_accel  ***
+      !!
+      !! ** Purpose :   compute the iceberg acceleration.
+      !!
+      !! ** Method  : - sum the terms in the momentum budget
+      !!----------------------------------------------------------------------
+      TYPE(iceberg ), POINTER, INTENT(in   ) ::   berg             ! berg
+      REAL(wp)               , INTENT(in   ) ::   pxi   , pyj      ! berg position in (i,j) referential
+      REAL(wp)               , INTENT(in   ) ::   puvel , pvvel    ! berg velocity [m/s]
+      REAL(wp)               , INTENT(in   ) ::   puvel0, pvvel0   ! initial berg velocity [m/s]
+      REAL(wp)               , INTENT(  out) ::   pe1, pe2         ! horizontal scale factor at (xi,yj)
+      REAL(wp)               , INTENT(inout) ::   pax, pay         ! berg acceleration
+      REAL(wp)               , INTENT(in   ) ::   pdt              ! berg time step
+      !
+      REAL(wp), PARAMETER ::   pp_alpha     = 0._wp      !
+      REAL(wp), PARAMETER ::   pp_beta      = 1._wp      !
+      REAL(wp), PARAMETER ::   pp_vel_lim   =15._wp      ! max allowed berg speed
+      REAL(wp), PARAMETER ::   pp_accel_lim = 1.e-2_wp   ! max allowed berg acceleration
+      REAL(wp), PARAMETER ::   pp_Cr0       = 0.06_wp    !
+      !
+      INTEGER  ::   itloop
+      REAL(wp) ::   zuo, zui, zua, zuwave, zssh_x, zsst, zcn, zhi, zsss
+      REAL(wp) ::   zvo, zvi, zva, zvwave, zssh_y
+      REAL(wp) ::   zff, zT, zD, zW, zL, zM, zF
+      REAL(wp) ::   zdrag_ocn, zdrag_atm, zdrag_ice, zwave_rad
+      REAL(wp) ::   z_ocn, z_atm, z_ice
+      REAL(wp) ::   zampl, zwmod, zCr, zLwavelength, zLcutoff, zLtop
+      REAL(wp) ::   zlambda, zdetA, zA11, zA12, zaxe, zaye, zD_hi
+      REAL(wp) ::   zuveln, zvveln, zus, zvs, zspeed, zloc_dx, zspeed_new
+      !!----------------------------------------------------------------------
+
+      ! Interpolate gridded fields to berg
+      nknberg = berg%number(1)
+      CALL icb_utl_interp( pxi, pe1, zuo, zui, zua, zssh_x,                     &
+         &                 pyj, pe2, zvo, zvi, zva, zssh_y, zsst, zcn, zhi, zff, zsss )
+
+      zM = berg%current_point%mass
+      zT = berg%current_point%thickness               ! total thickness
+      zD = ( rn_rho_bergs / pp_rho_seawater ) * zT    ! draught (keel depth)
+      zF = zT - zD                                    ! freeboard
+      zW = berg%current_point%width
+      zL = berg%current_point%length
+
+      zhi   = MIN( zhi   , zD    )
+      zD_hi = MAX( 0._wp, zD-zhi )
+
+      ! Wave radiation
+      zuwave = zua - zuo   ;   zvwave = zva - zvo     ! Use wind speed rel. to ocean for wave model
+      zwmod  = zuwave*zuwave + zvwave*zvwave          ! The wave amplitude and length depend on the  current;
+      !                                               ! wind speed relative to the ocean. Actually wmod is wmod**2 here.
+      zampl        = 0.5 * 0.02025 * zwmod            ! This is "a", the wave amplitude
+      zLwavelength =       0.32    * zwmod            ! Surface wave length fitted to data in table at
+      !                                               ! http://www4.ncsu.edu/eos/users/c/ceknowle/public/chapter10/part2.html
+      zLcutoff     = 0.125 * zLwavelength
+      zLtop        = 0.25  * zLwavelength
+      zCr          = pp_Cr0 * MIN(  MAX( 0., (zL-zLcutoff) / ((zLtop-zLcutoff)+1.e-30)) , 1.)  ! Wave radiation coefficient
+      !                                               ! fitted to graph from Carrieres et al.,  POAC Drift Model.
+      zwave_rad    = 0.5 * pp_rho_seawater / zM * zCr * grav * zampl * MIN( zampl,zF ) * (2.*zW*zL) / (zW+zL)
+      zwmod        = SQRT( zua*zua + zva*zva )        ! Wind speed
+      IF( zwmod /= 0._wp ) THEN
+         zuwave = zua/zwmod   ! Wave radiation force acts in wind direction ...       !!gm  this should be the wind rel. to ocean ?
+         zvwave = zva/zwmod
+      ELSE
+         zuwave = 0.   ;    zvwave=0.   ;    zwave_rad=0. ! ... and only when wind is present.     !!gm  wave_rad=0. is useless
+      ENDIF
+
+      ! Weighted drag coefficients
+      z_ocn = pp_rho_seawater / zM * (0.5*pp_Cd_wv*zW*(zD_hi)+pp_Cd_wh*zW*zL)
+      z_atm = pp_rho_air      / zM * (0.5*pp_Cd_av*zW*zF     +pp_Cd_ah*zW*zL)
+      z_ice = pp_rho_ice      / zM * (0.5*pp_Cd_iv*zW*zhi              )
+      IF( abs(zui) + abs(zvi) == 0._wp )   z_ice = 0._wp
+
+      zuveln = puvel   ;   zvveln = pvvel ! Copy starting uvel, vvel
+      !
+      DO itloop = 1, 2  ! Iterate on drag coefficients
+         !
+         zus = 0.5 * ( zuveln + puvel )
+         zvs = 0.5 * ( zvveln + pvvel )
+         zdrag_ocn = z_ocn * SQRT( (zus-zuo)*(zus-zuo) + (zvs-zvo)*(zvs-zvo) )
+         zdrag_atm = z_atm * SQRT( (zus-zua)*(zus-zua) + (zvs-zva)*(zvs-zva) )
+         zdrag_ice = z_ice * SQRT( (zus-zui)*(zus-zui) + (zvs-zvi)*(zvs-zvi) )
+         !
+         ! Explicit accelerations
+         !zaxe= zff*pvvel -grav*zssh_x +zwave_rad*zuwave &
+         !    -zdrag_ocn*(puvel-zuo) -zdrag_atm*(puvel-zua) -zdrag_ice*(puvel-zui)
+         !zaye=-zff*puvel -grav*zssh_y +zwave_rad*zvwave &
+         !    -zdrag_ocn*(pvvel-zvo) -zdrag_atm*(pvvel-zva) -zdrag_ice*(pvvel-zvi)
+         zaxe = -grav * zssh_x + zwave_rad * zuwave
+         zaye = -grav * zssh_y + zwave_rad * zvwave
+         IF( pp_alpha > 0._wp ) THEN   ! If implicit, use time-level (n) rather than RK4 latest
+            zaxe = zaxe + zff*pvvel0
+            zaye = zaye - zff*puvel0
+         ELSE
+            zaxe = zaxe + zff*pvvel
+            zaye = zaye - zff*puvel
+         ENDIF
+         IF( pp_beta > 0._wp ) THEN    ! If implicit, use time-level (n) rather than RK4 latest
+            zaxe = zaxe - zdrag_ocn*(puvel0-zuo) - zdrag_atm*(puvel0-zua) -zdrag_ice*(puvel0-zui)
+            zaye = zaye - zdrag_ocn*(pvvel0-zvo) - zdrag_atm*(pvvel0-zva) -zdrag_ice*(pvvel0-zvi)
+         ELSE
+            zaxe = zaxe - zdrag_ocn*(puvel -zuo) - zdrag_atm*(puvel -zua) -zdrag_ice*(puvel -zui)
+            zaye = zaye - zdrag_ocn*(pvvel -zvo) - zdrag_atm*(pvvel -zva) -zdrag_ice*(pvvel -zvi)
+         ENDIF
+
+         ! Solve for implicit accelerations
+         IF( pp_alpha + pp_beta > 0._wp ) THEN
+            zlambda = zdrag_ocn + zdrag_atm + zdrag_ice
+            zA11    = 1._wp + pp_beta *pdt*zlambda
+            zA12    =         pp_alpha*pdt*zff
+            zdetA   = 1._wp / ( zA11*zA11 + zA12*zA12 )
+            pax     = zdetA * ( zA11*zaxe + zA12*zaye )
+            pay     = zdetA * ( zA11*zaye - zA12*zaxe )
+         ELSE
+            pax = zaxe   ;   pay = zaye
+         ENDIF
+
+         zuveln = puvel0 + pdt*pax
+         zvveln = pvvel0 + pdt*pay
+         !
+      END DO      ! itloop
+
+      IF( rn_speed_limit > 0._wp ) THEN       ! Limit speed of bergs based on a CFL criteria (if asked)
+         zspeed = SQRT( zuveln*zuveln + zvveln*zvveln )    ! Speed of berg
+         IF( zspeed > 0._wp ) THEN
+            zloc_dx = MIN( pe1, pe2 )                          ! minimum grid spacing
+            zspeed_new = zloc_dx / pdt * rn_speed_limit        ! Speed limit as a factor of dx / dt
+            IF( zspeed_new < zspeed ) THEN
+               zuveln = zuveln * ( zspeed_new / zspeed )        ! Scale velocity to reduce speed
+               zvveln = zvveln * ( zspeed_new / zspeed )        ! without changing the direction
+               CALL icb_dia_speed()
+            ENDIF
+         ENDIF
+      ENDIF
+      !                                      ! check the speed and acceleration limits
+      IF (nn_verbose_level > 0) THEN
+         IF( ABS( zuveln ) > pp_vel_lim   .OR. ABS( zvveln ) > pp_vel_lim   )   &
+            WRITE(numicb,'("pe=",i3,x,a)') narea,'Dump triggered by excessive velocity'
+         IF( ABS( pax    ) > pp_accel_lim .OR. ABS( pay    ) > pp_accel_lim )   &
+            WRITE(numicb,'("pe=",i3,x,a)') narea,'Dump triggered by excessive acceleration'
+      ENDIF
+      !
+   END SUBROUTINE icb_accel
+
+   !!======================================================================
+END MODULE icbdyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbini.F90	(revision 14097)
@@ -0,0 +1,498 @@
+MODULE icbini
+   !!======================================================================
+   !!                       ***  MODULE  icbini  ***
+   !! Icebergs:  initialise variables for iceberg tracking
+   !!======================================================================
+   !! History :   -   !  2010-01  (T. Martin & A. Adcroft)  Original code
+   !!            3.3  !  2011-03  (G. Madec)  Part conversion to NEMO form ; Removal of mapping from another grid
+   !!             -   !  2011-04  (S. Alderson)  Split into separate modules ; Restore restart routines
+   !!             -   !  2011-05  (S. Alderson)  generate_test_icebergs restored ; new forcing arrays with extra halo ;
+   !!             -   !                          north fold exchange arrays added
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   icb_init     : initialise icebergs
+   !!   icb_ini_gen  : generate test icebergs
+   !!   icb_nam      : read iceberg namelist
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE in_out_manager ! IO routines and numout in particular
+   USE lib_mpp        ! mpi library and lk_mpp in particular
+   USE sbc_oce        ! ocean  : surface boundary condition
+   USE sbc_ice        ! sea-ice: surface boundary condition
+   USE iom            ! IOM library
+   USE fldread        ! field read
+   USE lbclnk         ! lateral boundary condition - MPP link
+   !
+   USE icb_oce        ! define iceberg arrays
+   USE icbutl         ! iceberg utility routines
+   USE icbrst         ! iceberg restart routines
+   USE icbtrj         ! iceberg trajectory I/O routines
+   USE icbdia         ! iceberg budget routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_init  ! routine called in nemogcm.F90 module
+
+   CHARACTER(len=100)                                 ::   cn_dir = './'   !: Root directory for location of icb files
+   TYPE(FLD_N)                                        ::   sn_icb          !: information about the calving file to be read
+   TYPE(FLD), PUBLIC, ALLOCATABLE     , DIMENSION(:)  ::   sf_icb          !: structure: file information, fields read
+                                                                           !: used in icbini and icbstp
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_init( pdt, kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_init  ***
+      !!
+      !! ** Purpose :   iceberg initialization.
+      !!
+      !! ** Method  : - read the iceberg namelist
+      !!              - find non-overlapping processor interior since we can only
+      !!                have one instance of a particular iceberg
+      !!              - calculate the destinations for north fold exchanges
+      !!              - setup either test icebergs or calving file
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::   pdt   ! iceberg time-step (rdt*nn_fsbc)
+      INTEGER , INTENT(in) ::   kt    ! time step number
+      !
+      INTEGER ::   ji, jj, jn               ! dummy loop indices
+      INTEGER ::   i1, i2, i3               ! local integers
+      INTEGER ::   ii, inum, ivar           !   -       -
+      INTEGER ::   istat1, istat2, istat3   !   -       -
+      CHARACTER(len=300) ::   cl_sdist      ! local character
+      !!----------------------------------------------------------------------
+      !
+      CALL icb_nam               ! Read and print namelist parameters
+      !
+      IF( .NOT. ln_icebergs )   RETURN
+
+      !                          ! allocate gridded fields
+      IF( icb_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'icb_alloc : unable to allocate arrays' )
+      !
+      !                          ! initialised variable with extra haloes to zero
+      uo_e(:,:) = 0._wp   ;   vo_e(:,:) = 0._wp   ;
+      ua_e(:,:) = 0._wp   ;   va_e(:,:) = 0._wp   ;
+      ff_e(:,:) = 0._wp   ;   tt_e(:,:) = 0._wp   ;
+      fr_e(:,:) = 0._wp   ;   ss_e(:,:) = 0._wp   ;
+#if defined key_si3
+      hi_e(:,:) = 0._wp   ;
+      ui_e(:,:) = 0._wp   ;   vi_e(:,:) = 0._wp   ;
+#endif
+      ssh_e(:,:) = 0._wp  ; 
+      !
+      !                          ! open ascii output file or files for iceberg status information
+      !                          ! note that we choose to do this on all processors since we cannot
+      !                          ! predict where icebergs will be ahead of time
+      IF( nn_verbose_level > 0) THEN
+         CALL ctl_opn( numicb, 'icebergs.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+      ENDIF
+
+      ! set parameters (mostly from namelist)
+      !
+      berg_dt         = pdt
+      first_width (:) = SQRT(  rn_initial_mass(:) / ( rn_LoW_ratio * rn_rho_bergs * rn_initial_thickness(:) )  )
+      first_length(:) = rn_LoW_ratio * first_width(:)
+
+      berg_grid%calving      (:,:)   = 0._wp
+      berg_grid%calving_hflx (:,:)   = 0._wp
+      berg_grid%stored_heat  (:,:)   = 0._wp
+      berg_grid%floating_melt(:,:)   = 0._wp
+      berg_grid%maxclass     (:,:)   = nclasses
+      berg_grid%stored_ice   (:,:,:) = 0._wp
+      berg_grid%tmp          (:,:)   = 0._wp
+      src_calving            (:,:)   = 0._wp
+      src_calving_hflx       (:,:)   = 0._wp
+
+      !                          ! domain for icebergs
+      IF( lk_mpp .AND. jpni == 1 )   CALL ctl_stop( 'icbinit: having ONE processor in x currently does not work' )
+      ! NB: the issue here is simply that cyclic east-west boundary condition have not been coded in mpp case
+      ! for the north fold we work out which points communicate by asking
+      ! lbc_lnk to pass processor number (valid even in single processor case)
+      ! borrow src_calving arrays for this
+      !
+      ! pack i and j together using a scaling of a power of 10
+      nicbpack = 10000
+      IF( jpiglo >= nicbpack )   CALL ctl_stop( 'icbini: processor index packing failure' )
+      nicbfldproc(:) = -1
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            src_calving_hflx(ji,jj) = narea
+            src_calving     (ji,jj) = nicbpack * mjg(jj) + mig(ji)
+         END DO
+      END DO
+      CALL lbc_lnk( 'icbini', src_calving_hflx, 'T', 1._wp )
+      CALL lbc_lnk( 'icbini', src_calving     , 'T', 1._wp )
+
+      ! work out interior of processor from exchange array
+      ! first entry with narea for this processor is left hand interior index
+      ! last  entry                               is right hand interior index
+      jj = nlcj/2
+      nicbdi = -1
+      nicbei = -1
+      DO ji = 1, jpi
+         i3 = INT( src_calving(ji,jj) )
+         i2 = INT( i3/nicbpack )
+         i1 = i3 - i2*nicbpack
+         i3 = INT( src_calving_hflx(ji,jj) )
+         IF( i1 == mig(ji) .AND. i3 == narea ) THEN
+            IF( nicbdi < 0 ) THEN   ;   nicbdi = ji
+            ELSE                    ;   nicbei = ji
+            ENDIF
+         ENDIF
+      END DO
+      !
+      ! repeat for j direction
+      ji = nlci/2
+      nicbdj = -1
+      nicbej = -1
+      DO jj = 1, jpj
+         i3 = INT( src_calving(ji,jj) )
+         i2 = INT( i3/nicbpack )
+         i1 = i3 - i2*nicbpack
+         i3 = INT( src_calving_hflx(ji,jj) )
+         IF( i2 == mjg(jj) .AND. i3 == narea ) THEN
+            IF( nicbdj < 0 ) THEN   ;   nicbdj = jj
+            ELSE                    ;   nicbej = jj
+            ENDIF
+         ENDIF
+      END DO
+      !   
+      ! special for east-west boundary exchange we save the destination index
+      i1 = MAX( nicbdi-1, 1)
+      i3 = INT( src_calving(i1,nlcj/2) )
+      jj = INT( i3/nicbpack )
+      ricb_left = REAL( i3 - nicbpack*jj, wp )
+      i1 = MIN( nicbei+1, jpi )
+      i3 = INT( src_calving(i1,nlcj/2) )
+      jj = INT( i3/nicbpack )
+      ricb_right = REAL( i3 - nicbpack*jj, wp )
+      
+      ! north fold
+      IF( npolj > 0 ) THEN
+         !
+         ! icebergs in row nicbej+1 get passed across fold
+         nicbfldpts(:)  = INT( src_calving(:,nicbej+1) )
+         nicbflddest(:) = INT( src_calving_hflx(:,nicbej+1) )
+         !
+         ! work out list of unique processors to talk to
+         ! pack them into a fixed size array where empty slots are marked by a -1
+         DO ji = nicbdi, nicbei
+            ii = nicbflddest(ji)
+            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
+      !
+      IF( nn_verbose_level > 0) THEN
+         WRITE(numicb,*) 'processor ', narea
+         WRITE(numicb,*) 'jpi, jpj   ', jpi, jpj
+         WRITE(numicb,*) 'nldi, nlei ', nldi, nlei
+         WRITE(numicb,*) 'nldj, nlej ', nldj, nlej
+         WRITE(numicb,*) 'berg i interior ', nicbdi, nicbei
+         WRITE(numicb,*) 'berg j interior ', nicbdj, nicbej
+         WRITE(numicb,*) 'berg left       ', ricb_left
+         WRITE(numicb,*) 'berg right      ', ricb_right
+         jj = nlcj/2
+         WRITE(numicb,*) "central j line:"
+         WRITE(numicb,*) "i processor"
+         WRITE(numicb,*) (INT(src_calving_hflx(ji,jj)), ji=1,jpi)
+         WRITE(numicb,*) "i point"
+         WRITE(numicb,*) (INT(src_calving(ji,jj)), ji=1,jpi)
+         ji = nlci/2
+         WRITE(numicb,*) "central i line:"
+         WRITE(numicb,*) "j processor"
+         WRITE(numicb,*) (INT(src_calving_hflx(ji,jj)), jj=1,jpj)
+         WRITE(numicb,*) "j point"
+         WRITE(numicb,*) (INT(src_calving(ji,jj)), jj=1,jpj)
+         IF( npolj > 0 ) THEN
+            WRITE(numicb,*) 'north fold destination points '
+            WRITE(numicb,*) nicbfldpts
+            WRITE(numicb,*) 'north fold destination procs  '
+            WRITE(numicb,*) nicbflddest
+            WRITE(numicb,*) 'north fold destination proclist  '
+            WRITE(numicb,*) nicbfldproc
+         ENDIF
+         CALL flush(numicb)
+      ENDIF
+      
+      src_calving     (:,:) = 0._wp
+      src_calving_hflx(:,:) = 0._wp
+
+      ! definition of extended surface masked needed by icb_bilin_h
+      tmask_e(:,:) = 0._wp   ;   tmask_e(1:jpi,1:jpj) = tmask(:,:,1)
+      umask_e(:,:) = 0._wp   ;   umask_e(1:jpi,1:jpj) = umask(:,:,1)
+      vmask_e(:,:) = 0._wp   ;   vmask_e(1:jpi,1:jpj) = vmask(:,:,1)
+      CALL lbc_lnk_icb( 'icbini', tmask_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbini', umask_e, 'U', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbini', vmask_e, 'V', +1._wp, 1, 1 )
+      !
+      ! assign each new iceberg with a unique number constructed from the processor number
+      ! and incremented by the total number of processors
+      num_bergs(:) = 0
+      num_bergs(1) = narea - jpnij
+
+      ! when not generating test icebergs we need to setup calving file
+      IF( nn_test_icebergs < 0 .OR. ln_use_calving ) THEN
+         !
+         ! maximum distribution class array does not change in time so read it once
+         cl_sdist = TRIM( cn_dir )//TRIM( sn_icb%clname )
+         CALL iom_open ( cl_sdist, inum )                              ! open file
+         ivar = iom_varid( inum, 'maxclass', ldstop=.FALSE. )
+         IF( ivar > 0 ) THEN
+            CALL iom_get  ( inum, jpdom_data, 'maxclass', src_calving )   ! read the max distribution array
+            berg_grid%maxclass(:,:) = INT( src_calving )
+            src_calving(:,:) = 0._wp
+         ENDIF
+         CALL iom_close( inum )                                     ! close file
+         !
+         IF( nn_verbose_level > 0) THEN
+            WRITE(numicb,*)
+            WRITE(numicb,*) '          calving read in a file'
+         ENDIF
+         ALLOCATE( sf_icb(1), STAT=istat1 )         ! Create sf_icb structure (calving)
+         ALLOCATE( sf_icb(1)%fnow(jpi,jpj,1), STAT=istat2 )
+         ALLOCATE( sf_icb(1)%fdta(jpi,jpj,1,2), STAT=istat3 )
+         IF( istat1+istat2+istat3 > 0 ) THEN
+            CALL ctl_stop( 'sbc_icb: unable to allocate sf_icb structure' )   ;   RETURN
+         ENDIF
+         !                                          ! fill sf_icb with the namelist (sn_icb) and control print
+         CALL fld_fill( sf_icb, (/ sn_icb /), cn_dir, 'icb_init', 'read calving data', 'namicb' )
+         !
+      ENDIF
+
+      IF( .NOT.ln_rstart ) THEN
+         IF( nn_test_icebergs > 0 )   CALL icb_ini_gen()
+      ELSE
+         IF( nn_test_icebergs > 0 ) THEN
+            CALL icb_ini_gen()
+         ELSE
+            CALL icb_rst_read()
+            l_restarted_bergs = .TRUE.
+         ENDIF
+      ENDIF
+      !
+      IF( nn_sample_rate .GT. 0 ) CALL icb_trj_init( nitend )
+      !
+      CALL icb_dia_init()
+      !
+      IF( nn_verbose_level >= 2 )   CALL icb_utl_print('icb_init, initial status', nit000-1)
+      !
+   END SUBROUTINE icb_init
+
+
+   SUBROUTINE icb_ini_gen()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_ini_gen  ***
+      !!
+      !! ** Purpose :   iceberg generation
+      !!
+      !! ** Method  : - at each grid point of the test box supplied in the namelist
+      !!                generate an iceberg in one class determined by the value of
+      !!                parameter nn_test_icebergs
+      !!----------------------------------------------------------------------
+      INTEGER                         ::   ji, jj, ibergs
+      TYPE(iceberg)                   ::   localberg ! NOT a pointer but an actual local variable
+      TYPE(point)                     ::   localpt
+      INTEGER                         ::   iyr, imon, iday, ihr, imin, isec
+      INTEGER                         ::   iberg
+      !!----------------------------------------------------------------------
+
+      ! For convenience
+      iberg = nn_test_icebergs
+
+      ! call get_date(Time, iyr, imon, iday, ihr, imin, isec)
+      ! Convert nemo time variables from dom_oce into local versions
+      iyr  = nyear
+      imon = nmonth
+      iday = nday
+      ihr = INT(nsec_day/3600)
+      imin = INT((nsec_day-ihr*3600)/60)
+      isec = nsec_day - ihr*3600 - imin*60
+
+      ! no overlap for icebergs since we want only one instance of each across the whole domain
+      ! so restrict area of interest
+      ! use tmask here because tmask_i has been doctored on one side of the north fold line
+
+      DO jj = nicbdj, nicbej
+         DO ji = nicbdi, nicbei
+            IF( tmask(ji,jj,1) > 0._wp        .AND.                                       &
+                rn_test_box(1) < glamt(ji,jj) .AND. glamt(ji,jj) < rn_test_box(2) .AND.   &
+                rn_test_box(3) < gphit(ji,jj) .AND. gphit(ji,jj) < rn_test_box(4) ) THEN
+               localberg%mass_scaling = rn_mass_scaling(iberg)
+               localpt%xi = REAL( mig(ji), wp )
+               localpt%yj = REAL( mjg(jj), wp )
+               localpt%lon = icb_utl_bilin(glamt, localpt%xi, localpt%yj, 'T' )
+               localpt%lat = icb_utl_bilin(gphit, localpt%xi, localpt%yj, 'T' )
+               localpt%mass      = rn_initial_mass     (iberg)
+               localpt%thickness = rn_initial_thickness(iberg)
+               localpt%width  = first_width (iberg)
+               localpt%length = first_length(iberg)
+               localpt%year = iyr
+               localpt%day = REAL(iday,wp)+(REAL(ihr,wp)+REAL(imin,wp)/60._wp)/24._wp
+               localpt%mass_of_bits = 0._wp
+               localpt%heat_density = 0._wp
+               localpt%uvel = 0._wp
+               localpt%vvel = 0._wp
+               CALL icb_utl_incr()
+               localberg%number(:) = num_bergs(:)
+               call icb_utl_add(localberg, localpt)
+            ENDIF
+         END DO
+      END DO
+      !
+      ibergs = icb_utl_count()
+      CALL mpp_sum('icbini', ibergs)
+      IF( nn_verbose_level > 0) THEN
+         WRITE(numicb,'(a,i6,a)') 'diamonds, icb_ini_gen: ',ibergs,' were generated'
+      ENDIF
+      !
+   END SUBROUTINE icb_ini_gen
+
+
+   SUBROUTINE icb_nam
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE icb_nam  ***
+      !!
+      !! ** Purpose :   read iceberg namelist and print the variables.
+      !!
+      !! ** input   : - namberg namelist
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jn      ! dummy loop indices
+      INTEGER  ::   ios     ! Local integer output status for namelist read
+      REAL(wp) ::   zfact   ! local scalar
+      !
+      NAMELIST/namberg/ ln_icebergs    , ln_bergdia     , nn_sample_rate      , rn_initial_mass      ,   &
+         &              rn_distribution, rn_mass_scaling, rn_initial_thickness, nn_verbose_write     ,   &
+         &              rn_rho_bergs   , rn_LoW_ratio   , nn_verbose_level    , ln_operator_splitting,   &
+         &              rn_bits_erosion_fraction        , rn_sicn_shift       , ln_passive_mode      ,   &
+         &              nn_test_icebergs                , rn_test_box         , ln_use_calving       ,   &
+         &              rn_speed_limit , cn_dir, sn_icb
+      !!----------------------------------------------------------------------
+
+#if defined key_agrif
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'icb_nam : AGRIF is not compatible with namelist namberg :  '
+         WRITE(numout,*) '~~~~~~~   definition of rn_initial_mass(nclasses) with nclasses as PARAMETER '
+         WRITE(numout,*)
+         WRITE(numout,*) '   ==>>>   force  NO icebergs used. The namelist namberg is not read'
+      ENDIF
+      ln_icebergs = .false.      
+      RETURN
+#else
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'icb_nam : iceberg initialization through namberg namelist read'
+         WRITE(numout,*) '~~~~~~~~ '
+      ENDIF
+#endif   
+      !                             !==  read namelist  ==!
+      REWIND( numnam_ref )              ! Namelist namberg in reference namelist : Iceberg parameters
+      READ  ( numnam_ref, namberg, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namberg in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namberg in configuration namelist : Iceberg parameters
+      READ  ( numnam_cfg, namberg, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namberg in configuration namelist' )
+      IF(lwm) WRITE ( numond, namberg )
+      !
+      IF(lwp) WRITE(numout,*)
+      IF( ln_icebergs ) THEN
+         IF(lwp) WRITE(numout,*) '   ==>>>   icebergs are used'
+      ELSE
+         IF(lwp) WRITE(numout,*) '   ==>>>   No icebergs used'
+         RETURN
+      ENDIF
+      !
+      IF( nn_test_icebergs > nclasses ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   Resetting of nn_test_icebergs to ', nclasses
+         nn_test_icebergs = nclasses
+      ENDIF
+      !
+      IF( nn_test_icebergs < 0 .AND. .NOT. ln_use_calving ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   Resetting ln_use_calving to .true. since we are not using test icebergs'
+         ln_use_calving = .true.
+      ENDIF
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'icb_nam : iceberg initialization through namberg namelist read'
+         WRITE(numout,*) '~~~~~~~~ '
+         WRITE(numout,*) '   Calculate budgets                                            ln_bergdia       = ', ln_bergdia
+         WRITE(numout,*) '   Period between sampling of position for trajectory storage   nn_sample_rate = ', nn_sample_rate
+         WRITE(numout,*) '   Mass thresholds between iceberg classes (kg)                 rn_initial_mass     ='
+         DO jn = 1, nclasses
+            WRITE(numout,'(a,f15.2)') '                                                                ', rn_initial_mass(jn)
+         ENDDO
+         WRITE(numout,*) '   Fraction of calving to apply to this class (non-dim)         rn_distribution     ='
+         DO jn = 1, nclasses
+            WRITE(numout,'(a,f10.4)') '                                                                ', rn_distribution(jn)
+         END DO
+         WRITE(numout,*) '   Ratio between effective and real iceberg mass (non-dim)      rn_mass_scaling     = '
+         DO jn = 1, nclasses
+            WRITE(numout,'(a,f10.2)') '                                                                ', rn_mass_scaling(jn)
+         END DO
+         WRITE(numout,*) '   Total thickness of newly calved bergs (m)                    rn_initial_thickness = '
+         DO jn = 1, nclasses
+            WRITE(numout,'(a,f10.2)') '                                                                ', rn_initial_thickness(jn)
+         END DO
+         WRITE(numout,*) '   Timesteps between verbose messages                           nn_verbose_write    = ', nn_verbose_write
+
+         WRITE(numout,*) '   Density of icebergs                           rn_rho_bergs  = ', rn_rho_bergs
+         WRITE(numout,*) '   Initial ratio L/W for newly calved icebergs   rn_LoW_ratio  = ', rn_LoW_ratio
+         WRITE(numout,*) '   Turn on more verbose output                          level  = ', nn_verbose_level
+         WRITE(numout,*) '   Use first order operator splitting for thermodynamics    ',   &
+            &                    'use_operator_splitting = ', ln_operator_splitting
+         WRITE(numout,*) '   Fraction of erosion melt flux to divert to bergy bits    ',   &
+            &                    'bits_erosion_fraction = ', rn_bits_erosion_fraction
+
+         WRITE(numout,*) '   Shift of sea-ice concentration in erosion flux modulation ',   &
+            &                    '(0<sicn_shift<1)    rn_sicn_shift  = ', rn_sicn_shift
+         WRITE(numout,*) '   Do not add freshwater flux from icebergs to ocean                ',   &
+            &                    '                  passive_mode            = ', ln_passive_mode
+         WRITE(numout,*) '   Create icebergs in absence of a restart file   nn_test_icebergs  = ', nn_test_icebergs
+         WRITE(numout,*) '                   in lon/lat box                                   = ', rn_test_box
+         WRITE(numout,*) '   Use calving data even if nn_test_icebergs > 0    ln_use_calving  = ', ln_use_calving
+         WRITE(numout,*) '   CFL speed limit for a berg            speed_limit                = ', rn_speed_limit
+         WRITE(numout,*) '   Writing Iceberg status information to icebergs.stat file        '
+      ENDIF
+      !
+      ! ensure that the sum of berg input distribution is equal to one
+      zfact = SUM( rn_distribution )
+      IF( zfact /= 1._wp .AND. 0_wp /= zfact ) THEN
+         rn_distribution(:) = rn_distribution(:) / zfact
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '      ==>>> CAUTION:    sum of berg input distribution = ', zfact
+            WRITE(numout,*) '            *******     redistribution has been rescaled'
+            WRITE(numout,*) '                        updated berg distribution is :'
+            DO jn = 1, nclasses
+               WRITE(numout,'(a,f10.4)') '                                   ',rn_distribution(jn)
+            END DO
+         ENDIF
+      ENDIF
+      IF( MINVAL( rn_distribution(:) ) < 0._wp ) THEN
+         CALL ctl_stop( 'icb_nam: a negative rn_distribution value encountered ==>> change your namelist namberg' )
+      ENDIF
+      !
+   END SUBROUTINE icb_nam
+
+   !!======================================================================
+END MODULE icbini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icblbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icblbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icblbc.F90	(revision 14097)
@@ -0,0 +1,926 @@
+MODULE icblbc
+   !!======================================================================
+   !!                       ***  MODULE  icblbc  ***
+   !! Ocean physics:  routines to handle boundary exchanges for icebergs
+   !!======================================================================
+   !! History :  3.3  !  2010-01  (Martin&Adcroft) Original code
+   !!             -   !  2011-03  (Madec)          Part conversion to NEMO form
+   !!             -   !                            Removal of mapping from another grid
+   !!             -   !  2011-04  (Alderson)       Split into separate modules
+   !!             -   !  2011-05  (Alderson)       MPP exchanges written based on lib_mpp
+   !!             -   !  2011-05  (Alderson)       MPP and single processor boundary conditions added
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_lbc       : -  Pass icebergs across cyclic boundaries
+   !!   icb_lbc_mpp   : -  In MPP pass icebergs from linked list between processors
+   !!                      as they advect around
+   !!                   -  Lagrangian processes cannot be handled by existing NEMO MPP
+   !!                      routines because they do not lie on regular jpi,jpj grids
+   !!                   -  Processor exchanges are handled as in lib_mpp whenever icebergs step 
+   !!                      across boundary of interior domain (nicbdi-nicbei, nicbdj-nicbej)
+   !!                      so that iceberg does not exist in more than one processor
+   !!                   -  North fold exchanges controlled by three arrays:
+   !!                         nicbflddest - unique processor numbers that current one exchanges with
+   !!                         nicbfldproc - processor number that current grid point exchanges with
+   !!                         nicbfldpts  - packed i,j point in exchanging processor
+   !!----------------------------------------------------------------------
+   USE par_oce                             ! ocean parameters
+   USE dom_oce                             ! ocean domain
+   USE in_out_manager                      ! IO parameters
+   USE lib_mpp                             ! MPI code and lk_mpp in particular
+   USE icb_oce                             ! define iceberg arrays
+   USE icbutl                              ! iceberg utility routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+#if defined key_mpp_mpi
+
+!$AGRIF_DO_NOT_TREAT
+   INCLUDE 'mpif.h'
+!$AGRIF_END_DO_NOT_TREAT
+
+   TYPE, PUBLIC :: buffer
+      INTEGER :: size = 0
+      REAL(wp), DIMENSION(:,:), POINTER ::   data
+   END TYPE buffer
+
+   TYPE(buffer), POINTER       ::   obuffer_n=>NULL() , ibuffer_n=>NULL()
+   TYPE(buffer), POINTER       ::   obuffer_s=>NULL() , ibuffer_s=>NULL()
+   TYPE(buffer), POINTER       ::   obuffer_e=>NULL() , ibuffer_e=>NULL()
+   TYPE(buffer), POINTER       ::   obuffer_w=>NULL() , ibuffer_w=>NULL()
+
+   ! north fold exchange buffers
+   TYPE(buffer), POINTER       ::   obuffer_f=>NULL() , ibuffer_f=>NULL()
+
+   INTEGER, PARAMETER, PRIVATE ::   jp_delta_buf = 25             ! Size by which to increment buffers
+   INTEGER, PARAMETER, PRIVATE ::   jp_buffer_width = 15+nkounts  ! items to store for each berg
+
+#endif
+
+   PUBLIC   icb_lbc
+   PUBLIC   icb_lbc_mpp
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_lbc()
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_lbc  ***
+      !!
+      !! ** Purpose :   in non-mpp case need to deal with cyclic conditions
+      !!                including north-fold
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER ::   this
+      TYPE(point)  , POINTER ::   pt
+      INTEGER                ::   iine
+      !!----------------------------------------------------------------------
+
+      !! periodic east/west boundaries
+      !! =============================
+
+      IF( l_Iperio ) THEN
+
+         this => first_berg
+         DO WHILE( ASSOCIATED(this) )
+            pt => this%current_point
+            iine = INT( pt%xi + 0.5 )
+            IF( iine > mig(nicbei) ) THEN
+               pt%xi = ricb_right + MOD(pt%xi, 1._wp ) - 1._wp
+            ELSE IF( iine < mig(nicbdi) ) THEN
+               pt%xi = ricb_left + MOD(pt%xi, 1._wp )
+            ENDIF
+            this => this%next
+         END DO
+         !
+      ENDIF
+
+      !! north/south boundaries
+      !! ======================
+      IF( l_Jperio)      CALL ctl_stop(' north-south periodicity not implemented for icebergs')
+      ! north fold
+      IF( npolj /= 0 )   CALL icb_lbc_nfld()
+      !
+   END SUBROUTINE icb_lbc
+
+
+   SUBROUTINE icb_lbc_nfld()
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_lbc_nfld  ***
+      !!
+      !! ** Purpose :   single processor north fold exchange
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER ::   this
+      TYPE(point)  , POINTER ::   pt
+      INTEGER                ::   iine, ijne, ipts
+      INTEGER                ::   iiglo, ijglo
+      !!----------------------------------------------------------------------
+      !
+      this => first_berg
+      DO WHILE( ASSOCIATED(this) )
+         pt => this%current_point
+         ijne = INT( pt%yj + 0.5 )
+         IF( ijne .GT. mjg(nicbej) ) THEN
+            !
+            iine = INT( pt%xi + 0.5 )
+            ipts  = nicbfldpts (mi1(iine))
+            !
+            ! moving across the cut line means both position and
+            ! velocity must change
+            ijglo = INT( ipts/nicbpack )
+            iiglo = ipts - nicbpack*ijglo
+            pt%xi = iiglo - ( pt%xi - REAL(iine,wp) )
+            pt%yj = ijglo - ( pt%yj - REAL(ijne,wp) )
+            pt%uvel = -1._wp * pt%uvel
+            pt%vvel = -1._wp * pt%vvel
+         ENDIF
+         this => this%next
+      END DO
+      !
+   END SUBROUTINE icb_lbc_nfld
+
+#if defined key_mpp_mpi
+   !!----------------------------------------------------------------------
+   !!   'key_mpp_mpi'             MPI massively parallel processing library
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE icb_lbc_mpp()
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_lbc_mpp  ***
+      !!
+      !! ** Purpose :   multi processor exchange
+      !!
+      !! ** Method  :   identify direction for exchange, pack into a buffer
+      !!                which is basically a real array and delete from linked list
+      !!                length of buffer is exchanged first with receiving processor
+      !!                then buffer is sent if necessary
+      !!----------------------------------------------------------------------
+      TYPE(iceberg)         , POINTER     ::   tmpberg, this
+      TYPE(point)           , POINTER     ::   pt
+      INTEGER                             ::   ibergs_to_send_e, ibergs_to_send_w
+      INTEGER                             ::   ibergs_to_send_n, ibergs_to_send_s
+      INTEGER                             ::   ibergs_rcvd_from_e, ibergs_rcvd_from_w
+      INTEGER                             ::   ibergs_rcvd_from_n, ibergs_rcvd_from_s
+      INTEGER                             ::   i, ibergs_start, ibergs_end
+      INTEGER                             ::   iine, ijne
+      INTEGER                             ::   ipe_N, ipe_S, ipe_W, ipe_E
+      REAL(wp), DIMENSION(2)              ::   zewbergs, zwebergs, znsbergs, zsnbergs
+      INTEGER                             ::   iml_req1, iml_req2, iml_req3, iml_req4
+      INTEGER                             ::   iml_req5, iml_req6, iml_req7, iml_req8, iml_err
+      INTEGER, DIMENSION(MPI_STATUS_SIZE) ::   iml_stat
+
+      ! set up indices of neighbouring processors
+      ipe_N = -1
+      ipe_S = -1
+      ipe_W = -1
+      ipe_E = -1
+      IF( nbondi .EQ.  0 .OR. nbondi .EQ. 1) ipe_W = nowe
+      IF( nbondi .EQ. -1 .OR. nbondi .EQ. 0) ipe_E = noea
+      IF( nbondj .EQ.  0 .OR. nbondj .EQ. 1) ipe_S = noso
+      IF( nbondj .EQ. -1 .OR. nbondj .EQ. 0) ipe_N = nono
+      !
+      ! at northern line of processors with north fold handle bergs differently
+      IF( npolj > 0 ) ipe_N = -1
+
+      ! if there's only one processor in x direction then don't let mpp try to handle periodicity
+      IF( jpni == 1 ) THEN
+         ipe_E = -1
+         ipe_W = -1
+      ENDIF
+
+      IF( nn_verbose_level >= 2 ) THEN
+         WRITE(numicb,*) 'processor west  : ', ipe_W
+         WRITE(numicb,*) 'processor east  : ', ipe_E
+         WRITE(numicb,*) 'processor north : ', ipe_N
+         WRITE(numicb,*) 'processor south : ', ipe_S
+         WRITE(numicb,*) 'processor nimpp : ', nimpp
+         WRITE(numicb,*) 'processor njmpp : ', njmpp
+         WRITE(numicb,*) 'processor nbondi: ', nbondi
+         WRITE(numicb,*) 'processor nbondj: ', nbondj
+         CALL flush( numicb )
+      ENDIF
+
+      ! periodicity is handled here when using mpp when there is more than one processor in
+      ! the i direction, but it also has to happen when jpni=1 case so this is dealt with
+      ! in icb_lbc and called here
+
+      IF( jpni == 1 ) CALL icb_lbc()
+
+      ! Note that xi is adjusted when swapping because of periodic condition
+
+      IF( nn_verbose_level > 0 ) THEN
+         ! store the number of icebergs on this processor at start
+         ibergs_start = icb_utl_count()
+      ENDIF
+
+      ibergs_to_send_e   = 0
+      ibergs_to_send_w   = 0
+      ibergs_to_send_n   = 0
+      ibergs_to_send_s   = 0
+      ibergs_rcvd_from_e = 0
+      ibergs_rcvd_from_w = 0
+      ibergs_rcvd_from_n = 0
+      ibergs_rcvd_from_s = 0
+
+      IF( ASSOCIATED(first_berg) ) THEN      ! Find number of bergs that headed east/west
+         this => first_berg
+         DO WHILE (ASSOCIATED(this))
+            pt => this%current_point
+            iine = INT( pt%xi + 0.5 )
+            IF( ipe_E >= 0 .AND. iine > mig(nicbei) ) THEN
+               tmpberg => this
+               this => this%next
+               ibergs_to_send_e = ibergs_to_send_e + 1
+               IF( nn_verbose_level >= 4 ) THEN
+                  WRITE(numicb,*) 'bergstep ',nktberg,' packing berg ',tmpberg%number(:),' for transfer to east'
+                  CALL flush( numicb )
+               ENDIF
+               ! deal with periodic case
+               tmpberg%current_point%xi = ricb_right + MOD(tmpberg%current_point%xi, 1._wp ) - 1._wp
+               ! now pack it into buffer and delete from list
+               CALL icb_pack_into_buffer( tmpberg, obuffer_e, ibergs_to_send_e)
+               CALL icb_utl_delete(first_berg, tmpberg)
+            ELSE IF( ipe_W >= 0 .AND. iine < mig(nicbdi) ) THEN
+               tmpberg => this
+               this => this%next
+               ibergs_to_send_w = ibergs_to_send_w + 1
+               IF( nn_verbose_level >= 4 ) THEN
+                  WRITE(numicb,*) 'bergstep ',nktberg,' packing berg ',tmpberg%number(:),' for transfer to west'
+                  CALL flush( numicb )
+               ENDIF
+               ! deal with periodic case
+               tmpberg%current_point%xi = ricb_left + MOD(tmpberg%current_point%xi, 1._wp )
+               ! now pack it into buffer and delete from list
+               CALL icb_pack_into_buffer( tmpberg, obuffer_w, ibergs_to_send_w)
+               CALL icb_utl_delete(first_berg, tmpberg)
+            ELSE
+               this => this%next
+            ENDIF
+         END DO
+      ENDIF
+      IF( nn_verbose_level >= 3) THEN
+         WRITE(numicb,*) 'bergstep ',nktberg,' send ew: ', ibergs_to_send_e, ibergs_to_send_w
+         CALL flush(numicb)
+      ENDIF
+
+      ! send bergs east and receive bergs from west (ie ones that were sent east) and vice versa
+
+      ! pattern here is copied from lib_mpp code
+
+      SELECT CASE ( nbondi )
+      CASE( -1 )
+         zwebergs(1) = ibergs_to_send_e
+         CALL mppsend( 12, zwebergs(1), 1, ipe_E, iml_req1)
+         CALL mpprecv( 11, zewbergs(2), 1, ipe_E )
+         CALL mpi_wait( iml_req1, iml_stat, iml_err )
+         ibergs_rcvd_from_e = INT( zewbergs(2) )
+      CASE(  0 )
+         zewbergs(1) = ibergs_to_send_w
+         zwebergs(1) = ibergs_to_send_e
+         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, ipe_E )
+         CALL mpprecv( 12, zwebergs(2), 1, ipe_W )
+         CALL mpi_wait( iml_req2, iml_stat, iml_err )
+         CALL mpi_wait( iml_req3, iml_stat, iml_err )
+         ibergs_rcvd_from_e = INT( zewbergs(2) )
+         ibergs_rcvd_from_w = INT( zwebergs(2) )
+      CASE(  1 )
+         zewbergs(1) = ibergs_to_send_w
+         CALL mppsend( 11, zewbergs(1), 1, ipe_W, iml_req4)
+         CALL mpprecv( 12, zwebergs(2), 1, ipe_W )
+         CALL mpi_wait( iml_req4, iml_stat, iml_err )
+         ibergs_rcvd_from_w = INT( zwebergs(2) )
+      END SELECT
+      IF( nn_verbose_level >= 3) THEN
+         WRITE(numicb,*) 'bergstep ',nktberg,' recv ew: ', ibergs_rcvd_from_w, ibergs_rcvd_from_e
+         CALL flush(numicb)
+      ENDIF
+
+      SELECT CASE ( nbondi )
+      CASE( -1 )
+         IF( ibergs_to_send_e > 0 ) CALL mppsend( 14, obuffer_e%data, ibergs_to_send_e*jp_buffer_width, ipe_E, iml_req1 )
+         IF( ibergs_rcvd_from_e > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_e, ibergs_rcvd_from_e)
+            CALL mpprecv( 13, ibuffer_e%data, ibergs_rcvd_from_e*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_e > 0 ) CALL mpi_wait( iml_req1, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_e
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_e%data(16,i)),' from east'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_e, i)
+         ENDDO
+      CASE(  0 )
+         IF( ibergs_to_send_w > 0 ) CALL mppsend( 13, obuffer_w%data, ibergs_to_send_w*jp_buffer_width, ipe_W, iml_req2 )
+         IF( ibergs_to_send_e > 0 ) CALL mppsend( 14, obuffer_e%data, ibergs_to_send_e*jp_buffer_width, ipe_E, iml_req3 )
+         IF( ibergs_rcvd_from_e > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_e, ibergs_rcvd_from_e)
+            CALL mpprecv( 13, ibuffer_e%data, ibergs_rcvd_from_e*jp_buffer_width )
+         ENDIF
+         IF( ibergs_rcvd_from_w > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_w, ibergs_rcvd_from_w)
+            CALL mpprecv( 14, ibuffer_w%data, ibergs_rcvd_from_w*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_w > 0 ) CALL mpi_wait( iml_req2, iml_stat, iml_err )
+         IF( ibergs_to_send_e > 0 ) CALL mpi_wait( iml_req3, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_e
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_e%data(16,i)),' from east'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_e, i)
+         END DO
+         DO i = 1, ibergs_rcvd_from_w
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_w%data(16,i)),' from west'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_w, i)
+         ENDDO
+      CASE(  1 )
+         IF( ibergs_to_send_w > 0 ) CALL mppsend( 13, obuffer_w%data, ibergs_to_send_w*jp_buffer_width, ipe_W, iml_req4 )
+         IF( ibergs_rcvd_from_w > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_w, ibergs_rcvd_from_w)
+            CALL mpprecv( 14, ibuffer_w%data, ibergs_rcvd_from_w*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_w > 0 ) CALL mpi_wait( iml_req4, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_w
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_w%data(16,i)),' from west'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_w, i)
+         END DO
+      END SELECT
+
+      ! Find number of bergs that headed north/south
+      ! (note: this block should technically go ahead of the E/W recv block above
+      !  to handle arbitrary orientation of PEs. But for simplicity, it is
+      !  here to accomodate diagonal transfer of bergs between PEs -AJA)
+
+      IF( ASSOCIATED(first_berg) ) THEN
+         this => first_berg
+         DO WHILE (ASSOCIATED(this))
+            pt => this%current_point
+            ijne = INT( pt%yj + 0.5 )
+            IF( ipe_N >= 0 .AND. ijne .GT. mjg(nicbej) ) THEN
+               tmpberg => this
+               this => this%next
+               ibergs_to_send_n = ibergs_to_send_n + 1
+               IF( nn_verbose_level >= 4 ) THEN
+                  WRITE(numicb,*) 'bergstep ',nktberg,' packing berg ',tmpberg%number(:),' for transfer to north'
+                  CALL flush( numicb )
+               ENDIF
+               CALL icb_pack_into_buffer( tmpberg, obuffer_n, ibergs_to_send_n)
+               CALL icb_utl_delete(first_berg, tmpberg)
+            ELSE IF( ipe_S >= 0 .AND. ijne .LT. mjg(nicbdj) ) THEN
+               tmpberg => this
+               this => this%next
+               ibergs_to_send_s = ibergs_to_send_s + 1
+               IF( nn_verbose_level >= 4 ) THEN
+                  WRITE(numicb,*) 'bergstep ',nktberg,' packing berg ',tmpberg%number(:),' for transfer to south'
+                  CALL flush( numicb )
+               ENDIF
+               CALL icb_pack_into_buffer( tmpberg, obuffer_s, ibergs_to_send_s)
+               CALL icb_utl_delete(first_berg, tmpberg)
+            ELSE
+               this => this%next
+            ENDIF
+         END DO
+      ENDIF
+      if( nn_verbose_level >= 3) then
+         write(numicb,*) 'bergstep ',nktberg,' send ns: ', ibergs_to_send_n, ibergs_to_send_s
+         call flush(numicb)
+      endif
+
+      ! send bergs north
+      ! and receive bergs from south (ie ones sent north)
+
+      SELECT CASE ( nbondj )
+      CASE( -1 )
+         zsnbergs(1) = ibergs_to_send_n
+         CALL mppsend( 16, zsnbergs(1), 1, ipe_N, iml_req1)
+         CALL mpprecv( 15, znsbergs(2), 1, ipe_N )
+         CALL mpi_wait( iml_req1, iml_stat, iml_err )
+         ibergs_rcvd_from_n = INT( znsbergs(2) )
+      CASE(  0 )
+         znsbergs(1) = ibergs_to_send_s
+         zsnbergs(1) = ibergs_to_send_n
+         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, ipe_N )
+         CALL mpprecv( 16, zsnbergs(2), 1, ipe_S )
+         CALL mpi_wait( iml_req2, iml_stat, iml_err )
+         CALL mpi_wait( iml_req3, iml_stat, iml_err )
+         ibergs_rcvd_from_n = INT( znsbergs(2) )
+         ibergs_rcvd_from_s = INT( zsnbergs(2) )
+      CASE(  1 )
+         znsbergs(1) = ibergs_to_send_s
+         CALL mppsend( 15, znsbergs(1), 1, ipe_S, iml_req4)
+         CALL mpprecv( 16, zsnbergs(2), 1, ipe_S )
+         CALL mpi_wait( iml_req4, iml_stat, iml_err )
+         ibergs_rcvd_from_s = INT( zsnbergs(2) )
+      END SELECT
+      if( nn_verbose_level >= 3) then
+         write(numicb,*) 'bergstep ',nktberg,' recv ns: ', ibergs_rcvd_from_s, ibergs_rcvd_from_n
+         call flush(numicb)
+      endif
+
+      SELECT CASE ( nbondj )
+      CASE( -1 )
+         IF( ibergs_to_send_n > 0 ) CALL mppsend( 18, obuffer_n%data, ibergs_to_send_n*jp_buffer_width, ipe_N, iml_req1 )
+         IF( ibergs_rcvd_from_n > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_n, ibergs_rcvd_from_n)
+            CALL mpprecv( 17, ibuffer_n%data, ibergs_rcvd_from_n*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_n > 0 ) CALL mpi_wait( iml_req1, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_n
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_n%data(16,i)),' from north'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_n, i)
+         END DO
+      CASE(  0 )
+         IF( ibergs_to_send_s > 0 ) CALL mppsend( 17, obuffer_s%data, ibergs_to_send_s*jp_buffer_width, ipe_S, iml_req2 )
+         IF( ibergs_to_send_n > 0 ) CALL mppsend( 18, obuffer_n%data, ibergs_to_send_n*jp_buffer_width, ipe_N, iml_req3 )
+         IF( ibergs_rcvd_from_n > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_n, ibergs_rcvd_from_n)
+            CALL mpprecv( 17, ibuffer_n%data, ibergs_rcvd_from_n*jp_buffer_width )
+         ENDIF
+         IF( ibergs_rcvd_from_s > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_s, ibergs_rcvd_from_s)
+            CALL mpprecv( 18, ibuffer_s%data, ibergs_rcvd_from_s*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_s > 0 ) CALL mpi_wait( iml_req2, iml_stat, iml_err )
+         IF( ibergs_to_send_n > 0 ) CALL mpi_wait( iml_req3, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_n
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_n%data(16,i)),' from north'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_n, i)
+         END DO
+         DO i = 1, ibergs_rcvd_from_s
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_s%data(16,i)),' from south'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_s, i)
+         ENDDO
+      CASE(  1 )
+         IF( ibergs_to_send_s > 0 ) CALL mppsend( 17, obuffer_s%data, ibergs_to_send_s*jp_buffer_width, ipe_S, iml_req4 )
+         IF( ibergs_rcvd_from_s > 0 ) THEN
+            CALL icb_increase_ibuffer(ibuffer_s, ibergs_rcvd_from_s)
+            CALL mpprecv( 18, ibuffer_s%data, ibergs_rcvd_from_s*jp_buffer_width )
+         ENDIF
+         IF( ibergs_to_send_s > 0 ) CALL mpi_wait( iml_req4, iml_stat, iml_err )
+         DO i = 1, ibergs_rcvd_from_s
+            IF( nn_verbose_level >= 4 ) THEN
+               WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_s%data(16,i)),' from south'
+               CALL flush( numicb )
+            ENDIF
+            CALL icb_unpack_from_buffer(first_berg, ibuffer_s, i)
+         END DO
+      END SELECT
+
+      IF( nn_verbose_level > 0 ) THEN
+         ! compare the number of icebergs on this processor from the start to the end
+         ibergs_end = icb_utl_count()
+         i = ( ibergs_rcvd_from_n + ibergs_rcvd_from_s + ibergs_rcvd_from_e + ibergs_rcvd_from_w ) - &
+             ( ibergs_to_send_n + ibergs_to_send_s + ibergs_to_send_e + ibergs_to_send_w )
+         IF( ibergs_end-(ibergs_start+i) .NE. 0 ) THEN
+            WRITE( numicb,*   ) 'send_bergs_to_other_pes: net change in number of icebergs'
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_end=', &
+                                ibergs_end,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_start=', &
+                                ibergs_start,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: delta=', &
+                                i,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: error=', &
+                                ibergs_end-(ibergs_start+i),' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_to_send_n=', &
+                                ibergs_to_send_n,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_to_send_s=', &
+                                ibergs_to_send_s,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_to_send_e=', &
+                                ibergs_to_send_e,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_to_send_w=', &
+                                ibergs_to_send_w,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_rcvd_from_n=', &
+                                ibergs_rcvd_from_n,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_rcvd_from_s=', &
+                                ibergs_rcvd_from_s,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_rcvd_from_e=', &
+                                ibergs_rcvd_from_e,' on PE',narea
+            WRITE( numicb,1000) 'send_bergs_to_other_pes: ibergs_rcvd_from_w=', &
+                                ibergs_rcvd_from_w,' on PE',narea
+  1000      FORMAT(a,i5,a,i4)
+            CALL ctl_stop('send_bergs_to_other_pes: lost or gained an iceberg or two')
+         ENDIF
+      ENDIF
+
+      ! deal with north fold if we necessary when there is more than one top row processor
+      ! note that for jpni=1 north fold has been dealt with above in call to icb_lbc
+      IF( npolj /= 0 .AND. jpni > 1 ) CALL icb_lbc_mpp_nfld( )
+
+      IF( nn_verbose_level > 0 ) THEN
+         i = 0
+         this => first_berg
+         DO WHILE (ASSOCIATED(this))
+            pt => this%current_point
+            iine = INT( pt%xi + 0.5 )
+            ijne = INT( pt%yj + 0.5 )
+            IF( iine .LT. mig(nicbdi) .OR. &
+                iine .GT. mig(nicbei) .OR. &
+                ijne .LT. mjg(nicbdj) .OR. &
+                ijne .GT. mjg(nicbej)) THEN
+               i = i + 1
+               WRITE(numicb,*) 'berg lost in halo: ', this%number(:),iine,ijne
+               WRITE(numicb,*) '                   ', nimpp, njmpp
+               WRITE(numicb,*) '                   ', nicbdi, nicbei, nicbdj, nicbej
+               CALL flush( numicb )
+            ENDIF
+            this => this%next
+         ENDDO ! WHILE
+         CALL mpp_sum('icblbc', i)
+         IF( i .GT. 0 ) THEN
+            WRITE( numicb,'(a,i4)') 'send_bergs_to_other_pes: # of bergs outside computational domain = ',i
+            CALL ctl_stop('send_bergs_to_other_pes:  there are bergs still in halos!')
+         ENDIF ! root_pe
+      ENDIF ! debug
+      !
+      CALL mppsync()
+      !
+   END SUBROUTINE icb_lbc_mpp
+
+
+   SUBROUTINE icb_lbc_mpp_nfld()
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_lbc_mpp_nfld  ***
+      !!
+      !! ** Purpose :   north fold treatment in multi processor exchange
+      !!
+      !! ** Method  :   
+      !!----------------------------------------------------------------------
+      TYPE(iceberg)         , POINTER     :: tmpberg, this
+      TYPE(point)           , POINTER     :: pt
+      INTEGER                             :: ibergs_to_send
+      INTEGER                             :: ibergs_to_rcv
+      INTEGER                             :: iiglo, ijglo, jk, jn
+      INTEGER                             :: ifldproc, iproc, ipts
+      INTEGER                             :: iine, ijne
+      INTEGER                             :: jjn
+      REAL(wp), DIMENSION(0:3)            :: zsbergs, znbergs
+      INTEGER                             :: iml_req1, iml_req2, iml_err
+      INTEGER, DIMENSION(MPI_STATUS_SIZE) :: iml_stat
+
+      ! set up indices of neighbouring processors
+
+      ! nicbfldproc is a list of unique processor numbers that this processor
+      ! exchanges with (including itself), so we loop over this array; since
+      ! 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 .AND. nn_verbose_level > 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 .AND. nn_verbose_level > 0 ) write(numicb,*) 'ICB ERROR'
+            nicbfldexpect(jjn) = INT( znbergs(2) )
+            !IF ( nicbfldexpect(jjn) .GT. 0 .AND. nn_verbose_level > 0 ) write(numicb,*) 'ICB expecting ',nicbfldexpect(jjn),' from ', nicbfldproc(jjn)
+            !IF (nn_verbose_level > 0) 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
+            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
+            ifldproc = nicbfldproc(jn)
+            ibergs_to_send = 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 )
+                  ipts  = nicbfldpts (mi1(iine))
+                  iproc = nicbflddest(mi1(iine))
+                  IF( ijne .GT. mjg(nicbej) ) THEN
+                     IF( iproc == ifldproc ) THEN
+                        !
+                        ! moving across the cut line means both position and
+                        ! velocity must change
+                        ijglo = INT( ipts/nicbpack )
+                        iiglo = ipts - nicbpack*ijglo
+                        pt%xi = iiglo - ( pt%xi - REAL(iine,wp) )
+                        pt%yj = ijglo - ( pt%yj - REAL(ijne,wp) )
+                        pt%uvel = -1._wp * pt%uvel
+                        pt%vvel = -1._wp * pt%vvel
+                        !
+                        ! now remove berg from list and pack it into a buffer
+                        IF( iproc /= narea ) THEN
+                           tmpberg => this
+                           ibergs_to_send = ibergs_to_send + 1
+                           IF( nn_verbose_level >= 4 ) THEN
+                              WRITE(numicb,*) 'bergstep ',nktberg,' packing berg ',tmpberg%number(:),' for north fold'
+                              CALL flush( numicb )
+                           ENDIF
+                           CALL icb_pack_into_buffer( tmpberg, obuffer_f, ibergs_to_send)
+                           CALL icb_utl_delete(first_berg, tmpberg)
+                        ENDIF
+                        !
+                     ENDIF
+                  ENDIF
+                  this => this%next
+               END DO
+            ENDIF
+            if( nn_verbose_level >= 3) then
+               write(numicb,*) 'bergstep ',nktberg,' send nfld: ', ibergs_to_send
+               call flush(numicb)
+            endif
+            !
+            ! if we're in this processor, then we've done everything we need to
+            ! so go on to next element of loop
+            IF( ifldproc == narea ) CYCLE
+   
+            ! send bergs
+   
+            IF( ibergs_to_send > 0 )  &
+                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, ifldproc-1 )
+            ENDIF
+            !
+            DO jk = 1, ibergs_to_rcv
+               IF( nn_verbose_level >= 4 ) THEN
+                  WRITE(numicb,*) 'bergstep ',nktberg,' unpacking berg ',INT(ibuffer_f%data(16,jk)),' from north fold'
+                  CALL flush( numicb )
+               ENDIF
+               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
+            CALL mpi_wait( nicbfldreq(jn), iml_stat, iml_err )
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE icb_lbc_mpp_nfld
+
+
+   SUBROUTINE icb_pack_into_buffer( berg, pbuff, kb )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER :: berg
+      TYPE(buffer) , POINTER :: pbuff
+      INTEGER               , INTENT(in) :: kb
+      ! 
+      INTEGER ::   k   ! local integer
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT. ASSOCIATED(pbuff) ) CALL icb_increase_buffer( pbuff, jp_delta_buf )
+      IF( kb .GT. pbuff%size ) CALL icb_increase_buffer( pbuff, jp_delta_buf )
+
+      !! pack points into buffer
+
+      pbuff%data( 1,kb) = berg%current_point%lon
+      pbuff%data( 2,kb) = berg%current_point%lat
+      pbuff%data( 3,kb) = berg%current_point%uvel
+      pbuff%data( 4,kb) = berg%current_point%vvel
+      pbuff%data( 5,kb) = berg%current_point%xi
+      pbuff%data( 6,kb) = berg%current_point%yj
+      pbuff%data( 7,kb) = float(berg%current_point%year)
+      pbuff%data( 8,kb) = berg%current_point%day
+      pbuff%data( 9,kb) = berg%current_point%mass
+      pbuff%data(10,kb) = berg%current_point%thickness
+      pbuff%data(11,kb) = berg%current_point%width
+      pbuff%data(12,kb) = berg%current_point%length
+      pbuff%data(13,kb) = berg%current_point%mass_of_bits
+      pbuff%data(14,kb) = berg%current_point%heat_density
+
+      pbuff%data(15,kb) = berg%mass_scaling
+      DO k=1,nkounts
+         pbuff%data(15+k,kb) = REAL( berg%number(k), wp )
+      END DO
+      !
+   END SUBROUTINE icb_pack_into_buffer
+
+
+   SUBROUTINE icb_unpack_from_buffer(first, pbuff, kb)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      TYPE(iceberg),             POINTER :: first
+      TYPE(buffer) ,             POINTER :: pbuff
+      INTEGER      , INTENT(in)          :: kb
+      ! 
+      TYPE(iceberg)                      :: currentberg
+      TYPE(point)                        :: pt
+      INTEGER                            :: ik
+      !!----------------------------------------------------------------------
+      !
+      pt%lon            =      pbuff%data( 1,kb)
+      pt%lat            =      pbuff%data( 2,kb)
+      pt%uvel           =      pbuff%data( 3,kb)
+      pt%vvel           =      pbuff%data( 4,kb)
+      pt%xi             =      pbuff%data( 5,kb)
+      pt%yj             =      pbuff%data( 6,kb)
+      pt%year           = INT( pbuff%data( 7,kb) )
+      pt%day            =      pbuff%data( 8,kb)
+      pt%mass           =      pbuff%data( 9,kb)
+      pt%thickness      =      pbuff%data(10,kb)
+      pt%width          =      pbuff%data(11,kb)
+      pt%length         =      pbuff%data(12,kb)
+      pt%mass_of_bits   =      pbuff%data(13,kb)
+      pt%heat_density   =      pbuff%data(14,kb)
+
+      currentberg%mass_scaling =      pbuff%data(15,kb)
+      DO ik = 1, nkounts
+         currentberg%number(ik) = INT( pbuff%data(15+ik,kb) )
+      END DO
+      !
+      CALL icb_utl_add(currentberg, pt )
+      !
+   END SUBROUTINE icb_unpack_from_buffer
+
+
+   SUBROUTINE icb_increase_buffer(old,kdelta)
+      !!----------------------------------------------------------------------
+      TYPE(buffer), POINTER    :: old
+      INTEGER     , INTENT(in) :: kdelta
+      ! 
+      TYPE(buffer), POINTER ::   new
+      INTEGER ::   inew_size
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT. ASSOCIATED(old) ) THEN   ;   inew_size = kdelta
+      ELSE                               ;   inew_size = old%size + kdelta
+      ENDIF
+      ALLOCATE( new )
+      ALLOCATE( new%data( jp_buffer_width, inew_size) )
+      new%size = inew_size
+      IF( ASSOCIATED(old) ) THEN
+         new%data(:,1:old%size) = old%data(:,1:old%size)
+         DEALLOCATE(old%data)
+         DEALLOCATE(old)
+      ENDIF
+      old => new
+      !
+   END SUBROUTINE icb_increase_buffer
+
+
+   SUBROUTINE icb_increase_ibuffer(old,kdelta)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      TYPE(buffer),            POINTER :: old
+      INTEGER     , INTENT(in)         :: kdelta
+      !
+      TYPE(buffer),            POINTER :: new
+      INTEGER                          :: inew_size, iold_size
+      !!----------------------------------------------------------------------
+
+      IF( .NOT. ASSOCIATED(old) ) THEN
+         inew_size = kdelta + jp_delta_buf
+         iold_size = 0
+      ELSE
+         iold_size = old%size
+         IF( kdelta .LT. old%size ) THEN
+            inew_size = old%size + kdelta
+         ELSE
+            inew_size = kdelta + jp_delta_buf
+         ENDIF
+      ENDIF
+
+      IF( iold_size .NE. inew_size ) THEN
+         ALLOCATE( new )
+         ALLOCATE( new%data( jp_buffer_width, inew_size) )
+         new%size = inew_size
+         IF( ASSOCIATED(old) ) THEN
+            new%data(:,1:old%size) = old%data(:,1:old%size)
+            DEALLOCATE(old%data)
+            DEALLOCATE(old)
+         ENDIF
+         old => new
+         !IF (nn_verbose_level > 0) WRITE( numicb,*) 'icb_increase_ibuffer',narea,' increased to',inew_size
+      ENDIF
+      !
+   END SUBROUTINE icb_increase_ibuffer
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default case:            Dummy module        share memory computing
+   !!----------------------------------------------------------------------
+   SUBROUTINE icb_lbc_mpp()
+      WRITE(numout,*) 'icb_lbc_mpp: You should not have seen this message!!'
+   END SUBROUTINE icb_lbc_mpp
+#endif
+
+   !!======================================================================
+END MODULE icblbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbrst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbrst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbrst.F90	(revision 14097)
@@ -0,0 +1,424 @@
+MODULE icbrst
+   !!======================================================================
+   !!                       ***  MODULE  icbrst  ***
+   !! Ocean physics:  read and write iceberg restart files
+   !!======================================================================
+   !! History : 3.3.1 !  2010-01  (Martin&Adcroft) Original code
+   !!            -    !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -    !                            Removal of mapping from another grid
+   !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!            -    !  2011-04  (Alderson)       Restore restart routine
+   !!            -    !                            Currently needs a fixed processor
+   !!            -    !                            layout between restarts
+   !!            -    !  2015-11  Dave Storkey     Convert icb_rst_read to use IOM so can
+   !!                                              read single restart files
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_rst_read    : read restart file
+   !!   icb_rst_write   : write restart file
+   !!----------------------------------------------------------------------
+   USE par_oce        ! NEMO parameters
+   USE dom_oce        ! NEMO domain
+   USE in_out_manager ! NEMO IO routines
+   USE lib_mpp        ! NEMO MPI library, lk_mpp in particular
+   USE netcdf         ! netcdf routines for IO
+   USE iom
+   USE icb_oce        ! define iceberg arrays
+   USE icbutl         ! iceberg utility routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_rst_read    ! routine called in icbini.F90 module
+   PUBLIC   icb_rst_write   ! routine called in icbstp.F90 module
+   
+   INTEGER ::   nlonid, nlatid, nxid, nyid, nuvelid, nvvelid
+   INTEGER ::   nmassid, nthicknessid, nwidthid, nlengthid
+   INTEGER ::   nyearid, ndayid
+   INTEGER ::   nscaling_id, nmass_of_bits_id, nheat_density_id, numberid
+   INTEGER ::   nsiceid, nsheatid, ncalvid, ncalvhid, nkountid
+   INTEGER ::   nret, ncid, nc_dim
+   
+   INTEGER,  DIMENSION(3)                  :: nstrt3, nlngth3
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_rst_read()
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_rst_read  ***
+      !!
+      !! ** Purpose :   read a iceberg restart file
+      !!      NB: for this version, we just read back in the restart for this processor
+      !!      so we cannot change the processor layout currently with iceberg code
+      !!----------------------------------------------------------------------
+      INTEGER                      ::   idim, ivar, iatt
+      INTEGER                      ::   jn, iunlim_dim, ibergs_in_file
+      INTEGER                      ::   ii, ij, iclass, ibase_err, imax_icb
+      REAL(wp), DIMENSION(nkounts) ::   zdata      
+      LOGICAL                      ::   ll_found_restart
+      CHARACTER(len=256)           ::   cl_path
+      CHARACTER(len=256)           ::   cl_filename
+      CHARACTER(len=NF90_MAX_NAME) ::   cl_dname
+      TYPE(iceberg)                ::   localberg ! NOT a pointer but an actual local variable
+      TYPE(point)                  ::   localpt   ! NOT a pointer but an actual local variable
+      !!----------------------------------------------------------------------
+
+      ! Find a restart file. Assume iceberg restarts in same directory as ocean restarts
+      ! and are called TRIM(cn_ocerst)//'_icebergs'
+      cl_path = TRIM(cn_ocerst_indir)
+      IF( cl_path(LEN_TRIM(cl_path):) /= '/' ) cl_path = TRIM(cl_path) // '/'
+      cl_filename = TRIM(cn_ocerst_in)//'_icebergs'
+      CALL iom_open( TRIM(cl_path)//cl_filename, ncid )
+
+      imax_icb = 0
+      IF( iom_file(ncid)%iduld .GE. 0) THEN
+
+         ibergs_in_file = iom_file(ncid)%lenuld
+         DO jn = 1,ibergs_in_file
+
+            ! iom_get treats the unlimited dimension as time. Here the unlimited dimension 
+            ! is the iceberg index, but we can still use the ktime keyword to get the iceberg we want. 
+
+            CALL iom_get( ncid, 'xi'     ,localpt%xi  , ktime=jn )
+            CALL iom_get( ncid, 'yj'     ,localpt%yj  , ktime=jn )
+
+            ii = INT( localpt%xi + 0.5 )
+            ij = INT( localpt%yj + 0.5 )
+            ! Only proceed if this iceberg is on the local processor (excluding halos).
+            IF ( ii .GE. nldi+nimpp-1 .AND. ii .LE. nlei+nimpp-1 .AND. &
+           &     ij .GE. nldj+njmpp-1 .AND. ij .LE. nlej+njmpp-1 ) THEN           
+
+               CALL iom_get( ncid, jpdom_unknown, 'number'       , zdata(:) , ktime=jn, kstart=(/1/), kcount=(/nkounts/) )
+               localberg%number(:) = INT(zdata(:))
+               imax_icb = MAX( imax_icb, INT(zdata(1)) )
+               CALL iom_get( ncid, 'mass_scaling' , localberg%mass_scaling, ktime=jn )
+               CALL iom_get( ncid, 'lon'          , localpt%lon           , ktime=jn )
+               CALL iom_get( ncid, 'lat'          , localpt%lat           , ktime=jn )
+               CALL iom_get( ncid, 'uvel'         , localpt%uvel          , ktime=jn )
+               CALL iom_get( ncid, 'vvel'         , localpt%vvel          , ktime=jn )
+               CALL iom_get( ncid, 'mass'         , localpt%mass          , ktime=jn )
+               CALL iom_get( ncid, 'thickness'    , localpt%thickness     , ktime=jn )
+               CALL iom_get( ncid, 'width'        , localpt%width         , ktime=jn )
+               CALL iom_get( ncid, 'length'       , localpt%length        , ktime=jn )
+               CALL iom_get( ncid, 'year'         , zdata(1)              , ktime=jn )
+               localpt%year = INT(zdata(1))
+               CALL iom_get( ncid, 'day'          , localpt%day           , ktime=jn )
+               CALL iom_get( ncid, 'mass_of_bits' , localpt%mass_of_bits  , ktime=jn )
+               CALL iom_get( ncid, 'heat_density' , localpt%heat_density  , ktime=jn )
+               !
+               CALL icb_utl_add( localberg, localpt )
+               !
+            ENDIF
+            !
+         END DO
+         !
+      ELSE
+         ibergs_in_file = 0
+      ENDIF 
+
+      ! Gridded variables
+      CALL iom_get( ncid, jpdom_autoglo,    'calving'     , src_calving  )
+      CALL iom_get( ncid, jpdom_autoglo,    'calving_hflx', src_calving_hflx  )
+      CALL iom_get( ncid, jpdom_autoglo,    'stored_heat' , berg_grid%stored_heat  )
+      CALL iom_get( ncid, jpdom_autoglo_xy, 'stored_ice'  , berg_grid%stored_ice, kstart=(/1,1,1/), kcount=(/1,1,nclasses/) )
+      
+      CALL iom_get( ncid, jpdom_unknown, 'kount' , zdata(:) )
+      num_bergs(:) = INT(zdata(:))
+      !
+
+      ! Sanity checks
+      jn = icb_utl_count()
+      IF ( lwp .AND. nn_verbose_level >= 0 )   &
+         WRITE(numout,'(2(a,i5))') 'icebergs, read_restart_bergs: # bergs =',jn,' on PE',narea-1
+      IF( lk_mpp ) THEN
+         ! Only mpp_sum ibergs_in_file if we are reading from multiple restart files. 
+         IF( INDEX(iom_file(ncid)%name,'icebergs.nc' ) .EQ. 0 ) CALL mpp_sum('icbrst', ibergs_in_file)
+         CALL mpp_sum('icbrst', jn)
+      ENDIF
+      IF( lwp )   WRITE(numout,'(a,i5,a,i5,a)') 'icebergs, icb_rst_read: there were',ibergs_in_file,   &
+         &                                    ' bergs in the restart file and', jn,' bergs have been read'
+      ! Close file
+      CALL iom_close( ncid )
+      !
+      ! Confirm that all areas have a suitable base for assigning new iceberg
+      ! numbers. This will not be the case if restarting from a collated dataset
+      ! (even if using the same processor decomposition)
+      !
+      ibase_err = 0
+      IF( num_bergs(1) < 0 .AND. num_bergs(1) /= narea - jpnij ) THEN
+         ! If this area has never calved a new berg then the base should be
+         ! set to narea - jpnij. If it is negative but something else then
+         ! a new base will be needed to guarantee unique, future iceberg numbers
+         ibase_err = 1
+      ELSEIF( MOD( num_bergs(1) - narea , jpnij ) /= 0 ) THEN
+         ! If this area has a base which is not in the set {narea + N*jpnij}
+         ! for positive integers N then a new base will be needed to guarantee 
+         ! unique, future iceberg numbers
+         ibase_err = 1
+      ENDIF
+      IF( lk_mpp ) THEN
+         CALL mpp_sum('icbrst', ibase_err)
+      ENDIF
+      IF( ibase_err > 0 ) THEN
+         ! 
+         ! A new base is needed. The only secure solution is to set bases such that
+         ! all future icebergs numbers will be greater than the current global maximum
+         IF( lk_mpp ) THEN
+            CALL mpp_max('icbrst', imax_icb)
+         ENDIF
+         num_bergs(1) = imax_icb - jpnij + narea
+      ENDIF
+      !
+      IF( lwp .AND. nn_verbose_level >= 0 )  WRITE(numout,'(a)') 'icebergs, icb_rst_read: completed'
+      !
+   END SUBROUTINE icb_rst_read
+
+
+   SUBROUTINE icb_rst_write( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE icb_rst_write  ***
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) :: kt
+      !
+      INTEGER ::   jn   ! dummy loop index
+      INTEGER ::   idg  ! number of digits
+      INTEGER ::   ix_dim, iy_dim, ik_dim, in_dim
+      CHARACTER(len=256)     :: cl_path
+      CHARACTER(len=256)     :: cl_filename
+      CHARACTER(len=8  )     :: cl_kt
+      CHARACTER(LEN=12 )     :: clfmt            ! writing format
+      TYPE(iceberg), POINTER :: this
+      TYPE(point)  , POINTER :: pt
+      !!----------------------------------------------------------------------
+
+      ! Following the normal restart procedure, this routine will be called
+      ! the timestep before a restart stage as well as the restart timestep.
+      ! This is a performance step enabling the file to be opened and contents
+      ! defined in advance of the write. This is not possible with icebergs
+      ! since the number of bergs to be written could change between timesteps
+      IF( kt == nitrst ) THEN
+         ! Only operate on the restart timestep itself.
+         ! Assume we write iceberg restarts to same directory as ocean restarts.
+         cl_path = TRIM(cn_ocerst_outdir)
+         IF( cl_path(LEN_TRIM(cl_path):) /= '/' ) cl_path = TRIM(cl_path) // '/'
+         WRITE(cl_kt, '(i8.8)') kt
+         cl_filename = TRIM(cexper)//"_icebergs_"//cl_kt//"_restart"
+         IF( lk_mpp ) THEN
+            idg = MAX( INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1, 4 )          ! how many digits to we need to write? min=4, max=9
+            WRITE(clfmt, "('(a,a,i', i1, '.', i1, ',a)')") idg, idg          ! '(a,a,ix.x,a)'
+            WRITE(cl_filename,  clfmt) TRIM(cl_filename), '_', narea-1, '.nc'
+         ELSE
+            WRITE(cl_filename,'(a,a)') TRIM(cl_filename),               '.nc'
+         ENDIF
+         IF ( lwp .AND. nn_verbose_level >= 0) WRITE(numout,'(2a)') 'icebergs, write_restart: creating ',  &
+           &                                                         TRIM(cl_path)//TRIM(cl_filename)
+   
+         nret = NF90_CREATE(TRIM(cl_path)//TRIM(cl_filename), NF90_CLOBBER, ncid)
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_create failed')
+   
+         ! Dimensions
+         nret = NF90_DEF_DIM(ncid, 'x', jpi, ix_dim)
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_def_dim x failed')
+   
+         nret = NF90_DEF_DIM(ncid, 'y', jpj, iy_dim)
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_def_dim y failed')
+   
+         nret = NF90_DEF_DIM(ncid, 'c', nclasses, nc_dim)
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_def_dim c failed')
+   
+         nret = NF90_DEF_DIM(ncid, 'k', nkounts, ik_dim)
+         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)
+            IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_def_dim n failed')
+         ENDIF
+   
+         ! Variables
+         nret = NF90_DEF_VAR(ncid, 'kount'       , NF90_INT   , (/ ik_dim /), nkountid)
+         nret = NF90_DEF_VAR(ncid, 'calving'     , NF90_DOUBLE, (/ ix_dim, iy_dim /), ncalvid)
+         nret = NF90_DEF_VAR(ncid, 'calving_hflx', NF90_DOUBLE, (/ ix_dim, iy_dim /), ncalvhid)
+         nret = NF90_DEF_VAR(ncid, 'stored_ice'  , NF90_DOUBLE, (/ ix_dim, iy_dim, nc_dim /), nsiceid)
+         nret = NF90_DEF_VAR(ncid, 'stored_heat' , NF90_DOUBLE, (/ ix_dim, iy_dim /), nsheatid)
+   
+         ! Attributes
+         nret = NF90_PUT_ATT(ncid, ncalvid , 'long_name', 'iceberg calving')
+         nret = NF90_PUT_ATT(ncid, ncalvid , 'units', 'some')
+         nret = NF90_PUT_ATT(ncid, ncalvhid, 'long_name', 'heat flux associated with iceberg calving')
+         nret = NF90_PUT_ATT(ncid, ncalvhid, 'units', 'some')
+         nret = NF90_PUT_ATT(ncid, nsiceid , 'long_name', 'stored ice used to calve icebergs')
+         nret = NF90_PUT_ATT(ncid, nsiceid , 'units', 'kg/s')
+         nret = NF90_PUT_ATT(ncid, nsheatid, 'long_name', 'heat in stored ice used to calve icebergs')
+         nret = NF90_PUT_ATT(ncid, nsheatid, 'units', 'J/kg/s')
+   
+         IF ( ASSOCIATED(first_berg) ) THEN
+   
+            ! Only add berg variables for this PE if we have anything to say
+   
+            ! Variables
+            nret = NF90_DEF_VAR(ncid, 'lon', NF90_DOUBLE, in_dim, nlonid)
+            nret = NF90_DEF_VAR(ncid, 'lat', NF90_DOUBLE, in_dim, nlatid)
+            nret = NF90_DEF_VAR(ncid, 'xi', NF90_DOUBLE, in_dim, nxid)
+            nret = NF90_DEF_VAR(ncid, 'yj', NF90_DOUBLE, in_dim, nyid)
+            nret = NF90_DEF_VAR(ncid, 'uvel', NF90_DOUBLE, in_dim, nuvelid)
+            nret = NF90_DEF_VAR(ncid, 'vvel', NF90_DOUBLE, in_dim, nvvelid)
+            nret = NF90_DEF_VAR(ncid, 'mass', NF90_DOUBLE, in_dim, nmassid)
+            nret = NF90_DEF_VAR(ncid, 'thickness', NF90_DOUBLE, in_dim, nthicknessid)
+            nret = NF90_DEF_VAR(ncid, 'width', NF90_DOUBLE, in_dim, nwidthid)
+            nret = NF90_DEF_VAR(ncid, 'length', NF90_DOUBLE, in_dim, nlengthid)
+            nret = NF90_DEF_VAR(ncid, 'number', NF90_INT, (/ik_dim,in_dim/), numberid)
+            nret = NF90_DEF_VAR(ncid, 'year', NF90_INT, in_dim, nyearid)
+            nret = NF90_DEF_VAR(ncid, 'day', NF90_DOUBLE, in_dim, ndayid)
+            nret = NF90_DEF_VAR(ncid, 'mass_scaling', NF90_DOUBLE, in_dim, nscaling_id)
+            nret = NF90_DEF_VAR(ncid, 'mass_of_bits', NF90_DOUBLE, in_dim, nmass_of_bits_id)
+            nret = NF90_DEF_VAR(ncid, 'heat_density', NF90_DOUBLE, in_dim, nheat_density_id)
+   
+            ! Attributes
+            nret = NF90_PUT_ATT(ncid, nlonid, 'long_name', 'longitude')
+            nret = NF90_PUT_ATT(ncid, nlonid, 'units', 'degrees_E')
+            nret = NF90_PUT_ATT(ncid, nlatid, 'long_name', 'latitude')
+            nret = NF90_PUT_ATT(ncid, nlatid, 'units', 'degrees_N')
+            nret = NF90_PUT_ATT(ncid, nxid, 'long_name', 'x grid box position')
+            nret = NF90_PUT_ATT(ncid, nxid, 'units', 'fractional')
+            nret = NF90_PUT_ATT(ncid, nyid, 'long_name', 'y grid box position')
+            nret = NF90_PUT_ATT(ncid, nyid, 'units', 'fractional')
+            nret = NF90_PUT_ATT(ncid, nuvelid, 'long_name', 'zonal velocity')
+            nret = NF90_PUT_ATT(ncid, nuvelid, 'units', 'm/s')
+            nret = NF90_PUT_ATT(ncid, nvvelid, 'long_name', 'meridional velocity')
+            nret = NF90_PUT_ATT(ncid, nvvelid, 'units', 'm/s')
+            nret = NF90_PUT_ATT(ncid, nmassid, 'long_name', 'mass')
+            nret = NF90_PUT_ATT(ncid, nmassid, 'units', 'kg')
+            nret = NF90_PUT_ATT(ncid, nthicknessid, 'long_name', 'thickness')
+            nret = NF90_PUT_ATT(ncid, nthicknessid, 'units', 'm')
+            nret = NF90_PUT_ATT(ncid, nwidthid, 'long_name', 'width')
+            nret = NF90_PUT_ATT(ncid, nwidthid, 'units', 'm')
+            nret = NF90_PUT_ATT(ncid, nlengthid, 'long_name', 'length')
+            nret = NF90_PUT_ATT(ncid, nlengthid, 'units', 'm')
+            nret = NF90_PUT_ATT(ncid, numberid, 'long_name', 'iceberg number on this processor')
+            nret = NF90_PUT_ATT(ncid, numberid, 'units', 'count')
+            nret = NF90_PUT_ATT(ncid, nyearid, 'long_name', 'calendar year of calving event')
+            nret = NF90_PUT_ATT(ncid, nyearid, 'units', 'years')
+            nret = NF90_PUT_ATT(ncid, ndayid, 'long_name', 'year day of calving event')
+            nret = NF90_PUT_ATT(ncid, ndayid, 'units', 'days')
+            nret = NF90_PUT_ATT(ncid, nscaling_id, 'long_name', 'scaling factor for mass of calving berg')
+            nret = NF90_PUT_ATT(ncid, nscaling_id, 'units', 'none')
+            nret = NF90_PUT_ATT(ncid, nmass_of_bits_id, 'long_name', 'mass of bergy bits')
+            nret = NF90_PUT_ATT(ncid, nmass_of_bits_id, 'units', 'kg')
+            nret = NF90_PUT_ATT(ncid, nheat_density_id, 'long_name', 'heat density')
+            nret = NF90_PUT_ATT(ncid, nheat_density_id, 'units', 'J/kg')
+   
+         ENDIF ! associated(first_berg)
+   
+         ! End define mode
+         nret = NF90_ENDDEF(ncid)
+   
+         ! --------------------------------
+         ! now write some data
+   
+         nstrt3(1) = 1
+         nstrt3(2) = 1
+         nlngth3(1) = jpi
+         nlngth3(2) = jpj
+         nlngth3(3) = 1
+   
+         DO jn=1,nclasses
+            griddata(:,:,1) = berg_grid%stored_ice(:,:,jn)
+            nstrt3(3) = jn
+            nret = NF90_PUT_VAR( ncid, nsiceid, griddata, nstrt3, nlngth3 )
+            IF (nret .ne. NF90_NOERR) THEN
+               IF( lwp ) WRITE(numout,*) TRIM(NF90_STRERROR( nret ))
+               CALL ctl_stop('icebergs, write_restart: nf_put_var stored_ice failed')
+            ENDIF
+         ENDDO
+         IF( lwp ) WRITE(numout,*) 'file: ',TRIM(cl_path)//TRIM(cl_filename),' var: stored_ice  written'
+   
+         nret = NF90_PUT_VAR( ncid, nkountid, num_bergs(:) )
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_put_var kount failed')
+   
+         nret = NF90_PUT_VAR( ncid, nsheatid, berg_grid%stored_heat(:,:) )
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_put_var stored_heat failed')
+         IF( lwp ) WRITE(numout,*) 'file: ',TRIM(cl_path)//TRIM(cl_filename),' var: stored_heat written'
+   
+         nret = NF90_PUT_VAR( ncid, ncalvid , src_calving(:,:) )
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_put_var calving failed')
+         nret = NF90_PUT_VAR( ncid, ncalvhid, src_calving_hflx(:,:) )
+         IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_put_var calving_hflx failed')
+         IF( lwp ) WRITE(numout,*) 'file: ',TRIM(cl_path)//TRIM(cl_filename),' var: calving written'
+   
+         IF ( ASSOCIATED(first_berg) ) THEN
+   
+            ! Write variables
+            ! just write out the current point of the trajectory
+   
+            this => first_berg
+            jn = 0
+            DO WHILE (ASSOCIATED(this))
+               pt => this%current_point
+               jn=jn+1
+   
+               nret = NF90_PUT_VAR(ncid, numberid, this%number, (/1,jn/), (/nkounts,1/) )
+               nret = NF90_PUT_VAR(ncid, nscaling_id, this%mass_scaling, (/ jn /) )
+   
+               nret = NF90_PUT_VAR(ncid, nlonid, pt%lon, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nlatid, pt%lat, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nxid, pt%xi, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nyid, pt%yj, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nuvelid, pt%uvel, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nvvelid, pt%vvel, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nmassid, pt%mass, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nthicknessid, pt%thickness, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nwidthid, pt%width, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nlengthid, pt%length, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nyearid, pt%year, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, ndayid, pt%day, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nmass_of_bits_id, pt%mass_of_bits, (/ jn /) )
+               nret = NF90_PUT_VAR(ncid, nheat_density_id, pt%heat_density, (/ jn /) )
+   
+               this=>this%next
+            END DO
+            !
+         ENDIF ! associated(first_berg)
+   
+         ! Finish up
+         nret = NF90_CLOSE(ncid)
+         IF (nret /= NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_close failed')
+   
+         ! Sanity check
+         jn = icb_utl_count()
+         IF ( lwp .AND. nn_verbose_level >= 0)   &
+            WRITE(numout,'(2(a,i5))') 'icebergs, icb_rst_write: # bergs =',jn,' on PE',narea-1
+         IF( lk_mpp ) THEN
+            CALL mpp_sum('icbrst', jn)
+         ENDIF
+         IF(lwp)   WRITE(numout,'(a,i5,a,i5,a)') 'icebergs, icb_rst_write: ', jn,   &
+            &                                    ' bergs in total have been written at timestep ', kt
+         !
+         ! Finish up
+         !
+      ENDIF
+   END SUBROUTINE icb_rst_write
+   !
+   !!======================================================================
+END MODULE icbrst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbstp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbstp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbstp.F90	(revision 14097)
@@ -0,0 +1,173 @@
+MODULE icbstp
+   !!======================================================================
+   !!                       ***  MODULE  icbstp  ***
+   !! Icebergs:  initialise variables for iceberg tracking
+   !!======================================================================
+   !! History : 3.3.1 !  2010-01  (Martin&Adcroft) Original code
+   !!            -    !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -    !                            Removal of mapping from another grid
+   !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!            -    !                            Move budgets to icbdia routine
+   !!            -    !  2011-05  (Alderson)       Add call to copy forcing arrays
+   !!            -    !                            into icb copies with haloes
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_stp       : start iceberg tracking
+   !!   icb_end       : end   iceberg tracking
+   !!----------------------------------------------------------------------
+   USE par_oce        ! nemo parameters
+   USE dom_oce        ! ocean domain
+   USE sbc_oce        ! ocean surface forcing
+   USE phycst         ! physical constants
+   !
+   USE icb_oce        ! iceberg: define arrays
+   USE icbini         ! iceberg: initialisation routines
+   USE icbutl         ! iceberg: utility routines
+   USE icbrst         ! iceberg: restart routines
+   USE icbdyn         ! iceberg: dynamics (ie advection) routines
+   USE icbclv         ! iceberg: calving routines
+   USE icbthm         ! iceberg: thermodynamics routines
+   USE icblbc         ! iceberg: lateral boundary routines (including mpp)
+   USE icbtrj         ! iceberg: trajectory I/O routines
+   USE icbdia         ! iceberg: budget
+   !
+   USE in_out_manager ! nemo IO
+   USE lib_mpp        ! massively parallel library 
+   USE iom            ! I/O manager
+   USE fldread        ! field read
+   USE timing         ! timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_stp        ! routine called in sbcmod.F90 module
+   PUBLIC   icb_end        ! routine called in nemogcm.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_stp( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_stp  ***
+      !!
+      !! ** Purpose :   iceberg time stepping.
+      !!
+      !! ** Method  : - top level routine to do things in the correct order
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step index
+      !
+      LOGICAL ::   ll_sample_traj, ll_budget, ll_verbose   ! local logical
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('icb_stp')
+
+      !                       !==  start of timestep housekeeping  ==!
+      !
+      nktberg = kt
+      !
+      IF( nn_test_icebergs < 0 .OR. ln_use_calving ) THEN !* read calving data
+         !
+         CALL fld_read ( kt, 1, sf_icb )
+         src_calving     (:,:) = sf_icb(1)%fnow(:,:,1)    ! calving in km^3/year (water equivalent)
+         src_calving_hflx(:,:) = 0._wp                    ! NO heat flux for now
+         !
+      ENDIF
+      !
+      berg_grid%floating_melt(:,:) = 0._wp
+      !
+      !                                   !* anything that needs to be reset to zero each timestep 
+      CALL icb_dia_step()                 !  for budgets is dealt with here
+      !
+      !                                   !* write out time
+      ll_verbose = .FALSE.
+      IF( nn_verbose_write > 0 .AND. MOD( kt-1 , nn_verbose_write ) == 0 )   ll_verbose = ( nn_verbose_level > 0 )
+      !
+      IF( ll_verbose )   WRITE(numicb,9100) nktberg, ndastp, nsec_day
+ 9100 FORMAT('kt= ',i8, ' day= ',i8,' secs=',i8)
+      !
+      !                                   !* copy nemo forcing arrays into iceberg versions with extra halo
+      CALL icb_utl_copy()                 ! only necessary for variables not on T points
+      !
+      !
+      !                       !==  process icebergs  ==!
+      !                              !
+                                     CALL icb_clv_flx( kt )   ! Accumulate ice from calving
+      !                              !
+                                     CALL icb_clv( kt )       ! Calve excess stored ice into icebergs
+      !                              !
+      !
+      !                       !==  For each berg, evolve  ==!
+      !
+      IF( ASSOCIATED(first_berg) )   CALL icb_dyn( kt )       ! ice berg dynamics
+
+      IF( lk_mpp ) THEN   ;          CALL icb_lbc_mpp()       ! Send bergs to other PEs
+      ELSE                ;          CALL icb_lbc()           ! Deal with any cyclic boundaries in non-mpp case
+      ENDIF
+
+      IF( ASSOCIATED(first_berg) )   CALL icb_thm( kt )       ! Ice berg thermodynamics (melting) + rolling
+      !
+      !
+      !                       !==  diagnostics and output  ==!
+      !
+      !                                   !* For each berg, record trajectory (when needed)
+      ll_sample_traj = .FALSE.
+      IF( nn_sample_rate > 0 .AND. MOD(kt-1,nn_sample_rate) == 0 )   ll_sample_traj = .TRUE.
+      IF( ll_sample_traj .AND. ASSOCIATED(first_berg) )   CALL icb_trj_write( kt )
+
+      !                                   !* Gridded diagnostics
+      !                                   !  To get these iom_put's and those preceding to actually do something
+      !                                   !  use key_iomput in cpp file and create content for XML file
+      !
+      CALL iom_put( "calving"           , berg_grid%calving      (:,:)   )  ! 'calving mass input'
+      CALL iom_put( "berg_floating_melt", berg_grid%floating_melt(:,:)   )  ! 'Melt rate of icebergs + bits' , 'kg/m2/s'
+      CALL iom_put( "berg_stored_ice"   , berg_grid%stored_ice   (:,:,:) )  ! 'Accumulated ice mass by class', 'kg'
+      !
+      CALL icb_dia_put()                  !* store mean budgets
+      !
+      !                                   !*  Dump icebergs to screen
+      IF( nn_verbose_level >= 2 )   CALL icb_utl_print( 'icb_stp, status', kt )
+      !
+      !                                   !* Diagnose budgets
+      ll_budget = .FALSE.
+      IF( nn_verbose_write > 0 .AND. MOD(kt-1,nn_verbose_write) == 0 )   ll_budget = ln_bergdia
+      CALL icb_dia( ll_budget )
+      !
+      IF( lrst_oce ) THEN    !* restart
+         CALL icb_rst_write( kt )
+         IF( nn_sample_rate > 0 )   CALL icb_trj_sync()
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('icb_stp')
+      !
+   END SUBROUTINE icb_stp
+
+
+   SUBROUTINE icb_end( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_end  ***
+      !!
+      !! ** Purpose :   close iceberg files
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )  ::   kt   ! model time-step index
+      !!----------------------------------------------------------------------
+      !
+      ! finish with trajectories if they were written
+      IF( nn_sample_rate > 0 )   CALL icb_trj_end()
+
+      IF(lwp) WRITE(numout,'(a,i6)') 'icebergs: icb_end complete', narea
+      !
+      IF( nn_verbose_level > 0 ) THEN
+         CALL flush( numicb )
+         CLOSE( numicb )
+      ENDIF
+      !
+   END SUBROUTINE icb_end
+
+   !!======================================================================
+END MODULE icbstp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbthm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbthm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbthm.F90	(revision 14097)
@@ -0,0 +1,253 @@
+MODULE icbthm
+   !!======================================================================
+   !!                       ***  MODULE  icbthm  ***
+   !! Icebergs:  thermodynamics routines for icebergs
+   !!======================================================================
+   !! History : 3.3.1 !  2010-01  (Martin&Adcroft) Original code
+   !!            -    !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -    !                            Removal of mapping from another grid
+   !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!            -    !  2011-05  (Alderson)       Use tmask instead of tmask_i
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   icb_thm : initialise
+   !!             reference for equations - M = Martin + Adcroft, OM 34, 2010
+   !!----------------------------------------------------------------------
+   USE par_oce        ! NEMO parameters
+   USE dom_oce        ! NEMO domain
+   USE in_out_manager ! NEMO IO routines, numout in particular
+   USE lib_mpp        ! NEMO MPI routines, ctl_stop in particular
+   USE phycst         ! NEMO physical constants
+   USE sbc_oce
+   USE eosbn2         ! equation of state
+   USE lib_fortran, ONLY : DDPDD
+
+   USE icb_oce        ! define iceberg arrays
+   USE icbutl         ! iceberg utility routines
+   USE icbdia         ! iceberg budget routines
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_thm ! routine called in icbstp.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_thm( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_thm  ***
+      !!
+      !! ** Purpose :   compute the iceberg thermodynamics.
+      !!
+      !! ** Method  : - See Martin & Adcroft, Ocean Modelling 34, 2010
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! timestep number, just passed to icb_utl_print_berg
+      !
+      INTEGER  ::   ii, ij
+      REAL(wp) ::   zM, zT, zW, zL, zSST, zVol, zLn, zWn, zTn, znVol, zIC, zDn
+      REAL(wp) ::   zSSS, zfzpt
+      REAL(wp) ::   zMv, zMe, zMb, zmelt, zdvo, zdva, zdM, zSs, zdMe, zdMb, zdMv
+      REAL(wp) ::   zMnew, zMnew1, zMnew2, zheat_hcflux, zheat_latent, z1_12
+      REAL(wp) ::   zMbits, znMbits, zdMbitsE, zdMbitsM, zLbits, zAbits, zMbb
+      REAL(wp) ::   zxi, zyj, zff, z1_rday, z1_e1e2, zdt, z1_dt, z1_dt_e1e2
+      TYPE(iceberg), POINTER ::   this, next
+      TYPE(point)  , POINTER ::   pt
+      !
+      COMPLEX(wp), DIMENSION(jpi,jpj) :: cicb_melt, cicb_hflx
+      !!----------------------------------------------------------------------
+      !
+      !! initialiaze cicb_melt and cicb_heat
+      cicb_melt = CMPLX( 0.e0, 0.e0, wp ) 
+      cicb_hflx = CMPLX( 0.e0, 0.e0, wp ) 
+      !
+      z1_rday = 1._wp / rday
+      z1_12   = 1._wp / 12._wp
+      zdt     = berg_dt
+      z1_dt   = 1._wp / zdt
+      !
+      ! we're either going to ignore berg fresh water melt flux and associated heat
+      ! or we pass it into the ocean, so at this point we set them both to zero,
+      ! accumulate the contributions to them from each iceberg in the while loop following
+      ! and then pass them (or not) to the ocean
+      !
+      berg_grid%floating_melt(:,:) = 0._wp
+      ! calving_hflx re-used here as temporary workspace for the heat flux associated with melting
+      berg_grid%calving_hflx(:,:)  = 0._wp
+      !
+      this => first_berg
+      DO WHILE( ASSOCIATED(this) )
+         !
+         pt => this%current_point
+         nknberg = this%number(1)
+         CALL icb_utl_interp( pt%xi, pt%e1, pt%uo, pt%ui, pt%ua, pt%ssh_x,   &
+            &                 pt%yj, pt%e2, pt%vo, pt%vi, pt%va, pt%ssh_y,   &
+            &                 pt%sst, pt%cn, pt%hi, zff, pt%sss )
+         !
+         zSST = pt%sst
+         zSSS = pt%sss
+         CALL eos_fzp(zSSS,zfzpt)                       ! freezing point
+         zIC  = MIN( 1._wp, pt%cn + rn_sicn_shift )     ! Shift sea-ice concentration       !!gm ???
+         zM   = pt%mass
+         zT   = pt%thickness                               ! total thickness
+       ! D   = (rn_rho_bergs/pp_rho_seawater)*zT ! draught (keel depth)
+       ! F   = zT - D ! freeboard
+         zW   = pt%width
+         zL   = pt%length
+         zxi  = pt%xi                                      ! position in (i,j) referential
+         zyj  = pt%yj
+         ii  = INT( zxi + 0.5 )                            ! T-cell of the berg
+         ii  = mi1( ii )
+         ij  = INT( zyj + 0.5 )              
+         ij  = mj1( ij )
+         zVol = zT * zW * zL
+
+         ! Environment
+         zdvo = SQRT( (pt%uvel-pt%uo)**2 + (pt%vvel-pt%vo)**2 )
+         zdva = SQRT( (pt%ua  -pt%uo)**2 + (pt%va  -pt%vo)**2 )
+         zSs  = 1.5_wp * SQRT( zdva ) + 0.1_wp * zdva                ! Sea state      (eqn M.A9)
+
+         ! Melt rates in m/s (i.e. division by rday)
+         zMv = MAX( 7.62d-3*zSST+1.29d-3*(zSST**2)                    , 0._wp ) * z1_rday      ! Buoyant convection at sides (eqn M.A10)
+         IF ( zSST > zfzpt ) THEN                                                              ! Calculate basal melting only if SST above freezing point  
+            zMb = MAX( 0.58_wp*(zdvo**0.8_wp)*(zSST+4.0_wp)/(zL**0.2_wp) , 0._wp ) * z1_rday   ! Basal turbulent melting     (eqn M.A7 )
+         ELSE
+            zMb = 0._wp                                                                        ! No basal melting if SST below freezing point     
+         ENDIF
+         zMe = MAX( z1_12*(zSST+2.)*zSs*(1._wp+COS(rpi*(zIC**3)))     , 0._wp ) * z1_rday      ! Wave erosion                (eqn M.A8 )
+
+         IF( ln_operator_splitting ) THEN      ! Operator split update of volume/mass
+            zTn    = MAX( zT - zMb*zdt , 0._wp )         ! new total thickness (m)
+            znVol  = zTn * zW * zL                       ! new volume (m^3)
+            zMnew1 = ( znVol / zVol ) * zM               ! new mass (kg)
+            zdMb   = zM - zMnew1                         ! mass lost to basal melting (>0) (kg)
+            !
+            zLn    = MAX( zL - zMv*zdt , 0._wp )         ! new length (m)
+            zWn    = MAX( zW - zMv*zdt , 0._wp )         ! new width (m)
+            znVol  = zTn * zWn * zLn                     ! new volume (m^3)
+            zMnew2 = ( znVol / zVol ) * zM               ! new mass (kg)
+            zdMv   = zMnew1 - zMnew2                     ! mass lost to buoyant convection (>0) (kg)
+            !
+            zLn    = MAX( zLn - zMe*zdt , 0._wp )        ! new length (m)
+            zWn    = MAX( zWn - zMe*zdt , 0._wp )        ! new width (m)
+            znVol  = zTn * zWn * zLn                     ! new volume (m^3)
+            zMnew  = ( znVol / zVol ) * zM               ! new mass (kg)
+            zdMe   = zMnew2 - zMnew                      ! mass lost to erosion (>0) (kg)
+            zdM    = zM - zMnew                          ! mass lost to all erosion and melting (>0) (kg)
+            !
+         ELSE                                         ! Update dimensions of berg
+            zLn = MAX( zL -(zMv+zMe)*zdt ,0._wp )        ! (m)
+            zWn = MAX( zW -(zMv+zMe)*zdt ,0._wp )        ! (m)
+            zTn = MAX( zT - zMb    *zdt ,0._wp )         ! (m)
+            ! Update volume and mass of berg
+            znVol = zTn*zWn*zLn                          ! (m^3)
+            zMnew = (znVol/zVol)*zM                      ! (kg)
+            zdM   = zM - zMnew                           ! (kg)
+            zdMb = (zM/zVol) * (zW*   zL ) *zMb*zdt      ! approx. mass loss to basal melting (kg)
+            zdMe = (zM/zVol) * (zT*(zW+zL)) *zMe*zdt     ! approx. mass lost to erosion (kg)
+            zdMv = (zM/zVol) * (zT*(zW+zL)) *zMv*zdt     ! approx. mass loss to buoyant convection (kg)
+         ENDIF
+
+         IF( rn_bits_erosion_fraction > 0._wp ) THEN     ! Bergy bits
+            !
+            zMbits   = pt%mass_of_bits                                               ! mass of bergy bits (kg)
+            zdMbitsE = rn_bits_erosion_fraction * zdMe                               ! change in mass of bits (kg)
+            znMbits  = zMbits + zdMbitsE                                             ! add new bergy bits to mass (kg)
+            zLbits   = MIN( zL, zW, zT, 40._wp )                                     ! assume bergy bits are smallest dimension or 40 meters
+            zAbits   = ( zMbits / rn_rho_bergs ) / zLbits                            ! Effective bottom area (assuming T=Lbits)
+            zMbb     = MAX( 0.58_wp*(zdvo**0.8_wp)*(zSST+2._wp) /   &
+               &                              ( zLbits**0.2_wp ) , 0._wp ) * z1_rday ! Basal turbulent melting (for bits)
+            zMbb     = rn_rho_bergs * zAbits * zMbb                                  ! in kg/s
+            zdMbitsM = MIN( zMbb*zdt , znMbits )                                     ! bergy bits mass lost to melting (kg)
+            znMbits  = znMbits-zdMbitsM                                              ! remove mass lost to bergy bits melt
+            IF( zMnew == 0._wp ) THEN                                                ! if parent berg has completely melted then
+               zdMbitsM = zdMbitsM + znMbits                                         ! instantly melt all the bergy bits
+               znMbits  = 0._wp
+            ENDIF
+         ELSE                                                     ! No bergy bits
+            zAbits   = 0._wp
+            zdMbitsE = 0._wp
+            zdMbitsM = 0._wp
+            znMbits  = pt%mass_of_bits                             ! retain previous value incase non-zero
+         ENDIF
+
+         ! use tmask rather than tmask_i when dealing with icebergs
+         IF( tmask(ii,ij,1) /= 0._wp ) THEN    ! Add melting to the grid and field diagnostics
+            z1_e1e2    = r1_e1e2t(ii,ij) * this%mass_scaling
+            z1_dt_e1e2 = z1_dt * z1_e1e2
+            !
+            ! iceberg melt
+            !! the use of DDPDD function for the cumulative sum is needed for reproducibility
+            zmelt    = ( zdM - ( zdMbitsE - zdMbitsM ) ) * z1_dt   ! kg/s
+            CALL DDPDD( CMPLX( zmelt * z1_e1e2, 0.e0, wp ), cicb_melt(ii,ij) )
+            !
+            ! iceberg heat flux
+            !! the use of DDPDD function for the cumulative sum is needed for reproducibility
+            !! NB. The src_calving_hflx field is currently hardwired to zero in icb_stp, which means that the
+            !!     heat density of the icebergs is zero and the heat content flux to the ocean from iceberg
+            !!     melting is always zero. Leaving the term in the code until such a time as this is fixed. DS.
+            zheat_hcflux = zmelt * pt%heat_density       ! heat content flux : kg/s x J/kg = J/s
+            zheat_latent = - zmelt * rLfus               ! latent heat flux:  kg/s x J/kg = J/s
+            CALL DDPDD( CMPLX( ( zheat_hcflux + zheat_latent ) * z1_e1e2, 0.e0, wp ), cicb_hflx(ii,ij) )
+            !
+            ! diagnostics
+            CALL icb_dia_melt( ii, ij, zMnew, zheat_hcflux, zheat_latent, this%mass_scaling,       &
+               &                       zdM, zdMbitsE, zdMbitsM, zdMb, zdMe,   &
+               &                       zdMv, z1_dt_e1e2 )
+         ELSE
+            WRITE(numout,*) 'icb_thm: berg ',this%number(:),' appears to have grounded  at ',narea,ii,ij
+            CALL icb_utl_print_berg( this, kt )
+            WRITE(numout,*) 'msk=',tmask(ii,ij,1), e1e2t(ii,ij)
+            CALL ctl_stop('icb_thm', 'berg appears to have grounded!')
+         ENDIF
+
+         ! Rolling
+         zDn = ( rn_rho_bergs / pp_rho_seawater ) * zTn       ! draught (keel depth)
+         IF( zDn > 0._wp .AND. MAX(zWn,zLn) < SQRT( 0.92*(zDn**2) + 58.32*zDn ) ) THEN
+            zT  = zTn
+            zTn = zWn
+            zWn = zT
+         ENDIF
+
+         ! Store the new state of iceberg (with L>W)
+         pt%mass         = zMnew
+         pt%mass_of_bits = znMbits
+         pt%thickness    = zTn
+         pt%width        = MIN( zWn , zLn )
+         pt%length       = MAX( zWn , zLn )
+
+         next=>this%next
+
+!!gm  add a test to avoid over melting ?
+
+         IF( zMnew <= 0._wp ) THEN       ! Delete the berg if completely melted
+            CALL icb_utl_delete( first_berg, this )
+            !
+         ELSE                            ! Diagnose mass distribution on grid
+            z1_e1e2 = r1_e1e2t(ii,ij) * this%mass_scaling
+            CALL icb_dia_size( ii, ij, zWn, zLn, zAbits,   &
+               &               this%mass_scaling, zMnew, znMbits, z1_e1e2 )
+         ENDIF
+         !
+         this=>next
+         !
+      END DO
+      !
+      berg_grid%floating_melt = REAL(cicb_melt,wp)    ! kg/m2/s
+      berg_grid%calving_hflx  = REAL(cicb_hflx,wp)
+      !
+      ! now use melt and associated heat flux in ocean (or not)
+      !
+      IF(.NOT. ln_passive_mode ) THEN
+         emp (:,:) = emp (:,:) - berg_grid%floating_melt(:,:)
+         qns (:,:) = qns (:,:) + berg_grid%calving_hflx (:,:)  
+      ENDIF
+      !
+   END SUBROUTINE icb_thm
+
+   !!======================================================================
+END MODULE icbthm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbtrj.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbtrj.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbtrj.F90	(revision 14097)
@@ -0,0 +1,287 @@
+MODULE icbtrj
+   !!======================================================================
+   !!                       ***  MODULE  icbtrj  ***
+   !! Ocean physics:  trajectory I/O routines
+   !!======================================================================
+   !! History :  3.3  !  2010-01  (Martin&Adcroft) Original code
+   !!             -   !  2011-03  (Madec)          Part conversion to NEMO form
+   !!             -   !                            Removal of mapping from another grid
+   !!             -   !  2011-05  (Alderson)       New module to handle trajectory output
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_trj_init  : initialise iceberg trajectory output files
+   !!   icb_trj_write :
+   !!   icb_trj_sync  :
+   !!   icb_trj_end   :
+   !!----------------------------------------------------------------------
+   USE par_oce        ! NEMO parameters
+   USE dom_oce        ! NEMO ocean domain
+   USE phycst         ! NEMO physical constants
+   USE icb_oce        ! define iceberg arrays
+   USE icbutl         ! iceberg utility routines
+   !
+   USE lib_mpp        ! NEMO MPI library, lk_mpp in particular
+   USE in_out_manager ! NEMO IO, numout in particular
+   USE ioipsl  , ONLY : ju2ymds    ! for calendar
+   USE netcdf
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_trj_init    ! routine called in icbini.F90 module
+   PUBLIC   icb_trj_write   ! routine called in icbstp.F90 module
+   PUBLIC   icb_trj_sync    ! routine called in icbstp.F90 module
+   PUBLIC   icb_trj_end     ! routine called in icbstp.F90 module
+
+   INTEGER ::   num_traj
+   INTEGER ::   n_dim, m_dim
+   INTEGER ::   ntrajid
+   INTEGER ::   numberid, nstepid, nscaling_id
+   INTEGER ::   nlonid, nlatid, nxid, nyid, nuvelid, nvvelid, nmassid
+   INTEGER ::   nuoid, nvoid, nuaid, nvaid, nuiid, nviid
+   INTEGER ::   nsshxid, nsshyid, nsstid, ncntid, nthkid
+   INTEGER ::   nthicknessid, nwidthid, nlengthid
+   INTEGER ::   nyearid, ndayid
+   INTEGER ::   nmass_of_bits_id, nheat_density_id
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_trj_init( ktend )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_trj_init  ***
+      !!
+      !! ** Purpose :   initialise iceberg trajectory output files
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   ktend   ! time step index
+      !
+      INTEGER                ::   iret, iyear, imonth, iday
+      INTEGER                ::   idg  ! number of digits
+      REAL(wp)               ::   zfjulday, zsec
+      CHARACTER(len=80)      ::   cl_filename
+      CHARACTER(LEN=8 )      ::   cldate_ini, cldate_end
+      CHARACTER(LEN=12)      ::   clfmt            ! writing format
+      TYPE(iceberg), POINTER ::   this
+      TYPE(point)  , POINTER ::   pt
+      !!----------------------------------------------------------------------
+
+      ! compute initial time step date
+      CALL ju2ymds( fjulday, iyear, imonth, iday, zsec )
+      WRITE(cldate_ini, '(i4.4,2i2.2)') iyear, imonth, iday
+
+      ! compute end time step date
+      zfjulday = fjulday + rdt / rday * REAL( nitend - nit000 + 1 , wp)
+      IF( ABS(zfjulday - REAL(NINT(zfjulday),wp)) < 0.1 / rday )   zfjulday = REAL(NINT(zfjulday),wp)   ! avoid truncation error
+      CALL ju2ymds( zfjulday, iyear, imonth, iday, zsec )
+      WRITE(cldate_end, '(i4.4,2i2.2)') iyear, imonth, iday
+
+      ! define trajectory output name
+      cl_filename = 'trajectory_icebergs_'//cldate_ini//'-'//cldate_end
+      IF ( lk_mpp ) THEN
+         idg = MAX( INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1, 4 )          ! how many digits to we need to write? min=4, max=9
+         WRITE(clfmt, "('(a,a,i', i1, '.', i1, ',a)')") idg, idg          ! '(a,a,ix.x,a)'
+         WRITE(cl_filename,  clfmt) TRIM(cl_filename), '_', narea-1, '.nc'
+      ELSE
+         WRITE(cl_filename,'(a,a)') TRIM(cl_filename),               '.nc'
+      ENDIF
+      IF( lwp .AND. nn_verbose_level >= 0 )   WRITE(numout,'(2a)') 'icebergs, icb_trj_init: creating ',TRIM(cl_filename)
+
+      iret = NF90_CREATE( TRIM(cl_filename), NF90_CLOBBER, ntrajid )
+      IF (iret .NE. NF90_NOERR)   CALL ctl_stop('icebergs, icb_trj_init: nf_create failed')
+
+      ! Dimensions
+      iret = NF90_DEF_DIM( ntrajid, 'n', NF90_UNLIMITED, n_dim )
+      IF ( iret /= NF90_NOERR )   CALL ctl_stop('icebergs, icb_trj_init: nf_def_dim n failed')
+      iret = NF90_DEF_DIM( ntrajid, 'k', nkounts, m_dim )
+      IF ( iret /= NF90_NOERR )   CALL ctl_stop('icebergs, icb_trj_init: nf_def_dim k failed')
+
+      ! Variables
+      iret = NF90_DEF_VAR( ntrajid, 'iceberg_number', NF90_INT   , (/m_dim,n_dim/), numberid         )
+      iret = NF90_DEF_VAR( ntrajid, 'timestep'      , NF90_INT   , n_dim          , nstepid          )
+      iret = NF90_DEF_VAR( ntrajid, 'mass_scaling'  , NF90_DOUBLE, n_dim          , nscaling_id      )
+      iret = NF90_DEF_VAR( ntrajid, 'lon'           , NF90_DOUBLE, n_dim          , nlonid           )
+      iret = NF90_DEF_VAR( ntrajid, 'lat'           , NF90_DOUBLE, n_dim          , nlatid           )
+      iret = NF90_DEF_VAR( ntrajid, 'xi'            , NF90_DOUBLE, n_dim          , nxid             )
+      iret = NF90_DEF_VAR( ntrajid, 'yj'            , NF90_DOUBLE, n_dim          , nyid             )
+      iret = NF90_DEF_VAR( ntrajid, 'uvel'          , NF90_DOUBLE, n_dim          , nuvelid          )
+      iret = NF90_DEF_VAR( ntrajid, 'vvel'          , NF90_DOUBLE, n_dim          , nvvelid          )
+      iret = NF90_DEF_VAR( ntrajid, 'uto'           , NF90_DOUBLE, n_dim          , nuoid            )
+      iret = NF90_DEF_VAR( ntrajid, 'vto'           , NF90_DOUBLE, n_dim          , nvoid            )
+      iret = NF90_DEF_VAR( ntrajid, 'uta'           , NF90_DOUBLE, n_dim          , nuaid            )
+      iret = NF90_DEF_VAR( ntrajid, 'vta'           , NF90_DOUBLE, n_dim          , nvaid            )
+      iret = NF90_DEF_VAR( ntrajid, 'uti'           , NF90_DOUBLE, n_dim          , nuiid            )
+      iret = NF90_DEF_VAR( ntrajid, 'vti'           , NF90_DOUBLE, n_dim          , nviid            )
+      iret = NF90_DEF_VAR( ntrajid, 'ssh_x'         , NF90_DOUBLE, n_dim          , nsshxid          )
+      iret = NF90_DEF_VAR( ntrajid, 'ssh_y'         , NF90_DOUBLE, n_dim          , nsshyid          )
+      iret = NF90_DEF_VAR( ntrajid, 'sst'           , NF90_DOUBLE, n_dim          , nsstid           )
+      iret = NF90_DEF_VAR( ntrajid, 'icnt'          , NF90_DOUBLE, n_dim          , ncntid           )
+      iret = NF90_DEF_VAR( ntrajid, 'ithk'          , NF90_DOUBLE, n_dim          , nthkid           )
+      iret = NF90_DEF_VAR( ntrajid, 'mass'          , NF90_DOUBLE, n_dim          , nmassid          )
+      iret = NF90_DEF_VAR( ntrajid, 'thickness'     , NF90_DOUBLE, n_dim          , nthicknessid     )
+      iret = NF90_DEF_VAR( ntrajid, 'width'         , NF90_DOUBLE, n_dim          , nwidthid         )
+      iret = NF90_DEF_VAR( ntrajid, 'length'        , NF90_DOUBLE, n_dim          , nlengthid        )
+      iret = NF90_DEF_VAR( ntrajid, 'year'          , NF90_INT   , n_dim          , nyearid          )
+      iret = NF90_DEF_VAR( ntrajid, 'day'           , NF90_DOUBLE, n_dim          , ndayid           )
+      iret = NF90_DEF_VAR( ntrajid, 'mass_of_bits'  , NF90_DOUBLE, n_dim          , nmass_of_bits_id )
+      iret = NF90_DEF_VAR( ntrajid, 'heat_density'  , NF90_DOUBLE, n_dim          , nheat_density_id )
+
+      ! Attributes
+      iret = NF90_PUT_ATT( ntrajid, numberid        , 'long_name', 'iceberg number on this processor' )
+      iret = NF90_PUT_ATT( ntrajid, numberid        , 'units'    , 'count' )
+      iret = NF90_PUT_ATT( ntrajid, nstepid         , 'long_name', 'timestep number kt' )
+      iret = NF90_PUT_ATT( ntrajid, nstepid         , 'units'    , 'count' )
+      iret = NF90_PUT_ATT( ntrajid, nlonid          , 'long_name', 'longitude' )
+      iret = NF90_PUT_ATT( ntrajid, nlonid          , 'units'    , 'degrees_E')
+      iret = NF90_PUT_ATT( ntrajid, nlatid          , 'long_name', 'latitude' )
+      iret = NF90_PUT_ATT( ntrajid, nlatid          , 'units'    , 'degrees_N' )
+      iret = NF90_PUT_ATT( ntrajid, nxid            , 'long_name', 'x grid box position' )
+      iret = NF90_PUT_ATT( ntrajid, nxid            , 'units'    , 'fractional' )
+      iret = NF90_PUT_ATT( ntrajid, nyid            , 'long_name', 'y grid box position' )
+      iret = NF90_PUT_ATT( ntrajid, nyid            , 'units'    , 'fractional' )
+      iret = NF90_PUT_ATT( ntrajid, nuvelid         , 'long_name', 'zonal velocity' )
+      iret = NF90_PUT_ATT( ntrajid, nuvelid         , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nvvelid         , 'long_name', 'meridional velocity' )
+      iret = NF90_PUT_ATT( ntrajid, nvvelid         , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nuoid           , 'long_name', 'ocean u component' )
+      iret = NF90_PUT_ATT( ntrajid, nuoid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nvoid           , 'long_name', 'ocean v component' )
+      iret = NF90_PUT_ATT( ntrajid, nvoid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nuaid           , 'long_name', 'atmosphere u component' )
+      iret = NF90_PUT_ATT( ntrajid, nuaid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nvaid           , 'long_name', 'atmosphere v component' )
+      iret = NF90_PUT_ATT( ntrajid, nvaid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nuiid           , 'long_name', 'sea ice u component' )
+      iret = NF90_PUT_ATT( ntrajid, nuiid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nviid           , 'long_name', 'sea ice v component' )
+      iret = NF90_PUT_ATT( ntrajid, nviid           , 'units'    , 'm/s' )
+      iret = NF90_PUT_ATT( ntrajid, nsshxid         , 'long_name', 'sea surface height gradient from x points' )
+      iret = NF90_PUT_ATT( ntrajid, nsshxid         , 'units'    , 'm/m' )
+      iret = NF90_PUT_ATT( ntrajid, nsshyid         , 'long_name', 'sea surface height gradient from y points' )
+      iret = NF90_PUT_ATT( ntrajid, nsshyid         , 'units'    , 'm/m' )
+      iret = NF90_PUT_ATT( ntrajid, nsstid          , 'long_name', 'sea surface temperature' )
+      iret = NF90_PUT_ATT( ntrajid, nsstid          , 'units'    , 'degC')
+      iret = NF90_PUT_ATT( ntrajid, ncntid          , 'long_name', 'sea ice concentration' )
+      iret = NF90_PUT_ATT( ntrajid, ncntid          , 'units'    , 'degC')
+      iret = NF90_PUT_ATT( ntrajid, nthkid          , 'long_name', 'sea ice thickness' )
+      iret = NF90_PUT_ATT( ntrajid, nthkid          , 'units'    , 'm'   )
+      iret = NF90_PUT_ATT( ntrajid, nmassid         , 'long_name', 'mass')
+      iret = NF90_PUT_ATT( ntrajid, nmassid         , 'units'    , 'kg'  )
+      iret = NF90_PUT_ATT( ntrajid, nthicknessid    , 'long_name', 'thickness' )
+      iret = NF90_PUT_ATT( ntrajid, nthicknessid    , 'units'    , 'm'   )
+      iret = NF90_PUT_ATT( ntrajid, nwidthid        , 'long_name', 'width' )
+      iret = NF90_PUT_ATT( ntrajid, nwidthid        , 'units'    , 'm'    )
+      iret = NF90_PUT_ATT( ntrajid, nlengthid       , 'long_name', 'length' )
+      iret = NF90_PUT_ATT( ntrajid, nlengthid       , 'units'    , 'm'    )
+      iret = NF90_PUT_ATT( ntrajid, nyearid         , 'long_name', 'calendar year' )
+      iret = NF90_PUT_ATT( ntrajid, nyearid         , 'units'    , 'years' )
+      iret = NF90_PUT_ATT( ntrajid, ndayid          , 'long_name', 'day of year' )
+      iret = NF90_PUT_ATT( ntrajid, ndayid          , 'units'    , 'days' )
+      iret = NF90_PUT_ATT( ntrajid, nscaling_id     , 'long_name', 'scaling factor for mass of berg' )
+      iret = NF90_PUT_ATT( ntrajid, nscaling_id     , 'units'    , 'none' )
+      iret = NF90_PUT_ATT( ntrajid, nmass_of_bits_id, 'long_name', 'mass of bergy bits' )
+      iret = NF90_PUT_ATT( ntrajid, nmass_of_bits_id, 'units'    , 'kg'   )
+      iret = NF90_PUT_ATT( ntrajid, nheat_density_id, 'long_name', 'heat density' )
+      iret = NF90_PUT_ATT( ntrajid, nheat_density_id, 'units'    , 'J/kg' )
+      !
+      ! End define mode
+      iret = NF90_ENDDEF( ntrajid )
+      !
+   END SUBROUTINE icb_trj_init
+
+
+   SUBROUTINE icb_trj_write( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_trj_write  ***
+      !!
+      !! ** Purpose :   write out iceberg trajectories
+      !!
+      !! ** Method  : - for the moment write out each snapshot of positions later
+      !!                can rewrite so that it is buffered and written out more efficiently
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! time-step index
+      !
+      INTEGER                ::   iret, jn
+      CHARACTER(len=80)      ::   cl_filename
+      TYPE(iceberg), POINTER ::   this
+      TYPE(point  ), POINTER ::   pt
+      !!----------------------------------------------------------------------
+
+      ! Write variables
+      ! sga - just write out the current point of the trajectory
+
+      this => first_berg
+      jn = num_traj
+      DO WHILE( ASSOCIATED(this) )
+         pt => this%current_point
+         jn = jn + 1
+         !
+         iret = NF90_PUT_VAR( ntrajid, numberid        , this%number      , (/1,jn/) , (/nkounts,1/) )
+         iret = NF90_PUT_VAR( ntrajid, nstepid         , kt               , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nscaling_id     , this%mass_scaling, (/ jn /) )
+         !
+         iret = NF90_PUT_VAR( ntrajid, nlonid          , pt%lon           , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nlatid          , pt%lat           , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nxid            , pt%xi            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nyid            , pt%yj            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nuvelid         , pt%uvel          , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nvvelid         , pt%vvel          , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nuoid           , pt%uo            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nvoid           , pt%vo            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nuaid           , pt%ua            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nvaid           , pt%va            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nuiid           , pt%ui            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nviid           , pt%vi            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nsshxid         , pt%ssh_x         , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nsshyid         , pt%ssh_y         , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nsstid          , pt%sst           , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, ncntid          , pt%cn            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nthkid          , pt%hi            , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nmassid         , pt%mass          , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nthicknessid    , pt%thickness     , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nwidthid        , pt%width         , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nlengthid       , pt%length        , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nyearid         , pt%year          , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, ndayid          , pt%day           , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nmass_of_bits_id, pt%mass_of_bits  , (/ jn /) )
+         iret = NF90_PUT_VAR( ntrajid, nheat_density_id, pt%heat_density  , (/ jn /) )
+         !
+         this => this%next
+      END DO
+      IF( lwp .AND. nn_verbose_level > 0 )   WRITE(numout,*) 'trajectory write to frame ', jn
+      num_traj = jn
+      !
+   END SUBROUTINE icb_trj_write
+
+
+   SUBROUTINE icb_trj_sync()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_trj_sync  ***
+      !!
+      !! ** Purpose :   
+      !!----------------------------------------------------------------------
+      INTEGER ::   iret
+      !!----------------------------------------------------------------------
+      ! flush to file
+      iret = NF90_SYNC( ntrajid )
+      IF ( iret /= NF90_NOERR )   CALL ctl_stop( 'icebergs, icb_trj_sync: nf_sync failed' )
+      !
+   END SUBROUTINE icb_trj_sync
+
+
+   SUBROUTINE icb_trj_end()
+      !!----------------------------------------------------------------------
+      INTEGER ::   iret
+      !!----------------------------------------------------------------------
+      ! Finish up
+      iret = NF90_CLOSE( ntrajid )
+      IF ( iret /= NF90_NOERR )   CALL ctl_stop( 'icebergs, icb_trj_end: nf_close failed' )
+      !
+   END SUBROUTINE icb_trj_end
+
+   !!======================================================================
+END MODULE icbtrj
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbutl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbutl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ICB/icbutl.F90	(revision 14097)
@@ -0,0 +1,826 @@
+MODULE icbutl
+   !!======================================================================
+   !!                       ***  MODULE  icbutl  ***
+   !! Icebergs:  various iceberg utility routines
+   !!======================================================================
+   !! History : 3.3.1 !  2010-01  (Martin&Adcroft) Original code
+   !!            -    !  2011-03  (Madec)          Part conversion to NEMO form
+   !!            -    !                            Removal of mapping from another grid
+   !!            -    !  2011-04  (Alderson)       Split into separate modules
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   icb_utl_interp   :
+   !!   icb_utl_bilin    :
+   !!   icb_utl_bilin_e  :
+   !!----------------------------------------------------------------------
+   USE par_oce                             ! ocean parameters
+   USE dom_oce                             ! ocean domain
+   USE in_out_manager                      ! IO parameters
+   USE lbclnk                              ! lateral boundary condition
+   USE lib_mpp                             ! MPI code and lk_mpp in particular
+   USE icb_oce                             ! define iceberg arrays
+   USE sbc_oce                             ! ocean surface boundary conditions
+#if defined key_si3
+   USE ice,    ONLY: u_ice, v_ice, hm_i    ! SI3 variables
+   USE icevar                              ! ice_var_sshdyn
+   USE sbc_ice, ONLY: snwice_mass, snwice_mass_b
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   icb_utl_copy          ! routine called in icbstp module
+   PUBLIC   icb_utl_interp        ! routine called in icbdyn, icbthm modules
+   PUBLIC   icb_utl_bilin         ! routine called in icbini, icbdyn modules
+   PUBLIC   icb_utl_bilin_x       ! routine called in icbdyn module
+   PUBLIC   icb_utl_add           ! routine called in icbini.F90, icbclv, icblbc and icbrst modules
+   PUBLIC   icb_utl_delete        ! routine called in icblbc, icbthm modules
+   PUBLIC   icb_utl_destroy       ! routine called in icbstp module
+   PUBLIC   icb_utl_track         ! routine not currently used, retain just in case
+   PUBLIC   icb_utl_print_berg    ! routine called in icbthm module
+   PUBLIC   icb_utl_print         ! routine called in icbini, icbstp module
+   PUBLIC   icb_utl_count         ! routine called in icbdia, icbini, icblbc, icbrst modules
+   PUBLIC   icb_utl_incr          ! routine called in icbini, icbclv modules
+   PUBLIC   icb_utl_yearday       ! routine called in icbclv, icbstp module
+   PUBLIC   icb_utl_mass          ! routine called in icbdia module
+   PUBLIC   icb_utl_heat          ! routine called in icbdia module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE icb_utl_copy()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_utl_copy  ***
+      !!
+      !! ** Purpose :   iceberg initialization.
+      !!
+      !! ** Method  : - blah blah
+      !!----------------------------------------------------------------------
+#if defined key_si3
+      REAL(wp), DIMENSION(jpi,jpj) :: zssh_lead_m    !    ocean surface (ssh_m) if ice is not embedded
+      !                                              !    ocean surface in leads if ice is embedded   
+#endif
+      ! copy nemo forcing arrays into iceberg versions with extra halo
+      ! only necessary for variables not on T points
+      ! and ssh which is used to calculate gradients
+
+      uo_e(1:jpi,1:jpj) = ssu_m(:,:) * umask(:,:,1)
+      vo_e(1:jpi,1:jpj) = ssv_m(:,:) * vmask(:,:,1)
+      ff_e(1:jpi,1:jpj) = ff_f (:,:) 
+      tt_e(1:jpi,1:jpj) = sst_m(:,:)
+      ss_e(1:jpi,1:jpj) = sss_m(:,:)
+      fr_e(1:jpi,1:jpj) = fr_i (:,:)
+      ua_e(1:jpi,1:jpj) = utau (:,:) * umask(:,:,1) ! maybe mask useless because mask applied in sbcblk
+      va_e(1:jpi,1:jpj) = vtau (:,:) * vmask(:,:,1) ! maybe mask useless because mask applied in sbcblk
+      !
+      CALL lbc_lnk_icb( 'icbutl', uo_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', vo_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ff_e, 'F', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ua_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', va_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', fr_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', tt_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ss_e, 'T', +1._wp, 1, 1 )
+#if defined key_si3
+      hi_e(1:jpi, 1:jpj) = hm_i (:,:)  
+      ui_e(1:jpi, 1:jpj) = u_ice(:,:)
+      vi_e(1:jpi, 1:jpj) = v_ice(:,:)
+      !      
+      ! compute ssh slope using ssh_lead if embedded
+      zssh_lead_m(:,:) = ice_var_sshdyn(ssh_m, snwice_mass, snwice_mass_b)
+      ssh_e(1:jpi, 1:jpj) = zssh_lead_m(:,:) * tmask(:,:,1)
+      !
+      CALL lbc_lnk_icb( 'icbutl', hi_e , 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', ui_e , 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( 'icbutl', vi_e , 'V', -1._wp, 1, 1 )
+#else
+      ssh_e(1:jpi, 1:jpj) = ssh_m(:,:) * tmask(:,:,1)
+#endif
+      CALL lbc_lnk_icb( 'icbutl', ssh_e, 'T', +1._wp, 1, 1 )
+      !
+   END SUBROUTINE icb_utl_copy
+
+
+   SUBROUTINE icb_utl_interp( pi, pe1, puo, pui, pua, pssh_i,   &
+      &                       pj, pe2, pvo, pvi, pva, pssh_j,   &
+      &                       psst, pcn, phi, pff, psss        )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE icb_utl_interp  ***
+      !!
+      !! ** Purpose :   interpolation
+      !!
+      !! ** Method  : - interpolate from various ocean arrays onto iceberg position
+      !!
+      !!       !!gm  CAUTION here I do not care of the slip/no-slip conditions
+      !!             this can be done later (not that easy to do...)
+      !!             right now, U is 0 in land so that the coastal value of velocity parallel to the coast
+      !!             is half the off shore value, wile the normal-to-the-coast value is zero.
+      !!             This is OK as a starting point.
+      !!       !!pm  HARD CODED: - rho_air now computed in sbcblk (what are the effect ?)
+      !!                         - drag coefficient (should it be namelist parameter ?)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in   ) ::   pi , pj                        ! position in (i,j) referential
+      REAL(wp), INTENT(  out) ::   pe1, pe2                       ! i- and j scale factors
+      REAL(wp), INTENT(  out) ::   puo, pvo, pui, pvi, pua, pva   ! ocean, ice and wind speeds
+      REAL(wp), INTENT(  out) ::   pssh_i, pssh_j                 ! ssh i- & j-gradients
+      REAL(wp), INTENT(  out) ::   psst, pcn, phi, pff, psss      ! SST, ice concentration, ice thickness, Coriolis, SSS
+      !
+      REAL(wp) ::   zcd, zmod       ! local scalars
+      !!----------------------------------------------------------------------
+
+      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', .false.  )    ! ocean velocities
+      pvo  = icb_utl_bilin_h( vo_e, pi, pj, 'V', .false.  )
+      psst = icb_utl_bilin_h( tt_e, pi, pj, 'T', .true.   )    ! SST
+      psss = icb_utl_bilin_h( ss_e, pi, pj, 'T', .true.   )    ! SSS
+      pcn  = icb_utl_bilin_h( fr_e, pi, pj, 'T', .true.   )    ! ice concentration
+      pff  = icb_utl_bilin_h( ff_e, pi, pj, 'F', .false.  )    ! Coriolis parameter
+      !
+      pua  = icb_utl_bilin_h( ua_e, pi, pj, 'U', .true.   )    ! 10m wind
+      pva  = icb_utl_bilin_h( va_e, pi, pj, 'V', .true.   )    ! here (ua,va) are stress => rough conversion from stress to speed
+      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
+      pva  = pva * zmod
+
+#if defined key_si3
+      pui = icb_utl_bilin_h( ui_e , pi, pj, 'U', .false. )    ! sea-ice velocities
+      pvi = icb_utl_bilin_h( vi_e , pi, pj, 'V', .false. )
+      phi = icb_utl_bilin_h( hi_e , pi, pj, 'T', .true.  )    ! ice thickness
+#else
+      pui = 0._wp
+      pvi = 0._wp
+      phi = 0._wp
+#endif
+
+      ! Estimate SSH gradient in i- and j-direction (centred evaluation)
+      pssh_i = ( icb_utl_bilin_h( ssh_e, pi+0.1_wp, pj, 'T', .true. ) -   &
+         &       icb_utl_bilin_h( ssh_e, pi-0.1_wp, pj, 'T', .true. )  ) / ( 0.2_wp * pe1 )
+      pssh_j = ( icb_utl_bilin_h( ssh_e, pi, pj+0.1_wp, 'T', .true. ) -   &
+         &       icb_utl_bilin_h( ssh_e, pi, pj-0.1_wp, 'T', .true. )  ) / ( 0.2_wp * pe2 )
+      !
+   END SUBROUTINE icb_utl_interp
+
+
+   REAL(wp) FUNCTION icb_utl_bilin_h( pfld, pi, pj, cd_type, plmask )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION icb_utl_bilin  ***
+      !!
+      !! ** Purpose :   bilinear interpolation at berg location depending on the grid-point type
+      !!                this version deals with extra halo points
+      !!
+      !!       !!gm  CAUTION an optional argument should be added to handle
+      !!             the slip/no-slip conditions  ==>>> to be done later
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(0:jpi+1,0:jpj+1), INTENT(in) ::   pfld      ! field to be interpolated
+      REAL(wp)                            , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
+      CHARACTER(len=1)                    , INTENT(in) ::   cd_type   ! type of pfld array grid-points: = T , U , V or F points
+      LOGICAL                             , INTENT(in) ::   plmask    ! special treatment of mask point
+      !
+      INTEGER  ::   ii, ij   ! local integer
+      REAL(wp) ::   zi, zj   ! local real
+      REAL(wp) :: zw1, zw2, zw3, zw4
+      REAL(wp), DIMENSION(4) :: zmask
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( cd_type )
+      CASE ( 'T' )
+         ! note that here there is no +0.5 added
+         ! since we're looking for four T points containing quadrant we're in of 
+         ! current T cell
+         ii = MAX(0, INT( pi     ))
+         ij = MAX(0, INT( pj     ))    ! T-point
+         zi = pi - REAL(ii,wp)
+         zj = pj - REAL(ij,wp)
+      CASE ( 'U' )
+         ii = MAX(0, INT( pi-0.5_wp ))
+         ij = MAX(0, INT( pj     ))    ! U-point
+         zi = pi - 0.5_wp - REAL(ii,wp)
+         zj = pj - REAL(ij,wp)
+      CASE ( 'V' )
+         ii = MAX(0, INT( pi     ))
+         ij = MAX(0, INT( pj-0.5_wp ))    ! V-point
+         zi = pi - REAL(ii,wp)
+         zj = pj - 0.5_wp - REAL(ij,wp)
+      CASE ( 'F' )
+         ii = MAX(0, INT( pi-0.5_wp ))
+         ij = MAX(0, INT( pj-0.5_wp ))    ! F-point
+         zi = pi - 0.5_wp - REAL(ii,wp)
+         zj = pj - 0.5_wp - REAL(ij,wp)
+      END SELECT
+      !
+      ! find position in this processor. Prevent near edge problems (see #1389)
+      ! (PM) will be useless if extra halo is used in NEMO
+      !
+      IF    ( ii <= mig(1)-1 ) THEN   ;   ii = 0
+      ELSEIF( ii  > mig(jpi) ) THEN   ;   ii = jpi
+      ELSE                            ;   ii = mi1(ii)
+      ENDIF
+      IF    ( ij <= mjg(1)-1 ) THEN   ;   ij = 0
+      ELSEIF( ij  > mjg(jpj) ) THEN   ;   ij = jpj
+      ELSE                            ;   ij = mj1(ij)
+      ENDIF
+      !
+      ! define mask array 
+      IF (plmask) THEN
+         ! land value is not used in the interpolation
+         SELECT CASE ( cd_type )
+         CASE ( 'T' )
+            zmask = (/tmask_e(ii,ij), tmask_e(ii+1,ij), tmask_e(ii,ij+1), tmask_e(ii+1,ij+1)/)
+         CASE ( 'U' )
+            zmask = (/umask_e(ii,ij), umask_e(ii+1,ij), umask_e(ii,ij+1), umask_e(ii+1,ij+1)/)
+         CASE ( 'V' )
+            zmask = (/vmask_e(ii,ij), vmask_e(ii+1,ij), vmask_e(ii,ij+1), vmask_e(ii+1,ij+1)/)
+         CASE ( 'F' )
+            ! F case only used for coriolis, ff_f is not mask so zmask = 1
+            zmask = 1.
+         END SELECT
+      ELSE
+         ! land value is used during interpolation
+         zmask = 1.
+      END iF
+      !
+      ! compute weight
+      zw1 = zmask(1) * (1._wp-zi) * (1._wp-zj)
+      zw2 = zmask(2) *        zi  * (1._wp-zj)
+      zw3 = zmask(3) * (1._wp-zi) *        zj
+      zw4 = zmask(4) *        zi  *        zj
+      !
+      ! compute interpolated value
+      icb_utl_bilin_h = ( pfld(ii,ij)*zw1 + pfld(ii+1,ij)*zw2 + pfld(ii,ij+1)*zw3 + pfld(ii+1,ij+1)*zw4 ) / MAX(1.e-20, zw1+zw2+zw3+zw4) 
+      !
+   END FUNCTION icb_utl_bilin_h
+
+
+   REAL(wp) FUNCTION icb_utl_bilin( pfld, pi, pj, cd_type )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION icb_utl_bilin  ***
+      !!
+      !! ** Purpose :   bilinear interpolation at berg location depending on the grid-point type
+      !!
+      !!       !!gm  CAUTION an optional argument should be added to handle
+      !!             the slip/no-slip conditions  ==>>> to be done later
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pfld      ! field to be interpolated
+      REAL(wp)                    , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
+      CHARACTER(len=1)            , INTENT(in) ::   cd_type   ! type of pfld array grid-points: = T , U , V or F points
+      !
+      INTEGER  ::   ii, ij   ! local integer
+      REAL(wp) ::   zi, zj   ! local real
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( cd_type )
+         CASE ( 'T' )
+            ! note that here there is no +0.5 added
+            ! since we're looking for four T points containing quadrant we're in of 
+            ! current T cell
+            ii = MAX(1, INT( pi     ))
+            ij = MAX(1, INT( pj     ))    ! T-point
+            zi = pi - REAL(ii,wp)
+            zj = pj - REAL(ij,wp)
+         CASE ( 'U' )
+            ii = MAX(1, INT( pi-0.5 ))
+            ij = MAX(1, INT( pj     ))    ! U-point
+            zi = pi - 0.5 - REAL(ii,wp)
+            zj = pj - REAL(ij,wp)
+         CASE ( 'V' )
+            ii = MAX(1, INT( pi     ))
+            ij = MAX(1, INT( pj-0.5 ))    ! V-point
+            zi = pi - REAL(ii,wp)
+            zj = pj - 0.5 - REAL(ij,wp)
+         CASE ( 'F' )
+            ii = MAX(1, INT( pi-0.5 ))
+            ij = MAX(1, INT( pj-0.5 ))    ! F-point
+            zi = pi - 0.5 - REAL(ii,wp)
+            zj = pj - 0.5 - REAL(ij,wp)
+      END SELECT
+      !
+      ! find position in this processor. Prevent near edge problems (see #1389)
+      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1
+      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi
+      ELSE                           ;   ii = mi1(ii)
+      ENDIF
+      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1
+      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj
+      ELSE                           ;   ij  = mj1(ij)
+      ENDIF
+      !
+      IF( ii == jpi )   ii = ii-1      
+      IF( ij == jpj )   ij = ij-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
+      !
+   END FUNCTION icb_utl_bilin
+
+
+   REAL(wp) FUNCTION icb_utl_bilin_x( pfld, pi, pj )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION icb_utl_bilin_x  ***
+      !!
+      !! ** Purpose :   bilinear interpolation at berg location depending on the grid-point type
+      !!                Special case for interpolating longitude
+      !!
+      !!       !!gm  CAUTION an optional argument should be added to handle
+      !!             the slip/no-slip conditions  ==>>> to be done later
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pfld      ! field to be interpolated
+      REAL(wp)                    , INTENT(in) ::   pi, pj    ! targeted coordinates in (i,j) referential
+      !
+      INTEGER                                  ::   ii, ij   ! local integer
+      REAL(wp)                                 ::   zi, zj   ! local real
+      REAL(wp)                                 ::   zret     ! local real
+      REAL(wp), DIMENSION(4)                   ::   z4
+      !!----------------------------------------------------------------------
+      !
+      ! note that here there is no +0.5 added
+      ! since we're looking for four T points containing quadrant we're in of 
+      ! current T cell
+      ii = MAX(1, INT( pi     ))
+      ij = MAX(1, INT( pj     ))    ! T-point
+      zi = pi - REAL(ii,wp)
+      zj = pj - REAL(ij,wp)
+      !
+      ! find position in this processor. Prevent near edge problems (see #1389)
+      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1
+      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi
+      ELSE                           ;   ii = mi1(ii)
+      ENDIF
+      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1
+      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj
+      ELSE                           ;   ij  = mj1(ij)
+      ENDIF
+      !
+      IF( ii == jpi )   ii = ii-1      
+      IF( ij == jpj )   ij = ij-1
+      !
+      z4(1) = pfld(ii  ,ij  )
+      z4(2) = pfld(ii+1,ij  )
+      z4(3) = pfld(ii  ,ij+1)
+      z4(4) = pfld(ii+1,ij+1)
+      IF( MAXVAL(z4) - MINVAL(z4) > 90._wp ) THEN
+         WHERE( z4 < 0._wp ) z4 = z4 + 360._wp
+      ENDIF
+      !
+      zret = (z4(1) * (1.-zi) + z4(2) * zi) * (1.-zj) + (z4(3) * (1.-zi) + z4(4) * zi) * zj
+      IF( zret > 180._wp ) zret = zret - 360._wp
+      icb_utl_bilin_x = zret
+      !
+   END FUNCTION icb_utl_bilin_x
+
+
+   REAL(wp) FUNCTION icb_utl_bilin_e( pet, peu, pev, pef, pi, pj )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION dom_init  ***
+      !!
+      !! ** Purpose :   bilinear interpolation at berg location of horizontal scale factor
+      !! ** Method  :   interpolation done using the 4 nearest grid points among
+      !!                t-, u-, v-, and f-points.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(in) ::   pet, peu, pev, pef   ! horizontal scale factor to be interpolated at t-,u-,v- & f-pts
+      REAL(wp)                , INTENT(in) ::   pi, pj               ! targeted coordinates in (i,j) referential
+      !
+      INTEGER  ::   ii, ij, icase, ierr   ! local integer
+      !
+      ! weights corresponding to corner points of a T cell quadrant
+      REAL(wp) ::   zi, zj          ! local real
+      !
+      ! values at corner points of a T cell quadrant
+      ! 00 = bottom left, 10 = bottom right, 01 = top left, 11 = top right
+      REAL(wp) ::   ze00, ze10, ze01, ze11
+      !!----------------------------------------------------------------------
+      !
+      ii = MAX(1, INT( pi ))   ;   ij = MAX(1, INT( pj ))            ! left bottom T-point (i,j) indices
+
+      ! fractional box spacing
+      ! 0   <= zi < 0.5, 0   <= zj < 0.5   -->  NW quadrant of current T cell
+      ! 0.5 <= zi < 1  , 0   <= zj < 0.5   -->  NE quadrant
+      ! 0   <= zi < 0.5, 0.5 <= zj < 1     -->  SE quadrant
+      ! 0.5 <= zi < 1  , 0.5 <= zj < 1     -->  SW quadrant
+
+      zi = pi - REAL(ii,wp)          !!gm use here mig, mjg arrays
+      zj = pj - REAL(ij,wp)
+
+      ! find position in this processor. Prevent near edge problems (see #1389)
+      !
+      ierr = 0
+      IF    ( ii < mig( 1 ) ) THEN   ;   ii = 1       ; ierr = ierr + 1
+      ELSEIF( ii > mig(jpi) ) THEN   ;   ii = jpi     ; ierr = ierr + 1
+      ELSE                           ;   ii = mi1(ii)
+      ENDIF
+      IF    ( ij < mjg( 1 ) ) THEN   ;   ij = 1       ; ierr = ierr + 1
+      ELSEIF( ij > mjg(jpj) ) THEN   ;   ij = jpj     ; ierr = ierr + 1
+      ELSE                           ;   ij  = mj1(ij)
+      ENDIF
+      !
+      IF( ii == jpi ) THEN ; ii = ii-1 ; ierr = ierr + 1 ; END IF     
+      IF( ij == jpj ) THEN ; ij = ij-1 ; ierr = ierr + 1 ; END IF
+      !
+      IF ( ierr > 0 ) CALL ctl_stop('STOP','icb_utl_bilin_e: an icebergs coordinates is out of valid range (out of bound error)')
+      !
+      IF(    0.0_wp <= zi .AND. zi < 0.5_wp   ) THEN
+         IF( 0.0_wp <= zj .AND. zj < 0.5_wp        )   THEN        !  NE quadrant
+            !                                                      !             i=I       i=I+1/2
+            ze01 = pev(ii  ,ij  )   ;   ze11 = pef(ii  ,ij  )      !   j=J+1/2    V ------- F
+            ze00 = pet(ii  ,ij  )   ;   ze10 = peu(ii  ,ij  )      !   j=J        T ------- U
+            zi = 2._wp * zi
+            zj = 2._wp * zj
+         ELSE                                                      !  SE quadrant
+            !                                                                    !             i=I       i=I+1/2
+            ze01 = pet(ii  ,ij+1)   ;   ze11 = peu(ii  ,ij+1)      !   j=J+1      T ------- U
+            ze00 = pev(ii  ,ij  )   ;   ze10 = pef(ii  ,ij  )      !   j=J+1/2    V ------- F
+            zi = 2._wp *  zi
+            zj = 2._wp * (zj-0.5_wp)
+         ENDIF
+      ELSE
+         IF( 0.0_wp <= zj .AND. zj < 0.5_wp        )   THEN        !  NW quadrant
+            !                                                                    !             i=I       i=I+1/2
+            ze01 = pef(ii  ,ij  )   ;   ze11 = pev(ii+1,ij)        !   j=J+1/2    F ------- V
+            ze00 = peu(ii  ,ij  )   ;   ze10 = pet(ii+1,ij)        !   j=J        U ------- T
+            zi = 2._wp * (zi-0.5_wp)
+            zj = 2._wp *  zj
+         ELSE                                                      !  SW quadrant
+            !                                                                    !             i=I+1/2   i=I+1
+            ze01 = peu(ii  ,ij+1)   ;   ze11 = pet(ii+1,ij+1)      !   j=J+1      U ------- T
+            ze00 = pef(ii  ,ij  )   ;   ze10 = pev(ii+1,ij  )      !   j=J+1/2    F ------- V
+            zi = 2._wp * (zi-0.5_wp)
+            zj = 2._wp * (zj-0.5_wp)
+         ENDIF
+      ENDIF
+      !
+      icb_utl_bilin_e = ( ze01 * (1._wp-zi) + ze11 * zi ) *        zj    &
+         &            + ( ze00 * (1._wp-zi) + ze10 * zi ) * (1._wp-zj)
+      !
+   END FUNCTION icb_utl_bilin_e
+
+
+   SUBROUTINE icb_utl_add( bergvals, ptvals )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE icb_utl_add           ***
+      !!
+      !! ** Purpose :   add a new berg to the iceberg list
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), INTENT(in)           ::   bergvals
+      TYPE(point)  , INTENT(in)           ::   ptvals
+      !
+      TYPE(iceberg), POINTER ::   new => NULL()
+      !!----------------------------------------------------------------------
+      !
+      new => NULL()
+      CALL icb_utl_create( new, bergvals, ptvals )
+      CALL icb_utl_insert( new )
+      new => NULL()     ! Clear new
+      !
+   END SUBROUTINE icb_utl_add         
+
+
+   SUBROUTINE icb_utl_create( berg, bergvals, ptvals )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE icb_utl_create  ***
+      !!
+      !! ** Purpose :   add a new berg to the iceberg list
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), INTENT(in) ::   bergvals
+      TYPE(point)  , INTENT(in) ::   ptvals
+      TYPE(iceberg), POINTER    ::   berg
+      !
+      TYPE(point)  , POINTER    ::   pt
+      INTEGER                   ::   istat
+      !!----------------------------------------------------------------------
+      !
+      IF( ASSOCIATED(berg) )   CALL ctl_stop( 'icebergs, icb_utl_create: berg already associated' )
+      ALLOCATE(berg, STAT=istat)
+      IF( istat /= 0 ) CALL ctl_stop( 'failed to allocate iceberg' )
+      berg%number(:) = bergvals%number(:)
+      berg%mass_scaling = bergvals%mass_scaling
+      berg%prev => NULL()
+      berg%next => NULL()
+      !
+      ALLOCATE(pt, STAT=istat)
+      IF( istat /= 0 ) CALL ctl_stop( 'failed to allocate first iceberg point' )
+      pt = ptvals
+      berg%current_point => pt
+      !
+   END SUBROUTINE icb_utl_create
+
+
+   SUBROUTINE icb_utl_insert( newberg )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_insert  ***
+      !!
+      !! ** Purpose :   add a new berg to the iceberg list
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER  ::   newberg
+      !
+      TYPE(iceberg), POINTER  ::   this, prev, last
+      !!----------------------------------------------------------------------
+      !
+      IF( ASSOCIATED( first_berg ) ) THEN
+         last => first_berg
+         DO WHILE (ASSOCIATED(last%next))
+            last => last%next
+         ENDDO
+         newberg%prev => last
+         last%next    => newberg
+         last         => newberg
+      ELSE                       ! list is empty so create it
+         first_berg => newberg
+      ENDIF
+      !
+   END SUBROUTINE icb_utl_insert
+
+
+   REAL(wp) FUNCTION icb_utl_yearday(kmon, kday, khr, kmin, ksec)
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION icb_utl_yearday  ***
+      !!
+      !! ** Purpose :   
+      !!
+      ! sga - improved but still only applies to 365 day year, need to do this properly
+      !
+      !!gm  all these info are already known in daymod, no???
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in)     :: kmon, kday, khr, kmin, ksec
+      ! 
+      INTEGER, DIMENSION(12)  :: imonths = (/ 0,31,28,31,30,31,30,31,31,30,31,30 /)
+      !!----------------------------------------------------------------------
+      !
+      icb_utl_yearday = REAL( SUM( imonths(1:kmon) ), wp )
+      icb_utl_yearday = icb_utl_yearday + REAL(kday-1,wp) + (REAL(khr,wp) + (REAL(kmin,wp) + REAL(ksec,wp)/60.)/60.)/24.
+      !
+   END FUNCTION icb_utl_yearday
+
+   !!-------------------------------------------------------------------------
+
+   SUBROUTINE icb_utl_delete( first, berg )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_delete  ***
+      !!
+      !! ** Purpose :   
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER :: first, berg
+      !!----------------------------------------------------------------------
+      ! Connect neighbors to each other
+      IF ( ASSOCIATED(berg%prev) ) THEN
+        berg%prev%next => berg%next
+      ELSE
+        first => berg%next
+      ENDIF
+      IF (ASSOCIATED(berg%next)) berg%next%prev => berg%prev
+      !
+      CALL icb_utl_destroy(berg)
+      !
+   END SUBROUTINE icb_utl_delete
+
+
+   SUBROUTINE icb_utl_destroy( berg )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_destroy  ***
+      !!
+      !! ** Purpose :   remove a single iceberg instance
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER :: berg
+      !!----------------------------------------------------------------------
+      !
+      ! Remove any points
+      IF( ASSOCIATED( berg%current_point ) )   DEALLOCATE( berg%current_point )
+      !
+      DEALLOCATE(berg)
+      !
+   END SUBROUTINE icb_utl_destroy
+
+
+   SUBROUTINE icb_utl_track( knum, cd_label, kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_track  ***
+      !!
+      !! ** Purpose :   
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(nkounts)    :: knum       ! iceberg number
+      CHARACTER(len=*)               :: cd_label   ! 
+      INTEGER                        :: kt         ! timestep number
+      ! 
+      TYPE(iceberg), POINTER         :: this
+      LOGICAL                        :: match
+      INTEGER                        :: k
+      !!----------------------------------------------------------------------
+      !
+      this => first_berg
+      DO WHILE( ASSOCIATED(this) )
+         match = .TRUE.
+         DO k = 1, nkounts
+            IF( this%number(k) /= knum(k) ) match = .FALSE.
+         END DO
+         IF( match )   CALL icb_utl_print_berg(this, kt)
+         this => this%next
+      END DO
+      !
+   END SUBROUTINE icb_utl_track
+
+
+   SUBROUTINE icb_utl_print_berg( berg, kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_print_berg  ***
+      !!
+      !! ** Purpose :   print one
+      !!
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER :: berg
+      TYPE(point)  , POINTER :: pt
+      INTEGER                :: kt      ! timestep number
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      pt => berg%current_point
+      WRITE(numicb, 9200) kt, berg%number(1), &
+                   pt%xi, pt%yj, pt%lon, pt%lat, pt%uvel, pt%vvel,  &
+                   pt%uo, pt%vo, pt%ua, pt%va, pt%ui, pt%vi
+      CALL flush( numicb )
+ 9200 FORMAT(5x,i5,2x,i10,6(2x,2f10.4))
+      !
+   END SUBROUTINE icb_utl_print_berg
+
+
+   SUBROUTINE icb_utl_print( cd_label, kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_print  ***
+      !!
+      !! ** Purpose :   print many
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)       :: cd_label
+      INTEGER                :: kt             ! timestep number
+      ! 
+      INTEGER                :: ibergs, inbergs
+      TYPE(iceberg), POINTER :: this
+      !!----------------------------------------------------------------------
+      !
+      IF (nn_verbose_level == 0) RETURN
+      this => first_berg
+      IF( ASSOCIATED(this) ) THEN
+         WRITE(numicb,'(a," pe=(",i3,")")' ) cd_label, narea
+         WRITE(numicb,'(a8,4x,a6,12x,a5,15x,a7,19x,a3,17x,a5,17x,a5,17x,a5)' )   &
+            &         'timestep', 'number', 'xi,yj','lon,lat','u,v','uo,vo','ua,va','ui,vi'
+      ENDIF
+      DO WHILE( ASSOCIATED(this) )
+        CALL icb_utl_print_berg(this, kt)
+        this => this%next
+      END DO
+      ibergs = icb_utl_count()
+      inbergs = ibergs
+      CALL mpp_sum('icbutl', inbergs)
+      IF( ibergs > 0 )   WRITE(numicb,'(a," there are",i5," bergs out of",i6," on PE ",i4)')   &
+         &                                  cd_label, ibergs, inbergs, narea
+      !
+   END SUBROUTINE icb_utl_print
+
+
+   SUBROUTINE icb_utl_incr()
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE icb_utl_incr  ***
+      !!
+      !! ** Purpose :   
+      !!
+      ! Small routine for coping with very large integer values labelling icebergs
+      ! num_bergs is a array of integers
+      ! the first member is incremented in steps of jpnij starting from narea
+      ! this means each iceberg is labelled with a unique number
+      ! when this gets to the maximum allowed integer the second and subsequent members are 
+      ! used to count how many times the member before cycles
+      !!----------------------------------------------------------------------
+      INTEGER ::   ii, ibig
+      !!----------------------------------------------------------------------
+
+      ibig = HUGE(num_bergs(1))
+      IF( ibig-jpnij < num_bergs(1) ) THEN
+         num_bergs(1) = narea
+         DO ii = 2,nkounts
+            IF( num_bergs(ii) == ibig ) THEN
+               num_bergs(ii) = 0
+               IF( ii == nkounts ) CALL ctl_stop('Sorry, run out of iceberg number space')
+            ELSE
+               num_bergs(ii) = num_bergs(ii) + 1
+               EXIT
+            ENDIF
+         END DO
+      ELSE
+         num_bergs(1) = num_bergs(1) + jpnij
+      ENDIF
+      !
+   END SUBROUTINE icb_utl_incr
+
+
+   INTEGER FUNCTION icb_utl_count()
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION icb_utl_count  ***
+      !!
+      !! ** Purpose :   
+      !!----------------------------------------------------------------------
+      TYPE(iceberg), POINTER :: this
+      !!----------------------------------------------------------------------
+      !
+      icb_utl_count = 0
+      this => first_berg
+      DO WHILE( ASSOCIATED(this) )
+         icb_utl_count = icb_utl_count+1
+         this => this%next
+      END DO
+      !
+   END FUNCTION icb_utl_count
+
+
+   REAL(wp) FUNCTION icb_utl_mass( first, justbits, justbergs )
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION icb_utl_mass  ***
+      !!
+      !! ** Purpose :   compute the mass all iceberg, all berg bits or all bergs.
+      !!----------------------------------------------------------------------
+      TYPE(iceberg)      , POINTER  ::   first
+      TYPE(point)        , POINTER  ::   pt
+      LOGICAL, INTENT(in), OPTIONAL ::   justbits, justbergs
+      !
+      TYPE(iceberg), POINTER ::   this
+      !!----------------------------------------------------------------------
+      icb_utl_mass = 0._wp
+      this => first
+      !
+      IF( PRESENT( justbergs  ) ) THEN
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_mass = icb_utl_mass + pt%mass         * this%mass_scaling
+            this => this%next
+         END DO
+      ELSEIF( PRESENT(justbits) ) THEN
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_mass = icb_utl_mass + pt%mass_of_bits * this%mass_scaling
+            this => this%next
+         END DO
+      ELSE
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_mass = icb_utl_mass + ( pt%mass + pt%mass_of_bits ) * this%mass_scaling
+            this => this%next
+         END DO
+      ENDIF
+      !
+   END FUNCTION icb_utl_mass
+
+
+   REAL(wp) FUNCTION icb_utl_heat( first, justbits, justbergs )
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION icb_utl_heat  ***
+      !!
+      !! ** Purpose :   compute the heat in all iceberg, all bergies or all bergs.
+      !!----------------------------------------------------------------------
+      TYPE(iceberg)      , POINTER  ::   first
+      LOGICAL, INTENT(in), OPTIONAL ::   justbits, justbergs
+      !
+      TYPE(iceberg)      , POINTER  ::   this
+      TYPE(point)        , POINTER  ::   pt
+      !!----------------------------------------------------------------------
+      icb_utl_heat = 0._wp
+      this => first
+      !
+      IF( PRESENT( justbergs  ) ) THEN
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_heat = icb_utl_heat + pt%mass         * this%mass_scaling * pt%heat_density
+            this => this%next
+         END DO
+      ELSEIF( PRESENT(justbits) ) THEN
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_heat = icb_utl_heat + pt%mass_of_bits * this%mass_scaling * pt%heat_density
+            this => this%next
+         END DO
+      ELSE
+         DO WHILE( ASSOCIATED( this ) )
+            pt => this%current_point
+            icb_utl_heat = icb_utl_heat + ( pt%mass + pt%mass_of_bits ) * this%mass_scaling * pt%heat_density
+            this => this%next
+         END DO
+      ENDIF
+      !
+   END FUNCTION icb_utl_heat
+
+   !!======================================================================
+END MODULE icbutl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/in_out_manager.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/in_out_manager.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/in_out_manager.F90	(revision 14097)
@@ -0,0 +1,181 @@
+MODULE in_out_manager   
+   !!======================================================================
+   !!                       ***  MODULE  in_out_manager  ***
+   !! I/O manager utilities : Defines run parameters together with logical units
+   !!=====================================================================
+   !! History :   1.0  !  2002-06  (G. Madec)   original code
+   !!             2.0  !  2006-07  (S. Masson)  iom, add ctl_stop, ctl_warn
+   !!             3.0  !  2008-06  (G. Madec)   add ctmp4 to ctmp10
+   !!             3.2  !  2009-08  (S. MAsson)  add new ctl_opn
+   !!             3.3  !  2010-10  (A. Coward)  add NetCDF4 usage
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   USE par_oce       ! ocean parameter
+   USE nc4interface  ! NetCDF4 interface
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !!----------------------------------------------------------------------
+   !!                   namrun namelist parameters
+   !!----------------------------------------------------------------------
+   CHARACTER(lc) ::   cn_exp           !: experiment name used for output filename
+   CHARACTER(lc) ::   cn_ocerst_in     !: suffix of ocean restart name (input)
+   CHARACTER(lc) ::   cn_ocerst_indir  !: restart input directory
+   CHARACTER(lc) ::   cn_ocerst_out    !: suffix of ocean restart name (output)
+   CHARACTER(lc) ::   cn_ocerst_outdir !: restart output directory
+   LOGICAL       ::   ln_rstart        !: start from (F) rest or (T) a restart file
+   LOGICAL       ::   ln_rst_list      !: output restarts at list of times (T) or by frequency (F)
+   INTEGER       ::   nn_rstctl        !: control of the time step (0, 1 or 2)
+   INTEGER       ::   nn_rstssh   = 0  !: hand made initilization of ssh or not (1/0)
+   INTEGER       ::   nn_it000         !: index of the first time step
+   INTEGER       ::   nn_itend         !: index of the last time step
+   INTEGER       ::   nn_date0         !: initial calendar date aammjj
+   INTEGER       ::   nn_time0         !: initial time of day in hhmm
+   INTEGER       ::   nn_leapy         !: Leap year calendar flag (0/1 or 30)
+   INTEGER       ::   nn_istate        !: initial state output flag (0/1)
+   INTEGER       ::   nn_write         !: model standard output frequency
+   INTEGER       ::   nn_stock         !: restart file frequency
+   INTEGER, DIMENSION(10) :: nn_stocklist  !: restart dump times
+   LOGICAL       ::   ln_mskland       !: mask land points in NetCDF outputs (costly: + ~15%)
+   LOGICAL       ::   ln_cfmeta        !: output additional data to netCDF files required for compliance with the CF metadata standard
+   LOGICAL       ::   ln_clobber       !: clobber (overwrite) an existing file
+   INTEGER       ::   nn_chunksz       !: chunksize (bytes) for NetCDF file (works only with iom_nf90 routines)
+   LOGICAL       ::   ln_xios_read     !: use xios to read single file restart
+   INTEGER       ::   nn_wxios         !: write resart using xios 0 - no, 1 - single, 2 - multiple file output
+   INTEGER       ::   nn_no            !: Assimilation cycle
+
+#if defined key_netcdf4
+   !!----------------------------------------------------------------------
+   !!                   namnc4 namelist parameters                         (key_netcdf4)
+   !!----------------------------------------------------------------------
+   ! The following four values determine the partitioning of the output fields
+   ! into netcdf4 chunks. They are unrelated to the nn_chunk_sz setting which is
+   ! for runtime optimisation. The individual netcdf4 chunks can be optionally 
+   ! gzipped (recommended) leading to significant reductions in I/O volumes 
+   !                         !!!**  variables only used with iom_nf90 routines and key_netcdf4 **
+   INTEGER ::   nn_nchunks_i   !: number of chunks required in the i-dimension 
+   INTEGER ::   nn_nchunks_j   !: number of chunks required in the j-dimension 
+   INTEGER ::   nn_nchunks_k   !: number of chunks required in the k-dimension 
+   INTEGER ::   nn_nchunks_t   !: number of chunks required in the t-dimension 
+   LOGICAL ::   ln_nc4zip      !: netcdf4 usage: (T) chunk and compress output using the HDF5 sublayers of netcdf4
+   !                           !                 (F) ignore chunking request and use the netcdf4 library 
+   !                           !                     to produce netcdf3-compatible files 
+#endif
+
+!$AGRIF_DO_NOT_TREAT
+   TYPE(snc4_ctl)     :: snc4set        !: netcdf4 chunking control structure (always needed for decision making)
+!$AGRIF_END_DO_NOT_TREAT
+
+
+   !! conversion of DOCTOR norm namelist name into model name
+   !! (this should disappear in a near futur)
+
+   CHARACTER(lc) ::   cexper                      !: experiment name used for output filename
+   INTEGER       ::   nrstdt                      !: control of the time step (0, 1 or 2)
+   INTEGER       ::   nit000                      !: index of the first time step
+   INTEGER       ::   nitend                      !: index of the last time step
+   INTEGER       ::   ndate0                      !: initial calendar date aammjj
+   INTEGER       ::   nleapy                      !: Leap year calendar flag (0/1 or 30)
+   INTEGER       ::   ninist                      !: initial state output flag (0/1)
+
+   !!----------------------------------------------------------------------
+   !! was in restart but moved here because of the OFF line... better solution should be found...
+   !!----------------------------------------------------------------------
+   INTEGER ::   nitrst                !: time step at which restart file should be written
+   LOGICAL ::   lrst_oce              !: logical to control the oce restart write 
+   LOGICAL ::   lrst_ice              !: logical to control the ice restart write 
+   INTEGER ::   numror = 0            !: logical unit for ocean restart (read). Init to 0 is needed for SAS (in daymod.F90)
+   INTEGER ::   numrir                !: logical unit for ice   restart (read)
+   INTEGER ::   numrow                !: logical unit for ocean restart (write)
+   INTEGER ::   numriw                !: logical unit for ice   restart (write)
+   INTEGER ::   nrst_lst              !: number of restart to output next
+
+   !!----------------------------------------------------------------------
+   !!                    output monitoring
+   !!----------------------------------------------------------------------
+   LOGICAL ::   ln_ctl           !: run control for debugging
+   TYPE :: sn_ctl                !: optional use structure for finer control over output selection
+      LOGICAL :: l_config  = .FALSE.  !: activate/deactivate finer control
+                                      !  Note if l_config is True then ln_ctl is ignored.
+                                      !  Otherwise setting ln_ctl True is equivalent to setting
+                                      !  all the following logicals in this structure True
+      LOGICAL :: l_runstat = .FALSE.  !: Produce/do not produce run.stat file (T/F)
+      LOGICAL :: l_trcstat = .FALSE.  !: Produce/do not produce tracer.stat file (T/F)
+      LOGICAL :: l_oceout  = .FALSE.  !: Produce all ocean.outputs    (T) or just one (F)
+      LOGICAL :: l_layout  = .FALSE.  !: Produce all layout.dat files (T) or just one (F)
+      LOGICAL :: l_mppout  = .FALSE.  !: Produce/do not produce mpp.output_XXXX files (T/F)
+      LOGICAL :: l_mpptop  = .FALSE.  !: Produce/do not produce mpp.top.output_XXXX files (T/F)
+                                      !  Optional subsetting of processor report files
+                                      !  Default settings of 0/1000000/1 should ensure all areas report.
+                                      !  Set to a more restrictive range to select specific areas
+      INTEGER :: procmin   = 0        !: Minimum narea to output
+      INTEGER :: procmax   = 1000000  !: Maximum narea to output
+      INTEGER :: procincr  = 1        !: narea increment to output
+      INTEGER :: ptimincr  = 1        !: timestep increment to output (time.step and run.stat)
+   END TYPE
+   TYPE(sn_ctl), SAVE :: sn_cfctl     !: run control structure for selective output, must have SAVE for default init. of sn_ctl
+   LOGICAL ::   ln_timing        !: run control for timing
+   LOGICAL ::   ln_diacfl        !: flag whether to create CFL diagnostics
+   INTEGER ::   nn_print         !: level of print (0 no print)
+   INTEGER ::   nn_ictls         !: Start i indice for the SUM control
+   INTEGER ::   nn_ictle         !: End   i indice for the SUM control
+   INTEGER ::   nn_jctls         !: Start j indice for the SUM control
+   INTEGER ::   nn_jctle         !: End   j indice for the SUM control
+   INTEGER ::   nn_isplt         !: number of processors following i
+   INTEGER ::   nn_jsplt         !: number of processors following j
+   !                                          
+   INTEGER ::   nprint, nictls, nictle, njctls, njctle, isplt, jsplt    !: OLD namelist names
+
+   INTEGER ::   ijsplt     =    1      !: nb of local domain = nb of processors
+
+   !!----------------------------------------------------------------------
+   !!                        logical units
+   !!----------------------------------------------------------------------
+   INTEGER ::   numstp          =   -1      !: logical unit for time step
+   INTEGER ::   numtime         =   -1      !: logical unit for timing
+   INTEGER ::   numout          =    6      !: logical unit for output print; Set to stdout to ensure any
+   INTEGER ::   numnul          =   -1      !: logical unit for /dev/null
+      !                                     !  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          =   -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          =   -1      !: logical unit for Output Namelist Ice
+   INTEGER ::   numevo_ice      =   -1      !: logical unit for ice variables (temp. evolution)
+   INTEGER ::   numrun          =   -1      !: logical unit for run statistics
+   INTEGER ::   numdct_in       =   -1      !: logical unit for transports computing
+   INTEGER ::   numdct_vol      =   -1      !: logical unit for voulume transports output
+   INTEGER ::   numdct_heat     =   -1      !: logical unit for heat    transports output
+   INTEGER ::   numdct_salt     =   -1      !: logical unit for salt    transports output
+   INTEGER ::   numfl           =   -1      !: logical unit for floats ascii output
+   INTEGER ::   numflo          =   -1      !: logical unit for floats ascii output
+
+   !!----------------------------------------------------------------------
+   !!                          Run control  
+   !!----------------------------------------------------------------------
+   INTEGER       ::   no_print = 0          !: optional argument of fld_fill (if present, suppress some control print)
+   INTEGER       ::   nstop = 0             !: error flag (=number of reason for a premature stop run)
+!$AGRIF_DO_NOT_TREAT
+   INTEGER       ::   ngrdstop = -1         !: grid number having nstop > 1
+!$AGRIF_END_DO_NOT_TREAT
+   INTEGER       ::   nwarn = 0             !: warning flag (=number of warning found during the run)
+   CHARACTER(lc) ::   ctmp1, ctmp2, ctmp3   !: temporary characters 1 to 3
+   CHARACTER(lc) ::   ctmp4, ctmp5, ctmp6   !: temporary characters 4 to 6
+   CHARACTER(lc) ::   ctmp7, ctmp8, ctmp9   !: temporary characters 7 to 9
+   CHARACTER(lc) ::   ctmp10                !: temporary character 10
+   LOGICAL       ::   lwm      = .FALSE.    !: boolean : true on the 1st processor only (always)
+   LOGICAL       ::   lwp      = .FALSE.    !: boolean : true on the 1st processor only .OR. ln_ctl
+   LOGICAL       ::   lsp_area = .TRUE.     !: to make a control print over a specific area
+   CHARACTER(lc) ::   cxios_context         !: context name used in xios
+   CHARACTER(lc) ::   crxios_context         !: context name used in xios to read restart
+   CHARACTER(lc) ::   cwxios_context        !: context name used in xios to write restart file
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!=====================================================================
+END MODULE in_out_manager
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom.F90	(revision 14097)
@@ -0,0 +1,2469 @@
+MODULE iom
+   !!======================================================================
+   !!                    ***  MODULE  iom ***
+   !! Input/Output manager :  Library to read input files
+   !!======================================================================
+   !! History :  2.0  ! 2005-12  (J. Belier) Original code
+   !!            2.0  ! 2006-02  (S. Masson) Adaptation to NEMO
+   !!            3.0  ! 2007-07  (D. Storkey) Changes to iom_gettime
+   !!            3.4  ! 2012-12  (R. Bourdalle-Badie and G. Reffray)  add C1D case  
+   !!            3.6  ! 2014-15  DIMG format removed
+   !!            3.6  ! 2015-15  (J. Harle) Added procedure to read REAL attributes
+   !!            4.0  ! 2017-11  (M. Andrejczuk) Extend IOM interface to write any 3D fields
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   iom_open       : open a file read only
+   !!   iom_close      : close a file or all files opened by iom
+   !!   iom_get        : read a field (interfaced to several routines)
+   !!   iom_varid      : get the id of a variable in a file
+   !!   iom_rstput     : write a field in a restart file (interfaced to several routines)
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE c1d             ! 1D vertical configuration
+   USE flo_oce         ! floats module declarations
+   USE lbclnk          ! lateal boundary condition / mpp exchanges
+   USE iom_def         ! iom variables definitions
+   USE iom_nf90        ! NetCDF format with native NetCDF library
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp           ! MPP library
+#if defined key_iomput
+   USE sbc_oce  , ONLY :   nn_fsbc         ! ocean space and time domain
+   USE trc_oce  , ONLY :   nn_dttrc        !  !: frequency of step on passive tracers
+   USE icb_oce  , ONLY :   nclasses, class_num       !  !: iceberg classes
+#if defined key_si3
+   USE ice      , ONLY :   jpl
+#endif
+   USE domngb          ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE dianam          ! build name of file
+   USE xios
+# endif
+   USE ioipsl, ONLY :  ju2ymds    ! for calendar
+   USE crs             ! Grid coarsening
+#if defined key_top
+   USE trc, ONLY    :  profsed
+#endif
+   USE lib_fortran 
+   USE diurnal_bulk, ONLY : ln_diurnal_only, ln_diurnal
+
+   IMPLICIT NONE
+   PUBLIC   !   must be public to be able to access iom_def through iom
+   
+#if defined key_iomput
+   LOGICAL, PUBLIC, PARAMETER ::   lk_iomput = .TRUE.        !: iom_put flag
+#else
+   LOGICAL, PUBLIC, PARAMETER ::   lk_iomput = .FALSE.       !: iom_put flag
+#endif
+   PUBLIC iom_init, iom_swap, iom_open, iom_close, iom_setkt, iom_varid, iom_get, iom_get_var
+   PUBLIC iom_chkatt, iom_getatt, iom_putatt, iom_getszuld, iom_rstput, iom_delay_rst, iom_put
+   PUBLIC iom_use, iom_context_finalize, iom_miss_val
+
+   PRIVATE iom_rp0d, iom_rp1d, iom_rp2d, iom_rp3d
+   PRIVATE iom_g0d, iom_g1d, iom_g2d, iom_g3d, iom_get_123d
+   PRIVATE iom_p1d, iom_p2d, iom_p3d, iom_p4d
+#if defined key_iomput
+   PRIVATE iom_set_domain_attr, iom_set_axis_attr, iom_set_field_attr, iom_set_file_attr, iom_get_file_attr, iom_set_grid_attr
+   PRIVATE set_grid, set_grid_bounds, set_scalar, set_xmlatt, set_mooring, iom_update_file_name, iom_sdate
+   PRIVATE iom_set_rst_context, iom_set_rstw_active, iom_set_rstr_active
+# endif
+   PUBLIC iom_set_rstw_var_active, iom_set_rstw_core, iom_set_rst_vars
+
+   INTERFACE iom_get
+      MODULE PROCEDURE iom_g0d, iom_g1d, iom_g2d, iom_g3d
+   END INTERFACE
+   INTERFACE iom_getatt
+      MODULE PROCEDURE iom_g0d_iatt, iom_g1d_iatt, iom_g0d_ratt, iom_g1d_ratt, iom_g0d_catt
+   END INTERFACE
+   INTERFACE iom_putatt
+      MODULE PROCEDURE iom_p0d_iatt, iom_p1d_iatt, iom_p0d_ratt, iom_p1d_ratt, iom_p0d_catt
+   END INTERFACE
+   INTERFACE iom_rstput
+      MODULE PROCEDURE iom_rp0d, iom_rp1d, iom_rp2d, iom_rp3d
+   END INTERFACE
+   INTERFACE iom_put
+      MODULE PROCEDURE iom_p0d, iom_p1d, iom_p2d, iom_p3d, iom_p4d
+   END INTERFACE iom_put
+  
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE iom_init( cdname, fname, ld_tmppatch ) 
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE   ***
+      !!
+      !! ** Purpose :   
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),           INTENT(in)  :: cdname
+      CHARACTER(len=*), OPTIONAL, INTENT(in)  :: fname
+      LOGICAL         , OPTIONAL, INTENT(in)  :: ld_tmppatch
+#if defined key_iomput
+      !
+      TYPE(xios_duration) :: dtime    = xios_duration(0, 0, 0, 0, 0, 0)
+      TYPE(xios_date)     :: start_date
+      CHARACTER(len=lc) :: clname
+      INTEGER             :: irefyear, irefmonth, irefday
+      INTEGER           :: ji
+      LOGICAL :: llrst_context              ! is context related to restart
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zt_bnds, zw_bnds
+      LOGICAL ::   ll_tmppatch = .TRUE.    !: seb: patch before we remove periodicity
+      INTEGER ::   nldi_save, nlei_save    !:      and close boundaries in output files
+      INTEGER ::   nldj_save, nlej_save    !:
+      !!----------------------------------------------------------------------
+      !
+      ! seb: patch before we remove periodicity and close boundaries in output files
+      IF( PRESENT(ld_tmppatch) ) THEN   ;   ll_tmppatch = ld_tmppatch
+      ELSE                              ;   ll_tmppatch = .TRUE.
+      ENDIF
+      IF ( ll_tmppatch ) THEN
+         nldi_save = nldi   ;   nlei_save = nlei
+         nldj_save = nldj   ;   nlej_save = nlej
+         IF( nimpp           ==      1 ) nldi = 1
+         IF( nimpp + jpi - 1 == jpiglo ) nlei = jpi
+         IF( njmpp           ==      1 ) nldj = 1
+         IF( njmpp + jpj - 1 == jpjglo ) nlej = jpj
+      ENDIF
+      !
+      ALLOCATE( zt_bnds(2,jpk), zw_bnds(2,jpk) )
+      !
+      clname = cdname
+      IF( TRIM(Agrif_CFixed()) /= '0' )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(cdname)
+      CALL xios_context_initialize(TRIM(clname), mpi_comm_oce)
+      CALL iom_swap( cdname )
+      llrst_context =  (TRIM(cdname) == TRIM(crxios_context) .OR. TRIM(cdname) == TRIM(cwxios_context))
+
+      ! Calendar type is now defined in xml file 
+      IF (.NOT.(xios_getvar('ref_year' ,irefyear ))) irefyear  = 1900
+      IF (.NOT.(xios_getvar('ref_month',irefmonth))) irefmonth = 01
+      IF (.NOT.(xios_getvar('ref_day'  ,irefday  ))) irefday   = 01
+
+      SELECT CASE ( nleapy )        ! Choose calendar for IOIPSL
+      CASE ( 1)   ; CALL xios_define_calendar( TYPE = "Gregorian", time_origin = xios_date(irefyear,irefmonth,irefday,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      CASE ( 0)   ; CALL xios_define_calendar( TYPE = "NoLeap"   , time_origin = xios_date(irefyear,irefmonth,irefday,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      CASE (30)   ; CALL xios_define_calendar( TYPE = "D360"     , time_origin = xios_date(irefyear,irefmonth,irefday,00,00,00), &
+          &                                    start_date = xios_date(nyear,nmonth,nday,0,0,0) )
+      END SELECT
+
+      ! horizontal grid definition
+      IF(.NOT.llrst_context) CALL set_scalar
+      !
+      IF( TRIM(cdname) == TRIM(cxios_context) ) THEN  
+         CALL set_grid( "T", glamt, gphit, .FALSE., .FALSE. ) 
+         CALL set_grid( "U", glamu, gphiu, .FALSE., .FALSE. )
+         CALL set_grid( "V", glamv, gphiv, .FALSE., .FALSE. )
+         CALL set_grid( "W", glamt, gphit, .FALSE., .FALSE. )
+         CALL set_grid_znl( gphit )
+         !
+         IF( ln_cfmeta ) THEN   ! Add additional grid metadata
+            CALL iom_set_domain_attr("grid_T", area = e1e2t(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_U", area = e1e2u(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_V", area = e1e2v(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_W", area = e1e2t(nldi:nlei, nldj:nlej))
+            CALL set_grid_bounds( "T", glamf, gphif, glamt, gphit )
+            CALL set_grid_bounds( "U", glamv, gphiv, glamu, gphiu )
+            CALL set_grid_bounds( "V", glamu, gphiu, glamv, gphiv )
+            CALL set_grid_bounds( "W", glamf, gphif, glamt, gphit )
+         ENDIF
+      ENDIF
+      !
+      IF( TRIM(cdname) == TRIM(cxios_context)//"_crs" ) THEN  
+         CALL dom_grid_crs   ! Save the parent grid information  & Switch to coarse grid domain
+         !
+         CALL set_grid( "T", glamt_crs, gphit_crs, .FALSE., .FALSE. ) 
+         CALL set_grid( "U", glamu_crs, gphiu_crs, .FALSE., .FALSE. ) 
+         CALL set_grid( "V", glamv_crs, gphiv_crs, .FALSE., .FALSE. ) 
+         CALL set_grid( "W", glamt_crs, gphit_crs, .FALSE., .FALSE. ) 
+         CALL set_grid_znl( gphit_crs )
+          !
+         CALL dom_grid_glo   ! Return to parent grid domain
+         !
+         IF( ln_cfmeta .AND. .NOT. llrst_context) THEN   ! Add additional grid metadata
+            CALL iom_set_domain_attr("grid_T", area = e1e2t_crs(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_U", area = e1u_crs(nldi:nlei, nldj:nlej) * e2u_crs(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_V", area = e1v_crs(nldi:nlei, nldj:nlej) * e2v_crs(nldi:nlei, nldj:nlej))
+            CALL iom_set_domain_attr("grid_W", area = e1e2t_crs(nldi:nlei, nldj:nlej))
+            CALL set_grid_bounds( "T", glamf_crs, gphif_crs, glamt_crs, gphit_crs )
+            CALL set_grid_bounds( "U", glamv_crs, gphiv_crs, glamu_crs, gphiu_crs )
+            CALL set_grid_bounds( "V", glamu_crs, gphiu_crs, glamv_crs, gphiv_crs )
+            CALL set_grid_bounds( "W", glamf_crs, gphif_crs, glamt_crs, gphit_crs )
+         ENDIF
+      ENDIF
+      !
+      ! vertical grid definition
+      IF(.NOT.llrst_context) THEN
+          CALL iom_set_axis_attr( "deptht",  paxis = gdept_1d )
+          CALL iom_set_axis_attr( "depthu",  paxis = gdept_1d )
+          CALL iom_set_axis_attr( "depthv",  paxis = gdept_1d )
+          CALL iom_set_axis_attr( "depthw",  paxis = gdepw_1d )
+
+          ! Add vertical grid bounds
+          zt_bnds(2,:        ) = gdept_1d(:)
+          zt_bnds(1,2:jpk    ) = gdept_1d(1:jpkm1)
+          zt_bnds(1,1        ) = gdept_1d(1) - e3w_1d(1)
+          zw_bnds(1,:        ) = gdepw_1d(:)
+          zw_bnds(2,1:jpkm1  ) = gdepw_1d(2:jpk)
+          zw_bnds(2,jpk:     ) = gdepw_1d(jpk) + e3t_1d(jpk)
+          CALL iom_set_axis_attr( "deptht", bounds=zw_bnds )
+          CALL iom_set_axis_attr( "depthu", bounds=zw_bnds )
+          CALL iom_set_axis_attr( "depthv", bounds=zw_bnds )
+          CALL iom_set_axis_attr( "depthw", bounds=zt_bnds )
+          CALL iom_set_axis_attr( "nfloat", (/ (REAL(ji,wp), ji=1,jpnfl) /) )
+# if defined key_si3
+          CALL iom_set_axis_attr( "ncatice", (/ (REAL(ji,wp), ji=1,jpl) /) )
+          ! SIMIP diagnostics (4 main arctic straits)
+          CALL iom_set_axis_attr( "nstrait", (/ (REAL(ji,wp), ji=1,4) /) )
+# endif
+#if defined key_top
+          IF( ALLOCATED(profsed) ) CALL iom_set_axis_attr( "profsed", paxis = profsed )
+#endif
+          CALL iom_set_axis_attr( "icbcla", class_num )
+          CALL iom_set_axis_attr( "iax_20C", (/ REAL(20,wp) /) )   ! strange syntaxe and idea...
+          CALL iom_set_axis_attr( "iax_26C", (/ REAL(26,wp) /) )   ! strange syntaxe and idea...
+          CALL iom_set_axis_attr( "iax_28C", (/ REAL(28,wp) /) )   ! strange syntaxe and idea...
+          CALL iom_set_axis_attr( "basin"  , (/ (REAL(ji,wp), ji=1,5) /) )
+      ENDIF
+      !
+      ! automatic definitions of some of the xml attributs
+      IF( TRIM(cdname) == TRIM(crxios_context) ) THEN
+!set names of the fields in restart file IF using XIOS to read data
+          CALL iom_set_rst_context(.TRUE.)
+          CALL iom_set_rst_vars(rst_rfields)
+!set which fields are to be read from restart file
+          CALL iom_set_rstr_active()
+      ELSE IF( TRIM(cdname) == TRIM(cwxios_context) ) THEN
+!set names of the fields in restart file IF using XIOS to write data
+          CALL iom_set_rst_context(.FALSE.)
+          CALL iom_set_rst_vars(rst_wfields)
+!set which fields are to be written to a restart file
+          CALL iom_set_rstw_active(fname)
+      ELSE
+          CALL set_xmlatt
+      ENDIF
+      !
+      ! end file definition
+      dtime%second = rdt
+      CALL xios_set_timestep( dtime )
+      CALL xios_close_context_definition()
+      CALL xios_update_calendar( 0 )
+      !
+      DEALLOCATE( zt_bnds, zw_bnds )
+      !
+      IF ( ll_tmppatch ) THEN
+         nldi = nldi_save   ;   nlei = nlei_save
+         nldj = nldj_save   ;   nlej = nlej_save
+      ENDIF
+#endif
+      !
+   END SUBROUTINE iom_init
+
+   SUBROUTINE iom_set_rstw_var_active(field)
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_set_rstw_var_active  ***
+      !!
+      !! ** Purpose :  enable variable in restart file when writing with XIOS 
+      !!---------------------------------------------------------------------
+   CHARACTER(len = *), INTENT(IN) :: field
+   INTEGER :: i
+   LOGICAL :: llis_set
+   CHARACTER(LEN=256) :: clinfo    ! info character
+
+#if defined key_iomput
+   llis_set = .FALSE.
+
+   DO i = 1, max_rst_fields
+       IF(TRIM(rst_wfields(i)%vname) == field) THEN 
+          rst_wfields(i)%active = .TRUE.
+          llis_set = .TRUE.
+          EXIT
+       ENDIF
+   ENDDO
+!Warn if variable is not in defined in rst_wfields
+   IF(.NOT.llis_set) THEN
+      WRITE(ctmp1,*) 'iom_set_rstw_var_active: variable ', field ,' is available for writing but not defined' 
+      CALL ctl_stop( 'iom_set_rstw_var_active:', ctmp1 )
+   ENDIF
+#else
+        clinfo = 'iom_set_rstw_var_active: key_iomput is needed to use XIOS restart read/write functionality'
+        CALL ctl_stop('STOP', TRIM(clinfo))
+#endif
+
+   END SUBROUTINE iom_set_rstw_var_active
+
+   SUBROUTINE iom_set_rstr_active()
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_set_rstr_active  ***
+      !!
+      !! ** Purpose :  define file name in XIOS context for reading restart file,
+      !!               enable variables present in restart file for reading with XIOS 
+      !!---------------------------------------------------------------------
+
+!sets enabled = .TRUE. for each field in restart file
+   CHARACTER(len=256) :: rst_file
+
+#if defined key_iomput
+   TYPE(xios_field) :: field_hdl
+   TYPE(xios_file) :: file_hdl
+   TYPE(xios_filegroup) :: filegroup_hdl
+   INTEGER :: i
+   CHARACTER(lc)  ::   clpath
+
+        clpath = TRIM(cn_ocerst_indir)
+        IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+        IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+           rst_file = TRIM(clpath)//TRIM(cn_ocerst_in)
+        ELSE
+           rst_file = TRIM(clpath)//TRIM(Agrif_CFixed())//'_'//TRIM(cn_ocerst_in)
+        ENDIF
+!set name of the restart file and enable available fields
+        if(lwp) WRITE(numout,*) 'Setting restart filename (for XIOS) to: ',rst_file
+        CALL xios_get_handle("file_definition", filegroup_hdl )
+        CALL xios_add_child(filegroup_hdl, file_hdl, 'rrestart')
+        CALL xios_set_file_attr( "rrestart", name=trim(rst_file), type="one_file", &
+             par_access="collective", enabled=.TRUE., mode="read",                 &
+             output_freq=xios_timestep)
+!define variables for restart context
+        DO i = 1, max_rst_fields
+         IF( TRIM(rst_rfields(i)%vname) /= "NO_NAME") THEN
+           IF( iom_varid( numror, TRIM(rst_rfields(i)%vname), ldstop = .FALSE. ) > 0 ) THEN
+                CALL xios_add_child(file_hdl, field_hdl, TRIM(rst_rfields(i)%vname))
+                SELECT CASE (TRIM(rst_rfields(i)%grid))
+                 CASE ("grid_N_3D")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
+                        domain_ref="grid_N", axis_ref="nav_lev", operation = "instant")
+                 CASE ("grid_N")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
+                        domain_ref="grid_N", operation = "instant") 
+                CASE ("grid_vector")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
+                         axis_ref="nav_lev", operation = "instant")
+                 CASE ("grid_scalar")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_rfields(i)%vname), &
+                        scalar_ref = "grid_scalar", operation = "instant")
+                END SELECT
+                IF(lwp) WRITE(numout,*) 'XIOS read: ', TRIM(rst_rfields(i)%vname), ' enabled in ', TRIM(rst_file)
+           ENDIF
+         ENDIF
+        END DO
+#endif
+   END SUBROUTINE iom_set_rstr_active
+
+   SUBROUTINE iom_set_rstw_core(cdmdl)
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_set_rstw_core  ***
+      !!
+      !! ** Purpose :  set variables which are always in restart file 
+      !!---------------------------------------------------------------------
+   CHARACTER (len=*), INTENT (IN) :: cdmdl ! model OPA or SAS
+   CHARACTER(LEN=256)             :: clinfo    ! info character
+#if defined key_iomput
+   IF(cdmdl == "OPA") THEN
+!from restart.F90
+   CALL iom_set_rstw_var_active("rdt")
+   IF ( .NOT. ln_diurnal_only ) THEN
+        CALL iom_set_rstw_var_active('ub'  )
+        CALL iom_set_rstw_var_active('vb'  )
+        CALL iom_set_rstw_var_active('tb'  )
+        CALL iom_set_rstw_var_active('sb'  )
+        CALL iom_set_rstw_var_active('sshb')
+        !
+        CALL iom_set_rstw_var_active('un'  )
+        CALL iom_set_rstw_var_active('vn'  )
+        CALL iom_set_rstw_var_active('tn'  )
+        CALL iom_set_rstw_var_active('sn'  )
+        CALL iom_set_rstw_var_active('sshn')
+        CALL iom_set_rstw_var_active('rhop')
+     ! extra variable needed for the ice sheet coupling
+        IF ( ln_iscpl ) THEN
+             CALL iom_set_rstw_var_active('tmask')
+             CALL iom_set_rstw_var_active('umask')
+             CALL iom_set_rstw_var_active('vmask')
+             CALL iom_set_rstw_var_active('smask')
+             CALL iom_set_rstw_var_active('e3t_n')
+             CALL iom_set_rstw_var_active('e3u_n')
+             CALL iom_set_rstw_var_active('e3v_n')
+             CALL iom_set_rstw_var_active('gdepw_n')
+        END IF
+      ENDIF
+      IF(ln_diurnal) CALL iom_set_rstw_var_active('Dsst')
+!from trasbc.F90
+         CALL iom_set_rstw_var_active('sbc_hc_b')
+         CALL iom_set_rstw_var_active('sbc_sc_b')
+   ENDIF
+#else
+        clinfo = 'iom_set_rstw_core: key_iomput is needed to use XIOS restart read/write functionality'
+        CALL ctl_stop('STOP', TRIM(clinfo))
+#endif
+   END SUBROUTINE iom_set_rstw_core
+
+   SUBROUTINE iom_set_rst_vars(fields)
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE iom_set_rst_vars   ***
+      !!
+      !! ** Purpose :  Fill array fields with the information about all 
+      !!               possible variables and corresponding grids definition 
+      !!               for reading/writing restart with XIOS
+      !!---------------------------------------------------------------------
+   TYPE(RST_FIELD), INTENT(INOUT) :: fields(max_rst_fields)
+   INTEGER :: i
+
+        i = 0
+        i = i + 1; fields(i)%vname="rdt";            fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="un";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="ub";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="vn";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="vb";             fields(i)%grid="grid_N_3D"  
+        i = i + 1; fields(i)%vname="tn";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="tb";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="sn";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="sb";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="sshn";           fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sshb";           fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="rhop";           fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="kt";             fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="ndastp";         fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="adatrj";         fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="utau_b";         fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vtau_b";         fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="qns_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="emp_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sfx_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="en" ;            fields(i)%grid="grid_N_3D" 
+        i = i + 1; fields(i)%vname="avt_k";            fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="avm_k";            fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="dissl";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="sbc_hc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sbc_sc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="qsr_hc_b";       fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="fraqsr_1lev";    fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="greenland_icesheet_mass"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="greenland_icesheet_timelapsed"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="greenland_icesheet_mass_roc"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="antarctica_icesheet_mass"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="antarctica_icesheet_timelapsed"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="antarctica_icesheet_mass_roc"
+                                               fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="frc_v";          fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="frc_t";          fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="frc_s";          fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="frc_wn_t";       fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="frc_wn_s";       fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="ssh_ini";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="e3t_ini";        fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="hc_loc_ini";     fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="sc_loc_ini";     fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="ssh_hc_loc_ini"; fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ssh_sc_loc_ini"; fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="tilde_e3t_b";    fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="tilde_e3t_n";    fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="hdiv_lf";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ub2_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vb2_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sshbb_e";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ubb_e";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vbb_e";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sshb_e";         fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ub_e";           fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vb_e";           fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="fwf_isf_b";      fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="isf_sc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="isf_hc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ssh_ibb";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="rnf_b";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="rnf_hc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="rnf_sc_b";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="nn_fsbc";        fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="ssu_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ssv_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sst_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="sss_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ssh_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="e3t_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="frq_m";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="avmb";           fields(i)%grid="grid_vector"
+        i = i + 1; fields(i)%vname="avtb";           fields(i)%grid="grid_vector"
+        i = i + 1; fields(i)%vname="ub2_i_b";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vb2_i_b";        fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="ntime";          fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="Dsst";           fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="tmask";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="umask";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="vmask";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="smask";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="gdepw_n";        fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="e3t_n";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="e3u_n";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="e3v_n";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="surf_ini";       fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="e3t_b";          fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="hmxl_n";         fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="un_bf";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="vn_bf";          fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="hbl";            fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="hbli";           fields(i)%grid="grid_N"
+        i = i + 1; fields(i)%vname="wn";             fields(i)%grid="grid_N_3D"
+        i = i + 1; fields(i)%vname="a_fwb_b";        fields(i)%grid="grid_scalar"
+        i = i + 1; fields(i)%vname="a_fwb";          fields(i)%grid="grid_scalar"
+
+        IF( i-1 > max_rst_fields) THEN
+           WRITE(ctmp1,*) 'E R R O R : iom_set_rst_vars SIZE of RST_FIELD array is too small'
+           CALL ctl_stop( 'iom_set_rst_vars:', ctmp1 )
+        ENDIF
+   END SUBROUTINE iom_set_rst_vars
+
+
+   SUBROUTINE iom_set_rstw_active(cdrst_file)
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE iom_set_rstw_active   ***
+      !!
+      !! ** Purpose :  define file name in XIOS context for writing restart
+      !!               enable variables present in restart file for writing
+      !!---------------------------------------------------------------------
+!sets enabled = .TRUE. for each field in restart file
+   CHARACTER(len=*) :: cdrst_file
+#if defined key_iomput
+   TYPE(xios_field) :: field_hdl
+   TYPE(xios_file) :: file_hdl
+   TYPE(xios_filegroup) :: filegroup_hdl
+   INTEGER :: i
+   CHARACTER(lc)  ::   clpath
+
+!set name of the restart file and enable available fields
+        IF(lwp) WRITE(numout,*) 'Setting restart filename (for XIOS write) to: ',cdrst_file
+        CALL xios_get_handle("file_definition", filegroup_hdl )
+        CALL xios_add_child(filegroup_hdl, file_hdl, 'wrestart')
+        IF(nxioso.eq.1) THEN 
+           CALL xios_set_file_attr( "wrestart", type="one_file", enabled=.TRUE.,& 
+                                    mode="write", output_freq=xios_timestep) 
+           if(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in one_file mode' 
+        ELSE  
+           CALL xios_set_file_attr( "wrestart", type="multiple_file", enabled=.TRUE.,& 
+                                    mode="write", output_freq=xios_timestep) 
+           if(lwp) write(numout,*) 'OPEN ', trim(cdrst_file), ' in multiple_file mode' 
+        ENDIF 
+        CALL xios_set_file_attr( "wrestart", name=trim(cdrst_file))
+!define fields for restart context
+        DO i = 1, max_rst_fields
+         IF( rst_wfields(i)%active ) THEN
+                CALL xios_add_child(file_hdl, field_hdl, TRIM(rst_wfields(i)%vname))
+                SELECT CASE (TRIM(rst_wfields(i)%grid))
+                 CASE ("grid_N_3D")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
+                        domain_ref="grid_N", axis_ref="nav_lev", prec = 8, operation = "instant")
+                 CASE ("grid_N")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
+                        domain_ref="grid_N", prec = 8, operation = "instant") 
+                 CASE ("grid_vector")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
+                         axis_ref="nav_lev", prec = 8, operation = "instant")
+                 CASE ("grid_scalar")
+                    CALL xios_set_attr (field_hdl, enabled = .TRUE., name = TRIM(rst_wfields(i)%vname), &
+                        scalar_ref = "grid_scalar", prec = 8, operation = "instant")
+                END SELECT
+         ENDIF
+        END DO
+#endif
+   END SUBROUTINE iom_set_rstw_active
+
+   SUBROUTINE iom_set_rst_context(ld_rstr) 
+     !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_set_rst_context  ***
+      !!
+      !! ** Purpose : Define domain, axis and grid for restart (read/write) 
+      !!              context 
+      !!               
+      !!---------------------------------------------------------------------
+   LOGICAL, INTENT(IN)               :: ld_rstr
+!ld_rstr is true for restart context. There is no need to define grid for 
+!restart read, because it's read from file
+#if defined key_iomput
+   TYPE(xios_domaingroup)            :: domaingroup_hdl 
+   TYPE(xios_domain)                 :: domain_hdl 
+   TYPE(xios_axisgroup)              :: axisgroup_hdl 
+   TYPE(xios_axis)                   :: axis_hdl 
+   TYPE(xios_scalar)                 :: scalar_hdl 
+   TYPE(xios_scalargroup)            :: scalargroup_hdl 
+
+     CALL xios_get_handle("domain_definition",domaingroup_hdl) 
+     CALL xios_add_child(domaingroup_hdl, domain_hdl, "grid_N") 
+     CALL set_grid("N", glamt, gphit, .TRUE., ld_rstr) 
+ 
+     CALL xios_get_handle("axis_definition",axisgroup_hdl) 
+     CALL xios_add_child(axisgroup_hdl, axis_hdl, "nav_lev") 
+!AGRIF fails to compile when unit= is in call to xios_set_axis_attr
+!    CALL xios_set_axis_attr( "nav_lev", long_name="Vertical levels",  unit="m", positive="down") 
+     CALL xios_set_axis_attr( "nav_lev", long_name="Vertical levels in meters", positive="down")
+     CALL iom_set_axis_attr( "nav_lev", paxis = gdept_1d ) 
+
+     CALL xios_get_handle("scalar_definition", scalargroup_hdl) 
+     CALL xios_add_child(scalargroup_hdl, scalar_hdl, "grid_scalar") 
+#endif
+   END SUBROUTINE iom_set_rst_context
+
+   SUBROUTINE iom_swap( cdname )
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_swap  ***
+      !!
+      !! ** Purpose :  swap context between different agrif grid for xmlio_server
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) :: cdname
+#if defined key_iomput
+      TYPE(xios_context) :: nemo_hdl
+
+      IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+        CALL xios_get_handle(TRIM(cdname),nemo_hdl)
+      ELSE
+        CALL xios_get_handle(TRIM(Agrif_CFixed())//"_"//TRIM(cdname),nemo_hdl)
+      ENDIF
+      !
+      CALL xios_set_current_context(nemo_hdl)
+#endif
+      !
+   END SUBROUTINE iom_swap
+
+
+   SUBROUTINE iom_open( cdname, kiomid, ldwrt, kdom, ldstop, ldiof, kdlev )
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_open  ***
+      !!
+      !! ** Purpose :  open an input file (return 0 if not found)
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   )           ::   cdname   ! File name
+      INTEGER         , INTENT(  out)           ::   kiomid   ! iom identifier of the opened file
+      LOGICAL         , INTENT(in   ), OPTIONAL ::   ldwrt    ! open in write modeb          (default = .FALSE.)
+      INTEGER         , INTENT(in   ), OPTIONAL ::   kdom     ! Type of domain to be written (default = jpdom_local_noovlap)
+      LOGICAL         , INTENT(in   ), OPTIONAL ::   ldstop   ! stop if open to read a non-existing file (default = .TRUE.)
+      LOGICAL         , INTENT(in   ), OPTIONAL ::   ldiof    ! Interp On the Fly, needed for AGRIF (default = .FALSE.)
+      INTEGER         , INTENT(in   ), OPTIONAL ::   kdlev    ! number of vertical levels
+      !
+      CHARACTER(LEN=256)    ::   clname    ! the name of the file based on cdname [[+clcpu]+clcpu]
+      CHARACTER(LEN=256)    ::   cltmpn    ! tempory name to store clname (in writting mode)
+      CHARACTER(LEN=10)     ::   clsuffix  ! ".nc" 
+      CHARACTER(LEN=15)     ::   clcpu     ! the cpu number (max jpmax_digits digits)
+      CHARACTER(LEN=256)    ::   clinfo    ! info character
+      LOGICAL               ::   llok      ! check the existence 
+      LOGICAL               ::   llwrt     ! local definition of ldwrt
+      LOGICAL               ::   llnoov    ! local definition to read overlap
+      LOGICAL               ::   llstop    ! local definition of ldstop
+      LOGICAL               ::   lliof     ! local definition of ldiof
+      INTEGER               ::   icnt      ! counter for digits in clcpu (max = jpmax_digits)
+      INTEGER               ::   iln, ils  ! lengths of character
+      INTEGER               ::   idom      ! type of domain
+      INTEGER               ::   istop     ! 
+      INTEGER, DIMENSION(2,5) ::   idompar ! domain parameters: 
+      ! local number of points for x,y dimensions
+      ! position of first local point for x,y dimensions
+      ! position of last local point for x,y dimensions
+      ! start halo size for x,y dimensions
+      ! end halo size for x,y dimensions
+      !---------------------------------------------------------------------
+      ! Initializations and control
+      ! =============
+      kiomid = -1
+      clinfo = '                    iom_open ~~~  '
+      istop = nstop
+      ! if iom_open is called for the first time: initialize iom_file(:)%nfid to 0
+      ! (could be done when defining iom_file in f95 but not in f90)
+      IF( Agrif_Root() ) THEN
+         IF( iom_open_init == 0 ) THEN
+            iom_file(:)%nfid = 0
+            iom_open_init = 1
+         ENDIF
+      ENDIF
+      ! do we read or write the file?
+      IF( PRESENT(ldwrt) ) THEN   ;   llwrt = ldwrt
+      ELSE                        ;   llwrt = .FALSE.
+      ENDIF
+      ! do we call ctl_stop if we try to open a non-existing file in read mode?
+      IF( PRESENT(ldstop) ) THEN   ;   llstop = ldstop
+      ELSE                         ;   llstop = .TRUE.
+      ENDIF
+      ! are we using interpolation on the fly?
+      IF( PRESENT(ldiof) ) THEN   ;   lliof = ldiof
+      ELSE                        ;   lliof = .FALSE.
+      ENDIF
+      ! do we read the overlap 
+      ! ugly patch SM+JMM+RB to overwrite global definition in some cases
+      llnoov = (jpni * jpnj ) == jpnij .AND. .NOT. lk_agrif
+      ! create the file name by added, if needed, TRIM(Agrif_CFixed()) and TRIM(clsuffix)
+      ! =============
+      clname   = trim(cdname)
+      IF ( .NOT. Agrif_Root() .AND. .NOT. lliof ) THEN
+!FUS         iln    = INDEX(clname,'/') 
+         iln    = INDEX(clname,'/',BACK=.true.)  ! FUS: to insert the nest index at the right location within the string, the last / has to be found (search from the right to left)
+         cltmpn = clname(1:iln)
+         clname = clname(iln+1:LEN_TRIM(clname))
+         clname=TRIM(cltmpn)//TRIM(Agrif_CFixed())//'_'//TRIM(clname)
+      ENDIF
+      ! which suffix should we use?
+      clsuffix = '.nc'
+      ! Add the suffix if needed
+      iln = LEN_TRIM(clname)
+      ils = LEN_TRIM(clsuffix)
+      IF( iln <= ils .OR. INDEX( TRIM(clname), TRIM(clsuffix), back = .TRUE. ) /= iln - ils + 1 )   &
+         &   clname = TRIM(clname)//TRIM(clsuffix)
+      cltmpn = clname   ! store this name
+      ! try to find if the file to be opened already exist
+      ! =============
+      INQUIRE( FILE = clname, EXIST = llok )
+      IF( .NOT.llok ) THEN
+         ! we try to add the cpu number to the name
+         WRITE(clcpu,*) narea-1
+
+         clcpu  = TRIM(ADJUSTL(clcpu))
+         iln = INDEX(clname,TRIM(clsuffix), back = .TRUE.)
+         clname = clname(1:iln-1)//'_'//TRIM(clcpu)//TRIM(clsuffix)
+         icnt = 0
+         INQUIRE( FILE = clname, EXIST = llok ) 
+         ! we try different formats for the cpu number by adding 0
+         DO WHILE( .NOT.llok .AND. icnt < jpmax_digits )
+            clcpu  = "0"//trim(clcpu)
+            clname = clname(1:iln-1)//'_'//TRIM(clcpu)//TRIM(clsuffix)
+            INQUIRE( FILE = clname, EXIST = llok )
+            icnt = icnt + 1
+         END DO
+      ELSE
+         lxios_sini = .TRUE.
+      ENDIF
+      IF( llwrt ) THEN
+         ! check the domain definition
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!         idom = jpdom_local_noovlap   ! default definition
+         IF( llnoov ) THEN   ;   idom = jpdom_local_noovlap   ! default definition
+         ELSE                ;   idom = jpdom_local_full      ! default definition
+         ENDIF
+         IF( PRESENT(kdom) )   idom = kdom
+         ! create the domain informations
+         ! =============
+         SELECT CASE (idom)
+         CASE (jpdom_local_full)
+            idompar(:,1) = (/ jpi             , jpj              /)
+            idompar(:,2) = (/ nimpp           , njmpp            /)
+            idompar(:,3) = (/ nimpp + jpi - 1 , njmpp + jpj - 1  /)
+            idompar(:,4) = (/ nldi - 1        , nldj - 1         /)
+            idompar(:,5) = (/ jpi - nlei      , jpj - nlej       /)
+         CASE (jpdom_local_noextra)
+            idompar(:,1) = (/ nlci            , nlcj             /)
+            idompar(:,2) = (/ nimpp           , njmpp            /)
+            idompar(:,3) = (/ nimpp + nlci - 1, njmpp + nlcj - 1 /)
+            idompar(:,4) = (/ nldi - 1        , nldj - 1         /)
+            idompar(:,5) = (/ nlci - nlei     , nlcj - nlej      /)
+         CASE (jpdom_local_noovlap)
+            idompar(:,1) = (/ nlei  - nldi + 1, nlej  - nldj + 1 /)
+            idompar(:,2) = (/ nimpp + nldi - 1, njmpp + nldj - 1 /)
+            idompar(:,3) = (/ nimpp + nlei - 1, njmpp + nlej - 1 /)
+            idompar(:,4) = (/ 0               , 0                /)
+            idompar(:,5) = (/ 0               , 0                /)
+         CASE DEFAULT
+            CALL ctl_stop( TRIM(clinfo), 'wrong value of kdom, only jpdom_local* cases are accepted' )
+         END SELECT
+      ENDIF
+      ! Open the NetCDF file
+      ! =============
+      ! do we have some free file identifier?
+      IF( MINVAL(iom_file(:)%nfid) /= 0 )   &
+         &   CALL ctl_stop( TRIM(clinfo), 'No more free file identifier', 'increase jpmax_files in iom_def' )
+      ! if no file was found...
+      IF( .NOT. llok ) THEN
+         IF( .NOT. llwrt ) THEN   ! we are in read mode 
+            IF( llstop ) THEN   ;   CALL ctl_stop( TRIM(clinfo), 'File '//TRIM(cltmpn)//'* not found' )
+            ELSE                ;   istop = nstop + 1   ! make sure that istop /= nstop so we don't open the file
+            ENDIF
+         ELSE                     ! we are in write mode so we 
+            clname = cltmpn       ! get back the file name without the cpu number
+         ENDIF
+      ELSE
+         IF( llwrt .AND. .NOT. ln_clobber ) THEN   ! we stop as we want to write in a new file 
+            CALL ctl_stop( TRIM(clinfo), 'We want to write in a new file but '//TRIM(clname)//' already exists...' )
+            istop = nstop + 1                      ! make sure that istop /= nstop so we don't open the file
+         ELSEIF( llwrt ) THEN     ! the file exists and we are in write mode with permission to 
+            clname = cltmpn       ! overwrite so get back the file name without the cpu number
+         ENDIF
+      ENDIF
+      IF( istop == nstop ) THEN   ! no error within this routine
+         CALL iom_nf90_open( clname, kiomid, llwrt, llok, idompar, kdlev = kdlev )
+      ENDIF
+      !
+   END SUBROUTINE iom_open
+
+
+   SUBROUTINE iom_close( kiomid )
+      !!--------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_close  ***
+      !!
+      !! ** Purpose : close an input file, or all files opened by iom
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT(inout), OPTIONAL ::   kiomid   ! iom identifier of the file to be closed
+      !                                              ! return 0 when file is properly closed
+      !                                              ! No argument: all files opened by iom are closed
+
+      INTEGER ::   jf         ! dummy loop indices
+      INTEGER ::   i_s, i_e   ! temporary integer
+      CHARACTER(LEN=100)    ::   clinfo    ! info character
+      !---------------------------------------------------------------------
+      !
+      IF( iom_open_init == 0 )   RETURN   ! avoid to use iom_file(jf)%nfid that us not yet initialized
+      !
+      clinfo = '                    iom_close ~~~  '
+      IF( PRESENT(kiomid) ) THEN
+         i_s = kiomid
+         i_e = kiomid
+      ELSE
+         i_s = 1
+         i_e = jpmax_files
+      ENDIF
+
+      IF( i_s > 0 ) THEN
+         DO jf = i_s, i_e
+            IF( iom_file(jf)%nfid > 0 ) THEN
+               CALL iom_nf90_close( jf )
+               iom_file(jf)%nfid       = 0          ! free the id 
+               IF( PRESENT(kiomid) )   kiomid = 0   ! return 0 as id to specify that the file was closed
+               IF(lwp) WRITE(numout,*) TRIM(clinfo)//' close file: '//TRIM(iom_file(jf)%name)//' ok'
+            ELSEIF( PRESENT(kiomid) ) THEN
+               WRITE(ctmp1,*) '--->',  kiomid
+               CALL ctl_stop( TRIM(clinfo)//' Invalid file identifier', ctmp1 )
+            ENDIF
+         END DO
+      ENDIF
+      !    
+   END SUBROUTINE iom_close
+
+
+   FUNCTION iom_varid ( kiomid, cdvar, kdimsz, kndims, lduld, ldstop )  
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION  iom_varid  ***
+      !!
+      !! ** Purpose : get the id of a variable in a file (return 0 if not found)
+      !!-----------------------------------------------------------------------
+      INTEGER              , INTENT(in   )           ::   kiomid   ! file Identifier
+      CHARACTER(len=*)     , INTENT(in   )           ::   cdvar    ! name of the variable
+      INTEGER, DIMENSION(:), INTENT(  out), OPTIONAL ::   kdimsz   ! size of each dimension
+      INTEGER              , INTENT(  out), OPTIONAL ::   kndims   ! number of dimensions
+      LOGICAL              , INTENT(  out), OPTIONAL ::   lduld    ! true if the last dimension is unlimited (time)
+      LOGICAL              , INTENT(in   ), OPTIONAL ::   ldstop   ! stop if looking for non-existing variable (default = .TRUE.)
+      !
+      INTEGER                        ::   iom_varid, iiv, i_nvd
+      LOGICAL                        ::   ll_fnd
+      CHARACTER(LEN=100)             ::   clinfo                   ! info character
+      LOGICAL                        ::   llstop                   ! local definition of ldstop
+      !!-----------------------------------------------------------------------
+      iom_varid = 0                         ! default definition
+      ! do we call ctl_stop if we look for non-existing variable?
+      IF( PRESENT(ldstop) ) THEN   ;   llstop = ldstop
+      ELSE                         ;   llstop = .TRUE.
+      ENDIF
+      !
+      IF( kiomid > 0 ) THEN
+         clinfo = 'iom_varid, file: '//trim(iom_file(kiomid)%name)//', var: '//trim(cdvar)
+         IF( iom_file(kiomid)%nfid == 0 ) THEN 
+            CALL ctl_stop( trim(clinfo), 'the file is not open' )
+         ELSE
+            ll_fnd  = .FALSE.
+            iiv = 0
+            !
+            DO WHILE ( .NOT.ll_fnd .AND. iiv < iom_file(kiomid)%nvars )
+               iiv = iiv + 1
+               ll_fnd  = ( TRIM(cdvar) == TRIM(iom_file(kiomid)%cn_var(iiv)) )
+            END DO
+            !
+            IF( .NOT.ll_fnd ) THEN
+               iiv = iiv + 1
+               IF( iiv <= jpmax_vars ) THEN
+                  iom_varid = iom_nf90_varid( kiomid, cdvar, iiv, kdimsz, kndims, lduld )
+               ELSE
+                  CALL ctl_stop( trim(clinfo), 'Too many variables in the file '//iom_file(kiomid)%name,   &
+                        &                      'increase the parameter jpmax_vars')
+               ENDIF
+               IF( llstop .AND. iom_varid == -1 )   CALL ctl_stop( TRIM(clinfo)//' not found' ) 
+            ELSE
+               iom_varid = iiv
+               IF( PRESENT(kdimsz) ) THEN 
+                  i_nvd = iom_file(kiomid)%ndims(iiv)
+                  IF( i_nvd <= size(kdimsz) ) THEN
+                     kdimsz(1:i_nvd) = iom_file(kiomid)%dimsz(1:i_nvd,iiv)
+                  ELSE
+                     WRITE(ctmp1,*) i_nvd, size(kdimsz)
+                     CALL ctl_stop( trim(clinfo), 'error in kdimsz size'//trim(ctmp1) )
+                  ENDIF
+               ENDIF
+               IF( PRESENT(kndims) )  kndims = iom_file(kiomid)%ndims(iiv)
+               IF( PRESENT( lduld) )  lduld  = iom_file(kiomid)%luld( iiv)
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+   END FUNCTION iom_varid
+
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_get
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_g0d( kiomid, cdvar, pvar, ktime, ldxios )
+      INTEGER         , INTENT(in   )                 ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*), INTENT(in   )                 ::   cdvar     ! Name of the variable
+      REAL(wp)        , INTENT(  out)                 ::   pvar      ! read field
+      INTEGER         , INTENT(in   ),     OPTIONAL   ::   ktime     ! record number
+      LOGICAL         , INTENT(in   ),     OPTIONAL   ::   ldxios    ! use xios to read restart
+      !
+      INTEGER                                         ::   idvar     ! variable id
+      INTEGER                                         ::   idmspc    ! number of spatial dimensions
+      INTEGER         , DIMENSION(1)                  ::   itime     ! record number
+      CHARACTER(LEN=100)                              ::   clinfo    ! info character
+      CHARACTER(LEN=100)                              ::   clname    ! file name
+      CHARACTER(LEN=1)                                ::   cldmspc   !
+      LOGICAL                                         ::   llxios
+      !
+      llxios = .FALSE.
+      IF( PRESENT(ldxios) ) llxios = ldxios
+
+      IF(.NOT.llxios) THEN  ! read data using default library
+         itime = 1
+         IF( PRESENT(ktime) ) itime = ktime
+         !
+         clname = iom_file(kiomid)%name
+         clinfo = '          iom_g0d, file: '//trim(clname)//', var: '//trim(cdvar)
+         !
+         IF( kiomid > 0 ) THEN
+            idvar = iom_varid( kiomid, cdvar )
+            IF( iom_file(kiomid)%nfid > 0 .AND. idvar > 0 ) THEN
+               idmspc = iom_file ( kiomid )%ndims( idvar )
+               IF( iom_file(kiomid)%luld(idvar) )  idmspc = idmspc - 1
+               WRITE(cldmspc , fmt='(i1)') idmspc
+               IF( idmspc > 0 )  CALL ctl_stop( TRIM(clinfo), 'When reading to a 0D array, we do not accept data', &
+                                    &                         'with 1 or more spatial dimensions: '//cldmspc//' were found.' , &
+                                    &                         'Use ncwa -a to suppress the unnecessary dimensions' )
+               CALL iom_nf90_get( kiomid, idvar, pvar, itime )
+            ENDIF
+         ENDIF
+      ELSE
+#if defined key_iomput
+         IF(lwp) WRITE(numout,*) 'XIOS RST READ (0D): ', trim(cdvar)
+         CALL iom_swap( TRIM(crxios_context) )
+         CALL xios_recv_field( trim(cdvar), pvar)
+         CALL iom_swap( TRIM(cxios_context) )
+#else
+         WRITE(ctmp1,*) 'Can not use XIOS in iom_g0d, file: '//trim(clname)//', var:'//trim(cdvar)
+         CALL ctl_stop( 'iom_g0d', ctmp1 )
+#endif
+      ENDIF
+   END SUBROUTINE iom_g0d
+
+   SUBROUTINE iom_g1d( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount, ldxios )
+      INTEGER         , INTENT(in   )                         ::   kiomid    ! Identifier of the file
+      INTEGER         , INTENT(in   )                         ::   kdom      ! Type of domain to be read
+      CHARACTER(len=*), INTENT(in   )                         ::   cdvar     ! Name of the variable
+      REAL(wp)        , INTENT(  out), DIMENSION(:)           ::   pvar      ! read field
+      INTEGER         , INTENT(in   )              , OPTIONAL ::   ktime     ! record number
+      INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kstart    ! start axis position of the reading 
+      INTEGER         , INTENT(in   ), DIMENSION(1), OPTIONAL ::   kcount    ! number of points in each axis
+      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios    ! read data using XIOS
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 ) CALL iom_get_123d( kiomid, kdom       , cdvar        , pv_r1d=pvar,   &
+              &                                                     ktime=ktime, kstart=kstart, kcount=kcount, &
+              &                                                     ldxios=ldxios )
+      ENDIF
+   END SUBROUTINE iom_g1d
+
+   SUBROUTINE iom_g2d( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount, lrowattr, ldxios)
+      INTEGER         , INTENT(in   )                           ::   kiomid    ! Identifier of the file
+      INTEGER         , INTENT(in   )                           ::   kdom      ! Type of domain to be read
+      CHARACTER(len=*), INTENT(in   )                           ::   cdvar     ! Name of the variable
+      REAL(wp)        , INTENT(  out), DIMENSION(:,:)           ::   pvar      ! read field
+      INTEGER         , INTENT(in   )                , OPTIONAL ::   ktime     ! record number
+      INTEGER         , INTENT(in   ), DIMENSION(2)  , OPTIONAL ::   kstart    ! start axis position of the reading 
+      INTEGER         , INTENT(in   ), DIMENSION(2)  , OPTIONAL ::   kcount    ! number of points in each axis
+      LOGICAL         , INTENT(in   )                , OPTIONAL ::   lrowattr  ! logical flag telling iom_get to
+                                                                               ! look for and use a file attribute
+                                                                               ! called open_ocean_jstart to set the start
+                                                                               ! value for the 2nd dimension (netcdf only)
+      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios      ! read data using XIOS
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 ) CALL iom_get_123d( kiomid, kdom       , cdvar        , pv_r2d=pvar,   &
+              &                                                     ktime=ktime, kstart=kstart, kcount=kcount, &
+              &                                                     lrowattr=lrowattr,  ldxios=ldxios)
+      ENDIF
+   END SUBROUTINE iom_g2d
+
+   SUBROUTINE iom_g3d( kiomid, kdom, cdvar, pvar, ktime, kstart, kcount, lrowattr, ldxios )
+      INTEGER         , INTENT(in   )                             ::   kiomid    ! Identifier of the file
+      INTEGER         , INTENT(in   )                             ::   kdom      ! Type of domain to be read
+      CHARACTER(len=*), INTENT(in   )                             ::   cdvar     ! Name of the variable
+      REAL(wp)        , INTENT(  out), DIMENSION(:,:,:)           ::   pvar      ! read field
+      INTEGER         , INTENT(in   )                  , OPTIONAL ::   ktime     ! record number
+      INTEGER         , INTENT(in   ), DIMENSION(3)    , OPTIONAL ::   kstart    ! start axis position of the reading 
+      INTEGER         , INTENT(in   ), DIMENSION(3)    , OPTIONAL ::   kcount    ! number of points in each axis
+      LOGICAL         , INTENT(in   )                  , OPTIONAL ::   lrowattr  ! logical flag telling iom_get to
+                                                                                 ! look for and use a file attribute
+                                                                                 ! called open_ocean_jstart to set the start
+                                                                                 ! value for the 2nd dimension (netcdf only)
+      LOGICAL         , INTENT(in   ),               OPTIONAL ::   ldxios        ! read data using XIOS
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 ) CALL iom_get_123d( kiomid, kdom       , cdvar        , pv_r3d=pvar,   &
+              &                                                     ktime=ktime, kstart=kstart, kcount=kcount, &
+              &                                                     lrowattr=lrowattr, ldxios=ldxios )
+      ENDIF
+   END SUBROUTINE iom_g3d
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE iom_get_123d( kiomid, kdom  , cdvar ,   &
+         &                  pv_r1d, pv_r2d, pv_r3d,   &
+         &                  ktime , kstart, kcount,   &
+         &                  lrowattr, ldxios        )
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_get_123d  ***
+      !!
+      !! ** Purpose : read a 1D/2D/3D variable
+      !!
+      !! ** Method : read ONE record at each CALL
+      !!-----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   )           ::   kiomid     ! Identifier of the file
+      INTEGER                    , INTENT(in   )           ::   kdom       ! Type of domain to be read
+      CHARACTER(len=*)           , INTENT(in   )           ::   cdvar      ! Name of the variable
+      REAL(wp), DIMENSION(:)     , INTENT(  out), OPTIONAL ::   pv_r1d     ! read field (1D case)
+      REAL(wp), DIMENSION(:,:)   , INTENT(  out), OPTIONAL ::   pv_r2d     ! read field (2D case)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(  out), OPTIONAL ::   pv_r3d     ! read field (3D case)
+      INTEGER                    , INTENT(in   ), OPTIONAL ::   ktime      ! record number
+      INTEGER , DIMENSION(:)     , INTENT(in   ), OPTIONAL ::   kstart     ! start position of the reading in each axis 
+      INTEGER , DIMENSION(:)     , INTENT(in   ), OPTIONAL ::   kcount     ! number of points to be read in each axis
+      LOGICAL                    , INTENT(in   ), OPTIONAL ::   lrowattr   ! logical flag telling iom_get to
+                                                                           ! look for and use a file attribute
+                                                                           ! called open_ocean_jstart to set the start
+                                                                           ! value for the 2nd dimension (netcdf only)
+      LOGICAL                    , INTENT(in   ), OPTIONAL ::   ldxios     ! use XIOS to read restart
+      !
+      LOGICAL                        ::   llxios       ! local definition for XIOS read
+      LOGICAL                        ::   llnoov      ! local definition to read overlap
+      LOGICAL                        ::   luse_jattr  ! local definition to read open_ocean_jstart file attribute
+      INTEGER                        ::   jstartrow   ! start point for 2nd dimension optionally set by file attribute
+      INTEGER                        ::   jl          ! loop on number of dimension 
+      INTEGER                        ::   idom        ! type of domain
+      INTEGER                        ::   idvar       ! id of the variable
+      INTEGER                        ::   inbdim      ! number of dimensions of the variable
+      INTEGER                        ::   idmspc      ! number of spatial dimensions 
+      INTEGER                        ::   itime       ! record number
+      INTEGER                        ::   istop       ! temporary value of nstop
+      INTEGER                        ::   ix1, ix2, iy1, iy2   ! subdomain indexes
+      INTEGER                        ::   ji, jj      ! loop counters
+      INTEGER                        ::   irankpv     ! 
+      INTEGER                        ::   ind1, ind2  ! substring index
+      INTEGER, DIMENSION(jpmax_dims) ::   istart      ! starting point to read for each axis
+      INTEGER, DIMENSION(jpmax_dims) ::   icnt        ! number of value to read along each axis 
+      INTEGER, DIMENSION(jpmax_dims) ::   idimsz      ! size of the dimensions of the variable
+      INTEGER, DIMENSION(jpmax_dims) ::   ishape      ! size of the dimensions of the variable
+      REAL(wp)                       ::   zscf, zofs  ! sacle_factor and add_offset
+      INTEGER                        ::   itmp        ! temporary integer
+      CHARACTER(LEN=256)             ::   clinfo      ! info character
+      CHARACTER(LEN=256)             ::   clname      ! file name
+      CHARACTER(LEN=1)               ::   clrankpv, cldmspc      ! 
+      LOGICAL                        ::   ll_depth_spec ! T => if kstart, kcount present then *only* use values for 3rd spatial dimension.
+      INTEGER                        ::   inlev       ! number of levels for 3D data
+      REAL(wp)                       ::   gma, gmi
+      !---------------------------------------------------------------------
+      !
+      inlev = -1
+      IF( PRESENT(pv_r3d) )   inlev = SIZE(pv_r3d, 3)
+      !
+      llxios = .FALSE.
+      if(PRESENT(ldxios)) llxios = ldxios
+      idvar = iom_varid( kiomid, cdvar ) 
+      idom = kdom
+      !
+      IF(.NOT.llxios) THEN
+         clname = iom_file(kiomid)%name   !   esier to read
+         clinfo = '          iom_get_123d, file: '//trim(clname)//', var: '//trim(cdvar)
+         ! local definition of the domain ?
+         ! do we read the overlap 
+         ! ugly patch SM+JMM+RB to overwrite global definition in some cases
+         llnoov = (jpni * jpnj ) == jpnij .AND. .NOT. lk_agrif 
+         ! check kcount and kstart optionals parameters...
+         IF( PRESENT(kcount) .AND. (.NOT. PRESENT(kstart)) ) CALL ctl_stop(trim(clinfo), 'kcount present needs kstart present')
+         IF( PRESENT(kstart) .AND. (.NOT. PRESENT(kcount)) ) CALL ctl_stop(trim(clinfo), 'kstart present needs kcount present')
+         IF( PRESENT(kstart) .AND. idom /= jpdom_unknown .AND.  idom /= jpdom_autoglo_xy  ) &
+     &          CALL ctl_stop(trim(clinfo), 'kstart present needs kdom = jpdom_unknown or kdom = jpdom_autoglo_xy')
+
+         luse_jattr = .false.
+         IF( PRESENT(lrowattr) ) THEN
+            IF( lrowattr .AND. idom /= jpdom_data   ) CALL ctl_stop(trim(clinfo), 'lrowattr present and true needs kdom = jpdom_data')
+            IF( lrowattr .AND. idom == jpdom_data   ) luse_jattr = .true.
+         ENDIF
+
+         ! Search for the variable in the data base (eventually actualize data)
+         istop = nstop
+         !
+         IF( idvar > 0 ) THEN
+            ! to write iom_file(kiomid)%dimsz in a shorter way !
+            idimsz(:) = iom_file(kiomid)%dimsz(:, idvar) 
+            inbdim = iom_file(kiomid)%ndims(idvar)            ! number of dimensions in the file
+            idmspc = inbdim                                   ! number of spatial dimensions in the file
+            IF( iom_file(kiomid)%luld(idvar) )   idmspc = inbdim - 1
+            IF( idmspc > 3 )   CALL ctl_stop(trim(clinfo), 'the file has more than 3 spatial dimensions this case is not coded...') 
+            !
+            ! update idom definition...
+            ! Identify the domain in case of jpdom_auto(glo/dta) definition
+            IF( idom == jpdom_autoglo_xy ) THEN
+               ll_depth_spec = .TRUE.
+               idom = jpdom_autoglo
+            ELSE
+               ll_depth_spec = .FALSE.
+            ENDIF
+            IF( idom == jpdom_autoglo .OR. idom == jpdom_autodta ) THEN            
+               IF( idom == jpdom_autoglo ) THEN   ;   idom = jpdom_global 
+               ELSE                               ;   idom = jpdom_data
+               ENDIF
+               ind1 = INDEX( clname, '_', back = .TRUE. ) + 1
+               ind2 = INDEX( clname, '.', back = .TRUE. ) - 1
+               IF( ind2 > ind1 ) THEN   ;   IF( VERIFY( clname(ind1:ind2), '0123456789' ) == 0 )   idom = jpdom_local   ;   ENDIF
+            ENDIF
+            ! Identify the domain in case of jpdom_local definition
+            IF( idom == jpdom_local ) THEN
+               IF(     idimsz(1) == jpi               .AND. idimsz(2) == jpj               ) THEN   ;   idom = jpdom_local_full
+               ELSEIF( idimsz(1) == nlci              .AND. idimsz(2) == nlcj              ) THEN   ;   idom = jpdom_local_noextra
+               ELSEIF( idimsz(1) == (nlei - nldi + 1) .AND. idimsz(2) == (nlej - nldj + 1) ) THEN   ;   idom = jpdom_local_noovlap
+               ELSE   ;   CALL ctl_stop( trim(clinfo), 'impossible to identify the local domain' )
+               ENDIF
+            ENDIF
+            !
+            ! check the consistency between input array and data rank in the file
+            !
+            ! initializations
+            itime = 1
+            IF( PRESENT(ktime) ) itime = ktime
+            !
+            irankpv = 1 * COUNT( (/PRESENT(pv_r1d)/) ) + 2 * COUNT( (/PRESENT(pv_r2d)/) ) + 3 * COUNT( (/PRESENT(pv_r3d)/) )
+            WRITE(clrankpv, fmt='(i1)') irankpv
+            WRITE(cldmspc , fmt='(i1)') idmspc
+            !
+            IF(     idmspc <  irankpv ) THEN 
+               CALL ctl_stop( TRIM(clinfo), 'The file has only '//cldmspc//' spatial dimension',   &
+                  &                         'it is impossible to read a '//clrankpv//'D array from this file...' )
+            ELSEIF( idmspc == irankpv ) THEN
+               IF( PRESENT(pv_r1d) .AND. idom /= jpdom_unknown )   &
+                  &   CALL ctl_stop( TRIM(clinfo), 'case not coded...You must use jpdom_unknown' )
+            ELSEIF( idmspc >  irankpv ) THEN
+                  IF( PRESENT(pv_r2d) .AND. itime == 1 .AND. idimsz(3) == 1 .AND. idmspc == 3 ) THEN
+                     CALL ctl_warn( trim(clinfo), '2D array but 3 spatial dimensions for the data...'              ,   &
+                           &         'As the size of the z dimension is 1 and as we try to read the first record, ',   &
+                           &         'we accept this case, even if there is a possible mix-up between z and time dimension' )   
+                     idmspc = idmspc - 1
+                  ELSE
+                     CALL ctl_stop( TRIM(clinfo), 'To keep iom lisibility, when reading a '//clrankpv//'D array,'         ,   &
+                        &                         'we do not accept data with '//cldmspc//' spatial dimensions',   &
+                        &                         'Use ncwa -a to suppress the unnecessary dimensions' )
+                  ENDIF
+            ENDIF
+            !
+            ! definition of istart and icnt
+            !
+            icnt  (:) = 1
+            istart(:) = 1
+            istart(idmspc+1) = itime
+   
+            IF( PRESENT(kstart) .AND. .NOT. ll_depth_spec ) THEN 
+               istart(1:idmspc) = kstart(1:idmspc) 
+               icnt  (1:idmspc) = kcount(1:idmspc)
+            ELSE
+               IF(idom == jpdom_unknown ) THEN
+                  icnt(1:idmspc) = idimsz(1:idmspc)
+               ELSE 
+                  IF( .NOT. PRESENT(pv_r1d) ) THEN   !   not a 1D array
+                     IF(     idom == jpdom_data    ) THEN
+                        jstartrow = 1
+                        IF( luse_jattr ) THEN
+                           CALL iom_getatt(kiomid, 'open_ocean_jstart', jstartrow ) ! -999 is returned if the attribute is not found
+                           jstartrow = MAX(1,jstartrow)
+                        ENDIF
+                        istart(1:2) = (/ mig(1), mjg(1) + jstartrow - 1 /)  ! icnt(1:2) done below
+                     ELSEIF( idom == jpdom_global  ) THEN ; istart(1:2) = (/ nimpp , njmpp  /)  ! icnt(1:2) done below
+                     ENDIF
+                     ! we do not read the overlap                     -> we start to read at nldi, nldj
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!                  IF( idom /= jpdom_local_noovlap )   istart(1:2) = istart(1:2) + (/ nldi - 1, nldj - 1 /)
+                     IF( llnoov .AND. idom /= jpdom_local_noovlap ) istart(1:2) = istart(1:2) + (/ nldi - 1, nldj - 1 /)
+                  ! we do not read the overlap and the extra-halos -> from nldi to nlei and from nldj to nlej 
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!                  icnt(1:2) = (/ nlei - nldi + 1, nlej - nldj + 1 /)
+                     IF( llnoov ) THEN   ;   icnt(1:2) = (/ nlei - nldi + 1, nlej - nldj + 1 /)
+                     ELSE                ;   icnt(1:2) = (/ nlci           , nlcj            /)
+                     ENDIF
+                     IF( PRESENT(pv_r3d) ) THEN
+                        IF( idom == jpdom_data ) THEN                        ;                               icnt(3) = inlev
+                        ELSEIF( ll_depth_spec .AND. PRESENT(kstart) ) THEN   ;   istart(3) = kstart(3)   ;   icnt(3) = kcount(3)
+                        ELSE                                                 ;                               icnt(3) = inlev
+                        ENDIF
+                     ENDIF
+                  ENDIF
+               ENDIF
+            ENDIF
+
+            ! check that istart and icnt can be used with this file
+            !-
+            DO jl = 1, jpmax_dims
+               itmp = istart(jl)+icnt(jl)-1
+               IF( itmp > idimsz(jl) .AND. idimsz(jl) /= 0 ) THEN
+                  WRITE( ctmp1, FMT="('(istart(', i1, ') + icnt(', i1, ') - 1) = ', i5)" ) jl, jl, itmp
+                  WRITE( ctmp2, FMT="(' is larger than idimsz(', i1,') = ', i5)"         ) jl, idimsz(jl)
+                  CALL ctl_stop( trim(clinfo), 'start and count too big regarding to the size of the data, ', ctmp1, ctmp2 )     
+               ENDIF
+            END DO
+
+            ! check that icnt matches the input array
+            !-     
+            IF( idom == jpdom_unknown ) THEN
+               IF( irankpv == 1 )        ishape(1:1) = SHAPE(pv_r1d)
+               IF( irankpv == 2 )        ishape(1:2) = SHAPE(pv_r2d)
+               IF( irankpv == 3 )        ishape(1:3) = SHAPE(pv_r3d)
+               ctmp1 = 'd'
+            ELSE
+               IF( irankpv == 2 ) THEN
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!               ishape(1:2) = SHAPE(pv_r2d(nldi:nlei,nldj:nlej  ))   ;   ctmp1 = 'd(nldi:nlei,nldj:nlej)'
+                  IF( llnoov ) THEN ; ishape(1:2)=SHAPE(pv_r2d(nldi:nlei,nldj:nlej  )) ; ctmp1='d(nldi:nlei,nldj:nlej)'
+                  ELSE              ; ishape(1:2)=SHAPE(pv_r2d(1   :nlci,1   :nlcj  )) ; ctmp1='d(1:nlci,1:nlcj)'
+                  ENDIF
+               ENDIF
+               IF( irankpv == 3 ) THEN 
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!               ishape(1:3) = SHAPE(pv_r3d(nldi:nlei,nldj:nlej,:))   ;   ctmp1 = 'd(nldi:nlei,nldj:nlej,:)'
+                  IF( llnoov ) THEN ; ishape(1:3)=SHAPE(pv_r3d(nldi:nlei,nldj:nlej,:)) ; ctmp1='d(nldi:nlei,nldj:nlej,:)'
+                  ELSE              ; ishape(1:3)=SHAPE(pv_r3d(1   :nlci,1   :nlcj,:)) ; ctmp1='d(1:nlci,1:nlcj,:)'
+                  ENDIF
+               ENDIF
+            ENDIF
+         
+            DO jl = 1, irankpv
+               WRITE( ctmp2, FMT="(', ', i1,'): ', i5,' /= icnt(', i1,'):', i5)" ) jl, ishape(jl), jl, icnt(jl)
+               IF( ishape(jl) /= icnt(jl) )   CALL ctl_stop( TRIM(clinfo), 'size(pv_r'//clrankpv//TRIM(ctmp1)//TRIM(ctmp2) )
+            END DO
+
+         ENDIF
+
+         ! read the data
+         !-     
+         IF( idvar > 0 .AND. istop == nstop ) THEN   ! no additional errors until this point...
+            !
+         ! find the right index of the array to be read
+! JMM + SM: ugly patch before getting the new version of lib_mpp)
+!         IF( idom /= jpdom_unknown ) THEN   ;   ix1 = nldi   ;   ix2 = nlei      ;   iy1 = nldj   ;   iy2 = nlej
+!         ELSE                               ;   ix1 = 1      ;   ix2 = icnt(1)   ;   iy1 = 1      ;   iy2 = icnt(2)
+!         ENDIF
+            IF( llnoov ) THEN
+               IF( idom /= jpdom_unknown ) THEN   ;   ix1 = nldi   ;   ix2 = nlei      ;   iy1 = nldj   ;   iy2 = nlej
+               ELSE                               ;   ix1 = 1      ;   ix2 = icnt(1)   ;   iy1 = 1      ;   iy2 = icnt(2)
+               ENDIF
+            ELSE
+               IF( idom /= jpdom_unknown ) THEN   ;   ix1 = 1      ;   ix2 = nlci      ;   iy1 = 1      ;   iy2 = nlcj
+               ELSE                               ;   ix1 = 1      ;   ix2 = icnt(1)   ;   iy1 = 1      ;   iy2 = icnt(2)
+               ENDIF
+            ENDIF
+      
+            CALL iom_nf90_get( kiomid, idvar, inbdim, istart, icnt, ix1, ix2, iy1, iy2, pv_r1d, pv_r2d, pv_r3d )
+
+            IF( istop == nstop ) THEN   ! no additional errors until this point...
+               IF(lwp) WRITE(numout,"(10x,' read ',a,' (rec: ',i6,') in ',a,' ok')") TRIM(cdvar), itime, TRIM(iom_file(kiomid)%name)
+             
+               !--- overlap areas and extra hallows (mpp)
+               IF(     PRESENT(pv_r2d) .AND. idom /= jpdom_unknown ) THEN
+                  CALL lbc_lnk( 'iom', pv_r2d,'Z', -999., kfillmode = jpfillnothing )
+               ELSEIF( PRESENT(pv_r3d) .AND. idom /= jpdom_unknown ) THEN
+                  ! this if could be simplified with the new lbc_lnk that works with any size of the 3rd dimension
+                  IF( icnt(3) == inlev ) THEN
+                     CALL lbc_lnk( 'iom', pv_r3d,'Z', -999., kfillmode = jpfillnothing )
+                  ELSE   ! put some arbitrary value (a call to lbc_lnk will be done later...)
+                     DO jj = nlcj+1, jpj   ;   pv_r3d(1:nlci, jj, :) = pv_r3d(1:nlci, nlej, :)   ;   END DO
+                     DO ji = nlci+1, jpi   ;   pv_r3d(ji    , : , :) = pv_r3d(nlei  , :   , :)   ;   END DO
+                  ENDIF
+               ENDIF
+               !
+            ELSE
+               ! return if istop == nstop is false
+               RETURN
+            ENDIF
+         ELSE
+            ! return if statment idvar > 0 .AND. istop == nstop is false
+            RETURN
+         ENDIF
+         !
+      ELSE        ! read using XIOS. Only if KEY_IOMPUT is defined
+#if defined key_iomput
+!would be good to be able to check which context is active and swap only if current is not restart
+         CALL iom_swap( TRIM(crxios_context) ) 
+         IF( PRESENT(pv_r3d) ) THEN
+            pv_r3d(:, :, :) = 0.
+            if(lwp) write(numout,*) 'XIOS RST READ (3D): ',trim(cdvar)
+            CALL xios_recv_field( trim(cdvar), pv_r3d)
+            IF(idom /= jpdom_unknown ) then
+                CALL lbc_lnk( 'iom', pv_r3d,'Z', -999., kfillmode = jpfillnothing)
+            ENDIF
+         ELSEIF( PRESENT(pv_r2d) ) THEN
+            pv_r2d(:, :) = 0.
+            if(lwp) write(numout,*) 'XIOS RST READ (2D): ', trim(cdvar)
+            CALL xios_recv_field( trim(cdvar), pv_r2d)
+            IF(idom /= jpdom_unknown ) THEN
+                CALL lbc_lnk('iom', pv_r2d,'Z',-999., kfillmode = jpfillnothing)
+            ENDIF
+         ELSEIF( PRESENT(pv_r1d) ) THEN
+            pv_r1d(:) = 0.
+            if(lwp) write(numout,*) 'XIOS RST READ (1D): ', trim(cdvar)
+            CALL xios_recv_field( trim(cdvar), pv_r1d)
+         ENDIF
+         CALL iom_swap( TRIM(cxios_context) )
+#else
+         istop = istop + 1 
+         clinfo = 'Can not use XIOS in iom_get_123d, file: '//trim(clname)//', var:'//trim(cdvar)
+#endif
+      ENDIF
+!some final adjustments
+      ! C1D case : always call lbc_lnk to replicate the central value over the whole 3X3 domain
+      IF( lk_c1d .AND. PRESENT(pv_r2d) )   CALL lbc_lnk( 'iom', pv_r2d,'Z',1. )
+      IF( lk_c1d .AND. PRESENT(pv_r3d) )   CALL lbc_lnk( 'iom', pv_r3d,'Z',1. )
+
+      !--- Apply scale_factor and offset
+      zscf = iom_file(kiomid)%scf(idvar)      ! scale factor
+      zofs = iom_file(kiomid)%ofs(idvar)      ! offset
+      IF(     PRESENT(pv_r1d) ) THEN
+         IF( zscf /= 1. )   pv_r1d(:) = pv_r1d(:) * zscf 
+         IF( zofs /= 0. )   pv_r1d(:) = pv_r1d(:) + zofs
+      ELSEIF( PRESENT(pv_r2d) ) THEN
+         IF( zscf /= 1.)   pv_r2d(:,:) = pv_r2d(:,:) * zscf
+         IF( zofs /= 0.)   pv_r2d(:,:) = pv_r2d(:,:) + zofs
+      ELSEIF( PRESENT(pv_r3d) ) THEN
+         IF( zscf /= 1.)   pv_r3d(:,:,:) = pv_r3d(:,:,:) * zscf
+         IF( zofs /= 0.)   pv_r3d(:,:,:) = pv_r3d(:,:,:) + zofs
+      ENDIF
+      !
+   END SUBROUTINE iom_get_123d
+
+   SUBROUTINE iom_get_var( cdname, z2d)
+      CHARACTER(LEN=*), INTENT(in ) ::   cdname
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d 
+#if defined key_iomput
+      IF( xios_field_is_active( cdname, at_current_timestep_arg = .TRUE. ) ) THEN
+         z2d(:,:) = 0._wp
+         CALL xios_recv_field( cdname, z2d)
+      ENDIF
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, z2d ! useless test to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_get_var
+
+
+   FUNCTION iom_getszuld ( kiomid )  
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION  iom_getszuld  ***
+      !!
+      !! ** Purpose : get the size of the unlimited dimension in a file
+      !!              (return -1 if not found)
+      !!-----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kiomid   ! file Identifier
+      !
+      INTEGER                ::   iom_getszuld
+      !!-----------------------------------------------------------------------
+      iom_getszuld = -1
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%iduld > 0 )   iom_getszuld = iom_file(kiomid)%lenuld
+      ENDIF
+   END FUNCTION iom_getszuld
+   
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_chkatt
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_chkatt( kiomid, cdatt, llok, ksize, cdvar )
+      INTEGER         , INTENT(in   )                 ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*), INTENT(in   )                 ::   cdatt     ! Name of the attribute
+      LOGICAL         , INTENT(  out)                 ::   llok      ! Error code
+      INTEGER         , INTENT(  out), OPTIONAL       ::   ksize     ! Size of the attribute array
+      CHARACTER(len=*), INTENT(in   ), OPTIONAL       ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_chkatt( kiomid, cdatt, llok, ksize=ksize, cdvar=cdvar )
+      ENDIF
+      !
+   END SUBROUTINE iom_chkatt
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_getatt
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_g0d_iatt( kiomid, cdatt, katt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      INTEGER               , INTENT(  out)           ::   katt0d    ! read field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_getatt( kiomid, cdatt,  katt0d =  katt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_g0d_iatt
+
+   SUBROUTINE iom_g1d_iatt( kiomid, cdatt, katt1d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      INTEGER, DIMENSION(:) , INTENT(  out)           ::   katt1d    ! read field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_getatt( kiomid, cdatt,  katt1d =  katt1d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_g1d_iatt
+
+   SUBROUTINE iom_g0d_ratt( kiomid, cdatt, patt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      REAL(wp)              , INTENT(  out)           ::   patt0d    ! read field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_getatt( kiomid, cdatt,  patt0d =  patt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_g0d_ratt
+
+   SUBROUTINE iom_g1d_ratt( kiomid, cdatt, patt1d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      REAL(wp), DIMENSION(:), INTENT(  out)           ::   patt1d    ! read field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_getatt( kiomid, cdatt,  patt1d =  patt1d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_g1d_ratt
+   
+   SUBROUTINE iom_g0d_catt( kiomid, cdatt, cdatt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      CHARACTER(len=*)      , INTENT(  out)           ::   cdatt0d   ! read field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_getatt( kiomid, cdatt, cdatt0d = cdatt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_g0d_catt
+
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_putatt
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_p0d_iatt( kiomid, cdatt, katt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      INTEGER               , INTENT(in   )           ::   katt0d    ! written field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_putatt( kiomid, cdatt,  katt0d =  katt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_p0d_iatt
+
+   SUBROUTINE iom_p1d_iatt( kiomid, cdatt, katt1d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      INTEGER, DIMENSION(:) , INTENT(in   )           ::   katt1d    ! written field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_putatt( kiomid, cdatt,  katt1d =  katt1d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_p1d_iatt
+
+   SUBROUTINE iom_p0d_ratt( kiomid, cdatt, patt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      REAL(wp)              , INTENT(in   )           ::   patt0d    ! written field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_putatt( kiomid, cdatt,  patt0d =  patt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_p0d_ratt
+
+   SUBROUTINE iom_p1d_ratt( kiomid, cdatt, patt1d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      REAL(wp), DIMENSION(:), INTENT(in   )           ::   patt1d    ! written field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_putatt( kiomid, cdatt,  patt1d =  patt1d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_p1d_ratt
+   
+   SUBROUTINE iom_p0d_catt( kiomid, cdatt, cdatt0d, cdvar )
+      INTEGER               , INTENT(in   )           ::   kiomid    ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt     ! Name of the attribute
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt0d   ! written field
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar     ! Name of the variable
+      !
+      IF( kiomid > 0 ) THEN
+         IF( iom_file(kiomid)%nfid > 0 )   CALL iom_nf90_putatt( kiomid, cdatt, cdatt0d = cdatt0d, cdvar=cdvar )
+      ENDIF
+   END SUBROUTINE iom_p0d_catt
+
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_rstput
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_rp0d( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+      INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
+      INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
+      INTEGER         , INTENT(in)                         ::   kiomid   ! Identifier of the file 
+      CHARACTER(len=*), INTENT(in)                         ::   cdvar    ! time axis name
+      REAL(wp)        , INTENT(in)                         ::   pvar     ! written field
+      INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
+      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
+      LOGICAL :: llx                ! local xios write flag
+      INTEGER :: ivid   ! variable id
+
+      llx = .FALSE.
+      IF(PRESENT(ldxios)) llx = ldxios
+      IF( llx ) THEN
+#ifdef key_iomput
+      IF( kt == kwrite ) THEN
+          IF(lwp) write(numout,*) 'RESTART: write (XIOS 0D) ',trim(cdvar)
+          CALL xios_send_field(trim(cdvar), pvar)
+      ENDIF
+#endif
+      ELSE
+         IF( kiomid > 0 ) THEN
+            IF( iom_file(kiomid)%nfid > 0 ) THEN
+               ivid = iom_varid( kiomid, cdvar, ldstop = .FALSE. )
+               CALL iom_nf90_rstput( kt, kwrite, kiomid, cdvar, ivid, ktype, pv_r0d = pvar )
+            ENDIF
+         ENDIF
+      ENDIF
+   END SUBROUTINE iom_rp0d
+
+   SUBROUTINE iom_rp1d( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+      INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
+      INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
+      INTEGER         , INTENT(in)                         ::   kiomid   ! Identifier of the file 
+      CHARACTER(len=*), INTENT(in)                         ::   cdvar    ! time axis name
+      REAL(wp)        , INTENT(in), DIMENSION(          :) ::   pvar     ! written field
+      INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
+      LOGICAL, OPTIONAL                                    ::   ldxios   ! xios write flag
+      LOGICAL :: llx                ! local xios write flag
+      INTEGER :: ivid   ! variable id
+
+      llx = .FALSE.
+      IF(PRESENT(ldxios)) llx = ldxios
+      IF( llx ) THEN
+#ifdef key_iomput
+      IF( kt == kwrite ) THEN
+         IF(lwp) write(numout,*) 'RESTART: write (XIOS 1D) ',trim(cdvar)
+         CALL xios_send_field(trim(cdvar), pvar)
+      ENDIF
+#endif
+      ELSE
+         IF( kiomid > 0 ) THEN
+            IF( iom_file(kiomid)%nfid > 0 ) THEN
+               ivid = iom_varid( kiomid, cdvar, ldstop = .FALSE. )
+               CALL iom_nf90_rstput( kt, kwrite, kiomid, cdvar, ivid, ktype, pv_r1d = pvar )
+            ENDIF
+         ENDIF
+      ENDIF
+   END SUBROUTINE iom_rp1d
+
+   SUBROUTINE iom_rp2d( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+      INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
+      INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
+      INTEGER         , INTENT(in)                         ::   kiomid   ! Identifier of the file 
+      CHARACTER(len=*), INTENT(in)                         ::   cdvar    ! time axis name
+      REAL(wp)        , INTENT(in), DIMENSION(:,    :    ) ::   pvar     ! written field
+      INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
+      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
+      LOGICAL :: llx
+      INTEGER :: ivid   ! variable id
+
+      llx = .FALSE.
+      IF(PRESENT(ldxios)) llx = ldxios
+      IF( llx ) THEN
+#ifdef key_iomput
+      IF( kt == kwrite ) THEN
+         IF(lwp) write(numout,*) 'RESTART: write (XIOS 2D) ',trim(cdvar)
+         CALL xios_send_field(trim(cdvar), pvar)
+      ENDIF
+#endif
+      ELSE
+         IF( kiomid > 0 ) THEN
+            IF( iom_file(kiomid)%nfid > 0 ) THEN
+               ivid = iom_varid( kiomid, cdvar, ldstop = .FALSE. )
+               CALL iom_nf90_rstput( kt, kwrite, kiomid, cdvar, ivid, ktype, pv_r2d = pvar )
+            ENDIF
+         ENDIF
+      ENDIF
+   END SUBROUTINE iom_rp2d
+
+   SUBROUTINE iom_rp3d( kt, kwrite, kiomid, cdvar, pvar, ktype, ldxios )
+      INTEGER         , INTENT(in)                         ::   kt       ! ocean time-step
+      INTEGER         , INTENT(in)                         ::   kwrite   ! writing time-step
+      INTEGER         , INTENT(in)                         ::   kiomid   ! Identifier of the file 
+      CHARACTER(len=*), INTENT(in)                         ::   cdvar    ! time axis name
+      REAL(wp)        , INTENT(in),       DIMENSION(:,:,:) ::   pvar     ! written field
+      INTEGER         , INTENT(in), OPTIONAL               ::   ktype    ! variable external type
+      LOGICAL, OPTIONAL :: ldxios   ! xios write flag
+      LOGICAL :: llx                 ! local xios write flag
+      INTEGER :: ivid   ! variable id
+
+      llx = .FALSE.
+      IF(PRESENT(ldxios)) llx = ldxios
+      IF( llx ) THEN
+#ifdef key_iomput
+      IF( kt == kwrite ) THEN
+         IF(lwp) write(numout,*) 'RESTART: write (XIOS 3D) ',trim(cdvar)
+         CALL xios_send_field(trim(cdvar), pvar)
+      ENDIF
+#endif
+      ELSE
+         IF( kiomid > 0 ) THEN
+            IF( iom_file(kiomid)%nfid > 0 ) THEN
+               ivid = iom_varid( kiomid, cdvar, ldstop = .FALSE. )
+               CALL iom_nf90_rstput( kt, kwrite, kiomid, cdvar, ivid, ktype, pv_r3d = pvar )
+            ENDIF
+         ENDIF
+      ENDIF
+   END SUBROUTINE iom_rp3d
+
+
+  SUBROUTINE iom_delay_rst( cdaction, cdcpnt, kncid )
+      !!---------------------------------------------------------------------
+      !!   Routine iom_delay_rst: used read/write restart related to mpp_delay
+      !!
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   ) ::   cdaction        !
+      CHARACTER(len=*), INTENT(in   ) ::   cdcpnt
+      INTEGER         , INTENT(in   ) ::   kncid
+      !
+      INTEGER  :: ji
+      INTEGER  :: indim
+      LOGICAL  :: llattexist
+      REAL(wp), ALLOCATABLE, DIMENSION(:) ::   zreal1d
+      !!---------------------------------------------------------------------
+      !
+      !                                      ===================================
+      IF( TRIM(cdaction) == 'READ' ) THEN   ! read restart related to mpp_delay !
+         !                                   ===================================
+         DO ji = 1, nbdelay
+            IF ( c_delaycpnt(ji) == cdcpnt ) THEN
+               CALL iom_chkatt( kncid, 'DELAY_'//c_delaylist(ji), llattexist, indim )
+               IF( llattexist )  THEN
+                  ALLOCATE( todelay(ji)%z1d(indim) )
+                  CALL iom_getatt( kncid, 'DELAY_'//c_delaylist(ji), todelay(ji)%z1d(:) )
+                  ndelayid(ji) = 0   ! set to 0 to specify that the value was read in the restart
+               ENDIF
+           ENDIF
+         END DO
+         !                                   ====================================
+      ELSE                                  ! write restart related to mpp_delay !
+         !                                   ====================================
+         DO ji = 1, nbdelay   ! save only ocean delayed global communication variables
+            IF ( c_delaycpnt(ji) == cdcpnt ) THEN
+               IF( ASSOCIATED(todelay(ji)%z1d) ) THEN
+                  CALL mpp_delay_rcv(ji)   ! make sure %z1d is received
+                  CALL iom_putatt( kncid, 'DELAY_'//c_delaylist(ji), todelay(ji)%z1d(:) )
+               ENDIF
+            ENDIF
+         END DO
+         !
+      ENDIF
+      
+   END SUBROUTINE iom_delay_rst
+  
+   
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_put
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_p0d( cdname, pfield0d )
+      CHARACTER(LEN=*), INTENT(in) ::   cdname
+      REAL(wp)        , INTENT(in) ::   pfield0d
+!!      REAL(wp)        , DIMENSION(jpi,jpj) ::   zz     ! masson
+#if defined key_iomput
+!!clem      zz(:,:)=pfield0d
+!!clem      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
+#endif
+   END SUBROUTINE iom_p0d
+
+   SUBROUTINE iom_p1d( cdname, pfield1d )
+      CHARACTER(LEN=*)          , INTENT(in) ::   cdname
+      REAL(wp),     DIMENSION(:), INTENT(in) ::   pfield1d
+#if defined key_iomput
+      CALL xios_send_field( cdname, RESHAPE( (/pfield1d/), (/1,1,SIZE(pfield1d)/) ) )
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, pfield1d   ! useless test to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_p1d
+
+   SUBROUTINE iom_p2d( cdname, pfield2d )
+      CHARACTER(LEN=*)            , INTENT(in) ::   cdname
+      REAL(wp),     DIMENSION(:,:), INTENT(in) ::   pfield2d
+#if defined key_iomput
+      CALL xios_send_field(cdname, pfield2d)
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, pfield2d   ! useless test to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_p2d
+
+   SUBROUTINE iom_p3d( cdname, pfield3d )
+      CHARACTER(LEN=*)                , INTENT(in) ::   cdname
+      REAL(wp),       DIMENSION(:,:,:), INTENT(in) ::   pfield3d
+#if defined key_iomput
+      CALL xios_send_field( cdname, pfield3d )
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, pfield3d   ! useless test to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_p3d
+
+   SUBROUTINE iom_p4d( cdname, pfield4d )
+      CHARACTER(LEN=*)                  , INTENT(in) ::   cdname
+      REAL(wp),       DIMENSION(:,:,:,:), INTENT(in) ::   pfield4d
+#if defined key_iomput
+      CALL xios_send_field(cdname, pfield4d)
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, pfield4d   ! useless test to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_p4d
+
+
+#if defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_iomput'                                         XIOS interface
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE iom_set_domain_attr( cdid, ni_glo, nj_glo, ibegin, jbegin, ni, nj,                                               &
+      &                                    data_dim, data_ibegin, data_ni, data_jbegin, data_nj, lonvalue, latvalue, mask,     &
+      &                                    nvertex, bounds_lon, bounds_lat, area )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)                  , INTENT(in) ::   cdid
+      INTEGER                 , OPTIONAL, INTENT(in) ::   ni_glo, nj_glo, ibegin, jbegin, ni, nj
+      INTEGER                 , OPTIONAL, INTENT(in) ::   data_dim, data_ibegin, data_ni, data_jbegin, data_nj
+      INTEGER                 , OPTIONAL, INTENT(in) ::   nvertex
+      REAL(wp), DIMENSION(:)  , OPTIONAL, INTENT(in) ::   lonvalue, latvalue
+      REAL(wp), DIMENSION(:,:), OPTIONAL, INTENT(in) ::   bounds_lon, bounds_lat, area
+      LOGICAL , DIMENSION(:)  , OPTIONAL, INTENT(in) ::   mask
+      !!----------------------------------------------------------------------
+      !
+      IF( xios_is_valid_domain     (cdid) ) THEN
+         CALL xios_set_domain_attr     ( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
+            &    data_dim=data_dim, data_ibegin=data_ibegin, data_ni=data_ni, data_jbegin=data_jbegin, data_nj=data_nj ,   &
+            &    lonvalue_1D=lonvalue, latvalue_1D=latvalue, mask_1D=mask, nvertex=nvertex, bounds_lon_1D=bounds_lon,      &
+            &    bounds_lat_1D=bounds_lat, area=area, type='curvilinear')
+      ENDIF
+      IF( xios_is_valid_domaingroup(cdid) ) THEN
+         CALL xios_set_domaingroup_attr( cdid, ni_glo=ni_glo, nj_glo=nj_glo, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj,   &
+            &    data_dim=data_dim, data_ibegin=data_ibegin, data_ni=data_ni, data_jbegin=data_jbegin, data_nj=data_nj ,   &
+            &    lonvalue_1D=lonvalue, latvalue_1D=latvalue, mask_1D=mask, nvertex=nvertex, bounds_lon_1D=bounds_lon,      &
+            &    bounds_lat_1D=bounds_lat, area=area, type='curvilinear' )
+      ENDIF
+      !
+      CALL xios_solve_inheritance()
+      !
+   END SUBROUTINE iom_set_domain_attr
+
+
+   SUBROUTINE iom_set_zoom_domain_attr( cdid, ibegin, jbegin, ni, nj )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) ::   cdid
+      INTEGER         , INTENT(in) ::   ibegin, jbegin, ni, nj
+      !
+      TYPE(xios_gridgroup) :: gridgroup_hdl
+      TYPE(xios_grid)      :: grid_hdl
+      TYPE(xios_domain)    :: domain_hdl 
+      TYPE(xios_axis)      :: axis_hdl 
+      CHARACTER(LEN=64)    :: cldomrefid   ! domain_ref name
+      CHARACTER(len=1)     :: cl1          ! last character of this name
+      !!----------------------------------------------------------------------
+      !
+      IF( xios_is_valid_zoom_domain(cdid) ) THEN
+         ! define the zoom_domain attributs
+         CALL xios_set_zoom_domain_attr( cdid, ibegin=ibegin, jbegin=jbegin, ni=ni, nj=nj )
+         ! define a new 2D grid with this new domain
+         CALL xios_get_handle("grid_definition", gridgroup_hdl )
+         CALL xios_add_child(gridgroup_hdl, grid_hdl, TRIM(cdid)//'_2D' )   ! add a new 2D grid to grid_definition
+         CALL xios_add_child(grid_hdl, domain_hdl, TRIM(cdid) )             ! add its domain
+         ! define a new 3D grid with this new domain
+         CALL xios_add_child(gridgroup_hdl, grid_hdl, TRIM(cdid)//'_3D' )   ! add a new 3D grid to grid_definition
+         CALL xios_add_child(grid_hdl, domain_hdl, TRIM(cdid) )             ! add its domain
+         ! vertical axis
+         cl1 = cdid(LEN_TRIM(cdid):)                                        ! last letter of cdid
+         cl1 = CHAR(ICHAR(cl1)+32)                                          ! from upper to lower case
+         CALL xios_add_child(grid_hdl, axis_hdl, 'depth'//cl1)              ! add its axis
+      ENDIF
+      !      
+   END SUBROUTINE iom_set_zoom_domain_attr
+
+
+   SUBROUTINE iom_set_axis_attr( cdid, paxis, bounds )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)      , INTENT(in) ::   cdid
+      REAL(wp), DIMENSION(:)  , OPTIONAL, INTENT(in) ::   paxis
+      REAL(wp), DIMENSION(:,:), OPTIONAL, INTENT(in) ::   bounds
+      !!----------------------------------------------------------------------
+      IF( PRESENT(paxis) ) THEN
+         IF( xios_is_valid_axis     (cdid) )   CALL xios_set_axis_attr     ( cdid, n_glo=SIZE(paxis), value=paxis )
+         IF( xios_is_valid_axisgroup(cdid) )   CALL xios_set_axisgroup_attr( cdid, n_glo=SIZE(paxis), value=paxis )
+      ENDIF
+      IF( xios_is_valid_axis     (cdid) )   CALL xios_set_axis_attr     ( cdid, bounds=bounds )
+      IF( xios_is_valid_axisgroup(cdid) )   CALL xios_set_axisgroup_attr( cdid, bounds=bounds )
+      CALL xios_solve_inheritance()
+   END SUBROUTINE iom_set_axis_attr
+
+
+   SUBROUTINE iom_set_field_attr( cdid, freq_op, freq_offset )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)             , INTENT(in) ::   cdid
+      TYPE(xios_duration), OPTIONAL, INTENT(in) ::   freq_op
+      TYPE(xios_duration), OPTIONAL, INTENT(in) ::   freq_offset
+      !!----------------------------------------------------------------------
+      IF( xios_is_valid_field     (cdid) )   CALL xios_set_field_attr     ( cdid, freq_op=freq_op, freq_offset=freq_offset )
+      IF( xios_is_valid_fieldgroup(cdid) )   CALL xios_set_fieldgroup_attr( cdid, freq_op=freq_op, freq_offset=freq_offset )
+      CALL xios_solve_inheritance()
+   END SUBROUTINE iom_set_field_attr
+
+
+   SUBROUTINE iom_set_file_attr( cdid, name, name_suffix )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)          , INTENT(in) ::   cdid
+      CHARACTER(LEN=*),OPTIONAL , INTENT(in) ::   name, name_suffix
+      !!----------------------------------------------------------------------
+      IF( xios_is_valid_file     (cdid) )   CALL xios_set_file_attr     ( cdid, name=name, name_suffix=name_suffix )
+      IF( xios_is_valid_filegroup(cdid) )   CALL xios_set_filegroup_attr( cdid, name=name, name_suffix=name_suffix )
+      CALL xios_solve_inheritance()
+   END SUBROUTINE iom_set_file_attr
+
+
+   SUBROUTINE iom_get_file_attr( cdid, name, name_suffix, output_freq )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)          , INTENT(in ) ::   cdid
+      CHARACTER(LEN=*),OPTIONAL , INTENT(out) ::   name, name_suffix
+      TYPE(xios_duration), OPTIONAL , INTENT(out) :: output_freq
+      LOGICAL                                 ::   llexist1,llexist2,llexist3
+      !---------------------------------------------------------------------
+      IF( PRESENT( name        ) )   name = ''          ! default values
+      IF( PRESENT( name_suffix ) )   name_suffix = ''
+      IF( PRESENT( output_freq ) )   output_freq = xios_duration(0,0,0,0,0,0)
+      IF( xios_is_valid_file     (cdid) ) THEN
+         CALL xios_solve_inheritance()
+         CALL xios_is_defined_file_attr     ( cdid, name = llexist1, name_suffix = llexist2, output_freq = llexist3)
+         IF(llexist1)   CALL xios_get_file_attr     ( cdid, name = name )
+         IF(llexist2)   CALL xios_get_file_attr     ( cdid, name_suffix = name_suffix )
+         IF(llexist3)   CALL xios_get_file_attr     ( cdid, output_freq = output_freq )
+      ENDIF
+      IF( xios_is_valid_filegroup(cdid) ) THEN
+         CALL xios_solve_inheritance()
+         CALL xios_is_defined_filegroup_attr( cdid, name = llexist1, name_suffix = llexist2, output_freq = llexist3)
+         IF(llexist1)   CALL xios_get_filegroup_attr( cdid, name = name )
+         IF(llexist2)   CALL xios_get_filegroup_attr( cdid, name_suffix = name_suffix )
+         IF(llexist3)   CALL xios_get_filegroup_attr( cdid, output_freq = output_freq )
+      ENDIF
+   END SUBROUTINE iom_get_file_attr
+
+
+   SUBROUTINE iom_set_grid_attr( cdid, mask )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)                   , INTENT(in) ::   cdid
+      LOGICAL, DIMENSION(:,:,:), OPTIONAL, INTENT(in) ::   mask
+      !!----------------------------------------------------------------------
+      IF( xios_is_valid_grid     (cdid) )   CALL xios_set_grid_attr     ( cdid, mask_3D=mask )
+      IF( xios_is_valid_gridgroup(cdid) )   CALL xios_set_gridgroup_attr( cdid, mask_3D=mask )
+      CALL xios_solve_inheritance()
+   END SUBROUTINE iom_set_grid_attr
+
+   SUBROUTINE iom_setkt( kt, cdname )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt 
+      CHARACTER(LEN=*), INTENT(in) ::   cdname
+      !!----------------------------------------------------------------------
+      CALL iom_swap( cdname )   ! swap to cdname context
+      CALL xios_update_calendar(kt)
+      IF( cdname /= TRIM(cxios_context) )   CALL iom_swap( TRIM(cxios_context) )   ! return back to nemo context
+   END SUBROUTINE iom_setkt
+
+   SUBROUTINE iom_context_finalize( cdname )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*), INTENT(in) :: cdname
+      CHARACTER(LEN=120)           :: clname
+      !!----------------------------------------------------------------------
+      clname = cdname
+      IF( TRIM(Agrif_CFixed()) .NE. '0' ) clname = TRIM(Agrif_CFixed())//"_"//clname 
+      IF( xios_is_valid_context(clname) ) THEN
+         CALL iom_swap( cdname )   ! swap to cdname context
+         CALL xios_context_finalize() ! finalize the context
+         IF( cdname /= TRIM(cxios_context) ) CALL iom_swap( TRIM(cxios_context) )   ! return back to nemo context
+      ENDIF
+      !
+   END SUBROUTINE iom_context_finalize
+
+
+   SUBROUTINE set_grid( cdgrd, plon, plat, ldxios, ldrxios )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_grid  ***
+      !!
+      !! ** Purpose :   define horizontal grids
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=1)            , INTENT(in) ::   cdgrd
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   plon
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   plat
+      !
+      INTEGER  :: ni, nj
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zmask
+      LOGICAL, INTENT(IN) :: ldxios, ldrxios
+      !!----------------------------------------------------------------------
+      !
+      ni = nlei-nldi+1
+      nj = nlej-nldj+1
+      !
+      CALL iom_set_domain_attr("grid_"//cdgrd, ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-2, jbegin=njmpp+nldj-2, ni=ni, nj=nj)
+      CALL iom_set_domain_attr("grid_"//cdgrd, data_dim=2, data_ibegin = 1-nldi, data_ni = jpi, data_jbegin = 1-nldj, data_nj = jpj)
+!don't define lon and lat for restart reading context. 
+      IF ( .NOT.ldrxios ) &
+         CALL iom_set_domain_attr("grid_"//cdgrd, lonvalue = RESHAPE(plon(nldi:nlei, nldj:nlej),(/ ni*nj /)),   &
+         &                                     latvalue = RESHAPE(plat(nldi:nlei, nldj:nlej),(/ ni*nj /)))  
+      !
+      IF ( ln_mskland .AND. (.NOT.ldxios) ) THEN
+         ! mask land points, keep values on coast line -> specific mask for U, V and W points
+         SELECT CASE ( cdgrd )
+         CASE('T')   ;   zmask(:,:,:)       = tmask(:,:,:)
+         CASE('U')   ;   zmask(2:jpim1,:,:) = tmask(2:jpim1,:,:) + tmask(3:jpi,:,:)   ;   CALL lbc_lnk( 'iom', zmask, 'U', 1. )
+         CASE('V')   ;   zmask(:,2:jpjm1,:) = tmask(:,2:jpjm1,:) + tmask(:,3:jpj,:)   ;   CALL lbc_lnk( 'iom', zmask, 'V', 1. )
+         CASE('W')   ;   zmask(:,:,2:jpk  ) = tmask(:,:,1:jpkm1) + tmask(:,:,2:jpk)   ;   zmask(:,:,1) = tmask(:,:,1)
+         END SELECT
+         !
+         CALL iom_set_domain_attr( "grid_"//cdgrd       , mask = RESHAPE(zmask(nldi:nlei,nldj:nlej,1),(/ni*nj    /)) /= 0. )
+         CALL iom_set_grid_attr  ( "grid_"//cdgrd//"_3D", mask = RESHAPE(zmask(nldi:nlei,nldj:nlej,:),(/ni,nj,jpk/)) /= 0. )
+      ENDIF
+      !
+   END SUBROUTINE set_grid
+
+
+   SUBROUTINE set_grid_bounds( cdgrd, plon_cnr, plat_cnr, plon_pnt, plat_pnt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE set_grid_bounds  ***
+      !!
+      !! ** Purpose :   define horizontal grid corners
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=1)                      , INTENT(in) :: cdgrd
+      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(in) :: plon_cnr, plat_cnr  ! Lat/lon coord. of a contiguous vertex of cell (i,j)
+      REAL(wp), DIMENSION(jpi,jpj), OPTIONAL, INTENT(in) :: plon_pnt, plat_pnt  ! Lat/lon coord. of the point of cell (i,j)
+      !
+      INTEGER :: ji, jj, jn, ni, nj
+      INTEGER :: icnr, jcnr                                    ! Offset such that the vertex coordinate (i+icnr,j+jcnr)
+      !                                                        ! represents the bottom-left corner of cell (i,j)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) :: z_bnds      ! Lat/lon coordinates of the vertices of cell (i,j)
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     :: z_fld       ! Working array to determine where to rotate cells
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)     :: z_rot       ! Lat/lon working array for rotation of cells
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( z_bnds(4,jpi,jpj,2), z_fld(jpi,jpj), z_rot(4,2)  )
+      !
+      ! Offset of coordinate representing bottom-left corner
+      SELECT CASE ( TRIM(cdgrd) )
+      CASE ('T', 'W')   ;   icnr = -1   ;   jcnr = -1
+      CASE ('U')        ;   icnr =  0   ;   jcnr = -1
+      CASE ('V')        ;   icnr = -1   ;   jcnr =  0
+      END SELECT
+      !
+      ni = nlei-nldi+1   ! Dimensions of subdomain interior
+      nj = nlej-nldj+1
+      !
+      z_fld(:,:) = 1._wp
+      CALL lbc_lnk( 'iom', z_fld, cdgrd, -1. )    ! Working array for location of northfold
+      !
+      ! Cell vertices that can be defined
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            z_bnds(1,ji,jj,1) = plat_cnr(ji+icnr,  jj+jcnr  ) ! Bottom-left
+            z_bnds(2,ji,jj,1) = plat_cnr(ji+icnr+1,jj+jcnr  ) ! Bottom-right
+            z_bnds(3,ji,jj,1) = plat_cnr(ji+icnr+1,jj+jcnr+1) ! Top-right
+            z_bnds(4,ji,jj,1) = plat_cnr(ji+icnr,  jj+jcnr+1) ! Top-left
+            z_bnds(1,ji,jj,2) = plon_cnr(ji+icnr,  jj+jcnr  ) ! Bottom-left
+            z_bnds(2,ji,jj,2) = plon_cnr(ji+icnr+1,jj+jcnr  ) ! Bottom-right
+            z_bnds(3,ji,jj,2) = plon_cnr(ji+icnr+1,jj+jcnr+1) ! Top-right
+            z_bnds(4,ji,jj,2) = plon_cnr(ji+icnr,  jj+jcnr+1) ! Top-left
+         END DO
+      END DO
+      !
+      ! Cell vertices on boundries
+      DO jn = 1, 4
+         CALL lbc_lnk( 'iom', z_bnds(jn,:,:,1), cdgrd, 1., pfillval=999._wp )
+         CALL lbc_lnk( 'iom', z_bnds(jn,:,:,2), cdgrd, 1., pfillval=999._wp )
+      END DO
+      !
+      ! Zero-size cells at closed boundaries if cell points provided,
+      ! otherwise they are closed cells with unrealistic bounds
+      IF( PRESENT(plon_pnt) .AND. PRESENT(plat_pnt) ) THEN
+         IF( (nbondi == -1 .OR. nbondi == 2) .AND. .NOT. (jperio == 1 .OR. jperio == 4 .OR. jperio == 6) ) THEN
+            DO jn = 1, 4        ! (West or jpni = 1), closed E-W
+               z_bnds(jn,1,:,1) = plat_pnt(1,:)  ;  z_bnds(jn,1,:,2) = plon_pnt(1,:)
+            END DO
+         ENDIF
+         IF( (nbondi == 1 .OR. nbondi == 2) .AND. .NOT. (jperio == 1 .OR. jperio == 4 .OR. jperio == 6) ) THEN
+            DO jn = 1, 4        ! (East or jpni = 1), closed E-W
+               z_bnds(jn,nlci,:,1) = plat_pnt(nlci,:)  ;  z_bnds(jn,nlci,:,2) = plon_pnt(nlci,:)
+            END DO
+         ENDIF
+         IF( nbondj == -1 .OR. (nbondj == 2 .AND. jperio /= 2) ) THEN
+            DO jn = 1, 4        ! South or (jpnj = 1, not symmetric)
+               z_bnds(jn,:,1,1) = plat_pnt(:,1)  ;  z_bnds(jn,:,1,2) = plon_pnt(:,1)
+            END DO
+         ENDIF
+         IF( (nbondj == 1 .OR. nbondj == 2) .AND. jperio  < 3 ) THEN
+            DO jn = 1, 4        ! (North or jpnj = 1), no north fold
+               z_bnds(jn,:,nlcj,1) = plat_pnt(:,nlcj)  ;  z_bnds(jn,:,nlcj,2) = plon_pnt(:,nlcj)
+            END DO
+         ENDIF
+      ENDIF
+      !
+      IF( (nbondj == 1 .OR. nbondj == 2) .AND. jperio >= 3 ) THEN    ! Rotate cells at the north fold
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( z_fld(ji,jj) == -1. ) THEN
+                  z_rot(1,:) = z_bnds(3,ji,jj,:) ; z_rot(2,:) = z_bnds(4,ji,jj,:)
+                  z_rot(3,:) = z_bnds(1,ji,jj,:) ; z_rot(4,:) = z_bnds(2,ji,jj,:)
+                  z_bnds(:,ji,jj,:) = z_rot(:,:)
+               ENDIF
+            END DO
+         END DO
+      ELSE IF( nbondj == 2 .AND. jperio == 2 ) THEN                  ! Invert cells at the symmetric equator
+         DO ji = 1, jpi
+            z_rot(1:2,:) = z_bnds(3:4,ji,1,:)
+            z_rot(3:4,:) = z_bnds(1:2,ji,1,:)
+            z_bnds(:,ji,1,:) = z_rot(:,:)
+         END DO
+      ENDIF
+      !
+      CALL iom_set_domain_attr("grid_"//cdgrd, bounds_lat = RESHAPE(z_bnds(:,nldi:nlei,nldj:nlej,1),(/ 4,ni*nj /)),           &
+          &                                    bounds_lon = RESHAPE(z_bnds(:,nldi:nlei,nldj:nlej,2),(/ 4,ni*nj /)), nvertex=4 )
+      !
+      DEALLOCATE( z_bnds, z_fld, z_rot ) 
+      !
+   END SUBROUTINE set_grid_bounds
+
+
+   SUBROUTINE set_grid_znl( plat )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_grid_znl  ***
+      !!
+      !! ** Purpose :   define grids for zonal mean
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   plat
+      !
+      INTEGER  :: ni, nj, ix, iy
+      REAL(wp), DIMENSION(:), ALLOCATABLE  ::   zlon
+      !!----------------------------------------------------------------------
+      !
+      ni=nlei-nldi+1       ! define zonal mean domain (jpj*jpk)
+      nj=nlej-nldj+1
+      ALLOCATE( zlon(ni*nj) )       ;       zlon(:) = 0._wp
+      !
+!      CALL dom_ngb( -168.53, 65.03, ix, iy, 'T' ) !  i-line that passes through Bering Strait: Reference latitude (used in plots)
+      CALL dom_ngb( 180., 90., ix, iy, 'T' ) !  i-line that passes near the North Pole : Reference latitude (used in plots)
+      CALL iom_set_domain_attr("gznl", ni_glo=jpiglo, nj_glo=jpjglo, ibegin=nimpp+nldi-2, jbegin=njmpp+nldj-2, ni=ni, nj=nj)
+      CALL iom_set_domain_attr("gznl", data_dim=2, data_ibegin = 1-nldi, data_ni = jpi, data_jbegin = 1-nldj, data_nj = jpj)
+      CALL iom_set_domain_attr("gznl", lonvalue = zlon,   &
+         &                             latvalue = RESHAPE(plat(nldi:nlei, nldj:nlej),(/ ni*nj /)))  
+      CALL iom_set_zoom_domain_attr("ptr", ibegin=ix-1, jbegin=0, ni=1, nj=jpjglo)
+      !
+      CALL iom_update_file_name('ptr')
+      !
+   END SUBROUTINE set_grid_znl
+
+
+   SUBROUTINE set_scalar
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_scalar  ***
+      !!
+      !! ** Purpose :   define fake grids for scalar point
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(1)   ::   zz = 1.
+      !!----------------------------------------------------------------------
+      !
+      CALL iom_set_domain_attr('scalarpoint', ni_glo=jpnij, nj_glo=1, ibegin=narea-1, jbegin=0, ni=1, nj=1)
+      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
+
+
+   SUBROUTINE set_xmlatt
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_xmlatt  ***
+      !!
+      !! ** Purpose :   automatic definitions of some of the xml attributs...
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=1),DIMENSION( 3) ::   clgrd                    ! suffix name
+      CHARACTER(len=256)             ::   clsuff                   ! suffix name
+      CHARACTER(len=1)               ::   cl1                      ! 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
+      REAL(wp)        ,DIMENSION(11) ::   zlontao                  ! longitudes of tao    moorings
+      REAL(wp)        ,DIMENSION( 7) ::   zlattao                  ! latitudes  of tao    moorings
+      REAL(wp)        ,DIMENSION( 4) ::   zlonrama                 ! longitudes of rama   moorings
+      REAL(wp)        ,DIMENSION(11) ::   zlatrama                 ! latitudes  of rama   moorings
+      REAL(wp)        ,DIMENSION( 3) ::   zlonpira                 ! longitudes of pirata moorings
+      REAL(wp)        ,DIMENSION( 9) ::   zlatpira                 ! latitudes  of pirata moorings
+      TYPE(xios_duration)            ::   f_op, f_of
+      !!----------------------------------------------------------------------
+      ! 
+      ! frequency of the call of iom_put (attribut: freq_op)
+      f_op%timestep = 1        ;  f_of%timestep =  0  ; CALL iom_set_field_attr('field_definition', freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = 2        ;  f_of%timestep =  0  ; CALL iom_set_field_attr('trendT_even'     , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = 2        ;  f_of%timestep = -1  ; CALL iom_set_field_attr('trendT_odd'      , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_fsbc  ;  f_of%timestep =  0  ; CALL iom_set_field_attr('SBC'             , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_fsbc  ;  f_of%timestep =  0  ; CALL iom_set_field_attr('SBC_scalar'      , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_dttrc ;  f_of%timestep =  0  ; CALL iom_set_field_attr('ptrc_T'          , freq_op=f_op, freq_offset=f_of)
+      f_op%timestep = nn_dttrc ;  f_of%timestep =  0  ; CALL iom_set_field_attr('diad_T'          , freq_op=f_op, freq_offset=f_of)
+
+      ! output file names (attribut: name)
+      DO ji = 1, 9
+         WRITE(cl1,'(i1)') ji 
+         CALL iom_update_file_name('file'//cl1)
+      END DO
+      DO ji = 1, 99
+         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
+
+      ! Zooms...
+      clgrd = (/ 'T', 'U', 'W' /) 
+      DO jg = 1, SIZE(clgrd)                                                                   ! grid type
+         cl1 = clgrd(jg)
+         ! Equatorial section (attributs: jbegin, ni, name_suffix)
+         CALL dom_ngb( 0., 0., ix, iy, cl1 )
+         CALL iom_set_zoom_domain_attr('Eq'//cl1, ibegin=0, jbegin=iy-1, ni=jpiglo, nj=1 )
+         CALL iom_get_file_attr   ('Eq'//cl1, name_suffix = clsuff             )
+         CALL iom_set_file_attr   ('Eq'//cl1, name_suffix = TRIM(clsuff)//'_Eq')
+         CALL iom_update_file_name('Eq'//cl1)
+      END DO
+      ! TAO moorings (attributs: ibegin, jbegin, name_suffix)
+      zlontao = (/ 137.0, 147.0, 156.0, 165.0, -180.0, -170.0, -155.0, -140.0, -125.0, -110.0, -95.0 /)
+      zlattao = (/  -8.0,  -5.0,  -2.0,   0.0,    2.0,    5.0,    8.0 /)
+      CALL set_mooring( zlontao, zlattao )
+      ! RAMA moorings (attributs: ibegin, jbegin, name_suffix)
+      zlonrama = (/  55.0,  67.0, 80.5, 90.0 /)
+      zlatrama = (/ -16.0, -12.0, -8.0, -4.0, -1.5, 0.0, 1.5, 4.0, 8.0, 12.0, 15.0 /)
+      CALL set_mooring( zlonrama, zlatrama )
+      ! PIRATA moorings (attributs: ibegin, jbegin, name_suffix)
+      zlonpira = (/ -38.0, -23.0, -10.0 /)
+      zlatpira = (/ -19.0, -14.0,  -8.0, 0.0, 4.0, 8.0, 12.0, 15.0, 20.0 /)
+      CALL set_mooring( zlonpira, zlatpira )
+      !
+   END SUBROUTINE set_xmlatt
+
+
+   SUBROUTINE set_mooring( plon, plat )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE set_mooring  ***
+      !!
+      !! ** Purpose :   automatic definitions of moorings xml attributs...
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(in) ::   plon, plat   ! longitudes/latitudes oft the mooring
+      !
+!!$      CHARACTER(len=1),DIMENSION(4) ::   clgrd = (/ 'T', 'U', 'V', 'W' /)   ! suffix name
+      CHARACTER(len=1),DIMENSION(1) ::   clgrd = (/ 'T' /)        ! suffix name
+      CHARACTER(len=256)            ::   clname                   ! file name
+      CHARACTER(len=256)            ::   clsuff                   ! suffix name
+      CHARACTER(len=1)              ::   cl1                      ! 1 character
+      CHARACTER(len=6)              ::   clon,clat                ! name of longitude, latitude
+      INTEGER                       ::   ji, jj, jg               ! loop counters
+      INTEGER                       ::   ix, iy                   ! i-,j- index
+      REAL(wp)                      ::   zlon, zlat
+      !!----------------------------------------------------------------------
+      DO jg = 1, SIZE(clgrd)
+         cl1 = clgrd(jg)
+         DO ji = 1, SIZE(plon)
+            DO jj = 1, SIZE(plat)
+               zlon = plon(ji)
+               zlat = plat(jj)
+               ! modifications for RAMA moorings
+               IF( zlon ==  67. .AND. zlat ==  15. )   zlon =  65.
+               IF( zlon ==  90. .AND. zlat <=  -4. )   zlon =  95.
+               IF( zlon ==  95. .AND. zlat ==  -4. )   zlat =  -5.
+               ! modifications for PIRATA moorings
+               IF( zlon == -38. .AND. zlat == -19. )   zlon = -34.
+               IF( zlon == -38. .AND. zlat == -14. )   zlon = -32.
+               IF( zlon == -38. .AND. zlat ==  -8. )   zlon = -30.
+               IF( zlon == -38. .AND. zlat ==   0. )   zlon = -35.
+               IF( zlon == -23. .AND. zlat ==  20. )   zlat =  21.
+               IF( zlon == -10. .AND. zlat == -14. )   zlat = -10.
+               IF( zlon == -10. .AND. zlat ==  -8. )   zlat =  -6.
+               IF( zlon == -10. .AND. zlat ==   4. ) THEN   ;   zlon = 0.   ;   zlat = 0.   ;   ENDIF
+               CALL dom_ngb( zlon, zlat, ix, iy, cl1 )
+               IF( zlon >= 0. ) THEN  
+                  IF( zlon == REAL(NINT(zlon), wp) ) THEN   ;   WRITE(clon, '(i3,  a)') NINT( zlon), 'e'
+                  ELSE                                      ;   WRITE(clon, '(f5.1,a)')       zlon , 'e'
+                  ENDIF
+               ELSE             
+                  IF( zlon == REAL(NINT(zlon), wp) ) THEN   ;   WRITE(clon, '(i3,  a)') NINT(-zlon), 'w'
+                  ELSE                                      ;   WRITE(clon, '(f5.1,a)')      -zlon , 'w'
+                  ENDIF
+               ENDIF
+               IF( zlat >= 0. ) THEN  
+                  IF( zlat == REAL(NINT(zlat), wp) ) THEN   ;   WRITE(clat, '(i2,  a)') NINT( zlat), 'n'
+                  ELSE                                      ;   WRITE(clat, '(f4.1,a)')       zlat , 'n'
+                  ENDIF
+               ELSE             
+                  IF( zlat == REAL(NINT(zlat), wp) ) THEN   ;   WRITE(clat, '(i2,  a)') NINT(-zlat), 's'
+                  ELSE                                      ;   WRITE(clat, '(f4.1,a)')      -zlat , 's'
+                  ENDIF
+               ENDIF
+               clname = TRIM(ADJUSTL(clat))//TRIM(ADJUSTL(clon))
+               CALL iom_set_zoom_domain_attr(TRIM(clname)//cl1, ibegin= ix-1, jbegin= iy-1, ni=1, nj=1)
+
+               CALL iom_get_file_attr   (TRIM(clname)//cl1, name_suffix = clsuff                         )
+               CALL iom_set_file_attr   (TRIM(clname)//cl1, name_suffix = TRIM(clsuff)//'_'//TRIM(clname))
+               CALL iom_update_file_name(TRIM(clname)//cl1)
+            END DO
+         END DO
+      END DO
+      
+   END SUBROUTINE set_mooring
+
+   
+   SUBROUTINE iom_update_file_name( cdid )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE iom_update_file_name  ***
+      !!
+      !! ** Purpose :   
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(LEN=*)          , INTENT(in) ::   cdid
+      !
+      CHARACTER(LEN=256) ::   clname
+      CHARACTER(LEN=20)  ::   clfreq
+      CHARACTER(LEN=20)  ::   cldate
+      CHARACTER(LEN=256) ::   cltmpn                 !FUS needed for correct path with AGRIF
+      INTEGER            ::   iln                    !FUS needed for correct path with AGRIF
+      INTEGER            ::   idx
+      INTEGER            ::   jn
+      INTEGER            ::   itrlen
+      INTEGER            ::   iyear, imonth, iday, isec
+      REAL(wp)           ::   zsec
+      LOGICAL            ::   llexist
+      TYPE(xios_duration)   ::   output_freq 
+      !!----------------------------------------------------------------------
+      !
+      DO jn = 1, 2
+         !
+         output_freq = xios_duration(0,0,0,0,0,0)
+         IF( jn == 1 )   CALL iom_get_file_attr( cdid, name        = clname, output_freq = output_freq )
+         IF( jn == 2 )   CALL iom_get_file_attr( cdid, name_suffix = clname )
+         !
+         IF ( TRIM(clname) /= '' ) THEN 
+            !
+            idx = INDEX(clname,'@expname@') + INDEX(clname,'@EXPNAME@')
+            DO WHILE ( idx /= 0 ) 
+               clname = clname(1:idx-1)//TRIM(cexper)//clname(idx+9:LEN_TRIM(clname))
+               idx = INDEX(clname,'@expname@') + INDEX(clname,'@EXPNAME@')
+            END DO
+            !
+            idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
+            DO WHILE ( idx /= 0 ) 
+              IF ( output_freq%timestep /= 0) THEN
+                  WRITE(clfreq,'(I18,A2)')INT(output_freq%timestep),'ts' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%second /= 0 ) THEN
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%second),'s' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%minute /= 0 ) THEN
+                  WRITE(clfreq,'(I18,A2)')INT(output_freq%minute),'mi' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%hour /= 0 ) THEN
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%hour),'h' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%day /= 0 ) THEN
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%day),'d' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%month /= 0 ) THEN   
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%month),'m' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE IF ( output_freq%year /= 0 ) THEN   
+                  WRITE(clfreq,'(I19,A1)')INT(output_freq%year),'y' 
+                  itrlen = LEN_TRIM(ADJUSTL(clfreq))
+              ELSE
+                  CALL ctl_stop('error in the name of file id '//TRIM(cdid),   &
+                     & ' attribute output_freq is undefined -> cannot replace @freq@ in '//TRIM(clname) )
+              ENDIF
+              clname = clname(1:idx-1)//TRIM(ADJUSTL(clfreq))//clname(idx+6:LEN_TRIM(clname))
+              idx = INDEX(clname,'@freq@') + INDEX(clname,'@FREQ@')
+            END DO
+            !
+            idx = INDEX(clname,'@startdate@') + INDEX(clname,'@STARTDATE@')
+            DO WHILE ( idx /= 0 ) 
+               cldate = iom_sdate( fjulday - rdt / rday )
+               clname = clname(1:idx-1)//TRIM(cldate)//clname(idx+11:LEN_TRIM(clname))
+               idx = INDEX(clname,'@startdate@') + INDEX(clname,'@STARTDATE@')
+            END DO
+            !
+            idx = INDEX(clname,'@startdatefull@') + INDEX(clname,'@STARTDATEFULL@')
+            DO WHILE ( idx /= 0 ) 
+               cldate = iom_sdate( fjulday - rdt / rday, ldfull = .TRUE. )
+               clname = clname(1:idx-1)//TRIM(cldate)//clname(idx+15:LEN_TRIM(clname))
+               idx = INDEX(clname,'@startdatefull@') + INDEX(clname,'@STARTDATEFULL@')
+            END DO
+            !
+            idx = INDEX(clname,'@enddate@') + INDEX(clname,'@ENDDATE@')
+            DO WHILE ( idx /= 0 ) 
+               cldate = iom_sdate( fjulday + rdt / rday * REAL( nitend - nit000, wp ), ld24 = .TRUE. )
+               clname = clname(1:idx-1)//TRIM(cldate)//clname(idx+9:LEN_TRIM(clname))
+               idx = INDEX(clname,'@enddate@') + INDEX(clname,'@ENDDATE@')
+            END DO
+            !
+            idx = INDEX(clname,'@enddatefull@') + INDEX(clname,'@ENDDATEFULL@')
+            DO WHILE ( idx /= 0 ) 
+               cldate = iom_sdate( fjulday + rdt / rday * REAL( nitend - nit000, wp ), ld24 = .TRUE., ldfull = .TRUE. )
+               clname = clname(1:idx-1)//TRIM(cldate)//clname(idx+13:LEN_TRIM(clname))
+               idx = INDEX(clname,'@enddatefull@') + INDEX(clname,'@ENDDATEFULL@')
+            END DO
+            !
+!FUS            IF( jn == 1 .AND. TRIM(Agrif_CFixed()) /= '0' )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+!FUS see comment line 700 
+            IF( jn == 1 .AND. TRIM(Agrif_CFixed()) /= '0' ) THEN
+             iln    = INDEX(clname,'/',BACK=.true.)
+             cltmpn = clname(1:iln)
+             clname = clname(iln+1:LEN_TRIM(clname))
+             clname = TRIM(cltmpn)//TRIM(Agrif_CFixed())//'_'//TRIM(clname)
+            ENDIF
+!FUS 
+            IF( jn == 1 )   CALL iom_set_file_attr( cdid, name        = clname )
+            IF( jn == 2 )   CALL iom_set_file_attr( cdid, name_suffix = clname )
+            !
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE iom_update_file_name
+
+
+   FUNCTION iom_sdate( pjday, ld24, ldfull )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE iom_sdate  ***
+      !!
+      !! ** Purpose :   send back the date corresponding to the given julian day
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in   )           ::   pjday    ! julian day
+      LOGICAL , INTENT(in   ), OPTIONAL ::   ld24     ! true to force 24:00 instead of 00:00
+      LOGICAL , INTENT(in   ), OPTIONAL ::   ldfull   ! true to get the compleate date: yyyymmdd_hh:mm:ss
+      !
+      CHARACTER(LEN=20) ::   iom_sdate
+      CHARACTER(LEN=50) ::   clfmt                         !  format used to write the date 
+      INTEGER           ::   iyear, imonth, iday, ihour, iminute, isec
+      REAL(wp)          ::   zsec
+      LOGICAL           ::   ll24, llfull
+      !!----------------------------------------------------------------------
+      !
+      IF( PRESENT(ld24) ) THEN   ;   ll24 = ld24
+      ELSE                       ;   ll24 = .FALSE.
+      ENDIF
+      !
+      IF( PRESENT(ldfull) ) THEN   ;   llfull = ldfull
+      ELSE                         ;   llfull = .FALSE.
+      ENDIF
+      !
+      CALL ju2ymds( pjday, iyear, imonth, iday, zsec )
+      isec = NINT(zsec)
+      !
+      IF ( ll24 .AND. isec == 0 ) THEN   ! 00:00 of the next day -> move to 24:00 of the current day
+         CALL ju2ymds( pjday - 1., iyear, imonth, iday, zsec )
+         isec = 86400
+      ENDIF
+      !
+      IF( iyear < 10000 ) THEN   ;   clfmt = "i4.4,2i2.2"                ! format used to write the date 
+      ELSE                       ;   WRITE(clfmt, "('i',i1,',2i2.2')") INT(LOG10(REAL(iyear,wp))) + 1
+      ENDIF
+      !
+!$AGRIF_DO_NOT_TREAT      
+      ! needed in the conv
+      IF( llfull ) THEN 
+         clfmt = TRIM(clfmt)//",'_',i2.2,':',i2.2,':',i2.2"
+         ihour   = isec / 3600
+         isec    = MOD(isec, 3600)
+         iminute = isec / 60
+         isec    = MOD(isec, 60)
+         WRITE(iom_sdate, '('//TRIM(clfmt)//')') iyear, imonth, iday, ihour, iminute, isec    ! date of the end of run
+      ELSE
+         WRITE(iom_sdate, '('//TRIM(clfmt)//')') iyear, imonth, iday                          ! date of the end of run
+      ENDIF
+!$AGRIF_END_DO_NOT_TREAT      
+      !
+   END FUNCTION iom_sdate
+
+#else
+   !!----------------------------------------------------------------------
+   !!   NOT 'key_iomput'                               a few dummy routines
+   !!----------------------------------------------------------------------
+   SUBROUTINE iom_setkt( kt, cdname )
+      INTEGER         , INTENT(in)::   kt 
+      CHARACTER(LEN=*), INTENT(in) ::   cdname
+      IF( .FALSE. )   WRITE(numout,*) kt, cdname   ! useless test to avoid compilation warnings
+   END SUBROUTINE iom_setkt
+
+   SUBROUTINE iom_context_finalize( cdname )
+      CHARACTER(LEN=*), INTENT(in) ::   cdname
+      IF( .FALSE. )   WRITE(numout,*)  cdname   ! useless test to avoid compilation warnings
+   END SUBROUTINE iom_context_finalize
+
+#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
+
+   SUBROUTINE iom_miss_val( cdname, pmiss_val )
+      CHARACTER(LEN=*), INTENT(in ) ::   cdname
+      REAL(wp)        , INTENT(out) ::   pmiss_val   
+#if defined key_iomput
+      ! get missing value
+      CALL xios_get_field_attr( cdname, default_value = pmiss_val )
+#else
+      IF( .FALSE. )   WRITE(numout,*) cdname, pmiss_val   ! useless test to avoid compilation warnings
+      IF( .FALSE. )   pmiss_val = 0._wp                   ! useless assignment to avoid compilation warnings
+#endif
+   END SUBROUTINE iom_miss_val
+  
+   !!======================================================================
+END MODULE iom
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_def.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_def.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_def.F90	(revision 14097)
@@ -0,0 +1,84 @@
+MODULE iom_def
+   !!======================================================================
+   !!                    ***  MODULE  iom_def ***
+   !! IOM variables definitions
+   !!======================================================================
+   !! History :  9.0  ! 2006 09  (S. Masson) Original code
+   !!             -   ! 2007 07  (D. Storkey) Add uldname
+   !!            4.0  ! 2017-11 (M. Andrejczuk) Extend IOM interface to write any 3D fields
+   !!----------------------------------------------------------------------
+   USE par_kind
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_data          = 1   !: ( 1  :jpiglo, 1  :jpjglo)    !!gm to be suppressed
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_global        = 2   !: ( 1  :jpiglo, 1  :jpjglo)
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_local         = 3   !: One of the 3 following cases
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_local_full    = 4   !: ( 1  :jpi   , 1  :jpi   )
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_local_noextra = 5   !: ( 1  :nlci  , 1  :nlcj  )
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_local_noovlap = 6   !: (nldi:nlei  ,nldj:nlej  )
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_unknown       = 7   !: No dimension checking
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_autoglo       = 8   !: 
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_autoglo_xy    = 9   !: Automatically set horizontal dimensions only
+   INTEGER, PARAMETER, PUBLIC ::   jpdom_autodta       = 10  !: 
+
+   INTEGER, PARAMETER, PUBLIC ::   jp_r8    = 200      !: write REAL(8)
+   INTEGER, PARAMETER, PUBLIC ::   jp_r4    = 201      !: write REAL(4)
+   INTEGER, PARAMETER, PUBLIC ::   jp_i4    = 202      !: write INTEGER(4)
+   INTEGER, PARAMETER, PUBLIC ::   jp_i2    = 203      !: write INTEGER(2)
+   INTEGER, PARAMETER, PUBLIC ::   jp_i1    = 204      !: write INTEGER(1)
+
+   INTEGER, PARAMETER, PUBLIC ::   jpmax_files  = 100  !: maximum number of simultaneously opened file
+   INTEGER, PARAMETER, PUBLIC ::   jpmax_vars   = 1200 !: maximum number of variables in one file
+   INTEGER, PARAMETER, PUBLIC ::   jpmax_dims   =  4   !: maximum number of dimensions for one variable
+   INTEGER, PARAMETER, PUBLIC ::   jpmax_digits =  9   !: maximum number of digits for the cpu number in the file name
+
+
+!$AGRIF_DO_NOT_TREAT
+   INTEGER, PUBLIC            ::   iom_open_init = 0   !: used to initialize iom_file(:)%nfid to 0
+!XIOS write restart   
+   LOGICAL, PUBLIC            ::   lwxios          !: write single file restart using XIOS
+   INTEGER, PUBLIC            ::   nxioso          !: type of restart file when writing using XIOS 1 - single, 2 - multiple
+!XIOS read restart   
+   LOGICAL, PUBLIC            ::   lrxios          !: read single file restart using XIOS
+   LOGICAL, PUBLIC            ::   lxios_sini = .FALSE. ! is restart in a single file
+   LOGICAL, PUBLIC            ::   lxios_set  = .FALSE. 
+
+
+
+   TYPE, PUBLIC ::   file_descriptor
+      CHARACTER(LEN=240)                        ::   name     !: name of the file
+      INTEGER                                   ::   nfid     !: identifier of the file (0 if closed)
+                                                              !: jpioipsl option has been removed)
+      INTEGER                                   ::   nvars    !: number of identified varibles in the file
+      INTEGER                                   ::   iduld    !: id of the unlimited dimension
+      INTEGER                                   ::   lenuld   !: length of the unlimited dimension (number of records in file)
+      INTEGER                                   ::   irec     !: writing record position  
+      CHARACTER(LEN=32)                         ::   uldname  !: name of the unlimited dimension
+      CHARACTER(LEN=32), DIMENSION(jpmax_vars)  ::   cn_var   !: names of the variables
+      INTEGER, DIMENSION(jpmax_vars)            ::   nvid     !: id of the variables
+      INTEGER, DIMENSION(jpmax_vars)            ::   ndims    !: number of dimensions of the variables
+      LOGICAL, DIMENSION(jpmax_vars)            ::   luld     !: variable using the unlimited dimension
+      INTEGER, DIMENSION(jpmax_dims,jpmax_vars) ::   dimsz    !: size of variables dimensions 
+      REAL(kind=wp), DIMENSION(jpmax_vars)      ::   scf      !: scale_factor of the variables
+      REAL(kind=wp), DIMENSION(jpmax_vars)      ::   ofs      !: add_offset of the variables
+      INTEGER                                   ::   nlev     ! number of vertical levels
+   END TYPE file_descriptor
+   TYPE(file_descriptor), DIMENSION(jpmax_files), PUBLIC ::   iom_file !: array containing the info for all opened files
+   INTEGER, PARAMETER, PUBLIC                   :: max_rst_fields = 97 !: maximum number of restart variables defined in iom_set_rst_vars
+   TYPE, PUBLIC :: RST_FIELD  
+    CHARACTER(len=30) :: vname = "NO_NAME" ! names of variables in restart file
+    CHARACTER(len=30) :: grid = "NO_GRID"
+    LOGICAL           :: active =.FALSE. ! for restart write only: true - write field, false do not write field
+   END TYPE RST_FIELD
+!$AGRIF_END_DO_NOT_TREAT
+   !
+   TYPE(RST_FIELD), PUBLIC, SAVE :: rst_wfields(max_rst_fields), rst_rfields(max_rst_fields)
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE iom_def
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_nf90.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_nf90.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/iom_nf90.F90	(revision 14097)
@@ -0,0 +1,730 @@
+MODULE iom_nf90
+   !!======================================================================
+   !!                    ***  MODULE  iom_nf90 ***
+   !! Input/Output manager :  Library to read input files with NF90 (only fliocom module)
+   !!======================================================================
+   !! History :  9.0  ! 05 12  (J. Belier) Original code
+   !!            9.0  ! 06 02  (S. Masson) Adaptation to NEMO
+   !!             "   ! 07 07  (D. Storkey) Changes to iom_nf90_gettime
+   !!            3.6  ! 2015-15  (J. Harle) Added procedure to read REAL attributes
+   !!            4.0  ! 2017-11 (M. Andrejczuk) Extend IOM interface to write any 3D fields
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   iom_open       : open a file read only
+   !!   iom_close      : close a file or all files opened by iom
+   !!   iom_get        : read a field (interfaced to several routines)
+   !!   iom_varid      : get the id of a variable in a file
+   !!   iom_rstput     : write a field in a restart file (interfaced to several routines)
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE lbclnk          ! lateal boundary condition / mpp exchanges
+   USE iom_def         ! iom variables definitions
+   USE netcdf          ! NetCDF library
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC iom_nf90_open  , iom_nf90_close, iom_nf90_varid, iom_nf90_get, iom_nf90_rstput
+   PUBLIC iom_nf90_chkatt, iom_nf90_getatt, iom_nf90_putatt
+
+   INTERFACE iom_nf90_get
+      MODULE PROCEDURE iom_nf90_g0d, iom_nf90_g123d
+   END INTERFACE
+   INTERFACE iom_nf90_rstput
+      MODULE PROCEDURE iom_nf90_rp0123d
+   END INTERFACE
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE iom_nf90_open( cdname, kiomid, ldwrt, ldok, kdompar, kdlev )
+      !!---------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_open  ***
+      !!
+      !! ** Purpose : open an input file with NF90
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*)       , INTENT(inout)           ::   cdname      ! File name
+      INTEGER                , INTENT(  out)           ::   kiomid      ! nf90 identifier of the opened file
+      LOGICAL                , INTENT(in   )           ::   ldwrt       ! read or write the file?
+      LOGICAL                , INTENT(in   )           ::   ldok        ! check the existence 
+      INTEGER, DIMENSION(2,5), INTENT(in   ), OPTIONAL ::   kdompar     ! domain parameters: 
+      INTEGER                , INTENT(in   ), OPTIONAL ::   kdlev       ! size of the third dimension
+
+      CHARACTER(LEN=256) ::   clinfo           ! info character
+      CHARACTER(LEN=256) ::   cltmp            ! temporary character
+      CHARACTER(LEN=12 ) ::   clfmt            ! writing format
+      INTEGER            ::   idg              ! number of digits
+      INTEGER            ::   iln              ! lengths of character
+      INTEGER            ::   istop            ! temporary storage of nstop
+      INTEGER            ::   if90id           ! nf90 identifier of the opened file
+      INTEGER            ::   idmy             ! dummy variable
+      INTEGER            ::   jl               ! loop variable
+      INTEGER            ::   ichunk           ! temporary storage of nn_chunksz
+      INTEGER            ::   imode            ! creation mode flag: NF90_CLOBBER or NF90_NOCLOBBER or NF90_HDF5
+      INTEGER            ::   ihdf5            ! local variable for retrieval of value for NF90_HDF5
+      LOGICAL            ::   llclobber        ! local definition of ln_clobber
+      INTEGER            ::   ilevels          ! vertical levels
+      !---------------------------------------------------------------------
+      !
+      clinfo = '                    iom_nf90_open ~~~  '
+      istop = nstop     ! store the actual value of nstop
+      !
+      !                 !number of vertical levels
+      IF( PRESENT(kdlev) ) THEN   ;   ilevels = kdlev    ! use input value (useful for sea-ice)
+      ELSE                        ;   ilevels = jpk      ! by default jpk
+      ENDIF
+      !
+      IF( nn_chunksz > 0 ) THEN   ;   ichunk = nn_chunksz
+      ELSE                        ;   ichunk = NF90_SIZEHINT_DEFAULT
+      ENDIF
+      !
+      llclobber = ldwrt .AND. ln_clobber
+      IF( ldok .AND. .NOT. llclobber ) THEN      !==  Open existing file ==!
+         !                                       !=========================!
+         IF( ldwrt ) THEN  ! ... in write mode
+            IF(lwp) WRITE(numout,*) TRIM(clinfo)//' open existing file: '//TRIM(cdname)//' in WRITE mode'
+            IF( snc4set%luse ) THEN
+               CALL iom_nf90_check(NF90_OPEN( TRIM(cdname), NF90_WRITE  , if90id ), clinfo)
+            ELSE
+               CALL iom_nf90_check(NF90_OPEN( TRIM(cdname), NF90_WRITE  , if90id, chunksize = ichunk ), clinfo)
+            ENDIF
+            CALL iom_nf90_check(NF90_SET_FILL( if90id, NF90_NOFILL, idmy                          ), clinfo)
+         ELSE              ! ... in read mode
+            IF(lwp) WRITE(numout,*) TRIM(clinfo)//' open existing file: '//TRIM(cdname)//' in READ mode'
+            CALL iom_nf90_check(NF90_OPEN( TRIM(cdname), NF90_NOWRITE, if90id, chunksize = ichunk ), clinfo)
+         ENDIF
+      ELSE                                       !== the file doesn't exist ==!   (or we overwrite it)
+         !                                       !============================!
+         iln = INDEX( cdname, '.nc' )
+         IF( ldwrt ) THEN              !* the file should be open in write mode so we create it...
+            IF( jpnij > 1 ) THEN
+               idg = MAX( INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1, 4 )          ! how many digits to we need to write? min=4, max=9
+               WRITE(clfmt, "('(a,a,i', i1, '.', i1, ',a)')") idg, idg          ! '(a,a,ix.x,a)'
+               WRITE(cltmp,clfmt) cdname(1:iln-1), '_', narea-1, '.nc'
+               cdname = TRIM(cltmp)
+            ENDIF
+            IF(lwp) WRITE(numout,*) TRIM(clinfo)//' create new file: '//TRIM(cdname)//' in WRITE mode'
+
+            IF( llclobber ) THEN   ;   imode = IOR( NF90_64BIT_OFFSET, NF90_CLOBBER   )
+            ELSE                   ;   imode = IOR( NF90_64BIT_OFFSET, NF90_NOCLOBBER ) 
+            ENDIF
+            IF( snc4set%luse ) THEN
+               IF(lwp) WRITE(numout,*) TRIM(clinfo)//' creating file: '//TRIM(cdname)//' in hdf5 (netcdf4) mode'
+               CALL GET_NF90_SYMBOL("NF90_HDF5", ihdf5)
+               IF( llclobber ) THEN   ;   imode = IOR(ihdf5, NF90_CLOBBER)
+               ELSE                   ;   imode = IOR(ihdf5, NF90_NOCLOBBER)
+               ENDIF
+               CALL iom_nf90_check(NF90_CREATE( TRIM(cdname), imode, if90id ), clinfo)
+            ELSE
+               CALL iom_nf90_check(NF90_CREATE( TRIM(cdname), imode, if90id, chunksize = ichunk ), clinfo)
+            ENDIF
+            CALL iom_nf90_check(NF90_SET_FILL( if90id, NF90_NOFILL,                   idmy ), clinfo)
+            ! define dimensions
+            CALL iom_nf90_check(NF90_DEF_DIM( if90id,            'x',   kdompar(1,1), idmy ), clinfo)
+            CALL iom_nf90_check(NF90_DEF_DIM( if90id,            'y',   kdompar(2,1), idmy ), clinfo)
+            CALL iom_nf90_check(NF90_DEF_DIM( if90id,      'nav_lev',            jpk, idmy ), clinfo)
+            CALL iom_nf90_check(NF90_DEF_DIM( if90id, 'time_counter', NF90_UNLIMITED, idmy ), clinfo)
+            IF( PRESENT(kdlev) )   &
+               CALL iom_nf90_check(NF90_DEF_DIM( if90id,    'numcat',          kdlev, idmy ), clinfo)
+            ! global attributes
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_number_total'   , jpnij              ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_number'         , narea-1            ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_dimensions_ids' , (/1     , 2     /) ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_size_global'    , (/jpiglo, jpjglo/) ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_size_local'     , kdompar(:,1)       ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_position_first' , kdompar(:,2)       ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_position_last'  , kdompar(:,3)       ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_halo_size_start', kdompar(:,4)       ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_halo_size_end'  , kdompar(:,5)       ), clinfo)
+            CALL iom_nf90_check(NF90_PUT_ATT( if90id, NF90_GLOBAL, 'DOMAIN_type'           , 'BOX'              ), clinfo)
+         ELSE                          !* the file should be open for read mode so it must exist...
+            CALL ctl_stop( TRIM(clinfo), ' should be impossible case...' )
+         ENDIF
+      ENDIF
+      !
+      ! start to fill file informations
+      ! =============
+      IF( istop == nstop ) THEN   ! no error within this routine
+!does not work with some compilers         kiomid = MINLOC(iom_file(:)%nfid, dim = 1)
+         kiomid = 0
+         DO jl = jpmax_files, 1, -1
+            IF( iom_file(jl)%nfid == 0 )   kiomid = jl
+         ENDDO
+         iom_file(kiomid)%name   = TRIM(cdname)
+         iom_file(kiomid)%nfid   = if90id
+         iom_file(kiomid)%nvars  = 0
+         iom_file(kiomid)%irec   = -1   ! useless for NetCDF files, used to know if the file is in define mode 
+         iom_file(kiomid)%nlev   = ilevels
+         CALL iom_nf90_check(NF90_Inquire(if90id, unlimitedDimId = iom_file(kiomid)%iduld), clinfo)
+         IF( iom_file(kiomid)%iduld .GE. 0 ) THEN
+            CALL iom_nf90_check(NF90_Inquire_Dimension(if90id, iom_file(kiomid)%iduld,    & 
+               &                                       name = iom_file(kiomid)%uldname,   &
+               &                                       len  = iom_file(kiomid)%lenuld ), clinfo )
+         ENDIF
+         IF(lwp) WRITE(numout,*) '                   ---> '//TRIM(cdname)//' OK'
+      ELSE
+         kiomid = 0               ! return error flag
+      ENDIF
+      !
+   END SUBROUTINE iom_nf90_open
+
+
+   SUBROUTINE iom_nf90_close( kiomid )
+      !!--------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_nf90_close  ***
+      !!
+      !! ** Purpose : close an input file with NF90
+      !!--------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kiomid   ! iom identifier of the file to be closed
+      CHARACTER(LEN=100)  ::   clinfo   ! info character
+      !---------------------------------------------------------------------
+      clinfo = '      iom_nf90_close    , file: '//TRIM(iom_file(kiomid)%name)
+      CALL iom_nf90_check(NF90_CLOSE(iom_file(kiomid)%nfid), clinfo)
+   END SUBROUTINE iom_nf90_close
+
+
+   FUNCTION iom_nf90_varid ( kiomid, cdvar, kiv, kdimsz, kndims, lduld )  
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION  iom_varid  ***
+      !!
+      !! ** Purpose : get the id of a variable in a file with NF90
+      !!-----------------------------------------------------------------------
+      INTEGER              , INTENT(in   )           ::   kiomid   ! file Identifier
+      CHARACTER(len=*)     , INTENT(in   )           ::   cdvar    ! name of the variable
+      INTEGER              , INTENT(in   )           ::   kiv   ! 
+      INTEGER, DIMENSION(:), INTENT(  out), OPTIONAL ::   kdimsz   ! size of the dimensions
+      INTEGER,               INTENT(  out), OPTIONAL ::   kndims   ! size of the dimensions
+      LOGICAL              , INTENT(  out), OPTIONAL ::   lduld    ! true if the last dimension is unlimited (time)
+      !
+      INTEGER                        ::   iom_nf90_varid   ! iom variable Id
+      INTEGER                        ::   if90id           ! nf90 file identifier
+      INTEGER                        ::   ji               ! dummy loop index
+      INTEGER                        ::   ivarid           ! NetCDF  variable Id
+      INTEGER                        ::   i_nvd            ! number of dimension of the variable
+      INTEGER, DIMENSION(jpmax_dims) ::   idimid           ! dimension ids of the variable
+      LOGICAL                        ::   llok             ! ok  test
+      CHARACTER(LEN=100)             ::   clinfo           ! info character
+      !!-----------------------------------------------------------------------
+      clinfo = '          iom_nf90_varid, file: '//TRIM(iom_file(kiomid)%name)//', var: '//TRIM(cdvar)
+      iom_nf90_varid = 0                    ! default definition
+      IF( PRESENT(kdimsz) ) kdimsz(:) = 0   ! default definition
+      if90id = iom_file(kiomid)%nfid        ! get back NetCDF file id
+      !
+      llok = NF90_INQ_VARID( if90id, TRIM(cdvar), ivarid ) == nf90_noerr   ! does the variable exist in the file
+      IF( llok ) THEN
+         iom_nf90_varid = kiv
+         iom_file(kiomid)%nvars       = kiv
+         iom_file(kiomid)%nvid(kiv)   = ivarid
+         iom_file(kiomid)%cn_var(kiv) = TRIM(cdvar)
+         CALL iom_nf90_check(NF90_Inquire_Variable(if90id, ivarid, ndims = i_nvd), clinfo)   ! number of dimensions
+         iom_file(kiomid)%ndims(kiv)  = i_nvd
+         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
+         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)   
+            IF( idimid(ji) == iom_file(kiomid)%iduld ) iom_file(kiomid)%luld(kiv) = .TRUE.   ! unlimited dimension? 
+         END DO
+         !---------- Deal with scale_factor and add_offset
+         llok = NF90_Inquire_attribute(if90id, ivarid, 'scale_factor') == nf90_noerr
+         IF( llok) THEN
+            CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, 'scale_factor', iom_file(kiomid)%scf(kiv)), clinfo)
+         ELSE
+            iom_file(kiomid)%scf(kiv) = 1.
+         END IF
+         llok = NF90_Inquire_attribute(if90id, ivarid, 'add_offset') == nf90_noerr
+         IF( llok ) THEN
+            CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, 'add_offset', iom_file(kiomid)%ofs(kiv)), clinfo)
+         ELSE
+            iom_file(kiomid)%ofs(kiv) = 0.
+         END IF
+         ! return the simension size
+         IF( PRESENT(kdimsz) ) THEN 
+            IF( i_nvd <= SIZE(kdimsz) ) THEN
+               kdimsz(1:i_nvd) = iom_file(kiomid)%dimsz(1:i_nvd,kiv)
+            ELSE
+               WRITE(ctmp1,*) i_nvd, SIZE(kdimsz)
+               CALL ctl_stop( TRIM(clinfo), 'error in kdimsz size'//TRIM(ctmp1) )
+            ENDIF
+         ENDIF
+         IF( PRESENT(kndims) )  kndims = iom_file(kiomid)%ndims(kiv)
+         IF( PRESENT( lduld) )  lduld  = iom_file(kiomid)%luld(kiv)
+      ELSE  
+         iom_nf90_varid = -1   !   variable not found, return error code: -1
+      ENDIF
+      !
+   END FUNCTION iom_nf90_varid
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_nf90_get
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE iom_nf90_g0d( kiomid, kvid, pvar, kstart )
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_nf90_g0d  ***
+      !!
+      !! ** Purpose : read a scalar with NF90
+      !!-----------------------------------------------------------------------
+      INTEGER ,               INTENT(in   )            ::   kiomid   ! Identifier of the file
+      INTEGER ,               INTENT(in   )            ::   kvid     ! variable id
+      REAL(wp),               INTENT(  out)            ::   pvar     ! read field
+      INTEGER , DIMENSION(1), INTENT(in   ), OPTIONAL  ::   kstart   ! start position of the reading in each axis
+      !
+      CHARACTER(LEN=100)      ::   clinfo   ! info character
+      !---------------------------------------------------------------------
+      clinfo = 'iom_nf90_g0d , file: '//TRIM(iom_file(kiomid)%name)//', var: '//TRIM(iom_file(kiomid)%cn_var(kvid))
+      CALL iom_nf90_check(NF90_GET_VAR(iom_file(kiomid)%nfid, iom_file(kiomid)%nvid(kvid), pvar, start = kstart), clinfo )
+   END SUBROUTINE iom_nf90_g0d
+
+
+   SUBROUTINE iom_nf90_g123d( kiomid, kvid, knbdim, kstart, kcount, kx1, kx2, ky1, ky2,   &
+         &                    pv_r1d, pv_r2d, pv_r3d )
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_nf90_g123d  ***
+      !!
+      !! ** Purpose : read a 1D/2D/3D variable with NF90
+      !!
+      !! ** Method : read ONE record at each CALL
+      !!-----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   )           ::   kiomid    ! iom identifier of the file
+      INTEGER                    , INTENT(in   )           ::   kvid      ! Name of the variable
+      INTEGER                    , INTENT(in   )           ::   knbdim    ! number of dimensions of the variable
+      INTEGER , DIMENSION(:)     , INTENT(in   )           ::   kstart    ! start position of the reading in each axis 
+      INTEGER , DIMENSION(:)     , INTENT(in   )           ::   kcount    ! number of points to be read in each axis
+      INTEGER ,                    INTENT(in   )           ::   kx1, kx2, ky1, ky2   ! subdomain indexes
+      REAL(wp), DIMENSION(:)     , INTENT(  out), OPTIONAL ::   pv_r1d    ! read field (1D case)
+      REAL(wp), DIMENSION(:,:)   , INTENT(  out), OPTIONAL ::   pv_r2d    ! read field (2D case)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(  out), OPTIONAL ::   pv_r3d    ! read field (3D case)
+      !
+      CHARACTER(LEN=100) ::   clinfo               ! info character
+      INTEGER            ::   if90id               ! nf90 identifier of the opened file
+      INTEGER            ::   ivid                 ! nf90 variable id
+      !---------------------------------------------------------------------
+      clinfo = 'iom_nf90_g123d , file: '//TRIM(iom_file(kiomid)%name)//', var: '//TRIM(iom_file(kiomid)%cn_var(kvid))
+      if90id = iom_file(kiomid)%nfid         ! get back NetCDF file id
+      ivid   = iom_file(kiomid)%nvid(kvid)   ! get back NetCDF var id
+      !
+      IF(     PRESENT(pv_r1d) ) THEN
+         CALL iom_nf90_check( NF90_GET_VAR(if90id, ivid, pv_r1d(:                ), start = kstart(1:knbdim),   &
+            &                                                                       count = kcount(1:knbdim)), clinfo )
+      ELSEIF( PRESENT(pv_r2d) ) THEN
+         CALL iom_nf90_check( NF90_GET_VAR(if90id, ivid, pv_r2d(kx1:kx2,ky1:ky2  ), start = kstart(1:knbdim),   &
+            &                                                                       count = kcount(1:knbdim)), clinfo )
+      ELSEIF( PRESENT(pv_r3d) ) THEN
+         CALL iom_nf90_check( NF90_GET_VAR(if90id, ivid, pv_r3d(kx1:kx2,ky1:ky2,:), start = kstart(1:knbdim),   &
+            &                                                                       count = kcount(1:knbdim)), clinfo )
+      ENDIF
+      !
+   END SUBROUTINE iom_nf90_g123d
+
+
+   SUBROUTINE iom_nf90_chkatt( kiomid, cdatt, llok, ksize, cdvar )
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_nf90_chkatt  ***
+      !!
+      !! ** Purpose : check existence of attribute with NF90
+      !!              (either a global attribute (default) or a variable
+      !!               attribute if optional variable name is supplied (cdvar))
+      !!-----------------------------------------------------------------------
+      INTEGER         , INTENT(in   ) ::   kiomid   ! Identifier of the file
+      CHARACTER(len=*), INTENT(in   ) ::   cdatt    ! attribute name
+      LOGICAL         , INTENT(  out) ::   llok     ! error code
+      INTEGER         , INTENT(  out), OPTIONAL     &
+                      &               ::   ksize    ! attribute size
+      CHARACTER(len=*), INTENT(in   ), OPTIONAL     &
+                      &               ::   cdvar    ! name of the variable
+      !
+      INTEGER                         ::   if90id   ! temporary integer
+      INTEGER                         ::   isize    ! temporary integer
+      INTEGER                         ::   ivarid   ! NetCDF variable Id
+      !---------------------------------------------------------------------
+      !
+      if90id = iom_file(kiomid)%nfid
+      IF( PRESENT(cdvar) ) THEN
+         ! check the variable exists in the file
+         llok = NF90_INQ_VARID( if90id, TRIM(cdvar), ivarid ) == nf90_noerr
+         IF( llok ) &
+            ! check the variable has the attribute required
+            llok = NF90_Inquire_attribute(if90id, ivarid, cdatt, len=isize ) == nf90_noerr
+      ELSE
+         llok = NF90_Inquire_attribute(if90id, NF90_GLOBAL, cdatt, len=isize ) == nf90_noerr
+      ENDIF
+      !
+      IF( PRESENT(ksize) ) ksize = isize
+      !
+      IF( .not. llok) &
+         CALL ctl_warn('iom_nf90_chkatt: no attribute '//cdatt//' found')
+      !
+   END SUBROUTINE iom_nf90_chkatt
+
+
+   !!----------------------------------------------------------------------
+   !!                   INTERFACE iom_nf90_getatt
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE iom_nf90_getatt( kiomid, cdatt, katt0d, katt1d, patt0d, patt1d, cdatt0d, cdvar)
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_nf90_getatt  ***
+      !!
+      !! ** Purpose : read an attribute with NF90
+      !!              (either a global attribute (default) or a variable
+      !!               attribute if optional variable name is supplied (cdvar))
+      !!-----------------------------------------------------------------------
+      INTEGER               , INTENT(in   )           ::   kiomid   ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt    ! attribute name
+      INTEGER               , INTENT(  out), OPTIONAL ::   katt0d   ! read scalar integer
+      INTEGER, DIMENSION(:) , INTENT(  out), OPTIONAL ::   katt1d   ! read 1d array integer
+      REAL(wp)              , INTENT(  out), OPTIONAL ::   patt0d   ! read scalar  real
+      REAL(wp), DIMENSION(:), INTENT(  out), OPTIONAL ::   patt1d   ! read 1d array real
+      CHARACTER(len=*)      , INTENT(  out), OPTIONAL ::   cdatt0d  ! read character
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar    ! name of the variable
+      !
+      INTEGER                         ::   if90id   ! temporary integer
+      INTEGER                         ::   ivarid   ! NetCDF variable Id
+      LOGICAL                         ::   llok     ! temporary logical
+      CHARACTER(LEN=100)              ::   clinfo   ! info character
+      !---------------------------------------------------------------------
+      !
+      if90id = iom_file(kiomid)%nfid
+      IF( PRESENT(cdvar) ) THEN
+         ! check the variable exists in the file
+         llok = NF90_INQ_VARID( if90id, TRIM(cdvar), ivarid ) == nf90_noerr
+         IF( llok ) THEN
+            ! check the variable has the attribute required
+            llok = NF90_Inquire_attribute(if90id, ivarid, cdatt) == nf90_noerr
+         ELSE
+            CALL ctl_warn('iom_nf90_getatt: no variable '//TRIM(cdvar)//' found')
+         ENDIF
+      ELSE
+         llok = NF90_Inquire_attribute(if90id, NF90_GLOBAL, cdatt) == nf90_noerr
+         ivarid = NF90_GLOBAL
+      ENDIF
+      !
+      IF( llok) THEN
+         clinfo = 'iom_nf90_getatt, file: '//TRIM(iom_file(kiomid)%name)//', att: '//TRIM(cdatt)
+         IF(PRESENT( katt0d))   CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, cdatt, values =  katt0d), clinfo)
+         IF(PRESENT( katt1d))   CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, cdatt, values =  katt1d), clinfo)
+         IF(PRESENT( patt0d))   CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, cdatt, values =  patt0d), clinfo)
+         IF(PRESENT( patt1d))   CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, cdatt, values =  patt1d), clinfo)
+         IF(PRESENT(cdatt0d))   CALL iom_nf90_check(NF90_GET_ATT(if90id, ivarid, cdatt, values = cdatt0d), clinfo)
+      ELSE
+         CALL ctl_warn('iom_nf90_getatt: no attribute '//TRIM(cdatt)//' found')
+         IF(PRESENT( katt0d))    katt0d    = -999
+         IF(PRESENT( katt1d))    katt1d(:) = -999
+         IF(PRESENT( patt0d))    patt0d    = -999._wp
+         IF(PRESENT( patt1d))    patt1d(:) = -999._wp
+         IF(PRESENT(cdatt0d))   cdatt0d    = '!'
+      ENDIF
+      !
+   END SUBROUTINE iom_nf90_getatt
+
+
+   SUBROUTINE iom_nf90_putatt( kiomid, cdatt, katt0d, katt1d, patt0d, patt1d, cdatt0d, cdvar)
+      !!-----------------------------------------------------------------------
+      !!                  ***  ROUTINE  iom_nf90_putatt  ***
+      !!
+      !! ** Purpose : write an attribute with NF90
+      !!              (either a global attribute (default) or a variable
+      !!               attribute if optional variable name is supplied (cdvar))
+      !!-----------------------------------------------------------------------
+      INTEGER               , INTENT(in   )           ::   kiomid   ! Identifier of the file
+      CHARACTER(len=*)      , INTENT(in   )           ::   cdatt    ! attribute name
+      INTEGER               , INTENT(in   ), OPTIONAL ::   katt0d   ! read scalar integer
+      INTEGER, DIMENSION(:) , INTENT(in   ), OPTIONAL ::   katt1d   ! read 1d array integer
+      REAL(wp)              , INTENT(in   ), OPTIONAL ::   patt0d   ! read scalar  real
+      REAL(wp), DIMENSION(:), INTENT(in   ), OPTIONAL ::   patt1d   ! read 1d array real
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdatt0d  ! read character
+      CHARACTER(len=*)      , INTENT(in   ), OPTIONAL ::   cdvar    ! name of the variable
+      !
+      INTEGER                         ::   if90id   ! temporary integer
+      INTEGER                         ::   ivarid   ! NetCDF variable Id
+      INTEGER                         ::   isize    ! Attribute size
+      INTEGER                         ::   itype    ! Attribute type
+      LOGICAL                         ::   llok     ! temporary logical
+      LOGICAL                         ::   llatt     ! temporary logical
+      LOGICAL                         ::   lldata   ! temporary logical
+      CHARACTER(LEN=100)              ::   clinfo   ! info character
+      !---------------------------------------------------------------------
+      !
+      if90id = iom_file(kiomid)%nfid
+      IF( PRESENT(cdvar) ) THEN
+         llok = NF90_INQ_VARID( if90id, TRIM(cdvar), ivarid ) == nf90_noerr   ! is the variable in the file?
+         IF( .NOT. llok ) THEN
+            CALL ctl_warn('iom_nf90_putatt: no variable '//TRIM(cdvar)//' found'   &
+               &        , '                 no attribute '//cdatt//' written' )
+            RETURN
+         ENDIF
+      ELSE
+         ivarid = NF90_GLOBAL
+      ENDIF
+      llatt = NF90_Inquire_attribute(if90id, ivarid, cdatt, len = isize, xtype = itype ) == nf90_noerr
+      !
+      ! trick: irec used to know if the file is in define mode or not
+      lldata = iom_file(kiomid)%irec /= -1   ! default: go back in define mode if in data mode
+      IF( lldata .AND. llatt ) THEN          ! attribute already there. Do we really need to go back in define mode?
+         ! do we have the appropriate type?
+         IF(PRESENT( katt0d) .OR. PRESENT( katt1d))   llok = itype == NF90_INT
+         IF(PRESENT( patt0d) .OR. PRESENT( patt1d))   llok = itype == NF90_DOUBLE
+         IF(PRESENT(cdatt0d)                      )   llok = itype == NF90_CHAR
+         ! and do we have the appropriate size?
+         IF(PRESENT( katt0d))   llok = llok .AND. isize == 1
+         IF(PRESENT( katt1d))   llok = llok .AND. isize == SIZE(katt1d)
+         IF(PRESENT( patt0d))   llok = llok .AND. isize == 1
+         IF(PRESENT( patt1d))   llok = llok .AND. isize == SIZE(patt1d)
+         IF(PRESENT(cdatt0d))   llok = llok .AND. isize == LEN_TRIM(cdatt0d)
+         !
+         lldata = .NOT. llok
+      ENDIF
+      !
+      clinfo = 'iom_nf90_putatt, file: '//TRIM(iom_file(kiomid)%name)//', att: '//TRIM(cdatt)
+      IF(lldata)   CALL iom_nf90_check(NF90_REDEF( if90id ), clinfo)   ! leave data mode to define mode
+      !
+      IF(PRESENT( katt0d))   CALL iom_nf90_check(NF90_PUT_ATT(if90id, ivarid, cdatt, values =       katt0d) , clinfo)
+      IF(PRESENT( katt1d))   CALL iom_nf90_check(NF90_PUT_ATT(if90id, ivarid, cdatt, values =       katt1d) , clinfo)
+      IF(PRESENT( patt0d))   CALL iom_nf90_check(NF90_PUT_ATT(if90id, ivarid, cdatt, values =       patt0d) , clinfo)
+      IF(PRESENT( patt1d))   CALL iom_nf90_check(NF90_PUT_ATT(if90id, ivarid, cdatt, values =       patt1d) , clinfo)
+      IF(PRESENT(cdatt0d))   CALL iom_nf90_check(NF90_PUT_ATT(if90id, ivarid, cdatt, values = trim(cdatt0d)), clinfo)
+      !
+      IF(lldata)   CALL iom_nf90_check(NF90_ENDDEF( if90id ), clinfo)   ! leave define mode to data mode
+      !
+   END SUBROUTINE iom_nf90_putatt
+
+
+   SUBROUTINE iom_nf90_rp0123d( kt, kwrite, kiomid, cdvar , kvid  , ktype,   &
+         &                                  pv_r0d, pv_r1d, pv_r2d, pv_r3d )
+      !!--------------------------------------------------------------------
+      !!                   ***  SUBROUTINE  iom_nf90_rstput  ***
+      !!
+      !! ** Purpose : read the time axis cdvar in the file 
+      !!--------------------------------------------------------------------
+      INTEGER                     , INTENT(in)           ::   kt       ! ocean time-step
+      INTEGER                     , INTENT(in)           ::   kwrite   ! writing time-step
+      INTEGER                     , INTENT(in)           ::   kiomid   ! Identifier of the file 
+      CHARACTER(len=*)            , INTENT(in)           ::   cdvar    ! variable name
+      INTEGER                     , INTENT(in)           ::   kvid     ! variable id
+      INTEGER                     , INTENT(in), OPTIONAL ::   ktype    ! variable type (default R8)
+      REAL(wp)                    , INTENT(in), OPTIONAL ::   pv_r0d   ! written Od field
+      REAL(wp), DIMENSION(      :), INTENT(in), OPTIONAL ::   pv_r1d   ! written 1d field
+      REAL(wp), DIMENSION(:, :   ), INTENT(in), OPTIONAL ::   pv_r2d   ! written 2d field
+      REAL(wp), DIMENSION(:, :, :), INTENT(in), OPTIONAL ::   pv_r3d   ! written 3d field
+      !
+      INTEGER               :: idims                ! number of dimension
+      INTEGER               :: idvar                ! variable id
+      INTEGER               :: jd                   ! dimension loop counter   
+      INTEGER               :: ix1, ix2, iy1, iy2   ! subdomain indexes   
+      INTEGER, DIMENSION(4) :: idimsz               ! dimensions size  
+      INTEGER, DIMENSION(4) :: idimid               ! dimensions id
+      CHARACTER(LEN=256)    :: clinfo               ! info character
+      CHARACTER(LEN= 12), DIMENSION(5) :: cltmp     ! temporary character
+      INTEGER               :: if90id               ! nf90 file identifier
+      INTEGER               :: idmy                 ! dummy variable
+      INTEGER               :: itype                ! variable type
+      INTEGER, DIMENSION(4) :: ichunksz             ! NetCDF4 chunk sizes. Will be computed using
+      !                                             ! nn_nchunks_[i,j,k,t] namelist parameters
+      INTEGER               :: ichunkalg, ishuffle, ideflate, ideflate_level
+      !                                             ! NetCDF4 internally fixed parameters
+      LOGICAL               :: lchunk               ! logical switch to activate chunking and compression
+      !                                             ! when appropriate (currently chunking is applied to 4d fields only)
+      INTEGER               :: idlv                 ! local variable
+      INTEGER               :: idim3                ! id of the third dimension
+      !---------------------------------------------------------------------
+      !
+      clinfo = '          iom_nf90_rp0123d, file: '//TRIM(iom_file(kiomid)%name)//', var: '//TRIM(cdvar)
+      if90id = iom_file(kiomid)%nfid
+      !
+      ! define dimension variables if it is not already done
+      ! ==========================
+      IF( iom_file(kiomid)%nvars == 0 ) THEN
+         ! are we in define mode?
+         IF( iom_file(kiomid)%irec /= -1 ) THEN   ! trick: irec used to know if the file is in define mode or not
+            CALL iom_nf90_check(NF90_REDEF( if90id ), clinfo)   ;   iom_file(kiomid)%irec = -1
+         ENDIF
+         ! define the dimension variables if it is not already done
+         ! Warning: we must use the same character length in an array constructor (at least for gcc compiler)
+         cltmp = (/ 'nav_lon     ', 'nav_lat     ', 'nav_lev     ', 'time_counter', 'numcat      ' /)   
+         CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cltmp(1)), NF90_FLOAT , (/ 1, 2 /), iom_file(kiomid)%nvid(1) ), clinfo)
+         CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cltmp(2)), NF90_FLOAT , (/ 1, 2 /), iom_file(kiomid)%nvid(2) ), clinfo)
+         CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cltmp(3)), NF90_FLOAT , (/ 3    /), iom_file(kiomid)%nvid(3) ), clinfo)
+         CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cltmp(4)), NF90_DOUBLE, (/ 4    /), iom_file(kiomid)%nvid(4) ), clinfo)
+         ! update informations structure related the dimension variable we just added...
+         iom_file(kiomid)%nvars       = 4
+         iom_file(kiomid)%luld(1:4)   = (/ .FALSE., .FALSE., .FALSE., .TRUE. /)
+         iom_file(kiomid)%cn_var(1:4) = cltmp(1:4)
+         iom_file(kiomid)%ndims(1:4)  = (/ 2, 2, 1, 1 /)
+         IF( NF90_INQ_DIMID( if90id, 'numcat', idmy ) == nf90_noerr ) THEN   ! add a 5th variable corresponding to the 5th dimension
+            CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cltmp(5)), NF90_FLOAT , (/ 5 /), iom_file(kiomid)%nvid(5) ), clinfo)
+            iom_file(kiomid)%nvars     = 5
+            iom_file(kiomid)%luld(5)   = .FALSE.
+            iom_file(kiomid)%cn_var(5) = cltmp(5)
+            iom_file(kiomid)%ndims(5)  = 1
+         ENDIF
+         ! trick: defined to 0 to say that dimension variables are defined but not yet written
+         iom_file(kiomid)%dimsz(1, 1)  = 0   
+         IF(lwp) WRITE(numout,*) TRIM(clinfo)//' define dimension variables done'
+      ENDIF
+      ! define the data if it is not already done
+      ! ===============
+      IF( kvid <= 0 ) THEN
+         !
+         ! NetCDF4 chunking and compression fixed settings
+         ichunkalg = 0
+         ishuffle = 1
+         ideflate = 1
+         ideflate_level = 1
+         !
+         idvar = iom_file(kiomid)%nvars + 1
+         ! are we in define mode?
+         IF( iom_file(kiomid)%irec /= -1 ) THEN   ! trick: irec used to know if the file is in define mode or not
+            CALL iom_nf90_check(NF90_REDEF( if90id ), clinfo)   ;   iom_file(kiomid)%irec = -1
+         ENDIF
+         ! variable definition
+         IF(     PRESENT(pv_r0d) ) THEN   ;   idims = 0
+         ELSEIF( PRESENT(pv_r1d) ) THEN
+            IF( SIZE(pv_r1d,1) == jpk ) THEN   ;   idim3 = 3
+            ELSE                               ;   idim3 = 5
+            ENDIF
+                                              idims = 2   ;   idimid(1:idims) = (/idim3,4/)
+         ELSEIF( PRESENT(pv_r2d) ) THEN   ;   idims = 3   ;   idimid(1:idims) = (/1,2  ,4/)
+         ELSEIF( PRESENT(pv_r3d) ) THEN
+            IF( SIZE(pv_r3d,3) == jpk ) THEN   ;   idim3 = 3
+            ELSE                               ;   idim3 = 5
+            ENDIF
+                                              idims = 4   ;   idimid(1:idims) = (/1,2,idim3,4/)
+         ENDIF
+         IF( PRESENT(ktype) ) THEN   ! variable external type
+            SELECT CASE (ktype)
+            CASE (jp_r8)   ;   itype = NF90_DOUBLE
+            CASE (jp_r4)   ;   itype = NF90_FLOAT
+            CASE (jp_i4)   ;   itype = NF90_INT
+            CASE (jp_i2)   ;   itype = NF90_SHORT
+            CASE (jp_i1)   ;   itype = NF90_BYTE
+            CASE DEFAULT   ;   CALL ctl_stop( TRIM(clinfo)//' unknown variable type' )
+            END SELECT
+         ELSE
+            itype = NF90_DOUBLE
+         ENDIF
+         IF( PRESENT(pv_r0d) ) THEN
+            CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cdvar), itype,                    &
+               &                              iom_file(kiomid)%nvid(idvar) ), clinfo )
+         ELSE
+            CALL iom_nf90_check(NF90_DEF_VAR( if90id, TRIM(cdvar), itype, idimid(1:idims),   &
+               &                              iom_file(kiomid)%nvid(idvar) ), clinfo )
+         ENDIF
+         lchunk = .false.
+         IF( snc4set%luse .AND. idims == 4 )   lchunk = .true.
+         ! update informations structure related the new variable we want to add...
+         iom_file(kiomid)%nvars         = idvar
+         iom_file(kiomid)%cn_var(idvar) = TRIM(cdvar)
+         iom_file(kiomid)%scf(idvar)    = 1.
+         iom_file(kiomid)%ofs(idvar)    = 0.
+         iom_file(kiomid)%ndims(idvar)  = idims
+         IF( .NOT. PRESENT(pv_r0d) ) THEN   ;   iom_file(kiomid)%luld(idvar) = .TRUE.
+         ELSE                               ;   iom_file(kiomid)%luld(idvar) = .FALSE.
+         ENDIF
+         DO jd = 1, idims
+            CALL iom_nf90_check(NF90_INQUIRE_DIMENSION( if90id, idimid(jd), len = iom_file(kiomid)%dimsz(jd,idvar) ), clinfo)
+            IF ( lchunk ) ichunksz(jd) = iom_file(kiomid)%dimsz(jd,idvar)
+         END DO
+         IF ( lchunk ) THEN
+            ! Calculate chunk sizes by partitioning each dimension as requested in namnc4 namelist
+            ! Disallow very small chunk sizes and prevent chunk sizes larger than each individual dimension
+            ichunksz(1) = MIN( ichunksz(1),MAX( (ichunksz(1)-1)/snc4set%ni + 1 ,16 ) ) ! Suggested default nc4set%ni=4
+            ichunksz(2) = MIN( ichunksz(2),MAX( (ichunksz(2)-1)/snc4set%nj + 1 ,16 ) ) ! Suggested default nc4set%nj=2
+            ichunksz(3) = MIN( ichunksz(3),MAX( (ichunksz(3)-1)/snc4set%nk + 1 , 1 ) ) ! Suggested default nc4set%nk=6
+            ichunksz(4) = 1                                                            ! Do not allow chunks to span the
+            !                                                                          ! unlimited dimension
+            CALL iom_nf90_check(SET_NF90_DEF_VAR_CHUNKING(if90id, idvar, ichunkalg, ichunksz), clinfo)
+            CALL iom_nf90_check(SET_NF90_DEF_VAR_DEFLATE(if90id, idvar, ishuffle, ideflate, ideflate_level), clinfo)
+            IF(lwp) WRITE(numout,*) TRIM(clinfo)//' chunked ok. Chunks sizes: ', ichunksz
+         ENDIF
+         IF(lwp) WRITE(numout,*) TRIM(clinfo)//' defined ok'
+      ELSE
+         idvar = kvid
+      ENDIF
+      !
+      ! time step kwrite : write the variable
+      IF( kt == kwrite ) THEN
+         ! are we in write mode?
+         IF( iom_file(kiomid)%irec == -1 ) THEN   ! trick: irec used to know if the file is in define mode or not
+            CALL iom_nf90_check(NF90_ENDDEF( if90id ), clinfo)   ;   iom_file(kiomid)%irec = 0
+         ENDIF
+         ! on what kind of domain must the data be written?
+         IF( PRESENT(pv_r2d) .OR. PRESENT(pv_r3d) ) THEN
+            idimsz(1:2) = iom_file(kiomid)%dimsz(1:2,idvar)
+            IF(     idimsz(1) == (nlei - nldi + 1) .AND. idimsz(2) == (nlej - nldj + 1) ) THEN
+               ix1 = nldi   ;   ix2 = nlei   ;   iy1 = nldj   ;   iy2 = nlej
+            ELSEIF( idimsz(1) == nlci              .AND. idimsz(2) == nlcj              ) THEN
+               ix1 = 1      ;   ix2 = nlci   ;   iy1 = 1      ;   iy2 = nlcj
+            ELSEIF( idimsz(1) == jpi               .AND. idimsz(2) == jpj               ) THEN
+               ix1 = 1      ;   ix2 = jpi    ;   iy1 = 1      ;   iy2 = jpj
+            ELSE 
+               CALL ctl_stop( 'iom_nf90_rp0123d: should have been an impossible case...' )
+            ENDIF
+
+            ! write dimension variables if it is not already done
+            ! =============
+            ! trick: is defined to 0 => dimension variable are defined but not yet written
+            IF( iom_file(kiomid)%dimsz(1, 1) == 0 ) THEN
+               CALL iom_nf90_check( NF90_INQ_VARID( if90id, 'nav_lon'     , idmy )         , clinfo )
+               CALL iom_nf90_check( NF90_PUT_VAR  ( if90id, idmy, glamt(ix1:ix2, iy1:iy2) ), clinfo )
+               CALL iom_nf90_check( NF90_INQ_VARID( if90id, 'nav_lat'     , idmy )         , clinfo )
+               CALL iom_nf90_check( NF90_PUT_VAR  ( if90id, idmy, gphit(ix1:ix2, iy1:iy2) ), clinfo )
+               CALL iom_nf90_check( NF90_INQ_VARID( if90id, 'nav_lev'     , idmy ), clinfo )
+               CALL iom_nf90_check( NF90_PUT_VAR  ( if90id, idmy, gdept_1d       ), clinfo )
+               IF( NF90_INQ_VARID( if90id, 'numcat', idmy ) == nf90_noerr ) THEN
+                  CALL iom_nf90_check( NF90_PUT_VAR  ( if90id, idmy, (/ (idlv, idlv = 1,iom_file(kiomid)%nlev) /)), clinfo )
+               ENDIF
+               ! +++ WRONG VALUE: to be improved but not really useful...
+               CALL iom_nf90_check( NF90_INQ_VARID( if90id, 'time_counter', idmy ), clinfo )
+               CALL iom_nf90_check( NF90_PUT_VAR( if90id, idmy, kt                      ), clinfo )   
+               ! update the values of the variables dimensions size
+               CALL iom_nf90_check( NF90_INQUIRE_DIMENSION( if90id, 1, len = iom_file(kiomid)%dimsz(1,1) ), clinfo )
+               CALL iom_nf90_check( NF90_INQUIRE_DIMENSION( if90id, 2, len = iom_file(kiomid)%dimsz(2,1) ), clinfo )
+               iom_file(kiomid)%dimsz(1:2, 2) = iom_file(kiomid)%dimsz(1:2, 1)
+               CALL iom_nf90_check( NF90_INQUIRE_DIMENSION( if90id, 3, len = iom_file(kiomid)%dimsz(1,3) ), clinfo )
+               iom_file(kiomid)%dimsz(1  , 4) = 1   ! unlimited dimension
+               IF(lwp) WRITE(numout,*) TRIM(clinfo)//' write dimension variables done'
+            ENDIF
+         ENDIF
+
+         ! write the data
+         ! =============
+         IF(     PRESENT(pv_r0d) ) THEN
+            CALL iom_nf90_check( NF90_PUT_VAR( if90id, idvar, pv_r0d                    ), clinfo )
+         ELSEIF( PRESENT(pv_r1d) ) THEN
+            CALL iom_nf90_check( NF90_PUT_VAR( if90id, idvar, pv_r1d(:)                 ), clinfo )
+         ELSEIF( PRESENT(pv_r2d) ) THEN
+            CALL iom_nf90_check( NF90_PUT_VAR( if90id, idvar, pv_r2d(ix1:ix2,iy1:iy2)   ), clinfo )
+         ELSEIF( PRESENT(pv_r3d) ) THEN
+            CALL iom_nf90_check( NF90_PUT_VAR( if90id, idvar, pv_r3d(ix1:ix2,iy1:iy2,:) ), clinfo )
+         ENDIF
+         ! add 1 to the size of the temporal dimension (not really useful...)
+         IF( iom_file(kiomid)%luld(idvar) )   iom_file(kiomid)%dimsz(iom_file(kiomid)%ndims(idvar), idvar)    &
+               &                            = iom_file(kiomid)%dimsz(iom_file(kiomid)%ndims(idvar), idvar) + 1
+         IF(lwp) WRITE(numout,*) TRIM(clinfo)//' written ok'
+      ENDIF
+      !     
+   END SUBROUTINE iom_nf90_rp0123d
+
+
+   SUBROUTINE iom_nf90_check( kstatus, cdinfo )
+      !!--------------------------------------------------------------------
+      !!                   ***  SUBROUTINE iom_nf90_check  ***
+      !!
+      !! ** Purpose :   check nf90 errors
+      !!--------------------------------------------------------------------
+      INTEGER,          INTENT(in) :: kstatus
+      CHARACTER(LEN=*), INTENT(in) :: cdinfo
+      !---------------------------------------------------------------------
+      IF(kstatus /= nf90_noerr)   CALL ctl_stop( 'iom_nf90_check : '//TRIM(nf90_strerror(kstatus)), TRIM(cdinfo) )
+   END SUBROUTINE iom_nf90_check
+
+   !!======================================================================
+END MODULE iom_nf90
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/prtctl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/prtctl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/prtctl.F90	(revision 14097)
@@ -0,0 +1,585 @@
+MODULE prtctl
+   !!======================================================================
+   !!                       ***  MODULE prtctl   ***
+   !! Ocean system : print all SUM trends for each processor domain
+   !!======================================================================
+   !! History :  9.0  !  05-07  (C. Talandier) original code
+   !!            3.4  !  11-11  (C. Harris) decomposition changes for running with CICE
+   !!----------------------------------------------------------------------
+   USE dom_oce          ! ocean space and time domain variables
+#if defined key_nemocice_decomp
+   USE ice_domain_size, only: nx_global, ny_global
+#endif
+   USE in_out_manager   ! I/O manager
+   USE lib_mpp          ! distributed memory computing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   numid
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   nlditl , nldjtl    ! first, last indoor index for each i-domain
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   nleitl , nlejtl    ! first, last indoor index for each j-domain
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   nimpptl, njmpptl   ! i-, j-indexes for each processor
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   nlcitl , nlcjtl    ! dimensions of every subdomain
+   INTEGER , DIMENSION(:), ALLOCATABLE, SAVE ::   ibonitl, ibonjtl   !
+
+   REAL(wp), DIMENSION(:), ALLOCATABLE, SAVE ::   t_ctll , s_ctll    ! previous tracer trend values
+   REAL(wp), DIMENSION(:), ALLOCATABLE, SAVE ::   u_ctll , v_ctll    ! previous velocity trend values
+
+   INTEGER ::   ktime   ! time step
+
+   PUBLIC prt_ctl         ! called by all subroutines
+   PUBLIC prt_ctl_info    ! called by all subroutines
+   PUBLIC prt_ctl_init    ! called by opa.F90
+   PUBLIC sub_dom         ! called by opa.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE prt_ctl (tab2d_1, tab3d_1, mask1, clinfo1, tab2d_2, tab3d_2,   &
+      &                                  mask2, clinfo2, kdim, clinfo3 )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl  ***
+      !!
+      !! ** Purpose : - print sum control of 2D or 3D arrays over the same area 
+      !!                in mono and mpp case. This way can be usefull when
+      !!                debugging a new parametrization in mono or mpp. 
+      !!
+      !! ** Method  : 2 possibilities exist when setting the ln_ctl parameter to
+      !!                .true. in the ocean namelist:
+      !!              - to debug a MPI run .vs. a mono-processor one; 
+      !!                the control print will be done over each sub-domain.
+      !!                The nictl[se] and njctl[se] parameters in the namelist must 
+      !!                be set to zero and [ij]splt to the corresponding splitted
+      !!                domain in MPI along respectively i-, j- directions.
+      !!              - to debug a mono-processor run over the whole domain/a specific area; 
+      !!                in the first case the nictl[se] and njctl[se] parameters must be set
+      !!                to zero else to the indices of the area to be controled. In both cases
+      !!                isplt and jsplt must be set to 1.
+      !!              - All arguments of the above calling sequence are optional so their
+      !!                name must be explicitly typed if used. For instance if the 3D
+      !!                array tn(:,:,:) must be passed through the prt_ctl subroutine, 
+      !!                it must looks like: CALL prt_ctl(tab3d_1=tn).
+      !!
+      !!                    tab2d_1 : first 2D array
+      !!                    tab3d_1 : first 3D array
+      !!                    mask1   : mask (3D) to apply to the tab[23]d_1 array
+      !!                    clinfo1 : information about the tab[23]d_1 array
+      !!                    tab2d_2 : second 2D array
+      !!                    tab3d_2 : second 3D array
+      !!                    mask2   : mask (3D) to apply to the tab[23]d_2 array
+      !!                    clinfo2 : information about the tab[23]d_2 array
+      !!                    kdim    : k- direction for 3D arrays 
+      !!                    clinfo3 : additional information 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:)  , INTENT(in), OPTIONAL ::   tab2d_1
+      REAL(wp), DIMENSION(:,:,:), INTENT(in), OPTIONAL ::   tab3d_1
+      REAL(wp), DIMENSION(:,:,:), INTENT(in), OPTIONAL ::   mask1
+      CHARACTER (len=*)         , INTENT(in), OPTIONAL ::   clinfo1
+      REAL(wp), DIMENSION(:,:)  , INTENT(in), OPTIONAL ::   tab2d_2
+      REAL(wp), DIMENSION(:,:,:), INTENT(in), OPTIONAL ::   tab3d_2
+      REAL(wp), DIMENSION(:,:,:), INTENT(in), OPTIONAL ::   mask2
+      CHARACTER (len=*)         , INTENT(in), OPTIONAL ::   clinfo2
+      INTEGER                   , INTENT(in), OPTIONAL ::   kdim
+      CHARACTER (len=*)         , INTENT(in), OPTIONAL ::   clinfo3
+      !
+      CHARACTER (len=15) :: cl2
+      INTEGER ::  jn, sind, eind, kdir,j_id
+      REAL(wp) :: zsum1, zsum2, zvctl1, zvctl2
+      REAL(wp), DIMENSION(jpi,jpj)     :: ztab2d_1, ztab2d_2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zmask1, zmask2, ztab3d_1, ztab3d_2
+      !!----------------------------------------------------------------------
+
+      ! Arrays, scalars initialization 
+      kdir      = jpkm1
+      cl2       = ''
+      zsum1     = 0.e0
+      zsum2     = 0.e0
+      zvctl1    = 0.e0
+      zvctl2    = 0.e0
+      ztab2d_1(:,:)   = 0.e0
+      ztab2d_2(:,:)   = 0.e0
+      ztab3d_1(:,:,:) = 0.e0
+      ztab3d_2(:,:,:) = 0.e0
+      zmask1  (:,:,:) = 1.e0
+      zmask2  (:,:,:) = 1.e0
+
+      ! Control of optional arguments
+      IF( PRESENT(clinfo2) )   cl2                  = clinfo2
+      IF( PRESENT(kdim)    )   kdir                 = kdim
+      IF( PRESENT(tab2d_1) )   ztab2d_1(:,:)        = tab2d_1(:,:)
+      IF( PRESENT(tab2d_2) )   ztab2d_2(:,:)        = tab2d_2(:,:)
+      IF( PRESENT(tab3d_1) )   ztab3d_1(:,:,1:kdir) = tab3d_1(:,:,1:kdir)
+      IF( PRESENT(tab3d_2) )   ztab3d_2(:,:,1:kdir) = tab3d_2(:,:,1:kdir)
+      IF( PRESENT(mask1)   )   zmask1  (:,:,:)      = mask1  (:,:,:)
+      IF( PRESENT(mask2)   )   zmask2  (:,:,:)      = mask2  (:,:,:)
+
+      IF( lk_mpp .AND. jpnij > 1 ) THEN       ! processor number
+         sind = narea
+         eind = narea
+      ELSE                                    ! processors total number
+         sind = 1
+         eind = ijsplt
+      ENDIF
+
+      ! Loop over each sub-domain, i.e. the total number of processors ijsplt
+      DO jn = sind, eind
+         ! Set logical unit
+         j_id = numid(jn - narea + 1)
+         ! Set indices for the SUM control
+         IF( .NOT. lsp_area ) THEN
+            IF (lk_mpp .AND. jpnij > 1)   THEN
+               nictls = MAX(  1, nlditl(jn) )
+               nictle = MIN(jpi, nleitl(jn) )
+               njctls = MAX(  1, nldjtl(jn) )
+               njctle = MIN(jpj, nlejtl(jn) )
+               ! Do not take into account the bound of the domain
+               IF( ibonitl(jn) == -1 .OR. ibonitl(jn) == 2 ) nictls = MAX(2, nictls)
+               IF( ibonjtl(jn) == -1 .OR. ibonjtl(jn) == 2 ) njctls = MAX(2, njctls)
+               IF( ibonitl(jn) ==  1 .OR. ibonitl(jn) == 2 ) nictle = MIN(nictle, nleitl(jn) - 1)
+               IF( ibonjtl(jn) ==  1 .OR. ibonjtl(jn) == 2 ) njctle = MIN(njctle, nlejtl(jn) - 1)
+            ELSE
+               nictls = MAX(  1, nimpptl(jn) - 1 + nlditl(jn) )
+               nictle = MIN(jpi, nimpptl(jn) - 1 + nleitl(jn) )
+               njctls = MAX(  1, njmpptl(jn) - 1 + nldjtl(jn) )
+               njctle = MIN(jpj, njmpptl(jn) - 1 + nlejtl(jn) )
+               ! Do not take into account the bound of the domain
+               IF( ibonitl(jn) == -1 .OR. ibonitl(jn) == 2 ) nictls = MAX(2, nictls)
+               IF( ibonjtl(jn) == -1 .OR. ibonjtl(jn) == 2 ) njctls = MAX(2, njctls)
+               IF( ibonitl(jn) ==  1 .OR. ibonitl(jn) == 2 ) nictle = MIN(nictle, nimpptl(jn) + nleitl(jn) - 2)
+               IF( ibonjtl(jn) ==  1 .OR. ibonjtl(jn) == 2 ) njctle = MIN(njctle, njmpptl(jn) + nlejtl(jn) - 2)
+            ENDIF
+         ENDIF
+
+         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
+
+         ! Compute the sum control
+         ! 2D arrays
+         IF( PRESENT(tab2d_1) )   THEN
+            zsum1 = SUM( ztab2d_1(nictls:nictle,njctls:njctle)*zmask1(nictls:nictle,njctls:njctle,1) )
+            zsum2 = SUM( ztab2d_2(nictls:nictle,njctls:njctle)*zmask2(nictls:nictle,njctls:njctle,1) )
+         ENDIF
+
+         ! 3D arrays
+         IF( PRESENT(tab3d_1) )   THEN
+            zsum1 = SUM( ztab3d_1(nictls:nictle,njctls:njctle,1:kdir)*zmask1(nictls:nictle,njctls:njctle,1:kdir) )
+            zsum2 = SUM( ztab3d_2(nictls:nictle,njctls:njctle,1:kdir)*zmask2(nictls:nictle,njctls:njctle,1:kdir) )
+         ENDIF
+
+         ! Print the result
+         IF( PRESENT(clinfo3) )   THEN
+            WRITE(j_id,FMT='(a,D23.16,3x,a,D23.16)')clinfo1, zsum1-zvctl1, cl2, zsum2-zvctl2
+            SELECT CASE( clinfo3 )
+            CASE ( 'tra-ta' ) 
+               t_ctll(jn) = zsum1
+            CASE ( 'tra' ) 
+                t_ctll(jn) = zsum1
+                s_ctll(jn) = zsum2
+            CASE ( 'dyn' ) 
+                u_ctll(jn) = zsum1
+                v_ctll(jn) = zsum2 
+            END SELECT
+         ELSEIF ( PRESENT(clinfo2) .OR. PRESENT(tab2d_2) .OR. PRESENT(tab3d_2) )   THEN
+            WRITE(j_id,FMT='(a,D23.16,3x,a,D23.16)')clinfo1, zsum1, cl2, zsum2
+         ELSE
+            WRITE(j_id,FMT='(a,D23.16)')clinfo1, zsum1
+         ENDIF
+
+      ENDDO
+      !
+   END SUBROUTINE prt_ctl
+
+
+   SUBROUTINE prt_ctl_info (clinfo1, ivar1, clinfo2, ivar2, itime)
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl_info  ***
+      !!
+      !! ** Purpose : - print information without any computation
+      !!
+      !! ** Action  : - input arguments
+      !!                    clinfo1 : information about the ivar1
+      !!                    ivar1   : value to print
+      !!                    clinfo2 : information about the ivar2
+      !!                    ivar2   : value to print
+      !!----------------------------------------------------------------------
+      CHARACTER (len=*), INTENT(in)           ::   clinfo1
+      INTEGER          , INTENT(in), OPTIONAL ::   ivar1
+      CHARACTER (len=*), INTENT(in), OPTIONAL ::   clinfo2
+      INTEGER          , INTENT(in), OPTIONAL ::   ivar2
+      INTEGER          , INTENT(in), OPTIONAL ::   itime
+      !
+      INTEGER :: jn, sind, eind, iltime, j_id
+      !!----------------------------------------------------------------------
+
+      IF( lk_mpp .AND. jpnij > 1 ) THEN       ! processor number
+         sind = narea
+         eind = narea
+      ELSE                                    ! total number of processors
+         sind = 1
+         eind = ijsplt
+      ENDIF
+
+      ! Set to zero arrays at each new time step
+      IF( PRESENT(itime) )   THEN
+         iltime = itime
+         IF( iltime > ktime )   THEN
+            t_ctll(:) = 0.e0   ;   s_ctll(:) = 0.e0
+            u_ctll(:) = 0.e0   ;   v_ctll(:) = 0.e0
+            ktime = iltime
+         ENDIF
+      ENDIF
+
+      ! Loop over each sub-domain, i.e. number of processors ijsplt
+      DO jn = sind, eind
+         !
+         j_id = numid(jn - narea + 1)         ! Set logical unit
+         !
+         IF( PRESENT(ivar1) .AND. PRESENT(clinfo2) .AND. PRESENT(ivar2) )   THEN
+            WRITE(j_id,*)clinfo1, ivar1, clinfo2, ivar2
+         ELSEIF ( PRESENT(ivar1) .AND. PRESENT(clinfo2) .AND. .NOT. PRESENT(ivar2) )   THEN
+            WRITE(j_id,*)clinfo1, ivar1, clinfo2
+         ELSEIF ( PRESENT(ivar1) .AND. .NOT. PRESENT(clinfo2) .AND. PRESENT(ivar2) )   THEN
+            WRITE(j_id,*)clinfo1, ivar1, ivar2
+         ELSEIF ( PRESENT(ivar1) .AND. .NOT. PRESENT(clinfo2) .AND. .NOT. PRESENT(ivar2) )   THEN
+            WRITE(j_id,*)clinfo1, ivar1
+         ELSE
+            WRITE(j_id,*)clinfo1
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE prt_ctl_info
+
+
+   SUBROUTINE prt_ctl_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl_init  ***
+      !!
+      !! ** Purpose :   open ASCII files & compute indices
+      !!----------------------------------------------------------------------
+      INTEGER ::   jn, sind, eind, j_id
+      CHARACTER (len=28) :: clfile_out
+      CHARACTER (len=23) :: clb_name
+      CHARACTER (len=19) :: cl_run
+      !!----------------------------------------------------------------------
+
+      ! Allocate arrays
+      ALLOCATE( nlditl(ijsplt) , nleitl(ijsplt) , nimpptl(ijsplt) , ibonitl(ijsplt) ,   &
+         &      nldjtl(ijsplt) , nlejtl(ijsplt) , njmpptl(ijsplt) , ibonjtl(ijsplt) ,   &
+         &      nlcitl(ijsplt) , t_ctll(ijsplt) , u_ctll (ijsplt) ,                     &
+         &      nlcjtl(ijsplt) , s_ctll(ijsplt) , v_ctll (ijsplt)                       )
+
+      ! Initialization 
+      t_ctll(:) = 0.e0
+      s_ctll(:) = 0.e0
+      u_ctll(:) = 0.e0
+      v_ctll(:) = 0.e0
+      ktime = 1
+
+      IF( lk_mpp .AND. jpnij > 1 ) THEN
+         sind = narea
+         eind = narea
+         clb_name = "('mpp.output_',I4.4)"
+         cl_run = 'MULTI processor run'
+         ! use indices for each area computed by mpp_init subroutine
+         nlditl(1:jpnij) = nldit(:) 
+         nleitl(1:jpnij) = nleit(:) 
+         nldjtl(1:jpnij) = nldjt(:) 
+         nlejtl(1:jpnij) = nlejt(:) 
+         !
+         nimpptl(1:jpnij) = nimppt(:)
+         njmpptl(1:jpnij) = njmppt(:)
+         !
+         nlcitl(1:jpnij) = nlcit(:)
+         nlcjtl(1:jpnij) = nlcjt(:)
+         !
+         ibonitl(1:jpnij) = ibonit(:)
+         ibonjtl(1:jpnij) = ibonjt(:)
+      ELSE
+         sind = 1
+         eind = ijsplt
+         clb_name = "('mono.output_',I4.4)"
+         cl_run = 'MONO processor run '
+         ! compute indices for each area as done in mpp_init subroutine
+         CALL sub_dom
+      ENDIF
+
+      ALLOCATE( numid(eind-sind+1) )
+
+      DO jn = sind, eind
+         WRITE(clfile_out,FMT=clb_name) jn-1
+         CALL ctl_opn( numid(jn -narea + 1), clfile_out, 'REPLACE', 'FORMATTED', 'SEQUENTIAL', 1, numout, .FALSE. )
+         j_id = numid(jn -narea + 1)
+         WRITE(j_id,*)
+         WRITE(j_id,*) '                 L O D Y C - I P S L'
+         WRITE(j_id,*) '                     O P A model'
+         WRITE(j_id,*) '            Ocean General Circulation Model'
+         WRITE(j_id,*) '               version OPA 9.0  (2005) '
+         WRITE(j_id,*)
+         WRITE(j_id,*) '                   PROC number: ', jn
+         WRITE(j_id,*)
+         WRITE(j_id,FMT="(19x,a20)")cl_run
+
+         ! Print the SUM control indices
+         IF( .NOT. lsp_area )   THEN
+            nictls = nimpptl(jn) + nlditl(jn) - 1
+            nictle = nimpptl(jn) + nleitl(jn) - 1
+            njctls = njmpptl(jn) + nldjtl(jn) - 1
+            njctle = njmpptl(jn) + nlejtl(jn) - 1
+         ENDIF
+         WRITE(j_id,*) 
+         WRITE(j_id,*) 'prt_ctl :  Sum control indices'
+         WRITE(j_id,*) '~~~~~~~'
+         WRITE(j_id,*)
+         WRITE(j_id,9000)'                                nlej   = ', nlejtl(jn), '              '
+         WRITE(j_id,9000)'                  ------------- njctle = ', njctle, ' -------------'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9002)'           nictls = ', nictls,  '                           nictle = ', nictle
+         WRITE(j_id,9002)'           nldi   = ', nlditl(jn),  '                           nlei   = ', nleitl(jn)
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9004)'  njmpp  = ',njmpptl(jn),'   ------------- njctls = ', njctls, ' -------------'
+         WRITE(j_id,9003)'           nimpp  = ', nimpptl(jn), '        nldj   = ', nldjtl(jn), '              '
+         WRITE(j_id,*)
+         WRITE(j_id,*)
+
+9000     FORMAT(a41,i4.4,a14)
+9001     FORMAT(a59)
+9002     FORMAT(a20,i4.4,a36,i4.4)
+9003     FORMAT(a20,i4.4,a17,i4.4)
+9004     FORMAT(a11,i4.4,a26,i4.4,a14)
+      END DO
+      !
+   END SUBROUTINE prt_ctl_init
+
+
+   SUBROUTINE sub_dom
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sub_dom  ***
+      !!                    
+      !! ** Purpose :   Lay out the global domain over processors. 
+      !!                CAUTION: 
+      !!                This part has been extracted from the mpp_init
+      !!                subroutine and names of variables/arrays have been 
+      !!                slightly changed to avoid confusion but the computation
+      !!                is exactly the same. Any modification about indices of
+      !!                each sub-domain in the mppini.F90 module should be reported 
+      !!                here.
+      !!
+      !! ** Method  :   Global domain is distributed in smaller local domains.
+      !!                Periodic condition is a function of the local domain position
+      !!                (global boundary or neighbouring domain) and of the global
+      !!                periodic
+      !!                Type :         jperio global periodic condition
+      !!
+      !! ** Action  : - set domain parameters
+      !!                    nimpp     : longitudinal index 
+      !!                    njmpp     : latitudinal  index
+      !!                    narea     : number for local area
+      !!                    nlcil      : first dimension
+      !!                    nlcjl      : second dimension
+      !!                    nbondil    : mark for "east-west local boundary"
+      !!                    nbondjl    : mark for "north-south local boundary"
+      !!
+      !! History :
+      !!        !  94-11  (M. Guyon)  Original code
+      !!        !  95-04  (J. Escobar, M. Imbard)
+      !!        !  98-02  (M. Guyon)  FETI method
+      !!        !  98-05  (M. Imbard, J. Escobar, L. Colombet )  SHMEM and MPI versions
+      !!   8.5  !  02-08  (G. Madec)  F90 : free form
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jn               ! dummy loop indices
+      INTEGER ::   &
+         ii, ij,                         &  ! temporary integers
+         irestil, irestjl,               &  !    "          "
+         ijpi  , ijpj, nlcil,            &  ! temporary logical unit
+         nlcjl , nbondil, nbondjl,       &
+         nrecil, nrecjl, nldil, nleil, nldjl, nlejl
+
+      INTEGER, DIMENSION(jpi,jpj) ::   iimpptl, ijmpptl, ilcitl, ilcjtl   ! workspace
+      REAL(wp) ::   zidom, zjdom            ! temporary scalars
+      INTEGER ::   inum                     ! local logical unit
+      !!----------------------------------------------------------------------
+
+      !
+      !
+      !  1. Dimension arrays for subdomains
+      ! -----------------------------------
+      !  Computation of local domain sizes ilcitl() ilcjtl()
+      !  These dimensions depend on global sizes isplt,jsplt and jpiglo,jpjglo
+      !  The subdomains are squares leeser than or equal to the global
+      !  dimensions divided by the number of processors minus the overlap
+      !  array (cf. par_oce.F90).
+
+#if defined key_nemocice_decomp
+      ijpi = ( nx_global+2-2*nn_hls + (isplt-1) ) / isplt + 2*nn_hls
+      ijpj = ( ny_global+2-2*nn_hls + (jsplt-1) ) / jsplt + 2*nn_hls 
+#else
+      ijpi = ( jpiglo-2*nn_hls + (isplt-1) ) / isplt + 2*nn_hls
+      ijpj = ( jpjglo-2*nn_hls + (jsplt-1) ) / jsplt + 2*nn_hls
+#endif
+
+
+      nrecil  = 2 * nn_hls
+      nrecjl  = 2 * nn_hls
+      irestil = MOD( jpiglo - nrecil , isplt )
+      irestjl = MOD( jpjglo - nrecjl , jsplt )
+
+      IF(  irestil == 0 )   irestil = isplt
+#if defined key_nemocice_decomp
+
+      ! In order to match CICE the size of domains in NEMO has to be changed
+      ! The last line of blocks (west) will have fewer points 
+      DO jj = 1, jsplt 
+         DO ji=1, isplt-1 
+            ilcitl(ji,jj) = ijpi 
+         END DO 
+         ilcitl(isplt,jj) = jpiglo - (isplt - 1) * (ijpi - nrecil)
+      END DO 
+
+#else 
+
+      DO jj = 1, jsplt
+         DO ji = 1, irestil
+            ilcitl(ji,jj) = ijpi
+         END DO
+         DO ji = irestil+1, isplt
+            ilcitl(ji,jj) = ijpi -1
+         END DO
+      END DO
+
+#endif
+      
+      IF( irestjl == 0 )   irestjl = jsplt
+#if defined key_nemocice_decomp 
+
+      ! Same change to domains in North-South direction as in East-West. 
+      DO ji = 1, isplt 
+         DO jj=1, jsplt-1 
+            ilcjtl(ji,jj) = ijpj 
+         END DO 
+         ilcjtl(ji,jsplt) = jpjglo - (jsplt - 1) * (ijpj - nrecjl)
+      END DO 
+
+#else 
+
+      DO ji = 1, isplt
+         DO jj = 1, irestjl
+            ilcjtl(ji,jj) = ijpj
+         END DO
+         DO jj = irestjl+1, jsplt
+            ilcjtl(ji,jj) = ijpj -1
+         END DO
+      END DO
+
+#endif
+      zidom = nrecil
+      DO ji = 1, isplt
+         zidom = zidom + ilcitl(ji,1) - nrecil
+      END DO
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*)' sum ilcitl(i,1) = ', zidom, ' jpiglo = ', jpiglo
+      
+      zjdom = nrecjl
+      DO jj = 1, jsplt
+         zjdom = zjdom + ilcjtl(1,jj) - nrecjl
+      END DO
+      IF(lwp) WRITE(numout,*)' sum ilcitl(1,j) = ', zjdom, ' jpjglo = ', jpjglo
+      IF(lwp) WRITE(numout,*)
+      
+
+      !  2. Index arrays for subdomains
+      ! -------------------------------
+
+      iimpptl(:,:) = 1
+      ijmpptl(:,:) = 1
+      
+      IF( isplt > 1 ) THEN
+         DO jj = 1, jsplt
+            DO ji = 2, isplt
+               iimpptl(ji,jj) = iimpptl(ji-1,jj) + ilcitl(ji-1,jj) - nrecil
+            END DO
+         END DO
+      ENDIF
+
+      IF( jsplt > 1 ) THEN
+         DO jj = 2, jsplt
+            DO ji = 1, isplt
+               ijmpptl(ji,jj) = ijmpptl(ji,jj-1)+ilcjtl(ji,jj-1)-nrecjl
+            END DO
+         END DO
+      ENDIF
+      
+      ! 3. Subdomain description
+      ! ------------------------
+
+      DO jn = 1, ijsplt
+         ii = 1 + MOD( jn-1, isplt )
+         ij = 1 + (jn-1) / isplt
+         nimpptl(jn) = iimpptl(ii,ij)
+         njmpptl(jn) = ijmpptl(ii,ij)
+         nlcitl (jn) = ilcitl (ii,ij)     
+         nlcil       = nlcitl (jn)     
+         nlcjtl (jn) = ilcjtl (ii,ij)     
+         nlcjl       = nlcjtl (jn)
+         nbondjl = -1                                    ! general case
+         IF( jn   >  isplt          )   nbondjl = 0      ! first row of processor
+         IF( jn   >  (jsplt-1)*isplt )  nbondjl = 1     ! last  row of processor
+         IF( jsplt == 1             )   nbondjl = 2      ! one processor only in j-direction
+         ibonjtl(jn) = nbondjl
+         
+         nbondil = 0                                     ! 
+         IF( MOD( jn, isplt ) == 1 )   nbondil = -1      !
+         IF( MOD( jn, isplt ) == 0 )   nbondil =  1      !
+         IF( isplt            == 1 )   nbondil =  2      ! one processor only in i-direction
+         ibonitl(jn) = nbondil
+         
+         nldil =  1   + nn_hls
+         nleil = nlcil - nn_hls
+         IF( nbondil == -1 .OR. nbondil == 2 )   nldil = 1
+         IF( nbondil ==  1 .OR. nbondil == 2 )   nleil = nlcil
+         nldjl =  1   + nn_hls
+         nlejl = nlcjl - nn_hls
+         IF( nbondjl == -1 .OR. nbondjl == 2 )   nldjl = 1
+         IF( nbondjl ==  1 .OR. nbondjl == 2 )   nlejl = nlcjl
+         nlditl(jn) = nldil
+         nleitl(jn) = nleil
+         nldjtl(jn) = nldjl
+         nlejtl(jn) = nlejl
+      END DO
+      !
+      ! Save processor layout in layout_prtctl.dat file 
+      IF(lwp) THEN
+         CALL ctl_opn( inum, 'layout_prtctl.dat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., narea )
+         WRITE(inum,'(a)') 'nproc nlcil nlcjl nldil nldjl nleil nlejl nimpptl njmpptl ibonitl ibonjtl'
+         !
+         DO jn = 1, ijsplt
+            WRITE(inum,'(i5,6i6,4i8)') jn-1,nlcitl(jn),  nlcjtl(jn), &
+               &                            nlditl(jn),  nldjtl(jn), &
+               &                            nleitl(jn),  nlejtl(jn), &
+               &                           nimpptl(jn), njmpptl(jn), &
+               &                           ibonitl(jn), ibonjtl(jn)
+         END DO
+         CLOSE(inum)   
+      END IF
+      !
+      !
+   END SUBROUTINE sub_dom
+
+   !!======================================================================
+END MODULE prtctl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/restart.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/restart.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/IOM/restart.F90	(revision 14097)
@@ -0,0 +1,314 @@
+MODULE restart
+   !!======================================================================
+   !!                     ***  MODULE  restart  ***
+   !! Ocean restart :  write the ocean restart file
+   !!======================================================================
+   !! History :  OPA  !  1999-11  (M. Imbard)  Original code
+   !!   NEMO     1.0  !  2002-08  (G. Madec)  F90: Free form
+   !!            2.0  !  2006-07  (S. Masson)  use IOM for restart
+   !!            3.3  !  2010-04  (M. Leclair, G. Madec)  modified LF-RA
+   !!            - -  !  2010-10  (C. Ethe, G. Madec) TRC-TRA merge (T-S in 4D)
+   !!            3.7  !  2014-01  (G. Madec) suppression of curl and hdiv from the restart
+   !!             -   !  2014-12  (G. Madec) remove KPP scheme
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   rst_opn    : open the ocean restart file
+   !!   rst_write  : write the ocean restart file
+   !!   rst_read   : read the ocean restart file
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_ice         ! only lk_si3 
+   USE phycst          ! physical constants
+   USE eosbn2          ! equation of state            (eos bn2 routine)
+   USE trdmxl_oce      ! ocean active mixed layer tracers trends variables
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module
+   USE diurnal_bulk
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   rst_opn         ! routine called by step module
+   PUBLIC   rst_write       ! routine called by step module
+   PUBLIC   rst_read        ! routine called by istate module
+   PUBLIC   rst_read_open   ! routine called in rst_read and (possibly) in dom_vvl_init
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE rst_opn( kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rst_opn  ***
+      !!                     
+      !! ** Purpose : + initialization (should be read in the namelist) of nitrst 
+      !!              + open the restart when we are one time step before nitrst
+      !!                   - restart header is defined when kt = nitrst-1
+      !!                   - restart data  are written when kt = nitrst
+      !!              + define lrst_oce to .TRUE. when we need to define or write the restart
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ocean time-step
+      !!
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
+      CHARACTER(LEN=50)   ::   clname   ! ocean output restart file name
+      CHARACTER(lc)       ::   clpath   ! full path to ocean output restart file
+      CHARACTER(LEN=52)   ::   clpname   ! ocean output restart file name including prefix for AGRIF
+      CHARACTER(LEN=256)  ::   clinfo    ! info character
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN   ! default definitions
+         lrst_oce = .FALSE.   
+         IF( ln_rst_list ) THEN
+            nrst_lst = 1
+            nitrst = nn_stocklist( nrst_lst )
+         ELSE
+            nitrst = nitend
+         ENDIF
+      ENDIF
+      
+      IF( .NOT. ln_rst_list .AND. nn_stock == -1 )   RETURN   ! we will never do any restart
+
+      ! frequency-based restart dumping (nn_stock)
+      IF( .NOT. ln_rst_list .AND. MOD( kt - 1, nn_stock ) == 0 ) THEN   
+         ! we use kt - 1 and not kt - nit000 to keep the same periodicity from the beginning of the experiment
+         nitrst = kt + nn_stock - 1                  ! define the next value of nitrst for restart writing
+         IF( nitrst > nitend )   nitrst = nitend   ! make sure we write a restart at the end of the run
+      ENDIF
+      ! to get better performances with NetCDF format:
+      ! we open and define the ocean restart file one time step before writing the data (-> at nitrst - 1)
+      ! except if we write ocean restart files every time step or if an ocean restart file was writen at nitend - 1
+      IF( kt == nitrst - 1 .OR. nn_stock == 1 .OR. ( kt == nitend .AND. .NOT. lrst_oce ) ) THEN
+         IF( nitrst <= nitend .AND. nitrst > 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_ocerst_out)
+            clpath = TRIM(cn_ocerst_outdir)
+            IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+            IF(lwp) THEN
+               WRITE(numout,*)
+               IF(.NOT.lwxios) THEN
+                  WRITE(numout,*) '             open ocean restart NetCDF file: ',TRIM(clpath)//TRIM(clname)
+                  IF ( snc4set%luse )      WRITE(numout,*) '             opened for NetCDF4 chunking and compression'
+                  IF( kt == nitrst - 1 ) THEN   ;   WRITE(numout,*) '             kt = nitrst - 1 = ', kt
+                  ELSE                          ;   WRITE(numout,*) '             kt = '             , kt
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+            IF(.NOT.lwxios) THEN
+               CALL iom_open( TRIM(clpath)//TRIM(clname), numrow, ldwrt = .TRUE. )
+            ELSE
+#if defined key_iomput
+               cwxios_context = "rstw_"//TRIM(ADJUSTL(clkt))
+               IF( TRIM(Agrif_CFixed()) == '0' ) THEN
+                  clpname = clname
+               ELSE
+                  clpname = TRIM(Agrif_CFixed())//"_"//clname   
+               ENDIF
+               CALL iom_init( cwxios_context, TRIM(clpath)//TRIM(clpname), .false. )
+               CALL xios_update_calendar(nitrst)
+               CALL iom_swap(      cxios_context          )
+#else
+               clinfo = 'Can not use XIOS in rst_opn'
+               CALL ctl_stop(TRIM(clinfo))
+#endif
+            ENDIF
+            lrst_oce = .TRUE.
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE rst_opn
+
+
+   SUBROUTINE rst_write( kt )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE rstwrite  ***
+      !!                     
+      !! ** Purpose :   Write restart fields in NetCDF format
+      !!
+      !! ** Method  :   Write in numrow when kt == nitrst in NetCDF
+      !!              file, save fields which are necessary for restart
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step
+      !!----------------------------------------------------------------------
+                     IF(lwxios) CALL iom_swap(      cwxios_context          )
+                     CALL iom_rstput( kt, nitrst, numrow, 'rdt'    , rdt       , ldxios = lwxios)   ! dynamics time step
+                     CALL iom_delay_rst( 'WRITE', 'OCE', numrow )   ! save only ocean delayed global communication variables
+
+      IF ( .NOT. ln_diurnal_only ) THEN
+                     CALL iom_rstput( kt, nitrst, numrow, 'ub'     , ub, ldxios = lwxios        )     ! before fields
+                     CALL iom_rstput( kt, nitrst, numrow, 'vb'     , vb, ldxios = lwxios        )
+                     CALL iom_rstput( kt, nitrst, numrow, 'tb'     , tsb(:,:,:,jp_tem), ldxios = lwxios )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sb'     , tsb(:,:,:,jp_sal), ldxios = lwxios )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sshb'   , sshb, ldxios = lwxios      )
+                     !
+                     CALL iom_rstput( kt, nitrst, numrow, 'un'     , un, ldxios = lwxios        )     ! now fields
+                     CALL iom_rstput( kt, nitrst, numrow, 'vn'     , vn, ldxios = lwxios        )
+                     CALL iom_rstput( kt, nitrst, numrow, 'tn'     , tsn(:,:,:,jp_tem), ldxios = lwxios )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sn'     , tsn(:,:,:,jp_sal), ldxios = lwxios )
+                     CALL iom_rstput( kt, nitrst, numrow, 'sshn'   , sshn, ldxios = lwxios      )
+                     CALL iom_rstput( kt, nitrst, numrow, 'rhop'   , rhop, ldxios = lwxios      )
+                  ! extra variable needed for the ice sheet coupling
+                  IF ( ln_iscpl ) THEN 
+                     CALL iom_rstput( kt, nitrst, numrow, 'tmask'  , tmask, ldxios = lwxios ) ! need to extrapolate T/S
+                     CALL iom_rstput( kt, nitrst, numrow, 'umask'  , umask, ldxios = lwxios ) ! need to correct barotropic velocity
+                     CALL iom_rstput( kt, nitrst, numrow, 'vmask'  , vmask, ldxios = lwxios ) ! need to correct barotropic velocity
+                     CALL iom_rstput( kt, nitrst, numrow, 'smask'  , ssmask, ldxios = lwxios) ! need to correct barotropic velocity
+                     CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t_n(:,:,:), ldxios = lwxios )   ! need to compute temperature correction
+                     CALL iom_rstput( kt, nitrst, numrow, 'e3u_n', e3u_n(:,:,:), ldxios = lwxios )   ! need to compute bt conservation
+                     CALL iom_rstput( kt, nitrst, numrow, 'e3v_n', e3v_n(:,:,:), ldxios = lwxios )   ! need to compute bt conservation
+                     CALL iom_rstput( kt, nitrst, numrow, 'gdepw_n', gdepw_n(:,:,:), ldxios = lwxios ) ! need to compute extrapolation if vvl
+                  END IF
+      ENDIF
+      
+      IF (ln_diurnal) CALL iom_rstput( kt, nitrst, numrow, 'Dsst', x_dsst, ldxios = lwxios )  
+      IF(lwxios) CALL iom_swap(      cxios_context          )
+      IF( kt == nitrst ) THEN
+         IF(.NOT.lwxios) THEN
+            CALL iom_close( numrow )     ! close the restart file (only at last time step)
+         ELSE
+            CALL iom_context_finalize(      cwxios_context          )
+         ENDIF
+!!gm         IF( .NOT. lk_trdmld )   lrst_oce = .FALSE.
+!!gm  not sure what to do here   ===>>>  ask to Sebastian
+         lrst_oce = .FALSE.
+            IF( ln_rst_list ) THEN
+               nrst_lst = MIN(nrst_lst + 1, SIZE(nn_stocklist,1))
+               nitrst = nn_stocklist( nrst_lst )
+            ENDIF
+      ENDIF
+      !
+   END SUBROUTINE rst_write
+
+
+   SUBROUTINE rst_read_open
+      !!---------------------------------------------------------------------- 
+      !!                   ***  ROUTINE rst_read_open  ***
+      !! 
+      !! ** Purpose :   Open read files for NetCDF restart
+      !! 
+      !! ** Method  :   Use a non-zero, positive value of numror to assess whether or not
+      !!                the file has already been opened
+      !!----------------------------------------------------------------------
+      LOGICAL        ::   llok
+      CHARACTER(lc)  ::   clpath   ! full path to ocean output restart file
+      !!----------------------------------------------------------------------
+      !
+      IF( numror <= 0 ) THEN
+         IF(lwp) THEN                                             ! Contol prints
+            WRITE(numout,*)
+            WRITE(numout,*) 'rst_read : read oce NetCDF restart file'
+            IF ( snc4set%luse )      WRITE(numout,*) 'rst_read : configured with NetCDF4 support'
+            WRITE(numout,*) '~~~~~~~~'
+         ENDIF
+         lxios_sini = .FALSE.
+         clpath = TRIM(cn_ocerst_indir)
+         IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+         CALL iom_open( TRIM(clpath)//cn_ocerst_in, numror )
+! are we using XIOS to read the data? Part above will have to modified once XIOS
+! can handle checking if variable is in the restart file (there will be no need to open
+! restart)
+         IF(.NOT.lxios_set) lrxios = lrxios.AND.lxios_sini
+         IF( lrxios) THEN
+             crxios_context = 'nemo_rst'
+             IF( .NOT.lxios_set ) THEN
+                 IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS'
+                 CALL iom_init( crxios_context, ld_tmppatch = .false. )
+                 lxios_set = .TRUE.
+             ENDIF
+         ENDIF
+         IF( TRIM(Agrif_CFixed()) /= '0' .AND. lrxios) THEN
+             CALL iom_init( crxios_context, ld_tmppatch = .false. )
+             IF(lwp) WRITE(numout,*) 'Enable restart reading by XIOS for AGRIF'
+             lxios_set = .TRUE.
+         ENDIF 
+      ENDIF
+
+   END SUBROUTINE rst_read_open
+
+
+   SUBROUTINE rst_read
+      !!---------------------------------------------------------------------- 
+      !!                   ***  ROUTINE rst_read  ***
+      !! 
+      !! ** Purpose :   Read files for NetCDF restart
+      !! 
+      !! ** Method  :   Read in restart.nc file fields which are necessary for restart
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zrdt
+      INTEGER  ::   jk
+      REAL(wp), DIMENSION(jpi, jpj, jpk) :: w3d
+      !!----------------------------------------------------------------------
+
+      CALL rst_read_open           ! open restart for reading (if not already opened)
+
+      ! Check dynamics and tracer time-step consistency and force Euler restart if changed
+      IF( iom_varid( numror, 'rdt', ldstop = .FALSE. ) > 0 )   THEN
+         CALL iom_get( numror, 'rdt', zrdt, ldxios = lrxios )
+         IF( zrdt /= rdt )   neuler = 0
+      ENDIF
+
+      CALL iom_delay_rst( 'READ', 'OCE', numror )   ! read only ocean delayed global communication variables
+      
+      ! Diurnal DSST 
+      IF( ln_diurnal ) CALL iom_get( numror, jpdom_autoglo, 'Dsst' , x_dsst, ldxios = lrxios ) 
+      IF ( ln_diurnal_only ) THEN 
+         IF(lwp) WRITE( numout, * ) &
+         &   "rst_read:- ln_diurnal_only set, setting rhop=rau0" 
+         rhop = rau0
+         CALL iom_get( numror, jpdom_autoglo, 'tn'     , w3d, ldxios = lrxios ) 
+         tsn(:,:,1,jp_tem) = w3d(:,:,1)
+         RETURN 
+      ENDIF  
+      
+      IF( iom_varid( numror, 'ub', ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numror, jpdom_autoglo, 'ub'     , ub, ldxios = lrxios                )   ! before fields
+         CALL iom_get( numror, jpdom_autoglo, 'vb'     , vb, ldxios = lrxios                )
+         CALL iom_get( numror, jpdom_autoglo, 'tb'     , tsb(:,:,:,jp_tem), ldxios = lrxios )
+         CALL iom_get( numror, jpdom_autoglo, 'sb'     , tsb(:,:,:,jp_sal), ldxios = lrxios )
+         CALL iom_get( numror, jpdom_autoglo, 'sshb'   , sshb, ldxios = lrxios              )
+      ELSE
+         neuler = 0
+      ENDIF
+      !
+      CALL iom_get( numror, jpdom_autoglo, 'un'     , un, ldxios = lrxios )   ! now    fields
+      CALL iom_get( numror, jpdom_autoglo, 'vn'     , vn, ldxios = lrxios )
+      CALL iom_get( numror, jpdom_autoglo, 'tn'     , tsn(:,:,:,jp_tem), ldxios = lrxios )
+      CALL iom_get( numror, jpdom_autoglo, 'sn'     , tsn(:,:,:,jp_sal), ldxios = lrxios )
+      CALL iom_get( numror, jpdom_autoglo, 'sshn'   , sshn, ldxios = lrxios )
+      IF( iom_varid( numror, 'rhop', ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numror, jpdom_autoglo, 'rhop'   , rhop, ldxios = lrxios )   ! now    potential density
+      ELSE
+         CALL eos( tsn, rhd, rhop, gdept_n(:,:,:) )   
+      ENDIF
+      !
+      IF( neuler == 0 ) THEN                                  ! Euler restart (neuler=0)
+         tsb  (:,:,:,:) = tsn  (:,:,:,:)                             ! all before fields set to now values
+         ub   (:,:,:)   = un   (:,:,:)
+         vb   (:,:,:)   = vn   (:,:,:)
+         sshb (:,:)     = sshn (:,:)
+         !
+         IF( .NOT.ln_linssh ) THEN
+            DO jk = 1, jpk
+               e3t_b(:,:,jk) = e3t_n(:,:,jk)
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE rst_read
+
+   !!=====================================================================
+END MODULE restart
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_lnk_multi_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_lnk_multi_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_lnk_multi_generic.h90	(revision 14097)
@@ -0,0 +1,92 @@
+#if defined DIM_2d
+#   define ARRAY_TYPE(i,j,k,l)   REAL(wp), DIMENSION(i,j)
+#   define PTR_TYPE              TYPE(PTR_2D)
+#   define PTR_ptab              pt2d
+#endif
+#if defined DIM_3d
+#   define ARRAY_TYPE(i,j,k,l)   REAL(wp), DIMENSION(i,j,k)
+#   define PTR_TYPE              TYPE(PTR_3D)
+#   define PTR_ptab              pt3d
+#endif
+#if defined DIM_4d
+#   define ARRAY_TYPE(i,j,k,l)   REAL(wp), DIMENSION(i,j,k,l)
+#   define PTR_TYPE              TYPE(PTR_4D)
+#   define PTR_ptab              pt4d
+#endif
+
+   SUBROUTINE ROUTINE_MULTI( cdname                                                                               &
+      &                    , pt1 , cdna1 , psgn1 , pt2 , cdna2 , psgn2 , pt3 , cdna3 , psgn3 , pt4 , cdna4 , psgn4   &
+      &                    , pt5 , cdna5 , psgn5 , pt6 , cdna6 , psgn6 , pt7 , cdna7 , psgn7 , pt8 , cdna8 , psgn8   &
+      &                    , pt9 , cdna9 , psgn9 , pt10, cdna10, psgn10, pt11, cdna11, psgn11, pt12, cdna12, psgn12  &
+      &                    , pt13, cdna13, psgn13, pt14, cdna14, psgn14, pt15, cdna15, psgn15, pt16, cdna16, psgn16  &
+      &                    , kfillmode, pfillval, lsend, lrecv, ihlcom )
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*)     ,                   INTENT(in   ) ::   cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:,:,:,:)            , TARGET, INTENT(inout) ::   pt1     ! arrays on which the lbc is applied
+      ARRAY_TYPE(:,:,:,:)  , OPTIONAL, TARGET, INTENT(inout) ::   pt2   , pt3   , pt4   , pt5   , pt6   , pt7   , pt8   , pt9  , &
+         &                                                        pt10  , pt11  , pt12  , pt13  , pt14  , pt15  , pt16
+      CHARACTER(len=1)                       , INTENT(in   ) ::   cdna1   ! nature of pt2D. array grid-points
+      CHARACTER(len=1)     , OPTIONAL        , INTENT(in   ) ::   cdna2 , cdna3 , cdna4 , cdna5 , cdna6 , cdna7 , cdna8 , cdna9, &
+         &                                                        cdna10, cdna11, cdna12, cdna13, cdna14, cdna15, cdna16
+      REAL(wp)                               , INTENT(in   ) ::   psgn1   ! sign used across the north fold
+      REAL(wp)             , OPTIONAL        , INTENT(in   ) ::   psgn2 , psgn3 , psgn4 , psgn5 , psgn6 , psgn7 , psgn8 , psgn9, &
+         &                                                        psgn10, psgn11, psgn12, psgn13, psgn14, psgn15, psgn16
+      INTEGER              , OPTIONAL        , INTENT(in   ) ::   kfillmode   ! filling method for halo over land (default = constant)
+      REAL(wp)             , OPTIONAL        , INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
+      LOGICAL, DIMENSION(4), OPTIONAL        , INTENT(in   ) ::   lsend, lrecv   ! indicate how communications are to be carried out
+      INTEGER              , OPTIONAL        , INTENT(in   ) ::   ihlcom         ! number of ranks and rows to be communicated
+      !!
+      INTEGER                          ::   kfld        ! number of elements that will be attributed
+      PTR_TYPE         , DIMENSION(16) ::   ptab_ptr    ! pointer array
+      CHARACTER(len=1) , DIMENSION(16) ::   cdna_ptr    ! nature of ptab_ptr grid-points
+      REAL(wp)         , DIMENSION(16) ::   psgn_ptr    ! sign used across the north fold boundary
+      !!---------------------------------------------------------------------
+      !
+      kfld = 0          ! initial array of pointer size
+      !
+      !                 ! Load the first array
+      CALL ROUTINE_LOAD( pt1, cdna1, psgn1, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !
+      !                 ! Look if more arrays are added
+      IF( PRESENT(psgn2 ) )   CALL ROUTINE_LOAD( pt2 , cdna2 , psgn2 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn3 ) )   CALL ROUTINE_LOAD( pt3 , cdna3 , psgn3 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn4 ) )   CALL ROUTINE_LOAD( pt4 , cdna4 , psgn4 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn5 ) )   CALL ROUTINE_LOAD( pt5 , cdna5 , psgn5 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn6 ) )   CALL ROUTINE_LOAD( pt6 , cdna6 , psgn6 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn7 ) )   CALL ROUTINE_LOAD( pt7 , cdna7 , psgn7 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn8 ) )   CALL ROUTINE_LOAD( pt8 , cdna8 , psgn8 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn9 ) )   CALL ROUTINE_LOAD( pt9 , cdna9 , psgn9 , ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn10) )   CALL ROUTINE_LOAD( pt10, cdna10, psgn10, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn11) )   CALL ROUTINE_LOAD( pt11, cdna11, psgn11, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn12) )   CALL ROUTINE_LOAD( pt12, cdna12, psgn12, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn13) )   CALL ROUTINE_LOAD( pt13, cdna13, psgn13, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn14) )   CALL ROUTINE_LOAD( pt14, cdna14, psgn14, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn15) )   CALL ROUTINE_LOAD( pt15, cdna15, psgn15, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      IF( PRESENT(psgn16) )   CALL ROUTINE_LOAD( pt16, cdna16, psgn16, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !
+      CALL lbc_lnk_ptr( cdname, ptab_ptr, cdna_ptr, psgn_ptr, kfld, kfillmode, pfillval, lsend, lrecv, ihlcom )
+      !
+   END SUBROUTINE ROUTINE_MULTI
+
+
+   SUBROUTINE ROUTINE_LOAD( ptab, cdna, psgn, ptab_ptr, cdna_ptr, psgn_ptr, kfld )
+      !!---------------------------------------------------------------------
+      ARRAY_TYPE(:,:,:,:)   , TARGET, INTENT(inout) ::   ptab       ! arrays on which the lbc is applied
+      CHARACTER(len=1)              , INTENT(in   ) ::   cdna       ! nature of pt2d array grid-points
+      REAL(wp)                      , INTENT(in   ) ::   psgn       ! sign used across the north fold boundary
+      PTR_TYPE        , DIMENSION(:), INTENT(inout) ::   ptab_ptr   ! array of pointers
+      CHARACTER(len=1), DIMENSION(:), INTENT(inout) ::   cdna_ptr   ! nature of pt2d_array array grid-points
+      REAL(wp)        , DIMENSION(:), INTENT(inout) ::   psgn_ptr   ! sign used across the north fold boundary
+      INTEGER                       , INTENT(inout) ::   kfld       ! number of elements that has been attributed
+      !!---------------------------------------------------------------------
+      !
+      kfld                    =  kfld + 1
+      ptab_ptr(kfld)%PTR_ptab => ptab
+      cdna_ptr(kfld)          =  cdna
+      psgn_ptr(kfld)          =  psgn
+      !
+   END SUBROUTINE ROUTINE_LOAD
+
+#undef ARRAY_TYPE
+#undef PTR_TYPE
+#undef PTR_ptab
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_ext_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_ext_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_ext_generic.h90	(revision 14097)
@@ -0,0 +1,157 @@
+!                          !==  IN: ptab is an array  ==!
+#define NAT_IN(k)                cd_nat
+#define SGN_IN(k)                psgn
+#define F_SIZE(ptab)             1
+#if defined DIM_2d
+#   define ARRAY_IN(i,j,k,l,f)   ptab(i,j)
+#   define K_SIZE(ptab)          1
+#   define L_SIZE(ptab)          1
+#endif
+#define ARRAY_TYPE(i,j,k,l,f)    REAL(wp),INTENT(inout)::ARRAY_IN(i,j,k,l,f)
+
+   SUBROUTINE ROUTINE_NFD( ptab, cd_nat, psgn, kextj )
+      !!----------------------------------------------------------------------
+      INTEGER          , INTENT(in   ) ::   kextj       ! extra halo width at north fold, declared before its use in ARRAY_TYPE
+      ARRAY_TYPE(:,1-kextj:,:,:,:)                      ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=1) , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)         , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      !
+      INTEGER  ::    ji,  jj,  jk,  jl, jh,  jf   ! dummy loop indices
+      INTEGER  ::   ipi, ipj, ipk, ipl,     ipf   ! dimension of the input array
+      INTEGER  ::   ijt, iju, ipjm1
+      !!----------------------------------------------------------------------
+      !
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      !
+      SELECT CASE ( jpni )
+      CASE ( 1 )     ;   ipj = nlcj       ! 1 proc only  along the i-direction
+      CASE DEFAULT   ;   ipj = 4          ! several proc along the i-direction
+      END SELECT
+      !
+      ipjm1 = ipj-1
+
+      !
+      DO jf = 1, ipf                      ! Loop on the number of arrays to be treated
+         !
+         SELECT CASE ( npolj )
+         !
+         CASE ( 3 , 4 )                        ! *  North fold  T-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf)  )
+            CASE ( 'T' , 'W' )                         ! T-, W-point
+               DO jh = 0, kextj
+                  DO ji = 2, jpiglo
+                     ijt = jpiglo-ji+2
+                     ARRAY_IN(ji,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2-jh,:,:,jf)
+                  END DO
+                  ARRAY_IN(1,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(3,ipj-2-jh,:,:,jf)
+               END DO
+               DO ji = jpiglo/2+1, jpiglo
+                  ijt = jpiglo-ji+2
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'U' )                               ! U-point
+               DO jh = 0, kextj
+                  DO ji = 2, jpiglo-1
+                     iju = jpiglo-ji+1
+                     ARRAY_IN(ji,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2-jh,:,:,jf)
+                  END DO
+                 ARRAY_IN(   1  ,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(    2   ,ipj-2-jh,:,:,jf)
+                 ARRAY_IN(jpiglo,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-1,ipj-2-jh,:,:,jf) 
+               END DO
+               DO ji = jpiglo/2, jpiglo-1
+                  iju = jpiglo-ji+1
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'V' )                               ! V-point
+               DO jh = 0, kextj
+                  DO ji = 2, jpiglo
+                     ijt = jpiglo-ji+2
+                     ARRAY_IN(ji,ipj-1+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2-jh,:,:,jf)
+                     ARRAY_IN(ji,ipj+jh  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-3-jh,:,:,jf)
+                  END DO
+                  ARRAY_IN(1,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(3,ipj-3-jh,:,:,jf) 
+               END DO
+            CASE ( 'F' )                               ! F-point
+               DO jh = 0, kextj
+                  DO ji = 1, jpiglo-1
+                     iju = jpiglo-ji+1
+                     ARRAY_IN(ji,ipj-1+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2-jh,:,:,jf)
+                     ARRAY_IN(ji,ipj+jh  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-3-jh,:,:,jf)
+                  END DO
+               END DO
+               DO jh = 0, kextj
+                  ARRAY_IN(   1  ,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(    2   ,ipj-3-jh,:,:,jf)
+                  ARRAY_IN(jpiglo,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-1,ipj-3-jh,:,:,jf)
+               END DO
+            END SELECT
+            !
+         CASE ( 5 , 6 )                        ! *  North fold  F-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf)  )
+            CASE ( 'T' , 'W' )                         ! T-, W-point
+               DO jh = 0, kextj
+                  DO ji = 1, jpiglo
+                     ijt = jpiglo-ji+1
+                     ARRAY_IN(ji,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-1-jh,:,:,jf)
+                  END DO
+               END DO
+            CASE ( 'U' )                               ! U-point
+               DO jh = 0, kextj
+                  DO ji = 1, jpiglo-1
+                     iju = jpiglo-ji
+                     ARRAY_IN(ji,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-1-jh,:,:,jf)
+                  END DO
+                  ARRAY_IN(jpiglo,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-2,ipj-1-jh,:,:,jf)
+               END DO
+            CASE ( 'V' )                               ! V-point
+               DO jh = 0, kextj
+                  DO ji = 1, jpiglo
+                     ijt = jpiglo-ji+1
+                     ARRAY_IN(ji,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2-jh,:,:,jf)
+                  END DO
+               END DO
+               DO ji = jpiglo/2+1, jpiglo
+                  ijt = jpiglo-ji+1
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'F' )                               ! F-point
+               DO jh = 0, kextj
+                  DO ji = 1, jpiglo-1
+                     iju = jpiglo-ji
+                     ARRAY_IN(ji,ipj+jh  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2-jh,:,:,jf)
+                  END DO
+                  ARRAY_IN(jpiglo,ipj+jh,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-2,ipj-2-jh,:,:,jf)
+               END DO
+               DO ji = jpiglo/2+1, jpiglo-1
+                  iju = jpiglo-ji
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipjm1,:,:,jf)
+               END DO
+            END SELECT
+            !
+         CASE DEFAULT                           ! *  closed : the code probably never go through
+            !
+            SELECT CASE ( NAT_IN(jf) )
+            CASE ( 'T' , 'U' , 'V' , 'W' )             ! T-, U-, V-, W-points
+               ARRAY_IN(:,  1:1-kextj  ,:,:,jf) = 0._wp
+               ARRAY_IN(:,ipj:ipj+kextj,:,:,jf) = 0._wp
+            CASE ( 'F' )                               ! F-point
+               ARRAY_IN(:,ipj:ipj+kextj,:,:,jf) = 0._wp
+            END SELECT
+            !
+         END SELECT     !  npolj
+         !
+      END DO
+      !
+   END SUBROUTINE ROUTINE_NFD
+
+#undef ARRAY_TYPE
+#undef ARRAY_IN
+#undef NAT_IN
+#undef SGN_IN
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_generic.h90	(revision 14097)
@@ -0,0 +1,175 @@
+#if defined MULTI
+#   define NAT_IN(k)                cd_nat(k)   
+#   define SGN_IN(k)                psgn(k)
+#   define F_SIZE(ptab)             kfld
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt2d(i,j)
+#      define K_SIZE(ptab)             1
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt3d(i,j,k)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt3d,3)
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt4d(i,j,k,l)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt4d,3)
+#      define L_SIZE(ptab)             SIZE(ptab(1)%pt4d,4)
+#   endif
+#else
+!                          !==  IN: ptab is an array  ==!
+#   define NAT_IN(k)                cd_nat
+#   define SGN_IN(k)                psgn
+#   define F_SIZE(ptab)             1
+#   if defined DIM_2d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j)
+#      define K_SIZE(ptab)          1
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k,l)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          SIZE(ptab,4)
+#   endif
+#   define ARRAY_TYPE(i,j,k,l,f)    REAL(wp),INTENT(inout)::ARRAY_IN(i,j,k,l,f)
+#endif
+
+#if defined MULTI
+   SUBROUTINE ROUTINE_NFD( ptab, cd_nat, psgn, kfld )
+      INTEGER          , INTENT(in   ) ::   kfld        ! number of pt3d arrays
+#else
+   SUBROUTINE ROUTINE_NFD( ptab, cd_nat, psgn       )
+#endif
+      ARRAY_TYPE(:,:,:,:,:)                             ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=1) , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)         , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      !
+      INTEGER  ::    ji,  jj,  jk,  jl, jh,  jf   ! dummy loop indices
+      INTEGER  ::   ipi, ipj, ipk, ipl,     ipf   ! dimension of the input array
+      INTEGER  ::   ijt, iju, ipjm1
+      !!----------------------------------------------------------------------
+      !
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      !
+      SELECT CASE ( jpni )
+      CASE ( 1 )     ;   ipj = nlcj       ! 1 proc only  along the i-direction
+      CASE DEFAULT   ;   ipj = 4          ! several proc along the i-direction
+      END SELECT
+      ipjm1 = ipj-1
+
+      !
+      DO jf = 1, ipf                      ! Loop on the number of arrays to be treated
+         !
+         SELECT CASE ( npolj )
+         !
+         CASE ( 3 , 4 )                        ! *  North fold  T-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf)  )
+            CASE ( 'T' , 'W' )                         ! T-, W-point
+               DO ji = 2, jpiglo
+                  ijt = jpiglo-ji+2
+                  ARRAY_IN(ji,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2,:,:,jf)
+               END DO
+               ARRAY_IN(1,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(3,ipj-2,:,:,jf)
+               DO ji = jpiglo/2+1, jpiglo
+                  ijt = jpiglo-ji+2
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'U' )                               ! U-point
+               DO ji = 1, jpiglo-1
+                  iju = jpiglo-ji+1
+                  ARRAY_IN(ji,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2,:,:,jf)
+               END DO
+               ARRAY_IN(   1  ,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(    2   ,ipj-2,:,:,jf)
+               ARRAY_IN(jpiglo,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-1,ipj-2,:,:,jf) 
+               DO ji = jpiglo/2, jpiglo-1
+                  iju = jpiglo-ji+1
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'V' )                               ! V-point
+               DO ji = 2, jpiglo
+                  ijt = jpiglo-ji+2
+                  ARRAY_IN(ji,ipj-1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2,:,:,jf)
+                  ARRAY_IN(ji,ipj  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-3,:,:,jf)
+               END DO
+               ARRAY_IN(1,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(3,ipj-3,:,:,jf) 
+            CASE ( 'F' )                               ! F-point
+               DO ji = 1, jpiglo-1
+                  iju = jpiglo-ji+1
+                  ARRAY_IN(ji,ipj-1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2,:,:,jf)
+                  ARRAY_IN(ji,ipj  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-3,:,:,jf)
+               END DO
+               ARRAY_IN(   1  ,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(    2   ,ipj-3,:,:,jf)
+               ARRAY_IN(jpiglo,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(jpiglo-1,ipj-3,:,:,jf) 
+            END SELECT
+            !
+         CASE ( 5 , 6 )                        ! *  North fold  F-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf)  )
+            CASE ( 'T' , 'W' )                         ! T-, W-point
+               DO ji = 1, jpiglo
+                  ijt = jpiglo-ji+1
+                  ARRAY_IN(ji,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-1,:,:,jf)
+               END DO
+            CASE ( 'U' )                               ! U-point
+               DO ji = 1, jpiglo-1
+                  iju = jpiglo-ji
+                  ARRAY_IN(ji,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-1,:,:,jf)
+               END DO
+               ARRAY_IN(jpiglo,ipj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(jpiglo-2,ipj-1,:,:,jf)
+            CASE ( 'V' )                               ! V-point
+               DO ji = 1, jpiglo
+                  ijt = jpiglo-ji+1
+                  ARRAY_IN(ji,ipj,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipj-2,:,:,jf)
+               END DO
+               DO ji = jpiglo/2+1, jpiglo
+                  ijt = jpiglo-ji+1
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(ijt,ipjm1,:,:,jf)
+               END DO
+            CASE ( 'F' )                               ! F-point
+               DO ji = 1, jpiglo-1
+                  iju = jpiglo-ji
+                  ARRAY_IN(ji,ipj  ,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipj-2,:,:,jf)
+               END DO
+               ARRAY_IN(jpiglo,ipj,:,:,jf) = SGN_IN(jf)   * ARRAY_IN(jpiglo-2,ipj-2,:,:,jf)
+               DO ji = jpiglo/2+1, jpiglo-1
+                  iju = jpiglo-ji
+                  ARRAY_IN(ji,ipjm1,:,:,jf) = SGN_IN(jf)  * ARRAY_IN(iju,ipjm1,:,:,jf)
+               END DO
+            END SELECT
+            !
+         CASE DEFAULT                           ! *  closed : the code probably never go through
+            !
+            SELECT CASE ( NAT_IN(jf) )
+            CASE ( 'T' , 'U' , 'V' , 'W' )             ! T-, U-, V-, W-points
+               ARRAY_IN(:, 1 ,:,:,jf) = 0._wp
+               ARRAY_IN(:,ipj,:,:,jf) = 0._wp
+            CASE ( 'F' )                               ! F-point
+               ARRAY_IN(:,ipj,:,:,jf) = 0._wp
+            END SELECT
+            !
+         END SELECT     !  npolj
+         !
+      END DO
+      !
+   END SUBROUTINE ROUTINE_NFD
+
+#undef ARRAY_TYPE
+#undef ARRAY_IN
+#undef NAT_IN
+#undef SGN_IN
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_nogather_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_nogather_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbc_nfd_nogather_generic.h90	(revision 14097)
@@ -0,0 +1,356 @@
+#if defined MULTI
+#   define NAT_IN(k)                cd_nat(k)   
+#   define SGN_IN(k)                psgn(k)
+#   define F_SIZE(ptab)             kfld
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt2d(i,j)
+#      define K_SIZE(ptab)             1
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt3d(i,j,k)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt3d,3)
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D),INTENT(inout)::ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt4d(i,j,k,l)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt4d,3)
+#      define L_SIZE(ptab)             SIZE(ptab(1)%pt4d,4)
+#   endif
+#   define ARRAY2_TYPE(i,j,k,l,f)   TYPE(PTR_4D),INTENT(inout)::ptab2(f)
+#   define J_SIZE(ptab2)            SIZE(ptab2(1)%pt4d,2)
+#   define ARRAY2_IN(i,j,k,l,f)     ptab2(f)%pt4d(i,j,k,l)
+#else
+!                          !==  IN: ptab is an array  ==!
+#   define NAT_IN(k)                cd_nat
+#   define SGN_IN(k)                psgn
+#   define F_SIZE(ptab)             1
+#   if defined DIM_2d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j)
+#      define K_SIZE(ptab)          1
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k,l)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          SIZE(ptab,4)
+#   endif
+#   define ARRAY2_IN(i,j,k,l,f)  ptab2(i,j,k,l)
+#   define J_SIZE(ptab2)             SIZE(ptab2,2)
+#   define ARRAY_TYPE(i,j,k,l,f)     REAL(wp),INTENT(inout)::ARRAY_IN(i,j,k,l,f)
+#   define ARRAY2_TYPE(i,j,k,l,f)    REAL(wp),INTENT(inout)::ARRAY2_IN(i,j,k,l,f)
+#endif
+
+   SUBROUTINE ROUTINE_NFD( ptab, ptab2, cd_nat, psgn, kfld )
+      !!----------------------------------------------------------------------
+      !!
+      !! ** Purpose :   lateral boundary condition : North fold treatment
+      !!                without allgather exchanges. 
+      !!
+      !!----------------------------------------------------------------------
+      ARRAY_TYPE(:,:,:,:,:)                             ! array or pointer of arrays on which the boundary condition is applied
+      ARRAY2_TYPE(:,:,:,:,:)                            ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=1) , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)         , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kfld        ! number of pt3d arrays
+      !
+      INTEGER  ::    ji,  jj,   jk,     jl,   jh,  jf   ! dummy loop indices
+      INTEGER  ::   ipi, ipj,  ipk,    ipl,  ipf        ! dimension of the input array
+      INTEGER  ::   ijt, iju, ijpj, ijpjp1, ijta, ijua, jia, startloop, endloop
+      LOGICAL  ::   l_fast_exchanges
+      !!----------------------------------------------------------------------
+      ipj = J_SIZE(ptab2)  ! 2nd dimension of input array
+      ipk = K_SIZE(ptab)   ! 3rd dimension of output array
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      ! Security check for further developments
+      IF ( ipf > 1 ) CALL ctl_stop( 'STOP', 'lbc_nfd_nogather: multiple fields not allowed. Revise implementation...' )
+      !
+      ijpj   = 1    ! index of first modified line 
+      ijpjp1 = 2    ! index + 1
+      
+      ! 2nd dimension determines exchange speed
+      IF (ipj == 1 ) THEN
+        l_fast_exchanges = .TRUE.
+      ELSE
+        l_fast_exchanges = .FALSE.
+      ENDIF
+      !
+      DO jf = 1, ipf                      ! Loop over the number of arrays to be processed
+         !
+         SELECT CASE ( npolj )
+         !
+         CASE ( 3, 4 )                       ! *  North fold  T-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf) )
+            !
+            CASE ( 'T' , 'W' )                         ! T-, W-point
+               IF ( nimpp /= 1 ) THEN   ;   startloop = 1
+               ELSE                     ;   startloop = 2
+               ENDIF
+               !
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = startloop, nlci
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF( nimpp == 1 ) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     ARRAY_IN(1,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY_IN(3,nlcj-2,jk,jl,jf)
+                  END DO; END DO
+               ENDIF
+               !
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  IF( nimpp >= jpiglo/2+1 ) THEN
+                     startloop = 1
+                  ELSEIF( nimpp+nlci-1 >= jpiglo/2+1 .AND. nimpp < jpiglo/2+1 ) THEN
+                     startloop = jpiglo/2+1 - nimpp + 1
+                  ELSE
+                     startloop = nlci + 1
+                  ENDIF
+                  IF( startloop <= nlci ) THEN
+                     DO jl = 1, ipl; DO jk = 1, ipk
+                        DO ji = startloop, nlci
+                           ijt  = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
+                           jia  = ji + nimpp - 1
+                           ijta = jpiglo - jia + 2
+                           IF( ijta >= startloop+nimpp-1 .AND. ijta < jia ) THEN
+                              ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY_IN(ijta-nimpp+1,nlcj-1,jk,jl,jf)
+                           ELSE
+                              ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpjp1,jk,jl,jf)
+                           ENDIF
+                        END DO
+                     END DO; END DO
+                  ENDIF
+               ENDIF
+
+            CASE ( 'U' )                                     ! U-point
+               IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                  endloop = nlci
+               ELSE
+                  endloop = nlci - 1
+               ENDIF
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, endloop
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF (nimpp .eq. 1) THEN
+                  ARRAY_IN(1,nlcj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(2,nlcj-2,:,:,jf)
+               ENDIF
+               IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                  ARRAY_IN(nlci,nlcj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(nlci-1,nlcj-2,:,:,jf)
+               ENDIF
+               !
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                     endloop = nlci
+                  ELSE
+                     endloop = nlci - 1
+                  ENDIF
+                  IF( nimpp >= jpiglo/2 ) THEN
+                     startloop = 1
+                     ELSEIF( ( nimpp+nlci-1 >= jpiglo/2 ) .AND. ( nimpp < jpiglo/2 ) ) THEN
+                     startloop = jpiglo/2 - nimpp + 1
+                  ELSE
+                     startloop = endloop + 1
+                  ENDIF
+                  IF( startloop <= endloop ) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     DO ji = startloop, endloop
+                        iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                        jia = ji + nimpp - 1
+                        ijua = jpiglo - jia + 1
+                        IF( ijua >= startloop+nimpp-1 .AND. ijua < jia ) THEN
+                           ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY_IN(ijua-nimpp+1,nlcj-1,jk,jl,jf)
+                        ELSE
+                           ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpjp1,jk,jl,jf)
+                        ENDIF
+                     END DO
+                  END DO; END DO
+                  ENDIF
+               ENDIF
+               !
+            CASE ( 'V' )                                     ! V-point
+               IF( nimpp /= 1 ) THEN
+                 startloop = 1
+               ELSE
+                 startloop = 2
+               ENDIF
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     DO ji = startloop, nlci
+                        ijt=jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
+                        ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpjp1,jk,jl,jf)
+                     END DO
+                  END DO; END DO
+               ENDIF
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = startloop, nlci
+                     ijt=jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF (nimpp .eq. 1) THEN
+                  ARRAY_IN(1,nlcj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(3,nlcj-3,:,:,jf)
+               ENDIF
+            CASE ( 'F' )                                     ! F-point
+               IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                  endloop = nlci
+               ELSE
+                  endloop = nlci - 1
+               ENDIF
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     DO ji = 1, endloop
+                        iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                        ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpjp1,jk,jl,jf)
+                     END DO
+                  END DO; END DO
+               ENDIF
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, endloop
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF (nimpp .eq. 1) THEN
+                  ARRAY_IN(1,nlcj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(2,nlcj-3,:,:,jf)
+                  IF ( .NOT. l_fast_exchanges ) &
+                     ARRAY_IN(1,nlcj-1,:,:,jf) = SGN_IN(jf) * ARRAY_IN(2,nlcj-2,:,:,jf)
+               ENDIF
+               IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                  ARRAY_IN(nlci,nlcj,:,:,jf) = SGN_IN(jf) * ARRAY_IN(nlci-1,nlcj-3,:,:,jf)
+                  IF ( .NOT. l_fast_exchanges ) &
+                     ARRAY_IN(nlci,nlcj-1,:,:,jf) = SGN_IN(jf) * ARRAY_IN(nlci-1,nlcj-2,:,:,jf)
+               ENDIF
+               !
+            END SELECT
+            !
+         CASE ( 5, 6 )                        ! *  North fold  F-point pivot
+            !
+            SELECT CASE ( NAT_IN(jf) )
+            CASE ( 'T' , 'W' )                               ! T-, W-point
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, nlci
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               !
+            CASE ( 'U' )                                     ! U-point
+               IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                  endloop = nlci
+               ELSE
+                  endloop = nlci - 1
+               ENDIF
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, endloop
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     ARRAY_IN(nlci,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY_IN(nlci-2,nlcj-1,jk,jl,jf)
+                  END DO; END DO
+               ENDIF
+               !
+            CASE ( 'V' )                                     ! V-point
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, nlci
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                     ARRAY_IN(ji,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  IF( nimpp >= jpiglo/2+1 ) THEN
+                     startloop = 1
+                  ELSEIF( nimpp+nlci-1 >= jpiglo/2+1 .AND. nimpp < jpiglo/2+1 ) THEN
+                     startloop = jpiglo/2+1 - nimpp + 1
+                  ELSE
+                     startloop = nlci + 1
+                  ENDIF
+                  IF( startloop <= nlci ) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     DO ji = startloop, nlci
+                        ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
+                        ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(ijt,ijpjp1,jk,jl,jf)
+                     END DO
+                  END DO; END DO
+                  ENDIF
+               ENDIF
+               !
+            CASE ( 'F' )                               ! F-point
+               IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                  endloop = nlci
+               ELSE
+                  endloop = nlci - 1
+               ENDIF
+               DO jl = 1, ipl; DO jk = 1, ipk
+                  DO ji = 1, endloop
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
+                     ARRAY_IN(ji,nlcj ,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpj,jk,jl,jf)
+                  END DO
+               END DO; END DO
+               IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                  DO jl = 1, ipl; DO jk = 1, ipk
+                     ARRAY_IN(nlci,nlcj,jk,jl,jf) = SGN_IN(jf) * ARRAY_IN(nlci-2,nlcj-2,jk,jl,jf)
+                  END DO; END DO
+               ENDIF
+               !
+               IF ( .NOT. l_fast_exchanges ) THEN
+                  IF( nimpp + nlci - 1 /= jpiglo ) THEN
+                     endloop = nlci
+                  ELSE
+                     endloop = nlci - 1
+                  ENDIF
+                  IF( nimpp >= jpiglo/2+1 ) THEN
+                     startloop = 1
+                  ELSEIF( nimpp+nlci-1 >= jpiglo/2+1 .AND. nimpp < jpiglo/2+1 ) THEN
+                     startloop = jpiglo/2+1 - nimpp + 1
+                  ELSE
+                     startloop = endloop + 1
+                  ENDIF
+                  IF( startloop <= endloop ) THEN
+                     DO jl = 1, ipl; DO jk = 1, ipk
+                        DO ji = startloop, endloop
+                           iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
+                           ARRAY_IN(ji,nlcj-1,jk,jl,jf) = SGN_IN(jf) * ARRAY2_IN(iju,ijpjp1,jk,jl,jf)
+                        END DO
+                     END DO; END DO
+                  ENDIF
+               ENDIF
+               !
+            END SELECT
+            !
+         CASE DEFAULT                           ! *  closed : the code probably never go through
+            !
+            WRITE(*,*) 'lbc_nfd_nogather_generic: You should not have seen this print! error?', npolj
+            !
+         END SELECT     !  npolj
+         !
+      END DO            ! End jf loop
+   END SUBROUTINE ROUTINE_NFD
+#undef ARRAY_TYPE
+#undef ARRAY_IN
+#undef NAT_IN
+#undef SGN_IN
+#undef J_SIZE
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
+#undef ARRAY2_TYPE
+#undef ARRAY2_IN
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbclnk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbclnk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbclnk.F90	(revision 14097)
@@ -0,0 +1,507 @@
+MODULE lbclnk
+   !!======================================================================
+   !!                       ***  MODULE  lbclnk  ***
+   !! NEMO        : lateral boundary conditions
+   !!=====================================================================
+   !! History :  OPA  ! 1997-06  (G. Madec)  Original code
+   !!   NEMO     1.0  ! 2002-09  (G. Madec)  F90: Free form and module
+   !!            3.2  ! 2009-03  (R. Benshila)  External north fold treatment  
+   !!            3.5  ! 2012     (S.Mocavero, I. Epicoco)  optimization of BDY comm. via lbc_bdy_lnk and lbc_obc_lnk
+   !!            3.4  ! 2012-12  (R. Bourdalle-Badie, G. Reffray)  add a C1D case  
+   !!            3.6  ! 2015-06  (O. Tintó and M. Castrillo)  add lbc_lnk_multi  
+   !!            4.0  ! 2017-03  (G. Madec) automatique allocation of array size (use with any 3rd dim size)
+   !!             -   ! 2017-04  (G. Madec) remove duplicated routines (lbc_lnk_2d_9, lbc_lnk_2d_multiple, lbc_lnk_3d_gather)
+   !!             -   ! 2017-05  (G. Madec) create generic.h90 files to generate all lbc and north fold routines
+   !!----------------------------------------------------------------------
+   !!           define the generic interfaces of lib_mpp routines
+   !!----------------------------------------------------------------------
+   !!   lbc_lnk       : generic interface for mpp_lnk_3d and mpp_lnk_2d routines defined in lib_mpp
+   !!   lbc_bdy_lnk   : generic interface for mpp_lnk_bdy_2d and mpp_lnk_bdy_3d routines defined in lib_mpp
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE lib_mpp        ! distributed memory computing library
+   USE lbcnfd         ! north fold
+   USE in_out_manager ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE lbc_lnk
+      MODULE PROCEDURE   mpp_lnk_2d      , mpp_lnk_3d      , mpp_lnk_4d
+   END INTERFACE
+   INTERFACE lbc_lnk_ptr
+      MODULE PROCEDURE   mpp_lnk_2d_ptr  , mpp_lnk_3d_ptr  , mpp_lnk_4d_ptr
+   END INTERFACE
+   INTERFACE lbc_lnk_multi
+      MODULE PROCEDURE   lbc_lnk_2d_multi, lbc_lnk_3d_multi, lbc_lnk_4d_multi
+   END INTERFACE
+   !
+   INTERFACE lbc_lnk_icb
+      MODULE PROCEDURE mpp_lnk_2d_icb
+   END INTERFACE
+
+   INTERFACE mpp_nfd
+      MODULE PROCEDURE   mpp_nfd_2d    , mpp_nfd_3d    , mpp_nfd_4d
+      MODULE PROCEDURE   mpp_nfd_2d_ptr, mpp_nfd_3d_ptr, mpp_nfd_4d_ptr
+   END INTERFACE
+
+   PUBLIC   lbc_lnk       ! ocean/ice lateral boundary conditions
+   PUBLIC   lbc_lnk_multi ! modified ocean/ice lateral boundary conditions
+   PUBLIC   lbc_lnk_icb   ! iceberg lateral boundary conditions
+
+#if   defined key_mpp_mpi
+!$AGRIF_DO_NOT_TREAT
+   INCLUDE 'mpif.h'
+!$AGRIF_END_DO_NOT_TREAT
+#endif
+
+   INTEGER, PUBLIC, PARAMETER ::   jpfillnothing = 1
+   INTEGER, PUBLIC, PARAMETER ::   jpfillcst     = 2
+   INTEGER, PUBLIC, PARAMETER ::   jpfillcopy    = 3
+   INTEGER, PUBLIC, PARAMETER ::   jpfillperio   = 4
+   INTEGER, PUBLIC, PARAMETER ::   jpfillmpi     = 5
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   !!----------------------------------------------------------------------
+   !!                   ***   load_ptr_(2,3,4)d   ***
+   !!
+   !!   * Dummy Argument :
+   !!       in    ==>   ptab       ! array to be loaded (2D, 3D or 4D)
+   !!                   cd_nat     ! nature of pt2d array grid-points
+   !!                   psgn       ! sign used across the north fold boundary
+   !!       inout <=>   ptab_ptr   ! array of 2D, 3D or 4D pointers
+   !!                   cdna_ptr   ! nature of ptab array grid-points
+   !!                   psgn_ptr   ! sign used across the north fold boundary
+   !!                   kfld       ! number of elements that has been attributed
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!                  ***   lbc_lnk_(2,3,4)d_multi   ***
+   !!                     ***   load_ptr_(2,3,4)d   ***
+   !!
+   !!   * Argument : dummy argument use in lbc_lnk_multi_... routines
+   !!
+   !!----------------------------------------------------------------------
+
+#  define DIM_2d
+#     define ROUTINE_LOAD           load_ptr_2d
+#     define ROUTINE_MULTI          lbc_lnk_2d_multi
+#     include "lbc_lnk_multi_generic.h90"
+#     undef ROUTINE_MULTI
+#     undef ROUTINE_LOAD
+#  undef DIM_2d
+
+#  define DIM_3d
+#     define ROUTINE_LOAD           load_ptr_3d
+#     define ROUTINE_MULTI          lbc_lnk_3d_multi
+#     include "lbc_lnk_multi_generic.h90"
+#     undef ROUTINE_MULTI
+#     undef ROUTINE_LOAD
+#  undef DIM_3d
+
+#  define DIM_4d
+#     define ROUTINE_LOAD           load_ptr_4d
+#     define ROUTINE_MULTI          lbc_lnk_4d_multi
+#     include "lbc_lnk_multi_generic.h90"
+#     undef ROUTINE_MULTI
+#     undef ROUTINE_LOAD
+#  undef DIM_4d
+
+   !!----------------------------------------------------------------------
+   !!                   ***  routine mpp_lnk_(2,3,4)d  ***
+   !!
+   !!   * Argument : dummy argument use in mpp_lnk_... routines
+   !!                ptab      :   array or pointer of arrays on which the boundary condition is applied
+   !!                cd_nat    :   nature of array grid-points
+   !!                psgn      :   sign used across the north fold boundary
+   !!                kfld      :   optional, number of pt3d arrays
+   !!                kfillmode :   optional, method to be use to fill the halos (see jpfill* variables)
+   !!                pfillval  :   optional, background value (used with jpfillcopy)
+   !!----------------------------------------------------------------------
+   !
+   !                       !==  2D array and array of 2D pointer  ==!
+   !
+#  define DIM_2d
+#     define ROUTINE_LNK           mpp_lnk_2d
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     define MULTI
+#     define ROUTINE_LNK           mpp_lnk_2d_ptr
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     undef MULTI
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_LNK           mpp_lnk_3d
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     define MULTI
+#     define ROUTINE_LNK           mpp_lnk_3d_ptr
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     undef MULTI
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_LNK           mpp_lnk_4d
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     define MULTI
+#     define ROUTINE_LNK           mpp_lnk_4d_ptr
+#     include "mpp_lnk_generic.h90"
+#     undef ROUTINE_LNK
+#     undef MULTI
+#  undef DIM_4d
+
+   !!----------------------------------------------------------------------
+   !!                   ***  routine mpp_nfd_(2,3,4)d  ***
+   !!
+   !!   * Argument : dummy argument use in mpp_nfd_... routines
+   !!                ptab      :   array or pointer of arrays on which the boundary condition is applied
+   !!                cd_nat    :   nature of array grid-points
+   !!                psgn      :   sign used across the north fold boundary
+   !!                kfld      :   optional, number of pt3d arrays
+   !!                kfillmode :   optional, method to be use to fill the halos (see jpfill* variables)
+   !!                pfillval  :   optional, background value (used with jpfillcopy)
+   !!----------------------------------------------------------------------
+   !
+   !                       !==  2D array and array of 2D pointer  ==!
+   !
+#  define DIM_2d
+#     define ROUTINE_NFD           mpp_nfd_2d
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           mpp_nfd_2d_ptr
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_NFD           mpp_nfd_3d
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           mpp_nfd_3d_ptr
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_NFD           mpp_nfd_4d
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           mpp_nfd_4d_ptr
+#     include "mpp_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_4d
+
+
+   !!======================================================================
+
+
+
+   SUBROUTINE mpp_lbc_north_icb( pt2d, cd_type, psgn, kextj)
+      !!---------------------------------------------------------------------
+      !!                   ***  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+kextj 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 routine accounts for an extra halo with icebergs
+      !!              and assumes ghost rows and columns have been suppressed.
+      !!
+      !!----------------------------------------------------------------------
+      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                 , INTENT(in   ) ::   kextj    ! Extra halo width at north fold
+      !
+      INTEGER ::   ji, jj, jr
+      INTEGER ::   ierr, itaille, ildi, ilei, iilb
+      INTEGER ::   ipj, ij, iproc
+      !
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE  ::  ztab_e, znorthloc_e
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE  ::  znorthgloio_e
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      !
+      ipj=4
+      ALLOCATE(        ztab_e(jpiglo, 1-kextj:ipj+kextj)       ,       &
+     &            znorthloc_e(jpimax, 1-kextj:ipj+kextj)       ,       &
+     &          znorthgloio_e(jpimax, 1-kextj:ipj+kextj,jpni)    )
+      !
+      ztab_e(:,:)      = 0._wp
+      znorthloc_e(:,:) = 0._wp
+      !
+      ij = 1 - kextj
+      ! put the last ipj+2*kextj lines of pt2d into znorthloc_e 
+      DO jj = jpj - ipj + 1 - kextj , jpj + kextj
+         znorthloc_e(1:jpi,ij)=pt2d(1:jpi,jj)
+         ij = ij + 1
+      END DO
+      !
+      itaille = jpimax * ( ipj + 2*kextj )
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE.)
+      CALL MPI_ALLGATHER( znorthloc_e(1,1-kextj)    , itaille, MPI_DOUBLE_PRECISION,    &
+         &                znorthgloio_e(1,1-kextj,1), itaille, MPI_DOUBLE_PRECISION,    &
+         &                ncomm_north, ierr )
+      !
+      IF( ln_timing ) CALL tic_tac(.FALSE.)
+      !
+      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-kextj, ipj+kextj
+            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(:,1-kextj:ipj+kextj), cd_type, psgn, kextj )
+
+      ij = 1 - kextj
+      !! Scatter back to pt2d
+      DO jj = jpj - ipj + 1 - kextj , jpj + kextj
+         DO ji= 1, jpi
+            pt2d(ji,jj) = ztab_e(ji+nimpp-1,ij)
+         END DO
+         ij  = ij +1
+      END DO
+      !
+      DEALLOCATE( ztab_e, znorthloc_e, znorthgloio_e )
+      !
+#endif
+   END SUBROUTINE mpp_lbc_north_icb
+
+
+   SUBROUTINE mpp_lnk_2d_icb( cdname, pt2d, cd_type, psgn, kexti, kextj )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mpp_lnk_2d_icb  ***
+      !!
+      !! ** Purpose :   Message passing management for 2d array (with extra halo for icebergs)
+      !!                This routine receives a (1-kexti:jpi+kexti,1-kexti:jpj+kextj)
+      !!                array (usually (0:jpi+1, 0:jpj+1)) from lbc_lnk_icb calls.
+      !!
+      !! ** Method  :   Use mppsend and mpprecv function for passing mask
+      !!      between processors following neighboring subdomains.
+      !!            domain parameters
+      !!                    jpi    : first dimension of the local subdomain
+      !!                    jpj    : second dimension of the local subdomain
+      !!                    kexti  : number of columns for extra outer halo
+      !!                    kextj  : number of rows 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
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)                                        , INTENT(in   ) ::   cdname      ! name of the calling subroutine
+      REAL(wp), DIMENSION(1-kexti:jpi+kexti,1-kextj:jpj+kextj), INTENT(inout) ::   pt2d     ! 2D array with extra halo
+      CHARACTER(len=1)                                        , INTENT(in   ) ::   cd_type  ! nature of ptab array grid-points
+      REAL(wp)                                                , INTENT(in   ) ::   psgn     ! sign used across the north fold
+      INTEGER                                                 , INTENT(in   ) ::   kexti    ! extra i-halo width
+      INTEGER                                                 , INTENT(in   ) ::   kextj    ! extra j-halo width
+      !
+      INTEGER  ::   jl   ! dummy loop indices
+      INTEGER  ::   imigr, iihom, ijhom        ! local integers
+      INTEGER  ::   ipreci, iprecj             !   -       -
+      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-kexti:jpi+kexti,nn_hls+kextj,2) ::   r2dns, r2dsn
+      REAL(wp), DIMENSION(1-kextj:jpj+kextj,nn_hls+kexti,2) ::   r2dwe, r2dew
+      !!----------------------------------------------------------------------
+
+      ipreci = nn_hls + kexti      ! take into account outer extra 2D overlap area
+      iprecj = nn_hls + kextj
+
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, 1, 1, 1, ld_lbc = .TRUE. )
+
+      ! 1. standard boundary treatment
+      ! ------------------------------
+      ! Order matters Here !!!!
+      !
+      !                                      ! East-West boundaries
+      !                                           !* Cyclic east-west
+      IF( l_Iperio ) THEN
+         pt2d(1-kexti:     1   ,:) = pt2d(jpim1-kexti: jpim1 ,:)       ! east
+         pt2d(  jpi  :jpi+kexti,:) = pt2d(     2     :2+kexti,:)       ! west
+         !
+      ELSE                                        !* closed
+         IF( .NOT. cd_type == 'F' )   pt2d(  1-kexti   :nn_hls   ,:) = 0._wp    ! east except at F-point
+                                      pt2d(jpi-nn_hls+1:jpi+kexti,:) = 0._wp    ! west
+      ENDIF
+      !                                      ! North-South boundaries
+      IF( l_Jperio ) THEN                         !* cyclic (only with no mpp j-split)
+         pt2d(:,1-kextj:     1   ) = pt2d(:,jpjm1-kextj:  jpjm1)       ! north
+         pt2d(:,  jpj  :jpj+kextj) = pt2d(:,     2     :2+kextj)       ! south
+      ELSE                                        !* closed
+         IF( .NOT. cd_type == 'F' )   pt2d(:,  1-kextj   :nn_hls   ) = 0._wp    ! north except at F-point
+                                      pt2d(:,jpj-nn_hls+1:jpj+kextj) = 0._wp    ! south
+      ENDIF
+      !
+
+      ! north fold treatment
+      ! -----------------------
+      IF( npolj /= 0 ) THEN
+         !
+         SELECT CASE ( jpni )
+                   CASE ( 1 )     ;   CALL lbc_nfd          ( pt2d(1:jpi,1-kextj:jpj+kextj), cd_type, psgn, kextj )
+                   CASE DEFAULT   ;   CALL mpp_lbc_north_icb( pt2d(1:jpi,1:jpj+kextj), cd_type, psgn, kextj )
+         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 = jpi-nreci-kexti
+         DO jl = 1, ipreci
+            r2dew(:,jl,1) = pt2d(nn_hls+jl,:)
+            r2dwe(:,jl,1) = pt2d(iihom +jl,:)
+         END DO
+      END SELECT
+      !
+      !                           ! Migrations
+      imigr = ipreci * ( jpj + 2*kextj )
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE.)
+      !
+      SELECT CASE ( nbondi )
+      CASE ( -1 )
+         CALL mppsend( 2, r2dwe(1-kextj,1,1), imigr, noea, ml_req1 )
+         CALL mpprecv( 1, r2dew(1-kextj,1,2), imigr, noea )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      CASE ( 0 )
+         CALL mppsend( 1, r2dew(1-kextj,1,1), imigr, nowe, ml_req1 )
+         CALL mppsend( 2, r2dwe(1-kextj,1,1), imigr, noea, ml_req2 )
+         CALL mpprecv( 1, r2dew(1-kextj,1,2), imigr, noea )
+         CALL mpprecv( 2, r2dwe(1-kextj,1,2), imigr, nowe )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+         CALL mpi_wait(ml_req2,ml_stat,ml_err)
+      CASE ( 1 )
+         CALL mppsend( 1, r2dew(1-kextj,1,1), imigr, nowe, ml_req1 )
+         CALL mpprecv( 2, r2dwe(1-kextj,1,2), imigr, nowe )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      END SELECT
+      !
+      IF( ln_timing ) CALL tic_tac(.FALSE.)
+      !
+      !                           ! Write Dirichlet lateral conditions
+      iihom = jpi - nn_hls
+      !
+      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-kexti,:) = r2dwe(:,jl,2)
+            pt2d(iihom+jl,:) = r2dew(:,jl,2)
+         END DO
+      CASE ( 1 )
+         DO jl = 1, ipreci
+            pt2d(jl-kexti,:) = 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 = jpj-nrecj-kextj
+         DO jl = 1, iprecj
+            r2dsn(:,jl,1) = pt2d(:,ijhom +jl)
+            r2dns(:,jl,1) = pt2d(:,nn_hls+jl)
+         END DO
+      ENDIF
+      !
+      !                           ! Migrations
+      imigr = iprecj * ( jpi + 2*kexti )
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE.)
+      !
+      SELECT CASE ( nbondj )
+      CASE ( -1 )
+         CALL mppsend( 4, r2dsn(1-kexti,1,1), imigr, nono, ml_req1 )
+         CALL mpprecv( 3, r2dns(1-kexti,1,2), imigr, nono )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      CASE ( 0 )
+         CALL mppsend( 3, r2dns(1-kexti,1,1), imigr, noso, ml_req1 )
+         CALL mppsend( 4, r2dsn(1-kexti,1,1), imigr, nono, ml_req2 )
+         CALL mpprecv( 3, r2dns(1-kexti,1,2), imigr, nono )
+         CALL mpprecv( 4, r2dsn(1-kexti,1,2), imigr, noso )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+         CALL mpi_wait(ml_req2,ml_stat,ml_err)
+      CASE ( 1 )
+         CALL mppsend( 3, r2dns(1-kexti,1,1), imigr, noso, ml_req1 )
+         CALL mpprecv( 4, r2dsn(1-kexti,1,2), imigr, noso )
+         CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      END SELECT
+      !
+      IF( ln_timing ) CALL tic_tac(.FALSE.)
+      !
+      !                           ! Write Dirichlet lateral conditions
+      ijhom = jpj - nn_hls
+      !
+      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-kextj) = r2dsn(:,jl,2)
+            pt2d(:,ijhom+jl) = r2dns(:,jl,2)
+         END DO
+      CASE ( 1 )
+         DO jl = 1, iprecj
+            pt2d(:,jl-kextj) = r2dsn(:,jl,2)
+         END DO
+      END SELECT
+      !
+   END SUBROUTINE mpp_lnk_2d_icb
+   
+END MODULE lbclnk
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbcnfd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbcnfd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lbcnfd.F90	(revision 14097)
@@ -0,0 +1,169 @@
+MODULE lbcnfd
+   !!======================================================================
+   !!                       ***  MODULE  lbcnfd  ***
+   !! Ocean        : north fold  boundary conditions
+   !!======================================================================
+   !! History :  3.2  ! 2009-03  (R. Benshila)  Original code 
+   !!            3.5  ! 2013-07  (I. Epicoco, S. Mocavero - CMCC) MPP optimization
+   !!            4.0  ! 2017-04  (G. Madec) automatique allocation of array argument (use any 3rd dimension)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   lbc_nfd       : generic interface for lbc_nfd_3d and lbc_nfd_2d routines
+   !!   lbc_nfd_3d    : lateral boundary condition: North fold treatment for a 3D arrays   (lbc_nfd)
+   !!   lbc_nfd_2d    : lateral boundary condition: North fold treatment for a 2D arrays   (lbc_nfd)
+   !!   lbc_nfd_nogather       : generic interface for lbc_nfd_nogather_3d and 
+   !!                            lbc_nfd_nogather_2d routines (designed for use
+   !!                            with ln_nnogather to avoid global width arrays
+   !!                            mpi all gather operations)
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain 
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE lbc_nfd
+      MODULE PROCEDURE   lbc_nfd_2d    , lbc_nfd_3d    , lbc_nfd_4d
+      MODULE PROCEDURE   lbc_nfd_2d_ptr, lbc_nfd_3d_ptr, lbc_nfd_4d_ptr
+      MODULE PROCEDURE   lbc_nfd_2d_ext
+   END INTERFACE
+   !
+   INTERFACE lbc_nfd_nogather
+!                        ! Currently only 4d array version is needed
+     MODULE PROCEDURE   lbc_nfd_nogather_2d    , lbc_nfd_nogather_3d
+     MODULE PROCEDURE   lbc_nfd_nogather_4d
+     MODULE PROCEDURE   lbc_nfd_nogather_2d_ptr, lbc_nfd_nogather_3d_ptr
+!     MODULE PROCEDURE   lbc_nfd_nogather_4d_ptr
+   END INTERFACE
+
+   TYPE, PUBLIC ::   PTR_2D   !: array of 2D pointers (also used in lib_mpp)
+      REAL(wp), DIMENSION (:,:)    , POINTER ::   pt2d
+   END TYPE PTR_2D
+   TYPE, PUBLIC ::   PTR_3D   !: array of 3D pointers (also used in lib_mpp)
+      REAL(wp), DIMENSION (:,:,:)  , POINTER ::   pt3d
+   END TYPE PTR_3D
+   TYPE, PUBLIC ::   PTR_4D   !: array of 4D pointers (also used in lib_mpp)
+      REAL(wp), DIMENSION (:,:,:,:), POINTER ::   pt4d
+   END TYPE PTR_4D
+
+   PUBLIC   lbc_nfd            ! north fold conditions
+   PUBLIC   lbc_nfd_nogather   ! north fold conditions (no allgather case)
+
+   INTEGER, PUBLIC, PARAMETER            ::   jpmaxngh = 3               !:
+   INTEGER, PUBLIC                       ::   nsndto, nfsloop, nfeloop   !:
+   INTEGER, PUBLIC, DIMENSION (jpmaxngh) ::   isendto                    !: processes to which communicate
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   !!----------------------------------------------------------------------
+   !!                   ***  routine lbc_nfd_(2,3,4)d  ***
+   !!----------------------------------------------------------------------
+   !!
+   !! ** Purpose :   lateral boundary condition 
+   !!                North fold treatment without processor exchanges. 
+   !!
+   !! ** Method  :   
+   !!
+   !! ** Action  :   ptab with updated values along the north fold
+   !!----------------------------------------------------------------------
+   !
+   !                       !==  2D array and array of 2D pointer  ==!
+   !
+#  define DIM_2d
+#     define ROUTINE_NFD           lbc_nfd_2d
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           lbc_nfd_2d_ptr
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_2d
+   !
+   !                       !==  2D array with extra haloes  ==!
+   !
+#  define DIM_2d
+#     define ROUTINE_NFD           lbc_nfd_2d_ext
+#     include "lbc_nfd_ext_generic.h90"
+#     undef ROUTINE_NFD
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_NFD           lbc_nfd_3d
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           lbc_nfd_3d_ptr
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_NFD           lbc_nfd_4d
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           lbc_nfd_4d_ptr
+#     include "lbc_nfd_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_4d
+   !
+   !  lbc_nfd_nogather routines
+   !
+   !                       !==  2D array and array of 2D pointer  ==!
+   !
+#  define DIM_2d
+#     define ROUTINE_NFD           lbc_nfd_nogather_2d
+#     include "lbc_nfd_nogather_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           lbc_nfd_nogather_2d_ptr
+#     include "lbc_nfd_nogather_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_2d
+   !
+   !                       !==  3D array and array of 3D pointer  ==!
+   !
+#  define DIM_3d
+#     define ROUTINE_NFD           lbc_nfd_nogather_3d
+#     include "lbc_nfd_nogather_generic.h90"
+#     undef ROUTINE_NFD
+#     define MULTI
+#     define ROUTINE_NFD           lbc_nfd_nogather_3d_ptr
+#     include "lbc_nfd_nogather_generic.h90"
+#     undef ROUTINE_NFD
+#     undef MULTI
+#  undef DIM_3d
+   !
+   !                       !==  4D array and array of 4D pointer  ==!
+   !
+#  define DIM_4d
+#     define ROUTINE_NFD           lbc_nfd_nogather_4d
+#     include "lbc_nfd_nogather_generic.h90"
+#     undef ROUTINE_NFD
+!#     define MULTI
+!#     define ROUTINE_NFD           lbc_nfd_nogather_4d_ptr
+!#     include "lbc_nfd_nogather_generic.h90"
+!#     undef ROUTINE_NFD
+!#     undef MULTI
+#  undef DIM_4d
+
+   !!----------------------------------------------------------------------
+
+
+   !!======================================================================
+END MODULE lbcnfd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lib_mpp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lib_mpp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/lib_mpp.F90	(revision 14097)
@@ -0,0 +1,1303 @@
+MODULE lib_mpp
+   !!======================================================================
+   !!                       ***  MODULE  lib_mpp  ***
+   !! Ocean numerics:  massively parallel processing library
+   !!=====================================================================
+   !! History :  OPA  !  1994  (M. Guyon, J. Escobar, M. Imbard)  Original code
+   !!            7.0  !  1997  (A.M. Treguier)  SHMEM additions
+   !!            8.0  !  1998  (M. Imbard, J. Escobar, L. Colombet ) SHMEM and MPI
+   !!                 !  1998  (J.M. Molines) Open boundary conditions
+   !!   NEMO     1.0  !  2003  (J.M. Molines, G. Madec)  F90, free form
+   !!                 !  2003  (J.M. Molines) add mpp_ini_north(_3d,_2d)
+   !!             -   !  2004  (R. Bourdalle Badie)  isend option in mpi
+   !!                 !  2004  (J.M. Molines) minloc, maxloc
+   !!             -   !  2005  (G. Madec, S. Masson)  npolj=5,6 F-point & ice cases
+   !!             -   !  2005  (R. Redler) Replacement of MPI_COMM_WORLD except for MPI_Abort
+   !!             -   !  2005  (R. Benshila, G. Madec)  add extra halo case
+   !!             -   !  2008  (R. Benshila) add mpp_ini_ice
+   !!            3.2  !  2009  (R. Benshila) SHMEM suppression, north fold in lbc_nfd
+   !!            3.2  !  2009  (O. Marti)    add mpp_ini_znl
+   !!            4.0  !  2011  (G. Madec)  move ctl_ routines from in_out_manager
+   !!            3.5  !  2012  (S.Mocavero, I. Epicoco) Add mpp_lnk_bdy_3d/2d routines to optimize the BDY comm.
+   !!            3.5  !  2013  (C. Ethe, G. Madec)  message passing arrays as local variables 
+   !!            3.5  !  2013  (S.Mocavero, I.Epicoco - CMCC) north fold optimizations
+   !!            3.6  !  2015  (O. Tintó and M. Castrillo - BSC) Added '_multiple' case for 2D lbc and max
+   !!            4.0  !  2017  (G. Madec) automatique allocation of array argument (use any 3rd dimension)
+   !!             -   !  2017  (G. Madec) create generic.h90 files to generate all lbc and north fold routines
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ctl_stop      : update momentum and tracer Kz from a tke scheme
+   !!   ctl_warn      : initialization, namelist read, and parameters control
+   !!   ctl_opn       : Open file and check if required file is available.
+   !!   ctl_nam       : Prints informations when an error occurs while reading a namelist
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   mpp_start     : get local communicator its size and rank
+   !!   mpp_lnk       : interface (defined in lbclnk) for message passing of 2d or 3d arrays (mpp_lnk_2d, mpp_lnk_3d)
+   !!   mpp_lnk_icb   : interface for message passing of 2d arrays with extra halo for icebergs (mpp_lnk_2d_icb)
+   !!   mpprecv       :
+   !!   mppsend       :
+   !!   mppscatter    :
+   !!   mppgather     :
+   !!   mpp_min       : generic interface for mppmin_int , mppmin_a_int , mppmin_real, mppmin_a_real
+   !!   mpp_max       : generic interface for mppmax_int , mppmax_a_int , mppmax_real, mppmax_a_real
+   !!   mpp_sum       : generic interface for mppsum_int , mppsum_a_int , mppsum_real, mppsum_a_real
+   !!   mpp_minloc    :
+   !!   mpp_maxloc    :
+   !!   mppsync       :
+   !!   mppstop       :
+   !!   mpp_ini_north : initialisation of north fold
+   !!   mpp_lbc_north_icb : alternative to mpp_nfd for extra outer halo with icebergs
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE in_out_manager ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+   !
+   PUBLIC   ctl_stop, ctl_warn, ctl_opn, ctl_nam
+   PUBLIC   mpp_start, mppstop, mppsync, mpp_comm_free
+   PUBLIC   mpp_ini_north
+   PUBLIC   mpp_min, mpp_max, mpp_sum, mpp_minloc, mpp_maxloc
+   PUBLIC   mpp_delay_max, mpp_delay_sum, mpp_delay_rcv
+   PUBLIC   mppscatter, mppgather
+   PUBLIC   mpp_ini_znl
+   PUBLIC   mppsend, mpprecv                          ! needed by TAM and ICB routines
+   PUBLIC   mpp_report
+   PUBLIC   tic_tac
+#if ! defined key_mpp_mpi
+   PUBLIC MPI_Wtime
+#endif
+   
+   !! * Interfaces
+   !! define generic interface for these routine as they are called sometimes
+   !! with scalar arguments instead of array arguments, which causes problems
+   !! for the compilation on AIX system as well as NEC and SGI. Ok on COMPACQ
+   INTERFACE mpp_min
+      MODULE PROCEDURE mppmin_a_int, mppmin_int, mppmin_a_real, mppmin_real
+   END INTERFACE
+   INTERFACE mpp_max
+      MODULE PROCEDURE mppmax_a_int, mppmax_int, mppmax_a_real, mppmax_real
+   END INTERFACE
+   INTERFACE mpp_sum
+      MODULE PROCEDURE mppsum_a_int, mppsum_int, mppsum_a_real, mppsum_real,   &
+         &             mppsum_realdd, mppsum_a_realdd
+   END INTERFACE
+   INTERFACE mpp_minloc
+      MODULE PROCEDURE mpp_minloc2d ,mpp_minloc3d
+   END INTERFACE
+   INTERFACE mpp_maxloc
+      MODULE PROCEDURE mpp_maxloc2d ,mpp_maxloc3d
+   END INTERFACE
+
+   !! ========================= !!
+   !!  MPI  variable definition !!
+   !! ========================= !!
+#if   defined key_mpp_mpi
+!$AGRIF_DO_NOT_TREAT
+   INCLUDE 'mpif.h'
+!$AGRIF_END_DO_NOT_TREAT
+   LOGICAL, PUBLIC, PARAMETER ::   lk_mpp = .TRUE.    !: mpp flag
+#else   
+   INTEGER, PUBLIC, PARAMETER ::   MPI_STATUS_SIZE = 1
+   INTEGER, PUBLIC, PARAMETER ::   MPI_DOUBLE_PRECISION = 8
+   LOGICAL, PUBLIC, PARAMETER ::   lk_mpp = .FALSE.    !: mpp flag
+#endif
+
+   INTEGER, PARAMETER         ::   nprocmax = 2**10   ! maximun dimension (required to be a power of 2)
+
+   INTEGER, PUBLIC ::   mppsize        ! number of process
+   INTEGER, PUBLIC ::   mpprank        ! process number  [ 0 - size-1 ]
+!$AGRIF_DO_NOT_TREAT
+   INTEGER, PUBLIC ::   mpi_comm_oce   ! opa local communicator
+!$AGRIF_END_DO_NOT_TREAT
+
+   INTEGER :: MPI_SUMDD
+
+   ! variables used for zonal integration
+   INTEGER, PUBLIC ::   ncomm_znl       !: communicator made by the processors on the same zonal average
+   LOGICAL, PUBLIC ::   l_znl_root      !: True on the 'left'most processor on the same row
+   INTEGER         ::   ngrp_znl        !  group ID for the znl processors
+   INTEGER         ::   ndim_rank_znl   !  number of processors on the same zonal average
+   INTEGER, DIMENSION(:), ALLOCATABLE, SAVE ::   nrank_znl  ! dimension ndim_rank_znl, number of the procs into the same znl domain
+
+   ! North fold condition in mpp_mpi with jpni > 1 (PUBLIC for TAM)
+   INTEGER, PUBLIC ::   ngrp_world        !: group ID for the world processors
+   INTEGER, PUBLIC ::   ngrp_opa          !: group ID for the opa processors
+   INTEGER, PUBLIC ::   ngrp_north        !: group ID for the northern processors (to be fold)
+   INTEGER, PUBLIC ::   ncomm_north       !: communicator made by the processors belonging to ngrp_north
+   INTEGER, PUBLIC ::   ndim_rank_north   !: number of 'sea' processor in the northern line (can be /= jpni !)
+   INTEGER, PUBLIC ::   njmppmax          !: value of njmpp for the processors of the northern line
+   INTEGER, PUBLIC ::   north_root        !: number (in the comm_opa) of proc 0 in the northern comm
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE, SAVE ::   nrank_north   !: dimension ndim_rank_north
+
+   ! Communications summary report
+   CHARACTER(len=128), DIMENSION(:), ALLOCATABLE ::   crname_lbc                   !: names of lbc_lnk calling routines
+   CHARACTER(len=128), DIMENSION(:), ALLOCATABLE ::   crname_glb                   !: names of global comm calling routines
+   CHARACTER(len=128), DIMENSION(:), ALLOCATABLE ::   crname_dlg                   !: names of delayed global comm calling routines
+   INTEGER, PUBLIC                               ::   ncom_stp = 0                 !: copy of time step # istp
+   INTEGER, PUBLIC                               ::   ncom_fsbc = 1                !: copy of sbc time step # nn_fsbc
+   INTEGER, PUBLIC                               ::   ncom_dttrc = 1               !: copy of top time step # nn_dttrc
+   INTEGER, PUBLIC                               ::   ncom_freq                    !: frequency of comm diagnostic
+   INTEGER, PUBLIC , DIMENSION(:,:), ALLOCATABLE ::   ncomm_sequence               !: size of communicated arrays (halos)
+   INTEGER, PARAMETER, PUBLIC                    ::   ncom_rec_max = 5000          !: max number of communication record
+   INTEGER, PUBLIC                               ::   n_sequence_lbc = 0           !: # of communicated arraysvia lbc
+   INTEGER, PUBLIC                               ::   n_sequence_glb = 0           !: # of global communications
+   INTEGER, PUBLIC                               ::   n_sequence_dlg = 0           !: # of delayed global communications
+   INTEGER, PUBLIC                               ::   numcom = -1                  !: logical unit for communicaton report
+   LOGICAL, PUBLIC                               ::   l_full_nf_update = .TRUE.    !: logical for a full (2lines) update of bc at North fold report
+   INTEGER,                    PARAMETER, PUBLIC ::   nbdelay = 2       !: number of delayed operations
+   !: name (used as id) of allreduce-delayed operations
+   ! Warning: we must use the same character length in an array constructor (at least for gcc compiler)
+   CHARACTER(len=32), DIMENSION(nbdelay), PUBLIC ::   c_delaylist = (/ 'cflice', 'fwb   ' /)
+   !: component name where the allreduce-delayed operation is performed
+   CHARACTER(len=3),  DIMENSION(nbdelay), PUBLIC ::   c_delaycpnt = (/ 'ICE'   , 'OCE' /)
+   TYPE, PUBLIC ::   DELAYARR
+      REAL(   wp), POINTER, DIMENSION(:) ::  z1d => NULL()
+      COMPLEX(wp), POINTER, DIMENSION(:) ::  y1d => NULL()
+   END TYPE DELAYARR
+   TYPE( DELAYARR ), DIMENSION(nbdelay), PUBLIC, SAVE  ::   todelay         !: must have SAVE for default initialization of DELAYARR
+   INTEGER,          DIMENSION(nbdelay), PUBLIC        ::   ndelayid = -1   !: mpi request id of the delayed operations
+
+   ! timing summary report
+   REAL(wp), DIMENSION(2), PUBLIC ::  waiting_time = 0._wp
+   REAL(wp)              , PUBLIC ::  compute_time = 0._wp, elapsed_time = 0._wp
+   
+   REAL(wp), DIMENSION(:), ALLOCATABLE, SAVE ::   tampon   ! buffer in case of bsend
+
+   LOGICAL, PUBLIC ::   ln_nnogather                !: namelist control of northfold comms
+   LOGICAL, PUBLIC ::   l_north_nogather = .FALSE.  !: internal control of northfold comms
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE mpp_start( localComm )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mpp_start  ***
+      !!
+      !! ** Purpose :   get mpi_comm_oce, mpprank and mppsize
+      !!----------------------------------------------------------------------
+      INTEGER         , OPTIONAL   , INTENT(in   ) ::   localComm    !
+      !
+      INTEGER ::   ierr
+      LOGICAL ::   llmpi_init
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      !
+      CALL mpi_initialized ( llmpi_init, ierr )
+      IF( ierr /= MPI_SUCCESS ) CALL ctl_stop( 'STOP', ' lib_mpp: Error in routine mpi_initialized' )
+
+      IF( .NOT. llmpi_init ) THEN
+         IF( PRESENT(localComm) ) THEN
+            WRITE(ctmp1,*) ' lib_mpp: You cannot provide a local communicator '
+            WRITE(ctmp2,*) '          without calling MPI_Init before ! '
+            CALL ctl_stop( 'STOP', ctmp1, ctmp2 )
+         ENDIF
+         CALL mpi_init( ierr )
+         IF( ierr /= MPI_SUCCESS ) CALL ctl_stop( 'STOP', ' lib_mpp: Error in routine mpi_init' )
+      ENDIF
+       
+      IF( PRESENT(localComm) ) THEN
+         IF( Agrif_Root() ) THEN
+            mpi_comm_oce = localComm
+         ENDIF
+      ELSE
+         CALL mpi_comm_dup( mpi_comm_world, mpi_comm_oce, ierr)
+         IF( ierr /= MPI_SUCCESS ) CALL ctl_stop( 'STOP', ' lib_mpp: Error in routine mpi_comm_dup' )
+      ENDIF
+
+# if defined key_agrif
+      IF( Agrif_Root() ) THEN
+         CALL Agrif_MPI_Init(mpi_comm_oce)
+      ELSE
+         CALL Agrif_MPI_set_grid_comm(mpi_comm_oce)
+      ENDIF
+# endif
+
+      CALL mpi_comm_rank( mpi_comm_oce, mpprank, ierr )
+      CALL mpi_comm_size( mpi_comm_oce, mppsize, ierr )
+      !
+      CALL MPI_OP_CREATE(DDPDD_MPI, .TRUE., MPI_SUMDD, ierr)
+      !
+#else
+      IF( PRESENT( localComm ) ) mpi_comm_oce = localComm
+      mppsize = 1
+      mpprank = 0
+#endif
+   END SUBROUTINE mpp_start
+
+
+   SUBROUTINE mppsend( ktyp, pmess, kbytes, kdest, md_req )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mppsend  ***
+      !!
+      !! ** Purpose :   Send messag passing array
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(inout) ::   pmess(*)   ! array of real
+      INTEGER , INTENT(in   ) ::   kbytes     ! size of the array pmess
+      INTEGER , INTENT(in   ) ::   kdest      ! receive process number
+      INTEGER , INTENT(in   ) ::   ktyp       ! tag of the message
+      INTEGER , INTENT(in   ) ::   md_req     ! argument for isend
+      !!
+      INTEGER ::   iflag
+      !!----------------------------------------------------------------------
+      !
+#if defined key_mpp_mpi
+      CALL mpi_isend( pmess, kbytes, mpi_double_precision, kdest , ktyp, mpi_comm_oce, md_req, iflag )
+#endif
+      !
+   END SUBROUTINE mppsend
+
+
+   SUBROUTINE mpprecv( ktyp, pmess, kbytes, ksource )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mpprecv  ***
+      !!
+      !! ** Purpose :   Receive messag passing array
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(inout) ::   pmess(*)   ! array of real
+      INTEGER , INTENT(in   ) ::   kbytes     ! suze of the array pmess
+      INTEGER , INTENT(in   ) ::   ktyp       ! Tag of the recevied message
+      INTEGER, OPTIONAL, INTENT(in) :: ksource    ! source process number
+      !!
+      INTEGER :: istatus(mpi_status_size)
+      INTEGER :: iflag
+      INTEGER :: use_source
+      !!----------------------------------------------------------------------
+      !
+#if defined key_mpp_mpi
+      ! If a specific process number has been passed to the receive call,
+      ! use that one. Default is to use mpi_any_source
+      use_source = mpi_any_source
+      IF( PRESENT(ksource) )   use_source = ksource
+      !
+      CALL mpi_recv( pmess, kbytes, mpi_double_precision, use_source, ktyp, mpi_comm_oce, istatus, iflag )
+#endif
+      !
+   END SUBROUTINE mpprecv
+
+
+   SUBROUTINE mppgather( ptab, kp, pio )
+      !!----------------------------------------------------------------------
+      !!                   ***  routine mppgather  ***
+      !!
+      !! ** Purpose :   Transfert between a local subdomain array and a work
+      !!     array which is distributed following the vertical level.
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)      , INTENT(in   ) ::   ptab   ! subdomain input array
+      INTEGER                           , INTENT(in   ) ::   kp     ! record length
+      REAL(wp), DIMENSION(jpi,jpj,jpnij), INTENT(  out) ::   pio    ! subdomain input array
+      !!
+      INTEGER :: itaille, ierror   ! temporary integer
+      !!---------------------------------------------------------------------
+      !
+      itaille = jpi * jpj
+#if defined key_mpp_mpi
+      CALL mpi_gather( ptab, itaille, mpi_double_precision, pio, itaille     ,   &
+         &                            mpi_double_precision, kp , mpi_comm_oce, ierror )
+#else
+      pio(:,:,1) = ptab(:,:)
+#endif
+      !
+   END SUBROUTINE mppgather
+
+
+   SUBROUTINE mppscatter( pio, kp, ptab )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mppscatter  ***
+      !!
+      !! ** Purpose :   Transfert between awork array which is distributed
+      !!      following the vertical level and the local subdomain array.
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpnij)  ::   pio    ! output array
+      INTEGER                             ::   kp     ! Tag (not used with MPI
+      REAL(wp), DIMENSION(jpi,jpj)        ::   ptab   ! subdomain array input
+      !!
+      INTEGER :: itaille, ierror   ! temporary integer
+      !!---------------------------------------------------------------------
+      !
+      itaille = jpi * jpj
+      !
+#if defined key_mpp_mpi
+      CALL mpi_scatter( pio, itaille, mpi_double_precision, ptab, itaille     ,   &
+         &                            mpi_double_precision, kp  , mpi_comm_oce, ierror )
+#else
+      ptab(:,:) = pio(:,:,1)
+#endif
+      !
+   END SUBROUTINE mppscatter
+
+   
+   SUBROUTINE mpp_delay_sum( cdname, cdelay, y_in, pout, ldlast, kcom )
+     !!----------------------------------------------------------------------
+      !!                   ***  routine mpp_delay_sum  ***
+      !!
+      !! ** Purpose :   performed delayed mpp_sum, the result is received on next call
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   )               ::   cdname  ! name of the calling subroutine
+      CHARACTER(len=*), INTENT(in   )               ::   cdelay  ! name (used as id) of the delayed operation
+      COMPLEX(wp),      INTENT(in   ), DIMENSION(:) ::   y_in
+      REAL(wp),         INTENT(  out), DIMENSION(:) ::   pout
+      LOGICAL,          INTENT(in   )               ::   ldlast  ! true if this is the last time we call this routine
+      INTEGER,          INTENT(in   ), OPTIONAL     ::   kcom
+      !!
+      INTEGER ::   ji, isz
+      INTEGER ::   idvar
+      INTEGER ::   ierr, ilocalcomm
+      COMPLEX(wp), ALLOCATABLE, DIMENSION(:) ::   ytmp
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      ilocalcomm = mpi_comm_oce
+      IF( PRESENT(kcom) )   ilocalcomm = kcom
+
+      isz = SIZE(y_in)
+      
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ld_dlg = .TRUE. )
+
+      idvar = -1
+      DO ji = 1, nbdelay
+         IF( TRIM(cdelay) == TRIM(c_delaylist(ji)) ) idvar = ji
+      END DO
+      IF ( idvar == -1 )   CALL ctl_stop( 'STOP',' mpp_delay_sum : please add a new delayed exchange for '//TRIM(cdname) )
+
+      IF ( ndelayid(idvar) == 0 ) THEN         ! first call    with restart: %z1d defined in iom_delay_rst
+         !                                       --------------------------
+         IF ( SIZE(todelay(idvar)%z1d) /= isz ) THEN                  ! Check dimension coherence
+            IF(lwp) WRITE(numout,*) ' WARNING: the nb of delayed variables in restart file is not the model one'
+            DEALLOCATE(todelay(idvar)%z1d)
+            ndelayid(idvar) = -1                                      ! do as if we had no restart
+         ELSE
+            ALLOCATE(todelay(idvar)%y1d(isz))
+            todelay(idvar)%y1d(:) = CMPLX(todelay(idvar)%z1d(:), 0., wp)   ! create %y1d, complex variable needed by mpi_sumdd
+            ndelayid(idvar) = MPI_REQUEST_NULL                             ! initialised request to a valid value
+         END IF
+      ENDIF
+      
+      IF( ndelayid(idvar) == -1 ) THEN         ! first call without restart: define %y1d and %z1d from y_in with blocking allreduce
+         !                                       --------------------------
+         ALLOCATE(todelay(idvar)%z1d(isz), todelay(idvar)%y1d(isz))   ! allocate also %z1d as used for the restart
+         CALL mpi_allreduce( y_in(:), todelay(idvar)%y1d(:), isz, MPI_DOUBLE_COMPLEX, mpi_sumdd, ilocalcomm, ierr )   ! get %y1d
+         ndelayid(idvar) = MPI_REQUEST_NULL
+      ENDIF
+
+      CALL mpp_delay_rcv( idvar )         ! make sure %z1d is received
+
+      ! send back pout from todelay(idvar)%z1d defined at previous call
+      pout(:) = todelay(idvar)%z1d(:)
+
+      ! send y_in into todelay(idvar)%y1d with a non-blocking communication
+# if defined key_mpi2
+      IF( ln_timing ) CALL tic_tac( .TRUE., ld_global = .TRUE.)
+      CALL  mpi_allreduce( y_in(:), todelay(idvar)%y1d(:), isz, MPI_DOUBLE_COMPLEX, mpi_sumdd, ilocalcomm, ierr )
+      ndelayid(idvar) = MPI_REQUEST_NULL
+      IF( ln_timing ) CALL tic_tac(.FALSE., ld_global = .TRUE.)
+# else
+      CALL mpi_iallreduce( y_in(:), todelay(idvar)%y1d(:), isz, MPI_DOUBLE_COMPLEX, mpi_sumdd, ilocalcomm, ndelayid(idvar), ierr )
+# endif
+#else
+      pout(:) = REAL(y_in(:), wp)
+#endif
+
+   END SUBROUTINE mpp_delay_sum
+
+   
+   SUBROUTINE mpp_delay_max( cdname, cdelay, p_in, pout, ldlast, kcom )
+      !!----------------------------------------------------------------------
+      !!                   ***  routine mpp_delay_max  ***
+      !!
+      !! ** Purpose :   performed delayed mpp_max, the result is received on next call
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   )                 ::   cdname  ! name of the calling subroutine
+      CHARACTER(len=*), INTENT(in   )                 ::   cdelay  ! name (used as id) of the delayed operation
+      REAL(wp),         INTENT(in   ), DIMENSION(:)   ::   p_in    ! 
+      REAL(wp),         INTENT(  out), DIMENSION(:)   ::   pout    ! 
+      LOGICAL,          INTENT(in   )                 ::   ldlast  ! true if this is the last time we call this routine
+      INTEGER,          INTENT(in   ), OPTIONAL       ::   kcom
+      !!
+      INTEGER ::   ji, isz
+      INTEGER ::   idvar
+      INTEGER ::   ierr, ilocalcomm
+      !!----------------------------------------------------------------------
+      
+#if defined key_mpp_mpi
+      ilocalcomm = mpi_comm_oce
+      IF( PRESENT(kcom) )   ilocalcomm = kcom
+
+      isz = SIZE(p_in)
+
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ld_dlg = .TRUE. )
+
+      idvar = -1
+      DO ji = 1, nbdelay
+         IF( TRIM(cdelay) == TRIM(c_delaylist(ji)) ) idvar = ji
+      END DO
+      IF ( idvar == -1 )   CALL ctl_stop( 'STOP',' mpp_delay_max : please add a new delayed exchange for '//TRIM(cdname) )
+
+      IF ( ndelayid(idvar) == 0 ) THEN         ! first call    with restart: %z1d defined in iom_delay_rst
+         !                                       --------------------------
+         IF ( SIZE(todelay(idvar)%z1d) /= isz ) THEN                  ! Check dimension coherence
+            IF(lwp) WRITE(numout,*) ' WARNING: the nb of delayed variables in restart file is not the model one'
+            DEALLOCATE(todelay(idvar)%z1d)
+            ndelayid(idvar) = -1                                      ! do as if we had no restart
+         ELSE
+            ndelayid(idvar) = MPI_REQUEST_NULL
+         END IF
+      ENDIF
+
+      IF( ndelayid(idvar) == -1 ) THEN         ! first call without restart: define %z1d from p_in with a blocking allreduce
+         !                                       --------------------------
+         ALLOCATE(todelay(idvar)%z1d(isz))
+         CALL mpi_allreduce( p_in(:), todelay(idvar)%z1d(:), isz, MPI_DOUBLE_PRECISION, mpi_max, ilocalcomm, ierr )   ! get %z1d
+         ndelayid(idvar) = MPI_REQUEST_NULL
+      ENDIF
+
+      CALL mpp_delay_rcv( idvar )         ! make sure %z1d is received
+
+      ! send back pout from todelay(idvar)%z1d defined at previous call
+      pout(:) = todelay(idvar)%z1d(:)
+
+      ! send p_in into todelay(idvar)%z1d with a non-blocking communication
+      ! (PM) Should we get rid of MPI2 option ? MPI3 was release in 2013. Who is still using MPI2 ?
+# if defined key_mpi2
+      IF( ln_timing ) CALL tic_tac( .TRUE., ld_global = .TRUE.)
+      CALL  mpi_allreduce( p_in(:), todelay(idvar)%z1d(:), isz, MPI_DOUBLE_PRECISION, mpi_max, ilocalcomm, ierr )
+      IF( ln_timing ) CALL tic_tac(.FALSE., ld_global = .TRUE.)
+# else
+      CALL mpi_iallreduce( p_in(:), todelay(idvar)%z1d(:), isz, MPI_DOUBLE_PRECISION, mpi_max, ilocalcomm, ndelayid(idvar), ierr )
+# endif
+#else
+      pout(:) = p_in(:)
+#endif
+
+   END SUBROUTINE mpp_delay_max
+
+   
+   SUBROUTINE mpp_delay_rcv( kid )
+      !!----------------------------------------------------------------------
+      !!                   ***  routine mpp_delay_rcv  ***
+      !!
+      !! ** Purpose :  force barrier for delayed mpp (needed for restart) 
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER,INTENT(in   )      ::  kid 
+      INTEGER ::   ierr
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      IF( ln_timing ) CALL tic_tac( .TRUE., ld_global = .TRUE.)
+      ! test on ndelayid(kid) useless as mpi_wait return immediatly if the request handle is MPI_REQUEST_NULL
+      CALL mpi_wait( ndelayid(kid), MPI_STATUS_IGNORE, ierr ) ! after this ndelayid(kid) = MPI_REQUEST_NULL
+      IF( ln_timing ) CALL tic_tac( .FALSE., ld_global = .TRUE.)
+      IF( ASSOCIATED(todelay(kid)%y1d) )   todelay(kid)%z1d(:) = REAL(todelay(kid)%y1d(:), wp)  ! define %z1d from %y1d
+#endif
+   END SUBROUTINE mpp_delay_rcv
+
+   
+   !!----------------------------------------------------------------------
+   !!    ***  mppmax_a_int, mppmax_int, mppmax_a_real, mppmax_real  ***
+   !!   
+   !!----------------------------------------------------------------------
+   !!
+#  define OPERATION_MAX
+#  define INTEGER_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppmax_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppmax_a_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef INTEGER_TYPE
+!
+#  define REAL_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppmax_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppmax_a_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef REAL_TYPE
+#  undef OPERATION_MAX
+   !!----------------------------------------------------------------------
+   !!    ***  mppmin_a_int, mppmin_int, mppmin_a_real, mppmin_real  ***
+   !!   
+   !!----------------------------------------------------------------------
+   !!
+#  define OPERATION_MIN
+#  define INTEGER_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppmin_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppmin_a_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef INTEGER_TYPE
+!
+#  define REAL_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppmin_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppmin_a_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef REAL_TYPE
+#  undef OPERATION_MIN
+
+   !!----------------------------------------------------------------------
+   !!    ***  mppsum_a_int, mppsum_int, mppsum_a_real, mppsum_real  ***
+   !!   
+   !!   Global sum of 1D array or a variable (integer, real or complex)
+   !!----------------------------------------------------------------------
+   !!
+#  define OPERATION_SUM
+#  define INTEGER_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppsum_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppsum_a_int
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef INTEGER_TYPE
+!
+#  define REAL_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppsum_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppsum_a_real
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef REAL_TYPE
+#  undef OPERATION_SUM
+
+#  define OPERATION_SUM_DD
+#  define COMPLEX_TYPE
+#  define DIM_0d
+#     define ROUTINE_ALLREDUCE           mppsum_realdd
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_0d
+#  define DIM_1d
+#     define ROUTINE_ALLREDUCE           mppsum_a_realdd
+#     include "mpp_allreduce_generic.h90"
+#     undef ROUTINE_ALLREDUCE
+#  undef DIM_1d
+#  undef COMPLEX_TYPE
+#  undef OPERATION_SUM_DD
+
+   !!----------------------------------------------------------------------
+   !!    ***  mpp_minloc2d, mpp_minloc3d, mpp_maxloc2d, mpp_maxloc3d
+   !!   
+   !!----------------------------------------------------------------------
+   !!
+#  define OPERATION_MINLOC
+#  define DIM_2d
+#     define ROUTINE_LOC           mpp_minloc2d
+#     include "mpp_loc_generic.h90"
+#     undef ROUTINE_LOC
+#  undef DIM_2d
+#  define DIM_3d
+#     define ROUTINE_LOC           mpp_minloc3d
+#     include "mpp_loc_generic.h90"
+#     undef ROUTINE_LOC
+#  undef DIM_3d
+#  undef OPERATION_MINLOC
+
+#  define OPERATION_MAXLOC
+#  define DIM_2d
+#     define ROUTINE_LOC           mpp_maxloc2d
+#     include "mpp_loc_generic.h90"
+#     undef ROUTINE_LOC
+#  undef DIM_2d
+#  define DIM_3d
+#     define ROUTINE_LOC           mpp_maxloc3d
+#     include "mpp_loc_generic.h90"
+#     undef ROUTINE_LOC
+#  undef DIM_3d
+#  undef OPERATION_MAXLOC
+
+   SUBROUTINE mppsync()
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mppsync  ***
+      !!
+      !! ** Purpose :   Massively parallel processors, synchroneous
+      !!
+      !!-----------------------------------------------------------------------
+      INTEGER :: ierror
+      !!-----------------------------------------------------------------------
+      !
+#if defined key_mpp_mpi
+      CALL mpi_barrier( mpi_comm_oce, ierror )
+#endif
+      !
+   END SUBROUTINE mppsync
+
+
+   SUBROUTINE mppstop( ld_abort ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mppstop  ***
+      !!
+      !! ** purpose :   Stop massively parallel processors method
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL, OPTIONAL, INTENT(in) :: ld_abort    ! source process number
+      LOGICAL ::   ll_abort
+      INTEGER ::   info
+      !!----------------------------------------------------------------------
+      ll_abort = .FALSE.
+      IF( PRESENT(ld_abort) ) ll_abort = ld_abort
+      !
+#if defined key_mpp_mpi
+      IF(ll_abort) THEN
+         CALL mpi_abort( MPI_COMM_WORLD )
+      ELSE
+         CALL mppsync
+         CALL mpi_finalize( info )
+      ENDIF
+#endif
+      IF( ll_abort ) STOP 123
+      !
+   END SUBROUTINE mppstop
+
+
+   SUBROUTINE mpp_comm_free( kcom )
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kcom
+      !!
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+#if defined key_mpp_mpi
+      CALL MPI_COMM_FREE(kcom, ierr)
+#endif
+      !
+   END SUBROUTINE mpp_comm_free
+
+
+   SUBROUTINE mpp_ini_znl( kumout )
+      !!----------------------------------------------------------------------
+      !!               ***  routine mpp_ini_znl  ***
+      !!
+      !! ** Purpose :   Initialize special communicator for computing zonal sum
+      !!
+      !! ** Method  : - Look for processors in the same row
+      !!              - Put their number in nrank_znl
+      !!              - Create group for the znl processors
+      !!              - Create a communicator for znl processors
+      !!              - Determine if processor should write znl files
+      !!
+      !! ** output
+      !!      ndim_rank_znl = number of processors on the same row
+      !!      ngrp_znl = group ID for the znl processors
+      !!      ncomm_znl = communicator for the ice procs.
+      !!      n_znl_root = number (in the world) of proc 0 in the ice comm.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kumout   ! ocean.output logical units
+      !
+      INTEGER :: jproc      ! dummy loop integer
+      INTEGER :: ierr, ii   ! local integer
+      INTEGER, ALLOCATABLE, DIMENSION(:) ::   kwork
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      !-$$     WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - ngrp_world     : ', ngrp_world
+      !-$$     WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - mpi_comm_world : ', mpi_comm_world
+      !-$$     WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - mpi_comm_oce   : ', mpi_comm_oce
+      !
+      ALLOCATE( kwork(jpnij), STAT=ierr )
+      IF( ierr /= 0 ) CALL ctl_stop( 'STOP', 'mpp_ini_znl : failed to allocate 1D array of length jpnij')
+
+      IF( jpnj == 1 ) THEN
+         ngrp_znl  = ngrp_world
+         ncomm_znl = mpi_comm_oce
+      ELSE
+         !
+         CALL MPI_ALLGATHER ( njmpp, 1, mpi_integer, kwork, 1, mpi_integer, mpi_comm_oce, ierr )
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - kwork pour njmpp : ', kwork
+         !-$$        CALL flush(numout)
+         !
+         ! Count number of processors on the same row
+         ndim_rank_znl = 0
+         DO jproc=1,jpnij
+            IF ( kwork(jproc) == njmpp ) THEN
+               ndim_rank_znl = ndim_rank_znl + 1
+            ENDIF
+         END DO
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - ndim_rank_znl : ', ndim_rank_znl
+         !-$$        CALL flush(numout)
+         ! Allocate the right size to nrank_znl
+         IF (ALLOCATED (nrank_znl)) DEALLOCATE(nrank_znl)
+         ALLOCATE(nrank_znl(ndim_rank_znl))
+         ii = 0
+         nrank_znl (:) = 0
+         DO jproc=1,jpnij
+            IF ( kwork(jproc) == njmpp) THEN
+               ii = ii + 1
+               nrank_znl(ii) = jproc -1
+            ENDIF
+         END DO
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - nrank_znl : ', nrank_znl
+         !-$$        CALL flush(numout)
+
+         ! Create the opa group
+         CALL MPI_COMM_GROUP(mpi_comm_oce,ngrp_opa,ierr)
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - ngrp_opa : ', ngrp_opa
+         !-$$        CALL flush(numout)
+
+         ! Create the znl group from the opa group
+         CALL MPI_GROUP_INCL  ( ngrp_opa, ndim_rank_znl, nrank_znl, ngrp_znl, ierr )
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - ngrp_znl ', ngrp_znl
+         !-$$        CALL flush(numout)
+
+         ! Create the znl communicator from the opa communicator, ie the pool of procs in the same row
+         CALL MPI_COMM_CREATE ( mpi_comm_oce, ngrp_znl, ncomm_znl, ierr )
+         !-$$        WRITE (numout,*) 'mpp_ini_znl ', nproc, ' - ncomm_znl ', ncomm_znl
+         !-$$        CALL flush(numout)
+         !
+      END IF
+
+      ! Determines if processor if the first (starting from i=1) on the row
+      IF ( jpni == 1 ) THEN
+         l_znl_root = .TRUE.
+      ELSE
+         l_znl_root = .FALSE.
+         kwork (1) = nimpp
+         CALL mpp_min ( 'lib_mpp', kwork(1), kcom = ncomm_znl)
+         IF ( nimpp == kwork(1)) l_znl_root = .TRUE.
+      END IF
+
+      DEALLOCATE(kwork)
+#endif
+
+   END SUBROUTINE mpp_ini_znl
+
+
+   SUBROUTINE mpp_ini_north
+      !!----------------------------------------------------------------------
+      !!               ***  routine mpp_ini_north  ***
+      !!
+      !! ** Purpose :   Initialize special communicator for north folding
+      !!      condition together with global variables needed in the mpp folding
+      !!
+      !! ** Method  : - Look for northern processors
+      !!              - Put their number in nrank_north
+      !!              - Create groups for the world processors and the north processors
+      !!              - Create a communicator for northern processors
+      !!
+      !! ** output
+      !!      njmppmax = njmpp for northern procs
+      !!      ndim_rank_north = number of processors in the northern line
+      !!      nrank_north (ndim_rank_north) = number  of the northern procs.
+      !!      ngrp_world = group ID for the world processors
+      !!      ngrp_north = group ID for the northern processors
+      !!      ncomm_north = communicator for the northern procs.
+      !!      north_root = number (in the world) of proc 0 in the northern comm.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ierr
+      INTEGER ::   jjproc
+      INTEGER ::   ii, ji
+      !!----------------------------------------------------------------------
+      !
+#if defined key_mpp_mpi
+      njmppmax = MAXVAL( njmppt )
+      !
+      ! Look for how many procs on the northern boundary
+      ndim_rank_north = 0
+      DO jjproc = 1, jpnij
+         IF( njmppt(jjproc) == njmppmax )   ndim_rank_north = ndim_rank_north + 1
+      END DO
+      !
+      ! Allocate the right size to nrank_north
+      IF (ALLOCATED (nrank_north)) DEALLOCATE(nrank_north)
+      ALLOCATE( nrank_north(ndim_rank_north) )
+
+      ! Fill the nrank_north array with proc. number of northern procs.
+      ! Note : the rank start at 0 in MPI
+      ii = 0
+      DO ji = 1, jpnij
+         IF ( njmppt(ji) == njmppmax   ) THEN
+            ii=ii+1
+            nrank_north(ii)=ji-1
+         END IF
+      END DO
+      !
+      ! create the world group
+      CALL MPI_COMM_GROUP( mpi_comm_oce, ngrp_world, ierr )
+      !
+      ! Create the North group from the world group
+      CALL MPI_GROUP_INCL( ngrp_world, ndim_rank_north, nrank_north, ngrp_north, ierr )
+      !
+      ! Create the North communicator , ie the pool of procs in the north group
+      CALL MPI_COMM_CREATE( mpi_comm_oce, ngrp_north, ncomm_north, ierr )
+      !
+#endif
+   END SUBROUTINE mpp_ini_north
+
+
+   SUBROUTINE DDPDD_MPI( ydda, yddb, ilen, itype )
+      !!---------------------------------------------------------------------
+      !!   Routine DDPDD_MPI: used by reduction operator MPI_SUMDD
+      !!
+      !!   Modification of original codes written by David H. Bailey
+      !!   This subroutine computes yddb(i) = ydda(i)+yddb(i)
+      !!---------------------------------------------------------------------
+      INTEGER                     , INTENT(in)    ::   ilen, itype
+      COMPLEX(wp), DIMENSION(ilen), INTENT(in)    ::   ydda
+      COMPLEX(wp), DIMENSION(ilen), INTENT(inout) ::   yddb
+      !
+      REAL(wp) :: zerr, zt1, zt2    ! local work variables
+      INTEGER  :: ji, ztmp           ! local scalar
+      !!---------------------------------------------------------------------
+      !
+      ztmp = itype   ! avoid compilation warning
+      !
+      DO ji=1,ilen
+      ! Compute ydda + yddb using Knuth's trick.
+         zt1  = real(ydda(ji)) + real(yddb(ji))
+         zerr = zt1 - real(ydda(ji))
+         zt2  = ((real(yddb(ji)) - zerr) + (real(ydda(ji)) - (zt1 - zerr))) &
+                + aimag(ydda(ji)) + aimag(yddb(ji))
+
+         ! The result is zt1 + zt2, after normalization.
+         yddb(ji) = cmplx ( zt1 + zt2, zt2 - ((zt1 + zt2) - zt1),wp )
+      END DO
+      !
+   END SUBROUTINE DDPDD_MPI
+
+
+   SUBROUTINE mpp_report( cdname, kpk, kpl, kpf, ld_lbc, ld_glb, ld_dlg )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mpp_report  ***
+      !!
+      !! ** Purpose :   report use of mpp routines per time-setp
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),           INTENT(in   ) ::   cdname      ! name of the calling subroutine
+      INTEGER         , OPTIONAL, INTENT(in   ) ::   kpk, kpl, kpf
+      LOGICAL         , OPTIONAL, INTENT(in   ) ::   ld_lbc, ld_glb, ld_dlg
+      !!
+      CHARACTER(len=128)                        ::   ccountname  ! name of a subroutine to count communications
+      LOGICAL ::   ll_lbc, ll_glb, ll_dlg
+      INTEGER ::    ji,  jj,  jk,  jh, jf, jcount   ! dummy loop indices
+      !!----------------------------------------------------------------------
+#if defined key_mpp_mpi
+      !
+      ll_lbc = .FALSE.
+      IF( PRESENT(ld_lbc) ) ll_lbc = ld_lbc
+      ll_glb = .FALSE.
+      IF( PRESENT(ld_glb) ) ll_glb = ld_glb
+      ll_dlg = .FALSE.
+      IF( PRESENT(ld_dlg) ) ll_dlg = ld_dlg
+      !
+      ! find the smallest common frequency: default = frequency product, if multiple, choose the larger of the 2 frequency
+      IF( ncom_dttrc /= 1 )   CALL ctl_stop( 'STOP', 'mpp_report, ncom_dttrc /= 1 not coded...' ) 
+      ncom_freq = ncom_fsbc
+      !
+      IF ( ncom_stp == nit000+ncom_freq ) THEN   ! avoid to count extra communications in potential initializations at nit000
+         IF( ll_lbc ) THEN
+            IF( .NOT. ALLOCATED(ncomm_sequence) ) ALLOCATE( ncomm_sequence(ncom_rec_max,2) )
+            IF( .NOT. ALLOCATED(    crname_lbc) ) ALLOCATE(     crname_lbc(ncom_rec_max  ) )
+            n_sequence_lbc = n_sequence_lbc + 1
+            IF( n_sequence_lbc > ncom_rec_max ) CALL ctl_stop( 'STOP', 'lib_mpp, increase ncom_rec_max' )   ! deadlock
+            crname_lbc(n_sequence_lbc) = cdname     ! keep the name of the calling routine
+            ncomm_sequence(n_sequence_lbc,1) = kpk*kpl   ! size of 3rd and 4th dimensions
+            ncomm_sequence(n_sequence_lbc,2) = kpf       ! number of arrays to be treated (multi)
+         ENDIF
+         IF( ll_glb ) THEN
+            IF( .NOT. ALLOCATED(crname_glb) ) ALLOCATE( crname_glb(ncom_rec_max) )
+            n_sequence_glb = n_sequence_glb + 1
+            IF( n_sequence_glb > ncom_rec_max ) CALL ctl_stop( 'STOP', 'lib_mpp, increase ncom_rec_max' )   ! deadlock
+            crname_glb(n_sequence_glb) = cdname     ! keep the name of the calling routine
+         ENDIF
+         IF( ll_dlg ) THEN
+            IF( .NOT. ALLOCATED(crname_dlg) ) ALLOCATE( crname_dlg(ncom_rec_max) )
+            n_sequence_dlg = n_sequence_dlg + 1
+            IF( n_sequence_dlg > ncom_rec_max ) CALL ctl_stop( 'STOP', 'lib_mpp, increase ncom_rec_max' )   ! deadlock
+            crname_dlg(n_sequence_dlg) = cdname     ! keep the name of the calling routine
+         ENDIF
+      ELSE IF ( ncom_stp == nit000+2*ncom_freq ) THEN
+         CALL ctl_opn( numcom, 'communication_report.txt', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., narea )
+         WRITE(numcom,*) ' '
+         WRITE(numcom,*) ' ------------------------------------------------------------'
+         WRITE(numcom,*) ' Communication pattern report (second oce+sbc+top time step):'
+         WRITE(numcom,*) ' ------------------------------------------------------------'
+         WRITE(numcom,*) ' '
+         WRITE(numcom,'(A,I4)') ' Exchanged halos : ', n_sequence_lbc
+         jj = 0; jk = 0; jf = 0; jh = 0
+         DO ji = 1, n_sequence_lbc
+            IF ( ncomm_sequence(ji,1) .GT. 1 ) jk = jk + 1
+            IF ( ncomm_sequence(ji,2) .GT. 1 ) jf = jf + 1
+            IF ( ncomm_sequence(ji,1) .GT. 1 .AND. ncomm_sequence(ji,2) .GT. 1 ) jj = jj + 1
+            jh = MAX (jh, ncomm_sequence(ji,1)*ncomm_sequence(ji,2))
+         END DO
+         WRITE(numcom,'(A,I3)') ' 3D Exchanged halos : ', jk
+         WRITE(numcom,'(A,I3)') ' Multi arrays exchanged halos : ', jf
+         WRITE(numcom,'(A,I3)') '   from which 3D : ', jj
+         WRITE(numcom,'(A,I10)') ' Array max size : ', jh*jpi*jpj
+         WRITE(numcom,*) ' '
+         WRITE(numcom,*) ' lbc_lnk called'
+         DO ji = 1, n_sequence_lbc - 1
+            IF ( crname_lbc(ji) /= 'already counted' ) THEN
+               ccountname = crname_lbc(ji)
+               crname_lbc(ji) = 'already counted'
+               jcount = 1
+               DO jj = ji + 1, n_sequence_lbc
+                  IF ( ccountname ==  crname_lbc(jj) ) THEN
+                     jcount = jcount + 1
+                     crname_lbc(jj) = 'already counted'
+                  END IF
+               END DO
+               WRITE(numcom,'(A, I4, A, A)') ' - ', jcount,' times by subroutine ', TRIM(ccountname)
+            END IF
+         END DO
+         IF ( crname_lbc(n_sequence_lbc) /= 'already counted' ) THEN
+            WRITE(numcom,'(A, I4, A, A)') ' - ', 1,' times by subroutine ', TRIM(crname_lbc(ncom_rec_max))
+         END IF
+         WRITE(numcom,*) ' '
+         IF ( n_sequence_glb > 0 ) THEN
+            WRITE(numcom,'(A,I4)') ' Global communications : ', n_sequence_glb
+            jj = 1
+            DO ji = 2, n_sequence_glb
+               IF( crname_glb(ji-1) /= crname_glb(ji) ) THEN
+                  WRITE(numcom,'(A, I4, A, A)') ' - ', jj,' times by subroutine ', TRIM(crname_glb(ji-1))
+                  jj = 0
+               END IF
+               jj = jj + 1 
+            END DO
+            WRITE(numcom,'(A, I4, A, A)') ' - ', jj,' times by subroutine ', TRIM(crname_glb(n_sequence_glb))
+            DEALLOCATE(crname_glb)
+         ELSE
+            WRITE(numcom,*) ' No MPI global communication '
+         ENDIF
+         WRITE(numcom,*) ' '
+         IF ( n_sequence_dlg > 0 ) THEN
+            WRITE(numcom,'(A,I4)') ' Delayed global communications : ', n_sequence_dlg
+            jj = 1
+            DO ji = 2, n_sequence_dlg
+               IF( crname_dlg(ji-1) /= crname_dlg(ji) ) THEN
+                  WRITE(numcom,'(A, I4, A, A)') ' - ', jj,' times by subroutine ', TRIM(crname_dlg(ji-1))
+                  jj = 0
+               END IF
+               jj = jj + 1 
+            END DO
+            WRITE(numcom,'(A, I4, A, A)') ' - ', jj,' times by subroutine ', TRIM(crname_dlg(n_sequence_dlg))
+            DEALLOCATE(crname_dlg)
+         ELSE
+            WRITE(numcom,*) ' No MPI delayed global communication '
+         ENDIF
+         WRITE(numcom,*) ' '
+         WRITE(numcom,*) ' -----------------------------------------------'
+         WRITE(numcom,*) ' '
+         DEALLOCATE(ncomm_sequence)
+         DEALLOCATE(crname_lbc)
+      ENDIF
+#endif
+   END SUBROUTINE mpp_report
+
+   
+   SUBROUTINE tic_tac (ld_tic, ld_global)
+
+    LOGICAL,           INTENT(IN) :: ld_tic
+    LOGICAL, OPTIONAL, INTENT(IN) :: ld_global
+    REAL(wp), DIMENSION(2), SAVE :: tic_wt
+    REAL(wp),               SAVE :: tic_ct = 0._wp
+    INTEGER :: ii
+#if defined key_mpp_mpi
+
+    IF( ncom_stp <= nit000 ) RETURN
+    IF( ncom_stp == nitend ) RETURN
+    ii = 1
+    IF( PRESENT( ld_global ) ) THEN
+       IF( ld_global ) ii = 2
+    END IF
+    
+    IF ( ld_tic ) THEN
+       tic_wt(ii) = MPI_Wtime()                                                    ! start count tic->tac (waiting time)
+       IF ( tic_ct > 0.0_wp ) compute_time = compute_time + MPI_Wtime() - tic_ct   ! cumulate count tac->tic
+    ELSE
+       waiting_time(ii) = waiting_time(ii) + MPI_Wtime() - tic_wt(ii)              ! cumulate count tic->tac
+       tic_ct = MPI_Wtime()                                                        ! start count tac->tic (waiting time)
+    ENDIF
+#endif
+    
+   END SUBROUTINE tic_tac
+
+#if ! defined key_mpp_mpi
+   SUBROUTINE mpi_wait(request, status, ierror)
+      INTEGER                            , INTENT(in   ) ::   request
+      INTEGER, DIMENSION(MPI_STATUS_SIZE), INTENT(  out) ::   status
+      INTEGER                            , INTENT(  out) ::   ierror
+   END SUBROUTINE mpi_wait
+
+   
+   FUNCTION MPI_Wtime()
+      REAL(wp) ::  MPI_Wtime
+      MPI_Wtime = -1.
+   END FUNCTION MPI_Wtime
+#endif
+
+   !!----------------------------------------------------------------------
+   !!   ctl_stop, ctl_warn, get_unit, ctl_opn, ctl_nam   routines
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE ctl_stop( cd1, cd2, cd3, cd4, cd5 ,   &
+      &                 cd6, cd7, cd8, cd9, cd10 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE  stop_opa  ***
+      !!
+      !! ** Purpose :   print in ocean.outpput file a error message and
+      !!                increment the error number (nstop) by one.
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   )           ::   cd1
+      CHARACTER(len=*), INTENT(in   ), OPTIONAL ::        cd2, cd3, cd4, cd5
+      CHARACTER(len=*), INTENT(in   ), OPTIONAL ::   cd6, cd7, cd8, cd9, cd10
+      !
+      INTEGER ::   inum
+      !!----------------------------------------------------------------------
+      !
+      nstop = nstop + 1
+      !
+      IF( cd1 == 'STOP' .AND. narea /= 1 ) THEN    ! Immediate stop: add an arror message in 'ocean.output' file
+         CALL ctl_opn( inum, 'ocean.output', 'APPEND', 'FORMATTED', 'SEQUENTIAL', -1, 6, .FALSE. )
+         WRITE(inum,*)
+         WRITE(inum,*) ' ==>>>   Look for "E R R O R" messages in all existing *ocean.output* files'
+         CLOSE(inum)
+      ENDIF
+      IF( numout == 6 ) THEN                       ! force to open ocean.output file if not already opened
+         CALL ctl_opn( numout, 'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE., narea )
+      ENDIF
+      !
+                            WRITE(numout,*)
+                            WRITE(numout,*) ' ===>>> : E R R O R'
+                            WRITE(numout,*)
+                            WRITE(numout,*) '         ==========='
+                            WRITE(numout,*)
+                            WRITE(numout,*) TRIM(cd1)
+      IF( PRESENT(cd2 ) )   WRITE(numout,*) TRIM(cd2)
+      IF( PRESENT(cd3 ) )   WRITE(numout,*) TRIM(cd3)
+      IF( PRESENT(cd4 ) )   WRITE(numout,*) TRIM(cd4)
+      IF( PRESENT(cd5 ) )   WRITE(numout,*) TRIM(cd5)
+      IF( PRESENT(cd6 ) )   WRITE(numout,*) TRIM(cd6)
+      IF( PRESENT(cd7 ) )   WRITE(numout,*) TRIM(cd7)
+      IF( PRESENT(cd8 ) )   WRITE(numout,*) TRIM(cd8)
+      IF( PRESENT(cd9 ) )   WRITE(numout,*) TRIM(cd9)
+      IF( PRESENT(cd10) )   WRITE(numout,*) TRIM(cd10)
+                            WRITE(numout,*)
+      !
+                               CALL FLUSH(numout    )
+      IF( numstp     /= -1 )   CALL FLUSH(numstp    )
+      IF( numrun     /= -1 )   CALL FLUSH(numrun    )
+      IF( numevo_ice /= -1 )   CALL FLUSH(numevo_ice)
+      !
+      IF( cd1 == 'STOP' ) THEN
+         WRITE(numout,*)  
+         WRITE(numout,*)  'huge E-R-R-O-R : immediate stop'
+         WRITE(numout,*)  
+         CALL FLUSH(numout)
+         CALL SLEEP(60)   ! make sure that all output and abort files are written by all cores. 60s should be enough...
+         CALL mppstop( ld_abort = .true. )
+      ENDIF
+      !
+   END SUBROUTINE ctl_stop
+
+
+   SUBROUTINE ctl_warn( cd1, cd2, cd3, cd4, cd5,   &
+      &                 cd6, cd7, cd8, cd9, cd10 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE  stop_warn  ***
+      !!
+      !! ** Purpose :   print in ocean.outpput file a error message and
+      !!                increment the warning number (nwarn) by one.
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in), OPTIONAL ::  cd1, cd2, cd3, cd4, cd5
+      CHARACTER(len=*), INTENT(in), OPTIONAL ::  cd6, cd7, cd8, cd9, cd10
+      !!----------------------------------------------------------------------
+      !
+      nwarn = nwarn + 1
+      !
+      IF(lwp) THEN
+                               WRITE(numout,*)
+                               WRITE(numout,*) ' ===>>> : W A R N I N G'
+                               WRITE(numout,*)
+                               WRITE(numout,*) '         ==============='
+                               WRITE(numout,*)
+         IF( PRESENT(cd1 ) )   WRITE(numout,*) TRIM(cd1)
+         IF( PRESENT(cd2 ) )   WRITE(numout,*) TRIM(cd2)
+         IF( PRESENT(cd3 ) )   WRITE(numout,*) TRIM(cd3)
+         IF( PRESENT(cd4 ) )   WRITE(numout,*) TRIM(cd4)
+         IF( PRESENT(cd5 ) )   WRITE(numout,*) TRIM(cd5)
+         IF( PRESENT(cd6 ) )   WRITE(numout,*) TRIM(cd6)
+         IF( PRESENT(cd7 ) )   WRITE(numout,*) TRIM(cd7)
+         IF( PRESENT(cd8 ) )   WRITE(numout,*) TRIM(cd8)
+         IF( PRESENT(cd9 ) )   WRITE(numout,*) TRIM(cd9)
+         IF( PRESENT(cd10) )   WRITE(numout,*) TRIM(cd10)
+                               WRITE(numout,*)
+      ENDIF
+      CALL FLUSH(numout)
+      !
+   END SUBROUTINE ctl_warn
+
+
+   SUBROUTINE ctl_opn( knum, cdfile, cdstat, cdform, cdacce, klengh, kout, ldwp, karea )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ctl_opn  ***
+      !!
+      !! ** Purpose :   Open file and check if required file is available.
+      !!
+      !! ** Method  :   Fortan open
+      !!----------------------------------------------------------------------
+      INTEGER          , INTENT(  out) ::   knum      ! logical unit to open
+      CHARACTER(len=*) , INTENT(in   ) ::   cdfile    ! file name to open
+      CHARACTER(len=*) , INTENT(in   ) ::   cdstat    ! disposition specifier
+      CHARACTER(len=*) , INTENT(in   ) ::   cdform    ! formatting specifier
+      CHARACTER(len=*) , INTENT(in   ) ::   cdacce    ! access specifier
+      INTEGER          , INTENT(in   ) ::   klengh    ! record length
+      INTEGER          , INTENT(in   ) ::   kout      ! number of logical units for write
+      LOGICAL          , INTENT(in   ) ::   ldwp      ! boolean term for print
+      INTEGER, OPTIONAL, INTENT(in   ) ::   karea     ! proc number
+      !
+      CHARACTER(len=80) ::   clfile
+      CHARACTER(LEN=10) ::   clfmt            ! writing format
+      INTEGER           ::   iost
+      INTEGER           ::   idg              ! number of digits
+      !!----------------------------------------------------------------------
+      !
+      ! adapt filename
+      ! ----------------
+      clfile = TRIM(cdfile)
+      IF( PRESENT( karea ) ) THEN
+         IF( karea > 1 ) THEN
+            ! Warning: jpnij is maybe not already defined when calling ctl_opn -> use mppsize instead of jpnij
+            idg = MAX( INT(LOG10(REAL(MAX(1,mppsize-1),wp))) + 1, 4 )      ! how many digits to we need to write? min=4, max=9
+            WRITE(clfmt, "('(a,a,i', i1, '.', i1, ')')") idg, idg          ! '(a,a,ix.x)'
+            WRITE(clfile, clfmt) TRIM(clfile), '_', karea-1
+         ENDIF
+      ENDIF
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() )   clfile = TRIM(Agrif_CFixed())//'_'//TRIM(clfile)
+      knum=Agrif_Get_Unit()
+#else
+      knum=get_unit()
+#endif
+      IF( TRIM(cdfile) == '/dev/null' )   clfile = TRIM(cdfile)   ! force the use of /dev/null
+      !
+      IF(       cdacce(1:6) == 'DIRECT' )  THEN   ! cdacce has always more than 6 characters
+         OPEN( UNIT=knum, FILE=clfile, FORM=cdform, ACCESS=cdacce, STATUS=cdstat, RECL=klengh         , ERR=100, IOSTAT=iost )
+      ELSE IF( TRIM(cdstat) == 'APPEND' )  THEN   ! cdstat can have less than 6 characters
+         OPEN( UNIT=knum, FILE=clfile, FORM=cdform, ACCESS=cdacce, STATUS='UNKNOWN', POSITION='APPEND', ERR=100, IOSTAT=iost )
+      ELSE
+         OPEN( UNIT=knum, FILE=clfile, FORM=cdform, ACCESS=cdacce, STATUS=cdstat                      , ERR=100, IOSTAT=iost )
+      ENDIF
+      IF( iost /= 0 .AND. TRIM(clfile) == '/dev/null' ) &   ! for windows
+         &  OPEN(UNIT=knum,FILE='NUL', FORM=cdform, ACCESS=cdacce, STATUS=cdstat                      , ERR=100, IOSTAT=iost )   
+      IF( iost == 0 ) THEN
+         IF(ldwp .AND. kout > 0) THEN
+            WRITE(kout,*) '     file   : ', TRIM(clfile),' open ok'
+            WRITE(kout,*) '     unit   = ', knum
+            WRITE(kout,*) '     status = ', cdstat
+            WRITE(kout,*) '     form   = ', cdform
+            WRITE(kout,*) '     access = ', cdacce
+            WRITE(kout,*)
+         ENDIF
+      ENDIF
+100   CONTINUE
+      IF( iost /= 0 ) THEN
+         WRITE(ctmp1,*) ' ===>>>> : bad opening file: ', TRIM(clfile)
+         WRITE(ctmp2,*) ' =======   ===  '
+         WRITE(ctmp3,*) '           unit   = ', knum
+         WRITE(ctmp4,*) '           status = ', cdstat
+         WRITE(ctmp5,*) '           form   = ', cdform
+         WRITE(ctmp6,*) '           access = ', cdacce
+         WRITE(ctmp7,*) '           iostat = ', iost
+         WRITE(ctmp8,*) '           we stop. verify the file '
+         CALL ctl_stop( 'STOP', ctmp1, ctmp2, ctmp3, ctmp4, ctmp5, ctmp6, ctmp7, ctmp8 )
+      ENDIF
+      !
+   END SUBROUTINE ctl_opn
+
+
+   SUBROUTINE ctl_nam ( kios, cdnam )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ctl_nam  ***
+      !!
+      !! ** Purpose :   Informations when error while reading a namelist
+      !!
+      !! ** Method  :   Fortan open
+      !!----------------------------------------------------------------------
+      INTEGER                                , INTENT(inout) ::   kios    ! IO status after reading the namelist
+      CHARACTER(len=*)                       , INTENT(in   ) ::   cdnam   ! group name of namelist for which error occurs
+      !
+      CHARACTER(len=5) ::   clios   ! string to convert iostat in character for print
+      !!----------------------------------------------------------------------
+      !
+      WRITE (clios, '(I5.0)')   kios
+      IF( kios < 0 ) THEN         
+         CALL ctl_warn( 'end of record or file while reading namelist '   &
+            &           // TRIM(cdnam) // ' iostat = ' // TRIM(clios) )
+      ENDIF
+      !
+      IF( kios > 0 ) THEN
+         CALL ctl_stop( 'misspelled variable in namelist '   &
+            &           // TRIM(cdnam) // ' iostat = ' // TRIM(clios) )
+      ENDIF
+      kios = 0
+      !
+   END SUBROUTINE ctl_nam
+
+
+   INTEGER FUNCTION get_unit()
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION  get_unit  ***
+      !!
+      !! ** Purpose :   return the index of an unused logical unit
+      !!----------------------------------------------------------------------
+      LOGICAL :: llopn
+      !!----------------------------------------------------------------------
+      !
+      get_unit = 15   ! choose a unit that is big enough then it is not already used in NEMO
+      llopn = .TRUE.
+      DO WHILE( (get_unit < 998) .AND. llopn )
+         get_unit = get_unit + 1
+         INQUIRE( unit = get_unit, opened = llopn )
+      END DO
+      IF( (get_unit == 999) .AND. llopn ) THEN
+         CALL ctl_stop( 'STOP', 'get_unit: All logical units until 999 are used...' )
+      ENDIF
+      !
+   END FUNCTION get_unit
+
+   !!----------------------------------------------------------------------
+END MODULE lib_mpp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_allreduce_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_allreduce_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_allreduce_generic.h90	(revision 14097)
@@ -0,0 +1,82 @@
+!                          !==  IN: ptab is an array  ==!
+#   if defined REAL_TYPE
+#      define ARRAY_TYPE(i)    REAL(wp)         , INTENT(inout) ::   ARRAY_IN(i)
+#      define TMP_TYPE(i)      REAL(wp)         , ALLOCATABLE   ::   work(i)
+#      define MPI_TYPE mpi_double_precision
+#   endif
+#   if defined INTEGER_TYPE
+#      define ARRAY_TYPE(i)    INTEGER          , INTENT(inout) ::   ARRAY_IN(i)
+#      define TMP_TYPE(i)      INTEGER          , ALLOCATABLE   ::   work(i)
+#      define MPI_TYPE mpi_integer
+#   endif
+#   if defined COMPLEX_TYPE
+#      define ARRAY_TYPE(i)    COMPLEX          , INTENT(inout) ::   ARRAY_IN(i)
+#      define TMP_TYPE(i)      COMPLEX          , ALLOCATABLE   ::   work(i)
+#      define MPI_TYPE mpi_double_complex
+#   endif
+#   if defined DIM_0d
+#      define ARRAY_IN(i)   ptab
+#      define I_SIZE(ptab)          1
+#   endif
+#   if defined DIM_1d
+#      define ARRAY_IN(i)   ptab(i)
+#      define I_SIZE(ptab)          SIZE(ptab,1)
+#   endif
+#   if defined OPERATION_MAX
+#      define MPI_OPERATION mpi_max
+#   endif
+#   if defined OPERATION_MIN
+#      define MPI_OPERATION mpi_min
+#   endif
+#   if defined OPERATION_SUM
+#      define MPI_OPERATION mpi_sum
+#   endif
+#   if defined OPERATION_SUM_DD
+#      define MPI_OPERATION mpi_sumdd
+#   endif
+
+   SUBROUTINE ROUTINE_ALLREDUCE( cdname, ptab, kdim, kcom )
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),                   INTENT(in   ) ::   cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:)   ! array or pointer of arrays on which the boundary condition is applied
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kdim        ! optional pointer dimension
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kcom        ! optional communicator
+#if defined key_mpp_mpi
+      !
+      INTEGER :: ipi, ii, ierr
+      INTEGER :: ierror, ilocalcomm
+      TMP_TYPE(:)
+      !!-----------------------------------------------------------------------
+      !
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ld_glb = .TRUE. )
+      !
+      ilocalcomm = mpi_comm_oce
+      IF( PRESENT(kcom) )   ilocalcomm = kcom
+      !
+      IF( PRESENT(kdim) ) then
+         ipi = kdim
+      ELSE
+         ipi = I_SIZE(ptab)   ! 1st dimension
+      ENDIF
+      !
+      ALLOCATE(work(ipi))
+      IF( ln_timing ) CALL tic_tac(.TRUE., ld_global = .TRUE.)
+      CALL mpi_allreduce( ARRAY_IN(:), work, ipi, MPI_TYPE, MPI_OPERATION, ilocalcomm, ierror )
+      IF( ln_timing ) CALL tic_tac(.FALSE., ld_global = .TRUE.)
+      DO ii = 1, ipi
+         ARRAY_IN(ii) = work(ii)
+      ENDDO
+      DEALLOCATE(work)
+#else
+      ! nothing to do if non-mpp case
+      RETURN
+#endif
+
+   END SUBROUTINE ROUTINE_ALLREDUCE
+
+#undef ARRAY_TYPE
+#undef ARRAY_IN
+#undef I_SIZE
+#undef MPI_OPERATION
+#undef TMP_TYPE
+#undef MPI_TYPE
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_lnk_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_lnk_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_lnk_generic.h90	(revision 14097)
@@ -0,0 +1,394 @@
+#if defined MULTI
+#   define NAT_IN(k)                cd_nat(k)   
+#   define SGN_IN(k)                psgn(k)
+#   define F_SIZE(ptab)             kfld
+#   define OPT_K(k)                 ,ipf
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D)                , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt2d(i,j)
+#      define K_SIZE(ptab)             1
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D)                , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt3d(i,j,k)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt3d,3)
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D)                , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt4d(i,j,k,l)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt4d,3)
+#      define L_SIZE(ptab)             SIZE(ptab(1)%pt4d,4)
+#   endif
+#else
+#   define ARRAY_TYPE(i,j,k,l,f)    REAL(wp)                    , INTENT(inout) ::   ARRAY_IN(i,j,k,l,f)
+#   define NAT_IN(k)                cd_nat
+#   define SGN_IN(k)                psgn
+#   define F_SIZE(ptab)             1
+#   define OPT_K(k)                 
+#   if defined DIM_2d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j)
+#      define K_SIZE(ptab)          1
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k,l)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          SIZE(ptab,4)
+#   endif
+#endif
+
+#if defined MULTI
+   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn, kfld, kfillmode, pfillval, lsend, lrecv, ihlcom )
+      INTEGER             , INTENT(in   ) ::   kfld        ! number of pt3d arrays
+#else
+   SUBROUTINE ROUTINE_LNK( cdname, ptab, cd_nat, psgn      , kfillmode, pfillval, lsend, lrecv, ihlcom )
+#endif
+      ARRAY_TYPE(:,:,:,:,:)                                        ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=*)              , INTENT(in   ) ::   cdname      ! name of the calling subroutine
+      CHARACTER(len=1)              , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)                      , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      INTEGER ,             OPTIONAL, INTENT(in   ) ::   kfillmode   ! filling method for halo over land (default = constant)
+      REAL(wp),             OPTIONAL, INTENT(in   ) ::   pfillval    ! background value (used at closed boundaries)
+      LOGICAL, DIMENSION(4),OPTIONAL, INTENT(in   ) ::   lsend, lrecv  ! communication with other 4 proc
+      INTEGER              ,OPTIONAL, INTENT(in   ) ::   ihlcom        ! number of ranks and rows to be communicated
+      !
+      INTEGER  ::    ji,  jj,  jk,  jl,  jf      ! dummy loop indices
+      INTEGER  ::   ipi, ipj, ipk, ipl, ipf      ! dimension of the input array
+      INTEGER  ::   isize, ishift, ishift2       ! local integers
+      INTEGER  ::   ireq_we, ireq_ea, ireq_so, ireq_no     ! mpi_request id
+      INTEGER  ::   ierr
+      INTEGER  ::   ifill_we, ifill_ea, ifill_so, ifill_no
+      INTEGER  ::   ihl                          ! number of ranks and rows to be communicated 
+      REAL(wp) ::   zland
+      INTEGER , DIMENSION(MPI_STATUS_SIZE)        ::   istat          ! for mpi_isend
+      REAL(wp), DIMENSION(:,:,:,:,:), ALLOCATABLE ::   zsnd_we, zrcv_we, zsnd_ea, zrcv_ea   ! east -west  & west - east  halos
+      REAL(wp), DIMENSION(:,:,:,:,:), ALLOCATABLE ::   zsnd_so, zrcv_so, zsnd_no, zrcv_no   ! north-south & south-north  halos
+      LOGICAL  ::   llsend_we, llsend_ea, llsend_no, llsend_so       ! communication send
+      LOGICAL  ::   llrecv_we, llrecv_ea, llrecv_no, llrecv_so       ! communication receive 
+      LOGICAL  ::   lldo_nfd                                     ! do north pole folding
+      !!----------------------------------------------------------------------
+      !
+      ! ----------------------------------------- !
+      !     0. local variables initialization     !
+      ! ----------------------------------------- !
+      !
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      IF( PRESENT(ihlcom) ) THEN   ;   ihl = ihlcom
+      ELSE                         ;   ihl = 1
+      END IF
+      !
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ipk, ipl, ipf, ld_lbc = .TRUE. )
+      !
+      IF     ( PRESENT(lsend) .AND. PRESENT(lrecv) ) THEN
+         llsend_we = lsend(1)   ;   llsend_ea = lsend(2)   ;   llsend_so = lsend(3)   ;   llsend_no = lsend(4)
+         llrecv_we = lrecv(1)   ;   llrecv_ea = lrecv(2)   ;   llrecv_so = lrecv(3)   ;   llrecv_no = lrecv(4)
+      ELSE IF( PRESENT(lsend) .OR.  PRESENT(lrecv) ) THEN
+         WRITE(ctmp1,*) ' E R R O R : Routine ', cdname, '  is calling lbc_lnk with only one of the two arguments lsend or lrecv'
+         WRITE(ctmp2,*) ' ========== '
+         CALL ctl_stop( ' ', ctmp1, ctmp2, ' ' )
+      ELSE   ! send and receive with every neighbour
+         llsend_we = nbondi ==  1 .OR. nbondi == 0   ! keep for compatibility, should be defined in mppini
+         llsend_ea = nbondi == -1 .OR. nbondi == 0   ! keep for compatibility, should be defined in mppini
+         llsend_so = nbondj ==  1 .OR. nbondj == 0   ! keep for compatibility, should be defined in mppini
+         llsend_no = nbondj == -1 .OR. nbondj == 0   ! keep for compatibility, should be defined in mppini
+         llrecv_we = llsend_we   ;   llrecv_ea = llsend_ea   ;   llrecv_so = llsend_so   ;   llrecv_no = llsend_no
+      END IF
+         
+         
+      lldo_nfd = npolj /= 0                      ! keep for compatibility, should be defined in mppini
+
+      zland = 0._wp                                     ! land filling value: zero by default
+      IF( PRESENT( pfillval ) )   zland = pfillval      ! set land value
+
+      ! define the method we will use to fill the halos in each direction
+      IF(              llrecv_we ) THEN   ;   ifill_we = jpfillmpi
+      ELSEIF(           l_Iperio ) THEN   ;   ifill_we = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_we = kfillmode
+      ELSE                                ;   ifill_we = jpfillcst
+      END IF
+      !
+      IF(              llrecv_ea ) THEN   ;   ifill_ea = jpfillmpi
+      ELSEIF(           l_Iperio ) THEN   ;   ifill_ea = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_ea = kfillmode
+      ELSE                                ;   ifill_ea = jpfillcst
+      END IF
+      !
+      IF(              llrecv_so ) THEN   ;   ifill_so = jpfillmpi
+      ELSEIF(           l_Jperio ) THEN   ;   ifill_so = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_so = kfillmode
+      ELSE                                ;   ifill_so = jpfillcst
+      END IF
+      !
+      IF(              llrecv_no ) THEN   ;   ifill_no = jpfillmpi
+      ELSEIF(           l_Jperio ) THEN   ;   ifill_no = jpfillperio
+      ELSEIF( PRESENT(kfillmode) ) THEN   ;   ifill_no = kfillmode
+      ELSE                                ;   ifill_no = jpfillcst
+      END IF
+      !
+#if defined PRINT_CAUTION
+      !
+      ! ================================================================================== !
+      ! CAUTION: semi-column notation is often impossible because of the cpp preprocessing !
+      ! ================================================================================== !
+      !
+#endif
+      !
+      ! -------------------------------------------------- !
+      !     1. Do east and west MPI exchange if needed     !
+      ! -------------------------------------------------- !
+      !
+      ! Must exchange the whole column (from 1 to jpj) to get the corners if we have no south/north neighbourg
+      isize = ihl * jpj * ipk * ipl * ipf      
+      !
+      ! Allocate local temporary arrays to be sent/received. Fill arrays to be sent
+      IF( llsend_we )   ALLOCATE( zsnd_we(ihl,jpj,ipk,ipl,ipf) )
+      IF( llsend_ea )   ALLOCATE( zsnd_ea(ihl,jpj,ipk,ipl,ipf) )
+      IF( llrecv_we )   ALLOCATE( zrcv_we(ihl,jpj,ipk,ipl,ipf) )
+      IF( llrecv_ea )   ALLOCATE( zrcv_ea(ihl,jpj,ipk,ipl,ipf) )
+      !
+      IF( llsend_we ) THEN   ! copy western side of the inner mpi domain in local temporary array to be sent by MPI
+         ishift = ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            zsnd_we(ji,jj,jk,jl,jf) = ARRAY_IN(ishift+ji,jj,jk,jl,jf)   ! ihl + 1 -> 2*ihl
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      ENDIF
+      !
+      IF(llsend_ea  ) THEN   ! copy eastern side of the inner mpi domain in local temporary array to be sent by MPI
+         ishift = jpi - 2 * ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            zsnd_ea(ji,jj,jk,jl,jf) = ARRAY_IN(ishift+ji,jj,jk,jl,jf)   ! jpi - 2*ihl + 1 -> jpi - ihl
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      ENDIF
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE.)
+      !
+      ! non-blocking send of the western/eastern side using local temporary arrays
+      IF( llsend_we )   CALL mppsend( 1, zsnd_we(1,1,1,1,1), isize, nowe, ireq_we )
+      IF( llsend_ea )   CALL mppsend( 2, zsnd_ea(1,1,1,1,1), isize, noea, ireq_ea )
+      ! blocking receive of the western/eastern halo in local temporary arrays
+      IF( llrecv_we )   CALL mpprecv( 2, zrcv_we(1,1,1,1,1), isize, nowe )
+      IF( llrecv_ea )   CALL mpprecv( 1, zrcv_ea(1,1,1,1,1), isize, noea )
+      !
+      IF( ln_timing ) CALL tic_tac(.FALSE.)
+      !
+      !
+      ! ----------------------------------- !
+      !     2. Fill east and west halos     !
+      ! ----------------------------------- !
+      !
+      ! 2.1 fill weastern halo
+      ! ----------------------
+      ! ishift = 0                         ! fill halo from ji = 1 to ihl
+      SELECT CASE ( ifill_we )
+      CASE ( jpfillnothing )               ! no filling 
+      CASE ( jpfillmpi   )                 ! use data received by MPI 
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ji,jj,jk,jl,jf) = zrcv_we(ji,jj,jk,jl,jf)   ! 1 -> ihl
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillperio )                 ! use east-weast periodicity
+         ishift2 = jpi - 2 * ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcopy  )                 ! filling with inner domain values
+         DO jf = 1, ipf                               ! number of arrays to be treated
+            IF( .NOT. NAT_IN(jf) == 'F' ) THEN        ! do nothing for F point
+               DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+                  ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ihl+1,jj,jk,jl,jf)
+               END DO   ;   END DO   ;   END DO   ;   END DO
+            ENDIF
+         END DO
+      CASE ( jpfillcst   )                 ! filling with constant value
+         DO jf = 1, ipf                               ! number of arrays to be treated
+            IF( .NOT. NAT_IN(jf) == 'F' ) THEN        ! do nothing for F point
+               DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+                  ARRAY_IN(ji,jj,jk,jl,jf) = zland
+               END DO;   END DO   ;   END DO   ;   END DO
+            ENDIF
+         END DO
+      END SELECT
+      !
+      ! 2.2 fill eastern halo
+      ! ---------------------
+      ishift = jpi - ihl                ! fill halo from ji = jpi-ihl+1 to jpi 
+      SELECT CASE ( ifill_ea )
+      CASE ( jpfillnothing )               ! no filling 
+      CASE ( jpfillmpi   )                 ! use data received by MPI 
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zrcv_ea(ji,jj,jk,jl,jf)   ! jpi - ihl + 1 -> jpi
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillperio )                 ! use east-weast periodicity
+         ishift2 = ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift2+ji,jj,jk,jl,jf)
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcopy  )                 ! filling with inner domain values
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ishift+ji,jj,jk,jl,jf) = ARRAY_IN(ishift,jj,jk,jl,jf)
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcst   )                 ! filling with constant value
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, jpj   ;   DO ji = 1, ihl
+            ARRAY_IN(ishift+ji,jj,jk,jl,jf) = zland
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      END SELECT
+      !
+      ! ------------------------------- !
+      !     3. north fold treatment     !
+      ! ------------------------------- !
+      !
+      ! do it before south directions so concerned processes can do it without waiting for the comm with the sourthern neighbor
+      !
+      IF( lldo_nfd .AND. ifill_no /= jpfillnothing ) THEN
+         !
+         SELECT CASE ( jpni )
+         CASE ( 1 )     ;   CALL lbc_nfd( ptab, NAT_IN(:), SGN_IN(:) OPT_K(:) )   ! only 1 northern proc, no mpp
+         CASE DEFAULT   ;   CALL mpp_nfd( ptab, NAT_IN(:), SGN_IN(:) OPT_K(:) )   ! for all northern procs.
+         END SELECT
+         !
+         ifill_no = jpfillnothing  ! force to do nothing for the northern halo as we just done the north pole folding
+         !
+      ENDIF
+      !
+      ! ---------------------------------------------------- !
+      !     4. Do north and south MPI exchange if needed     !
+      ! ---------------------------------------------------- !
+      !
+      IF( llsend_so )   ALLOCATE( zsnd_so(jpi,ihl,ipk,ipl,ipf) )
+      IF( llsend_no )   ALLOCATE( zsnd_no(jpi,ihl,ipk,ipl,ipf) )
+      IF( llrecv_so )   ALLOCATE( zrcv_so(jpi,ihl,ipk,ipl,ipf) )
+      IF( llrecv_no )   ALLOCATE( zrcv_no(jpi,ihl,ipk,ipl,ipf) )
+      !
+      isize = jpi * ihl * ipk * ipl * ipf      
+
+      ! allocate local temporary arrays to be sent/received. Fill arrays to be sent
+      IF( llsend_so ) THEN   ! copy sourhern side of the inner mpi domain in local temporary array to be sent by MPI
+         ishift = ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            zsnd_so(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ishift+jj,jk,jl,jf)   ! ihl+1 -> 2*ihl
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      ENDIF
+      !
+      IF( llsend_no ) THEN   ! copy eastern side of the inner mpi domain in local temporary array to be sent by MPI
+         ishift = jpj - 2 * ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            zsnd_no(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ishift+jj,jk,jl,jf)   ! jpj-2*ihl+1 -> jpj-ihl
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      ENDIF
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE.)
+      !
+      ! non-blocking send of the southern/northern side
+      IF( llsend_so )   CALL mppsend( 3, zsnd_so(1,1,1,1,1), isize, noso, ireq_so )
+      IF( llsend_no )   CALL mppsend( 4, zsnd_no(1,1,1,1,1), isize, nono, ireq_no )
+      ! blocking receive of the southern/northern halo
+      IF( llrecv_so )   CALL mpprecv( 4, zrcv_so(1,1,1,1,1), isize, noso )
+      IF( llrecv_no )   CALL mpprecv( 3, zrcv_no(1,1,1,1,1), isize, nono )
+      !
+      IF( ln_timing ) CALL tic_tac(.FALSE.)
+      !
+      ! ------------------------------------- !
+      !     5. Fill south and north halos     !
+      ! ------------------------------------- !
+      !
+      ! 5.1 fill southern halo
+      ! ----------------------
+      ! ishift = 0                         ! fill halo from jj = 1 to ihl
+      SELECT CASE ( ifill_so )
+      CASE ( jpfillnothing )               ! no filling 
+      CASE ( jpfillmpi   )                 ! use data received by MPI 
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,jj,jk,jl,jf) = zrcv_so(ji,jj,jk,jl,jf)   ! 1 -> ihl
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillperio )                 ! use north-south periodicity
+         ishift2 = jpj - 2 * ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcopy  )                 ! filling with inner domain values
+         DO jf = 1, ipf                               ! number of arrays to be treated
+            IF( .NOT. NAT_IN(jf) == 'F' ) THEN        ! do nothing for F point
+               DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+                  ARRAY_IN(ji,jj,jk,jl,jf) = ARRAY_IN(ji,ihl+1,jk,jl,jf)
+               END DO   ;   END DO   ;   END DO   ;   END DO
+            ENDIF
+         END DO
+      CASE ( jpfillcst   )                 ! filling with constant value
+         DO jf = 1, ipf                               ! number of arrays to be treated
+            IF( .NOT. NAT_IN(jf) == 'F' ) THEN        ! do nothing for F point
+               DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi 
+                  ARRAY_IN(ji,jj,jk,jl,jf) = zland
+               END DO;   END DO   ;   END DO   ;   END DO
+            ENDIF
+         END DO
+      END SELECT
+      !
+      ! 5.2 fill northern halo
+      ! ----------------------
+      ishift = jpj - ihl                ! fill halo from jj = jpj-ihl+1 to jpj 
+      SELECT CASE ( ifill_no )
+      CASE ( jpfillnothing )               ! no filling 
+      CASE ( jpfillmpi   )                 ! use data received by MPI 
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zrcv_no(ji,jj,jk,jl,jf)   ! jpj-ihl+1 -> jpj
+         END DO   ;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillperio )                 ! use north-south periodicity
+         ishift2 = ihl
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift2+jj,jk,jl,jf)
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcopy  )                 ! filling with inner domain values
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,ishift+jj,jk,jl,jf) = ARRAY_IN(ji,ishift,jk,jl,jf)
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      CASE ( jpfillcst   )                 ! filling with constant value
+         DO jf = 1, ipf   ;   DO jl = 1, ipl   ;   DO jk = 1, ipk   ;   DO jj = 1, ihl   ;   DO ji = 1, jpi
+            ARRAY_IN(ji,ishift+jj,jk,jl,jf) = zland
+         END DO;   END DO   ;   END DO   ;   END DO   ;   END DO
+      END SELECT
+      !
+      ! -------------------------------------------- !
+      !     6. deallocate local temporary arrays     !
+      ! -------------------------------------------- !
+      !
+      IF( llsend_we ) THEN
+         CALL mpi_wait(ireq_we, istat, ierr )
+         DEALLOCATE( zsnd_we )
+      ENDIF
+      IF( llsend_ea )  THEN
+         CALL mpi_wait(ireq_ea, istat, ierr )
+         DEALLOCATE( zsnd_ea )
+      ENDIF
+      IF( llsend_so ) THEN
+         CALL mpi_wait(ireq_so, istat, ierr )
+         DEALLOCATE( zsnd_so )
+      ENDIF
+      IF( llsend_no ) THEN
+         CALL mpi_wait(ireq_no, istat, ierr )
+         DEALLOCATE( zsnd_no )
+      ENDIF
+      !
+      IF( llrecv_we )   DEALLOCATE( zrcv_we )
+      IF( llrecv_ea )   DEALLOCATE( zrcv_ea )
+      IF( llrecv_so )   DEALLOCATE( zrcv_so )
+      IF( llrecv_no )   DEALLOCATE( zrcv_no )
+      !
+   END SUBROUTINE ROUTINE_LNK
+
+#undef ARRAY_TYPE
+#undef NAT_IN
+#undef SGN_IN
+#undef ARRAY_IN
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
+#undef OPT_K
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_loc_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_loc_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_loc_generic.h90	(revision 14097)
@@ -0,0 +1,108 @@
+                          !==  IN: ptab is an array  ==!
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)        , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define MASK_TYPE(i,j,k)     REAL(wp)        , INTENT(in   ) ::   MASK_IN(i,j,k)
+#   if defined DIM_2d
+#      define ARRAY_IN(i,j,k)   ptab(i,j)
+#      define MASK_IN(i,j,k)    pmask(i,j)
+#      define INDEX_TYPE(k)        INTEGER         , INTENT(  out) ::   kindex(2)
+#      define K_SIZE(ptab)      1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_IN(i,j,k)   ptab(i,j,k)
+#      define MASK_IN(i,j,k)    pmask(i,j,k)
+#      define INDEX_TYPE(k)        INTEGER         , INTENT(  out) ::   kindex(3)
+#      define K_SIZE(ptab)      SIZE(ptab,3)
+#   endif
+#   if defined OPERATION_MAXLOC
+#      define MPI_OPERATION mpi_maxloc
+#      define LOC_OPERATION MAXLOC
+#      define ERRVAL -HUGE
+#   endif
+#   if defined OPERATION_MINLOC
+#      define MPI_OPERATION mpi_minloc
+#      define LOC_OPERATION MINLOC
+#      define ERRVAL HUGE
+#   endif
+
+   SUBROUTINE ROUTINE_LOC( cdname, ptab, pmask, pmin, kindex )
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in   ) ::   cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:,:,:)                            ! array on which loctrans operation is applied
+      MASK_TYPE(:,:,:)                             ! local mask
+      REAL(wp)        , INTENT(  out) ::   pmin    ! Global minimum of ptab
+      INDEX_TYPE(:)                                ! index of minimum in global frame
+      !
+      INTEGER  ::   ierror, ii, idim
+      INTEGER  ::   index0
+      REAL(wp) ::   zmin     ! local minimum
+      INTEGER , DIMENSION(:), ALLOCATABLE  ::   ilocs
+      REAL(wp), DIMENSION(2,1) ::   zain, zaout
+      !!-----------------------------------------------------------------------
+      !
+      IF( narea == 1 .AND. numcom == -1 ) CALL mpp_report( cdname, ld_glb = .TRUE. )
+      !
+      idim = SIZE(kindex)
+      !
+      IF ( ALL(MASK_IN(:,:,:) /= 1._wp) ) THEN
+         ! special case for land processors
+         zmin = ERRVAL(zmin)
+         index0 = 0
+      ELSE
+         ALLOCATE ( ilocs(idim) )
+         !
+         ilocs = LOC_OPERATION( ARRAY_IN(:,:,:) , mask= MASK_IN(:,:,:) == 1._wp )
+         zmin  = ARRAY_IN(ilocs(1),ilocs(2),ilocs(3))
+         !
+         kindex(1) = mig( ilocs(1) )
+#  if defined DIM_2d || defined DIM_3d    /* avoid warning when kindex has 1 element */
+         kindex(2) = mjg( ilocs(2) )
+#  endif
+#  if defined DIM_3d                      /* avoid warning when kindex has 2 elements */
+         kindex(3) = ilocs(3)
+#  endif
+         ! 
+         DEALLOCATE (ilocs)
+         !
+         index0 = kindex(1)-1   ! 1d index starting at 0
+#  if defined DIM_2d || defined DIM_3d   /* avoid warning when kindex has 1 element */
+         index0 = index0 + jpiglo * (kindex(2)-1)
+#  endif
+#  if defined DIM_3d                     /* avoid warning when kindex has 2 elements */
+         index0 = index0 + jpiglo * jpjglo * (kindex(3)-1)
+#  endif
+      END IF
+      zain(1,:) = zmin
+      zain(2,:) = REAL(index0, wp)
+      !
+      IF( ln_timing ) CALL tic_tac(.TRUE., ld_global = .TRUE.)
+#if defined key_mpp_mpi
+      CALL MPI_ALLREDUCE( zain, zaout, 1, MPI_2DOUBLE_PRECISION, MPI_OPERATION ,MPI_COMM_OCE, ierror)
+#else
+      zaout(:,:) = zain(:,:)
+#endif
+      IF( ln_timing ) CALL tic_tac(.FALSE., ld_global = .TRUE.)
+      !
+      pmin      = zaout(1,1)
+      index0    = NINT( zaout(2,1) )
+#  if defined DIM_3d                     /* avoid warning when kindex has 2 elements */
+      kindex(3) = index0 / (jpiglo*jpjglo)
+      index0    = index0 - kindex(3) * (jpiglo*jpjglo)
+#  endif
+#  if defined DIM_2d || defined DIM_3d   /* avoid warning when kindex has 1 element */
+      kindex(2) = index0 / jpiglo
+      index0 = index0 - kindex(2) * jpiglo
+#  endif
+      kindex(1) = index0
+      kindex(:) = kindex(:) + 1   ! start indices at 1
+
+   END SUBROUTINE ROUTINE_LOC
+
+#undef ARRAY_TYPE
+#undef MAX_TYPE
+#undef ARRAY_IN
+#undef MASK_IN
+#undef K_SIZE
+#undef MPI_OPERATION
+#undef LOC_OPERATION
+#undef INDEX_TYPE
+#undef ERRVAL
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_nfd_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_nfd_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mpp_nfd_generic.h90	(revision 14097)
@@ -0,0 +1,307 @@
+#if defined MULTI
+#   define NAT_IN(k)                cd_nat(k)   
+#   define SGN_IN(k)                psgn(k)
+#   define F_SIZE(ptab)             kfld
+#   define LBC_ARG                  (jf)
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_2D)     , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt2d(i,j)
+#      define K_SIZE(ptab)             1
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_3D)     , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt3d(i,j,k)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt3d,3)
+#      define L_SIZE(ptab)             1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_TYPE(i,j,k,l,f)    TYPE(PTR_4D)     , INTENT(inout) ::   ptab(f)
+#      define ARRAY_IN(i,j,k,l,f)      ptab(f)%pt4d(i,j,k,l)
+#      define K_SIZE(ptab)             SIZE(ptab(1)%pt4d,3)
+#      define L_SIZE(ptab)             SIZE(ptab(1)%pt4d,4)
+#   endif
+#else
+!                          !==  IN: ptab is an array  ==!
+#   define ARRAY_TYPE(i,j,k,l,f)    REAL(wp)         , INTENT(inout) ::   ARRAY_IN(i,j,k,l,f)
+#   define NAT_IN(k)                cd_nat
+#   define SGN_IN(k)                psgn
+#   define F_SIZE(ptab)             1
+#   define LBC_ARG
+#   if defined DIM_2d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j)
+#      define K_SIZE(ptab)          1
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          1
+#   endif
+#   if defined DIM_4d
+#      define ARRAY_IN(i,j,k,l,f)   ptab(i,j,k,l)
+#      define K_SIZE(ptab)          SIZE(ptab,3)
+#      define L_SIZE(ptab)          SIZE(ptab,4)
+#   endif
+#endif
+
+   SUBROUTINE ROUTINE_NFD( ptab, cd_nat, psgn, kfld )
+      !!----------------------------------------------------------------------
+      ARRAY_TYPE(:,:,:,:,:)   ! array or pointer of arrays on which the boundary condition is applied
+      CHARACTER(len=1) , INTENT(in   ) ::   NAT_IN(:)   ! nature of array grid-points
+      REAL(wp)         , INTENT(in   ) ::   SGN_IN(:)   ! sign used across the north fold boundary
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kfld        ! number of pt3d arrays
+      !
+      INTEGER  ::   ji,  jj,  jk,  jl, jh, jf, jr   ! dummy loop indices
+      INTEGER  ::   ipi, ipj, ipk, ipl, ipf         ! dimension of the input array
+      INTEGER  ::   imigr, iihom, ijhom             ! local integers
+      INTEGER  ::   ierr, ibuffsize, ilci, ildi, ilei, iilb
+      INTEGER  ::   ij, iproc
+      INTEGER, DIMENSION (jpmaxngh)       ::   ml_req_nf   ! for mpi_isend when avoiding mpi_allgather
+      INTEGER                             ::   ml_err      ! for mpi_isend when avoiding mpi_allgather
+      INTEGER, DIMENSION(MPI_STATUS_SIZE) ::   ml_stat     ! for mpi_isend when avoiding mpi_allgather
+      !                                                    ! Workspace for message transfers avoiding mpi_allgather
+      INTEGER                             ::   ipf_j       ! sum of lines for all multi fields
+      INTEGER                             ::   js          ! counter
+      INTEGER, DIMENSION(:,:),          ALLOCATABLE ::   jj_s  ! position of sent lines
+      INTEGER, DIMENSION(:),            ALLOCATABLE ::   ipj_s ! number of sent lines
+      REAL(wp), DIMENSION(:,:,:)      , ALLOCATABLE ::   ztabl
+      REAL(wp), DIMENSION(:,:,:,:,:)  , ALLOCATABLE ::   ztab, ztabr
+      REAL(wp), DIMENSION(:,:,:,:,:)  , ALLOCATABLE ::   znorthloc, zfoldwk      
+      REAL(wp), DIMENSION(:,:,:,:,:,:), ALLOCATABLE ::   znorthgloio
+      !!----------------------------------------------------------------------
+      !
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      ipl = L_SIZE(ptab)   ! 4th    -
+      ipf = F_SIZE(ptab)   ! 5th    -      use in "multi" case (array of pointers)
+      !
+      IF( l_north_nogather ) THEN      !==  no allgather exchanges  ==!
+
+         ALLOCATE(ipj_s(ipf))
+
+         ipj      = 2            ! Max 2nd dimension of message transfers (last two j-line only)
+         ipj_s(:) = 1            ! Real 2nd dimension of message transfers (depending on perf requirement)
+                                 ! by default, only one line is exchanged
+
+         ALLOCATE( jj_s(ipf,2) )
+
+         ! re-define number of exchanged lines :
+         !  must be two during the first two time steps
+         !  to correct possible incoherent values on North fold lines from restart 
+
+         !!!!!!!!!           temporary switch off this optimisation ==> force TRUE           !!!!!!!!
+         !!!!!!!!!  needed to get the same results without agrif and with agrif and no zoom  !!!!!!!!
+         !!!!!!!!!                    I don't know why we must do that...                    !!!!!!!!
+         l_full_nf_update = .TRUE.
+
+         ! Two lines update (slower but necessary to avoid different values ion identical grid points
+         IF ( l_full_nf_update .OR.                          &    ! if coupling fields
+              ( ncom_stp == nit000 .AND. .NOT. ln_rstart ) ) &    ! at first time step, if not restart
+            ipj_s(:) = 2
+
+         ! Index of modifying lines in input
+         DO jf = 1, ipf                      ! Loop over the number of arrays to be processed
+            !
+            SELECT CASE ( npolj )
+            !
+            CASE ( 3, 4 )                       ! *  North fold  T-point pivot
+               !
+               SELECT CASE ( NAT_IN(jf) )
+               !
+               CASE ( 'T' , 'W' ,'U' )                            ! T-, U-, W-point
+                  jj_s(jf,1) = nlcj - 2 ;  jj_s(jf,2) = nlcj - 1
+               CASE ( 'V' , 'F' )                                 ! V-, F-point
+                  jj_s(jf,1) = nlcj - 3 ;  jj_s(jf,2) = nlcj - 2
+               END SELECT
+            !
+            CASE ( 5, 6 )                        ! *  North fold  F-point pivot
+               SELECT CASE ( NAT_IN(jf) )
+               !
+               CASE ( 'T' , 'W' ,'U' )                            ! T-, U-, W-point
+                  jj_s(jf,1) = nlcj - 1      
+                  ipj_s(jf) = 1                  ! need only one line anyway
+               CASE ( 'V' , 'F' )                                 ! V-, F-point
+                  jj_s(jf,1) = nlcj - 2 ;  jj_s(jf,2) = nlcj - 1
+               END SELECT
+            !
+            END SELECT
+            !
+         ENDDO
+         ! 
+         ipf_j = sum (ipj_s(:))      ! Total number of lines to be exchanged
+         !
+         ALLOCATE( znorthloc(jpimax,ipf_j,ipk,ipl,1) )
+         !
+         js = 0
+         DO jf = 1, ipf                      ! Loop over the number of arrays to be processed
+            DO jj = 1, ipj_s(jf)
+               js = js + 1
+               DO jl = 1, ipl
+                  DO jk = 1, ipk
+                     znorthloc(1:jpi,js,jk,jl,1) = ARRAY_IN(1:jpi,jj_s(jf,jj),jk,jl,jf)
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         ibuffsize = jpimax * ipf_j * ipk * ipl
+         !
+         ALLOCATE( zfoldwk(jpimax,ipf_j,ipk,ipl,1) )
+         ALLOCATE( ztabr(jpimax*jpmaxngh,ipj,ipk,ipl,ipf) ) 
+         ! when some processors of the north fold are suppressed, 
+         ! values of ztab* arrays corresponding to these suppressed domain won't be defined 
+         ! and we need a default definition to 0.
+         ! a better test should be: a testing if "suppressed land-processors" belongs to the north-pole folding
+         IF ( jpni*jpnj /= jpnij ) ztabr(:,:,:,:,:) = 0._wp
+         !
+         ! start waiting time measurement
+         IF( ln_timing ) CALL tic_tac(.TRUE.)
+         !
+         DO jr = 1, nsndto
+            IF( nfipproc(isendto(jr),jpnj) /= narea-1 .AND. nfipproc(isendto(jr),jpnj) /= -1 ) THEN
+               CALL mppsend( 5, znorthloc, ibuffsize, nfipproc(isendto(jr),jpnj), ml_req_nf(jr) )
+            ENDIF
+         END DO
+         !
+         DO jr = 1,nsndto
+            iproc = nfipproc(isendto(jr),jpnj)
+            IF(iproc /= -1) THEN
+               iilb = nimppt(iproc+1)
+               ilci = nlcit (iproc+1)
+               ildi = nldit (iproc+1)
+               ilei = nleit (iproc+1)
+               IF( iilb            ==      1 )   ildi = 1      ! e-w boundary already done -> force to take 1st column
+               IF( iilb + ilci - 1 == jpiglo )   ilei = ilci   ! e-w boundary already done -> force to take last column
+               iilb = nfiimpp(isendto(jr),jpnj) - nfiimpp(isendto(1),jpnj)
+            ENDIF
+            IF( iproc /= narea-1 .AND. iproc /= -1 ) THEN
+               CALL mpprecv(5, zfoldwk, ibuffsize, iproc)
+               js = 0
+               DO jf = 1, ipf ; DO jj = 1, ipj_s(jf)
+                  js = js + 1
+                  DO jl = 1, ipl
+                     DO jk = 1, ipk
+                        DO ji = ildi, ilei
+                           ztabr(iilb+ji,jj,jk,jl,jf) = zfoldwk(ji,js,jk,jl,1)
+                        END DO
+                     END DO
+                  END DO
+               END DO; END DO
+            ELSE IF( iproc == narea-1 ) THEN
+               DO jf = 1, ipf ; DO jj = 1, ipj_s(jf)
+                  DO jl = 1, ipl
+                     DO jk = 1, ipk
+                        DO ji = ildi, ilei
+                           ztabr(iilb+ji,jj,jk,jl,jf) = ARRAY_IN(ji,jj_s(jf,jj),jk,jl,jf)
+                        END DO
+                     END DO
+                  END DO
+               END DO; END DO
+            ENDIF
+         END DO
+         DO jr = 1,nsndto
+            IF( nfipproc(isendto(jr),jpnj) /= narea-1 .AND. nfipproc(isendto(jr),jpnj) /= -1 ) THEN
+               CALL mpi_wait( ml_req_nf(jr), ml_stat, ml_err )
+            ENDIF
+         END DO
+         !
+         IF( ln_timing ) CALL tic_tac(.FALSE.)
+         !
+         ! North fold boundary condition
+         !
+         DO jf = 1, ipf
+            CALL lbc_nfd_nogather( ARRAY_IN(:,:,:,:,jf), ztabr(:,1:ipj_s(jf),:,:,jf), cd_nat LBC_ARG, psgn LBC_ARG )
+         END DO
+         !
+         DEALLOCATE( zfoldwk, ztabr, jj_s, ipj_s )
+         !
+      ELSE                             !==  allgather exchanges  ==!
+         !
+         ipj   = 4            ! 2nd dimension of message transfers (last j-lines)
+         !
+         ALLOCATE( znorthloc(jpimax,ipj,ipk,ipl,ipf) )
+         !
+         DO jf = 1, ipf                ! put in znorthloc the last ipj j-lines of ptab
+            DO jl = 1, ipl
+               DO jk = 1, ipk
+                  DO jj = nlcj - ipj +1, nlcj
+                     ij = jj - nlcj + ipj
+                     znorthloc(1:jpi,ij,jk,jl,jf) = ARRAY_IN(1:jpi,jj,jk,jl,jf)
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         ibuffsize = jpimax * ipj * ipk * ipl * ipf
+         !
+         ALLOCATE( ztab       (jpiglo,ipj,ipk,ipl,ipf     ) )
+         ALLOCATE( znorthgloio(jpimax,ipj,ipk,ipl,ipf,jpni) )
+         !
+         ! when some processors of the north fold are suppressed,
+         ! values of ztab* arrays corresponding to these suppressed domain won't be defined
+         ! and we need a default definition to 0.
+         ! a better test should be: a testing if "suppressed land-processors" belongs to the north-pole folding
+         IF ( jpni*jpnj /= jpnij ) ztab(:,:,:,:,:) = 0._wp
+         !
+         ! start waiting time measurement
+         IF( ln_timing ) CALL tic_tac(.TRUE.)
+         CALL MPI_ALLGATHER( znorthloc  , ibuffsize, MPI_DOUBLE_PRECISION,                &
+            &                znorthgloio, ibuffsize, MPI_DOUBLE_PRECISION, ncomm_north, ierr )
+         !
+         ! stop waiting time measurement
+         IF( ln_timing ) CALL tic_tac(.FALSE.)
+         !
+         DO jr = 1, ndim_rank_north         ! recover the global north array
+            iproc = nrank_north(jr) + 1
+            iilb  = nimppt(iproc)
+            ilci  = nlcit (iproc)
+            ildi  = nldit (iproc)
+            ilei  = nleit (iproc)
+            IF( iilb            ==      1 )   ildi = 1      ! e-w boundary already done -> force to take 1st column
+            IF( iilb + ilci - 1 == jpiglo )   ilei = ilci   ! e-w boundary already done -> force to take last column
+            DO jf = 1, ipf
+               DO jl = 1, ipl
+                  DO jk = 1, ipk
+                     DO jj = 1, ipj
+                        DO ji = ildi, ilei
+                           ztab(ji+iilb-1,jj,jk,jl,jf) = znorthgloio(ji,jj,jk,jl,jf,jr)
+                        END DO
+                     END DO
+                  END DO
+               END DO
+            END DO
+         END DO
+         DO jf = 1, ipf
+            CALL lbc_nfd( ztab(:,:,:,:,jf), cd_nat LBC_ARG, psgn LBC_ARG )   ! North fold boundary condition
+         END DO
+         !
+         DO jf = 1, ipf
+            DO jl = 1, ipl
+               DO jk = 1, ipk
+                  DO jj = nlcj-ipj+1, nlcj             ! Scatter back to ARRAY_IN
+                     ij = jj - nlcj + ipj
+                     DO ji= 1, nlci
+                        ARRAY_IN(ji,jj,jk,jl,jf) = ztab(ji+nimpp-1,ij,jk,jl,jf)
+                     END DO
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+      !
+         DEALLOCATE( ztab )
+         DEALLOCATE( znorthgloio )
+      ENDIF
+      !
+      DEALLOCATE( znorthloc )
+      !
+   END SUBROUTINE ROUTINE_NFD
+
+#undef ARRAY_TYPE
+#undef NAT_IN
+#undef SGN_IN
+#undef ARRAY_IN
+#undef K_SIZE
+#undef L_SIZE
+#undef F_SIZE
+#undef LBC_ARG
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mppini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mppini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LBC/mppini.F90	(revision 14097)
@@ -0,0 +1,1306 @@
+MODULE mppini
+   !!======================================================================
+   !!                       ***  MODULE mppini   ***
+   !! Ocean initialization : distributed memory computing initialization
+   !!======================================================================
+   !! History :  6.0  !  1994-11  (M. Guyon)  Original code
+   !!  OPA       7.0  !  1995-04  (J. Escobar, M. Imbard)
+   !!            8.0  !  1998-05  (M. Imbard, J. Escobar, L. Colombet )  SHMEM and MPI versions
+   !!  NEMO      1.0  !  2004-01  (G. Madec, J.M Molines)  F90 : free form , north fold jpni > 1
+   !!            3.4  ! 2011-10  (A. C. Coward, NOCS & J. Donners, PRACE) add mpp_init_nfdcom
+   !!            3.   ! 2013-06  (I. Epicoco, S. Mocavero, CMCC) mpp_init_nfdcom: setup avoiding MPI communication 
+   !!            4.0  !  2016-06  (G. Madec)  use domain configuration file instead of bathymetry file
+   !!            4.0  !  2017-06  (J.M. Molines, T. Lovato) merge of mppini and mppini_2
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  mpp_init          : Lay out the global domain over processors with/without land processor elimination
+   !!  mpp_init_mask     : Read global bathymetric information to facilitate land suppression
+   !!  mpp_init_ioipsl   : IOIPSL initialization in mpp 
+   !!  mpp_init_partition: Calculate MPP domain decomposition
+   !!  factorise         : Calculate the factors of the no. of MPI processes
+   !!  mpp_init_nfdcom   : Setup for north fold exchanges with explicit point-to-point messaging
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE bdy_oce        ! open BounDarY  
+   !
+   USE lbcnfd  , ONLY : isendto, nsndto, nfsloop, nfeloop   ! Setup of north fold exchanges 
+   USE lib_mpp        ! distribued memory computing library
+   USE iom            ! nemo I/O library 
+   USE ioipsl         ! I/O IPSL library
+   USE in_out_manager ! I/O Manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC mpp_init       ! called by opa.F90
+
+   INTEGER :: numbot = -1  ! 'bottom_level' local logical unit
+   INTEGER :: numbdy = -1  ! 'bdy_msk'      local logical unit
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if ! defined key_mpp_mpi
+   !!----------------------------------------------------------------------
+   !!   Default option :                            shared memory computing
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE mpp_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init  ***
+      !!
+      !! ** Purpose :   Lay out the global domain over processors.
+      !!
+      !! ** Method  :   Shared memory computing, set the local processor
+      !!              variables to the value of the global domain
+      !!----------------------------------------------------------------------
+      !
+      jpimax = jpiglo
+      jpjmax = jpjglo
+      jpi    = jpiglo
+      jpj    = jpjglo
+      jpk    = jpkglo
+      jpim1  = jpi-1                                            ! inner domain indices
+      jpjm1  = jpj-1                                            !   "           "
+      jpkm1  = MAX( 1, jpk-1 )                                  !   "           "
+      jpij   = jpi*jpj
+      jpni   = 1
+      jpnj   = 1
+      jpnij  = jpni*jpnj
+      nimpp  = 1           ! 
+      njmpp  = 1
+      nlci   = jpi
+      nlcj   = jpj
+      nldi   = 1
+      nldj   = 1
+      nlei   = jpi
+      nlej   = jpj
+      nbondi = 2
+      nbondj = 2
+      nidom  = FLIO_DOM_NONE
+      npolj = 0
+      IF( jperio == 3 .OR. jperio == 4 )   npolj = 3
+      IF( jperio == 5 .OR. jperio == 6 )   npolj = 5
+      l_Iperio = jpni == 1 .AND. (jperio == 1 .OR. jperio == 4 .OR. jperio == 6 .OR. jperio == 7)
+      l_Jperio = jpnj == 1 .AND. (jperio == 2 .OR. jperio == 7)
+      !
+      ! Set flags to detect global domain edges for AGRIF
+      l_Westedge = .true. ; l_Eastedge = .true. ; l_Northedge = .true.; l_Southedge = .true.
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'mpp_init : NO massively parallel processing'
+         WRITE(numout,*) '~~~~~~~~ '
+         WRITE(numout,*) '   l_Iperio = ', l_Iperio, '    l_Jperio = ', l_Jperio 
+         WRITE(numout,*) '     npolj  = ',   npolj , '      njmpp  = ', njmpp
+      ENDIF
+      !
+      IF(  jpni /= 1 .OR. jpnj /= 1 .OR. jpnij /= 1 )                                     &
+         CALL ctl_stop( 'mpp_init: equality  jpni = jpnj = jpnij = 1 is not satisfied',   &
+            &           'the domain is lay out for distributed memory computing!' )
+         !
+   END SUBROUTINE mpp_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   'key_mpp_mpi'                     MPI massively parallel processing
+   !!----------------------------------------------------------------------
+
+
+   SUBROUTINE mpp_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init  ***
+      !!                    
+      !! ** Purpose :   Lay out the global domain over processors.
+      !!      If land processors are to be eliminated, this program requires the
+      !!      presence of the domain configuration file. Land processors elimination
+      !!      is performed if jpni x jpnj /= jpnij. In this case, using the MPP_PREP
+      !!      preprocessing tool, help for defining the best cutting out.
+      !!
+      !! ** Method  :   Global domain is distributed in smaller local domains.
+      !!      Periodic condition is a function of the local domain position
+      !!      (global boundary or neighbouring domain) and of the global
+      !!      periodic
+      !!      Type :         jperio global periodic condition
+      !!
+      !! ** Action : - set domain parameters
+      !!                    nimpp     : longitudinal index 
+      !!                    njmpp     : latitudinal  index
+      !!                    narea     : number for local area
+      !!                    nlci      : first dimension
+      !!                    nlcj      : second dimension
+      !!                    nbondi    : mark for "east-west local boundary"
+      !!                    nbondj    : mark for "north-south local boundary"
+      !!                    nproc     : number for local processor
+      !!                    noea      : number for local neighboring processor
+      !!                    nowe      : number for local neighboring processor
+      !!                    noso      : number for local neighboring processor
+      !!                    nono      : number for local neighboring processor
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jn, jproc, jarea   ! dummy loop indices
+      INTEGER ::   inijmin
+      INTEGER ::   i2add
+      INTEGER ::   inum                       ! local logical unit
+      INTEGER ::   idir, ifreq, icont         ! local integers
+      INTEGER ::   ii, il1, ili, imil         !   -       -
+      INTEGER ::   ij, il2, ilj, ijm1         !   -       -
+      INTEGER ::   iino, ijno, iiso, ijso     !   -       -
+      INTEGER ::   iiea, ijea, iiwe, ijwe     !   -       -
+      INTEGER ::   iarea0                     !   -       -
+      INTEGER ::   ierr, ios                  ! 
+      INTEGER ::   inbi, inbj, iimax,  ijmax, icnt1, icnt2
+      LOGICAL ::   llbest, llauto
+      LOGICAL ::   llwrtlay
+      LOGICAL ::   ln_listonly
+      INTEGER, ALLOCATABLE, DIMENSION(:)     ::   iin, ii_nono, ii_noea          ! 1D workspace
+      INTEGER, ALLOCATABLE, DIMENSION(:)     ::   ijn, ii_noso, ii_nowe          !  -     -
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   iimppt, ilci, ibondi, ipproc   ! 2D workspace
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   ijmppt, ilcj, ibondj, ipolj    !  -     -
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   ilei, ildi, iono, ioea         !  -     -
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   ilej, ildj, ioso, iowe         !  -     -
+      LOGICAL, ALLOCATABLE, DIMENSION(:,:) ::   llisoce                        !  -     -
+      LOGICAL, ALLOCATABLE, DIMENSION(:,:) ::   lliswest, lliseast, llisnorth, llissouth  !  -     -
+      NAMELIST/nambdy/ ln_bdy, nb_bdy, ln_coords_file, cn_coords_file,           &
+           &             ln_mask_file, cn_mask_file, cn_dyn2d, nn_dyn2d_dta,     &
+           &             cn_dyn3d, nn_dyn3d_dta, cn_tra, nn_tra_dta,             &  
+           &             ln_tra_dmp, ln_dyn3d_dmp, rn_time_dmp, rn_time_dmp_out, &
+           &             cn_ice, nn_ice_dta,                                     &
+           &             ln_vol, nn_volctl, nn_rimwidth
+      NAMELIST/nammpp/ jpni, jpnj, ln_nnogather, ln_listonly
+      !!----------------------------------------------------------------------
+      !
+      llwrtlay = lwp .OR. ln_ctl .OR. sn_cfctl%l_layout
+      !
+      !  0. read namelists parameters
+      ! -----------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist nammpp in reference namelist
+      READ  ( numnam_ref, nammpp, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nammpp in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nammpp in confguration namelist
+      READ  ( numnam_cfg, nammpp, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nammpp in configuration namelist' )   
+      !
+      IF(lwp) THEN
+            WRITE(numout,*) '   Namelist nammpp'
+         IF( jpni < 1 .OR. jpnj < 1  ) THEN
+            WRITE(numout,*) '      jpni and jpnj will be calculated automatically'
+         ELSE
+            WRITE(numout,*) '      processor grid extent in i                            jpni = ', jpni
+            WRITE(numout,*) '      processor grid extent in j                            jpnj = ', jpnj
+         ENDIF
+            WRITE(numout,*) '      avoid use of mpi_allgather at the north fold  ln_nnogather = ', ln_nnogather
+      ENDIF
+      !
+      IF(lwm)   WRITE( numond, nammpp )
+
+      ! do we need to take into account bdy_msk?
+      REWIND( numnam_ref )              ! Namelist nambdy in reference namelist : BDY
+      READ  ( numnam_ref, nambdy, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambdy in reference namelist (mppini)' )
+      REWIND( numnam_cfg )              ! Namelist nambdy in configuration namelist : BDY
+      READ  ( numnam_cfg, nambdy, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'nambdy in configuration namelist (mppini)' )
+      !
+      IF(               ln_read_cfg ) CALL iom_open( cn_domcfg,    numbot )
+      IF( ln_bdy .AND. ln_mask_file ) CALL iom_open( cn_mask_file, numbdy )
+      !
+      IF( ln_listonly )   CALL mpp_init_bestpartition( MAX(mppsize,jpni*jpnj), ldlist = .TRUE. )   ! must be done by all core
+      !
+      !  1. Dimension arrays for subdomains
+      ! -----------------------------------
+      !
+      ! If dimensions of processor grid weren't specified in the namelist file
+      ! then we calculate them here now that we have our communicator size
+      IF(lwp) THEN
+         WRITE(numout,*) 'mpp_init:'
+         WRITE(numout,*) '~~~~~~~~ '
+         WRITE(numout,*)
+      ENDIF
+      IF( jpni < 1 .OR. jpnj < 1 ) THEN
+         CALL mpp_init_bestpartition( mppsize, jpni, jpnj )           ! best mpi decomposition for mppsize mpi processes
+         llauto = .TRUE.
+         llbest = .TRUE.
+      ELSE
+         llauto = .FALSE.
+         CALL mpp_init_bestpartition( mppsize, inbi, inbj, icnt2 )    ! best mpi decomposition for mppsize mpi processes
+         ! largest subdomain size for mpi decoposition jpni*jpnj given in the namelist
+         CALL mpp_basic_decomposition( jpni, jpnj, jpimax, jpjmax )
+         ! largest subdomain size for mpi decoposition inbi*inbj given by mpp_init_bestpartition
+         CALL mpp_basic_decomposition( inbi, inbj,  iimax,  ijmax )
+         icnt1 = jpni*jpnj - mppsize   ! number of land subdomains that should be removed to use mppsize mpi processes
+         IF(lwp) THEN
+            WRITE(numout,9000) '   The chosen domain decomposition ', jpni, ' x ', jpnj, ' with ', icnt1, ' land subdomains'
+            WRITE(numout,9002) '      - uses a total of ',  mppsize,' mpi process'
+            WRITE(numout,9000) '      - has mpi subdomains with a maximum size of (jpi = ', jpimax, ', jpj = ', jpjmax,   &
+               &                                                                ', jpi*jpj = ', jpimax*jpjmax, ')'
+            WRITE(numout,9000) '   The best domain decompostion ', inbi, ' x ', inbj, ' with ', icnt2, ' land subdomains'
+            WRITE(numout,9002) '      - uses a total of ',  inbi*inbj-icnt2,' mpi process'
+            WRITE(numout,9000) '      - has mpi subdomains with a maximum size of (jpi = ',  iimax, ', jpj = ',  ijmax,   &
+               &                                                             ', jpi*jpj = ',  iimax* ijmax, ')'
+         ENDIF
+         IF( iimax*ijmax < jpimax*jpjmax ) THEN   ! chosen subdomain size is larger that the best subdomain size
+            llbest = .FALSE.
+            IF ( inbi*inbj-icnt2 < mppsize ) THEN
+               WRITE(ctmp1,*) '   ==> You could therefore have smaller mpi subdomains with less mpi processes'
+            ELSE
+               WRITE(ctmp1,*) '   ==> You could therefore have smaller mpi subdomains with the same number of mpi processes'
+            ENDIF
+            CALL ctl_warn( ' ', ctmp1, ' ', '    ---   YOU ARE WASTING CPU...   ---', ' ' )
+         ELSE IF ( iimax*ijmax == jpimax*jpjmax .AND. (inbi*inbj-icnt2) <  mppsize) THEN
+            llbest = .FALSE.
+            WRITE(ctmp1,*) '   ==> You could therefore have the same mpi subdomains size with less mpi processes'
+            CALL ctl_warn( ' ', ctmp1, ' ', '    ---   YOU ARE WASTING CPU...   ---', ' ' )
+         ELSE
+            llbest = .TRUE.
+         ENDIF
+      ENDIF
+      
+      ! look for land mpi subdomains...
+      ALLOCATE( llisoce(jpni,jpnj) )
+      CALL mpp_init_isoce( jpni, jpnj, llisoce )
+      inijmin = COUNT( llisoce )   ! number of oce subdomains
+
+      IF( mppsize < inijmin ) THEN   ! too many oce subdomains: can happen only if jpni and jpnj are prescribed...
+         WRITE(ctmp1,9001) '   With this specified domain decomposition: jpni = ', jpni, ' jpnj = ', jpnj
+         WRITE(ctmp2,9002) '   we can eliminate only ', jpni*jpnj - inijmin, ' land mpi subdomains therefore '
+         WRITE(ctmp3,9001) '   the number of ocean mpi subdomains (', inijmin,') exceed the number of MPI processes:', mppsize
+         WRITE(ctmp4,*) '   ==>>> There is the list of best domain decompositions you should use: '
+         CALL ctl_stop( ctmp1, ctmp2, ctmp3, ' ', ctmp4, ' ' )
+         CALL mpp_init_bestpartition( mppsize, ldlist = .TRUE. )   ! must be done by all core
+      ENDIF
+
+      IF( mppsize > jpni*jpnj ) THEN   ! not enough mpi subdomains for the total number of mpi processes
+         IF(lwp) THEN
+            WRITE(numout,9003) '   The number of mpi processes: ', mppsize
+            WRITE(numout,9003) '   exceeds the maximum number of subdomains (ocean+land) = ', jpni*jpnj
+            WRITE(numout,9001) '   defined by the following domain decomposition: jpni = ', jpni, ' jpnj = ', jpnj
+            WRITE(numout,   *) '   You should: '
+           IF( llauto ) THEN
+               WRITE(numout,*) '     - either prescribe your domain decomposition with the namelist variables'
+               WRITE(numout,*) '       jpni and jpnj to match the number of mpi process you want to use, '
+               WRITE(numout,*) '       even IF it not the best choice...'
+               WRITE(numout,*) '     - or keep the automatic and optimal domain decomposition by picking up one'
+               WRITE(numout,*) '       of the number of mpi process proposed in the list bellow'
+            ELSE
+               WRITE(numout,*) '     - either properly prescribe your domain decomposition with jpni and jpnj'
+               WRITE(numout,*) '       in order to be consistent with the number of mpi process you want to use'
+               WRITE(numout,*) '       even IF it not the best choice...'
+               WRITE(numout,*) '     - or use the automatic and optimal domain decomposition and pick up one of'
+               WRITE(numout,*) '       the domain decomposition proposed in the list bellow'
+            ENDIF
+            WRITE(numout,*)
+         ENDIF
+         CALL mpp_init_bestpartition( mppsize, ldlist = .TRUE. )   ! must be done by all core
+      ENDIF
+
+      jpnij = mppsize   ! force jpnij definition <-- remove as much land subdomains as needed to reach this condition
+      IF( mppsize > inijmin ) THEN
+         WRITE(ctmp1,9003) '   The number of mpi processes: ', mppsize
+         WRITE(ctmp2,9003) '   exceeds the maximum number of ocean subdomains = ', inijmin
+         WRITE(ctmp3,9002) '   we suppressed ', jpni*jpnj - mppsize, ' land subdomains '
+         WRITE(ctmp4,9002) '   BUT we had to keep ', mppsize - inijmin, ' land subdomains that are useless...'
+         CALL ctl_warn( ctmp1, ctmp2, ctmp3, ctmp4, ' ', '    --- YOU ARE WASTING CPU... ---', ' ' )
+      ELSE   ! mppsize = inijmin
+         IF(lwp) THEN
+            IF(llbest) WRITE(numout,*) '   ==> you use the best mpi decomposition'
+            WRITE(numout,*)
+            WRITE(numout,9003) '   Number of mpi processes: ', mppsize
+            WRITE(numout,9003) '   Number of ocean subdomains = ', inijmin
+            WRITE(numout,9003) '   Number of suppressed land subdomains = ', jpni*jpnj - inijmin
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+9000  FORMAT (a, i4, a, i4, a, i7, a)
+9001  FORMAT (a, i4, a, i4)
+9002  FORMAT (a, i4, a)
+9003  FORMAT (a, i5)
+
+      IF( numbot /= -1 )   CALL iom_close( numbot )
+      IF( numbdy /= -1 )   CALL iom_close( numbdy )
+    
+      ALLOCATE(  nfiimpp(jpni,jpnj), nfipproc(jpni,jpnj), nfilcit(jpni,jpnj) ,    &
+         &       nimppt(jpnij) , ibonit(jpnij) , nlcit(jpnij) , nlcjt(jpnij) ,    &
+         &       njmppt(jpnij) , ibonjt(jpnij) , nldit(jpnij) , nldjt(jpnij) ,    &
+         &                                       nleit(jpnij) , nlejt(jpnij) ,    &
+         &       iin(jpnij), ii_nono(jpnij), ii_noea(jpnij),   &
+         &       ijn(jpnij), ii_noso(jpnij), ii_nowe(jpnij),   &
+         &       iimppt(jpni,jpnj), ilci(jpni,jpnj), ibondi(jpni,jpnj), ipproc(jpni,jpnj),   &
+         &       ijmppt(jpni,jpnj), ilcj(jpni,jpnj), ibondj(jpni,jpnj), ipolj(jpni,jpnj),   &
+         &       ilei(jpni,jpnj), ildi(jpni,jpnj), iono(jpni,jpnj), ioea(jpni,jpnj),   &
+         &       ilej(jpni,jpnj), ildj(jpni,jpnj), ioso(jpni,jpnj), iowe(jpni,jpnj),   &
+#if defined key_agrif
+                 lliswest(jpni,jpnj), lliseast(jpni,jpnj),  & 
+         &       llisnorth(jpni,jpnj),llissouth(jpni,jpnj), &
+#endif
+         &       STAT=ierr )
+      CALL mpp_sum( 'mppini', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'mpp_init: unable to allocate standard ocean arrays' )
+      
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() ) THEN       ! AGRIF children: specific setting (cf. agrif_user.F90)
+         IF( jpiglo /= nbcellsx + 2 + 2*nbghostcells )   &
+            CALL ctl_stop( 'STOP', 'mpp_init: Agrif children requires jpiglo == nbcellsx + 2 + 2*nbghostcells' )
+         IF( jpjglo /= nbcellsy + 2 + 2*nbghostcells )   &
+            CALL ctl_stop( 'STOP', 'mpp_init: Agrif children requires jpjglo == nbcellsy + 2 + 2*nbghostcells' )
+         IF( ln_use_jattr )   CALL ctl_stop( 'STOP', 'mpp_init:Agrif children requires ln_use_jattr = .false. ' )
+      ENDIF
+      lliswest(:,:) = .false. ; lliseast(:,:) = .false. ; llisnorth(:,:) = .false. ; llissouth(:,:) = .false.
+#endif
+      !
+      !  2. Index arrays for subdomains
+      ! -----------------------------------
+      !
+      nreci = 2 * nn_hls
+      nrecj = 2 * nn_hls
+      CALL mpp_basic_decomposition( jpni, jpnj, jpimax, jpjmax, iimppt, ijmppt, ilci, ilcj )
+      nfiimpp(:,:) = iimppt(:,:)
+      nfilcit(:,:) = ilci(:,:)
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'MPI Message Passing MPI - domain lay out over processors'
+         WRITE(numout,*)
+         WRITE(numout,*) '   defines mpp subdomains'
+         WRITE(numout,*) '      jpni = ', jpni  
+         WRITE(numout,*) '      jpnj = ', jpnj
+         WRITE(numout,*)
+         WRITE(numout,*) '      sum ilci(i,1) = ', sum(ilci(:,1)), ' jpiglo = ', jpiglo
+         WRITE(numout,*) '      sum ilcj(1,j) = ', sum(ilcj(1,:)), ' jpjglo = ', jpjglo
+      ENDIF
+     
+      ! 3. Subdomain description in the Regular Case
+      ! --------------------------------------------
+      ! specific cases where there is no communication -> must do the periodicity by itself
+      ! Warning: because of potential land-area suppression, do not use nbond[ij] == 2  
+      l_Iperio = jpni == 1 .AND. (jperio == 1 .OR. jperio == 4 .OR. jperio == 6 .OR. jperio == 7)
+      l_Jperio = jpnj == 1 .AND. (jperio == 2 .OR. jperio == 7)
+      
+      DO jarea = 1, jpni*jpnj
+         !
+         iarea0 = jarea - 1
+         ii = 1 + MOD(iarea0,jpni)
+         ij = 1 +     iarea0/jpni
+         ili = ilci(ii,ij)
+         ilj = ilcj(ii,ij)
+         ibondi(ii,ij) = 0                         ! default: has e-w neighbours
+         IF( ii   ==    1 )   ibondi(ii,ij) = -1   ! first column, has only e neighbour
+         IF( ii   == jpni )   ibondi(ii,ij) =  1   ! last column,  has only w neighbour
+         IF( jpni ==    1 )   ibondi(ii,ij) =  2   ! has no e-w neighbour
+         ibondj(ii,ij) = 0                         ! default: has n-s neighbours
+         IF( ij   ==    1 )   ibondj(ii,ij) = -1   ! first row, has only n neighbour
+         IF( ij   == jpnj )   ibondj(ii,ij) =  1   ! last row,  has only s neighbour
+         IF( jpnj ==    1 )   ibondj(ii,ij) =  2   ! has no n-s neighbour
+
+         ! Subdomain neighbors (get their zone number): default definition
+         ioso(ii,ij) = iarea0 - jpni
+         iowe(ii,ij) = iarea0 - 1
+         ioea(ii,ij) = iarea0 + 1
+         iono(ii,ij) = iarea0 + jpni
+         ildi(ii,ij) =  1  + nn_hls
+         ilei(ii,ij) = ili - nn_hls
+         ildj(ii,ij) =  1  + nn_hls
+         ilej(ii,ij) = ilj - nn_hls
+
+         ! East-West periodicity: change ibondi, ioea, iowe
+         IF( jperio == 1 .OR. jperio == 4 .OR. jperio == 6 .OR. jperio == 7 ) THEN
+            IF( jpni  /= 1 )   ibondi(ii,ij) = 0                        ! redefine: all have e-w neighbours
+            IF( ii ==    1 )   iowe(ii,ij) = iarea0 +        (jpni-1)   ! redefine: first column, address of w neighbour
+            IF( ii == jpni )   ioea(ii,ij) = iarea0 -        (jpni-1)   ! redefine: last column,  address of e neighbour
+         ENDIF
+
+         ! Simple North-South periodicity: change ibondj, ioso, iono
+         IF( jperio == 2 .OR. jperio == 7 ) THEN
+            IF( jpnj  /= 1 )   ibondj(ii,ij) = 0                        ! redefine: all have n-s neighbours
+            IF( ij ==    1 )   ioso(ii,ij) = iarea0 + jpni * (jpnj-1)   ! redefine: first row, address of s neighbour
+            IF( ij == jpnj )   iono(ii,ij) = iarea0 - jpni * (jpnj-1)   ! redefine: last row,  address of n neighbour
+         ENDIF
+
+         ! North fold: define ipolj, change iono. Warning: we do not change ibondj...
+         ipolj(ii,ij) = 0
+         IF( jperio == 3 .OR. jperio == 4 ) THEN
+            ijm1 = jpni*(jpnj-1)
+            imil = ijm1+(jpni+1)/2
+            IF( jarea > ijm1 ) ipolj(ii,ij) = 3
+            IF( MOD(jpni,2) == 1 .AND. jarea == imil ) ipolj(ii,ij) = 4
+            IF( ipolj(ii,ij) == 3 ) iono(ii,ij) = jpni*jpnj-jarea+ijm1   ! MPI rank of northern neighbour
+         ENDIF
+         IF( jperio == 5 .OR. jperio == 6 ) THEN
+            ijm1 = jpni*(jpnj-1)
+            imil = ijm1+(jpni+1)/2
+            IF( jarea > ijm1) ipolj(ii,ij) = 5
+            IF( MOD(jpni,2) == 1 .AND. jarea == imil ) ipolj(ii,ij) = 6
+            IF( ipolj(ii,ij) == 5) iono(ii,ij) = jpni*jpnj-jarea+ijm1    ! MPI rank of northern neighbour
+         ENDIF
+         !
+#if defined key_agrif
+         IF ((ibondi(ii,ij) ==  1).OR.(ibondi(ii,ij) == 2)) lliseast(ii,ij)  = .true.      ! east 
+         IF ((ibondi(ii,ij) == -1).OR.(ibondi(ii,ij) == 2)) lliswest(ii,ij)  = .true.      ! west 
+         IF ((ibondj(ii,ij) ==  1).OR.(ibondj(ii,ij) == 2)) llisnorth(ii,ij) = .true.      ! north 
+         IF ((ibondj(ii,ij) == -1).OR.(ibondj(ii,ij) == 2)) llissouth(ii,ij) = .true.      ! south 
+#endif
+      END DO
+      ! 4. deal with land subdomains
+      ! ----------------------------
+      !
+      ! specify which subdomains are oce subdomains; other are land subdomains
+      ipproc(:,:) = -1
+      icont = -1
+      DO jarea = 1, jpni*jpnj
+         iarea0 = jarea - 1
+         ii = 1 + MOD(iarea0,jpni)
+         ij = 1 +     iarea0/jpni
+         IF( llisoce(ii,ij) ) THEN
+            icont = icont + 1
+            ipproc(ii,ij) = icont
+            iin(icont+1) = ii
+            ijn(icont+1) = ij
+         ENDIF
+      END DO
+      ! if needed add some land subdomains to reach jpnij active subdomains
+      i2add = jpnij - inijmin
+      DO jarea = 1, jpni*jpnj
+         iarea0 = jarea - 1
+         ii = 1 + MOD(iarea0,jpni)
+         ij = 1 +     iarea0/jpni
+         IF( .NOT. llisoce(ii,ij) .AND. i2add > 0 ) THEN
+            icont = icont + 1
+            ipproc(ii,ij) = icont
+            iin(icont+1) = ii
+            ijn(icont+1) = ij
+            i2add = i2add - 1
+         ENDIF
+      END DO
+      nfipproc(:,:) = ipproc(:,:)
+
+      ! neighbour treatment: change ibondi, ibondj if next to a land zone
+      DO jarea = 1, jpni*jpnj
+         ii = 1 + MOD( jarea-1  , jpni )
+         ij = 1 +     (jarea-1) / jpni
+         ! land-only area with an active n neigbour
+         IF ( ipproc(ii,ij) == -1 .AND. 0 <= iono(ii,ij) .AND. iono(ii,ij) <= jpni*jpnj-1 ) THEN
+            iino = 1 + MOD( iono(ii,ij) , jpni )                    ! ii index of this n neigbour
+            ijno = 1 +      iono(ii,ij) / jpni                      ! ij index of this n neigbour
+            ! In case of north fold exchange: I am the n neigbour of my n neigbour!! (#1057)
+            ! --> for northern neighbours of northern row processors (in case of north-fold)
+            !     need to reverse the LOGICAL direction of communication 
+            idir = 1                                           ! we are indeed the s neigbour of this n neigbour
+            IF( ij == jpnj .AND. ijno == jpnj )   idir = -1    ! both are on the last row, we are in fact the n neigbour
+            IF( ibondj(iino,ijno) == idir     )   ibondj(iino,ijno) =   2     ! this n neigbour had only a s/n neigbour -> no more
+            IF( ibondj(iino,ijno) == 0        )   ibondj(iino,ijno) = -idir   ! this n neigbour had both, n-s neighbours -> keep 1
+         ENDIF
+         ! land-only area with an active s neigbour
+         IF( ipproc(ii,ij) == -1 .AND. 0 <= ioso(ii,ij) .AND. ioso(ii,ij) <= jpni*jpnj-1 ) THEN
+            iiso = 1 + MOD( ioso(ii,ij) , jpni )                    ! ii index of this s neigbour
+            ijso = 1 +      ioso(ii,ij) / jpni                      ! ij index of this s neigbour
+            IF( ibondj(iiso,ijso) == -1 )   ibondj(iiso,ijso) = 2   ! this s neigbour had only a n neigbour    -> no more neigbour
+            IF( ibondj(iiso,ijso) ==  0 )   ibondj(iiso,ijso) = 1   ! this s neigbour had both, n-s neighbours -> keep s neigbour
+         ENDIF
+         ! land-only area with an active e neigbour
+         IF( ipproc(ii,ij) == -1 .AND. 0 <= ioea(ii,ij) .AND. ioea(ii,ij) <= jpni*jpnj-1 ) THEN
+            iiea = 1 + MOD( ioea(ii,ij) , jpni )                    ! ii index of this e neigbour
+            ijea = 1 +      ioea(ii,ij) / jpni                      ! ij index of this e neigbour
+            IF( ibondi(iiea,ijea) == 1 )   ibondi(iiea,ijea) =  2   ! this e neigbour had only a w neigbour    -> no more neigbour
+            IF( ibondi(iiea,ijea) == 0 )   ibondi(iiea,ijea) = -1   ! this e neigbour had both, e-w neighbours -> keep e neigbour
+         ENDIF
+         ! land-only area with an active w neigbour
+         IF( ipproc(ii,ij) == -1 .AND. 0 <= iowe(ii,ij) .AND. iowe(ii,ij) <= jpni*jpnj-1) THEN
+            iiwe = 1 + MOD( iowe(ii,ij) , jpni )                    ! ii index of this w neigbour
+            ijwe = 1 +      iowe(ii,ij) / jpni                      ! ij index of this w neigbour
+            IF( ibondi(iiwe,ijwe) == -1 )   ibondi(iiwe,ijwe) = 2   ! this w neigbour had only a e neigbour    -> no more neigbour
+            IF( ibondi(iiwe,ijwe) ==  0 )   ibondi(iiwe,ijwe) = 1   ! this w neigbour had both, e-w neighbours -> keep w neigbour
+         ENDIF
+      END DO
+
+      ! Update il[de][ij] according to modified ibond[ij]
+      ! ----------------------
+      DO jproc = 1, jpnij
+         ii = iin(jproc)
+         ij = ijn(jproc)
+         IF( ibondi(ii,ij) == -1 .OR. ibondi(ii,ij) == 2 ) ildi(ii,ij) =  1
+         IF( ibondi(ii,ij) ==  1 .OR. ibondi(ii,ij) == 2 ) ilei(ii,ij) = ilci(ii,ij)
+         IF( ibondj(ii,ij) == -1 .OR. ibondj(ii,ij) == 2 ) ildj(ii,ij) =  1
+         IF( ibondj(ii,ij) ==  1 .OR. ibondj(ii,ij) == 2 ) ilej(ii,ij) = ilcj(ii,ij)
+      END DO
+      
+      ! 5. Subdomain print
+      ! ------------------
+      IF(lwp) THEN
+         ifreq = 4
+         il1 = 1
+         DO jn = 1, (jpni-1)/ifreq+1
+            il2 = MIN(jpni,il1+ifreq-1)
+            WRITE(numout,*)
+            WRITE(numout,9400) ('***',ji=il1,il2-1)
+            DO jj = jpnj, 1, -1
+               WRITE(numout,9403) ('   ',ji=il1,il2-1)
+               WRITE(numout,9402) jj, (ilci(ji,jj),ilcj(ji,jj),ji=il1,il2)
+               WRITE(numout,9404) (ipproc(ji,jj),ji=il1,il2)
+               WRITE(numout,9403) ('   ',ji=il1,il2-1)
+               WRITE(numout,9400) ('***',ji=il1,il2-1)
+            END DO
+            WRITE(numout,9401) (ji,ji=il1,il2)
+            il1 = il1+ifreq
+         END DO
+ 9400    FORMAT('           ***'   ,20('*************',a3)    )
+ 9403    FORMAT('           *     ',20('         *   ',a3)    )
+ 9401    FORMAT('              '   ,20('   ',i3,'          ') )
+ 9402    FORMAT('       ',i3,' *  ',20(i3,'  x',i3,'   *   ') )
+ 9404    FORMAT('           *  '   ,20('     ' ,i4,'   *   ') )
+      ENDIF
+         
+      ! just to save nono etc for all proc
+      ! warning ii*ij (zone) /= nproc (processors)!
+      ! ioso = zone number, ii_noso = proc number
+      ii_noso(:) = -1
+      ii_nono(:) = -1
+      ii_noea(:) = -1
+      ii_nowe(:) = -1 
+      DO jproc = 1, jpnij
+         ii = iin(jproc)
+         ij = ijn(jproc)
+         IF( 0 <= ioso(ii,ij) .AND. ioso(ii,ij) <= (jpni*jpnj-1) ) THEN
+            iiso = 1 + MOD( ioso(ii,ij) , jpni )
+            ijso = 1 +      ioso(ii,ij) / jpni
+            ii_noso(jproc) = ipproc(iiso,ijso)
+         ENDIF
+         IF( 0 <= iowe(ii,ij) .AND. iowe(ii,ij) <= (jpni*jpnj-1) ) THEN
+          iiwe = 1 + MOD( iowe(ii,ij) , jpni )
+          ijwe = 1 +      iowe(ii,ij) / jpni
+          ii_nowe(jproc) = ipproc(iiwe,ijwe)
+         ENDIF
+         IF( 0 <= ioea(ii,ij) .AND. ioea(ii,ij) <= (jpni*jpnj-1) ) THEN
+            iiea = 1 + MOD( ioea(ii,ij) , jpni )
+            ijea = 1 +      ioea(ii,ij) / jpni
+            ii_noea(jproc)= ipproc(iiea,ijea)
+         ENDIF
+         IF( 0 <= iono(ii,ij) .AND. iono(ii,ij) <= (jpni*jpnj-1) ) THEN
+            iino = 1 + MOD( iono(ii,ij) , jpni )
+            ijno = 1 +      iono(ii,ij) / jpni
+            ii_nono(jproc)= ipproc(iino,ijno)
+         ENDIF
+      END DO
+    
+      ! 6. Change processor name
+      ! ------------------------
+      ii = iin(narea)
+      ij = ijn(narea)
+      !
+      ! set default neighbours
+      noso = ii_noso(narea)
+      nowe = ii_nowe(narea)
+      noea = ii_noea(narea)
+      nono = ii_nono(narea)
+      nlci = ilci(ii,ij)  
+      nldi = ildi(ii,ij)
+      nlei = ilei(ii,ij)
+      nlcj = ilcj(ii,ij)  
+      nldj = ildj(ii,ij)
+      nlej = ilej(ii,ij)
+      nbondi = ibondi(ii,ij)
+      nbondj = ibondj(ii,ij)
+      nimpp = iimppt(ii,ij)  
+      njmpp = ijmppt(ii,ij)
+      jpi = nlci
+      jpj = nlcj
+      jpk = jpkglo                                             ! third dim
+#if defined key_agrif
+      ! simple trick to use same vertical grid as parent but different number of levels: 
+      ! Save maximum number of levels in jpkglo, then define all vertical grids with this number.
+      ! Suppress once vertical online interpolation is ok
+!!$      IF(.NOT.Agrif_Root())   jpkglo = Agrif_Parent( jpkglo )
+      l_Westedge  = lliswest(ii,ij)
+      l_Eastedge  = lliseast(ii,ij)
+      l_Northedge = llisnorth(ii,ij)
+      l_Southedge = llissouth(ii,ij) 
+#endif
+      jpim1 = jpi-1                                            ! inner domain indices
+      jpjm1 = jpj-1                                            !   "           "
+      jpkm1 = MAX( 1, jpk-1 )                                  !   "           "
+      jpij  = jpi*jpj                                          !  jpi x j
+      DO jproc = 1, jpnij
+         ii = iin(jproc)
+         ij = ijn(jproc)
+         nlcit(jproc) = ilci(ii,ij)
+         nldit(jproc) = ildi(ii,ij)
+         nleit(jproc) = ilei(ii,ij)
+         nlcjt(jproc) = ilcj(ii,ij)
+         nldjt(jproc) = ildj(ii,ij)
+         nlejt(jproc) = ilej(ii,ij)
+         ibonit(jproc) = ibondi(ii,ij)
+         ibonjt(jproc) = ibondj(ii,ij)
+         nimppt(jproc) = iimppt(ii,ij)  
+         njmppt(jproc) = ijmppt(ii,ij) 
+      END DO
+
+      ! Save processor layout in ascii file
+      IF (llwrtlay) THEN
+         CALL ctl_opn( inum, 'layout.dat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., narea )
+         WRITE(inum,'(a)') '   jpnij   jpimax  jpjmax    jpk  jpiglo  jpjglo'//&
+   &           ' ( local:    narea     jpi     jpj )'
+         WRITE(inum,'(6i8,a,3i8,a)') jpnij,jpimax,jpjmax,jpk,jpiglo,jpjglo,&
+   &           ' ( local: ',narea,jpi,jpj,' )'
+         WRITE(inum,'(a)') 'nproc nlci nlcj nldi nldj nlei nlej nimp njmp nono noso nowe noea nbondi nbondj '
+
+         DO jproc = 1, jpnij
+            WRITE(inum,'(13i5,2i7)')   jproc-1, nlcit  (jproc), nlcjt  (jproc),   &
+               &                                nldit  (jproc), nldjt  (jproc),   &
+               &                                nleit  (jproc), nlejt  (jproc),   &
+               &                                nimppt (jproc), njmppt (jproc),   & 
+               &                                ii_nono(jproc), ii_noso(jproc),   &
+               &                                ii_nowe(jproc), ii_noea(jproc),   &
+               &                                ibonit (jproc), ibonjt (jproc) 
+         END DO
+      END IF
+
+      !                          ! north fold parameter
+      ! Defined npolj, either 0, 3 , 4 , 5 , 6
+      ! In this case the important thing is that npolj /= 0
+      ! Because if we go through these line it is because jpni >1 and thus
+      ! we must use lbcnorthmpp, which tests only npolj =0 or npolj /= 0
+      npolj = 0
+      ij = ijn(narea)
+      IF( jperio == 3 .OR. jperio == 4 ) THEN
+         IF( ij == jpnj )   npolj = 3
+      ENDIF
+      IF( jperio == 5 .OR. jperio == 6 ) THEN
+         IF( ij == jpnj )   npolj = 5
+      ENDIF
+      !
+      nproc = narea-1
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   resulting internal parameters : '
+         WRITE(numout,*) '      nproc  = ', nproc
+         WRITE(numout,*) '      nowe   = ', nowe  , '   noea  =  ', noea
+         WRITE(numout,*) '      nono   = ', nono  , '   noso  =  ', noso
+         WRITE(numout,*) '      nbondi = ', nbondi
+         WRITE(numout,*) '      nbondj = ', nbondj
+         WRITE(numout,*) '      npolj  = ', npolj
+         WRITE(numout,*) '    l_Iperio = ', l_Iperio
+         WRITE(numout,*) '    l_Jperio = ', l_Jperio
+         WRITE(numout,*) '      nlci   = ', nlci
+         WRITE(numout,*) '      nlcj   = ', nlcj
+         WRITE(numout,*) '      nimpp  = ', nimpp
+         WRITE(numout,*) '      njmpp  = ', njmpp
+         WRITE(numout,*) '      nreci  = ', nreci  
+         WRITE(numout,*) '      nrecj  = ', nrecj  
+         WRITE(numout,*) '      nn_hls = ', nn_hls 
+      ENDIF
+
+      !                          ! Prepare mpp north fold
+      IF( jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ) THEN
+         CALL mpp_ini_north
+         IF (lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   North fold boundary prepared for jpni >1'
+            ! additional prints in layout.dat
+         ENDIF
+         IF (llwrtlay) THEN
+            WRITE(inum,*)
+            WRITE(inum,*)
+            WRITE(inum,*) 'number of subdomains located along the north fold : ', ndim_rank_north
+            WRITE(inum,*) 'Rank of the subdomains located along the north fold : ', ndim_rank_north
+            DO jproc = 1, ndim_rank_north, 5
+               WRITE(inum,*) nrank_north( jproc:MINVAL( (/jproc+4,ndim_rank_north/) ) )
+            END DO
+         ENDIF
+      ENDIF
+      !
+      CALL mpp_init_ioipsl       ! Prepare NetCDF output file (if necessary)
+      !      
+      IF (( jperio >= 3 .AND. jperio <= 6 .AND. jpni > 1 ).AND.( ln_nnogather )) THEN
+         CALL mpp_init_nfdcom     ! northfold neighbour lists
+         IF (llwrtlay) THEN
+            WRITE(inum,*)
+            WRITE(inum,*)
+            WRITE(inum,*) 'north fold exchanges with explicit point-to-point messaging :'
+            WRITE(inum,*) 'nfsloop : ', nfsloop
+            WRITE(inum,*) 'nfeloop : ', nfeloop
+            WRITE(inum,*) 'nsndto : ', nsndto
+            WRITE(inum,*) 'isendto : ', isendto
+         ENDIF
+      ENDIF
+      !
+      IF (llwrtlay) CLOSE(inum)   
+      !
+      DEALLOCATE(iin, ijn, ii_nono, ii_noea, ii_noso, ii_nowe,    &
+         &       iimppt, ijmppt, ibondi, ibondj, ipproc, ipolj,   &
+         &       ilci, ilcj, ilei, ilej, ildi, ildj,              &
+         &       iono, ioea, ioso, iowe, llisoce)
+#if defined key_agrif
+      DEALLOCATE(lliswest, lliseast, llisnorth, llissouth)
+#endif
+      !
+    END SUBROUTINE mpp_init
+
+
+    SUBROUTINE mpp_basic_decomposition( knbi, knbj, kimax, kjmax, kimppt, kjmppt, klci, klcj)
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_basic_decomposition  ***
+      !!                    
+      !! ** Purpose :   Lay out the global domain over processors.
+      !!
+      !! ** Method  :   Global domain is distributed in smaller local domains.
+      !!
+      !! ** Action : - set for all knbi*knbj domains:
+      !!                    kimppt     : longitudinal index
+      !!                    kjmppt     : latitudinal  index
+      !!                    klci       : first dimension
+      !!                    klcj       : second dimension
+      !!----------------------------------------------------------------------
+      INTEGER,                                 INTENT(in   ) ::   knbi, knbj
+      INTEGER,                                 INTENT(  out) ::   kimax, kjmax
+      INTEGER, DIMENSION(knbi,knbj), OPTIONAL, INTENT(  out) ::   kimppt, kjmppt
+      INTEGER, DIMENSION(knbi,knbj), OPTIONAL, INTENT(  out) ::   klci, klcj
+      !
+      INTEGER ::   ji, jj
+      INTEGER ::   iresti, irestj, irm, ijpjmin
+      INTEGER ::   ireci, irecj
+      !!----------------------------------------------------------------------
+      !
+#if defined key_nemocice_decomp
+      kimax = ( nx_global+2-2*nn_hls + (knbi-1) ) / knbi + 2*nn_hls    ! first  dim.
+      kjmax = ( ny_global+2-2*nn_hls + (knbj-1) ) / knbj + 2*nn_hls    ! second dim. 
+#else
+      kimax = ( jpiglo - 2*nn_hls + (knbi-1) ) / knbi + 2*nn_hls    ! first  dim.
+      kjmax = ( jpjglo - 2*nn_hls + (knbj-1) ) / knbj + 2*nn_hls    ! second dim.
+#endif
+      IF( .NOT. PRESENT(kimppt) ) RETURN
+      !
+      !  1. Dimension arrays for subdomains
+      ! -----------------------------------
+      !  Computation of local domain sizes klci() klcj()
+      !  These dimensions depend on global sizes knbi,knbj and jpiglo,jpjglo
+      !  The subdomains are squares lesser than or equal to the global
+      !  dimensions divided by the number of processors minus the overlap array.
+      !
+      ireci = 2 * nn_hls
+      irecj = 2 * nn_hls
+      iresti = 1 + MOD( jpiglo - ireci -1 , knbi )
+      irestj = 1 + MOD( jpjglo - irecj -1 , knbj )
+      !
+      !  Need to use kimax and kjmax here since jpi and jpj not yet defined
+#if defined key_nemocice_decomp
+      ! Change padding to be consistent with CICE
+      klci(1:knbi-1      ,:) = kimax
+      klci(knbi          ,:) = jpiglo - (knbi - 1) * (kimax - nreci)
+      klcj(:,      1:knbj-1) = kjmax
+      klcj(:,          knbj) = jpjglo - (knbj - 1) * (kjmax - nrecj)
+#else
+      klci(1:iresti      ,:) = kimax
+      klci(iresti+1:knbi ,:) = kimax-1
+      IF( MINVAL(klci) < 3 ) THEN
+         WRITE(ctmp1,*) '   mpp_basic_decomposition: minimum value of jpi must be >= 3'
+         WRITE(ctmp2,*) '   We have ', MINVAL(klci)
+        CALL ctl_stop( 'STOP', ctmp1, ctmp2 )
+      ENDIF
+      IF( jperio == 3 .OR. jperio == 4 .OR. jperio == 5 .OR. jperio == 6 ) THEN
+         ! minimize the size of the last row to compensate for the north pole folding coast
+         IF( jperio == 3 .OR. jperio == 4 )   ijpjmin = 5   ! V and F folding involves line jpj-3 that must not be south boundary
+         IF( jperio == 5 .OR. jperio == 6 )   ijpjmin = 4   ! V and F folding involves line jpj-2 that must not be south boundary
+         irm = knbj - irestj                                    ! total number of lines to be removed
+         klcj(:,            knbj) = MAX( ijpjmin, kjmax-irm )   ! we must have jpj >= ijpjmin in the last row
+         irm = irm - ( kjmax - klcj(1,knbj) )                   ! remaining number of lines to remove 
+         irestj = knbj - 1 - irm                        
+         klcj(:,        1:irestj) = kjmax
+         klcj(:, irestj+1:knbj-1) = kjmax-1
+      ELSE
+         ijpjmin = 3
+         klcj(:,      1:irestj) = kjmax
+         klcj(:, irestj+1:knbj) = kjmax-1
+      ENDIF
+      IF( MINVAL(klcj) < ijpjmin ) THEN
+         WRITE(ctmp1,*) '   mpp_basic_decomposition: minimum value of jpj must be >= ', ijpjmin
+         WRITE(ctmp2,*) '   We have ', MINVAL(klcj)
+         CALL ctl_stop( 'STOP', ctmp1, ctmp2 )
+      ENDIF
+#endif
+
+      !  2. Index arrays for subdomains
+      ! -------------------------------
+      kimppt(:,:) = 1
+      kjmppt(:,:) = 1
+      !
+      IF( knbi > 1 ) THEN
+         DO jj = 1, knbj
+            DO ji = 2, knbi
+               kimppt(ji,jj) = kimppt(ji-1,jj) + klci(ji-1,jj) - ireci
+            END DO
+         END DO
+      ENDIF
+      !
+      IF( knbj > 1 )THEN
+         DO jj = 2, knbj
+            DO ji = 1, knbi
+               kjmppt(ji,jj) = kjmppt(ji,jj-1) + klcj(ji,jj-1) - irecj
+            END DO
+         END DO
+      ENDIF
+      
+   END SUBROUTINE mpp_basic_decomposition
+
+
+   SUBROUTINE mpp_init_bestpartition( knbij, knbi, knbj, knbcnt, ldlist )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE mpp_init_bestpartition  ***
+      !!
+      !! ** Purpose :
+      !!
+      !! ** Method  :
+      !!----------------------------------------------------------------------
+      INTEGER,           INTENT(in   ) ::   knbij         ! total number if subdomains               (knbi*knbj)
+      INTEGER, OPTIONAL, INTENT(  out) ::   knbi, knbj    ! number if subdomains along i and j (knbi and knbj)
+      INTEGER, OPTIONAL, INTENT(  out) ::   knbcnt        ! number of land subdomains
+      LOGICAL, OPTIONAL, INTENT(in   ) ::   ldlist        ! .true.: print the list the best domain decompositions (with land)
+      !
+      INTEGER :: ji, jj, ii, iitarget
+      INTEGER :: iszitst, iszjtst
+      INTEGER :: isziref, iszjref
+      INTEGER :: inbij, iszij
+      INTEGER :: inbimax, inbjmax, inbijmax, inbijold
+      INTEGER :: isz0, isz1
+      INTEGER, DIMENSION(  :), ALLOCATABLE :: indexok
+      INTEGER, DIMENSION(  :), ALLOCATABLE :: inbi0, inbj0, inbij0   ! number of subdomains along i,j
+      INTEGER, DIMENSION(  :), ALLOCATABLE :: iszi0, iszj0, iszij0   ! max size of the subdomains along i,j
+      INTEGER, DIMENSION(  :), ALLOCATABLE :: inbi1, inbj1, inbij1   ! number of subdomains along i,j
+      INTEGER, DIMENSION(  :), ALLOCATABLE :: iszi1, iszj1, iszij1   ! max size of the subdomains along i,j
+      LOGICAL :: llist
+      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: llmsk2d                 ! max size of the subdomains along i,j
+      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: llisoce              !  -     -
+      REAL(wp)::   zpropland
+      !!----------------------------------------------------------------------
+      !
+      llist = .FALSE.
+      IF( PRESENT(ldlist) ) llist = ldlist
+
+      CALL mpp_init_landprop( zpropland )                      ! get the proportion of land point over the gloal domain
+      inbij = NINT( REAL(knbij, wp) / ( 1.0 - zpropland ) )    ! define the largest possible value for jpni*jpnj
+      !
+      IF( llist ) THEN   ;   inbijmax = inbij*2
+      ELSE               ;   inbijmax = inbij
+      ENDIF
+      !
+      ALLOCATE(inbi0(inbijmax),inbj0(inbijmax),iszi0(inbijmax),iszj0(inbijmax))
+      !
+      inbimax = 0
+      inbjmax = 0
+      isziref = jpiglo*jpjglo+1
+      iszjref = jpiglo*jpjglo+1
+      !
+      ! get the list of knbi that gives a smaller jpimax than knbi-1
+      ! get the list of knbj that gives a smaller jpjmax than knbj-1
+      DO ji = 1, inbijmax      
+#if defined key_nemocice_decomp
+         iszitst = ( nx_global+2-2*nn_hls + (ji-1) ) / ji + 2*nn_hls    ! first  dim.
+#else
+         iszitst = ( jpiglo - 2*nn_hls + (ji-1) ) / ji + 2*nn_hls
+#endif
+         IF( iszitst < isziref ) THEN
+            isziref = iszitst
+            inbimax = inbimax + 1
+            inbi0(inbimax) = ji
+            iszi0(inbimax) = isziref
+         ENDIF
+#if defined key_nemocice_decomp
+         iszjtst = ( ny_global+2-2*nn_hls + (ji-1) ) / ji + 2*nn_hls    ! first  dim.
+#else
+         iszjtst = ( jpjglo - 2*nn_hls + (ji-1) ) / ji + 2*nn_hls
+#endif
+         IF( iszjtst < iszjref ) THEN
+            iszjref = iszjtst
+            inbjmax = inbjmax + 1
+            inbj0(inbjmax) = ji
+            iszj0(inbjmax) = iszjref
+         ENDIF
+      END DO
+
+      ! combine these 2 lists to get all possible knbi*knbj <  inbijmax
+      ALLOCATE( llmsk2d(inbimax,inbjmax) )
+      DO jj = 1, inbjmax
+         DO ji = 1, inbimax
+            IF ( inbi0(ji) * inbj0(jj) <= inbijmax ) THEN   ;   llmsk2d(ji,jj) = .TRUE.
+            ELSE                                            ;   llmsk2d(ji,jj) = .FALSE.
+            ENDIF
+         END DO
+      END DO
+      isz1 = COUNT(llmsk2d)
+      ALLOCATE( inbi1(isz1), inbj1(isz1), iszi1(isz1), iszj1(isz1) )
+      ii = 0
+      DO jj = 1, inbjmax
+         DO ji = 1, inbimax
+            IF( llmsk2d(ji,jj) .EQV. .TRUE. ) THEN
+               ii = ii + 1
+               inbi1(ii) = inbi0(ji)
+               inbj1(ii) = inbj0(jj)
+               iszi1(ii) = iszi0(ji)
+               iszj1(ii) = iszj0(jj)
+            END IF
+         END DO
+      END DO
+      DEALLOCATE( inbi0, inbj0, iszi0, iszj0 )
+      DEALLOCATE( llmsk2d )
+
+      ALLOCATE( inbij1(isz1), iszij1(isz1) )
+      inbij1(:) = inbi1(:) * inbj1(:)
+      iszij1(:) = iszi1(:) * iszj1(:)
+
+      ! if therr is no land and no print
+      IF( .NOT. llist .AND. numbot == -1 .AND. numbdy == -1 ) THEN
+         ! get the smaller partition which gives the smallest subdomain size
+         ii = MINLOC(inbij1, mask = iszij1 == MINVAL(iszij1), dim = 1)
+         knbi = inbi1(ii)
+         knbj = inbj1(ii)
+         IF(PRESENT(knbcnt))   knbcnt = 0
+         DEALLOCATE( inbi1, inbj1, inbij1, iszi1, iszj1, iszij1 )
+         RETURN
+      ENDIF
+
+      ! extract only the partitions which reduce the subdomain size in comparison with smaller partitions
+      ALLOCATE( indexok(isz1) )                                 ! to store indices of the best partitions
+      isz0 = 0                                                  ! number of best partitions     
+      inbij = 1                                                 ! start with the min value of inbij1 => 1
+      iszij = jpiglo*jpjglo+1                                   ! default: larger than global domain
+      DO WHILE( inbij <= inbijmax )                             ! if we did not reach the max of inbij1
+         ii = MINLOC(iszij1, mask = inbij1 == inbij, dim = 1)   ! warning: send back the first occurence if multiple results
+         IF ( iszij1(ii) < iszij ) THEN
+            isz0 = isz0 + 1
+            indexok(isz0) = ii
+            iszij = iszij1(ii)
+         ENDIF
+         inbij = MINVAL(inbij1, mask = inbij1 > inbij)   ! warning: return largest integer value if mask = .false. everywhere
+      END DO
+      DEALLOCATE( inbij1, iszij1 )
+
+      ! keep only the best partitions (sorted by increasing order of subdomains number and decreassing subdomain size)
+      ALLOCATE( inbi0(isz0), inbj0(isz0), iszi0(isz0), iszj0(isz0) )
+      DO ji = 1, isz0
+         ii = indexok(ji)
+         inbi0(ji) = inbi1(ii)
+         inbj0(ji) = inbj1(ii)
+         iszi0(ji) = iszi1(ii)
+         iszj0(ji) = iszj1(ii)
+      END DO
+      DEALLOCATE( indexok, inbi1, inbj1, iszi1, iszj1 )
+
+      IF( llist ) THEN
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '                  For your information:'
+            WRITE(numout,*) '  list of the best partitions including land supression'
+            WRITE(numout,*) '  -----------------------------------------------------'
+            WRITE(numout,*)
+         END IF
+         ji = isz0   ! initialization with the largest value
+         ALLOCATE( llisoce(inbi0(ji), inbj0(ji)) )
+         CALL mpp_init_isoce( inbi0(ji), inbj0(ji), llisoce ) ! Warning: must be call by all cores (call mpp_sum)
+         inbijold = COUNT(llisoce)
+         DEALLOCATE( llisoce )
+         DO ji =isz0-1,1,-1
+            ALLOCATE( llisoce(inbi0(ji), inbj0(ji)) )
+            CALL mpp_init_isoce( inbi0(ji), inbj0(ji), llisoce ) ! Warning: must be call by all cores (call mpp_sum)
+            inbij = COUNT(llisoce)
+            DEALLOCATE( llisoce )
+            IF(lwp .AND. inbij < inbijold) THEN
+               WRITE(numout,'(a, i6, a, i6, a, f4.1, a, i9, a, i6, a, i6, a)')                                 &
+                  &   'nb_cores oce: ', inbij, ', land domains excluded: ', inbi0(ji)*inbj0(ji) - inbij,       &
+                  &   ' (', REAL(inbi0(ji)*inbj0(ji) - inbij,wp) / REAL(inbi0(ji)*inbj0(ji),wp) *100.,         &
+                  &   '%), largest oce domain: ', iszi0(ji)*iszj0(ji), ' ( ', iszi0(ji),' x ', iszj0(ji), ' )'
+               inbijold = inbij
+            END IF
+         END DO
+         DEALLOCATE( inbi0, inbj0, iszi0, iszj0 )
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*)  '  -----------------------------------------------------------'
+         ENDIF
+         CALL mppsync
+         CALL mppstop( ld_abort = .TRUE. )
+      ENDIF
+      
+      DEALLOCATE( iszi0, iszj0 )
+      inbij = inbijmax + 1        ! default: larger than possible
+      ii = isz0+1                 ! start from the end of the list (smaller subdomains)
+      DO WHILE( inbij > knbij )   ! while the number of ocean subdomains exceed the number of procs
+         ii = ii -1 
+         ALLOCATE( llisoce(inbi0(ii), inbj0(ii)) )
+         CALL mpp_init_isoce( inbi0(ii), inbj0(ii), llisoce )            ! must be done by all core
+         inbij = COUNT(llisoce)
+         DEALLOCATE( llisoce )
+      END DO
+      knbi = inbi0(ii)
+      knbj = inbj0(ii)
+      IF(PRESENT(knbcnt))   knbcnt = knbi * knbj - inbij
+      DEALLOCATE( inbi0, inbj0 )
+      !
+   END SUBROUTINE mpp_init_bestpartition
+   
+   
+   SUBROUTINE mpp_init_landprop( propland )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init_landprop  ***
+      !!
+      !! ** Purpose : the the proportion of land points in the surface land-sea mask
+      !!
+      !! ** Method  : read iproc strips (of length jpiglo) of the land-sea mask
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(  out) :: propland    ! proportion of land points in the global domain (between 0 and 1)
+      !
+      INTEGER, DIMENSION(jpni*jpnj) ::   kusedom_1d
+      INTEGER :: inboce, iarea
+      INTEGER :: iproc, idiv, ijsz
+      INTEGER :: ijstr
+      LOGICAL, ALLOCATABLE, DIMENSION(:,:) ::   lloce
+      !!----------------------------------------------------------------------
+      ! do nothing if there is no land-sea mask
+      IF( numbot == -1 .and. numbdy == -1 ) THEN
+         propland = 0.
+         RETURN
+      ENDIF
+
+      ! number of processes reading the bathymetry file 
+      iproc = MINVAL( (/mppsize, jpjglo/2, 100/) )  ! read a least 2 lines, no more that 100 processes reading at the same time
+      
+      ! we want to read iproc strips of the land-sea mask. -> pick up iproc processes every idiv processes starting at 1
+      IF( iproc == 1 ) THEN   ;   idiv = mppsize
+      ELSE                    ;   idiv = ( mppsize - 1 ) / ( iproc - 1 )
+      ENDIF
+
+      iarea = (narea-1)/idiv   ! involed process number (starting counting at 0)
+      IF( MOD( narea-1, idiv ) == 0 .AND. iarea < iproc ) THEN   ! beware idiv can be = to 1
+         !
+         ijsz = jpjglo / iproc                                               ! width of the stripe to read
+         IF( iarea < MOD(jpjglo,iproc) ) ijsz = ijsz + 1
+         ijstr = iarea*(jpjglo/iproc) + MIN(iarea, MOD(jpjglo,iproc)) + 1    ! starting j position of the reading
+         !
+         ALLOCATE( lloce(jpiglo, ijsz) )                                     ! allocate the strip
+         CALL mpp_init_readbot_strip( ijstr, ijsz, lloce )
+         inboce = COUNT(lloce)                                               ! number of ocean point in the stripe
+         DEALLOCATE(lloce)
+         !
+      ELSE
+         inboce = 0
+      ENDIF
+      CALL mpp_sum( 'mppini', inboce )   ! total number of ocean points over the global domain
+      !
+      propland = REAL( jpiglo*jpjglo - inboce, wp ) / REAL( jpiglo*jpjglo, wp ) 
+      !
+   END SUBROUTINE mpp_init_landprop
+   
+   
+   SUBROUTINE mpp_init_isoce( knbi, knbj, ldisoce )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init_nboce  ***
+      !!
+      !! ** Purpose : check for a mpi domain decomposition knbi x knbj which
+      !!              subdomains contain at least 1 ocean point
+      !!
+      !! ** Method  : read knbj strips (of length jpiglo) of the land-sea mask
+      !!----------------------------------------------------------------------
+      INTEGER,                       INTENT(in   ) ::   knbi, knbj     ! domain decomposition
+      LOGICAL, DIMENSION(knbi,knbj), INTENT(  out) ::   ldisoce        ! .true. if a sub domain constains 1 ocean point 
+      !
+      INTEGER, DIMENSION(knbi,knbj) ::   inboce                        ! number oce oce pint in each mpi subdomain
+      INTEGER, DIMENSION(knbi*knbj) ::   inboce_1d
+      INTEGER :: idiv, iimax, ijmax, iarea
+      INTEGER :: ji, jn
+      LOGICAL, ALLOCATABLE, DIMENSION(:,:) ::   lloce                  ! lloce(i,j) = .true. if the point (i,j) is ocean 
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   iimppt, ilci
+      INTEGER, ALLOCATABLE, DIMENSION(:,:) ::   ijmppt, ilcj
+      !!----------------------------------------------------------------------
+      ! do nothing if there is no land-sea mask
+      IF( numbot == -1 .AND. numbdy == -1 ) THEN
+         ldisoce(:,:) = .TRUE.
+         RETURN
+      ENDIF
+
+      ! we want to read knbj strips of the land-sea mask. -> pick up knbj processes every idiv processes starting at 1
+      IF           ( knbj == 1 ) THEN   ;   idiv = mppsize
+      ELSE IF ( mppsize < knbj ) THEN   ;   idiv = 1
+      ELSE                              ;   idiv = ( mppsize - 1 ) / ( knbj - 1 )
+      ENDIF
+      inboce(:,:) = 0          ! default no ocean point found
+
+      DO jn = 0, (knbj-1)/mppsize   ! if mppsize < knbj : more strips than mpi processes (because of potential land domains)
+         !
+         iarea = (narea-1)/idiv + jn * mppsize   ! involed process number (starting counting at 0)
+         IF( MOD( narea-1, idiv ) == 0 .AND. iarea < knbj ) THEN   ! beware idiv can be = to 1
+            !
+            ALLOCATE( iimppt(knbi,knbj), ijmppt(knbi,knbj), ilci(knbi,knbj), ilcj(knbi,knbj) )
+            CALL mpp_basic_decomposition( knbi, knbj, iimax, ijmax, iimppt, ijmppt, ilci, ilcj )
+            !
+            ALLOCATE( lloce(jpiglo, ilcj(1,iarea+1)) )                                         ! allocate the strip
+            CALL mpp_init_readbot_strip( ijmppt(1,iarea+1), ilcj(1,iarea+1), lloce )           ! read the strip
+            DO  ji = 1, knbi
+               inboce(ji,iarea+1) = COUNT( lloce(iimppt(ji,1):iimppt(ji,1)+ilci(ji,1)-1,:) )   ! number of ocean point in subdomain
+            END DO
+            !
+            DEALLOCATE(lloce)
+            DEALLOCATE(iimppt, ijmppt, ilci, ilcj)
+            !
+         ENDIF
+      END DO
+   
+      inboce_1d = RESHAPE(inboce, (/ knbi*knbj /))
+      CALL mpp_sum( 'mppini', inboce_1d )
+      inboce = RESHAPE(inboce_1d, (/knbi, knbj/))
+      ldisoce(:,:) = inboce(:,:) /= 0
+      !
+   END SUBROUTINE mpp_init_isoce
+   
+   
+   SUBROUTINE mpp_init_readbot_strip( kjstr, kjcnt, ldoce )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init_readbot_strip  ***
+      !!
+      !! ** Purpose : Read relevant bathymetric information in order to
+      !!              provide a land/sea mask used for the elimination
+      !!              of land domains, in an mpp computation.
+      !!
+      !! ** Method  : read stipe of size (jpiglo,...)
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) :: kjstr       ! starting j position of the reading
+      INTEGER                         , INTENT(in   ) :: kjcnt       ! number of lines to read
+      LOGICAL, DIMENSION(jpiglo,kjcnt), INTENT(  out) :: ldoce       ! ldoce(i,j) = .true. if the point (i,j) is ocean 
+      !
+      INTEGER                           ::   inumsave                ! local logical unit
+      REAL(wp), DIMENSION(jpiglo,kjcnt) ::   zbot, zbdy 
+      !!----------------------------------------------------------------------
+      !
+      inumsave = numout   ;   numout = numnul   !   redirect all print to /dev/null
+      !
+      IF( numbot /= -1 ) THEN
+         CALL iom_get( numbot, jpdom_unknown, 'bottom_level', zbot, kstart = (/1,kjstr/), kcount = (/jpiglo, kjcnt/) )
+      ELSE
+         zbot(:,:) = 1.                         ! put a non-null value
+      ENDIF
+
+       IF( numbdy /= -1 ) THEN                  ! Adjust with bdy_msk if it exists    
+         CALL iom_get ( numbdy, jpdom_unknown, 'bdy_msk', zbdy, kstart = (/1,kjstr/), kcount = (/jpiglo, kjcnt/) )
+         zbot(:,:) = zbot(:,:) * zbdy(:,:)
+      ENDIF
+      !
+      ldoce(:,:) = zbot(:,:) > 0.
+      numout = inumsave
+      !
+   END SUBROUTINE mpp_init_readbot_strip
+
+
+   SUBROUTINE mpp_init_ioipsl
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE mpp_init_ioipsl  ***
+      !!
+      !! ** Purpose :   
+      !!
+      !! ** Method  :   
+      !!
+      !! History :
+      !!   9.0  !  04-03  (G. Madec )  MPP-IOIPSL 
+      !!   " "  !  08-12  (A. Coward)  addition in case of jpni*jpnj < jpnij
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(2) ::   iglo, iloc, iabsf, iabsl, ihals, ihale, idid
+      !!----------------------------------------------------------------------
+
+      ! The domain is split only horizontally along i- or/and j- direction
+      ! So we need at the most only 1D arrays with 2 elements.
+      ! Set idompar values equivalent to the jpdom_local_noextra definition
+      ! used in IOM. This works even if jpnij .ne. jpni*jpnj.
+      iglo(1) = jpiglo
+      iglo(2) = jpjglo
+      iloc(1) = nlci
+      iloc(2) = nlcj
+      iabsf(1) = nimppt(narea)
+      iabsf(2) = njmppt(narea)
+      iabsl(:) = iabsf(:) + iloc(:) - 1
+      ihals(1) = nldi - 1
+      ihals(2) = nldj - 1
+      ihale(1) = nlci - nlei
+      ihale(2) = nlcj - nlej
+      idid(1) = 1
+      idid(2) = 2
+
+      IF(lwp) THEN
+          WRITE(numout,*)
+          WRITE(numout,*) 'mpp_init_ioipsl :   iloc  = ', iloc (1), iloc (2)
+          WRITE(numout,*) '~~~~~~~~~~~~~~~     iabsf = ', iabsf(1), iabsf(2)
+          WRITE(numout,*) '                    ihals = ', ihals(1), ihals(2)
+          WRITE(numout,*) '                    ihale = ', ihale(1), ihale(2)
+      ENDIF
+      !
+      CALL flio_dom_set ( jpnij, nproc, idid, iglo, iloc, iabsf, iabsl, ihals, ihale, 'BOX', nidom)
+      !
+   END SUBROUTINE mpp_init_ioipsl  
+
+
+   SUBROUTINE mpp_init_nfdcom
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE  mpp_init_nfdcom  ***
+      !! ** Purpose :   Setup for north fold exchanges with explicit 
+      !!                point-to-point messaging
+      !!
+      !! ** Method :   Initialization of the northern neighbours lists.
+      !!----------------------------------------------------------------------
+      !!    1.0  ! 2011-10  (A. C. Coward, NOCS & J. Donners, PRACE)
+      !!    2.0  ! 2013-06 Setup avoiding MPI communication (I. Epicoco, S. Mocavero, CMCC) 
+      !!----------------------------------------------------------------------
+      INTEGER  ::   sxM, dxM, sxT, dxT, jn
+      INTEGER  ::   njmppmax
+      !!----------------------------------------------------------------------
+      !
+      njmppmax = MAXVAL( njmppt )
+      !
+      !initializes the north-fold communication variables
+      isendto(:) = 0
+      nsndto     = 0
+      !
+      IF ( njmpp == njmppmax ) THEN      ! if I am a process in the north
+         !
+         !sxM is the first point (in the global domain) needed to compute the north-fold for the current process
+         sxM = jpiglo - nimppt(narea) - nlcit(narea) + 1
+         !dxM is the last point (in the global domain) needed to compute the north-fold for the current process
+         dxM = jpiglo - nimppt(narea) + 2
+         !
+         ! loop over the other north-fold processes to find the processes
+         ! managing the points belonging to the sxT-dxT range
+         !
+         DO jn = 1, jpni
+            !
+            sxT = nfiimpp(jn, jpnj)                            ! sxT = 1st  point (in the global domain) of the jn process
+            dxT = nfiimpp(jn, jpnj) + nfilcit(jn, jpnj) - 1    ! dxT = last point (in the global domain) of the jn process
+            !
+            IF    ( sxT < sxM  .AND.  sxM < dxT ) THEN
+               nsndto          = nsndto + 1
+               isendto(nsndto) = jn
+            ELSEIF( sxM <= sxT  .AND.  dxM >= dxT ) THEN
+               nsndto          = nsndto + 1
+               isendto(nsndto) = jn
+            ELSEIF( dxM <  dxT  .AND.  sxT <  dxM ) THEN
+               nsndto          = nsndto + 1
+               isendto(nsndto) = jn
+            ENDIF
+            !
+         END DO
+         nfsloop = 1
+         nfeloop = nlci
+         DO jn = 2,jpni-1
+            IF( nfipproc(jn,jpnj) == (narea - 1) ) THEN
+               IF( nfipproc(jn-1,jpnj) == -1 )   nfsloop = nldi
+               IF( nfipproc(jn+1,jpnj) == -1 )   nfeloop = nlei
+            ENDIF
+         END DO
+         !
+      ENDIF
+      l_north_nogather = .TRUE.
+      !
+   END SUBROUTINE mpp_init_nfdcom
+
+
+#endif
+
+   !!======================================================================
+END MODULE mppini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfc1d_c2d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfc1d_c2d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfc1d_c2d.F90	(revision 14097)
@@ -0,0 +1,168 @@
+MODULE ldfc1d_c2d
+   !!======================================================================
+   !!                    ***  MODULE  ldfc1d_c2d  ***
+   !! Ocean physics:  profile and horizontal shape of lateral eddy coefficients 
+   !!=====================================================================
+   !! History :  3.7  ! 2013-12  (G. Madec)  restructuration/simplification of aht/aeiv specification,
+   !!                 !                      add velocity dependent coefficient and optional read in file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ldf_c1d       : ah reduced by 1/4 on the vertical (tanh profile, inflection at 300m) 
+   !!   ldf_c2d       : ah = F(e1,e2) (laplacian or = F(e1^3,e2^3) (bilaplacian)
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ldf_c1d   ! called by ldftra and ldfdyn modules
+   PUBLIC   ldf_c2d   ! called by ldftra and ldfdyn modules
+
+   REAL(wp) ::   r1_2  = 0.5_wp           ! =1/2
+   REAL(wp) ::   r1_4  = 0.25_wp          ! =1/4
+   REAL(wp) ::   r1_12 = 1._wp / 12._wp   ! =1/12
+ 
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ldf_c1d( cd_type, pahs1, pahs2, pah1, pah2 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_c1d  ***
+      !!              
+      !! ** Purpose :   1D eddy diffusivity/viscosity coefficients
+      !!
+      !! ** Method  :   1D eddy diffusivity coefficients F( depth )
+      !!                Reduction by zratio from surface to bottom 
+      !!                hyperbolic tangent profile with inflection point 
+      !!                at zh=500m and a width of zw=200m
+      !!
+      !!   cd_type = TRA      pah1, pah2 defined at U- and V-points
+      !!             DYN      pah1, pah2 defined at T- and F-points
+      !!----------------------------------------------------------------------
+      CHARACTER(len=3)                , INTENT(in   ) ::   cd_type        ! DYNamique or TRAcers
+      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(in   ) ::   pahs1, pahs2   ! surface value of eddy coefficient   [m2/s]
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pah1 , pah2    ! eddy coefficient                    [m2/s]
+      !
+      INTEGER  ::   ji, jj, jk      ! dummy loop indices
+      REAL(wp) ::   zh, zc, zdep1   ! local scalars
+      REAL(wp) ::   zw    , zdep2   !   -      -
+      REAL(wp) ::   zratio          !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   ldf_c1d : set a given profile to eddy mixing coefficients'
+      !
+      ! initialization of the profile
+      zratio = 0.25_wp           ! surface/bottom ratio
+      zh =  500._wp              ! depth    of the inflection point [m]
+      zw =  1._wp / 200._wp      ! width^-1     -        -      -   [1/m]
+      !                          ! associated coefficient           [-]
+      zc = ( 1._wp - zratio ) / ( 1._wp + TANH( zh * zw) )
+      !
+      !
+      SELECT CASE( cd_type )        ! point of calculation
+      !
+      CASE( 'DYN' )                     ! T- and F-points
+         DO jk = jpkm1, 1, -1                ! pah1 at T-point
+            pah1(:,:,jk) = pahs1(:,:) * (  zratio + zc * ( 1._wp + TANH( - ( gdept_0(:,:,jk) - zh ) * zw) )  )
+         END DO
+         DO jk = jpkm1, 1, -1                ! pah2 at F-point (zdep2 is an approximation in zps-coord.)
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zdep2 = (  gdept_0(ji,jj+1,jk) + gdept_0(ji+1,jj+1,jk)   &
+                     &     + gdept_0(ji,jj  ,jk) + gdept_0(ji+1,jj  ,jk)  ) * r1_4
+                  pah2(ji,jj,jk) = pahs2(ji,jj) * (  zratio + zc * ( 1._wp + TANH( - ( zdep2 - zh ) * zw) )  )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'ldfc1d_c2d', pah2, 'F', 1. )   ! Lateral boundary conditions
+         !
+      CASE( 'TRA' )                     ! U- and V-points (zdep1 & 2 are an approximation in zps-coord.)
+         DO jk = jpkm1, 1, -1
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zdep1 = (  gdept_0(ji,jj,jk) + gdept_0(ji+1,jj,jk)  ) * 0.5_wp
+                  zdep2 = (  gdept_0(ji,jj,jk) + gdept_0(ji,jj+1,jk)  ) * 0.5_wp
+                  pah1(ji,jj,jk) = pahs1(ji,jj) * (  zratio + zc * ( 1._wp + TANH( - ( zdep1 - zh ) * zw) )  )
+                  pah2(ji,jj,jk) = pahs2(ji,jj) * (  zratio + zc * ( 1._wp + TANH( - ( zdep2 - zh ) * zw) )  )
+               END DO
+            END DO
+         END DO
+         ! Lateral boundary conditions
+         CALL lbc_lnk_multi( 'ldfc1d_c2d', pah1, 'U', 1. , pah2, 'V', 1. )   
+         !
+      CASE DEFAULT                        ! error
+         CALL ctl_stop( 'ldf_c1d: ', cd_type, ' Unknown, i.e. /= DYN or TRA' )
+      END SELECT
+      !
+   END SUBROUTINE ldf_c1d
+
+
+   SUBROUTINE ldf_c2d( cd_type, pUfac, knn, pah1, pah2 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_c2d  ***
+      !!              
+      !! ** Purpose :   2D eddy diffusivity/viscosity coefficients
+      !!
+      !! ** Method  :   2D eddy diffusivity coefficients F( e1 , e2 )
+      !!       laplacian   operator :   ah proportional to the scale factor      [m2/s]
+      !!       bilaplacian operator :   ah proportional to the (scale factor)^3  [m4/s]
+      !!       In both cases, pah0 is the maximum value reached by the coefficient 
+      !!       at the Equator in case of e1=ra*rad= ~111km, not over the whole domain.
+      !!
+      !!   cd_type = TRA      pah1, pah2 defined at U- and V-points
+      !!             DYN      pah1, pah2 defined at T- and F-points
+      !!----------------------------------------------------------------------
+      CHARACTER(len=3)          , INTENT(in   ) ::   cd_type      ! DYNamique or TRAcers
+      REAL(wp)                  , INTENT(in   ) ::   pUfac        ! =1/2*Uc LAPlacian BiLaPlacian
+      INTEGER                   , INTENT(in   ) ::   knn          ! characteristic velocity   [m/s]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pah1, pah2   ! eddy coefficients         [m2/s or m4/s]
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   inn          ! local integer
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   ldf_c2d :   aht = Ufac * max(e1,e2)   with Ufac = ', pUfac, ' m/s'
+      !
+      !
+      SELECT CASE( cd_type )        !==  surface values  ==!  (chosen grid point function of DYN or TRA)
+      !
+      CASE( 'DYN' )                       ! T- and F-points
+         DO jj = 1, jpj
+            DO ji = 1, jpi 
+               pah1(ji,jj,1) = pUfac * MAX( e1t(ji,jj) , e2t(ji,jj) )**knn
+               pah2(ji,jj,1) = pUfac * MAX( e1f(ji,jj) , e2f(ji,jj) )**knn
+            END DO
+         END DO
+      CASE( 'TRA' )                       ! U- and V-points
+         DO jj = 1, jpj 
+            DO ji = 1, jpi 
+               pah1(ji,jj,1) = pUfac * MAX( e1u(ji,jj), e2u(ji,jj) )**knn
+               pah2(ji,jj,1) = pUfac * MAX( e1v(ji,jj), e2v(ji,jj) )**knn
+            END DO
+         END DO
+      CASE DEFAULT                        ! error
+         CALL ctl_stop( 'ldf_c2d: ', cd_type, ' Unknown, i.e. /= DYN or TRA' )
+      END SELECT
+      !                             !==  deeper values = surface one  ==!  (except jpk)
+      DO jk = 2, jpkm1
+         pah1(:,:,jk) = pah1(:,:,1)
+         pah2(:,:,jk) = pah2(:,:,1)
+      END DO
+      !
+   END SUBROUTINE ldf_c2d
+
+   !!======================================================================
+END MODULE ldfc1d_c2d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfdyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfdyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfdyn.F90	(revision 14097)
@@ -0,0 +1,516 @@
+MODULE ldfdyn
+   !!======================================================================
+   !!                       ***  MODULE  ldfdyn  ***
+   !! Ocean physics:  lateral viscosity coefficient 
+   !!=====================================================================
+   !! History :  OPA  ! 1997-07  (G. Madec)  multi dimensional coefficients
+   !!   NEMO     1.0  ! 2002-09  (G. Madec)  F90: Free form and module
+   !!            3.7  ! 2014-01  (F. Lemarie, G. Madec)  restructuration/simplification of ahm specification,
+   !!                 !                                  add velocity dependent coefficient and optional read in file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ldf_dyn_init  : initialization, namelist read, and parameters control
+   !!   ldf_dyn       : update lateral eddy viscosity coefficients at each time step 
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers   
+   USE dom_oce         ! ocean space and time domain 
+   USE phycst          ! physical constants
+   USE ldfslp          ! lateral diffusion: slopes of mixing orientation
+   USE ldfc1d_c2d      ! lateral diffusion: 1D and 2D cases
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module for ehanced bottom friction file
+   USE timing          ! Timing
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ldf_dyn_init   ! called by nemogcm.F90
+   PUBLIC   ldf_dyn        ! called by step.F90
+
+   !                                    !!* Namelist namdyn_ldf : lateral mixing on momentum *
+   LOGICAL , PUBLIC ::   ln_dynldf_OFF   !: No operator (i.e. no explicit diffusion)
+   LOGICAL , PUBLIC ::   ln_dynldf_lap   !: laplacian operator
+   LOGICAL , PUBLIC ::   ln_dynldf_blp   !: bilaplacian operator
+   LOGICAL , PUBLIC ::   ln_dynldf_lev   !: iso-level direction
+   LOGICAL , PUBLIC ::   ln_dynldf_hor   !: horizontal (geopotential) direction
+!  LOGICAL , PUBLIC ::   ln_dynldf_iso   !: iso-neutral direction                        (see ldfslp)
+   INTEGER , PUBLIC ::   nn_ahm_ijk_t    !: choice of time & space variations of the lateral eddy viscosity coef.
+   !                                        !  time invariant coefficients:  aht = 1/2  Ud*Ld   (lap case) 
+   !                                           !                             bht = 1/12 Ud*Ld^3 (blp case)
+   REAL(wp), PUBLIC ::   rn_Uv                 !: lateral viscous velocity  [m/s]
+   REAL(wp), PUBLIC ::   rn_Lv                 !: lateral viscous length    [m]
+   !                                        ! Smagorinsky viscosity  (nn_ahm_ijk_t = 32) 
+   REAL(wp), PUBLIC ::   rn_csmc               !: Smagorinsky constant of proportionality 
+   REAL(wp), PUBLIC ::   rn_minfac             !: Multiplicative factor of theorectical minimum Smagorinsky viscosity
+   REAL(wp), PUBLIC ::   rn_maxfac             !: Multiplicative factor of theorectical maximum Smagorinsky viscosity
+   !                                        ! iso-neutral laplacian (ln_dynldf_lap=ln_dynldf_iso=T)
+   REAL(wp), PUBLIC ::   rn_ahm_b              !: lateral laplacian background eddy viscosity  [m2/s]
+
+   !                                    !!* Parameter to control the type of lateral viscous operator
+   INTEGER, PARAMETER, PUBLIC ::   np_ERROR  =-10                       !: error in setting the operator
+   INTEGER, PARAMETER, PUBLIC ::   np_no_ldf = 00                       !: without operator (i.e. no lateral viscous trend)
+   !                          !!      laplacian     !    bilaplacian    !
+   INTEGER, PARAMETER, PUBLIC ::   np_lap    = 10   ,   np_blp    = 20  !: iso-level operator
+   INTEGER, PARAMETER, PUBLIC ::   np_lap_i  = 11                       !: iso-neutral or geopotential operator
+   !
+   INTEGER           , PUBLIC ::   nldf_dyn         !: type of lateral diffusion used defined from ln_dynldf_... (namlist logicals)
+   LOGICAL           , PUBLIC ::   l_ldfdyn_time    !: flag for time variation of the lateral eddy viscosity coef.
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ahmt, ahmf   !: eddy viscosity coef. at T- and F-points [m2/s or m4/s]
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dtensq       !: horizontal tension squared         (Smagorinsky only)
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dshesq       !: horizontal shearing strain squared (Smagorinsky only)
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   esqt, esqf   !: Square of the local gridscale (e1e2/(e1+e2))**2           
+
+   REAL(wp) ::   r1_2    = 0.5_wp            ! =1/2
+   REAL(wp) ::   r1_4    = 0.25_wp           ! =1/4
+   REAL(wp) ::   r1_8    = 0.125_wp          ! =1/8
+   REAL(wp) ::   r1_12   = 1._wp / 12._wp    ! =1/12
+   REAL(wp) ::   r1_288  = 1._wp / 288._wp   ! =1/( 12^2 * 2 )
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ldf_dyn_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_dyn_init  ***
+      !!                   
+      !! ** Purpose :   set the horizontal ocean dynamics physics
+      !!
+      !! ** Method  :   the eddy viscosity coef. specification depends on:
+      !!              - the operator:
+      !!             ln_dynldf_lap = T     laplacian operator
+      !!             ln_dynldf_blp = T   bilaplacian operator
+      !!              - the parameter nn_ahm_ijk_t:
+      !!    nn_ahm_ijk_t  =  0 => = constant
+      !!                  = 10 => = F(z) :     = constant with a reduction of 1/4 with depth 
+      !!                  =-20 => = F(i,j)     = shape read in 'eddy_viscosity.nc' file
+      !!                  = 20    = F(i,j)     = F(e1,e2) or F(e1^3,e2^3) (lap or bilap case)
+      !!                  =-30 => = F(i,j,k)   = shape read in 'eddy_viscosity.nc'  file
+      !!                  = 30    = F(i,j,k)   = 2D (case 20) + decrease with depth (case 10)
+      !!                  = 31    = F(i,j,k,t) = F(local velocity) (  |u|e  /12   laplacian operator
+      !!                                                           or |u|e^3/12 bilaplacian operator )
+      !!                  = 32    = F(i,j,k,t) = F(local deformation rate and gridscale) (D and L) (Smagorinsky)  
+      !!                                                           (   L^2|D|      laplacian operator
+      !!                                                           or  L^4|D|/8  bilaplacian operator )
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk                     ! dummy loop indices
+      INTEGER  ::   ioptio, ierr, inum, ios, inn   ! local integer
+      REAL(wp) ::   zah0, zah_max, zUfac           ! local scalar
+      CHARACTER(len=5) ::   cl_Units               ! units (m2/s or m4/s)
+      !!
+      NAMELIST/namdyn_ldf/ ln_dynldf_OFF, ln_dynldf_lap, ln_dynldf_blp,   &   ! type of operator
+         &                 ln_dynldf_lev, ln_dynldf_hor, ln_dynldf_iso,   &   ! acting direction of the operator
+         &                 nn_ahm_ijk_t , rn_Uv    , rn_Lv,   rn_ahm_b,   &   ! lateral eddy coefficient
+         &                 rn_csmc      , rn_minfac    , rn_maxfac            ! Smagorinsky settings
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, namdyn_ldf, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdyn_ldf in reference namelist' )
+
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, namdyn_ldf, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdyn_ldf in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdyn_ldf )
+
+      IF(lwp) THEN                      ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ldf_dyn : lateral momentum physics'
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,*) '   Namelist namdyn_ldf : set lateral mixing parameters'
+         !
+         WRITE(numout,*) '      type :'
+         WRITE(numout,*) '         no explicit diffusion                ln_dynldf_OFF = ', ln_dynldf_OFF
+         WRITE(numout,*) '         laplacian operator                   ln_dynldf_lap = ', ln_dynldf_lap
+         WRITE(numout,*) '         bilaplacian operator                 ln_dynldf_blp = ', ln_dynldf_blp
+         !
+         WRITE(numout,*) '      direction of action :'
+         WRITE(numout,*) '         iso-level                            ln_dynldf_lev = ', ln_dynldf_lev
+         WRITE(numout,*) '         horizontal (geopotential)            ln_dynldf_hor = ', ln_dynldf_hor
+         WRITE(numout,*) '         iso-neutral                          ln_dynldf_iso = ', ln_dynldf_iso
+         !
+         WRITE(numout,*) '      coefficients :'
+         WRITE(numout,*) '         type of time-space variation         nn_ahm_ijk_t  = ', nn_ahm_ijk_t
+         WRITE(numout,*) '         lateral viscous velocity  (if cst)      rn_Uv      = ', rn_Uv, ' m/s'
+         WRITE(numout,*) '         lateral viscous length    (if cst)      rn_Lv      = ', rn_Lv, ' m'
+         WRITE(numout,*) '         background viscosity (iso-lap case)     rn_ahm_b   = ', rn_ahm_b, ' m2/s'
+         !
+         WRITE(numout,*) '      Smagorinsky settings (nn_ahm_ijk_t  = 32) :'
+         WRITE(numout,*) '         Smagorinsky coefficient              rn_csmc       = ', rn_csmc
+         WRITE(numout,*) '         factor multiplier for eddy visc.'
+         WRITE(numout,*) '            lower limit (default 1.0)         rn_minfac    = ', rn_minfac
+         WRITE(numout,*) '            upper limit (default 1.0)         rn_maxfac    = ', rn_maxfac
+      ENDIF
+
+      !
+      !           !==  type of lateral operator used  ==!   (set nldf_dyn)
+      !           !=====================================!
+      !
+      nldf_dyn = np_ERROR
+      ioptio = 0
+      IF( ln_dynldf_OFF ) THEN   ;   nldf_dyn = np_no_ldf   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_dynldf_lap ) THEN   ;                              ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_dynldf_blp ) THEN   ;                              ioptio = ioptio + 1   ;   ENDIF
+      IF( ioptio /= 1   )   CALL ctl_stop( 'dyn_ldf_init: use ONE of the 3 operator options (NONE/lap/blp)' )
+      !
+      IF(.NOT.ln_dynldf_OFF ) THEN     !==  direction ==>> type of operator  ==!
+         ioptio = 0
+         IF( ln_dynldf_lev )   ioptio = ioptio + 1
+         IF( ln_dynldf_hor )   ioptio = ioptio + 1
+         IF( ln_dynldf_iso )   ioptio = ioptio + 1
+         IF( ioptio /= 1   )   CALL ctl_stop( 'dyn_ldf_init: use ONE of the 3 direction options (level/hor/iso)' )
+         !
+         !                             ! Set nldf_dyn, the type of lateral diffusion, from ln_dynldf_... logicals
+         ierr = 0
+         IF( ln_dynldf_lap ) THEN         ! laplacian operator
+            IF( ln_zco ) THEN                   ! z-coordinate
+               IF ( ln_dynldf_lev )   nldf_dyn = np_lap     ! iso-level = horizontal (no rotation)
+               IF ( ln_dynldf_hor )   nldf_dyn = np_lap     ! iso-level = horizontal (no rotation)
+               IF ( ln_dynldf_iso )   nldf_dyn = np_lap_i   ! iso-neutral            (   rotation)
+            ENDIF
+            IF( ln_zps ) THEN                   ! z-coordinate with partial step
+               IF ( ln_dynldf_lev )   nldf_dyn = np_lap     ! iso-level              (no rotation)
+               IF ( ln_dynldf_hor )   nldf_dyn = np_lap     ! iso-level              (no rotation)
+               IF ( ln_dynldf_iso )   nldf_dyn = np_lap_i   ! iso-neutral            (   rotation)
+            ENDIF
+            IF( ln_sco ) THEN                   ! s-coordinate
+               IF ( ln_dynldf_lev )   nldf_dyn = np_lap     ! iso-level = horizontal (no rotation)
+               IF ( ln_dynldf_hor )   nldf_dyn = np_lap_i   ! horizontal             (   rotation)
+               IF ( ln_dynldf_iso )   nldf_dyn = np_lap_i   ! iso-neutral            (   rotation)
+            ENDIF
+         ENDIF
+         !
+         IF( ln_dynldf_blp ) THEN         ! bilaplacian operator
+            IF( ln_zco ) THEN                   ! z-coordinate
+               IF( ln_dynldf_lev )   nldf_dyn = np_blp   ! iso-level = horizontal (no rotation)
+               IF( ln_dynldf_hor )   nldf_dyn = np_blp   ! iso-level = horizontal (no rotation)
+               IF( ln_dynldf_iso )   ierr = 2            ! iso-neutral            (   rotation)
+            ENDIF
+            IF( ln_zps ) THEN                   ! z-coordinate with partial step
+               IF( ln_dynldf_lev )   nldf_dyn = np_blp   ! iso-level              (no rotation)
+               IF( ln_dynldf_hor )   nldf_dyn = np_blp   ! iso-level              (no rotation)
+               IF( ln_dynldf_iso )   ierr = 2            ! iso-neutral            (   rotation)
+            ENDIF
+            IF( ln_sco ) THEN                   ! s-coordinate
+               IF( ln_dynldf_lev )   nldf_dyn = np_blp   ! iso-level              (no rotation)
+               IF( ln_dynldf_hor )   ierr = 2            ! horizontal             (   rotation)
+               IF( ln_dynldf_iso )   ierr = 2            ! iso-neutral            (   rotation)
+            ENDIF
+         ENDIF
+         !
+         IF( ierr == 2 )   CALL ctl_stop( 'rotated bi-laplacian operator does not exist' )
+         !
+         IF( nldf_dyn == np_lap_i )   l_ldfslp = .TRUE.  ! rotation require the computation of the slopes
+         !
+      ENDIF
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE( nldf_dyn )
+         CASE( np_no_ldf )   ;   WRITE(numout,*) '   ==>>>   NO lateral viscosity'
+         CASE( np_lap    )   ;   WRITE(numout,*) '   ==>>>   iso-level laplacian operator'
+         CASE( np_lap_i  )   ;   WRITE(numout,*) '   ==>>>   rotated laplacian operator with iso-level background'
+         CASE( np_blp    )   ;   WRITE(numout,*) '   ==>>>   iso-level bi-laplacian operator'
+         END SELECT
+         WRITE(numout,*)
+      ENDIF
+      
+      !
+      !           !==  Space/time variation of eddy coefficients  ==!
+      !           !=================================================!
+      !
+      l_ldfdyn_time = .FALSE.                ! no time variation except in case defined below
+      !
+      IF( ln_dynldf_OFF ) THEN
+         IF(lwp) WRITE(numout,*) '   ==>>>   No viscous operator selected. ahmt and ahmf are not allocated'
+         RETURN
+         !
+      ELSE                                   !==  a lateral diffusion operator is used  ==!
+         !
+         !                                         ! allocate the ahm arrays
+         ALLOCATE( ahmt(jpi,jpj,jpk) , ahmf(jpi,jpj,jpk) , STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'ldf_dyn_init: failed to allocate arrays')
+         !
+         ahmt(:,:,:) = 0._wp                       ! init to 0 needed 
+         ahmf(:,:,:) = 0._wp
+         !
+         !                                         ! value of lap/blp eddy mixing coef.
+         IF(     ln_dynldf_lap ) THEN   ;   zUfac = r1_2 *rn_Uv   ;   inn = 1   ;   cl_Units = ' m2/s'   !   laplacian
+         ELSEIF( ln_dynldf_blp ) THEN   ;   zUfac = r1_12*rn_Uv   ;   inn = 3   ;   cl_Units = ' m4/s'   ! bilaplacian
+         ENDIF
+         zah0    = zUfac *    rn_Lv**inn              ! mixing coefficient
+         zah_max = zUfac * (ra*rad)**inn              ! maximum reachable coefficient (value at the Equator)
+         !
+         SELECT CASE(  nn_ahm_ijk_t  )             !* Specification of space-time variations of ahmt, ahmf
+         !
+         CASE(   0  )      !==  constant  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity. = constant = ', zah0, cl_Units
+            ahmt(:,:,1:jpkm1) = zah0
+            ahmf(:,:,1:jpkm1) = zah0
+            !
+         CASE(  10  )      !==  fixed profile  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F( depth )'
+            IF(lwp) WRITE(numout,*) '           surface viscous coef. = constant = ', zah0, cl_Units
+            ahmt(:,:,1) = zah0                        ! constant surface value
+            ahmf(:,:,1) = zah0
+            CALL ldf_c1d( 'DYN', ahmt(:,:,1), ahmf(:,:,1), ahmt, ahmf )
+            !
+         CASE ( -20 )      !== fixed horizontal shape read in file  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F(i,j) read in eddy_viscosity.nc file'
+            CALL iom_open( 'eddy_viscosity_2D.nc', inum )
+            CALL iom_get ( inum, jpdom_data, 'ahmt_2d', ahmt(:,:,1) )
+            CALL iom_get ( inum, jpdom_data, 'ahmf_2d', ahmf(:,:,1) )
+            CALL iom_close( inum )
+            DO jk = 2, jpkm1
+               ahmt(:,:,jk) = ahmt(:,:,1)
+               ahmf(:,:,jk) = ahmf(:,:,1)
+            END DO
+            !
+         CASE(  20  )      !== fixed horizontal shape  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F( e1, e2 ) or F( e1^3, e2^3 ) (lap. or blp. case)'
+            IF(lwp) WRITE(numout,*) '           using a fixed viscous velocity = ', rn_Uv  ,' m/s   and   Lv = Max(e1,e2)'
+            IF(lwp) WRITE(numout,*) '           maximum reachable coefficient (at the Equator) = ', zah_max, cl_Units, '  for e1=1°)'
+            CALL ldf_c2d( 'DYN', zUfac      , inn        , ahmt, ahmf )         ! surface value proportional to scale factor^inn
+            !
+         CASE( -30  )      !== fixed 3D shape read in file  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F(i,j,k) read in eddy_viscosity_3D.nc file'
+            CALL iom_open( 'eddy_viscosity_3D.nc', inum )
+            CALL iom_get ( inum, jpdom_data, 'ahmt_3d', ahmt )
+            CALL iom_get ( inum, jpdom_data, 'ahmf_3d', ahmf )
+            CALL iom_close( inum )
+            !
+         CASE(  30  )       !==  fixed 3D shape  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F( latitude, longitude, depth )'
+            IF(lwp) WRITE(numout,*) '           using a fixed viscous velocity = ', rn_Uv  ,' m/s   and   Ld = Max(e1,e2)'
+            IF(lwp) WRITE(numout,*) '           maximum reachable coefficient (at the Equator) = ', zah_max, cl_Units, '  for e1=1°)'
+            CALL ldf_c2d( 'DYN', zUfac      , inn        , ahmt, ahmf )         ! surface value proportional to scale factor^inn
+            CALL ldf_c1d( 'DYN', ahmt(:,:,1), ahmf(:,:,1), ahmt, ahmf )  ! reduction with depth
+            !
+         CASE(  31  )       !==  time varying 3D field  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F( latitude, longitude, depth , time )'
+            IF(lwp) WRITE(numout,*) '           proportional to the local velocity : 1/2 |u|e (lap) or 1/12 |u|e^3 (blp)'
+            !
+            l_ldfdyn_time = .TRUE.     ! will be calculated by call to ldf_dyn routine in step.F90
+            !
+         CASE(  32  )       !==  time varying 3D field  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy viscosity = F( latitude, longitude, depth , time )'
+            IF(lwp) WRITE(numout,*) '           proportional to the local deformation rate and gridscale (Smagorinsky)'
+            !
+            l_ldfdyn_time = .TRUE.     ! will be calculated by call to ldf_dyn routine in step.F90
+            !
+            !                          ! allocate arrays used in ldf_dyn. 
+            ALLOCATE( dtensq(jpi,jpj,jpk) , dshesq(jpi,jpj,jpk) , esqt(jpi,jpj) , esqf(jpi,jpj) , STAT=ierr )
+            IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'ldf_dyn_init: failed to allocate Smagorinsky arrays')
+            !
+            DO jj = 1, jpj             ! Set local gridscale values
+               DO ji = 1, jpi
+                  esqt(ji,jj) = ( 2._wp * e1e2t(ji,jj) / ( e1t(ji,jj) + e2t(ji,jj) ) )**2 
+                  esqf(ji,jj) = ( 2._wp * e1e2f(ji,jj) / ( e1f(ji,jj) + e2f(ji,jj) ) )**2 
+               END DO
+            END DO
+            !
+         CASE DEFAULT
+            CALL ctl_stop('ldf_dyn_init: wrong choice for nn_ahm_ijk_t, the type of space-time variation of ahm')
+         END SELECT
+         !
+         IF( .NOT.l_ldfdyn_time ) THEN             !* No time variation 
+            IF(     ln_dynldf_lap ) THEN                 !   laplacian operator (mask only)
+               ahmt(:,:,1:jpkm1) =       ahmt(:,:,1:jpkm1)   * tmask(:,:,1:jpkm1)
+               ahmf(:,:,1:jpkm1) =       ahmf(:,:,1:jpkm1)   * fmask(:,:,1:jpkm1)
+            ELSEIF( ln_dynldf_blp ) THEN                 ! bilaplacian operator (square root + mask)
+               ahmt(:,:,1:jpkm1) = SQRT( ahmt(:,:,1:jpkm1) ) * tmask(:,:,1:jpkm1)
+               ahmf(:,:,1:jpkm1) = SQRT( ahmf(:,:,1:jpkm1) ) * fmask(:,:,1:jpkm1)
+            ENDIF
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE ldf_dyn_init
+
+
+   SUBROUTINE ldf_dyn( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_dyn  ***
+      !! 
+      !! ** Purpose :   update at kt the momentum lateral mixing coeff. (ahmt and ahmf)
+      !!
+      !! ** Method  :   time varying eddy viscosity coefficients:
+      !!
+      !!    nn_ahm_ijk_t = 31    ahmt, ahmf = F(i,j,k,t) = F(local velocity) 
+      !!                         ( |u|e /12  or  |u|e^3/12 for laplacian or bilaplacian operator )
+      !!
+      !!    nn_ahm_ijk_t = 32    ahmt, ahmf = F(i,j,k,t) = F(local deformation rate and gridscale) (D and L) (Smagorinsky)  
+      !!                         ( L^2|D|    or  L^4|D|/8  for laplacian or bilaplacian operator )
+      !!
+      !! ** note    :    in BLP cases the sqrt of the eddy coef is returned, since bilaplacian is en re-entrant laplacian
+      !! ** action  :    ahmt, ahmf   updated at each time step
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zu2pv2_ij_p1, zu2pv2_ij, zu2pv2_ij_m1, zemax   ! local scalar (option 31)
+      REAL(wp) ::   zcmsmag, zstabf_lo, zstabf_up, zdelta, zdb     ! local scalar (option 32)
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ldf_dyn')
+      !
+      SELECT CASE(  nn_ahm_ijk_t  )       !== Eddy vicosity coefficients ==!
+      !
+      CASE(  31  )       !==  time varying 3D field  ==!   = F( local velocity )
+         !
+         IF( ln_dynldf_lap   ) THEN        ! laplacian operator : |u| e /12 = |u/144| e
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     zu2pv2_ij_m1 = ub(ji-1,jj  ,jk) * ub(ji-1,jj  ,jk) + vb(ji  ,jj-1,jk) * vb(ji  ,jj-1,jk)
+                     zemax = MAX( e1t(ji,jj) , e2t(ji,jj) )
+                     ahmt(ji,jj,jk) = SQRT( (zu2pv2_ij + zu2pv2_ij_m1) * r1_288 ) * zemax * tmask(ji,jj,jk)      ! 288= 12*12 * 2
+                  END DO
+               END DO
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1
+                     zu2pv2_ij_p1 = ub(ji  ,jj+1,jk) * ub(ji  ,jj+1,jk) + vb(ji+1,jj  ,jk) * vb(ji+1,jj  ,jk)
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     zemax = MAX( e1f(ji,jj) , e2f(ji,jj) )
+                     ahmf(ji,jj,jk) = SQRT( (zu2pv2_ij + zu2pv2_ij_p1) * r1_288 ) * zemax * fmask(ji,jj,jk)      ! 288= 12*12 * 2
+                  END DO
+               END DO
+            END DO
+         ELSEIF( ln_dynldf_blp ) THEN      ! bilaplacian operator : sqrt( |u| e^3 /12 ) = sqrt( |u/144| e ) * e
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     zu2pv2_ij_m1 = ub(ji-1,jj  ,jk) * ub(ji-1,jj  ,jk) + vb(ji  ,jj-1,jk) * vb(ji  ,jj-1,jk)
+                     zemax = MAX( e1t(ji,jj) , e2t(ji,jj) )
+                     ahmt(ji,jj,jk) = SQRT(  SQRT( (zu2pv2_ij + zu2pv2_ij_m1) * r1_288 ) * zemax  ) * zemax * tmask(ji,jj,jk)
+                  END DO
+               END DO
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1
+                     zu2pv2_ij_p1 = ub(ji  ,jj+1,jk) * ub(ji  ,jj+1,jk) + vb(ji+1,jj  ,jk) * vb(ji+1,jj  ,jk)
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     zemax = MAX( e1f(ji,jj) , e2f(ji,jj) )
+                     ahmf(ji,jj,jk) = SQRT(  SQRT( (zu2pv2_ij + zu2pv2_ij_p1) * r1_288 ) * zemax  ) * zemax * fmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         !
+         CALL lbc_lnk_multi( 'ldfdyn', ahmt, 'T', 1.,  ahmf, 'F', 1. )
+         !
+         !
+      CASE(  32  )       !==  time varying 3D field  ==!   = F( local deformation rate and gridscale ) (Smagorinsky)
+         !
+         IF( ln_dynldf_lap .OR. ln_dynldf_blp  ) THEN        ! laplacian operator : (C_smag/pi)^2 L^2 |D|
+            !
+            zcmsmag   = (rn_csmc/rpi)**2                                            ! (C_smag/pi)^2
+            zstabf_lo = rn_minfac * rn_minfac / ( 2._wp * 12._wp * 12._wp * zcmsmag ) ! lower limit stability factor scaling
+            zstabf_up = rn_maxfac / ( 4._wp * zcmsmag * 2._wp * rdt )               ! upper limit stability factor scaling
+            IF( ln_dynldf_blp ) zstabf_lo = ( 16._wp / 9._wp ) * zstabf_lo          ! provide |U|L^3/12 lower limit instead 
+            !                                                                       ! of |U|L^3/16 in blp case
+            DO jk = 1, jpkm1
+               !
+               DO jj = 2, jpjm1
+                  DO ji = 2, jpim1
+                     zdb =   ( ub(ji,jj,jk) * r1_e2u(ji,jj) - ub(ji-1,jj,jk) * r1_e2u(ji-1,jj) ) * r1_e1t(ji,jj) * e2t(ji,jj)  &
+                        &  - ( vb(ji,jj,jk) * r1_e1v(ji,jj) - vb(ji,jj-1,jk) * r1_e1v(ji,jj-1) ) * r1_e2t(ji,jj) * e1t(ji,jj)
+                     dtensq(ji,jj,jk) = zdb * zdb * tmask(ji,jj,jk)
+                  END DO
+               END DO
+               !
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zdb =   ( ub(ji,jj+1,jk) * r1_e1u(ji,jj+1) - ub(ji,jj,jk) * r1_e1u(ji,jj) ) * r1_e2f(ji,jj) * e1f(ji,jj)  &
+                        &  + ( vb(ji+1,jj,jk) * r1_e2v(ji+1,jj) - vb(ji,jj,jk) * r1_e2v(ji,jj) ) * r1_e1f(ji,jj) * e2f(ji,jj)
+                     dshesq(ji,jj,jk) = zdb * zdb * fmask(ji,jj,jk)
+                  END DO
+               END DO
+               !
+            END DO
+            !
+            CALL lbc_lnk_multi( 'ldfdyn', dtensq, 'T', 1. )  ! lbc_lnk on dshesq not needed
+            !
+            DO jk = 1, jpkm1
+              !
+               DO jj = 2, jpjm1                                ! T-point value
+                  DO ji = fs_2, fs_jpim1
+                     !
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     zu2pv2_ij_m1 = ub(ji-1,jj  ,jk) * ub(ji-1,jj  ,jk) + vb(ji  ,jj-1,jk) * vb(ji  ,jj-1,jk)
+                     !
+                     zdelta         = zcmsmag * esqt(ji,jj)                                        ! L^2 * (C_smag/pi)^2
+                     ahmt(ji,jj,jk) = zdelta * SQRT(          dtensq(ji  ,jj,jk) +                         &
+                        &                            r1_4 * ( dshesq(ji  ,jj,jk) + dshesq(ji  ,jj-1,jk) +  &
+                        &                                     dshesq(ji-1,jj,jk) + dshesq(ji-1,jj-1,jk) ) )
+                     ahmt(ji,jj,jk) = MAX( ahmt(ji,jj,jk), SQRT( (zu2pv2_ij + zu2pv2_ij_m1) * zdelta * zstabf_lo ) ) ! Impose lower limit == minfac  * |U|L/2
+                     ahmt(ji,jj,jk) = MIN( ahmt(ji,jj,jk),                                    zdelta * zstabf_up )   ! Impose upper limit == maxfac  * L^2/(4*2dt)
+                     !
+                  END DO
+               END DO
+               !
+               DO jj = 1, jpjm1                                ! F-point value
+                  DO ji = 1, fs_jpim1
+                     !
+                     zu2pv2_ij_p1 = ub(ji  ,jj+1,jk) * ub(ji  ,jj+1,jk) + vb(ji+1,jj  ,jk) * vb(ji+1,jj  ,jk)
+                     zu2pv2_ij    = ub(ji  ,jj  ,jk) * ub(ji  ,jj  ,jk) + vb(ji  ,jj  ,jk) * vb(ji  ,jj  ,jk)
+                     !
+                     zdelta         = zcmsmag * esqf(ji,jj)                                        ! L^2 * (C_smag/pi)^2
+                     ahmf(ji,jj,jk) = zdelta * SQRT(          dshesq(ji  ,jj,jk) +                         &
+                        &                            r1_4 * ( dtensq(ji  ,jj,jk) + dtensq(ji  ,jj+1,jk) +  &
+                        &                                     dtensq(ji+1,jj,jk) + dtensq(ji+1,jj+1,jk) ) )
+                     ahmf(ji,jj,jk) = MAX( ahmf(ji,jj,jk), SQRT( (zu2pv2_ij + zu2pv2_ij_p1) * zdelta * zstabf_lo ) ) ! Impose lower limit == minfac  * |U|L/2
+                     ahmf(ji,jj,jk) = MIN( ahmf(ji,jj,jk),                                    zdelta * zstabf_up )   ! Impose upper limit == maxfac  * L^2/(4*2dt)
+                     !
+                  END DO
+               END DO
+               !
+            END DO
+            !
+         ENDIF
+         !
+         IF( ln_dynldf_blp ) THEN      ! bilaplacian operator : sqrt( (C_smag/pi)^2 L^4 |D|/8)
+            !                          !                      = sqrt( A_lap_smag L^2/8 )
+            !                          ! stability limits already applied to laplacian values
+            !                          ! effective default limits are 1/12 |U|L^3 < B_hm < 1//(32*2dt) L^4
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     ahmt(ji,jj,jk) = SQRT( r1_8 * esqt(ji,jj) * ahmt(ji,jj,jk) )
+                  END DO
+               END DO
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1
+                     ahmf(ji,jj,jk) = SQRT( r1_8 * esqf(ji,jj) * ahmf(ji,jj,jk) )
+                  END DO
+               END DO
+            END DO
+            !
+         ENDIF
+         !
+         CALL lbc_lnk_multi( 'ldfdyn', ahmt, 'T', 1. , ahmf, 'F', 1. )
+         !
+      END SELECT
+      !
+      CALL iom_put( "ahmt_2d", ahmt(:,:,1) )   ! surface u-eddy diffusivity coeff.
+      CALL iom_put( "ahmf_2d", ahmf(:,:,1) )   ! surface v-eddy diffusivity coeff.
+      CALL iom_put( "ahmt_3d", ahmt(:,:,:) )   ! 3D      u-eddy diffusivity coeff.
+      CALL iom_put( "ahmf_3d", ahmf(:,:,:) )   ! 3D      v-eddy diffusivity coeff.
+      !
+      IF( ln_timing )   CALL timing_stop('ldf_dyn')
+      !
+   END SUBROUTINE ldf_dyn
+
+   !!======================================================================
+END MODULE ldfdyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfslp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfslp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldfslp.F90	(revision 14097)
@@ -0,0 +1,807 @@
+MODULE ldfslp
+   !!======================================================================
+   !!                       ***  MODULE  ldfslp  ***
+   !! Ocean physics: slopes of neutral surfaces
+   !!======================================================================
+   !! History :  OPA  ! 1994-12  (G. Madec, M. Imbard)  Original code
+   !!            8.0  ! 1997-06  (G. Madec)  optimization, lbc
+   !!            8.1  ! 1999-10  (A. Jouzeau)  NEW profile in the mixed layer
+   !!   NEMO     1.0  ! 2002-10  (G. Madec)  Free form, F90
+   !!             -   ! 2005-10  (A. Beckmann)  correction for s-coordinates
+   !!            3.3  ! 2010-10  (G. Nurser, C. Harris, G. Madec)  add Griffies operator
+   !!             -   ! 2010-11  (F. Dupond, G. Madec)  bug correction in slopes just below the ML
+   !!            3.7  ! 2013-12  (F. Lemarie, G. Madec)  add limiter on triad slopes
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ldf_slp       : calculates the slopes of neutral surface   (Madec operator)
+   !!   ldf_slp_triad : calculates the triads of isoneutral slopes (Griffies operator)
+   !!   ldf_slp_mxl   : calculates the slopes at the base of the mixed layer (Madec operator)
+   !!   ldf_slp_init  : initialization of the slopes computation
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+!   USE ldfdyn         ! lateral diffusion: eddy viscosity coef.
+   USE phycst         ! physical constants
+   USE zdfmxl         ! mixed layer depth
+   USE eosbn2         ! equation of states
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distribued memory computing library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ldf_slp         ! routine called by step.F90
+   PUBLIC   ldf_slp_triad   ! routine called by step.F90
+   PUBLIC   ldf_slp_init    ! routine called by nemogcm.F90
+
+   LOGICAL , PUBLIC ::   l_ldfslp = .FALSE.     !: slopes flag
+
+   LOGICAL , PUBLIC ::   ln_traldf_iso   = .TRUE.       !: iso-neutral direction                           (nam_traldf namelist)
+   LOGICAL , PUBLIC ::   ln_traldf_triad = .FALSE.      !: griffies triad scheme                           (nam_traldf namelist)
+   LOGICAL , PUBLIC ::   ln_dynldf_iso                  !: iso-neutral direction                           (nam_dynldf namelist)
+
+   LOGICAL , PUBLIC ::   ln_triad_iso    = .FALSE.      !: pure horizontal mixing in ML                    (nam_traldf namelist)
+   LOGICAL , PUBLIC ::   ln_botmix_triad = .FALSE.      !: mixing on bottom                                (nam_traldf namelist)
+   REAL(wp), PUBLIC ::   rn_sw_triad     = 1._wp        !: =1 switching triads ; =0 all four triads used   (nam_traldf namelist)
+   REAL(wp), PUBLIC ::   rn_slpmax       = 0.01_wp      !: slope limit                                     (nam_traldf namelist)
+
+   LOGICAL , PUBLIC ::   l_grad_zps = .FALSE.           !: special treatment for Horz Tgradients w partial steps (triad operator)
+   
+   !                                                     !! Classic operator (Madec)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)     ::   uslp, wslpi          !: i_slope at U- and W-points
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)     ::   vslp, wslpj          !: j-slope at V- and W-points
+   !                                                     !! triad operator (Griffies)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)     ::   wslp2                !: wslp**2 from Griffies quarter cells
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:,:) ::   triadi_g, triadj_g   !: skew flux  slopes relative to geopotentials
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:,:) ::   triadi  , triadj     !: isoneutral slopes relative to model-coordinate
+   !                                                     !! both operators
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)     ::   ah_wslp2             !: ah * slope^2 at w-point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)     ::   akz                  !: stabilizing vertical diffusivity
+   
+   !                                                     !! Madec operator
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   omlmask           ! mask of the surface mixed layer at T-pt
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   uslpml, wslpiml   ! i_slope at U- and W-points just below the mixed layer
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   vslpml, wslpjml   ! j_slope at V- and W-points just below the mixed layer
+
+   REAL(wp) ::   repsln = 1.e-25_wp       ! tiny value used as minium of di(rho), dj(rho) and dk(rho)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ldf_slp( kt, prd, pn2 )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE ldf_slp  ***
+      !!
+      !! ** Purpose :   Compute the slopes of neutral surface (slope of isopycnal
+      !!              surfaces referenced locally) (ln_traldf_iso=T).
+      !!
+      !! ** Method  :   The slope in the i-direction is computed at U- and
+      !!      W-points (uslp, wslpi) and the slope in the j-direction is
+      !!      computed at V- and W-points (vslp, wslpj).
+      !!      They are bounded by 1/100 over the whole ocean, and within the
+      !!      surface layer they are bounded by the distance to the surface
+      !!      ( slope<= depth/l  where l is the length scale of horizontal
+      !!      diffusion (here, aht=2000m2/s ==> l=20km with a typical velocity
+      !!      of 10cm/s)
+      !!        A horizontal shapiro filter is applied to the slopes
+      !!        ln_sco=T, s-coordinate, add to the previously computed slopes
+      !!      the slope of the model level surface.
+      !!        macro-tasked on horizontal slab (jk-loop)  (2, jpk-1)
+      !!      [slopes already set to zero at level 1, and to zero or the ocean
+      !!      bottom slope (ln_sco=T) at level jpk in inildf]
+      !!
+      !! ** Action : - uslp, wslpi, and vslp, wslpj, the i- and  j-slopes
+      !!               of now neutral surfaces at u-, w- and v- w-points, resp.
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in)                   ::   kt    ! ocean time-step index
+      REAL(wp), INTENT(in), DIMENSION(:,:,:) ::   prd   ! in situ density
+      REAL(wp), INTENT(in), DIMENSION(:,:,:) ::   pn2   ! Brunt-Vaisala frequency (locally ref.)
+      !!
+      INTEGER  ::   ji , jj , jk    ! dummy loop indices
+      INTEGER  ::   ii0, ii1        ! temporary integer
+      INTEGER  ::   ij0, ij1        ! temporary integer
+      REAL(wp) ::   zeps, zm1_g, zm1_2g, z1_16, zcofw, z1_slpmax ! local scalars
+      REAL(wp) ::   zci, zfi, zau, zbu, zai, zbi   !   -      -
+      REAL(wp) ::   zcj, zfj, zav, zbv, zaj, zbj   !   -      -
+      REAL(wp) ::   zck, zfk,      zbw             !   -      -
+      REAL(wp) ::   zdepu, zdepv                   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj)     ::  zslpml_hmlpu, zslpml_hmlpv
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zgru, zwz, zdzr
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zgrv, zww
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ldf_slp')
+      !
+      zeps   =  1.e-20_wp        !==   Local constant initialization   ==!
+      z1_16  =  1.0_wp / 16._wp
+      zm1_g  = -1.0_wp / grav
+      zm1_2g = -0.5_wp / grav
+      z1_slpmax = 1._wp / rn_slpmax
+      !
+      zww(:,:,:) = 0._wp
+      zwz(:,:,:) = 0._wp
+      !
+      DO jk = 1, jpk             !==   i- & j-gradient of density   ==!
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zgru(ji,jj,jk) = umask(ji,jj,jk) * ( prd(ji+1,jj  ,jk) - prd(ji,jj,jk) )
+               zgrv(ji,jj,jk) = vmask(ji,jj,jk) * ( prd(ji  ,jj+1,jk) - prd(ji,jj,jk) )
+            END DO
+         END DO
+      END DO
+      IF( ln_zps ) THEN                           ! partial steps correction at the bottom ocean level
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               zgru(ji,jj,mbku(ji,jj)) = gru(ji,jj)
+               zgrv(ji,jj,mbkv(ji,jj)) = grv(ji,jj)
+            END DO
+         END DO
+      ENDIF
+      IF( ln_zps .AND. ln_isfcav ) THEN           ! partial steps correction at the bottom ocean level
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               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
+      ENDIF
+      !
+      zdzr(:,:,1) = 0._wp        !==   Local vertical density gradient at T-point   == !   (evaluated from N^2)
+      DO jk = 2, jpkm1
+         !                                ! zdzr = d/dz(prd)= - ( prd ) / grav * mk(pn2) -- at t point
+         !                                !   trick: tmask(ik  )  = 0   =>   all pn2   = 0   =>   zdzr = 0
+         !                                !    else  tmask(ik+1)  = 0   =>   pn2(ik+1) = 0   =>   zdzr divides by 1
+         !                                !          umask(ik+1) /= 0   =>   all pn2  /= 0   =>   zdzr divides by 2
+         !                                ! NB: 1/(tmask+1) = (1-.5*tmask)  substitute a / by a *  ==> faster
+         zdzr(:,:,jk) = zm1_g * ( prd(:,:,jk) + 1._wp )              &
+            &                 * ( pn2(:,:,jk) + pn2(:,:,jk+1) ) * ( 1._wp - 0.5_wp * tmask(:,:,jk+1) )
+      END DO
+      !
+      !                          !==   Slopes just below the mixed layer   ==!
+      CALL ldf_slp_mxl( prd, pn2, zgru, zgrv, zdzr )        ! output: uslpml, vslpml, wslpiml, wslpjml
+
+
+      ! I.  slopes at u and v point      | uslp = d/di( prd ) / d/dz( prd )
+      ! ===========================      | vslp = d/dj( prd ) / d/dz( prd )
+      !
+      IF ( ln_isfcav ) THEN
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zslpml_hmlpu(ji,jj) = uslpml(ji,jj) / ( MAX(hmlpt  (ji,jj), hmlpt  (ji+1,jj  ), 5._wp) &
+                  &                                  - MAX(risfdep(ji,jj), risfdep(ji+1,jj  )       ) ) 
+               zslpml_hmlpv(ji,jj) = vslpml(ji,jj) / ( MAX(hmlpt  (ji,jj), hmlpt  (ji  ,jj+1), 5._wp) &
+                  &                                  - MAX(risfdep(ji,jj), risfdep(ji  ,jj+1)       ) )
+            END DO
+         END DO
+      ELSE
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zslpml_hmlpu(ji,jj) = uslpml(ji,jj) / MAX(hmlpt(ji,jj), hmlpt(ji+1,jj  ), 5._wp)
+               zslpml_hmlpv(ji,jj) = vslpml(ji,jj) / MAX(hmlpt(ji,jj), hmlpt(ji  ,jj+1), 5._wp)
+            END DO
+         END DO
+      END IF
+
+      DO jk = 2, jpkm1                            !* Slopes at u and v points
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               !                                      ! horizontal and vertical density gradient at u- and v-points
+               zau = zgru(ji,jj,jk) * r1_e1u(ji,jj)
+               zav = zgrv(ji,jj,jk) * r1_e2v(ji,jj)
+               zbu = 0.5_wp * ( zdzr(ji,jj,jk) + zdzr(ji+1,jj  ,jk) )
+               zbv = 0.5_wp * ( zdzr(ji,jj,jk) + zdzr(ji  ,jj+1,jk) )
+               !                                      ! bound the slopes: abs(zw.)<= 1/100 and zb..<0
+               !                                      ! + kxz max= ah slope max =< e1 e3 /(pi**2 2 dt)
+               zbu = MIN(  zbu, - z1_slpmax * ABS( zau ) , -7.e+3_wp/e3u_n(ji,jj,jk)* ABS( zau )  )
+               zbv = MIN(  zbv, - z1_slpmax * ABS( zav ) , -7.e+3_wp/e3v_n(ji,jj,jk)* ABS( zav )  )
+               !                                      ! Fred Dupont: add a correction for bottom partial steps:
+               !                                      !              max slope = 1/2 * e3 / e1
+               IF (ln_zps .AND. jk==mbku(ji,jj)) &
+                  zbu = MIN(  zbu, - z1_slpmax * ABS( zau ) , - 2._wp * e1u(ji,jj) / e3u_n(ji,jj,jk)* ABS( zau )  )
+               IF (ln_zps .AND. jk==mbkv(ji,jj)) &
+                  zbv = MIN(  zbv, - z1_slpmax * ABS( zav ) , - 2._wp * e2v(ji,jj) / e3v_n(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) )
+               ! thickness of water column between surface and level k at u/v point
+               zdepu = 0.5_wp * ( ( gdept_n (ji,jj,jk) + gdept_n (ji+1,jj,jk) )                            &
+                                - 2 * MAX( risfdep(ji,jj), risfdep(ji+1,jj) ) - e3u_n(ji,jj,miku(ji,jj))   )
+               zdepv = 0.5_wp * ( ( gdept_n (ji,jj,jk) + gdept_n (ji,jj+1,jk) )                            &
+                                - 2 * MAX( risfdep(ji,jj), risfdep(ji,jj+1) ) - e3v_n(ji,jj,mikv(ji,jj))   )
+               !
+               zwz(ji,jj,jk) = ( ( 1._wp - zfi) * zau / ( zbu - zeps )                                     &
+                  &                      + zfi  * zdepu * zslpml_hmlpu(ji,jj) ) * umask(ji,jj,jk)
+               zww(ji,jj,jk) = ( ( 1._wp - zfj) * zav / ( zbv - zeps )                                     &
+                  &                      + zfj  * zdepv * zslpml_hmlpv(ji,jj) ) * vmask(ji,jj,jk)
+!!gm  modif to suppress omlmask.... (as in Griffies case)
+!               !                                         ! jk must be >= ML level for zf=1. otherwise  zf=0.
+!               zfi = REAL( 1 - 1/(1 + jk / MAX( nmln(ji+1,jj), nmln(ji,jj) ) ), wp )
+!               zfj = REAL( 1 - 1/(1 + jk / MAX( nmln(ji,jj+1), nmln(ji,jj) ) ), wp )
+!               zci = 0.5 * ( gdept_n(ji+1,jj,jk)+gdept_n(ji,jj,jk) ) / MAX( hmlpt(ji,jj), hmlpt(ji+1,jj), 10. ) )
+!               zcj = 0.5 * ( gdept_n(ji,jj+1,jk)+gdept_n(ji,jj,jk) ) / MAX( hmlpt(ji,jj), hmlpt(ji,jj+1), 10. ) )
+!               zwz(ji,jj,jk) = ( zfi * zai / ( zbi - zeps ) + ( 1._wp - zfi ) * wslpiml(ji,jj) * zci ) * tmask(ji,jj,jk)
+!               zww(ji,jj,jk) = ( zfj * zaj / ( zbj - zeps ) + ( 1._wp - zfj ) * wslpjml(ji,jj) * zcj ) * tmask(ji,jj,jk)
+!!gm end modif
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'ldfslp', zwz, 'U', -1.,  zww, 'V', -1. )      ! lateral boundary conditions
+      !
+      !                                            !* horizontal Shapiro filter
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1, MAX(1, jpj-3)                        ! rows jj=2 and =jpjm1 only
+            DO ji = 2, jpim1
+               uslp(ji,jj,jk) = z1_16 * (        zwz(ji-1,jj-1,jk) + zwz(ji+1,jj-1,jk)      &
+                  &                       +      zwz(ji-1,jj+1,jk) + zwz(ji+1,jj+1,jk)      &
+                  &                       + 2.*( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj  ,jk)      &
+                  &                       +      zwz(ji+1,jj  ,jk) + zwz(ji  ,jj+1,jk) )    &
+                  &                       + 4.*  zwz(ji  ,jj  ,jk)                       )
+               vslp(ji,jj,jk) = z1_16 * (        zww(ji-1,jj-1,jk) + zww(ji+1,jj-1,jk)      &
+                  &                       +      zww(ji-1,jj+1,jk) + zww(ji+1,jj+1,jk)      &
+                  &                       + 2.*( zww(ji  ,jj-1,jk) + zww(ji-1,jj  ,jk)      &
+                  &                       +      zww(ji+1,jj  ,jk) + zww(ji  ,jj+1,jk) )    &
+                  &                       + 4.*  zww(ji,jj    ,jk)                       )
+            END DO
+         END DO
+         DO jj = 3, jpj-2                               ! other rows
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               uslp(ji,jj,jk) = z1_16 * (        zwz(ji-1,jj-1,jk) + zwz(ji+1,jj-1,jk)      &
+                  &                       +      zwz(ji-1,jj+1,jk) + zwz(ji+1,jj+1,jk)      &
+                  &                       + 2.*( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj  ,jk)      &
+                  &                       +      zwz(ji+1,jj  ,jk) + zwz(ji  ,jj+1,jk) )    &
+                  &                       + 4.*  zwz(ji  ,jj  ,jk)                       )
+               vslp(ji,jj,jk) = z1_16 * (        zww(ji-1,jj-1,jk) + zww(ji+1,jj-1,jk)      &
+                  &                       +      zww(ji-1,jj+1,jk) + zww(ji+1,jj+1,jk)      &
+                  &                       + 2.*( zww(ji  ,jj-1,jk) + zww(ji-1,jj  ,jk)      &
+                  &                       +      zww(ji+1,jj  ,jk) + zww(ji  ,jj+1,jk) )    &
+                  &                       + 4.*  zww(ji,jj    ,jk)                       )
+            END DO
+         END DO
+         !                                        !* decrease along coastal boundaries
+         DO jj = 2, jpjm1
+            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
+               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
+            END DO
+         END DO
+      END DO
+
+
+      ! II.  slopes at w point           | wslpi = mij( d/di( prd ) / d/dz( prd )
+      ! ===========================      | wslpj = mij( d/dj( prd ) / d/dz( prd )
+      !
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            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. )
+               !                                  !* Slopes at w point
+               !                                        ! i- & j-gradient of density at w-points
+               zci = MAX(  umask(ji-1,jj,jk  ) + umask(ji,jj,jk  )           &
+                  &      + umask(ji-1,jj,jk-1) + umask(ji,jj,jk-1) , zeps  ) * e1t(ji,jj)
+               zcj = MAX(  vmask(ji,jj-1,jk  ) + vmask(ji,jj,jk-1)           &
+                  &      + 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 * wmask (ji,jj,jk)
+               zaj =    (  zgrv (ji,jj-1,jk  ) + zgrv (ji,jj,jk-1)           &
+                  &      + zgrv (ji,jj-1,jk-1) + zgrv (ji,jj,jk  )   ) / zcj * wmask (ji,jj,jk)
+               !                                        ! bound the slopes: abs(zw.)<= 1/100 and zb..<0.
+               !                                        ! + kxz max= ah slope max =< e1 e3 /(pi**2 2 dt)
+               zbi = MIN( zbw ,- 100._wp* ABS( zai ) , -7.e+3_wp/e3w_n(ji,jj,jk)* ABS( zai )  )
+               zbj = MIN( zbw , -100._wp* ABS( zaj ) , -7.e+3_wp/e3w_n(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 = ( gdepw_n(ji,jj,jk) - gdepw_n(ji,jj,mikt(ji,jj) ) ) / MAX( hmlp(ji,jj) - gdepw_n(ji,jj,mikt(ji,jj)), 10._wp )
+               zwz(ji,jj,jk) = (  zai / ( zbi - zeps ) * ( 1._wp - zfk ) + zck * wslpiml(ji,jj) * zfk  ) * wmask(ji,jj,jk)
+               zww(ji,jj,jk) = (  zaj / ( zbj - zeps ) * ( 1._wp - zfk ) + zck * wslpjml(ji,jj) * zfk  ) * wmask(ji,jj,jk)
+
+!!gm  modif to suppress omlmask....  (as in Griffies operator)
+!               !                                         ! jk must be >= ML level for zfk=1. otherwise  zfk=0.
+!               zfk = REAL( 1 - 1/(1 + jk / nmln(ji+1,jj)), wp )
+!               zck = gdepw(ji,jj,jk)    / MAX( hmlp(ji,jj), 10. )
+!               zwz(ji,jj,jk) = ( zfk * zai / ( zbi - zeps ) + ( 1._wp - zfk ) * wslpiml(ji,jj) * zck ) * tmask(ji,jj,jk)
+!               zww(ji,jj,jk) = ( zfk * zaj / ( zbj - zeps ) + ( 1._wp - zfk ) * wslpjml(ji,jj) * zck ) * tmask(ji,jj,jk)
+!!gm end modif
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'ldfslp', zwz, 'T', -1.,  zww, 'T', -1. )      ! lateral boundary conditions
+      !
+      !                                           !* horizontal Shapiro filter
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1, MAX(1, jpj-3)                        ! rows jj=2 and =jpjm1 only
+            DO ji = 2, jpim1
+               zcofw = wmask(ji,jj,jk) * z1_16
+               wslpi(ji,jj,jk) = (         zwz(ji-1,jj-1,jk) + zwz(ji+1,jj-1,jk)     &
+                    &               +      zwz(ji-1,jj+1,jk) + zwz(ji+1,jj+1,jk)     &
+                    &               + 2.*( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj  ,jk)     &
+                    &               +      zwz(ji+1,jj  ,jk) + zwz(ji  ,jj+1,jk) )   &
+                    &               + 4.*  zwz(ji  ,jj  ,jk)                         ) * zcofw
+
+               wslpj(ji,jj,jk) = (         zww(ji-1,jj-1,jk) + zww(ji+1,jj-1,jk)     &
+                    &               +      zww(ji-1,jj+1,jk) + zww(ji+1,jj+1,jk)     &
+                    &               + 2.*( zww(ji  ,jj-1,jk) + zww(ji-1,jj  ,jk)     &
+                    &               +      zww(ji+1,jj  ,jk) + zww(ji  ,jj+1,jk) )   &
+                    &               + 4.*  zww(ji  ,jj  ,jk)                         ) * zcofw
+            END DO
+         END DO
+         DO jj = 3, jpj-2                               ! other rows
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zcofw = wmask(ji,jj,jk) * z1_16
+               wslpi(ji,jj,jk) = (         zwz(ji-1,jj-1,jk) + zwz(ji+1,jj-1,jk)     &
+                    &               +      zwz(ji-1,jj+1,jk) + zwz(ji+1,jj+1,jk)     &
+                    &               + 2.*( zwz(ji  ,jj-1,jk) + zwz(ji-1,jj  ,jk)     &
+                    &               +      zwz(ji+1,jj  ,jk) + zwz(ji  ,jj+1,jk) )   &
+                    &               + 4.*  zwz(ji  ,jj  ,jk)                         ) * zcofw
+
+               wslpj(ji,jj,jk) = (         zww(ji-1,jj-1,jk) + zww(ji+1,jj-1,jk)     &
+                    &               +      zww(ji-1,jj+1,jk) + zww(ji+1,jj+1,jk)     &
+                    &               + 2.*( zww(ji  ,jj-1,jk) + zww(ji-1,jj  ,jk)     &
+                    &               +      zww(ji+1,jj  ,jk) + zww(ji  ,jj+1,jk) )   &
+                    &               + 4.*  zww(ji  ,jj  ,jk)                         ) * zcofw
+            END DO
+         END DO
+         !                                        !* decrease in vicinity of topography
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               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
+            END DO
+         END DO
+      END DO
+
+      ! IV. Lateral boundary conditions
+      ! ===============================
+      CALL lbc_lnk_multi( 'ldfslp', uslp , 'U', -1. , vslp , 'V', -1. , wslpi, 'W', -1., wslpj, 'W', -1. )
+
+      IF(ln_ctl) THEN
+         CALL prt_ctl(tab3d_1=uslp , clinfo1=' slp  - u : ', tab3d_2=vslp,  clinfo2=' v : ', kdim=jpk)
+         CALL prt_ctl(tab3d_1=wslpi, clinfo1=' slp  - wi: ', tab3d_2=wslpj, clinfo2=' wj: ', kdim=jpk)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('ldf_slp')
+      !
+   END SUBROUTINE ldf_slp
+
+
+   SUBROUTINE ldf_slp_triad ( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE ldf_slp_triad  ***
+      !!
+      !! ** Purpose :   Compute the squared slopes of neutral surfaces (slope
+      !!      of iso-pycnal surfaces referenced locally) (ln_traldf_triad=T)
+      !!      at W-points using the Griffies quarter-cells.
+      !!
+      !! ** Method  :   calculates alpha and beta at T-points
+      !!
+      !! ** Action : - triadi_g, triadj_g   T-pts i- and j-slope triads relative to geopot. (used for eiv)
+      !!             - triadi , triadj    T-pts i- and j-slope triads relative to model-coordinate
+      !!             - wslp2              squared slope of neutral surfaces at w-points.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt             ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk, jl, ip, jp, kp  ! dummy loop indices
+      INTEGER  ::   iku, ikv                    ! local integer
+      REAL(wp) ::   zfacti, zfactj              ! local scalars
+      REAL(wp) ::   znot_thru_surface           ! local scalars
+      REAL(wp) ::   zdit, zdis, zdkt, zbu, zbti, zisw
+      REAL(wp) ::   zdjt, zdjs, zdks, zbv, zbtj, zjsw
+      REAL(wp) ::   zdxrho_raw, zti_coord, zti_raw, zti_lim, zti_g_raw, zti_g_lim
+      REAL(wp) ::   zdyrho_raw, ztj_coord, ztj_raw, ztj_lim, ztj_g_raw, ztj_g_lim
+      REAL(wp) ::   zdzrho_raw
+      REAL(wp) ::   zbeta0, ze3_e1, ze3_e2
+      REAL(wp), DIMENSION(jpi,jpj)     ::   z1_mlbw
+      REAL(wp), DIMENSION(jpi,jpj,jpk,0:1) ::   zdxrho , zdyrho, zdzrho     ! Horizontal and vertical density gradients
+      REAL(wp), DIMENSION(jpi,jpj,0:1,0:1) ::   zti_mlb, ztj_mlb            ! for Griffies operator only
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('ldf_slp_triad')
+      !
+      !--------------------------------!
+      !  Some preliminary calculation  !
+      !--------------------------------!
+      !
+      DO jl = 0, 1                            !==  unmasked before density i- j-, k-gradients  ==!
+         !
+         ip = jl   ;   jp = jl                ! guaranteed nonzero gradients ( absolute value larger than repsln)
+         DO jk = 1, jpkm1                     ! done each pair of triad
+            DO jj = 1, jpjm1                  ! NB: not masked ==>  a minimum value is set
+               DO ji = 1, fs_jpim1            ! vector opt.
+                  zdit = ( tsb(ji+1,jj,jk,jp_tem) - tsb(ji,jj,jk,jp_tem) )    ! i-gradient of T & S at u-point
+                  zdis = ( tsb(ji+1,jj,jk,jp_sal) - tsb(ji,jj,jk,jp_sal) )
+                  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 = ( - rab_b(ji+ip,jj   ,jk,jp_tem) * zdit + rab_b(ji+ip,jj   ,jk,jp_sal) * zdis ) * r1_e1u(ji,jj)
+                  zdyrho_raw = ( - rab_b(ji   ,jj+jp,jk,jp_tem) * zdjt + rab_b(ji   ,jj+jp,jk,jp_sal) * zdjs ) * r1_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
+            END DO
+         END DO
+         !
+         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
+                  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 = ( - rab_b(ji+ip,jj   ,iku,jp_tem) * zdit + rab_b(ji+ip,jj   ,iku,jp_sal) * zdis ) * r1_e1u(ji,jj)
+                  zdyrho_raw = ( - rab_b(ji   ,jj+jp,ikv,jp_tem) * zdjt + rab_b(ji   ,jj+jp,ikv,jp_sal) * zdjs ) * r1_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 )
+               END DO
+            END DO
+         ENDIF
+         !
+      END DO
+
+      DO kp = 0, 1                            !==  unmasked before density i- j-, k-gradients  ==!
+         DO jk = 1, jpkm1                     ! done each pair of triad
+            DO jj = 1, jpj                    ! NB: not masked ==>  a minimum value is set
+               DO ji = 1, jpi                 ! vector opt.
+                  IF( jk+kp > 1 ) THEN        ! k-gradient of T & S a jk+kp
+                     zdkt = ( tsb(ji,jj,jk+kp-1,jp_tem) - tsb(ji,jj,jk+kp,jp_tem) )
+                     zdks = ( tsb(ji,jj,jk+kp-1,jp_sal) - tsb(ji,jj,jk+kp,jp_sal) )
+                  ELSE
+                     zdkt = 0._wp                                             ! 1st level gradient set to zero
+                     zdks = 0._wp
+                  ENDIF
+                  zdzrho_raw = ( - rab_b(ji,jj,jk   ,jp_tem) * zdkt & 
+                             &   + rab_b(ji,jj,jk   ,jp_sal) * zdks &
+                             & ) / e3w_n(ji,jj,jk+kp)  
+                  zdzrho(ji,jj,jk,kp) = - MIN( - repsln , zdzrho_raw )    ! force zdzrho >= repsln
+                 END DO
+            END DO
+         END DO
+      END DO
+      !
+      DO jj = 1, jpj                          !==  Reciprocal depth of the w-point below ML base  ==!
+         DO ji = 1, jpi
+            jk = MIN( nmln(ji,jj), mbkt(ji,jj) ) + 1     ! MIN in case ML depth is the ocean depth
+            z1_mlbw(ji,jj) = 1._wp / gdepw_n(ji,jj,jk)
+         END DO
+      END DO
+      !
+      !                                       !==  intialisations to zero  ==!
+      !
+      wslp2  (:,:,:)     = 0._wp              ! wslp2 will be cumulated 3D field set to zero
+      triadi_g(:,:,1,:,:) = 0._wp   ;   triadi_g(:,:,jpk,:,:) = 0._wp   ! set surface and bottom slope to zero
+      triadj_g(:,:,1,:,:) = 0._wp   ;   triadj_g(:,:,jpk,:,:) = 0._wp
+      !!gm _iso set to zero missing
+      triadi  (:,:,1,:,:) = 0._wp   ;   triadj  (:,:,jpk,:,:) = 0._wp   ! set surface and bottom slope to zero
+      triadj  (:,:,1,:,:) = 0._wp   ;   triadj  (:,:,jpk,:,:) = 0._wp
+
+      !-------------------------------------!
+      !  Triads just below the Mixed Layer  !
+      !-------------------------------------!
+      !
+      DO jl = 0, 1                            ! calculate slope of the 4 triads immediately ONE level below mixed-layer base
+         DO kp = 0, 1                         ! with only the slope-max limit   and   MASKED
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1
+                  ip = jl   ;   jp = jl
+                  !
+                  jk = nmln(ji+ip,jj) + 1
+                  IF( jk > mbkt(ji+ip,jj) ) THEN   ! ML reaches bottom
+                     zti_mlb(ji+ip,jj   ,1-ip,kp) = 0.0_wp
+                  ELSE                             
+                     ! Add s-coordinate slope at t-points (do this by *subtracting* gradient of depth)
+                     zti_g_raw = (  zdxrho(ji+ip,jj,jk-kp,1-ip) / zdzrho(ji+ip,jj,jk-kp,kp)      &
+                        &          - ( gdept_n(ji+1,jj,jk-kp) - gdept_n(ji,jj,jk-kp) ) * r1_e1u(ji,jj)  ) * umask(ji,jj,jk)
+                     ze3_e1    =  e3w_n(ji+ip,jj,jk-kp) * r1_e1u(ji,jj) 
+                     zti_mlb(ji+ip,jj   ,1-ip,kp) = SIGN( MIN( rn_slpmax, 5.0_wp * ze3_e1  , ABS( zti_g_raw ) ), zti_g_raw )
+                  ENDIF
+                  !
+                  jk = nmln(ji,jj+jp) + 1
+                  IF( jk >  mbkt(ji,jj+jp) ) THEN  !ML reaches bottom
+                     ztj_mlb(ji   ,jj+jp,1-jp,kp) = 0.0_wp
+                  ELSE
+                     ztj_g_raw = (  zdyrho(ji,jj+jp,jk-kp,1-jp) / zdzrho(ji,jj+jp,jk-kp,kp)      &
+                        &      - ( gdept_n(ji,jj+1,jk-kp) - gdept_n(ji,jj,jk-kp) ) / e2v(ji,jj)  ) * vmask(ji,jj,jk)
+                     ze3_e2    =  e3w_n(ji,jj+jp,jk-kp) / e2v(ji,jj)
+                     ztj_mlb(ji   ,jj+jp,1-jp,kp) = SIGN( MIN( rn_slpmax, 5.0_wp * ze3_e2  , ABS( ztj_g_raw ) ), ztj_g_raw )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+
+      !-------------------------------------!
+      !  Triads with surface limits         !
+      !-------------------------------------!
+      !
+      DO kp = 0, 1                            ! k-index of triads
+         DO jl = 0, 1
+            ip = jl   ;   jp = jl             ! i- and j-indices of triads (i-k and j-k planes)
+            DO jk = 1, jpkm1
+               ! Must mask contribution to slope from dz/dx at constant s for triads jk=1,kp=0 that poke up though ocean surface
+               znot_thru_surface = REAL( 1-1/(jk+kp), wp )  !jk+kp=1,=0.; otherwise=1.0
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1         ! vector opt.
+                     !
+                     ! Calculate slope relative to geopotentials used for GM skew fluxes
+                     ! Add s-coordinate slope at t-points (do this by *subtracting* gradient of depth)
+                     ! Limit by slope *relative to geopotentials* by rn_slpmax, and mask by psi-point
+                     ! masked by umask taken at the level of dz(rho)
+                     !
+                     ! raw slopes: unmasked unbounded slopes (relative to geopotential (zti_g) and model surface (zti)
+                     !
+                     zti_raw   = zdxrho(ji+ip,jj   ,jk,1-ip) / zdzrho(ji+ip,jj   ,jk,kp)                   ! unmasked
+                     ztj_raw   = zdyrho(ji   ,jj+jp,jk,1-jp) / zdzrho(ji   ,jj+jp,jk,kp)
+                     !
+                     ! Must mask contribution to slope for triad jk=1,kp=0 that poke up though ocean surface
+                     zti_coord = znot_thru_surface * ( gdept_n(ji+1,jj  ,jk) - gdept_n(ji,jj,jk) ) * r1_e1u(ji,jj)
+                     ztj_coord = znot_thru_surface * ( gdept_n(ji  ,jj+1,jk) - gdept_n(ji,jj,jk) ) * r1_e2v(ji,jj)     ! unmasked
+                     zti_g_raw = zti_raw - zti_coord      ! ref to geopot surfaces
+                     ztj_g_raw = ztj_raw - ztj_coord
+                     ! additional limit required in bilaplacian case
+                     ze3_e1    = e3w_n(ji+ip,jj   ,jk+kp) * r1_e1u(ji,jj)
+                     ze3_e2    = e3w_n(ji   ,jj+jp,jk+kp) * r1_e2v(ji,jj)
+                     ! NB: hard coded factor 5 (can be a namelist parameter...)
+                     zti_g_lim = SIGN( MIN( rn_slpmax, 5.0_wp * ze3_e1, ABS( zti_g_raw ) ), zti_g_raw )
+                     ztj_g_lim = SIGN( MIN( rn_slpmax, 5.0_wp * ze3_e2, ABS( ztj_g_raw ) ), ztj_g_raw )
+                     !
+                     ! Below  ML use limited zti_g as is & mask
+                     ! Inside ML replace by linearly reducing sx_mlb towards surface & mask
+                     !
+                     zfacti = REAL( 1 - 1/(1 + (jk+kp-1)/nmln(ji+ip,jj)), wp )  ! k index of uppermost point(s) of triad is jk+kp-1
+                     zfactj = REAL( 1 - 1/(1 + (jk+kp-1)/nmln(ji,jj+jp)), wp )  ! must be .ge. nmln(ji,jj) for zfact=1
+                     !                                                          !                   otherwise  zfact=0
+                     zti_g_lim =          ( zfacti   * zti_g_lim                       &
+                        &      + ( 1._wp - zfacti ) * zti_mlb(ji+ip,jj,1-ip,kp)   &
+                        &                           * gdepw_n(ji+ip,jj,jk+kp) * z1_mlbw(ji+ip,jj) ) * umask(ji,jj,jk+kp)
+                     ztj_g_lim =          ( zfactj   * ztj_g_lim                       &
+                        &      + ( 1._wp - zfactj ) * ztj_mlb(ji,jj+jp,1-jp,kp)   &
+                        &                           * gdepw_n(ji,jj+jp,jk+kp) * z1_mlbw(ji,jj+jp) ) * vmask(ji,jj,jk+kp)
+                     !
+                     triadi_g(ji+ip,jj   ,jk,1-ip,kp) = zti_g_lim
+                     triadj_g(ji   ,jj+jp,jk,1-jp,kp) = ztj_g_lim
+                     !
+                     ! Get coefficients of isoneutral diffusion tensor
+                     ! 1. Utilise gradients *relative* to s-coordinate, so add t-point slopes (*subtract* depth gradients)
+                     ! 2. We require that isoneutral diffusion  gives no vertical buoyancy flux
+                     !     i.e. 33 term = (real slope* 31, 13 terms)
+                     ! To do this, retain limited sx**2  in vertical flux, but divide by real slope for 13/31 terms
+                     ! Equivalent to tapering A_iso = sx_limited**2/(real slope)**2
+                     !
+                     zti_lim  = ( zti_g_lim + zti_coord ) * umask(ji,jj,jk+kp)    ! remove coordinate slope => relative to coordinate surfaces
+                     ztj_lim  = ( ztj_g_lim + ztj_coord ) * vmask(ji,jj,jk+kp)
+                     !
+                     IF( ln_triad_iso ) THEN
+                        zti_raw = zti_lim*zti_lim / zti_raw
+                        ztj_raw = ztj_lim*ztj_lim / ztj_raw
+                        zti_raw = SIGN( MIN( ABS(zti_lim), ABS( zti_raw ) ), zti_raw )
+                        ztj_raw = SIGN( MIN( ABS(ztj_lim), ABS( ztj_raw ) ), ztj_raw )
+                        zti_lim = zfacti * zti_lim + ( 1._wp - zfacti ) * zti_raw
+                        ztj_lim = zfactj * ztj_lim + ( 1._wp - zfactj ) * ztj_raw
+                     ENDIF
+                     !                                      ! switching triad scheme 
+                     zisw = (1._wp - rn_sw_triad ) + rn_sw_triad    &
+                        &            * 2._wp * ABS( 0.5_wp - kp - ( 0.5_wp - ip ) * SIGN( 1._wp , zdxrho(ji+ip,jj,jk,1-ip) )  )
+                     zjsw = (1._wp - rn_sw_triad ) + rn_sw_triad    &
+                        &            * 2._wp * ABS( 0.5_wp - kp - ( 0.5_wp - jp ) * SIGN( 1._wp , zdyrho(ji,jj+jp,jk,1-jp) )  )
+                     !
+                     triadi(ji+ip,jj   ,jk,1-ip,kp) = zti_lim * zisw
+                     triadj(ji   ,jj+jp,jk,1-jp,kp) = ztj_lim * zjsw
+                     !
+                     zbu  = e1e2u(ji   ,jj   ) * e3u_n(ji   ,jj   ,jk   )
+                     zbv  = e1e2v(ji   ,jj   ) * e3v_n(ji   ,jj   ,jk   )
+                     zbti = e1e2t(ji+ip,jj   ) * e3w_n(ji+ip,jj   ,jk+kp)
+                     zbtj = e1e2t(ji   ,jj+jp) * e3w_n(ji   ,jj+jp,jk+kp)
+                     !
+                     wslp2(ji+ip,jj,jk+kp) = wslp2(ji+ip,jj,jk+kp) + 0.25_wp * zbu / zbti * zti_g_lim*zti_g_lim      ! masked
+                     wslp2(ji,jj+jp,jk+kp) = wslp2(ji,jj+jp,jk+kp) + 0.25_wp * zbv / zbtj * ztj_g_lim*ztj_g_lim
+                  END DO
+               END DO
+            END DO
+         END DO
+      END DO
+      !
+      wslp2(:,:,1) = 0._wp                ! force the surface wslp to zero
+
+      CALL lbc_lnk( 'ldfslp', wslp2, 'W', 1. )      ! lateral boundary confition on wslp2 only   ==>>> gm : necessary ? to be checked
+      !
+      IF( ln_timing )   CALL timing_stop('ldf_slp_triad')
+      !
+   END SUBROUTINE ldf_slp_triad
+
+
+   SUBROUTINE ldf_slp_mxl( prd, pn2, p_gru, p_grv, p_dzr )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_slp_mxl  ***
+      !!
+      !! ** Purpose :   Compute the slopes of iso-neutral surface just below
+      !!              the mixed layer.
+      !!
+      !! ** Method  :   The slope in the i-direction is computed at u- & w-points
+      !!              (uslpml, wslpiml) and the slope in the j-direction is computed
+      !!              at v- and w-points (vslpml, wslpjml) with the same bounds as
+      !!              in ldf_slp.
+      !!
+      !! ** Action  :   uslpml, wslpiml :  i- &  j-slopes of neutral surfaces
+      !!                vslpml, wslpjml    just below the mixed layer
+      !!                omlmask         :  mixed layer mask
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   prd            ! in situ density
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   pn2            ! Brunt-Vaisala frequency (locally ref.)
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   p_gru, p_grv   ! i- & j-gradient of density (u- & v-pts)
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   p_dzr          ! z-gradient of density      (T-point)
+      !!
+      INTEGER  ::   ji , jj , jk                   ! dummy loop indices
+      INTEGER  ::   iku, ikv, ik, ikm1             ! local integers
+      REAL(wp) ::   zeps, zm1_g, zm1_2g, z1_slpmax ! local scalars
+      REAL(wp) ::   zci, zfi, zau, zbu, zai, zbi   !   -      -
+      REAL(wp) ::   zcj, zfj, zav, zbv, zaj, zbj   !   -      -
+      REAL(wp) ::   zck, zfk,      zbw             !   -      -
+      !!----------------------------------------------------------------------
+      !
+      zeps   =  1.e-20_wp        !==   Local constant initialization   ==!
+      zm1_g  = -1.0_wp / grav
+      zm1_2g = -0.5_wp / grav
+      z1_slpmax = 1._wp / rn_slpmax
+      !
+      uslpml (1,:) = 0._wp      ;      uslpml (jpi,:) = 0._wp
+      vslpml (1,:) = 0._wp      ;      vslpml (jpi,:) = 0._wp
+      wslpiml(1,:) = 0._wp      ;      wslpiml(jpi,:) = 0._wp
+      wslpjml(1,:) = 0._wp      ;      wslpjml(jpi,:) = 0._wp
+      !
+      !                                            !==   surface mixed layer mask   !
+      DO jk = 1, jpk                               ! =1 inside the mixed layer, =0 otherwise
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ik = nmln(ji,jj) - 1
+               IF( jk <= ik ) THEN   ;   omlmask(ji,jj,jk) = 1._wp
+               ELSE                  ;   omlmask(ji,jj,jk) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+
+      ! Slopes of isopycnal surfaces just before bottom of mixed layer
+      ! --------------------------------------------------------------
+      ! The slope are computed as in the 3D case.
+      ! A key point here is the definition of the mixed layer at u- and v-points.
+      ! It is assumed to be the maximum of the two neighbouring T-point mixed layer depth.
+      ! Otherwise, a n2 value inside the mixed layer can be involved in the computation
+      ! of the slope, resulting in a too steep diagnosed slope and thus a spurious eddy
+      ! induce velocity field near the base of the mixed layer.
+      !-----------------------------------------------------------------------
+      !
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            !                        !==   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  )   !
+            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) )
+            !                        !- horizontal density gradient at u- & v-points
+            zau = p_gru(ji,jj,iku) * r1_e1u(ji,jj)
+            zav = p_grv(ji,jj,ikv) * r1_e2v(ji,jj)
+            !                        !- bound the slopes: abs(zw.)<= 1/100 and zb..<0
+            !                           kxz max= ah slope max =< e1 e3 /(pi**2 2 dt)
+            zbu = MIN(  zbu , - z1_slpmax * ABS( zau ) , -7.e+3_wp/e3u_n(ji,jj,iku)* ABS( zau )  )
+            zbv = MIN(  zbv , - z1_slpmax * ABS( zav ) , -7.e+3_wp/e3v_n(ji,jj,ikv)* ABS( zav )  )
+            !                        !- Slope at u- & v-points (uslpml, vslpml)
+            uslpml(ji,jj) = zau / ( zbu - zeps ) * umask(ji,jj,iku)
+            vslpml(ji,jj) = zav / ( zbv - zeps ) * vmask(ji,jj,ikv)
+            !
+            !                        !==   i- & j-slopes at w-points just below the Mixed Layer   ==!
+            !
+            ik   = MIN( nmln(ji,jj) + 1, jpk )
+            ikm1 = MAX( 1, ik-1 )
+            !                        !- vertical density gradient for w-slope (from N^2)
+            zbw = zm1_2g * pn2 (ji,jj,ik) * ( prd (ji,jj,ik) + prd (ji,jj,ikm1) + 2. )
+            !                        !- horizontal density i- & j-gradient at w-points
+            zci = MAX(   umask(ji-1,jj,ik  ) + umask(ji,jj,ik  )           &
+               &       + umask(ji-1,jj,ikm1) + umask(ji,jj,ikm1) , zeps  ) * e1t(ji,jj)
+            zcj = MAX(   vmask(ji,jj-1,ik  ) + vmask(ji,jj,ik  )           &
+               &       + vmask(ji,jj-1,ikm1) + vmask(ji,jj,ikm1) , zeps  ) * e2t(ji,jj)
+            zai =    (   p_gru(ji-1,jj,ik  ) + p_gru(ji,jj,ik)             &
+               &       + p_gru(ji-1,jj,ikm1) + p_gru(ji,jj,ikm1  )  ) / zci  * tmask(ji,jj,ik)
+            zaj =    (   p_grv(ji,jj-1,ik  ) + p_grv(ji,jj,ik  )           &
+               &       + p_grv(ji,jj-1,ikm1) + p_grv(ji,jj,ikm1)  ) / zcj  * tmask(ji,jj,ik)
+            !                        !- bound the slopes: abs(zw.)<= 1/100 and zb..<0.
+            !                           kxz max= ah slope max =< e1 e3 /(pi**2 2 dt)
+            zbi = MIN(  zbw , -100._wp* ABS( zai ) , -7.e+3_wp/e3w_n(ji,jj,ik)* ABS( zai )  )
+            zbj = MIN(  zbw , -100._wp* ABS( zaj ) , -7.e+3_wp/e3w_n(ji,jj,ik)* ABS( zaj )  )
+            !                        !- i- & j-slope at w-points (wslpiml, wslpjml)
+            wslpiml(ji,jj) = zai / ( zbi - zeps ) * tmask (ji,jj,ik)
+            wslpjml(ji,jj) = zaj / ( zbj - zeps ) * tmask (ji,jj,ik)
+         END DO
+      END DO
+      !!gm this lbc_lnk should be useless....
+      CALL lbc_lnk_multi( 'ldfslp', uslpml , 'U', -1. , vslpml , 'V', -1. , wslpiml, 'W', -1. , wslpjml, 'W', -1. ) 
+      !
+   END SUBROUTINE ldf_slp_mxl
+
+
+   SUBROUTINE ldf_slp_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_slp_init  ***
+      !!
+      !! ** Purpose :   Initialization for the isopycnal slopes computation
+      !!
+      !! ** Method  :   
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      INTEGER ::   ierr         ! local integer
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'ldf_slp_init : direction of lateral mixing'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      ALLOCATE( ah_wslp2(jpi,jpj,jpk) , akz(jpi,jpj,jpk) , STAT=ierr )
+      IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'ldf_slp_init : unable to allocate ah_slp2 or akz' )
+      !
+      IF( ln_traldf_triad ) THEN        ! Griffies operator : triad of slopes
+         IF(lwp) WRITE(numout,*) '   ==>>>   triad) operator (Griffies)'
+         ALLOCATE( triadi_g(jpi,jpj,jpk,0:1,0:1) , triadj_g(jpi,jpj,jpk,0:1,0:1) ,     &
+            &      triadi  (jpi,jpj,jpk,0:1,0:1) , triadj  (jpi,jpj,jpk,0:1,0:1) ,     &
+            &      wslp2   (jpi,jpj,jpk)                                         , STAT=ierr )
+         IF( ierr > 0      )   CALL ctl_stop( 'STOP', 'ldf_slp_init : unable to allocate Griffies operator slope' )
+         IF( ln_dynldf_iso )   CALL ctl_stop( 'ldf_slp_init: Griffies operator on momentum not supported' )
+         !
+      ELSE                             ! Madec operator : slopes at u-, v-, and w-points
+         IF(lwp) WRITE(numout,*) '   ==>>>   iso operator (Madec)'
+         ALLOCATE( omlmask(jpi,jpj,jpk) ,                                                                        &
+            &      uslp(jpi,jpj,jpk) , uslpml(jpi,jpj) , wslpi(jpi,jpj,jpk) , wslpiml(jpi,jpj) ,     &
+            &      vslp(jpi,jpj,jpk) , vslpml(jpi,jpj) , wslpj(jpi,jpj,jpk) , wslpjml(jpi,jpj) , STAT=ierr )
+         IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'ldf_slp_init : unable to allocate Madec operator slope ' )
+
+         ! Direction of lateral diffusion (tracers and/or momentum)
+         ! ------------------------------
+         uslp (:,:,:) = 0._wp   ;   uslpml (:,:) = 0._wp      ! set the slope to zero (even in s-coordinates)
+         vslp (:,:,:) = 0._wp   ;   vslpml (:,:) = 0._wp
+         wslpi(:,:,:) = 0._wp   ;   wslpiml(:,:) = 0._wp
+         wslpj(:,:,:) = 0._wp   ;   wslpjml(:,:) = 0._wp
+
+         !!gm I no longer understand this.....
+!!gm         IF( (ln_traldf_hor .OR. ln_dynldf_hor) .AND. .NOT. (.NOT.ln_linssh .AND. ln_rstart) ) THEN
+!            IF(lwp)   WRITE(numout,*) '          Horizontal mixing in s-coordinate: slope = slope of s-surfaces'
+!
+!            ! geopotential diffusion in s-coordinates on tracers and/or momentum
+!            ! The slopes of s-surfaces are computed once (no call to ldfslp in step)
+!            ! The slopes for momentum diffusion are i- or j- averaged of those on tracers
+!
+!            ! set the slope of diffusion to the slope of s-surfaces
+!            !      ( c a u t i o n : minus sign as dep has positive value )
+!            DO jk = 1, jpk
+!               DO jj = 2, jpjm1
+!                  DO ji = fs_2, fs_jpim1   ! vector opt.
+!                     uslp (ji,jj,jk) = - ( gdept_n(ji+1,jj,jk) - gdept_n(ji ,jj ,jk) ) * r1_e1u(ji,jj) * umask(ji,jj,jk)
+!                     vslp (ji,jj,jk) = - ( gdept_n(ji,jj+1,jk) - gdept_n(ji ,jj ,jk) ) * r1_e2v(ji,jj) * vmask(ji,jj,jk)
+!                     wslpi(ji,jj,jk) = - ( gdepw_n(ji+1,jj,jk) - gdepw_n(ji-1,jj,jk) ) * r1_e1t(ji,jj) * wmask(ji,jj,jk) * 0.5
+!                     wslpj(ji,jj,jk) = - ( gdepw_n(ji,jj+1,jk) - gdepw_n(ji,jj-1,jk) ) * r1_e2t(ji,jj) * wmask(ji,jj,jk) * 0.5
+!                  END DO
+!               END DO
+!            END DO
+!            CALL lbc_lnk_multi( 'ldfslp', uslp , 'U', -1. ; CALL lbc_lnk( 'ldfslp', vslp , 'V', -1.,  wslpi, 'W', -1.,  wslpj, 'W', -1. )
+!!gm         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE ldf_slp_init
+
+   !!======================================================================
+END MODULE ldfslp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldftra.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldftra.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/LDF/ldftra.F90	(revision 14097)
@@ -0,0 +1,953 @@
+MODULE ldftra
+   !!======================================================================
+   !!                       ***  MODULE  ldftra  ***
+   !! Ocean physics:  lateral diffusivity coefficients 
+   !!=====================================================================
+   !! History :       ! 1997-07  (G. Madec)  from inimix.F split in 2 routines
+   !!   NEMO     1.0  ! 2002-09  (G. Madec)  F90: Free form and module
+   !!            2.0  ! 2005-11  (G. Madec)  
+   !!            3.7  ! 2013-12  (F. Lemarie, G. Madec)  restructuration/simplification of aht/aeiv specification,
+   !!                 !                                  add velocity dependent coefficient and optional read in file
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   ldf_tra_init : initialization, namelist read, and parameters control
+   !!   ldf_tra      : update lateral eddy diffusivity coefficients at each time step 
+   !!   ldf_eiv_init : initialization of the eiv coeff. from namelist choices 
+   !!   ldf_eiv      : time evolution of the eiv coefficients (function of the growth rate of baroclinic instability)
+   !!   ldf_eiv_trp  : add to the input ocean transport the contribution of the EIV parametrization
+   !!   ldf_eiv_dia  : diagnose the eddy induced velocity from the eiv streamfunction
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE ldfslp          ! lateral diffusion: slope of iso-neutral surfaces
+   USE ldfc1d_c2d      ! lateral diffusion: 1D & 2D cases 
+   USE diaptr
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module for ehanced bottom friction file
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   ldf_tra_init   ! called by nemogcm.F90
+   PUBLIC   ldf_tra        ! called by step.F90
+   PUBLIC   ldf_eiv_init   ! called by nemogcm.F90
+   PUBLIC   ldf_eiv        ! called by step.F90
+   PUBLIC   ldf_eiv_trp    ! called by traadv.F90
+   PUBLIC   ldf_eiv_dia    ! called by traldf_iso and traldf_iso_triad.F90
+   
+   !                                   !!* Namelist namtra_ldf : lateral mixing on tracers * 
+   !                                    != Operator type =!
+   LOGICAL , PUBLIC ::   ln_traldf_OFF       !: no operator: No explicit diffusion
+   LOGICAL , PUBLIC ::   ln_traldf_lap       !: laplacian operator
+   LOGICAL , PUBLIC ::   ln_traldf_blp       !: bilaplacian operator
+   !                                    != Direction of action =!
+   LOGICAL , PUBLIC ::   ln_traldf_lev       !: iso-level direction
+   LOGICAL , PUBLIC ::   ln_traldf_hor       !: horizontal (geopotential) direction
+!  LOGICAL , PUBLIC ::   ln_traldf_iso       !: iso-neutral direction                    (see ldfslp)
+   !		       	                      != iso-neutral options =!
+!  LOGICAL , PUBLIC ::   ln_traldf_triad     !: griffies triad scheme                    (see ldfslp)
+   LOGICAL , PUBLIC ::   ln_traldf_msc       !: Method of Stabilizing Correction 
+!  LOGICAL , PUBLIC ::   ln_triad_iso        !: pure horizontal mixing in ML             (see ldfslp)
+!  LOGICAL , PUBLIC ::   ln_botmix_triad     !: mixing on bottom                         (see ldfslp)
+!  REAL(wp), PUBLIC ::   rn_sw_triad         !: =1/0 switching triad / all 4 triads used (see ldfslp)
+!  REAL(wp), PUBLIC ::   rn_slpmax           !: slope limit                              (see ldfslp)
+   !                                    !=  Coefficients =!
+   INTEGER , PUBLIC ::   nn_aht_ijk_t        !: choice of time & space variations of the lateral eddy diffusivity coef.
+   !                                            !  time invariant coefficients:  aht_0 = 1/2  Ud*Ld   (lap case) 
+   !                                            !                                bht_0 = 1/12 Ud*Ld^3 (blp case)
+   REAL(wp), PUBLIC ::      rn_Ud               !: lateral diffusive velocity  [m/s]
+   REAL(wp), PUBLIC ::      rn_Ld               !: lateral diffusive length    [m]
+
+   !                                   !!* Namelist namtra_eiv : eddy induced velocity param. *
+   !                                    != Use/diagnose eiv =!
+   LOGICAL , PUBLIC ::   ln_ldfeiv           !: eddy induced velocity flag
+   LOGICAL , PUBLIC ::   ln_ldfeiv_dia       !: diagnose & output eiv streamfunction and velocity (IOM)
+   !                                    != Coefficients =!
+   INTEGER , PUBLIC ::   nn_aei_ijk_t        !: choice of time/space variation of the eiv coeff.
+   REAL(wp), PUBLIC ::      rn_Ue               !: lateral diffusive velocity  [m/s]
+   REAL(wp), PUBLIC ::      rn_Le               !: lateral diffusive length    [m]
+   
+   !                                  ! Flag to control the type of lateral diffusive operator
+   INTEGER, PARAMETER, PUBLIC ::   np_ERROR  =-10   ! error in specification of lateral diffusion
+   INTEGER, PARAMETER, PUBLIC ::   np_no_ldf = 00   ! without operator (i.e. no lateral diffusive trend)
+   !                          !!      laplacian     !    bilaplacian    !
+   INTEGER, PARAMETER, PUBLIC ::   np_lap    = 10   ,   np_blp    = 20  ! iso-level operator
+   INTEGER, PARAMETER, PUBLIC ::   np_lap_i  = 11   ,   np_blp_i  = 21  ! standard iso-neutral or geopotential operator
+   INTEGER, PARAMETER, PUBLIC ::   np_lap_it = 12   ,   np_blp_it = 22  ! triad    iso-neutral or geopotential operator
+
+   INTEGER , PUBLIC ::   nldf_tra      = 0         !: type of lateral diffusion used defined from ln_traldf_... (namlist logicals)
+   LOGICAL , PUBLIC ::   l_ldftra_time = .FALSE.   !: flag for time variation of the lateral eddy diffusivity coef.
+   LOGICAL , PUBLIC ::   l_ldfeiv_time = .FALSE.   !: flag for time variation of the eiv coef.
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ahtu, ahtv   !: eddy diffusivity coef. at U- and V-points   [m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aeiu, aeiv   !: eddy induced velocity coeff.                [m2/s]
+
+   REAL(wp) ::   aht0, aei0               ! constant eddy coefficients (deduced from namelist values)                     [m2/s]
+   REAL(wp) ::   r1_2  = 0.5_wp           ! =1/2
+   REAL(wp) ::   r1_4  = 0.25_wp          ! =1/4
+   REAL(wp) ::   r1_12 = 1._wp / 12._wp   ! =1/12
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE ldf_tra_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_tra_init  ***
+      !! 
+      !! ** Purpose :   initializations of the tracer lateral mixing coeff.
+      !!
+      !! ** Method  : * the eddy diffusivity coef. specification depends on:
+      !!
+      !!    ln_traldf_lap = T     laplacian operator
+      !!    ln_traldf_blp = T   bilaplacian operator
+      !!
+      !!    nn_aht_ijk_t  =  0 => = constant
+      !!                  !
+      !!                  = 10 => = F(z) : constant with a reduction of 1/4 with depth 
+      !!                  !
+      !!                  =-20 => = F(i,j)   = shape read in 'eddy_diffusivity.nc' file
+      !!                  = 20    = F(i,j)   = F(e1,e2) or F(e1^3,e2^3) (lap or bilap case)
+      !!                  = 21    = F(i,j,t) = F(growth rate of baroclinic instability)
+      !!                  !
+      !!                  =-30 => = F(i,j,k)   = shape read in 'eddy_diffusivity.nc' file
+      !!                  = 30    = F(i,j,k)   = 2D (case 20) + decrease with depth (case 10)
+      !!                  = 31    = F(i,j,k,t) = F(local velocity) (  1/2  |u|e     laplacian operator
+      !!                                                           or 1/12 |u|e^3 bilaplacian operator )
+      !!              * initialisation of the eddy induced velocity coefficient by a call to ldf_eiv_init 
+      !!            
+      !! ** action  : ahtu, ahtv initialized one for all or l_ldftra_time set to true
+      !!              aeiu, aeiv initialized one for all or l_ldfeiv_time set to true
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jk                             ! dummy loop indices
+      INTEGER  ::   ioptio, ierr, inum, ios, inn   ! local integer
+      REAL(wp) ::   zah_max, zUfac                 !   -      -
+      CHARACTER(len=5) ::   cl_Units               ! units (m2/s or m4/s)
+      !!
+      NAMELIST/namtra_ldf/ ln_traldf_OFF, ln_traldf_lap  , ln_traldf_blp  ,   &   ! type of operator
+         &                 ln_traldf_lev, ln_traldf_hor  , ln_traldf_triad,   &   ! acting direction of the operator
+         &                 ln_traldf_iso, ln_traldf_msc  ,  rn_slpmax     ,   &   ! option for iso-neutral operator
+         &                 ln_triad_iso , ln_botmix_triad, rn_sw_triad    ,   &   ! option for triad operator
+         &                 nn_aht_ijk_t , rn_Ud          , rn_Ld                  ! lateral eddy coefficient
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                      ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ldf_tra_init : lateral tracer diffusion'
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+      
+      !
+      !  Choice of lateral tracer physics
+      ! =================================
+      !
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, namtra_ldf, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_ldf in reference namelist' )
+
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, namtra_ldf, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_ldf in configuration namelist' )
+      IF(lwm) WRITE( numond, namtra_ldf )
+      !
+      IF(lwp) THEN                      ! control print
+         WRITE(numout,*) '   Namelist : namtra_ldf --- lateral mixing parameters (type, direction, coefficients)'
+         WRITE(numout,*) '      type :'
+         WRITE(numout,*) '         no explicit diffusion                   ln_traldf_OFF   = ', ln_traldf_OFF
+         WRITE(numout,*) '         laplacian operator                      ln_traldf_lap   = ', ln_traldf_lap
+         WRITE(numout,*) '         bilaplacian operator                    ln_traldf_blp   = ', ln_traldf_blp
+         WRITE(numout,*) '      direction of action :'
+         WRITE(numout,*) '         iso-level                               ln_traldf_lev   = ', ln_traldf_lev
+         WRITE(numout,*) '         horizontal (geopotential)               ln_traldf_hor   = ', ln_traldf_hor
+         WRITE(numout,*) '         iso-neutral Madec operator              ln_traldf_iso   = ', ln_traldf_iso
+         WRITE(numout,*) '         iso-neutral triad operator              ln_traldf_triad = ', ln_traldf_triad
+         WRITE(numout,*) '            use the Method of Stab. Correction   ln_traldf_msc   = ', ln_traldf_msc
+         WRITE(numout,*) '            maximum isoppycnal slope             rn_slpmax       = ', rn_slpmax
+         WRITE(numout,*) '            pure lateral mixing in ML            ln_triad_iso    = ', ln_triad_iso
+         WRITE(numout,*) '            switching triad or not               rn_sw_triad     = ', rn_sw_triad
+         WRITE(numout,*) '            lateral mixing on bottom             ln_botmix_triad = ', ln_botmix_triad
+         WRITE(numout,*) '      coefficients :'
+         WRITE(numout,*) '         type of time-space variation            nn_aht_ijk_t    = ', nn_aht_ijk_t
+         WRITE(numout,*) '            lateral diffusive velocity (if cst)  rn_Ud           = ', rn_Ud, ' m/s'
+         WRITE(numout,*) '            lateral diffusive length   (if cst)  rn_Ld           = ', rn_Ld, ' m'
+      ENDIF
+      !
+      !
+      ! Operator and its acting direction   (set nldf_tra)  
+      ! =================================
+      !
+      nldf_tra = np_ERROR
+      ioptio   = 0
+      IF( ln_traldf_OFF ) THEN   ;   nldf_tra = np_no_ldf   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_traldf_lap ) THEN   ;                              ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_traldf_blp ) THEN   ;                              ioptio = ioptio + 1   ;   ENDIF
+      IF( ioptio /=  1  )   CALL ctl_stop( 'tra_ldf_init: use ONE of the 3 operator options (NONE/lap/blp)' )
+      !
+      IF( .NOT.ln_traldf_OFF ) THEN    !==  direction ==>> type of operator  ==!
+         ioptio = 0
+         IF( ln_traldf_lev   )   ioptio = ioptio + 1
+         IF( ln_traldf_hor   )   ioptio = ioptio + 1
+         IF( ln_traldf_iso   )   ioptio = ioptio + 1
+         IF( ln_traldf_triad )   ioptio = ioptio + 1
+         IF( ioptio /=  1  )   CALL ctl_stop( 'tra_ldf_init: use ONE direction (level/hor/iso/triad)' )
+         !
+         !                                ! defined the type of lateral diffusion from ln_traldf_... logicals
+         ierr = 0
+         IF ( ln_traldf_lap ) THEN        ! laplacian operator
+            IF ( ln_zco ) THEN                  ! z-coordinate
+               IF ( ln_traldf_lev   )   nldf_tra = np_lap     ! iso-level = horizontal (no rotation)
+               IF ( ln_traldf_hor   )   nldf_tra = np_lap     ! iso-level = horizontal (no rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_lap_i   ! iso-neutral: standard  (   rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_lap_it  ! iso-neutral: triad     (   rotation)
+            ENDIF
+            IF ( ln_zps ) THEN                  ! z-coordinate with partial step
+               IF ( ln_traldf_lev   )   ierr     = 1          ! iso-level not allowed 
+               IF ( ln_traldf_hor   )   nldf_tra = np_lap     ! horizontal             (no rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_lap_i   ! iso-neutral: standard     (rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_lap_it  ! iso-neutral: triad        (rotation)
+            ENDIF
+            IF ( ln_sco ) THEN                  ! s-coordinate
+               IF ( ln_traldf_lev   )   nldf_tra = np_lap     ! iso-level              (no rotation)
+               IF ( ln_traldf_hor   )   nldf_tra = np_lap_i   ! horizontal             (   rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_lap_i   ! iso-neutral: standard  (   rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_lap_it  ! iso-neutral: triad     (   rotation)
+            ENDIF
+         ENDIF
+         !
+         IF( ln_traldf_blp ) THEN         ! bilaplacian operator
+            IF ( ln_zco ) THEN                  ! z-coordinate
+               IF ( ln_traldf_lev   )   nldf_tra = np_blp     ! iso-level = horizontal (no rotation)
+               IF ( ln_traldf_hor   )   nldf_tra = np_blp     ! iso-level = horizontal (no rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_blp_i   ! iso-neutral: standard  (   rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_blp_it  ! iso-neutral: triad     (   rotation)
+            ENDIF
+            IF ( ln_zps ) THEN                  ! z-coordinate with partial step
+               IF ( ln_traldf_lev   )   ierr     = 1          ! iso-level not allowed 
+               IF ( ln_traldf_hor   )   nldf_tra = np_blp     ! horizontal             (no rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_blp_i   ! iso-neutral: standard  (   rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_blp_it  ! iso-neutral: triad     (   rotation)
+            ENDIF
+            IF ( ln_sco ) THEN                  ! s-coordinate
+               IF ( ln_traldf_lev   )   nldf_tra = np_blp     ! iso-level              (no rotation)
+               IF ( ln_traldf_hor   )   nldf_tra = np_blp_it  ! horizontal             (   rotation)
+               IF ( ln_traldf_iso   )   nldf_tra = np_blp_i   ! iso-neutral: standard  (   rotation)
+               IF ( ln_traldf_triad )   nldf_tra = np_blp_it  ! iso-neutral: triad     (   rotation)
+            ENDIF
+         ENDIF
+         IF ( ierr == 1 )   CALL ctl_stop( 'iso-level in z-partial step, not allowed' )
+      ENDIF
+      !
+      IF( ln_ldfeiv .AND. .NOT.( ln_traldf_iso .OR. ln_traldf_triad ) )                &
+           &            CALL ctl_stop( 'ln_ldfeiv=T requires iso-neutral laplacian diffusion' )
+      IF( ln_isfcav .AND. ln_traldf_triad ) &
+           &            CALL ctl_stop( ' ice shelf cavity and traldf_triad not tested' )
+           !
+      IF(  nldf_tra == np_lap_i .OR. nldf_tra == np_lap_it .OR. &
+         & nldf_tra == np_blp_i .OR. nldf_tra == np_blp_it  )   l_ldfslp = .TRUE.    ! slope of neutral surfaces required 
+      !
+      IF( ln_traldf_blp .AND. ( ln_traldf_iso .OR. ln_traldf_triad) ) THEN     ! iso-neutral bilaplacian need MSC
+         IF( .NOT.ln_traldf_msc )   CALL ctl_stop( 'tra_ldf_init: iso-neutral bilaplacian requires ln_traldf_msc=.true.' )
+      ENDIF
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE( nldf_tra )
+         CASE( np_no_ldf )   ;   WRITE(numout,*) '   ==>>>   NO lateral diffusion'
+         CASE( np_lap    )   ;   WRITE(numout,*) '   ==>>>   laplacian iso-level operator'
+         CASE( np_lap_i  )   ;   WRITE(numout,*) '   ==>>>   Rotated laplacian operator (standard)'
+         CASE( np_lap_it )   ;   WRITE(numout,*) '   ==>>>   Rotated laplacian operator (triad)'
+         CASE( np_blp    )   ;   WRITE(numout,*) '   ==>>>   bilaplacian iso-level operator'
+         CASE( np_blp_i  )   ;   WRITE(numout,*) '   ==>>>   Rotated bilaplacian operator (standard)'
+         CASE( np_blp_it )   ;   WRITE(numout,*) '   ==>>>   Rotated bilaplacian operator (triad)'
+         END SELECT
+         WRITE(numout,*)
+      ENDIF
+
+      !
+      !  Space/time variation of eddy coefficients 
+      ! ===========================================
+      !
+      l_ldftra_time = .FALSE.                ! no time variation except in case defined below
+      !
+      IF( ln_traldf_OFF ) THEN               !== no explicit diffusive operator  ==!
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>>   No diffusive operator selected. ahtu and ahtv are not allocated'
+         RETURN
+         !
+      ELSE                                   !==  a lateral diffusion operator is used  ==!
+         !
+         !                                         ! allocate the aht arrays
+         ALLOCATE( ahtu(jpi,jpj,jpk) , ahtv(jpi,jpj,jpk) , STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'ldf_tra_init: failed to allocate arrays')
+         !
+         ahtu(:,:,jpk) = 0._wp                     ! last level always 0  
+         ahtv(:,:,jpk) = 0._wp
+         !.
+         !                                         ! value of lap/blp eddy mixing coef.
+         IF(     ln_traldf_lap ) THEN   ;   zUfac = r1_2 *rn_Ud   ;   inn = 1   ;   cl_Units = ' m2/s'   !   laplacian
+         ELSEIF( ln_traldf_blp ) THEN   ;   zUfac = r1_12*rn_Ud   ;   inn = 3   ;   cl_Units = ' m4/s'   ! bilaplacian
+         ENDIF
+         aht0    = zUfac *    rn_Ld**inn              ! mixing coefficient
+         zah_max = zUfac * (ra*rad)**inn              ! maximum reachable coefficient (value at the Equator for e1=1 degree)
+         !
+         !
+         SELECT CASE(  nn_aht_ijk_t  )             !* Specification of space-time variations of ahtu, ahtv
+         !
+         CASE(   0  )      !==  constant  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = constant = ', aht0, cl_Units
+            ahtu(:,:,1:jpkm1) = aht0
+            ahtv(:,:,1:jpkm1) = aht0
+            !
+         CASE(  10  )      !==  fixed profile  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F( depth )'
+            IF(lwp) WRITE(numout,*) '           surface eddy diffusivity = constant = ', aht0, cl_Units
+            ahtu(:,:,1) = aht0                        ! constant surface value
+            ahtv(:,:,1) = aht0
+            CALL ldf_c1d( 'TRA', ahtu(:,:,1), ahtv(:,:,1), ahtu, ahtv )
+            !
+         CASE ( -20 )      !== fixed horizontal shape and magnitude read in file  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F(i,j) read in eddy_diffusivity.nc file'
+            CALL iom_open( 'eddy_diffusivity_2D.nc', inum )
+            CALL iom_get ( inum, jpdom_data, 'ahtu_2D', ahtu(:,:,1) )
+            CALL iom_get ( inum, jpdom_data, 'ahtv_2D', ahtv(:,:,1) )
+            CALL iom_close( inum )
+            DO jk = 2, jpkm1
+               ahtu(:,:,jk) = ahtu(:,:,1)
+               ahtv(:,:,jk) = ahtv(:,:,1)
+            END DO
+            !
+         CASE(  20  )      !== fixed horizontal shape  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F( e1, e2 ) or F( e1^3, e2^3 ) (lap or blp case)'
+            IF(lwp) WRITE(numout,*) '           using a fixed diffusive velocity = ', rn_Ud,' m/s   and   Ld = Max(e1,e2)'
+            IF(lwp) WRITE(numout,*) '           maximum reachable coefficient (at the Equator) = ', zah_max, cl_Units, '  for e1=1°)'
+            CALL ldf_c2d( 'TRA', zUfac      , inn        , ahtu, ahtv )    ! value proportional to scale factor^inn
+            !
+         CASE(  21  )      !==  time varying 2D field  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F( latitude, longitude, time )'
+            IF(lwp) WRITE(numout,*) '                            = F( growth rate of baroclinic instability )'
+            IF(lwp) WRITE(numout,*) '            min value = 0.2 * aht0 (with aht0= 1/2 rn_Ud*rn_Ld)'
+            IF(lwp) WRITE(numout,*) '            max value =       aei0 (with aei0=1/2 rn_Ue*Le  increased to aht0 within 20N-20S'
+            !
+            l_ldftra_time = .TRUE.     ! will be calculated by call to ldf_tra routine in step.F90
+            !
+            IF( ln_traldf_blp )   CALL ctl_stop( 'ldf_tra_init: aht=F( growth rate of baroc. insta .)',   &
+               &                                 '              incompatible with bilaplacian operator' )
+            !
+         CASE( -30  )      !== fixed 3D shape read in file  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F(i,j,k) read in eddy_diffusivity.nc file'
+            CALL iom_open( 'eddy_diffusivity_3D.nc', inum )
+            CALL iom_get ( inum, jpdom_data, 'ahtu_3D', ahtu )
+            CALL iom_get ( inum, jpdom_data, 'ahtv_3D', ahtv )
+            CALL iom_close( inum )
+            !
+         CASE(  30  )      !==  fixed 3D shape  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F( latitude, longitude, depth )'
+            IF(lwp) WRITE(numout,*) '           using a fixed diffusive velocity = ', rn_Ud,' m/s   and   Ld = Max(e1,e2)'
+            IF(lwp) WRITE(numout,*) '           maximum reachable coefficient (at the Equator) = ', zah_max, cl_Units, '  for e1=1°)'
+            CALL ldf_c2d( 'TRA', zUfac      , inn        , ahtu, ahtv )    ! surface value proportional to scale factor^inn
+            CALL ldf_c1d( 'TRA', ahtu(:,:,1), ahtv(:,:,1), ahtu, ahtv )    ! reduction with depth
+            !
+         CASE(  31  )      !==  time varying 3D field  ==!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy diffusivity = F( latitude, longitude, depth , time )'
+            IF(lwp) WRITE(numout,*) '           proportional to the velocity : 1/2 |u|e or 1/12 |u|e^3'
+            !
+            l_ldftra_time = .TRUE.     ! will be calculated by call to ldf_tra routine in step.F90
+            !
+         CASE DEFAULT
+            CALL ctl_stop('ldf_tra_init: wrong choice for nn_aht_ijk_t, the type of space-time variation of aht')
+         END SELECT
+         !
+         IF( .NOT.l_ldftra_time ) THEN             !* No time variation 
+            IF(     ln_traldf_lap ) THEN                 !   laplacian operator (mask only)
+               ahtu(:,:,1:jpkm1) =       ahtu(:,:,1:jpkm1)   * umask(:,:,1:jpkm1)
+               ahtv(:,:,1:jpkm1) =       ahtv(:,:,1:jpkm1)   * vmask(:,:,1:jpkm1)
+            ELSEIF( ln_traldf_blp ) THEN                 ! bilaplacian operator (square root + mask)
+               ahtu(:,:,1:jpkm1) = SQRT( ahtu(:,:,1:jpkm1) ) * umask(:,:,1:jpkm1)
+               ahtv(:,:,1:jpkm1) = SQRT( ahtv(:,:,1:jpkm1) ) * vmask(:,:,1:jpkm1)
+            ENDIF
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE ldf_tra_init
+
+
+   SUBROUTINE ldf_tra( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_tra  ***
+      !! 
+      !! ** Purpose :   update at kt the tracer lateral mixing coeff. (aht and aeiv)
+      !!
+      !! ** Method  : * time varying eddy diffusivity coefficients:
+      !!
+      !!    nn_aei_ijk_t = 21    aeiu, aeiv = F(i,j,  t) = F(growth rate of baroclinic instability)
+      !!                                                   with a reduction to 0 in vicinity of the Equator
+      !!    nn_aht_ijk_t = 21    ahtu, ahtv = F(i,j,  t) = F(growth rate of baroclinic instability)
+      !!
+      !!                 = 31    ahtu, ahtv = F(i,j,k,t) = F(local velocity) (  |u|e  /12   laplacian operator
+      !!                                                                     or |u|e^3/12 bilaplacian operator )
+      !!
+      !!              * time varying EIV coefficients: call to ldf_eiv routine
+      !!
+      !! ** action  :   ahtu, ahtv   update at each time step   
+      !!                aeiu, aeiv      -       -     -    -   (if ln_ldfeiv=T) 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zaht, zahf, zaht_min, zDaht, z1_f20   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_ldfeiv .AND. nn_aei_ijk_t == 21 ) THEN       ! eddy induced velocity coefficients
+         !                                ! =F(growth rate of baroclinic instability)
+         !                                ! max value aeiv_0 ; decreased to 0 within 20N-20S
+         CALL ldf_eiv( kt, aei0, aeiu, aeiv )
+      ENDIF
+      !
+      SELECT CASE(  nn_aht_ijk_t  )       ! Eddy diffusivity coefficients
+      !
+      CASE(  21  )       !==  time varying 2D field  ==!   = F( growth rate of baroclinic instability )
+         !                                             !   min value 0.2*aht0
+         !                                             !   max value aht0 (aei0 if nn_aei_ijk_t=21)
+         !                                             !   increase to aht0 within 20N-20S
+         IF( ln_ldfeiv .AND. nn_aei_ijk_t == 21 ) THEN   ! use the already computed aei.
+            ahtu(:,:,1) = aeiu(:,:,1)
+            ahtv(:,:,1) = aeiv(:,:,1)
+         ELSE                                            ! compute aht. 
+            CALL ldf_eiv( kt, aht0, ahtu, ahtv )
+         ENDIF
+         !
+         z1_f20   = 1._wp / (  2._wp * omega * SIN( rad * 20._wp )  )   ! 1 / ff(20 degrees)   
+         zaht_min = 0.2_wp * aht0                                       ! minimum value for aht
+         zDaht    = aht0 - zaht_min                                      
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !!gm CAUTION : here we assume lat/lon grid in 20deg N/S band (like all ORCA cfg)
+               !!     ==>>>   The Coriolis value is identical for t- & u_points, and for v- and f-points
+               zaht = ( 1._wp -  MIN( 1._wp , ABS( ff_t(ji,jj) * z1_f20 ) ) ) * zDaht
+               zahf = ( 1._wp -  MIN( 1._wp , ABS( ff_f(ji,jj) * z1_f20 ) ) ) * zDaht
+               ahtu(ji,jj,1) = (  MAX( zaht_min, ahtu(ji,jj,1) ) + zaht  )     ! min value zaht_min
+               ahtv(ji,jj,1) = (  MAX( zaht_min, ahtv(ji,jj,1) ) + zahf  )     ! increase within 20S-20N
+            END DO
+         END DO
+         DO jk = 1, jpkm1                             ! deeper value = surface value + mask for all levels
+            ahtu(:,:,jk) = ahtu(:,:,1) * umask(:,:,jk)
+            ahtv(:,:,jk) = ahtv(:,:,1) * vmask(:,:,jk)
+         END DO
+         !
+      CASE(  31  )       !==  time varying 3D field  ==!   = F( local velocity )
+         IF( ln_traldf_lap     ) THEN          !   laplacian operator |u| e /12
+            DO jk = 1, jpkm1
+               ahtu(:,:,jk) = ABS( ub(:,:,jk) ) * e1u(:,:) * r1_12   ! n.b. ub,vb are masked
+               ahtv(:,:,jk) = ABS( vb(:,:,jk) ) * e2v(:,:) * r1_12
+            END DO
+         ELSEIF( ln_traldf_blp ) THEN      ! bilaplacian operator      sqrt( |u| e^3 /12 ) = sqrt( |u| e /12 ) * e
+            DO jk = 1, jpkm1
+               ahtu(:,:,jk) = SQRT(  ABS( ub(:,:,jk) ) * e1u(:,:) * r1_12  ) * e1u(:,:)
+               ahtv(:,:,jk) = SQRT(  ABS( vb(:,:,jk) ) * e2v(:,:) * r1_12  ) * e2v(:,:)
+            END DO
+         ENDIF
+         !
+      END SELECT
+      !
+      CALL iom_put( "ahtu_2d", ahtu(:,:,1) )   ! surface u-eddy diffusivity coeff.
+      CALL iom_put( "ahtv_2d", ahtv(:,:,1) )   ! surface v-eddy diffusivity coeff.
+      CALL iom_put( "ahtu_3d", ahtu(:,:,:) )   ! 3D      u-eddy diffusivity coeff.
+      CALL iom_put( "ahtv_3d", ahtv(:,:,:) )   ! 3D      v-eddy diffusivity coeff.
+      !
+      IF( ln_ldfeiv ) THEN
+        CALL iom_put( "aeiu_2d", aeiu(:,:,1) )   ! surface u-EIV coeff.
+        CALL iom_put( "aeiv_2d", aeiv(:,:,1) )   ! surface v-EIV coeff.
+        CALL iom_put( "aeiu_3d", aeiu(:,:,:) )   ! 3D      u-EIV coeff.
+        CALL iom_put( "aeiv_3d", aeiv(:,:,:) )   ! 3D      v-EIV coeff.
+      ENDIF
+      !
+   END SUBROUTINE ldf_tra
+
+
+   SUBROUTINE ldf_eiv_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_eiv_init  ***
+      !!
+      !! ** Purpose :   initialization of the eiv coeff. from namelist choices.
+      !!
+      !! ** Method  :   the eiv diffusivity coef. specification depends on:
+      !!    nn_aei_ijk_t  =  0 => = constant
+      !!                  !
+      !!                  = 10 => = F(z) : constant with a reduction of 1/4 with depth 
+      !!                  !
+      !!                  =-20 => = F(i,j)   = shape read in 'eddy_diffusivity.nc' file
+      !!                  = 20    = F(i,j)   = F(e1,e2) or F(e1^3,e2^3) (lap or bilap case)
+      !!                  = 21    = F(i,j,t) = F(growth rate of baroclinic instability)
+      !!                  !
+      !!                  =-30 => = F(i,j,k)   = shape read in 'eddy_diffusivity.nc' file
+      !!                  = 30    = F(i,j,k)   = 2D (case 20) + decrease with depth (case 10)
+      !!
+      !! ** Action  :   aeiu , aeiv   :  initialized one for all or l_ldftra_time set to true
+      !!                l_ldfeiv_time : =T if EIV coefficients vary with time
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jk                     ! dummy loop indices
+      INTEGER  ::   ierr, inum, ios, inn   ! local integer
+      REAL(wp) ::   zah_max, zUfac         !   -   scalar
+      !!
+      NAMELIST/namtra_eiv/ ln_ldfeiv   , ln_ldfeiv_dia,   &   ! eddy induced velocity (eiv)
+         &                 nn_aei_ijk_t, rn_Ue, rn_Le         ! eiv  coefficient
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                      ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'ldf_eiv_init : eddy induced velocity parametrization'
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+      !
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, namtra_eiv, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_eiv in reference namelist' )
+      !
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, namtra_eiv, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_eiv in configuration namelist' )
+      IF(lwm)  WRITE ( numond, namtra_eiv )
+
+      IF(lwp) THEN                      ! control print
+         WRITE(numout,*) '   Namelist namtra_eiv : '
+         WRITE(numout,*) '      Eddy Induced Velocity (eiv) param.         ln_ldfeiv     = ', ln_ldfeiv
+         WRITE(numout,*) '      eiv streamfunction & velocity diag.        ln_ldfeiv_dia = ', ln_ldfeiv_dia
+         WRITE(numout,*) '      coefficients :'
+         WRITE(numout,*) '         type of time-space variation            nn_aei_ijk_t  = ', nn_aht_ijk_t
+         WRITE(numout,*) '         lateral diffusive velocity (if cst)     rn_Ue         = ', rn_Ue, ' m/s'
+         WRITE(numout,*) '         lateral diffusive length   (if cst)     rn_Le         = ', rn_Le, ' m'
+         WRITE(numout,*)
+      ENDIF
+      !
+      l_ldfeiv_time = .FALSE.       ! no time variation except in case defined below
+      !
+      !
+      IF( .NOT.ln_ldfeiv ) THEN     !== Parametrization not used  ==!
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity param is NOT used'
+         ln_ldfeiv_dia = .FALSE.
+         !
+      ELSE                          !== use the parametrization  ==!
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>>   use eddy induced velocity parametrization'
+         IF(lwp) WRITE(numout,*)
+         !
+         IF( ln_traldf_blp )   CALL ctl_stop( 'ldf_eiv_init: eddy induced velocity ONLY with laplacian diffusivity' )
+         !
+         !                                != allocate the aei arrays
+         ALLOCATE( aeiu(jpi,jpj,jpk), aeiv(jpi,jpj,jpk), STAT=ierr )
+         IF( ierr /= 0 )   CALL ctl_stop('STOP', 'ldf_eiv: failed to allocate arrays')
+         !
+         !                                != Specification of space-time variations of eaiu, aeiv
+         !
+         aeiu(:,:,jpk) = 0._wp               ! last level always 0  
+         aeiv(:,:,jpk) = 0._wp
+         !                                   ! value of EIV coef. (laplacian operator)
+         zUfac = r1_2 *rn_Ue                    ! velocity factor
+         inn = 1                                ! L-exponent
+         aei0    = zUfac *    rn_Le**inn        ! mixing coefficient
+         zah_max = zUfac * (ra*rad)**inn        ! maximum reachable coefficient (value at the Equator)
+
+         SELECT CASE( nn_aei_ijk_t )         !* Specification of space-time variations
+         !
+         CASE(   0  )                        !--  constant  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = constant = ', aei0, ' m2/s'
+            aeiu(:,:,1:jpkm1) = aei0
+            aeiv(:,:,1:jpkm1) = aei0
+            !
+         CASE(  10  )                        !--  fixed profile  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F( depth )'
+            IF(lwp) WRITE(numout,*) '           surface eddy diffusivity = constant = ', aht0, ' m2/s'
+            aeiu(:,:,1) = aei0                  ! constant surface value
+            aeiv(:,:,1) = aei0
+            CALL ldf_c1d( 'TRA', aeiu(:,:,1), aeiv(:,:,1), aeiu, aeiv )
+            !
+         CASE ( -20 )                        !--  fixed horizontal shape read in file  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F(i,j) read in eddy_diffusivity_2D.nc file'
+            CALL iom_open ( 'eddy_induced_velocity_2D.nc', inum )
+            CALL iom_get  ( inum, jpdom_data, 'aeiu', aeiu(:,:,1) )
+            CALL iom_get  ( inum, jpdom_data, 'aeiv', aeiv(:,:,1) )
+            CALL iom_close( inum )
+            DO jk = 2, jpkm1
+               aeiu(:,:,jk) = aeiu(:,:,1)
+               aeiv(:,:,jk) = aeiv(:,:,1)
+            END DO
+            !
+         CASE(  20  )                        !--  fixed horizontal shape  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F( e1, e2 )'
+            IF(lwp) WRITE(numout,*) '           using a fixed diffusive velocity = ', rn_Ue, ' m/s   and   Le = Max(e1,e2)'
+            IF(lwp) WRITE(numout,*) '           maximum reachable coefficient (at the Equator) = ', zah_max, ' m2/s   for e1=1°)'
+            CALL ldf_c2d( 'TRA', zUfac      , inn        , aeiu, aeiv )    ! value proportional to scale factor^inn
+            !
+         CASE(  21  )                        !--  time varying 2D field  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F( latitude, longitude, time )'
+            IF(lwp) WRITE(numout,*) '                                       = F( growth rate of baroclinic instability )'
+            IF(lwp) WRITE(numout,*) '           maximum allowed value: aei0 = ', aei0, ' m2/s'
+            !
+            l_ldfeiv_time = .TRUE.     ! will be calculated by call to ldf_tra routine in step.F90
+            !
+         CASE( -30  )                        !-- fixed 3D shape read in file  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F(i,j,k) read in eddy_diffusivity_3D.nc file'
+            CALL iom_open ( 'eddy_induced_velocity_3D.nc', inum )
+            CALL iom_get  ( inum, jpdom_data, 'aeiu', aeiu )
+            CALL iom_get  ( inum, jpdom_data, 'aeiv', aeiv )
+            CALL iom_close( inum )
+            !
+         CASE(  30  )                        !--  fixed 3D shape  --!
+            IF(lwp) WRITE(numout,*) '   ==>>>   eddy induced velocity coef. = F( latitude, longitude, depth )'
+            CALL ldf_c2d( 'TRA', zUfac      , inn        , aeiu, aeiv )    ! surface value proportional to scale factor^inn
+            CALL ldf_c1d( 'TRA', aeiu(:,:,1), aeiv(:,:,1), aeiu, aeiv )    ! reduction with depth
+            !
+         CASE DEFAULT
+            CALL ctl_stop('ldf_tra_init: wrong choice for nn_aei_ijk_t, the type of space-time variation of aei')
+         END SELECT
+         !
+         IF( .NOT.l_ldfeiv_time ) THEN             !* mask if No time variation 
+            DO jk = 1, jpkm1
+               aeiu(:,:,jk) = aeiu(:,:,jk) * umask(:,:,jk)
+               ahtv(:,:,jk) = ahtv(:,:,jk) * vmask(:,:,jk)
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !                    
+   END SUBROUTINE ldf_eiv_init
+
+
+   SUBROUTINE ldf_eiv( kt, paei0, paeiu, paeiv )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_eiv  ***
+      !!
+      !! ** Purpose :   Compute the eddy induced velocity coefficient from the
+      !!              growth rate of baroclinic instability.
+      !!
+      !! ** Method  :   coefficient function of the growth rate of baroclinic instability
+      !!
+      !! Reference : Treguier et al. JPO 1997   ; Held and Larichev JAS 1996
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt             ! ocean time-step index
+      REAL(wp)                        , INTENT(inout) ::   paei0          ! max value            [m2/s]
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   paeiu, paeiv   ! eiv coefficient      [m2/s]
+      !
+      INTEGER  ::   ji, jj, jk    ! dummy loop indices
+      REAL(wp) ::   zfw, ze3w, zn2, z1_f20, zaht, zaht_min, zzaei    ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zn, zah, zhw, zRo, zaeiw   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      zn (:,:) = 0._wp        ! Local initialization
+      zhw(:,:) = 5._wp
+      zah(:,:) = 0._wp
+      zRo(:,:) = 0._wp
+      !                       ! Compute lateral diffusive coefficient at T-point
+      IF( ln_traldf_triad ) THEN
+         DO jk = 1, jpk
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  ! 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,jj,jk), 0._wp )
+                  zn(ji,jj) = zn(ji,jj) + SQRT( zn2 ) * e3w_n(ji,jj,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 = e3w_n(ji,jj,jk) * wmask(ji,jj,jk)
+                  zah(ji,jj) = zah(ji,jj) + zn2 * wslp2(ji,jj,jk) * ze3w
+                  zhw(ji,jj) = zhw(ji,jj) + ze3w
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, jpk
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  ! 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,jj,jk), 0._wp )
+                  zn(ji,jj) = zn(ji,jj) + SQRT( zn2 ) * e3w_n(ji,jj,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 = e3w_n(ji,jj,jk) * wmask(ji,jj,jk)
+                  zah(ji,jj) = zah(ji,jj) + zn2 * ( wslpi(ji,jj,jk) * wslpi(ji,jj,jk)   &
+                     &                            + wslpj(ji,jj,jk) * wslpj(ji,jj,jk) ) * ze3w
+                  zhw(ji,jj) = zhw(ji,jj) + ze3w
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zfw = MAX( ABS( 2. * omega * SIN( rad * gphit(ji,jj) ) ) , 1.e-10 )
+            ! Rossby radius at w-point taken betwenn 2 km and  40km
+            zRo(ji,jj) = MAX(  2.e3 , MIN( .4 * zn(ji,jj) / zfw, 40.e3 )  )
+            ! Compute aeiw by multiplying Ro^2 and T^-1
+            zaeiw(ji,jj) = zRo(ji,jj) * zRo(ji,jj) * SQRT( zah(ji,jj) / zhw(ji,jj) ) * tmask(ji,jj,1)
+         END DO
+      END DO
+
+      !                                         !==  Bound on eiv coeff.  ==!
+      z1_f20 = 1._wp / (  2._wp * omega * sin( rad * 20._wp )  )
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zzaei = MIN( 1._wp, ABS( ff_t(ji,jj) * z1_f20 ) ) * zaeiw(ji,jj)     ! tropical decrease
+            zaeiw(ji,jj) = MIN( zzaei , paei0 )                                  ! Max value = paei0
+         END DO
+      END DO
+      CALL lbc_lnk( 'ldftra', zaeiw(:,:), 'W', 1. )       ! lateral boundary condition
+      !               
+      DO jj = 2, jpjm1                          !== aei at u- and v-points  ==!
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            paeiu(ji,jj,1) = 0.5_wp * ( zaeiw(ji,jj) + zaeiw(ji+1,jj  ) ) * umask(ji,jj,1)
+            paeiv(ji,jj,1) = 0.5_wp * ( zaeiw(ji,jj) + zaeiw(ji  ,jj+1) ) * vmask(ji,jj,1)
+         END DO 
+      END DO 
+      CALL lbc_lnk_multi( 'ldftra', paeiu(:,:,1), 'U', 1. , paeiv(:,:,1), 'V', 1. )      ! lateral boundary condition
+
+      DO jk = 2, jpkm1                          !==  deeper values equal the surface one  ==!
+         paeiu(:,:,jk) = paeiu(:,:,1) * umask(:,:,jk)
+         paeiv(:,:,jk) = paeiv(:,:,1) * vmask(:,:,jk)
+      END DO
+      !  
+   END SUBROUTINE ldf_eiv
+
+
+   SUBROUTINE ldf_eiv_trp( kt, kit000, pun, pvn, pwn, cdtype )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_eiv_trp  ***
+      !! 
+      !! ** Purpose :   add to the input ocean transport the contribution of 
+      !!              the eddy induced velocity parametrization.
+      !!
+      !! ** Method  :   The eddy induced transport is computed from a flux stream-
+      !!              function which depends on the slope of iso-neutral surfaces
+      !!              (see ldf_slp). For example, in the i-k plan : 
+      !!                   psi_uw = mk(aeiu) e2u mi(wslpi)   [in m3/s]
+      !!                   Utr_eiv = - dk[psi_uw]
+      !!                   Vtr_eiv = + di[psi_uw]
+      !!                ln_ldfeiv_dia = T : output the associated streamfunction,
+      !!                                    velocity and heat transport (call ldf_eiv_dia)
+      !!
+      !! ** Action  : pun, pvn increased by the eiv transport
+      !!----------------------------------------------------------------------
+      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)
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pun      ! in : 3 ocean transport components   [m3/s]
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pvn      ! out: 3 ocean transport components   [m3/s]
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pwn      ! increased by the eiv                [m3/s]
+      !!
+      INTEGER  ::   ji, jj, jk                 ! dummy loop indices
+      REAL(wp) ::   zuwk, zuwk1, zuwi, zuwi1   ! local scalars
+      REAL(wp) ::   zvwk, zvwk1, zvwj, zvwj1   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zpsi_uw, zpsi_vw
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'ldf_eiv_trp : eddy induced advection on ', cdtype,' :'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   add to velocity fields the eiv component'
+      ENDIF
+
+      
+      zpsi_uw(:,:, 1 ) = 0._wp   ;   zpsi_vw(:,:, 1 ) = 0._wp
+      zpsi_uw(:,:,jpk) = 0._wp   ;   zpsi_vw(:,:,jpk) = 0._wp
+      !
+      DO jk = 2, jpkm1
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zpsi_uw(ji,jj,jk) = - r1_4 * e2u(ji,jj) * ( wslpi(ji,jj,jk  ) + wslpi(ji+1,jj,jk) )   &
+                  &                                    * ( aeiu (ji,jj,jk-1) + aeiu (ji  ,jj,jk) ) * wumask(ji,jj,jk)
+               zpsi_vw(ji,jj,jk) = - r1_4 * e1v(ji,jj) * ( wslpj(ji,jj,jk  ) + wslpj(ji,jj+1,jk) )   &
+                  &                                    * ( aeiv (ji,jj,jk-1) + aeiv (ji,jj  ,jk) ) * wvmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.               
+               pun(ji,jj,jk) = pun(ji,jj,jk) - ( zpsi_uw(ji,jj,jk) - zpsi_uw(ji,jj,jk+1) )
+               pvn(ji,jj,jk) = pvn(ji,jj,jk) - ( zpsi_vw(ji,jj,jk) - zpsi_vw(ji,jj,jk+1) )
+            END DO
+         END DO
+      END DO
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               pwn(ji,jj,jk) = pwn(ji,jj,jk) + (  zpsi_uw(ji,jj,jk) - zpsi_uw(ji-1,jj  ,jk)   &
+                  &                             + zpsi_vw(ji,jj,jk) - zpsi_vw(ji  ,jj-1,jk) )
+            END DO
+         END DO
+      END DO
+      !
+      !                              ! diagnose the eddy induced velocity and associated heat transport
+      IF( ln_ldfeiv_dia .AND. cdtype == 'TRA' )   CALL ldf_eiv_dia( zpsi_uw, zpsi_vw )
+      !
+    END SUBROUTINE ldf_eiv_trp
+
+
+   SUBROUTINE ldf_eiv_dia( psi_uw, psi_vw )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_eiv_dia  ***
+      !!
+      !! ** Purpose :   diagnose the eddy induced velocity and its associated
+      !!              vertically integrated heat transport.
+      !!
+      !! ** Method :
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   psi_uw, psi_vw   ! streamfunction   [m3/s]
+      !
+      INTEGER  ::   ji, jj, jk    ! dummy loop indices
+      REAL(wp) ::   zztmp   ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zw2d   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zw3d   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+!!gm I don't like this routine....   Crazy  way of doing things, not optimal at all...
+!!gm     to be redesigned....   
+      !                                                  !==  eiv stream function: output  ==!
+      CALL lbc_lnk_multi( 'ldftra', psi_uw, 'U', -1. , psi_vw, 'V', -1. )
+      !
+!!gm      CALL iom_put( "psi_eiv_uw", psi_uw )                 ! output
+!!gm      CALL iom_put( "psi_eiv_vw", psi_vw )
+      !
+      !                                                  !==  eiv velocities: calculate and output  ==!
+      !
+      zw3d(:,:,jpk) = 0._wp                                    ! bottom value always 0
+      !
+      DO jk = 1, jpkm1                                         ! e2u e3u u_eiv = -dk[psi_uw]
+         zw3d(:,:,jk) = ( psi_uw(:,:,jk+1) - psi_uw(:,:,jk) ) / ( e2u(:,:) * e3u_n(:,:,jk) )
+      END DO
+      CALL iom_put( "uoce_eiv", zw3d )
+      !
+      DO jk = 1, jpkm1                                         ! e1v e3v v_eiv = -dk[psi_vw]
+         zw3d(:,:,jk) = ( psi_vw(:,:,jk+1) - psi_vw(:,:,jk) ) / ( e1v(:,:) * e3v_n(:,:,jk) )
+      END DO
+      CALL iom_put( "voce_eiv", zw3d )
+      !
+      DO jk = 1, jpkm1                                         ! e1 e2 w_eiv = dk[psix] + dk[psix]
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1  ! vector opt.
+               zw3d(ji,jj,jk) = (  psi_vw(ji,jj,jk) - psi_vw(ji  ,jj-1,jk)    &
+                  &              + psi_uw(ji,jj,jk) - psi_uw(ji-1,jj  ,jk)  ) / e1e2t(ji,jj)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'ldftra', zw3d, 'T', 1. )      ! lateral boundary condition
+      CALL iom_put( "woce_eiv", zw3d )
+      !
+      IF( iom_use('weiv_masstr') ) THEN   ! vertical mass transport & its square value
+         zw2d(:,:) = rau0 * e1e2t(:,:)
+         DO jk = 1, jpk
+            zw3d(:,:,jk) = zw3d(:,:,jk) * zw2d(:,:)
+         END DO
+         CALL iom_put( "weiv_masstr" , zw3d )  
+      ENDIF
+      !
+      IF( iom_use('ueiv_masstr') ) THEN
+         zw3d(:,:,:) = 0.e0
+         DO jk = 1, jpkm1
+            zw3d(:,:,jk) = rau0 * ( psi_uw(:,:,jk+1) - psi_uw(:,:,jk) ) 
+         END DO
+         CALL iom_put( "ueiv_masstr", zw3d )                  ! mass transport in i-direction
+      ENDIF
+      !
+      zztmp = 0.5_wp * rau0 * rcp 
+      IF( iom_use('ueiv_heattr') .OR. iom_use('ueiv_heattr3d') ) THEN
+        zw2d(:,:)   = 0._wp 
+        zw3d(:,:,:) = 0._wp 
+        DO jk = 1, jpkm1
+           DO jj = 2, jpjm1
+              DO ji = fs_2, fs_jpim1   ! vector opt.
+                 zw3d(ji,jj,jk) = zw3d(ji,jj,jk) + ( psi_uw(ji,jj,jk+1)      - psi_uw(ji,jj,jk)          )   &
+                    &                            * ( tsn   (ji,jj,jk,jp_tem) + tsn   (ji+1,jj,jk,jp_tem) ) 
+                 zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
+              END DO
+           END DO
+        END DO
+        CALL lbc_lnk( 'ldftra', zw2d, 'U', -1. )
+        CALL lbc_lnk( 'ldftra', zw3d, 'U', -1. )
+        CALL iom_put( "ueiv_heattr"  , zztmp * zw2d )                  ! heat transport in i-direction
+        CALL iom_put( "ueiv_heattr3d", zztmp * zw3d )                  ! heat transport in i-direction
+      ENDIF
+      !
+      IF( iom_use('veiv_masstr') ) THEN
+         zw3d(:,:,:) = 0.e0
+         DO jk = 1, jpkm1
+            zw3d(:,:,jk) = rau0 * ( psi_vw(:,:,jk+1) - psi_vw(:,:,jk) ) 
+         END DO
+         CALL iom_put( "veiv_masstr", zw3d )                  ! mass transport in i-direction
+      ENDIF
+      !
+      zw2d(:,:)   = 0._wp 
+      zw3d(:,:,:) = 0._wp 
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zw3d(ji,jj,jk) = zw3d(ji,jj,jk) + ( psi_vw(ji,jj,jk+1)      - psi_vw(ji,jj,jk)          )   &
+                  &                            * ( tsn   (ji,jj,jk,jp_tem) + tsn   (ji,jj+1,jk,jp_tem) ) 
+               zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'ldftra', zw2d, 'V', -1. )
+      CALL iom_put( "veiv_heattr", zztmp * zw2d )                  !  heat transport in j-direction
+      CALL iom_put( "veiv_heattr", zztmp * zw3d )                  !  heat transport in j-direction
+      !
+      IF( ln_diaptr )   CALL dia_ptr_hst( jp_tem, 'eiv', 0.5 * zw3d )
+      !
+      zztmp = 0.5_wp * 0.5
+      IF( iom_use('ueiv_salttr') .OR. iom_use('ueiv_salttr3d')) THEN
+        zw2d(:,:) = 0._wp 
+        zw3d(:,:,:) = 0._wp 
+        DO jk = 1, jpkm1
+           DO jj = 2, jpjm1
+              DO ji = fs_2, fs_jpim1   ! vector opt.
+                 zw3d(ji,jj,jk) = zw3d(ji,jj,jk) * ( psi_uw(ji,jj,jk+1)      - psi_uw(ji,jj,jk)          )   &
+                    &                            * ( tsn   (ji,jj,jk,jp_sal) + tsn   (ji+1,jj,jk,jp_sal) ) 
+                 zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
+              END DO
+           END DO
+        END DO
+        CALL lbc_lnk( 'ldftra', zw2d, 'U', -1. )
+        CALL lbc_lnk( 'ldftra', zw3d, 'U', -1. )
+        CALL iom_put( "ueiv_salttr", zztmp * zw2d )                  ! salt transport in i-direction
+        CALL iom_put( "ueiv_salttr3d", zztmp * zw3d )                  ! salt transport in i-direction
+      ENDIF
+      zw2d(:,:) = 0._wp 
+      zw3d(:,:,:) = 0._wp 
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zw3d(ji,jj,jk) = zw3d(ji,jj,jk) + ( psi_vw(ji,jj,jk+1)      - psi_vw(ji,jj,jk)          )   &
+                  &                            * ( tsn   (ji,jj,jk,jp_sal) + tsn   (ji,jj+1,jk,jp_sal) ) 
+               zw2d(ji,jj) = zw2d(ji,jj) + zw3d(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'ldftra', zw2d, 'V', -1. )
+      CALL iom_put( "veiv_salttr", zztmp * zw2d )                  !  salt transport in j-direction
+      CALL iom_put( "veiv_salttr", zztmp * zw3d )                  !  salt transport in j-direction
+      !
+      IF( ln_diaptr ) CALL dia_ptr_hst( jp_sal, 'eiv', 0.5 * zw3d )
+      !
+      !
+   END SUBROUTINE ldf_eiv_dia
+
+   !!======================================================================
+END MODULE ldftra
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/README.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../doc/rst/source/data_assimilation.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/ddatetoymdhms.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/ddatetoymdhms.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/ddatetoymdhms.h90	(revision 14097)
@@ -0,0 +1,43 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE ddatetoymdhms( ddate, kyea, kmon, kday, khou, kmin, ksec )
+      !!----------------------------------------------------------------------
+      !!
+      !!                    *** ROUTINE ddatetoymdhms ***
+      !!
+      !! ** Purpose : Convert YYYYMMDD.hhmmss to components
+      !!
+      !! ** Method  :
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!----------------------------------------------------------------------
+      !! * Modules used
+
+      !! * Arguments
+      real(wp), INTENT(IN) :: ddate
+      INTEGER, INTENT(OUT) :: kyea
+      INTEGER, INTENT(OUT) :: kmon
+      INTEGER, INTENT(OUT) :: kday
+      INTEGER, INTENT(OUT) :: khou
+      INTEGER, INTENT(OUT) :: kmin
+      INTEGER, INTENT(OUT) :: ksec
+      !! * Local declarations
+      INTEGER :: iyymmdd
+      INTEGER :: ihhmmss
+      
+      iyymmdd = INT( ddate )
+      ihhmmss = INT( ( ddate - iyymmdd ) * 1000000 )
+      kyea = iyymmdd/10000
+      kmon = iyymmdd / 100 - 100 * kyea
+      kday = MOD( iyymmdd, 100 )
+      khou = ihhmmss/10000
+      kmin = ihhmmss / 100 - 100 * khou
+      ksec = MOD( ihhmmss, 100 )
+      
+   END SUBROUTINE ddatetoymdhms
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/diaobs.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/diaobs.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/diaobs.F90	(revision 14097)
@@ -0,0 +1,1013 @@
+MODULE diaobs
+   !!======================================================================
+   !!                       ***  MODULE diaobs  ***
+   !! Observation diagnostics: Computation of the misfit between data and
+   !!                          their model equivalent 
+   !!======================================================================
+   !! History :  1.0  !  2006-03  (K. Mogensen) Original code
+   !!             -   !  2006-05  (K. Mogensen, A. Weaver) Reformatted
+   !!             -   !  2006-10  (A. Weaver) Cleaning and add controls
+   !!             -   !  2007-03  (K. Mogensen) General handling of profiles
+   !!             -   !  2007-04  (G. Smith) Generalized surface operators
+   !!            2.0  !  2008-10  (M. Valdivieso) obs operator for velocity profiles
+   !!            3.4  !  2014-08  (J. While) observation operator for profiles in all vertical coordinates
+   !!             -   !                      Incorporated SST bias correction  
+   !!            3.6  !  2015-02  (M. Martin) Simplification of namelist and code
+   !!             -   !  2015-08  (M. Martin) Combined surface/profile routines.
+   !!            4.0  !  2017-11  (G. Madec) style only
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_obs_init  : Reading and prepare observations
+   !!   dia_obs       : Compute model equivalent to observations
+   !!   dia_obs_wri   : Write observational diagnostics
+   !!   calc_date     : Compute the date of timestep in YYYYMMDD.HHMMSS format
+   !!   ini_date      : Compute the initial date YYYYMMDD.HHMMSS
+   !!   fin_date      : Compute the final date YYYYMMDD.HHMMSS
+   !!----------------------------------------------------------------------
+   USE par_kind       ! Precision variables
+   USE in_out_manager ! I/O manager
+   USE par_oce        ! ocean parameter
+   USE dom_oce        ! Ocean space and time domain variables
+   USE sbc_oce        ! Sea-ice fraction
+   !
+   USE obs_read_prof  ! Reading and allocation of profile obs
+   USE obs_read_surf  ! Reading and allocation of surface obs
+   USE obs_sstbias    ! Bias correction routine for SST 
+   USE obs_readmdt    ! Reading and allocation of MDT for SLA.
+   USE obs_prep       ! Preparation of obs. (grid search etc).
+   USE obs_oper       ! Observation operators
+   USE obs_write      ! Writing of observation related diagnostics
+   USE obs_grid       ! Grid searching
+   USE obs_read_altbias ! Bias treatment for altimeter
+   USE obs_profiles_def ! Profile data definitions
+   USE obs_surf_def   ! Surface data definitions
+   USE obs_types      ! Definitions for observation types
+   !
+   USE mpp_map        ! MPP mapping
+   USE lib_mpp        ! For ctl_warn/stop
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC dia_obs_init     ! Initialize and read observations
+   PUBLIC dia_obs          ! Compute model equivalent to observations
+   PUBLIC dia_obs_wri      ! Write model equivalent to observations
+   PUBLIC dia_obs_dealloc  ! Deallocate dia_obs data
+   PUBLIC calc_date        ! Compute the date of a timestep
+
+   LOGICAL, PUBLIC :: ln_diaobs          !: Logical switch for the obs operator
+   LOGICAL         :: ln_sstnight        !  Logical switch for night mean SST obs
+   LOGICAL         :: ln_sla_fp_indegs   !  T=> SLA obs footprint size specified in degrees, F=> in metres
+   LOGICAL         :: ln_sst_fp_indegs   !  T=> SST obs footprint size specified in degrees, F=> in metres
+   LOGICAL         :: ln_sss_fp_indegs   !  T=> SSS obs footprint size specified in degrees, F=> in metres
+   LOGICAL         :: ln_sic_fp_indegs   !  T=> sea-ice obs footprint size specified in degrees, F=> in metres
+
+   REAL(wp) ::   rn_sla_avglamscl   ! E/W diameter of SLA observation footprint (metres)
+   REAL(wp) ::   rn_sla_avgphiscl   ! N/S diameter of SLA observation footprint (metres)
+   REAL(wp) ::   rn_sst_avglamscl   ! E/W diameter of SST observation footprint (metres)
+   REAL(wp) ::   rn_sst_avgphiscl   ! N/S diameter of SST observation footprint (metres)
+   REAL(wp) ::   rn_sss_avglamscl   ! E/W diameter of SSS observation footprint (metres)
+   REAL(wp) ::   rn_sss_avgphiscl   ! N/S diameter of SSS observation footprint (metres)
+   REAL(wp) ::   rn_sic_avglamscl   ! E/W diameter of sea-ice observation footprint (metres)
+   REAL(wp) ::   rn_sic_avgphiscl   ! N/S diameter of sea-ice observation footprint (metres)
+
+   INTEGER :: nn_1dint       ! Vertical interpolation method
+   INTEGER :: nn_2dint       ! Default horizontal interpolation method
+   INTEGER :: nn_2dint_sla   ! SLA horizontal interpolation method 
+   INTEGER :: nn_2dint_sst   ! SST horizontal interpolation method 
+   INTEGER :: nn_2dint_sss   ! SSS horizontal interpolation method 
+   INTEGER :: nn_2dint_sic   ! Seaice horizontal interpolation method 
+   INTEGER, DIMENSION(imaxavtypes) ::   nn_profdavtypes   ! Profile data types representing a daily average
+   INTEGER :: nproftypes     ! Number of profile obs types
+   INTEGER :: nsurftypes     ! Number of surface obs types
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nvarsprof, nvarssurf   ! Number of profile & surface variables
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nextrprof, nextrsurf   ! Number of profile & surface extra variables
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   n2dintsurf             ! Interpolation option for surface variables
+   REAL(wp), DIMENSION(:), ALLOCATABLE ::   zavglamscl, zavgphiscl ! E/W & N/S diameter of averaging footprint for surface variables
+   LOGICAL , DIMENSION(:), ALLOCATABLE ::   lfpindegs              ! T=> surface obs footprint size specified in degrees, F=> in metres
+   LOGICAL , DIMENSION(:), ALLOCATABLE ::   llnightav              ! Logical for calculating night-time averages
+
+   TYPE(obs_surf), PUBLIC, POINTER, DIMENSION(:) ::   surfdata     !: Initial surface data
+   TYPE(obs_surf), PUBLIC, POINTER, DIMENSION(:) ::   surfdataqc   !: Surface data after quality control
+   TYPE(obs_prof), PUBLIC, POINTER, DIMENSION(:) ::   profdata     !: Initial profile data
+   TYPE(obs_prof), PUBLIC, POINTER, DIMENSION(:) ::   profdataqc   !: Profile data after quality control
+
+   CHARACTER(len=6), PUBLIC, DIMENSION(:), ALLOCATABLE ::   cobstypesprof, cobstypessurf   !: Profile & surface obs types
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dia_obs_init
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_obs_init  ***
+      !!          
+      !! ** Purpose : Initialize and read observations
+      !!
+      !! ** Method  : Read the namelist and call reading routines
+      !!
+      !! ** Action  : Read the namelist and call reading routines
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, PARAMETER ::   jpmaxnfiles = 1000    ! Maximum number of files for each obs type
+      INTEGER, DIMENSION(:), ALLOCATABLE ::   ifilesprof, ifilessurf   ! Number of profile & surface files
+      INTEGER :: ios             ! Local integer output status for namelist read
+      INTEGER :: jtype           ! Counter for obs types
+      INTEGER :: jvar            ! Counter for variables
+      INTEGER :: jfile           ! Counter for files
+      INTEGER :: jnumsstbias
+      !
+      CHARACTER(len=128), DIMENSION(jpmaxnfiles) :: &
+         & cn_profbfiles, &      ! T/S profile input filenames
+         & cn_sstfbfiles, &      ! Sea surface temperature input filenames
+         & cn_sssfbfiles, &      ! Sea surface salinity input filenames
+         & cn_slafbfiles, &      ! Sea level anomaly input filenames
+         & cn_sicfbfiles, &      ! Seaice concentration input filenames
+         & cn_velfbfiles, &      ! Velocity profile input filenames
+         & cn_sstbiasfiles      ! SST bias input filenames
+      CHARACTER(LEN=128) :: &
+         & cn_altbiasfile        ! Altimeter bias input filename
+      CHARACTER(len=128), DIMENSION(:,:), ALLOCATABLE :: &
+         & clproffiles, &        ! Profile filenames
+         & clsurffiles           ! Surface filenames
+         !
+      LOGICAL :: ln_t3d          ! Logical switch for temperature profiles
+      LOGICAL :: ln_s3d          ! Logical switch for salinity profiles
+      LOGICAL :: ln_sla          ! Logical switch for sea level anomalies 
+      LOGICAL :: ln_sst          ! Logical switch for sea surface temperature
+      LOGICAL :: ln_sss          ! Logical switch for sea surface salinity
+      LOGICAL :: ln_sic          ! Logical switch for sea ice concentration
+      LOGICAL :: ln_vel3d        ! Logical switch for velocity (u,v) obs
+      LOGICAL :: ln_nea          ! Logical switch to remove obs near land
+      LOGICAL :: ln_altbias      ! Logical switch for altimeter bias
+      LOGICAL :: ln_sstbias      ! Logical switch for bias corection of SST 
+      LOGICAL :: ln_ignmis       ! Logical switch for ignoring missing files
+      LOGICAL :: ln_s_at_t       ! Logical switch to compute model S at T obs
+      LOGICAL :: ln_bound_reject ! Logical to remove obs near boundaries in LAMs.
+      LOGICAL :: llvar1          ! Logical for profile variable 1
+      LOGICAL :: llvar2          ! Logical for profile variable 1
+      LOGICAL, DIMENSION(jpmaxnfiles) :: lmask ! Used for finding number of sstbias files
+      !
+      REAL(dp) :: rn_dobsini     ! Obs window start date YYYYMMDD.HHMMSS
+      REAL(dp) :: rn_dobsend     ! Obs window end date   YYYYMMDD.HHMMSS
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zglam1, zglam2   ! Model longitudes for profile variable 1 & 2
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zgphi1, zgphi2   ! Model latitudes  for profile variable 1 & 2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zmask1, zmask2   ! Model land/sea mask associated with variable 1 & 2
+      !!
+      NAMELIST/namobs/ln_diaobs, ln_t3d, ln_s3d, ln_sla,              &
+         &            ln_sst, ln_sic, ln_sss, ln_vel3d,               &
+         &            ln_altbias, ln_sstbias, ln_nea,                 &
+         &            ln_grid_global, ln_grid_search_lookup,          &
+         &            ln_ignmis, ln_s_at_t, ln_bound_reject,          &
+         &            ln_sstnight,                                    &
+         &            ln_sla_fp_indegs, ln_sst_fp_indegs,             &
+         &            ln_sss_fp_indegs, ln_sic_fp_indegs,             &
+         &            cn_profbfiles, cn_slafbfiles,                   &
+         &            cn_sstfbfiles, cn_sicfbfiles,                   &
+         &            cn_velfbfiles, cn_sssfbfiles,                   &
+         &            cn_sstbiasfiles, cn_altbiasfile,                &
+         &            cn_gridsearchfile, rn_gridsearchres,            &
+         &            rn_dobsini, rn_dobsend,                         &
+         &            rn_sla_avglamscl, rn_sla_avgphiscl,             &
+         &            rn_sst_avglamscl, rn_sst_avgphiscl,             &
+         &            rn_sss_avglamscl, rn_sss_avgphiscl,             &
+         &            rn_sic_avglamscl, rn_sic_avgphiscl,             &
+         &            nn_1dint, nn_2dint,                             &
+         &            nn_2dint_sla, nn_2dint_sst,                     &
+         &            nn_2dint_sss, nn_2dint_sic,                     &
+         &            nn_msshc, rn_mdtcorr, rn_mdtcutoff,             &
+         &            nn_profdavtypes
+      !-----------------------------------------------------------------------
+
+      !-----------------------------------------------------------------------
+      ! Read namelist parameters
+      !-----------------------------------------------------------------------
+      ! Some namelist arrays need initialising
+      cn_profbfiles  (:) = ''
+      cn_slafbfiles  (:) = ''
+      cn_sstfbfiles  (:) = ''
+      cn_sicfbfiles  (:) = ''
+      cn_velfbfiles  (:) = ''
+      cn_sssfbfiles  (:) = ''
+      cn_sstbiasfiles(:) = ''
+      nn_profdavtypes(:) = -1
+
+      CALL ini_date( rn_dobsini )
+      CALL fin_date( rn_dobsend )
+
+      ! Read namelist namobs : control observation diagnostics
+      REWIND( numnam_ref )   ! Namelist namobs in reference namelist
+      READ  ( numnam_ref, namobs, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namobs in reference namelist' )
+      REWIND( numnam_cfg )   ! Namelist namobs in configuration namelist
+      READ  ( numnam_cfg, namobs, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namobs in configuration namelist' )
+      IF(lwm) WRITE ( numond, namobs )
+
+      IF( .NOT.ln_diaobs ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dia_obs_init : NO Observation diagnostic used'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+         RETURN
+      ENDIF
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_obs_init : Observation diagnostic initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namobs : set observation diagnostic parameters' 
+         WRITE(numout,*) '      Logical switch for T profile observations                ln_t3d = ', ln_t3d
+         WRITE(numout,*) '      Logical switch for S profile observations                ln_s3d = ', ln_s3d
+         WRITE(numout,*) '      Logical switch for SLA observations                      ln_sla = ', ln_sla
+         WRITE(numout,*) '      Logical switch for SST observations                      ln_sst = ', ln_sst
+         WRITE(numout,*) '      Logical switch for Sea Ice observations                  ln_sic = ', ln_sic
+         WRITE(numout,*) '      Logical switch for velocity observations               ln_vel3d = ', ln_vel3d
+         WRITE(numout,*) '      Logical switch for SSS observations                      ln_sss = ', ln_sss
+         WRITE(numout,*) '      Global distribution of observations              ln_grid_global = ', ln_grid_global
+         WRITE(numout,*) '      Logical switch for obs grid search lookup ln_grid_search_lookup = ', ln_grid_search_lookup
+         IF (ln_grid_search_lookup) &
+            WRITE(numout,*) '      Grid search lookup file header                cn_gridsearchfile = ', cn_gridsearchfile
+         WRITE(numout,*) '      Initial date in window YYYYMMDD.HHMMSS               rn_dobsini = ', rn_dobsini
+         WRITE(numout,*) '      Final date in window YYYYMMDD.HHMMSS                 rn_dobsend = ', rn_dobsend
+         WRITE(numout,*) '      Type of vertical interpolation method                  nn_1dint = ', nn_1dint
+         WRITE(numout,*) '      Type of horizontal interpolation method                nn_2dint = ', nn_2dint
+         WRITE(numout,*) '      Rejection of observations near land switch               ln_nea = ', ln_nea
+         WRITE(numout,*) '      Rejection of obs near open bdys                 ln_bound_reject = ', ln_bound_reject
+         WRITE(numout,*) '      MSSH correction scheme                                 nn_msshc = ', nn_msshc
+         WRITE(numout,*) '      MDT  correction                                      rn_mdtcorr = ', rn_mdtcorr
+         WRITE(numout,*) '      MDT cutoff for computed correction                 rn_mdtcutoff = ', rn_mdtcutoff
+         WRITE(numout,*) '      Logical switch for alt bias                          ln_altbias = ', ln_altbias
+         WRITE(numout,*) '      Logical switch for sst bias                          ln_sstbias = ', ln_sstbias
+         WRITE(numout,*) '      Logical switch for ignoring missing files             ln_ignmis = ', ln_ignmis
+         WRITE(numout,*) '      Daily average types                             nn_profdavtypes = ', nn_profdavtypes
+         WRITE(numout,*) '      Logical switch for night-time SST obs               ln_sstnight = ', ln_sstnight
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Set up list of observation types to be used
+      ! and the files associated with each type
+      !-----------------------------------------------------------------------
+
+      nproftypes = COUNT( (/ln_t3d .OR. ln_s3d, ln_vel3d /) )
+      nsurftypes = COUNT( (/ln_sla, ln_sst, ln_sic, ln_sss /) )
+
+      IF( ln_sstbias ) THEN 
+         lmask(:) = .FALSE. 
+         WHERE( cn_sstbiasfiles(:) /= '' )   lmask(:) = .TRUE. 
+         jnumsstbias = COUNT(lmask) 
+         lmask(:) = .FALSE. 
+      ENDIF      
+
+      IF( nproftypes == 0 .AND. nsurftypes == 0 ) THEN
+         CALL ctl_warn( 'dia_obs_init: ln_diaobs is set to true, but all obs operator logical flags',   &
+            &           ' (ln_t3d, ln_s3d, ln_sla, ln_sst, ln_sic, ln_vel3d)',                          &
+            &           ' are set to .FALSE. so turning off calls to dia_obs'  )
+         ln_diaobs = .FALSE.
+         RETURN
+      ENDIF
+
+      IF( nproftypes > 0 ) THEN
+         !
+         ALLOCATE( cobstypesprof(nproftypes)             )
+         ALLOCATE( ifilesprof   (nproftypes)             )
+         ALLOCATE( clproffiles  (nproftypes,jpmaxnfiles) )
+         !
+         jtype = 0
+         IF( ln_t3d .OR. ln_s3d ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nproftypes, jpmaxnfiles, jtype, 'prof  ', &
+               &                   cn_profbfiles, ifilesprof, cobstypesprof, clproffiles )
+         ENDIF
+         IF( ln_vel3d ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nproftypes, jpmaxnfiles, jtype, 'vel   ', &
+               &                   cn_velfbfiles, ifilesprof, cobstypesprof, clproffiles )
+         ENDIF
+         !
+      ENDIF
+
+      IF( nsurftypes > 0 ) THEN
+         !
+         ALLOCATE( cobstypessurf(nsurftypes)             )
+         ALLOCATE( ifilessurf   (nsurftypes)             )
+         ALLOCATE( clsurffiles  (nsurftypes,jpmaxnfiles) )
+         ALLOCATE( n2dintsurf   (nsurftypes)             )
+         ALLOCATE( zavglamscl   (nsurftypes)             )
+         ALLOCATE( zavgphiscl   (nsurftypes)             )
+         ALLOCATE( lfpindegs    (nsurftypes)             )
+         ALLOCATE( llnightav    (nsurftypes)             )
+         !
+         jtype = 0
+         IF( ln_sla ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nsurftypes, jpmaxnfiles, jtype, 'sla   ', &
+               &                   cn_slafbfiles, ifilessurf, cobstypessurf, clsurffiles )
+            CALL obs_setinterpopts( nsurftypes, jtype, 'sla   ',      &
+               &                  nn_2dint, nn_2dint_sla,             &
+               &                  rn_sla_avglamscl, rn_sla_avgphiscl, &
+               &                  ln_sla_fp_indegs, .FALSE.,          &
+               &                  n2dintsurf, zavglamscl, zavgphiscl, &
+               &                  lfpindegs, llnightav )
+         ENDIF
+         IF( ln_sst ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nsurftypes, jpmaxnfiles, jtype, 'sst   ', &
+               &                   cn_sstfbfiles, ifilessurf, cobstypessurf, clsurffiles )
+            CALL obs_setinterpopts( nsurftypes, jtype, 'sst   ',      &
+               &                  nn_2dint, nn_2dint_sst,             &
+               &                  rn_sst_avglamscl, rn_sst_avgphiscl, &
+               &                  ln_sst_fp_indegs, ln_sstnight,      &
+               &                  n2dintsurf, zavglamscl, zavgphiscl, &
+               &                  lfpindegs, llnightav )
+         ENDIF
+#if defined key_si3 || defined key_cice
+         IF( ln_sic ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nsurftypes, jpmaxnfiles, jtype, 'sic   ', &
+               &                   cn_sicfbfiles, ifilessurf, cobstypessurf, clsurffiles )
+            CALL obs_setinterpopts( nsurftypes, jtype, 'sic   ',      &
+               &                  nn_2dint, nn_2dint_sic,             &
+               &                  rn_sic_avglamscl, rn_sic_avgphiscl, &
+               &                  ln_sic_fp_indegs, .FALSE.,          &
+               &                  n2dintsurf, zavglamscl, zavgphiscl, &
+               &                  lfpindegs, llnightav )
+         ENDIF
+#endif
+         IF( ln_sss ) THEN
+            jtype = jtype + 1
+            CALL obs_settypefiles( nsurftypes, jpmaxnfiles, jtype, 'sss   ', &
+               &                   cn_sssfbfiles, ifilessurf, cobstypessurf, clsurffiles )
+            CALL obs_setinterpopts( nsurftypes, jtype, 'sss   ',      &
+               &                  nn_2dint, nn_2dint_sss,             &
+               &                  rn_sss_avglamscl, rn_sss_avgphiscl, &
+               &                  ln_sss_fp_indegs, .FALSE.,          &
+               &                  n2dintsurf, zavglamscl, zavgphiscl, &
+               &                  lfpindegs, llnightav )
+         ENDIF
+         !
+      ENDIF
+
+
+      !-----------------------------------------------------------------------
+      ! Obs operator parameter checking and initialisations
+      !-----------------------------------------------------------------------
+      !
+      IF( ln_vel3d  .AND.  .NOT.ln_grid_global ) THEN
+         CALL ctl_stop( 'Velocity data only works with ln_grid_global=.true.' )
+         RETURN
+      ENDIF
+      !
+      IF( ln_grid_global ) THEN
+         CALL ctl_warn( 'dia_obs_init: ln_grid_global=T may cause memory issues when used with a large number of processors' )
+      ENDIF
+      !
+      IF( nn_1dint < 0  .OR.  nn_1dint > 1 ) THEN
+         CALL ctl_stop('dia_obs_init: Choice of vertical (1D) interpolation method is not available')
+      ENDIF
+      !
+      IF( nn_2dint < 0  .OR.  nn_2dint > 6  ) THEN
+         CALL ctl_stop('dia_obs_init: Choice of horizontal (2D) interpolation method is not available')
+      ENDIF
+      !
+      CALL obs_typ_init
+      IF( ln_grid_global )   CALL mppmap_init
+      !
+      CALL obs_grid_setup( )
+
+      !-----------------------------------------------------------------------
+      ! Depending on switches read the various observation types
+      !-----------------------------------------------------------------------
+      !
+      IF( nproftypes > 0 ) THEN
+         !
+         ALLOCATE( profdata  (nproftypes) , nvarsprof (nproftypes) )
+         ALLOCATE( profdataqc(nproftypes) , nextrprof (nproftypes) )
+         !
+         DO jtype = 1, nproftypes
+            !
+            nvarsprof(jtype) = 2
+            IF ( TRIM(cobstypesprof(jtype)) == 'prof' ) THEN
+               nextrprof(jtype) = 1
+               llvar1 = ln_t3d
+               llvar2 = ln_s3d
+               zglam1 = glamt
+               zgphi1 = gphit
+               zmask1 = tmask
+               zglam2 = glamt
+               zgphi2 = gphit
+               zmask2 = tmask
+            ENDIF
+            IF ( TRIM(cobstypesprof(jtype)) == 'vel' )  THEN
+               nextrprof(jtype) = 2
+               llvar1 = ln_vel3d
+               llvar2 = ln_vel3d
+               zglam1 = glamu
+               zgphi1 = gphiu
+               zmask1 = umask
+               zglam2 = glamv
+               zgphi2 = gphiv
+               zmask2 = vmask
+            ENDIF
+            !
+            ! Read in profile or profile obs types
+            CALL obs_rea_prof( profdata(jtype), ifilesprof(jtype),       &
+               &               clproffiles(jtype,1:ifilesprof(jtype)), &
+               &               nvarsprof(jtype), nextrprof(jtype), nitend-nit000+2, &
+               &               rn_dobsini, rn_dobsend, llvar1, llvar2, &
+               &               ln_ignmis, ln_s_at_t, .FALSE., &
+               &               kdailyavtypes = nn_profdavtypes )
+               !
+            DO jvar = 1, nvarsprof(jtype)
+               CALL obs_prof_staend( profdata(jtype), jvar )
+            END DO
+            !
+            CALL obs_pre_prof( profdata(jtype), profdataqc(jtype), &
+               &               llvar1, llvar2, &
+               &               jpi, jpj, jpk, &
+               &               zmask1, zglam1, zgphi1, zmask2, zglam2, zgphi2,  &
+               &               ln_nea, ln_bound_reject, &
+               &               kdailyavtypes = nn_profdavtypes )
+         END DO
+         !
+         DEALLOCATE( ifilesprof, clproffiles )
+         !
+      ENDIF
+      !
+      IF( nsurftypes > 0 ) THEN
+         !
+         ALLOCATE( surfdata  (nsurftypes) , nvarssurf(nsurftypes) )
+         ALLOCATE( surfdataqc(nsurftypes) , nextrsurf(nsurftypes) )
+         !
+         DO jtype = 1, nsurftypes
+            !
+            nvarssurf(jtype) = 1
+            nextrsurf(jtype) = 0
+            llnightav(jtype) = .FALSE.
+            IF( TRIM(cobstypessurf(jtype)) == 'sla' )   nextrsurf(jtype) = 2
+            IF( TRIM(cobstypessurf(jtype)) == 'sst' )   llnightav(jtype) = ln_sstnight
+            !
+            ! Read in surface obs types
+            CALL obs_rea_surf( surfdata(jtype), ifilessurf(jtype), &
+               &               clsurffiles(jtype,1:ifilessurf(jtype)), &
+               &               nvarssurf(jtype), nextrsurf(jtype), nitend-nit000+2, &
+               &               rn_dobsini, rn_dobsend, ln_ignmis, .FALSE., llnightav(jtype) )
+               !
+            CALL obs_pre_surf( surfdata(jtype), surfdataqc(jtype), ln_nea, ln_bound_reject )
+            !
+            IF( TRIM(cobstypessurf(jtype)) == 'sla' ) THEN
+               CALL obs_rea_mdt( surfdataqc(jtype), n2dintsurf(jtype) )
+               IF( ln_altbias )   &
+                  & CALL obs_rea_altbias ( surfdataqc(jtype), n2dintsurf(jtype), cn_altbiasfile )
+            ENDIF
+            !
+            IF( TRIM(cobstypessurf(jtype)) == 'sst' .AND. ln_sstbias ) THEN
+               jnumsstbias = 0
+               DO jfile = 1, jpmaxnfiles
+                  IF( TRIM(cn_sstbiasfiles(jfile)) /= '' )   jnumsstbias = jnumsstbias + 1
+               END DO
+               IF( jnumsstbias == 0 )   CALL ctl_stop("ln_sstbias set but no bias files to read in")    
+               !
+               CALL obs_app_sstbias( surfdataqc(jtype), n2dintsurf(jtype)             ,   & 
+                  &                  jnumsstbias      , cn_sstbiasfiles(1:jnumsstbias) ) 
+            ENDIF
+         END DO
+         !
+         DEALLOCATE( ifilessurf, clsurffiles )
+         !
+      ENDIF
+      !
+   END SUBROUTINE dia_obs_init
+
+
+   SUBROUTINE dia_obs( kstp )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_obs  ***
+      !!          
+      !! ** Purpose : Call the observation operators on each time step
+      !!
+      !! ** Method  : Call the observation operators on each time step to
+      !!              compute the model equivalent of the following data:
+      !!               - Profile data, currently T/S or U/V
+      !!               - Surface data, currently SST, SLA or sea-ice concentration.
+      !!
+      !! ** Action  :
+      !!----------------------------------------------------------------------
+      USE dom_oce, ONLY : gdept_n, gdept_1d   ! Ocean space and time domain variables
+      USE phycst , ONLY : rday                ! Physical constants
+      USE oce    , ONLY : tsn, un, vn, sshn   ! Ocean dynamics and tracers variables
+      USE phycst , ONLY : rday                ! Physical constants
+#if defined  key_si3
+      USE ice    , ONLY : at_i                ! SI3 Ice model variables
+#endif
+#if defined key_cice
+      USE sbc_oce, ONLY : fr_i     ! ice fraction
+#endif
+
+      IMPLICIT NONE
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kstp  ! Current timestep
+      !! * Local declarations
+      INTEGER :: idaystp           ! Number of timesteps per day
+      INTEGER :: jtype             ! Data loop variable
+      INTEGER :: jvar              ! Variable number
+      INTEGER :: ji, jj            ! Loop counters
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: &
+         & zprofvar1, &            ! Model values for 1st variable in a prof ob
+         & zprofvar2               ! Model values for 2nd variable in a prof ob
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: &
+         & zprofmask1, &           ! Mask associated with zprofvar1
+         & zprofmask2              ! Mask associated with zprofvar2
+      REAL(wp), DIMENSION(jpi,jpj) :: &
+         & zsurfvar, &             ! Model values equivalent to surface ob.
+         & zsurfmask               ! Mask associated with surface variable
+      REAL(wp), DIMENSION(jpi,jpj) :: &
+         & zglam1,    &            ! Model longitudes for prof variable 1
+         & zglam2,    &            ! Model longitudes for prof variable 2
+         & zgphi1,    &            ! Model latitudes for prof variable 1
+         & zgphi2                  ! Model latitudes for prof variable 2
+
+      !-----------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_obs : Call the observation operators', kstp
+         WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      idaystp = NINT( rday / rdt )
+
+      !-----------------------------------------------------------------------
+      ! Call the profile and surface observation operators
+      !-----------------------------------------------------------------------
+
+      IF ( nproftypes > 0 ) THEN
+
+         DO jtype = 1, nproftypes
+
+            SELECT CASE ( TRIM(cobstypesprof(jtype)) )
+            CASE('prof')
+               zprofvar1(:,:,:) = tsn(:,:,:,jp_tem)
+               zprofvar2(:,:,:) = tsn(:,:,:,jp_sal)
+               zprofmask1(:,:,:) = tmask(:,:,:)
+               zprofmask2(:,:,:) = tmask(:,:,:)
+               zglam1(:,:) = glamt(:,:)
+               zglam2(:,:) = glamt(:,:)
+               zgphi1(:,:) = gphit(:,:)
+               zgphi2(:,:) = gphit(:,:)
+            CASE('vel')
+               zprofvar1(:,:,:) = un(:,:,:)
+               zprofvar2(:,:,:) = vn(:,:,:)
+               zprofmask1(:,:,:) = umask(:,:,:)
+               zprofmask2(:,:,:) = vmask(:,:,:)
+               zglam1(:,:) = glamu(:,:)
+               zglam2(:,:) = glamv(:,:)
+               zgphi1(:,:) = gphiu(:,:)
+               zgphi2(:,:) = gphiv(:,:)
+            CASE DEFAULT
+               CALL ctl_stop( 'Unknown profile observation type '//TRIM(cobstypesprof(jtype))//' in dia_obs' )
+            END SELECT
+
+            CALL obs_prof_opt( profdataqc(jtype), kstp, jpi, jpj, jpk,  &
+               &               nit000, idaystp,                         &
+               &               zprofvar1, zprofvar2,                    &
+               &               gdept_n(:,:,:), gdepw_n(:,:,:),            & 
+               &               zprofmask1, zprofmask2,                  &
+               &               zglam1, zglam2, zgphi1, zgphi2,          &
+               &               nn_1dint, nn_2dint,                      &
+               &               kdailyavtypes = nn_profdavtypes )
+
+         END DO
+
+      ENDIF
+
+      IF ( nsurftypes > 0 ) THEN
+
+         DO jtype = 1, nsurftypes
+
+            !Defaults which might be changed
+            zsurfmask(:,:) = tmask(:,:,1)
+
+            SELECT CASE ( TRIM(cobstypessurf(jtype)) )
+            CASE('sst')
+               zsurfvar(:,:) = tsn(:,:,1,jp_tem)
+            CASE('sla')
+               zsurfvar(:,:) = sshn(:,:)
+            CASE('sss')
+               zsurfvar(:,:) = tsn(:,:,1,jp_sal)
+            CASE('sic')
+               IF ( kstp == 0 ) THEN
+                  IF ( lwp .AND. surfdataqc(jtype)%nsstpmpp(1) > 0 ) THEN
+                     CALL ctl_warn( 'Sea-ice not initialised on zeroth '// &
+                        &           'time-step but some obs are valid then.' )
+                     WRITE(numout,*)surfdataqc(jtype)%nsstpmpp(1), &
+                        &           ' sea-ice obs will be missed'
+                  ENDIF
+                  surfdataqc(jtype)%nsurfup = surfdataqc(jtype)%nsurfup + &
+                     &                        surfdataqc(jtype)%nsstp(1)
+                  CYCLE
+               ELSE
+#if defined key_cice || defined key_si3
+                  zsurfvar(:,:) = fr_i(:,:)
+#else
+                  CALL ctl_stop( ' Trying to run sea-ice observation operator', &
+                     &           ' but no sea-ice model appears to have been defined' )
+#endif
+               ENDIF
+
+            END SELECT
+
+            CALL obs_surf_opt( surfdataqc(jtype), kstp, jpi, jpj,       &
+               &               nit000, idaystp, zsurfvar, zsurfmask,    &
+               &               n2dintsurf(jtype), llnightav(jtype),     &
+               &               zavglamscl(jtype), zavgphiscl(jtype),     &
+               &               lfpindegs(jtype) )
+
+         END DO
+
+      ENDIF
+
+   END SUBROUTINE dia_obs
+
+   SUBROUTINE dia_obs_wri
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dia_obs_wri  ***
+      !!          
+      !! ** Purpose : Call observation diagnostic output routines
+      !!
+      !! ** Method  : Call observation diagnostic output routines
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        !  06-03  (K. Mogensen) Original code
+      !!        !  06-05  (K. Mogensen) Reformatted
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!        !  07-03  (K. Mogensen) General handling of profiles
+      !!        !  08-09  (M. Valdivieso) Velocity component (U,V) profiles
+      !!        !  15-08  (M. Martin) Combined writing for prof and surf types
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE obs_rot_vel          ! Rotation of velocities
+
+      IMPLICIT NONE
+
+      !! * Local declarations
+      INTEGER :: jtype                    ! Data set loop variable
+      INTEGER :: jo, jvar, jk
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zu, &
+         & zv
+
+      !-----------------------------------------------------------------------
+      ! Depending on switches call various observation output routines
+      !-----------------------------------------------------------------------
+
+      IF ( nproftypes > 0 ) THEN
+
+         DO jtype = 1, nproftypes
+
+            IF ( TRIM(cobstypesprof(jtype)) == 'vel' ) THEN
+
+               ! For velocity data, rotate the model velocities to N/S, E/W
+               ! using the compressed data structure.
+               ALLOCATE( &
+                  & zu(profdataqc(jtype)%nvprot(1)), &
+                  & zv(profdataqc(jtype)%nvprot(2))  &
+                  & )
+
+               CALL obs_rotvel( profdataqc(jtype), nn_2dint, zu, zv )
+
+               DO jo = 1, profdataqc(jtype)%nprof
+                  DO jvar = 1, 2
+                     DO jk = profdataqc(jtype)%npvsta(jo,jvar), profdataqc(jtype)%npvend(jo,jvar)
+
+                        IF ( jvar == 1 ) THEN
+                           profdataqc(jtype)%var(jvar)%vmod(jk) = zu(jk)
+                        ELSE
+                           profdataqc(jtype)%var(jvar)%vmod(jk) = zv(jk)
+                        ENDIF
+
+                     END DO
+                  END DO
+               END DO
+
+               DEALLOCATE( zu )
+               DEALLOCATE( zv )
+
+            END IF
+
+            CALL obs_prof_decompress( profdataqc(jtype), &
+               &                      profdata(jtype), .TRUE., numout )
+
+            CALL obs_wri_prof( profdata(jtype) )
+
+         END DO
+
+      ENDIF
+
+      IF ( nsurftypes > 0 ) THEN
+
+         DO jtype = 1, nsurftypes
+
+            CALL obs_surf_decompress( surfdataqc(jtype), &
+               &                      surfdata(jtype), .TRUE., numout )
+
+            CALL obs_wri_surf( surfdata(jtype) )
+
+         END DO
+
+      ENDIF
+
+   END SUBROUTINE dia_obs_wri
+
+   SUBROUTINE dia_obs_dealloc
+      IMPLICIT NONE
+      !!----------------------------------------------------------------------
+      !!                    *** ROUTINE dia_obs_dealloc ***
+      !!
+      !!  ** Purpose : To deallocate data to enable the obs_oper online loop.
+      !!               Specifically: dia_obs_init --> dia_obs --> dia_obs_wri
+      !!
+      !!  ** Method : Clean up various arrays left behind by the obs_oper.
+      !!
+      !!  ** Action :
+      !!
+      !!----------------------------------------------------------------------
+      ! obs_grid deallocation
+      CALL obs_grid_deallocate
+
+      ! diaobs deallocation
+      IF ( nproftypes > 0 ) &
+         &   DEALLOCATE( cobstypesprof, profdata, profdataqc, nvarsprof, nextrprof )
+
+      IF ( nsurftypes > 0 ) &
+         &   DEALLOCATE( cobstypessurf, surfdata, surfdataqc, nvarssurf, nextrsurf, &
+         &               n2dintsurf, zavglamscl, zavgphiscl, lfpindegs, llnightav )
+
+   END SUBROUTINE dia_obs_dealloc
+
+   SUBROUTINE calc_date( kstp, ddobs )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE calc_date  ***
+      !!          
+      !! ** Purpose : Get date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! ** Method  : Get date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! ** Action  : Get date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! ** Action  : Get initial date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! History :
+      !!        !  06-03  (K. Mogensen)  Original code
+      !!        !  06-05  (K. Mogensen)  Reformatted
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!        !  06-10  (G. Smith) Calculates initial date the same as method for final date
+      !!        !  10-05  (D. Lea) Update to month length calculation for NEMO vn3.2
+      !!        !  2014-09  (D. Lea) New generic routine now deals with arbitrary initial time of day
+      !!----------------------------------------------------------------------
+      USE phycst, ONLY : &            ! Physical constants
+         & rday
+      USE dom_oce, ONLY : &           ! Ocean space and time domain variables
+         & rdt
+
+      IMPLICIT NONE
+
+      !! * Arguments
+      REAL(KIND=dp), INTENT(OUT) :: ddobs                        ! Date in YYYYMMDD.HHMMSS
+      INTEGER :: kstp
+
+      !! * Local declarations
+      INTEGER :: iyea        ! date - (year, month, day, hour, minute)
+      INTEGER :: imon
+      INTEGER :: iday
+      INTEGER :: ihou
+      INTEGER :: imin
+      INTEGER :: imday       ! Number of days in month.
+      REAL(wp) :: zdayfrc    ! Fraction of day
+
+      INTEGER, DIMENSION(12) ::   imonth_len    !: length in days of the months of the current year
+
+      !!----------------------------------------------------------------------
+      !! Initial date initialization (year, month, day, hour, minute)
+      !!----------------------------------------------------------------------
+      iyea =   ndate0 / 10000
+      imon = ( ndate0 - iyea * 10000 ) / 100
+      iday =   ndate0 - iyea * 10000 - imon * 100
+      ihou =   nn_time0 / 100
+      imin = ( nn_time0 - ihou * 100 ) 
+
+      !!----------------------------------------------------------------------
+      !! Compute number of days + number of hours + min since initial time
+      !!----------------------------------------------------------------------
+      zdayfrc = kstp * rdt / rday
+      zdayfrc = zdayfrc - aint(zdayfrc)
+      imin = imin + int( zdayfrc * 24 * 60 ) 
+      DO WHILE (imin >= 60) 
+        imin=imin-60
+        ihou=ihou+1
+      END DO
+      DO WHILE (ihou >= 24)
+        ihou=ihou-24
+        iday=iday+1
+      END DO 
+      iday = iday + kstp * rdt / rday 
+
+      !-----------------------------------------------------------------------
+      ! Convert number of days (iday) into a real date
+      !----------------------------------------------------------------------
+
+      CALL calc_month_len( iyea, imonth_len )
+
+      DO WHILE ( iday > imonth_len(imon) )
+         iday = iday - imonth_len(imon)
+         imon = imon + 1 
+         IF ( imon > 12 ) THEN
+            imon = 1
+            iyea = iyea + 1
+            CALL calc_month_len( iyea, imonth_len )  ! update month lengths
+         ENDIF
+      END DO
+
+      !----------------------------------------------------------------------
+      ! Convert it into YYYYMMDD.HHMMSS format.
+      !----------------------------------------------------------------------
+      ddobs = iyea * 10000_dp + imon * 100_dp + &
+         &    iday + ihou * 0.01_dp + imin * 0.0001_dp
+
+   END SUBROUTINE calc_date
+
+   SUBROUTINE ini_date( ddobsini )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE ini_date  ***
+      !!          
+      !! ** Purpose : Get initial date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  06-03  (K. Mogensen)  Original code
+      !!        !  06-05  (K. Mogensen)  Reformatted
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!        !  10-05  (D. Lea) Update to month length calculation for NEMO vn3.2
+      !!        !  2014-09  (D. Lea) Change to call generic routine calc_date
+      !!----------------------------------------------------------------------
+
+      IMPLICIT NONE
+
+      !! * Arguments
+      REAL(KIND=dp), INTENT(OUT) :: ddobsini                   ! Initial date in YYYYMMDD.HHMMSS
+
+      CALL calc_date( nit000 - 1, ddobsini )
+
+   END SUBROUTINE ini_date
+
+   SUBROUTINE fin_date( ddobsfin )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE fin_date  ***
+      !!          
+      !! ** Purpose : Get final date in double precision YYYYMMDD.HHMMSS format
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  06-03  (K. Mogensen)  Original code
+      !!        !  06-05  (K. Mogensen)  Reformatted
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!        !  10-05  (D. Lea) Update to month length calculation for NEMO vn3.2
+      !!        !  2014-09  (D. Lea) Change to call generic routine calc_date
+      !!----------------------------------------------------------------------
+
+      IMPLICIT NONE
+
+      !! * Arguments
+      REAL(dp), INTENT(OUT) :: ddobsfin ! Final date in YYYYMMDD.HHMMSS
+
+      CALL calc_date( nitend, ddobsfin )
+
+   END SUBROUTINE fin_date
+   
+    SUBROUTINE obs_settypefiles( ntypes, jpmaxnfiles, jtype, ctypein, &
+       &                         cfilestype, ifiles, cobstypes, cfiles )
+
+    INTEGER, INTENT(IN) :: ntypes      ! Total number of obs types
+    INTEGER, INTENT(IN) :: jpmaxnfiles ! Maximum number of files allowed for each type
+    INTEGER, INTENT(IN) :: jtype       ! Index of the current type of obs
+    INTEGER, DIMENSION(ntypes), INTENT(INOUT) :: &
+       &                   ifiles      ! Out appended number of files for this type
+
+    CHARACTER(len=6), INTENT(IN) :: ctypein 
+    CHARACTER(len=128), DIMENSION(jpmaxnfiles), INTENT(IN) :: &
+       &                   cfilestype  ! In list of files for this obs type
+    CHARACTER(len=6), DIMENSION(ntypes), INTENT(INOUT) :: &
+       &                   cobstypes   ! Out appended list of obs types
+    CHARACTER(len=128), DIMENSION(ntypes, jpmaxnfiles), INTENT(INOUT) :: &
+       &                   cfiles      ! Out appended list of files for all types
+
+    !Local variables
+    INTEGER :: jfile
+
+    cfiles(jtype,:) = cfilestype(:)
+    cobstypes(jtype) = ctypein
+    ifiles(jtype) = 0
+    DO jfile = 1, jpmaxnfiles
+       IF ( trim(cfiles(jtype,jfile)) /= '' ) &
+                 ifiles(jtype) = ifiles(jtype) + 1
+    END DO
+
+    IF ( ifiles(jtype) == 0 ) THEN
+         CALL ctl_stop( 'Logical for observation type '//TRIM(ctypein)//   &
+            &           ' set to true but no files available to read' )
+    ENDIF
+
+    IF(lwp) THEN    
+       WRITE(numout,*) '             '//cobstypes(jtype)//' input observation file names:'
+       DO jfile = 1, ifiles(jtype)
+          WRITE(numout,*) '                '//TRIM(cfiles(jtype,jfile))
+       END DO
+    ENDIF
+
+    END SUBROUTINE obs_settypefiles
+
+    SUBROUTINE obs_setinterpopts( ntypes, jtype, ctypein,             &
+               &                  n2dint_default, n2dint_type,        &
+               &                  zavglamscl_type, zavgphiscl_type,   &
+               &                  lfp_indegs_type, lavnight_type,     &
+               &                  n2dint, zavglamscl, zavgphiscl,     &
+               &                  lfpindegs, lavnight )
+
+    INTEGER, INTENT(IN)  :: ntypes             ! Total number of obs types
+    INTEGER, INTENT(IN)  :: jtype              ! Index of the current type of obs
+    INTEGER, INTENT(IN)  :: n2dint_default     ! Default option for interpolation type
+    INTEGER, INTENT(IN)  :: n2dint_type        ! Option for interpolation type
+    REAL(wp), INTENT(IN) :: &
+       &                    zavglamscl_type, & !E/W diameter of obs footprint for this type
+       &                    zavgphiscl_type    !N/S diameter of obs footprint for this type
+    LOGICAL, INTENT(IN)  :: lfp_indegs_type    !T=> footprint in degrees, F=> in metres
+    LOGICAL, INTENT(IN)  :: lavnight_type      !T=> obs represent night time average
+    CHARACTER(len=6), INTENT(IN) :: ctypein 
+
+    INTEGER, DIMENSION(ntypes), INTENT(INOUT) :: &
+       &                    n2dint 
+    REAL(wp), DIMENSION(ntypes), INTENT(INOUT) :: &
+       &                    zavglamscl, zavgphiscl
+    LOGICAL, DIMENSION(ntypes), INTENT(INOUT) :: &
+       &                    lfpindegs, lavnight
+
+    lavnight(jtype) = lavnight_type
+
+    IF ( (n2dint_type >= 1) .AND. (n2dint_type <= 6) ) THEN
+       n2dint(jtype) = n2dint_type
+    ELSE
+       n2dint(jtype) = n2dint_default
+    ENDIF
+
+    ! For averaging observation footprints set options for size of footprint 
+    IF ( (n2dint(jtype) > 4) .AND. (n2dint(jtype) <= 6) ) THEN
+       IF ( zavglamscl_type > 0._wp ) THEN
+          zavglamscl(jtype) = zavglamscl_type
+       ELSE
+          CALL ctl_stop( 'Incorrect value set for averaging footprint '// &
+                         'scale (zavglamscl) for observation type '//TRIM(ctypein) )      
+       ENDIF
+
+       IF ( zavgphiscl_type > 0._wp ) THEN
+          zavgphiscl(jtype) = zavgphiscl_type
+       ELSE
+          CALL ctl_stop( 'Incorrect value set for averaging footprint '// &
+                         'scale (zavgphiscl) for observation type '//TRIM(ctypein) )      
+       ENDIF
+
+       lfpindegs(jtype) = lfp_indegs_type 
+
+    ENDIF
+
+    ! Write out info 
+    IF(lwp) THEN
+       IF ( n2dint(jtype) <= 4 ) THEN
+          WRITE(numout,*) '             '//TRIM(ctypein)// &
+             &            ' model counterparts will be interpolated horizontally'
+       ELSE IF ( n2dint(jtype) <= 6 ) THEN
+          WRITE(numout,*) '             '//TRIM(ctypein)// &
+             &            ' model counterparts will be averaged horizontally'
+          WRITE(numout,*) '             '//'    with E/W scale: ',zavglamscl(jtype)
+          WRITE(numout,*) '             '//'    with N/S scale: ',zavgphiscl(jtype)
+          IF ( lfpindegs(jtype) ) THEN
+              WRITE(numout,*) '             '//'    (in degrees)'
+          ELSE
+              WRITE(numout,*) '             '//'    (in metres)'
+          ENDIF
+       ENDIF
+    ENDIF
+
+    END SUBROUTINE obs_setinterpopts
+
+END MODULE diaobs
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/find_obs_proc.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/find_obs_proc.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/find_obs_proc.h90	(revision 14097)
@@ -0,0 +1,60 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE find_obs_proc(kldi,klei,kldj,klej,kmyproc,kobsp,kobsi,kobsj,kno)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE find_obs_proc ***
+      !!          
+      !! ** Purpose : From the array kobsp containing the results of the grid
+      !!              grid search on each processor the processor return a
+      !!              decision of which processors should hold the observation.
+      !!
+      !! ** Method : Use i and j and halo regions to decide which processor to 
+      !!             put ob in. Intended to avoid the mpp calls required by
+      !!             obs_mpp_find_obs_proc
+      !!
+      !! History : 
+      !!! 03-08  (D. Lea)  Original code
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+
+      INTEGER, INTENT(IN) :: kldi               ! Start of inner domain in i
+      INTEGER, INTENT(IN) :: klei               ! End of inner domain in i
+      INTEGER, INTENT(IN) :: kldj               ! Start of inner domain in j
+      INTEGER, INTENT(IN) :: klej               ! End of inner domain in j
+
+      INTEGER, INTENT(IN) :: kmyproc
+      INTEGER, INTENT(IN) :: kno
+
+      INTEGER, DIMENSION(kno), INTENT(IN) :: kobsi
+      INTEGER, DIMENSION(kno), INTENT(IN) :: kobsj
+      INTEGER, DIMENSION(kno), INTENT(INOUT) :: kobsp
+      
+      !! * local variables
+      INTEGER :: &
+         & ji
+          
+      ! first and last indoor i- and j-indexes      kldi, klei,   kldj, klej
+      ! exclude any obs in the bottom-left overlap region
+      ! also any obs outside to whole region (defined by nlci and nlcj)
+      ! I am assuming that kobsp does not need to be the correct processor 
+      ! number
+      
+      DO ji = 1, kno
+         IF (kobsi(ji) < kldi .OR. kobsj(ji) < kldj &
+            .OR. kobsi(ji) > klei  .OR. kobsj(ji) > klej) THEN
+            IF (lwp .AND. kobsp(ji) /= -1) WRITE(numout,*) &
+               & 'kobs: ',kobsi(ji), kobsj(ji), kobsp(ji)
+            kobsp(ji)=1000000
+         ENDIF
+      END DO
+
+      ! Ensure that observations not in processor are masked
+
+      WHERE(kobsp(:) /= kmyproc) kobsp(:)=1000000
+
+   END SUBROUTINE find_obs_proc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/greg2jul.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/greg2jul.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/greg2jul.h90	(revision 14097)
@@ -0,0 +1,89 @@
+   SUBROUTINE greg2jul( ksec, kmin, khour, kday, kmonth, kyear, pjulian, &
+      &                 krefdate )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE greg2jul  ***
+      !!
+      !! ** Purpose : Produce the time relative to the current date and time.
+      !!
+      !! ** Method  : The units are days, so hours and minutes transform to
+      !!              fractions of a day. 
+      !!
+      !!              Reference date : 19500101
+      !! ** Action  :
+      !!
+      !! History :
+      !!      ! 06-04  (A. Vidard) Original
+      !!      ! 06-04  (A. Vidard) Reformatted
+      !!      ! 06-10  (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      ! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & ksec,   &
+         & kmin,   &
+         & khour,  & 
+         & kday,   &
+         & kmonth, & 
+         & kyear
+      REAL(KIND=dp), INTENT(OUT) :: &
+         & pjulian
+      INTEGER, INTENT(IN), OPTIONAL :: &
+         & krefdate
+
+      !! * Local declarations
+      INTEGER, PARAMETER :: &
+         & jpgreg = 15 + 31 * ( 10 + 12 * 1582 ), &     ! Gregorian calendar introduction date
+         & jporef = 2433283,                      &     ! Julian reference date: 19500101
+         & jparef = 2415021,                      &     ! Julian reference date: 19000101
+         & jpgref = 2299161                             ! Julian reference date start of Gregorian calender
+      INTEGER :: &
+         & ija,     &
+         & ijy,     &
+         & ijm,     &
+         & ijultmp, &
+         & ijyear,  &
+         & iref
+      CHARACTER(len=200) :: &
+         & cerr
+
+      IF ( PRESENT( krefdate ) ) THEN
+         SELECT CASE ( krefdate )
+
+         CASE( 0 ) 
+            iref = jpgref
+
+         CASE( 19500101 )
+            iref = jporef
+
+         CASE( 19000101 )
+            iref = jparef
+
+         CASE DEFAULT
+            WRITE(cerr,'(A,I8.8)')'greg2jul: Unknown krefdate:', krefdate
+            CALL ctl_stop( cerr )
+
+         END SELECT
+
+      ELSE
+         iref = jporef 
+      ENDIF
+
+      ! Main computation
+      ijyear = kyear
+      IF ( ijyear < 0 ) ijyear = ijyear + 1
+      IF ( kmonth > 2 ) THEN
+	 ijy = ijyear
+	 ijm = kmonth + 1
+      ELSE
+	 ijy = ijyear  - 1
+	 ijm = kmonth + 13
+      ENDIF
+      ijultmp = INT( 365.25 * ijy ) + INT( 30.6001 * ijm ) + kday + 1720995
+      IF ( kday + 31 * ( kmonth + 12 * ijyear ) >= jpgreg ) THEN
+	 ija = INT( 0.01 * ijy )
+	 ijultmp = ijultmp + 2 - ija + INT( 0.25 * ija )
+      ENDIF
+      pjulian = ( ijultmp - iref ) + ( ( 60 * khour + kmin ) * 60 + ksec ) / 86400.
+
+   END SUBROUTINE greg2jul
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis.h90	(revision 14097)
@@ -0,0 +1,33 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   REAL(KIND=wp) FUNCTION grt_cir_dis( pa1, pa2, pb1, pb2, pc1, pc2 )
+      !!----------------------------------------------------------------------
+      !!                     *** FUNCTION grt_cir_dis ***
+      !!
+      !! ** Purpose : Great circle distance between pts (lat1,lon1) 
+      !!               & (lat2,lon2)
+      !!                   
+      !! ** Method   : Geometry.
+      !!
+      !! History :
+      !!        !  1995-12 (G. Madec, E. Durand, A. Weaver, N. Daget) Original 
+      !!        !  2006-03 (A. Vidard) Migration to NEMOVAR 
+      !!        !  2006-10 (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+      
+      !! * Arguments
+      REAL(KIND=wp) :: pa1   !  sin(lat1)
+      REAL(KIND=wp) :: pa2   !  sin(lat2)
+      REAL(KIND=wp) :: pb1   !  cos(lat1) * cos(lon1)
+      REAL(KIND=wp) :: pb2   !  cos(lat2) * cos(lon2)
+      REAL(KIND=wp) :: pc1   !  cos(lat1) * sin(lon1)
+      REAL(KIND=wp) :: pc2   !  cos(lat2) * sin(lon2)
+
+      grt_cir_dis = &
+         &  ASIN( SQRT( 1.0 - ( pa1 * pa2 + pb1 * pb2 + pc1 * pc2 )**2 ) )
+      
+   END FUNCTION grt_cir_dis
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis_saa.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis_saa.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/grt_cir_dis_saa.h90	(revision 14097)
@@ -0,0 +1,32 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   REAL(KIND=wp) FUNCTION grt_cir_dis_saa( pa, pb, pc )
+      !!----------------------------------------------------------------------
+      !!                     *** FUNCTION grt_cir_dis_saa ***
+      !!
+      !! ** Purpose : Great circle distance between pts (lat1,lon1) 
+      !!               & (lat2,lon2) with a small-angle approximation
+      !!
+      !! ** Method  : Geometry
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!      !  95-12 (G. Madec, E. Durand, A. Weaver, N. Daget) Original 
+      !!      !  06-03 (A. Vidard) Migration to NEMOVAR 
+      !!      !  06-10 (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+      
+      !! * Arguments
+      REAL(KIND=wp) :: pa   !  lon1 - lon2
+      REAL(KIND=wp) :: pb   !  lat1 - lat2
+      REAL(KIND=wp) :: pc   !  cos(lat2)
+
+      grt_cir_dis_saa = SQRT( pa * pa + ( pb * pc )**2 )
+
+   END FUNCTION grt_cir_dis_saa
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/jul2greg.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/jul2greg.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/jul2greg.h90	(revision 14097)
@@ -0,0 +1,115 @@
+   RECURSIVE SUBROUTINE jul2greg( ksec, kminut, khour, kday, kmonth, kyear, &
+      &                           prelday, krefdate )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE jul2greg  ***
+      !!
+      !! ** Purpose : Take the relative time in days and re-express in terms of
+      !!              seconds, minutes, hours, days, month, year.
+      !!
+      !! ** Method  : Reference date : 19500101
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!      ! 06-04  (A. Vidard) Original
+      !!      ! 06-05  (A. Vidard) Reformatted and refdate      
+      !!      ! 06-10  (A. Weaver) Cleanup
+      !!      ! 2014-09 (D. Lea) Change to use FLOOR to deal with negative prelday
+      !!-----------------------------------------------------------------------
+
+      ! * Arguments
+      INTEGER, INTENT(IN), OPTIONAL :: &
+         & krefdate
+      INTEGER, INTENT(OUT) :: &
+         & ksec,   &
+         & kminut, &
+         & khour,  &
+         & kday,   &
+         & kmonth, &
+         & kyear
+      REAL(KIND=dp), INTENT(IN) :: &
+         & prelday
+
+      !! * Local declarations
+      INTEGER, PARAMETER :: &
+         & jpgreg = 2299161, &
+         & jporef = 2433283, &
+         & jparef = 2415021
+      INTEGER :: &
+         & ijulian, &
+         & ij1,     &
+         & ija,     &
+         & ijb,     &
+         & ijc,     &
+         & ijd,     &
+         & ije,     &
+         & isec,    &
+         & imin,    &
+         & ihou,    &
+         & iday,    &
+         & imon,    &
+         & iyea,    &
+         & iref
+      REAL(KIND=wp) :: &
+         & zday, &
+         & zref
+      CHARACTER(len=200) :: &
+         & cerr
+
+      ! Main computation
+      IF ( PRESENT( krefdate ) ) THEN
+
+         SELECT CASE ( krefdate )
+
+         CASE( 0 ) 
+            iref = jpgreg
+
+         CASE( 19500101 )
+            iref = jporef
+
+         CASE( 19000101 )
+            iref = jparef
+
+         CASE DEFAULT
+            WRITE(cerr,'(A,I8.8)')'jul2greg: Unknown krefdate:', krefdate
+            CALL ctl_stop( cerr )
+
+         END SELECT
+
+      ELSE
+         iref = jporef 
+      ENDIF
+
+      zday = prelday
+      ksec = FLOOR( 86400. * MOD( zday, 1. ) )
+
+      IF ( ksec < 0. ) ksec = 86400. + ksec
+
+      khour  = ksec / 3600
+      kminut = ( ksec - 3600 * khour ) / 60
+      ksec   = MOD( ksec , 60 )
+
+      ijulian = iref + INT( zday )
+      IF ( zday < 0. ) ijulian = ijulian - 1
+
+      ! If input date after 10/15/1582 :
+      IF ( ijulian >= jpgreg ) THEN
+	 ij1 = INT( ( DBLE( ijulian - 1867216 ) - 0.25 ) / 36524.25 )
+	 ija = ijulian + 1 + ij1 - INT( ( 0.25 * ij1 ) )
+      ELSE
+	 ija = ijulian
+      ENDIF
+
+      ijb = ija + 1524
+      ijc = INT( 6680. + ( DBLE ( ijb - 2439870 ) - 122.1 ) / 365.25 )
+      ijd = 365 * ijc + INT( 0.25 * ijc )
+      ije = INT( ( ijb - ijd ) / 30.6001 )
+      kday = ijb - ijd - INT( 30.6001 * ije )
+      kmonth = ije - 1
+      IF ( kmonth > 12 ) kmonth = kmonth - 12
+      kyear = ijc - 4715
+      IF ( kmonth > 2 ) kyear = kyear - 1
+      IF ( kyear <= 0 ) kyear = kyear - 1
+
+   END SUBROUTINE jul2greg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/julian.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/julian.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/julian.F90	(revision 14097)
@@ -0,0 +1,33 @@
+MODULE julian
+   !!======================================================================
+   !!                       ***  MODULE julian   ***
+   !! Ocean          : Julian data utilities
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   jul2greg        : Convert relative time to date
+   !!   greg2jul        : Convert date to relative time
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : &       ! Precision variables
+      & wp, &
+      & dp  
+   !USE in_out_manager           ! I/O manager
+   USE lib_mpp,  ONLY : &
+      & ctl_warn, ctl_stop
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+   PUBLIC jul2greg,        &  ! Convert relative time to date
+      &   greg2jul            ! Convert date to relative time 
+  
+   !! $Id$
+CONTAINS
+ 
+#include "jul2greg.h90"
+
+#include "greg2jul.h90"
+   
+END MODULE julian
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/linquad.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/linquad.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/linquad.h90	(revision 14097)
@@ -0,0 +1,59 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   LOGICAL FUNCTION linquad( px, py, pxv, pyv )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION linquad ***
+      !!
+      !! ** Purpose : Determine whether a point P(x,y) lies within or on the
+      !!              boundary of a quadrangle (ABCD) of any shape on a plane.
+      !!
+      !! ** Method  : Check if the vectorial products PA x PC, PB x PA, 
+      !!              PC x PD, and PD x PB are all negative.
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  2001-11  (N. Daget, A. Weaver)
+      !!        !  2006-08  (A. Weaver) NEMOVAR migration
+      !!        !  2006-10  (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: px        ! (lon) of the point P(x,y) 
+      REAL(KIND=wp), INTENT(IN) :: py        ! (lat) of the point P(x,y)               
+      REAL(KIND=wp), DIMENSION(4), INTENT(IN) :: &
+         & pxv,  &                  ! (lon, lat) of the surrounding cell
+         & pyv                     
+  
+      !! * Local declarations
+      REAL(KIND=wp) :: zst1
+      REAL(KIND=wp) :: zst2
+      REAL(KIND=wp) :: zst3
+      REAL(KIND=wp) :: zst4
+
+      !-----------------------------------------------------------------------
+      ! Test to see if the point is within the cell
+      !-----------------------------------------------------------------------
+      linquad = .FALSE.
+      zst1 =   ( px - pxv(1) ) * ( py - pyv(4) ) &
+         &   - ( py - pyv(1) ) * ( px - pxv(4) )
+      IF ( zst1 <= 0.0 ) THEN
+         zst2 =   ( px - pxv(4) ) * ( py - pyv(3) ) &
+         &   - ( py - pyv(4) ) * ( px - pxv(3) )
+         IF ( zst2 <= 0.0 ) THEN
+            zst3 =   ( px - pxv(3) ) * ( py - pyv(2) ) &
+               &   - ( py - pyv(3) ) * ( px - pxv(2) )
+            IF ( zst3 <= 0.0) THEN
+               zst4 =   ( px - pxv(2) ) * ( py - pyv(1) ) &
+                  &   - ( py - pyv(2) ) * ( px - pxv(1) )
+               IF ( zst4 <= 0.0 ) linquad = .TRUE.
+            ENDIF
+         ENDIF
+      ENDIF
+
+   END FUNCTION linquad
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/maxdist.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/maxdist.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/maxdist.h90	(revision 14097)
@@ -0,0 +1,76 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   REAL FUNCTION maxdist( pxv, pyv )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION maxdist ***
+      !!
+      !! ** Purpose : Compute the maximum distance between any points within
+      !!              a cell
+      !!
+      !! ** Method  : Call to grt_cir_dis
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  2006-08  (K. Mogensen)
+      !!        !  2006-10  (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), DIMENSION(4), INTENT(IN) :: &
+          & pxv, &                 ! (lon, lat) of the surrounding cell
+          & pyv    
+
+      !! * Local declarations
+      REAL(KIND=wp), DIMENSION(4) :: &
+          &  zxv, &
+          &  zyv, &
+          &  za,  &
+          &  zb,  &
+          &  zc
+      REAL(KIND=wp) :: zdist
+      
+      INTEGER :: ji
+      INTEGER :: jj
+      
+      !-----------------------------------------------------------------------
+      ! Convert data to radians
+      !-----------------------------------------------------------------------
+      DO ji = 1, 4
+         zxv(ji) = pxv(ji) * rad
+         zyv(ji) = pyv(ji) * rad
+      END DO
+
+      !-----------------------------------------------------------------------
+      ! Prepare input to grt_cir_dis
+      !-----------------------------------------------------------------------
+      DO ji = 1, 4
+         za(ji) = SIN( zyv(ji) )
+         zb(ji) = COS( zyv(ji) ) * COS( zxv(ji) )
+         zc(ji) = COS( zyv(ji) ) * SIN( zxv(ji) )
+      END DO
+      
+      !-----------------------------------------------------------------------
+      ! Get max distance between any points in the area
+      !-----------------------------------------------------------------------
+      maxdist = 0.0
+      DO jj = 1, 4
+         DO ji = jj+1, 4
+            zdist = grt_cir_dis( za(jj), za(ji), zb(jj), &
+               &                 zb(ji), zc(jj), zc(ji))
+            IF ( zdist > maxdist ) THEN
+               maxdist = zdist
+            ENDIF
+         END DO
+      END DO
+      
+      !-----------------------------------------------------------------------
+      ! Convert to degrees.
+      !-----------------------------------------------------------------------
+      maxdist = maxdist / rad
+
+   END FUNCTION maxdist
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/mpp_map.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/mpp_map.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/mpp_map.F90	(revision 14097)
@@ -0,0 +1,85 @@
+MODULE mpp_map
+   !!======================================================================
+   !!                       ***  MODULE mpp_mpa  ***
+   !! NEMOVAR: MPP global grid point mapping to processors
+   !!======================================================================
+   !! History :  2.0  ! 2007-08  (K. Mogensen)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  mppmap_init : Initialize mppmap.
+   !!----------------------------------------------------------------------
+   USE par_kind, ONLY :   wp            ! Precision variables
+   USE par_oce , ONLY :   jpi, jpj      ! Ocean parameters
+   USE dom_oce , ONLY :   mig, mjg, nldi, nlei, nldj, nlej, nlci, nlcj, narea   ! Ocean space and time domain variables
+#if defined key_mpp_mpi
+   USE lib_mpp, ONLY :   mpi_comm_oce   ! MPP library
+#endif
+   USE in_out_manager   ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ::   mppmap_init, mppmap   !: ???
+
+   INTEGER, DIMENSION(:,:), ALLOCATABLE ::   mppmap   ! ???
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE mppmap_init
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE mppmap_init ***
+      !!          
+      !! ** Purpose : Setup a global map of processor rank for all gridpoints
+      !!
+      !! ** Method  : MPI all reduce.
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER, DIMENSION(:,:), ALLOCATABLE ::   imppmap   !
+#if defined key_mpp_mpi
+      INTEGER :: ierr
+
+INCLUDE 'mpif.h'
+#endif
+      !!----------------------------------------------------------------------
+
+      IF (.NOT. ALLOCATED(mppmap)) THEN
+         ALLOCATE( &
+            & mppmap(jpiglo,jpjglo) &
+            & )
+      ENDIF
+      ! Initialize local imppmap
+
+      ALLOCATE( &
+         & imppmap(jpiglo,jpjglo) &
+         & )
+      imppmap(:,:) = 0
+
+!      ! Setup local grid points
+      imppmap(mig(1):mig(nlci),mjg(1):mjg(nlcj)) = narea
+      
+      ! Get global data
+
+#if defined key_mpp_mpi
+
+      ! Call the MPI library to find the max across processors
+      CALL mpi_allreduce( imppmap, mppmap, jpiglo*jpjglo, mpi_integer,   &
+         &                mpi_max, mpi_comm_oce, ierr )
+#else      
+      
+      ! No MPP: Just copy the data
+      mppmap(:,:) = imppmap(:,:)
+#endif
+      !
+   END SUBROUTINE mppmap_init
+
+   !!======================================================================
+END MODULE mpp_map
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_averg_h2d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_averg_h2d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_averg_h2d.F90	(revision 14097)
@@ -0,0 +1,824 @@
+MODULE obs_averg_h2d
+   !!======================================================================
+   !!                       ***  MODULE obs_averg_h2d   ***
+   !! Observation diagnostics: Perform the horizontal averaging
+   !!                          from model grid to observation footprint
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_averg_h2d     : Horizontal averaging to the observation footprint
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : &  ! Precision variables
+      & wp
+   USE par_oce, ONLY : & 
+      & jpi, jpj
+   USE phycst,   ONLY : &  ! Physical constants
+      & rad,  &
+      & ra,   &
+      & rpi
+   USE dom_oce,   ONLY : &
+      & e1t, e2t, &
+      & e1f, e2f, &
+      & glamt, gphit, &
+      & nproc
+   USE in_out_manager
+   USE obs_const, ONLY : &
+      & obfillflt		! Fillvalue
+   USE obs_utils           ! Utility functions
+   USE lib_mpp,   ONLY : &
+      & ctl_warn, ctl_stop, &
+      & mpp_min, lk_mpp
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE obs_avg_h2d_rad, & ! Horizontal averaging using a radial footprint
+      &    obs_avg_h2d_rec, & ! Horizontal averaging using a rectangular footprint
+      &    obs_deg2dist,    & ! Conversion of distance in degrees to distance in metres
+      &    obs_dist2corners   ! Distance from the centre of obs footprint to the corners of a grid box
+   
+   PUBLIC obs_avg_h2d,      & ! Horizontal averaging to the observation footprint
+      &   obs_avg_h2d_init, & ! Set up weights for the averaging
+      &   obs_max_fpsize      ! Works out the maximum number of grid points required for the averaging
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+   SUBROUTINE obs_avg_h2d_init( kpk, kpk2, kmaxifp, kmaxjfp, k2dint, plam,  pphi, &
+      &                         pglam, pgphi, pglamf, pgphif, pmask, plamscl, pphiscl, lindegrees, &
+      &                         pweig, pobsmask, iminpoints )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_avg_h2d_init  ***
+      !!
+      !! ** Purpose : Computes weights for horizontal averaging to the 
+      !!              observation footprint.
+      !!
+      !! ** Method  : Horizontal averaging to the observation footprint using
+      !!              model values at a defined area.
+      !!
+      !!    Averaging schemes :
+      !!
+      !!    Two horizontal averaging schemes are available:
+      !!        - weighted radial footprint        (k2dint = 5)
+      !!        - weighted rectangular footprint   (k2dint = 6)
+      !!
+      !! History :
+      !!        ! 13-10 (M. Martin)
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk,   &             ! Parameter values for automatic arrays
+         & kpk2,  &
+         & kmaxifp,  &          ! Max size of model points in i-direction for obs footprint
+         & kmaxjfp,  &          ! Max size of model points in j-direction for obs footprint
+         & k2dint               ! Averaging scheme options - see header
+      REAL(KIND=wp), INTENT(INOUT) :: &
+         & plam, &              ! Geographical (lat,lon) coordinates of
+         & pphi                 ! observation
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp), INTENT(IN) :: &
+         & pglam, &             ! Model variable lon
+         & pgphi                ! Model variable lat
+      REAL(KIND=wp), DIMENSION(kmaxifp+1,kmaxjfp+1), INTENT(IN) :: &
+         & pglamf, &            ! Model variable lon at corners of grid-boxes
+         & pgphif               ! Model variable lat at corners of grid-boxes
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(IN) :: &
+         & pmask                ! Model variable mask
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl, &           ! Diameter (lat,lon) of obs footprint in metres
+         & pphiscl              ! This is the full width (rather than half-width)
+      LOGICAL, INTENT(IN) :: &
+         & lindegrees           ! T=> obs footprint specified in degrees, F=> in metres
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(OUT) ::  &
+         & pweig                ! Weights for averaging
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) ::  &
+         & pobsmask             ! Vertical mask for observations
+      INTEGER, INTENT(IN), OPTIONAL :: &
+         & iminpoints           ! Reject point which is not surrounded
+                                ! by at least iminpoints sea points
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      INTEGER :: &
+         & ikmax
+
+
+      !------------------------------------------------------------------------
+      !
+      !------------------------------------------------------------------------
+
+      !------------------------------------------------------------------------
+      ! Initialize number of levels
+      !------------------------------------------------------------------------
+      IF ( kpk2 == 1 ) THEN
+         ikmax = 1
+      ELSEIF ( kpk2 == kpk) THEN
+         ikmax = kpk-1
+      ENDIF
+
+
+         SELECT CASE (k2dint)
+         CASE(5)
+            CALL obs_avg_h2d_rad( kpk2, ikmax, kmaxifp, kmaxjfp, plam, pphi, &
+      &                           plamscl, pphiscl, lindegrees, pmask, pglam, pgphi, pglamf, pgphif, pweig )
+         CASE(6)
+            CALL obs_avg_h2d_rec( kpk2, ikmax, kmaxifp, kmaxjfp, plam, pphi, &
+      &                           plamscl, pphiscl, lindegrees, pmask, pglam, pgphi, pglamf, pgphif, pweig )
+         END SELECT
+
+
+      END SUBROUTINE obs_avg_h2d_init
+
+
+      SUBROUTINE obs_avg_h2d_rad( kpk2, kmax, kmaxifp, kmaxjfp, plam, pphi, &
+      &                           plamscl, pphiscl, lindegrees, pmask, pglam, pgphi, pglamf, pgphif, pweig )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_avg_h2d_rad  ***
+      !!
+      !! ** Purpose : Computes weights for horizontal averaging to the 
+      !!              observation using a radial footprint.
+      !!
+      !! ** Method  : Calculate whether each grid box is completely or 
+      !!              partially within the observation footprint.
+      !!              If it is partially in the footprint then calculate
+      !!              the ratio of the area inside the footprint to the total 
+      !!              area of the grid box.
+      !!
+      !! History :
+      !!        ! 14-01 (M. Martin)
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      USE phycst,   ONLY : &  ! Physical constants
+         & ra,  &
+         & rpi
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &             ! Parameter values for automatic arrays
+         & kmax
+
+      INTEGER, INTENT(IN) :: &
+         & kmaxifp,   &         ! Max size of model points in i-direction for obs footprint
+         & kmaxjfp              ! Max size of model points in j-direction for obs footprint
+
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plam, &
+         & pphi                 ! Geographical (lat,lon) coordinates of
+                                ! observation
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl, &           ! Diameter (lat,lon) of obs footprint in metres or degrees (see below)
+         & pphiscl              ! This is the full width (rather than half-width)
+      LOGICAL, INTENT(IN) :: &
+         & lindegrees           ! T=>scales specified in degrees, F=> in metres
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(IN) :: &
+         & pmask                ! Model variable mask
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp), INTENT(IN) :: &
+         & pglam, &             ! Model variable lon
+         & pgphi                ! Model variable lat
+      REAL(KIND=wp), DIMENSION(kmaxifp+1,kmaxjfp+1), INTENT(IN) :: &
+         & pglamf, &             ! Model variable lon at corners of grid boxes
+         & pgphif                ! Model variable lat at corners of grid boxes
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(OUT) ::  &
+         & pweig                ! Weights for interpolation
+
+      !! Local declarations
+      INTEGER :: ji, jj, jk
+      INTEGER :: jvert, jis, jjs
+      INTEGER :: jnumvert, jnumvertbig
+      INTEGER, PARAMETER :: &
+         & jnumsubgrid = 20     ! The number of sub grid-boxes (in x and y directions) used to approximate area of obs fp
+
+      REAL(KIND=wp), DIMENSION(4) :: &
+         & zxvert, zyvert, &    ! The lon/lat of the vertices(corners) of the grid box in m relative to centre of obs fp
+         & zdist                ! Distance of each vertex to the centre of the obs footprint
+      REAL(KIND=wp), DIMENSION(4) :: &
+         & zxgrid, zygrid, &      ! Distance of each vertex of grid box to the centre of the grid box in x/y directions
+         & zdgrid
+      REAL(KIND=wp) :: &
+         & zdx, zdy, &          ! The sub grid-box sizes (in metres)
+         & zarea_subbox, &      ! The area of each sub grid-box (in metres squared)
+         & zxpos, zypos, &      ! The x,y position (relative to centre of obs footprint) of the centre of each sub grid-box
+         & zsubdist, &          ! The distance of the centre of each sub grid-box from the centre of the obs footprint
+         & zarea_fp, &          ! Total area of obs footprint within the grid box
+         & zareabox             ! Total area of the grid box
+      REAL(KIND=wp) :: &
+         & zphiscl_m, &         ! Diameter of obs footprint in metres
+         & zlamscl_m
+      !---------------------------------------------------------------------------------------------------
+      !Initialise weights to zero.
+      pweig(:,:,:) = 0.0_wp
+      
+      !Two footprint sizes can be specified in the namelist but this routine assumes a circular footprint. 
+      !If the two sizes are different then write out a warning.
+      IF ( pphiscl /= plamscl ) THEN
+               CALL ctl_warn( 'obs_avg_h2d_rad:',   &
+                  &           'The two components of the obs footprint size are not equal', &
+                  &           'yet the radial option has been selected - using pphiscl here' )
+      ENDIF
+      
+      DO jk = 1, kmax
+         DO ji = 1, kmaxifp
+            DO jj = 1, kmaxjfp
+            
+               IF ( pmask(ji,jj,jk) == 1.0_wp ) THEN
+
+                  IF ( lindegrees ) THEN
+                     !If the scales are specified in degrees, work out the
+                     !scales (metres) in x/y directions
+                     CALL obs_deg2dist( 1, 1, pglam(ji,jj), pgphi(ji,jj), &
+                        &               plamscl, pphiscl, zlamscl_m, zphiscl_m )
+                  ELSE
+                     zphiscl_m = pphiscl
+                  ENDIF
+
+
+                  ! Work out the area of the grid box using distance of corners relative to centre of grid box
+                  CALL obs_dist2corners(pglamf(ji,jj), pglamf(ji+1,jj), pglamf(ji,jj+1), pglamf(ji+1,jj+1), &
+                     &                  pgphif(ji,jj), pgphif(ji+1,jj), pgphif(ji,jj+1), pgphif(ji+1,jj+1), &
+                     &                  pglam(ji,jj), pgphi(ji,jj), zxgrid, zygrid, zdgrid)
+                  zareabox = ABS( zxgrid(1) - zxgrid(2) ) * ABS( zygrid(1) - zygrid(4) )
+
+                  !1. Determine how many of the vertices of the grid box lie within the circle
+                  
+                  !For each vertex, calculate its location and distance relative 
+                  !to the centre of the observation footprint
+                  
+                  CALL obs_dist2corners(pglamf(ji,jj), pglamf(ji+1,jj), pglamf(ji,jj+1), pglamf(ji+1,jj+1), &
+                     &                  pgphif(ji,jj), pgphif(ji+1,jj), pgphif(ji,jj+1), pgphif(ji+1,jj+1), &
+                     &                  plam, pphi, zxvert, zyvert, zdist)
+
+                  jnumvert = 0
+                  jnumvertbig = 0
+                  DO jvert = 1, 4
+
+                     !If the distance to the center to the observation footprint is less
+                     !than the radius of the footprint (half the diameter) then this
+                     !vertex is within the observation footprint
+                     IF ( zdist(jvert) <= ( zphiscl_m / 2.0_wp ) ) jnumvert = jnumvert + 1
+                     
+                     !For expediency, check if the vertices are "nearly" within the obs
+                     !footprint as if none of them are close to the edge of the footprint
+                     !then the footprint is unlikely to be intersecting the grid box
+                     IF ( zdist(jvert) - ( 0.5_wp * zareabox ) <= ( zphiscl_m / 2.0 ) ) &
+                        & jnumvertbig = jnumvertbig + 1
+                     
+                  END DO
+                  
+                  !2. If none of the vertices are even close to the edge of the obs
+                  !footprint then leave weight as zero and cycle to next grid box.
+                  IF ( jnumvertbig == 0 ) CYCLE
+
+                  !3. If all the vertices of the box are within the observation footprint then the 
+                  !      whole grid box is within the footprint so set the weight to one and 
+                  !      move to the next grid box.
+                  IF ( jnumvert == 4 ) THEN
+                     pweig(ji,jj,jk) = 1.0_wp
+                     CYCLE
+                  ENDIF
+
+
+                  !4. Use a brute force technique for calculating the area within 
+                  !   the grid box covered by the obs footprint.
+                  !  (alternative could be to use formulae on 
+                  !         http://mathworld.wolfram.com/Circle-LineIntersection.html)
+                  !   For now split the grid box into a specified number of smaller 
+                  !   boxes and add up the area of those whose centre is within the obs footprint.
+                  !   Order of vertices is 1=topleft, 2=topright, 3=bottomright, 4=bottomleft
+                  zdx = ABS( zxvert(3) - zxvert(4) ) / REAL(jnumsubgrid, wp)
+                  zdy = ABS( zyvert(1) - zyvert(4) ) / REAL(jnumsubgrid, wp)
+                  zarea_subbox = zdx * zdy
+
+                  zarea_fp = 0.0_wp
+                  DO jis = 1, jnumsubgrid
+                     zxpos = zxvert(4) + ( REAL(jis, wp) * zdx ) - (0.5_wp * zdx )
+                     DO jjs = 1, jnumsubgrid
+                        !Find the distance of the centre of this sub grid box to the
+                        !centre of the obs footprint
+                        zypos = zyvert(4) + ( REAL(jjs, wp) * zdy ) - ( 0.5_wp * zdy )
+                        zsubdist = SQRT( (zxpos * zxpos) + (zypos * zypos) )
+                        IF ( zsubdist < ( zphiscl_m / 2.0_wp ) ) &
+                           &  zarea_fp = zarea_fp + zarea_subbox
+                     END DO
+                  END DO
+
+                  !6. Calculate the ratio of the area of the footprint within the box 
+                  !   to the total area of the grid box and use this fraction to weight 
+                  !   the model value in this grid box.
+                  pweig(ji,jj,jk) = MIN( zarea_fp / zareabox, 1.0_wp )
+
+               END IF  !pmask
+            END DO
+         END DO
+      END DO
+      
+      END SUBROUTINE obs_avg_h2d_rad
+
+
+      SUBROUTINE obs_avg_h2d_rec( kpk2, kmax, kmaxifp, kmaxjfp, plam, pphi, &
+      &                           plamscl, pphiscl, lindegrees, pmask, pglam, pgphi, pglamf, pgphif, pweig )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_avg_h2d_rec  ***
+      !!
+      !! ** Purpose : Computes weights for horizontal averaging to the
+      !!              observation using a rectangular footprint which
+      !!              is aligned with lines of lat/lon.
+      !!
+      !! ** Method  : Horizontal averaging to the observation footprint using
+      !!              model values at a defined area.
+      !!
+      !! History :
+      !!        ! 14-01 (M. Martin)
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      USE phycst,   ONLY : &    ! Physical constants
+         & ra,  &
+         & rpi
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &              ! Parameter values for automatic arrays
+         & kmax
+
+      INTEGER, INTENT(IN) :: &
+         & kmaxifp,   &         ! Max size of model points in i-direction for obs footprint
+         & kmaxjfp              ! Max size of model points in j-direction for obs footprint
+
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plam, &
+         & pphi                 ! Geographical (lat,lon) coordinates of
+                                ! observation
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl, &
+         & pphiscl              ! Width in x/y directions of obs footprint in metres
+                                ! This is the full width (rather than half-width)
+      LOGICAL, INTENT(IN) :: &
+         & lindegrees           !T=> scales specified in degrees, F=> in metres
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(IN) :: &
+         & pmask                ! Model variable mask
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp), INTENT(IN) :: &
+         & pglam, &             ! Model variable lat at centre of grid boxes
+         & pgphi                ! Model variable lon at centre of grid boxes
+      REAL(KIND=wp), DIMENSION(kmaxifp+1,kmaxjfp+1), INTENT(IN) :: &
+         & pglamf, &             ! Model variable lat at corners of grid boxes
+         & pgphif                ! Model variable lon at corners of grid boxes
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(OUT) ::  &
+         & pweig                ! Weights for interpolation
+
+      !! Local declarations
+      INTEGER :: ji, jj, jk
+      INTEGER :: jvert
+      INTEGER, DIMENSION(4) :: &
+         & jnumvert
+      REAL(KIND=wp), DIMENSION(4) :: &
+         & zxvert, zyvert         ! The lon/lat of the vertices(corners) of the grid box in m relative to centre of obs fp
+      REAL(KIND=wp), DIMENSION(4) :: &
+         & zdist                  ! Distance of each vertex to the centre of the obs footprint
+      REAL(KIND=wp), DIMENSION(4) :: &
+         & zxgrid, zygrid, &      ! Distance of each vertex of grid box to the centre of the grid box in x/y directions
+         & zdgrid
+      REAL(KIND=wp) :: &
+         & zareabox, &            ! Total area of grid box
+         & zarea_fp, &            ! Total area of obs footprint
+         & zarea_intersect        ! Area of the intersection between the grid box and the obs footprint
+      REAL(KIND=wp) :: &
+         & zlamscl_m, &
+         & zphiscl_m              ! Total width (lat,lon) of obs footprint in metres
+      REAL(KIND=wp) :: &
+         & z_awidth, z_aheight, & ! Width and height of model grid box
+         & z_cwidth, z_cheight    ! Width and height of union of model grid box and obs footprint
+      REAL(KIND=wp) :: &
+         & zleft, zright, &       ! Distance (metres) of corners area of intersection
+         & ztop, zbottom          ! between grid box and obs footprint
+
+      !-----------------------------------------------------------------------
+
+      !Initialise weights to zero
+      pweig(:,:,:) = 0.0_wp
+      
+      !Loop over the grid boxes which have been identified as potentially being within the
+      !observation footprint
+      DO jk = 1, kmax
+         DO ji = 1, kmaxifp
+            DO jj = 1, kmaxjfp
+
+               IF ( pmask(ji,jj,jk) == 1.0_wp ) THEN
+
+
+                  IF ( lindegrees ) THEN
+                     !If the scales are specified in degrees, work out the
+                     !scales (metres) in x/y directions
+                     CALL obs_deg2dist( 1, 1, pglam(ji,jj), pgphi(ji,jj), &
+                        &               plamscl, pphiscl, zlamscl_m, zphiscl_m )
+                  ELSE
+                     zlamscl_m = plamscl
+                     zphiscl_m = pphiscl
+                  ENDIF
+
+                  ! Work out the area of the grid box using distance of corners relative to centre of grid box
+                  CALL obs_dist2corners(pglamf(ji,jj), pglamf(ji+1,jj), pglamf(ji,jj+1), pglamf(ji+1,jj+1), &
+                     &                  pgphif(ji,jj), pgphif(ji+1,jj), pgphif(ji,jj+1), pgphif(ji+1,jj+1), &
+                     &                  pglam(ji,jj), pgphi(ji,jj), zxgrid, zygrid, zdgrid)
+
+                  !Calculate width and height of model grid box
+                  z_awidth  = ABS( zxgrid(1) - zxgrid(2) )
+                  z_aheight = ABS( zygrid(1) - zygrid(4) )
+                  zareabox = z_awidth * z_aheight
+
+                  ! Work out area of the observation footprint
+                  zarea_fp = zlamscl_m * zphiscl_m
+
+                  ! For each corner of the grid box, calculate its location and distance relative
+                  ! to the centre of the observation footprint
+                  CALL obs_dist2corners(pglamf(ji,jj), pglamf(ji+1,jj), pglamf(ji,jj+1), pglamf(ji+1,jj+1), &
+                     &                  pgphif(ji,jj), pgphif(ji+1,jj), pgphif(ji,jj+1), pgphif(ji+1,jj+1), &
+                     &                  plam, pphi, zxvert, zyvert, zdist)
+
+                  !Work out maximum width and height of rectangle covered by corners of obs fp and grid box
+                  z_cwidth  = MAX( zxvert(1), zxvert(2), -zlamscl_m/2.0_wp, zlamscl_m/2.0_wp ) - &
+                     &       MIN( zxvert(1), zxvert(2), -zlamscl_m/2.0_wp, zlamscl_m/2.0_wp )
+                     
+                  z_cheight = MAX( zyvert(1), zyvert(4), zphiscl_m/2.0_wp, -zphiscl_m/2.0_wp ) - &
+                     &       MIN( zyvert(1), zyvert(4), zphiscl_m/2.0_wp, -zphiscl_m/2.0_wp )
+                  
+                  IF ( ( z_cwidth  >= z_awidth  + zlamscl_m  ) .OR. &
+                     & ( z_cheight >= z_aheight + zphiscl_m ) ) THEN
+                     !The obs footprint and the model grid box don't overlap so set weight to zero
+                     pweig(ji,jj,jk) = 0.0_wp
+                  ELSE IF ( ( z_cwidth  == zlamscl_m ) .AND. &
+                     &      ( z_cheight == zphiscl_m ) ) THEN
+                     !The grid box is totally contained within the obs footprint so set weight to one
+                     pweig(ji,jj,jk) = 1.0_wp
+                  ELSE IF ( ( z_cwidth  == z_awidth  ) .AND. &
+                     &      ( z_cheight == z_aheight ) ) THEN
+                     !The obs footprint is totally contained within the grid box so set weight as ratio of the two
+                     pweig(ji,jj,jk) = zarea_fp / zareabox
+                  ELSE 
+                     !The obs footprint and the grid box overlap so calculate the area of the intersection of the two
+                     zleft   = max(zxvert(1), -zlamscl_m/2.0_wp)
+                     zright  = min(zxvert(2),  zlamscl_m/2.0_wp)
+                     zbottom = max(zyvert(4), -zphiscl_m/2.0_wp)
+                     ztop    = min(zyvert(1),  zphiscl_m/2.0_wp)
+                     
+                     IF (  ( zleft < zright ) .AND. ( zbottom < ztop ) ) THEN
+                        zarea_intersect = ( zright - zleft ) * ( ztop - zbottom )
+                        pweig(ji,jj,jk) = zarea_intersect / zareabox
+                     ENDIF
+                  ENDIF
+
+               END IF !pmask
+            END DO
+         END DO
+      END DO
+
+   END SUBROUTINE obs_avg_h2d_rec
+
+   SUBROUTINE obs_avg_h2d( kpk, kpk2, kmaxifp, kmaxjfp, pweig, pmod, pobsk )
+
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d  ***
+      !!
+      !! ** Purpose : Horizontal averaging to the observation footprint.
+      !!
+      !! ** Method  : Average the model points based on the weights already calculated.
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : 
+      !!
+      !! History :
+      !!        ! 13/10. M. Martin.
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk,   &             ! Parameter values for automatic arrays
+         & kpk2
+      INTEGER, INTENT(IN) :: &
+         & kmaxifp,   &         ! Max size of model points in i-direction for obs footprint
+         & kmaxjfp              ! Max size of model points in j-direction for obs footprint
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(IN) :: &
+         & pweig                ! Interpolation weights
+      REAL(KIND=wp), DIMENSION(kmaxifp,kmaxjfp,kpk2), INTENT(IN) :: &
+         & pmod                 ! Model variable to interpolate
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) ::  &
+         & pobsk                ! Model profile interpolated to obs (i,j) pt
+
+      INTEGER :: &
+         & jk
+      INTEGER :: &
+         & ikmax
+      REAL(KIND=wp) :: &
+         & zsum
+
+      !------------------------------------------------------------------------
+      ! Initialize number of levels
+      !------------------------------------------------------------------------
+      IF ( kpk2 == 1 ) THEN
+         ikmax = 1
+      ELSEIF ( kpk2 == kpk) THEN
+         ikmax = kpk-1
+      ENDIF
+
+      !------------------------------------------------------------------------
+      ! Average model values to the observation footprint
+      !------------------------------------------------------------------------
+      pobsk = obfillflt
+
+      DO jk = 1, ikmax
+
+         zsum = SUM( pweig(:,:,jk) )
+
+         IF ( zsum /= 0.0_wp ) THEN
+            pobsk(jk) = SUM ( pweig(:,:,jk) * pmod(:,:,jk), Mask=pweig(:,:,jk) > 0.0_wp )
+            pobsk(jk) = pobsk(jk) / zsum
+         END IF
+
+      END DO
+
+   END SUBROUTINE obs_avg_h2d
+
+   SUBROUTINE obs_max_fpsize( k2dint, plamscl, pphiscl, lindegrees, pmask, kmaxifp, kmaxjfp )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_max_fpsize  ***
+      !!
+      !! ** Purpose : Calculate maximum number of grid points which may
+      !!              need to be used in the averaging in the global domain.
+      !!
+      !!
+      !! ** Method  : Work out the minimum grid size and work out
+      !!              how many of the smallest grid points would be needed
+      !!              to cover the scale of the observation footprint.
+      !!              This needs to be done using the max/min of the global domain
+      !!              as the obs can be distributed from other parts of the grid.
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : 
+      !!
+      !! History :
+      !!        ! 14/01. M. Martin. 
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER , INTENT(IN) :: &
+         & k2dint                   !Type of interpolation/averaging used
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl,   &             !Total width/radius in metres of the observation footprint
+         & pphiscl                  !
+      LOGICAL, INTENT(IN) :: &
+         & lindegrees               !T=> plamscl and pphiscl are specified in degrees
+      REAL(KIND=wp), DIMENSION(jpi,jpj), INTENT(IN) :: &
+         & pmask                    !Land/sea mask
+                                    !F=> plamscl and pphiscl are specified in metres
+      INTEGER, INTENT(OUT)  :: &
+         & kmaxifp,   &             !Max number of grid points in i,j directions to use in averaging
+         & kmaxjfp                  !these have to be even so that the footprint is centred
+
+      !! * Local variables
+      REAL(KIND=wp) :: &
+         & ze1min,     &            !Minimum global grid-size in i,j directions
+         & ze2min
+      REAL(KIND=wp) :: &
+         & zphiscl_m, &
+         & zlamscl_m
+      !------------------------------------------------------------------------
+
+      IF ( k2dint <= 4 ) THEN
+         !If interpolation is being used then only need to use a 2x2 footprint
+         kmaxifp = 2
+         kmaxjfp = 2
+
+      ELSE
+
+         IF ( lindegrees ) THEN
+            !If the scales are specified in degrees, work out the max 
+            !distance (metres) in x/y directions
+            CALL obs_deg2dist( jpi, jpj, glamt, gphit, &
+               &               plamscl, pphiscl, zlamscl_m, zphiscl_m )
+         ELSE
+            zlamscl_m = plamscl
+            zphiscl_m = pphiscl
+         ENDIF
+
+         ze1min = MINVAL( e1t(:,:), mask = pmask(:,:) == 1._wp )
+         ze2min = MINVAL( e2t(:,:), mask = pmask(:,:) == 1._wp )
+         
+         IF(lk_mpp) THEN
+            CALL mpp_min( 'obs_averg_h2d', ze1min )
+            CALL mpp_min( 'obs_averg_h2d', ze2min )
+         ENDIF
+
+         kmaxifp = ceiling(zlamscl_m/ze1min) + 1
+         kmaxjfp = ceiling(zphiscl_m/ze2min) + 1
+         
+         !Ensure that these numbers are even
+         kmaxifp = kmaxifp + MOD(kmaxifp,2)
+         kmaxjfp = kmaxjfp + MOD(kmaxjfp,2)
+         
+
+      ENDIF
+
+   END SUBROUTINE obs_max_fpsize
+
+   SUBROUTINE obs_deg2dist( ki, kj, pglam, pgphi, plamscl_deg, pphiscl_deg, &
+      &                     plamscl_max, pphiscl_max )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_deg2dist  ***
+      !!
+      !! ** Purpose : Calculate the maximum distance in m of the length scale
+      !!              in degrees.
+      !!
+      !! ** Method  : At each lon/lat point, work out the distances in the 
+      !!              zonal and meridional directions.
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : 
+      !!
+      !! History :
+      !!        ! 14/01. M. Martin. 
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER , INTENT(IN) :: &
+         & ki, kj                   !x/y dimensions of input lat/lon variables
+      REAL(KIND=wp), INTENT(IN), DIMENSION(ki,kj) :: &
+         & pglam, pgphi             !Longitude and latitudes of grid points
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl_deg,   &         !Size in degrees of the observation footprint
+         & pphiscl_deg              !
+      REAL(KIND=wp), INTENT(OUT) :: &
+         & plamscl_max, &           !Maximum size of obs footprint in metres
+         & pphiscl_max
+      
+      !! * Local declarations
+      INTEGER :: &
+         & ji, jj                   !Counters
+      REAL(KIND=wp) :: &
+         & zlon1, zlon2, &          !Lon values surrounding centre of grid point
+         & zlat1, zlat2, &          !Lat values surrounding centre of grid point
+         & zdlat, zdlon             !Distance in radians in lat/lon directions
+      REAL(KIND=wp) :: &
+         & za1, za2, za, zc, zd
+      
+      plamscl_max = -1.0_wp
+      pphiscl_max = -1.0_wp
+
+      DO ji = 1, ki
+         DO jj = 1, kj
+
+            !Calculate distance in metres in zonal(x) direction
+
+            zlon1 = rad * ( pglam(ji,jj) + ( 0.5_wp * plamscl_deg ) )
+            zlon2 = rad * ( pglam(ji,jj) - ( 0.5_wp * plamscl_deg ) )
+            zlat1 = rad * pgphi(ji,jj)
+            zlat2 = rad * pgphi(ji,jj)
+            zdlon = zlon2 - zlon1
+            zdlat = zlat2 - zlat1
+
+            za1 = sin( zdlat/2.0_wp )
+            za2 = sin( zdlon/2.0_wp )
+            za = ( za1 * za1 ) + ( COS( zlat1 ) * COS( zlat2 ) * ( za2 * za2 ) )
+            zc = 2.0_wp * atan2( SQRT( za ), SQRT( 1.0_wp-za ) )
+            zd = ra * zc
+
+            IF ( zd > plamscl_max ) plamscl_max = zd
+
+            !Calculate distance in metres in meridional(y) direction
+
+            zlon1 = rad * pglam(ji,jj)
+            zlon2 = rad * pglam(ji,jj)
+            zlat1 = rad * ( pgphi(ji,jj) + ( 0.5_wp * pphiscl_deg ) )
+            zlat2 = rad * ( pgphi(ji,jj) - ( 0.5_wp * pphiscl_deg ) )
+            zdlon = zlon2 - zlon1
+            zdlat = zlat2 - zlat1
+
+            za1 = sin( zdlat/2.0_wp )
+            za2 = sin( zdlon/2.0_wp )
+            za = ( za1 * za1 ) + ( COS( zlat1 ) * COS( zlat2 ) * ( za2 * za2 ) )
+            zc = 2.0_wp * atan2( SQRT( za ), SQRT( 1.0_wp-za ) )
+            zd = ra * zc
+
+            IF ( zd > pphiscl_max ) pphiscl_max = zd
+
+         END DO
+      END DO
+         
+   END SUBROUTINE obs_deg2dist
+
+   SUBROUTINE obs_dist2corners(pglam_bl, pglam_br, pglam_tl, pglam_tr, &
+      &                        pgphi_bl, pgphi_br, pgphi_tl, pgphi_tr, &
+      &                        plam, pphi, pxvert, pyvert, pdist)
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_dist2corners  ***
+      !!
+      !! ** Purpose : Calculate distance from centre of obs footprint to the corners of a grid box
+      !!
+      !! ** Method  : Use great circle distance formulae.
+      !!              Order of corners is 1=topleft, 2=topright, 3=bottomright, 4=bottomleft
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : 
+      !!
+      !! History :
+      !!        ! 14/01. M. Martin.
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+         REAL(KIND=wp), INTENT(IN) :: &
+            &  pglam_bl, pglam_br, &       !lon at corners of grid box
+            &  pglam_tl, pglam_tr
+         REAL(KIND=wp), INTENT(IN) :: &
+            &  pgphi_bl, pgphi_br, &       !lat at corners of grid box
+            &  pgphi_tl, pgphi_tr
+         REAL(KIND=wp), INTENT(IN) :: &
+            &  pphi, plam                  !lat/lon of centre of obs footprint
+         REAL(KIND=wp), DIMENSION(4), INTENT(OUT) :: &
+            &  pxvert, pyvert              !x/y location (in metres relative to centre of obs footprint) of corners
+         REAL(KIND=wp), DIMENSION(4), INTENT(OUT) :: &
+            &  pdist                       !distance (in metres) of each corner relative to centre of obs footprint
+
+      !! * Local variables
+         INTEGER :: &
+            &  jvert                       !Counter for corners
+         REAL(KIND=wp) :: &
+            &  zphi, zlam                  !Local values for lon/lat of corners
+         REAL(KIND=wp) :: & 
+            &  za1, za2,  &                !For great circle distance calculations
+            &  zb1, zb2,  &
+            &  zc1, zc2
+         REAL(KIND=wp) :: &
+            &  zdist_centre_lat, &         !Distances in lat/lon directions (in metres)
+            &  zdist_centre_lon
+
+      !!-----------------------------------------------------------------------
+
+         ! Work out latitudinal and longitudinal distance from centre of 
+         ! obs fp to corners of grid box
+         DO jvert = 1, 4
+            SELECT CASE(jvert)
+            CASE(1)
+               zphi = pgphi_tl
+               zlam = pglam_tl
+            CASE(2)
+               zphi = pgphi_tr
+               zlam = pglam_tr
+            CASE(3)
+               zphi = pgphi_br
+               zlam = pglam_br
+            CASE(4)
+               zphi = pgphi_bl
+               zlam = pglam_bl
+            END SELECT
+            
+            IF (zlam == plam ) THEN
+               pxvert(jvert) = 0.0_wp
+            ELSE
+               za1 = SIN( zphi * rad )
+               za2 = SIN( zphi * rad )
+               zb1 = COS( zphi * rad ) * COS( zlam * rad )
+               zb2 = COS( zphi * rad ) * COS( plam  * rad )
+               zc1 = COS( zphi * rad ) * SIN( zlam * rad )
+               zc2 = COS( zphi * rad ) * SIN( plam  * rad )
+               pxvert(jvert) = grt_cir_dis( za1, za2, zb1, zb2, zc1, zc2 )
+               pxvert(jvert) =  ra * pxvert(jvert)
+               IF ( zlam < plam ) pxvert(jvert) = - pxvert(jvert)
+            ENDIF
+            
+            IF ( zphi == pphi ) THEN
+               pyvert(jvert) = 0.0_wp
+            ELSE
+               za1 = SIN( zphi * rad )
+               za2 = SIN( pphi * rad )
+               zb1 = COS( zphi * rad ) * COS( zlam * rad )
+               zb2 = COS( pphi * rad ) * COS( zlam * rad )
+               zc1 = COS( zphi * rad ) * SIN( zlam * rad )
+               zc2 = COS( pphi * rad ) * SIN( zlam * rad )
+               pyvert(jvert) = grt_cir_dis( za1, za2, zb1, zb2, zc1, zc2 )
+               pyvert(jvert) =  ra * pyvert(jvert)
+               IF ( zphi < pphi ) pyvert(jvert) = - pyvert(jvert)
+            ENDIF
+
+            !Calculate the distance of each vertex relative to centre of obs footprint
+            pdist(jvert) = SQRT( ( pxvert(jvert) * pxvert(jvert) ) + &
+               &                 ( pyvert(jvert) * pyvert(jvert) ) )
+
+         END DO
+
+      END SUBROUTINE obs_dist2corners
+
+END MODULE obs_averg_h2d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_const.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_const.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_const.F90	(revision 14097)
@@ -0,0 +1,23 @@
+MODULE obs_const
+   !!=====================================================================
+   !!                       ***  MODULE obs_const  ***
+   !! Observation diagnostics: Constants used by many modules
+   !!===================================================================== 
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   !! * Modules used
+   USE par_kind, ONLY : & ! Precision variables
+      & sp         
+   IMPLICIT NONE
+
+   !! * Routine/type accessibility
+   PUBLIC
+
+   REAL(kind=sp), PARAMETER :: obfillflt=99999.
+
+END MODULE obs_const
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv.F90	(revision 14097)
@@ -0,0 +1,46 @@
+MODULE obs_conv
+   !!=====================================================================
+   !!                       ***  MODULE  obs_conv  ***
+   !! Observation diagnostics: Various conversion functions
+   !!=====================================================================
+   !!
+   !!   potemp   : Compute potential temperature from insitu temperature,
+   !!              salinity and pressure
+   !!   fspott   : Compute potential temperature from insitu temperature,
+   !!              salinity and pressure
+   !!   atg      : Compute adiabatic temperature gradient deg c per decibar
+   !!   theta    : Compute potential temperature from insitu temperature,
+   !!              salinity and pressure
+   !!   depth    : Compute depth from pressure and latitude.
+   !!   p_to_dep : Compute depth from pressure and latitude 
+   !!              (approximate version)
+   !!   dep_to_p : Compute pressure from depth and latitude 
+   !!              (approximate version)
+   !!---------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : & ! Precision variables
+      & wp   
+   IMPLICIT NONE
+ 
+   !! * Function accessibility
+   PRIVATE
+   PUBLIC &
+      & potemp,   &
+      & fspott,   &
+      & atg,      &
+      & theta,    &
+      & depth,    &
+      & p_to_dep, &
+      & dep_to_p
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+#include "obs_conv_functions.h90"
+
+END MODULE obs_conv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv_functions.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv_functions.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_conv_functions.h90	(revision 14097)
@@ -0,0 +1,294 @@
+    !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+  REAL(KIND=wp) FUNCTION potemp( ps, pt, pp, ppr )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION potemp  ***
+      !!          
+      !! ** Purpose : Compute potential temperature
+      !!
+      !! ** Method  : A regression formula is used. 
+      !!
+      !! ** Action  : The code is kept as close to the F77 code as possible
+      !!              Check value: potemp(35,20,2000,0) = 19.621967
+      !!
+      !! References : T. J. Mcdougall, D. R. Jackett, D. G. Wright 
+      !!              and R. Feistel
+      !!              Accurate and computationally efficient algoritms for
+      !!              potential temperatures and density of seawater
+      !!              Journal of atmospheric and oceanic technology
+      !!              Vol 20, 2003, pp 730-741
+      !!              
+      !!
+      !! History :
+      !!        !  07-05 (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+
+      REAL(KIND=wp), INTENT(IN) :: ps
+      REAL(KIND=wp), INTENT(IN) :: pt
+      REAL(KIND=wp), INTENT(IN) :: pp
+      REAL(KIND=wp), INTENT(IN) :: ppr
+
+      !! * Local declarations
+      REAL(KIND=wp) :: zpol
+      REAL(KIND=wp), PARAMETER :: a1 =  1.067610e-05
+      REAL(KIND=wp), PARAMETER :: a2 = -1.434297e-06
+      REAL(KIND=wp), PARAMETER :: a3 = -7.566349e-09
+      REAL(KIND=wp), PARAMETER :: a4 = -8.535585e-06
+      REAL(KIND=wp), PARAMETER :: a5 =  3.074672e-08
+      REAL(KIND=wp), PARAMETER :: a6 =  1.918639e-08
+      REAL(KIND=wp), PARAMETER :: a7 =  1.788718e-10
+
+      zpol = a1 + a2 * ps + a3 * ( pp + ppr ) + a4 * pt &
+         & + a5 * ps * pt + a6 * pt * pt + a7 * pt * ( pp + ppr )
+      
+      potemp = pt + ( pp - ppr ) * zpol
+      
+   END FUNCTION potemp
+
+   REAL(KIND=wp) FUNCTION fspott( pft, pfs, pfp )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION fspott  ***
+      !!          
+      !! ** Purpose : Compute potential temperature
+      !!
+      !! ** Method  : A regression formula is used. 
+      !!
+      !! ** Action  : Check value: fspott(10,25,1000) = 8.4678516
+      !!
+      !! References : A. E. Gill
+      !!              Atmosphere-Ocean Dynamics
+      !!              Volume 30 (International Geophysics)
+      !!
+      !! History :
+      !!        !  07-05 (K. Mogensen) NEMO adopting of OPAVAR code.
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp) :: pft   ! in situ temperature in degrees Celsius
+      REAL(KIND=wp) :: pfs   ! salinity in psu
+      REAL(KIND=wp) :: pfp   ! pressure in bars
+      
+      fspott = &
+         &  pft - pfp * (   (            3.6504e-4                     &
+         &                    + pft * (  8.3198e-5                     &
+         &                    + pft * ( -5.4065e-7                     &
+         &                    + pft *    4.0274e-9  ) ) )              &
+         &                + ( pfs - 35.0 ) * (         1.7439e-5       &
+         &                                     - pft * 2.9778e-7 )     &
+         &                + pfp * (            8.9309e-7               &
+         &                          + pft * ( -3.1628e-8               &
+         &                          + pft *    2.1987e-10 )            &
+         &                          - ( pfs - 35.0 ) *  4.1057e-9      &
+         &                          + pfp * (          -1.6056e-10     &
+         &                                    + pft * 5.0484e-12 ) ) )
+
+   END FUNCTION fspott
+
+   REAL(KIND=wp) FUNCTION atg( p_s, p_t, p_p )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION atg  ***
+      !!          
+      !! ** Purpose : Compute adiabatic temperature gradient deg c per decibar
+      !!
+      !! ** Method  : A regression formula is used
+      !!
+      !! ** Action  : The code is kept as close to the F77 code as possible
+      !!              Check value: atg(40,40,10000) = 3.255974e-4
+      !!
+      !! References : N. P. Fotonoff and R.C. Millard jr., 
+      !!              Algoritms for computation of fundamental
+      !!              properties of seawater
+      !!              Unesco technical papers in marine science 44
+      !!              Unesco 1983
+      !!
+      !! History :
+      !!        !  07-05 (K. Mogensen) Original code based on the F77 code.
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+
+      REAL(KIND=wp), INTENT(IN) :: p_s    ! Salinity in PSU
+      REAL(KIND=wp), INTENT(IN) :: p_t    ! Temperature in centigrades
+      REAL(KIND=wp), INTENT(IN) :: p_p    ! Pressure in decibars.
+
+      !! * Local declarations
+      
+      REAL(KIND=wp) :: z_ds
+
+      z_ds = p_s - 35.0
+      atg = ((( -2.1687e-16 * p_t + 1.8676e-14 ) * p_t - 4.6206e-13 ) * p_p      &
+         &  + (( 2.7759e-12 * p_t - 1.1351e-10 ) * z_ds + (( - 5.4481e-14 * p_t  &  
+         &  + 8.733e-12 ) * p_t - 6.7795e-10 ) * p_t  + 1.8741e-8)) * p_p        &
+         &  + ( -4.2393e-8 * p_t + 1.8932e-6 ) * z_ds                          &
+         &  + (( 6.6228e-10 * p_t - 6.836e-8 ) * p_t + 8.5258e-6 ) * p_t + 3.5803e-5
+
+   END FUNCTION atg
+      
+   REAL(KIND=wp) FUNCTION theta( p_s, p_t0, p_p0, p_pr )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION theta  ***
+      !!          
+      !! ** Purpose : Compute potential temperature
+      !!
+      !! ** Method  : A regression formula is used. 
+      !!
+      !! ** Action  : The code is kept as close to the F77 code as possible
+      !!              Check value: theta(40,40,10000,0) = 36.89073
+      !!
+      !! References : N. P. Fotonoff and R.C. Millard jr., 
+      !!              Algoritms for computation of fundamental
+      !!              properties of seawater
+      !!              Unesco technical papers in marine science 44
+      !!              Unesco 1983
+      !!
+      !! History :
+      !!        !  07-05 (K. Mogensen) Original code based on the F77 code.
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: p_s
+      REAL(KIND=wp), INTENT(IN) :: p_t0
+      REAL(KIND=wp), INTENT(IN) :: p_p0
+      REAL(KIND=wp), INTENT(IN) :: p_pr
+
+      !! * Local declarations
+      REAL(KIND=wp) :: z_p
+      REAL(KIND=wp) :: z_t
+      REAL(KIND=wp) :: z_h
+      REAL(KIND=wp) :: z_xk
+      REAL(KIND=wp) :: z_q
+
+      z_p = p_p0
+      z_t = p_t0
+      z_h = p_pr - z_p
+      z_xk = z_h * atg( p_s, z_t, z_p ) 
+      Z_t = z_t + 0.5 * z_xk
+      z_q = z_xk
+      z_p = z_p + 0.5 * z_h
+      z_xk = z_h * atg( p_s, z_t, z_p )
+      z_t = z_t + 0.29289322 * ( z_xk - z_q )
+      z_q = 0.58578644 * z_xk + 0.121320344 * z_q
+      z_xk = z_h * atg( p_s, z_t, z_p )
+      z_t = z_t + 1.707106781 * ( z_xk - z_q )
+      z_q = 3.414213562 * z_xk - 4.121320244 * z_q
+      z_p = z_p + 0.5 * z_h
+      z_xk = z_h * atg( p_s, z_t, z_p )
+      theta = z_t + ( z_xk - 2.0 * z_q ) / 6.0
+
+   END FUNCTION theta
+
+   REAL(KIND=wp) FUNCTION depth( p_p, p_lat )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION depth  ***
+      !!          
+      !! ** Purpose : Compute depth from pressure and latitudes
+      !!
+      !! ** Method  : A regression formula is used. 
+      !!
+      !! ** Action  : The code is kept as close to the F77 code as possible
+      !!              Check value: depth(10000,30) = 9712.653
+      !!
+      !! References : N. P. Fotonoff and R.C. Millard jr., 
+      !!              Algoritms for computation of fundamental
+      !!              properties of seawater
+      !!              Unesco technical papers in marine science 44
+      !!              Unesco 1983
+      !!
+      !! History :
+      !!        !  07-05 (K. Mogensen) Original code based on the F77 code.
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: p_p     ! Pressure in decibars
+      REAL(KIND=wp), INTENT(IN) :: p_lat   ! Latitude in degrees
+
+      !! * Local declarations
+      REAL(KIND=wp) :: z_x
+      REAL(KIND=wp) :: z_gr
+      
+      z_x = SIN( p_lat / 57.29578 )
+      z_x = z_x * z_x
+      z_gr = 9.780318 * ( 1.0 + ( 5.2788e-3 + 2.36e-5 * z_x ) * z_x ) + 1.092e-6 * p_p
+      depth = ((( -1.82e-15 * p_p + 2.279e-10 ) * p_p - 2.2512e-5 ) * p_p + 9.72659 ) * p_p
+      depth = depth / z_gr
+
+   END FUNCTION depth
+
+   REAL(KIND=wp) FUNCTION p_to_dep( p_p, p_lat )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION p_to_dep  ***
+      !!          
+      !! ** Purpose : Compute depth from pressure and latitudes
+      !!
+      !! ** Method  : A regression formula is used. This version is less
+      !!              accurate the "depth" but invertible.
+      !!
+      !! ** Action  : 
+      !!
+      !! References : P.M Saunders
+      !!              Pratical conversion of pressure to depth
+      !!              Journal of physical oceanography Vol 11, 1981, pp 573-574
+      !!
+      !! History :
+      !!        !  07-05  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: p_p    ! Pressure in decibars
+      REAL(KIND=wp), INTENT(IN) :: p_lat  ! Latitude in degrees
+
+      !! * Local declarations
+      REAL(KIND=wp) :: z_x
+      REAL(KIND=wp) :: z_c1
+      REAL(KIND=wp) :: z_c2
+
+      z_x = SIN( p_lat / 57.29578 )
+      z_x = z_x * z_x
+      z_c1 = ( 5.92  + 5.25 * z_x ) * 1e-3 
+      z_c2 = 2.21e-6 
+      p_to_dep = (1 - z_c1)  * p_p - z_c2 * p_p * p_p
+
+   END FUNCTION p_to_dep
+
+   REAL(KIND=wp) FUNCTION dep_to_p( p_dep, p_lat )
+      !!----------------------------------------------------------------------
+      !!                    ***  FUNCTION dep_to_p  ***
+      !!          
+      !! ** Purpose : Compute depth from pressure and latitudes
+      !!
+      !! ** Method  : The expression used in p_to_dep is inverted.
+      !!
+      !! ** Action  : 
+      !!
+      !! References : P.M Saunders
+      !!              Pratical conversion of pressure to depth
+      !!              Journal of physical oceanography Vol 11, 1981, pp 573-574
+      !!
+      !! History :
+      !!        !  07-05  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: p_dep    ! Depth in meters
+      REAL(KIND=wp), INTENT(IN) :: p_lat    ! Latitude in degrees
+
+      !! * Local declarations
+      REAL(KIND=wp) :: z_x
+      REAL(KIND=wp) :: z_c1
+      REAL(KIND=wp) :: z_c2
+      REAL(KIND=wp) :: z_d
+
+      z_x = SIN( p_lat / 57.29578 )
+      z_x = z_x * z_x
+      z_c1 = ( 5.92  + 5.25 * z_x ) * 1e-3 
+      z_c2 = 2.21e-6 
+      z_d = ( z_c1 - 1 ) * ( z_c1 - 1  ) - 4 * z_c2 * p_dep
+      dep_to_p = (( 1 - z_c1 ) - SQRT( z_d )) / ( 2 * z_c2 )
+
+   END FUNCTION dep_to_p
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_fbm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_fbm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_fbm.F90	(revision 14097)
@@ -0,0 +1,1998 @@
+MODULE obs_fbm
+   !!======================================================================
+   !!                       ***  MODULE obs_fbm  ***
+   !! Observation operators : I/O + tools for feedback files
+   !!======================================================================
+   !! History : 
+   !!             !  08-11  (K. Mogensen) Initial version
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   init_obfbdata     :  Initialize sizes in obfbdata structure
+   !!   alloc_obfbdata    :  Allocate data in an obfbdata structure
+   !!   dealloc_obfbdata  :  Dellocate data in an obfbdata structure
+   !!   copy_obfbdata     :  Copy an obfbdata structure
+   !!   subsamp_obfbdata  :  Sumsample an obfbdata structure
+   !!   merge_obfbdata    :  Merge multiple obfbdata structures into an one.
+   !!   write_obfbdata    :  Write an obfbdata structure into a netCDF file.
+   !!   read_obfbdata     :  Read an obfbdata structure from a netCDF file.
+   !!----------------------------------------------------------------------
+   USE netcdf
+   USE obs_utils      ! Various utilities for observation operators
+
+   IMPLICIT NONE
+   PUBLIC
+
+   ! Type kinds for feedback data.
+
+   INTEGER, PARAMETER :: fbsp = SELECTED_REAL_KIND( 6, 37) !: single precision
+   INTEGER, PARAMETER :: fbdp = SELECTED_REAL_KIND(12,307) !: double precision
+
+   ! Parameters for string lengths.
+
+   INTEGER, PARAMETER    :: ilenwmo  = 8    !: Length of station identifier
+   INTEGER, PARAMETER    :: ilentyp  = 4    !: Length of type
+   INTEGER, PARAMETER    :: ilenname = 8    !: Length of variable names
+   INTEGER, PARAMETER    :: ilengrid = 1    !: Grid (e.g. 'T') length
+   INTEGER, PARAMETER    :: ilenjuld = 14   !: Lenght of reference julian date
+   INTEGER, PARAMETER    :: idefnqcf = 2    !: Default number of words in QC
+                                            !  flags
+   INTEGER, PARAMETER    :: ilenlong = 128  !: Length of long name
+   INTEGER, PARAMETER    :: ilenunit = 32   !: Length of units
+   
+   ! Missinge data indicators 
+   
+   INTEGER, PARAMETER    :: fbimdi = -99999   !: Integers
+   REAL(fbsp), PARAMETER :: fbrmdi =  99999   !: Reals
+ 
+   ! Main data structure for observation feedback data.
+
+   TYPE obfbdata
+      LOGICAL :: lalloc         !: Allocation status for data
+      LOGICAL :: lgrid          !: Include grid search info
+      INTEGER :: nvar           !: Number of variables
+      INTEGER :: nobs           !: Number of observations
+      INTEGER :: nlev           !: Number of levels
+      INTEGER :: nadd           !: Number of additional entries
+      INTEGER :: next           !: Number of extra variables
+      INTEGER :: nqcf           !: Number of words per qc flag
+      CHARACTER(LEN=ilenwmo), DIMENSION(:), POINTER :: &
+         & cdwmo                !: Identifier
+      CHARACTER(LEN=ilentyp), DIMENSION(:), POINTER :: &
+         & cdtyp                !: Instrument type
+      CHARACTER(LEN=ilenjuld) :: &
+         & cdjuldref            !: Julian date reference
+      INTEGER, DIMENSION(:), POINTER :: &
+         & kindex               !: Index of observations in the original file
+      INTEGER, DIMENSION(:), POINTER :: &
+         & ioqc, &              !: Observation QC
+         & ipqc, &              !: Position QC
+         & itqc                 !: Time QC
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & ioqcf, &             !: Observation QC flags
+         & ipqcf, &             !: Position QC flags
+         & itqcf                !: Time QC flags
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & idqc                 !: Depth QC
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & idqcf                !: Depth QC flags
+      REAL(KIND=fbdp), DIMENSION(:), POINTER :: &
+         & plam, &              !: Longitude
+         & pphi, &              !: Latitude
+         & ptim                 !: Time
+      REAL(KIND=fbsp), DIMENSION(:,:), POINTER :: &
+         & pdep                 !: Depth
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER  :: &
+         & cname                !: Name of variable
+      REAL(fbsp), DIMENSION(:,:,:), POINTER :: &
+         & pob                  !: Observation
+      CHARACTER(LEN=ilenlong), DIMENSION(:), POINTER :: &
+         & coblong              !: Observation long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:), POINTER :: &
+         & cobunit              !: Observation units (for output)
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & ivqc                 !: Variable QC
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & ivqcf                !: Variable QC flags
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & ivlqc                !: Variable level QC
+      INTEGER, DIMENSION(:,:,:,:), POINTER :: &
+         & ivlqcf               !: Variable level QC flags
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & iproc, &             !: Processor of obs (no I/O for this variable).
+         & iobsi, &             !: Global i index
+         & iobsj                !: Global j index
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & iobsk                !: k index
+      CHARACTER(LEN=ilengrid), DIMENSION(:), POINTER  :: &
+         & cgrid                !: Grid for this variable
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER :: &
+         & caddname             !: Additional entries names
+      CHARACTER(LEN=ilenlong), DIMENSION(:,:), POINTER :: &
+         & caddlong             !: Additional entries long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:,:), POINTER :: &
+         & caddunit             !: Additional entries units (for output)
+      REAL(fbsp), DIMENSION(:,:,:,:)   , POINTER :: &
+         & padd                 !: Additional entries
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER :: &
+         & cextname             !: Extra variables names
+      CHARACTER(LEN=ilenlong), DIMENSION(:), POINTER :: &
+         & cextlong             !: Extra variables long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:), POINTER :: &
+         & cextunit             !: Extra variables units (for output)
+      REAL(fbsp), DIMENSION(:,:,:)   , POINTER :: &
+         & pext                 !: Extra variables
+   END TYPE obfbdata
+
+   PRIVATE putvaratt_obfbdata
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE init_obfbdata( fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE init_obfbdata  ***
+      !!
+      !! ** Purpose :   Initialize sizes in obfbdata structure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata      ! obsfbdata structure
+
+      fbdata%nvar   = 0
+      fbdata%nobs   = 0
+      fbdata%nlev   = 0
+      fbdata%nadd   = 0
+      fbdata%next   = 0
+      fbdata%nqcf   = idefnqcf
+      fbdata%lalloc = .FALSE.
+      fbdata%lgrid  = .FALSE.
+
+   END SUBROUTINE init_obfbdata
+   
+   SUBROUTINE alloc_obfbdata( fbdata, kvar, kobs, klev, kadd, kext, lgrid, &
+      &                       kqcf)
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE alloc_obfbdata  ***
+      !!
+      !! ** Purpose :   Allocate data in an obfbdata structure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) ::  fbdata          ! obsfbdata structure to be allocated
+      INTEGER, INTENT(IN) :: kvar        ! Number of variables
+      INTEGER, INTENT(IN) :: kobs        ! Number of observations
+      INTEGER, INTENT(IN) :: klev        ! Number of levels
+      INTEGER, INTENT(IN) :: kadd        ! Number of additional entries
+      INTEGER, INTENT(IN) :: kext        ! Number of extra variables
+      LOGICAL, INTENT(IN) :: lgrid       ! Include grid search information
+      INTEGER, OPTIONAL ::  kqcf         ! Number of words for QC flags
+      !! * Local variables
+      INTEGER :: ji
+      INTEGER :: jv
+
+      ! Check allocation status and deallocate previous allocated structures
+
+      IF ( fbdata%lalloc ) THEN
+         CALL dealloc_obfbdata( fbdata )
+      ENDIF
+
+      ! Set dimensions
+
+      fbdata%lalloc = .TRUE.
+      fbdata%nvar   = kvar
+      fbdata%nobs   = kobs
+      fbdata%nlev   = MAX( klev, 1 )
+      fbdata%nadd   = kadd
+      fbdata%next   = kext
+      IF ( PRESENT(kqcf) ) THEN
+         fbdata%nqcf = kqcf
+      ELSE
+         fbdata%nqcf = idefnqcf
+      ENDIF
+
+      ! Set data not depending on number of observations
+
+      fbdata%cdjuldref  = REPEAT( 'X', ilenjuld )
+
+      ! Allocate and initialize standard data 
+
+      ALLOCATE( &
+         & fbdata%cname(fbdata%nvar),   &
+         & fbdata%coblong(fbdata%nvar), &
+         & fbdata%cobunit(fbdata%nvar)  &
+         & )
+      DO ji = 1, fbdata%nvar
+         WRITE(fbdata%cname(ji),'(A,I2.2)')'V_',ji
+         fbdata%coblong(ji) = REPEAT( ' ', ilenlong )
+         fbdata%cobunit(ji) = REPEAT( ' ', ilenunit )
+      END DO
+
+      ! Optionally also store grid search information
+      
+      IF ( lgrid ) THEN
+         ALLOCATE ( &
+            & fbdata%cgrid(fbdata%nvar) &
+            & )
+         fbdata%cgrid(:)      = REPEAT( 'X', ilengrid )
+         fbdata%lgrid         = .TRUE.
+      ENDIF
+         
+      ! Allocate and initialize additional entries if present
+         
+      IF ( fbdata%nadd > 0 ) THEN
+         ALLOCATE( &
+            & fbdata%caddname(fbdata%nadd),              &
+            & fbdata%caddlong(fbdata%nadd, fbdata%nvar), &
+            & fbdata%caddunit(fbdata%nadd, fbdata%nvar)  &
+            & )
+         DO ji = 1, fbdata%nadd
+            WRITE(fbdata%caddname(ji),'(A,I2.2)')'A',ji
+         END DO
+         DO jv = 1, fbdata%nvar
+            DO ji = 1, fbdata%nadd
+               fbdata%caddlong(ji,jv) = REPEAT( ' ', ilenlong )
+               fbdata%caddunit(ji,jv) = REPEAT( ' ', ilenunit )
+            END DO
+         END DO
+      ENDIF
+         
+      ! Allocate and initialize additional variables if present
+         
+      IF ( fbdata%next > 0 ) THEN
+         ALLOCATE( &
+            & fbdata%cextname(fbdata%next), &
+            & fbdata%cextlong(fbdata%next), &
+            & fbdata%cextunit(fbdata%next)  &
+            & )
+         DO ji = 1, fbdata%next
+            WRITE(fbdata%cextname(ji),'(A,I2.2)')'E_',ji
+            fbdata%cextlong(ji) = REPEAT( ' ', ilenlong )
+            fbdata%cextunit(ji) = REPEAT( ' ', ilenunit )
+         END DO
+      ENDIF
+
+      ! Data depending on number of observations is only allocated if nobs>0
+
+      IF ( fbdata%nobs > 0 ) THEN
+
+         ALLOCATE( &
+            & fbdata%cdwmo(fbdata%nobs),                                      &
+            & fbdata%cdtyp(fbdata%nobs),                                      &
+            & fbdata%ioqc(fbdata%nobs),                                       &
+            & fbdata%ioqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%ipqc(fbdata%nobs),                                       &
+            & fbdata%ipqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%itqc(fbdata%nobs),                                       &
+            & fbdata%itqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%idqc(fbdata%nlev,fbdata%nobs),                           &
+            & fbdata%idqcf(fbdata%nqcf,fbdata%nlev,fbdata%nobs),              &
+            & fbdata%plam(fbdata%nobs),                                       &
+            & fbdata%pphi(fbdata%nobs),                                       &
+            & fbdata%pdep(fbdata%nlev,fbdata%nobs),                           &
+            & fbdata%ptim(fbdata%nobs),                                       &
+            & fbdata%kindex(fbdata%nobs),                                     &
+            & fbdata%ivqc(fbdata%nobs,fbdata%nvar),                           &
+            & fbdata%ivqcf(fbdata%nqcf,fbdata%nobs,fbdata%nvar),              &
+            & fbdata%ivlqc(fbdata%nlev,fbdata%nobs,fbdata%nvar),              &
+            & fbdata%ivlqcf(fbdata%nqcf,fbdata%nlev,fbdata%nobs,fbdata%nvar), &
+            & fbdata%pob(fbdata%nlev,fbdata%nobs,fbdata%nvar)                 &
+            & )
+         fbdata%kindex(:)       = fbimdi
+         fbdata%cdwmo(:)        = REPEAT( 'X', ilenwmo )
+         fbdata%cdtyp(:)        = REPEAT( 'X', ilentyp )
+         fbdata%ioqc(:)         = fbimdi
+         fbdata%ioqcf(:,:)      = fbimdi
+         fbdata%ipqc(:)         = fbimdi
+         fbdata%ipqcf(:,:)      = fbimdi
+         fbdata%itqc(:)         = fbimdi
+         fbdata%itqcf(:,:)      = fbimdi
+         fbdata%idqc(:,:)       = fbimdi
+         fbdata%idqcf(:,:,:)    = fbimdi
+         fbdata%plam(:)         = fbrmdi
+         fbdata%pphi(:)         = fbrmdi
+         fbdata%pdep(:,:)       = fbrmdi
+         fbdata%ptim(:)         = fbrmdi
+         fbdata%ivqc(:,:)       = fbimdi
+         fbdata%ivqcf(:,:,:)    = fbimdi
+         fbdata%ivlqc(:,:,:)    = fbimdi
+         fbdata%ivlqcf(:,:,:,:) = fbimdi
+         fbdata%pob(:,:,:)      = fbrmdi
+         
+         ! Optionally also store grid search information
+         
+         IF ( lgrid ) THEN
+            ALLOCATE ( &
+               & fbdata%iproc(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsi(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsj(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsk(fbdata%nlev,fbdata%nobs,fbdata%nvar) &
+               & )
+            fbdata%iproc(:,:)    = fbimdi
+            fbdata%iobsi(:,:)    = fbimdi
+            fbdata%iobsj(:,:)    = fbimdi
+            fbdata%iobsk(:,:,:)  = fbimdi
+            fbdata%lgrid         = .TRUE.
+         ENDIF
+         
+         ! Allocate and initialize additional entries if present
+         
+         IF ( fbdata%nadd > 0 ) THEN
+            ALLOCATE( &
+               & fbdata%padd(fbdata%nlev,fbdata%nobs,fbdata%nadd,fbdata%nvar) &
+               & )
+            fbdata%padd(:,:,:,:) = fbrmdi
+         ENDIF
+         
+         ! Allocate and initialize additional variables if present
+         
+         IF ( fbdata%next > 0 ) THEN
+            ALLOCATE( &
+               & fbdata%pext(fbdata%nlev,fbdata%nobs,fbdata%next) &
+               & )
+            fbdata%pext(:,:,:) = fbrmdi
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE alloc_obfbdata
+
+   SUBROUTINE dealloc_obfbdata( fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dealloc_obfbdata  ***
+      !!
+      !! ** Purpose :   Deallocate data in an obfbdata strucure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata      ! obsfbdata structure
+
+      ! Deallocate data 
+
+      DEALLOCATE( &
+         & fbdata%cname,  &
+         & fbdata%coblong,&
+         & fbdata%cobunit &
+         & )
+
+      ! Deallocate optional grid search information
+      
+      IF ( fbdata%lgrid ) THEN
+         DEALLOCATE ( &
+            & fbdata%cgrid  &
+            & )
+      ENDIF
+
+      ! Deallocate additional entries
+
+      IF ( fbdata%nadd > 0 ) THEN
+         DEALLOCATE( &
+            & fbdata%caddname, &
+            & fbdata%caddlong, &
+            & fbdata%caddunit  &
+            & )
+      ENDIF
+
+      ! Deallocate extra variables
+
+      IF ( fbdata%next > 0 ) THEN
+         DEALLOCATE( &
+            & fbdata%cextname, &
+            & fbdata%cextlong, &
+            & fbdata%cextunit  &
+            & )
+      ENDIF
+
+      ! Deallocate arrays depending on number of obs (if nobs>0 only).
+
+      IF ( fbdata%nobs > 0 ) THEN
+
+         DEALLOCATE( &
+            & fbdata%cdwmo,  &
+            & fbdata%cdtyp,  &
+            & fbdata%ioqc,   &
+            & fbdata%ioqcf,  &
+            & fbdata%ipqc,   &
+            & fbdata%ipqcf,  &
+            & fbdata%itqc,   &
+            & fbdata%itqcf,  &
+            & fbdata%idqc,   &
+            & fbdata%idqcf,  &
+            & fbdata%plam,   &
+            & fbdata%pphi,   &
+            & fbdata%pdep,   &
+            & fbdata%ptim,   &
+            & fbdata%kindex, &
+            & fbdata%ivqc,   &
+            & fbdata%ivqcf,  &
+            & fbdata%ivlqc,  &
+            & fbdata%ivlqcf, &
+            & fbdata%pob     &
+            & )
+
+
+         ! Deallocate optional grid search information
+      
+         IF ( fbdata%lgrid ) THEN
+            DEALLOCATE ( &
+               & fbdata%iproc, &
+               & fbdata%iobsi, &
+               & fbdata%iobsj, &
+               & fbdata%iobsk  & 
+               & )
+         ENDIF
+
+         ! Deallocate additional entries
+
+         IF ( fbdata%nadd > 0 ) THEN
+            DEALLOCATE( &
+               & fbdata%padd       &
+               & )
+         ENDIF
+
+         ! Deallocate extra variables
+
+         IF ( fbdata%next > 0 ) THEN
+            DEALLOCATE( &
+               & fbdata%pext       &
+               & )
+         ENDIF
+
+      ENDIF
+
+      ! Reset arrays sizes
+
+      fbdata%lalloc = .FALSE.
+      fbdata%lgrid  = .FALSE.
+      fbdata%nvar   = 0
+      fbdata%nobs   = 0
+      fbdata%nlev   = 0
+      fbdata%nadd   = 0
+      fbdata%next   = 0
+   
+   END SUBROUTINE dealloc_obfbdata
+
+   SUBROUTINE copy_obfbdata( fbdata1, fbdata2, kadd, kext, lgrid, kqcf )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE copy_obfbdata  ***
+      !!
+      !! ** Purpose :   Copy an obfbdata structure
+      !!
+      !! ** Method  :   Copy all data from fbdata1 to fbdata2
+      !!                If fbdata2 is allocated it needs to be compliant
+      !!                with fbdata1.
+      !!                Additional entries can be added by setting nadd
+      !!                Additional extra fields can be added by setting next
+      !!                Grid information can be included with lgrid=.true.
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata1               ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdata2               ! Output obsfbdata structure
+      INTEGER, INTENT(IN), OPTIONAL :: kadd   ! Number of additional entries
+      INTEGER, INTENT(IN), OPTIONAL :: kext   ! Number of extra variables
+      INTEGER, INTENT(IN), OPTIONAL :: kqcf   ! Number of words per qc flags
+      LOGICAL, OPTIONAL :: lgrid              ! Grid info on output file
+
+      !! * Local variables
+      INTEGER :: nadd
+      INTEGER :: next
+      INTEGER :: nqcf
+      LOGICAL :: llgrid
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+
+      ! Check allocation status of fbdata1
+
+      IF ( .NOT. fbdata1%lalloc ) THEN
+         CALL fatal_error( 'copy_obfbdata: input data not allocated', &
+            &              __LINE__ )
+      ENDIF
+      
+      ! If nadd,next not specified use the ones from fbdata1
+      ! Otherwise check that they have large than the original ones
+      
+      IF ( PRESENT(kadd) ) THEN
+         nadd = kadd
+         IF ( nadd < fbdata1%nadd ) THEN
+            CALL warning    ( 'copy_obfbdata: ' // &
+               &              'nadd smaller than input nadd', __LINE__ )
+         ENDIF
+      ELSE
+         nadd = fbdata1%nadd
+      ENDIF
+      IF ( PRESENT(kext) ) THEN
+         next = kext
+         IF ( next < fbdata1%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'next smaller than input next', __LINE__ )
+         ENDIF
+      ELSE
+         next = fbdata1%next
+      ENDIF
+      IF ( PRESENT(lgrid) ) THEN
+         llgrid = lgrid
+         IF ( fbdata1%lgrid .AND. (.NOT. llgrid) ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'switching off grid info not possible', &
+               &              __LINE__ )
+         ENDIF
+      ELSE
+         llgrid = fbdata1%lgrid
+      ENDIF
+      IF ( PRESENT(kqcf) ) THEN
+         nqcf = kqcf
+         IF ( nqcf < fbdata1%nqcf ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'nqcf smaller than input nqcf', __LINE__ )
+         ENDIF
+      ELSE
+         nqcf = fbdata1%nqcf
+      ENDIF
+
+      ! Check allocation status of fbdata2 and 
+      ! a) check that it conforms in size if already allocated
+      ! b) allocate it if not already allocated
+      
+      IF ( fbdata2%lalloc ) THEN
+         IF ( fbdata1%nvar > fbdata2%nvar ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output kvar smaller than input kvar', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nobs > fbdata2%nobs ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output kobs smaller than input kobs', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nlev > fbdata2%nlev ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output klev smaller than input klev', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nadd > fbdata2%nadd ) THEN
+            CALL warning    ( 'copy_obfbdata: ' // &
+               &              'output nadd smaller than input nadd', __LINE__ )
+         ENDIF
+         IF ( fbdata1%next > fbdata2%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output next smaller than input next', __LINE__ )
+         ENDIF
+         IF ( fbdata1%lgrid .NEQV. fbdata2%lgrid ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'lgrid inconsistent', __LINE__ )
+         ENDIF
+         IF ( fbdata1%next > fbdata2%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output next smaller than input next', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nqcf > fbdata2%nqcf ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output  smaller than input kext', __LINE__ )
+         ENDIF
+      ELSE
+         CALL alloc_obfbdata( fbdata2, fbdata1%nvar, fbdata1%nobs, &
+            &                 fbdata1%nlev, nadd, next, llgrid, kqcf = nqcf )
+      ENDIF
+
+      ! Copy the header data
+
+      fbdata2%cdjuldref = fbdata1%cdjuldref
+
+      DO ji = 1, fbdata1%nobs
+         fbdata2%cdwmo(ji)  = fbdata1%cdwmo(ji)
+         fbdata2%cdtyp(ji)  = fbdata1%cdtyp(ji)
+         fbdata2%ioqc(ji)   = fbdata1%ioqc(ji)
+         fbdata2%ipqc(ji)   = fbdata1%ipqc(ji)
+         fbdata2%itqc(ji)   = fbdata1%itqc(ji)
+         fbdata2%plam(ji)   = fbdata1%plam(ji)
+         fbdata2%pphi(ji)   = fbdata1%pphi(ji)
+         fbdata2%ptim(ji)   = fbdata1%ptim(ji)
+         fbdata2%kindex(ji) = fbdata1%kindex(ji)
+         DO jq = 1, fbdata1%nqcf
+            fbdata2%ioqcf(jq,ji)  = fbdata1%ioqcf(jq,ji)
+            fbdata2%ipqcf(jq,ji)  = fbdata1%ipqcf(jq,ji)
+            fbdata2%itqcf(jq,ji)  = fbdata1%itqcf(jq,ji)
+         END DO
+         DO jk = 1, fbdata1%nlev
+            fbdata2%idqc(jk,ji)  = fbdata1%idqc(jk,ji)
+            fbdata2%pdep(jk,ji)  = fbdata1%pdep(jk,ji)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%idqcf(jq,jk,ji) = fbdata1%idqcf(jq,jk,ji)
+            END DO
+         END DO
+      END DO
+
+      ! Copy the variable data
+
+      DO jv = 1, fbdata1%nvar
+         fbdata2%cname(jv) = fbdata1%cname(jv)
+         fbdata2%coblong(jv) = fbdata1%coblong(jv)
+         fbdata2%cobunit(jv) = fbdata1%cobunit(jv)
+         DO ji = 1, fbdata1%nobs
+            fbdata2%ivqc(ji,jv)  = fbdata1%ivqc(ji,jv)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%ivqcf(jq,ji,jv) = fbdata1%ivqcf(jq,ji,jv)
+            END DO
+            DO jk = 1, fbdata1%nlev
+               fbdata2%ivlqc(jk,ji,jv)  = fbdata1%ivlqc(jk,ji,jv)
+               fbdata2%pob(jk,ji,jv)    = fbdata1%pob(jk,ji,jv)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%ivlqcf(jq,jk,ji,jv) = fbdata1%ivlqcf(jq,jk,ji,jv)
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Copy grid information
+      
+      IF ( fbdata1%lgrid ) THEN
+         DO jv = 1, fbdata1%nvar
+            fbdata2%cgrid(jv) = fbdata1%cgrid(jv)
+            DO ji = 1, fbdata1%nobs
+               fbdata2%iproc(ji,jv) = fbdata1%iproc(ji,jv)
+               fbdata2%iobsi(ji,jv) = fbdata1%iobsi(ji,jv)
+               fbdata2%iobsj(ji,jv) = fbdata1%iobsj(ji,jv)
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%iobsk(jk,ji,jv)  = fbdata1%iobsk(jk,ji,jv)
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      ! Copy additional information
+      
+      DO je = 1, MIN( fbdata1%nadd, fbdata2%nadd )
+         fbdata2%caddname(je) = fbdata1%caddname(je)
+      END DO
+      DO jv = 1, fbdata1%nvar
+         DO je = 1, MIN( fbdata1%nadd, fbdata2%nadd )
+            fbdata2%caddlong(je,jv) = fbdata1%caddlong(je,jv)
+            fbdata2%caddunit(je,jv) = fbdata1%caddunit(je,jv)
+            DO ji = 1, fbdata1%nobs
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%padd(jk,ji,je,jv) = fbdata1%padd(jk,ji,je,jv)
+               END DO
+            END DO
+         END DO
+      END DO
+      
+      ! Copy extra information
+
+      DO je = 1, fbdata1%next
+         fbdata2%cextname(je) = fbdata1%cextname(je)
+         fbdata2%cextlong(je) = fbdata1%cextlong(je)
+         fbdata2%cextunit(je) = fbdata1%cextunit(je)
+      END DO
+      DO je = 1, fbdata1%next
+         DO ji = 1, fbdata1%nobs
+            DO jk = 1, fbdata1%nlev
+               fbdata2%pext(jk,ji,je) = fbdata1%pext(jk,ji,je)
+            END DO
+         END DO
+      END DO
+
+   END SUBROUTINE copy_obfbdata
+
+   SUBROUTINE subsamp_obfbdata( fbdata1, fbdata2, llvalid )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE susbamp_obfbdata  ***
+      !!
+      !! ** Purpose :   Subsample an obfbdata structure based on the
+      !!                logical mask.
+      !!
+      !! ** Method  :   Copy all data from fbdata1 to fbdata2 if
+      !!                llvalid(obs)==true
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata1           ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdata2           ! Output obsfbdata structure
+      LOGICAL, DIMENSION(fbdata1%nobs) :: llvalid     ! Grid info on output file
+      !! * Local variables
+      INTEGER :: nobs
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+      INTEGER :: ij
+
+      ! Check allocation status of fbdata1
+
+      IF ( .NOT. fbdata1%lalloc ) THEN
+         CALL fatal_error( 'copy_obfbdata: input data not allocated', &
+            &              __LINE__ )
+      ENDIF
+      
+      ! Check allocation status of fbdata2 and abort if already allocated
+      
+      IF ( fbdata2%lalloc ) THEN
+         CALL fatal_error( 'subsample_obfbdata: ' // &
+            &              'fbdata2 already allocated', __LINE__ )
+      ENDIF
+      
+      ! Count number of subsampled observations
+
+      nobs = COUNT(llvalid)
+      
+      ! Allocate new data structure
+
+      CALL alloc_obfbdata( fbdata2, fbdata1%nvar, nobs, &
+         &                 fbdata1%nlev, fbdata1%nadd, fbdata1%next, &
+         &                 fbdata1%lgrid, kqcf = fbdata1%nqcf )
+
+      ! Copy the header data
+
+      fbdata2%cdjuldref = fbdata1%cdjuldref
+      
+      ij = 0
+      DO ji = 1, fbdata1%nobs
+         IF ( llvalid(ji) ) THEN
+            ij = ij +1
+            fbdata2%cdwmo(ij)  = fbdata1%cdwmo(ji)
+            fbdata2%cdtyp(ij)  = fbdata1%cdtyp(ji)
+            fbdata2%ioqc(ij)   = fbdata1%ioqc(ji)
+            fbdata2%ipqc(ij)   = fbdata1%ipqc(ji)
+            fbdata2%itqc(ij)   = fbdata1%itqc(ji)
+            fbdata2%plam(ij)   = fbdata1%plam(ji)
+            fbdata2%pphi(ij)   = fbdata1%pphi(ji)
+            fbdata2%ptim(ij)   = fbdata1%ptim(ji)
+            fbdata2%kindex(ij) = fbdata1%kindex(ji)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%ioqcf(jq,ij)  = fbdata1%ioqcf(jq,ji)
+               fbdata2%ipqcf(jq,ij)  = fbdata1%ipqcf(jq,ji)
+               fbdata2%itqcf(jq,ij)  = fbdata1%itqcf(jq,ji)
+            END DO
+            DO jk = 1, fbdata1%nlev
+               fbdata2%idqc(jk,ij)  = fbdata1%idqc(jk,ji)
+               fbdata2%pdep(jk,ij)  = fbdata1%pdep(jk,ji)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%idqcf(jq,jk,ij) = fbdata1%idqcf(jq,jk,ji)
+               END DO
+            END DO
+         ENDIF
+      END DO
+
+      ! Copy the variable data
+
+      DO jv = 1, fbdata1%nvar
+         fbdata2%cname(jv) = fbdata1%cname(jv)
+         fbdata2%coblong(jv) = fbdata1%coblong(jv)
+         fbdata2%cobunit(jv) = fbdata1%cobunit(jv)
+         ij = 0
+         DO ji = 1, fbdata1%nobs
+            IF ( llvalid(ji) ) THEN
+               ij = ij + 1
+               fbdata2%ivqc(ij,jv)  = fbdata1%ivqc(ji,jv)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%ivqcf(jq,ij,jv) = fbdata1%ivqcf(jq,ji,jv)
+               END DO
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%ivlqc(jk,ij,jv)  = fbdata1%ivlqc(jk,ji,jv)
+                  fbdata2%pob(jk,ij,jv)    = fbdata1%pob(jk,ji,jv)
+                  DO jq = 1, fbdata1%nqcf
+                     fbdata2%ivlqcf(jq,jk,ij,jv) = fbdata1%ivlqcf(jq,jk,ji,jv)
+                  END DO
+               END DO
+            ENDIF
+         END DO
+      END DO
+
+      ! Copy grid information
+      
+      IF ( fbdata1%lgrid ) THEN
+         DO jv = 1, fbdata1%nvar
+            fbdata2%cgrid(jv) = fbdata1%cgrid(jv)
+            ij = 0
+            DO ji = 1, fbdata1%nobs
+               IF ( llvalid(ji) ) THEN
+                  ij = ij + 1
+                  fbdata2%iproc(ij,jv) = fbdata1%iproc(ji,jv)
+                  fbdata2%iobsi(ij,jv) = fbdata1%iobsi(ji,jv)
+                  fbdata2%iobsj(ij,jv) = fbdata1%iobsj(ji,jv)
+                  DO jk = 1, fbdata1%nlev
+                     fbdata2%iobsk(jk,ij,jv)  = fbdata1%iobsk(jk,ji,jv)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+      ENDIF
+
+      ! Copy additional information
+      
+      DO je = 1, fbdata1%nadd
+         fbdata2%caddname(je) = fbdata1%caddname(je)
+      END DO
+      DO jv = 1, fbdata1%nvar
+         DO je = 1, fbdata1%nadd
+            fbdata2%caddlong(je,jv) = fbdata1%caddlong(je,jv)
+            fbdata2%caddunit(je,jv) = fbdata1%caddunit(je,jv)
+            ij = 0
+            DO ji = 1, fbdata1%nobs
+               IF ( llvalid(ji) ) THEN
+                  ij = ij + 1
+                  DO jk = 1, fbdata1%nlev
+                     fbdata2%padd(jk,ij,je,jv) = fbdata1%padd(jk,ji,je,jv)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+      END DO
+      
+      ! Copy extra information
+
+      DO je = 1, fbdata1%next
+         fbdata2%cextname(je) = fbdata1%cextname(je)
+         fbdata2%cextlong(je) = fbdata1%cextlong(je)
+         fbdata2%cextunit(je) = fbdata1%cextunit(je)
+      END DO
+      DO je = 1, fbdata1%next
+         ij = 0
+         DO ji = 1, fbdata1%nobs
+            IF ( llvalid(ji) ) THEN
+               ij = ij + 1
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%pext(jk,ij,je) = fbdata1%pext(jk,ji,je)
+               END DO
+            ENDIF
+         END DO
+      END DO
+
+   END SUBROUTINE subsamp_obfbdata
+
+   SUBROUTINE merge_obfbdata( nsets, fbdatain, fbdataout, iset, inum, iind )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE merge_obfbdata  ***
+      !!
+      !! ** Purpose :   Merge multiple obfbdata structures into an one.
+      !!
+      !! ** Method  :   The order of elements is based on the indices in
+      !!                iind.
+      !!                All input data are assumed to be consistent. This
+      !!                is assumed to be checked before calling this routine.
+      !!                Likewise output data is assume to be consistent as 
+      !!                well without error checking.
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN):: nsets      ! Number of input data sets 
+      TYPE(obfbdata), DIMENSION(nsets) :: fbdatain  ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdataout      ! Output obsfbdata structure
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & iset                 ! Set number for a given obs.
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & inum                 ! Number within set for an obs
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & iind                 ! Indices for copying.
+      !! * Local variables
+
+      INTEGER :: js
+      INTEGER :: jo
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+
+      ! Check allocation status of fbdatain 
+      
+      DO js = 1, nsets
+         IF ( .NOT. fbdatain(js)%lalloc ) THEN
+            CALL fatal_error( 'merge_obfbdata: input data not allocated', &
+               &              __LINE__ )
+         ENDIF
+      END DO
+
+      ! Check allocation status of fbdataout
+      
+      IF ( .NOT.fbdataout%lalloc ) THEN
+         CALL fatal_error( 'merge_obfbdata: output data not allocated', &
+            &              __LINE__ )
+      ENDIF
+
+      ! Merge various names
+
+      DO jv = 1, fbdatain(1)%nvar
+         fbdataout%cname(jv) = fbdatain(1)%cname(jv)
+         fbdataout%coblong(jv) = fbdatain(1)%coblong(jv)
+         fbdataout%cobunit(jv) = fbdatain(1)%cobunit(jv)
+         IF ( fbdatain(1)%lgrid ) THEN
+            fbdataout%cgrid(jv) = fbdatain(1)%cgrid(jv)
+         ENDIF
+      END DO
+      DO jv = 1, fbdatain(1)%nadd
+         fbdataout%caddname(jv) = fbdatain(1)%caddname(jv)
+      END DO
+      DO jv = 1, fbdatain(1)%nvar
+         DO je = 1, fbdatain(1)%nadd
+            fbdataout%caddlong(je,jv) = fbdatain(1)%caddlong(je,jv)
+            fbdataout%caddunit(je,jv) = fbdatain(1)%caddunit(je,jv)
+         END DO
+      END DO
+      DO jv = 1, fbdatain(1)%next
+         fbdataout%cextname(jv) = fbdatain(1)%cextname(jv)
+         fbdataout%cextlong(jv) = fbdatain(1)%cextlong(jv)
+         fbdataout%cextunit(jv) = fbdatain(1)%cextunit(jv)
+      END DO
+      fbdataout%cdjuldref = fbdatain(1)%cdjuldref
+
+      ! Loop over total views
+
+      DO jo = 1, fbdataout%nobs
+
+         js = iset(iind(jo))
+         ji = inum(iind(jo))
+
+         ! Merge the header data
+
+         fbdataout%cdwmo(jo)  = fbdatain(js)%cdwmo(ji)
+         fbdataout%cdtyp(jo)  = fbdatain(js)%cdtyp(ji)
+         fbdataout%ioqc(jo)   = fbdatain(js)%ioqc(ji)
+         fbdataout%ipqc(jo)   = fbdatain(js)%ipqc(ji)
+         fbdataout%itqc(jo)   = fbdatain(js)%itqc(ji)
+         fbdataout%plam(jo)   = fbdatain(js)%plam(ji)
+         fbdataout%pphi(jo)   = fbdatain(js)%pphi(ji)
+         fbdataout%ptim(jo)   = fbdatain(js)%ptim(ji)
+         fbdataout%kindex(jo) = fbdatain(js)%kindex(ji)
+         DO jq = 1, fbdatain(js)%nqcf
+            fbdataout%ioqcf(jq,jo)  = fbdatain(js)%ioqcf(jq,ji)
+            fbdataout%ipqcf(jq,jo)  = fbdatain(js)%ipqcf(jq,ji)
+            fbdataout%itqcf(jq,jo)  = fbdatain(js)%itqcf(jq,ji)
+         END DO
+         DO jk = 1, fbdatain(js)%nlev
+            fbdataout%pdep(jk,jo)  = fbdatain(js)%pdep(jk,ji)
+            fbdataout%idqc(jk,jo)  = fbdatain(js)%idqc(jk,ji)
+            DO jq = 1, fbdatain(js)%nqcf
+               fbdataout%idqcf(jq,jk,jo) = fbdatain(js)%idqcf(jq,jk,ji)
+            END DO
+         END DO
+
+         ! Merge the variable data
+
+         DO jv = 1, fbdatain(js)%nvar
+            fbdataout%ivqc(jo,jv)  = fbdatain(js)%ivqc(ji,jv)
+            DO jq = 1, fbdatain(js)%nqcf
+               fbdataout%ivqcf(jq,jo,jv) = fbdatain(js)%ivqcf(jq,ji,jv)
+            END DO
+            DO jk = 1, fbdatain(js)%nlev
+               fbdataout%ivlqc(jk,jo,jv)  = fbdatain(js)%ivlqc(jk,ji,jv)
+               fbdataout%pob(jk,jo,jv)    = fbdatain(js)%pob(jk,ji,jv)
+               DO jq = 1, fbdatain(js)%nqcf
+                  fbdataout%ivlqcf(jq,jk,jo,jv) = &
+                     &                     fbdatain(js)%ivlqcf(jq,jk,ji,jv)
+               END DO
+            END DO
+         END DO
+
+         ! Merge grid information
+         
+         IF ( fbdatain(js)%lgrid ) THEN
+            DO jv = 1, fbdatain(js)%nvar
+               fbdataout%cgrid(jv) = fbdatain(js)%cgrid(jv)
+               fbdataout%iproc(jo,jv) = fbdatain(js)%iproc(ji,jv)
+               fbdataout%iobsi(jo,jv) = fbdatain(js)%iobsi(ji,jv)
+               fbdataout%iobsj(jo,jv) = fbdatain(js)%iobsj(ji,jv)
+               DO jk = 1, fbdatain(js)%nlev
+                  fbdataout%iobsk(jk,jo,jv)  = fbdatain(js)%iobsk(jk,ji,jv)
+               END DO
+            END DO
+         ENDIF
+
+         ! Merge additional information
+      
+         DO jv = 1, fbdatain(js)%nvar
+            DO je = 1, fbdatain(js)%nadd
+               DO jk = 1, fbdatain(js)%nlev
+                  fbdataout%padd(jk,jo,je,jv) = fbdatain(js)%padd(jk,ji,je,jv)
+               END DO
+            END DO
+         END DO
+         
+         ! Merge extra information
+         
+         DO je = 1, fbdatain(js)%next
+            DO jk = 1, fbdatain(js)%nlev
+               fbdataout%pext(jk,jo,je) = fbdatain(js)%pext(jk,ji,je)
+            END DO
+         END DO
+
+      END DO
+
+   END SUBROUTINE merge_obfbdata
+
+   SUBROUTINE write_obfbdata( cdfilename, fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE write_obfbdata  ***
+      !!
+      !! ** Purpose :   Write an obfbdata structure into a netCDF file.
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      CHARACTER(len=*) :: cdfilename ! Output filename
+      TYPE(obfbdata)   :: fbdata     ! obsfbdata structure
+      !! * Local variables
+      CHARACTER(LEN=14), PARAMETER :: cpname = 'write_obfbdata'
+      ! Dimension ids
+      INTEGER :: idfile
+      INTEGER :: idodim
+      INTEGER :: idldim
+      INTEGER :: idvdim
+      INTEGER :: idadim
+      INTEGER :: idedim
+      INTEGER :: idsndim
+      INTEGER :: idsgdim
+      INTEGER :: idswdim
+      INTEGER :: idstdim
+      INTEGER :: idjddim
+      INTEGER :: idqcdim
+      INTEGER :: idvard
+      INTEGER :: idaddd
+      INTEGER :: idextd
+      INTEGER :: idcdwmo
+      INTEGER :: idcdtyp
+      INTEGER :: idplam
+      INTEGER :: idpphi
+      INTEGER :: idpdep
+      INTEGER :: idptim
+      INTEGER :: idptimr
+      INTEGER :: idioqc         
+      INTEGER :: idioqcf         
+      INTEGER :: idipqc
+      INTEGER :: idipqcf
+      INTEGER :: iditqc
+      INTEGER :: iditqcf
+      INTEGER :: ididqc
+      INTEGER :: ididqcf
+      INTEGER :: idkindex
+      INTEGER, DIMENSION(fbdata%nvar) :: &
+         & idpob,    &
+         & idivqc,   &
+         & idivqcf,  &
+         & idivlqc,  &
+         & idivlqcf, &
+         & idiobsi,  &
+         & idiobsj,  &
+         & idiobsk,  &
+         & idcgrid
+      INTEGER, DIMENSION(fbdata%nadd,fbdata%nvar) :: idpadd
+      INTEGER, DIMENSION(fbdata%next) :: idpext
+      INTEGER, DIMENSION(1) :: incdim1
+      INTEGER, DIMENSION(2) :: incdim2
+      INTEGER, DIMENSION(3) :: incdim3
+      INTEGER, DIMENSION(4) :: incdim4
+
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ioldfill
+      CHARACTER(len=nf90_max_name) :: &
+         & cdtmp
+      CHARACTER(len=16), PARAMETER :: &
+         & cdqcconv = 'q where q =[0,9]'
+      CHARACTER(len=24), PARAMETER :: &
+         & cdqcfconv = 'NEMOVAR flag conventions'
+      CHARACTER(len=ilenlong) :: &
+         & cdltmp
+
+      ! Open output filename
+
+      CALL chkerr( nf90_create( TRIM( cdfilename ), nf90_clobber, idfile ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_set_fill( idfile, nf90_nofill, ioldfill ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_put_att( idfile, nf90_global, 'title', &
+         &                       'NEMO observation operator output' ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_put_att( idfile, nf90_global, 'Convention', &
+         &                       'NEMO unified observation operator output' ),&
+         &         cpname,__LINE__ )
+
+      ! Create the dimensions
+
+      CALL chkerr( nf90_def_dim( idfile, 'N_OBS'  , fbdata%nobs, idodim ),  &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_LEVELS', fbdata%nlev, idldim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_VARS', fbdata%nvar, idvdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_QCF', fbdata%nqcf, idqcdim ),&
+         &         cpname,__LINE__ )
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'N_ENTRIES', fbdata%nadd, idadim ), &
+            &         cpname,__LINE__ )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'N_EXTRA', fbdata%next, idedim ), &
+            &         cpname,__LINE__ )
+      ENDIF
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGNAM', ilenname, idsndim ), &
+         &         cpname,__LINE__ )
+      IF (fbdata%lgrid) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'STRINGGRID', ilengrid, idsgdim ),&
+            &         cpname,__LINE__ )
+      ENDIF
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGWMO', ilenwmo, idswdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGTYP', ilentyp, idstdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGJULD', ilenjuld, idjddim ), &
+         &         cpname,__LINE__ )
+      
+      ! Define netCDF variables for header information
+      
+      incdim2(1) = idsndim
+      incdim2(2) = idvdim
+
+      CALL chkerr( nf90_def_var( idfile, 'VARIABLES', nf90_char, incdim2, &
+         &                       idvard ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata( idfile, idvard, &
+         &                     'List of variables in feedback files' )
+      
+      IF ( fbdata%nadd > 0 ) THEN
+         incdim2(1) = idsndim
+         incdim2(2) = idadim
+         CALL chkerr( nf90_def_var( idfile, 'ENTRIES', nf90_char, incdim2, &
+            &                       idaddd ), cpname, __LINE__ )
+         CALL putvaratt_obfbdata( idfile, idaddd,  &
+            &                     'List of additional entries for each '// &
+            &                     'variable in feedback files' )
+      ENDIF
+   
+      IF ( fbdata%next > 0 ) THEN
+         incdim2(1) = idsndim
+         incdim2(2) = idedim
+         CALL chkerr( nf90_def_var( idfile, 'EXTRA', nf90_char, incdim2, &
+            &                       idextd ), cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idextd, &
+            &                      'List of extra variables' )
+      ENDIF
+
+      incdim2(1) = idswdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'STATION_IDENTIFIER', &
+         &                       nf90_char, incdim2, &
+         &                       idcdwmo ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idcdwmo, &
+         &                      'Station identifier' )
+      incdim2(1) = idstdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'STATION_TYPE', &
+         &                       nf90_char, incdim2, &
+         &                       idcdtyp ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idcdtyp, &
+         &                      'Code instrument type' )
+      incdim1(1) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'LONGITUDE', &
+         &                       nf90_double, incdim1, &
+         &                       idplam ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idplam, &
+         &                      'Longitude', cdunits = 'degrees_east', &
+         &                      rfillvalue = fbrmdi )
+      CALL chkerr( nf90_def_var( idfile, 'LATITUDE', &
+         &                       nf90_double, incdim1, &
+         &                       idpphi ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idpphi, &
+         &                      'Latitude', cdunits = 'degrees_north', &
+         &                      rfillvalue = fbrmdi )
+      incdim2(1) = idldim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH', &
+         &                       nf90_double, incdim2, &
+         &                       idpdep ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idpdep, &
+         &                      'Depth', cdunits = 'metre', &
+         &                      rfillvalue = fbrmdi )
+      incdim3(1) = idqcdim
+      incdim3(2) = idldim
+      incdim3(3) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH_QC', &
+         &                       nf90_int, incdim2, &
+         &                       ididqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, ididqc, &
+         &                      'Quality on depth',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH_QC_FLAGS', &
+         &                       nf90_int, incdim3, &
+         &                       ididqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, ididqcf, &
+         &                      'Quality flags on depth',  &
+         &                      conventions = cdqcfconv )
+      CALL chkerr( nf90_def_var( idfile, 'JULD', &
+         &                       nf90_double, incdim1, &
+         &                       idptim ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idptim, &
+         &                      'Julian day', &
+         &                      cdunits = 'days since JULD_REFERENCE', &
+         &                      conventions = 'relative julian days with '// &
+         &                                 'decimal part (as parts of day)', &
+         &                      rfillvalue = fbrmdi )
+      incdim1(1) = idjddim
+      CALL chkerr( nf90_def_var( idfile, 'JULD_REFERENCE', &
+         &                       nf90_char, incdim1, &
+         &                       idptimr ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idptimr, &
+         &                      'Date of reference for julian days ', &
+         &                      conventions = 'YYYYMMDDHHMMSS' )
+      incdim1(1) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'OBSERVATION_QC', &
+         &                       nf90_int, incdim1, &
+         &                       idioqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idioqc, &
+         &                      'Quality on observation',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      incdim2(1) = idqcdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'OBSERVATION_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       idioqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idioqcf, &
+         &                      'Quality flags on observation',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'POSITION_QC', &
+         &                       nf90_int, incdim1, &
+         &                       idipqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idipqc, &
+         &                      'Quality on position (latitude and longitude)',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'POSITION_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       idipqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idipqcf, &
+         &                      'Quality flags on position',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'JULD_QC', &
+         &                       nf90_int, incdim1, &
+         &                       iditqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, iditqc, &
+         &                      'Quality on date and time',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'JULD_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       iditqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, iditqcf, &
+         &                      'Quality flags on date and time',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'ORIGINAL_FILE_INDEX', &
+         &                       nf90_int, incdim1, &
+         &                       idkindex ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idkindex, &
+         &                      'Index in original data file',  &
+         &                      ifillvalue = fbimdi )
+
+      ! Define netCDF variables for individual variables
+
+      DO jv = 1, fbdata%nvar
+
+         incdim1(1) = idodim
+         incdim2(1) = idldim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+            &                       incdim2, idpob(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idpob(jv), &
+            &                      fbdata%coblong(jv),  &
+            &                      cdunits =  fbdata%cobunit(jv), &
+            &                      rfillvalue = fbrmdi )
+
+         IF ( fbdata%nadd > 0 ) THEN
+            DO je = 1, fbdata%nadd
+               WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                  &                TRIM(fbdata%caddname(je))
+               CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+                  &                       incdim2, idpadd(je,jv) ), &
+                  &         cpname, __LINE__ )
+               CALL putvaratt_obfbdata(  idfile, idpadd(je,jv), &
+                  &                      fbdata%caddlong(je,jv), &
+                  &                      cdunits =  fbdata%caddunit(je,jv), &
+                  &                      rfillvalue = fbrmdi )
+            END DO
+         ENDIF
+
+         cdltmp = fbdata%coblong(jv)
+         IF (( cdltmp(1:1) >= 'A' ).AND.( cdltmp(1:1) <= 'Z' )) &
+            & cdltmp(1:1) = ACHAR(IACHAR(cdltmp(1:1)) + 32)
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim1, idivqc(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivqc(jv), &
+            &                      'Quality on '//cdltmp,  &
+            &                      conventions = cdqcconv, &
+            &                      ifillvalue = 0 )
+         incdim2(1) = idqcdim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC_FLAGS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim2, idivqcf(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivqcf(jv), &
+            &                      'Quality flags on '//cdltmp,  &
+            &                      conventions = cdqcfconv, &
+            &                      ifillvalue = 0 )
+         incdim2(1) = idldim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim2, idivlqc(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivlqc(jv), &
+            &                      'Quality for each level on '//cdltmp,  &
+            &                      conventions = cdqcconv, &
+            &                      ifillvalue = 0 )
+         incdim3(1) = idqcdim
+         incdim3(2) = idldim
+         incdim3(3) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC_FLAGS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim3, idivlqcf(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivlqcf(jv), &
+            &                      'Quality flags for each level on '//&
+            &                      cdltmp,  &
+            &                      conventions = cdqcfconv, &
+            &                      ifillvalue = 0 )
+
+         IF (fbdata%lgrid) THEN
+            incdim2(1) = idldim
+            incdim2(2) = idodim
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSI'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim1, idiobsi(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsi(jv), &
+               &                      'ORCA grid search I coordinate')
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSJ'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim1, idiobsj(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsj(jv), &
+               &                      'ORCA grid search J coordinate')
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSK'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim2, idiobsk(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsk(jv), &
+               &                      'ORCA grid search K coordinate')
+            incdim1(1) = idsgdim
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_GRID'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_char, incdim1, &
+               &                       idcgrid(jv) ), cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idcgrid(jv), &
+               &                      'ORCA grid search grid (T,U,V)')
+         ENDIF
+
+      END DO
+
+      IF ( fbdata%next > 0 ) THEN
+         DO je = 1, fbdata%next
+            incdim2(1) = idldim
+            incdim2(2) = idodim
+            WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+               &                       incdim2, idpext(je) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idpext(je), &
+               &                      fbdata%cextlong(je),  &
+               &                      cdunits =  fbdata%cextunit(je), &
+               &                      rfillvalue = fbrmdi )
+         END DO
+      ENDIF
+      
+      ! Stop definitions
+
+      CALL chkerr( nf90_enddef( idfile ), cpname, __LINE__ )
+      
+      ! Write the variables
+      
+      CALL chkerr( nf90_put_var( idfile, idvard, fbdata%cname ), &
+         &         cpname, __LINE__ )
+      
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_put_var( idfile, idaddd, fbdata%caddname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+      
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_put_var( idfile, idextd, fbdata%cextname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+
+      CALL chkerr( nf90_put_var( idfile, idptimr, fbdata%cdjuldref ), &
+         &         cpname, __LINE__ )
+
+      ! Only write the data if observation is available
+      
+      IF ( fbdata%nobs > 0 ) THEN
+
+         CALL chkerr( nf90_put_var( idfile, idcdwmo, fbdata%cdwmo ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idcdtyp, fbdata%cdtyp ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idplam, fbdata%plam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idpphi, fbdata%pphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idpdep, fbdata%pdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idptim, fbdata%ptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idioqc, fbdata%ioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idioqcf, fbdata%ioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idipqc, fbdata%ipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idipqcf, fbdata%ipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, iditqc, fbdata%itqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, iditqcf, fbdata%itqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, ididqc, fbdata%idqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, ididqcf, fbdata%idqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idkindex, fbdata%kindex ), &
+            &         cpname, __LINE__ )
+
+         DO jv = 1, fbdata%nvar
+            CALL chkerr( nf90_put_var( idfile, idpob(jv), fbdata%pob(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  CALL chkerr( nf90_put_var( idfile, idpadd(je,jv), &
+                     &                       fbdata%padd(:,:,je,jv) ), &
+                     &         cpname, __LINE__ )
+               END DO
+            ENDIF
+            CALL chkerr( nf90_put_var( idfile, idivqc(jv), &
+               &                       fbdata%ivqc(:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivqcf(jv), &
+               &                       fbdata%ivqcf(:,:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivlqc(jv), &
+               &                       fbdata%ivlqc(:,:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivlqcf(jv), &
+               &                       fbdata%ivlqcf(:,:,:,jv) ),&
+               &         cpname, __LINE__ )
+            IF (fbdata%lgrid) THEN
+               CALL chkerr( nf90_put_var( idfile, idiobsi(jv), &
+                  &                       fbdata%iobsi(:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idiobsj(jv), &
+                  &                       fbdata%iobsj(:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idiobsk(jv), &
+                  &                       fbdata%iobsk(:,:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idcgrid(jv), &
+                  &                       fbdata%cgrid(jv) ), &
+                  &         cpname, __LINE__ )
+            ENDIF
+         END DO
+
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               CALL chkerr( nf90_put_var( idfile, idpext(je), &
+                  &                       fbdata%pext(:,:,je) ), &
+                  &         cpname, __LINE__ )
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Close the file
+
+      CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+
+      
+   END SUBROUTINE write_obfbdata
+
+   SUBROUTINE putvaratt_obfbdata( idfile, idvar, cdlongname, cdunits, &
+      &                           conventions, cfillvalue, &
+      &                           ifillvalue, rfillvalue )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE putvaratt_obfbdata  ***
+      !!
+      !! ** Purpose :   Write netcdf attributes for variable
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER :: idfile                    ! File netcdf id.
+      INTEGER :: idvar                     ! Variable netcdf id.
+      CHARACTER(len=*) :: cdlongname       ! Long name for variable
+      CHARACTER(len=*), OPTIONAL :: cdunits       ! Units for variable
+      CHARACTER(len=*), OPTIONAL :: cfillvalue    ! Fill value for character variables
+      INTEGER, OPTIONAL :: ifillvalue             ! Fill value for integer variables
+      REAL(kind=fbsp), OPTIONAL :: rfillvalue     ! Fill value for real variables
+      CHARACTER(len=*), OPTIONAL :: conventions   ! Conventions for variable
+      !! * Local variables
+      CHARACTER(LEN=18), PARAMETER :: &
+         & cpname = 'putvaratt_obfbdata'
+
+      CALL chkerr( nf90_put_att( idfile, idvar, 'long_name', &
+         &                       TRIM(cdlongname) ), &
+         &                       cpname, __LINE__ )
+      
+      IF ( PRESENT(cdunits) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, 'units', &
+            &                       TRIM(cdunits) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(conventions) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, 'Conventions', &
+            &                       TRIM(conventions) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(cfillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       TRIM(cfillvalue) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(ifillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       ifillvalue ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(rfillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       rfillvalue ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+   END SUBROUTINE putvaratt_obfbdata
+
+   SUBROUTINE read_obfbdata( cdfilename, fbdata, ldgrid )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE read_obfbdata  ***
+      !!
+      !! ** Purpose :   Read an obfbdata structure from a netCDF file.
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      CHARACTER(len=*) :: cdfilename  ! Input filename
+      TYPE(obfbdata)   :: fbdata      ! obsfbdata structure
+      LOGICAL, OPTIONAL :: ldgrid     ! Allow forcing of grid info
+      !! * Local variables
+      CHARACTER(LEN=14), PARAMETER :: cpname = 'read_obfbdata'
+      INTEGER :: idfile
+      INTEGER :: idodim
+      INTEGER :: idldim
+      INTEGER :: idvdim
+      INTEGER :: idadim
+      INTEGER :: idedim
+      INTEGER :: idgdim
+      INTEGER :: idvard
+      INTEGER :: idaddd
+      INTEGER :: idextd
+      INTEGER :: idcdwmo
+      INTEGER :: idcdtyp
+      INTEGER :: idplam
+      INTEGER :: idpphi
+      INTEGER :: idpdep
+      INTEGER :: idptim
+      INTEGER :: idptimr
+      INTEGER :: idioqc        
+      INTEGER :: idioqcf
+      INTEGER :: idipqc
+      INTEGER :: idipqcf
+      INTEGER :: ididqc
+      INTEGER :: ididqcf
+      INTEGER :: iditqc
+      INTEGER :: iditqcf
+      INTEGER :: idkindex
+      INTEGER, DIMENSION(:), ALLOCATABLE :: &
+         & idpob,    &
+         & idivqc,   &
+         & idivqcf,  &
+         & idivlqc,  &
+         & idivlqcf, &
+         & idiobsi,  &
+         & idiobsj,  &
+         & idiobsk,  &
+         & idcgrid,  &
+         & idpext
+      INTEGER, DIMENSION(:,:), ALLOCATABLE :: &
+         & idpadd
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: nvar
+      INTEGER :: nobs
+      INTEGER :: nlev
+      INTEGER :: nadd
+      INTEGER :: next
+      LOGICAL :: lgrid
+      CHARACTER(len=NF90_MAX_NAME) :: cdtmp
+
+      ! Check allocation status and deallocate previous allocated structures
+
+      IF ( fbdata%lalloc ) THEN
+         CALL dealloc_obfbdata( fbdata )
+      ENDIF
+
+      ! Open input filename
+
+      CALL chkerr( nf90_open( TRIM( cdfilename ), nf90_nowrite, idfile ), &
+         &         cpname, __LINE__ )
+
+      ! Get input dimensions
+
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_OBS'  , idodim ),  &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idodim, len=nobs ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_LEVELS', idldim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idldim, len=nlev ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_VARS', idvdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idvdim, len=nvar ), &
+         &         cpname,__LINE__ )
+      IF ( nf90_inq_dimid( idfile, 'N_ENTRIES',  idadim ) == 0 ) THEN
+         CALL chkerr( nf90_inquire_dimension( idfile, idadim, len=nadd ), &
+            &         cpname,__LINE__ )
+      ELSE
+         nadd = 0
+      ENDIF
+      IF ( nf90_inq_dimid( idfile, 'N_EXTRA',  idedim ) == 0 ) THEN
+         CALL chkerr( nf90_inquire_dimension( idfile, idedim, len=next ), &
+            &         cpname,__LINE__ )
+      ELSE
+         next = 0
+      ENDIF
+      !
+      ! Check if this input file  contains grid search informations
+      !
+      lgrid = ( nf90_inq_dimid( idfile, 'STRINGGRID',  idgdim ) == 0 )
+
+      ! Allocate data structure
+
+      IF ( PRESENT(ldgrid) ) THEN
+         CALL alloc_obfbdata( fbdata, nvar, nobs, nlev, nadd, next, &
+            & lgrid.OR.ldgrid )
+      ELSE
+         CALL alloc_obfbdata( fbdata, nvar, nobs, nlev, nadd, next, &
+            & lgrid )
+      ENDIF
+
+      ! Allocate netcdf identifiers
+
+      ALLOCATE( &
+         & idpob(fbdata%nvar),    &
+         & idivqc(fbdata%nvar),   &
+         & idivqcf(fbdata%nvar),  &
+         & idivlqc(fbdata%nvar),  &
+         & idivlqcf(fbdata%nvar), &
+         & idiobsi(fbdata%nvar),  &
+         & idiobsj(fbdata%nvar),  &
+         & idiobsk(fbdata%nvar),  &
+         & idcgrid(fbdata%nvar)   &
+         & )
+      IF ( fbdata%nadd > 0 ) THEN
+         ALLOCATE( &
+            & idpadd(fbdata%nadd,fbdata%nvar) &
+            & )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         ALLOCATE( &
+            & idpext(fbdata%next) &
+            & )
+      ENDIF
+
+      ! Read variables for header information
+
+      CALL chkerr( nf90_inq_varid( idfile, 'VARIABLES',idvard ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_get_var( idfile, idvard, fbdata%cname ), &
+         &         cpname, __LINE__ )
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_inq_varid( idfile, 'ENTRIES', idaddd ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idaddd, fbdata%caddname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_inq_varid( idfile, 'EXTRA', idextd ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idextd, fbdata%cextname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+
+      CALL chkerr( nf90_inq_varid( idfile, 'JULD_REFERENCE', idptimr ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_get_var( idfile, idptimr, fbdata%cdjuldref ), &
+         &         cpname, __LINE__ )
+
+      IF  ( fbdata%nobs > 0 ) THEN
+         
+         CALL chkerr( nf90_inq_varid( idfile, 'STATION_IDENTIFIER', idcdwmo ),&
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idcdwmo, fbdata%cdwmo ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'STATION_TYPE', idcdtyp ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idcdtyp, fbdata%cdtyp), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'LONGITUDE', idplam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idplam, fbdata%plam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'LATITUDE', idpphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idpphi, fbdata%pphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH', idpdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idpdep, fbdata%pdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD', idptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idptim, fbdata%ptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'OBSERVATION_QC', idioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idioqc, fbdata%ioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'OBSERVATION_QC_FLAGS', idioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idioqcf, fbdata%ioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'POSITION_QC', idipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idipqc, fbdata%ipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'POSITION_QC_FLAGS', idipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idipqcf, fbdata%ipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH_QC', ididqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, ididqc, fbdata%idqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH_QC_FLAGS', ididqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, ididqcf, fbdata%idqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD_QC', iditqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, iditqc, fbdata%itqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD_QC_FLAGS', iditqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, iditqcf, fbdata%itqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'ORIGINAL_FILE_INDEX', idkindex ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idkindex, fbdata%kindex ), &
+            &         cpname, __LINE__ )
+         
+         ! Read netCDF variables for individual variables
+         
+         DO jv = 1, fbdata%nvar
+            
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpob(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idpob(jv), &
+               &                       fbdata%pob(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            CALL getvaratt_obfbdata( idfile, idpob(jv), &
+               &                     fbdata%coblong(jv), &
+               &                     fbdata%cobunit(jv) )
+            
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                     &                TRIM(fbdata%caddname(je))
+                  CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpadd(je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL chkerr( nf90_get_var( idfile, idpadd(je,jv), &
+                     &                       fbdata%padd(:,:,je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL getvaratt_obfbdata( idfile, idpadd(je,jv), &
+                     &                     fbdata%caddlong(je,jv), &
+                     &                     fbdata%caddunit(je,jv) )
+               END DO
+            ENDIF
+            
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivqc(jv) ), &
+            &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivqc(jv), &
+               &                       fbdata%ivqc(:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC_FLAGS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivqcf(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivqcf(jv), &
+               &                       fbdata%ivqcf(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivlqc(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivlqc(jv), &
+               &                       fbdata%ivlqc(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC_FLAGS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivlqcf(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivlqcf(jv), &
+               &                       fbdata%ivlqcf(:,:,:,jv) ), &
+               &         cpname, __LINE__ )
+            IF ( lgrid ) THEN
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSI'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsi(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsi(jv), &
+                  &                       fbdata%iobsi(:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSJ'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsj(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsj(jv), &
+                  &                       fbdata%iobsj(:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSK'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsk(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsk(jv), &
+                  &                       fbdata%iobsk(:,:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_GRID'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idcgrid(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idcgrid(jv), &
+                  &                       fbdata%cgrid(jv) ), &
+                  &         cpname, __LINE__ )
+            ENDIF
+            
+         END DO
+         
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpext(je) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idpext(je), &
+                  &                       fbdata%pext(:,:,je) ), &
+                  &         cpname, __LINE__ )
+               CALL getvaratt_obfbdata( idfile, idpext(je), &
+                  &                     fbdata%cextlong(je), &
+                  &                     fbdata%cextunit(je) )
+            END DO
+         ENDIF
+
+      ELSE ! if no observations only get attributes
+
+         DO jv = 1, fbdata%nvar            
+
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpob(jv) ), &
+               &         cpname, __LINE__ )
+            CALL getvaratt_obfbdata( idfile, idpob(jv), &
+               &                     fbdata%coblong(jv), &
+               &                     fbdata%cobunit(jv) )
+            
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                     &                TRIM(fbdata%caddname(je))
+                  CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpadd(je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL getvaratt_obfbdata( idfile, idpadd(je,jv), &
+                     &                     fbdata%caddlong(je,jv), &
+                     &                     fbdata%caddunit(je,jv) )
+               END DO
+            ENDIF
+            
+         END DO
+         
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpext(je) ), &
+                  &         cpname, __LINE__ )
+               CALL getvaratt_obfbdata( idfile, idpext(je), &
+                  &                     fbdata%cextlong(je), &
+                  &                     fbdata%cextunit(je) )
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Close the file
+
+      CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+
+   END SUBROUTINE read_obfbdata
+
+   SUBROUTINE getvaratt_obfbdata( idfile, idvar, cdlongname, cdunits )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE putvaratt_obfbdata  ***
+      !!
+      !! ** Purpose :   Read netcdf attributes for variable
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER :: idfile      ! File netcdf id.
+      INTEGER :: idvar       ! Variable netcdf id.
+      CHARACTER(len=*) :: cdlongname  ! Long name for variable
+      CHARACTER(len=*) :: cdunits     ! Units for variable
+      !! * Local variables
+      CHARACTER(LEN=18), PARAMETER :: cpname = 'getvaratt_obfbdata'
+
+      CALL chkerr( nf90_get_att( idfile, idvar, 'long_name', &
+         &                       cdlongname ), &
+         &                       cpname, __LINE__ )
+
+      CALL chkerr( nf90_get_att( idfile, idvar, 'units', &
+         &                       cdunits ), &
+         &                       cpname, __LINE__ )
+
+   END SUBROUTINE getvaratt_obfbdata
+
+END MODULE obs_fbm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grd_bruteforce.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grd_bruteforce.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grd_bruteforce.h90	(revision 14097)
@@ -0,0 +1,349 @@
+   SUBROUTINE obs_grd_bruteforce( kpi, kpj, kpiglo, kpjglo,       &
+      &                            kldi, klei, kldj, klej,         &
+      &                            kmyproc, ktotproc,              &
+      &                            pglam, pgphi, pmask,            &
+      &                            kobs, plam, pphi, kobsi, kobsj, &
+      &                                   kproc)
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE obs_grd_bruteforce ***
+      !!
+      !! ** Purpose : Search gridpoints to find the grid box containing
+      !!              the observations
+      !!
+      !! ** Method  : Call to linquad
+      !!
+      !! ** Action  : Return kproc holding the observation and kiobsi,kobsj
+      !!              valid on kproc=kmyproc processor only.
+      !!   
+      !! History :
+      !!        !  2001-11  (N. Daget, A. Weaver)
+      !!        !  2006-03  (A. Weaver) NEMOVAR migration.
+      !!        !  2006-05  (K. Mogensen) Moved to to separate routine.
+      !!        !  2007-10  (A. Vidard) Bug fix in wrap around checks; cleanup
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kpi                ! Number of local longitudes
+      INTEGER, INTENT(IN) :: kpj                ! Number of local latitudes
+      INTEGER, INTENT(IN) :: kpiglo             ! Number of global longitudes
+      INTEGER, INTENT(IN) :: kpjglo             ! Number of global latitudes
+      INTEGER, INTENT(IN) :: kldi               ! Start of inner domain in i
+      INTEGER, INTENT(IN) :: klei               ! End of inner domain in i
+      INTEGER, INTENT(IN) :: kldj               ! Start of inner domain in j
+      INTEGER, INTENT(IN) :: klej               ! End of inner domain in j
+      INTEGER, INTENT(IN) :: kmyproc            ! Processor number for MPP
+      INTEGER, INTENT(IN) :: ktotproc           ! Total number of processors
+      REAL(KIND=wp), DIMENSION(kpi,kpj), INTENT(IN) :: &
+         & pglam,   &               ! Grid point longitude
+         & pgphi,   &               ! Grid point latitude
+         & pmask                    ! Grid point mask
+      INTEGER,INTENT(IN) :: kobs                ! Size of the observation arrays
+      REAL(KIND=wp), DIMENSION(kobs), INTENT(IN) :: &
+         & plam, &                  ! Longitude of obsrvations 
+         & pphi                     ! Latitude of observations
+      INTEGER, DIMENSION(kobs), INTENT(OUT) :: &
+         & kobsi, &                 ! I-index of observations 
+         & kobsj, &                 ! J-index of observations 
+         & kproc                    ! Processor number of observations
+  
+      !! * Local declarations
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zplam, zpphi
+      REAL(wp) :: zlammax
+      REAL(wp) :: zlam
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: jo
+      INTEGER :: jlon
+      INTEGER :: jlat
+      INTEGER :: joffset
+      INTEGER :: jostride
+      REAL(KIND=wp), DIMENSION(:,:), ALLOCATABLE :: &
+         & zlamg, &
+         & zphig, &
+         & zmskg, &
+         & zphitmax,&
+         & zphitmin,&
+         & zlamtmax,&
+         & zlamtmin
+      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: &
+         & llinvalidcell
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zlamtm,  &
+         & zphitm
+
+      !-----------------------------------------------------------------------
+      ! Define grid setup for grid search
+      !-----------------------------------------------------------------------
+      IF (ln_grid_global) THEN
+         jlon     = kpiglo
+         jlat     = kpjglo
+         joffset  = kmyproc
+         jostride = ktotproc
+      ELSE
+         jlon     = kpi
+         jlat     = kpj
+         joffset  = 0
+         jostride = 1
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Set up data for grid search
+      !-----------------------------------------------------------------------
+      ALLOCATE( &
+         & zlamg(jlon,jlat),             &
+         & zphig(jlon,jlat),             &
+         & zmskg(jlon,jlat),             &
+         & zphitmax(jlon-1,jlat-1),      &
+         & zphitmin(jlon-1,jlat-1),      &
+         & zlamtmax(jlon-1,jlat-1),      &
+         & zlamtmin(jlon-1,jlat-1),      &
+         & llinvalidcell(jlon-1,jlat-1), &
+         & zlamtm(4,jlon-1,jlat-1),      &
+         & zphitm(4,jlon-1,jlat-1)       &
+         & )
+      !-----------------------------------------------------------------------
+      ! Copy data to local arrays
+      !-----------------------------------------------------------------------
+      IF (ln_grid_global) THEN
+         zlamg(:,:) = -1.e+10
+         zphig(:,:) = -1.e+10
+         zmskg(:,:) = -1.e+10
+         DO jj = kldj, klej
+            DO ji = kldi, klei
+               zlamg(mig(ji),mjg(jj)) = pglam(ji,jj)
+               zphig(mig(ji),mjg(jj)) = pgphi(ji,jj)
+               zmskg(mig(ji),mjg(jj)) = pmask(ji,jj)
+            END DO
+         END DO
+         CALL mpp_global_max( zlamg )
+         CALL mpp_global_max( zphig )
+         CALL mpp_global_max( zmskg )
+      ELSE
+         DO jj = 1, jlat
+            DO ji = 1, jlon
+               zlamg(ji,jj) = pglam(ji,jj)
+               zphig(ji,jj) = pgphi(ji,jj)
+               zmskg(ji,jj) = pmask(ji,jj)
+            END DO
+         END DO
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Copy longitudes and latitudes
+      !-----------------------------------------------------------------------
+      ALLOCATE( &
+         & zplam(kobs), &
+         & zpphi(kobs)  &
+         & )
+      DO jo = 1, kobs
+         zplam(jo) = plam(jo)
+         zpphi(jo) = pphi(jo)
+      END DO
+      !-----------------------------------------------------------------------
+      ! Set default values for output
+      !-----------------------------------------------------------------------
+      kproc(:) = -1
+      kobsi(:) = -1
+      kobsj(:) = -1
+      !-----------------------------------------------------------------------
+      ! Copy grid positions to temporary arrays and renormalize to 0 to 360.
+      !-----------------------------------------------------------------------
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            zlamtm(1,ji,jj) = zlamg(ji  ,jj  )
+            zphitm(1,ji,jj) = zphig(ji  ,jj  )
+            zlamtm(2,ji,jj) = zlamg(ji+1,jj  )
+            zphitm(2,ji,jj) = zphig(ji+1,jj  )
+            zlamtm(3,ji,jj) = zlamg(ji+1,jj+1)
+            zphitm(3,ji,jj) = zphig(ji+1,jj+1)
+            zlamtm(4,ji,jj) = zlamg(ji  ,jj+1)
+            zphitm(4,ji,jj) = zphig(ji  ,jj+1)
+         END DO
+      END DO
+      WHERE ( zlamtm(:,:,:) < 0.0_wp )
+         zlamtm(:,:,:) = zlamtm(:,:,:) + 360.0_wp
+      END WHERE
+      WHERE ( zlamtm(:,:,:) > 360.0_wp )
+         zlamtm(:,:,:) = zlamtm(:,:,:) - 360.0_wp
+      END WHERE
+      !-----------------------------------------------------------------------
+      ! Handle case of the wraparound; beware, not working with orca180
+      !-----------------------------------------------------------------------
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            zlammax = MAXVAL( zlamtm(:,ji,jj) )
+            WHERE (zlammax - zlamtm(:, ji, jj) > 180 ) &
+               & zlamtm(:,ji,jj) = zlamtm(:,ji,jj) + 360._wp
+            zphitmax(ji,jj) = MAXVAL(zphitm(:,ji,jj))
+            zphitmin(ji,jj) = MINVAL(zphitm(:,ji,jj))
+            zlamtmax(ji,jj) = MAXVAL(zlamtm(:,ji,jj))
+            zlamtmin(ji,jj) = MINVAL(zlamtm(:,ji,jj))
+         END DO
+      END DO
+      !-----------------------------------------------------------------------
+      ! Search for boxes with only land points mark them invalid
+      !-----------------------------------------------------------------------
+      llinvalidcell(:,:) = .FALSE.
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            llinvalidcell(ji,jj) =               &
+               & zmskg(ji  ,jj  ) == 0.0_wp .AND. &
+               & zmskg(ji+1,jj  ) == 0.0_wp .AND. &
+               & zmskg(ji+1,jj+1) == 0.0_wp .AND. &
+               & zmskg(ji  ,jj+1) == 0.0_wp
+         END DO
+      END DO
+
+      !------------------------------------------------------------------------
+      ! Master loop for grid search
+      !------------------------------------------------------------------------
+
+      DO jo = 1+joffset, kobs, jostride
+
+         !---------------------------------------------------------------------
+         ! Ensure that all observation longtiudes are between 0 and 360
+         !---------------------------------------------------------------------
+
+         IF ( zplam(jo) <   0.0_wp ) zplam(jo) = zplam(jo) + 360.0_wp
+         IF ( zplam(jo) > 360.0_wp ) zplam(jo) = zplam(jo) - 360.0_wp
+
+         !---------------------------------------------------------------------
+         ! Find observations which are on within 1e-6 of a grid point
+         !---------------------------------------------------------------------
+
+         gridloop: DO jj = 1, jlat-1
+            DO ji = 1, jlon-1
+               IF ( ABS( zphig(ji,jj) - zpphi(jo) ) < 1e-6 )  THEN
+                  zlam = zlamg(ji,jj)
+                  IF ( zlam <   0.0_wp ) zlam = zlam + 360.0_wp
+                  IF ( zlam > 360.0_wp ) zlam = zlam - 360.0_wp
+                  IF ( ABS( zlam - zplam(jo) ) < 1e-6 ) THEN
+                     IF ( llinvalidcell(ji,jj) ) THEN
+                        kproc(jo) = kmyproc + 1000000
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        CYCLE
+                     ELSE
+                        kproc(jo) = kmyproc
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        EXIT gridloop
+                     ENDIF
+                  ENDIF
+               ENDIF
+            END DO
+         END DO gridloop
+         
+         !---------------------------------------------------------------------
+         ! Ensure that all observation longtiudes are between -180 and 180
+         !---------------------------------------------------------------------
+
+         IF ( zplam(jo) > 180 ) zplam(jo) = zplam(jo) - 360.0_wp
+
+         !---------------------------------------------------------------------
+         ! Do coordinate search using brute force.
+         ! - For land points kproc is set to number of the processor + 1000000
+         !   and we continue the search.
+         ! - For ocean points kproc is set to the number of the processor 
+         !   and we stop the search.
+         !---------------------------------------------------------------------
+
+         IF ( kproc(jo) == -1 ) THEN
+
+            ! Normal case
+            gridpoints : DO jj = 1, jlat-1
+               DO ji = 1, jlon-1
+                  
+                  IF ( ( zplam(jo) > zlamtmax(ji,jj) ) .OR. &
+                     & ( zplam(jo) < zlamtmin(ji,jj) ) ) CYCLE
+                  
+                  IF ( ABS( zpphi(jo) ) < 85 ) THEN
+                     IF ( ( zpphi(jo) > zphitmax(ji,jj) ) .OR. &
+                        & ( zpphi(jo) < zphitmin(ji,jj) ) ) CYCLE
+                  ENDIF
+                  
+                  IF ( linquad( zplam(jo), zpphi(jo), &
+                     &          zlamtm(:,ji,jj), zphitm(:,ji,jj) ) ) THEN
+                     IF ( llinvalidcell(ji,jj) ) THEN
+                        kproc(jo) = kmyproc + 1000000
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        CYCLE
+                     ELSE
+                        kproc(jo) = kmyproc
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        EXIT gridpoints
+                     ENDIF
+                  ENDIF
+                  
+               END DO
+            END DO gridpoints
+
+         ENDIF
+
+         ! In case of failure retry for obs. longtiude + 360.
+         IF ( kproc(jo) == -1 ) THEN
+            gridpoints_greenwich : DO jj = 1, jlat-1
+               DO ji = 1, jlon-1
+
+                  IF ( ( zplam(jo)+360.0_wp > zlamtmax(ji,jj) ) .OR. &
+                     & ( zplam(jo)+360.0_wp < zlamtmin(ji,jj) ) ) CYCLE
+
+                  IF ( ABS( zpphi(jo) ) < 85 ) THEN
+                     IF ( ( zpphi(jo) > zphitmax(ji,jj) ) .OR. &
+                        & ( zpphi(jo) < zphitmin(ji,jj) ) ) CYCLE
+                  ENDIF
+
+                  IF ( linquad( zplam(jo)+360.0_wp, zpphi(jo), &
+                     &          zlamtm(:,ji,jj), zphitm(:,ji,jj) ) ) THEN
+                     IF ( llinvalidcell(ji,jj) ) THEN
+                        kproc(jo) = kmyproc + 1000000
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        CYCLE
+                     ELSE
+                        kproc(jo) = kmyproc
+                        kobsi(jo) = ji + 1
+                        kobsj(jo) = jj + 1
+                        EXIT gridpoints_greenwich
+                     ENDIF
+                  ENDIF
+
+               END DO
+            END DO gridpoints_greenwich
+
+         ENDIF
+      END DO
+
+      !----------------------------------------------------------------------
+      ! Synchronize kproc on all processors
+      !----------------------------------------------------------------------
+      IF ( ln_grid_global ) THEN
+         CALL obs_mpp_max_integer( kproc, kobs )
+         CALL obs_mpp_max_integer( kobsi, kobs )
+         CALL obs_mpp_max_integer( kobsj, kobs )
+      ELSE
+         CALL obs_mpp_find_obs_proc( kproc, kobs )
+      ENDIF
+
+      WHERE( kproc(:) >= 1000000 )
+         kproc(:) = kproc(:) - 1000000
+      END WHERE
+
+      DEALLOCATE( &
+         & zlamg,         &
+         & zphig,         &
+         & zmskg,         &
+         & zphitmax,      &
+         & zphitmin,      &
+         & zlamtmax,      &
+         & zlamtmin,      &
+         & llinvalidcell, &
+         & zlamtm,        &
+         & zphitm,        &
+         & zplam,         &
+         & zpphi          &
+         & )
+
+   END SUBROUTINE obs_grd_bruteforce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grid.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grid.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_grid.F90	(revision 14097)
@@ -0,0 +1,1182 @@
+MODULE obs_grid
+   !!======================================================================
+   !!                       ***  MODULE  obs_grid  ***
+   !! Observation diagnostics: Various tools for grid searching etc.
+   !!======================================================================
+   !!----------------------------------------------------------------------
+   !!   obs_grid_search   : Find i,j on the ORCA grid from lat,lon
+   !!   obs_level_search  : Find level from depth
+   !!   obs_zlevel_search : Find depth level from observed depth
+   !!   obs_tlevel_search : Find temperature level from observed temp
+   !!   obs_rlevel_search : Find density level from observed density
+   !!----------------------------------------------------------------------
+   !! * Modules used   
+   USE par_kind, ONLY : &          ! Precision variables
+      & wp 
+   USE par_oce, ONLY :  &          ! Ocean parameters
+      & jpk,     &
+      & jpni,    &
+      & jpnj,    &
+      & jpnij
+   USE dom_oce                     ! Ocean space and time domain variables
+   USE obs_mpp, ONLY : &           ! MPP support routines for observation diagnostics
+      & obs_mpp_find_obs_proc, &
+      & mpp_global_max,        &
+      & obs_mpp_max_integer
+   USE phycst, ONLY : &            ! Physical constants
+      & rad
+   USE obs_utils, ONLY : &         ! Observation operator utility functions
+      & grt_cir_dis, &
+      & chkerr
+   USE in_out_manager              ! Printing support
+   USE netcdf
+   USE obs_const, ONLY :      &
+      & obfillflt                  ! Fillvalue   
+   USE lib_mpp, ONLY :   &
+      & ctl_warn, ctl_stop
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PUBLIC  obs_grid_setup,      & ! Setup grid searching
+      &    obs_grid_search,     & ! Find i, j on the ORCA grid from lat, lon
+      &    obs_grid_deallocate, & ! Deallocate the look up table
+      &    obs_level_search       ! Find level from depth
+
+   PRIVATE linquad,                    & ! Determine whether a point lies within a cell
+      &    maxdist,                    & ! Find the maximum distance between 2 pts in a cell
+      &    obs_grd_bruteforce, & ! Find i, j on the ORCA grid from lat, lon
+      &    obs_grd_lookup        ! Find i, j on the ORCA grid from lat, lon quicker
+
+   !!* Module variables
+
+   !! Default values
+   REAL, PUBLIC :: rn_gridsearchres = 0.5   ! Resolution of grid
+   INTEGER, PRIVATE :: gsearch_nlons_def    ! Num of longitudes
+   INTEGER, PRIVATE :: gsearch_nlats_def    ! Num of latitudes
+   REAL(wp), PRIVATE :: gsearch_lonmin_def  ! Min longitude
+   REAL(wp), PRIVATE :: gsearch_latmin_def  ! Min latitude
+   REAL(wp), PRIVATE :: gsearch_dlon_def    ! Lon spacing
+   REAL(wp), PRIVATE :: gsearch_dlat_def    ! Lat spacing
+   !! Variable versions
+   INTEGER, PRIVATE :: nlons     ! Num of longitudes
+   INTEGER, PRIVATE :: nlats     ! Num of latitudes
+   REAL(wp), PRIVATE :: lonmin ! Min longitude
+   REAL(wp), PRIVATE :: latmin ! Min latitude
+   REAL(wp), PRIVATE :: dlon     ! Lon spacing
+   REAL(wp), PRIVATE :: dlat     ! Lat spacing
+   
+   INTEGER, PRIVATE :: maxxdiff, maxydiff ! Max diffs between model points
+   INTEGER, PRIVATE :: limxdiff, limydiff
+   
+   ! Data storage
+   REAL(wp), PRIVATE, DIMENSION(:,:), ALLOCATABLE :: &
+      & lons,  &
+      & lats
+   INTEGER, PRIVATE, DIMENSION(:,:), ALLOCATABLE :: &
+      & ixpos, &
+      & iypos, &
+      & iprocn    
+
+   ! Switches
+   LOGICAL, PUBLIC :: ln_grid_search_lookup  ! Use lookup table to speed up grid search
+   LOGICAL, PUBLIC :: ln_grid_global         ! Use global distribution of observations
+   CHARACTER(LEN=44), PUBLIC :: &
+      & cn_gridsearchfile    ! file name head for grid search lookup 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_grid_search( kobsin, plam, pphi, kobsi, kobsj, kproc, &
+      &                        cdgrid )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE obs_grid_search ***
+      !!
+      !! ** Purpose : Search local gridpoints to find the grid box containing
+      !!              the observations calls either
+      !!              obs_grd_bruteforce - the original brute force search
+      !!                     or
+      !!              obs_grd_lookup - uses a lookup table to do a fast 
+      !!search
+      !!History :
+      !!        !  2007-12  (D. Lea) 
+      !!------------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER :: &
+         & kobsin                     ! Size of the observation arrays
+      REAL(KIND=wp), DIMENSION(kobsin), INTENT(IN) :: &
+         & plam, &                  ! Longitude of obsrvations 
+         & pphi                     ! Latitude of observations
+      INTEGER, DIMENSION(kobsin), INTENT(OUT) :: &
+         & kobsi, &                 ! I-index of observations 
+         & kobsj, &                 ! J-index of observations 
+         & kproc                    ! Processor number of observations
+      CHARACTER(LEN=1) :: &
+         & cdgrid                   ! Grid to search
+
+      IF(kobsin > 0) THEN
+
+         IF ( ln_grid_search_lookup .AND. ( cdgrid == 'T' ) ) THEN
+            CALL obs_grd_lookup( kobsin, plam, pphi, &
+               &                         kobsi, kobsj, kproc )
+         ELSE
+            IF ( cdgrid == 'T' ) THEN
+               CALL obs_grd_bruteforce( jpi, jpj, jpiglo, jpjglo, &
+                  &                             1, nlci, 1, nlcj,         &
+                  &                             nproc, jpnij,             &
+                  &                             glamt, gphit, tmask,      &
+                  &                             kobsin, plam, pphi,       &
+                  &                             kobsi, kobsj, kproc )
+            ELSEIF ( cdgrid == 'U' ) THEN
+               CALL obs_grd_bruteforce( jpi, jpj, jpiglo, jpjglo, &
+                  &                             1, nlci, 1, nlcj,         &
+                  &                             nproc, jpnij,             &
+                  &                             glamu, gphiu, umask,      &
+                  &                             kobsin, plam, pphi,       &
+                  &                             kobsi, kobsj, kproc )
+            ELSEIF ( cdgrid == 'V' ) THEN
+               CALL obs_grd_bruteforce( jpi, jpj, jpiglo, jpjglo, &
+                  &                             1, nlci, 1, nlcj,         &
+                  &                             nproc, jpnij,             &
+                  &                             glamv, gphiv, vmask,      &
+                  &                             kobsin, plam, pphi,       &
+                  &                             kobsi, kobsj, kproc )
+            ELSEIF ( cdgrid == 'F' ) THEN
+               CALL obs_grd_bruteforce( jpi, jpj, jpiglo, jpjglo, &
+                  &                             1, nlci, 1, nlcj,         &
+                  &                             nproc, jpnij,             &
+                  &                             glamf, gphif, fmask,      &
+                  &                             kobsin, plam, pphi,       &
+                  &                             kobsi, kobsj, kproc )
+            ELSE
+               CALL ctl_stop( 'Grid not supported' )
+            ENDIF
+         ENDIF
+         
+      ENDIF
+
+   END SUBROUTINE obs_grid_search
+
+#include "obs_grd_bruteforce.h90"
+   
+   SUBROUTINE obs_grd_lookup( kobs, plam, pphi, kobsi, kobsj, kproc )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE obs_grid_lookup ***
+      !!
+      !! ** Purpose : Search local gridpoints to find the grid box containing
+      !!              the observations (much faster then obs_grd_bruteforce)
+      !!
+      !! ** Method  : Call to linquad
+      !!
+      !! ** Action  : Return kproc holding the observation and kiobsi,kobsj
+      !!              valid on kproc=nproc processor only.
+      !!   
+      !! History :
+      !!        !  2007-12 (D. Lea) new routine based on obs_grid_search
+      !!! updated with fixes from new version of obs_grid_search_bruteforce
+      !!! speeded up where points are not near a "difficult" region like an edge
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER :: kobs                     ! Size of the observation arrays
+      REAL(KIND=wp), DIMENSION(kobs), INTENT(IN) :: &
+         & plam, &                  ! Longitude of obsrvations 
+         & pphi                     ! Latitude of observations
+      INTEGER, DIMENSION(kobs), INTENT(OUT) :: &
+         & kobsi, &                 ! I-index of observations 
+         & kobsj, &                 ! J-index of observations 
+         & kproc                    ! Processor number of observations
+  
+      !! * Local declarations
+      REAL(KIND=wp), DIMENSION(:), ALLOCATABLE :: &
+         & zplam
+      REAL(wp) :: zlammax
+      REAL(wp) :: zlam
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: jo
+      INTEGER :: isx
+      INTEGER :: isy
+      INTEGER :: jimin
+      INTEGER :: jimax
+      INTEGER :: jjmin
+      INTEGER :: jjmax
+      INTEGER :: jojimin
+      INTEGER :: jojimax
+      INTEGER :: jojjmin
+      INTEGER :: jojjmax
+      INTEGER :: ipx1
+      INTEGER :: ipy1
+      INTEGER :: ip
+      INTEGER :: jp
+      INTEGER :: ipx
+      INTEGER :: ipy
+      INTEGER :: ipmx
+      INTEGER :: jlon
+      INTEGER :: jlat
+      INTEGER :: joffset
+      INTEGER :: jostride
+      REAL(KIND=wp), DIMENSION(:,:), ALLOCATABLE :: &
+         & zlamg, &
+         & zphig, &
+         & zmskg, &
+         & zphitmax,&
+         & zphitmin,&
+         & zlamtmax,&
+         & zlamtmin
+      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: &
+         & llinvalidcell
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zlamtm,  &
+         & zphitm
+      LOGICAL :: llfourflag
+      INTEGER :: ifourflagcountt
+      INTEGER :: ifourflagcountf
+      INTEGER, DIMENSION(5) :: ifourflagcountr
+
+      !-----------------------------------------------------------------------
+      ! Define grid for grid search
+      !-----------------------------------------------------------------------
+      IF (ln_grid_global) THEN
+         jlon     = jpiglo
+         jlat     = jpjglo
+         joffset  = nproc
+         jostride = jpnij
+      ELSE
+         jlon     = jpi
+         jlat     = jpj
+         joffset  = 0
+         jostride = 1
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Set up data for grid search
+      !-----------------------------------------------------------------------
+      ALLOCATE( &
+         & zlamg(jlon,jlat),             &
+         & zphig(jlon,jlat),             &
+         & zmskg(jlon,jlat),             &
+         & zphitmax(jlon-1,jlat-1),      &
+         & zphitmin(jlon-1,jlat-1),      &
+         & zlamtmax(jlon-1,jlat-1),      &
+         & zlamtmin(jlon-1,jlat-1),      &
+         & llinvalidcell(jlon-1,jlat-1), &
+         & zlamtm(4,jlon-1,jlat-1),      &
+         & zphitm(4,jlon-1,jlat-1)       &
+         & )
+      !-----------------------------------------------------------------------
+      ! Copy data to local arrays
+      !-----------------------------------------------------------------------
+      IF (ln_grid_global) THEN
+         zlamg(:,:) = -1.e+10
+         zphig(:,:) = -1.e+10
+         zmskg(:,:) = -1.e+10
+         ! Add various grids here.
+         DO jj = 1, nlcj
+            DO ji = 1, nlci
+               zlamg(mig(ji),mjg(jj)) = glamt(ji,jj)
+               zphig(mig(ji),mjg(jj)) = gphit(ji,jj)
+               zmskg(mig(ji),mjg(jj)) = tmask(ji,jj,1)
+            END DO
+         END DO
+         CALL mpp_global_max( zlamg )
+         CALL mpp_global_max( zphig )
+         CALL mpp_global_max( zmskg )
+      ELSE
+         ! Add various grids here.
+         DO jj = 1, jlat
+            DO ji = 1, jlon
+               zlamg(ji,jj) = glamt(ji,jj)
+               zphig(ji,jj) = gphit(ji,jj)
+               zmskg(ji,jj) = tmask(ji,jj,1)
+            END DO
+         END DO
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Copy longitudes
+      !----------------------------------------------------------------------- 
+      ALLOCATE( &
+         & zplam(kobs) &
+         & )
+      DO jo = 1, kobs
+         zplam(jo) = plam(jo)
+      END DO
+      !-----------------------------------------------------------------------
+      ! Set default values for output
+      !-----------------------------------------------------------------------
+      kproc(:) = -1
+      kobsi(:) = -1
+      kobsj(:) = -1
+      !-----------------------------------------------------------------------
+      ! Copy grid positions to temporary arrays and renormalize to 0 to 360.
+      !-----------------------------------------------------------------------
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            zlamtm(1,ji,jj) = zlamg(ji  ,jj  )
+            zphitm(1,ji,jj) = zphig(ji  ,jj  )
+            zlamtm(2,ji,jj) = zlamg(ji+1,jj  )
+            zphitm(2,ji,jj) = zphig(ji+1,jj  )
+            zlamtm(3,ji,jj) = zlamg(ji+1,jj+1)
+            zphitm(3,ji,jj) = zphig(ji+1,jj+1)
+            zlamtm(4,ji,jj) = zlamg(ji  ,jj+1)
+            zphitm(4,ji,jj) = zphig(ji  ,jj+1)
+         END DO
+      END DO
+      WHERE ( zlamtm(:,:,:) < 0.0_wp )
+         zlamtm(:,:,:) = zlamtm(:,:,:) + 360.0_wp
+      END WHERE
+      WHERE ( zlamtm(:,:,:) > 360.0_wp )
+         zlamtm(:,:,:) = zlamtm(:,:,:) - 360.0_wp
+      END WHERE
+      !-----------------------------------------------------------------------
+      ! Handle case of the wraparound; beware, not working with orca180
+      !-----------------------------------------------------------------------
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            zlammax = MAXVAL( zlamtm(:,ji,jj) )
+            WHERE (zlammax - zlamtm(:, ji, jj) > 180 ) & 
+               & zlamtm(:,ji,jj) = zlamtm(:,ji,jj) + 360._wp
+            zphitmax(ji,jj) = MAXVAL(zphitm(:,ji,jj))
+            zphitmin(ji,jj) = MINVAL(zphitm(:,ji,jj))
+            zlamtmax(ji,jj) = MAXVAL(zlamtm(:,ji,jj))
+            zlamtmin(ji,jj) = MINVAL(zlamtm(:,ji,jj))
+         END DO
+      END DO
+      !-----------------------------------------------------------------------
+      ! Search for boxes with only land points mark them invalid
+      !-----------------------------------------------------------------------
+      llinvalidcell(:,:) = .FALSE.
+      DO jj = 1, jlat-1
+         DO ji = 1, jlon-1
+            llinvalidcell(ji,jj) =               &
+               & zmskg(ji  ,jj  ) == 0.0_wp .AND. &
+               & zmskg(ji+1,jj  ) == 0.0_wp .AND. &
+               & zmskg(ji+1,jj+1) == 0.0_wp .AND. &
+               & zmskg(ji  ,jj+1) == 0.0_wp
+         END DO
+      END DO
+
+      if(lwp) WRITE(numout,*) 'obs_grid_lookup do coordinate search using lookup table'
+
+      !-----------------------------------------------------------------------
+      ! Do coordinate search using lookup table with local searches.
+      ! - For land points kproc is set to number of the processor + 1000000
+      !   and we continue the search.
+      ! - For ocean points kproc is set to the number of the processor 
+      !   and we stop the search.
+      !-----------------------------------------------------------------------
+      ifourflagcountt = 0
+      ifourflagcountf = 0
+      ifourflagcountr(:) = 0
+
+      !------------------------------------------------------------------------
+      ! Master loop for grid search
+      !------------------------------------------------------------------------
+         
+      gpkobs: DO jo = 1+joffset, kobs, jostride
+         ! Normal case
+         !        specify 4 points which surround the lat lon of interest
+         !                          x i,j+1  x i+1, j+1
+         !
+         !
+         !                             * lon,lat
+         !                          x i,j    x i+1,j
+
+         ! bottom corner point
+         ipx1 = INT( ( zplam(jo)  - lonmin ) / dlon + 1.0 ) 
+         ipy1 = INT( ( pphi (jo)  - latmin ) / dlat + 1.0 )  
+         
+         ipx = ipx1 + 1
+         ipy = ipy1 + 1
+
+         ! flag for searching around four points separately
+         ! default to false
+         llfourflag = .FALSE.
+         
+         ! check for point fully outside of region
+         IF ( (ipx1 > nlons) .OR. (ipy1 > nlats) .OR. &
+            & (ipx < 1) .OR. (ipy < 1) ) THEN
+            CYCLE
+         ENDIF
+         ! check wrap around
+         IF ( (ipx > nlons) .OR. (ipy > nlats) .OR. &
+            & (ipx1 < 1) .OR. (ipy1 < 1) ) THEN
+            llfourflag=.TRUE.
+            ifourflagcountr(1) = ifourflagcountr(1) + 1
+         ENDIF
+
+         IF (.NOT. llfourflag) THEN
+            IF (MAXVAL(ixpos(ipx1:ipx,ipy1:ipy)) == -1) CYCLE! cycle if no lookup points found
+         ENDIF
+         
+         jimin = 0
+         jimax = 0
+         jjmin = 0
+         jjmax = 0
+         
+         IF (.NOT. llfourflag) THEN 
+
+            ! calculate points range
+            ! define a square region encompassing the four corner points
+            ! do I need the -1 points?
+
+            jojimin = MINVAL(ixpos(ipx1:ipx,ipy1:ipy)) - 1
+            jojimax = MAXVAL(ixpos(ipx1:ipx,ipy1:ipy)) + 1
+            jojjmin = MINVAL(iypos(ipx1:ipx,ipy1:ipy)) - 1
+            jojjmax = MAXVAL(iypos(ipx1:ipx,ipy1:ipy)) + 1
+
+            jimin = jojimin - 1
+            jimax = jojimax + 1
+            jjmin = jojjmin - 1
+            jjmax = jojjmax + 1
+            
+            IF ( jojimin < 0 .OR. jojjmin < 0) THEN 
+               llfourflag = .TRUE.
+               ifourflagcountr(2) = ifourflagcountr(2) + 1
+            ENDIF
+            IF ( jojimax - jojimin > maxxdiff) THEN
+               llfourflag = .TRUE.
+               ifourflagcountr(3) = ifourflagcountr(3) + 1
+            ENDIF
+            IF ( jojjmax - jojjmin > maxydiff) THEN
+               llfourflag = .TRUE.
+               ifourflagcountr(4) = ifourflagcountr(4) + 1
+            ENDIF
+            
+         ENDIF
+
+         ipmx = 0
+         IF (llfourflag) ipmx = 1
+
+         IF (llfourflag) THEN 
+            ifourflagcountt = ifourflagcountt + 1
+         ELSE
+            ifourflagcountf = ifourflagcountf + 1
+         ENDIF
+
+         gridpointsn : DO ip = 0, ipmx
+            DO jp = 0, ipmx
+               
+               IF ( kproc(jo) /= -1 ) EXIT gridpointsn
+        
+               ipx = ipx1 + ip
+               ipy = ipy1 + jp
+               
+               IF (llfourflag) THEN
+
+                  ! deal with wrap around
+                  IF ( ipx > nlons ) ipx = 1
+                  IF ( ipy > nlats ) ipy = 1
+                  IF ( ipx < 1     ) ipx = nlons
+                  IF ( ipy < 1     ) ipy = nlats
+
+                  ! get i,j 
+                  isx = ixpos(ipx,ipy)
+                  isy = iypos(ipx,ipy)
+                  
+                  ! estimate appropriate search region (use max/min values)
+                  jimin = isx - maxxdiff - 1
+                  jimax = isx + maxxdiff + 1
+                  jjmin = isy - maxydiff - 1
+                  jjmax = isy + maxydiff + 1
+
+               ENDIF
+
+               IF ( jimin < 1      ) jimin = 1
+               IF ( jimax > jlon-1 ) jimax = jlon-1
+               IF ( jjmin < 1      ) jjmin = 1
+               IF ( jjmax > jlat-1 ) jjmax = jlat-1
+               
+               !---------------------------------------------------------------
+               ! Ensure that all observation longtiudes are between 0 and 360 
+               !---------------------------------------------------------------
+
+               IF ( zplam(jo) <   0.0_wp ) zplam(jo) = zplam(jo) + 360.0_wp
+               IF ( zplam(jo) > 360.0_wp ) zplam(jo) = zplam(jo) - 360.0_wp
+      
+               !---------------------------------------------------------------
+               ! Find observations which are on within 1e-6 of a grid point
+               !---------------------------------------------------------------
+
+               gridloop: DO jj = jjmin, jjmax
+                  DO ji = jimin, jimax
+                     IF ( ABS( zphig(ji,jj) - pphi(jo) ) < 1e-6 )  THEN
+                        zlam = zlamg(ji,jj)
+                        IF ( zlam <   0.0_wp ) zlam = zlam + 360.0_wp
+                        IF ( zlam > 360.0_wp ) zlam = zlam - 360.0_wp
+                        IF ( ABS( zlam - zplam(jo) ) < 1e-6 ) THEN
+                           IF ( llinvalidcell(ji,jj) ) THEN
+                              kproc(jo) = nproc + 1000000
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              CYCLE
+                           ELSE
+                              kproc(jo) = nproc
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              EXIT gridloop
+                           ENDIF
+                        ENDIF
+                     ENDIF
+                  END DO
+               END DO gridloop
+
+               !---------------------------------------------------------------
+               ! Ensure that all observation longtiudes are between -180/180
+               !---------------------------------------------------------------
+
+               IF ( zplam(jo) > 180 ) zplam(jo) = zplam(jo) - 360.0_wp
+
+               IF ( kproc(jo) == -1 ) THEN
+                  
+                  ! Normal case 
+                  gridpoints : DO jj = jjmin, jjmax
+                     DO ji = jimin, jimax
+
+
+                        IF ( ( zplam(jo) > zlamtmax(ji,jj) ) .OR. &
+                           & ( zplam(jo) < zlamtmin(ji,jj) ) ) CYCLE
+                        
+                        IF ( ABS( pphi(jo) ) < 85 ) THEN
+                           IF ( ( pphi(jo) > zphitmax(ji,jj) ) .OR. &
+                              & ( pphi(jo) < zphitmin(ji,jj) ) ) CYCLE
+                        ENDIF
+                        
+                        IF ( linquad( zplam(jo), pphi(jo), &
+                           &          zlamtm(:,ji,jj), zphitm(:,ji,jj) ) ) THEN
+                           IF ( llinvalidcell(ji,jj) ) THEN
+                              kproc(jo) = nproc + 1000000
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              CYCLE
+                           ELSE
+                              kproc(jo) = nproc
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              EXIT gridpoints
+                           ENDIF
+                        ENDIF
+                        
+                     END DO
+                  END DO gridpoints
+               ENDIF
+
+               ! In case of failure retry for obs. longtiude + 360.
+               IF ( kproc(jo) == -1 ) THEN
+                  gridpoints_greenwich : DO jj = jjmin, jjmax
+                     DO ji = jimin, jimax
+                        
+                        IF ( ( zplam(jo)+360.0_wp > zlamtmax(ji,jj) ) .OR. &
+                           & ( zplam(jo)+360.0_wp < zlamtmin(ji,jj) ) ) CYCLE
+
+                        IF ( ABS( pphi(jo) ) < 85 ) THEN
+                           IF ( ( pphi(jo) > zphitmax(ji,jj) ) .OR. &
+                              & ( pphi(jo) < zphitmin(ji,jj) ) ) CYCLE
+                        ENDIF
+
+                        IF ( linquad( zplam(jo)+360.0_wp, pphi(jo), &
+                           &          zlamtm(:,ji,jj), zphitm(:,ji,jj) ) ) THEN
+                           IF ( llinvalidcell(ji,jj) ) THEN
+                              kproc(jo) = nproc + 1000000
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              CYCLE
+                           ELSE
+                              kproc(jo) = nproc
+                              kobsi(jo) = ji + 1
+                              kobsj(jo) = jj + 1
+                              EXIT gridpoints_greenwich
+                           ENDIF
+                        ENDIF
+                        
+                     END DO
+                  END DO gridpoints_greenwich
+                  
+               ENDIF   ! kproc
+               
+            END DO
+         END DO gridpointsn
+      END DO gpkobs  ! kobs
+
+      !----------------------------------------------------------------------
+      ! Synchronize kproc on all processors
+      !----------------------------------------------------------------------
+      IF ( ln_grid_global ) THEN
+         CALL obs_mpp_max_integer( kproc, kobs )
+         CALL obs_mpp_max_integer( kobsi, kobs )
+         CALL obs_mpp_max_integer( kobsj, kobs )
+      ELSE
+         CALL obs_mpp_find_obs_proc( kproc, kobs )
+      ENDIF
+
+      WHERE( kproc(:) >= 1000000 )
+         kproc(:) = kproc(:) - 1000000
+      END WHERE
+
+      DEALLOCATE( &
+         & zlamg,         &
+         & zphig,         &
+         & zmskg,         &
+         & zphitmax,      &
+         & zphitmin,      &
+         & zlamtmax,      &
+         & zlamtmin,      &
+         & llinvalidcell, &
+         & zlamtm,        &
+         & zphitm,        &
+         & zplam          &
+         & )
+      
+   END SUBROUTINE obs_grd_lookup
+
+
+   SUBROUTINE obs_grid_setup
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE obs_grid_setup ***
+      !!
+      !! ** Purpose : Setup a lookup table to reduce the searching required
+      !!              for converting lat lons to grid point location
+      !!              produces or reads in a preexisting file for use in 
+      !!              obs_grid_search_lookup_local
+      !!
+      !! ** Method : calls obs_grid_search_bruteforce_local with a array 
+      !!             of lats and lons
+      !!
+      !! History :
+      !!        !  2007-12 (D. Lea) new routine
+      !!----------------------------------------------------------------------
+      
+      !! * Local declarations
+      CHARACTER(LEN=15), PARAMETER :: &
+         & cpname = 'obs_grid_setup'
+      CHARACTER(LEN=40) :: cfname      
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: jo
+      INTEGER :: idfile, idny, idnx, idxpos, idypos
+      INTEGER :: idlat, idlon, fileexist
+      INTEGER, DIMENSION(2) :: incdim
+      CHARACTER(LEN=20) :: datestr=" ",timestr=" "
+      REAL(wp) :: tmpx1, tmpx2, tmpy1, tmpy2
+      REAL(wp) :: meanxdiff, meanydiff
+      REAL(wp) :: meanxdiff1, meanydiff1
+      REAL(wp) :: meanxdiff2, meanydiff2
+      INTEGER :: numx1, numx2, numy1, numy2, df
+      INTEGER :: jimin, jimax, jjmin, jjmax
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE :: &
+         & lonsi,     &
+         & latsi
+      INTEGER, DIMENSION(:,:), ALLOCATABLE :: &  
+         & ixposi,    &
+         & iyposi,    & 
+         & iproci    
+      INTEGER, PARAMETER :: histsize=90
+      INTEGER, DIMENSION(histsize) :: &
+         & histx1, histx2, histy1, histy2
+      REAL, DIMENSION(histsize) :: &
+         & fhistx1, fhistx2, fhisty1, fhisty2
+      REAL(wp) :: histtol
+      
+      IF (ln_grid_search_lookup) THEN
+         
+         WRITE(numout,*) 'Calling obs_grid_setup'
+         
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*)'Grid search resolution : ', rn_gridsearchres
+         
+         gsearch_nlons_def  = NINT( 360.0_wp / rn_gridsearchres ) 
+         gsearch_nlats_def  = NINT( 180.0_wp / rn_gridsearchres )
+         gsearch_lonmin_def = -180.0_wp + 0.5_wp * rn_gridsearchres
+         gsearch_latmin_def =  -90.0_wp + 0.5_wp * rn_gridsearchres
+         gsearch_dlon_def   = rn_gridsearchres
+         gsearch_dlat_def   = rn_gridsearchres
+         
+         IF (lwp) THEN
+            WRITE(numout,*)'Grid search gsearch_nlons_def  = ',gsearch_nlons_def
+            WRITE(numout,*)'Grid search gsearch_nlats_def  = ',gsearch_nlats_def
+            WRITE(numout,*)'Grid search gsearch_lonmin_def = ',gsearch_lonmin_def
+            WRITE(numout,*)'Grid search gsearch_latmin_def = ',gsearch_latmin_def
+            WRITE(numout,*)'Grid search gsearch_dlon_def   = ',gsearch_dlon_def
+            WRITE(numout,*)'Grid search gsearch_dlat_def   = ',gsearch_dlat_def
+         ENDIF
+
+         IF ( ln_grid_global ) THEN
+            WRITE(cfname, FMT="(A,'_',A)") &
+               &          TRIM(cn_gridsearchfile), 'global.nc'
+         ELSE
+            WRITE(cfname, FMT="(A,'_',I4.4,'of',I4.4,'by',I4.4,'.nc')") &
+               &          TRIM(cn_gridsearchfile), nproc, jpni, jpnj
+         ENDIF
+
+         fileexist=nf90_open( TRIM( cfname ), nf90_nowrite, &
+            &                  idfile )
+         
+         IF ( fileexist == nf90_noerr ) THEN
+            
+            ! read data
+            ! initially assume size is as defined (to be fixed)
+            
+            WRITE(numout,*) 'Reading: ',cfname
+            
+            CALL chkerr( nf90_open( TRIM( cfname ), nf90_nowrite, idfile ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'maxxdiff', maxxdiff ), &
+               &         cpname, __LINE__ )        
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'maxydiff', maxydiff ), &
+               &         cpname, __LINE__ )        
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'dlon', dlon ), &
+            &         cpname, __LINE__ )        
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'dlat', dlat ), &
+               &         cpname, __LINE__ )        
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'lonmin', lonmin ), &
+               &         cpname, __LINE__ )        
+            CALL chkerr( nf90_get_att( idfile, nf90_global, 'latmin', latmin ), &
+               &         cpname, __LINE__ )        
+            
+            CALL chkerr( nf90_inq_dimid(idfile, 'nx'  , idnx), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_inquire_dimension( idfile, idnx, len = nlons ),     &
+               &         cpname, __LINE__ ) 
+            CALL chkerr( nf90_inq_dimid(idfile, 'ny'  , idny), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_inquire_dimension( idfile, idny, len = nlats ),     &
+               &         cpname, __LINE__ ) 
+            
+            ALLOCATE( &
+               & lons(nlons,nlats),  &
+               & lats(nlons,nlats),  &
+               & ixpos(nlons,nlats), &
+               & iypos(nlons,nlats), &
+               & iprocn(nlons,nlats)  &
+               & )
+            
+            CALL chkerr( nf90_inq_varid( idfile, 'XPOS', idxpos ), & 
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var  ( idfile, idxpos, ixpos),   &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_inq_varid( idfile, 'YPOS', idypos ), & 
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var  ( idfile, idypos, iypos),   &
+               &         cpname, __LINE__ )
+            
+            CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+            
+            ! setup arrays
+            
+            DO ji = 1, nlons
+               DO jj = 1, nlats
+                  lons(ji,jj) = lonmin + (ji-1) * dlon
+                  lats(ji,jj) = latmin + (jj-1) * dlat
+               END DO
+            END DO
+            
+            ! if we are not reading the file we need to create it
+            ! create new obs grid search lookup file
+            
+         ELSE 
+            
+            ! call obs_grid_search
+            
+            IF (lwp) THEN
+               WRITE(numout,*) 'creating: ',cfname
+               WRITE(numout,*) 'calling obs_grid_search: ',nlons*nlats
+            ENDIF
+
+            ! set parameters from default values
+            nlons  = gsearch_nlons_def
+            nlats  = gsearch_nlats_def
+            lonmin = gsearch_lonmin_def
+            latmin = gsearch_latmin_def
+            dlon   = gsearch_dlon_def
+            dlat   = gsearch_dlat_def
+            
+            ! setup arrays
+            
+            ALLOCATE( &
+               & lonsi(nlons,nlats),   &
+               & latsi(nlons,nlats),   &
+               & ixposi(nlons,nlats),  &
+               & iyposi(nlons,nlats),  &
+               & iproci(nlons,nlats)   &
+               & )
+         
+            DO ji = 1, nlons
+               DO jj = 1, nlats
+                  lonsi(ji,jj) = lonmin + (ji-1) * dlon
+                  latsi(ji,jj) = latmin + (jj-1) * dlat
+               END DO
+            END DO
+            
+            CALL obs_grd_bruteforce( jpi, jpj, jpiglo, jpjglo,  &
+               &                     1, nlci, 1, nlcj,          &
+               &                     nproc, jpnij,              &
+               &                     glamt, gphit, tmask,       &
+               &                     nlons*nlats, lonsi, latsi, &
+               &                     ixposi, iyposi, iproci )
+            
+            ! minimise file size by removing regions with no data from xypos file
+            ! should be able to just use xpos (ypos will have the same areas of missing data)
+         
+            jimin=1
+            jimax=nlons
+            jjmin=1
+            jjmax=nlats
+
+            minlon_xpos: DO ji= 1, nlons
+               IF (COUNT(ixposi(ji,:) >= 0) > 0) THEN
+                  jimin=ji
+                  EXIT minlon_xpos
+               ENDIF
+            END DO minlon_xpos
+
+            maxlon_xpos: DO ji= nlons, 1, -1
+               IF (COUNT(ixposi(ji,:) >= 0) > 0) THEN
+                  jimax=ji
+                  EXIT maxlon_xpos
+               ENDIF
+            END DO maxlon_xpos
+
+            minlat_xpos: DO jj= 1, nlats
+               IF (COUNT(ixposi(:,jj) >= 0) > 0) THEN
+                  jjmin=jj
+                  EXIT minlat_xpos
+               ENDIF
+            END DO minlat_xpos
+
+            maxlat_xpos: DO jj= nlats, 1, -1
+               IF (COUNT(ixposi(:,jj) >= 0) > 0) THEN 
+                  jjmax=jj
+                  EXIT maxlat_xpos
+               ENDIF
+            END DO maxlat_xpos
+
+            lonmin = lonsi(jimin,jjmin)
+            latmin = latsi(jimin,jjmin)
+            nlons  = jimax-jimin+1
+            nlats  = jjmax-jjmin+1
+
+            ! construct new arrays
+
+            ALLOCATE( &
+               & lons(nlons,nlats),    &
+               & lats(nlons,nlats),    &
+               & ixpos(nlons,nlats),   &
+               & iypos(nlons,nlats),   &
+               & iprocn(nlons,nlats)    &
+               & )
+
+            lons(:,:) = lonsi(jimin:jimax,jjmin:jjmax)
+            lats(:,:) = latsi(jimin:jimax,jjmin:jjmax)
+            ixpos(:,:) = ixposi(jimin:jimax,jjmin:jjmax)
+            iypos(:,:) = iyposi(jimin:jimax,jjmin:jjmax)
+            iprocn(:,:) = iproci(jimin:jimax,jjmin:jjmax)
+
+            DEALLOCATE(lonsi,latsi,ixposi,iyposi,iproci)
+
+            ! calculate (estimate) maxxdiff, maxydiff
+            ! this is to help define the search area for obs_grid_search_lookup
+
+            maxxdiff = 1
+            maxydiff = 1
+
+            tmpx1 = 0
+            tmpx2 = 0
+            tmpy1 = 0
+            tmpy2 = 0 
+
+            numx1 = 0
+            numx2 = 0
+            numy1 = 0
+            numy2 = 0
+
+            ! calculate the mean absolute xdiff and ydiff
+            ! also calculate a histogram
+            ! note the reason why looking for xdiff and ydiff in both directions
+            ! is to allow for rotated grids
+
+            DO ji = 1, nlons-1
+               DO jj = 1, nlats-1
+                  IF ( ixpos(ji,jj) > 0 .AND. iypos(ji,jj) > 0 ) THEN
+                     IF ( ixpos(ji+1,jj) > 0 ) THEN
+                        df = ABS( ixpos(ji+1,jj) - ixpos(ji,jj) )
+                        tmpx1 = tmpx1+df
+                        numx1 = numx1+1
+                        IF ( df < histsize ) histx1(df+1) = histx1(df+1) + 1
+                     ENDIF
+                     IF ( ixpos(ji,jj+1) > 0 ) THEN
+                        df = ABS( ixpos(ji,jj+1) - ixpos(ji,jj) )
+                        tmpx2 = tmpx2 + df
+                        numx2 = numx2 + 1
+                        IF ( df < histsize ) histx2(df+1) = histx2(df+1) + 1
+                     ENDIF
+                     IF (iypos(ji+1,jj) > 0) THEN
+                        df = ABS( iypos(ji+1,jj) - iypos(ji,jj) )
+                        tmpy1 = tmpy1 + df
+                        numy1 = numy1 + 1
+                        IF ( df < histsize ) histy1(df+1) = histy1(df+1) + 1
+                     ENDIF
+                     IF ( iypos(ji,jj+1) > 0 ) THEN
+                        df = ABS( iypos(ji,jj+1) - iypos(ji,jj) )
+                        tmpy2 = tmpy2 + df
+                        numy2 = numy2 + 1
+                        IF ( df < histsize ) histy2(df+1) = histy2(df+1) + 1
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+
+            IF (lwp) THEN
+               WRITE(numout,*) 'histograms'
+               WRITE(numout,*) '0   1   2   3   4   5   6   7   8   9   10 ...'
+               WRITE(numout,*) 'histx1'
+               WRITE(numout,*) histx1
+               WRITE(numout,*) 'histx2'
+               WRITE(numout,*) histx2
+               WRITE(numout,*) 'histy1'
+               WRITE(numout,*) histy1
+               WRITE(numout,*) 'histy2'
+               WRITE(numout,*) histy2
+            ENDIF
+
+            meanxdiff1 = tmpx1 / numx1
+            meanydiff1 = tmpy1 / numy1
+            meanxdiff2 = tmpx2 / numx2
+            meanydiff2 = tmpy2 / numy2
+
+            meanxdiff = MAXVAL((/ meanxdiff1, meanxdiff2 /))
+            meanydiff = MAXVAL((/ meanydiff1, meanydiff2 /))
+
+            IF (lwp) THEN
+               WRITE(numout,*) tmpx1, tmpx2, tmpy1, tmpy2
+               WRITE(numout,*) numx1, numx2, numy1, numy2
+               WRITE(numout,*) 'meanxdiff: ',meanxdiff, meanxdiff1, meanxdiff2
+               WRITE(numout,*) 'meanydiff: ',meanydiff, meanydiff1, meanydiff2
+            ENDIF
+
+            tmpx1 = 0
+            tmpx2 = 0
+            tmpy1 = 0
+            tmpy2 = 0
+
+            numx1 = 0
+            numx2 = 0
+            numy1 = 0
+            numy2 = 0
+
+            histx1(:) = 0
+            histx2(:) = 0
+            histy1(:) = 0
+            histy2(:) = 0
+
+            limxdiff = meanxdiff * 4! limit the difference to avoid picking up wraparound
+            limydiff = meanydiff * 4
+
+            DO ji = 1, nlons-1
+               DO jj = 1, nlats-1
+                  IF ( ixpos(ji,jj) > 0 .AND. iypos(ji,jj) > 0 ) THEN
+
+                     IF ( ixpos(ji+1,jj) > 0 ) THEN
+                        df = ABS( ixpos(ji+1,jj)-ixpos(ji,jj) )
+                        tmpx1 = df
+                        IF ( df < limxdiff ) numx1 = numx1+1
+                        IF ( df < histsize ) histx1(df+1) = histx1(df+1) + 1
+                     ENDIF
+                     IF ( ixpos(ji,jj+1) > 0 ) THEN
+                        df = ABS( ixpos(ji,jj+1) - ixpos(ji,jj) )
+                        tmpx2 = df
+                        IF ( df < limxdiff ) numx2 = numx2 + 1
+                        IF ( df < histsize ) histx2(df+1) = histx2(df+1) + 1
+                     ENDIF
+                     IF (iypos(ji+1,jj) > 0) THEN
+                        df = ABS( iypos(ji+1,jj) - iypos(ji,jj) )
+                        tmpy1 = df
+                        IF ( df < limydiff ) numy1 = numy1 + 1
+                        IF ( df < histsize ) histy1(df+1) = histy1(df+1) + 1
+                     ENDIF
+                     IF (iypos(ji,jj+1) > 0) THEN
+                        df = ABS( iypos(ji,jj+1) - iypos(ji,jj) )
+                        tmpy2 = df
+                        IF ( df < limydiff ) numy2 = numy2+1
+                        IF ( df < histsize ) histy2(df+1) = histy2(df+1)+1
+                     ENDIF
+
+                     IF ( maxxdiff < tmpx1 .AND. tmpx1 < limxdiff ) &
+                        & maxxdiff = tmpx1
+                     IF ( maxxdiff < tmpx2 .AND. tmpx2 < limxdiff ) &
+                        & maxxdiff = tmpx2
+                     IF ( maxydiff < tmpy1 .AND. tmpy1 < limydiff ) &
+                        & maxydiff = tmpy1
+                     IF ( maxydiff < tmpy2 .AND. tmpy2 < limydiff ) &
+                        & maxydiff = tmpy2
+
+                  ENDIF
+               END DO
+            END DO
+
+            ! cumulative histograms
+
+            DO ji = 1, histsize - 1
+               histx1(ji+1) = histx1(ji+1) + histx1(ji)
+               histx2(ji+1) = histx2(ji+1) + histx2(ji)
+               histy1(ji+1) = histy1(ji+1) + histy1(ji)
+               histy2(ji+1) = histy2(ji+1) + histy2(ji)
+            END DO
+
+            fhistx1(:) = histx1(:) * 1.0 / numx1
+            fhistx2(:) = histx2(:) * 1.0 / numx2
+            fhisty1(:) = histy1(:) * 1.0 / numy1
+            fhisty2(:) = histy2(:) * 1.0 / numy2
+
+            ! output new histograms
+
+            IF (lwp) THEN
+               WRITE(numout,*) 'cumulative histograms'
+               WRITE(numout,*) '0   1   2   3   4   5   6   7   8   9   10 ...'
+               WRITE(numout,*) 'fhistx1'
+               WRITE(numout,*) fhistx1
+               WRITE(numout,*) 'fhistx2'
+               WRITE(numout,*) fhistx2
+               WRITE(numout,*) 'fhisty1'
+               WRITE(numout,*) fhisty1
+               WRITE(numout,*) 'fhisty2'
+               WRITE(numout,*) fhisty2
+            ENDIF
+
+            ! calculate maxxdiff and maxydiff based on cumulative histograms
+            ! where > 0.999 of points are
+
+            ! maxval just converts 1x1 vector return from maxloc to a scalar 
+
+            histtol = 0.999
+            tmpx1 = MAXVAL( MAXLOC( fhistx1(:), mask = ( fhistx1(:) <= histtol ) ) )
+            tmpx2 = MAXVAL( MAXLOC( fhistx2(:), mask = ( fhistx2(:) <= histtol ) ) )
+            tmpy1 = MAXVAL( MAXLOC( fhisty1(:), mask = ( fhisty1(:) <= histtol ) ) )
+            tmpy2 = MAXVAL( MAXLOC( fhisty2(:), mask = ( fhisty2(:) <= histtol ) ) )
+
+            maxxdiff = MAXVAL( (/ tmpx1, tmpx2 /) ) + 1
+            maxydiff = MAXVAL( (/ tmpy1, tmpy2 /) ) + 1
+
+            ! Write out data
+
+            IF ( ( .NOT. ln_grid_global ) .OR. &
+               & ( ( ln_grid_global ) .AND. ( nproc==0 ) ) ) THEN
+
+               CALL chkerr( nf90_create (TRIM(cfname), nf90_clobber, idfile), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'title',       &
+                  &         'Mapping file from lon/lat to model grid point' ),&
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'maxxdiff',    &
+                  &                       maxxdiff ),                         &
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'maxydiff',    &
+                  &                       maxydiff ),                         &
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'dlon', dlon ),&
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'dlat', dlat ),&
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'lonmin',      &
+                  &                       lonmin ),                           &
+                  &         cpname,__LINE__ ) 
+               CALL chkerr( nf90_put_att( idfile, nf90_global, 'latmin',      &
+                  &                       latmin ),                           &
+                  &         cpname,__LINE__ ) 
+
+               CALL chkerr( nf90_def_dim(idfile, 'nx'  , nlons, idnx),        &
+                  &         cpname,__LINE__ )
+               CALL chkerr( nf90_def_dim(idfile, 'ny'  , nlats, idny),        &
+                  &         cpname,__LINE__ )
+
+               incdim(1) = idnx
+               incdim(2) = idny
+               
+               CALL chkerr( nf90_def_var( idfile, 'LON', nf90_float, incdim,  &
+                  &                       idlon ),                            &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idlon, 'long_name',         &
+                  &                       'longitude' ),                      &
+                  &         cpname, __LINE__ )
+               
+               CALL chkerr( nf90_def_var( idfile, 'LAT', nf90_float, incdim,  &
+                  &                       idlat ),                            &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idlat, 'long_name',         &
+                  &                       'latitude' ),                       &
+                  &         cpname, __LINE__ )
+
+               CALL chkerr( nf90_def_var( idfile, 'XPOS', nf90_int, incdim,   &
+                  &                       idxpos ),                           &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idxpos, 'long_name',        &
+                  &                       'x position' ),                     &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idxpos, '_FillValue', -1 ), &
+                  &         cpname, __LINE__ )
+
+               CALL chkerr( nf90_def_var( idfile, 'YPOS', nf90_int, incdim,   &
+                  &                       idypos ),                           &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idypos, 'long_name',        &
+                  &                       'y position' ),                     &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_att( idfile, idypos, '_FillValue', -1 ), &
+                  &         cpname, __LINE__ )
+
+               CALL chkerr( nf90_enddef( idfile ), cpname, __LINE__ )
+               
+               CALL chkerr( nf90_put_var( idfile, idlon, lons),               &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idlat, lats),               &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idxpos, ixpos),             &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idypos, iypos),             &
+                  &         cpname, __LINE__ )
+               
+               CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+               
+               ! should also output max i, max j spacing for use in 
+               ! obs_grid_search_lookup
+               
+            ENDIF
+
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE obs_grid_setup
+   
+   SUBROUTINE obs_grid_deallocate( )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE obs_grid_setup ***
+      !!
+      !! ** Purpose : Deallocate arrays setup by obs_grid_setup
+      !!
+      !! History :
+      !!        !  2007-12 (D. Lea) new routine
+      !!-----------------------------------------------------------------------
+
+      IF (ln_grid_search_lookup) THEN
+         DEALLOCATE( lons, lats, ixpos, iypos, iprocn )
+      ENDIF
+      
+   END SUBROUTINE obs_grid_deallocate
+
+#include "obs_level_search.h90"
+
+#include "linquad.h90"
+
+#include "maxdist.h90"
+
+#include "find_obs_proc.h90"
+
+END MODULE obs_grid
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_h2d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_h2d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_h2d.F90	(revision 14097)
@@ -0,0 +1,58 @@
+MODULE obs_inter_h2d
+   !!======================================================================
+   !!                       ***  MODULE obs_inter_h2d   ***
+   !! Observation diagnostics: Perform the horizontal interpolation
+   !!                          from model grid to observation location
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_int_h2d     : Horizontal interpolation to the observation point
+   !!   obs_int_h2d_ds1 : Distance-weighted interpolation                 (n2dint=0)
+   !!   obs_int_h2d_ds2 : Distance-weighted interpolation (small angle)   (n2dint=1)
+   !!   obs_int_h2d_bil : Bilinear interpolation (geographical grid)      (n2dint=2)
+   !!   obs_int_h2d_bir : Bilinear remapping interpolation (general grid) (n2dint=3)
+   !!   obs_int_h2d_pol : Polynomial interpolation                        (n2dint=4)
+   !!   bil_wgt         : Compute weights for bilinear remapping
+   !!   lu_invmat       : Invert a matrix using LU decomposition
+   !!   lu_decomp       : LU decomposition
+   !!   lu_backsb       : LU decomposition - back substitution
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : &  ! Precision variables
+      & wp
+   USE phycst,   ONLY : &  ! Physical constants
+      & rad,  &
+      & rpi
+   USE in_out_manager
+   USE obs_const, ONLY : &
+      & obfillflt		! Fillvalue
+   USE obs_utils           ! Utility functions
+      USE lib_mpp,ONLY : &
+      & ctl_warn, ctl_stop
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE obs_int_h2d_ds1, & ! Distance-weighted interpolation               
+      &    obs_int_h2d_ds2, & ! Distance-weighted interpolation (small angle) 
+      &    obs_int_h2d_bil, & ! Bilinear interpolation (geographical grid)    
+      &    obs_int_h2d_bir, & ! Bilinear remapping interpolation (general grid)
+      &    obs_int_h2d_pol, & ! Polynomial interpolation                       
+      &    lu_invmat,       & ! Invert a matrix using LU decomposition
+      &    lu_decomp,       & ! LU decomposition
+      &    lu_backsb,       & ! LU decomposition - back substitution
+      &    bil_wgt            ! Compute weights for bilinear remapping
+   PUBLIC obs_int_h2d,      & ! Horizontal interpolation to the observation point
+      &   obs_int_h2d_init    ! Set up weights and vertical mask
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+ 
+#include "obsinter_h2d.h90"
+
+END MODULE obs_inter_h2d
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_sup.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_sup.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_sup.F90	(revision 14097)
@@ -0,0 +1,386 @@
+MODULE obs_inter_sup
+   !!=====================================================================
+   !!                       ***  MODULE obs_inter_sup  ***
+   !! Observation diagnostics: Support for interpolation
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_int_comm_3d : Get 3D interpolation stencil
+   !!   obs_int_comm_2d : Get 2D interpolation stencil
+   !!---------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind        ! Precision variables
+   USE dom_oce         ! Domain variables
+   USE mpp_map         ! Map of processor points
+   USE lib_mpp         ! MPP stuff
+   USE obs_mpp         ! MPP stuff for observations
+   USE obs_grid        ! Grid tools
+   USE in_out_manager  ! I/O stuff
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+   
+   PUBLIC obs_int_comm_3d, & ! Get 3D interpolation stencil
+      &   obs_int_comm_2d    ! Get 2D interpolation stencil
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_int_comm_3d( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, kgrdj, &
+      &                        pval, pgval, kproc )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_int_comm_3d  ***
+      !!          
+      !! ** Purpose : Get 3D interpolation stencil
+      !!
+      !! ** Method  : Either on-demand communication with 
+      !!              obs_int_comm_3d_global 
+      !!              or local memory with
+      !!              obs_int_comm_3D_local
+      !!              depending on ln_global_grid
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  08-02  (K. Mogensen)  Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kptsi     ! Number of i horizontal points per stencil 
+      INTEGER, INTENT(IN) :: kptsj     ! Number of j horizontal points per stencil
+      INTEGER, INTENT(IN) :: kobs      ! Local number of observations
+      INTEGER, INTENT(IN) :: kpi       ! Number of points in i direction
+      INTEGER, INTENT(IN) :: kpj       ! Number of points in j direction
+      INTEGER, INTENT(IN) :: kpk       ! Number of levels
+      INTEGER, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kgrdi, &         ! i,j indicies for each stencil
+         & kgrdj
+      INTEGER, OPTIONAL, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kproc            ! Precomputed processor for each i,j,iobs points
+      REAL(KIND=wp), DIMENSION(kpi,kpj,kpk), INTENT(IN) ::&
+         & pval             ! Local 3D array to extract data from
+      REAL(KIND=wp), DIMENSION(kptsi,kptsj,kpk,kobs), INTENT(OUT) ::&
+         & pgval            ! Stencil at each point
+      !! * Local declarations
+      
+      IF (ln_grid_global) THEN
+         
+         IF (PRESENT(kproc)) THEN
+
+            CALL obs_int_comm_3d_global( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, &
+               &                         kgrdj, pval, pgval, kproc=kproc )
+
+         ELSE
+
+            CALL obs_int_comm_3d_global( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, &
+               &                         kgrdj, pval, pgval )
+
+         ENDIF
+
+      ELSE
+
+         CALL obs_int_comm_3d_local( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, kgrdj, &
+            &                        pval, pgval )
+
+      ENDIF
+
+   END SUBROUTINE obs_int_comm_3d
+
+   SUBROUTINE obs_int_comm_2d( kptsi, kptsj, kobs, kpi, kpj, kgrdi, kgrdj, pval, pgval, &
+      &                        kproc )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_int_comm_2d  ***
+      !!          
+      !! ** Purpose : Get 2D interpolation stencil
+      !!
+      !! ** Method  : Call to obs_int_comm_3d
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  08-02  (K. Mogensen)  Original code
+      !!----------------------------------------------------------------------
+      !!
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kptsi        ! Number of i horizontal points per stencil
+      INTEGER, INTENT(IN) :: kptsj        ! Number of j horizontal points per stencil
+      INTEGER, INTENT(IN) :: kobs          ! Local number of observations
+      INTEGER, INTENT(IN) :: kpi          ! Number of model grid points in i direction
+      INTEGER, INTENT(IN) :: kpj          ! Number of model grid points in j direction
+      INTEGER, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kgrdi, &         ! i,j indicies for each stencil
+         & kgrdj
+      INTEGER, OPTIONAL, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kproc            ! Precomputed processor for each i,j,iobs points
+      REAL(KIND=wp), DIMENSION(kpi,kpj), INTENT(IN) ::&
+         & pval             ! Local 3D array to extra data from
+      REAL(KIND=wp), DIMENSION(kptsi,kptsj,kobs), INTENT(OUT) ::&
+         & pgval            ! Stencil at each point
+      !! * Local declarations
+      REAL(KIND=wp), DIMENSION(jpi,jpj,1) ::   zval
+      REAL(KIND=wp), DIMENSION(kptsi,kptsj,1,kobs) ::&
+         & zgval 
+
+      ! Set up local "3D" buffer
+
+      zval(:,:,1) = pval(:,:)
+
+      ! Call the 3D version
+
+      IF (PRESENT(kproc)) THEN
+
+         CALL obs_int_comm_3d( kptsi, kptsj, kobs, kpi, kpj, 1, kgrdi, kgrdj, zval, &
+            &                  zgval, kproc=kproc )
+      ELSE
+
+         CALL obs_int_comm_3d( kptsi, kptsj, kobs, kpi, kpj, 1, kgrdi, kgrdj, zval, &
+            &                  zgval )
+
+      ENDIF
+
+      ! Copy "3D" data back to 2D
+
+      pgval(:,:,:) = zgval(:,:,1,:)
+
+   END SUBROUTINE obs_int_comm_2d
+
+   SUBROUTINE obs_int_comm_3d_global( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, kgrdj, &
+      &                               pval, pgval, kproc )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_int_comm_3d_global  ***
+      !!          
+      !! ** Purpose : Get 3D interpolation stencil (global version)
+      !!
+      !! ** Method  : On-demand communication where each processor send its
+      !!              list of (i,j) of points to all processors and receive 
+      !!              the corresponding values
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  08-02  (K. Mogensen)  Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kptsi     ! Number of i horizontal points per stencil 
+      INTEGER, INTENT(IN) :: kptsj     ! Number of j horizontal points per stencil
+      INTEGER, INTENT(IN) :: kobs      ! Local number of observations
+      INTEGER, INTENT(IN) :: kpi       ! Number of model points in i direction
+      INTEGER, INTENT(IN) :: kpj       ! Number of model points in j direction
+      INTEGER, INTENT(IN) :: kpk       ! Number of levels
+      INTEGER, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kgrdi, &         ! i,j indicies for each stencil
+         & kgrdj
+      INTEGER, OPTIONAL, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kproc            ! Precomputed processor for each i,j,iobs points
+      REAL(KIND=wp), DIMENSION(kpi,kpj,kpk), INTENT(IN) ::&
+         & pval             ! Local 3D array to extract data from
+      REAL(KIND=wp), DIMENSION(kptsi,kptsj,kpk,kobs), INTENT(OUT) ::&
+         & pgval            ! Stencil at each point
+      !! * Local declarations
+      REAL(KIND=wp), DIMENSION(:,:), ALLOCATABLE :: &
+         & zsend, &
+         & zrecv
+      INTEGER, DIMENSION(:), ALLOCATABLE :: &
+         & igrdij_send, &
+         & igrdij_recv
+      INTEGER, DIMENSION(kptsi,kptsj,kobs) :: &
+         & iorder, &
+         & iproc
+      INTEGER :: nplocal(jpnij)
+      INTEGER :: npglobal(jpnij)
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: jp
+      INTEGER :: jobs
+      INTEGER :: it
+      INTEGER :: itot
+      INTEGER :: ii
+      INTEGER :: ij
+
+      ! Check valid points
+
+      IF ( ( MAXVAL(kgrdi) > jpiglo ) .OR. ( MINVAL(kgrdi) < 1 ) .OR. &
+         & ( MAXVAL(kgrdj) > jpjglo ) .OR. ( MINVAL(kgrdj) < 1 ) ) THEN
+
+         CALL ctl_stop( 'Error in obs_int_comm_3d_global', &
+            &           'Point outside global domain' )
+
+      ENDIF
+
+      ! Count number of points on each processors
+
+      nplocal(:) = 0
+      IF (PRESENT(kproc)) THEN 
+         iproc(:,:,:) = kproc(:,:,:)
+         DO jobs = 1, kobs
+            DO jj = 1, kptsj
+               DO ji = 1, kptsi
+                  nplocal(iproc(ji,jj,jobs)) = nplocal(iproc(ji,jj,jobs)) + 1
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jobs = 1, kobs
+            DO jj = 1, kptsj
+               DO ji = 1, kptsi
+                  iproc(ji,jj,jobs) = mppmap(kgrdi(ji,jj,jobs),&
+                     &                       kgrdj(ji,jj,jobs))
+                  nplocal(iproc(ji,jj,jobs)) = nplocal(iproc(ji,jj,jobs)) + 1
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      ! Send local number of points and receive points on current domain
+
+      CALL mpp_alltoall_int( 1, nplocal, npglobal )
+
+      ! Allocate message parsing workspace
+
+      itot = SUM(npglobal)
+
+      ALLOCATE( &
+         & igrdij_send(kptsi*kptsj*kobs*2), &
+         & igrdij_recv(itot*2),             &
+         & zsend(kpk,itot),                 &
+         & zrecv(kpk,kptsi*kptsj*kobs)      &
+         & )
+
+      ! Pack buffers for list of points
+
+      it = 0
+      DO jp = 1, jpnij 
+         DO jobs = 1, kobs
+            DO jj = 1, kptsj
+               DO ji = 1, kptsi
+                  IF ( iproc(ji,jj,jobs) == jp ) THEN
+                     it = it + 1
+                     iorder(ji,jj,jobs) = it
+                     igrdij_send(2*it-1) = kgrdi(ji,jj,jobs)
+                     igrdij_send(2*it  ) = kgrdj(ji,jj,jobs)
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Send and recieve buffers for list of points
+
+      CALL mpp_alltoallv_int( igrdij_send, kptsi*kptsj*kobs*2, nplocal(:)*2, &
+         &                    igrdij_recv, itot*2, npglobal(:)*2 )
+
+      ! Pack interpolation data to be sent
+
+      DO ji = 1, itot
+         ii = mi1(igrdij_recv(2*ji-1))
+         ij = mj1(igrdij_recv(2*ji))
+         DO jk = 1, kpk
+            zsend(jk,ji) = pval(ii,ij,jk)
+         END DO
+      END DO
+
+      ! Re-adjust sizes
+
+      nplocal(:)  = kpk*nplocal(:)
+      npglobal(:) = kpk*npglobal(:)
+
+
+      ! Send and receive data for interpolation stencil
+
+      CALL mpp_alltoallv_real( zsend, kpk*itot,             npglobal, &
+         &                     zrecv, kpk*kptsi*kptsj*kobs, nplocal )
+
+      ! Copy the received data into output data structure
+      
+      DO jobs = 1, kobs
+         DO jj = 1, kptsj
+            DO ji = 1, kptsi
+               it = iorder(ji,jj,jobs)  
+               DO jk = 1, kpk
+                  pgval(ji,jj,jk,jobs) = zrecv(jk,it)
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Deallocate message parsing workspace
+
+      DEALLOCATE( &
+         & igrdij_send, &
+         & igrdij_recv, &
+         & zsend,       &
+         & zrecv        &
+         & )
+
+   END SUBROUTINE obs_int_comm_3d_global
+   
+   SUBROUTINE obs_int_comm_3d_local( kptsi, kptsj, kobs, kpi, kpj, kpk, kgrdi, kgrdj, &
+      &                              pval, pgval )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_int_comm_3d_global  ***
+      !!          
+      !! ** Purpose : Get 3D interpolation stencil (global version)
+      !!
+      !! ** Method  : On-demand communication where each processor send its
+      !!              list of (i,j) of points to all processors and receive 
+      !!              the corresponding values
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  08-02  (K. Mogensen)  Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kptsi        ! Number of i horizontal points per stencil 
+      INTEGER, INTENT(IN) :: kptsj        ! Number of j horizontal points per stencil
+      INTEGER, INTENT(IN) :: kobs         ! Local number of observations
+      INTEGER, INTENT(IN) :: kpi          ! Number of model points in i direction
+      INTEGER, INTENT(IN) :: kpj          ! Number of model points in j direction
+      INTEGER, INTENT(IN) :: kpk          ! Number of levels
+      INTEGER, DIMENSION(kptsi,kptsj,kobs), INTENT(IN) :: &
+         & kgrdi, &         ! i,j indicies for each stencil
+         & kgrdj
+      REAL(KIND=wp), DIMENSION(kpi,kpj,kpk), INTENT(IN) ::&
+         & pval             ! Local 3D array to extract data from
+      REAL(KIND=wp), DIMENSION(kptsi,kptsj,kpk,kobs), INTENT(OUT) ::&
+         & pgval            ! Stencil at each point
+      !! * Local declarations
+      INTEGER ::  ji
+      INTEGER ::  jj
+      INTEGER ::  jk
+      INTEGER ::  jobs
+
+      ! Check valid points
+
+      IF ( ( MAXVAL(kgrdi) > jpi ) .OR. ( MINVAL(kgrdi) < 1 ) .OR. &
+         & ( MAXVAL(kgrdj) > jpj ) .OR. ( MINVAL(kgrdj) < 1 ) ) THEN
+         
+         CALL ctl_stop( 'Error in obs_int_comm_3d_local', &
+            &           'Point outside local domain' )
+ 
+      ENDIF
+
+      ! Copy local data
+
+      DO jobs = 1, kobs
+         DO jj = 1, kptsj
+            DO ji = 1, kptsi
+               DO jk = 1, kpk
+                  pgval(ji,jj,jk,jobs) = &
+                     &            pval(kgrdi(ji,jj,jobs),kgrdj(ji,jj,jobs),jk)
+               END DO
+            END DO
+         END DO
+      END DO
+
+   END SUBROUTINE obs_int_comm_3d_local
+
+END MODULE obs_inter_sup
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_z1d.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_z1d.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_inter_z1d.F90	(revision 14097)
@@ -0,0 +1,37 @@
+MODULE obs_inter_z1d
+   !!======================================================================
+   !!                       ***  MODULE obs_inter_z1d  ***
+   !! Observation diagnostics: Perform the vertical interpolation
+   !!                          from model grid to observation location
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_int_z1d     : Vertical interpolation to the observation point
+   !!   obs_int_z1d_spl : Compute the vertical 2nd derivative of the
+   !!                     interpolating function for a cubic spline (n1dint=1)
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : &  ! Precision variables
+      & wp
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC obs_int_z1d,    &  ! Vertical interpolation to the observation pt.
+      &   obs_int_z1d_spl    ! Compute the vertical 2nd derivative of the
+                             ! interpolating function used with a cubic spline
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+#include "obsinter_z1d.h90"
+
+END MODULE obs_inter_z1d
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_level_search.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_level_search.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_level_search.h90	(revision 14097)
@@ -0,0 +1,51 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE obs_level_search( kgrd, pgrddep, kobs, pobsdep, kobsk )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_level_search ***
+      !!
+      !! ** Purpose : Search levels to find matching level to observed depth
+      !!
+      !! ** Method  : Straightforward search
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  2001-11  (N. Daget, A. Weaver)
+      !!        !  2006-03  (A. Weaver) NEMOVAR migration.
+      !!        !  2006-05  (K. Mogensen) Moved to to separate routine.
+      !!        !  2006-10  (A. Weaver) Cleanup
+      !!        !  2008-10  (K. Mogensen) Remove assumptions on grid.
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kgrd     ! Number of gridpoints
+      REAL(KIND=wp), DIMENSION(kgrd), INTENT(INOUT) :: &
+         &   pgrddep  ! Depths of gridpoints
+      INTEGER, INTENT(IN) :: &
+         &   kobs     ! Number of observations
+      REAL(KIND=wp), DIMENSION(kobs), INTENT(INOUT) :: &
+         &   pobsdep  ! Depths of observations
+      INTEGER ,DIMENSION(kobs), INTENT(OUT) :: &
+         &   kobsk    ! Level indices of observations
+  
+      !! * Local declarations
+      INTEGER :: ji
+      INTEGER :: jk
+
+      !------------------------------------------------------------------------
+      ! Search levels for each observations to find matching level
+      !------------------------------------------------------------------------
+      DO ji = 1, kobs 
+         kobsk(ji) = 1
+         depk: DO jk = 2, kgrd
+            IF ( pgrddep(jk) >= pobsdep(ji) ) EXIT depk
+         END DO depk
+         kobsk(ji) = jk
+      END DO
+
+   END SUBROUTINE obs_level_search
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_mpp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_mpp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_mpp.F90	(revision 14097)
@@ -0,0 +1,445 @@
+MODULE obs_mpp
+   !!======================================================================
+   !!                       ***  MODULE obs_mpp  ***
+   !! Observation diagnostics: Various MPP support routines
+   !!======================================================================
+   !! History :  2.0  ! 2006-03  (K. Mogensen)  Original code
+   !!             -   ! 2006-05  (K. Mogensen)  Reformatted
+   !!             -   ! 2008-01  (K. Mogensen)  add mpp_global_max
+   !!            3.6  ! 2015-01  (J. Waters) obs_mpp_find_obs_proc 
+   !!                            rewritten to avoid global arrays
+   !!----------------------------------------------------------------------
+#  define mpivar mpi_double_precision
+   !!----------------------------------------------------------------------
+   !! obs_mpp_bcast_integer : Broadcast an integer array from a processor to all processors
+   !! obs_mpp_max_integer   : Find maximum on all processors of each value in an integer on all processors
+   !! obs_mpp_find_obs_proc : Find processors which should hold the observations, avoiding global arrays
+   !! obs_mpp_sum_integers  : Sum an integer array from all processors
+   !! obs_mpp_sum_integer   : Sum an integer from all processors
+   !!----------------------------------------------------------------------
+   USE dom_oce, ONLY :   nproc, mig, mjg   ! Ocean space and time domain variables
+   USE mpp_map, ONLY :   mppmap
+   USE in_out_manager
+#if defined key_mpp_mpi
+   USE lib_mpp, ONLY :   mpi_comm_oce      ! MPP library
+#endif
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC obs_mpp_bcast_integer, & !: Broadcast an integer array from a proc to all procs
+      &   obs_mpp_max_integer,   & !: Find maximum across processors in an integer array
+      &   obs_mpp_find_obs_proc, & !: Find processors which should hold the observations
+      &   obs_mpp_sum_integers,  & !: Sum an integer array from all processors
+      &   obs_mpp_sum_integer,   & !: Sum an integer from all processors
+      &   mpp_alltoall_int,      &
+      &   mpp_alltoallv_int,     &
+      &   mpp_alltoallv_real,    &
+      &   mpp_global_max
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE obs_mpp_bcast_integer( kvals, kno, kroot )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE obs_mpp_bcast_integer ***
+      !!          
+      !! ** Purpose : Send array kvals to all processors
+      !!
+      !! ** Method  : MPI broadcast
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              MPI_COMM_OCE needs to be replace for OASIS4.!
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in   ) ::   kno     ! Number of elements in array
+      INTEGER                , INTENT(in   ) ::   kroot   ! Processor to send data
+      INTEGER, DIMENSION(kno), INTENT(inout) ::   kvals   ! Array to send on kroot, receive for non-kroot
+      !
+#if defined key_mpp_mpi
+      !
+      INTEGER :: ierr 
+      !
+INCLUDE 'mpif.h'
+      !!----------------------------------------------------------------------
+
+      ! Call the MPI library to broadcast data
+      CALL mpi_bcast( kvals, kno, mpi_integer,  &
+         &            kroot, mpi_comm_oce, ierr )
+#else
+      ! no MPI: empty routine
+#endif
+      !
+   END SUBROUTINE obs_mpp_bcast_integer
+
+  
+   SUBROUTINE obs_mpp_max_integer( kvals, kno )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE obs_mpp_bcast_integer ***
+      !!          
+      !! ** Purpose : Find maximum across processors in an integer array.
+      !!
+      !! ** Method  : MPI all reduce.
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!              MPI_COMM_OCE needs to be replace for OASIS4.!
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in   ) ::   kno     ! Number of elements in array
+      INTEGER, DIMENSION(kno), INTENT(inout) ::   kvals   ! Array to send on kroot, receive for non-kroot  
+      !
+#if defined key_mpp_mpi
+      !
+      INTEGER :: ierr 
+      INTEGER, DIMENSION(kno) ::   ivals
+      !
+INCLUDE 'mpif.h'
+      !!----------------------------------------------------------------------
+
+      ! Call the MPI library to find the maximum across processors
+      CALL mpi_allreduce( kvals, ivals, kno, mpi_integer,   &
+         &                mpi_max, mpi_comm_oce, ierr )
+      kvals(:) = ivals(:)
+#else
+      ! no MPI: empty routine
+#endif
+   END SUBROUTINE obs_mpp_max_integer
+
+
+   SUBROUTINE obs_mpp_find_obs_proc( kobsp,kno )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE obs_mpp_find_obs_proc  ***
+      !!         
+      !! ** Purpose : From the array kobsp containing the results of the
+      !!              grid search on each processor the processor return a
+      !!              decision of which processors should hold the observation.
+      !!
+      !! ** Method  : Synchronize the processor number for each obs using
+      !!              obs_mpp_max_integer. If an observation exists on two 
+      !!              processors it will be allocated to the lower numbered
+      !!              processor.
+      !!
+      !! ** Action  : This does only work for MPI.
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in   ) ::   kno
+      INTEGER, DIMENSION(kno), INTENT(inout) ::   kobsp
+      !
+#if defined key_mpp_mpi
+      !
+      !
+      INTEGER :: ji, isum
+      INTEGER, DIMENSION(kno) ::   iobsp
+      !!
+      !!
+
+      iobsp(:)=kobsp(:)
+
+      WHERE( iobsp(:) == -1 )
+         iobsp(:) = 9999999
+      END WHERE
+
+      iobsp(:)=-1*iobsp(:)
+
+      CALL obs_mpp_max_integer( iobsp, kno )
+
+      kobsp(:)=-1*iobsp(:)
+
+      isum=0
+      DO ji = 1, kno
+         IF ( kobsp(ji) == 9999999 ) THEN
+            isum=isum+1
+            kobsp(ji)=-1
+         ENDIF
+      ENDDO
+
+
+      IF ( isum > 0 ) THEN
+         IF (lwp) WRITE(numout,*) isum, ' observations failed the grid search.'
+         IF (lwp) WRITE(numout,*)'If ln_grid_search_lookup=.TRUE., try reducing grid_search_res'
+      ENDIF
+
+#else
+      ! no MPI: empty routine
+#endif     
+      
+   END SUBROUTINE obs_mpp_find_obs_proc
+
+
+   SUBROUTINE obs_mpp_sum_integers( kvalsin, kvalsout, kno )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE obs_mpp_sum_integers ***
+      !!          
+      !! ** Purpose : Sum an integer array.
+      !!
+      !! ** Method  : MPI all reduce.
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in   ) :: kno
+      INTEGER, DIMENSION(kno), INTENT(in   ) ::   kvalsin
+      INTEGER, DIMENSION(kno), INTENT(  out) ::   kvalsout
+      !
+#if defined key_mpp_mpi
+      !
+      INTEGER :: ierr
+      !
+INCLUDE 'mpif.h'
+      !!----------------------------------------------------------------------
+      !
+      !-----------------------------------------------------------------------
+      ! Call the MPI library to find the sum across processors
+      !-----------------------------------------------------------------------
+      CALL mpi_allreduce( kvalsin, kvalsout, kno, mpi_integer, &
+         &                mpi_sum, mpi_comm_oce, ierr )
+#else
+      !-----------------------------------------------------------------------
+      ! For no-MPP just return input values
+      !-----------------------------------------------------------------------
+      kvalsout(:) = kvalsin(:)
+#endif
+      !
+   END SUBROUTINE obs_mpp_sum_integers
+
+
+   SUBROUTINE obs_mpp_sum_integer( kvalin, kvalout )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE obs_mpp_sum_integers ***
+      !!          
+      !! ** Purpose : Sum a single integer
+      !!
+      !! ** Method  : MPI all reduce.
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kvalin
+      INTEGER, INTENT(  out) ::   kvalout
+      !
+#if defined key_mpp_mpi
+      !
+      INTEGER :: ierr
+      !
+INCLUDE 'mpif.h'
+      !!----------------------------------------------------------------------
+      !
+      !-----------------------------------------------------------------------
+      ! Call the MPI library to find the sum across processors
+      !-----------------------------------------------------------------------
+      CALL mpi_allreduce( kvalin, kvalout, 1, mpi_integer,   &
+         &                mpi_sum, mpi_comm_oce, ierr )
+#else
+      !-----------------------------------------------------------------------
+      ! For no-MPP just return input values
+      !-----------------------------------------------------------------------
+      kvalout = kvalin
+#endif
+      !
+   END SUBROUTINE obs_mpp_sum_integer
+
+
+   SUBROUTINE mpp_global_max( pval )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE mpp_global_or ***
+      !!          
+      !! ** Purpose : Get the maximum value across processors for a global 
+      !!              real array
+      !!
+      !! ** Method  : MPI allreduce
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      REAL(KIND=wp), DIMENSION(jpiglo,jpjglo), INTENT(inout) ::   pval
+      !
+      INTEGER :: ierr
+      !
+#if defined key_mpp_mpi
+      !
+INCLUDE 'mpif.h'
+      REAL(KIND=wp), DIMENSION(:,:), ALLOCATABLE ::   zcp
+      !!----------------------------------------------------------------------
+
+      ! Copy data for input to MPI
+
+      ALLOCATE( &
+         & zcp(jpiglo,jpjglo) &
+         & )
+      zcp(:,:) = pval(:,:)
+
+      ! Call the MPI library to find the coast lines globally
+
+      CALL mpi_allreduce( zcp, pval, jpiglo*jpjglo, mpivar, &
+         &                mpi_max, mpi_comm_oce, ierr )
+
+      DEALLOCATE( &
+         & zcp &
+         & )
+
+#else
+      ! no MPI: empty routine
+#endif
+      !
+   END SUBROUTINE mpp_global_max
+
+
+   SUBROUTINE mpp_alltoall_int( kno, kvalsin, kvalsout )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE mpp_allgatherv ***
+      !!          
+      !! ** Purpose : all to all.
+      !!
+      !! ** Method  : MPI alltoall
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                      , INTENT(in   ) ::   kno
+      INTEGER, DIMENSION(kno*jpnij), INTENT(in   ) ::   kvalsin
+      INTEGER, DIMENSION(kno*jpnij), INTENT(  out) ::   kvalsout
+      !!
+      INTEGER :: ierr
+      !
+#if defined key_mpp_mpi
+      !
+INCLUDE 'mpif.h'
+      !-----------------------------------------------------------------------
+      ! Call the MPI library to do the all to all operation of the data
+      !-----------------------------------------------------------------------
+      CALL mpi_alltoall( kvalsin,  kno, mpi_integer, &
+         &               kvalsout, kno, mpi_integer, &
+         &               mpi_comm_oce, ierr )
+#else
+      !-----------------------------------------------------------------------
+      ! For no-MPP just return input values
+      !-----------------------------------------------------------------------
+      kvalsout = kvalsin
+#endif
+      !
+   END SUBROUTINE mpp_alltoall_int
+
+
+   SUBROUTINE mpp_alltoallv_int( kvalsin, knoin , kinv , kvalsout,   &
+      &                                   knoout, koutv )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE mpp_alltoallv_int ***
+      !!          
+      !! ** Purpose : all to all (integer version).
+      !!
+      !! ** Method  : MPI alltoall
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in) :: knoin
+      INTEGER                   , INTENT(in) :: knoout
+      INTEGER, DIMENSION(jpnij)                 ::   kinv, koutv
+      INTEGER, DIMENSION(knoin) , INTENT(in   ) ::   kvalsin
+      INTEGER, DIMENSION(knoout), INTENT(  out) ::   kvalsout
+      !!
+      INTEGER :: ierr
+      INTEGER :: jproc
+      !
+#if defined key_mpp_mpi
+      !
+INCLUDE 'mpif.h'
+      INTEGER, DIMENSION(jpnij) ::   irdsp, isdsp
+      !-----------------------------------------------------------------------
+      ! Compute displacements
+      !-----------------------------------------------------------------------
+      irdsp(1) = 0
+      isdsp(1) = 0
+      DO jproc = 2, jpnij
+         isdsp(jproc) = isdsp(jproc-1) + kinv(jproc-1)
+         irdsp(jproc) = irdsp(jproc-1) + koutv(jproc-1)
+      END DO
+      !-----------------------------------------------------------------------
+      ! Call the MPI library to do the all to all operation of the data
+      !-----------------------------------------------------------------------
+      CALL mpi_alltoallv( kvalsin,  kinv,  isdsp, mpi_integer, &
+         &                kvalsout, koutv, irdsp, mpi_integer, &
+         &                mpi_comm_oce, ierr )
+#else
+      !-----------------------------------------------------------------------
+      ! For no-MPP just return input values
+      !-----------------------------------------------------------------------
+      kvalsout = kvalsin
+#endif
+      !
+   END SUBROUTINE mpp_alltoallv_int
+
+
+   SUBROUTINE mpp_alltoallv_real( pvalsin, knoin , kinv , pvalsout,   &
+      &                                    knoout, koutv )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE mpp_alltoallv_real ***
+      !!          
+      !! ** Purpose : all to all (integer version).
+      !!
+      !! ** Method  : MPI alltoall
+      !!
+      !! ** Action  : This does only work for MPI. 
+      !!              It does not work for SHMEM.
+      !!
+      !! References : http://www.mpi-forum.org
+      !!----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   ) :: knoin
+      INTEGER                    , INTENT(in   ) :: knoout
+      INTEGER , DIMENSION(jpnij)                 ::   kinv, koutv
+      REAL(wp), DIMENSION(knoin) , INTENT(in   ) ::   pvalsin
+      REAL(wp), DIMENSION(knoout), INTENT(  out) ::   pvalsout
+      !!
+      INTEGER :: ierr
+      INTEGER :: jproc
+      !
+#if defined key_mpp_mpi
+      !
+INCLUDE 'mpif.h'
+      INTEGER, DIMENSION(jpnij) ::   irdsp, isdsp
+      !!----------------------------------------------------------------------
+      !
+      !-----------------------------------------------------------------------
+      ! Compute displacements
+      !-----------------------------------------------------------------------
+      irdsp(1) = 0
+      isdsp(1) = 0
+      DO jproc = 2, jpnij
+         isdsp(jproc) = isdsp(jproc-1) + kinv(jproc-1)
+         irdsp(jproc) = irdsp(jproc-1) + koutv(jproc-1)
+      END DO
+      !-----------------------------------------------------------------------
+      ! Call the MPI library to do the all to all operation of the data
+      !-----------------------------------------------------------------------
+      CALL mpi_alltoallv( pvalsin,  kinv,  isdsp, mpivar, &
+         &                pvalsout, koutv, irdsp, mpivar, &
+         &                mpi_comm_oce, ierr )
+#else
+      !-----------------------------------------------------------------------
+      ! For no-MPP just return input values
+      !-----------------------------------------------------------------------
+      pvalsout = pvalsin
+#endif
+      !
+   END SUBROUTINE mpp_alltoallv_real
+
+   !!======================================================================
+END MODULE obs_mpp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_oper.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_oper.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_oper.F90	(revision 14097)
@@ -0,0 +1,977 @@
+MODULE obs_oper
+   !!======================================================================
+   !!                       ***  MODULE obs_oper  ***
+   !! Observation diagnostics: Observation operators for various observation
+   !!                          types
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_prof_opt :    Compute the model counterpart of profile data
+   !!   obs_surf_opt :    Compute the model counterpart of surface data
+   !!----------------------------------------------------------------------
+   USE obs_inter_sup                                        ! Interpolation support
+   USE obs_inter_h2d, ONLY : obs_int_h2d, obs_int_h2d_init  ! Horizontal interpolation to the obs pt
+   USE obs_averg_h2d, ONLY : obs_avg_h2d, obs_avg_h2d_init, obs_max_fpsize    ! Horizontal averaging to the obs footprint
+   USE obs_inter_z1d, ONLY : obs_int_z1d, obs_int_z1d_spl   ! Vertical interpolation to the obs pt
+   USE obs_const    , ONLY : obfillflt                      ! Obs fill value
+   USE dom_oce,       ONLY :   glamt, glamf, gphit, gphif   ! lat/lon of ocean grid-points
+   USE lib_mpp,       ONLY :   ctl_warn, ctl_stop           ! Warning and stopping routines
+   USE sbcdcy,        ONLY :   sbc_dcy, nday_qsr            ! For calculation of where it is night-time
+   USE obs_grid,      ONLY :   obs_level_search     
+   !
+   USE par_kind     , ONLY :   wp   ! Precision variables
+   USE in_out_manager               ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   obs_prof_opt   !: Compute the model counterpart of profile obs
+   PUBLIC   obs_surf_opt   !: Compute the model counterpart of surface obs
+
+   INTEGER, PARAMETER, PUBLIC ::   imaxavtypes = 20   !: Max number of daily avgd obs types
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE obs_prof_opt( prodatqc, kt, kpi, kpj, kpk,          &
+      &                     kit000, kdaystp,                      &
+      &                     pvar1, pvar2, pgdept, pgdepw,         &
+      &                     pmask1, pmask2,                       &  
+      &                     plam1, plam2, pphi1, pphi2,           &
+      &                     k1dint, k2dint, kdailyavtypes )
+      !!-----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_pro_opt  ***
+      !!
+      !! ** Purpose : Compute the model counterpart of profiles
+      !!              data by interpolating from the model grid to the 
+      !!              observation point.
+      !!
+      !! ** Method  : Linearly interpolate to each observation point using 
+      !!              the model values at the corners of the surrounding grid box.
+      !!
+      !!    First, a vertical profile of horizontally interpolated model
+      !!    now values is computed at the obs (lon, lat) point.
+      !!    Several horizontal interpolation schemes are available:
+      !!        - distance-weighted (great circle) (k2dint = 0)
+      !!        - distance-weighted (small angle)  (k2dint = 1)
+      !!        - bilinear (geographical grid)     (k2dint = 2)
+      !!        - bilinear (quadrilateral grid)    (k2dint = 3)
+      !!        - polynomial (quadrilateral grid)  (k2dint = 4)
+      !!
+      !!    Next, the vertical profile is interpolated to the
+      !!    data depth points. Two vertical interpolation schemes are
+      !!    available:
+      !!        - linear       (k1dint = 0)
+      !!        - Cubic spline (k1dint = 1)
+      !!
+      !!    For the cubic spline the 2nd derivative of the interpolating 
+      !!    polynomial is computed before entering the vertical interpolation 
+      !!    routine.
+      !!
+      !!    If the logical is switched on, the model equivalent is
+      !!    a daily mean model temperature field. So, we first compute
+      !!    the mean, then interpolate only at the end of the day.
+      !!
+      !!    Note: in situ temperature observations must be converted
+      !!    to potential temperature (the model variable) prior to
+      !!    assimilation. 
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!      ! 97-11 (A. Weaver, S. Ricci, N. Daget)
+      !!      ! 06-03 (G. Smith) NEMOVAR migration
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!      ! 07-01 (K. Mogensen) Merge of temperature and salinity
+      !!      ! 07-03 (K. Mogensen) General handling of profiles
+      !!      ! 15-02 (M. Martin) Combined routine for all profile types
+      !!      ! 17-02 (M. Martin) Include generalised vertical coordinate changes
+      !!-----------------------------------------------------------------------
+      USE obs_profiles_def ! Definition of storage space for profile obs.
+
+      IMPLICIT NONE
+
+      TYPE(obs_prof), INTENT(inout) ::   prodatqc        ! Subset of profile data passing QC
+      INTEGER       , INTENT(in   ) ::   kt              ! Time step
+      INTEGER       , INTENT(in   ) ::   kpi, kpj, kpk   ! Model grid parameters
+      INTEGER       , INTENT(in   ) ::   kit000          ! Number of the first time step (kit000-1 = restart time)
+      INTEGER       , INTENT(in   ) ::   k1dint          ! Vertical interpolation type (see header)
+      INTEGER       , INTENT(in   ) ::   k2dint          ! Horizontal interpolation type (see header)
+      INTEGER       , INTENT(in   ) ::   kdaystp         ! Number of time steps per day
+      REAL(KIND=wp) , INTENT(in   ), DIMENSION(kpi,kpj,kpk) ::   pvar1 , pvar2    ! Model field     1 and 2
+      REAL(KIND=wp) , INTENT(in   ), DIMENSION(kpi,kpj,kpk) ::   pmask1, pmask2   ! Land-sea mask   1 and 2
+      REAL(KIND=wp) , INTENT(in   ), DIMENSION(kpi,kpj)     ::   plam1 , plam2    ! Model longitude 1 and 2
+      REAL(KIND=wp) , INTENT(in   ), DIMENSION(kpi,kpj)     ::   pphi1 , pphi2    ! Model latitudes 1 and 2
+      REAL(KIND=wp) , INTENT(in   ), DIMENSION(kpi,kpj,kpk) ::   pgdept, pgdepw   ! depth of T and W levels 
+      INTEGER, DIMENSION(imaxavtypes), OPTIONAL ::   kdailyavtypes             ! Types for daily averages
+
+      !! * Local declarations
+      INTEGER ::   ji
+      INTEGER ::   jj
+      INTEGER ::   jk
+      INTEGER ::   jobs
+      INTEGER ::   inrc
+      INTEGER ::   ipro
+      INTEGER ::   idayend
+      INTEGER ::   ista
+      INTEGER ::   iend
+      INTEGER ::   iobs
+      INTEGER ::   iin, ijn, ikn, ik   ! looping indices over interpolation nodes 
+      INTEGER ::   inum_obs
+      INTEGER, DIMENSION(imaxavtypes) :: &
+         & idailyavtypes
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdi1, &
+         & igrdi2, &
+         & igrdj1, &
+         & igrdj2
+      INTEGER, ALLOCATABLE, DIMENSION(:) :: iv_indic
+
+      REAL(KIND=wp) :: zlam
+      REAL(KIND=wp) :: zphi
+      REAL(KIND=wp) :: zdaystp
+      REAL(KIND=wp), DIMENSION(kpk) :: &
+         & zobsmask1, &
+         & zobsmask2, &
+         & zobsk,    &
+         & zobs2k
+      REAL(KIND=wp), DIMENSION(2,2,1) :: &
+         & zweig1, &
+         & zweig2, &
+         & zweig
+      REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE :: &
+         & zmask1, &
+         & zmask2, &
+         & zint1,  &
+         & zint2,  &
+         & zinm1,  &
+         & zinm2,  &
+         & zgdept, & 
+         & zgdepw
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zglam1, &
+         & zglam2, &
+         & zgphi1, &
+         & zgphi2
+      REAL(KIND=wp), DIMENSION(1) :: zmsk_1, zmsk_2   
+      REAL(KIND=wp), DIMENSION(:,:,:), ALLOCATABLE :: interp_corner
+
+      LOGICAL :: ld_dailyav
+
+      !------------------------------------------------------------------------
+      ! Local initialization 
+      !------------------------------------------------------------------------
+      ! Record and data counters
+      inrc = kt - kit000 + 2
+      ipro = prodatqc%npstp(inrc)
+
+      ! Daily average types
+      ld_dailyav = .FALSE.
+      IF ( PRESENT(kdailyavtypes) ) THEN
+         idailyavtypes(:) = kdailyavtypes(:)
+         IF ( ANY (idailyavtypes(:) /= -1) ) ld_dailyav = .TRUE.
+      ELSE
+         idailyavtypes(:) = -1
+      ENDIF
+
+      ! Daily means are calculated for values over timesteps:
+      !  [1 <= kt <= kdaystp], [kdaystp+1 <= kt <= 2*kdaystp], ...
+      idayend = MOD( kt - kit000 + 1, kdaystp )
+
+      IF ( ld_dailyav ) THEN
+
+         ! Initialize daily mean for first timestep of the day
+         IF ( idayend == 1 .OR. kt == 0 ) THEN
+            DO jk = 1, jpk
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     prodatqc%vdmean(ji,jj,jk,1) = 0.0
+                     prodatqc%vdmean(ji,jj,jk,2) = 0.0
+                  END DO
+               END DO
+            END DO
+         ENDIF
+
+         DO jk = 1, jpk
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! Increment field 1 for computing daily mean
+                  prodatqc%vdmean(ji,jj,jk,1) = prodatqc%vdmean(ji,jj,jk,1) &
+                     &                        + pvar1(ji,jj,jk)
+                  ! Increment field 2 for computing daily mean
+                  prodatqc%vdmean(ji,jj,jk,2) = prodatqc%vdmean(ji,jj,jk,2) &
+                     &                        + pvar2(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+
+         ! Compute the daily mean at the end of day
+         zdaystp = 1.0 / REAL( kdaystp )
+         IF ( idayend == 0 ) THEN
+            IF (lwp) WRITE(numout,*) 'Calculating prodatqc%vdmean on time-step: ',kt
+            CALL FLUSH(numout)
+            DO jk = 1, jpk
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     prodatqc%vdmean(ji,jj,jk,1) = prodatqc%vdmean(ji,jj,jk,1) &
+                        &                        * zdaystp
+                     prodatqc%vdmean(ji,jj,jk,2) = prodatqc%vdmean(ji,jj,jk,2) &
+                        &                        * zdaystp
+                  END DO
+               END DO
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Get the data for interpolation
+      ALLOCATE( &
+         & igrdi1(2,2,ipro),      &
+         & igrdi2(2,2,ipro),      &
+         & igrdj1(2,2,ipro),      &
+         & igrdj2(2,2,ipro),      &
+         & zglam1(2,2,ipro),      &
+         & zglam2(2,2,ipro),      &
+         & zgphi1(2,2,ipro),      &
+         & zgphi2(2,2,ipro),      &
+         & zmask1(2,2,kpk,ipro),  &
+         & zmask2(2,2,kpk,ipro),  &
+         & zint1(2,2,kpk,ipro),   &
+         & zint2(2,2,kpk,ipro),   &
+         & zgdept(2,2,kpk,ipro),  & 
+         & zgdepw(2,2,kpk,ipro)   & 
+         & )
+
+      DO jobs = prodatqc%nprofup + 1, prodatqc%nprofup + ipro
+         iobs = jobs - prodatqc%nprofup
+         igrdi1(1,1,iobs) = prodatqc%mi(jobs,1)-1
+         igrdj1(1,1,iobs) = prodatqc%mj(jobs,1)-1
+         igrdi1(1,2,iobs) = prodatqc%mi(jobs,1)-1
+         igrdj1(1,2,iobs) = prodatqc%mj(jobs,1)
+         igrdi1(2,1,iobs) = prodatqc%mi(jobs,1)
+         igrdj1(2,1,iobs) = prodatqc%mj(jobs,1)-1
+         igrdi1(2,2,iobs) = prodatqc%mi(jobs,1)
+         igrdj1(2,2,iobs) = prodatqc%mj(jobs,1)
+         igrdi2(1,1,iobs) = prodatqc%mi(jobs,2)-1
+         igrdj2(1,1,iobs) = prodatqc%mj(jobs,2)-1
+         igrdi2(1,2,iobs) = prodatqc%mi(jobs,2)-1
+         igrdj2(1,2,iobs) = prodatqc%mj(jobs,2)
+         igrdi2(2,1,iobs) = prodatqc%mi(jobs,2)
+         igrdj2(2,1,iobs) = prodatqc%mj(jobs,2)-1
+         igrdi2(2,2,iobs) = prodatqc%mi(jobs,2)
+         igrdj2(2,2,iobs) = prodatqc%mj(jobs,2)
+      END DO
+
+      ! Initialise depth arrays
+      zgdept(:,:,:,:) = 0.0
+      zgdepw(:,:,:,:) = 0.0
+
+      CALL obs_int_comm_2d( 2, 2, ipro, kpi, kpj, igrdi1, igrdj1, plam1, zglam1 )
+      CALL obs_int_comm_2d( 2, 2, ipro, kpi, kpj, igrdi1, igrdj1, pphi1, zgphi1 )
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi1, igrdj1, pmask1, zmask1 )
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi1, igrdj1, pvar1,   zint1 )
+      
+      CALL obs_int_comm_2d( 2, 2, ipro, kpi, kpj, igrdi2, igrdj2, plam2, zglam2 )
+      CALL obs_int_comm_2d( 2, 2, ipro, kpi, kpj, igrdi2, igrdj2, pphi2, zgphi2 )
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi2, igrdj2, pmask2, zmask2 )
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi2, igrdj2, pvar2,   zint2 )
+
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi1, igrdj1, pgdept, zgdept ) 
+      CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi1, igrdj1, pgdepw, zgdepw ) 
+
+      ! At the end of the day also get interpolated means
+      IF ( ld_dailyav .AND. idayend == 0 ) THEN
+
+         ALLOCATE( &
+            & zinm1(2,2,kpk,ipro),  &
+            & zinm2(2,2,kpk,ipro)   &
+            & )
+
+         CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi1, igrdj1, &
+            &                  prodatqc%vdmean(:,:,:,1), zinm1 )
+         CALL obs_int_comm_3d( 2, 2, ipro, kpi, kpj, kpk, igrdi2, igrdj2, &
+            &                  prodatqc%vdmean(:,:,:,2), zinm2 )
+
+      ENDIF
+
+      ! Return if no observations to process 
+      ! Has to be done after comm commands to ensure processors 
+      ! stay in sync 
+      IF ( ipro == 0 ) RETURN 
+
+      DO jobs = prodatqc%nprofup + 1, prodatqc%nprofup + ipro
+
+         iobs = jobs - prodatqc%nprofup
+
+         IF ( kt /= prodatqc%mstp(jobs) ) THEN
+
+            IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) ' E R R O R : Observation',              &
+                  &            ' time step is not consistent with the', &
+                  &            ' model time step'
+               WRITE(numout,*) ' ========='
+               WRITE(numout,*)
+               WRITE(numout,*) ' Record  = ', jobs,                    &
+                  &            ' kt      = ', kt,                      &
+                  &            ' mstp    = ', prodatqc%mstp(jobs), &
+                  &            ' ntyp    = ', prodatqc%ntyp(jobs)
+            ENDIF
+            CALL ctl_stop( 'obs_pro_opt', 'Inconsistent time' )
+         ENDIF
+
+         zlam = prodatqc%rlam(jobs)
+         zphi = prodatqc%rphi(jobs)
+
+         ! Horizontal weights 
+         ! Masked values are calculated later.  
+         IF ( prodatqc%npvend(jobs,1) > 0 ) THEN
+
+            CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,     &
+               &                   zglam1(:,:,iobs), zgphi1(:,:,iobs), &
+               &                   zmask1(:,:,1,iobs), zweig1, zmsk_1 )
+
+         ENDIF
+
+         IF ( prodatqc%npvend(jobs,2) > 0 ) THEN
+
+            CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,     &
+               &                   zglam2(:,:,iobs), zgphi2(:,:,iobs), &
+               &                   zmask2(:,:,1,iobs), zweig2, zmsk_2 )
+ 
+         ENDIF
+
+         IF ( prodatqc%npvend(jobs,1) > 0 ) THEN
+
+            zobsk(:) = obfillflt
+
+            IF ( ANY (idailyavtypes(:) == prodatqc%ntyp(jobs)) ) THEN
+
+               IF ( idayend == 0 )  THEN
+                  ! Daily averaged data
+
+                  ! vertically interpolate all 4 corners 
+                  ista = prodatqc%npvsta(jobs,1) 
+                  iend = prodatqc%npvend(jobs,1) 
+                  inum_obs = iend - ista + 1 
+                  ALLOCATE(interp_corner(2,2,inum_obs),iv_indic(inum_obs)) 
+
+                  DO iin=1,2 
+                     DO ijn=1,2 
+
+                        IF ( k1dint == 1 ) THEN 
+                           CALL obs_int_z1d_spl( kpk, & 
+                              &     zinm1(iin,ijn,:,iobs), & 
+                              &     zobs2k, zgdept(iin,ijn,:,iobs), & 
+                              &     zmask1(iin,ijn,:,iobs)) 
+                        ENDIF 
+       
+                        CALL obs_level_search(kpk, & 
+                           &    zgdept(iin,ijn,:,iobs), & 
+                           &    inum_obs, prodatqc%var(1)%vdep(ista:iend), & 
+                           &    iv_indic) 
+
+                        CALL obs_int_z1d(kpk, iv_indic, k1dint, inum_obs, & 
+                           &    prodatqc%var(1)%vdep(ista:iend), & 
+                           &    zinm1(iin,ijn,:,iobs), & 
+                           &    zobs2k, interp_corner(iin,ijn,:), & 
+                           &    zgdept(iin,ijn,:,iobs), & 
+                           &    zmask1(iin,ijn,:,iobs)) 
+       
+                     ENDDO 
+                  ENDDO 
+
+               ENDIF !idayend
+
+            ELSE   
+
+               ! Point data 
+     
+               ! vertically interpolate all 4 corners 
+               ista = prodatqc%npvsta(jobs,1) 
+               iend = prodatqc%npvend(jobs,1) 
+               inum_obs = iend - ista + 1 
+               ALLOCATE(interp_corner(2,2,inum_obs), iv_indic(inum_obs)) 
+               DO iin=1,2  
+                  DO ijn=1,2 
+                    
+                     IF ( k1dint == 1 ) THEN 
+                        CALL obs_int_z1d_spl( kpk, & 
+                           &    zint1(iin,ijn,:,iobs),& 
+                           &    zobs2k, zgdept(iin,ijn,:,iobs), & 
+                           &    zmask1(iin,ijn,:,iobs)) 
+  
+                     ENDIF 
+       
+                     CALL obs_level_search(kpk, & 
+                         &        zgdept(iin,ijn,:,iobs),& 
+                         &        inum_obs, prodatqc%var(1)%vdep(ista:iend), & 
+                         &        iv_indic) 
+
+                     CALL obs_int_z1d(kpk, iv_indic, k1dint, inum_obs,     & 
+                         &          prodatqc%var(1)%vdep(ista:iend),     & 
+                         &          zint1(iin,ijn,:,iobs),            & 
+                         &          zobs2k,interp_corner(iin,ijn,:), & 
+                         &          zgdept(iin,ijn,:,iobs),         & 
+                         &          zmask1(iin,ijn,:,iobs) )      
+         
+                  ENDDO 
+               ENDDO 
+             
+            ENDIF 
+
+            !------------------------------------------------------------- 
+            ! Compute the horizontal interpolation for every profile level 
+            !------------------------------------------------------------- 
+             
+            DO ikn=1,inum_obs 
+               iend=ista+ikn-1
+                  
+               zweig(:,:,1) = 0._wp 
+   
+               ! This code forces the horizontal weights to be  
+               ! zero IF the observation is below the bottom of the  
+               ! corners of the interpolation nodes, Or if it is in  
+               ! the mask. This is important for observations near  
+               ! steep bathymetry 
+               DO iin=1,2 
+                  DO ijn=1,2 
+     
+                     depth_loop1: DO ik=kpk,2,-1 
+                        IF(zmask1(iin,ijn,ik-1,iobs ) > 0.9 )THEN   
+                            
+                           zweig(iin,ijn,1) = &  
+                              & zweig1(iin,ijn,1) * & 
+                              & MAX( SIGN(1._wp,(zgdepw(iin,ijn,ik,iobs) ) & 
+                              &  - prodatqc%var(1)%vdep(iend)),0._wp) 
+                            
+                           EXIT depth_loop1 
+
+                        ENDIF 
+
+                     ENDDO depth_loop1 
+     
+                  ENDDO 
+               ENDDO 
+   
+               CALL obs_int_h2d( 1, 1, zweig, interp_corner(:,:,ikn), & 
+                  &              prodatqc%var(1)%vmod(iend:iend) ) 
+
+                  ! Set QC flag for any observations found below the bottom
+                  ! needed as the check here is more strict than that in obs_prep
+               IF (sum(zweig) == 0.0_wp) prodatqc%var(1)%nvqc(iend:iend)=4
+ 
+            ENDDO 
+ 
+            DEALLOCATE(interp_corner,iv_indic) 
+          
+         ENDIF 
+
+         ! For the second variable
+         IF ( prodatqc%npvend(jobs,2) > 0 ) THEN
+
+            zobsk(:) = obfillflt
+
+            IF ( ANY (idailyavtypes(:) == prodatqc%ntyp(jobs)) ) THEN
+
+               IF ( idayend == 0 )  THEN
+                  ! Daily averaged data
+
+                  ! vertically interpolate all 4 corners 
+                  ista = prodatqc%npvsta(jobs,2) 
+                  iend = prodatqc%npvend(jobs,2) 
+                  inum_obs = iend - ista + 1 
+                  ALLOCATE(interp_corner(2,2,inum_obs),iv_indic(inum_obs)) 
+
+                  DO iin=1,2 
+                     DO ijn=1,2 
+
+                        IF ( k1dint == 1 ) THEN 
+                           CALL obs_int_z1d_spl( kpk, & 
+                              &     zinm2(iin,ijn,:,iobs), & 
+                              &     zobs2k, zgdept(iin,ijn,:,iobs), & 
+                              &     zmask2(iin,ijn,:,iobs)) 
+                        ENDIF 
+       
+                        CALL obs_level_search(kpk, & 
+                           &    zgdept(iin,ijn,:,iobs), & 
+                           &    inum_obs, prodatqc%var(2)%vdep(ista:iend), & 
+                           &    iv_indic) 
+
+                        CALL obs_int_z1d(kpk, iv_indic, k1dint, inum_obs, & 
+                           &    prodatqc%var(2)%vdep(ista:iend), & 
+                           &    zinm2(iin,ijn,:,iobs), & 
+                           &    zobs2k, interp_corner(iin,ijn,:), & 
+                           &    zgdept(iin,ijn,:,iobs), & 
+                           &    zmask2(iin,ijn,:,iobs)) 
+       
+                     ENDDO 
+                  ENDDO 
+
+               ENDIF !idayend
+
+            ELSE   
+
+               ! Point data 
+     
+               ! vertically interpolate all 4 corners 
+               ista = prodatqc%npvsta(jobs,2) 
+               iend = prodatqc%npvend(jobs,2) 
+               inum_obs = iend - ista + 1 
+               ALLOCATE(interp_corner(2,2,inum_obs), iv_indic(inum_obs)) 
+               DO iin=1,2  
+                  DO ijn=1,2 
+                    
+                     IF ( k1dint == 1 ) THEN 
+                        CALL obs_int_z1d_spl( kpk, & 
+                           &    zint2(iin,ijn,:,iobs),& 
+                           &    zobs2k, zgdept(iin,ijn,:,iobs), & 
+                           &    zmask2(iin,ijn,:,iobs)) 
+  
+                     ENDIF 
+       
+                     CALL obs_level_search(kpk, & 
+                         &        zgdept(iin,ijn,:,iobs),& 
+                         &        inum_obs, prodatqc%var(2)%vdep(ista:iend), & 
+                         &        iv_indic) 
+
+                     CALL obs_int_z1d(kpk, iv_indic, k1dint, inum_obs,     & 
+                         &          prodatqc%var(2)%vdep(ista:iend),     & 
+                         &          zint2(iin,ijn,:,iobs),            & 
+                         &          zobs2k,interp_corner(iin,ijn,:), & 
+                         &          zgdept(iin,ijn,:,iobs),         & 
+                         &          zmask2(iin,ijn,:,iobs) )      
+         
+                  ENDDO 
+               ENDDO 
+             
+            ENDIF 
+
+            !------------------------------------------------------------- 
+            ! Compute the horizontal interpolation for every profile level 
+            !------------------------------------------------------------- 
+             
+            DO ikn=1,inum_obs 
+               iend=ista+ikn-1
+                  
+               zweig(:,:,1) = 0._wp 
+   
+               ! This code forces the horizontal weights to be  
+               ! zero IF the observation is below the bottom of the  
+               ! corners of the interpolation nodes, Or if it is in  
+               ! the mask. This is important for observations near  
+               ! steep bathymetry 
+               DO iin=1,2 
+                  DO ijn=1,2 
+     
+                     depth_loop2: DO ik=kpk,2,-1 
+                        IF(zmask2(iin,ijn,ik-1,iobs ) > 0.9 )THEN   
+                            
+                           zweig(iin,ijn,1) = &  
+                              & zweig2(iin,ijn,1) * & 
+                              & MAX( SIGN(1._wp,(zgdepw(iin,ijn,ik,iobs) ) & 
+                              &  - prodatqc%var(2)%vdep(iend)),0._wp) 
+                            
+                           EXIT depth_loop2 
+
+                        ENDIF 
+
+                     ENDDO depth_loop2 
+     
+                  ENDDO 
+               ENDDO 
+   
+               CALL obs_int_h2d( 1, 1, zweig, interp_corner(:,:,ikn), & 
+                  &              prodatqc%var(2)%vmod(iend:iend) ) 
+
+                  ! Set QC flag for any observations found below the bottom
+                  ! needed as the check here is more strict than that in obs_prep
+               IF (sum(zweig) == 0.0_wp) prodatqc%var(2)%nvqc(iend:iend)=4
+ 
+            ENDDO 
+ 
+            DEALLOCATE(interp_corner,iv_indic) 
+          
+         ENDIF 
+
+      ENDDO
+
+      ! Deallocate the data for interpolation
+      DEALLOCATE( &
+         & igrdi1, &
+         & igrdi2, &
+         & igrdj1, &
+         & igrdj2, &
+         & zglam1, &
+         & zglam2, &
+         & zgphi1, &
+         & zgphi2, &
+         & zmask1, &
+         & zmask2, &
+         & zint1,  &
+         & zint2,  &
+         & zgdept, &
+         & zgdepw  &
+         & )
+
+      ! At the end of the day also get interpolated means
+      IF ( ld_dailyav .AND. idayend == 0 ) THEN
+         DEALLOCATE( &
+            & zinm1,  &
+            & zinm2   &
+            & )
+      ENDIF
+
+      prodatqc%nprofup = prodatqc%nprofup + ipro 
+
+   END SUBROUTINE obs_prof_opt
+
+   SUBROUTINE obs_surf_opt( surfdataqc, kt, kpi, kpj,            &
+      &                     kit000, kdaystp, psurf, psurfmask,   &
+      &                     k2dint, ldnightav, plamscl, pphiscl, &
+      &                     lindegrees )
+
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_surf_opt  ***
+      !!
+      !! ** Purpose : Compute the model counterpart of surface
+      !!              data by interpolating from the model grid to the 
+      !!              observation point.
+      !!
+      !! ** Method  : Linearly interpolate to each observation point using 
+      !!              the model values at the corners of the surrounding grid box.
+      !!
+      !!    The new model value is first computed at the obs (lon, lat) point.
+      !!
+      !!    Several horizontal interpolation schemes are available:
+      !!        - distance-weighted (great circle) (k2dint = 0)
+      !!        - distance-weighted (small angle)  (k2dint = 1)
+      !!        - bilinear (geographical grid)     (k2dint = 2)
+      !!        - bilinear (quadrilateral grid)    (k2dint = 3)
+      !!        - polynomial (quadrilateral grid)  (k2dint = 4)
+      !!
+      !!    Two horizontal averaging schemes are also available:
+      !!        - weighted radial footprint        (k2dint = 5)
+      !!        - weighted rectangular footprint   (k2dint = 6)
+      !!
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!      ! 07-03 (A. Weaver)
+      !!      ! 15-02 (M. Martin) Combined routine for surface types
+      !!      ! 17-03 (M. Martin) Added horizontal averaging options
+      !!-----------------------------------------------------------------------
+      USE obs_surf_def  ! Definition of storage space for surface observations
+
+      IMPLICIT NONE
+
+      TYPE(obs_surf), INTENT(INOUT) :: &
+         & surfdataqc                  ! Subset of surface data passing QC
+      INTEGER, INTENT(IN) :: kt        ! Time step
+      INTEGER, INTENT(IN) :: kpi       ! Model grid parameters
+      INTEGER, INTENT(IN) :: kpj
+      INTEGER, INTENT(IN) :: kit000    ! Number of the first time step 
+                                       !   (kit000-1 = restart time)
+      INTEGER, INTENT(IN) :: kdaystp   ! Number of time steps per day
+      INTEGER, INTENT(IN) :: k2dint    ! Horizontal interpolation type (see header)
+      REAL(wp), INTENT(IN), DIMENSION(kpi,kpj) :: &
+         & psurf,  &                   ! Model surface field
+         & psurfmask                   ! Land-sea mask
+      LOGICAL, INTENT(IN) :: ldnightav ! Logical for averaging night-time data
+      REAL(KIND=wp), INTENT(IN) :: &
+         & plamscl, &                  ! Diameter in metres of obs footprint in E/W, N/S directions
+         & pphiscl                     ! This is the full width (rather than half-width)
+      LOGICAL, INTENT(IN) :: &
+         & lindegrees                  ! T=> plamscl and pphiscl are specified in degrees, F=> in metres
+
+      !! * Local declarations
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jobs
+      INTEGER :: inrc
+      INTEGER :: isurf
+      INTEGER :: iobs
+      INTEGER :: imaxifp, imaxjfp
+      INTEGER :: imodi, imodj
+      INTEGER :: idayend
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdi,   &
+         & igrdj,   &
+         & igrdip1, &
+         & igrdjp1
+      INTEGER, DIMENSION(:,:), SAVE, ALLOCATABLE :: &
+         & icount_night,      &
+         & imask_night
+      REAL(wp) :: zlam
+      REAL(wp) :: zphi
+      REAL(wp), DIMENSION(1) :: zext, zobsmask
+      REAL(wp) :: zdaystp
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zweig,  &
+         & zmask,  &
+         & zsurf,  &
+         & zsurfm, &
+         & zsurftmp, &
+         & zglam,  &
+         & zgphi,  &
+         & zglamf, &
+         & zgphif
+
+      REAL(wp), DIMENSION(:,:), SAVE, ALLOCATABLE :: &
+         & zintmp,  &
+         & zouttmp, &
+         & zmeanday    ! to compute model sst in region of 24h daylight (pole)
+
+      !------------------------------------------------------------------------
+      ! Local initialization 
+      !------------------------------------------------------------------------
+      ! Record and data counters
+      inrc = kt - kit000 + 2
+      isurf = surfdataqc%nsstp(inrc)
+
+      ! Work out the maximum footprint size for the 
+      ! interpolation/averaging in model grid-points - has to be even.
+
+      CALL obs_max_fpsize( k2dint, plamscl, pphiscl, lindegrees, psurfmask, imaxifp, imaxjfp )
+
+
+      IF ( ldnightav ) THEN
+
+      ! Initialize array for night mean
+         IF ( kt == 0 ) THEN
+            ALLOCATE ( icount_night(kpi,kpj) )
+            ALLOCATE ( imask_night(kpi,kpj) )
+            ALLOCATE ( zintmp(kpi,kpj) )
+            ALLOCATE ( zouttmp(kpi,kpj) )
+            ALLOCATE ( zmeanday(kpi,kpj) )
+            nday_qsr = -1   ! initialisation flag for nbc_dcy
+         ENDIF
+
+         ! Night-time means are calculated for night-time values over timesteps:
+         !  [1 <= kt <= kdaystp], [kdaystp+1 <= kt <= 2*kdaystp], .....
+         idayend = MOD( kt - kit000 + 1, kdaystp )
+
+         ! Initialize night-time mean for first timestep of the day
+         IF ( idayend == 1 .OR. kt == 0 ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  surfdataqc%vdmean(ji,jj) = 0.0
+                  zmeanday(ji,jj) = 0.0
+                  icount_night(ji,jj) = 0
+               END DO
+            END DO
+         ENDIF
+
+         zintmp(:,:) = 0.0
+         zouttmp(:,:) = sbc_dcy( zintmp(:,:), .TRUE. )
+         imask_night(:,:) = INT( zouttmp(:,:) )
+
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! Increment the temperature field for computing night mean and counter
+               surfdataqc%vdmean(ji,jj) = surfdataqc%vdmean(ji,jj)  &
+                      &                    + psurf(ji,jj) * REAL( imask_night(ji,jj) )
+               zmeanday(ji,jj)          = zmeanday(ji,jj) + psurf(ji,jj)
+               icount_night(ji,jj)      = icount_night(ji,jj) + imask_night(ji,jj)
+            END DO
+         END DO
+
+         ! Compute the night-time mean at the end of the day
+         zdaystp = 1.0 / REAL( kdaystp )
+         IF ( idayend == 0 ) THEN
+            IF (lwp) WRITE(numout,*) 'Calculating surfdataqc%vdmean on time-step: ',kt
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! Test if "no night" point
+                  IF ( icount_night(ji,jj) > 0 ) THEN
+                     surfdataqc%vdmean(ji,jj) = surfdataqc%vdmean(ji,jj) &
+                       &                        / REAL( icount_night(ji,jj) )
+                  ELSE
+                     !At locations where there is no night (e.g. poles),
+                     ! calculate daily mean instead of night-time mean.
+                     surfdataqc%vdmean(ji,jj) = zmeanday(ji,jj) * zdaystp
+                  ENDIF
+               END DO
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Get the data for interpolation
+
+      ALLOCATE( &
+         & zweig(imaxifp,imaxjfp,1),      &
+         & igrdi(imaxifp,imaxjfp,isurf), &
+         & igrdj(imaxifp,imaxjfp,isurf), &
+         & zglam(imaxifp,imaxjfp,isurf), &
+         & zgphi(imaxifp,imaxjfp,isurf), &
+         & zmask(imaxifp,imaxjfp,isurf), &
+         & zsurf(imaxifp,imaxjfp,isurf), &
+         & zsurftmp(imaxifp,imaxjfp,isurf),  &
+         & zglamf(imaxifp+1,imaxjfp+1,isurf), &
+         & zgphif(imaxifp+1,imaxjfp+1,isurf), &
+         & igrdip1(imaxifp+1,imaxjfp+1,isurf), &
+         & igrdjp1(imaxifp+1,imaxjfp+1,isurf) &
+         & )
+
+      DO jobs = surfdataqc%nsurfup + 1, surfdataqc%nsurfup + isurf
+         iobs = jobs - surfdataqc%nsurfup
+         DO ji = 0, imaxifp
+            imodi = surfdataqc%mi(jobs) - int(imaxifp/2) + ji - 1
+            !
+            !Deal with wrap around in longitude
+            IF ( imodi < 1      ) imodi = imodi + jpiglo
+            IF ( imodi > jpiglo ) imodi = imodi - jpiglo
+            !
+            DO jj = 0, imaxjfp
+               imodj = surfdataqc%mj(jobs) - int(imaxjfp/2) + jj - 1
+               !If model values are out of the domain to the north/south then
+               !set them to be the edge of the domain
+               IF ( imodj < 1      ) imodj = 1
+               IF ( imodj > jpjglo ) imodj = jpjglo
+               !
+               igrdip1(ji+1,jj+1,iobs) = imodi
+               igrdjp1(ji+1,jj+1,iobs) = imodj
+               !
+               IF ( ji >= 1 .AND. jj >= 1 ) THEN
+                  igrdi(ji,jj,iobs) = imodi
+                  igrdj(ji,jj,iobs) = imodj
+               ENDIF
+               !
+            END DO
+         END DO
+      END DO
+
+      CALL obs_int_comm_2d( imaxifp, imaxjfp, isurf, kpi, kpj, &
+         &                  igrdi, igrdj, glamt, zglam )
+      CALL obs_int_comm_2d( imaxifp, imaxjfp, isurf, kpi, kpj, &
+         &                  igrdi, igrdj, gphit, zgphi )
+      CALL obs_int_comm_2d( imaxifp, imaxjfp, isurf, kpi, kpj, &
+         &                  igrdi, igrdj, psurfmask, zmask )
+      CALL obs_int_comm_2d( imaxifp, imaxjfp, isurf, kpi, kpj, &
+         &                  igrdi, igrdj, psurf, zsurf )
+      CALL obs_int_comm_2d( imaxifp+1, imaxjfp+1, isurf, kpi, kpj, &
+         &                  igrdip1, igrdjp1, glamf, zglamf )
+      CALL obs_int_comm_2d( imaxifp+1, imaxjfp+1, isurf, kpi, kpj, &
+         &                  igrdip1, igrdjp1, gphif, zgphif )
+
+      ! At the end of the day get interpolated means
+      IF ( idayend == 0 .AND. ldnightav ) THEN
+
+         ALLOCATE( &
+            & zsurfm(imaxifp,imaxjfp,isurf)  &
+            & )
+
+         CALL obs_int_comm_2d( imaxifp,imaxjfp, isurf, kpi, kpj, igrdi, igrdj, &
+            &               surfdataqc%vdmean(:,:), zsurfm )
+
+      ENDIF
+
+      ! Loop over observations
+      DO jobs = surfdataqc%nsurfup + 1, surfdataqc%nsurfup + isurf
+
+         iobs = jobs - surfdataqc%nsurfup
+
+         IF ( kt /= surfdataqc%mstp(jobs) ) THEN
+
+            IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) ' E R R O R : Observation',              &
+                  &            ' time step is not consistent with the', &
+                  &            ' model time step'
+               WRITE(numout,*) ' ========='
+               WRITE(numout,*)
+               WRITE(numout,*) ' Record  = ', jobs,                &
+                  &            ' kt      = ', kt,                  &
+                  &            ' mstp    = ', surfdataqc%mstp(jobs), &
+                  &            ' ntyp    = ', surfdataqc%ntyp(jobs)
+            ENDIF
+            CALL ctl_stop( 'obs_surf_opt', 'Inconsistent time' )
+
+         ENDIF
+
+         zlam = surfdataqc%rlam(jobs)
+         zphi = surfdataqc%rphi(jobs)
+
+         IF ( ldnightav .AND. idayend == 0 ) THEN
+            ! Night-time averaged data
+            zsurftmp(:,:,iobs) = zsurfm(:,:,iobs)
+         ELSE
+            zsurftmp(:,:,iobs) = zsurf(:,:,iobs)
+         ENDIF
+
+         IF ( k2dint <= 4 ) THEN
+
+            ! Get weights to interpolate the model value to the observation point
+            CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,         &
+               &                   zglam(:,:,iobs), zgphi(:,:,iobs), &
+               &                   zmask(:,:,iobs), zweig, zobsmask )
+
+            ! Interpolate the model value to the observation point 
+            CALL obs_int_h2d( 1, 1, zweig, zsurftmp(:,:,iobs), zext )
+
+         ELSE
+
+            ! Get weights to average the model SLA to the observation footprint
+            CALL obs_avg_h2d_init( 1, 1, imaxifp, imaxjfp, k2dint, zlam,  zphi, &
+               &                   zglam(:,:,iobs), zgphi(:,:,iobs), &
+               &                   zglamf(:,:,iobs), zgphif(:,:,iobs), &
+               &                   zmask(:,:,iobs), plamscl, pphiscl, &
+               &                   lindegrees, zweig, zobsmask )
+
+            ! Average the model SST to the observation footprint
+            CALL obs_avg_h2d( 1, 1, imaxifp, imaxjfp, &
+               &              zweig, zsurftmp(:,:,iobs),  zext )
+
+         ENDIF
+
+         IF ( TRIM(surfdataqc%cvars(1)) == 'SLA' .AND. surfdataqc%nextra == 2 ) THEN
+            ! ... Remove the MDT from the SSH at the observation point to get the SLA
+            surfdataqc%rext(jobs,1) = zext(1)
+            surfdataqc%rmod(jobs,1) = surfdataqc%rext(jobs,1) - surfdataqc%rext(jobs,2)
+         ELSE
+            surfdataqc%rmod(jobs,1) = zext(1)
+         ENDIF
+         
+         IF ( zext(1) == obfillflt ) THEN
+            ! If the observation value is a fill value, set QC flag to bad
+            surfdataqc%nqc(jobs) = 4
+         ENDIF
+
+      END DO
+
+      ! Deallocate the data for interpolation
+      DEALLOCATE( &
+         & zweig, &
+         & igrdi, &
+         & igrdj, &
+         & zglam, &
+         & zgphi, &
+         & zmask, &
+         & zsurf, &
+         & zsurftmp, &
+         & zglamf, &
+         & zgphif, &
+         & igrdip1,&
+         & igrdjp1 &
+         & )
+
+      ! At the end of the day also deallocate night-time mean array
+      IF ( idayend == 0 .AND. ldnightav ) THEN
+         DEALLOCATE( &
+            & zsurfm  &
+            & )
+      ENDIF
+      !
+      surfdataqc%nsurfup = surfdataqc%nsurfup + isurf
+      !
+   END SUBROUTINE obs_surf_opt
+
+   !!======================================================================
+END MODULE obs_oper
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_prep.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_prep.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_prep.F90	(revision 14097)
@@ -0,0 +1,1451 @@
+MODULE obs_prep
+   !!=====================================================================
+   !!                       ***  MODULE  obs_prep  ***
+   !! Observation diagnostics: Prepare observation arrays: screening, 
+   !!                          sorting, coordinate search
+   !!=====================================================================
+
+   !!---------------------------------------------------------------------
+   !!   obs_pre_prof  : First level check and screening of profile observations
+   !!   obs_pre_surf  : First level check and screening of surface observations
+   !!   obs_scr       : Basic screening of the observations
+   !!   obs_coo_tim   : Compute number of time steps to the observation time
+   !!   obs_sor       : Sort the observation arrays
+   !!---------------------------------------------------------------------
+   USE par_kind, ONLY : wp ! Precision variables
+   USE in_out_manager     ! I/O manager
+   USE obs_profiles_def   ! Definitions for storage arrays for profiles
+   USE obs_surf_def       ! Definitions for storage arrays for surface data
+   USE obs_mpp, ONLY : &  ! MPP support routines for observation diagnostics
+      & obs_mpp_sum_integer, &
+      & obs_mpp_sum_integers
+   USE obs_inter_sup      ! Interpolation support
+   USE obs_oper           ! Observation operators
+   USE lib_mpp, ONLY :   ctl_warn, ctl_stop
+   USE bdy_oce, ONLY : &        ! Boundary information
+      idx_bdy, nb_bdy, ln_bdy
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   obs_pre_prof     ! First level check and screening of profile obs
+   PUBLIC   obs_pre_surf     ! First level check and screening of surface obs
+   PUBLIC   calc_month_len   ! Calculate the number of days in the months of a year
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+
+CONTAINS
+
+   SUBROUTINE obs_pre_surf( surfdata, surfdataqc, ld_nea, ld_bound_reject, &
+                            kqc_cutoff )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_pre_sla  ***
+      !!
+      !! ** Purpose : First level check and screening of surface observations
+      !!
+      !! ** Method  : First level check and screening of surface observations
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :
+      !!        !  2007-03  (A. Weaver, K. Mogensen) Original
+      !!        !  2007-06  (K. Mogensen et al) Reject obs. near land.
+      !!        !  2015-02  (M. Martin) Combined routine for surface types.
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE par_oce             ! Ocean parameters
+      USE dom_oce, ONLY       :   glamt, gphit, tmask, nproc   ! Geographical information
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) :: surfdata    ! Full set of surface data
+      TYPE(obs_surf), INTENT(INOUT) :: surfdataqc   ! Subset of surface data not failing screening
+      LOGICAL, INTENT(IN) :: ld_nea         ! Switch for rejecting observation near land
+      LOGICAL, INTENT(IN) :: ld_bound_reject       ! Switch for rejecting obs near the boundary
+      INTEGER, INTENT(IN), OPTIONAL :: kqc_cutoff   ! cut off for QC value
+      !! * Local declarations
+      INTEGER :: iqc_cutoff = 255   ! cut off for QC value
+      INTEGER :: iyea0        ! Initial date
+      INTEGER :: imon0        !  - (year, month, day, hour, minute)
+      INTEGER :: iday0    
+      INTEGER :: ihou0    
+      INTEGER :: imin0
+      INTEGER :: icycle       ! Current assimilation cycle
+                              ! Counters for observations that
+      INTEGER :: iotdobs      !  - outside time domain
+      INTEGER :: iosdsobs     !  - outside space domain
+      INTEGER :: ilansobs     !  - within a model land cell
+      INTEGER :: inlasobs     !  - close to land
+      INTEGER :: igrdobs      !  - fail the grid search
+      INTEGER :: ibdysobs     !  - close to open boundary
+                              ! Global counters for observations that
+      INTEGER :: iotdobsmpp     !  - outside time domain
+      INTEGER :: iosdsobsmpp    !  - outside space domain
+      INTEGER :: ilansobsmpp    !  - within a model land cell
+      INTEGER :: inlasobsmpp    !  - close to land
+      INTEGER :: igrdobsmpp     !  - fail the grid search
+      INTEGER :: ibdysobsmpp  !  - close to open boundary
+      LOGICAL, DIMENSION(:), ALLOCATABLE :: & 
+         & llvalid            ! SLA data selection
+      INTEGER :: jobs         ! Obs. loop variable
+      INTEGER :: jstp         ! Time loop variable
+      INTEGER :: inrc         ! Time index variable
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*) 'obs_pre_surf : Preparing the surface observations...'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      
+      ! Initial date initialization (year, month, day, hour, minute)
+      iyea0 =   ndate0 / 10000
+      imon0 = ( ndate0 - iyea0 * 10000 ) / 100
+      iday0 =   ndate0 - iyea0 * 10000 - imon0 * 100
+      ihou0 = nn_time0 / 100
+      imin0 = ( nn_time0 - ihou0 * 100 )
+
+      icycle = nn_no     ! Assimilation cycle
+
+      ! Diagnotics counters for various failures.
+
+      iotdobs  = 0
+      igrdobs  = 0
+      iosdsobs = 0
+      ilansobs = 0
+      inlasobs = 0
+      ibdysobs = 0 
+
+      ! Set QC cutoff to optional value if provided
+      IF ( PRESENT(kqc_cutoff) ) iqc_cutoff=kqc_cutoff
+
+      ! -----------------------------------------------------------------------
+      ! Find time coordinate for surface data
+      ! -----------------------------------------------------------------------
+
+      CALL obs_coo_tim( icycle, &
+         &              iyea0,   imon0,   iday0,   ihou0,   imin0,      &
+         &              surfdata%nsurf,   surfdata%nyea, surfdata%nmon, &
+         &              surfdata%nday,    surfdata%nhou, surfdata%nmin, &
+         &              surfdata%nqc,     surfdata%mstp, iotdobs        )
+
+      CALL obs_mpp_sum_integer( iotdobs, iotdobsmpp )
+      
+      ! -----------------------------------------------------------------------
+      ! Check for surface data failing the grid search
+      ! -----------------------------------------------------------------------
+
+      CALL obs_coo_grd( surfdata%nsurf,   surfdata%mi, surfdata%mj, &
+         &              surfdata%nqc,     igrdobs                         )
+
+      CALL obs_mpp_sum_integer( igrdobs, igrdobsmpp )
+
+      ! -----------------------------------------------------------------------
+      ! Check for land points. 
+      ! -----------------------------------------------------------------------
+
+      CALL obs_coo_spc_2d( surfdata%nsurf,              &
+         &                 jpi,          jpj,          &
+         &                 surfdata%mi,   surfdata%mj,   & 
+         &                 surfdata%rlam, surfdata%rphi, &
+         &                 glamt,        gphit,        &
+         &                 tmask(:,:,1), surfdata%nqc,  &
+         &                 iosdsobs,     ilansobs,     &
+         &                 inlasobs,     ld_nea,       &
+         &                 ibdysobs,     ld_bound_reject, &
+         &                 iqc_cutoff                     )
+
+      CALL obs_mpp_sum_integer( iosdsobs, iosdsobsmpp )
+      CALL obs_mpp_sum_integer( ilansobs, ilansobsmpp )
+      CALL obs_mpp_sum_integer( inlasobs, inlasobsmpp )
+      CALL obs_mpp_sum_integer( ibdysobs, ibdysobsmpp )
+
+      ! -----------------------------------------------------------------------
+      ! Copy useful data from the surfdata data structure to
+      ! the surfdataqc data structure 
+      ! -----------------------------------------------------------------------
+
+      ! Allocate the selection arrays
+
+      ALLOCATE( llvalid(surfdata%nsurf) )
+      
+      ! We want all data which has qc flags <= iqc_cutoff
+
+      llvalid(:)  = ( surfdata%nqc(:)  <= iqc_cutoff )
+
+      ! The actual copying
+
+      CALL obs_surf_compress( surfdata,     surfdataqc,       .TRUE.,  numout, &
+         &                    lvalid=llvalid )
+
+      ! Dellocate the selection arrays
+      DEALLOCATE( llvalid )
+
+      ! -----------------------------------------------------------------------
+      ! Print information about what observations are left after qc
+      ! -----------------------------------------------------------------------
+
+      ! Update the total observation counter array
+      
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' '//surfdataqc%cvars(1)//' data outside time domain                  = ', &
+            &            iotdobsmpp
+         WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data that failed grid search    = ', &
+            &            igrdobsmpp
+         WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data outside space domain       = ', &
+            &            iosdsobsmpp
+         WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data at land points             = ', &
+            &            ilansobsmpp
+         IF (ld_nea) THEN
+            WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data near land points (removed) = ', &
+               &            inlasobsmpp
+         ELSE
+            WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data near land points (kept)    = ', &
+               &            inlasobsmpp
+         ENDIF
+         WRITE(numout,*) ' Remaining '//surfdataqc%cvars(1)//' data near open boundary (removed) = ', &
+            &            ibdysobsmpp  
+         WRITE(numout,*) ' '//surfdataqc%cvars(1)//' data accepted                             = ', &
+            &            surfdataqc%nsurfmpp
+
+         WRITE(numout,*)
+         WRITE(numout,*) ' Number of observations per time step :'
+         WRITE(numout,*)
+         WRITE(numout,'(10X,A,10X,A)')'Time step',surfdataqc%cvars(1)
+         WRITE(numout,'(10X,A,5X,A)')'---------','-----------------'
+         CALL FLUSH(numout)
+      ENDIF
+      
+      DO jobs = 1, surfdataqc%nsurf
+         inrc = surfdataqc%mstp(jobs) + 2 - nit000
+         surfdataqc%nsstp(inrc)  = surfdataqc%nsstp(inrc) + 1
+      END DO
+      
+      CALL obs_mpp_sum_integers( surfdataqc%nsstp, surfdataqc%nsstpmpp, &
+         &                       nitend - nit000 + 2 )
+
+      IF ( lwp ) THEN
+         DO jstp = nit000 - 1, nitend
+            inrc = jstp - nit000 + 2
+            WRITE(numout,1999) jstp, surfdataqc%nsstpmpp(inrc)
+            CALL FLUSH(numout)
+         END DO
+      ENDIF
+
+1999  FORMAT(10X,I9,5X,I17)
+
+   END SUBROUTINE obs_pre_surf
+
+
+   SUBROUTINE obs_pre_prof( profdata, prodatqc, ld_var1, ld_var2, &
+      &                     kpi, kpj, kpk, &
+      &                     zmask1, pglam1, pgphi1, zmask2, pglam2, pgphi2,  &
+      &                     ld_nea, ld_bound_reject, kdailyavtypes,  kqc_cutoff )
+
+!!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_pre_prof  ***
+      !!
+      !! ** Purpose : First level check and screening of profiles
+      !!
+      !! ** Method  : First level check and screening of profiles
+      !!
+      !! History :
+      !!        !  2007-06  (K. Mogensen) original : T and S profile data
+      !!        !  2008-09  (M. Valdivieso) : TAO velocity data
+      !!        !  2009-01  (K. Mogensen) : New feedback stricture
+      !!        !  2015-02  (M. Martin) : Combined profile routine.
+      !!
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE par_oce             ! Ocean parameters
+      USE dom_oce, ONLY : &   ! Geographical information
+         & gdept_1d,             &
+         & nproc
+
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: profdata   ! Full set of profile data
+      TYPE(obs_prof), INTENT(INOUT) :: prodatqc   ! Subset of profile data not failing screening
+      LOGICAL, INTENT(IN) :: ld_var1              ! Observed variables switches
+      LOGICAL, INTENT(IN) :: ld_var2
+      LOGICAL, INTENT(IN) :: ld_nea               ! Switch for rejecting observation near land
+      LOGICAL, INTENT(IN) :: ld_bound_reject      ! Switch for rejecting observations near the boundary
+      INTEGER, INTENT(IN) :: kpi, kpj, kpk        ! Local domain sizes
+      INTEGER, DIMENSION(imaxavtypes), OPTIONAL :: &
+         & kdailyavtypes                          ! Types for daily averages
+      REAL(wp), INTENT(IN), DIMENSION(kpi,kpj,kpk) :: &
+         & zmask1, &
+         & zmask2
+      REAL(wp), INTENT(IN), DIMENSION(kpi,kpj) :: &
+         & pglam1, &
+         & pglam2, &
+         & pgphi1, &
+         & pgphi2
+      INTEGER, INTENT(IN), OPTIONAL :: kqc_cutoff   ! cut off for QC value
+
+      !! * Local declarations
+      INTEGER :: iqc_cutoff = 255   ! cut off for QC value
+      INTEGER :: iyea0        ! Initial date
+      INTEGER :: imon0        !  - (year, month, day, hour, minute)
+      INTEGER :: iday0    
+      INTEGER :: ihou0    
+      INTEGER :: imin0
+      INTEGER :: icycle       ! Current assimilation cycle
+                              ! Counters for observations that are
+      INTEGER :: iotdobs      !  - outside time domain
+      INTEGER :: iosdv1obs    !  - outside space domain (variable 1)
+      INTEGER :: iosdv2obs    !  - outside space domain (variable 2)
+      INTEGER :: ilanv1obs    !  - within a model land cell (variable 1)
+      INTEGER :: ilanv2obs    !  - within a model land cell (variable 2)
+      INTEGER :: inlav1obs    !  - close to land (variable 1)
+      INTEGER :: inlav2obs    !  - close to land (variable 2)
+      INTEGER :: ibdyv1obs    !  - boundary (variable 1) 
+      INTEGER :: ibdyv2obs    !  - boundary (variable 2)      
+      INTEGER :: igrdobs      !  - fail the grid search
+      INTEGER :: iuvchku      !  - reject u if v rejected and vice versa
+      INTEGER :: iuvchkv      !
+                              ! Global counters for observations that are
+      INTEGER :: iotdobsmpp   !  - outside time domain
+      INTEGER :: iosdv1obsmpp !  - outside space domain (variable 1)
+      INTEGER :: iosdv2obsmpp !  - outside space domain (variable 2)
+      INTEGER :: ilanv1obsmpp !  - within a model land cell (variable 1)
+      INTEGER :: ilanv2obsmpp !  - within a model land cell (variable 2)
+      INTEGER :: inlav1obsmpp !  - close to land (variable 1)
+      INTEGER :: inlav2obsmpp !  - close to land (variable 2)
+      INTEGER :: ibdyv1obsmpp !  - boundary (variable 1) 
+      INTEGER :: ibdyv2obsmpp !  - boundary (variable 2)      
+      INTEGER :: igrdobsmpp   !  - fail the grid search
+      INTEGER :: iuvchkumpp   !  - reject var1 if var2 rejected and vice versa
+      INTEGER :: iuvchkvmpp   !
+      TYPE(obs_prof_valid) ::  llvalid      ! Profile selection 
+      TYPE(obs_prof_valid), DIMENSION(profdata%nvar) :: &
+         & llvvalid           ! var1,var2 selection 
+      INTEGER :: jvar         ! Variable loop variable
+      INTEGER :: jobs         ! Obs. loop variable
+      INTEGER :: jstp         ! Time loop variable
+      INTEGER :: inrc         ! Time index variable
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)'obs_pre_prof: Preparing the profile data...'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+
+      ! Initial date initialization (year, month, day, hour, minute)
+      iyea0 =   ndate0 / 10000
+      imon0 = ( ndate0 - iyea0 * 10000 ) / 100
+      iday0 =   ndate0 - iyea0 * 10000 - imon0 * 100
+      ihou0 = nn_time0 / 100
+      imin0 = ( nn_time0 - ihou0 * 100 )
+
+      icycle = nn_no     ! Assimilation cycle
+
+      ! Diagnotics counters for various failures.
+
+      iotdobs   = 0
+      igrdobs   = 0
+      iosdv1obs = 0
+      iosdv2obs = 0
+      ilanv1obs = 0
+      ilanv2obs = 0
+      inlav1obs = 0
+      inlav2obs = 0
+      ibdyv1obs = 0
+      ibdyv2obs = 0
+      iuvchku   = 0
+      iuvchkv   = 0
+
+
+      ! Set QC cutoff to optional value if provided
+      IF ( PRESENT(kqc_cutoff) ) iqc_cutoff=kqc_cutoff
+
+      ! -----------------------------------------------------------------------
+      ! Find time coordinate for profiles
+      ! -----------------------------------------------------------------------
+
+      IF ( PRESENT(kdailyavtypes) ) THEN
+         CALL obs_coo_tim_prof( icycle, &
+            &              iyea0,   imon0,   iday0,   ihou0,   imin0,      &
+            &              profdata%nprof,   profdata%nyea, profdata%nmon, &
+            &              profdata%nday,    profdata%nhou, profdata%nmin, &
+            &              profdata%ntyp,    profdata%nqc,  profdata%mstp, &
+            &              iotdobs, kdailyavtypes = kdailyavtypes,         &
+            &              kqc_cutoff = iqc_cutoff )
+      ELSE
+         CALL obs_coo_tim_prof( icycle, &
+            &              iyea0,   imon0,   iday0,   ihou0,   imin0,      &
+            &              profdata%nprof,   profdata%nyea, profdata%nmon, &
+            &              profdata%nday,    profdata%nhou, profdata%nmin, &
+            &              profdata%ntyp,    profdata%nqc,  profdata%mstp, &
+            &              iotdobs,          kqc_cutoff = iqc_cutoff )
+      ENDIF
+
+      CALL obs_mpp_sum_integer( iotdobs, iotdobsmpp )
+      
+      ! -----------------------------------------------------------------------
+      ! Check for profiles failing the grid search
+      ! -----------------------------------------------------------------------
+
+      CALL obs_coo_grd( profdata%nprof,   profdata%mi(:,1), profdata%mj(:,1), &
+         &              profdata%nqc,     igrdobs                         )
+      CALL obs_coo_grd( profdata%nprof,   profdata%mi(:,2), profdata%mj(:,2), &
+         &              profdata%nqc,     igrdobs                         )
+
+      CALL obs_mpp_sum_integer( igrdobs, igrdobsmpp )
+
+      ! -----------------------------------------------------------------------
+      ! Reject all observations for profiles with nqc > iqc_cutoff
+      ! -----------------------------------------------------------------------
+
+      CALL obs_pro_rej( profdata, kqc_cutoff = iqc_cutoff )
+
+      ! -----------------------------------------------------------------------
+      ! Check for land points. This includes points below the model
+      ! bathymetry so this is done for every point in the profile
+      ! -----------------------------------------------------------------------
+
+      ! Variable 1
+      CALL obs_coo_spc_3d( profdata%nprof,        profdata%nvprot(1),   &
+         &                 profdata%npvsta(:,1),  profdata%npvend(:,1), &
+         &                 jpi,                   jpj,                  &
+         &                 jpk,                                         &
+         &                 profdata%mi,           profdata%mj,          &
+         &                 profdata%var(1)%mvk,                         &
+         &                 profdata%rlam,         profdata%rphi,        &
+         &                 profdata%var(1)%vdep,                        &
+         &                 pglam1,                pgphi1,               &
+         &                 gdept_1d,              zmask1,               &
+         &                 profdata%nqc,          profdata%var(1)%nvqc, &
+         &                 iosdv1obs,             ilanv1obs,            &
+         &                 inlav1obs,             ld_nea,               &
+         &                 ibdyv1obs,             ld_bound_reject,      &
+         &                 iqc_cutoff       )
+
+      CALL obs_mpp_sum_integer( iosdv1obs, iosdv1obsmpp )
+      CALL obs_mpp_sum_integer( ilanv1obs, ilanv1obsmpp )
+      CALL obs_mpp_sum_integer( inlav1obs, inlav1obsmpp )
+      CALL obs_mpp_sum_integer( ibdyv1obs, ibdyv1obsmpp )
+
+      ! Variable 2
+      CALL obs_coo_spc_3d( profdata%nprof,        profdata%nvprot(2),   &
+         &                 profdata%npvsta(:,2),  profdata%npvend(:,2), &
+         &                 jpi,                   jpj,                  &
+         &                 jpk,                                         &
+         &                 profdata%mi,           profdata%mj,          & 
+         &                 profdata%var(2)%mvk,                         &
+         &                 profdata%rlam,         profdata%rphi,        &
+         &                 profdata%var(2)%vdep,                        &
+         &                 pglam2,                pgphi2,               &
+         &                 gdept_1d,              zmask2,               &
+         &                 profdata%nqc,          profdata%var(2)%nvqc, &
+         &                 iosdv2obs,             ilanv2obs,            &
+         &                 inlav2obs,             ld_nea,               &
+         &                 ibdyv2obs,             ld_bound_reject,      &
+         &                 iqc_cutoff       )
+
+      CALL obs_mpp_sum_integer( iosdv2obs, iosdv2obsmpp )
+      CALL obs_mpp_sum_integer( ilanv2obs, ilanv2obsmpp )
+      CALL obs_mpp_sum_integer( inlav2obs, inlav2obsmpp )
+      CALL obs_mpp_sum_integer( ibdyv2obs, ibdyv2obsmpp )
+
+      ! -----------------------------------------------------------------------
+      ! Reject u if v is rejected and vice versa
+      ! -----------------------------------------------------------------------
+
+      IF ( TRIM(profdata%cvars(1)) == 'UVEL' ) THEN
+         CALL obs_uv_rej( profdata, iuvchku, iuvchkv, iqc_cutoff )
+         CALL obs_mpp_sum_integer( iuvchku, iuvchkumpp )
+         CALL obs_mpp_sum_integer( iuvchkv, iuvchkvmpp )
+      ENDIF
+
+      ! -----------------------------------------------------------------------
+      ! Copy useful data from the profdata data structure to
+      ! the prodatqc data structure 
+      ! -----------------------------------------------------------------------
+
+      ! Allocate the selection arrays
+
+      ALLOCATE( llvalid%luse(profdata%nprof) )
+      DO jvar = 1,profdata%nvar
+         ALLOCATE( llvvalid(jvar)%luse(profdata%nvprot(jvar)) )
+      END DO
+
+      ! We want all data which has qc flags <= iqc_cutoff
+
+      llvalid%luse(:) = ( profdata%nqc(:)  <= iqc_cutoff )
+      DO jvar = 1,profdata%nvar
+         llvvalid(jvar)%luse(:) = ( profdata%var(jvar)%nvqc(:) <= iqc_cutoff )
+      END DO
+
+      ! The actual copying
+
+      CALL obs_prof_compress( profdata,     prodatqc,       .TRUE.,  numout, &
+         &                    lvalid=llvalid, lvvalid=llvvalid )
+
+      ! Dellocate the selection arrays
+      DEALLOCATE( llvalid%luse )
+      DO jvar = 1,profdata%nvar
+         DEALLOCATE( llvvalid(jvar)%luse )
+      END DO
+
+      ! -----------------------------------------------------------------------
+      ! Print information about what observations are left after qc
+      ! -----------------------------------------------------------------------
+
+      ! Update the total observation counter array
+      
+      IF(lwp) THEN
+      
+         WRITE(numout,*)
+         WRITE(numout,*) ' Profiles outside time domain                     = ', &
+            &            iotdobsmpp
+         WRITE(numout,*) ' Remaining profiles that failed grid search       = ', &
+            &            igrdobsmpp
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(1)//' data outside space domain       = ', &
+            &            iosdv1obsmpp
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(1)//' data at land points             = ', &
+            &            ilanv1obsmpp
+         IF (ld_nea) THEN
+            WRITE(numout,*) ' Remaining '//prodatqc%cvars(1)//' data near land points (removed) = ',&
+               &            inlav1obsmpp
+         ELSE
+            WRITE(numout,*) ' Remaining '//prodatqc%cvars(1)//' data near land points (kept)    = ',&
+               &            inlav1obsmpp
+         ENDIF
+         IF ( TRIM(profdata%cvars(1)) == 'UVEL' ) THEN
+            WRITE(numout,*) ' U observation rejected since V rejected     = ', &
+               &            iuvchku
+         ENDIF
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(1)//' data near open boundary (removed) = ',&
+               &            ibdyv1obsmpp
+         WRITE(numout,*) ' '//prodatqc%cvars(1)//' data accepted                             = ', &
+            &            prodatqc%nvprotmpp(1)
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(2)//' data outside space domain       = ', &
+            &            iosdv2obsmpp
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(2)//' data at land points             = ', &
+            &            ilanv2obsmpp
+         IF (ld_nea) THEN
+            WRITE(numout,*) ' Remaining '//prodatqc%cvars(2)//' data near land points (removed) = ',&
+               &            inlav2obsmpp
+         ELSE
+            WRITE(numout,*) ' Remaining '//prodatqc%cvars(2)//' data near land points (kept)    = ',&
+               &            inlav2obsmpp
+         ENDIF
+         IF ( TRIM(profdata%cvars(1)) == 'UVEL' ) THEN
+            WRITE(numout,*) ' V observation rejected since U rejected     = ', &
+               &            iuvchkv
+         ENDIF
+         WRITE(numout,*) ' Remaining '//prodatqc%cvars(2)//' data near open boundary (removed) = ',&
+               &            ibdyv2obsmpp
+         WRITE(numout,*) ' '//prodatqc%cvars(2)//' data accepted                             = ', &
+            &            prodatqc%nvprotmpp(2)
+
+         WRITE(numout,*)
+         WRITE(numout,*) ' Number of observations per time step :'
+         WRITE(numout,*)
+         WRITE(numout,'(10X,A,5X,A,5X,A,A)')'Time step','Profiles', &
+            &                               '     '//prodatqc%cvars(1)//'     ', &
+            &                               '     '//prodatqc%cvars(2)//'     '
+         WRITE(numout,998)
+      ENDIF
+      
+      DO jobs = 1, prodatqc%nprof
+         inrc = prodatqc%mstp(jobs) + 2 - nit000
+         prodatqc%npstp(inrc)  = prodatqc%npstp(inrc) + 1
+         DO jvar = 1, prodatqc%nvar
+            IF ( prodatqc%npvend(jobs,jvar) > 0 ) THEN
+               prodatqc%nvstp(inrc,jvar) = prodatqc%nvstp(inrc,jvar) + &
+                  &                      ( prodatqc%npvend(jobs,jvar) - &
+                  &                        prodatqc%npvsta(jobs,jvar) + 1 )
+            ENDIF
+         END DO
+      END DO
+      
+      
+      CALL obs_mpp_sum_integers( prodatqc%npstp, prodatqc%npstpmpp, &
+         &                       nitend - nit000 + 2 )
+      DO jvar = 1, prodatqc%nvar
+         CALL obs_mpp_sum_integers( prodatqc%nvstp(:,jvar), &
+            &                       prodatqc%nvstpmpp(:,jvar), &
+            &                       nitend - nit000 + 2 )
+      END DO
+
+      IF ( lwp ) THEN
+         DO jstp = nit000 - 1, nitend
+            inrc = jstp - nit000 + 2
+            WRITE(numout,999) jstp, prodatqc%npstpmpp(inrc), &
+               &                    prodatqc%nvstpmpp(inrc,1), &
+               &                    prodatqc%nvstpmpp(inrc,2)
+         END DO
+      ENDIF
+
+998   FORMAT(10X,'---------',5X,'--------',5X,'-----------',5X,'----------------')
+999   FORMAT(10X,I9,5X,I8,5X,I11,5X,I8)
+
+   END SUBROUTINE obs_pre_prof
+
+   SUBROUTINE obs_coo_tim( kcycle, &
+      &                    kyea0,   kmon0,   kday0,   khou0,   kmin0,     &
+      &                    kobsno,                                        &
+      &                    kobsyea, kobsmon, kobsday, kobshou, kobsmin,   &
+      &                    kobsqc,  kobsstp, kotdobs                      )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_coo_tim ***
+      !!
+      !! ** Purpose : Compute the number of time steps to the observation time.
+      !!
+      !! ** Method  : For time coordinates ( yea_obs, mon_obs, day_obs, 
+      !!              hou_obs, min_obs ), this routine locates the time step 
+      !!              that is closest to this time.
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :
+      !!        !  1997-07  (A. Weaver) Original
+      !!        !  2006-08  (A. Weaver) NEMOVAR migration
+      !!        !  2006-10  (A. Weaver) Cleanup
+      !!        !  2007-01  (K. Mogensen) Rewritten with loop
+      !!        !  2010-05  (D. Lea) Fix in leap year calculation for NEMO vn3.2
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE dom_oce, ONLY : &  ! Geographical information
+         & rdt
+      USE phycst, ONLY : &   ! Physical constants
+         & rday,  &             
+         & rmmss, &             
+         & rhhmm                        
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kcycle     ! Current cycle
+      INTEGER, INTENT(IN) :: kyea0      ! Initial date coordinates
+      INTEGER, INTENT(IN) :: kmon0
+      INTEGER, INTENT(IN) :: kday0 
+      INTEGER, INTENT(IN) :: khou0
+      INTEGER, INTENT(IN) :: kmin0
+      INTEGER, INTENT(IN) :: kobsno     ! Number of observations
+      INTEGER, INTENT(INOUT) :: kotdobs   ! Number of observations failing time check
+      INTEGER, DIMENSION(kobsno), INTENT(IN ) :: &
+         & kobsyea,  &      ! Observation time coordinates
+         & kobsmon,  &
+         & kobsday,  & 
+         & kobshou,  &
+         & kobsmin
+      INTEGER, DIMENSION(kobsno), INTENT(INOUT) :: &
+         & kobsqc           ! Quality control flag
+      INTEGER, DIMENSION(kobsno), INTENT(OUT) :: &
+         & kobsstp          ! Number of time steps up to the 
+                            ! observation time
+
+      !! * Local declarations
+      INTEGER :: jyea
+      INTEGER :: jmon
+      INTEGER :: jday
+      INTEGER :: jobs
+      INTEGER :: iyeastr
+      INTEGER :: iyeaend
+      INTEGER :: imonstr
+      INTEGER :: imonend
+      INTEGER :: idaystr
+      INTEGER :: idayend 
+      INTEGER :: iskip
+      INTEGER :: idaystp
+      REAL(KIND=wp) :: zminstp
+      REAL(KIND=wp) :: zhoustp
+      REAL(KIND=wp) :: zobsstp 
+      INTEGER, DIMENSION(12) ::   imonth_len    !: length in days of the months of the current year
+ 
+      !-----------------------------------------------------------------------
+      ! Initialization
+      !-----------------------------------------------------------------------
+
+      ! Intialize the number of time steps per day
+      idaystp = NINT( rday / rdt )
+
+      !---------------------------------------------------------------------
+      ! Locate the model time coordinates for interpolation
+      !---------------------------------------------------------------------
+
+      DO jobs = 1, kobsno
+
+         ! Initialize the time step counter
+         kobsstp(jobs) = nit000 - 1
+
+         ! Flag if observation date is less than the initial date
+
+         IF ( ( kobsyea(jobs) < kyea0 )                   &
+            & .OR. ( ( kobsyea(jobs) == kyea0 )           &
+            &        .AND. ( kobsmon(jobs) <  kmon0 ) )   &
+            & .OR. ( ( kobsyea(jobs) == kyea0 )           &
+            &        .AND. ( kobsmon(jobs) == kmon0 )     &
+            &        .AND. ( kobsday(jobs) <  kday0 ) )   &
+            & .OR. ( ( kobsyea(jobs) == kyea0 )           &
+            &        .AND. ( kobsmon(jobs) == kmon0 )     &
+            &        .AND. ( kobsday(jobs) == kday0 )     &
+            &        .AND. ( kobshou(jobs) <  khou0 ) )   &
+            &  .OR. ( ( kobsyea(jobs) == kyea0 )          &
+            &        .AND. ( kobsmon(jobs) == kmon0 )     &
+            &        .AND. ( kobsday(jobs) == kday0 )          &
+            &        .AND. ( kobshou(jobs) == khou0 )          &
+            &        .AND. ( kobsmin(jobs) <= kmin0 ) ) ) THEN
+            kobsstp(jobs) = -1
+            kobsqc(jobs)  = IBSET(kobsqc(jobs),13)
+            kotdobs       = kotdobs + 1
+            CYCLE
+         ENDIF
+
+         ! Compute the number of time steps to the observation day
+         iyeastr = kyea0
+         iyeaend = kobsyea(jobs)
+         
+         !---------------------------------------------------------------------
+         ! Year loop
+         !---------------------------------------------------------------------
+         DO jyea = iyeastr, iyeaend
+
+            CALL calc_month_len( jyea, imonth_len )
+            
+            imonstr = 1
+            IF ( jyea == kyea0         ) imonstr = kmon0
+            imonend = 12
+            IF ( jyea == kobsyea(jobs) ) imonend = kobsmon(jobs)
+            
+            ! Month loop
+            DO jmon = imonstr, imonend
+               
+               idaystr = 1
+               IF (       ( jmon == kmon0   ) &
+                  & .AND. ( jyea == kyea0   ) ) idaystr = kday0
+               idayend = imonth_len(jmon)
+               IF (       ( jmon == kobsmon(jobs) ) &
+                  & .AND. ( jyea == kobsyea(jobs) ) ) idayend = kobsday(jobs) - 1
+               
+               ! Day loop
+               DO jday = idaystr, idayend
+                  kobsstp(jobs) = kobsstp(jobs) + idaystp
+               END DO
+               
+            END DO
+
+         END DO
+
+         ! Add in the number of time steps to the observation minute
+         zminstp = rmmss / rdt
+         zhoustp = rhhmm * zminstp
+
+         zobsstp =   REAL( kobsmin(jobs) - kmin0, KIND=wp ) * zminstp &
+            &      + REAL( kobshou(jobs) - khou0, KIND=wp ) * zhoustp
+         kobsstp(jobs) = kobsstp(jobs) + NINT( zobsstp )
+
+         ! Flag if observation step outside the time window
+         IF ( ( kobsstp(jobs) < ( nit000 - 1 ) ) &
+            & .OR.( kobsstp(jobs) > nitend ) ) THEN
+            kobsqc(jobs) = IBSET(kobsqc(jobs),13)
+            kotdobs = kotdobs + 1
+            CYCLE
+         ENDIF
+
+      END DO
+
+   END SUBROUTINE obs_coo_tim
+
+   SUBROUTINE calc_month_len( iyear, imonth_len )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE calc_month_len  ***
+      !!          
+      !! ** Purpose : Compute the number of days in a months given a year.
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  10-05  (D. Lea)   New routine based on day_init 
+      !!----------------------------------------------------------------------
+
+      INTEGER, DIMENSION(12) ::   imonth_len    !: length in days of the months of the current year
+      INTEGER :: iyear         !: year
+      
+      ! length of the month of the current year (from nleapy, read in namelist)
+      IF ( nleapy < 2 ) THEN 
+         imonth_len(:) = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)
+         IF ( nleapy == 1 ) THEN   ! we are using calendar with leap years
+            IF ( MOD(iyear, 4) == 0 .AND. ( MOD(iyear, 400) == 0 .OR. MOD(iyear, 100) /= 0 ) ) THEN
+               imonth_len(2) = 29
+            ENDIF
+         ENDIF
+      ELSE
+         imonth_len(:) = nleapy   ! all months with nleapy days per year
+      ENDIF
+
+   END SUBROUTINE
+
+   SUBROUTINE obs_coo_tim_prof( kcycle,                                   &
+      &                    kyea0,   kmon0,   kday0,   khou0,   kmin0,     &
+      &                    kobsno,                                        &
+      &                    kobsyea, kobsmon, kobsday, kobshou, kobsmin,   &
+      &                    ktyp,    kobsqc,  kobsstp, kotdobs, kdailyavtypes, &
+      &                    kqc_cutoff )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_coo_tim ***
+      !!
+      !! ** Purpose : Compute the number of time steps to the observation time.
+      !!
+      !! ** Method  : For time coordinates ( yea_obs, mon_obs, day_obs, 
+      !!              hou_obs, min_obs ), this routine locates the time step 
+      !!              that is closest to this time.
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :
+      !!        !  1997-07  (A. Weaver) Original
+      !!        !  2006-08  (A. Weaver) NEMOVAR migration
+      !!        !  2006-10  (A. Weaver) Cleanup
+      !!        !  2007-01  (K. Mogensen) Rewritten with loop
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kcycle      ! Current cycle
+      INTEGER, INTENT(IN) :: kyea0       ! Initial date coordinates
+      INTEGER, INTENT(IN) :: kmon0
+      INTEGER, INTENT(IN) :: kday0
+      INTEGER, INTENT(IN) :: khou0
+      INTEGER, INTENT(IN) :: kmin0
+      INTEGER, INTENT(IN) :: kobsno      ! Number of observations
+      INTEGER, INTENT(INOUT) ::  kotdobs    ! Number of observations failing time check
+      INTEGER, DIMENSION(kobsno), INTENT(IN ) :: &
+         & kobsyea,  &      ! Observation time coordinates
+         & kobsmon,  &
+         & kobsday,  & 
+         & kobshou,  &
+         & kobsmin,  &
+         & ktyp             ! Observation type.
+      INTEGER, DIMENSION(kobsno), INTENT(INOUT) :: &
+         & kobsqc           ! Quality control flag
+      INTEGER, DIMENSION(kobsno), INTENT(OUT) :: &
+         & kobsstp          ! Number of time steps up to the 
+                            ! observation time
+      INTEGER, DIMENSION(imaxavtypes), OPTIONAL :: &
+         & kdailyavtypes    ! Types for daily averages
+      INTEGER, OPTIONAL, INTENT(IN) :: kqc_cutoff           ! QC cutoff value
+
+      !! * Local declarations
+      INTEGER :: jobs
+      INTEGER :: iqc_cutoff=255
+
+      !-----------------------------------------------------------------------
+      ! Call standard obs_coo_tim
+      !-----------------------------------------------------------------------
+
+      CALL obs_coo_tim( kcycle, &
+         &              kyea0,   kmon0,   kday0,   khou0,   kmin0,     &
+         &              kobsno,                                        &
+         &              kobsyea, kobsmon, kobsday, kobshou, kobsmin,   &
+         &              kobsqc,  kobsstp, kotdobs                      )
+
+      !------------------------------------------------------------------------
+      ! Always reject daily averaged data (e.g. MRB data (820)) at initial time
+      !------------------------------------------------------------------------
+
+      IF ( PRESENT(kdailyavtypes) ) THEN
+         DO jobs = 1, kobsno
+            
+            IF ( kobsqc(jobs) <= iqc_cutoff ) THEN
+               
+               IF ( ( kobsstp(jobs) == (nit000 - 1) ).AND.&
+                  & ( ANY (kdailyavtypes(:) == ktyp(jobs)) ) ) THEN
+                  kobsqc(jobs) = IBSET(kobsqc(jobs),13)
+                  kotdobs      = kotdobs + 1
+                  CYCLE
+               ENDIF
+               
+            ENDIF
+         END DO
+      ENDIF
+
+
+   END SUBROUTINE obs_coo_tim_prof
+
+   SUBROUTINE obs_coo_grd( kobsno, kobsi, kobsj, kobsqc, kgrdobs )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_coo_grd ***
+      !!
+      !! ** Purpose : Verify that the grid search has not failed
+      !!
+      !! ** Method  : The previously computed i,j indeces are checked  
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :
+      !!        !  2007-01  (K. Mogensen)  Original
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) :: kobsno        ! Number of observations
+      INTEGER, DIMENSION(kobsno), INTENT(IN ) :: &
+         & kobsi, &         ! i,j indeces previously computed
+         & kobsj
+      INTEGER, INTENT(INOUT) ::  kgrdobs   ! Number of observations failing the check
+      INTEGER, DIMENSION(kobsno), INTENT(INOUT) :: &
+         & kobsqc           ! Quality control flag
+
+      !! * Local declarations
+      INTEGER :: jobs       ! Loop variable
+
+      ! Flag if the grid search failed
+
+      DO jobs = 1, kobsno
+         IF ( ( kobsi(jobs) <= 0 ) .AND. ( kobsj(jobs) <= 0 ) ) THEN
+            kobsqc(jobs) = IBSET(kobsqc(jobs),12)
+            kgrdobs = kgrdobs + 1
+         ENDIF
+      END DO
+      
+   END SUBROUTINE obs_coo_grd
+
+   SUBROUTINE obs_coo_spc_2d( kobsno, kpi,     kpj,              &
+      &                       kobsi,  kobsj,   pobslam, pobsphi, & 
+      &                       plam,   pphi,    pmask,            &
+      &                       kobsqc, kosdobs, klanobs,          &
+      &                       knlaobs,ld_nea,                    &
+      &                       kbdyobs,ld_bound_reject,           &
+      &                       kqc_cutoff                         )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_coo_spc_2d  ***
+      !!
+      !! ** Purpose : Check for points outside the domain and land points
+      !!
+      !! ** Method  : Remove the observations that are outside the model space
+      !!              and time domain or located within model land cells.
+      !!
+      !! ** Action  : 
+      !!   
+      !! History :  2007-03  (A. Weaver, K. Mogensen)  Original
+      !!         !  2007-06  (K. Mogensen et al) Reject obs. near land.
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in   )                     ::   kobsno            ! Total number of observations
+      INTEGER , INTENT(in   )                     ::   kpi    , kpj      ! Number of grid points in (i,j)
+      INTEGER , INTENT(in   ), DIMENSION(kobsno)  ::   kobsi  , kobsj    ! Observation (i,j) coordinates
+      REAL(wp), INTENT(in   ), DIMENSION(kobsno)  ::   pobslam, pobsphi  ! Observation (lon,lat) coordinates
+      REAL(wp), INTENT(in   ), DIMENSION(kpi,kpj) ::   plam   , pphi     ! Model (lon,lat) coordinates
+      REAL(wp), INTENT(in   ), DIMENSION(kpi,kpj) ::   pmask             ! Land mask array
+      INTEGER , INTENT(inout), DIMENSION(kobsno)  ::   kobsqc            ! Observation quality control
+      INTEGER , INTENT(inout)                     ::   kosdobs           ! Observations outside space domain
+      INTEGER , INTENT(inout)                     ::   klanobs           ! Observations within a model land cell
+      INTEGER , INTENT(inout)                     ::   knlaobs           ! Observations near land
+      INTEGER , INTENT(inout)                     ::   kbdyobs           ! Observations near boundary
+      LOGICAL , INTENT(in   )                     ::   ld_nea            ! Flag observations near land
+      LOGICAL , INTENT(in   )                     ::   ld_bound_reject   ! Flag observations near open boundary 
+      INTEGER , INTENT(in   )                     ::   kqc_cutoff        ! Cutoff QC value
+      !
+      REAL(KIND=wp), DIMENSION(2,2,kobsno) ::   zgmsk          ! Grid mask
+      REAL(KIND=wp), DIMENSION(2,2,kobsno) ::   zbmsk          ! Boundary mask
+      REAL(KIND=wp), DIMENSION(jpi,jpj)    ::   zbdymask
+      REAL(KIND=wp), DIMENSION(2,2,kobsno) ::   zglam, zgphi   ! Model Lon/lat at grid points
+      INTEGER      , DIMENSION(2,2,kobsno) ::   igrdi, igrdj   ! Grid i,j
+      LOGICAL ::   lgridobs           ! Is observation on a model grid point.
+      INTEGER ::   iig, ijg           ! i,j of observation on model grid point.
+      INTEGER ::   jobs, ji, jj
+      !!----------------------------------------------------------------------
+      
+      ! Get grid point indices
+
+      DO jobs = 1, kobsno
+         
+         ! For invalid points use 2,2
+
+         IF ( kobsqc(jobs) >= kqc_cutoff ) THEN
+
+            igrdi(1,1,jobs) = 1
+            igrdj(1,1,jobs) = 1
+            igrdi(1,2,jobs) = 1
+            igrdj(1,2,jobs) = 2
+            igrdi(2,1,jobs) = 2
+            igrdj(2,1,jobs) = 1
+            igrdi(2,2,jobs) = 2
+            igrdj(2,2,jobs) = 2
+
+         ELSE
+
+            igrdi(1,1,jobs) = kobsi(jobs)-1
+            igrdj(1,1,jobs) = kobsj(jobs)-1
+            igrdi(1,2,jobs) = kobsi(jobs)-1
+            igrdj(1,2,jobs) = kobsj(jobs)
+            igrdi(2,1,jobs) = kobsi(jobs)
+            igrdj(2,1,jobs) = kobsj(jobs)-1
+            igrdi(2,2,jobs) = kobsi(jobs)
+            igrdj(2,2,jobs) = kobsj(jobs)
+
+         ENDIF
+
+      END DO
+
+      IF (ln_bdy) THEN
+        ! Create a mask grid points in boundary rim
+        IF (ld_bound_reject) THEN
+           zbdymask(:,:) = 1.0_wp
+           DO ji = 1, nb_bdy
+              DO jj = 1, idx_bdy(ji)%nblen(1)
+                 zbdymask(idx_bdy(ji)%nbi(jj,1),idx_bdy(ji)%nbj(jj,1)) = 0.0_wp
+              ENDDO
+           ENDDO
+
+           CALL obs_int_comm_2d( 2, 2, kobsno, kpi, kpj, igrdi, igrdj, zbdymask, zbmsk )
+        ENDIF
+      ENDIF
+
+      
+      CALL obs_int_comm_2d( 2, 2, kobsno, kpi, kpj, igrdi, igrdj, pmask, zgmsk )
+      CALL obs_int_comm_2d( 2, 2, kobsno, kpi, kpj, igrdi, igrdj, plam, zglam )
+      CALL obs_int_comm_2d( 2, 2, kobsno, kpi, kpj, igrdi, igrdj, pphi, zgphi )
+
+      DO jobs = 1, kobsno
+
+         ! Skip bad observations
+         IF ( kobsqc(jobs) >= kqc_cutoff ) CYCLE
+
+         ! Flag if the observation falls outside the model spatial domain
+         IF (       ( pobslam(jobs) < -180. ) &
+            &  .OR. ( pobslam(jobs) >  180. ) &
+            &  .OR. ( pobsphi(jobs) <  -90. ) &
+            &  .OR. ( pobsphi(jobs) >   90. ) ) THEN
+            kobsqc(jobs) = IBSET(kobsqc(jobs),11)
+            kosdobs = kosdobs + 1
+            CYCLE
+         ENDIF
+
+         ! Flag if the observation falls with a model land cell
+         IF ( SUM( zgmsk(1:2,1:2,jobs) ) == 0.0_wp ) THEN
+            kobsqc(jobs) = IBSET(kobsqc(jobs),10)
+            klanobs = klanobs + 1
+            CYCLE
+         ENDIF
+
+         ! Check if this observation is on a grid point
+
+         lgridobs = .FALSE.
+         iig = -1
+         ijg = -1
+         DO jj = 1, 2
+            DO ji = 1, 2
+               IF ( ( ABS( zgphi(ji,jj,jobs) - pobsphi(jobs) ) < 1.0e-6_wp ) &
+                  & .AND. &
+                  & ( ABS( MOD( zglam(ji,jj,jobs) - pobslam(jobs),360.0) )  &
+                  & < 1.0e-6_wp ) ) THEN
+                  lgridobs = .TRUE.
+                  iig = ji
+                  ijg = jj
+               ENDIF
+            END DO
+         END DO
+  
+         ! For observations on the grid reject them if their are at
+         ! a masked point
+         
+         IF (lgridobs) THEN
+            IF (zgmsk(iig,ijg,jobs) == 0.0_wp ) THEN
+               kobsqc(jobs) = IBSET(kobsqc(jobs),10)
+               klanobs = klanobs + 1
+               CYCLE
+            ENDIF
+         ENDIF
+                      
+         ! Flag if the observation falls is close to land
+         IF ( MINVAL( zgmsk(1:2,1:2,jobs) ) == 0.0_wp) THEN
+            knlaobs = knlaobs + 1
+            IF (ld_nea) THEN
+               kobsqc(jobs) = IBSET(kobsqc(jobs),9)
+               CYCLE
+            ENDIF
+         ENDIF
+
+         IF (ln_bdy) THEN
+         ! Flag if the observation falls close to the boundary rim
+           IF (ld_bound_reject) THEN
+              IF ( MINVAL( zbmsk(1:2,1:2,jobs) ) == 0.0_wp ) THEN
+                 kobsqc(jobs) = IBSET(kobsqc(jobs),8)
+                 kbdyobs = kbdyobs + 1
+                 CYCLE
+              ENDIF
+              ! for observations on the grid...
+              IF (lgridobs) THEN
+                 IF (zbmsk(iig,ijg,jobs) == 0.0_wp ) THEN
+                    kobsqc(jobs) = IBSET(kobsqc(jobs),8)
+                    kbdyobs = kbdyobs + 1
+                    CYCLE
+                 ENDIF
+              ENDIF
+            ENDIF
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE obs_coo_spc_2d
+
+
+   SUBROUTINE obs_coo_spc_3d( kprofno, kobsno,  kpstart, kpend, &
+      &                       kpi,     kpj,     kpk,            &
+      &                       kobsi,   kobsj,   kobsk,          &
+      &                       pobslam, pobsphi, pobsdep,        &
+      &                       plam,    pphi,    pdep,    pmask, &
+      &                       kpobsqc, kobsqc,  kosdobs,        &
+      &                       klanobs, knlaobs, ld_nea,         &
+      &                       kbdyobs, ld_bound_reject,         &
+      &                       kqc_cutoff                        )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_coo_spc_3d  ***
+      !!
+      !! ** Purpose : Check for points outside the domain and land points
+      !!              Reset depth of observation above highest model level
+      !!              to the value of highest model level
+      !!
+      !! ** Method  : Remove the observations that are outside the model space
+      !!              and time domain or located within model land cells.
+      !!
+      !!              NB. T and S profile observations lying between the ocean
+      !!              surface and the depth of the first model T point are 
+      !!              assigned a depth equal to that of the first model T pt.
+      !!
+      !! ** Action  : 
+      !!   
+      !! History :
+      !!        !  2007-01  (K. Mogensen) Rewrite of parts of obs_scr
+      !!        !  2007-06  (K. Mogensen et al) Reject obs. near land.
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE dom_oce, ONLY : &       ! Geographical information
+         & gdepw_1d,      &
+         & gdepw_0,       &                       
+         & gdepw_n,       &
+         & gdept_n,       &
+         & ln_zco,        &
+         & ln_zps             
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kprofno      ! Number of profiles
+      INTEGER, INTENT(IN) :: kobsno       ! Total number of observations
+      INTEGER, INTENT(IN) :: kpi          ! Number of grid points in (i,j,k)
+      INTEGER, INTENT(IN) :: kpj
+      INTEGER, INTENT(IN) :: kpk    
+      INTEGER, DIMENSION(kprofno), INTENT(IN) :: &
+         & kpstart, &         ! Start of individual profiles
+         & kpend              ! End of individual profiles
+      INTEGER, DIMENSION(kprofno), INTENT(IN) :: &
+         & kobsi, &           ! Observation (i,j) coordinates
+         & kobsj
+      INTEGER, DIMENSION(kobsno), INTENT(IN) :: &
+         & kobsk              ! Observation k coordinate
+      REAL(KIND=wp), DIMENSION(kprofno), INTENT(IN) :: &
+         & pobslam, &         ! Observation (lon,lat) coordinates
+         & pobsphi
+      REAL(KIND=wp), DIMENSION(kobsno), INTENT(INOUT) :: &
+         & pobsdep            ! Observation depths  
+      REAL(KIND=wp), DIMENSION(kpi,kpj), INTENT(IN) :: &
+         & plam, pphi         ! Model (lon,lat) coordinates
+      REAL(KIND=wp), DIMENSION(kpk), INTENT(IN) :: &
+         & pdep               ! Model depth coordinates
+      REAL(KIND=wp), DIMENSION(kpi,kpj,kpk), INTENT(IN) :: &
+         & pmask              ! Land mask array
+      INTEGER, DIMENSION(kprofno), INTENT(INOUT) :: &
+         & kpobsqc             ! Profile quality control
+      INTEGER, DIMENSION(kobsno), INTENT(INOUT) :: &
+         & kobsqc             ! Observation quality control
+      INTEGER, INTENT(INOUT) :: kosdobs     ! Observations outside space domain
+      INTEGER, INTENT(INOUT) :: klanobs     ! Observations within a model land cell
+      INTEGER, INTENT(INOUT) :: knlaobs     ! Observations near land
+      INTEGER, INTENT(INOUT) :: kbdyobs     ! Observations near boundary
+      LOGICAL, INTENT(IN) :: ld_nea         ! Flag observations near land
+      LOGICAL, INTENT(IN) :: ld_bound_reject  ! Flag observations near open boundary
+      INTEGER, INTENT(IN) :: kqc_cutoff     ! Cutoff QC value
+
+      !! * Local declarations
+      REAL(KIND=wp), DIMENSION(2,2,kpk,kprofno) :: &
+         & zgmsk              ! Grid mask
+      REAL(KIND=wp), DIMENSION(2,2,kprofno) :: &
+         & zbmsk              ! Boundary mask
+      REAL(KIND=wp), DIMENSION(jpi,jpj) :: zbdymask
+      REAL(KIND=wp), DIMENSION(2,2,kpk,kprofno) :: &
+         & zgdepw
+      REAL(KIND=wp), DIMENSION(2,2,kprofno) :: &
+         & zglam, &           ! Model longitude at grid points
+         & zgphi              ! Model latitude at grid points
+      INTEGER, DIMENSION(2,2,kprofno) :: &
+         & igrdi, &           ! Grid i,j
+         & igrdj
+      LOGICAL :: lgridobs           ! Is observation on a model grid point.
+      LOGICAL :: ll_next_to_land    ! Is a profile next to land 
+      INTEGER :: iig, ijg           ! i,j of observation on model grid point.
+      INTEGER :: jobs, jobsp, jk, ji, jj
+      !!----------------------------------------------------------------------
+
+      ! Get grid point indices
+      
+      DO jobs = 1, kprofno
+
+         ! For invalid points use 2,2
+
+         IF ( kpobsqc(jobs) >= kqc_cutoff ) THEN
+            
+            igrdi(1,1,jobs) = 1
+            igrdj(1,1,jobs) = 1
+            igrdi(1,2,jobs) = 1
+            igrdj(1,2,jobs) = 2
+            igrdi(2,1,jobs) = 2
+            igrdj(2,1,jobs) = 1
+            igrdi(2,2,jobs) = 2
+            igrdj(2,2,jobs) = 2
+            
+         ELSE
+            
+            igrdi(1,1,jobs) = kobsi(jobs)-1
+            igrdj(1,1,jobs) = kobsj(jobs)-1
+            igrdi(1,2,jobs) = kobsi(jobs)-1
+            igrdj(1,2,jobs) = kobsj(jobs)
+            igrdi(2,1,jobs) = kobsi(jobs)
+            igrdj(2,1,jobs) = kobsj(jobs)-1
+            igrdi(2,2,jobs) = kobsi(jobs)
+            igrdj(2,2,jobs) = kobsj(jobs)
+            
+         ENDIF
+         
+      END DO
+
+      IF (ln_bdy) THEN
+        ! Create a mask grid points in boundary rim
+        IF (ld_bound_reject) THEN           
+           zbdymask(:,:) = 1.0_wp
+           DO ji = 1, nb_bdy
+              DO jj = 1, idx_bdy(ji)%nblen(1)
+                 zbdymask(idx_bdy(ji)%nbi(jj,1),idx_bdy(ji)%nbj(jj,1)) = 0.0_wp
+              ENDDO
+           ENDDO
+        ENDIF
+   
+        CALL obs_int_comm_2d( 2, 2, kprofno, kpi, kpj, igrdi, igrdj, zbdymask, zbmsk )
+      ENDIF
+      
+      CALL obs_int_comm_3d( 2, 2, kprofno, kpi, kpj, kpk, igrdi, igrdj, pmask, zgmsk )
+      CALL obs_int_comm_2d( 2, 2, kprofno, kpi, kpj, igrdi, igrdj, plam, zglam )
+      CALL obs_int_comm_2d( 2, 2, kprofno, kpi, kpj, igrdi, igrdj, pphi, zgphi )
+      CALL obs_int_comm_3d( 2, 2, kprofno, kpi, kpj, kpk, igrdi, igrdj, gdepw_n(:,:,:), &
+        &                     zgdepw )
+
+      DO jobs = 1, kprofno
+
+         ! Skip bad profiles
+         IF ( kpobsqc(jobs) >= kqc_cutoff ) CYCLE
+
+         ! Check if this observation is on a grid point
+
+         lgridobs = .FALSE.
+         iig = -1
+         ijg = -1
+         DO jj = 1, 2
+            DO ji = 1, 2
+               IF ( ( ABS( zgphi(ji,jj,jobs) - pobsphi(jobs) ) < 1.0e-6_wp ) &
+                  & .AND. &
+                  & ( ABS( MOD( zglam(ji,jj,jobs) - pobslam(jobs),360.0) ) < 1.0e-6_wp ) &
+                  & ) THEN
+                  lgridobs = .TRUE.
+                  iig = ji
+                  ijg = jj
+               ENDIF
+            END DO
+         END DO
+
+         ! Check if next to land
+         IF (  ANY( zgmsk(1:2,1:2,1,jobs) == 0.0_wp ) ) THEN
+            ll_next_to_land=.TRUE.
+         ELSE
+            ll_next_to_land=.FALSE.
+         ENDIF 
+
+         ! Reject observations
+
+         DO jobsp = kpstart(jobs), kpend(jobs)
+
+            ! Flag if the observation falls outside the model spatial domain
+            IF (       ( pobslam(jobs) < -180.         )       &
+               &  .OR. ( pobslam(jobs) >  180.         )       &
+               &  .OR. ( pobsphi(jobs) <  -90.         )       &
+               &  .OR. ( pobsphi(jobs) >   90.         )       &
+               &  .OR. ( pobsdep(jobsp) < 0.0          )       &
+               &  .OR. ( pobsdep(jobsp) > gdepw_1d(kpk)) ) THEN
+               kobsqc(jobsp) = IBSET(kobsqc(jobsp),11)
+               kosdobs = kosdobs + 1
+               CYCLE
+            ENDIF
+
+            ! To check if an observations falls within land:
+             
+            ! Flag if the observation is deeper than the bathymetry
+            ! Or if it is within the mask
+            IF ( ALL( zgdepw(1:2,1:2,kpk,jobs) < pobsdep(jobsp) ) &
+               &     .OR. &
+               &  ( SUM( zgmsk(1:2,1:2,kobsk(jobsp)-1:kobsk(jobsp),jobs) ) &
+               &  == 0.0_wp) ) THEN
+               kobsqc(jobsp) = IBSET(kobsqc(jobsp),10)
+               klanobs = klanobs + 1
+               CYCLE
+            ENDIF
+               
+            ! Flag if the observation is close to land
+            IF ( ll_next_to_land ) THEN
+               knlaobs = knlaobs + 1
+               IF (ld_nea) THEN   
+                  kobsqc(jobsp) = IBSET(kobsqc(jobsp),10)
+               ENDIF 
+            ENDIF
+            
+            ! For observations on the grid reject them if their are at
+            ! a masked point
+            
+            IF (lgridobs) THEN
+               IF (zgmsk(iig,ijg,kobsk(jobsp)-1,jobs) == 0.0_wp ) THEN
+                  kobsqc(jobsp) = IBSET(kobsqc(jobs),10)
+                  klanobs = klanobs + 1
+                  CYCLE
+               ENDIF
+            ENDIF
+            
+            ! Flag if the observation falls is close to land
+            IF ( MINVAL( zgmsk(1:2,1:2,kobsk(jobsp)-1:kobsk(jobsp),jobs) ) == &
+               &  0.0_wp) THEN
+               IF (ld_nea) kobsqc(jobsp) = kobsqc(jobsp) + 14
+               knlaobs = knlaobs + 1
+            ENDIF
+
+            ! Set observation depth equal to that of the first model depth
+            IF ( pobsdep(jobsp) <= pdep(1) ) THEN
+               pobsdep(jobsp) = pdep(1)  
+            ENDIF
+            
+            IF (ln_bdy) THEN
+               ! Flag if the observation falls close to the boundary rim
+               IF (ld_bound_reject) THEN
+                  IF ( MINVAL( zbmsk(1:2,1:2,jobs) ) == 0.0_wp ) THEN
+                     kobsqc(jobsp) = IBSET(kobsqc(jobs),8)
+                     kbdyobs = kbdyobs + 1
+                     CYCLE
+                  ENDIF
+                  ! for observations on the grid...
+                  IF (lgridobs) THEN
+                     IF (zbmsk(iig,ijg,jobs) == 0.0_wp ) THEN
+                        kobsqc(jobsp) = IBSET(kobsqc(jobs),8)
+                        kbdyobs = kbdyobs + 1
+                        CYCLE
+                     ENDIF
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+         END DO
+      END DO
+      !
+   END SUBROUTINE obs_coo_spc_3d
+
+
+   SUBROUTINE obs_pro_rej( profdata, kqc_cutoff )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_pro_rej ***
+      !!
+      !! ** Purpose : Reject all data within a rejected profile
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :   2007-10  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      TYPE(obs_prof), INTENT(inout) ::   profdata     ! Profile data
+      INTEGER       , INTENT(in   ) ::   kqc_cutoff   ! QC cutoff value
+      !
+      INTEGER :: jprof
+      INTEGER :: jvar
+      INTEGER :: jobs
+      !!----------------------------------------------------------------------
+      
+      ! Loop over profiles
+
+      DO jprof = 1, profdata%nprof
+
+         IF ( profdata%nqc(jprof) > kqc_cutoff ) THEN
+            
+            DO jvar = 1, profdata%nvar
+
+               DO jobs = profdata%npvsta(jprof,jvar),  &
+                  &      profdata%npvend(jprof,jvar)
+                  
+                  profdata%var(jvar)%nvqc(jobs) = &
+                     & IBSET(profdata%var(jvar)%nvqc(jobs),14)
+
+               END DO
+
+            END DO
+
+         ENDIF
+
+      END DO
+      !
+   END SUBROUTINE obs_pro_rej
+
+
+   SUBROUTINE obs_uv_rej( profdata, knumu, knumv, kqc_cutoff )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE obs_uv_rej ***
+      !!
+      !! ** Purpose : Reject u if v is rejected and vice versa
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!   
+      !! History :   2009-2  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      TYPE(obs_prof), INTENT(INOUT) :: profdata   ! Profile data
+      INTEGER, INTENT(INOUT) :: knumu             ! Number of u rejected
+      INTEGER, INTENT(INOUT) :: knumv             ! Number of v rejected
+      INTEGER, INTENT(IN) :: kqc_cutoff           ! QC cutoff value
+      !
+      INTEGER :: jprof
+      INTEGER :: jvar
+      INTEGER :: jobs
+      !!----------------------------------------------------------------------
+
+      DO jprof = 1, profdata%nprof      !==  Loop over profiles  ==!
+         !
+         IF ( ( profdata%npvsta(jprof,1) /= profdata%npvsta(jprof,2) ) .OR. &
+            & ( profdata%npvend(jprof,1) /= profdata%npvend(jprof,2) ) ) THEN
+            !
+            CALL ctl_stop('U,V profiles inconsistent in obs_uv_rej')
+            RETURN
+            !
+         ENDIF
+         !
+         DO jobs = profdata%npvsta(jprof,1), profdata%npvend(jprof,1)
+            !  
+            IF ( ( profdata%var(1)%nvqc(jobs) >  kqc_cutoff ) .AND. &
+               & ( profdata%var(2)%nvqc(jobs) <=  kqc_cutoff) ) THEN
+               profdata%var(2)%nvqc(jobs) = IBSET(profdata%var(1)%nvqc(jobs),15)
+               knumv = knumv + 1
+            ENDIF
+            IF ( ( profdata%var(2)%nvqc(jobs) >  kqc_cutoff ) .AND. &
+               & ( profdata%var(1)%nvqc(jobs) <=  kqc_cutoff) ) THEN
+               profdata%var(1)%nvqc(jobs) = IBSET(profdata%var(1)%nvqc(jobs),15)
+               knumu = knumu + 1
+            ENDIF
+            !
+         END DO
+         !
+      END DO
+      !
+   END SUBROUTINE obs_uv_rej
+
+   !!=====================================================================
+END MODULE obs_prep
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles.F90	(revision 14097)
@@ -0,0 +1,39 @@
+MODULE obs_profiles
+   !!=====================================================================
+   !!                       ***  MODULE  obs_profiles  ***
+   !! Observation diagnostics: Storage space for profile observations
+   !!                          arrays and additional flags etc.
+   !!=====================================================================
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   
+   !! * Modules used 
+   USE obs_profiles_def ! Definition of profile data types and tools
+
+   IMPLICIT NONE
+   
+   SAVE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC nprofsets, nprofvars, nprofextr, profdata, prodatqc
+   PUBLIC nvelosets, nvelovars, nveloextr, velodata, veldatqc
+   
+   !! * Shared Module variables
+   INTEGER :: nprofsets                    ! Total number of profile data sets
+   INTEGER :: nprofvars                    ! Total number of variables for profiles
+   INTEGER :: nprofextr                    ! Extra fields for each variable
+   TYPE(obs_prof), POINTER ::  profdata(:) ! Initial profile data
+   TYPE(obs_prof), POINTER ::  prodatqc(:) ! Profile data after quality control
+
+   INTEGER :: nvelosets                     ! Total number of velocity profile data sets
+   INTEGER :: nvelovars                     ! Total number of variables for profiles
+   INTEGER :: nveloextr                     ! Extra fields for each variable
+   TYPE(obs_prof), POINTER ::  velodata(:)  ! Initial velocity profile data
+   TYPE(obs_prof), POINTER ::  veldatqc(:)  ! Velocity profile data after quality control
+END MODULE obs_profiles
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles_def.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles_def.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_profiles_def.F90	(revision 14097)
@@ -0,0 +1,928 @@
+MODULE obs_profiles_def
+   !!=====================================================================
+   !!                       ***  MODULE  obs_profiles_def  ***
+   !! Observation diagnostics: Storage handling for T,S profiles
+   !!                          arrays and additional flags etc.
+   !!                          This module only defines the data type and
+   !!                          operations on the data type. There is no
+   !!                          actual data in the module.
+   !!===================================================================== 
+
+   !!----------------------------------------------------------------------
+   !!   obs_prof            : F90 type containing the profile information
+   !!   obs_prof_var        : F90 type containing the variable definition
+   !!   obs_prof_valid       : F90 type containing the valid obs. definition
+   !!   obs_prof_alloc      : Allocates profile arrays
+   !!   obs_prof_dealloc    : Deallocates profile arrays
+   !!   obs_prof_compress   : Extract sub-information from a obs_prof type
+   !!                         to a new obs_prof type
+   !!   obs_prof_decompress : Reinsert sub-information from a obs_prof type
+   !!                         into the original obs_prof type
+   !!   obs_prof_staend     : Set npvsta and npvend of a variable within an 
+   !!                         obs_prof_var type
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : & ! Precision variables
+      & wp         
+   USE in_out_manager     ! I/O manager
+   USE obs_mpp, ONLY : &  ! MPP tools 
+      obs_mpp_sum_integers
+   USE obs_fbm            ! Obs feedback format
+   USE lib_mpp, ONLY : &
+      & ctl_warn, ctl_stop
+
+   IMPLICIT NONE
+
+   !! * Routine/type accessibility
+   PRIVATE
+
+   PUBLIC &
+      & obs_prof,           &
+      & obs_prof_var,       &
+      & obs_prof_valid,     &
+      & obs_prof_alloc,     &
+      & obs_prof_alloc_var, &
+      & obs_prof_dealloc,   &
+      & obs_prof_compress,  &
+      & obs_prof_decompress,&
+      & obs_prof_staend
+
+   !! * Type definition for valid observations
+
+   TYPE obs_prof_valid
+      
+      LOGICAL, POINTER, DIMENSION(:) :: luse
+
+   END TYPE obs_prof_valid
+
+   !! * Type definition for each variable
+
+   TYPE obs_prof_var
+
+      ! Arrays with size equal to the number of observations
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & mvk,   &       !: k-th grid coord. for interpolating to profile data
+         & nvpidx,&       !: Profile number
+         & nvlidx,&       !: Level number in profile
+         & nvqc,  &       !: Variable QC flags
+         & idqc           !: Depth QC flag
+
+      REAL(KIND=wp), POINTER, DIMENSION(:) :: &
+         & vdep,  &       !: Depth coordinate of profile data
+         & vobs,  &       !: Profile data
+         & vmod           !: Model counterpart of the profile data vector
+
+      REAL(KIND=wp), POINTER, DIMENSION(:,:) :: &
+         & vext           !: Extra variables
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & nvind          !: Source indices of temp. data in compressed data
+
+      ! Arrays with size equal to idefnqcf times the number of observations
+      INTEGER, POINTER, DIMENSION(:,:) :: &
+         & idqcf,  &      !: Depth QC flags
+         & nvqcf          !: Variable QC flags
+
+   END TYPE obs_prof_var
+
+   !! * Type definition for profile observation type
+
+   TYPE obs_prof
+
+      ! Bookkeeping
+
+      INTEGER :: nvar     !: Number of variables
+      INTEGER :: next     !: Number of extra fields
+      INTEGER :: nprof    !: Total number of profiles within window.
+      INTEGER :: nstp     !: Number of time steps
+      INTEGER :: npi      !: Number of 3D grid points
+      INTEGER :: npj
+      INTEGER :: npk
+      INTEGER :: nprofup  !: Observation counter used in obs_oper
+
+      ! Bookkeeping arrays with sizes equal to number of variables
+
+      CHARACTER(len=8), POINTER, DIMENSION(:) :: &
+         & cvars          !: Variable names
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & nvprot,   &    !: Local total number of profile T data
+         & nvprotmpp      !: Global total number of profile T data
+      
+      ! Arrays with size equal to the number of profiles
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & npidx,&        !: Profile number
+         & npfil,&        !: Profile number in file
+         & nyea, &        !: Year of profile
+         & nmon, &        !: Month of profile
+         & nday, &        !: Day of profile
+         & nhou, &        !: Hour of profile
+         & nmin, &        !: Minute of profile
+         & mstp, &        !: Time step nearest to profile
+         & nqc,  &        !: Profile QC
+         & ntyp, &        !: Type of profile product (WMO table 1770)
+         & ipqc, &        !: Position QC
+         & itqc           !: Time QC
+
+      REAL(KIND=wp), POINTER, DIMENSION(:) :: &
+         & rlam, &        !: Longitude coordinate of profile data
+         & rphi           !: Latitude coordinate of profile data
+
+      CHARACTER(LEN=8), POINTER, DIMENSION(:) :: &
+         & cwmo           !: Profile WMO indentifier
+      
+      ! Arrays with size equal to the number of profiles times
+      ! number of variables
+
+      INTEGER, POINTER, DIMENSION(:,:) :: &
+         & npvsta, &      !: Start of each variable profile in full arrays
+         & npvend, &      !: End of each variable profile in full arrays
+         & mi,     &      !: i-th grid coord. for interpolating to profile T data
+         & mj,     &      !: j-th grid coord. for interpolating to profile T data
+         & ivqc           !: QC flags for all levels for a variable
+
+      ! Arrays with size equal to idefnqcf
+      ! the number of profiles times number of variables
+      INTEGER, POINTER, DIMENSION(:,:) :: &
+         & nqcf,  &       !: Observation QC flags
+         & ipqcf, &       !: Position QC flags
+         & itqcf          !: Time QC flags
+
+      ! Arrays with size equal to idefnqcf
+      ! the number of profiles times number of variables
+      INTEGER, POINTER, DIMENSION(:,:,:) :: &
+         & ivqcf
+
+      ! Arrays of variables
+
+      TYPE(obs_prof_var), POINTER, DIMENSION(:) :: var
+
+      ! Arrays with size equal to the number of time steps in the window
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & npstp,    &    !: Total number of profiles
+         & npstpmpp       !: Total number of profiles
+
+      ! Arrays with size equal to the number of time steps in the window times
+      ! number of variables
+
+      INTEGER, POINTER, DIMENSION(:,:) :: &
+         & nvstp,    &    !: Local total num. of profile data each time step 
+         & nvstpmpp       !: Global total num. of profile data each time step
+      
+      ! Arrays with size equal to the number of grid points times number of
+      ! variables
+
+      REAL(KIND=wp), POINTER, DIMENSION(:,:,:,:) :: &
+         & vdmean        !: Daily averaged model field
+
+      ! Arrays used to store source indices when 
+      ! compressing obs_prof derived types
+      
+      ! Array with size nprof
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & npind         !: Source indices of profile data in compressed data
+
+   END TYPE obs_prof
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+   
+   SUBROUTINE obs_prof_alloc( prof,  kvar, kext, kprof,  &
+      &                       ko3dt, kstp, kpi, kpj, kpk )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_alloc  ***
+      !!                      
+      !! ** Purpose : - Allocate data for profile arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-01  (K. Mogensen) Original code
+      !!        !  07-03  (K. Mogensen) Generalized profiles
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: prof      ! Profile data to be allocated
+      INTEGER, INTENT(IN) :: kprof  ! Number of profiles
+      INTEGER, INTENT(IN) :: kvar   ! Number of variables
+      INTEGER, INTENT(IN) :: kext   ! Number of extra fields within each variable
+      INTEGER, INTENT(IN), DIMENSION(kvar) :: &
+         & ko3dt     ! Number of observations per variables
+      INTEGER, INTENT(IN) :: kstp   ! Number of time steps
+      INTEGER, INTENT(IN) :: kpi    ! Number of 3D grid points
+      INTEGER, INTENT(IN) :: kpj
+      INTEGER, INTENT(IN) :: kpk
+
+      !!* Local variables
+      INTEGER :: jvar
+      INTEGER :: ji
+
+      ! Set bookkeeping variables
+
+      prof%nvar      = kvar
+      prof%next      = kext
+      prof%nprof     = kprof
+
+      prof%nstp      = kstp
+      prof%npi       = kpi
+      prof%npj       = kpj
+      prof%npk       = kpk
+
+      ! Allocate arrays of size number of variables
+
+      ALLOCATE( &
+         & prof%cvars(kvar),    &
+         & prof%nvprot(kvar),   &
+         & prof%nvprotmpp(kvar) &
+         )
+         
+      DO jvar = 1, kvar
+         prof%cvars    (jvar) = "NotSet"
+         prof%nvprot   (jvar) = ko3dt(jvar)
+         prof%nvprotmpp(jvar) = 0
+      END DO
+
+      ! Allocate arrays of size number of profiles
+      ! times number of variables
+      
+      ALLOCATE( &
+         & prof%npvsta(kprof,kvar), &  
+         & prof%npvend(kprof,kvar), &
+         & prof%mi(kprof,kvar),     &
+         & prof%mj(kprof,kvar),     &
+         & prof%ivqc(kprof,kvar)    &
+         )
+
+      ! Allocate arrays of size iqcfdef times number of profiles
+      ! times number of variables
+
+      ALLOCATE( &
+         & prof%ivqcf(idefnqcf,kprof,kvar) &
+         & )
+
+      ! Allocate arrays of size number of profiles
+
+      ALLOCATE( &
+         & prof%npidx(kprof),   &
+         & prof%npfil(kprof),   &
+         & prof%nyea(kprof),    &
+         & prof%nmon(kprof),    &
+         & prof%nday(kprof),    &
+         & prof%nhou(kprof),    &
+         & prof%nmin(kprof),    &
+         & prof%mstp(kprof),    &
+         & prof%nqc(kprof),     &
+         & prof%ipqc(kprof),    &
+         & prof%itqc(kprof),    &
+         & prof%ntyp(kprof),    &
+         & prof%rlam(kprof),    &
+         & prof%rphi(kprof),    &
+         & prof%cwmo(kprof),    &
+         & prof%npind(kprof)    &
+         & )
+
+      ! Allocate arrays of size idefnqcf times number of profiles
+
+      ALLOCATE( &
+         & prof%nqcf(idefnqcf,kprof),  &
+         & prof%ipqcf(idefnqcf,kprof), &
+         & prof%itqcf(idefnqcf,kprof)  &
+         & )
+
+      ! Allocate obs_prof_var type
+      ALLOCATE( &
+         & prof%var(kvar) &
+         & )
+
+      ! For each variables allocate arrays of size number of observations
+
+      DO jvar = 1, kvar
+
+         IF ( ko3dt(jvar) >= 0 ) THEN
+            CALL obs_prof_alloc_var( prof, jvar, kext, ko3dt(jvar) )
+         ENDIF
+         
+      END DO
+
+      ! Allocate arrays of size number of time step size
+
+      ALLOCATE( &
+         & prof%npstp(kstp),   &
+         & prof%npstpmpp(kstp) &
+         & )
+
+      ! Allocate arrays of size number of time step size times 
+      ! number of variables
+      
+      ALLOCATE( &
+         & prof%nvstp(kstp,kvar),   &
+         & prof%nvstpmpp(kstp,kvar) &
+         & )
+
+      ! Allocate arrays of size number of grid points size times
+      ! number of variables
+
+      ALLOCATE( &
+         & prof%vdmean(kpi,kpj,kpk,kvar) &
+         & )
+
+      ! Set defaults for compression indices
+      
+      DO ji = 1, kprof
+         prof%npind(ji) = ji
+      END DO
+
+      DO jvar = 1, kvar
+         DO ji = 1, ko3dt(jvar)
+            prof%var(jvar)%nvind(ji) = ji
+         END DO
+      END DO
+
+      ! Set defaults for number of observations per time step
+
+      prof%npstp(:)      = 0
+      prof%npstpmpp(:)   = 0
+      prof%nvstp(:,:)    = 0
+      prof%nvstpmpp(:,:) = 0
+      
+      ! Set the observation counter used in obs_oper
+
+      prof%nprofup     = 0
+
+   END SUBROUTINE obs_prof_alloc
+
+   SUBROUTINE obs_prof_dealloc( prof )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_dealloc  ***
+      !!                      
+      !! ** Purpose : - Deallocate data for profile arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-01  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: &
+         & prof      ! Profile data to be deallocated
+
+      !!* Local variables
+      INTEGER :: &
+         & jvar
+
+      ! Deallocate arrays of size number of profiles
+      ! times number of variables
+      
+      DEALLOCATE( &
+         & prof%npvsta, &  
+         & prof%npvend  &
+         )
+
+      ! Dellocate arrays of size number of profiles size
+
+      DEALLOCATE( &
+         & prof%mi,      &
+         & prof%mj,      &
+         & prof%ivqc,    &
+         & prof%ivqcf,   &
+         & prof%npidx,   &
+         & prof%npfil,   &
+         & prof%nyea,    &
+         & prof%nmon,    &
+         & prof%nday,    &
+         & prof%nhou,    &
+         & prof%nmin,    &
+         & prof%mstp,    &
+         & prof%nqc,     &
+         & prof%ipqc,    &
+         & prof%itqc,    &
+         & prof%nqcf,    &
+         & prof%ipqcf,   &
+         & prof%itqcf,   &
+         & prof%ntyp,    &
+         & prof%rlam,    &
+         & prof%rphi,    &
+         & prof%cwmo,    &
+         & prof%npind    &
+         & )
+
+      ! For each variables allocate arrays of size number of observations
+
+      DO jvar = 1, prof%nvar
+
+         IF ( prof%nvprot(jvar) >= 0 ) THEN
+
+            CALL obs_prof_dealloc_var( prof, jvar )
+
+         ENDIF
+         
+      END DO
+
+      ! Dellocate obs_prof_var type
+      DEALLOCATE( &
+         & prof%var &
+         & )
+
+      ! Deallocate arrays of size number of time step size
+
+      DEALLOCATE( &
+         & prof%npstp,   &
+         & prof%npstpmpp &
+         & )
+
+      ! Deallocate arrays of size number of time step size times 
+      ! number of variables
+      
+      DEALLOCATE( &
+         & prof%nvstp,   &
+         & prof%nvstpmpp &
+         & )
+
+      ! Deallocate arrays of size number of grid points size times
+      ! number of variables
+
+      DEALLOCATE( &
+         & prof%vdmean &
+         & )
+
+      ! Dellocate arrays of size number of variables
+
+      DEALLOCATE( &
+         & prof%cvars,    &
+         & prof%nvprot,   &
+         & prof%nvprotmpp &
+         )
+
+
+   END SUBROUTINE obs_prof_dealloc
+
+
+   SUBROUTINE obs_prof_alloc_var( prof, kvar, kext, kobs )
+
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_alloc_var  ***
+      !!                      
+      !! ** Purpose : - Allocate data for variable data in profile arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-03  (K. Mogensen) Original code
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: prof   ! Profile data to be allocated
+      INTEGER, INTENT(IN) :: kvar   ! Variable number
+      INTEGER, INTENT(IN) :: kext   ! Number of extra fields within each variable
+      INTEGER, INTENT(IN) :: kobs   ! Number of observations
+      
+      ALLOCATE( & 
+         & prof%var(kvar)%mvk(kobs),       &
+         & prof%var(kvar)%nvpidx(kobs),    &
+         & prof%var(kvar)%nvlidx(kobs),    &
+         & prof%var(kvar)%nvqc(kobs),      &
+         & prof%var(kvar)%idqc(kobs),      &
+         & prof%var(kvar)%vdep(kobs),      &
+         & prof%var(kvar)%vobs(kobs),      &
+         & prof%var(kvar)%vmod(kobs),      &
+         & prof%var(kvar)%nvind(kobs)      &
+         & )
+      ALLOCATE( & 
+         & prof%var(kvar)%idqcf(idefnqcf,kobs), &
+         & prof%var(kvar)%nvqcf(idefnqcf,kobs)  &
+         & )
+      IF (kext>0) THEN
+         ALLOCATE( & 
+            & prof%var(kvar)%vext(kobs,kext) &
+            & )
+      ENDIF
+
+   END SUBROUTINE obs_prof_alloc_var
+
+   SUBROUTINE obs_prof_dealloc_var( prof, kvar )
+
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_alloc_var  ***
+      !!                      
+      !! ** Purpose : - Allocate data for variable data in profile arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-03  (K. Mogensen) Original code
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: prof   ! Profile data to be allocated
+      INTEGER, INTENT(IN) :: kvar      ! Variable number
+      
+      DEALLOCATE( & 
+         & prof%var(kvar)%mvk,    &
+         & prof%var(kvar)%nvpidx, &
+         & prof%var(kvar)%nvlidx, &
+         & prof%var(kvar)%nvqc,   &
+         & prof%var(kvar)%idqc,   &
+         & prof%var(kvar)%vdep,   &
+         & prof%var(kvar)%vobs,   &
+         & prof%var(kvar)%vmod,   &
+         & prof%var(kvar)%nvind,  &
+         & prof%var(kvar)%idqcf,  &
+         & prof%var(kvar)%nvqcf   &
+         & )
+      IF (prof%next>0) THEN
+         DEALLOCATE( & 
+            & prof%var(kvar)%vext  &
+            & )
+      ENDIF
+
+   END SUBROUTINE obs_prof_dealloc_var
+
+   SUBROUTINE obs_prof_compress( prof,   newprof, lallocate, &
+      &                          kumout, lvalid,   lvvalid )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_compress  ***
+      !!                      
+      !! ** Purpose : - Extract sub-information from a obs_prof type
+      !!                into a new obs_prof type
+      !! 
+      !! ** Method  : - The data is copied from prof to new prof.
+      !!                In the case of lvalid and lvvalid both being
+      !!                present only the selected data will be copied.
+      !!                If lallocate is true the data in the newprof is 
+      !!                allocated either with the same number of elements
+      !!                as prof or with only the subset of elements defined
+      !!                by the optional selection in lvalid and lvvalid
+      !!
+      !! History :
+      !!        !  07-01  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_prof), INTENT(IN)    :: prof      ! Original profile
+      TYPE(obs_prof), INTENT(INOUT) :: newprof   ! New profile with the copy of the data
+      LOGICAL :: lallocate                ! Allocate newprof data
+      INTEGER,INTENT(IN) :: kumout        ! Fortran unit for messages
+      TYPE(obs_prof_valid), OPTIONAL, INTENT(in) :: &
+         & lvalid        ! Valid profiles
+      TYPE(obs_prof_valid), OPTIONAL, INTENT(in), DIMENSION(prof%nvar) :: &
+         & lvvalid       ! Valid data within the profiles
+      
+      !!* Local variables
+      INTEGER :: inprof
+      INTEGER, DIMENSION(prof%nvar) :: &
+         & invpro
+      INTEGER :: jvar
+      INTEGER :: jext
+      INTEGER :: ji
+      INTEGER :: jj 
+      LOGICAL :: lfirst
+      TYPE(obs_prof_valid) :: &
+         & llvalid
+      TYPE(obs_prof_valid), DIMENSION(prof%nvar) :: &
+         & llvvalid
+      LOGICAL :: lallpresent
+      LOGICAL :: lnonepresent
+
+      ! Check that either all or none of the masks are persent.
+
+      lallpresent  = .FALSE.
+      lnonepresent = .FALSE.
+      IF ( PRESENT(lvalid) .AND. PRESENT(lvvalid) ) THEN
+         lallpresent =  .TRUE.
+      ELSEIF ( ( .NOT. PRESENT(lvalid)  ) .AND. &
+         &     ( .NOT. PRESENT(lvvalid) ) ) THEN
+         lnonepresent = .TRUE.
+      ELSE
+         CALL ctl_stop('Error in obs_prof_compress:', &
+            &          'Either all selection variables should be set', &
+            &          'or no selection variable should be set' )
+      ENDIF
+      
+      ! Count how many elements there should be in the new data structure
+
+      IF ( lallpresent ) THEN
+         inprof = 0
+         invpro(:) = 0
+         DO ji = 1, prof%nprof
+            IF ( lvalid%luse(ji) ) THEN
+               inprof=inprof+1
+               DO jvar = 1, prof%nvar
+                  DO jj = prof%npvsta(ji,jvar), prof%npvend(ji,jvar)
+                     IF ( lvvalid(jvar)%luse(jj) ) &
+                        &           invpro(jvar) = invpro(jvar) +1
+                  END DO
+               END DO
+            ENDIF
+         END DO
+      ELSE
+         inprof    = prof%nprof
+         invpro(:) = prof%nvprot(:)
+      ENDIF
+
+      ! Optionally allocate data in the new data structure
+
+      IF ( lallocate ) THEN
+         CALL obs_prof_alloc( newprof,   prof%nvar, &
+            &                 prof%next,            &
+            &                 inprof,    invpro,    &
+            &                 prof%nstp, prof%npi,  &
+            &                 prof%npj,  prof%npk )
+      ENDIF
+
+      ! Allocate temporary mask array to unify the code for both cases
+
+      ALLOCATE( llvalid%luse(prof%nprof) )
+      DO jvar = 1, prof%nvar
+         ALLOCATE( llvvalid(jvar)%luse(prof%nvprot(jvar)) )
+      END DO
+      IF ( lallpresent ) THEN
+         llvalid%luse(:) = lvalid%luse(:)
+         DO jvar = 1, prof%nvar
+            llvvalid(jvar)%luse(:) = lvvalid(jvar)%luse(:)
+         END DO
+      ELSE
+         llvalid%luse(:) = .TRUE.
+         DO jvar = 1, prof%nvar
+            llvvalid(jvar)%luse(:) = .TRUE.
+         END DO
+      ENDIF
+
+      ! Setup bookkeeping variables
+
+      inprof    = 0
+      invpro(:) = 0
+
+      newprof%npvsta(:,:) =  0
+      newprof%npvend(:,:) = -1
+      
+      ! Loop over source profiles
+
+      DO ji = 1, prof%nprof
+
+         IF ( llvalid%luse(ji) ) THEN
+
+            ! Copy the header information
+
+            inprof = inprof + 1
+
+            newprof%mi(inprof,:)  = prof%mi(ji,:)
+            newprof%mj(inprof,:) = prof%mj(ji,:)
+            newprof%npidx(inprof) = prof%npidx(ji)
+            newprof%npfil(inprof) = prof%npfil(ji)
+            newprof%nyea(inprof)  = prof%nyea(ji)
+            newprof%nmon(inprof)  = prof%nmon(ji)
+            newprof%nday(inprof)  = prof%nday(ji)
+            newprof%nhou(inprof)  = prof%nhou(ji)
+            newprof%nmin(inprof)  = prof%nmin(ji)
+            newprof%mstp(inprof)  = prof%mstp(ji)
+            newprof%nqc(inprof)   = prof%nqc(ji)
+            newprof%ipqc(inprof)  = prof%ipqc(ji)
+            newprof%itqc(inprof)  = prof%itqc(ji)
+            newprof%ivqc(inprof,:)= prof%ivqc(ji,:)
+            newprof%ntyp(inprof)  = prof%ntyp(ji)
+            newprof%rlam(inprof)  = prof%rlam(ji)
+            newprof%rphi(inprof)  = prof%rphi(ji)
+            newprof%cwmo(inprof)  = prof%cwmo(ji)
+            
+            ! QC info
+
+            newprof%nqcf(:,inprof)    = prof%nqcf(:,ji)
+            newprof%ipqcf(:,inprof)   = prof%ipqcf(:,ji)
+            newprof%itqcf(:,inprof)   = prof%itqcf(:,ji)
+            newprof%ivqcf(:,inprof,:) = prof%ivqcf(:,ji,:)
+            
+            ! npind is the index of the original profile
+            
+            newprof%npind(inprof) = ji
+
+            ! Copy the variable information
+
+            DO jvar = 1, prof%nvar
+
+               lfirst = .TRUE.
+               
+               DO jj = prof%npvsta(ji,jvar), prof%npvend(ji,jvar)
+                  
+                  IF ( llvvalid(jvar)%luse(jj) ) THEN
+
+                     invpro(jvar) = invpro(jvar) + 1
+                  
+                     ! Book keeping information
+                                    
+                     IF ( lfirst ) THEN
+                        lfirst = .FALSE.
+                        newprof%npvsta(inprof,jvar) = invpro(jvar)
+                     ENDIF
+                     newprof%npvend(inprof,jvar) = invpro(jvar)
+
+                     ! Variable data
+                     
+                     newprof%var(jvar)%mvk(invpro(jvar))    = &
+                        &                           prof%var(jvar)%mvk(jj)
+                     newprof%var(jvar)%nvpidx(invpro(jvar)) = &
+                        &                           prof%var(jvar)%nvpidx(jj)
+                     newprof%var(jvar)%nvlidx(invpro(jvar)) = &
+                        &                           prof%var(jvar)%nvlidx(jj)
+                     newprof%var(jvar)%nvqc(invpro(jvar))   = &
+                        &                           prof%var(jvar)%nvqc(jj)
+                     newprof%var(jvar)%idqc(invpro(jvar))   = &
+                        &                           prof%var(jvar)%idqc(jj)
+                     newprof%var(jvar)%idqcf(:,invpro(jvar))= &
+                        &                           prof%var(jvar)%idqcf(:,jj)
+                     newprof%var(jvar)%nvqcf(:,invpro(jvar))= &
+                        &                           prof%var(jvar)%nvqcf(:,jj)
+                     newprof%var(jvar)%vdep(invpro(jvar))   = &
+                        &                           prof%var(jvar)%vdep(jj)
+                     newprof%var(jvar)%vobs(invpro(jvar))   = &
+                        &                           prof%var(jvar)%vobs(jj)
+                     newprof%var(jvar)%vmod(invpro(jvar))   = &
+                        &                           prof%var(jvar)%vmod(jj)
+                     DO jext = 1, prof%next
+                        newprof%var(jvar)%vext(invpro(jvar),jext) = &
+                           &                      prof%var(jvar)%vext(jj,jext)
+                     END DO
+                  
+                     ! nvind is the index of the original variable data
+                     
+                     newprof%var(jvar)%nvind(invpro(jvar))  = jj
+                     
+                  ENDIF
+
+               END DO
+
+            END DO
+
+         ENDIF
+
+      END DO
+
+      ! Update MPP counters
+
+      DO jvar = 1, prof%nvar
+         newprof%nvprot(jvar) = invpro(jvar)
+      END DO
+      CALL obs_mpp_sum_integers ( newprof%nvprot, newprof%nvprotmpp,&
+         &                        prof%nvar )
+      
+      ! Set book keeping variables which do not depend on number of obs.
+
+      newprof%nvar     = prof%nvar
+      newprof%next     = prof%next
+      newprof%nstp     = prof%nstp
+      newprof%npi      = prof%npi
+      newprof%npj      = prof%npj
+      newprof%npk      = prof%npk
+      newprof%cvars(:) = prof%cvars(:)
+ 
+      ! Deallocate temporary data
+
+      DO jvar = 1, prof%nvar
+         DEALLOCATE( llvvalid(jvar)%luse )
+      END DO
+ 
+      DEALLOCATE( llvalid%luse )
+     
+   END SUBROUTINE obs_prof_compress
+
+   SUBROUTINE obs_prof_decompress( prof, oldprof, ldeallocate, kumout )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_decompress  ***
+      !!                      
+      !! ** Purpose : - Copy back information to original profile type
+      !!
+      !! ** Method  : - Reinsert updated information from a previous
+      !!                copied/compressed profile type into the original
+      !!                profile data and optionally deallocate the prof
+      !!                data input
+      !! 
+      !! History :
+      !!        !  07-01  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_prof),INTENT(INOUT) :: prof      ! Updated profile data
+      TYPE(obs_prof),INTENT(INOUT) :: oldprof   ! Original profile data
+      LOGICAL :: ldeallocate         ! Deallocate the updated data of insertion
+      INTEGER,INTENT(in) :: kumout   ! Output unit
+      
+      !!* Local variables
+      INTEGER :: jvar
+      INTEGER :: jext
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: jl
+
+      DO ji = 1, prof%nprof
+
+         ! Copy header information
+         
+         jk = prof%npind(ji)
+      
+         oldprof%mi(jk,:)  = prof%mi(ji,:)
+         oldprof%mj(jk,:)  = prof%mj(ji,:)
+         oldprof%npidx(jk) = prof%npidx(ji)
+         oldprof%npfil(jk) = prof%npfil(ji)
+         oldprof%nyea(jk)  = prof%nyea(ji)
+         oldprof%nmon(jk)  = prof%nmon(ji)
+         oldprof%nday(jk)  = prof%nday(ji)
+         oldprof%nhou(jk)  = prof%nhou(ji)
+         oldprof%nmin(jk)  = prof%nmin(ji)
+         oldprof%mstp(jk)  = prof%mstp(ji)
+         oldprof%nqc(jk)   = prof%nqc(ji)
+         oldprof%ipqc(jk)  = prof%ipqc(ji)
+         oldprof%itqc(jk)  = prof%itqc(ji)
+         oldprof%ivqc(jk,:)= prof%ivqc(ji,:)
+         oldprof%ntyp(jk)  = prof%ntyp(ji)
+         oldprof%rlam(jk)  = prof%rlam(ji)
+         oldprof%rphi(jk)  = prof%rphi(ji)
+         oldprof%cwmo(jk)  = prof%cwmo(ji)
+         
+         ! QC info
+
+         oldprof%nqcf(:,jk)    = prof%nqcf(:,ji)
+         oldprof%ipqcf(:,jk)   = prof%ipqcf(:,ji)
+         oldprof%itqcf(:,jk)   = prof%itqcf(:,ji)
+         oldprof%ivqcf(:,jk,:) = prof%ivqcf(:,ji,:)
+
+         ! Copy the variable information
+
+         DO jvar = 1, prof%nvar
+
+            DO jj = prof%npvsta(ji,jvar), prof%npvend(ji,jvar)
+               
+               jl = prof%var(jvar)%nvind(jj)
+
+               oldprof%var(jvar)%mvk(jl)    = prof%var(jvar)%mvk(jj)
+               oldprof%var(jvar)%nvpidx(jl) = prof%var(jvar)%nvpidx(jj)
+               oldprof%var(jvar)%nvlidx(jl) = prof%var(jvar)%nvlidx(jj)
+               oldprof%var(jvar)%nvqc(jl)   = prof%var(jvar)%nvqc(jj)
+               oldprof%var(jvar)%idqc(jl)   = prof%var(jvar)%idqc(jj)
+               oldprof%var(jvar)%vdep(jl)   = prof%var(jvar)%vdep(jj)
+               oldprof%var(jvar)%vobs(jl)   = prof%var(jvar)%vobs(jj)
+               oldprof%var(jvar)%vmod(jl)   = prof%var(jvar)%vmod(jj)
+               oldprof%var(jvar)%idqcf(:,jl) = prof%var(jvar)%idqcf(:,jj)
+               oldprof%var(jvar)%nvqcf(:,jl) = prof%var(jvar)%nvqcf(:,jj)
+               DO jext = 1, prof%next
+                  oldprof%var(jvar)%vext(jl,jext) = &
+                     &                        prof%var(jvar)%vext(jj,jext)
+               END DO
+               
+            END DO
+
+         END DO
+         
+      END DO
+
+      ! Optionally deallocate the updated profile data
+
+      IF ( ldeallocate ) CALL obs_prof_dealloc( prof )
+      
+   END SUBROUTINE obs_prof_decompress
+
+   SUBROUTINE obs_prof_staend( prof, kvarno )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_prof_decompress  ***
+      !!                      
+      !! ** Purpose : - Set npvsta and npvend of a variable within 
+      !!                an obs_prof_var type
+      !!
+      !! ** Method  : - Find the start and stop of a profile by searching 
+      !!                through the data
+      !! 
+      !! History :
+      !!        !  07-04  (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_prof),INTENT(INOUT) :: prof     ! Profile data
+      INTEGER,INTENT(IN) :: kvarno     ! Variable number
+
+      !!* Local variables
+      INTEGER :: ji
+      INTEGER :: iprofno
+
+      !-----------------------------------------------------------------------
+      ! Compute start and end bookkeeping arrays
+      !-----------------------------------------------------------------------
+
+      prof%npvsta(:,kvarno) = prof%nvprot(kvarno) + 1
+      prof%npvend(:,kvarno) = -1
+      DO ji = 1, prof%nvprot(kvarno)
+         iprofno = prof%var(kvarno)%nvpidx(ji)
+         prof%npvsta(iprofno,kvarno) = &
+            & MIN( ji, prof%npvsta(iprofno,kvarno) )
+         prof%npvend(iprofno,kvarno) = &
+            & MAX( ji, prof%npvend(iprofno,kvarno) )
+      END DO
+
+      DO ji = 1, prof%nprof
+         IF ( prof%npvsta(ji,kvarno) == ( prof%nvprot(kvarno) + 1 ) ) &
+            & prof%npvsta(ji,kvarno) = 0
+      END DO
+
+   END SUBROUTINE obs_prof_staend
+   
+END MODULE obs_profiles_def
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_altbias.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_altbias.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_altbias.F90	(revision 14097)
@@ -0,0 +1,204 @@
+MODULE obs_read_altbias
+   !!======================================================================
+   !!                       ***  MODULE obs_readaltbias  ***
+   !! Observation diagnostics: Read the bias for SLA data
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_rea_altbias : Driver for reading altimeter bias
+   !!----------------------------------------------------------------------
+
+   !! * Modules used   
+   USE par_kind, ONLY : &       ! Precision variables
+      & wp, &
+      & dp, &
+      & sp
+   USE par_oce, ONLY : &        ! Domain parameters
+      & jpi, &
+      & jpj, &
+      & jpim1
+   USE in_out_manager, ONLY : & ! I/O manager
+      & lwp,    &
+      & numout 
+   USE obs_surf_def             ! Surface observation definitions
+   USE dom_oce, ONLY : &        ! Domain variables
+      & tmask, &
+      & tmask_i, &
+      & e1t,   &
+      & e2t,   &
+      & gphit
+   USE oce, ONLY : &           ! Model variables
+      & sshn
+   USE obs_inter_h2d
+   USE obs_utils               ! Various observation tools
+   USE obs_inter_sup
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC obs_rea_altbias     ! Read the altimeter bias
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_rea_altbias( sladata, k2dint, bias_file )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_rea_altbias ***
+      !!
+      !! ** Purpose : Read from file the bias data 
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! References :
+      !!
+      !! History :  
+      !!      ! :  2008-02 (D. Lea) Initial version
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE iom
+      !
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) :: &
+         & sladata       ! SLA data
+      INTEGER, INTENT(IN) :: k2dint
+      CHARACTER(LEN=128) :: bias_file
+
+      !! * Local declarations
+
+      CHARACTER(LEN=12), PARAMETER :: cpname = 'obs_rea_altbias'
+
+      INTEGER :: jobs         ! Obs loop variable
+      INTEGER :: jpialtbias   ! Number of grid point in latitude for the bias
+      INTEGER :: jpjaltbias   ! Number of grid point in longitude for the bias
+      INTEGER :: iico         ! Grid point indicies
+      INTEGER :: ijco
+      INTEGER :: i_nx_id      ! Index to read the NetCDF file
+      INTEGER :: i_ny_id      ! 
+      INTEGER :: i_file_id    ! 
+      INTEGER :: i_var_id
+
+      REAL(wp), DIMENSION(1) :: &
+         & zext, &
+         & zobsmask
+      REAL(wp), DIMENSION(2,2,1) :: &
+         & zweig
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zmask, &
+         & zbias, &
+         & zglam, &
+         & zgphi
+      REAL(wp), DIMENSION(jpi,jpj) ::   z_altbias
+      REAL(wp) :: zlam
+      REAL(wp) :: zphi
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdi, &
+         & igrdj
+      INTEGER :: numaltbias
+
+      IF(lwp)WRITE(numout,*) 
+      IF(lwp)WRITE(numout,*) ' obs_rea_altbias : '
+      IF(lwp)WRITE(numout,*) ' ------------- '
+      IF(lwp)WRITE(numout,*) '   Read altimeter bias'
+
+      ! Open the file
+
+      z_altbias(:,:)=0.0_wp
+      numaltbias=0
+
+      IF(lwp)WRITE(numout,*) 'Opening ',bias_file
+
+      CALL iom_open( bias_file, numaltbias, ldstop=.FALSE. )
+      
+
+      IF (numaltbias .GT. 0) THEN      
+
+         ! Get the Alt bias data
+         
+         CALL iom_get( numaltbias, jpdom_data, 'altbias', z_altbias(:,:), 1 )
+         
+         ! Close the file
+         
+         CALL iom_close(numaltbias)     
+         
+      ELSE
+
+         IF(lwp)WRITE(numout,*) 'no file found'
+      
+      ENDIF
+
+      ! Intepolate the bias already on the model grid at the observation point
+  
+      ALLOCATE( &
+         & igrdi(2,2,sladata%nsurf), &
+         & igrdj(2,2,sladata%nsurf), &
+         & zglam(2,2,sladata%nsurf), &
+         & zgphi(2,2,sladata%nsurf), &
+         & zmask(2,2,sladata%nsurf), &
+         & zbias(2,2,sladata%nsurf)  &
+         & )
+         
+      DO jobs = 1, sladata%nsurf
+
+         igrdi(1,1,jobs) = sladata%mi(jobs)-1
+         igrdj(1,1,jobs) = sladata%mj(jobs)-1
+         igrdi(1,2,jobs) = sladata%mi(jobs)-1
+         igrdj(1,2,jobs) = sladata%mj(jobs)
+         igrdi(2,1,jobs) = sladata%mi(jobs)
+         igrdj(2,1,jobs) = sladata%mj(jobs)-1
+         igrdi(2,2,jobs) = sladata%mi(jobs)
+         igrdj(2,2,jobs) = sladata%mj(jobs)
+
+      END DO
+
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, glamt, zglam )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, gphit, zgphi )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, tmask(:,:,1), zmask )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, z_altbias, zbias )
+
+      DO jobs = 1, sladata%nsurf
+
+         zlam = sladata%rlam(jobs)
+         zphi = sladata%rphi(jobs)
+         iico = sladata%mi(jobs)
+         ijco = sladata%mj(jobs)
+            
+         CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,         &
+            &                   zglam(:,:,jobs), zgphi(:,:,jobs), &
+            &                   zmask(:,:,jobs), zweig, zobsmask )
+            
+         CALL obs_int_h2d( 1, 1,      &
+            &              zweig, zbias(:,:,jobs),  zext )
+
+         ! adjust mdt with bias field
+         sladata%rext(jobs,2) = sladata%rext(jobs,2) - zext(1)
+            
+      END DO
+
+      DEALLOCATE( &
+         & igrdi, &
+         & igrdj, &
+         & zglam, &
+         & zgphi, &
+         & zmask, &
+         & zbias  &
+         & )
+         
+   END SUBROUTINE obs_rea_altbias
+
+
+ 
+END MODULE obs_read_altbias
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_prof.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_prof.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_prof.F90	(revision 14097)
@@ -0,0 +1,866 @@
+MODULE obs_read_prof
+   !!======================================================================
+   !!                       ***  MODULE obs_read_prof  ***
+   !! Observation diagnostics: Read the T and S profile observations
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_rea_pro_dri : Driver for reading profile obs
+   !!----------------------------------------------------------------------
+
+   !! * Modules used   
+   USE par_kind                 ! Precision variables
+   USE par_oce                  ! Ocean parameters
+   USE in_out_manager           ! I/O manager
+   USE dom_oce                  ! Ocean space and time domain variables
+   USE obs_mpp                  ! MPP support routines for observation diagnostics
+   USE julian                   ! Julian date routines
+   USE obs_utils                ! Observation operator utility functions
+   USE obs_prep                 ! Prepare observation arrays
+   USE obs_grid                 ! Grid search
+   USE obs_sort                 ! Sorting observation arrays
+   USE obs_profiles_def         ! Profile definitions
+   USE obs_conv                 ! Various conversion routines
+   USE obs_types                ! Observation type definitions
+   USE netcdf                   ! NetCDF library
+   USE obs_oper                 ! Observation operators
+   USE lib_mpp                  ! For ctl_warn/stop
+   USE obs_fbm                  ! Feedback routines
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC obs_rea_prof  ! Read the profile observations 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_rea_prof( profdata, knumfiles, cdfilenames, &
+      &                     kvars, kextr, kstp, ddobsini, ddobsend, &
+      &                     ldvar1, ldvar2, ldignmis, ldsatt, &
+      &                     ldmod, kdailyavtypes )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_rea_prof ***
+      !!
+      !! ** Purpose : Read from file the profile observations
+      !!
+      !! ** Method  : Read feedback data in and transform to NEMO internal 
+      !!              profile data structure
+      !!
+      !! ** Action  : 
+      !!
+      !! References : 
+      !!
+      !! History :  
+      !!      ! :  2009-09 (K. Mogensen) : New merged version of old routines
+      !!      ! :  2015-08 (M. Martin) : Merged profile and velocity routines
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      TYPE(obs_prof), INTENT(OUT) :: &
+         & profdata                     ! Profile data to be read
+      INTEGER, INTENT(IN) :: knumfiles  ! Number of files to read
+      CHARACTER(LEN=128), INTENT(IN) ::  &
+         & cdfilenames(knumfiles)        ! File names to read in
+      INTEGER, INTENT(IN) :: kvars      ! Number of variables in profdata
+      INTEGER, INTENT(IN) :: kextr      ! Number of extra fields for each var
+      INTEGER, INTENT(IN) :: kstp       ! Ocean time-step index
+      LOGICAL, INTENT(IN) :: ldvar1     ! Observed variables switches
+      LOGICAL, INTENT(IN) :: ldvar2
+      LOGICAL, INTENT(IN) :: ldignmis   ! Ignore missing files
+      LOGICAL, INTENT(IN) :: ldsatt     ! Compute salinity at all temperature points
+      LOGICAL, INTENT(IN) :: ldmod      ! Initialize model from input data
+      REAL(dp), INTENT(IN) :: ddobsini  ! Obs. ini time in YYYYMMDD.HHMMSS
+      REAL(dp), INTENT(IN) :: ddobsend  ! Obs. end time in YYYYMMDD.HHMMSS
+      INTEGER, DIMENSION(imaxavtypes), OPTIONAL :: &
+         & kdailyavtypes                ! Types of daily average observations
+
+      !! * Local declarations
+      CHARACTER(LEN=15), PARAMETER :: cpname='obs_rea_prof'
+      CHARACTER(len=8) :: clrefdate
+      CHARACTER(len=8), DIMENSION(:), ALLOCATABLE :: clvars
+      INTEGER :: jvar
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: ij
+      INTEGER :: iflag
+      INTEGER :: inobf
+      INTEGER :: i_file_id
+      INTEGER :: inowin
+      INTEGER :: iyea
+      INTEGER :: imon
+      INTEGER :: iday
+      INTEGER :: ihou
+      INTEGER :: imin
+      INTEGER :: isec
+      INTEGER :: iprof
+      INTEGER :: iproftot
+      INTEGER :: ivar1t0
+      INTEGER :: ivar2t0
+      INTEGER :: ivar1t
+      INTEGER :: ivar2t
+      INTEGER :: ip3dt
+      INTEGER :: ios
+      INTEGER :: ioserrcount
+      INTEGER :: ivar1tmpp
+      INTEGER :: ivar2tmpp
+      INTEGER :: ip3dtmpp
+      INTEGER :: itype
+      INTEGER, DIMENSION(knumfiles) :: &
+         & irefdate
+      INTEGER, DIMENSION(ntyp1770+1) :: &
+         & itypvar1,    &
+         & itypvar1mpp, &
+         & itypvar2,    &
+         & itypvar2mpp 
+      INTEGER, DIMENSION(:), ALLOCATABLE :: &
+         & iobsi1,    &
+         & iobsj1,    &
+         & iproc1,    &
+         & iobsi2,    &
+         & iobsj2,    &
+         & iproc2,    &
+         & iindx,    &
+         & ifileidx, &
+         & iprofidx
+      INTEGER, DIMENSION(imaxavtypes) :: &
+         & idailyavtypes
+      INTEGER, DIMENSION(kvars) :: &
+         & iv3dt
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zphi, &
+         & zlam
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zdat
+      REAL(wp), DIMENSION(knumfiles) :: &
+         & djulini, &
+         & djulend
+      LOGICAL :: llvalprof
+      LOGICAL :: lldavtimset
+      TYPE(obfbdata), POINTER, DIMENSION(:) :: &
+         & inpfiles
+
+      ! Local initialization
+      iprof = 0
+      ivar1t0 = 0
+      ivar2t0 = 0
+      ip3dt = 0
+
+      ! Daily average types
+      lldavtimset = .FALSE.
+      IF ( PRESENT(kdailyavtypes) ) THEN
+         idailyavtypes(:) = kdailyavtypes(:)
+         IF ( ANY (idailyavtypes(:) /= -1) ) lldavtimset = .TRUE.
+      ELSE
+         idailyavtypes(:) = -1
+      ENDIF
+
+      !-----------------------------------------------------------------------
+      ! Count the number of files needed and allocate the obfbdata type
+      !-----------------------------------------------------------------------
+
+      inobf = knumfiles
+
+      ALLOCATE( inpfiles(inobf) )
+
+      prof_files : DO jj = 1, inobf
+
+         !---------------------------------------------------------------------
+         ! Prints
+         !---------------------------------------------------------------------
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) ' obs_rea_pro_dri : Reading from file = ', &
+               & TRIM( TRIM( cdfilenames(jj) ) )
+            WRITE(numout,*) ' ~~~~~~~~~~~~~~~'
+            WRITE(numout,*)
+         ENDIF
+
+         !---------------------------------------------------------------------
+         !  Initialization: Open file and get dimensions only
+         !---------------------------------------------------------------------
+
+         iflag = nf90_open( TRIM( cdfilenames(jj) ), nf90_nowrite, &
+            &                      i_file_id )
+
+         IF ( iflag /= nf90_noerr ) THEN
+
+            IF ( ldignmis ) THEN
+               inpfiles(jj)%nobs = 0
+               CALL ctl_warn( 'File ' // TRIM( cdfilenames(jj) ) // &
+                  &           ' not found' )
+            ELSE 
+               CALL ctl_stop( 'File ' // TRIM( cdfilenames(jj) ) // &
+                  &           ' not found' )
+            ENDIF
+
+         ELSE 
+
+            !------------------------------------------------------------------
+            !  Close the file since it is opened in read_obfbdata
+            !------------------------------------------------------------------
+
+            iflag = nf90_close( i_file_id )
+
+            !------------------------------------------------------------------
+            !  Read the profile file into inpfiles
+            !------------------------------------------------------------------
+            CALL init_obfbdata( inpfiles(jj) )
+            CALL read_obfbdata( TRIM( cdfilenames(jj) ), inpfiles(jj), &
+               &                ldgrid = .TRUE. )
+
+            IF ( inpfiles(jj)%nvar < 2 ) THEN
+               CALL ctl_stop( 'Feedback format error: ', &
+                  &           ' less than 2 vars in profile file' )
+            ENDIF
+
+            IF ( ldmod .AND. ( inpfiles(jj)%nadd == 0 ) ) THEN
+               CALL ctl_stop( 'Model not in input data' )
+            ENDIF
+
+            IF ( jj == 1 ) THEN
+               ALLOCATE( clvars( inpfiles(jj)%nvar ) )
+               DO ji = 1, inpfiles(jj)%nvar
+                 clvars(ji) = inpfiles(jj)%cname(ji)
+               END DO
+            ELSE
+               DO ji = 1, inpfiles(jj)%nvar
+                  IF ( inpfiles(jj)%cname(ji) /= clvars(ji) ) THEN
+                     CALL ctl_stop( 'Feedback file variables not consistent', &
+                        &           ' with previous files for this type' )
+                  ENDIF
+               END DO
+            ENDIF
+
+            !------------------------------------------------------------------
+            !  Change longitude (-180,180)
+            !------------------------------------------------------------------
+
+            DO ji = 1, inpfiles(jj)%nobs 
+
+               IF ( inpfiles(jj)%plam(ji) < -180. ) &
+                  &   inpfiles(jj)%plam(ji) = inpfiles(jj)%plam(ji) + 360.
+
+               IF ( inpfiles(jj)%plam(ji) >  180. ) &
+                  &   inpfiles(jj)%plam(ji) = inpfiles(jj)%plam(ji) - 360.
+
+            END DO
+
+            !------------------------------------------------------------------
+            !  Calculate the date  (change eventually)
+            !------------------------------------------------------------------
+            clrefdate=inpfiles(jj)%cdjuldref(1:8)
+            READ(clrefdate,'(I8)') irefdate(jj)
+
+            CALL ddatetoymdhms( ddobsini, iyea, imon, iday, ihou, imin, isec )
+            CALL greg2jul( isec, imin, ihou, iday, imon, iyea, djulini(jj), &
+               &           krefdate = irefdate(jj) )
+            CALL ddatetoymdhms( ddobsend, iyea, imon, iday, ihou, imin, isec )
+            CALL greg2jul( isec, imin, ihou, iday, imon, iyea, djulend(jj), &
+               &           krefdate = irefdate(jj) )
+
+            ioserrcount=0
+            IF ( lldavtimset ) THEN
+
+               IF ( ANY ( idailyavtypes(:) /= -1 ) .AND. lwp) THEN
+                  WRITE(numout,*)' Resetting time of daily averaged', &
+                     &           ' observations to the end of the day'
+               ENDIF
+
+               DO ji = 1, inpfiles(jj)%nobs
+                  READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 900 ) itype
+900               IF ( ios /= 0 ) THEN
+                     ! Set type to zero if there is a problem in the string conversion
+                     itype = 0
+                  ENDIF
+
+                  IF ( ANY ( idailyavtypes(:) == itype ) ) THEN
+                  !  for daily averaged data force the time
+                  !  to be the last time-step of the day, but still within the day.
+                     IF ( inpfiles(jj)%ptim(ji) >= 0. ) THEN
+                        inpfiles(jj)%ptim(ji) = &
+                           & INT(inpfiles(jj)%ptim(ji)) + 0.9999
+                     ELSE
+                        inpfiles(jj)%ptim(ji) = &
+                           & INT(inpfiles(jj)%ptim(ji)) - 0.0001
+                     ENDIF
+                  ENDIF
+
+               END DO
+
+            ENDIF
+
+            IF ( inpfiles(jj)%nobs > 0 ) THEN
+               inpfiles(jj)%iproc(:,:) = -1
+               inpfiles(jj)%iobsi(:,:) = -1
+               inpfiles(jj)%iobsj(:,:) = -1
+            ENDIF
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+               IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+                  & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+               ENDIF
+            END DO
+            ALLOCATE( zlam(inowin)  )
+            ALLOCATE( zphi(inowin)  )
+            ALLOCATE( iobsi1(inowin) )
+            ALLOCATE( iobsj1(inowin) )
+            ALLOCATE( iproc1(inowin) )
+            ALLOCATE( iobsi2(inowin) )
+            ALLOCATE( iobsj2(inowin) )
+            ALLOCATE( iproc2(inowin) )
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+               IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+                  & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+                  zlam(inowin) = inpfiles(jj)%plam(ji)
+                  zphi(inowin) = inpfiles(jj)%pphi(ji)
+               ENDIF
+            END DO
+
+            IF ( TRIM( inpfiles(jj)%cname(1) ) == 'POTM' ) THEN
+               CALL obs_grid_search( inowin, zlam, zphi, iobsi1, iobsj1, &
+                  &                  iproc1, 'T' )
+               iobsi2(:) = iobsi1(:)
+               iobsj2(:) = iobsj1(:)
+               iproc2(:) = iproc1(:)
+            ELSEIF ( TRIM( inpfiles(jj)%cname(1) ) == 'UVEL' ) THEN
+               CALL obs_grid_search( inowin, zlam, zphi, iobsi1, iobsj1, &
+                  &                  iproc1, 'U' )
+               CALL obs_grid_search( inowin, zlam, zphi, iobsi2, iobsj2, &
+                  &                  iproc2, 'V' )
+            ENDIF
+
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+               IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+                  & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+                  inpfiles(jj)%iproc(ji,1) = iproc1(inowin)
+                  inpfiles(jj)%iobsi(ji,1) = iobsi1(inowin)
+                  inpfiles(jj)%iobsj(ji,1) = iobsj1(inowin)
+                  inpfiles(jj)%iproc(ji,2) = iproc2(inowin)
+                  inpfiles(jj)%iobsi(ji,2) = iobsi2(inowin)
+                  inpfiles(jj)%iobsj(ji,2) = iobsj2(inowin)
+                  IF ( inpfiles(jj)%iproc(ji,1) /= &
+                     & inpfiles(jj)%iproc(ji,2) ) THEN
+                     CALL ctl_stop( 'Error in obs_read_prof:', &
+                        & 'var1 and var2 observation on different processors')
+                  ENDIF
+               ENDIF
+            END DO
+            DEALLOCATE( zlam, zphi, iobsi1, iobsj1, iproc1, iobsi2, iobsj2, iproc2 )
+
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+               IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+                  & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  IF ( nproc == 0 ) THEN
+                     IF ( inpfiles(jj)%iproc(ji,1) >  nproc ) CYCLE
+                  ELSE
+                     IF ( inpfiles(jj)%iproc(ji,1) /= nproc ) CYCLE
+                  ENDIF
+                  llvalprof = .FALSE.
+                  IF ( ldvar1 ) THEN
+                     loop_t_count : DO ij = 1,inpfiles(jj)%nlev
+                        IF ( inpfiles(jj)%pdep(ij,ji) >= 6000. ) &
+                           & CYCLE
+                        IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                           & .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) ) THEN
+                           ivar1t0 = ivar1t0 + 1
+                        ENDIF
+                     END DO loop_t_count
+                  ENDIF
+                  IF ( ldvar2 ) THEN
+                     loop_s_count : DO ij = 1,inpfiles(jj)%nlev
+                        IF ( inpfiles(jj)%pdep(ij,ji) >= 6000. ) &
+                           & CYCLE
+                        IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) .AND. &
+                           & .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) ) THEN
+                           ivar2t0 = ivar2t0 + 1
+                        ENDIF
+                     END DO loop_s_count
+                  ENDIF
+                  loop_p_count : DO ij = 1,inpfiles(jj)%nlev
+                     IF ( inpfiles(jj)%pdep(ij,ji) >= 6000. ) &
+                        & CYCLE
+                     IF ( ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                        &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) .AND. &
+                        &    ldvar1 ) .OR. &
+                        & ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) .AND. &
+                        &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) .AND. &
+                        &     ldvar2 ) ) THEN
+                        ip3dt = ip3dt + 1
+                        llvalprof = .TRUE.
+                     ENDIF
+                  END DO loop_p_count
+
+                  IF ( llvalprof ) iprof = iprof + 1
+
+               ENDIF
+            END DO
+
+         ENDIF
+
+      END DO prof_files
+
+      !-----------------------------------------------------------------------
+      ! Get the time ordered indices of the input data
+      !-----------------------------------------------------------------------
+
+      !---------------------------------------------------------------------
+      !  Loop over input data files to count total number of profiles
+      !---------------------------------------------------------------------
+      iproftot = 0
+      DO jj = 1, inobf
+         DO ji = 1, inpfiles(jj)%nobs
+            IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+            IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+               & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+            IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+               & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+               iproftot = iproftot + 1
+            ENDIF
+         END DO
+      END DO
+
+      ALLOCATE( iindx(iproftot), ifileidx(iproftot), &
+         &      iprofidx(iproftot), zdat(iproftot) )
+      jk = 0
+      DO jj = 1, inobf
+         DO ji = 1, inpfiles(jj)%nobs
+            IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+            IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+               & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+            IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+               & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+               jk = jk + 1
+               ifileidx(jk) = jj
+               iprofidx(jk) = ji
+               zdat(jk)     = inpfiles(jj)%ptim(ji)
+            ENDIF
+         END DO
+      END DO
+      CALL sort_dp_indx( iproftot, &
+         &               zdat,     &
+         &               iindx   )
+
+      iv3dt(:) = -1
+      IF (ldsatt) THEN
+         iv3dt(1) = ip3dt
+         iv3dt(2) = ip3dt
+      ELSE
+         iv3dt(1) = ivar1t0
+         iv3dt(2) = ivar2t0
+      ENDIF
+      CALL obs_prof_alloc( profdata, kvars, kextr, iprof, iv3dt, &
+         &                 kstp, jpi, jpj, jpk )
+
+      ! * Read obs/positions, QC, all variable and assign to profdata
+
+      profdata%nprof     = 0
+      profdata%nvprot(:) = 0
+      profdata%cvars(:)  = clvars(:)
+      iprof = 0
+
+      ip3dt = 0
+      ivar1t = 0
+      ivar2t = 0
+      itypvar1   (:) = 0
+      itypvar1mpp(:) = 0
+
+      itypvar2   (:) = 0
+      itypvar2mpp(:) = 0
+
+      ioserrcount = 0
+      DO jk = 1, iproftot
+
+         jj = ifileidx(iindx(jk))
+         ji = iprofidx(iindx(jk))
+
+            IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+            IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+               & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+
+         IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND.  &
+            & ( inpfiles(jj)%ptim(ji) <= djulend(jj) ) ) THEN
+
+            IF ( nproc == 0 ) THEN
+               IF ( inpfiles(jj)%iproc(ji,1) >  nproc ) CYCLE
+            ELSE
+               IF ( inpfiles(jj)%iproc(ji,1) /= nproc ) CYCLE
+            ENDIF
+
+            llvalprof = .FALSE.
+
+            IF ( inpfiles(jj)%ioqc(ji) > 2 ) CYCLE
+
+            IF ( BTEST(inpfiles(jj)%ioqc(ji),2 ) ) CYCLE
+            IF ( BTEST(inpfiles(jj)%ivqc(ji,1),2) .AND. &
+               & BTEST(inpfiles(jj)%ivqc(ji,2),2) ) CYCLE
+
+            loop_prof : DO ij = 1, inpfiles(jj)%nlev
+
+               IF ( inpfiles(jj)%pdep(ij,ji) >= 6000. ) &
+                  & CYCLE
+
+               IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                  & .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) ) THEN
+
+                  llvalprof = .TRUE. 
+                  EXIT loop_prof
+
+               ENDIF
+
+               IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) .AND. &
+                  & .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) ) THEN
+
+                  llvalprof = .TRUE. 
+                  EXIT loop_prof
+
+               ENDIF
+
+            END DO loop_prof
+
+            ! Set profile information
+
+            IF ( llvalprof ) THEN
+
+               iprof = iprof + 1
+
+               CALL jul2greg( isec,                   &
+                  &           imin,                   &
+                  &           ihou,                   &
+                  &           iday,                   &
+                  &           imon,                   &
+                  &           iyea,                   &
+                  &           inpfiles(jj)%ptim(ji), &
+                  &           irefdate(jj) )
+
+
+               ! Profile time coordinates
+               profdata%nyea(iprof) = iyea
+               profdata%nmon(iprof) = imon
+               profdata%nday(iprof) = iday
+               profdata%nhou(iprof) = ihou
+               profdata%nmin(iprof) = imin
+
+               ! Profile space coordinates
+               profdata%rlam(iprof) = inpfiles(jj)%plam(ji)
+               profdata%rphi(iprof) = inpfiles(jj)%pphi(ji)
+
+               ! Coordinate search parameters
+               profdata%mi  (iprof,1) = inpfiles(jj)%iobsi(ji,1)
+               profdata%mj  (iprof,1) = inpfiles(jj)%iobsj(ji,1)
+               profdata%mi  (iprof,2) = inpfiles(jj)%iobsi(ji,2)
+               profdata%mj  (iprof,2) = inpfiles(jj)%iobsj(ji,2)
+
+               ! Profile WMO number
+               profdata%cwmo(iprof) = inpfiles(jj)%cdwmo(ji)
+
+               ! Instrument type
+               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
+
+               ! QC stuff
+
+               profdata%nqc(iprof)     = inpfiles(jj)%ioqc(ji)
+               profdata%nqcf(:,iprof)  = inpfiles(jj)%ioqcf(:,ji)
+               profdata%ipqc(iprof)    = inpfiles(jj)%ipqc(ji)
+               profdata%ipqcf(:,iprof) = inpfiles(jj)%ipqcf(:,ji)
+               profdata%itqc(iprof)    = inpfiles(jj)%itqc(ji)
+               profdata%itqcf(:,iprof) = inpfiles(jj)%itqcf(:,ji)
+               profdata%ivqc(iprof,:)  = inpfiles(jj)%ivqc(ji,:)
+               profdata%ivqcf(:,iprof,:) = inpfiles(jj)%ivqcf(:,ji,:)
+
+               ! Bookkeeping data to match profiles
+               profdata%npidx(iprof) = iprof
+               profdata%npfil(iprof) = iindx(jk)
+
+               ! Observation QC flag (whole profile)
+               profdata%nqc(iprof)  = 0 !TODO
+
+               loop_p : DO ij = 1, inpfiles(jj)%nlev
+
+                  IF ( inpfiles(jj)%pdep(ij,ji) >= 6000. ) &
+                     & CYCLE
+
+                  IF (ldsatt) THEN
+
+                     IF ( ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                        &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) .AND. &
+                        &    ldvar1 ) .OR. &
+                        & ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) .AND. &
+                        &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) .AND. &
+                        &   ldvar2 ) ) THEN
+                        ip3dt = ip3dt + 1
+                     ELSE
+                        CYCLE
+                     ENDIF
+
+                  ENDIF
+
+                  IF ( ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                    &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) .AND. &
+                    &    ldvar1 ) .OR. ldsatt ) THEN
+
+                     IF (ldsatt) THEN
+
+                        ivar1t = ip3dt
+
+                     ELSE
+
+                        ivar1t = ivar1t + 1
+
+                     ENDIF
+
+                     ! Depth of var1 observation
+                     profdata%var(1)%vdep(ivar1t) = &
+                        &                inpfiles(jj)%pdep(ij,ji)
+
+                     ! Depth of var1 observation QC
+                     profdata%var(1)%idqc(ivar1t) = &
+                        &                inpfiles(jj)%idqc(ij,ji)
+
+                     ! Depth of var1 observation QC flags
+                     profdata%var(1)%idqcf(:,ivar1t) = &
+                        &                inpfiles(jj)%idqcf(:,ij,ji)
+
+                     ! Profile index
+                     profdata%var(1)%nvpidx(ivar1t) = iprof
+
+                     ! Vertical index in original profile
+                     profdata%var(1)%nvlidx(ivar1t) = ij
+
+                     ! Profile var1 value
+                     IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,1),2) .AND. &
+                        & .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2) ) THEN
+                        profdata%var(1)%vobs(ivar1t) = &
+                           &                inpfiles(jj)%pob(ij,ji,1)
+                        IF ( ldmod ) THEN
+                           profdata%var(1)%vmod(ivar1t) = &
+                              &                inpfiles(jj)%padd(ij,ji,1,1)
+                        ENDIF
+                        ! Count number of profile var1 data as function of type
+                        itypvar1( profdata%ntyp(iprof) + 1 ) = &
+                           & itypvar1( profdata%ntyp(iprof) + 1 ) + 1
+                     ELSE
+                        profdata%var(1)%vobs(ivar1t) = fbrmdi
+                     ENDIF
+
+                     ! Profile var1 qc
+                     profdata%var(1)%nvqc(ivar1t) = &
+                        & inpfiles(jj)%ivlqc(ij,ji,1)
+
+                     ! Profile var1 qc flags
+                     profdata%var(1)%nvqcf(:,ivar1t) = &
+                        & inpfiles(jj)%ivlqcf(:,ij,ji,1)
+
+                     ! Profile insitu T value
+                     IF ( TRIM( inpfiles(jj)%cname(1) ) == 'POTM' ) THEN
+                        profdata%var(1)%vext(ivar1t,1) = &
+                           &                inpfiles(jj)%pext(ij,ji,1)
+                     ENDIF
+
+                  ENDIF
+
+                  IF ( ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) .AND. &
+                     &   .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2)    .AND. &
+                     &   ldvar2 ) .OR. ldsatt ) THEN
+
+                     IF (ldsatt) THEN
+
+                        ivar2t = ip3dt
+
+                     ELSE
+
+                        ivar2t = ivar2t + 1
+
+                     ENDIF
+
+                     ! Depth of var2 observation
+                     profdata%var(2)%vdep(ivar2t) = &
+                        &                inpfiles(jj)%pdep(ij,ji)
+
+                     ! Depth of var2 observation QC
+                     profdata%var(2)%idqc(ivar2t) = &
+                        &                inpfiles(jj)%idqc(ij,ji)
+
+                     ! Depth of var2 observation QC flags
+                     profdata%var(2)%idqcf(:,ivar2t) = &
+                        &                inpfiles(jj)%idqcf(:,ij,ji)
+
+                     ! Profile index
+                     profdata%var(2)%nvpidx(ivar2t) = iprof
+
+                     ! Vertical index in original profile
+                     profdata%var(2)%nvlidx(ivar2t) = ij
+
+                     ! Profile var2 value
+                  IF (  ( .NOT. BTEST(inpfiles(jj)%ivlqc(ij,ji,2),2) ) .AND. &
+                    &   ( .NOT. BTEST(inpfiles(jj)%idqc(ij,ji),2)    )  ) THEN
+                        profdata%var(2)%vobs(ivar2t) = &
+                           &                inpfiles(jj)%pob(ij,ji,2)
+                        IF ( ldmod ) THEN
+                           profdata%var(2)%vmod(ivar2t) = &
+                              &                inpfiles(jj)%padd(ij,ji,1,2)
+                        ENDIF
+                        ! Count number of profile var2 data as function of type
+                        itypvar2( profdata%ntyp(iprof) + 1 ) = &
+                           & itypvar2( profdata%ntyp(iprof) + 1 ) + 1
+                     ELSE
+                        profdata%var(2)%vobs(ivar2t) = fbrmdi
+                     ENDIF
+
+                     ! Profile var2 qc
+                     profdata%var(2)%nvqc(ivar2t) = &
+                        & inpfiles(jj)%ivlqc(ij,ji,2)
+
+                     ! Profile var2 qc flags
+                     profdata%var(2)%nvqcf(:,ivar2t) = &
+                        & inpfiles(jj)%ivlqcf(:,ij,ji,2)
+
+                  ENDIF
+
+               END DO loop_p
+
+            ENDIF
+
+         ENDIF
+
+      END DO
+
+      !-----------------------------------------------------------------------
+      ! Sum up over processors
+      !-----------------------------------------------------------------------
+
+      CALL obs_mpp_sum_integer ( ivar1t0, ivar1tmpp )
+      CALL obs_mpp_sum_integer ( ivar2t0, ivar2tmpp )
+      CALL obs_mpp_sum_integer ( ip3dt,   ip3dtmpp  )
+
+      CALL obs_mpp_sum_integers( itypvar1, itypvar1mpp, ntyp1770 + 1 )
+      CALL obs_mpp_sum_integers( itypvar2, itypvar2mpp, ntyp1770 + 1 )
+
+      !-----------------------------------------------------------------------
+      ! Output number of observations.
+      !-----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,'(A)') ' Profile data'
+         WRITE(numout,'(1X,A)') '------------'
+         WRITE(numout,*) 
+         WRITE(numout,'(1X,A)') 'Profile data, '//TRIM( profdata%cvars(1) )
+         WRITE(numout,'(1X,A)') '------------------------'
+         DO ji = 0, ntyp1770
+            IF ( itypvar1mpp(ji+1) > 0 ) THEN
+               WRITE(numout,'(1X,A3,1X,A48,A3,I8)') ctypshort(ji), &
+                  & cwmonam1770(ji)(1:52),' = ', &
+                  & itypvar1mpp(ji+1)
+            ENDIF
+         END DO
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,'(1X,A55,I8)') &
+            & 'Total profile data for variable '//TRIM( profdata%cvars(1) )// &
+            & '             = ', ivar1tmpp
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,*) 
+         WRITE(numout,'(1X,A)') 'Profile data, '//TRIM( profdata%cvars(2) )
+         WRITE(numout,'(1X,A)') '------------------------'
+         DO ji = 0, ntyp1770
+            IF ( itypvar2mpp(ji+1) > 0 ) THEN
+               WRITE(numout,'(1X,A3,1X,A48,A3,I8)') ctypshort(ji), &
+                  & cwmonam1770(ji)(1:52),' = ', &
+                  & itypvar2mpp(ji+1)
+            ENDIF
+         END DO
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,'(1X,A55,I8)') &
+            & 'Total profile data for variable '//TRIM( profdata%cvars(2) )// &
+            & '             = ', ivar2tmpp
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,*) 
+      ENDIF
+
+      IF (ldsatt) THEN
+         profdata%nvprot(1)    = ip3dt
+         profdata%nvprot(2)    = ip3dt
+         profdata%nvprotmpp(1) = ip3dtmpp
+         profdata%nvprotmpp(2) = ip3dtmpp
+      ELSE
+         profdata%nvprot(1)    = ivar1t
+         profdata%nvprot(2)    = ivar2t
+         profdata%nvprotmpp(1) = ivar1tmpp
+         profdata%nvprotmpp(2) = ivar2tmpp
+      ENDIF
+      profdata%nprof        = iprof
+
+      !-----------------------------------------------------------------------
+      ! Model level search
+      !-----------------------------------------------------------------------
+      IF ( ldvar1 ) THEN
+         CALL obs_level_search( jpk, gdept_1d, &
+            & profdata%nvprot(1), profdata%var(1)%vdep, &
+            & profdata%var(1)%mvk )
+      ENDIF
+      IF ( ldvar2 ) THEN
+         CALL obs_level_search( jpk, gdept_1d, &
+            & profdata%nvprot(2), profdata%var(2)%vdep, &
+            & profdata%var(2)%mvk )
+      ENDIF
+
+      !-----------------------------------------------------------------------
+      ! Set model equivalent to 99999
+      !-----------------------------------------------------------------------
+      IF ( .NOT. ldmod ) THEN
+         DO jvar = 1, kvars
+            profdata%var(jvar)%vmod(:) = fbrmdi
+         END DO
+      ENDIF
+      !-----------------------------------------------------------------------
+      ! Deallocate temporary data
+      !-----------------------------------------------------------------------
+      DEALLOCATE( ifileidx, iprofidx, zdat, clvars )
+
+      !-----------------------------------------------------------------------
+      ! Deallocate input data
+      !-----------------------------------------------------------------------
+      DO jj = 1, inobf
+         CALL dealloc_obfbdata( inpfiles(jj) )
+      END DO
+      DEALLOCATE( inpfiles )
+
+   END SUBROUTINE obs_rea_prof
+
+END MODULE obs_read_prof
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_surf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_surf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_read_surf.F90	(revision 14097)
@@ -0,0 +1,496 @@
+MODULE obs_read_surf
+   !!======================================================================
+   !!                       ***  MODULE obs_read_surf  ***
+   !! Observation diagnostics: Read the surface data from feedback files
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_rea_surf : Driver for reading surface data from feedback files
+   !!----------------------------------------------------------------------
+
+   !! * Modules used
+   USE par_kind                 ! Precision variables
+   USE in_out_manager           ! I/O manager
+   USE dom_oce                  ! Ocean space and time domain variables
+   USE obs_mpp                  ! MPP support routines for observation diagnostics
+   USE julian                   ! Julian date routines
+   USE obs_utils                ! Observation operator utility functions
+   USE obs_grid                 ! Grid search
+   USE obs_sort                 ! Sorting observation arrays
+   USE obs_surf_def             ! Surface observation definitions
+   USE obs_types                ! Observation type definitions
+   USE obs_fbm                  ! Feedback routines
+   USE netcdf                   ! NetCDF library
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC obs_rea_surf      ! Read the surface observations from the point data
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_rea_surf( surfdata, knumfiles, cdfilenames, &
+      &                     kvars, kextr, kstp, ddobsini, ddobsend, &
+      &                     ldignmis, ldmod, ldnightav )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_rea_surf ***
+      !!
+      !! ** Purpose : Read from file the surface data
+      !!
+      !! ** Method  : Read in the data from feedback format files and 
+      !!              put into the NEMO internal surface data structure
+      !!
+      !! ** Action  : 
+      !!
+      !!
+      !! History :  
+      !!      ! :  2009-01 (K. Mogensen) Initial version based on old versions
+      !!      ! :  2015-02 (M. Martin)   Unify the different surface data type reading.
+      !!----------------------------------------------------------------------
+      !! * Modules used
+
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) :: &
+         & surfdata                     ! Surface data to be read
+      INTEGER, INTENT(IN) :: knumfiles  ! Number of corio format files to read
+      CHARACTER(LEN=128), INTENT(IN) :: &
+         & cdfilenames(knumfiles)       ! File names to read in
+      INTEGER, INTENT(IN) :: kvars      ! Number of variables in surfdata
+      INTEGER, INTENT(IN) :: kextr      ! Number of extra fields for each var
+      INTEGER, INTENT(IN) :: kstp       ! Ocean time-step index
+      LOGICAL, INTENT(IN) :: ldignmis   ! Ignore missing files
+      LOGICAL, INTENT(IN) :: ldmod      ! Initialize model from input data
+      LOGICAL, INTENT(IN) :: ldnightav  ! Observations represent a night-time average
+      REAL(dp), INTENT(IN) :: ddobsini   ! Obs. ini time in YYYYMMDD.HHMMSS
+      REAL(dp), INTENT(IN) :: ddobsend   ! Obs. end time in YYYYMMDD.HHMMSS
+
+      !! * Local declarations
+      CHARACTER(LEN=11), PARAMETER :: cpname='obs_rea_surf'
+      CHARACTER(len=8) :: clrefdate
+      CHARACTER(len=8), DIMENSION(:), ALLOCATABLE :: clvars
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+      INTEGER :: iflag
+      INTEGER :: inobf
+      INTEGER :: i_file_id
+      INTEGER :: inowin
+      INTEGER :: iyea
+      INTEGER :: imon
+      INTEGER :: iday
+      INTEGER :: ihou
+      INTEGER :: imin
+      INTEGER :: isec
+      INTEGER :: itype
+      INTEGER :: iobsmpp
+      INTEGER :: iobs
+      INTEGER :: iobstot
+      INTEGER :: ios
+      INTEGER :: ioserrcount
+      INTEGER, PARAMETER :: jpsurfmaxtype = 1024
+      INTEGER, DIMENSION(knumfiles) :: irefdate
+      INTEGER, DIMENSION(jpsurfmaxtype+1) :: &
+         & ityp, &
+         & itypmpp
+      INTEGER, DIMENSION(:), ALLOCATABLE :: &
+         & iobsi,    &
+         & iobsj,    &
+         & iproc,    &
+         & iindx,    &
+         & ifileidx, &
+         & isurfidx
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zphi, &
+         & zlam
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: &
+         & zdat
+      REAL(wp), DIMENSION(knumfiles) :: &
+         & djulini, &
+         & djulend
+      LOGICAL :: llvalprof
+      TYPE(obfbdata), POINTER, DIMENSION(:) :: &
+         & inpfiles
+
+      ! Local initialization
+      iobs = 0
+
+      !-----------------------------------------------------------------------
+      ! Count the number of files needed and allocate the obfbdata type
+      !-----------------------------------------------------------------------
+
+      inobf = knumfiles
+
+      ALLOCATE( inpfiles(inobf) )
+
+      surf_files : DO jj = 1, inobf
+
+         !---------------------------------------------------------------------
+         ! Prints
+         !---------------------------------------------------------------------
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) ' obs_rea_surf : Reading from file = ', &
+               & TRIM( TRIM( cdfilenames(jj) ) )
+            WRITE(numout,*) ' ~~~~~~~~~~~'
+            WRITE(numout,*)
+         ENDIF
+
+         !---------------------------------------------------------------------
+         !  Initialization: Open file and get dimensions only
+         !---------------------------------------------------------------------
+
+         iflag = nf90_open( TRIM( TRIM( cdfilenames(jj) ) ), nf90_nowrite, &
+            &                      i_file_id )
+
+         IF ( iflag /= nf90_noerr ) THEN
+
+            IF ( ldignmis ) THEN
+               inpfiles(jj)%nobs = 0
+               CALL ctl_warn( 'File ' // TRIM( TRIM( cdfilenames(jj) ) ) // &
+                  &           ' not found' )
+            ELSE 
+               CALL ctl_stop( 'File ' // TRIM( TRIM( cdfilenames(jj) ) ) // &
+                  &           ' not found' )
+            ENDIF
+
+         ELSE 
+
+            !------------------------------------------------------------------
+            !  Close the file since it is opened in read_obfbdata
+            !------------------------------------------------------------------
+
+            iflag = nf90_close( i_file_id )
+
+            !------------------------------------------------------------------
+            !  Read the surface file into inpfiles
+            !------------------------------------------------------------------
+            CALL init_obfbdata( inpfiles(jj) )
+            CALL read_obfbdata( TRIM( cdfilenames(jj) ), inpfiles(jj), &
+               &                ldgrid = .TRUE. )
+
+            IF ( ldmod .AND. ( inpfiles(jj)%nadd == 0 ) ) THEN
+               CALL ctl_stop( 'Model not in input data' )
+               RETURN
+            ENDIF
+
+            IF ( jj == 1 ) THEN
+               ALLOCATE( clvars( inpfiles(jj)%nvar ) )
+               DO ji = 1, inpfiles(jj)%nvar
+                 clvars(ji) = inpfiles(jj)%cname(ji)
+               END DO
+            ELSE
+               DO ji = 1, inpfiles(jj)%nvar
+                  IF ( inpfiles(jj)%cname(ji) /= clvars(ji) ) THEN
+                     CALL ctl_stop( 'Feedback file variables not consistent', &
+                        &           ' with previous files for this type' )
+                  ENDIF
+               END DO
+            ENDIF
+
+            IF (lwp) WRITE(numout,*)'Observation file contains ',inpfiles(jj)%nobs,' observations'
+
+            !------------------------------------------------------------------
+            !  Change longitude (-180,180)
+            !------------------------------------------------------------------
+
+            DO ji = 1, inpfiles(jj)%nobs
+
+               IF ( inpfiles(jj)%plam(ji) < -180. ) &
+                  &   inpfiles(jj)%plam(ji) = inpfiles(jj)%plam(ji) + 360.
+
+               IF ( inpfiles(jj)%plam(ji) >  180. ) &
+                  &   inpfiles(jj)%plam(ji) = inpfiles(jj)%plam(ji) - 360.
+
+            END DO
+
+            !------------------------------------------------------------------
+            !  Calculate the date  (change eventually)
+            !------------------------------------------------------------------
+            clrefdate=inpfiles(jj)%cdjuldref(1:8)
+            READ(clrefdate,'(I8)') irefdate(jj)
+
+            CALL ddatetoymdhms( ddobsini, iyea, imon, iday, ihou, imin, isec )
+            CALL greg2jul( isec, imin, ihou, iday, imon, iyea, djulini(jj), &
+               &           krefdate = irefdate(jj) )
+            CALL ddatetoymdhms( ddobsend, iyea, imon, iday, ihou, imin, isec )
+            CALL greg2jul( isec, imin, ihou, iday, imon, iyea, djulend(jj), &
+               &           krefdate = irefdate(jj) )
+
+            IF ( ldnightav ) THEN
+
+               IF ( lwp ) THEN
+                  WRITE(numout,*)'Resetting time of night-time averaged observations', &
+                     &             ' to the end of the day'
+               ENDIF
+
+               DO ji = 1, inpfiles(jj)%nobs
+                  !  for night-time averaged data force the time
+                  !  to be the last time-step of the day, but still within the day.
+                  IF ( inpfiles(jj)%ptim(ji) >= 0. ) THEN
+                     inpfiles(jj)%ptim(ji) = &
+                        & INT(inpfiles(jj)%ptim(ji)) + 0.9999
+                  ELSE
+                     inpfiles(jj)%ptim(ji) = &
+                        & INT(inpfiles(jj)%ptim(ji)) - 0.0001
+                  ENDIF
+               END DO
+            ENDIF
+
+            IF ( inpfiles(jj)%nobs > 0 ) THEN
+               inpfiles(jj)%iproc = -1
+               inpfiles(jj)%iobsi = -1
+               inpfiles(jj)%iobsj = -1
+            ENDIF
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+               ENDIF
+            END DO
+            ALLOCATE( zlam(inowin)  )
+            ALLOCATE( zphi(inowin)  )
+            ALLOCATE( iobsi(inowin) )
+            ALLOCATE( iobsj(inowin) )
+            ALLOCATE( iproc(inowin) )
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+                  zlam(inowin) = inpfiles(jj)%plam(ji)
+                  zphi(inowin) = inpfiles(jj)%pphi(ji)
+               ENDIF
+            END DO
+
+            CALL obs_grid_search( inowin, zlam, zphi, iobsi, iobsj, iproc, 'T' )
+
+            inowin = 0
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  inowin = inowin + 1
+                  inpfiles(jj)%iproc(ji,1) = iproc(inowin)
+                  inpfiles(jj)%iobsi(ji,1) = iobsi(inowin)
+                  inpfiles(jj)%iobsj(ji,1) = iobsj(inowin)
+               ENDIF
+            END DO
+            DEALLOCATE( zlam, zphi, iobsi, iobsj, iproc )
+
+            DO ji = 1, inpfiles(jj)%nobs
+               IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+                  & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+                  IF ( nproc == 0 ) THEN
+                     IF ( inpfiles(jj)%iproc(ji,1) >  nproc ) CYCLE
+                  ELSE
+                     IF ( inpfiles(jj)%iproc(ji,1) /= nproc ) CYCLE
+                  ENDIF
+                  llvalprof = .FALSE.
+                  IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(1,ji,1),2) ) THEN
+                     iobs = iobs + 1
+                  ENDIF
+               ENDIF
+            END DO
+
+         ENDIF
+
+      END DO surf_files
+
+      !-----------------------------------------------------------------------
+      ! Get the time ordered indices of the input data
+      !-----------------------------------------------------------------------
+
+      !---------------------------------------------------------------------
+      !  Loop over input data files to count total number of profiles
+      !---------------------------------------------------------------------
+      iobstot = 0
+      DO jj = 1, inobf
+         DO ji = 1, inpfiles(jj)%nobs
+            IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+               & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+               iobstot = iobstot + 1
+            ENDIF
+         END DO
+      END DO
+
+      ALLOCATE( iindx(iobstot), ifileidx(iobstot), &
+         &      isurfidx(iobstot), zdat(iobstot) )
+      jk = 0
+      DO jj = 1, inobf
+         DO ji = 1, inpfiles(jj)%nobs
+            IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND. &
+               & ( inpfiles(jj)%ptim(ji) <= djulend(jj) )       ) THEN
+               jk = jk + 1
+               ifileidx(jk) = jj
+               isurfidx(jk) = ji
+               zdat(jk)     = inpfiles(jj)%ptim(ji)
+            ENDIF
+         END DO
+      END DO
+      CALL sort_dp_indx( iobstot, &
+         &               zdat,     &
+         &               iindx   )
+
+      CALL obs_surf_alloc( surfdata, iobs, kvars, kextr, kstp, jpi, jpj )
+
+      ! Read obs/positions, QC, all variable and assign to surfdata
+
+      iobs = 0
+
+      surfdata%cvars(:)  = clvars(:)
+
+      ityp   (:) = 0
+      itypmpp(:) = 0
+
+      ioserrcount = 0
+
+      DO jk = 1, iobstot
+
+         jj = ifileidx(iindx(jk))
+         ji = isurfidx(iindx(jk))
+         IF ( ( inpfiles(jj)%ptim(ji) >  djulini(jj) ) .AND.  &
+            & ( inpfiles(jj)%ptim(ji) <= djulend(jj) ) ) THEN
+
+            IF ( nproc == 0 ) THEN
+               IF ( inpfiles(jj)%iproc(ji,1) >  nproc ) CYCLE
+            ELSE
+               IF ( inpfiles(jj)%iproc(ji,1) /= nproc ) CYCLE
+            ENDIF
+
+            ! Set observation information
+
+            IF ( .NOT. BTEST(inpfiles(jj)%ivlqc(1,ji,1),2) ) THEN
+
+               iobs = iobs + 1
+
+               CALL jul2greg( isec,                   &
+                  &           imin,                   &
+                  &           ihou,                   &
+                  &           iday,                   &
+                  &           imon,                   &
+                  &           iyea,                   &
+                  &           inpfiles(jj)%ptim(ji), &
+                  &           irefdate(jj) )
+
+
+               ! Surface time coordinates
+               surfdata%nyea(iobs) = iyea
+               surfdata%nmon(iobs) = imon
+               surfdata%nday(iobs) = iday
+               surfdata%nhou(iobs) = ihou
+               surfdata%nmin(iobs) = imin
+
+               ! Surface space coordinates
+               surfdata%rlam(iobs) = inpfiles(jj)%plam(ji)
+               surfdata%rphi(iobs) = inpfiles(jj)%pphi(ji)
+
+               ! Coordinate search parameters
+               surfdata%mi  (iobs) = inpfiles(jj)%iobsi(ji,1)
+               surfdata%mj  (iobs) = inpfiles(jj)%iobsj(ji,1)
+
+               ! WMO number
+               surfdata%cwmo(iobs) = inpfiles(jj)%cdwmo(ji)
+
+               ! Instrument type
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) THEN
+                     CALL ctl_warn ( 'Problem converting an instrument type ', &
+                        &            'to integer. Setting type to zero' )
+                  ENDIF
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
+               surfdata%ntyp(iobs) = itype
+               IF ( itype < jpsurfmaxtype + 1 ) THEN
+                  ityp(itype+1) = ityp(itype+1) + 1
+               ELSE
+                  IF(lwp)WRITE(numout,*)'WARNING:Increase jpsurfmaxtype in ',&
+                     &                  cpname
+               ENDIF
+
+               ! Bookkeeping data to match observations
+               surfdata%nsidx(iobs) = iobs
+               surfdata%nsfil(iobs) = iindx(jk)
+
+               ! QC flags
+               surfdata%nqc(iobs) = inpfiles(jj)%ivqc(ji,1)
+
+               ! Observed value
+               surfdata%robs(iobs,1) = inpfiles(jj)%pob(1,ji,1)
+
+
+               ! Model and MDT is set to fbrmdi unless read from file
+               IF ( ldmod ) THEN
+                  surfdata%rmod(iobs,1) = inpfiles(jj)%padd(1,ji,1,1)
+                  IF ( TRIM(surfdata%cvars(1)) == 'SLA' ) THEN
+                     surfdata%rext(iobs,1) = inpfiles(jj)%padd(1,ji,2,1)
+                     surfdata%rext(iobs,2) = inpfiles(jj)%pext(1,ji,1)
+                  ENDIF
+                ELSE
+                  surfdata%rmod(iobs,1) = fbrmdi
+                  IF ( TRIM(surfdata%cvars(1)) == 'SLA' ) surfdata%rext(iobs,:) = fbrmdi
+               ENDIF
+            ENDIF
+         ENDIF
+
+      END DO
+
+      !-----------------------------------------------------------------------
+      ! Sum up over processors
+      !-----------------------------------------------------------------------
+
+      CALL obs_mpp_sum_integer( iobs, iobsmpp )
+      CALL obs_mpp_sum_integers( ityp, itypmpp, jpsurfmaxtype + 1 )
+
+      !-----------------------------------------------------------------------
+      ! Output number of observations.
+      !-----------------------------------------------------------------------
+      IF (lwp) THEN
+
+         WRITE(numout,*)
+         WRITE(numout,'(1X,A)')TRIM( surfdata%cvars(1) )//' data'
+         WRITE(numout,'(1X,A)')'--------------'
+         DO jj = 1,8
+            IF ( itypmpp(jj) > 0 ) THEN
+               WRITE(numout,'(1X,A4,I4,A3,I10)')'Type ', jj,' = ',itypmpp(jj)
+            ENDIF
+         END DO
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,'(1X,A,I8)') &
+            & 'Total data for variable '//TRIM( surfdata%cvars(1) )// &
+            & '           = ', iobsmpp
+         WRITE(numout,'(1X,A)') &
+            & '---------------------------------------------------------------'
+         WRITE(numout,*)
+
+      ENDIF
+
+      !-----------------------------------------------------------------------
+      ! Deallocate temporary data
+      !-----------------------------------------------------------------------
+      DEALLOCATE( ifileidx, isurfidx, zdat, clvars )
+
+      !-----------------------------------------------------------------------
+      ! Deallocate input data
+      !-----------------------------------------------------------------------
+      DO jj = 1, inobf
+         IF ( inpfiles(jj)%lalloc ) THEN
+            CALL dealloc_obfbdata( inpfiles(jj) )
+         ENDIF
+      END DO
+      DEALLOCATE( inpfiles )
+
+   END SUBROUTINE obs_rea_surf
+
+END MODULE obs_read_surf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_readmdt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_readmdt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_readmdt.F90	(revision 14097)
@@ -0,0 +1,258 @@
+MODULE obs_readmdt
+   !!======================================================================
+   !!                       ***  MODULE obs_readmdt  ***
+   !! Observation diagnostics: Read the MDT for SLA data (skeleton for now)
+   !!======================================================================
+   !! History :      ! 2007-03 (K. Mogensen) Initial skeleton version
+   !!                ! 2007-04 (E. Remy) migration and improvement from OPAVAR
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   obs_rea_mdt    : Driver for reading MDT
+   !!   obs_offset_mdt : Remove the offset between the model MDT and the used one
+   !!----------------------------------------------------------------------
+   USE par_kind         ! Precision variables
+   USE par_oce          ! Domain parameters
+   USE in_out_manager   ! I/O manager
+   USE obs_surf_def     ! Surface observation definitions
+   USE obs_inter_sup    ! Interpolation support routines
+   USE obs_inter_h2d    ! 2D interpolation
+   USE obs_utils        ! Various observation tools
+   USE iom_nf90         ! IOM NetCDF
+   USE netcdf           ! NetCDF library
+   USE lib_mpp          ! MPP library
+   USE dom_oce, ONLY : &                  ! Domain variables
+      &                    tmask, tmask_i, e1e2t, gphit, glamt
+   USE obs_const, ONLY :   obfillflt      ! Fillvalue
+   USE oce      , ONLY :   sshn           ! Model variables
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   obs_rea_mdt     ! called by dia_obs_init
+   PUBLIC   obs_offset_mdt  ! called by obs_rea_mdt
+
+   INTEGER , PUBLIC :: nn_msshc    = 1         ! MDT correction scheme
+   REAL(wp), PUBLIC :: rn_mdtcorr   = 1.61_wp  ! User specified MDT correction
+   REAL(wp), PUBLIC :: rn_mdtcutoff = 65.0_wp  ! MDT cutoff for computed correction
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE obs_rea_mdt( sladata, k2dint )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_rea_mdt ***
+      !!
+      !! ** Purpose : Read from file the MDT data (skeleton)
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      USE iom
+      !
+      TYPE(obs_surf), INTENT(inout) ::   sladata   ! SLA data
+      INTEGER       , INTENT(in)    ::   k2dint    ! ?
+      !
+      CHARACTER(LEN=12), PARAMETER ::   cpname  = 'obs_rea_mdt'
+      CHARACTER(LEN=20), PARAMETER ::   mdtname = 'slaReferenceLevel.nc'
+
+      INTEGER ::   jobs                ! Obs loop variable
+      INTEGER ::   jpimdt, jpjmdt      ! Number of grid point in lat/lon for the MDT
+      INTEGER ::   iico, ijco          ! Grid point indicies
+      INTEGER ::   i_nx_id, i_ny_id, i_file_id, i_var_id, i_stat
+      INTEGER ::   nummdt
+      !
+      REAL(wp), DIMENSION(1)     ::   zext, zobsmask
+      REAL(wp), DIMENSION(2,2,1) ::   zweig
+      !
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zmask, zmdtl, zglam, zgphi
+      INTEGER , DIMENSION(:,:,:), ALLOCATABLE ::   igrdi, igrdj
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::  z_mdt, mdtmask
+         
+      REAL(wp) :: zlam, zphi, zfill, zinfill    ! local scalar
+      !!----------------------------------------------------------------------
+
+      IF(lwp)WRITE(numout,*) 
+      IF(lwp)WRITE(numout,*) ' obs_rea_mdt : Read MDT for referencing altimeter anomalies'
+      IF(lwp)WRITE(numout,*) ' ------------- '
+      CALL FLUSH(numout)
+
+      CALL iom_open( mdtname, nummdt )       ! Open the file
+      !                                      ! Get the MDT data
+      CALL iom_get ( nummdt, jpdom_data, 'sossheig', z_mdt(:,:), 1 )
+      CALL iom_close(nummdt)                 ! Close the file
+      
+      ! Read in the fill value
+      zinfill = 0.0
+      i_stat = nf90_open( mdtname, nf90_nowrite, nummdt )
+      i_stat = nf90_inq_varid( nummdt, 'sossheig', i_var_id )
+      i_stat = nf90_get_att( nummdt, i_var_id, "_FillValue",zinfill)
+      zfill = zinfill
+      i_stat = nf90_close( nummdt )
+
+      ! setup mask based on tmask and MDT mask
+      ! set mask to 0 where the MDT is set to fillvalue
+      WHERE(z_mdt(:,:) /= zfill)   ;   mdtmask(:,:) = tmask(:,:,1)
+      ELSE WHERE                   ;   mdtmask(:,:) = 0
+      END WHERE
+
+      ! Remove the offset between the MDT used with the sla and the model MDT
+      IF( nn_msshc == 1 .OR. nn_msshc == 2 ) &
+         & CALL obs_offset_mdt( jpi, jpj, z_mdt, zfill )
+
+      ! Intepolate the MDT already on the model grid at the observation point
+  
+      ALLOCATE( &
+         & igrdi(2,2,sladata%nsurf), &
+         & igrdj(2,2,sladata%nsurf), &
+         & zglam(2,2,sladata%nsurf), &
+         & zgphi(2,2,sladata%nsurf), &
+         & zmask(2,2,sladata%nsurf), &
+         & zmdtl(2,2,sladata%nsurf)  &
+         & )
+         
+      DO jobs = 1, sladata%nsurf
+
+         igrdi(1,1,jobs) = sladata%mi(jobs)-1
+         igrdj(1,1,jobs) = sladata%mj(jobs)-1
+         igrdi(1,2,jobs) = sladata%mi(jobs)-1
+         igrdj(1,2,jobs) = sladata%mj(jobs)
+         igrdi(2,1,jobs) = sladata%mi(jobs)
+         igrdj(2,1,jobs) = sladata%mj(jobs)-1
+         igrdi(2,2,jobs) = sladata%mi(jobs)
+         igrdj(2,2,jobs) = sladata%mj(jobs)
+
+      END DO
+
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, igrdi, igrdj, glamt  , zglam )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, igrdi, igrdj, gphit  , zgphi )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, igrdi, igrdj, mdtmask, zmask )
+      CALL obs_int_comm_2d( 2, 2, sladata%nsurf, jpi, jpj, igrdi, igrdj, z_mdt  , zmdtl )
+
+      DO jobs = 1, sladata%nsurf
+            
+         zlam = sladata%rlam(jobs)
+         zphi = sladata%rphi(jobs)
+
+         CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,         &
+            &                   zglam(:,:,jobs), zgphi(:,:,jobs), &
+            &                   zmask(:,:,jobs), zweig, zobsmask )
+            
+         CALL obs_int_h2d( 1, 1, zweig, zmdtl(:,:,jobs),  zext )
+ 
+         sladata%rext(jobs,2) = zext(1)
+
+! mark any masked data with a QC flag
+         IF( zobsmask(1) == 0 )   sladata%nqc(jobs) = IBSET(sladata%nqc(jobs),15)
+
+         END DO
+         
+      DEALLOCATE( &
+         & igrdi, &
+         & igrdj, &
+         & zglam, &
+         & zgphi, &
+         & zmask, &
+         & zmdtl  &
+         & )
+
+      IF(lwp)WRITE(numout,*) ' ------------- '
+      !
+   END SUBROUTINE obs_rea_mdt
+
+
+   SUBROUTINE obs_offset_mdt( kpi, kpj, mdt, zfill )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_offset_mdt ***
+      !!
+      !! ** Purpose : Compute a correction term for the MDT on the model grid
+      !!             !!!!! IF it is on the model grid
+      !!
+      !! ** Method  : Compute the mean difference between the model and the 
+      !!              used MDT and remove the offset. 
+      !!
+      !! ** Action  : 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(IN) ::  kpi, kpj
+      REAL(wp), DIMENSION(kpi,kpj), INTENT(INOUT) ::   mdt     ! MDT used on the model grid
+      REAL(wp)                    , INTENT(IN   ) ::   zfill 
+      ! 
+      INTEGER  :: ji, jj
+      REAL(wp) :: zdxdy, zarea, zeta1, zeta2, zcorr_mdt, zcorr_bcketa, zcorr     ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj) :: zpromsk
+      CHARACTER(LEN=14), PARAMETER ::   cpname = 'obs_offset_mdt'
+      !!----------------------------------------------------------------------
+
+      !  Initialize the local mask, for domain projection 
+      !  Also exclude mdt points which are set to missing data
+
+      DO ji = 1, jpi
+        DO jj = 1, jpj
+           zpromsk(ji,jj) = tmask_i(ji,jj)
+           IF (    ( gphit(ji,jj) .GT.  rn_mdtcutoff ) &
+              &.OR.( gphit(ji,jj) .LT. -rn_mdtcutoff ) &
+              &.OR.( mdt(ji,jj) .EQ. zfill ) ) &
+              &        zpromsk(ji,jj) = 0.0
+        END DO
+      END DO 
+
+      ! Compute MSSH mean over [0,360] x [-rn_mdtcutoff,rn_mdtcutoff]
+
+      zarea = 0.0
+      zeta1 = 0.0
+      zeta2 = 0.0
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+          zdxdy = e1e2t(ji,jj) * zpromsk(ji,jj)
+          zarea = zarea + zdxdy
+          zeta1 = zeta1 + mdt(ji,jj) * zdxdy
+          zeta2 = zeta2 + sshn (ji,jj) * zdxdy
+        END DO      
+      END DO
+
+      CALL mpp_sum( 'obs_readmdt', zeta1 )
+      CALL mpp_sum( 'obs_readmdt', zeta2 )
+      CALL mpp_sum( 'obs_readmdt', zarea )
+      
+      zcorr_mdt    = zeta1 / zarea
+      zcorr_bcketa = zeta2 / zarea
+
+      !  Define correction term
+
+      zcorr = zcorr_mdt - zcorr_bcketa
+
+      !  Correct spatial mean of the MSSH
+
+      IF( nn_msshc == 1 )   mdt(:,:) = mdt(:,:) - zcorr  
+
+      ! User defined value : 1.6 m for the Rio MDT compared to ORCA2 MDT
+
+      IF( nn_msshc == 2 )   mdt(:,:) = mdt(:,:) - rn_mdtcorr
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' obs_readmdt : rn_mdtcutoff     = ', rn_mdtcutoff
+         WRITE(numout,*) ' -----------   zcorr_mdt     = ', zcorr_mdt
+         WRITE(numout,*) '               zcorr_bcketa  = ', zcorr_bcketa
+         WRITE(numout,*) '               zcorr         = ', zcorr
+         WRITE(numout,*) '               nn_msshc        = ', nn_msshc
+      ENDIF
+
+      IF ( nn_msshc == 0 ) WRITE(numout,*) '           MSSH correction is not applied'
+      IF ( nn_msshc == 1 ) WRITE(numout,*) '           MSSH correction is applied'
+      IF ( nn_msshc == 2 ) WRITE(numout,*) '           User defined MSSH correction' 
+
+      !
+   END SUBROUTINE obs_offset_mdt
+ 
+   !!======================================================================
+END MODULE obs_readmdt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_rot_vel.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_rot_vel.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_rot_vel.F90	(revision 14097)
@@ -0,0 +1,228 @@
+MODULE obs_rot_vel
+   !!======================================================================
+   !!                       ***  MODULE obs_rot_vel  ***
+   !! Observation diagnostics: Read the velocity profile observations
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_rotvel : Rotate velocity data into N-S,E-W directorions
+   !!----------------------------------------------------------------------
+   !! * Modules used   
+   USE par_kind                 ! Precision variables
+   USE par_oce                  ! Ocean parameters
+   USE in_out_manager           ! I/O manager
+   USE dom_oce                  ! Ocean space and time domain variables
+   USE obs_grid                 ! Grid search
+   USE obs_utils                ! For error handling
+   USE obs_profiles_def         ! Profile definitions
+   USE obs_inter_h2d            ! Horizontal interpolation
+   USE obs_inter_sup            ! MPP support routines for interpolation
+   USE geo2ocean                ! Rotation of vectors
+   USE obs_fbm                  ! Feedback definitions
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+
+   PUBLIC obs_rotvel            ! Rotate the observations
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_rotvel( profdata, k2dint, pu, pv )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_rea_pro_dri ***
+      !!
+      !! ** Purpose : Rotate velocity data into N-S,E-W directorions
+      !!
+      !! ** Method  : Interpolation of geo2ocean coefficients on U,V grid
+      !!              to observation point followed by a similar computations
+      !!              as in geo2ocean.
+      !!
+      !! ** Action  : Review if there is a better way to do this.
+      !!
+      !! References : 
+      !!
+      !! History :  
+      !!      ! :  2009-02 (K. Mogensen) : New routine
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: profdata    ! Profile data to be read
+      INTEGER, INTENT(IN) :: k2dint     ! Horizontal interpolation methed
+      REAL(wp), DIMENSION(*) :: &
+         & pu, &
+         & pv
+      !! * Local declarations
+      REAL(wp), DIMENSION(2,2,1) :: zweig
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zmasku, &
+         & zmaskv, &
+         & zcoslu, &
+         & zsinlu, &
+         & zcoslv, &
+         & zsinlv, &
+         & zglamu, &
+         & zgphiu, &
+         & zglamv, &
+         & zgphiv
+      REAL(wp), DIMENSION(1) :: &
+         & zsinu, &
+         & zcosu, &
+         & zsinv, &
+         & zcosv
+      REAL(wp) :: zsin
+      REAL(wp) :: zcos
+      REAL(wp), DIMENSION(1) :: zobsmask
+      REAL(wp), DIMENSION(jpi,jpj) :: zsingu,zcosgu,zsingv,zcosgv
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdiu, &
+         & igrdju, &
+         & igrdiv, &
+         & igrdjv
+      INTEGER :: ji
+      INTEGER :: jk
+
+
+      !-----------------------------------------------------------------------
+      ! Allocate data for message parsing and interpolation
+      !-----------------------------------------------------------------------
+
+      ALLOCATE( &
+         & igrdiu(2,2,profdata%nprof), &
+         & igrdju(2,2,profdata%nprof), &
+         & zglamu(2,2,profdata%nprof), &
+         & zgphiu(2,2,profdata%nprof), &
+         & zmasku(2,2,profdata%nprof), &
+         & zcoslu(2,2,profdata%nprof), &
+         & zsinlu(2,2,profdata%nprof), &
+         & igrdiv(2,2,profdata%nprof), &
+         & igrdjv(2,2,profdata%nprof), &
+         & zglamv(2,2,profdata%nprof), &
+         & zgphiv(2,2,profdata%nprof), &
+         & zmaskv(2,2,profdata%nprof), &
+         & zcoslv(2,2,profdata%nprof), &
+         & zsinlv(2,2,profdata%nprof)  &
+         & )
+
+      !-----------------------------------------------------------------------
+      ! Receive the angles on the U and V grids.
+      !-----------------------------------------------------------------------
+
+      CALL obs_rot( zsingu, zcosgu, zsingv, zcosgv )
+
+      DO ji = 1, profdata%nprof
+         igrdiu(1,1,ji) = profdata%mi(ji,1)-1
+         igrdju(1,1,ji) = profdata%mj(ji,1)-1
+         igrdiu(1,2,ji) = profdata%mi(ji,1)-1
+         igrdju(1,2,ji) = profdata%mj(ji,1)
+         igrdiu(2,1,ji) = profdata%mi(ji,1)
+         igrdju(2,1,ji) = profdata%mj(ji,1)-1
+         igrdiu(2,2,ji) = profdata%mi(ji,1)
+         igrdju(2,2,ji) = profdata%mj(ji,1)
+         igrdiv(1,1,ji) = profdata%mi(ji,2)-1
+         igrdjv(1,1,ji) = profdata%mj(ji,2)-1
+         igrdiv(1,2,ji) = profdata%mi(ji,2)-1
+         igrdjv(1,2,ji) = profdata%mj(ji,2)
+         igrdiv(2,1,ji) = profdata%mi(ji,2)
+         igrdjv(2,1,ji) = profdata%mj(ji,2)-1
+         igrdiv(2,2,ji) = profdata%mi(ji,2)
+         igrdjv(2,2,ji) = profdata%mj(ji,2)
+      END DO
+
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiu, igrdju, &
+         &                  glamu, zglamu )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiu, igrdju, &
+         &                  gphiu, zgphiu )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiu, igrdju, &
+         &                  umask(:,:,1), zmasku )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiu, igrdju, &
+         &                  zsingu, zsinlu )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiu, igrdju, &
+         &                  zcosgu, zcoslu )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiv, igrdjv, &
+         &                  glamv, zglamv )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiv, igrdjv, &
+         &                  gphiv, zgphiv )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiv, igrdjv, &
+         &                  vmask(:,:,1), zmaskv )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiv, igrdjv, &
+         &                  zsingv, zsinlv )
+      CALL obs_int_comm_2d( 2, 2, profdata%nprof, jpi, jpj, igrdiv, igrdjv, &
+         &                  zcosgv, zcoslv )
+
+      DO ji = 1, profdata%nprof
+            
+         CALL obs_int_h2d_init( 1, 1, k2dint, &
+            &                   profdata%rlam(ji), profdata%rphi(ji), &
+            &                   zglamu(:,:,ji), zgphiu(:,:,ji), &
+            &                   zmasku(:,:,ji), zweig, zobsmask )
+         
+         CALL obs_int_h2d( 1, 1, zweig, zsinlu(:,:,ji),  zsinu )
+
+         CALL obs_int_h2d( 1, 1, zweig, zcoslu(:,:,ji),  zcosu )
+
+         CALL obs_int_h2d_init( 1, 1, k2dint, &
+            &                   profdata%rlam(ji), profdata%rphi(ji), &
+            &                   zglamv(:,:,ji), zgphiv(:,:,ji), &
+            &                   zmaskv(:,:,ji), zweig, zobsmask )
+         
+         CALL obs_int_h2d( 1, 1, zweig, zsinlv(:,:,ji),  zsinv )
+
+         CALL obs_int_h2d( 1, 1, zweig, zcoslv(:,:,ji),  zcosv )
+
+         ! Assume that the angle at observation point is the 
+         ! mean of u and v cosines/sines
+
+         zcos = 0.5_wp * ( zcosu(1) + zcosv(1) )
+         zsin = 0.5_wp * ( zsinu(1) + zsinv(1) )
+         
+         IF ( ( profdata%npvsta(ji,1) /= profdata%npvsta(ji,2) ) .OR. &
+            & ( profdata%npvend(ji,1) /= profdata%npvend(ji,2) ) ) THEN
+            CALL fatal_error( 'Different number of U and V observations '// &
+               'in a profile in obs_rotvel', __LINE__ )
+         ENDIF
+
+         DO jk = profdata%npvsta(ji,1), profdata%npvend(ji,1)
+            IF ( ( profdata%var(1)%vmod(jk) /= fbrmdi ) .AND. &
+               & ( profdata%var(2)%vmod(jk) /= fbrmdi ) ) THEN
+               pu(jk) = profdata%var(1)%vmod(jk) * zcos - &
+                  &     profdata%var(2)%vmod(jk) * zsin
+               pv(jk) = profdata%var(2)%vmod(jk) * zcos + &
+                  &     profdata%var(1)%vmod(jk) * zsin
+            ELSE
+               pu(jk) = fbrmdi
+               pv(jk) = fbrmdi
+            ENDIF
+
+         END DO
+
+      END DO
+      
+      DEALLOCATE( &
+         & igrdiu, &
+         & igrdju, &
+         & zglamu, &
+         & zgphiu, &
+         & zmasku, &
+         & zcoslu, &
+         & zsinlu, &
+         & igrdiv, &
+         & igrdjv, &
+         & zglamv, &
+         & zgphiv, &
+         & zmaskv, &
+         & zcoslv, &
+         & zsinlv  &
+         & )
+
+   END SUBROUTINE obs_rotvel
+
+END MODULE obs_rot_vel
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sort.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sort.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sort.F90	(revision 14097)
@@ -0,0 +1,147 @@
+MODULE obs_sort
+   !!=====================================================================
+   !!                       ***  MODULE obs_sort  ***
+   !! Observation diagnostics: Various tools for sorting etc.
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   sort_dp_indx : Get indicies for ascending order for a double prec. array
+   !!   index_sort   : Get indicies for ascending order for a double prec. array
+   !!---------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : & ! Precision variables
+      & dp
+  
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE index_sort    ! Get indicies for ascending order for a double prec. array
+   
+   PUBLIC sort_dp_indx   ! Get indicies for ascending order for a double prec. array
+  
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE sort_dp_indx( kvals, pvals, kindx )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE sort_dp_indx  ***
+      !!          
+      !! ** Purpose : Get indicies for ascending order for a double precision array
+      !!
+      !! ** Method  : Call index_sort routine
+      !!
+      !! ** Action  : 
+      !!
+      !! History :
+      !!        !  06-05  (K. Mogensen)  Original code
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kvals     ! Number of elements to be sorted
+      REAL(KIND=dp), DIMENSION(kvals), INTENT(IN) :: &
+         & pvals            ! Array to be sorted
+      INTEGER, DIMENSION(kvals), INTENT(OUT) ::  &
+         & kindx            ! Indices for ordering of array
+
+      !! * Local declarations
+
+      !-----------------------------------------------------------------------
+      ! Call qsort routine
+      !-----------------------------------------------------------------------
+      IF (kvals>=1) THEN
+
+         CALL index_sort( pvals, kindx, kvals )
+
+      ENDIF
+
+   END SUBROUTINE sort_dp_indx
+
+   SUBROUTINE index_sort( pval, kindx, kvals )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE index_sort  ***
+      !!          
+      !! ** Purpose : Get indicies for ascending order for a double precision array
+      !!
+      !! ** Method  : Heapsort
+      !!
+      !! ** Action  : 
+      !!
+      !! References : http://en.wikipedia.org/wiki/Heapsort
+      !!
+      !! History :
+      !!        !  06-05  (K. Mogensen)  Original code
+      !!        !  06-10  (A. Weaver) Cleaning
+      !!----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kvals         ! Number of values
+      REAL(KIND=dp), DIMENSION(kvals), INTENT(IN) :: &
+         & pval                            ! Array to be sorted
+      INTEGER, DIMENSION(kvals), INTENT(INOUT) :: &
+         & kindx                           ! Indicies for ordering
+
+      !! * Local declarations
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jt
+      INTEGER :: jn
+      INTEGER :: jparent
+      INTEGER :: jchild
+
+      DO ji = 1, kvals
+         kindx(ji) = ji
+      END DO
+      
+      ji = kvals/2 + 1
+      jn = kvals
+
+      main_loop : DO
+
+         IF ( ji > 1 ) THEN
+            ji = ji-1
+            jt = kindx(ji)
+         ELSE
+            jt = kindx(jn)
+            kindx(jn) = kindx(1)
+            jn = jn-1
+            IF ( jn <= 1 ) THEN
+               kindx(1) = jt
+               EXIT main_loop
+            ENDIF
+         ENDIF
+
+         jparent = ji
+         jchild =  2 * ji
+
+         inner_loop : DO
+
+            IF ( jchild > jn ) EXIT inner_loop
+            IF ( jchild < jn ) THEN
+               IF ( pval(kindx(jchild)) < pval(kindx(jchild+1)) ) THEN
+                 jchild = jchild+1
+               ENDIF
+            ENDIF
+            IF  ( pval(jt) < pval(kindx(jchild))) THEN
+               kindx(jparent) = kindx(jchild)
+               jparent = jchild
+               jchild  = jchild*2
+            ELSE 
+               jchild = jn + 1 
+            ENDIF
+
+         END DO inner_loop
+
+         kindx(jparent) = jt
+
+      END DO main_loop
+      
+   END SUBROUTINE index_sort
+
+END MODULE obs_sort
+ 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sstbias.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sstbias.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_sstbias.F90	(revision 14097)
@@ -0,0 +1,243 @@
+MODULE obs_sstbias
+   !!======================================================================
+   !!                       ***  MODULE obs_sstbias  ***
+   !! Observation diagnostics: Read the bias for SST data
+   !!======================================================================
+   !!----------------------------------------------------------------------
+   !!   obs_app_sstbias : Driver for reading and applying the SST bias
+   !!----------------------------------------------------------------------
+   !! * Modules used   
+   USE par_kind, ONLY : &       ! Precision variables
+      & wp, &
+      & dp, &
+      & sp
+   USE par_oce, ONLY : &        ! Domain parameters
+      & jpi, &
+      & jpj, &
+      & jpim1
+   USE in_out_manager, ONLY : & ! I/O manager
+      & lwp,    &
+      & numout 
+   USE obs_surf_def             ! Surface observation definitions
+   USE dom_oce, ONLY : &        ! Domain variables
+      & tmask, &
+      & tmask_i, &
+      & e1t,   &
+      & e2t,   &
+      & gphit, &
+      & glamt
+   USE oce, ONLY : &           ! Model variables
+      & sshn
+   USE obs_inter_h2d
+   USE obs_utils               ! Various observation tools
+   USE obs_inter_sup
+   IMPLICIT NONE
+   !! * Routine accessibility
+   PRIVATE
+   PUBLIC obs_app_sstbias     ! Read the altimeter bias
+CONTAINS
+   SUBROUTINE obs_app_sstbias( sstdata, k2dint, knumtypes, &
+                               cl_bias_files )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_app_sstbias ***
+      !!
+      !! ** Purpose : Read SST bias data from files and apply correction to
+      !!             observations
+      !!
+      !! ** Method  :
+      !!
+      !! ** Action  :
+      !!
+      !! References :
+      !!
+      !! History : 
+      !!      ! :  2014-08 (J. While) Bias correction code for SST obs,
+      !!      !                      based on obs_rea_altbias
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE iom
+      USE netcdf
+      !! * Arguments
+
+      TYPE(obs_surf), INTENT(INOUT) :: sstdata       ! SST data
+      INTEGER, INTENT(IN) :: k2dint
+      INTEGER, INTENT(IN) :: knumtypes !number of bias types to read in
+      CHARACTER(LEN=128), DIMENSION(knumtypes), INTENT(IN) :: &
+                          cl_bias_files !List of files to read
+      !! * Local declarations
+      INTEGER :: jobs         ! Obs loop variable
+      INTEGER :: jpisstbias   ! Number of grid point in latitude for the bias
+      INTEGER :: jpjsstbias   ! Number of grid point in longitude for the bias
+      INTEGER :: iico         ! Grid point indices
+      INTEGER :: ijco
+      INTEGER :: jt
+      INTEGER :: i_nx_id      ! Index to read the NetCDF file
+      INTEGER :: i_ny_id      !
+      INTEGER :: i_file_id    !
+      INTEGER :: i_var_id
+      INTEGER, DIMENSION(knumtypes) :: &
+         & ibiastypes             ! Array of the bias types in each file
+      REAL(wp), DIMENSION(jpi,jpj,knumtypes) :: & 
+         & z_sstbias              ! Array to store the SST bias values
+      REAL(wp), DIMENSION(jpi,jpj) :: & 
+         & z_sstbias_2d           ! Array to store the SST bias values   
+      REAL(wp), DIMENSION(1) :: &
+         & zext, &
+         & zobsmask
+      REAL(wp), DIMENSION(2,2,1) :: &
+         & zweig
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zmask, &
+         & zglam, &
+         & zgphi
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: &
+         & zmask_tmp, &
+         & zglam_tmp, &
+         & zgphi_tmp   
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  zbias   
+      REAL(wp) :: zlam
+      REAL(wp) :: zphi
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdi, &
+         & igrdj
+      INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: &
+         & igrdi_tmp, &
+         & igrdj_tmp   
+      INTEGER :: numsstbias
+      INTEGER(KIND=NF90_INT) :: ifile_source
+     
+      INTEGER :: incfile
+      INTEGER :: jtype
+      INTEGER :: iret 
+      INTEGER :: inumtype
+      IF(lwp)WRITE(numout,*) 
+      IF(lwp)WRITE(numout,*) 'obs_rea_sstbias : '
+      IF(lwp)WRITE(numout,*) '----------------- '
+      IF(lwp)WRITE(numout,*) 'Read SST bias '
+      ! Open and read the files
+      z_sstbias(:,:,:)=0.0_wp
+      DO jtype = 1, knumtypes
+     
+         numsstbias=0
+         IF(lwp)WRITE(numout,*) 'Opening ',cl_bias_files(jtype)
+         CALL iom_open( cl_bias_files(jtype), numsstbias, ldstop=.FALSE. )       
+         IF (numsstbias > 0) THEN
+     
+            !Read the bias type from the file
+            !No IOM get attribute command at time of writing, 
+            !so have to use NETCDF
+            !routines directly - should be upgraded in the future
+            iret=NF90_OPEN(TRIM(cl_bias_files(jtype)), NF90_NOWRITE, incfile)
+            iret=NF90_GET_ATT( incfile, NF90_GLOBAL, "SST_source", &
+                              ifile_source )
+            ibiastypes(jtype) = ifile_source                 
+            iret=NF90_CLOSE(incfile)       
+           
+            IF ( iret /= 0  ) CALL ctl_stop( &
+               'obs_rea_sstbias : Cannot read bias type from file '// &
+               cl_bias_files(jtype) )
+            ! Get the SST bias data
+            CALL iom_get( numsstbias, jpdom_data, 'tn', z_sstbias_2d(:,:), 1 )
+            z_sstbias(:,:,jtype) = z_sstbias_2d(:,:)       
+            ! Close the file
+            CALL iom_close(numsstbias)       
+         ELSE
+            CALL ctl_stop('obs_read_sstbias: File '// & 
+                           TRIM( cl_bias_files(jtype) )//' Not found')
+         ENDIF
+      END DO
+           
+      ! Interpolate the bias already on the model grid at the observation point
+      ALLOCATE( &
+         & igrdi(2,2,sstdata%nsurf), &
+         & igrdj(2,2,sstdata%nsurf), &
+         & zglam(2,2,sstdata%nsurf), &
+         & zgphi(2,2,sstdata%nsurf), &
+         & zmask(2,2,sstdata%nsurf)  )
+       
+      DO jobs = 1, sstdata%nsurf 
+         igrdi(1,1,jobs) = sstdata%mi(jobs)-1
+         igrdj(1,1,jobs) = sstdata%mj(jobs)-1
+         igrdi(1,2,jobs) = sstdata%mi(jobs)-1
+         igrdj(1,2,jobs) = sstdata%mj(jobs)
+         igrdi(2,1,jobs) = sstdata%mi(jobs)
+         igrdj(2,1,jobs) = sstdata%mj(jobs)-1
+         igrdi(2,2,jobs) = sstdata%mi(jobs)
+         igrdj(2,2,jobs) = sstdata%mj(jobs)
+      END DO
+      CALL obs_int_comm_2d( 2, 2, sstdata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, glamt, zglam )
+      CALL obs_int_comm_2d( 2, 2, sstdata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, gphit, zgphi )
+      CALL obs_int_comm_2d( 2, 2, sstdata%nsurf, jpi, jpj, &
+         &                  igrdi, igrdj, tmask(:,:,1), zmask )
+      DO jtype = 1, knumtypes
+         
+         !Find the number observations of type and allocate tempory arrays
+         inumtype = COUNT( sstdata%ntyp(:) == ibiastypes(jtype) )
+         ALLOCATE( &
+            & igrdi_tmp(2,2,inumtype), &
+            & igrdj_tmp(2,2,inumtype), &
+            & zglam_tmp(2,2,inumtype), &
+            & zgphi_tmp(2,2,inumtype), &
+            & zmask_tmp(2,2,inumtype), &
+            & zbias( 2,2,inumtype ) )
+         jt=1
+         DO jobs = 1, sstdata%nsurf 
+            IF ( sstdata%ntyp(jobs) == ibiastypes(jtype) ) THEN
+               igrdi_tmp(:,:,jt) = igrdi(:,:,jobs) 
+               igrdj_tmp(:,:,jt) = igrdj(:,:,jobs)
+               zglam_tmp(:,:,jt) = zglam(:,:,jobs)
+               zgphi_tmp(:,:,jt) = zgphi(:,:,jobs)
+               zmask_tmp(:,:,jt) = zmask(:,:,jobs)
+               jt = jt +1
+            ENDIF
+         END DO
+                         
+         CALL obs_int_comm_2d( 2, 2, inumtype, jpi, jpj, &
+               &           igrdi_tmp(:,:,:), igrdj_tmp(:,:,:), &
+               &           z_sstbias(:,:,jtype), zbias(:,:,:) )
+         jt=1
+         DO jobs = 1, sstdata%nsurf
+            IF ( sstdata%ntyp(jobs) == ibiastypes(jtype) ) THEN
+               zlam = sstdata%rlam(jobs)
+               zphi = sstdata%rphi(jobs)
+               iico = sstdata%mi(jobs)
+               ijco = sstdata%mj(jobs)         
+               CALL obs_int_h2d_init( 1, 1, k2dint, zlam, zphi,         &
+                  &                   zglam_tmp(:,:,jt), &
+                  &                   zgphi_tmp(:,:,jt), &
+                  &                   zmask_tmp(:,:,jt), zweig, zobsmask )
+               CALL obs_int_h2d( 1, 1, zweig, zbias(:,:,jt),  zext )
+               ! adjust sst with bias field
+               sstdata%robs(jobs,1) = sstdata%robs(jobs,1) - zext(1)
+               jt=jt+1
+            ENDIF
+         END DO 
+               
+         !Deallocate arrays
+         DEALLOCATE( &
+         & igrdi_tmp, &
+         & igrdj_tmp, &
+         & zglam_tmp, &
+         & zgphi_tmp, &
+         & zmask_tmp, &
+         & zbias )           
+      END DO
+      DEALLOCATE( &
+         & igrdi, &
+         & igrdj, &
+         & zglam, &
+         & zgphi, &
+         & zmask )
+
+      IF(lwp) THEN
+         WRITE(numout,*) " "
+         WRITE(numout,*) "SST bias correction applied successfully"
+         WRITE(numout,*) "Obs types: ",ibiastypes(:), &
+                              " Have all been bias corrected\n"
+      ENDIF
+   END SUBROUTINE obs_app_sstbias
+ 
+END MODULE obs_sstbias
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_surf_def.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_surf_def.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_surf_def.F90	(revision 14097)
@@ -0,0 +1,530 @@
+MODULE obs_surf_def
+   !!=====================================================================
+   !!                       ***  MODULE  obs_surf_def  ***
+   !! Observation diagnostics: Storage handling for surface observation
+   !!                          arrays and additional flags etc.
+   !!                          This module only defines the data type and
+   !!                          operations on the data type. There is no
+   !!                          actual data in the module.
+   !!===================================================================== 
+
+   !!----------------------------------------------------------------------
+   !!   obs_surf            : F90 type containing the surface information
+   !!   obs_surf_alloc      : Allocates surface data arrays
+   !!   obs_surf_dealloc    : Deallocates surface data arrays
+   !!   obs_surf_compress   : Extract sub-information from a obs_surf type
+   !!                         to a new obs_surf type
+   !!   obs_surf_decompress : Reinsert sub-information from a obs_surf type
+   !!                         into the original obs_surf type
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_kind, ONLY : & ! Precision variables
+      & wp         
+   USE obs_mpp, ONLY : &  ! MPP tools 
+      obs_mpp_sum_integer
+
+   IMPLICIT NONE
+
+   !! * Routine/type accessibility
+   PRIVATE
+
+   PUBLIC &
+      & obs_surf,           &
+      & obs_surf_alloc,     &
+      & obs_surf_dealloc,   &
+      & obs_surf_compress,  &
+      & obs_surf_decompress
+
+   !! * Type definition for surface observation type
+
+   TYPE obs_surf
+
+      ! Bookkeeping
+
+      INTEGER :: nsurf      !: Local number of surface data within window
+      INTEGER :: nsurfmpp   !: Global number of surface data within window
+      INTEGER :: nvar       !: Number of variables at observation points
+      INTEGER :: nextra     !: Number of extra fields at observation points
+      INTEGER :: nstp       !: Number of time steps
+      INTEGER :: npi        !: Number of 3D grid points
+      INTEGER :: npj
+      INTEGER :: nsurfup    !: Observation counter used in obs_oper
+      INTEGER :: nrec       !: Number of surface observation records in window
+
+      ! Arrays with size equal to the number of surface observations
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & mi,   &        !: i-th grid coord. for interpolating to surface observation
+         & mj,   &        !: j-th grid coord. for interpolating to surface observation
+         & mt,   &        !: time record number for gridded data
+         & nsidx,&        !: Surface observation number
+         & nsfil,&        !: Surface observation number in file
+         & nyea, &        !: Year of surface observation
+         & nmon, &        !: Month of surface observation 
+         & nday, &        !: Day of surface observation
+         & nhou, &        !: Hour of surface observation
+         & nmin, &        !: Minute of surface observation
+         & mstp, &        !: Time step nearest to surface observation
+         & nqc,  &        !: Surface observation qc flag
+         & ntyp           !: Type of surface observation product
+
+      CHARACTER(len=8), POINTER, DIMENSION(:) :: &
+         & cvars          !: Variable names
+
+      CHARACTER(LEN=8), POINTER, DIMENSION(:) :: &
+         & cwmo           !: WMO indentifier
+         
+      REAL(KIND=wp), POINTER, DIMENSION(:) :: &
+         & rlam, &        !: Longitude coordinate of surface observation
+         & rphi           !: Latitude coordinate of surface observation
+
+      REAL(KIND=wp), POINTER, DIMENSION(:,:) :: &
+         & robs, &        !: Surface observation 
+         & rmod           !: Model counterpart of the surface observation vector
+
+      REAL(KIND=wp), POINTER, DIMENSION(:,:) :: &
+         & rext           !: Extra fields interpolated to observation points
+
+      REAL(KIND=wp), POINTER, DIMENSION(:,:) :: &
+         & vdmean         !: Time averaged of model field
+
+      ! Arrays with size equal to the number of time steps in the window
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & nsstp,     &   !: Local number of surface observations per time step
+         & nsstpmpp       !: Global number of surface observations per time step
+
+      ! Arrays with size equal to the number of observation records in the window
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & mrecstp   ! Time step of the records
+
+      ! Arrays used to store source indices when 
+      ! compressing obs_surf derived types
+      
+      ! Array with size nsurf
+
+      INTEGER, POINTER, DIMENSION(:) :: &
+         & nsind          !: Source indices of surface data in compressed data
+
+      ! Is this a gridded product?
+     
+      LOGICAL :: lgrid
+
+   END TYPE obs_surf
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+   
+   SUBROUTINE obs_surf_alloc( surf, ksurf, kvar, kextra, kstp, kpi, kpj )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_surf_alloc  ***
+      !!                      
+      !! ** Purpose : - Allocate data for surface data arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-03  (K. Mogensen, A. Weaver, E. Remy, S. Ricci) original
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) ::  surf      ! Surface data to be allocated
+      INTEGER, INTENT(IN) :: ksurf   ! Number of surface observations
+      INTEGER, INTENT(IN) :: kvar    ! Number of surface variables
+      INTEGER, INTENT(IN) :: kextra  ! Number of extra fields at observation points
+      INTEGER, INTENT(IN) :: kstp    ! Number of time steps
+      INTEGER, INTENT(IN) :: kpi     ! Number of 3D grid points
+      INTEGER, INTENT(IN) :: kpj
+
+      !!* Local variables
+      INTEGER :: ji
+      INTEGER :: jvar
+
+      ! Set bookkeeping variables
+
+      surf%nsurf    = ksurf
+      surf%nsurfmpp = 0
+      surf%nextra   = kextra
+      surf%nvar     = kvar
+      surf%nstp     = kstp
+      surf%npi      = kpi
+      surf%npj      = kpj
+
+      ! Allocate arrays of size number of variables
+
+      ALLOCATE( &
+         & surf%cvars(kvar)    &
+         & )
+
+      DO jvar = 1, kvar
+         surf%cvars(jvar) = "NotSet"
+      END DO
+      
+      ! Allocate arrays of number of surface data size
+
+      ALLOCATE( &
+         & surf%mi(ksurf),      &
+         & surf%mj(ksurf),      &
+         & surf%mt(ksurf),      &
+         & surf%nsidx(ksurf),   &
+         & surf%nsfil(ksurf),   &
+         & surf%nyea(ksurf),    &
+         & surf%nmon(ksurf),    &
+         & surf%nday(ksurf),    &
+         & surf%nhou(ksurf),    &
+         & surf%nmin(ksurf),    &
+         & surf%mstp(ksurf),    &
+         & surf%nqc(ksurf),     &
+         & surf%ntyp(ksurf),    &
+         & surf%cwmo(ksurf),    &
+         & surf%rlam(ksurf),    &
+         & surf%rphi(ksurf),    &
+         & surf%nsind(ksurf)    &
+         & )
+
+      surf%mt(:) = -1
+
+
+      ! Allocate arrays of number of surface data size * number of variables
+
+      ALLOCATE( & 
+         & surf%robs(ksurf,kvar), &
+         & surf%rmod(ksurf,kvar)  &
+         & )   
+
+      ! Allocate arrays of number of extra fields at observation points
+
+      ALLOCATE( & 
+         & surf%rext(ksurf,kextra) &
+         & )
+
+      surf%rext(:,:) = 0.0_wp 
+
+      ! Allocate arrays of number of time step size
+
+      ALLOCATE( &
+         & surf%nsstp(kstp),     &
+         & surf%nsstpmpp(kstp)   &
+         & )
+
+      ! Allocate arrays of size number of grid points
+
+      ALLOCATE( &
+         & surf%vdmean(kpi,kpj) &
+         & )
+
+      ! Set defaults for compression indices
+      
+      DO ji = 1, ksurf
+         surf%nsind(ji) = ji
+      END DO
+      
+      ! Set defaults for number of observations per time step
+
+      surf%nsstp(:)     = 0
+      surf%nsstpmpp(:)  = 0
+
+      ! Set the observation counter used in obs_oper
+
+      surf%nsurfup     = 0
+      
+      ! Not gridded by default
+          
+      surf%lgrid       = .FALSE.
+              
+   END SUBROUTINE obs_surf_alloc
+
+   SUBROUTINE obs_surf_dealloc( surf )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_surf_dealloc  ***
+      !!                      
+      !! ** Purpose : - Deallocate data for surface data arrays
+      !! 
+      !! ** Method  : - Fortran-90 dynamic arrays
+      !!
+      !! History :
+      !!        !  07-03  (K. Mogensen, A. Weaver, E. Remy, S. Ricci) original
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) :: &
+         & surf      ! Surface data to be allocated
+
+      !!* Local variables
+
+      ! Deallocate arrays of number of surface data size
+
+      DEALLOCATE( &
+         & surf%mi,      &
+         & surf%mj,      &
+         & surf%mt,      &
+         & surf%nsidx,   &
+         & surf%nsfil,   &
+         & surf%nyea,    &
+         & surf%nmon,    &
+         & surf%nday,    &
+         & surf%nhou,    &
+         & surf%nmin,    &
+         & surf%mstp,    &
+         & surf%nqc,     &
+         & surf%ntyp,    &
+         & surf%cwmo,    &
+         & surf%rlam,    &
+         & surf%rphi,    &
+         & surf%nsind    &
+         & )
+
+      ! Allocate arrays of number of surface data size * number of variables
+
+      DEALLOCATE( & 
+         & surf%robs,    &
+         & surf%rmod     &
+         & )
+
+      ! Deallocate arrays of number of extra fields at observation points
+
+      DEALLOCATE( & 
+         & surf%rext &
+         & )
+
+      ! Deallocate arrays of size number of grid points size times
+      ! number of variables
+
+      DEALLOCATE( &
+         & surf%vdmean &
+         & )
+
+      ! Deallocate arrays of number of time step size
+
+      DEALLOCATE( &
+         & surf%nsstp,     &
+         & surf%nsstpmpp   &
+         & )
+
+      ! Dellocate arrays of size number of variables
+
+      DEALLOCATE( &
+         & surf%cvars     &
+         & )
+
+   END SUBROUTINE obs_surf_dealloc
+
+   SUBROUTINE obs_surf_compress( surf, newsurf, lallocate, kumout, lvalid )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_surf_compress  ***
+      !!                      
+      !! ** Purpose : - Extract sub-information from a obs_surf type
+      !!                into a new obs_surf type
+      !! 
+      !! ** Method  : - The data is copied from surf to new surf.
+      !!                In the case of lvalid being present only the 
+      !!                selected data will be copied.
+      !!                If lallocate is true the data in the newsurf is 
+      !!                allocated either with the same number of elements
+      !!                as surf or with only the subset of elements defined
+      !!                by the optional selection.
+      !!
+      !! History :
+      !!        !  07-03  (K. Mogensen, A. Weaver, E. Remy, S. Ricci) original
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_surf), INTENT(IN)    :: surf      ! Original surface data
+      TYPE(obs_surf), INTENT(INOUT) :: newsurf   ! New surface data with a subset of the original data
+      LOGICAL :: lallocate     ! Allocate newsurf data
+      INTEGER,INTENT(IN) :: kumout        ! Fortran unit for messages
+      LOGICAL, OPTIONAL, INTENT(in), DIMENSION(:) :: &
+         & lvalid         ! Valid of surface observations
+      
+      !!* Local variables
+      INTEGER :: insurf
+      INTEGER :: ji
+      INTEGER :: jk
+      LOGICAL, DIMENSION(:), ALLOCATABLE :: llvalid
+
+      ! Count how many elements there should be in the new data structure
+
+      IF ( PRESENT(lvalid) ) THEN
+         insurf = 0
+         DO ji = 1, surf%nsurf
+            IF ( lvalid(ji) ) THEN
+               insurf = insurf + 1
+            ENDIF
+         END DO
+      ELSE
+         insurf = surf%nsurf
+      ENDIF
+
+      ! Optionally allocate data in the new data structure
+
+      IF ( lallocate ) THEN
+         CALL obs_surf_alloc( newsurf,  insurf, surf%nvar, &
+            & surf%nextra, surf%nstp, surf%npi, surf%npj )
+      ENDIF
+
+      ! Allocate temporary valid array to unify the code for both cases
+
+      ALLOCATE( llvalid(surf%nsurf) )
+      IF ( PRESENT(lvalid) ) THEN
+         llvalid(:)  = lvalid(:)
+      ELSE
+         llvalid(:)  = .TRUE.
+      ENDIF
+
+      ! Setup bookkeeping variables
+
+      insurf = 0
+
+      ! Loop over source surface data
+
+      DO ji = 1, surf%nsurf
+
+         IF ( llvalid(ji) ) THEN
+
+            ! Copy the header information
+
+            insurf = insurf + 1
+
+            newsurf%mi(insurf)    = surf%mi(ji)
+            newsurf%mj(insurf)    = surf%mj(ji)
+            newsurf%mt(insurf)    = surf%mt(ji)
+            newsurf%nsidx(insurf) = surf%nsidx(ji)
+            newsurf%nsfil(insurf) = surf%nsfil(ji)
+            newsurf%nyea(insurf)  = surf%nyea(ji)
+            newsurf%nmon(insurf)  = surf%nmon(ji)
+            newsurf%nday(insurf)  = surf%nday(ji)
+            newsurf%nhou(insurf)  = surf%nhou(ji)
+            newsurf%nmin(insurf)  = surf%nmin(ji)
+            newsurf%mstp(insurf)  = surf%mstp(ji)
+            newsurf%nqc(insurf)   = surf%nqc(ji)
+            newsurf%ntyp(insurf)  = surf%ntyp(ji)
+            newsurf%cwmo(insurf)  = surf%cwmo(ji)
+            newsurf%rlam(insurf)  = surf%rlam(ji)
+            newsurf%rphi(insurf)  = surf%rphi(ji)
+
+            DO jk = 1, surf%nvar
+
+               newsurf%robs(insurf,jk)  = surf%robs(ji,jk)
+               newsurf%rmod(insurf,jk)  = surf%rmod(ji,jk)
+               
+            END DO
+
+            DO jk = 1, surf%nextra
+
+               newsurf%rext(insurf,jk) = surf%rext(ji,jk)
+
+            END DO
+            
+            ! nsind is the index of the original surface data
+            
+            newsurf%nsind(insurf) = ji
+
+         ENDIF
+
+      END DO
+
+      ! Update MPP counters
+
+      newsurf%nsurf = insurf
+      CALL obs_mpp_sum_integer ( newsurf%nsurf, newsurf%nsurfmpp )
+
+      ! Set book keeping variables which do not depend on number of obs.
+
+      newsurf%nstp     = surf%nstp
+      newsurf%cvars(:) = surf%cvars(:)
+      
+      ! Set gridded stuff
+      
+      newsurf%mt(insurf)    = surf%mt(ji)
+ 
+      ! Deallocate temporary data
+
+      DEALLOCATE( llvalid )
+     
+   END SUBROUTINE obs_surf_compress
+
+   SUBROUTINE obs_surf_decompress( surf, oldsurf, ldeallocate, kumout )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE obs_surf_decompress  ***
+      !!                      
+      !! ** Purpose : - Copy back information to original surface data type
+      !!
+      !! ** Method  : - Reinsert updated information from a previous
+      !!                copied/compressed surface data type into the original
+      !!                surface data and optionally deallocate the surface
+      !!                data input
+      !! 
+      !! History :
+      !!        !  07-03  (K. Mogensen, A. Weaver, E. Remy, S. Ricci) original
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obs_surf),INTENT(INOUT) :: surf       ! Updated surface data
+      TYPE(obs_surf),INTENT(INOUT) :: oldsurf    ! Original surface data
+      LOGICAL :: ldeallocate ! Deallocate the updated data of insertion
+      INTEGER,INTENT(in) :: kumout      ! Output unit
+      
+      !!* Local variables
+      INTEGER :: ji
+      INTEGER :: jj
+      INTEGER :: jk
+
+      ! Copy data from surf to old surf
+
+      DO ji = 1, surf%nsurf
+
+         jj=surf%nsind(ji)
+
+         oldsurf%mi(jj)    = surf%mi(ji)
+         oldsurf%mj(jj)    = surf%mj(ji)
+         oldsurf%mt(jj)    = surf%mt(ji)
+         oldsurf%nsidx(jj) = surf%nsidx(ji)
+         oldsurf%nsfil(jj) = surf%nsfil(ji)
+         oldsurf%nyea(jj)  = surf%nyea(ji)
+         oldsurf%nmon(jj)  = surf%nmon(ji)
+         oldsurf%nday(jj)  = surf%nday(ji)
+         oldsurf%nhou(jj)  = surf%nhou(ji)
+         oldsurf%nmin(jj)  = surf%nmin(ji)
+         oldsurf%mstp(jj)  = surf%mstp(ji)
+         oldsurf%nqc(jj)   = surf%nqc(ji)
+         oldsurf%ntyp(jj)  = surf%ntyp(ji)
+         oldsurf%cwmo(jj)  = surf%cwmo(ji)
+         oldsurf%rlam(jj)  = surf%rlam(ji)
+         oldsurf%rphi(jj)  = surf%rphi(ji)
+
+      END DO
+
+      DO jk = 1, surf%nvar
+
+         DO ji = 1, surf%nsurf
+            
+            jj=surf%nsind(ji)
+
+            oldsurf%robs(jj,jk)  = surf%robs(ji,jk)
+            oldsurf%rmod(jj,jk)  = surf%rmod(ji,jk)
+
+         END DO
+
+      END DO
+
+      DO jk = 1, surf%nextra
+
+         DO ji = 1, surf%nsurf
+            
+            jj=surf%nsind(ji)
+
+            oldsurf%rext(jj,jk)  = surf%rext(ji,jk)
+
+         END DO
+
+      END DO
+
+      ! Optionally deallocate the updated surface data
+
+      IF ( ldeallocate ) CALL obs_surf_dealloc( surf )
+      
+   END SUBROUTINE obs_surf_decompress
+   
+END MODULE obs_surf_def
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_types.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_types.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_types.F90	(revision 14097)
@@ -0,0 +1,267 @@
+MODULE obs_types
+   !!=====================================================================
+   !!                       ***  MODULE  obs_types  ***
+   !! Observation diagnostics: Observation type integer to character 
+   !!                          translation
+   !!=====================================================================
+
+   !!---------------------------------------------------------------------
+   !! 
+   !!   The NetCDF variable CWMO_INST_TYP_COR is used to identify the 
+   !!   different instrument types for coriolis data.
+   !!
+   !!    WMO  NEMOVAR  TYPE                   DESCRIPTION
+   !!    ---  -------  ----   --------------------------------------------
+   !!    800     0     MBT    (1941-) mechanical bathythermograph data
+   !!    401     1     XBT    (1967-) expendable bathythermograph data
+   !!    830     2     CTD    (1967-) high resolution CTD data
+   !!    820     3     MRB    (1990-) moored buoy data
+   !!    831     4     PFL    (1994-) profiling float data
+   !!    995     5     DRB    (1998-) drifting buoy data
+   !!    997     6     APB    (1997-) autonomous pinniped bathythermograph
+   !!    996     7     UOR    (1992-) undulating oceanographic recorder
+   !!    741     8     OSD    (1800-) low resolution (bottle) CTD data
+  !!
+   !! History :
+   !!        !  06-03  (K. Mogensen) Original code
+   !!        !  06-10  (A. Weaver) Cleanup
+   !!---------------------------------------------------------------------
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE 
+
+   !! * Shared Module variables
+
+   INTEGER, PUBLIC, PARAMETER :: ntyp1770 = 1023
+!RBbug useless ?   CHARACTER(LEN=4), PUBLIC, DIMENSION(0:ntyp1770) :: cwmotyp1770
+   CHARACTER(LEN=80), PUBLIC, DIMENSION(0:ntyp1770) :: cwmonam1770
+   CHARACTER(LEN=3), PUBLIC, DIMENSION(0:ntyp1770) :: ctypshort
+
+   INTEGER, PUBLIC, PARAMETER :: ntypalt = 8
+   CHARACTER(LEN=40), PUBLIC, DIMENSION(0:ntypalt) :: calttyp
+
+   PUBLIC obs_typ_init
+   PUBLIC obs_wmo_init
+   PUBLIC obs_alt_typ_init
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS 
+   
+   SUBROUTINE obs_typ_init
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_wmo_init ***
+      !!
+      !! ** Purpose : Initialize code tables
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  : 
+      !!
+      !! References : 
+      !!
+      !! History :  
+      !!      ! :  2007-06 (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      
+      !! * Arguments
+
+      !! * Local declarations
+
+      CALL obs_wmo_init
+
+      CALL obs_alt_typ_init
+
+   END SUBROUTINE obs_typ_init
+
+   SUBROUTINE obs_wmo_init
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_wmo_init ***
+      !!
+      !! ** Purpose : Initialize WMO code 1770 code tables
+      !!
+      !! ** Method  : Direct initialisation of variables
+      !!
+      !! ** Action  : 
+      !!
+      !! References : WORLD  METEOROLOGICAL  ORGANIZATION
+      !!              Manual on Codes
+      !!              International Codes
+      !!              VOLUME I.1 (Annex II to WMO Technical Regulations)
+      !!              Part A -- Alphanumeric Codes
+      !!              1995 edition
+      !!              WMO-No. 306 
+      !!              Secretariat of the World Meteorological Organization 
+      !!              Geneva, Switzerland
+      !!
+      !! History :  
+      !!      ! :  2007-04 (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      
+      !! * Arguments
+
+      !! * Local declarations
+      INTEGER :: ji
+
+      DO ji = 0, ntyp1770
+
+         cwmonam1770(ji) = 'Not defined'
+         ctypshort(ji) = '---'
+
+!         IF ( ji < 1000 ) THEN
+!            WRITE(cwmotyp1770(ji),'(1X,I3.3)') ji
+!         ELSE
+!            WRITE(cwmotyp1770(ji),'(I4.4)') ji
+!         ENDIF
+
+      END DO
+
+      cwmonam1770(   1) = 'Sippican T-4'
+      cwmonam1770(   2) = 'Sippican T-4'
+      cwmonam1770(  11) = 'Sippican T-5'
+      cwmonam1770(  21) = 'Sippican Fast Deep'
+      cwmonam1770(  31) = 'Sippican T-6'
+      cwmonam1770(  32) = 'Sippican T-6'
+      cwmonam1770(  41) = 'Sippican T-7'
+      cwmonam1770(  42) = 'Sippican T-7'
+      cwmonam1770(  51) = 'Sippican Deep Blue'
+      cwmonam1770(  52) = 'Sippican Deep Blue'
+      cwmonam1770(  61) = 'Sippican T-10'
+      cwmonam1770(  71) = 'Sippican T-11'
+      cwmonam1770( 201) = 'TSK T-4'
+      cwmonam1770( 202) = 'TSK T-4'
+      cwmonam1770( 211) = 'TSK T-6'
+      cwmonam1770( 212) = 'TSK T-6'
+      cwmonam1770( 221) = 'TSK T-7'
+      cwmonam1770( 222) = 'TSK T-7'
+      cwmonam1770( 231) = 'TSK T-5'
+      cwmonam1770( 241) = 'TSK T-10'
+      cwmonam1770( 251) = 'TSK Deep Blue'
+      cwmonam1770( 252) = 'TSK Deep Blue'
+      cwmonam1770( 261) = 'TSK AXBT '
+      cwmonam1770( 401) = 'Sparton XBT-1'
+      cwmonam1770( 411) = 'Sparton XBT-3'
+      cwmonam1770( 421) = 'Sparton XBT-4'
+      cwmonam1770( 431) = 'Sparton XBT-5'
+      cwmonam1770( 441) = 'Sparton XBT-5DB'
+      cwmonam1770( 451) = 'Sparton XBT-6'
+      cwmonam1770( 461) = 'Sparton XBT-7'
+      cwmonam1770( 462) = 'Sparton XBT-7'
+      cwmonam1770( 471) = 'Sparton XBT-7DB'
+      cwmonam1770( 481) = 'Sparton XBT-10'
+      cwmonam1770( 491) = 'Sparton XBT-20'
+      cwmonam1770( 501) = 'Sparton XBT-20DB'
+      cwmonam1770( 510) = 'Sparton 536 AXBT'
+      cwmonam1770( 700) = 'Sippican XCTD standard'
+      cwmonam1770( 710) = 'Sippican XCTD deep'
+      cwmonam1770( 720) = 'Sippican AXCTD'
+      cwmonam1770( 730) = 'Sippican SXCTD'
+      cwmonam1770( 741) = 'TSK XCTD'
+      cwmonam1770( 742) = 'TSK XCTD-2 '
+      cwmonam1770( 743) = 'TSK XCTD-2F '
+      cwmonam1770( 751) = 'TSK AXCTD '
+      cwmonam1770( 800) = 'Mechanical BT'
+      cwmonam1770( 810) = 'Hydrocast'
+      cwmonam1770( 820) = 'Thermistor Chain'
+      cwmonam1770( 825) = 'Temperature (sonic) and pressure probes'
+      cwmonam1770( 830) = 'CTD'
+      cwmonam1770( 831) = 'CTD-P-ALACE float'
+      cwmonam1770( 840) = 'PROVOR, No conductivity sensor '
+      cwmonam1770( 841) = 'PROVOR, Seabird conductivity sensor '
+      cwmonam1770( 842) = 'PROVOR, FSI conductivity sensor '
+      cwmonam1770( 845) = 'Web Research, No conductivity sensor '
+      cwmonam1770( 846) = 'Web Research, Seabird conductivity sensor '
+      cwmonam1770( 847) = 'Web Research. FSI conductivity sensor'
+      cwmonam1770( 850) = 'SOLO, No conductivity sensor '
+      cwmonam1770( 851) = 'SOLO, Seabird conductivity sensor '
+      cwmonam1770( 852) = 'SOLO, FSI conductivity sensor'
+      cwmonam1770( 855) = 'Profiling float, NINJA, no conductivity sensor'
+      cwmonam1770( 856) = 'Profiling float, NINJA, SBE conductivity sensor'
+      cwmonam1770( 857) = 'Profiling float, NINJA, FSI conductivity sensor'
+      cwmonam1770( 858) = 'Profiling float, NINJA, TSK conductivity sensor'
+      cwmonam1770( 900) = 'Sippican T-12 XBT'
+      cwmonam1770(1023) = 'Missing value'
+
+      DO ji = 853, 854
+         cwmonam1770(ji) = 'Reserved'
+      END DO
+
+      DO ji = 859, 899
+         cwmonam1770(ji) = 'Reserved'
+      END DO
+
+      DO ji = 901, 999
+         cwmonam1770(ji) = 'Reserved'
+      END DO
+
+      DO ji = 1000, 1022
+         cwmonam1770(ji) = 'Reserved'
+      END DO
+
+      ctypshort(800) = 'MBT'
+      ctypshort(401) = 'XBT'
+      ctypshort(830) = 'CTD'
+      ctypshort(820) = 'MRB'
+      ctypshort(831) = 'PFL'
+      ctypshort(995) = 'DRB'
+      ctypshort(997) = 'APB'
+      ctypshort(996) = 'UOR'
+      ctypshort(700:799) = 'OSD'
+
+   END SUBROUTINE obs_wmo_init
+
+   SUBROUTINE obs_alt_typ_init
+      !!---------------------------------------------------------------------
+      !!
+      !!                   *** ROUTINE obs_alt_typ_init ***
+      !!
+      !! ** Purpose : Initialize CLS altimeter code tables
+      !!
+      !! ** Method  : Direct initialisation of variables
+      !!
+      !! ** Action  : 
+      !!
+      !! References : CLS
+      !1              SSALTO/DUACS User Handbook
+      !!              (M)SLA and (M)ADT Near-Real Time and
+      !!              Delayed time products
+      !!              CLS-DOS-NT-06-034
+      !!              2006
+      !!              CLS
+      !!              8-10 Rue Hermes
+      !!              Parc Technologique du Canal
+      !!              31526 Ramonville St-Agne
+      !!              France
+      !!
+      !! History :  
+      !!      ! :  2007-06 (K. Mogensen) Original code
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      
+      !! * Arguments
+
+      !! * Local declarations
+
+      calttyp(0) = 'Unknown'
+      calttyp(1) = 'ERS-1'
+      calttyp(2) = 'ERS-2'
+      calttyp(3) = 'Topex/Poseidon'
+      calttyp(4) = 'Topex/Poseidon on its new orbit'
+      calttyp(5) = 'GFO'
+      calttyp(6) = 'Jason-1'
+      calttyp(7) = 'Envisat'
+      calttyp(8) = 'Jason-2'
+
+   END SUBROUTINE obs_alt_typ_init
+
+END MODULE obs_types
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_utils.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_utils.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_utils.F90	(revision 14097)
@@ -0,0 +1,213 @@
+MODULE obs_utils
+   !!======================================================================
+   !!                       ***  MODULE obs_utils   ***
+   !! Observation diagnostics: Utility functions
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   grt_cir_dis     : Great circle distance 
+   !!   grt_cir_dis_saa : Great circle distance (small angle)
+   !!   chkerr          : Error-message managment for NetCDF files
+   !!   chkdim          : Error-message managment for NetCDF files
+   !!   fatal_error     : Fatal error handling
+   !!   ddatetoymdhms   : Convert YYYYMMDD.hhmmss to components
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_oce, ONLY : &        ! Precision variables
+      & wp, &
+      & dp, &
+      & i8  
+   USE in_out_manager           ! I/O manager
+   USE lib_mpp                  ! For ctl_warn/stop
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+   PUBLIC grt_cir_dis,     &  ! Great circle distance 
+      &   grt_cir_dis_saa, &  ! Great circle distance (small angle)
+      &   str_c_to_for,    &  ! Remove non-printable chars from string
+      &   chkerr,          &  ! Error-message managment for NetCDF files
+      &   chkdim,          &  ! Check if dimensions are correct for a variable
+      &   fatal_error,     &  ! Fatal error handling
+      &   warning,         &  ! Warning handling
+      &   ddatetoymdhms       ! Convert YYYYMMDD.hhmmss to components
+         
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+ 
+#include "grt_cir_dis.h90"
+
+#include "grt_cir_dis_saa.h90"
+
+#include "str_c_to_for.h90"
+
+   SUBROUTINE chkerr( kstatus, cd_name, klineno )
+      !!----------------------------------------------------------------------
+      !!   
+      !!                    *** ROUTINE chkerr ***
+      !! 
+      !! ** Purpose : Error-message managment for NetCDF files.
+      !! 
+      !! ** Method  : 
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!      ! 02-12  (N. Daget)  hdlerr
+      !!      ! 06-04  (A. Vidard) f90/nemovar migration, change name
+      !!      ! 06-10  (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE netcdf             ! NetCDF library
+      USE dom_oce, ONLY : &  ! Ocean space and time domain variables
+         & nproc
+
+      !! * Arguments
+      INTEGER :: kstatus
+      INTEGER :: klineno
+      CHARACTER(LEN=*) :: cd_name
+      
+      !! * Local declarations
+      CHARACTER(len=200) :: clineno
+
+      ! Main computation
+      IF ( kstatus /= nf90_noerr ) THEN
+         WRITE(clineno,'(A,I8)')' at line number ', klineno
+         CALL ctl_stop( ' chkerr', ' Netcdf Error in ' // TRIM( cd_name ), &
+            &           clineno, nf90_strerror( kstatus ) )
+      ENDIF
+
+   END SUBROUTINE chkerr
+
+   SUBROUTINE chkdim( kfileid, kvarid, kndim, kdim, cd_name, klineno )
+      !!----------------------------------------------------------------------
+      !!   
+      !!                    *** ROUTINE chkerr ***
+      !! 
+      !! ** Purpose : Error-message managment for NetCDF files.
+      !! 
+      !! ** Method  : 
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!      ! 07-03  (K. Mogenen + E. Remy) Initial version
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      USE netcdf             ! NetCDF library
+      USE dom_oce, ONLY : &  ! Ocean space and time domain variables
+         & nproc
+
+      !! * Arguments
+      INTEGER :: kfileid       ! NetCDF file id   
+      INTEGER :: kvarid        ! NetCDF variable id   
+      INTEGER :: kndim         ! Expected number of dimensions
+      INTEGER, DIMENSION(kndim) :: kdim      ! Expected dimensions
+      CHARACTER(LEN=*) :: cd_name            ! Calling routine name
+      INTEGER ::  klineno      ! Calling line number
+
+      !! * Local declarations
+      INTEGER :: indim
+      INTEGER, ALLOCATABLE, DIMENSION(:) :: &
+         & idim,ilendim
+      INTEGER :: ji
+      LOGICAL :: llerr
+      CHARACTER(len=200) :: clineno
+
+      CALL chkerr( nf90_inquire_variable( kfileid, kvarid, ndims=indim ), &
+         &         cd_name, klineno )
+
+      ALLOCATE(idim(indim),ilendim(indim))
+
+      CALL chkerr( nf90_inquire_variable( kfileid, kvarid, dimids=idim ), &
+         &         cd_name, klineno )
+
+      DO ji = 1, indim
+         CALL chkerr( nf90_inquire_dimension( kfileid, idim(ji), &
+            &                                 len=ilendim(ji) ), &
+            &         cd_name, klineno )
+      END DO
+      
+      IF ( indim /= kndim ) THEN
+         WRITE(clineno,'(A,I8)')' at line number ', klineno
+         CALL ctl_stop( ' chkdim',  &
+            &           ' Netcdf no dim error in ' // TRIM( cd_name ), &
+            &           clineno )
+      ENDIF
+
+      DO ji = 1, indim
+         IF ( ilendim(ji) /= kdim(ji) ) THEN
+            WRITE(clineno,'(A,I8)')' at line number ', klineno
+            CALL ctl_stop( ' chkdim',  &
+               &           ' Netcdf dim len error in ' // TRIM( cd_name ), &
+               &           clineno )
+         ENDIF
+      END DO
+         
+      DEALLOCATE(idim,ilendim)
+
+   END SUBROUTINE chkdim
+   
+  SUBROUTINE fatal_error( cd_name, klineno )
+      !!----------------------------------------------------------------------
+      !!
+      !!                    *** ROUTINE fatal_error ***
+      !!
+      !! ** Purpose : Fatal error handling
+      !!
+      !! ** Method  :
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!----------------------------------------------------------------------
+      !! * Modules used
+
+      !! * Arguments
+      INTEGER :: klineno
+      CHARACTER(LEN=*) :: cd_name
+      !! * Local declarations
+      CHARACTER(len=200) :: clineno
+
+      WRITE(clineno,'(A,I8)')' at line number ', klineno
+      CALL ctl_stop( ' fatal_error', ' Error in ' // TRIM( cd_name ), &
+         &           clineno)
+      
+   END SUBROUTINE fatal_error
+
+   SUBROUTINE warning( cd_name, klineno )
+      !!----------------------------------------------------------------------
+      !!
+      !!                    *** ROUTINE warning ***
+      !!
+      !! ** Purpose : Warning handling
+      !!
+      !! ** Method  :
+      !!
+      !! ** Action  :
+      !!
+      !! History
+      !!----------------------------------------------------------------------
+      !! * Modules used
+
+      !! * Arguments
+      INTEGER :: klineno
+      CHARACTER(LEN=*) :: cd_name
+      !! * Local declarations
+      CHARACTER(len=200) :: clineno
+
+      WRITE(clineno,'(A,I8)')' at line number ', klineno
+      CALL ctl_warn( ' warning', ' Potential problem in ' // TRIM( cd_name ), &
+         &           clineno)
+      
+   END SUBROUTINE warning
+
+#include "ddatetoymdhms.h90"
+
+END MODULE obs_utils
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_write.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_write.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obs_write.F90	(revision 14097)
@@ -0,0 +1,608 @@
+MODULE obs_write
+   !!======================================================================
+   !!                       ***  MODULE obs_write   ***
+   !! Observation diagnosticss: Write observation related diagnostics
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   obs_wri_prof   : Write profile observations in feedback format
+   !!   obs_wri_surf   : Write surface observations in feedback format
+   !!   obs_wri_stats  : Print basic statistics on the data being written out
+   !!----------------------------------------------------------------------
+
+   !! * Modules used
+   USE par_kind, ONLY : &   ! Precision variables
+      & wp
+   USE in_out_manager       ! I/O manager
+   USE dom_oce              ! Ocean space and time domain variables
+   USE obs_types            ! Observation type integer to character translation
+   USE julian, ONLY : &         ! Julian date routines
+      & greg2jul
+   USE obs_utils, ONLY : &  ! Observation operator utility functions
+      & chkerr
+   USE obs_profiles_def     ! Type definitions for profiles
+   USE obs_surf_def         ! Type defintions for surface observations
+   USE obs_fbm              ! Observation feedback I/O
+   USE obs_grid             ! Grid tools
+   USE obs_conv             ! Conversion between units
+   USE obs_const
+   USE obs_mpp              ! MPP support routines for observation diagnostics
+   USE lib_mpp		    ! MPP routines
+
+   IMPLICIT NONE
+
+   !! * Routine accessibility
+   PRIVATE
+   PUBLIC obs_wri_prof, &    ! Write profile observation files
+      &   obs_wri_surf, &    ! Write surface observation files
+      &   obswriinfo
+   
+   TYPE obswriinfo
+      INTEGER :: inum
+      INTEGER, POINTER, DIMENSION(:) :: ipoint
+      CHARACTER(len=ilenname), POINTER, DIMENSION(:) :: cdname
+      CHARACTER(len=ilenlong), POINTER, DIMENSION(:,:) :: cdlong
+      CHARACTER(len=ilenunit), POINTER, DIMENSION(:,:) :: cdunit
+   END TYPE obswriinfo
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE obs_wri_prof( profdata, padd, pext )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     *** ROUTINE obs_wri_prof  ***
+      !!
+      !! ** Purpose : Write profile feedback files
+      !!
+      !! ** Method  : NetCDF
+      !! 
+      !! ** Action  :
+      !!
+      !! History :
+      !!      ! 06-04  (A. Vidard) Original
+      !!      ! 06-04  (A. Vidard) Reformatted
+      !!      ! 06-10  (A. Weaver) Cleanup
+      !!      ! 07-01  (K. Mogensen) Use profile data types
+      !!      ! 07-03  (K. Mogensen) General handling of profiles
+      !!      ! 09-01  (K. Mogensen) New feedback format
+      !!      ! 15-02  (M. Martin) Combined routine for writing profiles
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      TYPE(obs_prof), INTENT(INOUT) :: profdata      ! Full set of profile data
+      TYPE(obswriinfo), OPTIONAL :: padd             ! Additional info for each variable
+      TYPE(obswriinfo), OPTIONAL :: pext             ! Extra info
+
+      !! * Local declarations
+      TYPE(obfbdata) :: fbdata
+      CHARACTER(LEN=40) :: clfname
+      CHARACTER(LEN=10) :: clfiletype
+      INTEGER :: ilevel
+      INTEGER :: jvar
+      INTEGER :: jo
+      INTEGER :: jk
+      INTEGER :: ik
+      INTEGER :: ja
+      INTEGER :: je
+      INTEGER :: iadd
+      INTEGER :: iext
+      REAL(wp) :: zpres
+
+      IF ( PRESENT( padd ) ) THEN
+         iadd = padd%inum
+      ELSE
+         iadd = 0
+      ENDIF
+
+      IF ( PRESENT( pext ) ) THEN
+         iext = pext%inum
+      ELSE
+         iext = 0
+      ENDIF
+
+      CALL init_obfbdata( fbdata )
+
+      ! Find maximum level
+      ilevel = 0
+      DO jvar = 1, 2
+         ilevel = MAX( ilevel, MAXVAL( profdata%var(jvar)%nvlidx(:) ) )
+      END DO
+
+      SELECT CASE ( TRIM(profdata%cvars(1)) )
+      CASE('POTM')
+
+         clfiletype='profb'
+         CALL alloc_obfbdata( fbdata, 2, profdata%nprof, ilevel, &
+            &                 1 + iadd, 1 + iext, .TRUE. )
+         fbdata%cname(1)      = profdata%cvars(1)
+         fbdata%cname(2)      = profdata%cvars(2)
+         fbdata%coblong(1)    = 'Potential temperature'
+         fbdata%coblong(2)    = 'Practical salinity'
+         fbdata%cobunit(1)    = 'Degrees centigrade'
+         fbdata%cobunit(2)    = 'PSU'
+         fbdata%cextname(1)   = 'TEMP'
+         fbdata%cextlong(1)   = 'Insitu temperature'
+         fbdata%cextunit(1)   = 'Degrees centigrade'
+         fbdata%caddlong(1,1) = 'Model interpolated potential temperature'
+         fbdata%caddlong(1,2) = 'Model interpolated practical salinity'
+         fbdata%caddunit(1,1) = 'Degrees centigrade'
+         fbdata%caddunit(1,2) = 'PSU'
+         fbdata%cgrid(:)      = 'T'
+         DO je = 1, iext
+            fbdata%cextname(1+je) = pext%cdname(je)
+            fbdata%cextlong(1+je) = pext%cdlong(je,1)
+            fbdata%cextunit(1+je) = pext%cdunit(je,1)
+         END DO
+         DO ja = 1, iadd
+            fbdata%caddname(1+ja) = padd%cdname(ja)
+            DO jvar = 1, 2
+               fbdata%caddlong(1+ja,jvar) = padd%cdlong(ja,jvar)
+               fbdata%caddunit(1+ja,jvar) = padd%cdunit(ja,jvar)
+            END DO
+         END DO
+
+      CASE('UVEL')
+
+         clfiletype='velfb'
+         CALL alloc_obfbdata( fbdata, 2, profdata%nprof, ilevel, 1, 0, .TRUE. )
+         fbdata%cname(1)      = profdata%cvars(1)
+         fbdata%cname(2)      = profdata%cvars(2)
+         fbdata%coblong(1)    = 'Zonal velocity'
+         fbdata%coblong(2)    = 'Meridional velocity'
+         fbdata%cobunit(1)    = 'm/s'
+         fbdata%cobunit(2)    = 'm/s'
+         DO je = 1, iext
+            fbdata%cextname(je) = pext%cdname(je)
+            fbdata%cextlong(je) = pext%cdlong(je,1)
+            fbdata%cextunit(je) = pext%cdunit(je,1)
+         END DO
+         fbdata%caddlong(1,1) = 'Model interpolated zonal velocity'
+         fbdata%caddlong(1,2) = 'Model interpolated meridional velocity'
+         fbdata%caddunit(1,1) = 'm/s'
+         fbdata%caddunit(1,2) = 'm/s'
+         fbdata%cgrid(1)      = 'U' 
+         fbdata%cgrid(2)      = 'V'
+         DO ja = 1, iadd
+            fbdata%caddname(1+ja) = padd%cdname(ja)
+            fbdata%caddlong(1+ja,1) = padd%cdlong(ja,1)
+            fbdata%caddunit(1+ja,1) = padd%cdunit(ja,1)
+         END DO
+
+      END SELECT
+
+      fbdata%caddname(1)   = 'Hx'
+
+      WRITE(clfname, FMT="(A,'_fdbk_',I4.4,'.nc')") TRIM(clfiletype), nproc
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'obs_wri_prof :'
+         WRITE(numout,*)'~~~~~~~~~~~~~'
+         WRITE(numout,*)'Writing '//TRIM(clfiletype)//' feedback file : ',TRIM(clfname)
+      ENDIF
+
+      ! Transform obs_prof data structure into obfb data structure
+      fbdata%cdjuldref = '19500101000000'
+      DO jo = 1, profdata%nprof
+         fbdata%plam(jo)      = profdata%rlam(jo)
+         fbdata%pphi(jo)      = profdata%rphi(jo)
+         WRITE(fbdata%cdtyp(jo),'(I4)') profdata%ntyp(jo)
+         fbdata%ivqc(jo,:)    = profdata%ivqc(jo,:)
+         fbdata%ivqcf(:,jo,:) = profdata%ivqcf(:,jo,:)
+         IF ( profdata%nqc(jo) > 255 ) THEN
+            fbdata%ioqc(jo)    = IBSET(profdata%nqc(jo),2)
+            fbdata%ioqcf(1,jo) = profdata%nqcf(1,jo)
+            fbdata%ioqcf(2,jo) = profdata%nqc(jo)
+         ELSE
+            fbdata%ioqc(jo)    = profdata%nqc(jo)
+            fbdata%ioqcf(:,jo) = profdata%nqcf(:,jo)
+         ENDIF
+         fbdata%ipqc(jo)      = profdata%ipqc(jo)
+         fbdata%ipqcf(:,jo)   = profdata%ipqcf(:,jo)
+         fbdata%itqc(jo)      = profdata%itqc(jo)
+         fbdata%itqcf(:,jo)   = profdata%itqcf(:,jo)
+         fbdata%cdwmo(jo)     = profdata%cwmo(jo)
+         fbdata%kindex(jo)    = profdata%npfil(jo)
+         DO jvar = 1, profdata%nvar
+            IF (ln_grid_global) THEN
+               fbdata%iobsi(jo,jvar) = profdata%mi(jo,jvar)
+               fbdata%iobsj(jo,jvar) = profdata%mj(jo,jvar)
+            ELSE
+               fbdata%iobsi(jo,jvar) = mig(profdata%mi(jo,jvar))
+               fbdata%iobsj(jo,jvar) = mjg(profdata%mj(jo,jvar))
+            ENDIF
+         END DO
+         CALL greg2jul( 0, &
+            &           profdata%nmin(jo), &
+            &           profdata%nhou(jo), &
+            &           profdata%nday(jo), &
+            &           profdata%nmon(jo), &
+            &           profdata%nyea(jo), &
+            &           fbdata%ptim(jo),   &
+            &           krefdate = 19500101 )
+         ! Reform the profiles arrays for output
+         DO jvar = 1, 2
+            DO jk = profdata%npvsta(jo,jvar), profdata%npvend(jo,jvar)
+               ik = profdata%var(jvar)%nvlidx(jk)
+               fbdata%padd(ik,jo,1,jvar) = profdata%var(jvar)%vmod(jk)
+               fbdata%pob(ik,jo,jvar)    = profdata%var(jvar)%vobs(jk)
+               fbdata%pdep(ik,jo)        = profdata%var(jvar)%vdep(jk)
+               fbdata%idqc(ik,jo)        = profdata%var(jvar)%idqc(jk)
+               fbdata%idqcf(:,ik,jo)     = profdata%var(jvar)%idqcf(:,jk)
+               IF ( profdata%var(jvar)%nvqc(jk) > 255 ) THEN
+                  fbdata%ivlqc(ik,jo,jvar) = IBSET(profdata%var(jvar)%nvqc(jk),2)
+                  fbdata%ivlqcf(1,ik,jo,jvar) = profdata%var(jvar)%nvqcf(1,jk)
+!$AGRIF_DO_NOT_TREAT
+                  fbdata%ivlqcf(2,ik,jo,jvar) = IAND(profdata%var(jvar)%nvqc(jk),b'0000000011111111')
+!$AGRIF_END_DO_NOT_TREAT
+               ELSE
+                  fbdata%ivlqc(ik,jo,jvar) = profdata%var(jvar)%nvqc(jk)
+                  fbdata%ivlqcf(:,ik,jo,jvar) = profdata%var(jvar)%nvqcf(:,jk)
+               ENDIF
+               fbdata%iobsk(ik,jo,jvar)  = profdata%var(jvar)%mvk(jk)
+               DO ja = 1, iadd
+                  fbdata%padd(ik,jo,1+ja,jvar) = &
+                     & profdata%var(jvar)%vext(jk,padd%ipoint(ja))
+               END DO
+               DO je = 1, iext
+                  fbdata%pext(ik,jo,1+je) = &
+                     & profdata%var(jvar)%vext(jk,pext%ipoint(je))
+               END DO
+               IF ( ( jvar == 1 ) .AND. &
+                  & ( TRIM(profdata%cvars(1)) == 'POTM' ) ) THEN
+                  fbdata%pext(ik,jo,1) = profdata%var(jvar)%vext(jk,1)
+               ENDIF 
+            END DO
+         END DO
+      END DO
+
+      IF ( TRIM(profdata%cvars(1)) == 'POTM' ) THEN
+         ! Convert insitu temperature to potential temperature using the model
+         ! salinity if no potential temperature
+         DO jo = 1, fbdata%nobs
+            IF ( fbdata%pphi(jo) < 9999.0 ) THEN
+               DO jk = 1, fbdata%nlev
+                  IF ( ( fbdata%pob(jk,jo,1) >= 9999.0 ) .AND. &
+                     & ( fbdata%pdep(jk,jo) < 9999.0 ) .AND. &
+                     & ( fbdata%padd(jk,jo,1,2) < 9999.0 ) .AND. &
+                     & ( fbdata%pext(jk,jo,1) < 9999.0 ) ) THEN
+                     zpres = dep_to_p( REAL(fbdata%pdep(jk,jo),wp), &
+                        &              REAL(fbdata%pphi(jo),wp) )
+                     fbdata%pob(jk,jo,1) = potemp( &
+                        &                     REAL(fbdata%padd(jk,jo,1,2), wp),  &
+                        &                     REAL(fbdata%pext(jk,jo,1), wp), &
+                        &                     zpres, 0.0_wp )
+                  ENDIF
+               END DO
+            ENDIF
+         END DO
+      ENDIF
+
+      ! Write the obfbdata structure
+      CALL write_obfbdata( clfname, fbdata )
+
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
+      CALL dealloc_obfbdata( fbdata )
+
+   END SUBROUTINE obs_wri_prof
+
+   SUBROUTINE obs_wri_surf( surfdata, padd, pext )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     *** ROUTINE obs_wri_surf  ***
+      !!
+      !! ** Purpose : Write surface observation files
+      !!
+      !! ** Method  : NetCDF
+      !! 
+      !! ** Action  :
+      !!
+      !!      ! 07-03  (K. Mogensen) Original
+      !!      ! 09-01  (K. Mogensen) New feedback format.
+      !!      ! 15-02  (M. Martin) Combined surface writing routine.
+      !!-----------------------------------------------------------------------
+
+      !! * Modules used
+      IMPLICIT NONE
+
+      !! * Arguments
+      TYPE(obs_surf), INTENT(INOUT) :: surfdata         ! Full set of surface data
+      TYPE(obswriinfo), OPTIONAL :: padd               ! Additional info for each variable
+      TYPE(obswriinfo), OPTIONAL :: pext               ! Extra info
+
+      !! * Local declarations
+      TYPE(obfbdata) :: fbdata
+      CHARACTER(LEN=40) :: clfname         ! netCDF filename
+      CHARACTER(LEN=10) :: clfiletype
+      CHARACTER(LEN=12), PARAMETER :: cpname = 'obs_wri_surf'
+      INTEGER :: jo
+      INTEGER :: ja
+      INTEGER :: je
+      INTEGER :: iadd
+      INTEGER :: iext
+
+      IF ( PRESENT( padd ) ) THEN
+         iadd = padd%inum
+      ELSE
+         iadd = 0
+      ENDIF
+
+      IF ( PRESENT( pext ) ) THEN
+         iext = pext%inum
+      ELSE
+         iext = 0
+      ENDIF
+
+      CALL init_obfbdata( fbdata )
+
+      SELECT CASE ( TRIM(surfdata%cvars(1)) )
+      CASE('SLA')
+
+         CALL alloc_obfbdata( fbdata, 1, surfdata%nsurf, 1, &
+            &                 2 + iadd, 1 + iext, .TRUE. )
+
+         clfiletype = 'slafb'
+         fbdata%cname(1)      = surfdata%cvars(1)
+         fbdata%coblong(1)    = 'Sea level anomaly'
+         fbdata%cobunit(1)    = 'Metres'
+         fbdata%cextname(1)   = 'MDT'
+         fbdata%cextlong(1)   = 'Mean dynamic topography'
+         fbdata%cextunit(1)   = 'Metres'
+         DO je = 1, iext
+            fbdata%cextname(je) = pext%cdname(je)
+            fbdata%cextlong(je) = pext%cdlong(je,1)
+            fbdata%cextunit(je) = pext%cdunit(je,1)
+         END DO
+         fbdata%caddlong(1,1) = 'Model interpolated SSH - MDT'
+         fbdata%caddunit(1,1) = 'Metres' 
+         fbdata%caddname(2)   = 'SSH'
+         fbdata%caddlong(2,1) = 'Model Sea surface height'
+         fbdata%caddunit(2,1) = 'Metres'
+         fbdata%cgrid(1)      = 'T'
+         DO ja = 1, iadd
+            fbdata%caddname(2+ja) = padd%cdname(ja)
+            fbdata%caddlong(2+ja,1) = padd%cdlong(ja,1)
+            fbdata%caddunit(2+ja,1) = padd%cdunit(ja,1)
+         END DO
+
+      CASE('SST')
+
+         CALL alloc_obfbdata( fbdata, 1, surfdata%nsurf, 1, &
+            &                 1 + iadd, iext, .TRUE. )
+
+         clfiletype = 'sstfb'
+         fbdata%cname(1)      = surfdata%cvars(1)
+         fbdata%coblong(1)    = 'Sea surface temperature'
+         fbdata%cobunit(1)    = 'Degree centigrade'
+         DO je = 1, iext
+            fbdata%cextname(je) = pext%cdname(je)
+            fbdata%cextlong(je) = pext%cdlong(je,1)
+            fbdata%cextunit(je) = pext%cdunit(je,1)
+         END DO
+         fbdata%caddlong(1,1) = 'Model interpolated SST'
+         fbdata%caddunit(1,1) = 'Degree centigrade'
+         fbdata%cgrid(1)      = 'T'
+         DO ja = 1, iadd
+            fbdata%caddname(1+ja) = padd%cdname(ja)
+            fbdata%caddlong(1+ja,1) = padd%cdlong(ja,1)
+            fbdata%caddunit(1+ja,1) = padd%cdunit(ja,1)
+         END DO
+
+      CASE('ICECONC')
+
+         CALL alloc_obfbdata( fbdata, 1, surfdata%nsurf, 1, &
+            &                 1 + iadd, iext, .TRUE. )
+
+         clfiletype = 'sicfb'
+         fbdata%cname(1)      = surfdata%cvars(1)
+         fbdata%coblong(1)    = 'Sea ice'
+         fbdata%cobunit(1)    = 'Fraction'
+         DO je = 1, iext
+            fbdata%cextname(je) = pext%cdname(je)
+            fbdata%cextlong(je) = pext%cdlong(je,1)
+            fbdata%cextunit(je) = pext%cdunit(je,1)
+         END DO
+         fbdata%caddlong(1,1) = 'Model interpolated ICE'
+         fbdata%caddunit(1,1) = 'Fraction'
+         fbdata%cgrid(1)      = 'T'
+         DO ja = 1, iadd
+            fbdata%caddname(1+ja) = padd%cdname(ja)
+            fbdata%caddlong(1+ja,1) = padd%cdlong(ja,1)
+            fbdata%caddunit(1+ja,1) = padd%cdunit(ja,1)
+         END DO
+
+      CASE('SSS')
+
+         CALL alloc_obfbdata( fbdata, 1, surfdata%nsurf, 1, &
+            &                 1 + iadd, iext, .TRUE. )
+
+         clfiletype = 'sssfb'
+         fbdata%cname(1)      = surfdata%cvars(1)
+         fbdata%coblong(1)    = 'Sea surface salinity'
+         fbdata%cobunit(1)    = 'psu'
+         DO je = 1, iext
+            fbdata%cextname(je) = pext%cdname(je)
+            fbdata%cextlong(je) = pext%cdlong(je,1)
+            fbdata%cextunit(je) = pext%cdunit(je,1)
+         END DO
+         fbdata%caddlong(1,1) = 'Model interpolated SSS'
+         fbdata%caddunit(1,1) = 'psu'
+         fbdata%cgrid(1)      = 'T'
+         DO ja = 1, iadd
+            fbdata%caddname(1+ja) = padd%cdname(ja)
+            fbdata%caddlong(1+ja,1) = padd%cdlong(ja,1)
+            fbdata%caddunit(1+ja,1) = padd%cdunit(ja,1)
+         END DO
+
+      CASE DEFAULT
+
+         CALL ctl_stop( 'Unknown observation type '//TRIM(surfdata%cvars(1))//' in obs_wri_surf' )
+
+      END SELECT
+
+      fbdata%caddname(1)   = 'Hx'
+
+      WRITE(clfname, FMT="(A,'_fdbk_',I4.4,'.nc')") TRIM(clfiletype), nproc
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*)'obs_wri_surf :'
+         WRITE(numout,*)'~~~~~~~~~~~~~'
+         WRITE(numout,*)'Writing '//TRIM(surfdata%cvars(1))//' feedback file : ',TRIM(clfname)
+      ENDIF
+
+      ! Transform surf data structure into obfbdata structure
+      fbdata%cdjuldref = '19500101000000'
+      DO jo = 1, surfdata%nsurf
+         fbdata%plam(jo)      = surfdata%rlam(jo)
+         fbdata%pphi(jo)      = surfdata%rphi(jo)
+         WRITE(fbdata%cdtyp(jo),'(I4)') surfdata%ntyp(jo)
+         fbdata%ivqc(jo,:)    = 0
+         fbdata%ivqcf(:,jo,:) = 0
+         IF ( surfdata%nqc(jo) > 255 ) THEN
+            fbdata%ioqc(jo)    = 4
+            fbdata%ioqcf(1,jo) = 0
+!$AGRIF_DO_NOT_TREAT
+            fbdata%ioqcf(2,jo) = IAND(surfdata%nqc(jo),b'0000000011111111')
+!$AGRIF_END_DO_NOT_TREAT
+         ELSE
+            fbdata%ioqc(jo)    = surfdata%nqc(jo)
+            fbdata%ioqcf(:,jo) = 0
+         ENDIF
+         fbdata%ipqc(jo)      = 0
+         fbdata%ipqcf(:,jo)   = 0
+         fbdata%itqc(jo)      = 0
+         fbdata%itqcf(:,jo)   = 0
+         fbdata%cdwmo(jo)     = surfdata%cwmo(jo)
+         fbdata%kindex(jo)    = surfdata%nsfil(jo)
+         IF (ln_grid_global) THEN
+            fbdata%iobsi(jo,1) = surfdata%mi(jo)
+            fbdata%iobsj(jo,1) = surfdata%mj(jo)
+         ELSE
+            fbdata%iobsi(jo,1) = mig(surfdata%mi(jo))
+            fbdata%iobsj(jo,1) = mjg(surfdata%mj(jo))
+         ENDIF
+         CALL greg2jul( 0, &
+            &           surfdata%nmin(jo), &
+            &           surfdata%nhou(jo), &
+            &           surfdata%nday(jo), &
+            &           surfdata%nmon(jo), &
+            &           surfdata%nyea(jo), &
+            &           fbdata%ptim(jo),   &
+            &           krefdate = 19500101 )
+         fbdata%padd(1,jo,1,1) = surfdata%rmod(jo,1)
+         IF ( TRIM(surfdata%cvars(1)) == 'SLA' ) fbdata%padd(1,jo,2,1) = surfdata%rext(jo,1)
+         fbdata%pob(1,jo,1)    = surfdata%robs(jo,1) 
+         fbdata%pdep(1,jo)     = 0.0
+         fbdata%idqc(1,jo)     = 0
+         fbdata%idqcf(:,1,jo)  = 0
+         IF ( surfdata%nqc(jo) > 255 ) THEN
+            fbdata%ivqc(jo,1)       = 4
+            fbdata%ivlqc(1,jo,1)    = 4
+            fbdata%ivlqcf(1,1,jo,1) = 0
+!$AGRIF_DO_NOT_TREAT
+            fbdata%ivlqcf(2,1,jo,1) = IAND(surfdata%nqc(jo),b'0000000011111111')
+!$AGRIF_END_DO_NOT_TREAT
+         ELSE
+            fbdata%ivqc(jo,1)       = surfdata%nqc(jo)
+            fbdata%ivlqc(1,jo,1)    = surfdata%nqc(jo)
+            fbdata%ivlqcf(:,1,jo,1) = 0
+         ENDIF
+         fbdata%iobsk(1,jo,1)  = 0
+         IF ( TRIM(surfdata%cvars(1)) == 'SLA' ) fbdata%pext(1,jo,1) = surfdata%rext(jo,2)
+         DO ja = 1, iadd
+            fbdata%padd(1,jo,2+ja,1) = &
+               & surfdata%rext(jo,padd%ipoint(ja))
+         END DO
+         DO je = 1, iext
+            fbdata%pext(1,jo,1+je) = &
+               & surfdata%rext(jo,pext%ipoint(je))
+         END DO
+      END DO
+
+      ! Write the obfbdata structure
+      CALL write_obfbdata( clfname, fbdata )
+
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
+      CALL dealloc_obfbdata( fbdata )
+
+   END SUBROUTINE obs_wri_surf
+
+   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 :: inumgoodobs
+      INTEGER :: inumgoodobsmpp
+      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
+         inumgoodobs=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
+                  inumgoodobs=inumgoodobs+1
+               ENDIF
+            ENDDO
+         ENDDO
+
+         CALL obs_mpp_sum_integer( inumgoodobs, inumgoodobsmpp )
+         CALL mpp_sum('obs_write', zsumx)
+         CALL mpp_sum('obs_write', zsumx2)
+
+         IF (lwp) THEN
+            WRITE(numout,*) 'Type: ',fbdata%cname(jvar),'  Total number of good observations: ',inumgoodobsmpp 
+            WRITE(numout,*) 'Overall mean obs minus model of the good observations: ',zsumx/inumgoodobsmpp
+            WRITE(numout,*) 'Overall RMS obs minus model of the good observations: ',sqrt( zsumx2/inumgoodobsmpp )
+            WRITE(numout,*) ''
+         ENDIF
+
+      ENDDO
+
+   END SUBROUTINE obs_wri_stats
+
+END MODULE obs_write
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_h2d.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_h2d.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_h2d.h90	(revision 14097)
@@ -0,0 +1,1359 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE obs_int_h2d_init( kpk,   kpk2,  k2dint, plam,  pphi, &
+      &                         pglam, pgphi, pmask,  pweig, pobsmask, &
+      &                         iminpoints )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d  ***
+      !!
+      !! ** Purpose : Computes weights for horizontal interpolation to the 
+      !!              observation point.
+      !!
+      !! ** Method  : Horizontal interpolation to the observation point using
+      !!              model values at the corners of the surrounding grid 
+      !!              points.
+      !!
+      !!    Interpolation Schemes : 
+      !!
+      !!    1) k2dint = 0: Distance-weighted interpolation scheme 1
+      !!
+      !!       The interpolation weights are computed as a weighted 
+      !!       sum of the distance between the model grid points (A)
+      !!       and the observation point (B). Distance (s) is computed 
+      !!       using the great-circle distance formula: 
+      !!
+      !!       s(AB) = arcos(   sin( phiA ) x sin( phiB )
+      !!                      + cos( phiA ) x cos( phiB ) 
+      !!                                    x cos( lamB - lamA ) )
+      !!
+      !!    2) k2dint = 1: Distance-weighted interpolation scheme 2
+      !!
+      !!       As k2dint = 0 but with distance (ds) computed using 
+      !!       a small-angle approximation to the great-circle formula:
+      !!
+      !!       ds(AB) = sqrt(   ( phiB - phiA )^{2} 
+      !!                    + ( ( lamB - lamA ) * cos( phiB ) )^{2} )
+      !!
+      !!    3) k2dint = 2: Bilinear interpolation on a geographical grid
+      !!
+      !!       The interpolation is split into two 1D interpolations in
+      !!       the longitude and latitude directions, respectively.
+      !!
+      !!    4) k2dint = 3: General bilinear remapping interpolation
+      !!
+      !!       An iterative scheme that involves first mapping a 
+      !!       quadrilateral cell into a cell with coordinates 
+      !!       (0,0), (1,0), (0,1) and (1,1).
+      !!
+      !!    5) k2dint = 4: Polynomial interpolation
+      !!
+      !!       The interpolation weights are computed by fitting a 
+      !!       polynomial function of the form 
+      !!              
+      !!       P(i) = a1(i) + a2(i) * phi + a3(i) * plam 
+      !!                                  + a4(i) * phi * plam
+      !!    
+      !!       through the model values at the four surrounding grid points.
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : Jones, P.: A users guide for SCRIP: A Spherical 
+      !!                        Coordinate Remapping and Interpolation Package.
+      !!                        Version 1.4. Los Alomos. 
+      !!                    
+      !!       http://www.acl.lanl.gov/climate/software/SCRIP/SCRIPmain.html
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-03 (A. Vidard) NEMOVAR migration
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!        ! 07-08 (K. Mogensen) Split in two routines for easier adj.
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk,   &             ! Parameter values for automatic arrays
+         & kpk2,  &        
+         & k2dint               ! Interpolation scheme options
+                                ! = 0 distance-weighted (great circle)
+                                ! = 1 distance-weighted (small angle)
+                                ! = 2 bilinear (geographical grid)
+                                ! = 3 bilinear (quadrilateral grid)
+                                ! = 4 polynomial (quadrilateral grid)
+      REAL(KIND=wp), INTENT(INOUT) :: &
+         & plam, &
+         & pphi                 ! Geographical (lat,lon) coordinates of
+                                ! observation
+      REAL(KIND=wp), DIMENSION(2,2), INTENT(IN) :: &
+         & pglam, &             ! Model variable lat
+         & pgphi                ! Model variable lon
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmask                ! Model variable mask
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(OUT) ::  &
+         & pweig                ! Weights for interpolation
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) ::  &
+         & pobsmask             ! Vertical mask for observations
+      INTEGER, INTENT(IN), OPTIONAL :: &
+         & iminpoints           ! Reject point which is not surrounded
+                                ! by at least iminpoints sea points
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      INTEGER :: &
+         & ikmax, &
+         & iamb1, &
+         & iamb2
+      REAL(KIND=wp) :: &
+         & zphimm,  &
+         & zphimp,  &
+         & zphipm,  &
+         & zphipp,  &
+         & zlammm,  &
+         & zlammp,  &
+         & zlampm,  &
+         & zlampp,  &
+         & zphimin, &
+         & zphimax, &
+         & zlammin, &
+         & zlammax
+      REAL(KIND=wp), DIMENSION(kpk2) :: &
+         & z2dmm,  &
+         & z2dmp,  &
+         & z2dpm,  &
+         & z2dpp,  &
+         & z2dmmt, &
+         & z2dmpt, &
+         & z2dpmt, &
+         & z2dppt, &
+         & zsum
+      LOGICAL :: &
+         & ll_ds1, &
+         & ll_skip, &
+         & ll_fail
+       
+      !------------------------------------------------------------------------
+      ! Constants for the 360 degrees ambiguity
+      !------------------------------------------------------------------------
+      iamb1 = 10   ! dlam < iamb1 * dphi
+      iamb2 = 3    ! Special treatment if iamb2 * lam < max(lam) 
+       
+      !------------------------------------------------------------------------
+      ! Initialize number of levels
+      !------------------------------------------------------------------------
+      IF ( kpk2 == 1 ) THEN
+         ikmax = 1
+      ELSEIF ( kpk2 == kpk) THEN
+         ikmax = kpk-1
+      ENDIF
+      !------------------------------------------------------------------------
+      ! Initialize the cell corners
+      !------------------------------------------------------------------------
+      zphimm = pgphi(1,1)
+      zphimp = pgphi(1,2)
+      zphipm = pgphi(2,1)
+      zphipp = pgphi(2,2)
+      zlammm = pglam(1,1)
+      zlammp = pglam(1,2)
+      zlampm = pglam(2,1)
+      zlampp = pglam(2,2)
+       
+      !------------------------------------------------------------------------
+      ! Treat the 360 degrees ambiguity
+      !------------------------------------------------------------------------
+      DO WHILE ( ( zlammm < 0.0_wp ).OR.( zlammm > 360.0_wp )  &
+         &   .OR.( zlampm < 0.0_wp ).OR.( zlampm > 360.0_wp )  &
+         &   .OR.( zlampp < 0.0_wp ).OR.( zlampp > 360.0_wp )  &
+         &   .OR.( zlammp < 0.0_wp ).OR.( zlammp > 360.0_wp ) )
+       
+         IF ( zlammm < 0.0_wp   ) zlammm = zlammm + 360.0_wp
+         IF ( zlammm > 360.0_wp ) zlammm = zlammm - 360.0_wp
+         IF ( zlammp < 0.0_wp   ) zlammp = zlammp + 360.0_wp
+         IF ( zlammp > 360.0_wp ) zlammp = zlammp - 360.0_wp
+         IF ( zlampm < 0.0_wp   ) zlampm = zlampm + 360.0_wp
+         IF ( zlampm > 360.0_wp ) zlampm = zlampm - 360.0_wp
+         IF ( zlampp < 0.0_wp   ) zlampp = zlampp + 360.0_wp
+         IF ( zlampp > 360.0_wp ) zlampp = zlampp - 360.0_wp
+       
+      END DO
+
+      DO WHILE ( ( plam < 0.0_wp ) .OR. ( plam > 360.0_wp ) )
+         IF ( plam < 0.0_wp   ) plam = plam + 360.0_wp
+         IF ( plam > 360.0_wp ) plam = plam - 360.0_wp
+      END DO
+
+      !------------------------------------------------------------------------
+      ! Special case for observation on grid points
+      !------------------------------------------------------------------------
+      ll_skip = .FALSE.
+      IF ( ( ABS( zphimm - pphi ) < 1.0e-6_wp ) .AND. &
+         & ( ABS( zlammm - plam ) < 1.0e-6_wp ) ) THEN
+         z2dmm(:) = 1.0_wp
+         z2dpm(:) = 0.0_wp
+         z2dmp(:) = 0.0_wp
+         z2dpp(:) = 0.0_wp
+         ll_skip = .TRUE.
+      ENDIF
+      IF ( ( ABS( zphipm - pphi ) < 1.0e-6_wp ) .AND. &
+         & ( ABS( zlampm - plam ) < 1.0e-6_wp ) ) THEN
+         z2dmm(:) = 0.0_wp
+         z2dpm(:) = 1.0_wp
+         z2dmp(:) = 0.0_wp
+         z2dpp(:) = 0.0_wp
+         ll_skip = .TRUE.
+      ENDIF
+      IF ( ( ABS( zphimp - pphi ) < 1.0e-6_wp ) .AND. &
+         & ( ABS( zlammp - plam ) < 1.0e-6_wp ) ) THEN
+         z2dmm(:) = 0.0_wp
+         z2dpm(:) = 0.0_wp
+         z2dmp(:) = 1.0_wp
+         z2dpp(:) = 0.0_wp
+         ll_skip = .TRUE.
+      ENDIF
+      IF ( ( ABS( zphipp - pphi ) < 1.0e-6_wp ) .AND. &
+         & ( ABS( zlampp - plam ) < 1.0e-6_wp ) ) THEN
+         z2dmm(:) = 0.0_wp
+         z2dpm(:) = 0.0_wp
+         z2dmp(:) = 0.0_wp
+         z2dpp(:) = 1.0_wp
+         ll_skip = .TRUE.
+      ENDIF
+
+      IF ( .NOT.ll_skip ) THEN
+
+         zphimin = MIN( zphimm, zphipm, zphipp, zphimp )
+         zphimax = MAX( zphimm, zphipm, zphipp, zphimp )
+         zlammin = MIN( zlammm, zlampm, zlampp, zlammp )
+         zlammax = MAX( zlammm, zlampm, zlampp, zlammp )
+
+         IF ( ( ( zlammax - zlammin ) / ( zphimax - zphimin ) ) > iamb1 ) THEN
+            IF ( iamb2 * zlammm < zlammax ) zlammm = zlammm + 360.0_wp
+            IF ( iamb2 * zlammp < zlammax ) zlammp = zlammp + 360.0_wp
+            IF ( iamb2 * zlampm < zlammax ) zlampm = zlampm + 360.0_wp
+            IF ( iamb2 * zlampp < zlammax ) zlampp = zlampp + 360.0_wp
+         ENDIF
+
+         zlammin = MIN( zlammm, zlampm, zlampp, zlammp )
+         IF ( zlammm > ( zlammin + 180.0_wp ) ) zlammm = zlammm - 360.0_wp
+         IF ( zlammp > ( zlammin + 180.0_wp ) ) zlammp = zlammp - 360.0_wp
+         IF ( zlampm > ( zlammin + 180.0_wp ) ) zlampm = zlampm - 360.0_wp
+         IF ( zlampp > ( zlammin + 180.0_wp ) ) zlampp = zlampp - 360.0_wp
+         
+         IF ( plam < zlammin ) plam = plam + 360.0_wp
+	   z2dmm = 0.0_wp
+	   z2dmp = 0.0_wp
+	   z2dpm = 0.0_wp
+	   z2dpp = 0.0_wp
+         SELECT CASE (k2dint)
+            
+         CASE(0)
+            CALL obs_int_h2d_ds1( kpk2, ikmax,                        &
+               &                  pphi, plam, pmask,                  &
+               &                  zphimm, zlammm, zphimp, zlammp,     & 
+               &                  zphipm, zlampm, zphipp, zlampp,     &
+               &                  z2dmm, z2dmp, z2dpm, z2dpp )
+         CASE(1)
+            CALL obs_int_h2d_ds2( kpk2, ikmax,                        &
+               &                  pphi, plam, pmask,                  &
+               &                  zphimm, zlammm, zphimp, zlammp,     &
+               &                  zphipm, zlampm, zphipp, zlampp,     &
+               &                  z2dmm, z2dmp, z2dpm, z2dpp )
+         CASE(2)
+            CALL obs_int_h2d_bil( kpk2, ikmax,                        &
+               &                  pphi, plam, pmask,                  &
+               &                                          zlammp,     &
+               &                  zphipm,         zphipp, zlampp,     &
+               &                  z2dmm, z2dmp, z2dpm, z2dpp )
+         CASE(3)
+            CALL obs_int_h2d_bir( kpk2, ikmax,                        &
+               &                  pphi, plam, pmask,                  &
+               &                  zphimm, zlammm, zphimp, zlammp,     &
+               &                  zphipm, zlampm, zphipp, zlampp,     &
+               &                  z2dmm, z2dmp, z2dpm, z2dpp, ll_fail )
+            IF (ll_fail) THEN
+               IF(lwp) THEN
+                  WRITE(numout,*)'Bilinear weight computation failed'
+                  WRITE(numout,*)'Switching to great circle distance'
+                  WRITE(numout,*)
+               ENDIF
+               CALL obs_int_h2d_ds1( kpk2, ikmax,                        &
+                  &                  pphi, plam, pmask,                  &
+                  &                  zphimm, zlammm, zphimp, zlammp,     & 
+                  &                  zphipm, zlampm, zphipp, zlampp,     &
+                  &                  z2dmm, z2dmp, z2dpm, z2dpp )
+            ENDIF
+         CASE(4)  
+            CALL obs_int_h2d_pol( kpk2, ikmax,                        &
+               &                  pphi, plam, pmask,                  &
+               &                  zphimm, zlammm, zphimp, zlammp,     &
+               &                  zphipm, zlampm, zphipp, zlampp,     & 
+               &                  z2dmm, z2dmp, z2dpm, z2dpp )
+         END SELECT
+
+      ENDIF
+      !------------------------------------------------------------------------
+      ! Compute weights for interpolation to the observation point
+      !------------------------------------------------------------------------
+      pobsmask(:) = 0.0_wp
+      pweig(:,:,:) = 0.0_wp
+      ! ll_ds1 is used for failed interpolations
+      ll_ds1 = .FALSE.
+      DO jk = 1, ikmax
+         IF (PRESENT(iminpoints)) THEN
+            IF (NINT(SUM(pmask(:,:,jk)))<iminpoints) CYCLE
+         ENDIF
+         zsum(jk) = z2dmm(jk) + z2dmp(jk) + z2dpm(jk) + z2dpp(jk) 
+         IF ( zsum(jk) /= 0.0_wp ) THEN
+            pweig(1,1,jk) = z2dmm(jk) 
+            pweig(1,2,jk) = z2dmp(jk)
+            pweig(2,1,jk) = z2dpm(jk)
+            pweig(2,2,jk) = z2dpp(jk)
+            ! Set the vertical mask
+            IF ( ( ( z2dmm(jk) > 0.0_wp ) .AND.       &
+               &   ( pmask(1,1,jk) == 1.0_wp ) ) .OR. &
+               & ( ( z2dmp(jk) > 0.0_wp ) .AND.       &
+               &   ( pmask(1,2,jk) == 1.0_wp ) ) .OR. &
+               & ( ( z2dpm(jk) > 0.0_wp ) .AND.       &
+               &   ( pmask(2,1,jk) == 1.0_wp ) ) .OR. &
+               & ( ( z2dpp(jk) > 0.0_wp ) .AND.       &
+               &   ( pmask(2,2,jk) == 1.0_wp ) ) ) pobsmask(jk)=1.0_wp
+         ELSE
+            ! If the interpolation has failed due to the point
+            ! being on the intersect of two land points retry with
+            ! k2dint = 0
+            IF ( ( pmask(1,1,jk) /= 0.0_wp ).OR. &
+               & ( pmask(1,2,jk) /= 0.0_wp ).OR. &
+               & ( pmask(2,1,jk) /= 0.0_wp ).OR. &
+               & ( pmask(2,2,jk) /= 0.0_wp ) ) THEN
+               ! If ll_ds1 is false compute k2dint = 0 weights
+               IF ( .NOT.ll_ds1 ) THEN
+                  CALL obs_int_h2d_ds1( kpk2, ikmax,                        &
+                     &                  pphi, plam, pmask,                  &
+                     &                  zphimm, zlammm, zphimp, zlammp,     & 
+                     &                  zphipm, zlampm, zphipp, zlampp,     &
+                     &                  z2dmmt, z2dmpt, z2dpmt, z2dppt ) 
+                  ll_ds1 = .TRUE.
+               ENDIF
+               zsum(jk) = z2dmmt(jk) + z2dmpt(jk) + z2dpmt(jk) + z2dppt(jk) 
+               IF ( zsum(jk) /= 0.0_wp ) THEN
+                  pweig(1,1,jk) = z2dmmt(jk) 
+                  pweig(1,2,jk) = z2dmpt(jk)
+                  pweig(2,1,jk) = z2dpmt(jk)
+                  pweig(2,2,jk) = z2dppt(jk)
+                  ! Set the vertical mask
+                  IF ( ( ( z2dmmt(jk) > 0.0_wp ) .AND.      &
+                     &   ( pmask(1,1,jk) == 1.0_wp ) ) .OR. &
+                     & ( ( z2dmpt(jk) > 0.0_wp ) .AND.      &
+                     &   ( pmask(1,2,jk) == 1.0_wp ) ) .OR. &
+                     & ( ( z2dpmt(jk) > 0.0_wp) .AND.      &
+                     &   ( pmask(2,1,jk) == 1.0_wp ) ) .OR. &
+                     & ( ( z2dppt(jk) > 0.0_wp ) .AND.      &
+                     &   ( pmask(2,2,jk) == 1.0_wp ) ) )    &
+                     & pobsmask(jk)=1.0_wp
+               ENDIF
+            ENDIF
+         ENDIF
+      END DO
+  
+   END SUBROUTINE obs_int_h2d_init
+
+   SUBROUTINE obs_int_h2d( kpk, kpk2, &
+      &                    pweig, pmod, pobsk )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d  ***
+      !!
+      !! ** Purpose : Horizontal interpolation to the observation point.
+      !!
+      !! ** Method  : Horizontal interpolation to the observation point using
+      !!              model values at the corners of the surrounding grid 
+      !!              points.
+      !!
+      !! ** Action  :
+      !!                   
+      !! References : 
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-03 (A. Vidard) NEMOVAR migration
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!        ! 07-08 (K. Mogensen) Split in two routines for easier adj.
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk,   &             ! Parameter values for automatic arrays
+         & kpk2
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pweig                ! Interpolation weights
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmod                 ! Model variable to interpolate
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) ::  &
+         & pobsk                ! Model profile interpolated to obs (i,j) pt
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      INTEGER :: &
+         & ikmax
+      REAL(KIND=wp) :: &
+         & zsum
+      !------------------------------------------------------------------------
+      ! Initialize number of levels
+      !------------------------------------------------------------------------
+      IF ( kpk2 == 1 ) THEN
+         ikmax = 1
+      ELSEIF ( kpk2 == kpk) THEN
+         ikmax = kpk-1
+      ENDIF
+      !------------------------------------------------------------------------
+      ! Interpolate to the observation point
+      !------------------------------------------------------------------------
+      pobsk(:) = obfillflt
+      DO jk = 1, ikmax
+         zsum = pweig(1,1,jk) + pweig(1,2,jk) + pweig(2,1,jk) +  pweig(2,2,jk) 
+         IF ( zsum /= 0.0_wp ) THEN
+            pobsk(jk) = (  pweig(1,1,jk) * pmod(1,1,jk)         &
+               &         + pweig(1,2,jk) * pmod(1,2,jk)         &
+               &         + pweig(2,1,jk) * pmod(2,1,jk)         &
+               &         + pweig(2,2,jk) * pmod(2,2,jk)         &
+               &                                             ) / zsum
+         ENDIF
+      END DO
+
+   END SUBROUTINE obs_int_h2d
+  
+   SUBROUTINE obs_int_h2d_ds1( kpk2, kmax,                        &
+      &                        pphi, plam, pmask,                 &
+      &                        pphimm, plammm, pphimp, plammp,    & 
+      &                        pphipm, plampm, pphipp, plampp,    &
+      &                        p2dmm, p2dmp, p2dpm, p2dpp )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d_ds1  ***
+      !!
+      !! ** Purpose : Distance-weighted interpolation scheme (k2dint = 0)
+      !!
+      !! ** Method  : The interpolation weights are computed as a weighted 
+      !!              sum of the distance between the model grid points (A) 
+      !!              and the observation point (B). 
+      !!
+      !!    Distance (s) is computed using the great-circle distance formula:
+      !!
+      !!    s(AB) = arcos(   sin( phiA ) x sin( phiB )
+      !!                   + cos( phiA ) x cos( phiB ) x cos( lamB - lamA )
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      !! * Modules used
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &             ! Parameter values for automatic arrays
+         & kmax
+      REAL(KIND=wp), INTENT(IN) :: &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphimm, &           ! Geographical location of surrounding
+         & pphimp, &           ! model grid points
+         & pphipm, &
+         & pphipp, & 
+         & plammm, &
+         & plammp, &
+         & plampm, &
+         & plampp
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmask               ! Model variable mask 
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) :: &
+         & p2dmm, &            ! Interpolation weights
+         & p2dmp, &
+         & p2dpm, &
+         & p2dpp
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      REAL(KIND=wp) :: &
+         & zphi2,   &
+         & zlam2,   &
+         & zcola,   &
+         & za2,     &
+         & zb2,     &
+         & zc2,     &
+         & zphimm2, &
+         & zphimp2, &
+         & zphipm2, &
+         & zphipp2, &
+         & zlammm2, &
+         & zlammp2, &
+         & zlampm2, &
+         & zlampp2, &
+         & za1mm,   &
+         & za1mp,   &
+         & za1pm,   &
+         & za1pp,   &
+         & zcomm,   &
+         & zcomp,   &
+         & zcopm,   &
+         & zcopp,   &
+         & zb1mm,   &
+         & zb1mp,   &
+         & zb1pm,   &
+         & zb1pp,   &
+         & zc1mm,   &
+         & zc1mp,   &
+         & zc1pm,   &
+         & zc1pp,   &
+         & zsopmpp, &
+         & zsommmp, &
+         & zsomm,   &
+         & zsomp,   &
+         & zsopm,   &
+         & zsopp
+       
+      !------------------------------------------------------------------------
+      ! Distance-weighted interpolation using the great circle formula
+      !------------------------------------------------------------------------
+      zphi2 = pphi * rad
+      zlam2 = plam * rad
+      zcola = COS( zphi2 )
+      za2   = SIN( zphi2 )
+      zb2   = zcola * COS( zlam2 )
+      zc2   = zcola * SIN( zlam2 )
+       
+      zphimm2 = pphimm * rad
+      zphimp2 = pphimp * rad
+      zphipm2 = pphipm * rad
+      zphipp2 = pphipp * rad
+       
+      zlammm2 = plammm * rad
+      zlammp2 = plammp * rad
+      zlampm2 = plampm * rad
+      zlampp2 = plampp * rad
+       
+      za1mm = SIN( zphimm2 )
+      za1mp = SIN( zphimp2 )
+      za1pm = SIN( zphipm2 )
+      za1pp = SIN( zphipp2 )
+       
+      zcomm = COS( zphimm2 )
+      zcomp = COS( zphimp2 )
+      zcopm = COS( zphipm2 )
+      zcopp = COS( zphipp2 )
+       
+      zb1mm = zcomm * COS( zlammm2 )
+      zb1mp = zcomp * COS( zlammp2 )
+      zb1pm = zcopm * COS( zlampm2 )
+      zb1pp = zcopp * COS( zlampp2 )
+       
+      zc1mm = zcomm * SIN( zlammm2 )
+      zc1mp = zcomp * SIN( zlammp2 )
+      zc1pm = zcopm * SIN( zlampm2 )
+      zc1pp = zcopp * SIN( zlampp2 )
+       
+      ! Function for arcsin(sqrt(1-x^2) version of great-circle formula
+      zsomm = grt_cir_dis( za1mm, za2, zb1mm, zb2, zc1mm, zc2 )
+      zsomp = grt_cir_dis( za1mp, za2, zb1mp, zb2, zc1mp, zc2 )
+      zsopm = grt_cir_dis( za1pm, za2, zb1pm, zb2, zc1pm, zc2 )
+      zsopp = grt_cir_dis( za1pp, za2, zb1pp, zb2, zc1pp, zc2 )
+       
+      zsopmpp = zsopm * zsopp
+      zsommmp = zsomm * zsomp
+      DO jk = 1, kmax
+         p2dmm(jk) = zsomp * zsopmpp * pmask(1,1,jk)
+         p2dmp(jk) = zsomm * zsopmpp * pmask(1,2,jk) 
+         p2dpm(jk) = zsopp * zsommmp * pmask(2,1,jk)
+         p2dpp(jk) = zsopm * zsommmp * pmask(2,2,jk)
+      END DO
+       
+   END SUBROUTINE obs_int_h2d_ds1
+  
+   SUBROUTINE obs_int_h2d_ds2( kpk2, kmax,                        &
+      &                        pphi, plam, pmask,                 &
+      &                        pphimm, plammm, pphimp, plammp,    &
+      &                        pphipm, plampm, pphipp, plampp,    &
+      &                        p2dmm, p2dmp, p2dpm, p2dpp ) 
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d_ds2  ***
+      !!
+      !! ** Purpose : Distance-weighted interpolation scheme (k2dint = 1)
+      !!
+      !! ** Method  : As k2dint = 0 but with distance (ds) computed using a 
+      !!              small-angle approximation to the great-circle distance 
+      !!              formula:
+      !!
+      !!    ds(AB) = sqrt(   ( phiB - phiA )^{2}
+      !!                   + ( ( lamB - lamA ) * cos( phiB ) )^{2} )
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      !!-----------------------------------------------------------------------
+      !! * Modules used
+      !!----------------------------------------------------------------------- 
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &             ! Parameter values for automatic arrays
+         & kmax
+      REAL(KIND=wp), INTENT(IN) ::        &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphimm, &           ! Geographical location of surrounding
+         & pphimp, &           ! model grid points
+         & pphipm, &
+         & pphipp, & 
+         & plammm, &
+         & plammp, &
+         & plampm, &
+         & plampp
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmask               ! Model variable mask 
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) :: &
+         & p2dmm, &            ! Interpolation weights
+         & p2dmp, &
+         & p2dpm, &
+         & p2dpp
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      REAL(KIND=wp) :: &
+         & zcosp,   &
+         & zdlmm,   &
+         & zdlmp,   &
+         & zdlpm,   &
+         & zdlpp,   &
+         & zdpmm,   &
+         & zdpmp,   &
+         & zdppm,   &
+         & zdppp,   &
+         & zsomm,   &
+         & zsomp,   &
+         & zsopm,   &
+         & zsopp,   &
+         & zsopmpp, &
+         & zsommmp
+       
+      !------------------------------------------------------------------------
+      ! Distance-weighted interpolation with a small angle approximation
+      !------------------------------------------------------------------------
+      zcosp = COS( pphi * rad )
+       
+      zdlmm = plammm - plam
+      zdlmp = plammp - plam
+      zdlpm = plampm - plam
+      zdlpp = plampp - plam
+       
+      zdpmm = pphimm - pphi
+      zdpmp = pphimp - pphi
+      zdppm = pphipm - pphi
+      zdppp = pphipp - pphi
+       
+      zsomm = grt_cir_dis_saa( zdlmm, zdpmm, zcosp )
+      zsomp = grt_cir_dis_saa( zdlmp, zdpmp, zcosp )
+      zsopm = grt_cir_dis_saa( zdlpm, zdppm, zcosp )
+      zsopp = grt_cir_dis_saa( zdlpp, zdppp, zcosp )
+       
+      zsopmpp = zsopm * zsopp
+      zsommmp = zsomm * zsomp
+       
+      DO jk = 1, kmax
+         p2dmm(jk) = zsomp * zsopmpp * pmask(1,1,jk)
+         p2dmp(jk) = zsomm * zsopmpp * pmask(1,2,jk)
+         p2dpm(jk) = zsopp * zsommmp * pmask(2,1,jk)
+         p2dpp(jk) = zsopm * zsommmp * pmask(2,2,jk)
+      END DO
+       
+   END SUBROUTINE obs_int_h2d_ds2
+  
+   SUBROUTINE obs_int_h2d_bil( kpk2, kmax,                        &
+      &                        pphi, plam, pmask,                 &
+      &                        plammp, pphipm, pphipp, plampp,    &
+      &                        p2dmm, p2dmp, p2dpm, p2dpp)
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d_bil  ***
+      !!
+      !! ** Purpose : Bilinear interpolation on a geographical grid (k2dint = 2)
+      !!
+      !! ** Method  : The interpolation is split into two 1D interpolations in 
+      !!              the longitude and latitude directions, respectively.
+      !!
+      !!    An iterative scheme that involves first mapping a quadrilateral
+      !!    cell into a cell with coordinates (0,0), (1,0), (0,1) and (1,1).
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &             ! Parameter values for automatic arrays
+         & kmax
+      REAL(KIND=wp), INTENT(IN) :: &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphipm, &           ! Geographical location of surrounding
+         & pphipp, &           ! model grid points
+         & plammp, &
+         & plampp
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN)  :: &
+         & pmask               ! Model variable mask
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) :: &
+         & p2dmm, &            ! Interpolation weights
+         & p2dmp, &
+         & p2dpm, &
+         & p2dpp
+
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      REAL(KIND=wp) :: &
+         & zdlmp, &
+         & zdppm, &
+         & zdlpp, &
+         & zdppp
+       
+      !----------------------------------------------------------------------
+      ! Bilinear interpolation for geographical grid
+      !----------------------------------------------------------------------
+      zdlmp = ABS(plam   - plammp) 
+      zdppm = ABS(pphi   - pphipm)
+      zdlpp = ABS(plampp - plam)
+      zdppp = ABS(pphipp - pphi)
+       
+      DO jk = 1, kmax
+         p2dmm(jk) = zdlpp * zdppp * pmask(1,1,jk)
+         p2dmp(jk) = zdlpp * zdppm * pmask(1,2,jk)
+         p2dpm(jk) = zdlmp * zdppp * pmask(2,1,jk)
+         p2dpp(jk) = zdlmp * zdppm * pmask(2,2,jk)
+      END DO
+       
+   END SUBROUTINE obs_int_h2d_bil
+  
+   SUBROUTINE obs_int_h2d_bir( kpk2, kmax,                        &
+      &                        pphi, plam, pmask,                 &
+      &                        pphimm, plammm, pphimp, plammp,    &
+      &                        pphipm, plampm, pphipp, plampp,    &
+      &                        p2dmm, p2dmp, p2dpm, p2dpp, ldfail )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d_bir  ***
+      !!
+      !! ** Purpose : General bilinear remapping interpolation (k2dint = 3)
+      !!
+      !! ** Method  : An iterative scheme that involves first mapping a 
+      !!              quadrilateral cell into a cell with coordinates 
+      !!              (0,0), (1,0), (0,1) and (1,1).
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kpk2, &             ! Parameter values for automatic arrays
+         & kmax
+      REAL(KIND=wp), INTENT(IN) ::        &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphimm, &           ! Geographical location of surrounding
+         & pphimp, &           ! model grid points
+         & pphipm, &
+         & pphipp, & 
+         & plammm, &
+         & plammp, &
+         & plampm, &
+         & plampp
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmask               ! Model variable mask 
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) :: &
+         & p2dmm, &            ! Interpolation weights
+         & p2dmp, &
+         & p2dpm, &
+         & p2dpp
+      LOGICAL, INTENT(OUT) :: &
+         & ldfail
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      REAL(KIND=wp) :: &
+         & zbiwmm, &
+         & zbiwmp, &
+         & zbiwpm, &
+         & zbiwpp
+  
+      !----------------------------------------------------------------------
+      ! Bilinear remapping interpolation for general quadrilateral grid
+      !----------------------------------------------------------------------
+      CALL bil_wgt( pphimm, pphimp, pphipm, pphipp,  &
+         &          plammm, plammp, plampm, plampp,  &
+         &          zbiwmm, zbiwmp, zbiwpm, zbiwpp,  &
+         &          pphi  , plam,   ldfail           )
+
+      IF ( .NOT.ldfail ) THEN
+         DO jk = 1, kmax
+            p2dmm(jk) = zbiwmm * pmask(1,1,jk)
+            p2dmp(jk) = zbiwmp * pmask(1,2,jk)
+            p2dpm(jk) = zbiwpm * pmask(2,1,jk)
+            p2dpp(jk) = zbiwpp * pmask(2,2,jk)
+         END DO
+      ENDIF
+
+   END SUBROUTINE obs_int_h2d_bir
+
+   SUBROUTINE obs_int_h2d_pol( kpk2, kmax,                         &
+      &                        pphi, plam, pmask,                  &
+      &                        pphimm, plammm, pphimp, plammp,     &
+      &                        pphipm, plampm, pphipp, plampp,     &
+      &                        p2dmm, p2dmp, p2dpm, p2dpp )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     ***  ROUTINE obs_int_h2d_pol  ***
+      !!
+      !! ** Purpose : Polynomial interpolation (k2dint = 4)
+      !!
+      !! ** Method  : The interpolation weights are computed by fitting a 
+      !!              polynomial function of the form
+      !!
+      !!    P(i) = a1(i) + a2(i) * phi + a3(i) * plam + a4(i) * phi * plam
+      !!
+      !!    through the model values at four surrounding grid pts (i=1,4).
+      !!    As k2dint = 0 but with distance (ds) computed using a small-
+      !!    angle approximation to the great-circle distance formula:
+      !!
+      !!    ds(AB) = sqrt(   ( phiB - phiA )^{2}
+      !!                   + ( ( lamB - lamA ) * cos( phiB ) )^{2} )
+      !!
+      !! ** Action  :
+      !!
+      !! History :
+      !!        ! 97-11 (A. Weaver, N. Daget)
+      !!        ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &  
+         & kpk2,   &           ! Parameter values for automatic arrays 
+         & kmax
+      REAL(KIND=wp), INTENT(IN) :: &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphimm, &           ! Geographical location of surrounding
+         & pphimp, &           ! model grid points
+         & pphipm, &
+         & pphipp, &
+         & plammm, &
+         & plammp, &
+         & plampm, &
+         & plampp
+      REAL(KIND=wp), DIMENSION(2,2,kpk2), INTENT(IN) :: &
+         & pmask               ! Model variable mask
+      REAL(KIND=wp), DIMENSION(kpk2), INTENT(OUT) :: &
+         & p2dmm,  &           ! Interpolation weights
+         & p2dmp,  &
+         & p2dpm,  &
+         & p2dpp
+  
+      !! * Local declarations
+      INTEGER :: &
+         & jk
+      REAL(KIND=wp) :: &
+         & zplp
+      REAL(KIND=wp), DIMENSION(4,4) :: &
+         & zmat,  &
+         & zmati
+       
+      !------------------------------------------------------------------------
+      ! Polynomial interpolation
+      !------------------------------------------------------------------------       
+      zmat(1,1) = 1.0_wp
+      zmat(1,2) = 1.0_wp
+      zmat(1,3) = 1.0_wp
+      zmat(1,4) = 1.0_wp
+      zmat(2,1) = plammm
+      zmat(2,2) = plammp
+      zmat(2,3) = plampm
+      zmat(2,4) = plampp
+      zmat(3,1) = pphimm
+      zmat(3,2) = pphimp
+      zmat(3,3) = pphipm
+      zmat(3,4) = pphipp
+      zmat(4,1) = plammm * pphimm
+      zmat(4,2) = plammp * pphimp
+      zmat(4,3) = plampm * pphipm
+      zmat(4,4) = plampp * pphipp
+       
+      CALL lu_invmat( zmat, 4, zmati )
+       
+      zplp = plam * pphi            
+      DO jk = 1, kmax
+         p2dmm(jk) = ABS(   zmati(1,1)        + zmati(1,2) * plam    &
+            &             + zmati(1,3) * pphi + zmati(1,4) * zplp )  &
+            &      * pmask(1,1,jk) 
+         p2dmp(jk) = ABS(   zmati(2,1)        + zmati(2,2) * plam    &
+            &             + zmati(2,3) * pphi + zmati(2,4) * zplp )  &
+            &      * pmask(1,2,jk)
+         p2dpm(jk) = ABS(   zmati(3,1)        + zmati(3,2) * plam    &
+            &             + zmati(3,3) * pphi + zmati(3,4) * zplp )  &
+            &      * pmask(2,1,jk)
+         p2dpp(jk) = ABS(   zmati(4,1)        + zmati(4,2) * plam    &
+            &             + zmati(4,3) * pphi + zmati(4,4) * zplp )  &
+            &      * pmask(2,2,jk)
+      END DO
+  
+   END SUBROUTINE obs_int_h2d_pol
+
+   SUBROUTINE bil_wgt( pphimm, pphimp, pphipm, pphipp,   &
+      &               plammm, plammp, plampm, plampp,   &
+      &               pbiwmm, pbiwmp, pbiwpm, pbiwpp,   &
+      &               pphi  , plam,   ldfail            )
+      !!-------------------------------------------------------------------
+      !!
+      !!                   ***  ROUTINE bil_wgt  ***
+      !!
+      !! ** Purpose : Compute the weights for a bilinear remapping 
+      !!              interpolation scheme.
+      !!
+      !! ** Method  : This scheme is appropriate for bilinear interpolation 
+      !!              on a general quadrilateral grid.    
+      !!              This scheme is also used in OASIS.
+      !!
+      !!              This routine is a derivative of the SCRIP software.
+      !!              Copyright 1997, 1998 the Regents of the University 
+      !!              of California. See SCRIP_Copyright.txt.
+      !!     
+      !! ** Action  :
+      !!
+      !! References : Jones, P.: A user's guide for SCRIP: A Spherical 
+      !!                Coordinate Remapping and Interpolation Package. 
+      !!                Version 1.4. Los Alamos. 
+      !!                  
+      !!         http://www.acl.lanl.gov/climate/software/SCRIP/SCRIPmain.html
+      !!
+      !! History
+      !!      ! 97-11 (A. Weaver, N. Daget)
+      !!      ! 06-03 (A. Vidard)
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+ 
+      !! * Arguments
+      REAL(KIND=wp), INTENT(IN) :: &
+         & pphi,   &           ! Geographical location of observation
+         & plam,   &
+         & pphimm, &           ! Geographical location of surrounding
+         & pphimp, &           ! model grid points
+         & pphipm, &
+         & pphipp, &
+         & plammm, &
+         & plammp, & 
+         & plampm, &
+         & plampp
+      REAL(KIND=wp), INTENT(OUT) :: &
+         & pbiwmm, &           ! Interpolation weights
+         & pbiwmp, &
+         & pbiwpm, &
+         & pbiwpp
+      LOGICAL, INTENT(out) :: &
+         & ldfail
+
+      !! * Local declarations
+      INTEGER :: &
+         & jiter
+      INTEGER :: &
+         & itermax
+      REAL(KIND=wp) :: &
+         & zphi,    &           ! Geographical location of observation
+         & zlam,    &
+         & zphimm,  &           ! Geographical location of surrounding
+         & zphimp,  &           ! model grid points
+         & zphipm,  &
+         & zphipp,  &
+         & zlammm,  &
+         & zlammp,  & 
+         & zlampm,  &
+         & zlampp,  &
+         & zdth1,   &
+         & zdth2,   &
+         & zdth3,   &
+         & zdthp,   &
+         & zdph1,   &
+         & zdph2,   &
+         & zdph3,   &
+         & zdphp,   &
+         & zmat1,   &
+         & zmat2,   &
+         & zmat3,   &
+         & zmat4,   &
+         & zdeli,   &
+         & zdelj,   &
+         & ziguess, &
+         & zjguess, &
+         & zeps,    &
+         & zdeterm, &
+         & z2pi,    &
+         & zhpi
+      
+      ! Initialization
+
+      ! Conversion to radians
+
+      zphi   = pphi   * rad
+      zlam   = plam   * rad
+      zphimm = pphimm * rad
+      zphimp = pphimp * rad
+      zphipm = pphipm * rad
+      zphipp = pphipp * rad
+      zlammm = plammm * rad
+      zlammp = plammp * rad
+      zlampm = plampm * rad
+      zlampp = plampp * rad
+
+      ldfail = .FALSE.
+
+      zdth1 = zphipm - zphimm
+      zdth2 = zphimp - zphimm
+      zdth3 = zphipp - zphipm - zdth2
+       
+      zdph1 = zlampm - zlammm
+      zdph2 = zlammp - zlammm
+      zdph3 = zlampp - zlampm
+       
+      z2pi = 2.0_wp * rpi
+       
+      IF ( zdph1 >  3.0_wp * rpi ) zdph1 = zdph1 - z2pi
+      IF ( zdph2 >  3.0_wp * rpi ) zdph2 = zdph2 - z2pi
+      IF ( zdph3 >  3.0_wp * rpi ) zdph3 = zdph3 - z2pi
+      IF ( zdph1 < -3.0_wp * rpi ) zdph1 = zdph1 + z2pi
+      IF ( zdph2 < -3.0_wp * rpi ) zdph2 = zdph2 + z2pi
+      IF ( zdph3 < -3.0_wp * rpi ) zdph3 = zdph3 + z2pi
+       
+      zdph3 = zdph3 - zdph2
+       
+      ziguess = 0.5_wp
+      zjguess = 0.5_wp
+       
+      itermax = 100
+
+      IF ( wp == sp ) THEN
+         zeps = 1.0e-6_wp	! Single precision
+      ELSE
+         zeps = 1.0e-10_wp      ! Double precision
+      ENDIF
+  
+      !------------------------------------------------------------------------
+      ! Iterate to determine (i,j) in new coordinate system
+      !------------------------------------------------------------------------
+      jiter_loop: DO jiter = 1, itermax
+         
+         zdthp = zphi - zphimm - zdth1 * ziguess - zdth2 * zjguess &
+            &  - zdth3 * ziguess * zjguess
+         zdphp = zlam - zlammm
+         
+         zhpi = 0.5_wp * rpi
+         IF ( zdphp >  3.0_wp * zhpi ) zdphp = zdphp - z2pi
+         IF ( zdphp < -3.0_wp * zhpi ) zdphp = zdphp + z2pi
+         
+         zdphp = zdphp - zdph1 * ziguess - zdph2 * zjguess &
+            &  - zdph3 * ziguess * zjguess
+         
+         zmat1 = zdth1 + zdth3 * zjguess
+         zmat2 = zdth2 + zdth3 * ziguess
+         zmat3 = zdph1 + zdph3 * zjguess
+         zmat4 = zdph2 + zdph3 * ziguess
+         
+         ! Matrix determinant
+         zdeterm = zmat1 * zmat4 - zmat2 * zmat3
+         
+         zdeli = ( zdthp * zmat4 - zmat2 * zdphp) / zdeterm
+         zdelj = ( zmat1 * zdphp - zdthp * zmat3) / zdeterm
+         
+         IF ( ABS( zdeli ) < zeps .AND. ABS( zdelj ) < zeps ) EXIT jiter_loop
+         
+         ziguess = ziguess + zdeli
+         zjguess = zjguess + zdelj
+
+         ! DJL prevent ziguess and zjguess from going outside the range
+         ! 0 to 1
+         ! prevents interpolated value going wrong
+         ! for example sea ice concentration gt 1
+         
+         IF ( ziguess < 0 ) ziguess = 0.0_wp
+         IF ( zjguess < 0 ) zjguess = 0.0_wp
+         IF ( ziguess > 1 ) ziguess = 1.0_wp
+         IF ( zjguess > 1 ) zjguess = 1.0_wp
+         
+      END DO jiter_loop
+       
+      IF ( jiter <= itermax ) THEN
+           
+         ! Successfully found i,j, now compute the weights
+
+         pbiwmm = ( 1.0_wp - ziguess ) * ( 1.0_wp - zjguess )
+         pbiwmp = ( 1.0_wp - ziguess ) *            zjguess
+         pbiwpm =            ziguess   * ( 1.0_wp - zjguess )
+         pbiwpp =            ziguess   *            zjguess
+         
+      ELSEIF ( jiter > itermax ) THEN
+            
+         IF(lwp) THEN
+            
+            WRITE(numout,*)'Obs lat/lon  : ',pphi, plam
+            WRITE(numout,*)'Grid lats    : ',pphimm, pphimp, pphipm, pphipp
+            WRITE(numout,*)'Grid lons    : ',plammm, plammp, plampm, plampp
+            WRITE(numout,*)'Current i,j  : ',ziguess, zjguess
+            WRITE(numout,*)'jiter        = ',jiter
+            WRITE(numout,*)'zeps         = ',zeps
+            WRITE(numout,*)'zdeli, zdelj = ',zdeli, zdelj
+            WRITE(numout,*)' Iterations for i,j exceed max iteration count!'
+            WRITE(numout,*)
+            
+            ldfail = .TRUE.
+
+         ENDIF
+         
+      ENDIF
+    
+   END SUBROUTINE bil_wgt
+
+   SUBROUTINE lu_invmat( pmatin, kdim, pmatou )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                   ***  ROUTINE lu_invmat  ***
+      !!
+      !! ** Purpose : Invert a matrix using LU decomposition.
+      !!
+      !! ** Method  : 
+      !! 
+      !! ** Action  :
+      !!
+      !! References : 
+      !!
+      !! History
+      !!      ! 02-11 (A. Weaver, N. Daget)
+      !!      ! 06-03 (A. Vidard)
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!      ! 06-11 (NEMOVAR task force) Fix declaration of zd.
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kdim             ! Array dimension
+      REAL(KIND=wp), DIMENSION(kdim,kdim), INTENT(IN) :: &
+         & pmatin 
+      REAL(KIND=wp), DIMENSION(kdim,kdim), INTENT(OUT) :: &
+         & pmatou 
+  
+      !! * Local declarations
+      INTEGER :: &
+         & ji, &
+         & jj
+      INTEGER, DIMENSION(kdim) :: &
+         & indx
+      REAL(KIND=wp), DIMENSION(kdim,kdim) :: &
+         & zmat
+      REAL(KIND=wp) :: &
+         & zd
+
+      ! Invert the matrix       
+      DO jj = 1, kdim
+         DO ji = 1, kdim
+            pmatou(ji,jj) = 0.0_wp
+            zmat(ji,jj) = pmatin(ji,jj)
+         END DO
+         pmatou(jj,jj) = 1.0_wp
+      END DO
+      CALL lu_decomp( zmat, kdim, kdim, indx, zd )
+      DO jj = 1, kdim
+         CALL lu_backsb( zmat, kdim, kdim, indx, pmatou(1,jj) )
+      END DO
+      
+   END SUBROUTINE lu_invmat
+
+   SUBROUTINE lu_decomp( pmatin, kdim1, kdim2, kindex, pflt )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                   ***  ROUTINE lu_decomp  ***
+      !!
+      !! ** Purpose : Compute the LU decomposition of a matrix
+      !!
+      !! ** Method  : 
+      !! 
+      !! ** Action  :
+      !!
+      !! References : 
+      !!
+      !! History
+      !!      ! 02-11 (A. Weaver, N. Daget)
+      !!      ! 06-03 (A. Vidard)
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+       
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kdim1, &   ! Array dimensions
+         & kdim2
+      INTEGER, DIMENSION(kdim1), INTENT(OUT) :: &
+         & kindex
+      REAL(KIND=wp), INTENT(OUT) :: &
+         & pflt
+      REAL(KIND=wp), DIMENSION(kdim2,kdim2), INTENT(INOUT) :: &
+         & pmatin 
+  
+      !! * Local declarations
+      INTEGER, PARAMETER :: &
+         & jpmax = 100
+      REAL(KIND=wp), PARAMETER :: &
+         & pptiny = 1.0e-20_wp
+      REAL(KIND=wp), DIMENSION(jpmax) :: &
+         & zvv
+      INTEGER :: &
+         & ji, &
+         & jj, &
+         & jk
+      INTEGER :: &
+         & imax
+      REAL(KIND=wp) :: &
+         & zsum,  &
+         & zdum,  &
+         & zaamax
+      
+      imax = -1 
+      ! Main computation
+      pflt = 1.0_wp
+      DO ji = 1, kdim1
+         zaamax = 0.0_wp
+         DO jj = 1, kdim1
+            IF ( ABS( pmatin(ji,jj) ) > zaamax ) zaamax = ABS( pmatin(ji,jj) )
+         END DO
+         IF ( zaamax == 0.0_wp ) THEN
+            CALL ctl_stop( 'singular matrix' )
+         ENDIF 
+         zvv(ji) = 1.0_wp / zaamax
+      END DO
+      DO jj = 1, kdim1
+         DO ji = 1, jj-1
+            zsum = pmatin(ji,jj)
+            DO jk = 1, ji-1
+	       zsum = zsum - pmatin(ji,jk) * pmatin(jk,jj)
+	    END DO
+            pmatin(ji,jj) = zsum
+         END DO
+         zaamax = 0.0_wp
+         DO ji = jj, kdim1
+            zsum = pmatin(ji,jj)
+            DO jk = 1, jj-1
+               zsum = zsum - pmatin(ji,jk) * pmatin(jk,jj)
+            END DO
+            pmatin(ji,jj) = zsum
+            zdum = zvv(ji) * ABS( zsum )
+            IF ( zdum >= zaamax ) THEN
+               imax = ji
+               zaamax = zdum
+            ENDIF
+	 END DO
+         IF ( jj /= imax ) THEN
+            DO jk = 1, kdim1
+               zdum = pmatin(imax,jk)
+               pmatin(imax,jk) = pmatin(jj,jk)
+               pmatin(jj,jk) = zdum
+	    END DO
+            pflt = -pflt
+            zvv(imax) = zvv(jj)
+         ENDIF
+         kindex(jj) = imax
+         IF ( pmatin(jj,jj) == 0.0_wp ) pmatin(jj,jj) = pptiny
+         IF ( jj /= kdim1 ) THEN
+            zdum = 1.0_wp / pmatin(jj,jj)
+            DO ji = jj+1, kdim1
+               pmatin(ji,jj) = pmatin(ji,jj) * zdum
+	    END DO
+         ENDIF
+      END DO
+     
+   END SUBROUTINE lu_decomp
+     
+   SUBROUTINE lu_backsb( pmat, kdim1, kdim2, kindex, pvect )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                   ***  ROUTINE lu_backsb  ***
+      !!
+      !! ** Purpose : Back substitution
+      !!
+      !! ** Method  : 
+      !! 
+      !! ** Action  :
+      !!
+      !! References : 
+      !!
+      !! History
+      !!      ! 02-11 (A. Weaver, N. Daget)
+      !!      ! 06-03 (A. Vidard)
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!-----------------------------------------------------------------------
+      
+      !! * Arguments
+      INTEGER, INTENT(IN) :: &
+         & kdim1, &     ! Array dimensions
+         & kdim2
+      INTEGER, DIMENSION(kdim1), INTENT(IN) :: &
+         & kindex
+      REAL(KIND=wp), DIMENSION(kdim1), INTENT(INOUT) :: &
+         & pvect
+      REAL(KIND=wp), DIMENSION(kdim2,kdim2), INTENT(IN) :: &
+         & pmat
+  
+      !! * Local declarations
+      INTEGER :: &
+         & ji,  &
+         & jii, &
+         & jj,  &
+         & jll
+      REAL(KIND=wp) :: &
+         & zsum
+
+      ! Main computation
+      jii = 0
+      DO ji = 1, kdim1
+         jll = kindex(ji)
+         zsum = pvect(jll)
+         pvect(jll) = pvect(ji)
+         IF ( jii /= 0 ) THEN
+            DO jj = jii, ji-1
+               zsum = zsum - pmat(ji,jj) * pvect(jj)
+            END DO
+         ELSEIF ( zsum /= 0.0_wp ) THEN
+            jii = ji
+         ENDIF
+         pvect(ji) = zsum
+      END DO
+      DO ji = kdim1, 1, -1
+         zsum = pvect(ji)
+         DO jj = ji+1, kdim1
+            zsum = zsum - pmat(ji,jj) * pvect(jj)
+         END DO
+         pvect(ji) = zsum / pmat(ji,ji)
+      END DO
+     
+   END SUBROUTINE lu_backsb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_z1d.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_z1d.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/obsinter_z1d.h90	(revision 14097)
@@ -0,0 +1,191 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE obs_int_z1d( kpk, kkco, k1dint, kdep, &
+      &                    pobsdep, pobsk, pobs2k,  &
+      &                    pobs, pdep, pobsmask )
+      !!---------------------------------------------------------------------
+      !!
+      !!                   ***  ROUTINE obs_int_z1d ***
+      !!
+      !! ** Purpose : Vertical interpolation to the observation point.
+      !!  
+      !! ** Method  : If k1dint = 0 then use linear interpolation.
+      !!              If k1dint = 1 then use cubic spline interpolation.
+      !! 
+      !! ** Action  :
+      !!
+      !! References :
+      !!
+      !! History
+      !!      ! 97-11 (A. Weaver, S. Ricci, N. Daget)
+      !!      ! 06-03 (G. Smith) Conversion to F90 for use with NEMOVAR
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!      ! 07-01 (K. Mogensen) Use profile rather than single level
+      !!---------------------------------------------------------------------
+
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kpk        ! Number of vertical levels
+      INTEGER, INTENT(IN) :: k1dint     ! 0 = linear; 1 = cubic spline interpolation 
+      INTEGER, INTENT(IN) :: kdep       ! Number of levels in profile
+      INTEGER, INTENT(IN), DIMENSION(kdep) :: &
+         & kkco                 ! Array indicies for interpolation
+      REAL(KIND=wp), INTENT(IN), DIMENSION(kdep) :: &
+         & pobsdep              ! Depth of the observation
+      REAL(KIND=wp), INTENT(IN), DIMENSION(kpk) :: &
+         & pobsk,  &            ! Model profile at a given (lon,lat)
+         & pobs2k, &            ! 2nd derivative of the interpolating function
+         & pdep,   &            ! Model depth array
+         & pobsmask             ! Vertical mask
+      REAL(KIND=wp), INTENT(OUT), DIMENSION(kdep) :: &
+         & pobs                 ! Model equivalent at observation point
+  
+      !! * Local declarations
+      REAL(KIND=wp) :: z1dm       ! Distance above and below obs to model grid points
+      REAL(KIND=wp) :: z1dp         
+      REAL(KIND=wp) :: zsum       ! Dummy variables for computation
+      REAL(KIND=wp) :: zsum2
+      INTEGER :: jdep             ! Observation depths loop variable
+    
+      !------------------------------------------------------------------------
+      ! Loop over all observation depths
+      !------------------------------------------------------------------------
+
+      DO jdep = 1, kdep
+
+         !---------------------------------------------------------------------
+         ! Initialization
+         !---------------------------------------------------------------------
+         z1dm = ( pdep(kkco(jdep)) - pobsdep(jdep)      )
+         z1dp = ( pobsdep(jdep)    - pdep(kkco(jdep)-1) )
+         IF ( pobsmask(kkco(jdep)) == 0.0_wp ) z1dp = 0.0_wp
+
+         zsum = z1dm + z1dp
+         
+         IF ( k1dint == 0 ) THEN
+
+            !-----------------------------------------------------------------
+            !  Linear interpolation
+            !-----------------------------------------------------------------
+            pobs(jdep) = (   z1dm * pobsk(kkco(jdep)-1) &
+               &           + z1dp * pobsk(kkco(jdep)  ) ) / zsum
+
+         ELSEIF ( k1dint == 1 ) THEN
+
+            !-----------------------------------------------------------------
+            ! Cubic spline interpolation
+            !-----------------------------------------------------------------
+            zsum2 = zsum * zsum
+            pobs(jdep)  = (  z1dm                             * pobsk (kkco(jdep)-1) &
+               &           + z1dp                             * pobsk (kkco(jdep)  ) &
+               &           + ( z1dm * ( z1dm * z1dm - zsum2 ) * pobs2k(kkco(jdep)-1) &
+               &           +   z1dp * ( z1dp * z1dp - zsum2 ) * pobs2k(kkco(jdep)  ) &
+               &             ) / 6.0_wp                                              &
+               &          ) / zsum
+
+         ENDIF
+      END DO
+
+   END SUBROUTINE obs_int_z1d
+
+   SUBROUTINE obs_int_z1d_spl( kpk, pobsk, pobs2k, &
+      &                        pdep, pobsmask )
+      !!--------------------------------------------------------------------
+      !!
+      !!                  *** ROUTINE obs_int_z1d_spl ***
+      !!
+      !! ** Purpose : Compute the local vector of vertical second-derivatives 
+      !!              of the interpolating function used with a cubic spline.
+      !!  
+      !! ** Method  : 
+      !! 
+      !!    Top and bottom boundary conditions on the 2nd derivative are
+      !!    set to zero.
+      !!
+      !! ** Action  :
+      !!
+      !! References : 
+      !!
+      !! History
+      !!      ! 01-11 (A. Weaver, S. Ricci, N. Daget)
+      !!      ! 06-03 (G. Smith) Conversion to F90 for use with NEMOVAR
+      !!      ! 06-10 (A. Weaver) Cleanup
+      !!----------------------------------------------------------------------
+     
+      !! * Arguments
+      INTEGER, INTENT(IN) :: kpk               ! Number of vertical levels
+      REAL(KIND=wp), INTENT(IN), DIMENSION(kpk) :: &
+         & pobsk, &          ! Model profile at a given (lon,lat)
+         & pdep,  &          ! Model depth array
+         & pobsmask          ! Vertical mask
+      REAL(KIND=wp), INTENT(OUT), DIMENSION(kpk) :: &
+         & pobs2k            ! 2nd derivative of the interpolating function
+  
+      !! * Local declarations
+      INTEGER :: jk
+      REAL(KIND=wp) :: za
+      REAL(KIND=wp) :: zb
+      REAL(KIND=wp) :: zc
+      REAL(KIND=wp) :: zpa
+      REAL(KIND=wp) :: zkm
+      REAL(KIND=wp) :: zkp
+      REAL(KIND=wp) :: zk
+      REAL(KIND=wp), DIMENSION(kpk-1) :: &
+         & zs, &
+         & zp, &
+         & zu, &
+         & zv
+
+      !-----------------------------------------------------------------------
+      ! Matrix initialisation
+      !-----------------------------------------------------------------------
+      zs(1) =  0.0_wp
+      zp(1) =  0.0_wp
+      zv(1) = -0.5_wp
+      DO jk = 2, kpk-1
+         zs(jk) =  ( pdep(jk  ) - pdep(jk-1) ) &
+            &    / ( pdep(jk+1) - pdep(jk-1) )
+         zp(jk) = zs(jk) * zv(jk-1) + 2.0_wp
+         zv(jk) = ( zs(jk) - 1.0_wp ) / zp(jk)
+      END DO
+ 
+      !-----------------------------------------------------------------------
+      ! Solution of the tridiagonal system
+      !-----------------------------------------------------------------------
+ 
+      ! Top boundary condition
+      zu(1) = 0.0_wp
+ 
+      DO jk = 2, kpk-1
+         za = pdep(jk+1) - pdep(jk-1)
+         zb = pdep(jk+1) - pdep(jk  )
+         zc = pdep(jk  ) - pdep(jk-1)
+ 
+         zpa = 6.0_wp / ( zp(jk) * za )
+         zkm = zpa / zc
+         zkp = zpa / zb
+         zk  = - ( zkm + zkp )
+  
+         zu(jk) =  pobsk(jk+1) * zkp  &
+            &    + pobsk(jk  ) * zk   &
+            &    + pobsk(jk-1) * zkm  &
+            &    + zu(jk-1) * ( -zs(jk) / zp(jk) )
+      END DO
+ 
+      !-----------------------------------------------------------------------
+      ! Second derivative
+      !-----------------------------------------------------------------------
+      pobs2k(kpk) = 0.0_wp
+ 
+      ! Bottom boundary condition
+      DO jk = kpk-1, 1, -1
+         pobs2k(jk) = zv(jk) * pobs2k(jk+1) + zu(jk)
+         IF ( pobsmask(jk+1) == 0.0_wp ) pobs2k(jk) = 0.0_wp
+      END DO
+ 
+  END SUBROUTINE obs_int_z1d_spl
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/str_c_to_for.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/str_c_to_for.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/OBS/str_c_to_for.h90	(revision 14097)
@@ -0,0 +1,39 @@
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE str_c_to_for( cd_str )
+      !!---------------------------------------------------------------------
+      !!   
+      !!                     *** ROUTINE str_c_to_for ***
+      !! 
+      !! ** Purpose : Loop over a string and replace all non-printable
+      !!              ASCII characters with spaces assuming English 
+      !!              characters only
+      !!
+      !! ** Method  : Loop over a string and replace all non-printable
+      !!              ASCII characters with spaces assuming English 
+      !!              characters only
+      !!
+      !! ** Action  : 
+      !! 
+      !! History :  
+      !!        ! : 06-05 (K. Mogensen) Original
+      !!        ! : 06-05 (A. Vidard) Cleaning up
+      !!        ! : 06-10 (A. Weaver) More cleaning
+      !!---------------------------------------------------------------------
+      !! * Arguments
+      CHARACTER(LEN=*), INTENT(INOUT) :: cd_str
+
+      !! * Local declarations
+      INTEGER :: &
+         & ji
+
+      DO ji = 1, LEN( cd_str )
+         IF (     ( IACHAR( cd_str(ji:ji) ) > 128 ) &
+            & .OR.( IACHAR( cd_str(ji:ji) ) < 32  ) ) cd_str(ji:ji) = ' '
+      END DO
+
+   END SUBROUTINE str_c_to_for
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/README.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../doc/rst/source/coupling.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cpl_oasis3.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cpl_oasis3.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cpl_oasis3.F90	(revision 14097)
@@ -0,0 +1,625 @@
+MODULE cpl_oasis3
+   !!======================================================================
+   !!                    ***  MODULE cpl_oasis  ***
+   !! Coupled O/A : coupled ocean-atmosphere case using OASIS3-MCT
+   !!=====================================================================
+   !! History :  1.0  !  2004-06  (R. Redler, NEC Laboratories Europe, Germany) Original code
+   !!             -   !  2004-11  (R. Redler, NEC Laboratories Europe; N. Keenlyside, W. Park, IFM-GEOMAR, Germany) revision
+   !!             -   !  2004-11  (V. Gayler, MPI M&D) Grid writing
+   !!            2.0  !  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
+   !!            3.4  !  2011-11  (C. Harris) Changes to allow mutiple category fields
+   !!            3.6  !  2014-11  (S. Masson) OASIS3-MCT
+   !!----------------------------------------------------------------------
+   
+   !!----------------------------------------------------------------------
+   !!   'key_oasis3'                    coupled Ocean/Atmosphere via OASIS3-MCT
+   !!   'key_oa3mct_v3'                 to be added for OASIS3-MCT version 3
+   !!----------------------------------------------------------------------
+   !!   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
+   USE mod_oasis                    ! OASIS3-MCT module
+#endif
+   USE par_oce                      ! ocean parameters
+   USE dom_oce                      ! ocean space and time domain
+   USE in_out_manager               ! I/O manager
+   USE lbclnk                       ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   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 oasis_init_comp
+   INTEGER                    ::   nerror            ! return error code
+#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                    ::   nrcv         ! total number of fields received 
+   INTEGER                    ::   nsnd         ! total number of fields sent 
+   INTEGER                    ::   ncplmodel    ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
+   INTEGER, PUBLIC, PARAMETER ::   nmaxfld=60   ! 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
+   LOGICAL, PARAMETER         ::   ltmp_wapatch = .TRUE.   ! patch to restore wraparound rows in cpl_send, cpl_rcv, cpl_define  
+   INTEGER                    ::   nldi_save, nlei_save
+   INTEGER                    ::   nldj_save, nlej_save
+   
+   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, 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
+
+   TYPE(FLD_CPL), DIMENSION(nmaxfld), PUBLIC ::   srcv, ssnd   !: Coupling fields
+
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   exfld   ! Temporary buffer for receiving
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE cpl_init( cd_modname, kl_comm )
+      !!-------------------------------------------------------------------
+      !!             ***  ROUTINE cpl_init  ***
+      !!
+      !! ** Purpose :   Initialize coupled mode communication for ocean
+      !!    exchange between AGCM, OGCM and COUPLER. (OASIS3 software)
+      !!
+      !! ** Method  :   OASIS3 MPI communication 
+      !!--------------------------------------------------------------------
+      CHARACTER(len = *), INTENT(in   ) ::   cd_modname   ! model name as set in namcouple file
+      INTEGER           , INTENT(  out) ::   kl_comm      ! local communicator of the model
+      !!--------------------------------------------------------------------
+
+      ! WARNING: No write in numout in this routine
+      !============================================
+
+      !------------------------------------------------------------------
+      ! 1st Initialize the OASIS system for the application
+      !------------------------------------------------------------------
+      CALL oasis_init_comp ( ncomp_id, TRIM(cd_modname), nerror )
+      IF ( nerror /= OASIS_Ok ) &
+         CALL oasis_abort (ncomp_id, 'cpl_init', 'Failure in oasis_init_comp')
+
+      !------------------------------------------------------------------
+      ! 3rd Get an MPI communicator for OPA local communication
+      !------------------------------------------------------------------
+
+      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_define  ***
+      !!
+      !! ** Purpose :   Define grid and field information for ocean
+      !!    exchange between AGCM, OGCM and COUPLER. (OASIS3 software)
+      !!
+      !! ** Method  :   OASIS3 MPI communication 
+      !!--------------------------------------------------------------------
+      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(4)    ! shape of arrays passed to PSMILe
+      INTEGER :: ji,jc,jm       ! local loop indicees
+      CHARACTER(LEN=64) :: zclname
+      CHARACTER(LEN=2) :: cli2
+      !!--------------------------------------------------------------------
+
+      ! patch to restore wraparound rows in cpl_send, cpl_rcv, cpl_define
+      IF ( ltmp_wapatch ) THEN
+         nldi_save = nldi   ;   nlei_save = nlei
+         nldj_save = nldj   ;   nlej_save = nlej
+         IF( nimpp           ==      1 ) nldi = 1
+         IF( nimpp + jpi - 1 == jpiglo ) nlei = jpi
+         IF( njmpp           ==      1 ) nldj = 1
+         IF( njmpp + jpj - 1 == jpjglo ) nlej = jpj
+      ENDIF 
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'cpl_define : initialization in coupled ocean/atmosphere case'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*)
+
+      ncplmodel = kcplmodel
+      IF( kcplmodel > nmaxcpl ) THEN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'ncplmodel is larger than nmaxcpl, increase nmaxcpl')   ;   RETURN
+      ENDIF
+
+      nrcv = krcv
+      IF( nrcv > nmaxfld ) THEN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'nrcv is larger than nmaxfld, increase nmaxfld')   ;   RETURN
+      ENDIF
+
+      nsnd = ksnd
+      IF( nsnd > nmaxfld ) THEN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'nsnd is larger than nmaxfld, increase nmaxfld')   ;   RETURN
+      ENDIF
+      !
+      ! ... Define the shape for the area that excludes the halo
+      !     For serial configuration (key_mpp_mpi not being active)
+      !     nl* is set to the global values 1 and jp*glo.
+      !
+      ishape(1) = 1
+      ishape(2) = nlei-nldi+1
+      ishape(3) = 1
+      ishape(4) = nlej-nldj+1
+      !
+      ! ... Allocate memory for data exchange
+      !
+      ALLOCATE(exfld(nlei-nldi+1, nlej-nldj+1), stat = nerror)
+      IF( nerror > 0 ) THEN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'Failure in allocating exfld')   ;   RETURN
+      ENDIF
+      !
+      ! -----------------------------------------------------------------
+      ! ... Define the partition 
+      ! -----------------------------------------------------------------
+      
+      paral(1) = 2                                              ! box partitioning
+      paral(2) = jpiglo * (nldj-1+njmpp-1) + (nldi-1+nimpp-1)   ! NEMO lower left corner global offset    
+      paral(3) = nlei-nldi+1                                    ! local extent in i 
+      paral(4) = nlej-nldj+1                                    ! local extent in j
+      paral(5) = jpiglo                                         ! global extent in x
+      
+      IF( ln_ctl ) THEN
+         WRITE(numout,*) ' multiexchg: paral (1:5)', paral
+         WRITE(numout,*) ' multiexchg: jpi, jpj =', jpi, jpj
+         WRITE(numout,*) ' multiexchg: nldi, nlei, nimpp =', nldi, nlei, nimpp
+         WRITE(numout,*) ' multiexchg: nldj, nlej, njmpp =', nldj, nlej, njmpp
+      ENDIF
+   
+      CALL oasis_def_partition ( id_part, paral, nerror, jpiglo*jpjglo )
+      !
+      ! ... Announce send variables. 
+      !
+      ssnd(:)%ncplmodel = kcplmodel
+      !
+      DO ji = 1, ksnd
+         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
+               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, 1 /),   &
+                     &                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
+      END DO
+      !
+      ! ... 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
+               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, 1 /),   &
+                     &                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
+      END DO
+      
+      !------------------------------------------------------------------
+      ! End of definition phase
+      !------------------------------------------------------------------
+      !     
+#if defined key_agrif
+      IF( agrif_fixed() == Agrif_Nb_Fine_Grids() ) THEN
+#endif
+      CALL oasis_enddef(nerror)
+      IF( nerror /= OASIS_Ok )   CALL oasis_abort ( ncomp_id, 'cpl_define', 'Failure in oasis_enddef')
+#if defined key_agrif
+      ENDIF
+#endif
+      !
+      IF ( ltmp_wapatch ) THEN
+         nldi = nldi_save   ;   nlei = nlei_save
+         nldj = nldj_save   ;   nlej = nlej_save
+      ENDIF
+   END SUBROUTINE cpl_define
+   
+   
+   SUBROUTINE cpl_snd( kid, kstep, pdata, kinfo )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE cpl_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 index in the array
+      INTEGER                   , INTENT(  out) ::   kinfo     ! OASIS3 info argument
+      INTEGER                   , INTENT(in   ) ::   kstep     ! ocean time-step in seconds
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdata
+      !!
+      INTEGER                                   ::   jc,jm     ! local loop index
+      !!--------------------------------------------------------------------
+      ! patch to restore wraparound rows in cpl_send, cpl_rcv, cpl_define
+      IF ( ltmp_wapatch ) THEN
+         nldi_save = nldi   ;   nlei_save = nlei
+         nldj_save = nldj   ;   nlej_save = nlej
+         IF( nimpp           ==      1 ) nldi = 1
+         IF( nimpp + jpi - 1 == jpiglo ) nlei = jpi
+         IF( njmpp           ==      1 ) nldj = 1
+         IF( njmpp + jpj - 1 == jpjglo ) nlej = jpj
+      ENDIF
+      !
+      ! snd data to OASIS3
+      !
+      DO jc = 1, ssnd(kid)%nct
+         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(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '     -     Sum value is ',    SUM(pdata(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '****************'
+                  ENDIF
+               ENDIF
+               
+            ENDIF
+            
+         ENDDO
+      ENDDO
+      IF ( ltmp_wapatch ) THEN
+         nldi = nldi_save   ;   nlei = nlei_save
+         nldj = nldj_save   ;   nlej = nlej_save
+      ENDIF
+      !
+    END SUBROUTINE cpl_snd
+
+
+   SUBROUTINE cpl_rcv( kid, kstep, pdata, pmask, kinfo )
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE cpl_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 index 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
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pmask     ! coupling mask
+      INTEGER                   , INTENT(  out) ::   kinfo     ! OASIS3 info argument
+      !!
+      INTEGER                                   ::   jc,jm     ! local loop index
+      LOGICAL                                   ::   llaction, llfisrt
+      !!--------------------------------------------------------------------
+      ! patch to restore wraparound rows in cpl_send, cpl_rcv, cpl_define
+      IF ( ltmp_wapatch ) THEN
+         nldi_save = nldi   ;   nlei_save = nlei
+         nldj_save = nldj   ;   nlej_save = nlej
+      ENDIF
+      !
+      ! receive local data from OASIS3 on every process
+      !
+      kinfo = OASIS_idle
+      !
+      DO jc = 1, srcv(kid)%nct
+         IF ( ltmp_wapatch ) THEN
+            IF( nimpp           ==      1 ) nldi = 1
+            IF( nimpp + jpi - 1 == jpiglo ) nlei = jpi
+            IF( njmpp           ==      1 ) nldj = 1
+            IF( njmpp + jpj - 1 == jpjglo ) nlej = jpj
+         ENDIF
+         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(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '     -     Sum value is ',    SUM(pdata(nldi:nlei,nldj:nlej,jc))
+                     WRITE(numout,*) '****************'
+                  ENDIF
+                  
+               ENDIF
+               
+            ENDIF
+            
+         ENDDO
+
+         IF ( ltmp_wapatch ) THEN
+            nldi = nldi_save   ;   nlei = nlei_save
+            nldj = nldj_save   ;   nlej = nlej_save
+         ENDIF
+         !--- Fill the overlap areas and extra hallows (mpp)
+         !--- check periodicity conditions (all cases)
+         IF( .not. llfisrt ) THEN
+            CALL lbc_lnk( 'cpl_oasis3', pdata(:,:,jc), srcv(kid)%clgrid, srcv(kid)%nsgn )   
+         ENDIF
+ 
+      ENDDO
+      !
+   END SUBROUTINE cpl_rcv
+
+
+   INTEGER FUNCTION cpl_freq( cdfieldname )  
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE cpl_freq  ***
+      !!
+      !! ** Purpose : - send back the coupling frequency for a particular field
+      !!----------------------------------------------------------------------
+      CHARACTER(len = *), INTENT(in) ::   cdfieldname    ! field name as set in namcouple file
+      !!
+      INTEGER               :: id
+      INTEGER               :: info
+      INTEGER, DIMENSION(1) :: itmp
+      INTEGER               :: ji,jm     ! local loop index
+      INTEGER               :: mop
+      !!----------------------------------------------------------------------
+      cpl_freq = 0   ! defaut definition
+      id = -1        ! defaut definition
+      !
+      DO ji = 1, nsnd
+         IF (ssnd(ji)%laction ) THEN
+            DO jm = 1, ncplmodel
+               IF( ssnd(ji)%nid(1,jm) /= -1 ) THEN
+                  IF( TRIM(cdfieldname) == TRIM(ssnd(ji)%clname) ) THEN
+                     id = ssnd(ji)%nid(1,jm)
+                     mop = OASIS_Out
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDIF
+      ENDDO
+      DO ji = 1, nrcv
+         IF (srcv(ji)%laction ) THEN
+            DO jm = 1, ncplmodel
+               IF( srcv(ji)%nid(1,jm) /= -1 ) THEN
+                  IF( TRIM(cdfieldname) == TRIM(srcv(ji)%clname) ) THEN
+                     id = srcv(ji)%nid(1,jm)
+                     mop = OASIS_In
+                  ENDIF
+               ENDIF
+            ENDDO
+         ENDIF
+      ENDDO
+      !
+      IF( id /= -1 ) THEN
+#if ! defined key_oa3mct_v1v2
+         CALL oasis_get_freqs(id, mop, 1, itmp, info)
+#else
+         CALL oasis_get_freqs(id,      1, itmp, info)
+#endif
+         cpl_freq = itmp(1)
+      ENDIF
+      !
+   END FUNCTION cpl_freq
+
+
+   SUBROUTINE cpl_finalize
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE cpl_finalize  ***
+      !!
+      !! ** Purpose : - Finalizes the coupling. If MPI_init has not been
+      !!      called explicitly before cpl_init it will also close
+      !!      MPI communication.
+      !!----------------------------------------------------------------------
+      !
+      DEALLOCATE( exfld )
+      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,k4)
+      INTEGER     , INTENT(  out) ::  k1,k3
+      INTEGER     , INTENT(in   ) ::  k2(5)
+      INTEGER     , INTENT(in   ) ::  k4
+      k1 = k2(1) ; k3 = k2(5)+k4
+      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,k5,k2,k3,k4)
+      INTEGER              , INTENT(in   ) ::  k1,k2
+      INTEGER, DIMENSION(1), INTENT(  out) ::  k3
+      INTEGER              , INTENT(  out) ::  k4,k5
+      k3(1) = k1 ; k4 = k2 ; k5 = 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
+
+   !!=====================================================================
+END MODULE cpl_oasis3
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cyclone.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cyclone.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/cyclone.F90	(revision 14097)
@@ -0,0 +1,275 @@
+MODULE cyclone
+   !!======================================================================
+   !!                       ***  MODULE  cyclone  ***
+   !! add the Tropical Cyclones along tracks to the surface wind forcing
+   !!                 
+   !!======================================================================
+   !! History : 3.3  ! 2010-05  (E Vincent, G Madec, S Masson)  Original code
+   !!----------------------------------------------------------------------
+
+#if defined key_cyclone
+   !!----------------------------------------------------------------------
+   !!  'key_cyclone' : key option add Tropical Cyclones in the wind forcing
+   !!----------------------------------------------------------------------
+   !!   wnd_cyc      : 1 module subroutine
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and active tracers
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE dom_oce         ! ocean space domain variables
+   USE phycst          ! physical constant
+   USE fldread         ! read input fields
+   USE in_out_manager  ! I/O manager
+   USE geo2ocean       ! tools for projection on ORCA grid
+   USE lib_mpp       
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   wnd_cyc   ! routine called in sbcblk.F90 module
+
+   INTEGER , PARAMETER ::   jp_is1  = 1   ! index of presence 1 or absence 0 of a TC record
+   INTEGER , PARAMETER ::   jp_lon  = 2   ! index of longitude for present TCs
+   INTEGER , PARAMETER ::   jp_lat  = 3   ! index of latitude  for present TCs
+   INTEGER , PARAMETER ::   jp_vmax = 4   ! index of max wind  for present TCs
+   INTEGER , PARAMETER ::   jp_pres = 5   ! index of eye-pres  for present TCs
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf   ! structure of input fields (file informations, fields read)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE wnd_cyc( kt, pwnd_i, pwnd_j )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE wnd_cyc  ***
+      !!
+      !! ** Purpose :  Add cyclone winds on the ORCA grid
+      !!
+      !! ** Action  : - open TC data, find TCs for the current timestep
+      !!              - for each potential TC, add the winds on the grid
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in)                      ::   kt       ! time step index 
+      REAL(wp), INTENT(out), DIMENSION(jpi,jpj) ::   pwnd_i   ! wind speed i-components at T-point ORCA direction
+      REAL(wp), INTENT(out), DIMENSION(jpi,jpj) ::   pwnd_j   ! wind speed j-components at T-point ORCA direction
+      ! 
+      !!
+      INTEGER  ::   ji, jj , jtc        ! loop arguments
+      INTEGER  ::   ierror              ! loop arguments
+      INTEGER  ::   vortex=1            ! vortex shape to be used: 0=Holland 1=Willoughby
+      REAL(wp) ::   zrout1=1.5e6        ! distance from center where we begin to kill vortex (m)
+      REAL(wp) ::   zrout2=2.5e6        ! distance from center where we bring vortex to zero (m)
+      REAL(wp) ::   zb                  ! power in Holland vortex shape
+      REAL(wp) ::   zA                  ! shape parameter in Willoughby vortex : A transtion between first and second outter exp
+      REAL(wp) ::   zn                  ! shape parameter in Willoughby vortex : n power law in the eye
+      REAL(wp) ::   zXX1                ! shape parameter in Willoughby vortex : decay length second outter exponential
+      REAL(wp) ::   zXX2                ! shape parameter in Willoughby vortex : decay length first  outter exponential
+      REAL(wp) ::   zztmp               ! temporary 
+      REAL(wp) ::   zzrglam, zzrgphi    ! temporary 
+      REAL(wp) ::   ztheta              ! azimuthal angle
+      REAL(wp) ::   zdist               ! dist to the TC center
+      REAL(wp) ::   zhemi               ! 1 for NH ;  -1 for SH
+      REAL(wp) ::   zinfl               ! clim inflow angle in TCs
+      REAL(wp) ::   zrmw                ! mean radius of Max wind of a tropical cyclone (Willoughby 2004) [m]
+      REAL(wp) ::   zwnd_r, zwnd_t      ! radial and tangential components of the wind
+      REAL(wp) ::   zvmax               ! timestep interpolated vmax
+      REAL(wp) ::   zrlon, zrlat        ! temporary 
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwnd_x, zwnd_y   ! zonal and meridional components of the wind
+      REAL(wp), DIMENSION(14,5)    ::   ztct                ! tropical cyclone track data at kt
+      !
+      CHARACTER(len=100) ::  cn_dir            ! Root directory for location of files
+      TYPE(FLD_N), DIMENSION(1) ::   slf_i     ! array of namelist informations on the TC position
+      TYPE(FLD_N) ::   sn_tc                   ! informations about the fields to be read
+      !!--------------------------------------------------------------------
+
+      !                                         ! ====================== !
+      IF( kt == nit000 ) THEN                   !  First call kt=nit000  !
+         !                                      ! ====================== !
+         ! 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   ! land/sea mask !
+         !          !    name     !  (hours)  !   name    !   (T/F)    !  (T/F)  !  'monthly'  ! filename ! pairs      ! filename      !
+         sn_tc = FLD_N( 'tc_track',     6     ,  'tc'     ,  .true.    , .false. ,   'yearly'  , ''       , ''         , ''            )
+         !
+         !  Namelist is read in namsbc_blk
+         ! set sf structure
+         ALLOCATE( sf(1), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'wnd_cyc: unable to allocate sf structure' )   ;   RETURN
+         ENDIF
+         ALLOCATE( sf(1)%fnow(14,5,1) )
+         ALLOCATE( sf(1)%fdta(14,5,1,2) )
+         slf_i(1) = sn_tc
+         !
+         ! fill sf with slf_i and control print
+         CALL fld_fill( sf, slf_i, cn_dir, 'sbc_blk_tc', 'tropical cyclone track', 'namsbc_tc' )
+         !
+      ENDIF
+
+
+      !       Interpolation of lon lat vmax... at the current timestep
+      !       ***************************************************************
+
+      CALL fld_read( kt, nn_fsbc, sf )                   ! input fields provided at the current time-step
+
+      ztct(:,:) = sf(1)%fnow(:,:,1)
+
+      !       Add TC wind on the grid
+      !       ***************************************************************
+
+      zwnd_x(:,:) = 0.e0  
+      zwnd_y(:,:) = 0.e0 
+      
+      DO jtc = 1, 14
+         !
+         IF( ztct(jtc,jp_is1) == 1 ) THEN                ! cyclone is defined in this slot ? yes--> begin
+
+            zvmax =       ztct(jtc,jp_vmax)
+            zrlon = rad * ztct(jtc,jp_lon )
+            zrlat = rad * ztct(jtc,jp_lat )
+            zhemi = SIGN( 1. , zrlat )
+            zinfl = 15.* rad                             ! clim inflow angle in Tropical Cyclones
+         IF ( vortex == 0 ) THEN
+
+            ! Vortex Holland reconstruct wind at each lon-lat position
+            ! ********************************************************
+            zrmw = 51.6 * EXP( -0.0223*zvmax + 0.0281* ABS( ztct(jtc,jp_lat) ) ) * 1000.
+            ! climatological ZRMW of cyclones as a function of wind and latitude (Willoughby 2004)             
+            ! zb = 1.0036 + 0.0173 * zvmax - 0.0313 * LOG(zrmw/1000.) + 0.0087 * ABS( ztct(jtc,jp_lat) ) 
+            ! fitted B parameter (Willoughby 2004)
+            zb = 2.
+
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+
+                  ! calc distance between TC center and any point following great circle
+                  ! source : http://www.movable-type.co.uk/scripts/latlong.html
+                  zzrglam = rad * glamt(ji,jj) - zrlon
+                  zzrgphi = rad * gphit(ji,jj)
+                  zdist = ra * ACOS(  SIN( zrlat ) * SIN( zzrgphi )   &
+                     &              + COS( zrlat ) * COS( zzrgphi ) * COS( zzrglam ) )
+
+                 IF (zdist < zrout2) THEN ! calculation of wind only to a given max radius
+                  ! shape of the wind profile
+                  zztmp = ( zrmw / ( zdist + 1.e-12 ) )**zb
+                  zztmp =  zvmax * SQRT( zztmp * EXP(1. - zztmp) )    
+
+                  IF (zdist > zrout1) THEN ! bring to zero between r_out1 and r_out2
+                     zztmp = zztmp * ( (zrout2-zdist)*1.e-6 )
+                  ENDIF
+
+                  ! !!! KILL EQ WINDS
+                  ! IF (SIGN( 1. , zrlat ) /= zhemi) THEN
+                  !    zztmp = 0.                              ! winds in other hemisphere
+                  !    IF (ABS(gphit(ji,jj)) <= 5.) zztmp=0.   ! kill between 5N-5S
+                  ! ENDIF
+                  ! IF (ABS(gphit(ji,jj)) <= 10. .and. ABS(gphit(ji,jj)) > 5.) THEN
+                  !    zztmp = zztmp * ( 1./5. * (ABS(gphit(ji,jj)) - 5.) ) 
+                  !    !linear to zero between 10 and 5
+                  ! ENDIF
+                  ! !!! / KILL EQ
+
+                  IF (ABS(gphit(ji,jj)) >= 55.) zztmp = 0. ! kill weak spurious winds at high latitude
+
+                  zwnd_t =   COS( zinfl ) * zztmp    
+                  zwnd_r = - SIN( zinfl ) * zztmp
+
+                  ! Project radial-tangential components on zonal-meridional components
+                  ! -------------------------------------------------------------------
+                  
+                  ! ztheta = azimuthal angle of the great circle between two points
+                  zztmp = COS( zrlat ) * SIN( zzrgphi ) &
+                     &  - SIN( zrlat ) * COS( zzrgphi ) * COS( zzrglam )
+                  ztheta = ATAN2(        COS( zzrgphi ) * SIN( zzrglam ) , zztmp )
+
+                  zwnd_x(ji,jj) = zwnd_x(ji,jj) - zhemi * COS(ztheta)*zwnd_t + SIN(ztheta)*zwnd_r
+                  zwnd_y(ji,jj) = zwnd_y(ji,jj) + zhemi * SIN(ztheta)*zwnd_t + COS(ztheta)*zwnd_r
+                 ENDIF
+               END DO
+            END DO
+         
+         ELSE IF ( vortex == 1 ) THEN
+
+            ! Vortex Willoughby reconstruct wind at each lon-lat position
+            ! ***********************************************************
+            zrmw = 46.4 * EXP( -0.0155*zvmax + 0.0169* ABS( ztct(jtc,jp_lat) ) )*1000.
+            ! climatological ZRMW of cyclones as a function of wind and latitude (Willoughby 2006)
+            zXX2 = 25.*1000.                                              ! 25km fixed "near-eye" exponential decay
+            zXX1 = ( 287.6  - 1.942 *zvmax + 7.799 *LOG(zrmw/1000.) + 1.819 *ABS( ztct(jtc,jp_lat) ) )*1000.    
+            zn   =   2.1340 + 0.0077*zvmax - 0.4522*LOG(zrmw/1000.) - 0.0038*ABS( ztct(jtc,jp_lat) )            
+            zA   =   0.5913 + 0.0029*zvmax - 0.1361*LOG(zrmw/1000.) - 0.0042*ABS( ztct(jtc,jp_lat) )  
+            IF (zA < 0) THEN 
+               zA=0
+            ENDIF           
+        
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                                  
+                  zzrglam = rad * glamt(ji,jj) - zrlon
+                  zzrgphi = rad * gphit(ji,jj)
+                  zdist = ra * ACOS(  SIN( zrlat ) * SIN( zzrgphi )   &
+                     &              + COS( zrlat ) * COS( zzrgphi ) * COS( zzrglam ) )
+
+                 IF (zdist < zrout2) THEN ! calculation of wind only to a given max radius
+               
+                  ! shape of the wind profile                     
+                  IF (zdist <= zrmw) THEN     ! inside the Radius of Maximum Wind
+                     zztmp  = zvmax * (zdist/zrmw)**zn
+                  ELSE 
+                     zztmp  = zvmax * ( (1-zA) * EXP(- (zdist-zrmw)/zXX1 ) + zA * EXP(- (zdist-zrmw)/zXX2 ) )
+                  ENDIF
+
+                  IF (zdist > zrout1) THEN ! bring to zero between r_out1 and r_out2
+                     zztmp = zztmp * ( (zrout2-zdist)*1.e-6 )
+                  ENDIF
+
+                  ! !!! KILL EQ WINDS
+                  ! IF (SIGN( 1. , zrlat ) /= zhemi) THEN
+                  !    zztmp = 0.                              ! winds in other hemisphere
+                  !    IF (ABS(gphit(ji,jj)) <= 5.) zztmp=0.   ! kill between 5N-5S
+                  ! ENDIF
+                  ! IF (ABS(gphit(ji,jj)) <= 10. .and. ABS(gphit(ji,jj)) > 5.) THEN
+                  !    zztmp = zztmp * ( 1./5. * (ABS(gphit(ji,jj)) - 5.) ) 
+                  !    !linear to zero between 10 and 5
+                  ! ENDIF
+                  ! !!! / KILL EQ
+
+                  IF (ABS(gphit(ji,jj)) >= 55.) zztmp = 0. ! kill weak spurious winds at high latitude
+
+                  zwnd_t =   COS( zinfl ) * zztmp    
+                  zwnd_r = - SIN( zinfl ) * zztmp
+
+                  ! Project radial-tangential components on zonal-meridional components
+                  ! -------------------------------------------------------------------
+                  
+                  ! ztheta = azimuthal angle of the great circle between two points
+                  zztmp = COS( zrlat ) * SIN( zzrgphi ) &
+                     &  - SIN( zrlat ) * COS( zzrgphi ) * COS( zzrglam )
+                  ztheta = ATAN2(        COS( zzrgphi ) * SIN( zzrglam ) , zztmp )
+
+                  zwnd_x(ji,jj) = zwnd_x(ji,jj) - zhemi * COS(ztheta)*zwnd_t + SIN(ztheta)*zwnd_r
+                  zwnd_y(ji,jj) = zwnd_y(ji,jj) + zhemi * SIN(ztheta)*zwnd_t + COS(ztheta)*zwnd_r
+                  
+                 ENDIF
+               END DO
+            END DO
+         ENDIF                                         ! / vortex Holland or Wiloughby
+         ENDIF                                           ! / cyclone is defined in this slot ? yes--> begin
+      END DO ! / end simultaneous cyclones loop
+
+      CALL rot_rep ( zwnd_x, zwnd_y, 'T', 'en->i', pwnd_i ) !rotation of components on ORCA grid
+      CALL rot_rep ( zwnd_x, zwnd_y, 'T', 'en->j', pwnd_j ) !rotation of components on ORCA grid
+
+   END SUBROUTINE wnd_cyc
+
+#endif
+
+   !!======================================================================
+END MODULE cyclone
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/fldread.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/fldread.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/fldread.F90	(revision 14097)
@@ -0,0 +1,1762 @@
+MODULE fldread
+   !!======================================================================
+   !!                       ***  MODULE  fldread  ***
+   !! Ocean forcing:  read input field for surface boundary condition
+   !!=====================================================================
+   !! History :  2.0  !  2006-06  (S. Masson, G. Madec)  Original code
+   !!            3.0  !  2008-05  (S. Alderson)  Modified for Interpolation in memory from input grid to model grid
+   !!            3.4  !  2013-10  (D. Delrosso, P. Oddo)  suppression of land point prior to interpolation
+   !!                 !  12-2015  (J. Harle) Adding BDY on-the-fly interpolation
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   fld_read      : read input fields used for the computation of the surface boundary condition
+   !!   fld_init      : initialization of field read
+   !!   fld_rec       : determined the record(s) to be read
+   !!   fld_get       : read the data
+   !!   fld_map       : read global data from file and map onto local data using a general mapping (use for open boundaries)
+   !!   fld_rot       : rotate the vector fields onto the local grid direction
+   !!   fld_clopn     : update the data file name and close/open the files
+   !!   fld_fill      : fill the data structure with the associated information read in namelist
+   !!   wgt_list      : manage the weights used for interpolation
+   !!   wgt_print     : print the list of known weights
+   !!   fld_weight    : create a WGT structure and fill in data from file, restructuring as required
+   !!   apply_seaoverland : fill land with ocean values
+   !!   seaoverland   : create shifted matrices for seaoverland application
+   !!   fld_interp    : apply weights to input gridded data to create data on model grid
+   !!   ksec_week     : function returning the first 3 letters of the first day of the weekly file
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constant
+   USE sbc_oce        ! surface boundary conditions : fields
+   USE geo2ocean      ! for vector rotation on to model grid
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE ioipsl  , ONLY : ymds2ju, ju2ymds   ! for calendar
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary conditions (C1D case)
+   
+   IMPLICIT NONE
+   PRIVATE   
+ 
+   PUBLIC   fld_map    ! routine called by tides_init
+   PUBLIC   fld_read, fld_fill   ! called by sbc... modules
+   PUBLIC   fld_clopn
+
+   TYPE, PUBLIC ::   FLD_N      !: Namelist field informations
+      CHARACTER(len = 256) ::   clname      ! generic name of the NetCDF flux file
+      REAL(wp)             ::   freqh       ! frequency of each flux file
+      CHARACTER(len = 34)  ::   clvar       ! generic name of the variable in the NetCDF flux file
+      LOGICAL              ::   ln_tint     ! time interpolation or not (T/F)
+      LOGICAL              ::   ln_clim     ! climatology or not (T/F)
+      CHARACTER(len = 8)   ::   cltype      ! type of data file 'daily', 'monthly' or yearly'
+      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   
+      !                                     ! chars 2 onwards identify which components go together  
+      CHARACTER(len = 34)  ::   lname       ! generic name of a NetCDF land/sea mask file to be used, blank if not 
+      !                                     ! 0=sea 1=land
+   END TYPE FLD_N
+
+   TYPE, PUBLIC ::   FLD        !: Input field related variables
+      CHARACTER(len = 256)            ::   clrootname   ! generic name of the NetCDF file
+      CHARACTER(len = 256)            ::   clname       ! current name of the NetCDF file
+      REAL(wp)                        ::   freqh        ! frequency of each flux file
+      CHARACTER(len = 34)             ::   clvar        ! generic name of the variable in the NetCDF flux file
+      LOGICAL                         ::   ln_tint      ! time interpolation or not (T/F)
+      LOGICAL                         ::   ln_clim      ! climatology or not (T/F)
+      CHARACTER(len = 8)              ::   cltype       ! type of data file 'daily', 'monthly' or yearly'
+      INTEGER                         ::   num          ! iom id of the jpfld files to be read
+      INTEGER , DIMENSION(2)          ::   nrec_b       ! before record (1: index, 2: second since Jan. 1st 00h of nit000 year)
+      INTEGER , DIMENSION(2)          ::   nrec_a       ! after  record (1: index, 2: second since Jan. 1st 00h of nit000 year)
+      REAL(wp) , ALLOCATABLE, DIMENSION(:,:,:  ) ::   fnow   ! input fields interpolated to now time step
+      REAL(wp) , ALLOCATABLE, DIMENSION(:,:,:,:) ::   fdta   ! 2 consecutive record of input fields
+      CHARACTER(len = 256)            ::   wgtname      ! current name of the NetCDF weight file acting as a key
+      !                                                 ! into the WGTLIST structure
+      CHARACTER(len = 34)             ::   vcomp        ! symbolic name for a vector component that needs rotation
+      LOGICAL, DIMENSION(2)           ::   rotn         ! flag to indicate whether before/after field has been rotated
+      INTEGER                         ::   nreclast     ! last record to be read in the current file
+      CHARACTER(len = 256)            ::   lsmname      ! current name of the NetCDF mask file acting as a key
+      !                                                 ! 
+      !                                                 ! Variables related to BDY
+      INTEGER                         ::   igrd         !   grid type for bdy data
+      INTEGER                         ::   ibdy         !   bdy set id number
+      INTEGER, POINTER, DIMENSION(:)  ::   imap         !   Array of integer pointers to 1D arrays
+      LOGICAL                         ::   ltotvel      !   total velocity or not (T/F)
+      LOGICAL                         ::   lzint        !   T if it requires a vertical interpolation
+   END TYPE FLD
+
+!$AGRIF_DO_NOT_TREAT
+
+   !! keep list of all weights variables so they're only read in once
+   !! need to add AGRIF directives not to process this structure
+   !! also need to force wgtname to include AGRIF nest number
+   TYPE         ::   WGT        !: Input weights related variables
+      CHARACTER(len = 256)                    ::   wgtname      ! current name of the NetCDF weight file
+      INTEGER , DIMENSION(2)                  ::   ddims        ! shape of input grid
+      INTEGER , DIMENSION(2)                  ::   botleft      ! top left corner of box in input grid containing 
+      !                                                         ! current processor grid
+      INTEGER , DIMENSION(2)                  ::   topright     ! top right corner of box 
+      INTEGER                                 ::   jpiwgt       ! width of box on input grid
+      INTEGER                                 ::   jpjwgt       ! height of box on input grid
+      INTEGER                                 ::   numwgt       ! number of weights (4=bilinear, 16=bicubic)
+      INTEGER                                 ::   nestid       ! for agrif, keep track of nest we're in
+      INTEGER                                 ::   overlap      ! =0 when cyclic grid has no overlapping EW columns
+      !                                                         ! =>1 when they have one or more overlapping columns      
+      !                                                         ! =-1 not cyclic
+      LOGICAL                                 ::   cyclic       ! east-west cyclic or not
+      INTEGER,  DIMENSION(:,:,:), POINTER     ::   data_jpi     ! array of source integers
+      INTEGER,  DIMENSION(:,:,:), POINTER     ::   data_jpj     ! array of source integers
+      REAL(wp), DIMENSION(:,:,:), POINTER     ::   data_wgt     ! array of weights on model grid
+      REAL(wp), DIMENSION(:,:,:), POINTER     ::   fly_dta      ! array of values on input grid
+      REAL(wp), DIMENSION(:,:,:), POINTER     ::   col          ! temporary array for reading in columns
+   END TYPE WGT
+
+   INTEGER,     PARAMETER             ::   tot_wgts = 20
+   TYPE( WGT ), DIMENSION(tot_wgts)   ::   ref_wgts     ! array of wgts
+   INTEGER                            ::   nxt_wgt = 1  ! point to next available space in ref_wgts array
+   REAL(wp), PARAMETER                ::   undeff_lsm = -999.00_wp
+
+!$AGRIF_END_DO_NOT_TREAT
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE fld_read( kt, kn_fsbc, sd, kit, kt_offset )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_read  ***
+      !!                   
+      !! ** Purpose :   provide at each time step the surface ocean fluxes
+      !!                (momentum, heat, freshwater and runoff) 
+      !!
+      !! ** Method  :   READ each input fields in NetCDF files using IOM
+      !!      and intepolate it to the model time-step.
+      !!         Several assumptions are made on the input file:
+      !!      blahblahblah....
+      !!----------------------------------------------------------------------
+      INTEGER  , INTENT(in   )               ::   kt        ! ocean time step
+      INTEGER  , INTENT(in   )               ::   kn_fsbc   ! sbc computation period (in time step) 
+      TYPE(FLD), INTENT(inout), DIMENSION(:) ::   sd        ! input field related variables
+      INTEGER  , INTENT(in   ), OPTIONAL     ::   kit       ! subcycle timestep for timesplitting option
+      INTEGER  , INTENT(in   ), OPTIONAL     ::   kt_offset ! provide fields at time other than "now"
+      !                                                     !   kt_offset = -1 => fields at "before" time level
+      !                                                     !   kt_offset = +1 => fields at "after"  time level
+      !                                                     !   etc.
+      !!
+      INTEGER  ::   itmp         ! local variable
+      INTEGER  ::   imf          ! size of the structure sd
+      INTEGER  ::   jf           ! dummy indices
+      INTEGER  ::   isecend      ! number of second since Jan. 1st 00h of nit000 year at nitend
+      INTEGER  ::   isecsbc      ! number of seconds between Jan. 1st 00h of nit000 year and the middle of sbc time step
+      INTEGER  ::   it_offset    ! local time offset variable
+      LOGICAL  ::   llnxtyr      ! open next year  file?
+      LOGICAL  ::   llnxtmth     ! open next month file?
+      LOGICAL  ::   llstop       ! stop is the file does not exist
+      LOGICAL  ::   ll_firstcall ! true if this is the first call to fld_read for this set of fields
+      REAL(wp) ::   ztinta       ! ratio applied to after  records when doing time interpolation
+      REAL(wp) ::   ztintb       ! ratio applied to before records when doing time interpolation
+      CHARACTER(LEN=1000) ::   clfmt  ! write format
+      !!---------------------------------------------------------------------
+      ll_firstcall = kt == nit000
+      IF( PRESENT(kit) )   ll_firstcall = ll_firstcall .and. kit == 1
+
+      IF ( nn_components == jp_iam_sas ) THEN   ;   it_offset = nn_fsbc
+      ELSE                                      ;   it_offset = 0
+      ENDIF
+      IF( PRESENT(kt_offset) )   it_offset = kt_offset
+
+      ! Note that shifting time to be centrered in the middle of sbc time step impacts only nsec_* variables of the calendar 
+      IF( present(kit) ) THEN   ! ignore kn_fsbc in this case
+         isecsbc = nsec_year + nsec1jan000 + (kit+it_offset)*NINT( rdt/REAL(nn_baro,wp) )
+      ELSE                      ! middle of sbc time step
+         isecsbc = nsec_year + nsec1jan000 + NINT(0.5 * REAL(kn_fsbc - 1,wp) * rdt) + it_offset * NINT(rdt)
+      ENDIF
+      imf = SIZE( sd )
+      !
+      IF( ll_firstcall ) THEN                      ! initialization
+         DO jf = 1, imf 
+            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
+            CALL fld_init( kn_fsbc, sd(jf) )       ! read each before field (put them in after as they will be swapped)
+         END DO
+         IF( lwp ) CALL wgt_print()                ! control print
+      ENDIF
+      !                                            ! ====================================== !
+      IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN         ! update field at each kn_fsbc time-step !
+         !                                         ! ====================================== !
+         !
+         DO jf = 1, imf                            ! ---   loop over field   --- !
+
+            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
+                      
+            IF( isecsbc > sd(jf)%nrec_a(2) .OR. ll_firstcall ) THEN    ! read/update the after data?
+
+               sd(jf)%nrec_b(:) = sd(jf)%nrec_a(:)                                  ! swap before record informations
+               sd(jf)%rotn(1) = sd(jf)%rotn(2)                                      ! swap before rotate informations
+               IF( sd(jf)%ln_tint )   sd(jf)%fdta(:,:,:,1) = sd(jf)%fdta(:,:,:,2)   ! swap before record field
+
+               CALL fld_rec( kn_fsbc, sd(jf), kt_offset = it_offset, kit = kit )    ! update after record informations
+
+               ! if kn_fsbc*rdt is larger than freqh (which is kind of odd),
+               ! it is possible that the before value is no more the good one... we have to re-read it
+               ! if before is not the last record of the file currently opened and after is the first record to be read
+               ! in a new file which means after = 1 (the file to be opened corresponds to the current time)
+               ! or after = nreclast + 1 (the file to be opened corresponds to a future time step)
+               IF( .NOT. ll_firstcall .AND. sd(jf)%ln_tint .AND. sd(jf)%nrec_b(1) /= sd(jf)%nreclast &
+                  &                   .AND. MOD( sd(jf)%nrec_a(1), sd(jf)%nreclast ) == 1 ) THEN
+                  itmp = sd(jf)%nrec_a(1)                       ! temporary storage
+                  sd(jf)%nrec_a(1) = sd(jf)%nreclast            ! read the last record of the file currently opened
+                  CALL fld_get( sd(jf) )                        ! read after data
+                  sd(jf)%fdta(:,:,:,1) = sd(jf)%fdta(:,:,:,2)   ! re-swap before record field
+                  sd(jf)%nrec_b(1) = sd(jf)%nrec_a(1)           ! update before record informations
+                  sd(jf)%nrec_b(2) = sd(jf)%nrec_a(2) - NINT( sd(jf)%freqh * 3600. )  ! assume freq to be in hours in this case
+                  sd(jf)%rotn(1)   = sd(jf)%rotn(2)             ! update before rotate informations
+                  sd(jf)%nrec_a(1) = itmp                       ! move back to after record 
+               ENDIF
+
+               CALL fld_clopn( sd(jf) )   ! Do we need to open a new year/month/week/day file?
+               
+               IF( sd(jf)%ln_tint ) THEN
+                  
+                  ! if kn_fsbc*rdt is larger than freqh (which is kind of odd),
+                  ! it is possible that the before value is no more the good one... we have to re-read it
+                  ! if before record is not just just before the after record...
+                  IF( .NOT. ll_firstcall .AND. MOD( sd(jf)%nrec_a(1), sd(jf)%nreclast ) /= 1 &
+                     &                   .AND. sd(jf)%nrec_b(1) /= sd(jf)%nrec_a(1) - 1 ) THEN   
+                     sd(jf)%nrec_a(1) = sd(jf)%nrec_a(1) - 1       ! move back to before record
+                     CALL fld_get( sd(jf) )                        ! read after data
+                     sd(jf)%fdta(:,:,:,1) = sd(jf)%fdta(:,:,:,2)   ! re-swap before record field
+                     sd(jf)%nrec_b(1) = sd(jf)%nrec_a(1)           ! update before record informations
+                     sd(jf)%nrec_b(2) = sd(jf)%nrec_a(2) - NINT( sd(jf)%freqh * 3600. )  ! assume freq to be in hours in this case
+                     sd(jf)%rotn(1)   = sd(jf)%rotn(2)             ! update before rotate informations
+                     sd(jf)%nrec_a(1) = sd(jf)%nrec_a(1) + 1       ! move back to after record
+                  ENDIF
+               ENDIF ! temporal interpolation?
+
+               ! do we have to change the year/month/week/day of the forcing field?? 
+               ! if we do time interpolation we will need to open next year/month/week/day file before the end of the current
+               ! one. If so, we are still before the end of the year/month/week/day when calling fld_rec so sd(jf)%nrec_a(1)
+               ! will be larger than the record number that should be read for current year/month/week/day
+               ! do we need next file data?
+               ! This applies to both cases with or without time interpolation
+               IF( sd(jf)%nrec_a(1) > sd(jf)%nreclast ) THEN
+                  
+                  sd(jf)%nrec_a(1) = sd(jf)%nrec_a(1) - sd(jf)%nreclast   ! 
+                  
+                  IF( .NOT. ( sd(jf)%ln_clim .AND. sd(jf)%cltype == 'yearly' ) ) THEN   ! close/open the current/new file
+                     
+                     llnxtmth = sd(jf)%cltype == 'monthly' .OR. nday == nmonth_len(nmonth)      ! open next month file?
+                     llnxtyr  = sd(jf)%cltype == 'yearly'  .OR. (nmonth == 12 .AND. llnxtmth)   ! open next year  file?
+
+                     ! if the run finishes at the end of the current year/month/week/day, we will allow next
+                     ! year/month/week/day file to be not present. If the run continue further than the current
+                     ! year/month/week/day, next year/month/week/day file must exist
+                     isecend = nsec_year + nsec1jan000 + (nitend - kt) * NINT(rdt)   ! second at the end of the run
+                     llstop = isecend > sd(jf)%nrec_a(2)                             ! read more than 1 record of next year
+                     ! we suppose that the date of next file is next day (should be ok even for weekly files...)
+                     CALL fld_clopn( sd(jf), nyear  + COUNT((/llnxtyr /))                                           ,         &
+                        &                    nmonth + COUNT((/llnxtmth/)) - 12                 * COUNT((/llnxtyr /)),         &
+                        &                    nday   + 1                   - nmonth_len(nmonth) * COUNT((/llnxtmth/)), llstop )
+
+                     IF( sd(jf)%num <= 0 .AND. .NOT. llstop ) THEN    ! next year file does not exist
+                        CALL ctl_warn('next year/month/week/day file: '//TRIM(sd(jf)%clname)//     &
+                           &     ' not present -> back to current year/month/day')
+                        CALL fld_clopn( sd(jf) )               ! back to the current year/month/day
+                        sd(jf)%nrec_a(1) = sd(jf)%nreclast     ! force to read the last record in the current year file
+                     ENDIF
+                     
+                  ENDIF
+               ENDIF   ! open need next file?
+                  
+               ! read after data
+               CALL fld_get( sd(jf) )
+               
+            ENDIF   ! read new data?
+         END DO                                    ! --- end loop over field --- !
+
+         CALL fld_rot( kt, sd )                    ! rotate vector before/now/after fields if needed
+
+         DO jf = 1, imf                            ! ---   loop over field   --- !
+            !
+            IF( TRIM(sd(jf)%clrootname) == 'NOT USED' )   CYCLE
+            !
+            IF( sd(jf)%ln_tint ) THEN              ! temporal interpolation
+               IF(lwp .AND. kt - nit000 <= 100 ) THEN 
+                  clfmt = "('   fld_read: var ', a, ' kt = ', i8, ' (', f9.4,' days), Y/M/D = ', i4.4,'/', i2.2,'/', i2.2," //   &
+                     &    "', records b/a: ', i6.4, '/', i6.4, ' (days ', f9.4,'/', f9.4, ')')"
+                  WRITE(numout, clfmt)  TRIM( sd(jf)%clvar ), kt, REAL(isecsbc,wp)/rday, nyear, nmonth, nday,   &            
+                     & sd(jf)%nrec_b(1), sd(jf)%nrec_a(1), REAL(sd(jf)%nrec_b(2),wp)/rday, REAL(sd(jf)%nrec_a(2),wp)/rday
+                  WRITE(numout, *) '      it_offset is : ',it_offset
+               ENDIF
+               ! temporal interpolation weights
+               ztinta =  REAL( isecsbc - sd(jf)%nrec_b(2), wp ) / REAL( sd(jf)%nrec_a(2) - sd(jf)%nrec_b(2), wp )
+               ztintb =  1. - ztinta
+               sd(jf)%fnow(:,:,:) = ztintb * sd(jf)%fdta(:,:,:,1) + ztinta * sd(jf)%fdta(:,:,:,2)
+            ELSE   ! nothing to do...
+               IF(lwp .AND. kt - nit000 <= 100 ) THEN
+                  clfmt = "('   fld_read: var ', a, ' kt = ', i8,' (', f9.4,' days), Y/M/D = ', i4.4,'/', i2.2,'/', i2.2," //   &
+                     &    "', record: ', i6.4, ' (days ', f9.4, ' <-> ', f9.4, ')')"
+                  WRITE(numout, clfmt) TRIM(sd(jf)%clvar), kt, REAL(isecsbc,wp)/rday, nyear, nmonth, nday,    &
+                     &                 sd(jf)%nrec_a(1), REAL(sd(jf)%nrec_b(2),wp)/rday, REAL(sd(jf)%nrec_a(2),wp)/rday
+               ENDIF
+            ENDIF
+            !
+            IF( kt == nitend - kn_fsbc + 1 )   CALL iom_close( sd(jf)%num )   ! Close the input files
+
+         END DO                                    ! --- end loop over field --- !
+         !
+      ENDIF
+      !
+   END SUBROUTINE fld_read
+
+
+   SUBROUTINE fld_init( kn_fsbc, sdjf )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_init  ***
+      !!
+      !! ** Purpose :  - first call to fld_rec to define before values
+      !!               - if time interpolation, read before data 
+      !!----------------------------------------------------------------------
+      INTEGER  , INTENT(in   ) ::   kn_fsbc      ! sbc computation period (in time step) 
+      TYPE(FLD), INTENT(inout) ::   sdjf         ! input field related variables
+      !!
+      LOGICAL :: llprevyr              ! are we reading previous year  file?
+      LOGICAL :: llprevmth             ! are we reading previous month file?
+      LOGICAL :: llprevweek            ! are we reading previous week  file?
+      LOGICAL :: llprevday             ! are we reading previous day   file?
+      LOGICAL :: llprev                ! llprevyr .OR. llprevmth .OR. llprevweek .OR. llprevday
+      INTEGER :: idvar                 ! variable id 
+      INTEGER :: inrec                 ! number of record existing for this variable
+      INTEGER :: iyear, imonth, iday   ! first day of the current file in yyyy mm dd
+      INTEGER :: isec_week             ! number of seconds since start of the weekly file
+      CHARACTER(LEN=1000) ::   clfmt   ! write format
+      !!---------------------------------------------------------------------
+      !
+      llprevyr   = .FALSE.
+      llprevmth  = .FALSE.
+      llprevweek = .FALSE.
+      llprevday  = .FALSE.
+      isec_week  = 0
+      !
+      ! define record informations
+      CALL fld_rec( kn_fsbc, sdjf, ldbefore = .TRUE. )  ! return before values in sdjf%nrec_a (as we will swap it later)
+      !
+      ! Note that shifting time to be centrered in the middle of sbc time step impacts only nsec_* variables of the calendar 
+      !
+      IF( sdjf%ln_tint ) THEN ! we need to read the previous record and we will put it in the current record structure
+         !
+         IF( sdjf%nrec_a(1) == 0  ) THEN   ! we redefine record sdjf%nrec_a(1) with the last record of previous year file
+            IF    ( NINT(sdjf%freqh) == -12 ) THEN   ! yearly mean
+               IF( sdjf%cltype == 'yearly' ) THEN             ! yearly file
+                  sdjf%nrec_a(1) = 1                                                       ! force to read the unique record
+                  llprevyr  = .NOT. sdjf%ln_clim                                           ! use previous year  file?
+               ELSE
+                  CALL ctl_stop( "fld_init: yearly mean file must be in a yearly type of file: "//TRIM(sdjf%clrootname) )
+               ENDIF
+            ELSEIF( NINT(sdjf%freqh) ==  -1 ) THEN   ! monthly mean
+               IF( sdjf%cltype == 'monthly' ) THEN            ! monthly file
+                  sdjf%nrec_a(1) = 1                                                       ! force to read the unique record
+                  llprevmth = .TRUE.                                                       ! use previous month file?
+                  llprevyr  = llprevmth .AND. nmonth == 1                                  ! use previous year  file?
+               ELSE                                           ! yearly file
+                  sdjf%nrec_a(1) = 12                                                      ! force to read december mean
+                  llprevyr = .NOT. sdjf%ln_clim                                            ! use previous year  file?
+               ENDIF
+            ELSE                                     ! higher frequency mean (in hours) 
+               IF    ( sdjf%cltype      == 'monthly' ) THEN   ! monthly file
+                  sdjf%nrec_a(1) = NINT( 24. * REAL(nmonth_len(nmonth-1),wp) / sdjf%freqh )! last record of previous month
+                  llprevmth = .TRUE.                                                       ! use previous month file?
+                  llprevyr  = llprevmth .AND. nmonth == 1                                  ! use previous year  file?
+               ELSEIF( sdjf%cltype(1:4) == 'week'    ) THEN   ! weekly file
+                  llprevweek = .TRUE.                                                      ! use previous week  file?
+                  sdjf%nrec_a(1) = NINT( 24. * 7. / sdjf%freqh )                           ! last record of previous week
+                  isec_week = NINT(rday) * 7                                               ! add a shift toward previous week
+               ELSEIF( sdjf%cltype      == 'daily'   ) THEN   ! daily file
+                  sdjf%nrec_a(1) = NINT( 24. / sdjf%freqh )                                ! last record of previous day
+                  llprevday = .TRUE.                                                       ! use previous day   file?
+                  llprevmth = llprevday .AND. nday   == 1                                  ! use previous month file?
+                  llprevyr  = llprevmth .AND. nmonth == 1                                  ! use previous year  file?
+               ELSE                                           ! yearly file
+                  sdjf%nrec_a(1) = NINT( 24. * REAL(nyear_len(0),wp) / sdjf%freqh )        ! last record of previous year 
+                  llprevyr = .NOT. sdjf%ln_clim                                            ! use previous year  file?
+               ENDIF
+            ENDIF
+         ENDIF
+         !
+         IF ( sdjf%cltype(1:4) == 'week' ) THEN
+            isec_week = isec_week + ksec_week( sdjf%cltype(6:8) )   ! second since the beginning of the week
+            llprevmth = isec_week > nsec_month                      ! longer time since the beginning of the week than the month
+            llprevyr  = llprevmth .AND. nmonth == 1
+         ENDIF
+         llprev = llprevyr .OR. llprevmth .OR. llprevweek .OR. llprevday
+         !
+         iyear  = nyear  - COUNT((/llprevyr /))
+         imonth = nmonth - COUNT((/llprevmth/)) + 12 * COUNT((/llprevyr /))
+         iday   = nday   - COUNT((/llprevday/)) + nmonth_len(nmonth-1) * COUNT((/llprevmth/)) - isec_week / NINT(rday)
+         !
+         CALL fld_clopn( sdjf, iyear, imonth, iday, .NOT. llprev )
+         !
+         ! if previous year/month/day file does not exist, we switch to the current year/month/day
+         IF( llprev .AND. sdjf%num <= 0 ) THEN
+            CALL ctl_warn( 'previous year/month/week/day file: '//TRIM(sdjf%clrootname)//   &
+               &           ' not present -> back to current year/month/week/day' )
+            ! we force to read the first record of the current year/month/day instead of last record of previous year/month/day
+            llprev = .FALSE.
+            sdjf%nrec_a(1) = 1
+            CALL fld_clopn( sdjf )
+         ENDIF
+         !
+         IF( llprev ) THEN   ! check if the record sdjf%nrec_a(1) exists in the file
+            idvar = iom_varid( sdjf%num, sdjf%clvar )                                        ! id of the variable sdjf%clvar
+            IF( idvar <= 0 )   RETURN
+            inrec = iom_file( sdjf%num )%dimsz( iom_file( sdjf%num )%ndims(idvar), idvar )   ! size of the last dim of idvar
+            sdjf%nrec_a(1) = MIN( sdjf%nrec_a(1), inrec )   ! make sure we select an existing record
+         ENDIF
+         !
+         ! read before data in after arrays(as we will swap it later)
+         CALL fld_get( sdjf )
+         !
+         clfmt = "('   fld_init : time-interpolation for ', a, ' read previous record = ', i6, ' at time = ', f7.2, ' days')"
+         IF(lwp) WRITE(numout, clfmt) TRIM(sdjf%clvar), sdjf%nrec_a(1), REAL(sdjf%nrec_a(2),wp)/rday
+         !
+      ENDIF
+      !
+   END SUBROUTINE fld_init
+
+
+   SUBROUTINE fld_rec( kn_fsbc, sdjf, ldbefore, kit, kt_offset )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_rec  ***
+      !!
+      !! ** Purpose : Compute
+      !!              if sdjf%ln_tint = .TRUE.
+      !!                  nrec_a: record number and its time (nrec_b is obtained from nrec_a when swapping)
+      !!              if sdjf%ln_tint = .FALSE.
+      !!                  nrec_a(1): record number
+      !!                  nrec_b(2) and nrec_a(2): time of the beginning and end of the record
+      !!----------------------------------------------------------------------
+      INTEGER  , INTENT(in   )           ::   kn_fsbc   ! sbc computation period (in time step) 
+      TYPE(FLD), INTENT(inout)           ::   sdjf      ! input field related variables
+      LOGICAL  , INTENT(in   ), OPTIONAL ::   ldbefore  ! sent back before record values (default = .FALSE.)
+      INTEGER  , INTENT(in   ), OPTIONAL ::   kit       ! index of barotropic subcycle
+      !                                                 ! used only if sdjf%ln_tint = .TRUE.
+      INTEGER  , INTENT(in   ), OPTIONAL ::   kt_offset ! Offset of required time level compared to "now"
+      !                                                 !   time level in units of time steps.
+      !
+      LOGICAL  ::   llbefore    ! local definition of ldbefore
+      INTEGER  ::   iendrec     ! end of this record (in seconds)
+      INTEGER  ::   imth        ! month number
+      INTEGER  ::   ifreq_sec   ! frequency mean (in seconds)
+      INTEGER  ::   isec_week   ! number of seconds since the start of the weekly file
+      INTEGER  ::   it_offset   ! local time offset variable
+      REAL(wp) ::   ztmp        ! temporary variable
+      !!----------------------------------------------------------------------
+      !
+      ! Note that shifting time to be centrered in the middle of sbc time step impacts only nsec_* variables of the calendar 
+      !
+      IF( PRESENT(ldbefore) ) THEN   ;   llbefore = ldbefore .AND. sdjf%ln_tint   ! needed only if sdjf%ln_tint = .TRUE.
+      ELSE                           ;   llbefore = .FALSE.
+      ENDIF
+      !
+      IF ( nn_components == jp_iam_sas ) THEN   ;   it_offset = nn_fsbc
+      ELSE                                      ;   it_offset = 0
+      ENDIF
+      IF( PRESENT(kt_offset) )      it_offset = kt_offset
+      IF( PRESENT(kit) ) THEN   ;   it_offset = ( kit + it_offset ) * NINT( rdt/REAL(nn_baro,wp) )
+      ELSE                      ;   it_offset =         it_offset   * NINT(       rdt            )
+      ENDIF
+      !
+      !                                           ! =========== !
+      IF    ( NINT(sdjf%freqh) == -12 ) THEN      ! yearly mean
+         !                                        ! =========== !
+         !
+         IF( sdjf%ln_tint ) THEN                  ! time interpolation, shift by 1/2 record
+            !
+            !                  INT( ztmp )
+            !                     /|\
+            !                    1 |    *----
+            !                    0 |----(              
+            !                      |----+----|--> time
+            !                      0   /|\   1   (nday/nyear_len(1))
+            !                           |   
+            !                           |   
+            !       forcing record :    1 
+            !                            
+            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 - (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
+            sdjf%nrec_a(1) = 1
+            sdjf%nrec_a(2) = NINT(rday) * nyear_len(1) + nsec1jan000   ! swap at the end    of the year
+            sdjf%nrec_b(2) = nsec1jan000                               ! beginning of the year (only for print)
+         ENDIF
+         !
+         !                                        ! ============ !
+      ELSEIF( NINT(sdjf%freqh) ==  -1 ) THEN      ! monthly mean !
+         !                                        ! ============ !
+         !
+         IF( sdjf%ln_tint ) THEN                  ! time interpolation, shift by 1/2 record
+            !
+            !                  INT( ztmp )
+            !                     /|\
+            !                    1 |    *----
+            !                    0 |----(              
+            !                      |----+----|--> time
+            !                      0   /|\   1   (nday/nmonth_len(nmonth))
+            !                           |   
+            !                           |   
+            !       forcing record :  nmonth 
+            !                            
+            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/))
+            ELSE                                  ;   sdjf%nrec_a(1) = imth
+            ENDIF
+            sdjf%nrec_a(2) = nmonth_half(   imth ) + nsec1jan000   ! swap at the middle of the month
+         ELSE                                    ! no time interpolation
+            IF( sdjf%cltype == 'monthly' ) THEN   ;   sdjf%nrec_a(1) = 1
+            ELSE                                  ;   sdjf%nrec_a(1) = nmonth
+            ENDIF
+            sdjf%nrec_a(2) =  nmonth_end(nmonth  ) + nsec1jan000   ! swap at the end    of the month
+            sdjf%nrec_b(2) =  nmonth_end(nmonth-1) + nsec1jan000   ! beginning of the month (only for print)
+         ENDIF
+         !
+         !                                        ! ================================ !
+      ELSE                                        ! higher frequency mean (in hours)
+         !                                        ! ================================ !
+         !
+         ifreq_sec = NINT( sdjf%freqh * 3600. )                                         ! frequency mean (in seconds)
+         IF( sdjf%cltype(1:4) == 'week' )   isec_week = ksec_week( sdjf%cltype(6:8) )   ! since the first day of the current week
+         ! number of second since the beginning of the file
+         IF(     sdjf%cltype      == 'monthly' ) THEN   ;   ztmp = REAL(nsec_month,wp)  ! since the first day of the current month
+         ELSEIF( sdjf%cltype(1:4) == 'week'    ) THEN   ;   ztmp = REAL(isec_week ,wp)  ! since the first day of the current week
+         ELSEIF( sdjf%cltype      == 'daily'   ) THEN   ;   ztmp = REAL(nsec_day  ,wp)  ! since 00h of the current day
+         ELSE                                           ;   ztmp = REAL(nsec_year ,wp)  ! since 00h on Jan 1 of the current year
+         ENDIF
+         ztmp = ztmp + 0.5 * REAL(kn_fsbc - 1, wp) * rdt + REAL( it_offset, wp )        ! centrered in the middle of sbc time step
+         ztmp = ztmp + 0.01 * rdt                                                       ! avoid truncation error 
+         IF( sdjf%ln_tint ) THEN                 ! time interpolation, shift by 1/2 record
+            !
+            !          INT( ztmp/ifreq_sec + 0.5 )
+            !                     /|\
+            !                    2 |        *-----(
+            !                    1 |  *-----(
+            !                    0 |--(              
+            !                      |--+--|--+--|--+--|--> time
+            !                      0 /|\ 1 /|\ 2 /|\ 3    (ztmp/ifreq_sec)
+            !                         |     |     |
+            !                         |     |     |
+            !       forcing record :  1     2     3
+            !                   
+            ztmp= ztmp / REAL(ifreq_sec, wp) + 0.5
+         ELSE                                    ! no time interpolation
+            !
+            !           INT( ztmp/ifreq_sec )
+            !                     /|\
+            !                    2 |           *-----(
+            !                    1 |     *-----(
+            !                    0 |-----(              
+            !                      |--+--|--+--|--+--|--> time
+            !                      0 /|\ 1 /|\ 2 /|\ 3    (ztmp/ifreq_sec)
+            !                         |     |     |
+            !                         |     |     |
+            !       forcing record :  1     2     3
+            !                            
+            ztmp= ztmp / REAL(ifreq_sec, wp)
+         ENDIF
+         sdjf%nrec_a(1) = 1 + INT( ztmp ) - COUNT((/llbefore/))   ! record number to be read
+
+         iendrec = ifreq_sec * sdjf%nrec_a(1) + nsec1jan000       ! end of this record (in second)
+         ! add the number of seconds between 00h Jan 1 and the end of previous month/week/day (ok if nmonth=1)
+         IF( sdjf%cltype      == 'monthly' )   iendrec = iendrec + NINT(rday) * SUM(nmonth_len(1:nmonth -1))
+         IF( sdjf%cltype(1:4) == 'week'    )   iendrec = iendrec + ( nsec_year - isec_week )
+         IF( sdjf%cltype      == 'daily'   )   iendrec = iendrec + NINT(rday) * ( nday_year - 1 )
+         IF( sdjf%ln_tint ) THEN
+             sdjf%nrec_a(2) = iendrec - ifreq_sec / 2        ! swap at the middle of the record
+         ELSE
+             sdjf%nrec_a(2) = iendrec                        ! swap at the end    of the record
+             sdjf%nrec_b(2) = iendrec - ifreq_sec            ! beginning of the record (only for print)
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( .NOT. sdjf%ln_tint ) sdjf%nrec_a(2) = sdjf%nrec_a(2) - 1   ! last second belongs to bext record : *----(
+      !
+   END SUBROUTINE fld_rec
+
+
+   SUBROUTINE fld_get( sdjf )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_get  ***
+      !!
+      !! ** Purpose :   read the data
+      !!----------------------------------------------------------------------
+      TYPE(FLD)        , INTENT(inout) ::   sdjf   ! input field related variables
+      !
+      INTEGER ::   ipk      ! number of vertical levels of sdjf%fdta ( 2D: ipk=1 ; 3D: ipk=jpk )
+      INTEGER ::   iw       ! index into wgts array
+      INTEGER ::   ipdom    ! index of the domain
+      INTEGER ::   idvar    ! variable ID
+      INTEGER ::   idmspc   ! number of spatial dimensions
+      LOGICAL ::   lmoor    ! C1D case: point data
+      !!---------------------------------------------------------------------
+      !
+      ipk = SIZE( sdjf%fnow, 3 )
+      !
+      IF( ASSOCIATED(sdjf%imap) ) THEN
+         IF( sdjf%ln_tint ) THEN   ;   CALL fld_map( sdjf%num, sdjf%clvar, sdjf%fdta(:,:,:,2), sdjf%nrec_a(1),   &
+            &                                        sdjf%imap, sdjf%igrd, sdjf%ibdy, sdjf%ltotvel, sdjf%lzint )
+         ELSE                      ;   CALL fld_map( sdjf%num, sdjf%clvar, sdjf%fnow(:,:,:  ), sdjf%nrec_a(1),   &
+            &                                        sdjf%imap, sdjf%igrd, sdjf%ibdy, sdjf%ltotvel, sdjf%lzint )
+         ENDIF
+      ELSE IF( LEN(TRIM(sdjf%wgtname)) > 0 ) THEN
+         CALL wgt_list( sdjf, iw )
+         IF( sdjf%ln_tint ) THEN   ;   CALL fld_interp( sdjf%num, sdjf%clvar, iw, ipk, sdjf%fdta(:,:,:,2),          & 
+            &                                                                          sdjf%nrec_a(1), sdjf%lsmname )
+         ELSE                      ;   CALL fld_interp( sdjf%num, sdjf%clvar, iw, ipk, sdjf%fnow(:,:,:  ),          &
+            &                                                                          sdjf%nrec_a(1), sdjf%lsmname )
+         ENDIF
+      ELSE
+         IF( SIZE(sdjf%fnow, 1) == jpi ) THEN   ;   ipdom = jpdom_data
+         ELSE                                   ;   ipdom = jpdom_unknown
+         ENDIF
+         ! C1D case: If product of spatial dimensions == ipk, then x,y are of
+         ! size 1 (point/mooring data): this must be read onto the central grid point
+         idvar  = iom_varid( sdjf%num, sdjf%clvar )
+         idmspc = iom_file ( sdjf%num )%ndims( idvar )
+         IF( iom_file( sdjf%num )%luld( idvar ) )   idmspc = idmspc - 1
+         lmoor  = (  idmspc == 0 .OR. PRODUCT( iom_file( sdjf%num )%dimsz( 1:MAX(idmspc,1) ,idvar ) ) == ipk  )
+         !
+         SELECT CASE( ipk )
+         CASE(1)
+            IF( lk_c1d .AND. lmoor ) THEN
+               IF( sdjf%ln_tint ) THEN
+                  CALL iom_get( sdjf%num, sdjf%clvar, sdjf%fdta(2,2,1,2), sdjf%nrec_a(1) )
+                  CALL lbc_lnk( 'fldread', sdjf%fdta(:,:,1,2),'Z',1. )
+               ELSE
+                  CALL iom_get( sdjf%num, sdjf%clvar, sdjf%fnow(2,2,1  ), sdjf%nrec_a(1) )
+                  CALL lbc_lnk( 'fldread', sdjf%fnow(:,:,1  ),'Z',1. )
+               ENDIF
+            ELSE
+               IF( sdjf%ln_tint ) THEN   ;   CALL iom_get( sdjf%num, ipdom, sdjf%clvar, sdjf%fdta(:,:,1,2), sdjf%nrec_a(1) )
+               ELSE                      ;   CALL iom_get( sdjf%num, ipdom, sdjf%clvar, sdjf%fnow(:,:,1  ), sdjf%nrec_a(1) )
+               ENDIF
+            ENDIF
+         CASE DEFAULT
+            IF (lk_c1d .AND. lmoor ) THEN
+               IF( sdjf%ln_tint ) THEN
+                  CALL iom_get( sdjf%num, jpdom_unknown, sdjf%clvar, sdjf%fdta(2,2,:,2), sdjf%nrec_a(1) )
+                  CALL lbc_lnk( 'fldread', sdjf%fdta(:,:,:,2),'Z',1. )
+               ELSE
+                  CALL iom_get( sdjf%num, jpdom_unknown, sdjf%clvar, sdjf%fnow(2,2,:  ), sdjf%nrec_a(1) )
+                  CALL lbc_lnk( 'fldread', sdjf%fnow(:,:,:  ),'Z',1. )
+               ENDIF
+            ELSE
+               IF( sdjf%ln_tint ) THEN   ;   CALL iom_get( sdjf%num, ipdom, sdjf%clvar, sdjf%fdta(:,:,:,2), sdjf%nrec_a(1) )
+               ELSE                      ;   CALL iom_get( sdjf%num, ipdom, sdjf%clvar, sdjf%fnow(:,:,:  ), sdjf%nrec_a(1) )
+               ENDIF
+            ENDIF
+         END SELECT
+      ENDIF
+      !
+      sdjf%rotn(2) = .false.   ! vector not yet rotated
+      !
+   END SUBROUTINE fld_get
+
+   
+   SUBROUTINE fld_map( knum, cdvar, pdta, krec, kmap, kgrd, kbdy, ldtotvel, ldzint )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_map  ***
+      !!
+      !! ** Purpose :   read global data from file and map onto local data
+      !!                using a general mapping (for open boundaries)
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   knum         ! stream number
+      CHARACTER(LEN=*)          , INTENT(in   ) ::   cdvar        ! variable name
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdta         ! bdy output field on model grid
+      INTEGER                   , INTENT(in   ) ::   krec         ! record number to read (ie time slice)
+      INTEGER , DIMENSION(:)    , INTENT(in   ) ::   kmap         ! global-to-local bdy mapping indices
+      ! optional variables used for vertical interpolation:
+      INTEGER, OPTIONAL         , INTENT(in   ) ::   kgrd         ! grid type (t, u, v)
+      INTEGER, OPTIONAL         , INTENT(in   ) ::   kbdy         ! bdy number
+      LOGICAL, OPTIONAL         , INTENT(in   ) ::   ldtotvel     ! true if total ( = barotrop + barocline) velocity
+      LOGICAL, OPTIONAL         , INTENT(in   ) ::   ldzint       ! true if 3D variable requires a vertical interpolation
+      !!
+      INTEGER                                   ::   ipi          ! length of boundary data on local process
+      INTEGER                                   ::   ipj          ! length of dummy dimension ( = 1 )
+      INTEGER                                   ::   ipk          ! number of vertical levels of pdta ( 2D: ipk=1 ; 3D: ipk=jpk )
+      INTEGER                                   ::   ipkb         ! number of vertical levels in boundary data file
+      INTEGER                                   ::   idvar        ! variable ID
+      INTEGER                                   ::   indims       ! number of dimensions of the variable
+      INTEGER, DIMENSION(4)                     ::   idimsz       ! size of variable dimensions 
+      REAL(wp)                                  ::   zfv          ! fillvalue 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zz_read      ! work space for global boundary data
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read    ! work space local data requiring vertical interpolation
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read_z  ! work space local data requiring vertical interpolation
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zdta_read_dz ! work space local data requiring vertical interpolation
+      CHARACTER(LEN=1),DIMENSION(3)             ::   clgrid
+      LOGICAL                                   ::   lluld        ! is the variable using the unlimited dimension
+      LOGICAL                                   ::   llzint       ! local value of ldzint
+      !!---------------------------------------------------------------------
+      !
+      clgrid = (/'t','u','v'/)
+      !
+      ipi = SIZE( pdta, 1 )
+      ipj = SIZE( pdta, 2 )   ! must be equal to 1
+      ipk = SIZE( pdta, 3 )
+      !
+      llzint = .FALSE.
+      IF( PRESENT(ldzint) )   llzint = ldzint
+      !
+      idvar = iom_varid( knum, cdvar, kndims = indims, kdimsz = idimsz, lduld = lluld  )
+      IF( indims == 4 .OR. ( indims == 3 .AND. .NOT. lluld ) ) THEN   ;   ipkb = idimsz(3)   ! xy(zl)t or xy(zl)
+      ELSE                                                            ;   ipkb = 1           ! xy or xyt
+      ENDIF
+      !
+      ALLOCATE( zz_read( idimsz(1), idimsz(2), ipkb ) )  ! ++++++++ !!! this can be very big...         
+      !
+      IF( ipk == 1 ) THEN
+
+         IF( ipkb /= 1 ) CALL ctl_stop( 'fld_map : we must have ipkb = 1 to read surface data' )
+         CALL iom_get ( knum, jpdom_unknown, cdvar, zz_read(:,:,1), krec )   ! call iom_get with a 2D file
+         CALL fld_map_core( zz_read, kmap, pdta )
+
+      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+      ! Do we include something here to adjust barotropic velocities !
+      ! in case of a depth difference between bdy files and          !
+      ! bathymetry in the case ln_totvel = .false. and ipkb>0?       !
+      ! [as the enveloping and parital cells could change H]         !
+      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+      ELSE
+         !
+         CALL iom_get ( knum, jpdom_unknown, cdvar, zz_read(:,:,:), krec )   ! call iom_get with a 3D file
+         !
+         IF( ipkb /= ipk .OR. llzint ) THEN   ! boundary data not on model vertical grid : vertical interpolation
+            !
+            IF( ipk == jpk .AND. iom_varid(knum,'gdep'//clgrid(kgrd)) /= -1 .AND. iom_varid(knum,'e3'//clgrid(kgrd)) /= -1 ) THEN
+               
+               ALLOCATE( zdta_read(ipi,ipj,ipkb), zdta_read_z(ipi,ipj,ipkb), zdta_read_dz(ipi,ipj,ipkb) )
+                
+               CALL fld_map_core( zz_read, kmap, zdta_read )
+               CALL iom_get ( knum, jpdom_unknown, 'gdep'//clgrid(kgrd), zz_read )   ! read only once? Potential temporal evolution?
+               CALL fld_map_core( zz_read, kmap, zdta_read_z )
+               CALL iom_get ( knum, jpdom_unknown,   'e3'//clgrid(kgrd), zz_read )   ! read only once? Potential temporal evolution?
+               CALL fld_map_core( zz_read, kmap, zdta_read_dz )
+               
+               CALL iom_getatt(knum, '_FillValue', zfv, cdvar=cdvar )
+               CALL fld_bdy_interp(zdta_read, zdta_read_z, zdta_read_dz, pdta, kgrd, kbdy, zfv, ldtotvel)
+               DEALLOCATE( zdta_read, zdta_read_z, zdta_read_dz )
+               
+            ELSE
+               IF( ipk /= jpk ) CALL ctl_stop( 'fld_map : this should be an impossible case...' )
+               WRITE(ctmp1,*) 'fld_map : vertical interpolation for bdy variable '//TRIM(cdvar)//' requires ' 
+               IF( iom_varid(knum, 'gdep'//clgrid(kgrd)) == -1 ) CALL ctl_stop( ctmp1//'gdep'//clgrid(kgrd)//' variable' )
+               IF( iom_varid(knum,   'e3'//clgrid(kgrd)) == -1 ) CALL ctl_stop( ctmp1//  'e3'//clgrid(kgrd)//' variable' )
+
+            ENDIF
+            !
+         ELSE                            ! bdy data assumed to be the same levels as bdy variables
+            !
+            CALL fld_map_core( zz_read, kmap, pdta )
+            !
+         ENDIF   ! ipkb /= ipk
+      ENDIF   ! ipk == 1
+      
+      DEALLOCATE( zz_read )
+
+   END SUBROUTINE fld_map
+
+     
+   SUBROUTINE fld_map_core( pdta_read, kmap, pdta_bdy )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_map_core  ***
+      !!
+      !! ** Purpose :  inner core of fld_map
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read    ! global boundary data
+      INTEGER,  DIMENSION(:    ), INTENT(in   ) ::   kmap         ! global-to-local bdy mapping indices
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdta_bdy     ! bdy output field on model grid
+      !!
+      INTEGER,  DIMENSION(3) ::   idim_read,  idim_bdy            ! arrays dimensions
+      INTEGER                ::   ji, jj, jk, jb                  ! loop counters
+      INTEGER                ::   im1
+      !!---------------------------------------------------------------------
+      !
+      idim_read = SHAPE( pdta_read )
+      idim_bdy  = SHAPE( pdta_bdy  )
+      !
+      ! in all cases: idim_bdy(2) == 1 .AND. idim_read(1) * idim_read(2) == idim_bdy(1)
+      ! structured BDY with rimwidth > 1                     : idim_read(2) == rimwidth /= 1
+      ! structured BDY with rimwidth == 1 or unstructured BDY: idim_read(2) == 1
+      !
+      IF( idim_read(2) > 1 ) THEN    ! structured BDY with rimwidth > 1  
+         DO jk = 1, idim_bdy(3)
+            DO jb = 1, idim_bdy(1)
+               im1 = kmap(jb) - 1
+               jj = im1 / idim_read(1) + 1
+               ji = MOD( im1, idim_read(1) ) + 1
+               pdta_bdy(jb,1,jk) =  pdta_read(ji,jj,jk)
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, idim_bdy(3)
+            DO jb = 1, idim_bdy(1)   ! horizontal remap of bdy data on the local bdy 
+               pdta_bdy(jb,1,jk) = pdta_read(kmap(jb),1,jk)
+            END DO
+         END DO
+      ENDIF
+      
+   END SUBROUTINE fld_map_core
+   
+   
+   SUBROUTINE fld_bdy_interp(pdta_read, pdta_read_z, pdta_read_dz, pdta, kgrd, kbdy, pfv, ldtotvel)
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_bdy_interp  ***
+      !!
+      !! ** Purpose :   on the fly vertical interpolation to allow the use of
+      !!                boundary data from non-native vertical grid
+      !!----------------------------------------------------------------------
+      USE bdy_oce, ONLY:  idx_bdy         ! indexing for map <-> ij transformation
+
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read       ! data read in bdy file
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read_z     ! depth of the data read in bdy file
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdta_read_dz    ! thickness of the levels in bdy file
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdta            ! output field on model grid (2 dimensional)
+      REAL(wp)                  , INTENT(in   ) ::   pfv             ! fillvalue of the data read in bdy file
+      LOGICAL                   , INTENT(in   ) ::   ldtotvel        ! true if toal ( = barotrop + barocline) velocity
+      INTEGER                   , INTENT(in   ) ::   kgrd            ! grid type (t, u, v)
+      INTEGER                   , INTENT(in   ) ::   kbdy            ! bdy number
+      !!
+      INTEGER                  ::   ipi                 ! length of boundary data on local process
+      INTEGER                  ::   ipkb                ! number of vertical levels in boundary data file
+      INTEGER                  ::   ipkmax              ! number of vertical levels in boundary data file where no mask
+      INTEGER                  ::   jb, ji, jj, jk, jkb ! loop counters
+      REAL(wp)                 ::   zcoef, zi           ! 
+      REAL(wp)                 ::   ztrans, ztrans_new  ! transports
+      REAL(wp), DIMENSION(jpk) ::   zdepth, zdhalf      ! level and half-level depth
+      !!---------------------------------------------------------------------
+     
+      ipi  = SIZE( pdta, 1 )
+      ipkb = SIZE( pdta_read, 3 )
+      
+      DO jb = 1, ipi
+         ji = idx_bdy(kbdy)%nbi(jb,kgrd)
+         jj = idx_bdy(kbdy)%nbj(jb,kgrd)
+         !
+         ! --- max jk where input data /= FillValue --- !
+         ipkmax = 1
+         DO jkb = 2, ipkb
+            IF( pdta_read(jb,1,jkb) /= pfv )   ipkmax = MAX( ipkmax, jkb )
+         END DO
+         !
+         ! --- calculate depth at t,u,v points --- !
+         SELECT CASE( kgrd )                         
+         CASE(1)            ! depth of T points:
+            zdepth(:) = gdept_n(ji,jj,:)
+         CASE(2)            ! depth of U points: we must not use gdept_n as we don't want to do a communication
+            !                 --> copy what is done for gdept_n in domvvl...
+            zdhalf(1) = 0.0_wp
+            zdepth(1) = 0.5_wp * e3uw_n(ji,jj,1)
+            DO jk = 2, jpk                               ! vertical sum
+               !    zcoef = umask - wumask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+               !                              ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
+               !                              ! 0.5 where jk = mikt     
+               !!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
+               zcoef = ( umask(ji,jj,jk) - wumask(ji,jj,jk) )
+               zdhalf(jk) = zdhalf(jk-1) + e3u_n(ji,jj,jk-1)
+               zdepth(jk) =       zcoef  * ( zdhalf(jk  ) + 0.5 * e3uw_n(ji,jj,jk))  &
+                  &         + (1.-zcoef) * ( zdepth(jk-1) +       e3uw_n(ji,jj,jk))
+            END DO
+         CASE(3)            ! depth of V points: we must not use gdept_n as we don't want to do a communication
+            !                 --> copy what is done for gdept_n in domvvl...
+            zdhalf(1) = 0.0_wp
+            zdepth(1) = 0.5_wp * e3vw_n(ji,jj,1)
+            DO jk = 2, jpk                               ! vertical sum
+               !    zcoef = vmask - wvmask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+               !                              ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
+               !                              ! 0.5 where jk = mikt     
+               !!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
+               zcoef = ( vmask(ji,jj,jk) - wvmask(ji,jj,jk) )
+               zdhalf(jk) = zdhalf(jk-1) + e3v_n(ji,jj,jk-1)
+               zdepth(jk) =       zcoef  * ( zdhalf(jk  ) + 0.5 * e3vw_n(ji,jj,jk))  &
+                  &         + (1.-zcoef) * ( zdepth(jk-1) +       e3vw_n(ji,jj,jk))
+            END DO
+         END SELECT
+         !         
+         ! --- interpolate bdy data on the model grid --- !
+         DO jk = 1, jpk
+            IF(     zdepth(jk) <= pdta_read_z(jb,1,1)      ) THEN   ! above the first level of external data
+               pdta(jb,1,jk) = pdta_read(jb,1,1)
+            ELSEIF( zdepth(jk) >  pdta_read_z(jb,1,ipkmax) ) THEN   ! below the last level of external data /= FillValue
+               pdta(jb,1,jk) = pdta_read(jb,1,ipkmax)
+            ELSE                                                    ! inbetween: vertical interpolation between jkb & jkb+1
+               DO jkb = 1, ipkmax-1
+                  IF( ( ( zdepth(jk) - pdta_read_z(jb,1,jkb) ) * ( zdepth(jk) - pdta_read_z(jb,1,jkb+1) ) ) <= 0._wp ) THEN ! linear interpolation between 2 levels
+                     zi = ( zdepth(jk) - pdta_read_z(jb,1,jkb) ) / ( pdta_read_z(jb,1,jkb+1) - pdta_read_z(jb,1,jkb) )
+                     pdta(jb,1,jk) = pdta_read(jb,1,jkb) + zi * ( pdta_read(jb,1,jkb+1) - pdta_read(jb,1,jkb) )
+                  ENDIF
+               END DO
+            ENDIF
+         END DO
+         !
+      END DO   ! ipi
+
+      ! --- mask data and adjust transport --- !
+      SELECT CASE( kgrd )                         
+
+      CASE(1)                                 ! mask data (probably unecessary)
+         DO jb = 1, ipi
+            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
+            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
+            DO jk = 1, jpk                      
+               pdta(jb,1,jk) = pdta(jb,1,jk) * tmask(ji,jj,jk)
+            END DO
+         END DO
+         
+      CASE(2)                                 ! adjust the U-transport term
+         DO jb = 1, ipi
+            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
+            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
+            ztrans = 0._wp
+            DO jkb = 1, ipkb                              ! calculate transport on input grid
+               IF( pdta_read(jb,1,jkb) /= pfv )   ztrans = ztrans + pdta_read(jb,1,jkb) * pdta_read_dz(jb,1,jkb)
+            ENDDO
+            ztrans_new = 0._wp
+            DO jk = 1, jpk                                ! calculate transport on model grid
+               ztrans_new = ztrans_new + pdta(jb,1,jk ) * e3u_n(ji,jj,jk) * umask(ji,jj,jk)
+            ENDDO
+            DO jk = 1, jpk                                ! make transport correction
+               IF(ldtotvel) THEN ! bdy data are total velocity so adjust bt transport term to match input data
+                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + ( ztrans - ztrans_new ) * r1_hu_n(ji,jj) ) * umask(ji,jj,jk)
+               ELSE              ! we're just dealing with bc velocity so bt transport term should sum to zero
+                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + (  0._wp - ztrans_new ) * r1_hu_n(ji,jj) ) * umask(ji,jj,jk)
+               ENDIF
+            ENDDO
+         ENDDO
+
+      CASE(3)                                 ! adjust the V-transport term
+         DO jb = 1, ipi
+            ji = idx_bdy(kbdy)%nbi(jb,kgrd)
+            jj = idx_bdy(kbdy)%nbj(jb,kgrd)
+            ztrans = 0._wp
+            DO jkb = 1, ipkb                              ! calculate transport on input grid
+               IF( pdta_read(jb,1,jkb) /= pfv )   ztrans = ztrans + pdta_read(jb,1,jkb) * pdta_read_dz(jb,1,jkb)
+            ENDDO
+            ztrans_new = 0._wp
+            DO jk = 1, jpk                                ! calculate transport on model grid
+               ztrans_new = ztrans_new + pdta(jb,1,jk ) * e3v_n(ji,jj,jk) * vmask(ji,jj,jk)
+            ENDDO
+            DO jk = 1, jpk                                ! make transport correction
+               IF(ldtotvel) THEN ! bdy data are total velocity so adjust bt transport term to match input data
+                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + ( ztrans - ztrans_new ) * r1_hv_n(ji,jj) ) * vmask(ji,jj,jk)
+               ELSE              ! we're just dealing with bc velocity so bt transport term should sum to zero
+                  pdta(jb,1,jk) = ( pdta(jb,1,jk) + (  0._wp - ztrans_new ) * r1_hv_n(ji,jj) ) * vmask(ji,jj,jk)
+               ENDIF
+            ENDDO
+         ENDDO
+      END SELECT
+
+   END SUBROUTINE fld_bdy_interp
+
+   
+   SUBROUTINE fld_rot( kt, sd )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_rot  ***
+      !!
+      !! ** Purpose :   Vector fields may need to be rotated onto the local grid direction
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in   ) ::   kt   ! ocean time step
+      TYPE(FLD), DIMENSION(:), INTENT(inout) ::   sd   ! input field related variables
+      !
+      INTEGER ::   ju, jv, jk, jn  ! loop indices
+      INTEGER ::   imf             ! size of the structure sd
+      INTEGER ::   ill             ! character length
+      INTEGER ::   iv              ! indice of V component
+      CHARACTER (LEN=100)          ::   clcomp       ! dummy weight name
+      REAL(wp), DIMENSION(jpi,jpj) ::   utmp, vtmp   ! temporary arrays for vector rotation
+      !!---------------------------------------------------------------------
+      !
+      !! (sga: following code should be modified so that pairs arent searched for each time
+      !
+      imf = SIZE( sd )
+      DO ju = 1, imf
+         IF( TRIM(sd(ju)%clrootname) == 'NOT USED' )   CYCLE
+         ill = LEN_TRIM( sd(ju)%vcomp )
+         DO jn = 2-COUNT((/sd(ju)%ln_tint/)), 2
+            IF( ill > 0 .AND. .NOT. sd(ju)%rotn(jn) ) THEN   ! find vector rotations required             
+               IF( sd(ju)%vcomp(1:1) == 'U' ) THEN      ! east-west component has symbolic name starting with 'U'
+                  ! look for the north-south component which has same symbolic name but with 'U' replaced with 'V'
+                  clcomp = 'V' // sd(ju)%vcomp(2:ill)   ! works even if ill == 1
+                  iv = -1
+                  DO jv = 1, imf
+                     IF( TRIM(sd(jv)%clrootname) == 'NOT USED' )   CYCLE
+                     IF( TRIM(sd(jv)%vcomp) == TRIM(clcomp) )   iv = jv
+                  END DO
+                  IF( iv > 0 ) THEN   ! fields ju and iv are two components which need to be rotated together
+                     DO jk = 1, SIZE( sd(ju)%fnow, 3 )
+                        IF( sd(ju)%ln_tint )THEN
+                           CALL rot_rep( sd(ju)%fdta(:,:,jk,jn), sd(iv)%fdta(:,:,jk,jn), 'T', 'en->i', utmp(:,:) )
+                           CALL rot_rep( sd(ju)%fdta(:,:,jk,jn), sd(iv)%fdta(:,:,jk,jn), 'T', 'en->j', vtmp(:,:) )
+                           sd(ju)%fdta(:,:,jk,jn) = utmp(:,:)   ;   sd(iv)%fdta(:,:,jk,jn) = vtmp(:,:)
+                        ELSE 
+                           CALL rot_rep( sd(ju)%fnow(:,:,jk  ), sd(iv)%fnow(:,:,jk  ), 'T', 'en->i', utmp(:,:) )
+                           CALL rot_rep( sd(ju)%fnow(:,:,jk  ), sd(iv)%fnow(:,:,jk  ), 'T', 'en->j', vtmp(:,:) )
+                           sd(ju)%fnow(:,:,jk   ) = utmp(:,:)   ;   sd(iv)%fnow(:,:,jk   ) = vtmp(:,:)
+                        ENDIF
+                     END DO
+                     sd(ju)%rotn(jn) = .TRUE.               ! vector was rotated 
+                     IF( lwp .AND. kt == nit000 )   WRITE(numout,*)   &
+                        &   'fld_read: vector pair ('//TRIM(sd(ju)%clvar)//', '//TRIM(sd(iv)%clvar)//') rotated on to model grid'
+                  ENDIF
+               ENDIF
+            ENDIF
+         END DO
+       END DO
+      !
+   END SUBROUTINE fld_rot
+
+
+   SUBROUTINE fld_clopn( sdjf, kyear, kmonth, kday, ldstop )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_clopn  ***
+      !!
+      !! ** Purpose :   update the file name and close/open the files
+      !!----------------------------------------------------------------------
+      TYPE(FLD)        , INTENT(inout) ::   sdjf     ! input field related variables
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kyear    ! year value
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kmonth   ! month value
+      INTEGER, OPTIONAL, INTENT(in   ) ::   kday     ! day value
+      LOGICAL, OPTIONAL, INTENT(in   ) ::   ldstop   ! stop if open to read a non-existing file (default = .TRUE.)
+      !
+      LOGICAL  :: llprevyr              ! are we reading previous year  file?
+      LOGICAL  :: llprevmth             ! are we reading previous month file?
+      INTEGER  :: iyear, imonth, iday   ! first day of the current file in yyyy mm dd
+      INTEGER  :: isec_week             ! number of seconds since start of the weekly file
+      INTEGER  :: indexyr               ! year undex (O/1/2: previous/current/next)
+      REAL(wp) :: zyear_len, zmonth_len ! length (days) of iyear and imonth             ! 
+      CHARACTER(len = 256) ::   clname  ! temporary file name
+      !!----------------------------------------------------------------------
+      IF( PRESENT(kyear) ) THEN                             ! use given values 
+         iyear = kyear
+         imonth = kmonth
+         iday = kday
+         IF ( sdjf%cltype(1:4) == 'week' ) THEN             ! find the day of the beginning of the week
+            isec_week = ksec_week( sdjf%cltype(6:8) )- (86400 * 8 )  
+            llprevmth  = isec_week > nsec_month             ! longer time since beginning of the week than the month
+            llprevyr   = llprevmth .AND. nmonth == 1
+            iyear  = nyear  - COUNT((/llprevyr /))
+            imonth = nmonth - COUNT((/llprevmth/)) + 12 * COUNT((/llprevyr /))
+            iday   = nday   + nmonth_len(nmonth-1) * COUNT((/llprevmth/)) - isec_week / NINT(rday)
+         ENDIF
+      ELSE                                                  ! use current day values
+         IF ( sdjf%cltype(1:4) == 'week' ) THEN             ! find the day of the beginning of the week
+            isec_week  = ksec_week( sdjf%cltype(6:8) )      ! second since the beginning of the week
+            llprevmth  = isec_week > nsec_month             ! longer time since beginning of the week than the month
+            llprevyr   = llprevmth .AND. nmonth == 1
+         ELSE
+            isec_week  = 0
+            llprevmth  = .FALSE.
+            llprevyr   = .FALSE.
+         ENDIF
+         iyear  = nyear  - COUNT((/llprevyr /))
+         imonth = nmonth - COUNT((/llprevmth/)) + 12 * COUNT((/llprevyr /))
+         iday   = nday   + nmonth_len(nmonth-1) * COUNT((/llprevmth/)) - isec_week / NINT(rday)
+      ENDIF
+
+      ! build the new filename if not climatological data
+      clname=TRIM(sdjf%clrootname)
+      !
+      ! note that sdjf%ln_clim is is only acting on the presence of the year in the file name
+      IF( .NOT. sdjf%ln_clim ) THEN   
+                                         WRITE(clname, '(a,"_y",i4.4)' ) TRIM( sdjf%clrootname ), iyear    ! add year
+         IF( sdjf%cltype /= 'yearly' )   WRITE(clname, '(a,"m" ,i2.2)' ) TRIM( clname          ), imonth   ! add month
+      ELSE
+         ! build the new filename if climatological data
+         IF( sdjf%cltype /= 'yearly' )   WRITE(clname, '(a,"_m",i2.2)' ) TRIM( sdjf%clrootname ), imonth   ! add month
+      ENDIF
+      IF( sdjf%cltype == 'daily' .OR. sdjf%cltype(1:4) == 'week' ) &
+            &                            WRITE(clname, '(a,"d" ,i2.2)' ) TRIM( clname          ), iday     ! add day
+      !
+      IF( TRIM(clname) /= TRIM(sdjf%clname) .OR. sdjf%num == 0 ) THEN   ! new file to be open 
+         !
+         sdjf%clname = TRIM(clname)
+         IF( sdjf%num /= 0 )   CALL iom_close( sdjf%num )   ! close file if already open
+         CALL iom_open( sdjf%clname, sdjf%num, ldstop = ldstop, ldiof =  LEN(TRIM(sdjf%wgtname)) > 0 )
+         !
+         ! find the last record to be read -> update sdjf%nreclast
+         indexyr = iyear - nyear + 1
+         zyear_len = REAL(nyear_len( indexyr ), wp)
+         SELECT CASE ( indexyr )
+         CASE ( 0 )   ;   zmonth_len = 31.   ! previous year -> imonth = 12
+         CASE ( 1 )   ;   zmonth_len = REAL(nmonth_len(imonth), wp)
+         CASE ( 2 )   ;   zmonth_len = 31.   ! next     year -> imonth = 1
+         END SELECT
+         !
+         ! last record to be read in the current file
+         IF    ( sdjf%freqh == -12. ) THEN                 ;   sdjf%nreclast = 1    !  yearly mean
+         ELSEIF( sdjf%freqh ==  -1. ) THEN                                          ! monthly mean
+            IF(     sdjf%cltype      == 'monthly' ) THEN   ;   sdjf%nreclast = 1
+            ELSE                                           ;   sdjf%nreclast = 12
+            ENDIF
+         ELSE                                                                       ! higher frequency mean (in hours)
+            IF(     sdjf%cltype      == 'monthly' ) THEN   ;   sdjf%nreclast = NINT( 24. * zmonth_len / sdjf%freqh )
+            ELSEIF( sdjf%cltype(1:4) == 'week'    ) THEN   ;   sdjf%nreclast = NINT( 24. * 7.         / sdjf%freqh )
+            ELSEIF( sdjf%cltype      == 'daily'   ) THEN   ;   sdjf%nreclast = NINT( 24.              / sdjf%freqh )
+            ELSE                                           ;   sdjf%nreclast = NINT( 24. * zyear_len  / sdjf%freqh )
+            ENDIF
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE fld_clopn
+
+
+   SUBROUTINE fld_fill( sdf, sdf_n, cdir, cdcaller, cdtitle, cdnam, knoprint )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_fill  ***
+      !!
+      !! ** Purpose :   fill the data structure (sdf) with the associated information 
+      !!              read in namelist (sdf_n) and control print
+      !!----------------------------------------------------------------------
+      TYPE(FLD)  , DIMENSION(:)          , INTENT(inout) ::   sdf        ! structure of input fields (file informations, fields read)
+      TYPE(FLD_N), DIMENSION(:)          , INTENT(in   ) ::   sdf_n      ! array of namelist information structures
+      CHARACTER(len=*)                   , INTENT(in   ) ::   cdir       ! Root directory for location of flx files
+      CHARACTER(len=*)                   , INTENT(in   ) ::   cdcaller   ! name of the calling routine
+      CHARACTER(len=*)                   , INTENT(in   ) ::   cdtitle    ! description of the calling routine 
+      CHARACTER(len=*)                   , INTENT(in   ) ::   cdnam      ! name of the namelist from which sdf_n comes
+      INTEGER                  , OPTIONAL, INTENT(in   ) ::   knoprint   ! no calling routine information printed
+      !
+      INTEGER  ::   jf   ! dummy indices
+      !!---------------------------------------------------------------------
+      !
+      DO jf = 1, SIZE(sdf)
+         sdf(jf)%clrootname = sdf_n(jf)%clname
+         IF( TRIM(sdf_n(jf)%clname) /= 'NOT USED' )   sdf(jf)%clrootname = TRIM( cdir )//sdf(jf)%clrootname
+         sdf(jf)%clname     = "not yet defined"
+         sdf(jf)%freqh      = sdf_n(jf)%freqh
+         sdf(jf)%clvar      = sdf_n(jf)%clvar
+         sdf(jf)%ln_tint    = sdf_n(jf)%ln_tint
+         sdf(jf)%ln_clim    = sdf_n(jf)%ln_clim
+         sdf(jf)%cltype     = sdf_n(jf)%cltype
+         sdf(jf)%num        = -1
+         sdf(jf)%wgtname    = " "
+         IF( LEN( TRIM(sdf_n(jf)%wname) ) > 0 )   sdf(jf)%wgtname = TRIM( cdir )//sdf_n(jf)%wname
+         sdf(jf)%lsmname = " "
+         IF( LEN( TRIM(sdf_n(jf)%lname) ) > 0 )   sdf(jf)%lsmname = TRIM( cdir )//sdf_n(jf)%lname
+         sdf(jf)%vcomp      = sdf_n(jf)%vcomp
+         sdf(jf)%rotn(:)    = .TRUE.   ! pretend to be rotated -> won't try to rotate data before the first call to fld_get
+         IF( sdf(jf)%cltype(1:4) == 'week' .AND. nn_leapy == 0  )   &
+            &   CALL ctl_stop('fld_clopn: weekly file ('//TRIM(sdf(jf)%clrootname)//') needs nn_leapy = 1')
+         IF( sdf(jf)%cltype(1:4) == 'week' .AND. sdf(jf)%ln_clim )   &
+            &   CALL ctl_stop('fld_clopn: weekly file ('//TRIM(sdf(jf)%clrootname)//') needs ln_clim = .FALSE.')
+         sdf(jf)%nreclast   = -1 ! Set to non zero default value to avoid errors, is updated to meaningful value during fld_clopn
+         sdf(jf)%igrd       = 0
+         sdf(jf)%ibdy       = 0
+         sdf(jf)%imap       => NULL()
+         sdf(jf)%ltotvel    = .FALSE.
+         sdf(jf)%lzint      = .FALSE.
+      END DO
+      !
+      IF(lwp) THEN      ! control print
+         WRITE(numout,*)
+         IF( .NOT.PRESENT( knoprint) ) THEN
+            WRITE(numout,*) TRIM( cdcaller )//' : '//TRIM( cdtitle )
+            WRITE(numout,*) (/ ('~', jf = 1, LEN_TRIM( cdcaller ) ) /)
+         ENDIF
+         WRITE(numout,*) '   fld_fill : fill data structure with information from namelist '//TRIM( cdnam )
+         WRITE(numout,*) '   ~~~~~~~~'
+         WRITE(numout,*) '      list of files and frequency (>0: in hours ; <0 in months)'
+         DO jf = 1, SIZE(sdf)
+            WRITE(numout,*) '      root filename: '  , TRIM( sdf(jf)%clrootname ), '   variable name: ', TRIM( sdf(jf)%clvar )
+            WRITE(numout,*) '         frequency: '      ,       sdf(jf)%freqh       ,   &
+               &                  '   time interp: '    ,       sdf(jf)%ln_tint     ,   &
+               &                  '   climatology: '    ,       sdf(jf)%ln_clim
+            WRITE(numout,*) '         weights: '        , TRIM( sdf(jf)%wgtname    ),   &
+               &                  '   pairing: '        , TRIM( sdf(jf)%vcomp      ),   &
+               &                  '   data type: '      ,       sdf(jf)%cltype      ,   &
+               &                  '   land/sea mask:'   , TRIM( sdf(jf)%lsmname    )
+            call flush(numout)
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE fld_fill
+
+
+   SUBROUTINE wgt_list( sd, kwgt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE wgt_list  ***
+      !!
+      !! ** Purpose :   search array of WGTs and find a weights file entry,
+      !!                or return a new one adding it to the end if new entry.
+      !!                the weights data is read in and restructured (fld_weight)
+      !!----------------------------------------------------------------------
+      TYPE( FLD ), INTENT(in   ) ::   sd        ! field with name of weights file
+      INTEGER    , INTENT(inout) ::   kwgt      ! index of weights
+      !
+      INTEGER ::   kw, nestid   ! local integer
+      LOGICAL ::   found        ! local logical
+      !!----------------------------------------------------------------------
+      !
+      !! search down linked list 
+      !! weights filename is either present or we hit the end of the list
+      found = .FALSE.
+      !
+      !! because agrif nest part of filenames are now added in iom_open
+      !! to distinguish between weights files on the different grids, need to track
+      !! nest number explicitly
+      nestid = 0
+#if defined key_agrif
+      nestid = Agrif_Fixed()
+#endif
+      DO kw = 1, nxt_wgt-1
+         IF( TRIM(ref_wgts(kw)%wgtname) == TRIM(sd%wgtname) .AND. &
+             ref_wgts(kw)%nestid == nestid) THEN
+            kwgt = kw
+            found = .TRUE.
+            EXIT
+         ENDIF
+      END DO
+      IF( .NOT.found ) THEN
+         kwgt = nxt_wgt
+         CALL fld_weight( sd )
+      ENDIF
+      !
+   END SUBROUTINE wgt_list
+
+
+   SUBROUTINE wgt_print( )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE wgt_print  ***
+      !!
+      !! ** Purpose :   print the list of known weights
+      !!----------------------------------------------------------------------
+      INTEGER ::   kw   !
+      !!----------------------------------------------------------------------
+      !
+      DO kw = 1, nxt_wgt-1
+         WRITE(numout,*) 'weight file:  ',TRIM(ref_wgts(kw)%wgtname)
+         WRITE(numout,*) '      ddims:  ',ref_wgts(kw)%ddims(1),ref_wgts(kw)%ddims(2)
+         WRITE(numout,*) '     numwgt:  ',ref_wgts(kw)%numwgt
+         WRITE(numout,*) '     jpiwgt:  ',ref_wgts(kw)%jpiwgt
+         WRITE(numout,*) '     jpjwgt:  ',ref_wgts(kw)%jpjwgt
+         WRITE(numout,*) '    botleft:  ',ref_wgts(kw)%botleft
+         WRITE(numout,*) '   topright:  ',ref_wgts(kw)%topright
+         IF( ref_wgts(kw)%cyclic ) THEN
+            WRITE(numout,*) '       cyclical'
+            IF( ref_wgts(kw)%overlap > 0 ) WRITE(numout,*) '              with overlap of ', ref_wgts(kw)%overlap
+         ELSE
+            WRITE(numout,*) '       not cyclical'
+         ENDIF
+         IF( ASSOCIATED(ref_wgts(kw)%data_wgt) )  WRITE(numout,*) '       allocated'
+      END DO
+      !
+   END SUBROUTINE wgt_print
+
+
+   SUBROUTINE fld_weight( sd )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_weight  ***
+      !!
+      !! ** Purpose :   create a new WGT structure and fill in data from file,
+      !!              restructuring as required
+      !!----------------------------------------------------------------------
+      TYPE( FLD ), INTENT(in) ::   sd   ! field with name of weights file
+      !!
+      INTEGER ::   jn         ! dummy loop indices
+      INTEGER ::   inum       ! local logical unit
+      INTEGER ::   id         ! local variable id
+      INTEGER ::   ipk        ! local vertical dimension
+      INTEGER ::   zwrap      ! local integer
+      LOGICAL ::   cyclical   ! 
+      CHARACTER (len=5) ::   aname   !
+      INTEGER , DIMENSION(:), ALLOCATABLE ::   ddims
+      INTEGER,  DIMENSION(jpi,jpj) ::   data_src
+      REAL(wp), DIMENSION(jpi,jpj) ::   data_tmp
+      !!----------------------------------------------------------------------
+      !
+      IF( nxt_wgt > tot_wgts ) THEN
+        CALL ctl_stop("fld_weight: weights array size exceeded, increase tot_wgts")
+      ENDIF
+      !
+      !! new weights file entry, add in extra information
+      !! a weights file represents a 2D grid of a certain shape, so we assume that the current
+      !! input data file is representative of all other files to be opened and processed with the
+      !! current weights file
+
+      !! open input data file (non-model grid)
+      CALL iom_open( sd%clname, inum, ldiof =  LEN(TRIM(sd%wgtname)) > 0 )
+
+      !! get dimensions
+      IF ( SIZE(sd%fnow, 3) > 1 ) THEN
+         ALLOCATE( ddims(4) )
+      ELSE
+         ALLOCATE( ddims(3) )
+      ENDIF
+      id = iom_varid( inum, sd%clvar, ddims )
+
+      !! close it
+      CALL iom_close( inum )
+
+      !! now open the weights file
+
+      CALL iom_open ( sd%wgtname, inum )   ! interpolation weights
+      IF ( inum > 0 ) THEN
+
+         !! determine whether we have an east-west cyclic grid
+         !! from global attribute called "ew_wrap" in the weights file
+         !! note that if not found, iom_getatt returns -999 and cyclic with no overlap is assumed
+         !! since this is the most common forcing configuration
+
+         CALL iom_getatt(inum, 'ew_wrap', zwrap)
+         IF( zwrap >= 0 ) THEN
+            cyclical = .TRUE.
+         ELSE IF( zwrap == -999 ) THEN
+            cyclical = .TRUE.
+            zwrap = 0
+         ELSE
+            cyclical = .FALSE.
+         ENDIF
+
+         ref_wgts(nxt_wgt)%ddims(1) = ddims(1)
+         ref_wgts(nxt_wgt)%ddims(2) = ddims(2)
+         ref_wgts(nxt_wgt)%wgtname = sd%wgtname
+         ref_wgts(nxt_wgt)%overlap = zwrap
+         ref_wgts(nxt_wgt)%cyclic = cyclical
+         ref_wgts(nxt_wgt)%nestid = 0
+#if defined key_agrif
+         ref_wgts(nxt_wgt)%nestid = Agrif_Fixed()
+#endif
+         !! weights file is stored as a set of weights (wgt01->wgt04 or wgt01->wgt16)
+         !! for each weight wgtNN there is an integer array srcNN which gives the point in
+         !! the input data grid which is to be multiplied by the weight
+         !! they are both arrays on the model grid so the result of the multiplication is
+         !! added into an output array on the model grid as a running sum
+
+         !! two possible cases: bilinear (4 weights) or bicubic (16 weights)
+         id = iom_varid(inum, 'src05', ldstop=.FALSE.)
+         IF( id <= 0) THEN
+            ref_wgts(nxt_wgt)%numwgt = 4
+         ELSE
+            ref_wgts(nxt_wgt)%numwgt = 16
+         ENDIF
+
+         ALLOCATE( ref_wgts(nxt_wgt)%data_jpi(jpi,jpj,4) )
+         ALLOCATE( ref_wgts(nxt_wgt)%data_jpj(jpi,jpj,4) )
+         ALLOCATE( ref_wgts(nxt_wgt)%data_wgt(jpi,jpj,ref_wgts(nxt_wgt)%numwgt) )
+
+         DO jn = 1,4
+            aname = ' '
+            WRITE(aname,'(a3,i2.2)') 'src',jn
+            data_tmp(:,:) = 0
+            CALL iom_get ( inum, jpdom_data, aname, data_tmp(:,:) )
+            data_src(:,:) = INT(data_tmp(:,:))
+            ref_wgts(nxt_wgt)%data_jpj(:,:,jn) = 1 + (data_src(:,:)-1) / ref_wgts(nxt_wgt)%ddims(1)
+            ref_wgts(nxt_wgt)%data_jpi(:,:,jn) = data_src(:,:) - ref_wgts(nxt_wgt)%ddims(1)*(ref_wgts(nxt_wgt)%data_jpj(:,:,jn)-1)
+         END DO
+
+         DO jn = 1, ref_wgts(nxt_wgt)%numwgt
+            aname = ' '
+            WRITE(aname,'(a3,i2.2)') 'wgt',jn
+            ref_wgts(nxt_wgt)%data_wgt(:,:,jn) = 0.0
+            CALL iom_get ( inum, jpdom_data, aname, ref_wgts(nxt_wgt)%data_wgt(:,:,jn) )
+         END DO
+         CALL iom_close (inum)
+ 
+         ! find min and max indices in grid
+         ref_wgts(nxt_wgt)%botleft(1) = MINVAL(ref_wgts(nxt_wgt)%data_jpi(:,:,:))
+         ref_wgts(nxt_wgt)%botleft(2) = MINVAL(ref_wgts(nxt_wgt)%data_jpj(:,:,:))
+         ref_wgts(nxt_wgt)%topright(1) = MAXVAL(ref_wgts(nxt_wgt)%data_jpi(:,:,:))
+         ref_wgts(nxt_wgt)%topright(2) = MAXVAL(ref_wgts(nxt_wgt)%data_jpj(:,:,:))
+
+         ! and therefore dimensions of the input box
+         ref_wgts(nxt_wgt)%jpiwgt = ref_wgts(nxt_wgt)%topright(1) - ref_wgts(nxt_wgt)%botleft(1) + 1
+         ref_wgts(nxt_wgt)%jpjwgt = ref_wgts(nxt_wgt)%topright(2) - ref_wgts(nxt_wgt)%botleft(2) + 1
+
+         ! shift indexing of source grid
+         ref_wgts(nxt_wgt)%data_jpi(:,:,:) = ref_wgts(nxt_wgt)%data_jpi(:,:,:) - ref_wgts(nxt_wgt)%botleft(1) + 1
+         ref_wgts(nxt_wgt)%data_jpj(:,:,:) = ref_wgts(nxt_wgt)%data_jpj(:,:,:) - ref_wgts(nxt_wgt)%botleft(2) + 1
+
+         ! create input grid, give it a halo to allow gradient calculations
+         ! SA: +3 stencil is a patch to avoid out-of-bound computation in some configuration. 
+         ! a more robust solution will be given in next release
+         ipk =  SIZE(sd%fnow, 3)
+         ALLOCATE( ref_wgts(nxt_wgt)%fly_dta(ref_wgts(nxt_wgt)%jpiwgt+3, ref_wgts(nxt_wgt)%jpjwgt+3 ,ipk) )
+         IF( ref_wgts(nxt_wgt)%cyclic ) ALLOCATE( ref_wgts(nxt_wgt)%col(1,ref_wgts(nxt_wgt)%jpjwgt+3,ipk) )
+         !
+         nxt_wgt = nxt_wgt + 1
+         !
+      ELSE 
+         CALL ctl_stop( '    fld_weight : unable to read the file ' )
+      ENDIF
+
+      DEALLOCATE (ddims )
+      !
+   END SUBROUTINE fld_weight
+
+
+   SUBROUTINE apply_seaoverland( clmaskfile, zfieldo, jpi1_lsm, jpi2_lsm, jpj1_lsm,   &
+      &                          jpj2_lsm, itmpi, itmpj, itmpz, rec1_lsm, recn_lsm )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE apply_seaoverland  ***
+      !!
+      !! ** Purpose :   avoid spurious fluxes in coastal or near-coastal areas
+      !!                due to the wrong usage of "land" values from the coarse
+      !!                atmospheric model when spatial interpolation is required
+      !!      D. Delrosso INGV          
+      !!---------------------------------------------------------------------- 
+      INTEGER,                   INTENT(in   ) :: itmpi,itmpj,itmpz                    ! lengths
+      INTEGER,                   INTENT(in   ) :: jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm  ! temporary indices
+      INTEGER, DIMENSION(3),     INTENT(in   ) :: rec1_lsm,recn_lsm                    ! temporary arrays for start and length
+      REAL(wp),DIMENSION (:,:,:),INTENT(inout) :: zfieldo                              ! input/output array for seaoverland application
+      CHARACTER (len=100),       INTENT(in   ) :: clmaskfile                           ! land/sea mask file name
+      !
+      INTEGER :: inum,jni,jnj,jnz,jc   ! local indices
+      REAL(wp),DIMENSION (:,:,:),ALLOCATABLE :: zslmec1             ! local array for land point detection
+      REAL(wp),DIMENSION (:,:),  ALLOCATABLE :: zfieldn   ! array of forcing field with undeff for land points
+      REAL(wp),DIMENSION (:,:),  ALLOCATABLE :: zfield    ! array of forcing field
+      !!---------------------------------------------------------------------
+      !
+      ALLOCATE ( zslmec1(itmpi,itmpj,itmpz), zfieldn(itmpi,itmpj), zfield(itmpi,itmpj) )
+      !
+      ! Retrieve the land sea mask data
+      CALL iom_open( clmaskfile, inum )
+      SELECT CASE( SIZE(zfieldo(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),3) )
+      CASE(1)
+         CALL iom_get( inum, jpdom_unknown, 'LSM', zslmec1(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,1), 1, rec1_lsm, recn_lsm)
+      CASE DEFAULT
+         CALL iom_get( inum, jpdom_unknown, 'LSM', zslmec1(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:), 1, rec1_lsm, recn_lsm)
+      END SELECT
+      CALL iom_close( inum )
+      !
+      DO jnz=1,rec1_lsm(3)             !! Loop over k dimension
+         !
+         DO jni = 1, itmpi                               !! copy the original field into a tmp array
+            DO jnj = 1, itmpj                            !! substituting undeff over land points
+               zfieldn(jni,jnj) = zfieldo(jni,jnj,jnz)
+               IF( zslmec1(jni,jnj,jnz) == 1. )   zfieldn(jni,jnj) = undeff_lsm
+            END DO
+         END DO
+         !
+         CALL seaoverland( zfieldn, itmpi, itmpj, zfield )
+         DO jc = 1, nn_lsm
+            CALL seaoverland( zfield, itmpi, itmpj, zfield )
+         END DO
+         !
+         !   Check for Undeff and substitute original values
+         IF( ANY(zfield==undeff_lsm) ) THEN
+            DO jni = 1, itmpi
+               DO jnj = 1, itmpj
+                  IF( zfield(jni,jnj)==undeff_lsm )   zfield(jni,jnj) = zfieldo(jni,jnj,jnz)
+               END DO
+            END DO
+         ENDIF
+         !
+         zfieldo(:,:,jnz) = zfield(:,:)
+         !
+      END DO                           !! End Loop over k dimension
+      !
+      DEALLOCATE ( zslmec1, zfieldn, zfield )
+      !
+   END SUBROUTINE apply_seaoverland 
+
+
+   SUBROUTINE seaoverland( zfieldn, ileni, ilenj, zfield )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE seaoverland  ***
+      !!
+      !! ** Purpose :   create shifted matrices for seaoverland application  
+      !!      D. Delrosso INGV
+      !!---------------------------------------------------------------------- 
+      INTEGER                      , INTENT(in   ) :: ileni,ilenj   ! lengths 
+      REAL, DIMENSION (ileni,ilenj), INTENT(in   ) :: zfieldn       ! array of forcing field with undeff for land points
+      REAL, DIMENSION (ileni,ilenj), INTENT(  out) :: zfield        ! array of forcing field
+      !
+      REAL   , DIMENSION (ileni,ilenj)   :: zmat1, zmat2, zmat3, zmat4  ! local arrays 
+      REAL   , DIMENSION (ileni,ilenj)   :: zmat5, zmat6, zmat7, zmat8  !   -     - 
+      REAL   , DIMENSION (ileni,ilenj)   :: zlsm2d                      !   -     - 
+      REAL   , DIMENSION (ileni,ilenj,8) :: zlsm3d                      !   -     -
+      LOGICAL, DIMENSION (ileni,ilenj,8) :: ll_msknan3d                 ! logical mask for undeff detection
+      LOGICAL, DIMENSION (ileni,ilenj)   :: ll_msknan2d                 ! logical mask for undeff detection
+      !!---------------------------------------------------------------------- 
+      zmat8 = eoshift( zfieldn , SHIFT=-1 , BOUNDARY = (/zfieldn(:,1)/)     , DIM=2 )
+      zmat1 = eoshift( zmat8   , SHIFT=-1 , BOUNDARY = (/zmat8(1,:)/)       , DIM=1 )
+      zmat2 = eoshift( zfieldn , SHIFT=-1 , BOUNDARY = (/zfieldn(1,:)/)     , DIM=1 )
+      zmat4 = eoshift( zfieldn , SHIFT= 1 , BOUNDARY = (/zfieldn(:,ilenj)/) , DIM=2 )
+      zmat3 = eoshift( zmat4   , SHIFT=-1 , BOUNDARY = (/zmat4(1,:)/)       , DIM=1 )
+      zmat5 = eoshift( zmat4   , SHIFT= 1 , BOUNDARY = (/zmat4(ileni,:)/)   , DIM=1 )
+      zmat6 = eoshift( zfieldn , SHIFT= 1 , BOUNDARY = (/zfieldn(ileni,:)/) , DIM=1 )
+      zmat7 = eoshift( zmat8   , SHIFT= 1 , BOUNDARY = (/zmat8(ileni,:)/)   , DIM=1 )
+      !
+      zlsm3d  = RESHAPE( (/ zmat1, zmat2, zmat3, zmat4, zmat5, zmat6, zmat7, zmat8 /), (/ ileni, ilenj, 8 /))
+      ll_msknan3d = .NOT.( zlsm3d  == undeff_lsm )
+      ll_msknan2d = .NOT.( zfieldn == undeff_lsm )  ! FALSE where is Undeff (land)
+      zlsm2d = SUM( zlsm3d, 3 , ll_msknan3d ) / MAX( 1 , COUNT( ll_msknan3d , 3 ) )
+      WHERE( COUNT( ll_msknan3d , 3 ) == 0._wp )   zlsm2d = undeff_lsm
+      zfield = MERGE( zfieldn, zlsm2d, ll_msknan2d )
+      !
+   END SUBROUTINE seaoverland
+
+
+   SUBROUTINE fld_interp( num, clvar, kw, kk, dta,  &
+                          &         nrec, lsmfile)      
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE fld_interp  ***
+      !!
+      !! ** Purpose :   apply weights to input gridded data to create data
+      !!                on model grid
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   num     ! stream number
+      CHARACTER(LEN=*)          , INTENT(in   ) ::   clvar   ! variable name
+      INTEGER                   , INTENT(in   ) ::   kw      ! weights number
+      INTEGER                   , INTENT(in   ) ::   kk      ! vertical dimension of kk
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   dta     ! output field on model grid
+      INTEGER                   , INTENT(in   ) ::   nrec    ! record number to read (ie time slice)
+      CHARACTER(LEN=*)          , INTENT(in   ) ::   lsmfile ! land sea mask file name
+      !
+      INTEGER, DIMENSION(3) ::   rec1, recn           ! temporary arrays for start and length
+      INTEGER, DIMENSION(3) ::   rec1_lsm, recn_lsm   ! temporary arrays for start and length in case of seaoverland
+      INTEGER ::   ii_lsm1,ii_lsm2,ij_lsm1,ij_lsm2    ! temporary indices
+      INTEGER ::   jk, jn, jm, jir, jjr               ! loop counters
+      INTEGER ::   ni, nj                             ! lengths
+      INTEGER ::   jpimin,jpiwid                      ! temporary indices
+      INTEGER ::   jpimin_lsm,jpiwid_lsm              ! temporary indices
+      INTEGER ::   jpjmin,jpjwid                      ! temporary indices
+      INTEGER ::   jpjmin_lsm,jpjwid_lsm              ! temporary indices
+      INTEGER ::   jpi1,jpi2,jpj1,jpj2                ! temporary indices
+      INTEGER ::   jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm   ! temporary indices
+      INTEGER ::   itmpi,itmpj,itmpz                     ! lengths
+      REAL(wp),DIMENSION(:,:,:), ALLOCATABLE ::   ztmp_fly_dta                 ! local array of values on input grid     
+      !!----------------------------------------------------------------------
+      !
+      !! for weighted interpolation we have weights at four corners of a box surrounding 
+      !! a model grid point, each weight is multiplied by a grid value (bilinear case)
+      !! or by a grid value and gradients at the corner point (bicubic case) 
+      !! so we need to have a 4 by 4 subgrid surrounding each model point to cover both cases
+
+      !! sub grid from non-model input grid which encloses all grid points in this nemo process
+      jpimin = ref_wgts(kw)%botleft(1)
+      jpjmin = ref_wgts(kw)%botleft(2)
+      jpiwid = ref_wgts(kw)%jpiwgt
+      jpjwid = ref_wgts(kw)%jpjwgt
+
+      !! when reading in, expand this sub-grid by one halo point all the way round for calculating gradients
+      rec1(1) = MAX( jpimin-1, 1 )
+      rec1(2) = MAX( jpjmin-1, 1 )
+      rec1(3) = 1
+      recn(1) = MIN( jpiwid+2, ref_wgts(kw)%ddims(1)-rec1(1)+1 )
+      recn(2) = MIN( jpjwid+2, ref_wgts(kw)%ddims(2)-rec1(2)+1 )
+      recn(3) = kk
+
+      !! where we need to put it in the non-nemo grid fly_dta
+      !! note that jpi1 and jpj1 only differ from 1 when jpimin and jpjmin are 1
+      !! (ie at the extreme west or south of the whole input grid) and similarly for jpi2 and jpj2
+      jpi1 = 2 + rec1(1) - jpimin
+      jpj1 = 2 + rec1(2) - jpjmin
+      jpi2 = jpi1 + recn(1) - 1
+      jpj2 = jpj1 + recn(2) - 1
+
+
+      IF( LEN( TRIM(lsmfile) ) > 0 ) THEN
+      !! indeces for ztmp_fly_dta
+      ! --------------------------
+         rec1_lsm(1)=MAX(rec1(1)-nn_lsm,1)  ! starting index for enlarged external data, x direction
+         rec1_lsm(2)=MAX(rec1(2)-nn_lsm,1)  ! starting index for enlarged external data, y direction
+         rec1_lsm(3) = 1                    ! vertical dimension
+         recn_lsm(1)=MIN(rec1(1)-rec1_lsm(1)+recn(1)+nn_lsm,ref_wgts(kw)%ddims(1)-rec1_lsm(1)) ! n points in x direction
+         recn_lsm(2)=MIN(rec1(2)-rec1_lsm(2)+recn(2)+nn_lsm,ref_wgts(kw)%ddims(2)-rec1_lsm(2)) ! n points in y direction
+         recn_lsm(3) = kk                   ! number of vertical levels in the input file
+
+      !  Avoid out of bound
+         jpimin_lsm = MAX( rec1_lsm(1)+1, 1 )
+         jpjmin_lsm = MAX( rec1_lsm(2)+1, 1 )
+         jpiwid_lsm = MIN( recn_lsm(1)-2,ref_wgts(kw)%ddims(1)-rec1(1)+1)
+         jpjwid_lsm = MIN( recn_lsm(2)-2,ref_wgts(kw)%ddims(2)-rec1(2)+1)
+
+         jpi1_lsm = 2+rec1_lsm(1)-jpimin_lsm
+         jpj1_lsm = 2+rec1_lsm(2)-jpjmin_lsm
+         jpi2_lsm = jpi1_lsm + recn_lsm(1) - 1
+         jpj2_lsm = jpj1_lsm + recn_lsm(2) - 1
+
+
+         itmpi=jpi2_lsm-jpi1_lsm+1
+         itmpj=jpj2_lsm-jpj1_lsm+1
+         itmpz=kk
+         ALLOCATE(ztmp_fly_dta(itmpi,itmpj,itmpz))
+         ztmp_fly_dta(:,:,:) = 0.0
+         SELECT CASE( SIZE(ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),3) )
+         CASE(1)
+              CALL iom_get( num, jpdom_unknown, clvar, ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,1),   &
+                 &                                                                nrec, rec1_lsm, recn_lsm)
+         CASE DEFAULT
+              CALL iom_get( num, jpdom_unknown, clvar, ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),   &
+                 &                                                                nrec, rec1_lsm, recn_lsm)
+         END SELECT
+         CALL apply_seaoverland(lsmfile,ztmp_fly_dta(jpi1_lsm:jpi2_lsm,jpj1_lsm:jpj2_lsm,:),                  &
+                 &                                      jpi1_lsm,jpi2_lsm,jpj1_lsm,jpj2_lsm,                  &
+                 &                                      itmpi,itmpj,itmpz,rec1_lsm,recn_lsm)
+
+
+         ! Relative indeces for remapping
+         ii_lsm1 = (rec1(1)-rec1_lsm(1))+1
+         ii_lsm2 = (ii_lsm1+recn(1))-1
+         ij_lsm1 = (rec1(2)-rec1_lsm(2))+1
+         ij_lsm2 = (ij_lsm1+recn(2))-1
+
+         ref_wgts(kw)%fly_dta(:,:,:) = 0.0
+         ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,:) = ztmp_fly_dta(ii_lsm1:ii_lsm2,ij_lsm1:ij_lsm2,:)
+         DEALLOCATE(ztmp_fly_dta)
+
+      ELSE
+         
+         ref_wgts(kw)%fly_dta(:,:,:) = 0.0
+         SELECT CASE( SIZE(ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,:),3) )
+         CASE(1)
+              CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,1), nrec, rec1, recn)
+         CASE DEFAULT
+              CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%fly_dta(jpi1:jpi2,jpj1:jpj2,:), nrec, rec1, recn)
+         END SELECT 
+      ENDIF
+      
+
+      !! first four weights common to both bilinear and bicubic
+      !! data_jpi, data_jpj have already been shifted to (1,1) corresponding to botleft
+      !! note that we have to offset by 1 into fly_dta array because of halo
+      dta(:,:,:) = 0.0
+      DO jk = 1,4
+        DO jn = 1, jpj
+          DO jm = 1,jpi
+            ni = ref_wgts(kw)%data_jpi(jm,jn,jk)
+            nj = ref_wgts(kw)%data_jpj(jm,jn,jk)
+            dta(jm,jn,:) = dta(jm,jn,:) + ref_wgts(kw)%data_wgt(jm,jn,jk) * ref_wgts(kw)%fly_dta(ni+1,nj+1,:)
+          END DO
+        END DO
+      END DO
+
+      IF (ref_wgts(kw)%numwgt .EQ. 16) THEN
+
+        !! fix up halo points that we couldnt read from file
+        IF( jpi1 == 2 ) THEN
+           ref_wgts(kw)%fly_dta(jpi1-1,:,:) = ref_wgts(kw)%fly_dta(jpi1,:,:)
+        ENDIF
+        IF( jpi2 + jpimin - 1 == ref_wgts(kw)%ddims(1)+1 ) THEN
+           ref_wgts(kw)%fly_dta(jpi2+1,:,:) = ref_wgts(kw)%fly_dta(jpi2,:,:)
+        ENDIF
+        IF( jpj1 == 2 ) THEN
+           ref_wgts(kw)%fly_dta(:,jpj1-1,:) = ref_wgts(kw)%fly_dta(:,jpj1,:)
+        ENDIF
+        IF( jpj2 + jpjmin - 1 == ref_wgts(kw)%ddims(2)+1 .AND. jpj2 .lt. jpjwid+2 ) THEN
+           ref_wgts(kw)%fly_dta(:,jpj2+1,:) = 2.0*ref_wgts(kw)%fly_dta(:,jpj2,:) - ref_wgts(kw)%fly_dta(:,jpj2-1,:)
+        ENDIF
+
+        !! if data grid is cyclic we can do better on east-west edges
+        !! but have to allow for whether first and last columns are coincident
+        IF( ref_wgts(kw)%cyclic ) THEN
+           rec1(2) = MAX( jpjmin-1, 1 )
+           recn(1) = 1
+           recn(2) = MIN( jpjwid+2, ref_wgts(kw)%ddims(2)-rec1(2)+1 )
+           jpj1 = 2 + rec1(2) - jpjmin
+           jpj2 = jpj1 + recn(2) - 1
+           IF( jpi1 == 2 ) THEN
+              rec1(1) = ref_wgts(kw)%ddims(1) - ref_wgts(kw)%overlap
+              SELECT CASE( SIZE( ref_wgts(kw)%col(:,jpj1:jpj2,:),3) )
+              CASE(1)
+                   CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,1), nrec, rec1, recn)
+              CASE DEFAULT
+                   CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,:), nrec, rec1, recn)
+              END SELECT      
+              ref_wgts(kw)%fly_dta(jpi1-1,jpj1:jpj2,:) = ref_wgts(kw)%col(1,jpj1:jpj2,:)
+           ENDIF
+           IF( jpi2 + jpimin - 1 == ref_wgts(kw)%ddims(1)+1 ) THEN
+              rec1(1) = 1 + ref_wgts(kw)%overlap
+              SELECT CASE( SIZE( ref_wgts(kw)%col(:,jpj1:jpj2,:),3) )
+              CASE(1)
+                   CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,1), nrec, rec1, recn)
+              CASE DEFAULT
+                   CALL iom_get( num, jpdom_unknown, clvar, ref_wgts(kw)%col(:,jpj1:jpj2,:), nrec, rec1, recn)
+              END SELECT
+              ref_wgts(kw)%fly_dta(jpi2+1,jpj1:jpj2,:) = ref_wgts(kw)%col(1,jpj1:jpj2,:)
+           ENDIF
+        ENDIF
+
+        ! gradient in the i direction
+        DO jk = 1,4
+          DO jn = 1, jpj
+            DO jm = 1,jpi
+              ni = ref_wgts(kw)%data_jpi(jm,jn,jk)
+              nj = ref_wgts(kw)%data_jpj(jm,jn,jk)
+              dta(jm,jn,:) = dta(jm,jn,:) + ref_wgts(kw)%data_wgt(jm,jn,jk+4) * 0.5 *         &
+                               (ref_wgts(kw)%fly_dta(ni+2,nj+1,:) - ref_wgts(kw)%fly_dta(ni,nj+1,:))
+            END DO
+          END DO
+        END DO
+
+        ! gradient in the j direction
+        DO jk = 1,4
+          DO jn = 1, jpj
+            DO jm = 1,jpi
+              ni = ref_wgts(kw)%data_jpi(jm,jn,jk)
+              nj = ref_wgts(kw)%data_jpj(jm,jn,jk)
+              dta(jm,jn,:) = dta(jm,jn,:) + ref_wgts(kw)%data_wgt(jm,jn,jk+8) * 0.5 *         &
+                               (ref_wgts(kw)%fly_dta(ni+1,nj+2,:) - ref_wgts(kw)%fly_dta(ni+1,nj,:))
+            END DO
+          END DO
+        END DO
+
+         ! gradient in the ij direction
+         DO jk = 1,4
+            DO jn = 1, jpj
+               DO jm = 1,jpi
+                  ni = ref_wgts(kw)%data_jpi(jm,jn,jk)
+                  nj = ref_wgts(kw)%data_jpj(jm,jn,jk)
+                  dta(jm,jn,:) = dta(jm,jn,:) + ref_wgts(kw)%data_wgt(jm,jn,jk+12) * 0.25 * ( &
+                               (ref_wgts(kw)%fly_dta(ni+2,nj+2,:) - ref_wgts(kw)%fly_dta(ni  ,nj+2,:)) -   &
+                               (ref_wgts(kw)%fly_dta(ni+2,nj  ,:) - ref_wgts(kw)%fly_dta(ni  ,nj  ,:)))
+               END DO
+            END DO
+         END DO
+         !
+      END IF
+      !
+   END SUBROUTINE fld_interp
+
+
+   FUNCTION ksec_week( cdday )
+      !!---------------------------------------------------------------------
+      !!                    ***  FUNCTION kshift_week *** 
+      !!
+      !! ** Purpose :   return the first 3 letters of the first day of the weekly file
+      !!---------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in)   ::   cdday   ! first 3 letters of the first day of the weekly file
+      !!
+      INTEGER                        ::   ksec_week      ! output variable
+      INTEGER                        ::   ijul, ishift   ! local integer
+      CHARACTER(len=3),DIMENSION(7)  ::   cl_week 
+      !!----------------------------------------------------------------------
+      cl_week = (/"sun","sat","fri","thu","wed","tue","mon"/)
+      DO ijul = 1, 7
+         IF( cl_week(ijul) == TRIM(cdday) ) EXIT
+      END DO
+      IF( ijul .GT. 7 )   CALL ctl_stop( 'ksec_week: wrong day for sdjf%cltype(6:8): '//TRIM(cdday) )
+      !
+      ishift = ijul * NINT(rday)
+      ! 
+      ksec_week = nsec_week + ishift
+      ksec_week = MOD( ksec_week, 7*NINT(rday) )
+      ! 
+   END FUNCTION ksec_week
+
+   !!======================================================================
+END MODULE fldread
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/geo2ocean.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/geo2ocean.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/geo2ocean.F90	(revision 14097)
@@ -0,0 +1,467 @@
+MODULE geo2ocean
+   !!======================================================================
+   !!                     ***  MODULE  geo2ocean  ***
+   !! Ocean mesh    :  ???
+   !!======================================================================
+   !! History :  OPA  !  07-1996  (O. Marti)  Original code
+   !!   NEMO     1.0  !  06-2006  (G. Madec )  Free form, F90 + opt.
+   !!                 !  04-2007  (S. Masson)  angle: Add T, F points and bugfix in cos lateral boundary
+   !!            3.0  !  07-2008  (G. Madec)  geo2oce suppress lon/lat agruments
+   !!            3.7  !  11-2015  (G. Madec)  remove the unused repere and repcmo routines
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   rot_rep       : Rotate the Repere: geographic grid <==> stretched coordinates grid
+   !!   angle         :
+   !!   geo2oce       :
+   !!   oce2geo       :
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! mesh and scale factors
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   rot_rep   ! called in sbccpl, fldread, and cyclone
+   PUBLIC   geo2oce   ! called in sbccpl
+   PUBLIC   oce2geo   ! called in sbccpl
+   PUBLIC   obs_rot   ! called in obs_rot_vel and obs_write
+
+   !                                         ! cos/sin between model grid lines and NP direction
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   gsint, gcost   ! at T point
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   gsinu, gcosu   ! at U point
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   gsinv, gcosv   ! at V point
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   gsinf, gcosf   ! at F point
+
+   LOGICAL ,              SAVE, DIMENSION(4)     ::   linit = .FALSE.
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gsinlon, gcoslon, gsinlat, gcoslat
+
+   LOGICAL ::   lmust_init = .TRUE.        !: used to initialize the cos/sin variables (see above)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE rot_rep ( pxin, pyin, cd_type, cdtodo, prot )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE rot_rep  ***
+      !!
+      !! ** Purpose :   Rotate the Repere: Change vector componantes between
+      !!                geographic grid <--> stretched coordinates grid.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   pxin, pyin   ! vector componantes
+      CHARACTER(len=1),             INTENT(in   ) ::   cd_type      ! define the nature of pt2d array grid-points
+      CHARACTER(len=5),             INTENT(in   ) ::   cdtodo       ! type of transpormation:
+      !                                                             ! 'en->i' = east-north to i-component
+      !                                                             ! 'en->j' = east-north to j-component
+      !                                                             ! 'ij->e' = (i,j) components to east
+      !                                                             ! 'ij->n' = (i,j) components to north
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::   prot      
+      !!----------------------------------------------------------------------
+      !
+      IF( lmust_init ) THEN      ! at 1st call only: set  gsin. & gcos.
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' rot_rep: coordinate transformation : geographic <==> model (i,j)-components'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~    '
+         !
+         CALL angle( glamt, gphit, glamu, gphiu, glamv, gphiv, glamf, gphif )       ! initialization of the transformation
+         lmust_init = .FALSE.
+      ENDIF
+      !
+      SELECT CASE( cdtodo )      ! type of rotation
+      !
+      CASE( 'en->i' )                  ! east-north to i-component
+         SELECT CASE (cd_type)
+         CASE ('T')   ;   prot(:,:) = pxin(:,:) * gcost(:,:) + pyin(:,:) * gsint(:,:)
+         CASE ('U')   ;   prot(:,:) = pxin(:,:) * gcosu(:,:) + pyin(:,:) * gsinu(:,:)
+         CASE ('V')   ;   prot(:,:) = pxin(:,:) * gcosv(:,:) + pyin(:,:) * gsinv(:,:)
+         CASE ('F')   ;   prot(:,:) = pxin(:,:) * gcosf(:,:) + pyin(:,:) * gsinf(:,:)
+         CASE DEFAULT   ;   CALL ctl_stop( 'Only T, U, V and F grid points are coded' )
+         END SELECT
+      CASE ('en->j')                   ! east-north to j-component
+         SELECT CASE (cd_type)
+         CASE ('T')   ;   prot(:,:) = pyin(:,:) * gcost(:,:) - pxin(:,:) * gsint(:,:)
+         CASE ('U')   ;   prot(:,:) = pyin(:,:) * gcosu(:,:) - pxin(:,:) * gsinu(:,:)
+         CASE ('V')   ;   prot(:,:) = pyin(:,:) * gcosv(:,:) - pxin(:,:) * gsinv(:,:)   
+         CASE ('F')   ;   prot(:,:) = pyin(:,:) * gcosf(:,:) - pxin(:,:) * gsinf(:,:)   
+         CASE DEFAULT   ;   CALL ctl_stop( 'Only T, U, V and F grid points are coded' )
+         END SELECT
+      CASE ('ij->e')                   ! (i,j)-components to east
+         SELECT CASE (cd_type)
+         CASE ('T')   ;   prot(:,:) = pxin(:,:) * gcost(:,:) - pyin(:,:) * gsint(:,:)
+         CASE ('U')   ;   prot(:,:) = pxin(:,:) * gcosu(:,:) - pyin(:,:) * gsinu(:,:)
+         CASE ('V')   ;   prot(:,:) = pxin(:,:) * gcosv(:,:) - pyin(:,:) * gsinv(:,:)
+         CASE ('F')   ;   prot(:,:) = pxin(:,:) * gcosf(:,:) - pyin(:,:) * gsinf(:,:)
+         CASE DEFAULT   ;   CALL ctl_stop( 'Only T, U, V and F grid points are coded' )
+         END SELECT
+      CASE ('ij->n')                   ! (i,j)-components to north 
+         SELECT CASE (cd_type)
+         CASE ('T')   ;   prot(:,:) = pyin(:,:) * gcost(:,:) + pxin(:,:) * gsint(:,:)
+         CASE ('U')   ;   prot(:,:) = pyin(:,:) * gcosu(:,:) + pxin(:,:) * gsinu(:,:)
+         CASE ('V')   ;   prot(:,:) = pyin(:,:) * gcosv(:,:) + pxin(:,:) * gsinv(:,:)
+         CASE ('F')   ;   prot(:,:) = pyin(:,:) * gcosf(:,:) + pxin(:,:) * gsinf(:,:)
+         CASE DEFAULT   ;   CALL ctl_stop( 'Only T, U, V and F grid points are coded' )
+         END SELECT
+      CASE DEFAULT   ;   CALL ctl_stop( 'rot_rep: Syntax Error in the definition of cdtodo' )
+      !
+      END SELECT
+      !
+   END SUBROUTINE rot_rep
+
+
+   SUBROUTINE angle( plamt, pphit, plamu, pphiu, plamv, pphiv, plamf, pphif )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE angle  ***
+      !! 
+      !! ** Purpose :   Compute angles between model grid lines and the North direction
+      !!
+      !! ** Method  :   sinus and cosinus of the angle between the north-south axe 
+      !!              and the j-direction at t, u, v and f-points
+      !!                dot and cross products are used to obtain cos and sin, resp.
+      !!
+      !! ** Action  : - gsint, gcost, gsinu, gcosu, gsinv, gcosv, gsinf, gcosf
+      !!----------------------------------------------------------------------
+      ! WARNING: for an unexplained reason, we need to pass all glam, gphi arrays as input parameters in
+      !          order to get AGRIF working with -03 compilation option
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) :: plamt, pphit, plamu, pphiu, plamv, pphiv, plamf, pphif  
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      INTEGER  ::   ierr     ! local integer
+      REAL(wp) ::   zlam, zphi            ! local scalars
+      REAL(wp) ::   zlan, zphh            !   -      -
+      REAL(wp) ::   zxnpt, zynpt, znnpt   ! x,y components and norm of the vector: T point to North Pole
+      REAL(wp) ::   zxnpu, zynpu, znnpu   ! x,y components and norm of the vector: U point to North Pole
+      REAL(wp) ::   zxnpv, zynpv, znnpv   ! x,y components and norm of the vector: V point to North Pole
+      REAL(wp) ::   zxnpf, zynpf, znnpf   ! x,y components and norm of the vector: F point to North Pole
+      REAL(wp) ::   zxvvt, zyvvt, znvvt   ! x,y components and norm of the vector: between V points below and above a T point
+      REAL(wp) ::   zxffu, zyffu, znffu   ! x,y components and norm of the vector: between F points below and above a U point
+      REAL(wp) ::   zxffv, zyffv, znffv   ! x,y components and norm of the vector: between F points left  and right a V point
+      REAL(wp) ::   zxuuf, zyuuf, znuuf   ! x,y components and norm of the vector: between U points below and above a F point
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( gsint(jpi,jpj), gcost(jpi,jpj),   & 
+         &      gsinu(jpi,jpj), gcosu(jpi,jpj),   & 
+         &      gsinv(jpi,jpj), gcosv(jpi,jpj),   &  
+         &      gsinf(jpi,jpj), gcosf(jpi,jpj), STAT=ierr )
+      CALL mpp_sum( 'geo2ocean', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'angle: unable to allocate arrays' )
+      !
+      ! ============================= !
+      ! Compute the cosinus and sinus !
+      ! ============================= !
+      ! (computation done on the north stereographic polar plane)
+      !
+      DO jj = 2, jpjm1
+         DO ji = fs_2, jpi   ! vector opt.
+            !                  
+            zlam = plamt(ji,jj)     ! north pole direction & modulous (at t-point)
+            zphi = pphit(ji,jj)
+            zxnpt = 0. - 2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            zynpt = 0. - 2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            znnpt = zxnpt*zxnpt + zynpt*zynpt
+            !
+            zlam = plamu(ji,jj)     ! north pole direction & modulous (at u-point)
+            zphi = pphiu(ji,jj)
+            zxnpu = 0. - 2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            zynpu = 0. - 2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            znnpu = zxnpu*zxnpu + zynpu*zynpu
+            !
+            zlam = plamv(ji,jj)     ! north pole direction & modulous (at v-point)
+            zphi = pphiv(ji,jj)
+            zxnpv = 0. - 2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            zynpv = 0. - 2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            znnpv = zxnpv*zxnpv + zynpv*zynpv
+            !
+            zlam = plamf(ji,jj)     ! north pole direction & modulous (at f-point)
+            zphi = pphif(ji,jj)
+            zxnpf = 0. - 2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            zynpf = 0. - 2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )
+            znnpf = zxnpf*zxnpf + zynpf*zynpf
+            !
+            zlam = plamv(ji,jj  )   ! j-direction: v-point segment direction (around t-point)
+            zphi = pphiv(ji,jj  )
+            zlan = plamv(ji,jj-1)
+            zphh = pphiv(ji,jj-1)
+            zxvvt =  2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * COS( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            zyvvt =  2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * SIN( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            znvvt = SQRT( znnpt * ( zxvvt*zxvvt + zyvvt*zyvvt )  )
+            znvvt = MAX( znvvt, 1.e-14 )
+            !
+            zlam = plamf(ji,jj  )   ! j-direction: f-point segment direction (around u-point)
+            zphi = pphif(ji,jj  )
+            zlan = plamf(ji,jj-1)
+            zphh = pphif(ji,jj-1)
+            zxffu =  2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * COS( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            zyffu =  2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * SIN( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            znffu = SQRT( znnpu * ( zxffu*zxffu + zyffu*zyffu )  )
+            znffu = MAX( znffu, 1.e-14 )
+            !
+            zlam = plamf(ji  ,jj)   ! i-direction: f-point segment direction (around v-point)
+            zphi = pphif(ji  ,jj)
+            zlan = plamf(ji-1,jj)
+            zphh = pphif(ji-1,jj)
+            zxffv =  2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * COS( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            zyffv =  2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * SIN( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            znffv = SQRT( znnpv * ( zxffv*zxffv + zyffv*zyffv )  )
+            znffv = MAX( znffv, 1.e-14 )
+            !
+            zlam = plamu(ji,jj+1)   ! j-direction: u-point segment direction (around f-point)
+            zphi = pphiu(ji,jj+1)
+            zlan = plamu(ji,jj  )
+            zphh = pphiu(ji,jj  )
+            zxuuf =  2. * COS( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * COS( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            zyuuf =  2. * SIN( rad*zlam ) * TAN( rpi/4. - rad*zphi/2. )   &
+               &  -  2. * SIN( rad*zlan ) * TAN( rpi/4. - rad*zphh/2. )
+            znuuf = SQRT( znnpf * ( zxuuf*zxuuf + zyuuf*zyuuf )  )
+            znuuf = MAX( znuuf, 1.e-14 )
+            !
+            !                       ! cosinus and sinus using dot and cross products
+            gsint(ji,jj) = ( zxnpt*zyvvt - zynpt*zxvvt ) / znvvt
+            gcost(ji,jj) = ( zxnpt*zxvvt + zynpt*zyvvt ) / znvvt
+            !
+            gsinu(ji,jj) = ( zxnpu*zyffu - zynpu*zxffu ) / znffu
+            gcosu(ji,jj) = ( zxnpu*zxffu + zynpu*zyffu ) / znffu
+            !
+            gsinf(ji,jj) = ( zxnpf*zyuuf - zynpf*zxuuf ) / znuuf
+            gcosf(ji,jj) = ( zxnpf*zxuuf + zynpf*zyuuf ) / znuuf
+            !
+            gsinv(ji,jj) = ( zxnpv*zxffv + zynpv*zyffv ) / znffv
+            gcosv(ji,jj) =-( zxnpv*zyffv - zynpv*zxffv ) / znffv     ! (caution, rotation of 90 degres)
+            !
+         END DO
+      END DO
+
+      ! =============== !
+      ! Geographic mesh !
+      ! =============== !
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, jpi   ! vector opt.
+            IF( MOD( ABS( plamv(ji,jj) - plamv(ji,jj-1) ), 360. ) < 1.e-8 ) THEN
+               gsint(ji,jj) = 0.
+               gcost(ji,jj) = 1.
+            ENDIF
+            IF( MOD( ABS( plamf(ji,jj) - plamf(ji,jj-1) ), 360. ) < 1.e-8 ) THEN
+               gsinu(ji,jj) = 0.
+               gcosu(ji,jj) = 1.
+            ENDIF
+            IF(      ABS( pphif(ji,jj) - pphif(ji-1,jj) )         < 1.e-8 ) THEN
+               gsinv(ji,jj) = 0.
+               gcosv(ji,jj) = 1.
+            ENDIF
+            IF( MOD( ABS( plamu(ji,jj) - plamu(ji,jj+1) ), 360. ) < 1.e-8 ) THEN
+               gsinf(ji,jj) = 0.
+               gcosf(ji,jj) = 1.
+            ENDIF
+         END DO
+      END DO
+
+      ! =========================== !
+      ! Lateral boundary conditions !
+      ! =========================== !
+      !           ! lateral boundary cond.: T-, U-, V-, F-pts, sgn
+      CALL lbc_lnk_multi( 'geo2ocean', gcost, 'T', -1., gsint, 'T', -1., gcosu, 'U', -1., gsinu, 'U', -1., & 
+                      &   gcosv, 'V', -1., gsinv, 'V', -1., gcosf, 'F', -1., gsinf, 'F', -1.  )
+      !
+   END SUBROUTINE angle
+
+
+   SUBROUTINE geo2oce ( pxx, pyy, pzz, cgrid, pte, ptn )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE geo2oce  ***
+      !!      
+      !! ** Purpose :
+      !!
+      !! ** Method  :   Change a vector from geocentric to east/north 
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::  pxx, pyy, pzz
+      CHARACTER(len=1)            , INTENT(in   ) ::  cgrid
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(  out) ::  pte, ptn
+      !
+      REAL(wp), PARAMETER :: rpi = 3.141592653e0
+      REAL(wp), PARAMETER :: rad = rpi / 180.e0
+      INTEGER ::   ig     !
+      INTEGER ::   ierr   ! local integer
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT. ALLOCATED( gsinlon ) ) THEN
+         ALLOCATE( gsinlon(jpi,jpj,4) , gcoslon(jpi,jpj,4) ,   &
+            &      gsinlat(jpi,jpj,4) , gcoslat(jpi,jpj,4) , STAT=ierr )
+         CALL mpp_sum( 'geo2ocean', ierr )
+         IF( ierr /= 0 )   CALL ctl_stop('geo2oce: unable to allocate arrays' )
+      ENDIF
+      !
+      SELECT CASE( cgrid)
+      CASE ( 'T' )   
+         ig = 1
+         IF( .NOT. linit(ig) ) THEN 
+            gsinlon(:,:,ig) = SIN( rad * glamt(:,:) )
+            gcoslon(:,:,ig) = COS( rad * glamt(:,:) )
+            gsinlat(:,:,ig) = SIN( rad * gphit(:,:) )
+            gcoslat(:,:,ig) = COS( rad * gphit(:,:) )
+            linit(ig) = .TRUE.
+         ENDIF
+      CASE ( 'U' )   
+         ig = 2
+         IF( .NOT. linit(ig) ) THEN 
+            gsinlon(:,:,ig) = SIN( rad * glamu(:,:) )
+            gcoslon(:,:,ig) = COS( rad * glamu(:,:) )
+            gsinlat(:,:,ig) = SIN( rad * gphiu(:,:) )
+            gcoslat(:,:,ig) = COS( rad * gphiu(:,:) )
+            linit(ig) = .TRUE.
+         ENDIF
+      CASE ( 'V' )   
+         ig = 3
+         IF( .NOT. linit(ig) ) THEN 
+            gsinlon(:,:,ig) = SIN( rad * glamv(:,:) )
+            gcoslon(:,:,ig) = COS( rad * glamv(:,:) )
+            gsinlat(:,:,ig) = SIN( rad * gphiv(:,:) )
+            gcoslat(:,:,ig) = COS( rad * gphiv(:,:) )
+            linit(ig) = .TRUE.
+         ENDIF
+      CASE ( 'F' )   
+         ig = 4
+         IF( .NOT. linit(ig) ) THEN 
+            gsinlon(:,:,ig) = SIN( rad * glamf(:,:) )
+            gcoslon(:,:,ig) = COS( rad * glamf(:,:) )
+            gsinlat(:,:,ig) = SIN( rad * gphif(:,:) )
+            gcoslat(:,:,ig) = COS( rad * gphif(:,:) )
+            linit(ig) = .TRUE.
+         ENDIF
+      CASE default   
+         WRITE(ctmp1,*) 'geo2oce : bad grid argument : ', cgrid
+         CALL ctl_stop( ctmp1 )
+      END SELECT
+      !
+      pte = - gsinlon(:,:,ig) * pxx + gcoslon(:,:,ig) * pyy
+      ptn = - gcoslon(:,:,ig) * gsinlat(:,:,ig) * pxx    &
+         &  - gsinlon(:,:,ig) * gsinlat(:,:,ig) * pyy    &
+         &  + gcoslat(:,:,ig) * pzz
+      !
+   END SUBROUTINE geo2oce
+
+
+   SUBROUTINE oce2geo ( pte, ptn, cgrid, pxx , pyy , pzz )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE oce2geo  ***
+      !!      
+      !! ** Purpose :
+      !!
+      !! ** Method  :   Change vector from east/north to geocentric
+      !!
+      !! History :     ! (A. Caubel)  oce2geo - Original code
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT( IN    ) ::  pte, ptn
+      CHARACTER(len=1)            , INTENT( IN    ) ::  cgrid
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(   OUT ) ::  pxx , pyy , pzz
+      !!
+      REAL(wp), PARAMETER :: rpi = 3.141592653E0
+      REAL(wp), PARAMETER :: rad = rpi / 180.e0
+      INTEGER ::   ig     !
+      INTEGER ::   ierr   ! local integer
+      !!----------------------------------------------------------------------
+
+      IF( .NOT. ALLOCATED( gsinlon ) ) THEN
+         ALLOCATE( gsinlon(jpi,jpj,4) , gcoslon(jpi,jpj,4) ,   &
+            &      gsinlat(jpi,jpj,4) , gcoslat(jpi,jpj,4) , STAT=ierr )
+         CALL mpp_sum( 'geo2ocean', ierr )
+         IF( ierr /= 0 )   CALL ctl_stop('oce2geo: unable to allocate arrays' )
+      ENDIF
+
+      SELECT CASE( cgrid)
+         CASE ( 'T' )   
+            ig = 1
+            IF( .NOT. linit(ig) ) THEN 
+               gsinlon(:,:,ig) = SIN( rad * glamt(:,:) )
+               gcoslon(:,:,ig) = COS( rad * glamt(:,:) )
+               gsinlat(:,:,ig) = SIN( rad * gphit(:,:) )
+               gcoslat(:,:,ig) = COS( rad * gphit(:,:) )
+               linit(ig) = .TRUE.
+            ENDIF
+         CASE ( 'U' )   
+            ig = 2
+            IF( .NOT. linit(ig) ) THEN 
+               gsinlon(:,:,ig) = SIN( rad * glamu(:,:) )
+               gcoslon(:,:,ig) = COS( rad * glamu(:,:) )
+               gsinlat(:,:,ig) = SIN( rad * gphiu(:,:) )
+               gcoslat(:,:,ig) = COS( rad * gphiu(:,:) )
+               linit(ig) = .TRUE.
+            ENDIF
+         CASE ( 'V' )   
+            ig = 3
+            IF( .NOT. linit(ig) ) THEN 
+               gsinlon(:,:,ig) = SIN( rad * glamv(:,:) )
+               gcoslon(:,:,ig) = COS( rad * glamv(:,:) )
+               gsinlat(:,:,ig) = SIN( rad * gphiv(:,:) )
+               gcoslat(:,:,ig) = COS( rad * gphiv(:,:) )
+               linit(ig) = .TRUE.
+            ENDIF
+         CASE ( 'F' )   
+            ig = 4
+            IF( .NOT. linit(ig) ) THEN 
+               gsinlon(:,:,ig) = SIN( rad * glamf(:,:) )
+               gcoslon(:,:,ig) = COS( rad * glamf(:,:) )
+               gsinlat(:,:,ig) = SIN( rad * gphif(:,:) )
+               gcoslat(:,:,ig) = COS( rad * gphif(:,:) )
+               linit(ig) = .TRUE.
+            ENDIF
+         CASE default   
+            WRITE(ctmp1,*) 'geo2oce : bad grid argument : ', cgrid
+            CALL ctl_stop( ctmp1 )
+      END SELECT
+      !
+      pxx = - gsinlon(:,:,ig) * pte - gcoslon(:,:,ig) * gsinlat(:,:,ig) * ptn 
+      pyy =   gcoslon(:,:,ig) * pte - gsinlon(:,:,ig) * gsinlat(:,:,ig) * ptn
+      pzz =   gcoslat(:,:,ig) * ptn
+      !
+   END SUBROUTINE oce2geo
+
+
+   SUBROUTINE obs_rot( psinu, pcosu, psinv, pcosv )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE obs_rot  ***
+      !!
+      !! ** Purpose :   Copy gsinu, gcosu, gsinv and gsinv
+      !!                to input data for rotations of
+      !!                current at observation points
+      !!
+      !! History :  9.2  !  09-02  (K. Mogensen)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT( OUT )::   psinu, pcosu, psinv, pcosv   ! copy of data
+      !!----------------------------------------------------------------------
+      !
+      ! Initialization of gsin* and gcos* at first call
+      ! -----------------------------------------------
+      IF( lmust_init ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' obs_rot : geographic <--> stretched'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~   coordinate transformation'
+         CALL angle( glamt, gphit, glamu, gphiu, glamv, gphiv, glamf, gphif )       ! initialization of the transformation
+         lmust_init = .FALSE.
+      ENDIF
+      !
+      psinu(:,:) = gsinu(:,:)
+      pcosu(:,:) = gcosu(:,:)
+      psinv(:,:) = gsinv(:,:)
+      pcosv(:,:) = gcosv(:,:)
+      !
+   END SUBROUTINE obs_rot
+
+  !!======================================================================
+END MODULE geo2ocean
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/ocealb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/ocealb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/ocealb.F90	(revision 14097)
@@ -0,0 +1,48 @@
+MODULE ocealb
+   !!======================================================================
+   !!                       ***  MODULE  ocealb  ***
+   !! Ocean forcing:  bulk thermohaline forcing of the ocean
+   !!=====================================================================
+   !! History :
+   !!   NEMO     4.0  ! 2017-07  (C. Rousset) Split ocean and ice albedos
+   !!----------------------------------------------------------------------
+   !!   oce_alb    : albedo for ocean (clear and overcast skies)
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
+   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)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   oce_alb   ! routine called by sbccpl
+  
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE oce_alb( palb_os , palb_cs )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE oce_alb  ***
+      !! 
+      !! ** Purpose :   Computation of the albedo of the ocean
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   palb_os   !  albedo of ocean under overcast sky
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   palb_cs   !  albedo of ocean under clear sky
+      !!
+      REAL(wp) ::   zcoef 
+      REAL(wp) ::   rmue = 0.40    !  cosine of local solar altitude
+      !!----------------------------------------------------------------------
+      !
+      zcoef = 0.05 / ( 1.1 * rmue**1.4 + 0.15 )   ! Parameterization of Briegled and Ramanathan, 1982
+      palb_cs(:,:) = zcoef 
+      palb_os(:,:) = 0.06                         ! Parameterization of Kondratyev, 1969 and Payne, 1972
+      !
+   END SUBROUTINE oce_alb
+
+   !!======================================================================
+END MODULE ocealb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_ice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_ice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_ice.F90	(revision 14097)
@@ -0,0 +1,205 @@
+MODULE sbc_ice
+   !!======================================================================
+   !!                 ***  MODULE  sbc_ice  ***
+   !! Surface module - SI3 & CICE: parameters & variables defined in memory
+   !!======================================================================
+   !! History :  3.0   !  2006-08  (G. Madec)        Surface module
+   !!            3.2   !  2009-06  (S. Masson)       merge with ice_oce
+   !!            3.3.1 !  2011-01  (A. R. Porter, STFC Daresbury) dynamical allocation
+   !!            3.4   !  2011-11  (C. Harris)       CICE added as an option
+   !!            4.0   !  2018     (many people)     SI3 compatibility
+   !!----------------------------------------------------------------------
+#if defined key_si3 || defined key_cice
+   !!----------------------------------------------------------------------
+   !!   'key_si3' or 'key_cice' :              SI3 or CICE sea-ice model
+   !!----------------------------------------------------------------------
+   USE par_oce          ! ocean parameters
+   USE sbc_oce          ! surface boundary condition: ocean
+# if defined key_si3
+   USE ice              ! SI3 parameters
+# endif
+# if defined key_cice
+   USE ice_domain_size, only: ncat 
+#endif
+   USE lib_mpp          ! MPP library
+   USE in_out_manager   ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ice_alloc   ! called in sbcmod.F90 or sbcice_cice.F90
+
+# if defined  key_si3
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_si3     = .TRUE.   !: SI3 ice model
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_cice    = .FALSE.  !: no CICE 
+# endif
+# if defined  key_cice
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_si3     = .FALSE.  !: no SI3
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_cice    = .TRUE.   !: CICE ice model
+# endif
+
+   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(:,:,:) ::   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(:,:,:) ::   qml_ice        !: heat available for snow / ice surface melting     [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qcn_ice        !: heat conduction flux in the layer below surface   [W/m2] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qtr_ice_top    !: solar flux transmitted below the ice surface      [W/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(:,:)   ::   emp_ice        !: sublimation - precip over sea ice          [kg/m2/s]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   topmelt            !: category topmelt
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   botmelt            !: category botmelt
+
+#if defined  key_si3
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   evap_ice       !: sublimation                              [kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   devap_ice      !: sublimation sensitivity                [kg/m2/s/K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qns_oce        !: non solar heat flux over ocean              [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qsr_oce        !: non solar heat flux over ocean              [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qemp_oce       !: heat flux of precip and evap over ocean     [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qemp_ice       !: heat flux of precip and evap over ice       [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qevap_ice      !: heat flux of evap over ice                  [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qprec_ice      !: enthalpy of precip over ice                 [J/m3]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_oce        !: evap - precip over ocean                 [kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wndm_ice       !: wind speed module at T-point                 [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sstfrz         !: sea surface freezing temperature            [degC]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rCdU_ice       !: ice-ocean drag at T-point (<0)               [m/s]
+#endif
+
+#if defined key_cice
+   !
+   ! for consistency with SI3, these are declared with three dimensions
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qlw_ice            !: incoming long-wave
+   !
+   ! 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(:,:)   ::   qatm_ice           !: specific humidity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wndi_ice           !: i wind at T point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wndj_ice           !: j wind at T point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nfrzmlt            !: NEMO frzmlt
+   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
+   
+   ! variables used in the coupled interface
+   INTEGER , PUBLIC, PARAMETER ::   jpl = ncat
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_ice, v_ice 
+   
+   ! already defined in ice.F90 for SI3
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  a_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  h_i, h_s
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   tatm_ice       !: air temperature [K]
+#endif
+
+   REAL(wp), PUBLIC, SAVE ::   pp_cldf = 0.81    !: cloud fraction over sea ice, summer CLIO value   [-]
+
+   !! arrays relating to embedding ice in the ocean
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_mass        !: mass of snow and ice at current  ice time step   [Kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_mass_b      !: mass of snow and ice at previous ice time step   [Kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_fmass       !: time evolution of mass of snow+ice               [Kg/m2/s]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_ice_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  FUNCTION sbc_ice_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(4)
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+
+      ALLOCATE( snwice_mass(jpi,jpj) , snwice_mass_b(jpi,jpj), snwice_fmass(jpi,jpj) , STAT=ierr(1) )
+
+#if defined key_si3
+      ALLOCATE( qns_ice (jpi,jpj,jpl) , qsr_ice  (jpi,jpj,jpl) ,     &
+         &      qla_ice (jpi,jpj,jpl) , dqla_ice (jpi,jpj,jpl) ,     &
+         &      dqns_ice(jpi,jpj,jpl) , tn_ice   (jpi,jpj,jpl) , alb_ice    (jpi,jpj,jpl) ,   &
+         &      qml_ice (jpi,jpj,jpl) , qcn_ice  (jpi,jpj,jpl) , qtr_ice_top(jpi,jpj,jpl) ,   &
+         &      utau_ice(jpi,jpj)     , vtau_ice (jpi,jpj)     , wndm_ice   (jpi,jpj)     ,   &
+         &      evap_ice(jpi,jpj,jpl) , devap_ice(jpi,jpj,jpl) , qprec_ice  (jpi,jpj)     ,   &
+         &      qemp_ice(jpi,jpj)     , qevap_ice(jpi,jpj,jpl) , qemp_oce   (jpi,jpj)     ,   &
+         &      qns_oce (jpi,jpj)     , qsr_oce  (jpi,jpj)     , emp_oce    (jpi,jpj)     ,   &
+         &      emp_ice (jpi,jpj)     , sstfrz   (jpi,jpj)     , rCdU_ice   (jpi,jpj)     , STAT= ierr(2) )
+#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(2) )
+      IF( ln_cpl )   ALLOCATE( u_ice(jpi,jpj)        , tn_ice (jpi,jpj,1)    , &
+         &                     v_ice(jpi,jpj)        , alb_ice(jpi,jpj,1)    , &
+         &                     emp_ice(jpi,jpj)      , qns_ice(jpi,jpj,1)    , dqns_ice(jpi,jpj,1)   , &
+         &                     STAT= ierr(3) )      
+      IF( ln_cpl )   ALLOCATE( h_i(jpi,jpj,jpl) , h_s(jpi,jpj,jpl) , STAT=ierr(4) )
+#endif
+
+      sbc_ice_alloc = MAXVAL( ierr )
+      CALL mpp_sum ( 'sbc_ice', sbc_ice_alloc )
+      IF( sbc_ice_alloc > 0 )   CALL ctl_warn('sbc_ice_alloc: allocation of arrays failed')
+   END FUNCTION sbc_ice_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                      NO SI3 or CICE sea-ice model
+   !!----------------------------------------------------------------------
+   USE lib_mpp          ! MPP library
+   USE in_out_manager   ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ice_alloc   !
+
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_si3     = .FALSE.  !: no SI3 ice model
+   LOGICAL         , PUBLIC, PARAMETER ::   lk_cice    = .FALSE.  !: no CICE ice model
+   REAL(wp)        , PUBLIC, PARAMETER ::   pp_cldf    = 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                        ! 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(:,:,:) ::   h_i, h_s
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   topmelt, botmelt
+   !
+   !! arrays related to embedding ice in the ocean. 
+   !! These arrays need to be declared even if no ice model is required. 
+   !! In the no ice model or traditional levitating ice cases they contain only zeros
+   !! ---------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_mass        !: mass of snow and ice at current  ice time step   [Kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_mass_b      !: mass of snow and ice at previous ice time step   [Kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_fmass       !: time evolution of mass of snow+ice               [Kg/m2/s]
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_ice_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  FUNCTION sbc_ice_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(1)
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      ALLOCATE( snwice_mass(jpi,jpj) , snwice_mass_b(jpi,jpj), snwice_fmass(jpi,jpj) , STAT=ierr(1) )
+      sbc_ice_alloc = MAXVAL( ierr )
+      CALL mpp_sum ( 'sbc_ice', sbc_ice_alloc )
+      IF( sbc_ice_alloc > 0 )   CALL ctl_warn('sbc_ice_alloc: allocation of arrays failed')
+   END FUNCTION sbc_ice_alloc
+#endif
+
+   !!======================================================================
+END MODULE sbc_ice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbc_oce.F90	(revision 14097)
@@ -0,0 +1,224 @@
+MODULE sbc_oce
+   !!======================================================================
+   !!                       ***  MODULE  sbc_oce  ***
+   !! Surface module :   variables defined in core memory 
+   !!======================================================================
+   !! History :  3.0  ! 2006-06  (G. Madec)  Original code
+   !!             -   ! 2008-08  (G. Madec)  namsbc moved from sbcmod
+   !!            3.3  ! 2010-04  (M. Leclair, G. Madec)  Forcing averaged over 2 time steps
+   !!             -   ! 2010-11  (G. Madec) ice-ocean stress always computed at each ocean time-step
+   !!            3.3  ! 2010-10  (J. Chanut, C. Bricaud)  add the surface pressure forcing
+   !!            4.0  ! 2012-05  (C. Rousset) add attenuation coef for use in ice model 
+   !!            4.0  ! 2016-06  (L. Brodeau) new unified bulk routine (based on AeroBulk)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_oce_alloc : allocation of sbc arrays
+   !!   sbc_tau2wnd   : wind speed estimated from wind stress
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_oce_alloc   ! routine called in sbcmod.F90
+   PUBLIC   sbc_tau2wnd     ! routine called in several sbc modules
+   
+   !!----------------------------------------------------------------------
+   !!           Namelist for the Ocean Surface Boundary Condition
+   !!----------------------------------------------------------------------
+   !                                   !!* namsbc namelist *
+   LOGICAL , PUBLIC ::   ln_usr         !: user defined formulation
+   LOGICAL , PUBLIC ::   ln_flx         !: flux      formulation
+   LOGICAL , PUBLIC ::   ln_blk         !: bulk formulation
+#if defined key_oasis3
+   LOGICAL , PUBLIC ::   lk_oasis = .TRUE.  !: OASIS used
+#else
+   LOGICAL , PUBLIC ::   lk_oasis = .FALSE. !: OASIS unused
+#endif
+   LOGICAL , PUBLIC ::   ln_cpl         !: ocean-atmosphere coupled formulation
+   LOGICAL , PUBLIC ::   ln_mixcpl      !: ocean-atmosphere forced-coupled mixed formulation
+   LOGICAL , PUBLIC ::   ln_dm2dc       !: Daily mean to Diurnal Cycle short wave (qsr)
+   LOGICAL , PUBLIC ::   ln_rnf         !: runoffs / runoff mouths
+   LOGICAL , PUBLIC ::   ln_isf         !: ice shelf melting
+   LOGICAL , PUBLIC ::   ln_ssr         !: Sea Surface restoring on SST and/or SSS      
+   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)
+   LOGICAL , PUBLIC ::   ln_ice_embd    !: flag for levitating/embedding sea-ice in the ocean
+   !                                             !: =F levitating ice (no presure effect) with mass and salt exchanges
+   !                                             !: =T embedded sea-ice (pressure effect + mass and salt exchanges)
+   INTEGER , PUBLIC ::   nn_components  !: flag for sbc module (including sea-ice) coupling mode (see component definition below) 
+   INTEGER , PUBLIC ::   nn_fwb         !: FreshWater Budget: 
+   !                                             !:  = 0 unchecked 
+   !                                             !:  = 1 global mean of e-p-r set to zero at each nn_fsbc time step
+   !                                             !:  = 2 annual global mean of e-p-r set to zero
+   LOGICAL , PUBLIC ::   ln_wave        !: true if some coupling with wave model
+   LOGICAL , PUBLIC ::   ln_cdgw        !: true if neutral drag coefficient from wave model
+   LOGICAL , PUBLIC ::   ln_sdw         !: true if 3d stokes drift from wave model
+   LOGICAL , PUBLIC ::   ln_tauwoc       !: true if normalized stress from wave is used
+   LOGICAL , PUBLIC ::   ln_tauw        !: true if ocean stress components from wave is used
+   LOGICAL , PUBLIC ::   ln_stcor       !: true if Stokes-Coriolis term is used
+   !
+   INTEGER , PUBLIC ::   nn_sdrift      ! type of parameterization to calculate vertical Stokes drift
+   !
+   LOGICAL , PUBLIC ::   ln_icebergs    !: Icebergs
+   !
+   INTEGER , PUBLIC ::   nn_lsm         !: Number of iteration if seaoverland is applied
+   !
+   !                                   !!* namsbc_cpl namelist *
+   INTEGER , PUBLIC ::   nn_cats_cpl    !: Number of sea ice categories over which the coupling is carried out
+
+   !!----------------------------------------------------------------------
+   !!           switch definition (improve readability)
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC, PARAMETER ::   jp_usr     = 1        !: user defined                  formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_flx     = 2        !: flux                          formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_blk     = 3        !: bulk                          formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_purecpl = 4        !: Pure ocean-atmosphere Coupled formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_none    = 5        !: for OPA when doing coupling via SAS module
+   
+   !!----------------------------------------------------------------------
+   !!           Stokes drift parametrization definition 
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC, PARAMETER ::   jp_breivik_2014 = 0     !: Breivik  2014: v_z=v_0*[exp(2*k*z)/(1-8*k*z)]
+   INTEGER , PUBLIC, PARAMETER ::   jp_li_2017      = 1     !: Li et al 2017: Stokes drift based on Phillips spectrum (Breivik 2016) 
+                                                            !  with depth averaged profile
+   INTEGER , PUBLIC, PARAMETER ::   jp_peakfr       = 2     !: Li et al 2017: using the peak wave number read from wave model instead 
+                                                            !  of the inverse depth scale
+   LOGICAL , PUBLIC            ::   ll_st_bv2014  = .FALSE. !  logical indicator, .true. if Breivik 2014 parameterisation is active.
+   LOGICAL , PUBLIC            ::   ll_st_li2017  = .FALSE. !  logical indicator, .true. if Li 2017 parameterisation is active.
+   LOGICAL , PUBLIC            ::   ll_st_bv_li   = .FALSE. !  logical indicator, .true. if either Breivik or Li parameterisation is active.
+   LOGICAL , PUBLIC            ::   ll_st_peakfr  = .FALSE. !  logical indicator, .true. if using Li 2017 with peak wave number
+
+   !!----------------------------------------------------------------------
+   !!           component definition
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC, PARAMETER ::   jp_iam_nemo = 0      !: Initial single executable configuration 
+                                                         !  (no internal OASIS coupling)
+   INTEGER , PUBLIC, PARAMETER ::   jp_iam_opa  = 1      !: Multi executable configuration - OPA component
+                                                         !  (internal OASIS coupling)
+   INTEGER , PUBLIC, PARAMETER ::   jp_iam_sas  = 2      !: Multi executable configuration - SAS component
+                                                         !  (internal OASIS coupling)
+   !!----------------------------------------------------------------------
+   !!              Ocean Surface Boundary Condition fields
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC ::  ncpl_qsr_freq = 0        !: qsr coupling frequency per days from atmosphere (used by top)
+   !
+   LOGICAL , PUBLIC ::   lhftau = .FALSE.        !: HF tau used in TKE: mean(stress module) - module(mean stress)
+   !!                                   !!   now    ! before   !!
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   utau   , utau_b   !: sea surface i-stress (ocean referential)     [N/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   vtau   , vtau_b   !: sea surface j-stress (ocean referential)     [N/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   taum              !: module of sea surface stress (at T-point)    [N/m2] 
+   !! wndm is used onmpute surface gases exchanges in ice-free ocean or leads
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wndm              !: wind speed module at T-point (=|U10m-Uoce|)  [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qsr               !: sea heat flux:     solar                     [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qns    , qns_b    !: sea heat flux: non solar                     [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qsr_tot           !: total     solar heat flux (over sea and ice) [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qns_tot           !: total non solar heat flux (over sea and ice) [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   emp    , emp_b    !: freshwater budget: volume flux               [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx    , sfx_b    !: salt flux                                    [PSS.kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   emp_tot           !: total E-P over ocean and ice                 [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fmmflx            !: freshwater budget: freezing/melting          [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rnf    , rnf_b    !: river runoff        [Kg/m2/s]  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fwfisf , fwfisf_b !: ice shelf melting   [Kg/m2/s]  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fwficb , fwficb_b !: iceberg melting [Kg/m2/s]  
+
+   !!
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  sbc_tsc, sbc_tsc_b  !: sbc content trend                      [K.m/s] jpi,jpj,jpts
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  qsr_hc , qsr_hc_b   !: heat content trend due to qsr flux     [K.m/s] jpi,jpj,jpk
+   !!
+   !!
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tprecip           !: total precipitation                          [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sprecip           !: solid precipitation                          [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fr_i              !: ice fraction = 1 - lead fraction      (between 0 to 1)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   atm_co2           !: atmospheric pCO2                             [ppm]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: xcplmask          !: coupling mask for ln_mixcpl (warning: allocated in sbccpl)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   cloud_fra         !: cloud cover (fraction of cloud in a gridcell) [-]
+
+   !!----------------------------------------------------------------------
+   !!                     Sea Surface Mean fields
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC                     ::   nn_fsbc   !: frequency of sbc computation (as well as sea-ice model)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ssu_m     !: mean (nn_fsbc time-step) surface sea i-current (U-point) [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ssv_m     !: mean (nn_fsbc time-step) surface sea j-current (V-point) [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sst_m     !: mean (nn_fsbc time-step) surface sea temperature     [Celsius]
+   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 layer thickness       [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   frq_m     !: mean (nn_fsbc time-step) fraction of solar net radiation absorbed in the 1st T level [-]
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_oce_alloc()
+      !!---------------------------------------------------------------------
+      !!                  ***  FUNCTION sbc_oce_alloc  ***
+      !!---------------------------------------------------------------------
+      INTEGER :: ierr(5)
+      !!---------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( utau(jpi,jpj) , utau_b(jpi,jpj) , taum(jpi,jpj) ,     &
+         &      vtau(jpi,jpj) , vtau_b(jpi,jpj) , wndm(jpi,jpj) , STAT=ierr(1) ) 
+         !
+      ALLOCATE( qns_tot(jpi,jpj) , qns  (jpi,jpj) , qns_b(jpi,jpj),        &
+         &      qsr_tot(jpi,jpj) , qsr  (jpi,jpj) ,                        &
+         &      emp    (jpi,jpj) , emp_b(jpi,jpj) ,                        &
+         &      sfx    (jpi,jpj) , sfx_b(jpi,jpj) , emp_tot(jpi,jpj), fmmflx(jpi,jpj), STAT=ierr(2) )
+         !
+      ALLOCATE( fwfisf  (jpi,jpj), rnf  (jpi,jpj) , sbc_tsc  (jpi,jpj,jpts) , qsr_hc  (jpi,jpj,jpk) ,  &
+         &      fwfisf_b(jpi,jpj), rnf_b(jpi,jpj) , sbc_tsc_b(jpi,jpj,jpts) , qsr_hc_b(jpi,jpj,jpk) ,  &
+         &      fwficb  (jpi,jpj), fwficb_b(jpi,jpj), STAT=ierr(3) )
+         !
+      ALLOCATE( tprecip(jpi,jpj) , sprecip  (jpi,jpj) , fr_i(jpi,jpj) ,   &
+         &      atm_co2(jpi,jpj) , cloud_fra(jpi,jpj) ,                   &
+         &      ssu_m  (jpi,jpj) , sst_m    (jpi,jpj) , frq_m(jpi,jpj) ,  &
+         &      ssv_m  (jpi,jpj) , sss_m    (jpi,jpj) , ssh_m(jpi,jpj) , STAT=ierr(4) )
+         !
+      ALLOCATE( e3t_m(jpi,jpj) , STAT=ierr(5) )
+         !
+      sbc_oce_alloc = MAXVAL( ierr )
+      CALL mpp_sum ( 'sbc_oce', sbc_oce_alloc )
+      IF( sbc_oce_alloc > 0 )   CALL ctl_warn('sbc_oce_alloc: allocation of arrays failed')
+      !
+   END FUNCTION sbc_oce_alloc
+
+
+   SUBROUTINE sbc_tau2wnd
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_tau2wnd  ***
+      !!                   
+      !! ** Purpose : Estimation of wind speed as a function of wind stress   
+      !!
+      !! ** Method  : |tau|=rhoa*Cd*|U|^2
+      !!---------------------------------------------------------------------
+      USE dom_oce         ! ocean space and time domain
+      USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+      REAL(wp) ::   zrhoa  = 1.22         ! Air density kg/m3
+      REAL(wp) ::   zcdrag = 1.5e-3       ! drag coefficient
+      REAL(wp) ::   ztx, zty, ztau, zcoef ! temporary variables
+      INTEGER  ::   ji, jj                ! dummy indices
+      !!---------------------------------------------------------------------
+      zcoef = 0.5 / ( zrhoa * zcdrag ) 
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            ztx = utau(ji-1,jj  ) + utau(ji,jj) 
+            zty = vtau(ji  ,jj-1) + vtau(ji,jj) 
+            ztau = SQRT( ztx * ztx + zty * zty )
+            wndm(ji,jj) = SQRT ( ztau * zcoef ) * tmask(ji,jj,1)
+         END DO
+      END DO
+      CALL lbc_lnk( 'sbc_oce', wndm(:,:) , 'T', 1. )
+      !
+   END SUBROUTINE sbc_tau2wnd
+
+   !!======================================================================
+END MODULE sbc_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcapr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcapr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcapr.F90	(revision 14097)
@@ -0,0 +1,179 @@
+MODULE sbcapr
+   !!======================================================================
+   !!                       ***  MODULE  sbcapr  ***
+   !! Surface module :   atmospheric pressure forcing
+   !!======================================================================
+   !! History :  3.3  !   2010-09  (J. Chanut, C. Bricaud, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+   
+   !!----------------------------------------------------------------------
+   !!   sbc_apr        : read atmospheric pressure in netcdf files 
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! surface boundary condition
+   USE phycst          ! physical constants
+   !
+   USE fldread         ! read input fields
+   USE in_out_manager  ! I/O manager
+   USE lib_fortran     ! distribued memory computing library
+   USE iom             ! IOM library
+   USE lib_mpp         ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_apr       ! routine called in sbcmod
+   PUBLIC   sbc_apr_init  ! routine called in sbcmod
+   
+   !                                          !!* namsbc_apr namelist (Atmospheric PRessure) *
+   LOGICAL, PUBLIC ::   ln_apr_obc = .false.   !: inverse barometer added to OBC ssh data 
+   LOGICAL, PUBLIC ::   ln_ref_apr             !: ref. pressure: global mean Patm (F) or a constant (F)
+   REAL(wp)        ::   rn_pref                !  reference atmospheric pressure   [N/m2]
+
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   ssh_ib    ! Inverse barometer now    sea surface height   [m]
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   ssh_ibb   ! Inverse barometer before sea surface height   [m]
+   REAL(wp), ALLOCATABLE, SAVE, PUBLIC, DIMENSION(:,:) ::   apr       ! atmospheric pressure at kt                 [N/m2]
+   
+   REAL(wp) ::   tarea                ! whole domain mean masked ocean surface
+   REAL(wp) ::   r1_grau              ! = 1.e0 / (grav * rau0)
+   
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_apr   ! structure of input fields (file informations, fields read)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_apr_init
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_apr  ***
+      !!
+      !! ** Purpose :   read atmospheric pressure fields in netcdf files.
+      !!
+      !! ** Method  : - Read namelist namsbc_apr
+      !!              - Read Patm fields in netcdf files 
+      !!              - Compute reference atmospheric pressure
+      !!              - Compute inverse barometer ssh
+      !! ** action  :   apr      : atmospheric pressure at kt
+      !!                ssh_ib   : inverse barometer ssh at kt
+      !!---------------------------------------------------------------------
+      INTEGER            ::   ierror  ! local integer 
+      INTEGER            ::   ios     ! Local integer output status for namelist read
+      !!
+      CHARACTER(len=100) ::  cn_dir   ! Root directory for location of ssr files
+      TYPE(FLD_N)        ::  sn_apr   ! informations about the fields to be read
+      LOGICAL            ::  lrxios   ! read restart using XIOS?
+      !!
+      NAMELIST/namsbc_apr/ cn_dir, sn_apr, ln_ref_apr, rn_pref, ln_apr_obc
+      !!----------------------------------------------------------------------
+      REWIND( numnam_ref )              ! Namelist namsbc_apr in reference namelist : File for atmospheric pressure forcing
+      READ  ( numnam_ref, namsbc_apr, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_apr in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namsbc_apr in configuration namelist : File for atmospheric pressure forcing
+      READ  ( numnam_cfg, namsbc_apr, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_apr in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_apr )
+      !
+      ALLOCATE( sf_apr(1), STAT=ierror )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+      IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_apr: unable to allocate sf_apr structure' )
+      !
+      CALL fld_fill( sf_apr, (/ sn_apr /), cn_dir, 'sbc_apr', 'Atmospheric pressure ', 'namsbc_apr' )
+                                ALLOCATE( sf_apr(1)%fnow(jpi,jpj,1)   )
+      IF( sn_apr%ln_tint )   ALLOCATE( sf_apr(1)%fdta(jpi,jpj,1,2) )
+                             ALLOCATE( ssh_ib(jpi,jpj) , ssh_ibb(jpi,jpj) )
+                             ALLOCATE( apr (jpi,jpj) )
+      !
+      IF( lwp )THEN                                 !* control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namsbc_apr : Atmospheric PRessure as extrenal forcing'
+         WRITE(numout,*) '      ref. pressure: global mean Patm (T) or a constant (F)  ln_ref_apr = ', ln_ref_apr
+      ENDIF
+      !
+      IF( ln_ref_apr ) THEN                        !* Compute whole inner domain mean masked ocean surface
+         tarea = glob_sum( 'sbcapr', e1e2t(:,:) )
+         IF(lwp) WRITE(numout,*) '         Variable ref. Patm computed over a ocean surface of ', tarea*1e-6, 'km2'
+      ELSE
+         IF(lwp) WRITE(numout,*) '         Reference Patm used : ', rn_pref, ' N/m2'
+      ENDIF
+      !
+      r1_grau = 1.e0 / (grav * rau0)               !* constant for optimization
+      !
+      !                                            !* control check
+      IF ( ln_apr_obc  ) THEN
+         IF(lwp) WRITE(numout,*) '         Inverse barometer added to OBC ssh data'
+      ENDIF
+!jc: stop below should rather be a warning 
+      IF( ln_apr_obc .AND. .NOT.ln_apr_dyn   )   &
+            CALL ctl_warn( 'sbc_apr: use inverse barometer ssh at open boundary ONLY requires ln_apr_dyn=T' )
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('ssh_ibb')
+      ENDIF
+   END SUBROUTINE sbc_apr_init
+
+   SUBROUTINE sbc_apr( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_apr  ***
+      !!
+      !! ** Purpose :   read atmospheric pressure fields in netcdf files.
+      !!
+      !! ** Method  : - Read namelist namsbc_apr
+      !!              - Read Patm fields in netcdf files 
+      !!              - Compute reference atmospheric pressure
+      !!              - Compute inverse barometer ssh
+      !! ** action  :   apr      : atmospheric pressure at kt
+      !!                ssh_ib   : inverse barometer ssh at kt
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in)::   kt   ! ocean time step
+      !
+      !!----------------------------------------------------------------------
+
+      !                                         ! ========================== !
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN      !    At each sbc time-step   !
+         !                                      ! ===========+++============ !
+         !
+         IF( kt /= nit000 )   ssh_ibb(:,:) = ssh_ib(:,:)    !* Swap of ssh_ib fields
+         !
+         CALL fld_read( kt, nn_fsbc, sf_apr )               !* input Patm provided at kt + nn_fsbc/2
+         !
+         !                                                  !* update the reference atmospheric pressure (if necessary)
+         IF( ln_ref_apr )   rn_pref = glob_sum( 'sbcapr', sf_apr(1)%fnow(:,:,1) * e1e2t(:,:) ) / tarea
+         !
+         !                                                  !* Patm related forcing at kt
+         ssh_ib(:,:) = - ( sf_apr(1)%fnow(:,:,1) - rn_pref ) * r1_grau    ! equivalent ssh (inverse barometer)
+         apr   (:,:) =     sf_apr(1)%fnow(:,:,1)                        ! atmospheric pressure
+         !
+         CALL iom_put( "ssh_ib", ssh_ib )                   !* output the inverse barometer ssh
+      ENDIF
+
+      !                                         ! ---------------------------------------- !
+      IF( kt == nit000 ) THEN                   !   set the forcing field at nit000 - 1    !
+         !                                      ! ---------------------------------------- !
+         !                                            !* Restart: read in restart file
+         IF( ln_rstart .AND. iom_varid( numror, 'ssh_ibb', ldstop = .FALSE. ) > 0 ) THEN 
+            IF(lwp) WRITE(numout,*) 'sbc_apr:   ssh_ibb read in the restart file'
+            CALL iom_get( numror, jpdom_autoglo, 'ssh_ibb', ssh_ibb, ldxios = lrxios )   ! before inv. barometer ssh
+            !
+         ELSE                                         !* no restart: set from nit000 values
+            IF(lwp) WRITE(numout,*) 'sbc_apr:   ssh_ibb set to nit000 values'
+            ssh_ibb(:,:) = ssh_ib(:,:)
+         ENDIF
+      ENDIF
+      !                                         ! ---------------------------------------- !
+      IF( lrst_oce ) THEN                       !      Write in the ocean restart file     !
+         !                                      ! ---------------------------------------- !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbc_apr : ssh_ib written in ocean restart file at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'ssh_ibb' , ssh_ib, ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE sbc_apr
+      
+   !!======================================================================
+END MODULE sbcapr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk.F90	(revision 14097)
@@ -0,0 +1,1249 @@
+MODULE sbcblk
+   !!======================================================================
+   !!                       ***  MODULE  sbcblk  ***
+   !! Ocean forcing:  momentum, heat and freshwater flux formulation
+   !!                         Aerodynamic Bulk Formulas
+   !!                        SUCCESSOR OF "sbcblk_core"
+   !!=====================================================================
+   !! History :  1.0  !  2004-08  (U. Schweckendiek)  Original CORE code
+   !!            2.0  !  2005-04  (L. Brodeau, A.M. Treguier)  improved CORE bulk and its user interface
+   !!            3.0  !  2006-06  (G. Madec)  sbc rewritting
+   !!             -   !  2006-12  (L. Brodeau)  Original code for turb_core
+   !!            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
+   !!            4.0  !  2016-06  (L. Brodeau)  sbcblk_core becomes sbcblk and is not restricted to the CORE algorithm anymore
+   !!                 !                        ==> based on AeroBulk (http://aerobulk.sourceforge.net/)
+   !!            4.0  !  2016-10  (G. Madec)  introduce a sbc_blk_init routine
+   !!            4.0  !  2016-10  (M. Vancoppenolle)  Introduce conduction flux emulator (M. Vancoppenolle) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_blk_init  : initialisation of the chosen bulk formulation as ocean surface boundary condition
+   !!   sbc_blk       : bulk formulation as ocean surface boundary condition
+   !!   blk_oce       : computes momentum, heat and freshwater fluxes over ocean
+   !!   rho_air       : density of (moist) air (depends on T_air, q_air and SLP
+   !!   cp_air        : specific heat of (moist) air (depends spec. hum. q_air)
+   !!   q_sat         : saturation humidity as a function of SLP and temperature
+   !!   L_vap         : latent heat of vaporization of water as a function of temperature
+   !!             sea-ice case only : 
+   !!   blk_ice_tau   : provide the air-ice stress
+   !!   blk_ice_flx   : provide the heat and mass fluxes at air-ice interface
+   !!   blk_ice_qcn   : provide ice surface temperature and snow/ice conduction flux (emulating conduction flux)
+   !!   Cdn10_Lupkes2012 : Lupkes et al. (2012) air-ice drag
+   !!   Cdn10_Lupkes2015 : Lupkes et al. (2015) air-ice drag 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE fldread        ! read input fields
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE cyclone        ! Cyclone 10m wind form trac of cyclone centres
+   USE sbcdcy         ! surface boundary condition: diurnal cycle
+   USE sbcwave , ONLY :   cdn_wave ! wave module
+   USE sbc_ice        ! Surface boundary condition: ice fields
+   USE lib_fortran    ! to use key_nosignedzero
+#if defined key_si3
+   USE ice     , ONLY :   u_ice, v_ice, jpl, a_i_b, at_i_b, t_su, rn_cnd_s, hfx_err_dif, nn_qtrice
+   USE icevar         ! for CALL ice_var_snwblow
+#endif
+   USE sbcblk_algo_ncar     ! => turb_ncar     : NCAR - CORE (Large & Yeager, 2009) 
+   USE sbcblk_algo_coare    ! => turb_coare    : COAREv3.0 (Fairall et al. 2003) 
+   USE sbcblk_algo_coare3p5 ! => turb_coare3p5 : COAREv3.5 (Edson et al. 2013)
+   USE sbcblk_algo_ecmwf    ! => turb_ecmwf    : ECMWF (IFS cycle 31) 
+   !
+   USE iom            ! I/O manager library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl         ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_blk_init  ! called in sbcmod
+   PUBLIC   sbc_blk       ! called in sbcmod
+#if defined key_si3
+   PUBLIC   blk_ice_tau   ! routine called in icesbc
+   PUBLIC   blk_ice_flx   ! routine called in icesbc
+   PUBLIC   blk_ice_qcn   ! routine called in icesbc
+#endif 
+
+!!Lolo: should ultimately be moved in the module with all physical constants ?
+!!gm  : In principle, yes.
+   REAL(wp), PARAMETER ::   Cp_dry = 1005.0       !: Specic heat of dry air, constant pressure      [J/K/kg]
+   REAL(wp), PARAMETER ::   Cp_vap = 1860.0       !: Specic heat of water vapor, constant pressure  [J/K/kg]
+   REAL(wp), PARAMETER ::   R_dry = 287.05_wp     !: Specific gas constant for dry air              [J/K/kg]
+   REAL(wp), PARAMETER ::   R_vap = 461.495_wp    !: Specific gas constant for water vapor          [J/K/kg]
+   REAL(wp), PARAMETER ::   reps0 = R_dry/R_vap   !: ratio of gas constant for dry air and water vapor => ~ 0.622
+   REAL(wp), PARAMETER ::   rctv0 = R_vap/R_dry - 1._wp !: for virtual temperature (== (1-eps)/eps) => ~ 0.608
+
+   INTEGER , PARAMETER ::   jpfld   =11           ! 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
+   INTEGER , PARAMETER ::   jp_tair = 3           ! index of 10m air temperature             (Kelvin)
+   INTEGER , PARAMETER ::   jp_humi = 4           ! index of specific humidity               ( % )
+   INTEGER , PARAMETER ::   jp_qsr  = 5           ! index of solar heat                      (W/m2)
+   INTEGER , PARAMETER ::   jp_qlw  = 6           ! index of Long wave                       (W/m2)
+   INTEGER , PARAMETER ::   jp_prec = 7           ! index of total precipitation (rain+snow) (Kg/m2/s)
+   INTEGER , PARAMETER ::   jp_snow = 8           ! index of snow (solid prcipitation)       (kg/m2/s)
+   INTEGER , PARAMETER ::   jp_slp  = 9           ! index of sea level pressure              (Pa)
+   INTEGER , PARAMETER ::   jp_cc   =10           ! index of cloud cover                     (-)      range:0-1
+   INTEGER , PARAMETER ::   jp_tdif =11           ! 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)
+
+   !                                             !!! Bulk parameters
+   REAL(wp), PARAMETER ::   cpa    = 1000.5         ! specific heat of air (only used for ice fluxes now...)
+   REAL(wp), PARAMETER ::   Ls     =    2.839e6     ! latent heat of sublimation
+   REAL(wp), PARAMETER ::   Stef   =    5.67e-8     ! Stefan Boltzmann constant
+   REAL(wp), PARAMETER ::   Cd_ice =    1.4e-3      ! transfer coefficient over ice
+   REAL(wp), PARAMETER ::   albo   =    0.066       ! ocean albedo assumed to be constant
+   !
+   !                           !!* Namelist namsbc_blk : bulk parameters
+   LOGICAL  ::   ln_NCAR        ! "NCAR"      algorithm   (Large and Yeager 2008)
+   LOGICAL  ::   ln_COARE_3p0   ! "COARE 3.0" algorithm   (Fairall et al. 2003)
+   LOGICAL  ::   ln_COARE_3p5   ! "COARE 3.5" algorithm   (Edson et al. 2013)
+   LOGICAL  ::   ln_ECMWF       ! "ECMWF"     algorithm   (IFS cycle 31)
+   !
+   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
+   REAL(wp) ::   rn_vfac        ! multiplication factor for ice/ocean velocity in the calculation of wind stress
+   REAL(wp) ::   rn_zqt         ! z(q,t) : height of humidity and temperature measurements
+   REAL(wp) ::   rn_zu          ! z(u)   : height of wind measurements
+!!gm ref namelist initialize it so remove the setting to false below
+   LOGICAL  ::   ln_Cd_L12 = .FALSE. !  Modify the drag ice-atm depending on ice concentration (from Lupkes et al. JGR2012)
+   LOGICAL  ::   ln_Cd_L15 = .FALSE. !  Modify the drag ice-atm depending on ice concentration (from Lupkes et al. JGR2015)
+   !
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   Cd_atm                    ! transfer coefficient for momentum      (tau)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   Ch_atm                    ! transfer coefficient for sensible heat (Q_sens)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   Ce_atm                    ! tansfert coefficient for evaporation   (Q_lat)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_zu                      ! air temperature at wind speed height (needed by Lupkes 2015 bulk scheme)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_zu                      ! air spec. hum.  at wind speed height (needed by Lupkes 2015 bulk scheme)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   cdn_oce, chn_oce, cen_oce ! needed by Lupkes 2015 bulk scheme
+
+   INTEGER  ::   nblk           ! choice of the bulk algorithm
+   !                            ! associated indices:
+   INTEGER, PARAMETER ::   np_NCAR      = 1   ! "NCAR" algorithm        (Large and Yeager 2008)
+   INTEGER, PARAMETER ::   np_COARE_3p0 = 2   ! "COARE 3.0" algorithm   (Fairall et al. 2003)
+   INTEGER, PARAMETER ::   np_COARE_3p5 = 3   ! "COARE 3.5" algorithm   (Edson et al. 2013)
+   INTEGER, PARAMETER ::   np_ECMWF     = 4   ! "ECMWF" algorithm       (IFS cycle 31)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_blk_alloc()
+      !!-------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_blk_alloc ***
+      !!-------------------------------------------------------------------
+      ALLOCATE( Cd_atm (jpi,jpj), Ch_atm (jpi,jpj), Ce_atm (jpi,jpj), t_zu(jpi,jpj), q_zu(jpi,jpj), &
+         &      cdn_oce(jpi,jpj), chn_oce(jpi,jpj), cen_oce(jpi,jpj), STAT=sbc_blk_alloc )
+      !
+      CALL mpp_sum ( 'sbcblk', sbc_blk_alloc )
+      IF( sbc_blk_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sbc_blk_alloc: failed to allocate arrays' )
+   END FUNCTION sbc_blk_alloc
+
+
+   SUBROUTINE sbc_blk_init
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_blk_init  ***
+      !!
+      !! ** Purpose :   choose and initialize a bulk formulae formulation
+      !!
+      !! ** Method  : 
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jfpr, jfld            ! dummy loop indice and argument
+      INTEGER  ::   ios, ierror, ioptio   ! Local integer
+      !!
+      CHARACTER(len=100)            ::   cn_dir                ! Root directory for location of atmospheric forcing files
+      TYPE(FLD_N), DIMENSION(jpfld) ::   slf_i                 ! array of namelist informations on the fields to read
+      TYPE(FLD_N) ::   sn_wndi, sn_wndj, sn_humi, sn_qsr       ! informations about the fields to be read
+      TYPE(FLD_N) ::   sn_qlw , sn_tair, sn_prec, sn_snow      !       "                        "
+      TYPE(FLD_N) ::   sn_slp , sn_tdif, sn_cc                 !       "                        "
+      NAMELIST/namsbc_blk/ sn_wndi, sn_wndj, sn_humi, sn_qsr, sn_qlw ,                &   ! input fields
+         &                 sn_tair, sn_prec, sn_snow, sn_slp, sn_tdif, sn_cc,         &
+         &                 ln_NCAR, ln_COARE_3p0, ln_COARE_3p5, ln_ECMWF,             &   ! bulk algorithm
+         &                 cn_dir , ln_taudif, rn_zqt, rn_zu,                         & 
+         &                 rn_pfac, rn_efac, rn_vfac, ln_Cd_L12, ln_Cd_L15
+      !!---------------------------------------------------------------------
+      !
+      !                                      ! allocate sbc_blk_core array
+      IF( sbc_blk_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_blk : unable to allocate standard arrays' )
+      !
+      !                             !** read bulk namelist  
+      REWIND( numnam_ref )                !* Namelist namsbc_blk in reference namelist : bulk parameters
+      READ  ( numnam_ref, namsbc_blk, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_blk in reference namelist' )
+      !
+      REWIND( numnam_cfg )                !* Namelist namsbc_blk in configuration namelist : bulk parameters
+      READ  ( numnam_cfg, namsbc_blk, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_blk in configuration namelist' )
+      !
+      IF(lwm) WRITE( numond, namsbc_blk )
+      !
+      !                             !** initialization of the chosen bulk formulae (+ check)
+      !                                   !* select the bulk chosen in the namelist and check the choice
+                                                               ioptio = 0
+      IF( ln_NCAR      ) THEN   ;   nblk =  np_NCAR        ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_COARE_3p0 ) THEN   ;   nblk =  np_COARE_3p0   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_COARE_3p5 ) THEN   ;   nblk =  np_COARE_3p5   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_ECMWF     ) THEN   ;   nblk =  np_ECMWF       ;   ioptio = ioptio + 1   ;   ENDIF
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'sbc_blk_init: Choose one and only one bulk algorithm' )
+      !
+      IF( ln_dm2dc ) THEN                 !* check: diurnal cycle on Qsr
+         IF( sn_qsr%freqh /= 24. )   CALL ctl_stop( 'sbc_blk_init: ln_dm2dc=T only with daily short-wave input' )
+         IF( sn_qsr%ln_tint ) THEN 
+            CALL ctl_warn( 'sbc_blk_init: ln_dm2dc=T daily qsr time interpolation done by sbcdcy module',   &
+               &           '              ==> We force time interpolation = .false. for qsr' )
+            sn_qsr%ln_tint = .false.
+         ENDIF
+      ENDIF
+      !                                   !* set the bulk structure
+      !                                      !- store namelist information in an array
+      slf_i(jp_wndi) = sn_wndi   ;   slf_i(jp_wndj) = sn_wndj
+      slf_i(jp_qsr ) = sn_qsr    ;   slf_i(jp_qlw ) = sn_qlw
+      slf_i(jp_tair) = sn_tair   ;   slf_i(jp_humi) = sn_humi
+      slf_i(jp_prec) = sn_prec   ;   slf_i(jp_snow) = sn_snow
+      slf_i(jp_slp)  = sn_slp    ;   slf_i(jp_cc)   = sn_cc
+      slf_i(jp_tdif) = sn_tdif
+      !
+      lhftau = ln_taudif                     !- add an extra field if HF stress is used
+      jfld = jpfld - COUNT( (/.NOT.lhftau/) )
+      !
+      !                                      !- allocate the bulk structure
+      ALLOCATE( sf(jfld), STAT=ierror )
+      IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_blk_init: unable to allocate sf structure' )
+
+      !                                      !- fill the bulk structure with namelist informations
+      CALL fld_fill( sf, slf_i, cn_dir, 'sbc_blk_init', 'surface boundary condition -- bulk formulae', 'namsbc_blk' )
+      !
+      DO jfpr = 1, jfld
+         !
+         IF( TRIM(sf(jfpr)%clrootname) == 'NOT USED' ) THEN    !--  not used field  --!   (only now allocated and set to zero)
+            ALLOCATE( sf(jfpr)%fnow(jpi,jpj,1) )
+            sf(jfpr)%fnow(:,:,1) = 0._wp
+         ELSE                                                  !-- used field --!
+            ALLOCATE( sf(jfpr)%fnow(jpi,jpj,1) )
+            IF( slf_i(jfpr)%ln_tint )   ALLOCATE( sf(jfpr)%fdta(jpi,jpj,1,2) )
+            IF( slf_i(jfpr)%freqh > 0. .AND. MOD( NINT(3600. * slf_i(jfpr)%freqh), nn_fsbc * NINT(rdt) ) /= 0 )                      &
+               &  CALL ctl_warn( 'sbc_blk_init: sbcmod timestep rdt*nn_fsbc is NOT a submultiple of atmospheric forcing frequency.', &
+               &                 '               This is not ideal. You should consider changing either rdt or nn_fsbc value...' )
+         ENDIF
+      ENDDO
+      ! fill cloud cover array with constant value if "not used"
+      IF( TRIM(sf(jp_cc)%clrootname) == 'NOT USED' )   sf(jp_cc)%fnow(:,:,1) = pp_cldf
+         
+      IF ( ln_wave ) THEN
+      !Activated wave module but neither drag nor stokes drift activated
+         IF ( .NOT.(ln_cdgw .OR. ln_sdw .OR. ln_tauwoc .OR. ln_stcor ) )   THEN
+            CALL ctl_stop( 'STOP',  'Ask for wave coupling but ln_cdgw=F, ln_sdw=F, ln_tauwoc=F, ln_stcor=F' )
+      !drag coefficient read from wave model definable only with mfs bulk formulae and core 
+         ELSEIF (ln_cdgw .AND. .NOT. ln_NCAR )       THEN       
+             CALL ctl_stop( 'drag coefficient read from wave model definable only with NCAR and CORE bulk formulae')
+         ELSEIF (ln_stcor .AND. .NOT. ln_sdw)                             THEN
+             CALL ctl_stop( 'Stokes-Coriolis term calculated only if activated Stokes Drift ln_sdw=T')
+         ENDIF
+      ELSE
+      IF ( ln_cdgw .OR. ln_sdw .OR. ln_tauwoc .OR. ln_stcor )                & 
+         &   CALL ctl_stop( 'Not Activated Wave Module (ln_wave=F) but asked coupling ',    &
+         &                  'with drag coefficient (ln_cdgw =T) '  ,                        &
+         &                  'or Stokes Drift (ln_sdw=T) ' ,                                 &
+         &                  'or ocean stress modification due to waves (ln_tauwoc=T) ',      &  
+         &                  'or Stokes-Coriolis term (ln_stcori=T)'  )
+      ENDIF 
+      !
+      !           
+      IF(lwp) THEN                     !** Control print
+         !
+         WRITE(numout,*)                  !* namelist 
+         WRITE(numout,*) '   Namelist namsbc_blk (other than data information):'
+         WRITE(numout,*) '      "NCAR"      algorithm   (Large and Yeager 2008)     ln_NCAR      = ', ln_NCAR
+         WRITE(numout,*) '      "COARE 3.0" algorithm   (Fairall et al. 2003)       ln_COARE_3p0 = ', ln_COARE_3p0
+         WRITE(numout,*) '      "COARE 3.5" algorithm   (Edson et al. 2013)         ln_COARE_3p5 = ', ln_COARE_3p5
+         WRITE(numout,*) '      "ECMWF"     algorithm   (IFS cycle 31)              ln_ECMWF     = ', ln_ECMWF
+         WRITE(numout,*) '      add High freq.contribution to the stress module     ln_taudif    = ', ln_taudif
+         WRITE(numout,*) '      Air temperature and humidity reference height (m)   rn_zqt       = ', rn_zqt
+         WRITE(numout,*) '      Wind vector reference height (m)                    rn_zu        = ', rn_zu
+         WRITE(numout,*) '      factor applied on precipitation (total & snow)      rn_pfac      = ', rn_pfac
+         WRITE(numout,*) '      factor applied on evaporation                       rn_efac      = ', rn_efac
+         WRITE(numout,*) '      factor applied on ocean/ice velocity                rn_vfac      = ', rn_vfac
+         WRITE(numout,*) '         (form absolute (=0) to relative winds(=1))'
+         WRITE(numout,*) '      use ice-atm drag from Lupkes2012                    ln_Cd_L12    = ', ln_Cd_L12
+         WRITE(numout,*) '      use ice-atm drag from Lupkes2015                    ln_Cd_L15    = ', ln_Cd_L15
+         !
+         WRITE(numout,*)
+         SELECT CASE( nblk )              !* Print the choice of bulk algorithm
+         CASE( np_NCAR      )   ;   WRITE(numout,*) '   ==>>>   "NCAR" algorithm        (Large and Yeager 2008)'
+         CASE( np_COARE_3p0 )   ;   WRITE(numout,*) '   ==>>>   "COARE 3.0" algorithm   (Fairall et al. 2003)'
+         CASE( np_COARE_3p5 )   ;   WRITE(numout,*) '   ==>>>   "COARE 3.5" algorithm   (Edson et al. 2013)'
+         CASE( np_ECMWF     )   ;   WRITE(numout,*) '   ==>>>   "ECMWF" algorithm       (IFS cycle 31)'
+         END SELECT
+         !
+      ENDIF
+      !
+   END SUBROUTINE sbc_blk_init
+
+
+   SUBROUTINE sbc_blk( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_blk  ***
+      !!
+      !! ** Purpose :   provide at each time step the surface ocean fluxes
+      !!              (momentum, heat, freshwater and runoff)
+      !!
+      !! ** Method  : (1) READ each fluxes in NetCDF files:
+      !!      the 10m wind velocity (i-component) (m/s)    at T-point
+      !!      the 10m wind velocity (j-component) (m/s)    at T-point
+      !!      the 10m or 2m specific humidity     ( % )
+      !!      the solar heat                      (W/m2)
+      !!      the Long wave                       (W/m2)
+      !!      the 10m or 2m air temperature       (Kelvin)
+      !!      the total precipitation (rain+snow) (Kg/m2/s)
+      !!      the snow (solid prcipitation)       (kg/m2/s)
+      !!      the tau diff associated to HF tau   (N/m2)   at T-point   (ln_taudif=T)
+      !!              (2) CALL blk_oce
+      !!
+      !!      C A U T I O N : never mask the surface stress fields
+      !!                      the stress is assumed to be in the (i,j) mesh referential
+      !!
+      !! ** Action  :   defined at each time-step at the air-sea interface
+      !!              - utau, vtau  i- and j-component of the wind stress
+      !!              - 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)
+      !!
+      !! ** References :   Large & Yeager, 2004 / Large & Yeager, 2008
+      !!                   Brodeau et al. Ocean Modelling 2010
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      CALL fld_read( kt, nn_fsbc, sf )             ! input fields provided at the current time-step
+      !
+      !                                            ! compute the surface ocean fluxes using bulk formulea
+      IF( MOD( kt - 1, nn_fsbc ) == 0 )   CALL blk_oce( kt, sf, sst_m, ssu_m, ssv_m )
+
+#if defined key_cice
+      IF( MOD( kt - 1, nn_fsbc ) == 0 )   THEN
+         qlw_ice(:,:,1)   = sf(jp_qlw )%fnow(:,:,1)
+         IF( ln_dm2dc ) THEN ; qsr_ice(:,:,1) = sbc_dcy( sf(jp_qsr)%fnow(:,:,1) )
+         ELSE                ; qsr_ice(:,:,1) =          sf(jp_qsr)%fnow(:,:,1) 
+         ENDIF 
+         tatm_ice(:,:)    = sf(jp_tair)%fnow(:,:,1)
+         qatm_ice(:,:)    = sf(jp_humi)%fnow(:,:,1)
+         tprecip(:,:)     = sf(jp_prec)%fnow(:,:,1) * rn_pfac
+         sprecip(:,:)     = sf(jp_snow)%fnow(:,:,1) * rn_pfac
+         wndi_ice(:,:)    = sf(jp_wndi)%fnow(:,:,1)
+         wndj_ice(:,:)    = sf(jp_wndj)%fnow(:,:,1)
+      ENDIF
+#endif
+      !
+   END SUBROUTINE sbc_blk
+
+
+   SUBROUTINE blk_oce( kt, sf, pst, pu, pv )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE blk_oce  ***
+      !!
+      !! ** Purpose :   provide the momentum, heat and freshwater fluxes at
+      !!      the ocean surface at each time step
+      !!
+      !! ** Method  :   bulk formulea for the ocean using atmospheric
+      !!      fields read in sbc_read
+      !!
+      !! ** Outputs : - utau    : i-component of the stress at U-point  (N/m2)
+      !!              - vtau    : j-component of the stress at V-point  (N/m2)
+      !!              - taum    : Wind stress module at T-point         (N/m2)
+      !!              - wndm    : Wind speed module at T-point          (m/s)
+      !!              - qsr     : Solar heat flux over the ocean        (W/m2)
+      !!              - qns     : Non Solar heat flux over the ocean    (W/m2)
+      !!              - emp     : evaporation minus precipitation       (kg/m2/s)
+      !!
+      !!  ** Nota  :   sf has to be a dummy argument for AGRIF on NEC
+      !!---------------------------------------------------------------------
+      INTEGER  , INTENT(in   )                 ::   kt    ! time step index
+      TYPE(fld), INTENT(inout), DIMENSION(:)   ::   sf    ! input data
+      REAL(wp) , INTENT(in)   , DIMENSION(:,:) ::   pst   ! surface temperature                      [Celcius]
+      REAL(wp) , INTENT(in)   , DIMENSION(:,:) ::   pu    ! surface current at U-point (i-component) [m/s]
+      REAL(wp) , INTENT(in)   , DIMENSION(:,:) ::   pv    ! surface current at V-point (j-component) [m/s]
+      !
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) ::   zztmp                ! local variable
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwnd_i, zwnd_j    ! wind speed components at T-point
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsq               ! specific humidity at pst
+      REAL(wp), DIMENSION(jpi,jpj) ::   zqlw, zqsb        ! long wave and sensible heat fluxes
+      REAL(wp), DIMENSION(jpi,jpj) ::   zqla, zevap       ! latent heat fluxes and evaporation
+      REAL(wp), DIMENSION(jpi,jpj) ::   zst               ! surface temperature in Kelvin
+      REAL(wp), DIMENSION(jpi,jpj) ::   zU_zu             ! bulk wind speed at height zu  [m/s]
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztpot             ! potential temperature of air at z=rn_zqt [K]
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrhoa             ! density of air   [kg/m^3]
+      !!---------------------------------------------------------------------
+      !
+      ! local scalars ( place there for vector optimisation purposes)
+      zst(:,:) = pst(:,:) + rt0      ! convert SST from Celcius to Kelvin (and set minimum value far above 0 K)
+
+      ! --- cloud cover --- !
+      cloud_fra(:,:) = sf(jp_cc)%fnow(:,:,1)
+
+      ! ----------------------------------------------------------------------------- !
+      !      0   Wind components and module at T-point relative to the moving ocean   !
+      ! ----------------------------------------------------------------------------- !
+
+      ! ... components ( U10m - U_oce ) at T-point (unmasked)
+!!gm    move zwnd_i (_j) set to zero  inside the key_cyclone ???
+      zwnd_i(:,:) = 0._wp
+      zwnd_j(:,:) = 0._wp
+#if defined key_cyclone
+      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.
+            sf(jp_wndi)%fnow(ji,jj,1) = sf(jp_wndi)%fnow(ji,jj,1) + zwnd_i(ji,jj)
+            sf(jp_wndj)%fnow(ji,jj,1) = sf(jp_wndj)%fnow(ji,jj,1) + zwnd_j(ji,jj)
+         END DO
+      END DO
+#endif
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            zwnd_i(ji,jj) = (  sf(jp_wndi)%fnow(ji,jj,1) - rn_vfac * 0.5 * ( pu(ji-1,jj  ) + pu(ji,jj) )  )
+            zwnd_j(ji,jj) = (  sf(jp_wndj)%fnow(ji,jj,1) - rn_vfac * 0.5 * ( pv(ji  ,jj-1) + pv(ji,jj) )  )
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'sbcblk', zwnd_i, 'T', -1., zwnd_j, 'T', -1. )
+      ! ... scalar wind ( = | U10m - U_oce | ) at T-point (masked)
+      wndm(:,:) = SQRT(  zwnd_i(:,:) * zwnd_i(:,:)   &
+         &             + zwnd_j(:,:) * zwnd_j(:,:)  ) * tmask(:,:,1)
+
+      ! ----------------------------------------------------------------------------- !
+      !      I   Radiative FLUXES                                                     !
+      ! ----------------------------------------------------------------------------- !
+
+      ! ocean albedo assumed to be constant + modify now Qsr to include the diurnal cycle                    ! Short Wave
+      zztmp = 1. - albo
+      IF( ln_dm2dc ) THEN   ;   qsr(:,:) = zztmp * sbc_dcy( sf(jp_qsr)%fnow(:,:,1) ) * tmask(:,:,1)
+      ELSE                  ;   qsr(:,:) = zztmp *          sf(jp_qsr)%fnow(:,:,1)   * tmask(:,:,1)
+      ENDIF
+
+      zqlw(:,:) = (  sf(jp_qlw)%fnow(:,:,1) - Stef * zst(:,:)*zst(:,:)*zst(:,:)*zst(:,:)  ) * tmask(:,:,1)   ! Long  Wave
+
+      ! ----------------------------------------------------------------------------- !
+      !     II    Turbulent FLUXES                                                    !
+      ! ----------------------------------------------------------------------------- !
+
+      ! ... specific humidity at SST and IST tmask(
+      zsq(:,:) = 0.98 * q_sat( zst(:,:), sf(jp_slp)%fnow(:,:,1) )
+      !!
+      !! Estimate of potential temperature at z=rn_zqt, based on adiabatic lapse-rate
+      !!    (see Josey, Gulev & Yu, 2013) / doi=10.1016/B978-0-12-391851-2.00005-2
+      !!    (since reanalysis products provide T at z, not theta !)
+      ztpot = sf(jp_tair)%fnow(:,:,1) + gamma_moist( sf(jp_tair)%fnow(:,:,1), sf(jp_humi)%fnow(:,:,1) ) * rn_zqt
+
+      SELECT CASE( nblk )        !==  transfer coefficients  ==!   Cd, Ch, Ce at T-point
+      !
+      CASE( np_NCAR      )   ;   CALL turb_ncar    ( rn_zqt, rn_zu, zst, ztpot, zsq, sf(jp_humi)%fnow, wndm,   &  ! NCAR-COREv2
+         &                                           Cd_atm, Ch_atm, Ce_atm, t_zu, q_zu, zU_zu, cdn_oce, chn_oce, cen_oce )
+      CASE( np_COARE_3p0 )   ;   CALL turb_coare   ( rn_zqt, rn_zu, zst, ztpot, zsq, sf(jp_humi)%fnow, wndm,   &  ! COARE v3.0
+         &                                           Cd_atm, Ch_atm, Ce_atm, t_zu, q_zu, zU_zu, cdn_oce, chn_oce, cen_oce )
+      CASE( np_COARE_3p5 )   ;   CALL turb_coare3p5( rn_zqt, rn_zu, zst, ztpot, zsq, sf(jp_humi)%fnow, wndm,   &  ! COARE v3.5
+         &                                           Cd_atm, Ch_atm, Ce_atm, t_zu, q_zu, zU_zu, cdn_oce, chn_oce, cen_oce )
+      CASE( np_ECMWF     )   ;   CALL turb_ecmwf   ( rn_zqt, rn_zu, zst, ztpot, zsq, sf(jp_humi)%fnow, wndm,   &  ! ECMWF
+         &                                           Cd_atm, Ch_atm, Ce_atm, t_zu, q_zu, zU_zu, cdn_oce, chn_oce, cen_oce )
+      CASE DEFAULT
+         CALL ctl_stop( 'STOP', 'sbc_oce: non-existing bulk formula selected' )
+      END SELECT
+
+      !                          ! Compute true air density :
+      IF( ABS(rn_zu - rn_zqt) > 0.01 ) THEN     ! At zu: (probably useless to remove zrho*grav*rn_zu from SLP...)
+         zrhoa(:,:) = rho_air( t_zu(:,:)              , q_zu(:,:)              , sf(jp_slp)%fnow(:,:,1) )
+      ELSE                                      ! At zt:
+         zrhoa(:,:) = rho_air( sf(jp_tair)%fnow(:,:,1), sf(jp_humi)%fnow(:,:,1), sf(jp_slp)%fnow(:,:,1) )
+      END IF
+
+!!      CALL iom_put( "Cd_oce", Cd_atm)  ! output value of pure ocean-atm. transfer coef.
+!!      CALL iom_put( "Ch_oce", Ch_atm)  ! output value of pure ocean-atm. transfer coef.
+
+      DO jj = 1, jpj             ! tau module, i and j component
+         DO ji = 1, jpi
+            zztmp = zrhoa(ji,jj)  * zU_zu(ji,jj) * Cd_atm(ji,jj)   ! using bulk wind speed
+            taum  (ji,jj) = zztmp * wndm  (ji,jj)
+            zwnd_i(ji,jj) = zztmp * zwnd_i(ji,jj)
+            zwnd_j(ji,jj) = zztmp * zwnd_j(ji,jj)
+         END DO
+      END DO
+
+      !                          ! add the HF tau contribution to the wind stress module
+      IF( lhftau )   taum(:,:) = taum(:,:) + sf(jp_tdif)%fnow(:,:,1)
+
+      CALL iom_put( "taum_oce", taum )   ! output wind stress module
+
+      ! ... 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  ) ) &
+               &          * 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
+      CALL lbc_lnk_multi( 'sbcblk', utau, 'U', -1., vtau, 'V', -1. )
+
+      !  Turbulent fluxes over ocean
+      ! -----------------------------
+
+      ! zqla used as temporary array, for rho*U (common term of bulk formulae):
+      zqla(:,:) = zrhoa(:,:) * zU_zu(:,:) * tmask(:,:,1)
+
+      IF( ABS( rn_zu - rn_zqt) < 0.01_wp ) THEN
+         !! q_air and t_air are given at 10m (wind reference height)
+         zevap(:,:) = rn_efac*MAX( 0._wp,             zqla(:,:)*Ce_atm(:,:)*(zsq(:,:) - sf(jp_humi)%fnow(:,:,1)) ) ! Evaporation, using bulk wind speed
+         zqsb (:,:) = cp_air(sf(jp_humi)%fnow(:,:,1))*zqla(:,:)*Ch_atm(:,:)*(zst(:,:) - ztpot(:,:)             )   ! Sensible Heat, using bulk wind speed
+      ELSE
+         !! 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,             zqla(:,:)*Ce_atm(:,:)*(zsq(:,:) - q_zu(:,:) ) ) ! Evaporation, using bulk wind speed
+         zqsb (:,:) = cp_air(sf(jp_humi)%fnow(:,:,1))*zqla(:,:)*Ch_atm(:,:)*(zst(:,:) - t_zu(:,:) )   ! Sensible Heat, using bulk wind speed
+      ENDIF
+
+      zqla(:,:) = L_vap(zst(:,:)) * zevap(:,:)     ! Latent Heat flux
+
+
+      IF(ln_ctl) THEN
+         CALL prt_ctl( tab2d_1=zqla  , clinfo1=' blk_oce: zqla   : ', tab2d_2=Ce_atm , clinfo2=' Ce_oce  : ' )
+         CALL prt_ctl( tab2d_1=zqsb  , clinfo1=' blk_oce: zqsb   : ', tab2d_2=Ch_atm , clinfo2=' Ch_oce  : ' )
+         CALL prt_ctl( tab2d_1=zqlw  , clinfo1=' blk_oce: zqlw   : ', tab2d_2=qsr, clinfo2=' qsr : ' )
+         CALL prt_ctl( tab2d_1=zsq   , clinfo1=' blk_oce: zsq    : ', tab2d_2=zst, clinfo2=' zst : ' )
+         CALL prt_ctl( tab2d_1=utau  , clinfo1=' blk_oce: utau   : ', mask1=umask,   &
+            &          tab2d_2=vtau  , clinfo2=           ' vtau : ', mask2=vmask )
+         CALL prt_ctl( tab2d_1=wndm  , clinfo1=' blk_oce: wndm   : ')
+         CALL prt_ctl( tab2d_1=zst   , clinfo1=' blk_oce: zst    : ')
+      ENDIF
+
+      ! ----------------------------------------------------------------------------- !
+      !     III    Total FLUXES                                                       !
+      ! ----------------------------------------------------------------------------- !
+      !
+      emp (:,:) = (  zevap(:,:)                                          &   ! mass flux (evap. - precip.)
+         &         - sf(jp_prec)%fnow(:,:,1) * rn_pfac  ) * tmask(:,:,1)
+      !
+      qns(:,:) = zqlw(:,:) - zqsb(:,:) - zqla(:,:)                                &   ! Downward Non Solar
+         &     - sf(jp_snow)%fnow(:,:,1) * rn_pfac * rLfus                        &   ! 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_snow)%fnow(:,:,1) * rn_pfac                                &   ! add solid  precip heat content at min(Tair,Tsnow)
+         &     * ( MIN( sf(jp_tair)%fnow(:,:,1), rt0 ) - rt0 ) * rcpi
+      qns(:,:) = qns(:,:) * tmask(:,:,1)
+      !
+#if defined key_si3
+      qns_oce(:,:) = zqlw(:,:) - zqsb(:,:) - zqla(:,:)                                ! non solar without emp (only needed by SI3)
+      qsr_oce(:,:) = qsr(:,:)
+#endif
+      !
+      IF ( nn_ice == 0 ) THEN
+         CALL iom_put( "qlw_oce" ,   zqlw )                 ! output downward longwave heat over the ocean
+         CALL iom_put( "qsb_oce" , - zqsb )                 ! output downward sensible heat over the ocean
+         CALL iom_put( "qla_oce" , - zqla )                 ! output downward latent   heat over the ocean
+         CALL iom_put( "qemp_oce",   qns-zqlw+zqsb+zqla )   ! output downward heat content of E-P over the ocean
+         CALL iom_put( "qns_oce" ,   qns  )                 ! output downward non solar heat over the ocean
+         CALL iom_put( "qsr_oce" ,   qsr  )                 ! output downward solar heat over the ocean
+         CALL iom_put( "qt_oce"  ,   qns+qsr )              ! output total downward heat over the ocean
+         tprecip(:,:) = sf(jp_prec)%fnow(:,:,1) * rn_pfac * tmask(:,:,1) ! output total precipitation [kg/m2/s]
+         sprecip(:,:) = sf(jp_snow)%fnow(:,:,1) * rn_pfac * tmask(:,:,1) ! output solid precipitation [kg/m2/s]
+         CALL iom_put( 'snowpre', sprecip )                 ! Snow
+         CALL iom_put( 'precip' , tprecip )                 ! Total precipitation
+      ENDIF
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl(tab2d_1=zqsb , clinfo1=' blk_oce: zqsb   : ', tab2d_2=zqlw , clinfo2=' zqlw  : ')
+         CALL prt_ctl(tab2d_1=zqla , clinfo1=' blk_oce: zqla   : ', tab2d_2=qsr  , clinfo2=' qsr   : ')
+         CALL prt_ctl(tab2d_1=pst  , clinfo1=' blk_oce: pst    : ', tab2d_2=emp  , clinfo2=' emp   : ')
+         CALL prt_ctl(tab2d_1=utau , clinfo1=' blk_oce: utau   : ', mask1=umask,   &
+            &         tab2d_2=vtau , clinfo2=              ' vtau  : ' , mask2=vmask )
+      ENDIF
+      !
+   END SUBROUTINE blk_oce
+
+
+
+   FUNCTION rho_air( ptak, pqa, pslp )
+      !!-------------------------------------------------------------------------------
+      !!                           ***  FUNCTION rho_air  ***
+      !!
+      !! ** Purpose : compute density of (moist) air using the eq. of state of the atmosphere
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk) 
+      !!-------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptak      ! air temperature             [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pqa       ! air specific humidity   [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pslp      ! pressure in                [Pa]
+      REAL(wp), DIMENSION(jpi,jpj)             ::   rho_air   ! density of moist air   [kg/m^3]
+      !!-------------------------------------------------------------------------------
+      !
+      rho_air = pslp / (  R_dry*ptak * ( 1._wp + rctv0*pqa )  )
+      !
+   END FUNCTION rho_air
+
+
+   FUNCTION cp_air( pqa )
+      !!-------------------------------------------------------------------------------
+      !!                           ***  FUNCTION cp_air  ***
+      !!
+      !! ** Purpose : Compute specific heat (Cp) of moist air
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!-------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pqa      ! air specific humidity         [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj)             ::   cp_air   ! specific heat of moist air   [J/K/kg]
+      !!-------------------------------------------------------------------------------
+      !
+      Cp_air = Cp_dry + Cp_vap * pqa
+      !
+   END FUNCTION cp_air
+
+
+   FUNCTION q_sat( ptak, pslp )
+      !!----------------------------------------------------------------------------------
+      !!                           ***  FUNCTION q_sat  ***
+      !!
+      !! ** Purpose : Specific humidity at saturation in [kg/kg]
+      !!              Based on accurate estimate of "e_sat"
+      !!              aka saturation water vapor (Goff, 1957)
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptak    ! air temperature                       [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pslp    ! sea level atmospheric pressure       [Pa]
+      REAL(wp), DIMENSION(jpi,jpj)             ::   q_sat   ! Specific humidity at saturation   [kg/kg]
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::   ze_sat, ztmp   ! local scalar
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            ztmp = rt0 / ptak(ji,jj)
+            !
+            ! Vapour pressure at saturation [hPa] : WMO, (Goff, 1957)
+            ze_sat = 10.**( 10.79574*(1. - ztmp) - 5.028*LOG10(ptak(ji,jj)/rt0)        &
+               &    + 1.50475*10.**(-4)*(1. - 10.**(-8.2969*(ptak(ji,jj)/rt0 - 1.)) )  &
+               &    + 0.42873*10.**(-3)*(10.**(4.76955*(1. - ztmp)) - 1.) + 0.78614  )
+               !
+            q_sat(ji,jj) = reps0 * ze_sat/( 0.01_wp*pslp(ji,jj) - (1._wp - reps0)*ze_sat )   ! 0.01 because SLP is in [Pa]
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION q_sat
+
+
+   FUNCTION gamma_moist( ptak, pqa )
+      !!----------------------------------------------------------------------------------
+      !!                           ***  FUNCTION gamma_moist  ***
+      !!
+      !! ** Purpose : Compute the moist adiabatic lapse-rate.
+      !!     => http://glossary.ametsoc.org/wiki/Moist-adiabatic_lapse_rate
+      !!     => http://www.geog.ucsb.edu/~joel/g266_s10/lecture_notes/chapt03/oh10_3_01/oh10_3_01.html
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptak          ! air temperature       [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pqa           ! specific humidity [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj)             ::   gamma_moist   ! moist adiabatic lapse-rate
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) :: zrv, ziRT        ! local scalar
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zrv = pqa(ji,jj) / (1. - pqa(ji,jj))
+            ziRT = 1. / (R_dry*ptak(ji,jj))    ! 1/RT
+            gamma_moist(ji,jj) = grav * ( 1. + rLevap*zrv*ziRT ) / ( Cp_dry + rLevap*rLevap*zrv*reps0*ziRT/ptak(ji,jj) )
+         END DO
+      END DO
+      !
+   END FUNCTION gamma_moist
+
+
+   FUNCTION L_vap( psst )
+      !!---------------------------------------------------------------------------------
+      !!                           ***  FUNCTION L_vap  ***
+      !!
+      !! ** Purpose : Compute the latent heat of vaporization of water from temperature
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             ::   L_vap   ! latent heat of vaporization   [J/kg]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   psst   ! water temperature                [K]
+      !!----------------------------------------------------------------------------------
+      !
+      L_vap = (  2.501 - 0.00237 * ( psst(:,:) - rt0)  ) * 1.e6
+      !
+   END FUNCTION L_vap
+
+#if defined key_si3
+   !!----------------------------------------------------------------------
+   !!   'key_si3'                                       SI3 sea-ice model
+   !!----------------------------------------------------------------------
+   !!   blk_ice_tau : provide the air-ice stress
+   !!   blk_ice_flx : provide the heat and mass fluxes at air-ice interface
+   !!   blk_ice_qcn : provide ice surface temperature and snow/ice conduction flux (emulating conduction flux)
+   !!   Cdn10_Lupkes2012 : Lupkes et al. (2012) air-ice drag
+   !!   Cdn10_Lupkes2015 : Lupkes et al. (2015) air-ice drag 
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE blk_ice_tau
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE blk_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary condition over sea-ice
+      !!
+      !! ** Method  :   compute momentum using bulk formulation
+      !!                formulea, ice variables and read atmospheric fields.
+      !!                NB: ice drag coefficient is assumed to be a constant
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp) ::   zwndi_f , zwndj_f, zwnorm_f   ! relative wind module and components at F-point
+      REAL(wp) ::   zwndi_t , zwndj_t             ! relative wind components at T-point
+      REAL(wp) ::   zztmp1  , zztmp2              ! temporary values
+      REAL(wp), DIMENSION(jpi,jpj) ::   zrhoa     ! transfer coefficient for momentum      (tau)
+      !!---------------------------------------------------------------------
+      !
+      ! set transfer coefficients to default sea-ice values
+      Cd_atm(:,:) = Cd_ice
+      Ch_atm(:,:) = Cd_ice
+      Ce_atm(:,:) = Cd_ice
+
+      wndm_ice(:,:) = 0._wp      !!gm brutal....
+
+      ! ------------------------------------------------------------ !
+      !    Wind module relative to the moving ice ( U10m - U_ice )   !
+      ! ------------------------------------------------------------ !
+      ! C-grid ice dynamics :   U & V-points (same as ocean)
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            zwndi_t = (  sf(jp_wndi)%fnow(ji,jj,1) - rn_vfac * 0.5 * ( u_ice(ji-1,jj  ) + u_ice(ji,jj) )  )
+            zwndj_t = (  sf(jp_wndj)%fnow(ji,jj,1) - rn_vfac * 0.5 * ( v_ice(ji  ,jj-1) + v_ice(ji,jj) )  )
+            wndm_ice(ji,jj) = SQRT( zwndi_t * zwndi_t + zwndj_t * zwndj_t ) * tmask(ji,jj,1)
+         END DO
+      END DO
+      CALL lbc_lnk( 'sbcblk', wndm_ice, 'T',  1. )
+      !
+      ! Make ice-atm. drag dependent on ice concentration
+      IF    ( ln_Cd_L12 ) THEN   ! calculate new drag from Lupkes(2012) equations
+         CALL Cdn10_Lupkes2012( Cd_atm )
+         Ch_atm(:,:) = Cd_atm(:,:)       ! momentum and heat transfer coef. are considered identical
+      ELSEIF( ln_Cd_L15 ) THEN   ! calculate new drag from Lupkes(2015) equations
+         CALL Cdn10_Lupkes2015( Cd_atm, Ch_atm ) 
+      ENDIF
+
+!!      CALL iom_put( "Cd_ice", Cd_atm)  ! output value of pure ice-atm. transfer coef.
+!!      CALL iom_put( "Ch_ice", Ch_atm)  ! output value of pure ice-atm. transfer coef.
+
+      ! local scalars ( place there for vector optimisation purposes)
+      ! Computing density of air! Way denser that 1.2 over sea-ice !!!
+      zrhoa (:,:) =  rho_air(sf(jp_tair)%fnow(:,:,1), sf(jp_humi)%fnow(:,:,1), sf(jp_slp)%fnow(:,:,1))
+
+      ! ------------------------------------------------------------ !
+      !    Wind stress relative to the moving ice ( U10m - U_ice )   !
+      ! ------------------------------------------------------------ !
+      zztmp1 = rn_vfac * 0.5_wp
+      DO jj = 2, jpj    ! at T point
+         DO ji = 2, jpi
+            zztmp2 = zrhoa(ji,jj) * Cd_atm(ji,jj) * wndm_ice(ji,jj)
+            utau_ice(ji,jj) = zztmp2 * ( sf(jp_wndi)%fnow(ji,jj,1) - zztmp1 * ( u_ice(ji-1,jj  ) + u_ice(ji,jj) ) )
+            vtau_ice(ji,jj) = zztmp2 * ( sf(jp_wndj)%fnow(ji,jj,1) - zztmp1 * ( v_ice(ji  ,jj-1) + v_ice(ji,jj) ) )
+         END DO
+      END DO
+      !
+      DO jj = 2, jpjm1  ! U & V-points (same as ocean).
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            ! take care of the land-sea mask to avoid "pollution" of coastal stress. p[uv]taui used in frazil and  rheology 
+            zztmp1 = 0.5_wp * ( 2. - umask(ji,jj,1) ) * MAX( tmask(ji,jj,1),tmask(ji+1,jj  ,1) )
+            zztmp2 = 0.5_wp * ( 2. - vmask(ji,jj,1) ) * MAX( tmask(ji,jj,1),tmask(ji  ,jj+1,1) )
+            utau_ice(ji,jj) = zztmp1 * ( utau_ice(ji,jj) + utau_ice(ji+1,jj  ) )
+            vtau_ice(ji,jj) = zztmp2 * ( vtau_ice(ji,jj) + vtau_ice(ji  ,jj+1) )
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'sbcblk', utau_ice, 'U', -1., vtau_ice, 'V', -1. )
+      !
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl(tab2d_1=utau_ice  , clinfo1=' blk_ice: utau_ice : ', tab2d_2=vtau_ice  , clinfo2=' vtau_ice : ')
+         CALL prt_ctl(tab2d_1=wndm_ice  , clinfo1=' blk_ice: wndm_ice : ')
+      ENDIF
+      !
+   END SUBROUTINE blk_ice_tau
+
+
+   SUBROUTINE blk_ice_flx( ptsu, phs, phi, palb )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE blk_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the heat and mass fluxes at air-ice interface
+      !!
+      !! ** Method  :   compute heat and freshwater exchanged
+      !!                between atmosphere and sea-ice using bulk formulation
+      !!                formulea, ice variables and read atmmospheric fields.
+      !!
+      !! caution : the net upward water flux has with mm/day unit
+      !!---------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   ptsu   ! sea ice surface temperature
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   palb   ! ice albedo (all skies)
+      !!
+      INTEGER  ::   ji, jj, jl               ! dummy loop indices
+      REAL(wp) ::   zst3                     ! local variable
+      REAL(wp) ::   zcoef_dqlw, zcoef_dqla   !   -      -
+      REAL(wp) ::   zztmp, z1_rLsub          !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z1_st         ! inverse of surface temperature
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z_qlw         ! long wave heat flux over ice
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z_qsb         ! sensible  heat flux over ice
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z_dqlw        ! long wave heat sensitivity over ice
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   z_dqsb        ! sensible  heat sensitivity over ice
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zevap, zsnw   ! evaporation and snw distribution after wind blowing (SI3)
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zrhoa
+      REAL(wp), DIMENSION(jpi,jpj)     ::   ztmp, ztmp2
+      REAL(wp), DIMENSION(jpi,jpj)     ::   ztri
+      !!---------------------------------------------------------------------
+      !
+      zcoef_dqlw = 4.0 * 0.95 * Stef             ! local scalars
+      zcoef_dqla = -Ls * 11637800. * (-5897.8)
+      !
+      zrhoa(:,:) = rho_air( sf(jp_tair)%fnow(:,:,1), sf(jp_humi)%fnow(:,:,1), sf(jp_slp)%fnow(:,:,1) )
+      !
+      zztmp = 1. / ( 1. - albo )
+      WHERE( ptsu(:,:,:) /= 0._wp )   ;   z1_st(:,:,:) = 1._wp / ptsu(:,:,:)
+      ELSEWHERE                       ;   z1_st(:,:,:) = 0._wp
+      END WHERE
+      !                                     ! ========================== !
+      DO jl = 1, jpl                        !  Loop over ice categories  !
+         !                                  ! ========================== !
+         DO jj = 1 , jpj
+            DO ji = 1, jpi
+               ! ----------------------------!
+               !      I   Radiative FLUXES   !
+               ! ----------------------------!
+               zst3 = ptsu(ji,jj,jl) * ptsu(ji,jj,jl) * ptsu(ji,jj,jl)
+               ! Short Wave (sw)
+               qsr_ice(ji,jj,jl) = zztmp * ( 1. - palb(ji,jj,jl) ) * qsr(ji,jj)
+               ! Long  Wave (lw)
+               z_qlw(ji,jj,jl) = 0.95 * ( sf(jp_qlw)%fnow(ji,jj,1) - Stef * ptsu(ji,jj,jl) * zst3 ) * tmask(ji,jj,1)
+               ! lw sensitivity
+               z_dqlw(ji,jj,jl) = zcoef_dqlw * zst3
+
+               ! ----------------------------!
+               !     II    Turbulent FLUXES  !
+               ! ----------------------------!
+
+               ! ... turbulent heat fluxes with Ch_atm recalculated in blk_ice_tau
+               ! Sensible Heat
+               z_qsb(ji,jj,jl) = zrhoa(ji,jj) * cpa * Ch_atm(ji,jj) * wndm_ice(ji,jj) * (ptsu(ji,jj,jl) - sf(jp_tair)%fnow(ji,jj,1))
+               ! Latent Heat
+               qla_ice(ji,jj,jl) = rn_efac * MAX( 0.e0, zrhoa(ji,jj) * Ls  * Ch_atm(ji,jj) * wndm_ice(ji,jj) *  &
+                  &                ( 11637800. * EXP( -5897.8 * z1_st(ji,jj,jl) ) / zrhoa(ji,jj) - sf(jp_humi)%fnow(ji,jj,1) ) )
+               ! Latent heat sensitivity for ice (Dqla/Dt)
+               IF( qla_ice(ji,jj,jl) > 0._wp ) THEN
+                  dqla_ice(ji,jj,jl) = rn_efac * zcoef_dqla * Ch_atm(ji,jj) * wndm_ice(ji,jj) *  &
+                     &                 z1_st(ji,jj,jl)*z1_st(ji,jj,jl) * EXP(-5897.8 * z1_st(ji,jj,jl))
+               ELSE
+                  dqla_ice(ji,jj,jl) = 0._wp
+               ENDIF
+
+               ! Sensible heat sensitivity (Dqsb_ice/Dtn_ice)
+               z_dqsb(ji,jj,jl) = zrhoa(ji,jj) * cpa * Ch_atm(ji,jj) * wndm_ice(ji,jj)
+
+               ! ----------------------------!
+               !     III    Total FLUXES     !
+               ! ----------------------------!
+               ! Downward Non Solar flux
+               qns_ice (ji,jj,jl) =     z_qlw (ji,jj,jl) - z_qsb (ji,jj,jl) - qla_ice (ji,jj,jl)
+               ! Total non solar heat flux sensitivity for ice
+               dqns_ice(ji,jj,jl) = - ( z_dqlw(ji,jj,jl) + z_dqsb(ji,jj,jl) + dqla_ice(ji,jj,jl) )
+            END DO
+            !
+         END DO
+         !
+      END DO
+      !
+      tprecip(:,:) = sf(jp_prec)%fnow(:,:,1) * rn_pfac * tmask(:,:,1)  ! total precipitation [kg/m2/s]
+      sprecip(:,:) = sf(jp_snow)%fnow(:,:,1) * rn_pfac * tmask(:,:,1)  ! solid precipitation [kg/m2/s]
+      CALL iom_put( 'snowpre', sprecip )                    ! Snow precipitation
+      CALL iom_put( 'precip' , tprecip )                    ! Total precipitation
+
+      ! --- evaporation --- !
+      z1_rLsub = 1._wp / rLsub
+      evap_ice (:,:,:) = rn_efac * qla_ice (:,:,:) * z1_rLsub    ! sublimation
+      devap_ice(:,:,:) = rn_efac * dqla_ice(:,:,:) * z1_rLsub    ! d(sublimation)/dT
+      zevap    (:,:)   = rn_efac * ( emp(:,:) + tprecip(:,:) )   ! evaporation over ocean
+
+      ! --- evaporation minus precipitation --- !
+      zsnw(:,:) = 0._wp
+      CALL ice_var_snwblow( (1.-at_i_b(:,:)), zsnw )  ! snow distribution over ice after wind blowing
+      emp_oce(:,:) = ( 1._wp - at_i_b(:,:) ) * zevap(:,:) - ( tprecip(:,:) - sprecip(:,:) ) - sprecip(:,:) * (1._wp - zsnw )
+      emp_ice(:,:) = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw
+      emp_tot(:,:) = emp_oce(:,:) + emp_ice(:,:)
+
+      ! --- heat flux associated with emp --- !
+      qemp_oce(:,:) = - ( 1._wp - at_i_b(:,:) ) * zevap(:,:) * sst_m(:,:) * rcp                  & ! evap at sst
+         &          + ( tprecip(:,:) - sprecip(:,:) ) * ( sf(jp_tair)%fnow(:,:,1) - rt0 ) * rcp  & ! liquid precip at Tair
+         &          +   sprecip(:,:) * ( 1._wp - zsnw ) *                                        & ! solid precip at min(Tair,Tsnow)
+         &              ( ( MIN( sf(jp_tair)%fnow(:,:,1), rt0 ) - rt0 ) * rcpi * tmask(:,:,1) - rLfus )
+      qemp_ice(:,:) =   sprecip(:,:) * zsnw *                                                    & ! solid precip (only)
+         &              ( ( MIN( sf(jp_tair)%fnow(:,:,1), rt0 ) - rt0 ) * rcpi * tmask(:,:,1) - rLfus )
+
+      ! --- total solar and non solar fluxes --- !
+      qns_tot(:,:) = ( 1._wp - at_i_b(:,:) ) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 )  &
+         &           + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot(:,:) = ( 1._wp - at_i_b(:,:) ) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- heat content of precip over ice in J/m3 (to be used in 1D-thermo) --- !
+      qprec_ice(:,:) = rhos * ( ( MIN( sf(jp_tair)%fnow(:,:,1), rt0 ) - rt0 ) * rcpi * tmask(:,:,1) - rLfus )
+
+      ! --- heat content of evap over ice in W/m2 (to be used in 1D-thermo) ---
+      DO jl = 1, jpl
+         qevap_ice(:,:,jl) = 0._wp ! should be -evap_ice(:,:,jl)*( ( Tice - rt0 ) * rcpi * tmask(:,:,1) )
+         !                         ! But we do not have Tice => consider it at 0degC => evap=0 
+      END DO
+
+      ! --- shortwave radiation transmitted thru the surface scattering layer (W/m2) --- !
+      IF( nn_qtrice == 0 ) THEN
+         ! formulation derived from Grenfell and Maykut (1977), where transmission rate
+         !    1) depends on cloudiness
+         !    2) is 0 when there is any snow
+         !    3) tends to 1 for thin ice
+         ztri(:,:) = 0.18 * ( 1.0 - cloud_fra(:,:) ) + 0.35 * cloud_fra(:,:)  ! surface transmission when hi>10cm
+         DO jl = 1, jpl
+            WHERE    ( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) <  0.1_wp )     ! linear decrease from hi=0 to 10cm  
+               qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ( ztri(:,:) + ( 1._wp - ztri(:,:) ) * ( 1._wp - phi(:,:,jl) * 10._wp ) )
+            ELSEWHERE( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) >= 0.1_wp )     ! constant (ztri) when hi>10cm
+               qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ztri(:,:)
+            ELSEWHERE                                                         ! zero when hs>0
+               qtr_ice_top(:,:,jl) = 0._wp 
+            END WHERE
+         ENDDO
+      ELSEIF( nn_qtrice == 1 ) THEN
+         ! formulation is derived from the thesis of M. Lebrun (2019).
+         !    It represents the best fit using several sets of observations
+         !    It comes with snow conductivities adapted to freezing/melting conditions (see icethd_zdf_bl99.F90)
+         qtr_ice_top(:,:,:) = 0.3_wp * qsr_ice(:,:,:)
+      ENDIF
+      !
+
+      IF( iom_use('evap_ao_cea') .OR. iom_use('hflx_evap_cea') ) THEN
+         ztmp(:,:) = zevap(:,:) * ( 1._wp - at_i_b(:,:) ) 
+         CALL iom_put( 'evap_ao_cea'  , ztmp(:,:) * tmask(:,:,1) )   ! ice-free oce evap (cell average)
+         CALL iom_put( 'hflx_evap_cea', ztmp(:,:) * sst_m(:,:) * rcp * tmask(:,:,1) )   ! heat flux from evap (cell average)
+      ENDIF
+      IF( iom_use('hflx_rain_cea') ) THEN
+         ztmp(:,:) = rcp * ( SUM( (ptsu-rt0) * a_i_b, dim=3 ) + sst_m(:,:) * ( 1._wp - at_i_b(:,:) ) )
+         CALL iom_put( 'hflx_rain_cea', ( tprecip(:,:) - sprecip(:,:) ) * ztmp(:,:) )   ! heat flux from rain (cell average)
+      ENDIF
+      IF( iom_use('hflx_snow_cea') .OR. iom_use('hflx_snow_ao_cea') .OR. iom_use('hflx_snow_ai_cea')  )  THEN
+          WHERE( SUM( a_i_b, dim=3 ) > 1.e-10 ) ;   ztmp(:,:) = rcpi * SUM( (ptsu-rt0) * a_i_b, dim=3 ) / SUM( a_i_b, dim=3 )
+          ELSEWHERE                             ;   ztmp(:,:) = rcp * sst_m(:,:)    
+          ENDWHERE
+          ztmp2(:,:) = sprecip(:,:) * ( ztmp(:,:) - rLfus ) 
+          CALL iom_put('hflx_snow_cea'   , ztmp2(:,:) ) ! heat flux from snow (cell average)
+          CALL iom_put('hflx_snow_ao_cea', ztmp2(:,:) * ( 1._wp - zsnw(:,:) ) ) ! heat flux from snow (over ocean)
+          CALL iom_put('hflx_snow_ai_cea', ztmp2(:,:) *           zsnw(:,:)   ) ! heat flux from snow (over ice)
+      ENDIF
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl(tab3d_1=qla_ice , clinfo1=' blk_ice: qla_ice  : ', tab3d_2=z_qsb   , clinfo2=' z_qsb    : ', kdim=jpl)
+         CALL prt_ctl(tab3d_1=z_qlw   , clinfo1=' blk_ice: z_qlw    : ', tab3d_2=dqla_ice, clinfo2=' dqla_ice : ', kdim=jpl)
+         CALL prt_ctl(tab3d_1=z_dqsb  , clinfo1=' blk_ice: z_dqsb   : ', tab3d_2=z_dqlw  , clinfo2=' z_dqlw   : ', kdim=jpl)
+         CALL prt_ctl(tab3d_1=dqns_ice, clinfo1=' blk_ice: dqns_ice : ', tab3d_2=qsr_ice , clinfo2=' qsr_ice  : ', kdim=jpl)
+         CALL prt_ctl(tab3d_1=ptsu    , clinfo1=' blk_ice: ptsu     : ', tab3d_2=qns_ice , clinfo2=' qns_ice  : ', kdim=jpl)
+         CALL prt_ctl(tab2d_1=tprecip , clinfo1=' blk_ice: tprecip  : ', tab2d_2=sprecip , clinfo2=' sprecip  : ')
+      ENDIF
+      !
+   END SUBROUTINE blk_ice_flx
+   
+
+   SUBROUTINE blk_ice_qcn( ld_virtual_itd, ptsu, ptb, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE blk_ice_qcn  ***
+      !!
+      !! ** Purpose :   Compute surface temperature and snow/ice conduction flux
+      !!                to force sea ice / snow thermodynamics
+      !!                in the case conduction flux is emulated
+      !!                
+      !! ** Method  :   compute surface energy balance assuming neglecting heat storage
+      !!                following the 0-layer Semtner (1976) approach
+      !!
+      !! ** Outputs : - ptsu    : sea-ice / snow surface temperature (K)
+      !!              - qcn_ice : surface inner conduction flux (W/m2)
+      !!
+      !!---------------------------------------------------------------------
+      LOGICAL                   , INTENT(in   ) ::   ld_virtual_itd  ! single-category option
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptsu            ! sea ice / snow surface temperature
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   ptb             ! sea ice base temperature
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   phs             ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   phi             ! sea ice thickness
+      !
+      INTEGER , PARAMETER ::   nit = 10                  ! number of iterations
+      REAL(wp), PARAMETER ::   zepsilon = 0.1_wp         ! characteristic thickness for enhanced conduction
+      !
+      INTEGER  ::   ji, jj, jl           ! dummy loop indices
+      INTEGER  ::   iter                 ! local integer
+      REAL(wp) ::   zfac, zfac2, zfac3   ! local scalars
+      REAL(wp) ::   zkeff_h, ztsu, ztsu0 !
+      REAL(wp) ::   zqc, zqnet           !
+      REAL(wp) ::   zhe, zqa0            !
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zgfac   ! enhanced conduction factor
+      !!---------------------------------------------------------------------
+      
+      ! -------------------------------------!
+      !      I   Enhanced conduction factor  !
+      ! -------------------------------------!
+      ! Emulates the enhancement of conduction by unresolved thin ice (ld_virtual_itd = T)
+      ! Fichefet and Morales Maqueda, JGR 1997
+      !
+      zgfac(:,:,:) = 1._wp
+      
+      IF( ld_virtual_itd ) THEN
+         !
+         zfac  = 1._wp /  ( rn_cnd_s + rcnd_i )
+         zfac2 = EXP(1._wp) * 0.5_wp * zepsilon
+         zfac3 = 2._wp / zepsilon
+         !   
+         DO jl = 1, jpl                
+            DO jj = 1 , jpj
+               DO ji = 1, jpi
+                  zhe = ( rn_cnd_s * phi(ji,jj,jl) + rcnd_i * phs(ji,jj,jl) ) * zfac                            ! Effective thickness
+                  IF( zhe >=  zfac2 )   zgfac(ji,jj,jl) = MIN( 2._wp, 0.5_wp * ( 1._wp + LOG( zhe * zfac3 ) ) ) ! Enhanced conduction factor
+               END DO
+            END DO
+         END DO
+         !      
+      ENDIF
+      
+      ! -------------------------------------------------------------!
+      !      II   Surface temperature and conduction flux            !
+      ! -------------------------------------------------------------!
+      !
+      zfac = rcnd_i * rn_cnd_s
+      !
+      DO jl = 1, jpl
+         DO jj = 1 , jpj
+            DO ji = 1, jpi
+               !                    
+               zkeff_h = zfac * zgfac(ji,jj,jl) / &                                    ! Effective conductivity of the snow-ice system divided by thickness
+                  &      ( rcnd_i * phs(ji,jj,jl) + rn_cnd_s * MAX( 0.01, phi(ji,jj,jl) ) )
+               ztsu    = ptsu(ji,jj,jl)                                                ! Store current iteration temperature
+               ztsu0   = ptsu(ji,jj,jl)                                                ! Store initial surface temperature
+               zqa0    = qsr_ice(ji,jj,jl) - qtr_ice_top(ji,jj,jl) + qns_ice(ji,jj,jl) ! Net initial atmospheric heat flux
+               !
+               DO iter = 1, nit     ! --- Iterative loop
+                  zqc   = zkeff_h * ( ztsu - ptb(ji,jj) )                              ! Conduction heat flux through snow-ice system (>0 downwards)
+                  zqnet = zqa0 + dqns_ice(ji,jj,jl) * ( ztsu - ptsu(ji,jj,jl) ) - zqc  ! Surface energy budget
+                  ztsu  = ztsu - zqnet / ( dqns_ice(ji,jj,jl) - zkeff_h )              ! Temperature update
+               END DO
+               !
+               ptsu   (ji,jj,jl) = MIN( rt0, ztsu )
+               qcn_ice(ji,jj,jl) = zkeff_h * ( ptsu(ji,jj,jl) - ptb(ji,jj) )
+               qns_ice(ji,jj,jl) = qns_ice(ji,jj,jl) + dqns_ice(ji,jj,jl) * ( ptsu(ji,jj,jl) - ztsu0 )
+               qml_ice(ji,jj,jl) = ( qsr_ice(ji,jj,jl) - qtr_ice_top(ji,jj,jl) + qns_ice(ji,jj,jl) - qcn_ice(ji,jj,jl) )  &
+                             &   * MAX( 0._wp , SIGN( 1._wp, ptsu(ji,jj,jl) - rt0 ) )
+
+               ! --- Diagnose the heat loss due to changing non-solar flux (as in icethd_zdf_bl99) --- !
+               hfx_err_dif(ji,jj) = hfx_err_dif(ji,jj) - ( dqns_ice(ji,jj,jl) * ( ptsu(ji,jj,jl) - ztsu0 ) ) * a_i_b(ji,jj,jl) 
+
+            END DO
+         END DO
+         !
+      END DO 
+      !      
+   END SUBROUTINE blk_ice_qcn
+   
+
+   SUBROUTINE Cdn10_Lupkes2012( Cd )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE  Cdn10_Lupkes2012  ***
+      !!
+      !! ** Purpose :    Recompute the neutral air-ice drag referenced at 10m 
+      !!                 to make it dependent on edges at leads, melt ponds and flows.
+      !!                 After some approximations, this can be resumed to a dependency
+      !!                 on ice concentration.
+      !!                
+      !! ** Method :     The parameterization is taken from Lupkes et al. (2012) eq.(50)
+      !!                 with the highest level of approximation: level4, eq.(59)
+      !!                 The generic drag over a cell partly covered by ice can be re-written as follows:
+      !!
+      !!                 Cd = Cdw * (1-A) + Cdi * A + Ce * (1-A)**(nu+1/(10*beta)) * A**mu
+      !!
+      !!                    Ce = 2.23e-3       , as suggested by Lupkes (eq. 59)
+      !!                    nu = mu = beta = 1 , as suggested by Lupkes (eq. 59)
+      !!                    A is the concentration of ice minus melt ponds (if any)
+      !!
+      !!                 This new drag has a parabolic shape (as a function of A) starting at
+      !!                 Cdw(say 1.5e-3) for A=0, reaching 1.97e-3 for A~0.5 
+      !!                 and going down to Cdi(say 1.4e-3) for A=1
+      !!
+      !!                 It is theoretically applicable to all ice conditions (not only MIZ)
+      !!                 => see Lupkes et al (2013)
+      !!
+      !! ** References : Lupkes et al. JGR 2012 (theory)
+      !!                 Lupkes et al. GRL 2013 (application to GCM)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   Cd
+      REAL(wp), PARAMETER ::   zCe   = 2.23e-03_wp
+      REAL(wp), PARAMETER ::   znu   = 1._wp
+      REAL(wp), PARAMETER ::   zmu   = 1._wp
+      REAL(wp), PARAMETER ::   zbeta = 1._wp
+      REAL(wp)            ::   zcoef
+      !!----------------------------------------------------------------------
+      zcoef = znu + 1._wp / ( 10._wp * zbeta )
+
+      ! generic drag over a cell partly covered by ice
+      !!Cd(:,:) = Cd_oce(:,:) * ( 1._wp - at_i_b(:,:) ) +  &                        ! pure ocean drag
+      !!   &      Cd_ice      *           at_i_b(:,:)   +  &                        ! pure ice drag
+      !!   &      zCe         * ( 1._wp - at_i_b(:,:) )**zcoef * at_i_b(:,:)**zmu   ! change due to sea-ice morphology
+
+      ! ice-atm drag
+      Cd(:,:) = Cd_ice +  &                                                         ! pure ice drag
+         &      zCe    * ( 1._wp - at_i_b(:,:) )**zcoef * at_i_b(:,:)**(zmu-1._wp)  ! change due to sea-ice morphology
+      
+   END SUBROUTINE Cdn10_Lupkes2012
+
+
+   SUBROUTINE Cdn10_Lupkes2015( Cd, Ch )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE  Cdn10_Lupkes2015  ***
+      !!
+      !! ** pUrpose :    Alternative turbulent transfert coefficients formulation
+      !!                 between sea-ice and atmosphere with distinct momentum 
+      !!                 and heat coefficients depending on sea-ice concentration 
+      !!                 and atmospheric stability (no meltponds effect for now).
+      !!                
+      !! ** Method :     The parameterization is adapted from Lupkes et al. (2015)
+      !!                 and ECHAM6 atmospheric model. Compared to Lupkes2012 scheme,
+      !!                 it considers specific skin and form drags (Andreas et al. 2010)
+      !!                 to compute neutral transfert coefficients for both heat and 
+      !!                 momemtum fluxes. Atmospheric stability effect on transfert
+      !!                 coefficient is also taken into account following Louis (1979).
+      !!
+      !! ** References : Lupkes et al. JGR 2015 (theory)
+      !!                 Lupkes et al. ECHAM6 documentation 2015 (implementation)
+      !!
+      !!----------------------------------------------------------------------
+      !
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   Cd
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   Ch
+      REAL(wp), DIMENSION(jpi,jpj)            ::   ztm_su, zst, zqo_sat, zqi_sat
+      !
+      ! ECHAM6 constants
+      REAL(wp), PARAMETER ::   z0_skin_ice  = 0.69e-3_wp  ! Eq. 43 [m]
+      REAL(wp), PARAMETER ::   z0_form_ice  = 0.57e-3_wp  ! Eq. 42 [m]
+      REAL(wp), PARAMETER ::   z0_ice       = 1.00e-3_wp  ! Eq. 15 [m]
+      REAL(wp), PARAMETER ::   zce10        = 2.80e-3_wp  ! Eq. 41
+      REAL(wp), PARAMETER ::   zbeta        = 1.1_wp      ! Eq. 41
+      REAL(wp), PARAMETER ::   zc           = 5._wp       ! Eq. 13
+      REAL(wp), PARAMETER ::   zc2          = zc * zc
+      REAL(wp), PARAMETER ::   zam          = 2. * zc     ! Eq. 14
+      REAL(wp), PARAMETER ::   zah          = 3. * zc     ! Eq. 30
+      REAL(wp), PARAMETER ::   z1_alpha     = 1._wp / 0.2_wp  ! Eq. 51
+      REAL(wp), PARAMETER ::   z1_alphaf    = z1_alpha    ! Eq. 56
+      REAL(wp), PARAMETER ::   zbetah       = 1.e-3_wp    ! Eq. 26
+      REAL(wp), PARAMETER ::   zgamma       = 1.25_wp     ! Eq. 26
+      REAL(wp), PARAMETER ::   z1_gamma     = 1._wp / zgamma
+      REAL(wp), PARAMETER ::   r1_3         = 1._wp / 3._wp
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::   zthetav_os, zthetav_is, zthetav_zu
+      REAL(wp) ::   zrib_o, zrib_i
+      REAL(wp) ::   zCdn_skin_ice, zCdn_form_ice, zCdn_ice
+      REAL(wp) ::   zChn_skin_ice, zChn_form_ice
+      REAL(wp) ::   z0w, z0i, zfmi, zfmw, zfhi, zfhw
+      REAL(wp) ::   zCdn_form_tmp
+      !!----------------------------------------------------------------------
+
+      ! mean temperature
+      WHERE( at_i_b(:,:) > 1.e-20 )   ;   ztm_su(:,:) = SUM( t_su(:,:,:) * a_i_b(:,:,:) , dim=3 ) / at_i_b(:,:)
+      ELSEWHERE                       ;   ztm_su(:,:) = rt0
+      ENDWHERE
+      
+      ! Momentum Neutral Transfert Coefficients (should be a constant)
+      zCdn_form_tmp = zce10 * ( LOG( 10._wp / z0_form_ice + 1._wp ) / LOG( rn_zu / z0_form_ice + 1._wp ) )**2   ! Eq. 40
+      zCdn_skin_ice = ( vkarmn                                      / LOG( rn_zu / z0_skin_ice + 1._wp ) )**2   ! Eq. 7
+      zCdn_ice      = zCdn_skin_ice   ! Eq. 7 (cf Lupkes email for details)
+      !zCdn_ice     = 1.89e-3         ! old ECHAM5 value (cf Eq. 32)
+
+      ! Heat Neutral Transfert Coefficients
+      zChn_skin_ice = vkarmn**2 / ( LOG( rn_zu / z0_ice + 1._wp ) * LOG( rn_zu * z1_alpha / z0_skin_ice + 1._wp ) )   ! Eq. 50 + Eq. 52 (cf Lupkes email for details)
+     
+      ! Atmospheric and Surface Variables
+      zst(:,:)     = sst_m(:,:) + rt0                                        ! convert SST from Celcius to Kelvin
+      zqo_sat(:,:) = 0.98_wp * q_sat( zst(:,:)   , sf(jp_slp)%fnow(:,:,1) )  ! saturation humidity over ocean [kg/kg]
+      zqi_sat(:,:) = 0.98_wp * q_sat( ztm_su(:,:), sf(jp_slp)%fnow(:,:,1) )  ! saturation humidity over ice   [kg/kg]
+      !
+      DO jj = 2, jpjm1           ! reduced loop is necessary for reproducibility
+         DO ji = fs_2, fs_jpim1
+            ! Virtual potential temperature [K]
+            zthetav_os = zst(ji,jj)    * ( 1._wp + rctv0 * zqo_sat(ji,jj) )   ! over ocean
+            zthetav_is = ztm_su(ji,jj) * ( 1._wp + rctv0 * zqi_sat(ji,jj) )   ! ocean ice
+            zthetav_zu = t_zu (ji,jj)  * ( 1._wp + rctv0 * q_zu(ji,jj)    )   ! at zu
+            
+            ! Bulk Richardson Number (could use Ri_bulk function from aerobulk instead)
+            zrib_o = grav / zthetav_os * ( zthetav_zu - zthetav_os ) * rn_zu / MAX( 0.5, wndm(ji,jj)     )**2   ! over ocean
+            zrib_i = grav / zthetav_is * ( zthetav_zu - zthetav_is ) * rn_zu / MAX( 0.5, wndm_ice(ji,jj) )**2   ! over ice
+            
+            ! Momentum and Heat Neutral Transfert Coefficients
+            zCdn_form_ice = zCdn_form_tmp * at_i_b(ji,jj) * ( 1._wp - at_i_b(ji,jj) )**zbeta  ! Eq. 40
+            zChn_form_ice = zCdn_form_ice / ( 1._wp + ( LOG( z1_alphaf ) / vkarmn ) * SQRT( zCdn_form_ice ) )               ! Eq. 53 
+                       
+            ! Momentum and Heat Stability functions (possibility to use psi_m_ecmwf instead)
+            z0w = rn_zu * EXP( -1._wp * vkarmn / SQRT( Cdn_oce(ji,jj) ) ) ! over water
+            z0i = z0_skin_ice                                             ! over ice (cf Lupkes email for details)
+            IF( zrib_o <= 0._wp ) THEN
+               zfmw = 1._wp - zam * zrib_o / ( 1._wp + 3._wp * zc2 * Cdn_oce(ji,jj) * SQRT( -zrib_o * ( rn_zu / z0w + 1._wp ) ) )  ! Eq. 10
+               zfhw = ( 1._wp + ( zbetah * ( zthetav_os - zthetav_zu )**r1_3 / ( Chn_oce(ji,jj) * MAX(0.01, wndm(ji,jj)) )   &     ! Eq. 26
+                  &             )**zgamma )**z1_gamma
+            ELSE
+               zfmw = 1._wp / ( 1._wp + zam * zrib_o / SQRT( 1._wp + zrib_o ) )   ! Eq. 12
+               zfhw = 1._wp / ( 1._wp + zah * zrib_o / SQRT( 1._wp + zrib_o ) )   ! Eq. 28
+            ENDIF
+            
+            IF( zrib_i <= 0._wp ) THEN
+               zfmi = 1._wp - zam * zrib_i / (1._wp + 3._wp * zc2 * zCdn_ice * SQRT( -zrib_i * ( rn_zu / z0i + 1._wp)))   ! Eq.  9
+               zfhi = 1._wp - zah * zrib_i / (1._wp + 3._wp * zc2 * zCdn_ice * SQRT( -zrib_i * ( rn_zu / z0i + 1._wp)))   ! Eq. 25
+            ELSE
+               zfmi = 1._wp / ( 1._wp + zam * zrib_i / SQRT( 1._wp + zrib_i ) )   ! Eq. 11
+               zfhi = 1._wp / ( 1._wp + zah * zrib_i / SQRT( 1._wp + zrib_i ) )   ! Eq. 27
+            ENDIF
+            
+            ! Momentum Transfert Coefficients (Eq. 38)
+            Cd(ji,jj) = zCdn_skin_ice *   zfmi +  &
+               &        zCdn_form_ice * ( zfmi * at_i_b(ji,jj) + zfmw * ( 1._wp - at_i_b(ji,jj) ) ) / MAX( 1.e-06, at_i_b(ji,jj) )
+            
+            ! Heat Transfert Coefficients (Eq. 49)
+            Ch(ji,jj) = zChn_skin_ice *   zfhi +  &
+               &        zChn_form_ice * ( zfhi * at_i_b(ji,jj) + zfhw * ( 1._wp - at_i_b(ji,jj) ) ) / MAX( 1.e-06, at_i_b(ji,jj) )
+            !
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'sbcblk', Cd, 'T',  1., Ch, 'T', 1. )
+      !
+   END SUBROUTINE Cdn10_Lupkes2015
+
+#endif
+
+   !!======================================================================
+END MODULE sbcblk
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare.F90	(revision 14097)
@@ -0,0 +1,448 @@
+MODULE sbcblk_algo_coare
+   !!======================================================================
+   !!                       ***  MODULE  sbcblk_algo_coare  ***
+   !! Computes turbulent components of surface fluxes
+   !!         according to Fairall et al. 2003 (COARE v3)
+   !!
+   !!   * bulk transfer coefficients C_D, C_E and C_H
+   !!   * air temp. and spec. hum. adjusted from zt (2m) to zu (10m) if needed
+   !!   * the effective bulk wind speed at 10m U_blk
+   !!   => all these are used in bulk formulas in sbcblk.F90
+   !!
+   !!    Using the bulk formulation/param. of COARE v3, Fairall et al. 2003
+   !!
+   !!
+   !!       Routine turb_coare maintained and developed in AeroBulk
+   !!                     (http://aerobulk.sourceforge.net/)
+   !!
+   !!            Author: Laurent Brodeau, 2016, brodeau@gmail.com
+   !!
+   !!======================================================================
+   !! History :  3.6  !  2016-02  (L.Brodeau)   Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   turb_coare  : computes the bulk turbulent transfer coefficients
+   !!                   adjusts t_air and q_air from zt to zu m
+   !!                   returns the effective bulk wind speed at 10m
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbcwave, ONLY  :  cdn_wave ! wave module
+#if defined key_si3 || defined key_cice
+   USE sbc_ice        ! Surface boundary condition: ice fields
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! distribued memory computing library
+   USE prtctl         ! Print control
+   USE lib_fortran    ! to use key_nosignedzero
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ::   TURB_COARE   ! called by sbcblk.F90
+
+   !                                              !! COARE own values for given constants:
+   REAL(wp), PARAMETER ::   zi0     = 600._wp      ! scale height of the atmospheric boundary layer...
+   REAL(wp), PARAMETER ::   Beta0   =   1.250_wp   ! gustiness parameter
+   REAL(wp), PARAMETER ::   rctv0   =   0.608_wp   ! constant to obtain virtual temperature...
+
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE turb_coare( zt, zu, sst, t_zt, ssq, q_zt, U_zu, &
+      &                   Cd, Ch, Ce, t_zu, q_zu, U_blk,      &
+      &                   Cdn, Chn, Cen                       )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE  turb_coare  ***
+      !!
+      !!            2015: L. Brodeau (brodeau@gmail.com)
+      !!
+      !! ** Purpose :   Computes turbulent transfert coefficients of surface
+      !!                fluxes according to Fairall et al. (2003)
+      !!                If relevant (zt /= zu), adjust temperature and humidity from height zt to zu
+      !!
+      !! ** Method : Monin Obukhov Similarity Theory
+      !!----------------------------------------------------------------------
+      !!
+      !! INPUT :
+      !! -------
+      !!    *  zt   : height for temperature and spec. hum. of air            [m]
+      !!    *  zu   : height for wind speed (generally 10m)                   [m]
+      !!    *  U_zu : scalar wind speed at 10m                                [m/s]
+      !!    *  sst  : SST                                                     [K]
+      !!    *  t_zt : potential air temperature at zt                         [K]
+      !!    *  ssq  : specific humidity at saturation at SST                  [kg/kg]
+      !!    *  q_zt : specific humidity of air at zt                          [kg/kg]
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!    *  Cd     : drag coefficient
+      !!    *  Ch     : sensible heat coefficient
+      !!    *  Ce     : evaporation coefficient
+      !!    *  t_zu   : pot. air temperature adjusted at wind height zu       [K]
+      !!    *  q_zu   : specific humidity of air        //                    [kg/kg]
+      !!    *  U_blk  : bulk wind at 10m                                      [m/s]
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in   )                     ::   zt       ! height for t_zt and q_zt                    [m]
+      REAL(wp), INTENT(in   )                     ::   zu       ! height for U_zu                             [m]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   sst      ! sea surface temperature                [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   t_zt     ! potential air temperature              [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   ssq      ! sea surface specific humidity           [kg/kg]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   q_zt     ! specific air humidity at zt             [kg/kg]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   U_zu     ! 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)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ce       ! transfert coefficient for evaporation   (Q_lat)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   t_zu     ! pot. air temp. adjusted at zu               [K]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   q_zu     ! spec. humidity adjusted at zu           [kg/kg]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   U_blk    ! bulk wind at 10m                          [m/s]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Cdn, Chn, Cen ! neutral transfer coefficients
+      !
+      INTEGER :: j_itt
+      LOGICAL ::   l_zt_equal_zu = .FALSE.      ! if q and t are given at same height as U
+      INTEGER , PARAMETER ::   nb_itt = 4       ! number of itterations
+
+      REAL(wp), DIMENSION(jpi,jpj) ::  &
+         &  u_star, t_star, q_star, &
+         &  dt_zu, dq_zu,    &
+         &  znu_a,           & !: Nu_air, Viscosity of air
+         &  z0, z0t
+      REAL(wp), DIMENSION(jpi,jpj) ::   zeta_u        ! stability parameter at height zu
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztmp0, ztmp1, ztmp2
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zeta_t        ! stability parameter at height zt
+      !!----------------------------------------------------------------------
+      !
+      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 )  ALLOCATE( zeta_t(jpi,jpj) )
+
+      !! First guess of temperature and humidity at height zu:
+      t_zu = MAX(t_zt , 0.0)    ! who knows what's given on masked-continental regions...
+      q_zu = MAX(q_zt , 1.e-6)  !               "
+
+      !! Pot. temp. difference (and we don't want it to be 0!)
+      dt_zu = t_zu - sst ;  dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+      dq_zu = q_zu - ssq ;  dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+
+      znu_a = visc_air(t_zt) ! Air viscosity (m^2/s) at zt given from temperature in (K)
+
+      ztmp2 = 0.5*0.5  ! initial guess for wind gustiness contribution
+      U_blk = SQRT(U_zu*U_zu + ztmp2)
+
+      ztmp2   = 10000.     ! optimization: ztmp2 == 1/z0 (with z0 first guess == 0.0001)
+      ztmp0   = LOG(zu*ztmp2)
+      ztmp1   = LOG(10.*ztmp2)
+      u_star = 0.035*U_blk*ztmp1/ztmp0       ! (u* = 0.035*Un10)
+
+
+      z0     = alfa_charn(U_blk)*u_star*u_star/grav + 0.11*znu_a/u_star
+      z0t    = 0.1*EXP(vkarmn/(0.00115/(vkarmn/ztmp1)))   !  WARNING: 1/z0t !
+
+      ztmp2  = vkarmn/ztmp0
+      Cd     = ztmp2*ztmp2    ! first guess of Cd
+
+      ztmp0 = vkarmn*vkarmn/LOG(zt*z0t)/Cd
+
+      !Ribcu = -zu/(zi0*0.004*Beta0**3) !! Saturation Rib, zi0 = tropicalbound. layer depth
+      ztmp2  = grav*zu*(dt_zu + rctv0*t_zu*dq_zu)/(t_zu*U_blk*U_blk)  !! Ribu Bulk Richardson number
+      ztmp1 = 0.5 + sign(0.5 , ztmp2)
+      ztmp0 = ztmp0*ztmp2
+      !!             Ribu < 0                                 Ribu > 0   Beta = 1.25
+      zeta_u = (1.-ztmp1) * (ztmp0/(1.+ztmp2/(-zu/(zi0*0.004*Beta0**3)))) &
+         &  +     ztmp1   * (ztmp0*(1. + 27./9.*ztmp2/ztmp0))
+
+      !! First guess M-O stability dependent scaling params.(u*,t*,q*) to estimate z0 and z/L
+      ztmp0  =  vkarmn/(LOG(zu*z0t) - psi_h_coare(zeta_u))
+
+      u_star = U_blk*vkarmn/(LOG(zu) - LOG(z0)  - psi_m_coare(zeta_u))
+      t_star = dt_zu*ztmp0
+      q_star = dq_zu*ztmp0
+
+      ! What's need to be done if zt /= zu:
+      IF( .NOT. l_zt_equal_zu ) THEN
+
+         zeta_t = zt*zeta_u/zu
+
+         !! First update of values at zu (or zt for wind)
+         ztmp0 = psi_h_coare(zeta_u) - psi_h_coare(zeta_t)
+         ztmp1 = log(zt/zu) + ztmp0
+         t_zu = t_zt - t_star/vkarmn*ztmp1
+         q_zu = q_zt - q_star/vkarmn*ztmp1
+         q_zu = (0.5 + sign(0.5,q_zu))*q_zu !Makes it impossible to have negative humidity :
+
+         dt_zu = t_zu - sst  ; dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+         dq_zu = q_zu - ssq  ; dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+
+      END IF
+
+      !! ITERATION BLOCK
+      DO j_itt = 1, nb_itt
+
+         !!Inverse of Monin-Obukov length (1/L) :
+         ztmp0 = One_on_L(t_zu, q_zu, u_star, t_star, q_star)  ! 1/L == 1/[Monin-Obukhov length]
+
+         ztmp1 = u_star*u_star   ! u*^2
+
+         !! Update wind at 10m taking into acount convection-related wind gustiness:
+         ! Ug = Beta*w*  (Beta = 1.25, Fairall et al. 2003, Eq.8):
+         ztmp2 = Beta0*Beta0*ztmp1*(MAX(-zi0*ztmp0/vkarmn,0.))**(2./3.)   ! => ztmp2 == Ug^2
+         !!   ! Only true when unstable (L<0) => when ztmp0 < 0 => explains "-" before 600.
+         U_blk = MAX(sqrt(U_zu*U_zu + ztmp2), 0.2)        ! include gustiness in bulk wind speed
+         ! => 0.2 prevents U_blk to be 0 in stable case when U_zu=0.
+
+         !! Updating Charnock parameter, increases with the wind (Fairall et al., 2003 p. 577-578)
+         ztmp2 = alfa_charn(U_blk)  ! alpha Charnock parameter
+
+         !! Roughness lengthes z0, z0t (z0q = z0t) :
+         z0   = ztmp2*ztmp1/grav + 0.11*znu_a/u_star ! Roughness length (eq.6)
+         ztmp1 = z0*u_star/znu_a                             ! Re_r: roughness Reynolds number
+         z0t  = min( 1.1E-4 , 5.5E-5*ztmp1**(-0.6) )         ! Scalar roughness for both theta and q (eq.28)
+
+         !! Stability parameters:
+         zeta_u = zu*ztmp0 ; zeta_u = sign( min(abs(zeta_u),50.0), zeta_u )
+         IF( .NOT. l_zt_equal_zu ) THEN
+            zeta_t = zt*ztmp0 ;  zeta_t = sign( min(abs(zeta_t),50.0), zeta_t )
+         END IF
+
+         !! Turbulent scales at zu=10m :
+         ztmp0   = psi_h_coare(zeta_u)
+         ztmp1   = vkarmn/(LOG(zu) -LOG(z0t) - ztmp0)
+
+         t_star = dt_zu*ztmp1
+         q_star = dq_zu*ztmp1
+         u_star = U_blk*vkarmn/(LOG(zu) -LOG(z0) - psi_m_coare(zeta_u))
+
+         IF( .NOT. l_zt_equal_zu ) THEN
+            ! What's need to be done if zt /= zu
+            !! Re-updating temperature and humidity at zu :
+            ztmp2 = ztmp0 - psi_h_coare(zeta_t)
+            ztmp1 = log(zt/zu) + ztmp2
+            t_zu = t_zt - t_star/vkarmn*ztmp1
+            q_zu = q_zt - q_star/vkarmn*ztmp1
+            dt_zu = t_zu - sst ;  dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+            dq_zu = q_zu - ssq ;  dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+         END IF
+
+      END DO
+      !
+      ! compute transfer coefficients at zu :
+      ztmp0 = u_star/U_blk
+      Cd   = ztmp0*ztmp0
+      Ch   = ztmp0*t_star/dt_zu
+      Ce   = ztmp0*q_star/dq_zu
+      !
+      ztmp1 = zu + z0
+      Cdn = vkarmn*vkarmn / (log(ztmp1/z0 )*log(ztmp1/z0 ))
+      Chn = vkarmn*vkarmn / (log(ztmp1/z0t)*log(ztmp1/z0t))
+      Cen = Chn
+      !
+      IF( .NOT. l_zt_equal_zu ) DEALLOCATE( zeta_t )
+      !
+   END SUBROUTINE turb_coare
+
+
+   FUNCTION alfa_charn( pwnd )
+      !!-------------------------------------------------------------------
+      !! Compute the Charnock parameter as a function of the wind speed
+      !!
+      !! (Fairall et al., 2003 p.577-578)
+      !!
+      !! Wind below 10 m/s :  alfa = 0.011
+      !! Wind between 10 and 18 m/s : linear increase from 0.011 to 0.018
+      !! Wind greater than 18 m/s :  alfa = 0.018
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk  (https://sourceforge.net/p/aerobulk)
+      !!-------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: alfa_charn
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pwnd   ! wind speed
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) :: zw, zgt10, zgt18
+      !!-------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zw = pwnd(ji,jj)   ! wind speed
+            !
+            ! Charnock's constant, increases with the wind :
+            zgt10 = 0.5 + SIGN(0.5,(zw - 10.)) ! If zw<10. --> 0, else --> 1
+            zgt18 = 0.5 + SIGN(0.5,(zw - 18.)) ! If zw<18. --> 0, else --> 1
+            !
+            alfa_charn(ji,jj) =  (1. - zgt10)*0.011    &    ! wind is lower than 10 m/s
+               &     + zgt10*((1. - zgt18)*(0.011 + (0.018 - 0.011) &
+               &      *(zw - 10.)/(18. - 10.)) + zgt18*( 0.018 ) )    ! Hare et al. (1999)
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION alfa_charn
+
+
+   FUNCTION One_on_L( ptha, pqa, pus, pts, pqs )
+      !!------------------------------------------------------------------------
+      !!
+      !! Evaluates the 1./(Monin Obukhov length) from air temperature and
+      !!  specific humidity, and frictional scales u*, t* and q*
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: One_on_L         !: 1./(Monin Obukhov length) [m^-1]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: ptha,  &  !: average potetntial air temperature [K]
+         &                                        pqa,   &  !: average specific humidity of air   [kg/kg]
+         &                                      pus, pts, pqs   !: frictional velocity, temperature and humidity
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::     zqa          ! local scalar
+      !!-------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zqa = (1. + rctv0*pqa(ji,jj))
+            !
+            One_on_L(ji,jj) =  grav*vkarmn*(pts(ji,jj)*zqa + rctv0*ptha(ji,jj)*pqs(ji,jj)) &
+               &                      / ( pus(ji,jj)*pus(ji,jj) * ptha(ji,jj)*zqa )
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION One_on_L
+
+
+   FUNCTION psi_m_coare( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! ** Purpose: compute the universal profile stability function for momentum
+      !!             COARE 3.0, Fairall et al. 2003
+      !!             pzeta : stability paramenter, z/L where z is altitude
+      !!                     measurement and L is M-O length
+      !!       Stability function for wind speed and scalars matching Kansas and free
+      !!       convection forms with weighting f convective form, follows Fairall et
+      !!       al (1996) with profile constants from Grachev et al (2000) BLM stable
+      !!       form from Beljaars and Holtslag (1991)
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_m_coare
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp) :: zta, zphi_m, zphi_c, zpsi_k, zpsi_c, zf, zc, zstab
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zta = pzeta(ji,jj)
+            !
+            zphi_m = ABS(1. - 15.*zta)**.25    !!Kansas unstable
+            !
+            zpsi_k = 2.*LOG((1. + zphi_m)/2.) + LOG((1. + zphi_m*zphi_m)/2.)   &
+               & - 2.*ATAN(zphi_m) + 0.5*rpi
+            !
+            zphi_c = ABS(1. - 10.15*zta)**.3333                   !!Convective
+            !
+            zpsi_c = 1.5*LOG((1. + zphi_c + zphi_c*zphi_c)/3.) &
+               &     - 1.7320508*ATAN((1. + 2.*zphi_c)/1.7320508) + 1.813799447
+            !
+            zf = zta*zta
+            zf = zf/(1. + zf)
+            zc = MIN(50., 0.35*zta)
+            zstab = 0.5 + SIGN(0.5, zta)
+            !
+            psi_m_coare(ji,jj) = (1. - zstab) * ( (1. - zf)*zpsi_k + zf*zpsi_c ) & ! (zta < 0)
+               &                -   zstab     * ( 1. + 1.*zta     &                ! (zta > 0)
+               &                         + 0.6667*(zta - 14.28)/EXP(zc) + 8.525 )   !     "
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_m_coare
+
+
+   FUNCTION psi_h_coare( pzeta )
+      !!---------------------------------------------------------------------
+      !! Universal profile stability function for temperature and humidity
+      !! COARE 3.0, Fairall et al. 2003
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! Stability function for wind speed and scalars matching Kansas and free
+      !! convection forms with weighting f convective form, follows Fairall et
+      !! al (1996) with profile constants from Grachev et al (2000) BLM stable
+      !! form from Beljaars and Holtslag (1991)
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------
+      !!
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_h_coare
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) :: zta, zphi_h, zphi_c, zpsi_k, zpsi_c, zf, zc, zstab
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zta = pzeta(ji,jj)
+            !
+            zphi_h = (ABS(1. - 15.*zta))**.5  !! Kansas unstable   (zphi_h = zphi_m**2 when unstable, zphi_m when stable)
+            !
+            zpsi_k = 2.*LOG((1. + zphi_h)/2.)
+            !
+            zphi_c = (ABS(1. - 34.15*zta))**.3333   !! Convective
+            !
+            zpsi_c = 1.5*LOG((1. + zphi_c + zphi_c*zphi_c)/3.) &
+               &    -1.7320508*ATAN((1. + 2.*zphi_c)/1.7320508) + 1.813799447
+            !
+            zf = zta*zta
+            zf = zf/(1. + zf)
+            zc = MIN(50.,0.35*zta)
+            zstab = 0.5 + SIGN(0.5, zta)
+            !
+            psi_h_coare(ji,jj) = (1. - zstab) * ( (1. - zf)*zpsi_k + zf*zpsi_c ) &
+               &                -   zstab     * ( (ABS(1. + 2.*zta/3.))**1.5     &
+               &                           + .6667*(zta - 14.28)/EXP(zc) + 8.525 )
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_h_coare
+
+
+   FUNCTION visc_air( ptak )
+      !!---------------------------------------------------------------------
+      !! Air kinetic viscosity (m^2/s) given from temperature in degrees...
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!---------------------------------------------------------------------
+      !!
+      REAL(wp), DIMENSION(jpi,jpj) :: visc_air
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: ptak  ! air temperature in (K)
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::   ztc, ztc2      ! local scalar
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztc  = ptak(ji,jj) - rt0   ! air temp, in deg. C
+            ztc2 = ztc*ztc
+            visc_air(ji,jj) = 1.326E-5*(1. + 6.542E-3*ztc + 8.301E-6*ztc2 - 4.84E-9*ztc2*ztc)
+         END DO
+      END DO
+      !
+   END FUNCTION visc_air
+
+
+END MODULE sbcblk_algo_coare
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare3p5.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare3p5.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_coare3p5.F90	(revision 14097)
@@ -0,0 +1,417 @@
+MODULE sbcblk_algo_coare3p5
+   !!======================================================================
+   !!                       ***  MODULE  sbcblk_algo_coare3p5  ***
+   !! Computes turbulent components of surface fluxes
+   !!         according to Edson et al. 2013 (COARE v3.5) /JPO
+   !!
+   !!   * bulk transfer coefficients C_D, C_E and C_H
+   !!   * air temp. and spec. hum. adjusted from zt (2m) to zu (10m) if needed
+   !!   * the effective bulk wind speed at 10m U_blk
+   !!   => all these are used in bulk formulas in sbcblk.F90
+   !!
+   !!    Using the bulk formulation/param. of COARE v3.5, Edson et al. 2013
+   !!
+   !!
+   !!       Routine turb_coare3p5 maintained and developed in AeroBulk
+   !!                     (http://aerobulk.sourceforge.net/)
+   !!
+   !!            Author: Laurent Brodeau, 2016, brodeau@gmail.com
+   !!
+   !!======================================================================
+   !! History :  3.6  !  2016-02  (L.Brodeau)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   turb_coare3p5  : computes the bulk turbulent transfer coefficients
+   !!                   adjusts t_air and q_air from zt to zu m
+   !!                   returns the effective bulk wind speed at 10m
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbcwave, ONLY   :  cdn_wave ! wave module
+#if defined key_si3 || defined key_cice
+   USE sbc_ice         ! Surface boundary condition: ice fields
+#endif
+   !
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distribued memory computing library
+   USE in_out_manager  ! I/O manager
+   USE prtctl          ! Print control
+   USE lib_fortran     ! to use key_nosignedzero
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ::   TURB_COARE3P5   ! called by sbcblk.F90
+
+   !                                   ! COARE own values for given constants:
+   REAL(wp), PARAMETER ::   charn0_max =   0.028   ! value above which the Charnock paramter levels off for winds > 18
+   REAL(wp), PARAMETER ::   zi0        = 600.      ! scale height of the atmospheric boundary layer...1
+   REAL(wp), PARAMETER ::   Beta0      =   1.25    ! gustiness parameter
+   REAL(wp), PARAMETER ::   rctv0      =   0.608   ! constant to obtain virtual temperature...
+
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE turb_coare3p5( zt, zu, sst, t_zt, ssq, q_zt, U_zu,  &
+      &                      Cd, Ch, Ce, t_zu, q_zu, U_blk,       &
+      &                      Cdn, Chn, Cen                        )
+      !!----------------------------------------------------------------------------------
+      !!                      ***  ROUTINE  turb_coare3p5  ***
+      !!
+      !! ** Purpose :   Computes turbulent transfert coefficients of surface
+      !!                fluxes according to Fairall et al. (2003)
+      !!                If relevant (zt /= zu), adjust temperature and humidity from height zt to zu
+      !!
+      !! ** Method : Monin Obukhov Similarity Theory
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk) 
+      !!
+      !! INPUT :
+      !! -------
+      !!    *  zt   : height for temperature and spec. hum. of air            [m]
+      !!    *  zu   : height for wind speed (generally 10m)                   [m]
+      !!    *  U_zu : scalar wind speed at 10m                                [m/s]
+      !!    *  sst  : SST                                                     [K]
+      !!    *  t_zt : potential air temperature at zt                         [K]
+      !!    *  ssq  : specific humidity at saturation at SST                  [kg/kg]
+      !!    *  q_zt : specific humidity of air at zt                          [kg/kg]
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!    *  Cd     : drag coefficient
+      !!    *  Ch     : sensible heat coefficient
+      !!    *  Ce     : evaporation coefficient
+      !!    *  t_zu   : pot. air temperature adjusted at wind height zu       [K]
+      !!    *  q_zu   : specific humidity of air        //                    [kg/kg]
+      !!    *  U_blk  : bulk wind at 10m                                      [m/s]
+      !!
+      !!----------------------------------------------------------------------------------
+      REAL(wp), INTENT(in   )                     ::   zt       ! height for t_zt and q_zt                   [m]
+      REAL(wp), INTENT(in   )                     ::   zu       ! height for U_zu                              [m]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   sst      ! sea surface temperature              [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   t_zt     ! potential air temperature            [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   ssq      ! 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) ::   U_zu     ! 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)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ce       ! transfert coefficient for evaporation   (Q_lat)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   t_zu     ! pot. air temp. adjusted at zu             [K]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   q_zu     ! spec. humidity adjusted at zu             [kg/kg]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   U_blk    ! bulk wind at 10m                          [m/s]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Cdn, Chn, Cen ! neutral transfer coefficients
+      !
+      INTEGER :: j_itt
+      LOGICAL ::   l_zt_equal_zu = .FALSE.      ! if q and t are given at same height as U
+      INTEGER , PARAMETER ::   nb_itt = 4       ! number of itterations
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::  &
+         &  u_star, t_star, q_star, &
+         &  dt_zu, dq_zu,    &
+         &  znu_a,           & !: Nu_air, Viscosity of air
+         &  z0, z0t
+      REAL(wp), DIMENSION(jpi,jpj) ::   zeta_u        ! stability parameter at height zu
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztmp0, ztmp1, ztmp2
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   zeta_t        ! stability parameter at height zt
+      !!----------------------------------------------------------------------------------
+      !
+      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 )   ALLOCATE( zeta_t(jpi,jpj) )
+
+      !! First guess of temperature and humidity at height zu:
+      t_zu = MAX(t_zt , 0.0)    ! who knows what's given on masked-continental regions...
+      q_zu = MAX(q_zt , 1.E-6)  !               "
+
+      !! Pot. temp. difference (and we don't want it to be 0!)
+      dt_zu = t_zu - sst ;  dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+      dq_zu = q_zu - ssq ;  dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+
+      znu_a = visc_air(t_zt) ! Air viscosity (m^2/s) at zt given from temperature in (K)
+
+      ztmp2 = 0.5*0.5  ! initial guess for wind gustiness contribution
+      U_blk = SQRT(U_zu*U_zu + ztmp2)
+
+      ztmp2   = 10000.     ! optimization: ztmp2 == 1/z0 (with z0 first guess == 0.0001)
+      ztmp0   = LOG(zu*ztmp2)
+      ztmp1   = LOG(10.*ztmp2)
+      u_star = 0.035*U_blk*ztmp1/ztmp0       ! (u* = 0.035*Un10)
+
+      !! COARE 3.5 first guess of UN10 is U_zu
+      ztmp2 = MIN( 0.0017*U_zu - 0.005 , charn0_max)  ! alpha Charnock parameter (Eq. 13 Edson al. 2013)
+      ztmp2 = MAX( ztmp2 , 0. )                       ! alpha Charnock parameter (Eq. 13 Edson al. 2013)
+      z0     = ztmp2*u_star*u_star/grav + 0.11*znu_a/u_star
+      z0t    = 0.1*EXP(vkarmn/(0.00115/(vkarmn/ztmp1)))   !  WARNING: 1/z0t !
+
+      ztmp2  = vkarmn/ztmp0
+      Cd     = ztmp2*ztmp2    ! first guess of Cd
+
+      ztmp0 = vkarmn*vkarmn/LOG(zt*z0t)/Cd
+
+      !Ribcu = -zu/(zi0*0.004*Beta0**3) !! Saturation Rib, zi0 = tropicalbound. layer depth
+      ztmp2  = grav*zu*(dt_zu + rctv0*t_zu*dq_zu)/(t_zu*U_blk*U_blk)  !! Ribu Bulk Richardson number
+      ztmp1 = 0.5 + sign(0.5 , ztmp2)
+      ztmp0 = ztmp0*ztmp2
+      !!             Ribu < 0                                 Ribu > 0   Beta = 1.25
+      zeta_u = (1.-ztmp1) * (ztmp0/(1.+ztmp2/(-zu/(zi0*0.004*Beta0**3)))) &
+         &  +     ztmp1   * (ztmp0*(1. + 27./9.*ztmp2/ztmp0))
+
+      !! First guess M-O stability dependent scaling params.(u*,t*,q*) to estimate z0 and z/L
+      ztmp0  =  vkarmn/(LOG(zu*z0t) - psi_h_coare(zeta_u))
+
+      u_star = U_blk*vkarmn/(LOG(zu) - LOG(z0)  - psi_m_coare(zeta_u))
+      t_star = dt_zu*ztmp0
+      q_star = dq_zu*ztmp0
+
+      ! What's need to be done if zt /= zu:
+      IF( .NOT. l_zt_equal_zu ) THEN
+
+         zeta_t = zt*zeta_u/zu
+
+         !! First update of values at zu (or zt for wind)
+         ztmp0 = psi_h_coare(zeta_u) - psi_h_coare(zeta_t)
+         ztmp1 = log(zt/zu) + ztmp0
+         t_zu = t_zt - t_star/vkarmn*ztmp1
+         q_zu = q_zt - q_star/vkarmn*ztmp1
+         q_zu = (0.5 + sign(0.5,q_zu))*q_zu !Makes it impossible to have negative humidity :
+
+         dt_zu = t_zu - sst  ; dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+         dq_zu = q_zu - ssq  ; dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+
+      END IF
+
+      !! ITERATION BLOCK
+      DO j_itt = 1, nb_itt
+
+         !!Inverse of Monin-Obukov length (1/L) :
+         ztmp0 = One_on_L(t_zu, q_zu, u_star, t_star, q_star)  ! 1/L == 1/[Monin-Obukhov length]
+
+         ztmp1 = u_star*u_star   ! u*^2
+
+         !! Update wind at 10m taking into acount convection-related wind gustiness:
+         ! Ug = Beta*w*  (Beta = 1.25, Fairall et al. 2003, Eq.8):
+         ztmp2 = Beta0*Beta0*ztmp1*(MAX(-zi0*ztmp0/vkarmn,0.))**(2./3.)   ! => ztmp2 == Ug^2
+         !!   ! Only true when unstable (L<0) => when ztmp0 < 0 => explains "-" before 600.
+         U_blk = MAX(sqrt(U_zu*U_zu + ztmp2), 0.2)        ! include gustiness in bulk wind speed
+         ! => 0.2 prevents U_blk to be 0 in stable case when U_zu=0.
+
+         !! COARE 3.5: Charnock parameter is computed from the neutral wind speed at 10m: Eq. 13 (Edson al. 2013)
+         ztmp2 = u_star/vkarmn*LOG(10./z0)   ! UN10 Neutral wind at 10m!
+         ztmp2 = MIN( 0.0017*ztmp2 - 0.005 , charn0_max)  ! alpha Charnock parameter (Eq. 13 Edson al. 2013)
+         ztmp2 = MAX( ztmp2 , 0. )
+
+         !! Roughness lengthes z0, z0t (z0q = z0t) :
+         z0   = ztmp2*ztmp1/grav + 0.11*znu_a/u_star ! Roughness length (eq.6)
+         ztmp1 = z0*u_star/znu_a                             ! Re_r: roughness Reynolds number
+         !z0t  = MIN( 1.1E-4 , 5.5E-5*ztmp1**(-0.6) )   ! COARE 3.0
+         !! Chris Fairall and Jim Edsson, private communication, March 2016 / COARE 3.5 :
+         z0t   = MIN( 1.6e-4 , 5.8E-5*ztmp1**(-0.72)) ! These thermal roughness lengths give Stanton and
+         !z0q = z0t                                   ! Dalton numbers that closely approximate COARE3.0
+
+         !! Stability parameters:
+         zeta_u = zu*ztmp0 ; zeta_u = sign( min(abs(zeta_u),50.0), zeta_u )
+         IF( .NOT. l_zt_equal_zu ) THEN
+            zeta_t = zt*ztmp0 ;  zeta_t = sign( min(abs(zeta_t),50.0), zeta_t )
+         END IF
+
+         !! Turbulent scales at zu=10m :
+         ztmp0   = psi_h_coare(zeta_u)
+         ztmp1   = vkarmn/(LOG(zu) -LOG(z0t) - ztmp0)
+
+         t_star = dt_zu*ztmp1
+         q_star = dq_zu*ztmp1
+         u_star = U_blk*vkarmn/(LOG(zu) -LOG(z0) - psi_m_coare(zeta_u))
+
+         IF( .NOT. l_zt_equal_zu ) THEN
+            ! What's need to be done if zt /= zu
+            !! Re-updating temperature and humidity at zu :
+            ztmp2 = ztmp0 - psi_h_coare(zeta_t)
+            ztmp1 = log(zt/zu) + ztmp2
+            t_zu = t_zt - t_star/vkarmn*ztmp1
+            q_zu = q_zt - q_star/vkarmn*ztmp1
+            dt_zu = t_zu - sst ;  dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+            dq_zu = q_zu - ssq ;  dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+         END IF
+
+      END DO
+      !
+      ! compute transfer coefficients at zu :
+      ztmp0 = u_star/U_blk
+      Cd   = ztmp0*ztmp0
+      Ch   = ztmp0*t_star/dt_zu
+      Ce   = ztmp0*q_star/dq_zu
+      !
+      ztmp1 = zu + z0
+      Cdn = vkarmn*vkarmn / (log(ztmp1/z0 )*log(ztmp1/z0 ))
+      Chn = vkarmn*vkarmn / (log(ztmp1/z0t)*log(ztmp1/z0t))
+      Cen = Chn
+      !
+      IF( .NOT. l_zt_equal_zu ) DEALLOCATE( zeta_t )
+      !
+   END SUBROUTINE turb_coare3p5
+
+
+
+   FUNCTION One_on_L( ptha, pqa, pus, pts, pqs )
+      !!------------------------------------------------------------------------
+      !!
+      !! Evaluates the 1./(Monin Obukhov length) from air temperature and
+      !!  specific humidity, and frictional scales u*, t* and q*
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: One_on_L         !: 1./(Monin Obukhov length) [m^-1]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: ptha,  &  !: average potetntial air temperature [K]
+         &                                        pqa,   &  !: average specific humidity of air   [kg/kg]
+         &                                      pus, pts, pqs   !: frictional velocity, temperature and humidity
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::     zqa          ! local scalar
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zqa = (1. + rctv0*pqa(ji,jj))
+            !
+            One_on_L(ji,jj) =  grav*vkarmn*(pts(ji,jj)*zqa + rctv0*ptha(ji,jj)*pqs(ji,jj)) &
+               &                      / ( pus(ji,jj)*pus(ji,jj) * ptha(ji,jj)*zqa )
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION One_on_L
+
+
+   FUNCTION psi_m_coare( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! ** Purpose: compute the universal profile stability function for momentum
+      !!             COARE 3.0, Fairall et al. 2003
+      !!             pzeta : stability paramenter, z/L where z is altitude
+      !!                     measurement and L is M-O length
+      !!       Stability function for wind speed and scalars matching Kansas and free
+      !!       convection forms with weighting f convective form, follows Fairall et
+      !!       al (1996) with profile constants from Grachev et al (2000) BLM stable
+      !!       form from Beljaars and Holtslag (1991)
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_m_coare
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp) :: zta, zphi_m, zphi_c, zpsi_k, zpsi_c, zf, zc, zstab
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zta = pzeta(ji,jj)
+            !
+            zphi_m = ABS(1. - 15.*zta)**.25    !!Kansas unstable
+            !
+            zpsi_k = 2.*LOG((1. + zphi_m)/2.) + LOG((1. + zphi_m*zphi_m)/2.)   &
+               & - 2.*ATAN(zphi_m) + 0.5*rpi
+            !
+            zphi_c = ABS(1. - 10.15*zta)**.3333                   !!Convective
+            !
+            zpsi_c = 1.5*LOG((1. + zphi_c + zphi_c*zphi_c)/3.) &
+               &     - 1.7320508*ATAN((1. + 2.*zphi_c)/1.7320508) + 1.813799447
+            !
+            zf = zta*zta
+            zf = zf/(1. + zf)
+            zc = MIN(50., 0.35*zta)
+            zstab = 0.5 + SIGN(0.5, zta)
+            !
+            psi_m_coare(ji,jj) = (1. - zstab) * ( (1. - zf)*zpsi_k + zf*zpsi_c ) & ! (zta < 0)
+               &                -   zstab     * ( 1. + 1.*zta     &                ! (zta > 0)
+               &                         + 0.6667*(zta - 14.28)/EXP(zc) + 8.525 )   !     "
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_m_coare
+
+
+   FUNCTION psi_h_coare( pzeta )
+      !!---------------------------------------------------------------------
+      !! Universal profile stability function for temperature and humidity
+      !! COARE 3.0, Fairall et al. 2003
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! Stability function for wind speed and scalars matching Kansas and free
+      !! convection forms with weighting f convective form, follows Fairall et
+      !! al (1996) with profile constants from Grachev et al (2000) BLM stable
+      !! form from Beljaars and Holtslag (1991)
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------
+      !!
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_h_coare
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) :: zta, zphi_h, zphi_c, zpsi_k, zpsi_c, zf, zc, zstab
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zta = pzeta(ji,jj)
+            !
+            zphi_h = (ABS(1. - 15.*zta))**.5  !! Kansas unstable   (zphi_h = zphi_m**2 when unstable, zphi_m when stable)
+            !
+            zpsi_k = 2.*LOG((1. + zphi_h)/2.)
+            !
+            zphi_c = (ABS(1. - 34.15*zta))**.3333   !! Convective
+            !
+            zpsi_c = 1.5*LOG((1. + zphi_c + zphi_c*zphi_c)/3.) &
+               &    -1.7320508*ATAN((1. + 2.*zphi_c)/1.7320508) + 1.813799447
+            !
+            zf = zta*zta
+            zf = zf/(1. + zf)
+            zc = MIN(50.,0.35*zta)
+            zstab = 0.5 + SIGN(0.5, zta)
+            !
+            psi_h_coare(ji,jj) = (1. - zstab) * ( (1. - zf)*zpsi_k + zf*zpsi_c ) &
+               &                -   zstab     * ( (ABS(1. + 2.*zta/3.))**1.5     &
+               &                           + .6667*(zta - 14.28)/EXP(zc) + 8.525 )
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_h_coare
+
+
+   FUNCTION visc_air( ptak )
+      !!---------------------------------------------------------------------
+      !! Air kinetic viscosity (m^2/s) given from temperature in degrees...
+      !!
+      !! Author: L. Brodeau, june 2016 / AeroBulk
+      !!         (https://sourceforge.net/p/aerobulk)
+      !!---------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             ::   visc_air
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptak       ! air temperature   [K]
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::   ztc, ztc2      ! local scalar
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztc  = ptak(ji,jj) - rt0   ! air temp, in deg. C
+            ztc2 = ztc*ztc
+            visc_air(ji,jj) = 1.326E-5*(1. + 6.542E-3*ztc + 8.301E-6*ztc2 - 4.84E-9*ztc2*ztc)
+         END DO
+      END DO
+      !
+   END FUNCTION visc_air
+
+   !!======================================================================
+END MODULE sbcblk_algo_coare3p5
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ecmwf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ecmwf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ecmwf.F90	(revision 14097)
@@ -0,0 +1,427 @@
+MODULE sbcblk_algo_ecmwf
+   !!======================================================================
+   !!                       ***  MODULE  sbcblk_algo_ecmwf  ***
+   !! Computes turbulent components of surface fluxes
+   !!         according to the method in IFS of the ECMWF model
+   !!
+   !!   * bulk transfer coefficients C_D, C_E and C_H
+   !!   * air temp. and spec. hum. adjusted from zt (2m) to zu (10m) if needed
+   !!   * the effective bulk wind speed at 10m U_blk
+   !!   => all these are used in bulk formulas in sbcblk.F90
+   !!
+   !!    Using the bulk formulation/param. of IFS of ECMWF (cycle 31r2)
+   !!         based on IFS doc (avaible online on the ECMWF's website)
+   !!
+   !!
+   !!       Routine turb_ecmwf maintained and developed in AeroBulk
+   !!                     (http://aerobulk.sourceforge.net/)
+   !!
+   !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+   !!----------------------------------------------------------------------
+   !! History :  4.0  !  2016-02  (L.Brodeau)   Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   turb_ecmwf  : computes the bulk turbulent transfer coefficients
+   !!                   adjusts t_air and q_air from zt to zu m
+   !!                   returns the effective bulk wind speed at 10m
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distribued memory computing library
+   USE in_out_manager  ! I/O manager
+   USE prtctl          ! Print control
+   USE sbcwave, ONLY   :  cdn_wave ! wave module
+#if defined key_si3 || defined key_cice
+   USE sbc_ice         ! Surface boundary condition: ice fields
+#endif
+   USE lib_fortran     ! to use key_nosignedzero
+
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC ::   TURB_ECMWF   ! called by sbcblk.F90
+
+   !                   !! ECMWF own values for given constants, taken form IFS documentation...
+   REAL(wp), PARAMETER ::   charn0 = 0.018    ! Charnock constant (pretty high value here !!!
+   !                                          !    =>  Usually 0.011 for moderate winds)
+   REAL(wp), PARAMETER ::   zi0     = 1000.   ! scale height of the atmospheric boundary layer...1
+   REAL(wp), PARAMETER ::   Beta0    = 1.     ! gustiness parameter ( = 1.25 in COAREv3)
+   REAL(wp), PARAMETER ::   rctv0    = 0.608  ! constant to obtain virtual temperature...
+   REAL(wp), PARAMETER ::   Cp_dry = 1005.0   ! Specic heat of dry air, constant pressure      [J/K/kg]
+   REAL(wp), PARAMETER ::   Cp_vap = 1860.0   ! Specic heat of water vapor, constant pressure  [J/K/kg]
+   REAL(wp), PARAMETER ::   alpha_M = 0.11    ! For roughness length (smooth surface term)
+   REAL(wp), PARAMETER ::   alpha_H = 0.40    ! (Chapter 3, p.34, IFS doc Cy31r1)
+   REAL(wp), PARAMETER ::   alpha_Q = 0.62    !
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE TURB_ECMWF( zt, zu, sst, t_zt, ssq , q_zt , U_zu,   &
+      &                   Cd, Ch, Ce , t_zu, q_zu, U_blk,         &
+      &                   Cdn, Chn, Cen                           )
+      !!----------------------------------------------------------------------------------
+      !!                      ***  ROUTINE  turb_ecmwf  ***
+      !!
+      !!            2015: L. Brodeau (brodeau@gmail.com)
+      !!
+      !! ** Purpose :   Computes turbulent transfert coefficients of surface
+      !!                fluxes according to IFS doc. (cycle 31)
+      !!                If relevant (zt /= zu), adjust temperature and humidity from height zt to zu
+      !!
+      !! ** Method : Monin Obukhov Similarity Theory
+      !!
+      !! INPUT :
+      !! -------
+      !!    *  zt   : height for temperature and spec. hum. of air            [m]
+      !!    *  zu   : height for wind speed (generally 10m)                   [m]
+      !!    *  U_zu : scalar wind speed at 10m                                [m/s]
+      !!    *  sst  : SST                                                     [K]
+      !!    *  t_zt : potential air temperature at zt                         [K]
+      !!    *  ssq  : specific humidity at saturation at SST                  [kg/kg]
+      !!    *  q_zt : specific humidity of air at zt                          [kg/kg]
+      !!
+      !!
+      !! OUTPUT :
+      !! --------
+      !!    *  Cd     : drag coefficient
+      !!    *  Ch     : sensible heat coefficient
+      !!    *  Ce     : evaporation coefficient
+      !!    *  t_zu   : pot. air temperature adjusted at wind height zu       [K]
+      !!    *  q_zu   : specific humidity of air        //                    [kg/kg]
+      !!    *  U_blk  : bulk wind at 10m                                      [m/s]
+      !!
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), INTENT(in   )                     ::   zt       ! height for t_zt and q_zt                    [m]
+      REAL(wp), INTENT(in   )                     ::   zu       ! height for U_zu                             [m]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   sst      ! sea surface temperature                [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   t_zt     ! potential air temperature              [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   ssq      ! 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) ::   U_zu     ! 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)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ce       ! transfert coefficient for evaporation   (Q_lat)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   t_zu     ! pot. air temp. adjusted at zu               [K]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   q_zu     ! spec. humidity adjusted at zu           [kg/kg]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   U_blk    ! bulk wind at 10m                          [m/s]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Cdn, Chn, Cen ! neutral transfer coefficients
+      !
+      INTEGER :: j_itt
+      LOGICAL ::   l_zt_equal_zu = .FALSE.      ! if q and t are given at same height as U
+      INTEGER , PARAMETER ::   nb_itt = 4       ! number of itterations
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   u_star, t_star, q_star,   &
+         &  dt_zu, dq_zu,    &
+         &  znu_a,           & !: Nu_air, Viscosity of air
+         &  Linv,            & !: 1/L (inverse of Monin Obukhov length...
+         &  z0, z0t, z0q
+      REAL(wp), DIMENSION(jpi,jpj) ::   func_m, func_h
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztmp0, ztmp1, ztmp2
+      !!----------------------------------------------------------------------------------
+      !
+      ! Identical first gess as in COARE, with IFS parameter values though
+      !
+      l_zt_equal_zu = .FALSE.
+      IF( ABS(zu - zt) < 0.01 )   l_zt_equal_zu = .TRUE.    ! testing "zu == zt" is risky with double precision
+
+
+      !! First guess of temperature and humidity at height zu:
+      t_zu = MAX( t_zt , 0.0  )   ! who knows what's given on masked-continental regions...
+      q_zu = MAX( q_zt , 1.e-6)   !               "
+
+      !! Pot. temp. difference (and we don't want it to be 0!)
+      dt_zu = t_zu - sst   ;   dt_zu = SIGN( MAX(ABS(dt_zu),1.e-6), dt_zu )
+      dq_zu = q_zu - ssq   ;   dq_zu = SIGN( MAX(ABS(dq_zu),1.e-9), dq_zu )
+
+      znu_a = visc_air(t_zt) ! Air viscosity (m^2/s) at zt given from temperature in (K)
+
+      ztmp2 = 0.5 * 0.5  ! initial guess for wind gustiness contribution
+      U_blk = SQRT(U_zu*U_zu + ztmp2)
+
+      ! z0     = 0.0001
+      ztmp2   = 10000.     ! optimization: ztmp2 == 1/z0
+      ztmp0   = LOG(zu*ztmp2)
+      ztmp1   = LOG(10.*ztmp2)
+      u_star = 0.035*U_blk*ztmp1/ztmp0       ! (u* = 0.035*Un10)
+
+      z0     = charn0*u_star*u_star/grav + 0.11*znu_a/u_star
+      z0t    = 0.1*EXP(vkarmn/(0.00115/(vkarmn/ztmp1)))   !  WARNING: 1/z0t !
+
+      Cd     = (vkarmn/ztmp0)**2    ! first guess of Cd
+
+      ztmp0 = vkarmn*vkarmn/LOG(zt*z0t)/Cd
+
+      ztmp2 = Ri_bulk( zu, t_zu, dt_zu, q_zu, dq_zu, U_blk )   ! Ribu = Bulk Richardson number
+
+      !! First estimate of zeta_u, depending on the stability, ie sign of Ribu (ztmp2):
+      ztmp1 = 0.5 + SIGN( 0.5 , ztmp2 )
+      func_m = ztmp0*ztmp2 ! temporary array !!
+      !!             Ribu < 0                                 Ribu > 0   Beta = 1.25
+      func_h = (1.-ztmp1)*(func_m/(1.+ztmp2/(-zu/(zi0*0.004*Beta0**3)))) &  ! temporary array !!! func_h == zeta_u
+         &  +     ztmp1*(func_m*(1. + 27./9.*ztmp2/ztmp0))
+
+      !! First guess M-O stability dependent scaling params.(u*,t*,q*) to estimate z0 and z/L
+      ztmp0   =        vkarmn/(LOG(zu*z0t) - psi_h_ecmwf(func_h))
+
+      u_star = U_blk*vkarmn/(LOG(zu) - LOG(z0)  - psi_m_ecmwf(func_h))
+      t_star = dt_zu*ztmp0
+      q_star = dq_zu*ztmp0
+
+      ! What's need to be done if zt /= zu:
+      IF( .NOT. l_zt_equal_zu ) THEN
+         !
+         !! First update of values at zu (or zt for wind)
+         ztmp0 = psi_h_ecmwf(func_h) - psi_h_ecmwf(zt*func_h/zu)    ! zt*func_h/zu == zeta_t
+         ztmp1 = log(zt/zu) + ztmp0
+         t_zu = t_zt - t_star/vkarmn*ztmp1
+         q_zu = q_zt - q_star/vkarmn*ztmp1
+         q_zu = (0.5 + sign(0.5,q_zu))*q_zu !Makes it impossible to have negative humidity :
+
+         dt_zu = t_zu - sst  ; dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+         dq_zu = q_zu - ssq  ; dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+         !
+      ENDIF
+
+
+      !! => that was same first guess as in COARE...
+
+
+      !! First guess of inverse of Monin-Obukov length (1/L) :
+      ztmp0 = (1. + rctv0*q_zu)  ! the factor to apply to temp. to get virt. temp...
+      Linv  =  grav*vkarmn*(t_star*ztmp0 + rctv0*t_zu*q_star) / ( u_star*u_star * t_zu*ztmp0 )
+
+      !! Functions such as  u* = U_blk*vkarmn/func_m
+      ztmp1 = zu + z0
+      ztmp0 = ztmp1*Linv
+      func_m = LOG(ztmp1) -LOG(z0) - psi_m_ecmwf(ztmp0) + psi_m_ecmwf(z0*Linv)
+      func_h = LOG(ztmp1*z0t) - psi_h_ecmwf(ztmp0) + psi_h_ecmwf(1./z0t*Linv)
+
+
+      !! ITERATION BLOCK
+      !! ***************
+
+      DO j_itt = 1, nb_itt
+
+         !! Bulk Richardson Number at z=zu (Eq. 3.25)
+         ztmp0 = Ri_bulk(zu, t_zu, dt_zu, q_zu, dq_zu, U_blk)
+
+         !! New estimate of the inverse of the Monin-Obukhon length (Linv == zeta/zu) :
+         Linv = ztmp0*func_m*func_m/func_h / zu     ! From Eq. 3.23, Chap.3, p.33, IFS doc - Cy31r1
+
+         !! Update func_m with new Linv:
+         ztmp1 = zu + z0
+         func_m = LOG(ztmp1) -LOG(z0) - psi_m_ecmwf(ztmp1*Linv) + psi_m_ecmwf(z0*Linv)
+
+         !! Need to update roughness lengthes:
+         u_star = U_blk*vkarmn/func_m
+         ztmp2  = u_star*u_star
+         ztmp1  = znu_a/u_star
+         z0    = alpha_M*ztmp1 + charn0*ztmp2/grav
+         z0t    = alpha_H*ztmp1                              ! eq.3.26, Chap.3, p.34, IFS doc - Cy31r1
+         z0q    = alpha_Q*ztmp1
+
+         !! Update wind at 10m taking into acount convection-related wind gustiness:
+         ! Only true when unstable (L<0) => when ztmp0 < 0 => - !!!
+         ztmp2 = ztmp2 * (MAX(-zi0*Linv/vkarmn,0.))**(2./3.) ! => w*^2  (combining Eq. 3.8 and 3.18, hap.3, IFS doc - Cy31r1)
+         !! => equivalent using Beta=1 (gustiness parameter, 1.25 for COARE, also zi0=600 in COARE..)
+         U_blk = MAX(sqrt(U_zu*U_zu + ztmp2), 0.2)              ! eq.3.17, Chap.3, p.32, IFS doc - Cy31r1
+         ! => 0.2 prevents U_blk to be 0 in stable case when U_zu=0.
+
+
+         !! Need to update "theta" and "q" at zu in case they are given at different heights
+         !! as well the air-sea differences:
+         IF( .NOT. l_zt_equal_zu ) THEN
+
+            !! Arrays func_m and func_h are free for a while so using them as temporary arrays...
+            func_h = psi_h_ecmwf((zu+z0)*Linv) ! temporary array !!!
+            func_m = psi_h_ecmwf((zt+z0)*Linv) ! temporary array !!!
+
+            ztmp2  = psi_h_ecmwf(z0t*Linv)
+            ztmp0  = func_h - ztmp2
+            ztmp1  = vkarmn/(LOG(zu+z0) - LOG(z0t) - ztmp0)
+            t_star = dt_zu*ztmp1
+            ztmp2  = ztmp0 - func_m + ztmp2
+            ztmp1  = LOG(zt/zu) + ztmp2
+            t_zu   = t_zt - t_star/vkarmn*ztmp1
+
+            ztmp2  = psi_h_ecmwf(z0q*Linv)
+            ztmp0  = func_h - ztmp2
+            ztmp1  = vkarmn/(LOG(zu+z0) - LOG(z0q) - ztmp0)
+            q_star = dq_zu*ztmp1
+            ztmp2  = ztmp0 - func_m + ztmp2
+            ztmp1  = log(zt/zu) + ztmp2
+            q_zu   = q_zt - q_star/vkarmn*ztmp1
+
+            dt_zu = t_zu - sst ;  dt_zu = SIGN( MAX(ABS(dt_zu),1.E-6), dt_zu )
+            dq_zu = q_zu - ssq ;  dq_zu = SIGN( MAX(ABS(dq_zu),1.E-9), dq_zu )
+
+         END IF
+
+         !! Updating because of updated z0 and z0t and new Linv...
+         ztmp1 = zu + z0
+         ztmp0 = ztmp1*Linv
+         func_m = log(ztmp1) - LOG(z0 ) - psi_m_ecmwf(ztmp0) + psi_m_ecmwf(z0 *Linv)
+         func_h = log(ztmp1) - LOG(z0t) - psi_h_ecmwf(ztmp0) + psi_h_ecmwf(z0t*Linv)
+
+      END DO
+
+      Cd = vkarmn*vkarmn/(func_m*func_m)
+      Ch = vkarmn*vkarmn/(func_m*func_h)
+      ztmp1 = log((zu + z0)/z0q) - psi_h_ecmwf((zu + z0)*Linv) + psi_h_ecmwf(z0q*Linv)   ! func_q
+      Ce = vkarmn*vkarmn/(func_m*ztmp1)
+
+      ztmp1 = zu + z0
+      Cdn = vkarmn*vkarmn / (log(ztmp1/z0 )*log(ztmp1/z0 ))
+      Chn = vkarmn*vkarmn / (log(ztmp1/z0t)*log(ztmp1/z0t))
+      Cen = vkarmn*vkarmn / (log(ztmp1/z0q)*log(ztmp1/z0q))
+
+   END SUBROUTINE TURB_ECMWF
+
+
+   FUNCTION psi_m_ecmwf( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! Universal profile stability function for momentum
+      !!     ECMWF / as in IFS cy31r1 documentation, available online
+      !!     at ecmwf.int
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_m_ecmwf
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp) :: zzeta, zx, ztmp, psi_unst, psi_stab, stab
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zzeta = MIN( pzeta(ji,jj) , 5. ) !! Very stable conditions (L positif and big!):
+            !
+            ! Unstable (Paulson 1970):
+            !   eq.3.20, Chap.3, p.33, IFS doc - Cy31r1
+            zx = SQRT(ABS(1. - 16.*zzeta))
+            ztmp = 1. + SQRT(zx)
+            ztmp = ztmp*ztmp
+            psi_unst = LOG( 0.125*ztmp*(1. + zx) )   &
+               &       -2.*ATAN( SQRT(zx) ) + 0.5*rpi
+            !
+            ! Unstable:
+            ! eq.3.22, Chap.3, p.33, IFS doc - Cy31r1
+            psi_stab = -2./3.*(zzeta - 5./0.35)*EXP(-0.35*zzeta) &
+               &       - zzeta - 2./3.*5./0.35
+            !
+            ! Combining:
+            stab = 0.5 + SIGN(0.5, zzeta) ! zzeta > 0 => stab = 1
+            !
+            psi_m_ecmwf(ji,jj) = (1. - stab) * psi_unst & ! (zzeta < 0) Unstable
+               &                +      stab  * psi_stab   ! (zzeta > 0) Stable
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_m_ecmwf
+
+   
+   FUNCTION psi_h_ecmwf( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! Universal profile stability function for temperature and humidity
+      !!     ECMWF / as in IFS cy31r1 documentation, available online
+      !!     at ecmwf.int
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_h_ecmwf
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) ::  zzeta, zx, psi_unst, psi_stab, stab
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zzeta = MIN(pzeta(ji,jj) , 5.)   ! Very stable conditions (L positif and big!):
+            !
+            zx  = ABS(1. - 16.*zzeta)**.25        ! this is actually (1/phi_m)**2  !!!
+            !                                     ! eq.3.19, Chap.3, p.33, IFS doc - Cy31r1
+            ! Unstable (Paulson 1970) :
+            psi_unst = 2.*LOG(0.5*(1. + zx*zx))   ! eq.3.20, Chap.3, p.33, IFS doc - Cy31r1
+            !
+            ! Stable:
+            psi_stab = -2./3.*(zzeta - 5./0.35)*EXP(-0.35*zzeta) & ! eq.3.22, Chap.3, p.33, IFS doc - Cy31r1
+               &       - ABS(1. + 2./3.*zzeta)**1.5 - 2./3.*5./0.35 + 1. 
+            ! LB: added ABS() to avoid NaN values when unstable, which contaminates the unstable solution...
+            !
+            stab = 0.5 + SIGN(0.5, zzeta) ! zzeta > 0 => stab = 1
+            !
+            !
+            psi_h_ecmwf(ji,jj) = (1. - stab) * psi_unst &   ! (zzeta < 0) Unstable
+               &                +    stab    * psi_stab     ! (zzeta > 0) Stable
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION psi_h_ecmwf
+
+
+   FUNCTION Ri_bulk( pz, ptz, pdt, pqz, pdq, pub )
+      !!----------------------------------------------------------------------------------
+      !! Bulk Richardson number (Eq. 3.25 IFS doc)
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) ::   Ri_bulk   !
+      !
+      REAL(wp)                    , INTENT(in) ::   pz    ! height above the sea        [m]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptz   ! air temperature at pz m     [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pdt   ! ptz - sst                   [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pqz   ! air temperature at pz m [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pdq   ! pqz - ssq               [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pub   ! bulk wind speed           [m/s]
+      !!----------------------------------------------------------------------------------
+      !
+      Ri_bulk =   grav*pz/(pub*pub)                                          &
+         &      * ( pdt/(ptz - 0.5_wp*(pdt + grav*pz/(Cp_dry+Cp_vap*pqz)))   &
+         &          + rctv0*pdq )
+      !
+   END FUNCTION Ri_bulk
+
+
+   FUNCTION visc_air(ptak)
+      !!----------------------------------------------------------------------------------
+      !! Air kinetic viscosity (m^2/s) given from temperature in degrees...
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://sourceforge.net/p/aerobulk)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             ::   visc_air   !
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   ptak       ! air temperature in (K)
+      !
+      INTEGER  ::   ji, jj      ! dummy loop indices
+      REAL(wp) ::   ztc, ztc2   ! local scalar
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztc  = ptak(ji,jj) - rt0   ! air temp, in deg. C
+            ztc2 = ztc*ztc
+            visc_air(ji,jj) = 1.326e-5*(1. + 6.542E-3*ztc + 8.301e-6*ztc2 - 4.84e-9*ztc2*ztc)
+         END DO
+      END DO
+      !
+   END FUNCTION visc_air
+
+   !!======================================================================
+END MODULE sbcblk_algo_ecmwf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ncar.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ncar.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcblk_algo_ncar.F90	(revision 14097)
@@ -0,0 +1,431 @@
+MODULE sbcblk_algo_ncar
+   !!======================================================================
+   !!                   ***  MODULE  sbcblk_algo_ncar  ***
+   !! Computes:
+   !!   * bulk transfer coefficients C_D, C_E and C_H
+   !!   * air temp. and spec. hum. adjusted from zt (2m) to zu (10m) if needed
+   !!   * the effective bulk wind speed at 10m U_blk
+   !!   => all these are used in bulk formulas in sbcblk.F90
+   !!
+   !!    Using the bulk formulation/param. of Large & Yeager 2008
+   !!
+   !!       Routine turb_ncar maintained and developed in AeroBulk
+   !!                     (https://github.com/brodeau/aerobulk/)
+   !!
+   !!                         L. Brodeau, 2020
+   !!=====================================================================
+   !! History :  4.0  !  2020-06  (L.Brodeau) successor of old turb_ncar of former sbcblk_core.F90
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   turb_ncar  : computes the bulk turbulent transfer coefficients
+   !!                   adjusts t_air and q_air from zt to zu m
+   !!                   returns the effective bulk wind speed at 10m
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbcwave, ONLY   :  cdn_wave ! wave module
+#if defined key_si3 || defined key_cice
+   USE sbc_ice         ! Surface boundary condition: ice fields
+#endif
+   !
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distribued memory computing library
+   USE in_out_manager  ! I/O manager
+   USE prtctl          ! Print control
+   USE lib_fortran     ! to use key_nosignedzero
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC :: TURB_NCAR   ! called by sbcblk.F90
+
+   !                              ! NCAR own values for given constants:
+   REAL(wp), PARAMETER ::   rctv0 = 0.608   ! constant to obtain virtual temperature...
+
+   INTEGER , PARAMETER ::   nb_itt = 4       ! number of itterations
+
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE turb_ncar( zt, zu, sst, t_zt, ssq, q_zt, U_zu, &
+      &                  Cd, Ch, Ce, t_zu, q_zu, Ub,         &
+      &                  CdN, ChN, CeN                       )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE  turb_ncar  ***
+      !!
+      !! ** Purpose :   Computes turbulent transfert coefficients of surface
+      !!                fluxes according to Large & Yeager (2004) and Large & Yeager (2008)
+      !!                If relevant (zt /= zu), adjust temperature and humidity from height zt to zu
+      !!                Returns the effective bulk wind speed at zu to be used in the bulk formulas
+      !!
+      !! INPUT :
+      !! -------
+      !!    *  zt   : height for temperature and spec. hum. of air            [m]
+      !!    *  zu   : height for wind speed (usually 10m)                     [m]
+      !!    *  sst  : bulk SST                                                [K]
+      !!    *  t_zt : potential air temperature at zt                         [K]
+      !!    *  ssq  : specific humidity at saturation at SST                  [kg/kg]
+      !!    *  q_zt : specific humidity of air at zt                          [kg/kg]
+      !!    *  U_zu : scalar wind speed at zu                                 [m/s]
+      !!
+      !! OUTPUT :
+      !! --------
+      !!    *  Cd     : drag coefficient
+      !!    *  Ch     : sensible heat coefficient
+      !!    *  Ce     : evaporation coefficient
+      !!    *  t_zu   : pot. air temperature adjusted at wind height zu       [K]
+      !!    *  q_zu   : specific humidity of air        //                    [kg/kg]
+      !!    *  Ub  : bulk wind speed at zu                                 [m/s]
+      !!
+      !! ** Author: L. Brodeau, June 2019 / AeroBulk (https://github.com/brodeau/aerobulk/)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), INTENT(in   )                     ::   zt       ! height for t_zt and q_zt                    [m]
+      REAL(wp), INTENT(in   )                     ::   zu       ! height for U_zu                             [m]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   sst      ! sea surface temperature                [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   t_zt     ! potential air temperature              [Kelvin]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   ssq      ! sea surface specific humidity           [kg/kg]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   q_zt     ! specific air humidity at zt             [kg/kg]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   U_zu     ! 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)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ce       ! transfert coefficient for evaporation   (Q_lat)
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   t_zu     ! pot. air temp. adjusted at zu               [K]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   q_zu     ! spec. humidity adjusted at zu           [kg/kg]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ub    ! bulk wind speed at zu                     [m/s]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   CdN, ChN, CeN ! neutral transfer coefficients
+      !
+      INTEGER :: j_itt
+      LOGICAL :: l_zt_equal_zu = .FALSE.      ! if q and t are given at same height as U
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   Cx_n10        ! 10m neutral latent/sensible coefficient
+      REAL(wp), DIMENSION(jpi,jpj) ::   sqrtCdN10   ! root square of Cd_n10
+      REAL(wp), DIMENSION(jpi,jpj) ::   zeta_u        ! stability parameter at height zu
+      REAL(wp), DIMENSION(jpi,jpj) ::   zpsi_h_u
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztmp0, ztmp1, ztmp2
+      REAL(wp), DIMENSION(jpi,jpj) ::   sqrtCd
+      !!----------------------------------------------------------------------------------
+
+      l_zt_equal_zu = ( ABS(zu - zt) < 0.01_wp )
+
+      Ub = MAX( 0.5_wp , U_zu )   !  relative wind speed at zu (normally 10m), we don't want to fall under 0.5 m/s
+
+      !! Neutral drag coefficient at zu:
+      IF( ln_cdgw ) THEN      ! wave drag case
+         CdN = MAX( cdn_wave(:,:) + rsmall * ( 1._wp - tmask(:,:,1) ) , 0.1E-3_wp )
+      ELSE
+         CdN = CD_N10_NCAR( Ub )
+      ENDIF
+      sqrtCdN10 = SQRT( CdN )
+
+      !! Initializing transf. coeff. with their first guess neutral equivalents :
+      Cd = CdN
+      Ce = CE_N10_NCAR( sqrtCdN10 )
+      ztmp0 = 0.5_wp + SIGN(0.5_wp, virt_temp(t_zt, q_zt) - virt_temp(sst, ssq)) ! we guess stability based on delta of virt. pot. temp.
+      Ch = CH_N10_NCAR( sqrtCdN10 , ztmp0 )
+      sqrtCd = sqrtCdN10
+
+      !! Initializing values at z_u with z_t values:
+      t_zu = t_zt
+      q_zu = q_zt
+
+      !! ITERATION BLOCK
+      DO j_itt = 1, nb_itt
+         !
+         ztmp1 = t_zu - sst   ! Updating air/sea differences
+         ztmp2 = q_zu - ssq
+
+         ! Updating turbulent scales :   (L&Y 2004 Eq. (7))
+         ztmp0 = sqrtCd*Ub          ! u*
+         ztmp1 = Ch/sqrtCd*ztmp1    ! theta*
+         ztmp2 = Ce/sqrtCd*ztmp2    ! q*
+
+         ! Estimate the inverse of Obukov length (1/L) at height zu:
+         ztmp0 = One_on_L( t_zu, q_zu, ztmp0, ztmp1, ztmp2 )
+
+         !! Stability parameters :
+         zeta_u   = zu*ztmp0
+         zeta_u   = sign( min(abs(zeta_u),10._wp), zeta_u )
+
+         !! Shifting temperature and humidity at zu (L&Y 2004 Eq. (9b-9c))
+         IF( .NOT. l_zt_equal_zu ) THEN
+            ztmp0 = zt*ztmp0 ! zeta_t !
+            ztmp0 = SIGN( MIN(ABS(ztmp0),10._wp), ztmp0 )  ! Temporaty array ztmp0 == zeta_t !!!
+            ztmp0 = LOG(zt/zu) + psi_h_ncar(zeta_u) - psi_h_ncar(ztmp0)                   ! ztmp0 just used as temp array again!
+            t_zu = t_zt - ztmp1/vkarmn*ztmp0    ! ztmp1 is still theta*  L&Y 2004 Eq. (9b)
+            !!
+            q_zu = q_zt - ztmp2/vkarmn*ztmp0    ! ztmp2 is still q*      L&Y 2004 Eq. (9c)
+            q_zu = MAX(0._wp, q_zu)
+         END IF
+
+         ! 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.
+         ztmp2 = psi_m_ncar(zeta_u)
+         ztmp0 = MAX( 0.25_wp , UN10_from_CD(zu, Ub, Cd, ppsi=ztmp2) ) ! U_n10 (ztmp2 == psi_m_ncar(zeta_u))
+
+         IF( ln_cdgw ) THEN      ! wave drag case
+            CdN = MAX( cdn_wave(:,:) + rsmall * ( 1._wp - tmask(:,:,1) ) , 0.1E-3_wp )
+         ELSE
+            CdN   = CD_N10_NCAR(ztmp0)                                       ! Cd_n10
+         END IF
+         sqrtCdN10 = SQRT(CdN)
+
+         !! Update of transfer coefficients:
+         ztmp1  = 1._wp + sqrtCdN10/vkarmn*(LOG(zu/10._wp) - ztmp2)   ! L&Y 2004 Eq. (10a) (ztmp2 == psi_m(zeta_u))
+         Cd     = MAX( CdN / ( ztmp1*ztmp1 ) , 0.1E-3_wp )
+         sqrtCd = SQRT( Cd )
+
+         ztmp0  = ( LOG(zu/10._wp) - psi_h_ncar(zeta_u) ) / vkarmn / sqrtCdN10
+         ztmp2  = sqrtCd / sqrtCdN10
+
+         ztmp1  = 0.5_wp + sign(0.5_wp,zeta_u) ! stability flag
+         ChN    = CH_N10_NCAR( sqrtCdN10 , ztmp1 )
+         ztmp1  = 1._wp + ChN*ztmp0
+         Ch     = MAX( ChN*ztmp2 / ztmp1 , 0.1E-3_wp )   ! L&Y 2004 Eq. (10b)
+
+         CeN = CE_N10_NCAR( sqrtCdN10 )
+         ztmp1  = 1._wp + CeN*ztmp0
+         Ce     = MAX( CeN*ztmp2 / ztmp1 , 0.1E-3_wp )  ! L&Y 2004 Eq. (10c)
+
+      END DO !DO j_itt = 1, nb_itt
+
+   END SUBROUTINE turb_ncar
+
+
+   FUNCTION CD_N10_NCAR( pw10 )
+      !!----------------------------------------------------------------------------------
+      !! Estimate of the neutral drag coefficient at 10m as a function
+      !! of neutral wind  speed at 10m
+      !!
+      !! Origin: Large & Yeager 2008, Eq. (11)
+      !!
+      !! ** Author: L. Brodeau, june 2016 / AeroBulk (https://github.com/brodeau/aerobulk/)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pw10           ! scalar wind speed at 10m (m/s)
+      REAL(wp), DIMENSION(jpi,jpj)             :: CD_N10_NCAR
+      !
+      INTEGER  ::     ji, jj     ! dummy loop indices
+      REAL(wp) :: zgt33, zw, zw6 ! local scalars
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zw  = pw10(ji,jj)
+            zw6 = zw*zw*zw
+            zw6 = zw6*zw6
+            !
+            ! When wind speed > 33 m/s => Cyclone conditions => special treatment
+            zgt33 = 0.5_wp + SIGN( 0.5_wp, (zw - 33._wp) )   ! If pw10 < 33. => 0, else => 1
+            !
+            CD_N10_NCAR(ji,jj) = 1.e-3_wp * ( &
+               &       (1._wp - zgt33)*( 2.7_wp/zw + 0.142_wp + zw/13.09_wp - 3.14807E-10_wp*zw6) & ! wind <  33 m/s
+               &      +    zgt33   *      2.34_wp )                                                 ! wind >= 33 m/s
+            !
+            CD_N10_NCAR(ji,jj) = MAX( CD_N10_NCAR(ji,jj), 0.1E-3_wp )
+            !
+         END DO
+      END DO
+      !
+   END FUNCTION CD_N10_NCAR
+
+
+
+   FUNCTION CH_N10_NCAR( psqrtcdn10 , pstab )
+      !!----------------------------------------------------------------------------------
+      !! Estimate of the neutral heat transfer coefficient at 10m      !!
+      !! Origin: Large & Yeager 2008, Eq. (9) and (12)
+
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: ch_n10_ncar
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: psqrtcdn10 ! sqrt( CdN10 )
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pstab      ! stable ABL => 1 / unstable ABL => 0
+      !!----------------------------------------------------------------------------------
+      !
+      ch_n10_ncar = MAX( 1.e-3_wp * psqrtcdn10*( 18._wp*pstab + 32.7_wp*(1._wp - pstab) )  , 0.1E-3_wp )   ! Eq. (9) & (12) Large & Yeager, 2008
+      !
+   END FUNCTION CH_N10_NCAR
+
+   FUNCTION CE_N10_NCAR( psqrtcdn10 )
+      !!----------------------------------------------------------------------------------
+      !! Estimate of the neutral heat transfer coefficient at 10m      !!
+      !! Origin: Large & Yeager 2008, Eq. (9) and (13)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: ce_n10_ncar
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: psqrtcdn10 ! sqrt( CdN10 )
+      !!----------------------------------------------------------------------------------
+      ce_n10_ncar = MAX( 1.e-3_wp * ( 34.6_wp * psqrtcdn10 ) , 0.1E-3_wp )
+      !
+   END FUNCTION CE_N10_NCAR
+
+
+   FUNCTION psi_m_ncar( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! Universal profile stability function for momentum
+      !!    !! Psis, L&Y 2004, Eq. (8c), (8d), (8e)
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! ** Author: L. Brodeau, June 2016 / AeroBulk (https://github.com/brodeau/aerobulk/)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_m_ncar
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp) :: zzeta, zx2, zx, zpsi_unst, zpsi_stab,  zstab   ! local scalars
+      !!----------------------------------------------------------------------------------
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+
+            zzeta = pzeta(ji,jj)
+            !
+            zx2 = SQRT( ABS(1._wp - 16._wp*zzeta) )  ! (1 - 16z)^0.5
+            zx2 = MAX( zx2 , 1._wp )
+            zx  = SQRT(zx2)                          ! (1 - 16z)^0.25
+            zpsi_unst = 2._wp*LOG( (1._wp + zx )*0.5_wp )   &
+               &            + LOG( (1._wp + zx2)*0.5_wp )   &
+               &          - 2._wp*ATAN(zx) + rpi*0.5_wp
+            !
+            zpsi_stab = -5._wp*zzeta
+            !
+            zstab = 0.5_wp + SIGN(0.5_wp, zzeta) ! zzeta > 0 => zstab = 1
+            !
+            psi_m_ncar(ji,jj) =          zstab  * zpsi_stab &  ! (zzeta > 0) Stable
+               &              + (1._wp - zstab) * zpsi_unst    ! (zzeta < 0) Unstable
+            !
+         END DO
+      END DO
+   END FUNCTION psi_m_ncar
+
+
+   FUNCTION psi_h_ncar( pzeta )
+      !!----------------------------------------------------------------------------------
+      !! Universal profile stability function for temperature and humidity
+      !!    !! Psis, L&Y 2004, Eq. (8c), (8d), (8e)
+      !!
+      !! pzeta : stability paramenter, z/L where z is altitude measurement
+      !!         and L is M-O length
+      !!
+      !! ** Author: L. Brodeau, June 2016 / AeroBulk (https://github.com/brodeau/aerobulk/)
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) :: psi_h_ncar
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pzeta
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) :: zzeta, zx2, zpsi_unst, zpsi_stab, zstab  ! local scalars
+      !!----------------------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zzeta = pzeta(ji,jj)
+            !
+            zx2 = SQRT( ABS(1._wp - 16._wp*zzeta) )  ! (1 -16z)^0.5
+            zx2 = MAX( zx2 , 1._wp )
+            zpsi_unst = 2._wp*LOG( 0.5_wp*(1._wp + zx2) )
+            !
+            zpsi_stab = -5._wp*zzeta
+            !
+            zstab = 0.5_wp + SIGN(0.5_wp, zzeta) ! zzeta > 0 => zstab = 1
+            !
+            psi_h_ncar(ji,jj) =          zstab  * zpsi_stab &  ! (zzeta > 0) Stable
+               &              + (1._wp - zstab) * zpsi_unst    ! (zzeta < 0) Unstable
+            !
+         END DO
+      END DO
+   END FUNCTION psi_h_ncar
+
+
+
+
+   FUNCTION UN10_from_CD( pzu, pUb, pCd, ppsi )
+      !!----------------------------------------------------------------------------------
+      !!  Provides the neutral-stability wind speed at 10 m
+      !!----------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: UN10_from_CD  !: [m/s]
+      REAL(wp),                     INTENT(in) :: pzu  !: measurement heigh of bulk wind speed
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pUb  !: bulk wind speed at height pzu m   [m/s]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pCd  !: drag coefficient
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: ppsi !: "Psi_m(pzu/L)" stability correction profile for momentum []
+      !!----------------------------------------------------------------------------------
+      !! Reminder: UN10 = u*/vkarmn * log(10/z0)
+      !!     and: u* = sqrt(Cd) * Ub
+      !!                                  u*/vkarmn * log(   10   /       z0    )
+      UN10_from_CD(:,:) = SQRT(pCd(:,:))*pUb/vkarmn * LOG( 10._wp / z0_from_Cd( pzu, pCd(:,:), ppsi=ppsi(:,:) ) )
+      !!
+   END FUNCTION UN10_from_CD
+
+
+   FUNCTION One_on_L( ptha, pqa, pus, pts, pqs )
+      !!------------------------------------------------------------------------
+      !!
+      !! Evaluates the 1./(Obukhov length) from air temperature,
+      !! air specific humidity, and frictional scales u*, t* and q*
+      !!
+      !! Author: L. Brodeau, June 2019 / AeroBulk
+      !!         (https://github.com/brodeau/aerobulk/)
+      !!------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj)             :: One_on_L     !: 1./(Obukhov length) [m^-1]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: ptha         !: reference potential temperature of air [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pqa          !: reference specific humidity of air   [kg/kg]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pus          !: u*: friction velocity [m/s]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pts, pqs     !: \theta* and q* friction aka turb. scales for temp. and spec. hum.
+      !
+      INTEGER  ::   ji, jj         ! dummy loop indices
+      REAL(wp) ::     zqa          ! local scalar
+      !!-------------------------------------------------------------------
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zqa = (1._wp + rctv0*pqa(ji,jj))
+            !
+            ! The main concern is to know whether, the vertical turbulent flux of virtual temperature, < u' theta_v' > is estimated with:
+            !  a/  -u* [ theta* (1 + 0.61 q) + 0.61 theta q* ] => this is the one that seems correct! chose this one!
+            !                      or
+            !  b/  -u* [ theta*              + 0.61 theta q* ]
+            !
+            One_on_L(ji,jj) = grav*vkarmn*( pts(ji,jj)*zqa + rctv0*ptha(ji,jj)*pqs(ji,jj) ) &
+               &               / MAX( pus(ji,jj)*pus(ji,jj)*ptha(ji,jj)*zqa , 1.E-9_wp )
+            !
+         END DO
+      END DO
+      !
+      One_on_L = SIGN( MIN(ABS(One_on_L),200._wp), One_on_L ) ! (prevent FPE from stupid values over masked regions...)
+      !
+   END FUNCTION One_on_L
+
+
+   FUNCTION z0_from_Cd( pzu, pCd,  ppsi )
+      REAL(wp), DIMENSION(jpi,jpj) :: z0_from_Cd        !: roughness length [m]
+      REAL(wp)                    , INTENT(in) :: pzu   !: reference height zu [m]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pCd   !: (neutral or non-neutral) drag coefficient []
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in), OPTIONAL :: ppsi !: "Psi_m(pzu/L)" stability correction profile for momentum []
+      !!
+      !! If pCd is the NEUTRAL-STABILITY drag coefficient then ppsi must be 0 or not given
+      !! If pCd is the drag coefficient (in stable or unstable conditions) then pssi must be provided
+      !!----------------------------------------------------------------------------------
+      IF ( PRESENT(ppsi) ) THEN
+         !! Cd provided is the actual Cd (not the neutral-stability CdN) :
+         z0_from_Cd = pzu * EXP( - ( vkarmn/SQRT(pCd(:,:)) + ppsi(:,:) ) ) !LB: ok, double-checked!
+      ELSE
+         !! Cd provided is the neutral-stability Cd, aka CdN :
+         z0_from_Cd = pzu * EXP( - vkarmn/SQRT(pCd(:,:)) )            !LB: ok, double-checked!
+      END IF
+   END FUNCTION z0_from_Cd
+
+   FUNCTION virt_temp( pta, pqa )
+      REAL(wp), DIMENSION(jpi,jpj)             :: virt_temp !: virtual temperature [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pta !: absolute or potential air temperature [K]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pqa !: specific humidity of air   [kg/kg]
+      virt_temp(:,:) = pta(:,:) * (1._wp + rctv0*pqa(:,:))
+   END FUNCTION virt_temp
+
+   !!======================================================================
+END MODULE sbcblk_algo_ncar
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbccpl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbccpl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbccpl.F90	(revision 14097)
@@ -0,0 +1,2684 @@
+MODULE sbccpl
+   !!======================================================================
+   !!                       ***  MODULE  sbccpl  ***
+   !! Surface Boundary Condition :  momentum, heat and freshwater fluxes in coupled mode
+   !!======================================================================
+   !! History :  2.0  ! 2007-06  (R. Redler, N. Keenlyside, W. Park) Original code split into flxmod & taumod
+   !!            3.0  ! 2008-02  (G. Madec, C Talandier)  surface module
+   !!            3.1  ! 2009_02  (G. Madec, S. Masson, E. Maisonave, A. Caubel) generic coupled interface
+   !!            3.4  ! 2011_11  (C. Harris) more flexibility + multi-category fields
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   namsbc_cpl      : coupled formulation namlist
+   !!   sbc_cpl_init    : initialisation of the coupled exchanges
+   !!   sbc_cpl_rcv     : receive fields from the atmosphere over the ocean (ocean only)
+   !!                     receive stress from the atmosphere over the ocean (ocean-ice case)
+   !!   sbc_cpl_ice_tau : receive stress from the atmosphere over ice
+   !!   sbc_cpl_ice_flx : receive fluxes from the atmosphere over ice
+   !!   sbc_cpl_snd     : send     fields to the atmosphere
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE trc_oce         ! share SMS/Ocean variables
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE sbcapr          ! Stochastic param. : ???
+   USE sbcdcy          ! surface boundary condition: diurnal cycle
+   USE sbcwave         ! surface boundary condition: waves
+   USE phycst          ! physical constants
+#if defined key_si3
+   USE ice            ! ice variables
+#endif
+   USE cpl_oasis3     ! OASIS3 coupling
+   USE geo2ocean      ! 
+   USE oce     , ONLY : tsn, un, vn, sshn, ub, vb, sshb, fraqsr_1lev
+   USE ocealb         ! 
+   USE eosbn2         ! 
+   USE sbcrnf  , ONLY : l_rnfcpl
+   USE sbcisf  , ONLY : l_isfcpl
+#if defined key_cice
+   USE ice_domain_size, only: ncat
+#endif
+#if defined key_si3
+   USE icevar         ! for CALL ice_var_snwblow
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! NetCDF library
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+#if defined key_oasis3 
+   USE mod_oasis, ONLY : OASIS_Sent, OASIS_ToRest, OASIS_SentOut, OASIS_ToRestOut 
+#endif 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_cpl_init      ! routine called by sbcmod.F90
+   PUBLIC   sbc_cpl_rcv       ! routine called by icestp.F90
+   PUBLIC   sbc_cpl_snd       ! routine called by step.F90
+   PUBLIC   sbc_cpl_ice_tau   ! routine called by icestp.F90
+   PUBLIC   sbc_cpl_ice_flx   ! routine called by icestp.F90
+   PUBLIC   sbc_cpl_alloc     ! routine called in sbcice_cice.F90
+
+   INTEGER, PARAMETER ::   jpr_otx1   =  1   ! 3 atmosphere-ocean stress components on grid 1
+   INTEGER, PARAMETER ::   jpr_oty1   =  2   ! 
+   INTEGER, PARAMETER ::   jpr_otz1   =  3   ! 
+   INTEGER, PARAMETER ::   jpr_otx2   =  4   ! 3 atmosphere-ocean stress components on grid 2
+   INTEGER, PARAMETER ::   jpr_oty2   =  5   ! 
+   INTEGER, PARAMETER ::   jpr_otz2   =  6   ! 
+   INTEGER, PARAMETER ::   jpr_itx1   =  7   ! 3 atmosphere-ice   stress components on grid 1
+   INTEGER, PARAMETER ::   jpr_ity1   =  8   ! 
+   INTEGER, PARAMETER ::   jpr_itz1   =  9   ! 
+   INTEGER, PARAMETER ::   jpr_itx2   = 10   ! 3 atmosphere-ice   stress components on grid 2
+   INTEGER, PARAMETER ::   jpr_ity2   = 11   ! 
+   INTEGER, PARAMETER ::   jpr_itz2   = 12   ! 
+   INTEGER, PARAMETER ::   jpr_qsroce = 13   ! Qsr above the ocean
+   INTEGER, PARAMETER ::   jpr_qsrice = 14   ! Qsr above the ice
+   INTEGER, PARAMETER ::   jpr_qsrmix = 15 
+   INTEGER, PARAMETER ::   jpr_qnsoce = 16   ! Qns above the ocean
+   INTEGER, PARAMETER ::   jpr_qnsice = 17   ! Qns above the ice
+   INTEGER, PARAMETER ::   jpr_qnsmix = 18
+   INTEGER, PARAMETER ::   jpr_rain   = 19   ! total liquid precipitation (rain)
+   INTEGER, PARAMETER ::   jpr_snow   = 20   ! solid precipitation over the ocean (snow)
+   INTEGER, PARAMETER ::   jpr_tevp   = 21   ! total evaporation
+   INTEGER, PARAMETER ::   jpr_ievp   = 22   ! solid evaporation (sublimation)
+   INTEGER, PARAMETER ::   jpr_sbpr   = 23   ! sublimation - liquid precipitation - solid precipitation
+   INTEGER, PARAMETER ::   jpr_semp   = 24   ! solid freshwater budget (sublimation - snow)
+   INTEGER, PARAMETER ::   jpr_oemp   = 25   ! ocean freshwater budget (evap - precip)
+   INTEGER, PARAMETER ::   jpr_w10m   = 26   ! 10m wind
+   INTEGER, PARAMETER ::   jpr_dqnsdt = 27   ! d(Q non solar)/d(temperature)
+   INTEGER, PARAMETER ::   jpr_rnf    = 28   ! runoffs
+   INTEGER, PARAMETER ::   jpr_cal    = 29   ! calving
+   INTEGER, PARAMETER ::   jpr_taum   = 30   ! wind stress module
+   INTEGER, PARAMETER ::   jpr_co2    = 31
+   INTEGER, PARAMETER ::   jpr_topm   = 32   ! topmeltn
+   INTEGER, PARAMETER ::   jpr_botm   = 33   ! botmeltn
+   INTEGER, PARAMETER ::   jpr_sflx   = 34   ! salt flux
+   INTEGER, PARAMETER ::   jpr_toce   = 35   ! ocean temperature
+   INTEGER, PARAMETER ::   jpr_soce   = 36   ! ocean salinity
+   INTEGER, PARAMETER ::   jpr_ocx1   = 37   ! ocean current on grid 1
+   INTEGER, PARAMETER ::   jpr_ocy1   = 38   !
+   INTEGER, PARAMETER ::   jpr_ssh    = 39   ! sea surface height
+   INTEGER, PARAMETER ::   jpr_fice   = 40   ! ice fraction          
+   INTEGER, PARAMETER ::   jpr_e3t1st = 41   ! first T level thickness 
+   INTEGER, PARAMETER ::   jpr_fraqsr = 42   ! fraction of solar net radiation absorbed in the first ocean level
+   INTEGER, PARAMETER ::   jpr_mslp   = 43   ! mean sea level pressure 
+   INTEGER, PARAMETER ::   jpr_hsig   = 44   ! Hsig 
+   INTEGER, PARAMETER ::   jpr_phioc  = 45   ! Wave=>ocean energy flux 
+   INTEGER, PARAMETER ::   jpr_sdrftx = 46   ! Stokes drift on grid 1 
+   INTEGER, PARAMETER ::   jpr_sdrfty = 47   ! Stokes drift on grid 2 
+   INTEGER, PARAMETER ::   jpr_wper   = 48   ! Mean wave period
+   INTEGER, PARAMETER ::   jpr_wnum   = 49   ! Mean wavenumber
+   INTEGER, PARAMETER ::   jpr_tauwoc = 50   ! Stress fraction adsorbed by waves
+   INTEGER, PARAMETER ::   jpr_wdrag  = 51   ! Neutral surface drag coefficient
+   INTEGER, PARAMETER ::   jpr_isf    = 52
+   INTEGER, PARAMETER ::   jpr_icb    = 53
+   INTEGER, PARAMETER ::   jpr_wfreq  = 54   ! Wave peak frequency
+   INTEGER, PARAMETER ::   jpr_tauwx  = 55   ! x component of the ocean stress from waves
+   INTEGER, PARAMETER ::   jpr_tauwy  = 56   ! y component of the ocean stress from waves
+   INTEGER, PARAMETER ::   jpr_ts_ice = 57   ! Sea ice surface temp
+
+   INTEGER, PARAMETER ::   jprcv      = 57   ! total number of fields received  
+
+   INTEGER, PARAMETER ::   jps_fice   =  1   ! ice fraction sent to the atmosphere
+   INTEGER, PARAMETER ::   jps_toce   =  2   ! ocean temperature
+   INTEGER, PARAMETER ::   jps_tice   =  3   ! ice   temperature
+   INTEGER, PARAMETER ::   jps_tmix   =  4   ! mixed temperature (ocean+ice)
+   INTEGER, PARAMETER ::   jps_albice =  5   ! ice   albedo
+   INTEGER, PARAMETER ::   jps_albmix =  6   ! mixed albedo
+   INTEGER, PARAMETER ::   jps_hice   =  7   ! ice  thickness
+   INTEGER, PARAMETER ::   jps_hsnw   =  8   ! snow thickness
+   INTEGER, PARAMETER ::   jps_ocx1   =  9   ! ocean current on grid 1
+   INTEGER, PARAMETER ::   jps_ocy1   = 10   !
+   INTEGER, PARAMETER ::   jps_ocz1   = 11   !
+   INTEGER, PARAMETER ::   jps_ivx1   = 12   ! ice   current on grid 1
+   INTEGER, PARAMETER ::   jps_ivy1   = 13   !
+   INTEGER, PARAMETER ::   jps_ivz1   = 14   !
+   INTEGER, PARAMETER ::   jps_co2    = 15
+   INTEGER, PARAMETER ::   jps_soce   = 16   ! ocean salinity
+   INTEGER, PARAMETER ::   jps_ssh    = 17   ! sea surface height
+   INTEGER, PARAMETER ::   jps_qsroce = 18   ! Qsr above the ocean
+   INTEGER, PARAMETER ::   jps_qnsoce = 19   ! Qns above the ocean
+   INTEGER, PARAMETER ::   jps_oemp   = 20   ! ocean freshwater budget (evap - precip)
+   INTEGER, PARAMETER ::   jps_sflx   = 21   ! salt flux
+   INTEGER, PARAMETER ::   jps_otx1   = 22   ! 2 atmosphere-ocean stress components on grid 1
+   INTEGER, PARAMETER ::   jps_oty1   = 23   ! 
+   INTEGER, PARAMETER ::   jps_rnf    = 24   ! runoffs
+   INTEGER, PARAMETER ::   jps_taum   = 25   ! wind stress module
+   INTEGER, PARAMETER ::   jps_fice2  = 26   ! ice fraction sent to OPA (by SAS when doing SAS-OPA coupling)
+   INTEGER, PARAMETER ::   jps_e3t1st = 27   ! first level depth (vvl)
+   INTEGER, PARAMETER ::   jps_fraqsr = 28   ! fraction of solar net radiation absorbed in the first ocean level
+   INTEGER, PARAMETER ::   jps_ficet  = 29   ! total ice fraction  
+   INTEGER, PARAMETER ::   jps_ocxw   = 30   ! currents on grid 1  
+   INTEGER, PARAMETER ::   jps_ocyw   = 31   ! currents on grid 2
+   INTEGER, PARAMETER ::   jps_wlev   = 32   ! water level 
+   INTEGER, PARAMETER ::   jps_fice1  = 33   ! first-order ice concentration (for semi-implicit coupling of atmos-ice fluxes)
+   INTEGER, PARAMETER ::   jps_a_p    = 34   ! meltpond area fraction
+   INTEGER, PARAMETER ::   jps_ht_p   = 35   ! meltpond thickness
+   INTEGER, PARAMETER ::   jps_kice   = 36   ! sea ice effective conductivity
+   INTEGER, PARAMETER ::   jps_sstfrz = 37   ! sea surface freezing temperature
+   INTEGER, PARAMETER ::   jps_ttilyr = 38   ! sea ice top layer temp
+
+   INTEGER, PARAMETER ::   jpsnd      = 38   ! total number of fields sent 
+
+#if ! defined key_oasis3 
+   ! Dummy variables to enable compilation when oasis3 is not being used 
+   INTEGER                    ::   OASIS_Sent        = -1 
+   INTEGER                    ::   OASIS_SentOut     = -1 
+   INTEGER                    ::   OASIS_ToRest      = -1 
+   INTEGER                    ::   OASIS_ToRestOut   = -1 
+#endif 
+
+   !                                  !!** namelist namsbc_cpl **
+   TYPE ::   FLD_C                     !   
+      CHARACTER(len = 32) ::   cldes      ! desciption of the coupling strategy
+      CHARACTER(len = 32) ::   clcat      ! multiple ice categories strategy
+      CHARACTER(len = 32) ::   clvref     ! reference of vector ('spherical' or 'cartesian')
+      CHARACTER(len = 32) ::   clvor      ! orientation of vector fields ('eastward-northward' or 'local grid')
+      CHARACTER(len = 32) ::   clvgrd     ! grids on which is located the vector fields
+   END TYPE FLD_C
+   !                                   ! Send to the atmosphere  
+   TYPE(FLD_C) ::   sn_snd_temp  , sn_snd_alb , sn_snd_thick, sn_snd_crt   , sn_snd_co2,  &
+      &             sn_snd_thick1, sn_snd_cond, sn_snd_mpnd , sn_snd_sstfrz, sn_snd_ttilyr
+   !                                   ! Received from the atmosphere
+   TYPE(FLD_C) ::   sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau, sn_rcv_tauw, sn_rcv_dqnsdt, sn_rcv_qsr,  &
+      &             sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf, sn_rcv_ts_ice
+   TYPE(FLD_C) ::   sn_rcv_cal, sn_rcv_iceflx, sn_rcv_co2, sn_rcv_mslp, sn_rcv_icb, sn_rcv_isf
+   ! Send to waves 
+   TYPE(FLD_C) ::   sn_snd_ifrac, sn_snd_crtw, sn_snd_wlev 
+   ! Received from waves 
+   TYPE(FLD_C) ::   sn_rcv_hsig, sn_rcv_phioc, sn_rcv_sdrfx, sn_rcv_sdrfy, sn_rcv_wper, sn_rcv_wnum, sn_rcv_tauwoc, &
+                    sn_rcv_wdrag, sn_rcv_wfreq
+   !                                   ! 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)
+   LOGICAL     ::   ln_scale_ice_flux     !  use ice fluxes that are already "ice weighted" ( i.e. multiplied ice concentration) 
+
+   TYPE ::   DYNARR     
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   z3   
+   END TYPE DYNARR
+
+   TYPE( DYNARR ), SAVE, DIMENSION(jprcv) ::   frcv                ! all fields recieved from the atmosphere
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   alb_oce_mix    ! ocean albedo sent to atmosphere (mix clear/overcast sky)
+#if defined key_si3 || defined key_cice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   a_i_last_couple !: Ice fractional area at last coupling time
+#endif
+
+   REAL(wp) ::   rpref = 101000._wp   ! reference atmospheric pressure[N/m2] 
+   REAL(wp) ::   r1_grau              ! = 1.e0 / (grav * rau0) 
+
+   INTEGER , ALLOCATABLE, SAVE, DIMENSION(:) ::   nrcvinfo           ! OASIS info argument
+
+   !! Substitution
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   INTEGER FUNCTION sbc_cpl_alloc()
+      !!----------------------------------------------------------------------
+      !!             ***  FUNCTION sbc_cpl_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(5)
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( alb_oce_mix(jpi,jpj), nrcvinfo(jprcv),  STAT=ierr(1) )
+      
+#if ! defined key_si3 && ! 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
+      ALLOCATE( xcplmask(jpi,jpj,0:nn_cplmodel) , STAT=ierr(3) )
+#if defined key_si3 || defined key_cice
+      ALLOCATE( a_i_last_couple(jpi,jpj,jpl) , STAT=ierr(4) )
+#endif
+      !
+      IF( .NOT. ln_apr_dyn ) ALLOCATE( ssh_ib(jpi,jpj), ssh_ibb(jpi,jpj), apr(jpi, jpj), STAT=ierr(5) )
+
+      sbc_cpl_alloc = MAXVAL( ierr )
+      CALL mpp_sum ( 'sbccpl', sbc_cpl_alloc )
+      IF( sbc_cpl_alloc > 0 )   CALL ctl_warn('sbc_cpl_alloc: allocation of arrays failed')
+      !
+   END FUNCTION sbc_cpl_alloc
+
+
+   SUBROUTINE sbc_cpl_init( k_ice )     
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_cpl_init  ***
+      !!
+      !! ** Purpose :   Initialisation of send and received information from
+      !!                the atmospheric component
+      !!
+      !! ** Method  : * Read namsbc_cpl namelist 
+      !!              * define the receive interface
+      !!              * define the send    interface
+      !!              * initialise the OASIS coupler
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   k_ice   ! ice management in the sbc (=0/1/2/3)
+      !
+      INTEGER ::   jn          ! dummy loop index
+      INTEGER ::   ios, inum   ! Local integer
+      REAL(wp), DIMENSION(jpi,jpj) ::   zacs, zaos
+      !!
+      NAMELIST/namsbc_cpl/  nn_cplmodel  , ln_usecplmask, nn_cats_cpl , ln_scale_ice_flux,             &
+         &                  sn_snd_temp  , sn_snd_alb   , sn_snd_thick, sn_snd_crt   , sn_snd_co2   ,  & 
+         &                  sn_snd_ttilyr, sn_snd_cond  , sn_snd_mpnd , sn_snd_sstfrz, sn_snd_thick1,  & 
+         &                  sn_snd_ifrac , sn_snd_crtw  , sn_snd_wlev , sn_rcv_hsig  , sn_rcv_phioc ,  & 
+         &                  sn_rcv_w10m  , sn_rcv_taumod, sn_rcv_tau  , sn_rcv_dqnsdt, sn_rcv_qsr   ,  & 
+         &                  sn_rcv_sdrfx , sn_rcv_sdrfy , sn_rcv_wper , sn_rcv_wnum  , sn_rcv_tauwoc,  &
+         &                  sn_rcv_wdrag , sn_rcv_qns   , sn_rcv_emp  , sn_rcv_rnf   , sn_rcv_cal   ,  &
+         &                  sn_rcv_iceflx, sn_rcv_co2   , sn_rcv_mslp ,                                &
+         &                  sn_rcv_icb   , sn_rcv_isf   , sn_rcv_wfreq, sn_rcv_tauw  ,                 &
+         &                  sn_rcv_ts_ice
+      !!---------------------------------------------------------------------
+      !
+      ! ================================ !
+      !      Namelist informations       !
+      ! ================================ !
+      !
+      REWIND( numnam_ref )              ! Namelist namsbc_cpl in reference namelist : Variables for OASIS coupling
+      READ  ( numnam_ref, namsbc_cpl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_cpl in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namsbc_cpl in configuration namelist : Variables for OASIS coupling
+      READ  ( numnam_cfg, namsbc_cpl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_cpl in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_cpl )
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*)'sbc_cpl_init : namsbc_cpl namelist '
+         WRITE(numout,*)'~~~~~~~~~~~~'
+      ENDIF
+      IF( lwp .AND. ln_cpl ) THEN                        ! control print
+         WRITE(numout,*)'  nn_cplmodel                         = ', nn_cplmodel
+         WRITE(numout,*)'  ln_usecplmask                       = ', ln_usecplmask
+         WRITE(numout,*)'  ln_scale_ice_flux                   = ', ln_scale_ice_flux
+         WRITE(numout,*)'  nn_cats_cpl                         = ', nn_cats_cpl
+         WRITE(numout,*)'  received fields (mutiple ice categogies)'
+         WRITE(numout,*)'      10m wind module                 = ', TRIM(sn_rcv_w10m%cldes  ), ' (', TRIM(sn_rcv_w10m%clcat  ), ')'
+         WRITE(numout,*)'      stress module                   = ', TRIM(sn_rcv_taumod%cldes), ' (', TRIM(sn_rcv_taumod%clcat), ')'
+         WRITE(numout,*)'      surface stress                  = ', TRIM(sn_rcv_tau%cldes   ), ' (', TRIM(sn_rcv_tau%clcat   ), ')'
+         WRITE(numout,*)'                     - referential    = ', sn_rcv_tau%clvref
+         WRITE(numout,*)'                     - orientation    = ', sn_rcv_tau%clvor
+         WRITE(numout,*)'                     - mesh           = ', sn_rcv_tau%clvgrd
+         WRITE(numout,*)'      non-solar heat flux sensitivity = ', TRIM(sn_rcv_dqnsdt%cldes), ' (', TRIM(sn_rcv_dqnsdt%clcat), ')'
+         WRITE(numout,*)'      solar heat flux                 = ', TRIM(sn_rcv_qsr%cldes   ), ' (', TRIM(sn_rcv_qsr%clcat   ), ')'
+         WRITE(numout,*)'      non-solar heat flux             = ', TRIM(sn_rcv_qns%cldes   ), ' (', TRIM(sn_rcv_qns%clcat   ), ')'
+         WRITE(numout,*)'      freshwater budget               = ', TRIM(sn_rcv_emp%cldes   ), ' (', TRIM(sn_rcv_emp%clcat   ), ')'
+         WRITE(numout,*)'      runoffs                         = ', TRIM(sn_rcv_rnf%cldes   ), ' (', TRIM(sn_rcv_rnf%clcat   ), ')'
+         WRITE(numout,*)'      calving                         = ', TRIM(sn_rcv_cal%cldes   ), ' (', TRIM(sn_rcv_cal%clcat   ), ')'
+         WRITE(numout,*)'      iceberg                         = ', TRIM(sn_rcv_icb%cldes   ), ' (', TRIM(sn_rcv_icb%clcat   ), ')'
+         WRITE(numout,*)'      ice shelf                       = ', TRIM(sn_rcv_isf%cldes   ), ' (', TRIM(sn_rcv_isf%clcat   ), ')'
+         WRITE(numout,*)'      sea ice heat fluxes             = ', TRIM(sn_rcv_iceflx%cldes), ' (', TRIM(sn_rcv_iceflx%clcat), ')'
+         WRITE(numout,*)'      atm co2                         = ', TRIM(sn_rcv_co2%cldes   ), ' (', TRIM(sn_rcv_co2%clcat   ), ')'
+         WRITE(numout,*)'      significant wave heigth         = ', TRIM(sn_rcv_hsig%cldes  ), ' (', TRIM(sn_rcv_hsig%clcat  ), ')' 
+         WRITE(numout,*)'      wave to oce energy flux         = ', TRIM(sn_rcv_phioc%cldes ), ' (', TRIM(sn_rcv_phioc%clcat ), ')' 
+         WRITE(numout,*)'      Surface Stokes drift grid u     = ', TRIM(sn_rcv_sdrfx%cldes ), ' (', TRIM(sn_rcv_sdrfx%clcat ), ')' 
+         WRITE(numout,*)'      Surface Stokes drift grid v     = ', TRIM(sn_rcv_sdrfy%cldes ), ' (', TRIM(sn_rcv_sdrfy%clcat ), ')' 
+         WRITE(numout,*)'      Mean wave period                = ', TRIM(sn_rcv_wper%cldes  ), ' (', TRIM(sn_rcv_wper%clcat  ), ')' 
+         WRITE(numout,*)'      Mean wave number                = ', TRIM(sn_rcv_wnum%cldes  ), ' (', TRIM(sn_rcv_wnum%clcat  ), ')' 
+         WRITE(numout,*)'      Wave peak frequency             = ', TRIM(sn_rcv_wfreq%cldes ), ' (', TRIM(sn_rcv_wfreq%clcat ), ')'
+         WRITE(numout,*)'      Stress frac adsorbed by waves   = ', TRIM(sn_rcv_tauwoc%cldes), ' (', TRIM(sn_rcv_tauwoc%clcat ), ')' 
+         WRITE(numout,*)'      Stress components by waves      = ', TRIM(sn_rcv_tauw%cldes  ), ' (', TRIM(sn_rcv_tauw%clcat  ), ')'
+         WRITE(numout,*)'      Neutral surf drag coefficient   = ', TRIM(sn_rcv_wdrag%cldes ), ' (', TRIM(sn_rcv_wdrag%clcat ), ')' 
+         WRITE(numout,*)'      Sea ice surface skin temperature= ', TRIM(sn_rcv_ts_ice%cldes), ' (', TRIM(sn_rcv_ts_ice%clcat), ')' 
+         WRITE(numout,*)'  sent fields (multiple ice categories)'
+         WRITE(numout,*)'      surface temperature             = ', TRIM(sn_snd_temp%cldes  ), ' (', TRIM(sn_snd_temp%clcat  ), ')'
+         WRITE(numout,*)'      top ice layer temperature       = ', TRIM(sn_snd_ttilyr%cldes), ' (', TRIM(sn_snd_ttilyr%clcat), ')'
+         WRITE(numout,*)'      albedo                          = ', TRIM(sn_snd_alb%cldes   ), ' (', TRIM(sn_snd_alb%clcat   ), ')'
+         WRITE(numout,*)'      ice/snow thickness              = ', TRIM(sn_snd_thick%cldes ), ' (', TRIM(sn_snd_thick%clcat ), ')'
+         WRITE(numout,*)'      total ice fraction              = ', TRIM(sn_snd_ifrac%cldes ), ' (', TRIM(sn_snd_ifrac%clcat ), ')' 
+         WRITE(numout,*)'      surface current                 = ', TRIM(sn_snd_crt%cldes   ), ' (', TRIM(sn_snd_crt%clcat   ), ')'
+         WRITE(numout,*)'                      - referential   = ', sn_snd_crt%clvref 
+         WRITE(numout,*)'                      - orientation   = ', sn_snd_crt%clvor
+         WRITE(numout,*)'                      - mesh          = ', sn_snd_crt%clvgrd
+         WRITE(numout,*)'      oce co2 flux                    = ', TRIM(sn_snd_co2%cldes   ), ' (', TRIM(sn_snd_co2%clcat   ), ')'
+         WRITE(numout,*)'      ice effective conductivity      = ', TRIM(sn_snd_cond%cldes  ), ' (', TRIM(sn_snd_cond%clcat  ), ')'
+         WRITE(numout,*)'      meltponds fraction and depth    = ', TRIM(sn_snd_mpnd%cldes  ), ' (', TRIM(sn_snd_mpnd%clcat  ), ')'
+         WRITE(numout,*)'      sea surface freezing temp       = ', TRIM(sn_snd_sstfrz%cldes), ' (', TRIM(sn_snd_sstfrz%clcat), ')'
+         WRITE(numout,*)'      water level                     = ', TRIM(sn_snd_wlev%cldes  ), ' (', TRIM(sn_snd_wlev%clcat  ), ')' 
+         WRITE(numout,*)'      mean sea level pressure         = ', TRIM(sn_rcv_mslp%cldes  ), ' (', TRIM(sn_rcv_mslp%clcat  ), ')' 
+         WRITE(numout,*)'      surface current to waves        = ', TRIM(sn_snd_crtw%cldes  ), ' (', TRIM(sn_snd_crtw%clcat  ), ')' 
+         WRITE(numout,*)'                      - referential   = ', sn_snd_crtw%clvref 
+         WRITE(numout,*)'                      - orientation   = ', sn_snd_crtw%clvor 
+         WRITE(numout,*)'                      - mesh          = ', sn_snd_crtw%clvgrd 
+      ENDIF
+
+      !                                   ! allocate sbccpl arrays
+      IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
+     
+      ! ================================ !
+      !   Define the receive interface   !
+      ! ================================ !
+      nrcvinfo(:) = OASIS_idle   ! needed by nrcvinfo(jpr_otx1) if we do not receive ocean stress 
+
+      ! for each field: define the OASIS name                              (srcv(:)%clname)
+      !                 define receive or not from the namelist parameters (srcv(:)%laction)
+      !                 define the north fold type of lbc                  (srcv(:)%nsgn)
+
+      ! default definitions of srcv
+      srcv(:)%laction = .FALSE.   ;   srcv(:)%clgrid = 'T'   ;   srcv(:)%nsgn = 1.   ;   srcv(:)%nct = 1
+
+      !                                                      ! ------------------------- !
+      !                                                      ! ice and ocean wind stress !   
+      !                                                      ! ------------------------- !
+      !                                                           ! Name 
+      srcv(jpr_otx1)%clname = 'O_OTaux1'      ! 1st ocean component on grid ONE (T or U)
+      srcv(jpr_oty1)%clname = 'O_OTauy1'      ! 2nd   -      -         -     - 
+      srcv(jpr_otz1)%clname = 'O_OTauz1'      ! 3rd   -      -         -     - 
+      srcv(jpr_otx2)%clname = 'O_OTaux2'      ! 1st ocean component on grid TWO (V)
+      srcv(jpr_oty2)%clname = 'O_OTauy2'      ! 2nd   -      -         -     - 
+      srcv(jpr_otz2)%clname = 'O_OTauz2'      ! 3rd   -      -         -     - 
+      !
+      srcv(jpr_itx1)%clname = 'O_ITaux1'      ! 1st  ice  component on grid ONE (T, F, I or U)
+      srcv(jpr_ity1)%clname = 'O_ITauy1'      ! 2nd   -      -         -     - 
+      srcv(jpr_itz1)%clname = 'O_ITauz1'      ! 3rd   -      -         -     - 
+      srcv(jpr_itx2)%clname = 'O_ITaux2'      ! 1st  ice  component on grid TWO (V)
+      srcv(jpr_ity2)%clname = 'O_ITauy2'      ! 2nd   -      -         -     - 
+      srcv(jpr_itz2)%clname = 'O_ITauz2'      ! 3rd   -      -         -     - 
+      ! 
+      ! Vectors: change of sign at north fold ONLY if on the local grid
+      IF(       TRIM( sn_rcv_tau%cldes ) == 'oce only' .OR. TRIM( sn_rcv_tau%cldes ) == 'oce and ice'  &
+           .OR. TRIM( sn_rcv_tau%cldes ) == 'mixed oce-ice' ) THEN ! avoid working with the atmospheric fields if they are not coupled
+      !
+      IF( TRIM( sn_rcv_tau%clvor ) == 'local grid' )   srcv(jpr_otx1:jpr_itz2)%nsgn = -1.
+      
+      !                                                           ! Set grid and action
+      SELECT CASE( TRIM( sn_rcv_tau%clvgrd ) )      !  'T', 'U,V', 'U,V,I', 'U,V,F', 'T,I', 'T,F', or 'T,U,V'
+      CASE( 'T' ) 
+         srcv(jpr_otx1:jpr_itz2)%clgrid  = 'T'        ! oce and ice components given at T-point
+         srcv(jpr_otx1:jpr_otz1)%laction = .TRUE.     ! receive oce components on grid 1 
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 
+      CASE( 'U,V' ) 
+         srcv(jpr_otx1:jpr_otz1)%clgrid  = 'U'        ! oce components given at U-point
+         srcv(jpr_otx2:jpr_otz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'U'        ! ice components given at U-point
+         srcv(jpr_itx2:jpr_itz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_otx1:jpr_itz2)%laction = .TRUE.     ! receive oce and ice components on both grid 1 & 2
+      CASE( 'U,V,T' )
+         srcv(jpr_otx1:jpr_otz1)%clgrid  = 'U'        ! oce components given at U-point
+         srcv(jpr_otx2:jpr_otz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'T'        ! ice components given at T-point
+         srcv(jpr_otx1:jpr_otz2)%laction = .TRUE.     ! receive oce components on grid 1 & 2
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 only
+      CASE( 'U,V,I' )
+         srcv(jpr_otx1:jpr_otz1)%clgrid  = 'U'        ! oce components given at U-point
+         srcv(jpr_otx2:jpr_otz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'I'        ! ice components given at I-point
+         srcv(jpr_otx1:jpr_otz2)%laction = .TRUE.     ! receive oce components on grid 1 & 2
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 only
+      CASE( 'U,V,F' )
+         srcv(jpr_otx1:jpr_otz1)%clgrid  = 'U'        ! oce components given at U-point
+         srcv(jpr_otx2:jpr_otz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'F'        ! ice components given at F-point
+         srcv(jpr_otx1:jpr_otz2)%laction = .TRUE.     ! receive oce components on grid 1 & 2
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 only
+      CASE( 'T,I' ) 
+         srcv(jpr_otx1:jpr_itz2)%clgrid  = 'T'        ! oce and ice components given at T-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'I'        ! ice components given at I-point
+         srcv(jpr_otx1:jpr_otz1)%laction = .TRUE.     ! receive oce components on grid 1 
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 
+      CASE( 'T,F' ) 
+         srcv(jpr_otx1:jpr_itz2)%clgrid  = 'T'        ! oce and ice components given at T-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'F'        ! ice components given at F-point
+         srcv(jpr_otx1:jpr_otz1)%laction = .TRUE.     ! receive oce components on grid 1 
+         srcv(jpr_itx1:jpr_itz1)%laction = .TRUE.     ! receive ice components on grid 1 
+      CASE( 'T,U,V' )
+         srcv(jpr_otx1:jpr_otz1)%clgrid  = 'T'        ! oce components given at T-point
+         srcv(jpr_itx1:jpr_itz1)%clgrid  = 'U'        ! ice components given at U-point
+         srcv(jpr_itx2:jpr_itz2)%clgrid  = 'V'        !           and           V-point
+         srcv(jpr_otx1:jpr_otz1)%laction = .TRUE.     ! receive oce components on grid 1 only
+         srcv(jpr_itx1:jpr_itz2)%laction = .TRUE.     ! receive ice components on grid 1 & 2
+      CASE default   
+         CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_rcv_tau%clvgrd' )
+      END SELECT
+      !
+      IF( TRIM( sn_rcv_tau%clvref ) == 'spherical' )   &           ! spherical: 3rd component not received
+         &     srcv( (/jpr_otz1, jpr_otz2, jpr_itz1, jpr_itz2/) )%laction = .FALSE. 
+      !
+      IF( TRIM( sn_rcv_tau%clvor  ) == 'local grid' ) THEN        ! already on local grid -> no need of the second grid
+            srcv(jpr_otx2:jpr_otz2)%laction = .FALSE. 
+            srcv(jpr_itx2:jpr_itz2)%laction = .FALSE. 
+            srcv(jpr_oty1)%clgrid = srcv(jpr_oty2)%clgrid   ! not needed but cleaner...
+            srcv(jpr_ity1)%clgrid = srcv(jpr_ity2)%clgrid   ! not needed but cleaner...
+      ENDIF
+      !
+      IF( TRIM( sn_rcv_tau%cldes ) /= 'oce and ice' ) THEN        ! 'oce and ice' case ocean stress on ocean mesh used
+         srcv(jpr_itx1:jpr_itz2)%laction = .FALSE.    ! ice components not received
+         srcv(jpr_itx1)%clgrid = 'U'                  ! ocean stress used after its transformation
+         srcv(jpr_ity1)%clgrid = 'V'                  ! i.e. it is always at U- & V-points for i- & j-comp. resp.
+      ENDIF
+      ENDIF
+
+      !                                                      ! ------------------------- !
+      !                                                      !    freshwater budget      !   E-P
+      !                                                      ! ------------------------- !
+      ! we suppose that atmosphere modele do not make the difference between precipiration (liquide or solid)
+      ! over ice of free ocean within the same atmospheric cell.cd 
+      srcv(jpr_rain)%clname = 'OTotRain'      ! Rain = liquid precipitation
+      srcv(jpr_snow)%clname = 'OTotSnow'      ! Snow = solid precipitation
+      srcv(jpr_tevp)%clname = 'OTotEvap'      ! total evaporation (over oce + ice sublimation)
+      srcv(jpr_ievp)%clname = 'OIceEvap'      ! evaporation over ice = sublimation
+      srcv(jpr_sbpr)%clname = 'OSubMPre'      ! sublimation - liquid precipitation - solid precipitation 
+      srcv(jpr_semp)%clname = 'OISubMSn'      ! ice solid water budget = sublimation - solid precipitation
+      srcv(jpr_oemp)%clname = 'OOEvaMPr'      ! ocean water budget = ocean Evap - ocean precip
+      SELECT CASE( TRIM( sn_rcv_emp%cldes ) )
+      CASE( 'none'          )       ! nothing to do
+      CASE( 'oce only'      )   ;   srcv(jpr_oemp)%laction = .TRUE. 
+      CASE( 'conservative'  )
+         srcv( (/jpr_rain, jpr_snow, jpr_ievp, jpr_tevp/) )%laction = .TRUE.
+         IF ( k_ice <= 1 )  srcv(jpr_ievp)%laction = .FALSE.
+      CASE( 'oce and ice'   )   ;   srcv( (/jpr_ievp, jpr_sbpr, jpr_semp, jpr_oemp/) )%laction = .TRUE.
+      CASE default              ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_rcv_emp%cldes' )
+      END SELECT
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !     Runoffs & Calving     !   
+      !                                                      ! ------------------------- !
+      srcv(jpr_rnf   )%clname = 'O_Runoff'
+      IF( TRIM( sn_rcv_rnf%cldes ) == 'coupled' ) THEN
+         srcv(jpr_rnf)%laction = .TRUE.
+         l_rnfcpl              = .TRUE.                      ! -> no need to read runoffs in sbcrnf
+         ln_rnf                = nn_components /= jp_iam_sas ! -> force to go through sbcrnf if not sas
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   runoffs received from oasis -> force ln_rnf = ', ln_rnf
+      ENDIF
+      !
+      srcv(jpr_cal)%clname = 'OCalving'   ;  IF( TRIM( sn_rcv_cal%cldes) == 'coupled' )   srcv(jpr_cal)%laction = .TRUE.
+      srcv(jpr_isf)%clname = 'OIcshelf'   ;  IF( TRIM( sn_rcv_isf%cldes) == 'coupled' )   srcv(jpr_isf)%laction = .TRUE.
+      srcv(jpr_icb)%clname = 'OIceberg'   ;  IF( TRIM( sn_rcv_icb%cldes) == 'coupled' )   srcv(jpr_icb)%laction = .TRUE.
+
+      IF( srcv(jpr_isf)%laction .AND. ln_isf ) THEN
+         l_isfcpl             = .TRUE.                      ! -> no need to read isf in sbcisf
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   iceshelf received from oasis '
+      ENDIF
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !    non solar radiation    !   Qns
+      !                                                      ! ------------------------- !
+      srcv(jpr_qnsoce)%clname = 'O_QnsOce'
+      srcv(jpr_qnsice)%clname = 'O_QnsIce'
+      srcv(jpr_qnsmix)%clname = 'O_QnsMix'
+      SELECT CASE( TRIM( sn_rcv_qns%cldes ) )
+      CASE( 'none'          )       ! nothing to do
+      CASE( 'oce only'      )   ;   srcv(               jpr_qnsoce   )%laction = .TRUE.
+      CASE( 'conservative'  )   ;   srcv( (/jpr_qnsice, jpr_qnsmix/) )%laction = .TRUE.
+      CASE( 'oce and ice'   )   ;   srcv( (/jpr_qnsice, jpr_qnsoce/) )%laction = .TRUE.
+      CASE( 'mixed oce-ice' )   ;   srcv(               jpr_qnsmix   )%laction = .TRUE. 
+      CASE default              ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_rcv_qns%cldes' )
+      END SELECT
+      IF( TRIM( sn_rcv_qns%cldes ) == 'mixed oce-ice' .AND. nn_cats_cpl > 1 ) &
+         CALL ctl_stop( 'sbc_cpl_init: sn_rcv_qns%cldes not currently allowed to be mixed oce-ice for multi-category ice' )
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !    solar radiation        !   Qsr
+      !                                                      ! ------------------------- !
+      srcv(jpr_qsroce)%clname = 'O_QsrOce'
+      srcv(jpr_qsrice)%clname = 'O_QsrIce'
+      srcv(jpr_qsrmix)%clname = 'O_QsrMix'
+      SELECT CASE( TRIM( sn_rcv_qsr%cldes ) )
+      CASE( 'none'          )       ! nothing to do
+      CASE( 'oce only'      )   ;   srcv(               jpr_qsroce   )%laction = .TRUE.
+      CASE( 'conservative'  )   ;   srcv( (/jpr_qsrice, jpr_qsrmix/) )%laction = .TRUE.
+      CASE( 'oce and ice'   )   ;   srcv( (/jpr_qsrice, jpr_qsroce/) )%laction = .TRUE.
+      CASE( 'mixed oce-ice' )   ;   srcv(               jpr_qsrmix   )%laction = .TRUE. 
+      CASE default              ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_rcv_qsr%cldes' )
+      END SELECT
+      IF( TRIM( sn_rcv_qsr%cldes ) == 'mixed oce-ice' .AND. nn_cats_cpl > 1 ) &
+         CALL ctl_stop( 'sbc_cpl_init: sn_rcv_qsr%cldes not currently allowed to be mixed oce-ice for multi-category ice' )
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !   non solar sensitivity   !   d(Qns)/d(T)
+      !                                                      ! ------------------------- !
+      srcv(jpr_dqnsdt)%clname = 'O_dQnsdT'   
+      IF( TRIM( sn_rcv_dqnsdt%cldes ) == 'coupled' )   srcv(jpr_dqnsdt)%laction = .TRUE.
+      !
+      ! non solar sensitivity mandatory for mixed oce-ice solar radiation coupling technique
+      IF( TRIM( sn_rcv_dqnsdt%cldes ) == 'none' .AND. TRIM( sn_rcv_qns%cldes ) == 'mixed oce-ice' )  &
+         &   CALL ctl_stop( 'sbc_cpl_init: namsbc_cpl namelist mismatch between sn_rcv_qns%cldes and sn_rcv_dqnsdt%cldes' )
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !      10m wind module      !   
+      !                                                      ! ------------------------- !
+      srcv(jpr_w10m)%clname = 'O_Wind10'   ;   IF( TRIM(sn_rcv_w10m%cldes  ) == 'coupled' )   srcv(jpr_w10m)%laction = .TRUE. 
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !   wind stress module      !   
+      !                                                      ! ------------------------- !
+      srcv(jpr_taum)%clname = 'O_TauMod'   ;   IF( TRIM(sn_rcv_taumod%cldes) == 'coupled' )   srcv(jpr_taum)%laction = .TRUE.
+      lhftau = srcv(jpr_taum)%laction
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !      Atmospheric CO2      !
+      !                                                      ! ------------------------- !
+      srcv(jpr_co2 )%clname = 'O_AtmCO2'   
+      IF( TRIM(sn_rcv_co2%cldes   ) == 'coupled' )  THEN
+         srcv(jpr_co2 )%laction = .TRUE.
+         l_co2cpl = .TRUE.
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   Atmospheric pco2 received from oasis '
+         IF(lwp) WRITE(numout,*)
+      ENDIF
+      !
+      !                                                      ! ------------------------- ! 
+      !                                                      ! Mean Sea Level Pressure   ! 
+      !                                                      ! ------------------------- ! 
+      srcv(jpr_mslp)%clname = 'O_MSLP'     ;   IF( TRIM(sn_rcv_mslp%cldes  ) == 'coupled' )    srcv(jpr_mslp)%laction = .TRUE. 
+      !
+      !                                                      ! ------------------------- !
+      !                                                      !  ice topmelt and botmelt  !   
+      !                                                      ! ------------------------- !
+      srcv(jpr_topm )%clname = 'OTopMlt'
+      srcv(jpr_botm )%clname = 'OBotMlt'
+      IF( TRIM(sn_rcv_iceflx%cldes) == 'coupled' ) THEN
+         IF ( TRIM( sn_rcv_iceflx%clcat ) == 'yes' ) THEN
+            srcv(jpr_topm:jpr_botm)%nct = nn_cats_cpl
+         ELSE
+            CALL ctl_stop( 'sbc_cpl_init: sn_rcv_iceflx%clcat should always be set to yes currently' )
+         ENDIF
+         srcv(jpr_topm:jpr_botm)%laction = .TRUE.
+      ENDIF
+      !                                                      ! ------------------------- !
+      !                                                      !    ice skin temperature   !   
+      !                                                      ! ------------------------- !
+      srcv(jpr_ts_ice)%clname = 'OTsfIce'    ! needed by Met Office
+      IF ( TRIM( sn_rcv_ts_ice%cldes ) == 'ice' )   srcv(jpr_ts_ice)%laction = .TRUE.
+      IF ( TRIM( sn_rcv_ts_ice%clcat ) == 'yes' )   srcv(jpr_ts_ice)%nct     = nn_cats_cpl
+      IF ( TRIM( sn_rcv_emp%clcat    ) == 'yes' )   srcv(jpr_ievp)%nct       = nn_cats_cpl
+
+#if defined key_si3
+      IF( ln_cndflx .AND. .NOT.ln_cndemulate ) THEN 
+         IF( .NOT.srcv(jpr_ts_ice)%laction )  &
+            &   CALL ctl_stop( 'sbc_cpl_init: srcv(jpr_ts_ice)%laction should be set to true when ln_cndflx=T' )     
+      ENDIF
+#endif
+      !                                                      ! ------------------------- !
+      !                                                      !      Wave breaking        !    
+      !                                                      ! ------------------------- ! 
+      srcv(jpr_hsig)%clname  = 'O_Hsigwa'    ! significant wave height
+      IF( TRIM(sn_rcv_hsig%cldes  ) == 'coupled' )  THEN
+         srcv(jpr_hsig)%laction = .TRUE.
+         cpl_hsig = .TRUE.
+      ENDIF
+      srcv(jpr_phioc)%clname = 'O_PhiOce'    ! wave to ocean energy
+      IF( TRIM(sn_rcv_phioc%cldes ) == 'coupled' )  THEN
+         srcv(jpr_phioc)%laction = .TRUE.
+         cpl_phioc = .TRUE.
+      ENDIF
+      srcv(jpr_sdrftx)%clname = 'O_Sdrfx'    ! Stokes drift in the u direction
+      IF( TRIM(sn_rcv_sdrfx%cldes ) == 'coupled' )  THEN
+         srcv(jpr_sdrftx)%laction = .TRUE.
+         cpl_sdrftx = .TRUE.
+      ENDIF
+      srcv(jpr_sdrfty)%clname = 'O_Sdrfy'    ! Stokes drift in the v direction
+      IF( TRIM(sn_rcv_sdrfy%cldes ) == 'coupled' )  THEN
+         srcv(jpr_sdrfty)%laction = .TRUE.
+         cpl_sdrfty = .TRUE.
+      ENDIF
+      srcv(jpr_wper)%clname = 'O_WPer'       ! mean wave period
+      IF( TRIM(sn_rcv_wper%cldes  ) == 'coupled' )  THEN
+         srcv(jpr_wper)%laction = .TRUE.
+         cpl_wper = .TRUE.
+      ENDIF
+      srcv(jpr_wfreq)%clname = 'O_WFreq'     ! wave peak frequency 
+      IF( TRIM(sn_rcv_wfreq%cldes ) == 'coupled' )  THEN
+         srcv(jpr_wfreq)%laction = .TRUE.
+         cpl_wfreq = .TRUE.
+      ENDIF
+      srcv(jpr_wnum)%clname = 'O_WNum'       ! mean wave number
+      IF( TRIM(sn_rcv_wnum%cldes ) == 'coupled' )  THEN
+         srcv(jpr_wnum)%laction = .TRUE.
+         cpl_wnum = .TRUE.
+      ENDIF
+      srcv(jpr_tauwoc)%clname = 'O_TauOce'   ! stress fraction adsorbed by the wave
+      IF( TRIM(sn_rcv_tauwoc%cldes ) == 'coupled' )  THEN
+         srcv(jpr_tauwoc)%laction = .TRUE.
+         cpl_tauwoc = .TRUE.
+      ENDIF
+      srcv(jpr_tauwx)%clname = 'O_Tauwx'      ! ocean stress from wave in the x direction
+      srcv(jpr_tauwy)%clname = 'O_Tauwy'      ! ocean stress from wave in the y direction
+      IF( TRIM(sn_rcv_tauw%cldes ) == 'coupled' )  THEN
+         srcv(jpr_tauwx)%laction = .TRUE.
+         srcv(jpr_tauwy)%laction = .TRUE.
+         cpl_tauw = .TRUE.
+      ENDIF
+      srcv(jpr_wdrag)%clname = 'O_WDrag'     ! neutral surface drag coefficient
+      IF( TRIM(sn_rcv_wdrag%cldes ) == 'coupled' )  THEN
+         srcv(jpr_wdrag)%laction = .TRUE.
+         cpl_wdrag = .TRUE.
+      ENDIF
+      IF( srcv(jpr_tauwoc)%laction .AND. srcv(jpr_tauwx)%laction .AND. srcv(jpr_tauwy)%laction ) &
+            CALL ctl_stop( 'More than one method for modifying the ocean stress has been selected ', &
+                                     '(sn_rcv_tauwoc=coupled and sn_rcv_tauw=coupled)' )
+      !
+      !                                                      ! ------------------------------- !
+      !                                                      !   OPA-SAS coupling - rcv by opa !   
+      !                                                      ! ------------------------------- !
+      srcv(jpr_sflx)%clname = 'O_SFLX'
+      srcv(jpr_fice)%clname = 'RIceFrc'
+      !
+      IF( nn_components == jp_iam_opa ) THEN    ! OPA coupled to SAS via OASIS: force received field by OPA (sent by SAS)
+         srcv(:)%laction = .FALSE.   ! force default definition in case of opa <-> sas coupling
+         srcv(:)%clgrid  = 'T'       ! force default definition in case of opa <-> sas coupling
+         srcv(:)%nsgn    = 1.        ! force default definition in case of opa <-> sas coupling
+         srcv( (/jpr_qsroce, jpr_qnsoce, jpr_oemp, jpr_sflx, jpr_fice, jpr_otx1, jpr_oty1, jpr_taum/) )%laction = .TRUE.
+         srcv(jpr_otx1)%clgrid = 'U'        ! oce components given at U-point
+         srcv(jpr_oty1)%clgrid = 'V'        !           and           V-point
+         ! Vectors: change of sign at north fold ONLY if on the local grid
+         srcv( (/jpr_otx1,jpr_oty1/) )%nsgn = -1.
+         sn_rcv_tau%clvgrd = 'U,V'
+         sn_rcv_tau%clvor = 'local grid'
+         sn_rcv_tau%clvref = 'spherical'
+         sn_rcv_emp%cldes = 'oce only'
+         !
+         IF(lwp) THEN                        ! control print
+            WRITE(numout,*)
+            WRITE(numout,*)'               Special conditions for SAS-OPA coupling  '
+            WRITE(numout,*)'               OPA component  '
+            WRITE(numout,*)
+            WRITE(numout,*)'  received fields from SAS component '
+            WRITE(numout,*)'                  ice cover '
+            WRITE(numout,*)'                  oce only EMP  '
+            WRITE(numout,*)'                  salt flux  '
+            WRITE(numout,*)'                  mixed oce-ice solar flux  '
+            WRITE(numout,*)'                  mixed oce-ice non solar flux  '
+            WRITE(numout,*)'                  wind stress U,V on local grid and sperical coordinates '
+            WRITE(numout,*)'                  wind stress module'
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+      !                                                      ! -------------------------------- !
+      !                                                      !   OPA-SAS coupling - rcv by sas  !   
+      !                                                      ! -------------------------------- !
+      srcv(jpr_toce  )%clname = 'I_SSTSST'
+      srcv(jpr_soce  )%clname = 'I_SSSal'
+      srcv(jpr_ocx1  )%clname = 'I_OCurx1'
+      srcv(jpr_ocy1  )%clname = 'I_OCury1'
+      srcv(jpr_ssh   )%clname = 'I_SSHght'
+      srcv(jpr_e3t1st)%clname = 'I_E3T1st'   
+      srcv(jpr_fraqsr)%clname = 'I_FraQsr'   
+      !
+      IF( nn_components == jp_iam_sas ) THEN
+         IF( .NOT. ln_cpl ) srcv(:)%laction = .FALSE.   ! force default definition in case of opa <-> sas coupling
+         IF( .NOT. ln_cpl ) srcv(:)%clgrid  = 'T'       ! force default definition in case of opa <-> sas coupling
+         IF( .NOT. ln_cpl ) srcv(:)%nsgn    = 1.        ! force default definition in case of opa <-> sas coupling
+         srcv( (/jpr_toce, jpr_soce, jpr_ssh, jpr_fraqsr, jpr_ocx1, jpr_ocy1/) )%laction = .TRUE.
+         srcv( jpr_e3t1st )%laction = .NOT.ln_linssh
+         srcv(jpr_ocx1)%clgrid = 'U'        ! oce components given at U-point
+         srcv(jpr_ocy1)%clgrid = 'V'        !           and           V-point
+         ! Vectors: change of sign at north fold ONLY if on the local grid
+         srcv(jpr_ocx1:jpr_ocy1)%nsgn = -1.
+         ! Change first letter to couple with atmosphere if already coupled OPA
+         ! this is nedeed as each variable name used in the namcouple must be unique:
+         ! for example O_Runoff received by OPA from SAS and therefore O_Runoff received by SAS from the Atmosphere
+         DO jn = 1, jprcv
+            IF ( srcv(jn)%clname(1:1) == "O" ) srcv(jn)%clname = "S"//srcv(jn)%clname(2:LEN(srcv(jn)%clname))
+         END DO
+         !
+         IF(lwp) THEN                        ! control print
+            WRITE(numout,*)
+            WRITE(numout,*)'               Special conditions for SAS-OPA coupling  '
+            WRITE(numout,*)'               SAS component  '
+            WRITE(numout,*)
+            IF( .NOT. ln_cpl ) THEN
+               WRITE(numout,*)'  received fields from OPA component '
+            ELSE
+               WRITE(numout,*)'  Additional received fields from OPA component : '
+            ENDIF
+            WRITE(numout,*)'               sea surface temperature (Celsius) '
+            WRITE(numout,*)'               sea surface salinity ' 
+            WRITE(numout,*)'               surface currents ' 
+            WRITE(numout,*)'               sea surface height ' 
+            WRITE(numout,*)'               thickness of first ocean T level '        
+            WRITE(numout,*)'               fraction of solar net radiation absorbed in the first ocean level'
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+      
+      ! =================================================== !
+      ! Allocate all parts of frcv used for received fields !
+      ! =================================================== !
+      DO jn = 1, jprcv
+         IF ( srcv(jn)%laction ) ALLOCATE( frcv(jn)%z3(jpi,jpj,srcv(jn)%nct) )
+      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(jpr_taum)%nct) )
+      ! Allocate w10m part of frcv which is used even when not received as coupling field
+      IF ( .NOT. srcv(jpr_w10m)%laction ) ALLOCATE( frcv(jpr_w10m)%z3(jpi,jpj,srcv(jpr_w10m)%nct) )
+      ! Allocate jpr_otx1 part of frcv which is used even when not received as coupling field
+      IF ( .NOT. srcv(jpr_otx1)%laction ) ALLOCATE( frcv(jpr_otx1)%z3(jpi,jpj,srcv(jpr_otx1)%nct) )
+      IF ( .NOT. srcv(jpr_oty1)%laction ) ALLOCATE( frcv(jpr_oty1)%z3(jpi,jpj,srcv(jpr_oty1)%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(jpr_itx1)%nct) )
+         IF ( .NOT. srcv(jpr_ity1)%laction ) ALLOCATE( frcv(jpr_ity1)%z3(jpi,jpj,srcv(jpr_ity1)%nct) )
+      END IF
+
+      ! ================================ !
+      !     Define the send interface    !
+      ! ================================ !
+      ! for each field: define the OASIS name                           (ssnd(:)%clname)
+      !                 define send or not from the namelist parameters (ssnd(:)%laction)
+      !                 define the north fold type of lbc               (ssnd(:)%nsgn)
+      
+      ! default definitions of nsnd
+      ssnd(:)%laction = .FALSE.   ;   ssnd(:)%clgrid = 'T'   ;   ssnd(:)%nsgn = 1.  ; ssnd(:)%nct = 1
+         
+      !                                                      ! ------------------------- !
+      !                                                      !    Surface temperature    !
+      !                                                      ! ------------------------- !
+      ssnd(jps_toce)%clname   = 'O_SSTSST'
+      ssnd(jps_tice)%clname   = 'O_TepIce'
+      ssnd(jps_ttilyr)%clname = 'O_TtiLyr'
+      ssnd(jps_tmix)%clname   = 'O_TepMix'
+      SELECT CASE( TRIM( sn_snd_temp%cldes ) )
+      CASE( 'none'                                 )       ! nothing to do
+      CASE( 'oce only'                             )   ;   ssnd( jps_toce )%laction = .TRUE.
+      CASE( 'oce and ice' , 'weighted oce and ice' , 'oce and weighted ice' )
+         ssnd( (/jps_toce, jps_tice/) )%laction = .TRUE.
+         IF ( TRIM( sn_snd_temp%clcat ) == 'yes' )  ssnd(jps_tice)%nct = nn_cats_cpl
+      CASE( 'mixed oce-ice'                        )   ;   ssnd( jps_tmix )%laction = .TRUE.
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_temp%cldes' )
+      END SELECT
+           
+      !                                                      ! ------------------------- !
+      !                                                      !          Albedo           !
+      !                                                      ! ------------------------- !
+      ssnd(jps_albice)%clname = 'O_AlbIce' 
+      ssnd(jps_albmix)%clname = 'O_AlbMix'
+      SELECT CASE( TRIM( sn_snd_alb%cldes ) )
+      CASE( 'none'                 )     ! nothing to do
+      CASE( 'ice' , 'weighted ice' )   ; ssnd(jps_albice)%laction = .TRUE.
+      CASE( 'mixed oce-ice'        )   ; ssnd(jps_albmix)%laction = .TRUE.
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_alb%cldes' )
+      END SELECT
+      !
+      ! Need to calculate oceanic albedo if
+      !     1. sending mixed oce-ice albedo or
+      !     2. receiving mixed oce-ice solar radiation 
+      IF ( TRIM ( sn_snd_alb%cldes ) == 'mixed oce-ice' .OR. TRIM ( sn_rcv_qsr%cldes ) == 'mixed oce-ice' ) THEN
+         CALL oce_alb( zaos, zacs )
+         ! Due to lack of information on nebulosity : mean clear/overcast sky
+         alb_oce_mix(:,:) = ( zacs(:,:) + zaos(:,:) ) * 0.5
+      ENDIF
+      !                                                      ! ------------------------- !
+      !                                                      !  Ice fraction & Thickness ! 
+      !                                                      ! ------------------------- !
+      ssnd(jps_fice)%clname  = 'OIceFrc'
+      ssnd(jps_ficet)%clname = 'OIceFrcT' 
+      ssnd(jps_hice)%clname  = 'OIceTck'
+      ssnd(jps_a_p)%clname   = 'OPndFrc'
+      ssnd(jps_ht_p)%clname  = 'OPndTck'
+      ssnd(jps_hsnw)%clname  = 'OSnwTck'
+      ssnd(jps_fice1)%clname = 'OIceFrd'
+      IF( k_ice /= 0 ) THEN
+         ssnd(jps_fice)%laction  = .TRUE.                 ! if ice treated in the ocean (even in climato case)
+         ssnd(jps_fice1)%laction = .TRUE.                 ! First-order regridded ice concentration, to be used producing atmos-to-ice fluxes (Met Office requirement)
+! Currently no namelist entry to determine sending of multi-category ice fraction so use the thickness entry for now
+         IF ( TRIM( sn_snd_thick%clcat  ) == 'yes' ) ssnd(jps_fice)%nct  = nn_cats_cpl
+         IF ( TRIM( sn_snd_thick1%clcat ) == 'yes' ) ssnd(jps_fice1)%nct = nn_cats_cpl
+      ENDIF
+      
+      IF (TRIM( sn_snd_ifrac%cldes )  == 'coupled') ssnd(jps_ficet)%laction = .TRUE. 
+
+      SELECT CASE ( TRIM( sn_snd_thick%cldes ) )
+      CASE( 'none'         )       ! nothing to do
+      CASE( 'ice and snow' ) 
+         ssnd(jps_hice:jps_hsnw)%laction = .TRUE.
+         IF ( TRIM( sn_snd_thick%clcat ) == 'yes' ) THEN
+            ssnd(jps_hice:jps_hsnw)%nct = nn_cats_cpl
+         ENDIF
+      CASE ( 'weighted ice and snow' ) 
+         ssnd(jps_hice:jps_hsnw)%laction = .TRUE.
+         IF ( TRIM( sn_snd_thick%clcat ) == 'yes' ) ssnd(jps_hice:jps_hsnw)%nct = nn_cats_cpl
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_thick%cldes' )
+      END SELECT
+
+      ! Initialise ice fractions from last coupling time to zero (needed by Met-Office)
+#if defined key_si3 || defined key_cice
+       a_i_last_couple(:,:,:) = 0._wp
+#endif
+      !                                                      ! ------------------------- ! 
+      !                                                      !      Ice Meltponds        ! 
+      !                                                      ! ------------------------- ! 
+      ! Needed by Met Office
+      ssnd(jps_a_p)%clname  = 'OPndFrc'    
+      ssnd(jps_ht_p)%clname = 'OPndTck'    
+      SELECT CASE ( TRIM( sn_snd_mpnd%cldes ) ) 
+      CASE ( 'none' ) 
+         ssnd(jps_a_p)%laction  = .FALSE. 
+         ssnd(jps_ht_p)%laction = .FALSE. 
+      CASE ( 'ice only' )  
+         ssnd(jps_a_p)%laction  = .TRUE. 
+         ssnd(jps_ht_p)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_mpnd%clcat ) == 'yes' ) THEN 
+            ssnd(jps_a_p)%nct  = nn_cats_cpl 
+            ssnd(jps_ht_p)%nct = nn_cats_cpl 
+         ELSE 
+            IF ( nn_cats_cpl > 1 ) THEN 
+               CALL ctl_stop( 'sbc_cpl_init: use weighted ice option for sn_snd_mpnd%cldes if not exchanging category fields' ) 
+            ENDIF 
+         ENDIF 
+      CASE ( 'weighted ice' )  
+         ssnd(jps_a_p)%laction  = .TRUE. 
+         ssnd(jps_ht_p)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_mpnd%clcat ) == 'yes' ) THEN 
+            ssnd(jps_a_p)%nct  = nn_cats_cpl  
+            ssnd(jps_ht_p)%nct = nn_cats_cpl  
+         ENDIF 
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_mpnd%cldes; '//sn_snd_mpnd%cldes ) 
+      END SELECT 
+ 
+      !                                                      ! ------------------------- !
+      !                                                      !      Surface current      !
+      !                                                      ! ------------------------- !
+      !        ocean currents              !            ice velocities
+      ssnd(jps_ocx1)%clname = 'O_OCurx1'   ;   ssnd(jps_ivx1)%clname = 'O_IVelx1'
+      ssnd(jps_ocy1)%clname = 'O_OCury1'   ;   ssnd(jps_ivy1)%clname = 'O_IVely1'
+      ssnd(jps_ocz1)%clname = 'O_OCurz1'   ;   ssnd(jps_ivz1)%clname = 'O_IVelz1'
+      ssnd(jps_ocxw)%clname = 'O_OCurxw' 
+      ssnd(jps_ocyw)%clname = 'O_OCuryw' 
+      !
+      ssnd(jps_ocx1:jps_ivz1)%nsgn = -1.   ! vectors: change of the sign at the north fold
+
+      IF( sn_snd_crt%clvgrd == 'U,V' ) THEN
+         ssnd(jps_ocx1)%clgrid = 'U' ; ssnd(jps_ocy1)%clgrid = 'V'
+      ELSE IF( sn_snd_crt%clvgrd /= 'T' ) THEN  
+         CALL ctl_stop( 'sn_snd_crt%clvgrd must be equal to T' )
+      ENDIF
+      ssnd(jps_ocx1:jps_ivz1)%laction = .TRUE.   ! default: all are send
+      IF( TRIM( sn_snd_crt%clvref ) == 'spherical' )   ssnd( (/jps_ocz1, jps_ivz1/) )%laction = .FALSE. 
+      IF( TRIM( sn_snd_crt%clvor ) == 'eastward-northward' ) ssnd(jps_ocx1:jps_ivz1)%nsgn = 1.
+      SELECT CASE( TRIM( sn_snd_crt%cldes ) )
+      CASE( 'none'                 )   ;   ssnd(jps_ocx1:jps_ivz1)%laction = .FALSE.
+      CASE( 'oce only'             )   ;   ssnd(jps_ivx1:jps_ivz1)%laction = .FALSE.
+      CASE( 'weighted oce and ice' )   !   nothing to do
+      CASE( 'mixed oce-ice'        )   ;   ssnd(jps_ivx1:jps_ivz1)%laction = .FALSE.
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_crt%cldes' )
+      END SELECT
+
+      ssnd(jps_ocxw:jps_ocyw)%nsgn = -1.   ! vectors: change of the sign at the north fold 
+        
+      IF( sn_snd_crtw%clvgrd == 'U,V' ) THEN 
+         ssnd(jps_ocxw)%clgrid = 'U' ; ssnd(jps_ocyw)%clgrid = 'V' 
+      ELSE IF( sn_snd_crtw%clvgrd /= 'T' ) THEN 
+         CALL ctl_stop( 'sn_snd_crtw%clvgrd must be equal to T' ) 
+      ENDIF 
+      IF( TRIM( sn_snd_crtw%clvor ) == 'eastward-northward' ) ssnd(jps_ocxw:jps_ocyw)%nsgn = 1. 
+      SELECT CASE( TRIM( sn_snd_crtw%cldes ) ) 
+         CASE( 'none'                 )   ; ssnd(jps_ocxw:jps_ocyw)%laction = .FALSE. 
+         CASE( 'oce only'             )   ; ssnd(jps_ocxw:jps_ocyw)%laction = .TRUE. 
+         CASE( 'weighted oce and ice' )   !   nothing to do 
+         CASE( 'mixed oce-ice'        )   ; ssnd(jps_ivx1:jps_ivz1)%laction = .FALSE. 
+         CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_crtw%cldes' ) 
+      END SELECT 
+
+      !                                                      ! ------------------------- !
+      !                                                      !          CO2 flux         !
+      !                                                      ! ------------------------- !
+      ssnd(jps_co2)%clname = 'O_CO2FLX' ;  IF( TRIM(sn_snd_co2%cldes) == 'coupled' )    ssnd(jps_co2 )%laction = .TRUE.
+      ! 
+      !                                                      ! ------------------------- ! 
+      !                                                      ! Sea surface freezing temp ! 
+      !                                                      ! ------------------------- ! 
+      ! needed by Met Office
+      ssnd(jps_sstfrz)%clname = 'O_SSTFrz' ; IF( TRIM(sn_snd_sstfrz%cldes) == 'coupled' )  ssnd(jps_sstfrz)%laction = .TRUE. 
+      ! 
+      !                                                      ! ------------------------- ! 
+      !                                                      !    Ice conductivity       ! 
+      !                                                      ! ------------------------- ! 
+      ! needed by Met Office
+      ! Note that ultimately we will move to passing an ocean effective conductivity as well so there 
+      ! will be some changes to the parts of the code which currently relate only to ice conductivity 
+      ssnd(jps_ttilyr )%clname = 'O_TtiLyr' 
+      SELECT CASE ( TRIM( sn_snd_ttilyr%cldes ) ) 
+      CASE ( 'none' ) 
+         ssnd(jps_ttilyr)%laction = .FALSE. 
+      CASE ( 'ice only' ) 
+         ssnd(jps_ttilyr)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_ttilyr%clcat ) == 'yes' ) THEN 
+            ssnd(jps_ttilyr)%nct = nn_cats_cpl 
+         ELSE 
+            IF ( nn_cats_cpl > 1 ) THEN 
+               CALL ctl_stop( 'sbc_cpl_init: use weighted ice option for sn_snd_ttilyr%cldes if not exchanging category fields' ) 
+            ENDIF 
+         ENDIF 
+      CASE ( 'weighted ice' ) 
+         ssnd(jps_ttilyr)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_ttilyr%clcat ) == 'yes' ) ssnd(jps_ttilyr)%nct = nn_cats_cpl 
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_ttilyr%cldes;'//sn_snd_ttilyr%cldes ) 
+      END SELECT 
+
+      ssnd(jps_kice )%clname = 'OIceKn' 
+      SELECT CASE ( TRIM( sn_snd_cond%cldes ) ) 
+      CASE ( 'none' ) 
+         ssnd(jps_kice)%laction = .FALSE. 
+      CASE ( 'ice only' ) 
+         ssnd(jps_kice)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_cond%clcat ) == 'yes' ) THEN 
+            ssnd(jps_kice)%nct = nn_cats_cpl 
+         ELSE 
+            IF ( nn_cats_cpl > 1 ) THEN 
+               CALL ctl_stop( 'sbc_cpl_init: use weighted ice option for sn_snd_cond%cldes if not exchanging category fields' ) 
+            ENDIF 
+         ENDIF 
+      CASE ( 'weighted ice' ) 
+         ssnd(jps_kice)%laction = .TRUE. 
+         IF ( TRIM( sn_snd_cond%clcat ) == 'yes' ) ssnd(jps_kice)%nct = nn_cats_cpl 
+      CASE default   ;   CALL ctl_stop( 'sbc_cpl_init: wrong definition of sn_snd_cond%cldes;'//sn_snd_cond%cldes ) 
+      END SELECT 
+      ! 
+      !                                                      ! ------------------------- ! 
+      !                                                      !     Sea surface height    ! 
+      !                                                      ! ------------------------- ! 
+      ssnd(jps_wlev)%clname = 'O_Wlevel' ;  IF( TRIM(sn_snd_wlev%cldes) == 'coupled' )   ssnd(jps_wlev)%laction = .TRUE. 
+
+      !                                                      ! ------------------------------- !
+      !                                                      !   OPA-SAS coupling - snd by opa !   
+      !                                                      ! ------------------------------- !
+      ssnd(jps_ssh   )%clname = 'O_SSHght' 
+      ssnd(jps_soce  )%clname = 'O_SSSal' 
+      ssnd(jps_e3t1st)%clname = 'O_E3T1st'   
+      ssnd(jps_fraqsr)%clname = 'O_FraQsr'
+      !
+      IF( nn_components == jp_iam_opa ) THEN
+         ssnd(:)%laction = .FALSE.   ! force default definition in case of opa <-> sas coupling
+         ssnd( (/jps_toce, jps_soce, jps_ssh, jps_fraqsr, jps_ocx1, jps_ocy1/) )%laction = .TRUE.
+         ssnd( jps_e3t1st )%laction = .NOT.ln_linssh
+         ! vector definition: not used but cleaner...
+         ssnd(jps_ocx1)%clgrid  = 'U'        ! oce components given at U-point
+         ssnd(jps_ocy1)%clgrid  = 'V'        !           and           V-point
+         sn_snd_crt%clvgrd = 'U,V'
+         sn_snd_crt%clvor = 'local grid'
+         sn_snd_crt%clvref = 'spherical'
+         !
+         IF(lwp) THEN                        ! control print
+            WRITE(numout,*)
+            WRITE(numout,*)'  sent fields to SAS component '
+            WRITE(numout,*)'               sea surface temperature (T before, Celsius) '
+            WRITE(numout,*)'               sea surface salinity ' 
+            WRITE(numout,*)'               surface currents U,V on local grid and spherical coordinates' 
+            WRITE(numout,*)'               sea surface height ' 
+            WRITE(numout,*)'               thickness of first ocean T level '        
+            WRITE(numout,*)'               fraction of solar net radiation absorbed in the first ocean level'
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+      !                                                      ! ------------------------------- !
+      !                                                      !   OPA-SAS coupling - snd by sas !   
+      !                                                      ! ------------------------------- !
+      ssnd(jps_sflx  )%clname = 'I_SFLX'     
+      ssnd(jps_fice2 )%clname = 'IIceFrc'
+      ssnd(jps_qsroce)%clname = 'I_QsrOce'   
+      ssnd(jps_qnsoce)%clname = 'I_QnsOce'   
+      ssnd(jps_oemp  )%clname = 'IOEvaMPr' 
+      ssnd(jps_otx1  )%clname = 'I_OTaux1'   
+      ssnd(jps_oty1  )%clname = 'I_OTauy1'   
+      ssnd(jps_rnf   )%clname = 'I_Runoff'   
+      ssnd(jps_taum  )%clname = 'I_TauMod'   
+      !
+      IF( nn_components == jp_iam_sas ) THEN
+         IF( .NOT. ln_cpl ) ssnd(:)%laction = .FALSE.   ! force default definition in case of opa <-> sas coupling
+         ssnd( (/jps_qsroce, jps_qnsoce, jps_oemp, jps_fice2, jps_sflx, jps_otx1, jps_oty1, jps_taum/) )%laction = .TRUE.
+         !
+         ! Change first letter to couple with atmosphere if already coupled with sea_ice
+         ! this is nedeed as each variable name used in the namcouple must be unique:
+         ! for example O_SSTSST sent by OPA to SAS and therefore S_SSTSST sent by SAS to the Atmosphere
+         DO jn = 1, jpsnd
+            IF ( ssnd(jn)%clname(1:1) == "O" ) ssnd(jn)%clname = "S"//ssnd(jn)%clname(2:LEN(ssnd(jn)%clname))
+         END DO
+         !
+         IF(lwp) THEN                        ! control print
+            WRITE(numout,*)
+            IF( .NOT. ln_cpl ) THEN
+               WRITE(numout,*)'  sent fields to OPA component '
+            ELSE
+               WRITE(numout,*)'  Additional sent fields to OPA component : '
+            ENDIF
+            WRITE(numout,*)'                  ice cover '
+            WRITE(numout,*)'                  oce only EMP  '
+            WRITE(numout,*)'                  salt flux  '
+            WRITE(numout,*)'                  mixed oce-ice solar flux  '
+            WRITE(numout,*)'                  mixed oce-ice non solar flux  '
+            WRITE(numout,*)'                  wind stress U,V components'
+            WRITE(numout,*)'                  wind stress module'
+         ENDIF
+      ENDIF
+
+      !
+      ! ================================ !
+      !   initialisation of the coupler  !
+      ! ================================ !
+
+      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
+      xcplmask(:,:,0) = 1. - SUM( xcplmask(:,:,1:nn_cplmodel), dim = 3 )
+      !
+   END SUBROUTINE sbc_cpl_init
+
+
+   SUBROUTINE sbc_cpl_rcv( kt, k_fsbc, k_ice )     
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_cpl_rcv  ***
+      !!
+      !! ** Purpose :   provide the stress over the ocean and, if no sea-ice,
+      !!                provide the ocean heat and freshwater fluxes.
+      !!
+      !! ** Method  : - Receive all the atmospheric fields (stored in frcv array). called at each time step.
+      !!                OASIS controls if there is something do receive or not. nrcvinfo contains the info
+      !!                to know if the field was really received or not
+      !!
+      !!              --> If ocean stress was really received:
+      !!
+      !!                  - transform the received ocean stress vector from the received
+      !!                 referential and grid into an atmosphere-ocean stress in 
+      !!                 the (i,j) ocean referencial and at the ocean velocity point. 
+      !!                    The received stress are :
+      !!                     - defined by 3 components (if cartesian coordinate)
+      !!                            or by 2 components (if spherical)
+      !!                     - oriented along geographical   coordinate (if eastward-northward)
+      !!                            or  along the local grid coordinate (if local grid)
+      !!                     - given at U- and V-point, resp.   if received on 2 grids
+      !!                            or at T-point               if received on 1 grid
+      !!                    Therefore and if necessary, they are successively 
+      !!                  processed in order to obtain them 
+      !!                     first  as  2 components on the sphere 
+      !!                     second as  2 components oriented along the local grid
+      !!                     third  as  2 components on the U,V grid 
+      !!
+      !!              --> 
+      !!
+      !!              - In 'ocean only' case, non solar and solar ocean heat fluxes 
+      !!             and total ocean freshwater fluxes  
+      !!
+      !! ** Method  :   receive all fields from the atmosphere and transform 
+      !!              them into ocean surface boundary condition fields 
+      !!
+      !! ** Action  :   update  utau, vtau   ocean stress at U,V grid 
+      !!                        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
+      !!                        qsr          solar ocean heat fluxes   (ocean only case)
+      !!                        emp          upward mass flux [evap. - precip. (- runoffs) (- calving)] (ocean only case)
+      !!----------------------------------------------------------------------
+      USE zdf_oce,  ONLY :   ln_zdfswm
+      !
+      INTEGER, INTENT(in) ::   kt          ! ocean model time step index
+      INTEGER, INTENT(in) ::   k_fsbc      ! frequency of sbc (-> ice model) computation 
+      INTEGER, INTENT(in) ::   k_ice       ! ice management in the sbc (=0/1/2/3)
+      !!
+      LOGICAL  ::   llnewtx, llnewtau      ! update wind stress components and module??
+      INTEGER  ::   ji, jj, jn             ! dummy loop indices
+      INTEGER  ::   isec                   ! number of seconds since nit000 (assuming rdt did not change since nit000)
+      REAL(wp) ::   zcumulneg, zcumulpos   ! temporary scalars     
+      REAL(wp) ::   zcoef                  ! temporary scalar
+      REAL(wp) ::   zrhoa  = 1.22          ! Air density kg/m3
+      REAL(wp) ::   zcdrag = 1.5e-3        ! drag coefficient
+      REAL(wp) ::   zzx, zzy               ! temporary variables
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztx, zty, zmsk, zemp, zqns, zqsr, zcloud_fra
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+      !   cannot be done in the init phase when we use agrif as cpl_freq requires that oasis_enddef is done
+         ncpl_qsr_freq = cpl_freq( 'O_QsrOce' ) + cpl_freq( 'O_QsrMix' ) + cpl_freq( 'I_QsrOce' ) + cpl_freq( 'I_QsrMix' )
+         IF( ln_dm2dc .AND. ncpl_qsr_freq /= 86400 )   &
+            &   CALL ctl_stop( 'sbc_cpl_rcv: diurnal cycle reconstruction (ln_dm2dc) needs daily couping for solar radiation' )
+         ncpl_qsr_freq = 86400 / ncpl_qsr_freq   ! used by top
+      ENDIF
+      !
+      IF( ln_mixcpl )   zmsk(:,:) = 1. - xcplmask(:,:,0)
+      !
+      !                                                      ! ======================================================= !
+      !                                                      ! Receive all the atmos. fields (including ice information)
+      !                                                      ! ======================================================= !
+      isec = ( kt - nit000 ) * NINT( rdt )                      ! date of exchanges
+      DO jn = 1, jprcv                                          ! received fields sent by the atmosphere
+         IF( srcv(jn)%laction )   CALL cpl_rcv( jn, isec, frcv(jn)%z3, xcplmask(:,:,1:nn_cplmodel), nrcvinfo(jn) )
+      END DO
+
+      !                                                      ! ========================= !
+      IF( srcv(jpr_otx1)%laction ) THEN                      !  ocean stress components  !
+         !                                                   ! ========================= !
+         ! define frcv(jpr_otx1)%z3(:,:,1) and frcv(jpr_oty1)%z3(:,:,1): stress at U/V point along model grid
+         ! => need to be done only when we receive the field
+         IF(  nrcvinfo(jpr_otx1) == OASIS_Rcv ) THEN
+            !
+            IF( TRIM( sn_rcv_tau%clvref ) == 'cartesian' ) THEN            ! 2 components on the sphere
+               !                                                       ! (cartesian to spherical -> 3 to 2 components)
+               !
+               CALL geo2oce( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), frcv(jpr_otz1)%z3(:,:,1),   &
+                  &          srcv(jpr_otx1)%clgrid, ztx, zty )
+               frcv(jpr_otx1)%z3(:,:,1) = ztx(:,:)   ! overwrite 1st comp. on the 1st grid
+               frcv(jpr_oty1)%z3(:,:,1) = zty(:,:)   ! overwrite 2nd comp. on the 1st grid
+               !
+               IF( srcv(jpr_otx2)%laction ) THEN
+                  CALL geo2oce( frcv(jpr_otx2)%z3(:,:,1), frcv(jpr_oty2)%z3(:,:,1), frcv(jpr_otz2)%z3(:,:,1),   &
+                     &          srcv(jpr_otx2)%clgrid, ztx, zty )
+                  frcv(jpr_otx2)%z3(:,:,1) = ztx(:,:)   ! overwrite 1st comp. on the 2nd grid
+                  frcv(jpr_oty2)%z3(:,:,1) = zty(:,:)   ! overwrite 2nd comp. on the 2nd grid
+               ENDIF
+               !
+            ENDIF
+            !
+            IF( TRIM( sn_rcv_tau%clvor ) == 'eastward-northward' ) THEN   ! 2 components oriented along the local grid
+               !                                                       ! (geographical to local grid -> rotate the components)
+               CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->i', ztx )   
+               IF( srcv(jpr_otx2)%laction ) THEN
+                  CALL rot_rep( frcv(jpr_otx2)%z3(:,:,1), frcv(jpr_oty2)%z3(:,:,1), srcv(jpr_otx2)%clgrid, 'en->j', zty )   
+               ELSE
+                  CALL rot_rep( frcv(jpr_otx1)%z3(:,:,1), frcv(jpr_oty1)%z3(:,:,1), srcv(jpr_otx1)%clgrid, 'en->j', zty )  
+               ENDIF
+               frcv(jpr_otx1)%z3(:,:,1) = ztx(:,:)      ! overwrite 1st component on the 1st grid
+               frcv(jpr_oty1)%z3(:,:,1) = zty(:,:)      ! overwrite 2nd component on the 2nd grid
+            ENDIF
+            !                              
+            IF( srcv(jpr_otx1)%clgrid == 'T' ) THEN
+               DO jj = 2, jpjm1                                          ! T ==> (U,V)
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     frcv(jpr_otx1)%z3(ji,jj,1) = 0.5 * ( frcv(jpr_otx1)%z3(ji+1,jj  ,1) + frcv(jpr_otx1)%z3(ji,jj,1) )
+                     frcv(jpr_oty1)%z3(ji,jj,1) = 0.5 * ( frcv(jpr_oty1)%z3(ji  ,jj+1,1) + frcv(jpr_oty1)%z3(ji,jj,1) )
+                  END DO
+               END DO
+               CALL lbc_lnk_multi( 'sbccpl', frcv(jpr_otx1)%z3(:,:,1), 'U',  -1., frcv(jpr_oty1)%z3(:,:,1), 'V',  -1. )
+            ENDIF
+            llnewtx = .TRUE.
+         ELSE
+            llnewtx = .FALSE.
+         ENDIF
+         !                                                   ! ========================= !
+      ELSE                                                   !   No dynamical coupling   !
+         !                                                   ! ========================= !
+         frcv(jpr_otx1)%z3(:,:,1) = 0.e0                               ! here simply set to zero 
+         frcv(jpr_oty1)%z3(:,:,1) = 0.e0                               ! an external read in a file can be added instead
+         llnewtx = .TRUE.
+         !
+      ENDIF
+      !                                                      ! ========================= !
+      !                                                      !    wind stress module     !   (taum)
+      !                                                      ! ========================= !
+      IF( .NOT. srcv(jpr_taum)%laction ) THEN                    ! compute wind stress module from its components if not received 
+         ! => need to be done only when otx1 was changed
+         IF( llnewtx ) THEN
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vect. opt.
+                  zzx = frcv(jpr_otx1)%z3(ji-1,jj  ,1) + frcv(jpr_otx1)%z3(ji,jj,1)
+                  zzy = frcv(jpr_oty1)%z3(ji  ,jj-1,1) + frcv(jpr_oty1)%z3(ji,jj,1)
+                  frcv(jpr_taum)%z3(ji,jj,1) = 0.5 * SQRT( zzx * zzx + zzy * zzy )
+               END DO
+            END DO
+            CALL lbc_lnk( 'sbccpl', frcv(jpr_taum)%z3(:,:,1), 'T', 1. )
+            llnewtau = .TRUE.
+         ELSE
+            llnewtau = .FALSE.
+         ENDIF
+      ELSE
+         llnewtau = nrcvinfo(jpr_taum) == OASIS_Rcv
+         ! Stress module can be negative when received (interpolation problem)
+         IF( llnewtau ) THEN 
+            frcv(jpr_taum)%z3(:,:,1) = MAX( 0._wp, frcv(jpr_taum)%z3(:,:,1) )
+         ENDIF
+      ENDIF
+      !
+      !                                                      ! ========================= !
+      !                                                      !      10 m wind speed      !   (wndm)
+      !                                                      ! ========================= !
+      IF( .NOT. srcv(jpr_w10m)%laction ) THEN                    ! compute wind spreed from wind stress module if not received  
+         ! => need to be done only when taumod was changed
+         IF( llnewtau ) THEN 
+            zcoef = 1. / ( zrhoa * zcdrag ) 
+            DO jj = 1, jpj
+               DO ji = 1, jpi 
+                  frcv(jpr_w10m)%z3(ji,jj,1) = SQRT( frcv(jpr_taum)%z3(ji,jj,1) * zcoef )
+               END DO
+            END DO
+         ENDIF
+      ENDIF
+!!$      !                                                      ! ========================= !
+!!$      SELECT CASE( TRIM( sn_rcv_clouds%cldes ) )             !       cloud fraction      !
+!!$      !                                                      ! ========================= !
+!!$      cloud_fra(:,:) = frcv(jpr_clfra)*z3(:,:,1)
+!!$      END SELECT
+!!$
+      zcloud_fra(:,:) = pp_cldf   ! should be real cloud fraction instead (as in the bulk) but needs to be read from atm.
+      IF( ln_mixcpl ) THEN
+         cloud_fra(:,:) = cloud_fra(:,:) * xcplmask(:,:,0) + zcloud_fra(:,:)* zmsk(:,:)
+      ELSE
+         cloud_fra(:,:) = zcloud_fra(:,:)
+      ENDIF
+      !                                                      ! ========================= !
+      ! u(v)tau and taum will be modified by ice model
+      ! -> need to be reset before each call of the ice/fsbc      
+      IF( MOD( kt-1, k_fsbc ) == 0 ) THEN
+         !
+         IF( ln_mixcpl ) THEN
+            utau(:,:) = utau(:,:) * xcplmask(:,:,0) + frcv(jpr_otx1)%z3(:,:,1) * zmsk(:,:)
+            vtau(:,:) = vtau(:,:) * xcplmask(:,:,0) + frcv(jpr_oty1)%z3(:,:,1) * zmsk(:,:)
+            taum(:,:) = taum(:,:) * xcplmask(:,:,0) + frcv(jpr_taum)%z3(:,:,1) * zmsk(:,:)
+            wndm(:,:) = wndm(:,:) * xcplmask(:,:,0) + frcv(jpr_w10m)%z3(:,:,1) * zmsk(:,:)
+         ELSE
+            utau(:,:) = frcv(jpr_otx1)%z3(:,:,1)
+            vtau(:,:) = frcv(jpr_oty1)%z3(:,:,1)
+            taum(:,:) = frcv(jpr_taum)%z3(:,:,1)
+            wndm(:,:) = frcv(jpr_w10m)%z3(:,:,1)
+         ENDIF
+         CALL iom_put( "taum_oce", taum )   ! output wind stress module
+         !  
+      ENDIF
+
+      !                                                      ! ================== !
+      !                                                      ! atmosph. CO2 (ppm) !
+      !                                                      ! ================== !
+      IF( srcv(jpr_co2)%laction )   atm_co2(:,:) = frcv(jpr_co2)%z3(:,:,1)
+      !
+      !                                                      ! ========================= ! 
+      !                                                      ! Mean Sea Level Pressure   !   (taum) 
+      !                                                      ! ========================= ! 
+      IF( srcv(jpr_mslp)%laction ) THEN                    ! UKMO SHELF effect of atmospheric pressure on SSH 
+          IF( kt /= nit000 )   ssh_ibb(:,:) = ssh_ib(:,:)    !* Swap of ssh_ib fields 
+
+          r1_grau = 1.e0 / (grav * rau0)               !* constant for optimization 
+          ssh_ib(:,:) = - ( frcv(jpr_mslp)%z3(:,:,1) - rpref ) * r1_grau    ! equivalent ssh (inverse barometer) 
+          apr   (:,:) =     frcv(jpr_mslp)%z3(:,:,1)                         !atmospheric pressure 
+    
+          IF( kt == nit000 ) ssh_ibb(:,:) = ssh_ib(:,:)  ! correct this later (read from restart if possible) 
+      END IF 
+      !
+      IF( ln_sdw ) THEN  ! Stokes Drift correction activated
+      !                                                      ! ========================= ! 
+      !                                                      !       Stokes drift u      !
+      !                                                      ! ========================= ! 
+         IF( srcv(jpr_sdrftx)%laction ) ut0sd(:,:) = frcv(jpr_sdrftx)%z3(:,:,1)
+      !
+      !                                                      ! ========================= ! 
+      !                                                      !       Stokes drift v      !
+      !                                                      ! ========================= ! 
+         IF( srcv(jpr_sdrfty)%laction ) vt0sd(:,:) = frcv(jpr_sdrfty)%z3(:,:,1)
+      !
+      !                                                      ! ========================= ! 
+      !                                                      !      Wave mean period     !
+      !                                                      ! ========================= ! 
+         IF( srcv(jpr_wper)%laction ) wmp(:,:) = frcv(jpr_wper)%z3(:,:,1)
+      !
+      !                                                      ! ========================= ! 
+      !                                                      !  Significant wave height  !
+      !                                                      ! ========================= ! 
+         IF( srcv(jpr_hsig)%laction ) hsw(:,:) = frcv(jpr_hsig)%z3(:,:,1)
+      ! 
+      !                                                      ! ========================= !  
+      !                                                      !    Wave peak frequency    ! 
+      !                                                      ! ========================= !  
+         IF( srcv(jpr_wfreq)%laction ) wfreq(:,:) = frcv(jpr_wfreq)%z3(:,:,1)
+      !
+      !                                                      ! ========================= ! 
+      !                                                      !    Vertical mixing Qiao   !
+      !                                                      ! ========================= ! 
+         IF( srcv(jpr_wnum)%laction .AND. ln_zdfswm ) wnum(:,:) = frcv(jpr_wnum)%z3(:,:,1)
+
+         ! Calculate the 3D Stokes drift both in coupled and not fully uncoupled mode
+         IF( srcv(jpr_sdrftx)%laction .OR. srcv(jpr_sdrfty)%laction .OR. srcv(jpr_wper)%laction &
+                                      .OR. srcv(jpr_hsig)%laction   .OR. srcv(jpr_wfreq)%laction) THEN
+            CALL sbc_stokes()
+         ENDIF
+      ENDIF
+      !                                                      ! ========================= ! 
+      !                                                      ! Stress adsorbed by waves  !
+      !                                                      ! ========================= ! 
+      IF( srcv(jpr_tauwoc)%laction .AND. ln_tauwoc ) tauoc_wave(:,:) = frcv(jpr_tauwoc)%z3(:,:,1)
+
+      !                                                      ! ========================= !  
+      !                                                      ! Stress component by waves ! 
+      !                                                      ! ========================= !  
+      IF( srcv(jpr_tauwx)%laction .AND. srcv(jpr_tauwy)%laction .AND. ln_tauw ) THEN
+         tauw_x(:,:) = frcv(jpr_tauwx)%z3(:,:,1)
+         tauw_y(:,:) = frcv(jpr_tauwy)%z3(:,:,1)
+      ENDIF
+
+      !                                                      ! ========================= ! 
+      !                                                      !   Wave drag coefficient   !
+      !                                                      ! ========================= ! 
+      IF( srcv(jpr_wdrag)%laction .AND. ln_cdgw )   cdn_wave(:,:) = frcv(jpr_wdrag)%z3(:,:,1)
+
+      !  Fields received by SAS when OASIS coupling
+      !  (arrays no more filled at sbcssm stage)
+      !                                                      ! ================== !
+      !                                                      !        SSS         !
+      !                                                      ! ================== !
+      IF( srcv(jpr_soce)%laction ) THEN                      ! received by sas in case of opa <-> sas coupling
+         sss_m(:,:) = frcv(jpr_soce)%z3(:,:,1)
+         CALL iom_put( 'sss_m', sss_m )
+      ENDIF
+      !                                               
+      !                                                      ! ================== !
+      !                                                      !        SST         !
+      !                                                      ! ================== !
+      IF( srcv(jpr_toce)%laction ) THEN                      ! received by sas in case of opa <-> sas coupling
+         sst_m(:,:) = frcv(jpr_toce)%z3(:,:,1)
+         IF( srcv(jpr_soce)%laction .AND. l_useCT ) THEN    ! make sure that sst_m is the potential temperature
+            sst_m(:,:) = eos_pt_from_ct( sst_m(:,:), sss_m(:,:) )
+         ENDIF
+      ENDIF
+      !                                                      ! ================== !
+      !                                                      !        SSH         !
+      !                                                      ! ================== !
+      IF( srcv(jpr_ssh )%laction ) THEN                      ! received by sas in case of opa <-> sas coupling
+         ssh_m(:,:) = frcv(jpr_ssh )%z3(:,:,1)
+         CALL iom_put( 'ssh_m', ssh_m )
+      ENDIF
+      !                                                      ! ================== !
+      !                                                      !  surface currents  !
+      !                                                      ! ================== !
+      IF( srcv(jpr_ocx1)%laction ) THEN                      ! received by sas in case of opa <-> sas coupling
+         ssu_m(:,:) = frcv(jpr_ocx1)%z3(:,:,1)
+         ub (:,:,1) = ssu_m(:,:)                             ! will be used in icestp in the call of ice_forcing_tau
+         un (:,:,1) = ssu_m(:,:)                             ! will be used in sbc_cpl_snd if atmosphere coupling
+         CALL iom_put( 'ssu_m', ssu_m )
+      ENDIF
+      IF( srcv(jpr_ocy1)%laction ) THEN
+         ssv_m(:,:) = frcv(jpr_ocy1)%z3(:,:,1)
+         vb (:,:,1) = ssv_m(:,:)                             ! will be used in icestp in the call of ice_forcing_tau
+         vn (:,:,1) = ssv_m(:,:)                             ! will be used in sbc_cpl_snd if atmosphere coupling
+         CALL iom_put( 'ssv_m', ssv_m )
+      ENDIF
+      !                                                      ! ======================== !
+      !                                                      !  first T level thickness !
+      !                                                      ! ======================== !
+      IF( srcv(jpr_e3t1st )%laction ) THEN                   ! received by sas in case of opa <-> sas coupling
+         e3t_m(:,:) = frcv(jpr_e3t1st )%z3(:,:,1)
+         CALL iom_put( 'e3t_m', e3t_m(:,:) )
+      ENDIF
+      !                                                      ! ================================ !
+      !                                                      !  fraction of solar net radiation !
+      !                                                      ! ================================ !
+      IF( srcv(jpr_fraqsr)%laction ) THEN                    ! received by sas in case of opa <-> sas coupling
+         frq_m(:,:) = frcv(jpr_fraqsr)%z3(:,:,1)
+         CALL iom_put( 'frq_m', frq_m )
+      ENDIF
+      
+      !                                                      ! ========================= !
+      IF( k_ice <= 1 .AND. MOD( kt-1, k_fsbc ) == 0 ) THEN   !  heat & freshwater fluxes ! (Ocean only case)
+         !                                                   ! ========================= !
+         !
+         !                                                       ! total freshwater fluxes over the ocean (emp)
+         IF( srcv(jpr_oemp)%laction .OR. srcv(jpr_rain)%laction ) THEN
+            SELECT CASE( TRIM( sn_rcv_emp%cldes ) )                                    ! evaporation - precipitation
+            CASE( 'conservative' )
+               zemp(:,:) = frcv(jpr_tevp)%z3(:,:,1) - ( frcv(jpr_rain)%z3(:,:,1) + frcv(jpr_snow)%z3(:,:,1) )
+            CASE( 'oce only', 'oce and ice' )
+               zemp(:,:) = frcv(jpr_oemp)%z3(:,:,1)
+            CASE default
+               CALL ctl_stop( 'sbc_cpl_rcv: wrong definition of sn_rcv_emp%cldes' )
+            END SELECT
+         ELSE
+            zemp(:,:) = 0._wp
+         ENDIF
+         !
+         !                                                        ! runoffs and calving (added in emp)
+         IF( srcv(jpr_rnf)%laction )     rnf(:,:) = frcv(jpr_rnf)%z3(:,:,1)
+         IF( srcv(jpr_cal)%laction )     zemp(:,:) = zemp(:,:) - frcv(jpr_cal)%z3(:,:,1)
+ 
+         IF( srcv(jpr_icb)%laction )  THEN 
+             fwficb(:,:) = frcv(jpr_icb)%z3(:,:,1)
+             rnf(:,:)    = rnf(:,:) + fwficb(:,:)   ! iceberg added to runfofs
+         ENDIF
+         IF( srcv(jpr_isf)%laction )  fwfisf(:,:) = - frcv(jpr_isf)%z3(:,:,1)  ! fresh water flux from the isf (fwfisf <0 mean melting)  
+        
+         IF( ln_mixcpl ) THEN   ;   emp(:,:) = emp(:,:) * xcplmask(:,:,0) + zemp(:,:) * zmsk(:,:)
+         ELSE                   ;   emp(:,:) =                              zemp(:,:)
+         ENDIF
+         !
+         !                                                       ! non solar heat flux over the ocean (qns)
+         IF(      srcv(jpr_qnsoce)%laction ) THEN   ;   zqns(:,:) = frcv(jpr_qnsoce)%z3(:,:,1)
+         ELSE IF( srcv(jpr_qnsmix)%laction ) THEN   ;   zqns(:,:) = frcv(jpr_qnsmix)%z3(:,:,1)
+         ELSE                                       ;   zqns(:,:) = 0._wp
+         END IF
+         ! update qns over the free ocean with:
+         IF( nn_components /= jp_iam_opa ) THEN
+            zqns(:,:) =  zqns(:,:) - zemp(:,:) * sst_m(:,:) * rcp         ! remove heat content due to mass flux (assumed to be at SST)
+            IF( srcv(jpr_snow  )%laction ) THEN
+               zqns(:,:) = zqns(:,:) - frcv(jpr_snow)%z3(:,:,1) * rLfus   ! energy for melting solid precipitation over the free ocean
+            ENDIF
+         ENDIF
+         !
+         IF( srcv(jpr_icb)%laction )  zqns(:,:) = zqns(:,:) - frcv(jpr_icb)%z3(:,:,1) * rLfus ! remove heat content associated to iceberg melting
+         !
+         IF( ln_mixcpl ) THEN   ;   qns(:,:) = qns(:,:) * xcplmask(:,:,0) + zqns(:,:) * zmsk(:,:)
+         ELSE                   ;   qns(:,:) =                              zqns(:,:)
+         ENDIF
+
+         !                                                       ! solar flux over the ocean          (qsr)
+         IF     ( srcv(jpr_qsroce)%laction ) THEN   ;   zqsr(:,:) = frcv(jpr_qsroce)%z3(:,:,1)
+         ELSE IF( srcv(jpr_qsrmix)%laction ) then   ;   zqsr(:,:) = frcv(jpr_qsrmix)%z3(:,:,1)
+         ELSE                                       ;   zqsr(:,:) = 0._wp
+         ENDIF
+         IF( ln_dm2dc .AND. ln_cpl )   zqsr(:,:) = sbc_dcy( zqsr )   ! modify qsr to include the diurnal cycle
+         IF( ln_mixcpl ) THEN   ;   qsr(:,:) = qsr(:,:) * xcplmask(:,:,0) + zqsr(:,:) * zmsk(:,:)
+         ELSE                   ;   qsr(:,:) =                              zqsr(:,:)
+         ENDIF
+         !
+         ! salt flux over the ocean (received by opa in case of opa <-> sas coupling)
+         IF( srcv(jpr_sflx )%laction )   sfx(:,:) = frcv(jpr_sflx  )%z3(:,:,1)
+         ! Ice cover  (received by opa in case of opa <-> sas coupling)
+         IF( srcv(jpr_fice )%laction )   fr_i(:,:) = frcv(jpr_fice )%z3(:,:,1)
+         !
+      ENDIF
+      !
+   END SUBROUTINE sbc_cpl_rcv
+   
+
+   SUBROUTINE sbc_cpl_ice_tau( p_taui, p_tauj )     
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_cpl_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the stress over sea-ice in coupled mode 
+      !!
+      !! ** Method  :   transform the received stress from the atmosphere into
+      !!             an atmosphere-ice stress in the (i,j) ocean referencial
+      !!             and at the velocity point of the sea-ice model:
+      !!                'C'-grid : i- (j-) components given at U- (V-) point 
+      !!
+      !!                The received stress are :
+      !!                 - defined by 3 components (if cartesian coordinate)
+      !!                        or by 2 components (if spherical)
+      !!                 - oriented along geographical   coordinate (if eastward-northward)
+      !!                        or  along the local grid coordinate (if local grid)
+      !!                 - given at U- and V-point, resp.   if received on 2 grids
+      !!                        or at a same point (T or I) if received on 1 grid
+      !!                Therefore and if necessary, they are successively 
+      !!             processed in order to obtain them 
+      !!                 first  as  2 components on the sphere 
+      !!                 second as  2 components oriented along the local grid
+      !!                 third  as  2 components on the ice grid point 
+      !!
+      !!                Except in 'oce and ice' case, only one vector stress field 
+      !!             is received. It has already been processed in sbc_cpl_rcv
+      !!             so that it is now defined as (i,j) components given at U-
+      !!             and V-points, respectively.  
+      !!
+      !! ** Action  :   return ptau_i, ptau_j, the stress over the ice
+      !!----------------------------------------------------------------------
+      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)
+      !!
+      INTEGER ::   ji, jj   ! dummy loop indices
+      INTEGER ::   itx      ! index of taux over ice
+      REAL(wp)                     ::   zztmp1, zztmp2
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztx, zty 
+      !!----------------------------------------------------------------------
+      !
+      IF( srcv(jpr_itx1)%laction ) THEN   ;   itx =  jpr_itx1   
+      ELSE                                ;   itx =  jpr_otx1
+      ENDIF
+
+      ! do something only if we just received the stress from atmosphere
+      IF(  nrcvinfo(itx) == OASIS_Rcv ) THEN
+         !                                                      ! ======================= !
+         IF( srcv(jpr_itx1)%laction ) THEN                      !   ice stress received   !
+            !                                                   ! ======================= !
+            !  
+            IF( TRIM( sn_rcv_tau%clvref ) == 'cartesian' ) THEN            ! 2 components on the sphere
+               !                                                       ! (cartesian to spherical -> 3 to 2 components)
+               CALL geo2oce(  frcv(jpr_itx1)%z3(:,:,1), frcv(jpr_ity1)%z3(:,:,1), frcv(jpr_itz1)%z3(:,:,1),   &
+                  &          srcv(jpr_itx1)%clgrid, ztx, zty )
+               frcv(jpr_itx1)%z3(:,:,1) = ztx(:,:)   ! overwrite 1st comp. on the 1st grid
+               frcv(jpr_ity1)%z3(:,:,1) = zty(:,:)   ! overwrite 2nd comp. on the 1st grid
+               !
+               IF( srcv(jpr_itx2)%laction ) THEN
+                  CALL geo2oce( frcv(jpr_itx2)%z3(:,:,1), frcv(jpr_ity2)%z3(:,:,1), frcv(jpr_itz2)%z3(:,:,1),   &
+                     &          srcv(jpr_itx2)%clgrid, ztx, zty )
+                  frcv(jpr_itx2)%z3(:,:,1) = ztx(:,:)   ! overwrite 1st comp. on the 2nd grid
+                  frcv(jpr_ity2)%z3(:,:,1) = zty(:,:)   ! overwrite 2nd comp. on the 2nd grid
+               ENDIF
+               !
+            ENDIF
+            !
+            IF( TRIM( sn_rcv_tau%clvor ) == 'eastward-northward' ) THEN   ! 2 components oriented along the local grid
+               !                                                       ! (geographical to local grid -> rotate the components)
+               CALL rot_rep( frcv(jpr_itx1)%z3(:,:,1), frcv(jpr_ity1)%z3(:,:,1), srcv(jpr_itx1)%clgrid, 'en->i', ztx )   
+               IF( srcv(jpr_itx2)%laction ) THEN
+                  CALL rot_rep( frcv(jpr_itx2)%z3(:,:,1), frcv(jpr_ity2)%z3(:,:,1), srcv(jpr_itx2)%clgrid, 'en->j', zty )   
+               ELSE
+                  CALL rot_rep( frcv(jpr_itx1)%z3(:,:,1), frcv(jpr_ity1)%z3(:,:,1), srcv(jpr_itx1)%clgrid, 'en->j', zty )  
+               ENDIF
+               frcv(jpr_itx1)%z3(:,:,1) = ztx(:,:)      ! overwrite 1st component on the 1st grid
+               frcv(jpr_ity1)%z3(:,:,1) = zty(:,:)      ! overwrite 2nd component on the 1st grid
+            ENDIF
+            !                                                   ! ======================= !
+         ELSE                                                   !     use ocean stress    !
+            !                                                   ! ======================= !
+            frcv(jpr_itx1)%z3(:,:,1) = frcv(jpr_otx1)%z3(:,:,1)
+            frcv(jpr_ity1)%z3(:,:,1) = frcv(jpr_oty1)%z3(:,:,1)
+            !
+         ENDIF
+         !                                                      ! ======================= !
+         !                                                      !     put on ice grid     !
+         !                                                      ! ======================= !
+         !    
+         !                                                  j+1   j     -----V---F
+         ! ice stress on ice velocity point                              !       |
+         ! (C-grid ==>(U,V))                                      j      |   T   U
+         !                                                               |       |
+         !                                                   j    j-1   -I-------|
+         !                                               (for I)         |       |
+         !                                                              i-1  i   i
+         !                                                               i      i+1 (for I)
+         SELECT CASE ( srcv(jpr_itx1)%clgrid )
+         CASE( 'U' )
+            p_taui(:,:) = frcv(jpr_itx1)%z3(:,:,1)                   ! (U,V) ==> (U,V)
+            p_tauj(:,:) = frcv(jpr_ity1)%z3(:,:,1)
+         CASE( 'T' )
+            DO jj = 2, jpjm1                                   ! T ==> (U,V)
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ! take care of the land-sea mask to avoid "pollution" of coastal stress. p[uv]taui used in frazil and  rheology 
+                  zztmp1 = 0.5_wp * ( 2. - umask(ji,jj,1) ) * MAX( tmask(ji,jj,1),tmask(ji+1,jj  ,1) )
+                  zztmp2 = 0.5_wp * ( 2. - vmask(ji,jj,1) ) * MAX( tmask(ji,jj,1),tmask(ji  ,jj+1,1) )
+                  p_taui(ji,jj) = zztmp1 * ( frcv(jpr_itx1)%z3(ji+1,jj  ,1) + frcv(jpr_itx1)%z3(ji,jj,1) )
+                  p_tauj(ji,jj) = zztmp2 * ( frcv(jpr_ity1)%z3(ji  ,jj+1,1) + frcv(jpr_ity1)%z3(ji,jj,1) )
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'sbccpl', p_taui, 'U',  -1., p_tauj, 'V',  -1. )
+         END SELECT
+         
+      ENDIF
+      !
+   END SUBROUTINE sbc_cpl_ice_tau
+   
+
+   SUBROUTINE sbc_cpl_ice_flx( picefr, palbi, psst, pist, phs, phi )
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_cpl_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the heat and freshwater fluxes of the ocean-ice system
+      !!
+      !! ** Method  :   transform the fields received from the atmosphere into
+      !!             surface heat and fresh water boundary condition for the 
+      !!             ice-ocean system. The following fields are provided:
+      !!               * total non solar, solar and freshwater fluxes (qns_tot, 
+      !!             qsr_tot and emp_tot) (total means weighted ice-ocean flux)
+      !!             NB: emp_tot include runoffs and calving.
+      !!               * fluxes over ice (qns_ice, qsr_ice, emp_ice) where
+      !!             emp_ice = sublimation - solid precipitation as liquid
+      !!             precipitation are re-routed directly to the ocean and 
+      !!             calving directly enter the ocean (runoffs are read but included in trasbc.F90)
+      !!               * solid precipitation (sprecip), used to add to qns_tot 
+      !!             the heat lost associated to melting solid precipitation
+      !!             over the ocean fraction.
+      !!               * heat content of rain, snow and evap can also be provided,
+      !!             otherwise heat flux associated with these mass flux are
+      !!             guessed (qemp_oce, qemp_ice)
+      !!
+      !!             - the fluxes have been separated from the stress as
+      !!               (a) they are updated at each ice time step compare to
+      !!               an update at each coupled time step for the stress, and
+      !!               (b) the conservative computation of the fluxes over the
+      !!               sea-ice area requires the knowledge of the ice fraction
+      !!               after the ice advection and before the ice thermodynamics,
+      !!               so that the stress is updated before the ice dynamics
+      !!               while the fluxes are updated after it.
+      !!
+      !! ** Details
+      !!             qns_tot = (1-a) * qns_oce + a * qns_ice               => provided
+      !!                     + qemp_oce + qemp_ice                         => recalculated and added up to qns
+      !!
+      !!             qsr_tot = (1-a) * qsr_oce + a * qsr_ice               => provided
+      !!
+      !!             emp_tot = emp_oce + emp_ice                           => calving is provided and added to emp_tot (and emp_oce).
+      !!                                                                      runoff (which includes rivers+icebergs) and iceshelf
+      !!                                                                      are provided but not included in emp here. Only runoff will
+      !!                                                                      be included in emp in other parts of NEMO code
+      !! ** Action  :   update at each nf_ice time step:
+      !!                   qns_tot, qsr_tot  non-solar and solar total heat fluxes
+      !!                   qns_ice, qsr_ice  non-solar and solar heat fluxes over the ice
+      !!                   emp_tot           total evaporation - precipitation(liquid and solid) (-calving)
+      !!                   emp_ice           ice sublimation - solid precipitation over the ice
+      !!                   dqns_ice          d(non-solar heat flux)/d(Temperature) over the ice
+      !!                   sprecip           solid precipitation over the ocean  
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in)   , DIMENSION(:,:)             ::   picefr     ! ice fraction                [0 to 1]
+      !                                                   !!           ! optional arguments, used only in 'mixed oce-ice' case or for Met-Office coupling
+      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(inout), DIMENSION(:,:,:), OPTIONAL ::   pist       ! ice surface temperature     [Kelvin] => inout for Met-Office
+      REAL(wp), INTENT(in)   , DIMENSION(:,:,:), OPTIONAL ::   phs        ! snow depth                  [m]
+      REAL(wp), INTENT(in)   , DIMENSION(:,:,:), OPTIONAL ::   phi        ! ice thickness               [m]
+      !
+      INTEGER  ::   ji, jj, jl   ! dummy loop index
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zcptn, zcptrain, zcptsnw, ziceld, zmsk, zsnw
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zemp_tot, zemp_ice, zemp_oce, ztprecip, zsprecip  , zevap_oce, zdevap_ice
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zqns_tot, zqns_oce, zqsr_tot, zqsr_oce, zqprec_ice, zqemp_oce, zqemp_ice
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zevap_ice_total
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   zqns_ice, zqsr_ice, zdqns_ice, zqevap_ice, zevap_ice, zqtr_ice_top, ztsu
+      REAL(wp), DIMENSION(jpi,jpj)     ::   ztri
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_mixcpl )   zmsk(:,:) = 1. - xcplmask(:,:,0)
+      ziceld(:,:) = 1._wp - picefr(:,:)
+      zcptn (:,:) = rcp * sst_m(:,:)
+      !
+      !                                                      ! ========================= !
+      !                                                      !    freshwater budget      !   (emp_tot)
+      !                                                      ! ========================= !
+      !
+      !                                                           ! solid Precipitation                                (sprecip)
+      !                                                           ! liquid + solid Precipitation                       (tprecip)
+      !                                                           ! total Evaporation - total Precipitation            (emp_tot)
+      !                                                           ! sublimation - solid precipitation (cell average)   (emp_ice)
+      SELECT CASE( TRIM( sn_rcv_emp%cldes ) )
+      CASE( 'conservative' )   ! received fields: jpr_rain, jpr_snow, jpr_ievp, jpr_tevp
+         zsprecip(:,:) =   frcv(jpr_snow)%z3(:,:,1)                  ! May need to ensure positive here
+         ztprecip(:,:) =   frcv(jpr_rain)%z3(:,:,1) + zsprecip(:,:)  ! May need to ensure positive here
+         zemp_tot(:,:) =   frcv(jpr_tevp)%z3(:,:,1) - ztprecip(:,:)
+      CASE( 'oce and ice'   )   ! received fields: jpr_sbpr, jpr_semp, jpr_oemp, jpr_ievp
+         zemp_tot(:,:) = ziceld(:,:) * frcv(jpr_oemp)%z3(:,:,1) + picefr(:,:) * frcv(jpr_sbpr)%z3(:,:,1)
+         zemp_ice(:,:) = frcv(jpr_semp)%z3(:,:,1) * picefr(:,:)
+         zsprecip(:,:) = frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_semp)%z3(:,:,1)
+         ztprecip(:,:) = frcv(jpr_semp)%z3(:,:,1) - frcv(jpr_sbpr)%z3(:,:,1) + zsprecip(:,:)
+      CASE( 'none'      )       ! Not available as for now: needs additional coding below when computing zevap_oce 
+      !                         ! since fields received are not defined with none option
+         CALL ctl_stop( 'STOP', 'sbccpl/sbc_cpl_ice_flx: some fields are not defined. Change sn_rcv_emp value in namelist namsbc_cpl' )
+      END SELECT
+
+#if defined key_si3
+
+      ! --- evaporation over ice (kg/m2/s) --- !
+      IF (ln_scale_ice_flux) THEN ! typically met-office requirements
+         IF (sn_rcv_emp%clcat == 'yes') THEN
+            WHERE( a_i(:,:,:) > 1.e-10 )  ; zevap_ice(:,:,:) = frcv(jpr_ievp)%z3(:,:,:) * a_i_last_couple(:,:,:) / a_i(:,:,:)
+            ELSEWHERE                     ; zevap_ice(:,:,:) = 0._wp
+            END WHERE
+            WHERE( picefr(:,:) > 1.e-10 ) ; zevap_ice_total(:,:) = SUM( zevap_ice(:,:,:) * a_i(:,:,:), dim=3 ) / picefr(:,:)
+            ELSEWHERE                     ; zevap_ice_total(:,:) = 0._wp
+            END WHERE
+         ELSE
+            WHERE( picefr(:,:) > 1.e-10 ) ; zevap_ice(:,:,1) = frcv(jpr_ievp)%z3(:,:,1) * SUM( a_i_last_couple, dim=3 ) / picefr(:,:)
+            ELSEWHERE                     ; zevap_ice(:,:,1) = 0._wp
+            END WHERE
+            zevap_ice_total(:,:) = zevap_ice(:,:,1)
+            DO jl = 2, jpl
+               zevap_ice(:,:,jl) = zevap_ice(:,:,1)
+            ENDDO
+         ENDIF
+      ELSE
+         IF (sn_rcv_emp%clcat == 'yes') THEN
+            zevap_ice(:,:,1:jpl) = frcv(jpr_ievp)%z3(:,:,1:jpl)
+            WHERE( picefr(:,:) > 1.e-10 ) ; zevap_ice_total(:,:) = SUM( zevap_ice(:,:,:) * a_i(:,:,:), dim=3 ) / picefr(:,:)
+            ELSEWHERE                     ; zevap_ice_total(:,:) = 0._wp
+            END WHERE
+         ELSE
+            zevap_ice(:,:,1) = frcv(jpr_ievp)%z3(:,:,1)
+            zevap_ice_total(:,:) = zevap_ice(:,:,1)
+            DO jl = 2, jpl
+               zevap_ice(:,:,jl) = zevap_ice(:,:,1)
+            ENDDO
+         ENDIF
+      ENDIF
+
+      IF ( TRIM( sn_rcv_emp%cldes ) == 'conservative' ) THEN
+         ! For conservative case zemp_ice has not been defined yet. Do it now.
+         zemp_ice(:,:) = zevap_ice_total(:,:) * picefr(:,:) - frcv(jpr_snow)%z3(:,:,1) * picefr(:,:)
+      ENDIF
+
+      ! zsnw = snow fraction over ice after wind blowing (=picefr if no blowing)
+      zsnw(:,:) = 0._wp   ;   CALL ice_var_snwblow( ziceld, zsnw )
+      
+      ! --- evaporation minus precipitation corrected (because of wind blowing on snow) --- !
+      zemp_ice(:,:) = zemp_ice(:,:) + zsprecip(:,:) * ( picefr(:,:) - zsnw(:,:) )  ! emp_ice = A * sublimation - zsnw * sprecip
+      zemp_oce(:,:) = zemp_tot(:,:) - zemp_ice(:,:)                                ! emp_oce = emp_tot - emp_ice
+
+      ! --- evaporation over ocean (used later for qemp) --- !
+      zevap_oce(:,:) = frcv(jpr_tevp)%z3(:,:,1) - zevap_ice_total(:,:) * picefr(:,:)
+
+      ! since the sensitivity of evap to temperature (devap/dT) is not prescribed by the atmosphere, we set it to 0
+      ! therefore, sublimation is not redistributed over the ice categories when no subgrid scale fluxes are provided by atm.
+      zdevap_ice(:,:) = 0._wp
+      
+      ! --- Continental fluxes --- !
+      IF( srcv(jpr_rnf)%laction ) THEN   ! runoffs (included in emp later on)
+         rnf(:,:) = frcv(jpr_rnf)%z3(:,:,1)
+      ENDIF
+      IF( srcv(jpr_cal)%laction ) THEN   ! calving (put in emp_tot and emp_oce)
+         zemp_tot(:,:) = zemp_tot(:,:) - frcv(jpr_cal)%z3(:,:,1)
+         zemp_oce(:,:) = zemp_oce(:,:) - frcv(jpr_cal)%z3(:,:,1)
+      ENDIF
+      IF( srcv(jpr_icb)%laction ) THEN   ! iceberg added to runoffs
+         fwficb(:,:) = frcv(jpr_icb)%z3(:,:,1)
+         rnf(:,:)    = rnf(:,:) + fwficb(:,:)
+      ENDIF
+      IF( srcv(jpr_isf)%laction ) THEN   ! iceshelf (fwfisf <0 mean melting)
+        fwfisf(:,:) = - frcv(jpr_isf)%z3(:,:,1)  
+      ENDIF
+
+      IF( ln_mixcpl ) THEN
+         emp_tot(:,:) = emp_tot(:,:) * xcplmask(:,:,0) + zemp_tot(:,:) * zmsk(:,:)
+         emp_ice(:,:) = emp_ice(:,:) * xcplmask(:,:,0) + zemp_ice(:,:) * zmsk(:,:)
+         emp_oce(:,:) = emp_oce(:,:) * xcplmask(:,:,0) + zemp_oce(:,:) * zmsk(:,:)
+         sprecip(:,:) = sprecip(:,:) * xcplmask(:,:,0) + zsprecip(:,:) * zmsk(:,:)
+         tprecip(:,:) = tprecip(:,:) * xcplmask(:,:,0) + ztprecip(:,:) * zmsk(:,:)
+         DO jl = 1, jpl
+            evap_ice (:,:,jl) = evap_ice (:,:,jl) * xcplmask(:,:,0) + zevap_ice (:,:,jl) * zmsk(:,:)
+            devap_ice(:,:,jl) = devap_ice(:,:,jl) * xcplmask(:,:,0) + zdevap_ice(:,:)    * zmsk(:,:)
+         END DO
+      ELSE
+         emp_tot (:,:)   = zemp_tot (:,:)
+         emp_ice (:,:)   = zemp_ice (:,:)
+         emp_oce (:,:)   = zemp_oce (:,:)     
+         sprecip (:,:)   = zsprecip (:,:)
+         tprecip (:,:)   = ztprecip (:,:)
+         evap_ice(:,:,:) = zevap_ice(:,:,:)
+         DO jl = 1, jpl
+            devap_ice(:,:,jl) = zdevap_ice(:,:)
+         END DO
+      ENDIF
+
+#else
+      zsnw(:,:) = picefr(:,:)
+      ! --- Continental fluxes --- !
+      IF( srcv(jpr_rnf)%laction ) THEN   ! runoffs (included in emp later on)
+         rnf(:,:) = frcv(jpr_rnf)%z3(:,:,1)
+      ENDIF
+      IF( srcv(jpr_cal)%laction ) THEN   ! calving (put in emp_tot)
+         zemp_tot(:,:) = zemp_tot(:,:) - frcv(jpr_cal)%z3(:,:,1)
+      ENDIF
+      IF( srcv(jpr_icb)%laction ) THEN   ! iceberg added to runoffs
+         fwficb(:,:) = frcv(jpr_icb)%z3(:,:,1)
+         rnf(:,:)    = rnf(:,:) + fwficb(:,:)
+      ENDIF
+      IF( srcv(jpr_isf)%laction ) THEN   ! iceshelf (fwfisf <0 mean melting)
+        fwfisf(:,:) = - frcv(jpr_isf)%z3(:,:,1)
+      ENDIF
+      !
+      IF( ln_mixcpl ) THEN
+         emp_tot(:,:) = emp_tot(:,:) * xcplmask(:,:,0) + zemp_tot(:,:) * zmsk(:,:)
+         emp_ice(:,:) = emp_ice(:,:) * xcplmask(:,:,0) + zemp_ice(:,:) * zmsk(:,:)
+         sprecip(:,:) = sprecip(:,:) * xcplmask(:,:,0) + zsprecip(:,:) * zmsk(:,:)
+         tprecip(:,:) = tprecip(:,:) * xcplmask(:,:,0) + ztprecip(:,:) * zmsk(:,:)
+      ELSE
+         emp_tot(:,:) =                                  zemp_tot(:,:)
+         emp_ice(:,:) =                                  zemp_ice(:,:)
+         sprecip(:,:) =                                  zsprecip(:,:)
+         tprecip(:,:) =                                  ztprecip(:,:)
+      ENDIF
+      !
+#endif
+
+      ! outputs
+!!      IF( srcv(jpr_rnf)%laction )   CALL iom_put( 'runoffs' , rnf(:,:) * tmask(:,:,1)                                 )  ! runoff
+!!      IF( srcv(jpr_isf)%laction )   CALL iom_put( 'iceshelf_cea', -fwfisf(:,:) * tmask(:,:,1)                         )  ! iceshelf
+      IF( srcv(jpr_cal)%laction )    CALL iom_put( 'calving_cea' , frcv(jpr_cal)%z3(:,:,1) * tmask(:,:,1)                )  ! calving
+      IF( srcv(jpr_icb)%laction )    CALL iom_put( 'iceberg_cea' , frcv(jpr_icb)%z3(:,:,1) * tmask(:,:,1)                )  ! icebergs
+      IF( iom_use('snowpre') )       CALL iom_put( 'snowpre'     , sprecip(:,:)                                          )  ! Snow
+      IF( iom_use('precip') )        CALL iom_put( 'precip'      , tprecip(:,:)                                          )  ! total  precipitation
+      IF( iom_use('rain') )          CALL iom_put( 'rain'        , tprecip(:,:) - sprecip(:,:)                           )  ! liquid precipitation 
+      IF( iom_use('snow_ao_cea') )   CALL iom_put( 'snow_ao_cea' , sprecip(:,:) * ( 1._wp - zsnw(:,:) )                  )  ! Snow over ice-free ocean  (cell average)
+      IF( iom_use('snow_ai_cea') )   CALL iom_put( 'snow_ai_cea' , sprecip(:,:) *           zsnw(:,:)                    )  ! Snow over sea-ice         (cell average)
+      IF( iom_use('rain_ao_cea') )   CALL iom_put( 'rain_ao_cea' , ( tprecip(:,:) - sprecip(:,:) ) * picefr(:,:)         )  ! liquid precipitation over ocean (cell average)
+      IF( iom_use('subl_ai_cea') )   CALL iom_put( 'subl_ai_cea' , frcv(jpr_ievp)%z3(:,:,1) * picefr(:,:) * tmask(:,:,1) )     ! Sublimation over sea-ice (cell average)
+      IF( iom_use('evap_ao_cea') )   CALL iom_put( 'evap_ao_cea' , ( frcv(jpr_tevp)%z3(:,:,1)  &
+         &                                                         - frcv(jpr_ievp)%z3(:,:,1) * picefr(:,:) ) * tmask(:,:,1) ) ! ice-free oce evap (cell average)
+      ! note: runoff output is done in sbcrnf (which includes icebergs too) and iceshelf output is done in sbcisf
+      !
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_qns%cldes ) )                !   non solar heat fluxes   !   (qns)
+      !                                                      ! ========================= !
+      CASE( 'oce only' )         ! the required field is directly provided
+         zqns_tot(:,:) = frcv(jpr_qnsoce)%z3(:,:,1)
+         ! For Met Office sea ice non-solar fluxes are already delt with by JULES so setting to zero
+         ! here so the only flux is the ocean only one.
+         zqns_ice(:,:,:) = 0._wp 
+      CASE( 'conservative' )     ! the required fields are directly provided
+         zqns_tot(:,:) = frcv(jpr_qnsmix)%z3(:,:,1)
+         IF ( TRIM(sn_rcv_qns%clcat) == 'yes' ) THEN
+            zqns_ice(:,:,1:jpl) = frcv(jpr_qnsice)%z3(:,:,1:jpl)
+         ELSE
+            DO jl = 1, jpl
+               zqns_ice(:,:,jl) = frcv(jpr_qnsice)%z3(:,:,1) ! Set all category values equal
+            END DO
+         ENDIF
+      CASE( 'oce and ice' )      ! the total flux is computed from ocean and ice fluxes
+         zqns_tot(:,:) =  ziceld(:,:) * frcv(jpr_qnsoce)%z3(:,:,1)
+         IF ( TRIM(sn_rcv_qns%clcat) == 'yes' ) THEN
+            DO jl=1,jpl
+               zqns_tot(:,:   ) = zqns_tot(:,:) + a_i(:,:,jl) * frcv(jpr_qnsice)%z3(:,:,jl)   
+               zqns_ice(:,:,jl) = frcv(jpr_qnsice)%z3(:,:,jl)
+            ENDDO
+         ELSE
+            zqns_tot(:,:) = zqns_tot(:,:) + picefr(:,:) * frcv(jpr_qnsice)%z3(:,:,1)
+            DO jl = 1, jpl
+               zqns_ice(:,:,jl) = frcv(jpr_qnsice)%z3(:,:,1)
+            END DO
+         ENDIF
+      CASE( 'mixed oce-ice' )    ! the ice flux is cumputed from the total flux, the SST and ice informations
+! ** NEED TO SORT OUT HOW THIS SHOULD WORK IN THE MULTI-CATEGORY CASE - CURRENTLY NOT ALLOWED WHEN INTERFACE INITIALISED **
+         zqns_tot(:,:  ) = frcv(jpr_qnsmix)%z3(:,:,1)
+         IF ( TRIM(sn_rcv_qsr%clcat) == 'yes' ) THEN
+            DO jl = 1, jpl
+               zqns_ice(:,:,jl) = frcv(jpr_qnsmix)%z3(:,:,jl)    &
+                  &             + frcv(jpr_dqnsdt)%z3(:,:,jl) * ( pist(:,:,jl) - ( ( rt0 + psst(:,:) ) * ziceld(:,:)   &
+                  &                                             + pist(:,:,jl) * picefr(:,:) ) )
+            END DO
+         ELSE
+            DO jl = 1, jpl
+               zqns_ice(:,:,jl) = frcv(jpr_qnsmix)%z3(:,:, 1)    &
+                  &             + frcv(jpr_dqnsdt)%z3(:,:, 1) * ( pist(:,:,jl) - ( ( rt0 + psst(:,:) ) * ziceld(:,:)   &
+                  &                                             + pist(:,:,jl) * picefr(:,:) ) )
+            END DO
+         ENDIF
+      END SELECT
+      !                                     
+      ! --- calving (removed from qns_tot) --- !
+      IF( srcv(jpr_cal)%laction )   zqns_tot(:,:) = zqns_tot(:,:) - frcv(jpr_cal)%z3(:,:,1) * rLfus  ! remove latent heat of calving
+                                                                                                     ! we suppose it melts at 0deg, though it should be temp. of surrounding ocean
+      ! --- iceberg (removed from qns_tot) --- !
+      IF( srcv(jpr_icb)%laction )   zqns_tot(:,:) = zqns_tot(:,:) - frcv(jpr_icb)%z3(:,:,1) * rLfus  ! remove latent heat of iceberg melting
+
+#if defined key_si3      
+      ! --- non solar flux over ocean --- !
+      !         note: ziceld cannot be = 0 since we limit the ice concentration to amax
+      zqns_oce = 0._wp
+      WHERE( ziceld /= 0._wp )   zqns_oce(:,:) = ( zqns_tot(:,:) - SUM( a_i * zqns_ice, dim=3 ) ) / ziceld(:,:)
+
+      ! Heat content per unit mass of snow (J/kg)
+      WHERE( SUM( a_i, dim=3 ) > 1.e-10 )   ;   zcptsnw(:,:) = rcpi * SUM( (tn_ice - rt0) * a_i, dim=3 ) / SUM( a_i, dim=3 )
+      ELSEWHERE                             ;   zcptsnw(:,:) = zcptn(:,:)
+      ENDWHERE
+      ! Heat content per unit mass of rain (J/kg)
+      zcptrain(:,:) = rcp * ( SUM( (tn_ice(:,:,:) - rt0) * a_i(:,:,:), dim=3 ) + sst_m(:,:) * ziceld(:,:) ) 
+
+      ! --- enthalpy of snow precip over ice in J/m3 (to be used in 1D-thermo) --- !
+      zqprec_ice(:,:) = rhos * ( zcptsnw(:,:) - rLfus )
+
+      ! --- heat content of evap over ice in W/m2 (to be used in 1D-thermo) --- !
+      DO jl = 1, jpl
+         zqevap_ice(:,:,jl) = 0._wp ! should be -evap * ( ( Tice - rt0 ) * rcpi ) but atm. does not take it into account
+      END DO
+
+      ! --- heat flux associated with emp (W/m2) --- !
+      zqemp_oce(:,:) = -  zevap_oce(:,:)                                      *   zcptn   (:,:)   &        ! evap
+         &             + ( ztprecip(:,:) - zsprecip(:,:) )                    *   zcptrain(:,:)   &        ! liquid precip
+         &             +   zsprecip(:,:)                   * ( 1._wp - zsnw ) * ( zcptsnw (:,:) - rLfus )  ! solid precip over ocean + snow melting
+      zqemp_ice(:,:) =     zsprecip(:,:)                   * zsnw             * ( zcptsnw (:,:) - rLfus )  ! solid precip over ice (qevap_ice=0 since atm. does not take it into account)
+!!    zqemp_ice(:,:) = -   frcv(jpr_ievp)%z3(:,:,1)        * picefr(:,:)      *   zcptsnw (:,:)   &        ! ice evap
+!!       &             +   zsprecip(:,:)                   * zsnw             * zqprec_ice(:,:) * r1_rhos  ! solid precip over ice
+      
+      ! --- total non solar flux (including evap/precip) --- !
+      zqns_tot(:,:) = zqns_tot(:,:) + zqemp_ice(:,:) + zqemp_oce(:,:)
+
+      ! --- in case both coupled/forced are active, we must mix values --- ! 
+      IF( ln_mixcpl ) THEN
+         qns_tot(:,:) = qns_tot(:,:) * xcplmask(:,:,0) + zqns_tot(:,:)* zmsk(:,:)
+         qns_oce(:,:) = qns_oce(:,:) * xcplmask(:,:,0) + zqns_oce(:,:)* zmsk(:,:)
+         DO jl=1,jpl
+            qns_ice  (:,:,jl) = qns_ice  (:,:,jl) * xcplmask(:,:,0) +  zqns_ice  (:,:,jl)* zmsk(:,:)
+            qevap_ice(:,:,jl) = qevap_ice(:,:,jl) * xcplmask(:,:,0) +  zqevap_ice(:,:,jl)* zmsk(:,:)
+         ENDDO
+         qprec_ice(:,:) = qprec_ice(:,:) * xcplmask(:,:,0) + zqprec_ice(:,:)* zmsk(:,:)
+         qemp_oce (:,:) =  qemp_oce(:,:) * xcplmask(:,:,0) +  zqemp_oce(:,:)* zmsk(:,:)
+         qemp_ice (:,:) =  qemp_ice(:,:) * xcplmask(:,:,0) +  zqemp_ice(:,:)* zmsk(:,:)
+      ELSE
+         qns_tot  (:,:  ) = zqns_tot  (:,:  )
+         qns_oce  (:,:  ) = zqns_oce  (:,:  )
+         qns_ice  (:,:,:) = zqns_ice  (:,:,:)
+         qevap_ice(:,:,:) = zqevap_ice(:,:,:)
+         qprec_ice(:,:  ) = zqprec_ice(:,:  )
+         qemp_oce (:,:  ) = zqemp_oce (:,:  )
+         qemp_ice (:,:  ) = zqemp_ice (:,:  )
+      ENDIF
+
+#else
+      zcptsnw (:,:) = zcptn(:,:)
+      zcptrain(:,:) = zcptn(:,:)
+      
+      ! clem: this formulation is certainly wrong... but better than it was...
+      zqns_tot(:,:) = zqns_tot(:,:)                             &          ! zqns_tot update over free ocean with:
+         &          - (  ziceld(:,:) * zsprecip(:,:) * rLfus )  &          ! remove the latent heat flux of solid precip. melting
+         &          - (  zemp_tot(:,:)                          &          ! remove the heat content of mass flux (assumed to be at SST)
+         &             - zemp_ice(:,:) ) * zcptn(:,:) 
+
+     IF( ln_mixcpl ) THEN
+         qns_tot(:,:) = qns(:,:) * ziceld(:,:) + SUM( qns_ice(:,:,:) * a_i(:,:,:), dim=3 )   ! total flux from blk
+         qns_tot(:,:) = qns_tot(:,:) * xcplmask(:,:,0) +  zqns_tot(:,:)* zmsk(:,:)
+         DO jl=1,jpl
+            qns_ice(:,:,jl) = qns_ice(:,:,jl) * xcplmask(:,:,0) +  zqns_ice(:,:,jl)* zmsk(:,:)
+         ENDDO
+      ELSE
+         qns_tot(:,:  ) = zqns_tot(:,:  )
+         qns_ice(:,:,:) = zqns_ice(:,:,:)
+      ENDIF
+
+#endif
+      ! outputs
+      IF ( srcv(jpr_cal)%laction ) CALL iom_put('hflx_cal_cea'    , - frcv(jpr_cal)%z3(:,:,1) * rLfus )   ! latent heat from calving
+      IF ( srcv(jpr_icb)%laction ) CALL iom_put('hflx_icb_cea'    , - frcv(jpr_icb)%z3(:,:,1) * rLfus )   ! latent heat from icebergs melting
+      IF ( iom_use(   'hflx_rain_cea') ) CALL iom_put('hflx_rain_cea' , ( tprecip(:,:) - sprecip(:,:) ) * zcptrain(:,:) )        ! heat flux from rain (cell average)
+      IF ( iom_use(   'hflx_evap_cea') ) CALL iom_put('hflx_evap_cea' , ( frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * picefr(:,:) )  &
+           &                         * zcptn(:,:) * tmask(:,:,1) )            ! heat flux from evap (cell average)
+      IF ( iom_use(   'hflx_prec_cea') ) CALL iom_put('hflx_prec_cea' ,    sprecip(:,:) * ( zcptsnw(:,:) - rLfus )  &                    ! heat flux from all precip (cell avg)
+         &                          + ( tprecip(:,:) - sprecip(:,:) ) * zcptrain(:,:) )
+      IF ( iom_use(   'hflx_snow_cea') ) CALL iom_put('hflx_snow_cea'   , sprecip(:,:) * ( zcptsnw(:,:) - rLfus )  )               ! heat flux from snow (cell average)
+      IF ( iom_use('hflx_snow_ao_cea') ) CALL iom_put('hflx_snow_ao_cea', sprecip(:,:) * ( zcptsnw(:,:) - rLfus ) * ( 1._wp - zsnw(:,:) ) )   ! heat flux from snow (over ocean)
+      IF ( iom_use('hflx_snow_ai_cea') ) CALL iom_put('hflx_snow_ai_cea', sprecip(:,:) * ( zcptsnw(:,:) - rLfus ) *  zsnw(:,:) )              ! heat flux from snow (over ice)
+      ! note: hflx for runoff and iceshelf are done in sbcrnf and sbcisf resp.
+      !
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_qsr%cldes ) )                !      solar heat fluxes    !   (qsr)
+      !                                                      ! ========================= !
+      CASE( 'oce only' )
+         zqsr_tot(:,:  ) = MAX( 0._wp , frcv(jpr_qsroce)%z3(:,:,1) )
+         ! For Met Office sea ice solar fluxes are already delt with by JULES so setting to zero
+         ! here so the only flux is the ocean only one.
+         zqsr_ice(:,:,:) = 0._wp
+      CASE( 'conservative' )
+         zqsr_tot(:,:  ) = frcv(jpr_qsrmix)%z3(:,:,1)
+         IF ( TRIM(sn_rcv_qsr%clcat) == 'yes' ) THEN
+            zqsr_ice(:,:,1:jpl) = frcv(jpr_qsrice)%z3(:,:,1:jpl)
+         ELSE
+            ! Set all category values equal for the moment
+            DO jl = 1, jpl
+               zqsr_ice(:,:,jl) = frcv(jpr_qsrice)%z3(:,:,1)
+            END DO
+         ENDIF
+      CASE( 'oce and ice' )
+         zqsr_tot(:,:  ) =  ziceld(:,:) * frcv(jpr_qsroce)%z3(:,:,1)
+         IF ( TRIM(sn_rcv_qsr%clcat) == 'yes' ) THEN
+            DO jl = 1, jpl
+               zqsr_tot(:,:   ) = zqsr_tot(:,:) + a_i(:,:,jl) * frcv(jpr_qsrice)%z3(:,:,jl)   
+               zqsr_ice(:,:,jl) = frcv(jpr_qsrice)%z3(:,:,jl)
+            END DO
+         ELSE
+            zqsr_tot(:,:) = zqsr_tot(:,:) + picefr(:,:) * frcv(jpr_qsrice)%z3(:,:,1)
+            DO jl = 1, jpl
+               zqsr_ice(:,:,jl) = frcv(jpr_qsrice)%z3(:,:,1)
+            END DO
+         ENDIF
+      CASE( 'mixed oce-ice' )
+         zqsr_tot(:,:  ) = frcv(jpr_qsrmix)%z3(:,:,1)
+! ** NEED TO SORT OUT HOW THIS SHOULD WORK IN THE MULTI-CATEGORY CASE - CURRENTLY NOT ALLOWED WHEN INTERFACE INITIALISED **
+!       Create solar heat flux over ice using incoming solar heat flux and albedos
+!       ( see OASIS3 user guide, 5th edition, p39 )
+         IF ( TRIM(sn_rcv_qsr%clcat) == 'yes' ) THEN
+            DO jl = 1, jpl
+               zqsr_ice(:,:,jl) = frcv(jpr_qsrmix)%z3(:,:,jl) * ( 1.- palbi(:,:,jl) )   &
+                  &            / (  1.- ( alb_oce_mix(:,:   ) * ziceld(:,:)       &
+                  &                     + palbi      (:,:,jl) * picefr(:,:) ) )
+            END DO
+         ELSE
+            DO jl = 1, jpl
+               zqsr_ice(:,:,jl) = frcv(jpr_qsrmix)%z3(:,:, 1) * ( 1.- palbi(:,:,jl) )   &
+                  &            / (  1.- ( alb_oce_mix(:,:   ) * ziceld(:,:)       &
+                  &                     + palbi      (:,:,jl) * picefr(:,:) ) )
+            END DO
+         ENDIF
+      CASE( 'none'      )       ! Not available as for now: needs additional coding  
+      !                         ! since fields received, here zqsr_tot,  are not defined with none option
+         CALL ctl_stop( 'STOP', 'sbccpl/sbc_cpl_ice_flx: some fields are not defined. Change sn_rcv_qsr value in namelist namsbc_cpl' )
+      END SELECT
+      IF( ln_dm2dc .AND. ln_cpl ) THEN   ! modify qsr to include the diurnal cycle
+         zqsr_tot(:,:  ) = sbc_dcy( zqsr_tot(:,:  ) )
+         DO jl = 1, jpl
+            zqsr_ice(:,:,jl) = sbc_dcy( zqsr_ice(:,:,jl) )
+         END DO
+      ENDIF
+
+#if defined key_si3
+      ! --- solar flux over ocean --- !
+      !         note: ziceld cannot be = 0 since we limit the ice concentration to amax
+      zqsr_oce = 0._wp
+      WHERE( ziceld /= 0._wp )  zqsr_oce(:,:) = ( zqsr_tot(:,:) - SUM( a_i * zqsr_ice, dim=3 ) ) / ziceld(:,:)
+
+      IF( ln_mixcpl ) THEN   ;   qsr_oce(:,:) = qsr_oce(:,:) * xcplmask(:,:,0) +  zqsr_oce(:,:)* zmsk(:,:)
+      ELSE                   ;   qsr_oce(:,:) = zqsr_oce(:,:)   ;   ENDIF
+#endif
+
+      IF( ln_mixcpl ) THEN
+         qsr_tot(:,:) = qsr(:,:) * ziceld(:,:) + SUM( qsr_ice(:,:,:) * a_i(:,:,:), dim=3 )   ! total flux from blk
+         qsr_tot(:,:) = qsr_tot(:,:) * xcplmask(:,:,0) +  zqsr_tot(:,:)* zmsk(:,:)
+         DO jl = 1, jpl
+            qsr_ice(:,:,jl) = qsr_ice(:,:,jl) * xcplmask(:,:,0) +  zqsr_ice(:,:,jl)* zmsk(:,:)
+         END DO
+      ELSE
+         qsr_tot(:,:  ) = zqsr_tot(:,:  )
+         qsr_ice(:,:,:) = zqsr_ice(:,:,:)
+      ENDIF
+
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_dqnsdt%cldes ) )             !          d(qns)/dt        !
+      !                                                      ! ========================= !
+      CASE ('coupled')
+         IF ( TRIM(sn_rcv_dqnsdt%clcat) == 'yes' ) THEN
+            zdqns_ice(:,:,1:jpl) = frcv(jpr_dqnsdt)%z3(:,:,1:jpl)
+         ELSE
+            ! Set all category values equal for the moment
+            DO jl=1,jpl
+               zdqns_ice(:,:,jl) = frcv(jpr_dqnsdt)%z3(:,:,1)
+            ENDDO
+         ENDIF
+      CASE( 'none' ) 
+         zdqns_ice(:,:,:) = 0._wp
+      END SELECT
+      
+      IF( ln_mixcpl ) THEN
+         DO jl=1,jpl
+            dqns_ice(:,:,jl) = dqns_ice(:,:,jl) * xcplmask(:,:,0) + zdqns_ice(:,:,jl) * zmsk(:,:)
+         ENDDO
+      ELSE
+         dqns_ice(:,:,:) = zdqns_ice(:,:,:)
+      ENDIF
+
+#if defined key_si3      
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_iceflx%cldes ) )             !  ice topmelt and botmelt  !
+      !                                                      ! ========================= !
+      CASE ('coupled')
+         IF (ln_scale_ice_flux) THEN
+            WHERE( a_i(:,:,:) > 1.e-10_wp )
+               qml_ice(:,:,:) = frcv(jpr_topm)%z3(:,:,:) * a_i_last_couple(:,:,:) / a_i(:,:,:)
+               qcn_ice(:,:,:) = frcv(jpr_botm)%z3(:,:,:) * a_i_last_couple(:,:,:) / a_i(:,:,:)
+            ELSEWHERE
+               qml_ice(:,:,:) = 0.0_wp
+               qcn_ice(:,:,:) = 0.0_wp
+            END WHERE
+         ELSE
+            qml_ice(:,:,:) = frcv(jpr_topm)%z3(:,:,:)
+            qcn_ice(:,:,:) = frcv(jpr_botm)%z3(:,:,:)
+         ENDIF
+      END SELECT
+      !                                                      ! ========================= !
+      !                                                      !      Transmitted Qsr      !   [W/m2]
+      !                                                      ! ========================= !
+      IF( .NOT.ln_cndflx ) THEN                              !==  No conduction flux as surface forcing  ==!
+         !
+         IF( nn_qtrice == 0 ) THEN
+            ! formulation derived from Grenfell and Maykut (1977), where transmission rate
+            !    1) depends on cloudiness
+            !       ! ===> used prescribed cloud fraction representative for polar oceans in summer (0.81)
+            !       !      should be real cloud fraction instead (as in the bulk) but needs to be read from atm.
+            !    2) is 0 when there is any snow
+            !    3) tends to 1 for thin ice
+            ztri(:,:) = 0.18 * ( 1.0 - cloud_fra(:,:) ) + 0.35 * cloud_fra(:,:)  ! surface transmission when hi>10cm
+            DO jl = 1, jpl
+               WHERE    ( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) <  0.1_wp )       ! linear decrease from hi=0 to 10cm  
+                  zqtr_ice_top(:,:,jl) = zqsr_ice(:,:,jl) * ( ztri(:,:) + ( 1._wp - ztri(:,:) ) * ( 1._wp - phi(:,:,jl) * 10._wp ) )
+               ELSEWHERE( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) >= 0.1_wp )       ! constant (ztri) when hi>10cm
+                  zqtr_ice_top(:,:,jl) = zqsr_ice(:,:,jl) * ztri(:,:)
+               ELSEWHERE                                                           ! zero when hs>0
+                  zqtr_ice_top(:,:,jl) = 0._wp 
+               END WHERE
+            ENDDO
+         ELSEIF( nn_qtrice == 1 ) THEN
+            ! formulation is derived from the thesis of M. Lebrun (2019).
+            !    It represents the best fit using several sets of observations
+            !    It comes with snow conductivities adapted to freezing/melting conditions (see icethd_zdf_bl99.F90)
+            zqtr_ice_top(:,:,:) = 0.3_wp * zqsr_ice(:,:,:)
+         ENDIF
+         !     
+      ELSEIF( ln_cndflx .AND. .NOT.ln_cndemulate ) THEN      !==  conduction flux as surface forcing  ==!
+         !
+         !          ! ===> here we must receive the qtr_ice_top array from the coupler
+         !                 for now just assume zero (fully opaque ice)
+         zqtr_ice_top(:,:,:) = 0._wp
+         !
+      ENDIF
+      !
+      IF( ln_mixcpl ) THEN
+         DO jl=1,jpl
+            qtr_ice_top(:,:,jl) = qtr_ice_top(:,:,jl) * xcplmask(:,:,0) + zqtr_ice_top(:,:,jl) * zmsk(:,:)
+         ENDDO
+      ELSE
+         qtr_ice_top(:,:,:) = zqtr_ice_top(:,:,:)
+      ENDIF
+      !                                                      ! ================== !
+      !                                                      !   ice skin temp.   !
+      !                                                      ! ================== !
+      ! needed by Met Office
+      IF( srcv(jpr_ts_ice)%laction ) THEN 
+         WHERE    ( frcv(jpr_ts_ice)%z3(:,:,:) > 0.0  )   ;   ztsu(:,:,:) =   0. + rt0 
+         ELSEWHERE( frcv(jpr_ts_ice)%z3(:,:,:) < -60. )   ;   ztsu(:,:,:) = -60. + rt0
+         ELSEWHERE                                        ;   ztsu(:,:,:) = frcv(jpr_ts_ice)%z3(:,:,:) + rt0
+         END WHERE
+         !
+         IF( ln_mixcpl ) THEN
+            DO jl=1,jpl
+               pist(:,:,jl) = pist(:,:,jl) * xcplmask(:,:,0) + ztsu(:,:,jl) * zmsk(:,:)
+            ENDDO
+         ELSE
+            pist(:,:,:) = ztsu(:,:,:)
+         ENDIF
+         !
+      ENDIF
+      !
+#endif
+      !
+   END SUBROUTINE sbc_cpl_ice_flx
+   
+   
+   SUBROUTINE sbc_cpl_snd( kt )
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE sbc_cpl_snd  ***
+      !!
+      !! ** Purpose :   provide the ocean-ice informations to the atmosphere
+      !!
+      !! ** Method  :   send to the atmosphere through a call to cpl_snd
+      !!              all the needed fields (as defined in sbc_cpl_init)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt
+      !
+      INTEGER ::   ji, jj, jl   ! dummy loop indices
+      INTEGER ::   isec, info   ! local integer
+      REAL(wp) ::   zumax, zvmax
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zfr_l, ztmp1, ztmp2, zotx1, zoty1, zotz1, zitx1, zity1, zitz1
+      REAL(wp), DIMENSION(jpi,jpj,jpl) ::   ztmp3, ztmp4   
+      !!----------------------------------------------------------------------
+      !
+      isec = ( kt - nit000 ) * NINT( rdt )        ! date of exchanges
+      info = OASIS_idle
+
+      zfr_l(:,:) = 1.- fr_i(:,:)
+      !                                                      ! ------------------------- !
+      !                                                      !    Surface temperature    !   in Kelvin
+      !                                                      ! ------------------------- !
+      IF( ssnd(jps_toce)%laction .OR. ssnd(jps_tice)%laction .OR. ssnd(jps_tmix)%laction ) THEN
+         
+         IF ( nn_components == jp_iam_opa ) THEN
+            ztmp1(:,:) = tsn(:,:,1,jp_tem)   ! send temperature as it is (potential or conservative) -> use of l_useCT on the received part
+         ELSE
+            ! we must send the surface potential temperature 
+            IF( l_useCT )  THEN    ;   ztmp1(:,:) = eos_pt_from_ct( tsn(:,:,1,jp_tem), tsn(:,:,1,jp_sal) )
+            ELSE                   ;   ztmp1(:,:) = tsn(:,:,1,jp_tem)
+            ENDIF
+            !
+            SELECT CASE( sn_snd_temp%cldes)
+            CASE( 'oce only'             )   ;   ztmp1(:,:) =   ztmp1(:,:) + rt0
+            CASE( 'oce and ice'          )   ;   ztmp1(:,:) =   ztmp1(:,:) + rt0
+               SELECT CASE( sn_snd_temp%clcat )
+               CASE( 'yes' )   
+                  ztmp3(:,:,1:jpl) = tn_ice(:,:,1:jpl)
+               CASE( 'no' )
+                  WHERE( SUM( a_i, dim=3 ) /= 0. )
+                     ztmp3(:,:,1) = SUM( tn_ice * a_i, dim=3 ) / SUM( a_i, dim=3 )
+                  ELSEWHERE
+                     ztmp3(:,:,1) = rt0
+                  END WHERE
+               CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' )
+               END SELECT
+            CASE( 'weighted oce and ice' )   ;   ztmp1(:,:) = ( ztmp1(:,:) + rt0 ) * zfr_l(:,:)   
+               SELECT CASE( sn_snd_temp%clcat )
+               CASE( 'yes' )   
+                  ztmp3(:,:,1:jpl) = tn_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
+               CASE( 'no' )
+                  ztmp3(:,:,:) = 0.0
+                  DO jl=1,jpl
+                     ztmp3(:,:,1) = ztmp3(:,:,1) + tn_ice(:,:,jl) * a_i(:,:,jl)
+                  ENDDO
+               CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' )
+               END SELECT
+            CASE( 'oce and weighted ice')    ;   ztmp1(:,:) =   tsn(:,:,1,jp_tem) + rt0  
+               SELECT CASE( sn_snd_temp%clcat ) 
+               CASE( 'yes' )    
+                  ztmp3(:,:,1:jpl) = tn_ice(:,:,1:jpl) * a_i(:,:,1:jpl) 
+               CASE( 'no' ) 
+                  ztmp3(:,:,:) = 0.0 
+                  DO jl=1,jpl 
+                     ztmp3(:,:,1) = ztmp3(:,:,1) + tn_ice(:,:,jl) * a_i(:,:,jl) 
+                  ENDDO 
+               CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%clcat' ) 
+               END SELECT 
+            CASE( 'mixed oce-ice'        )   
+               ztmp1(:,:) = ( ztmp1(:,:) + rt0 ) * zfr_l(:,:) 
+               DO jl=1,jpl
+                  ztmp1(:,:) = ztmp1(:,:) + tn_ice(:,:,jl) * a_i(:,:,jl)
+               ENDDO
+            CASE default                     ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%cldes' )
+            END SELECT
+         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
+      !
+      !                                                      ! ------------------------- !
+      !                                                      ! 1st layer ice/snow temp.  !
+      !                                                      ! ------------------------- !
+#if defined key_si3
+      ! needed by  Met Office
+      IF( ssnd(jps_ttilyr)%laction) THEN
+         SELECT CASE( sn_snd_ttilyr%cldes)
+         CASE ('weighted ice')
+            ztmp3(:,:,1:jpl) = t1_ice(:,:,1:jpl) * a_i(:,:,1:jpl) 
+         CASE default                     ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_ttilyr%cldes' )
+         END SELECT
+         IF( ssnd(jps_ttilyr)%laction )   CALL cpl_snd( jps_ttilyr, isec, ztmp3, info )
+      ENDIF
+#endif
+      !                                                      ! ------------------------- !
+      !                                                      !           Albedo          !
+      !                                                      ! ------------------------- !
+      IF( ssnd(jps_albice)%laction ) THEN                         ! ice 
+          SELECT CASE( sn_snd_alb%cldes )
+          CASE( 'ice' )
+             SELECT CASE( sn_snd_alb%clcat )
+             CASE( 'yes' )   
+                ztmp3(:,:,1:jpl) = alb_ice(:,:,1:jpl)
+             CASE( 'no' )
+                WHERE( SUM( a_i, dim=3 ) /= 0. )
+                   ztmp1(:,:) = SUM( alb_ice (:,:,1:jpl) * a_i(:,:,1:jpl), dim=3 ) / SUM( a_i(:,:,1:jpl), dim=3 )
+                ELSEWHERE
+                   ztmp1(:,:) = alb_oce_mix(:,:)
+                END WHERE
+             CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_alb%clcat' )
+             END SELECT
+          CASE( 'weighted ice' )   ;
+             SELECT CASE( sn_snd_alb%clcat )
+             CASE( 'yes' )   
+                ztmp3(:,:,1:jpl) =  alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
+             CASE( 'no' )
+                WHERE( fr_i (:,:) > 0. )
+                   ztmp1(:,:) = SUM (  alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl), dim=3 )
+                ELSEWHERE
+                   ztmp1(:,:) = 0.
+                END WHERE
+             CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_ice%clcat' )
+             END SELECT
+          CASE default      ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_alb%cldes' )
+         END SELECT
+
+         SELECT CASE( sn_snd_alb%clcat )
+            CASE( 'yes' )   
+               CALL cpl_snd( jps_albice, isec, ztmp3, info )      !-> MV this has never been checked in coupled mode
+            CASE( 'no'  )   
+               CALL cpl_snd( jps_albice, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info ) 
+         END SELECT
+      ENDIF
+
+      IF( ssnd(jps_albmix)%laction ) THEN                         ! mixed ice-ocean
+         ztmp1(:,:) = alb_oce_mix(:,:) * zfr_l(:,:)
+         DO jl = 1, jpl
+            ztmp1(:,:) = ztmp1(:,:) + alb_ice(:,:,jl) * a_i(:,:,jl)
+         END DO
+         CALL cpl_snd( jps_albmix, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
+      ENDIF
+      !                                                      ! ------------------------- !
+      !                                                      !  Ice fraction & Thickness ! 
+      !                                                      ! ------------------------- !
+      ! Send ice fraction field to atmosphere
+      IF( ssnd(jps_fice)%laction ) THEN
+         SELECT CASE( sn_snd_thick%clcat )
+         CASE( 'yes' )   ;   ztmp3(:,:,1:jpl) =  a_i(:,:,1:jpl)
+         CASE( 'no'  )   ;   ztmp3(:,:,1    ) = fr_i(:,:      )
+         CASE default    ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%clcat' )
+         END SELECT
+         CALL cpl_snd( jps_fice, isec, ztmp3, info )
+      ENDIF
+
+#if defined key_si3 || defined key_cice
+      ! If this coupling was successful then save ice fraction for use between coupling points. 
+      ! This is needed for some calculations where the ice fraction at the last coupling point 
+      ! is needed. 
+      IF(  info == OASIS_Sent    .OR. info == OASIS_ToRest .OR. & 
+         & info == OASIS_SentOut .OR. info == OASIS_ToRestOut ) THEN 
+         IF ( sn_snd_thick%clcat == 'yes' ) THEN 
+           a_i_last_couple(:,:,1:jpl) = a_i(:,:,1:jpl)
+         ENDIF
+      ENDIF
+#endif
+
+      IF( ssnd(jps_fice1)%laction ) THEN
+         SELECT CASE( sn_snd_thick1%clcat )
+         CASE( 'yes' )   ;   ztmp3(:,:,1:jpl) =  a_i(:,:,1:jpl)
+         CASE( 'no'  )   ;   ztmp3(:,:,1    ) = fr_i(:,:      )
+         CASE default    ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick1%clcat' )
+         END SELECT
+         CALL cpl_snd( jps_fice1, isec, ztmp3, info )
+      ENDIF
+      
+      ! Send ice fraction field to OPA (sent by SAS in SAS-OPA coupling)
+      IF( ssnd(jps_fice2)%laction ) THEN
+         ztmp3(:,:,1) = fr_i(:,:)
+         IF( ssnd(jps_fice2)%laction )   CALL cpl_snd( jps_fice2, isec, ztmp3, info )
+      ENDIF
+
+      ! Send ice and snow thickness field 
+      IF( ssnd(jps_hice)%laction .OR. ssnd(jps_hsnw)%laction ) THEN 
+         SELECT CASE( sn_snd_thick%cldes)
+         CASE( 'none'                  )       ! nothing to do
+         CASE( 'weighted ice and snow' )   
+            SELECT CASE( sn_snd_thick%clcat )
+            CASE( 'yes' )   
+               ztmp3(:,:,1:jpl) =  h_i(:,:,1:jpl) * a_i(:,:,1:jpl)
+               ztmp4(:,:,1:jpl) =  h_s(:,:,1:jpl) * a_i(:,:,1:jpl)
+            CASE( 'no' )
+               ztmp3(:,:,:) = 0.0   ;  ztmp4(:,:,:) = 0.0
+               DO jl=1,jpl
+                  ztmp3(:,:,1) = ztmp3(:,:,1) + h_i(:,:,jl) * a_i(:,:,jl)
+                  ztmp4(:,:,1) = ztmp4(:,:,1) + h_s(:,:,jl) * a_i(:,:,jl)
+               ENDDO
+            CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%clcat' )
+            END SELECT
+         CASE( 'ice and snow'         )   
+            SELECT CASE( sn_snd_thick%clcat )
+            CASE( 'yes' )
+               ztmp3(:,:,1:jpl) = h_i(:,:,1:jpl)
+               ztmp4(:,:,1:jpl) = h_s(:,:,1:jpl)
+            CASE( 'no' )
+               WHERE( SUM( a_i, dim=3 ) /= 0. )
+                  ztmp3(:,:,1) = SUM( h_i * a_i, dim=3 ) / SUM( a_i, dim=3 )
+                  ztmp4(:,:,1) = SUM( h_s * a_i, dim=3 ) / SUM( a_i, dim=3 )
+               ELSEWHERE
+                 ztmp3(:,:,1) = 0.
+                 ztmp4(:,:,1) = 0.
+               END WHERE
+            CASE default                  ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%clcat' )
+            END SELECT
+         CASE default                     ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%cldes' )
+         END SELECT
+         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
+
+#if defined key_si3
+      !                                                      ! ------------------------- !
+      !                                                      !      Ice melt ponds       ! 
+      !                                                      ! ------------------------- !
+      ! needed by Met Office: 1) fraction of ponded ice 2) local/actual pond depth 
+      IF( ssnd(jps_a_p)%laction .OR. ssnd(jps_ht_p)%laction ) THEN 
+         SELECT CASE( sn_snd_mpnd%cldes)  
+         CASE( 'ice only' )  
+            SELECT CASE( sn_snd_mpnd%clcat )  
+            CASE( 'yes' )  
+               ztmp3(:,:,1:jpl) =  a_ip_eff(:,:,1:jpl)
+               ztmp4(:,:,1:jpl) =  h_ip(:,:,1:jpl)  
+            CASE( 'no' )  
+               ztmp3(:,:,:) = 0.0  
+               ztmp4(:,:,:) = 0.0  
+               DO jl=1,jpl  
+                 ztmp3(:,:,1) = ztmp3(:,:,1) + a_ip_frac(:,:,jpl)
+                 ztmp4(:,:,1) = ztmp4(:,:,1) + h_ip(:,:,jpl)
+               ENDDO  
+            CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_mpnd%clcat' )  
+            END SELECT  
+         CASE default      ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_mpnd%cldes' )     
+         END SELECT  
+         IF( ssnd(jps_a_p)%laction  )   CALL cpl_snd( jps_a_p , isec, ztmp3, info )     
+         IF( ssnd(jps_ht_p)%laction )   CALL cpl_snd( jps_ht_p, isec, ztmp4, info )     
+      ENDIF 
+      ! 
+      !                                                      ! ------------------------- !
+      !                                                      !     Ice conductivity      ! 
+      !                                                      ! ------------------------- !
+      ! needed by Met Office
+      IF( ssnd(jps_kice)%laction ) THEN 
+         SELECT CASE( sn_snd_cond%cldes) 
+         CASE( 'weighted ice' )    
+            SELECT CASE( sn_snd_cond%clcat ) 
+            CASE( 'yes' )    
+	       ztmp3(:,:,1:jpl) =  cnd_ice(:,:,1:jpl) * a_i(:,:,1:jpl) 
+            CASE( 'no' ) 
+               ztmp3(:,:,:) = 0.0 
+               DO jl=1,jpl 
+                 ztmp3(:,:,1) = ztmp3(:,:,1) + cnd_ice(:,:,jl) * a_i(:,:,jl) 
+               ENDDO 
+            CASE default   ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_cond%clcat' ) 
+            END SELECT 
+         CASE( 'ice only' )    
+           ztmp3(:,:,1:jpl) = cnd_ice(:,:,1:jpl) 
+         CASE default      ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_cond%cldes' )     
+         END SELECT 
+         IF( ssnd(jps_kice)%laction )   CALL cpl_snd( jps_kice, isec, ztmp3, info ) 
+      ENDIF 
+#endif
+
+      !                                                      ! ------------------------- !
+      !                                                      !  CO2 flux from PISCES     ! 
+      !                                                      ! ------------------------- !
+      IF( ssnd(jps_co2)%laction .AND. l_co2cpl )   THEN  
+         ztmp1(:,:) = oce_co2(:,:) * 1000.  ! conversion in molC/m2/s 
+         CALL cpl_snd( jps_co2, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ) , info ) 
+      ENDIF 
+      !
+      !                                                      ! ------------------------- !
+      IF( ssnd(jps_ocx1)%laction ) THEN                      !      Surface current      !
+         !                                                   ! ------------------------- !
+         !    
+         !                                                  j+1   j     -----V---F
+         ! surface velocity always sent from T point                     !       |
+         !                                                        j      |   T   U
+         !                                                               |       |
+         !                                                   j    j-1   -I-------|
+         !                                               (for I)         |       |
+         !                                                              i-1  i   i
+         !                                                               i      i+1 (for I)
+         IF( nn_components == jp_iam_opa ) THEN
+            zotx1(:,:) = un(:,:,1)  
+            zoty1(:,:) = vn(:,:,1)  
+         ELSE        
+            SELECT CASE( TRIM( sn_snd_crt%cldes ) )
+            CASE( 'oce only'             )      ! C-grid ==> T
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zotx1(ji,jj) = 0.5 * ( un(ji,jj,1) + un(ji-1,jj  ,1) )
+                     zoty1(ji,jj) = 0.5 * ( vn(ji,jj,1) + vn(ji  ,jj-1,1) ) 
+                  END DO
+               END DO
+            CASE( 'weighted oce and ice' )      ! Ocean and Ice on C-grid ==> T  
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zotx1(ji,jj) = 0.5 * ( un   (ji,jj,1) + un   (ji-1,jj  ,1) ) * zfr_l(ji,jj)  
+                     zoty1(ji,jj) = 0.5 * ( vn   (ji,jj,1) + vn   (ji  ,jj-1,1) ) * zfr_l(ji,jj)
+                     zitx1(ji,jj) = 0.5 * ( u_ice(ji,jj  ) + u_ice(ji-1,jj    ) ) *  fr_i(ji,jj)
+                     zity1(ji,jj) = 0.5 * ( v_ice(ji,jj  ) + v_ice(ji  ,jj-1  ) ) *  fr_i(ji,jj)
+                  END DO
+               END DO
+               CALL lbc_lnk_multi( 'sbccpl', zitx1, 'T', -1., zity1, 'T', -1. )
+            CASE( 'mixed oce-ice'        )      ! Ocean and Ice on C-grid ==> T
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zotx1(ji,jj) = 0.5 * ( un   (ji,jj,1) + un   (ji-1,jj  ,1) ) * zfr_l(ji,jj)   &
+                        &         + 0.5 * ( u_ice(ji,jj  ) + u_ice(ji-1,jj    ) ) *  fr_i(ji,jj)
+                     zoty1(ji,jj) = 0.5 * ( vn   (ji,jj,1) + vn   (ji  ,jj-1,1) ) * zfr_l(ji,jj)   &
+                        &         + 0.5 * ( v_ice(ji,jj  ) + v_ice(ji  ,jj-1  ) ) *  fr_i(ji,jj)
+                  END DO
+               END DO
+            END SELECT
+            CALL lbc_lnk_multi( 'sbccpl', zotx1, ssnd(jps_ocx1)%clgrid, -1.,  zoty1, ssnd(jps_ocy1)%clgrid, -1. )
+            !
+         ENDIF
+         !
+         !
+         IF( TRIM( sn_snd_crt%clvor ) == 'eastward-northward' ) THEN             ! Rotation of the components
+            !                                                                     ! Ocean component
+            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->e', ztmp1 )       ! 1st component 
+            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocx1)%clgrid, 'ij->n', ztmp2 )       ! 2nd component 
+            zotx1(:,:) = ztmp1(:,:)                                                   ! overwrite the components 
+            zoty1(:,:) = ztmp2(:,:)
+            IF( ssnd(jps_ivx1)%laction ) THEN                                     ! Ice component
+               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->e', ztmp1 )    ! 1st component 
+               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->n', ztmp2 )    ! 2nd component 
+               zitx1(:,:) = ztmp1(:,:)                                                ! overwrite the components 
+               zity1(:,:) = ztmp2(:,:)
+            ENDIF
+         ENDIF
+         !
+         ! spherical coordinates to cartesian -> 2 components to 3 components
+         IF( TRIM( sn_snd_crt%clvref ) == 'cartesian' ) THEN
+            ztmp1(:,:) = zotx1(:,:)                     ! ocean currents
+            ztmp2(:,:) = zoty1(:,:)
+            CALL oce2geo ( ztmp1, ztmp2, 'T', zotx1, zoty1, zotz1 )
+            !
+            IF( ssnd(jps_ivx1)%laction ) THEN           ! ice velocities
+               ztmp1(:,:) = zitx1(:,:)
+               ztmp1(:,:) = zity1(:,:)
+               CALL oce2geo ( ztmp1, ztmp2, 'T', zitx1, zity1, zitz1 )
+            ENDIF
+         ENDIF
+         !
+         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_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
+      !
+      !                                                      ! ------------------------- ! 
+      !                                                      !  Surface current to waves ! 
+      !                                                      ! ------------------------- ! 
+      IF( ssnd(jps_ocxw)%laction .OR. ssnd(jps_ocyw)%laction ) THEN 
+          !     
+          !                                                  j+1  j     -----V---F 
+          ! surface velocity always sent from T point                    !       | 
+          !                                                       j      |   T   U 
+          !                                                              |       | 
+          !                                                   j   j-1   -I-------| 
+          !                                               (for I)        |       | 
+          !                                                             i-1  i   i 
+          !                                                              i      i+1 (for I) 
+          SELECT CASE( TRIM( sn_snd_crtw%cldes ) ) 
+          CASE( 'oce only'             )      ! C-grid ==> T 
+             DO jj = 2, jpjm1 
+                DO ji = fs_2, fs_jpim1   ! vector opt. 
+                   zotx1(ji,jj) = 0.5 * ( un(ji,jj,1) + un(ji-1,jj  ,1) ) 
+                   zoty1(ji,jj) = 0.5 * ( vn(ji,jj,1) + vn(ji , jj-1,1) )  
+                END DO 
+             END DO 
+          CASE( 'weighted oce and ice' )      ! Ocean and Ice on C-grid ==> T   
+             DO jj = 2, jpjm1 
+                DO ji = fs_2, fs_jpim1   ! vector opt. 
+                   zotx1(ji,jj) = 0.5 * ( un   (ji,jj,1) + un   (ji-1,jj  ,1) ) * zfr_l(ji,jj)   
+                   zoty1(ji,jj) = 0.5 * ( vn   (ji,jj,1) + vn   (ji  ,jj-1,1) ) * zfr_l(ji,jj) 
+                   zitx1(ji,jj) = 0.5 * ( u_ice(ji,jj  ) + u_ice(ji-1,jj    ) ) *  fr_i(ji,jj) 
+                   zity1(ji,jj) = 0.5 * ( v_ice(ji,jj  ) + v_ice(ji  ,jj-1  ) ) *  fr_i(ji,jj) 
+                END DO
+             END DO
+             CALL lbc_lnk_multi( 'sbccpl', zitx1, 'T', -1.,  zity1, 'T', -1. ) 
+          CASE( 'mixed oce-ice'        )      ! Ocean and Ice on C-grid ==> T  
+             DO jj = 2, jpjm1 
+                DO ji = fs_2, fs_jpim1   ! vector opt. 
+                   zotx1(ji,jj) = 0.5 * ( un   (ji,jj,1) + un   (ji-1,jj  ,1) ) * zfr_l(ji,jj)   & 
+                      &         + 0.5 * ( u_ice(ji,jj  ) + u_ice(ji-1,jj    ) ) *  fr_i(ji,jj) 
+                   zoty1(ji,jj) = 0.5 * ( vn   (ji,jj,1) + vn   (ji  ,jj-1,1) ) * zfr_l(ji,jj)   & 
+                      &         + 0.5 * ( v_ice(ji,jj  ) + v_ice(ji  ,jj-1  ) ) *  fr_i(ji,jj) 
+                END DO
+             END DO
+          END SELECT
+         CALL lbc_lnk_multi( 'sbccpl', zotx1, ssnd(jps_ocxw)%clgrid, -1., zoty1, ssnd(jps_ocyw)%clgrid, -1. ) 
+         ! 
+         ! 
+         IF( TRIM( sn_snd_crtw%clvor ) == 'eastward-northward' ) THEN             ! Rotation of the components 
+         !                                                                        ! Ocean component 
+            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocxw)%clgrid, 'ij->e', ztmp1 )       ! 1st component  
+            CALL rot_rep( zotx1, zoty1, ssnd(jps_ocxw)%clgrid, 'ij->n', ztmp2 )       ! 2nd component  
+            zotx1(:,:) = ztmp1(:,:)                                                   ! overwrite the components  
+            zoty1(:,:) = ztmp2(:,:)  
+            IF( ssnd(jps_ivx1)%laction ) THEN                                     ! Ice component 
+               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->e', ztmp1 )    ! 1st component  
+               CALL rot_rep( zitx1, zity1, ssnd(jps_ivx1)%clgrid, 'ij->n', ztmp2 )    ! 2nd component  
+               zitx1(:,:) = ztmp1(:,:)                                                ! overwrite the components  
+               zity1(:,:) = ztmp2(:,:) 
+            ENDIF 
+         ENDIF 
+         ! 
+!         ! spherical coordinates to cartesian -> 2 components to 3 components 
+!         IF( TRIM( sn_snd_crtw%clvref ) == 'cartesian' ) THEN 
+!            ztmp1(:,:) = zotx1(:,:)                     ! ocean currents 
+!            ztmp2(:,:) = zoty1(:,:) 
+!            CALL oce2geo ( ztmp1, ztmp2, 'T', zotx1, zoty1, zotz1 ) 
+!            ! 
+!            IF( ssnd(jps_ivx1)%laction ) THEN           ! ice velocities 
+!               ztmp1(:,:) = zitx1(:,:) 
+!               ztmp1(:,:) = zity1(:,:) 
+!               CALL oce2geo ( ztmp1, ztmp2, 'T', zitx1, zity1, zitz1 ) 
+!            ENDIF 
+!         ENDIF 
+         ! 
+         IF( ssnd(jps_ocxw)%laction )   CALL cpl_snd( jps_ocxw, isec, RESHAPE ( zotx1, (/jpi,jpj,1/) ), info )   ! ocean x current 1st grid 
+         IF( ssnd(jps_ocyw)%laction )   CALL cpl_snd( jps_ocyw, isec, RESHAPE ( zoty1, (/jpi,jpj,1/) ), info )   ! ocean y current 1st grid 
+         !  
+      ENDIF 
+      ! 
+      IF( ssnd(jps_ficet)%laction ) THEN 
+         CALL cpl_snd( jps_ficet, isec, RESHAPE ( fr_i, (/jpi,jpj,1/) ), info ) 
+      END IF 
+      !                                                      ! ------------------------- ! 
+      !                                                      !   Water levels to waves   ! 
+      !                                                      ! ------------------------- ! 
+      IF( ssnd(jps_wlev)%laction ) THEN 
+         IF( ln_apr_dyn ) THEN  
+            IF( kt /= nit000 ) THEN  
+               ztmp1(:,:) = sshb(:,:) - 0.5 * ( ssh_ib(:,:) + ssh_ibb(:,:) )  
+            ELSE  
+               ztmp1(:,:) = sshb(:,:)  
+            ENDIF  
+         ELSE  
+            ztmp1(:,:) = sshn(:,:)  
+         ENDIF  
+         CALL cpl_snd( jps_wlev  , isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info ) 
+      END IF 
+      !
+      !  Fields sent by OPA to SAS when doing OPA<->SAS coupling
+      !                                                        ! SSH
+      IF( ssnd(jps_ssh )%laction )  THEN
+         !                          ! removed inverse barometer ssh when Patm
+         !                          forcing is used (for sea-ice dynamics)
+         IF( ln_apr_dyn ) THEN   ;   ztmp1(:,:) = sshb(:,:) - 0.5 * ( ssh_ib(:,:) + ssh_ibb(:,:) )
+         ELSE                    ;   ztmp1(:,:) = sshn(:,:)
+         ENDIF
+         CALL cpl_snd( jps_ssh   , isec, RESHAPE ( ztmp1            , (/jpi,jpj,1/) ), info )
+
+      ENDIF
+      !                                                        ! SSS
+      IF( ssnd(jps_soce  )%laction )  THEN
+         CALL cpl_snd( jps_soce  , isec, RESHAPE ( tsn(:,:,1,jp_sal), (/jpi,jpj,1/) ), info )
+      ENDIF
+      !                                                        ! first T level thickness 
+      IF( ssnd(jps_e3t1st )%laction )  THEN
+         CALL cpl_snd( jps_e3t1st, isec, RESHAPE ( e3t_n(:,:,1)   , (/jpi,jpj,1/) ), info )
+      ENDIF
+      !                                                        ! Qsr fraction
+      IF( ssnd(jps_fraqsr)%laction )  THEN
+         CALL cpl_snd( jps_fraqsr, isec, RESHAPE ( fraqsr_1lev(:,:) , (/jpi,jpj,1/) ), info )
+      ENDIF
+      !
+      !  Fields sent by SAS to OPA when OASIS coupling
+      !                                                        ! Solar heat flux
+      IF( ssnd(jps_qsroce)%laction )  CALL cpl_snd( jps_qsroce, isec, RESHAPE ( qsr , (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_qnsoce)%laction )  CALL cpl_snd( jps_qnsoce, isec, RESHAPE ( qns , (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_oemp  )%laction )  CALL cpl_snd( jps_oemp  , isec, RESHAPE ( emp , (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_sflx  )%laction )  CALL cpl_snd( jps_sflx  , isec, RESHAPE ( sfx , (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_otx1  )%laction )  CALL cpl_snd( jps_otx1  , isec, RESHAPE ( utau, (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_oty1  )%laction )  CALL cpl_snd( jps_oty1  , isec, RESHAPE ( vtau, (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_rnf   )%laction )  CALL cpl_snd( jps_rnf   , isec, RESHAPE ( rnf , (/jpi,jpj,1/) ), info )
+      IF( ssnd(jps_taum  )%laction )  CALL cpl_snd( jps_taum  , isec, RESHAPE ( taum, (/jpi,jpj,1/) ), info )
+
+#if defined key_si3
+      !                                                      ! ------------------------- !
+      !                                                      ! Sea surface freezing temp ! 
+      !                                                      ! ------------------------- !
+      ! needed by Met Office
+      CALL eos_fzp(tsn(:,:,1,jp_sal), sstfrz)
+      ztmp1(:,:) = sstfrz(:,:) + rt0
+      IF( ssnd(jps_sstfrz)%laction )  CALL cpl_snd( jps_sstfrz, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info)
+#endif
+      !
+   END SUBROUTINE sbc_cpl_snd
+   
+   !!======================================================================
+END MODULE sbccpl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcdcy.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcdcy.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcdcy.F90	(revision 14097)
@@ -0,0 +1,248 @@
+MODULE sbcdcy
+   !!======================================================================
+   !!                    ***  MODULE  sbcdcy  ***
+   !! Ocean forcing:  compute the diurnal cycle
+   !!======================================================================
+   !! History : OPA  !  2005-02  (D. Bernie)  Original code
+   !!   NEMO    2.0  !  2006-02  (S. Masson, G. Madec)  adaptation to NEMO
+   !!           3.1  !  2009-07  (J.M. Molines)  adaptation to v3.1
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  sbc_dcy : solar flux at kt from daily mean, taking diurnal cycle into account
+   !!----------------------------------------------------------------------
+   USE oce              ! ocean dynamics and tracers
+   USE phycst           ! ocean physics
+   USE dom_oce          ! ocean space and time domain
+   USE sbc_oce          ! Surface boundary condition: ocean fields
+   !
+   USE in_out_manager   ! I/O manager
+   USE lib_mpp          ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   INTEGER, PUBLIC ::   nday_qsr   !: day when parameters were computed
+   
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   raa , rbb  , rcc  , rab     ! diurnal cycle parameters
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rtmd, rdawn, rdusk, rscal   !    -      -       -
+  
+   PUBLIC   sbc_dcy        ! routine called by sbc
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+      INTEGER FUNCTION sbc_dcy_alloc()
+         !!----------------------------------------------------------------------
+         !!                ***  FUNCTION sbc_dcy_alloc  ***
+         !!----------------------------------------------------------------------
+         ALLOCATE( raa (jpi,jpj) , rbb  (jpi,jpj) , rcc  (jpi,jpj) , rab  (jpi,jpj) ,     &
+            &      rtmd(jpi,jpj) , rdawn(jpi,jpj) , rdusk(jpi,jpj) , rscal(jpi,jpj) , STAT=sbc_dcy_alloc )
+            !
+         CALL mpp_sum ( 'sbcdcy', sbc_dcy_alloc )
+         IF( sbc_dcy_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sbc_dcy_alloc: failed to allocate arrays' )
+      END FUNCTION sbc_dcy_alloc
+
+
+   FUNCTION sbc_dcy( pqsrin, l_mask ) RESULT( zqsrout )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_dcy  ***
+      !!
+      !! ** Purpose : introduce a diurnal cycle of qsr from daily values
+      !!
+      !! ** Method  : see Appendix A of Bernie et al. 2007.
+      !!
+      !! ** Action  : redistribute daily QSR on each time step following the diurnal cycle
+      !!
+      !! reference  : Bernie, DJ, E Guilyardi, G Madec, JM Slingo, and SJ Woolnough, 2007
+      !!              Impact of resolving the diurnal cycle in an ocean--atmosphere GCM. 
+      !!              Part 1: a diurnally forced OGCM. Climate Dynamics 29:6, 575-590.
+      !!----------------------------------------------------------------------
+      LOGICAL , OPTIONAL          , INTENT(in) ::   l_mask    ! use the routine for night mask computation
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pqsrin    ! input daily QSR flux 
+      REAL(wp), DIMENSION(jpi,jpj)             ::   zqsrout   ! output QSR flux with diurnal cycle
+      !!
+      INTEGER  ::   ji, jj                                       ! dummy loop indices
+      INTEGER, DIMENSION(jpi,jpj) :: imask_night ! night mask
+      REAL(wp) ::   ztwopi, zinvtwopi, zconvrad 
+      REAL(wp) ::   zlo, zup, zlousd, zupusd
+      REAL(wp) ::   zdsws, zdecrad, ztx, zsin, zcos
+      REAL(wp) ::   ztmp, ztmp1, ztmp2, ztest
+      REAL(wp) ::   ztmpm, ztmpm1, ztmpm2
+      !---------------------------statement functions------------------------
+      REAL(wp) ::   fintegral, pt1, pt2, paaa, pbbb, pccc        ! dummy statement function arguments
+      fintegral( pt1, pt2, paaa, pbbb, pccc ) =                         &
+         &   paaa * pt2 + zinvtwopi * pbbb * SIN(pccc + ztwopi * pt2)   &
+         & - paaa * pt1 - zinvtwopi * pbbb * SIN(pccc + ztwopi * pt1)
+      !!---------------------------------------------------------------------
+      !
+      ! Initialization
+      ! --------------
+      ztwopi    = 2._wp * rpi
+      zinvtwopi = 1._wp / ztwopi
+      zconvrad  = ztwopi / 360._wp
+
+      ! When are we during the day (from 0 to 1)
+      zlo = ( REAL(nsec_day, wp) - 0.5_wp * rdt ) / rday
+      zup = zlo + ( REAL(nn_fsbc, wp)     * rdt ) / rday
+      !                                          
+      IF( nday_qsr == -1 ) THEN       ! first time step only  
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'sbc_dcy : introduce diurnal cycle from daily mean qsr'
+            WRITE(numout,*) '~~~~~~~'
+            WRITE(numout,*)
+         ENDIF
+         ! allocate sbcdcy arrays
+         IF( sbc_dcy_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_dcy_alloc : unable to allocate arrays' )
+         ! Compute rcc needed to compute the time integral of the diurnal cycle
+         rcc(:,:) = zconvrad * glamt(:,:) - rpi
+         ! time of midday
+         rtmd(:,:) = 0.5_wp - glamt(:,:) / 360._wp
+         rtmd(:,:) = MOD( (rtmd(:,:) + 1._wp) , 1._wp)
+      ENDIF
+
+      ! If this is a new day, we have to update the dawn, dusk and scaling function  
+      !----------------------
+    
+      !     2.1 dawn and dusk  
+
+      ! nday is the number of days since the beginning of the current month 
+      IF( nday_qsr /= nday ) THEN 
+         ! save the day of the year and the daily mean of qsr
+         nday_qsr = nday 
+         ! number of days since the previous winter solstice (supposed to be always 21 December)         
+         zdsws = REAL(11 + nday_year, wp)
+         ! declination of the earths orbit
+         zdecrad = (-23.5_wp * zconvrad) * COS( zdsws * ztwopi / REAL(nyear_len(1),wp) )
+         ! Compute A and B needed to compute the time integral of the diurnal cycle
+
+         zsin = SIN( zdecrad )   ;   zcos = COS( zdecrad )
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ztmp = zconvrad * gphit(ji,jj)
+               raa(ji,jj) = SIN( ztmp ) * zsin
+               rbb(ji,jj) = COS( ztmp ) * zcos
+            END DO  
+         END DO  
+         ! Compute the time of dawn and dusk
+
+         ! rab to test if the day time is equal to 0, less than 24h of full day        
+         rab(:,:) = -raa(:,:) / rbb(:,:)
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( ABS(rab(ji,jj)) < 1._wp ) THEN         ! day duration is less than 24h
+         ! When is it night?
+                  ztx = zinvtwopi * (ACOS(rab(ji,jj)) - rcc(ji,jj))
+                  ztest = -rbb(ji,jj) * SIN( rcc(ji,jj) + ztwopi * ztx )
+         ! is it dawn or dusk?
+                  IF ( ztest > 0._wp ) THEN
+                     rdawn(ji,jj) = ztx
+                     rdusk(ji,jj) = rtmd(ji,jj) + ( rtmd(ji,jj) - rdawn(ji,jj) )
+                  ELSE
+                     rdusk(ji,jj) = ztx
+                     rdawn(ji,jj) = rtmd(ji,jj) - ( rdusk(ji,jj) - rtmd(ji,jj) )
+                  ENDIF
+               ELSE
+                  rdawn(ji,jj) = rtmd(ji,jj) + 0.5_wp
+                  rdusk(ji,jj) = rdawn(ji,jj)
+               ENDIF
+             END DO  
+         END DO  
+         rdawn(:,:) = MOD( (rdawn(:,:) + 1._wp), 1._wp )
+         rdusk(:,:) = MOD( (rdusk(:,:) + 1._wp), 1._wp )
+         !     2.2 Compute the scaling function:
+         !         S* = the inverse of the time integral of the diurnal cycle from dawn to dusk
+         !         Avoid possible infinite scaling factor, associated with very short daylight
+         !         periods, by ignoring periods less than 1/1000th of a day (ticket #1040)
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( ABS(rab(ji,jj)) < 1._wp ) THEN         ! day duration is less than 24h
+                  rscal(ji,jj) = 0.0_wp
+                  IF ( rdawn(ji,jj) < rdusk(ji,jj) ) THEN      ! day time in one part
+                     IF( (rdusk(ji,jj) - rdawn(ji,jj) ) .ge. 0.001_wp ) THEN
+                       rscal(ji,jj) = fintegral(rdawn(ji,jj), rdusk(ji,jj), raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                       rscal(ji,jj) = 1._wp / rscal(ji,jj)
+                     ENDIF
+                  ELSE                                         ! day time in two parts
+                     IF( (rdusk(ji,jj) + (1._wp - rdawn(ji,jj)) ) .ge. 0.001_wp ) THEN
+                       rscal(ji,jj) = fintegral(0._wp, rdusk(ji,jj), raa(ji,jj), rbb(ji,jj), rcc(ji,jj))   &
+                          &         + fintegral(rdawn(ji,jj), 1._wp, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                       rscal(ji,jj) = 1. / rscal(ji,jj)
+                     ENDIF
+                  ENDIF
+               ELSE
+                  IF ( raa(ji,jj) > rbb(ji,jj) ) THEN         ! 24h day
+                     rscal(ji,jj) = fintegral(0._wp, 1._wp, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                     rscal(ji,jj) = 1._wp / rscal(ji,jj)
+                  ELSE                                          ! No day
+                     rscal(ji,jj) = 0.0_wp
+                  ENDIF
+               ENDIF
+            END DO  
+         END DO  
+         !
+         ztmp = rday / ( rdt * REAL(nn_fsbc, wp) )
+         rscal(:,:) = rscal(:,:) * ztmp
+         !
+      ENDIF 
+         !     3. update qsr with the diurnal cycle
+         !     ------------------------------------
+
+      imask_night(:,:) = 0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztmpm = 0._wp
+            IF( ABS(rab(ji,jj)) < 1. ) THEN         ! day duration is less than 24h
+               !
+               IF( rdawn(ji,jj) < rdusk(ji,jj) ) THEN       ! day time in one part
+                  zlousd = MAX(zlo, rdawn(ji,jj))
+                  zlousd = MIN(zlousd, zup)
+                  zupusd = MIN(zup, rdusk(ji,jj))
+                  zupusd = MAX(zupusd, zlo)
+                  ztmp = fintegral(zlousd, zupusd, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                  zqsrout(ji,jj) = pqsrin(ji,jj) * ztmp * rscal(ji,jj)
+                  ztmpm = zupusd - zlousd
+                  IF ( ztmpm .EQ. 0 ) imask_night(ji,jj) = 1
+                  !
+               ELSE                                         ! day time in two parts
+                  zlousd = MIN(zlo, rdusk(ji,jj))
+                  zupusd = MIN(zup, rdusk(ji,jj))
+                  ztmp1 = fintegral(zlousd, zupusd, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                  ztmpm1=zupusd-zlousd
+                  zlousd = MAX(zlo, rdawn(ji,jj))
+                  zupusd = MAX(zup, rdawn(ji,jj))
+                  ztmp2 = fintegral(zlousd, zupusd, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                  ztmpm2 =zupusd-zlousd
+                  ztmp = ztmp1 + ztmp2
+                  ztmpm = ztmpm1 + ztmpm2
+                  zqsrout(ji,jj) = pqsrin(ji,jj) * ztmp * rscal(ji,jj)
+                  IF (ztmpm .EQ. 0.) imask_night(ji,jj) = 1
+               ENDIF
+            ELSE                                   ! 24h light or 24h night
+               !
+               IF( raa(ji,jj) > rbb(ji,jj) ) THEN           ! 24h day
+                  ztmp = fintegral(zlo, zup, raa(ji,jj), rbb(ji,jj), rcc(ji,jj)) 
+                  zqsrout(ji,jj) = pqsrin(ji,jj) * ztmp * rscal(ji,jj)
+                  imask_night(ji,jj) = 0
+                  !
+               ELSE                                         ! No day
+                  zqsrout(ji,jj) = 0.0_wp
+                  imask_night(ji,jj) = 1
+               ENDIF
+            ENDIF
+         END DO  
+      END DO  
+      !
+      IF( PRESENT(l_mask) .AND. l_mask ) THEN
+         zqsrout(:,:) = float(imask_night(:,:))
+      ENDIF
+      !
+   END FUNCTION sbc_dcy
+
+   !!======================================================================
+END MODULE sbcdcy
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcflx.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcflx.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcflx.F90	(revision 14097)
@@ -0,0 +1,183 @@
+MODULE sbcflx
+   !!======================================================================
+   !!                       ***  MODULE  sbcflx  ***
+   !! Ocean forcing:  momentum, heat and freshwater flux formulation
+   !!=====================================================================
+   !! History :  1.0  !  2006-06  (G. Madec)  Original code
+   !!            3.3  !  2010-10  (S. Masson)  add diurnal cycle
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   namflx   : flux formulation namlist
+   !!   sbc_flx  : flux formulation as ocean surface boundary condition (forced mode, fluxes read in NetCDF files)
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! surface boundary condition: ocean fields
+   USE sbcdcy          ! surface boundary condition: diurnal cycle on qsr
+   USE phycst          ! physical constants
+   !
+   USE fldread         ! read input fields
+   USE iom             ! IOM library
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sbc_flx       ! routine called by step.F90
+
+   INTEGER , PARAMETER ::   jp_utau = 1   ! index of wind stress (i-component) file
+   INTEGER , PARAMETER ::   jp_vtau = 2   ! index of wind stress (j-component) file
+   INTEGER , PARAMETER ::   jp_qtot = 3   ! index of total (non solar+solar) heat file
+   INTEGER , PARAMETER ::   jp_qsr  = 4   ! index of solar heat file
+   INTEGER , PARAMETER ::   jp_emp  = 5   ! index of evaporation-precipation file
+ !!INTEGER , PARAMETER ::   jp_sfx  = 6   ! index of salt flux flux
+   INTEGER , PARAMETER ::   jpfld   = 5 !! 6 ! maximum number of files to read 
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf    ! structure of input fields (file informations, fields read)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_flx( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_flx  ***
+      !!                   
+      !! ** Purpose :   provide at each time step the surface ocean fluxes
+      !!                (momentum, heat, freshwater and runoff) 
+      !!
+      !! ** Method  : - READ each fluxes in NetCDF files:
+      !!                   i-component of the stress              utau  (N/m2)
+      !!                   j-component of the stress              vtau  (N/m2)
+      !!                   net downward heat flux                 qtot  (watt/m2)
+      !!                   net downward radiative flux            qsr   (watt/m2)
+      !!                   net upward freshwater (evapo - precip) emp   (kg/m2/s)
+      !!                   salt flux                              sfx   (pss*dh*rho/dt => g/m2/s)
+      !!
+      !!      CAUTION :  - never mask the surface stress fields
+      !!                 - the stress is assumed to be in the (i,j) mesh referential
+      !!
+      !! ** Action  :   update at each time-step
+      !!              - utau, vtau  i- and j-component of the wind stress
+      !!              - taum        wind stress module at T-point
+      !!              - wndm        10m wind module at T-point
+      !!              - qns         non solar heat flux including heat flux due to emp
+      !!              - qsr         solar heat flux
+      !!              - emp         upward mass flux (evap. - precip.)
+      !!              - sfx         salt flux; set to zero at nit000 but possibly non-zero
+      !!                            if ice
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!
+      INTEGER  ::   ji, jj, jf            ! dummy indices
+      INTEGER  ::   ierror                ! return error code
+      INTEGER  ::   ios                   ! Local integer output status for namelist read
+      REAL(wp) ::   zfact                 ! temporary scalar
+      REAL(wp) ::   zrhoa  = 1.22         ! Air density kg/m3
+      REAL(wp) ::   zcdrag = 1.5e-3       ! drag coefficient
+      REAL(wp) ::   ztx, zty, zmod, zcoef ! temporary variables
+      !!
+      CHARACTER(len=100) ::  cn_dir                               ! Root directory for location of flx files
+      TYPE(FLD_N), DIMENSION(jpfld) ::   slf_i                    ! array of namelist information structures
+      TYPE(FLD_N) ::   sn_utau, sn_vtau, sn_qtot, sn_qsr, sn_emp !!, sn_sfx ! informations about the fields to be read
+      NAMELIST/namsbc_flx/ cn_dir, sn_utau, sn_vtau, sn_qtot, sn_qsr, sn_emp !!, sn_sfx
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN                ! First call kt=nit000  
+         ! set file information
+         REWIND( numnam_ref )              ! Namelist namsbc_flx in reference namelist : Files for fluxes
+         READ  ( numnam_ref, namsbc_flx, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_flx in reference namelist' )
+
+         REWIND( numnam_cfg )              ! Namelist namsbc_flx in configuration namelist : Files for fluxes
+         READ  ( numnam_cfg, namsbc_flx, IOSTAT = ios, ERR = 902 )
+902      IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_flx in configuration namelist' )
+         IF(lwm) WRITE ( numond, namsbc_flx ) 
+         !
+         !                                         ! check: do we plan to use ln_dm2dc with non-daily forcing?
+         IF( ln_dm2dc .AND. sn_qsr%freqh /= 24. )   &
+            &   CALL ctl_stop( 'sbc_blk_core: ln_dm2dc can be activated only with daily short-wave forcing' ) 
+         !
+         !                                         ! store namelist information in an array
+         slf_i(jp_utau) = sn_utau   ;   slf_i(jp_vtau) = sn_vtau
+         slf_i(jp_qtot) = sn_qtot   ;   slf_i(jp_qsr ) = sn_qsr 
+         slf_i(jp_emp ) = sn_emp !! ;   slf_i(jp_sfx ) = sn_sfx
+         !
+         ALLOCATE( sf(jpfld), STAT=ierror )        ! set sf structure
+         IF( ierror > 0 ) THEN   
+            CALL ctl_stop( 'sbc_flx: unable to allocate sf structure' )   ;   RETURN  
+         ENDIF
+         DO ji= 1, jpfld
+            ALLOCATE( sf(ji)%fnow(jpi,jpj,1) )
+            IF( slf_i(ji)%ln_tint ) ALLOCATE( sf(ji)%fdta(jpi,jpj,1,2) )
+         END DO
+         !                                         ! fill sf with slf_i and control print
+         CALL fld_fill( sf, slf_i, cn_dir, 'sbc_flx', 'flux formulation for ocean surface boundary condition', 'namsbc_flx' )
+         !
+      ENDIF
+
+      CALL fld_read( kt, nn_fsbc, sf )                            ! input fields provided at the current time-step
+     
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN                        ! update ocean fluxes at each SBC frequency
+
+         IF( ln_dm2dc ) THEN   ;   qsr(:,:) = sbc_dcy( sf(jp_qsr)%fnow(:,:,1) ) * tmask(:,:,1)  ! modify now Qsr to include the diurnal cycle
+         ELSE                  ;   qsr(:,:) =          sf(jp_qsr)%fnow(:,:,1)   * tmask(:,:,1)
+         ENDIF
+         DO jj = 1, jpj                                           ! set the ocean fluxes from read fields
+            DO ji = 1, jpi
+               utau(ji,jj) =   sf(jp_utau)%fnow(ji,jj,1)                              * umask(ji,jj,1)
+               vtau(ji,jj) =   sf(jp_vtau)%fnow(ji,jj,1)                              * vmask(ji,jj,1)
+               qns (ji,jj) = ( sf(jp_qtot)%fnow(ji,jj,1) - sf(jp_qsr)%fnow(ji,jj,1) ) * tmask(ji,jj,1)
+               emp (ji,jj) =   sf(jp_emp )%fnow(ji,jj,1)                              * tmask(ji,jj,1)
+               !!sfx (ji,jj) = sf(jp_sfx )%fnow(ji,jj,1)                              * tmask(ji,jj,1) 
+            END DO
+         END DO
+         !                                                        ! add to qns the heat due to e-p
+         !clem: I do not think it is needed
+         !!qns(:,:) = qns(:,:) - emp(:,:) * sst_m(:,:) * rcp        ! mass flux is at SST
+         !
+         ! clem: without these lbc calls, it seems that the northfold is not ok (true in 3.6, not sure in 4.x) 
+         CALL lbc_lnk_multi( 'sbcflx', utau, 'U', -1._wp, vtau, 'V', -1._wp, &
+            &                           qns, 'T',  1._wp, emp , 'T',  1._wp, qsr, 'T', 1._wp ) !! sfx, 'T', 1._wp  )
+         !
+         IF( nitend-nit000 <= 100 .AND. lwp ) THEN                ! control print (if less than 100 time-step asked)
+            WRITE(numout,*) 
+            WRITE(numout,*) '        read daily momentum, heat and freshwater fluxes OK'
+            DO jf = 1, jpfld
+               IF( jf == jp_utau .OR. jf == jp_vtau )   zfact =     1.
+               IF( jf == jp_qtot .OR. jf == jp_qsr  )   zfact =     0.1
+               IF( jf == jp_emp                     )   zfact = 86400.
+               WRITE(numout,*) 
+               WRITE(numout,*) ' day: ', ndastp , TRIM(sf(jf)%clvar), ' * ', zfact
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !                                                           ! module of wind stress and wind speed at T-point
+      ! Note the use of 0.5*(2-umask) in order to unmask the stress along coastlines
+      zcoef = 1. / ( zrhoa * zcdrag )
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            ztx = ( utau(ji-1,jj  ) + utau(ji,jj) ) * 0.5_wp * ( 2._wp - MIN( umask(ji-1,jj  ,1), umask(ji,jj,1) ) )
+            zty = ( vtau(ji  ,jj-1) + vtau(ji,jj) ) * 0.5_wp * ( 2._wp - MIN( vmask(ji  ,jj-1,1), vmask(ji,jj,1) ) ) 
+            zmod = 0.5_wp * SQRT( ztx * ztx + zty * zty ) * tmask(ji,jj,1)
+            taum(ji,jj) = zmod
+            wndm(ji,jj) = SQRT( zmod * zcoef )  !!clem: not used?
+         END DO
+      END DO
+      !
+      CALL lbc_lnk_multi( 'sbcflx', taum, 'T', 1._wp, wndm, 'T', 1._wp )
+      !
+      !
+   END SUBROUTINE sbc_flx
+
+   !!======================================================================
+END MODULE sbcflx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcfwb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcfwb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcfwb.F90	(revision 14097)
@@ -0,0 +1,238 @@
+MODULE sbcfwb
+   !!======================================================================
+   !!                       ***  MODULE  sbcfwb  ***
+   !! Ocean fluxes   : domain averaged freshwater budget
+   !!======================================================================
+   !! History :  OPA  ! 2001-02  (E. Durand)  Original code
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            3.0  ! 2006-08  (G. Madec)  Surface module
+   !!            3.2  ! 2009-07  (C. Talandier) emp mean s spread over erp area 
+   !!            3.6  ! 2014-11  (P. Mathiot  ) add ice shelf melting
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_fwb       : freshwater budget for global ocean configurations (free surface & forced mode)
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! surface ocean boundary condition
+   USE sbc_ice , ONLY : snwice_mass, snwice_mass_b, snwice_fmass
+   USE phycst         ! physical constants
+   USE sbcrnf         ! ocean runoffs
+   USE sbcisf         ! ice shelf melting contribution
+   USE sbcssr         ! Sea-Surface damping terms
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! IOM
+   USE lib_mpp        ! distribued memory computing library
+   USE timing         ! Timing
+   USE lbclnk         ! ocean lateral boundary conditions
+   USE lib_fortran    ! 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_fwb    ! routine called by step
+
+   REAL(wp) ::   a_fwb_b   ! annual domain averaged freshwater budget
+   REAL(wp) ::   a_fwb     ! for 2 year before (_b) and before year.
+   REAL(wp) ::   fwfold    ! fwfold to be suppressed
+   REAL(wp) ::   area      ! global mean ocean surface (interior domain)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_fwb( kt, kn_fwb, kn_fsbc )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_fwb  ***
+      !!
+      !! ** Purpose :   Control the mean sea surface drift
+      !!
+      !! ** Method  :   several ways  depending on kn_fwb
+      !!                =0 no control 
+      !!                =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 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt       ! ocean time-step index
+      INTEGER, INTENT( in ) ::   kn_fsbc  ! 
+      INTEGER, INTENT( in ) ::   kn_fwb   ! ocean time-step index
+      !
+      INTEGER  ::   inum, ikty, iyear     ! local integers
+      REAL(wp) ::   z_fwf, z_fwf_nsrf, zsum_fwf, zsum_erp                ! local scalars
+      REAL(wp) ::   zsurf_neg, zsurf_pos, zsurf_tospread, zcoef          !   -      -
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   ztmsk_neg, ztmsk_pos, z_wgt ! 2D workspaces
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   ztmsk_tospread, zerp_cor    !   -      -
+      REAL(wp)   ,DIMENSION(1) ::   z_fwfprv  
+      COMPLEX(wp),DIMENSION(1) ::   y_fwfnow  
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'sbc_fwb : FreshWater Budget correction'
+            WRITE(numout,*) '~~~~~~~'
+            IF( kn_fwb == 1 )   WRITE(numout,*) '          instantaneously set to zero'
+            IF( kn_fwb == 2 )   WRITE(numout,*) '          adjusted from previous year budget'
+            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 ' )
+         IF( kn_fwb == 3 .AND. ln_isfcav    )   CALL ctl_stop( 'sbc_fwb: nn_fwb = 3 with ln_isfcav = .TRUE. not working, we stop ' )
+         !
+         area = glob_sum( 'sbcfwb', e1e2t(:,:) * tmask(:,:,1))           ! interior global domain surface
+         ! isf cavities are excluded because it can feedback to the melting with generation of inhibition of plumes
+         ! and in case of no melt, it can generate HSSW.
+         !
+#if ! defined key_si3 && ! defined key_cice
+         snwice_mass_b(:,:) = 0.e0               ! no sea-ice model is being used : no snow+ice mass
+         snwice_mass  (:,:) = 0.e0
+         snwice_fmass (:,:) = 0.e0
+#endif
+         !
+      ENDIF
+
+      SELECT CASE ( kn_fwb )
+      !
+      CASE ( 1 )                             !==  global mean fwf set to zero  ==!
+         !
+         IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN
+            y_fwfnow(1) = local_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + fwfisf(:,:) - snwice_fmass(:,:) ) )
+            CALL mpp_delay_sum( 'sbcfwb', 'fwb', y_fwfnow(:), z_fwfprv(:), kt == nitend - nn_fsbc + 1 )
+            z_fwfprv(1) = z_fwfprv(1) / area
+            zcoef = z_fwfprv(1) * rcp
+            emp(:,:) = emp(:,:) - z_fwfprv(1)        * tmask(:,:,1)
+            qns(:,:) = qns(:,:) + zcoef * sst_m(:,:) * tmask(:,:,1) ! account for change to the heat budget due to fw correction
+         ENDIF
+         !
+      CASE ( 2 )                             !==  fwf budget adjusted from the previous year  ==!
+         !
+         IF( kt == nit000 ) THEN                      ! initialisation
+            !                                         ! Read the corrective factor on precipitations (fwfold)
+            IF ( ln_rstart .AND. iom_varid( numror, 'a_fwb_b', ldstop = .FALSE. ) > 0     &
+               &           .AND. iom_varid( numror, 'a_fwb',   ldstop = .FALSE. ) > 0 ) THEN
+               IF(lwp) WRITE(numout,*) 'sbc_fwb : reading FW-budget adjustment from restart file'
+               CALL iom_get( numror, 'a_fwb_b', a_fwb_b, ldxios = lrxios )
+               CALL iom_get( numror, 'a_fwb',   a_fwb,   ldxios = lrxios )
+            ELSE
+               CALL ctl_opn( inum, 'EMPave_old.dat', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+               READ ( inum, "(24X,I8,2ES24.16)" ) iyear, a_fwb_b, a_fwb
+               CLOSE( inum )
+            END IF
+            fwfold = a_fwb                            ! current year freshwater budget correction
+            !                                         ! estimate from the previous year budget
+            IF(lwp)WRITE(numout,*)
+            IF(lwp)WRITE(numout,*)'sbc_fwb : year = ',iyear  , ' freshwater budget correction = ', fwfold
+            IF(lwp)WRITE(numout,*)'          year = ',iyear-1, ' freshwater budget read       = ', a_fwb
+            IF(lwp)WRITE(numout,*)'          year = ',iyear-2, ' freshwater budget read       = ', a_fwb_b
+            !
+            IF( lwxios ) THEN                         ! Activate output of restart variables
+               CALL iom_set_rstw_var_active( 'a_fwb_b' )
+               CALL iom_set_rstw_var_active( 'a_fwb'   )
+            END IF
+         ENDIF   
+         !                                         ! Update fwfold if new year start
+         ikty = 365 * 86400 / rdt                  !!bug  use of 365 days leap year or 360d year !!!!!!!
+         IF( MOD( kt, ikty ) == 0 ) THEN
+            a_fwb_b = a_fwb                           ! mean sea level taking into account the ice+snow
+                                                      ! sum over the global domain
+            a_fwb   = glob_sum( 'sbcfwb', e1e2t(:,:) * ( sshn(:,:) + snwice_mass(:,:) * r1_rau0 ) )
+            a_fwb   = a_fwb * 1.e+3 / ( area * rday * 365. )     ! convert in Kg/m3/s = mm/s
+!!gm        !                                                      !!bug 365d year 
+            fwfold =  a_fwb                           ! current year freshwater budget correction
+            !                                         ! estimate from the previous year budget
+         ENDIF
+         ! 
+         IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN         ! correct the freshwater fluxes
+            zcoef = fwfold * rcp
+            emp(:,:) = emp(:,:) + fwfold             * tmask(:,:,1)
+            qns(:,:) = qns(:,:) - zcoef * sst_m(:,:) * tmask(:,:,1) ! account for change to the heat budget due to fw correction
+         ENDIF
+         ! Output restart information
+         IF( lrst_oce ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'sbc_fwb : writing FW-budget adjustment to ocean restart file at it = ', kt
+            IF(lwp) WRITE(numout,*) '~~~~'
+            IF( lwxios ) CALL iom_swap( cwxios_context )
+            CALL iom_rstput( kt, nitrst, numrow, 'a_fwb_b', a_fwb_b, ldxios = lwxios )
+            CALL iom_rstput( kt, nitrst, numrow, 'a_fwb',   a_fwb,   ldxios = lwxios )
+            IF( lwxios ) CALL iom_swap( cxios_context  )
+         END IF
+         !
+         IF( kt == nitend .AND. lwm ) THEN            ! save fwfold value in a file (only one required)
+            CALL ctl_opn( inum, 'EMPave.dat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., narea )
+            WRITE( inum, "(24X,I8,2ES24.16)" ) nyear, a_fwb_b, a_fwb
+            CLOSE( inum )
+         ENDIF
+         !
+      CASE ( 3 )                             !==  global fwf set to zero and spread out over erp area  ==!
+         !
+         ALLOCATE( ztmsk_neg(jpi,jpj) , ztmsk_pos(jpi,jpj) , ztmsk_tospread(jpi,jpj) , z_wgt(jpi,jpj) , zerp_cor(jpi,jpj) )
+         !
+         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(:,:)
+            !                                                  ! fwf global mean (excluding ocean to ice/snow exchanges) 
+            z_fwf     = glob_sum( 'sbcfwb', e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + fwfisf(:,:) - snwice_fmass(:,:) ) ) / area
+            !            
+            IF( z_fwf < 0._wp ) THEN         ! spread out over >0 erp area to increase evaporation
+               zsurf_pos = glob_sum( 'sbcfwb', e1e2t(:,:)*ztmsk_pos(:,:) )
+               zsurf_tospread      = zsurf_pos
+               ztmsk_tospread(:,:) = ztmsk_pos(:,:)
+            ELSE                             ! spread out over <0 erp area to increase precipitation
+               zsurf_neg = glob_sum( 'sbcfwb', e1e2t(:,:)*ztmsk_neg(:,:) )  ! Area filled by <0 and >0 erp 
+               zsurf_tospread      = zsurf_neg
+               ztmsk_tospread(:,:) = ztmsk_neg(:,:)
+            ENDIF
+            !
+            zsum_fwf   = glob_sum( 'sbcfwb', 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( 'sbcfwb', 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( 'sbcfwb', 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
+         DEALLOCATE( ztmsk_neg , ztmsk_pos , ztmsk_tospread , z_wgt , zerp_cor )
+         !
+      CASE DEFAULT                           !==  you should never be there  ==!
+         CALL ctl_stop( 'sbc_fwb : wrong nn_fwb value for the FreshWater Budget correction, choose either 1, 2 or 3' )
+         !
+      END SELECT
+      !
+   END SUBROUTINE sbc_fwb
+
+   !!======================================================================
+END MODULE sbcfwb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_cice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_cice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_cice.F90	(revision 14097)
@@ -0,0 +1,1072 @@
+MODULE sbcice_cice
+   !!======================================================================
+   !!                       ***  MODULE  sbcice_cice  ***
+   !! To couple with sea ice model CICE (LANL)
+   !!=====================================================================
+#if defined key_cice
+   !!----------------------------------------------------------------------
+   !!   'key_cice' :                                     CICE sea-ice model
+   !!----------------------------------------------------------------------
+   !!   sbc_ice_cice  : sea-ice model time-stepping and update ocean sbc over ice-covered area
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE domvvl
+   USE phycst, only : rcp, rau0, r1_rau0, rhos, rhoi
+   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)
+   USE daymod          ! calendar
+   USE fldread         ! read input fields
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice   fields
+   USE sbcblk          ! Surface boundary condition: bulk
+   USE sbccpl
+
+   USE ice_kinds_mod
+   USE ice_blocks
+   USE ice_domain
+   USE ice_domain_size
+   USE ice_boundary
+   USE ice_constants
+   USE ice_gather_scatter
+   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,  &
+                strocnxT,strocnyT,                               & 
+                sst,sss,uocn,vocn,ss_tltx,ss_tlty,fsalt_gbm,     &
+                fresh_gbm,fhocn_gbm,fswthru_gbm,frzmlt,          &
+                flatn_f,fsurfn_f,fcondtopn_f,                    &
+                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,  &
+                strocnxT,strocnyT,                               & 
+                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 CICE_InitMod
+   USE CICE_RunMod
+   USE CICE_FinalMod
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC cice_sbc_init   ! routine called by sbc_init
+   PUBLIC cice_sbc_final  ! routine called by sbc_final
+   PUBLIC sbc_ice_cice    ! routine called by sbc
+
+   INTEGER             ::   ji_off
+   INTEGER             ::   jj_off
+
+   INTEGER , PARAMETER ::   jpfld   = 13   ! maximum number of files to read 
+   INTEGER , PARAMETER ::   jp_snow = 1    ! index of snow file
+   INTEGER , PARAMETER ::   jp_rain = 2    ! index of rain file
+   INTEGER , PARAMETER ::   jp_sblm = 3    ! index of sublimation file
+   INTEGER , PARAMETER ::   jp_top1 = 4    ! index of category 1 topmelt file
+   INTEGER , PARAMETER ::   jp_top2 = 5    ! index of category 2 topmelt file
+   INTEGER , PARAMETER ::   jp_top3 = 6    ! index of category 3 topmelt file
+   INTEGER , PARAMETER ::   jp_top4 = 7    ! index of category 4 topmelt file
+   INTEGER , PARAMETER ::   jp_top5 = 8    ! index of category 5 topmelt file
+   INTEGER , PARAMETER ::   jp_bot1 = 9    ! index of category 1 botmelt file
+   INTEGER , PARAMETER ::   jp_bot2 = 10   ! index of category 2 botmelt file
+   INTEGER , PARAMETER ::   jp_bot3 = 11   ! index of category 3 botmelt file
+   INTEGER , PARAMETER ::   jp_bot4 = 12   ! index of category 4 botmelt file
+   INTEGER , PARAMETER ::   jp_bot5 = 13   ! index of category 5 botmelt file
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf    ! structure of input fields (file informations, fields read)
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:), PRIVATE ::   png     ! local array used in sbc_cice_ice
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_ice_cice_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION sbc_ice_cice_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( png(jpi,jpj,jpnij), STAT=sbc_ice_cice_alloc )
+      CALL mpp_sum ( 'sbcice_cice', sbc_ice_cice_alloc )
+      IF( sbc_ice_cice_alloc > 0 )   CALL ctl_warn('sbc_ice_cice_alloc: allocation of arrays failed.')
+   END FUNCTION sbc_ice_cice_alloc
+
+   SUBROUTINE sbc_ice_cice( kt, ksbc )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ice_cice  ***
+      !!                   
+      !! ** Purpose :   update the ocean surface boundary condition via the 
+      !!                CICE Sea Ice Model time stepping 
+      !!
+      !! ** Method  : - Get any extra forcing fields for CICE  
+      !!              - Prepare forcing fields
+      !!              - CICE model time stepping
+      !!              - call the routine that computes mass and 
+      !!                heat fluxes at the ice/ocean interface
+      !!
+      !! ** Action  : - time evolution of the CICE sea-ice model
+      !!              - update all sbc variables below sea-ice:
+      !!                utau, vtau, qns , qsr, emp , sfx
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt      ! ocean time step
+      INTEGER, INTENT(in) ::   ksbc    ! surface forcing type
+      !!----------------------------------------------------------------------
+      !
+      !                                        !----------------------!
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN     !  Ice time-step only  !
+         !                                     !----------------------!
+
+         ! Make sure any fluxes required for CICE are set
+         IF      ( ksbc == jp_flx ) THEN
+            CALL cice_sbc_force(kt)
+         ELSE IF ( ksbc == jp_purecpl ) THEN
+            CALL sbc_cpl_ice_flx( fr_i )
+         ENDIF
+
+         CALL cice_sbc_in  ( kt, ksbc )
+         CALL CICE_Run
+         CALL cice_sbc_out ( kt, ksbc )
+
+         IF ( ksbc == jp_purecpl )  CALL cice_sbc_hadgam(kt+1)
+
+      ENDIF                                          ! End sea-ice time step only
+      !
+   END SUBROUTINE sbc_ice_cice
+
+
+   SUBROUTINE cice_sbc_init( ksbc )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_init  ***
+      !! ** Purpose: Initialise ice related fields for NEMO and coupling
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in  ) ::   ksbc                ! surface forcing type
+      REAL(wp), DIMENSION(jpi,jpj) :: ztmp1, ztmp2
+      REAL(wp) ::   zcoefu, zcoefv, zcoeff            ! local scalar
+      INTEGER  ::   ji, jj, jl, jk                    ! dummy loop indices
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)'cice_sbc_init'
+
+      ji_off = INT ( (jpiglo - nx_global) / 2 )
+      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 ( (ksbc == jp_flx) .OR. (ksbc == jp_purecpl) ) 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 (ksbc == jp_blk) 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' )
+         ENDIF
+      ENDIF
+
+
+! allocate sbc_ice and sbc_cice arrays
+      IF( sbc_ice_alloc()      /= 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_cice_alloc : unable to allocate arrays' )
+      IF( sbc_ice_cice_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_cice_alloc : unable to allocate cice arrays' )
+
+! Ensure ocean temperatures are nowhere below freezing if not a NEMO restart
+      IF( .NOT. ln_rstart ) THEN
+         tsn(:,:,:,jp_tem) = MAX (tsn(:,:,:,jp_tem),Tocnfrz)
+         tsb(:,:,:,jp_tem) = tsn(:,:,:,jp_tem)
+      ENDIF
+
+      fr_iu(:,:)=0.0
+      fr_iv(:,:)=0.0
+
+      CALL cice2nemo(aice,fr_i, 'T', 1. )
+      IF ( (ksbc == jp_flx) .OR. (ksbc == jp_purecpl) ) THEN
+         DO jl=1,ncat
+            CALL cice2nemo(aicen(:,:,jl,:),a_i(:,:,jl), 'T', 1. )
+         ENDDO
+      ENDIF
+
+! T point to U point
+! T point to V point
+      DO jj=1,jpjm1
+         DO ji=1,jpim1
+            fr_iu(ji,jj)=0.5*(fr_i(ji,jj)+fr_i(ji+1,jj))*umask(ji,jj,1)
+            fr_iv(ji,jj)=0.5*(fr_i(ji,jj)+fr_i(ji,jj+1))*vmask(ji,jj,1)
+         ENDDO
+      ENDDO
+
+      CALL lbc_lnk_multi( 'sbcice_cice', fr_iu , 'U', 1.,  fr_iv , 'V', 1. )
+
+      ! set the snow+ice mass
+      CALL cice2nemo(vsno(:,:,:),ztmp1,'T', 1. )
+      CALL cice2nemo(vice(:,:,:),ztmp2,'T', 1. )
+      snwice_mass  (:,:) = ( rhos * ztmp1(:,:) + rhoi * ztmp2(:,:)  )
+      snwice_mass_b(:,:) = snwice_mass(:,:)
+
+      IF( .NOT.ln_rstart ) THEN
+         IF( ln_ice_embd ) THEN            ! embedded sea-ice: deplete the initial ssh below sea-ice area
+            sshn(:,:) = sshn(:,:) - snwice_mass(:,:) * r1_rau0
+            sshb(:,:) = sshb(:,:) - snwice_mass(:,:) * r1_rau0
+
+!!gm This should be put elsewhere....   (same remark for limsbc)
+!!gm especially here it is assumed zstar coordinate, but it can be ztilde....
+            IF( .NOT.ln_linssh ) THEN
+               !
+               DO jk = 1,jpkm1                     ! adjust initial vertical scale factors
+                  e3t_n(:,:,jk) = e3t_0(:,:,jk)*( 1._wp + sshn(:,:)*tmask(:,:,1)/(ht_0(:,:) + 1.0 - tmask(:,:,1)) )
+                  e3t_b(:,:,jk) = e3t_0(:,:,jk)*( 1._wp + sshb(:,:)*tmask(:,:,1)/(ht_0(:,:) + 1.0 - tmask(:,:,1)) )
+               ENDDO
+               e3t_a(:,:,:) = e3t_b(:,:,:)
+               ! Reconstruction of all vertical scale factors at now and before time-steps
+               ! =============================================================================
+               ! Horizontal scale factor interpolations
+               ! --------------------------------------
+               CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )
+               CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )
+               CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+               CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+               CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )
+               ! Vertical scale factor interpolations
+               ! ------------------------------------
+               CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )
+               CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+               CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+               CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+               CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+               ! t- and w- points depth
+               ! ----------------------
+               gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+               gdepw_n(:,:,1) = 0.0_wp
+               gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+               DO jk = 2, jpk
+                  gdept_n(:,:,jk) = gdept_n(:,:,jk-1) + e3w_n(:,:,jk)
+                  gdepw_n(:,:,jk) = gdepw_n(:,:,jk-1) + e3t_n(:,:,jk-1)
+                  gde3w_n(:,:,jk) = gdept_n(:,:,jk  ) - sshn   (:,:)
+               END DO
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE cice_sbc_init
+
+   
+   SUBROUTINE cice_sbc_in( kt, ksbc )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_in  ***
+      !! ** Purpose: Set coupling fields and pass to CICE
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt   ! ocean time step
+      INTEGER, INTENT(in   ) ::   ksbc ! surface forcing type
+      !
+      INTEGER  ::   ji, jj, jl                   ! dummy loop indices      
+      REAL(wp), DIMENSION(jpi,jpj) :: ztmp, zpice
+      REAL(wp), DIMENSION(jpi,jpj,ncat) :: ztmpn
+      REAL(wp) ::   zintb, zintn  ! dummy argument
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp) WRITE(numout,*)'cice_sbc_in'
+      ENDIF
+
+      ztmp(:,:)=0.0
+
+! Aggregate ice concentration already set in cice_sbc_out (or cice_sbc_init on 
+! the first time-step)
+
+! forced and coupled case 
+
+      IF ( (ksbc == jp_flx).OR.(ksbc == jp_purecpl) ) THEN
+
+         ztmpn(:,:,:)=0.0
+
+! x comp of wind stress (CI_1)
+! U point to F point
+         DO jj=1,jpjm1
+            DO ji=1,jpi
+               ztmp(ji,jj) = 0.5 * (  fr_iu(ji,jj) * utau(ji,jj)      &
+                                    + fr_iu(ji,jj+1) * utau(ji,jj+1) ) * fmask(ji,jj,1)
+            ENDDO
+         ENDDO
+         CALL nemo2cice(ztmp,strax,'F', -1. )
+
+! y comp of wind stress (CI_2)
+! V point to F point
+         DO jj=1,jpj
+            DO ji=1,jpim1
+               ztmp(ji,jj) = 0.5 * (  fr_iv(ji,jj) * vtau(ji,jj)      &
+                                    + fr_iv(ji+1,jj) * vtau(ji+1,jj) ) * fmask(ji,jj,1)
+            ENDDO
+         ENDDO
+         CALL nemo2cice(ztmp,stray,'F', -1. )
+
+! Surface downward latent heat flux (CI_5)
+         IF (ksbc == jp_flx) THEN
+            DO jl=1,ncat
+               ztmpn(:,:,jl)=qla_ice(:,:,1)*a_i(:,:,jl)
+            ENDDO
+         ELSE
+! emp_ice is set in sbc_cpl_ice_flx as sublimation-snow
+            qla_ice(:,:,1)= - ( emp_ice(:,:)+sprecip(:,:) ) * rLsub
+! End of temporary code
+            DO jj=1,jpj
+               DO ji=1,jpi
+                  IF (fr_i(ji,jj).eq.0.0) THEN
+                     DO jl=1,ncat
+                        ztmpn(ji,jj,jl)=0.0
+                     ENDDO
+                     ! This will then be conserved in CICE
+                     ztmpn(ji,jj,1)=qla_ice(ji,jj,1)
+                  ELSE
+                     DO jl=1,ncat
+                        ztmpn(ji,jj,jl)=qla_ice(ji,jj,1)*a_i(ji,jj,jl)/fr_i(ji,jj)
+                     ENDDO
+                  ENDIF
+               ENDDO
+            ENDDO
+         ENDIF
+         DO jl=1,ncat
+            CALL nemo2cice(ztmpn(:,:,jl),flatn_f(:,:,jl,:),'T', 1. )
+
+! GBM conductive flux through ice (CI_6)
+!  Convert to GBM
+            IF (ksbc == jp_flx) THEN
+               ztmp(:,:) = botmelt(:,:,jl)*a_i(:,:,jl)
+            ELSE
+               ztmp(:,:) = botmelt(:,:,jl)
+            ENDIF
+            CALL nemo2cice(ztmp,fcondtopn_f(:,:,jl,:),'T', 1. )
+
+! GBM surface heat flux (CI_7)
+!  Convert to GBM
+            IF (ksbc == jp_flx) THEN
+               ztmp(:,:) = (topmelt(:,:,jl)+botmelt(:,:,jl))*a_i(:,:,jl) 
+            ELSE
+               ztmp(:,:) = (topmelt(:,:,jl)+botmelt(:,:,jl))
+            ENDIF
+            CALL nemo2cice(ztmp,fsurfn_f(:,:,jl,:),'T', 1. )
+         ENDDO
+
+      ELSE IF (ksbc == jp_blk) THEN
+
+! Pass bulk forcing fields to CICE (which will calculate heat fluxes etc itself)
+! x comp and y comp of atmosphere surface wind (CICE expects on T points)
+         ztmp(:,:) = wndi_ice(:,:)
+         CALL nemo2cice(ztmp,uatm,'T', -1. )
+         ztmp(:,:) = wndj_ice(:,:)
+         CALL nemo2cice(ztmp,vatm,'T', -1. )
+         ztmp(:,:) = SQRT ( wndi_ice(:,:)**2 + wndj_ice(:,:)**2 )
+         CALL nemo2cice(ztmp,wind,'T', 1. )    ! Wind speed (m/s)
+         ztmp(:,:) = qsr_ice(:,:,1)
+         CALL nemo2cice(ztmp,fsw,'T', 1. )     ! Incoming short-wave (W/m^2)
+         ztmp(:,:) = qlw_ice(:,:,1)
+         CALL nemo2cice(ztmp,flw,'T', 1. )     ! Incoming long-wave (W/m^2)
+         ztmp(:,:) = tatm_ice(:,:)
+         CALL nemo2cice(ztmp,Tair,'T', 1. )    ! Air temperature (K)
+         CALL nemo2cice(ztmp,potT,'T', 1. )    ! Potential temp (K)
+! Following line uses MAX(....) to avoid problems if tatm_ice has unset halo rows  
+         ztmp(:,:) = 101000. / ( 287.04 * MAX(1.0,tatm_ice(:,:)) )    
+                                               ! Constant (101000.) atm pressure assumed
+         CALL nemo2cice(ztmp,rhoa,'T', 1. )    ! Air density (kg/m^3)
+         ztmp(:,:) = qatm_ice(:,:)
+         CALL nemo2cice(ztmp,Qa,'T', 1. )      ! Specific humidity (kg/kg)
+         ztmp(:,:)=10.0
+         CALL nemo2cice(ztmp,zlvl,'T', 1. )    ! Atmos level height (m)
+
+! May want to check all values are physically realistic (as in CICE routine 
+! prepare_forcing)?
+
+! Divide shortwave into spectral bands (as in prepare_forcing)
+         ztmp(:,:)=qsr_ice(:,:,1)*frcvdr       ! visible direct
+         CALL nemo2cice(ztmp,swvdr,'T', 1. )             
+         ztmp(:,:)=qsr_ice(:,:,1)*frcvdf       ! visible diffuse
+         CALL nemo2cice(ztmp,swvdf,'T', 1. )              
+         ztmp(:,:)=qsr_ice(:,:,1)*frcidr       ! near IR direct
+         CALL nemo2cice(ztmp,swidr,'T', 1. )
+         ztmp(:,:)=qsr_ice(:,:,1)*frcidf       ! near IR diffuse
+         CALL nemo2cice(ztmp,swidf,'T', 1. )
+
+      ENDIF
+
+! Snowfall
+! 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. ) 
+
+! Freezing/melting potential
+! Calculated over NEMO leapfrog timestep (hence 2*dt)
+      nfrzmlt(:,:) = rau0 * rcp * e3t_m(:,:) * ( Tocnfrz-sst_m(:,:) ) / ( 2.0*dt )
+
+      ztmp(:,:) = nfrzmlt(:,:)
+      CALL nemo2cice(ztmp,frzmlt,'T', 1. )
+
+! SST  and SSS
+
+      CALL nemo2cice(sst_m,sst,'T', 1. )
+      CALL nemo2cice(sss_m,sss,'T', 1. )
+
+! x comp and y comp of surface ocean current
+! U point to F point
+      DO jj=1,jpjm1
+         DO ji=1,jpi
+            ztmp(ji,jj)=0.5*(ssu_m(ji,jj)+ssu_m(ji,jj+1))*fmask(ji,jj,1)
+         ENDDO
+      ENDDO
+      CALL nemo2cice(ztmp,uocn,'F', -1. )
+
+! V point to F point
+      DO jj=1,jpj
+         DO ji=1,jpim1
+            ztmp(ji,jj)=0.5*(ssv_m(ji,jj)+ssv_m(ji+1,jj))*fmask(ji,jj,1)
+         ENDDO
+      ENDDO
+      CALL nemo2cice(ztmp,vocn,'F', -1. )
+
+      IF( ln_ice_embd ) THEN             !== embedded sea ice: compute representative ice top surface ==!
+          !
+          ! average interpolation coeff as used in dynspg = (1/nn_fsbc) * {SUM[n/nn_fsbc], n=0,nn_fsbc-1}
+          !                                               = (1/nn_fsbc)^2 * {SUM[n], n=0,nn_fsbc-1}
+         zintn = REAL( nn_fsbc - 1 ) / REAL( nn_fsbc ) * 0.5_wp
+          !
+          ! average interpolation coeff as used in dynspg = (1/nn_fsbc) * {SUM[1-n/nn_fsbc], n=0,nn_fsbc-1}
+          !                                               = (1/nn_fsbc)^2 * (nn_fsbc^2 - {SUM[n], n=0,nn_fsbc-1})
+         zintb = REAL( nn_fsbc + 1 ) / REAL( nn_fsbc ) * 0.5_wp
+          !
+         zpice(:,:) = ssh_m(:,:) + (  zintn * snwice_mass(:,:) +  zintb * snwice_mass_b(:,:)  ) * r1_rau0
+          !
+         !
+      ELSE                                    !== non-embedded sea ice: use ocean surface for slope calculation ==!
+         zpice(:,:) = ssh_m(:,:)
+      ENDIF
+
+! x comp and y comp of sea surface slope (on F points)
+! T point to F point
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1
+            ztmp(ji,jj)=0.5 * (  (zpice(ji+1,jj  )-zpice(ji,jj  )) * r1_e1u(ji,jj  )    &
+               &               + (zpice(ji+1,jj+1)-zpice(ji,jj+1)) * r1_e1u(ji,jj+1)  ) * fmask(ji,jj,1)
+         END DO
+      END DO
+      CALL nemo2cice( ztmp,ss_tltx,'F', -1. )
+
+! T point to F point
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1
+            ztmp(ji,jj)=0.5 * (  (zpice(ji  ,jj+1)-zpice(ji  ,jj)) * r1_e2v(ji  ,jj)    &
+               &               + (zpice(ji+1,jj+1)-zpice(ji+1,jj)) * r1_e2v(ji+1,jj)  ) *  fmask(ji,jj,1)
+         END DO
+      END DO
+      CALL nemo2cice(ztmp,ss_tlty,'F', -1. )
+      !
+   END SUBROUTINE cice_sbc_in
+
+
+   SUBROUTINE cice_sbc_out( kt, ksbc )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_out  ***
+      !! ** Purpose: Get fields from CICE and set surface fields for NEMO
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+      INTEGER, INTENT( in  ) ::   ksbc ! surface forcing type
+      
+      INTEGER  ::   ji, jj, jl                 ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) :: ztmp1, ztmp2
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp) WRITE(numout,*)'cice_sbc_out'
+      ENDIF
+      
+! x comp of ocean-ice stress 
+      CALL cice2nemo(strocnx,ztmp1,'F', -1. )
+      ss_iou(:,:)=0.0
+! F point to U point
+      DO jj=2,jpjm1
+         DO ji=2,jpim1
+            ss_iou(ji,jj) = 0.5 * ( ztmp1(ji,jj-1) + ztmp1(ji,jj) ) * umask(ji,jj,1)
+         ENDDO
+      ENDDO
+      CALL lbc_lnk( 'sbcice_cice', ss_iou , 'U', -1. )
+
+! y comp of ocean-ice stress 
+      CALL cice2nemo(strocny,ztmp1,'F', -1. )
+      ss_iov(:,:)=0.0
+! F point to V point
+
+      DO jj=1,jpjm1
+         DO ji=2,jpim1
+            ss_iov(ji,jj) = 0.5 * ( ztmp1(ji-1,jj) + ztmp1(ji,jj) ) * vmask(ji,jj,1)
+         ENDDO
+      ENDDO
+      CALL lbc_lnk( 'sbcice_cice', ss_iov , 'V', -1. )
+
+! x and y comps of surface stress
+! Combine wind stress and ocean-ice stress
+! [Note that fr_iu hasn't yet been updated, so still from start of CICE timestep]
+! strocnx and strocny already weighted by ice fraction in CICE so not done here 
+
+      utau(:,:)=(1.0-fr_iu(:,:))*utau(:,:)-ss_iou(:,:)
+      vtau(:,:)=(1.0-fr_iv(:,:))*vtau(:,:)-ss_iov(:,:)     
+ 
+! Also need ice/ocean stress on T points so that taum can be updated 
+! This interpolation is already done in CICE so best to use those values 
+      CALL cice2nemo(strocnxT,ztmp1,'T',-1.) 
+      CALL cice2nemo(strocnyT,ztmp2,'T',-1.) 
+ 
+! Update taum with modulus of ice-ocean stress 
+! strocnxT and strocnyT are not weighted by ice fraction in CICE so must be done here 
+taum(:,:)=(1.0-fr_i(:,:))*taum(:,:)+fr_i(:,:)*SQRT(ztmp1*ztmp1 + ztmp2*ztmp2) 
+
+! Freshwater fluxes 
+
+      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
+! Not ideal since aice won't be the same as in the atmosphere.  
+! 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 (ksbc == jp_blk) THEN
+         emp(:,:)  = (1.0-fr_i(:,:))*emp(:,:)        
+      ELSE IF (ksbc == jp_purecpl) 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
+         emp(:,:) = emp_tot(:,:)+tprecip(:,:)*fr_i(:,:) 
+      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)
+! Otherwise we are effectively allowing ice of higher salinity than the ocean to form
+! which has to be compensated for by the ocean salinity potentially going negative
+! This check breaks conservation but seems reasonable until we have prognostic ice salinity
+! Note the 1000.0 below is to convert from kg salt to g salt (needed for PSU)
+      WHERE (ztmp1(:,:).lt.0.0) ztmp2(:,:)=MAX(ztmp2(:,:),ztmp1(:,:)*sss_m(:,:)/1000.0)
+      sfx(:,:)=ztmp2(:,:)*1000.0
+      emp(:,:)=emp(:,:)-ztmp1(:,:)
+      fmmflx(:,:) = ztmp1(:,:) !!Joakim edit
+      
+      CALL lbc_lnk_multi( 'sbcice_cice', emp , 'T', 1., sfx , 'T', 1. )
+
+! Solar penetrative radiation and non solar surface heat flux
+
+! Scale qsr and qns according to ice fraction (bulk formulae only)
+
+      IF (ksbc == jp_blk) 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 (ksbc == jp_purecpl) THEN
+         qsr(:,:)= qsr_tot(:,:)
+         qns(:,:)= qns_tot(:,:)
+      ELSE
+         qns(:,:)= qns(:,:)-sprecip(:,:)*Lfresh*(1.0-fr_i(:,:))
+      ENDIF
+
+! 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( 'sbcice_cice', qsr , 'T', 1. )
+
+      DO jj=1,jpj
+         DO ji=1,jpi
+            nfrzmlt(ji,jj)=MAX(nfrzmlt(ji,jj),0.0)
+         ENDDO
+      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(:,:)
+
+      CALL lbc_lnk( 'sbcice_cice', qns , 'T', 1. )
+
+! Prepare for the following CICE time-step
+
+      CALL cice2nemo(aice,fr_i,'T', 1. )
+      IF ( (ksbc == jp_flx).OR.(ksbc == jp_purecpl) ) THEN
+         DO jl=1,ncat
+            CALL cice2nemo(aicen(:,:,jl,:),a_i(:,:,jl), 'T', 1. )
+         ENDDO
+      ENDIF
+
+! T point to U point
+! T point to V point
+      DO jj=1,jpjm1
+         DO ji=1,jpim1
+            fr_iu(ji,jj)=0.5*(fr_i(ji,jj)+fr_i(ji+1,jj))*umask(ji,jj,1)
+            fr_iv(ji,jj)=0.5*(fr_i(ji,jj)+fr_i(ji,jj+1))*vmask(ji,jj,1)
+         ENDDO
+      ENDDO
+
+      CALL lbc_lnk_multi( 'sbcice_cice', fr_iu , 'U', 1., fr_iv , 'V', 1. )
+
+      ! set the snow+ice mass
+      CALL cice2nemo(vsno(:,:,:),ztmp1,'T', 1. )
+      CALL cice2nemo(vice(:,:,:),ztmp2,'T', 1. )
+      snwice_mass  (:,:) = ( rhos * ztmp1(:,:) + rhoi * ztmp2(:,:)  )
+      snwice_mass_b(:,:) = snwice_mass(:,:)
+      snwice_fmass (:,:) = ( snwice_mass(:,:) - snwice_mass_b(:,:) ) / dt
+      !
+   END SUBROUTINE cice_sbc_out
+
+
+   SUBROUTINE cice_sbc_hadgam( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_hadgam  ***
+      !! ** Purpose: Prepare fields needed to pass to HadGAM3 atmosphere
+      !! 
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+      !!
+      INTEGER  ::   jl                        ! dummy loop index
+      INTEGER  ::   ierror
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp) WRITE(numout,*)'cice_sbc_hadgam'
+         IF( sbc_cpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_cpl_alloc : unable to allocate arrays' )
+      ENDIF
+
+      !                                         ! =========================== !
+      !                                         !   Prepare Coupling fields   !
+      !                                         ! =========================== !
+      !
+      ! x and y comp of ice velocity
+      !
+      CALL cice2nemo(uvel,u_ice,'F', -1. )
+      CALL cice2nemo(vvel,v_ice,'F', -1. )
+      !
+      ! Ice concentration (CO_1) = a_i calculated at end of cice_sbc_out  
+      !
+      ! Snow and ice thicknesses (CO_2 and CO_3)
+      !
+      DO jl = 1, ncat
+         CALL cice2nemo( vsnon(:,:,jl,:), h_s(:,:,jl),'T', 1. )
+         CALL cice2nemo( vicen(:,:,jl,:), h_i(:,:,jl),'T', 1. )
+      END DO
+      !
+   END SUBROUTINE cice_sbc_hadgam
+
+
+   SUBROUTINE cice_sbc_final
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_final  ***
+      !! ** Purpose: Finalize CICE
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)'cice_sbc_final'
+      !
+      CALL CICE_Finalize
+      !
+   END SUBROUTINE cice_sbc_final
+
+
+   SUBROUTINE cice_sbc_force (kt)
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice_sbc_force  ***
+      !! ** Purpose : Provide CICE forcing from files
+      !!
+      !!---------------------------------------------------------------------
+      !! ** Method  :   READ monthly flux file in NetCDF files
+      !!      
+      !!  snowfall    
+      !!  rainfall    
+      !!  sublimation rate    
+      !!  topmelt (category)
+      !!  botmelt (category)
+      !!
+      !! History :
+      !!----------------------------------------------------------------------
+      USE iom
+      !!
+      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
+      !!
+      INTEGER  ::   ierror             ! return error code
+      INTEGER  ::   ifpr               ! dummy loop index
+      !!
+      CHARACTER(len=100) ::  cn_dir                            !   Root directory for location of CICE forcing files
+      TYPE(FLD_N), DIMENSION(jpfld) ::   slf_i                 ! array of namelist informations on the fields to read
+      TYPE(FLD_N) ::   sn_snow, sn_rain, sn_sblm               ! informations about the fields to be read
+      TYPE(FLD_N) ::   sn_top1, sn_top2, sn_top3, sn_top4, sn_top5
+      TYPE(FLD_N) ::   sn_bot1, sn_bot2, sn_bot3, sn_bot4, sn_bot5 
+      !!
+      NAMELIST/namsbc_cice/ cn_dir, sn_snow, sn_rain, sn_sblm,   &
+         &                          sn_top1, sn_top2, sn_top3, sn_top4, sn_top5,  &
+         &                          sn_bot1, sn_bot2, sn_bot3, sn_bot4, sn_bot5
+      INTEGER :: ios
+      !!---------------------------------------------------------------------
+
+      !                                         ! ====================== !
+      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)
+901      IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_cice in reference namelist' )
+
+         REWIND( numnam_cfg )              ! Namelist namsbc_cice in configuration namelist : Parameters of the run
+         READ  ( numnam_cfg, namsbc_cice, IOSTAT = ios, ERR = 902 )
+902      IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_cice in configuration namelist' )
+         IF(lwm) WRITE ( numond, namsbc_cice )
+
+         ! store namelist information in an array
+         slf_i(jp_snow) = sn_snow   ;   slf_i(jp_rain) = sn_rain   ;   slf_i(jp_sblm) = sn_sblm
+         slf_i(jp_top1) = sn_top1   ;   slf_i(jp_top2) = sn_top2   ;   slf_i(jp_top3) = sn_top3
+         slf_i(jp_top4) = sn_top4   ;   slf_i(jp_top5) = sn_top5   ;   slf_i(jp_bot1) = sn_bot1
+         slf_i(jp_bot2) = sn_bot2   ;   slf_i(jp_bot3) = sn_bot3   ;   slf_i(jp_bot4) = sn_bot4
+         slf_i(jp_bot5) = sn_bot5
+         
+         ! set sf structure
+         ALLOCATE( sf(jpfld), STAT=ierror )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'cice_sbc_force: unable to allocate sf structure' )   ;   RETURN
+         ENDIF
+
+         DO ifpr= 1, jpfld
+            ALLOCATE( sf(ifpr)%fnow(jpi,jpj,1) )
+            ALLOCATE( sf(ifpr)%fdta(jpi,jpj,1,2) )
+         END DO
+
+         ! fill sf with slf_i and control print
+         CALL fld_fill( sf, slf_i, cn_dir, 'cice_sbc_force', 'flux formulation for CICE', 'namsbc_cice' )
+         !
+      ENDIF
+
+      CALL fld_read( kt, nn_fsbc, sf )           ! Read input fields and provides the
+      !                                          ! input fields at the current time-step
+
+      ! set the fluxes from read fields
+      sprecip(:,:) = sf(jp_snow)%fnow(:,:,1)
+      tprecip(:,:) = sf(jp_snow)%fnow(:,:,1)+sf(jp_rain)%fnow(:,:,1)
+! May be better to do this conversion somewhere else
+      qla_ice(:,:,1) = -rLsub*sf(jp_sblm)%fnow(:,:,1)
+      topmelt(:,:,1) = sf(jp_top1)%fnow(:,:,1)
+      topmelt(:,:,2) = sf(jp_top2)%fnow(:,:,1)
+      topmelt(:,:,3) = sf(jp_top3)%fnow(:,:,1)
+      topmelt(:,:,4) = sf(jp_top4)%fnow(:,:,1)
+      topmelt(:,:,5) = sf(jp_top5)%fnow(:,:,1)
+      botmelt(:,:,1) = sf(jp_bot1)%fnow(:,:,1)
+      botmelt(:,:,2) = sf(jp_bot2)%fnow(:,:,1)
+      botmelt(:,:,3) = sf(jp_bot3)%fnow(:,:,1)
+      botmelt(:,:,4) = sf(jp_bot4)%fnow(:,:,1)
+      botmelt(:,:,5) = sf(jp_bot5)%fnow(:,:,1)
+
+      ! control print (if less than 100 time-step asked)
+      IF( nitend-nit000 <= 100 .AND. lwp ) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) '        read forcing fluxes for CICE OK'
+         CALL FLUSH(numout)
+      ENDIF
+
+   END SUBROUTINE cice_sbc_force
+
+   SUBROUTINE nemo2cice( pn, pc, cd_type, psgn)
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE nemo2cice  ***
+      !! ** Purpose :   Transfer field in NEMO array to field in CICE array.  
+#if defined key_nemocice_decomp
+      !!             
+      !!                NEMO and CICE PE sub domains are identical, hence
+      !!                there is no need to gather or scatter data from 
+      !!                one PE configuration to another.
+#else
+      !!                Automatically gather/scatter between 
+      !!                different processors and blocks
+      !! ** Method :    A. Ensure all haloes are filled in NEMO field (pn)
+      !!                B. Gather pn into global array (png)
+      !!                C. Map png into CICE global array (pcg)
+      !!                D. Scatter pcg to CICE blocks (pc) + update haloes  
+#endif
+      !!---------------------------------------------------------------------
+      CHARACTER(len=1), INTENT( in ) ::   &
+          cd_type       ! nature of pn grid-point
+          !             !   = T or F gridpoints
+      REAL(wp), INTENT( in ) ::   &
+          psgn          ! control of the sign change
+          !             !   =-1 , the sign is modified following the type of b.c. used
+          !             !   = 1 , no sign change
+      REAL(wp), DIMENSION(jpi,jpj) :: pn
+#if !defined key_nemocice_decomp
+      REAL(wp), DIMENSION(jpiglo,jpjglo) :: png2
+      REAL (kind=dbl_kind), dimension(nx_global,ny_global) :: pcg
+#endif
+      REAL (kind=dbl_kind), dimension(nx_block,ny_block,max_blocks) :: pc
+      INTEGER (int_kind) :: &
+         field_type,        &! id for type of field (scalar, vector, angle)
+         grid_loc            ! id for location on horizontal grid
+                            !  (center, NEcorner, Nface, Eface)
+
+      INTEGER  ::   ji, jj, jn                      ! dummy loop indices
+      !!---------------------------------------------------------------------
+
+!     A. Ensure all haloes are filled in NEMO field (pn)
+
+      CALL lbc_lnk( 'sbcice_cice', pn , cd_type, psgn )
+
+#if defined key_nemocice_decomp
+
+      ! Copy local domain data from NEMO to CICE field
+      pc(:,:,1)=0.0
+      DO jj=2,ny_block-1
+         DO ji=2,nx_block-1
+            pc(ji,jj,1)=pn(ji-1+ji_off,jj-1+jj_off)
+         ENDDO
+      ENDDO
+
+#else
+
+!     B. Gather pn into global array (png)
+
+      IF ( jpnij > 1) THEN
+         CALL mppsync
+         CALL mppgather (pn,0,png) 
+         CALL mppsync
+      ELSE
+         png(:,:,1)=pn(:,:)
+      ENDIF
+
+!     C. Map png into CICE global array (pcg)
+
+! Need to make sure this is robust to changes in NEMO halo rows....
+! (may be OK but not 100% sure)
+
+      IF (nproc==0) THEN     
+!        pcg(:,:)=0.0
+         DO jn=1,jpnij
+            DO jj=nldjt(jn),nlejt(jn)
+               DO ji=nldit(jn),nleit(jn)
+                  png2(ji+nimppt(jn)-1,jj+njmppt(jn)-1)=png(ji,jj,jn)
+               ENDDO
+            ENDDO
+         ENDDO
+         DO jj=1,ny_global
+            DO ji=1,nx_global
+               pcg(ji,jj)=png2(ji+ji_off,jj+jj_off)
+            ENDDO
+         ENDDO
+      ENDIF
+
+#endif
+
+      SELECT CASE ( cd_type )
+         CASE ( 'T' )
+            grid_loc=field_loc_center
+         CASE ( 'F' )                              
+            grid_loc=field_loc_NEcorner
+      END SELECT
+
+      SELECT CASE ( NINT(psgn) )
+         CASE ( -1 )
+            field_type=field_type_vector
+         CASE ( 1 )                              
+            field_type=field_type_scalar
+      END SELECT
+
+#if defined key_nemocice_decomp
+      ! Ensure CICE halos are up to date
+      CALL ice_HaloUpdate (pc, halo_info, grid_loc, field_type)
+#else
+!     D. Scatter pcg to CICE blocks (pc) + update halos
+      CALL scatter_global(pc, pcg, 0, distrb_info, grid_loc, field_type)
+#endif
+
+   END SUBROUTINE nemo2cice
+
+   SUBROUTINE cice2nemo ( pc, pn, cd_type, psgn )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE cice2nemo  ***
+      !! ** Purpose :   Transfer field in CICE array to field in NEMO array.
+#if defined key_nemocice_decomp
+      !!             
+      !!                NEMO and CICE PE sub domains are identical, hence
+      !!                there is no need to gather or scatter data from 
+      !!                one PE configuration to another.
+#else 
+      !!                Automatically deal with scatter/gather between
+      !!                different processors and blocks
+      !! ** Method :    A. Gather CICE blocks (pc) into global array (pcg)
+      !!                B. Map pcg into NEMO global array (png)
+      !!                C. Scatter png into NEMO field (pn) for each processor
+      !!                D. Ensure all haloes are filled in pn 
+#endif
+      !!---------------------------------------------------------------------
+
+      CHARACTER(len=1), INTENT( in ) ::   &
+          cd_type       ! nature of pn grid-point
+          !             !   = T or F gridpoints
+      REAL(wp), INTENT( in ) ::   &
+          psgn          ! control of the sign change
+          !             !   =-1 , the sign is modified following the type of b.c. used
+          !             !   = 1 , no sign change
+      REAL(wp), DIMENSION(jpi,jpj) :: pn
+
+#if defined key_nemocice_decomp
+      INTEGER (int_kind) :: &
+         field_type,        & ! id for type of field (scalar, vector, angle)
+         grid_loc             ! id for location on horizontal grid
+                              ! (center, NEcorner, Nface, Eface)
+#else
+      REAL (kind=dbl_kind), dimension(nx_global,ny_global) :: pcg
+#endif
+
+      REAL (kind=dbl_kind), dimension(nx_block,ny_block,max_blocks) :: pc
+
+      INTEGER  ::   ji, jj, jn                      ! dummy loop indices
+
+
+#if defined key_nemocice_decomp
+
+      SELECT CASE ( cd_type )
+         CASE ( 'T' )
+            grid_loc=field_loc_center
+         CASE ( 'F' )                              
+            grid_loc=field_loc_NEcorner
+      END SELECT
+
+      SELECT CASE ( NINT(psgn) )
+         CASE ( -1 )
+            field_type=field_type_vector
+         CASE ( 1 )                              
+            field_type=field_type_scalar
+      END SELECT
+
+      CALL ice_HaloUpdate (pc, halo_info, grid_loc, field_type)
+
+
+      pn(:,:)=0.0
+      DO jj=1,jpjm1
+         DO ji=1,jpim1
+            pn(ji,jj)=pc(ji+1-ji_off,jj+1-jj_off,1)
+         ENDDO
+      ENDDO
+
+#else
+
+!      A. Gather CICE blocks (pc) into global array (pcg) 
+
+      CALL gather_global(pcg, pc, 0, distrb_info)
+
+!     B. Map pcg into NEMO global array (png)
+
+! Need to make sure this is robust to changes in NEMO halo rows....
+! (may be OK but not spent much time thinking about it)
+! Note that non-existent pcg elements may be used below, but
+! the lbclnk call on pn will replace these with sensible values
+
+      IF (nproc==0) THEN
+         png(:,:,:)=0.0
+         DO jn=1,jpnij
+            DO jj=nldjt(jn),nlejt(jn)
+               DO ji=nldit(jn),nleit(jn)
+                  png(ji,jj,jn)=pcg(ji+nimppt(jn)-1-ji_off,jj+njmppt(jn)-1-jj_off)
+               ENDDO
+            ENDDO
+         ENDDO
+      ENDIF
+
+!     C. Scatter png into NEMO field (pn) for each processor
+
+      IF ( jpnij > 1) THEN
+         CALL mppsync
+         CALL mppscatter (png,0,pn) 
+         CALL mppsync
+      ELSE
+         pn(:,:)=png(:,:,1)
+      ENDIF
+
+#endif
+
+!     D. Ensure all haloes are filled in pn
+
+      CALL lbc_lnk( 'sbcice_cice', pn , cd_type, psgn )
+
+   END SUBROUTINE cice2nemo
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option           Dummy module         NO CICE sea-ice model
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_ice_cice ( kt, ksbc )     ! Dummy routine
+      IMPLICIT NONE
+      INTEGER, INTENT( in ) :: kt, ksbc
+      WRITE(*,*) 'sbc_ice_cice: You should not have seen this print! error?', kt
+   END SUBROUTINE sbc_ice_cice
+
+   SUBROUTINE cice_sbc_init (ksbc)    ! Dummy routine
+      IMPLICIT NONE
+      INTEGER, INTENT( in ) :: ksbc
+      WRITE(*,*) 'cice_sbc_init: You should not have seen this print! error?', ksbc
+   END SUBROUTINE cice_sbc_init
+
+   SUBROUTINE cice_sbc_final     ! Dummy routine
+      IMPLICIT NONE
+      WRITE(*,*) 'cice_sbc_final: You should not have seen this print! error?'
+   END SUBROUTINE cice_sbc_final
+
+#endif
+
+   !!======================================================================
+END MODULE sbcice_cice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_if.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_if.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcice_if.F90	(revision 14097)
@@ -0,0 +1,149 @@
+MODULE sbcice_if
+   !!======================================================================
+   !!                       ***  MODULE  sbcice  ***
+   !! Surface module :  update surface ocean boundary condition over ice
+   !!                   covered area using ice-if model
+   !!======================================================================
+   !! History :  3.0  !  2006-06  (G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_ice_if    : update sbc in ice-covered area
+   !!----------------------------------------------------------------------
+   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
+#if defined key_si3
+   USE ice            , ONLY :   a_i
+#else
+   USE sbc_ice        , ONLY :   a_i 
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE fldread        ! read input field
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ice_if      ! routine called in sbcmod
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_ice   ! structure of input ice-cover (file informations, fields read)
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_ice_if( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_ice_if  ***
+      !!
+      !! ** Purpose :   handle surface boundary condition over ice cover area
+      !!      when sea-ice model are not used
+      !!
+      !! ** Method  : - read sea-ice cover climatology
+      !!              - blah blah blah, ...
+      !!
+      !! ** Action  :   utau, vtau : remain unchanged
+      !!                taum, wndm : remain unchanged
+      !!                qns, qsr   : update heat flux below sea-ice
+      !!                emp, sfx   : update freshwater flux below sea-ice
+      !!                fr_i       : update the ice fraction
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      INTEGER  ::   ierror     ! return error code
+      INTEGER  ::   ios        ! Local integer output status for namelist read
+      REAL(wp) ::   ztrp, zsice, zt_fzp, zfr_obs
+      REAL(wp) ::   zqri, zqrj, zqrp, zqi
+      !!
+      CHARACTER(len=100) ::   cn_dir              ! Root directory for location of ice-if files
+      TYPE(FLD_N)        ::   sn_ice              ! informations about the fields to be read
+      NAMELIST/namsbc_iif/ cn_dir, sn_ice
+      !!---------------------------------------------------------------------
+      !                                         ! ====================== !
+      IF( kt == nit000 ) THEN                   !  First call kt=nit000  !
+         !                                      ! ====================== !
+         ! set file information
+         REWIND( numnam_ref )              ! Namelist namsbc_iif in reference namelist : Ice if file
+         READ  ( numnam_ref, namsbc_iif, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_iif in reference namelist' )
+
+         REWIND( numnam_cfg )              ! Namelist Namelist namsbc_iif in configuration namelist : Ice if file
+         READ  ( numnam_cfg, namsbc_iif, IOSTAT = ios, ERR = 902 )
+902      IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_iif in configuration namelist' )
+         IF(lwm) WRITE ( numond, namsbc_iif )
+
+         ALLOCATE( sf_ice(1), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ice_if: unable to allocate sf_ice structure' )
+         ALLOCATE( sf_ice(1)%fnow(jpi,jpj,1) )
+         IF( sn_ice%ln_tint )   ALLOCATE( sf_ice(1)%fdta(jpi,jpj,1,2) )
+
+         ! fill sf_ice with sn_ice and control print
+         CALL fld_fill( sf_ice, (/ sn_ice /), cn_dir, 'sbc_ice_if', 'ice-if sea-ice model', 'namsbc_iif' )
+         !
+      ENDIF
+
+      CALL fld_read( kt, nn_fsbc, sf_ice )           ! Read input fields and provides the
+      !                                              ! input fields at the current time-step
+      
+      IF( MOD( kt-1, nn_fsbc) == 0 ) THEN
+         !
+         ztrp = -40.             ! restoring terme for temperature (w/m2/k)
+         zsice = - 0.04 / 0.8    ! ratio of isohaline compressibility over isotherme compressibility
+                                 ! ( d rho / dt ) / ( d rho / ds )      ( s = 34, t = -1.8 )
+         
+         CALL eos_fzp( sss_m(:,:), fr_i(:,:) )       ! sea surface freezing temperature [Celsius]
+         fr_i(:,:) = fr_i(:,:) * tmask(:,:,1)
+
+         IF( ln_cpl )   a_i(:,:,1) = fr_i(:,:)         
+
+         ! Flux and ice fraction computation
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !
+               zt_fzp  = fr_i(ji,jj)                        ! freezing point temperature
+               zfr_obs = sf_ice(1)%fnow(ji,jj,1)            ! observed ice cover
+               !                                            ! ocean ice fraction (0/1) from the freezing point temperature
+               IF( sst_m(ji,jj) <= zt_fzp ) THEN   ;   fr_i(ji,jj) = 1.e0
+               ELSE                                ;   fr_i(ji,jj) = 0.e0
+               ENDIF
+
+               tsn(ji,jj,1,jp_tem) = MAX( tsn(ji,jj,1,jp_tem), zt_fzp )     ! avoid over-freezing point temperature
+
+               qsr(ji,jj) = ( 1. - zfr_obs ) * qsr(ji,jj)   ! solar heat flux : zero below observed ice cover
+
+               !                                            ! non solar heat flux : add a damping term 
+               !      # ztrp*(t-(tgel-1.))  if observed ice and no opa ice   (zfr_obs=1 fr_i=0)
+               !      # ztrp*min(0,t-tgel)  if observed ice and opa ice      (zfr_obs=1 fr_i=1)
+               zqri = ztrp * ( tsb(ji,jj,1,jp_tem) - ( zt_fzp - 1.) )
+               zqrj = ztrp * MIN( 0., tsb(ji,jj,1,jp_tem) - zt_fzp )
+               zqrp = ( zfr_obs * ( (1. - fr_i(ji,jj) ) * zqri    &
+                 &                 +      fr_i(ji,jj)   * zqrj ) ) * tmask(ji,jj,1)
+
+               !                                            ! non-solar heat flux 
+               !      # qns unchanged              if no climatological ice              (zfr_obs=0)
+               !      # qns = zqrp                 if climatological ice and no opa ice  (zfr_obs=1, fr_i=0)
+               !      # qns = zqrp -2(-4) watt/m2  if climatological ice and opa ice     (zfr_obs=1, fr_i=1)
+               !                                   (-2=arctic, -4=antarctic)   
+               zqi = -3. + SIGN( 1._wp, ff_f(ji,jj) )
+               qns(ji,jj) = ( ( 1.- zfr_obs ) * qns(ji,jj)                             &
+                  &          +      zfr_obs   * fr_i(ji,jj) * zqi ) * tmask(ji,jj,1)   &
+                  &       + zqrp
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+   END SUBROUTINE sbc_ice_if
+
+   !!======================================================================
+END MODULE sbcice_if
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcisf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcisf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcisf.F90	(revision 14097)
@@ -0,0 +1,909 @@
+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 + parametrization
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   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 zdfdrg         ! vertical physics: top/bottom drag coef.
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE fldread        ! read input field at current time step
+   USE lbclnk         !
+   USE lib_fortran    ! glob_sum
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_isf, sbc_isf_init, sbc_isf_div, sbc_isf_alloc  ! routine called in sbcmod and divhor
+
+   ! public in order to be able to output then 
+
+   REAL(wp), PUBLIC ::   rn_hisf_tbl                 !: thickness of top boundary layer [m]
+   INTEGER , PUBLIC ::   nn_isf                      !: flag to choose between explicit/param/specified  
+   INTEGER , PUBLIC ::   nn_isfblk                   !: flag to choose the bulk formulation to compute the ice shelf melting
+   INTEGER , PUBLIC ::   nn_gammablk                 !: flag to choose how the exchange coefficient is computed
+   REAL(wp), PUBLIC ::   rn_gammat0                  !: temperature exchange coeficient []
+   REAL(wp), PUBLIC ::   rn_gammas0                  !: salinity    exchange coeficient []
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   misfkt   , misfkb        !: Level of ice shelf base
+   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  [m]
+   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
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qisf                     !: net heat flux from ice shelf      [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   risf_tsc_b, risf_tsc     !: before and now T & S isf contents [K.m/s & PSU.m/s]  
+
+   LOGICAL, PUBLIC ::   l_isfcpl = .false.       !: isf recieved from oasis
+
+   REAL(wp), PUBLIC, SAVE ::   rcpisf   = 2000.0_wp     !: specific heat of ice shelf             [J/kg/K]
+   REAL(wp), PUBLIC, SAVE ::   rkappa   = 1.54e-6_wp    !: heat diffusivity through the ice-shelf [m2/s]
+   REAL(wp), PUBLIC, SAVE ::   rhoisf   = 920.0_wp      !: volumic mass of ice shelf              [kg/m3]
+   REAL(wp), PUBLIC, SAVE ::   tsurf    = -20.0_wp      !: air temperature on top of ice shelf    [C]
+   REAL(wp), PUBLIC, SAVE ::   rLfusisf = 0.334e6_wp    !: latent heat of fusion of ice shelf     [J/kg]
+
+!: 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_fwfisf         !: information about the isf melting file to be read
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) :: sf_fwfisf
+   TYPE(FLD_N)       , PUBLIC           :: sn_rnfisf         !: information about the isf melting param.   file to be read
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) :: sf_rnfisf           
+   TYPE(FLD_N)       , PUBLIC           :: sn_depmax_isf     !: information about the grounding line depth file to be read
+   TYPE(FLD_N)       , PUBLIC           :: sn_depmin_isf     !: information about the calving   line depth file to be read
+   TYPE(FLD_N)       , PUBLIC           :: sn_Leff_isf       !: information about the effective length     file to be read
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+ 
+  SUBROUTINE sbc_isf( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_isf  ***
+      !!
+      !! ** Purpose : Compute Salt and Heat fluxes related to ice_shelf 
+      !!              melting and freezing 
+      !!
+      !! ** Method  :  4 parameterizations are available according to nn_isf 
+      !!               nn_isf = 1 : Realistic ice_shelf formulation
+      !!                        2 : Beckmann & Goose parameterization
+      !!                        3 : Specified runoff in deptht (Mathiot & al. )
+      !!                        4 : specified fwf and heat flux forcing beneath the ice shelf
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      INTEGER ::   ji, jj, jk   ! loop index
+      INTEGER ::   ikt, ikb     ! local integers
+      REAL(wp), DIMENSION(jpi,jpj) ::   zt_frz, zdep   ! freezing temperature (zt_frz) at depth (zdep) 
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zqhcisf2d
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zfwfisf3d, zqhcisf3d, zqlatisf3d
+      !!---------------------------------------------------------------------
+      !
+      IF( MOD( kt-1, nn_fsbc) == 0 ) THEN    ! compute salt and heat flux
+         !
+         SELECT CASE ( nn_isf )
+         CASE ( 1 )    ! 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(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:))
+            CALL iom_put('vtbl',vtbl(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:))
+            ! compute fwf and heat flux
+            ! compute fwf and heat flux
+            IF( .NOT.l_isfcpl ) THEN    ;   CALL sbc_isf_cav (kt)
+            ELSE                        ;   qisf(:,:)  = fwfisf(:,:) * rLfusisf  ! heat        flux
+            ENDIF
+            !
+         CASE ( 2 )    ! Beckmann and Goosse parametrisation 
+            stbl(:,:)   = soce
+            CALL sbc_isf_bg03(kt)
+            !
+         CASE ( 3 )    ! specified runoff in depth (Mathiot et al., XXXX in preparation)
+            ! specified runoff in depth (Mathiot et al., XXXX in preparation)
+            IF( .NOT.l_isfcpl ) THEN
+               CALL fld_read ( kt, nn_fsbc, sf_rnfisf   )
+               fwfisf(:,:) = - sf_rnfisf(1)%fnow(:,:,1)         ! fresh water flux from the isf (fwfisf <0 mean melting) 
+            ENDIF
+            qisf(:,:)   = fwfisf(:,:) * rLfusisf             ! heat flux
+            stbl(:,:)   = soce
+            !
+         CASE ( 4 )    ! specified fwf and heat flux forcing beneath the ice shelf
+            !          ! specified fwf and heat flux forcing beneath the ice shelf
+            IF( .NOT.l_isfcpl ) THEN
+               CALL fld_read ( kt, nn_fsbc, sf_fwfisf   )
+               !CALL fld_read ( kt, nn_fsbc, sf_qisf   )
+               fwfisf(:,:) = -sf_fwfisf(1)%fnow(:,:,1)            ! fwf
+            ENDIF
+            qisf(:,:)   = fwfisf(:,:) * rLfusisf               ! heat flux
+            stbl(:,:)   = soce
+            !
+         END SELECT
+
+         ! compute tsc due to isf
+         ! isf melting implemented as a volume flux and we assume that melt water is at 0 PSU.
+         ! WARNING water add at temp = 0C, need to add a correction term (fwfisf * tfreez / rau0).
+         ! compute freezing point beneath ice shelf (or top cell if nn_isf = 3)
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               zdep(ji,jj)=gdepw_n(ji,jj,misfkt(ji,jj))
+            END DO
+         END DO
+         CALL eos_fzp( stbl(:,:), zt_frz(:,:), zdep(:,:) )
+         
+         risf_tsc(:,:,jp_tem) = qisf(:,:) * r1_rau0_rcp - fwfisf(:,:) * zt_frz(:,:) * r1_rau0 !
+         risf_tsc(:,:,jp_sal) = 0.0_wp
+
+         ! lbclnk
+         CALL lbc_lnk_multi( 'sbcisf', risf_tsc(:,:,jp_tem), 'T', 1., risf_tsc(:,:,jp_sal), 'T', 1., fwfisf,'T', 1., qisf, 'T', 1.)
+         ! output
+         IF( iom_use('iceshelf_cea') )   CALL iom_put( 'iceshelf_cea', -fwfisf(:,:)                      )   ! isf mass flux
+         IF( iom_use('hflx_isf_cea') )   CALL iom_put( 'hflx_isf_cea', risf_tsc(:,:,jp_tem) * rau0 * rcp )   ! isf sensible+latent heat (W/m2)
+         IF( iom_use('qlatisf' ) )       CALL iom_put( 'qlatisf'     , qisf(:,:)                         )   ! isf latent heat
+         IF( iom_use('fwfisf'  ) )       CALL iom_put( 'fwfisf'      , fwfisf(:,:)                       )   ! isf mass flux (opposite sign)
+
+         ! Diagnostics
+         IF( iom_use('fwfisf3d') .OR. iom_use('qlatisf3d') .OR. iom_use('qhcisf3d') .OR. iom_use('qhcisf')) THEN
+            ALLOCATE( zfwfisf3d(jpi,jpj,jpk) , zqhcisf3d(jpi,jpj,jpk) , zqlatisf3d(jpi,jpj,jpk) )
+            ALLOCATE( zqhcisf2d(jpi,jpj) )
+            !
+            zfwfisf3d (:,:,:) = 0._wp                         ! 3d ice shelf melting (kg/m2/s)
+            zqhcisf3d (:,:,:) = 0._wp                         ! 3d heat content flux (W/m2)
+            zqlatisf3d(:,:,:) = 0._wp                         ! 3d ice shelf melting latent heat flux (W/m2)
+            zqhcisf2d (:,:)   = fwfisf(:,:) * zt_frz * rcp    ! 2d heat content flux (W/m2)
+            !
+            DO jj = 1,jpj
+               DO ji = 1,jpi
+                  ikt = misfkt(ji,jj)
+                  ikb = misfkb(ji,jj)
+                  DO jk = ikt, ikb - 1
+                     zfwfisf3d (ji,jj,jk) = zfwfisf3d (ji,jj,jk) + fwfisf   (ji,jj) * r1_hisf_tbl(ji,jj) * e3t_n(ji,jj,jk)
+                     zqhcisf3d (ji,jj,jk) = zqhcisf3d (ji,jj,jk) + zqhcisf2d(ji,jj) * r1_hisf_tbl(ji,jj) * e3t_n(ji,jj,jk)
+                     zqlatisf3d(ji,jj,jk) = zqlatisf3d(ji,jj,jk) + qisf     (ji,jj) * r1_hisf_tbl(ji,jj) * e3t_n(ji,jj,jk)
+                  END DO
+                  zfwfisf3d (ji,jj,jk) = zfwfisf3d (ji,jj,jk) + fwfisf   (ji,jj) * r1_hisf_tbl(ji,jj)   & 
+                     &                                                                   * ralpha(ji,jj) * e3t_n(ji,jj,jk)
+                  zqhcisf3d (ji,jj,jk) = zqhcisf3d (ji,jj,jk) + zqhcisf2d(ji,jj) * r1_hisf_tbl(ji,jj)   & 
+                     &                                                                   * ralpha(ji,jj) * e3t_n(ji,jj,jk)
+                  zqlatisf3d(ji,jj,jk) = zqlatisf3d(ji,jj,jk) + qisf     (ji,jj) * r1_hisf_tbl(ji,jj)   &  
+                     &                                                                   * ralpha(ji,jj) * e3t_n(ji,jj,jk)
+               END DO
+            END DO
+            !
+            CALL iom_put('fwfisf3d' , zfwfisf3d (:,:,:))
+            CALL iom_put('qlatisf3d', zqlatisf3d(:,:,:))
+            CALL iom_put('qhcisf3d' , zqhcisf3d (:,:,:))
+            CALL iom_put('qhcisf'   , zqhcisf2d (:,:  ))
+            !
+            DEALLOCATE( zfwfisf3d, zqhcisf3d, zqlatisf3d )
+            DEALLOCATE( zqhcisf2d )
+         ENDIF
+         !
+      ENDIF
+
+      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(:,:)         , ldxios = lrxios )   ! before salt content isf_tsc trend
+            CALL iom_get( numror, jpdom_autoglo, 'isf_sc_b' , risf_tsc_b(:,:,jp_sal), ldxios = lrxios )   ! before salt content isf_tsc trend
+            CALL iom_get( numror, jpdom_autoglo, 'isf_hc_b' , risf_tsc_b(:,:,jp_tem), ldxios = lrxios )   ! before salt content isf_tsc trend
+         ELSE
+            fwfisf_b(:,:)    = fwfisf(:,:)
+            risf_tsc_b(:,:,:)= risf_tsc(:,:,:)
+         ENDIF
+      ENDIF
+      ! 
+      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,*) '~~~~'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'fwf_isf_b', fwfisf(:,:)         , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'isf_hc_b' , risf_tsc(:,:,jp_tem), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'isf_sc_b' , risf_tsc(:,:,jp_sal), ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   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)   , &
+               &    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 )
+         !
+         CALL mpp_sum ( 'sbcisf', sbc_isf_alloc )
+         IF( sbc_isf_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sbc_isf_alloc: failed to allocate arrays.' )
+         !
+      ENDIF
+   END FUNCTION
+
+
+  SUBROUTINE sbc_isf_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_isf_init  ***
+      !!
+      !! ** Purpose : Initialisation of variables for iceshelf fluxes formulation
+      !!
+      !! ** Method  :  4 parameterizations are available according to nn_isf 
+      !!               nn_isf = 1 : Realistic ice_shelf formulation
+      !!                        2 : Beckmann & Goose parameterization
+      !!                        3 : Specified runoff in deptht (Mathiot & al. )
+      !!                        4 : specified fwf and heat flux forcing beneath the ice shelf
+      !!----------------------------------------------------------------------
+      INTEGER               :: ji, jj, jk           ! loop index
+      INTEGER               :: ik                   ! current level index
+      INTEGER               :: ikt, ikb             ! top and bottom level of the isf boundary layer
+      INTEGER               :: inum, ierror
+      INTEGER               :: ios                  ! Local integer output status for namelist read
+      REAL(wp)              :: zhk
+      CHARACTER(len=256)    :: cvarzisf, cvarhisf   ! name for isf file
+      CHARACTER(LEN=32 )    :: cvarLeff             ! variable name for efficient Length scale
+      !!----------------------------------------------------------------------
+      NAMELIST/namsbc_isf/ nn_isfblk, rn_hisf_tbl, rn_gammat0, rn_gammas0, nn_gammablk, nn_isf, &
+                         & sn_fwfisf, sn_rnfisf, sn_depmax_isf, sn_depmin_isf, sn_Leff_isf
+      !!----------------------------------------------------------------------
+
+      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' )
+
+      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' )
+      IF(lwm) WRITE ( numond, namsbc_isf )
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'sbc_isf_init : heat flux of the ice shelf'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '   Namelist namsbc_isf :'
+      IF(lwp) WRITE(numout,*) '      type ice shelf melting/freezing         nn_isf      = ', nn_isf
+      IF(lwp) WRITE(numout,*) '      bulk formulation (nn_isf=1 only)        nn_isfblk   = ', nn_isfblk
+      IF(lwp) WRITE(numout,*) '      thickness of the top boundary layer     rn_hisf_tbl = ', rn_hisf_tbl
+      IF(lwp) WRITE(numout,*) '      gamma formulation                       nn_gammablk = ', nn_gammablk 
+      IF(lwp) WRITE(numout,*) '      gammat coefficient                      rn_gammat0  = ', rn_gammat0  
+      IF(lwp) WRITE(numout,*) '      gammas coefficient                      rn_gammas0  = ', rn_gammas0  
+      IF(lwp) WRITE(numout,*) '      top drag coef. used (from namdrg_top)   rn_Cd0      = ', r_Cdmin_top 
+
+
+                           !  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)
+      !
+      ! 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   ;   fwfisf_b(:,:) = 0._wp
+      !
+      ! define isf tbl tickness, top and bottom indice
+      SELECT CASE ( nn_isf )
+      CASE ( 1 ) 
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '      ==>>>   presence of under iceshelf seas (nn_isf = 1)'
+         rhisf_tbl(:,:) = rn_hisf_tbl
+         misfkt   (:,:) = mikt(:,:)         ! same indice for bg03 et cav => used in isfdiv
+         !
+      CASE ( 2 , 3 )
+         IF( .NOT.l_isfcpl ) 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' )
+          ENDIF
+          !  read effective lenght (BG03)
+          IF( nn_isf == 2 ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '      ==>>>   bg03 parametrisation (nn_isf = 2)'
+            CALL iom_open( sn_Leff_isf%clname, inum )
+            cvarLeff = TRIM(sn_Leff_isf%clvar)
+            CALL iom_get( inum, jpdom_data, cvarLeff, risfLeff , 1)
+            CALL iom_close(inum)
+            !
+            risfLeff = risfLeff*1000.0_wp           !: convertion in m
+         ELSE
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '      ==>>>   rnf file for isf (nn_isf = 3)'
+         ENDIF
+         ! 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
+                ik = 2
+!!gm potential bug: use gdepw_0 not _n
+                DO WHILE ( ik <= mbkt(ji,jj) .AND. gdepw_n(ji,jj,ik) < rzisf_tbl(ji,jj) ) ;  ik = ik + 1 ;  END DO
+                misfkt(ji,jj) = ik-1
+            END DO
+         END DO
+         !
+      CASE ( 4 ) 
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '      ==>>>   specified fresh water flux in ISF (nn_isf = 4)'
+         ! 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)
+         IF( .NOT.l_isfcpl ) THEN
+           ALLOCATE( sf_fwfisf(1), STAT=ierror )
+           ALLOCATE( sf_fwfisf(1)%fnow(jpi,jpj,1), sf_fwfisf(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' )
+         ENDIF
+         !
+      CASE DEFAULT
+         CALL ctl_stop( 'sbc_isf_init: wrong value of nn_isf' )
+      END SELECT
+         
+      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), e3t_n(ji,jj,ikt))
+
+            ! determine the deepest level influenced by the boundary layer
+            DO jk = ikt+1, mbkt(ji,jj)
+               IF( (SUM(e3t_n(ji,jj,ikt:jk-1)) < rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) )   ikb = jk
+            END DO
+            rhisf_tbl(ji,jj) = MIN(rhisf_tbl(ji,jj), SUM(e3t_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( e3t_n(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 ) / e3t_n(ji,jj,ikb)  ! proportion of bottom cell influenced by boundary layer
+         END DO
+      END DO
+
+      IF( lwxios ) THEN
+          CALL iom_set_rstw_var_active('fwf_isf_b')
+          CALL iom_set_rstw_var_active('isf_hc_b')
+          CALL iom_set_rstw_var_active('isf_sc_b')
+      ENDIF
+
+
+  END SUBROUTINE sbc_isf_init
+
+
+  SUBROUTINE sbc_isf_bg03(kt)
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_isf_bg03  ***
+      !!
+      !! ** Purpose : add net heat and fresh water flux from ice shelf melting
+      !!          into the adjacent ocean
+      !!
+      !! ** Method  :   See reference
+      !!
+      !! ** Reference : Beckmann and Goosse (2003), "A parameterization of ice shelf-ocean
+      !!         interaction for climate models", Ocean Modelling 5(2003) 157-170.
+      !!         (hereafter BG)
+      !! History :  06-02  (C. Wang) Original code
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT ( in ) :: kt
+      !
+      INTEGER  :: ji, jj, jk ! dummy loop index
+      INTEGER  :: ik         ! current level
+      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
+      !!----------------------------------------------------------------------
+      !
+      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 > 1 ) THEN
+               ! 1. -----------the average temperature between 200m and 600m ---------------------
+               DO jk = misfkt(ji,jj),misfkb(ji,jj)
+                  ! Calculate freezing temperature
+                  zpress = grav*rau0*gdept_n(ji,jj,ik)*1.e-04
+                  CALL eos_fzp(stbl(ji,jj), zt_frz, zpress) 
+                  zt_sum = zt_sum + (tsn(ji,jj,jk,jp_tem)-zt_frz) * e3t_n(ji,jj,jk) * tmask(ji,jj,jk)  ! sum temp
+               END DO
+               zt_ave = zt_sum/rhisf_tbl(ji,jj) ! calcul mean value
+               ! 2. ------------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  &
+                           & * r1_e1e2t(ji,jj) * tmask(ji,jj,jk)
+             
+               fwfisf(ji,jj) = qisf(ji,jj) / rLfusisf          !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
+         END DO
+      END DO
+      !
+  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
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      INTEGER  ::   nit
+      LOGICAL  ::   lit
+      REAL(wp) ::   zlamb1, zlamb2, zlamb3
+      REAL(wp) ::   zeps1,zeps2,zeps3,zeps4,zeps6,zeps7
+      REAL(wp) ::   zaqe,zbqe,zcqe,zaqer,zdis,zsfrz,zcfac
+      REAL(wp) ::   zeps = 1.e-20_wp        
+      REAL(wp) ::   zerr
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfrz
+      REAL(wp), DIMENSION(jpi,jpj) ::   zgammat, zgammas 
+      REAL(wp), DIMENSION(jpi,jpj) ::   zfwflx, zhtflx, zhtflx_b
+      !!---------------------------------------------------------------------
+      !
+      ! coeficient for linearisation of potential tfreez
+      ! Crude approximation for pressure (but commonly used)
+      IF ( l_useCT ) THEN   ! linearisation from Jourdain et al. (2017)
+         zlamb1 =-0.0564_wp
+         zlamb2 = 0.0773_wp
+         zlamb3 =-7.8633e-8 * grav * rau0
+      ELSE                  ! linearisation from table 4 (Asay-Davis et al., 2015)
+         zlamb1 =-0.0573_wp
+         zlamb2 = 0.0832_wp
+         zlamb3 =-7.53e-8 * grav * rau0
+      ENDIF
+      !
+      ! initialisation
+      zgammat(:,:) = rn_gammat0 ; zgammas (:,:) = rn_gammas0
+      zhtflx (:,:) = 0.0_wp     ; zhtflx_b(:,:) = 0.0_wp    
+      zfwflx (:,:) = 0.0_wp
+
+      ! compute ice shelf melting
+      nit = 1 ; lit = .TRUE.
+      DO WHILE ( lit )    ! maybe just a constant number of iteration as in blk_core is fine
+         SELECT CASE ( nn_isfblk )
+         CASE ( 1 )   !  ISOMIP formulation (2 equations) for volume flux (Hunter et al., 2006)
+            ! Calculate freezing temperature
+            CALL eos_fzp( stbl(:,:), zfrz(:,:), risfdep(:,:) )
+
+            ! compute gammat every where (2d)
+            CALL sbc_isf_gammats(zgammat, zgammas, zhtflx, zfwflx)
+            
+            ! compute upward heat flux zhtflx and upward water flux zwflx
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zhtflx(ji,jj) =   zgammat(ji,jj)*rcp*rau0*(ttbl(ji,jj)-zfrz(ji,jj))
+                  zfwflx(ji,jj) = - zhtflx(ji,jj)/rLfusisf
+               END DO
+            END DO
+
+            ! Compute heat flux and upward fresh water flux
+            qisf  (:,:) = - zhtflx(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:)
+            fwfisf(:,:) =   zfwflx(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:)
+
+         CASE ( 2 )  ! ISOMIP+ formulation (3 equations) for volume flux (Asay-Davis et al., 2015)
+            ! compute gammat every where (2d)
+            CALL sbc_isf_gammats(zgammat, zgammas, zhtflx, zfwflx)
+
+            ! compute upward heat flux zhtflx and upward water flux zwflx
+            ! Resolution of a 2d equation from equation 21, 22 and 23 to find Sb (Asay-Davis et al., 2015)
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! compute coeficient to solve the 2nd order equation
+                  zeps1 = rcp*rau0*zgammat(ji,jj)
+                  zeps2 = rLfusisf*rau0*zgammas(ji,jj)
+                  zeps3 = rhoisf*rcpisf*rkappa/MAX(risfdep(ji,jj),zeps)
+                  zeps4 = zlamb2+zlamb3*risfdep(ji,jj)
+                  zeps6 = zeps4-ttbl(ji,jj)
+                  zeps7 = zeps4-tsurf
+                  zaqe  = zlamb1 * (zeps1 + zeps3)
+                  zaqer = 0.5_wp/MIN(zaqe,-zeps)
+                  zbqe  = zeps1*zeps6+zeps3*zeps7-zeps2
+                  zcqe  = zeps2*stbl(ji,jj)
+                  zdis  = zbqe*zbqe-4.0_wp*zaqe*zcqe               
+
+                  ! Presumably zdis can never be negative because gammas is very small compared to gammat
+                  ! compute s freeze
+                  zsfrz=(-zbqe-SQRT(zdis))*zaqer
+                  IF ( zsfrz < 0.0_wp ) zsfrz=(-zbqe+SQRT(zdis))*zaqer
+
+                  ! compute t freeze (eq. 22)
+                  zfrz(ji,jj)=zeps4+zlamb1*zsfrz
+  
+                  ! zfwflx is upward water flux
+                  ! zhtflx is upward heat flux (out of ocean)
+                  ! compute the upward water and heat flux (eq. 28 and eq. 29)
+                  zfwflx(ji,jj) = rau0 * zgammas(ji,jj) * (zsfrz-stbl(ji,jj)) / MAX(zsfrz,zeps)
+                  zhtflx(ji,jj) = zgammat(ji,jj) * rau0 * rcp * (ttbl(ji,jj) - zfrz(ji,jj) ) 
+               END DO
+            END DO
+
+            ! compute heat and water flux
+            qisf  (:,:) = - zhtflx(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:)
+            fwfisf(:,:) =   zfwflx(:,:) * (1._wp - tmask(:,:,1)) * ssmask(:,:)
+
+         END SELECT
+
+         ! define if we need to iterate (nn_gammablk 0/1 do not need iteration)
+         IF ( nn_gammablk <  2 ) THEN ; lit = .FALSE.
+         ELSE                           
+            ! check total number of iteration
+            IF (nit >= 100) THEN ; CALL ctl_stop( 'STOP', 'sbc_isf_hol99 : too many iteration ...' )
+            ELSE                 ; nit = nit + 1
+            END IF
+
+            ! compute error between 2 iterations
+            ! if needed save gammat and compute zhtflx_b for next iteration
+            zerr = MAXVAL(ABS(zhtflx-zhtflx_b))
+            IF ( zerr <= 0.01_wp ) THEN ; lit = .FALSE.
+            ELSE                        ; zhtflx_b(:,:) = zhtflx(:,:)
+            END IF
+         END IF
+      END DO
+      !
+      CALL iom_put('isfgammat', zgammat)
+      CALL iom_put('isfgammas', zgammas)
+      ! 
+   END SUBROUTINE sbc_isf_cav
+
+
+   SUBROUTINE sbc_isf_gammats(pgt, pgs, pqhisf, pqwisf )
+      !!----------------------------------------------------------------------
+      !! ** 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), DIMENSION(:,:), INTENT(  out) ::   pgt   , pgs      ! 
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   pqhisf, pqwisf   ! 
+      !
+      INTEGER  :: ji, jj                     ! loop index
+      INTEGER  :: ikt                        ! local integer
+      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) :: zeps = 1.0e-20_wp    
+      REAL(wp), PARAMETER :: zxsiN = 0.052_wp   ! dimensionless constant
+      REAL(wp), PARAMETER :: znu   = 1.95e-6_wp ! kinamatic viscosity of sea water (m2.s-1)
+      REAL(wp), DIMENSION(2) :: zts, zab
+      REAL(wp), DIMENSION(jpi,jpj) :: zustar   ! U, V at T point and friction velocity
+      !!---------------------------------------------------------------------
+      !
+      SELECT CASE ( nn_gammablk )
+      CASE ( 0 ) ! gamma is constant (specified in namelist)
+         !! ISOMIP formulation (Hunter et al, 2006)
+         pgt(:,:) = rn_gammat0
+         pgs(:,:) = rn_gammas0
+
+      CASE ( 1 ) ! gamma is assume to be proportional to u*
+         !! Jenkins et al., 2010, JPO, p2298-2312
+         !! Adopted by Asay-Davis et al. (2015)
+         !! compute ustar (eq. 24)
+!!gm  NB  use pCdU here so that it will incorporate local boost of Cd0 and log layer case :
+!!         zustar(:,:) = SQRT( rCdU_top(:,:) * SQRT(utbl(:,:) * utbl(:,:) + vtbl(:,:) * vtbl(:,:) + r_ke0_top) )
+!! or better :  compute ustar in zdfdrg  and use it here as well as in TKE, GLS and Co
+!!
+!!     ===>>>>    GM  to be done this chrismas
+!!         
+!!gm end
+         zustar(:,:) = SQRT( r_Cdmin_top * (utbl(:,:) * utbl(:,:) + vtbl(:,:) * vtbl(:,:) + r_ke0_top) )
+
+         !! Compute gammats
+         pgt(:,:) = zustar(:,:) * rn_gammat0
+         pgs(:,:) = zustar(:,:) * rn_gammas0
+      
+      CASE ( 2 ) ! gamma depends of stability of boundary layer
+         !! 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)
+         !! compute ustar
+         zustar(:,:) = SQRT( r_Cdmin_top * (utbl(:,:) * utbl(:,:) + vtbl(:,:) * vtbl(:,:) + r_ke0_top) )
+
+         !! compute Pr and Sc number (can be improved)
+         zPr =   13.8_wp
+         zSc = 2432.0_wp
+
+         !! compute gamma mole
+         zgmolet = 12.5_wp * zPr ** (2.0/3.0) - 6.0_wp
+         zgmoles = 12.5_wp * zSc ** (2.0/3.0) - 6.0_wp
+
+         !! compute gamma
+         DO ji = 2, jpi
+            DO jj = 2, jpj
+               ikt = mikt(ji,jj)
+
+               IF( zustar(ji,jj) == 0._wp ) THEN           ! only for kt = 1 I think
+                  pgt = rn_gammat0
+                  pgs = rn_gammas0
+               ELSE
+                  !! compute Rc number (as done in zdfric.F90)
+!!gm better to do it like in the new zdfric.F90   i.e. avm weighted Ri computation
+!!gm moreover, use Max(rn2,0) to take care of static instabilities....
+                  zcoef = 0.5_wp / e3w_n(ji,jj,ikt+1)
+                  !                                            ! 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) / MAX( zdku*zdku + zdkv*zdkv, zeps )
+
+                  !! compute bouyancy 
+                  zts(jp_tem) = ttbl(ji,jj)
+                  zts(jp_sal) = stbl(ji,jj)
+                  zdep        = gdepw_n(ji,jj,ikt)
+                  !
+                  CALL eos_rab( zts, zdep, zab )
+                  !
+                  !! compute length scale 
+                  zbuofdep = grav * ( zab(jp_tem) * pqhisf(ji,jj) - zab(jp_sal) * pqwisf(ji,jj) )  !!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+                  !! compute Monin Obukov Length
+                  ! Maximum boundary layer depth
+                  zhmax = gdept_n(ji,jj,mbkt(ji,jj)) - gdepw_n(ji,jj,mikt(ji,jj)) -0.001_wp
+                  ! Compute Monin obukhov length scale at the surface and Ekman depth:
+                  zmob   = zustar(ji,jj) ** 3 / (vkarmn * (zbuofdep + zeps))
+                  zmols  = SIGN(1._wp, zmob) * MIN(ABS(zmob), zhmax) * tmask(ji,jj,ikt)
+
+                  !! compute eta* (stability parameter)
+                  zetastar = 1._wp / ( SQRT(1._wp + MAX(zxsiN * zustar(ji,jj) / ( ABS(ff_f(ji,jj)) * zmols * zRc ), 0._wp)))
+
+                  !! compute the sublayer thickness
+                  zhnu = 5 * znu / zustar(ji,jj)
+
+                  !! compute gamma turb
+                  zgturb = 1._wp / vkarmn * LOG(zustar(ji,jj) * zxsiN * zetastar * zetastar / ( ABS(ff_f(ji,jj)) * zhnu )) &
+                  &      + 1._wp / ( 2 * zxsiN * zetastar ) - 1._wp / vkarmn
+
+                  !! compute gammats
+                  pgt(ji,jj) = zustar(ji,jj) / (zgturb + zgmolet)
+                  pgs(ji,jj) = zustar(ji,jj) / (zgturb + zgmoles)
+               END IF
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'sbcisf', pgt, 'T', 1., pgs, 'T', 1.)
+      END SELECT
+      !
+   END SUBROUTINE sbc_isf_gammats
+
+
+   SUBROUTINE sbc_isf_tbl( pvarin, pvarout, cd_ptin )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE sbc_isf_tbl  ***
+      !!
+      !! ** Purpose : compute mean T/S/U/V in the boundary layer at T- point
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) :: pvarin
+      REAL(wp), DIMENSION(:,:)  , INTENT(  out) :: pvarout
+      CHARACTER(len=1),           INTENT(in   ) :: cd_ptin ! point of variable in/out
+      !
+      INTEGER ::   ji, jj, jk                   ! loop index
+      INTEGER ::   ikt, ikb                     ! top and bottom index of the tbl
+      REAL(wp) ::   ze3, zhk
+      REAL(wp), DIMENSION(jpi,jpj) :: zhisf_tbl ! thickness of the tbl
+      REAL(wp), DIMENSION(jpi,jpj) :: zvarout
+      !!----------------------------------------------------------------------
+      
+      ! initialisation
+      pvarout(:,:)=0._wp
+   
+      SELECT CASE ( cd_ptin )
+      CASE ( 'U' ) ! compute U in the top boundary layer at T- point 
+         !
+         zvarout(:,:)=0._wp
+         !
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               ikt = miku(ji,jj) ; ikb = miku(ji,jj)
+               ! thickness of boundary layer at least the top level thickness
+               zhisf_tbl(ji,jj) = MAX( rhisf_tbl_0(ji,jj) , e3u_n(ji,jj,ikt) )
+
+               ! determine the deepest level influenced by the boundary layer
+               DO jk = ikt+1, mbku(ji,jj)
+                  IF ( (SUM(e3u_n(ji,jj,ikt:jk-1)) < zhisf_tbl(ji,jj)) .AND. (umask(ji,jj,jk) == 1) ) ikb = jk
+               END DO
+               zhisf_tbl(ji,jj) = MIN(zhisf_tbl(ji,jj), SUM(e3u_n(ji,jj,ikt:ikb)))  ! limit the tbl to water thickness.
+
+               ! level fully include in the ice shelf boundary layer
+               DO jk = ikt, ikb - 1
+                  ze3 = e3u_n(ji,jj,jk)
+                  zvarout(ji,jj) = zvarout(ji,jj) + pvarin(ji,jj,jk) / zhisf_tbl(ji,jj) * ze3
+               END DO
+
+               ! level partially include in ice shelf boundary layer 
+               zhk = SUM( e3u_n(ji, jj, ikt:ikb - 1)) / zhisf_tbl(ji,jj)
+               zvarout(ji,jj) = zvarout(ji,jj) + pvarin(ji,jj,ikb) * (1._wp - zhk)
+            END DO
+         END DO
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+!!gm a wet-point only average should be used here !!!
+               pvarout(ji,jj) = 0.5_wp * (zvarout(ji,jj) + zvarout(ji-1,jj))
+            END DO
+         END DO
+         CALL lbc_lnk('sbcisf', pvarout,'T',-1.)
+      
+      CASE ( 'V' ) ! compute V in the top boundary layer at T- point 
+         !
+         zvarout(:,:)=0._wp
+         !
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               ikt = mikv(ji,jj) ; ikb = mikv(ji,jj)
+               ! thickness of boundary layer at least the top level thickness
+               zhisf_tbl(ji,jj) = MAX(rhisf_tbl_0(ji,jj), e3v_n(ji,jj,ikt))
+
+               ! determine the deepest level influenced by the boundary layer
+               DO jk = ikt+1, mbkv(ji,jj)
+                  IF ( (SUM(e3v_n(ji,jj,ikt:jk-1)) < zhisf_tbl(ji,jj)) .AND. (vmask(ji,jj,jk) == 1) ) ikb = jk
+               END DO
+               zhisf_tbl(ji,jj) = MIN(zhisf_tbl(ji,jj), SUM(e3v_n(ji,jj,ikt:ikb)))  ! limit the tbl to water thickness.
+
+               ! level fully include in the ice shelf boundary layer
+               DO jk = ikt, ikb - 1
+                  ze3 = e3v_n(ji,jj,jk)
+                  zvarout(ji,jj) = zvarout(ji,jj) + pvarin(ji,jj,jk) / zhisf_tbl(ji,jj) * ze3
+               END DO
+
+               ! level partially include in ice shelf boundary layer 
+               zhk = SUM( e3v_n(ji, jj, ikt:ikb - 1)) / zhisf_tbl(ji,jj)
+               zvarout(ji,jj) = zvarout(ji,jj) + pvarin(ji,jj,ikb) * (1._wp - zhk)
+            END DO
+         END DO
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+!!gm a wet-point only average should be used here !!!
+               pvarout(ji,jj) = 0.5_wp * (zvarout(ji,jj) + zvarout(ji,jj-1))
+            END DO
+         END DO
+         CALL lbc_lnk('sbcisf', pvarout,'T',-1.)
+
+      CASE ( 'T' ) ! compute T in the top boundary layer at T- point 
+         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
+                  ze3 = e3t_n(ji,jj,jk)
+                  pvarout(ji,jj) = pvarout(ji,jj) + pvarin(ji,jj,jk) * r1_hisf_tbl(ji,jj) * ze3
+               END DO
+
+               ! level partially include in ice shelf boundary layer 
+               zhk = SUM( e3t_n(ji, jj, ikt:ikb - 1)) * r1_hisf_tbl(ji,jj)
+               pvarout(ji,jj) = pvarout(ji,jj) + pvarin(ji,jj,ikb) * (1._wp - zhk)
+            END DO
+         END DO
+      END SELECT
+      !
+      ! mask mean tbl value
+      pvarout(:,:) = pvarout(:,:) * ssmask(:,:)
+      !
+   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 
+      REAL(wp) ::   zhk
+      REAL(wp) ::   zfact     ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zfact   = 0.5_wp
+      !
+      IF(.NOT.ln_linssh ) 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), e3t_n(ji,jj,ikt))
+
+               ! determine the deepest level influenced by the boundary layer
+               DO jk = ikt, mbkt(ji,jj)
+                  IF ( (SUM(e3t_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(e3t_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( e3t_n(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 ) / e3t_n(ji,jj,ikb)  ! proportion of bottom cell influenced by boundary layer
+            END DO
+         END DO
+      END IF 
+      !
+      !==   ice shelf melting distributed over several levels   ==!
+      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) 
+         END DO
+      END DO
+      !
+   END SUBROUTINE sbc_isf_div
+
+   !!======================================================================
+END MODULE sbcisf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcmod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcmod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcmod.F90	(revision 14097)
@@ -0,0 +1,602 @@
+MODULE sbcmod
+   !!======================================================================
+   !!                       ***  MODULE  sbcmod  ***
+   !! Surface module :  provide to the ocean its surface boundary condition
+   !!======================================================================
+   !! History :  3.0  ! 2006-07  (G. Madec)  Original code
+   !!            3.1  ! 2008-08  (S. Masson, A. Caubel, E. Maisonnave, G. Madec) coupled interface
+   !!            3.3  ! 2010-04  (M. Leclair, G. Madec)  Forcing averaged over 2 time steps
+   !!            3.3  ! 2010-10  (S. Masson)  add diurnal cycle
+   !!            3.3  ! 2010-09  (D. Storkey) add ice boundary conditions (BDY)
+   !!             -   ! 2010-11  (G. Madec) ice-ocean stress always computed at each ocean time-step
+   !!             -   ! 2010-10  (J. Chanut, C. Bricaud, G. Madec)  add the surface pressure forcing
+   !!            3.4  ! 2011-11  (C. Harris) CICE added as an option
+   !!            3.5  ! 2012-11  (A. Coward, G. Madec) Rethink of heat, mass and salt surface fluxes
+   !!            3.6  ! 2014-11  (P. Mathiot, C. Harris) add ice shelves melting
+   !!            4.0  ! 2016-06  (L. Brodeau) new general bulk formulation
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_init      : read namsbc namelist
+   !!   sbc           : surface ocean momentum, heat and freshwater boundary conditions
+   !!   sbc_final     : Finalize CICE ice model (if used)
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE trc_oce        ! shared ocean-passive tracers variables
+   USE sbc_ice        ! Surface boundary condition: ice fields
+   USE sbcdcy         ! surface boundary condition: diurnal cycle
+   USE sbcssm         ! surface boundary condition: sea-surface mean variables
+   USE sbcflx         ! surface boundary condition: flux formulation
+   USE sbcblk         ! surface boundary condition: bulk formulation
+   USE sbcice_if      ! surface boundary condition: ice-if sea-ice model
+#if defined key_si3
+   USE icestp         ! surface boundary condition: SI3 sea-ice model
+#endif
+   USE sbcice_cice    ! surface boundary condition: CICE sea-ice model
+   USE sbcisf         ! surface boundary condition: ice-shelf
+   USE sbccpl         ! surface boundary condition: coupled formulation
+   USE cpl_oasis3     ! OASIS routines for coupling
+   USE sbcssr         ! surface boundary condition: sea surface restoring
+   USE sbcrnf         ! surface boundary condition: runoffs
+   USE sbcapr         ! surface boundary condition: atmo pressure 
+   USE sbcisf         ! surface boundary condition: ice shelf
+   USE sbcfwb         ! surface boundary condition: freshwater budget
+   USE icbstp         ! Icebergs
+   USE icb_oce  , ONLY : ln_passive_mode      ! iceberg interaction mode
+   USE traqsr         ! active tracers: light penetration
+   USE sbcwave        ! Wave module
+   USE bdy_oce   , ONLY: ln_bdy
+   USE usrdef_sbc     ! user defined: surface boundary condition
+   USE closea         ! closed sea
+   !
+   USE prtctl         ! Print control                    (prt_ctl routine)
+   USE iom            ! IOM library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   USE wet_dry
+   USE diurnal_bulk, ONLY:   ln_diurnal_only   ! diurnal SST diagnostic
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc        ! routine called by step.F90
+   PUBLIC   sbc_init   ! routine called by opa.F90
+
+   INTEGER ::   nsbc   ! type of surface boundary condition (deduced from namsbc informations)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_init
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_init ***
+      !!
+      !! ** Purpose :   Initialisation of the ocean surface boundary computation
+      !!
+      !! ** Method  :   Read the namsbc namelist and set derived parameters
+      !!                Call init routines for all other SBC modules that have one
+      !!
+      !! ** Action  : - read namsbc parameters
+      !!              - nsbc: type of sbc
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, icpt                         ! local integer
+      LOGICAL ::   ll_purecpl, ll_opa, ll_not_nemo   ! local logical
+      !!
+      NAMELIST/namsbc/ nn_fsbc  ,                                                    &
+         &             ln_usr   , ln_flx   , ln_blk       ,                          &
+         &             ln_cpl   , ln_mixcpl, nn_components,                          &
+         &             nn_ice   , ln_ice_embd,                                       &
+         &             ln_traqsr, ln_dm2dc ,                                         &
+         &             ln_rnf   , nn_fwb   , ln_ssr   , ln_isf    , ln_apr_dyn ,     &
+         &             ln_wave  , ln_cdgw  , ln_sdw   , ln_tauwoc  , ln_stcor   ,     &
+         &             ln_tauw  , nn_lsm, nn_sdrift
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_init : surface boundary condition setting'
+         WRITE(numout,*) '~~~~~~~~ '
+      ENDIF
+      !
+      !                       !**  read Surface Module namelist
+      REWIND( numnam_ref )          !* Namelist namsbc in reference namelist : Surface boundary
+      READ  ( numnam_ref, namsbc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc in reference namelist' )
+      REWIND( numnam_cfg )          !* Namelist namsbc in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, namsbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc in configuration namelist' )
+      IF(lwm) WRITE( numond, namsbc )
+      !
+#if defined key_mpp_mpi
+      ncom_fsbc = nn_fsbc    ! make nn_fsbc available for lib_mpp
+#endif
+      !                             !* overwrite namelist parameter using CPP key information
+#if defined key_agrif
+      IF( Agrif_Root() ) THEN                ! AGRIF zoom (cf r1242: possibility to run without ice in fine grid)
+         IF( lk_si3  )   nn_ice      = 2
+         IF( lk_cice )   nn_ice      = 3
+      ENDIF
+#else
+      IF( lk_si3  )   nn_ice      = 2
+      IF( lk_cice )   nn_ice      = 3
+#endif
+      !
+#if ! defined key_si3
+      IF( nn_ice == 2 )    nn_ice = 0  ! without key key_si3 you cannot use si3...
+#endif
+      !
+      IF(lwp) THEN                  !* Control print
+         WRITE(numout,*) '   Namelist namsbc (partly overwritten with CPP key setting)'
+         WRITE(numout,*) '      frequency update of sbc (and ice)             nn_fsbc       = ', nn_fsbc
+         WRITE(numout,*) '      Type of air-sea fluxes : '
+         WRITE(numout,*) '         user defined formulation                   ln_usr        = ', ln_usr
+         WRITE(numout,*) '         flux         formulation                   ln_flx        = ', ln_flx
+         WRITE(numout,*) '         bulk         formulation                   ln_blk        = ', ln_blk
+         WRITE(numout,*) '      Type of coupling (Ocean/Ice/Atmosphere) : '
+         WRITE(numout,*) '         ocean-atmosphere coupled formulation       ln_cpl        = ', ln_cpl
+         WRITE(numout,*) '         mixed forced-coupled     formulation       ln_mixcpl     = ', ln_mixcpl
+!!gm  lk_oasis is controlled by key_oasis3  ===>>>  It shoud be removed from the namelist 
+         WRITE(numout,*) '         OASIS coupling (with atm or sas)           lk_oasis      = ', lk_oasis
+         WRITE(numout,*) '         components of your executable              nn_components = ', nn_components
+         WRITE(numout,*) '      Sea-ice : '
+         WRITE(numout,*) '         ice management in the sbc (=0/1/2/3)       nn_ice        = ', nn_ice
+         WRITE(numout,*) '         ice embedded into ocean                    ln_ice_embd   = ', ln_ice_embd
+         WRITE(numout,*) '      Misc. options of sbc : '
+         WRITE(numout,*) '         Light penetration in temperature Eq.       ln_traqsr     = ', ln_traqsr
+         WRITE(numout,*) '            daily mean to diurnal cycle qsr            ln_dm2dc   = ', ln_dm2dc
+         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
+         WRITE(numout,*) '         Patm gradient added in ocean & ice Eqs.    ln_apr_dyn    = ', ln_apr_dyn
+         WRITE(numout,*) '         runoff / runoff mouths                     ln_rnf        = ', ln_rnf
+         WRITE(numout,*) '         iceshelf formulation                       ln_isf        = ', ln_isf
+         WRITE(numout,*) '         nb of iterations if land-sea-mask applied  nn_lsm        = ', nn_lsm
+         WRITE(numout,*) '         surface wave                               ln_wave       = ', ln_wave
+         WRITE(numout,*) '               Stokes drift corr. to vert. velocity ln_sdw        = ', ln_sdw
+         WRITE(numout,*) '                  vertical parametrization          nn_sdrift     = ', nn_sdrift
+         WRITE(numout,*) '               wave modified ocean stress           ln_tauwoc     = ', ln_tauwoc
+         WRITE(numout,*) '               wave modified ocean stress component ln_tauw       = ', ln_tauw
+         WRITE(numout,*) '               Stokes coriolis term                 ln_stcor      = ', ln_stcor
+         WRITE(numout,*) '               neutral drag coefficient (CORE,NCAR) ln_cdgw       = ', ln_cdgw
+      ENDIF
+      !
+      IF( .NOT.ln_wave ) THEN
+         ln_sdw = .false. ; ln_cdgw = .false. ; ln_tauwoc = .false. ; ln_tauw = .false. ; ln_stcor = .false.
+      ENDIF 
+      IF( ln_sdw ) THEN
+         IF( .NOT.(nn_sdrift==jp_breivik_2014 .OR. nn_sdrift==jp_li_2017 .OR. nn_sdrift==jp_peakfr) ) &
+            CALL ctl_stop( 'The chosen nn_sdrift for Stokes drift vertical velocity must be 0, 1, or 2' )
+      ENDIF
+      ll_st_bv2014  = ( nn_sdrift==jp_breivik_2014 )
+      ll_st_li2017  = ( nn_sdrift==jp_li_2017 )
+      ll_st_bv_li   = ( ll_st_bv2014 .OR. ll_st_li2017 )
+      ll_st_peakfr  = ( nn_sdrift==jp_peakfr )
+      IF( ln_tauwoc .AND. ln_tauw ) &
+         CALL ctl_stop( 'More than one method for modifying the ocean stress has been selected ', &
+                                  '(ln_tauwoc=.true. and ln_tauw=.true.)' )
+      IF( ln_tauwoc ) &
+         CALL ctl_warn( 'You are subtracting the wave stress to the ocean (ln_tauwoc=.true.)' )
+      IF( ln_tauw ) &
+         CALL ctl_warn( 'The wave modified ocean stress components are used (ln_tauw=.true.) ', &
+                              'This will override any other specification of the ocean stress' )
+      !
+      IF( .NOT.ln_usr ) THEN     ! the model calendar needs some specificities (except in user defined case)
+         IF( MOD( rday , rdt ) /= 0. )   CALL ctl_stop( 'the time step must devide the number of second of in a day' )
+         IF( MOD( rday , 2.  ) /= 0. )   CALL ctl_stop( 'the number of second of in a day must be an even number'    )
+         IF( MOD( rdt  , 2.  ) /= 0. )   CALL ctl_stop( 'the time step (in second) must be an even number'           )
+      ENDIF
+      !                       !**  check option consistency
+      !
+      IF(lwp) WRITE(numout,*)       !* Single / Multi - executable (NEMO / OPA+SAS) 
+      SELECT CASE( nn_components )
+      CASE( jp_iam_nemo )
+         IF(lwp) WRITE(numout,*) '   ==>>>   NEMO configured as a single executable (i.e. including both OPA and Surface module)'
+      CASE( jp_iam_opa  )
+         IF(lwp) WRITE(numout,*) '   ==>>>   Multi executable configuration. Here, OPA component'
+         IF( .NOT.lk_oasis )   CALL ctl_stop( 'sbc_init : OPA-SAS coupled via OASIS, but key_oasis3 disabled' )
+         IF( ln_cpl        )   CALL ctl_stop( 'sbc_init : OPA-SAS coupled via OASIS, but ln_cpl = T in OPA'   )
+         IF( ln_mixcpl     )   CALL ctl_stop( 'sbc_init : OPA-SAS coupled via OASIS, but ln_mixcpl = T in OPA' )
+      CASE( jp_iam_sas  )
+         IF(lwp) WRITE(numout,*) '   ==>>>   Multi executable configuration. Here, SAS component'
+         IF( .NOT.lk_oasis )   CALL ctl_stop( 'sbc_init : OPA-SAS coupled via OASIS, but key_oasis3 disabled' )
+         IF( ln_mixcpl     )   CALL ctl_stop( 'sbc_init : OPA-SAS coupled via OASIS, but ln_mixcpl = T in OPA' )
+      CASE DEFAULT
+         CALL ctl_stop( 'sbc_init : unsupported value for nn_components' )
+      END SELECT
+      !                             !* coupled options
+      IF( ln_cpl ) THEN
+         IF( .NOT. lk_oasis )   CALL ctl_stop( 'sbc_init : coupled mode with an atmosphere model (ln_cpl=T)',   &
+            &                                  '           required to defined key_oasis3' )
+      ENDIF
+      IF( ln_mixcpl ) THEN
+         IF( .NOT. lk_oasis )   CALL ctl_stop( 'sbc_init : mixed forced-coupled mode (ln_mixcpl=T) ',   &
+            &                                  '           required to defined key_oasis3' )
+         IF( .NOT.ln_cpl    )   CALL ctl_stop( 'sbc_init : mixed forced-coupled mode (ln_mixcpl=T) requires ln_cpl = T' )
+         IF( nn_components /= jp_iam_nemo )    &
+            &                   CALL ctl_stop( 'sbc_init : the mixed forced-coupled mode (ln_mixcpl=T) ',   &
+            &                                   '          not yet working with sas-opa coupling via oasis' )
+      ENDIF
+      !                             !* sea-ice
+      SELECT CASE( nn_ice )
+      CASE( 0 )                        !- no ice in the domain
+      CASE( 1 )                        !- Ice-cover climatology ("Ice-if" model)  
+      CASE( 2 )                        !- SI3  ice model
+      CASE( 3 )                        !- CICE ice model
+         IF( .NOT.( ln_blk .OR. ln_cpl ) )   CALL ctl_stop( 'sbc_init : CICE sea-ice model requires ln_blk or ln_cpl = T' )
+         IF( lk_agrif                    )   CALL ctl_stop( 'sbc_init : CICE sea-ice model not currently available with AGRIF' ) 
+      CASE DEFAULT                     !- not supported
+      END SELECT
+      !
+      !                       !**  allocate and set required variables
+      !
+      !                             !* allocate sbc arrays
+      IF( sbc_oce_alloc() /= 0 )   CALL ctl_stop( 'sbc_init : unable to allocate sbc_oce arrays' )
+#if ! defined key_si3 && ! defined key_cice
+      IF( sbc_ice_alloc() /= 0 )   CALL ctl_stop( 'sbc_init : unable to allocate sbc_ice arrays' )
+#endif
+      !
+      IF( .NOT.ln_isf ) THEN        !* No ice-shelf in the domain : allocate and set to zero
+         IF( sbc_isf_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_init : unable to allocate sbc_isf arrays' )
+         fwfisf  (:,:)   = 0._wp   ;   risf_tsc  (:,:,:) = 0._wp
+         fwfisf_b(:,:)   = 0._wp   ;   risf_tsc_b(:,:,:) = 0._wp
+      END IF
+      !
+      IF( sbc_ssr_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_init : unable to allocate sbc_ssr arrays' )
+      IF( .NOT.ln_ssr ) THEN               !* Initialize qrp and erp if no restoring 
+         qrp(:,:) = 0._wp
+         erp(:,:) = 0._wp
+      ENDIF
+      !
+
+      IF( nn_ice == 0 ) THEN        !* No sea-ice in the domain : ice fraction is always zero
+         IF( nn_components /= jp_iam_opa )   fr_i(:,:) = 0._wp    ! except for OPA in SAS-OPA coupled case
+      ENDIF
+      !
+      sfx   (:,:) = 0._wp           !* salt flux due to freezing/melting
+      fmmflx(:,:) = 0._wp           !* freezing minus melting flux
+
+      taum(:,:) = 0._wp             !* wind stress module (needed in GLS in case of reduced restart)
+
+      !                          ! Choice of the Surface Boudary Condition (set nsbc)
+      IF( ln_dm2dc ) THEN           !* daily mean to diurnal cycle
+         nday_qsr = -1   ! allow initialization at the 1st call
+         IF( .NOT.( ln_flx .OR. ln_blk ) .AND. nn_components /= jp_iam_opa )   &
+            &   CALL ctl_stop( 'qsr diurnal cycle from daily values requires a flux or bulk formulation' )
+      ENDIF
+      !                             !* Choice of the Surface Boudary Condition
+      !                             (set nsbc)
+      !
+      ll_purecpl  = ln_cpl .AND. .NOT.ln_mixcpl
+      ll_opa      = nn_components == jp_iam_opa
+      ll_not_nemo = nn_components /= jp_iam_nemo
+      icpt = 0
+      !
+      IF( ln_usr          ) THEN   ;   nsbc = jp_usr     ; icpt = icpt + 1   ;   ENDIF       ! user defined         formulation
+      IF( ln_flx          ) THEN   ;   nsbc = jp_flx     ; icpt = icpt + 1   ;   ENDIF       ! flux                 formulation
+      IF( ln_blk          ) THEN   ;   nsbc = jp_blk     ; icpt = icpt + 1   ;   ENDIF       ! bulk                 formulation
+      IF( ll_purecpl      ) THEN   ;   nsbc = jp_purecpl ; icpt = icpt + 1   ;   ENDIF       ! Pure Coupled         formulation
+      IF( ll_opa          ) THEN   ;   nsbc = jp_none    ; icpt = icpt + 1   ;   ENDIF       ! opa coupling via SAS module
+      !
+      IF( icpt /= 1 )    CALL ctl_stop( 'sbc_init : choose ONE and only ONE sbc option' )
+      !
+      IF(lwp) THEN                     !- print the choice of surface flux formulation
+         WRITE(numout,*)
+         SELECT CASE( nsbc )
+         CASE( jp_usr     )   ;   WRITE(numout,*) '   ==>>>   user defined forcing formulation'
+         CASE( jp_flx     )   ;   WRITE(numout,*) '   ==>>>   flux formulation'
+         CASE( jp_blk     )   ;   WRITE(numout,*) '   ==>>>   bulk formulation'
+         CASE( jp_purecpl )   ;   WRITE(numout,*) '   ==>>>   pure coupled formulation'
+!!gm abusive use of jp_none ??   ===>>> need to be check and changed by adding a jp_sas parameter
+         CASE( jp_none    )   ;   WRITE(numout,*) '   ==>>>   OPA coupled to SAS via oasis'
+            IF( ln_mixcpl )       WRITE(numout,*) '               + forced-coupled mixed formulation'
+         END SELECT
+         IF( ll_not_nemo  )       WRITE(numout,*) '               + OASIS coupled SAS'
+      ENDIF
+      !
+      !                             !* OASIS initialization
+      !
+      IF( lk_oasis )   CALL sbc_cpl_init( nn_ice )   ! Must be done before: (1) first time step
+      !                                              !                      (2) the use of nn_fsbc
+      !     nn_fsbc initialization if OPA-SAS coupling via OASIS
+      !     SAS time-step has to be declared in OASIS (mandatory) -> nn_fsbc has to be modified accordingly
+      IF( nn_components /= jp_iam_nemo ) THEN
+         IF( nn_components == jp_iam_opa )   nn_fsbc = cpl_freq('O_SFLX') / NINT(rdt)
+         IF( nn_components == jp_iam_sas )   nn_fsbc = cpl_freq('I_SFLX') / NINT(rdt)
+         !
+         IF(lwp)THEN
+            WRITE(numout,*)
+            WRITE(numout,*)"   OPA-SAS coupled via OASIS : nn_fsbc re-defined from OASIS namcouple ", nn_fsbc
+            WRITE(numout,*)
+         ENDIF
+      ENDIF
+      !
+      !                             !* check consistency between model timeline and nn_fsbc
+      IF( ln_rst_list .OR. nn_stock /= -1 ) THEN   ! we will do restart files
+         IF( MOD( nitend - nit000 + 1, nn_fsbc) /= 0 ) THEN
+            WRITE(ctmp1,*) 'sbc_init : experiment length (', nitend - nit000 + 1, ') is NOT a multiple of nn_fsbc (', nn_fsbc, ')'
+            CALL ctl_stop( ctmp1, 'Impossible to properly do model restart' )
+         ENDIF
+         IF( .NOT. ln_rst_list .AND. MOD( nn_stock, nn_fsbc) /= 0 ) THEN   ! we don't use nn_stock if ln_rst_list
+            WRITE(ctmp1,*) 'sbc_init : nn_stock (', nn_stock, ') is NOT a multiple of nn_fsbc (', nn_fsbc, ')'
+            CALL ctl_stop( ctmp1, 'Impossible to properly do model restart' )
+         ENDIF
+      ENDIF
+      !
+      IF( MOD( rday, REAL(nn_fsbc, wp) * rdt ) /= 0 )   &
+         &  CALL ctl_warn( 'sbc_init : nn_fsbc is NOT a multiple of the number of time steps in a day' )
+      !
+      IF( ln_dm2dc .AND. NINT(rday) / ( nn_fsbc * NINT(rdt) ) < 8  )   &
+         &   CALL ctl_warn( 'sbc_init : diurnal cycle for qsr: the sampling of the diurnal cycle is too small...' )
+      !
+   
+      !                       !**  associated modules : initialization
+      !
+                          CALL sbc_ssm_init            ! Sea-surface mean fields initialization
+      !
+      IF( ln_blk      )   CALL sbc_blk_init            ! bulk formulae initialization
+
+      IF( ln_ssr      )   CALL sbc_ssr_init            ! Sea-Surface Restoring initialization
+      !
+      IF( ln_isf      )   CALL sbc_isf_init            ! Compute iceshelves
+      !
+                          CALL sbc_rnf_init            ! Runof initialization
+      !
+      IF( ln_apr_dyn )    CALL sbc_apr_init            ! Atmo Pressure Forcing initialization
+      !
+#if defined key_si3
+      IF( lk_agrif .AND. nn_ice == 0 ) THEN            ! allocate ice arrays in case agrif + ice-model + no-ice in child grid
+                          IF( sbc_ice_alloc() /= 0 )   CALL ctl_stop('STOP', 'sbc_ice_alloc : unable to allocate arrays' )
+      ELSEIF( nn_ice == 2 ) THEN
+                          CALL ice_init                ! ICE initialization
+      ENDIF
+#endif
+      IF( nn_ice == 3 )   CALL cice_sbc_init( nsbc )   ! CICE initialization
+      !
+      IF( ln_wave     )   CALL sbc_wave_init           ! surface wave initialisation
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('utau_b')
+         CALL iom_set_rstw_var_active('vtau_b')
+         CALL iom_set_rstw_var_active('qns_b')
+         ! The 3D heat content due to qsr forcing is treated in traqsr
+         ! CALL iom_set_rstw_var_active('qsr_b')
+         CALL iom_set_rstw_var_active('emp_b')
+         CALL iom_set_rstw_var_active('sfx_b')
+      ENDIF
+
+   END SUBROUTINE sbc_init
+
+
+   SUBROUTINE sbc( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc  ***
+      !!
+      !! ** Purpose :   provide at each time-step the ocean surface boundary
+      !!                condition (momentum, heat and freshwater fluxes)
+      !!
+      !! ** Method  :   blah blah  to be written ?????????
+      !!                CAUTION : never mask the surface stress field (tke sbc)
+      !!
+      !! ** Action  : - set the ocean surface boundary condition at before and now
+      !!                time step, i.e.
+      !!                utau_b, vtau_b, qns_b, qsr_b, emp_n, sfx_b, qrp_b, erp_b
+      !!                utau  , vtau  , qns  , qsr  , emp  , sfx  , qrp  , erp
+      !!              - updte the ice fraction : fr_i
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      LOGICAL ::   ll_sas, ll_opa   ! local logical
+      !
+      REAL(wp) ::     zthscl        ! wd  tanh scale
+      REAL(wp), DIMENSION(jpi,jpj) ::  zwdht, zwght  ! wd dep over wd limit, wgt  
+
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('sbc')
+      !
+      !                                            ! ---------------------------------------- !
+      IF( kt /= nit000 ) THEN                      !          Swap of forcing fields          !
+         !                                         ! ---------------------------------------- !
+         utau_b(:,:) = utau(:,:)                         ! Swap the ocean forcing fields
+         vtau_b(:,:) = vtau(:,:)                         ! (except at nit000 where before fields
+         qns_b (:,:) = qns (:,:)                         !  are set at the end of the routine)
+         emp_b (:,:) = emp (:,:)
+         sfx_b (:,:) = sfx (:,:)
+         IF ( ln_rnf ) THEN
+            rnf_b    (:,:  ) = rnf    (:,:  )
+            rnf_tsc_b(:,:,:) = rnf_tsc(:,:,:)
+         ENDIF
+         IF( ln_isf )  THEN
+            fwfisf_b  (:,:  ) = fwfisf  (:,:  )               
+            risf_tsc_b(:,:,:) = risf_tsc(:,:,:)              
+         ENDIF
+        !
+      ENDIF
+      !                                            ! ---------------------------------------- !
+      !                                            !        forcing field computation         !
+      !                                            ! ---------------------------------------- !
+      !
+      ll_sas = nn_components == jp_iam_sas               ! component flags
+      ll_opa = nn_components == jp_iam_opa
+      !
+      IF( .NOT.ll_sas )   CALL sbc_ssm ( kt )            ! mean ocean sea surface variables (sst_m, sss_m, ssu_m, ssv_m)
+      IF( ln_wave     )   CALL sbc_wave( kt )            ! surface waves
+
+      !
+      !                                            !==  sbc formulation  ==!
+      !                                                   
+      SELECT CASE( nsbc )                                ! Compute ocean surface boundary condition
+      !                                                  ! (i.e. utau,vtau, qns, qsr, emp, sfx)
+      CASE( jp_usr   )     ;   CALL usrdef_sbc_oce( kt )                    ! user defined formulation 
+      CASE( jp_flx     )   ;   CALL sbc_flx       ( kt )                    ! flux formulation
+      CASE( jp_blk     )
+         IF( ll_sas    )       CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice )   ! OPA-SAS coupling: SAS receiving fields from OPA
+                               CALL sbc_blk       ( kt )                    ! bulk formulation for the ocean
+                               !
+      CASE( jp_purecpl )   ;   CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice )   ! pure coupled formulation
+      CASE( jp_none    )
+         IF( ll_opa    )       CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice )   ! OPA-SAS coupling: OPA receiving fields from SAS
+      END SELECT
+      !
+      IF( ln_mixcpl )          CALL sbc_cpl_rcv   ( kt, nn_fsbc, nn_ice )   ! forced-coupled mixed formulation after forcing
+      !
+      IF ( ln_wave .AND. (ln_tauwoc .OR. ln_tauw) ) CALL sbc_wstress( )      ! Wind stress provided by waves 
+      !
+      !                                            !==  Misc. Options  ==!
+      !
+      SELECT CASE( nn_ice )                                       ! Update heat and freshwater fluxes over sea-ice areas
+      CASE(  1 )   ;         CALL sbc_ice_if   ( kt )             ! Ice-cover climatology ("Ice-if" model)
+#if defined key_si3
+      CASE(  2 )   ;         CALL ice_stp  ( kt, nsbc )           ! SI3 ice model
+#endif
+      CASE(  3 )   ;         CALL sbc_ice_cice ( kt, nsbc )       ! CICE ice model
+      END SELECT
+
+      IF( ln_icebergs    )   THEN
+                                     CALL icb_stp( kt )           ! compute icebergs
+         ! icebergs may advect into haloes during the icb step and alter emp.
+         ! A lbc_lnk is necessary here to ensure restartability (#2113)
+         IF( .NOT. ln_passive_mode ) CALL lbc_lnk( 'sbcmod', emp, 'T', 1. ) ! ensure restartability with icebergs
+      ENDIF
+
+      IF( ln_isf         )   CALL sbc_isf( kt )                   ! compute iceshelves
+
+      IF( ln_rnf         )   CALL sbc_rnf( kt )                   ! add runoffs to fresh water fluxes
+
+      IF( ln_ssr         )   CALL sbc_ssr( kt )                   ! add SST/SSS damping term
+
+      IF( nn_fwb    /= 0 )   CALL sbc_fwb( kt, nn_fwb, nn_fsbc )  ! control the freshwater budget
+
+      ! Special treatment of freshwater fluxes over closed seas in the model domain
+      ! Should not be run if ln_diurnal_only
+      IF( l_sbc_clo .AND. (.NOT. ln_diurnal_only) )   CALL sbc_clo( kt )   
+
+!!$!RBbug do not understand why see ticket 667
+!!$!clem: it looks like it is necessary for the north fold (in certain circumstances). Don't know why.
+!!$      CALL lbc_lnk( 'sbcmod', emp, 'T', 1. )
+      IF ( ll_wd ) THEN     ! If near WAD point limit the flux for now
+         zthscl = atanh(rn_wd_sbcfra)                     ! taper frac default is .999 
+         zwdht(:,:) = sshn(:,:) + ht_0(:,:) - rn_wdmin1   ! do this calc of water
+                                                     ! depth above wd limit once
+         WHERE( zwdht(:,:) <= 0.0 )
+            taum(:,:) = 0.0
+            utau(:,:) = 0.0
+            vtau(:,:) = 0.0
+            qns (:,:) = 0.0
+            qsr (:,:) = 0.0
+            emp (:,:) = min(emp(:,:),0.0) !can allow puddles to grow but not shrink
+            sfx (:,:) = 0.0
+         END WHERE
+         zwght(:,:) = tanh(zthscl*zwdht(:,:))
+         WHERE( zwdht(:,:) > 0.0  .and. zwdht(:,:) < rn_wd_sbcdep ) !  5 m hard limit here is arbitrary
+            qsr  (:,:) =  qsr(:,:)  * zwght(:,:)
+            qns  (:,:) =  qns(:,:)  * zwght(:,:)
+            taum (:,:) =  taum(:,:) * zwght(:,:)
+            utau (:,:) =  utau(:,:) * zwght(:,:)
+            vtau (:,:) =  vtau(:,:) * zwght(:,:)
+            sfx  (:,:) =  sfx(:,:)  * zwght(:,:)
+            emp  (:,:) =  emp(:,:)  * zwght(:,:)
+         END WHERE
+      ENDIF
+      !
+      IF( kt == nit000 ) THEN                          !   set the forcing field at nit000 - 1    !
+         !                                             ! ---------------------------------------- !
+         IF( ln_rstart .AND.    &                               !* Restart: read in restart file
+            & iom_varid( numror, 'utau_b', ldstop = .FALSE. ) > 0 ) THEN
+            IF(lwp) WRITE(numout,*) '          nit000-1 surface forcing fields red in the restart file'
+            CALL iom_get( numror, jpdom_autoglo, 'utau_b', utau_b, ldxios = lrxios )   ! before i-stress  (U-point)
+            CALL iom_get( numror, jpdom_autoglo, 'vtau_b', vtau_b, ldxios = lrxios )   ! before j-stress  (V-point)
+            CALL iom_get( numror, jpdom_autoglo, 'qns_b' , qns_b, ldxios = lrxios  )   ! before non solar heat flux (T-point)
+            ! The 3D heat content due to qsr forcing is treated in traqsr
+            ! CALL iom_get( numror, jpdom_autoglo, 'qsr_b' , qsr_b, ldxios = lrxios  ) ! before     solar heat flux (T-point)
+            CALL iom_get( numror, jpdom_autoglo, 'emp_b', emp_b, ldxios = lrxios  )    ! before     freshwater flux (T-point)
+            ! To ensure restart capability with 3.3x/3.4 restart files    !! to be removed in v3.6
+            IF( iom_varid( numror, 'sfx_b', ldstop = .FALSE. ) > 0 ) THEN
+               CALL iom_get( numror, jpdom_autoglo, 'sfx_b', sfx_b, ldxios = lrxios )  ! before salt flux (T-point)
+            ELSE
+               sfx_b (:,:) = sfx(:,:)
+            ENDIF
+         ELSE                                                   !* no restart: set from nit000 values
+            IF(lwp) WRITE(numout,*) '          nit000-1 surface forcing fields set to nit000'
+            utau_b(:,:) = utau(:,:)
+            vtau_b(:,:) = vtau(:,:)
+            qns_b (:,:) = qns (:,:)
+            emp_b (:,:) = emp (:,:)
+            sfx_b (:,:) = sfx (:,:)
+         ENDIF
+      ENDIF
+      !                                                ! ---------------------------------------- !
+      IF( lrst_oce ) THEN                              !      Write in the ocean restart file     !
+         !                                             ! ---------------------------------------- !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbc : ocean surface forcing fields written in ocean restart file ',   &
+            &                    'at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'utau_b' , utau, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'vtau_b' , vtau, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'qns_b'  , qns, ldxios = lwxios  )
+         ! The 3D heat content due to qsr forcing is treated in traqsr
+         ! CALL iom_rstput( kt, nitrst, numrow, 'qsr_b'  , qsr  )
+         CALL iom_rstput( kt, nitrst, numrow, 'emp_b'  , emp, ldxios = lwxios  )
+         CALL iom_rstput( kt, nitrst, numrow, 'sfx_b'  , sfx, ldxios = lwxios  )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !                                                ! ---------------------------------------- !
+      !                                                !        Outputs and control print         !
+      !                                                ! ---------------------------------------- !
+      IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN
+         CALL iom_put( "empmr"  , emp    - rnf )                ! upward water flux
+         CALL iom_put( "empbmr" , emp_b  - rnf )                ! before upward water flux ( needed to recalculate the time evolution of ssh in offline )
+         CALL iom_put( "saltflx", sfx  )                        ! downward salt flux (includes virtual salt flux beneath ice in linear free surface case)
+         CALL iom_put( "fmmflx", fmmflx  )                      ! Freezing-melting water flux
+         CALL iom_put( "qt"    , qns  + qsr )                   ! total heat flux
+         CALL iom_put( "qns"   , qns        )                   ! solar heat flux
+         CALL iom_put( "qsr"   ,       qsr  )                   ! solar heat flux
+         IF( nn_ice > 0 .OR. ll_opa )   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
+         CALL iom_put( "qrp", qrp )                             ! heat flux damping
+         CALL iom_put( "erp", erp )                             ! freshwater flux damping
+      ENDIF
+      !
+      IF(ln_ctl) THEN         ! print mean trends (used for debugging)
+         CALL prt_ctl(tab2d_1=fr_i              , clinfo1=' fr_i    - : ', mask1=tmask )
+         CALL prt_ctl(tab2d_1=(emp-rnf + fwfisf), clinfo1=' emp-rnf - : ', mask1=tmask )
+         CALL prt_ctl(tab2d_1=(sfx-rnf + fwfisf), clinfo1=' sfx-rnf - : ', mask1=tmask )
+         CALL prt_ctl(tab2d_1=qns              , clinfo1=' qns      - : ', mask1=tmask )
+         CALL prt_ctl(tab2d_1=qsr              , clinfo1=' qsr      - : ', mask1=tmask )
+         CALL prt_ctl(tab3d_1=tmask            , clinfo1=' tmask    - : ', mask1=tmask, kdim=jpk )
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_tem), clinfo1=' sst      - : ', mask1=tmask, kdim=1   )
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_sal), clinfo1=' sss      - : ', mask1=tmask, kdim=1   )
+         CALL prt_ctl(tab2d_1=utau             , clinfo1=' utau     - : ', mask1=umask,                      &
+            &         tab2d_2=vtau             , clinfo2=' vtau     - : ', mask2=vmask )
+      ENDIF
+
+      IF( kt == nitend )   CALL sbc_final         ! Close down surface module if necessary
+      !
+      IF( ln_timing )   CALL timing_stop('sbc')
+      !
+   END SUBROUTINE sbc
+
+
+   SUBROUTINE sbc_final
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE sbc_final  ***
+      !!
+      !! ** Purpose :   Finalize CICE (if used)
+      !!---------------------------------------------------------------------
+      !
+      IF( nn_ice == 3 )   CALL cice_sbc_final
+      !
+   END SUBROUTINE sbc_final
+
+   !!======================================================================
+END MODULE sbcmod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcrnf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcrnf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcrnf.F90	(revision 14097)
@@ -0,0 +1,552 @@
+MODULE sbcrnf
+   !!======================================================================
+   !!                       ***  MODULE  sbcrnf  ***
+   !! Ocean forcing:  river runoff
+   !!=====================================================================
+   !! History :  OPA  ! 2000-11  (R. Hordoir, E. Durand)  NetCDF FORMAT
+   !!   NEMO     1.0  ! 2002-09  (G. Madec)  F90: Free form and module
+   !!            3.0  ! 2006-07  (G. Madec)  Surface module
+   !!            3.2  ! 2009-04  (B. Lemaire)  Introduce iom_put
+   !!            3.3  ! 2010-10  (R. Furner, G. Madec) runoff distributed over ocean levels
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_rnf       : monthly runoffs read in a NetCDF file
+   !!   sbc_rnf_init  : runoffs initialisation
+   !!   rnf_mouth     : set river mouth mask
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE sbc_oce        ! surface boundary condition variables
+   USE eosbn2         ! Equation Of State
+   USE closea, ONLY: l_clo_rnf, clo_rnf ! closed seas
+   !
+   USE in_out_manager ! I/O manager
+   USE fldread        ! read input field at current time step
+   USE iom            ! I/O module
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_rnf       ! called in sbcmod module
+   PUBLIC   sbc_rnf_div   ! called in divhor module
+   PUBLIC   sbc_rnf_alloc ! called in sbcmod module
+   PUBLIC   sbc_rnf_init  ! called in sbcmod module
+   
+   !                                                !!* namsbc_rnf namelist *
+   CHARACTER(len=100)         ::   cn_dir            !: Root directory for location of rnf files
+   LOGICAL           , PUBLIC ::   ln_rnf_depth      !: depth       river runoffs attribute specified in a file
+   LOGICAL                    ::      ln_rnf_depth_ini  !: depth       river runoffs  computed at the initialisation
+   REAL(wp)                   ::      rn_rnf_max        !: maximum value of the runoff climatologie (ln_rnf_depth_ini =T)
+   REAL(wp)                   ::      rn_dep_max        !: depth over which runoffs is spread       (ln_rnf_depth_ini =T)
+   INTEGER                    ::      nn_rnf_depth_file !: create (=1) a runoff depth file or not (=0)
+   LOGICAL                    ::   ln_rnf_icb        !: iceberg flux is specified in a file
+   LOGICAL                    ::   ln_rnf_tem        !: temperature river runoffs attribute specified in a file
+   LOGICAL           , PUBLIC ::   ln_rnf_sal        !: salinity    river runoffs attribute specified in a file
+   TYPE(FLD_N)       , PUBLIC ::   sn_rnf            !: information about the runoff file to be read
+   TYPE(FLD_N)                ::   sn_cnf            !: information about the runoff mouth file to be read
+   TYPE(FLD_N)                ::   sn_i_rnf          !: information about the iceberg flux file to be read
+   TYPE(FLD_N)                ::   sn_s_rnf          !: information about the salinities of runoff file to be read
+   TYPE(FLD_N)                ::   sn_t_rnf          !: information about the temperatures of runoff file to be read
+   TYPE(FLD_N)                ::   sn_dep_rnf        !: information about the depth which river inflow affects
+   LOGICAL           , PUBLIC ::   ln_rnf_mouth      !: specific treatment in mouths vicinity
+   REAL(wp)                   ::   rn_hrnf           !: runoffs, depth over which enhanced vertical mixing is used
+   REAL(wp)          , PUBLIC ::   rn_avt_rnf        !: runoffs, value of the additional vertical mixing coef. [m2/s]
+   REAL(wp)          , PUBLIC ::   rn_rfact          !: multiplicative factor for runoff
+
+   LOGICAL , PUBLIC ::   l_rnfcpl = .false.   !: runoffs recieved from oasis
+   INTEGER , PUBLIC ::   nkrnf = 0            !: nb of levels over which Kz is increased at river mouths
+   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rnfmsk              !: river mouth mask (hori.)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)     ::   rnfmsk_z            !: river mouth mask (vert.)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   h_rnf               !: depth of runoff in m
+   INTEGER,  PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nk_rnf              !: depth of runoff in model levels
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   rnf_tsc_b, rnf_tsc  !: before and now T & S runoff contents   [K.m/s & PSU.m/s]   
+
+   TYPE(FLD),        ALLOCATABLE, DIMENSION(:) ::   sf_rnf       ! structure: river runoff (file information, fields read)
+   TYPE(FLD),        ALLOCATABLE, DIMENSION(:) ::   sf_i_rnf     ! structure: iceberg flux (file information, fields read)
+   TYPE(FLD),        ALLOCATABLE, DIMENSION(:) ::   sf_s_rnf     ! structure: river runoff salinity (file information, fields read)  
+   TYPE(FLD),        ALLOCATABLE, DIMENSION(:) ::   sf_t_rnf     ! structure: river runoff temperature (file information, fields read)  
+ 
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sbc_rnf_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE sbc_rnf_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( rnfmsk(jpi,jpj)         , rnfmsk_z(jpk)          ,     &
+         &      h_rnf (jpi,jpj)         , nk_rnf  (jpi,jpj)      ,     &
+         &      rnf_tsc_b(jpi,jpj,jpts) , rnf_tsc (jpi,jpj,jpts) , STAT=sbc_rnf_alloc )
+         !
+      CALL mpp_sum ( 'sbcrnf', sbc_rnf_alloc )
+      IF( sbc_rnf_alloc > 0 )   CALL ctl_warn('sbc_rnf_alloc: allocation of arrays failed')
+   END FUNCTION sbc_rnf_alloc
+
+
+   SUBROUTINE sbc_rnf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_rnf  ***
+      !!
+      !! ** Purpose :   Introduce a climatological run off forcing
+      !!
+      !! ** Method  :   Set each river mouth with a monthly climatology
+      !!                provided from different data.
+      !!                CAUTION : upward water flux, runoff forced to be < 0
+      !!
+      !! ** Action  :   runoff updated runoff field at time-step kt
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt          ! ocean time step
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      INTEGER  ::   z_err = 0 ! dummy integer for error handling
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztfrz   ! freezing point used for temperature correction
+      !
+      !
+      !                                            !-------------------!
+      !                                            !   Update runoff   !
+      !                                            !-------------------!
+      !
+      !
+      IF( .NOT. l_rnfcpl )  THEN
+                            CALL fld_read ( kt, nn_fsbc, sf_rnf   )    ! Read Runoffs data and provide it at kt ( runoffs + iceberg )
+         IF( ln_rnf_icb )   CALL fld_read ( kt, nn_fsbc, sf_i_rnf )    ! idem for iceberg flux if required
+      ENDIF
+      IF(   ln_rnf_tem   )   CALL fld_read ( kt, nn_fsbc, sf_t_rnf )    ! idem for runoffs temperature if required
+      IF(   ln_rnf_sal   )   CALL fld_read ( kt, nn_fsbc, sf_s_rnf )    ! idem for runoffs salinity    if required
+      !
+      IF( MOD( kt - 1, nn_fsbc ) == 0 ) THEN
+         !
+         IF( .NOT. l_rnfcpl ) THEN
+             rnf(:,:) = rn_rfact * ( sf_rnf(1)%fnow(:,:,1) ) * tmask(:,:,1)  ! updated runoff value at time step kt
+             IF( ln_rnf_icb ) THEN
+                fwficb(:,:) = rn_rfact * ( sf_i_rnf(1)%fnow(:,:,1) ) * tmask(:,:,1)  ! updated runoff value at time step kt
+                CALL iom_put( 'iceberg_cea'  , fwficb(:,:)  )         ! output iceberg flux
+                CALL iom_put( 'hflx_icb_cea' , fwficb(:,:) * rLfus )   ! output Heat Flux into Sea Water due to Iceberg Thermodynamics -->
+             ENDIF
+         ENDIF
+         !
+         !                                                           ! set temperature & salinity content of runoffs
+         IF( ln_rnf_tem ) THEN                                       ! use runoffs temperature data
+            rnf_tsc(:,:,jp_tem) = ( sf_t_rnf(1)%fnow(:,:,1) ) * rnf(:,:) * r1_rau0
+            CALL eos_fzp( sss_m(:,:), ztfrz(:,:) )
+            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
+         ELSE                                                        ! use SST as runoffs temperature
+            !CEOD River is fresh water so must at least be 0 unless we consider ice
+            rnf_tsc(:,:,jp_tem) = MAX( sst_m(:,:), 0.0_wp ) * rnf(:,:) * r1_rau0
+         ENDIF
+         !                                                           ! use runoffs salinity data
+         IF( ln_rnf_sal )   rnf_tsc(:,:,jp_sal) = ( sf_s_rnf(1)%fnow(:,:,1) ) * rnf(:,:) * r1_rau0
+         !                                                           ! else use S=0 for runoffs (done one for all in the init)
+                                         CALL iom_put( 'runoffs'     , rnf(:,:)                         )   ! output runoff mass flux
+         IF( iom_use('hflx_rnf_cea') )   CALL iom_put( 'hflx_rnf_cea', rnf_tsc(:,:,jp_tem) * rau0 * rcp )   ! output runoff sensible heat (W/m2)
+      ENDIF
+      !
+      !                                                ! ---------------------------------------- !
+      IF( kt == nit000 ) THEN                          !   set the forcing field at nit000 - 1    !
+         !                                             ! ---------------------------------------- !
+         IF( ln_rstart .AND.    &                               !* Restart: read in restart file
+            & iom_varid( numror, 'rnf_b', ldstop = .FALSE. ) > 0 ) THEN
+            IF(lwp) WRITE(numout,*) '          nit000-1 runoff forcing fields red in the restart file', lrxios
+            CALL iom_get( numror, jpdom_autoglo, 'rnf_b', rnf_b, ldxios = lrxios )     ! before runoff
+            CALL iom_get( numror, jpdom_autoglo, 'rnf_hc_b', rnf_tsc_b(:,:,jp_tem), ldxios = lrxios )   ! before heat content of runoff
+            CALL iom_get( numror, jpdom_autoglo, 'rnf_sc_b', rnf_tsc_b(:,:,jp_sal), ldxios = lrxios )   ! before salinity content of runoff
+         ELSE                                                   !* no restart: set from nit000 values
+            IF(lwp) WRITE(numout,*) '          nit000-1 runoff forcing fields set to nit000'
+            rnf_b    (:,:  ) = rnf    (:,:  )
+            rnf_tsc_b(:,:,:) = rnf_tsc(:,:,:)
+         ENDIF
+      ENDIF
+      !                                                ! ---------------------------------------- !
+      IF( lrst_oce ) THEN                              !      Write in the ocean restart file     !
+         !                                             ! ---------------------------------------- !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbcrnf : runoff forcing fields written in ocean restart file ',   &
+            &                    'at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_b' , rnf, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_hc_b', rnf_tsc(:,:,jp_tem), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'rnf_sc_b', rnf_tsc(:,:,jp_sal), ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE sbc_rnf
+
+
+   SUBROUTINE sbc_rnf_div( phdivn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_rnf  ***
+      !!
+      !! ** Purpose :   update the horizontal divergence with the runoff inflow
+      !!
+      !! ** Method  :
+      !!                CAUTION : rnf is positive (inflow) decreasing 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
+      REAL(wp) ::   zfact     ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zfact = 0.5_wp
+      !
+      IF( ln_rnf_depth .OR. ln_rnf_depth_ini ) THEN      !==   runoff distributed over several levels   ==!
+         IF( ln_linssh ) THEN    !* constant volume case : just apply the runoff input flow
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  DO jk = 1, nk_rnf(ji,jj)
+                     phdivn(ji,jj,jk) = phdivn(ji,jj,jk) - ( rnf(ji,jj) + rnf_b(ji,jj) ) * zfact * r1_rau0 / h_rnf(ji,jj)
+                  END DO
+               END DO
+            END DO
+         ELSE                    !* variable volume case
+            DO jj = 1, jpj                   ! update the depth over which runoffs are distributed
+               DO ji = 1, jpi
+                  h_rnf(ji,jj) = 0._wp
+                  DO jk = 1, nk_rnf(ji,jj)                           ! recalculates h_rnf to be the depth in metres
+                     h_rnf(ji,jj) = h_rnf(ji,jj) + e3t_n(ji,jj,jk)   ! to the bottom of the relevant grid box
+                  END DO
+                  !                          ! apply the runoff input flow
+                  DO jk = 1, nk_rnf(ji,jj)
+                     phdivn(ji,jj,jk) = phdivn(ji,jj,jk) - ( rnf(ji,jj) + rnf_b(ji,jj) ) * zfact * r1_rau0 / h_rnf(ji,jj)
+                  END DO
+               END DO
+            END DO
+         ENDIF
+      ELSE                       !==   runoff put only at the surface   ==!
+         h_rnf (:,:)   = e3t_n (:,:,1)        ! update h_rnf to be depth of top box
+         phdivn(:,:,1) = phdivn(:,:,1) - ( rnf(:,:) + rnf_b(:,:) ) * zfact * r1_rau0 / e3t_n(:,:,1)
+      ENDIF
+      !
+   END SUBROUTINE sbc_rnf_div
+
+
+   SUBROUTINE sbc_rnf_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_rnf_init  ***
+      !!
+      !! ** Purpose :   Initialisation of the runoffs if (ln_rnf=T)
+      !!
+      !! ** Method  : - read the runoff namsbc_rnf namelist
+      !!
+      !! ** Action  : - read parameters
+      !!----------------------------------------------------------------------
+      CHARACTER(len=32) ::   rn_dep_file   ! runoff file name
+      INTEGER           ::   ji, jj, jk, jm    ! dummy loop indices
+      INTEGER           ::   ierror, inum  ! temporary integer
+      INTEGER           ::   ios           ! Local integer output status for namelist read
+      INTEGER           ::   nbrec         ! temporary integer
+      REAL(wp)          ::   zacoef  
+      REAL(wp), DIMENSION(jpi,jpj,2) :: zrnfcl    
+      !!
+      NAMELIST/namsbc_rnf/ cn_dir            , ln_rnf_depth, ln_rnf_tem, ln_rnf_sal, ln_rnf_icb,   &
+         &                 sn_rnf, sn_cnf    , sn_i_rnf, sn_s_rnf    , sn_t_rnf  , sn_dep_rnf,   &
+         &                 ln_rnf_mouth      , rn_hrnf     , rn_avt_rnf, rn_rfact,     &
+         &                 ln_rnf_depth_ini  , rn_dep_max  , rn_rnf_max, nn_rnf_depth_file
+      !!----------------------------------------------------------------------
+      !
+      !                                         !==  allocate runoff arrays
+      IF( sbc_rnf_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_rnf_alloc : unable to allocate arrays' )
+      !
+      IF( .NOT. ln_rnf ) THEN                      ! no specific treatment in vicinity of river mouths 
+         ln_rnf_mouth  = .FALSE.                   ! default definition needed for example by sbc_ssr or by tra_adv_muscl
+         nkrnf         = 0
+         rnf     (:,:) = 0.0_wp
+         rnf_b   (:,:) = 0.0_wp
+         rnfmsk  (:,:) = 0.0_wp
+         rnfmsk_z(:)   = 0.0_wp
+         RETURN
+      ENDIF
+      !
+      !                                   ! ============
+      !                                   !   Namelist
+      !                                   ! ============
+      !
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, namsbc_rnf, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_rnf in reference namelist' )
+
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, namsbc_rnf, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_rnf in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_rnf )
+      !
+      !                                         ! Control print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_rnf_init : runoff '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namsbc_rnf'
+         WRITE(numout,*) '      specific river mouths treatment            ln_rnf_mouth = ', ln_rnf_mouth
+         WRITE(numout,*) '      river mouth additional Kz                  rn_avt_rnf   = ', rn_avt_rnf
+         WRITE(numout,*) '      depth of river mouth additional mixing     rn_hrnf      = ', rn_hrnf
+         WRITE(numout,*) '      multiplicative factor for runoff           rn_rfact     = ', rn_rfact
+      ENDIF
+      !                                   ! ==================
+      !                                   !   Type of runoff
+      !                                   ! ==================
+      !
+      IF( .NOT. l_rnfcpl ) THEN                    
+         ALLOCATE( sf_rnf(1), STAT=ierror )         ! Create sf_rnf structure (runoff inflow)
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   runoffs inflow read in a file'
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'sbc_rnf_init: unable to allocate sf_rnf structure' )   ;   RETURN
+         ENDIF
+         ALLOCATE( sf_rnf(1)%fnow(jpi,jpj,1)   )
+         IF( sn_rnf%ln_tint ) ALLOCATE( sf_rnf(1)%fdta(jpi,jpj,1,2) )
+         CALL fld_fill( sf_rnf, (/ sn_rnf /), cn_dir, 'sbc_rnf_init', 'read runoffs data', 'namsbc_rnf', no_print )
+         !
+         IF( ln_rnf_icb ) THEN                      ! Create (if required) sf_i_rnf structure
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '          iceberg flux read in a file'
+            ALLOCATE( sf_i_rnf(1), STAT=ierror  )
+            IF( ierror > 0 ) THEN
+               CALL ctl_stop( 'sbc_rnf_init: unable to allocate sf_i_rnf structure' )   ;   RETURN
+            ENDIF
+            ALLOCATE( sf_i_rnf(1)%fnow(jpi,jpj,1)   )
+            IF( sn_i_rnf%ln_tint ) ALLOCATE( sf_i_rnf(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill (sf_i_rnf, (/ sn_i_rnf /), cn_dir, 'sbc_rnf_init', 'read iceberg flux data', 'namsbc_rnf' )
+         ELSE
+            fwficb(:,:) = 0._wp
+         ENDIF
+
+      ENDIF
+      !
+      IF( ln_rnf_tem ) THEN                      ! Create (if required) sf_t_rnf structure
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   runoffs temperatures read in a file'
+         ALLOCATE( sf_t_rnf(1), STAT=ierror  )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'sbc_rnf_init: unable to allocate sf_t_rnf structure' )   ;   RETURN
+         ENDIF
+         ALLOCATE( sf_t_rnf(1)%fnow(jpi,jpj,1)   )
+         IF( sn_t_rnf%ln_tint ) ALLOCATE( sf_t_rnf(1)%fdta(jpi,jpj,1,2) )
+         CALL fld_fill (sf_t_rnf, (/ sn_t_rnf /), cn_dir, 'sbc_rnf_init', 'read runoff temperature data', 'namsbc_rnf', no_print )
+      ENDIF
+      !
+      IF( ln_rnf_sal  ) THEN                     ! Create (if required) sf_s_rnf and sf_t_rnf structures
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   runoffs salinities read in a file'
+         ALLOCATE( sf_s_rnf(1), STAT=ierror  )
+         IF( ierror > 0 ) THEN
+            CALL ctl_stop( 'sbc_rnf_init: unable to allocate sf_s_rnf structure' )   ;   RETURN
+         ENDIF
+         ALLOCATE( sf_s_rnf(1)%fnow(jpi,jpj,1)   )
+         IF( sn_s_rnf%ln_tint ) ALLOCATE( sf_s_rnf(1)%fdta(jpi,jpj,1,2) )
+         CALL fld_fill (sf_s_rnf, (/ sn_s_rnf /), cn_dir, 'sbc_rnf_init', 'read runoff salinity data', 'namsbc_rnf', no_print )
+      ENDIF
+      !
+      IF( ln_rnf_depth ) THEN                    ! depth of runoffs set from a file
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   runoffs depth read in a file'
+         rn_dep_file = TRIM( cn_dir )//TRIM( sn_dep_rnf%clname )
+         IF( .NOT. sn_dep_rnf%ln_clim ) THEN   ;   WRITE(rn_dep_file, '(a,"_y",i4)' ) TRIM( rn_dep_file ), nyear    ! add year 
+            IF( sn_dep_rnf%cltype == 'monthly' )   WRITE(rn_dep_file, '(a,"m",i2)'  ) TRIM( rn_dep_file ), nmonth   ! add month 
+         ENDIF
+         CALL iom_open ( rn_dep_file, inum )                           ! open file
+         CALL iom_get  ( inum, jpdom_data, sn_dep_rnf%clvar, h_rnf )   ! read the river mouth array
+         CALL iom_close( inum )                                        ! close file
+         !
+         nk_rnf(:,:) = 0                               ! set the number of level over which river runoffs are applied
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( h_rnf(ji,jj) > 0._wp ) THEN
+                  jk = 2
+                  DO WHILE ( jk < mbkt(ji,jj) .AND. gdept_0(ji,jj,jk) < h_rnf(ji,jj) ) ;  jk = jk + 1
+                  END DO
+                  nk_rnf(ji,jj) = jk
+               ELSEIF( h_rnf(ji,jj) == -1._wp   ) THEN   ;  nk_rnf(ji,jj) = 1
+               ELSEIF( h_rnf(ji,jj) == -999._wp ) THEN   ;  nk_rnf(ji,jj) = mbkt(ji,jj)
+               ELSE
+                  CALL ctl_stop( 'sbc_rnf_init: runoff depth not positive, and not -999 or -1, rnf value in file fort.999'  )
+                  WRITE(999,*) 'ji, jj, h_rnf(ji,jj) :', ji, jj, h_rnf(ji,jj)
+               ENDIF
+            END DO
+         END DO
+         DO jj = 1, jpj                                ! set the associated depth
+            DO ji = 1, jpi
+               h_rnf(ji,jj) = 0._wp
+               DO jk = 1, nk_rnf(ji,jj)
+                  h_rnf(ji,jj) = h_rnf(ji,jj) + e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      ELSE IF( ln_rnf_depth_ini ) THEN           ! runoffs applied at the surface
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   depth of runoff computed once from max value of runoff'
+         IF(lwp) WRITE(numout,*) '        max value of the runoff climatologie (over global domain) rn_rnf_max = ', rn_rnf_max
+         IF(lwp) WRITE(numout,*) '        depth over which runoffs is spread                        rn_dep_max = ', rn_dep_max
+         IF(lwp) WRITE(numout,*) '        create (=1) a runoff depth file or not (=0)      nn_rnf_depth_file  = ', nn_rnf_depth_file
+
+         CALL iom_open( TRIM( sn_rnf%clname ), inum )    !  open runoff file
+         nbrec = iom_getszuld( inum )
+         zrnfcl(:,:,1) = 0._wp                                                          ! init the max to 0. in 1
+         DO jm = 1, nbrec
+            CALL iom_get( inum, jpdom_data, TRIM( sn_rnf%clvar ), zrnfcl(:,:,2), jm )   ! read the value in 2
+            zrnfcl(:,:,1) = MAXVAL( zrnfcl(:,:,:), DIM=3 )                              ! store the maximum value in time in 1
+         END DO
+         CALL iom_close( inum )
+         !
+         h_rnf(:,:) = 1.
+         !
+         zacoef = rn_dep_max / rn_rnf_max            ! coef of linear relation between runoff and its depth (150m for max of runoff)
+         !
+         WHERE( zrnfcl(:,:,1) > 0._wp )  h_rnf(:,:) = zacoef * zrnfcl(:,:,1)   ! compute depth for all runoffs
+         !
+         DO jj = 1, jpj                     ! take in account min depth of ocean rn_hmin
+            DO ji = 1, jpi
+               IF( zrnfcl(ji,jj,1) > 0._wp ) THEN
+                  jk = mbkt(ji,jj)
+                  h_rnf(ji,jj) = MIN( h_rnf(ji,jj), gdept_0(ji,jj,jk ) )
+               ENDIF
+            END DO
+         END DO
+         !
+         nk_rnf(:,:) = 0                       ! number of levels on which runoffs are distributed
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zrnfcl(ji,jj,1) > 0._wp ) THEN
+                  jk = 2
+                  DO WHILE ( jk < mbkt(ji,jj) .AND. gdept_0(ji,jj,jk) < h_rnf(ji,jj) ) ;  jk = jk + 1
+                  END DO
+                  nk_rnf(ji,jj) = jk
+               ELSE
+                  nk_rnf(ji,jj) = 1
+               ENDIF
+            END DO
+         END DO
+         !
+         DO jj = 1, jpj                                ! set the associated depth
+            DO ji = 1, jpi
+               h_rnf(ji,jj) = 0._wp
+               DO jk = 1, nk_rnf(ji,jj)
+                  h_rnf(ji,jj) = h_rnf(ji,jj) + e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF( nn_rnf_depth_file == 1 ) THEN      !  save  output nb levels for runoff
+            IF(lwp) WRITE(numout,*) '   ==>>>   create runoff depht file'
+            CALL iom_open  ( TRIM( sn_dep_rnf%clname ), inum, ldwrt = .TRUE. )
+            CALL iom_rstput( 0, 0, inum, 'rodepth', h_rnf )
+            CALL iom_close ( inum )
+         ENDIF
+      ELSE                                       ! runoffs applied at the surface
+         nk_rnf(:,:) = 1
+         h_rnf (:,:) = e3t_n(:,:,1)
+      ENDIF
+      !
+      rnf(:,:) =  0._wp                         ! runoff initialisation
+      rnf_tsc(:,:,:) = 0._wp                    ! runoffs temperature & salinty contents initilisation
+      !
+      !                                   ! ========================
+      !                                   !   River mouth vicinity
+      !                                   ! ========================
+      !
+      IF( ln_rnf_mouth ) THEN                   ! Specific treatment in vicinity of river mouths :
+         !                                      !    - Increase Kz in surface layers ( rn_hrnf > 0 )
+         !                                      !    - set to zero SSS damping (ln_ssr=T)
+         !                                      !    - mixed upstream-centered (ln_traadv_cen2=T)
+         !
+         IF( ln_rnf_depth )   CALL ctl_warn( 'sbc_rnf_init: increased mixing turned on but effects may already',   &
+            &                                              'be spread through depth by ln_rnf_depth'               )
+         !
+         nkrnf = 0                                  ! Number of level over which Kz increase
+         IF( rn_hrnf > 0._wp ) THEN
+            nkrnf = 2
+            DO WHILE( nkrnf /= jpkm1 .AND. gdepw_1d(nkrnf+1) < rn_hrnf )   ;   nkrnf = nkrnf + 1
+            END DO
+            IF( ln_sco )   CALL ctl_warn( 'sbc_rnf_init: number of levels over which Kz is increased is computed for zco...' )
+         ENDIF
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   Specific treatment used in vicinity of river mouths :'
+         IF(lwp) WRITE(numout,*) '             - Increase Kz in surface layers (if rn_hrnf > 0 )'
+         IF(lwp) WRITE(numout,*) '               by ', rn_avt_rnf,' m2/s  over ', nkrnf, ' w-levels'
+         IF(lwp) WRITE(numout,*) '             - set to zero SSS damping       (if ln_ssr=T)'
+         IF(lwp) WRITE(numout,*) '             - mixed upstream-centered       (if ln_traadv_cen2=T)'
+         !
+         CALL rnf_mouth                             ! set river mouth mask
+         !
+      ELSE                                      ! No treatment at river mouths
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   No specific treatment at river mouths'
+         rnfmsk  (:,:) = 0._wp
+         rnfmsk_z(:)   = 0._wp
+         nkrnf = 0
+      ENDIF
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('rnf_b')
+         CALL iom_set_rstw_var_active('rnf_hc_b')
+         CALL iom_set_rstw_var_active('rnf_sc_b')
+      ENDIF
+
+   END SUBROUTINE sbc_rnf_init
+
+
+   SUBROUTINE rnf_mouth
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE rnf_mouth  ***
+      !!
+      !! ** Purpose :   define the river mouths mask
+      !!
+      !! ** Method  :   read the river mouth mask (=0/1) in the river runoff
+      !!                climatological file. Defined a given vertical structure.
+      !!                CAUTION, the vertical structure is hard coded on the
+      !!                first 5 levels.
+      !!                This fields can be used to:
+      !!                 - set an upstream advection scheme
+      !!                   (ln_rnf_mouth=T and ln_traadv_cen2=T)
+      !!                 - increase vertical on the top nn_krnf vertical levels
+      !!                   at river runoff input grid point (nn_krnf>=2, see step.F90)
+      !!                 - set to zero SSS restoring flux at river mouth grid points
+      !!
+      !! ** Action  :   rnfmsk   set to 1 at river runoff input, 0 elsewhere
+      !!                rnfmsk_z vertical structure
+      !!----------------------------------------------------------------------
+      INTEGER            ::   inum        ! temporary integers
+      CHARACTER(len=140) ::   cl_rnfile   ! runoff file name
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   rnf_mouth : river mouth mask'
+      IF(lwp) WRITE(numout,*) '   ~~~~~~~~~ '
+      !
+      cl_rnfile = TRIM( cn_dir )//TRIM( sn_cnf%clname )
+      IF( .NOT. sn_cnf%ln_clim ) THEN   ;   WRITE(cl_rnfile, '(a,"_y",i4)' ) TRIM( cl_rnfile ), nyear    ! add year
+         IF( sn_cnf%cltype == 'monthly' )   WRITE(cl_rnfile, '(a,"m",i2)'  ) TRIM( cl_rnfile ), nmonth   ! add month
+      ENDIF
+      !
+      ! horizontal mask (read in NetCDF file)
+      CALL iom_open ( cl_rnfile, inum )                           ! open file
+      CALL iom_get  ( inum, jpdom_data, sn_cnf%clvar, rnfmsk )    ! read the river mouth array
+      CALL iom_close( inum )                                      ! close file
+      !
+      IF( l_clo_rnf )   CALL clo_rnf( rnfmsk )   ! closed sea inflow set as river mouth
+      !
+      rnfmsk_z(:)   = 0._wp                                       ! vertical structure
+      rnfmsk_z(1)   = 1.0
+      rnfmsk_z(2)   = 1.0                                         ! **********
+      rnfmsk_z(3)   = 0.5                                         ! HARD CODED on the 5 first levels
+      rnfmsk_z(4)   = 0.25                                        ! **********
+      rnfmsk_z(5)   = 0.125
+      !
+   END SUBROUTINE rnf_mouth
+
+   !!======================================================================
+END MODULE sbcrnf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssm.F90	(revision 14097)
@@ -0,0 +1,272 @@
+MODULE sbcssm
+   !!======================================================================
+   !!                       ***  MODULE  sbcssm  ***
+   !! Surface module :  provide time-mean ocean surface variables
+   !!======================================================================
+   !! History :  9.0  ! 2006-07  (G. Madec)  Original code
+   !!            3.3  ! 2010-10  (C. Bricaud, G. Madec)  add the Patm forcing for sea-ice
+   !!            3.7  ! 2015-11  (G. Madec)  non linear free surface by default: e3t_m always computed
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_ssm       : calculate sea surface mean currents, temperature,  
+   !!                   and salinity over nn_fsbc time-step
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! surface boundary condition: ocean fields
+   USE sbcapr         ! surface boundary condition: atmospheric pressure
+   USE eosbn2         ! equation of state and related derivatives
+   USE traqsr, ONLY: ln_traqsr
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE iom            ! IOM library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ssm        ! routine called by step.F90
+   PUBLIC   sbc_ssm_init   ! routine called by sbcmod.F90
+
+   LOGICAL, SAVE ::   l_ssm_mean = .FALSE.   ! keep track of whether means have been read from restart file
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_ssm( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_oce  ***
+      !!                     
+      !! ** Purpose :   provide ocean surface variable to sea-surface boundary
+      !!                condition computation 
+      !!                
+      !! ** Method  :   compute mean surface velocity (2 components at U and 
+      !!      V-points) [m/s], temperature [Celsius] and salinity [psu] over
+      !!      the periode (kt - nn_fsbc) to kt
+      !!         Note that the inverse barometer ssh (i.e. ssh associated with Patm)
+      !!      is add to ssh_m when ln_apr_dyn = T. Required for sea-ice dynamics.
+      !!---------------------------------------------------------------------
+      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
+      !!---------------------------------------------------------------------
+      !
+      !                                        !* surface T-, U-, V- ocean level variables (T, S, depth, velocity)
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            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( nn_fsbc == 1 ) THEN                             !   Instantaneous surface fields        !
+         !                                                ! ---------------------------------------- !
+         ssu_m(:,:) = ub(:,:,1)
+         ssv_m(:,:) = vb(:,:,1)
+         IF( l_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(:,:) )
+         ELSE                    ;   ssh_m(:,:) = sshn(:,:)
+         ENDIF
+         !
+         e3t_m(:,:) = e3t_n(:,:,1)
+         !
+         frq_m(:,:) = fraqsr_1lev(:,:)
+         !
+      ELSE
+         !                                                ! ----------------------------------------------- !
+         IF( kt == nit000 .AND. .NOT. l_ssm_mean ) THEN   !   Initialisation: 1st time-step, no input means !
+            !                                             ! ----------------------------------------------- !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'sbc_ssm : mean fields initialised to instantaneous values'
+            IF(lwp) WRITE(numout,*) '~~~~~~~   '
+            zcoef = REAL( nn_fsbc - 1, wp )
+            ssu_m(:,:) = zcoef * ub(:,:,1)
+            ssv_m(:,:) = zcoef * vb(:,:,1)
+            IF( l_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(:,:)
+            ENDIF
+            !
+            e3t_m(:,:) = zcoef * e3t_n(:,:,1)
+            !
+            frq_m(:,:) = zcoef * fraqsr_1lev(:,:)
+            !                                             ! ---------------------------------------- !
+         ELSEIF( MOD( kt - 2 , nn_fsbc ) == 0 ) THEN      !   Initialisation: New mean computation   !
+            !                                             ! ---------------------------------------- !
+            ssu_m(:,:) = 0._wp     ! reset to zero ocean mean sbc fields
+            ssv_m(:,:) = 0._wp
+            sst_m(:,:) = 0._wp
+            sss_m(:,:) = 0._wp
+            ssh_m(:,:) = 0._wp
+            e3t_m(:,:) = 0._wp
+            frq_m(:,:) = 0._wp
+         ENDIF
+         !                                                ! ---------------------------------------- !
+         !                                                !        Cumulate at each time step        !
+         !                                                ! ---------------------------------------- !
+         ssu_m(:,:) = ssu_m(:,:) + ub(:,:,1)
+         ssv_m(:,:) = ssv_m(:,:) + vb(:,:,1)
+         IF( l_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(:,:) )
+         ELSE                    ;   ssh_m(:,:) = ssh_m(:,:) + sshn(:,:)
+         ENDIF
+         !
+         e3t_m(:,:) = e3t_m(:,:) + e3t_n(:,:,1)
+         !
+         frq_m(:,:) = frq_m(:,:) + fraqsr_1lev(:,:)
+
+         !                                                ! ---------------------------------------- !
+         IF( MOD( kt - 1 , nn_fsbc ) == 0 ) THEN          !   Mean value at each nn_fsbc time-step   !
+            !                                             ! ---------------------------------------- !
+            zcoef = 1. / REAL( nn_fsbc, wp )
+            sst_m(:,:) = sst_m(:,:) * zcoef     ! mean SST             [Celsius]
+            sss_m(:,:) = sss_m(:,:) * zcoef     ! mean SSS             [psu]
+            ssu_m(:,:) = ssu_m(:,:) * zcoef     ! mean suface current  [m/s]
+            ssv_m(:,:) = ssv_m(:,:) * zcoef     !
+            ssh_m(:,:) = ssh_m(:,:) * zcoef     ! mean SSH             [m]
+            e3t_m(:,:) = e3t_m(:,:) * zcoef     ! mean vertical scale factor [m]
+            frq_m(:,:) = frq_m(:,:) * zcoef     ! mean fraction of solar net radiation absorbed in the 1st T level [-]
+            !
+         ENDIF
+         !                                                ! ---------------------------------------- !
+         IF( lrst_oce ) THEN                              !      Write in the ocean restart file     !
+            !                                             ! ---------------------------------------- !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'sbc_ssm : sea surface mean fields written in ocean restart file ',   &
+               &                    'at it= ', kt,' date= ', ndastp
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+            zf_sbc = REAL( nn_fsbc, wp )
+            IF( lwxios ) CALL iom_swap(      cwxios_context          )
+            CALL iom_rstput( kt, nitrst, numrow, 'nn_fsbc', zf_sbc, ldxios = lwxios )    ! sbc frequency
+            CALL iom_rstput( kt, nitrst, numrow, 'ssu_m'  , ssu_m, ldxios = lwxios  )    ! sea surface mean fields
+            CALL iom_rstput( kt, nitrst, numrow, 'ssv_m'  , ssv_m, ldxios = lwxios  )
+            CALL iom_rstput( kt, nitrst, numrow, 'sst_m'  , sst_m, ldxios = lwxios  )
+            CALL iom_rstput( kt, nitrst, numrow, 'sss_m'  , sss_m, ldxios = lwxios  )
+            CALL iom_rstput( kt, nitrst, numrow, 'ssh_m'  , ssh_m, ldxios = lwxios  )
+            CALL iom_rstput( kt, nitrst, numrow, 'e3t_m'  , e3t_m, ldxios = lwxios  )
+            CALL iom_rstput( kt, nitrst, numrow, 'frq_m'  , frq_m, ldxios = lwxios  )
+            !
+            IF( lwxios ) CALL iom_swap(      cxios_context          )
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( MOD( kt - 1 , nn_fsbc ) == 0 ) THEN          !   Mean value at each nn_fsbc time-step   !
+         CALL iom_put( 'ssu_m', ssu_m )
+         CALL iom_put( 'ssv_m', ssv_m )
+         CALL iom_put( 'sst_m', sst_m )
+         CALL iom_put( 'sss_m', sss_m )
+         CALL iom_put( 'ssh_m', ssh_m )
+         CALL iom_put( 'e3t_m', e3t_m )
+         CALL iom_put( 'frq_m', frq_m )
+      ENDIF
+      !
+   END SUBROUTINE sbc_ssm
+
+
+   SUBROUTINE sbc_ssm_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ssm_init  ***
+      !!
+      !! ** Purpose :   Initialisation of the sbc data
+      !!
+      !! ** Action  : - read parameters
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zcoef, zf_sbc   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_fsbc == 1 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbc_ssm_init : sea surface mean fields, nn_fsbc=1 : instantaneous values'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~ '
+         !
+      ELSE
+         !               
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbc_ssm_init : sea surface mean fields'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~ '
+         !
+         IF( ln_rstart .AND. iom_varid( numror, 'nn_fsbc', ldstop = .FALSE. ) > 0 ) THEN
+            l_ssm_mean = .TRUE.
+            CALL iom_get( numror               , 'nn_fsbc', zf_sbc, ldxios = lrxios )    ! sbc frequency of previous run
+            CALL iom_get( numror, jpdom_autoglo, 'ssu_m'  , ssu_m, ldxios = lrxios  )    ! sea surface mean velocity    (U-point)
+            CALL iom_get( numror, jpdom_autoglo, 'ssv_m'  , ssv_m, ldxios = lrxios  )    !   "         "    velocity    (V-point)
+            CALL iom_get( numror, jpdom_autoglo, 'sst_m'  , sst_m, ldxios = lrxios  )    !   "         "    temperature (T-point)
+            CALL iom_get( numror, jpdom_autoglo, 'sss_m'  , sss_m, ldxios = lrxios  )    !   "         "    salinity    (T-point)
+            CALL iom_get( numror, jpdom_autoglo, 'ssh_m'  , ssh_m, ldxios = lrxios  )    !   "         "    height      (T-point)
+            CALL iom_get( numror, jpdom_autoglo, 'e3t_m'  , e3t_m, ldxios = lrxios  )    ! 1st level thickness          (T-point)
+            ! fraction of solar net radiation absorbed in 1st T level
+            IF( iom_varid( numror, 'frq_m', ldstop = .FALSE. ) > 0 ) THEN
+               CALL iom_get( numror, jpdom_autoglo, 'frq_m'  , frq_m, ldxios = lrxios  )
+            ELSE
+               frq_m(:,:) = 1._wp   ! default definition
+            ENDIF
+            !
+            IF( zf_sbc /= REAL( nn_fsbc, wp ) ) THEN      ! nn_fsbc has changed between 2 runs
+               IF(lwp) WRITE(numout,*) '   restart with a change in the frequency of mean from ', zf_sbc, ' to ', nn_fsbc 
+               zcoef = REAL( nn_fsbc - 1, wp ) / zf_sbc 
+               ssu_m(:,:) = zcoef * ssu_m(:,:) 
+               ssv_m(:,:) = zcoef * ssv_m(:,:)
+               sst_m(:,:) = zcoef * sst_m(:,:)
+               sss_m(:,:) = zcoef * sss_m(:,:)
+               ssh_m(:,:) = zcoef * ssh_m(:,:)
+               e3t_m(:,:) = zcoef * e3t_m(:,:)
+               frq_m(:,:) = zcoef * frq_m(:,:)
+            ELSE
+               IF(lwp) WRITE(numout,*) '   mean fields read in the ocean restart file'
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( .NOT.l_ssm_mean ) THEN   ! default initialisation. needed by iceistate
+         !
+         IF(lwp) WRITE(numout,*) '   default initialisation of ss._m arrays'
+         ssu_m(:,:) = ub(:,:,1)
+         ssv_m(:,:) = vb(:,:,1)
+         IF( l_useCT )  THEN    ;   sst_m(:,:) = eos_pt_from_ct( tsn(:,:,1,jp_tem), tsn(:,:,1,jp_sal) )
+         ELSE                   ;   sst_m(:,:) = tsn(:,:,1,jp_tem)
+         ENDIF
+         sss_m(:,:) = tsn  (:,:,1,jp_sal)
+         ssh_m(:,:) = sshn (:,:)
+         e3t_m(:,:) = e3t_n(:,:,1)
+         frq_m(:,:) = 1._wp
+         !
+      ENDIF
+      !
+      IF( .NOT. ln_traqsr )   fraqsr_1lev(:,:) = 1._wp   ! default definition: qsr 100% in the fisrt level 
+      !
+      IF( lwxios.AND.nn_fsbc > 1 ) THEN
+         CALL iom_set_rstw_var_active('nn_fsbc')
+         CALL iom_set_rstw_var_active('ssu_m')
+         CALL iom_set_rstw_var_active('ssv_m')
+         CALL iom_set_rstw_var_active('sst_m')
+         CALL iom_set_rstw_var_active('sss_m')
+         CALL iom_set_rstw_var_active('ssh_m')
+         CALL iom_set_rstw_var_active('e3t_m')
+         CALL iom_set_rstw_var_active('frq_m')
+      ENDIF
+
+   END SUBROUTINE sbc_ssm_init
+
+   !!======================================================================
+END MODULE sbcssm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcssr.F90	(revision 14097)
@@ -0,0 +1,256 @@
+MODULE sbcssr
+   !!======================================================================
+   !!                       ***  MODULE  sbcssr  ***
+   !! Surface module :  heat and fresh water fluxes a restoring term toward observed SST/SSS
+   !!======================================================================
+   !! History :  3.0  !  2006-06  (G. Madec)  Original code
+   !!            3.2  !  2009-04  (B. Lemaire)  Introduce iom_put
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   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
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! surface boundary condition
+   USE phycst         ! physical constants
+   USE sbcrnf         ! surface boundary condition : runoffs
+   !
+   USE fldread        ! read input fields
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ssr        ! routine called in sbcmod
+   PUBLIC   sbc_ssr_init   ! routine called in sbcmod
+   PUBLIC   sbc_ssr_alloc  ! routine called in sbcmod
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   erp   !: evaporation damping   [kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qrp   !: heat flux damping        [w/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   coefice   !: under ice relaxation coefficient
+
+   !                                   !!* Namelist namsbc_ssr *
+   INTEGER, PUBLIC ::   nn_sstr         ! SST/SSS restoring indicator
+   INTEGER, PUBLIC ::   nn_sssr         ! SST/SSS restoring indicator
+   REAL(wp)        ::   rn_dqdt         ! restoring factor on SST and SSS
+   REAL(wp)        ::   rn_deds         ! restoring factor on SST and SSS
+   LOGICAL         ::   ln_sssr_bnd     ! flag to bound erp term 
+   REAL(wp)        ::   rn_sssr_bnd     ! ABS(Max./Min.) value of erp term [mm/day]
+   INTEGER         ::   nn_sssr_ice     ! Control of restoring under ice
+
+   REAL(wp) , ALLOCATABLE, DIMENSION(:) ::   buffer   ! Temporary buffer for exchange
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_sst   ! structure of input SST (file informations, fields read)
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_sss   ! structure of input SSS (file informations, fields read)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_ssr( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_ssr  ***
+      !!
+      !! ** Purpose :   Add to heat and/or freshwater fluxes a damping term
+      !!                toward observed SST and/or SSS.
+      !!
+      !! ** Method  : - Read namelist namsbc_ssr
+      !!              - Read observed SST and/or SSS
+      !!              - at each nscb time step
+      !!                   add a retroaction term on qns    (nn_sstr = 1)
+      !!                   add a damping term on sfx        (nn_sssr = 1)
+      !!                   add a damping term on emp        (nn_sssr = 2)
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt   ! ocean time step
+      !!
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zerp     ! local scalar for evaporation damping
+      REAL(wp) ::   zqrp     ! local scalar for heat flux damping
+      REAL(wp) ::   zsrp     ! local scalar for unit conversion of rn_deds factor
+      REAL(wp) ::   zerp_bnd ! local scalar for unit conversion of rn_epr_max factor
+      INTEGER  ::   ierror   ! return error code
+      !!
+      CHARACTER(len=100) ::  cn_dir          ! Root directory for location of ssr files
+      TYPE(FLD_N) ::   sn_sst, sn_sss        ! informations about the fields to be read
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_sstr + nn_sssr /= 0 ) THEN
+         !
+         IF( nn_sstr == 1)   CALL fld_read( kt, nn_fsbc, sf_sst )   ! Read SST data and provides it at kt
+         IF( nn_sssr >= 1)   CALL fld_read( kt, nn_fsbc, sf_sss )   ! Read SSS data and provides it at kt
+         !
+         !                                         ! ========================= !
+         IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN      !    Add restoring term     !
+            !                                      ! ========================= !
+            !
+            IF( nn_sstr == 1 ) THEN                                   !* Temperature restoring term
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zqrp = rn_dqdt * ( sst_m(ji,jj) - sf_sst(1)%fnow(ji,jj,1) ) * tmask(ji,jj,1)
+                     qns(ji,jj) = qns(ji,jj) + zqrp
+                     qrp(ji,jj) = zqrp
+                  END DO
+               END DO
+            ENDIF
+            !
+            IF( nn_sssr /= 0 .AND. nn_sssr_ice /= 1 ) THEN
+              ! use fraction of ice ( fr_i ) to adjust relaxation under ice if nn_sssr_ice .ne. 1
+              ! n.b. coefice is initialised and fixed to 1._wp if nn_sssr_ice = 1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     SELECT CASE ( nn_sssr_ice )
+                       CASE ( 0 )    ;  coefice(ji,jj) = 1._wp - fr_i(ji,jj)              ! no/reduced damping under ice
+                       CASE  DEFAULT ;  coefice(ji,jj) = 1._wp + ( nn_sssr_ice - 1 ) * fr_i(ji,jj) ! reinforced damping (x nn_sssr_ice) under ice )
+                     END SELECT
+                  END DO
+               END DO
+            ENDIF
+            !
+            IF( nn_sssr == 1 ) THEN                                   !* Salinity damping term (salt flux only (sfx))
+               zsrp = rn_deds / rday                                  ! from [mm/day] to [kg/m2/s]
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zerp = zsrp * ( 1. - 2.*rnfmsk(ji,jj) )   &      ! No damping in vicinity of river mouths
+                        &        *   coefice(ji,jj)            &      ! Optional control of damping under sea-ice
+                        &        * ( sss_m(ji,jj) - sf_sss(1)%fnow(ji,jj,1) ) * tmask(ji,jj,1)
+                     sfx(ji,jj) = sfx(ji,jj) + zerp                 ! salt flux
+                     erp(ji,jj) = zerp / MAX( sss_m(ji,jj), 1.e-20 ) ! converted into an equivalent volume flux (diagnostic only)
+                  END DO
+               END DO
+               !
+            ELSEIF( nn_sssr == 2 ) THEN                               !* Salinity damping term (volume flux (emp) and associated heat flux (qns)
+               zsrp = rn_deds / rday                                  ! from [mm/day] to [kg/m2/s]
+               zerp_bnd = rn_sssr_bnd / rday                          !       -              -    
+               DO jj = 1, jpj
+                  DO ji = 1, jpi                            
+                     zerp = zsrp * ( 1. - 2.*rnfmsk(ji,jj) )   &      ! No damping in vicinity of river mouths
+                        &        *   coefice(ji,jj)            &      ! Optional control of damping under sea-ice
+                        &        * ( sss_m(ji,jj) - sf_sss(1)%fnow(ji,jj,1) )   &
+                        &        / MAX(  sss_m(ji,jj), 1.e-20   ) * tmask(ji,jj,1)
+                     IF( ln_sssr_bnd )   zerp = SIGN( 1., zerp ) * MIN( zerp_bnd, ABS(zerp) )
+                     emp(ji,jj) = emp (ji,jj) + zerp
+                     qns(ji,jj) = qns(ji,jj) - zerp * rcp * sst_m(ji,jj)
+                     erp(ji,jj) = zerp
+                  END DO
+               END DO
+            ENDIF
+            !
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE sbc_ssr
+
+ 
+   SUBROUTINE sbc_ssr_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ssr_init  ***
+      !!
+      !! ** Purpose :   initialisation of surface damping term
+      !!
+      !! ** Method  : - Read namelist namsbc_ssr
+      !!              - Read observed SST and/or SSS if required
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zerp     ! local scalar for evaporation damping
+      REAL(wp) ::   zqrp     ! local scalar for heat flux damping
+      REAL(wp) ::   zsrp     ! local scalar for unit conversion of rn_deds factor
+      REAL(wp) ::   zerp_bnd ! local scalar for unit conversion of rn_epr_max factor
+      INTEGER  ::   ierror   ! return error code
+      !!
+      CHARACTER(len=100) ::  cn_dir          ! Root directory for location of ssr files
+      TYPE(FLD_N) ::   sn_sst, sn_sss        ! informations about the fields to be read
+      NAMELIST/namsbc_ssr/ cn_dir, nn_sstr, nn_sssr, rn_dqdt, rn_deds, sn_sst, &
+              & sn_sss, ln_sssr_bnd, rn_sssr_bnd, nn_sssr_ice
+      INTEGER     ::  ios
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_ssr : SST and/or SSS damping term '
+         WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      ! 
+      REWIND( numnam_ref )              ! Namelist namsbc_ssr in reference namelist : 
+      READ  ( numnam_ref, namsbc_ssr, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_ssr in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namsbc_ssr in configuration namelist :
+      READ  ( numnam_cfg, namsbc_ssr, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_ssr in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_ssr )
+
+      IF(lwp) THEN                 !* control print
+         WRITE(numout,*) '   Namelist namsbc_ssr :'
+         WRITE(numout,*) '      SST restoring term (Yes=1)             nn_sstr        = ', nn_sstr
+         WRITE(numout,*) '         dQ/dT (restoring magnitude on SST)     rn_dqdt     = ', rn_dqdt, ' W/m2/K'
+         WRITE(numout,*) '      SSS damping term (Yes=1, salt   flux)  nn_sssr        = ', nn_sssr
+         WRITE(numout,*) '                       (Yes=2, volume flux) '
+         WRITE(numout,*) '         dE/dS (restoring magnitude on SST)     rn_deds     = ', rn_deds, ' mm/day'
+         WRITE(numout,*) '         flag to bound erp term                 ln_sssr_bnd = ', ln_sssr_bnd
+         WRITE(numout,*) '         ABS(Max./Min.) erp threshold           rn_sssr_bnd = ', rn_sssr_bnd, ' mm/day'
+         WRITE(numout,*) '      Cntrl of surface restoration under ice nn_sssr_ice    = ', nn_sssr_ice
+         WRITE(numout,*) '          ( 0 = no restoration under ice)'
+         WRITE(numout,*) '          ( 1 = restoration everywhere  )'
+         WRITE(numout,*) '          (>1 = enhanced restoration under ice  )'
+      ENDIF
+      !
+      IF( nn_sstr == 1 ) THEN      !* set sf_sst structure & allocate arrays
+         !
+         ALLOCATE( sf_sst(1), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sst structure' )
+         ALLOCATE( sf_sst(1)%fnow(jpi,jpj,1), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sst now array' )
+         !
+         ! fill sf_sst with sn_sst and control print
+         CALL fld_fill( sf_sst, (/ sn_sst /), cn_dir, 'sbc_ssr', 'SST restoring term toward SST data', 'namsbc_ssr', no_print )
+         IF( sf_sst(1)%ln_tint )   ALLOCATE( sf_sst(1)%fdta(jpi,jpj,1,2), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sst data array' )
+         !
+      ENDIF
+      !
+      IF( nn_sssr >= 1 ) THEN      !* set sf_sss structure & allocate arrays
+         !
+         ALLOCATE( sf_sss(1), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sss structure' )
+         ALLOCATE( sf_sss(1)%fnow(jpi,jpj,1), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sss now array' )
+         !
+         ! fill sf_sss with sn_sss and control print
+         CALL fld_fill( sf_sss, (/ sn_sss /), cn_dir, 'sbc_ssr', 'SSS restoring term toward SSS data', 'namsbc_ssr', no_print )
+         IF( sf_sss(1)%ln_tint )   ALLOCATE( sf_sss(1)%fdta(jpi,jpj,1,2), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_ssr: unable to allocate sf_sss data array' )
+         !
+      ENDIF
+      !
+      coefice(:,:) = 1._wp         !  Initialise coefice to 1._wp ; will not need to be changed if nn_sssr_ice=1
+      !                            !* Initialize qrp and erp if no restoring 
+      IF( nn_sstr /= 1                   )   qrp(:,:) = 0._wp
+      IF( nn_sssr /= 1 .OR. nn_sssr /= 2 )   erp(:,:) = 0._wp
+      !
+   END SUBROUTINE sbc_ssr_init
+         
+   INTEGER FUNCTION sbc_ssr_alloc()
+      !!----------------------------------------------------------------------
+      !!               ***  FUNCTION sbc_ssr_alloc  ***
+      !!----------------------------------------------------------------------
+      sbc_ssr_alloc = 0       ! set to zero if no array to be allocated
+      IF( .NOT. ALLOCATED( erp ) ) THEN
+         ALLOCATE( qrp(jpi,jpj), erp(jpi,jpj), coefice(jpi,jpj), STAT= sbc_ssr_alloc )
+         !
+         IF( lk_mpp                  )   CALL mpp_sum ( 'sbcssr', sbc_ssr_alloc )
+         IF( sbc_ssr_alloc /= 0 )   CALL ctl_warn('sbc_ssr_alloc: failed to allocate arrays.')
+         !
+      ENDIF
+   END FUNCTION
+      
+   !!======================================================================
+END MODULE sbcssr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbctide.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbctide.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbctide.F90	(revision 14097)
@@ -0,0 +1,168 @@
+MODULE sbctide
+   !!======================================================================
+   !!                       ***  MODULE  sbctide  ***
+   !! Initialization of tidal forcing
+   !!======================================================================
+   !! History :  9.0  !  2007  (O. Le Galloudec)  Original code
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constant
+   USE daymod         ! calandar
+   USE tideini        ! 
+   !
+   USE in_out_manager ! I/O units
+   USE iom            ! xIOs server
+   USE ioipsl         ! NetCDF IPSL library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PUBLIC
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:) ::   pot_astro   !
+
+   !!----------------------------------------------------------------------
+   !!   tidal potential
+   !!----------------------------------------------------------------------
+   !!   sbc_tide            : 
+   !!   tide_init_potential :
+   !!----------------------------------------------------------------------
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   amp_pot, phi_pot
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   amp_load, phi_load
+ 
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_tide( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE sbc_tide  ***
+      !!----------------------------------------------------------------------      
+      INTEGER, INTENT( in ) ::   kt     ! ocean time-step
+      INTEGER               ::   jk     ! dummy loop index
+      INTEGER               ::   nsec_day_orig     ! Temporary variable
+      !!----------------------------------------------------------------------
+      
+      IF( nsec_day == NINT(0.5_wp * rdt) .OR. kt == nit000 ) THEN      ! start a new day
+         !
+         IF( kt == nit000 )THEN
+            ALLOCATE( amp_pot(jpi,jpj,nb_harmo),                      &
+               &      phi_pot(jpi,jpj,nb_harmo), pot_astro(jpi,jpj)   )
+            IF( ln_read_load )THEN
+               ALLOCATE( amp_load(jpi,jpj,nb_harmo), phi_load(jpi,jpj,nb_harmo) )
+               CALL tide_init_load
+            ENDIF
+         ENDIF
+         !
+         IF( ln_read_load )THEN
+            amp_pot(:,:,:) = amp_load(:,:,:)
+            phi_pot(:,:,:) = phi_load(:,:,:)
+         ELSE 
+            amp_pot(:,:,:) = 0._wp
+            phi_pot(:,:,:) = 0._wp
+         ENDIF
+         pot_astro(:,:) = 0._wp
+         !
+         ! If the run does not start from midnight then need to initialise tides
+         ! at the start of the current day (only occurs when kt==nit000)
+         ! Temporarily set nsec_day to beginning of day.
+         nsec_day_orig = nsec_day
+         IF ( nsec_day /= NINT(0.5_wp * rdt) ) THEN 
+            kt_tide = kt - (nsec_day - 0.5_wp * rdt)/rdt
+            nsec_day = NINT(0.5_wp * rdt)
+         ELSE
+            kt_tide = kt 
+         ENDIF
+         CALL tide_harmo( omega_tide, v0tide, utide, ftide, ntide, nb_harmo )
+         !
+         !
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'sbc_tide : Update of the components and (re)Init. the potential at kt=', kt
+            WRITE(numout,*) '~~~~~~~~ '
+            DO jk = 1, nb_harmo
+               WRITE(numout,*) Wave(ntide(jk))%cname_tide, utide(jk), ftide(jk), v0tide(jk), omega_tide(jk)
+            END DO
+         ENDIF
+         !
+         IF( ln_tide_pot )   CALL tide_init_potential
+         !
+         ! Reset nsec_day
+         nsec_day = nsec_day_orig 
+      ENDIF
+      !
+   END SUBROUTINE sbc_tide
+
+
+   SUBROUTINE tide_init_potential
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tide_init_potential  ***
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcons, ztmp1, ztmp2, zlat, zlon, ztmp, zamp, zcs   ! local scalar
+      !!----------------------------------------------------------------------
+
+      DO jk = 1, nb_harmo
+         zcons = 0.7_wp * Wave(ntide(jk))%equitide * ftide(jk)
+         DO ji = 1, jpi
+            DO jj = 1, jpj
+               ztmp1 =  ftide(jk) * amp_pot(ji,jj,jk) * COS( phi_pot(ji,jj,jk) + v0tide(jk) + utide(jk) )
+               ztmp2 = -ftide(jk) * amp_pot(ji,jj,jk) * SIN( phi_pot(ji,jj,jk) + v0tide(jk) + utide(jk) )
+               zlat = gphit(ji,jj)*rad !! latitude en radian
+               zlon = glamt(ji,jj)*rad !! longitude en radian
+               ztmp = v0tide(jk) + utide(jk) + Wave(ntide(jk))%nutide * zlon
+               ! le potentiel est composé des effets des astres:
+               IF    ( Wave(ntide(jk))%nutide == 1 )  THEN  ;  zcs = zcons * SIN( 2._wp*zlat )
+               ELSEIF( Wave(ntide(jk))%nutide == 2 )  THEN  ;  zcs = zcons * COS( zlat )**2
+               ELSE                                         ;  zcs = 0._wp
+               ENDIF
+               ztmp1 = ztmp1 + zcs * COS( ztmp )
+               ztmp2 = ztmp2 - zcs * SIN( ztmp )
+               zamp = SQRT( ztmp1*ztmp1 + ztmp2*ztmp2 )
+               amp_pot(ji,jj,jk) = zamp
+               phi_pot(ji,jj,jk) = ATAN2( -ztmp2 / MAX( 1.e-10_wp , zamp ) ,   &
+                  &                        ztmp1 / MAX( 1.e-10_wp,  zamp )   )
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE tide_init_potential
+
+   SUBROUTINE tide_init_load
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tide_init_load  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: inum                 ! Logical unit of input file
+      INTEGER :: ji, jj, itide        ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztr, zti   !: workspace to read in tidal harmonics data 
+      !!----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'tide_init_load : Initialization of load potential from file'
+         WRITE(numout,*) '~~~~~~~~~~~~~~ '
+      ENDIF
+      !
+      CALL iom_open ( cn_tide_load , inum )
+      !
+      DO itide = 1, nb_harmo
+         CALL iom_get  ( inum, jpdom_data,TRIM(Wave(ntide(itide))%cname_tide)//'_z1', ztr(:,:) )
+         CALL iom_get  ( inum, jpdom_data,TRIM(Wave(ntide(itide))%cname_tide)//'_z2', zti(:,:) )
+         !
+         DO ji=1,jpi
+            DO jj=1,jpj
+               amp_load(ji,jj,itide) =  SQRT( ztr(ji,jj)**2. + zti(ji,jj)**2. )
+               phi_load(ji,jj,itide) = ATAN2(-zti(ji,jj), ztr(ji,jj) )
+            END DO
+         END DO
+         !
+      END DO
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE tide_init_load
+
+  !!======================================================================
+END MODULE sbctide
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcwave.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcwave.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/sbcwave.F90	(revision 14097)
@@ -0,0 +1,520 @@
+MODULE sbcwave
+   !!======================================================================
+   !!                       ***  MODULE  sbcwave  ***
+   !! Wave module 
+   !!======================================================================
+   !! History :  3.3  !  2011-09  (M. Adani)  Original code: Drag Coefficient 
+   !!         :  3.4  !  2012-10  (M. Adani)  Stokes Drift 
+   !!            3.6  !  2014-09  (E. Clementi,P. Oddo) New Stokes Drift Computation
+   !!             -   !  2016-12  (G. Madec, E. Clementi) update Stoke drift computation
+   !!                                                    + add sbc_wave_ini routine
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_stokes    : calculate 3D Stokes-drift velocities
+   !!   sbc_wave      : wave data from wave model in netcdf files 
+   !!   sbc_wave_init : initialisation fo surface waves 
+   !!----------------------------------------------------------------------
+   USE phycst         ! physical constants 
+   USE oce            ! ocean variables
+   USE sbc_oce	       ! Surface boundary condition: ocean fields
+   USE zdf_oce,  ONLY : ln_zdfswm
+   USE bdy_oce        ! open boundary condition variables
+   USE domvvl         ! domain: variable volume layers
+   !
+   USE iom            ! I/O manager library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE fldread	       ! read input fields
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_stokes      ! routine called in sbccpl
+   PUBLIC   sbc_wstress     ! routine called in sbcmod 
+   PUBLIC   sbc_wave        ! routine called in sbcmod
+   PUBLIC   sbc_wave_init   ! routine called in sbcmod
+   
+   ! Variables checking if the wave parameters are coupled (if not, they are read from file)
+   LOGICAL, PUBLIC ::   cpl_hsig   = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_phioc  = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_sdrftx = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_sdrfty = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wper   = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wfreq  = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wnum   = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_tauwoc = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_tauw   = .FALSE.
+   LOGICAL, PUBLIC ::   cpl_wdrag  = .FALSE.
+
+   INTEGER ::   jpfld    ! number of files to read for stokes drift
+   INTEGER ::   jp_usd   ! index of stokes drift  (i-component) (m/s)    at T-point
+   INTEGER ::   jp_vsd   ! index of stokes drift  (j-component) (m/s)    at T-point
+   INTEGER ::   jp_hsw   ! index of significant wave hight      (m)      at T-point
+   INTEGER ::   jp_wmp   ! index of mean wave period            (s)      at T-point
+   INTEGER ::   jp_wfr   ! index of wave peak frequency         (1/s)    at T-point
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_cd      ! structure of input fields (file informations, fields read) Drag Coefficient
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_sd      ! structure of input fields (file informations, fields read) Stokes Drift
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_wn      ! structure of input fields (file informations, fields read) wave number for Qiao
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tauwoc  ! structure of input fields (file informations, fields read) normalized wave stress into the ocean
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_tauw    ! structure of input fields (file informations, fields read) ocean stress components from wave model
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   cdn_wave            !:
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   hsw, wmp, wnum      !: 
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   wfreq               !: 
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauoc_wave          !:  
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tauw_x, tauw_y      !:  
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   tsd2d               !: 
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   div_sd              !: barotropic stokes drift divergence
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:)   ::   ut0sd, vt0sd        !: surface Stokes drift velocities at t-point
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::   usd  , vsd  , wsd   !: Stokes drift velocities at u-, v- & w-points, resp.
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_stokes( )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_stokes  ***
+      !!
+      !! ** Purpose :   compute the 3d Stokes Drift according to Breivik et al.,
+      !!                2014 (DOI: 10.1175/JPO-D-14-0020.1)
+      !!
+      !! ** Method  : - Calculate Stokes transport speed 
+      !!              - Calculate horizontal divergence 
+      !!              - Integrate the horizontal divergenze from the bottom 
+      !! ** action  
+      !!---------------------------------------------------------------------
+      INTEGER  ::   jj, ji, jk   ! dummy loop argument
+      INTEGER  ::   ik           ! local integer 
+      REAL(wp) ::  ztransp, zfac, zsp0
+      REAL(wp) ::  zdepth, zsqrt_depth,  zexp_depth, z_two_thirds, zsqrtpi !sqrt of pi
+      REAL(wp) ::  zbot_u, zbot_v, zkb_u, zkb_v, zke3_u, zke3_v, zda_u, zda_v
+      REAL(wp) ::  zstokes_psi_u_bot, zstokes_psi_v_bot
+      REAL(wp) ::  zdep_u, zdep_v, zkh_u, zkh_v
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zk_t, zk_u, zk_v, zu0_sd, zv0_sd     ! 2D workspace
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   zstokes_psi_u_top, zstokes_psi_v_top ! 2D workspace
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ze3divh                              ! 3D workspace
+      !!---------------------------------------------------------------------
+      !
+      ALLOCATE( ze3divh(jpi,jpj,jpk) )
+      ALLOCATE( zk_t(jpi,jpj), zk_u(jpi,jpj), zk_v(jpi,jpj), zu0_sd(jpi,jpj), zv0_sd(jpi,jpj) )
+      !
+      ! select parameterization for the calculation of vertical Stokes drift
+      ! exp. wave number at t-point
+      IF( ll_st_bv_li ) THEN   ! (Eq. (19) in Breivik et al. (2014) )
+         zfac = 2.0_wp * rpi / 16.0_wp
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! Stokes drift velocity estimated from Hs and Tmean
+               ztransp = zfac * hsw(ji,jj)*hsw(ji,jj) / MAX( wmp(ji,jj), 0.0000001_wp )
+               ! Stokes surface speed
+               tsd2d(ji,jj) = SQRT( ut0sd(ji,jj)*ut0sd(ji,jj) + vt0sd(ji,jj)*vt0sd(ji,jj))
+               ! Wavenumber scale
+               zk_t(ji,jj) = ABS( tsd2d(ji,jj) ) / MAX( ABS( 5.97_wp*ztransp ), 0.0000001_wp )
+            END DO
+         END DO
+         DO jj = 1, jpjm1              ! exp. wave number & Stokes drift velocity at u- & v-points
+            DO ji = 1, jpim1
+               zk_u(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji+1,jj) )
+               zk_v(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji,jj+1) )
+               !
+               zu0_sd(ji,jj) = 0.5_wp * ( ut0sd(ji,jj) + ut0sd(ji+1,jj) )
+               zv0_sd(ji,jj) = 0.5_wp * ( vt0sd(ji,jj) + vt0sd(ji,jj+1) )
+            END DO
+         END DO
+      ELSE IF( ll_st_peakfr ) THEN    ! peak wave number calculated from the peak frequency received by the wave model
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zk_t(ji,jj) = ( 2.0_wp * rpi * wfreq(ji,jj) ) * ( 2.0_wp * rpi * wfreq(ji,jj) ) / grav
+            END DO
+         END DO
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               zk_u(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji+1,jj) )
+               zk_v(ji,jj) = 0.5_wp * ( zk_t(ji,jj) + zk_t(ji,jj+1) )
+               !
+               zu0_sd(ji,jj) = 0.5_wp * ( ut0sd(ji,jj) + ut0sd(ji+1,jj) )
+               zv0_sd(ji,jj) = 0.5_wp * ( vt0sd(ji,jj) + vt0sd(ji,jj+1) )
+            END DO
+         END DO
+      ENDIF
+      !
+      !                       !==  horizontal Stokes Drift 3D velocity  ==!
+      IF( ll_st_bv2014 ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  zdep_u = 0.5_wp * ( gdept_n(ji,jj,jk) + gdept_n(ji+1,jj,jk) )
+                  zdep_v = 0.5_wp * ( gdept_n(ji,jj,jk) + gdept_n(ji,jj+1,jk) )
+                  !                          
+                  zkh_u = zk_u(ji,jj) * zdep_u     ! k * depth
+                  zkh_v = zk_v(ji,jj) * zdep_v
+                  !                                ! Depth attenuation
+                  zda_u = EXP( -2.0_wp*zkh_u ) / ( 1.0_wp + 8.0_wp*zkh_u )
+                  zda_v = EXP( -2.0_wp*zkh_v ) / ( 1.0_wp + 8.0_wp*zkh_v )
+                  !
+                  usd(ji,jj,jk) = zda_u * zu0_sd(ji,jj) * umask(ji,jj,jk)
+                  vsd(ji,jj,jk) = zda_v * zv0_sd(ji,jj) * vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE IF( ll_st_li2017 .OR. ll_st_peakfr ) THEN
+         ALLOCATE( zstokes_psi_u_top(jpi,jpj), zstokes_psi_v_top(jpi,jpj) )
+         DO jj = 1, jpjm1              ! exp. wave number & Stokes drift velocity at u- & v-points
+            DO ji = 1, jpim1
+               zstokes_psi_u_top(ji,jj) = 0._wp
+               zstokes_psi_v_top(ji,jj) = 0._wp
+            END DO
+         END DO
+         zsqrtpi = SQRT(rpi)
+         z_two_thirds = 2.0_wp / 3.0_wp
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  zbot_u = ( gdepw_n(ji,jj,jk+1) + gdepw_n(ji+1,jj,jk+1) )  ! 2 * bottom depth
+                  zbot_v = ( gdepw_n(ji,jj,jk+1) + gdepw_n(ji,jj+1,jk+1) )  ! 2 * bottom depth
+                  zkb_u  = zk_u(ji,jj) * zbot_u                             ! 2 * k * bottom depth
+                  zkb_v  = zk_v(ji,jj) * zbot_v                             ! 2 * k * bottom depth
+                  !
+                  zke3_u = MAX(1.e-8_wp, 2.0_wp * zk_u(ji,jj) * e3u_n(ji,jj,jk))     ! 2k * thickness
+                  zke3_v = MAX(1.e-8_wp, 2.0_wp * zk_v(ji,jj) * e3v_n(ji,jj,jk))     ! 2k * thickness
+
+                  ! Depth attenuation .... do u component first..
+                  zdepth      = zkb_u
+                  zsqrt_depth = SQRT(zdepth)
+                  zexp_depth  = EXP(-zdepth)
+                  zstokes_psi_u_bot = 1.0_wp - zexp_depth  &
+                       &              - z_two_thirds * ( zsqrtpi*zsqrt_depth*zdepth*ERFC(zsqrt_depth) &
+                       &              + 1.0_wp - (1.0_wp + zdepth)*zexp_depth )
+                  zda_u                    = ( zstokes_psi_u_bot - zstokes_psi_u_top(ji,jj) ) / zke3_u
+                  zstokes_psi_u_top(ji,jj) =   zstokes_psi_u_bot
+
+                  !         ... and then v component
+                  zdepth      =zkb_v
+                  zsqrt_depth = SQRT(zdepth)
+                  zexp_depth  = EXP(-zdepth)
+                  zstokes_psi_v_bot = 1.0_wp - zexp_depth  &
+                       &              - z_two_thirds * ( zsqrtpi*zsqrt_depth*zdepth*ERFC(zsqrt_depth) &
+                       &              + 1.0_wp - (1.0_wp + zdepth)*zexp_depth )
+                  zda_v                    = ( zstokes_psi_v_bot - zstokes_psi_v_top(ji,jj) ) / zke3_v
+                  zstokes_psi_v_top(ji,jj) =   zstokes_psi_v_bot
+                  !
+                  usd(ji,jj,jk) = zda_u * zu0_sd(ji,jj) * umask(ji,jj,jk)
+                  vsd(ji,jj,jk) = zda_v * zv0_sd(ji,jj) * vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         DEALLOCATE( zstokes_psi_u_top, zstokes_psi_v_top )
+      ENDIF
+
+      CALL lbc_lnk_multi( 'sbcwave', usd, 'U', -1., vsd, 'V', -1. )
+
+      !
+      !                       !==  vertical Stokes Drift 3D velocity  ==!
+      !
+      DO jk = 1, jpkm1               ! Horizontal e3*divergence
+         DO jj = 2, jpj
+            DO ji = fs_2, jpi
+               ze3divh(ji,jj,jk) = (  e2u(ji  ,jj) * e3u_n(ji  ,jj,jk) * usd(ji  ,jj,jk)    &
+                  &                 - e2u(ji-1,jj) * e3u_n(ji-1,jj,jk) * usd(ji-1,jj,jk)    &
+                  &                 + e1v(ji,jj  ) * e3v_n(ji,jj  ,jk) * vsd(ji,jj  ,jk)    &
+                  &                 - e1v(ji,jj-1) * e3v_n(ji,jj-1,jk) * vsd(ji,jj-1,jk)  ) * r1_e1e2t(ji,jj)
+            END DO
+         END DO
+      END DO
+      !
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() ) THEN
+         IF( l_Westedge )    ze3divh( 2:nbghostcells+1,:        ,:) = 0._wp      ! west
+         IF( l_Eastedge )    ze3divh( nlci-nbghostcells:nlci-1,:,:) = 0._wp      ! east
+         IF( l_Southedge )   ze3divh( :,2:nbghostcells+1        ,:) = 0._wp      ! south
+         IF( l_Northedge )   ze3divh( :,nlcj-nbghostcells:nlcj-1,:) = 0._wp      ! north
+      ENDIF
+#endif
+      !
+      CALL lbc_lnk( 'sbcwave', ze3divh, 'T', 1. )
+      !
+      IF( ln_linssh ) THEN   ;   ik = 1   ! none zero velocity through the sea surface
+      ELSE                   ;   ik = 2   ! w=0 at the surface (set one for all in sbc_wave_init)
+      ENDIF
+      DO jk = jpkm1, ik, -1          ! integrate from the bottom the hor. divergence (NB: at k=jpk w is always zero)
+         wsd(:,:,jk) = wsd(:,:,jk+1) - ze3divh(:,:,jk)
+      END DO
+      !
+      IF( ln_bdy ) THEN
+         DO jk = 1, jpkm1
+            wsd(:,:,jk) = wsd(:,:,jk) * bdytmask(:,:)
+         END DO
+      ENDIF
+      !                       !==  Horizontal divergence of barotropic Stokes transport  ==!
+      div_sd(:,:) = 0._wp
+      DO jk = 1, jpkm1                                 ! 
+        div_sd(:,:) = div_sd(:,:) + ze3divh(:,:,jk)
+      END DO
+      !
+      CALL iom_put( "ustokes",  usd  )
+      CALL iom_put( "vstokes",  vsd  )
+      CALL iom_put( "wstokes",  wsd  )
+      !
+      DEALLOCATE( ze3divh )
+      DEALLOCATE( zk_t, zk_u, zk_v, zu0_sd, zv0_sd )
+      !
+   END SUBROUTINE sbc_stokes
+
+
+   SUBROUTINE sbc_wstress( )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_wstress  ***
+      !!
+      !! ** Purpose :   Updates the ocean momentum modified by waves
+      !!
+      !! ** Method  : - Calculate u,v components of stress depending on stress
+      !!                model 
+      !!              - Calculate the stress module
+      !!              - The wind module is not modified by waves 
+      !! ** action  
+      !!---------------------------------------------------------------------
+      INTEGER  ::   jj, ji   ! dummy loop argument
+      !
+      IF( ln_tauwoc ) THEN
+         utau(:,:) = utau(:,:)*tauoc_wave(:,:)
+         vtau(:,:) = vtau(:,:)*tauoc_wave(:,:)
+         taum(:,:) = taum(:,:)*tauoc_wave(:,:)
+      ENDIF
+      !
+      IF( ln_tauw ) THEN
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               ! Stress components at u- & v-points
+               utau(ji,jj) = 0.5_wp * ( tauw_x(ji,jj) + tauw_x(ji+1,jj) )
+               vtau(ji,jj) = 0.5_wp * ( tauw_y(ji,jj) + tauw_y(ji,jj+1) )
+               !
+               ! Stress module at t points
+               taum(ji,jj) = SQRT( tauw_x(ji,jj)*tauw_x(ji,jj) + tauw_y(ji,jj)*tauw_y(ji,jj) )
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'sbcwave', utau(:,:), 'U', -1. , vtau(:,:), 'V', -1. , taum(:,:) , 'T', -1. )
+      ENDIF
+      !
+   END SUBROUTINE sbc_wstress
+
+
+   SUBROUTINE sbc_wave( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_wave  ***
+      !!
+      !! ** Purpose :   read wave parameters from wave model  in netcdf files.
+      !!
+      !! ** Method  : - Read namelist namsbc_wave
+      !!              - Read Cd_n10 fields in netcdf files 
+      !!              - Read stokes drift 2d in netcdf files 
+      !!              - Read wave number in netcdf files 
+      !!              - Compute 3d stokes drift using Breivik et al.,2014
+      !!                formulation
+      !! ** action  
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_cdgw .AND. .NOT. cpl_wdrag ) THEN     !==  Neutral drag coefficient  ==!
+         CALL fld_read( kt, nn_fsbc, sf_cd )             ! read from external forcing
+         cdn_wave(:,:) = sf_cd(1)%fnow(:,:,1) * tmask(:,:,1)
+      ENDIF
+
+      IF( ln_tauwoc .AND. .NOT. cpl_tauwoc ) THEN  !==  Wave induced stress  ==!
+         CALL fld_read( kt, nn_fsbc, sf_tauwoc )         ! read wave norm stress from external forcing
+         tauoc_wave(:,:) = sf_tauwoc(1)%fnow(:,:,1) * tmask(:,:,1)
+      ENDIF
+
+      IF( ln_tauw .AND. .NOT. cpl_tauw ) THEN      !==  Wave induced stress  ==!
+         CALL fld_read( kt, nn_fsbc, sf_tauw )           ! read ocean stress components from external forcing (T grid)
+         tauw_x(:,:) = sf_tauw(1)%fnow(:,:,1) * tmask(:,:,1)
+         tauw_y(:,:) = sf_tauw(2)%fnow(:,:,1) * tmask(:,:,1)
+      ENDIF
+
+      IF( ln_sdw )  THEN                           !==  Computation of the 3d Stokes Drift  ==! 
+         !
+         IF( jpfld > 0 ) THEN                            ! Read from file only if the field is not coupled
+            CALL fld_read( kt, nn_fsbc, sf_sd )          ! read wave parameters from external forcing
+            IF( jp_hsw > 0 )   hsw  (:,:) = sf_sd(jp_hsw)%fnow(:,:,1) * tmask(:,:,1)  ! significant wave height
+            IF( jp_wmp > 0 )   wmp  (:,:) = sf_sd(jp_wmp)%fnow(:,:,1) * tmask(:,:,1)  ! wave mean period
+            IF( jp_wfr > 0 )   wfreq(:,:) = sf_sd(jp_wfr)%fnow(:,:,1) * tmask(:,:,1)  ! Peak wave frequency
+            IF( jp_usd > 0 )   ut0sd(:,:) = sf_sd(jp_usd)%fnow(:,:,1) * tmask(:,:,1)  ! 2D zonal Stokes Drift at T point
+            IF( jp_vsd > 0 )   vt0sd(:,:) = sf_sd(jp_vsd)%fnow(:,:,1) * tmask(:,:,1)  ! 2D meridional Stokes Drift at T point
+         ENDIF
+         !
+         ! Read also wave number if needed, so that it is available in coupling routines
+         IF( ln_zdfswm .AND. .NOT.cpl_wnum ) THEN
+            CALL fld_read( kt, nn_fsbc, sf_wn )          ! read wave parameters from external forcing
+            wnum(:,:) = sf_wn(1)%fnow(:,:,1) * tmask(:,:,1)
+         ENDIF
+           
+         ! Calculate only if required fields have been read
+         ! In coupled wave model-NEMO case the call is done after coupling
+         !
+         IF( ( ll_st_bv_li   .AND. jp_hsw>0 .AND. jp_wmp>0 .AND. jp_usd>0 .AND. jp_vsd>0 ) .OR. &
+           & ( ll_st_peakfr  .AND. jp_wfr>0 .AND. jp_usd>0 .AND. jp_vsd>0                ) ) CALL sbc_stokes()
+         !
+      ENDIF
+      !
+   END SUBROUTINE sbc_wave
+
+
+   SUBROUTINE sbc_wave_init
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_wave_init  ***
+      !!
+      !! ** Purpose :   read wave parameters from wave model  in netcdf files.
+      !!
+      !! ** Method  : - Read namelist namsbc_wave
+      !!              - Read Cd_n10 fields in netcdf files 
+      !!              - Read stokes drift 2d in netcdf files 
+      !!              - Read wave number in netcdf files 
+      !!              - Compute 3d stokes drift using Breivik et al.,2014
+      !!                formulation
+      !! ** action  
+      !!---------------------------------------------------------------------
+      INTEGER ::   ierror, ios   ! local integer
+      INTEGER ::   ifpr
+      !!
+      CHARACTER(len=100)     ::  cn_dir                            ! Root directory for location of drag coefficient files
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) ::   slf_i, slf_j     ! array of namelist informations on the fields to read
+      TYPE(FLD_N)            ::  sn_cdg, sn_usd, sn_vsd,  &
+                             &   sn_hsw, sn_wmp, sn_wfr, sn_wnum, &
+                             &   sn_tauwoc, sn_tauwx, sn_tauwy     ! informations about the fields to be read
+      !
+      NAMELIST/namsbc_wave/  sn_cdg, cn_dir, sn_usd, sn_vsd, sn_hsw, sn_wmp, sn_wfr, &
+                          &  sn_wnum, sn_tauwoc, sn_tauwx, sn_tauwy
+      !!---------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namsbc_wave in reference namelist : File for drag coeff. from wave model
+      READ  ( numnam_ref, namsbc_wave, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_wave in reference namelist' )
+         
+      REWIND( numnam_cfg )              ! Namelist namsbc_wave in configuration namelist : File for drag coeff. from wave model
+      READ  ( numnam_cfg, namsbc_wave, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_wave in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_wave )
+      !
+      IF( ln_cdgw ) THEN
+         IF( .NOT. cpl_wdrag ) THEN
+            ALLOCATE( sf_cd(1), STAT=ierror )               !* allocate and fill sf_wave with sn_cdg
+            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+            !
+                                   ALLOCATE( sf_cd(1)%fnow(jpi,jpj,1)   )
+            IF( sn_cdg%ln_tint )   ALLOCATE( sf_cd(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_cd, (/ sn_cdg /), cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
+         ENDIF
+         ALLOCATE( cdn_wave(jpi,jpj) )
+      ENDIF
+
+      IF( ln_tauwoc ) THEN
+         IF( .NOT. cpl_tauwoc ) THEN
+            ALLOCATE( sf_tauwoc(1), STAT=ierror )           !* allocate and fill sf_wave with sn_tauwoc
+            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+            !
+                                     ALLOCATE( sf_tauwoc(1)%fnow(jpi,jpj,1)   )
+            IF( sn_tauwoc%ln_tint )  ALLOCATE( sf_tauwoc(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_tauwoc, (/ sn_tauwoc /), cn_dir, 'sbc_wave_init', 'Wave module', 'namsbc_wave' )
+         ENDIF
+         ALLOCATE( tauoc_wave(jpi,jpj) )
+      ENDIF
+
+      IF( ln_tauw ) THEN
+         IF( .NOT. cpl_tauw ) THEN
+            ALLOCATE( sf_tauw(2), STAT=ierror )           !* allocate and fill sf_wave with sn_tauwx/y
+            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_tauw structure' )
+            !
+            ALLOCATE( slf_j(2) )
+            slf_j(1) = sn_tauwx
+            slf_j(2) = sn_tauwy
+                                    ALLOCATE( sf_tauw(1)%fnow(jpi,jpj,1)   )
+                                    ALLOCATE( sf_tauw(2)%fnow(jpi,jpj,1)   )
+            IF( slf_j(1)%ln_tint )  ALLOCATE( sf_tauw(1)%fdta(jpi,jpj,1,2) )
+            IF( slf_j(2)%ln_tint )  ALLOCATE( sf_tauw(2)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_tauw, (/ slf_j /), cn_dir, 'sbc_wave_init', 'read wave input', 'namsbc_wave' )
+         ENDIF
+         ALLOCATE( tauw_x(jpi,jpj) )
+         ALLOCATE( tauw_y(jpi,jpj) )
+      ENDIF
+
+      IF( ln_sdw ) THEN   ! Find out how many fields have to be read from file if not coupled
+         jpfld=0
+         jp_usd=0   ;   jp_vsd=0   ;   jp_hsw=0   ;   jp_wmp=0   ;   jp_wfr=0
+         IF( .NOT. cpl_sdrftx ) THEN
+            jpfld  = jpfld + 1
+            jp_usd = jpfld
+         ENDIF
+         IF( .NOT. cpl_sdrfty ) THEN
+            jpfld  = jpfld + 1
+            jp_vsd = jpfld
+         ENDIF
+         IF( .NOT. cpl_hsig  .AND. ll_st_bv_li  ) THEN
+            jpfld  = jpfld + 1
+            jp_hsw = jpfld
+         ENDIF
+         IF( .NOT. cpl_wper  .AND. ll_st_bv_li  ) THEN
+            jpfld  = jpfld + 1
+            jp_wmp = jpfld
+         ENDIF
+         IF( .NOT. cpl_wfreq .AND. ll_st_peakfr ) THEN
+            jpfld  = jpfld + 1
+            jp_wfr = jpfld
+         ENDIF
+
+         ! Read from file only the non-coupled fields 
+         IF( jpfld > 0 ) THEN
+            ALLOCATE( slf_i(jpfld) )
+            IF( jp_usd > 0 )   slf_i(jp_usd) = sn_usd
+            IF( jp_vsd > 0 )   slf_i(jp_vsd) = sn_vsd
+            IF( jp_hsw > 0 )   slf_i(jp_hsw) = sn_hsw
+            IF( jp_wmp > 0 )   slf_i(jp_wmp) = sn_wmp
+            IF( jp_wfr > 0 )   slf_i(jp_wfr) = sn_wfr
+
+            ALLOCATE( sf_sd(jpfld), STAT=ierror )   !* allocate and fill sf_sd with stokes drift
+            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable to allocate sf_wave structure' )
+            !
+            DO ifpr= 1, jpfld
+               ALLOCATE( sf_sd(ifpr)%fnow(jpi,jpj,1) )
+               IF( slf_i(ifpr)%ln_tint )   ALLOCATE( sf_sd(ifpr)%fdta(jpi,jpj,1,2) )
+            END DO
+            !
+            CALL fld_fill( sf_sd, slf_i, cn_dir, 'sbc_wave_init', 'Wave module ', 'namsbc_wave' )
+         ENDIF
+         ALLOCATE( usd  (jpi,jpj,jpk), vsd  (jpi,jpj,jpk), wsd(jpi,jpj,jpk) )
+         ALLOCATE( hsw  (jpi,jpj)    , wmp  (jpi,jpj)     )
+         ALLOCATE( wfreq(jpi,jpj) )
+         ALLOCATE( ut0sd(jpi,jpj)    , vt0sd(jpi,jpj)     )
+         ALLOCATE( div_sd(jpi,jpj) )
+         ALLOCATE( tsd2d (jpi,jpj) )
+
+         ut0sd(:,:) = 0._wp
+         vt0sd(:,:) = 0._wp
+         hsw(:,:) = 0._wp
+         wmp(:,:) = 0._wp
+
+         usd(:,:,:) = 0._wp
+         vsd(:,:,:) = 0._wp
+         wsd(:,:,:) = 0._wp
+         ! Wave number needed only if ln_zdfswm=T
+         IF( .NOT. cpl_wnum ) THEN
+            ALLOCATE( sf_wn(1), STAT=ierror )           !* allocate and fill sf_wave with sn_wnum
+            IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'sbc_wave_init: unable toallocate sf_wave structure' )
+                                   ALLOCATE( sf_wn(1)%fnow(jpi,jpj,1)   )
+            IF( sn_wnum%ln_tint )  ALLOCATE( sf_wn(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_wn, (/ sn_wnum /), cn_dir, 'sbc_wave', 'Wave module', 'namsbc_wave' )
+         ENDIF
+         ALLOCATE( wnum(jpi,jpj) )
+      ENDIF
+      !
+   END SUBROUTINE sbc_wave_init
+
+   !!======================================================================
+END MODULE sbcwave
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide.h90	(revision 14097)
@@ -0,0 +1,29 @@
+   !!----------------------------------------------------------------------
+   !! History :  3.2  !  2007  (O. Le Galloudec)  Original code
+   !!----------------------------------------------------------------------
+
+   !             !! name_tide , equitide , nutide , nt , ns , nh , np , np1 , shift , nksi , nnu0 , nnu1 , nnu2 , R , formula !!
+   !             !!           !          !        !    !    !    !    !     !       !      !      !      !      !   !         !!
+   Wave( 1) = tide(  'M2'     , 0.242297 ,    2   ,  2 , -2 ,  2 ,  0 ,  0  ,    0  ,  2   , -2   ,  0   ,  0   , 0 ,    78   )
+   Wave( 2) = tide(  'N2'     , 0.046313 ,    2   ,  2 , -3 ,  2 ,  1 ,  0  ,    0  ,  2   , -2   ,  0   ,  0   , 0 ,    78   )
+   Wave( 3) = tide( '2N2'     , 0.006184 ,    2   ,  2 , -4 ,  2 ,  2 ,  0  ,    0  ,  2   , -2   ,  0   ,  0   , 0 ,    78   )
+   Wave( 4) = tide(  'S2'     , 0.113572 ,    2   ,  2 ,  0 ,  0 ,  0 ,  0  ,    0  ,  0   ,  0   ,  0   ,  0   , 0 ,     0   )
+   Wave( 5) = tide(  'K2'     , 0.030875 ,    2   ,  2 ,  0 ,  2 ,  0 ,  0  ,    0  ,  0   ,  0   ,  0   , -2   , 0 ,   235   )
+   !              !           !          !        !    !    !    !    !     !       !      !      !      !      !   !         !
+   Wave( 6) = tide(  'K1'     , 0.142408 ,    1   ,  1 ,  0 ,  1 ,  0 ,  0  ,  -90  ,  0   ,  0   , -1   ,  0   , 0 ,   227   )
+   Wave( 7) = tide(  'O1'     , 0.101266 ,    1   ,  1 , -2 ,  1 ,  0 ,  0  ,  +90  ,  2   , -1   ,  0   ,  0   , 0 ,    75   )
+   Wave( 8) = tide(  'Q1'     , 0.019387 ,    1   ,  1 , -3 ,  1 ,  1 ,  0  ,  +90  ,  2   , -1   ,  0   ,  0   , 0 ,    75   )
+   Wave( 9) = tide(  'P1'     , 0.047129 ,    1   ,  1 ,  0 , -1 ,  0 ,  0  ,  +90  ,  0   ,  0   ,  0   ,  0   , 0 ,    0    )
+   !              !           !          !        !    !    !    !    !     !       !      !      !      !      !   !         !
+   Wave(10) = tide(  'M4'     , 0.000000 ,    4   ,  4 , -4 ,  4 ,  0 ,  0  ,    0  ,  4   , -4   ,  0   ,  0   , 0 ,    1    )
+   !              !           !          !        !    !    !    !    !     !       !      !      !      !      !   !         !
+   Wave(11) = tide(  'Mf'     , 0.042017 ,    0   ,  0 ,  2 ,  0 ,  0 ,  0  ,    0  , -2   ,  0   ,  0   ,  0   , 0 ,   74    )
+   Wave(12) = tide(  'Mm'     , 0.022191 ,    0   ,  0 ,  1 ,  0 , -1 ,  0  ,    0  ,  0   ,  0   ,  0   ,  0   , 0 ,   73    )
+   Wave(13) = tide(  'Msqm'   , 0.000667 ,    0   ,  0 ,  4 , -2 ,  0 ,  0  ,    0  , -2   ,  0   ,  0   ,  0   , 0 ,   74    )
+   Wave(14) = tide(  'Mtm'    , 0.008049 ,    0   ,  0 ,  3 ,  0 , -1 ,  0  ,    0  , -2   ,  0   ,  0   ,  0   , 0 ,   74    )
+   !              !           !          !        !    !    !    !    !     !       !      !      !      !      !   !         !
+   Wave(15) = tide(  'S1'     , 0.000000 ,    1   ,  1 ,  0 ,  0 ,  0 ,  0  ,    0  ,  0   ,  0   ,  0   ,  0   , 0 ,    0    )   
+   Wave(16) = tide(  'MU2'    , 0.005841 ,    2   ,  2 , -4 ,  4 ,  0 ,  0  ,    0  ,  2   , -2   ,  0   ,  0   , 0 ,   78    )
+   Wave(17) = tide(  'NU2'    , 0.009094 ,    2   ,  2 , -3 ,  4 , -1 ,  0  ,    0  ,  2   , -2   ,  0   ,  0   , 0 ,   78    ) 
+   Wave(18) = tide(  'L2'     , 0.006694 ,    2   ,  2 , -1 ,  2 , -1 ,  0  , +180  ,  2   , -2   ,  0   ,  0   , 0 ,  215    )
+   Wave(19) = tide(  'T2'     , 0.006614 ,    2   ,  2 ,  0 , -1 ,  0 ,  1  ,    0  ,  0   ,  0   ,  0   ,  0   , 0 ,    0    )
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide_mod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide_mod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tide_mod.F90	(revision 14097)
@@ -0,0 +1,411 @@
+MODULE tide_mod
+   !!======================================================================
+   !!                       ***  MODULE  tide_mod  ***
+   !! Compute nodal modulations corrections and pulsations
+   !!======================================================================
+   !! History :  1.0  !  2007  (O. Le Galloudec)  Original code
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constant
+   USE daymod         ! calendar
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tide_harmo       ! called by tideini and diaharm modules
+   PUBLIC   tide_init_Wave   ! called by tideini and diaharm modules
+
+   INTEGER, PUBLIC, PARAMETER ::   jpmax_harmo = 19   !: maximum number of harmonic
+
+   TYPE, PUBLIC ::    tide
+      CHARACTER(LEN=4) ::   cname_tide
+      REAL(wp)         ::   equitide
+      INTEGER          ::   nutide
+      INTEGER          ::   nt, ns, nh, np, np1, shift
+      INTEGER          ::   nksi, nnu0, nnu1, nnu2, R
+      INTEGER          ::   nformula
+   END TYPE tide
+
+   TYPE(tide), PUBLIC, DIMENSION(jpmax_harmo) ::   Wave   !:
+
+   REAL(wp) ::   sh_T, sh_s, sh_h, sh_p, sh_p1             ! astronomic angles
+   REAL(wp) ::   sh_xi, sh_nu, sh_nuprim, sh_nusec, sh_R   !
+   REAL(wp) ::   sh_I, sh_x1ra, sh_N                       !
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tide_init_Wave
+#     include "tide.h90"
+   END SUBROUTINE tide_init_Wave
+
+
+   SUBROUTINE tide_harmo( pomega, pvt, put , pcor, ktide ,kc)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(kc), INTENT(in ) ::   ktide            ! Indice of tidal constituents
+      INTEGER                , INTENT(in ) ::   kc               ! Total number of tidal constituents
+      REAL(wp), DIMENSION(kc), INTENT(out) ::   pomega           ! pulsation in radians/s
+      REAL(wp), DIMENSION(kc), INTENT(out) ::   pvt, put, pcor   !
+      !!----------------------------------------------------------------------
+      !
+      CALL astronomic_angle
+      CALL tide_pulse( pomega, ktide ,kc )
+      CALL tide_vuf  ( pvt, put, pcor, ktide ,kc )
+      !
+   END SUBROUTINE tide_harmo
+
+
+   SUBROUTINE astronomic_angle
+      !!----------------------------------------------------------------------
+      !!  tj is time elapsed since 1st January 1900, 0 hour, counted in julian
+      !!  century (e.g. time in days divide by 36525)
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   cosI, p, q, t2, t4, sin2I, s2, tgI2, P1, sh_tgn2, at1, at2
+      REAL(wp) ::   zqy , zsy, zday, zdj, zhfrac
+      !!----------------------------------------------------------------------
+      !
+      zqy = AINT( (nyear-1901.)/4. )
+      zsy = nyear - 1900.
+      !
+      zdj  = dayjul( nyear, nmonth, nday )
+      zday = zdj + zqy - 1.
+      !
+      zhfrac = nsec_day / 3600.
+      !
+      !----------------------------------------------------------------------
+      !  Sh_n Longitude of ascending lunar node
+      !----------------------------------------------------------------------
+      sh_N=(259.1560564-19.328185764*zsy-.0529539336*zday-.0022064139*zhfrac)*rad
+      !----------------------------------------------------------------------
+      ! T mean solar angle (Greenwhich time)
+      !----------------------------------------------------------------------
+      sh_T=(180.+zhfrac*(360./24.))*rad
+      !----------------------------------------------------------------------
+      ! h mean solar Longitude
+      !----------------------------------------------------------------------
+      sh_h=(280.1895014-.238724988*zsy+.9856473288*zday+.0410686387*zhfrac)*rad
+      !----------------------------------------------------------------------
+      ! s mean lunar Longitude
+      !----------------------------------------------------------------------
+      sh_s=(277.0256206+129.38482032*zsy+13.176396768*zday+.549016532*zhfrac)*rad
+      !----------------------------------------------------------------------
+      ! p1 Longitude of solar perigee
+      !----------------------------------------------------------------------
+      sh_p1=(281.2208569+.01717836*zsy+.000047064*zday+.000001961*zhfrac)*rad
+      !----------------------------------------------------------------------
+      ! p Longitude of lunar perigee
+      !----------------------------------------------------------------------
+      sh_p=(334.3837214+40.66246584*zsy+.111404016*zday+.004641834*zhfrac)*rad
+
+      sh_N = MOD( sh_N ,2*rpi )
+      sh_s = MOD( sh_s ,2*rpi )
+      sh_h = MOD( sh_h, 2*rpi )
+      sh_p = MOD( sh_p, 2*rpi )
+      sh_p1= MOD( sh_p1,2*rpi )
+
+      cosI = 0.913694997 -0.035692561 *cos(sh_N)
+
+      sh_I = ACOS( cosI )
+
+      sin2I   = sin(sh_I)
+      sh_tgn2 = tan(sh_N/2.0)
+
+      at1=atan(1.01883*sh_tgn2)
+      at2=atan(0.64412*sh_tgn2)
+
+      sh_xi=-at1-at2+sh_N
+
+      IF( sh_N > rpi )   sh_xi=sh_xi-2.0*rpi
+
+      sh_nu = at1 - at2
+
+      !----------------------------------------------------------------------
+      ! For constituents l2 k1 k2
+      !----------------------------------------------------------------------
+
+      tgI2 = tan(sh_I/2.0)
+      P1   = sh_p-sh_xi
+
+      t2 = tgI2*tgI2
+      t4 = t2*t2
+      sh_x1ra = sqrt( 1.0-12.0*t2*cos(2.0*P1)+36.0*t4 )
+
+      p = sin(2.0*P1)
+      q = 1.0/(6.0*t2)-cos(2.0*P1)
+      sh_R = atan(p/q)
+
+      p = sin(2.0*sh_I)*sin(sh_nu)
+      q = sin(2.0*sh_I)*cos(sh_nu)+0.3347
+      sh_nuprim = atan(p/q)
+
+      s2 = sin(sh_I)*sin(sh_I)
+      p  = s2*sin(2.0*sh_nu)
+      q  = s2*cos(2.0*sh_nu)+0.0727
+      sh_nusec = 0.5*atan(p/q)
+      !
+   END SUBROUTINE astronomic_angle
+
+
+   SUBROUTINE tide_pulse( pomega, ktide ,kc )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE tide_pulse  ***
+      !!                      
+      !! ** Purpose : Compute tidal frequencies
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in ) ::   kc       ! Total number of tidal constituents
+      INTEGER , DIMENSION(kc), INTENT(in ) ::   ktide    ! Indice of tidal constituents
+      REAL(wp), DIMENSION(kc), INTENT(out) ::   pomega   ! pulsation in radians/s
+      !
+      INTEGER  ::   jh
+      REAL(wp) ::   zscale
+      REAL(wp) ::   zomega_T =  13149000.0_wp
+      REAL(wp) ::   zomega_s =    481267.892_wp
+      REAL(wp) ::   zomega_h =     36000.76892_wp
+      REAL(wp) ::   zomega_p =      4069.0322056_wp
+      REAL(wp) ::   zomega_n =      1934.1423972_wp
+      REAL(wp) ::   zomega_p1=         1.719175_wp
+      !!----------------------------------------------------------------------
+      !
+      zscale =  rad / ( 36525._wp * 86400._wp ) 
+      !
+      DO jh = 1, kc
+         pomega(jh) = (  zomega_T * Wave( ktide(jh) )%nT   &
+            &          + zomega_s * Wave( ktide(jh) )%ns   &
+            &          + zomega_h * Wave( ktide(jh) )%nh   &
+            &          + zomega_p * Wave( ktide(jh) )%np   &
+            &          + zomega_p1* Wave( ktide(jh) )%np1  ) * zscale
+      END DO
+      !
+   END SUBROUTINE tide_pulse
+
+
+   SUBROUTINE tide_vuf( pvt, put, pcor, ktide ,kc )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE tide_vuf  ***
+      !!                      
+      !! ** Purpose : Compute nodal modulation corrections
+      !!
+      !! ** Outputs : vt: Phase of tidal potential relative to Greenwich (radians)
+      !!              ut: Phase correction u due to nodal motion (radians)
+      !!              ft: Nodal correction factor
+      !!----------------------------------------------------------------------
+      INTEGER                , INTENT(in ) ::   kc               ! Total number of tidal constituents
+      INTEGER , DIMENSION(kc), INTENT(in ) ::   ktide            ! Indice of tidal constituents
+      REAL(wp), DIMENSION(kc), INTENT(out) ::   pvt, put, pcor   !
+      !
+      INTEGER ::   jh   ! dummy loop index
+      !!----------------------------------------------------------------------
+      !
+      DO jh = 1, kc
+         !  Phase of the tidal potential relative to the Greenwhich 
+         !  meridian (e.g. the position of the fictuous celestial body). Units are radian:
+         pvt(jh) = sh_T * Wave( ktide(jh) )%nT    &
+            &    + sh_s * Wave( ktide(jh) )%ns    &
+            &    + sh_h * Wave( ktide(jh) )%nh    &
+            &    + sh_p * Wave( ktide(jh) )%np    &
+            &    + sh_p1* Wave( ktide(jh) )%np1   &
+            &    +        Wave( ktide(jh) )%shift * rad
+         !
+         !  Phase correction u due to nodal motion. Units are radian:
+         put(jh) = sh_xi     * Wave( ktide(jh) )%nksi   &
+            &    + sh_nu     * Wave( ktide(jh) )%nnu0   &
+            &    + sh_nuprim * Wave( ktide(jh) )%nnu1   &
+            &    + sh_nusec  * Wave( ktide(jh) )%nnu2   &
+            &    + sh_R      * Wave( ktide(jh) )%R
+
+         !  Nodal correction factor:
+         pcor(jh) = nodal_factort( Wave( ktide(jh) )%nformula )
+      END DO
+      !
+   END SUBROUTINE tide_vuf
+
+
+   RECURSIVE FUNCTION nodal_factort( kformula ) RESULT( zf )
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kformula
+      !
+      REAL(wp) :: zf
+      REAL(wp) :: zs, zf1, zf2
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE( kformula )
+      !
+      CASE( 0 )                  !==  formule 0, solar waves
+         zf = 1.0
+         !
+      CASE( 1 )                  !==  formule 1, compound waves (78 x 78)
+         zf=nodal_factort(78)
+         zf = zf * zf
+         !
+      CASE ( 2 )                 !==  formule 2, compound waves (78 x 0)  ===  (78) 
+       zf1= nodal_factort(78)
+       zf = nodal_factort( 0)
+       zf = zf1 * zf
+       !
+      CASE ( 4 )                 !==  formule 4,  compound waves (78 x 235) 
+         zf1 = nodal_factort( 78)
+         zf  = nodal_factort(235)
+         zf  = zf1 * zf
+         !
+      CASE ( 5 )                 !==  formule 5,  compound waves (78 *78 x 235)
+         zf1 = nodal_factort( 78)
+         zf  = nodal_factort(235)
+         zf  = zf * zf1 * zf1
+         !
+      CASE ( 6 )                 !==  formule 6,  compound waves (78 *78 x 0)
+         zf1 = nodal_factort(78)
+         zf  = nodal_factort( 0)
+         zf  = zf * zf1 * zf1 
+         !
+      CASE( 7 )                  !==  formule 7, compound waves (75 x 75)
+         zf = nodal_factort(75)
+         zf = zf * zf
+         !
+      CASE( 8 )                  !==  formule 8,  compound waves (78 x 0 x 235)
+         zf  = nodal_factort( 78)
+         zf1 = nodal_factort(  0)
+         zf2 = nodal_factort(235)
+         zf  = zf * zf1 * zf2
+         !
+      CASE( 9 )                  !==  formule 9,  compound waves (78 x 0 x 227)
+         zf  = nodal_factort( 78)
+         zf1 = nodal_factort(  0)
+         zf2 = nodal_factort(227)
+         zf  = zf * zf1 * zf2
+         !
+      CASE( 10 )                 !==  formule 10,  compound waves (78 x 227)
+         zf  = nodal_factort( 78)
+         zf1 = nodal_factort(227)
+         zf  = zf * zf1
+         !
+      CASE( 11 )                 !==  formule 11,  compound waves (75 x 0)
+!!gm bug???? zf 2 fois !
+         zf = nodal_factort(75)
+         zf1 = nodal_factort( 0)
+         zf = zf * zf1
+         !
+      CASE( 12 )                 !==  formule 12,  compound waves (78 x 78 x 78 x 0) 
+         zf1 = nodal_factort(78)
+         zf  = nodal_factort( 0)
+         zf  = zf * zf1 * zf1 * zf1
+         !
+      CASE( 13 )                 !==  formule 13, compound waves (78 x 75)
+         zf1 = nodal_factort(78)
+         zf  = nodal_factort(75)
+         zf  = zf * zf1
+         !
+      CASE( 14 )                 !==  formule 14, compound waves (235 x 0)  ===  (235)
+         zf  = nodal_factort(235)
+         zf1 = nodal_factort(  0)
+         zf  = zf * zf1
+         !
+      CASE( 15 )                 !==  formule 15, compound waves (235 x 75) 
+         zf  = nodal_factort(235)
+         zf1 = nodal_factort( 75)
+         zf  = zf * zf1
+         !
+      CASE( 16 )                 !==  formule 16, compound waves (78 x 0 x 0)  ===  (78)
+         zf  = nodal_factort(78)
+         zf1 = nodal_factort( 0)
+         zf  = zf * zf1 * zf1
+         !
+      CASE( 17 )                 !==  formule 17,  compound waves (227 x 0) 
+         zf1 = nodal_factort(227)
+         zf  = nodal_factort(  0)
+         zf  = zf * zf1
+         !
+      CASE( 18 )                 !==  formule 18,  compound waves (78 x 78 x 78 )
+         zf1 = nodal_factort(78)
+         zf  = zf1 * zf1 * zf1
+         !
+      CASE( 19 )                 !==  formule 19, compound waves (78 x 0 x 0 x 0)  ===  (78)
+!!gm bug2 ==>>>   here identical to formule 16,  a third multiplication by zf1 is missing
+         zf  = nodal_factort(78)
+         zf1 = nodal_factort( 0)
+         zf = zf * zf1 * zf1
+         !
+      CASE( 73 )                 !==  formule 73
+         zs = sin(sh_I)
+         zf = (2./3.-zs*zs)/0.5021
+         !
+      CASE( 74 )                 !==  formule 74
+         zs = sin(sh_I)
+         zf = zs * zs / 0.1578
+         !
+      CASE( 75 )                 !==  formule 75
+         zs = cos(sh_I/2)
+         zf = sin(sh_I) * zs * zs / 0.3800
+         !
+      CASE( 76 )                 !==  formule 76
+         zf = sin(2*sh_I) / 0.7214
+         !
+      CASE( 77 )                 !==  formule 77
+         zs = sin(sh_I/2)
+         zf = sin(sh_I) * zs * zs / 0.0164
+         !
+      CASE( 78 )                 !==  formule 78
+         zs = cos(sh_I/2)
+         zf = zs * zs * zs * zs / 0.9154
+         !
+      CASE( 79 )                 !==  formule 79
+         zs = sin(sh_I)
+         zf = zs * zs / 0.1565
+         !
+      CASE( 144 )                !==  formule 144
+         zs = sin(sh_I/2)
+         zf = ( 1-10*zs*zs+15*zs*zs*zs*zs ) * cos(sh_I/2) / 0.5873
+         !
+      CASE( 149 )                !==  formule 149
+         zs = cos(sh_I/2)
+         zf = zs*zs*zs*zs*zs*zs / 0.8758
+         !
+      CASE( 215 )                !==  formule 215
+         zs = cos(sh_I/2)
+         zf = zs*zs*zs*zs / 0.9154 * sh_x1ra
+         !
+      CASE( 227 )                !==  formule 227 
+         zs = sin(2*sh_I)
+         zf = sqrt( 0.8965*zs*zs+0.6001*zs*cos (sh_nu)+0.1006 )
+         !
+      CASE ( 235 )               !==  formule 235 
+         zs = sin(sh_I)
+         zf = sqrt( 19.0444*zs*zs*zs*zs + 2.7702*zs*zs*cos(2*sh_nu) + .0981 )
+         !
+      END SELECT
+      !
+   END FUNCTION nodal_factort
+
+
+   FUNCTION dayjul( kyr, kmonth, kday )
+      !!----------------------------------------------------------------------
+      !!  *** THIS ROUTINE COMPUTES THE JULIAN DAY (AS A REAL VARIABLE)
+      !!----------------------------------------------------------------------
+      INTEGER,INTENT(in) ::   kyr, kmonth, kday
+      !
+      INTEGER,DIMENSION(12) ::  idayt, idays
+      INTEGER  ::   inc, ji
+      REAL(wp) ::   dayjul, zyq
+      !
+      DATA idayt/0.,31.,59.,90.,120.,151.,181.,212.,243.,273.,304.,334./
+      !!----------------------------------------------------------------------
+      !
+      idays(1) = 0.
+      idays(2) = 31.
+      inc = 0.
+      zyq = MOD( kyr-1900. , 4. )
+      IF( zyq == 0.)   inc = 1.
+      DO ji = 3, 12
+         idays(ji)=idayt(ji)+inc
+      END DO
+      dayjul = idays(kmonth) + kday
+      !
+   END FUNCTION dayjul
+
+   !!======================================================================
+END MODULE tide_mod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tideini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tideini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/tideini.F90	(revision 14097)
@@ -0,0 +1,134 @@
+MODULE tideini
+   !!======================================================================
+   !!                       ***  MODULE  tideini  ***
+   !! Initialization of tidal forcing
+   !!======================================================================
+   !! History :  1.0  !  2007  (O. Le Galloudec)  Original code
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE daymod         ! calendar
+   USE tide_mod       ! 
+   !
+   USE in_out_manager ! I/O units
+   USE iom            ! xIOs server
+   USE ioipsl         ! NetCDF IPSL library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PUBLIC
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   omega_tide   !:
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   v0tide       !:
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   utide        !:
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:) ::   ftide        !:
+
+   LOGICAL , PUBLIC ::   ln_tide         !:
+   LOGICAL , PUBLIC ::   ln_tide_pot     !:
+   LOGICAL , PUBLIC ::   ln_read_load    !:
+   LOGICAL , PUBLIC ::   ln_scal_load    !:
+   LOGICAL , PUBLIC ::   ln_tide_ramp    !:
+   INTEGER , PUBLIC ::   nb_harmo        !:
+   INTEGER , PUBLIC ::   kt_tide         !:
+   REAL(wp), PUBLIC ::   rdttideramp     !:
+   REAL(wp), PUBLIC ::   rn_scal_load    !:
+   CHARACTER(lc), PUBLIC ::   cn_tide_load   !: 
+
+   INTEGER , PUBLIC, ALLOCATABLE, DIMENSION(:) ::   ntide   !:
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE tide_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tide_init  ***
+      !!----------------------------------------------------------------------      
+      INTEGER  :: ji, jk
+      CHARACTER(LEN=4), DIMENSION(jpmax_harmo) :: clname
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      !
+      NAMELIST/nam_tide/ln_tide, ln_tide_pot, ln_scal_load, ln_read_load, cn_tide_load, &
+                  &     ln_tide_ramp, rn_scal_load, rdttideramp, clname
+      !!----------------------------------------------------------------------
+      !
+      ! Read Namelist nam_tide
+      REWIND( numnam_ref )              ! Namelist nam_tide in reference namelist : Tides
+      READ  ( numnam_ref, nam_tide, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_tide in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist nam_tide in configuration namelist : Tides
+      READ  ( numnam_cfg, nam_tide, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nam_tide in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_tide )
+      !
+      IF( ln_tide ) THEN
+         IF (lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'tide_init : Initialization of the tidal components'
+            WRITE(numout,*) '~~~~~~~~~ '
+            WRITE(numout,*) '   Namelist nam_tide'
+            WRITE(numout,*) '      Use tidal components                       ln_tide      = ', ln_tide
+            WRITE(numout,*) '         Apply astronomical potential            ln_tide_pot  = ', ln_tide_pot
+            WRITE(numout,*) '         Use scalar approx. for load potential   ln_scal_load = ', ln_scal_load
+            WRITE(numout,*) '         Read load potential from file           ln_read_load = ', ln_read_load
+            WRITE(numout,*) '         Apply ramp on tides at startup          ln_tide_ramp = ', ln_tide_ramp
+            WRITE(numout,*) '         Fraction of SSH used in scal. approx.   rn_scal_load = ', rn_scal_load
+            WRITE(numout,*) '         Duration (days) of ramp                 rdttideramp  = ', rdttideramp
+         ENDIF
+      ELSE
+         rn_scal_load = 0._wp 
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tide_init : tidal components not used (ln_tide = F)'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~ '
+         RETURN
+      ENDIF
+      !
+      CALL tide_init_Wave
+      !
+      nb_harmo=0
+      DO jk = 1, jpmax_harmo
+         DO ji = 1,jpmax_harmo
+            IF( TRIM(clname(jk)) == Wave(ji)%cname_tide )   nb_harmo = nb_harmo + 1
+         END DO
+      END DO
+      !       
+      ! Ensure that tidal components have been set in namelist_cfg
+      IF( nb_harmo == 0 )   CALL ctl_stop( 'tide_init : No tidal components set in nam_tide' )
+      !
+      IF( ln_read_load.AND.(.NOT.ln_tide_pot) ) &
+          &   CALL ctl_stop('ln_read_load requires ln_tide_pot')
+      IF( ln_scal_load.AND.(.NOT.ln_tide_pot) ) &
+          &   CALL ctl_stop('ln_scal_load requires ln_tide_pot')
+      IF( ln_scal_load.AND.ln_read_load ) &
+          &   CALL ctl_stop('Choose between ln_scal_load and ln_read_load')
+      IF( ln_tide_ramp.AND.((nitend-nit000+1)*rdt/rday < rdttideramp) )   &
+         &   CALL ctl_stop('rdttideramp must be lower than run duration')
+      IF( ln_tide_ramp.AND.(rdttideramp<0.) ) &
+         &   CALL ctl_stop('rdttideramp must be positive')
+      !
+      ALLOCATE( ntide(nb_harmo) )
+      DO jk = 1, nb_harmo
+         DO ji = 1, jpmax_harmo
+            IF( TRIM(clname(jk)) == Wave(ji)%cname_tide ) THEN
+               ntide(jk) = ji
+               EXIT
+            ENDIF
+         END DO
+      END DO
+      !
+      ALLOCATE( omega_tide(nb_harmo), v0tide    (nb_harmo),   &
+         &      utide     (nb_harmo), ftide     (nb_harmo)  )
+      kt_tide = nit000
+      !
+      IF (.NOT.ln_scal_load ) rn_scal_load = 0._wp
+      !
+   END SUBROUTINE tide_init
+     
+   !!======================================================================
+END MODULE tideini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/updtide.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/updtide.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/SBC/updtide.F90	(revision 14097)
@@ -0,0 +1,81 @@
+MODULE updtide
+   !!======================================================================
+   !!                       ***  MODULE  updtide  ***
+   !! Initialization of tidal forcing
+   !!======================================================================
+   !! History :  9.0  !  07  (O. Le Galloudec)  Original code
+   !!----------------------------------------------------------------------
+   !!   upd_tide       : update tidal potential
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain
+   USE in_out_manager  ! I/O units
+   USE phycst          ! physical constant
+   USE sbctide         ! tide potential variable
+   USE tideini, ONLY: ln_tide_ramp, rdttideramp
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC   upd_tide   ! called in dynspg_... modules
+  
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE upd_tide( kt, kit, kt_offset )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE upd_tide  ***
+      !!
+      !! ** Purpose :   provide at each time step the astronomical potential
+      !!
+      !! ** Method  :   computed from pulsation and amplitude of all tide components
+      !!
+      !! ** Action  :   pot_astro   actronomical potential
+      !!----------------------------------------------------------------------      
+      INTEGER, INTENT(in)           ::   kt      ! ocean time-step index
+      INTEGER, INTENT(in), OPTIONAL ::   kit     ! external mode sub-time-step index (lk_dynspg_ts=T)
+      INTEGER, INTENT(in), OPTIONAL ::   kt_offset ! time offset in number 
+                                                     ! of internal steps             (lk_dynspg_ts=F)
+                                                     ! of external steps             (lk_dynspg_ts=T)
+      !
+      INTEGER  ::   ioffset      ! local integer
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zt, zramp    ! local scalar
+      REAL(wp), DIMENSION(nb_harmo) ::   zwt 
+      !!----------------------------------------------------------------------      
+      !
+      !                               ! tide pulsation at model time step (or sub-time-step)
+      zt = ( kt - kt_tide ) * rdt
+      !
+      ioffset = 0
+      IF( PRESENT( kt_offset ) )   ioffset = kt_offset
+      !
+      IF( PRESENT( kit ) )   THEN
+         zt = zt + ( kit +  ioffset - 1 ) * rdt / REAL( nn_baro, wp )
+      ELSE
+         zt = zt + ioffset * rdt
+      ENDIF
+      !
+      zwt(:) = omega_tide(:) * zt
+
+      pot_astro(:,:) = 0._wp          ! update tidal potential (sum of all harmonics)
+      DO jk = 1, nb_harmo   
+         pot_astro(:,:) = pot_astro(:,:) + amp_pot(:,:,jk) * COS( zwt(jk) + phi_pot(:,:,jk) )      
+      END DO
+      !
+      IF( ln_tide_ramp ) THEN         ! linear increase if asked
+         zt = ( kt - nit000 ) * rdt
+         IF( PRESENT( kit ) )   zt = zt + ( kit + ioffset -1) * rdt / REAL( nn_baro, wp )
+         zramp = MIN(  MAX( zt / (rdttideramp*rday) , 0._wp ) , 1._wp  )
+         pot_astro(:,:) = zramp * pot_astro(:,:)
+      ENDIF
+      !
+   END SUBROUTINE upd_tide
+
+  !!======================================================================
+
+END MODULE updtide
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopar.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopar.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopar.F90	(revision 14097)
@@ -0,0 +1,915 @@
+MODULE stopar
+   !!======================================================================
+   !!                       ***  MODULE  stopar  ***
+   !! Stochastic parameters : definition and time stepping
+   !!=====================================================================
+   !! History :  3.3  ! 2011-10 (J.-M. Brankart)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sto_par       : update the stochastic parameters
+   !!   sto_par_init  : define the stochastic parameterization
+   !!   sto_rst_read  : read restart file for stochastic parameters
+   !!   sto_rst_write : write restart file for stochastic parameters
+   !!   sto_par_white : fill input array with white Gaussian noise
+   !!   sto_par_flt   : apply horizontal Laplacian filter to input array
+   !!----------------------------------------------------------------------
+   USE storng          ! random number generator (external module)
+   USE par_oce         ! ocean parameters
+   USE dom_oce         ! ocean space and time domain variables
+   USE lbclnk          ! lateral boundary conditions (or mpp link)
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module
+   USE lib_mpp
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sto_par_init    ! called by nemogcm.F90
+   PUBLIC   sto_par         ! called by step.F90
+   PUBLIC   sto_rst_write   ! called by step.F90
+
+   LOGICAL           :: ln_rststo = .FALSE.  ! restart stochastic parameters from restart file
+   LOGICAL           :: ln_rstseed = .FALSE. ! read seed of RNG from restart file
+   CHARACTER(len=32) :: cn_storst_in = "restart_sto"     ! suffix of sto restart name (input)
+   CHARACTER(len=32) :: cn_storst_out = "restart_sto"    ! suffix of sto restart name (output)
+   INTEGER           :: numstor, numstow     ! logical unit for restart (read and write)
+
+   INTEGER           :: jpsto2d = 0          ! number of 2D stochastic parameters
+   INTEGER           :: jpsto3d = 0          ! number of 3D stochastic parameters
+
+   REAL(wp), PUBLIC, DIMENSION(:,:,:),   ALLOCATABLE :: sto2d      ! 2D stochastic parameters
+   REAL(wp), PUBLIC, DIMENSION(:,:,:,:), ALLOCATABLE :: sto3d      ! 3D stochastic parameters
+   REAL(wp),         DIMENSION(:,:),     ALLOCATABLE :: sto_tmp    ! temporary workspace
+   REAL(wp),         DIMENSION(:,:),     ALLOCATABLE :: sto2d_abc  ! a, b, c parameters (for 2D arrays)
+   REAL(wp),         DIMENSION(:,:),     ALLOCATABLE :: sto3d_abc  ! a, b, c parameters (for 3D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_ave  ! mean value (for 2D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_ave  ! mean value (for 3D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_std  ! standard deviation (for 2D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_std  ! standard deviation (for 3D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_lim  ! limitation factor (for 2D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_lim  ! limitation factor (for 3D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_tcor ! time correlation (for 2D arrays)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_tcor ! time correlation (for 3D arrays)
+   INTEGER,          DIMENSION(:),       ALLOCATABLE :: sto2d_ord  ! order of autoregressive process
+   INTEGER,          DIMENSION(:),       ALLOCATABLE :: sto3d_ord  ! order of autoregressive process
+
+   CHARACTER(len=1), DIMENSION(:),       ALLOCATABLE :: sto2d_typ  ! nature of grid point (T, U, V, W, F, I)
+   CHARACTER(len=1), DIMENSION(:),       ALLOCATABLE :: sto3d_typ  ! nature of grid point (T, U, V, W, F, I)
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_sgn  ! control of the sign accross the north fold
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_sgn  ! control of the sign accross the north fold
+   INTEGER,          DIMENSION(:),       ALLOCATABLE :: sto2d_flt  ! number of passes of Laplacian filter
+   INTEGER,          DIMENSION(:),       ALLOCATABLE :: sto3d_flt  ! number of passes of Laplacian filter
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto2d_fac  ! factor to restore std after filtering
+   REAL(wp),         DIMENSION(:),       ALLOCATABLE :: sto3d_fac  ! factor to restore std after filtering
+
+   LOGICAL, PUBLIC :: ln_sto_ldf = .FALSE.    ! stochastic lateral diffusion
+   INTEGER, PUBLIC :: jsto_ldf                ! index of lateral diffusion stochastic parameter
+   REAL(wp)        :: rn_ldf_std              ! lateral diffusion standard deviation (in percent)
+   REAL(wp)        :: rn_ldf_tcor             ! lateral diffusion correlation timescale (in timesteps)
+
+   LOGICAL, PUBLIC :: ln_sto_hpg = .FALSE.    ! stochastic horizontal pressure gradient
+   INTEGER, PUBLIC :: jsto_hpgi               ! index of stochastic hpg parameter (i direction)
+   INTEGER, PUBLIC :: jsto_hpgj               ! index of stochastic hpg parameter (j direction)
+   REAL(wp)        :: rn_hpg_std              ! density gradient standard deviation (in percent)
+   REAL(wp)        :: rn_hpg_tcor             ! density gradient correlation timescale (in timesteps)
+
+   LOGICAL, PUBLIC :: ln_sto_pstar = .FALSE.  ! stochastic ice strength
+   INTEGER, PUBLIC :: jsto_pstar              ! index of stochastic ice strength
+   REAL(wp), PUBLIC:: rn_pstar_std            ! ice strength standard deviation (in percent)
+   REAL(wp)        :: rn_pstar_tcor           ! ice strength correlation timescale (in timesteps)
+   INTEGER         :: nn_pstar_flt = 0        ! number of passes of Laplacian filter
+   INTEGER         :: nn_pstar_ord = 1        ! order of autoregressive processes
+
+   LOGICAL, PUBLIC :: ln_sto_trd = .FALSE.    ! stochastic model trend
+   INTEGER, PUBLIC :: jsto_trd                ! index of stochastic trend parameter
+   REAL(wp)        :: rn_trd_std              ! trend standard deviation (in percent)
+   REAL(wp)        :: rn_trd_tcor             ! trend correlation timescale (in timesteps)
+
+   LOGICAL, PUBLIC :: ln_sto_eos = .FALSE.    ! stochastic equation of state
+   INTEGER, PUBLIC :: nn_sto_eos = 1          ! number of degrees of freedom in stochastic equation of state
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_eosi ! index of stochastic eos parameter (i direction)
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_eosj ! index of stochastic eos parameter (j direction)
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_eosk ! index of stochastic eos parameter (k direction)
+   REAL(wp)        :: rn_eos_stdxy            ! random walk horz. standard deviation (in grid points)
+   REAL(wp)        :: rn_eos_stdz             ! random walk vert. standard deviation (in grid points)
+   REAL(wp)        :: rn_eos_tcor             ! random walk correlation timescale (in timesteps)
+   REAL(wp)        :: rn_eos_lim = 3.0_wp     ! limitation factor
+   INTEGER         :: nn_eos_flt = 0          ! number of passes of Laplacian filter
+   INTEGER         :: nn_eos_ord = 1          ! order of autoregressive processes
+
+   LOGICAL, PUBLIC :: ln_sto_trc = .FALSE.    ! stochastic tracer dynamics
+   INTEGER, PUBLIC :: nn_sto_trc = 1          ! number of degrees of freedom in stochastic tracer dynamics
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_trci ! index of stochastic trc parameter (i direction)
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_trcj ! index of stochastic trc parameter (j direction)
+   INTEGER, PUBLIC, DIMENSION(:), ALLOCATABLE :: jsto_trck ! index of stochastic trc parameter (k direction)
+   REAL(wp)        :: rn_trc_stdxy            ! random walk horz. standard deviation (in grid points)
+   REAL(wp)        :: rn_trc_stdz             ! random walk vert. standard deviation (in grid points)
+   REAL(wp)        :: rn_trc_tcor             ! random walk correlation timescale (in timesteps)
+   REAL(wp)        :: rn_trc_lim = 3.0_wp     ! limitation factor
+   INTEGER         :: nn_trc_flt = 0          ! number of passes of Laplacian filter
+   INTEGER         :: nn_trc_ord = 1          ! order of autoregressive processes
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sto_par( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_par  ***
+      !!
+      !! ** Purpose :   update the stochastic parameters
+      !!
+      !! ** Method  :   model basic stochastic parameters
+      !!                as a first order autoregressive process AR(1),
+      !!                governed by the equation:
+      !!                   X(t) = a * X(t-1) + b * w + c
+      !!                where the parameters a, b and c are related
+      !!                to expected value, standard deviation
+      !!                and time correlation (all stationary in time) by:
+      !!                   E   [X(t)]        = c / ( 1 - a )
+      !!                   STD [X(t)]        = b / SQRT( 1 - a * a )
+      !!                   COR [X(t),X(t-k)] = a ** k
+      !!                and w is a Gaussian white noise.
+      !!
+      !!                Higher order autoregressive proces can be optionally generated
+      !!                by replacing the white noise by a lower order process.
+      !!
+      !!                1) The statistics of the stochastic parameters (X) are assumed
+      !!                constant in space (homogeneous) and time (stationary).
+      !!                This could be generalized by replacing the constant
+      !!                a, b, c parameters by functions of space and time.
+      !!
+      !!                2) The computation is performed independently for every model
+      !!                grid point, which corresponds to assume that the stochastic
+      !!                parameters are uncorrelated in space.
+      !!                This could be generalized by including a spatial filter: Y = Filt[ X ]
+      !!                (possibly non-homgeneous and non-stationary) in the computation,
+      !!                or by solving an elliptic equation: L[ Y ] = X.
+      !!
+      !!                3) The stochastic model for the parameters could also
+      !!                be generalized to depend on the current state of the ocean (not done here).
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !!
+      INTEGER  :: ji, jj, jk, jsto, jflt
+      REAL(wp) :: stomax
+      !!----------------------------------------------------------------------
+      !
+      ! Update 2D stochastic arrays
+      !
+      DO jsto = 1, jpsto2d
+        ! Store array from previous time step
+        sto_tmp(:,:) = sto2d(:,:,jsto)
+
+        IF ( sto2d_ord(jsto) == 1 ) THEN
+          ! Draw new random numbers from N(0,1) --> w
+          CALL sto_par_white( sto2d(:,:,jsto) )
+          ! Apply horizontal Laplacian filter to w
+          DO jflt = 1, sto2d_flt(jsto)
+            CALL lbc_lnk( 'stopar', sto2d(:,:,jsto), sto2d_typ(jsto), sto2d_sgn(jsto) )
+            CALL sto_par_flt( sto2d(:,:,jsto) )
+          END DO
+          ! Factor to restore standard deviation after filtering
+          sto2d(:,:,jsto) = sto2d(:,:,jsto) * sto2d_fac(jsto)
+        ELSE
+          ! Use previous process (one order lower) instead of white noise
+          sto2d(:,:,jsto) = sto2d(:,:,jsto-1)
+        ENDIF
+
+        ! Multiply white noise (or lower order process) by b --> b * w
+        sto2d(:,:,jsto) = sto2d(:,:,jsto) * sto2d_abc(jsto,2)
+        ! Update autoregressive processes --> a * X(t-1) + b * w
+        sto2d(:,:,jsto) = sto2d(:,:,jsto) + sto_tmp(:,:) * sto2d_abc(jsto,1)
+        ! Add parameter c --> a * X(t-1) + b * w + c
+        sto2d(:,:,jsto) = sto2d(:,:,jsto) + sto2d_abc(jsto,3)
+        ! Limit random parameter anomalies to std times the limitation factor
+        stomax = sto2d_std(jsto) * sto2d_lim(jsto)
+        sto2d(:,:,jsto) = sto2d(:,:,jsto) - sto2d_ave(jsto)
+        sto2d(:,:,jsto) = SIGN(MIN(stomax,ABS(sto2d(:,:,jsto))),sto2d(:,:,jsto))
+        sto2d(:,:,jsto) = sto2d(:,:,jsto) + sto2d_ave(jsto)
+
+        ! Lateral boundary conditions on sto2d
+        CALL lbc_lnk( 'stopar', sto2d(:,:,jsto), sto2d_typ(jsto), sto2d_sgn(jsto) )
+      END DO
+      !
+      ! Update 3D stochastic arrays
+      !
+      DO jsto = 1, jpsto3d
+         DO jk = 1, jpk
+           ! Store array from previous time step
+           sto_tmp(:,:) = sto3d(:,:,jk,jsto)
+
+           IF ( sto3d_ord(jsto) == 1 ) THEN
+             ! Draw new random numbers from N(0,1) --> w
+             CALL sto_par_white( sto3d(:,:,jk,jsto) )
+             ! Apply horizontal Laplacian filter to w
+             DO jflt = 1, sto3d_flt(jsto)
+               CALL lbc_lnk( 'stopar', sto3d(:,:,jk,jsto), sto3d_typ(jsto), sto3d_sgn(jsto) )
+               CALL sto_par_flt( sto3d(:,:,jk,jsto) )
+             END DO
+             ! Factor to restore standard deviation after filtering
+             sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) * sto3d_fac(jsto)
+           ELSE
+             ! Use previous process (one order lower) instead of white noise
+             sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto-1)
+           ENDIF
+
+           ! Multiply white noise by b --> b * w
+           sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) * sto3d_abc(jsto,2)
+           ! Update autoregressive processes --> a * X(t-1) + b * w
+           sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) + sto_tmp(:,:) * sto3d_abc(jsto,1)
+           ! Add parameter c --> a * X(t-1) + b * w + c
+           sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) + sto3d_abc(jsto,3)
+           ! Limit random parameters anomalies to std times the limitation factor
+           stomax = sto3d_std(jsto) * sto3d_lim(jsto)
+           sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) - sto3d_ave(jsto)
+           sto3d(:,:,jk,jsto) = SIGN(MIN(stomax,ABS(sto3d(:,:,jk,jsto))),sto3d(:,:,jk,jsto))
+           sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) + sto3d_ave(jsto)
+         END DO
+         ! Lateral boundary conditions on sto3d
+         CALL lbc_lnk( 'stopar', sto3d(:,:,:,jsto), sto3d_typ(jsto), sto3d_sgn(jsto) )
+      END DO
+      !
+   END SUBROUTINE sto_par
+
+
+   SUBROUTINE sto_par_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_par_init  ***
+      !!
+      !! ** Purpose :   define the stochastic parameterization
+      !!----------------------------------------------------------------------
+      ! stochastic equation of state only (for now)
+      NAMELIST/namsto/ ln_sto_eos, nn_sto_eos, rn_eos_stdxy, rn_eos_stdz, &
+        &              rn_eos_tcor, nn_eos_ord, nn_eos_flt, rn_eos_lim,   &
+        &              ln_rststo, ln_rstseed, cn_storst_in, cn_storst_out
+      !NAMELIST/namsto/ ln_sto_ldf, rn_ldf_std, rn_ldf_tcor, &
+      !  &              ln_sto_hpg, rn_hpg_std, rn_hpg_tcor, &
+      !  &              ln_sto_pstar, rn_pstar_std, rn_pstar_tcor, nn_pstar_flt, nn_pstar_ord, &
+      !  &              ln_sto_trd, rn_trd_std, rn_trd_tcor, &
+      !  &              ln_sto_trc, nn_sto_trc, rn_trc_stdxy, rn_trc_stdz, &
+      !  &              rn_trc_tcor, nn_trc_ord, nn_trc_flt, rn_trc_lim
+      !!----------------------------------------------------------------------
+      INTEGER :: jsto, jmem, jarea, jdof, jord, jordm1, jk, jflt
+      INTEGER(KIND=8) :: zseed1, zseed2, zseed3, zseed4
+      REAL(wp) :: rinflate
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+
+      ! Read namsto namelist : stochastic parameterization
+      REWIND( numnam_ref )              ! Namelist namsto in reference namelist : stochastic parameterization
+      READ  ( numnam_ref, namsto, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namsto in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namsto in configuration namelist : stochastic parameterization
+      READ  ( numnam_cfg, namsto, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namsto in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsto )
+
+      IF( .NOT.ln_sto_eos ) THEN   ! no use of stochastic parameterization
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'sto_par_init : NO use of stochastic parameterization'
+            WRITE(numout,*) '~~~~~~~~~~~~'
+         ENDIF
+         RETURN
+      ENDIF
+
+      !IF(ln_ens_rst_in) cn_storst_in = cn_mem//cn_storst_in
+
+      ! Parameter print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sto_par_init : stochastic parameterization'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namsto : stochastic parameterization'
+         WRITE(numout,*) '      restart stochastic parameters           ln_rststo     = ', ln_rststo
+         WRITE(numout,*) '      read seed of RNG from restart file      ln_rstseed    = ', ln_rstseed
+         WRITE(numout,*) '      suffix of sto restart name (input)      cn_storst_in  = ', cn_storst_in
+         WRITE(numout,*) '      suffix of sto restart name (output)     cn_storst_out = ', cn_storst_out
+
+         ! WRITE(numout,*) '      stochastic lateral diffusion            ln_sto_ldf    = ', ln_sto_ldf
+         ! WRITE(numout,*) '      lateral diffusion std (in percent)      rn_ldf_std    = ', rn_ldf_std
+         ! WRITE(numout,*) '      lateral diffusion tcor (in timesteps)   rn_ldf_tcor   = ', rn_ldf_tcor
+
+         ! WRITE(numout,*) '      stochastic horizontal pressure gradient ln_sto_hpg    = ', ln_sto_hpg
+         ! WRITE(numout,*) '      density gradient std (in percent)       rn_hpg_std    = ', rn_hpg_std
+         ! WRITE(numout,*) '      density gradient tcor (in timesteps)    rn_hpg_tcor   = ', rn_hpg_tcor
+
+         ! WRITE(numout,*) '      stochastic ice strength                 ln_sto_pstar  = ', ln_sto_pstar
+         ! WRITE(numout,*) '      ice strength std (in percent)           rn_pstar_std  = ', rn_pstar_std
+         ! WRITE(numout,*) '      ice strength tcor (in timesteps)        rn_pstar_tcor = ', rn_pstar_tcor
+         ! WRITE(numout,*) '      order of autoregressive  processes      nn_pstar_ord  = ', nn_pstar_ord
+         ! WRITE(numout,*) '      passes of Laplacian filter              nn_pstar_flt  = ', nn_pstar_flt
+
+         !WRITE(numout,*) '      stochastic trend                        ln_sto_trd    = ', ln_sto_trd
+         !WRITE(numout,*) '      trend std (in percent)                  rn_trd_std    = ', rn_trd_std
+         !WRITE(numout,*) '      trend tcor (in timesteps)               rn_trd_tcor   = ', rn_trd_tcor
+
+         WRITE(numout,*) '      stochastic equation of state            ln_sto_eos    = ', ln_sto_eos
+         WRITE(numout,*) '      number of degrees of freedom            nn_sto_eos    = ', nn_sto_eos
+         WRITE(numout,*) '      random walk horz. std (in grid points)  rn_eos_stdxy  = ', rn_eos_stdxy
+         WRITE(numout,*) '      random walk vert. std (in grid points)  rn_eos_stdz   = ', rn_eos_stdz
+         WRITE(numout,*) '      random walk tcor (in timesteps)         rn_eos_tcor   = ', rn_eos_tcor
+         WRITE(numout,*) '      order of autoregressive  processes      nn_eos_ord    = ', nn_eos_ord
+         WRITE(numout,*) '      passes of Laplacian filter              nn_eos_flt    = ', nn_eos_flt
+         WRITE(numout,*) '      limitation factor                       rn_eos_lim    = ', rn_eos_lim
+
+         ! WRITE(numout,*) '      stochastic tracers dynamics             ln_sto_trc    = ', ln_sto_trc
+         ! WRITE(numout,*) '      number of degrees of freedom            nn_sto_trc    = ', nn_sto_trc
+         ! WRITE(numout,*) '      random walk horz. std (in grid points)  rn_trc_stdxy  = ', rn_trc_stdxy
+         ! WRITE(numout,*) '      random walk vert. std (in grid points)  rn_trc_stdz   = ', rn_trc_stdz
+         ! WRITE(numout,*) '      random walk tcor (in timesteps)         rn_trc_tcor   = ', rn_trc_tcor
+         ! WRITE(numout,*) '      order of autoregressive  processes      nn_trc_ord    = ', nn_trc_ord
+         ! WRITE(numout,*) '      passes of Laplacian filter              nn_trc_flt    = ', nn_trc_flt
+         ! WRITE(numout,*) '      limitation factor                       rn_trc_lim    = ', rn_trc_lim
+
+      ENDIF
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   stochastic parameterization :'
+
+      ! Set number of 2D stochastic arrays
+      jpsto2d = 0
+      IF( ln_sto_ldf ) THEN
+         IF(lwp) WRITE(numout,*) '       - stochastic lateral diffusion'
+         jpsto2d   = jpsto2d + 1
+         jsto_ldf  = jpsto2d
+      ENDIF
+      IF( ln_sto_pstar ) THEN
+         IF(lwp) WRITE(numout,*) '       - stochastic ice strength'
+         jpsto2d    = jpsto2d + 1 * nn_pstar_ord
+         jsto_pstar = jpsto2d
+      ENDIF
+      IF( ln_sto_eos ) THEN
+         IF ( lk_agrif ) CALL ctl_stop('EOS stochastic parametrization is not compatible with AGRIF')
+         IF(lwp) WRITE(numout,*) '       - stochastic equation of state'
+         ALLOCATE(jsto_eosi(nn_sto_eos))
+         ALLOCATE(jsto_eosj(nn_sto_eos))
+         ALLOCATE(jsto_eosk(nn_sto_eos))
+         DO jdof = 1, nn_sto_eos
+            jpsto2d   = jpsto2d + 3 * nn_eos_ord
+            jsto_eosi(jdof) = jpsto2d - 2 * nn_eos_ord
+            jsto_eosj(jdof) = jpsto2d - 1 * nn_eos_ord
+            jsto_eosk(jdof) = jpsto2d
+         END DO
+      ELSE
+         nn_sto_eos = 0
+      ENDIF
+      IF( ln_sto_trc ) THEN
+         IF(lwp) WRITE(numout,*) '       - stochastic tracers dynamics'
+         ALLOCATE(jsto_trci(nn_sto_trc))
+         ALLOCATE(jsto_trcj(nn_sto_trc))
+         ALLOCATE(jsto_trck(nn_sto_trc))
+         DO jdof = 1, nn_sto_trc
+            jpsto2d   = jpsto2d + 3 * nn_trc_ord
+            jsto_trci(jdof) = jpsto2d - 2 * nn_trc_ord
+            jsto_trcj(jdof) = jpsto2d - 1 * nn_trc_ord
+            jsto_trck(jdof) = jpsto2d
+         END DO
+      ELSE
+         nn_sto_trc = 0
+      ENDIF
+
+      ! Set number of 3D stochastic arrays
+      jpsto3d = 0
+      IF( ln_sto_hpg ) THEN
+         IF(lwp) WRITE(numout,*) '       - stochastic horizontal pressure gradient'
+         jpsto3d   = jpsto3d + 2
+         jsto_hpgi = jpsto3d - 1
+         jsto_hpgj = jpsto3d
+      ENDIF
+      IF( ln_sto_trd ) THEN
+         IF(lwp) WRITE(numout,*) '       - stochastic trend'
+         jpsto3d   = jpsto3d + 1
+         jsto_trd  = jpsto3d
+      ENDIF
+
+      ! Allocate 2D stochastic arrays
+      IF ( jpsto2d > 0 ) THEN
+         ALLOCATE ( sto2d(jpi,jpj,jpsto2d) )
+         ALLOCATE ( sto2d_abc(jpsto2d,3) )
+         ALLOCATE ( sto2d_ave(jpsto2d) )
+         ALLOCATE ( sto2d_std(jpsto2d) )
+         ALLOCATE ( sto2d_lim(jpsto2d) )
+         ALLOCATE ( sto2d_tcor(jpsto2d) )
+         ALLOCATE ( sto2d_ord(jpsto2d) )
+         ALLOCATE ( sto2d_typ(jpsto2d) )
+         ALLOCATE ( sto2d_sgn(jpsto2d) )
+         ALLOCATE ( sto2d_flt(jpsto2d) )
+         ALLOCATE ( sto2d_fac(jpsto2d) )
+      ENDIF
+
+      ! Allocate 3D stochastic arrays
+      IF ( jpsto3d > 0 ) THEN
+         ALLOCATE ( sto3d(jpi,jpj,jpk,jpsto3d) )
+         ALLOCATE ( sto3d_abc(jpsto3d,3) )
+         ALLOCATE ( sto3d_ave(jpsto3d) )
+         ALLOCATE ( sto3d_std(jpsto3d) )
+         ALLOCATE ( sto3d_lim(jpsto3d) )
+         ALLOCATE ( sto3d_tcor(jpsto3d) )
+         ALLOCATE ( sto3d_ord(jpsto3d) )
+         ALLOCATE ( sto3d_typ(jpsto3d) )
+         ALLOCATE ( sto3d_sgn(jpsto3d) )
+         ALLOCATE ( sto3d_flt(jpsto3d) )
+         ALLOCATE ( sto3d_fac(jpsto3d) )
+      ENDIF
+
+      ! Allocate temporary workspace
+      IF ( jpsto2d > 0 .OR. jpsto3d > 0 ) THEN
+         ALLOCATE ( sto_tmp(jpi,jpj) ) ; sto_tmp(:,:) = 0._wp
+      ENDIF
+
+      ! 1) For every stochastic parameter:
+      ! ----------------------------------
+      ! - set nature of grid point and control of the sign
+      !       across the north fold (sto2d_typ, sto2d_sgn)
+      ! - set number of passes of Laplacian filter (sto2d_flt)
+      ! - set order of every autoregressive process (sto2d_ord)
+      DO jsto = 1, jpsto2d
+         sto2d_typ(jsto) = 'T'
+         sto2d_sgn(jsto) = 1._wp
+         sto2d_flt(jsto) = 0
+         sto2d_ord(jsto) = 1
+         DO jord = 0, nn_pstar_ord-1
+            IF ( jsto+jord == jsto_pstar ) THEN ! Stochastic ice strength (ave=1)
+               sto2d_ord(jsto) = nn_pstar_ord - jord
+               sto2d_flt(jsto) = nn_pstar_flt
+            ENDIF
+         ENDDO
+         DO jdof = 1, nn_sto_eos
+         DO jord = 0, nn_eos_ord-1
+            IF ( jsto+jord == jsto_eosi(jdof) ) THEN ! Stochastic equation of state i (ave=0)
+               sto2d_ord(jsto) = nn_eos_ord - jord
+               sto2d_sgn(jsto) = -1._wp
+               sto2d_flt(jsto) = nn_eos_flt
+            ENDIF
+            IF ( jsto+jord == jsto_eosj(jdof) ) THEN ! Stochastic equation of state j (ave=0)
+               sto2d_ord(jsto) = nn_eos_ord - jord
+               sto2d_sgn(jsto) = -1._wp
+               sto2d_flt(jsto) = nn_eos_flt
+            ENDIF
+            IF ( jsto+jord == jsto_eosk(jdof) ) THEN ! Stochastic equation of state k (ave=0)
+               sto2d_ord(jsto) = nn_eos_ord - jord
+               sto2d_flt(jsto) = nn_eos_flt
+            ENDIF
+         END DO
+         END DO
+         DO jdof = 1, nn_sto_trc
+         DO jord = 0, nn_trc_ord-1
+            IF ( jsto+jord == jsto_trci(jdof) ) THEN ! Stochastic tracers dynamics i (ave=0)
+               sto2d_ord(jsto) = nn_trc_ord - jord
+               sto2d_sgn(jsto) = -1._wp
+               sto2d_flt(jsto) = nn_trc_flt
+            ENDIF
+            IF ( jsto+jord == jsto_trcj(jdof) ) THEN ! Stochastic tracers dynamics j (ave=0)
+               sto2d_ord(jsto) = nn_trc_ord - jord
+               sto2d_sgn(jsto) = -1._wp
+               sto2d_flt(jsto) = nn_trc_flt
+            ENDIF
+            IF ( jsto+jord == jsto_trck(jdof) ) THEN ! Stochastic tracers dynamics k (ave=0)
+               sto2d_ord(jsto) = nn_trc_ord - jord
+               sto2d_flt(jsto) = nn_trc_flt
+            ENDIF
+         END DO
+         END DO
+
+         sto2d_fac(jsto) = sto_par_flt_fac ( sto2d_flt(jsto) )
+      END DO
+      !
+      DO jsto = 1, jpsto3d
+         sto3d_typ(jsto) = 'T'
+         sto3d_sgn(jsto) = 1._wp
+         sto3d_flt(jsto) = 0
+         sto3d_ord(jsto) = 1
+         IF ( jsto == jsto_hpgi ) THEN ! Stochastic density gradient i (ave=1)
+            sto3d_typ(jsto) = 'U'
+         ENDIF
+         IF ( jsto == jsto_hpgj ) THEN ! Stochastic density gradient j (ave=1)
+            sto3d_typ(jsto) = 'V'
+         ENDIF
+         sto3d_fac(jsto) = sto_par_flt_fac ( sto3d_flt(jsto) )
+      END DO
+
+      ! 2) For every stochastic parameter:
+      ! ----------------------------------
+      ! set average, standard deviation and time correlation
+      DO jsto = 1, jpsto2d
+         sto2d_ave(jsto)  = 0._wp
+         sto2d_std(jsto)  = 1._wp
+         sto2d_tcor(jsto) = 1._wp
+         sto2d_lim(jsto)  = 3._wp
+         IF ( jsto == jsto_ldf  ) THEN ! Stochastic lateral diffusion (ave=1)
+            sto2d_ave(jsto)  = 1._wp
+            sto2d_std(jsto)  = rn_ldf_std
+            sto2d_tcor(jsto) = rn_ldf_tcor
+         ENDIF
+         DO jord = 0, nn_pstar_ord-1
+            IF ( jsto+jord == jsto_pstar ) THEN ! Stochastic ice strength (ave=1)
+               sto2d_std(jsto) = 1._wp
+               sto2d_tcor(jsto) = rn_pstar_tcor
+            ENDIF
+         ENDDO
+         DO jdof = 1, nn_sto_eos
+         DO jord = 0, nn_eos_ord-1
+            IF ( jsto+jord == jsto_eosi(jdof) ) THEN ! Stochastic equation of state i (ave=0)
+               sto2d_std(jsto)  = rn_eos_stdxy
+               sto2d_tcor(jsto) = rn_eos_tcor
+               sto2d_lim(jsto)  = rn_eos_lim
+            ENDIF
+            IF ( jsto+jord == jsto_eosj(jdof) ) THEN ! Stochastic equation of state j (ave=0)
+               sto2d_std(jsto)  = rn_eos_stdxy
+               sto2d_tcor(jsto) = rn_eos_tcor
+               sto2d_lim(jsto)  = rn_eos_lim
+            ENDIF
+            IF ( jsto+jord == jsto_eosk(jdof) ) THEN ! Stochastic equation of state k (ave=0)
+               sto2d_std(jsto)  = rn_eos_stdz
+               sto2d_tcor(jsto) = rn_eos_tcor
+               sto2d_lim(jsto)  = rn_eos_lim
+            ENDIF
+         END DO
+         END DO
+         DO jdof = 1, nn_sto_trc
+         DO jord = 0, nn_trc_ord-1
+            IF ( jsto+jord == jsto_trci(jdof) ) THEN ! Stochastic tracer dynamics i (ave=0)
+               sto2d_std(jsto)  = rn_trc_stdxy
+               sto2d_tcor(jsto) = rn_trc_tcor
+               sto2d_lim(jsto)  = rn_trc_lim
+            ENDIF
+            IF ( jsto+jord == jsto_trcj(jdof) ) THEN ! Stochastic tracer dynamics j (ave=0)
+               sto2d_std(jsto)  = rn_trc_stdxy
+               sto2d_tcor(jsto) = rn_trc_tcor
+               sto2d_lim(jsto)  = rn_trc_lim
+            ENDIF
+            IF ( jsto+jord == jsto_trck(jdof) ) THEN ! Stochastic tracer dynamics k (ave=0)
+               sto2d_std(jsto)  = rn_trc_stdz
+               sto2d_tcor(jsto) = rn_trc_tcor
+               sto2d_lim(jsto)  = rn_trc_lim
+            ENDIF
+         END DO
+         END DO
+
+      END DO
+      !
+      DO jsto = 1, jpsto3d
+         sto3d_ave(jsto)  = 0._wp
+         sto3d_std(jsto)  = 1._wp
+         sto3d_tcor(jsto) = 1._wp
+         sto3d_lim(jsto)  = 3._wp
+         IF ( jsto == jsto_hpgi ) THEN ! Stochastic density gradient i (ave=1)
+            sto3d_ave(jsto)  = 1._wp
+            sto3d_std(jsto)  = rn_hpg_std
+            sto3d_tcor(jsto) = rn_hpg_tcor
+         ENDIF
+         IF ( jsto == jsto_hpgj ) THEN ! Stochastic density gradient j (ave=1)
+            sto3d_ave(jsto)  = 1._wp
+            sto3d_std(jsto)  = rn_hpg_std
+            sto3d_tcor(jsto) = rn_hpg_tcor
+         ENDIF
+         IF ( jsto == jsto_trd ) THEN ! Stochastic trend (ave=1)
+            sto3d_ave(jsto)  = 1._wp
+            sto3d_std(jsto)  = rn_trd_std
+            sto3d_tcor(jsto) = rn_trd_tcor
+         ENDIF
+      END DO
+
+      ! 3) For every stochastic parameter:
+      ! ----------------------------------
+      ! - compute parameters (a, b, c) of the AR1 autoregressive process
+      !   from expected value (ave), standard deviation (std)
+      !   and time correlation (tcor):
+      !     a = EXP ( - 1 / tcor )           --> sto2d_abc(:,1)
+      !     b = std * SQRT( 1 - a * a )      --> sto2d_abc(:,2)
+      !     c = ave * ( 1 - a )              --> sto2d_abc(:,3)
+      ! - for higher order processes (ARn, n>1), use approximate formula
+      !   for the b parameter (valid for tcor>>1 time step)
+      DO jsto = 1, jpsto2d
+         IF ( sto2d_tcor(jsto) == 0._wp ) THEN
+            sto2d_abc(jsto,1) = 0._wp
+         ELSE
+            sto2d_abc(jsto,1) = EXP ( - 1._wp / sto2d_tcor(jsto) )
+         ENDIF
+         IF ( sto2d_ord(jsto) == 1 ) THEN      ! Exact formula for 1st order process
+            rinflate = sto2d_std(jsto)
+         ELSE
+            ! Approximate formula, valid for tcor >> 1
+            jordm1 = sto2d_ord(jsto) - 1
+            rinflate = SQRT ( REAL( jordm1 , wp ) / REAL( 2*(2*jordm1-1) , wp ) )
+         ENDIF
+         sto2d_abc(jsto,2) = rinflate * SQRT ( 1._wp - sto2d_abc(jsto,1) &
+                                                     * sto2d_abc(jsto,1) )
+         sto2d_abc(jsto,3) = sto2d_ave(jsto) * ( 1._wp - sto2d_abc(jsto,1) )
+      END DO
+      !
+      DO jsto = 1, jpsto3d
+         IF ( sto3d_tcor(jsto) == 0._wp ) THEN
+            sto3d_abc(jsto,1) = 0._wp
+         ELSE
+            sto3d_abc(jsto,1) = EXP ( - 1._wp / sto3d_tcor(jsto) )
+         ENDIF
+         IF ( sto3d_ord(jsto) == 1 ) THEN      ! Exact formula for 1st order process
+            rinflate = sto3d_std(jsto)
+         ELSE
+            ! Approximate formula, valid for tcor >> 1
+            jordm1 = sto3d_ord(jsto) - 1
+            rinflate = SQRT ( REAL( jordm1 , wp ) / REAL( 2*(2*jordm1-1) , wp ) )
+         ENDIF
+         sto3d_abc(jsto,2) = rinflate * SQRT ( 1._wp - sto3d_abc(jsto,1) &
+                                                     * sto3d_abc(jsto,1) )
+         sto3d_abc(jsto,3) = sto3d_ave(jsto) * ( 1._wp - sto3d_abc(jsto,1) )
+      END DO
+
+      ! 4) Initialize seeds for random number generator
+      ! -----------------------------------------------
+      ! using different seeds for different processors (jarea)
+      ! and different ensemble members (jmem)
+      CALL kiss_reset( )
+      DO jarea = 1, narea
+         !DO jmem = 0, nmember
+         zseed1 = kiss() ; zseed2 = kiss() ; zseed3 = kiss() ; zseed4 = kiss()
+         !END DO
+      END DO
+      CALL kiss_seed( zseed1, zseed2, zseed3, zseed4 )
+
+      ! 5) Initialize stochastic parameters to: ave + std * w
+      ! -----------------------------------------------------
+      DO jsto = 1, jpsto2d
+         ! Draw random numbers from N(0,1) --> w
+         CALL sto_par_white( sto2d(:,:,jsto) )
+         ! Apply horizontal Laplacian filter to w
+         DO jflt = 1, sto2d_flt(jsto)
+            CALL lbc_lnk( 'stopar', sto2d(:,:,jsto), sto2d_typ(jsto), sto2d_sgn(jsto) )
+            CALL sto_par_flt( sto2d(:,:,jsto) )
+         END DO
+         ! Factor to restore standard deviation after filtering
+         sto2d(:,:,jsto) = sto2d(:,:,jsto) * sto2d_fac(jsto)
+         ! Limit random parameter to the limitation factor
+         sto2d(:,:,jsto) = SIGN(MIN(sto2d_lim(jsto),ABS(sto2d(:,:,jsto))),sto2d(:,:,jsto))
+         ! Multiply by standard devation and add average value
+         sto2d(:,:,jsto) = sto2d(:,:,jsto) * sto2d_std(jsto) + sto2d_ave(jsto)
+      END DO
+      !
+      DO jsto = 1, jpsto3d
+         DO jk = 1, jpk
+            ! Draw random numbers from N(0,1) --> w
+            CALL sto_par_white( sto3d(:,:,jk,jsto) )
+            ! Apply horizontal Laplacian filter to w
+            DO jflt = 1, sto3d_flt(jsto)
+               CALL lbc_lnk( 'stopar', sto3d(:,:,jk,jsto), sto3d_typ(jsto), sto3d_sgn(jsto) )
+               CALL sto_par_flt( sto3d(:,:,jk,jsto) )
+            END DO
+            ! Factor to restore standard deviation after filtering
+            sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) * sto3d_fac(jsto)
+            ! Limit random parameter to the limitation factor
+            sto3d(:,:,jk,jsto) = SIGN(MIN(sto3d_lim(jsto),ABS(sto3d(:,:,jk,jsto))),sto3d(:,:,jk,jsto))
+            ! Multiply by standard devation and add average value
+            sto3d(:,:,jk,jsto) = sto3d(:,:,jk,jsto) * sto3d_std(jsto) + sto3d_ave(jsto)
+         END DO
+      END DO
+
+      ! 6) Restart stochastic parameters from file
+      ! ------------------------------------------
+      IF( ln_rststo ) CALL sto_rst_read
+
+   END SUBROUTINE sto_par_init
+
+
+   SUBROUTINE sto_rst_read
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_rst_read  ***
+      !!
+      !! ** Purpose :   read stochastic parameters from restart file
+      !!----------------------------------------------------------------------
+      INTEGER  :: jsto, jseed
+      INTEGER(KIND=8)     ::   ziseed(4)           ! RNG seeds in integer type
+      REAL(KIND=8)        ::   zrseed(4)           ! RNG seeds in real type (with same bits to save in restart)
+      CHARACTER(LEN=9)    ::   clsto2d='sto2d_000' ! stochastic parameter variable name
+      CHARACTER(LEN=9)    ::   clsto3d='sto3d_000' ! stochastic parameter variable name
+      CHARACTER(LEN=10)   ::   clseed='seed0_0000' ! seed variable name
+      !!----------------------------------------------------------------------
+
+      IF ( jpsto2d > 0 .OR. jpsto3d > 0 ) THEN
+
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'sto_rst_read : read stochastic parameters from restart file'
+            WRITE(numout,*) '~~~~~~~~~~~~'
+         ENDIF
+
+         ! Open the restart file
+         CALL iom_open( cn_storst_in, numstor )
+
+         ! Get stochastic parameters from restart file:
+         ! 2D stochastic parameters
+         DO jsto = 1 , jpsto2d
+            WRITE(clsto2d(7:9),'(i3.3)') jsto
+            CALL iom_get( numstor, jpdom_autoglo, clsto2d , sto2d(:,:,jsto) )
+         END DO
+         ! 3D stochastic parameters
+         DO jsto = 1 , jpsto3d
+            WRITE(clsto3d(7:9),'(i3.3)') jsto
+            CALL iom_get( numstor, jpdom_autoglo, clsto3d , sto3d(:,:,:,jsto) )
+         END DO
+
+         IF (ln_rstseed) THEN
+            ! Get saved state of the random number generator
+            DO jseed = 1 , 4
+               WRITE(clseed(5:5) ,'(i1.1)') jseed
+               WRITE(clseed(7:10),'(i4.4)') narea
+               CALL iom_get( numstor, clseed , zrseed(jseed) )
+            END DO
+            ziseed = TRANSFER( zrseed , ziseed)
+            CALL kiss_seed( ziseed(1) , ziseed(2) , ziseed(3) , ziseed(4) )
+         ENDIF
+
+         ! Close the restart file
+         CALL iom_close( numstor )
+
+      ENDIF
+
+   END SUBROUTINE sto_rst_read
+
+
+   SUBROUTINE sto_rst_write( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_rst_write  ***
+      !!
+      !! ** Purpose :   write stochastic parameters in restart file
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ocean time-step
+      !!
+      INTEGER  :: jsto, jseed
+      INTEGER(KIND=8)     ::   ziseed(4)           ! RNG seeds in integer type
+      REAL(KIND=8)        ::   zrseed(4)           ! RNG seeds in real type (with same bits to save in restart)
+      CHARACTER(LEN=20)   ::   clkt                ! ocean time-step defined as a character
+      CHARACTER(LEN=50)   ::   clname              ! restart file name
+      CHARACTER(LEN=9)    ::   clsto2d='sto2d_000' ! stochastic parameter variable name
+      CHARACTER(LEN=9)    ::   clsto3d='sto3d_000' ! stochastic parameter variable name
+      CHARACTER(LEN=10)   ::   clseed='seed0_0000' ! seed variable name
+      !!----------------------------------------------------------------------
+
+      IF( .NOT. ln_rst_list .AND. nn_stock == -1 ) RETURN   ! we will never do any restart
+      
+      IF ( jpsto2d > 0 .OR. jpsto3d > 0 ) THEN
+
+         IF( kt == nitrst .OR. kt == nitend ) THEN
+            IF(lwp) THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'sto_rst_write : write stochastic parameters in restart file'
+               WRITE(numout,*) '~~~~~~~~~~~~~'
+            ENDIF
+         ENDIF
+
+         ! Put stochastic parameters in restart files
+         ! (as opened at previous timestep, see below)
+         IF( kt > nit000) THEN
+         IF( kt == nitrst .OR. kt == nitend ) THEN
+            ! get and save current state of the random number generator
+            CALL kiss_state( ziseed(1) , ziseed(2) , ziseed(3) , ziseed(4) )
+            zrseed = TRANSFER( ziseed , zrseed)
+            DO jseed = 1 , 4
+               WRITE(clseed(5:5) ,'(i1.1)') jseed
+               WRITE(clseed(7:10),'(i4.4)') narea
+               CALL iom_rstput( kt, nitrst, numstow, clseed , zrseed(jseed) )
+            END DO
+            ! 2D stochastic parameters
+            DO jsto = 1 , jpsto2d
+               WRITE(clsto2d(7:9),'(i3.3)') jsto
+               CALL iom_rstput( kt, nitrst, numstow, clsto2d , sto2d(:,:,jsto) )
+            END DO
+            ! 3D stochastic parameters
+            DO jsto = 1 , jpsto3d
+               WRITE(clsto3d(7:9),'(i3.3)') jsto
+               CALL iom_rstput( kt, nitrst, numstow, clsto3d , sto3d(:,:,:,jsto) )
+            END DO
+            ! close the restart file
+            CALL iom_close( numstow )
+         ENDIF
+         ENDIF
+
+         ! Open the restart file one timestep before writing restart
+         IF( kt < nitend) THEN
+         IF( kt == nitrst - 1 .OR. nn_stock == 1 .OR. kt == nitend-1 ) THEN
+            ! create the filename
+            IF( nitrst > 999999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
+            ELSE                            ;   WRITE(clkt, '(i8.8)') nitrst
+            ENDIF
+            clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_storst_out)
+            ! print information
+            IF(lwp) THEN
+               WRITE(numout,*) '             open stochastic parameters restart file: '//clname
+               IF( kt == nitrst - 1 ) THEN
+                  WRITE(numout,*) '             kt = nitrst - 1 = ', kt
+               ELSE
+                  WRITE(numout,*) '             kt = '             , kt
+               ENDIF
+            ENDIF
+            ! open the restart file
+            CALL iom_open( clname, numstow, ldwrt = .TRUE. )
+         ENDIF
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE sto_rst_write
+
+
+   SUBROUTINE sto_par_white( psto )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_par_white  ***
+      !!
+      !! ** Purpose :   fill input array with white Gaussian noise
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(out)           ::   psto
+      !!
+      INTEGER  :: ji, jj
+      REAL(KIND=8) :: gran   ! Gaussian random number (forced KIND=8 as in kiss_gaussian)
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            CALL kiss_gaussian( gran )
+            psto(ji,jj) = gran
+         END DO
+      END DO
+
+   END SUBROUTINE sto_par_white
+
+
+   SUBROUTINE sto_par_flt( psto )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_par_flt  ***
+      !!
+      !! ** Purpose :   apply horizontal Laplacian filter to input array
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(out)           ::   psto
+      !!
+      INTEGER  :: ji, jj
+
+      DO jj = 2, jpj-1
+         DO ji = 2, jpi-1
+            psto(ji,jj) = 0.5_wp * psto(ji,jj) + 0.125_wp * &
+                              &  ( psto(ji-1,jj) + psto(ji+1,jj) +  &
+                              &    psto(ji,jj-1) + psto(ji,jj+1) )
+         END DO
+      END DO
+
+   END SUBROUTINE sto_par_flt
+
+
+   FUNCTION sto_par_flt_fac( kpasses )
+      !!----------------------------------------------------------------------
+      !!                  ***  FUNCTION sto_par_flt_fac  ***
+      !!
+      !! ** Purpose :   compute factor to restore standard deviation
+      !!                as a function of the number of passes
+      !!                of the Laplacian filter
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kpasses
+      REAL(wp) :: sto_par_flt_fac
+      !!
+      INTEGER :: jpasses, ji, jj, jflti, jfltj
+      INTEGER, DIMENSION(-1:1,-1:1) :: pflt0
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE :: pfltb
+      REAL(wp), DIMENSION(:,:), ALLOCATABLE :: pflta
+      REAL(wp) :: ratio
+
+      pflt0(-1,-1) = 0 ; pflt0(-1,0) = 1 ; pflt0(-1,1) = 0
+      pflt0( 0,-1) = 1 ; pflt0( 0,0) = 4 ; pflt0( 0,1) = 1
+      pflt0( 1,-1) = 0 ; pflt0( 1,0) = 1 ; pflt0( 1,1) = 0
+
+      ALLOCATE(pfltb(-kpasses-1:kpasses+1,-kpasses-1:kpasses+1))
+      ALLOCATE(pflta(-kpasses-1:kpasses+1,-kpasses-1:kpasses+1))
+
+      pfltb(:,:) = 0
+      pfltb(0,0) = 1
+      DO jpasses = 1, kpasses
+        pflta(:,:) = 0
+        DO jflti= -1, 1
+        DO jfltj= -1, 1
+          DO ji= -kpasses, kpasses
+          DO jj= -kpasses, kpasses
+            pflta(ji,jj) = pflta(ji,jj) + pfltb(ji+jflti,jj+jfltj) * pflt0(jflti,jfltj)
+          ENDDO
+          ENDDO
+        ENDDO
+        ENDDO
+        pfltb(:,:) = pflta(:,:)
+      ENDDO
+
+      ratio = SUM(pfltb(:,:))
+      ratio = ratio * ratio / SUM(pfltb(:,:)*pfltb(:,:))
+      ratio = SQRT(ratio)
+
+      DEALLOCATE(pfltb,pflta)
+
+      sto_par_flt_fac = ratio
+
+   END FUNCTION sto_par_flt_fac
+
+
+END MODULE stopar
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopts.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopts.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/stopts.F90	(revision 14097)
@@ -0,0 +1,146 @@
+MODULE stopts
+   !!==============================================================================
+   !!                       ***  MODULE  stopts  ***
+   !! Stochastic parameterization: compute stochastic tracer fluctuations
+   !!==============================================================================
+   !! History :  3.3  ! 2011-12 (J.-M. Brankart)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sto_pts        : compute current stochastic tracer fluctuations
+   !!   sto_pts_init   : initialisation for stochastic tracer fluctuations
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE lbclnk          ! lateral boundary conditions (or mpp link)
+   USE phycst          ! physical constants
+   USE stopar          ! stochastic parameterization
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sto_pts         ! called by step.F90
+   PUBLIC   sto_pts_init    ! called by nemogcm.F90
+
+   ! Public array with random tracer fluctuations
+   REAL(wp), PUBLIC, DIMENSION(:,:,:,:,:), ALLOCATABLE :: pts_ran
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sto_pts( pts )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_pts  ***
+      !!
+      !! ** Purpose :   Compute current stochastic tracer fluctuations
+      !!
+      !! ** Method  :   Compute tracer differences from a random walk
+      !!                around every model grid point
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(inout) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                               ! 2 : salinity               [psu]
+      INTEGER  ::   ji, jj, jk, jts, jdof ! dummy loop indices
+      INTEGER  ::   jim1, jjm1, jkm1  ! incremented indices
+      INTEGER  ::   jip1, jjp1, jkp1  !     -          -
+      REAL(wp) ::   zdtsim, zdtsjm, zdtskm         ! temporary scalars
+      REAL(wp) ::   zdtsip, zdtsjp, zdtskp, zdts   !     -        -
+      !!----------------------------------------------------------------------
+
+      DO jts = 1, jpts
+        CALL lbc_lnk( 'stopts', pts(:,:,:,jts), 'T' , 1._wp )
+      ENDDO
+
+      DO jdof = 1, nn_sto_eos
+        DO jts = 1, jpts
+           DO jk = 1, jpkm1
+              jkm1 = MAX(jk-1,1) ; jkp1 = MIN(jk+1,jpkm1)
+              DO jj = 1, jpj
+                 jjm1 = MAX(jj-1,1) ; jjp1 = MIN(jj+1,jpj)
+                 DO ji = 1, jpi
+                    jim1 = MAX(ji-1,1) ; jip1 = MIN(ji+1,jpi)
+                    !
+                    ! compute tracer gradient
+                    zdtsip = ( pts(jip1,jj,jk,jts) - pts(ji,jj,jk,jts) ) * tmask(jip1,jj,jk)
+                    zdtsim = ( pts(ji,jj,jk,jts) - pts(jim1,jj,jk,jts) ) * tmask(jim1,jj,jk)
+                    zdtsjp = ( pts(ji,jjp1,jk,jts) - pts(ji,jj,jk,jts) ) * tmask(ji,jjp1,jk)
+                    zdtsjm = ( pts(ji,jj,jk,jts) - pts(ji,jjm1,jk,jts) ) * tmask(ji,jjm1,jk)
+                    zdtskp = ( pts(ji,jj,jkp1,jts) - pts(ji,jj,jk,jts) ) * tmask(ji,jj,jkp1)
+                    zdtskm = ( pts(ji,jj,jk,jts) - pts(ji,jj,jkm1,jts) ) * tmask(ji,jj,jkm1)
+                    !
+                    ! compute random tracer fluctuation (zdts)
+                    zdts   = ( zdtsip + zdtsim ) * sto2d(ji,jj,jsto_eosi(jdof)) + &
+                           & ( zdtsjp + zdtsjm ) * sto2d(ji,jj,jsto_eosj(jdof)) + &
+                           & ( zdtskp + zdtskm ) * sto2d(ji,jj,jsto_eosk(jdof))
+!                   zdts   = zdtsip * MAX(sto2d(ji,jj,jsto_eosi),0._wp) + &
+!                          & zdtsim * MIN(sto2d(ji,jj,jsto_eosi),0._wp) + &
+!                          & zdtsjp * MAX(sto2d(ji,jj,jsto_eosj),0._wp) + &
+!                          & zdtsjm * MIN(sto2d(ji,jj,jsto_eosj),0._wp) + &
+!                          & zdtskp * MAX(sto2d(ji,jj,jsto_eosk),0._wp) + &
+!                          & zdtskm * MIN(sto2d(ji,jj,jsto_eosk),0._wp)
+                    zdts   = zdts  * tmask(ji,jj,jk) *SIN( gphit(ji,jj) * rad )
+                    pts_ran(ji,jj,jk,jts,jdof) = zdts * 0.5_wp
+                    !
+                  END DO
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Eliminate any possible negative salinity
+      DO jdof = 1, nn_sto_eos
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  pts_ran(ji,jj,jk,jp_sal,jdof) = MIN( ABS(pts_ran(ji,jj,jk,jp_sal,jdof)) ,  &
+                                                &      MAX(pts(ji,jj,jk,jp_sal),0._wp) )     &
+                                                &  * SIGN(1._wp,pts_ran(ji,jj,jk,jp_sal,jdof))
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Eliminate any temperature lower than -2 degC
+!     DO jdof = 1, nn_sto_eos
+!        DO jk = 1, jpkm1
+!           DO jj = 1, jpj
+!              DO ji = 1, jpi
+!                 pts_ran(ji,jj,jk,jp_tem,jdof) = MIN( ABS(pts_ran(ji,jj,jk,jp_tem,jdof)) ,    &
+!                                               &      MAX(pts(ji,jj,jk,jp_tem)+2._wp,0._wp) ) &
+!                                               &  * SIGN(1._wp,pts_ran(ji,jj,jk,jp_tem,jdof))
+!              END DO
+!           END DO
+!        END DO
+!     END DO
+
+
+      ! Lateral boundary conditions on pts_ran
+      DO jdof = 1, nn_sto_eos
+         DO jts = 1, jpts
+            CALL lbc_lnk( 'stopts', pts_ran(:,:,:,jts,jdof), 'T' , 1._wp )
+         END DO
+      END DO
+
+   END SUBROUTINE sto_pts
+
+
+   SUBROUTINE sto_pts_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sto_pts_init  ***
+      !!
+      !! ** Purpose :   Initialisation for stochastic tracer fluctuations
+      !!
+      !! ** Method  :   Allocate required array
+      !!
+      !!----------------------------------------------------------------------
+
+      ALLOCATE(pts_ran(jpi,jpj,jpk,jpts,nn_sto_eos))
+
+   END SUBROUTINE sto_pts_init
+
+END MODULE stopts
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/storng.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/storng.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/STO/storng.F90	(revision 14097)
@@ -0,0 +1,407 @@
+MODULE storng
+!$AGRIF_DO_NOT_TREAT
+   !!======================================================================
+   !!                       ***  MODULE  storng  ***
+   !! Random number generator, used in NEMO stochastic parameterization
+   !!
+   !!=====================================================================
+   !! History :  3.3  ! 2011-10 (J.-M. Brankart)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !! The module is based on (and includes) the
+   !! 64-bit KISS (Keep It Simple Stupid) random number generator
+   !! distributed by George Marsaglia :
+   !! http://groups.google.com/group/comp.lang.fortran/
+   !!        browse_thread/thread/a85bf5f2a97f5a55
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   kiss          : 64-bit KISS random number generator (period ~ 2^250)
+   !!   kiss_seed     : Define seeds for KISS random number generator
+   !!   kiss_state    : Get current state of KISS random number generator
+   !!   kiss_save     : Save current state of KISS (for future restart)
+   !!   kiss_load     : Load the saved state of KISS
+   !!   kiss_reset    : Reset the default seeds
+   !!   kiss_check    : Check the KISS pseudo-random sequence
+   !!   kiss_uniform  : Real random numbers with uniform distribution in [0,1]
+   !!   kiss_gaussian : Real random numbers with Gaussian distribution N(0,1)
+   !!   kiss_gamma    : Real random numbers with Gamma distribution Gamma(k,1)
+   !!   kiss_sample   : Select a random sample from a set of integers
+   !!
+   !!   ---CURRENTLY NOT USED IN NEMO :
+   !!   kiss_save, kiss_load, kiss_check, kiss_gamma, kiss_sample
+   !!----------------------------------------------------------------------
+   USE par_kind
+   USE lib_mpp
+
+   IMPLICIT NONE
+   PRIVATE
+
+   ! Public functions/subroutines
+   PUBLIC :: kiss, kiss_seed, kiss_state, kiss_reset ! kiss_save, kiss_load, kiss_check
+   PUBLIC :: kiss_uniform, kiss_gaussian, kiss_gamma, kiss_sample
+
+   ! Default/initial seeds
+   INTEGER(KIND=i8) :: x=1234567890987654321_8
+   INTEGER(KIND=i8) :: y=362436362436362436_8
+   INTEGER(KIND=i8) :: z=1066149217761810_8
+   INTEGER(KIND=i8) :: w=123456123456123456_8
+
+   ! Parameters to generate real random variates
+   REAL(KIND=wp), PARAMETER :: huge64=9223372036854775808.0  ! +1
+   REAL(KIND=wp), PARAMETER :: zero=0.0, half=0.5, one=1.0, two=2.0
+
+   ! Variables to store 2 Gaussian random numbers with current index (ig)
+   INTEGER(KIND=i8), SAVE :: ig=1
+   REAL(KIND=wp), SAVE :: gran1, gran2
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   FUNCTION kiss()
+      !! --------------------------------------------------------------------
+      !!                  ***  FUNCTION kiss  ***
+      !!
+      !! ** Purpose :   64-bit KISS random number generator
+      !!
+      !! ** Method  :   combine several random number generators:
+      !!                (1) Xorshift (XSH), period 2^64-1,
+      !!                (2) Multiply-with-carry (MWC), period (2^121+2^63-1)
+      !!                (3) Congruential generator (CNG), period 2^64.
+      !!
+      !!                overall period:
+      !!                (2^250+2^192+2^64-2^186-2^129)/6
+      !!                            ~= 2^(247.42) or 10^(74.48)
+      !!
+      !!                set your own seeds with 'kiss_seed'
+      ! --------------------------------------------------------------------
+      IMPLICIT NONE
+      INTEGER(KIND=i8) :: kiss, t
+
+      t = ISHFT(x,58) + w
+      IF (s(x).eq.s(t)) THEN
+         w = ISHFT(x,-6) + s(x)
+      ELSE
+         w = ISHFT(x,-6) + 1 - s(x+t)
+      ENDIF
+      x = t + x
+      y = m( m( m(y,13_8), -17_8 ), 43_8 )
+      z = 6906969069_8 * z + 1234567_8
+
+      kiss = x + y + z
+
+      CONTAINS
+
+         FUNCTION s(k)
+            INTEGER(KIND=i8) :: s, k
+            s = ISHFT(k,-63)
+         END FUNCTION s
+
+         FUNCTION m(k, n)
+            INTEGER(KIND=i8) :: m, k, n
+            m =  IEOR(k, ISHFT(k, n) )
+         END FUNCTION m
+
+   END FUNCTION kiss
+
+
+   SUBROUTINE kiss_seed(ix, iy, iz, iw)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_seed  ***
+      !!
+      !! ** Purpose :   Define seeds for KISS random number generator
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      INTEGER(KIND=i8) :: ix, iy, iz, iw
+
+      x = ix
+      y = iy
+      z = iz
+      w = iw
+
+   END SUBROUTINE kiss_seed
+
+
+   SUBROUTINE kiss_state(ix, iy, iz, iw)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_state  ***
+      !!
+      !! ** Purpose :   Get current state of KISS random number generator
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      INTEGER(KIND=i8) :: ix, iy, iz, iw
+
+      ix = x
+      iy = y
+      iz = z
+      iw = w
+
+   END SUBROUTINE kiss_state
+
+
+   SUBROUTINE kiss_reset()
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_reset  ***
+      !!
+      !! ** Purpose :   Reset the default seeds for KISS random number generator
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+
+      x=1234567890987654321_8
+      y=362436362436362436_8
+      z=1066149217761810_8
+      w=123456123456123456_8
+
+    END SUBROUTINE kiss_reset
+
+
+   !  SUBROUTINE kiss_check(check_type)
+   !    !! --------------------------------------------------------------------
+   !    !!                  ***  ROUTINE kiss_check  ***
+   !    !!
+   !    !! ** Purpose :   Check the KISS pseudo-random sequence
+   !    !!
+   !    !! ** Method  :   Check that it reproduces the correct sequence
+   !    !!                from the default seed
+   !    !!
+   !    !! --------------------------------------------------------------------
+   !    IMPLICIT NONE
+   !    INTEGER(KIND=i8) :: iter, niter, correct, iran
+   !    CHARACTER(LEN=*) :: check_type
+   !    LOGICAL :: print_success
+
+   !    ! Save current state of KISS
+   !    CALL kiss_save()
+   !    ! Reset the default seed
+   !    CALL kiss_reset()
+
+   !    ! Select check type
+   !    SELECT CASE(check_type)
+   !    CASE('short')
+   !       niter = 5_8
+   !       correct = 542381058189297533
+   !       print_success = .FALSE.
+   !    CASE('long')
+   !       niter = 100000000_8
+   !       correct = 1666297717051644203 ! Check provided by G. Marsaglia
+   !       print_success = .TRUE.
+   !    CASE('default')
+   !    CASE DEFAULT
+   !       STOP 'Bad check type in kiss_check'
+   !    END SELECT
+
+   !    ! Run kiss for the required number of iterations (niter)
+   !    DO iter=1,niter
+   !       iran = kiss()
+   !    ENDDO
+
+   !    ! Check that last iterate is correct
+   !    IF (iran.NE.correct) THEN
+   !       STOP 'Check failed: KISS internal error !!'
+   !    ELSE
+   !       IF (print_success) PRINT *, 'Check successful: 100 million calls to KISS OK'
+   !    ENDIF
+
+   !    ! Reload the previous state of KISS
+   !    CALL kiss_load()
+
+   ! END SUBROUTINE kiss_check
+
+
+   ! SUBROUTINE kiss_save
+   !    !! --------------------------------------------------------------------
+   !    !!                  ***  ROUTINE kiss_save  ***
+   !    !!
+   !    !! ** Purpose :   Save current state of KISS random number generator
+   !    !!
+   !    !! --------------------------------------------------------------------
+   !    INTEGER :: inum     !! Local integer
+
+   !    IMPLICIT NONE
+
+   !    CALL ctl_opn( inum, '.kiss_restart', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+
+   !    ! OPEN(UNIT=30,FILE='.kiss_restart')
+   !    WRITE(inum,*) x
+   !    WRITE(inum,*) y
+   !    WRITE(inum,*) z
+   !    WRITE(inum,*) w
+   !    CALL flush(inum)
+
+   !  END SUBROUTINE kiss_save
+
+
+   !  SUBROUTINE kiss_load
+   !    !! --------------------------------------------------------------------
+   !    !!                  ***  ROUTINE kiss_load  ***
+   !    !!
+   !    !! ** Purpose :   Load the saved state of KISS random number generator
+   !    !!
+   !    !! --------------------------------------------------------------------
+   !    IMPLICIT NONE
+   !    LOGICAL :: filexists
+   ! Use ctl_opn routine rather than fortran intrinsic functions
+   !    INQUIRE(FILE='.kiss_restart',EXIST=filexists)
+   !    IF (filexists) THEN
+   !       OPEN(UNIT=30,FILE='.kiss_restart')
+   !       READ(30,*) x
+   !       READ(30,*) y
+   !       READ(30,*) z
+   !       READ(30,*) w
+   !       CLOSE(30)
+   !    ENDIF
+
+   ! END SUBROUTINE kiss_load
+
+
+   SUBROUTINE kiss_uniform(uran)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_uniform  ***
+      !!
+      !! ** Purpose :   Real random numbers with uniform distribution in [0,1]
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      REAL(KIND=wp) :: uran
+
+      uran = half * ( one + REAL(kiss(),wp) / huge64 )
+
+   END SUBROUTINE kiss_uniform
+
+
+   SUBROUTINE kiss_gaussian(gran)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_gaussian  ***
+      !!
+      !! ** Purpose :   Real random numbers with Gaussian distribution N(0,1)
+      !!
+      !! ** Method  :   Generate 2 new Gaussian draws (gran1 and gran2)
+      !!                from 2 uniform draws on [-1,1] (u1 and u2),
+      !!                using the Marsaglia polar method
+      !!                (see Devroye, Non-Uniform Random Variate Generation, p. 235-236)
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      REAL(KIND=wp) :: gran, u1, u2, rsq, fac
+
+      IF (ig.EQ.1) THEN
+         rsq = two
+         DO WHILE ( (rsq.GE.one).OR. (rsq.EQ.zero) )
+            u1 = REAL(kiss(),wp) / huge64
+            u2 = REAL(kiss(),wp) / huge64
+            rsq = u1*u1 + u2*u2
+         ENDDO
+         fac = SQRT(-two*LOG(rsq)/rsq)
+         gran1 = u1 * fac
+         gran2 = u2 * fac
+      ENDIF
+
+      ! Output one of the 2 draws
+      IF (ig.EQ.1) THEN
+         gran = gran1 ; ig = 2
+      ELSE
+         gran = gran2 ; ig = 1
+      ENDIF
+
+   END SUBROUTINE kiss_gaussian
+
+
+   SUBROUTINE kiss_gamma(gamr,k)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_gamma  ***
+      !!
+      !! ** Purpose :   Real random numbers with Gamma distribution Gamma(k,1)
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      REAL(KIND=wp), PARAMETER :: p1 = 4.5_8
+      REAL(KIND=wp), PARAMETER :: p2 = 2.50407739677627_8  ! 1+LOG(9/2)
+      REAL(KIND=wp), PARAMETER :: p3 = 1.38629436111989_8  ! LOG(4)
+      REAL(KIND=wp) :: gamr, k, u1, u2, b, c, d, xx, yy, zz, rr, ee
+      LOGICAL :: accepted
+
+      IF (k.GT.one) THEN
+         ! Cheng's rejection algorithm
+         ! (see Devroye, Non-Uniform Random Variate Generation, p. 413)
+         b = k - p3 ; d = SQRT(two*k-one) ; c = k + d
+
+         accepted=.FALSE.
+         DO WHILE (.NOT.accepted)
+            CALL kiss_uniform(u1)
+            yy = LOG(u1/(one-u1)) / d  ! Mistake in Devroye: "* k" instead of "/ d"
+            xx = k * EXP(yy)
+            rr = b + c * yy - xx
+            CALL kiss_uniform(u2)
+            zz = u1 * u1 * u2
+
+            accepted = rr .GE. (zz*p1-p2)
+            IF (.NOT.accepted) accepted =  rr .GE. LOG(zz)
+         ENDDO
+
+         gamr = xx
+
+      ELSEIF (k.LT.one) THEN
+        ! Rejection from the Weibull density
+        ! (see Devroye, Non-Uniform Random Variate Generation, p. 415)
+        c = one/k ; d = (one-k) * EXP( (k/(one-k)) * LOG(k) )
+
+        accepted=.FALSE.
+        DO WHILE (.NOT.accepted)
+           CALL kiss_uniform(u1)
+           zz = -LOG(u1)
+           xx = EXP( c * LOG(zz) )
+           CALL kiss_uniform(u2)
+           ee = -LOG(u2)
+
+           accepted = (zz+ee) .GE. (d+xx)  ! Mistake in Devroye: "LE" instead of "GE"
+        ENDDO
+
+        gamr = xx
+
+      ELSE
+         ! Exponential distribution
+         CALL kiss_uniform(u1)
+         gamr = -LOG(u1)
+
+      ENDIF
+
+   END SUBROUTINE kiss_gamma
+
+
+   SUBROUTINE kiss_sample(a,n,k)
+      !! --------------------------------------------------------------------
+      !!                  ***  ROUTINE kiss_sample  ***
+      !!
+      !! ** Purpose :   Select a random sample of size k from a set of n integers
+      !!
+      !! ** Method  :   The sample is output in the first k elements of a
+      !!                Set k equal to n to obtain a random permutation
+      !!                  of the whole set of integers
+      !!
+      !! --------------------------------------------------------------------
+      IMPLICIT NONE
+      INTEGER(KIND=i8), DIMENSION(:) :: a
+      INTEGER(KIND=i8) :: n, k, i, j, atmp
+      REAL(KIND=wp) :: uran
+
+      ! Select the sample using the swapping method
+      ! (see Devroye, Non-Uniform Random Variate Generation, p. 612)
+      DO i=1,k
+         ! Randomly select the swapping element between i and n (inclusive)
+         CALL kiss_uniform(uran)
+         j = i - 1 + CEILING( REAL(n-i+1,8) * uran )
+         ! Swap elements i and j
+         atmp = a(i) ; a(i) = a(j) ; a(j) = atmp
+      ENDDO
+
+   END SUBROUTINE kiss_sample
+!$AGRIF_END_DO_NOT_TREAT
+END MODULE storng
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/eosbn2.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/eosbn2.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/eosbn2.F90	(revision 14097)
@@ -0,0 +1,1704 @@
+MODULE eosbn2
+   !!==============================================================================
+   !!                       ***  MODULE  eosbn2  ***
+   !! Equation Of Seawater : in situ density - Brunt-Vaisala frequency
+   !!==============================================================================
+   !! History :  OPA  ! 1989-03  (O. Marti)  Original code
+   !!            6.0  ! 1994-07  (G. Madec, M. Imbard)  add bn2
+   !!            6.0  ! 1994-08  (G. Madec)  Add Jackett & McDougall eos
+   !!            7.0  ! 1996-01  (G. Madec)  statement function for e3
+   !!            8.1  ! 1997-07  (G. Madec)  density instead of volumic mass
+   !!             -   ! 1999-02  (G. Madec, N. Grima) semi-implicit pressure gradient
+   !!            8.2  ! 2001-09  (M. Ben Jelloul)  bugfix on linear eos
+   !!   NEMO     1.0  ! 2002-10  (G. Madec)  add eos_init
+   !!             -   ! 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 (now eos_fzp function)
+   !!            3.3  ! 2010-05  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!             -   ! 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
+   !!             -   ! 2015-06  (P.A. Bouttier) eos_fzp functions changed to subroutines for AGRIF
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   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_2d : Compute the in situ density for 2d fields
+   !!   bn2           : Compute the Brunt-Vaisala frequency
+   !!   bn2           : compute the Brunt-Vaisala frequency
+   !!   eos_pt_from_ct: compute the potential temperature from the Conservative Temperature
+   !!   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 stopar         ! Stochastic T/S fluctuations
+   USE stopts         ! Stochastic T/S fluctuations
+   !
+   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 lbclnk         ! ocean lateral boundary conditions
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !                  !! * Interface
+   INTERFACE eos
+      MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d
+   END INTERFACE
+   !
+   INTERFACE eos_rab
+      MODULE PROCEDURE rab_3d, rab_2d, rab_0d
+   END INTERFACE
+   !
+   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 **
+   LOGICAL , PUBLIC ::   ln_TEOS10
+   LOGICAL , PUBLIC ::   ln_EOS80
+   LOGICAL , PUBLIC ::   ln_SEOS
+
+   ! Parameters
+   LOGICAL , PUBLIC    ::   l_useCT         ! =T in ln_TEOS10=T (i.e. use eos_pt_from_ct to compute sst_m), =F otherwise
+   INTEGER , PUBLIC    ::   neos            ! Identifier for equation of state used
+
+   INTEGER , PARAMETER ::   np_teos10 = -1  ! parameter for using TEOS10
+   INTEGER , PARAMETER ::   np_eos80  =  0  ! parameter for using EOS80
+   INTEGER , PARAMETER ::   np_seos   = 1   ! parameter for using Simplified Equation of state
+
+   !                               !!!  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
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE eos_insitu( pts, prd, pdep )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE eos_insitu  ***
+      !!
+      !! ** Purpose :   Compute the in situ density (ratio rho/rau0) from
+      !!       potential temperature and salinity using an equation of state
+      !!       selected in the nameos namelist
+      !!
+      !! ** 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
+      !!
+      !!     ln_teos10 : 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 Celsius, sa=35.5 g/kg
+      !!
+      !!     ln_eos80 : 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 Celsius, sp=35.5 psu
+      !!
+      !!     ln_seos : 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 :   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  [Celsius]
+      !                                                               ! 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( ln_timing )   CALL timing_start('eos-insitu')
+      !
+      SELECT CASE( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  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( np_seos )                !==  simplified EOS  ==!
+         !
+         DO jk = 1, jpkm1
+            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
+         !
+      END SELECT
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-insitu  : ', kdim=jpk )
+      !
+      IF( ln_timing )   CALL timing_stop('eos-insitu')
+      !
+   END SUBROUTINE eos_insitu
+
+
+   SUBROUTINE eos_insitu_pot( pts, prd, prhop, pdep )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE eos_insitu_pot  ***
+      !!
+      !! ** Purpose :   Compute the in situ density (ratio rho/rau0) and the
+      !!      potential volumic mass (Kg/m3) from potential temperature and
+      !!      salinity fields using an equation of state selected in the
+      !!     namelist.
+      !!
+      !! ** Action  : - prd  , the in situ density (no units)
+      !!              - prhop, the potential volumic mass (Kg/m3)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celsius]
+      !                                                                ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd    ! in situ density            [-]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prhop  ! potential density (surface referenced)
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep   ! depth                      [m]
+      !
+      INTEGER  ::   ji, jj, jk, jsmp             ! dummy loop indices
+      INTEGER  ::   jdof
+      REAL(wp) ::   zt , zh , zstemp, zs , ztm   ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3      !   -      -
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: zn0_sto, zn_sto, zsign    ! local vectors
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('eos-pot')
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         ! Stochastic equation of state
+         IF ( ln_sto_eos ) THEN
+            ALLOCATE(zn0_sto(1:2*nn_sto_eos))
+            ALLOCATE(zn_sto(1:2*nn_sto_eos))
+            ALLOCATE(zsign(1:2*nn_sto_eos))
+            DO jsmp = 1, 2*nn_sto_eos, 2
+              zsign(jsmp)   = 1._wp
+              zsign(jsmp+1) = -1._wp
+            END DO
+            !
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     !
+                     ! compute density (2*nn_sto_eos) times:
+                     ! (1) for t+dt, s+ds (with the random TS fluctutation computed in sto_pts)
+                     ! (2) for t-dt, s-ds (with the opposite fluctuation)
+                     DO jsmp = 1, nn_sto_eos*2
+                        jdof   = (jsmp + 1) / 2
+                        zh     = pdep(ji,jj,jk) * r1_Z0                                  ! depth
+                        zt     = (pts (ji,jj,jk,jp_tem) + pts_ran(ji,jj,jk,jp_tem,jdof) * zsign(jsmp)) * r1_T0    ! temperature
+                        zstemp = pts  (ji,jj,jk,jp_sal) + pts_ran(ji,jj,jk,jp_sal,jdof) * zsign(jsmp)
+                        zs     = SQRT( ABS( zstemp + 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_sto(jsmp) = (((((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_sto(jsmp)  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0_sto(jsmp)
+                     END DO
+                     !
+                     ! compute stochastic density as the mean of the (2*nn_sto_eos) densities
+                     prhop(ji,jj,jk) = 0._wp ; prd(ji,jj,jk) = 0._wp
+                     DO jsmp = 1, nn_sto_eos*2
+                        prhop(ji,jj,jk) = prhop(ji,jj,jk) + zn0_sto(jsmp)                      ! potential density referenced at the surface
+                        !
+                        prd(ji,jj,jk) = prd(ji,jj,jk) + (  zn_sto(jsmp) * r1_rau0 - 1._wp  )   ! density anomaly (masked)
+                     END DO
+                     prhop(ji,jj,jk) = 0.5_wp * prhop(ji,jj,jk) * ztm / nn_sto_eos
+                     prd  (ji,jj,jk) = 0.5_wp * prd  (ji,jj,jk) * ztm / nn_sto_eos
+                  END DO
+               END DO
+            END DO
+            DEALLOCATE(zn0_sto,zn_sto,zsign)
+         ! Non-stochastic equation of state
+         ELSE
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     !
+                     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
+         ENDIF
+         
+      CASE( np_seos )                !==  simplified EOS  ==!
+         !
+         DO jk = 1, jpkm1
+            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
+         !
+      END SELECT
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-pot: ', tab3d_2=prhop, clinfo2=' pot : ', kdim=jpk )
+      !
+      IF( ln_timing )   CALL timing_stop('eos-pot')
+      !
+   END SUBROUTINE eos_insitu_pot
+
+
+   SUBROUTINE eos_insitu_2d( pts, pdep, prd )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE eos_insitu_2d  ***
+      !!
+      !! ** Purpose :   Compute the in situ density (ratio rho/rau0) from
+      !!      potential temperature and salinity using an equation of state
+      !!      selected in the nameos namelist. * 2D field case
+      !!
+      !! ** Action  : - prd , the in situ density (no units) (unmasked)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celsius]
+      !                                                           ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(in   ) ::   pdep  ! depth                      [m]
+      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(  out) ::   prd   ! in situ density
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs              ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('eos2d')
+      !
+      prd(:,:) = 0._wp
+      !
+      SELECT CASE( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  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
+               !
+               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( 'eosbn2', prd, 'T', 1. )                    ! Lateral boundary conditions
+         !
+      CASE( np_seos )                !==  simplified EOS  ==!
+         !
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               !
+               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
+         !
+         CALL lbc_lnk( 'eosbn2', prd, 'T', 1. )                    ! Lateral boundary conditions
+         !
+      END SELECT
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=prd, clinfo1=' eos2d: ' )
+      !
+      IF( ln_timing )   CALL timing_stop('eos2d')
+      !
+   END SUBROUTINE eos_insitu_2d
+
+
+   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( ln_timing )   CALL timing_start('rab_3d')
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  zh  = gdept_n(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( np_seos )                  !==  simplified EOS  ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  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  = gdept_n(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
+         !
+      CASE DEFAULT
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'rab_3d:', ctmp1 )
+         !
+      END SELECT
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pab(:,:,:,jp_tem), clinfo1=' rab_3d_t: ', &
+         &                       tab3d_2=pab(:,:,:,jp_sal), clinfo2=' rab_3d_s : ', kdim=jpk )
+      !
+      IF( ln_timing )   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( ln_timing )   CALL timing_start('rab_2d')
+      !
+      pab(:,:,:) = 0._wp
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  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
+         !                            ! Lateral boundary conditions
+         CALL lbc_lnk_multi( 'eosbn2', pab(:,:,jp_tem), 'T', 1. , pab(:,:,jp_sal), 'T', 1. )                    
+         !
+      CASE( np_seos )                  !==  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
+         !                            ! Lateral boundary conditions
+         CALL lbc_lnk_multi( 'eosbn2', pab(:,:,jp_tem), 'T', 1. , pab(:,:,jp_sal), 'T', 1. )                    
+         !
+      CASE DEFAULT
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'rab_2d:', ctmp1 )
+         !
+      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( ln_timing )   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( ln_timing )   CALL timing_start('rab_0d')
+      !
+      pab(:) = 0._wp
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )      !==  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( np_seos )                  !==  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
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'rab_0d:', ctmp1 )
+         !
+      END SELECT
+      !
+      IF( ln_timing )   CALL timing_stop('rab_0d')
+      !
+   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   [Celsius,psu]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celsius-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( ln_timing )   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 =   ( gdepw_n(ji,jj,jk  ) - gdept_n(ji,jj,jk) )   &
+                  &  / ( gdept_n(ji,jj,jk-1) - gdept_n(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) )  )  &
+                  &            / e3w_n(ji,jj,jk) * wmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pn2, clinfo1=' bn2  : ', kdim=jpk )
+      !
+      IF( ln_timing )   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. [Celsius]
+      !!
+      !! ** 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   [Celsius]
+      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 [Celsius]
+      !
+      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( ln_timing )   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( ln_timing )   CALL timing_stop('eos_pt_from_ct')
+      !
+   END FUNCTION eos_pt_from_ct
+
+
+   SUBROUTINE  eos_fzp_2d( psal, ptf, pdep )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_fzp  ***
+      !!
+      !! ** Purpose :   Compute the freezing point temperature [Celsius]
+      !!
+      !! ** Method  :   UNESCO freezing point (ptf) in Celsius 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), INTENT(out  )           ::   ptf    ! freezing temperature [Celsius]
+      !
+      INTEGER  ::   ji, jj          ! dummy loop indices
+      REAL(wp) ::   zt, zs, z1_S0   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( neos )
+      !
+      CASE ( np_teos10, np_seos )      !==  CT,SA (TEOS-10 and S-EOS formulations) ==!
+         !
+         z1_S0 = 1._wp / 35.16504_wp
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zs= SQRT( ABS( psal(ji,jj) ) * z1_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 ( np_eos80 )                !==  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
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'eos_fzp_2d:', ctmp1 )
+         !
+      END SELECT      
+      !
+  END SUBROUTINE eos_fzp_2d
+
+
+  SUBROUTINE eos_fzp_0d( psal, ptf, pdep )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_fzp  ***
+      !!
+      !! ** Purpose :   Compute the freezing point temperature [Celsius]
+      !!
+      !! ** Method  :   UNESCO freezing point (ptf) in Celsius 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), INTENT(out)           ::   ptf          ! freezing temperature [Celsius]
+      !
+      REAL(wp) :: zs   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( neos )
+      !
+      CASE ( np_teos10, np_seos )      !==  CT,SA (TEOS-10 and S-EOS formulations) ==!
+         !
+         zs  = SQRT( ABS( psal ) / 35.16504_wp )           ! 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 ( np_eos80 )                !==  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
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'eos_fzp_0d:', ctmp1 )
+         !
+      END SELECT
+      !
+   END SUBROUTINE 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( ln_timing )   CALL timing_start('eos_pen')
+      !
+      SELECT CASE ( neos )
+      !
+      CASE( np_teos10, np_eos80 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  zh  = gdept_n(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( np_seos )                !==  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  = gdept_n(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
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos
+         CALL ctl_stop( 'eos_pen:', ctmp1 )
+         !
+      END SELECT
+      !
+      IF( ln_timing )   CALL timing_stop('eos_pen')
+      !
+   END SUBROUTINE eos_pen
+
+
+   SUBROUTINE eos_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_init  ***
+      !!
+      !! ** Purpose :   initializations for the equation of state
+      !!
+      !! ** Method  :   Read the namelist nameos and control the parameters
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ios   ! local integer
+      INTEGER  ::   ioptio   ! local integer
+      !!
+      NAMELIST/nameos/ ln_TEOS10, ln_EOS80, ln_SEOS, 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' )
+      !
+      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' )
+      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
+         WRITE(numout,*)
+         WRITE(numout,*) 'eos_init : equation of state'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist nameos : Chosen the Equation Of Seawater (EOS)'
+         WRITE(numout,*) '      TEOS-10 : rho=F(Conservative Temperature, Absolute  Salinity, depth)   ln_TEOS10 = ', ln_TEOS10
+         WRITE(numout,*) '      EOS-80  : rho=F(Potential    Temperature, Practical Salinity, depth)   ln_EOS80  = ', ln_EOS80
+         WRITE(numout,*) '      S-EOS   : rho=F(Conservative Temperature, Absolute  Salinity, depth)   ln_SEOS   = ', ln_SEOS
+      ENDIF
+
+      ! Check options for equation of state & set neos based on logical flags
+      ioptio = 0
+      IF( ln_TEOS10 ) THEN   ;   ioptio = ioptio+1   ;   neos = np_teos10   ;   ENDIF
+      IF( ln_EOS80  ) THEN   ;   ioptio = ioptio+1   ;   neos = np_eos80    ;   ENDIF
+      IF( ln_SEOS   ) THEN   ;   ioptio = ioptio+1   ;   neos = np_seos     ;   ENDIF
+      IF( ioptio /= 1 )   CALL ctl_stop("Exactly one equation of state option must be selected")
+      !
+      SELECT CASE( neos )         ! check option
+      !
+      CASE( np_teos10 )                       !==  polynomial TEOS-10  ==!
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   use of TEOS-10 equation of state (cons. temp. and abs. salinity)'
+         !
+         l_useCT = .TRUE.                          ! model temperature is Conservative temperature 
+         !
+         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( np_eos80 )                        !==  polynomial EOS-80 formulation  ==!
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   use of EOS-80 equation of state (pot. temp. and pract. salinity)'
+         !
+         l_useCT = .FALSE.                         ! model temperature is Potential temperature
+         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( np_seos )                        !==  Simplified EOS     ==!
+
+         r1_S0  = 0.875_wp/35.16504_wp   ! Used to convert CT in potential temperature when using bulk formulae (eos_pt_from_ct)
+         
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   use of simplified eos:    '
+            WRITE(numout,*) '              rhd(dT=T-10,dS=S-35,Z) = [-a0*(1+lambda1/2*dT+mu1*Z)*dT '
+            WRITE(numout,*) '                                       + b0*(1+lambda2/2*dT+mu2*Z)*dS - nu*dT*dS] / rau0'
+            WRITE(numout,*) '              with the following coefficients :'
+            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
+         l_useCT = .TRUE.          ! Use conservative temperature
+         !
+      CASE DEFAULT                     !==  ERROR in neos  ==!
+         WRITE(ctmp1,*) '          bad flag value for neos = ', neos, '. You should never see this error'
+         CALL ctl_stop( ctmp1 )
+         !
+      END SELECT
+      !
+      rau0_rcp    = rau0 * rcp 
+      r1_rau0     = 1._wp / rau0
+      r1_rcp      = 1._wp / rcp
+      r1_rau0_rcp = 1._wp / rau0_rcp 
+      !
+      IF(lwp) THEN
+         IF( l_useCT )   THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   model uses Conservative Temperature'
+            WRITE(numout,*) '           Important: model must be initialized with CT and SA fields'
+         ELSE
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   model does not use Conservative Temperature'
+         ENDIF
+      ENDIF
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '   Associated physical constant'
+      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,*) '      rau0 * rcp                       rau0_rcp = ', rau0_rcp
+      IF(lwp) WRITE(numout,*) '      1. / ( rau0 * rcp )           r1_rau0_rcp = ', r1_rau0_rcp
+      !
+   END SUBROUTINE eos_init
+
+   !!======================================================================
+END MODULE eosbn2
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv.F90	(revision 14097)
@@ -0,0 +1,274 @@
+MODULE traadv
+   !!==============================================================================
+   !!                       ***  MODULE  traadv  ***
+   !! Ocean active tracers:  advection trend 
+   !!==============================================================================
+   !! History :  2.0  !  2005-11  (G. Madec)  Original code
+   !!            3.3  !  2010-09  (C. Ethe, G. Madec)  merge TRC-TRA + switch from velocity to transport
+   !!            3.6  !  2011-06  (G. Madec)  Addition of Mixed Layer Eddy parameterisation
+   !!            3.7  !  2014-05  (G. Madec)  Add 2nd/4th order cases for CEN and FCT schemes 
+   !!             -   !  2014-12  (G. Madec) suppression of cross land advection option
+   !!            3.6  !  2015-06  (E. Clementi) Addition of Stokes drift in case of wave coupling
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv       : compute ocean tracer advection trend
+   !!   tra_adv_init  : control the different options of advection scheme
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE domvvl         ! variable vertical scale factors
+   USE sbcwave        ! wave module
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE traadv_cen     ! centered scheme            (tra_adv_cen  routine)
+   USE traadv_fct     ! FCT      scheme            (tra_adv_fct  routine)
+   USE traadv_mus     ! MUSCL    scheme            (tra_adv_mus  routine)
+   USE traadv_ubs     ! UBS      scheme            (tra_adv_ubs  routine)
+   USE traadv_qck     ! QUICKEST scheme            (tra_adv_qck  routine)
+   USE tramle         ! Mixed Layer Eddy transport (tra_mle_trp  routine)
+   USE ldftra         ! Eddy Induced transport     (ldf_eiv_trp  routine)
+   USE ldfslp         ! Lateral diffusion: slopes of neutral surfaces
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+   USE diaptr         ! Poleward heat transport 
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O module
+   USE prtctl         ! Print control
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv        ! called by step.F90
+   PUBLIC   tra_adv_init   ! called by nemogcm.F90
+
+   !                            !!* Namelist namtra_adv *
+   LOGICAL ::   ln_traadv_OFF    ! no advection on T and S
+   LOGICAL ::   ln_traadv_cen    ! centered scheme flag
+   INTEGER ::      nn_cen_h, nn_cen_v   ! =2/4 : horizontal and vertical choices of the order of CEN scheme
+   LOGICAL ::   ln_traadv_fct    ! FCT scheme flag
+   INTEGER ::      nn_fct_h, nn_fct_v   ! =2/4 : horizontal and vertical choices of the order of FCT scheme
+   LOGICAL ::   ln_traadv_mus    ! MUSCL scheme flag
+   LOGICAL ::      ln_mus_ups           ! use upstream scheme in vivcinity of river mouths
+   LOGICAL ::   ln_traadv_ubs    ! UBS scheme flag
+   INTEGER ::      nn_ubs_v             ! =2/4 : vertical choice of the order of UBS scheme
+   LOGICAL ::   ln_traadv_qck    ! QUICKEST scheme flag
+
+   INTEGER ::   nadv             ! choice of the type of advection scheme
+   !                             ! associated indices:
+   INTEGER, PARAMETER ::   np_NO_adv  = 0   ! no T-S advection
+   INTEGER, PARAMETER ::   np_CEN     = 1   ! 2nd/4th order centered scheme
+   INTEGER, PARAMETER ::   np_FCT     = 2   ! 2nd/4th order Flux Corrected Transport scheme
+   INTEGER, PARAMETER ::   np_MUS     = 3   ! MUSCL scheme
+   INTEGER, PARAMETER ::   np_UBS     = 4   ! 3rd order Upstream Biased Scheme
+   INTEGER, PARAMETER ::   np_QCK     = 5   ! QUICK scheme
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv  ***
+      !!
+      !! ** Purpose :   compute the ocean tracer advection trend.
+      !!
+      !! ** Method  : - Update (ua,va) with the advection term following nadv
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   jk   ! dummy loop index
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        :: zun, zvn, zwn   ! 3D workspace
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_adv')
+      !
+      !                                          ! set time step
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;   r2dt =         rdt   ! at nit000             (Euler)
+      ELSEIF( kt <= nit000 + 1 )           THEN   ;   r2dt = 2._wp * rdt   ! at nit000 or nit000+1 (Leapfrog)
+      ENDIF
+      !
+      !                                         !==  effective transport  ==!
+      zun(:,:,jpk) = 0._wp
+      zvn(:,:,jpk) = 0._wp
+      zwn(:,:,jpk) = 0._wp
+      IF( ln_wave .AND. ln_sdw )  THEN
+         DO jk = 1, jpkm1                                                       ! eulerian transport + Stokes Drift
+            zun(:,:,jk) = e2u  (:,:) * e3u_n(:,:,jk) * ( un(:,:,jk) + usd(:,:,jk) )
+            zvn(:,:,jk) = e1v  (:,:) * e3v_n(:,:,jk) * ( vn(:,:,jk) + vsd(:,:,jk) )
+            zwn(:,:,jk) = e1e2t(:,:)                 * ( wn(:,:,jk) + wsd(:,:,jk) )
+         END DO
+      ELSE
+         DO jk = 1, jpkm1
+            zun(:,:,jk) = e2u  (:,:) * e3u_n(:,:,jk) * un(:,:,jk)               ! eulerian transport only
+            zvn(:,:,jk) = e1v  (:,:) * e3v_n(:,:,jk) * vn(:,:,jk)
+            zwn(:,:,jk) = e1e2t(:,:)                 * wn(:,:,jk)
+         END DO
+      ENDIF
+      !
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN                                ! add z-tilde and/or vvl corrections
+         zun(:,:,:) = zun(:,:,:) + un_td(:,:,:)
+         zvn(:,:,:) = zvn(:,:,:) + vn_td(:,:,:)
+      ENDIF
+      !
+      zun(:,:,jpk) = 0._wp                                                      ! no transport trough the bottom
+      zvn(:,:,jpk) = 0._wp
+      zwn(:,:,jpk) = 0._wp
+      !
+      IF( ln_ldfeiv .AND. .NOT. ln_traldf_triad )   &
+         &              CALL ldf_eiv_trp( kt, nit000, zun, zvn, zwn, 'TRA' )   ! add the eiv transport (if necessary)
+      !
+      IF( ln_mle    )   CALL tra_mle_trp( kt, nit000, zun, zvn, zwn, 'TRA' )   ! add the mle transport (if necessary)
+      !
+      CALL iom_put( "uocetr_eff", zun )                                        ! output effective transport      
+      CALL iom_put( "vocetr_eff", zvn )
+      CALL iom_put( "wocetr_eff", zwn )
+      !
+!!gm ???
+      IF( ln_diaptr )   CALL dia_ptr( zvn )                                    ! diagnose the effective MSF 
+!!gm ???
+      !
+      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk), ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
+      SELECT CASE ( nadv )                      !==  compute advection trend and add it to general trend  ==!
+      !
+      CASE ( np_CEN )                                 ! Centered scheme : 2nd / 4th order
+         CALL tra_adv_cen    ( kt, nit000, 'TRA',         zun, zvn, zwn     , tsn, tsa, jpts, nn_cen_h, nn_cen_v )
+      CASE ( np_FCT )                                 ! FCT scheme      : 2nd / 4th order
+         CALL tra_adv_fct    ( kt, nit000, 'TRA', r2dt, zun, zvn, zwn, tsb, tsn, tsa, jpts, nn_fct_h, nn_fct_v )
+      CASE ( np_MUS )                                 ! MUSCL
+         CALL tra_adv_mus    ( kt, nit000, 'TRA', r2dt, zun, zvn, zwn, tsb,      tsa, jpts        , ln_mus_ups ) 
+      CASE ( np_UBS )                                 ! UBS
+         CALL tra_adv_ubs    ( kt, nit000, 'TRA', r2dt, zun, zvn, zwn, tsb, tsn, tsa, jpts        , nn_ubs_v   )
+      CASE ( np_QCK )                                 ! QUICKEST
+         CALL tra_adv_qck    ( kt, nit000, 'TRA', r2dt, zun, zvn, zwn, tsb, tsn, tsa, jpts                     )
+      !
+      END SELECT
+      !
+      IF( l_trdtra )   THEN                      ! save the advective trends for further diagnostics
+         DO jk = 1, jpkm1
+            ztrdt(:,:,jk) = tsa(:,:,jk,jp_tem) - ztrdt(:,:,jk)
+            ztrds(:,:,jk) = tsa(:,:,jk,jp_sal) - ztrds(:,:,jk)
+         END DO
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_totad, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_totad, ztrds )
+         DEALLOCATE( ztrdt, ztrds )
+      ENDIF
+      !                                              ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' adv  - Ta: ', mask1=tmask,               &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop( 'tra_adv' )
+      !
+   END SUBROUTINE tra_adv
+
+
+   SUBROUTINE tra_adv_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_init  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options for 
+      !!              tracer advection schemes and set nadv
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios   ! Local integers
+      !
+      NAMELIST/namtra_adv/ ln_traadv_OFF,                        &   ! No advection
+         &                 ln_traadv_cen , nn_cen_h, nn_cen_v,   &   ! CEN
+         &                 ln_traadv_fct , nn_fct_h, nn_fct_v,   &   ! FCT
+         &                 ln_traadv_mus , ln_mus_ups,           &   ! MUSCL
+         &                 ln_traadv_ubs ,           nn_ubs_v,   &   ! UBS
+         &                 ln_traadv_qck                             ! QCK
+      !!----------------------------------------------------------------------
+      !
+      !                                !==  Namelist  ==!
+      REWIND( numnam_ref )                   ! Namelist namtra_adv in reference namelist : Tracer advection scheme
+      READ  ( numnam_ref, namtra_adv, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_adv in reference namelist' )
+      !
+      REWIND( numnam_cfg )                   ! Namelist namtra_adv in configuration namelist : Tracer advection scheme
+      READ  ( numnam_cfg, namtra_adv, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_adv in configuration namelist' )
+      IF(lwm) WRITE( numond, namtra_adv )
+      !
+      IF(lwp) THEN                           ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_adv_init : choice/control of the tracer advection scheme'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtra_adv : chose a advection scheme for tracers'
+         WRITE(numout,*) '      No advection on T & S                     ln_traadv_OFF = ', ln_traadv_OFF
+         WRITE(numout,*) '      centered scheme                           ln_traadv_cen = ', ln_traadv_cen
+         WRITE(numout,*) '            horizontal 2nd/4th order               nn_cen_h   = ', nn_fct_h
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_cen_v   = ', nn_fct_v
+         WRITE(numout,*) '      Flux Corrected Transport scheme           ln_traadv_fct = ', ln_traadv_fct
+         WRITE(numout,*) '            horizontal 2nd/4th order               nn_fct_h   = ', nn_fct_h
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_fct_v   = ', nn_fct_v
+         WRITE(numout,*) '      MUSCL scheme                              ln_traadv_mus = ', ln_traadv_mus
+         WRITE(numout,*) '            + upstream scheme near river mouths    ln_mus_ups = ', ln_mus_ups
+         WRITE(numout,*) '      UBS scheme                                ln_traadv_ubs = ', ln_traadv_ubs
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_ubs_v   = ', nn_ubs_v
+         WRITE(numout,*) '      QUICKEST scheme                           ln_traadv_qck = ', ln_traadv_qck
+      ENDIF
+      !
+      !                                !==  Parameter control & set nadv ==!
+      ioptio = 0                       
+      IF( ln_traadv_OFF ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_NO_adv   ;   ENDIF
+      IF( ln_traadv_cen ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_CEN      ;   ENDIF
+      IF( ln_traadv_fct ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_FCT      ;   ENDIF
+      IF( ln_traadv_mus ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_MUS      ;   ENDIF
+      IF( ln_traadv_ubs ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_UBS      ;   ENDIF
+      IF( ln_traadv_qck ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_QCK      ;   ENDIF
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'tra_adv_init: Choose ONE advection option in namelist namtra_adv' )
+      !
+      IF( ln_traadv_cen .AND. ( nn_cen_h /= 2 .AND. nn_cen_h /= 4 )   &          ! Centered
+                        .AND. ( nn_cen_v /= 2 .AND. nn_cen_v /= 4 )   ) THEN
+        CALL ctl_stop( 'tra_adv_init: CEN scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_traadv_fct .AND. ( nn_fct_h /= 2 .AND. nn_fct_h /= 4 )   &          ! FCT
+                        .AND. ( nn_fct_v /= 2 .AND. nn_fct_v /= 4 )   ) THEN
+        CALL ctl_stop( 'tra_adv_init: FCT scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_traadv_ubs .AND. ( nn_ubs_v /= 2 .AND. nn_ubs_v /= 4 )   ) THEN     ! UBS
+        CALL ctl_stop( 'tra_adv_init: UBS scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_traadv_ubs .AND. nn_ubs_v == 4 ) THEN
+         CALL ctl_warn( 'tra_adv_init: UBS scheme, only 2nd FCT scheme available on the vertical. It will be used' )
+      ENDIF
+      IF( ln_isfcav ) THEN                                                       ! ice-shelf cavities
+         IF(  ln_traadv_cen .AND. nn_cen_v == 4    .OR.   &                            ! NO 4th order with ISF
+            & ln_traadv_fct .AND. nn_fct_v == 4   )   CALL ctl_stop( 'tra_adv_init: 4th order COMPACT scheme not allowed with ISF' )
+      ENDIF
+      !
+      !                                !==  Print the choice  ==!  
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE ( nadv )
+         CASE( np_NO_adv  )   ;   WRITE(numout,*) '   ==>>>   NO T-S advection'
+         CASE( np_CEN     )   ;   WRITE(numout,*) '   ==>>>   CEN      scheme is used. Horizontal order: ', nn_cen_h,   &
+            &                                                                        ' Vertical   order: ', nn_cen_v
+         CASE( np_FCT     )   ;   WRITE(numout,*) '   ==>>>   FCT      scheme is used. Horizontal order: ', nn_fct_h,   &
+            &                                                                        ' Vertical   order: ', nn_fct_v
+         CASE( np_MUS     )   ;   WRITE(numout,*) '   ==>>>   MUSCL    scheme is used'
+         CASE( np_UBS     )   ;   WRITE(numout,*) '   ==>>>   UBS      scheme is used'
+         CASE( np_QCK     )   ;   WRITE(numout,*) '   ==>>>   QUICKEST scheme is used'
+         END SELECT
+      ENDIF
+      !
+      CALL tra_mle_init            !== initialisation of the Mixed Layer Eddy parametrisation (MLE)  ==!
+      !
+   END SUBROUTINE tra_adv_init
+
+  !!======================================================================
+END MODULE traadv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_cen.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_cen.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_cen.F90	(revision 14097)
@@ -0,0 +1,208 @@
+MODULE traadv_cen
+   !!======================================================================
+   !!                     ***  MODULE  traadv_cen  ***
+   !! Ocean  tracers:   advective trend (2nd/4th order centered)
+   !!======================================================================
+   !! History :  3.7  ! 2014-05  (G. Madec)  original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv_cen   : update the tracer trend with the advection trends using a centered or scheme (2nd or 4th order)
+   !!                   NB: on the vertical it is actually a 4th order COMPACT scheme which is used
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE eosbn2         ! equation of state
+   USE traadv_fct     ! acces to routine interp_4th_cpt 
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! IOM library
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_cen   ! called by traadv.F90
+   
+   REAL(wp) ::   r1_6 = 1._wp / 6._wp   ! =1/6
+
+   LOGICAL ::   l_trd   ! flag to compute trends
+   LOGICAL ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL ::   l_hst   ! flag to compute heat/salt transport
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_cen( kt, kit000, cdtype, pun, pvn, pwn,     &
+      &                                        ptn, pta, kjpt, kn_cen_h, kn_cen_v ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_cen  ***
+      !!                 
+      !! ** Purpose :   Compute the now trend due to the advection of tracers
+      !!      and add it to the general trend of passive tracer equations.
+      !!
+      !! ** Method  :   The advection is evaluated by a 2nd or 4th order scheme
+      !!               using now fields (leap-frog scheme). 
+      !!       kn_cen_h = 2  ==>> 2nd order centered scheme on the horizontal
+      !!                = 4  ==>> 4th order    -        -       -      -
+      !!       kn_cen_v = 2  ==>> 2nd order centered scheme on the vertical
+      !!                = 4  ==>> 4th order COMPACT  scheme     -      -
+      !!
+      !! ** Action : - update pta  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostcs (l_trdtra=T)
+      !!             - htr_adv, str_adv : poleward advective heat and salt transport (ln_diaptr=T)
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kn_cen_h        ! =2/4 (2nd or 4th order scheme)
+      INTEGER                              , INTENT(in   ) ::   kn_cen_v        ! =2/4 (2nd or 4th order scheme)
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pun, pvn, pwn   ! 3 ocean velocity components
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptn             ! now tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::   ierr             ! local integer
+      REAL(wp) ::   zC2t_u, zC4t_u   ! local scalars
+      REAL(wp) ::   zC2t_v, zC4t_v   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zwy, zwz, ztu, ztv, ztw
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_cen : centered advection scheme on ', cdtype, ' order h/v =', kn_cen_h,'/', kn_cen_v
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+      !                          ! set local switches
+      l_trd = .FALSE.
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )        l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ln_diaptr )                                                 l_ptr = .TRUE. 
+      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )   l_hst = .TRUE.
+      !
+      !                    
+      zwz(:,:, 1 ) = 0._wp       ! surface & bottom vertical flux set to zero for all tracers
+      zwz(:,:,jpk) = 0._wp
+      !
+      DO jn = 1, kjpt            !==  loop over the tracers  ==!
+         !
+         SELECT CASE( kn_cen_h )       !--  Horizontal fluxes  --!
+         !
+         CASE(  2  )                         !* 2nd order centered
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     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
+            END DO
+            !
+         CASE(  4  )                         !* 4th order centered
+            ztu(:,:,jpk) = 0._wp                   ! Bottom value : flux set to zero
+            ztv(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1                       ! masked gradient
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ztu(ji,jj,jk) = ( ptn(ji+1,jj  ,jk,jn) - ptn(ji,jj,jk,jn) ) * umask(ji,jj,jk)
+                     ztv(ji,jj,jk) = ( ptn(ji  ,jj+1,jk,jn) - ptn(ji,jj,jk,jn) ) * vmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'traadv_cen', ztu, 'U', -1. , ztv, 'V', -1. )   ! Lateral boundary cond.
+            !
+            DO jk = 1, jpkm1                       ! Horizontal advective fluxes
+               DO jj = 2, jpjm1
+                  DO ji = 2, fs_jpim1   ! vector opt.
+                     zC2t_u = ptn(ji,jj,jk,jn) + ptn(ji+1,jj  ,jk,jn)   ! C2 interpolation of T at u- & v-points (x2)
+                     zC2t_v = ptn(ji,jj,jk,jn) + ptn(ji  ,jj+1,jk,jn)
+                     !                                                  ! C4 interpolation of T at u- & v-points (x2)
+                     zC4t_u =  zC2t_u + r1_6 * ( ztu(ji-1,jj,jk) - ztu(ji+1,jj,jk) )
+                     zC4t_v =  zC2t_v + r1_6 * ( ztv(ji,jj-1,jk) - ztv(ji,jj+1,jk) )
+                     !                                                  ! C4 fluxes
+                     zwx(ji,jj,jk) =  0.5_wp * pun(ji,jj,jk) * zC4t_u
+                     zwy(ji,jj,jk) =  0.5_wp * pvn(ji,jj,jk) * zC4t_v
+                  END DO
+               END DO
+            END DO         
+            CALL lbc_lnk_multi( 'traadv_cen', zwx, 'U', -1. , zwy, 'V', -1. )
+            !
+         CASE DEFAULT
+            CALL ctl_stop( 'traadv_cen: wrong value for nn_cen' )
+         END SELECT
+         !
+         SELECT CASE( kn_cen_v )       !--  Vertical fluxes  --!   (interior)
+         !
+         CASE(  2  )                         !* 2nd order centered
+            DO jk = 2, jpk
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zwz(ji,jj,jk) = 0.5 * pwn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj,jk-1,jn) ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         CASE(  4  )                         !* 4th order compact
+            CALL interp_4th_cpt( ptn(:,:,:,jn) , ztw )      ! ztw = interpolated value of T at w-point
+            DO jk = 2, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zwz(ji,jj,jk) = pwn(ji,jj,jk) * ztw(ji,jj,jk) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         END SELECT
+         !
+         IF( ln_linssh ) THEN                !* top value   (linear free surf. only as zwz is multiplied by wmask)
+            IF( ln_isfcav ) THEN                  ! ice-shelf cavities (top of the ocean)
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zwz(ji,jj, mikt(ji,jj) ) = pwn(ji,jj,mikt(ji,jj)) * ptn(ji,jj,mikt(ji,jj),jn) 
+                  END DO
+               END DO   
+            ELSE                                   ! no ice-shelf cavities (only ocean surface)
+               zwz(:,:,1) = pwn(:,:,1) * ptn(:,:,1,jn)
+            ENDIF
+         ENDIF
+         !               
+         DO jk = 1, jpkm1              !--  Divergence of advective fluxes  --!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn)    &
+                     &             - (  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)  ) * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !                             ! trend diagnostics
+         IF( l_trd ) 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 
+         IF( l_ptr )   CALL dia_ptr_hst( jn, 'adv', zwy(:,:,:) )
+         !                                 !  heat and salt transport
+         IF( l_hst )   CALL dia_ar5_hst( jn, 'adv', zwx(:,:,:), zwy(:,:,:) )
+         !
+      END DO
+      !
+   END SUBROUTINE tra_adv_cen
+   
+   !!======================================================================
+END MODULE traadv_cen
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_fct.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_fct.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_fct.F90	(revision 14097)
@@ -0,0 +1,793 @@
+MODULE traadv_fct
+   !!==============================================================================
+   !!                       ***  MODULE  traadv_fct  ***
+   !! Ocean  tracers:  horizontal & vertical advective trend (2nd/4th order Flux Corrected Transport method)
+   !!==============================================================================
+   !! History :  3.7  !  2015-09  (L. Debreu, G. Madec)  original code (inspired from traadv_tvd.F90)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  tra_adv_fct    : update the tracer trend with a 3D advective trends using a 2nd or 4th order FCT scheme
+   !!                   with sub-time-stepping in the vertical direction
+   !!  nonosc         : compute monotonic tracer fluxes by a non-oscillatory algorithm 
+   !!  interp_4th_cpt : 4th order compact scheme for the vertical component of the advection
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracers trends
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   USE phycst  , ONLY : rau0_rcp
+   USE zdf_oce , ONLY : ln_zad_Aimp
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! 
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_fct        ! called by traadv.F90
+   PUBLIC   interp_4th_cpt     ! called by traadv_cen.F90
+
+   LOGICAL  ::   l_trd   ! flag to compute trends
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat/salt transport
+   REAL(wp) ::   r1_6 = 1._wp / 6._wp   ! =1/6
+
+   !                                        ! tridiag solver associated indices:
+   INTEGER, PARAMETER ::   np_NH   = 0   ! Neumann homogeneous boundary condition
+   INTEGER, PARAMETER ::   np_CEN2 = 1   ! 2nd order centered  boundary condition
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_fct( kt, kit000, cdtype, p2dt, pun, pvn, pwn,       &
+      &                                              ptb, ptn, pta, kjpt, kn_fct_h, kn_fct_v )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_fct  ***
+      !! 
+      !! **  Purpose :   Compute the now trend due to total advection of tracers
+      !!               and add it to the general trend of tracer equations
+      !!
+      !! **  Method  : - 2nd or 4th FCT scheme on the horizontal direction
+      !!               (choice through the value of kn_fct)
+      !!               - on the vertical the 4th order is a compact scheme 
+      !!               - corrected flux (monotonic correction) 
+      !!
+      !! ** Action : - update pta  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostics (l_trdtra=T)
+      !!             - htr_adv, str_adv : poleward advective heat and salt transport (ln_diaptr=T)
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kn_fct_h        ! order of the FCT scheme (=2 or 4)
+      INTEGER                              , INTENT(in   ) ::   kn_fct_v        ! order of the FCT scheme (=2 or 4)
+      REAL(wp)                             , INTENT(in   ) ::   p2dt            ! 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 
+      !
+      INTEGER  ::   ji, jj, jk, jn                           ! dummy loop indices  
+      REAL(wp) ::   ztra                                     ! local scalar
+      REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk, zC2t_u, zC4t_u   !   -      -
+      REAL(wp) ::   zfm_ui, zfm_vj, zfm_wk, zC2t_v, zC4t_v   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk)        ::   zwi, zwx, zwy, zwz, ztu, ztv, zltu, zltv, ztw
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdx, ztrdy, ztrdz, zptry
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   zwinf, zwdia, zwsup
+      LOGICAL  ::   ll_zAimp                                 ! flag to apply adaptive implicit vertical advection
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_fct : FCT advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      l_trd = .FALSE.            ! set local switches
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      ll_zAimp = .FALSE.
+      IF( ( cdtype =='TRA' .AND. l_trdtra  ) .OR. ( cdtype =='TRC' .AND. l_trdtrc ) )       l_trd = .TRUE.
+      IF(   cdtype =='TRA' .AND. ln_diaptr )                                                l_ptr = .TRUE. 
+      IF(   cdtype =='TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR.  &
+         &                         iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+      !
+      IF( l_trd .OR. l_hst )  THEN
+         ALLOCATE( ztrdx(jpi,jpj,jpk), ztrdy(jpi,jpj,jpk), ztrdz(jpi,jpj,jpk) )
+         ztrdx(:,:,:) = 0._wp   ;    ztrdy(:,:,:) = 0._wp   ;   ztrdz(:,:,:) = 0._wp
+      ENDIF
+      !
+      IF( l_ptr ) THEN  
+         ALLOCATE( zptry(jpi,jpj,jpk) )
+         zptry(:,:,:) = 0._wp
+      ENDIF
+      !                          ! surface & bottom value : flux set to zero one for all
+      zwz(:,:, 1 ) = 0._wp            
+      zwx(:,:,jpk) = 0._wp   ;   zwy(:,:,jpk) = 0._wp    ;    zwz(:,:,jpk) = 0._wp
+      !
+      zwi(:,:,:) = 0._wp        
+      !
+      ! If adaptive vertical advection, check if it is needed on this PE at this time
+      IF( ln_zad_Aimp ) THEN
+         IF( MAXVAL( ABS( wi(:,:,:) ) ) > 0._wp ) ll_zAimp = .TRUE.
+      END IF
+      ! If active adaptive vertical advection, build tridiagonal matrix
+      IF( ll_zAimp ) THEN
+         ALLOCATE(zwdia(jpi,jpj,jpk), zwinf(jpi,jpj,jpk),zwsup(jpi,jpj,jpk))
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt. (ensure same order of calculation as below if wi=0.)
+                  zwdia(ji,jj,jk) =  1._wp + p2dt * ( MAX( wi(ji,jj,jk  ) , 0._wp ) - MIN( wi(ji,jj,jk+1) , 0._wp ) ) / e3t_a(ji,jj,jk)
+                  zwinf(ji,jj,jk) =  p2dt * MIN( wi(ji,jj,jk  ) , 0._wp ) / e3t_a(ji,jj,jk)
+                  zwsup(ji,jj,jk) = -p2dt * MAX( wi(ji,jj,jk+1) , 0._wp ) / e3t_a(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      END IF
+      !
+      DO jn = 1, kjpt            !==  loop over the tracers  ==!
+         !
+         !        !==  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 * ( zfp_ui * ptb(ji,jj,jk,jn) + zfm_ui * ptb(ji+1,jj  ,jk,jn) )
+                  zwy(ji,jj,jk) = 0.5 * ( 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 *!
+         DO jk = 2, jpkm1        ! Interior value ( multiplied by wmask)
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  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 * ( zfp_wk * ptb(ji,jj,jk,jn) + zfm_wk * ptb(ji,jj,jk-1,jn) ) * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         IF( ln_linssh ) THEN    ! top ocean value (only in linear free surface as zwz has been w-masked)
+            IF( ln_isfcav ) THEN             ! top of the ice-shelf cavities and at the ocean surface
+               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   
+            ELSE                             ! no cavities: only at the ocean surface
+               zwz(:,:,1) = pwn(:,:,1) * ptb(:,:,1,jn)
+            ENDIF
+         ENDIF
+         !               
+         DO jk = 1, jpkm1     !* trend and after field with monotonic scheme
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  !                             ! total intermediate advective trends
+                  ztra = - (  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) ) * r1_e1e2t(ji,jj)
+                  !                             ! update and guess with monotonic sheme
+                  pta(ji,jj,jk,jn) =                     pta(ji,jj,jk,jn) +        ztra   / e3t_n(ji,jj,jk) * tmask(ji,jj,jk)
+                  zwi(ji,jj,jk)    = ( e3t_b(ji,jj,jk) * ptb(ji,jj,jk,jn) + p2dt * ztra ) / e3t_a(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         
+         IF ( ll_zAimp ) THEN
+            CALL tridia_solver( zwdia, zwsup, zwinf, zwi, zwi , 0 )
+            !
+            ztw(:,:,1) = 0._wp ; ztw(:,:,jpk) = 0._wp ;
+            DO jk = 2, jpkm1        ! Interior value ( multiplied by wmask)
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.  
+                     zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+                     zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+                     ztw(ji,jj,jk) =  0.5 * e1e2t(ji,jj) * ( zfp_wk * zwi(ji,jj,jk) + zfm_wk * zwi(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+                     zwz(ji,jj,jk) = zwz(ji,jj,jk) + ztw(ji,jj,jk) ! update vertical fluxes
+                  END DO
+               END DO
+            END DO
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.  
+                     pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) - ( ztw(ji,jj,jk) - ztw(ji  ,jj  ,jk+1) ) &
+                        &                                  * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         END IF
+         !                
+         IF( l_trd .OR. l_hst )  THEN             ! trend diagnostics (contribution of upstream fluxes)
+            ztrdx(:,:,:) = zwx(:,:,:)   ;   ztrdy(:,:,:) = zwy(:,:,:)   ;   ztrdz(:,:,:) = zwz(:,:,:)
+         END IF
+         !                             ! "Poleward" heat and salt transports (contribution of upstream fluxes)
+         IF( l_ptr )   zptry(:,:,:) = zwy(:,:,:) 
+         !
+         !        !==  anti-diffusive flux : high order minus low order  ==!
+         !
+         SELECT CASE( kn_fct_h )    !* horizontal anti-diffusive fluxes
+         !
+         CASE(  2  )                   !- 2nd order centered
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     zwx(ji,jj,jk) = 0.5_wp * pun(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji+1,jj,jk,jn) ) - zwx(ji,jj,jk)
+                     zwy(ji,jj,jk) = 0.5_wp * pvn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj+1,jk,jn) ) - zwy(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         CASE(  4  )                   !- 4th order centered
+            zltu(:,:,jpk) = 0._wp            ! Bottom value : flux set to zero
+            zltv(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1                 ! Laplacian
+               DO jj = 1, jpjm1                    ! 1st derivative (gradient)
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     ztu(ji,jj,jk) = ( ptn(ji+1,jj  ,jk,jn) - ptn(ji,jj,jk,jn) ) * umask(ji,jj,jk)
+                     ztv(ji,jj,jk) = ( ptn(ji  ,jj+1,jk,jn) - ptn(ji,jj,jk,jn) ) * vmask(ji,jj,jk)
+                  END DO
+               END DO
+               DO jj = 2, jpjm1                    ! 2nd derivative * 1/ 6
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zltu(ji,jj,jk) = (  ztu(ji,jj,jk) + ztu(ji-1,jj,jk)  ) * r1_6
+                     zltv(ji,jj,jk) = (  ztv(ji,jj,jk) + ztv(ji,jj-1,jk)  ) * r1_6
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'traadv_fct', zltu, 'T', 1. , zltv, 'T', 1. )   ! Lateral boundary cond. (unchanged sgn)
+            !
+            DO jk = 1, jpkm1                 ! Horizontal advective fluxes
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     zC2t_u = ptn(ji,jj,jk,jn) + ptn(ji+1,jj  ,jk,jn)   ! 2 x C2 interpolation of T at u- & v-points
+                     zC2t_v = ptn(ji,jj,jk,jn) + ptn(ji  ,jj+1,jk,jn)
+                     !                                                  ! C4 minus upstream advective fluxes 
+                     zwx(ji,jj,jk) =  0.5_wp * pun(ji,jj,jk) * ( zC2t_u + zltu(ji,jj,jk) - zltu(ji+1,jj,jk) ) - zwx(ji,jj,jk)
+                     zwy(ji,jj,jk) =  0.5_wp * pvn(ji,jj,jk) * ( zC2t_v + zltv(ji,jj,jk) - zltv(ji,jj+1,jk) ) - zwy(ji,jj,jk)
+                  END DO
+               END DO
+            END DO         
+            !
+         CASE(  41 )                   !- 4th order centered       ==>>   !!gm coding attempt   need to be tested
+            ztu(:,:,jpk) = 0._wp             ! Bottom value : flux set to zero
+            ztv(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1                 ! 1st derivative (gradient)
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     ztu(ji,jj,jk) = ( ptn(ji+1,jj  ,jk,jn) - ptn(ji,jj,jk,jn) ) * umask(ji,jj,jk)
+                     ztv(ji,jj,jk) = ( ptn(ji  ,jj+1,jk,jn) - ptn(ji,jj,jk,jn) ) * vmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'traadv_fct', ztu, 'U', -1. , ztv, 'V', -1. )   ! Lateral boundary cond. (unchanged sgn)
+            !
+            DO jk = 1, jpkm1                 ! Horizontal advective fluxes
+               DO jj = 2, jpjm1
+                  DO ji = 2, fs_jpim1   ! vector opt.
+                     zC2t_u = ptn(ji,jj,jk,jn) + ptn(ji+1,jj  ,jk,jn)   ! 2 x C2 interpolation of T at u- & v-points (x2)
+                     zC2t_v = ptn(ji,jj,jk,jn) + ptn(ji  ,jj+1,jk,jn)
+                     !                                                  ! C4 interpolation of T at u- & v-points (x2)
+                     zC4t_u =  zC2t_u + r1_6 * ( ztu(ji-1,jj  ,jk) - ztu(ji+1,jj  ,jk) )
+                     zC4t_v =  zC2t_v + r1_6 * ( ztv(ji  ,jj-1,jk) - ztv(ji  ,jj+1,jk) )
+                     !                                                  ! C4 minus upstream advective fluxes 
+                     zwx(ji,jj,jk) =  0.5_wp * pun(ji,jj,jk) * zC4t_u - zwx(ji,jj,jk)
+                     zwy(ji,jj,jk) =  0.5_wp * pvn(ji,jj,jk) * zC4t_v - zwy(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         END SELECT
+         !                      
+         SELECT CASE( kn_fct_v )    !* vertical anti-diffusive fluxes (w-masked interior values)
+         !
+         CASE(  2  )                   !- 2nd order centered
+            DO jk = 2, jpkm1    
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zwz(ji,jj,jk) =  (  pwn(ji,jj,jk) * 0.5_wp * ( ptn(ji,jj,jk,jn) + ptn(ji,jj,jk-1,jn) )   &
+                        &              - zwz(ji,jj,jk)  ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         CASE(  4  )                   !- 4th order COMPACT
+            CALL interp_4th_cpt( ptn(:,:,:,jn) , ztw )   ! zwt = COMPACT interpolation of T at w-point
+            DO jk = 2, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zwz(ji,jj,jk) = ( pwn(ji,jj,jk) * ztw(ji,jj,jk) - zwz(ji,jj,jk) ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+         END SELECT
+         IF( ln_linssh ) THEN    ! top ocean value: high order = upstream  ==>>  zwz=0
+            zwz(:,:,1) = 0._wp   ! only ocean surface as interior zwz values have been w-masked
+         ENDIF
+         !         
+         IF ( ll_zAimp ) THEN
+            DO jk = 1, jpkm1     !* trend and after field with monotonic scheme
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     !                             ! total intermediate advective trends
+                     ztra = - (  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) ) * r1_e1e2t(ji,jj)
+                     ztw(ji,jj,jk)  = zwi(ji,jj,jk) + p2dt * ztra / e3t_a(ji,jj,jk) * tmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !
+            CALL tridia_solver( zwdia, zwsup, zwinf, ztw, ztw , 0 )
+            !
+            DO jk = 2, jpkm1        ! Interior value ( multiplied by wmask)
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+                     zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+                     zwz(ji,jj,jk) =  zwz(ji,jj,jk) + 0.5 * e1e2t(ji,jj) * ( zfp_wk * ztw(ji,jj,jk) + zfm_wk * ztw(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+         END IF
+         !
+         CALL lbc_lnk_multi( 'traadv_fct', zwi, 'T', 1., zwx, 'U', -1. , zwy, 'V', -1.,  zwz, 'W',  1. )
+         !
+         !        !==  monotonicity algorithm  ==!
+         !
+         CALL nonosc( ptb(:,:,:,jn), zwx, zwy, zwz, zwi, p2dt )
+         !
+         !        !==  final trend with corrected fluxes  ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.  
+                  ztra = - (  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) ) * r1_e1e2t(ji,jj)
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra / e3t_n(ji,jj,jk)
+                  zwi(ji,jj,jk) = zwi(ji,jj,jk) + p2dt * ztra / e3t_a(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF ( ll_zAimp ) THEN
+            !
+            ztw(:,:,1) = 0._wp ; ztw(:,:,jpk) = 0._wp
+            DO jk = 2, jpkm1        ! Interior value ( multiplied by wmask)
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zfp_wk = wi(ji,jj,jk) + ABS( wi(ji,jj,jk) )
+                     zfm_wk = wi(ji,jj,jk) - ABS( wi(ji,jj,jk) )
+                     ztw(ji,jj,jk) = - 0.5 * e1e2t(ji,jj) * ( zfp_wk * zwi(ji,jj,jk) + zfm_wk * zwi(ji,jj,jk-1) ) * wmask(ji,jj,jk)
+                     zwz(ji,jj,jk) = zwz(ji,jj,jk) + ztw(ji,jj,jk) ! Update vertical fluxes for trend diagnostic
+                  END DO
+               END DO
+            END DO
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.  
+                     pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) - ( ztw(ji,jj,jk) - ztw(ji  ,jj  ,jk+1) ) &
+                        &                                * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+         END IF         
+         !
+         IF( l_trd .OR. l_hst ) THEN   ! trend diagnostics // heat/salt transport
+            ztrdx(:,:,:) = ztrdx(:,:,:) + zwx(:,:,:)  ! <<< add anti-diffusive fluxes 
+            ztrdy(:,:,:) = ztrdy(:,:,:) + zwy(:,:,:)  !     to upstream fluxes
+            ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  !
+            !
+            IF( l_trd ) THEN              ! trend diagnostics
+               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) )
+            ENDIF
+            !                             ! heat/salt transport
+            IF( l_hst )   CALL dia_ar5_hst( jn, 'adv', ztrdx(:,:,:), ztrdy(:,:,:) )
+            !
+         ENDIF
+         IF( l_ptr ) THEN              ! "Poleward" transports
+            zptry(:,:,:) = zptry(:,:,:) + zwy(:,:,:)  ! <<< add anti-diffusive fluxes
+            CALL dia_ptr_hst( jn, 'adv', zptry(:,:,:) )
+         ENDIF
+         !
+      END DO                     ! end of tracer loop
+      !
+      IF ( ll_zAimp ) THEN
+         DEALLOCATE( zwdia, zwinf, zwsup )
+      ENDIF
+      IF( l_trd .OR. l_hst ) THEN 
+         DEALLOCATE( ztrdx, ztrdy, ztrdz )
+      ENDIF
+      IF( l_ptr ) THEN 
+         DEALLOCATE( zptry )
+      ENDIF
+      !
+   END SUBROUTINE tra_adv_fct
+
+
+   SUBROUTINE nonosc( pbef, paa, pbb, pcc, paft, p2dt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE nonosc  ***
+      !!     
+      !! **  Purpose :   compute monotonic tracer fluxes from the upstream 
+      !!       scheme and the before field by a nonoscillatory algorithm 
+      !!
+      !! **  Method  :   ... ???
+      !!       warning : pbef and paft must be masked, but the boundaries
+      !!       conditions on the fluxes are not necessary zalezak (1979)
+      !!       drange (1995) multi-dimensional forward-in-time and upstream-
+      !!       in-space based differencing for fluid
+      !!----------------------------------------------------------------------
+      REAL(wp)                         , INTENT(in   ) ::   p2dt            ! 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
+      REAL(wp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn    ! local scalars
+      REAL(wp) ::   zau, zbu, zcu, zav, zbv, zcv, zup, zdo            !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zbetup, zbetdo, zbup, zbdo
+      !!----------------------------------------------------------------------
+      !
+      zbig  = 1.e+40_wp
+      zrtrn = 1.e-15_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._wp - tmask ),   &
+         &        paft * tmask - zbig * ( 1._wp - tmask )  )
+      zbdo = MIN( pbef * tmask + zbig * ( 1._wp - tmask ),   &
+         &        paft * tmask + zbig * ( 1._wp - tmask )  )
+
+      DO jk = 1, jpkm1
+         ikm1 = MAX(jk-1,1)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+
+               ! search maximum in neighbourhood
+               zup = MAX(  zbup(ji  ,jj  ,jk  ),   &
+                  &        zbup(ji-1,jj  ,jk  ), zbup(ji+1,jj  ,jk  ),   &
+                  &        zbup(ji  ,jj-1,jk  ), zbup(ji  ,jj+1,jk  ),   &
+                  &        zbup(ji  ,jj  ,ikm1), zbup(ji  ,jj  ,jk+1)  )
+
+               ! search minimum in neighbourhood
+               zdo = MIN(  zbdo(ji  ,jj  ,jk  ),   &
+                  &        zbdo(ji-1,jj  ,jk  ), zbdo(ji+1,jj  ,jk  ),   &
+                  &        zbdo(ji  ,jj-1,jk  ), zbdo(ji  ,jj+1,jk  ),   &
+                  &        zbdo(ji  ,jj  ,ikm1), zbdo(ji  ,jj  ,jk+1)  )
+
+               ! positive part of the flux
+               zpos = MAX( 0., paa(ji-1,jj  ,jk  ) ) - MIN( 0., paa(ji  ,jj  ,jk  ) )   &
+                  & + MAX( 0., pbb(ji  ,jj-1,jk  ) ) - MIN( 0., pbb(ji  ,jj  ,jk  ) )   &
+                  & + MAX( 0., pcc(ji  ,jj  ,jk+1) ) - MIN( 0., pcc(ji  ,jj  ,jk  ) )
+
+               ! negative part of the flux
+               zneg = MAX( 0., paa(ji  ,jj  ,jk  ) ) - MIN( 0., paa(ji-1,jj  ,jk  ) )   &
+                  & + MAX( 0., pbb(ji  ,jj  ,jk  ) ) - MIN( 0., pbb(ji  ,jj-1,jk  ) )   &
+                  & + MAX( 0., pcc(ji  ,jj  ,jk  ) ) - MIN( 0., pcc(ji  ,jj  ,jk+1) )
+
+               ! up & down beta terms
+               zbt = e1e2t(ji,jj) * e3t_n(ji,jj,jk) / p2dt
+               zbetup(ji,jj,jk) = ( zup            - paft(ji,jj,jk) ) / ( zpos + zrtrn ) * zbt
+               zbetdo(ji,jj,jk) = ( paft(ji,jj,jk) - zdo            ) / ( zneg + zrtrn ) * zbt
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'traadv_fct', zbetup, 'T', 1. , zbetdo, 'T', 1. )   ! lateral boundary cond. (unchanged sign)
+
+      ! 3. monotonic flux in the i & j direction (paa & pbb)
+      ! ----------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               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._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._wp - zcv) * zbv )
+
+      ! monotonic flux in the k direction, i.e. pcc
+      ! -------------------------------------------
+               za = MIN( 1., zbetdo(ji,jj,jk+1), zbetup(ji,jj,jk) )
+               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._wp - zc) * zb )
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'traadv_fct', paa, 'U', -1. , pbb, 'V', -1. )   ! lateral boundary condition (changed sign)
+      !
+   END SUBROUTINE nonosc
+
+
+   SUBROUTINE interp_4th_cpt_org( pt_in, pt_out )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interp_4th_cpt_org  ***
+      !! 
+      !! **  Purpose :   Compute the interpolation of tracer at w-point
+      !!
+      !! **  Method  :   4th order compact interpolation
+      !!----------------------------------------------------------------------
+      REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pt_in    ! now tracer fields
+      REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(  out) ::   pt_out   ! now tracer field interpolated at w-pts
+      !
+      INTEGER :: ji, jj, jk   ! dummy loop integers
+      REAL(wp),DIMENSION(jpi,jpj,jpk) :: zwd, zwi, zws, zwrm, zwt
+      !!----------------------------------------------------------------------
+      
+      DO jk = 3, jpkm1        !==  build the three diagonal matrix  ==!
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zwd (ji,jj,jk) = 4._wp
+               zwi (ji,jj,jk) = 1._wp
+               zws (ji,jj,jk) = 1._wp
+               zwrm(ji,jj,jk) = 3._wp * ( pt_in(ji,jj,jk-1) + pt_in(ji,jj,jk) )
+               !
+               IF( tmask(ji,jj,jk+1) == 0._wp) THEN   ! Switch to second order centered at bottom
+                  zwd (ji,jj,jk) = 1._wp
+                  zwi (ji,jj,jk) = 0._wp
+                  zws (ji,jj,jk) = 0._wp
+                  zwrm(ji,jj,jk) = 0.5 * ( pt_in(ji,jj,jk-1) + pt_in(ji,jj,jk) )    
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      jk = 2                                          ! Switch to second order centered at top
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zwd (ji,jj,jk) = 1._wp
+            zwi (ji,jj,jk) = 0._wp
+            zws (ji,jj,jk) = 0._wp
+            zwrm(ji,jj,jk) = 0.5 * ( pt_in(ji,jj,jk-1) + pt_in(ji,jj,jk) )
+         END DO
+      END DO   
+      !
+      !                       !==  tridiagonal solve  ==!
+      DO jj = 1, jpj                ! first recurrence
+         DO ji = 1, jpi
+            zwt(ji,jj,2) = zwd(ji,jj,2)
+         END DO
+      END DO
+      DO jk = 3, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               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
+      END DO
+      !
+      DO jj = 1, jpj                ! second recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+         DO ji = 1, jpi
+            pt_out(ji,jj,2) = zwrm(ji,jj,2)
+         END DO
+      END DO
+      DO jk = 3, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               pt_out(ji,jj,jk) = zwrm(ji,jj,jk) - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) *pt_out(ji,jj,jk-1)             
+            END DO
+         END DO
+      END DO
+
+      DO jj = 1, jpj                ! third recurrence: Xk = (Zk - Sk Xk+1 ) / Tk
+         DO ji = 1, jpi
+            pt_out(ji,jj,jpkm1) = pt_out(ji,jj,jpkm1) / zwt(ji,jj,jpkm1)
+         END DO
+      END DO
+      DO jk = jpk-2, 2, -1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               pt_out(ji,jj,jk) = ( pt_out(ji,jj,jk) - zws(ji,jj,jk) * pt_out(ji,jj,jk+1) ) / zwt(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !    
+   END SUBROUTINE interp_4th_cpt_org
+   
+
+   SUBROUTINE interp_4th_cpt( pt_in, pt_out )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE interp_4th_cpt  ***
+      !! 
+      !! **  Purpose :   Compute the interpolation of tracer at w-point
+      !!
+      !! **  Method  :   4th order compact interpolation
+      !!----------------------------------------------------------------------
+      REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pt_in    ! field at t-point
+      REAL(wp),DIMENSION(jpi,jpj,jpk), INTENT(  out) ::   pt_out   ! field interpolated at w-point
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop integers
+      INTEGER ::   ikt, ikb     ! local integers
+      REAL(wp),DIMENSION(jpi,jpj,jpk) :: zwd, zwi, zws, zwrm, zwt
+      !!----------------------------------------------------------------------
+      !
+      !                      !==  build the three diagonal matrix & the RHS  ==!
+      !
+      DO jk = 3, jpkm1                 ! interior (from jk=3 to jpk-1)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zwd (ji,jj,jk) = 3._wp * wmask(ji,jj,jk) + 1._wp                 !       diagonal
+               zwi (ji,jj,jk) =         wmask(ji,jj,jk)                         ! lower diagonal
+               zws (ji,jj,jk) =         wmask(ji,jj,jk)                         ! upper diagonal
+               zwrm(ji,jj,jk) = 3._wp * wmask(ji,jj,jk)                     &   ! RHS
+                  &           *       ( pt_in(ji,jj,jk) + pt_in(ji,jj,jk-1) )
+            END DO
+         END DO
+      END DO
+      !
+!!gm
+!      SELECT CASE( kbc )               !* boundary condition
+!      CASE( np_NH   )   ! Neumann homogeneous at top & bottom
+!      CASE( np_CEN2 )   ! 2nd order centered  at top & bottom
+!      END SELECT
+!!gm  
+      !
+      IF ( ln_isfcav ) THEN            ! set level two values which may not be set in ISF case
+         zwd(:,:,2) = 1._wp  ;  zwi(:,:,2) = 0._wp  ;  zws(:,:,2) = 0._wp  ;  zwrm(:,:,2) = 0._wp
+      END IF
+      !
+      DO jj = 2, jpjm1                 ! 2nd order centered at top & bottom
+         DO ji = fs_2, fs_jpim1
+            ikt = mikt(ji,jj) + 1            ! w-point below the 1st  wet point
+            ikb = MAX(mbkt(ji,jj), 2)        !     -   above the last wet point
+            !
+            zwd (ji,jj,ikt) = 1._wp          ! top
+            zwi (ji,jj,ikt) = 0._wp
+            zws (ji,jj,ikt) = 0._wp
+            zwrm(ji,jj,ikt) = 0.5_wp * ( pt_in(ji,jj,ikt-1) + pt_in(ji,jj,ikt) )
+            !
+            zwd (ji,jj,ikb) = 1._wp          ! bottom
+            zwi (ji,jj,ikb) = 0._wp
+            zws (ji,jj,ikb) = 0._wp
+            zwrm(ji,jj,ikb) = 0.5_wp * ( pt_in(ji,jj,ikb-1) + pt_in(ji,jj,ikb) )            
+         END DO
+      END DO   
+      !
+      !                       !==  tridiagonal solver  ==!
+      !
+      DO jj = 2, jpjm1              !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
+         DO ji = fs_2, fs_jpim1
+            zwt(ji,jj,2) = zwd(ji,jj,2)
+         END DO
+      END DO
+      DO jk = 3, 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)
+            END DO
+         END DO
+      END DO
+      !
+      DO jj = 2, jpjm1              !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+         DO ji = fs_2, fs_jpim1
+            pt_out(ji,jj,2) = zwrm(ji,jj,2)
+         END DO
+      END DO
+      DO jk = 3, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pt_out(ji,jj,jk) = zwrm(ji,jj,jk) - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) *pt_out(ji,jj,jk-1)             
+            END DO
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1              !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
+         DO ji = fs_2, fs_jpim1
+            pt_out(ji,jj,jpkm1) = pt_out(ji,jj,jpkm1) / zwt(ji,jj,jpkm1)
+         END DO
+      END DO
+      DO jk = jpk-2, 2, -1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pt_out(ji,jj,jk) = ( pt_out(ji,jj,jk) - zws(ji,jj,jk) * pt_out(ji,jj,jk+1) ) / zwt(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !    
+   END SUBROUTINE interp_4th_cpt
+
+
+   SUBROUTINE tridia_solver( pD, pU, pL, pRHS, pt_out , klev )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tridia_solver  ***
+      !! 
+      !! **  Purpose :   solve a symmetric 3diagonal system
+      !!
+      !! **  Method  :   solve M.t_out = RHS(t)  where M is a tri diagonal matrix ( jpk*jpk )
+      !!     
+      !!             ( D_1 U_1  0   0   0  )( t_1 )   ( RHS_1 )
+      !!             ( L_2 D_2 U_2  0   0  )( t_2 )   ( RHS_2 )
+      !!             (  0  L_3 D_3 U_3  0  )( t_3 ) = ( RHS_3 )
+      !!             (        ...          )( ... )   ( ...  )
+      !!             (  0   0   0  L_k D_k )( t_k )   ( RHS_k )
+      !!     
+      !!        M is decomposed in the product of an upper and lower triangular matrix.
+      !!        The tri-diagonals matrix is given as input 3D arrays:   pD, pU, pL 
+      !!        (i.e. the Diagonal, the Upper diagonal, and the Lower diagonal).
+      !!        The solution is pta.
+      !!        The 3d array zwt is used as a work space array.
+      !!----------------------------------------------------------------------
+      REAL(wp),DIMENSION(:,:,:), INTENT(in   ) ::   pD, pU, PL    ! 3-diagonal matrix
+      REAL(wp),DIMENSION(:,:,:), INTENT(in   ) ::   pRHS          ! Right-Hand-Side
+      REAL(wp),DIMENSION(:,:,:), INTENT(  out) ::   pt_out        !!gm field at level=F(klev)
+      INTEGER                  , INTENT(in   ) ::   klev          ! =1 pt_out at w-level 
+      !                                                           ! =0 pt at t-level
+      INTEGER ::   ji, jj, jk   ! dummy loop integers
+      INTEGER ::   kstart       ! local indices
+      REAL(wp),DIMENSION(jpi,jpj,jpk) ::   zwt   ! 3D work array
+      !!----------------------------------------------------------------------
+      !
+      kstart =  1  + klev
+      !
+      DO jj = 2, jpjm1              !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1
+         DO ji = fs_2, fs_jpim1
+            zwt(ji,jj,kstart) = pD(ji,jj,kstart)
+         END DO
+      END DO
+      DO jk = kstart+1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zwt(ji,jj,jk) = pD(ji,jj,jk) - pL(ji,jj,jk) * pU(ji,jj,jk-1) /zwt(ji,jj,jk-1)
+            END DO
+         END DO
+      END DO
+      !
+      DO jj = 2, jpjm1              !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+         DO ji = fs_2, fs_jpim1
+            pt_out(ji,jj,kstart) = pRHS(ji,jj,kstart)
+         END DO
+      END DO
+      DO jk = kstart+1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pt_out(ji,jj,jk) = pRHS(ji,jj,jk) - pL(ji,jj,jk) / zwt(ji,jj,jk-1) *pt_out(ji,jj,jk-1)             
+            END DO
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1              !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk
+         DO ji = fs_2, fs_jpim1
+            pt_out(ji,jj,jpkm1) = pt_out(ji,jj,jpkm1) / zwt(ji,jj,jpkm1)
+         END DO
+      END DO
+      DO jk = jpk-2, kstart, -1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               pt_out(ji,jj,jk) = ( pt_out(ji,jj,jk) - pU(ji,jj,jk) * pt_out(ji,jj,jk+1) ) / zwt(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE tridia_solver
+
+   !!======================================================================
+END MODULE traadv_fct
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_mus.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_mus.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_mus.F90	(revision 14097)
@@ -0,0 +1,277 @@
+MODULE traadv_mus
+   !!======================================================================
+   !!                       ***  MODULE  traadv_mus  ***
+   !! Ocean  tracers:  horizontal & vertical advective trend
+   !!======================================================================
+   !! History :       !  2000-06  (A.Estublier)  for passive tracers
+   !!                 !  2001-08  (E.Durand, G.Madec)  adapted for T & S
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  !  2010-05  (C. Ethe, G. Madec)  merge TRC-TRA + switch from velocity to transport
+   !!            3.4  !  2012-06  (P. Oddo, M. Vichi) include the upstream where needed
+   !!            3.7  !  2015-09  (G. Madec) add the ice-shelf cavities boundary condition
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv_mus   : update the tracer trend with the horizontal
+   !!                   and vertical advection trends using MUSCL scheme
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE dom_oce        ! ocean space and time domain
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracers trends manager
+   USE sbcrnf         ! river runoffs
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+
+   !
+   USE iom            ! XIOS library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_mus   ! 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 1 configurations)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xind     !: mixed upstream/centered index
+   
+   LOGICAL  ::   l_trd   ! flag to compute trends
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat/salt transport
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_mus( kt, kit000, cdtype, p2dt, pun, pvn, pwn,             &
+      &                                              ptb, pta, kjpt, ld_msc_ups )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE tra_adv_mus  ***
+      !!
+      !! ** Purpose :   Compute the now trend due to total advection of tracers
+      !!              using a MUSCL scheme (Monotone Upstream-centered Scheme for
+      !!              Conservation Laws) and add it to the general tracer trend.
+      !!
+      !! ** Method  : MUSCL scheme plus centered scheme at ocean boundaries
+      !!              ld_msc_ups=T : 
+      !!
+      !! ** Action : - update pta  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostcs (l_trdtra=T)
+      !!             - htr_adv, str_adv : poleward advective heat and salt transport (ln_diaptr=T)
+      !!
+      !! References : Estubier, A., and M. Levy, Notes Techn. Pole de Modelisation
+      !!              IPSL, Sept. 2000 (http://www.lodyc.jussieu.fr/opa)
+      !!----------------------------------------------------------------------
+      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
+      LOGICAL                              , INTENT(in   ) ::   ld_msc_ups      ! use upstream scheme within muscl
+      REAL(wp)                             , INTENT(in   ) ::   p2dt            ! 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             ! before tracer field
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::   ierr             ! local integer
+      REAL(wp) ::   zu, z0u, zzwx, zw , zalpha   ! local scalars
+      REAL(wp) ::   zv, z0v, zzwy, z0w           !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zslpx   ! 3D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwy, zslpy   ! -      - 
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv : MUSCL advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '        : mixed up-stream           ', ld_msc_ups
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+         IF(lwp) WRITE(numout,*)
+         !
+         ! Upstream / MUSCL scheme indicator
+         !
+         ALLOCATE( xind(jpi,jpj,jpk), STAT=ierr )
+         xind(:,:,:) = 1._wp              ! set equal to 1 where up-stream is not needed
+         !
+         IF( ld_msc_ups ) THEN            ! define the upstream indicator (if asked)
+            ALLOCATE( upsmsk(jpi,jpj), STAT=ierr )
+            upsmsk(:,:) = 0._wp                             ! not upstream by default
+            !
+            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 in some user defined area
+            END DO
+         ENDIF 
+         !
+      ENDIF 
+      !      
+      l_trd = .FALSE.
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ln_diaptr )                                               l_ptr = .TRUE. 
+      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
+      !
+      DO jn = 1, kjpt            !==  loop over the tracers  ==!
+         !
+         !                          !* Horizontal advective fluxes
+         !
+         !                                !-- first guess of the slopes
+         zwx(:,:,jpk) = 0._wp                   ! bottom values
+         zwy(:,:,jpk) = 0._wp  
+         DO jk = 1, jpkm1                       ! interior values
+            DO jj = 1, jpjm1      
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwx(ji,jj,jk) = umask(ji,jj,jk) * ( ptb(ji+1,jj,jk,jn) - ptb(ji,jj,jk,jn) )
+                  zwy(ji,jj,jk) = vmask(ji,jj,jk) * ( ptb(ji,jj+1,jk,jn) - ptb(ji,jj,jk,jn) )
+               END DO
+           END DO
+         END DO
+         ! lateral boundary conditions   (changed sign)
+         CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1. , zwy, 'V', -1. )
+         !                                !-- Slopes of tracer
+         zslpx(:,:,jpk) = 0._wp                 ! bottom values
+         zslpy(:,:,jpk) = 0._wp
+         DO jk = 1, jpkm1                       ! interior values
+            DO jj = 2, jpj
+               DO ji = fs_2, jpi   ! vector opt.
+                  zslpx(ji,jj,jk) =                    ( zwx(ji,jj,jk) + zwx(ji-1,jj  ,jk) )   &
+                     &            * ( 0.25 + SIGN( 0.25, zwx(ji,jj,jk) * zwx(ji-1,jj  ,jk) ) )
+                  zslpy(ji,jj,jk) =                    ( zwy(ji,jj,jk) + zwy(ji  ,jj-1,jk) )   &
+                     &            * ( 0.25 + SIGN( 0.25, zwy(ji,jj,jk) * zwy(ji  ,jj-1,jk) ) )
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, jpkm1                 !-- Slopes limitation
+            DO jj = 2, jpj
+               DO ji = fs_2, jpi   ! vector opt.
+                  zslpx(ji,jj,jk) = SIGN( 1., zslpx(ji,jj,jk) ) * MIN(    ABS( zslpx(ji  ,jj,jk) ),   &
+                     &                                                 2.*ABS( zwx  (ji-1,jj,jk) ),   &
+                     &                                                 2.*ABS( zwx  (ji  ,jj,jk) ) )
+                  zslpy(ji,jj,jk) = SIGN( 1., zslpy(ji,jj,jk) ) * MIN(    ABS( zslpy(ji,jj  ,jk) ),   &
+                     &                                                 2.*ABS( zwy  (ji,jj-1,jk) ),   &
+                     &                                                 2.*ABS( zwy  (ji,jj  ,jk) ) )
+               END DO
+           END DO
+         END DO
+         !
+         DO jk = 1, jpkm1                 !-- MUSCL horizontal advective fluxes
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ! MUSCL fluxes
+                  z0u = SIGN( 0.5, pun(ji,jj,jk) )
+                  zalpha = 0.5 - z0u
+                  zu  = z0u - 0.5 * pun(ji,jj,jk) * p2dt * r1_e1e2u(ji,jj) / e3u_n(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 )
+                  !
+                  z0v = SIGN( 0.5, pvn(ji,jj,jk) )
+                  zalpha = 0.5 - z0v
+                  zv  = z0v - 0.5 * pvn(ji,jj,jk) * p2dt * r1_e1e2v(ji,jj) / e3v_n(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
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'traadv_mus', zwx, 'U', -1. , zwy, 'V', -1. )   ! lateral boundary conditions   (changed sign)
+         !
+         DO jk = 1, jpkm1                 !-- Tracer advective trend
+            DO jj = 2, jpjm1      
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) - ( zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )       &
+                  &                                     + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  ) )     &
+                  &                                   * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+           END DO
+         END DO        
+         !                                ! trend diagnostics
+         IF( l_trd )  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 
+         IF( l_ptr )  CALL dia_ptr_hst( jn, 'adv', zwy(:,:,:) )
+         !                                 !  heat transport
+         IF( l_hst )  CALL dia_ar5_hst( jn, 'adv', zwx(:,:,:), zwy(:,:,:) )
+         !
+         !                          !* Vertical advective fluxes
+         !
+         !                                !-- first guess of the slopes
+         zwx(:,:, 1 ) = 0._wp                   ! surface & bottom boundary conditions
+         zwx(:,:,jpk) = 0._wp
+         DO jk = 2, jpkm1                       ! interior values
+            zwx(:,:,jk) = tmask(:,:,jk) * ( ptb(:,:,jk-1,jn) - ptb(:,:,jk,jn) )
+         END DO
+         !                                !-- Slopes of tracer
+         zslpx(:,:,1) = 0._wp                   ! surface values
+         DO jk = 2, jpkm1                       ! interior value
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zslpx(ji,jj,jk) =                     ( zwx(ji,jj,jk) + zwx(ji,jj,jk+1) )  &
+                     &            * (  0.25 + SIGN( 0.25, zwx(ji,jj,jk) * zwx(ji,jj,jk+1) )  )
+               END DO
+            END DO
+         END DO
+         DO jk = 2, jpkm1                 !-- Slopes limitation
+            DO jj = 1, jpj                      ! interior values
+               DO ji = 1, jpi
+                  zslpx(ji,jj,jk) = SIGN( 1., zslpx(ji,jj,jk) ) * MIN(    ABS( zslpx(ji,jj,jk  ) ),   &
+                     &                                                 2.*ABS( zwx  (ji,jj,jk+1) ),   &
+                     &                                                 2.*ABS( zwx  (ji,jj,jk  ) )  )
+               END DO
+            END DO
+         END DO
+         DO jk = 1, jpk-2                 !-- vertical advective flux
+            DO jj = 2, jpjm1      
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z0w = SIGN( 0.5, pwn(ji,jj,jk+1) )
+                  zalpha = 0.5 + z0w
+                  zw  = z0w - 0.5 * pwn(ji,jj,jk+1) * p2dt * r1_e1e2t(ji,jj) / e3w_n(ji,jj,jk+1)
+                  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 ) * wmask(ji,jj,jk)
+               END DO 
+            END DO
+         END DO
+         IF( ln_linssh ) THEN                   ! top values, linear free surface only
+            IF( ln_isfcav ) THEN                      ! ice-shelf cavities (top of the ocean)
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zwx(ji,jj, mikt(ji,jj) ) = pwn(ji,jj,mikt(ji,jj)) * ptb(ji,jj,mikt(ji,jj),jn)
+                  END DO
+               END DO   
+            ELSE                                      ! no cavities: only at the ocean surface
+               zwx(:,:,1) = pwn(:,:,1) * ptb(:,:,1,jn)
+            ENDIF
+         ENDIF
+         !
+         DO jk = 1, jpkm1                 !-- vertical advective trend
+            DO jj = 2, jpjm1      
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) =  pta(ji,jj,jk,jn) - ( zwx(ji,jj,jk) - zwx(ji,jj,jk+1) ) * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !                                ! send trends for diagnostic
+         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_zad, zwx, pwn, ptb(:,:,:,jn) )
+         !
+      END DO                     ! end of tracer loop
+      !
+   END SUBROUTINE tra_adv_mus
+
+   !!======================================================================
+END MODULE traadv_mus
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_qck.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_qck.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_qck.F90	(revision 14097)
@@ -0,0 +1,458 @@
+MODULE traadv_qck
+   !!==============================================================================
+   !!                       ***  MODULE  traadv_qck  ***
+   !! Ocean tracers:  horizontal & vertical advective trend
+   !!==============================================================================
+   !! History :  3.0  !  2008-07  (G. Reffray)  Original code
+   !!            3.3  !  2010-05  (C.Ethe, G. Madec)  merge TRC-TRA + switch from velocity to transport
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv_qck    : update the tracer trend with the horizontal advection
+   !!                    trends using a 3rd order finite difference scheme
+   !!   tra_adv_qck_i  : apply QUICK scheme in i-direction
+   !!   tra_adv_qck_j  : apply QUICK scheme in j-direction
+   !!   tra_adv_cen2_k : 2nd centered scheme for the vertical advection
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and active tracers
+   USE dom_oce         ! ocean space and time domain
+   USE trc_oce         ! share passive tracers/Ocean variables
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   USE diaptr          ! poleward transport diagnostics
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing
+   USE lbclnk          ! ocean lateral boundary condition (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_qck   ! routine called by step.F90
+
+   REAL(wp) :: r1_6 = 1./ 6.   ! 1/6 ratio
+
+   LOGICAL  ::   l_trd   ! flag to compute trends
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_qck ( kt, kit000, cdtype, p2dt, pun, pvn, pwn,      &
+      &                                       ptb, ptn, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_qck  ***
+      !!
+      !! ** Purpose :   Compute the now trend due to the advection of tracers
+      !!      and add it to the general trend of passive tracer equations.
+      !!
+      !! ** Method :   The advection is evaluated by a third order scheme
+      !!             For a positive velocity u :              u(i)>0
+      !!                                          |--FU--|--FC--|--FD--|------|
+      !!                                             i-1    i      i+1   i+2
+      !!
+      !!             For a negative velocity u :              u(i)<0
+      !!                                          |------|--FD--|--FC--|--FU--|
+      !!                                             i-1    i      i+1   i+2
+      !!             where  FU is the second upwind point
+      !!                    FD is the first douwning point
+      !!                    FC is the central point (or the first upwind point)
+      !!
+      !!      Flux(i) = u(i) * { 0.5(FC+FD)  -0.5C(i)(FD-FC)  -((1-C(i))/6)(FU+FD-2FC) }
+      !!                with C(i)=|u(i)|dx(i)/dt (=Courant number)
+      !!
+      !!         dt = 2*rdtra and the scalar values are tb and sb
+      !!
+      !!       On the vertical, the simple centered scheme used ptn
+      !!
+      !!               The fluxes are bounded by the ULTIMATE limiter to
+      !!             guarantee the monotonicity of the solution and to
+      !!            prevent the appearance of spurious numerical oscillations
+      !!
+      !! ** Action : - update pta  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostcs (l_trdtra=T)
+      !!             - htr_adv, str_adv : poleward advective heat and salt transport (ln_diaptr=T)
+      !!
+      !! ** Reference : Leonard (1979, 1991)
+      !!----------------------------------------------------------------------
+      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)                             , INTENT(in   ) ::   p2dt            ! 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 
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_qck : 3rd order quickest advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+         IF(lwp) WRITE(numout,*)
+      ENDIF
+      !
+      l_trd = .FALSE.
+      l_ptr = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ln_diaptr )                                               l_ptr = .TRUE. 
+      !
+      !
+      !        ! horizontal fluxes are computed with the QUICKEST + ULTIMATE scheme
+      CALL tra_adv_qck_i( kt, cdtype, p2dt, pun, ptb, ptn, pta, kjpt ) 
+      CALL tra_adv_qck_j( kt, cdtype, p2dt, pvn, ptb, ptn, pta, kjpt ) 
+
+      !        ! vertical fluxes are computed with the 2nd order centered scheme
+      CALL tra_adv_cen2_k( kt, cdtype, pwn,         ptn, pta, kjpt )
+      !
+   END SUBROUTINE tra_adv_qck
+
+
+   SUBROUTINE tra_adv_qck_i( kt, cdtype, p2dt, pun,                  &
+      &                                        ptb, ptn, pta, kjpt   )
+      !!----------------------------------------------------------------------
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                              , INTENT(in   ) ::   kt         ! ocean time-step index
+      CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
+      REAL(wp)                             , INTENT(in   ) ::   p2dt       ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pun        ! i-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 
+      !!
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   ztra, zbtr, zdir, zdx, zmsk   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwx, zfu, zfc, zfd
+      !----------------------------------------------------------------------
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         zfu(:,:,:) = 0._wp     ;   zfc(:,:,:) = 0._wp 
+         zfd(:,:,:) = 0._wp     ;   zwx(:,:,:) = 0._wp   
+         !
+!!gm why not using a SHIFT instruction...
+         DO jk = 1, jpkm1     !--- Computation of the ustream and downstream value of the tracer and the mask
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zfc(ji,jj,jk) = ptb(ji-1,jj,jk,jn)        ! Upstream   in the x-direction for the tracer
+                  zfd(ji,jj,jk) = ptb(ji+1,jj,jk,jn)        ! Downstream in the x-direction for the tracer
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1. , zfd(:,:,:), 'T', 1. )   ! Lateral boundary conditions 
+         
+         !
+         ! Horizontal advective fluxes
+         ! ---------------------------
+         DO jk = 1, jpkm1                             
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.         
+                  zdir = 0.5 + SIGN( 0.5, pun(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  zfu(ji,jj,jk) = zdir * zfc(ji,jj,jk ) + ( 1. - zdir ) * zfd(ji+1,jj,jk)  ! FU in the x-direction for T 
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.   
+                  zdir = 0.5 + SIGN( 0.5, pun(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  zdx = ( zdir * e1t(ji,jj) + ( 1. - zdir ) * e1t(ji+1,jj) ) * e2u(ji,jj) * e3u_n(ji,jj,jk)
+                  zwx(ji,jj,jk)  = ABS( pun(ji,jj,jk) ) * p2dt / zdx    ! (0<zc_cfl<1 : Courant number on x-direction)
+                  zfc(ji,jj,jk)  = zdir * ptb(ji  ,jj,jk,jn) + ( 1. - zdir ) * ptb(ji+1,jj,jk,jn)  ! FC in the x-direction for T
+                  zfd(ji,jj,jk)  = zdir * ptb(ji+1,jj,jk,jn) + ( 1. - zdir ) * ptb(ji  ,jj,jk,jn)  ! FD in the x-direction for T
+               END DO
+            END DO
+         END DO 
+         !--- Lateral boundary conditions 
+         CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1. , zfd(:,:,:), 'T', 1., zfc(:,:,:), 'T', 1.,  zwx(:,:,:), 'T', 1. )
+
+         !--- QUICKEST scheme
+         CALL quickest( zfu, zfd, zfc, zwx )
+         !
+         ! Mask at the T-points in the x-direction (mask=0 or mask=1)
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.               
+                  zfu(ji,jj,jk) = tmask(ji-1,jj,jk) + tmask(ji,jj,jk) + tmask(ji+1,jj,jk) - 2.
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1. )      ! Lateral boundary conditions 
+
+         !
+         ! Tracer flux on the x-direction
+         DO jk = 1, jpkm1  
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.               
+                  zdir = 0.5 + SIGN( 0.5, pun(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  !--- If the second ustream point is a land point
+                  !--- the flux is computed by the 1st order UPWIND scheme
+                  zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji+1,jj,jk)
+                  zwx(ji,jj,jk) = zmsk * zwx(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
+                  zwx(ji,jj,jk) = zwx(ji,jj,jk) * pun(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( 'traadv_qck', zwx(:,:,:), 'T', 1. ) ! Lateral boundary conditions
+         !
+         ! Computation of the trend
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.  
+                  zbtr = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  ! horizontal advective trends
+                  ztra = - zbtr * ( zwx(ji,jj,jk) - zwx(ji-1,jj,jk) )
+                  !--- add it to the general tracer trends
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra
+               END DO
+            END DO
+         END DO
+         !                                 ! trend diagnostics
+         IF( l_trd )   CALL trd_tra( kt, cdtype, jn, jptra_xad, zwx, pun, ptn(:,:,:,jn) )
+         !
+      END DO
+      !
+   END SUBROUTINE tra_adv_qck_i
+
+
+   SUBROUTINE tra_adv_qck_j( kt, cdtype, p2dt, pvn,                &
+      &                                        ptb, ptn, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                              , INTENT(in   ) ::   kt         ! ocean time-step index
+      CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
+      INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
+      REAL(wp)                             , INTENT(in   ) ::   p2dt       ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pvn        ! j-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 
+      !!
+      INTEGER  :: ji, jj, jk, jn                ! dummy loop indices
+      REAL(wp) :: ztra, zbtr, zdir, zdx, zmsk   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwy, zfu, zfc, zfd   ! 3D workspace
+      !----------------------------------------------------------------------
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         zfu(:,:,:) = 0.0     ;   zfc(:,:,:) = 0.0  
+         zfd(:,:,:) = 0.0     ;   zwy(:,:,:) = 0.0     
+         !                                                  
+         DO jk = 1, jpkm1                                
+            !                                             
+            !--- Computation of the ustream and downstream value of the tracer and the mask
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ! Upstream in the x-direction for the tracer
+                  zfc(ji,jj,jk) = ptb(ji,jj-1,jk,jn)
+                  ! Downstream in the x-direction for the tracer
+                  zfd(ji,jj,jk) = ptb(ji,jj+1,jk,jn)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'traadv_qck', zfc(:,:,:), 'T', 1. , zfd(:,:,:), 'T', 1. )   ! Lateral boundary conditions 
+
+         
+         !
+         ! Horizontal advective fluxes
+         ! ---------------------------
+         !
+         DO jk = 1, jpkm1                             
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.         
+                  zdir = 0.5 + SIGN( 0.5, pvn(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  zfu(ji,jj,jk) = zdir * zfc(ji,jj,jk ) + ( 1. - zdir ) * zfd(ji,jj+1,jk)  ! FU in the x-direction for T 
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.   
+                  zdir = 0.5 + SIGN( 0.5, pvn(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  zdx = ( zdir * e2t(ji,jj) + ( 1. - zdir ) * e2t(ji,jj+1) ) * e1v(ji,jj) * e3v_n(ji,jj,jk)
+                  zwy(ji,jj,jk)  = ABS( pvn(ji,jj,jk) ) * p2dt / zdx    ! (0<zc_cfl<1 : Courant number on x-direction)
+                  zfc(ji,jj,jk)  = zdir * ptb(ji,jj  ,jk,jn) + ( 1. - zdir ) * ptb(ji,jj+1,jk,jn)  ! FC in the x-direction for T
+                  zfd(ji,jj,jk)  = zdir * ptb(ji,jj+1,jk,jn) + ( 1. - zdir ) * ptb(ji,jj  ,jk,jn)  ! FD in the x-direction for T
+               END DO
+            END DO
+         END DO
+
+         !--- Lateral boundary conditions 
+         CALL lbc_lnk_multi( 'traadv_qck', zfu(:,:,:), 'T', 1. , zfd(:,:,:), 'T', 1., zfc(:,:,:), 'T', 1., zwy(:,:,:), 'T', 1. )
+
+         !--- QUICKEST scheme
+         CALL quickest( zfu, zfd, zfc, zwy )
+         !
+         ! Mask at the T-points in the x-direction (mask=0 or mask=1)
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.               
+                  zfu(ji,jj,jk) = tmask(ji,jj-1,jk) + tmask(ji,jj,jk) + tmask(ji,jj+1,jk) - 2.
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'traadv_qck', zfu(:,:,:), 'T', 1. )    !--- Lateral boundary conditions 
+         !
+         ! Tracer flux on the x-direction
+         DO jk = 1, jpkm1  
+            !
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.               
+                  zdir = 0.5 + SIGN( 0.5, pvn(ji,jj,jk) )   ! if pun > 0 : zdir = 1 otherwise zdir = 0 
+                  !--- If the second ustream point is a land point
+                  !--- the flux is computed by the 1st order UPWIND scheme
+                  zmsk = zdir * zfu(ji,jj,jk) + ( 1. - zdir ) * zfu(ji,jj+1,jk)
+                  zwy(ji,jj,jk) = zmsk * zwy(ji,jj,jk) + ( 1. - zmsk ) * zfc(ji,jj,jk)
+                  zwy(ji,jj,jk) = zwy(ji,jj,jk) * pvn(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( 'traadv_qck', zwy(:,:,:), 'T', 1. ) ! Lateral boundary conditions
+         !
+         ! Computation of the trend
+         DO jk = 1, jpkm1  
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.  
+                  zbtr = r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  ! horizontal advective trends
+                  ztra = - zbtr * ( 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
+               END DO
+            END DO
+         END DO
+         !                                 ! trend diagnostics
+         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( l_ptr )   CALL dia_ptr_hst( jn, 'adv', zwy(:,:,:) )
+         !
+      END DO
+      !
+   END SUBROUTINE tra_adv_qck_j
+
+
+   SUBROUTINE tra_adv_cen2_k( kt, cdtype, pwn,           &
+     &                                    ptn, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                              , INTENT(in   ) ::   kt       ! ocean time-step index
+      CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype   ! =TRA or TRC (tracer indicator)
+      INTEGER                              , INTENT(in   ) ::   kjpt     ! number of tracers
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pwn      ! vertical velocity 
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptn      ! before and now tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta      ! tracer trend 
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwz   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      zwz(:,:, 1 ) = 0._wp       ! surface & bottom values set to zero for all tracers
+      zwz(:,:,jpk) = 0._wp
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         !
+         DO jk = 2, jpkm1                    !* Interior point   (w-masked 2nd order centered flux)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zwz(ji,jj,jk) = 0.5 * pwn(ji,jj,jk) * ( ptn(ji,jj,jk-1,jn) + ptn(ji,jj,jk,jn) ) * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         IF( ln_linssh ) THEN                !* top value   (only in linear free surf. as zwz is multiplied by wmask)
+            IF( ln_isfcav ) THEN                  ! ice-shelf cavities (top of the ocean)
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zwz(ji,jj, mikt(ji,jj) ) = pwn(ji,jj,mikt(ji,jj)) * ptn(ji,jj,mikt(ji,jj),jn)   ! linear free surface 
+                  END DO
+               END DO   
+            ELSE                                   ! no ocean cavities (only ocean surface)
+               zwz(:,:,1) = pwn(:,:,1) * ptn(:,:,1,jn)
+            ENDIF
+         ENDIF
+         !
+         DO jk = 1, jpkm1          !==  Tracer flux divergence added to the general trend  ==!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) - ( zwz(ji,jj,jk) - zwz(ji,jj,jk+1) )   &
+                     &                                * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !                                 ! Send trends for diagnostic
+         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_zad, zwz, pwn, ptn(:,:,:,jn) )
+         !
+      END DO
+      !
+   END SUBROUTINE tra_adv_cen2_k
+
+
+   SUBROUTINE quickest( pfu, pfd, pfc, puc )
+      !!----------------------------------------------------------------------
+      !!
+      !! ** Purpose :  Computation of advective flux with Quickest scheme
+      !!
+      !! ** Method :   
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfu   ! second upwind point
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfd   ! first douwning point
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pfc   ! the central point (or the first upwind point)
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   puc   ! input as Courant number ; output as flux
+      !!
+      INTEGER  ::  ji, jj, jk               ! dummy loop indices 
+      REAL(wp) ::  zcoef1, zcoef2, zcoef3   ! local scalars          
+      REAL(wp) ::  zc, zcurv, zfho          !   -      -
+      !----------------------------------------------------------------------
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zc     = puc(ji,jj,jk)                         ! Courant number
+               zcurv  = pfd(ji,jj,jk) + pfu(ji,jj,jk) - 2. * pfc(ji,jj,jk)
+               zcoef1 = 0.5 *      ( pfc(ji,jj,jk) + pfd(ji,jj,jk) )
+               zcoef2 = 0.5 * zc * ( pfd(ji,jj,jk) - pfc(ji,jj,jk) )
+               zcoef3 = ( 1. - ( zc * zc ) ) * r1_6 * zcurv
+               zfho   = zcoef1 - zcoef2 - zcoef3              !  phi_f QUICKEST 
+               !
+               zcoef1 = pfd(ji,jj,jk) - pfu(ji,jj,jk)
+               zcoef2 = ABS( zcoef1 )
+               zcoef3 = ABS( zcurv )
+               IF( zcoef3 >= zcoef2 ) THEN
+                  zfho = pfc(ji,jj,jk) 
+               ELSE
+                  zcoef3 = pfu(ji,jj,jk) + ( ( pfc(ji,jj,jk) - pfu(ji,jj,jk) ) / MAX( zc, 1.e-9 ) )    ! phi_REF
+                  IF( zcoef1 >= 0. ) THEN
+                     zfho = MAX( pfc(ji,jj,jk), zfho ) 
+                     zfho = MIN( zfho, MIN( zcoef3, pfd(ji,jj,jk) ) ) 
+                  ELSE
+                     zfho = MIN( pfc(ji,jj,jk), zfho ) 
+                     zfho = MAX( zfho, MAX( zcoef3, pfd(ji,jj,jk) ) ) 
+                  ENDIF
+               ENDIF
+               puc(ji,jj,jk) = zfho
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE quickest
+
+   !!======================================================================
+END MODULE traadv_qck
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_ubs.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_ubs.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traadv_ubs.F90	(revision 14097)
@@ -0,0 +1,377 @@
+MODULE traadv_ubs
+   !!==============================================================================
+   !!                       ***  MODULE  traadv_ubs  ***
+   !! Ocean active tracers:  horizontal & vertical advective trend
+   !!==============================================================================
+   !! History :  1.0  !  2006-08  (L. Debreu, R. Benshila)  Original code
+   !!            3.3  !  2010-05  (C. Ethe, G. Madec)  merge TRC-TRA + switch from velocity to transport
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_adv_ubs : update the tracer trend with the horizontal
+   !!                 advection trends using a third order biaised scheme  
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE trd_oce        ! trends: ocean variables
+   USE traadv_fct      ! acces to routine interp_4th_cpt 
+   USE trdtra         ! trends manager: tracers 
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   !
+   USE iom            ! I/O library
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! massively parallel library
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link)
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_adv_ubs   ! routine called by traadv module
+
+   LOGICAL :: l_trd   ! flag to compute trends
+   LOGICAL :: l_ptr   ! flag to compute poleward transport
+   LOGICAL :: l_hst   ! flag to compute heat transport
+
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_adv_ubs( kt, kit000, cdtype, p2dt, pun, pvn, pwn,          &
+      &                                                ptb, ptn, pta, kjpt, kn_ubs_v )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_ubs  ***
+      !!                 
+      !! ** Purpose :   Compute the now trend due to the advection of tracers
+      !!      and add it to the general trend of passive tracer equations.
+      !!
+      !! ** Method  :   The 3rd order Upstream Biased Scheme (UBS) is based on an
+      !!      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
+      !!          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:
+      !!          zltu = 1/e3t di[ e2u e3u / e1u di[Tb] ]
+      !!        This results in a dissipatively dominant (i.e. hyper-diffusive) 
+      !!      truncation error. The overall performance of the advection scheme 
+      !!      is similar to that reported in (Farrow and Stevens, 1995). 
+      !!        For stability reasons, the first term of the fluxes which corresponds
+      !!      to a second order centered scheme is evaluated using the now velocity 
+      !!      (centered in time) while the second term which is the diffusive part 
+      !!      of the scheme, is evaluated using the before velocity (forward in time). 
+      !!      Note that UBS is not positive. Do not use it on passive tracers.
+      !!                On the vertical, the advection is evaluated using a FCT scheme,
+      !!      as the UBS have been found to be too diffusive. 
+      !!                kn_ubs_v argument controles whether the FCT is based on 
+      !!      a 2nd order centrered scheme (kn_ubs_v=2) or on a 4th order compact 
+      !!      scheme (kn_ubs_v=4).
+      !!
+      !! ** Action : - update pta  with the now advective tracer trends
+      !!             - send trends to trdtra module for further diagnostcs (l_trdtra=T)
+      !!             - htr_adv, str_adv : poleward advective heat and salt transport (ln_diaptr=T)
+      !!
+      !! Reference : Shchepetkin, A. F., J. C. McWilliams, 2005, Ocean Modelling, 9, 347-404. 
+      !!             Farrow, D.E., Stevens, D.P., 1995, J. Phys. Ocean. 25, 1731Ð1741. 
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kn_ubs_v        ! number of tracers
+      REAL(wp)                             , INTENT(in   ) ::   p2dt            ! tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pun, pvn, pwn   ! 3 ocean transport 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 
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   ztra, zbtr, zcoef                       ! local scalars
+      REAL(wp) ::   zfp_ui, zfm_ui, zcenut, ztak, zfp_wk, zfm_wk   !   -      -
+      REAL(wp) ::   zfp_vj, zfm_vj, zcenvt, zeeu, zeev, z_hdivn    !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztu, ztv, zltu, zltv, zti, ztw   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_ubs :  horizontal UBS advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      l_trd = .FALSE.
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )      l_trd = .TRUE.
+      IF(   cdtype == 'TRA' .AND. ln_diaptr )                                               l_ptr = .TRUE. 
+      IF(   cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                          iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) ) l_hst = .TRUE.
+      !
+      ztw (:,:, 1 ) = 0._wp      ! surface & bottom value : set to zero for all tracers
+      zltu(:,:,jpk) = 0._wp   ;   zltv(:,:,jpk) = 0._wp
+      ztw (:,:,jpk) = 0._wp   ;   zti (:,:,jpk) = 0._wp
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         !                                              
+         DO jk = 1, jpkm1        !==  horizontal laplacian of before tracer ==!
+            DO jj = 1, jpjm1              ! First derivative (masked gradient)
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zeeu = e2_e1u(ji,jj) * e3u_n(ji,jj,jk) * umask(ji,jj,jk)
+                  zeev = e1_e2v(ji,jj) * e3v_n(ji,jj,jk) * vmask(ji,jj,jk)
+                  ztu(ji,jj,jk) = zeeu * ( ptb(ji+1,jj  ,jk,jn) - ptb(ji,jj,jk,jn) )
+                  ztv(ji,jj,jk) = zeev * ( ptb(ji  ,jj+1,jk,jn) - ptb(ji,jj,jk,jn) )
+               END DO
+            END DO
+            DO jj = 2, jpjm1              ! Second derivative (divergence)
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zcoef = 1._wp / ( 6._wp * e3t_n(ji,jj,jk) )
+                  zltu(ji,jj,jk) = (  ztu(ji,jj,jk) - ztu(ji-1,jj,jk)  ) * zcoef
+                  zltv(ji,jj,jk) = (  ztv(ji,jj,jk) - ztv(ji,jj-1,jk)  ) * zcoef
+               END DO
+            END DO
+            !                                    
+         END DO         
+         CALL lbc_lnk( 'traadv_ubs', zltu, 'T', 1. )   ;    CALL lbc_lnk( 'traadv_ubs', zltv, 'T', 1. )   ! Lateral boundary cond. (unchanged sgn)
+         !    
+         DO jk = 1, jpkm1        !==  Horizontal advective fluxes  ==!     (UBS)
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zfp_ui = pun(ji,jj,jk) + ABS( pun(ji,jj,jk) )      ! upstream transport (x2)
+                  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) )
+                  !                                                  ! 2nd order centered advective fluxes (x2)
+                  zcenut = pun(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji+1,jj  ,jk,jn) )
+                  zcenvt = pvn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji  ,jj+1,jk,jn) )
+                  !                                                  ! UBS advective fluxes
+                  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
+         END DO         
+         !
+         zltu(:,:,:) = pta(:,:,:,jn)      ! store the initial trends before its update
+         !
+         DO jk = 1, jpkm1        !==  add the horizontal advective trend  ==!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  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)  ) * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+            !                                             
+         END DO
+         !
+         zltu(:,:,:) = pta(:,:,:,jn) - zltu(:,:,:)    ! Horizontal advective trend used in vertical 2nd order FCT case
+         !                                            ! and/or in trend diagnostic (l_trd=T) 
+         !                
+         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( l_ptr )  CALL dia_ptr_hst( jn, 'adv', ztv(:,:,:) )
+         !                                !  heati/salt transport
+         IF( l_hst )  CALL dia_ar5_hst( jn, 'adv', ztu(:,:,:), ztv(:,:,:) )
+         !
+         !
+         !                       !== vertical advective trend  ==!
+         !
+         SELECT CASE( kn_ubs_v )       ! select the vertical advection scheme
+         !
+         CASE(  2  )                   ! 2nd order FCT 
+            !         
+            IF( l_trd )   zltv(:,:,:) = pta(:,:,:,jn)          ! store pta if trend diag.
+            !
+            !                          !*  upstream advection with initial mass fluxes & intermediate update  ==!
+            DO jk = 2, jpkm1                 ! Interior value (w-masked)
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zfp_wk = pwn(ji,jj,jk) + ABS( pwn(ji,jj,jk) )
+                     zfm_wk = pwn(ji,jj,jk) - ABS( pwn(ji,jj,jk) )
+                     ztw(ji,jj,jk) = 0.5_wp * (  zfp_wk * ptb(ji,jj,jk,jn) + zfm_wk * ptb(ji,jj,jk-1,jn)  ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO 
+            IF( ln_linssh ) THEN             ! top ocean value (only in linear free surface as ztw has been w-masked)
+               IF( ln_isfcav ) THEN                ! top of the ice-shelf cavities and at the ocean surface
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        ztw(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   
+               ELSE                                ! no cavities: only at the ocean surface
+                  ztw(:,:,1) = pwn(:,:,1) * ptb(:,:,1,jn)
+               ENDIF
+            ENDIF
+            !
+            DO jk = 1, jpkm1           !* trend and after field with monotonic scheme
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ztak = - ( ztw(ji,jj,jk) - ztw(ji,jj,jk+1) ) * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                     pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn) +  ztak 
+                     zti(ji,jj,jk)    = ( ptb(ji,jj,jk,jn) + p2dt * ( ztak + zltu(ji,jj,jk) ) ) * tmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            CALL lbc_lnk( 'traadv_ubs', zti, 'T', 1. )      ! Lateral boundary conditions on zti, zsi   (unchanged sign)
+            !
+            !                          !*  anti-diffusive flux : high order minus low order
+            DO jk = 2, jpkm1        ! Interior value  (w-masked)
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     ztw(ji,jj,jk) = (   0.5_wp * pwn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj,jk-1,jn) )   &
+                        &              - ztw(ji,jj,jk)   ) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            !                                            ! top ocean value: high order == upstream  ==>>  zwz=0
+            IF( ln_linssh )   ztw(:,:, 1 ) = 0._wp       ! only ocean surface as interior zwz values have been w-masked
+            !
+            CALL nonosc_z( ptb(:,:,:,jn), ztw, zti, p2dt )      !  monotonicity algorithm
+            !
+         CASE(  4  )                               ! 4th order COMPACT
+            CALL interp_4th_cpt( ptn(:,:,:,jn) , ztw )         ! 4th order compact interpolation of T at w-point
+            DO jk = 2, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     ztw(ji,jj,jk) = pwn(ji,jj,jk) * ztw(ji,jj,jk) * wmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            IF( ln_linssh )   ztw(:,:, 1 ) = pwn(:,:,1) * ptn(:,:,1,jn)     !!gm ISF & 4th COMPACT doesn't work
+            !
+         END SELECT
+         !
+         DO jk = 1, jpkm1        !  final trend with corrected fluxes
+            DO jj = 2, jpjm1 
+               DO ji = fs_2, fs_jpim1   ! vector opt.   
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) - ( ztw(ji,jj,jk) - ztw(ji,jj,jk+1) ) * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF( l_trd )  THEN       ! vertical advective trend diagnostics
+            DO jk = 1, jpkm1                       ! (compute -w.dk[ptn]= -dk[w.ptn] + ptn.dk[w])
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     zltv(ji,jj,jk) = pta(ji,jj,jk,jn) - zltv(ji,jj,jk)                          &
+                        &           + ptn(ji,jj,jk,jn) * (  pwn(ji,jj,jk) - pwn(ji,jj,jk+1)  )   &
+                        &                              * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, zltv )
+         ENDIF
+         !
+      END DO
+      !
+   END SUBROUTINE tra_adv_ubs
+
+
+   SUBROUTINE nonosc_z( pbef, pcc, paft, p2dt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE nonosc_z  ***
+      !!     
+      !! **  Purpose :   compute monotonic tracer fluxes from the upstream 
+      !!       scheme and the before field by a nonoscillatory algorithm 
+      !!
+      !! **  Method  :   ... ???
+      !!       warning : pbef and paft must be masked, but the boundaries
+      !!       conditions on the fluxes are not necessary zalezak (1979)
+      !!       drange (1995) multi-dimensional forward-in-time and upstream-
+      !!       in-space based differencing for fluid
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in   )                          ::   p2dt   ! tracer time-step
+      REAL(wp),                DIMENSION (jpi,jpj,jpk) ::   pbef   ! before field
+      REAL(wp), INTENT(inout), DIMENSION (jpi,jpj,jpk) ::   paft   ! after field
+      REAL(wp), INTENT(inout), DIMENSION (jpi,jpj,jpk) ::   pcc    ! monotonic flux in the k direction
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ikm1         ! local integer
+      REAL(wp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zbetup, zbetdo     ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      zbig  = 1.e+40_wp
+      zrtrn = 1.e-15_wp
+      zbetup(:,:,:) = 0._wp   ;   zbetdo(:,:,:) = 0._wp
+      !
+      ! Search local extrema
+      ! --------------------
+      !                    ! large negative value (-zbig) inside land
+      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:) - zbig * ( 1.e0 - tmask(:,:,:) )
+      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:) - zbig * ( 1.e0 - tmask(:,:,:) )
+      !
+      DO jk = 1, jpkm1     ! search maximum in neighbourhood
+         ikm1 = MAX(jk-1,1)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zbetup(ji,jj,jk) = MAX(  pbef(ji  ,jj  ,jk  ), paft(ji  ,jj  ,jk  ),   &
+                  &                     pbef(ji  ,jj  ,ikm1), pbef(ji  ,jj  ,jk+1),   &
+                  &                     paft(ji  ,jj  ,ikm1), paft(ji  ,jj  ,jk+1)  )
+            END DO
+         END DO
+      END DO
+      !                    ! large positive value (+zbig) inside land
+      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:) + zbig * ( 1.e0 - tmask(:,:,:) )
+      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:) + zbig * ( 1.e0 - tmask(:,:,:) )
+      !
+      DO jk = 1, jpkm1     ! search minimum in neighbourhood
+         ikm1 = MAX(jk-1,1)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zbetdo(ji,jj,jk) = MIN(  pbef(ji  ,jj  ,jk  ), paft(ji  ,jj  ,jk  ),   &
+                  &                     pbef(ji  ,jj  ,ikm1), pbef(ji  ,jj  ,jk+1),   &
+                  &                     paft(ji  ,jj  ,ikm1), paft(ji  ,jj  ,jk+1)  )
+            END DO
+         END DO
+      END DO
+      !                    ! restore masked values to zero
+      pbef(:,:,:) = pbef(:,:,:) * tmask(:,:,:)
+      paft(:,:,:) = paft(:,:,:) * tmask(:,:,:)
+      !
+      ! Positive and negative part of fluxes and beta terms
+      ! ---------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ! positive & negative part of the flux
+               zpos = MAX( 0., pcc(ji  ,jj  ,jk+1) ) - MIN( 0., pcc(ji  ,jj  ,jk  ) )
+               zneg = MAX( 0., pcc(ji  ,jj  ,jk  ) ) - MIN( 0., pcc(ji  ,jj  ,jk+1) )
+               ! up & down beta terms
+               zbt = e1e2t(ji,jj) * e3t_n(ji,jj,jk) / p2dt
+               zbetup(ji,jj,jk) = ( zbetup(ji,jj,jk) - paft(ji,jj,jk) ) / (zpos+zrtrn) * zbt
+               zbetdo(ji,jj,jk) = ( paft(ji,jj,jk) - zbetdo(ji,jj,jk) ) / (zneg+zrtrn) * zbt
+            END DO
+         END DO
+      END DO
+      !
+      ! monotonic flux in the k direction, i.e. pcc
+      ! -------------------------------------------
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               za = MIN( 1., zbetdo(ji,jj,jk), zbetup(ji,jj,jk-1) )
+               zb = MIN( 1., zbetup(ji,jj,jk), zbetdo(ji,jj,jk-1) )
+               zc = 0.5 * ( 1.e0 + SIGN( 1.e0, pcc(ji,jj,jk) ) )
+               pcc(ji,jj,jk) = pcc(ji,jj,jk) * ( zc * za + ( 1.e0 - zc) * zb )
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE nonosc_z
+
+   !!======================================================================
+END MODULE traadv_ubs
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbc.F90	(revision 14097)
@@ -0,0 +1,196 @@
+MODULE trabbc
+   !!==============================================================================
+   !!                       ***  MODULE  trabbc  ***
+   !! Ocean active tracers:  bottom boundary condition (geothermal heat flux)
+   !!==============================================================================
+   !! History :  OPA  ! 1999-10 (G. Madec)  original code
+   !!   NEMO     1.0  ! 2002-08 (G. Madec)  free form + modules
+   !!             -   ! 2002-11 (A. Bozec)  tra_bbc_init: original code
+   !!            3.3  ! 2010-10 (G. Madec)  dynamical allocation + suppression of key_trabbc
+   !!             -   ! 2010-11 (G. Madec)  use mbkt array (deepest ocean t-level)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_bbc       : update the tracer trend at ocean bottom 
+   !!   tra_bbc_init  : initialization of geothermal heat flux trend
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! domain: ocean
+   USE phycst         ! physical constants
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! xIOS 
+   USE fldread        ! read input fields
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+   USE prtctl         ! Print control
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC tra_bbc          ! routine called by step.F90
+   PUBLIC tra_bbc_init     ! routine called by opa.F90
+
+   !                                 !!* Namelist nambbc: bottom boundary condition *
+   LOGICAL, PUBLIC ::   ln_trabbc     !: Geothermal heat flux flag
+   INTEGER         ::   nn_geoflx     !  Geothermal flux (=1:constant flux, =2:read in file )
+   REAL(wp)        ::   rn_geoflx_cst !  Constant value of geothermal heat flux
+
+   REAL(wp), PUBLIC , ALLOCATABLE, DIMENSION(:,:) ::   qgh_trd0   ! geothermal heating trend
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_qgh   ! structure of input qgh (file informations, fields read)
+ 
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_bbc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_bbc  ***
+      !!
+      !! ** Purpose :   Compute the bottom boundary contition on temperature 
+      !!              associated with geothermal heating and add it to the 
+      !!              general trend of temperature equations.
+      !!
+      !! ** Method  :   The geothermal heat flux set to its constant value of 
+      !!              86.4 mW/m2 (Stein and Stein 1992, Huang 1999).
+      !!       The temperature trend associated to this heat flux through the
+      !!       ocean bottom can be computed once and is added to the temperature
+      !!       trend juste above the bottom at each time step:
+      !!            ta = ta + Qsf / (rau0 rcp e3T) for k= mbkt
+      !!       Where Qsf is the geothermal heat flux.
+      !!
+      !! ** Action  : - update the temperature trends with geothermal heating trend
+      !!              - send the trend for further diagnostics (ln_trdtra=T)
+      !!
+      !! References : Stein, C. A., and S. Stein, 1992, Nature, 359, 123-129.
+      !!              Emile-Geay and Madec, 2009, Ocean Science.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj    ! dummy loop indices
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_bbc')
+      !
+      IF( l_trdtra )   THEN         ! Save the input temperature trend
+         ALLOCATE( ztrdt(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+      ENDIF
+      !                             !  Add the geothermal trend on temperature
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            tsa(ji,jj,mbkt(ji,jj),jp_tem) = tsa(ji,jj,mbkt(ji,jj),jp_tem) + qgh_trd0(ji,jj) / e3t_n(ji,jj,mbkt(ji,jj))
+         END DO
+      END DO
+      !
+      CALL lbc_lnk( 'trabbc', tsa(:,:,:,jp_tem) , 'T', 1. )
+      !
+      IF( l_trdtra ) THEN        ! Send the trend for diagnostics
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_bbc, ztrdt )
+         DEALLOCATE( ztrdt )
+      ENDIF
+      !
+      CALL iom_put ( "hfgeou" , rau0_rcp * qgh_trd0(:,:) )
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' bbc  - Ta: ', mask1=tmask, clinfo3='tra-ta' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_bbc')
+      !
+   END SUBROUTINE tra_bbc
+
+
+   SUBROUTINE tra_bbc_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_bbc_init  ***
+      !!
+      !! ** Purpose :   Compute once for all the trend associated with geothermal
+      !!              heating that will be applied at each time step at the
+      !!              last ocean level
+      !!
+      !! ** Method  :   Read the nambbc namelist and check the parameters.
+      !!
+      !! ** Input   : - Namlist nambbc
+      !!              - NetCDF file  : geothermal_heating.nc ( if necessary )
+      !!
+      !! ** Action  : - read/fix the geothermal heat qgh_trd0
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj              ! dummy loop indices
+      INTEGER  ::   inum                ! temporary logical unit
+      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      INTEGER  ::   ierror              ! local integer
+      !
+      TYPE(FLD_N)        ::   sn_qgh    ! informations about the geotherm. field to be read
+      CHARACTER(len=256) ::   cn_dir    ! Root directory for location of ssr files
+      !!
+      NAMELIST/nambbc/ln_trabbc, nn_geoflx, rn_geoflx_cst, sn_qgh, cn_dir 
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )
+      READ  ( numnam_ref, nambbc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambbc in reference namelist' )
+      !
+      REWIND( numnam_cfg )
+      READ  ( numnam_cfg, nambbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nambbc in configuration namelist' )
+      IF(lwm) WRITE ( numond, nambbc )
+      !
+      IF(lwp) THEN                     ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_bbc : Bottom Boundary Condition (bbc), apply a Geothermal heating'
+         WRITE(numout,*) '~~~~~~~   '
+         WRITE(numout,*) '   Namelist nambbc : set bbc parameters'
+         WRITE(numout,*) '      Apply a geothermal heating at ocean bottom   ln_trabbc     = ', ln_trabbc
+         WRITE(numout,*) '      type of geothermal flux                      nn_geoflx     = ', nn_geoflx
+         WRITE(numout,*) '      Constant geothermal flux value               rn_geoflx_cst = ', rn_geoflx_cst
+         WRITE(numout,*)
+      ENDIF
+      !
+      IF( ln_trabbc ) THEN             !==  geothermal heating  ==!
+         !
+         ALLOCATE( qgh_trd0(jpi,jpj) )    ! allocation
+         !
+         SELECT CASE ( nn_geoflx )        ! geothermal heat flux / (rauO * Cp)
+         !
+         CASE ( 1 )                          !* constant flux
+            IF(lwp) WRITE(numout,*) '   ==>>>   constant heat flux  =   ', rn_geoflx_cst
+            qgh_trd0(:,:) = r1_rau0_rcp * rn_geoflx_cst
+            !
+         CASE ( 2 )                          !* variable geothermal heat flux : read the geothermal fluxes in mW/m2
+            IF(lwp) WRITE(numout,*) '   ==>>>   variable geothermal heat flux'
+            !
+            ALLOCATE( sf_qgh(1), STAT=ierror )
+            IF( ierror > 0 ) THEN
+               CALL ctl_stop( 'tra_bbc_init: unable to allocate sf_qgh structure' )   ;
+               RETURN
+            ENDIF
+            ALLOCATE( sf_qgh(1)%fnow(jpi,jpj,1)   )
+            IF( sn_qgh%ln_tint )   ALLOCATE( sf_qgh(1)%fdta(jpi,jpj,1,2) )
+            ! fill sf_chl with sn_chl and control print
+            CALL fld_fill( sf_qgh, (/ sn_qgh /), cn_dir, 'tra_bbc_init',   &
+               &          'bottom temperature boundary condition', 'nambbc', no_print )
+
+            CALL fld_read( nit000, 1, sf_qgh )                         ! Read qgh data
+            qgh_trd0(:,:) = r1_rau0_rcp * sf_qgh(1)%fnow(:,:,1) * 1.e-3 ! conversion in W/m2
+            !
+         CASE DEFAULT
+            WRITE(ctmp1,*) '     bad flag value for nn_geoflx = ', nn_geoflx
+            CALL ctl_stop( ctmp1 )
+         END SELECT
+         !
+      ELSE
+         IF(lwp) WRITE(numout,*) '   ==>>>   no geothermal heat flux'
+      ENDIF
+      !
+   END SUBROUTINE tra_bbc_init
+
+   !!======================================================================
+END MODULE trabbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trabbl.F90	(revision 14097)
@@ -0,0 +1,561 @@
+MODULE trabbl
+   !!==============================================================================
+   !!                       ***  MODULE  trabbl  ***
+   !! Ocean physics :  advective and/or diffusive bottom boundary layer scheme
+   !!==============================================================================
+   !! History :  OPA  ! 1996-06  (L. Mortier)  Original code
+   !!            8.0  ! 1997-11  (G. Madec)    Optimization
+   !!   NEMO     1.0  ! 2002-08  (G. Madec)  free form + modules
+   !!             -   ! 2004-01  (A. de Miranda, G. Madec, J.M. Molines ) add advective bbl
+   !!            3.3  ! 2009-11  (G. Madec)  merge trabbl and trabbl_adv + style + optimization
+   !!             -   ! 2010-04  (G. Madec)  Campin & Goosse advective bbl
+   !!             -   ! 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
+   !!            4.0  ! 2017-04  (G. Madec)  ln_trabbl namelist variable instead of a CPP key
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_bbl_alloc : allocate trabbl arrays
+   !!   tra_bbl       : update the tracer trends due to the bottom boundary layer (advective and/or diffusive)
+   !!   tra_bbl_dif   : generic routine to compute bbl diffusive trend
+   !!   tra_bbl_adv   : generic routine to compute bbl advective trend
+   !!   bbl           : computation of bbl diffu. flux coef. & transport in bottom boundary layer
+   !!   tra_bbl_init  : initialization, namelist read, parameters control
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constant
+   USE eosbn2         ! equation of state
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends: active tracers
+   !
+   USE iom            ! IOM library               
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions
+   USE prtctl         ! Print control
+   USE timing         ! Timing
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_bbl       !  routine called by step.F90
+   PUBLIC   tra_bbl_init  !  routine called by nemogcm.F90
+   PUBLIC   tra_bbl_dif   !  routine called by trcbbl.F90
+   PUBLIC   tra_bbl_adv   !     -      -          -
+   PUBLIC   bbl           !  routine called by trcbbl.F90 and dtadyn.F90
+
+   !                                !!* Namelist nambbl *
+   LOGICAL , PUBLIC ::   ln_trabbl   !: bottom boundary layer flag
+   INTEGER , PUBLIC ::   nn_bbl_ldf  !: =1   : diffusive bbl or not (=0)
+   INTEGER , PUBLIC ::   nn_bbl_adv  !: =1/2 : advective bbl or not (=0)
+   !                                            !  =1 : advective bbl using the bottom ocean velocity
+   !                                            !  =2 :     -      -  using utr_bbl proportional to grad(rho)
+   REAL(wp), PUBLIC ::   rn_ahtbbl   !: along slope bbl diffusive coefficient [m2/s]
+   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
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   utr_bbl  , vtr_bbl   ! u- (v-) transport in the bottom boundary layer
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   ahu_bbl  , ahv_bbl   ! masked diffusive bbl coeff. at u & v-pts
+
+   INTEGER , ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   mbku_d   , mbkv_d      ! vertical index of the "lower" bottom ocean U/V-level (PUBLIC for TAM)
+   INTEGER , ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   mgrhu    , mgrhv       ! = +/-1, sign of grad(H) in u-(v-)direction (PUBLIC for TAM)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)         ::   ahu_bbl_0, ahv_bbl_0   ! diffusive bbl flux coefficients at u and v-points
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   e3u_bbl_0, e3v_bbl_0   ! thichness of the bbl (e3) at u and v-points (PUBLIC for TAM)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION tra_bbl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION tra_bbl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( utr_bbl  (jpi,jpj) , ahu_bbl  (jpi,jpj) , mbku_d(jpi,jpj) , mgrhu(jpi,jpj) ,     &
+         &      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 )
+         !
+      CALL mpp_sum ( 'trabbl', tra_bbl_alloc )
+      IF( tra_bbl_alloc > 0 )   CALL ctl_warn('tra_bbl_alloc: allocation of arrays failed.')
+   END FUNCTION tra_bbl_alloc
+
+
+   SUBROUTINE tra_bbl( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE bbl  ***
+      !!
+      !! ** Purpose :   Compute the before tracer (t & s) trend associated
+      !!              with the bottom boundary layer and add it to the general
+      !!              trend of tracer equations.
+      !!
+      !! ** Method  :   Depending on namtra_bbl namelist parameters the bbl
+      !!              diffusive and/or advective contribution to the tracer trend
+      !!              is added to the general tracer trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step
+      !
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'tra_bbl')
+      !
+      IF( l_trdtra )   THEN                         !* Save the T-S input trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      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
+         !
+         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' )
+         ! lateral boundary conditions ; just need for outputs
+         CALL lbc_lnk_multi( 'trabbl', ahu_bbl, 'U', 1. , ahv_bbl, 'V', 1. )
+         CALL iom_put( "ahu_bbl", ahu_bbl )   ! bbl diffusive flux i-coef
+         CALL iom_put( "ahv_bbl", ahv_bbl )   ! bbl diffusive flux j-coef
+         !
+      ENDIF
+      !
+      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' )
+         ! lateral boundary conditions ; just need for outputs
+         CALL lbc_lnk_multi( 'trabbl', utr_bbl, 'U', 1. , vtr_bbl, 'V', 1. )
+         CALL iom_put( "uoce_bbl", utr_bbl )  ! bbl i-transport
+         CALL iom_put( "voce_bbl", vtr_bbl )  ! bbl j-transport
+         !
+      ENDIF
+
+      IF( l_trdtra )   THEN                      ! send the trends for further diagnostics
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_bbl, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_bbl, ztrds )
+         DEALLOCATE( ztrdt, ztrds )
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop( 'tra_bbl')
+      !
+   END SUBROUTINE tra_bbl
+
+
+   SUBROUTINE tra_bbl_dif( ptb, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_bbl_dif  ***
+      !!
+      !! ** Purpose :   Computes the bottom boundary horizontal and vertical
+      !!                advection terms.
+      !!
+      !! ** 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
+      !!      diffusion along the bottom slope is added to the general
+      !!      tracer trend, otherwise the additional trend is set to 0.
+      !!      A typical value of ahbt is 2000 m2/s (equivalent to
+      !!      a downslope velocity of 20 cm/s if the condition for slope
+      !!      convection is satified)
+      !!
+      !! ** Action  :   pta   increased by the bbl diffusive trend
+      !!
+      !! References : Beckmann, A., and R. Doscher, 1997, J. Phys.Oceanogr., 581-591.
+      !!              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
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta    ! tracer trend
+      !
+      INTEGER  ::   ji, jj, jn   ! dummy loop indices
+      INTEGER  ::   ik           ! local integers
+      REAL(wp) ::   zbtr         ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zptb   ! workspace
+      !!----------------------------------------------------------------------
+      !
+      DO jn = 1, kjpt                                     ! tracer loop
+         !                                                ! ===========
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               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
+         !               
+         DO jj = 2, jpjm1                                    ! Compute the trend
+            DO ji = 2, jpim1
+               ik = mbkt(ji,jj)                            ! bottom T-level index
+               pta(ji,jj,ik,jn) = pta(ji,jj,ik,jn)                                                  &
+                  &             + (  ahu_bbl(ji  ,jj  ) * ( zptb(ji+1,jj  ) - zptb(ji  ,jj  ) )     &
+                  &                - ahu_bbl(ji-1,jj  ) * ( zptb(ji  ,jj  ) - zptb(ji-1,jj  ) )     &
+                  &                + ahv_bbl(ji  ,jj  ) * ( zptb(ji  ,jj+1) - zptb(ji  ,jj  ) )     &
+                  &                - ahv_bbl(ji  ,jj-1) * ( zptb(ji  ,jj  ) - zptb(ji  ,jj-1) )  )  &
+                  &             * r1_e1e2t(ji,jj) / e3t_n(ji,jj,ik)
+            END DO
+         END DO
+         !                                                  ! ===========
+      END DO                                                ! end tracer
+      !                                                     ! ===========
+   END SUBROUTINE tra_bbl_dif
+
+
+   SUBROUTINE tra_bbl_adv( ptb, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_bbl  ***
+      !!
+      !! ** Purpose :   Compute the before passive tracer trend associated
+      !!     with the bottom boundary layer and add it to the general trend
+      !!     of tracer equations.
+      !! ** Method  :   advective bbl (nn_bbl_adv = 1 or 2) :
+      !!      nn_bbl_adv = 1   use of the ocean near bottom velocity as bbl velocity
+      !!      nn_bbl_adv = 2   follow Campin and Goosse (1999) implentation i.e.
+      !!                       transport proportional to the along-slope density gradient
+      !!
+      !! References : Beckmann, A., and R. Doscher, 1997, J. Phys.Oceanogr., 581-591.
+      !!              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
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta    ! tracer trend
+      !
+      INTEGER  ::   ji, jj, jk, jn           ! dummy loop indices
+      INTEGER  ::   iis , iid , ijs , ijd    ! local integers
+      INTEGER  ::   ikus, ikud, ikvs, ikvd   !   -       -
+      REAL(wp) ::   zbtr, ztra               ! local scalars
+      REAL(wp) ::   zu_bbl, zv_bbl           !   -      -
+      !!----------------------------------------------------------------------
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1            ! CAUTION start from i=1 to update i=2 when cyclic east-west
+               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)
+                  iid  = ji + MAX( 0, mgrhu(ji,jj) )   ;   iis  = ji + 1 - MAX( 0, mgrhu(ji,jj) )
+                  ikud = mbku_d(ji,jj)                 ;   ikus = mbku(ji,jj)
+                  zu_bbl = ABS( utr_bbl(ji,jj) )
+                  !
+                  !                                               ! up  -slope T-point (shelf bottom point)
+                  zbtr = r1_e1e2t(iis,jj) / e3t_n(iis,jj,ikus)
+                  ztra = zu_bbl * ( ptb(iid,jj,ikus,jn) - ptb(iis,jj,ikus,jn) ) * zbtr
+                  pta(iis,jj,ikus,jn) = pta(iis,jj,ikus,jn) + ztra
+                  !
+                  DO jk = ikus, ikud-1                            ! down-slope upper to down T-point (deep column)
+                     zbtr = r1_e1e2t(iid,jj) / e3t_n(iid,jj,jk)
+                     ztra = zu_bbl * ( ptb(iid,jj,jk+1,jn) - ptb(iid,jj,jk,jn) ) * zbtr
+                     pta(iid,jj,jk,jn) = pta(iid,jj,jk,jn) + ztra
+                  END DO
+                  !
+                  zbtr = r1_e1e2t(iid,jj) / e3t_n(iid,jj,ikud)
+                  ztra = zu_bbl * ( ptb(iis,jj,ikus,jn) - ptb(iid,jj,ikud,jn) ) * zbtr
+                  pta(iid,jj,ikud,jn) = pta(iid,jj,ikud,jn) + ztra
+               ENDIF
+               !
+               IF( vtr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero j-direction bbl advection
+                  ! down-slope j/k-indices (deep)        &   up-slope j/k indices (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)
+                  zv_bbl = ABS( vtr_bbl(ji,jj) )
+                  !
+                  ! up  -slope T-point (shelf bottom point)
+                  zbtr = r1_e1e2t(ji,ijs) / e3t_n(ji,ijs,ikvs)
+                  ztra = zv_bbl * ( ptb(ji,ijd,ikvs,jn) - ptb(ji,ijs,ikvs,jn) ) * zbtr
+                  pta(ji,ijs,ikvs,jn) = pta(ji,ijs,ikvs,jn) + ztra
+                  !
+                  DO jk = ikvs, ikvd-1                            ! down-slope upper to down T-point (deep column)
+                     zbtr = r1_e1e2t(ji,ijd) / e3t_n(ji,ijd,jk)
+                     ztra = zv_bbl * ( ptb(ji,ijd,jk+1,jn) - ptb(ji,ijd,jk,jn) ) * zbtr
+                     pta(ji,ijd,jk,jn) = pta(ji,ijd,jk,jn)  + ztra
+                  END DO
+                  !                                               ! down-slope T-point (deep bottom point)
+                  zbtr = r1_e1e2t(ji,ijd) / e3t_n(ji,ijd,ikvd)
+                  ztra = zv_bbl * ( ptb(ji,ijs,ikvs,jn) - ptb(ji,ijd,ikvd,jn) ) * zbtr
+                  pta(ji,ijd,ikvd,jn) = pta(ji,ijd,ikvd,jn) + ztra
+               ENDIF
+            END DO
+            !
+         END DO
+         !                                                  ! ===========
+      END DO                                                ! end tracer
+      !                                                     ! ===========
+   END SUBROUTINE tra_bbl_adv
+
+
+   SUBROUTINE bbl( kt, kit000, cdtype )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE bbl  ***
+      !!
+      !! ** Purpose :   Computes the bottom boundary horizontal and vertical
+      !!                advection terms.
+      !!
+      !! ** 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
+      !!      diffusion along the bottom slope is added to the general
+      !!      tracer trend, otherwise the additional trend is set to 0.
+      !!      A typical value of ahbt is 2000 m2/s (equivalent to
+      !!      a downslope velocity of 20 cm/s if the condition for slope
+      !!      convection is satified)
+      !!              * 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
+      !!        i.e. transport proportional to the along-slope density gradient
+      !!
+      !!      NB: the along slope density gradient is evaluated using the
+      !!      local density (i.e. referenced at a common local depth).
+      !!
+      !! References : Beckmann, A., and R. Doscher, 1997, J. Phys.Oceanogr., 581-591.
+      !!              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
+      CHARACTER(len=3), INTENT(in   ) ::   cdtype   ! =TRA or TRC (tracer indicator)
+      !
+      INTEGER  ::   ji, jj                    ! dummy loop indices
+      INTEGER  ::   ik                        ! local integers
+      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( kt == kit000 )  THEN
+         IF(lwp)  WRITE(numout,*)
+         IF(lwp)  WRITE(numout,*) 'trabbl:bbl : Compute bbl velocities and diffusive coefficients in ', cdtype
+         IF(lwp)  WRITE(numout,*) '~~~~~~~~~~'
+      ENDIF
+      !                                        !* bottom variables (T, S, alpha, beta, depth, velocity)
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            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)
+            !
+            zdep(ji,jj) = gdept_n(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, 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.
+               !
+               !                                                   ! 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 )
+               ahv_bbl(ji,jj) = ( 0.5 - zsign ) * ahv_bbl_0(ji,jj)
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+      !                                   !-------------------!
+      IF( nn_bbl_adv /= 0 ) THEN          !   advective bbl   !
+         !                                !-------------------!
+         SELECT CASE ( nn_bbl_adv )             !* bbl transport type
+         !
+         CASE( 1 )                                   != use of upper velocity
+            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
+                  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
+                  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
+            END DO
+            !
+         CASE( 2 )                                 != bbl velocity = F( delta rho )
+            zgbbl = grav * rn_gambbl
+            DO jj = 1, jpjm1                            ! criteria: rho_up > rho_down
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  !                                                  ! 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)
+                  !
+                  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
+                  !  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)
+                  !
+                  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
+            END DO
+         END SELECT
+         !
+      ENDIF
+      !
+   END SUBROUTINE bbl
+
+
+   SUBROUTINE tra_bbl_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_bbl_init  ***
+      !!
+      !! ** Purpose :   Initialization for the bottom boundary layer scheme.
+      !!
+      !! ** Method  :   Read the nambbl namelist and check the parameters
+      !!              called by nemo_init at the first timestep (kit000)
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj                      ! dummy loop indices
+      INTEGER ::   ii0, ii1, ij0, ij1, ios     ! local integer
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmbku, zmbkv   ! workspace
+      !!
+      NAMELIST/nambbl/ ln_trabbl, nn_bbl_ldf, nn_bbl_adv, rn_ahtbbl, rn_gambbl
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist nambbl in reference namelist : Bottom boundary layer scheme
+      READ  ( numnam_ref, nambbl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nambbl in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist nambbl in configuration namelist : Bottom boundary layer scheme
+      READ  ( numnam_cfg, nambbl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nambbl in configuration namelist' )
+      IF(lwm) WRITE ( numond, nambbl )
+      !
+      l_bbl = .TRUE.                 !* flag to compute bbl coef and transport
+      !
+      IF(lwp) THEN                   !* Parameter control and print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_bbl_init : bottom boundary layer initialisation'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '       Namelist nambbl : set bbl parameters'
+         WRITE(numout,*) '          bottom boundary layer flag          ln_trabbl  = ', ln_trabbl
+      ENDIF
+      IF( .NOT.ln_trabbl )   RETURN
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) '          diffusive bbl (=1)   or not (=0)    nn_bbl_ldf = ', nn_bbl_ldf
+         WRITE(numout,*) '          advective bbl (=1/2) or not (=0)    nn_bbl_adv = ', nn_bbl_adv
+         WRITE(numout,*) '          diffusive bbl coefficient           rn_ahtbbl  = ', rn_ahtbbl, ' m2/s'
+         WRITE(numout,*) '          advective bbl coefficient           rn_gambbl  = ', rn_gambbl, ' s'
+      ENDIF
+      !
+      !                              ! allocate trabbl arrays
+      IF( tra_bbl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'tra_bbl_init : unable to allocate arrays' )
+      !
+      IF(lwp) THEN
+         IF( nn_bbl_adv == 1 )    WRITE(numout,*) '       * Advective BBL using upper velocity'
+         IF( nn_bbl_adv == 2 )    WRITE(numout,*) '       * Advective BBL using velocity = F( delta rho)'
+      ENDIF
+      !
+      !                             !* vertical index of  "deep" bottom u- and v-points
+      DO jj = 1, jpjm1                    ! (the "shelf" bottom k-indices are mbku and mbkv)
+         DO ji = 1, jpim1
+            mbku_d(ji,jj) = MAX(  mbkt(ji+1,jj  ) , mbkt(ji,jj)  )   ! >= 1 as mbkt=1 over land
+            mbkv_d(ji,jj) = MAX(  mbkt(ji  ,jj+1) , mbkt(ji,jj)  )
+         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
+      zmbku(:,:) = REAL( mbku_d(:,:), wp )   ;     zmbkv(:,:) = REAL( mbkv_d(:,:), wp )  
+      CALL lbc_lnk_multi( 'trabbl', zmbku,'U',1., zmbkv,'V',1.) 
+      mbku_d(:,:) = MAX( INT( zmbku(:,:) ), 1 ) ;  mbkv_d(:,:) = MAX( NINT( zmbkv(:,:) ), 1 )
+      !
+      !                             !* sign of grad(H) at u- and v-points; zero if grad(H) = 0
+      mgrhu(:,:) = 0   ;   mgrhv(:,:) = 0
+      DO jj = 1, jpjm1
+         DO ji = 1, jpim1
+            IF( gdept_0(ji+1,jj,mbkt(ji+1,jj)) - gdept_0(ji,jj,mbkt(ji,jj)) /= 0._wp ) THEN
+               mgrhu(ji,jj) = INT(  SIGN( 1.e0, gdept_0(ji+1,jj,mbkt(ji+1,jj)) - gdept_0(ji,jj,mbkt(ji,jj)) )  )
+            ENDIF
+            !
+            IF( gdept_0(ji,jj+1,mbkt(ji,jj+1)) - gdept_0(ji,jj,mbkt(ji,jj)) /= 0._wp ) THEN
+               mgrhv(ji,jj) = INT(  SIGN( 1.e0, gdept_0(ji,jj+1,mbkt(ji,jj+1)) - gdept_0(ji,jj,mbkt(ji,jj)) )  )
+            ENDIF
+         END DO
+      END DO
+      !
+      DO jj = 1, jpjm1              !* bbl thickness at u- (v-) point
+         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)) )
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'trabbl', e3u_bbl_0, 'U', 1. , e3v_bbl_0, 'V', 1. )      ! lateral boundary conditions
+      !
+      !                             !* masked diffusive flux coefficients
+      ahu_bbl_0(:,:) = rn_ahtbbl * e2_e1u(:,:) * e3u_bbl_0(:,:) * umask(:,:,1)
+      ahv_bbl_0(:,:) = rn_ahtbbl * e1_e2v(:,:) * e3v_bbl_0(:,:) * vmask(:,:,1)
+      !
+   END SUBROUTINE tra_bbl_init
+
+   !!======================================================================
+END MODULE trabbl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tradmp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tradmp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tradmp.F90	(revision 14097)
@@ -0,0 +1,228 @@
+MODULE tradmp
+   !!======================================================================
+   !!                       ***  MODULE  tradmp  ***
+   !! Ocean physics: internal restoring trend on active tracers (T and S)
+   !!======================================================================
+   !! History :  OPA  ! 1991-03  (O. Marti, G. Madec)  Original code
+   !!                 ! 1992-06  (M. Imbard)  doctor norme
+   !!                 ! 1998-07  (M. Imbard, G. Madec) ORCA version
+   !!            7.0  ! 2001-02  (M. Imbard)  add distance to coast, Original code
+   !!            8.1  ! 2001-02  (G. Madec, E. Durand)  cleaning
+   !!  NEMO      1.0  ! 2002-08  (G. Madec, E. Durand)  free form + modules
+   !!            3.2  ! 2009-08  (G. Madec, C. Talandier)  DOCTOR norm for namelist parameter
+   !!            3.3  ! 2010-06  (C. Ethe, G. Madec) merge TRA-TRC 
+   !!            3.4  ! 2011-04  (G. Madec, C. Ethe) Merge of dtatem and dtasal + suppression of CPP keys
+   !!            3.6  ! 2015-06  (T. Graham)  read restoring coefficient in a file
+   !!            3.7  ! 2015-10  (G. Madec)  remove useless trends arrays
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_dmp_alloc : allocate tradmp arrays
+   !!   tra_dmp       : update the tracer trend with the internal damping
+   !!   tra_dmp_init  : initialization, namlist read, parameters control
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean: variables
+   USE dom_oce        ! ocean: domain variables
+   USE c1d            ! 1D vertical configuration
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+   USE zdf_oce        ! ocean: vertical physics
+   USE phycst         ! physical constants
+   USE dtatsd         ! data: temperature & salinity
+   USE zdfmxl         ! vertical physics: mixed layer depth
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! XIOS
+   USE lib_mpp        ! MPP library
+   USE prtctl         ! Print control
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_dmp        ! called by step.F90
+   PUBLIC   tra_dmp_init   ! called by nemogcm.F90
+
+   !                                           !!* Namelist namtra_dmp : T & S newtonian damping *
+   LOGICAL            , PUBLIC ::   ln_tradmp   !: internal damping flag
+   INTEGER            , PUBLIC ::   nn_zdmp     !: = 0/1/2 flag for damping in the mixed layer
+   CHARACTER(LEN=200) , PUBLIC ::   cn_resto    !: name of netcdf file containing restoration coefficient field
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   resto    !: restoring coeff. on T and S (s-1)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION tra_dmp_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION tra_dmp_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( resto(jpi,jpj,jpk), STAT= tra_dmp_alloc )
+      !
+      CALL mpp_sum ( 'tradmp', tra_dmp_alloc )
+      IF( tra_dmp_alloc > 0 )   CALL ctl_warn('tra_dmp_alloc: allocation of arrays failed')
+      !
+   END FUNCTION tra_dmp_alloc
+
+
+   SUBROUTINE tra_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tra_dmp  ***
+      !!                  
+      !! ** Purpose :   Compute the tracer trend due to a newtonian damping
+      !!      of the tracer field towards given data field and add it to the
+      !!      general tracer trends.
+      !!
+      !! ** Method  :   Newtonian damping towards t_dta and s_dta computed 
+      !!      and add to the general tracer trends:
+      !!                     ta = ta + resto * (t_dta - tb)
+      !!                     sa = sa + resto * (s_dta - sb)
+      !!         The trend is computed either throughout the water column
+      !!      (nlmdmp=0) or in area of weak vertical mixing (nlmdmp=1) or
+      !!      below the well mixed layer (nlmdmp=2)
+      !!
+      !! ** Action  : - tsa: tracer trends updated with the damping trend
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts)     ::  zts_dta
+      REAL(wp), DIMENSION(:,:,:,:), ALLOCATABLE ::  ztrdts
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_dmp')
+      !
+      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         ALLOCATE( ztrdts(jpi,jpj,jpk,jpts) ) 
+         ztrdts(:,:,:,:) = tsa(:,:,:,:) 
+      ENDIF
+      !                           !==  input T-S data at kt  ==!
+      CALL dta_tsd( kt, zts_dta )            ! read and interpolates T-S data at kt
+      !
+      SELECT CASE ( nn_zdmp )     !==  type of damping  ==!
+      !
+      CASE( 0 )                        !*  newtonian damping throughout the water column  *!
+         DO jn = 1, jpts
+            DO jk = 1, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     tsa(ji,jj,jk,jn) = tsa(ji,jj,jk,jn) + resto(ji,jj,jk) * ( zts_dta(ji,jj,jk,jn) - tsb(ji,jj,jk,jn) )
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 1 )                       !*  no damping in the turbocline (avt > 5 cm2/s)  *!
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( avt(ji,jj,jk) <= avt_c ) THEN
+                     tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)   &
+                        &                 + resto(ji,jj,jk) * ( zts_dta(ji,jj,jk,jp_tem) - tsb(ji,jj,jk,jp_tem) )
+                     tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)   &
+                        &                 + resto(ji,jj,jk) * ( zts_dta(ji,jj,jk,jp_sal) - tsb(ji,jj,jk,jp_sal) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 2 )                       !*  no damping in the mixed layer   *!
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF( gdept_n(ji,jj,jk) >= hmlp (ji,jj) ) THEN
+                     tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)   &
+                        &                 + resto(ji,jj,jk) * ( zts_dta(ji,jj,jk,jp_tem) - tsb(ji,jj,jk,jp_tem) )
+                     tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)   &
+                        &                 + resto(ji,jj,jk) * ( zts_dta(ji,jj,jk,jp_sal) - tsb(ji,jj,jk,jp_sal) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      IF( l_trdtra )   THEN       ! trend diagnostic
+         ztrdts(:,:,:,:) = tsa(:,:,:,:) - ztrdts(:,:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_dmp, ztrdts(:,:,:,jp_tem) )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_dmp, ztrdts(:,:,:,jp_sal) )
+         DEALLOCATE( ztrdts ) 
+      ENDIF
+      !                           ! Control print
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' dmp  - Ta: ', mask1=tmask,   &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_dmp')
+      !
+   END SUBROUTINE tra_dmp
+
+
+   SUBROUTINE tra_dmp_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_dmp_init  ***
+      !! 
+      !! ** Purpose :   Initialization for the newtonian damping 
+      !!
+      !! ** Method  :   read the namtra_dmp namelist and check the parameters
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, imask   ! local integers 
+      !
+      NAMELIST/namtra_dmp/ ln_tradmp, nn_zdmp, cn_resto
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )   ! Namelist namtra_dmp in reference namelist : T & S relaxation
+      READ  ( numnam_ref, namtra_dmp, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_dmp in reference namelist' )
+      !
+      REWIND( numnam_cfg )   ! Namelist namtra_dmp in configuration namelist : T & S relaxation
+      READ  ( numnam_cfg, namtra_dmp, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_dmp in configuration namelist' )
+      IF(lwm) WRITE ( numond, namtra_dmp )
+      !
+      IF(lwp) THEN                  ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_dmp_init : T and S newtonian relaxation'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtra_dmp : set relaxation parameters'
+         WRITE(numout,*) '      Apply relaxation   or not       ln_tradmp   = ', ln_tradmp
+         WRITE(numout,*) '         mixed layer damping option      nn_zdmp  = ', nn_zdmp
+         WRITE(numout,*) '         Damping file name               cn_resto = ', cn_resto
+         WRITE(numout,*)
+      ENDIF
+      !
+      IF( ln_tradmp ) THEN
+         !                          ! Allocate arrays
+         IF( tra_dmp_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'tra_dmp_init: unable to allocate arrays' )
+         !
+         SELECT CASE (nn_zdmp)      ! Check values of nn_zdmp
+         CASE ( 0 )   ;   IF(lwp) WRITE(numout,*) '   tracer damping as specified by mask'
+         CASE ( 1 )   ;   IF(lwp) WRITE(numout,*) '   no tracer damping in the mixing layer (kz > 5 cm2/s)'
+         CASE ( 2 )   ;   IF(lwp) WRITE(numout,*) '   no tracer damping in the mixed  layer'
+         CASE DEFAULT
+            CALL ctl_stop('tra_dmp_init : wrong value of nn_zdmp')
+         END SELECT
+         !
+         !!TG: Initialisation of dtatsd - Would it be better to have dmpdta routine
+         !    so can damp to something other than intitial conditions files?
+         !!gm: In principle yes. Nevertheless, we can't anticipate demands that have never been formulated.
+         IF( .NOT.ln_tsd_dmp ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout, *)  '   read T-S data not initialized, we force ln_tsd_dmp=T'
+            CALL dta_tsd_init( ld_tradmp=ln_tradmp )        ! forces the initialisation of T-S data
+         ENDIF
+         !                          ! Read in mask from file
+         CALL iom_open ( cn_resto, imask)
+         CALL iom_get  ( imask, jpdom_autoglo, 'resto', resto )
+         CALL iom_close( imask )
+      ENDIF
+      !
+   END SUBROUTINE tra_dmp_init
+
+   !!======================================================================
+END MODULE tradmp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf.F90	(revision 14097)
@@ -0,0 +1,128 @@
+MODULE traldf
+   !!======================================================================
+   !!                       ***  MODULE  traldf  ***
+   !! Ocean Active tracers : lateral diffusive trends 
+   !!=====================================================================
+   !! History :  9.0  ! 2005-11  (G. Madec)  Original code
+   !!  NEMO      3.0  ! 2008-01  (C. Ethe, G. Madec)  merge TRC-TRA 
+   !!            3.7  ! 2013-12  (G. Madec) remove the optional computation from T & S anomaly profiles and traldf_bilapg
+   !!             -   ! 2013-12  (F. Lemarie, G. Madec)  triad operator (Griffies) + Method of Stabilizing Correction
+   !!             -   ! 2014-01  (G. Madec, S. Masson)  restructuration/simplification of lateral diffusive operators
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_ldf       : update the tracer trend with the lateral diffusion trend
+   !!   tra_ldf_init  : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ldftra         ! lateral diffusion: eddy diffusivity & EIV coeff.
+   USE ldfslp         ! lateral diffusion: iso-neutral slope
+   USE traldf_lap_blp ! lateral diffusion: laplacian iso-level            operator  (tra_ldf_lap/_blp   routines)
+   USE traldf_iso     ! lateral diffusion: laplacian iso-neutral standard operator  (tra_ldf_iso        routine )
+   USE traldf_triad   ! lateral diffusion: laplacian iso-neutral triad    operator  (tra_ldf_triad      routine )
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! ocean active tracers trends
+   !
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_ldf        ! called by step.F90 
+   PUBLIC   tra_ldf_init   ! called by nemogcm.F90 
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_ldf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf  ***
+      !! 
+      !! ** Purpose :   compute the lateral ocean tracer physics.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !!
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_ldf')
+      !
+      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) ) 
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) 
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
+      SELECT CASE ( nldf_tra )                 !* compute lateral mixing trend and add it to the general trend
+      CASE ( np_lap   )                                  ! laplacian: iso-level operator
+         CALL tra_ldf_lap  ( kt, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, tsb,      tsa, jpts,  1   )
+      CASE ( np_lap_i )                                  ! laplacian: standard iso-neutral operator (Madec)
+         CALL tra_ldf_iso  ( kt, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, tsb, tsb, tsa, jpts,  1   )
+      CASE ( np_lap_it )                                 ! laplacian: triad iso-neutral operator (griffies)
+         CALL tra_ldf_triad( kt, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, tsb, tsb, tsa, jpts,  1   )
+      CASE ( np_blp , np_blp_i , np_blp_it )             ! bilaplacian: iso-level & iso-neutral operators
+         CALL tra_ldf_blp  ( kt, nit000,'TRA', ahtu, ahtv, gtsu, gtsv, gtui, gtvi, tsb      , tsa, jpts, nldf_tra )
+      END SELECT
+      !
+      IF( l_trdtra )   THEN                    !* save the horizontal diffusive trends for further diagnostics
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_ldf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_ldf, ztrds )
+         DEALLOCATE( ztrdt, ztrds ) 
+      ENDIF
+      !                                        !* print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' ldf  - Ta: ', mask1=tmask,               &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_ldf')
+      !
+   END SUBROUTINE tra_ldf
+
+
+   SUBROUTINE tra_ldf_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf_init  ***
+      !! 
+      !! ** Purpose :   Choice of the operator for the lateral tracer diffusion
+      !!
+      !! ** Method  :   set nldf_tra from the namtra_ldf logicals
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ierr   ! temporary integers 
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                     !==  Namelist print  ==!
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_ldf_init : lateral tracer diffusive operator'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtra_ldf: already read in ldftra module'
+         WRITE(numout,*) '      see ldf_tra_init report for lateral mixing parameters'
+         WRITE(numout,*)
+         !
+         SELECT CASE( nldf_tra )             ! print the choice of operator
+         CASE( np_no_ldf )   ;   WRITE(numout,*) '   ==>>>   NO lateral diffusion'
+         CASE( np_lap    )   ;   WRITE(numout,*) '   ==>>>   laplacian iso-level operator'
+         CASE( np_lap_i  )   ;   WRITE(numout,*) '   ==>>>   Rotated laplacian operator (standard)'
+         CASE( np_lap_it )   ;   WRITE(numout,*) '   ==>>>   Rotated laplacian operator (triad)'
+         CASE( np_blp    )   ;   WRITE(numout,*) '   ==>>>   bilaplacian iso-level operator'
+         CASE( np_blp_i  )   ;   WRITE(numout,*) '   ==>>>   Rotated bilaplacian operator (standard)'
+         CASE( np_blp_it )   ;   WRITE(numout,*) '   ==>>>   Rotated bilaplacian operator (triad)'
+         END SELECT
+      ENDIF
+      !
+   END SUBROUTINE tra_ldf_init
+
+   !!======================================================================
+END MODULE traldf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_iso.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_iso.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_iso.F90	(revision 14097)
@@ -0,0 +1,385 @@
+MODULE traldf_iso
+   !!======================================================================
+   !!                   ***  MODULE  traldf_iso  ***
+   !! Ocean  tracers:  horizontal component of the lateral tracer mixing trend
+   !!======================================================================
+   !! History :  OPA  ! 1994-08  (G. Madec, M. Imbard)
+   !!            8.0  ! 1997-05  (G. Madec)  split into traldf and trazdf
+   !!            NEMO ! 2002-08  (G. Madec)  Free form, F90
+   !!            1.0  ! 2005-11  (G. Madec)  merge traldf and trazdf :-)
+   !!            3.3  ! 2010-09  (C. Ethe, G. Madec) Merge TRA-TRC
+   !!            3.7  ! 2014-01  (G. Madec, S. Masson)  restructuration/simplification of aht/aeiv specification
+   !!             -   ! 2014-02  (F. Lemarie, G. Madec)  triad operator (Griffies) + Method of Stabilizing Correction
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_ldf_iso   : update the tracer trend with the horizontal component of a iso-neutral laplacian operator
+   !!                   and with the vertical part of the isopycnal or geopotential s-coord. operator 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE zdf_oce        ! ocean vertical physics
+   USE ldftra         ! lateral diffusion: tracer eddy coefficients
+   USE ldfslp         ! iso-neutral slopes
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE phycst         ! physical constants
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_ldf_iso   ! routine called by step.F90
+
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat transport
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+  SUBROUTINE tra_ldf_iso( kt, kit000, cdtype, pahu, pahv, pgu , pgv ,   &
+      &                                                   pgui, pgvi,   &
+      &                                       ptb , ptbb, pta , kjpt, kpass )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf_iso  ***
+      !!
+      !! ** Purpose :   Compute the before horizontal tracer (t & s) diffusive 
+      !!      trend for a laplacian tensor (ezxcept the dz[ dz[.] ] term) and 
+      !!      add it to the general trend of tracer equation.
+      !!
+      !! ** Method  :   The horizontal component of the lateral diffusive trends 
+      !!      is provided by a 2nd order operator rotated along neural or geopo-
+      !!      tential surfaces to which an eddy induced advection can be added
+      !!      It is computed using before fields (forward in time) and isopyc-
+      !!      nal or geopotential slopes computed in routine ldfslp.
+      !!
+      !!      1st part :  masked horizontal derivative of T  ( di[ t ] )
+      !!      ========    with partial cell update if ln_zps=T
+      !!                  with top     cell update if ln_isfcav
+      !!
+      !!      2nd part :  horizontal fluxes of the lateral mixing operator
+      !!      ========    
+      !!         zftu =  pahu e2u*e3u/e1u di[ tb ]
+      !!               - pahu e2u*uslp    dk[ mi(mk(tb)) ]
+      !!         zftv =  pahv e1v*e3v/e2v dj[ tb ]
+      !!               - pahv e2u*vslp    dk[ mj(mk(tb)) ]
+      !!      take the horizontal divergence of the fluxes:
+      !!         difft = 1/(e1e2t*e3t) {  di-1[ zftu ] +  dj-1[ zftv ]  }
+      !!      Add this trend to the general trend (ta,sa):
+      !!         ta = ta + difft
+      !!
+      !!      3rd part: vertical trends of the lateral mixing operator
+      !!      ========  (excluding the vertical flux proportional to dk[t] )
+      !!      vertical fluxes associated with the rotated lateral mixing:
+      !!         zftw = - {  mi(mk(pahu)) * e2t*wslpi di[ mi(mk(tb)) ]
+      !!                   + mj(mk(pahv)) * e1t*wslpj dj[ mj(mk(tb)) ]  }
+      !!      take the horizontal divergence of the fluxes:
+      !!         difft = 1/(e1e2t*e3t) dk[ zftw ]
+      !!      Add this trend to the general trend (ta,sa):
+      !!         pta = pta + difft
+      !!
+      !! ** Action :   Update pta arrays with the before rotated diffusion
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      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        ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptbb       ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta        ! tracer trend
+      !
+      INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::  ikt
+      INTEGER  ::  ierr             ! local integer
+      REAL(wp) ::  zmsku, zahu_w, zabe1, zcof1, zcoef3   ! local scalars
+      REAL(wp) ::  zmskv, zahv_w, zabe2, zcof2, zcoef4   !   -      -
+      REAL(wp) ::  zcoef0, ze3w_2, zsign, z2dt, z1_2dt   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zdkt, zdk1t, z2d
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdit, zdjt, zftu, zftv, ztfw 
+      !!----------------------------------------------------------------------
+      !
+      IF( kpass == 1 .AND. kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_ldf_iso : rotated laplacian diffusion operator on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         !
+         akz     (:,:,:) = 0._wp      
+         ah_wslp2(:,:,:) = 0._wp
+      ENDIF
+      !   
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( cdtype == 'TRA' .AND. ln_diaptr )                                                 l_ptr = .TRUE. 
+      IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )   l_hst = .TRUE.
+      !
+      !                                            ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;   z2dt =     rdt      ! at nit000   (Euler)
+      ELSE                                        ;   z2dt = 2.* rdt      !             (Leapfrog)
+      ENDIF
+      z1_2dt = 1._wp / z2dt
+      !
+      IF( kpass == 1 ) THEN   ;   zsign =  1._wp      ! bilaplacian operator require a minus sign (eddy diffusivity >0)
+      ELSE                    ;   zsign = -1._wp
+      ENDIF
+         
+      !!----------------------------------------------------------------------
+      !!   0 - calculate  ah_wslp2 and akz
+      !!----------------------------------------------------------------------
+      !
+      IF( kpass == 1 ) THEN                  !==  first pass only  ==!
+         !
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  !
+                  zmsku = wmask(ji,jj,jk) / MAX(   umask(ji  ,jj,jk-1) + umask(ji-1,jj,jk)          &
+                     &                           + umask(ji-1,jj,jk-1) + umask(ji  ,jj,jk) , 1._wp  )
+                  zmskv = wmask(ji,jj,jk) / MAX(   vmask(ji,jj  ,jk-1) + vmask(ji,jj-1,jk)          &
+                     &                           + vmask(ji,jj-1,jk-1) + vmask(ji,jj  ,jk) , 1._wp  )
+                     !
+                  zahu_w = (   pahu(ji  ,jj,jk-1) + pahu(ji-1,jj,jk)    &
+                     &       + pahu(ji-1,jj,jk-1) + pahu(ji  ,jj,jk)  ) * zmsku
+                  zahv_w = (   pahv(ji,jj  ,jk-1) + pahv(ji,jj-1,jk)    &
+                     &       + pahv(ji,jj-1,jk-1) + pahv(ji,jj  ,jk)  ) * zmskv
+                     !
+                  ah_wslp2(ji,jj,jk) = zahu_w * wslpi(ji,jj,jk) * wslpi(ji,jj,jk)   &
+                     &               + zahv_w * wslpj(ji,jj,jk) * wslpj(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF( ln_traldf_msc ) THEN                ! stabilizing vertical diffusivity coefficient
+            DO jk = 2, jpkm1
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     akz(ji,jj,jk) = 0.25_wp * (                                                                     &
+                        &              ( pahu(ji  ,jj,jk) + pahu(ji  ,jj,jk-1) ) / ( e1u(ji  ,jj) * e1u(ji  ,jj) )   &
+                        &            + ( pahu(ji-1,jj,jk) + pahu(ji-1,jj,jk-1) ) / ( e1u(ji-1,jj) * e1u(ji-1,jj) )   &
+                        &            + ( pahv(ji,jj  ,jk) + pahv(ji,jj  ,jk-1) ) / ( e2v(ji,jj  ) * e2v(ji,jj  ) )   &
+                        &            + ( pahv(ji,jj-1,jk) + pahv(ji,jj-1,jk-1) ) / ( e2v(ji,jj-1) * e2v(ji,jj-1) )   )
+                  END DO
+               END DO
+            END DO
+            !
+            IF( ln_traldf_blp ) THEN                ! bilaplacian operator
+               DO jk = 2, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        akz(ji,jj,jk) = 16._wp * ah_wslp2(ji,jj,jk)   &
+                           &          * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ( e3w_n(ji,jj,jk) * e3w_n(ji,jj,jk) )  )
+                     END DO
+                  END DO
+               END DO
+            ELSEIF( ln_traldf_lap ) THEN              ! laplacian operator
+               DO jk = 2, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        ze3w_2 = e3w_n(ji,jj,jk) * e3w_n(ji,jj,jk)
+                        zcoef0 = z2dt * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ze3w_2  )
+                        akz(ji,jj,jk) = MAX( zcoef0 - 0.5_wp , 0._wp ) * ze3w_2 * z1_2dt
+                     END DO
+                  END DO
+               END DO
+           ENDIF
+           !
+         ELSE                                    ! 33 flux set to zero with akz=ah_wslp2 ==>> computed in full implicit
+            akz(:,:,:) = ah_wslp2(:,:,:)      
+         ENDIF
+      ENDIF
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         !                                               
+         !!----------------------------------------------------------------------
+         !!   I - masked horizontal derivative 
+         !!----------------------------------------------------------------------
+!!gm : bug.... why (x,:,:)?   (1,jpj,:) and (jpi,1,:) should be sufficient....
+         zdit (1,:,:) = 0._wp     ;     zdit (jpi,:,:) = 0._wp
+         zdjt (1,:,:) = 0._wp     ;     zdjt (jpi,:,:) = 0._wp
+         !!end
+
+         ! Horizontal tracer gradient 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zdit(ji,jj,jk) = ( ptb(ji+1,jj  ,jk,jn) - ptb(ji,jj,jk,jn) ) * umask(ji,jj,jk)
+                  zdjt(ji,jj,jk) = ( ptb(ji  ,jj+1,jk,jn) - ptb(ji,jj,jk,jn) ) * vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         IF( ln_zps ) THEN      ! botton and surface ocean correction of the horizontal gradient
+            DO jj = 1, jpjm1              ! bottom correction (partial bottom cell)
+               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)
+               END DO
+            END DO
+            IF( ln_isfcav ) THEN      ! first wet level beneath a cavity
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     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
+            ENDIF
+         ENDIF
+         !
+         !!----------------------------------------------------------------------
+         !!   II - horizontal trend  (full)
+         !!----------------------------------------------------------------------
+         !
+         DO jk = 1, jpkm1                                 ! Horizontal slab
+            !
+            !                             !== Vertical tracer gradient
+            zdk1t(:,:) = ( ptb(:,:,jk,jn) - ptb(:,:,jk+1,jn) ) * wmask(:,:,jk+1)     ! level jk+1
+            !
+            IF( jk == 1 ) THEN   ;   zdkt(:,:) = zdk1t(:,:)                          ! surface: zdkt(jk=1)=zdkt(jk=2)
+            ELSE                 ;   zdkt(:,:) = ( ptb(:,:,jk-1,jn) - ptb(:,:,jk,jn) ) * wmask(:,:,jk)
+            ENDIF
+            DO jj = 1 , jpjm1            !==  Horizontal fluxes
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zabe1 = pahu(ji,jj,jk) * e2_e1u(ji,jj) * e3u_n(ji,jj,jk)
+                  zabe2 = pahv(ji,jj,jk) * e1_e2v(ji,jj) * e3v_n(ji,jj,jk)
+                  !
+                  zmsku = 1. / MAX(  wmask(ji+1,jj,jk  ) + wmask(ji,jj,jk+1)   &
+                     &             + wmask(ji+1,jj,jk+1) + wmask(ji,jj,jk  ), 1. )
+                  !
+                  zmskv = 1. / MAX(  wmask(ji,jj+1,jk  ) + wmask(ji,jj,jk+1)   &
+                     &             + wmask(ji,jj+1,jk+1) + wmask(ji,jj,jk  ), 1. )
+                  !
+                  zcof1 = - pahu(ji,jj,jk) * e2u(ji,jj) * uslp(ji,jj,jk) * zmsku
+                  zcof2 = - pahv(ji,jj,jk) * e1v(ji,jj) * vslp(ji,jj,jk) * zmskv
+                  !
+                  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)
+                  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
+            !
+            DO jj = 2 , jpjm1          !== horizontal divergence and add to pta
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + zsign * (  zftu(ji,jj,jk) - zftu(ji-1,jj,jk)      &
+                     &                                           + zftv(ji,jj,jk) - zftv(ji,jj-1,jk)  )   &
+                     &                                        * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO                                        !   End of slab  
+
+         !!----------------------------------------------------------------------
+         !!   III - vertical trend (full)
+         !!----------------------------------------------------------------------
+         !
+         ztfw(fs_2:1,:,:) = 0._wp     ;     ztfw(jpi:fs_jpim1,:,:) = 0._wp   ! avoid to potentially manipulate NaN values
+         !
+         ! Vertical fluxes
+         ! ---------------
+         !                          ! Surface and bottom vertical fluxes set to zero
+         ztfw(:,:, 1 ) = 0._wp      ;      ztfw(:,:,jpk) = 0._wp
+         
+         DO jk = 2, jpkm1           ! interior (2=<jk=<jpk-1)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  !
+                  zmsku = wmask(ji,jj,jk) / MAX(   umask(ji  ,jj,jk-1) + umask(ji-1,jj,jk)          &
+                     &                           + umask(ji-1,jj,jk-1) + umask(ji  ,jj,jk) , 1._wp  )
+                  zmskv = wmask(ji,jj,jk) / MAX(   vmask(ji,jj  ,jk-1) + vmask(ji,jj-1,jk)          &
+                     &                           + vmask(ji,jj-1,jk-1) + vmask(ji,jj  ,jk) , 1._wp  )
+                     !
+                  zahu_w = (   pahu(ji  ,jj,jk-1) + pahu(ji-1,jj,jk)    &
+                     &       + pahu(ji-1,jj,jk-1) + pahu(ji  ,jj,jk)  ) * zmsku
+                  zahv_w = (   pahv(ji,jj  ,jk-1) + pahv(ji,jj-1,jk)    &
+                     &       + pahv(ji,jj-1,jk-1) + pahv(ji,jj  ,jk)  ) * zmskv
+                     !
+                  zcoef3 = - zahu_w * e2t(ji,jj) * zmsku * wslpi (ji,jj,jk)   !wslpi & j are already w-masked
+                  zcoef4 = - zahv_w * e1t(ji,jj) * zmskv * wslpj (ji,jj,jk)
+                  !
+                  ztfw(ji,jj,jk) = zcoef3 * (   zdit(ji  ,jj  ,jk-1) + zdit(ji-1,jj  ,jk)      &
+                     &                        + zdit(ji-1,jj  ,jk-1) + zdit(ji  ,jj  ,jk)  )   &
+                     &           + zcoef4 * (   zdjt(ji  ,jj  ,jk-1) + zdjt(ji  ,jj-1,jk)      &
+                     &                        + zdjt(ji  ,jj-1,jk-1) + zdjt(ji  ,jj  ,jk)  )
+               END DO
+            END DO
+         END DO
+         !                                !==  add the vertical 33 flux  ==!
+         IF( ln_traldf_lap ) THEN               ! laplacian case: eddy coef = ah_wslp2 - akz
+            DO jk = 2, jpkm1       
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     ztfw(ji,jj,jk) = ztfw(ji,jj,jk) + e1e2t(ji,jj) / e3w_n(ji,jj,jk) * wmask(ji,jj,jk)   &
+                        &                            * ( ah_wslp2(ji,jj,jk) - akz(ji,jj,jk) )             &
+                        &                            * ( ptb(ji,jj,jk-1,jn) - ptb(ji,jj,jk,jn) )
+                  END DO
+               END DO
+            END DO
+            !
+         ELSE                                   ! bilaplacian 
+            SELECT CASE( kpass )
+            CASE(  1  )                            ! 1st pass : eddy coef = ah_wslp2
+               DO jk = 2, jpkm1 
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1
+                        ztfw(ji,jj,jk) = ztfw(ji,jj,jk)    &
+                           &           + ah_wslp2(ji,jj,jk) * e1e2t(ji,jj)   &
+                           &           * ( ptb(ji,jj,jk-1,jn) - ptb(ji,jj,jk,jn) ) / e3w_n(ji,jj,jk) * wmask(ji,jj,jk)
+                     END DO
+                  END DO
+               END DO 
+            CASE(  2  )                         ! 2nd pass : eddy flux = ah_wslp2 and akz applied on ptb  and ptbb gradients, resp.
+               DO jk = 2, jpkm1 
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1
+                        ztfw(ji,jj,jk) = ztfw(ji,jj,jk) + e1e2t(ji,jj) / e3w_n(ji,jj,jk) * wmask(ji,jj,jk)                      &
+                           &                            * (  ah_wslp2(ji,jj,jk) * ( ptb (ji,jj,jk-1,jn) - ptb (ji,jj,jk,jn) )   &
+                           &                               + akz     (ji,jj,jk) * ( ptbb(ji,jj,jk-1,jn) - ptbb(ji,jj,jk,jn) )   )
+                     END DO
+                  END DO
+               END DO
+            END SELECT
+         ENDIF
+         !         
+         DO jk = 1, jpkm1                 !==  Divergence of vertical fluxes added to pta  ==!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + zsign * (  ztfw (ji,jj,jk) - ztfw(ji,jj,jk+1)  )   &
+                     &                                        * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         IF( ( kpass == 1 .AND. ln_traldf_lap ) .OR.  &     !==  first pass only (  laplacian)  ==!
+             ( kpass == 2 .AND. ln_traldf_blp ) ) THEN      !==  2nd   pass      (bilaplacian)  ==!
+            !
+            !                             ! "Poleward" diffusive heat or salt transports (T-S case only)
+               ! note sign is reversed to give down-gradient diffusive transports )
+            IF( l_ptr )  CALL dia_ptr_hst( jn, 'ldf', -zftv(:,:,:)  )
+            !                          ! Diffusive heat transports
+            IF( l_hst )  CALL dia_ar5_hst( jn, 'ldf', -zftu(:,:,:), -zftv(:,:,:) )
+            !
+         ENDIF                                                    !== end pass selection  ==!
+         !
+         !                                                        ! ===============
+      END DO                                                      ! end tracer loop
+      !
+   END SUBROUTINE tra_ldf_iso
+
+   !!==============================================================================
+END MODULE traldf_iso
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_lap_blp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_lap_blp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_lap_blp.F90	(revision 14097)
@@ -0,0 +1,234 @@
+MODULE traldf_lap_blp
+   !!==============================================================================
+   !!                       ***  MODULE  traldf_lap_blp  ***
+   !! Ocean tracers:  lateral diffusivity trend  (laplacian and bilaplacian)
+   !!==============================================================================
+   !! History :  3.7  ! 2014-01  (G. Madec, S. Masson)  Original code, re-entrant laplacian 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_ldf_lap   : tracer trend update with iso-level laplacian diffusive operator
+   !!   tra_ldf_blp   : tracer trend update with iso-level or iso-neutral bilaplacian operator
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE ldftra         ! lateral physics: eddy diffusivity
+   USE traldf_iso     ! iso-neutral lateral diffusion (standard operator)     (tra_ldf_iso   routine)
+   USE traldf_triad   ! iso-neutral lateral diffusion (triad    operator)     (tra_ldf_triad routine)
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE zpshde         ! partial step: hor. derivative     (zps_hde routine)
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distribued memory computing library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_ldf_lap   ! called by traldf.F90
+   PUBLIC   tra_ldf_blp   ! called by traldf.F90
+
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat transport
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_ldf_lap( kt, kit000, cdtype, pahu, pahv, pgu , pgv ,   &
+      &                                                    pgui, pgvi,   &
+      &                                        ptb , pta , kjpt, kpass ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf_lap  ***
+      !!                   
+      !! ** Purpose :   Compute the before horizontal tracer (t & s) diffusive 
+      !!      trend and add it to the general trend of tracer equation.
+      !!
+      !! ** Method  :   Second order diffusive operator evaluated using before
+      !!      fields (forward time scheme). The horizontal diffusive trends of 
+      !!      the tracer is given by:
+      !!          difft = 1/(e1e2t*e3t) {  di-1[ pahu e2u*e3u/e1u di(tb) ]
+      !!                                 + dj-1[ pahv e1v*e3v/e2v dj(tb) ] }
+      !!      Add this trend to the general tracer trend pta :
+      !!          pta = pta + difft
+      !!
+      !! ** Action  : - Update pta arrays with the before iso-level 
+      !!                harmonic mixing trend.
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      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 
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   zsign            ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztu, ztv, zaheeu, zaheev
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwp )  THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_ldf_lap : iso-level laplacian diffusion on ', cdtype, ', pass=', kpass
+         WRITE(numout,*) '~~~~~~~~~~~ '
+      ENDIF
+      !
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( cdtype == 'TRA' .AND. ln_diaptr )                                                l_ptr = .TRUE. 
+      IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )  l_hst = .TRUE.
+      !
+      !                                !==  Initialization of metric arrays used for all tracers  ==!
+      IF( kpass == 1 ) THEN   ;   zsign =  1._wp      ! bilaplacian operator require a minus sign (eddy diffusivity >0)
+      ELSE                    ;   zsign = -1._wp
+      ENDIF
+      DO jk = 1, jpkm1
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zaheeu(ji,jj,jk) = zsign * pahu(ji,jj,jk) * e2_e1u(ji,jj) * e3u_n(ji,jj,jk)   !!gm   * umask(ji,jj,jk) pah masked!
+               zaheev(ji,jj,jk) = zsign * pahv(ji,jj,jk) * e1_e2v(ji,jj) * e3v_n(ji,jj,jk)   !!gm   * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      !                             ! =========== !
+      DO jn = 1, kjpt               ! tracer loop !
+         !                          ! =========== !    
+         !                               
+         DO jk = 1, jpkm1              !== First derivative (gradient)  ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1
+                  ztu(ji,jj,jk) = zaheeu(ji,jj,jk) * ( ptb(ji+1,jj  ,jk,jn) - ptb(ji,jj,jk,jn) )
+                  ztv(ji,jj,jk) = zaheev(ji,jj,jk) * ( ptb(ji  ,jj+1,jk,jn) - ptb(ji,jj,jk,jn) )
+               END DO
+            END DO
+         END DO  
+         IF( ln_zps ) THEN                ! set gradient at bottom/top ocean level
+            DO jj = 1, jpjm1                    ! bottom
+               DO ji = 1, fs_jpim1
+                  ztu(ji,jj,mbku(ji,jj)) = zaheeu(ji,jj,mbku(ji,jj)) * pgu(ji,jj,jn)
+                  ztv(ji,jj,mbkv(ji,jj)) = zaheev(ji,jj,mbkv(ji,jj)) * pgv(ji,jj,jn)
+               END DO
+            END DO  
+            IF( ln_isfcav ) THEN                ! top in ocean cavities only
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     IF( miku(ji,jj) > 1 )   ztu(ji,jj,miku(ji,jj)) = zaheeu(ji,jj,miku(ji,jj)) * pgui(ji,jj,jn) 
+                     IF( mikv(ji,jj) > 1 )   ztv(ji,jj,mikv(ji,jj)) = zaheev(ji,jj,mikv(ji,jj)) * pgvi(ji,jj,jn) 
+                  END DO
+               END DO
+            ENDIF
+         ENDIF
+         !
+         DO jk = 1, jpkm1              !== Second derivative (divergence) added to the general tracer trends  ==!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  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) * e3t_n(ji,jj,jk) )
+               END DO
+            END DO
+         END DO  
+         !
+         !                             !== "Poleward" diffusive heat or salt transports  ==!
+         IF( ( kpass == 1 .AND. .NOT.ln_traldf_blp ) .OR.  &     !==  first pass only (  laplacian)  ==!
+             ( kpass == 2 .AND.      ln_traldf_blp ) ) THEN      !==  2nd   pass only (bilaplacian)  ==!
+
+            IF( l_ptr )  CALL dia_ptr_hst( jn, 'ldf', -ztv(:,:,:)  )
+            IF( l_hst )  CALL dia_ar5_hst( jn, 'ldf', -ztu(:,:,:), -ztv(:,:,:) )
+         ENDIF
+         !                          ! ==================
+      END DO                        ! end of tracer loop
+      !                             ! ==================
+      !
+   END SUBROUTINE tra_ldf_lap
+   
+
+   SUBROUTINE tra_ldf_blp( kt, kit000, cdtype, pahu, pahv, pgu , pgv ,   &
+      &                                                    pgui, pgvi,   &
+      &                                                    ptb , pta , kjpt, kldf )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE tra_ldf_blp  ***
+      !!                    
+      !! ** Purpose :   Compute the before lateral tracer diffusive 
+      !!      trend and add it to the general trend of tracer equation.
+      !!
+      !! ** Method  :   The lateral diffusive trends is provided by a bilaplacian
+      !!      operator applied to before field (forward in time).
+      !!      It is computed by two successive calls to laplacian routine
+      !!
+      !! ** Action :   pta   updated with the before rotated bilaplacian diffusion
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kldf       ! type of operator used
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      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
+      !
+      INTEGER ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt) :: zlap         ! laplacian at t-point
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt) :: zglu, zglv   ! bottom GRADh of the laplacian (u- and v-points)
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt) :: zgui, zgvi   ! top    GRADh of the laplacian (u- and v-points)
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == kit000 .AND. lwp )  THEN
+         WRITE(numout,*)
+         SELECT CASE ( kldf )
+         CASE ( np_blp    )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-level   bilaplacian operator on ', cdtype
+         CASE ( np_blp_i  )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (Standard)'
+         CASE ( np_blp_it )   ;   WRITE(numout,*) 'tra_ldf_blp : iso-neutral bilaplacian operator on ', cdtype, ' (triad)'
+         END SELECT
+         WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+
+      zlap(:,:,:,:) = 0._wp
+      !
+      SELECT CASE ( kldf )       !==  1st laplacian applied to ptb (output in zlap)  ==!
+      !
+      CASE ( np_blp    )               ! iso-level bilaplacian
+         CALL tra_ldf_lap  ( kt, kit000, cdtype, pahu, pahv, pgu, pgv, pgui, pgvi, ptb,      zlap, kjpt, 1 )
+      CASE ( np_blp_i  )               ! rotated   bilaplacian : standard operator (Madec)
+         CALL tra_ldf_iso  ( kt, kit000, cdtype, pahu, pahv, pgu, pgv, pgui, pgvi, ptb, ptb, zlap, kjpt, 1 )
+      CASE ( np_blp_it )               ! rotated  bilaplacian : triad operator (griffies)
+         CALL tra_ldf_triad( kt, kit000, cdtype, pahu, pahv, pgu, pgv, pgui, pgvi, ptb, ptb, zlap, kjpt, 1 )
+      END SELECT
+      !
+      CALL lbc_lnk( 'traldf_lap_blp', zlap(:,:,:,:) , 'T', 1. )     ! Lateral boundary conditions (unchanged sign)
+      !                                               ! Partial top/bottom cell: GRADh( zlap )  
+      IF( ln_isfcav .AND. ln_zps ) THEN   ;   CALL zps_hde_isf( kt, kjpt, zlap, zglu, zglv, zgui, zgvi )  ! both top & bottom
+      ELSEIF(             ln_zps ) THEN   ;   CALL zps_hde    ( kt, kjpt, zlap, zglu, zglv )              ! only bottom 
+      ENDIF
+      !
+      SELECT CASE ( kldf )       !==  2nd laplacian applied to zlap (output in pta)  ==!
+      !
+      CASE ( np_blp    )               ! iso-level bilaplacian
+         CALL tra_ldf_lap  ( kt, kit000, cdtype, pahu, pahv, zglu, zglv, zgui, zgvi, zlap, pta,      kjpt, 2 )
+      CASE ( np_blp_i  )               ! rotated   bilaplacian : standard operator (Madec)
+         CALL tra_ldf_iso  ( kt, kit000, cdtype, pahu, pahv, zglu, zglv, zgui, zgvi, zlap, ptb, pta, kjpt, 2 )
+      CASE ( np_blp_it )               ! rotated  bilaplacian : triad operator (griffies)
+         CALL tra_ldf_triad( kt, kit000, cdtype, pahu, pahv, zglu, zglv, zgui, zgvi, zlap, ptb, pta, kjpt, 2 )
+      END SELECT
+      !
+   END SUBROUTINE tra_ldf_blp
+
+   !!==============================================================================
+END MODULE traldf_lap_blp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_triad.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_triad.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traldf_triad.F90	(revision 14097)
@@ -0,0 +1,432 @@
+MODULE traldf_triad
+   !!======================================================================
+   !!                   ***  MODULE  traldf_triad  ***
+   !! Ocean  tracers:  horizontal component of the lateral tracer mixing trend
+   !!======================================================================
+   !! History :  3.3  ! 2010-10  (G. Nurser, C. Harris, G. Madec)  Griffies operator (original code)
+   !!            3.7  ! 2013-12  (F. Lemarie, G. Madec)  triad operator (Griffies) + Method of Stabilizing Correction
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_ldf_triad : update the tracer trend with the iso-neutral laplacian triad-operator
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE zdf_oce        ! ocean vertical physics
+   USE ldftra         ! lateral physics: eddy diffusivity
+   USE ldfslp         ! lateral physics: iso-neutral slopes
+   USE traldf_iso     ! lateral diffusion (Madec operator)         (tra_ldf_iso routine)
+   USE diaptr         ! poleward transport diagnostics
+   USE diaar5         ! AR5 diagnostics
+   USE zpshde         ! partial step: hor. derivative     (zps_hde routine)
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_ldf_triad   ! routine called by traldf.F90
+
+   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE, SAVE ::   zdkt3d   !: vertical tracer gradient at 2 levels
+
+   LOGICAL  ::   l_ptr   ! flag to compute poleward transport
+   LOGICAL  ::   l_hst   ! flag to compute heat transport
+
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+  SUBROUTINE tra_ldf_triad( kt, kit000, cdtype, pahu, pahv, pgu , pgv ,   &
+      &                                                     pgui, pgvi,   &
+      &                                         ptb , ptbb, pta , kjpt, kpass )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf_triad  ***
+      !!
+      !! ** Purpose :   Compute the before horizontal tracer (t & s) diffusive
+      !!      trend for a laplacian tensor (ezxcept the dz[ dz[.] ] term) and
+      !!      add it to the general trend of tracer equation.
+      !!
+      !! ** Method  :   The horizontal component of the lateral diffusive trends
+      !!      is provided by a 2nd order operator rotated along neural or geopo-
+      !!      tential surfaces to which an eddy induced advection can be added
+      !!      It is computed using before fields (forward in time) and isopyc-
+      !!      nal or geopotential slopes computed in routine ldfslp.
+      !!
+      !!      see documentation for the desciption
+      !!
+      !! ** Action :   pta   updated with the before rotated diffusion
+      !!               ah_wslp2 ....
+      !!               akz   stabilizing vertical diffusivity coefficient (used in trazdf_imp)
+      !!----------------------------------------------------------------------
+      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
+      INTEGER                              , INTENT(in   ) ::   kpass      ! =1/2 first or second passage
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pahu, pahv ! eddy diffusivity at u- and v-points  [m2/s]
+      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        ! tracer (kpass=1) or laplacian of tracer (kpass=2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptbb       ! tracer (only used in kpass=2)
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta        ! tracer trend
+      !
+      INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
+      INTEGER  ::  ip,jp,kp         ! dummy loop indices
+      INTEGER  ::  ierr            ! local integer
+      REAL(wp) ::  zmsku, zabe1, zcof1, zcoef3          ! local scalars
+      REAL(wp) ::  zmskv, zabe2, zcof2, zcoef4          !   -      -
+      REAL(wp) ::  zcoef0, ze3w_2, zsign, z2dt, z1_2dt  !   -      -
+      !
+      REAL(wp) ::   zslope_skew, zslope_iso, zslope2, zbu, zbv
+      REAL(wp) ::   ze1ur, ze2vr, ze3wr, zdxt, zdyt, zdzt
+      REAL(wp) ::   zah, zah_slp, zaei_slp
+      REAL(wp), DIMENSION(jpi,jpj    ) ::   z2d                                              ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zdit, zdjt, zftu, zftv, ztfw, zpsi_uw, zpsi_vw   ! 3D     -
+      !!----------------------------------------------------------------------
+      !
+      IF( .NOT.ALLOCATED(zdkt3d) )  THEN
+         ALLOCATE( zdkt3d(jpi,jpj,0:1) , STAT=ierr )
+         CALL mpp_sum ( 'traldf_triad', ierr )
+         IF( ierr > 0 )   CALL ctl_stop('STOP', 'tra_ldf_triad: unable to allocate arrays')
+      ENDIF
+     !
+      IF( kpass == 1 .AND. kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_ldf_triad : rotated laplacian diffusion operator on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !   
+      l_hst = .FALSE.
+      l_ptr = .FALSE.
+      IF( cdtype == 'TRA' .AND. ln_diaptr )                                                 l_ptr = .TRUE. 
+      IF( cdtype == 'TRA' .AND. ( iom_use("uadv_heattr") .OR. iom_use("vadv_heattr") .OR. &
+         &                        iom_use("uadv_salttr") .OR. iom_use("vadv_salttr")  ) )   l_hst = .TRUE.
+      !
+      !                                                        ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == kit000 ) THEN   ;   z2dt =     rdt      ! at nit000   (Euler)
+      ELSE                                        ;   z2dt = 2.* rdt      !             (Leapfrog)
+      ENDIF
+      z1_2dt = 1._wp / z2dt
+      !
+      IF( kpass == 1 ) THEN   ;   zsign =  1._wp      ! bilaplacian operator require a minus sign (eddy diffusivity >0)
+      ELSE                    ;   zsign = -1._wp
+      ENDIF
+      !    
+      !!----------------------------------------------------------------------
+      !!   0 - calculate  ah_wslp2, akz, and optionally zpsi_uw, zpsi_vw
+      !!----------------------------------------------------------------------
+      !
+      IF( kpass == 1 ) THEN         !==  first pass only  and whatever the tracer is  ==!
+         !
+         akz     (:,:,:) = 0._wp      
+         ah_wslp2(:,:,:) = 0._wp
+         IF( ln_ldfeiv_dia ) THEN
+            zpsi_uw(:,:,:) = 0._wp
+            zpsi_vw(:,:,:) = 0._wp
+         ENDIF
+         !
+         DO ip = 0, 1                            ! i-k triads
+            DO kp = 0, 1
+               DO jk = 1, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        ze3wr = 1._wp / e3w_n(ji+ip,jj,jk+kp)
+                        zbu   = e1e2u(ji,jj) * e3u_n(ji,jj,jk)
+                        zah   = 0.25_wp * pahu(ji,jj,jk)
+                        zslope_skew = triadi_g(ji+ip,jj,jk,1-ip,kp)
+                        ! Subtract s-coordinate slope at t-points to give slope rel to s-surfaces (do this by *adding* gradient of depth)
+                        zslope2 = zslope_skew + ( gdept_n(ji+1,jj,jk) - gdept_n(ji,jj,jk) ) * r1_e1u(ji,jj) * umask(ji,jj,jk+kp)
+                        zslope2 = zslope2 *zslope2
+                        ah_wslp2(ji+ip,jj,jk+kp) = ah_wslp2(ji+ip,jj,jk+kp) + zah * zbu * ze3wr * r1_e1e2t(ji+ip,jj) * zslope2
+                        akz     (ji+ip,jj,jk+kp) = akz     (ji+ip,jj,jk+kp) + zah * r1_e1u(ji,jj)       &
+                           &                                                      * r1_e1u(ji,jj) * umask(ji,jj,jk+kp)
+                           !
+                       IF( ln_ldfeiv_dia )   zpsi_uw(ji,jj,jk+kp) = zpsi_uw(ji,jj,jk+kp)   &
+                           &                                       + 0.25_wp * aeiu(ji,jj,jk) * e2u(ji,jj) * zslope_skew
+                     END DO
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         DO jp = 0, 1                            ! j-k triads 
+            DO kp = 0, 1
+               DO jk = 1, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        ze3wr = 1.0_wp / e3w_n(ji,jj+jp,jk+kp)
+                        zbv   = e1e2v(ji,jj) * e3v_n(ji,jj,jk)
+                        zah   = 0.25_wp * pahv(ji,jj,jk)
+                        zslope_skew = triadj_g(ji,jj+jp,jk,1-jp,kp)
+                        ! Subtract s-coordinate slope at t-points to give slope rel to s surfaces
+                        !    (do this by *adding* gradient of depth)
+                        zslope2 = zslope_skew + ( gdept_n(ji,jj+1,jk) - gdept_n(ji,jj,jk) ) * r1_e2v(ji,jj) * vmask(ji,jj,jk+kp)
+                        zslope2 = zslope2 * zslope2
+                        ah_wslp2(ji,jj+jp,jk+kp) = ah_wslp2(ji,jj+jp,jk+kp) + zah * zbv * ze3wr * r1_e1e2t(ji,jj+jp) * zslope2
+                        akz     (ji,jj+jp,jk+kp) = akz     (ji,jj+jp,jk+kp) + zah * r1_e2v(ji,jj)     &
+                           &                                                      * r1_e2v(ji,jj) * vmask(ji,jj,jk+kp)
+                        !
+                        IF( ln_ldfeiv_dia )   zpsi_vw(ji,jj,jk+kp) = zpsi_vw(ji,jj,jk+kp)   &
+                           &                                       + 0.25 * aeiv(ji,jj,jk) * e1v(ji,jj) * zslope_skew
+                     END DO
+                  END DO
+               END DO
+            END DO
+         END DO
+         !
+         IF( ln_traldf_msc ) THEN                ! stabilizing vertical diffusivity coefficient
+            !
+            IF( ln_traldf_blp ) THEN                ! bilaplacian operator
+               DO jk = 2, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        akz(ji,jj,jk) = 16._wp * ah_wslp2(ji,jj,jk)   &
+                           &          * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ( e3w_n(ji,jj,jk) * e3w_n(ji,jj,jk) )  )
+                     END DO
+                  END DO
+               END DO
+            ELSEIF( ln_traldf_lap ) THEN              ! laplacian operator
+               DO jk = 2, jpkm1
+                  DO jj = 1, jpjm1
+                     DO ji = 1, fs_jpim1
+                        ze3w_2 = e3w_n(ji,jj,jk) * e3w_n(ji,jj,jk)
+                        zcoef0 = z2dt * (  akz(ji,jj,jk) + ah_wslp2(ji,jj,jk) / ze3w_2  )
+                        akz(ji,jj,jk) = MAX( zcoef0 - 0.5_wp , 0._wp ) * ze3w_2 * z1_2dt
+                     END DO
+                  END DO
+               END DO
+           ENDIF
+           !
+         ELSE                                    ! 33 flux set to zero with akz=ah_wslp2 ==>> computed in full implicit
+            akz(:,:,:) = ah_wslp2(:,:,:)      
+         ENDIF
+         !
+         IF( ln_ldfeiv_dia .AND. cdtype == 'TRA' )   CALL ldf_eiv_dia( zpsi_uw, zpsi_vw )
+         !
+      ENDIF                                  !==  end 1st pass only  ==!
+      !
+      !                                                           ! ===========
+      DO jn = 1, kjpt                                             ! tracer loop
+         !                                                        ! ===========
+         ! Zero fluxes for each tracer
+!!gm  this should probably be done outside the jn loop
+         ztfw(:,:,:) = 0._wp
+         zftu(:,:,:) = 0._wp
+         zftv(:,:,:) = 0._wp
+         !
+         DO jk = 1, jpkm1        !==  before lateral T & S gradients at T-level jk  ==!
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zdit(ji,jj,jk) = ( ptb(ji+1,jj  ,jk,jn) - ptb(ji,jj,jk,jn) ) * umask(ji,jj,jk)
+                  zdjt(ji,jj,jk) = ( ptb(ji  ,jj+1,jk,jn) - ptb(ji,jj,jk,jn) ) * vmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         IF( ln_zps .AND. l_grad_zps ) THEN    ! partial steps: correction at top/bottom ocean level
+            DO jj = 1, jpjm1                       ! bottom level
+               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)
+               END DO
+            END DO
+            IF( ln_isfcav ) THEN                   ! top level (ocean cavities only)
+               DO jj = 1, jpjm1
+                  DO ji = 1, fs_jpim1   ! vector opt.
+                     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
+            ENDIF
+         ENDIF
+         !
+         !!----------------------------------------------------------------------
+         !!   II - horizontal trend  (full)
+         !!----------------------------------------------------------------------
+         !
+         DO jk = 1, jpkm1
+            !                    !==  Vertical tracer gradient at level jk and jk+1
+            zdkt3d(:,:,1) = ( ptb(:,:,jk,jn) - ptb(:,:,jk+1,jn) ) * tmask(:,:,jk+1)
+            !
+            !                    ! surface boundary condition: zdkt3d(jk=0)=zdkt3d(jk=1)
+            IF( jk == 1 ) THEN   ;   zdkt3d(:,:,0) = zdkt3d(:,:,1)
+            ELSE                 ;   zdkt3d(:,:,0) = ( ptb(:,:,jk-1,jn) - ptb(:,:,jk,jn) ) * tmask(:,:,jk)
+            ENDIF
+            !
+            zaei_slp = 0._wp
+            !
+            IF( ln_botmix_triad ) THEN
+               DO ip = 0, 1              !==  Horizontal & vertical fluxes
+                  DO kp = 0, 1
+                     DO jj = 1, jpjm1
+                        DO ji = 1, fs_jpim1
+                           ze1ur = r1_e1u(ji,jj)
+                           zdxt  = zdit(ji,jj,jk) * ze1ur
+                           ze3wr = 1._wp / e3w_n(ji+ip,jj,jk+kp)
+                           zdzt  = zdkt3d(ji+ip,jj,kp) * ze3wr
+                           zslope_skew = triadi_g(ji+ip,jj,jk,1-ip,kp)
+                           zslope_iso  = triadi  (ji+ip,jj,jk,1-ip,kp)
+                           !
+                           zbu = 0.25_wp * e1e2u(ji,jj) * e3u_n(ji,jj,jk)
+                           ! ln_botmix_triad is .T. don't mask zah for bottom half cells    !!gm ?????   ahu is masked....
+                           zah = pahu(ji,jj,jk)
+                           zah_slp  = zah * zslope_iso
+                           IF( ln_ldfeiv )   zaei_slp = aeiu(ji,jj,jk) * zslope_skew
+                           zftu(ji   ,jj,jk   ) = zftu(ji   ,jj,jk   ) - ( zah * zdxt + (zah_slp - zaei_slp) * zdzt ) * zbu * ze1ur
+                           ztfw(ji+ip,jj,jk+kp) = ztfw(ji+ip,jj,jk+kp) - ( zah_slp + zaei_slp) * zdxt                 * zbu * ze3wr
+                        END DO
+                     END DO
+                  END DO
+               END DO
+               !
+               DO jp = 0, 1
+                  DO kp = 0, 1
+                     DO jj = 1, jpjm1
+                        DO ji = 1, fs_jpim1
+                           ze2vr = r1_e2v(ji,jj)
+                           zdyt  = zdjt(ji,jj,jk) * ze2vr
+                           ze3wr = 1._wp / e3w_n(ji,jj+jp,jk+kp)
+                           zdzt  = zdkt3d(ji,jj+jp,kp) * ze3wr
+                           zslope_skew = triadj_g(ji,jj+jp,jk,1-jp,kp)
+                           zslope_iso  = triadj(ji,jj+jp,jk,1-jp,kp)
+                           zbv = 0.25_wp * e1e2v(ji,jj) * e3v_n(ji,jj,jk)
+                           ! ln_botmix_triad is .T. don't mask zah for bottom half cells    !!gm ?????  ahv is masked...
+                           zah = pahv(ji,jj,jk)
+                           zah_slp = zah * zslope_iso
+                           IF( ln_ldfeiv )   zaei_slp = aeiv(ji,jj,jk) * zslope_skew
+                           zftv(ji,jj   ,jk   ) = zftv(ji,jj   ,jk   ) - ( zah * zdyt + (zah_slp - zaei_slp) * zdzt ) * zbv * ze2vr
+                           ztfw(ji,jj+jp,jk+kp) = ztfw(ji,jj+jp,jk+kp) - ( zah_slp + zaei_slp ) * zdyt                * zbv * ze3wr
+                        END DO
+                     END DO
+                  END DO
+               END DO
+               !
+            ELSE
+               !
+               DO ip = 0, 1               !==  Horizontal & vertical fluxes
+                  DO kp = 0, 1
+                     DO jj = 1, jpjm1
+                        DO ji = 1, fs_jpim1
+                           ze1ur = r1_e1u(ji,jj)
+                           zdxt  = zdit(ji,jj,jk) * ze1ur
+                           ze3wr = 1._wp / e3w_n(ji+ip,jj,jk+kp)
+                           zdzt  = zdkt3d(ji+ip,jj,kp) * ze3wr
+                           zslope_skew = triadi_g(ji+ip,jj,jk,1-ip,kp)
+                           zslope_iso  = triadi(ji+ip,jj,jk,1-ip,kp)
+                           !
+                           zbu = 0.25_wp * e1e2u(ji,jj) * e3u_n(ji,jj,jk)
+                           ! ln_botmix_triad is .F. mask zah for bottom half cells
+                           zah = pahu(ji,jj,jk) * umask(ji,jj,jk+kp)         ! pahu(ji+ip,jj,jk)   ===>>  ????
+                           zah_slp  = zah * zslope_iso
+                           IF( ln_ldfeiv )   zaei_slp = aeiu(ji,jj,jk) * zslope_skew        ! aeit(ji+ip,jj,jk)*zslope_skew
+                           zftu(ji   ,jj,jk   ) = zftu(ji   ,jj,jk   ) - ( zah * zdxt + (zah_slp - zaei_slp) * zdzt ) * zbu * ze1ur
+                           ztfw(ji+ip,jj,jk+kp) = ztfw(ji+ip,jj,jk+kp) - (zah_slp + zaei_slp) * zdxt * zbu * ze3wr
+                        END DO
+                     END DO
+                  END DO
+               END DO
+               !
+               DO jp = 0, 1
+                  DO kp = 0, 1
+                     DO jj = 1, jpjm1
+                        DO ji = 1, fs_jpim1
+                           ze2vr = r1_e2v(ji,jj)
+                           zdyt  = zdjt(ji,jj,jk) * ze2vr
+                           ze3wr = 1._wp / e3w_n(ji,jj+jp,jk+kp)
+                           zdzt  = zdkt3d(ji,jj+jp,kp) * ze3wr
+                           zslope_skew = triadj_g(ji,jj+jp,jk,1-jp,kp)
+                           zslope_iso  = triadj(ji,jj+jp,jk,1-jp,kp)
+                           zbv = 0.25_wp * e1e2v(ji,jj) * e3v_n(ji,jj,jk)
+                           ! ln_botmix_triad is .F. mask zah for bottom half cells
+                           zah = pahv(ji,jj,jk) * vmask(ji,jj,jk+kp)         ! pahv(ji,jj+jp,jk)  ????
+                           zah_slp = zah * zslope_iso
+                           IF( ln_ldfeiv )   zaei_slp = aeiv(ji,jj,jk) * zslope_skew        ! aeit(ji,jj+jp,jk)*zslope_skew
+                           zftv(ji,jj,jk) = zftv(ji,jj,jk) - ( zah * zdyt + (zah_slp - zaei_slp) * zdzt ) * zbv * ze2vr
+                           ztfw(ji,jj+jp,jk+kp) = ztfw(ji,jj+jp,jk+kp) - (zah_slp + zaei_slp) * zdyt * zbv * ze3wr
+                        END DO
+                     END DO
+                  END DO
+               END DO
+            ENDIF
+            !                             !==  horizontal divergence and add to the general trend  ==!
+            DO jj = 2 , jpjm1
+               DO ji = fs_2, fs_jpim1  ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + zsign * (  zftu(ji-1,jj,jk) - zftu(ji,jj,jk)       &
+                     &                                           + zftv(ji,jj-1,jk) - zftv(ji,jj,jk)   )   &
+                     &                                        / (  e1e2t(ji,jj) * e3t_n(ji,jj,jk)  )
+               END DO
+            END DO
+            !
+         END DO
+         !
+         !                                !==  add the vertical 33 flux  ==!
+         IF( ln_traldf_lap ) THEN               ! laplacian case: eddy coef = ah_wslp2 - akz
+            DO jk = 2, jpkm1       
+               DO jj = 1, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     ztfw(ji,jj,jk) = ztfw(ji,jj,jk) - e1e2t(ji,jj) / e3w_n(ji,jj,jk) * tmask(ji,jj,jk)   &
+                        &                            * ( ah_wslp2(ji,jj,jk) - akz(ji,jj,jk) )             &
+                        &                            * ( ptb(ji,jj,jk-1,jn) - ptb(ji,jj,jk,jn) )
+                  END DO
+               END DO
+            END DO
+         ELSE                                   ! bilaplacian 
+            SELECT CASE( kpass )
+            CASE(  1  )                            ! 1st pass : eddy coef = ah_wslp2
+               DO jk = 2, jpkm1 
+                  DO jj = 1, jpjm1
+                     DO ji = fs_2, fs_jpim1
+                        ztfw(ji,jj,jk) = ztfw(ji,jj,jk) - e1e2t(ji,jj) / e3w_n(ji,jj,jk) * tmask(ji,jj,jk)             &
+                           &                            * ah_wslp2(ji,jj,jk) * ( ptb(ji,jj,jk-1,jn) - ptb(ji,jj,jk,jn) )
+                     END DO
+                  END DO
+               END DO 
+            CASE(  2  )                            ! 2nd pass : eddy flux = ah_wslp2 and akz applied on ptb  and ptbb gradients, resp.
+               DO jk = 2, jpkm1 
+                  DO jj = 1, jpjm1
+                     DO ji = fs_2, fs_jpim1
+                        ztfw(ji,jj,jk) = ztfw(ji,jj,jk) - e1e2t(ji,jj) / e3w_n(ji,jj,jk) * tmask(ji,jj,jk)                      &
+                           &                            * (  ah_wslp2(ji,jj,jk) * ( ptb (ji,jj,jk-1,jn) - ptb (ji,jj,jk,jn) )   &
+                           &                               + akz     (ji,jj,jk) * ( ptbb(ji,jj,jk-1,jn) - ptbb(ji,jj,jk,jn) )   )
+                     END DO
+                  END DO
+               END DO
+            END SELECT 
+         ENDIF
+         !
+         DO jk = 1, jpkm1                 !==  Divergence of vertical fluxes added to pta  ==!
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1  ! vector opt.
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + zsign * (  ztfw(ji,jj,jk+1) - ztfw(ji,jj,jk)  )   &
+                     &                                        / ( e1e2t(ji,jj) * e3t_n(ji,jj,jk) )
+               END DO
+            END DO
+         END DO
+         !
+         IF( ( kpass == 1 .AND. ln_traldf_lap ) .OR.  &     !==  first pass only (  laplacian)  ==!
+             ( kpass == 2 .AND. ln_traldf_blp ) ) THEN      !==  2nd   pass      (bilaplacian)  ==!
+            !
+            !                          ! "Poleward" diffusive heat or salt transports (T-S case only)
+            IF( l_ptr )  CALL dia_ptr_hst( jn, 'ldf', zftv(:,:,:)  )
+            !                          ! Diffusive heat transports
+            IF( l_hst )  CALL dia_ar5_hst( jn, 'ldf', zftu(:,:,:), zftv(:,:,:) )
+            !
+         ENDIF                                                    !== end pass selection  ==!
+         !
+         !                                                        ! ===============
+      END DO                                                      ! end tracer loop
+      !                                                           ! ===============
+   END SUBROUTINE tra_ldf_triad
+
+   !!==============================================================================
+END MODULE traldf_triad
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tramle.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tramle.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tramle.F90	(revision 14097)
@@ -0,0 +1,342 @@
+MODULE tramle
+   !!======================================================================
+   !!                    ***  MODULE  tramle  ***
+   !! Ocean tracers: Mixed Layer Eddy induced transport
+   !!======================================================================
+   !! History :  3.3  !  2010-08  (G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_mle_trp   : update the effective transport with the Mixed Layer Eddy induced transport
+   !!   tra_mle_init  : initialisation of the Mixed Layer Eddy induced transport computation
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE phycst         ! physical constant
+   USE zdfmxl         ! mixed layer depth
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! IOM library
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! lateral boundary condition / mpp link
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_mle_trp        ! routine called in traadv.F90
+   PUBLIC   tra_mle_init   ! routine called in traadv.F90
+
+   !                                    !!* namelist namtra_mle *
+   LOGICAL, PUBLIC ::   ln_mle           !: flag to activate the Mixed Layer Eddy (MLE) parameterisation
+   INTEGER         ::      nn_mle           ! MLE type: =0 standard Fox-Kemper ; =1 new formulation
+   INTEGER         ::      nn_mld_uv        ! space interpolation of MLD at u- & v-pts (0=min,1=averaged,2=max)
+   INTEGER         ::      nn_conv          ! =1 no MLE in case of convection ; =0 always MLE
+   REAL(wp)        ::      rn_ce            ! MLE coefficient
+   !                                        ! parameters used in nn_mle = 0 case
+   REAL(wp)        ::      rn_lf               ! typical scale of mixed layer front
+   REAL(wp)        ::      rn_time             ! time scale for mixing momentum across the mixed layer
+   !                                        ! parameters used in nn_mle = 1 case
+   REAL(wp)        ::      rn_lat              ! reference latitude for a 5 km scale of ML front
+   REAL(wp)        ::      rn_rho_c_mle        ! Density criterion for definition of MLD used by FK
+
+   REAL(wp) ::   r5_21 = 5.e0 / 21.e0   ! factor used in mle streamfunction computation
+   REAL(wp) ::   rb_c                   ! ML buoyancy criteria = g rho_c /rau0 where rho_c is defined in zdfmld
+   REAL(wp) ::   rc_f                   ! MLE coefficient (= rn_ce / (5 km * fo) ) in nn_mle=1 case
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rfu, rfv   ! modified Coriolis parameter (f+tau) at u- & v-pts
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   r1_ft      ! inverse of the modified Coriolis parameter at t-pts
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_mle_trp( kt, kit000, pu, pv, pw, cdtype )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_mle_trp  ***
+      !!
+      !! ** Purpose :   Add to the transport the Mixed Layer Eddy induced transport
+      !!
+      !! ** Method  :   The 3 components of the Mixed Layer Eddy (MLE) induced
+      !!              transport are computed as follows :
+      !!                zu_mle = dk[ zpsi_uw ]
+      !!                zv_mle = dk[ zpsi_vw ]
+      !!                zw_mle = - di[ zpsi_uw ] - dj[ zpsi_vw ]
+      !!                where zpsi is the MLE streamfunction at uw and vw points (see the doc)
+      !!              and added to the input velocity :
+      !!                p.n = p.n + z._mle
+      !!
+      !! ** Action  : - (pun,pvn,pwn) increased by the mle transport
+      !!                CAUTION, the transport is not updated at the last line/raw
+      !!                         this may be a problem for some advection schemes
+      !!
+      !! References: Fox-Kemper et al., JPO, 38, 1145-1165, 2008
+      !!             Fox-Kemper and Ferrari, JPO, 38, 1166-1179, 2008
+      !!----------------------------------------------------------------------
+      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)
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pu         ! in : 3 ocean transport components
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pv         ! out: same 3  transport components
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pw         !   increased by the MLE induced transport
+      !
+      INTEGER  ::   ji, jj, jk          ! dummy loop indices
+      INTEGER  ::   ii, ij, ik, ikmax   ! local integers
+      REAL(wp) ::   zcuw, zmuw, zc      ! local scalar
+      REAL(wp) ::   zcvw, zmvw          !   -      -
+      INTEGER , DIMENSION(jpi,jpj)     :: inml_mle
+      REAL(wp), DIMENSION(jpi,jpj)     :: zpsim_u, zpsim_v, zmld, zbm, zhu, zhv, zn2, zLf_NH, zLf_MH
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpsi_uw, zpsi_vw
+      !!----------------------------------------------------------------------
+      !
+      !                                      !==  MLD used for MLE  ==!
+      !                                                ! compute from the 10m density to deal with the diurnal cycle
+      inml_mle(:,:) = mbkt(:,:) + 1                    ! init. to number of ocean w-level (T-level + 1)
+      IF ( nla10 > 0 ) THEN                            ! avoid case where first level is thicker than 10m
+         DO jk = jpkm1, nlb10, -1                      ! from the bottom to nlb10 (10m)
+            DO jj = 1, jpj
+               DO ji = 1, jpi                          ! index of the w-level at the ML based
+                  IF( rhop(ji,jj,jk) > rhop(ji,jj,nla10) + rn_rho_c_mle )   inml_mle(ji,jj) = jk      ! Mixed layer
+               END DO
+            END DO
+         END DO
+      ENDIF
+      ikmax = MIN( MAXVAL( inml_mle(:,:) ), jpkm1 )                  ! max level of the computation
+      !
+      !
+      zmld(:,:) = 0._wp                      !==   Horizontal shape of the MLE  ==!
+      zbm (:,:) = 0._wp
+      zn2 (:,:) = 0._wp
+      DO jk = 1, ikmax                                 ! MLD and mean buoyancy and N2 over the mixed layer
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zc = e3t_n(ji,jj,jk) * REAL( MIN( MAX( 0, inml_mle(ji,jj)-jk ) , 1  )  )    ! zc being 0 outside the ML t-points
+               zmld(ji,jj) = zmld(ji,jj) + zc
+               zbm (ji,jj) = zbm (ji,jj) + zc * (rau0 - rhop(ji,jj,jk) ) * r1_rau0
+               zn2 (ji,jj) = zn2 (ji,jj) + zc * (rn2(ji,jj,jk)+rn2(ji,jj,jk+1))*0.5_wp
+            END DO
+         END DO
+      END DO
+
+      SELECT CASE( nn_mld_uv )                         ! MLD at u- & v-pts
+      CASE ( 0 )                                               != min of the 2 neighbour MLDs
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zhu(ji,jj) = MIN( zmld(ji+1,jj), zmld(ji,jj) )
+               zhv(ji,jj) = MIN( zmld(ji,jj+1), zmld(ji,jj) )
+            END DO
+         END DO
+      CASE ( 1 )                                               != average of the 2 neighbour MLDs
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zhu(ji,jj) = ( zmld(ji+1,jj) + zmld(ji,jj) ) * 0.5_wp
+               zhv(ji,jj) = ( zmld(ji,jj+1) + zmld(ji,jj) ) * 0.5_wp
+            END DO
+         END DO
+      CASE ( 2 )                                               != max of the 2 neighbour MLDs
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zhu(ji,jj) = MAX( zmld(ji+1,jj), zmld(ji,jj) )
+               zhv(ji,jj) = MAX( zmld(ji,jj+1), zmld(ji,jj) )
+            END DO
+         END DO
+      END SELECT
+      !                                                ! convert density into buoyancy
+      zbm(:,:) = + grav * zbm(:,:) / MAX( e3t_n(:,:,1), zmld(:,:) )
+      !
+      !
+      !                                      !==  Magnitude of the MLE stream function  ==!
+      !
+      !                 di[bm]  Ds
+      ! Psi = Ce  H^2 ---------------- e2u  mu(z)   where fu Lf = MAX( fu*rn_fl , (Db H)^1/2 )
+      !                  e1u   Lf fu                      and the e2u for the "transport"
+      !                                                      (not *e3u as divided by e3u at the end)
+      !
+      IF( nn_mle == 0 ) THEN           ! Fox-Kemper et al. 2010 formulation
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zpsim_u(ji,jj) = rn_ce * zhu(ji,jj) * zhu(ji,jj)  * e2_e1u(ji,jj)                                            &
+                  &           * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )   &
+                  &           / (  MAX( rn_lf * rfu(ji,jj) , SQRT( rb_c * zhu(ji,jj) ) )   )
+                  !
+               zpsim_v(ji,jj) = rn_ce * zhv(ji,jj) * zhv(ji,jj)  * e1_e2v(ji,jj)                                            &
+                  &           * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )   &
+                  &           / (  MAX( rn_lf * rfv(ji,jj) , SQRT( rb_c * zhv(ji,jj) ) )   )
+            END DO
+         END DO
+         !
+      ELSEIF( nn_mle == 1 ) THEN       ! New formulation (Lf = 5km fo/ff with fo=Coriolis parameter at latitude rn_lat)
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zpsim_u(ji,jj) = rc_f *   zhu(ji,jj)   * zhu(ji,jj)   * e2_e1u(ji,jj)               &
+                  &                  * ( zbm(ji+1,jj) - zbm(ji,jj) ) * MIN( 111.e3_wp , e1u(ji,jj) )
+                  !
+               zpsim_v(ji,jj) = rc_f *   zhv(ji,jj)   * zhv(ji,jj)   * e1_e2v(ji,jj)               &
+                  &                  * ( zbm(ji,jj+1) - zbm(ji,jj) ) * MIN( 111.e3_wp , e2v(ji,jj) )
+            END DO
+         END DO
+      ENDIF
+      !
+      IF( nn_conv == 1 ) THEN              ! No MLE in case of convection
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               IF( MIN( zn2(ji,jj) , zn2(ji+1,jj) ) < 0._wp )   zpsim_u(ji,jj) = 0._wp
+               IF( MIN( zn2(ji,jj) , zn2(ji,jj+1) ) < 0._wp )   zpsim_v(ji,jj) = 0._wp
+            END DO
+         END DO
+      ENDIF
+      !
+      !                                      !==  structure function value at uw- and vw-points  ==!
+      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
+      !
+      DO jk = 2, ikmax                                ! start from 2 : surface value = 0
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               zcuw = 1._wp - ( gdepw_n(ji+1,jj,jk) + gdepw_n(ji,jj,jk) ) * zhu(ji,jj)
+               zcvw = 1._wp - ( gdepw_n(ji,jj+1,jk) + gdepw_n(ji,jj,jk) ) * zhv(ji,jj)
+               zcuw = zcuw * zcuw
+               zcvw = zcvw * zcvw
+               zmuw = MAX(  0._wp , ( 1._wp - zcuw ) * ( 1._wp + r5_21 * zcuw )  )
+               zmvw = MAX(  0._wp , ( 1._wp - zcvw ) * ( 1._wp + r5_21 * zcvw )  )
+               !
+               zpsi_uw(ji,jj,jk) = zpsim_u(ji,jj) * zmuw * umask(ji,jj,jk)
+               zpsi_vw(ji,jj,jk) = zpsim_v(ji,jj) * zmvw * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      !                                      !==  transport increased by the MLE induced transport ==!
+      DO jk = 1, ikmax
+         DO jj = 1, jpjm1                          ! CAUTION pu,pv must be defined at row/column i=1 / j=1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               pu(ji,jj,jk) = pu(ji,jj,jk) + ( zpsi_uw(ji,jj,jk) - zpsi_uw(ji,jj,jk+1) )
+               pv(ji,jj,jk) = pv(ji,jj,jk) + ( zpsi_vw(ji,jj,jk) - zpsi_vw(ji,jj,jk+1) )
+            END DO
+         END DO
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               pw(ji,jj,jk) = pw(ji,jj,jk) - ( zpsi_uw(ji,jj,jk) - zpsi_uw(ji-1,jj,jk)   &
+                  &                          + zpsi_vw(ji,jj,jk) - zpsi_vw(ji,jj-1,jk) )
+            END DO
+         END DO
+      END DO
+
+      IF( cdtype == 'TRA') THEN              !==  outputs  ==!
+         !
+         zLf_NH(:,:) = SQRT( rb_c * zmld(:,:) ) * r1_ft(:,:)      ! Lf = N H / f
+         CALL iom_put( "Lf_NHpf" , zLf_NH  )    ! Lf = N H / f
+         !
+         ! divide by cross distance to give streamfunction with dimensions m^2/s
+         DO jk = 1, ikmax+1
+            zpsi_uw(:,:,jk) = zpsi_uw(:,:,jk) * r1_e2u(:,:)
+            zpsi_vw(:,:,jk) = zpsi_vw(:,:,jk) * r1_e1v(:,:)
+         END DO
+         CALL iom_put( "psiu_mle", zpsi_uw )    ! i-mle streamfunction
+         CALL iom_put( "psiv_mle", zpsi_vw )    ! j-mle streamfunction
+      ENDIF
+      !
+   END SUBROUTINE tra_mle_trp
+
+
+   SUBROUTINE tra_mle_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_mle_init  ***
+      !!
+      !! ** Purpose :   Control the consistency between namelist options for
+      !!              tracer advection schemes and set nadv
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ierr
+      INTEGER ::    ios                 ! Local integer output status for namelist read
+      REAL(wp) ::   z1_t2, zfu, zfv                                !    -         -
+      !
+      NAMELIST/namtra_mle/ ln_mle , nn_mle, rn_ce, rn_lf, rn_time, rn_lat, nn_mld_uv, nn_conv, rn_rho_c_mle
+      !!----------------------------------------------------------------------
+
+      REWIND( numnam_ref )              ! Namelist namtra_mle in reference namelist : Tracer advection scheme
+      READ  ( numnam_ref, namtra_mle, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_mle in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namtra_mle in configuration namelist : Tracer advection scheme
+      READ  ( numnam_cfg, namtra_mle, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_mle in configuration namelist' )
+      IF(lwm) WRITE ( numond, namtra_mle )
+
+      IF(lwp) THEN                     ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_mle_init : mixed layer eddy (MLE) advection acting on tracers'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtra_mle : mixed layer eddy advection applied on tracers'
+         WRITE(numout,*) '      use mixed layer eddy (MLE, i.e. Fox-Kemper param) (T/F)      ln_mle       = ', ln_mle
+         WRITE(numout,*) '         MLE type: =0 standard Fox-Kemper ; =1 new formulation        nn_mle    = ', nn_mle
+         WRITE(numout,*) '         magnitude of the MLE (typical value: 0.06 to 0.08)           rn_ce     = ', rn_ce
+         WRITE(numout,*) '         scale of ML front (ML radius of deformation) (rn_mle=0)      rn_lf     = ', rn_lf, 'm'
+         WRITE(numout,*) '         maximum time scale of MLE                    (rn_mle=0)      rn_time   = ', rn_time, 's'
+         WRITE(numout,*) '         reference latitude (degrees) of MLE coef.    (rn_mle=1)      rn_lat    = ', rn_lat, 'deg'
+         WRITE(numout,*) '         space interp. of MLD at u-(v-)pts (0=min,1=averaged,2=max)   nn_mld_uv = ', nn_mld_uv
+         WRITE(numout,*) '         =1 no MLE in case of convection ; =0 always MLE              nn_conv   = ', nn_conv
+         WRITE(numout,*) '         Density difference used to define ML for FK              rn_rho_c_mle  = ', rn_rho_c_mle
+      ENDIF
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         IF( ln_mle ) THEN
+            WRITE(numout,*) '   ==>>>   Mixed Layer Eddy induced transport added to tracer advection'
+            IF( nn_mle == 0 )   WRITE(numout,*) '              Fox-Kemper et al 2010 formulation'
+            IF( nn_mle == 1 )   WRITE(numout,*) '              New formulation'
+         ELSE
+            WRITE(numout,*) '   ==>>>   Mixed Layer Eddy parametrisation NOT used'
+         ENDIF
+      ENDIF
+      !
+      IF( ln_mle ) THEN                ! MLE initialisation
+         !
+         rb_c = grav * rn_rho_c_mle /rau0        ! Mixed Layer buoyancy criteria
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '      ML buoyancy criteria = ', rb_c, ' m/s2 '
+         IF(lwp) WRITE(numout,*) '      associated ML density criteria defined in zdfmxl = ', rho_c, 'kg/m3'
+         !
+         IF( nn_mle == 0 ) THEN           ! MLE array allocation & initialisation
+            ALLOCATE( rfu(jpi,jpj) , rfv(jpi,jpj) , STAT= ierr )
+            IF( ierr /= 0 )   CALL ctl_stop( 'tra_adv_mle_init: failed to allocate arrays' )
+            z1_t2 = 1._wp / ( rn_time * rn_time )
+            DO jj = 2, jpj                           ! "coriolis+ time^-1" at u- & v-points
+               DO ji = fs_2, jpi   ! vector opt.
+                  zfu = ( ff_f(ji,jj) + ff_f(ji,jj-1) ) * 0.5_wp
+                  zfv = ( ff_f(ji,jj) + ff_f(ji-1,jj) ) * 0.5_wp
+                  rfu(ji,jj) = SQRT(  zfu * zfu + z1_t2 )
+                  rfv(ji,jj) = SQRT(  zfv * zfv + z1_t2 )
+               END DO
+            END DO
+            CALL lbc_lnk_multi( 'tramle', rfu, 'U', 1. , rfv, 'V', 1. )
+            !
+         ELSEIF( nn_mle == 1 ) THEN           ! MLE array allocation & initialisation
+            rc_f = rn_ce / (  5.e3_wp * 2._wp * omega * SIN( rad * rn_lat )  )
+            !
+         ENDIF
+         !
+         !                                ! 1/(f^2+tau^2)^1/2 at t-point (needed in both nn_mle case)
+         ALLOCATE( r1_ft(jpi,jpj) , STAT= ierr )
+         IF( ierr /= 0 )   CALL ctl_stop( 'tra_adv_mle_init: failed to allocate r1_ft array' )
+         !
+         z1_t2 = 1._wp / ( rn_time * rn_time )
+         r1_ft(:,:) = 1._wp / SQRT(  ff_t(:,:) * ff_t(:,:) + z1_t2  )
+         !
+      ENDIF
+      !
+   END SUBROUTINE tra_mle_init
+
+   !!==============================================================================
+END MODULE tramle
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranpc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranpc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranpc.F90	(revision 14097)
@@ -0,0 +1,325 @@
+MODULE tranpc
+   !!==============================================================================
+   !!                       ***  MODULE  tranpc  ***
+   !! Ocean active tracers:  non penetrative convective adjustment scheme
+   !!==============================================================================
+   !! History :  1.0  ! 1990-09  (G. Madec)  Original code
+   !!                 ! 1996-01  (G. Madec)  statement function for e3
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  free form F90
+   !!            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.6  ! 2015-05  (L. Brodeau) new algorithm based on local Brunt-Vaisala freq.
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_npc       : apply the non penetrative convection scheme
+   !!----------------------------------------------------------------------
+   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 trd_oce        ! ocean active tracer trends
+   USE trdtra         ! ocean active tracer trends
+   USE eosbn2         ! equation of state (eos routine)
+   !
+   USE lbclnk         ! lateral boundary conditions (or mpp link)
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_npc    ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_npc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tranpc  ***
+      !!
+      !! ** Purpose : Non-penetrative convective adjustment scheme. solve
+      !!      the static instability of the water column on after fields
+      !!      while conserving heat and salt contents.
+      !!
+      !! ** Method  : updated algorithm able to deal with non-linear equation of state
+      !!              (i.e. static stability computed locally)
+      !!
+      !! ** Action  : - tsa: after tracers with the application of the npc scheme
+      !!              - send the associated trends for on-line diagnostics (l_trdtra=T)
+      !!
+      !! 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  ::   jiter, ikbot, ikp, ikup, ikdown, ilayer, ik_low   ! 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), PARAMETER ::   zn2_zero = 1.e-14_wp      ! acceptance criteria for neutrality (N2==0)
+      REAL(wp), DIMENSION(        jpk     ) ::   zvn2         ! vertical profile of N2 at 1 given point...
+      REAL(wp), DIMENSION(        jpk,jpts) ::   zvts, zvab   ! vertical profile of T & S , and  alpha & betaat 1 given point
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ) ::   zn2          ! N^2 
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) ::   zab          ! alpha and beta
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds   ! 3D workspace
+      !
+      LOGICAL, PARAMETER :: l_LB_debug = .FALSE. ! set to true if you want to follow what is
+      INTEGER :: ilc1, jlc1, klc1, nncpu         ! actually happening in a water column at point "ilc1, jlc1"
+      LOGICAL :: lp_monitor_point = .FALSE.      ! in CPU domain "nncpu"
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_npc')
+      !
+      IF( MOD( kt, nn_npc ) == 0 ) THEN
+         !
+         IF( l_trdtra )   THEN                    !* Save initial after fields
+            ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+            ztrdt(:,:,:) = tsa(:,:,:,jp_tem) 
+            ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+         ENDIF
+         !
+         IF( l_LB_debug ) THEN
+            ! Location of 1 known convection site to follow what's happening in the water column
+            ilc1 = 45 ;  jlc1 = 3 ; !  ORCA2 4x4, Antarctic coast, more than 2 unstable portions in the  water column...           
+            nncpu = 1  ;            ! the CPU domain contains the convection spot
+            klc1 =  mbkt(ilc1,jlc1) ! bottom of the ocean for debug point...          
+         ENDIF
+         !
+         CALL eos_rab( tsa, zab )         ! after alpha and beta (given on T-points)
+         CALL bn2    ( tsa, zab, zn2 )    ! after Brunt-Vaisala  (given on W-points)
+         !
+         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                      
+                  ENDIF                                  !LB debug  end
+                  !
+                  ikbot = mbkt(ji,jj)   ! ikbot: ocean bottom T-level
+                  ikp = 1                  ! because N2 is irrelevant at the surface level (will start at ikp=2)
+                  ilayer = 0
+                  jiter  = 0
+                  l_column_treated = .FALSE.
+                  !
+                  DO WHILE ( .NOT. l_column_treated )
+                     !
+                     jiter = jiter + 1
+                     ! 
+                     IF( jiter >= 400 ) EXIT
+                     !
+                     l_bottom_reached = .FALSE.
+                     !
+                     DO WHILE ( .NOT. l_bottom_reached )
+                        !
+                        ikp = ikp + 1
+                        !
+                        !! Testing level ikp for instability
+                        !! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+                        IF( zvn2(ikp) <  -zn2_zero ) THEN ! Instability found!
+                           !
+                           ilayer = ilayer + 1    ! yet another instable portion of the water column found....
+                           !
+                           IF( lp_monitor_point ) THEN 
+                              WRITE(numout,*)
+                              IF( ilayer == 1 .AND. jiter == 1 ) THEN   ! first time a column is spoted with an instability
+                                 WRITE(numout,*)
+                                 WRITE(numout,*) 'Time step = ',kt,' !!!'
+                              ENDIF
+                              WRITE(numout,*)  ' * Iteration #',jiter,': found instable portion #',ilayer,   &
+                                 &                                    ' in column! Starting at ikp =', ikp
+                              WRITE(numout,*)  ' *** N2 for point (i,j) = ',ji,' , ',jj
+                              DO jk = 1, klc1
+                                 WRITE(numout,*) jk, zvn2(jk)
+                              END DO
+                              WRITE(numout,*)
+                           ENDIF
+                           !
+                           IF( jiter == 1 )   inpcc = inpcc + 1 
+                           !
+                           IF( lp_monitor_point )   WRITE(numout, *) 'Negative N2 at ikp =',ikp,' for layer #', ilayer
+                           !
+                           !! ikup is the uppermost point where mixing will start:
+                           ikup = ikp - 1 ! ikup is always "at most at ikp-1", less if neutral levels overlying
+                           !
+                           !! If the points above ikp-1 have N2 == 0 they must also be mixed:
+                           IF( ikp > 2 ) THEN
+                              DO jk = ikp-1, 2, -1
+                                 IF( ABS(zvn2(jk)) < zn2_zero ) THEN
+                                    ikup = ikup - 1  ! 1 more upper level has N2=0 and must be added for the mixing
+                                 ELSE
+                                    EXIT
+                                 ENDIF
+                              END DO
+                           ENDIF
+                           !
+                           IF( ikup < 1 )   CALL ctl_stop( 'tra_npc :  PROBLEM #1')
+                           !
+                           zsum_temp = 0._wp
+                           zsum_sali = 0._wp
+                           zsum_alfa = 0._wp
+                           zsum_beta = 0._wp
+                           zsum_z    = 0._wp
+                                                    
+                           DO jk = ikup, ikbot      ! Inside the instable (and overlying neutral) portion of the column
+                              !
+                              zdz       = e3t_n(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
+                              !                              
+                              IF( jk == ikbot ) EXIT ! avoid array-index overshoot in case ikbot = jpk, cause we're calling jk+1 next line
+                              !! EXIT when we have reached the last layer that is instable (N2<0) or neutral (N2=0):
+                              IF( zvn2(jk+1) > zn2_zero ) EXIT
+                           END DO
+                          
+                           ikdown = jk ! for the current unstable layer, ikdown is the deepest point with a negative or neutral N2
+                           IF( ikup == ikdown )   CALL ctl_stop( 'tra_npc :  PROBLEM #2')
+
+                           ! Mixing Temperature, salinity, alpha and beta from ikup to ikdown included:
+                           zta   = zsum_temp/zsum_z
+                           zsa   = zsum_sali/zsum_z
+                           zalfa = zsum_alfa/zsum_z
+                           zbeta = zsum_beta/zsum_z
+
+                           IF( lp_monitor_point ) THEN
+                              WRITE(numout,*) 'MIXED T, S, alfa and beta between ikup =',ikup,   &
+                                 &            ' and ikdown =',ikdown,', in layer #',ilayer
+                              WRITE(numout,*) '  => Mean temp. in that portion =', zta
+                              WRITE(numout,*) '  => Mean sali. in that portion =', zsa
+                              WRITE(numout,*) '  => Mean Alfa  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
+                           
+                           
+                           !! Updating N2 in the relvant portion of the water column
+                           !! Temperature, Salinity, Alpha and Beta have been homogenized in the unstable portion
+                           !! => Need to re-compute N2! will use Alpha and Beta!
+                           
+                           ikup   = MAX(2,ikup)         ! ikup can never be 1 !
+                           ik_low = MIN(ikdown+1,ikbot) ! we must go 1 point deeper than ikdown!
+                           
+                           DO jk = ikup, ik_low              ! we must go 1 point deeper than ikdown!
+
+                              !! Interpolating alfa and beta at W point:
+                              zrw =  (gdepw_n(ji,jj,jk  ) - gdept_n(ji,jj,jk)) &
+                                 & / (gdept_n(ji,jj,jk-1) - gdept_n(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
+
+                              !! N2 at W point, doing exactly as in eosbn2.F90:
+                              zvn2(jk) = grav*( zaw * ( zvts(jk-1,jp_tem) - zvts(jk,jp_tem) )     &
+                                 &            - zbw * ( zvts(jk-1,jp_sal) - zvts(jk,jp_sal) )  )  &
+                                 &       / e3w_n(ji,jj,jk) * tmask(ji,jj,jk)
+
+                              !! OR, faster  => just considering the vertical gradient of density
+                              !! as only the signa maters...
+                              !zvn2(jk) = (  zaw * ( zvts(jk-1,jp_tem) - zvts(jk,jp_tem) )     &
+                              !     &      - zbw * ( zvts(jk-1,jp_sal) - zvts(jk,jp_sal) )  )
+
+                           END DO
+                        
+                           ikp = MIN(ikdown+1,ikbot)
+                           
+
+                        ENDIF  !IF( zvn2(ikp) < 0. )
+
+
+                        IF( ikp == ikbot ) l_bottom_reached = .TRUE.
+                        !
+                     END DO ! DO WHILE ( .NOT. l_bottom_reached )
+
+                     IF( ikp /= ikbot )   CALL ctl_stop( 'tra_npc :  PROBLEM #3')
+                    
+                     ! ******* At this stage ikp == ikbot ! *******
+                    
+                     IF( ilayer > 0 ) THEN      !! least an unstable layer has been found
+                        !
+                        IF( lp_monitor_point ) THEN
+                           WRITE(numout,*)
+                           WRITE(numout,*) 'After ',jiter,' iteration(s), we neutralized ',ilayer,' instable layer(s)'
+                           WRITE(numout,*) '   ==> N2 at i,j=',ji,',',jj,' now looks like this:'
+                           DO jk = 1, klc1
+                              WRITE(numout,*) jk, zvn2(jk)
+                           END DO
+                           WRITE(numout,*)
+                        ENDIF
+                        !
+                        ikp    = 1     ! starting again at the surface for the next iteration
+                        ilayer = 0
+                     ENDIF
+                     !
+                     IF( ikp >= ikbot )   l_column_treated = .TRUE.
+                     !
+                  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)
+
+                  !! LB:  Potentially some other global variable beside theta and S can be treated here
+                  !!      like BGC tracers.
+
+                  IF( 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 )
+            DEALLOCATE( ztrdt, ztrds )
+         ENDIF
+         !
+         CALL lbc_lnk_multi( 'tranpc', tsa(:,:,:,jp_tem), 'T', 1., tsa(:,:,:,jp_sal), 'T', 1. )
+         !
+         IF( lwp .AND. l_LB_debug ) THEN
+            WRITE(numout,*) 'Exiting tra_npc , kt = ',kt,', => numb. of statically instable water-columns: ', inpcc
+            WRITE(numout,*)
+         ENDIF
+         !
+      ENDIF   ! IF( MOD( kt, nn_npc ) == 0 ) THEN
+      !
+      IF( ln_timing )   CALL timing_stop('tra_npc')
+      !
+   END SUBROUTINE tra_npc
+
+   !!======================================================================
+END MODULE tranpc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranxt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranxt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/tranxt.F90	(revision 14097)
@@ -0,0 +1,374 @@
+MODULE tranxt
+   !!======================================================================
+   !!                       ***  MODULE  tranxt  ***
+   !! Ocean active tracers:  time stepping on temperature and salinity
+   !!======================================================================
+   !! History :  OPA  !  1991-11  (G. Madec)  Original code
+   !!            7.0  !  1993-03  (M. Guyon)  symetrical conditions
+   !!            8.0  !  1996-02  (G. Madec & M. Imbard)  opa release 8.0
+   !!             -   !  1996-04  (A. Weaver)  Euler forward step
+   !!            8.2  !  1999-02  (G. Madec, N. Grima)  semi-implicit pressure grad.
+   !!  NEMO      1.0  !  2002-08  (G. Madec)  F90: Free form and module
+   !!             -   !  2002-11  (C. Talandier, A-M Treguier) Open boundaries
+   !!             -   !  2005-04  (C. Deltel) Add Asselin trend in the ML budget
+   !!            2.0  !  2006-02  (L. Debreu, C. Mazauric) Agrif implementation
+   !!            3.0  !  2008-06  (G. Madec)  time stepping always done in trazdf
+   !!            3.1  !  2009-02  (G. Madec, R. Benshila)  re-introduce the vvl option
+   !!            3.3  !  2010-04  (M. Leclair, G. Madec)  semi-implicit hpg with asselin filter + modified LF-RA
+   !!             -   !  2010-05  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_nxt       : time stepping on tracers
+   !!   tra_nxt_fix   : time stepping on tracers : fixed    volume case
+   !!   tra_nxt_vvl   : time stepping on tracers : variable volume case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables 
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE sbcrnf          ! river runoffs
+   USE sbcisf          ! ice shelf melting
+   USE zdf_oce         ! ocean vertical mixing
+   USE domvvl          ! variable volume
+   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          ! lateral physics : tracers
+   USE ldfslp          ! lateral physics : slopes
+   USE bdy_oce  , ONLY : ln_bdy
+   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 timing          ! Timing
+#if defined key_agrif
+   USE agrif_oce_interp
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_nxt       ! routine called by step.F90
+   PUBLIC   tra_nxt_fix   ! to be used in trcnxt
+   PUBLIC   tra_nxt_vvl   ! to be used in trcnxt
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_nxt( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tranxt  ***
+      !!
+      !! ** Purpose :   Apply the boundary condition on the after temperature  
+      !!             and salinity fields, achieved the time stepping by adding
+      !!             the Asselin filter on now fields and swapping the fields.
+      !! 
+      !! ** Method  :   At this stage of the computation, ta and sa are the 
+      !!             after temperature and salinity as the time stepping has
+      !!             been performed in trazdf_imp or trazdf_exp module.
+      !!
+      !!              - Apply lateral boundary conditions on (ta,sa) 
+      !!             at the local domain   boundaries through lbc_lnk call, 
+      !!             at the one-way open boundaries (ln_bdy=T), 
+      !!             at the AGRIF zoom   boundaries (lk_agrif=T)
+      !!
+      !!              - Update lateral boundary conditions on AGRIF children
+      !!             domains (lk_agrif=T)
+      !!
+      !! ** Action  : - tsb & tsn ready for the next time step
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   zfact            ! local scalars
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrdt, ztrds
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'tra_nxt')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_nxt : achieve the time stepping by Asselin filter and array swap'
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      ENDIF
+
+      ! Update after tracer on domain lateral boundaries
+      ! 
+#if defined key_agrif
+      CALL Agrif_tra                     ! AGRIF zoom boundaries
+#endif
+      !                                              ! local domain boundaries  (T-point, unchanged sign)
+      CALL lbc_lnk_multi( 'tranxt', tsa(:,:,:,jp_tem), 'T', 1., tsa(:,:,:,jp_sal), 'T', 1. )
+      !
+      IF( ln_bdy )   CALL bdy_tra( kt )  ! BDY open boundaries
+ 
+      ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;   r2dt =        rdt   ! at nit000             (Euler)
+      ELSEIF( kt <= nit000 + 1 )           THEN   ;   r2dt = 2._wp* rdt   ! at nit000 or nit000+1 (Leapfrog)
+      ENDIF
+
+      ! trends computation initialisation
+      IF( l_trdtra )   THEN                    
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,jpk) = 0._wp
+         ztrds(:,:,jpk) = 0._wp
+         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
+         ! total trend for the non-time-filtered variables. 
+         zfact = 1.0 / rdt
+         ! G Nurser 23 Mar 2017. Recalculate trend as Delta(e3t*T)/e3tn; e3tn cancel from tsn terms
+         DO jk = 1, jpkm1
+            ztrdt(:,:,jk) = ( tsa(:,:,jk,jp_tem)*e3t_a(:,:,jk) / e3t_n(:,:,jk) - tsn(:,:,jk,jp_tem)) * zfact
+            ztrds(:,:,jk) = ( tsa(:,:,jk,jp_sal)*e3t_a(:,:,jk) / e3t_n(:,:,jk) - tsn(:,:,jk,jp_sal)) * zfact
+         END DO
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_tot, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_tot, ztrds )
+         IF( ln_linssh ) THEN       ! linear sea surface height only
+            ! Store now fields before applying the Asselin filter 
+            ! in order to calculate Asselin filter trend later.
+            ztrdt(:,:,:) = tsn(:,:,:,jp_tem) 
+            ztrds(:,:,:) = tsn(:,:,:,jp_sal)
+         ENDIF
+      ENDIF
+
+      IF( neuler == 0 .AND. kt == nit000 ) THEN       ! Euler time-stepping at first time-step (only swap)
+         DO jn = 1, jpts
+            DO jk = 1, jpkm1
+               tsn(:,:,jk,jn) = tsa(:,:,jk,jn)    
+            END DO
+         END DO
+         IF (l_trdtra .AND. .NOT. ln_linssh ) THEN   ! Zero Asselin filter contribution must be explicitly written out since for vvl
+            !                                        ! Asselin filter is output by tra_nxt_vvl that is not called on this time step
+            ztrdt(:,:,:) = 0._wp
+            ztrds(:,:,:) = 0._wp
+            CALL trd_tra( kt, 'TRA', jp_tem, jptra_atf, ztrdt )
+            CALL trd_tra( kt, 'TRA', jp_sal, jptra_atf, ztrds )
+         END IF
+         !
+      ELSE                                            ! Leap-Frog + Asselin filter time stepping
+         !
+         IF( ln_linssh ) THEN   ;   CALL tra_nxt_fix( kt, nit000,      'TRA', tsb, tsn, tsa, jpts )  ! linear free surface 
+         ELSE                   ;   CALL tra_nxt_vvl( kt, nit000, rdt, 'TRA', tsb, tsn, tsa,   &
+           &                                                                sbc_tsc, sbc_tsc_b, jpts )  ! non-linear free surface
+         ENDIF
+         !
+         CALL lbc_lnk_multi( 'tranxt', tsb(:,:,:,jp_tem), 'T', 1., tsb(:,:,:,jp_sal), 'T', 1., &
+                  &          tsn(:,:,:,jp_tem), 'T', 1., tsn(:,:,:,jp_sal), 'T', 1., &
+                  &          tsa(:,:,:,jp_tem), 'T', 1., tsa(:,:,:,jp_sal), 'T', 1.  )
+         !
+      ENDIF     
+      !
+      IF( l_trdtra .AND. ln_linssh ) THEN      ! trend of the Asselin filter (tb filtered - tb)/dt     
+         zfact = 1._wp / r2dt             
+         DO jk = 1, jpkm1
+            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_atf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_atf, ztrds )
+      END IF
+      IF( l_trdtra )   DEALLOCATE( ztrdt , ztrds )
+      !
+      !                        ! control print
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsn(:,:,:,jp_tem), clinfo1=' nxt  - Tn: ', mask1=tmask,   &
+         &                       tab3d_2=tsn(:,:,:,jp_sal), clinfo2=       ' Sn: ', mask2=tmask )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_nxt')
+      !
+   END SUBROUTINE tra_nxt
+
+
+   SUBROUTINE tra_nxt_fix( kt, kit000, cdtype, ptb, ptn, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tra_nxt_fix  ***
+      !!
+      !! ** Purpose :   fixed volume: apply the Asselin time filter and 
+      !!                swap the tracer fields.
+      !! 
+      !! ** Method  : - Apply a Asselin time filter on now fields.
+      !!              - swap tracer fields to prepare the next time_step.
+      !!
+      !! ** Action  : - tsb & tsn ready for the next time step
+      !!----------------------------------------------------------------------
+      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(jpi,jpj,jpk,kjpt), INTENT(inout) ::  ptb       ! before tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::  ptn       ! now tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::  pta       ! tracer trend
+      !
+      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::   ztn, ztd         ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_nxt_fix : time stepping', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      DO jn = 1, kjpt
+         !
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  ztn = ptn(ji,jj,jk,jn)                                    
+                  ztd = pta(ji,jj,jk,jn) - 2._wp * ztn + ptb(ji,jj,jk,jn)  ! time laplacian on tracers
+                  !
+                  ptb(ji,jj,jk,jn) = ztn + atfp * ztd                      ! ptb <-- filtered ptn 
+                  ptn(ji,jj,jk,jn) = pta(ji,jj,jk,jn)                      ! ptn <-- pta
+               END DO
+           END DO
+         END DO
+         !
+      END DO
+      !
+   END SUBROUTINE tra_nxt_fix
+
+
+   SUBROUTINE tra_nxt_vvl( kt, kit000, p2dt, cdtype, ptb, ptn, pta, psbc_tc, psbc_tc_b, kjpt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tra_nxt_vvl  ***
+      !!
+      !! ** Purpose :   Time varying volume: apply the Asselin time filter  
+      !!                and swap the tracer fields.
+      !! 
+      !! ** Method  : - Apply a thickness weighted Asselin time filter on now fields.
+      !!              - swap tracer fields to prepare the next time_step.
+      !!             tb  = ( e3t_n*tn + atfp*[ e3t_b*tb - 2 e3t_n*tn + e3t_a*ta ] )
+      !!                  /( e3t_n    + atfp*[ e3t_b    - 2 e3t_n    + e3t_a    ] )
+      !!             tn  = ta 
+      !!
+      !! ** Action  : - tsb & tsn ready for the next time step
+      !!----------------------------------------------------------------------
+      INTEGER                              , INTENT(in   ) ::  kt        ! ocean time-step index
+      INTEGER                              , INTENT(in   ) ::  kit000    ! first time step index
+      REAL(wp)                             , INTENT(in   ) ::  p2dt      ! time-step
+      CHARACTER(len=3)                     , INTENT(in   ) ::  cdtype    ! =TRA or TRC (tracer indicator)
+      INTEGER                              , INTENT(in   ) ::  kjpt      ! number of tracers
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::  ptb       ! before tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::  ptn       ! now tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::  pta       ! tracer trend
+      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::  psbc_tc   ! surface tracer content
+      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::  psbc_tc_b ! before surface tracer content
+      !
+      LOGICAL  ::   ll_traqsr, ll_rnf, ll_isf   ! local logical
+      INTEGER  ::   ji, jj, jk, jn              ! dummy loop indices
+      REAL(wp) ::   zfact, zfact1, ztc_a , ztc_n , ztc_b , ztc_f , ztc_d    ! local scalar
+      REAL(wp) ::   zfact2, ze3t_b, ze3t_n, ze3t_a, ze3t_f, ze3t_d, zscale  !   -      -
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ztrd_atf
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_nxt_vvl : time stepping', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      IF( cdtype == 'TRA' )  THEN   
+         ll_traqsr  = ln_traqsr        ! active  tracers case  and  solar penetration
+         ll_rnf     = ln_rnf           ! active  tracers case  and  river runoffs
+         ll_isf     = ln_isf           ! active  tracers case  and  ice shelf melting
+      ELSE                          ! passive tracers case
+         ll_traqsr  = .FALSE.          ! NO solar penetration
+         ll_rnf     = .FALSE.          ! NO river runoffs ????          !!gm BUG ?  
+         ll_isf     = .FALSE.          ! NO ice shelf melting/freezing  !!gm BUG ?? 
+      ENDIF
+      !
+      IF( ( l_trdtra .AND. cdtype == 'TRA' ) .OR. ( l_trdtrc .AND. cdtype == 'TRC' ) )   THEN
+         ALLOCATE( ztrd_atf(jpi,jpj,jpk,kjpt) )
+         ztrd_atf(:,:,:,:) = 0.0_wp
+      ENDIF
+      zfact = 1._wp / p2dt
+      zfact1 = atfp * p2dt
+      zfact2 = zfact1 * r1_rau0
+      DO jn = 1, kjpt      
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  ze3t_b = e3t_b(ji,jj,jk)
+                  ze3t_n = e3t_n(ji,jj,jk)
+                  ze3t_a = e3t_a(ji,jj,jk)
+                  !                                         ! tracer content at Before, now and after
+                  ztc_b  = ptb(ji,jj,jk,jn) * ze3t_b
+                  ztc_n  = ptn(ji,jj,jk,jn) * ze3t_n
+                  ztc_a  = pta(ji,jj,jk,jn) * ze3t_a
+                  !
+                  ze3t_d = ze3t_a - 2. * ze3t_n + ze3t_b
+                  ztc_d  = ztc_a  - 2. * ztc_n  + ztc_b
+                  !
+                  ze3t_f = ze3t_n + atfp * ze3t_d
+                  ztc_f  = ztc_n  + atfp * ztc_d
+                  !
+                  zscale = zfact2 * e3t_n(ji,jj,jk) / ( ht_n(ji,jj) + 1._wp - ssmask(ji,jj) )
+                  ze3t_f = ze3t_f - zscale * ( emp_b(ji,jj) - emp(ji,jj) )
+                  IF ( ll_rnf ) ze3t_f = ze3t_f + zscale * (    rnf_b(ji,jj) -    rnf(ji,jj) )
+                  IF ( ll_isf ) ze3t_f = ze3t_f - zscale * ( fwfisf_b(ji,jj) - fwfisf(ji,jj) )
+
+                  IF( jk == mikt(ji,jj) ) THEN           ! first level 
+                     ztc_f  = ztc_f  - zfact1 * ( psbc_tc(ji,jj,jn) - psbc_tc_b(ji,jj,jn) )
+                  ENDIF
+                  !
+                  ! solar penetration (temperature only)
+                  IF( ll_traqsr .AND. jn == jp_tem .AND. jk <= nksr )                            & 
+                     &     ztc_f  = ztc_f  - zfact1 * ( qsr_hc(ji,jj,jk) - qsr_hc_b(ji,jj,jk) ) 
+                     !
+                  ! river runoff
+                  IF( ll_rnf .AND. jk <= nk_rnf(ji,jj) )                                          &
+                     &     ztc_f  = ztc_f  - zfact1 * ( rnf_tsc(ji,jj,jn) - rnf_tsc_b(ji,jj,jn) ) & 
+                     &                              * e3t_n(ji,jj,jk) / h_rnf(ji,jj)
+                     !
+                  ! ice shelf
+                  IF( ll_isf ) THEN
+                     ! level fully include in the Losch_2008 ice shelf boundary layer
+                     IF ( jk >= misfkt(ji,jj) .AND. jk < misfkb(ji,jj) )                          &
+                        ztc_f  = ztc_f  - zfact1 * ( risf_tsc(ji,jj,jn) - risf_tsc_b(ji,jj,jn) )  &
+                               &                 * e3t_n(ji,jj,jk) * r1_hisf_tbl (ji,jj)
+                     ! level partially include in Losch_2008 ice shelf boundary layer 
+                     IF ( jk == misfkb(ji,jj) )                                                   &
+                        ztc_f  = ztc_f  - zfact1 * ( risf_tsc(ji,jj,jn) - risf_tsc_b(ji,jj,jn) )  &
+                               &                 * e3t_n(ji,jj,jk) * r1_hisf_tbl (ji,jj) * ralpha(ji,jj)
+                  END IF
+                  !
+                  ze3t_f = 1.e0 / ze3t_f
+                  ptb(ji,jj,jk,jn) = ztc_f * ze3t_f       ! ptb <-- ptn filtered
+                  ptn(ji,jj,jk,jn) = pta(ji,jj,jk,jn)     ! ptn <-- pta
+                  !
+                  IF( ( l_trdtra .and. cdtype == 'TRA' ) .OR. ( l_trdtrc .and. cdtype == 'TRC' ) ) THEN
+                     ztrd_atf(ji,jj,jk,jn) = (ztc_f - ztc_n) * zfact/ze3t_n
+                  ENDIF
+                  !
+               END DO
+            END DO
+         END DO
+         ! 
+      END DO
+      !
+      IF( ( l_trdtra .AND. cdtype == 'TRA' ) .OR. ( l_trdtrc .AND. cdtype == 'TRC' ) )   THEN
+         IF( l_trdtra .AND. cdtype == 'TRA' ) THEN 
+            CALL trd_tra( kt, cdtype, jp_tem, jptra_atf, ztrd_atf(:,:,:,jp_tem) )
+            CALL trd_tra( kt, cdtype, jp_sal, jptra_atf, ztrd_atf(:,:,:,jp_sal) )
+         ENDIF
+         IF( l_trdtrc .AND. cdtype == 'TRC' ) THEN
+            DO jn = 1, kjpt
+               CALL trd_tra( kt, cdtype, jn, jptra_atf, ztrd_atf(:,:,:,jn) )
+            END DO
+         ENDIF
+         DEALLOCATE( ztrd_atf )
+      ENDIF
+      !
+   END SUBROUTINE tra_nxt_vvl
+
+   !!======================================================================
+END MODULE tranxt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traqsr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traqsr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/traqsr.F90	(revision 14097)
@@ -0,0 +1,444 @@
+MODULE traqsr
+   !!======================================================================
+   !!                       ***  MODULE  traqsr  ***
+   !! Ocean physics:   solar radiation penetration in the top ocean levels
+   !!======================================================================
+   !! History :  OPA  !  1990-10  (B. Blanke)  Original code
+   !!            7.0  !  1991-11  (G. Madec)
+   !!                 !  1996-01  (G. Madec)  s-coordinates
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!             -   !  2005-11  (G. Madec) zco, zps, sco coordinate
+   !!            3.2  !  2009-04  (G. Madec & NEMO team) 
+   !!            3.6  !  2012-05  (C. Rousset) store attenuation coef for use in ice model 
+   !!            3.6  !  2015-12  (O. Aumont, J. Jouanno, C. Ethe) use vertical profile of chlorophyll
+   !!            3.7  !  2015-11  (G. Madec, A. Coward)  remove optimisation for fix volume 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_qsr       : temperature trend due to the penetration of solar radiation 
+   !!   tra_qsr_init  : initialization of the qsr penetration 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE phycst         ! physical constants
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE trc_oce        ! share SMS/Ocean variables
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE iom            ! I/O library
+   USE fldread        ! read input fields
+   USE restart        ! ocean restart
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_qsr       ! routine called by step.F90 (ln_traqsr=T)
+   PUBLIC   tra_qsr_init  ! routine called by nemogcm.F90
+
+   !                                 !!* Namelist namtra_qsr: penetrative solar radiation
+   LOGICAL , PUBLIC ::   ln_traqsr    !: light absorption (qsr) flag
+   LOGICAL , PUBLIC ::   ln_qsr_rgb   !: Red-Green-Blue light absorption flag  
+   LOGICAL , PUBLIC ::   ln_qsr_2bd   !: 2 band         light absorption flag
+   LOGICAL , PUBLIC ::   ln_qsr_bio   !: bio-model      light absorption flag
+   INTEGER , PUBLIC ::   nn_chldta    !: use Chlorophyll data (=1) or not (=0)
+   REAL(wp), PUBLIC ::   rn_abs       !: fraction absorbed in the very near surface (RGB & 2 bands)
+   REAL(wp), PUBLIC ::   rn_si0       !: very near surface depth of extinction      (RGB & 2 bands)
+   REAL(wp), PUBLIC ::   rn_si1       !: deepest depth of extinction (water type I)       (2 bands)
+   !
+   INTEGER , PUBLIC ::   nksr         !: levels below which the light cannot penetrate (depth larger than 391 m)
+ 
+   INTEGER, PARAMETER ::   np_RGB  = 1   ! R-G-B     light penetration with constant Chlorophyll
+   INTEGER, PARAMETER ::   np_RGBc = 2   ! R-G-B     light penetration with Chlorophyll data
+   INTEGER, PARAMETER ::   np_2BD  = 3   ! 2 bands   light penetration
+   INTEGER, PARAMETER ::   np_BIO  = 4   ! bio-model light penetration
+   !
+   INTEGER  ::   nqsr    ! user choice of the type of light penetration
+   REAL(wp) ::   xsi0r   ! inverse of rn_si0
+   REAL(wp) ::   xsi1r   ! inverse of rn_si1
+   !
+   REAL(wp) , PUBLIC, DIMENSION(3,61)   ::   rkrgb    ! tabulated attenuation coefficients for RGB absorption
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_chl   ! structure of input Chl (file informations, fields read)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_qsr( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_qsr  ***
+      !!
+      !! ** Purpose :   Compute the temperature trend due to the solar radiation
+      !!              penetration and add it to the general temperature trend.
+      !!
+      !! ** Method  : The profile of the solar radiation within the ocean is defined
+      !!      through 2 wavebands (rn_si0,rn_si1) or 3 wavebands (RGB) and a ratio rn_abs
+      !!      Considering the 2 wavebands case:
+      !!         I(k) = Qsr*( rn_abs*EXP(z(k)/rn_si0) + (1.-rn_abs)*EXP(z(k)/rn_si1) )
+      !!         The temperature trend associated with the solar radiation penetration 
+      !!         is given by : zta = 1/e3t dk[ I ] / (rau0*Cp)
+      !!         At the bottom, boudary condition for the radiation is no flux :
+      !!      all heat which has not been absorbed in the above levels is put
+      !!      in the last ocean level.
+      !!         The computation is only done down to the level where 
+      !!      I(k) < 1.e-15 W/m2 (i.e. over the top nksr levels) . 
+      !!
+      !! ** Action  : - update ta with the penetrative solar radiation trend
+      !!              - send  trend for further diagnostics (l_trdtra=T)
+      !!
+      !! Reference  : Jerlov, N. G., 1968 Optical Oceanography, Elsevier, 194pp.
+      !!              Lengaigne et al. 2007, Clim. Dyn., V28, 5, 503-516.
+      !!              Morel, A. et Berthon, JF, 1989, Limnol Oceanogr 34(8), 1545-1562
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt     ! ocean time-step
+      !
+      INTEGER  ::   ji, jj, jk               ! dummy loop indices
+      INTEGER  ::   irgb                     ! local integers
+      REAL(wp) ::   zchl, zcoef, z1_2        ! local scalars
+      REAL(wp) ::   zc0 , zc1 , zc2 , zc3    !    -         -
+      REAL(wp) ::   zzc0, zzc1, zzc2, zzc3   !    -         -
+      REAL(wp) ::   zz0 , zz1                !    -         -
+      REAL(wp) ::   zCb, zCmax, zze, zpsi, zpsimax, zdelpsi, zCtot, zCze
+      REAL(wp) ::   zlogc, zlogc2, zlogc3 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   :: zekb, zekg, zekr
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ze0, ze1, ze2, ze3, zea, ztrdt
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zetot, zchl3d
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_qsr')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_qsr : penetration of the surface solar radiation'
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+      ENDIF
+      !
+      IF( l_trdtra ) THEN      ! trends diagnostic: save the input temperature trend
+         ALLOCATE( ztrdt(jpi,jpj,jpk) ) 
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+      ENDIF
+      !
+      !                         !-----------------------------------!
+      !                         !  before qsr induced heat content  !
+      !                         !-----------------------------------!
+      IF( kt == nit000 ) THEN          !==  1st time step  ==!
+!!gm case neuler  not taken into account....
+         IF( ln_rstart .AND. iom_varid( numror, 'qsr_hc_b', ldstop = .FALSE. ) > 0 ) THEN    ! read in restart
+            IF(lwp) WRITE(numout,*) '          nit000-1 qsr tracer content forcing field read in the restart file'
+            z1_2 = 0.5_wp
+            CALL iom_get( numror, jpdom_autoglo, 'qsr_hc_b', qsr_hc_b, ldxios = lrxios )   ! before heat content trend due to Qsr flux
+         ELSE                                           ! No restart or restart not found: Euler forward time stepping
+            z1_2 = 1._wp
+            qsr_hc_b(:,:,:) = 0._wp
+         ENDIF
+      ELSE                             !==  Swap of qsr heat content  ==!
+         z1_2 = 0.5_wp
+         qsr_hc_b(:,:,:) = qsr_hc(:,:,:)
+      ENDIF
+      !
+      !                         !--------------------------------!
+      SELECT CASE( nqsr )       !  now qsr induced heat content  !
+      !                         !--------------------------------!
+      !
+      CASE( np_BIO )                   !==  bio-model fluxes  ==!
+         !
+         DO jk = 1, nksr
+            qsr_hc(:,:,jk) = r1_rau0_rcp * ( etot3(:,:,jk) - etot3(:,:,jk+1) )
+         END DO
+         !
+      CASE( np_RGB , np_RGBc )         !==  R-G-B fluxes  ==!
+         !
+         ALLOCATE( zekb(jpi,jpj)     , zekg(jpi,jpj)     , zekr  (jpi,jpj)     , &
+            &      ze0 (jpi,jpj,jpk) , ze1 (jpi,jpj,jpk) , ze2   (jpi,jpj,jpk) , &
+            &      ze3 (jpi,jpj,jpk) , zea (jpi,jpj,jpk) , zchl3d(jpi,jpj,jpk)   ) 
+         !
+         IF( nqsr == np_RGBc ) THEN          !*  Variable Chlorophyll
+            CALL fld_read( kt, 1, sf_chl )         ! Read Chl data and provides it at the current time step
+            DO jk = 1, nksr + 1
+               DO jj = 2, jpjm1                       ! Separation in R-G-B depending of the surface Chl
+                  DO ji = fs_2, fs_jpim1
+                     zchl    = MIN( 10. , MAX( 0.03, sf_chl(1)%fnow(ji,jj,1) ) )
+                     zCtot   = 40.6  * zchl**0.459
+                     zze     = 568.2 * zCtot**(-0.746)
+                     IF( zze > 102. ) zze = 200.0 * zCtot**(-0.293)
+                     zpsi    = gdepw_n(ji,jj,jk) / zze
+                     !
+                     zlogc   = LOG( zchl )
+                     zlogc2  = zlogc * zlogc
+                     zlogc3  = zlogc * zlogc * zlogc
+                     zCb     = 0.768 + 0.087 * zlogc - 0.179 * zlogc2 - 0.025 * zlogc3
+                     zCmax   = 0.299 - 0.289 * zlogc + 0.579 * zlogc2
+                     zpsimax = 0.6   - 0.640 * zlogc + 0.021 * zlogc2 + 0.115 * zlogc3
+                     zdelpsi = 0.710 + 0.159 * zlogc + 0.021 * zlogc2
+                     zCze    = 1.12  * (zchl)**0.803 
+                     !
+                     zchl3d(ji,jj,jk) = zCze * ( zCb + zCmax * EXP( -( (zpsi - zpsimax) / zdelpsi )**2 ) )
+                  END DO
+                  !
+               END DO
+            END DO
+         ELSE                                !* constant chrlorophyll
+           DO jk = 1, nksr + 1
+              zchl3d(:,:,jk) = 0.05 
+            ENDDO
+         ENDIF
+         !
+         zcoef  = ( 1. - rn_abs ) / 3._wp    !* surface equi-partition in R-G-B
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ze0(ji,jj,1) = rn_abs * qsr(ji,jj)
+               ze1(ji,jj,1) = zcoef  * qsr(ji,jj)
+               ze2(ji,jj,1) = zcoef  * qsr(ji,jj)
+               ze3(ji,jj,1) = zcoef  * qsr(ji,jj)
+               zea(ji,jj,1) =          qsr(ji,jj)
+            END DO
+         END DO
+         !
+         DO jk = 2, nksr+1                   !* interior equi-partition in R-G-B depending of vertical profile of Chl
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zchl = MIN( 10. , MAX( 0.03, zchl3d(ji,jj,jk) ) )
+                  irgb = NINT( 41 + 20.*LOG10(zchl) + 1.e-15 )
+                  zekb(ji,jj) = rkrgb(1,irgb)
+                  zekg(ji,jj) = rkrgb(2,irgb)
+                  zekr(ji,jj) = rkrgb(3,irgb)
+               END DO
+            END DO
+
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zc0 = ze0(ji,jj,jk-1) * EXP( - e3t_n(ji,jj,jk-1) * xsi0r       )
+                  zc1 = ze1(ji,jj,jk-1) * EXP( - e3t_n(ji,jj,jk-1) * zekb(ji,jj) )
+                  zc2 = ze2(ji,jj,jk-1) * EXP( - e3t_n(ji,jj,jk-1) * zekg(ji,jj) )
+                  zc3 = ze3(ji,jj,jk-1) * EXP( - e3t_n(ji,jj,jk-1) * zekr(ji,jj) )
+                  ze0(ji,jj,jk) = zc0
+                  ze1(ji,jj,jk) = zc1
+                  ze2(ji,jj,jk) = zc2
+                  ze3(ji,jj,jk) = zc3
+                  zea(ji,jj,jk) = ( zc0 + zc1 + zc2 + zc3 ) * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         DO jk = 1, nksr                     !* now qsr induced heat content
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  qsr_hc(ji,jj,jk) = r1_rau0_rcp * ( zea(ji,jj,jk) - zea(ji,jj,jk+1) )
+               END DO
+            END DO
+         END DO
+         !
+         DEALLOCATE( zekb , zekg , zekr , ze0 , ze1 , ze2 , ze3 , zea , zchl3d ) 
+         !
+      CASE( np_2BD  )            !==  2-bands fluxes  ==!
+         !
+         zz0 =        rn_abs   * r1_rau0_rcp      ! surface equi-partition in 2-bands
+         zz1 = ( 1. - rn_abs ) * r1_rau0_rcp
+         DO jk = 1, nksr                          ! solar heat absorbed at T-point in the top 400m 
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zc0 = zz0 * EXP( -gdepw_n(ji,jj,jk  )*xsi0r ) + zz1 * EXP( -gdepw_n(ji,jj,jk  )*xsi1r )
+                  zc1 = zz0 * EXP( -gdepw_n(ji,jj,jk+1)*xsi0r ) + zz1 * EXP( -gdepw_n(ji,jj,jk+1)*xsi1r )
+                  qsr_hc(ji,jj,jk) = qsr(ji,jj) * ( zc0 * wmask(ji,jj,jk) - zc1 * wmask(ji,jj,jk+1) ) 
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      !                          !-----------------------------!
+      DO jk = 1, nksr            !  update to the temp. trend  !
+         DO jj = 2, jpjm1        !-----------------------------!
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)   &
+                  &                 + z1_2 * ( qsr_hc_b(ji,jj,jk) + qsr_hc(ji,jj,jk) ) / e3t_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      ! sea-ice: store the 1st ocean level attenuation coefficient
+      DO jj = 2, jpjm1 
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            IF( qsr(ji,jj) /= 0._wp ) THEN   ;   fraqsr_1lev(ji,jj) = qsr_hc(ji,jj,1) / ( r1_rau0_rcp * qsr(ji,jj) )
+            ELSE                             ;   fraqsr_1lev(ji,jj) = 1._wp
+            ENDIF
+         END DO
+      END DO
+      CALL lbc_lnk( 'traqsr', fraqsr_1lev(:,:), 'T', 1._wp )
+      !
+      IF( iom_use('qsr3d') ) THEN      ! output the shortwave Radiation distribution
+         ALLOCATE( zetot(jpi,jpj,jpk) )
+         zetot(:,:,nksr+1:jpk) = 0._wp     ! below ~400m set to zero
+         DO jk = nksr, 1, -1
+            zetot(:,:,jk) = zetot(:,:,jk+1) + qsr_hc(:,:,jk) * rau0_rcp
+         END DO         
+         CALL iom_put( 'qsr3d', zetot )   ! 3D distribution of shortwave Radiation
+         DEALLOCATE( zetot ) 
+      ENDIF
+      !
+      IF( lrst_oce ) THEN     ! write in the ocean restart file
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'qsr_hc_b'   , qsr_hc     , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'fraqsr_1lev', fraqsr_1lev, ldxios = lwxios ) 
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+      IF( l_trdtra ) THEN     ! qsr tracers trends saved for diagnostics
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_qsr, ztrdt )
+         DEALLOCATE( ztrdt ) 
+      ENDIF
+      !                       ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' qsr  - Ta: ', mask1=tmask, clinfo3='tra-ta' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_qsr')
+      !
+   END SUBROUTINE tra_qsr
+
+
+   SUBROUTINE tra_qsr_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_qsr_init  ***
+      !!
+      !! ** Purpose :   Initialization for the penetrative solar radiation
+      !!
+      !! ** Method  :   The profile of solar radiation within the ocean is set
+      !!      from two length scale of penetration (rn_si0,rn_si1) and a ratio
+      !!      (rn_abs). These parameters are read in the namtra_qsr namelist. The
+      !!      default values correspond to clear water (type I in Jerlov' 
+      !!      (1968) classification.
+      !!         called by tra_qsr at the first timestep (nit000)
+      !!
+      !! ** Action  : - initialize rn_si0, rn_si1 and rn_abs
+      !!
+      !! Reference : Jerlov, N. G., 1968 Optical Oceanography, Elsevier, 194pp.
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk                  ! dummy loop indices
+      INTEGER  ::   ios, irgb, ierror, ioptio   ! local integer
+      REAL(wp) ::   zz0, zc0 , zc1, zcoef      ! local scalars
+      REAL(wp) ::   zz1, zc2 , zc3, zchl       !   -      -
+      !
+      CHARACTER(len=100) ::   cn_dir   ! Root directory for location of ssr files
+      TYPE(FLD_N)        ::   sn_chl   ! informations about the chlorofyl field to be read
+      !!
+      NAMELIST/namtra_qsr/  sn_chl, cn_dir, ln_qsr_rgb, ln_qsr_2bd, ln_qsr_bio,  &
+         &                  nn_chldta, rn_abs, rn_si0, rn_si1
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namtra_qsr in reference     namelist
+      READ  ( numnam_ref, namtra_qsr, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtra_qsr in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namtra_qsr in configuration namelist
+      READ  ( numnam_cfg, namtra_qsr, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtra_qsr in configuration namelist' )
+      IF(lwm) WRITE ( numond, namtra_qsr )
+      !
+      IF(lwp) THEN                ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'tra_qsr_init : penetration of the surface solar radiation'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtra_qsr : set the parameter of penetration'
+         WRITE(numout,*) '      RGB (Red-Green-Blue) light penetration       ln_qsr_rgb = ', ln_qsr_rgb
+         WRITE(numout,*) '      2 band               light penetration       ln_qsr_2bd = ', ln_qsr_2bd
+         WRITE(numout,*) '      bio-model            light penetration       ln_qsr_bio = ', ln_qsr_bio
+         WRITE(numout,*) '      RGB : Chl data (=1) or cst value (=0)        nn_chldta  = ', nn_chldta
+         WRITE(numout,*) '      RGB & 2 bands: fraction of light (rn_si1)    rn_abs     = ', rn_abs
+         WRITE(numout,*) '      RGB & 2 bands: shortess depth of extinction  rn_si0     = ', rn_si0
+         WRITE(numout,*) '      2 bands: longest depth of extinction         rn_si1     = ', rn_si1
+         WRITE(numout,*)
+      ENDIF
+      !
+      ioptio = 0                    ! Parameter control
+      IF( ln_qsr_rgb  )   ioptio = ioptio + 1
+      IF( ln_qsr_2bd  )   ioptio = ioptio + 1
+      IF( ln_qsr_bio  )   ioptio = ioptio + 1
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE type of light penetration in namelist namtra_qsr',  &
+         &                               ' 2 bands, 3 RGB bands or bio-model light penetration' )
+      !
+      IF( ln_qsr_rgb .AND. nn_chldta == 0 )   nqsr = np_RGB 
+      IF( ln_qsr_rgb .AND. nn_chldta == 1 )   nqsr = np_RGBc
+      IF( ln_qsr_2bd                      )   nqsr = np_2BD
+      IF( ln_qsr_bio                      )   nqsr = np_BIO
+      !
+      !                             ! Initialisation
+      xsi0r = 1._wp / rn_si0
+      xsi1r = 1._wp / rn_si1
+      !
+      SELECT CASE( nqsr )
+      !                               
+      CASE( np_RGB , np_RGBc )         !==  Red-Green-Blue light penetration  ==!
+         !                             
+         IF(lwp)   WRITE(numout,*) '   ==>>>   R-G-B   light penetration '
+         !
+         CALL trc_oce_rgb( rkrgb )                 ! tabulated attenuation coef.
+         !                                   
+         nksr = trc_oce_ext_lev( r_si2, 33._wp )   ! level of light extinction
+         !
+         IF(lwp) WRITE(numout,*) '        level of light extinction = ', nksr, ' ref depth = ', gdepw_1d(nksr+1), ' m'
+         !
+         IF( nqsr == np_RGBc ) THEN                ! Chl data : set sf_chl structure
+            IF(lwp) WRITE(numout,*) '   ==>>>   Chlorophyll read in a file'
+            ALLOCATE( sf_chl(1), STAT=ierror )
+            IF( ierror > 0 ) THEN
+               CALL ctl_stop( 'tra_qsr_init: unable to allocate sf_chl structure' )   ;   RETURN
+            ENDIF
+            ALLOCATE( sf_chl(1)%fnow(jpi,jpj,1)   )
+            IF( sn_chl%ln_tint )   ALLOCATE( sf_chl(1)%fdta(jpi,jpj,1,2) )
+            !                                        ! fill sf_chl with sn_chl and control print
+            CALL fld_fill( sf_chl, (/ sn_chl /), cn_dir, 'tra_qsr_init',   &
+               &           'Solar penetration function of read chlorophyll', 'namtra_qsr' , no_print )
+         ENDIF
+         IF( nqsr == np_RGB ) THEN                 ! constant Chl
+            IF(lwp) WRITE(numout,*) '   ==>>>   Constant Chlorophyll concentration = 0.05'
+         ENDIF
+         !
+      CASE( np_2BD )                   !==  2 bands light penetration  ==!
+         !
+         IF(lwp)  WRITE(numout,*) '   ==>>>   2 bands light penetration'
+         !
+         nksr = trc_oce_ext_lev( rn_si1, 100._wp )    ! level of light extinction
+         IF(lwp) WRITE(numout,*) '        level of light extinction = ', nksr, ' ref depth = ', gdepw_1d(nksr+1), ' m'
+         !
+      CASE( np_BIO )                   !==  BIO light penetration  ==!
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>>   bio-model light penetration'
+         IF( .NOT.lk_top )   CALL ctl_stop( 'No bio model : ln_qsr_bio = true impossible ' )
+         !                                   
+         CALL trc_oce_rgb( rkrgb )                 ! tabulated attenuation coef.
+         !                                   
+         nksr = trc_oce_ext_lev( r_si2, 33._wp )   ! level of light extinction
+         !
+         IF(lwp) WRITE(numout,*) '        level of light extinction = ', nksr, ' ref depth = ', gdepw_1d(nksr+1), ' m'
+         !
+      END SELECT
+      !
+      qsr_hc(:,:,:) = 0._wp     ! now qsr heat content set to zero where it will not be computed
+      !
+      ! 1st ocean level attenuation coefficient (used in sbcssm)
+      IF( iom_varid( numror, 'fraqsr_1lev', ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numror, jpdom_autoglo, 'fraqsr_1lev'  , fraqsr_1lev, ldxios = lrxios  )
+      ELSE
+         fraqsr_1lev(:,:) = 1._wp   ! default : no penetration
+      ENDIF
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('qsr_hc_b')
+         CALL iom_set_rstw_var_active('fraqsr_1lev')
+      ENDIF
+      !
+   END SUBROUTINE tra_qsr_init
+
+   !!======================================================================
+END MODULE traqsr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trasbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trasbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trasbc.F90	(revision 14097)
@@ -0,0 +1,276 @@
+MODULE trasbc
+   !!==============================================================================
+   !!                       ***  MODULE  trasbc  ***
+   !! Ocean active tracers:  surface boundary condition
+   !!==============================================================================
+   !! History :  OPA  !  1998-10  (G. Madec, G. Roullet, M. Imbard)  Original code
+   !!            8.2  !  2001-02  (D. Ludicone)  sea ice and free surface
+   !!  NEMO      1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            3.3  !  2010-04  (M. Leclair, G. Madec)  Forcing averaged over 2 time steps
+   !!             -   !  2010-09  (C. Ethe, G. Madec) Merge TRA-TRC
+   !!            3.6  !  2014-11  (P. Mathiot) isf melting forcing 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_sbc       : update the tracer trend at ocean surface
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE dom_oce        ! ocean space domain variables
+   USE phycst         ! physical constant
+   USE eosbn2         ! Equation Of State
+   USE sbcmod         ! ln_rnf  
+   USE sbcrnf         ! River runoff  
+   USE sbcisf         ! Ice shelf   
+   USE iscplini       ! Ice sheet coupling
+   USE traqsr         ! solar radiation penetration
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+#if defined key_asminc   
+   USE asminc         ! Assimilation increment
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE iom            ! xIOS server
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_sbc   ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_sbc ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_sbc  ***
+      !!                   
+      !! ** Purpose :   Compute the tracer surface boundary condition trend of
+      !!      (flux through the interface, concentration/dilution effect)
+      !!      and add it to the general trend of tracer equations.
+      !!
+      !! ** Method :   The (air+ice)-sea flux has two components: 
+      !!      (1) Fext, external forcing (i.e. flux through the (air+ice)-sea interface); 
+      !!      (2) Fwe , tracer carried with the water that is exchanged with air+ice. 
+      !!               The input forcing fields (emp, rnf, sfx, isf) contain Fext+Fwe,
+      !!             they are simply added to the tracer trend (tsa).
+      !!               In linear free surface case (ln_linssh=T), the volume of the
+      !!             ocean does not change with the water exchanges at the (air+ice)-sea
+      !!             interface. Therefore another term has to be added, to mimic the
+      !!             concentration/dilution effect associated with water exchanges.
+      !!
+      !! ** Action  : - Update tsa with the surface boundary condition trend 
+      !!              - send trends to trdtra module for further diagnostics(l_trdtra=T)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk, jn              ! dummy loop indices  
+      INTEGER  ::   ikt, ikb                    ! local integers
+      REAL(wp) ::   zfact, z1_e3t, zdep, ztim   ! local scalar
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::  ztrdt, ztrds
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_sbc')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_sbc : TRAcer Surface Boundary Condition'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      IF( l_trdtra ) THEN                    !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) ) 
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
+!!gm  This should be moved into sbcmod.F90 module ? (especially now that ln_traqsr is read in namsbc namelist)
+      IF( .NOT.ln_traqsr ) THEN     ! no solar radiation penetration
+         qns(:,:) = qns(:,:) + qsr(:,:)      ! total heat flux in qns
+         qsr(:,:) = 0._wp                     ! qsr set to zero
+      ENDIF
+
+      !----------------------------------------
+      !        EMP, SFX and QNS effects
+      !----------------------------------------
+      !                             !==  Set before sbc tracer content fields  ==!
+      IF( kt == nit000 ) THEN             !* 1st time-step
+         IF( ln_rstart .AND.    &               ! Restart: read in restart file
+              & iom_varid( numror, 'sbc_hc_b', ldstop = .FALSE. ) > 0 ) THEN
+            IF(lwp) WRITE(numout,*) '          nit000-1 sbc tracer content field read in the restart file'
+            zfact = 0.5_wp
+            sbc_tsc(:,:,:) = 0._wp
+            CALL iom_get( numror, jpdom_autoglo, 'sbc_hc_b', sbc_tsc_b(:,:,jp_tem), ldxios = lrxios )   ! before heat content sbc trend
+            CALL iom_get( numror, jpdom_autoglo, 'sbc_sc_b', sbc_tsc_b(:,:,jp_sal), ldxios = lrxios )   ! before salt content sbc trend
+         ELSE                                   ! No restart or restart not found: Euler forward time stepping
+            zfact = 1._wp
+            sbc_tsc(:,:,:) = 0._wp
+            sbc_tsc_b(:,:,:) = 0._wp
+         ENDIF
+      ELSE                                !* other time-steps: swap of forcing fields
+         zfact = 0.5_wp
+         sbc_tsc_b(:,:,:) = sbc_tsc(:,:,:)
+      ENDIF
+      !                             !==  Now sbc tracer content fields  ==!
+      DO jj = 2, jpj
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            sbc_tsc(ji,jj,jp_tem) = r1_rau0_rcp * qns(ji,jj)   ! non solar heat flux
+            sbc_tsc(ji,jj,jp_sal) = r1_rau0     * sfx(ji,jj)   ! salt flux due to freezing/melting
+         END DO
+      END DO
+      IF( ln_linssh ) THEN                !* linear free surface  
+         DO jj = 2, jpj                         !==>> add concentration/dilution effect due to constant volume cell
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               sbc_tsc(ji,jj,jp_tem) = sbc_tsc(ji,jj,jp_tem) + r1_rau0 * emp(ji,jj) * tsn(ji,jj,1,jp_tem)
+               sbc_tsc(ji,jj,jp_sal) = sbc_tsc(ji,jj,jp_sal) + r1_rau0 * emp(ji,jj) * tsn(ji,jj,1,jp_sal)
+            END DO
+         END DO                                 !==>> output c./d. term
+         IF( iom_use('emp_x_sst') )   CALL iom_put( "emp_x_sst", emp (:,:) * tsn(:,:,1,jp_tem) )
+         IF( iom_use('emp_x_sss') )   CALL iom_put( "emp_x_sss", emp (:,:) * tsn(:,:,1,jp_sal) )
+      ENDIF
+      !
+      DO jn = 1, jpts               !==  update tracer trend  ==!
+         DO jj = 2, jpj
+            DO ji = fs_2, fs_jpim1   ! vector opt.  
+               tsa(ji,jj,1,jn) = tsa(ji,jj,1,jn) + zfact * ( sbc_tsc_b(ji,jj,jn) + sbc_tsc(ji,jj,jn) ) / e3t_n(ji,jj,1)
+            END DO
+         END DO
+      END DO
+      !                  
+      IF( lrst_oce ) THEN           !==  write sbc_tsc in the ocean restart file  ==!
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'sbc_hc_b', sbc_tsc(:,:,jp_tem), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'sbc_sc_b', sbc_tsc(:,:,jp_sal), ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+      !----------------------------------------
+      !       Ice Shelf effects (ISF)
+      !     tbl treated as in Losh (2008) JGR
+      !----------------------------------------
+      !
+!!gm BUG ?   Why no differences between non-linear and linear free surface ?
+!!gm         probably taken into account in r1_hisf_tbl : to be verified
+      IF( ln_isf ) THEN
+         zfact = 0.5_wp
+         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
+               ! sign - because fwf sign of evapo (rnf sign of precip)
+               DO jk = ikt, ikb - 1
+               ! 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) )             &
+                     &           * r1_hisf_tbl(ji,jj)
+               END DO
+   
+               ! level partially include in ice shelf boundary layer 
+               ! 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) )             &
+                  &              * r1_hisf_tbl(ji,jj) * ralpha(ji,jj)
+
+            END DO
+         END DO
+      END IF
+      !
+      !----------------------------------------
+      !        River Runoff effects
+      !----------------------------------------
+      !
+      IF( ln_rnf ) THEN         ! input of heat and salt due to river runoff 
+         zfact = 0.5_wp
+         DO jj = 2, jpj 
+            DO ji = fs_2, fs_jpim1
+               IF( rnf(ji,jj) /= 0._wp ) THEN
+                  zdep = zfact / h_rnf(ji,jj)
+                  DO jk = 1, nk_rnf(ji,jj)
+                                        tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)                                 &
+                                           &                 +  ( rnf_tsc_b(ji,jj,jp_tem) + rnf_tsc(ji,jj,jp_tem) ) * zdep
+                     IF( ln_rnf_sal )   tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)                                 &
+                                           &                 +  ( rnf_tsc_b(ji,jj,jp_sal) + rnf_tsc(ji,jj,jp_sal) ) * zdep 
+                  END DO
+               ENDIF
+            END DO  
+         END DO  
+      ENDIF
+
+      IF( iom_use('rnf_x_sst') )   CALL iom_put( "rnf_x_sst", rnf*tsn(:,:,1,jp_tem) )   ! runoff term on sst
+      IF( iom_use('rnf_x_sss') )   CALL iom_put( "rnf_x_sss", rnf*tsn(:,:,1,jp_sal) )   ! runoff term on sss
+
+#if defined key_asminc
+      !
+      !----------------------------------------
+      !        Assmilation effects
+      !----------------------------------------
+      !
+      IF( ln_sshinc ) THEN         ! input of heat and salt due to assimilation
+      	 !
+         IF( ln_linssh ) THEN 
+            DO jj = 2, jpj 
+               DO ji = fs_2, fs_jpim1
+                  ztim = ssh_iau(ji,jj) / e3t_n(ji,jj,1)
+                  tsa(ji,jj,1,jp_tem) = tsa(ji,jj,1,jp_tem) + tsn(ji,jj,1,jp_tem) * ztim
+                  tsa(ji,jj,1,jp_sal) = tsa(ji,jj,1,jp_sal) + tsn(ji,jj,1,jp_sal) * ztim
+               END DO
+            END DO
+         ELSE
+            DO jj = 2, jpj 
+               DO ji = fs_2, fs_jpim1
+                  ztim = ssh_iau(ji,jj) / ( ht_n(ji,jj) + 1. - ssmask(ji, jj) )
+                  tsa(ji,jj,:,jp_tem) = tsa(ji,jj,:,jp_tem) + tsn(ji,jj,:,jp_tem) * ztim
+                  tsa(ji,jj,:,jp_sal) = tsa(ji,jj,:,jp_sal) + tsn(ji,jj,:,jp_sal) * ztim
+               END DO  
+            END DO  
+         ENDIF
+         !
+      ENDIF
+      !
+#endif
+      !
+      !----------------------------------------
+      !        Ice Sheet coupling imbalance correction to have conservation
+      !----------------------------------------
+      !
+      IF( ln_iscpl .AND. ln_hsb) THEN         ! input of heat and salt due to river runoff 
+         DO jk = 1,jpk
+            DO jj = 2, jpj 
+               DO ji = fs_2, fs_jpim1
+                  zdep = 1._wp / e3t_n(ji,jj,jk) 
+                  tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem) - htsc_iscpl(ji,jj,jk,jp_tem) * zdep
+                  tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal) - htsc_iscpl(ji,jj,jk,jp_sal) * zdep  
+               END DO  
+            END DO  
+         END DO
+      ENDIF
+
+      IF( l_trdtra )   THEN                      ! save the horizontal diffusive trends for further diagnostics
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_nsr, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_nsr, ztrds )
+         DEALLOCATE( ztrdt , ztrds ) 
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' sbc  - Ta: ', mask1=tmask,   &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_sbc')
+      !
+   END SUBROUTINE tra_sbc
+
+   !!======================================================================
+END MODULE trasbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trazdf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trazdf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/trazdf.F90	(revision 14097)
@@ -0,0 +1,271 @@
+MODULE trazdf
+   !!==============================================================================
+   !!                 ***  MODULE  trazdf  ***
+   !! Ocean active tracers:  vertical component of the tracer mixing trend
+   !!==============================================================================
+   !! History :  1.0  !  2005-11  (G. Madec)  Original code
+   !!            3.0  !  2008-01  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!            4.0  !  2017-06  (G. Madec)  remove explict time-stepping option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_zdf       : Update the tracer trend with the vertical diffusion
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables 
+   USE domvvl         ! variable volume
+   USE phycst         ! physical constant
+   USE zdf_oce        ! ocean vertical physics variables
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE ldftra         ! lateral diffusion: eddy diffusivity
+   USE ldfslp         ! lateral diffusion: iso-neutral slope 
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends: tracer trend manager
+   !
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_zdf       ! called by step.F90
+   PUBLIC   tra_zdf_imp   ! called by trczdf.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_zdf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_zdf  ***
+      !!
+      !! ** Purpose :   compute the vertical ocean tracer physics.
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   jk   ! Dummy loop indices
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds   ! 3D workspace
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_zdf')
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp)WRITE(numout,*)
+         IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
+         IF(lwp)WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;   r2dt =      rdt   ! at nit000, =   rdt (restarting with Euler time stepping)
+      ELSEIF( kt <= nit000 + 1           ) THEN   ;   r2dt = 2. * rdt   ! otherwise, = 2 rdt (leapfrog)
+      ENDIF
+      !
+      IF( l_trdtra )   THEN                  !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
+      !                                      !* compute lateral mixing trend and add it to the general trend
+      CALL tra_zdf_imp( kt, nit000, 'TRA', r2dt, tsb, tsa, jpts ) 
+
+!!gm WHY here !   and I don't like that !
+      ! DRAKKAR SSS control {
+      ! JMM avoid negative salinities near river outlet ! Ugly fix
+      ! JMM : restore negative salinities to small salinities:
+      WHERE( tsa(:,:,:,jp_sal) < 0._wp )   tsa(:,:,:,jp_sal) = 0.1_wp
+!!gm
+
+      IF( l_trdtra )   THEN                      ! save the vertical diffusive trends for further diagnostics
+         DO jk = 1, jpkm1
+            ztrdt(:,:,jk) = ( ( tsa(:,:,jk,jp_tem)*e3t_a(:,:,jk) - tsb(:,:,jk,jp_tem)*e3t_b(:,:,jk) ) &
+               &          / (e3t_n(:,:,jk)*r2dt) ) - ztrdt(:,:,jk)
+            ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal)*e3t_a(:,:,jk) - tsb(:,:,jk,jp_sal)*e3t_b(:,:,jk) ) &
+              &           / (e3t_n(:,:,jk)*r2dt) ) - ztrds(:,:,jk)
+         END DO
+!!gm this should be moved in trdtra.F90 and done on all trends
+         CALL lbc_lnk_multi( 'trazdf', ztrdt, 'T', 1. , ztrds, 'T', 1. )
+!!gm
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdf, ztrds )
+         DEALLOCATE( ztrdt , ztrds )
+      ENDIF
+      !                                          ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' zdf  - Ta: ', mask1=tmask,               &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_zdf')
+      !
+   END SUBROUTINE tra_zdf
+
+ 
+   SUBROUTINE tra_zdf_imp( kt, kit000, cdtype, p2dt, ptb, pta, kjpt ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_zdf_imp  ***
+      !!
+      !! ** Purpose :   Compute the after tracer through a implicit computation
+      !!     of the vertical tracer diffusion (including the vertical component 
+      !!     of lateral mixing (only for 2nd order operator, for fourth order 
+      !!     it is already computed and add to the general trend in traldf) 
+      !!
+      !! ** Method  :  The vertical diffusion of a tracer ,t , is given by:
+      !!          difft = dz( avt dz(t) ) = 1/e3t dk+1( avt/e3w dk(t) )
+      !!      It is computed using a backward time scheme (t=after field)
+      !!      which provide directly the after tracer field.
+      !!      If ln_zdfddm=T, use avs for salinity or for passive tracers
+      !!      Surface and bottom boundary conditions: no diffusive flux on
+      !!      both tracers (bottom, applied through the masked field avt).
+      !!      If iso-neutral mixing, add to avt the contribution due to lateral mixing.
+      !!
+      !! ** Action  : - pta  becomes the after tracer
+      !!---------------------------------------------------------------------
+      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)                             , INTENT(in   ) ::   p2dt     ! tracer time-step
+      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      ! in: tracer trend ; out: after tracer field
+      !
+      INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::  zrhs, zzwi, zzws ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zwi, zwt, zwd, zws
+      !!---------------------------------------------------------------------
+      !
+      !                                               ! ============= !
+      DO jn = 1, kjpt                                 !  tracer loop  !
+         !                                            ! ============= !
+         !  Matrix construction
+         ! --------------------
+         ! Build matrix if temperature or salinity (only in double diffusion case) or first passive tracer
+         !
+         IF(  ( cdtype == 'TRA' .AND. ( jn == jp_tem .OR. ( jn == jp_sal .AND. ln_zdfddm ) ) ) .OR.   &
+            & ( cdtype == 'TRC' .AND. jn == 1 )  )  THEN
+            !
+            ! vertical mixing coef.: avt for temperature, avs for salinity and passive tracers
+            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN   ;   zwt(:,:,2:jpk) = avt(:,:,2:jpk)
+            ELSE                                            ;   zwt(:,:,2:jpk) = avs(:,:,2:jpk)
+            ENDIF
+            zwt(:,:,1) = 0._wp
+            !
+            IF( l_ldfslp ) THEN            ! isoneutral diffusion: add the contribution 
+               IF( ln_traldf_msc  ) THEN     ! MSC iso-neutral operator 
+                  DO jk = 2, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           zwt(ji,jj,jk) = zwt(ji,jj,jk) + akz(ji,jj,jk)  
+                        END DO
+                     END DO
+                  END DO
+               ELSE                          ! standard or triad iso-neutral operator
+                  DO jk = 2, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           zwt(ji,jj,jk) = zwt(ji,jj,jk) + ah_wslp2(ji,jj,jk)
+                        END DO
+                     END DO
+                  END DO
+               ENDIF
+            ENDIF
+            !
+            ! Diagonal, lower (i), upper (s)  (including the bottom boundary condition since avt is masked)
+            IF( ln_zad_Aimp ) THEN         ! Adaptive implicit vertical advection
+               DO jk = 1, jpkm1
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1   ! vector opt. (ensure same order of calculation as below if wi=0.)
+                        zzwi = - p2dt * zwt(ji,jj,jk  ) / e3w_n(ji,jj,jk  )
+                        zzws = - p2dt * zwt(ji,jj,jk+1) / e3w_n(ji,jj,jk+1)
+                        zwd(ji,jj,jk) = e3t_a(ji,jj,jk) - zzwi - zzws   &
+                           &                 + p2dt * ( MAX( wi(ji,jj,jk  ) , 0._wp ) - MIN( wi(ji,jj,jk+1) , 0._wp ) )
+                        zwi(ji,jj,jk) = zzwi + p2dt *   MIN( wi(ji,jj,jk  ) , 0._wp )
+                        zws(ji,jj,jk) = zzws - p2dt *   MAX( wi(ji,jj,jk+1) , 0._wp )
+                    END DO
+                  END DO
+               END DO
+            ELSE
+               DO jk = 1, jpkm1
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1   ! vector opt.
+                        zwi(ji,jj,jk) = - p2dt * zwt(ji,jj,jk  ) / e3w_n(ji,jj,jk)
+                        zws(ji,jj,jk) = - p2dt * zwt(ji,jj,jk+1) / e3w_n(ji,jj,jk+1)
+                        zwd(ji,jj,jk) = e3t_a(ji,jj,jk) - zwi(ji,jj,jk) - zws(ji,jj,jk)
+                    END DO
+                  END DO
+               END DO
+            ENDIF
+            !
+            !! Matrix inversion from the first level
+            !!----------------------------------------------------------------------
+            !   solve m.x = y  where m is a tri diagonal matrix ( jpk*jpk )
+            !
+            !        ( zwd1 zws1   0    0    0  )( zwx1 ) ( zwy1 )
+            !        ( zwi2 zwd2 zws2   0    0  )( zwx2 ) ( zwy2 )
+            !        (  0   zwi3 zwd3 zws3   0  )( zwx3 )=( zwy3 )
+            !        (        ...               )( ...  ) ( ...  )
+            !        (  0    0    0   zwik zwdk )( zwxk ) ( zwyk )
+            !
+            !   m is decomposed in the product of an upper and lower triangular matrix.
+            !   The 3 diagonal terms are in 3d arrays: zwd, zws, zwi.
+            !   Suffices i,s and d indicate "inferior" (below diagonal), diagonal
+            !   and "superior" (above diagonal) components of the tridiagonal system.
+            !   The solution will be in the 4d array pta.
+            !   The 3d array zwt is used as a work space array.
+            !   En route to the solution pta is used a to evaluate the rhs and then 
+            !   used as a work space array: its value is modified.
+            !
+            DO jj = 2, jpjm1        !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1   (increasing k)
+               DO ji = fs_2, fs_jpim1            ! done one for all passive tracers (so included in the IF instruction)
+                  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)
+                  END DO
+               END DO
+            END DO
+            !
+         ENDIF 
+         !         
+         DO jj = 2, jpjm1           !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+            DO ji = fs_2, fs_jpim1
+               pta(ji,jj,1,jn) = e3t_b(ji,jj,1) * ptb(ji,jj,1,jn) + p2dt * e3t_n(ji,jj,1) * pta(ji,jj,1,jn)
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zrhs = e3t_b(ji,jj,jk) * ptb(ji,jj,jk,jn) + p2dt * e3t_n(ji,jj,jk) * pta(ji,jj,jk,jn)   ! zrhs=right hand side
+                  pta(ji,jj,jk,jn) = zrhs - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) * pta(ji,jj,jk-1,jn)
+               END DO
+            END DO
+         END DO
+         !
+         DO jj = 2, jpjm1           !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk   (result is the after tracer)
+            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
+                  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)
+               END DO
+            END DO
+         END DO
+         !                                            ! ================= !
+      END DO                                          !  end tracer loop  !
+      !                                               ! ================= !
+   END SUBROUTINE tra_zdf_imp
+
+   !!==============================================================================
+END MODULE trazdf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/zpshde.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/zpshde.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRA/zpshde.F90	(revision 14097)
@@ -0,0 +1,460 @@
+MODULE zpshde
+   !!======================================================================
+   !!                       ***  MODULE zpshde   ***
+   !! z-coordinate + partial step : Horizontal Derivative at ocean bottom level
+   !!======================================================================
+   !! History :  OPA  !  2002-04  (A. Bozec)  Original code
+   !!   NEMO     1.0  !  2002-08  (G. Madec E. Durand)  Optimization and Free form
+   !!             -   !  2004-03  (C. Ethe)  adapted for passive tracers
+   !!            3.3  !  2010-05  (C. Ethe, G. Madec)  merge TRC-TRA 
+   !!            3.6  !  2014-11  (P. Mathiot) Add zps_hde_isf (needed to open a cavity)
+   !!======================================================================
+   
+   !!----------------------------------------------------------------------
+   !!   zps_hde      :  Horizontal DErivative of T, S and rd at the last
+   !!                   ocean level (Z-coord. with Partial Steps)
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean: dynamics and tracers variables
+   USE dom_oce         ! domain: ocean variables
+   USE phycst          ! physical constants
+   USE eosbn2          ! ocean equation of state
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! MPP library
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zps_hde     ! routine called by step.F90
+   PUBLIC   zps_hde_isf ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zps_hde( kt, kjpt, pta, pgtu, pgtv,   &
+      &                          prd, pgru, pgrv    )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE zps_hde  ***
+      !!                    
+      !! ** Purpose :   Compute the horizontal derivative of T, S and rho
+      !!      at u- and v-points with a linear interpolation for z-coordinate
+      !!      with partial steps.
+      !!
+      !! ** Method  :   In z-coord with partial steps, scale factors on last 
+      !!      levels are different for each grid point, so that T, S and rd 
+      !!      points are not at the same depth as in z-coord. To have horizontal
+      !!      gradients again, we interpolate T and S at the good depth : 
+      !!      Linear interpolation of T, S   
+      !!         Computation of di(tb) and dj(tb) by vertical interpolation:
+      !!          di(t) = t~ - t(i,j,k) or t(i+1,j,k) - t~
+      !!          dj(t) = t~ - t(i,j,k) or t(i,j+1,k) - t~
+      !!         This formulation computes the two cases:
+      !!                 CASE 1                   CASE 2  
+      !!         k-1  ___ ___________   k-1   ___ ___________
+      !!                    Ti  T~                  T~  Ti+1
+      !!                  _____                        _____
+      !!         k        |   |Ti+1     k           Ti |   |
+      !!                  |   |____                ____|   |
+      !!              ___ |   |   |           ___  |   |   |
+      !!                  
+      !!      case 1->   e3w(i+1) >= e3w(i) ( and e3w(j+1) >= e3w(j) ) then
+      !!          t~ = t(i+1,j  ,k) + (e3w(i+1) - e3w(i)) * dk(Ti+1)/e3w(i+1)
+      !!        ( t~ = t(i  ,j+1,k) + (e3w(j+1) - e3w(j)) * dk(Tj+1)/e3w(j+1)  )
+      !!          or
+      !!      case 2->   e3w(i+1) <= e3w(i) ( and e3w(j+1) <= e3w(j) ) then
+      !!          t~ = t(i,j,k) + (e3w(i) - e3w(i+1)) * dk(Ti)/e3w(i )
+      !!        ( t~ = t(i,j,k) + (e3w(j) - e3w(j+1)) * dk(Tj)/e3w(j ) )
+      !!          Idem for di(s) and dj(s)          
+      !!
+      !!      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~
+      !!
+      !! ** Action  : compute for top interfaces
+      !!              - pgtu, pgtv: horizontal gradient of tracer at u- & v-points
+      !!              - pgru, pgrv: horizontal gradient of rho (if present) 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,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 (bottom)
+      !
+      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  ! local 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( ln_timing )   CALL timing_start( 'zps_hde')
+      !
+      pgtu(:,:,:) = 0._wp   ;   zti (:,:,:) = 0._wp   ;   zhi (:,:) = 0._wp
+      pgtv(:,:,:) = 0._wp   ;   ztj (:,:,:) = 0._wp   ;   zhj (:,:) = 0._wp
+      !
+      DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!
+         !
+         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
+!!gm BUG ? when applied to before fields, e3w_b should be used....
+               ze3wu = e3w_n(ji+1,jj  ,iku) - e3w_n(ji,jj,iku)
+               ze3wv = e3w_n(ji  ,jj+1,ikv) - e3w_n(ji,jj,ikv)
+               !
+               ! i- direction
+               IF( ze3wu >= 0._wp ) THEN      ! case 1
+                  zmaxu =  ze3wu / e3w_n(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) )
+                  ! gradient of  tracers
+                  pgtu(ji,jj,jn) = umask(ji,jj,1) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
+               ELSE                           ! case 2
+                  zmaxu = -ze3wu / e3w_n(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) )
+               ENDIF
+               !
+               ! j- direction
+               IF( ze3wv >= 0._wp ) THEN      ! case 1
+                  zmaxv =  ze3wv / e3w_n(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) )
+               ELSE                           ! case 2
+                  zmaxv =  -ze3wv / e3w_n(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
+            END DO
+         END DO
+      END DO
+      !
+      CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1. , pgtv(:,:,:), 'V', -1. )   ! Lateral boundary cond.
+      !                
+      IF( PRESENT( prd ) ) THEN    !==  horizontal derivative of density anomalies (rd)  ==!    (optional part)
+         pgru(:,:) = 0._wp
+         pgrv(:,:) = 0._wp                ! depth of the partial step level
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               iku = mbku(ji,jj)
+               ikv = mbkv(ji,jj)
+               ze3wu  = e3w_n(ji+1,jj  ,iku) - e3w_n(ji,jj,iku)
+               ze3wv  = e3w_n(ji  ,jj+1,ikv) - e3w_n(ji,jj,ikv)
+               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = gdept_n(ji  ,jj,iku)     ! i-direction: case 1
+               ELSE                        ;   zhi(ji,jj) = gdept_n(ji+1,jj,iku)     ! -     -      case 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = gdept_n(ji,jj  ,ikv)     ! j-direction: case 1
+               ELSE                        ;   zhj(ji,jj) = gdept_n(ji,jj+1,ikv)     ! -     -      case 2
+               ENDIF
+            END DO
+         END DO
+         !
+         CALL eos( zti, zhi, zri )        ! interpolated density from zti, ztj 
+         CALL eos( ztj, zhj, zrj )        ! at the partial step depth output in  zri, zrj 
+         !
+         DO jj = 1, jpjm1                 ! Gradient of density at the last level 
+            DO ji = 1, jpim1
+               iku = mbku(ji,jj)
+               ikv = mbkv(ji,jj)
+               ze3wu  = e3w_n(ji+1,jj  ,iku) - e3w_n(ji,jj,iku)
+               ze3wv  = e3w_n(ji  ,jj+1,ikv) - e3w_n(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
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1. , pgrv , 'V', -1. )   ! Lateral boundary conditions
+         !
+      END IF
+      !
+      IF( ln_timing )   CALL timing_stop( 'zps_hde')
+      !
+   END SUBROUTINE zps_hde
+
+
+   SUBROUTINE zps_hde_isf( kt, kjpt, pta, pgtu, pgtv, pgtui, pgtvi,  &
+      &                          prd, pgru, pgrv, pgrui, pgrvi )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE zps_hde_isf  ***
+      !!                    
+      !! ** Purpose :   Compute the horizontal derivative of T, S and rho
+      !!      at u- and v-points with a linear interpolation for z-coordinate
+      !!      with partial steps for top (ice shelf) and bottom.
+      !!
+      !! ** Method  :   In z-coord with partial steps, scale factors on last 
+      !!      levels are different for each grid point, so that T, S and rd 
+      !!      points are not at the same depth as in z-coord. To have horizontal
+      !!      gradients again, we interpolate T and S at the good depth :
+      !!      For the bottom case:
+      !!      Linear interpolation of T, S   
+      !!         Computation of di(tb) and dj(tb) by vertical interpolation:
+      !!          di(t) = t~ - t(i,j,k) or t(i+1,j,k) - t~
+      !!          dj(t) = t~ - t(i,j,k) or t(i,j+1,k) - t~
+      !!         This formulation computes the two cases:
+      !!                 CASE 1                   CASE 2  
+      !!         k-1  ___ ___________   k-1   ___ ___________
+      !!                    Ti  T~                  T~  Ti+1
+      !!                  _____                        _____
+      !!         k        |   |Ti+1     k           Ti |   |
+      !!                  |   |____                ____|   |
+      !!              ___ |   |   |           ___  |   |   |
+      !!                  
+      !!      case 1->   e3w(i+1) >= e3w(i) ( and e3w(j+1) >= e3w(j) ) then
+      !!          t~ = t(i+1,j  ,k) + (e3w(i+1) - e3w(i)) * dk(Ti+1)/e3w(i+1)
+      !!        ( t~ = t(i  ,j+1,k) + (e3w(j+1) - e3w(j)) * dk(Tj+1)/e3w(j+1)  )
+      !!          or
+      !!      case 2->   e3w(i+1) <= e3w(i) ( and e3w(j+1) <= e3w(j) ) then
+      !!          t~ = t(i,j,k) + (e3w(i) - e3w(i+1)) * dk(Ti)/e3w(i )
+      !!        ( t~ = t(i,j,k) + (e3w(j) - e3w(j+1)) * dk(Tj)/e3w(j ) )
+      !!          Idem for di(s) and dj(s)          
+      !!
+      !!      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~
+      !!
+      !!      For the top case (ice shelf): As for the bottom case but upside down
+      !!
+      !! ** Action  : compute for top and bottom interfaces
+      !!              - pgtu, pgtv, pgtui, pgtvi: horizontal gradient of tracer at u- & v-points
+      !!              - pgru, pgrv, pgrui, pgtvi: horizontal gradient of rho (if present) 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)           ::  pgtui, pgtvi ! 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 (bottom)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgrui, pgrvi ! hor. grad of prd at u- & v-pts (top)
+      !
+      INTEGER  ::   ji, jj, jn      ! Dummy loop indices
+      INTEGER  ::   iku, ikv, ikum1, ikvm1,ikup1, ikvp1   ! partial step level (ocean bottom level) at u- and v-points
+      REAL(wp) ::  ze3wu, ze3wv, zmaxu, zmaxv             ! 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( ln_timing )   CALL timing_start( 'zps_hde_isf')
+      !
+      pgtu (:,:,:) = 0._wp   ;   pgtv (:,:,:) =0._wp
+      pgtui(:,:,:) = 0._wp   ;   pgtvi(:,:,:) =0._wp
+      zti  (:,:,:) = 0._wp   ;   ztj  (:,:,:) =0._wp
+      zhi  (:,:  ) = 0._wp   ;   zhj  (:,:  ) =0._wp
+      !
+      DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!
+         !
+         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 = gdept_n(ji+1,jj,iku) - gdept_n(ji,jj,iku)
+               ze3wv = gdept_n(ji,jj+1,ikv) - gdept_n(ji,jj,ikv)
+               !
+               ! i- direction
+               IF( ze3wu >= 0._wp ) THEN      ! case 1
+                  zmaxu =  ze3wu / e3w_n(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) )
+                  ! gradient of  tracers
+                  pgtu(ji,jj,jn) = ssumask(ji,jj) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
+               ELSE                           ! case 2
+                  zmaxu = -ze3wu / e3w_n(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) = ssumask(ji,jj) * ( pta(ji+1,jj,iku,jn) - zti(ji,jj,jn) )
+               ENDIF
+               !
+               ! j- direction
+               IF( ze3wv >= 0._wp ) THEN      ! case 1
+                  zmaxv =  ze3wv / e3w_n(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) = ssvmask(ji,jj) * ( ztj(ji,jj,jn) - pta(ji,jj,ikv,jn) )
+               ELSE                           ! case 2
+                  zmaxv =  -ze3wv / e3w_n(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) = ssvmask(ji,jj) * ( pta(ji,jj+1,ikv,jn) - ztj(ji,jj,jn) )
+               ENDIF
+
+            END DO
+         END DO
+      END DO
+      !
+      CALL lbc_lnk_multi( 'zpshde', pgtu(:,:,:), 'U', -1. , pgtv(:,:,:), 'V', -1. )   ! Lateral boundary cond.
+
+      ! horizontal derivative of density anomalies (rd)
+      IF( PRESENT( prd ) ) THEN         ! depth of the partial step level
+         pgru(:,:)=0.0_wp   ; pgrv(:,:)=0.0_wp ; 
+         !
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+
+               iku = mbku(ji,jj)
+               ikv = mbkv(ji,jj)
+               ze3wu = gdept_n(ji+1,jj,iku) - gdept_n(ji,jj,iku)
+               ze3wv = gdept_n(ji,jj+1,ikv) - gdept_n(ji,jj,ikv)
+               !
+               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = gdept_n(ji  ,jj,iku)    ! i-direction: case 1
+               ELSE                        ;   zhi(ji,jj) = gdept_n(ji+1,jj,iku)    ! -     -      case 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = gdept_n(ji,jj  ,ikv)    ! j-direction: case 1
+               ELSE                        ;   zhj(ji,jj) = gdept_n(ji,jj+1,ikv)    ! -     -      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 )
+
+         DO jj = 1, jpjm1                 ! Gradient of density at the last level 
+            DO ji = 1, jpim1
+               iku = mbku(ji,jj)
+               ikv = mbkv(ji,jj)
+               ze3wu = gdept_n(ji+1,jj,iku) - gdept_n(ji,jj,iku)
+               ze3wv = gdept_n(ji,jj+1,ikv) - gdept_n(ji,jj,ikv)
+
+               IF( ze3wu >= 0._wp ) THEN   ;   pgru(ji,jj) = ssumask(ji,jj) * ( zri(ji  ,jj    ) - prd(ji,jj,iku) )   ! i: 1
+               ELSE                        ;   pgru(ji,jj) = ssumask(ji,jj) * ( prd(ji+1,jj,iku) - zri(ji,jj    ) )   ! i: 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN   ;   pgrv(ji,jj) = ssvmask(ji,jj) * ( zrj(ji,jj      ) - prd(ji,jj,ikv) )   ! j: 1
+               ELSE                        ;   pgrv(ji,jj) = ssvmask(ji,jj) * ( prd(ji,jj+1,ikv) - zrj(ji,jj    ) )   ! j: 2
+               ENDIF
+
+            END DO
+         END DO
+
+         CALL lbc_lnk_multi( 'zpshde', pgru , 'U', -1. , pgrv , 'V', -1. )   ! Lateral boundary conditions
+         !
+      END IF
+      !
+      !     !==  (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  =  gdept_n(ji,jj,iku) - gdept_n(ji+1,jj,iku)
+               ze3wv  =  gdept_n(ji,jj,ikv) - gdept_n(ji,jj+1,ikv) 
+
+               ! i- direction
+               IF( ze3wu >= 0._wp ) THEN      ! case 1
+                  zmaxu = ze3wu / e3w_n(ji+1,jj,ikup1)
+                  ! interpolated values of tracers
+                  zti(ji,jj,jn) = pta(ji+1,jj,iku,jn) + zmaxu * ( pta(ji+1,jj,ikup1,jn) - pta(ji+1,jj,iku,jn) )
+                  ! gradient of tracers
+                  pgtui(ji,jj,jn) = ssumask(ji,jj) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
+               ELSE                           ! case 2
+                  zmaxu = - ze3wu / e3w_n(ji,jj,ikup1)
+                  ! interpolated values of tracers
+                  zti(ji,jj,jn) = pta(ji,jj,iku,jn) + zmaxu * ( pta(ji,jj,ikup1,jn) - pta(ji,jj,iku,jn) )
+                  ! gradient of  tracers
+                  pgtui(ji,jj,jn) = ssumask(ji,jj) * ( pta(ji+1,jj,iku,jn) - zti(ji,jj,jn) )
+               ENDIF
+               !
+               ! j- direction
+               IF( ze3wv >= 0._wp ) THEN      ! case 1
+                  zmaxv =  ze3wv / e3w_n(ji,jj+1,ikvp1)
+                  ! interpolated values of tracers
+                  ztj(ji,jj,jn) = pta(ji,jj+1,ikv,jn) + zmaxv * ( pta(ji,jj+1,ikvp1,jn) - pta(ji,jj+1,ikv,jn) )
+                  ! gradient of tracers
+                  pgtvi(ji,jj,jn) = ssvmask(ji,jj) * ( ztj(ji,jj,jn) - pta(ji,jj,ikv,jn) )
+               ELSE                           ! case 2
+                  zmaxv =  - ze3wv / e3w_n(ji,jj,ikvp1)
+                  ! interpolated values of tracers
+                  ztj(ji,jj,jn) = pta(ji,jj,ikv,jn) + zmaxv * ( pta(ji,jj,ikvp1,jn) - pta(ji,jj,ikv,jn) )
+                  ! gradient of tracers
+                  pgtvi(ji,jj,jn) = ssvmask(ji,jj) * ( pta(ji,jj+1,ikv,jn) - ztj(ji,jj,jn) )
+               ENDIF
+
+            END DO
+         END DO
+         !
+      END DO
+      CALL lbc_lnk_multi( 'zpshde', pgtui(:,:,:), 'U', -1. , pgtvi(:,:,:), 'V', -1. )   ! Lateral boundary cond.
+
+      IF( PRESENT( prd ) ) THEN    !==  horizontal derivative of density anomalies (rd)  ==!    (optional part)
+         !
+         pgrui(:,:)  =0.0_wp; pgrvi(:,:)  =0.0_wp;
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+
+               iku = miku(ji,jj)
+               ikv = mikv(ji,jj)
+               ze3wu  =  gdept_n(ji,jj,iku) - gdept_n(ji+1,jj,iku)
+               ze3wv  =  gdept_n(ji,jj,ikv) - gdept_n(ji,jj+1,ikv) 
+               !
+               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = gdept_n(ji  ,jj,iku)    ! i-direction: case 1
+               ELSE                        ;   zhi(ji,jj) = gdept_n(ji+1,jj,iku)    ! -     -      case 2
+               ENDIF
+
+               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = gdept_n(ji,jj  ,ikv)    ! j-direction: case 1
+               ELSE                        ;   zhj(ji,jj) = gdept_n(ji,jj+1,ikv)    ! -     -      case 2
+               ENDIF
+
+            END DO
+         END DO
+         !
+         CALL eos( zti, zhi, zri )        ! interpolated density from zti, ztj 
+         CALL eos( ztj, zhj, zrj )        ! at the partial step depth output in  zri, zrj 
+         !
+         DO jj = 1, jpjm1                 ! Gradient of density at the last level 
+            DO ji = 1, jpim1
+               iku = miku(ji,jj) 
+               ikv = mikv(ji,jj) 
+               ze3wu  =  gdept_n(ji,jj,iku) - gdept_n(ji+1,jj,iku)
+               ze3wv  =  gdept_n(ji,jj,ikv) - gdept_n(ji,jj+1,ikv) 
+
+               IF( ze3wu >= 0._wp ) THEN ; pgrui(ji,jj) = ssumask(ji,jj) * ( zri(ji  ,jj      ) - prd(ji,jj,iku) ) ! i: 1
+               ELSE                      ; pgrui(ji,jj) = ssumask(ji,jj) * ( prd(ji+1,jj  ,iku) - zri(ji,jj    ) ) ! i: 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN ; pgrvi(ji,jj) = ssvmask(ji,jj) * ( zrj(ji  ,jj      ) - prd(ji,jj,ikv) ) ! j: 1
+               ELSE                      ; pgrvi(ji,jj) = ssvmask(ji,jj) * ( prd(ji  ,jj+1,ikv) - zrj(ji,jj    ) ) ! j: 2
+               ENDIF
+
+            END DO
+         END DO
+         CALL lbc_lnk_multi( 'zpshde', pgrui, 'U', -1. , pgrvi, 'V', -1. )   ! Lateral boundary conditions
+         !
+      END IF  
+      !
+      IF( ln_timing )   CALL timing_stop( 'zps_hde_isf')
+      !
+   END SUBROUTINE zps_hde_isf
+
+   !!======================================================================
+END MODULE zpshde
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trd_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trd_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trd_oce.F90	(revision 14097)
@@ -0,0 +1,82 @@
+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  = 20     !: 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_totad  =  5   !: total         advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_ldf  =  6     !: lateral       diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdf  =  7     !: vertical      diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdfp =  8     !: "PURE" vert.  diffusion (ln_traldf_iso=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_evd  =  9     !: EVD term (convection)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbc  = 10     !: Bottom Boundary Condition (geoth. heating) 
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbl  = 11     !: Bottom Boundary Layer (diffusive and/or advective)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_npc  = 12     !: non-penetrative convection treatment
+   INTEGER, PUBLIC, PARAMETER ::   jptra_dmp  = 13     !: internal restoring (damping)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_qsr  = 14     !: penetrative solar radiation
+   INTEGER, PUBLIC, PARAMETER ::   jptra_nsr  = 15     !: non solar radiation / C/D on salinity  (+runoff if ln_rnf=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_atf  = 16     !: Asselin time filter
+   INTEGER, PUBLIC, PARAMETER ::   jptra_tot  = 17     !: Model total trend
+   !
+   !                                                  !!!* Passive tracers trends indices (use if "key_top" defined)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_sms  = 18     !: sources m. sinks
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radn = 19     !: corr. trn<0 in trcrad
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radb = 20     !: corr. trb<0 in trcrad (like atf)
+   !
+   !                                                  !!!* Momentum trends indices
+   INTEGER, PUBLIC, PARAMETER ::   jptot_dyn  = 13     !: 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_drgimp=.TRUE.)
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_ken  = 13     !: use for calculation of KE
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trd_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trddyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trddyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trddyn.F90	(revision 14097)
@@ -0,0 +1,183 @@
+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 phycst         ! physical constants
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdf_oce        ! ocean vertical physics: variables
+!!gm   USE zdfdrg         ! ocean vertical physics: bottom friction
+   USE trd_oce        ! trends: ocean variables
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trd_dyn        ! called by all dynXXX modules
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+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), ALLOCATABLE, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
+      REAL(wp), ALLOCATABLE, 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_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 )
+                              ALLOCATE( z3dx(jpi,jpj,jpk) , z3dy(jpi,jpj,jpk) )
+                              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_multi( 'trddyn', z3dx, 'U', -1., z3dy, 'V', -1. )
+                              CALL iom_put( "utrd_udx", z3dx  )
+                              CALL iom_put( "vtrd_vdy", z3dy  )
+                              DEALLOCATE( 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
+                              ALLOCATE( z2dx(jpi,jpj) , z2dy(jpi,jpj) )
+                              z2dx(:,:) = ( utau_b(:,:) + utau(:,:) ) / ( e3u_n(:,:,1) * rau0 )
+                              z2dy(:,:) = ( vtau_b(:,:) + vtau(:,:) ) / ( e3v_n(:,:,1) * rau0 )
+                              CALL iom_put( "utrd_tau", z2dx )
+                              CALL iom_put( "vtrd_tau", z2dy )
+                              DEALLOCATE( z2dx , z2dy )
+!!gm  to be changed : computation should be done in dynzdf.F90
+!!gm                + missing the top friction 
+!                              !                                    ! bottom stress tends (implicit case)
+!                              IF( ln_drgimp ) THEN
+!                                 ALLOCATE( z3dx(jpi,jpj,jpk) , z3dy(jpi,jpj,jpk) )
+!                             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) = 0.5 * ( rCdU_bot(ji+1,jj) + rCdU_bot(ji,jj) ) & 
+!                                               &         * un(ji,jj,ikbu) / e3u_n(ji,jj,ikbu)
+!                                          z3dy(ji,jj,jk) = 0.5 * ( rCdU_bot(ji,jj+1) + rCdU_bot(ji,jj) ) &
+!                                               &         * vn(ji,jj,ikbv) / e3v_n(ji,jj,ikbv)
+!                                    END DO
+!                                 END DO
+!                              END DO
+!                              CALL lbc_lnk_multi( 'trddyn', z3dx, 'U', -1., z3dy, 'V', -1. )
+!                              CALL iom_put( "utrd_bfr", z3dx )
+!                              CALL iom_put( "vtrd_bfr", z3dy )
+!                                 DEALLOCATE( z3dx , z3dy )
+!                              ENDIF
+!!gm end
+      CASE( jpdyn_bfr )       ! called if ln_drgimp=F
+                              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 )
+      END SELECT
+      !
+   END SUBROUTINE trd_dyn_iom
+
+   !!======================================================================
+END MODULE trddyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdglo.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdglo.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdglo.F90	(revision 14097)
@@ -0,0 +1,559 @@
+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         ! lateral diffusion: eddy diffusivity & EIV coeff.
+   USE ldfdyn         ! ocean dynamics: lateral physics
+   USE zdf_oce        ! ocean vertical physics
+!!gm   USE zdfdrg         ! ocean vertical physics: 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
+
+   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 "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+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), DIMENSION(jpi,jpj)  :: ztswu, ztswv, z2dx, z2dy   ! 2D workspace 
+      !!----------------------------------------------------------------------
+      !
+      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) * e3t_n(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( ln_linssh .AND. ktrd == jptra_zad ) THEN  
+               tmo(jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_tem) * e1e2t(:,:) * tmask_i(:,:) )
+               smo(jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_sal) * e1e2t(:,:) * tmask_i(:,:)  )
+               t2 (jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_tem) * tsn(:,:,1,jp_tem) * e1e2t(:,:) * tmask_i(:,:)  )
+               s2 (jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_sal) * tsn(:,:,1,jp_sal) * e1e2t(:,:) * tmask_i(:,:)  )
+            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)   &
+                        &                                     * e1e2u  (ji,jj) * e3u_n(ji,jj,jk)
+                     zvs = ptrdy(ji,jj,jk) * tmask_i(ji,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)   &
+                        &                                     * e1e2v  (ji,jj) * e3u_n(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       * e1e2u(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       * e1e2v(ji,jj)
+                     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
+            !                       
+!!gm  miss placed calculation   ===>>>> to be done in dynzdf.F90
+!            IF( ktrd == jpdyn_atf ) THEN     ! last trend (asselin time filter)
+!               !
+!               IF( ln_drgimp ) THEN                   ! implicit drag 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 = 0.5*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) * un(ji,jj,ikbu) * e1e2u(ji,jj)
+!                        zvs = 0.5*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) * vn(ji,jj,ikbv) * e1e2v(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
+!
+!!gm top drag case is missing 
+!
+!               ! 
+!               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
+!!gm end
+            !
+         END SELECT
+         !
+      ENDIF
+      !
+   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), DIMENSION(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) * e3u_n(ji,jj,jk) * un(ji,jj,jk) * ( rhop(ji,jj,jk) + rhop(ji+1,jj,jk) )
+                  zky(ji,jj,jk) = zcof * e1v(ji,jj) * e3v_n(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) * e3t_n(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) * gdept_n(:,:,jk) * e1e2t(:,:) * e3t_n(:,:,jk) )
+         END DO
+         peke = grav * peke
+
+         ! I.3 Sums over the global domain
+         ! ---------------------------------
+         IF( lk_mpp ) THEN
+            CALL mpp_sum( 'trdglo', peke )
+            CALL mpp_sum( 'trdglo', umo , jptot_dyn )
+            CALL mpp_sum( 'trdglo', vmo , jptot_dyn )
+            CALL mpp_sum( 'trdglo', 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
+!!gm            IF( ln_drgimp )   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
+!!gm            IF( ln_drgimp )   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
+      !
+   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( 'trdglo', tmo, jptot_tra )   
+            CALL mpp_sum( 'trdglo', smo, jptot_tra )
+            CALL mpp_sum( 'trdglo', t2 , jptot_tra )
+            CALL mpp_sum( 'trdglo', 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(:,:) * e3t_n(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:) )
+      END DO
+      CALL mpp_sum( 'trdglo', 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) * e3u_n(ji,jj,jk) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)
+               tvolv = tvolv + e1v(ji,jj) * e2v(ji,jj) * e3v_n(ji,jj,jk) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      CALL mpp_sum( 'trdglo', tvolu )   ! sums over the global domain
+      CALL mpp_sum( 'trdglo', 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdini.F90	(revision 14097)
@@ -0,0 +1,107 @@
+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 "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+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' )
+      !
+      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' )
+      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( .NOT.ln_linssh .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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdken.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdken.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdken.F90	(revision 14097)
@@ -0,0 +1,256 @@
+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 phycst         ! physical constants
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdf_oce        ! ocean vertical physics variables
+!!gm   USE zdfdrg         ! ocean vertical physics: bottom friction
+   USE ldftra         ! ocean active tracers lateral physics
+   USE trd_oce        ! trends: ocean variables
+   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 ldfslp         ! Isopycnal slopes
+
+   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 "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+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 )
+      !
+      CALL mpp_sum ( 'trdken', trd_ken_alloc )
+      IF( trd_ken_alloc /= 0 )   CALL ctl_stop( 'STOP', '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_drgimp=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), DIMENSION(:,:), ALLOCATABLE ::   z2dx, z2dy, zke2d   ! 2D workspace 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)      ::   zke                 ! 3D workspace 
+      !!----------------------------------------------------------------------
+      !
+      CALL lbc_lnk_multi( 'trdken', putrd, 'U', -1. , pvtrd, 'V', -1. )      ! lateral boundary conditions
+      !
+      nkstp = kt
+      DO jk = 1, jpkm1
+         bu   (:,:,jk) =    e1e2u(:,:) * e3u_n(:,:,jk)
+         bv   (:,:,jk) =    e1e2v(:,:) * e3v_n(:,:,jk)
+         r1_bt(:,:,jk) = r1_e1e2t(:,:) / e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+      !
+      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_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
+                                 ALLOCATE( z2dx(jpi,jpj) , z2dy(jpi,jpj) , zke2d(jpi,jpj) )
+                           z2dx(:,:) = un(:,:,1) * ( utau_b(:,:) + utau(:,:) ) * e1e2u(:,:) * umask(:,:,1)
+                           z2dy(:,:) = vn(:,:,1) * ( vtau_b(:,:) + vtau(:,:) ) * e1e2v(:,:) * vmask(:,:,1)
+                           zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
+                           DO jj = 2, jpj
+                              DO ji = 2, jpi
+                                 zke2d(ji,jj) = r1_rau0 * 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 )  ! 
+                                 DEALLOCATE( 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_drgimp=F otherwise the bottom stress as to be recomputed at the end of the computation....
+!         IF(.NOT. ln_drgimp) 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_drgimp ) 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) / e3u_n(ji,jj,ikbu)
+!                  z2dy(ji,jj) = un(ji,jj,ikbu) * bfrva(ji,jj) * vn(ji,jj,ikbv) / e3v_n(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
+      !
+   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(:,:,:), INTENT(  out) ::   pconv   ! 
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   iku, ikv     ! local integers
+      REAL(wp) ::   zcoef        ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zconv  ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      ! 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) * e3w_n(:,:,1)
+
+      ! interior value (2=<jk=<jpkm1)
+      DO jk = 2, jpk
+         zconv(:,:,jk) = zcoef * ( rhd(:,:,jk) + rhd(:,:,jk-1) ) * wn(:,:,jk) * e3w_n(:,:,jk)
+      END DO
+
+      ! conv value on T-point
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcoef = 0.5_wp / e3t_n(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
+      !
+   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')
+      !
+   END SUBROUTINE trd_ken_init
+
+   !!======================================================================
+END MODULE trdken
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl.F90	(revision 14097)
@@ -0,0 +1,869 @@
+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          ! lateral diffusion: eddy diffusivity & EIV coeff.
+   USE zdf_oce         ! ocean vertical physics
+   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 lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE trdmxl_rst      ! restart for diagnosing the ML trends
+   !
+   USE in_out_manager  ! I/O manager
+   USE ioipsl          ! NetCDF library
+   USE prtctl          ! Print control
+   USE restart         ! for lrst_oce
+   USE lib_mpp         ! MPP library
+   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                   
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_mxl_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ndextrd1(jpi*jpj) , STAT=trd_mxl_alloc )
+      !
+      CALL mpp_sum ( 'trdmxl', 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) = e3t_n(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_multi( 'trdmxl', tmltrd(:,:,jl), 'T', 1. , 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), DIMENSION(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
+      !
+   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 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_ICE, 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), DIMENSION(jpi,jpj  )   ::  ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf
+      REAL(wp), DIMENSION(jpi,jpj  )   ::  ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2  
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  ztmltrd2, zsmltrd2   ! only needed for mean diagnostics
+      !!----------------------------------------------------------------------
+  
+      ! ======================================================================
+      ! 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)
+            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask)
+            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask)
+         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)
+            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask)
+            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask)
+         ELSE
+            WRITE(numout,*) '             restart from kt == nit000 = ', nit000
+            CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask)
+            CALL prt_ctl(tab2d_1=hmxlbn         , clinfo1=' hmxlbn          -  : ', mask1=tmask)
+            CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask)
+            CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask)
+            CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, 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_multi( 'trdmxl', ztmltot , 'T', 1., zsmltot , 'T', 1., &
+                  &          ztmlres , 'T', 1., zsmlres , 'T', 1., &
+                  &          ztmlatf , 'T', 1., 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_multi( 'trdmxl', ztmltot2, 'T', 1., zsmltot2, 'T', 1., &
+                  &          ztmlres2, 'T', 1., zsmlres2, 'T', 1. )
+         !
+         CALL lbc_lnk_multi( 'trdmxl', ztmltrd2(:,:,:), 'T', 1., zsmltrd2(:,:,:), 'T', 1. ) ! /  in the NetCDF trends file
+         
+         ! 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)
+               CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask)
+               CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask)
+            ELSE
+               CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask)
+               CALL prt_ctl(tab2d_1=hmxlbn         , clinfo1=' hmxlbn          -  : ', mask1=tmask)
+               CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask)
+               CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask)
+               CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, 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 ) 
+
+      !
+   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' )
+
+      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' )
+      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(ctmp1,*) '                Your nitend parameter, nitend = ', nitend
+         WRITE(ctmp2,*) '                is no multiple of the trends diagnostics frequency        '
+         WRITE(ctmp3,*) '                          you defined, nn_trd   = ', nn_trd
+         WRITE(ctmp4,*) '                This will not allow you to restart from this simulation.  '
+         WRITE(ctmp5,*) '                You should reconsider this choice.                        ' 
+         WRITE(ctmp6,*) 
+         WRITE(ctmp7,*) '                N.B. the nitend parameter is also constrained to be a     '
+         WRITE(ctmp8,*) '                     multiple of the nn_fsbc parameter '
+         CALL ctl_stop( ctmp1, ctmp2, ctmp3, ctmp4, ctmp5, ctmp6, ctmp7, ctmp8 )
+      END IF
+
+      !                                   ! 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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_oce.F90	(revision 14097)
@@ -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 = 12      !: 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  !: ! iso-neutral diffusion:"pure" vertical diffusion
+   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/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+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 )
+      CALL mpp_sum ( 'trdmxl_oce', trdmxl_oce_alloc )
+      IF( trdmxl_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'trdmxl_oce_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION trdmxl_oce_alloc
+
+   !!======================================================================
+END MODULE trdmxl_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_rst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_rst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdmxl_rst.F90	(revision 14097)
@@ -0,0 +1,190 @@
+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/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!---------------------------------------------------------------------------------
+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   ! output restart file name
+      CHARACTER(LEN=256)  ::   clpath   ! full path to restart file
+      !!--------------------------------------------------------------------------------
+
+      IF( .NOT. ln_rst_list .AND. nn_stock == -1 )   RETURN   ! we will never do any restart
+
+      ! 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. nn_stock == 1 .OR. ( kt == nitend .AND. MOD( nitend - 1, nn_stock ) == 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)
+         clpath = TRIM(cn_ocerst_outdir)
+         IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '             open ocean restart_mxl NetCDF file: '//clname
+            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( TRIM(clpath)//TRIM(clname), nummxlw, ldwrt = .TRUE. )
+      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
+      LOGICAL ::   llok
+      CHARACTER(LEN=256)  ::   clpath   ! full path to restart file
+      !!-----------------------------------------------------------------------------
+
+      IF(lwp)  THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_rst_read : read the NetCDF mixed layer trend restart file'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
+      ENDIF
+
+      clpath = TRIM(cn_ocerst_indir)
+      IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+      CALL iom_open( TRIM(clpath)//TRIM(cn_trdrst_in), inum ) 
+
+      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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdpen.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdpen.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdpen.F90	(revision 14097)
@@ -0,0 +1,155 @@
+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         ! lateral diffusion: eddy diffusivity & EIV coeff.
+   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
+
+   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 "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_pen_alloc()
+      !!---------------------------------------------------------------------
+      !!                  ***  FUNCTION trd_tra_alloc  ***
+      !!---------------------------------------------------------------------
+      ALLOCATE( rab_pe(jpi,jpj,jpk,jpts) , STAT= trd_pen_alloc )
+      !
+      CALL mpp_sum ( 'trdpen', trd_pen_alloc )
+      IF( trd_pen_alloc /= 0 )   CALL ctl_stop( 'STOP',  '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), ALLOCATABLE, DIMENSION(:,:)      ::   z2d            ! 2D workspace 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)           ::   zpe            ! 3D workspace 
+      !!----------------------------------------------------------------------
+      !
+      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( ln_linssh ) THEN                   ! cst volume : adv flux through z=0 surface
+                                   ALLOCATE( z2d(jpi,jpj) )
+                                   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)    &
+                                     & ) / e3t_n(:,:,1)
+                                   CALL iom_put( "petrd_sad" , z2d )
+                                   DEALLOCATE( 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( ln_linssh ) THEN                   ! cst volume : ssh term (otherwise include in e3t variation)
+                                !   ALLOCATE( z2d(jpi,jpj) )
+                                !   z2d(:,:) = ( ssha(:,:) - sshb(:,:) )                 &
+                                !      &     * (   dPE_dt(:,:,1) * tsn(:,:,1,jp_tem)    &
+                                !      &         + dPE_ds(:,:,1) * tsn(:,:,1,jp_sal)  ) / ( e3t_n(:,:,1) * pdt )
+                                !   CALL iom_put( "petrd_sad" , z2d )
+                                !   DEALLOCATE( z2d )
+                                !ENDIF
+         !
+      END SELECT
+      !
+      !
+   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( .NOT.ln_linssh )   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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtra.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtra.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtra.F90	(revision 14097)
@@ -0,0 +1,370 @@
+MODULE trdtra
+   !!======================================================================
+   !!                       ***  MODULE  trdtra  ***
+   !! Ocean diagnostics:  ocean tracers trends pre-processing
+   !!=====================================================================
+   !! 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         ! ocean active tracers lateral physics
+   USE ldfslp
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_tra   ! called by all tra_... modules
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   trdtx, trdty, trdt   ! use to store the temperature trends
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   avt_evd  ! store avt_evd to calculate EVD trend
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_tra_alloc()
+      !!---------------------------------------------------------------------
+      !!                  ***  FUNCTION trd_tra_alloc  ***
+      !!---------------------------------------------------------------------
+      ALLOCATE( trdtx(jpi,jpj,jpk) , trdty(jpi,jpj,jpk) , trdt(jpi,jpj,jpk) , avt_evd(jpi,jpj,jpk), STAT= trd_tra_alloc )
+      !
+      CALL mpp_sum ( 'trdtra', trd_tra_alloc )
+      IF( trd_tra_alloc /= 0 )   CALL ctl_stop( 'STOP', 'trd_tra_alloc: failed to allocate arrays' )
+   END FUNCTION trd_tra_alloc
+
+
+   SUBROUTINE trd_tra( kt, ctype, ktra, ktrd, ptrd, pun, ptra )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra  ***
+      !! 
+      !! ** Purpose : pre-process tracer trends
+      !!
+      !! ** 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
+      INTEGER ::   i01   ! 0 or 1
+      REAL(wp),        DIMENSION(jpi,jpj,jpk) ::   ztrds             ! 3D workspace
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zwt, zws, ztrdt   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !      
+      IF( .NOT. ALLOCATED( trdtx ) ) THEN      ! allocate trdtra arrays
+         IF( trd_tra_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trd_tra : unable to allocate arrays' )
+      ENDIF
+      !
+      i01 = COUNT( (/ PRESENT(pun) .OR. ( ktrd /= jptra_xad .AND. ktrd /= jptra_yad .AND. ktrd /= jptra_zad ) /) )
+      !
+      IF( ctype == 'TRA' .AND. ktra == jp_tem ) THEN   !==  Temperature trend  ==!
+         !
+         SELECT CASE( ktrd*i01 )
+         !                            ! 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 )
+ !!gm Gurvan, verify the jptra_evd trend please !
+         CASE( jptra_evd )   ;   avt_evd(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)
+         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*i01 )
+         !                            ! 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"
+            ALLOCATE( zwt(jpi,jpj,jpk), zws(jpi,jpj,jpk), ztrdt(jpi,jpj,jpk) )
+            !
+            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) ) / e3w_n(:,:,jk) * tmask(:,:,jk)
+               zws(:,:,jk) = avs(:,:,jk) * ( tsa(:,:,jk-1,jp_sal) - tsa(:,:,jk,jp_sal) ) / e3w_n(:,:,jk) * tmask(:,:,jk)
+            END DO
+            !
+            ztrdt(:,:,jpk) = 0._wp   ;   ztrds(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( zwt(:,:,jk) - zwt(:,:,jk+1) ) / e3t_n(:,:,jk)
+               ztrds(:,:,jk) = ( zws(:,:,jk) - zws(:,:,jk+1) ) / e3t_n(:,:,jk) 
+            END DO
+            CALL trd_tra_mng( ztrdt, ztrds, jptra_zdfp, kt )  
+            !
+            !                         ! Also calculate EVD trend at this point. 
+            zwt(:,:,:) = 0._wp   ;   zws(:,:,:) = 0._wp            ! vertical diffusive fluxes
+            DO jk = 2, jpk
+               zwt(:,:,jk) = avt_evd(:,:,jk) * ( tsa(:,:,jk-1,jp_tem) - tsa(:,:,jk,jp_tem) ) / e3w_n(:,:,jk) * tmask(:,:,jk)
+               zws(:,:,jk) = avt_evd(:,:,jk) * ( tsa(:,:,jk-1,jp_sal) - tsa(:,:,jk,jp_sal) ) / e3w_n(:,:,jk) * tmask(:,:,jk)
+            END DO
+            !
+            ztrdt(:,:,jpk) = 0._wp   ;   ztrds(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( zwt(:,:,jk) - zwt(:,:,jk+1) ) / e3t_n(:,:,jk)
+               ztrds(:,:,jk) = ( zws(:,:,jk) - zws(:,:,jk+1) ) / e3t_n(:,:,jk) 
+            END DO
+            CALL trd_tra_mng( ztrdt, ztrds, jptra_evd, kt )  
+            !
+            DEALLOCATE( 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*i01 )
+         !                            ! 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
+      !
+   END SUBROUTINE trd_tra
+
+
+   SUBROUTINE trd_tra_adv( pf, pun, ptn, cdir, ptrd )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra_adv  ***
+      !! 
+      !! ** 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 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._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.
+               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)  )   &
+                 &              * r1_e1e2t(ji,jj) / e3t_n(ji,jj,jk) * tmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE trd_tra_adv
+
+
+   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      ! = rdt (restart with Euler time stepping)
+      ELSEIF(               kt <= nit000 + 1) THEN   ;   r2dt = 2. * rdt      ! = 2 rdt (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), ALLOCATABLE, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
+      !!----------------------------------------------------------------------
+      !
+!!gm Rq: mask the trends already masked in trd_tra, but lbc_lnk should probably be added
+      !
+      ! Trends evaluated every time step that could go to the standard T file and can be output every ts into a 1ts file if 1ts output is selected
+      SELECT CASE( ktrd )
+      ! This total trend is done every time step
+      CASE( jptra_tot  )   ;   CALL iom_put( "ttrd_tot" , ptrdx )           ! model total trend
+                               CALL iom_put( "strd_tot" , ptrdy )
+      END SELECT
+      !
+      ! These trends are done every second time step. When 1ts output is selected must go different (2ts) file from standard T-file
+      IF( MOD( kt, 2 ) == 0 ) THEN
+         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( ln_linssh ) THEN                   ! cst volume : adv flux through z=0 surface
+                                     ALLOCATE( z2dx(jpi,jpj), z2dy(jpi,jpj) )
+                                     z2dx(:,:) = wn(:,:,1) * tsn(:,:,1,jp_tem) / e3t_n(:,:,1)
+                                     z2dy(:,:) = wn(:,:,1) * tsn(:,:,1,jp_sal) / e3t_n(:,:,1)
+                                     CALL iom_put( "ttrd_sad", z2dx )
+                                     CALL iom_put( "strd_sad", z2dy )
+                                     DEALLOCATE( z2dx, z2dy )
+                                  ENDIF
+         CASE( jptra_totad  ) ;   CALL iom_put( "ttrd_totad", ptrdx )        ! total   advection
+                                  CALL iom_put( "strd_totad", ptrdy )
+         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_evd )    ;   CALL iom_put( "ttrd_evd"  , ptrdx )        ! EVD trend (convection)
+                                  CALL iom_put( "strd_evd"  , 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_bbc  )   ;   CALL iom_put( "ttrd_bbc"  , ptrdx )        ! geothermal heating   (only on temperature)
+         CASE( jptra_nsr  )   ;   CALL iom_put( "ttrd_qns"  , ptrdx(:,:,1) ) ! surface forcing + runoff (ln_rnf=T)
+                                  CALL iom_put( "strd_cdt"  , ptrdy(:,:,1) )        ! output as 2D surface fields
+         CASE( jptra_qsr  )   ;   CALL iom_put( "ttrd_qsr"  , ptrdx )        ! penetrative solar radiat. (only on temperature)
+         END SELECT
+         ! the Asselin filter trend  is also every other time step but needs to be lagged one time step
+         ! Even when 1ts output is selected can go to the same (2ts) file as the trends plotted every even time step.
+      ELSE IF( MOD( kt, 2 ) == 1 ) THEN
+         SELECT CASE( ktrd )
+         CASE( jptra_atf  )   ;   CALL iom_put( "ttrd_atf" , ptrdx )        ! asselin time Filter
+                                  CALL iom_put( "strd_atf" , ptrdy )
+         END SELECT
+      END IF
+      !
+   END SUBROUTINE trd_tra_iom
+
+   !!======================================================================
+END MODULE trdtra
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtrc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtrc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdtrc.F90	(revision 14097)
@@ -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/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trdtrc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor.F90	(revision 14097)
@@ -0,0 +1,570 @@
+MODULE trdvor
+   !!======================================================================
+   !!                       ***  MODULE  trdvor  ***
+   !! Ocean diagnostics:  momentum trends
+   !!=====================================================================
+   !! 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
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_vor      : momentum trends averaged over the depth
+   !!   trd_vor_zint : vorticity vertical integration
+   !!   trd_vor_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 zdf_oce         ! ocean vertical physics
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE phycst          ! Define parameters for the routines
+   USE ldfdyn          ! ocean active tracers: lateral physics
+   USE dianam          ! build the name of file (routine)
+   USE zdfmxl          ! mixed layer depth
+   !
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE trd_vor_zint
+      MODULE PROCEDURE trd_vor_zint_2d, trd_vor_zint_3d
+   END INTERFACE
+
+   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
+
+   INTEGER ::   nh_t, nmoydpvor, nidvor, nhoridvor, ndimvor1, icount   ! needs for IOIPSL output
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) ::   ndexvor1   ! needed for IOIPSL output
+   INTEGER ::   ndebug     ! (0/1) set it to 1 in case of problem to have more print
+
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avr      ! average
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avrb     ! before vorticity (kt-1)
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avrbb    ! vorticity at begining of the nn_write-1 timestep averaging period
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avrbn    ! after vorticity at time step after the
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   rotot        ! begining of the NN_WRITE-1 timesteps
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avrtot   !
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   vor_avrres   !
+   REAL(wp), SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   vortrd       ! curl of trends
+         
+   CHARACTER(len=12) ::   cvort
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_vor_alloc()
+      !!----------------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor_alloc  ***
+      !!----------------------------------------------------------------------------
+      ALLOCATE( vor_avr   (jpi,jpj) , vor_avrb(jpi,jpj) , vor_avrbb (jpi,jpj) ,   &
+         &      vor_avrbn (jpi,jpj) , rotot   (jpi,jpj) , vor_avrtot(jpi,jpj) ,   &
+         &      vor_avrres(jpi,jpj) , vortrd  (jpi,jpj,jpltot_vor) ,              &
+         &      ndexvor1  (jpi*jpj)                                ,   STAT= trd_vor_alloc )
+         !
+      CALL mpp_sum ( 'trdvor', trd_vor_alloc )
+      IF( trd_vor_alloc /= 0 )   CALL ctl_stop( 'STOP', '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 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), DIMENSION(jpi,jpj) ::   ztswu, ztswv    ! 2D workspace 
+      !!----------------------------------------------------------------------
+
+      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) ) / ( e3u_n(ji,jj,1) * rau0 )
+               ztswv(ji,jj) = 0.5 * ( vtau_b(ji,jj) + vtau(ji,jj) ) / ( e3v_n(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
+      !
+   END SUBROUTINE trd_vor
+
+
+   SUBROUTINE trd_vor_zint_2d( putrdvor, pvtrdvor, ktrd )
+      !!----------------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor_zint  ***
+      !!
+      !! ** Purpose :   computation of vertically integrated vorticity budgets
+      !!              from ocean surface down to control surface (NetCDF output)
+      !!
+      !! ** Method/usage :   integration done over nn_write-1 time steps
+      !!
+      !! ** Action :   trends :
+      !!                  vortrd (,, 1) = Pressure Gradient Trend
+      !!                  vortrd (,, 2) = KE Gradient Trend
+      !!                  vortrd (,, 3) = Relative Vorticity Trend
+      !!                  vortrd (,, 4) = Coriolis Term Trend
+      !!                  vortrd (,, 5) = Horizontal Diffusion Trend
+      !!                  vortrd (,, 6) = Vertical Advection Trend
+      !!                  vortrd (,, 7) = Vertical Diffusion Trend
+      !!                  vortrd (,, 8) = Surface Pressure Grad. Trend
+      !!                  vortrd (,, 9) = Beta V
+      !!                  vortrd (,,10) = forcing term
+      !!		              vortrd (,,11) = bottom friction term
+      !!                  rotot(,) : total cumulative trends over nn_write-1 time steps
+      !!                  vor_avrtot(,) : first membre of vrticity equation
+      !!                  vor_avrres(,) : residual = dh/dt entrainment
+      !!
+      !!      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 
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   pvtrdvor   ! v vorticity trend
+      !
+      INTEGER ::   ji, jj       ! dummy loop indices
+      INTEGER ::   ikbu, ikbv   ! local integers
+      REAL(wp), DIMENSION(jpi,jpj) :: zudpvor, zvdpvor  ! total cmulative trends
+      !!----------------------------------------------------------------------
+
+      !
+
+      zudpvor(:,:) = 0._wp                 ;   zvdpvor(:,:) = 0._wp                    ! Initialisation
+      CALL lbc_lnk_multi( 'trdvor', putrdvor, 'U', -1. , pvtrdvor, 'V', -1. )      ! lateral boundary condition
+      
+
+      !  =====================================
+      !  I vertical integration of 2D trends
+      !  =====================================
+
+      SELECT CASE( ktrd ) 
+      !
+      CASE( jpvor_bfr )        ! bottom friction
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1 
+               ikbu = mbkv(ji,jj)
+               ikbv = mbkv(ji,jj)            
+               zudpvor(ji,jj) = putrdvor(ji,jj) * e3u_n(ji,jj,ikbu) * e1u(ji,jj) * umask(ji,jj,ikbu)
+               zvdpvor(ji,jj) = pvtrdvor(ji,jj) * e3v_n(ji,jj,ikbv) * e2v(ji,jj) * vmask(ji,jj,ikbv)
+            END DO
+         END DO
+         !
+      CASE( jpvor_swf )        ! wind stress
+         zudpvor(:,:) = putrdvor(:,:) * e3u_n(:,:,1) * e1u(:,:) * umask(:,:,1)
+         zvdpvor(:,:) = pvtrdvor(:,:) * e3v_n(:,:,1) * e2v(:,:) * vmask(:,:,1)
+         !
+      END SELECT
+
+      ! Average except for Beta.V
+      zudpvor(:,:) = zudpvor(:,:) * r1_hu_n(:,:)
+      zvdpvor(:,:) = zvdpvor(:,:) * r1_hv_n(:,:)
+   
+      ! Curl
+      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) )
+         END DO
+      END DO
+      vortrd(:,:,ktrd) = vortrd(:,:,ktrd) * fmask(:,:,1)      ! Surface mask
+
+      IF( ndebug /= 0 ) THEN
+         IF(lwp) WRITE(numout,*) ' debuging trd_vor_zint: I done'
+         CALL FLUSH(numout)
+      ENDIF
+      !
+   END SUBROUTINE trd_vor_zint_2d
+
+
+   SUBROUTINE trd_vor_zint_3d( putrdvor, pvtrdvor, ktrd )
+      !!----------------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor_zint  ***
+      !!
+      !! ** Purpose :   computation of vertically integrated vorticity budgets
+      !!              from ocean surface down to control surface (NetCDF output)
+      !!
+      !! ** Method/usage :   integration done over nn_write-1 time steps
+      !!
+      !! ** Action :     trends :
+      !!                  vortrd (,,1) = Pressure Gradient Trend
+      !!                  vortrd (,,2) = KE Gradient Trend
+      !!                  vortrd (,,3) = Relative Vorticity Trend
+      !!                  vortrd (,,4) = Coriolis Term Trend
+      !!                  vortrd (,,5) = Horizontal Diffusion Trend
+      !!                  vortrd (,,6) = Vertical Advection Trend
+      !!                  vortrd (,,7) = Vertical Diffusion Trend
+      !!                  vortrd (,,8) = Surface Pressure Grad. Trend
+      !!                  vortrd (,,9) = Beta V
+      !!                  vortrd (,,10) = forcing term
+      !!		  vortrd (,,11) = bottom friction term
+      !!                  rotot(,) : total cumulative trends over nn_write-1 time steps
+      !!                  vor_avrtot(,) : first membre of vrticity equation
+      !!                  vor_avrres(,) : residual = dh/dt entrainment
+      !!
+      !!      trends output in netCDF format using ioipsl
+      !!----------------------------------------------------------------------
+      !
+      INTEGER                         , INTENT(in   ) ::   ktrd       ! ocean trend index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   putrdvor   ! u vorticity trend 
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pvtrdvor   ! v vorticity trend
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) :: zubet  , zvbet    ! Beta.V   
+      REAL(wp), DIMENSION(jpi,jpj) :: zudpvor, zvdpvor  ! total cmulative trends
+      !!----------------------------------------------------------------------
+     
+      ! Initialization
+      zubet  (:,:) = 0._wp
+      zvbet  (:,:) = 0._wp
+      zudpvor(:,:) = 0._wp
+      zvdpvor(:,:) = 0._wp
+      !                            ! lateral boundary condition on input momentum trends
+      CALL lbc_lnk_multi( 'trdvor', putrdvor, 'U', -1. , pvtrdvor, 'V', -1. )
+
+      !  =====================================
+      !  I vertical integration of 3D trends
+      !  =====================================
+      ! putrdvor and pvtrdvor terms
+      DO jk = 1,jpk
+        zudpvor(:,:) = zudpvor(:,:) + putrdvor(:,:,jk) * e3u_n(:,:,jk) * e1u(:,:) * umask(:,:,jk)
+        zvdpvor(:,:) = zvdpvor(:,:) + pvtrdvor(:,:,jk) * e3v_n(:,:,jk) * e2v(:,:) * vmask(:,:,jk)
+      END DO
+
+      ! 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(:,:)
+         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) * r1_hu_n(:,:) * fmask(:,:,1)
+      ENDIF
+      !
+      ! Average 
+      zudpvor(:,:) = zudpvor(:,:) * r1_hu_n(:,:)
+      zvdpvor(:,:) = zvdpvor(:,:) * r1_hv_n(:,:)
+      !
+      ! Curl
+      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) )
+         END DO
+      END DO
+      ! Surface mask
+      vortrd(:,:,ktrd) = vortrd(:,:,ktrd) * fmask(:,:,1)
+   
+      IF( ndebug /= 0 ) THEN
+         IF(lwp) WRITE(numout,*) ' debuging trd_vor_zint: I done'
+         CALL FLUSH(numout)
+      ENDIF
+      !
+   END SUBROUTINE trd_vor_zint_3d
+
+
+   SUBROUTINE trd_vor_iom( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor  ***
+      !! 
+      !! ** Purpose :  computation of cumulated trends over analysis period
+      !!               and make outputs (NetCDF format)
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
+      !
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      INTEGER  ::   it, itmod        ! local integers
+      REAL(wp) ::   zmean            ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) :: zun, zvn
+      !!----------------------------------------------------------------------
+
+      !  =================
+      !  I. Initialization
+      !  =================
+     
+     
+      ! I.1 set before values of vertically average u and v
+      ! ---------------------------------------------------
+
+      IF( kt > nit000 )   vor_avrb(:,:) = vor_avr(:,:)
+
+      ! I.2 vertically integrated vorticity
+      !  ----------------------------------
+
+      vor_avr   (:,:) = 0._wp
+      zun       (:,:) = 0._wp
+      zvn       (:,:) = 0._wp
+      vor_avrtot(:,:) = 0._wp
+      vor_avrres(:,:) = 0._wp
+      
+      ! Vertically averaged velocity
+      DO jk = 1, jpk - 1
+         zun(:,:) = zun(:,:) + e1u(:,:) * un(:,:,jk) * e3u_n(:,:,jk)
+         zvn(:,:) = zvn(:,:) + e2v(:,:) * vn(:,:,jk) * e3v_n(:,:,jk)
+      END DO
+ 
+      zun(:,:) = zun(:,:) * r1_hu_n(:,:)
+      zvn(:,:) = zvn(:,:) * r1_hv_n(:,:)
+
+      ! Curl
+      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)
+         END DO
+      END DO
+      
+      !  =================================
+      !   II. Cumulated trends
+      !  =================================
+
+      ! II.1 set `before' mixed layer values for kt = nit000+1
+      ! ------------------------------------------------------
+      IF( kt == nit000+1 ) THEN
+         vor_avrbb(:,:) = vor_avrb(:,:)
+         vor_avrbn(:,:) = vor_avr (:,:)
+      ENDIF
+
+      ! II.2 cumulated trends over analysis period (kt=2 to nn_write)
+      ! ----------------------
+      ! trends cumulated over nn_write-2 time steps
+
+      IF( kt >= nit000+2 ) THEN
+         nmoydpvor = nmoydpvor + 1
+         DO jl = 1, jpltot_vor
+            IF( jl /= 9 ) THEN
+               rotot(:,:) = rotot(:,:) + vortrd(:,:,jl)
+            ENDIF
+         END DO
+      ENDIF
+
+      !  =============================================
+      !   III. Output in netCDF + residual computation
+      !  =============================================
+      
+      ! define time axis
+      it    = kt
+      itmod = kt - nit000 + 1
+
+      IF( MOD( it, nn_trd ) == 0 ) THEN
+
+         ! III.1 compute total trend
+         ! ------------------------
+         zmean = 1._wp / (  REAL( nmoydpvor, wp ) * 2._wp * rdt  )
+         vor_avrtot(:,:) = (  vor_avr(:,:) - vor_avrbn(:,:) + vor_avrb(:,:) - vor_avrbb(:,:) ) * zmean
+
+
+         ! III.2 compute residual
+         ! ---------------------
+         zmean = 1._wp / REAL( nmoydpvor, wp )
+         vor_avrres(:,:) = vor_avrtot(:,:) - rotot(:,:) / zmean
+
+         ! Boundary conditions
+         CALL lbc_lnk_multi( 'trdvor', vor_avrtot, 'F', 1. , vor_avrres, 'F', 1. )
+
+
+         ! III.3 time evolution array swap
+         ! ------------------------------
+         vor_avrbb(:,:) = vor_avrb(:,:)
+         vor_avrbn(:,:) = vor_avr (:,:)
+         !
+         nmoydpvor = 0
+         !
+      ENDIF
+
+      ! III.4 write trends to output
+      ! ---------------------------
+
+      IF( kt >=  nit000+1 ) THEN
+
+         IF( lwp .AND. MOD( itmod, nn_trd ) == 0 ) THEN
+            WRITE(numout,*) ''
+            WRITE(numout,*) 'trd_vor : write trends in the NetCDF file at kt = ', kt
+            WRITE(numout,*) '~~~~~~~  '
+         ENDIF
+ 
+         CALL histwrite( nidvor,"sovortPh",it,vortrd(:,:,jpvor_prg),ndimvor1,ndexvor1)  ! grad Ph
+         CALL histwrite( nidvor,"sovortEk",it,vortrd(:,:,jpvor_keg),ndimvor1,ndexvor1)  ! Energy
+         CALL histwrite( nidvor,"sovozeta",it,vortrd(:,:,jpvor_rvo),ndimvor1,ndexvor1)  ! rel vorticity
+         CALL histwrite( nidvor,"sovortif",it,vortrd(:,:,jpvor_pvo),ndimvor1,ndexvor1)  ! coriolis
+         CALL histwrite( nidvor,"sovodifl",it,vortrd(:,:,jpvor_ldf),ndimvor1,ndexvor1)  ! lat diff
+         CALL histwrite( nidvor,"sovoadvv",it,vortrd(:,:,jpvor_zad),ndimvor1,ndexvor1)  ! vert adv
+         CALL histwrite( nidvor,"sovodifv",it,vortrd(:,:,jpvor_zdf),ndimvor1,ndexvor1)  ! vert diff
+         CALL histwrite( nidvor,"sovortPs",it,vortrd(:,:,jpvor_spg),ndimvor1,ndexvor1)  ! grad Ps
+         CALL histwrite( nidvor,"sovortbv",it,vortrd(:,:,jpvor_bev),ndimvor1,ndexvor1)  ! beta.V
+         CALL histwrite( nidvor,"sovowind",it,vortrd(:,:,jpvor_swf),ndimvor1,ndexvor1) ! wind stress
+         CALL histwrite( nidvor,"sovobfri",it,vortrd(:,:,jpvor_bfr),ndimvor1,ndexvor1) ! bottom friction
+         CALL histwrite( nidvor,"1st_mbre",it,vor_avrtot    ,ndimvor1,ndexvor1) ! First membre
+         CALL histwrite( nidvor,"sovorgap",it,vor_avrres    ,ndimvor1,ndexvor1) ! gap between 1st and 2 nd mbre
+         !
+         IF( ndebug /= 0 ) THEN
+            WRITE(numout,*) ' debuging trd_vor: III.4 done'
+            CALL FLUSH(numout)
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( MOD( it, nn_trd ) == 0 ) rotot(:,:)=0
+      !
+      IF( kt == nitend )   CALL histclo( nidvor )
+      !
+   END SUBROUTINE trd_vor_iom
+
+
+   SUBROUTINE trd_vor_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor_init  ***
+      !! 
+      !! ** Purpose :   computation of vertically integrated T and S budgets
+      !!      from ocean surface down to control surface (NetCDF output)
+      !!----------------------------------------------------------------------
+      REAL(wp) ::   zjulian, zsto, zout
+      CHARACTER (len=40) ::   clhstnam
+      CHARACTER (len=40) ::   clop
+      !!----------------------------------------------------------------------
+
+      !  ===================
+      !   I. initialization
+      !  ===================
+
+      cvort='averaged-vor'
+
+      ! Open specifier
+      ndebug = 0      ! set it to 1 in case of problem to have more Print
+
+      IF(lwp) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' trd_vor_init: vorticity trends'
+         WRITE(numout,*) ' ~~~~~~~~~~~~'
+         WRITE(numout,*) ' '
+         WRITE(numout,*) '               ##########################################################################'
+         WRITE(numout,*) '                CAUTION: The interpretation of the vorticity trends is'
+         WRITE(numout,*) '                not obvious, please contact Anne-Marie TREGUIER at: treguier@ifremer.fr '
+         WRITE(numout,*) '               ##########################################################################'
+         WRITE(numout,*) ' '
+      ENDIF
+
+      IF( trd_vor_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trd_vor_init : unable to allocate trdvor arrays' )
+
+
+      ! cumulated trends array init
+      nmoydpvor = 0
+      rotot(:,:)=0
+      vor_avrtot(:,:)=0
+      vor_avrres(:,:)=0
+
+      IF( ndebug /= 0 ) THEN
+         WRITE(numout,*) ' debuging trd_vor_init: I. done'
+         CALL FLUSH(numout)
+      ENDIF
+
+      !  =================================
+      !   II. netCDF output initialization
+      !  =================================
+
+      !-----------------------------------------
+      ! 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
+      zsto = nn_write*rdt
+      clop = "inst("//TRIM(clop)//")"
+#else
+      zsto = rdt
+      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 (nidvor)
+      ! ---------------------------------
+      CALL dia_nam( clhstnam, nn_trd, 'vort' )                  ! filename
+      IF(lwp) WRITE(numout,*) ' Name of NETCDF file ', clhstnam
+      CALL histbeg( clhstnam, jpi, glamf, jpj, gphif,1, jpi,   &  ! Horizontal grid : glamt and gphit
+         &          1, jpj, nit000-1, zjulian, rdt, nh_t, nidvor, domain_id=nidom, snc4chunks=snc4set )
+      CALL wheneq( jpi*jpj, fmask, 1, 1., ndexvor1, ndimvor1 )    ! surface
+
+      ! Declare output fields as netCDF variables
+      CALL histdef( nidvor, "sovortPh", cvort//"grad Ph" , "s-2",        & ! grad Ph
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovortEk", cvort//"Energy", "s-2",          & ! Energy
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovozeta", cvort//"rel vorticity", "s-2",   & ! rel vorticity
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovortif", cvort//"coriolis", "s-2",        & ! coriolis
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovodifl", cvort//"lat diff ", "s-2",       & ! lat diff
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovoadvv", cvort//"vert adv", "s-2",        & ! vert adv
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovodifv", cvort//"vert diff" , "s-2",      & ! vert diff
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovortPs", cvort//"grad Ps", "s-2",         & ! grad Ps
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovortbv", cvort//"Beta V", "s-2",          & ! beta.V
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovowind", cvort//"wind stress", "s-2",     & ! wind stress
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovobfri", cvort//"bottom friction", "s-2", & ! bottom friction
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "1st_mbre", cvort//"1st mbre", "s-2",        & ! First membre
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histdef( nidvor, "sovorgap", cvort//"gap", "s-2",             & ! gap between 1st and 2 nd mbre
+         &          jpi,jpj,nh_t,1,1,1,-99,32,clop,zsto,zout)
+      CALL histend( nidvor, snc4set )
+
+      IF( ndebug /= 0 ) THEN
+         WRITE(numout,*) ' debuging trd_vor_init: II. done'
+         CALL FLUSH(numout)
+      ENDIF
+      !
+   END SUBROUTINE trd_vor_init
+
+   !!======================================================================
+END MODULE trdvor
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/TRD/trdvor_oce.F90	(revision 14097)
@@ -0,0 +1,34 @@
+MODULE trdvor_oce
+   !!======================================================================
+   !!                   ***  MODULE trdvor_oce  ***
+   !! Ocean trends :   set vorticity trend variables
+   !!======================================================================
+   !! History :  1.0  !  04-2006  (L. Brunier, A-M. Treguier) Original code 
+   !!----------------------------------------------------------------------
+   
+   USE par_oce      ! ocean parameters
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !                                               !!* vorticity trends index
+   INTEGER, PUBLIC, PARAMETER ::   jpltot_vor = 11  !: Number of vorticity trend terms
+   !
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_prg =  1   !: Pressure Gradient Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_keg =  2   !: KE Gradient Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_rvo =  3   !: Relative Vorticity Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_pvo =  4   !: Planetary Vorticity Term Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_ldf =  5   !: Horizontal Diffusion Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_zad =  6   !: Vertical Advection Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_zdf =  7   !: Vertical Diffusion Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_spg =  8   !: Surface Pressure Grad. Trend
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_bev =  9   !: Beta V
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_swf = 10   !: wind stress forcing term
+   INTEGER, PUBLIC, PARAMETER ::   jpvor_bfr = 11   !: bottom friction term
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trdvor_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/README.rst	(revision 14097)
@@ -0,0 +1,280 @@
+******************************
+Setting up a new configuration
+******************************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+Starting from an existing configuration
+=======================================
+
+There are three options to build a new configuration from an existing one.
+
+Option 1: Duplicate an existing configuration
+---------------------------------------------
+
+The NEMO so-called Reference Configurations cover a number of major features for NEMO setup
+(global, regional, 1D, using embedded zoom with AGRIF...)
+
+One can create a new configuration by duplicating one of the reference configurations
+(``ORCA2_ICE_PISCES`` in the following example)
+
+.. code-block:: console
+
+   $ ./makenemo –n 'ORCA2_ICE_PISCES_MINE' -r 'ORCA2_ICE_PISCES' -m 'my_arch'
+
+Option 2: Duplicate with differences
+------------------------------------
+
+Create and compile a new configuration based on a reference configuration
+(``ORCA2_ICE_PISCES`` in the following example) but with different pre-processor options.
+For this either add ``add_key`` or ``del_key`` keys as required; e.g.
+
+.. code-block:: console
+
+   $ ./makenemo –n 'ORCA2_ICE_PISCES_MINE' -r 'ORCA2_ICE_PISCES' -m 'my_arch' del_key 'key_iomput' add_key 'key_diahth'
+
+Option 3: Use the SIREN tools to subset an existing model
+---------------------------------------------------------
+
+Define a regional configuration which is a {sub,super}-set of an existing configuration.
+
+This last option employs the SIREN software tools that are included in the standard distribution.
+The software is written in Fortran 95 and available in the :file:`./tools/SIREN` directory.
+SIREN allows you to create your own regional configuration embedded in a wider one.
+
+SIREN is a set of programs to create all the input files you need to
+run a NEMO regional configuration.
+
+:Demo:     Set of GLORYS files (GLObal ReanalYSis on the ORCA025 grid),
+           as well as examples of namelists are available `here`_.
+:Doc:      :forge:`chrome/site/doc/SIREN/html/index.html`
+:Support:  Any questions or comments regarding the use of SIREN should be posted in
+  :forge:`the corresponding forum <discussion/forum/2>`.
+
+.. _here: https://prodn.idris.fr/thredds/catalog/ipsl_public/rron463/catalog.html
+
+Creating a completely new configuration
+=======================================
+
+From NEMO version 4.0 there are two ways to build configurations from scratch.
+The appropriate method to use depends largely on the target configuration.
+Method 1 is for more complex/realistic global or regional configurations and
+method 2 is intended for simpler, idealised configurations whose
+domains and characteristics can be described in simple geometries and formulae.
+
+Option 1: Create and use a domain configuration file
+----------------------------------------------------
+
+This method is used by each of the reference configurations,
+so that downloading their input files linked to their description can help.
+Although starting from scratch,
+it is advisable to create the directory structure to house your new configuration by
+duplicating the closest reference configuration to your target application.
+For example, if your application requires both ocean ice and passive tracers,
+then use the ``ORCA2_ICE_PISCES`` as template,
+and execute following command to build your ``MY_NEW_CONFIG`` configuration:
+
+.. code-block:: sh
+
+   $ ./makenemo –n 'MY_NEW_CONFIG' -r 'ORCA2_ICE_PISCES' -m 'my_arch'
+
+where ``MY_NEW_CONFIG`` can be substituted with
+a suitably descriptive name for your new configuration.
+
+The purpose of this step is simply to create and populate the appropriate :file:`WORK`,
+:file:`MY_SRC` and :file:`EXP00` subdirectories for your new configuration.
+Other choices for the base reference configuration might be
+
+:GYRE:  If your target application is ocean-only
+:AMM12: If your target application is regional with open boundaries
+
+All the domain information for your new configuration will be contained within
+a netcdf file called :file:`domain_cfg.nc` which you will need to create and
+place in the :file:`./cfgs/MY_NEW_CONFIG/EXP00` sub-directory.
+Firstly though, ensure that your configuration is set to use such a file by checking that
+
+.. code-block:: fortran
+
+   ln_read_cfg = .true.
+
+in :file:`./cfgs/MY_NEW_CONFIG/EXP00/namelist_cfg`
+
+Create the :file:`domain_cfg.nc` file which must contain the following fields
+
+.. code-block:: c
+
+   /* configuration name, configuration resolution                 */
+   int    ORCA, ORCA_index
+   /* global domain sizes                                          */
+   int    jpiglo, jpjglo, jpkglo
+   /* lateral global domain b.c.                                   */
+   int    jperio
+   /* flags for z-coord, z-coord with partial steps and s-coord    */
+   int    ln_zco, ln_zps, ln_sco
+   /* flag  for ice shelf cavities                                 */
+   int    ln_isfcav
+   /* geographic position                                          */
+   double glamt, glamu, glamv, glamf
+   /* geographic position                                          */
+   double gphit, gphiu, gphiv, gphif
+   /* Coriolis parameter (if not on the sphere)                    */
+   double iff, ff_f, ff_t
+   /* horizontal scale factors                                     */
+   double e1t, e1u, e1v, e1f
+   /* horizontal scale factors                                     */
+   double e2t, e2u, e2v, e2f
+   /* U and V surfaces (if grid size reduction in some straits)    */
+   double ie1e2u_v, e1e2u, e1e2v
+   /* reference vertical scale factors at T and W points           */
+   double e3t_1d, e3w_1d
+   /* vertical scale factors 3D coordinate at T,U,V,F and W points */
+   double e3t_0, e3u_0, e3v_0, e3f_0, e3w_0
+   /* vertical scale factors 3D coordinate at UW and VW points     */
+   double e3uw_0, e3vw_0
+   /* last wet T-points, 1st wet T-points (for ice shelf cavities) */
+   int    bottom_level, top_level
+
+There are two options for creating a :file:`domain_cfg.nc` file:
+
+- Users can use tools of their own choice to build a :file:`domain_cfg.nc` with all mandatory fields.
+- Users can adapt and apply the supplied tool available in :file:`./tools/DOMAINcfg`.
+  This tool is based on code extracted from NEMO version 3.6 and will allow similar choices for
+  the horizontal and vertical grids that were available internally to that version.
+  See :ref:`tools <DOMAINcfg>` for details.
+
+Option 2: Adapt the usr_def configuration module of NEMO for you own purposes
+-----------------------------------------------------------------------------
+
+This method is intended for configuring easily simple/idealised configurations which
+are often used as demonstrators or for process evaluation and comparison.
+This method can be used whenever the domain geometry has a simple mathematical description and
+the ocean initial state and boundary forcing is described analytically.
+As a start, consider the case of starting a completely new ocean-only test case based on
+the ``LOCK_EXCHANGE`` example.
+
+.. note::
+
+   We probably need an even more basic example than this with only one namelist and
+   minimal changes to the usrdef modules
+
+Firstly, construct the directory structure, starting in the :file:`cfgs` directory:
+
+.. code-block:: console
+
+   $ ./makenemo -n 'MY_NEW_TEST' -t 'LOCK_EXCHANGE' -m 'my_arch'
+
+where the ``-t`` option has been used to locate the new configuration in
+the :file:`tests` subdirectory
+(it is recommended practice to keep full configurations and idealised cases clearly distinguishable).
+This command will create (amongst others) the following files and directories::
+
+   ./tests/MY_NEW_TEST:
+   BLD  EXP00  MY_SRC WORK  cpp_MY_NEW_TEST.fcm
+
+   ./tests/MY_NEW_TEST/EXP00:
+   context_nemo.xml  domain_def_nemo.xml  field_def_nemo-oce.xml  file_def_nemo-oce.xml  iodef.xml
+   namelist_cfg      namelist_ref
+
+   ./tests/MY_NEW_TEST/MY_SRC:
+   usrdef_hgr.F90  usrdef_nam.F90  usrdef_zgr.F90  usrdef_istate.F90  usrdef_sbc.F90  zdfini.F90
+
+The key to setting up an idealised configuration lies in
+adapting a small set of short Fortran 90 modules which
+should be dropped into the :file:`MY_SRC` directory.
+Here the ``LOCK_EXCHANGE`` example is using 5 such routines but the full set that is available in
+the :file:`src/OCE/USR` directory is::
+
+   ./src/OCE/USR:
+   usrdef_closea.F90  usrdef_fmask.F90  usrdef_hgr.F90  usrdef_istate.F90
+   usrdef_nam.F90     usrdef_sbc.F90    usrdef_zgr.F90
+
+Before discussing these in more detail it is worth noting the various namelist controls that
+engage the different user-defined aspects.
+These controls are set using two new logical switches or are implied by the settings of existing ones.
+For example, the mandatory requirement for an idealised configuration is to provide routines which
+define the horizontal and vertical domains.
+Templates for these are provided in the :file:`usrdef_hgr.F90` and :file:`usrdef_zgr.F90` modules.
+The application of these modules is activated whenever:
+
+.. code-block:: fortran
+
+   ln_read_cfg = .false.
+
+in any configuration's :file:`namelist_cfg` file.
+This setting also activates the reading of an optional ``&nam_usrdef`` namelist which can be used to
+supply configuration specific settings.
+These need to be declared and read in the :file:`usrdef_nam.F90` module.
+
+Another explicit control is available in the ``&namsbc`` namelist which
+activates the use of analytical forcing.
+With
+
+.. code-block:: fortran
+
+   ln_usr = .true.
+
+Other usrdef modules are activated by less explicit means.
+For example, code in :file:`usrdef_istate.F90` is used to
+define initial temperature and salinity fields if
+
+.. code-block:: fortran
+
+   ln_tsd_init   = .false.
+
+in the ``&namtsd`` namelist.
+The remaining modules, namely :file:`usrdef_closea.F90` :file:`usrdef_fmask.F90` are specific to
+ORCA configurations and set local variations of some specific fields for
+the various resolutions of the global models.
+They do not need to be considered here in the context of idealised cases but
+it is worth noting that all configuration specific code has now been isolated in the usrdef modules.
+In the case of these last two modules, they are activated only if an ORCA configuration is detected.
+Currently,
+this requires a specific integer variable named ``ORCA`` to be set in a :file:`domain_cfg.nc` file.
+
+.. note::
+
+   This would be less confusing if the ``cn_cfg`` string is read directly as
+   a character attribue from the :file:`domain_cfg.nc`.
+
+So, in most cases, the set up of idealised model configurations can be completed by
+copying the template routines from :file:`./src/OCE/USR` into
+your new :file:`./cfgs/MY_NEW_TEST/MY_SRC` directory and
+editing the appropriate modules as needed.
+The default set are those used for the GYRE reference configuration.
+The contents of :file:`MY_SRC` directories from other idealised configurations may provide
+more convenient templates if they share common characteristics with your target application.
+
+Whatever the starting point,
+it should not require too many changes or additional lines of code to produce routines in
+:file:`./src/OCE/USR` that define analytically the domain,
+the initial state and the surface boundary conditions for your new configuration.
+
+To summarize, the base set of modules is:
+
+:usrdef_hgr.F90:    Define horizontal grid
+:usrdef_zgr.F90:    Define vertical grid
+:usrdef_sbc.F90:    Provides at each time-step the surface boundary condition,
+   i.e. the momentum, heat and freshwater fluxes
+:usrdef_istate.F90: Defines initialization of the dynamics and tracers
+:usrdef_nam.F90:    Configuration-specific namelist processing to
+   set any associated run-time parameters
+
+with two specialised ORCA modules
+(not related to idealised configurations but used to isolate configuration specific code that
+is used in ORCA2 reference configurations and established global configurations using
+the ORCA tripolar grid):
+
+:usrdef_fmask.F90:  only used in ORCA configurations for
+   alteration of f-point land/ocean mask in some straits
+:usrdef_closea.F90: only used in ORCA configurations for
+   specific treatments associated with closed seas
+
+From version 4.0, the NEMO release includes a :file:`tests` subdirectory containing available and
+up to date :doc:`test cases <tests>` build by the community.
+These will not be fully supported as are NEMO reference configurations,
+but should provide a source of raw material.
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_fmask.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_fmask.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_fmask.F90	(revision 14097)
@@ -0,0 +1,150 @@
+MODULE usrdef_fmask
+   !!======================================================================
+   !!                     ***  MODULE usrdef_fmask   ***
+   !!
+   !!                      ===  ORCA configuration  ===
+   !!                            (2 and 1 degrees)
+   !!
+   !! User defined : alteration of land/sea f-point mask in some straits
+   !!======================================================================
+   !! History :  4.0  ! 2016-06  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_fmask  : alteration of f-point land/ocean mask in some straits
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! Massively Parallel Processing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_fmask    ! routine called by dommsk.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_fmask( cd_cfg, kcfg, pfmsk )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE dom_msk  ***
+      !!
+      !! ** Purpose :   User defined alteration of the lateral boundary 
+      !!              condition on velocity.
+      !!
+      !! ** Method  :   Local change of the value of fmask at lateral ocean/land 
+      !!              boundary in straits in order to increase the viscous 
+      !!              boundary layer and thus reduce the transport through the 
+      !!              corresponding straits.
+      !!                Here only alterations in ORCA R2 and R1 cases
+      !!
+      !! ** Action :   fmask : land/ocean mask at f-point with increased value 
+      !!                       in some user defined straits
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)          , INTENT(in   ) ::   cd_cfg   ! configuration name
+      INTEGER                   , INTENT(in   ) ::   kcfg     ! configuration identifier 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pfmsk    ! Ocean/Land f-point mask including lateral boundary cond.
+      !
+      INTEGER  ::   iif, iil, ii0, ii1, ii   ! local integers
+      INTEGER  ::   ijf, ijl, ij0, ij1       !   -       -
+      INTEGER  ::   isrow                    ! index for ORCA1 starting row
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM( cd_cfg ) == "orca" .OR. TRIM( cd_cfg ) == "ORCA" ) THEN      !==  ORCA Configurations  ==!
+         !
+         SELECT CASE ( kcfg )
+         !
+         CASE( 2 )                           !  R2 case
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_fmask : ORCA_R2: increase lateral friction near the following straits:'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
+            !
+            IF(lwp) WRITE(numout,*) '      Gibraltar '
+            ij0 = 101   ;   ij1 = 101           ! Gibraltar strait  : partial slip (pfmsk=0.5)
+            ii0 = 139   ;   ii1 = 140   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) =  0.5_wp
+            ij0 = 102   ;   ij1 = 102
+            ii0 = 139   ;   ii1 = 140   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) =  0.5_wp
+            !
+            IF(lwp) WRITE(numout,*) '      Bab el Mandeb '
+            ij0 =  87   ;   ij1 =  88           ! Bab el Mandeb : partial slip (pfmsk=1)
+            ii0 = 160   ;   ii1 = 160   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) =  1._wp
+            ij0 =  88   ;   ij1 =  88
+            ii0 = 159   ;   ii1 = 159   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) =  1._wp
+            !
+            ! We keep this as an example but it is instable in this case 
+            !IF(lwp) WRITE(numout,*) '      Danish straits '
+            !         ij0 = 115   ;   ij1 = 115 ! Danish straits  : strong slip (pfmsk > 2)
+            !         ii0 = 145   ;   ii1 = 146   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) = 4._wp
+            !         ij0 = 116   ;   ij1 = 116
+            !         ii0 = 145   ;   ii1 = 146   ;   pfmsk( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) , 1:jpk ) = 4._wp
+            !
+         CASE( 1 )                           ! R1 case
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_fmask : ORCA_R1: increase lateral friction near the following straits:'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'   
+!!gm    ! This dirty section will be suppressed by simplification process:
+!!gm    ! all this will come back in input files
+!!gm    ! Currently these hard-wired indices relate to configuration with extend grid (jpjglo=332)
+            !
+            isrow = 332 - jpjglo
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   orca_r1: increase friction near the following straits : '
+            IF(lwp) WRITE(numout,*) '      Gibraltar '
+            ii0 = 282           ;   ii1 = 283        ! Gibraltar Strait 
+            ij0 = 241 - isrow   ;   ij1 = 241 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      Bhosporus '
+            ii0 = 314           ;   ii1 = 315        ! Bhosporus Strait 
+            ij0 = 248 - isrow   ;   ij1 = 248 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      Makassar (Top) '
+            ii0 =  48           ;   ii1 =  48        ! Makassar Strait (Top) 
+            ij0 = 189 - isrow   ;   ij1 = 190 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      Lombok '
+            ii0 =  44           ;   ii1 =  44        ! Lombok Strait 
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      Ombai '
+            ii0 =  53           ;   ii1 =  53        ! Ombai Strait 
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      Timor Passage '
+            ii0 =  56           ;   ii1 =  56        ! Timor Passage 
+            ij0 = 164 - isrow   ;   ij1 = 165 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 2._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      West Halmahera '
+            ii0 =  58           ;   ii1 =  58        ! West Halmahera Strait 
+            ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+            !
+            IF(lwp) WRITE(numout,*) '      East Halmahera '
+            ii0 =  55           ;   ii1 =  55        ! East Halmahera Strait 
+            ij0 = 181 - isrow   ;   ij1 = 182 - isrow   ;   pfmsk( mi0(ii0):mi1(ii1),mj0(ij0):mj1(ij1),1:jpk ) = 3._wp  
+            !
+         CASE DEFAULT
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_fmask : ORCA_R', kcfg,' : NO alteration of fmask in specific straits '
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'   
+         END SELECT
+      ELSE
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'usr_def_fmask : NO alteration of fmask in specific straits '
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      CALL lbc_lnk( 'usrdef_fmask', pfmsk, 'F', 1._wp )      ! Lateral boundary conditions on fmask
+      !
+   END SUBROUTINE usr_def_fmask
+   
+   !!======================================================================
+END MODULE usrdef_fmask
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,172 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                     ***  MODULE usrdef_hgr   ***
+   !!
+   !!                     ===  GYRE configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE usrdef_nam     !
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called in domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!
+      !!                Here GYRE configuration :
+      !!          Rectangular mid-latitude domain 
+      !!          - with axes rotated by 45 degrees
+      !!          - a constant horizontal resolution of 106 km 
+      !!          - on a beta-plane
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) ::   zlam1, zlam0, zcos_alpha, zim1 , zjm1 , ze1  , ze1deg, zf0 ! local scalars
+      REAL(wp) ::   zphi1, zphi0, zsin_alpha, zim05, zjm05, zbeta, znorme      !   -      -
+      !!-------------------------------------------------------------------------------
+      !
+      !     !==  beta-plane with regular grid-spacing and rotated domain ==!  (GYRE configuration)
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : GYRE configuration (beta-plane with rotated regular grid-spacing)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      !                       !==  grid point position  ==!
+      !
+      zlam1 = -85._wp                           ! position of gridpoint (i,j) = (1,jpjglo)
+      zphi1 =  29._wp
+      !
+      ze1 = 106000._wp / REAL( nn_GYRE , wp )   ! gridspacing in meters
+      !
+      zsin_alpha = - SQRT( 2._wp ) * 0.5_wp     ! angle: 45 degrees
+      zcos_alpha =   SQRT( 2._wp ) * 0.5_wp
+      ze1deg = ze1 / (ra * rad)
+      zlam0 = zlam1 + zcos_alpha * ze1deg * REAL( jpjglo-2 , wp )
+      zphi0 = zphi1 + zsin_alpha * ze1deg * REAL( jpjglo-2 , wp )
+
+#if defined key_agrif
+      ! ! Upper left longitude and latitude from parent:
+      IF (.NOT.Agrif_root()) THEN
+         zlam0 = zlam1 + Agrif_irhox() * REAL(Agrif_Parent(jpjglo)-2 , wp) * ze1deg * zcos_alpha  &
+                   &   + ( Agrif_Ix()*Agrif_irhox()-(0.5_wp+nbghostcells)) * ze1deg * zcos_alpha  &
+                   &   + ( Agrif_Iy()*Agrif_irhoy()-(0.5_wp+nbghostcells)) * ze1deg * zsin_alpha
+         zphi0 = zphi1 + Agrif_irhoy() * REAL(Agrif_Parent(jpjglo)-2 , wp) * ze1deg * zsin_alpha  &
+                   &   - ( Agrif_Ix()*Agrif_irhox()-nbghostcells )         * ze1deg * zsin_alpha  &
+                   &   + ( Agrif_Iy()*Agrif_irhoy()-nbghostcells )         * ze1deg * zcos_alpha
+      ENDIF 
+#endif
+      !   
+      IF( ln_bench ) THEN     ! benchmark: forced the resolution to be 106 km 
+         ze1 = 106000._wp     ! but keep (lat,lon) at the right nn_GYRE resolution
+         CALL ctl_warn( ' GYRE used as Benchmark: e1=e2=106km, no need to adjust rdt, ahm,aht ' )
+      ENDIF
+      IF( nprint==1 .AND. lwp )   THEN
+         WRITE(numout,*) 'ze1', ze1, 'cosalpha', zcos_alpha, 'sinalpha', zsin_alpha
+         WRITE(numout,*) 'ze1deg', ze1deg, 'zlam0', zlam0, 'zphi0', zphi0
+      ENDIF
+      !   
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+            zim1 = REAL( ji + nimpp - 1 ) - 1.   ;   zim05 = REAL( ji + nimpp - 1 ) - 1.5 
+            zjm1 = REAL( jj + njmpp - 1 ) - 1.   ;   zjm05 = REAL( jj + njmpp - 1 ) - 1.5 
+            !   
+            !glamt(i,j) longitude at T-point
+            !gphit(i,j) latitude at T-point  
+            plamt(ji,jj) = zlam0 + zim05 * ze1deg * zcos_alpha + zjm05 * ze1deg * zsin_alpha
+            pphit(ji,jj) = zphi0 - zim05 * ze1deg * zsin_alpha + zjm05 * ze1deg * zcos_alpha
+            !   
+            !glamu(i,j) longitude at U-point
+            !gphiu(i,j) latitude at U-point
+            plamu(ji,jj) = zlam0 + zim1  * ze1deg * zcos_alpha + zjm05 * ze1deg * zsin_alpha
+            pphiu(ji,jj) = zphi0 - zim1  * ze1deg * zsin_alpha + zjm05 * ze1deg * zcos_alpha
+            !   
+            !glamv(i,j) longitude at V-point
+            !gphiv(i,j) latitude at V-point
+            plamv(ji,jj) = zlam0 + zim05 * ze1deg * zcos_alpha + zjm1  * ze1deg * zsin_alpha
+            pphiv(ji,jj) = zphi0 - zim05 * ze1deg * zsin_alpha + zjm1  * ze1deg * zcos_alpha
+            !
+            !glamf(i,j) longitude at F-point
+            !gphif(i,j) latitude at F-point 
+            plamf(ji,jj) = zlam0 + zim1  * ze1deg * zcos_alpha + zjm1  * ze1deg * zsin_alpha
+            pphif(ji,jj) = zphi0 - zim1  * ze1deg * zsin_alpha + zjm1  * ze1deg * zcos_alpha
+         END DO
+      END DO
+      !
+      !                       !== Horizontal scale factors ==! (in meters)
+      !                     
+      !                                         ! constant grid spacing
+      pe1t(:,:) =  ze1     ;      pe2t(:,:) = ze1
+      pe1u(:,:) =  ze1     ;      pe2u(:,:) = ze1
+      pe1v(:,:) =  ze1     ;      pe2v(:,:) = ze1
+      pe1f(:,:) =  ze1     ;      pe2f(:,:) = ze1
+      !
+      !                                         ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                              !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp                       !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp                       !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                                            !  indicate not to compute ff afterward
+      !
+      zbeta = 2. * omega * COS( rad * zphi1 ) / ra       ! beta at latitude zphi1
+      !SF we overwrite zphi0 (south point in latitude) used just above to define pphif (value of zphi0=15.5190567531966)
+      !SF for computation of Coriolis we keep the parameter of Hazeleger, W., and S. S. Drijfhout, JPO 1998.
+      zphi0 = 15._wp                                     !  latitude of the most southern grid point  
+      zf0   = 2. * omega * SIN( rad * zphi0 )            !  compute f0 1st point south
+      !
+      pff_f(:,:) = ( zf0 + zbeta * ABS( pphif(:,:) - zphi0 ) * rad * ra ) ! f = f0 +beta* y ( y=0 at south)
+      pff_t(:,:) = ( zf0 + zbeta * ABS( pphit(:,:) - zphi0 ) * rad * ra ) ! f = f0 +beta* y ( y=0 at south)
+      !
+      IF(lwp) WRITE(numout,*) '                           beta-plane used. beta = ', zbeta, ' 1/(s.m)'
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,85 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_istate   ***
+   !!
+   !!                     ===  GYRE configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called in istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here GYRE configuration example : (double gyre with rotated domain)
+      !!
+      !! ** Method  : - set temprature field
+      !!              - set salinity   field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER :: ji, jj, jk  ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : analytical definition of initial state '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with an horizontally uniform T and S profiles'
+      !
+      pu  (:,:,:) = 0._wp        ! ocean at rest
+      pv  (:,:,:) = 0._wp
+      pssh(:,:)   = 0._wp
+      !
+      DO jk = 1, jpk             ! horizontally uniform T & S profiles
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               pts(ji,jj,jk,jp_tem) =  (  (  16. - 12. * TANH( (pdept(ji,jj,jk) - 400) / 700 ) )   &
+                    &           * (-TANH( (500. - pdept(ji,jj,jk)) / 150. ) + 1.) / 2.             &
+                    &           + ( 15. * ( 1. - TANH( (pdept(ji,jj,jk)-50.) / 1500.) )            &
+                    &           - 1.4 * TANH((pdept(ji,jj,jk)-100.) / 100.)                        &
+                    &           + 7.  * (1500. - pdept(ji,jj,jk) ) / 1500.)                        &
+                    &           * (-TANH( (pdept(ji,jj,jk) - 500.) / 150.) + 1.) / 2.  ) * ptmask(ji,jj,jk)
+
+               pts(ji,jj,jk,jp_sal) =  (  (  36.25 - 1.13 * TANH( (pdept(ji,jj,jk) - 305) / 460 ) )  &
+                    &         * (-TANH((500. - pdept(ji,jj,jk)) / 150.) + 1.) / 2                  &
+                    &         + ( 35.55 + 1.25 * (5000. - pdept(ji,jj,jk)) / 5000.                 &
+                    &         - 1.62 * TANH( (pdept(ji,jj,jk) - 60.  ) / 650. )                    &
+                    &         + 0.2  * TANH( (pdept(ji,jj,jk) - 35.  ) / 100. )                    &
+                    &         + 0.2  * TANH( (pdept(ji,jj,jk) - 1000.) / 5000.) )                  &
+                    &         * (-TANH( (pdept(ji,jj,jk) - 500.) / 150.) + 1.) / 2  ) * ptmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,109 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                     ***  MODULE usrdef_nam   ***
+   !!
+   !!                     ===  GYRE configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called in nemogcm.F90 module
+
+   !                              !!* namusr_def namelist *!!
+   LOGICAL, PUBLIC ::   ln_bench   ! =T benchmark test with gyre: the gridsize is constant (no need to adjust timestep or viscosity)
+   INTEGER, PUBLIC ::   nn_GYRE    ! 1/nn_GYRE = the resolution chosen in degrees and thus defining the horizontal domain size
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here GYRE configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER         , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER         , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER         , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ nn_GYRE, ln_bench, jpkglo
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'GYRE'               ! name & resolution (not used)
+#if defined key_agrif
+      IF (.NOT.Agrif_root()) nn_GYRE = Agrif_parent(nn_GYRE) * Agrif_irhox()
+#endif
+      kk_cfg = nn_GYRE
+      !
+      kpi = 30 * nn_GYRE + 2        ! Global Domain size
+      kpj = 20 * nn_GYRE + 2
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() ) THEN
+         kpi  = nbcellsx + 2 + 2*nbghostcells
+         kpj  = nbcellsy + 2 + 2*nbghostcells
+      ENDIF
+#endif
+      kpk = jpkglo
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! GYRE configuration : closed domain
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : GYRE case'
+         WRITE(numout,*) '      GYRE used as Benchmark (=T)                      ln_bench  = ', ln_bench
+         WRITE(numout,*) '      inverse resolution & implied domain size         nn_GYRE   = ', nn_GYRE
+#if defined key_agrif
+         IF( Agrif_Root() ) THEN
+#endif
+         WRITE(numout,*) '         jpiglo = 30*nn_GYRE+2                            jpiglo = ', kpi
+         WRITE(numout,*) '         jpjglo = 20*nn_GYRE+2                            jpjglo = ', kpj
+#if defined key_agrif
+         ENDIF
+#endif
+         WRITE(numout,*) '      number of model levels                              jpkglo = ', kpk
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral b.c. of the global domain set to closed        jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,240 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                     ***  MODULE  usrdef_sbc  ***
+   !!
+   !!                     ===  GYRE configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usrdef_sbc    : user defined surface bounday conditions in GYRE case
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers
+   USE dom_oce        ! ocean space and time domain
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran    !
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce       ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau   ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx   ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usrdef_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the GYRE surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   analytical seasonal cycle for GYRE configuration.
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !! Reference : Hazeleger, W., and S. Drijfhout, JPO, 30, 677-695, 2000.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!
+      INTEGER  ::   ji, jj                 ! dummy loop indices
+      INTEGER  ::   zyear0                 ! initial year 
+      INTEGER  ::   zmonth0                ! initial month
+      INTEGER  ::   zday0                  ! initial day
+      INTEGER  ::   zday_year0             ! initial day since january 1st
+      REAL(wp) ::   ztau     , ztau_sais   ! wind intensity and of the seasonal cycle
+      REAL(wp) ::   ztime                  ! time in hour
+      REAL(wp) ::   ztimemax , ztimemin    ! 21th June, and 21th decem. if date0 = 1st january
+      REAL(wp) ::   ztimemax1, ztimemin1   ! 21th June, and 21th decem. if date0 = 1st january
+      REAL(wp) ::   ztimemax2, ztimemin2   ! 21th June, and 21th decem. if date0 = 1st january
+      REAL(wp) ::   ztaun                  ! intensity
+      REAL(wp) ::   zemp_s, zemp_n, zemp_sais, ztstar
+      REAL(wp) ::   zcos_sais1, zcos_sais2, ztrp, zconv, t_star
+      REAL(wp) ::   zsumemp, zsurf
+      REAL(wp) ::   zrhoa  = 1.22         ! Air density kg/m3
+      REAL(wp) ::   zcdrag = 1.5e-3       ! drag coefficient
+      REAL(wp) ::   ztx, zty, zmod, zcoef ! temporary variables
+      REAL(wp) ::   zyydd                 ! number of days in one year
+      !!---------------------------------------------------------------------
+      zyydd = REAL(nyear_len(1),wp)
+
+      ! ---------------------------- !
+      !  heat and freshwater fluxes  !
+      ! ---------------------------- !
+      !same temperature, E-P as in HAZELEGER 2000
+
+      zyear0     =   ndate0 / 10000                             ! initial year
+      zmonth0    = ( ndate0 - zyear0 * 10000 ) / 100            ! initial month
+      zday0      =   ndate0 - zyear0 * 10000 - zmonth0 * 100    ! initial day betwen 1 and 30
+      zday_year0 = ( zmonth0 - 1 ) * 30.+zday0                  ! initial day betwen 1 and 360
+
+      ! current day (in hours) since january the 1st of the current year
+      ztime = REAL( kt ) * rdt / (rmmss * rhhmm)   &       !  total incrementation (in hours)
+         &      - (nyear  - 1) * rjjhh * zyydd             !  minus years since beginning of experiment (in hours)
+
+      ztimemax1 = ((5.*30.)+21.)* 24.                      ! 21th june     at 24h in hours
+      ztimemin1 = ztimemax1 + rjjhh * zyydd / 2            ! 21th december        in hours
+      ztimemax2 = ((6.*30.)+21.)* 24.                      ! 21th july     at 24h in hours
+      ztimemin2 = ztimemax2 - rjjhh * zyydd / 2            ! 21th january         in hours
+      !                                                    ! NB: rjjhh * zyydd / 4 = one seasonal cycle in hours
+
+      ! amplitudes
+      zemp_S    = 0.7       ! intensity of COS in the South
+      zemp_N    = 0.8       ! intensity of COS in the North
+      zemp_sais = 0.1
+      zTstar    = 28.3      ! intemsity from 28.3 a -5 deg
+
+      ! 1/2 period between 21th June and 21th December and between 21th July and 21th January
+      zcos_sais1 = COS( (ztime - ztimemax1) / (ztimemin1 - ztimemax1) * rpi ) 
+      zcos_sais2 = COS( (ztime - ztimemax2) / (ztimemax2 - ztimemin2) * rpi )
+
+      ztrp= - 40.e0        ! retroaction term on heat fluxes (W/m2/K)
+      zconv = 3.16e-5      ! convertion factor: 1 m/yr => 3.16e-5 mm/s
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ! domain from 15 deg to 50 deg between 27 and 28  degC at 15N, -3
+            ! and 13 degC at 50N 53.5 + or - 11 = 1/4 period :
+            ! 64.5 in summer, 42.5 in winter
+            t_star = zTstar * ( 1. + 1. / 50. * zcos_sais2 )                &
+               &                    * COS( rpi * (gphit(ji,jj) - 5.)               &
+               &                    / ( 53.5 * ( 1 + 11 / 53.5 * zcos_sais2 ) * 2.) )
+            ! 23.5 deg : tropics
+            qsr (ji,jj) =  230 * COS( 3.1415 * ( gphit(ji,jj) - 23.5 * zcos_sais1 ) / ( 0.9 * 180 ) )
+            qns (ji,jj) = ztrp * ( tsb(ji,jj,1,jp_tem) - t_star ) - qsr(ji,jj)
+            IF( gphit(ji,jj) >= 14.845 .AND. 37.2 >= gphit(ji,jj) ) THEN    ! zero at 37.8 deg, max at 24.6 deg
+               emp  (ji,jj) =   zemp_S * zconv   &
+                  &         * SIN( rpi / 2 * (gphit(ji,jj) - 37.2) / (24.6 - 37.2) )  &
+                  &         * ( 1 - zemp_sais / zemp_S * zcos_sais1)
+            ELSE
+               emp (ji,jj) =  - zemp_N * zconv   &
+                  &         * SIN( rpi / 2 * (gphit(ji,jj) - 37.2) / (46.8 - 37.2) )  &
+                  &         * ( 1 - zemp_sais / zemp_N * zcos_sais1 )
+            ENDIF
+         END DO
+      END DO
+
+      zsumemp = GLOB_SUM( 'usrdef_sbc', emp  (:,:)   ) 
+      zsurf   = GLOB_SUM( 'usrdef_sbc', tmask(:,:,1) ) 
+      zsumemp = zsumemp / zsurf         ! Default GYRE configuration
+
+      ! freshwater (mass flux) and update of qns with heat content of emp
+      emp (:,:) = emp(:,:) - zsumemp * tmask(:,:,1)        ! freshwater flux (=0 in domain average)
+      sfx (:,:) = 0.0_wp                                   ! no salt flux
+      qns (:,:) = qns(:,:) - emp(:,:) * sst_m(:,:) * rcp   ! evap and precip are at SST
+
+
+      ! ---------------------------- !
+      !       momentum fluxes        !
+      ! ---------------------------- !
+      ! same wind as in Wico
+      !test date0 : ndate0 = 010203
+      zyear0  =   ndate0 / 10000
+      zmonth0 = ( ndate0 - zyear0 * 10000 ) / 100
+      zday0   =   ndate0 - zyear0 * 10000 - zmonth0 * 100
+      !Calculates nday_year, day since january 1st
+      zday_year0 = (zmonth0-1)*30.+zday0
+
+      !accumulates days of previous months of this year
+      ! day (in hours) since january the 1st
+      ztime = FLOAT( kt ) * rdt / (rmmss * rhhmm)  &  ! incrementation in hour
+         &     - (nyear - 1) * rjjhh * zyydd          !  - nber of hours the precedent years
+      ztimemax = ((5.*30.)+21.)* 24.               ! 21th june     in hours
+      ztimemin = ztimemax + rjjhh * zyydd / 2      ! 21th december in hours
+      !                                            ! NB: rjjhh * zyydd / 4 = 1 seasonal cycle in hours
+
+      ! mean intensity at 0.105 ; srqt(2) because projected with 45deg angle
+      ztau = 0.105 / SQRT( 2. )
+      ! seasonal oscillation intensity
+      ztau_sais = 0.015
+      ztaun = ztau - ztau_sais * COS( (ztime - ztimemax) / (ztimemin - ztimemax) * rpi )
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+           ! domain from 15deg to 50deg and 1/2 period along 14deg
+           ! so 5/4 of half period with seasonal cycle
+           utau(ji,jj) = - ztaun * SIN( rpi * (gphiu(ji,jj) - 15.) / (29.-15.) )
+           vtau(ji,jj) =   ztaun * SIN( rpi * (gphiv(ji,jj) - 15.) / (29.-15.) )
+         END DO
+      END DO
+
+      ! module of wind stress and wind speed at T-point
+      zcoef = 1. / ( zrhoa * zcdrag ) 
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vect. opt.
+            ztx = utau(ji-1,jj  ) + utau(ji,jj) 
+            zty = vtau(ji  ,jj-1) + vtau(ji,jj) 
+            zmod = 0.5 * SQRT( ztx * ztx + zty * zty )
+            taum(ji,jj) = zmod
+            wndm(ji,jj) = SQRT( zmod * zcoef )
+         END DO
+      END DO
+      CALL lbc_lnk_multi( 'usrdef_sbc', taum(:,:), 'T', 1. , wndm(:,:), 'T', 1. )
+
+      ! ---------------------------------- !
+      !  control print at first time-step  !
+      ! ---------------------------------- !
+      IF( kt == nit000 .AND. lwp ) THEN 
+         WRITE(numout,*)
+         WRITE(numout,*)'usrdef_sbc_oce : analytical surface fluxes for GYRE configuration'               
+         WRITE(numout,*)'~~~~~~~~~~~ ' 
+         WRITE(numout,*)'           nyear      = ', nyear
+         WRITE(numout,*)'           nmonth     = ', nmonth
+         WRITE(numout,*)'           nday       = ', nday
+         WRITE(numout,*)'           nday_year  = ', nday_year
+         WRITE(numout,*)'           ztime      = ', ztime
+         WRITE(numout,*)'           ztimemax   = ', ztimemax
+         WRITE(numout,*)'           ztimemin   = ', ztimemin
+         WRITE(numout,*)'           ztimemax1  = ', ztimemax1
+         WRITE(numout,*)'           ztimemin1  = ', ztimemin1
+         WRITE(numout,*)'           ztimemax2  = ', ztimemax2
+         WRITE(numout,*)'           ztimemin2  = ', ztimemin2
+         WRITE(numout,*)'           zyear0     = ', zyear0
+         WRITE(numout,*)'           zmonth0    = ', zmonth0
+         WRITE(numout,*)'           zday0      = ', zday0
+         WRITE(numout,*)'           zday_year0 = ', zday_year0
+         WRITE(numout,*)'           zyydd      = ', zyydd
+         WRITE(numout,*)'           zemp_S     = ', zemp_S
+         WRITE(numout,*)'           zemp_N     = ', zemp_N
+         WRITE(numout,*)'           zemp_sais  = ', zemp_sais
+         WRITE(numout,*)'           zTstar     = ', zTstar
+         WRITE(numout,*)'           zsumemp    = ', zsumemp
+         WRITE(numout,*)'           zsurf      = ', zsurf
+         WRITE(numout,*)'           ztrp       = ', ztrp
+         WRITE(numout,*)'           zconv      = ', zconv
+         WRITE(numout,*)'           ndastp     = ', ndastp
+         WRITE(numout,*)'           adatrj     = ', adatrj
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/USR/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,248 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                       ===  GYRE configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-06  (G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE depth_e3       ! depth <=> e3
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   inum   ! local logical unit
+      REAL(WP) ::   z_zco, z_zps, z_sco, z_cav
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : GYRE configuration (z-coordinate closed flat box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .TRUE.         ! GYRE case:  z-coordinate without ocean cavities
+      ld_zps    = .FALSE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      CALL zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      CALL zgr_msk_top_bot( k_top , k_bot )                 ! masked top and bottom ocean t-level indices
+      !
+      !                                                     ! z-coordinate (3D arrays) from the 1D z-coord.
+      CALL zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in  : 1D reference vertical coordinate
+         &          pdept   , pdepw   ,                     &   ! out : 3D t & w-points depth
+         &          pe3t    , pe3u    , pe3v   , pe3f   ,   &   !       vertical scale factors
+         &          pe3w    , pe3uw   , pe3vw             )     !           -      -      -
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z  ***
+      !!
+      !! ** Purpose :   set the 1D depth of model levels and the resulting 
+      !!              vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!           with at top and bottom :
+      !!                   e3w_1d( 1 ) = 2 * ( dept_1d( 1 ) - depw_1d( 1 ) )
+      !!                   e3t_1d(jpk) = 2 * ( dept_1d(jpk) - depw_1d(jpk) )
+      !!       The depth are then re-computed from the sum of e3. This ensures 
+      !!    that depths are identical when reading domain configuration file. 
+      !!    Indeed, only e3. are saved in this file, depth are compute by a call
+      !!    to the e3_to_depth subroutine.
+      !!
+      !!       Here the Madec & Imbard (1996) function is used.
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!
+      !! Reference : Marti, Madec & Delecluse, 1992, JGR, 97, No8, 12,763-12,766.
+      !!             Madec and Imbard, 1996, Clim. Dyn.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zt, zw   ! local scalars
+      REAL(wp) ::   zsur, za0, za1, zkth, zacr   ! Values for the Madec & Imbard (1996) function  
+      !!----------------------------------------------------------------------
+      !
+      ! Set parameters of z(k) function
+      ! -------------------------------
+      zsur = -2033.194295283385_wp       
+      za0  =   155.8325369664153_wp 
+      za1  =   146.3615918601890_wp
+      zkth =    17.28520372419791_wp   
+      zacr =     5.0_wp       
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z   : Reference vertical z-coordinates '
+         WRITE(numout,*) '    ~~~~~~~'
+         WRITE(numout,*) '       GYRE case : MI96 function with the following coefficients :'
+         WRITE(numout,*) '                 zsur = ', zsur
+         WRITE(numout,*) '                 za0  = ', za0
+         WRITE(numout,*) '                 za1  = ', za1
+         WRITE(numout,*) '                 zkth = ', zkth
+         WRITE(numout,*) '                 zacr = ', zacr
+      ENDIF
+
+      !
+      ! 1D Reference z-coordinate    (using Madec & Imbard 1996 function)
+      ! -------------------------
+      !
+      DO jk = 1, jpk          ! depth at T and W-points
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) = ( zsur + za0 * zw + za1 * zacr *  LOG( COSH( (zw-zkth) / zacr ) )  )
+         pdept_1d(jk) = ( zsur + za0 * zt + za1 * zacr *  LOG( COSH( (zt-zkth) / zacr ) )  )
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d ) 
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d ) 
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z
+
+
+   SUBROUTINE zgr_msk_top_bot( k_top , k_bot )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_msk_top_bot  ***
+      !!
+      !! ** Purpose :   set the masked top and bottom ocean t-levels
+      !!
+      !! ** Method  :   GYRE case = closed flat box ocean without ocean cavities
+      !!                   k_top = 1     except along north, south, east and west boundaries
+      !!                   k_bot = jpk-1 except along north, south, east and west boundaries
+      !!
+      !! ** Action  : - k_top : first wet ocean level index
+      !!              - k_bot : last  wet ocean level index
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(out) ::   k_top , k_bot   ! first & last wet ocean level
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D local workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_bot : defines the top and bottom wet ocean levels.'
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '       GYRE case : closed flat box ocean without ocean cavities'
+      !
+      z2d(:,:) = REAL( jpkm1 , wp )          ! flat bottom
+      !
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )           ! set surrounding land to zero (here jperio=0 ==>> closed)
+      !
+      k_bot(:,:) = NINT( z2d(:,:) )           ! =jpkm1 over the ocean point, =0 elsewhere
+      !
+      k_top(:,:) = MIN( 1 , k_bot(:,:) )     ! = 1    over the ocean point, =0 elsewhere
+      !
+   END SUBROUTINE zgr_msk_top_bot
+   
+
+   SUBROUTINE zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in : 1D reference vertical coordinate
+      &                pdept   , pdepw   ,                     &   ! out: 3D t & w-points depth
+      &                pe3t    , pe3u    , pe3v   , pe3f   ,   &   !      vertical scale factors
+      &                pe3w    , pe3uw   , pe3vw             )     !          -      -      -
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zgr_zco  ***
+      !!
+      !! ** Purpose :   define the reference z-coordinate system
+      !!
+      !! ** Method  :   set 3D coord. arrays to reference 1D array 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth       [m]
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pe3t_1d , pe3w_1d           ! 1D vertical scale factors [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth          [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors    [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         !    -       -      -
+      !
+      INTEGER  ::   jk
+      !!----------------------------------------------------------------------
+      !
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE zgr_zco
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdf_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdf_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdf_oce.F90	(revision 14097)
@@ -0,0 +1,76 @@
+MODULE zdf_oce
+   !!======================================================================
+   !!              ***  MODULE  zdf_oce  ***
+   !! Ocean physics : define vertical mixing variables
+   !!=====================================================================
+   !! history :  1.0  !  2002-06  (G. Madec)  Original code
+   !!            3.2  !  2009-07  (G. Madec)  addition of avm
+   !!            4.0  !  2017-05  (G. Madec)  avm and drag coef. defined at t-point
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC  zdf_oce_alloc    ! Called in nemogcm.F90
+
+   !                            !!* namelist namzdf: vertical physics *
+   !                             ! Adaptive-implicit vertical advection flag
+   LOGICAL , PUBLIC ::   ln_zad_Aimp !: adaptive (Courant number-based) implicit vertical advection
+   !                             ! vertical closure scheme flags
+   LOGICAL , PUBLIC ::   ln_zdfcst   !: constant coefficients
+   LOGICAL , PUBLIC ::   ln_zdfric   !: Richardson depend coefficients
+   LOGICAL , PUBLIC ::   ln_zdftke   !: Turbulent Kinetic Energy closure
+   LOGICAL , PUBLIC ::   ln_zdfgls   !: Generic Length Scale closure
+   LOGICAL , PUBLIC ::   ln_zdfosm   !: OSMOSIS BL closure
+   !                             ! convection
+   LOGICAL , PUBLIC ::   ln_zdfevd   !: convection: enhanced vertical diffusion flag
+   INTEGER , PUBLIC ::      nn_evdm     !: =0/1 flag to apply enhanced avm or not
+   REAL(wp), PUBLIC ::      rn_evd      !: vertical eddy coeff. for enhanced vert. diff. (m2/s)
+   LOGICAL , PUBLIC ::   ln_zdfnpc   !: convection: non-penetrative convection flag
+   INTEGER , PUBLIC ::      nn_npc      !: non penetrative convective scheme call  frequency
+   INTEGER , PUBLIC ::      nn_npcp     !: non penetrative convective scheme print frequency
+   !                             ! double diffusion
+   LOGICAL , PUBLIC ::   ln_zdfddm   !: double diffusive mixing flag
+   REAL(wp), PUBLIC ::      rn_avts     !: maximum value of avs for salt fingering
+   REAL(wp), PUBLIC ::      rn_hsbfr    !: heat/salt buoyancy flux ratio
+   !                             ! gravity wave-induced vertical mixing
+   LOGICAL , PUBLIC ::   ln_zdfswm   !: surface  wave-induced mixing flag
+   LOGICAL , PUBLIC ::   ln_zdfiwm   !: internal wave-induced mixing flag
+   !                             ! coefficients 
+   REAL(wp), PUBLIC ::   rn_avm0     !: vertical eddy viscosity (m2/s)
+   REAL(wp), PUBLIC ::   rn_avt0     !: vertical eddy diffusivity (m2/s)
+   INTEGER , PUBLIC ::   nn_avb      !: constant or profile background on avt (=0/1)
+   INTEGER , PUBLIC ::   nn_havtb    !: horizontal shape or not for avtb (=0/1)   !                             ! convection
+
+
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avm, avt, avs  !: vertical mixing coefficients (w-point) [m2/s]
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avm_k , avt_k  !: Kz computed by turbulent closure alone [m2/s]
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   en             !: now turbulent kinetic energy          [m2/s2]
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:)     ::   avmb , avtb    !: background profile of avm and avt      [m2/s]
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   avtb_2d        !: horizontal shape of background Kz profile [-]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!            *** FUNCTION zdf_oce_alloc ***
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( avm (jpi,jpj,jpk) , avm_k(jpi,jpj,jpk) , avs(jpi,jpj,jpk) ,   &
+         &      avt (jpi,jpj,jpk) , avt_k(jpi,jpj,jpk) , en (jpi,jpj,jpk) ,   & 
+         &      avmb(jpk)         , avtb(jpk)          , avtb_2d(jpi,jpj) , STAT = zdf_oce_alloc )
+         !
+      IF( zdf_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_oce_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION zdf_oce_alloc
+
+   !!======================================================================
+END MODULE zdf_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfddm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfddm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfddm.F90	(revision 14097)
@@ -0,0 +1,172 @@
+MODULE zdfddm
+   !!======================================================================
+   !!                       ***  MODULE  zdfddm  ***
+   !! Ocean physics : double diffusion mixing parameterization
+   !!======================================================================
+   !! 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.6  ! 2013-04  (G. Madec, F. Roquet) zrau compute locally using interpolation of alpha & beta
+   !!            4.0  !  2017-04  (G. Madec)  remove CPP ddm key & avm at t-point only 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_ddm       : compute the Kz for salinity
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   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)
+   USE prtctl         ! Print control
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_ddm       ! called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_ddm( kt, p_avm, p_avt, p_avs )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_ddm  ***
+      !!                    
+      !! ** Purpose :   Add to the vertical eddy diffusivity coefficient the 
+      !!              effect of salt fingering and diffusive convection. 
+      !!
+      !! ** Method  :   Diapycnal mixing is increased in case of double
+      !!      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 (R=alpha/beta dk[T]/dk[S]):
+      !!         * salt fingering (Schmitt 1981):
+      !!      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< R < 1 and N^2 > 0 : zavdt = 1.3635e-6 * exp( 4.6 exp(-0.54 (1/R-1) ) )
+      !!      otherwise                   : zavdt = 0 
+      !!      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:
+      !!      avt = avt + zavft + zavdt
+      !!      avs = avs + zavfs + zavds
+      !!      avm is required to remain at least above avt and avs.
+      !!      
+      !! ** Action  :   avt, avs : updated vertical eddy diffusivity coef. for T & S
+      !!
+      !! References :   Merryfield et al., JPO, 29, 1124-1142, 1999.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt       ! ocean time-step indexocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   p_avm   !  Kz on momentum    (w-points)
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   p_avt   !  Kz on temperature (w-points)
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   p_avs   !  Kz on salinity    (w-points)
+      !
+      INTEGER  ::   ji, jj , jk     ! dummy loop indices
+      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), DIMENSION(jpi,jpj) ::   zrau, zmsks, zmskf, zmskd1, zmskd2, zmskd3
+      !!----------------------------------------------------------------------
+      !
+      !                                                ! ===============
+      DO jk = 2, jpkm1                                 ! Horizontal slab
+         !                                             ! ===============
+         ! Define the mask 
+         ! ---------------
+!!gm  WORK to be done:   change the code from vector optimisation to scalar one.
+!!gm                     ==>>>  test in the loop instead of use of mask arrays
+!!gm                            and many acces in memory
+         
+         DO jj = 1, jpj                !==  R=zrau = (alpha / beta) (dk[t] / dk[s])  ==!
+            DO ji = 1, jpi
+               zrw =   ( gdepw_n(ji,jj,jk  ) - gdept_n(ji,jj,jk) )   &
+!!gm please, use e3w_n below 
+                  &  / ( gdept_n(ji,jj,jk-1) - gdept_n(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  ==!
+            DO ji = 1, jpi
+               ! stability indicator: msks=1 if rn2>0; 0 elsewhere
+               IF( rn2(ji,jj,jk) + 1.e-12  <= 0. ) THEN   ;   zmsks(ji,jj) = 0._wp
+               ELSE                                       ;   zmsks(ji,jj) = 1._wp
+               ENDIF
+               ! 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< 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< 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< 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
+         END DO
+         ! mask zmsk in order to have avt and avs masked
+         zmsks(:,:) = zmsks(:,:) * wmask(:,:,jk)
+
+
+         ! Update avt and avs
+         ! ------------------
+         ! Constant eddy coefficient: reset to the background value
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zinr = 1._wp / zrau(ji,jj)
+               ! salt fingering
+               zrr = zrau(ji,jj) / rn_hsbfr
+               zrr = zrr * zrr
+               zavfs = rn_avts / ( 1 + zrr*zrr*zrr ) * zmsks(ji,jj) * zmskf(ji,jj)
+               zavft = 0.7 * zavfs * zinr
+               ! 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 * zrau(ji,jj) - 0.85 ) * zmskd3(ji,jj)   &
+                  &                             +  0.15 * zrau(ji,jj)          * zmskd2(ji,jj)  )
+               ! add to the eddy viscosity coef. previously computed
+               p_avs(ji,jj,jk) = p_avt(ji,jj,jk) + zavfs + zavds
+               p_avt(ji,jj,jk) = p_avt(ji,jj,jk) + zavft + zavdt
+               p_avm(ji,jj,jk) = p_avm(ji,jj,jk) + MAX( zavft + zavdt, zavfs + zavds )
+            END DO
+         END DO
+         !                                                ! ===============
+      END DO                                              !   End of slab
+      !                                                   ! ===============
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl(tab3d_1=avt , clinfo1=' ddm  - t: ', tab3d_2=avs , clinfo2=' s: ', kdim=jpk)
+      ENDIF
+      !
+   END SUBROUTINE zdf_ddm
+   
+   !!======================================================================
+END MODULE zdfddm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfdrg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfdrg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfdrg.F90	(revision 14097)
@@ -0,0 +1,466 @@
+MODULE zdfdrg
+   !!======================================================================
+   !!                       ***  MODULE  zdfdrg  ***
+   !! Ocean physics: top and/or Bottom friction 
+   !!======================================================================
+   !! History :  OPA  ! 1997-06  (G. Madec, A.-M. Treguier)  Original code
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  ! 2009-09  (A.C.Coward)  Correction to include barotropic contribution
+   !!            3.3  ! 2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.4  ! 2011-11  (H. Liu) implementation of semi-implicit bottom friction option
+   !!                 ! 2012-06  (H. Liu) implementation of Log Layer bottom friction option
+   !!            4.0  ! 2017-05  (G. Madec) zdfbfr becomes zdfdrg + variable names change
+   !!                                     + drag defined at t-point + new user interface + top drag (ocean cavities)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_drg       : update bottom friction coefficient (non-linear bottom friction only)
+   !!   zdf_drg_exp   : compute the top & bottom friction in explicit case
+   !!   zdf_drg_init  : read in namdrg namelist and control the bottom friction parameters.
+   !!       drg_init  :
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE phycst  , ONLY : vkarmn
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O module
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing
+   USE prtctl         ! Print control
+   USE sbc_oce , ONLY : nn_ice 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_drg         ! called by zdf_phy
+   PUBLIC   zdf_drg_exp     ! called by dyn_zdf
+   PUBLIC   zdf_drg_init    ! called by zdf_phy_init
+
+   !                                 !!* Namelist namdrg: nature of drag coefficient namelist *
+   LOGICAL , PUBLIC ::   ln_drg_OFF   ! free-slip       : Cd = 0
+   LOGICAL          ::   ln_lin       !     linear  drag: Cd = Cd0_lin
+   LOGICAL          ::   ln_non_lin   ! non-linear  drag: Cd = Cd0_nl |U|
+   LOGICAL          ::   ln_loglayer  ! logarithmic drag: Cd = vkarmn/log(z/z0)
+   LOGICAL , PUBLIC ::   ln_drgimp    ! implicit top/bottom friction flag
+   LOGICAL , PUBLIC ::   ln_drgice_imp ! implicit ice-ocean drag 
+   !                                 !!* Namelist namdrg_top & _bot: TOP or BOTTOM coefficient namelist *
+   REAL(wp)         ::   rn_Cd0       !: drag coefficient                                           [ - ]
+   REAL(wp)         ::   rn_Uc0       !: characteristic velocity (linear case: tau=rho*Cd0*Uc0*u)   [m/s]
+   REAL(wp)         ::   rn_Cdmax     !: drag value maximum (ln_loglayer=T)                         [ - ]
+   REAL(wp)         ::   rn_z0        !: roughness          (ln_loglayer=T)                         [ m ]
+   REAL(wp)         ::   rn_ke0       !: background kinetic energy (non-linear case)                [m2/s2]
+   LOGICAL          ::   ln_boost     !: =T regional boost of Cd0 ; =F Cd0 horizontally uniform
+   REAL(wp)         ::   rn_boost     !: local boost factor                                         [ - ]
+
+   REAL(wp), PUBLIC ::   r_Cdmin_top, r_Cdmax_top, r_z0_top, r_ke0_top   ! set from namdrg_top namelist values
+   REAL(wp), PUBLIC ::   r_Cdmin_bot, r_Cdmax_bot, r_z0_bot, r_ke0_bot   !  -    -  namdrg_bot    -       -
+
+   INTEGER ::              ndrg       ! choice of the type of drag coefficient
+   !                                  ! associated indices:
+   INTEGER, PARAMETER ::   np_OFF      = 0   ! free-slip: drag set to zero
+   INTEGER, PARAMETER ::   np_lin      = 1   !     linear drag: Cd = Cd0_lin
+   INTEGER, PARAMETER ::   np_non_lin  = 2   ! non-linear drag: Cd = Cd0_nl |U|
+   INTEGER, PARAMETER ::   np_loglayer = 3   ! non linear drag (logarithmic formulation): Cd = vkarmn/log(z/z0)
+
+   LOGICAL , PUBLIC ::   l_zdfdrg           !: flag to update at each time step the top/bottom Cd
+   LOGICAL          ::   l_log_not_linssh   !: flag to update at each time step the position ot the velocity point 
+   !
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   rCd0_top, rCd0_bot   !: precomputed top/bottom drag coeff. at t-point (>0)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   rCdU_top, rCdU_bot   !: top/bottom drag coeff. at t-point (<0)  [m/s]
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_drg( kt, k_mk, pCdmin, pCdmax, pz0, pke0, pCd0,   &   ! <<== in 
+      &                                                     pCdU )      ! ==>> out : bottom drag [m/s]
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_drg  ***
+      !!
+      !! ** Purpose :   update the top/bottom drag coefficient (non-linear case only)
+      !!
+      !! ** Method  :   In non linear friction case, the drag coeficient is
+      !!              a function of the velocity:
+      !!                          Cd = cd0 * |U+Ut|   
+      !!              where U is the top or bottom velocity and
+      !!                    Ut a tidal velocity (Ut^2 = Tidal kinetic energy 
+      !!                       assumed here here to be constant) 
+      !!              Depending on the input variable, the top- or bottom drag is compted
+      !!
+      !! ** Action  :   p_Cd   drag coefficient at t-point
+      !!----------------------------------------------------------------------
+      INTEGER                 , INTENT(in   ) ::   kt       ! ocean time-step index
+      !                       !               !!         !==  top or bottom variables  ==!
+      INTEGER , DIMENSION(:,:), INTENT(in   ) ::   k_mk     ! wet level (1st or last)
+      REAL(wp)                , INTENT(in   ) ::   pCdmin   ! min drag value
+      REAL(wp)                , INTENT(in   ) ::   pCdmax   ! max drag value
+      REAL(wp)                , INTENT(in   ) ::   pz0      ! roughness
+      REAL(wp)                , INTENT(in   ) ::   pke0     ! background tidal KE
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   pCd0     ! masked precomputed part of Cd0
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pCdU     ! = - Cd*|U|   (t-points) [m/s]
+      !!
+      INTEGER ::   ji, jj   ! dummy loop indices
+      INTEGER ::   imk      ! local integers
+      REAL(wp)::   zzz, zut, zvt, zcd   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      IF( l_log_not_linssh ) THEN     !==  "log layer"  ==!   compute Cd and -Cd*|U|
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               imk = k_mk(ji,jj)          ! ocean bottom level at t-points
+               zut = un(ji,jj,imk) + un(ji-1,jj,imk)     ! 2 x velocity at t-point
+               zvt = vn(ji,jj,imk) + vn(ji,jj-1,imk)
+               zzz = 0.5_wp * e3t_n(ji,jj,imk)           ! altitude below/above (top/bottom) the boundary
+               !
+!!JC: possible WAD implementation should modify line below if layers vanish
+               zcd = (  vkarmn / LOG( zzz / pz0 )  )**2
+               zcd = pCd0(ji,jj) * MIN(  MAX( pCdmin , zcd ) , pCdmax  )   ! here pCd0 = mask*boost
+               pCdU(ji,jj) = - zcd * SQRT(  0.25 * ( zut*zut + zvt*zvt ) + pke0  )
+            END DO
+         END DO
+      ELSE                                            !==  standard Cd  ==!
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               imk = k_mk(ji,jj)    ! ocean bottom level at t-points
+               zut = un(ji,jj,imk) + un(ji-1,jj,imk)     ! 2 x velocity at t-point
+               zvt = vn(ji,jj,imk) + vn(ji,jj-1,imk)
+               !                                                           ! here pCd0 = mask*boost * drag
+               pCdU(ji,jj) = - pCd0(ji,jj) * SQRT(  0.25 * ( zut*zut + zvt*zvt ) + pke0  )
+            END DO
+         END DO
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=pCdU, clinfo1=' Cd*U ')
+      !
+   END SUBROUTINE zdf_drg
+
+
+   SUBROUTINE zdf_drg_exp( kt, pub, pvb, pua, pva )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_drg_exp  ***
+      !!
+      !! ** Purpose :   compute and add the explicit top and bottom frictions.
+      !!
+      !! ** Method  :   in explicit case, 
+      !!
+      !!              NB: in implicit case the calculation is performed in dynzdf.F90
+      !!
+      !! ** Action  :   (pua,pva)   momentum trend increased by top & bottom friction trend
+      !!---------------------------------------------------------------------
+      INTEGER                         , INTENT(in   ) ::   kt         ! ocean time-step index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pub, pvb   ! the two components of the before velocity
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   pua, pva   ! the two components of the velocity tendency
+      !! 
+      INTEGER  ::   ji, jj       ! dummy loop indexes
+      INTEGER  ::   ikbu, ikbv   ! local integers
+      REAL(wp) ::   zm1_2dt      ! local scalar
+      REAL(wp) ::   zCdu, zCdv   !   -      -
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdu, ztrdv
+      !!---------------------------------------------------------------------
+      !
+!!gm bug : time step is only rdt (not 2 rdt if euler start !)
+      zm1_2dt = - 1._wp / ( 2._wp * rdt )
+
+      IF( l_trddyn ) THEN      ! trends: store the input trends
+         ALLOCATE( ztrdu(jpi,jpj,jpk) , ztrdv(jpi,jpj,jpk) )
+         ztrdu(:,:,:) = pua(:,:,:)
+         ztrdv(:,:,:) = pva(:,:,:)
+      ENDIF
+
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            ikbu = mbku(ji,jj)          ! deepest wet ocean u- & v-levels
+            ikbv = mbkv(ji,jj)
+            !
+            ! Apply stability criteria on absolute value  : abs(bfr/e3) < 1/(2dt) => bfr/e3 > -1/(2dt)
+            zCdu = 0.5*( rCdU_bot(ji+1,jj)+rCdU_bot(ji,jj) ) / e3u_n(ji,jj,ikbu)
+            zCdv = 0.5*( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj) ) / e3v_n(ji,jj,ikbv)
+            !
+            pua(ji,jj,ikbu) = pua(ji,jj,ikbu) + MAX(  zCdu , zm1_2dt  ) * pub(ji,jj,ikbu)
+            pva(ji,jj,ikbv) = pva(ji,jj,ikbv) + MAX(  zCdv , zm1_2dt  ) * pvb(ji,jj,ikbv)
+         END DO
+      END DO
+      !
+      IF( ln_isfcav ) THEN        ! ocean cavities
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               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)
+               zCdu = 0.5*( rCdU_top(ji+1,jj)+rCdU_top(ji,jj) ) / e3u_n(ji,jj,ikbu)    ! NB: Cdtop masked
+               zCdv = 0.5*( rCdU_top(ji,jj+1)+rCdU_top(ji,jj) ) / e3v_n(ji,jj,ikbv)
+               !
+               pua(ji,jj,ikbu) = pua(ji,jj,ikbu) + MAX(  zCdu , zm1_2dt  ) * pub(ji,jj,ikbu)
+               pva(ji,jj,ikbv) = pva(ji,jj,ikbv) + MAX(  zCdv , zm1_2dt  ) * pvb(ji,jj,ikbv)
+           END DO
+         END DO
+      ENDIF
+      !
+      IF( l_trddyn ) THEN      ! trends: send trends to trddyn for further diagnostics
+         ztrdu(:,:,:) = pua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = pva(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu(:,:,:), ztrdv(:,:,:), jpdyn_bfr, kt )
+         DEALLOCATE( ztrdu, ztrdv )
+      ENDIF
+      !                                          ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pua, clinfo1=' bfr  - Ua: ', mask1=umask,               &
+         &                       tab3d_2=pva, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+   END SUBROUTINE zdf_drg_exp
+
+
+   SUBROUTINE zdf_drg_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_brg_init  ***
+      !!
+      !! ** Purpose :   Initialization of the bottom friction
+      !!
+      !! ** Method  :   Read the namdrg namelist and check their consistency
+      !!                called at the first timestep (nit000)
+      !!----------------------------------------------------------------------
+      INTEGER   ::   ji, jj      ! dummy loop indexes
+      INTEGER   ::   ios, ioptio   ! local integers
+      !!
+      NAMELIST/namdrg/ ln_drg_OFF, ln_lin, ln_non_lin, ln_loglayer, ln_drgimp, ln_drgice_imp
+      !!----------------------------------------------------------------------
+      !
+      !                     !==  drag nature  ==!
+      !
+      REWIND( numnam_ref )                   ! Namelist namdrg in reference namelist
+      READ  ( numnam_ref, namdrg, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam( ios , 'namdrg in reference namelist' )
+      REWIND( numnam_cfg )                   ! Namelist namdrg in configuration namelist
+      READ  ( numnam_cfg, namdrg, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam( ios , 'namdrg in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdrg )
+      !
+      IF( ln_drgice_imp .AND. nn_ice /= 2 )   ln_drgice_imp = .FALSE.
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_drg_init : top and/or bottom drag setting'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namdrg : top/bottom friction choices'
+         WRITE(numout,*) '      free-slip       : Cd = 0                  ln_drg_OFF  = ', ln_drg_OFF 
+         WRITE(numout,*) '      linear  drag    : Cd = Cd0                ln_lin      = ', ln_lin
+         WRITE(numout,*) '      non-linear  drag: Cd = Cd0_nl |U|         ln_non_lin  = ', ln_non_lin
+         WRITE(numout,*) '      logarithmic drag: Cd = vkarmn/log(z/z0)   ln_loglayer = ', ln_loglayer
+         WRITE(numout,*) '      implicit friction                         ln_drgimp   = ', ln_drgimp
+         WRITE(numout,*) '      implicit ice-ocean drag                   ln_drgice_imp  =', ln_drgice_imp
+      ENDIF
+      !
+      ioptio = 0                       ! set ndrg and control check
+      IF( ln_drg_OFF  ) THEN   ;   ndrg = np_OFF        ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_lin      ) THEN   ;   ndrg = np_lin        ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_non_lin  ) THEN   ;   ndrg = np_non_lin    ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_loglayer ) THEN   ;   ndrg = np_loglayer   ;   ioptio = ioptio + 1   ;   ENDIF
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'zdf_drg_init: Choose ONE type of drag coef in namdrg' )
+      !
+      IF ( ln_drgice_imp.AND.(.NOT.ln_drgimp) ) & 
+         &                CALL ctl_stop( 'zdf_drg_init: ln_drgice_imp=T requires ln_drgimp=T' )
+      !
+      !                     !==  BOTTOM drag setting  ==!   (applied at seafloor)
+      !
+      ALLOCATE( rCd0_bot(jpi,jpj), rCdU_bot(jpi,jpj) )
+      CALL drg_init( 'BOTTOM'   , mbkt       ,                                         &   ! <== in
+         &           r_Cdmin_bot, r_Cdmax_bot, r_z0_bot, r_ke0_bot, rCd0_bot, rCdU_bot )   ! ==> out
+      !
+      !                     !==  TOP drag setting  ==!   (applied at the top of ocean cavities)
+      !
+      IF( ln_isfcav.OR.ln_drgice_imp ) THEN              ! Ocean cavities: top friction setting
+         ALLOCATE( rCdU_top(jpi,jpj) )
+      ENDIF
+      !
+      IF( ln_isfcav ) THEN
+         ALLOCATE( rCd0_top(jpi,jpj))
+         CALL drg_init( 'TOP   '   , mikt       ,                                         &   ! <== in
+            &           r_Cdmin_top, r_Cdmax_top, r_z0_top, r_ke0_top, rCd0_top, rCdU_top )   ! ==> out
+      ENDIF
+      !
+   END SUBROUTINE zdf_drg_init
+
+
+   SUBROUTINE drg_init( cd_topbot, k_mk,  &
+      &                 pCdmin, pCdmax, pz0, pke0, pCd0, pCdU ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE drg_init  ***
+      !!
+      !! ** Purpose :   Initialization of the top/bottom friction CdO and Cd
+      !!              from namelist parameters
+      !!----------------------------------------------------------------------
+      CHARACTER(len=6)        , INTENT(in   ) ::   cd_topbot       ! top/ bot indicator
+      INTEGER , DIMENSION(:,:), INTENT(in   ) ::   k_mk            ! 1st/last  wet level 
+      REAL(wp)                , INTENT(  out) ::   pCdmin, pCdmax  ! min and max drag coef. [-]
+      REAL(wp)                , INTENT(  out) ::   pz0             ! roughness              [m]
+      REAL(wp)                , INTENT(  out) ::   pke0            ! background KE          [m2/s2]
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pCd0            ! masked precomputed part of the non-linear drag coefficient
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   pCdU            ! minus linear drag*|U| at t-points  [m/s]
+      !!
+      CHARACTER(len=40) ::   cl_namdrg, cl_file, cl_varname, cl_namref, cl_namcfg  ! local names 
+      INTEGER ::   ji, jj              ! dummy loop indexes
+      LOGICAL ::   ll_top, ll_bot      ! local logical
+      INTEGER ::   ios, inum, imk      ! local integers
+      REAL(wp)::   zmsk, zzz, zcd      ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk_boost   ! 2D workspace
+      !!
+      NAMELIST/namdrg_top/ rn_Cd0, rn_Uc0, rn_Cdmax, rn_ke0, rn_z0, ln_boost, rn_boost
+      NAMELIST/namdrg_bot/ rn_Cd0, rn_Uc0, rn_Cdmax, rn_ke0, rn_z0, ln_boost, rn_boost
+      !!----------------------------------------------------------------------
+      !
+      !                          !==  set TOP / BOTTOM specificities  ==!
+      ll_top = .FALSE.
+      ll_bot = .FALSE.
+      !
+      SELECT CASE (cd_topbot)
+      CASE( 'TOP   ' )
+         ll_top = .TRUE.
+         cl_namdrg  = 'namdrg_top'
+         cl_namref  = 'namdrg_top in reference     namelist'
+         cl_namcfg  = 'namdrg_top in configuration namelist'
+         cl_file    = 'tfr_coef.nc'
+         cl_varname = 'tfr_coef'
+      CASE( 'BOTTOM' )
+         ll_bot = .TRUE.
+         cl_namdrg  = 'namdrg_bot'
+         cl_namref  = 'namdrg_bot  in reference     namelist'
+         cl_namcfg  = 'namdrg_bot  in configuration namelist'
+         cl_file    = 'bfr_coef.nc'
+         cl_varname = 'bfr_coef'
+      CASE DEFAULT
+         CALL ctl_stop( 'drg_init: bad value for cd_topbot ' )
+      END SELECT
+      !
+      !                          !==  read namlist  ==!
+      !
+      REWIND( numnam_ref )                   ! Namelist cl_namdrg in reference namelist
+      IF(ll_top)   READ  ( numnam_ref, namdrg_top, IOSTAT = ios, ERR = 901)
+      IF(ll_bot)   READ  ( numnam_ref, namdrg_bot, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam( ios , TRIM(cl_namref) )
+      REWIND( numnam_cfg )                   ! Namelist cd_namdrg in configuration namelist
+      IF(ll_top)   READ  ( numnam_cfg, namdrg_top, IOSTAT = ios, ERR = 902 )
+      IF(ll_bot)   READ  ( numnam_cfg, namdrg_bot, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam( ios , TRIM(cl_namcfg) )
+      IF(lwm .AND. ll_top)   WRITE ( numond, namdrg_top )
+      IF(lwm .AND. ll_bot)   WRITE ( numond, namdrg_bot )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist ',TRIM(cl_namdrg),' : set ',TRIM(cd_topbot),' friction parameters'
+         WRITE(numout,*) '      drag coefficient                        rn_Cd0   = ', rn_Cd0
+         WRITE(numout,*) '      characteristic velocity (linear case)   rn_Uc0   = ', rn_Uc0, ' m/s'
+         WRITE(numout,*) '      non-linear drag maximum                 rn_Cdmax = ', rn_Cdmax
+         WRITE(numout,*) '      background kinetic energy  (n-l case)   rn_ke0   = ', rn_ke0
+         WRITE(numout,*) '      bottom roughness           (n-l case)   rn_z0    = ', rn_z0
+         WRITE(numout,*) '      set a regional boost of Cd0             ln_boost = ', ln_boost
+         WRITE(numout,*) '         associated boost factor              rn_boost = ', rn_boost
+      ENDIF
+      !
+      !                          !==  return some namelist parametres  ==!   (used in non_lin and loglayer cases)
+      pCdmin = rn_Cd0
+      pCdmax = rn_Cdmax
+      pz0    = rn_z0
+      pke0   = rn_ke0
+      !
+      !                          !==  mask * boost factor  ==!
+      !
+      IF( ln_boost ) THEN           !* regional boost:   boost factor = 1 + regional boost
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   use a regional boost read in ', TRIM(cl_file), ' file'
+         IF(lwp) WRITE(numout,*) '           using enhancement factor of ', rn_boost
+         ! cl_varname is a coefficient in [0,1] giving where to apply the regional boost
+         CALL iom_open ( TRIM(cl_file), inum )
+         CALL iom_get  ( inum, jpdom_data, TRIM(cl_varname), zmsk_boost, 1 )
+         CALL iom_close( inum)
+         zmsk_boost(:,:) = 1._wp + rn_boost * zmsk_boost(:,:)
+         !
+      ELSE                          !* no boost:   boost factor = 1
+         zmsk_boost(:,:) = 1._wp
+      ENDIF
+      !                             !* mask outside ocean cavities area (top) or land area (bot)
+      IF(ll_top)   zmsk_boost(:,:) = zmsk_boost(:,:) * ssmask(:,:) * (1. - tmask(:,:,1) )  ! none zero in ocean cavities only
+      IF(ll_bot)   zmsk_boost(:,:) = zmsk_boost(:,:) * ssmask(:,:)                         ! x seafloor mask
+      !
+      !
+      SELECT CASE( ndrg )
+      !
+      CASE( np_OFF  )            !==  No top/bottom friction  ==!   (pCdU = 0)
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   ',TRIM(cd_topbot),' free-slip, friction set to zero'
+         !
+         l_zdfdrg = .FALSE.         ! no time variation of the drag: set it one for all
+         !
+         pCdU(:,:) = 0._wp
+         pCd0(:,:) = 0._wp
+         !
+      CASE( np_lin )             !==  linear friction  ==!   (pCdU = Cd0 * Uc0)
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   linear ',TRIM(cd_topbot),' friction (constant coef = Cd0*Uc0 = ', rn_Cd0*rn_Uc0, ')'
+         !
+         l_zdfdrg = .FALSE.         ! no time variation of the Cd*|U| : set it one for all
+         !                      
+         pCd0(:,:) = rn_Cd0 * zmsk_boost(:,:)  !* constant in time drag coefficient (= mask (and boost) Cd0)
+         pCdU(:,:) = - pCd0(:,:) * rn_Uc0      !  using a constant velocity
+         !
+      CASE( np_non_lin )         !== non-linear friction  ==!   (pCd0 = Cd0 )
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   quadratic ',TRIM(cd_topbot),' friction (propotional to module of the velocity)'
+         IF(lwp) WRITE(numout,*) '   with    a drag coefficient Cd0 = ', rn_Cd0, ', and'
+         IF(lwp) WRITE(numout,*) '           a background velocity module of (rn_ke0)^1/2 = ', SQRT(rn_ke0), 'm/s)'
+         !
+         l_zdfdrg = .TRUE.          !* Cd*|U| updated at each time-step (it depends on ocean velocity)
+         !
+         pCd0(:,:) = rn_Cd0 * zmsk_boost(:,:)  !* constant in time proportionality coefficient (= mask (and boost) Cd0)
+         pCdU(:,:) = 0._wp                     !  
+         !
+      CASE( np_loglayer )       !== logarithmic layer formulation of friction  ==!   (CdU = (vkarman log(z/z0))^2 |U| )
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   quadratic ',TRIM(cd_topbot),' drag (propotional to module of the velocity)'
+         IF(lwp) WRITE(numout,*) '   with   a logarithmic Cd0 formulation Cd0 = ( vkarman log(z/z0) )^2 ,'
+         IF(lwp) WRITE(numout,*) '          a background velocity module of (rn_ke0)^1/2 = ', SQRT(pke0), 'm/s), '
+         IF(lwp) WRITE(numout,*) '          a logarithmic formulation: a roughness of ', pz0, ' meters,   and '
+         IF(lwp) WRITE(numout,*) '          a proportionality factor bounded by min/max values of ', pCdmin, pCdmax
+         !
+         l_zdfdrg = .TRUE.          !* Cd*|U| updated at each time-step (it depends on ocean velocity)
+         !
+         IF( ln_linssh ) THEN       !* pCd0 = (v log(z/z0))^2   as velocity points have a fixed z position
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   N.B.   linear free surface case, Cd0 computed one for all'
+            !
+            l_log_not_linssh = .FALSE.    !- don't update Cd at each time step
+            !
+            DO jj = 1, jpj                   ! pCd0 = mask (and boosted) logarithmic drag coef. 
+               DO ji = 1, jpi
+                  zzz =  0.5_wp * e3t_0(ji,jj,k_mk(ji,jj))
+                  zcd = (  vkarmn / LOG( zzz / rn_z0 )  )**2
+                  pCd0(ji,jj) = zmsk_boost(ji,jj) * MIN(  MAX( rn_Cd0 , zcd ) , rn_Cdmax  )  ! rn_Cd0 < Cd0 < rn_Cdmax
+               END DO
+            END DO
+         ELSE                       !* Cd updated at each time-step ==> pCd0 = mask * boost
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   N.B.   non-linear free surface case, Cd0 updated at each time-step '
+            !
+            l_log_not_linssh = .TRUE.     ! compute the drag coef. at each time-step 
+            !
+            pCd0(:,:) = zmsk_boost(:,:)
+         ENDIF
+         pCdU(:,:) = 0._wp          ! initialisation to zero (will be updated at each time step)
+         !
+      CASE DEFAULT
+         CALL ctl_stop( 'drg_init: bad flag value for ndrg ' )
+      END SELECT
+      !
+   END SUBROUTINE drg_init
+
+   !!======================================================================
+END MODULE zdfdrg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfevd.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfevd.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfevd.F90	(revision 14097)
@@ -0,0 +1,124 @@
+MODULE zdfevd
+   !!======================================================================
+   !!                       ***  MODULE  zdfevd  ***
+   !! Ocean physics: parameterization of convection through an enhancement
+   !!                of vertical eddy mixing coefficient
+   !!======================================================================
+   !! History :  OPA  !  1997-06  (G. Madec, A. Lazar)  Original code
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            3.2  !  2009-03  (M. Leclair, G. Madec, R. Benshila) test on both before & after
+   !!            4.0  !  2017-04  (G. Madec)  evd applied on avm (at t-point) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_evd       : increase the momentum and tracer Kz at the location of
+   !!                   statically unstable portion of the water column (ln_zdfevd=T)
+   !!----------------------------------------------------------------------
+   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 trdtra          ! trends manager: tracers 
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! for iom_put
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_evd    ! called by step.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_evd( kt, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_evd  ***
+      !!                   
+      !! ** Purpose :   Local increased the vertical eddy viscosity and diffu-
+      !!      sivity coefficients when a static instability is encountered.
+      !!
+      !! ** Method  :   tracer (and momentum if nn_evdm=1) vertical mixing 
+      !!              coefficients are set to rn_evd (namelist parameter) 
+      !!              if the water column is statically unstable.
+      !!                The test of static instability is performed using
+      !!              Brunt-Vaisala frequency (rn2 < -1.e-12) of to successive
+      !!              time-step (Leap-Frog environnement): before and
+      !!              now time-step.
+      !!
+      !! ** Action  :   avt, avm   enhanced where static instability occurs
+      !!----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   ) ::   kt             ! ocean time-step indexocean time step
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avm, p_avt   !  momentum and tracer Kz (w-points)
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zavt_evd, zavm_evd
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'zdf_evd : Enhanced Vertical Diffusion (evd)'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+         IF(lwp) WRITE(numout,*)
+      ENDIF
+      !
+      !
+      zavt_evd(:,:,:) = p_avt(:,:,:)         ! set avt prior to evd application
+      !
+      SELECT CASE ( nn_evdm )
+      !
+      CASE ( 1 )           !==  enhance tracer & momentum Kz  ==!   (if rn2<-1.e-12)
+         !
+         zavm_evd(:,:,:) = p_avm(:,:,:)      ! set avm prior to evd application
+         !
+!! change last digits results
+!         WHERE( MAX( rn2(2:jpi,2:jpj,2:jpkm1), rn2b(2:jpi,2:jpj,2:jpkm1) )  <= -1.e-12 ) THEN
+!            p_avt(2:jpi,2:jpj,2:jpkm1) = rn_evd * wmask(2:jpi,2:jpj,2:jpkm1)
+!            p_avm(2:jpi,2:jpj,2:jpkm1) = rn_evd * wmask(2:jpi,2:jpj,2:jpkm1)
+!         END WHERE
+         !
+         DO jk = 1, jpkm1 
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  IF(  MIN( rn2(ji,jj,jk), rn2b(ji,jj,jk) ) <= -1.e-12 ) THEN
+                     p_avt(ji,jj,jk) = rn_evd * wmask(ji,jj,jk)
+                     p_avm(ji,jj,jk) = rn_evd * wmask(ji,jj,jk)
+                  ENDIF
+               END DO
+            END DO
+         END DO 
+         !
+         zavm_evd(:,:,:) = p_avm(:,:,:) - zavm_evd(:,:,:)   ! change in avm due to evd
+         CALL iom_put( "avm_evd", zavm_evd )                ! output this change
+         !
+      CASE DEFAULT         !==  enhance tracer Kz  ==!   (if rn2<-1.e-12) 
+!! change last digits results
+!         WHERE( MAX( rn2(2:jpi,2:jpj,2:jpkm1), rn2b(2:jpi,2:jpj,2:jpkm1) )  <= -1.e-12 )
+!            p_avt(2:jpi,2:jpj,2:jpkm1) = rn_evd * wmask(2:jpi,2:jpj,2:jpkm1)
+!         END WHERE
+
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  IF(  MIN( rn2(ji,jj,jk), rn2b(ji,jj,jk) ) <= -1.e-12 )   &
+                     p_avt(ji,jj,jk) = rn_evd * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT 
+      !
+      zavt_evd(:,:,:) = p_avt(:,:,:) - zavt_evd(:,:,:)   ! change in avt due to evd
+      CALL iom_put( "avt_evd", zavt_evd )              ! output this change
+      IF( l_trdtra ) CALL trd_tra( kt, 'TRA', jp_tem, jptra_evd, zavt_evd )
+      !
+   END SUBROUTINE zdf_evd
+
+   !!======================================================================
+END MODULE zdfevd
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfgls.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfgls.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfgls.F90	(revision 14097)
@@ -0,0 +1,1238 @@
+MODULE zdfgls
+   !!======================================================================
+   !!                       ***  MODULE  zdfgls  ***
+   !! Ocean physics:  vertical mixing coefficient computed from the gls 
+   !!                 turbulent closure parameterization
+   !!======================================================================
+   !! History :  3.0  !  2009-09  (G. Reffray)  Original code
+   !!            3.3  !  2010-10  (C. Bricaud)  Add in the reference
+   !!            4.0  !  2017-04  (G. Madec)  remove CPP keys & avm at t-point only 
+   !!             -   !  2017-05  (G. Madec)  add top friction as boundary condition
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_gls       : update momentum and tracer Kz from a gls scheme
+   !!   zdf_gls_init  : initialization, namelist read, and parameters control
+   !!   gls_rst       : read/write gls restart in ocean restart file
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE domvvl         ! ocean space and time domain : variable volume layer
+   USE zdfdrg  , ONLY : ln_drg_OFF            ! top/bottom free-slip flag
+   USE zdfdrg  , ONLY : r_z0_top , r_z0_bot   ! top/bottom roughness
+   USE zdfdrg  , ONLY : rCdU_top , rCdU_bot   ! top/bottom friction
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE phycst         ! physical constants
+   USE zdfmxl         ! mixed layer
+   USE sbcwave , ONLY : hsw   ! significant wave height
+   !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! MPP manager
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_gls        ! called in zdfphy
+   PUBLIC   zdf_gls_init   ! called in zdfphy
+   PUBLIC   gls_rst        ! called in zdfphy
+
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hmxl_n    !: now mixing length
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   zwall   !: wall function
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ustar2_surf !: Squared surface velocity scale at T-points
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ustar2_top  !: Squared top     velocity scale at T-points
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ustar2_bot  !: Squared bottom  velocity scale at T-points
+
+   !                              !! ** Namelist  namzdf_gls  **
+   LOGICAL  ::   ln_length_lim     ! use limit on the dissipation rate under stable stratification (Galperin et al. 1988)
+   LOGICAL  ::   ln_sigpsi         ! Activate Burchard (2003) modification for k-eps closure & wave breaking mixing
+   INTEGER  ::   nn_bc_surf        ! surface boundary condition (=0/1)
+   INTEGER  ::   nn_bc_bot         ! bottom boundary condition (=0/1)
+   INTEGER  ::   nn_z0_met         ! Method for surface roughness computation
+   INTEGER  ::   nn_z0_ice         ! Roughness accounting for sea ice
+   INTEGER  ::   nn_stab_func      ! stability functions G88, KC or Canuto (=0/1/2)
+   INTEGER  ::   nn_clos           ! closure 0/1/2/3 MY82/k-eps/k-w/gen
+   REAL(wp) ::   rn_clim_galp      ! Holt 2008 value for k-eps: 0.267
+   REAL(wp) ::   rn_epsmin         ! minimum value of dissipation (m2/s3)
+   REAL(wp) ::   rn_emin           ! minimum value of TKE (m2/s2)
+   REAL(wp) ::   rn_charn          ! Charnock constant for surface breaking waves mixing : 1400. (standard) or 2.e5 (Stacey value)
+   REAL(wp) ::   rn_crban          ! Craig and Banner constant for surface breaking waves mixing
+   REAL(wp) ::   rn_hsro           ! Minimum surface roughness
+   REAL(wp) ::   rn_hsri           ! Ice ocean roughness
+   REAL(wp) ::   rn_frac_hs        ! Fraction of wave height as surface roughness (if nn_z0_met > 1) 
+
+   REAL(wp) ::   rcm_sf        =  0.73_wp     ! Shear free turbulence parameters
+   REAL(wp) ::   ra_sf         = -2.0_wp      ! Must be negative -2 < ra_sf < -1 
+   REAL(wp) ::   rl_sf         =  0.2_wp      ! 0 <rl_sf<vkarmn    
+   REAL(wp) ::   rghmin        = -0.28_wp
+   REAL(wp) ::   rgh0          =  0.0329_wp
+   REAL(wp) ::   rghcri        =  0.03_wp
+   REAL(wp) ::   ra1           =  0.92_wp
+   REAL(wp) ::   ra2           =  0.74_wp
+   REAL(wp) ::   rb1           = 16.60_wp
+   REAL(wp) ::   rb2           = 10.10_wp         
+   REAL(wp) ::   re2           =  1.33_wp         
+   REAL(wp) ::   rl1           =  0.107_wp
+   REAL(wp) ::   rl2           =  0.0032_wp
+   REAL(wp) ::   rl3           =  0.0864_wp
+   REAL(wp) ::   rl4           =  0.12_wp
+   REAL(wp) ::   rl5           = 11.9_wp
+   REAL(wp) ::   rl6           =  0.4_wp
+   REAL(wp) ::   rl7           =  0.0_wp
+   REAL(wp) ::   rl8           =  0.48_wp
+   REAL(wp) ::   rm1           =  0.127_wp
+   REAL(wp) ::   rm2           =  0.00336_wp
+   REAL(wp) ::   rm3           =  0.0906_wp
+   REAL(wp) ::   rm4           =  0.101_wp
+   REAL(wp) ::   rm5           = 11.2_wp
+   REAL(wp) ::   rm6           =  0.4_wp
+   REAL(wp) ::   rm7           =  0.0_wp
+   REAL(wp) ::   rm8           =  0.318_wp
+   REAL(wp) ::   rtrans        =  0.1_wp
+   REAL(wp) ::   rc02, rc02r, rc03, rc04                          ! coefficients deduced from above parameters
+   REAL(wp) ::   rsbc_tke1, rsbc_tke2, rfact_tke                  !     -           -           -        -
+   REAL(wp) ::   rsbc_psi1, rsbc_psi2, rfact_psi                  !     -           -           -        -
+   REAL(wp) ::   rsbc_zs1, rsbc_zs2                               !     -           -           -        -
+   REAL(wp) ::   rc0, rc2, rc3, rf6, rcff, rc_diff                !     -           -           -        -
+   REAL(wp) ::   rs0, rs1, rs2, rs4, rs5, rs6                     !     -           -           -        -
+   REAL(wp) ::   rd0, rd1, rd2, rd3, rd4, rd5                     !     -           -           -        -
+   REAL(wp) ::   rsc_tke, rsc_psi, rpsi1, rpsi2, rpsi3, rsc_psi0  !     -           -           -        -
+   REAL(wp) ::   rpsi3m, rpsi3p, rpp, rmm, rnn                    !     -           -           -        -
+   !
+   REAL(wp) ::   r2_3 = 2._wp/3._wp   ! constant=2/3
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_gls_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_gls_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( hmxl_n(jpi,jpj,jpk) , ustar2_surf(jpi,jpj) ,                     &
+         &      zwall (jpi,jpj,jpk) , ustar2_top (jpi,jpj) , ustar2_bot(jpi,jpj) , STAT= zdf_gls_alloc )
+         !
+      CALL mpp_sum ( 'zdfgls', zdf_gls_alloc )
+      IF( zdf_gls_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_gls_alloc: failed to allocate arrays' )
+   END FUNCTION zdf_gls_alloc
+
+
+   SUBROUTINE zdf_gls( kt, p_sh2, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_gls  ***
+      !!
+      !! ** Purpose :   Compute the vertical eddy viscosity and diffusivity
+      !!              coefficients using the GLS turbulent closure scheme.
+      !!----------------------------------------------------------------------
+      USE zdf_oce , ONLY : en, avtb, avmb   ! ocean vertical physics
+      !!
+      INTEGER                   , INTENT(in   ) ::   kt             ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   p_sh2          ! shear production term
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   p_avm, p_avt   !  momentum and tracer Kz (w-points)
+      !
+      INTEGER  ::   ji, jj, jk    ! dummy loop arguments
+      INTEGER  ::   ibot, ibotm1  ! local integers
+      INTEGER  ::   itop, itopp1  !   -       -
+      REAL(wp) ::   zesh2, zsigpsi, zcoef, zex1 , zex2  ! local scalars
+      REAL(wp) ::   ztx2, zty2, zup, zdown, zcof, zdir  !   -      - 
+      REAL(wp) ::   zratio, zrn2, zflxb, sh     , z_en  !   -      -
+      REAL(wp) ::   prod, buoy, diss, zdiss, sm         !   -      -
+      REAL(wp) ::   gh, gm, shr, dif, zsqen, zavt, zavm !   -      -
+      REAL(wp) ::   zmsku, zmskv                        !   -      -
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zdep
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zkar
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zflxs       ! Turbulence fluxed induced by internal waves 
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zhsro       ! Surface roughness (surface waves)
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zice_fra    ! Tapering of wave breaking under sea ice
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   eb          ! tke at time before
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   hmxl_b      ! mixing length at time before
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   eps         ! dissipation rate
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwall_psi   ! Wall function use in the wb case (ln_sigpsi)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   psi         ! psi at time now
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zd_lw, zd_up, zdiag   ! lower, upper  and diagonal of the matrix
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zstt, zstm  ! stability function on tracer and momentum
+      !!--------------------------------------------------------------------
+      !
+      ! Preliminary computing
+
+      ustar2_surf(:,:) = 0._wp   ;         psi(:,:,:) = 0._wp   
+      ustar2_top (:,:) = 0._wp   ;   zwall_psi(:,:,:) = 0._wp
+      ustar2_bot (:,:) = 0._wp
+
+      SELECT CASE ( nn_z0_ice )
+      CASE( 0 )   ;   zice_fra(:,:) = 0._wp
+      CASE( 1 )   ;   zice_fra(:,:) =        TANH( fr_i(:,:) * 10._wp )
+      CASE( 2 )   ;   zice_fra(:,:) =              fr_i(:,:)
+      CASE( 3 )   ;   zice_fra(:,:) = MIN( 4._wp * fr_i(:,:) , 1._wp )
+      END SELECT
+      
+      ! Compute surface, top and bottom friction at T-points
+      DO jj = 2, jpjm1              !==  surface ocean friction
+         DO ji = fs_2, fs_jpim1           ! vector opt.         
+            ustar2_surf(ji,jj) = r1_rau0 * taum(ji,jj) * tmask(ji,jj,1)
+         END DO
+      END DO
+      !   
+!!gm Rq we may add here r_ke0(_top/_bot) ?  ==>> think about that...
+      !    
+      IF( .NOT.ln_drg_OFF ) THEN    !== top/bottom friction   (explicit before friction)
+         DO jj = 2, jpjm1                      ! bottom friction
+            DO ji = fs_2, fs_jpim1   ! vector opt.         
+               zmsku = ( 2._wp - umask(ji-1,jj,mbkt(ji,jj)) * umask(ji,jj,mbkt(ji,jj)) )
+               zmskv = ( 2._wp - vmask(ji,jj-1,mbkt(ji,jj)) * vmask(ji,jj,mbkt(ji,jj)) )     ! (CAUTION: CdU<0)
+               ustar2_bot(ji,jj) = - rCdU_bot(ji,jj) * SQRT(  ( zmsku*( ub(ji,jj,mbkt(ji,jj))+ub(ji-1,jj,mbkt(ji,jj)) ) )**2  &
+                  &                                         + ( zmskv*( vb(ji,jj,mbkt(ji,jj))+vb(ji,jj-1,mbkt(ji,jj)) ) )**2  )
+            END DO
+         END DO
+         IF( ln_isfcav ) THEN       !top friction
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zmsku = ( 2._wp - umask(ji-1,jj,mikt(ji,jj)) * umask(ji,jj,mikt(ji,jj)) )
+                  zmskv = ( 2._wp - vmask(ji,jj-1,mikt(ji,jj)) * vmask(ji,jj,mikt(ji,jj)) )     ! (CAUTION: CdU<0)
+                  ustar2_top(ji,jj) = - rCdU_top(ji,jj) * SQRT(  ( zmsku*( ub(ji,jj,mikt(ji,jj))+ub(ji-1,jj,mikt(ji,jj)) ) )**2  &
+                     &                                         + ( zmskv*( vb(ji,jj,mikt(ji,jj))+vb(ji,jj-1,mikt(ji,jj)) ) )**2  )
+               END DO
+            END DO
+         ENDIF
+      ENDIF
+   
+      SELECT CASE ( nn_z0_met )      !==  Set surface roughness length  ==!
+      CASE ( 0 )                          ! Constant roughness          
+         zhsro(:,:) = rn_hsro
+      CASE ( 1 )             ! Standard Charnock formula
+         zhsro(:,:) = MAX( rsbc_zs1 * ustar2_surf(:,:) , rn_hsro )
+      CASE ( 2 )             ! Roughness formulae according to Rascle et al., Ocean Modelling (2008)
+!!gm faster coding : the 2 comment lines should be used
+!!gm         zcof = 2._wp * 0.6_wp / 28._wp
+!!gm         zdep(:,:)  = 30._wp * TANH(  zcof/ SQRT( MAX(ustar2_surf(:,:),rsmall) )  )       ! Wave age (eq. 10)
+         zdep (:,:) = 30.*TANH( 2.*0.3/(28.*SQRT(MAX(ustar2_surf(:,:),rsmall))) )         ! Wave age (eq. 10)
+         zhsro(:,:) = MAX(rsbc_zs2 * ustar2_surf(:,:) * zdep(:,:)**1.5, rn_hsro)          ! zhsro = rn_frac_hs * Hsw (eq. 11)
+      CASE ( 3 )             ! Roughness given by the wave model (coupled or read in file)
+         zhsro(:,:) = MAX(rn_frac_hs * hsw(:,:), rn_hsro)   ! (rn_frac_hs=1.6 see Eq. (5) of Rascle et al. 2008 )
+      END SELECT
+      !
+      ! adapt roughness where there is sea ice
+      zhsro(:,:) = ( (1._wp-zice_fra(:,:)) * zhsro(:,:) + zice_fra(:,:) * rn_hsri )*tmask(:,:,1)  + (1._wp - tmask(:,:,1))*rn_hsro
+      !
+      DO jk = 2, jpkm1              !==  Compute dissipation rate  ==!
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               eps(ji,jj,jk)  = rc03 * en(ji,jj,jk) * SQRT( en(ji,jj,jk) ) / hmxl_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      ! Save tke at before time step
+      eb    (:,:,:) = en    (:,:,:)
+      hmxl_b(:,:,:) = hmxl_n(:,:,:)
+
+      IF( nn_clos == 0 ) THEN    ! Mellor-Yamada
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1 
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zup   = hmxl_n(ji,jj,jk) * gdepw_n(ji,jj,mbkt(ji,jj)+1)
+                  zdown = vkarmn * gdepw_n(ji,jj,jk) * ( -gdepw_n(ji,jj,jk) + gdepw_n(ji,jj,mbkt(ji,jj)+1) )
+                  zcoef = ( zup / MAX( zdown, rsmall ) )
+                  zwall (ji,jj,jk) = ( 1._wp + re2 * zcoef*zcoef ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      !!---------------------------------!!
+      !!   Equation to prognostic k      !!
+      !!---------------------------------!!
+      !
+      ! Now Turbulent kinetic energy (output in en)
+      ! -------------------------------
+      ! Resolution of a tridiagonal linear system by a "methode de chasse"
+      ! computation from level 2 to jpkm1  (e(1) computed after and e(jpk)=0 ).
+      ! The surface boundary condition are set after
+      ! The bottom boundary condition are also set after. In standard e(bottom)=0.
+      ! zdiag : diagonal zd_up : upper diagonal zd_lw : lower diagonal
+      ! Warning : after this step, en : right hand side of the matrix
+
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               !
+               buoy = - p_avt(ji,jj,jk) * rn2(ji,jj,jk)     ! stratif. destruction
+               !
+               diss = eps(ji,jj,jk)                         ! dissipation
+               !
+               zdir = 0.5_wp + SIGN( 0.5_wp, p_sh2(ji,jj,jk) + buoy )   ! zdir =1(=0) if shear(ji,jj,jk)+buoy >0(<0)
+               !
+               zesh2 = zdir*(p_sh2(ji,jj,jk)+buoy)+(1._wp-zdir)*p_sh2(ji,jj,jk)          ! production term
+               zdiss = zdir*(diss/en(ji,jj,jk))   +(1._wp-zdir)*(diss-buoy)/en(ji,jj,jk) ! dissipation term
+!!gm better coding, identical results
+!               zesh2 =   p_sh2(ji,jj,jk) + zdir*buoy               ! production term
+!               zdiss = ( diss - (1._wp-zdir)*buoy ) / en(ji,jj,jk) ! dissipation term
+!!gm
+               !
+               ! Compute a wall function from 1. to rsc_psi*zwall/rsc_psi0
+               ! Note that as long that Dirichlet boundary conditions are NOT set at the first and last levels (GOTM style)
+               ! there is no need to set a boundary condition for zwall_psi at the top and bottom boundaries.
+               ! Otherwise, this should be rsc_psi/rsc_psi0
+               IF( ln_sigpsi ) THEN
+                  zsigpsi = MIN( 1._wp, zesh2 / eps(ji,jj,jk) )     ! 0. <= zsigpsi <= 1.
+                  zwall_psi(ji,jj,jk) = rsc_psi /   & 
+                     &     (  zsigpsi * rsc_psi + (1._wp-zsigpsi) * rsc_psi0 / MAX( zwall(ji,jj,jk), 1._wp )  )
+               ELSE
+                  zwall_psi(ji,jj,jk) = 1._wp
+               ENDIF
+               !
+               ! building the matrix
+               zcof = rfact_tke * tmask(ji,jj,jk)
+               !                                        ! lower diagonal, in fact not used for jk = 2 (see surface conditions)
+               zd_lw(ji,jj,jk) = zcof * ( p_avm(ji,jj,jk  ) + p_avm(ji,jj,jk-1) ) / ( e3t_n(ji,jj,jk-1) * e3w_n(ji,jj,jk) )
+               !                                        ! upper diagonal, in fact not used for jk = ibotm1 (see bottom conditions)
+               zd_up(ji,jj,jk) = zcof * ( p_avm(ji,jj,jk+1) + p_avm(ji,jj,jk  ) ) / ( e3t_n(ji,jj,jk  ) * e3w_n(ji,jj,jk) )
+               !                                        ! diagonal
+               zdiag(ji,jj,jk) = 1._wp - zd_lw(ji,jj,jk) - zd_up(ji,jj,jk)  + rdt * zdiss * wmask(ji,jj,jk) 
+               !                                        ! right hand side in en
+               en(ji,jj,jk) = en(ji,jj,jk) + rdt * zesh2 * wmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      zdiag(:,:,jpk) = 1._wp
+      !
+      ! Set surface condition on zwall_psi (1 at the bottom)
+      zwall_psi(:,:, 1 ) = zwall_psi(:,:,2)
+      zwall_psi(:,:,jpk) = 1._wp
+      !
+      ! Surface boundary condition on tke
+      ! ---------------------------------
+      !
+      SELECT CASE ( nn_bc_surf )
+      !
+      CASE ( 0 )             ! Dirichlet boundary condition (set e at k=1 & 2) 
+      ! First level
+      en   (:,:,1) = MAX(  rn_emin , rc02r * ustar2_surf(:,:) * (1._wp + (1._wp-zice_fra(:,:))*rsbc_tke1)**r2_3  )
+      zd_lw(:,:,1) = en(:,:,1)
+      zd_up(:,:,1) = 0._wp
+      zdiag(:,:,1) = 1._wp
+      ! 
+      ! One level below
+      en   (:,:,2) =  MAX(  rc02r * ustar2_surf(:,:) * (  1._wp + (1._wp-zice_fra(:,:))*rsbc_tke1 * ((zhsro(:,:)+gdepw_n(:,:,2)) &
+         &                 / zhsro(:,:) )**(1.5_wp*ra_sf)  )**(2._wp/3._wp) , rn_emin   )
+      zd_lw(:,:,2) = 0._wp 
+      zd_up(:,:,2) = 0._wp
+      zdiag(:,:,2) = 1._wp
+      !
+      !
+      CASE ( 1 )             ! Neumann boundary condition (set d(e)/dz)
+      !
+      ! Dirichlet conditions at k=1
+      en   (:,:,1) = MAX(  rc02r * ustar2_surf(:,:) * (1._wp + (1._wp-zice_fra(:,:))*rsbc_tke1)**r2_3 , rn_emin  )
+      zd_lw(:,:,1) = en(:,:,1)
+      zd_up(:,:,1) = 0._wp
+      zdiag(:,:,1) = 1._wp
+      !
+      ! at k=2, set de/dz=Fw
+      !cbr
+      zdiag(:,:,2) = zdiag(:,:,2) +  zd_lw(:,:,2) ! Remove zd_lw from zdiag
+      zd_lw(:,:,2) = 0._wp
+      zkar (:,:)   = (rl_sf + (vkarmn-rl_sf)*(1.-EXP(-rtrans*gdept_n(:,:,1)/zhsro(:,:)) ))
+      zflxs(:,:)   = rsbc_tke2 * (1._wp-zice_fra(:,:)) * ustar2_surf(:,:)**1.5_wp * zkar(:,:) &
+          &                    * (  ( zhsro(:,:)+gdept_n(:,:,1) ) / zhsro(:,:)  )**(1.5_wp*ra_sf)
+!!gm why not   :                        * ( 1._wp + gdept_n(:,:,1) / zhsro(:,:) )**(1.5_wp*ra_sf)
+      en(:,:,2) = en(:,:,2) + zflxs(:,:) / e3w_n(:,:,2)
+      !
+      !
+      END SELECT
+
+      ! Bottom boundary condition on tke
+      ! --------------------------------
+      !
+      SELECT CASE ( nn_bc_bot )
+      !
+      CASE ( 0 )             ! Dirichlet 
+         !                      ! en(ibot) = u*^2 / Co2 and hmxl_n(ibot) = rn_lmin
+         !                      ! Balance between the production and the dissipation terms
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+!!gm This means that bottom and ocean w-level above have a specified "en" value.   Sure ????
+!!   With thick deep ocean level thickness, this may be quite large, no ???
+!!   in particular in ocean cavities where top stratification can be large...
+               ibot   = mbkt(ji,jj) + 1      ! k   bottom level of w-point
+               ibotm1 = mbkt(ji,jj)          ! k-1 bottom level of w-point but >=1
+               !
+               z_en =  MAX( rc02r * ustar2_bot(ji,jj), rn_emin )
+               !
+               ! Dirichlet condition applied at: 
+               !     Bottom level (ibot)      &      Just above it (ibotm1)   
+               zd_lw(ji,jj,ibot) = 0._wp   ;   zd_lw(ji,jj,ibotm1) = 0._wp
+               zd_up(ji,jj,ibot) = 0._wp   ;   zd_up(ji,jj,ibotm1) = 0._wp
+               zdiag(ji,jj,ibot) = 1._wp   ;   zdiag(ji,jj,ibotm1) = 1._wp
+               en   (ji,jj,ibot) = z_en    ;   en   (ji,jj,ibotm1) = z_en
+            END DO
+         END DO
+         !
+         IF( ln_isfcav) THEN     ! top boundary   (ocean cavity)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  itop   = mikt(ji,jj)       ! k   top w-point
+                  itopp1 = mikt(ji,jj) + 1   ! k+1 1st w-point below the top one
+                  !                                                ! mask at the ocean surface points
+                  z_en = MAX( rc02r * ustar2_top(ji,jj), rn_emin ) * ( 1._wp - tmask(ji,jj,1) )
+                  !
+ !!gm TO BE VERIFIED !!!
+                  ! Dirichlet condition applied at: 
+                  !     top level (itop)         &      Just below it (itopp1)   
+                  zd_lw(ji,jj,itop) = 0._wp   ;   zd_lw(ji,jj,itopp1) = 0._wp
+                  zd_up(ji,jj,itop) = 0._wp   ;   zd_up(ji,jj,itopp1) = 0._wp
+                  zdiag(ji,jj,itop) = 1._wp   ;   zdiag(ji,jj,itopp1) = 1._wp
+                  en   (ji,jj,itop) = z_en    ;   en   (ji,jj,itopp1) = z_en
+               END DO
+            END DO
+         ENDIF
+         !
+      CASE ( 1 )             ! Neumman boundary condition
+         !                      
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ibot   = mbkt(ji,jj) + 1      ! k   bottom level of w-point
+               ibotm1 = mbkt(ji,jj)          ! k-1 bottom level of w-point but >=1
+               !
+               z_en =  MAX( rc02r * ustar2_bot(ji,jj), rn_emin )
+               !
+               ! Bottom level Dirichlet condition:
+               !     Bottom level (ibot)      &      Just above it (ibotm1)   
+               !         Dirichlet            !         Neumann
+               zd_lw(ji,jj,ibot) = 0._wp   !   ! Remove zd_up from zdiag
+               zdiag(ji,jj,ibot) = 1._wp   ;   zdiag(ji,jj,ibotm1) = zdiag(ji,jj,ibotm1) + zd_up(ji,jj,ibotm1)
+               zd_up(ji,jj,ibot) = 0._wp   ;   zd_up(ji,jj,ibotm1) = 0._wp
+            END DO
+         END DO
+         IF( ln_isfcav) THEN     ! top boundary   (ocean cavity)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  itop   = mikt(ji,jj)       ! k   top w-point
+                  itopp1 = mikt(ji,jj) + 1   ! k+1 1st w-point below the top one
+                  !                                                ! mask at the ocean surface points
+                  z_en = MAX( rc02r * ustar2_top(ji,jj), rn_emin ) * ( 1._wp - tmask(ji,jj,1) )
+                  !
+                  ! Bottom level Dirichlet condition:
+                  !     Bottom level (ibot)      &      Just above it (ibotm1)   
+                  !         Dirichlet            !         Neumann
+                  zd_lw(ji,jj,itop) = 0._wp   !   ! Remove zd_up from zdiag
+                  zdiag(ji,jj,itop) = 1._wp   ;   zdiag(ji,jj,itopp1) = zdiag(ji,jj,itopp1) + zd_up(ji,jj,itopp1)
+                  zd_up(ji,jj,itop) = 0._wp   ;   zd_up(ji,jj,itopp1) = 0._wp
+               END DO
+            END DO
+         ENDIF
+         !
+      END SELECT
+
+      ! Matrix inversion (en prescribed at surface and the bottom)
+      ! ----------------------------------------------------------
+      !
+      DO jk = 2, jpkm1                             ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               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 jk = 2, jpkm1                             ! Second recurrence : Lk = RHSk - Lk / Dk-1 * Lk-1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               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 jk = jpkm1, 2, -1                         ! thrid recurrence : Ek = ( Lk - Uk * Ek+1 ) / Dk
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               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
+      !                                            ! set the minimum value of tke 
+      en(:,:,:) = MAX( en(:,:,:), rn_emin )
+
+      !!----------------------------------------!!
+      !!   Solve prognostic equation for psi    !!
+      !!----------------------------------------!!
+
+      ! Set psi to previous time step value
+      !
+      SELECT CASE ( nn_clos )
+      !
+      CASE( 0 )               ! k-kl  (Mellor-Yamada)
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  psi(ji,jj,jk)  = eb(ji,jj,jk) * hmxl_b(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 1 )               ! k-eps
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  psi(ji,jj,jk)  = eps(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 2 )               ! k-w
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  psi(ji,jj,jk)  = SQRT( eb(ji,jj,jk) ) / ( rc0 * hmxl_b(ji,jj,jk) )
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 3 )               ! generic
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  psi(ji,jj,jk)  = rc02 * eb(ji,jj,jk) * hmxl_b(ji,jj,jk)**rnn 
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      ! Now gls (output in psi)
+      ! -------------------------------
+      ! Resolution of a tridiagonal linear system by a "methode de chasse"
+      ! computation from level 2 to jpkm1  (e(1) already computed and e(jpk)=0 ).
+      ! zdiag : diagonal zd_up : upper diagonal zd_lw : lower diagonal
+      ! Warning : after this step, en : right hand side of the matrix
+
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               !
+               ! psi / k
+               zratio = psi(ji,jj,jk) / eb(ji,jj,jk) 
+               !
+               ! psi3+ : stable : B=-KhN²<0 => N²>0 if rn2>0 zdir = 1 (stable) otherwise zdir = 0 (unstable)
+               zdir = 0.5_wp + SIGN( 0.5_wp, rn2(ji,jj,jk) )
+               !
+               rpsi3 = zdir * rpsi3m + ( 1._wp - zdir ) * rpsi3p
+               !
+               ! shear prod. - stratif. destruction
+               prod = rpsi1 * zratio * p_sh2(ji,jj,jk)
+               !
+               ! stratif. destruction
+               buoy = rpsi3 * zratio * (- p_avt(ji,jj,jk) * rn2(ji,jj,jk) )
+               !
+               ! shear prod. - stratif. destruction
+               diss = rpsi2 * zratio * zwall(ji,jj,jk) * eps(ji,jj,jk)
+               !
+               zdir = 0.5_wp + SIGN( 0.5_wp, prod + buoy )     ! zdir =1(=0) if shear(ji,jj,jk)+buoy >0(<0)
+               !
+               zesh2 = zdir * ( prod + buoy )          + (1._wp - zdir ) * prod                        ! production term
+               zdiss = zdir * ( diss / psi(ji,jj,jk) ) + (1._wp - zdir ) * (diss-buoy) / psi(ji,jj,jk) ! dissipation term
+               !                                                        
+               ! building the matrix
+               zcof = rfact_psi * zwall_psi(ji,jj,jk) * tmask(ji,jj,jk)
+               !                                               ! lower diagonal
+               zd_lw(ji,jj,jk) = zcof * ( p_avm(ji,jj,jk  ) + p_avm(ji,jj,jk-1) ) / ( e3t_n(ji,jj,jk-1) * e3w_n(ji,jj,jk) )
+               !                                               ! upper diagonal
+               zd_up(ji,jj,jk) = zcof * ( p_avm(ji,jj,jk+1) + p_avm(ji,jj,jk  ) ) / ( e3t_n(ji,jj,jk  ) * e3w_n(ji,jj,jk) )
+               !                                               ! diagonal
+               zdiag(ji,jj,jk) = 1._wp - zd_lw(ji,jj,jk) - zd_up(ji,jj,jk) + rdt * zdiss * wmask(ji,jj,jk)
+               !                                               ! right hand side in psi
+               psi(ji,jj,jk) = psi(ji,jj,jk) + rdt * zesh2 * wmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      zdiag(:,:,jpk) = 1._wp
+
+      ! Surface boundary condition on psi
+      ! ---------------------------------
+      !
+      SELECT CASE ( nn_bc_surf )
+      !
+      CASE ( 0 )             ! Dirichlet boundary conditions
+         !
+         ! Surface value
+         zdep    (:,:)   = zhsro(:,:) * rl_sf ! Cosmetic
+         psi     (:,:,1) = rc0**rpp * en(:,:,1)**rmm * zdep(:,:)**rnn * tmask(:,:,1)
+         zd_lw(:,:,1) = psi(:,:,1)
+         zd_up(:,:,1) = 0._wp
+         zdiag(:,:,1) = 1._wp
+         !
+         ! One level below
+         zkar    (:,:)   = (rl_sf + (vkarmn-rl_sf)*(1._wp-EXP(-rtrans*gdepw_n(:,:,2)/zhsro(:,:) )))
+         zdep    (:,:)   = (zhsro(:,:) + gdepw_n(:,:,2)) * zkar(:,:)
+         psi     (:,:,2) = rc0**rpp * en(:,:,2)**rmm * zdep(:,:)**rnn * tmask(:,:,1)
+         zd_lw(:,:,2) = 0._wp
+         zd_up(:,:,2) = 0._wp
+         zdiag(:,:,2) = 1._wp
+         ! 
+      CASE ( 1 )             ! Neumann boundary condition on d(psi)/dz
+         !
+         ! Surface value: Dirichlet
+         zdep    (:,:)   = zhsro(:,:) * rl_sf
+         psi     (:,:,1) = rc0**rpp * en(:,:,1)**rmm * zdep(:,:)**rnn * tmask(:,:,1)
+         zd_lw(:,:,1) = psi(:,:,1)
+         zd_up(:,:,1) = 0._wp
+         zdiag(:,:,1) = 1._wp
+         !
+         ! Neumann condition at k=2
+         zdiag(:,:,2) = zdiag(:,:,2) +  zd_lw(:,:,2) ! Remove zd_lw from zdiag
+         zd_lw(:,:,2) = 0._wp
+         !
+         ! Set psi vertical flux at the surface:
+         zkar (:,:)   = rl_sf + (vkarmn-rl_sf)*(1._wp-EXP(-rtrans*gdept_n(:,:,1)/zhsro(:,:) )) ! Lengh scale slope
+         zdep (:,:)   = ((zhsro(:,:) + gdept_n(:,:,1)) / zhsro(:,:))**(rmm*ra_sf)
+         zflxs(:,:)   = (rnn + (1._wp-zice_fra(:,:))*rsbc_tke1 * (rnn + rmm*ra_sf) * zdep(:,:)) &
+            &           *(1._wp + (1._wp-zice_fra(:,:))*rsbc_tke1*zdep(:,:))**(2._wp*rmm/3._wp-1_wp)
+         zdep (:,:)   = rsbc_psi1 * (zwall_psi(:,:,1)*p_avm(:,:,1)+zwall_psi(:,:,2)*p_avm(:,:,2)) * &
+            &           ustar2_surf(:,:)**rmm * zkar(:,:)**rnn * (zhsro(:,:) + gdept_n(:,:,1))**(rnn-1.)
+         zflxs(:,:)   = zdep(:,:) * zflxs(:,:)
+         psi  (:,:,2) = psi(:,:,2) + zflxs(:,:) / e3w_n(:,:,2)
+         !
+      END SELECT
+
+      ! Bottom boundary condition on psi
+      ! --------------------------------
+      !
+!!gm should be done for ISF (top boundary cond.)
+!!gm so, totally new staff needed      ===>>> think about that !
+!
+      SELECT CASE ( nn_bc_bot )     ! bottom boundary
+      !
+      CASE ( 0 )             ! Dirichlet 
+         !                      ! en(ibot) = u*^2 / Co2 and hmxl_n(ibot) = vkarmn * r_z0_bot
+         !                      ! Balance between the production and the dissipation terms
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ibot   = mbkt(ji,jj) + 1      ! k   bottom level of w-point
+               ibotm1 = mbkt(ji,jj)          ! k-1 bottom level of w-point but >=1
+               zdep(ji,jj) = vkarmn * r_z0_bot
+               psi (ji,jj,ibot) = rc0**rpp * en(ji,jj,ibot)**rmm * zdep(ji,jj)**rnn
+               zd_lw(ji,jj,ibot) = 0._wp
+               zd_up(ji,jj,ibot) = 0._wp
+               zdiag(ji,jj,ibot) = 1._wp
+               !
+               ! Just above last level, Dirichlet condition again (GOTM like)
+               zdep(ji,jj) = vkarmn * ( r_z0_bot + e3t_n(ji,jj,ibotm1) )
+               psi (ji,jj,ibotm1) = rc0**rpp * en(ji,jj,ibot  )**rmm * zdep(ji,jj)**rnn
+               zd_lw(ji,jj,ibotm1) = 0._wp
+               zd_up(ji,jj,ibotm1) = 0._wp
+               zdiag(ji,jj,ibotm1) = 1._wp
+            END DO
+         END DO
+         !
+      CASE ( 1 )             ! Neumman boundary condition
+         !                      
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ibot   = mbkt(ji,jj) + 1      ! k   bottom level of w-point
+               ibotm1 = mbkt(ji,jj)          ! k-1 bottom level of w-point but >=1
+               !
+               ! Bottom level Dirichlet condition:
+               zdep(ji,jj) = vkarmn * r_z0_bot
+               psi (ji,jj,ibot) = rc0**rpp * en(ji,jj,ibot)**rmm * zdep(ji,jj)**rnn
+               !
+               zd_lw(ji,jj,ibot) = 0._wp
+               zd_up(ji,jj,ibot) = 0._wp
+               zdiag(ji,jj,ibot) = 1._wp
+               !
+               ! Just above last level: Neumann condition with flux injection
+               zdiag(ji,jj,ibotm1) = zdiag(ji,jj,ibotm1) + zd_up(ji,jj,ibotm1) ! Remove zd_up from zdiag
+               zd_up(ji,jj,ibotm1) = 0.
+               !
+               ! Set psi vertical flux at the bottom:
+               zdep(ji,jj) = r_z0_bot + 0.5_wp*e3t_n(ji,jj,ibotm1)
+               zflxb = rsbc_psi2 * ( p_avm(ji,jj,ibot) + p_avm(ji,jj,ibotm1) )   &
+                  &  * (0.5_wp*(en(ji,jj,ibot)+en(ji,jj,ibotm1)))**rmm * zdep(ji,jj)**(rnn-1._wp)
+               psi(ji,jj,ibotm1) = psi(ji,jj,ibotm1) + zflxb / e3w_n(ji,jj,ibotm1)
+            END DO
+         END DO
+         !
+      END SELECT
+
+      ! Matrix inversion
+      ! ----------------
+      !
+      DO jk = 2, jpkm1                             ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               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 jk = 2, jpkm1                             ! Second recurrence : Lk = RHSk - Lk / Dk-1 * Lk-1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               zd_lw(ji,jj,jk) = psi(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 jk = jpkm1, 2, -1                         ! Third recurrence : Ek = ( Lk - Uk * Ek+1 ) / Dk
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               psi(ji,jj,jk) = ( zd_lw(ji,jj,jk) - zd_up(ji,jj,jk) * psi(ji,jj,jk+1) ) / zdiag(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      ! Set dissipation
+      !----------------
+
+      SELECT CASE ( nn_clos )
+      !
+      CASE( 0 )               ! k-kl  (Mellor-Yamada)
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  eps(ji,jj,jk) = rc03 * en(ji,jj,jk) * en(ji,jj,jk) * SQRT( en(ji,jj,jk) ) / MAX( psi(ji,jj,jk), rn_epsmin)
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 1 )               ! k-eps
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  eps(ji,jj,jk) = psi(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 2 )               ! k-w
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  eps(ji,jj,jk) = rc04 * en(ji,jj,jk) * psi(ji,jj,jk) 
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 3 )               ! generic
+         zcoef = rc0**( 3._wp  + rpp/rnn )
+         zex1  =      ( 1.5_wp + rmm/rnn )
+         zex2  = -1._wp / rnn
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  eps(ji,jj,jk) = zcoef * en(ji,jj,jk)**zex1 * psi(ji,jj,jk)**zex2
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+
+      ! Limit dissipation rate under stable stratification
+      ! --------------------------------------------------
+      DO jk = 1, jpkm1 ! Note that this set boundary conditions on hmxl_n at the same time
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1    ! vector opt.
+               ! limitation
+               eps   (ji,jj,jk)  = MAX( eps(ji,jj,jk), rn_epsmin )
+               hmxl_n(ji,jj,jk)  = rc03 * en(ji,jj,jk) * SQRT( en(ji,jj,jk) ) / eps(ji,jj,jk)
+               ! Galperin criterium (NOTE : Not required if the proper value of C3 in stable cases is calculated) 
+               zrn2 = MAX( rn2(ji,jj,jk), rsmall )
+               IF( ln_length_lim )   hmxl_n(ji,jj,jk) = MIN(  rn_clim_galp * SQRT( 2._wp * en(ji,jj,jk) / zrn2 ), hmxl_n(ji,jj,jk) )
+            END DO
+         END DO
+      END DO 
+
+      !
+      ! Stability function and vertical viscosity and diffusivity
+      ! ---------------------------------------------------------
+      !
+      SELECT CASE ( nn_stab_func )
+      !
+      CASE ( 0 , 1 )             ! Galperin or Kantha-Clayson stability functions
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ! zcof =  l²/q²
+                  zcof = hmxl_b(ji,jj,jk) * hmxl_b(ji,jj,jk) / ( 2._wp*eb(ji,jj,jk) )
+                  ! Gh = -N²l²/q²
+                  gh = - rn2(ji,jj,jk) * zcof
+                  gh = MIN( gh, rgh0   )
+                  gh = MAX( gh, rghmin )
+                  ! Stability functions from Kantha and Clayson (if C2=C3=0 => Galperin)
+                  sh = ra2*( 1._wp-6._wp*ra1/rb1 ) / ( 1.-3.*ra2*gh*(6.*ra1+rb2*( 1._wp-rc3 ) ) )
+                  sm = ( rb1**(-1._wp/3._wp) + ( 18._wp*ra1*ra1 + 9._wp*ra1*ra2*(1._wp-rc2) )*sh*gh ) / (1._wp-9._wp*ra1*ra2*gh)
+                  !
+                  ! Store stability function in zstt and zstm
+                  zstt(ji,jj,jk) = rc_diff * sh * tmask(ji,jj,jk)
+                  zstm(ji,jj,jk) = rc_diff * sm * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 2, 3 )               ! Canuto stability functions
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  ! zcof =  l²/q²
+                  zcof = hmxl_b(ji,jj,jk)*hmxl_b(ji,jj,jk) / ( 2._wp * eb(ji,jj,jk) )
+                  ! Gh = -N²l²/q²
+                  gh = - rn2(ji,jj,jk) * zcof
+                  gh = MIN( gh, rgh0   )
+                  gh = MAX( gh, rghmin )
+                  gh = gh * rf6
+                  ! Gm =  M²l²/q² Shear number
+                  shr = p_sh2(ji,jj,jk) / MAX( p_avm(ji,jj,jk), rsmall )
+                  gm = MAX( shr * zcof , 1.e-10 )
+                  gm = gm * rf6
+                  gm = MIN ( (rd0 - rd1*gh + rd3*gh*gh) / (rd2-rd4*gh) , gm )
+                  ! Stability functions from Canuto
+                  rcff = rd0 - rd1*gh +rd2*gm + rd3*gh*gh - rd4*gh*gm + rd5*gm*gm
+                  sm = (rs0 - rs1*gh + rs2*gm) / rcff
+                  sh = (rs4 - rs5*gh + rs6*gm) / rcff
+                  !
+                  ! Store stability function in zstt and zstm
+                  zstt(ji,jj,jk) = rc_diff * sh * tmask(ji,jj,jk)
+                  zstm(ji,jj,jk) = rc_diff * sm * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+
+      ! Boundary conditions on stability functions for momentum (Neumann):
+      ! Lines below are useless if GOTM style Dirichlet conditions are used
+
+      zstm(:,:,1) = zstm(:,:,2)
+
+      ! default value, in case jpk > mbkt(ji,jj)+1. Not needed but avoid a bug when looking for undefined values (-fpe0)
+      zstm(:,:,jpk) = 0.  
+      DO jj = 2, jpjm1                ! update bottom with good values
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            zstm(ji,jj,mbkt(ji,jj)+1) = zstm(ji,jj,mbkt(ji,jj))
+         END DO
+      END DO
+
+      zstt(:,:,  1) = wmask(:,:,  1)  ! default value not needed but avoid a bug when looking for undefined values (-fpe0)
+      zstt(:,:,jpk) = wmask(:,:,jpk)  ! default value not needed but avoid a bug when looking for undefined values (-fpe0)
+
+!!gm should be done for ISF (top boundary cond.)
+!!gm so, totally new staff needed!!gm
+
+      ! Compute diffusivities/viscosities
+      ! The computation below could be restrained to jk=2 to jpkm1 if GOTM style Dirichlet conditions are used
+      !  -> yes BUT p_avm(:,:1) and p_avm(:,:jpk) are used when we compute zd_lw(:,:2) and zd_up(:,:jpkm1). These values are
+      !     later overwritten by surface/bottom boundaries conditions, so we don't really care of p_avm(:,:1) and p_avm(:,:jpk)
+      !     for zd_lw and zd_up but they have to be defined to avoid a bug when looking for undefined values (-fpe0)
+      DO jk = 1, jpk
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zsqen = SQRT( 2._wp * en(ji,jj,jk) ) * hmxl_n(ji,jj,jk)
+               zavt  = zsqen * zstt(ji,jj,jk)
+               zavm  = zsqen * zstm(ji,jj,jk)
+               p_avt(ji,jj,jk) = MAX( zavt, avtb(jk) ) * wmask(ji,jj,jk) ! apply mask for zdfmxl routine
+               p_avm(ji,jj,jk) = MAX( zavm, avmb(jk) )                   ! Note that avm is not masked at the surface and the bottom
+            END DO
+         END DO
+      END DO
+      p_avt(:,:,1) = 0._wp
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl( tab3d_1=en   , clinfo1=' gls  - e: ', tab3d_2=p_avt, clinfo2=' t: ', kdim=jpk)
+         CALL prt_ctl( tab3d_1=p_avm, clinfo1=' gls  - m: ', kdim=jpk )
+      ENDIF
+      !
+   END SUBROUTINE zdf_gls
+
+
+   SUBROUTINE zdf_gls_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_gls_init  ***
+      !!                     
+      !! ** Purpose :   Initialization of the vertical eddy diffivity and 
+      !!              viscosity computed using a GLS turbulent closure scheme
+      !!
+      !! ** Method  :   Read the namzdf_gls namelist and check the parameters
+      !!
+      !! ** input   :   Namlist namzdf_gls
+      !!
+      !! ** Action  :   Increase by 1 the nstop flag is setting problem encounter
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   jk    ! dummy loop indices
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      REAL(wp)::   zcr   ! local scalar
+      !!
+      NAMELIST/namzdf_gls/rn_emin, rn_epsmin, ln_length_lim,       &
+         &            rn_clim_galp, ln_sigpsi, rn_hsro, rn_hsri,   &
+         &            rn_crban, rn_charn, rn_frac_hs,              &
+         &            nn_bc_surf, nn_bc_bot, nn_z0_met, nn_z0_ice, &
+         &            nn_stab_func, nn_clos
+      !!----------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_gls in reference namelist : Vertical eddy diffivity and viscosity using gls turbulent closure scheme
+      READ  ( numnam_ref, namzdf_gls, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namzdf_gls in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namzdf_gls in configuration namelist : Vertical eddy diffivity and viscosity using gls turbulent closure scheme
+      READ  ( numnam_cfg, namzdf_gls, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namzdf_gls in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_gls )
+
+      IF(lwp) THEN                     !* Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_gls_init : GLS turbulent closure scheme'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_gls : set gls mixing parameters'
+         WRITE(numout,*) '      minimum value of en                           rn_emin        = ', rn_emin
+         WRITE(numout,*) '      minimum value of eps                          rn_epsmin      = ', rn_epsmin
+         WRITE(numout,*) '      Limit dissipation rate under stable stratif.  ln_length_lim  = ', ln_length_lim
+         WRITE(numout,*) '      Galperin limit (Standard: 0.53, Holt: 0.26)   rn_clim_galp   = ', rn_clim_galp
+         WRITE(numout,*) '      TKE Surface boundary condition                nn_bc_surf     = ', nn_bc_surf
+         WRITE(numout,*) '      TKE Bottom boundary condition                 nn_bc_bot      = ', nn_bc_bot
+         WRITE(numout,*) '      Modify psi Schmidt number (wb case)           ln_sigpsi      = ', ln_sigpsi
+         WRITE(numout,*) '      Craig and Banner coefficient                  rn_crban       = ', rn_crban
+         WRITE(numout,*) '      Charnock coefficient                          rn_charn       = ', rn_charn
+         WRITE(numout,*) '      Surface roughness formula                     nn_z0_met      = ', nn_z0_met
+         WRITE(numout,*) '      surface wave breaking under ice               nn_z0_ice      = ', nn_z0_ice
+         SELECT CASE( nn_z0_ice )
+         CASE( 0 )   ;   WRITE(numout,*) '   ==>>>   no impact of ice cover on surface wave breaking'
+         CASE( 1 )   ;   WRITE(numout,*) '   ==>>>   roughness uses rn_hsri and is weigthed by 1-TANH( fr_i(:,:) * 10 )'
+         CASE( 2 )   ;   WRITE(numout,*) '   ==>>>   roughness uses rn_hsri and is weighted by 1-fr_i(:,:)'
+         CASE( 3 )   ;   WRITE(numout,*) '   ==>>>   roughness uses rn_hsri and is weighted by 1-MIN( 1, 4 * fr_i(:,:) )'
+         CASE DEFAULT
+            CALL ctl_stop( 'zdf_gls_init: wrong value for nn_z0_ice, should be 0,1,2, or 3')
+         END SELECT
+         WRITE(numout,*) '      Wave height frac. (used if nn_z0_met=2)       rn_frac_hs     = ', rn_frac_hs
+         WRITE(numout,*) '      Stability functions                           nn_stab_func   = ', nn_stab_func
+         WRITE(numout,*) '      Type of closure                               nn_clos        = ', nn_clos
+         WRITE(numout,*) '      Surface roughness (m)                         rn_hsro        = ', rn_hsro
+         WRITE(numout,*) '      Ice-ocean roughness (used if nn_z0_ice/=0)    rn_hsri        = ', rn_hsri
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namdrg_top/_bot:   used values:'
+         WRITE(numout,*) '      top    ocean cavity roughness (m)             rn_z0(_top)   = ', r_z0_top
+         WRITE(numout,*) '      Bottom seafloor     roughness (m)             rn_z0(_bot)   = ', r_z0_bot
+         WRITE(numout,*)
+      ENDIF
+
+      !                                !* allocate GLS arrays
+      IF( zdf_gls_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_gls_init : unable to allocate arrays' )
+
+      !                                !* Check of some namelist values
+      IF( nn_bc_surf < 0   .OR. nn_bc_surf   > 1 )              CALL ctl_stop( 'zdf_gls_init: bad flag: nn_bc_surf is 0 or 1' )
+      IF( nn_bc_surf < 0   .OR. nn_bc_surf   > 1 )              CALL ctl_stop( 'zdf_gls_init: bad flag: nn_bc_surf is 0 or 1' )
+      IF( nn_z0_met  < 0   .OR. nn_z0_met    > 3 )              CALL ctl_stop( 'zdf_gls_init: bad flag: nn_z0_met is 0, 1, 2 or 3' )
+      IF( nn_z0_met == 3  .AND. .NOT. (ln_wave .AND. ln_sdw ) ) CALL ctl_stop( 'zdf_gls_init: nn_z0_met=3 requires ln_wave=T and ln_sdw=T' )
+      IF( nn_stab_func < 0 .OR. nn_stab_func > 3 )              CALL ctl_stop( 'zdf_gls_init: bad flag: nn_stab_func is 0, 1, 2 and 3' )
+      IF( nn_clos      < 0 .OR. nn_clos      > 3 )              CALL ctl_stop( 'zdf_gls_init: bad flag: nn_clos is 0, 1, 2 or 3' )
+
+      SELECT CASE ( nn_clos )          !* set the parameters for the chosen closure
+      !
+      CASE( 0 )                              ! k-kl  (Mellor-Yamada)
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   k-kl closure chosen (i.e. closed to the classical Mellor-Yamada)'
+         IF(lwp) WRITE(numout,*)
+         rpp     = 0._wp
+         rmm     = 1._wp
+         rnn     = 1._wp
+         rsc_tke = 1.96_wp
+         rsc_psi = 1.96_wp
+         rpsi1   = 0.9_wp
+         rpsi3p  = 1._wp
+         rpsi2   = 0.5_wp
+         !
+         SELECT CASE ( nn_stab_func )
+         CASE( 0, 1 )   ;   rpsi3m = 2.53_wp       ! G88 or KC stability functions
+         CASE( 2 )      ;   rpsi3m = 2.62_wp       ! Canuto A stability functions
+         CASE( 3 )      ;   rpsi3m = 2.38          ! Canuto B stability functions (caution : constant not identified)
+         END SELECT
+         !
+      CASE( 1 )                              ! k-eps
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   k-eps closure chosen'
+         IF(lwp) WRITE(numout,*)
+         rpp     =  3._wp
+         rmm     =  1.5_wp
+         rnn     = -1._wp
+         rsc_tke =  1._wp
+         rsc_psi =  1.2_wp  ! Schmidt number for psi
+         rpsi1   =  1.44_wp
+         rpsi3p  =  1._wp
+         rpsi2   =  1.92_wp
+         !
+         SELECT CASE ( nn_stab_func )
+         CASE( 0, 1 )   ;   rpsi3m = -0.52_wp      ! G88 or KC stability functions
+         CASE( 2 )      ;   rpsi3m = -0.629_wp     ! Canuto A stability functions
+         CASE( 3 )      ;   rpsi3m = -0.566        ! Canuto B stability functions
+         END SELECT
+         !
+      CASE( 2 )                              ! k-omega
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   k-omega closure chosen'
+         IF(lwp) WRITE(numout,*)
+         rpp     = -1._wp
+         rmm     =  0.5_wp
+         rnn     = -1._wp
+         rsc_tke =  2._wp
+         rsc_psi =  2._wp
+         rpsi1   =  0.555_wp
+         rpsi3p  =  1._wp
+         rpsi2   =  0.833_wp
+         !
+         SELECT CASE ( nn_stab_func )
+         CASE( 0, 1 )   ;   rpsi3m = -0.58_wp       ! G88 or KC stability functions
+         CASE( 2 )      ;   rpsi3m = -0.64_wp       ! Canuto A stability functions
+         CASE( 3 )      ;   rpsi3m = -0.64_wp       ! Canuto B stability functions caution : constant not identified)
+         END SELECT
+         !
+      CASE( 3 )                              ! generic
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   generic closure chosen'
+         IF(lwp) WRITE(numout,*)
+         rpp     = 2._wp
+         rmm     = 1._wp
+         rnn     = -0.67_wp
+         rsc_tke = 0.8_wp
+         rsc_psi = 1.07_wp
+         rpsi1   = 1._wp
+         rpsi3p  = 1._wp
+         rpsi2   = 1.22_wp
+         !
+         SELECT CASE ( nn_stab_func )
+         CASE( 0, 1 )   ;   rpsi3m = 0.1_wp         ! G88 or KC stability functions
+         CASE( 2 )      ;   rpsi3m = 0.05_wp        ! Canuto A stability functions
+         CASE( 3 )      ;   rpsi3m = 0.05_wp        ! Canuto B stability functions caution : constant not identified)
+         END SELECT
+         !
+      END SELECT
+
+      !
+      SELECT CASE ( nn_stab_func )     !* set the parameters of the stability functions
+      !
+      CASE ( 0 )                             ! Galperin stability functions
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   Stability functions from Galperin'
+         rc2     =  0._wp
+         rc3     =  0._wp
+         rc_diff =  1._wp
+         rc0     =  0.5544_wp
+         rcm_sf  =  0.9884_wp
+         rghmin  = -0.28_wp
+         rgh0    =  0.0233_wp
+         rghcri  =  0.02_wp
+         !
+      CASE ( 1 )                             ! Kantha-Clayson stability functions
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   Stability functions from Kantha-Clayson'
+         rc2     =  0.7_wp
+         rc3     =  0.2_wp
+         rc_diff =  1._wp
+         rc0     =  0.5544_wp
+         rcm_sf  =  0.9884_wp
+         rghmin  = -0.28_wp
+         rgh0    =  0.0233_wp
+         rghcri  =  0.02_wp
+         !
+      CASE ( 2 )                             ! Canuto A stability functions
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   Stability functions from Canuto A'
+         rs0 = 1.5_wp * rl1 * rl5*rl5
+         rs1 = -rl4*(rl6+rl7) + 2._wp*rl4*rl5*(rl1-(1._wp/3._wp)*rl2-rl3) + 1.5_wp*rl1*rl5*rl8
+         rs2 = -(3._wp/8._wp) * rl1*(rl6*rl6-rl7*rl7)
+         rs4 = 2._wp * rl5
+         rs5 = 2._wp * rl4
+         rs6 = (2._wp/3._wp) * rl5 * ( 3._wp*rl3*rl3 - rl2*rl2 ) - 0.5_wp * rl5*rl1 * (3._wp*rl3-rl2)   &
+            &                                                    + 0.75_wp * rl1 * ( rl6 - rl7 )
+         rd0 = 3._wp * rl5*rl5
+         rd1 = rl5 * ( 7._wp*rl4 + 3._wp*rl8 )
+         rd2 = rl5*rl5 * ( 3._wp*rl3*rl3 - rl2*rl2 ) - 0.75_wp*(rl6*rl6 - rl7*rl7 )
+         rd3 = rl4 * ( 4._wp*rl4 + 3._wp*rl8)
+         rd4 = rl4 * ( rl2 * rl6 - 3._wp*rl3*rl7 - rl5*(rl2*rl2 - rl3*rl3 ) ) + rl5*rl8 * ( 3._wp*rl3*rl3 - rl2*rl2 )
+         rd5 = 0.25_wp * ( rl2*rl2 - 3._wp *rl3*rl3 ) * ( rl6*rl6 - rl7*rl7 )
+         rc0 = 0.5268_wp
+         rf6 = 8._wp / (rc0**6._wp)
+         rc_diff = SQRT(2._wp) / (rc0**3._wp)
+         rcm_sf  =  0.7310_wp
+         rghmin  = -0.28_wp
+         rgh0    =  0.0329_wp
+         rghcri  =  0.03_wp
+         !
+      CASE ( 3 )                             ! Canuto B stability functions
+         !
+         IF(lwp) WRITE(numout,*) '   ==>>   Stability functions from Canuto B'
+         rs0 = 1.5_wp * rm1 * rm5*rm5
+         rs1 = -rm4 * (rm6+rm7) + 2._wp * rm4*rm5*(rm1-(1._wp/3._wp)*rm2-rm3) + 1.5_wp * rm1*rm5*rm8
+         rs2 = -(3._wp/8._wp) * rm1 * (rm6*rm6-rm7*rm7 )
+         rs4 = 2._wp * rm5
+         rs5 = 2._wp * rm4
+         rs6 = (2._wp/3._wp) * rm5 * (3._wp*rm3*rm3-rm2*rm2) - 0.5_wp * rm5*rm1*(3._wp*rm3-rm2) + 0.75_wp * rm1*(rm6-rm7)
+         rd0 = 3._wp * rm5*rm5
+         rd1 = rm5 * (7._wp*rm4 + 3._wp*rm8)
+         rd2 = rm5*rm5 * (3._wp*rm3*rm3 - rm2*rm2) - 0.75_wp * (rm6*rm6 - rm7*rm7)
+         rd3 = rm4 * ( 4._wp*rm4 + 3._wp*rm8 )
+         rd4 = rm4 * ( rm2*rm6 -3._wp*rm3*rm7 - rm5*(rm2*rm2 - rm3*rm3) ) + rm5 * rm8 * ( 3._wp*rm3*rm3 - rm2*rm2 )
+         rd5 = 0.25_wp * ( rm2*rm2 - 3._wp*rm3*rm3 ) * ( rm6*rm6 - rm7*rm7 )
+         rc0 = 0.5268_wp            !!       rc0 = 0.5540_wp (Warner ...) to verify !
+         rf6 = 8._wp / ( rc0**6._wp )
+         rc_diff = SQRT(2._wp)/(rc0**3.)
+         rcm_sf  =  0.7470_wp
+         rghmin  = -0.28_wp
+         rgh0    =  0.0444_wp
+         rghcri  =  0.0414_wp
+         !
+      END SELECT
+    
+      !                                !* Set Schmidt number for psi diffusion in the wave breaking case
+      !                                     ! See Eq. (13) of Carniel et al, OM, 30, 225-239, 2009
+      !                                     !  or Eq. (17) of Burchard, JPO, 31, 3133-3145, 2001
+      IF( ln_sigpsi ) THEN
+         ra_sf = -1.5 ! Set kinetic energy slope, then deduce rsc_psi and rl_sf 
+         ! Verification: retrieve Burchard (2001) results by uncomenting the line below:
+         ! Note that the results depend on the value of rn_cm_sf which is constant (=rc0) in his work
+         ! ra_sf = -SQRT(2./3.*rc0**3./rn_cm_sf*rn_sc_tke)/vkarmn
+         rsc_psi0 = rsc_tke/(24.*rpsi2)*(-1.+(4.*rnn + ra_sf*(1.+4.*rmm))**2./(ra_sf**2.))
+      ELSE
+         rsc_psi0 = rsc_psi
+      ENDIF
+ 
+      !                                !* Shear free turbulence parameters
+      !
+      ra_sf  = -4._wp*rnn*SQRT(rsc_tke) / ( (1._wp+4._wp*rmm)*SQRT(rsc_tke) &
+               &                              - SQRT(rsc_tke + 24._wp*rsc_psi0*rpsi2 ) )
+
+      IF ( rn_crban==0._wp ) THEN
+         rl_sf = vkarmn
+      ELSE
+         rl_sf = rc0 * SQRT(rc0/rcm_sf) * SQRT( ( (1._wp + 4._wp*rmm + 8._wp*rmm**2_wp) * rsc_tke        &
+            &                                            + 12._wp*rsc_psi0*rpsi2 - (1._wp + 4._wp*rmm)   &
+            &                                                     *SQRT(rsc_tke*(rsc_tke                 &
+            &                                                        + 24._wp*rsc_psi0*rpsi2)) )         &
+            &                                              /(12._wp*rnn**2.)                             )
+      ENDIF
+
+      !
+      IF(lwp) THEN                     !* Control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Limit values :'
+         WRITE(numout,*) '      Parameter  m = ', rmm
+         WRITE(numout,*) '      Parameter  n = ', rnn
+         WRITE(numout,*) '      Parameter  p = ', rpp
+         WRITE(numout,*) '      rpsi1    = ', rpsi1
+         WRITE(numout,*) '      rpsi2    = ', rpsi2
+         WRITE(numout,*) '      rpsi3m   = ', rpsi3m
+         WRITE(numout,*) '      rpsi3p   = ', rpsi3p
+         WRITE(numout,*) '      rsc_tke  = ', rsc_tke
+         WRITE(numout,*) '      rsc_psi  = ', rsc_psi
+         WRITE(numout,*) '      rsc_psi0 = ', rsc_psi0
+         WRITE(numout,*) '      rc0      = ', rc0
+         WRITE(numout,*)
+         WRITE(numout,*) '   Shear free turbulence parameters:'
+         WRITE(numout,*) '      rcm_sf   = ', rcm_sf
+         WRITE(numout,*) '      ra_sf    = ', ra_sf
+         WRITE(numout,*) '      rl_sf    = ', rl_sf
+      ENDIF
+
+      !                                !* Constants initialization
+      rc02  = rc0  * rc0   ;   rc02r = 1. / rc02
+      rc03  = rc02 * rc0
+      rc04  = rc03 * rc0
+      rsbc_tke1 = -3._wp/2._wp*rn_crban*ra_sf*rl_sf                      ! Dirichlet + Wave breaking
+      rsbc_tke2 = rdt * rn_crban / rl_sf                                 ! Neumann + Wave breaking 
+      zcr = MAX(rsmall, rsbc_tke1**(1./(-ra_sf*3._wp/2._wp))-1._wp )
+      rtrans = 0.2_wp / zcr                                              ! Ad. inverse transition length between log and wave layer 
+      rsbc_zs1  = rn_charn/grav                                          ! Charnock formula for surface roughness
+      rsbc_zs2  = rn_frac_hs / 0.85_wp / grav * 665._wp                  ! Rascle formula for surface roughness 
+      rsbc_psi1 = -0.5_wp * rdt * rc0**(rpp-2._wp*rmm) / rsc_psi
+      rsbc_psi2 = -0.5_wp * rdt * rc0**rpp * rnn * vkarmn**rnn / rsc_psi ! Neumann + NO Wave breaking 
+      !
+      rfact_tke = -0.5_wp / rsc_tke * rdt                                ! Cst used for the Diffusion term of tke
+      rfact_psi = -0.5_wp / rsc_psi * rdt                                ! Cst used for the Diffusion term of tke
+      !
+      !                                !* Wall proximity function
+!!gm tmask or wmask ????
+      zwall(:,:,:) = 1._wp * tmask(:,:,:)
+
+      !                                !* read or initialize all required files  
+      CALL gls_rst( nit000, 'READ' )      ! (en, avt_k, avm_k, hmxl_n)
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('en')
+         CALL iom_set_rstw_var_active('avt_k')
+         CALL iom_set_rstw_var_active('avm_k')
+         CALL iom_set_rstw_var_active('hmxl_n')
+      ENDIF
+      !
+   END SUBROUTINE zdf_gls_init
+
+
+   SUBROUTINE gls_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE gls_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write TKE file (en) in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain TKE, en is either 
+      !!                set to rn_emin or recomputed (nn_igls/=0)
+      !!----------------------------------------------------------------------
+      USE zdf_oce , ONLY : en, avt_k, avm_k   ! ocean vertical physics
+      !!
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   jit, jk   ! dummy loop indices
+      INTEGER ::   id1, id2, id3, id4
+      INTEGER ::   ji, jj, ikbu, ikbv
+      REAL(wp)::   cbx, cby
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            id1 = iom_varid( numror, 'en'    , ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'avt_k' , ldstop = .FALSE. )
+            id3 = iom_varid( numror, 'avm_k' , ldstop = .FALSE. )
+            id4 = iom_varid( numror, 'hmxl_n', ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3, id4 ) > 0 ) THEN        ! all required arrays exist
+               CALL iom_get( numror, jpdom_autoglo, 'en'    , en    , ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'avt_k' , avt_k , ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'avm_k' , avm_k , ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'hmxl_n', hmxl_n, ldxios = lrxios )
+            ELSE                        
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>   previous run without GLS scheme, set en and hmxl_n to background values'
+               en    (:,:,:) = rn_emin
+               hmxl_n(:,:,:) = 0.05_wp
+               ! avt_k, avm_k already set to the background value in zdf_phy_init
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>   start from rest, set en and hmxl_n by background values'
+            en    (:,:,:) = rn_emin
+            hmxl_n(:,:,:) = 0.05_wp
+            ! avt_k, avm_k already set to the background value in zdf_phy_init
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- gls-rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context         )
+         CALL iom_rstput( kt, nitrst, numrow, 'en'    , en    , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k' , avt_k , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k' , avm_k , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'hmxl_n', hmxl_n, ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         !
+      ENDIF
+      !
+   END SUBROUTINE gls_rst
+
+   !!======================================================================
+END MODULE zdfgls
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfiwm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfiwm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfiwm.F90	(revision 14097)
@@ -0,0 +1,495 @@
+MODULE zdfiwm
+   !!========================================================================
+   !!                       ***  MODULE  zdfiwm  ***
+   !! Ocean physics: Internal gravity wave-driven vertical mixing
+   !!========================================================================
+   !! History :  1.0  !  2004-04  (L. Bessieres, G. Madec)  Original code
+   !!             -   !  2006-08  (A. Koch-Larrouy)  Indonesian strait
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec)  reorganisation of initialisation phase
+   !!            3.6  !  2016-03  (C. de Lavergne)  New param: internal wave-driven mixing 
+   !!            4.0  !  2017-04  (G. Madec)  renamed module, remove the old param. and the CPP keys
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_iwm       : global     momentum & tracer Kz with wave induced Kz
+   !!   zdf_iwm_init  : global     momentum & tracer Kz with wave induced Kz
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE zdfddm         ! ocean vertical physics: double diffusive mixing
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE eosbn2         ! ocean equation of state
+   USE phycst         ! physical constants
+   !
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O Manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_iwm        ! called in step module 
+   PUBLIC   zdf_iwm_init   ! called in nemogcm module 
+
+   !                      !!* Namelist  namzdf_iwm : internal wave-driven mixing *
+   INTEGER ::  nn_zpyc     ! pycnocline-intensified mixing energy proportional to N (=1) or N^2 (=2)
+   LOGICAL ::  ln_mevar    ! variable (=T) or constant (=F) mixing efficiency
+   LOGICAL ::  ln_tsdiff   ! account for differential T/S wave-driven mixing (=T) or not (=F)
+
+   REAL(wp)::  r1_6 = 1._wp / 6._wp
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ebot_iwm   ! power available from high-mode wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   epyc_iwm   ! power available from low-mode, pycnocline-intensified wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ecri_iwm   ! power available from low-mode, critical slope wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hbot_iwm   ! WKB decay scale for high-mode energy dissipation (m)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hcri_iwm   ! decay scale for low-mode critical slope dissipation (m)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_iwm_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_iwm_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ebot_iwm(jpi,jpj),  epyc_iwm(jpi,jpj),  ecri_iwm(jpi,jpj) ,     &
+      &         hbot_iwm(jpi,jpj),  hcri_iwm(jpi,jpj)                     , STAT=zdf_iwm_alloc )
+      !
+      CALL mpp_sum ( 'zdfiwm', zdf_iwm_alloc )
+      IF( zdf_iwm_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_iwm_alloc: failed to allocate arrays' )
+   END FUNCTION zdf_iwm_alloc
+
+
+   SUBROUTINE zdf_iwm( kt, p_avm, p_avt, p_avs )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_iwm  ***
+      !!                   
+      !! ** Purpose :   add to the vertical mixing coefficients the effect of
+      !!              breaking internal waves.
+      !!
+      !! ** Method  : - internal wave-driven vertical mixing is given by:
+      !!                  Kz_wave = min(  100 cm2/s, f(  Reb = zemx_iwm /( Nu * N^2 )  )
+      !!              where zemx_iwm is the 3D space distribution of the wave-breaking 
+      !!              energy and Nu the molecular kinematic viscosity.
+      !!              The function f(Reb) is linear (constant mixing efficiency)
+      !!              if the namelist parameter ln_mevar = F and nonlinear if ln_mevar = T.
+      !!
+      !!              - Compute zemx_iwm, the 3D power density that allows to compute
+      !!              Reb and therefrom the wave-induced vertical diffusivity.
+      !!              This is divided into three components:
+      !!                 1. Bottom-intensified low-mode dissipation at critical slopes
+      !!                     zemx_iwm(z) = ( ecri_iwm / rau0 ) * EXP( -(H-z)/hcri_iwm )
+      !!                                   / ( 1. - EXP( - H/hcri_iwm ) ) * hcri_iwm
+      !!              where hcri_iwm is the characteristic length scale of the bottom 
+      !!              intensification, ecri_iwm a map of available power, and H the ocean depth.
+      !!                 2. Pycnocline-intensified low-mode dissipation
+      !!                     zemx_iwm(z) = ( epyc_iwm / rau0 ) * ( sqrt(rn2(z))^nn_zpyc )
+      !!                                   / SUM( sqrt(rn2(z))^nn_zpyc * e3w(z) )
+      !!              where epyc_iwm is a map of available power, and nn_zpyc
+      !!              is the chosen stratification-dependence of the internal wave
+      !!              energy dissipation.
+      !!                 3. WKB-height dependent high mode dissipation
+      !!                     zemx_iwm(z) = ( ebot_iwm / rau0 ) * rn2(z) * EXP(-z_wkb(z)/hbot_iwm)
+      !!                                   / SUM( rn2(z) * EXP(-z_wkb(z)/hbot_iwm) * e3w(z) )
+      !!              where hbot_iwm is the characteristic length scale of the WKB bottom 
+      !!              intensification, ebot_iwm is a map of available power, and z_wkb is the
+      !!              WKB-stretched height above bottom defined as
+      !!                    z_wkb(z) = H * SUM( sqrt(rn2(z'>=z)) * e3w(z'>=z) )
+      !!                                 / SUM( sqrt(rn2(z'))    * e3w(z')    )
+      !!
+      !!              - update the model vertical eddy viscosity and diffusivity: 
+      !!                     avt  = avt  +    av_wave
+      !!                     avm  = avm  +    av_wave
+      !!
+      !!              - if namelist parameter ln_tsdiff = T, account for differential mixing:
+      !!                     avs  = avt  +    av_wave * diffusivity_ratio(Reb)
+      !!
+      !! ** Action  : - avt, avs, avm, increased by tide internal wave-driven mixing    
+      !!
+      !! References :  de Lavergne et al. 2015, JPO; 2016, in prep.
+      !!----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   ) ::   kt             ! ocean time step
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avm          ! momentum Kz (w-points)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avt, p_avs   ! tracer   Kz (w-points)
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zztmp, ztmp1, ztmp2        ! scalar workspace
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zfact       ! Used for vertical structure
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zhdep       ! Ocean depth
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwkb        ! WKB-stretched height above bottom
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zweight     ! Weight for high mode vertical distribution
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   znu_t       ! Molecular kinematic viscosity (T grid)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   znu_w       ! Molecular kinematic viscosity (W grid)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zReb        ! Turbulence intensity parameter
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zemx_iwm    ! local energy density available for mixing (W/kg)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zav_ratio   ! S/T diffusivity ratio (only for ln_tsdiff=T)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zav_wave    ! Internal wave-induced diffusivity
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   z3d  ! 3D workspace used for iom_put 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   z2d  ! 2D     -      -    -     -
+      !!----------------------------------------------------------------------
+      !
+      !                       !* Set to zero the 1st and last vertical levels of appropriate variables
+      zemx_iwm (:,:,1) = 0._wp   ;   zemx_iwm (:,:,jpk) = 0._wp
+      zav_ratio(:,:,1) = 0._wp   ;   zav_ratio(:,:,jpk) = 0._wp
+      zav_wave (:,:,1) = 0._wp   ;   zav_wave (:,:,jpk) = 0._wp
+      !
+      !                       ! ----------------------------- !
+      !                       !  Internal wave-driven mixing  !  (compute zav_wave)
+      !                       ! ----------------------------- !
+      !                             
+      !                       !* Critical slope mixing: distribute energy over the time-varying ocean depth,
+      !                                                 using an exponential decay from the seafloor.
+      DO jj = 1, jpj                ! part independent of the level
+         DO ji = 1, jpi
+            zhdep(ji,jj) = gdepw_0(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean
+            zfact(ji,jj) = rau0 * (  1._wp - EXP( -zhdep(ji,jj) / hcri_iwm(ji,jj) )  )
+            IF( zfact(ji,jj) /= 0._wp )   zfact(ji,jj) = ecri_iwm(ji,jj) / zfact(ji,jj)
+         END DO
+      END DO
+!!gm gde3w ==>>>  check for ssh taken into account.... seem OK gde3w_n=gdept_n - sshn
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         DO jj = 1, jpj             
+            DO ji = 1, jpi
+               IF ( zfact(ji,jj) == 0._wp .OR. wmask(ji,jj,jk) == 0._wp ) THEN   ! optimization
+                  zemx_iwm(ji,jj,jk) = 0._wp
+               ELSE
+                  zemx_iwm(ji,jj,jk) = zfact(ji,jj) * (  EXP( ( gde3w_n(ji,jj,jk  ) - zhdep(ji,jj) ) / hcri_iwm(ji,jj) )     &
+                       &                               - EXP( ( gde3w_n(ji,jj,jk-1) - zhdep(ji,jj) ) / hcri_iwm(ji,jj) ) )   &
+                       &                            / ( gde3w_n(ji,jj,jk) - gde3w_n(ji,jj,jk-1) )
+               ENDIF
+            END DO
+         END DO
+!!gm delta(gde3w_n) = e3t_n  !!  Please verify the grid-point position w versus t-point
+!!gm it seems to me that only 1/hcri_iwm  is used ==>  compute it one for all
+
+      END DO
+
+      !                        !* Pycnocline-intensified mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to sqrt(rn2)^nn_zpyc
+      !                                          ! (NB: N2 is masked, so no use of wmask here)
+      SELECT CASE ( nn_zpyc )
+      !
+      CASE ( 1 )               ! Dissipation scales as N (recommended)
+         !
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+         !
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+         !
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zfact(:,:) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+         !
+      CASE ( 2 )               ! Dissipation scales as N^2
+         !
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+         !
+         DO jj= 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+         !
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zfact(:,:) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+         !
+      END SELECT
+
+      !                        !* WKB-height dependent mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to rn2 * exp(-z_wkb/rn_hbot)
+      !
+      zwkb (:,:,:) = 0._wp
+      zfact(:,:)   = 0._wp
+      DO jk = 2, jpkm1
+         zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         zwkb(:,:,jk) = zfact(:,:)
+      END DO
+!!gm even better:
+!      DO jk = 2, jpkm1
+!         zwkb(:,:) = zwkb(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  )
+!      END DO
+!      zfact(:,:) = zwkb(:,:,jpkm1)
+!!gm or just use zwkb(k=jpk-1) instead of zfact...
+!!gm
+      !
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zwkb(ji,jj,jk) = zhdep(ji,jj) * ( zfact(ji,jj) - zwkb(ji,jj,jk) )   &
+                  &                                     * wmask(ji,jj,jk) / zfact(ji,jj)
+            END DO
+         END DO
+      END DO
+      zwkb(:,:,1) = zhdep(:,:) * wmask(:,:,1)
+      !
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF ( rn2(ji,jj,jk) <= 0._wp .OR. wmask(ji,jj,jk) == 0._wp ) THEN   ! optimization
+                  zweight(ji,jj,jk) = 0._wp
+               ELSE
+                  zweight(ji,jj,jk) = rn2(ji,jj,jk) * hbot_iwm(ji,jj)    &
+                     &   * (  EXP( -zwkb(ji,jj,jk) / hbot_iwm(ji,jj) ) - EXP( -zwkb(ji,jj,jk-1) / hbot_iwm(ji,jj) )  )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      zfact(:,:) = 0._wp
+      DO jk = 2, jpkm1              ! part independent of the level
+         zfact(:,:) = zfact(:,:) + zweight(:,:,jk)
+      END DO
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = ebot_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+         END DO
+      END DO
+      !
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zweight(:,:,jk) * zfact(:,:) * wmask(:,:,jk)   &
+            &                                / ( gde3w_n(:,:,jk) - gde3w_n(:,:,jk-1) )
+!!gm  use of e3t_n just above?
+      END DO
+      !
+!!gm  this is to be replaced by just a constant value znu=1.e-6 m2/s
+      ! Calculate molecular kinematic viscosity
+      znu_t(:,:,:) = 1.e-4_wp * (  17.91_wp - 0.53810_wp * tsn(:,:,:,jp_tem) + 0.00694_wp * tsn(:,:,:,jp_tem) * tsn(:,:,:,jp_tem)  &
+         &                                  + 0.02305_wp * tsn(:,:,:,jp_sal)  ) * tmask(:,:,:) * r1_rau0
+      DO jk = 2, jpkm1
+         znu_w(:,:,jk) = 0.5_wp * ( znu_t(:,:,jk-1) + znu_t(:,:,jk) ) * wmask(:,:,jk)
+      END DO
+!!gm end
+      !
+      ! Calculate turbulence intensity parameter Reb
+      DO jk = 2, jpkm1
+         zReb(:,:,jk) = zemx_iwm(:,:,jk) / MAX( 1.e-20_wp, znu_w(:,:,jk) * rn2(:,:,jk) )
+      END DO
+      !
+      ! Define internal wave-induced diffusivity
+      DO jk = 2, jpkm1
+         zav_wave(:,:,jk) = znu_w(:,:,jk) * zReb(:,:,jk) * r1_6   ! This corresponds to a constant mixing efficiency of 1/6
+      END DO
+      !
+      IF( ln_mevar ) THEN              ! Variable mixing efficiency case : modify zav_wave in the
+         DO jk = 2, jpkm1              ! energetic (Reb > 480) and buoyancy-controlled (Reb <10.224 ) regimes
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( zReb(ji,jj,jk) > 480.00_wp ) THEN
+                     zav_wave(ji,jj,jk) = 3.6515_wp * znu_w(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ELSEIF( zReb(ji,jj,jk) < 10.224_wp ) THEN
+                     zav_wave(ji,jj,jk) = 0.052125_wp * znu_w(ji,jj,jk) * zReb(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+      DO jk = 2, jpkm1                 ! Bound diffusivity by molecular value and 100 cm2/s
+         zav_wave(:,:,jk) = MIN(  MAX( 1.4e-7_wp, zav_wave(:,:,jk) ), 1.e-2_wp  ) * wmask(:,:,jk)
+      END DO
+      !
+      IF( kt == nit000 ) THEN        !* Control print at first time-step: diagnose the energy consumed by zav_wave
+         zztmp = 0._wp
+!!gm used of glosum 3D....
+         DO jk = 2, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zztmp = zztmp + e3w_n(ji,jj,jk) * e1e2t(ji,jj)   &
+                     &          * MAX( 0._wp, rn2(ji,jj,jk) ) * zav_wave(ji,jj,jk) * wmask(ji,jj,jk) * tmask_i(ji,jj)
+               END DO
+            END DO
+         END DO
+         CALL mpp_sum( 'zdfiwm', zztmp )
+         zztmp = rau0 * zztmp ! Global integral of rauo * Kz * N^2 = power contributing to mixing 
+         !
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'zdf_iwm : Internal wave-driven mixing (iwm)'
+            WRITE(numout,*) '~~~~~~~ '
+            WRITE(numout,*)
+            WRITE(numout,*) '      Total power consumption by av_wave =  ', zztmp * 1.e-12_wp, 'TW'
+         ENDIF
+      ENDIF
+
+      !                          ! ----------------------- !
+      !                          !   Update  mixing coefs  !                          
+      !                          ! ----------------------- !
+      !      
+      IF( ln_tsdiff ) THEN          !* Option for differential mixing of salinity and temperature
+         ztmp1 = 0.505_wp + 0.495_wp * TANH( 0.92_wp * ( LOG10( 1.e-20_wp ) - 0.60_wp ) )
+         DO jk = 2, jpkm1              ! Calculate S/T diffusivity ratio as a function of Reb
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ztmp2 = zReb(ji,jj,jk) * 5._wp * r1_6
+                  IF ( ztmp2 > 1.e-20_wp .AND. wmask(ji,jj,jk) == 1._wp ) THEN
+                     zav_ratio(ji,jj,jk) = 0.505_wp + 0.495_wp * TANH( 0.92_wp * ( LOG10(ztmp2) - 0.60_wp ) )
+                  ELSE
+                     zav_ratio(ji,jj,jk) = ztmp1 * wmask(ji,jj,jk)
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "av_ratio", zav_ratio )
+         DO jk = 2, jpkm1           !* update momentum & tracer diffusivity with wave-driven mixing
+            p_avs(:,:,jk) = p_avs(:,:,jk) + zav_wave(:,:,jk) * zav_ratio(:,:,jk)
+            p_avt(:,:,jk) = p_avt(:,:,jk) + zav_wave(:,:,jk)
+            p_avm(:,:,jk) = p_avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+         !
+      ELSE                          !* update momentum & tracer diffusivity with wave-driven mixing
+         DO jk = 2, jpkm1
+            p_avs(:,:,jk) = p_avs(:,:,jk) + zav_wave(:,:,jk)
+            p_avt(:,:,jk) = p_avt(:,:,jk) + zav_wave(:,:,jk)
+            p_avm(:,:,jk) = p_avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+      ENDIF
+
+      !                             !* output internal wave-driven mixing coefficient
+      CALL iom_put( "av_wave", zav_wave )
+                                    !* output useful diagnostics: Kz*N^2 , 
+!!gm Kz*N2 should take into account the ratio avs/avt if it is used.... (see diaar5)
+                                    !  vertical integral of rau0 * Kz * N^2 , energy density (zemx_iwm)
+      IF( iom_use("bflx_iwm") .OR. iom_use("pcmap_iwm") ) THEN
+         ALLOCATE( z2d(jpi,jpj) , z3d(jpi,jpj,jpk) )
+         z3d(:,:,:) = MAX( 0._wp, rn2(:,:,:) ) * zav_wave(:,:,:)
+         z2d(:,:) = 0._wp
+         DO jk = 2, jpkm1
+            z2d(:,:) = z2d(:,:) + e3w_n(:,:,jk) * z3d(:,:,jk) * wmask(:,:,jk)
+         END DO
+         z2d(:,:) = rau0 * z2d(:,:)
+         CALL iom_put( "bflx_iwm", z3d )
+         CALL iom_put( "pcmap_iwm", z2d )
+         DEALLOCATE( z2d , z3d )
+      ENDIF
+      CALL iom_put( "emix_iwm", zemx_iwm )
+      
+      IF(ln_ctl)   CALL prt_ctl(tab3d_1=zav_wave , clinfo1=' iwm - av_wave: ', tab3d_2=avt, clinfo2=' avt: ', kdim=jpk)
+      !
+   END SUBROUTINE zdf_iwm
+
+
+   SUBROUTINE zdf_iwm_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_iwm_init  ***
+      !!                     
+      !! ** Purpose :   Initialization of the wave-driven vertical mixing, reading
+      !!              of input power maps and decay length scales in netcdf files.
+      !!
+      !! ** Method  : - Read the namzdf_iwm namelist and check the parameters
+      !!
+      !!              - Read the input data in NetCDF files :
+      !!              power available from high-mode wave breaking (mixing_power_bot.nc)
+      !!              power available from pycnocline-intensified wave-breaking (mixing_power_pyc.nc)
+      !!              power available from critical slope wave-breaking (mixing_power_cri.nc)
+      !!              WKB decay scale for high-mode wave-breaking (decay_scale_bot.nc)
+      !!              decay scale for critical slope wave-breaking (decay_scale_cri.nc)
+      !!
+      !! ** input   : - Namlist namzdf_iwm
+      !!              - NetCDF files : mixing_power_bot.nc, mixing_power_pyc.nc, mixing_power_cri.nc,
+      !!              decay_scale_bot.nc decay_scale_cri.nc
+      !!
+      !! ** Action  : - Increase by 1 the nstop flag is setting problem encounter
+      !!              - Define ebot_iwm, epyc_iwm, ecri_iwm, hbot_iwm, hcri_iwm
+      !!
+      !! References : de Lavergne et al. JPO, 2015 ; de Lavergne PhD 2016
+      !!              de Lavergne et al. in prep., 2017
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   inum         ! local integer
+      INTEGER  ::   ios
+      REAL(wp) ::   zbot, zpyc, zcri   ! local scalars
+      !!
+      NAMELIST/namzdf_iwm/ nn_zpyc, ln_mevar, ln_tsdiff
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_iwm in reference namelist : Wave-driven mixing
+      READ  ( numnam_ref, namzdf_iwm, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namzdf_iwm in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namzdf_iwm in configuration namelist : Wave-driven mixing
+      READ  ( numnam_cfg, namzdf_iwm, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namzdf_iwm in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_iwm )
+      !
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_iwm_init : internal wave-driven mixing'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_iwm : set wave-driven mixing parameters'
+         WRITE(numout,*) '      Pycnocline-intensified diss. scales as N (=1) or N^2 (=2) = ', nn_zpyc
+         WRITE(numout,*) '      Variable (T) or constant (F) mixing efficiency            = ', ln_mevar
+         WRITE(numout,*) '      Differential internal wave-driven mixing (T) or not (F)   = ', ln_tsdiff
+      ENDIF
+      
+      ! The new wave-driven mixing parameterization elevates avt and avm in the interior, and
+      ! ensures that avt remains larger than its molecular value (=1.4e-7). Therefore, avtb should 
+      ! be set here to a very small value, and avmb to its (uniform) molecular value (=1.4e-6).
+      avmb(:) = 1.4e-6_wp        ! viscous molecular value
+      avtb(:) = 1.e-10_wp        ! very small diffusive minimum (background avt is specified in zdf_iwm)    
+      avtb_2d(:,:) = 1.e0_wp     ! uniform 
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Force the background value applied to avm & avt in TKE to be everywhere ',   &
+            &               'the viscous molecular value & a very small diffusive value, resp.'
+      ENDIF
+            
+      !                             ! allocate iwm arrays
+      IF( zdf_iwm_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_iwm_init : unable to allocate iwm arrays' )
+      !
+      !                             ! read necessary fields
+      CALL iom_open('mixing_power_bot',inum)       ! energy flux for high-mode wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', ebot_iwm, 1 ) 
+      CALL iom_close(inum)
+      !
+      CALL iom_open('mixing_power_pyc',inum)       ! energy flux for pynocline-intensified wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', epyc_iwm, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('mixing_power_cri',inum)       ! energy flux for critical slope wave breaking [W/m2]
+      CALL iom_get  (inum, jpdom_data, 'field', ecri_iwm, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('decay_scale_bot',inum)        ! spatially variable decay scale for high-mode wave breaking [m]
+      CALL iom_get  (inum, jpdom_data, 'field', hbot_iwm, 1 )
+      CALL iom_close(inum)
+      !
+      CALL iom_open('decay_scale_cri',inum)        ! spatially variable decay scale for critical slope wave breaking [m]
+      CALL iom_get  (inum, jpdom_data, 'field', hcri_iwm, 1 )
+      CALL iom_close(inum)
+
+      ebot_iwm(:,:) = ebot_iwm(:,:) * ssmask(:,:)
+      epyc_iwm(:,:) = epyc_iwm(:,:) * ssmask(:,:)
+      ecri_iwm(:,:) = ecri_iwm(:,:) * ssmask(:,:)
+
+      zbot = glob_sum( 'zdfiwm', e1e2t(:,:) * ebot_iwm(:,:) )
+      zpyc = glob_sum( 'zdfiwm', e1e2t(:,:) * epyc_iwm(:,:) )
+      zcri = glob_sum( 'zdfiwm', e1e2t(:,:) * ecri_iwm(:,:) )
+      IF(lwp) THEN
+         WRITE(numout,*) '      High-mode wave-breaking energy:             ', zbot * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Pycnocline-intensifed wave-breaking energy: ', zpyc * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Critical slope wave-breaking energy:        ', zcri * 1.e-12_wp, 'TW'
+      ENDIF
+      !
+   END SUBROUTINE zdf_iwm_init
+
+   !!======================================================================
+END MODULE zdfiwm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfmxl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfmxl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfmxl.F90	(revision 14097)
@@ -0,0 +1,144 @@
+MODULE zdfmxl
+   !!======================================================================
+   !!                       ***  MODULE  zdfmxl  ***
+   !! Ocean physics: mixed layer depth 
+   !!======================================================================
+   !! 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.
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE trc_oce  , ONLY: l_offline         ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics
+   !
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_mxl   ! called by zdfphy.F90
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   nmln    !: number of level in the mixed layer (used by LDF, ZDF, TRD, TOP)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmld    !: mixing layer depth (turbocline)      [m]   (used by TOP)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlp    !: mixed layer depth  (rho=rho0+zdcrit) [m]   (used by LDF)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlpt   !: depth of the last T-point inside the mixed layer [m] (used by LDF)
+
+   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
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_mxl_alloc()
+      !!----------------------------------------------------------------------
+      !!               ***  FUNCTION zdf_mxl_alloc  ***
+      !!----------------------------------------------------------------------
+      zdf_mxl_alloc = 0      ! set to zero if no array to be allocated
+      IF( .NOT. ALLOCATED( nmln ) ) THEN
+         ALLOCATE( nmln(jpi,jpj), hmld(jpi,jpj), hmlp(jpi,jpj), hmlpt(jpi,jpj), STAT= zdf_mxl_alloc )
+         !
+         CALL mpp_sum ( 'zdfmxl', zdf_mxl_alloc )
+         IF( zdf_mxl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_mxl_alloc: failed to allocate arrays.' )
+         !
+      ENDIF
+   END FUNCTION zdf_mxl_alloc
+
+
+   SUBROUTINE zdf_mxl( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdfmxl  ***
+      !!                   
+      !! ** Purpose :   Compute the turbocline depth and the mixed layer depth
+      !!              with density criteria.
+      !!
+      !! ** Method  :   The mixed layer depth is the shallowest W depth with 
+      !!      the density of the corresponding T point (just bellow) bellow a
+      !!      given value defined locally as rho(10m) + rho_c
+      !!               The turbocline depth is the depth at which the vertical
+      !!      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 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, ikt ! local integer
+      REAL(wp) ::   zN2_c           ! local scalar
+      INTEGER, DIMENSION(jpi,jpj) ::   imld   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'zdf_mxl : mixed layer depth'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+         !                             ! allocate zdfmxl arrays
+         IF( zdf_mxl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_mxl : unable to allocate arrays' )
+      ENDIF
+      !
+      ! w-level of the mixing and mixed layers
+      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 ) * e3w_n(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 and mixing layer (iom_use)
+      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( avt (ji,jj,jk) < avt_c * wmask(ji,jj,jk) )   imld(ji,jj) = jk      ! Turbocline 
+            END DO
+         END DO
+      END DO
+      ! depth of the mixing and mixed layers
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            iiki = imld(ji,jj)
+            iikn = nmln(ji,jj)
+            hmld (ji,jj) = gdepw_n(ji,jj,iiki  ) * ssmask(ji,jj)    ! Turbocline depth 
+            hmlp (ji,jj) = gdepw_n(ji,jj,iikn  ) * ssmask(ji,jj)    ! Mixed layer depth
+            hmlpt(ji,jj) = gdept_n(ji,jj,iikn-1) * ssmask(ji,jj)    ! depth of the last T-point inside the mixed layer
+         END DO
+      END DO
+      !
+      IF( .NOT.l_offline ) THEN
+         IF( iom_use("mldr10_1") ) THEN
+            IF( ln_isfcav ) THEN  ;  CALL iom_put( "mldr10_1", hmlp - risfdep)   ! mixed layer thickness
+            ELSE                  ;  CALL iom_put( "mldr10_1", hmlp )            ! mixed layer depth
+            END IF
+         END IF
+         IF( iom_use("mldkz5") ) THEN
+            IF( ln_isfcav ) THEN  ;  CALL iom_put( "mldkz5"  , hmld - risfdep )   ! turbocline thickness
+            ELSE                  ;  CALL iom_put( "mldkz5"  , hmld )             ! turbocline depth
+            END IF
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=REAL(nmln,wp), clinfo1=' nmln : ', tab2d_2=hmlp, clinfo2=' hmlp : ' )
+      !
+   END SUBROUTINE zdf_mxl
+
+   !!======================================================================
+END MODULE zdfmxl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfosm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfosm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfosm.F90	(revision 14097)
@@ -0,0 +1,1733 @@
+MODULE zdfosm
+   !!======================================================================
+   !!                       ***  MODULE  zdfosm  ***
+   !! Ocean physics:  vertical mixing coefficient compute from the OSMOSIS
+   !!                 turbulent closure parameterization
+   !!=====================================================================
+   !!  History : NEMO 4.0  ! A. Grant, G. Nurser
+   !! 15/03/2017  Changed calculation of pycnocline thickness in unstable conditions and stable conditions AG
+   !! 15/03/2017  Calculation of pycnocline gradients for stable conditions changed. Pycnocline gradients now depend on stability of the OSBL. A.G
+   !! 06/06/2017  (1) Checks on sign of buoyancy jump in calculation of  OSBL depth.  A.G.
+   !!             (2) Removed variable zbrad0, zbradh and zbradav since they are not used.
+   !!             (3) Approximate treatment for shear turbulence.
+   !!                        Minimum values for zustar and zustke.
+   !!                        Add velocity scale, zvstr, that tends to zustar for large Langmuir numbers.
+   !!                        Limit maximum value for Langmuir number.
+   !!                        Use zvstr in definition of stability parameter zhol.
+   !!             (4) Modified parametrization of entrainment flux, changing original coefficient 0.0485 for Langmuir contribution to 0.135 * zla
+   !!             (5) For stable boundary layer add factor that depends on length of timestep to 'slow' collapse and growth. Make sure buoyancy jump not negative.
+   !!             (6) For unstable conditions when growth is over multiple levels, limit change to maximum of one level per cycle through loop.
+   !!             (7) Change lower limits for loops that calculate OSBL averages from 1 to 2. Large gradients between levels 1 and 2 can cause problems.
+   !!             (8) Change upper limits from ibld-1 to ibld.
+   !!             (9) Calculation of pycnocline thickness in unstable conditions. Check added to ensure that buoyancy jump is positive before calculating Ri.
+   !!            (10) Thickness of interface layer at base of the stable OSBL set by Richardson number. Gives continuity in transition from unstable OSBL.
+   !!            (11) Checks that buoyancy jump is poitive when calculating pycnocline profiles.
+   !!            (12) Replace zwstrl with zvstr in calculation of eddy viscosity.
+   !! 27/09/2017 (13) Calculate Stokes drift and Stokes penetration depth from wave information
+   !!            (14) Bouyancy flux due to entrainment changed to include contribution from shear turbulence (for testing commented out).
+   !! 28/09/2017 (15) Calculation of Stokes drift moved into separate do-loops to allow for different options for the determining the Stokes drift to be added.
+   !!            (16) Calculation of Stokes drift from windspeed for PM spectrum (for testing, commented out)
+   !!            (17) Modification to Langmuir velocity scale to include effects due to the Stokes penetration depth (for testing, commented out)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   'ln_zdfosm'                                             OSMOSIS scheme
+   !!----------------------------------------------------------------------
+   !!   zdf_osm       : update momentum and tracer Kz from osm scheme
+   !!   zdf_osm_init  : initialization, namelist read, and parameters control
+   !!   osm_rst       : read (or initialize) and write osmosis restart fields
+   !!   tra_osm       : compute and add to the T & S trend the non-local flux
+   !!   trc_osm       : compute and add to the passive tracer trend the non-local flux (TBD)
+   !!   dyn_osm       : compute and add to u & v trensd the non-local flux
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and active tracers
+                      ! uses wn from previous time step (which is now wb) to calculate hbl
+   USE dom_oce        ! ocean space and time domain
+   USE zdf_oce        ! ocean vertical physics
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE sbcwave        ! surface wave parameters
+   USE phycst         ! physical constants
+   USE eosbn2         ! equation of state
+   USE traqsr         ! details of solar radiation absorption
+   USE zdfddm         ! double diffusion mixing (avs array)
+   USE iom            ! I/O library
+   USE lib_mpp        ! MPP library
+   USE trd_oce        ! ocean trends definition
+   USE trdtra         ! tracers trends
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl         ! Print control
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_osm       ! routine called by step.F90
+   PUBLIC   zdf_osm_init  ! routine called by nemogcm.F90
+   PUBLIC   osm_rst       ! routine called by step.F90
+   PUBLIC   tra_osm       ! routine called by step.F90
+   PUBLIC   trc_osm       ! routine called by trcstp.F90
+   PUBLIC   dyn_osm       ! routine called by 'step.F90'
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ghamu    !: non-local u-momentum flux
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ghamv    !: non-local v-momentum flux
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ghamt    !: non-local temperature flux (gamma/<ws>o)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ghams    !: non-local salinity flux (gamma/<ws>o)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   etmean   !: averaging operator for avt
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hbl      !: boundary layer depth
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   hbli     !: intial boundary layer depth for stable blayer
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dstokes  !: penetration depth of the Stokes drift.
+
+   !                      !!** Namelist  namzdf_osm  **
+   LOGICAL  ::   ln_use_osm_la      ! Use namelist  rn_osm_la
+   REAL(wp) ::   rn_osm_la          ! Turbulent Langmuir number
+   REAL(wp) ::   rn_osm_dstokes     ! Depth scale of Stokes drift
+   REAL(wp) ::   rn_osm_hbl0 = 10._wp       ! Initial value of hbl for 1D runs
+   INTEGER  ::   nn_ave             ! = 0/1 flag for horizontal average on avt
+   INTEGER  ::   nn_osm_wave = 0    ! = 0/1/2 flag for getting stokes drift from La# / PM wind-waves/Inputs into sbcwave
+   LOGICAL  ::   ln_dia_osm         ! Use namelist  rn_osm_la
+
+
+   LOGICAL  ::   ln_kpprimix  = .true.  ! Shear instability mixing
+   REAL(wp) ::   rn_riinfty   = 0.7     ! local Richardson Number limit for shear instability
+   REAL(wp) ::   rn_difri    =  0.005   ! maximum shear mixing at Rig = 0    (m2/s)
+   LOGICAL  ::   ln_convmix  = .true.   ! Convective instability mixing
+   REAL(wp) ::   rn_difconv = 1._wp     ! diffusivity when unstable below BL  (m2/s)
+
+   !                                    !!! ** General constants  **
+   REAL(wp) ::   epsln   = 1.0e-20_wp   ! a small positive number
+   REAL(wp) ::   pthird  = 1._wp/3._wp  ! 1/3
+   REAL(wp) ::   p2third = 2._wp/3._wp  ! 2/3
+
+   INTEGER :: idebug = 236
+   INTEGER :: jdebug = 228
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_osm_alloc()
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION zdf_osm_alloc  ***
+      !!----------------------------------------------------------------------
+     ALLOCATE( ghamu(jpi,jpj,jpk), ghamv(jpi,jpj,jpk), ghamt(jpi,jpj,jpk), ghams(jpi,jpj,jpk), &
+          &      hbl(jpi,jpj)    ,  hbli(jpi,jpj)    , dstokes(jpi, jpj) ,                     &
+          &   etmean(jpi,jpj,jpk),  STAT= zdf_osm_alloc )
+     IF( zdf_osm_alloc /= 0 )   CALL ctl_warn('zdf_osm_alloc: failed to allocate zdf_osm arrays')
+     CALL mpp_sum ( 'zdfosm', zdf_osm_alloc )
+   END FUNCTION zdf_osm_alloc
+
+
+   SUBROUTINE zdf_osm( kt, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_osm  ***
+      !!
+      !! ** Purpose :   Compute the vertical eddy viscosity and diffusivity
+      !!      coefficients and non local mixing using the OSMOSIS scheme
+      !!
+      !! ** Method :   The boundary layer depth hosm is diagnosed at tracer points
+      !!      from profiles of buoyancy, and shear, and the surface forcing.
+      !!      Above hbl (sigma=-z/hbl <1) the mixing coefficients are computed from
+      !!
+      !!                      Kx =  hosm  Wx(sigma) G(sigma)
+      !!
+      !!             and the non local term ghamt = Cs / Ws(sigma) / hosm
+      !!      Below hosm  the coefficients are the sum of mixing due to internal waves
+      !!      shear instability and double diffusion.
+      !!
+      !!      -1- Compute the now interior vertical mixing coefficients at all depths.
+      !!      -2- Diagnose the boundary layer depth.
+      !!      -3- Compute the now boundary layer vertical mixing coefficients.
+      !!      -4- Compute the now vertical eddy vicosity and diffusivity.
+      !!      -5- Smoothing
+      !!
+      !!        N.B. The computation is done from jk=2 to jpkm1
+      !!             Surface value of avt are set once a time to zero
+      !!             in routine zdf_osm_init.
+      !!
+      !! ** Action  :   update the non-local terms ghamts
+      !!                update avt (before vertical eddy coef.)
+      !!
+      !! References : Large W.G., Mc Williams J.C. and Doney S.C.
+      !!         Reviews of Geophysics, 32, 4, November 1994
+      !!         Comments in the code refer to this paper, particularly
+      !!         the equation number. (LMD94, here after)
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   kt            ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::  p_avm, p_avt   ! momentum and tracer Kz (w-points)
+      !!
+      INTEGER ::   ji, jj, jk                   ! dummy loop indices
+      INTEGER ::   ikbot, jkmax, jkm1, jkp2     !
+
+      REAL(wp) ::   ztx, zty, zflageos, zstabl, zbuofdep,zucube      !
+      REAL(wp) ::   zbeta, zthermal                                  !
+      REAL(wp) ::   zehat, zeta, zhrib, zsig, zscale, zwst, zws, zwm ! Velocity scales
+      REAL(wp) ::   zwsun, zwmun, zcons, zconm, zwcons, zwconm       !
+      REAL(wp) ::   zsr, zbw, ze, zb, zd, zc, zaw, za, zb1, za1, zkw, zk0, zcomp , zrhd,zrhdr,zbvzed   ! In situ density
+      INTEGER  ::   jm                          ! dummy loop indices
+      REAL(wp) ::   zr1, zr2, zr3, zr4, zrhop   ! Compression terms
+      REAL(wp) ::   zflag, zrn2, zdep21, zdep32, zdep43
+      REAL(wp) ::   zesh2, zri, zfri            ! Interior richardson mixing
+      REAL(wp) ::   zdelta, zdelta2, zdzup, zdzdn, zdzh, zvath, zgat1, zdat1, zkm1m, zkm1t
+      REAL(wp) :: zt,zs,zu,zv,zrh               ! variables used in constructing averages
+! Scales
+      REAL(wp), DIMENSION(jpi,jpj) :: zrad0     ! Surface solar temperature flux (deg m/s)
+      REAL(wp), DIMENSION(jpi,jpj) :: zradh     ! Radiative flux at bl base (Buoyancy units)
+      REAL(wp), DIMENSION(jpi,jpj) :: zradav    ! Radiative flux, bl average (Buoyancy Units)
+      REAL(wp), DIMENSION(jpi,jpj) :: zustar    ! friction velocity
+      REAL(wp), DIMENSION(jpi,jpj) :: zwstrl    ! Langmuir velocity scale
+      REAL(wp), DIMENSION(jpi,jpj) :: zvstr     ! Velocity scale that ends to zustar for large Langmuir number.
+      REAL(wp), DIMENSION(jpi,jpj) :: zwstrc    ! Convective velocity scale
+      REAL(wp), DIMENSION(jpi,jpj) :: zuw0      ! Surface u-momentum flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zvw0      ! Surface v-momentum flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zwth0     ! Surface heat flux (Kinematic)
+      REAL(wp), DIMENSION(jpi,jpj) :: zws0      ! Surface freshwater flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zwb0      ! Surface buoyancy flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zwthav    ! Heat flux - bl average
+      REAL(wp), DIMENSION(jpi,jpj) :: zwsav     ! freshwater flux - bl average
+      REAL(wp), DIMENSION(jpi,jpj) :: zwbav     ! Buoyancy flux - bl average
+      REAL(wp), DIMENSION(jpi,jpj) :: zwb_ent   ! Buoyancy entrainment flux
+      REAL(wp), DIMENSION(jpi,jpj) :: zustke    ! Surface Stokes drift
+      REAL(wp), DIMENSION(jpi,jpj) :: zla       ! Trubulent Langmuir number
+      REAL(wp), DIMENSION(jpi,jpj) :: zcos_wind ! Cos angle of surface stress
+      REAL(wp), DIMENSION(jpi,jpj) :: zsin_wind ! Sin angle of surface stress
+      REAL(wp), DIMENSION(jpi,jpj) :: zhol      ! Stability parameter for boundary layer
+      LOGICAL, DIMENSION(:,:), ALLOCATABLE :: lconv ! unstable/stable bl
+
+      ! mixed-layer variables
+
+      INTEGER, DIMENSION(jpi,jpj) :: ibld ! level of boundary layer base
+      INTEGER, DIMENSION(jpi,jpj) :: imld ! level of mixed-layer depth (pycnocline top)
+
+      REAL(wp) :: ztgrad,zsgrad,zbgrad ! Temporary variables used to calculate pycnocline gradients
+      REAL(wp) :: zugrad,zvgrad        ! temporary variables for calculating pycnocline shear
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zhbl  ! bl depth - grid
+      REAL(wp), DIMENSION(jpi,jpj) :: zhml  ! ml depth - grid
+      REAL(wp), DIMENSION(jpi,jpj) :: zdh   ! pycnocline depth - grid
+      REAL(wp), DIMENSION(jpi,jpj) :: zdhdt ! BL depth tendency
+      REAL(wp), DIMENSION(jpi,jpj) :: zt_bl,zs_bl,zu_bl,zv_bl,zrh_bl  ! averages over the depth of the blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zt_ml,zs_ml,zu_ml,zv_ml,zrh_ml  ! averages over the depth of the mixed layer
+      REAL(wp), DIMENSION(jpi,jpj) :: zdt_bl,zds_bl,zdu_bl,zdv_bl,zdrh_bl,zdb_bl ! difference between blayer average and parameter at base of blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zdt_ml,zds_ml,zdu_ml,zdv_ml,zdrh_ml,zdb_ml ! difference between mixed layer average and parameter at base of blayer
+      REAL(wp), DIMENSION(jpi,jpj) :: zwth_ent,zws_ent ! heat and salinity fluxes at the top of the pycnocline
+      REAL(wp), DIMENSION(jpi,jpj) :: zuw_bse,zvw_bse  ! momentum fluxes at the top of the pycnocline
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdtdz_pyc    ! parametrized gradient of temperature in pycnocline
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdsdz_pyc    ! parametrised gradient of salinity in pycnocline
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdbdz_pyc    ! parametrised gradient of buoyancy in the pycnocline
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdudz_pyc    ! u-shear across the pycnocline
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdvdz_pyc    ! v-shear across the pycnocline
+
+      ! Flux-gradient relationship variables
+
+      REAL(wp) :: zl_c,zl_l,zl_eps  ! Used to calculate turbulence length scale.
+
+      REAL(wp), DIMENSION(jpi,jpj) :: zdifml_sc,zvisml_sc,zdifpyc_sc,zvispyc_sc,zbeta_d_sc,zbeta_v_sc ! Scales for eddy diffusivity/viscosity
+      REAL(wp), DIMENSION(jpi,jpj) :: zsc_wth_1,zsc_ws_1 ! Temporary scales used to calculate scalar non-gradient terms.
+      REAL(wp), DIMENSION(jpi,jpj) :: zsc_uw_1,zsc_uw_2,zsc_vw_1,zsc_vw_2 ! Temporary scales for non-gradient momentum flux terms.
+      REAL(wp), DIMENSION(jpi,jpj) :: zhbl_t ! holds boundary layer depth updated by full timestep
+
+      ! For calculating Ri#-dependent mixing
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: z3du   ! u-shear^2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: z3dv   ! v-shear^2
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zrimix ! spatial form of ri#-induced diffusion
+
+      ! Temporary variables
+      INTEGER :: inhml
+      INTEGER :: i_lconv_alloc
+      REAL(wp) :: znd,znd_d,zznd_ml,zznd_pyc,zznd_d ! temporary non-dimensional depths used in various routines
+      REAL(wp) :: ztemp, zari, zpert, zzdhdt, zdb   ! temporary variables
+      REAL(wp) :: zthick, zz0, zz1 ! temporary variables
+      REAL(wp) :: zvel_max, zhbl_s ! temporary variables
+      REAL(wp) :: zfac             ! temporary variable
+      REAL(wp) :: zus_x, zus_y     ! temporary Stokes drift
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zviscos ! viscosity
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdiffut ! t-diffusivity
+
+      ! For debugging
+      INTEGER :: ikt
+      !!--------------------------------------------------------------------
+      !
+      ALLOCATE( lconv(jpi,jpj),  STAT= i_lconv_alloc )
+      IF( i_lconv_alloc /= 0 )   CALL ctl_warn('zdf_osm: failed to allocate lconv')
+
+      ibld(:,:)   = 0     ; imld(:,:)  = 0
+      zrad0(:,:)  = 0._wp ; zradh(:,:) = 0._wp ; zradav(:,:)    = 0._wp ; zustar(:,:)    = 0._wp
+      zwstrl(:,:) = 0._wp ; zvstr(:,:) = 0._wp ; zwstrc(:,:)    = 0._wp ; zuw0(:,:)      = 0._wp
+      zvw0(:,:)   = 0._wp ; zwth0(:,:) = 0._wp ; zws0(:,:)      = 0._wp ; zwb0(:,:)      = 0._wp
+      zwthav(:,:) = 0._wp ; zwsav(:,:) = 0._wp ; zwbav(:,:)     = 0._wp ; zwb_ent(:,:)   = 0._wp
+      zustke(:,:) = 0._wp ; zla(:,:)   = 0._wp ; zcos_wind(:,:) = 0._wp ; zsin_wind(:,:) = 0._wp
+      zhol(:,:)   = 0._wp
+      lconv(:,:)  = .FALSE.
+      ! mixed layer
+      ! no initialization of zhbl or zhml (or zdh?)
+      zhbl(:,:)    = 1._wp ; zhml(:,:)    = 1._wp ; zdh(:,:)      = 1._wp ; zdhdt(:,:)   = 0._wp
+      zt_bl(:,:)   = 0._wp ; zs_bl(:,:)   = 0._wp ; zu_bl(:,:)    = 0._wp ; zv_bl(:,:)   = 0._wp
+      zrh_bl(:,:)  = 0._wp ; zt_ml(:,:)   = 0._wp ; zs_ml(:,:)    = 0._wp ; zu_ml(:,:)   = 0._wp
+      zv_ml(:,:)   = 0._wp ; zrh_ml(:,:)  = 0._wp ; zdt_bl(:,:)   = 0._wp ; zds_bl(:,:)  = 0._wp
+      zdu_bl(:,:)  = 0._wp ; zdv_bl(:,:)  = 0._wp ; zdrh_bl(:,:)  = 0._wp ; zdb_bl(:,:)  = 0._wp
+      zdt_ml(:,:)  = 0._wp ; zds_ml(:,:)  = 0._wp ; zdu_ml(:,:)   = 0._wp ; zdv_ml(:,:)  = 0._wp
+      zdrh_ml(:,:) = 0._wp ; zdb_ml(:,:)  = 0._wp ; zwth_ent(:,:) = 0._wp ; zws_ent(:,:) = 0._wp
+      zuw_bse(:,:) = 0._wp ; zvw_bse(:,:) = 0._wp
+      !
+      zdtdz_pyc(:,:,:) = 0._wp ; zdsdz_pyc(:,:,:) = 0._wp ; zdbdz_pyc(:,:,:) = 0._wp
+      zdudz_pyc(:,:,:) = 0._wp ; zdvdz_pyc(:,:,:) = 0._wp
+      !
+      ! Flux-Gradient arrays.
+      zdifml_sc(:,:)  = 0._wp ; zvisml_sc(:,:)  = 0._wp ; zdifpyc_sc(:,:) = 0._wp
+      zvispyc_sc(:,:) = 0._wp ; zbeta_d_sc(:,:) = 0._wp ; zbeta_v_sc(:,:) = 0._wp
+      zsc_wth_1(:,:)  = 0._wp ; zsc_ws_1(:,:)   = 0._wp ; zsc_uw_1(:,:)   = 0._wp
+      zsc_uw_2(:,:)   = 0._wp ; zsc_vw_1(:,:)   = 0._wp ; zsc_vw_2(:,:)   = 0._wp
+      zhbl_t(:,:)     = 0._wp ; zdhdt(:,:)      = 0._wp
+
+      zdiffut(:,:,:) = 0._wp ; zviscos(:,:,:) = 0._wp ; ghamt(:,:,:) = 0._wp
+      ghams(:,:,:)   = 0._wp ; ghamu(:,:,:)   = 0._wp ; ghamv(:,:,:) = 0._wp
+
+      ! hbl = MAX(hbl,epsln)
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Calculate boundary layer scales
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+      ! Assume two-band radiation model for depth of OSBL
+     zz0 =       rn_abs       ! surface equi-partition in 2-bands
+     zz1 =  1. - rn_abs
+     DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+           ! Surface downward irradiance (so always +ve)
+           zrad0(ji,jj) = qsr(ji,jj) * r1_rau0_rcp
+           ! Downwards irradiance at base of boundary layer
+           zradh(ji,jj) = zrad0(ji,jj) * ( zz0 * EXP( -hbl(ji,jj)/rn_si0 ) + zz1 * EXP( -hbl(ji,jj)/rn_si1) )
+           ! Downwards irradiance averaged over depth of the OSBL
+           zradav(ji,jj) = zrad0(ji,jj) * ( zz0 * ( 1.0 - EXP( -hbl(ji,jj)/rn_si0 ) )*rn_si0 &
+                 &                         + zz1 * ( 1.0 - EXP( -hbl(ji,jj)/rn_si1 ) )*rn_si1 ) / hbl(ji,jj)
+        END DO
+     END DO
+     ! Turbulent surface fluxes and fluxes averaged over depth of the OSBL
+     DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+           zthermal = rab_n(ji,jj,1,jp_tem)
+           zbeta    = rab_n(ji,jj,1,jp_sal)
+           ! Upwards surface Temperature flux for non-local term
+           zwth0(ji,jj) = - qns(ji,jj) * r1_rau0_rcp * tmask(ji,jj,1)
+           ! Upwards surface salinity flux for non-local term
+           zws0(ji,jj) = - ( ( emp(ji,jj)-rnf(ji,jj) ) * tsn(ji,jj,1,jp_sal)  + sfx(ji,jj) ) * r1_rau0 * tmask(ji,jj,1)
+           ! Non radiative upwards surface buoyancy flux
+           zwb0(ji,jj) = grav * zthermal * zwth0(ji,jj) -  grav * zbeta * zws0(ji,jj)
+           ! turbulent heat flux averaged over depth of OSBL
+           zwthav(ji,jj) = 0.5 * zwth0(ji,jj) - ( 0.5*( zrad0(ji,jj) + zradh(ji,jj) ) - zradav(ji,jj) )
+           ! turbulent salinity flux averaged over depth of the OBSL
+           zwsav(ji,jj) = 0.5 * zws0(ji,jj)
+           ! turbulent buoyancy flux averaged over the depth of the OBSBL
+           zwbav(ji,jj) = grav  * zthermal * zwthav(ji,jj) - grav  * zbeta * zwsav(ji,jj)
+           ! Surface upward velocity fluxes
+           zuw0(ji,jj) = -utau(ji,jj) * r1_rau0 * tmask(ji,jj,1)
+           zvw0(ji,jj) = -vtau(ji,jj) * r1_rau0 * tmask(ji,jj,1)
+           ! Friction velocity (zustar), at T-point : LMD94 eq. 2
+           zustar(ji,jj) = MAX( SQRT( SQRT( zuw0(ji,jj) * zuw0(ji,jj) + zvw0(ji,jj) * zvw0(ji,jj) ) ), 1.0e-8 )
+           zcos_wind(ji,jj) = -zuw0(ji,jj) / ( zustar(ji,jj) * zustar(ji,jj) )
+           zsin_wind(ji,jj) = -zvw0(ji,jj) / ( zustar(ji,jj) * zustar(ji,jj) )
+        END DO
+     END DO
+     ! Calculate Stokes drift in direction of wind (zustke) and Stokes penetration depth (dstokes)
+     SELECT CASE (nn_osm_wave)
+     ! Assume constant La#=0.3
+     CASE(0)
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1
+              zus_x = zcos_wind(ji,jj) * zustar(ji,jj) / 0.3**2
+              zus_y = zsin_wind(ji,jj) * zustar(ji,jj) / 0.3**2
+              zustke(ji,jj) = MAX ( SQRT( zus_x*zus_x + zus_y*zus_y), 1.0e-8 )
+              ! dstokes(ji,jj) set to constant value rn_osm_dstokes from namelist in zdf_osm_init
+           END DO
+        END DO
+     ! Assume Pierson-Moskovitz wind-wave spectrum
+     CASE(1)
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1
+              ! Use wind speed wndm included in sbc_oce module
+              zustke(ji,jj) = MAX ( 0.016 * wndm(ji,jj), 1.0e-8 )
+              dstokes(ji,jj) = 0.12 * wndm(ji,jj)**2 / grav
+           END DO
+        END DO
+     ! Use ECMWF wave fields as output from SBCWAVE
+     CASE(2)
+        zfac =  2.0_wp * rpi / 16.0_wp
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1
+              ! The Langmur number from the ECMWF model appears to give La<0.3 for wind-driven seas.
+              !    The coefficient 0.8 gives La=0.3  in this situation.
+              ! It could represent the effects of the spread of wave directions
+              ! around the mean wind. The effect of this adjustment needs to be tested.
+              zustke(ji,jj) = MAX ( 1.0 * ( zcos_wind(ji,jj) * ut0sd(ji,jj ) + zsin_wind(ji,jj)  * vt0sd(ji,jj) ), &
+                   &                zustar(ji,jj) / ( 0.45 * 0.45 )                                                  )
+              dstokes(ji,jj) = MAX(zfac * hsw(ji,jj)*hsw(ji,jj) / ( MAX(zustke(ji,jj)*wmp(ji,jj), 1.0e-7 ) ), 5.0e-1) !rn_osm_dstokes !
+           END DO
+        END DO
+     END SELECT
+
+     ! Langmuir velocity scale (zwstrl), La # (zla)
+     ! mixed scale (zvstr), convective velocity scale (zwstrc)
+     DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+           ! Langmuir velocity scale (zwstrl), at T-point
+           zwstrl(ji,jj) = ( zustar(ji,jj) * zustar(ji,jj) * zustke(ji,jj) )**pthird
+           ! Modify zwstrl to allow for small and large values of dstokes/hbl.
+           ! Intended as a possible test. Doesn't affect LES results for entrainment,
+           !  but hasn't been shown to be correct as dstokes/h becomes large or small.
+           zwstrl(ji,jj) = zwstrl(ji,jj) *  &
+                & (1.12 * ( 1.0 - ( 1.0 - EXP( -hbl(ji,jj) / dstokes(ji,jj) ) ) * dstokes(ji,jj) / hbl(ji,jj) ))**pthird * &
+                & ( 1.0 - EXP( -15.0 * dstokes(ji,jj) / hbl(ji,jj) ))
+           ! define La this way so effects of Stokes penetration depth on velocity scale are included
+           zla(ji,jj) = SQRT ( zustar(ji,jj) / zwstrl(ji,jj) )**3
+           ! Velocity scale that tends to zustar for large Langmuir numbers
+           zvstr(ji,jj) = ( zwstrl(ji,jj)**3  + &
+                & ( 1.0 - EXP( -0.5 * zla(ji,jj)**2 ) ) * zustar(ji,jj) * zustar(ji,jj) * zustar(ji,jj) )**pthird
+
+           ! limit maximum value of Langmuir number as approximate treatment for shear turbulence.
+           ! Note zustke and zwstrl are not amended.
+           IF ( zla(ji,jj) >= 0.45 ) zla(ji,jj) = 0.45
+           !
+           ! get convective velocity (zwstrc), stabilty scale (zhol) and logical conection flag lconv
+           IF ( zwbav(ji,jj) > 0.0) THEN
+              zwstrc(ji,jj) = ( 2.0 * zwbav(ji,jj) * 0.9 * hbl(ji,jj) )**pthird
+              zhol(ji,jj) = -0.9 * hbl(ji,jj) * 2.0 * zwbav(ji,jj) / (zvstr(ji,jj)**3 + epsln )
+              lconv(ji,jj) = .TRUE.
+           ELSE
+              zhol(ji,jj) = -hbl(ji,jj) *  2.0 * zwbav(ji,jj)/ (zvstr(ji,jj)**3  + epsln )
+              lconv(ji,jj) = .FALSE.
+           ENDIF
+        END DO
+     END DO
+
+     !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+     ! Mixed-layer model - calculate averages over the boundary layer, and the change in the boundary layer depth
+     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+     ! BL must be always 2 levels deep.
+      hbl(:,:) = MAX(hbl(:,:), gdepw_n(:,:,3) )
+      ibld(:,:) = 3
+      DO jk = 4, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF ( hbl(ji,jj) >= gdepw_n(ji,jj,jk) ) THEN
+                  ibld(ji,jj) = MIN(mbkt(ji,jj), jk)
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1                                 !  Vertical slab
+         DO ji = 2, jpim1
+               zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
+               zbeta    = rab_n(ji,jj,1,jp_sal)
+               zt   = 0._wp
+               zs   = 0._wp
+               zu   = 0._wp
+               zv   = 0._wp
+               ! average over depth of boundary layer
+               zthick=0._wp
+               DO jm = 2, ibld(ji,jj)
+                  zthick=zthick+e3t_n(ji,jj,jm)
+                  zt   = zt  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_tem)
+                  zs   = zs  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_sal)
+                  zu   = zu  + e3t_n(ji,jj,jm) &
+                     &            * ( ub(ji,jj,jm) + ub(ji - 1,jj,jm) ) &
+                     &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
+                  zv   = zv  + e3t_n(ji,jj,jm) &
+                     &            * ( vb(ji,jj,jm) + vb(ji,jj - 1,jm) ) &
+                     &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
+               END DO
+               zt_bl(ji,jj) = zt / zthick
+               zs_bl(ji,jj) = zs / zthick
+               zu_bl(ji,jj) = zu / zthick
+               zv_bl(ji,jj) = zv / zthick
+               zdt_bl(ji,jj) = zt_bl(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_tem)
+               zds_bl(ji,jj) = zs_bl(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_sal)
+               zdu_bl(ji,jj) = zu_bl(ji,jj) - ( ub(ji,jj,ibld(ji,jj)) + ub(ji-1,jj,ibld(ji,jj) ) ) &
+                     &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
+               zdv_bl(ji,jj) = zv_bl(ji,jj) - ( vb(ji,jj,ibld(ji,jj)) + vb(ji,jj-1,ibld(ji,jj) ) ) &
+                     &   / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
+               zdb_bl(ji,jj) = grav * zthermal * zdt_bl(ji,jj) - grav * zbeta * zds_bl(ji,jj)
+               IF ( lconv(ji,jj) ) THEN    ! Convective
+                      zwb_ent(ji,jj) = -( 2.0 * 0.2 * zwbav(ji,jj) &
+                           &            + 0.135 * zla(ji,jj) * zwstrl(ji,jj)**3/hbl(ji,jj) )
+
+                      zvel_max =  - ( 1.0 + 1.0 * ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_rdt / hbl(ji,jj) ) &
+                           &   * zwb_ent(ji,jj) / ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+! Entrainment including component due to shear turbulence. Modified Langmuir component, but gives same result for La=0.3 For testing uncomment.
+!                      zwb_ent(ji,jj) = -( 2.0 * 0.2 * zwbav(ji,jj) &
+!                           &            + ( 0.15 * ( 1.0 - EXP( -0.5 * zla(ji,jj) ) ) + 0.03 / zla(ji,jj)**2 ) * zustar(ji,jj)**3/hbl(ji,jj) )
+
+!                      zvel_max = - ( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_rdt / zhbl(ji,jj) ) * zwb_ent(ji,jj) / &
+!                           &       ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+                      zzdhdt = - zwb_ent(ji,jj) / ( zvel_max + MAX(zdb_bl(ji,jj),0.0) )
+               ELSE                        ! Stable
+                      zzdhdt = 0.32 * ( hbli(ji,jj) / hbl(ji,jj) -1.0 ) * zwstrl(ji,jj)**3 / hbli(ji,jj) &
+                           &   + ( ( 0.32 / 3.0 ) * exp ( -2.5 * ( hbli(ji,jj) / hbl(ji,jj) - 1.0 ) ) &
+                           & - ( 0.32 / 3.0 - 0.135 * zla(ji,jj) ) * exp ( -12.5 * ( hbli(ji,jj) / hbl(ji,jj) ) ) ) &
+                           &  * zwstrl(ji,jj)**3 / hbli(ji,jj)
+                      zzdhdt = zzdhdt + zwbav(ji,jj)
+                      IF ( zzdhdt < 0._wp ) THEN
+                      ! For long timsteps factor in brackets slows the rapid collapse of the OSBL
+                         zpert   = 2.0 * ( 1.0 + 2.0 * zwstrl(ji,jj) * rn_rdt / hbl(ji,jj) ) * zwstrl(ji,jj)**2 / hbl(ji,jj)
+                      ELSE
+                         zpert   = 2.0 * ( 1.0 + 2.0 * zwstrl(ji,jj) * rn_rdt / hbl(ji,jj) ) * zwstrl(ji,jj)**2 / hbl(ji,jj) &
+                              &  + MAX( zdb_bl(ji,jj), 0.0 )
+                      ENDIF
+                      zzdhdt = 2.0 * zzdhdt / zpert
+               ENDIF
+               zdhdt(ji,jj) = zzdhdt
+           END DO
+      END DO
+
+      ! Calculate averages over depth of boundary layer
+      imld = ibld           ! use imld to hold previous blayer index
+      ibld(:,:) = 3
+
+      zhbl_t(:,:) = hbl(:,:) + (zdhdt(:,:) - wn(ji,jj,ibld(ji,jj)))* rn_rdt ! certainly need wb here, so subtract it
+      zhbl_t(:,:) = MIN(zhbl_t(:,:), ht_n(:,:))
+      zdhdt(:,:) = MIN(zdhdt(:,:), (zhbl_t(:,:) - hbl(:,:))/rn_rdt + wn(ji,jj,ibld(ji,jj))) ! adjustment to represent limiting by ocean bottom
+
+      DO jk = 4, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               IF ( zhbl_t(ji,jj) >= gdepw_n(ji,jj,jk) ) THEN
+                  ibld(ji,jj) =  MIN(mbkt(ji,jj), jk)
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+!
+! Step through model levels taking account of buoyancy change to determine the effect on dhdt
+!
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            IF ( ibld(ji,jj) - imld(ji,jj) > 1 ) THEN
+!
+! If boundary layer changes by more than one level, need to check for stable layers between initial and final depths.
+!
+               zhbl_s = hbl(ji,jj)
+               jm = imld(ji,jj)
+               zthermal = rab_n(ji,jj,1,jp_tem)
+               zbeta = rab_n(ji,jj,1,jp_sal)
+               IF ( lconv(ji,jj) ) THEN
+!unstable
+                  zvel_max =  - ( 1.0 + 1.0 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * rn_rdt / hbl(ji,jj) ) &
+                       &   * zwb_ent(ji,jj) / ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+
+                  DO jk = imld(ji,jj), ibld(ji,jj)
+                     zdb = MAX( grav * ( zthermal * ( zt_bl(ji,jj) - tsn(ji,jj,jm,jp_tem) ) &
+                          & - zbeta * ( zs_bl(ji,jj) - tsn(ji,jj,jm,jp_sal) ) ), 0.0 ) + zvel_max
+
+                     zhbl_s = zhbl_s + MIN( - zwb_ent(ji,jj) / zdb * rn_rdt / FLOAT(ibld(ji,jj)-imld(ji,jj) ), e3w_n(ji,jj,jk) )
+                     zhbl_s = MIN(zhbl_s, ht_n(ji,jj))
+
+                     IF ( zhbl_s >= gdepw_n(ji,jj,jm+1) ) jm = jm + 1
+                  END DO
+                  hbl(ji,jj) = zhbl_s
+                  ibld(ji,jj) = jm
+                  hbli(ji,jj) = hbl(ji,jj)
+               ELSE
+! stable
+                  DO jk = imld(ji,jj), ibld(ji,jj)
+                     zdb = MAX( grav * ( zthermal * ( zt_bl(ji,jj) - tsn(ji,jj,jm,jp_tem) )          &
+                          &               - zbeta * ( zs_bl(ji,jj) - tsn(ji,jj,jm,jp_sal) ) ), 0.0 ) &
+                          & + 2.0 * zwstrl(ji,jj)**2 / zhbl_s
+
+                     zhbl_s = zhbl_s +  (                                                                                &
+                          &                     0.32         *                         ( hbli(ji,jj) / zhbl_s -1.0 )     &
+                          &               * zwstrl(ji,jj)**3 / hbli(ji,jj)                                               &
+                          &               + ( ( 0.32 / 3.0 )           * EXP( -  2.5 * ( hbli(ji,jj) / zhbl_s -1.0 ) )   &
+                          &               -   ( 0.32 / 3.0  - 0.0485 ) * EXP( - 12.5 * ( hbli(ji,jj) / zhbl_s      ) ) ) &
+                          &          * zwstrl(ji,jj)**3 / hbli(ji,jj) ) / zdb * e3w_n(ji,jj,jk) / zdhdt(ji,jj)  ! ALMG to investigate whether need to include wn here
+
+                     zhbl_s = MIN(zhbl_s, ht_n(ji,jj))
+                     IF ( zhbl_s >= gdepw_n(ji,jj,jm) ) jm = jm + 1
+                  END DO
+                  hbl(ji,jj) = MAX(zhbl_s, gdepw_n(ji,jj,3) )
+                  ibld(ji,jj) = MAX(jm, 3 )
+                  IF ( hbl(ji,jj) > hbli(ji,jj) ) hbli(ji,jj) = hbl(ji,jj)
+               ENDIF   ! IF ( lconv )
+            ELSE
+! change zero or one model level.
+               hbl(ji,jj) = zhbl_t(ji,jj)
+               IF ( lconv(ji,jj) ) THEN
+                  hbli(ji,jj) = hbl(ji,jj)
+               ELSE
+                  hbl(ji,jj) = MAX(hbl(ji,jj), gdepw_n(ji,jj,3) )
+                  IF ( hbl(ji,jj) > hbli(ji,jj) ) hbli(ji,jj) = hbl(ji,jj)
+               ENDIF
+            ENDIF
+            zhbl(ji,jj) = gdepw_n(ji,jj,ibld(ji,jj))
+         END DO
+      END DO
+      dstokes(:,:) = MIN ( dstokes(:,:), hbl(:,:)/3. )  !  Limit delta for shallow boundary layers for calculating flux-gradient terms.
+
+! Recalculate averages over boundary layer after depth updated
+     ! Consider later  combining this into the loop above and looking for columns
+     ! where the index for base of the boundary layer have changed
+      DO jj = 2, jpjm1                                 !  Vertical slab
+         DO ji = 2, jpim1
+               zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
+               zbeta    = rab_n(ji,jj,1,jp_sal)
+               zt   = 0._wp
+               zs   = 0._wp
+               zu   = 0._wp
+               zv   = 0._wp
+               ! average over depth of boundary layer
+               zthick=0._wp
+               DO jm = 2, ibld(ji,jj)
+                  zthick=zthick+e3t_n(ji,jj,jm)
+                  zt   = zt  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_tem)
+                  zs   = zs  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_sal)
+                  zu   = zu  + e3t_n(ji,jj,jm) &
+                     &            * ( ub(ji,jj,jm) + ub(ji - 1,jj,jm) ) &
+                     &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
+                  zv   = zv  + e3t_n(ji,jj,jm) &
+                     &            * ( vb(ji,jj,jm) + vb(ji,jj - 1,jm) ) &
+                     &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
+               END DO
+               zt_bl(ji,jj) = zt / zthick
+               zs_bl(ji,jj) = zs / zthick
+               zu_bl(ji,jj) = zu / zthick
+               zv_bl(ji,jj) = zv / zthick
+               zdt_bl(ji,jj) = zt_bl(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_tem)
+               zds_bl(ji,jj) = zs_bl(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_sal)
+               zdu_bl(ji,jj) = zu_bl(ji,jj) - ( ub(ji,jj,ibld(ji,jj)) + ub(ji-1,jj,ibld(ji,jj) ) ) &
+                      &   / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
+               zdv_bl(ji,jj) = zv_bl(ji,jj) - ( vb(ji,jj,ibld(ji,jj)) + vb(ji,jj-1,ibld(ji,jj) ) ) &
+                      &  / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
+               zdb_bl(ji,jj) = grav * zthermal * zdt_bl(ji,jj) - grav * zbeta * zds_bl(ji,jj)
+               zhbl(ji,jj) = gdepw_n(ji,jj,ibld(ji,jj))
+               IF ( lconv(ji,jj) ) THEN
+                  IF ( zdb_bl(ji,jj) > 0._wp )THEN
+                     IF ( ( zwstrc(ji,jj) / zvstr(ji,jj) )**3 <= 0.5 ) THEN  ! near neutral stability
+                           zari = 4.5 * ( zvstr(ji,jj)**2 ) &
+                             & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01
+                     ELSE                                                     ! unstable
+                           zari = 4.5 * ( zwstrc(ji,jj)**2 ) &
+                             & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01
+                     ENDIF
+                     IF ( zari > 0.2 ) THEN                                                ! This test checks for weakly stratified pycnocline
+                        zari = 0.2
+                        zwb_ent(ji,jj) = 0._wp
+                     ENDIF
+                     inhml = MAX( INT( zari * zhbl(ji,jj) / e3t_n(ji,jj,ibld(ji,jj)) ) , 1 )
+                     imld(ji,jj) = MAX( ibld(ji,jj) - inhml, 1)
+                     zhml(ji,jj) = gdepw_n(ji,jj,imld(ji,jj))
+                     zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
+                  ELSE  ! IF (zdb_bl)
+                     imld(ji,jj) = ibld(ji,jj) - 1
+                     zhml(ji,jj) = gdepw_n(ji,jj,imld(ji,jj))
+                     zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
+                  ENDIF
+               ELSE   ! IF (lconv)
+                  IF ( zdhdt(ji,jj) >= 0.0 ) THEN    ! probably shouldn't include wm here
+                  ! boundary layer deepening
+                     IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                  ! pycnocline thickness set by stratification - use same relationship as for neutral conditions.
+                        zari = MIN( 4.5 * ( zvstr(ji,jj)**2 ) &
+                          & / ( zdb_bl(ji,jj) * zhbl(ji,jj) ) + 0.01  , 0.2 )
+                        inhml = MAX( INT( zari * zhbl(ji,jj) / e3t_n(ji,jj,ibld(ji,jj)) ) , 1 )
+                        imld(ji,jj) = MAX( ibld(ji,jj) - inhml, 1)
+                        zhml(ji,jj) = gdepw_n(ji,jj,imld(ji,jj))
+                        zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
+                     ELSE
+                        imld(ji,jj) = ibld(ji,jj) - 1
+                        zhml(ji,jj) = gdepw_n(ji,jj,imld(ji,jj))
+                        zdh(ji,jj) = zhbl(ji,jj) - zhml(ji,jj)
+                     ENDIF ! IF (zdb_bl > 0.0)
+                  ELSE     ! IF(dhdt >= 0)
+                  ! boundary layer collapsing.
+                     imld(ji,jj) = ibld(ji,jj)
+                     zhml(ji,jj) = zhbl(ji,jj)
+                     zdh(ji,jj) = 0._wp
+                  ENDIF    ! IF (dhdt >= 0)
+               ENDIF       ! IF (lconv)
+         END DO
+      END DO
+
+      ! Average over the depth of the mixed layer in the convective boundary layer
+      ! Also calculate entrainment fluxes for temperature and salinity
+      DO jj = 2, jpjm1                                 !  Vertical slab
+         DO ji = 2, jpim1
+            zthermal = rab_n(ji,jj,1,jp_tem) !ideally use ibld not 1??
+            zbeta    = rab_n(ji,jj,1,jp_sal)
+            IF ( lconv(ji,jj) ) THEN
+               zt   = 0._wp
+               zs   = 0._wp
+               zu   = 0._wp
+               zv   = 0._wp
+               ! average over depth of boundary layer
+               zthick=0._wp
+               DO jm = 2, imld(ji,jj)
+                  zthick=zthick+e3t_n(ji,jj,jm)
+                  zt   = zt  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_tem)
+                  zs   = zs  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_sal)
+                  zu   = zu  + e3t_n(ji,jj,jm) &
+                     &            * ( ub(ji,jj,jm) + ub(ji - 1,jj,jm) ) &
+                     &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
+                  zv   = zv  + e3t_n(ji,jj,jm) &
+                     &            * ( vb(ji,jj,jm) + vb(ji,jj - 1,jm) ) &
+                     &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
+               END DO
+               zt_ml(ji,jj) = zt / zthick
+               zs_ml(ji,jj) = zs / zthick
+               zu_ml(ji,jj) = zu / zthick
+               zv_ml(ji,jj) = zv / zthick
+               zdt_ml(ji,jj) = zt_ml(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_tem)
+               zds_ml(ji,jj) = zs_ml(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_sal)
+               zdu_ml(ji,jj) = zu_ml(ji,jj) - ( ub(ji,jj,ibld(ji,jj)) + ub(ji-1,jj,ibld(ji,jj) ) ) &
+                     &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
+               zdv_ml(ji,jj) = zv_ml(ji,jj) - ( vb(ji,jj,ibld(ji,jj)) + vb(ji,jj-1,ibld(ji,jj) ) ) &
+                     &    / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
+               zdb_ml(ji,jj) = grav * zthermal * zdt_ml(ji,jj) - grav * zbeta * zds_ml(ji,jj)
+            ELSE
+            ! stable, if entraining calulate average below interface layer.
+               IF ( zdhdt(ji,jj) >= 0._wp ) THEN
+                  zt   = 0._wp
+                  zs   = 0._wp
+                  zu   = 0._wp
+                  zv   = 0._wp
+                  ! average over depth of boundary layer
+                  zthick=0._wp
+                  DO jm = 2, imld(ji,jj)
+                     zthick=zthick+e3t_n(ji,jj,jm)
+                     zt   = zt  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_tem)
+                     zs   = zs  + e3t_n(ji,jj,jm) * tsn(ji,jj,jm,jp_sal)
+                     zu   = zu  + e3t_n(ji,jj,jm) &
+                        &            * ( ub(ji,jj,jm) + ub(ji - 1,jj,jm) ) &
+                        &            / MAX( 1. , umask(ji,jj,jm) + umask(ji - 1,jj,jm) )
+                     zv   = zv  + e3t_n(ji,jj,jm) &
+                        &            * ( vb(ji,jj,jm) + vb(ji,jj - 1,jm) ) &
+                        &            / MAX( 1. , vmask(ji,jj,jm) + vmask(ji,jj - 1,jm) )
+                  END DO
+                  zt_ml(ji,jj) = zt / zthick
+                  zs_ml(ji,jj) = zs / zthick
+                  zu_ml(ji,jj) = zu / zthick
+                  zv_ml(ji,jj) = zv / zthick
+                  zdt_ml(ji,jj) = zt_ml(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_tem)
+                  zds_ml(ji,jj) = zs_ml(ji,jj) - tsn(ji,jj,ibld(ji,jj),jp_sal)
+                  zdu_ml(ji,jj) = zu_ml(ji,jj) - ( ub(ji,jj,ibld(ji,jj)) + ub(ji-1,jj,ibld(ji,jj) ) ) &
+                        &    / MAX(1. , umask(ji,jj,ibld(ji,jj) ) + umask(ji-1,jj,ibld(ji,jj) ) )
+                  zdv_ml(ji,jj) = zv_ml(ji,jj) - ( vb(ji,jj,ibld(ji,jj)) + vb(ji,jj-1,ibld(ji,jj) ) ) &
+                        &    / MAX(1. , vmask(ji,jj,ibld(ji,jj) ) + vmask(ji,jj-1,ibld(ji,jj) ) )
+                  zdb_ml(ji,jj) = grav * zthermal * zdt_ml(ji,jj) - grav * zbeta * zds_ml(ji,jj)
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+    !
+    ! rotate mean currents and changes onto wind align co-ordinates
+    !
+
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            ztemp = zu_ml(ji,jj)
+            zu_ml(ji,jj) = zu_ml(ji,jj) * zcos_wind(ji,jj) + zv_ml(ji,jj) * zsin_wind(ji,jj)
+            zv_ml(ji,jj) = zv_ml(ji,jj) * zcos_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
+            ztemp = zdu_ml(ji,jj)
+            zdu_ml(ji,jj) = zdu_ml(ji,jj) * zcos_wind(ji,jj) + zdv_ml(ji,jj) * zsin_wind(ji,jj)
+            zdv_ml(ji,jj) = zdv_ml(ji,jj) * zsin_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
+    !
+            ztemp = zu_bl(ji,jj)
+            zu_bl = zu_bl(ji,jj) * zcos_wind(ji,jj) + zv_bl(ji,jj) * zsin_wind(ji,jj)
+            zv_bl(ji,jj) = zv_bl(ji,jj) * zcos_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
+            ztemp = zdu_bl(ji,jj)
+            zdu_bl(ji,jj) = zdu_bl(ji,jj) * zcos_wind(ji,jj) + zdv_bl(ji,jj) * zsin_wind(ji,jj)
+            zdv_bl(ji,jj) = zdv_bl(ji,jj) * zsin_wind(ji,jj) - ztemp * zsin_wind(ji,jj)
+         END DO
+      END DO
+
+     zuw_bse = 0._wp
+     zvw_bse = 0._wp
+     DO jj = 2, jpjm1
+        DO ji = 2, jpim1
+
+           IF ( lconv(ji,jj) ) THEN
+              IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                 zwth_ent(ji,jj) = zwb_ent(ji,jj) * zdt_ml(ji,jj) / (zdb_ml(ji,jj) + epsln)
+                 zws_ent(ji,jj) = zwb_ent(ji,jj) * zds_ml(ji,jj) / (zdb_ml(ji,jj) + epsln)
+              ENDIF
+           ELSE
+              zwth_ent(ji,jj) = -2.0 * zwthav(ji,jj) * ( (1.0 - 0.8) - ( 1.0 - 0.8)**(3.0/2.0) )
+              zws_ent(ji,jj) = -2.0 * zwsav(ji,jj) * ( (1.0 - 0.8 ) - ( 1.0 - 0.8 )**(3.0/2.0) )
+           ENDIF
+        END DO
+     END DO
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      !  Pycnocline gradients for scalars and velocity
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+          !
+             IF ( lconv (ji,jj) ) THEN
+             ! Unstable conditions
+                IF( zdb_bl(ji,jj) > 0._wp ) THEN
+                ! calculate pycnocline profiles, no need if zdb_bl <= 0. since profile is zero and arrays have been initialized to zero
+                   ztgrad = ( zdt_ml(ji,jj) / zdh(ji,jj) )
+                   zsgrad = ( zds_ml(ji,jj) / zdh(ji,jj) )
+                   zbgrad = ( zdb_ml(ji,jj) / zdh(ji,jj) )
+                   DO jk = 2 , ibld(ji,jj)
+                      znd = -( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zdh(ji,jj)
+                      zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                      zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                      zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                   END DO
+                ENDIF
+             ELSE
+             ! stable conditions
+             ! if pycnocline profile only defined when depth steady of increasing.
+                IF ( zdhdt(ji,jj) >= 0.0 ) THEN        ! Depth increasing, or steady.
+                   IF ( zdb_bl(ji,jj) > 0._wp ) THEN
+                     IF ( zhol(ji,jj) >= 0.5 ) THEN      ! Very stable - 'thick' pycnocline
+                         ztgrad = zdt_bl(ji,jj) / zhbl(ji,jj)
+                         zsgrad = zds_bl(ji,jj) / zhbl(ji,jj)
+                         zbgrad = zdb_bl(ji,jj) / zhbl(ji,jj)
+                         DO jk = 2, ibld(ji,jj)
+                            znd = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                            zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                            zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                            zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -15.0 * ( znd - 0.9 )**2 )
+                         END DO
+                     ELSE                                   ! Slightly stable - 'thin' pycnoline - needed when stable layer begins to form.
+                         ztgrad = zdt_bl(ji,jj) / zdh(ji,jj)
+                         zsgrad = zds_bl(ji,jj) / zdh(ji,jj)
+                         zbgrad = zdb_bl(ji,jj) / zdh(ji,jj)
+                         DO jk = 2, ibld(ji,jj)
+                            znd = -( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zdh(ji,jj)
+                            zdtdz_pyc(ji,jj,jk) =  ztgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                            zdbdz_pyc(ji,jj,jk) =  zbgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                            zdsdz_pyc(ji,jj,jk) =  zsgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                         END DO
+                      ENDIF ! IF (zhol >=0.5)
+                   ENDIF    ! IF (zdb_bl> 0.)
+                ENDIF       ! IF (zdhdt >= 0) zdhdt < 0 not considered since pycnocline profile is zero, profile arrays are intialized to zero
+             ENDIF          ! IF (lconv)
+            !
+          END DO
+       END DO
+!
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+          !
+             IF ( lconv (ji,jj) ) THEN
+             ! Unstable conditions
+                 zugrad = ( zdu_ml(ji,jj) / zdh(ji,jj) ) + 0.275 * zustar(ji,jj)*zustar(ji,jj) / &
+               & (( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * zhml(ji,jj) ) / zla(ji,jj)**(8.0/3.0)
+                zvgrad = ( zdv_ml(ji,jj) / zdh(ji,jj) ) + 3.5 * ff_t(ji,jj) * zustke(ji,jj) / &
+              & ( zwstrl(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+                DO jk = 2 , ibld(ji,jj)-1
+                   znd = -( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zdh(ji,jj)
+                   zdudz_pyc(ji,jj,jk) =  zugrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                   zdvdz_pyc(ji,jj,jk) = zvgrad * EXP( -1.75 * ( znd + 0.75 )**2 )
+                END DO
+             ELSE
+             ! stable conditions
+                zugrad = 3.25 * zdu_bl(ji,jj) / zhbl(ji,jj)
+                zvgrad = 2.75 * zdv_bl(ji,jj) / zhbl(ji,jj)
+                DO jk = 2, ibld(ji,jj)
+                   znd = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                   IF ( znd < 1.0 ) THEN
+                      zdudz_pyc(ji,jj,jk) = zugrad * EXP( -40.0 * ( znd - 1.0 )**2 )
+                   ELSE
+                      zdudz_pyc(ji,jj,jk) = zugrad * EXP( -20.0 * ( znd - 1.0 )**2 )
+                   ENDIF
+                   zdvdz_pyc(ji,jj,jk) = zvgrad * EXP( -20.0 * ( znd - 0.85 )**2 )
+                END DO
+             ENDIF
+            !
+          END DO
+       END DO
+       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+       ! Eddy viscosity/diffusivity and non-gradient terms in the flux-gradient relationship
+       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+      ! WHERE ( lconv )
+      !     zdifml_sc = zhml * ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird
+      !     zvisml_sc = zdifml_sc
+      !     zdifpyc_sc = 0.165 * ( zwstrl**3 + zwstrc**3 )**pthird * ( zhbl - zhml )
+      !     zvispyc_sc = 0.142 * ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * ( zhbl - zhml )
+      !     zbeta_d_sc = 1.0 - (0.165 / 0.8 * ( zhbl - zhml ) / zhbl )**p2third
+      !     zbeta_v_sc = 1.0 -  2.0 * (0.142 /0.375) * (zhbl - zhml ) / zhml
+      !  ELSEWHERE
+      !     zdifml_sc = zwstrl * zhbl * EXP ( -( zhol / 0.183_wp )**2 )
+      !     zvisml_sc = zwstrl * zhbl * EXP ( -( zhol / 0.183_wp )**2 )
+      !  ENDWHERE
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+               zdifml_sc(ji,jj) = zhml(ji,jj) * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird
+               zvisml_sc(ji,jj) = zdifml_sc(ji,jj)
+               zdifpyc_sc(ji,jj) = 0.165 * ( zvstr(ji,jj)**3 + 0.5 *zwstrc(ji,jj)**3 )**pthird * zdh(ji,jj)
+               zvispyc_sc(ji,jj) = 0.142 * ( zvstr(ji,jj)**3 + 0.5 * zwstrc(ji,jj)**3 )**pthird * zdh(ji,jj)
+               zbeta_d_sc(ji,jj) = 1.0 - (0.165 / 0.8 * zdh(ji,jj) / zhbl(ji,jj) )**p2third
+               zbeta_v_sc(ji,jj) = 1.0 -  2.0 * (0.142 /0.375) * zdh(ji,jj) / zhml(ji,jj)
+             ELSE
+               zdifml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * EXP ( -( zhol(ji,jj) / 0.6_wp )**2 )
+               zvisml_sc(ji,jj) = zvstr(ji,jj) * zhbl(ji,jj) * EXP ( -( zhol(ji,jj) / 0.6_wp )**2 )
+            END IF
+        END DO
+    END DO
+!
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+                DO jk = 2, imld(ji,jj)   ! mixed layer diffusivity
+                    zznd_ml = gdepw_n(ji,jj,jk) / zhml(ji,jj)
+                    !
+                    zdiffut(ji,jj,jk) = 0.8   * zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_d_sc(ji,jj) * zznd_ml    )**1.5
+                    !
+                    zviscos(ji,jj,jk) = 0.375 * zvisml_sc(ji,jj) * zznd_ml * ( 1.0 - zbeta_v_sc(ji,jj) * zznd_ml    ) &
+                         &            *                                      ( 1.0 -               0.5 * zznd_ml**2 )
+                END DO
+                ! pycnocline - if present linear profile
+                IF ( zdh(ji,jj) > 0._wp ) THEN
+                   DO jk = imld(ji,jj)+1 , ibld(ji,jj)
+                       zznd_pyc = -( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zdh(ji,jj)
+                       !
+                       zdiffut(ji,jj,jk) = zdifpyc_sc(ji,jj) * ( 1.0 + zznd_pyc )
+                       !
+                       zviscos(ji,jj,jk) = zvispyc_sc(ji,jj) * ( 1.0 + zznd_pyc )
+                   END DO
+                ENDIF
+                ! Temporay fix to ensure zdiffut is +ve; won't be necessary with wn taken out
+                zdiffut(ji,jj,ibld(ji,jj)) = zdhdt(ji,jj)* e3t_n(ji,jj,ibld(ji,jj))
+                ! could be taken out, take account of entrainment represents as a diffusivity
+                ! should remove w from here, represents entrainment
+             ELSE
+             ! stable conditions
+                DO jk = 2, ibld(ji,jj)
+                   zznd_ml = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                   zdiffut(ji,jj,jk) = 0.75 * zdifml_sc(ji,jj) * zznd_ml * ( 1.0 - zznd_ml )**1.5
+                   zviscos(ji,jj,jk) = 0.375 * zvisml_sc(ji,jj) * zznd_ml * (1.0 - zznd_ml) * ( 1.0 - zznd_ml**2 )
+                END DO
+             ENDIF   ! end if ( lconv )
+!
+          END DO  ! end of ji loop
+       END DO     ! end of jj loop
+
+       !
+       ! calculate non-gradient components of the flux-gradient relationships
+       !
+! Stokes term in scalar flux, flux-gradient relationship
+       WHERE ( lconv )
+          zsc_wth_1 = zwstrl**3 * zwth0 / ( zvstr**3 + 0.5 * zwstrc**3 + epsln)
+          !
+          zsc_ws_1 = zwstrl**3 * zws0 / ( zvstr**3 + 0.5 * zwstrc**3 + epsln )
+       ELSEWHERE
+          zsc_wth_1 = 2.0 * zwthav
+          !
+          zsc_ws_1 = 2.0 * zwsav
+       ENDWHERE
+
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            IF ( lconv(ji,jj) ) THEN
+              DO jk = 2, imld(ji,jj)
+                 zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                 ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 1.35 * EXP ( -zznd_d ) * ( 1.0 - EXP ( -2.0 * zznd_d ) ) * zsc_wth_1(ji,jj)
+                 !
+                 ghams(ji,jj,jk) = ghams(ji,jj,jk) + 1.35 * EXP ( -zznd_d ) * ( 1.0 - EXP ( -2.0 * zznd_d ) ) *  zsc_ws_1(ji,jj)
+              END DO ! end jk loop
+            ELSE     ! else for if (lconv)
+ ! Stable conditions
+               DO jk = 2, ibld(ji,jj)
+                  zznd_d=gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 1.5 * EXP ( -0.9 * zznd_d ) &
+                       &          *                 ( 1.0 - EXP ( -4.0 * zznd_d ) ) * zsc_wth_1(ji,jj)
+                  !
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) + 1.5 * EXP ( -0.9 * zznd_d ) &
+                       &          *                 ( 1.0 - EXP ( -4.0 * zznd_d ) ) *  zsc_ws_1(ji,jj)
+               END DO
+            ENDIF               ! endif for check on lconv
+
+          END DO  ! end of ji loop
+       END DO     ! end of jj loop
+
+
+! Stokes term in flux-gradient relationship (note in zsc_uw_n don't use zvstr since term needs to go to zero as zwstrl goes to zero)
+       WHERE ( lconv )
+          zsc_uw_1 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke /( 1.0 - 1.0 * 6.5 * zla**(8.0/3.0) )
+          zsc_uw_2 = ( zwstrl**3 + 0.5 * zwstrc**3 )**pthird * zustke / ( zla**(8.0/3.0) + epsln )
+          zsc_vw_1 = ff_t * zhml * zustke**3 * zla**(8.0/3.0) / ( ( zvstr**3 + 0.5 * zwstrc**3 )**(2.0/3.0) + epsln )
+       ELSEWHERE
+          zsc_uw_1 = zustar**2
+          zsc_vw_1 = ff_t * zhbl * zustke**3 * zla**(8.0/3.0) / (zvstr**2 + epsln)
+       ENDWHERE
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+                DO jk = 2, imld(ji,jj)
+                   zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                   ghamu(ji,jj,jk) = ghamu(ji,jj,jk) +      ( -0.05 * EXP ( -0.4 * zznd_d )   * zsc_uw_1(ji,jj)   &
+                        &          +                        0.00125 * EXP (      - zznd_d )   * zsc_uw_2(ji,jj) ) &
+                        &          *                          ( 1.0 - EXP ( -2.0 * zznd_d ) )
+!
+                   ghamv(ji,jj,jk) = ghamv(ji,jj,jk) - 0.65 *  0.15 * EXP (      - zznd_d )                       &
+                        &          *                          ( 1.0 - EXP ( -2.0 * zznd_d ) ) * zsc_vw_1(ji,jj)
+                END DO   ! end jk loop
+             ELSE
+! Stable conditions
+                DO jk = 2, ibld(ji,jj) ! corrected to ibld
+                   zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                   ghamu(ji,jj,jk) = ghamu(ji,jj,jk) - 0.75 *   1.3 * EXP ( -0.5 * zznd_d )                       &
+                        &                                   * ( 1.0 - EXP ( -4.0 * zznd_d ) ) * zsc_uw_1(ji,jj)
+                   ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + 0._wp
+                END DO   ! end jk loop
+             ENDIF
+          END DO  ! ji loop
+       END DO     ! jj loo
+
+! Buoyancy term in flux-gradient relationship [note : includes ROI ratio (X0.3) and pressure (X0.5)]
+
+       WHERE ( lconv )
+          zsc_wth_1 = zwbav * zwth0 * ( 1.0 + EXP ( 0.2 * zhol ) ) / ( zvstr**3 + 0.5 * zwstrc**3 + epsln )
+          zsc_ws_1  = zwbav * zws0  * ( 1.0 + EXP ( 0.2 * zhol ) ) / ( zvstr**3 + 0.5 * zwstrc**3 + epsln )
+       ELSEWHERE
+          zsc_wth_1 = 0._wp
+          zsc_ws_1 = 0._wp
+       ENDWHERE
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF (lconv(ji,jj) ) THEN
+                DO jk = 2, imld(ji,jj)
+                   zznd_ml = gdepw_n(ji,jj,jk) / zhml(ji,jj)
+                   ! calculate turbulent length scale
+                   zl_c = 0.9 * ( 1.0 - EXP ( - 7.0 * ( zznd_ml - zznd_ml**3 / 3.0 ) ) )                                           &
+                        &     * ( 1.0 - EXP ( -15.0 * (     1.1 - zznd_ml          ) ) )
+                   zl_l = 2.0 * ( 1.0 - EXP ( - 2.0 * ( zznd_ml - zznd_ml**3 / 3.0 ) ) )                                           &
+                        &     * ( 1.0 - EXP ( - 5.0 * (     1.0 - zznd_ml          ) ) ) * ( 1.0 + dstokes(ji,jj) / zhml (ji,jj) )
+                   zl_eps = zl_l + ( zl_c - zl_l ) / ( 1.0 + EXP ( 3.0 * LOG10 ( - zhol(ji,jj) ) ) ) ** (3.0/2.0)
+                   ! non-gradient buoyancy terms
+                   ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * 0.5 * zsc_wth_1(ji,jj) * zl_eps * zhml(ji,jj) / ( 0.15 + zznd_ml )
+                   ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * 0.5 *  zsc_ws_1(ji,jj) * zl_eps * zhml(ji,jj) / ( 0.15 + zznd_ml )
+                END DO
+             ELSE
+                DO jk = 2, ibld(ji,jj)
+                   ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zsc_wth_1(ji,jj)
+                   ghams(ji,jj,jk) = ghams(ji,jj,jk) +  zsc_ws_1(ji,jj)
+                END DO
+             ENDIF
+          END DO   ! ji loop
+       END DO      ! jj loop
+
+
+       WHERE ( lconv )
+          zsc_uw_1 = -zwb0 * zustar**2 * zhml / ( zvstr**3 + 0.5 * zwstrc**3 + epsln )
+          zsc_uw_2 =  zwb0 * zustke    * zhml / ( zvstr**3 + 0.5 * zwstrc**3 + epsln )**(2.0/3.0)
+          zsc_vw_1 = 0._wp
+       ELSEWHERE
+         zsc_uw_1 = 0._wp
+         zsc_vw_1 = 0._wp
+       ENDWHERE
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+                DO jk = 2 , imld(ji,jj)
+                   zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                   ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + 0.3 * 0.5 * ( zsc_uw_1(ji,jj) +   0.125 * EXP( -0.5 * zznd_d )     &
+                        &                                                            * (   1.0 - EXP( -0.5 * zznd_d ) )   &
+                        &                                          * zsc_uw_2(ji,jj)                                    )
+                   ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zsc_vw_1(ji,jj)
+                END DO  ! jk loop
+             ELSE
+             ! stable conditions
+                DO jk = 2, ibld(ji,jj)
+                   ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zsc_uw_1(ji,jj)
+                   ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zsc_vw_1(ji,jj)
+                END DO
+             ENDIF
+          END DO        ! ji loop
+       END DO           ! jj loop
+
+! Transport term in flux-gradient relationship [note : includes ROI ratio (X0.3) ]
+
+       WHERE ( lconv )
+          zsc_wth_1 = zwth0
+          zsc_ws_1 = zws0
+       ELSEWHERE
+          zsc_wth_1 = 2.0 * zwthav
+          zsc_ws_1 = zws0
+       ENDWHERE
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+            IF ( lconv(ji,jj) ) THEN
+               DO jk = 2, imld(ji,jj)
+                  zznd_ml=gdepw_n(ji,jj,jk) / zhml(ji,jj)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * zsc_wth_1(ji,jj)                &
+                       &          * ( -2.0 + 2.75 * (       ( 1.0 + 0.6 * zznd_ml**4 )      &
+                       &                               - EXP(     - 6.0 * zznd_ml    ) ) )  &
+                       &          * ( 1.0 - EXP( - 15.0 * (         1.0 - zznd_ml    ) ) )
+                  !
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * zsc_ws_1(ji,jj)  &
+                       &          * ( -2.0 + 2.75 * (       ( 1.0 + 0.6 * zznd_ml**4 )      &
+                       &                               - EXP(     - 6.0 * zznd_ml    ) ) )  &
+                       &          * ( 1.0 - EXP ( -15.0 * (         1.0 - zznd_ml    ) ) )
+               END DO
+            ELSE
+               DO jk = 2, ibld(ji,jj)
+                  zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                  znd = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
+               &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_wth_1(ji,jj)
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) + 0.3 * ( -4.06 * EXP( -2.0 * zznd_d ) * (1.0 - EXP( -4.0 * zznd_d ) ) + &
+               &  7.5 * EXP ( -10.0 * ( 0.95 - znd )**2 ) * ( 1.0 - znd ) ) * zsc_ws_1(ji,jj)
+               END DO
+            ENDIF
+          ENDDO    ! ji loop
+       END DO      ! jj loop
+
+
+       WHERE ( lconv )
+          zsc_uw_1 = zustar**2
+          zsc_vw_1 = ff_t * zustke * zhml
+       ELSEWHERE
+          zsc_uw_1 = zustar**2
+          zsc_uw_2 = (2.25 - 3.0 * ( 1.0 - EXP( -1.25 * 2.0 ) ) ) * ( 1.0 - EXP( -4.0 * 2.0 ) ) * zsc_uw_1
+          zsc_vw_1 = ff_t * zustke * zhbl
+          zsc_vw_2 = -0.11 * SIN( 3.14159 * ( 2.0 + 0.4 ) ) * EXP(-( 1.5 + 2.0 )**2 ) * zsc_vw_1
+       ENDWHERE
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+               DO jk = 2, imld(ji,jj)
+                  zznd_ml = gdepw_n(ji,jj,jk) / zhml(ji,jj)
+                  zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                  ghamu(ji,jj,jk) = ghamu(ji,jj,jk)&
+                       & + 0.3 * ( -2.0 + 2.5 * ( 1.0 + 0.1 * zznd_ml**4 ) - EXP ( -8.0 * zznd_ml ) ) * zsc_uw_1(ji,jj)
+                  !
+                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk)&
+                       & + 0.3 * 0.1 * ( EXP( -zznd_d ) + EXP( -5.0 * ( 1.0 - zznd_ml ) ) ) * zsc_vw_1(ji,jj)
+               END DO
+             ELSE
+               DO jk = 2, ibld(ji,jj)
+                  znd = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                  zznd_d = gdepw_n(ji,jj,jk) / dstokes(ji,jj)
+                  IF ( zznd_d <= 2.0 ) THEN
+                     ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + 0.5 * 0.3 &
+                          &*  ( 2.25 - 3.0  * ( 1.0 - EXP( - 1.25 * zznd_d ) ) * ( 1.0 - EXP( -2.0 * zznd_d ) ) ) * zsc_uw_1(ji,jj)
+                     !
+                  ELSE
+                     ghamu(ji,jj,jk) = ghamu(ji,jj,jk)&
+                          & + 0.5 * 0.3 * ( 1.0 - EXP( -5.0 * ( 1.0 - znd ) ) ) * zsc_uw_2(ji,jj)
+                     !
+                  ENDIF
+
+                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk)&
+                       & + 0.3 * 0.15 * SIN( 3.14159 * ( 0.65 * zznd_d ) ) * EXP( -0.25 * zznd_d**2 ) * zsc_vw_1(ji,jj)
+                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk)&
+                       & + 0.3 * 0.15 * EXP( -5.0 * ( 1.0 - znd ) ) * ( 1.0 - EXP( -20.0 * ( 1.0 - znd ) ) ) * zsc_vw_2(ji,jj)
+               END DO
+             ENDIF
+          END DO
+       END DO
+!
+! Make surface forced velocity non-gradient terms go to zero at the base of the mixed layer.
+
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+            IF ( lconv(ji,jj) ) THEN
+               DO jk = 2, ibld(ji,jj)
+                  znd = ( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zhml(ji,jj) !ALMG to think about
+                  IF ( znd >= 0.0 ) THEN
+                     ghamu(ji,jj,jk) = ghamu(ji,jj,jk) * ( 1.0 - EXP( -30.0 * znd**2 ) )
+                     ghamv(ji,jj,jk) = ghamv(ji,jj,jk) * ( 1.0 - EXP( -30.0 * znd**2 ) )
+                  ELSE
+                     ghamu(ji,jj,jk) = 0._wp
+                     ghamv(ji,jj,jk) = 0._wp
+                  ENDIF
+               END DO
+            ELSE
+               DO jk = 2, ibld(ji,jj)
+                  znd = ( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zhml(ji,jj) !ALMG to think about
+                  IF ( znd >= 0.0 ) THEN
+                     ghamu(ji,jj,jk) = ghamu(ji,jj,jk) * ( 1.0 - EXP( -10.0 * znd**2 ) )
+                     ghamv(ji,jj,jk) = ghamv(ji,jj,jk) * ( 1.0 - EXP( -10.0 * znd**2 ) )
+                  ELSE
+                     ghamu(ji,jj,jk) = 0._wp
+                     ghamv(ji,jj,jk) = 0._wp
+                  ENDIF
+               END DO
+            ENDIF
+         END DO
+      END DO
+
+      ! pynocline contributions
+       ! Temporary fix to avoid instabilities when zdb_bl becomes very very small
+       zsc_uw_1 = 0._wp ! 50.0 * zla**(8.0/3.0) * zustar**2 * zhbl / ( zdb_bl + epsln )
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             DO jk= 2, ibld(ji,jj)
+                znd = gdepw_n(ji,jj,jk) / zhbl(ji,jj)
+                ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zdiffut(ji,jj,jk) * zdtdz_pyc(ji,jj,jk)
+                ghams(ji,jj,jk) = ghams(ji,jj,jk) + zdiffut(ji,jj,jk) * zdsdz_pyc(ji,jj,jk)
+                ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zviscos(ji,jj,jk) * zdudz_pyc(ji,jj,jk)
+                ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zsc_uw_1(ji,jj) * ( 1.0 - znd )**(7.0/4.0) * zdbdz_pyc(ji,jj,jk)
+                ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zviscos(ji,jj,jk) * zdvdz_pyc(ji,jj,jk)
+             END DO
+           END DO
+       END DO
+
+! Entrainment contribution.
+
+       DO jj=2, jpjm1
+          DO ji = 2, jpim1
+             IF ( lconv(ji,jj) ) THEN
+               DO jk = 1, imld(ji,jj) - 1
+                  znd=gdepw_n(ji,jj,jk) / zhml(ji,jj)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zwth_ent(ji,jj) * znd
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) + zws_ent(ji,jj) * znd
+                  ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zuw_bse(ji,jj) * znd
+                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zvw_bse(ji,jj) * znd
+               END DO
+               DO jk = imld(ji,jj), ibld(ji,jj)
+                  znd = -( gdepw_n(ji,jj,jk) - zhml(ji,jj) ) / zdh(ji,jj)
+                  ghamt(ji,jj,jk) = ghamt(ji,jj,jk) + zwth_ent(ji,jj) * ( 1.0 + znd )
+                  ghams(ji,jj,jk) = ghams(ji,jj,jk) + zws_ent(ji,jj) * ( 1.0 + znd )
+                  ghamu(ji,jj,jk) = ghamu(ji,jj,jk) + zuw_bse(ji,jj) * ( 1.0 + znd )
+                  ghamv(ji,jj,jk) = ghamv(ji,jj,jk) + zvw_bse(ji,jj) * ( 1.0 + znd )
+                END DO
+             ENDIF
+             ghamt(ji,jj,ibld(ji,jj)) = 0._wp
+             ghams(ji,jj,ibld(ji,jj)) = 0._wp
+             ghamu(ji,jj,ibld(ji,jj)) = 0._wp
+             ghamv(ji,jj,ibld(ji,jj)) = 0._wp
+          END DO       ! ji loop
+       END DO          ! jj loop
+
+
+       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+       ! Need to put in code for contributions that are applied explicitly to
+       ! the prognostic variables
+       !  1. Entrainment flux
+       !
+       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+
+
+       ! rotate non-gradient velocity terms back to model reference frame
+
+       DO jj = 2, jpjm1
+          DO ji = 2, jpim1
+             DO jk = 2, ibld(ji,jj)
+                ztemp = ghamu(ji,jj,jk)
+                ghamu(ji,jj,jk) = ghamu(ji,jj,jk) * zcos_wind(ji,jj) - ghamv(ji,jj,jk) * zsin_wind(ji,jj)
+                ghamv(ji,jj,jk) = ghamv(ji,jj,jk) * zcos_wind(ji,jj) + ztemp * zsin_wind(ji,jj)
+             END DO
+          END DO
+       END DO
+
+       IF(ln_dia_osm) THEN
+          IF ( iom_use("zdtdz_pyc") ) CALL iom_put( "zdtdz_pyc", wmask*zdtdz_pyc )
+       END IF
+
+! KPP-style Ri# mixing
+       IF( ln_kpprimix) THEN
+          DO jk = 2, jpkm1           !* Shear production at uw- and vw-points (energy conserving form)
+             DO jj = 1, jpjm1
+                DO ji = 1, jpim1   ! vector opt.
+                   z3du(ji,jj,jk) = 0.5 * (  un(ji,jj,jk-1) -  un(ji  ,jj,jk) )   &
+                        &                 * (  ub(ji,jj,jk-1) -  ub(ji  ,jj,jk) ) * wumask(ji,jj,jk) &
+                        &                 / (  e3uw_n(ji,jj,jk) * e3uw_b(ji,jj,jk) )
+                   z3dv(ji,jj,jk) = 0.5 * (  vn(ji,jj,jk-1) -  vn(ji,jj  ,jk) )   &
+                        &                 * (  vb(ji,jj,jk-1) -  vb(ji,jj  ,jk) ) * wvmask(ji,jj,jk) &
+                        &                 / (  e3vw_n(ji,jj,jk) * e3vw_b(ji,jj,jk) )
+                END DO
+             END DO
+          END DO
+      !
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1   ! vector opt.
+                  !                                          ! shear prod. at w-point weightened by mask
+                  zesh2  =  ( z3du(ji-1,jj,jk) + z3du(ji,jj,jk) ) / MAX( 1._wp , umask(ji-1,jj,jk) + umask(ji,jj,jk) )   &
+                     &    + ( z3dv(ji,jj-1,jk) + z3dv(ji,jj,jk) ) / MAX( 1._wp , vmask(ji,jj-1,jk) + vmask(ji,jj,jk) )
+                  !                                          ! local Richardson number
+                  zri   = MAX( rn2b(ji,jj,jk), 0._wp ) / MAX(zesh2, epsln)
+                  zfri =  MIN( zri / rn_riinfty , 1.0_wp )
+                  zfri  = ( 1.0_wp - zfri * zfri )
+                  zrimix(ji,jj,jk)  =  zfri * zfri  * zfri * wmask(ji, jj, jk)
+                END DO
+             END DO
+          END DO
+
+          DO jj = 2, jpjm1
+             DO ji = 2, jpim1
+                DO jk = ibld(ji,jj) + 1, jpkm1
+                   zdiffut(ji,jj,jk) = zrimix(ji,jj,jk)*rn_difri
+                   zviscos(ji,jj,jk) = zrimix(ji,jj,jk)*rn_difri
+                END DO
+             END DO
+          END DO
+
+       END IF ! ln_kpprimix = .true.
+
+! KPP-style set diffusivity large if unstable below BL
+       IF( ln_convmix) THEN
+          DO jj = 2, jpjm1
+             DO ji = 2, jpim1
+                DO jk = ibld(ji,jj) + 1, jpkm1
+                  IF(  MIN( rn2(ji,jj,jk), rn2b(ji,jj,jk) ) <= -1.e-12 ) zdiffut(ji,jj,jk) = rn_difconv
+                END DO
+             END DO
+          END DO
+       END IF ! ln_convmix = .true.
+
+       ! Lateral boundary conditions on zvicos (sign unchanged), needed to caclulate viscosities on u and v grids
+       CALL lbc_lnk( 'zdfosm', zviscos(:,:,:), 'W', 1. )
+
+       ! GN 25/8: need to change tmask --> wmask
+
+     DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+             DO ji = 2, jpim1
+                p_avt(ji,jj,jk) = MAX( zdiffut(ji,jj,jk), avtb(jk) ) * tmask(ji,jj,jk)
+                p_avm(ji,jj,jk) = MAX( zviscos(ji,jj,jk), avmb(jk) ) * tmask(ji,jj,jk)
+             END DO
+         END DO
+     END DO
+      ! Lateral boundary conditions on ghamu and ghamv, currently on W-grid  (sign unchanged), needed to caclulate gham[uv] on u and v grids
+     CALL lbc_lnk_multi( 'zdfosm', p_avt, 'W', 1. , p_avm, 'W', 1.,   &
+      &                  ghamu, 'W', 1. , ghamv, 'W', 1. )
+       DO jk = 2, jpkm1
+           DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  ghamu(ji,jj,jk) = ( ghamu(ji,jj,jk) + ghamu(ji+1,jj,jk) ) &
+                     &  / MAX( 1., tmask(ji,jj,jk) + tmask (ji + 1,jj,jk) ) * umask(ji,jj,jk)
+
+                  ghamv(ji,jj,jk) = ( ghamv(ji,jj,jk) + ghamv(ji,jj+1,jk) ) &
+                      &  / MAX( 1., tmask(ji,jj,jk) + tmask (ji,jj+1,jk) ) * vmask(ji,jj,jk)
+
+                  ghamt(ji,jj,jk) =  ghamt(ji,jj,jk) * tmask(ji,jj,jk)
+                  ghams(ji,jj,jk) =  ghams(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+           END DO
+        END DO
+        ! Lateral boundary conditions on final outputs for gham[ts],  on W-grid  (sign unchanged)
+        ! Lateral boundary conditions on final outputs for gham[uv],  on [UV]-grid  (sign unchanged)
+        CALL lbc_lnk_multi( 'zdfosm', ghamt, 'W', 1. , ghams, 'W', 1.,   &
+         &                  ghamu, 'U', 1. , ghamv, 'V', 1. )
+
+       IF(ln_dia_osm) THEN
+         SELECT CASE (nn_osm_wave)
+         ! Stokes drift set by assumimg onstant La#=0.3(=0)  or Pierson-Moskovitz spectrum (=1).
+         CASE(0:1)
+            IF ( iom_use("us_x") ) CALL iom_put( "us_x", tmask(:,:,1)*zustke*zcos_wind )   ! x surface Stokes drift
+            IF ( iom_use("us_y") ) CALL iom_put( "us_y", tmask(:,:,1)*zustke*zsin_wind )  ! y surface Stokes drift
+            IF ( iom_use("wind_wave_abs_power") ) CALL iom_put( "wind_wave_abs_power", 1000.*rau0*tmask(:,:,1)*zustar**2*zustke )
+         ! Stokes drift read in from sbcwave  (=2).
+         CASE(2)
+            IF ( iom_use("us_x") ) CALL iom_put( "us_x", ut0sd )               ! x surface Stokes drift
+            IF ( iom_use("us_y") ) CALL iom_put( "us_y", vt0sd )               ! y surface Stokes drift
+            IF ( iom_use("wind_wave_abs_power") ) CALL iom_put( "wind_wave_abs_power", 1000.*rau0*tmask(:,:,1)*zustar**2* &
+                 & SQRT(ut0sd**2 + vt0sd**2 ) )
+         END SELECT
+         IF ( iom_use("ghamt") ) CALL iom_put( "ghamt", tmask*ghamt )            ! <Tw_NL>
+         IF ( iom_use("ghams") ) CALL iom_put( "ghams", tmask*ghams )            ! <Sw_NL>
+         IF ( iom_use("ghamu") ) CALL iom_put( "ghamu", umask*ghamu )            ! <uw_NL>
+         IF ( iom_use("ghamv") ) CALL iom_put( "ghamv", vmask*ghamv )            ! <vw_NL>
+         IF ( iom_use("zwth0") ) CALL iom_put( "zwth0", tmask(:,:,1)*zwth0 )            ! <Tw_0>
+         IF ( iom_use("zws0") ) CALL iom_put( "zws0", tmask(:,:,1)*zws0 )                ! <Sw_0>
+         IF ( iom_use("hbl") ) CALL iom_put( "hbl", tmask(:,:,1)*hbl )                  ! boundary-layer depth
+         IF ( iom_use("hbli") ) CALL iom_put( "hbli", tmask(:,:,1)*hbli )               ! Initial boundary-layer depth
+         IF ( iom_use("dstokes") ) CALL iom_put( "dstokes", tmask(:,:,1)*dstokes )      ! Stokes drift penetration depth
+         IF ( iom_use("zustke") ) CALL iom_put( "zustke", tmask(:,:,1)*zustke )            ! Stokes drift magnitude at T-points
+         IF ( iom_use("zwstrc") ) CALL iom_put( "zwstrc", tmask(:,:,1)*zwstrc )         ! convective velocity scale
+         IF ( iom_use("zwstrl") ) CALL iom_put( "zwstrl", tmask(:,:,1)*zwstrl )         ! Langmuir velocity scale
+         IF ( iom_use("zustar") ) CALL iom_put( "zustar", tmask(:,:,1)*zustar )         ! friction velocity scale
+         IF ( iom_use("wind_power") ) CALL iom_put( "wind_power", 1000.*rau0*tmask(:,:,1)*zustar**3 ) ! BL depth internal to zdf_osm routine
+         IF ( iom_use("wind_wave_power") ) CALL iom_put( "wind_wave_power", 1000.*rau0*tmask(:,:,1)*zustar**2*zustke )
+         IF ( iom_use("zhbl") ) CALL iom_put( "zhbl", tmask(:,:,1)*zhbl )               ! BL depth internal to zdf_osm routine
+         IF ( iom_use("zhml") ) CALL iom_put( "zhml", tmask(:,:,1)*zhml )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("zdh") ) CALL iom_put( "zdh", tmask(:,:,1)*zdh )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("zhol") ) CALL iom_put( "zhol", tmask(:,:,1)*zhol )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("zwthav") ) CALL iom_put( "zwthav", tmask(:,:,1)*zwthav )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("zwth_ent") ) CALL iom_put( "zwth_ent", tmask(:,:,1)*zwth_ent )               ! ML depth internal to zdf_osm routine
+         IF ( iom_use("zt_ml") ) CALL iom_put( "zt_ml", tmask(:,:,1)*zt_ml )               ! average T in ML
+      END IF
+      ! Lateral boundary conditions on p_avt  (sign unchanged)
+      CALL lbc_lnk( 'zdfosm', p_avt(:,:,:), 'W', 1. )
+      !
+   END SUBROUTINE zdf_osm
+
+
+   SUBROUTINE zdf_osm_init
+     !!----------------------------------------------------------------------
+     !!                  ***  ROUTINE zdf_osm_init  ***
+     !!
+     !! ** Purpose :   Initialization of the vertical eddy diffivity and
+     !!      viscosity when using a osm turbulent closure scheme
+     !!
+     !! ** Method  :   Read the namosm namelist and check the parameters
+     !!      called at the first timestep (nit000)
+     !!
+     !! ** input   :   Namlist namosm
+     !!----------------------------------------------------------------------
+     INTEGER  ::   ios            ! local integer
+     INTEGER  ::   ji, jj, jk     ! dummy loop indices
+     !!
+     NAMELIST/namzdf_osm/ ln_use_osm_la, rn_osm_la, rn_osm_dstokes, nn_ave &
+          & ,nn_osm_wave, ln_dia_osm, rn_osm_hbl0 &
+          & ,ln_kpprimix, rn_riinfty, rn_difri, ln_convmix, rn_difconv
+     !!----------------------------------------------------------------------
+     !
+     REWIND( numnam_ref )              ! Namelist namzdf_osm in reference namelist : Osmosis ML model
+     READ  ( numnam_ref, namzdf_osm, IOSTAT = ios, ERR = 901)
+901  IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_osm in reference namelist' )
+
+     REWIND( numnam_cfg )              ! Namelist namzdf_tke in configuration namelist : Turbulent Kinetic Energy
+     READ  ( numnam_cfg, namzdf_osm, IOSTAT = ios, ERR = 902 )
+902  IF( ios >  0 ) CALL ctl_nam ( ios , 'namzdf_osm in configuration namelist' )
+     IF(lwm) WRITE ( numond, namzdf_osm )
+
+     IF(lwp) THEN                    ! Control print
+        WRITE(numout,*)
+        WRITE(numout,*) 'zdf_osm_init : OSMOSIS Parameterisation'
+        WRITE(numout,*) '~~~~~~~~~~~~'
+        WRITE(numout,*) '   Namelist namzdf_osm : set tke mixing parameters'
+        WRITE(numout,*) '     Use namelist  rn_osm_la                     ln_use_osm_la = ', ln_use_osm_la
+        WRITE(numout,*) '     Turbulent Langmuir number                     rn_osm_la   = ', rn_osm_la
+        WRITE(numout,*) '     Initial hbl for 1D runs                       rn_osm_hbl0   = ', rn_osm_hbl0
+        WRITE(numout,*) '     Depth scale of Stokes drift                rn_osm_dstokes = ', rn_osm_dstokes
+        WRITE(numout,*) '     horizontal average flag                       nn_ave      = ', nn_ave
+        WRITE(numout,*) '     Stokes drift                                  nn_osm_wave = ', nn_osm_wave
+        SELECT CASE (nn_osm_wave)
+        CASE(0)
+           WRITE(numout,*) '     calculated assuming constant La#=0.3'
+        CASE(1)
+           WRITE(numout,*) '     calculated from Pierson Moskowitz wind-waves'
+        CASE(2)
+           WRITE(numout,*) '     calculated from ECMWF wave fields'
+        END SELECT
+        WRITE(numout,*) '     Output osm diagnostics                       ln_dia_osm  = ',  ln_dia_osm
+        WRITE(numout,*) '     Use KPP-style shear instability mixing       ln_kpprimix = ', ln_kpprimix
+        WRITE(numout,*) '     local Richardson Number limit for shear instability rn_riinfty = ', rn_riinfty
+        WRITE(numout,*) '     maximum shear diffusivity at Rig = 0    (m2/s) rn_difri = ', rn_difri
+        WRITE(numout,*) '     Use large mixing below BL when unstable       ln_convmix = ', ln_convmix
+        WRITE(numout,*) '     diffusivity when unstable below BL     (m2/s) rn_difconv = ', rn_difconv
+     ENDIF
+
+
+     !                              ! Check wave coupling settings !
+     !                         ! Further work needed - see ticket #2447 !
+     IF( nn_osm_wave == 2 ) THEN
+        IF (.NOT. ( ln_wave .AND. ln_sdw )) &
+           & CALL ctl_stop( 'zdf_osm_init : ln_zdfosm and nn_osm_wave=2, ln_wave and ln_sdw must be true' )
+     END IF
+
+     !                              ! allocate zdfosm arrays
+     IF( zdf_osm_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_osm_init : unable to allocate arrays' )
+
+     call osm_rst( nit000, 'READ' ) !* read or initialize hbl
+
+     IF( ln_zdfddm) THEN
+        IF(lwp) THEN
+           WRITE(numout,*)
+           WRITE(numout,*) '    Double diffusion mixing on temperature and salinity '
+           WRITE(numout,*) '    CAUTION : done in routine zdfosm, not in routine zdfddm '
+        ENDIF
+     ENDIF
+
+
+     !set constants not in namelist
+     !-----------------------------
+
+     IF(lwp) THEN
+        WRITE(numout,*)
+     ENDIF
+
+     IF (nn_osm_wave == 0) THEN
+        dstokes(:,:) = rn_osm_dstokes
+     END IF
+
+     ! Horizontal average : initialization of weighting arrays
+     ! -------------------
+
+     SELECT CASE ( nn_ave )
+
+     CASE ( 0 )                ! no horizontal average
+        IF(lwp) WRITE(numout,*) '          no horizontal average on avt'
+        IF(lwp) WRITE(numout,*) '          only in very high horizontal resolution !'
+        ! weighting mean arrays etmean
+        !           ( 1  1 )
+        ! avt = 1/4 ( 1  1 )
+        !
+        etmean(:,:,:) = 0.e0
+
+        DO jk = 1, jpkm1
+           DO jj = 2, jpjm1
+              DO ji = 2, jpim1   ! vector opt.
+                 etmean(ji,jj,jk) = tmask(ji,jj,jk)                     &
+                      &  / MAX( 1.,  umask(ji-1,jj  ,jk) + umask(ji,jj,jk)   &
+                      &            + vmask(ji  ,jj-1,jk) + vmask(ji,jj,jk)  )
+              END DO
+           END DO
+        END DO
+
+     CASE ( 1 )                ! horizontal average
+        IF(lwp) WRITE(numout,*) '          horizontal average on avt'
+        ! weighting mean arrays etmean
+        !           ( 1/2  1  1/2 )
+        ! avt = 1/8 ( 1    2  1   )
+        !           ( 1/2  1  1/2 )
+        etmean(:,:,:) = 0.e0
+
+        DO jk = 1, jpkm1
+           DO jj = 2, jpjm1
+              DO ji = 2, jpim1   ! vector opt.
+                 etmean(ji,jj,jk) = tmask(ji, jj,jk)                           &
+                      & / MAX( 1., 2.* tmask(ji,jj,jk)                           &
+                      &      +.5 * ( tmask(ji-1,jj+1,jk) + tmask(ji-1,jj-1,jk)   &
+                      &             +tmask(ji+1,jj+1,jk) + tmask(ji+1,jj-1,jk) ) &
+                      &      +1. * ( tmask(ji-1,jj  ,jk) + tmask(ji  ,jj+1,jk)   &
+                      &             +tmask(ji  ,jj-1,jk) + tmask(ji+1,jj  ,jk) ) )
+              END DO
+           END DO
+        END DO
+
+     CASE DEFAULT
+        WRITE(ctmp1,*) '          bad flag value for nn_ave = ', nn_ave
+        CALL ctl_stop( ctmp1 )
+
+     END SELECT
+
+     ! Initialization of vertical eddy coef. to the background value
+     ! -------------------------------------------------------------
+     DO jk = 1, jpk
+        avt (:,:,jk) = avtb(jk) * tmask(:,:,jk)
+     END DO
+
+     ! zero the surface flux for non local term and osm mixed layer depth
+     ! ------------------------------------------------------------------
+     ghamt(:,:,:) = 0.
+     ghams(:,:,:) = 0.
+     ghamu(:,:,:) = 0.
+     ghamv(:,:,:) = 0.
+     !
+     IF( lwxios ) THEN
+        CALL iom_set_rstw_var_active('wn')
+        CALL iom_set_rstw_var_active('hbl')
+        CALL iom_set_rstw_var_active('hbli')
+     ENDIF
+   END SUBROUTINE zdf_osm_init
+
+
+   SUBROUTINE osm_rst( kt, cdrw )
+     !!---------------------------------------------------------------------
+     !!                   ***  ROUTINE osm_rst  ***
+     !!
+     !! ** Purpose :   Read or write BL fields in restart file
+     !!
+     !! ** Method  :   use of IOM library. If the restart does not contain
+     !!                required fields, they are recomputed from stratification
+     !!----------------------------------------------------------------------
+
+     INTEGER, INTENT(in) :: kt
+     CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+
+     INTEGER ::   id1, id2   ! iom enquiry index
+     INTEGER  ::   ji, jj, jk     ! dummy loop indices
+     INTEGER  ::   iiki, ikt ! local integer
+     REAL(wp) ::   zhbf           ! tempory scalars
+     REAL(wp) ::   zN2_c           ! local scalar
+     REAL(wp) ::   rho_c = 0.01_wp    !: density criterion for mixed layer depth
+     INTEGER, DIMENSION(:,:), ALLOCATABLE :: imld_rst ! level of mixed-layer depth (pycnocline top)
+     !!----------------------------------------------------------------------
+     !
+     !!-----------------------------------------------------------------------------
+     ! If READ/WRITE Flag is 'READ', try to get hbl from restart file. If successful then return
+     !!-----------------------------------------------------------------------------
+     IF( TRIM(cdrw) == 'READ'.AND. ln_rstart) THEN
+        id1 = iom_varid( numror, 'wn'   , ldstop = .FALSE. )
+        IF( id1 > 0 ) THEN                       ! 'wn' exists; read
+           CALL iom_get( numror, jpdom_autoglo, 'wn', wn, ldxios = lrxios )
+           WRITE(numout,*) ' ===>>>> :  wn read from restart file'
+        ELSE
+           wn(:,:,:) = 0._wp
+           WRITE(numout,*) ' ===>>>> :  wn not in restart file, set to zero initially'
+        END IF
+        id1 = iom_varid( numror, 'hbl'   , ldstop = .FALSE. )
+        id2 = iom_varid( numror, 'hbli'   , ldstop = .FALSE. )
+        IF( id1 > 0 .AND. id2 > 0) THEN                       ! 'hbl' exists; read and return
+           CALL iom_get( numror, jpdom_autoglo, 'hbl' , hbl , ldxios = lrxios )
+           CALL iom_get( numror, jpdom_autoglo, 'hbli', hbli, ldxios = lrxios  )
+           WRITE(numout,*) ' ===>>>> :  hbl & hbli read from restart file'
+           RETURN
+        ELSE                      ! 'hbl' & 'hbli' not in restart file, recalculate
+           WRITE(numout,*) ' ===>>>> : previous run without osmosis scheme, hbl computed from stratification'
+        END IF
+     END IF
+
+     !!-----------------------------------------------------------------------------
+     ! If READ/WRITE Flag is 'WRITE', write hbl into the restart file, then return
+     !!-----------------------------------------------------------------------------
+     IF( TRIM(cdrw) == 'WRITE') THEN     !* Write hbli into the restart file, then return
+        IF(lwp) WRITE(numout,*) '---- osm-rst ----'
+         CALL iom_rstput( kt, nitrst, numrow, 'wn'     , wn  , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'hbl'    , hbl , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'hbli'   , hbli, ldxios = lwxios )
+        RETURN
+     END IF
+
+     !!-----------------------------------------------------------------------------
+     ! Getting hbl, no restart file with hbl, so calculate from surface stratification
+     !!-----------------------------------------------------------------------------
+     IF( lwp ) WRITE(numout,*) ' ===>>>> : calculating hbl computed from stratification'
+     ALLOCATE( imld_rst(jpi,jpj) )
+     ! w-level of the mixing and mixed layers
+     CALL eos_rab( tsn, rab_n )
+     CALL bn2(tsn, rab_n, rn2)
+     imld_rst(:,:)  = nlb10         ! Initialization to the number of w ocean point
+     hbl(:,:)  = 0._wp              ! here hbl used as a dummy variable, integrating vertically N^2
+     zN2_c = grav * rho_c * r1_rau0 ! convert density criteria into N^2 criteria
+     !
+     hbl(:,:)  = 0._wp              ! here hbl used as a dummy variable, integrating vertically N^2
+     DO jk = 1, jpkm1
+        DO jj = 1, jpj              ! Mixed layer level: w-level
+           DO ji = 1, jpi
+              ikt = mbkt(ji,jj)
+              hbl(ji,jj) = hbl(ji,jj) + MAX( rn2(ji,jj,jk) , 0._wp ) * e3w_n(ji,jj,jk)
+              IF( hbl(ji,jj) < zN2_c )   imld_rst(ji,jj) = MIN( jk , ikt ) + 1   ! Mixed layer level
+           END DO
+        END DO
+     END DO
+     !
+     DO jj = 1, jpj
+        DO ji = 1, jpi
+           iiki = imld_rst(ji,jj)
+           hbl (ji,jj) = gdepw_n(ji,jj,iiki  ) * ssmask(ji,jj)    ! Turbocline depth
+        END DO
+     END DO
+     hbl = MAX(hbl,epsln)
+     hbli(:,:) = hbl(:,:)
+     DEALLOCATE( imld_rst )
+     WRITE(numout,*) ' ===>>>> : hbl computed from stratification'
+   END SUBROUTINE osm_rst
+
+
+   SUBROUTINE tra_osm( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_osm  ***
+      !!
+      !! ** Purpose :   compute and add to the tracer trend the non-local tracer flux
+      !!
+      !! ** Method  :   ???
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds   ! 3D workspace
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt
+      INTEGER :: ji, jj, jk
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_osm : OSM non-local tracer fluxes'
+         IF(lwp) WRITE(numout,*) '~~~~~~~   '
+      ENDIF
+
+      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) )   ;    ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ALLOCATE( ztrds(jpi,jpj,jpk) )   ;    ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+
+      ! add non-local temperature and salinity flux
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               tsa(ji,jj,jk,jp_tem) =  tsa(ji,jj,jk,jp_tem)                      &
+                  &                 - (  ghamt(ji,jj,jk  )  &
+                  &                    - ghamt(ji,jj,jk+1) ) /e3t_n(ji,jj,jk)
+               tsa(ji,jj,jk,jp_sal) =  tsa(ji,jj,jk,jp_sal)                      &
+                  &                 - (  ghams(ji,jj,jk  )  &
+                  &                    - ghams(ji,jj,jk+1) ) / e3t_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+
+      ! save the non-local tracer flux trends for diagnostic
+      IF( l_trdtra )   THEN
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
+!!bug gm jpttdzdf ==> jpttosm
+         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
+
+      IF(ln_ctl) THEN
+         CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' osm  - Ta: ', mask1=tmask,   &
+         &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      ENDIF
+      !
+   END SUBROUTINE tra_osm
+
+
+   SUBROUTINE trc_osm( kt )          ! Dummy routine
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_osm  ***
+      !!
+      !! ** Purpose :   compute and add to the passive tracer trend the non-local
+      !!                 passive tracer flux
+      !!
+      !!
+      !! ** Method  :   ???
+      !!----------------------------------------------------------------------
+      !
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt
+      WRITE(*,*) 'trc_osm: Not written yet', kt
+   END SUBROUTINE trc_osm
+
+
+   SUBROUTINE dyn_osm( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dyn_osm  ***
+      !!
+      !! ** Purpose :   compute and add to the velocity trend the non-local flux
+      !! copied/modified from tra_osm
+      !!
+      !! ** Method  :   ???
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   !
+      !
+      INTEGER :: ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dyn_osm : OSM non-local velocity'
+         IF(lwp) WRITE(numout,*) '~~~~~~~   '
+      ENDIF
+      !code saving tracer trends removed, replace with trdmxl_oce
+
+      DO jk = 1, jpkm1           ! add non-local u and v fluxes
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               ua(ji,jj,jk) =  ua(ji,jj,jk)                      &
+                  &                 - (  ghamu(ji,jj,jk  )  &
+                  &                    - ghamu(ji,jj,jk+1) ) / e3u_n(ji,jj,jk)
+               va(ji,jj,jk) =  va(ji,jj,jk)                      &
+                  &                 - (  ghamv(ji,jj,jk  )  &
+                  &                    - ghamv(ji,jj,jk+1) ) / e3v_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      ! code for saving tracer trends removed
+      !
+   END SUBROUTINE dyn_osm
+
+   !!======================================================================
+END MODULE zdfosm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfphy.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfphy.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfphy.F90	(revision 14097)
@@ -0,0 +1,349 @@
+MODULE zdfphy
+   !!======================================================================
+   !!                      ***  MODULE  zdfphy  ***
+   !! Vertical ocean physics :   manager of all vertical physics packages
+   !!======================================================================
+   !! History :  4.0  !  2017-04  (G. Madec)  original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_phy_init  : initialization of all vertical physics packages
+   !!   zdf_phy       : upadate at each time-step the vertical mixing coeff. 
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE zdf_oce        ! vertical physics: shared variables         
+   USE zdfdrg         ! vertical physics: top/bottom drag coef.
+   USE zdfsh2         ! vertical physics: shear production term of TKE
+   USE zdfric         ! vertical physics: RIChardson dependent vertical mixing   
+   USE zdftke         ! vertical physics: TKE vertical mixing
+   USE zdfgls         ! vertical physics: GLS vertical mixing
+   USE zdfosm         ! vertical physics: OSMOSIS vertical mixing
+   USE zdfddm         ! vertical physics: double diffusion mixing      
+   USE zdfevd         ! vertical physics: convection via enhanced vertical diffusion  
+   USE zdfiwm         ! vertical physics: internal wave-induced mixing  
+   USE zdfswm         ! vertical physics: surface  wave-induced mixing
+   USE zdfmxl         ! vertical physics: mixed layer
+   USE tranpc         ! convection: non penetrative adjustment
+   USE trc_oce        ! variables shared between passive tracer & ocean           
+   USE sbc_oce        ! surface module (only for nn_isf in the option compatibility test)
+   USE sbcrnf         ! surface boundary condition: runoff variables
+   USE sbc_ice        ! sea ice drag
+#if defined key_agrif
+   USE agrif_oce_interp   ! interpavm
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! IOM library
+   USE lbclnk         ! lateral boundary conditions
+   USE lib_mpp        ! distribued memory computing
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_phy_init  ! called by nemogcm.F90
+   PUBLIC   zdf_phy       ! called by step.F90
+
+   INTEGER ::   nzdf_phy   ! type of vertical closure used 
+   !                       ! associated indicators
+   INTEGER, PARAMETER ::   np_CST = 1   ! Constant Kz
+   INTEGER, PARAMETER ::   np_RIC = 2   ! Richardson number dependent Kz
+   INTEGER, PARAMETER ::   np_TKE = 3   ! Turbulente Kinetic Eenergy closure scheme for Kz
+   INTEGER, PARAMETER ::   np_GLS = 4   ! Generic Length Scale closure scheme for Kz
+   INTEGER, PARAMETER ::   np_OSM = 5   ! OSMOSIS-OBL closure scheme for Kz
+
+   LOGICAL ::   l_zdfsh2   ! shear production term flag (=F for CST, =T otherwise (i.e. TKE, GLS, RIC))
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_phy_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_phy_init  ***
+      !! 
+      !! ** Purpose :   initializations of the vertical ocean physics
+      !!
+      !! ** Method  :   Read namelist namzdf, control logicals 
+      !!                set horizontal shape and vertical profile of background mixing coef.
+      !!----------------------------------------------------------------------
+      INTEGER ::   jk            ! dummy loop indices
+      INTEGER ::   ioptio, ios   ! local integers
+      !!
+      NAMELIST/namzdf/ ln_zdfcst, ln_zdfric, ln_zdftke, ln_zdfgls,   &     ! type of closure scheme
+         &             ln_zdfosm,                                    &     ! type of closure scheme
+         &             ln_zdfevd, nn_evdm, rn_evd ,                  &     ! convection : evd
+         &             ln_zdfnpc, nn_npc , nn_npcp,                  &     ! convection : npc
+         &             ln_zdfddm, rn_avts, rn_hsbfr,                 &     ! double diffusion
+         &             ln_zdfswm,                                    &     ! surface  wave-induced mixing
+         &             ln_zdfiwm,                                    &     ! internal  -      -      -
+         &             ln_zad_Aimp,                                  &     ! apdative-implicit vertical advection
+         &             rn_avm0, rn_avt0, nn_avb, nn_havtb                  ! coefficients
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_phy_init: ocean vertical physics'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      !                           !==  Namelist  ==!
+      REWIND( numnam_ref )              ! Namelist namzdf in reference namelist : Vertical mixing parameters
+      READ  ( numnam_ref, namzdf, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namzdf in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namzdf in reference namelist : Vertical mixing parameters
+      READ  ( numnam_cfg, namzdf, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namzdf in configuration namelist' )
+      IF(lwm)   WRITE ( numond, namzdf )
+      !
+      IF(lwp) THEN                      ! Parameter print
+         WRITE(numout,*) '   Namelist namzdf : set vertical mixing mixing parameters'
+         WRITE(numout,*) '      adaptive-implicit vertical advection'
+         WRITE(numout,*) '         Courant number targeted application   ln_zad_Aimp = ', ln_zad_Aimp
+         WRITE(numout,*) '      vertical closure scheme'
+         WRITE(numout,*) '         constant vertical mixing coefficient    ln_zdfcst = ', ln_zdfcst
+         WRITE(numout,*) '         Richardson number dependent closure     ln_zdfric = ', ln_zdfric
+         WRITE(numout,*) '         Turbulent Kinetic Energy closure (TKE)  ln_zdftke = ', ln_zdftke
+         WRITE(numout,*) '         Generic Length Scale closure (GLS)      ln_zdfgls = ', ln_zdfgls
+         WRITE(numout,*) '         OSMOSIS-OBL closure (OSM)               ln_zdfosm = ', ln_zdfosm
+         WRITE(numout,*) '      convection: '
+         WRITE(numout,*) '         enhanced vertical diffusion             ln_zdfevd = ', ln_zdfevd
+         WRITE(numout,*) '            applied on momentum (=1/0)             nn_evdm = ', nn_evdm
+         WRITE(numout,*) '            vertical coefficient for evd           rn_evd  = ', rn_evd
+         WRITE(numout,*) '         non-penetrative convection (npc)        ln_zdfnpc = ', ln_zdfnpc
+         WRITE(numout,*) '            npc call  frequency                    nn_npc  = ', nn_npc
+         WRITE(numout,*) '            npc print frequency                    nn_npcp = ', nn_npcp
+         WRITE(numout,*) '      double diffusive mixing                    ln_zdfddm = ', ln_zdfddm
+         WRITE(numout,*) '         maximum avs for dd mixing                 rn_avts = ', rn_avts
+         WRITE(numout,*) '         heat/salt buoyancy flux ratio             rn_hsbfr= ', rn_hsbfr
+         WRITE(numout,*) '      gravity wave-induced mixing'
+         WRITE(numout,*) '         surface  wave (Qiao et al 2010)         ln_zdfswm = ', ln_zdfswm                                          ! surface wave induced mixing
+         WRITE(numout,*) '         internal wave (de Lavergne et al 2017)  ln_zdfiwm = ', ln_zdfiwm
+         WRITE(numout,*) '      coefficients : '
+         WRITE(numout,*) '         vertical eddy viscosity                 rn_avm0   = ', rn_avm0
+         WRITE(numout,*) '         vertical eddy diffusivity               rn_avt0   = ', rn_avt0
+         WRITE(numout,*) '         constant background or profile          nn_avb    = ', nn_avb
+         WRITE(numout,*) '         horizontal variation for avtb           nn_havtb  = ', nn_havtb
+      ENDIF
+
+      IF( ln_zad_Aimp ) THEN
+         IF( zdf_phy_alloc() /= 0 )   &
+            &       CALL ctl_stop( 'STOP', 'zdf_phy_init : unable to allocate adaptive-implicit z-advection arrays' )
+         Cu_adv(:,:,:) = 0._wp
+         wi    (:,:,:) = 0._wp
+      ENDIF
+      !                          !==  Background eddy viscosity and diffusivity  ==!
+      IF( nn_avb == 0 ) THEN             ! Define avmb, avtb from namelist parameter
+         avmb(:) = rn_avm0
+         avtb(:) = rn_avt0                     
+      ELSE                               ! Background profile of avt (fit a theoretical/observational profile (Krauss 1990)
+         avmb(:) = rn_avm0
+         avtb(:) = rn_avt0 + ( 3.e-4_wp - 2._wp * rn_avt0 ) * 1.e-4_wp * gdepw_1d(:)   ! m2/s
+         IF(ln_sco .AND. lwp)   CALL ctl_warn( 'avtb profile not valid in sco' )
+      ENDIF
+      !                                  ! 2D shape of the avtb
+      avtb_2d(:,:) = 1._wp                   ! uniform 
+      !
+      IF( nn_havtb == 1 ) THEN               ! decrease avtb by a factor of ten in the equatorial band
+           !                                 !   -15S -5S : linear decrease from avt0 to avt0/10.
+           !                                 !   -5S  +5N : cst value avt0/10.
+           !                                 !    5N  15N : linear increase from avt0/10, to avt0
+           WHERE(-15. <= gphit .AND. gphit < -5 )   avtb_2d = (1.  - 0.09 * (gphit + 15.))
+           WHERE( -5. <= gphit .AND. gphit <  5 )   avtb_2d =  0.1
+           WHERE(  5. <= gphit .AND. gphit < 15 )   avtb_2d = (0.1 + 0.09 * (gphit -  5.))
+      ENDIF
+      !
+      DO jk = 1, jpk                      ! set turbulent closure Kz to the background value (avt_k, avm_k)
+         avt_k(:,:,jk) = avtb_2d(:,:) * avtb(jk) * wmask (:,:,jk)
+         avm_k(:,:,jk) =                avmb(jk) * wmask (:,:,jk)
+      END DO
+!!gm  to be tested only the 1st & last levels
+!      avt  (:,:, 1 ) = 0._wp   ;   avs(:,:, 1 ) = 0._wp   ;   avm  (:,:, 1 ) = 0._wp
+!      avt  (:,:,jpk) = 0._wp   ;   avs(:,:,jpk) = 0._wp   ;   avm  (:,:,jpk) = 0._wp
+!!gm
+      avt  (:,:,:) = 0._wp   ;   avs(:,:,:) = 0._wp   ;   avm  (:,:,:) = 0._wp
+
+      !                          !==  Convection  ==!
+      !
+      IF( ln_zdfnpc .AND. ln_zdfevd )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfnpc and ln_zdfevd' )
+      IF( ln_zdfosm .AND. ln_zdfevd )   CALL ctl_stop( 'zdf_phy_init: chose between ln_zdfosm and ln_zdfevd' )
+      IF( lk_top    .AND. ln_zdfnpc )   CALL ctl_stop( 'zdf_phy_init: npc scheme is not working with key_top' )
+      IF( lk_top    .AND. ln_zdfosm )   CALL ctl_stop( 'zdf_phy_init: osmosis scheme is not working with key_top' )
+      IF(lwp) THEN
+         WRITE(numout,*)
+         IF    ( ln_zdfnpc ) THEN  ;   WRITE(numout,*) '   ==>>>   convection: use non penetrative convective scheme'
+         ELSEIF( ln_zdfevd ) THEN  ;   WRITE(numout,*) '   ==>>>   convection: use enhanced vertical diffusion scheme'
+         ELSE                      ;   WRITE(numout,*) '   ==>>>   convection: no specific scheme used'
+         ENDIF
+      ENDIF
+
+      IF(lwp) THEN               !==  Double Diffusion Mixing parameterization  ==!   (ddm)
+         WRITE(numout,*)
+         IF( ln_zdfddm ) THEN   ;   WRITE(numout,*) '   ==>>>   use double diffusive mixing: avs /= avt'
+         ELSE                   ;   WRITE(numout,*) '   ==>>>   No  double diffusive mixing: avs = avt'
+         ENDIF
+      ENDIF
+
+      !                          !==  type of vertical turbulent closure  ==!    (set nzdf_phy)
+      ioptio = 0 
+      IF( ln_zdfcst ) THEN   ;   ioptio = ioptio + 1   ;    nzdf_phy = np_CST   ;   ENDIF
+      IF( ln_zdfric ) THEN   ;   ioptio = ioptio + 1   ;    nzdf_phy = np_RIC   ;   CALL zdf_ric_init   ;   ENDIF
+      IF( ln_zdftke ) THEN   ;   ioptio = ioptio + 1   ;    nzdf_phy = np_TKE   ;   CALL zdf_tke_init   ;   ENDIF
+      IF( ln_zdfgls ) THEN   ;   ioptio = ioptio + 1   ;    nzdf_phy = np_GLS   ;   CALL zdf_gls_init   ;   ENDIF
+      IF( ln_zdfosm ) THEN   ;   ioptio = ioptio + 1   ;    nzdf_phy = np_OSM   ;   CALL zdf_osm_init   ;   ENDIF
+      !
+      IF( ioptio /= 1 )    CALL ctl_stop( 'zdf_phy_init: one and only one vertical diffusion option has to be defined ' )
+      IF( ln_isfcav ) THEN
+      IF( ln_zdfric .OR. ln_zdfgls )    CALL ctl_stop( 'zdf_phy_init: zdfric and zdfgls never tested with ice shelves cavities ' )
+      ENDIF
+      !                                ! shear production term flag
+      IF( ln_zdfcst ) THEN   ;   l_zdfsh2 = .FALSE.
+      ELSE                   ;   l_zdfsh2 = .TRUE.
+      ENDIF
+
+      !                          !== gravity wave-driven mixing  ==!
+      IF( ln_zdfiwm )   CALL zdf_iwm_init       ! internal wave-driven mixing
+      IF( ln_zdfswm )   CALL zdf_swm_init       ! surface  wave-driven mixing
+
+      !                          !== top/bottom friction  ==!
+      CALL zdf_drg_init
+      !
+      !                          !== time-stepping  ==!
+      ! Check/update of time stepping done in dynzdf_init/trazdf_init
+      !!gm move it here ?
+      !
+   END SUBROUTINE zdf_phy_init
+
+
+   SUBROUTINE zdf_phy( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE zdf_phy  ***
+      !!
+      !! ** Purpose :  Update ocean physics at each time-step
+      !!
+      !! ** Method  : 
+      !!
+      !! ** Action  :   avm, avt vertical eddy viscosity and diffusivity at w-points
+      !!                nmld ??? mixed layer depth in level and meters   <<<<====verifier !
+      !!                bottom stress.....                               <<<<====verifier !
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indice
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zsh2   ! shear production
+      !! ---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('zdf_phy')
+      !
+      IF( l_zdfdrg ) THEN     !==  update top/bottom drag  ==!   (non-linear cases)
+         !
+         !                       !* bottom drag
+         CALL zdf_drg( kt, mbkt    , r_Cdmin_bot, r_Cdmax_bot,   &   ! <<== in 
+            &              r_z0_bot,   r_ke0_bot,    rCd0_bot,   &
+            &                                        rCdU_bot  )     ! ==>> out : bottom drag [m/s]
+         IF( ln_isfcav ) THEN    !* top drag   (ocean cavities)
+            CALL zdf_drg( kt, mikt    , r_Cdmin_top, r_Cdmax_top,   &   ! <<== in 
+               &              r_z0_top,   r_ke0_top,    rCd0_top,   &
+               &                                        rCdU_top  )     ! ==>> out : bottom drag [m/s]
+         ENDIF
+      ENDIF
+      !
+#if defined key_si3
+      IF ( ln_drgice_imp) THEN
+         IF ( ln_isfcav ) THEN
+            rCdU_top(:,:) = rCdU_top(:,:) + ssmask(:,:) * tmask(:,:,1) * rCdU_ice(:,:)
+         ELSE
+            rCdU_top(:,:) = rCdU_ice(:,:)
+         ENDIF
+      ENDIF
+#endif
+      ! 
+      !                       !==  Kz from chosen turbulent closure  ==!   (avm_k, avt_k)
+      !
+      IF( l_zdfsh2 )   &         !* shear production at w-points (energy conserving form)
+         CALL zdf_sh2( ub, vb, un, vn, avm_k,   &     ! <<== in
+            &                           zsh2    )     ! ==>> out : shear production
+      !
+      SELECT CASE ( nzdf_phy )                  !* Vertical eddy viscosity and diffusivity coefficients at w-points
+      CASE( np_RIC )   ;   CALL zdf_ric( kt, gdept_n, zsh2, avm_k, avt_k )    ! Richardson number dependent Kz
+      CASE( np_TKE )   ;   CALL zdf_tke( kt         , zsh2, avm_k, avt_k )    ! TKE closure scheme for Kz
+      CASE( np_GLS )   ;   CALL zdf_gls( kt         , zsh2, avm_k, avt_k )    ! GLS closure scheme for Kz
+      CASE( np_OSM )   ;   CALL zdf_osm( kt               , avm_k, avt_k )    ! OSMOSIS closure scheme for Kz
+!     CASE( np_CST )                                  ! Constant Kz (reset avt, avm to the background value)
+!         ! avt_k and avm_k set one for all at initialisation phase
+!!gm         avt(2:jpim1,2:jpjm1,1:jpkm1) = rn_avt0 * wmask(2:jpim1,2:jpjm1,1:jpkm1)
+!!gm         avm(2:jpim1,2:jpjm1,1:jpkm1) = rn_avm0 * wmask(2:jpim1,2:jpjm1,1:jpkm1)
+      END SELECT
+      !  
+      !                          !==  ocean Kz  ==!   (avt, avs, avm)
+      !
+      !                                         !* start from turbulent closure values
+      avt(:,:,2:jpkm1) = avt_k(:,:,2:jpkm1)
+      avm(:,:,2:jpkm1) = avm_k(:,:,2:jpkm1)
+      !
+      IF( ln_rnf_mouth ) THEN                   !* increase diffusivity at rivers mouths
+         DO jk = 2, nkrnf
+            avt(:,:,jk) = avt(:,:,jk) + 2._wp * rn_avt_rnf * rnfmsk(:,:) * wmask(:,:,jk)
+         END DO
+      ENDIF
+      !
+      IF( ln_zdfevd )   CALL zdf_evd( kt, avm, avt )  !* convection: enhanced vertical eddy diffusivity
+      !
+      !                                         !* double diffusive mixing
+      IF( ln_zdfddm ) THEN                            ! update avt and compute avs
+                        CALL zdf_ddm( kt, avm, avt, avs )
+      ELSE                                            ! same mixing on all tracers
+         avs(2:jpim1,2:jpjm1,1:jpkm1) = avt(2:jpim1,2:jpjm1,1:jpkm1)
+      ENDIF
+      !
+      !                                         !* wave-induced mixing 
+      IF( ln_zdfswm )   CALL zdf_swm( kt, avm, avt, avs )   ! surface  wave (Qiao et al. 2004) 
+      IF( ln_zdfiwm )   CALL zdf_iwm( kt, avm, avt, avs )   ! internal wave (de Lavergne et al 2017)
+
+#if defined key_agrif 
+      ! interpolation parent grid => child grid for avm_k ( ex : at west border: update column 1 and 2)
+      IF( l_zdfsh2 )   CALL Agrif_avm
+#endif
+
+      !                                         !* Lateral boundary conditions (sign unchanged)
+      IF( l_zdfsh2 ) THEN
+         CALL lbc_lnk_multi( 'zdfphy', avm_k, 'W', 1. , avt_k, 'W', 1.,   &
+            &                avm  , 'W', 1. , avt  , 'W', 1. , avs , 'W', 1. )
+      ELSE
+         CALL lbc_lnk_multi( 'zdfphy', avm  , 'W', 1. , avt  , 'W', 1. , avs , 'W', 1. )
+      ENDIF
+      !
+      IF( l_zdfdrg ) THEN     ! drag  have been updated (non-linear cases)
+         IF( ln_isfcav ) THEN   ;  CALL lbc_lnk_multi( 'zdfphy', rCdU_top, 'T', 1. , rCdU_bot, 'T', 1. )   ! top & bot drag
+         ELSE                   ;  CALL lbc_lnk      ( 'zdfphy', rCdU_bot, 'T', 1. )                       ! bottom drag only
+         ENDIF
+      ENDIF
+      !
+      CALL zdf_mxl( kt )                        !* mixed layer depth, and level
+      !
+      IF( lrst_oce ) THEN                       !* write TKE, GLS or RIC fields in the restart file
+         IF( ln_zdftke )   CALL tke_rst( kt, 'WRITE' )
+         IF( ln_zdfgls )   CALL gls_rst( kt, 'WRITE' )
+         IF( ln_zdfric )   CALL ric_rst( kt, 'WRITE' ) 
+         ! NB. OSMOSIS restart (osm_rst) will be called in step.F90 after wn has been updated
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('zdf_phy')
+      !
+   END SUBROUTINE zdf_phy
+   INTEGER FUNCTION zdf_phy_alloc()
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION zdf_phy_alloc  ***
+      !!----------------------------------------------------------------------
+     ! Allocate wi array (declared in oce.F90) for use with the adaptive-implicit vertical velocity option
+     ALLOCATE(     wi(jpi,jpj,jpk), Cu_adv(jpi,jpj,jpk),  STAT= zdf_phy_alloc )
+     IF( zdf_phy_alloc /= 0 )   CALL ctl_warn('zdf_phy_alloc: failed to allocate ln_zad_Aimp=T required arrays')
+     CALL mpp_sum ( 'zdfphy', zdf_phy_alloc )
+   END FUNCTION zdf_phy_alloc
+
+   !!======================================================================
+END MODULE zdfphy
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfric.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfric.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfric.F90	(revision 14097)
@@ -0,0 +1,247 @@
+MODULE zdfric
+   !!======================================================================
+   !!                       ***  MODULE  zdfric  ***
+   !! Ocean physics:  vertical mixing coefficient compute from the local
+   !!                 Richardson number dependent formulation
+   !!======================================================================
+   !! History :  OPA  !  1987-09  (P. Andrich)  Original code
+   !!            4.0  !  1991-11  (G. Madec)
+   !!            7.0  !  1996-01  (G. Madec)  complete rewriting of multitasking suppression of common work arrays
+   !!            8.0  !  1997-06  (G. Madec)  complete rewriting of zdfmix
+   !!   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.1!  2011-09  (P. Oddo) Mixed layer depth parameterization
+   !!            4.0  !  2017-04  (G. Madec)  remove CPP ddm key & avm at t-point only 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_ric_init  : initialization, namelist read, & parameters control
+   !!   zdf_ric       : update momentum and tracer Kz from the Richardson number
+   !!   ric_rst       : read/write RIC restart in ocean restart file
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! vertical physics: variables
+   USE phycst         ! physical constants
+   USE sbc_oce,  ONLY :   taum
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_ric         ! called by zdfphy.F90
+   PUBLIC   ric_rst         ! called by zdfphy.F90
+   PUBLIC   zdf_ric_init    ! called by nemogcm.F90
+
+   !                        !!* Namelist namzdf_ric : Richardson number dependent Kz *
+   INTEGER  ::   nn_ric      ! coefficient of the parameterization
+   REAL(wp) ::   rn_avmri    ! maximum value of the vertical eddy viscosity
+   REAL(wp) ::   rn_alp      ! coefficient of the parameterization
+   REAL(wp) ::   rn_ekmfc    ! Ekman Factor Coeff
+   REAL(wp) ::   rn_mldmin   ! minimum mixed layer (ML) depth    
+   REAL(wp) ::   rn_mldmax   ! maximum mixed layer depth
+   REAL(wp) ::   rn_wtmix    ! Vertical eddy Diff. in the ML
+   REAL(wp) ::   rn_wvmix    ! Vertical eddy Visc. in the ML
+   LOGICAL  ::   ln_mldw     ! Use or not the MLD parameters
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_ric_init
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE zdf_ric_init  ***
+      !!                    
+      !! ** Purpose :   Initialization of the vertical eddy diffusivity and
+      !!      viscosity coef. for the Richardson number dependent formulation.
+      !!
+      !! ** Method  :   Read the namzdf_ric namelist and check the parameter values
+      !!
+      !! ** input   :   Namelist namzdf_ric
+      !!
+      !! ** Action  :   increase by 1 the nstop flag is setting problem encounter
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      INTEGER ::   ios          ! Local integer output status for namelist read
+      !!
+      NAMELIST/namzdf_ric/ rn_avmri, rn_alp   , nn_ric  , rn_ekmfc,  &
+         &                rn_mldmin, rn_mldmax, rn_wtmix, rn_wvmix, ln_mldw
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_ric in reference namelist : Vertical diffusion Kz depends on Richardson number
+      READ  ( numnam_ref, namzdf_ric, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_ric in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namzdf_ric in configuration namelist : Vertical diffusion Kz depends on Richardson number
+      READ  ( numnam_cfg, namzdf_ric, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namzdf_ric in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_ric )
+      !
+      IF(lwp) THEN                   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_ric_init : Ri depend vertical mixing scheme'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_ric : set Kz=F(Ri) parameters'
+         WRITE(numout,*) '      maximum vertical viscosity        rn_avmri  = ', rn_avmri
+         WRITE(numout,*) '      coefficient                       rn_alp    = ', rn_alp
+         WRITE(numout,*) '      exponent                          nn_ric    = ', nn_ric
+         WRITE(numout,*) '      Ekman layer enhanced mixing       ln_mldw   = ', ln_mldw
+         WRITE(numout,*) '         Ekman Factor Coeff             rn_ekmfc  = ', rn_ekmfc
+         WRITE(numout,*) '         minimum mixed layer depth      rn_mldmin = ', rn_mldmin
+         WRITE(numout,*) '         maximum mixed layer depth      rn_mldmax = ', rn_mldmax
+         WRITE(numout,*) '         Vertical eddy Diff. in the ML  rn_wtmix  = ', rn_wtmix
+         WRITE(numout,*) '         Vertical eddy Visc. in the ML  rn_wvmix  = ', rn_wvmix
+      ENDIF
+      !
+      CALL ric_rst( nit000, 'READ' )  !* read or initialize all required files
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('avt_k')
+         CALL iom_set_rstw_var_active('avm_k')
+      ENDIF
+   END SUBROUTINE zdf_ric_init
+
+
+   SUBROUTINE zdf_ric( kt, pdept, p_sh2, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE zdfric  ***
+      !!                    
+      !! ** Purpose :   Compute the before eddy viscosity and diffusivity as
+      !!                a function of the local richardson number.
+      !!
+      !! ** Method  :   Local richardson number dependent formulation of the 
+      !!                vertical eddy viscosity and diffusivity coefficients. 
+      !!                The eddy coefficients are given by:
+      !!                    avm = avm0 + avmb
+      !!                    avt = avm0 / (1 + rn_alp*ri)
+      !!                with ri  = N^2 / dz(u)**2
+      !!                         = e3w**2 * rn2/[ mi( dk(ub) )+mj( dk(vb) ) ]
+      !!                    avm0= rn_avmri / (1 + rn_alp*Ri)**nn_ric
+      !!                where ri is the before local Richardson number,
+      !!                rn_avmri is the maximum value reaches by avm and avt 
+      !!                and rn_alp, nn_ric are adjustable parameters.
+      !!                Typical values : rn_alp=5. and nn_ric=2.
+      !!
+      !!      As second step compute Ekman depth from wind stress forcing
+      !!      and apply namelist provided vertical coeff within this depth.
+      !!      The Ekman depth is:
+      !!              Ustar = SQRT(Taum/rho0)
+      !!              ekd= rn_ekmfc * Ustar / f0
+      !!      Large et al. (1994, eq.24) suggest rn_ekmfc=0.7; however, the derivation
+      !!      of the above equation indicates the value is somewhat arbitrary; therefore
+      !!      we allow the freedom to increase or decrease this value, if the
+      !!      Ekman depth estimate appears too shallow or too deep, respectively.
+      !!      Ekd is then limited by rn_mldmin and rn_mldmax provided in the
+      !!      namelist
+      !!        N.B. the mask are required for implicit scheme, and surface
+      !!      and bottom value already set in zdfphy.F90
+      !!
+      !! ** Action  :   avm, avt  mixing coeff (inner domain values only)
+      !!
+      !! References : Pacanowski & Philander 1981, JPO, 1441-1451.
+      !!              PFJ Lermusiaux 2001.
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   kt             ! ocean time-step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdept          ! depth of t-point  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   p_sh2          ! shear production term
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   p_avm, p_avt   ! momentum and tracer Kz (w-points)
+      !!
+      INTEGER  ::   ji, jj, jk                  ! dummy loop indices
+      REAL(wp) ::   zcfRi, zav, zustar, zhek    ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) ::   zh_ekm  ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      !                       !==  avm and avt = F(Richardson number)  ==!
+      DO jk = 2, jpkm1
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1              ! coefficient = F(richardson number) (avm-weighted Ri)
+               zcfRi = 1._wp / (  1._wp + rn_alp * MAX(  0._wp , avm(ji,jj,jk) * rn2(ji,jj,jk) / ( p_sh2(ji,jj,jk) + 1.e-20 ) )  )
+               zav   = rn_avmri * zcfRi**nn_ric
+               !                          ! avm and avt coefficients
+               p_avm(ji,jj,jk) = MAX(  zav         , avmb(jk)  ) * wmask(ji,jj,jk)
+               p_avt(ji,jj,jk) = MAX(  zav * zcfRi , avtb(jk)  ) * wmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+!!gm BUG <<<<====  This param can't work at low latitude 
+!!gm               it provides there much to thick mixed layer ( summer 150m in GYRE configuration !!! )
+      !
+      IF( ln_mldw ) THEN      !==  set a minimum value in the Ekman layer  ==!
+         !
+         DO jj = 2, jpjm1        !* Ekman depth
+            DO ji = 2, jpim1
+               zustar = SQRT( taum(ji,jj) * r1_rau0 )
+               zhek   = rn_ekmfc * zustar / ( ABS( ff_t(ji,jj) ) + rsmall )   ! Ekman depth
+               zh_ekm(ji,jj) = MAX(  rn_mldmin , MIN( zhek , rn_mldmax )  )   ! set allowed range
+            END DO
+         END DO
+         DO jk = 2, jpkm1        !* minimum mixing coeff. within the Ekman layer
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  IF( pdept(ji,jj,jk) < zh_ekm(ji,jj) ) THEN
+                     p_avm(ji,jj,jk) = MAX(  p_avm(ji,jj,jk), rn_wvmix  ) * wmask(ji,jj,jk)
+                     p_avt(ji,jj,jk) = MAX(  p_avt(ji,jj,jk), rn_wtmix  ) * wmask(ji,jj,jk)
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE zdf_ric
+
+
+   SUBROUTINE ric_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE ric_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write TKE file (en) in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain TKE, en is either 
+      !!                set to rn_emin or recomputed 
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   jit, jk    ! dummy loop indices
+      INTEGER ::   id1, id2   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ---------------
+         !           !* Read the restart file
+         IF( ln_rstart ) THEN
+            id1 = iom_varid( numror, 'avt_k', ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'avm_k', ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2 ) > 0 ) THEN         ! restart exists => read it
+               CALL iom_get( numror, jpdom_autoglo, 'avt_k', avt_k, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'avm_k', avm_k, ldxios = lrxios )
+            ENDIF
+         ENDIF
+         !           !* otherwise Kz already set to the background value in zdf_phy_init
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- ric-rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k, ldxios = lwxios)
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         !
+      ENDIF
+      !
+   END SUBROUTINE ric_rst
+
+   !!======================================================================
+END MODULE zdfric
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfsh2.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfsh2.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfsh2.F90	(revision 14097)
@@ -0,0 +1,79 @@
+MODULE zdfsh2
+   !!======================================================================
+   !!                       ***  MODULE  zdfsh2  ***
+   !! Ocean physics:  shear production term of TKE 
+   !!=====================================================================
+   !! History :   -   !  2014-10  (A. Barthelemy, G. Madec)  original code
+   !!   NEMO     4.0  !  2017-04  (G. Madec)  remove u-,v-pts avm
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_sh2       : compute mixing the shear production term of TKE
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! domain: ocean
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_sh2        ! called by zdftke, zdfglf, and zdfric
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_sh2( pub, pvb, pun, pvn, p_avm, p_sh2  ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_sh2  ***
+      !!
+      !! ** Purpose :   Compute the shear production term of a TKE equation
+      !!
+      !! ** Method  : - a stable discretization of this term is linked to the
+      !!                time-space discretization of the vertical diffusion
+      !!                of the OGCM. NEMO uses C-grid, a leap-frog environment 
+      !!                and an implicit computation of vertical mixing term,
+      !!                so the shear production at w-point is given by:
+      !!                   sh2 = mi[   mi(avm) * dk[ub]/e3ub * dk[un]/e3un   ] 
+      !!                       + mj[   mj(avm) * dk[vb]/e3vb * dk[vn]/e3vn   ] 
+      !!                NB: wet-point only horizontal averaging of shear
+      !!
+      !! ** Action  : - p_sh2 shear prod. term at w-point (inner domain only)
+      !!                                                   *****
+      !! References :   Bruchard, OM 2002
+      !! ---------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   pub, pvb, pun, pvn   ! before, now horizontal velocities
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   p_avm                ! vertical eddy viscosity (w-points)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(  out) ::   p_sh2                ! shear production of TKE (w-points)
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop arguments
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsh2u, zsh2v   ! 2D workspace
+      !!--------------------------------------------------------------------
+      !
+      DO jk = 2, jpkm1
+         DO jj = 1, jpjm1        !* 2 x shear production at uw- and vw-points (energy conserving form)
+            DO ji = 1, jpim1
+               zsh2u(ji,jj) = ( p_avm(ji+1,jj,jk) + p_avm(ji,jj,jk) ) &
+                  &         * (   pun(ji,jj,jk-1) -   pun(ji,jj,jk) ) &
+                  &         * (   pub(ji,jj,jk-1) -   pub(ji,jj,jk) ) / ( e3uw_n(ji,jj,jk) * e3uw_b(ji,jj,jk) ) * wumask(ji,jj,jk)
+               zsh2v(ji,jj) = ( p_avm(ji,jj+1,jk) + p_avm(ji,jj,jk) ) &
+                  &         * (   pvn(ji,jj,jk-1) -   pvn(ji,jj,jk) ) &
+                  &         * (   pvb(ji,jj,jk-1) -   pvb(ji,jj,jk) ) / ( e3vw_n(ji,jj,jk) * e3vw_b(ji,jj,jk) ) * wvmask(ji,jj,jk)
+            END DO
+         END DO
+         DO jj = 2, jpjm1        !* shear production at w-point
+            DO ji = 2, jpim1           ! coast mask: =2 at the coast ; =1 otherwise (NB: wmask useless as zsh2 are masked)
+               p_sh2(ji,jj,jk) = 0.25 * (   ( zsh2u(ji-1,jj) + zsh2u(ji,jj) ) * ( 2. - umask(ji-1,jj,jk) * umask(ji,jj,jk) )   &
+                  &                       + ( zsh2v(ji,jj-1) + zsh2v(ji,jj) ) * ( 2. - vmask(ji,jj-1,jk) * vmask(ji,jj,jk) )   )
+            END DO
+         END DO
+      END DO 
+      !
+   END SUBROUTINE zdf_sh2
+
+   !!======================================================================
+END MODULE zdfsh2
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfswm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfswm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdfswm.F90	(revision 14097)
@@ -0,0 +1,97 @@
+MODULE zdfswm
+   !!======================================================================
+   !!                       ***  MODULE  zdfswm  ***
+   !! vertical physics :   surface wave-induced mixing 
+   !!======================================================================
+   !! History :  3.6  !  2014-10  (E. Clementi)  Original code
+   !!            4.0  !  2017-04  (G. Madec)  debug + simplifications
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_swm      : update Kz due to surface wave-induced mixing 
+   !!   zdf_swm_init : initilisation
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain variable
+   USE zdf_oce        ! vertical physics: mixing coefficients
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbcwave        ! wave module
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)  
+   USE lib_mpp        ! distribued memory computing library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC zdf_swm         ! routine called in zdp_phy
+   PUBLIC zdf_swm_init    ! routine called in zdf_phy_init
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE zdf_swm( kt, p_avm, p_avt, p_avs )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE zdf_swm ***
+      !!
+      !! ** Purpose :Compute the swm term (qbv) to be added to
+      !!             vertical viscosity and diffusivity coeffs.  
+      !!
+      !! ** Method  :   Compute the swm term Bv (zqb) and added it to
+      !!               vertical viscosity and diffusivity coefficients
+      !!                   zqb = alpha * A * Us(0) * exp (3 * k * z)
+      !!               where alpha is set here to 1
+      !!             
+      !! ** action  :    avt, avs, avm updated by the surface wave-induced mixing
+      !!                               (inner domain only)
+      !!               
+      !! reference : Qiao et al. GRL, 2004
+      !!---------------------------------------------------------------------
+      INTEGER                    , INTENT(in   ) ::   kt             ! ocean time step
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avm          ! momentum Kz (w-points)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avt, p_avs   ! tracer   Kz (w-points)
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp)::   zcoef, zqb   ! local scalar
+      !!---------------------------------------------------------------------
+      !
+      zcoef = 1._wp * 0.353553_wp
+      DO jk = 2, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               zqb = zcoef * hsw(ji,jj) * tsd2d(ji,jj) * EXP( -3. * wnum(ji,jj) * gdepw_n(ji,jj,jk) ) * wmask(ji,jj,jk)
+               !
+               p_avt(ji,jj,jk) = p_avt(ji,jj,jk) + zqb
+               p_avs(ji,jj,jk) = p_avs(ji,jj,jk) + zqb
+               p_avm(ji,jj,jk) = p_avm(ji,jj,jk) + zqb
+            END DO
+         END DO
+      END DO
+      !
+   END SUBROUTINE zdf_swm
+   
+   
+   SUBROUTINE zdf_swm_init
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE zdf_swm_init ***
+      !!
+      !! ** Purpose :   surface wave-induced mixing initialisation  
+      !!
+      !! ** Method  :   check the availability of surface wave fields
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_swm_init : surface wave-driven mixing'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      IF(  .NOT.ln_wave .OR.   &
+         & .NOT.ln_sdw    )   CALL ctl_stop ( 'zdf_swm_init: ln_zdfswm=T but ln_wave and ln_sdw /= T')
+      !
+   END SUBROUTINE zdf_swm_init
+
+   !!======================================================================
+END MODULE zdfswm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdftke.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdftke.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/ZDF/zdftke.F90	(revision 14097)
@@ -0,0 +1,898 @@
+MODULE zdftke
+   !!======================================================================
+   !!                       ***  MODULE  zdftke  ***
+   !! Ocean physics:  vertical mixing coefficient computed from the tke 
+   !!                 turbulent closure parameterization
+   !!=====================================================================
+   !! History :  OPA  !  1991-03  (b. blanke)  Original code
+   !!            7.0  !  1991-11  (G. Madec)   bug fix
+   !!            7.1  !  1992-10  (G. Madec)   new mixing length and eav
+   !!            7.2  !  1993-03  (M. Guyon)   symetrical conditions
+   !!            7.3  !  1994-08  (G. Madec, M. Imbard)  nn_pdl flag
+   !!            7.5  !  1996-01  (G. Madec)   s-coordinates
+   !!            8.0  !  1997-07  (G. Madec)   lbc
+   !!            8.1  !  1999-01  (E. Stretta) new option for the mixing length
+   !!  NEMO      1.0  !  2002-06  (G. Madec) add tke_init routine
+   !!             -   !  2004-10  (C. Ethe )  1D configuration
+   !!            2.0  !  2006-07  (S. Masson)  distributed restart using iom
+   !!            3.0  !  2008-05  (C. Ethe,  G.Madec) : update TKE physics:
+   !!                 !           - tke penetration (wind steering)
+   !!                 !           - suface condition for tke & mixing length
+   !!                 !           - Langmuir cells
+   !!             -   !  2008-05  (J.-M. Molines, G. Madec)  2D form of avtb
+   !!             -   !  2008-06  (G. Madec)  style + DOCTOR name for namelist parameters
+   !!             -   !  2008-12  (G. Reffray) stable discretization of the production term 
+   !!            3.2  !  2009-06  (G. Madec, S. Masson) TKE restart compatible with key_cpl 
+   !!                 !                                + cleaning of the parameters + bugs correction
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.6  !  2014-11  (P. Mathiot) add ice shelf capability
+   !!            4.0  !  2017-04  (G. Madec)  remove CPP ddm key & avm at t-point only 
+   !!             -   !  2017-05  (G. Madec)  add top/bottom friction as boundary condition
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_tke       : update momentum and tracer Kz from a tke scheme
+   !!   tke_tke       : tke time stepping: update tke at now time step (en)
+   !!   tke_avn       : compute mixing length scale and deduce avm and avt
+   !!   zdf_tke_init  : initialization, namelist read, and parameters control
+   !!   tke_rst       : read/write tke restart in ocean restart file
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean: dynamics and active tracers variables
+   USE phycst         ! physical constants
+   USE dom_oce        ! domain: ocean
+   USE domvvl         ! domain: variable volume layer
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdfdrg         ! vertical physics: top/bottom drag coef.
+   USE zdfmxl         ! vertical physics: mixed layer
+   !
+#if defined key_si3
+   USE ice, ONLY: hm_i, h_i
+#endif
+#if defined key_cice
+   USE sbc_ice, ONLY: h_i
+#endif
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl         ! Print control
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_tke        ! routine called in step module
+   PUBLIC   zdf_tke_init   ! routine called in opa module
+   PUBLIC   tke_rst        ! routine called in step module
+
+   !                      !!** Namelist  namzdf_tke  **
+   LOGICAL  ::   ln_mxl0   ! mixing length scale surface value as function of wind stress or not
+   INTEGER  ::   nn_mxlice ! type of scaling under sea-ice (=0/1/2/3)
+   REAL(wp) ::   rn_mxlice ! ice thickness value when scaling under sea-ice
+   INTEGER  ::   nn_mxl    ! type of mixing length (=0/1/2/3)
+   REAL(wp) ::   rn_mxl0   ! surface  min value of mixing length (kappa*z_o=0.4*0.1 m)  [m]
+   INTEGER  ::   nn_pdl    ! Prandtl number or not (ratio avt/avm) (=0/1)
+   REAL(wp) ::   rn_ediff  ! coefficient for avt: avt=rn_ediff*mxl*sqrt(e)
+   REAL(wp) ::   rn_ediss  ! coefficient of the Kolmogoroff dissipation 
+   REAL(wp) ::   rn_ebb    ! coefficient of the surface input of tke
+   REAL(wp) ::   rn_emin   ! minimum value of tke           [m2/s2]
+   REAL(wp) ::   rn_emin0  ! surface minimum value of tke   [m2/s2]
+   REAL(wp) ::   rn_bshear ! background shear (>0) currently a numerical threshold (do not change it)
+   INTEGER  ::   nn_etau   ! type of depth penetration of surface tke (=0/1/2/3)
+   INTEGER  ::      nn_htau   ! type of tke profile of penetration (=0/1)
+   REAL(wp) ::      rn_efr    ! fraction of TKE surface value which penetrates in the ocean
+   LOGICAL  ::   ln_lc     ! Langmuir cells (LC) as a source term of TKE or not
+   REAL(wp) ::      rn_lc     ! coef to compute vertical velocity of Langmuir cells
+   INTEGER  ::   nn_eice   ! attenutaion of langmuir & surface wave breaking under ice (=0/1/2/3)   
+
+   REAL(wp) ::   ri_cri    ! critic Richardson number (deduced from rn_ediff and rn_ediss values)
+   REAL(wp) ::   rmxl_min  ! minimum mixing length value (deduced from rn_ediff and rn_emin values)  [m]
+   REAL(wp) ::   rhftau_add = 1.e-3_wp     ! add offset   applied to HF part of taum  (nn_etau=3)
+   REAL(wp) ::   rhftau_scl = 1.0_wp       ! scale factor applied to HF part of taum  (nn_etau=3)
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   htau    ! depth of tke penetration (nn_htau)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dissl   ! now mixing lenght of dissipation
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   apdlr   ! now mixing lenght of dissipation
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_tke_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_tke_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( htau(jpi,jpj) , dissl(jpi,jpj,jpk) , apdlr(jpi,jpj,jpk) ,   STAT= zdf_tke_alloc )
+      !
+      CALL mpp_sum ( 'zdftke', zdf_tke_alloc )
+      IF( zdf_tke_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_tke_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION zdf_tke_alloc
+
+
+   SUBROUTINE zdf_tke( kt, p_sh2, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zdf_tke  ***
+      !!
+      !! ** Purpose :   Compute the vertical eddy viscosity and diffusivity
+      !!              coefficients using a turbulent closure scheme (TKE).
+      !!
+      !! ** Method  :   The time evolution of the turbulent kinetic energy (tke)
+      !!              is computed from a prognostic equation :
+      !!         d(en)/dt = avm (d(u)/dz)**2             ! shear production
+      !!                  + d( avm d(en)/dz )/dz         ! diffusion of tke
+      !!                  + avt N^2                      ! stratif. destruc.
+      !!                  - rn_ediss / emxl en**(2/3)    ! Kolmogoroff dissipation
+      !!      with the boundary conditions:
+      !!         surface: en = max( rn_emin0, rn_ebb * taum )
+      !!         bottom : en = rn_emin
+      !!      The associated critical Richardson number is: ri_cri = 2/(2+rn_ediss/rn_ediff) 
+      !!
+      !!        The now Turbulent kinetic energy is computed using the following 
+      !!      time stepping: implicit for vertical diffusion term, linearized semi
+      !!      implicit for kolmogoroff dissipation term, and explicit forward for 
+      !!      both buoyancy and shear production terms. Therefore a tridiagonal 
+      !!      linear system is solved. Note that buoyancy and shear terms are
+      !!      discretized in a energy conserving form (Bruchard 2002).
+      !!
+      !!        The dissipative and mixing length scale are computed from en and
+      !!      the stratification (see tke_avn)
+      !!
+      !!        The now vertical eddy vicosity and diffusivity coefficients are
+      !!      given by: 
+      !!              avm = max( avtb, rn_ediff * zmxlm * en^1/2 )
+      !!              avt = max( avmb, pdl * avm                 )  
+      !!              eav = max( avmb, avm )
+      !!      where pdl, the inverse of the Prandtl number is 1 if nn_pdl=0 and
+      !!      given by an empirical funtion of the localRichardson number if nn_pdl=1 
+      !!
+      !! ** Action  :   compute en (now turbulent kinetic energy)
+      !!                update avt, avm (before vertical eddy coef.)
+      !!
+      !! References : Gaspar et al., JGR, 1990,
+      !!              Blanke and Delecluse, JPO, 1991
+      !!              Mellor and Blumberg, JPO 2004
+      !!              Axell, JGR, 2002
+      !!              Bruchard OM 2002
+      !!----------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   kt             ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   p_sh2          ! shear production term
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   p_avm, p_avt   !  momentum and tracer Kz (w-points)
+      !!----------------------------------------------------------------------
+      !
+      CALL tke_tke( gdepw_n, e3t_n, e3w_n, p_sh2, p_avm, p_avt )   ! now tke (en)
+      !
+      CALL tke_avn( gdepw_n, e3t_n, e3w_n,        p_avm, p_avt )   ! now avt, avm, dissl
+      !
+  END SUBROUTINE zdf_tke
+
+
+   SUBROUTINE tke_tke( pdepw, p_e3t, p_e3w, p_sh2, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tke_tke  ***
+      !!
+      !! ** Purpose :   Compute the now Turbulente Kinetic Energy (TKE)
+      !!
+      !! ** Method  : - TKE surface boundary condition
+      !!              - source term due to Langmuir cells (Axell JGR 2002) (ln_lc=T)
+      !!              - source term due to shear (= Kz dz[Ub] * dz[Un] )
+      !!              - Now TKE : resolution of the TKE equation by inverting
+      !!                a tridiagonal linear system by a "methode de chasse"
+      !!              - increase TKE due to surface and internal wave breaking
+      !!             NB: when sea-ice is present, both LC parameterization 
+      !!                 and TKE penetration are turned off when the ice fraction 
+      !!                 is smaller than 0.25 
+      !!
+      !! ** Action  : - en : now turbulent kinetic energy)
+      !! ---------------------------------------------------------------------
+      USE zdf_oce , ONLY : en   ! ocean vertical physics
+      !!
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   pdepw          ! depth of w-points
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   p_e3t, p_e3w   ! level thickness (t- & w-points)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   p_sh2          ! shear production term
+      REAL(wp), DIMENSION(:,:,:) , INTENT(in   ) ::   p_avm, p_avt   ! vertical eddy viscosity & diffusivity (w-points)
+      !
+      INTEGER ::   ji, jj, jk                  ! dummy loop arguments
+      REAL(wp) ::   zetop, zebot, zmsku, zmskv ! local scalars
+      REAL(wp) ::   zrhoa  = 1.22              ! Air density kg/m3
+      REAL(wp) ::   zcdrag = 1.5e-3            ! drag coefficient
+      REAL(wp) ::   zbbrau, zbbirau, zri       ! local scalars
+      REAL(wp) ::   zfact1, zfact2, zfact3     !   -      -
+      REAL(wp) ::   ztx2  , zty2  , zcof       !   -      -
+      REAL(wp) ::   ztau  , zdif               !   -      -
+      REAL(wp) ::   zus   , zwlc  , zind       !   -      -
+      REAL(wp) ::   zzd_up, zzd_lw             !   -      -
+      INTEGER , DIMENSION(jpi,jpj)     ::   imlc
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zice_fra, zhlc, zus3
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zpelc, zdiag, zd_up, zd_lw
+      !!--------------------------------------------------------------------
+      !
+      zbbrau  =  rn_ebb / rau0       ! Local constant initialisation
+      zbbirau =  3.75_wp / rau0
+      zfact1  = -0.5_wp * rdt 
+      zfact2  =  1.5_wp * rdt * rn_ediss
+      zfact3  =  0.5_wp       * rn_ediss
+      !
+      ! ice fraction considered for attenuation of langmuir & wave breaking
+      SELECT CASE ( nn_eice )
+      CASE( 0 )   ;   zice_fra(:,:) = 0._wp
+      CASE( 1 )   ;   zice_fra(:,:) =        TANH( fr_i(:,:) * 10._wp )
+      CASE( 2 )   ;   zice_fra(:,:) =              fr_i(:,:)
+      CASE( 3 )   ;   zice_fra(:,:) = MIN( 4._wp * fr_i(:,:) , 1._wp )
+      END SELECT
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Surface/top/bottom boundary condition on tke
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !
+      DO jj = 2, jpjm1            ! en(1)   = rn_ebb taum / rau0  (min value rn_emin0)
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+!! clem: this should be the right formulation but it makes the model unstable unless drags are calculated implicitly
+!!       one way around would be to increase zbbirau 
+!!          en(ji,jj,1) = MAX( rn_emin0, ( ( 1._wp - fr_i(ji,jj) ) * zbbrau + &
+!!             &                                     fr_i(ji,jj)   * zbbirau ) * taum(ji,jj) ) * tmask(ji,jj,1)
+            en(ji,jj,1) = MAX( rn_emin0, zbbrau * taum(ji,jj) ) * tmask(ji,jj,1)
+         END DO
+      END DO
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Bottom boundary condition on tke
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !
+      !   en(bot)   = (ebb0/rau0)*0.5*sqrt(u_botfr^2+v_botfr^2) (min value rn_emin)
+      ! where ebb0 does not includes surface wave enhancement (i.e. ebb0=3.75)
+      ! Note that stress averaged is done using an wet-only calculation of u and v at t-point like in zdfsh2
+      !
+      IF( .NOT.ln_drg_OFF ) THEN    !== friction used as top/bottom boundary condition on TKE
+         !
+         DO jj = 2, jpjm1              ! bottom friction
+            DO ji = fs_2, fs_jpim1     ! vector opt.
+               zmsku = ( 2. - umask(ji-1,jj,mbkt(ji,jj)) * umask(ji,jj,mbkt(ji,jj)) )
+               zmskv = ( 2. - vmask(ji,jj-1,mbkt(ji,jj)) * vmask(ji,jj,mbkt(ji,jj)) )
+               !                       ! where 0.001875 = (rn_ebb0/rau0) * 0.5 = 3.75*0.5/1000. (CAUTION CdU<0)
+               zebot = - 0.001875_wp * rCdU_bot(ji,jj) * SQRT(  ( zmsku*( ub(ji,jj,mbkt(ji,jj))+ub(ji-1,jj,mbkt(ji,jj)) ) )**2  &
+                  &                                           + ( zmskv*( vb(ji,jj,mbkt(ji,jj))+vb(ji,jj-1,mbkt(ji,jj)) ) )**2  )
+               en(ji,jj,mbkt(ji,jj)+1) = MAX( zebot, rn_emin ) * ssmask(ji,jj)
+            END DO
+         END DO
+         IF( ln_isfcav ) THEN       ! top friction
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zmsku = ( 2. - umask(ji-1,jj,mikt(ji,jj)) * umask(ji,jj,mikt(ji,jj)) )
+                  zmskv = ( 2. - vmask(ji,jj-1,mikt(ji,jj)) * vmask(ji,jj,mikt(ji,jj)) )
+                  !                             ! where 0.001875 = (rn_ebb0/rau0) * 0.5 = 3.75*0.5/1000.  (CAUTION CdU<0)
+                  zetop = - 0.001875_wp * rCdU_top(ji,jj) * SQRT(  ( zmsku*( ub(ji,jj,mikt(ji,jj))+ub(ji-1,jj,mikt(ji,jj)) ) )**2  &
+                     &                                           + ( zmskv*( vb(ji,jj,mikt(ji,jj))+vb(ji,jj-1,mikt(ji,jj)) ) )**2  )
+                  en(ji,jj,mikt(ji,jj)) = en(ji,jj,1)           * tmask(ji,jj,1) &     
+                     &                  + MAX( zetop, rn_emin ) * (1._wp - tmask(ji,jj,1)) * ssmask(ji,jj)
+               END DO
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_lc ) THEN      !  Langmuir circulation source term added to tke   !   (Axell JGR 2002)
+         !                  !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+         !
+         !                        !* total energy produce by LC : cumulative sum over jk
+         zpelc(:,:,1) =  MAX( rn2b(:,:,1), 0._wp ) * pdepw(:,:,1) * p_e3w(:,:,1)
+         DO jk = 2, jpk
+            zpelc(:,:,jk)  = zpelc(:,:,jk-1) + MAX( rn2b(:,:,jk), 0._wp ) * pdepw(:,:,jk) * p_e3w(:,:,jk)
+         END DO
+         !                        !* finite Langmuir Circulation depth
+         zcof = 0.5 * 0.016 * 0.016 / ( zrhoa * zcdrag )
+         imlc(:,:) = mbkt(:,:) + 1       ! Initialization to the number of w ocean point (=2 over land)
+         DO jk = jpkm1, 2, -1
+            DO jj = 1, jpj               ! Last w-level at which zpelc>=0.5*us*us 
+               DO ji = 1, jpi            !      with us=0.016*wind(starting from jpk-1)
+                  zus  = zcof * taum(ji,jj)
+                  IF( zpelc(ji,jj,jk) > zus )   imlc(ji,jj) = jk
+               END DO
+            END DO
+         END DO
+         !                               ! finite LC depth
+         DO jj = 1, jpj 
+            DO ji = 1, jpi
+               zhlc(ji,jj) = pdepw(ji,jj,imlc(ji,jj))
+            END DO
+         END DO
+         zcof = 0.016 / SQRT( zrhoa * zcdrag )
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zus  = zcof * SQRT( taum(ji,jj) )           ! Stokes drift
+               zus3(ji,jj) = MAX( 0._wp, 1._wp - zice_fra(ji,jj) ) * zus * zus * zus * tmask(ji,jj,1) ! zus > 0. ok
+            END DO
+         END DO         
+         DO jk = 2, jpkm1         !* TKE Langmuir circulation source term added to en
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  IF ( zus3(ji,jj) /= 0._wp ) THEN               
+                     ! vertical velocity due to LC   
+                     IF ( pdepw(ji,jj,jk) - zhlc(ji,jj) < 0 .AND. wmask(ji,jj,jk) /= 0. ) THEN
+                        !                                           ! vertical velocity due to LC
+                        zwlc = rn_lc * SIN( rpi * pdepw(ji,jj,jk) / zhlc(ji,jj) )
+                        !                                           ! TKE Langmuir circulation source term
+                        en(ji,jj,jk) = en(ji,jj,jk) + rdt * zus3(ji,jj) * ( zwlc * zwlc * zwlc ) / zhlc(ji,jj)
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Now Turbulent kinetic energy (output in en)
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     ! Resolution of a tridiagonal linear system by a "methode de chasse"
+      !                     ! computation from level 2 to jpkm1  (e(1) already computed and e(jpk)=0 ).
+      !                     ! zdiag : diagonal zd_up : upper diagonal zd_lw : lower diagonal
+      !
+      IF( nn_pdl == 1 ) THEN      !* Prandtl number = F( Ri )
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  !                             ! local Richardson number
+                  zri = MAX( rn2b(ji,jj,jk), 0._wp ) * p_avm(ji,jj,jk) / ( p_sh2(ji,jj,jk) + rn_bshear )
+                  !                             ! inverse of Prandtl number
+                  apdlr(ji,jj,jk) = MAX(  0.1_wp,  ri_cri / MAX( ri_cri , zri )  )
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !         
+      DO jk = 2, jpkm1           !* Matrix and right hand side in en
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zcof   = zfact1 * tmask(ji,jj,jk)
+               !                                   ! A minimum of 2.e-5 m2/s is imposed on TKE vertical
+               !                                   ! eddy coefficient (ensure numerical stability)
+               zzd_up = zcof * MAX(  p_avm(ji,jj,jk+1) + p_avm(ji,jj,jk  ) , 2.e-5_wp  )   &  ! upper diagonal
+                  &          /    (  p_e3t(ji,jj,jk  ) * p_e3w(ji,jj,jk  )  )
+               zzd_lw = zcof * MAX(  p_avm(ji,jj,jk  ) + p_avm(ji,jj,jk-1) , 2.e-5_wp  )   &  ! lower diagonal
+                  &          /    (  p_e3t(ji,jj,jk-1) * p_e3w(ji,jj,jk  )  )
+               !
+               zd_up(ji,jj,jk) = zzd_up            ! Matrix (zdiag, zd_up, zd_lw)
+               zd_lw(ji,jj,jk) = zzd_lw
+               zdiag(ji,jj,jk) = 1._wp - zzd_lw - zzd_up + zfact2 * dissl(ji,jj,jk) * wmask(ji,jj,jk)
+               !
+               !                                   ! right hand side in en
+               en(ji,jj,jk) = en(ji,jj,jk) + rdt * (  p_sh2(ji,jj,jk)                          &   ! shear
+                  &                                 - p_avt(ji,jj,jk) * rn2(ji,jj,jk)          &   ! stratification
+                  &                                 + zfact3 * dissl(ji,jj,jk) * en(ji,jj,jk)  &   ! dissipation
+                  &                                ) * wmask(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.
+               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.
+               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.
+            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.
+               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.
+               en(ji,jj,jk) = MAX( en(ji,jj,jk), rn_emin ) * wmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      !                            !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                            !  TKE due to surface and internal wave breaking
+      !                            !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!!gm BUG : in the exp  remove the depth of ssh !!!
+!!gm       i.e. use gde3w in argument (pdepw)
+      
+      
+      IF( nn_etau == 1 ) THEN           !* penetration below the mixed layer (rn_efr fraction)
+         DO jk = 2, jpkm1                       ! nn_eice=0 : ON below sea-ice ; nn_eice>0 : partly OFF
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  en(ji,jj,jk) = en(ji,jj,jk) + rn_efr * en(ji,jj,1) * EXP( -pdepw(ji,jj,jk) / htau(ji,jj) )   &
+                     &                                 * MAX( 0._wp, 1._wp - zice_fra(ji,jj) ) * wmask(ji,jj,jk) * tmask(ji,jj,1)
+               END DO
+            END DO
+         END DO
+      ELSEIF( nn_etau == 2 ) THEN       !* act only at the base of the mixed layer (jk=nmln)  (rn_efr fraction)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               jk = nmln(ji,jj)
+               en(ji,jj,jk) = en(ji,jj,jk) + rn_efr * en(ji,jj,1) * EXP( -pdepw(ji,jj,jk) / htau(ji,jj) )   &
+                  &                                 * MAX( 0._wp, 1._wp - zice_fra(ji,jj) ) * wmask(ji,jj,jk) * tmask(ji,jj,1)
+            END DO
+         END DO
+      ELSEIF( nn_etau == 3 ) THEN       !* penetration belox the mixed layer (HF variability)
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  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 ) * 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( -pdepw(ji,jj,jk) / htau(ji,jj) )   &
+                     &                                 * MAX( 0._wp, 1._wp - zice_fra(ji,jj) ) * wmask(ji,jj,jk) * tmask(ji,jj,1)
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE tke_tke
+
+
+   SUBROUTINE tke_avn( pdepw, p_e3t, p_e3w, p_avm, p_avt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tke_avn  ***
+      !!
+      !! ** Purpose :   Compute the vertical eddy viscosity and diffusivity
+      !!
+      !! ** Method  :   At this stage, en, the now TKE, is known (computed in 
+      !!              the tke_tke routine). First, the now mixing lenth is 
+      !!      computed from en and the strafification (N^2), then the mixings
+      !!      coefficients are computed.
+      !!              - Mixing length : a first evaluation of the mixing lengh
+      !!      scales is:
+      !!                      mxl = sqrt(2*en) / N  
+      !!      where N is the brunt-vaisala frequency, with a minimum value set
+      !!      to rmxl_min (rn_mxl0) in the interior (surface) ocean.
+      !!        The mixing and dissipative length scale are bound as follow : 
+      !!         nn_mxl=0 : mxl bounded by the distance to surface and bottom.
+      !!                        zmxld = zmxlm = mxl
+      !!         nn_mxl=1 : mxl bounded by the e3w and zmxld = zmxlm = mxl
+      !!         nn_mxl=2 : mxl bounded such that the vertical derivative of mxl is 
+      !!                    less than 1 (|d/dz(mxl)|<1) and zmxld = zmxlm = mxl
+      !!         nn_mxl=3 : mxl is bounded from the surface to the bottom usings
+      !!                    |d/dz(xml)|<1 to obtain lup, and from the bottom to 
+      !!                    the surface to obtain ldown. the resulting length 
+      !!                    scales are:
+      !!                        zmxld = sqrt( lup * ldown ) 
+      !!                        zmxlm = min ( lup , ldown )
+      !!              - Vertical eddy viscosity and diffusivity:
+      !!                      avm = max( avtb, rn_ediff * zmxlm * en^1/2 )
+      !!                      avt = max( avmb, pdlr * avm )  
+      !!      with pdlr=1 if nn_pdl=0, pdlr=1/pdl=F(Ri) otherwise.
+      !!
+      !! ** Action  : - avt, avm : now vertical eddy diffusivity and viscosity (w-point)
+      !!----------------------------------------------------------------------
+      USE zdf_oce , ONLY : en, avtb, avmb, avtb_2d   ! ocean vertical physics
+      !!
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdepw          ! depth (w-points)
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   p_e3t, p_e3w   ! level thickness (t- & w-points)
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   p_avm, p_avt   ! vertical eddy viscosity & diffusivity (w-points)
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zrn2, zraug, zcoef, zav   ! local scalars
+      REAL(wp) ::   zdku,   zdkv, zsqen       !   -      -
+      REAL(wp) ::   zemxl, zemlm, zemlp, zmaxice       !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zmxlm, zmxld   ! 3D workspace
+      !!--------------------------------------------------------------------
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Mixing length
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !
+      !                     !* Buoyancy length scale: l=sqrt(2*e/n**2)
+      !
+      ! initialisation of interior minimum value (avoid a 2d loop with mikt)
+      zmxlm(:,:,:)  = rmxl_min    
+      zmxld(:,:,:)  = rmxl_min
+      ! 
+      IF( ln_mxl0 ) THEN            ! surface mixing length = F(stress) : l=vkarmn*2.e5*taum/(rau0*g)
+         !
+         zraug = vkarmn * 2.e5_wp / ( rau0 * grav )
+#if ! defined key_si3 && ! defined key_cice
+         DO jj = 2, jpjm1                     ! No sea-ice
+            DO ji = fs_2, fs_jpim1
+               zmxlm(ji,jj,1) =  zraug * taum(ji,jj) * tmask(ji,jj,1)
+            END DO
+         END DO
+#else
+
+         SELECT CASE( nn_mxlice )             ! Type of scaling under sea-ice
+         !
+         CASE( 0 )                      ! No scaling under sea-ice
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zmxlm(ji,jj,1) = zraug * taum(ji,jj) * tmask(ji,jj,1)
+               END DO
+            END DO
+            !
+         CASE( 1 )                      ! scaling with constant sea-ice thickness
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zmxlm(ji,jj,1) =  ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                          fr_i(ji,jj)   * rn_mxlice           ) * tmask(ji,jj,1)
+               END DO
+            END DO
+            !
+         CASE( 2 )                      ! scaling with mean sea-ice thickness
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+#if defined key_si3
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * hm_i(ji,jj) * 2._wp ) * tmask(ji,jj,1)
+#elif defined key_cice
+                  zmaxice = MAXVAL( h_i(ji,jj,:) )
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
+#endif
+               END DO
+            END DO
+            !
+         CASE( 3 )                      ! scaling with max sea-ice thickness
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zmaxice = MAXVAL( h_i(ji,jj,:) )
+                  zmxlm(ji,jj,1) = ( ( 1._wp - fr_i(ji,jj) ) * zraug * taum(ji,jj) + &
+                     &                         fr_i(ji,jj)   * zmaxice             ) * tmask(ji,jj,1)
+               END DO
+            END DO
+            !
+         END SELECT
+#endif
+         !
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               zmxlm(ji,jj,1) = MAX( rn_mxl0, zmxlm(ji,jj,1) )
+            END DO
+         END DO
+         !
+      ELSE
+         zmxlm(:,:,1) = rn_mxl0
+      ENDIF
+      !
+      DO jk = 2, jpkm1              ! interior value : l=sqrt(2*e/n^2)
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zrn2 = MAX( rn2(ji,jj,jk), rsmall )
+               zmxlm(ji,jj,jk) = MAX(  rmxl_min,  SQRT( 2._wp * en(ji,jj,jk) / zrn2 )  )
+            END DO
+         END DO
+      END DO
+      !
+      !                     !* Physical limits for the mixing length
+      !
+      zmxld(:,:, 1 ) = zmxlm(:,:,1)   ! surface set to the minimum value 
+      zmxld(:,:,jpk) = rmxl_min       ! last level  set to the minimum value
+      !
+      SELECT CASE ( nn_mxl )
+      !
+ !!gm Not sure of that coding for ISF....
+      ! where wmask = 0 set zmxlm == p_e3w
+      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( pdepw(ji,jj,jk) - pdepw(ji,jj,mikt(ji,jj)), zmxlm(ji,jj,jk),   &
+                  &            pdepw(ji,jj,mbkt(ji,jj)+1) - pdepw(ji,jj,jk) )
+                  ! wmask prevent zmxlm = 0 if jk = mikt(ji,jj)
+                  zmxlm(ji,jj,jk) = zemxl * wmask(ji,jj,jk) + MIN( zmxlm(ji,jj,jk) , p_e3w(ji,jj,jk) ) * (1 - wmask(ji,jj,jk))
+                  zmxld(ji,jj,jk) = zemxl * wmask(ji,jj,jk) + MIN( zmxlm(ji,jj,jk) , p_e3w(ji,jj,jk) ) * (1 - wmask(ji,jj,jk))
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 1 )           ! bounded by the vertical scale factor
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zemxl = MIN( p_e3w(ji,jj,jk), zmxlm(ji,jj,jk) )
+                  zmxlm(ji,jj,jk) = zemxl
+                  zmxld(ji,jj,jk) = zemxl
+               END DO
+            END DO
+         END DO
+         !
+      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.
+                  zmxlm(ji,jj,jk) = MIN( zmxlm(ji,jj,jk-1) + p_e3t(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.
+                  zemxl = MIN( zmxlm(ji,jj,jk+1) + p_e3t(ji,jj,jk+1), zmxlm(ji,jj,jk) )
+                  zmxlm(ji,jj,jk) = zemxl
+                  zmxld(ji,jj,jk) = zemxl
+               END DO
+            END DO
+         END DO
+         !
+      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.
+                  zmxld(ji,jj,jk) = MIN( zmxld(ji,jj,jk-1) + p_e3t(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.
+                  zmxlm(ji,jj,jk) = MIN( zmxlm(ji,jj,jk+1) + p_e3t(ji,jj,jk+1), zmxlm(ji,jj,jk) )
+               END DO
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zemlm = MIN ( zmxld(ji,jj,jk),  zmxlm(ji,jj,jk) )
+                  zemlp = SQRT( zmxld(ji,jj,jk) * zmxlm(ji,jj,jk) )
+                  zmxlm(ji,jj,jk) = zemlm
+                  zmxld(ji,jj,jk) = zemlp
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !                     !  Vertical eddy viscosity and diffusivity  (avm and avt)
+      !                     !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      DO jk = 1, jpkm1            !* vertical eddy viscosity & diffivity at w-points
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zsqen = SQRT( en(ji,jj,jk) )
+               zav   = rn_ediff * zmxlm(ji,jj,jk) * zsqen
+               p_avm(ji,jj,jk) = MAX( zav,                  avmb(jk) ) * wmask(ji,jj,jk)
+               p_avt(ji,jj,jk) = MAX( zav, avtb_2d(ji,jj) * avtb(jk) ) * wmask(ji,jj,jk)
+               dissl(ji,jj,jk) = zsqen / zmxld(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      !
+      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.
+                  p_avt(ji,jj,jk)   = MAX( apdlr(ji,jj,jk) * p_avt(ji,jj,jk), avtb_2d(ji,jj) * avtb(jk) ) * wmask(ji,jj,jk)
+              END DO
+            END DO
+         END DO
+      ENDIF
+      !
+      IF(ln_ctl) THEN
+         CALL prt_ctl( tab3d_1=en   , clinfo1=' tke  - e: ', tab3d_2=p_avt, clinfo2=' t: ', kdim=jpk)
+         CALL prt_ctl( tab3d_1=p_avm, clinfo1=' tke  - m: ', kdim=jpk )
+      ENDIF
+      !
+   END SUBROUTINE tke_avn
+
+
+   SUBROUTINE zdf_tke_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_tke_init  ***
+      !!                     
+      !! ** Purpose :   Initialization of the vertical eddy diffivity and 
+      !!              viscosity when using a tke turbulent closure scheme
+      !!
+      !! ** Method  :   Read the namzdf_tke namelist and check the parameters
+      !!              called at the first timestep (nit000)
+      !!
+      !! ** input   :   Namlist namzdf_tke
+      !!
+      !! ** Action  :   Increase by 1 the nstop flag is setting problem encounter
+      !!----------------------------------------------------------------------
+      USE zdf_oce , ONLY : ln_zdfiwm   ! Internal Wave Mixing flag
+      !!
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      INTEGER ::   ios
+      !!
+      NAMELIST/namzdf_tke/ rn_ediff, rn_ediss , rn_ebb   , rn_emin  ,  &
+         &                 rn_emin0, rn_bshear, nn_mxl   , ln_mxl0  ,  &
+         &                 rn_mxl0 , nn_mxlice, rn_mxlice,             &
+         &                 nn_pdl  , ln_lc    , rn_lc,                 &
+         &                 nn_etau , nn_htau  , rn_efr   , nn_eice  
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_tke in reference namelist : Turbulent Kinetic Energy
+      READ  ( numnam_ref, namzdf_tke, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namzdf_tke in reference namelist' )
+
+      REWIND( numnam_cfg )              ! Namelist namzdf_tke in configuration namelist : Turbulent Kinetic Energy
+      READ  ( numnam_cfg, namzdf_tke, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namzdf_tke in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_tke )
+      !
+      ri_cri   = 2._wp    / ( 2._wp + rn_ediss / rn_ediff )   ! resulting critical Richardson number
+      !
+      IF(lwp) THEN                    !* Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_tke_init : tke turbulent closure scheme - initialisation'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_tke : set tke mixing parameters'
+         WRITE(numout,*) '      coef. to compute avt                        rn_ediff  = ', rn_ediff
+         WRITE(numout,*) '      Kolmogoroff dissipation coef.               rn_ediss  = ', rn_ediss
+         WRITE(numout,*) '      tke surface input coef.                     rn_ebb    = ', rn_ebb
+         WRITE(numout,*) '      minimum value of tke                        rn_emin   = ', rn_emin
+         WRITE(numout,*) '      surface minimum value of tke                rn_emin0  = ', rn_emin0
+         WRITE(numout,*) '      prandl number flag                          nn_pdl    = ', nn_pdl
+         WRITE(numout,*) '      background shear (>0)                       rn_bshear = ', rn_bshear
+         WRITE(numout,*) '      mixing length type                          nn_mxl    = ', nn_mxl
+         WRITE(numout,*) '         surface mixing length = F(stress) or not    ln_mxl0   = ', ln_mxl0
+         WRITE(numout,*) '         surface  mixing length minimum value        rn_mxl0   = ', rn_mxl0
+         IF( ln_mxl0 ) THEN
+            WRITE(numout,*) '      type of scaling under sea-ice               nn_mxlice = ', nn_mxlice
+            IF( nn_mxlice == 1 ) &
+            WRITE(numout,*) '      ice thickness when scaling under sea-ice    rn_mxlice = ', rn_mxlice
+            SELECT CASE( nn_mxlice )             ! Type of scaling under sea-ice
+            CASE( 0 )   ;   WRITE(numout,*) '   ==>>>   No scaling under sea-ice'
+            CASE( 1 )   ;   WRITE(numout,*) '   ==>>>   scaling with constant sea-ice thickness'
+            CASE( 2 )   ;   WRITE(numout,*) '   ==>>>   scaling with mean sea-ice thickness'
+            CASE( 3 )   ;   WRITE(numout,*) '   ==>>>   scaling with max sea-ice thickness'
+            CASE DEFAULT
+               CALL ctl_stop( 'zdf_tke_init: wrong value for nn_mxlice, should be 0,1,2,3 or 4')
+            END SELECT
+         ENDIF
+         WRITE(numout,*) '      Langmuir cells parametrization              ln_lc     = ', ln_lc
+         WRITE(numout,*) '         coef to compute vertical velocity of LC     rn_lc  = ', rn_lc
+         WRITE(numout,*) '      test param. to add tke induced by wind      nn_etau   = ', nn_etau
+         WRITE(numout,*) '          type of tke penetration profile            nn_htau   = ', nn_htau
+         WRITE(numout,*) '          fraction of TKE that penetrates            rn_efr    = ', rn_efr
+         WRITE(numout,*) '      langmuir & surface wave breaking under ice  nn_eice = ', nn_eice
+         SELECT CASE( nn_eice ) 
+         CASE( 0 )   ;   WRITE(numout,*) '   ==>>>   no impact of ice cover on langmuir & surface wave breaking'
+         CASE( 1 )   ;   WRITE(numout,*) '   ==>>>   weigthed by 1-TANH( fr_i(:,:) * 10 )'
+         CASE( 2 )   ;   WRITE(numout,*) '   ==>>>   weighted by 1-fr_i(:,:)'
+         CASE( 3 )   ;   WRITE(numout,*) '   ==>>>   weighted by 1-MIN( 1, 4 * fr_i(:,:) )'
+         CASE DEFAULT
+            CALL ctl_stop( 'zdf_tke_init: wrong value for nn_eice, should be 0,1,2, or 3')
+         END SELECT      
+         IF( .NOT.ln_drg_OFF ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   Namelist namdrg_top/_bot:   used values:'
+            WRITE(numout,*) '      top    ocean cavity roughness (m)          rn_z0(_top)= ', r_z0_top
+            WRITE(numout,*) '      Bottom seafloor     roughness (m)          rn_z0(_bot)= ', r_z0_bot
+         ENDIF
+         WRITE(numout,*)
+         WRITE(numout,*) '   ==>>>   critical Richardson nb with your parameters  ri_cri = ', ri_cri
+         WRITE(numout,*)
+      ENDIF
+      !
+      IF( ln_zdfiwm ) THEN          ! Internal wave-driven mixing
+         rn_emin  = 1.e-10_wp             ! specific values of rn_emin & rmxl_min are used
+         rmxl_min = 1.e-03_wp             ! associated avt minimum = molecular salt diffusivity (10^-9 m2/s)
+         IF(lwp) WRITE(numout,*) '   ==>>>   Internal wave-driven mixing case:   force   rn_emin = 1.e-10 and rmxl_min = 1.e-3'
+      ELSE                          ! standard case : associated avt minimum = molecular viscosity (10^-6 m2/s)
+         rmxl_min = 1.e-6_wp / ( rn_ediff * SQRT( rn_emin ) )    ! resulting minimum length to recover molecular viscosity
+         IF(lwp) WRITE(numout,*) '   ==>>>   minimum mixing length with your parameters rmxl_min = ', rmxl_min
+      ENDIF
+      !
+      !                              ! allocate tke arrays
+      IF( zdf_tke_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_tke_init : unable to allocate arrays' )
+      !
+      !                               !* 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( nn_etau == 3 .AND. .NOT. ln_cpl )   CALL ctl_stop( 'nn_etau == 3 : HF taum only known in coupled mode' )
+      !
+      IF( ln_mxl0 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   use a surface mixing length = F(stress) :   set rn_mxl0 = rmxl_min'
+         rn_mxl0 = rmxl_min
+      ENDIF
+      
+      IF( nn_etau == 2  )   CALL zdf_mxl( nit000 )      ! Initialization of nmln 
+
+      !                               !* depth of penetration of surface tke
+      IF( nn_etau /= 0 ) THEN      
+         SELECT CASE( nn_htau )             ! Choice of the depth of penetration
+         CASE( 0 )                                 ! constant depth penetration (here 10 meters)
+            htau(:,:) = 10._wp
+         CASE( 1 )                                 ! F(latitude) : 0.5m to 30m poleward of 40 degrees
+            htau(:,:) = MAX(  0.5_wp, MIN( 30._wp, 45._wp* ABS( SIN( rpi/180._wp * gphit(:,:) ) ) )   )            
+         END SELECT
+      ENDIF
+      !                                !* read or initialize all required files
+      CALL tke_rst( nit000, 'READ' )      ! (en, avt_k, avm_k, dissl) 
+      !
+      IF( lwxios ) THEN
+         CALL iom_set_rstw_var_active('en')
+         CALL iom_set_rstw_var_active('avt_k')
+         CALL iom_set_rstw_var_active('avm_k')
+         CALL iom_set_rstw_var_active('dissl')
+      ENDIF
+   END SUBROUTINE zdf_tke_init
+
+
+   SUBROUTINE tke_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE tke_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write TKE file (en) in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain TKE, en is either 
+      !!                set to rn_emin or recomputed 
+      !!----------------------------------------------------------------------
+      USE zdf_oce , ONLY : en, avt_k, avm_k   ! ocean vertical physics
+      !!
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   jit, jk              ! dummy loop indices
+      INTEGER ::   id1, id2, id3, id4   ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ---------------
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            id1 = iom_varid( numror, 'en'   , ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'avt_k', ldstop = .FALSE. )
+            id3 = iom_varid( numror, 'avm_k', ldstop = .FALSE. )
+            id4 = iom_varid( numror, 'dissl', ldstop = .FALSE. )
+            !
+            IF( MIN( id1, id2, id3, id4 ) > 0 ) THEN      ! fields exist
+               CALL iom_get( numror, jpdom_autoglo, 'en'   , en   , ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'avt_k', avt_k, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'avm_k', avm_k, ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'dissl', dissl, ldxios = lrxios )
+            ELSE                                          ! start TKE from rest
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) '   ==>>>   previous run without TKE scheme, set en to background values'
+               en   (:,:,:) = rn_emin * wmask(:,:,:)
+               dissl(:,:,:) = 1.e-12_wp
+               ! avt_k, avm_k already set to the background value in zdf_phy_init
+            ENDIF
+         ELSE                                   !* Start from rest
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) '   ==>>>   start from rest: set en to the background value'
+            en   (:,:,:) = rn_emin * wmask(:,:,:)
+            dissl(:,:,:) = 1.e-12_wp
+            ! avt_k, avm_k already set to the background value in zdf_phy_init
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! -------------------
+         IF(lwp) WRITE(numout,*) '---- tke_rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          ) 
+         CALL iom_rstput( kt, nitrst, numrow, 'en'   , en   , ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'avt_k', avt_k, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'avm_k', avm_k, ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'dissl', dissl, ldxios = lwxios )
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+         !
+      ENDIF
+      !
+   END SUBROUTINE tke_rst
+
+   !!======================================================================
+END MODULE zdftke
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_cray.f90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_cray.f90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_cray.f90	(revision 14097)
@@ -0,0 +1,34 @@
+!  Cray subroutines or functions used by OPA model and possibly 
+!  not found on other platforms.
+!
+!  check their existence
+!  
+!  wheneq
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+SUBROUTINE lib_cray
+      WRITE(*,*) 'lib_cray: You should not have seen this print! error?'
+END SUBROUTINE lib_cray
+
+SUBROUTINE wheneq ( i, x, j, t, ind, nn )
+        IMPLICIT NONE
+
+        INTEGER , INTENT (  in ) :: i, j
+        INTEGER , INTENT ( out ) :: nn
+        REAL    , INTENT (  in ), DIMENSION (1+(i-1)*j) :: x
+        REAL    , INTENT (  in ) :: t
+        INTEGER , INTENT ( out ), DIMENSION (1+(i-1)*j) :: ind
+        INTEGER :: n, k
+        nn = 0
+        DO n = 1, i
+          k = 1 + (n-1) * j
+          IF ( x ( k) == t ) THEN 
+              nn = nn + 1
+              ind (nn) = k
+          ENDIF
+        END DO 
+
+END SUBROUTINE wheneq
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran.F90	(revision 14097)
@@ -0,0 +1,489 @@
+MODULE lib_fortran
+   !!======================================================================
+   !!                       ***  MODULE  lib_fortran  ***
+   !! Fortran utilities:  includes some low levels fortran functionality
+   !!======================================================================
+   !! History :  3.2  !  2010-05  (M. Dunphy, R. Benshila)  Original code
+   !!            3.4  !  2013-06  (C. Rousset)  add glob_min, glob_max 
+   !!                                           + 3d dim. of input is fexible (jpk, jpl...) 
+   !!            4.0  !  2016-06  (T. Lovato)  double precision global sum by default 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   glob_sum    : generic interface for global masked summation over
+   !!                 the interior domain for 1 or 2 2D or 3D arrays
+   !!                 it works only for T points
+   !!   SIGN        : generic interface for SIGN to overwrite f95 behaviour
+   !!                 of intrinsinc sign function
+   !!----------------------------------------------------------------------
+   USE par_oce         ! Ocean parameter
+   USE dom_oce         ! ocean domain
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distributed memory computing
+   USE lbclnk          ! ocean lateral boundary conditions
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   glob_sum      ! used in many places (masked with tmask_i)
+   PUBLIC   glob_sum_full ! used in many places (masked with tmask_h, ie only over the halos)
+   PUBLIC   local_sum     ! used in trcrad, local operation before glob_sum_delay
+   PUBLIC   sum3x3        ! used in trcrad, do a sum over 3x3 boxes
+   PUBLIC   DDPDD         ! also used in closea module
+   PUBLIC   glob_min, glob_max
+#if defined key_nosignedzero
+   PUBLIC SIGN
+#endif
+
+   INTERFACE glob_sum
+      MODULE PROCEDURE glob_sum_1d, glob_sum_2d, glob_sum_3d
+   END INTERFACE
+   INTERFACE glob_sum_full
+      MODULE PROCEDURE glob_sum_full_2d, glob_sum_full_3d
+   END INTERFACE
+   INTERFACE local_sum
+      MODULE PROCEDURE local_sum_2d, local_sum_3d
+   END INTERFACE
+   INTERFACE sum3x3
+      MODULE PROCEDURE sum3x3_2d, sum3x3_3d
+   END INTERFACE
+   INTERFACE glob_min
+      MODULE PROCEDURE glob_min_2d, glob_min_3d
+   END INTERFACE
+   INTERFACE glob_max
+      MODULE PROCEDURE glob_max_2d, glob_max_3d
+   END INTERFACE
+
+#if defined key_nosignedzero
+   INTERFACE SIGN
+      MODULE PROCEDURE SIGN_SCALAR, SIGN_ARRAY_1D, SIGN_ARRAY_2D, SIGN_ARRAY_3D,   &
+         &             SIGN_ARRAY_1D_A, SIGN_ARRAY_2D_A, SIGN_ARRAY_3D_A,          &
+         &             SIGN_ARRAY_1D_B, SIGN_ARRAY_2D_B, SIGN_ARRAY_3D_B
+   END INTERFACE
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#  define GLOBSUM_CODE
+
+#     define DIM_1d
+#     define FUNCTION_GLOBSUM           glob_sum_1d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBSUM
+#     undef DIM_1d
+
+#     define DIM_2d
+#     define OPERATION_GLOBSUM
+#     define FUNCTION_GLOBSUM           glob_sum_2d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBSUM
+#     undef OPERATION_GLOBSUM
+#     define OPERATION_FULL_GLOBSUM
+#     define FUNCTION_GLOBSUM           glob_sum_full_2d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBSUM
+#     undef OPERATION_FULL_GLOBSUM
+#     undef DIM_2d
+
+#     define DIM_3d
+#     define OPERATION_GLOBSUM
+#     define FUNCTION_GLOBSUM           glob_sum_3d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBSUM
+#     undef OPERATION_GLOBSUM
+#     define OPERATION_FULL_GLOBSUM
+#     define FUNCTION_GLOBSUM           glob_sum_full_3d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBSUM
+#     undef OPERATION_FULL_GLOBSUM
+#     undef DIM_3d
+
+#  undef GLOBSUM_CODE
+
+
+#  define GLOBMINMAX_CODE
+
+#     define DIM_2d
+#     define OPERATION_GLOBMIN
+#     define FUNCTION_GLOBMINMAX           glob_min_2d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBMINMAX
+#     undef OPERATION_GLOBMIN
+#     define OPERATION_GLOBMAX
+#     define FUNCTION_GLOBMINMAX           glob_max_2d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBMINMAX
+#     undef OPERATION_GLOBMAX
+#     undef DIM_2d
+
+#     define DIM_3d
+#     define OPERATION_GLOBMIN
+#     define FUNCTION_GLOBMINMAX           glob_min_3d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBMINMAX
+#     undef OPERATION_GLOBMIN
+#     define OPERATION_GLOBMAX
+#     define FUNCTION_GLOBMINMAX           glob_max_3d
+#     include "lib_fortran_generic.h90"
+#     undef FUNCTION_GLOBMINMAX
+#     undef OPERATION_GLOBMAX
+#     undef DIM_3d
+#  undef GLOBMINMAX_CODE
+
+!                          ! FUNCTION local_sum !
+
+   FUNCTION local_sum_2d( ptab )
+      !!----------------------------------------------------------------------
+      REAL(wp),  INTENT(in   ) ::   ptab(:,:) ! array on which operation is applied
+      COMPLEX(wp)              ::  local_sum_2d
+      !
+      !!-----------------------------------------------------------------------
+      !
+      COMPLEX(wp)::   ctmp
+      REAL(wp)   ::   ztmp
+      INTEGER    ::   ji, jj    ! dummy loop indices
+      INTEGER    ::   ipi, ipj  ! dimensions
+      !!-----------------------------------------------------------------------
+      !
+      ipi = SIZE(ptab,1)   ! 1st dimension
+      ipj = SIZE(ptab,2)   ! 2nd dimension
+      !
+      ctmp = CMPLX( 0.e0, 0.e0, wp )   ! warning ctmp is cumulated
+
+      DO jj = 1, ipj
+         DO ji = 1, ipi
+            ztmp =  ptab(ji,jj) * tmask_i(ji,jj)
+            CALL DDPDD( CMPLX( ztmp, 0.e0, wp ), ctmp )
+         END DO
+      END DO
+      !
+      local_sum_2d = ctmp
+       
+   END FUNCTION local_sum_2d
+
+   FUNCTION local_sum_3d( ptab )
+      !!----------------------------------------------------------------------
+      REAL(wp),  INTENT(in   ) ::   ptab(:,:,:) ! array on which operation is applied
+      COMPLEX(wp)              ::  local_sum_3d
+      !
+      !!-----------------------------------------------------------------------
+      !
+      COMPLEX(wp)::   ctmp
+      REAL(wp)   ::   ztmp
+      INTEGER    ::   ji, jj, jk   ! dummy loop indices
+      INTEGER    ::   ipi, ipj, ipk    ! dimensions
+      !!-----------------------------------------------------------------------
+      !
+      ipi = SIZE(ptab,1)   ! 1st dimension
+      ipj = SIZE(ptab,2)   ! 2nd dimension
+      ipk = SIZE(ptab,3)   ! 3rd dimension
+      !
+      ctmp = CMPLX( 0.e0, 0.e0, wp )   ! warning ctmp is cumulated
+
+      DO jk = 1, ipk
+        DO jj = 1, ipj
+          DO ji = 1, ipi
+             ztmp =  ptab(ji,jj,jk) * tmask_i(ji,jj)
+             CALL DDPDD( CMPLX( ztmp, 0.e0, wp ), ctmp )
+          END DO
+        END DO
+      END DO
+      !
+      local_sum_3d = ctmp
+       
+   END FUNCTION local_sum_3d
+
+!                          ! FUNCTION sum3x3 !
+
+   SUBROUTINE sum3x3_2d( p2d )
+      !!-----------------------------------------------------------------------
+      !!                  ***  routine sum3x3_2d  ***
+      !!
+      !! ** Purpose : sum over 3x3 boxes
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION (:,:), INTENT(inout) ::   p2d
+      !
+      INTEGER ::   ji, ji2, jj, jj2     ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( SIZE(p2d,1) /= jpi ) CALL ctl_stop( 'STOP', 'wrong call of sum3x3_2d, the first dimension is not equal to jpi' ) 
+      IF( SIZE(p2d,2) /= jpj ) CALL ctl_stop( 'STOP', 'wrong call of sum3x3_2d, the second dimension is not equal to jpj' ) 
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi 
+            IF( MOD(mig(ji), 3) == 1 .AND. MOD(mjg(jj), 3) == 1 ) THEN   ! bottom left corber of a 3x3 box
+               ji2 = MIN(mig(ji)+2, jpiglo) - nimpp + 1                  ! right position of the box
+               jj2 = MIN(mjg(jj)+2, jpjglo) - njmpp + 1                  ! upper position of the box
+               IF( ji2 <= jpi .AND. jj2 <= jpj ) THEN                    ! the box is fully included in the local mpi domain
+                  p2d(ji:ji2,jj:jj2) = SUM(p2d(ji:ji2,jj:jj2))
+               ENDIF
+            ENDIF
+         END DO
+      END DO
+      CALL lbc_lnk( 'lib_fortran', p2d, 'T', 1. )
+      IF( nbondi /= -1 ) THEN
+         IF( MOD(mig(    1), 3) == 1 )   p2d(    1,:) = p2d(    2,:)
+         IF( MOD(mig(    1), 3) == 2 )   p2d(    2,:) = p2d(    1,:)
+      ENDIF
+      IF( nbondi /=  1 ) THEN
+         IF( MOD(mig(jpi-2), 3) == 1 )   p2d(  jpi,:) = p2d(jpi-1,:)
+         IF( MOD(mig(jpi-2), 3) == 0 )   p2d(jpi-1,:) = p2d(  jpi,:)
+      ENDIF
+      IF( nbondj /= -1 ) THEN
+         IF( MOD(mjg(    1), 3) == 1 )   p2d(:,    1) = p2d(:,    2)
+         IF( MOD(mjg(    1), 3) == 2 )   p2d(:,    2) = p2d(:,    1)
+      ENDIF
+      IF( nbondj /=  1 ) THEN
+         IF( MOD(mjg(jpj-2), 3) == 1 )   p2d(:,  jpj) = p2d(:,jpj-1)
+         IF( MOD(mjg(jpj-2), 3) == 0 )   p2d(:,jpj-1) = p2d(:,  jpj)
+      ENDIF
+      CALL lbc_lnk( 'lib_fortran', p2d, 'T', 1. )
+
+   END SUBROUTINE sum3x3_2d
+
+   SUBROUTINE sum3x3_3d( p3d )
+      !!-----------------------------------------------------------------------
+      !!                  ***  routine sum3x3_3d  ***
+      !!
+      !! ** Purpose : sum over 3x3 boxes
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION (:,:,:), INTENT(inout) ::   p3d
+      !
+      INTEGER ::   ji, ji2, jj, jj2, jn     ! dummy loop indices
+      INTEGER ::   ipn                      ! Third dimension size
+      !!----------------------------------------------------------------------
+      !
+      IF( SIZE(p3d,1) /= jpi ) CALL ctl_stop( 'STOP', 'wrong call of sum3x3_3d, the first dimension is not equal to jpi' ) 
+      IF( SIZE(p3d,2) /= jpj ) CALL ctl_stop( 'STOP', 'wrong call of sum3x3_3d, the second dimension is not equal to jpj' ) 
+      ipn = SIZE(p3d,3)
+      !
+      DO jn = 1, ipn
+         DO jj = 1, jpj
+            DO ji = 1, jpi 
+               IF( MOD(mig(ji), 3) == 1 .AND. MOD(mjg(jj), 3) == 1 ) THEN   ! bottom left corber of a 3x3 box
+                  ji2 = MIN(mig(ji)+2, jpiglo) - nimpp + 1                  ! right position of the box
+                  jj2 = MIN(mjg(jj)+2, jpjglo) - njmpp + 1                  ! upper position of the box
+                  IF( ji2 <= jpi .AND. jj2 <= jpj ) THEN                    ! the box is fully included in the local mpi domain
+                     p3d(ji:ji2,jj:jj2,jn) = SUM(p3d(ji:ji2,jj:jj2,jn))
+                  ENDIF
+               ENDIF
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( 'lib_fortran', p3d, 'T', 1. )
+      IF( nbondi /= -1 ) THEN
+         IF( MOD(mig(    1), 3) == 1 )   p3d(    1,:,:) = p3d(    2,:,:)
+         IF( MOD(mig(    1), 3) == 2 )   p3d(    2,:,:) = p3d(    1,:,:)
+      ENDIF
+      IF( nbondi /=  1 ) THEN
+         IF( MOD(mig(jpi-2), 3) == 1 )   p3d(  jpi,:,:) = p3d(jpi-1,:,:)
+         IF( MOD(mig(jpi-2), 3) == 0 )   p3d(jpi-1,:,:) = p3d(  jpi,:,:)
+      ENDIF
+      IF( nbondj /= -1 ) THEN
+         IF( MOD(mjg(    1), 3) == 1 )   p3d(:,    1,:) = p3d(:,    2,:)
+         IF( MOD(mjg(    1), 3) == 2 )   p3d(:,    2,:) = p3d(:,    1,:)
+      ENDIF
+      IF( nbondj /=  1 ) THEN
+         IF( MOD(mjg(jpj-2), 3) == 1 )   p3d(:,  jpj,:) = p3d(:,jpj-1,:)
+         IF( MOD(mjg(jpj-2), 3) == 0 )   p3d(:,jpj-1,:) = p3d(:,  jpj,:)
+      ENDIF
+      CALL lbc_lnk( 'lib_fortran', p3d, 'T', 1. )
+
+   END SUBROUTINE sum3x3_3d
+
+
+   SUBROUTINE DDPDD( ydda, yddb )
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE DDPDD ***
+      !!
+      !! ** Purpose : Add a scalar element to a sum
+      !!
+      !!
+      !! ** Method  : The code uses the compensated summation with doublet
+      !!              (sum,error) emulated useing complex numbers. ydda is the
+      !!               scalar to add to the summ yddb
+      !!
+      !! ** Action  : This does only work for MPI.
+      !!
+      !! References : Using Acurate Arithmetics to Improve Numerical
+      !!              Reproducibility and Sability in Parallel Applications
+      !!              Yun HE and Chris H. Q. DING, Journal of Supercomputing 18, 259-277, 2001
+      !!----------------------------------------------------------------------
+      COMPLEX(wp), INTENT(in   ) ::   ydda
+      COMPLEX(wp), INTENT(inout) ::   yddb
+      !
+      REAL(wp) :: zerr, zt1, zt2  ! local work variables
+      !!-----------------------------------------------------------------------
+      !
+      ! Compute ydda + yddb using Knuth's trick.
+      zt1  = REAL(ydda) + REAL(yddb)
+      zerr = zt1 - REAL(ydda)
+      zt2  = ( (REAL(yddb) - zerr) + (REAL(ydda) - (zt1 - zerr)) )   &
+         &   + AIMAG(ydda)         + AIMAG(yddb)
+      !
+      ! The result is t1 + t2, after normalization.
+      yddb = CMPLX( zt1 + zt2, zt2 - ((zt1 + zt2) - zt1), wp )
+      !
+   END SUBROUTINE DDPDD
+
+#if defined key_nosignedzero
+   !!----------------------------------------------------------------------
+   !!   'key_nosignedzero'                                         F90 SIGN
+   !!----------------------------------------------------------------------
+
+   FUNCTION SIGN_SCALAR( pa, pb )
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_SCALAR  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa,pb          ! input
+      REAL(wp) :: SIGN_SCALAR    ! result
+      !!-----------------------------------------------------------------------
+      IF ( pb >= 0.e0) THEN   ;   SIGN_SCALAR = ABS(pa)
+      ELSE                    ;   SIGN_SCALAR =-ABS(pa)
+      ENDIF
+   END FUNCTION SIGN_SCALAR
+
+
+   FUNCTION SIGN_ARRAY_1D( pa, pb )
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_1D  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa,pb(:)                   ! input
+      REAL(wp) :: SIGN_ARRAY_1D(SIZE(pb,1))  ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_1D = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_1D =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_1D
+
+
+   FUNCTION SIGN_ARRAY_2D(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_2D  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa,pb(:,:)      ! input
+      REAL(wp) :: SIGN_ARRAY_2D(SIZE(pb,1),SIZE(pb,2))  ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_2D = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_2D =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_2D
+
+   FUNCTION SIGN_ARRAY_3D(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_3D  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa,pb(:,:,:)      ! input
+      REAL(wp) :: SIGN_ARRAY_3D(SIZE(pb,1),SIZE(pb,2),SIZE(pb,3))  ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_3D = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_3D =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_3D
+
+
+   FUNCTION SIGN_ARRAY_1D_A(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_1D_A  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:),pb(:)      ! input
+      REAL(wp) :: SIGN_ARRAY_1D_A(SIZE(pb,1))  ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_1D_A = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_1D_A =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_1D_A
+
+
+   FUNCTION SIGN_ARRAY_2D_A(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_2D_A  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:,:),pb(:,:)      ! input
+      REAL(wp) :: SIGN_ARRAY_2D_A(SIZE(pb,1),SIZE(pb,2))  ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_2D_A = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_2D_A =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_2D_A
+
+
+   FUNCTION SIGN_ARRAY_3D_A(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_3D_A  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:,:,:),pb(:,:,:)  ! input
+      REAL(wp) :: SIGN_ARRAY_3D_A(SIZE(pb,1),SIZE(pb,2),SIZE(pb,3)) ! result
+      !!-----------------------------------------------------------------------
+      WHERE ( pb >= 0.e0 )   ;   SIGN_ARRAY_3D_A = ABS(pa)
+      ELSEWHERE              ;   SIGN_ARRAY_3D_A =-ABS(pa)
+      END WHERE
+   END FUNCTION SIGN_ARRAY_3D_A
+
+
+   FUNCTION SIGN_ARRAY_1D_B(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_1D_B  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:),pb      ! input
+      REAL(wp) :: SIGN_ARRAY_1D_B(SIZE(pa,1))  ! result
+      !!-----------------------------------------------------------------------
+      IF( pb >= 0.e0 ) THEN   ;   SIGN_ARRAY_1D_B = ABS(pa)
+      ELSE                    ;   SIGN_ARRAY_1D_B =-ABS(pa)
+      ENDIF
+   END FUNCTION SIGN_ARRAY_1D_B
+
+
+   FUNCTION SIGN_ARRAY_2D_B(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_2D_B  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:,:),pb      ! input
+      REAL(wp) :: SIGN_ARRAY_2D_B(SIZE(pa,1),SIZE(pa,2))  ! result
+      !!-----------------------------------------------------------------------
+      IF( pb >= 0.e0 ) THEN   ;   SIGN_ARRAY_2D_B = ABS(pa)
+      ELSE                    ;   SIGN_ARRAY_2D_B =-ABS(pa)
+      ENDIF
+   END FUNCTION SIGN_ARRAY_2D_B
+
+
+   FUNCTION SIGN_ARRAY_3D_B(pa,pb)
+      !!-----------------------------------------------------------------------
+      !!                  ***  FUNCTION SIGN_ARRAY_3D_B  ***
+      !!
+      !! ** Purpose : overwrite f95 behaviour of intrinsinc sign function
+      !!-----------------------------------------------------------------------
+      REAL(wp) :: pa(:,:,:),pb      ! input
+      REAL(wp) :: SIGN_ARRAY_3D_B(SIZE(pa,1),SIZE(pa,2),SIZE(pa,3))  ! result
+      !!-----------------------------------------------------------------------
+      IF( pb >= 0.e0 ) THEN   ;   SIGN_ARRAY_3D_B = ABS(pa)
+      ELSE                    ;   SIGN_ARRAY_3D_B =-ABS(pa)
+      ENDIF
+   END FUNCTION SIGN_ARRAY_3D_B
+#endif
+
+   !!======================================================================
+END MODULE lib_fortran
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran_generic.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran_generic.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/lib_fortran_generic.h90	(revision 14097)
@@ -0,0 +1,139 @@
+#if defined GLOBSUM_CODE
+!                          ! FUNCTION FUNCTION_GLOBSUM !
+#   if defined DIM_1d
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)                 , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define ARRAY_IN(i,j,k)   ptab(i)
+#      define ARRAY2_IN(i,j,k)  ptab2(i)
+#      define J_SIZE(ptab)      1
+#      define K_SIZE(ptab)      1
+#      define MASK_ARRAY(i,j)   1.
+#   endif
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)                 , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define ARRAY_IN(i,j,k)   ptab(i,j)
+#      define ARRAY2_IN(i,j,k)  ptab2(i,j)
+#      define J_SIZE(ptab)      SIZE(ptab,2)
+#      define K_SIZE(ptab)      1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)                 , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define ARRAY_IN(i,j,k)   ptab(i,j,k)
+#      define ARRAY2_IN(i,j,k)  ptab2(i,j,k)
+#      define J_SIZE(ptab)      SIZE(ptab,2)
+#      define K_SIZE(ptab)      SIZE(ptab,3)
+#   endif
+#   if defined OPERATION_GLOBSUM
+#      define MASK_ARRAY(i,j)   tmask_i(i,j)
+#   endif
+#   if defined OPERATION_FULL_GLOBSUM
+#      define MASK_ARRAY(i,j)   tmask_h(i,j)
+#   endif
+
+   FUNCTION FUNCTION_GLOBSUM( cdname, ptab )
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),  INTENT(in   ) ::   cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:,:,:)                             ! array on which operation is applied
+      REAL(wp)   ::  FUNCTION_GLOBSUM
+      !
+      !!-----------------------------------------------------------------------
+      !
+      REAL(wp)                              ::   FUNCTION_GLOB_OP   ! global sum
+      !!
+      COMPLEX(wp)::   ctmp
+      REAL(wp)   ::   ztmp
+      INTEGER    ::   ji, jj, jk   ! dummy loop indices
+      INTEGER    ::   ipi, ipj, ipk    ! dimensions
+      !!-----------------------------------------------------------------------
+      !
+      ipi = SIZE(ptab,1)   ! 1st dimension
+      ipj = J_SIZE(ptab)   ! 2nd dimension
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      !
+      ctmp = CMPLX( 0.e0, 0.e0, wp )   ! warning ctmp is cumulated
+   
+      DO jk = 1, ipk
+        DO jj = 1, ipj
+          DO ji = 1, ipi
+             ztmp =  ARRAY_IN(ji,jj,jk) * MASK_ARRAY(ji,jj)
+             CALL DDPDD( CMPLX( ztmp, 0.e0, wp ), ctmp )
+          END DO
+        END DO
+      END DO
+      CALL mpp_sum( cdname, ctmp )   ! sum over the global domain
+      FUNCTION_GLOBSUM = REAL(ctmp,wp)
+
+   END FUNCTION FUNCTION_GLOBSUM
+
+#undef ARRAY_TYPE
+#undef ARRAY2_TYPE
+#undef ARRAY_IN
+#undef ARRAY2_IN
+#undef J_SIZE
+#undef K_SIZE
+#undef MASK_ARRAY
+!
+# endif
+#if defined GLOBMINMAX_CODE
+!                          ! FUNCTION FUNCTION_GLOBMINMAX !
+#   if defined DIM_2d
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)                 , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define ARRAY_IN(i,j,k)   ptab(i,j)
+#      define ARRAY2_IN(i,j,k)  ptab2(i,j)
+#      define K_SIZE(ptab)      1
+#   endif
+#   if defined DIM_3d
+#      define ARRAY_TYPE(i,j,k)    REAL(wp)                 , INTENT(in   ) ::   ARRAY_IN(i,j,k)
+#      define ARRAY_IN(i,j,k)   ptab(i,j,k)
+#      define ARRAY2_IN(i,j,k)  ptab2(i,j,k)
+#      define K_SIZE(ptab)      SIZE(ptab,3)
+#   endif
+#   if defined OPERATION_GLOBMIN
+#      define SCALAR_OPERATION min
+#      define ARRAY_OPERATION minval
+#      define MPP_OPERATION mpp_min
+#   endif
+#   if defined OPERATION_GLOBMAX
+#      define SCALAR_OPERATION max
+#      define ARRAY_OPERATION maxval
+#      define MPP_OPERATION mpp_max
+#   endif
+
+   FUNCTION FUNCTION_GLOBMINMAX( cdname, ptab )
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),  INTENT(in   ) ::   cdname  ! name of the calling subroutine
+      ARRAY_TYPE(:,:,:)                             ! array on which operation is applied
+      REAL(wp)   ::  FUNCTION_GLOBMINMAX
+      !
+      !!-----------------------------------------------------------------------
+      !
+      REAL(wp)                              ::   FUNCTION_GLOB_OP   ! global sum
+      !!
+      COMPLEX(wp)::   ctmp
+      REAL(wp)   ::   ztmp
+      INTEGER    ::   jk       ! dummy loop indices
+      INTEGER    ::   ipk      ! dimensions
+      !!-----------------------------------------------------------------------
+      !
+      ipk = K_SIZE(ptab)   ! 3rd dimension
+      !
+      ztmp = ARRAY_OPERATION( ARRAY_IN(:,:,1)*tmask_i(:,:) )
+      DO jk = 2, ipk
+         ztmp = SCALAR_OPERATION(ztmp, ARRAY_OPERATION( ARRAY_IN(:,:,jk)*tmask_i(:,:) ))
+      ENDDO
+
+      CALL MPP_OPERATION( cdname, ztmp)
+
+      FUNCTION_GLOBMINMAX = ztmp
+
+
+   END FUNCTION FUNCTION_GLOBMINMAX
+
+#undef ARRAY_TYPE
+#undef ARRAY2_TYPE
+#undef ARRAY_IN
+#undef ARRAY2_IN
+#undef K_SIZE
+#undef SCALAR_OPERATION
+#undef ARRAY_OPERATION
+#undef MPP_OPERATION
+# endif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/module_example
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/module_example	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/module_example	(revision 14097)
@@ -0,0 +1,194 @@
+MODULE exampl
+   !!======================================================================
+   !!                       ***  MODULE  exampl  ***
+   !! Ocean physics:  brief description of the purpose of the module
+   !!                 (please no more than 2 lines)
+   !!======================================================================
+   !! History : 3.0  !  2008-06  (Author Names)  Original code
+   !!            -   !  2008-08  (Author names)  brief description of modifications
+   !!           3.3  !  2010-11  (Author names)        -              -
+   !!----------------------------------------------------------------------
+#if defined key_example
+   !!----------------------------------------------------------------------
+   !!   'key_example'  :                brief description of the key option
+   !!----------------------------------------------------------------------
+   !!   exa_mpl       : list of module subroutine (caution, never use the
+   !!   exa_mpl_init  : name of the module for a routine)
+   !!   exa_mpl_stp   : Please try to use 3 letter block for routine names
+   !!----------------------------------------------------------------------
+   USE module_name1   ! brief description of the used module
+   USE module_name2   ! ....
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   exa_mpl        ! routine called in xxx.F90 module
+   PUBLIC   exa_mpl_init   ! routine called in nemogcm.F90 module
+
+   TYPE ::   FLD_E                !: Structure type definition
+      CHARACTER(lc) ::   clname      ! clname description (default length, lc, is 256, see par_kind.F90)
+      INTEGER       ::   nfreqh      ! nfreqh description 
+   END TYPE FLD_E 
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var1         !: var1 description. CAUTION always use !: to describe
+   !                                                          !  a PUBLIC variable: simplify its search : 
+   !                                                          !  grep var1 *90 | grep '!:'
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   var2, var2   !: several variable on a same line OK, but 
+   !                                                          !  DO NOT use continuation lines in declaration
+
+   !                               !!* namelist nam_xxx *
+   LOGICAL   ::   ln_opt = .TRUE.   ! give the default value of each namelist parameter
+   CHARACTER ::   cn_tex = 'T'      ! short description  of the variable
+   INTEGER   ::   nn_opt = 1        ! please respect the DOCTOR norm for namelist variable
+   REAL(wp)  ::   rn_var = 2._wp    ! (it becomes easy to identify them in the code)
+   TYPE(FLD) ::   sn_ex             ! structure
+
+   INTEGER                          ::   nint    ! nint  description (local permanent variable)
+   REAL(wp)                         ::   var     ! var         -                -
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   array   ! array       -                -
+
+   !! * Substitutions
+#  include "exampl_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id: module_example 11536 2019-09-11 13:54:18Z smasson $ 
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION exa_mpl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION exa_mpl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( array(jpi,jpj,jpk) , STAT= exa_mpl_alloc )   ! Module array                                                                
+      !
+      CALL mpp_sum ( 'module_example', exa_mpl_alloc )
+      IF( exa_mpl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION exa_mpl_alloc
+   
+
+   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE exa_mpl  ***
+      !!
+      !! ** Purpose :   Brief description of the routine
+      !!
+      !! ** Method  :   description of the methodoloy used to achieve the
+      !!                objectives of the routine. Be as clear as possible!
+      !!
+      !! ** Action  : - first action (share memory array/varible modified
+      !!                in this routine
+      !!              - second action .....
+      !!              - .....
+      !!
+      !! References :   Author et al., Short_name_review, Year
+      !!                Give references if exist otherwise suppress these lines
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in   )                     ::   kt      ! short description 
+      INTEGER , INTENT(inout)                     ::   pvar1   !   -         -
+      REAL(wp), INTENT(  out)                     ::   pvar2   !   -         -
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   pvar2   !   -         -
+      !!
+      INTEGER  ::   ji, jj, jk       ! dummy loop arguments  (DOCTOR : start with j, but not jp)
+      INTEGER  ::   itoto, itata     ! temporary integers    (DOCTOR : start with i
+      REAL(wp) ::   zmlmin, zbbrau   ! temporary scalars     (DOCTOR : start with z)
+      REAL(wp) ::   zfact1, zfact2   ! do not use continuation lines in declaration
+      REAL(wp), DIMENSION(jpi,jpj) ::   zwrk_2d   ! 2D workspace
+      !!--------------------------------------------------------------------
+      !
+      IF( kt == nit000  )   CALL exa_mpl_init    ! Initialization (first time-step only)
+
+      zmlmin = 1.e-8                             ! Local constant initialization
+      zbbrau =  .5 * ebb / rau0
+      zfact1 = -.5 * rdt * efave
+      zfact2 = 1.5 * rdt * ediss
+
+      SELECT CASE ( npdl )                       ! short description of the action
+      !
+      CASE ( 0 )                                      ! describe case 1
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  avm(ji,jj,jk) = ....
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 1 )                                      ! describe case 2
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  avm(ji,jj,jk) = ...
+               END DO
+            END DO
+         END DO
+         !
+      END SELECT
+      !
+      CALL lbc_lnk( 'module_example', avm, 'T', 1. )              ! Lateral boundary conditions (unchanged sign)
+      !
+   END SUBROUTINE exa_mpl
+
+
+   SUBROUTINE exa_mpl_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE exa_mpl_init  ***
+      !!                   
+      !! ** Purpose :   initialization of ....
+      !!
+      !! ** Method  :   blah blah blah ...
+      !!
+      !! ** input   :   Namlist namexa
+      !!
+      !! ** Action  :   ...  
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk, jit   ! dummy loop indices
+      INTEGER  ::   ios              ! Local integer output status for namelist read
+      !!
+      NAMELIST/namexa/ exa_v1, exa_v2, nexa_0, sn_ex     
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namexa in reference namelist : Example
+      READ  ( numnam_ref, namexa, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namexa in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namexa in configuration namelist : Example
+      READ  ( numnam_cfg, namexa, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namexa in configuration namelist' )
+   ! Output namelist for control
+      WRITE ( numond, namexa )
+      !
+      IF(lwp) THEN                              ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'exa_mpl_init : example '
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namexa : set example parameters'
+         WRITE(numout,*) '      brief desciption               exa_v1  = ', exa_v1
+         WRITE(numout,*) '      brief desciption               exa_v2  = ', exa_v2
+         WRITE(numout,*) '      brief desciption               nexa_0  = ', nexa_0
+         WRITE(numout,*) '      brief desciption          sn_ex%clname = ', sn_ex%clname
+         WRITE(numout,*) '      brief desciption          sn_ex%nfreqh = ', sn_ex%nfreqh
+      ENDIF
+      !
+      !                              ! allocate exa_mpl arrays      
+      IF( exa_mpl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'exa_mpl_init : unable to allocate arrays' )
+      !                              ! Parameter control
+      IF( ln_opt      )   CALL ctl_stop( 'exa_mpl_init: this work and option xxx are incompatible'   )
+      IF( nn_opt == 2 )   CALL ctl_stop( 'STOP',  'exa_mpl_init: this work and option yyy may cause problems'  )
+      !
+   END SUBROUTINE exa_mpl_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                         NO example
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE exa_mpl( kt, pvar1, pvar2, ptab )              ! Empty routine
+      REAL::   ptab(:,:)
+      WRITE(*,*) 'exa_mpl: You should not have seen this print! error?', kt, pvar1, pvar2, ptab(1,1)
+   END SUBROUTINE exa_mpl
+#endif
+
+   !!======================================================================
+END MODULE exampl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemo.f90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemo.f90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemo.f90	(revision 14097)
@@ -0,0 +1,21 @@
+PROGRAM nemo
+   !!======================================================================
+   !!                     ***  PROGRAM nemo  ***
+   !!
+   !! ** Purpose :   encapsulate nemo_gcm so that it can also be called
+   !!              together with the linear tangent and adjoint models
+   !!======================================================================
+   !! History :   OPA  ! 2001-02  (M. Imbard, A. Weaver)  Original code
+   !!   NEMO      1.0  ! 2003-10  (G. Madec) F90
+   !!----------------------------------------------------------------------
+   USE nemogcm   ! NEMO system   (nemo_gcm routine)
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+   !
+   CALL nemo_gcm           ! NEMO direct code
+   ! 
+   !!======================================================================
+END PROGRAM nemo
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemogcm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemogcm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/nemogcm.F90	(revision 14097)
@@ -0,0 +1,702 @@
+MODULE nemogcm
+   !!======================================================================
+   !!                       ***  MODULE nemogcm   ***
+   !! Ocean system   : NEMO GCM (ocean dynamics, on-line tracers, biochemistry and sea-ice)
+   !!======================================================================
+   !! History :  OPA  ! 1990-10  (C. Levy, G. Madec)  Original code
+   !!            7.0  ! 1991-11  (M. Imbard, C. Levy, G. Madec)
+   !!            7.1  ! 1993-03  (M. Imbard, C. Levy, G. Madec, O. Marti, M. Guyon, A. Lazar,
+   !!                             P. Delecluse, C. Perigaud, G. Caniaux, B. Colot, C. Maes) release 7.1
+   !!             -   ! 1992-06  (L.Terray)  coupling implementation
+   !!             -   ! 1993-11  (M.A. Filiberti) IGLOO sea-ice
+   !!            8.0  ! 1996-03  (M. Imbard, C. Levy, G. Madec, O. Marti, M. Guyon, A. Lazar,
+   !!                             P. Delecluse, L.Terray, M.A. Filiberti, J. Vialar, A.M. Treguier, M. Levy) release 8.0
+   !!            8.1  ! 1997-06  (M. Imbard, G. Madec)
+   !!            8.2  ! 1999-11  (M. Imbard, H. Goosse)  sea-ice model
+   !!                 ! 1999-12  (V. Thierry, A-M. Treguier, M. Imbard, M-A. Foujols)  OPEN-MP
+   !!                 ! 2000-07  (J-M Molines, M. Imbard)  Open Boundary Conditions  (CLIPPER)
+   !!   NEMO     1.0  ! 2002-08  (G. Madec)  F90: Free form and modules
+   !!             -   ! 2004-06  (R. Redler, NEC CCRLE, Germany) add OASIS[3/4] coupled interfaces
+   !!             -   ! 2004-08  (C. Talandier) New trends organization
+   !!             -   ! 2005-06  (C. Ethe) Add the 1D configuration possibility
+   !!             -   ! 2005-11  (V. Garnier) Surface pressure gradient organization
+   !!             -   ! 2006-03  (L. Debreu, C. Mazauric)  Agrif implementation
+   !!             -   ! 2006-04  (G. Madec, R. Benshila)  Step reorganization
+   !!             -   ! 2007-07  (J. Chanut, A. Sellar) Unstructured open boundaries (BDY)
+   !!            3.2  ! 2009-08  (S. Masson)  open/write in the listing file in mpp
+   !!            3.3  ! 2010-05  (K. Mogensen, A. Weaver, M. Martin, D. Lea) Assimilation interface
+   !!             -   ! 2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.3.1! 2011-01  (A. R. Porter, STFC Daresbury) dynamical allocation
+   !!             -   ! 2011-11  (C. Harris) decomposition changes for running with CICE
+   !!            3.6  ! 2012-05  (C. Calone, J. Simeon, G. Madec, C. Ethe) Add grid coarsening 
+   !!             -   ! 2014-12  (G. Madec) remove KPP scheme and cross-land advection (cla)
+   !!            4.0  ! 2016-10  (G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   nemo_gcm      : solve ocean dynamics, tracer, biogeochemistry and/or sea-ice
+   !!   nemo_init     : initialization of the NEMO system
+   !!   nemo_ctl      : initialisation of the contol print
+   !!   nemo_closefile: close remaining open files
+   !!   nemo_alloc    : dynamical allocation
+   !!----------------------------------------------------------------------
+   USE step_oce       ! module used in the ocean time stepping module (step.F90)
+   USE phycst         ! physical constant                  (par_cst routine)
+   USE domain         ! domain initialization   (dom_init & dom_cfg routines)
+   USE closea         ! treatment of closed seas (for ln_closea)
+   USE usrdef_nam     ! user defined configuration
+   USE tideini        ! tidal components initialization   (tide_ini routine)
+   USE bdy_oce,  ONLY : ln_bdy
+   USE bdyini         ! open boundary cond. setting       (bdy_init routine)
+   USE istate         ! initial state setting          (istate_init routine)
+   USE ldfdyn         ! lateral viscosity setting      (ldfdyn_init routine)
+   USE ldftra         ! lateral diffusivity setting    (ldftra_init routine)
+   USE trdini         ! dyn/tra trends initialization     (trd_init routine)
+   USE asminc         ! assimilation increments     
+   USE asmbkg         ! writing out state trajectory
+   USE diaptr         ! poleward transports           (dia_ptr_init routine)
+   USE diadct         ! sections transports           (dia_dct_init routine)
+   USE diaobs         ! Observation diagnostics       (dia_obs_init routine)
+   USE diacfl         ! CFL diagnostics               (dia_cfl_init routine)
+   USE diaharm        ! tidal harmonics diagnostics  (dia_harm_init routine)
+   USE step           ! NEMO time-stepping                 (stp     routine)
+   USE icbini         ! handle bergs, initialisation
+   USE icbstp         ! handle bergs, calving, themodynamics and transport
+   USE cpl_oasis3     ! OASIS3 coupling
+   USE c1d            ! 1D configuration
+   USE step_c1d       ! Time stepping loop for the 1D configuration
+   USE dyndmp         ! Momentum damping
+   USE stopar         ! Stochastic param.: ???
+   USE stopts         ! Stochastic param.: ???
+   USE diurnal_bulk   ! diurnal bulk SST 
+   USE step_diu       ! diurnal bulk SST timestepping (called from here if run offline)
+   USE crsini         ! initialise grid coarsening utility
+   USE dia25h         ! 25h mean output
+   USE sbc_oce , ONLY : lk_oasis
+   USE wet_dry        ! Wetting and drying setting   (wad_init routine)
+#if defined key_top
+   USE trcini         ! passive tracer initialisation
+#endif
+#if defined key_nemocice_decomp
+   USE ice_domain_size, only: nx_global, ny_global
+#endif
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distributed memory computing
+   USE mppini         ! shared/distributed memory setting (mpp_init routine)
+   USE lbcnfd  , ONLY : isendto, nsndto, nfsloop, nfeloop   ! Setup of north fold exchanges 
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+#if defined key_iomput
+   USE xios           ! xIOserver
+#endif
+#if defined key_agrif
+   USE agrif_all_update   ! Master Agrif update
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   nemo_gcm    ! called by model.F90
+   PUBLIC   nemo_init   ! needed by AGRIF
+   PUBLIC   nemo_alloc  ! needed by TAM
+
+   CHARACTER(lc) ::   cform_aaa="( /, 'AAAAAAAA', / ) "     ! flag for output listing
+
+#if defined key_mpp_mpi
+   ! need MPI_Wtime
+   INCLUDE 'mpif.h'
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE nemo_gcm
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_gcm  ***
+      !!
+      !! ** Purpose :   NEMO solves the primitive equations on an orthogonal
+      !!              curvilinear mesh on the sphere.
+      !!
+      !! ** Method  : - model general initialization
+      !!              - launch the time-stepping (stp routine)
+      !!              - finalize the run by closing files and communications
+      !!
+      !! References : Madec, Delecluse, Imbard, and Levy, 1997:  internal report, IPSL.
+      !!              Madec, 2008, internal report, IPSL.
+      !!----------------------------------------------------------------------
+      INTEGER ::   istp   ! time step index
+      REAL(wp)::   zstptiming   ! elapsed time for 1 time step
+      !!----------------------------------------------------------------------
+      !
+#if defined key_agrif
+      CALL Agrif_Init_Grids()      ! AGRIF: set the meshes
+#endif
+      !                            !-----------------------!
+      CALL nemo_init               !==  Initialisations  ==!
+      !                            !-----------------------!
+#if defined key_agrif
+      CALL Agrif_Declare_Var_dom   ! AGRIF: set the meshes for DOM
+      CALL Agrif_Declare_Var       !  "      "   "   "      "  DYN/TRA 
+# if defined key_top
+      CALL Agrif_Declare_Var_top   !  "      "   "   "      "  TOP
+# endif
+# if defined key_si3
+      CALL Agrif_Declare_Var_ice   !  "      "   "   "      "  Sea ice
+# 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!
+      CALL mpp_max( 'nemogcm', nstop )
+
+      IF(lwp) WRITE(numout,cform_aaa)   ! Flag AAAAAAA
+
+      !                            !-----------------------!
+      !                            !==   time stepping   ==!
+      !                            !-----------------------!
+      istp = nit000
+      !
+#if defined key_c1d
+      DO WHILE ( istp <= nitend .AND. nstop == 0 )    !==  C1D time-stepping  ==!
+         CALL stp_c1d( istp )
+         istp = istp + 1
+      END DO
+#else
+      !
+# if defined key_agrif
+      !                                               !==  AGRIF time-stepping  ==!
+      CALL Agrif_Regrid()
+      !
+      ! Recursive update from highest nested level to lowest:
+      CALL Agrif_step_child_adj(Agrif_Update_All)
+      !
+      DO WHILE( istp <= nitend .AND. nstop == 0 )
+         CALL stp
+         istp = istp + 1
+      END DO
+      !
+# else
+      !
+      IF( .NOT.ln_diurnal_only ) THEN                 !==  Standard time-stepping  ==!
+         !
+         DO WHILE( istp <= nitend .AND. nstop == 0 )
+
+            ncom_stp = istp
+            IF( ln_timing ) THEN
+               zstptiming = MPI_Wtime()
+               IF ( istp == ( nit000 + 1 ) ) elapsed_time = zstptiming
+               IF ( istp ==         nitend ) elapsed_time = zstptiming - elapsed_time
+            ENDIF
+            
+            CALL stp        ( istp ) 
+            istp = istp + 1
+
+            IF( lwp .AND. ln_timing )   WRITE(numtime,*) 'timing step ', istp-1, ' : ', MPI_Wtime() - zstptiming
+
+         END DO
+         !
+      ELSE                                            !==  diurnal SST time-steeping only  ==!
+         !
+         DO WHILE( istp <= nitend .AND. nstop == 0 )
+            CALL stp_diurnal( istp )   ! time step only the diurnal SST 
+            istp = istp + 1
+         END DO
+         !
+      ENDIF
+      !
+# endif
+      !
+#endif
+      !
+      IF( ln_diaobs   )   CALL dia_obs_wri
+      !
+      IF( ln_icebergs )   CALL icb_end( nitend )
+
+      !                            !------------------------!
+      !                            !==  finalize the run  ==!
+      !                            !------------------------!
+      IF(lwp) WRITE(numout,cform_aaa)        ! Flag AAAAAAA
+      !
+      IF( nstop /= 0 .AND. lwp ) THEN        ! error print
+         WRITE(ctmp1,*) '   ==>>>   nemo_gcm: a total of ', nstop, ' errors have been found'
+         IF( ngrdstop > 0 ) THEN
+            WRITE(ctmp9,'(i2)') ngrdstop
+            WRITE(ctmp2,*) '           E R R O R detected in Agrif grid '//TRIM(ctmp9)
+            WRITE(ctmp3,*) '           Look for "E R R O R" messages in all existing '//TRIM(ctmp9)//'_ocean_output* files'
+            CALL ctl_stop( ' ', ctmp1, ' ', ctmp2, ' ', ctmp3 )
+         ELSE
+            WRITE(ctmp2,*) '           Look for "E R R O R" messages in all existing ocean_output* files'
+            CALL ctl_stop( ' ', ctmp1, ' ', ctmp2 )
+         ENDIF
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_finalize
+      !
+      CALL nemo_closefile
+      !
+#if defined key_iomput
+                                    CALL xios_finalize  ! end mpp communications with xios
+      IF( lk_oasis     )            CALL cpl_finalize   ! end coupling and mpp communications with OASIS
+#else
+      IF    ( lk_oasis ) THEN   ;   CALL cpl_finalize   ! end coupling and mpp communications with OASIS
+      ELSEIF( lk_mpp   ) THEN   ;   CALL mppstop      ! end mpp communications
+      ENDIF
+#endif
+      !
+      IF(lwm) THEN
+         IF( nstop == 0 ) THEN   ;   STOP 0
+         ELSE                    ;   STOP 123
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE nemo_gcm
+
+
+   SUBROUTINE nemo_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_init  ***
+      !!
+      !! ** Purpose :   initialization of the NEMO GCM
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, ilocal_comm   ! local integers
+      !!
+      NAMELIST/namctl/ ln_ctl   , sn_cfctl, nn_print, nn_ictls, nn_ictle,   &
+         &             nn_isplt , nn_jsplt, nn_jctls, nn_jctle,             &
+         &             ln_timing, ln_diacfl
+      NAMELIST/namcfg/ ln_read_cfg, cn_domcfg, ln_closea, ln_write_cfg, cn_domcfg_out, ln_use_jattr
+      !!----------------------------------------------------------------------
+      !
+      cxios_context = 'nemo'
+      !
+      !                             !-------------------------------------------------!
+      !                             !     set communicator & select the local rank    !
+      !                             !  must be done as soon as possible to get narea  !
+      !                             !-------------------------------------------------!
+      !
+#if defined key_iomput
+      IF( Agrif_Root() ) THEN
+         IF( lk_oasis ) THEN
+            CALL cpl_init( "oceanx", ilocal_comm )                               ! nemo local communicator given by oasis
+            CALL xios_initialize( "not used"       , local_comm =ilocal_comm )   ! send nemo communicator to xios
+         ELSE
+            CALL xios_initialize( "for_xios_mpi_id", return_comm=ilocal_comm )   ! nemo local communicator given by xios
+         ENDIF
+      ENDIF
+      CALL mpp_start( ilocal_comm )
+#else
+      IF( lk_oasis ) THEN
+         IF( Agrif_Root() ) THEN
+            CALL cpl_init( "oceanx", ilocal_comm )          ! nemo local communicator given by oasis
+         ENDIF
+         CALL mpp_start( ilocal_comm )
+      ELSE
+         CALL mpp_start( )
+      ENDIF
+#endif
+      !
+      narea = mpprank + 1               ! mpprank: the rank of proc (0 --> mppsize -1 )
+      lwm = (narea == 1)                ! control of output namelists
+      !
+      !                             !---------------------------------------------------------------!
+      !                             ! Open output files, reference and configuration namelist files !
+      !                             !---------------------------------------------------------------!
+      !
+      ! open ocean.output as soon as possible to get all output prints (including errors messages)
+      IF( lwm )   CALL ctl_opn(     numout,        'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open reference and configuration namelist files
+                  CALL ctl_opn( numnam_ref,        'namelist_ref',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+                  CALL ctl_opn( numnam_cfg,        'namelist_cfg',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      IF( lwm )   CALL ctl_opn(     numond, 'output.namelist.dyn', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open /dev/null file to be able to supress output write easily
+      IF( Agrif_Root() ) THEN
+                  CALL ctl_opn(     numnul,           '/dev/null', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+#ifdef key_agrif
+      ELSE
+                  numnul = Agrif_Parent(numnul)
+#endif
+      ENDIF
+      !
+      !                             !--------------------!
+      !                             ! Open listing units !  -> need ln_ctl from namctl to define lwp
+      !                             !--------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namctl in reference namelist
+      READ  ( numnam_ref, namctl, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namctl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namctl in confguration namelist
+      READ  ( numnam_cfg, namctl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namctl in configuration namelist' )
+      !
+      lwp = (narea == 1) .OR. ln_ctl    ! control of all listing output print
+      !
+      IF(lwp) THEN                      ! open listing units
+         !
+         IF( .NOT. lwm )   &            ! alreay opened for narea == 1
+            &            CALL ctl_opn( numout, 'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE., narea )
+         !
+         WRITE(numout,*)
+         WRITE(numout,*) '   CNRS - NERC - Met OFFICE - MERCATOR-ocean - CMCC'
+         WRITE(numout,*) '                       NEMO team'
+         WRITE(numout,*) '            Ocean General Circulation Model'
+         WRITE(numout,*) '                NEMO version 4.0  (2019) '
+         WRITE(numout,*)
+         WRITE(numout,*) "           ._      ._      ._      ._      ._    "
+         WRITE(numout,*) "       _.-._)`\_.-._)`\_.-._)`\_.-._)`\_.-._)`\_ "
+         WRITE(numout,*)
+         WRITE(numout,*) "           o         _,           _,             "
+         WRITE(numout,*) "            o      .' (        .-' /             "
+         WRITE(numout,*) "           o     _/..._'.    .'   /              "
+         WRITE(numout,*) "      (    o .-'`      ` '-./  _.'               "
+         WRITE(numout,*) "       )    ( o)           ;= <_         (       "
+         WRITE(numout,*) "      (      '-.,\\__ __.-;`\   '.        )      "
+         WRITE(numout,*) "       )  )       \) |`\ \)  '.   \      (   (   "
+         WRITE(numout,*) "      (  (           \_/       '-._\      )   )  "
+         WRITE(numout,*) "       )  ) jgs                     `    (   (   "
+         WRITE(numout,*) "     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
+         WRITE(numout,*)
+         !
+         WRITE(numout,cform_aaa)                                        ! Flag AAAAAAA
+         !
+      ENDIF
+      !
+      ! finalize the definition of namctl variables
+      IF( sn_cfctl%l_config ) THEN
+         ! Activate finer control of report outputs
+         ! optionally switch off output from selected areas (note this only
+         ! applies to output which does not involve global communications)
+         IF( ( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax  ) .OR. &
+           & ( MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 ) )    &
+           &   CALL nemo_set_cfctl( sn_cfctl, .FALSE., .FALSE. )
+      ELSE
+         ! Use ln_ctl to turn on or off all options.
+         CALL nemo_set_cfctl( sn_cfctl, ln_ctl, .TRUE. )
+      ENDIF
+      !
+      IF(lwm) WRITE( numond, namctl )
+      !
+      !                             !------------------------------------!
+      !                             !  Set global domain size parameters !
+      !                             !------------------------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namcfg in reference namelist
+      READ  ( numnam_ref, namcfg, IOSTAT = ios, ERR = 903 )
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcfg in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namcfg in confguration namelist
+      READ  ( numnam_cfg, namcfg, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcfg in configuration namelist' )   
+      !
+      IF( ln_read_cfg ) THEN            ! Read sizes in domain configuration file
+         CALL domain_cfg ( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ELSE                              ! user-defined namelist
+         CALL usr_def_nam( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ENDIF
+      !
+      IF(lwm)   WRITE( numond, namcfg )
+      !
+      !                             !-----------------------------------------!
+      !                             ! mpp parameters and domain decomposition !
+      !                             !-----------------------------------------!
+      CALL mpp_init
+
+      ! Now we know the dimensions of the grid and numout has been set: we can allocate arrays
+      CALL nemo_alloc()
+
+      !                             !-------------------------------!
+      !                             !  NEMO general initialization  !
+      !                             !-------------------------------!
+
+      CALL nemo_ctl                          ! Control prints
+      !
+      !                                      ! General initialization
+      IF( ln_timing    )   CALL timing_init     ! timing
+      IF( ln_timing    )   CALL timing_start( 'nemo_init')
+      !
+                           CALL     phy_cst         ! Physical constants
+                           CALL     eos_init        ! Equation of state
+      IF( lk_c1d       )   CALL     c1d_init        ! 1D column configuration
+                           CALL     wad_init        ! Wetting and drying options
+                           CALL     dom_init("OPA") ! Domain
+      IF( ln_crs       )   CALL     crs_init        ! coarsened grid: domain initialization 
+      IF( ln_ctl       )   CALL prt_ctl_init        ! Print control
+      
+      CALL diurnal_sst_bulk_init                ! diurnal sst
+      IF( ln_diurnal   )   CALL diurnal_sst_coolskin_init   ! cool skin   
+      !                            
+      IF( ln_diurnal_only ) THEN                   ! diurnal only: a subset of the initialisation routines
+         CALL  istate_init                            ! ocean initial state (Dynamics and tracers)
+         CALL     sbc_init                            ! Forcings : surface module
+         CALL tra_qsr_init                            ! penetrative solar radiation qsr
+         IF( ln_diaobs ) THEN                         ! Observation & model comparison
+            CALL dia_obs_init                            ! Initialize observational data
+            CALL dia_obs( nit000 - 1 )                   ! Observation operator for restart
+         ENDIF     
+         IF( lk_asminc )   CALL asm_inc_init          ! Assimilation increments
+         !
+         RETURN                                       ! end of initialization
+      ENDIF
+      
+                           CALL  istate_init    ! ocean initial state (Dynamics and tracers)
+
+      !                                      ! external forcing 
+                           CALL    tide_init    ! tidal harmonics
+                           CALL     sbc_init    ! surface boundary conditions (including sea-ice)
+                           CALL     bdy_init    ! Open boundaries initialisation
+
+      !                                      ! Ocean physics
+                           CALL zdf_phy_init    ! Vertical physics
+                                     
+      !                                         ! Lateral physics
+                           CALL ldf_tra_init      ! Lateral ocean tracer physics
+                           CALL ldf_eiv_init      ! eddy induced velocity param.
+                           CALL ldf_dyn_init      ! Lateral ocean momentum physics
+
+      !                                      ! Active tracers
+      IF( ln_traqsr    )   CALL tra_qsr_init      ! penetrative solar radiation qsr
+                           CALL tra_bbc_init      ! bottom heat flux
+                           CALL tra_bbl_init      ! advective (and/or diffusive) bottom boundary layer scheme
+                           CALL tra_dmp_init      ! internal tracer damping
+                           CALL tra_adv_init      ! horizontal & vertical advection
+                           CALL tra_ldf_init      ! lateral mixing
+
+      !                                      ! Dynamics
+      IF( lk_c1d       )   CALL dyn_dmp_init      ! internal momentum damping
+                           CALL dyn_adv_init      ! advection (vector or flux form)
+                           CALL dyn_vor_init      ! vorticity term including Coriolis
+                           CALL dyn_ldf_init      ! lateral mixing
+                           CALL dyn_hpg_init      ! horizontal gradient of Hydrostatic pressure
+                           CALL dyn_spg_init      ! surface pressure gradient
+
+#if defined key_top
+      !                                      ! Passive tracers
+                           CALL     trc_init
+#endif
+      IF( l_ldfslp     )   CALL ldf_slp_init    ! slope of lateral mixing
+
+      !                                      ! Icebergs
+                           CALL icb_init( rdt, nit000)   ! initialise icebergs instance
+
+      !                                      ! Misc. options
+                           CALL sto_par_init    ! Stochastic parametrization
+      IF( ln_sto_eos   )   CALL sto_pts_init    ! RRandom T/S fluctuations
+     
+      !                                      ! Diagnostics
+                           CALL     flo_init    ! drifting Floats
+      IF( ln_diacfl    )   CALL dia_cfl_init    ! Initialise CFL diagnostics
+                           CALL dia_ptr_init    ! Poleward TRansports initialization
+                           CALL dia_dct_init    ! Sections tranports
+                           CALL dia_hsb_init    ! heat content, salt content and volume budgets
+                           CALL     trd_init    ! Mixed-layer/Vorticity/Integral constraints trends
+                           CALL dia_obs_init    ! Initialize observational data
+                           CALL dia_25h_init    ! 25h mean  outputs
+                           CALL dia_harm_init   ! tidal harmonics outputs
+     IF( ln_diaobs    )    CALL dia_obs( nit000-1 )   ! Observation operator for restart
+
+      !                                      ! Assimilation increments
+      IF( lk_asminc    )   CALL asm_inc_init    ! Initialize assimilation increments
+      !
+      IF(lwp) WRITE(numout,cform_aaa)           ! Flag AAAAAAA
+      !
+      IF( ln_timing    )   CALL timing_stop( 'nemo_init')
+      !
+   END SUBROUTINE nemo_init
+
+
+   SUBROUTINE nemo_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_ctl  ***
+      !!
+      !! ** Purpose :   control print setting
+      !!
+      !! ** Method  : - print namctl and namcfg information and check some consistencies
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'nemo_ctl: Control prints'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist namctl'
+         WRITE(numout,*) '      run control (for debugging)     ln_ctl     = ', ln_ctl
+         WRITE(numout,*) '       finer control over o/p sn_cfctl%l_config  = ', sn_cfctl%l_config
+         WRITE(numout,*) '                              sn_cfctl%l_runstat = ', sn_cfctl%l_runstat
+         WRITE(numout,*) '                              sn_cfctl%l_trcstat = ', sn_cfctl%l_trcstat
+         WRITE(numout,*) '                              sn_cfctl%l_oceout  = ', sn_cfctl%l_oceout
+         WRITE(numout,*) '                              sn_cfctl%l_layout  = ', sn_cfctl%l_layout
+         WRITE(numout,*) '                              sn_cfctl%l_mppout  = ', sn_cfctl%l_mppout
+         WRITE(numout,*) '                              sn_cfctl%l_mpptop  = ', sn_cfctl%l_mpptop
+         WRITE(numout,*) '                              sn_cfctl%procmin   = ', sn_cfctl%procmin  
+         WRITE(numout,*) '                              sn_cfctl%procmax   = ', sn_cfctl%procmax  
+         WRITE(numout,*) '                              sn_cfctl%procincr  = ', sn_cfctl%procincr 
+         WRITE(numout,*) '                              sn_cfctl%ptimincr  = ', sn_cfctl%ptimincr 
+         WRITE(numout,*) '      level of print                  nn_print   = ', nn_print
+         WRITE(numout,*) '      Start i indice for SUM control  nn_ictls   = ', nn_ictls
+         WRITE(numout,*) '      End i indice for SUM control    nn_ictle   = ', nn_ictle
+         WRITE(numout,*) '      Start j indice for SUM control  nn_jctls   = ', nn_jctls
+         WRITE(numout,*) '      End j indice for SUM control    nn_jctle   = ', nn_jctle
+         WRITE(numout,*) '      number of proc. following i     nn_isplt   = ', nn_isplt
+         WRITE(numout,*) '      number of proc. following j     nn_jsplt   = ', nn_jsplt
+         WRITE(numout,*) '      timing by routine               ln_timing  = ', ln_timing
+         WRITE(numout,*) '      CFL diagnostics                 ln_diacfl  = ', ln_diacfl
+      ENDIF
+      !
+      nprint    = nn_print          ! convert DOCTOR namelist names into OLD names
+      nictls    = nn_ictls
+      nictle    = nn_ictle
+      njctls    = nn_jctls
+      njctle    = nn_jctle
+      isplt     = nn_isplt
+      jsplt     = nn_jsplt
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namcfg'
+         WRITE(numout,*) '      read domain configuration file                ln_read_cfg      = ', ln_read_cfg
+         WRITE(numout,*) '         filename to be read                           cn_domcfg     = ', TRIM(cn_domcfg)
+         WRITE(numout,*) '         keep closed seas in the domain (if exist)     ln_closea     = ', ln_closea
+         WRITE(numout,*) '      create a configuration definition file        ln_write_cfg     = ', ln_write_cfg
+         WRITE(numout,*) '         filename to be written                        cn_domcfg_out = ', TRIM(cn_domcfg_out)
+         WRITE(numout,*) '      use file attribute if exists as i/p j-start   ln_use_jattr     = ', ln_use_jattr
+      ENDIF
+      IF( .NOT.ln_read_cfg )   ln_closea = .false.   ! dealing possible only with a domcfg file
+      !
+      !                             ! Parameter control
+      !
+      IF( ln_ctl ) THEN                 ! sub-domain area indices for the control prints
+         IF( lk_mpp .AND. jpnij > 1 ) THEN
+            isplt = jpni   ;   jsplt = jpnj   ;   ijsplt = jpni*jpnj   ! the domain is forced to the real split domain
+         ELSE
+            IF( isplt == 1 .AND. jsplt == 1  ) THEN
+               CALL ctl_warn( ' - isplt & jsplt are equal to 1',   &
+                  &           ' - the print control will be done over the whole domain' )
+            ENDIF
+            ijsplt = isplt * jsplt            ! total number of processors ijsplt
+         ENDIF
+         IF(lwp) WRITE(numout,*)'          - The total number of processors over which the'
+         IF(lwp) WRITE(numout,*)'            print control will be done is ijsplt : ', ijsplt
+         !
+         !                              ! indices used for the SUM control
+         IF( nictls+nictle+njctls+njctle == 0 )   THEN    ! print control done over the default area
+            lsp_area = .FALSE.
+         ELSE                                             ! print control done over a specific  area
+            lsp_area = .TRUE.
+            IF( nictls < 1 .OR. nictls > jpiglo )   THEN
+               CALL ctl_warn( '          - nictls must be 1<=nictls>=jpiglo, it is forced to 1' )
+               nictls = 1
+            ENDIF
+            IF( nictle < 1 .OR. nictle > jpiglo )   THEN
+               CALL ctl_warn( '          - nictle must be 1<=nictle>=jpiglo, it is forced to jpiglo' )
+               nictle = jpiglo
+            ENDIF
+            IF( njctls < 1 .OR. njctls > jpjglo )   THEN
+               CALL ctl_warn( '          - njctls must be 1<=njctls>=jpjglo, it is forced to 1' )
+               njctls = 1
+            ENDIF
+            IF( njctle < 1 .OR. njctle > jpjglo )   THEN
+               CALL ctl_warn( '          - njctle must be 1<=njctle>=jpjglo, it is forced to jpjglo' )
+               njctle = jpjglo
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( 1._wp /= SIGN(1._wp,-0._wp)  )   CALL ctl_stop( 'nemo_ctl: The intrinsec SIGN function follows f2003 standard.',  &
+         &                                                'Compile with key_nosignedzero enabled:',   &
+         &                                                '--> add -Dkey_nosignedzero to the definition of %CPP in your arch file' )
+      !
+#if defined key_agrif
+      IF( ln_timing )   CALL ctl_stop( 'AGRIF not implemented with ln_timing = true')
+#endif
+      !
+   END SUBROUTINE nemo_ctl
+
+
+   SUBROUTINE nemo_closefile
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_closefile  ***
+      !!
+      !! ** Purpose :   Close the files
+      !!----------------------------------------------------------------------
+      !
+      IF( lk_mpp )   CALL mppsync
+      !
+      CALL iom_close                                 ! close all input/output files managed by iom_*
+      !
+      IF( numstp          /= -1 )   CLOSE( numstp          )   ! time-step file
+      IF( numrun          /= -1 )   CLOSE( numrun          )   ! run statistics file
+      IF( numnam_ref      /= -1 )   CLOSE( numnam_ref      )   ! oce reference namelist
+      IF( numnam_cfg      /= -1 )   CLOSE( numnam_cfg      )   ! oce configuration namelist
+      IF( lwm.AND.numond  /= -1 )   CLOSE( numond          )   ! oce output namelist
+      IF( numnam_ice_ref  /= -1 )   CLOSE( numnam_ice_ref  )   ! ice reference namelist
+      IF( numnam_ice_cfg  /= -1 )   CLOSE( numnam_ice_cfg  )   ! ice configuration namelist
+      IF( lwm.AND.numoni  /= -1 )   CLOSE( numoni          )   ! ice output namelist
+      IF( numevo_ice      /= -1 )   CLOSE( numevo_ice      )   ! ice variables (temp. evolution)
+      IF( numout          /=  6 )   CLOSE( numout          )   ! standard model output file
+      IF( numdct_vol      /= -1 )   CLOSE( numdct_vol      )   ! volume transports
+      IF( numdct_heat     /= -1 )   CLOSE( numdct_heat     )   ! heat transports
+      IF( numdct_salt     /= -1 )   CLOSE( numdct_salt     )   ! salt transports
+      !
+      numout = 6                                     ! redefine numout in case it is used after this point...
+      !
+   END SUBROUTINE nemo_closefile
+
+
+   SUBROUTINE nemo_alloc
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_alloc  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!
+      !! ** Method  :
+      !!----------------------------------------------------------------------
+      USE diawri    , ONLY : dia_wri_alloc
+      USE dom_oce   , ONLY : dom_oce_alloc
+      USE trc_oce   , ONLY : trc_oce_alloc
+      USE bdy_oce   , ONLY : bdy_oce_alloc
+      !
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ierr =        oce_alloc    ()    ! ocean 
+      ierr = ierr + dia_wri_alloc()
+      ierr = ierr + dom_oce_alloc()    ! ocean domain
+      ierr = ierr + zdf_oce_alloc()    ! ocean vertical physics
+      ierr = ierr + trc_oce_alloc()    ! shared TRC / TRA arrays
+      ierr = ierr + bdy_oce_alloc()    ! bdy masks (incl. initialization)
+      !
+      CALL mpp_sum( 'nemogcm', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'nemo_alloc: unable to allocate standard ocean arrays' )
+      !
+   END SUBROUTINE nemo_alloc
+
+   
+   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto, for_all )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_set_cfctl  ***
+      !!
+      !! ** Purpose :   Set elements of the output control structure to setto.
+      !!                for_all should be .false. unless all areas are to be
+      !!                treated identically.
+      !!
+      !! ** Method  :   Note this routine can be used to switch on/off some
+      !!                types of output for selected areas but any output types
+      !!                that involve global communications (e.g. mpp_max, glob_sum)
+      !!                should be protected from selective switching by the
+      !!                for_all argument
+      !!----------------------------------------------------------------------
+      LOGICAL :: setto, for_all
+      TYPE(sn_ctl) :: sn_cfctl
+      !!----------------------------------------------------------------------
+      IF( for_all ) THEN
+         sn_cfctl%l_runstat = setto
+         sn_cfctl%l_trcstat = setto
+      ENDIF
+      sn_cfctl%l_oceout  = setto
+      sn_cfctl%l_layout  = setto
+      sn_cfctl%l_mppout  = setto
+      sn_cfctl%l_mpptop  = setto
+   END SUBROUTINE nemo_set_cfctl
+
+   !!======================================================================
+END MODULE nemogcm
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/oce.F90	(revision 14097)
@@ -0,0 +1,122 @@
+MODULE oce
+   !!======================================================================
+   !!                      ***  MODULE  oce  ***
+   !! Ocean        :  dynamics and active tracers defined in memory 
+   !!======================================================================
+   !! History :  1.0  !  2002-11  (G. Madec)  F90: Free form and module
+   !!            3.1  !  2009-02  (G. Madec, M. Leclair)  pure z* coordinate
+   !!            3.3  !  2010-09  (C. Ethe) TRA-TRC merge: add ts, gtsu, gtsv 4D arrays
+   !!            3.7  !  2014-01  (G. Madec) suppression of curl and before hdiv from in-core memory
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC oce_alloc ! routine called by nemo_init in nemogcm.F90
+
+   !! 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(:,:,:)   ::           wn             !: vertical velocity            [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::           wi             !: vertical vel. (adaptive-implicit) [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::           hdivn          !: horizontal divergence        [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   tsb  ,  tsn   , tsa    !: 4D T-S fields                  [Celsius,psu] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   rab_b,  rab_n          !: thermal/haline expansion coef. [Celsius-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]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   rhop   !: potential volumic mass                           [kg/m3]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   Cu_adv                   !: vertical Courant number (adaptive-implicit)
+
+   !! free surface                                      !  before  ! now    ! after  !
+   !! ------------                                      !  fields  ! fields ! fields !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ub_b   ,  un_b  ,  ua_b  !: Barotropic velocities at u-point [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   vb_b   ,  vn_b  ,  va_b  !: Barotropic velocities at v-point [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sshb   ,  sshn  ,  ssha  !: sea surface height at t-point [m]
+
+   !! Arrays at barotropic time step:                   ! befbefore! before !  now   ! after  !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ubb_e  ,  ub_e  ,  un_e  , ua_e   !: u-external velocity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   vbb_e  ,  vb_e  ,  vn_e  , va_e   !: v-external velocity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sshbb_e,  sshb_e,  sshn_e, ssha_e !: external ssh
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::                              hu_e   !: external u-depth
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::                              hv_e   !: external v-depth
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::                              hur_e  !: inverse of u-depth
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::                              hvr_e  !: inverse of v-depth
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ub2_b  , vb2_b           !: Half step fluxes (ln_bt_fw=T)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   un_bf  , vn_bf           !: Asselin filtered half step fluxes (ln_bt_fw=T)
+#if defined key_agrif
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ub2_i_b, vb2_i_b         !: Half step time integrated fluxes 
+#endif
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   spgu, spgv               !: horizontal surface pressure gradient
+
+   !! interpolated gradient (only used in zps case)
+   !! ---------------------
+   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
+
+   !! (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  
+   !! (ISF) ice load
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riceload
+
+   !! 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 [-]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION oce_alloc()
+      !!----------------------------------------------------------------------
+      !!                   ***  FUNCTION oce_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(6)
+      !!----------------------------------------------------------------------
+      !
+      ierr(:) = 0 
+      ALLOCATE( ub   (jpi,jpj,jpk)      , un   (jpi,jpj,jpk)      , ua(jpi,jpj,jpk)       ,     &
+         &      vb   (jpi,jpj,jpk)      , vn   (jpi,jpj,jpk)      , va(jpi,jpj,jpk)       ,     &          
+         &      wn   (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)      ,                             &
+         &      rhd  (jpi,jpj,jpk)      , rhop (jpi,jpj,jpk)                              , STAT=ierr(1) )
+         !
+      ALLOCATE( sshb(jpi,jpj)     , sshn(jpi,jpj)   , ssha(jpi,jpj)   ,     &
+         &      ub_b(jpi,jpj)     , un_b(jpi,jpj)   , ua_b(jpi,jpj)   ,     &
+         &      vb_b(jpi,jpj)     , vn_b(jpi,jpj)   , va_b(jpi,jpj)   ,     &
+         &      spgu  (jpi,jpj)   , spgv(jpi,jpj)                     ,     &
+         &      gtsu(jpi,jpj,jpts), gtsv(jpi,jpj,jpts)                ,     &
+         &      gru(jpi,jpj)      , grv(jpi,jpj)                      ,     &
+         &      gtui(jpi,jpj,jpts), gtvi(jpi,jpj,jpts)                ,     &
+         &      grui(jpi,jpj)     , grvi(jpi,jpj)                     ,     &
+         &      riceload(jpi,jpj)                                     , STAT=ierr(2) )
+         !
+      ALLOCATE( fraqsr_1lev(jpi,jpj) , STAT=ierr(3) )
+         !
+      ALLOCATE( ssha_e(jpi,jpj),  sshn_e(jpi,jpj), sshb_e(jpi,jpj), sshbb_e(jpi,jpj), &
+         &        ua_e(jpi,jpj),    un_e(jpi,jpj),   ub_e(jpi,jpj),   ubb_e(jpi,jpj), &
+         &        va_e(jpi,jpj),    vn_e(jpi,jpj),   vb_e(jpi,jpj),   vbb_e(jpi,jpj), &
+         &        hu_e(jpi,jpj),   hur_e(jpi,jpj),   hv_e(jpi,jpj),   hvr_e(jpi,jpj), STAT=ierr(4) )
+         !
+      ALLOCATE( ub2_b(jpi,jpj), vb2_b(jpi,jpj), un_bf(jpi,jpj), vn_bf(jpi,jpj)      , STAT=ierr(6) )
+#if defined key_agrif
+      ALLOCATE( ub2_i_b(jpi,jpj), vb2_i_b(jpi,jpj)                                  , STAT=ierr(6) )
+#endif
+         !
+      oce_alloc = MAXVAL( ierr )
+      IF( oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'oce_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION oce_alloc
+
+   !!======================================================================
+END MODULE oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_kind.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_kind.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_kind.F90	(revision 14097)
@@ -0,0 +1,40 @@
+MODULE par_kind
+   !!======================================================================
+   !!                   ***  MODULE par_kind  ***
+   !! Ocean :  define the kind of real for the whole model
+   !!======================================================================
+   !! History :  1.0  ! 2002-06  (G. Madec)  Original code
+   !!            3.3  ! 2010-12  (G. Madec)  add a standard length of character strings
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTEGER, PUBLIC, PARAMETER ::   jpbyt   = 8    !: real size for mpp communications
+   INTEGER, PUBLIC, PARAMETER ::   jpbytda = 4    !: real size in input data files 4 or 8
+
+   ! Number model from which the SELECTED_*_KIND are requested:
+   !             4 byte REAL       8 byte REAL
+   ! CRAY:           -            precision = 13
+   !                              exponent = 2465
+   ! IEEE:      precision = 6     precision = 15
+   !            exponent = 37     exponent = 307
+
+   !                                                                !!** Floating point **
+   INTEGER, PUBLIC, PARAMETER ::   sp = SELECTED_REAL_KIND( 6, 37)   !: single precision (real 4)
+   INTEGER, PUBLIC, PARAMETER ::   dp = SELECTED_REAL_KIND(12,307)   !: double precision (real 8)
+   INTEGER, PUBLIC, PARAMETER ::   wp = dp                              !: working precision
+
+   !                                                                !!** Integer **
+   INTEGER, PUBLIC, PARAMETER ::   i4 = SELECTED_INT_KIND( 9)        !: single precision (integer 4)
+   INTEGER, PUBLIC, PARAMETER ::   i8 = SELECTED_INT_KIND(14)        !: double precision (integer 8)
+   
+   !                                                                !!** Integer **
+   INTEGER, PUBLIC, PARAMETER ::   lc = 256                          !: Lenght of Character strings
+
+   !!----------------------------------------------------------------------
+   !! NEMO 3.3 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+END MODULE par_kind
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/par_oce.F90	(revision 14097)
@@ -0,0 +1,83 @@
+MODULE par_oce
+   !!======================================================================
+   !!                        ***  par_oce  ***
+   !! Ocean :   set the ocean parameters
+   !!======================================================================
+   !! History :  OPA  !  1991     (Imbard, Levy, Madec)  Original code
+   !!   NEMO     1.0  !  2004-01  (G. Madec, J.-M. Molines)  Free form and module
+   !!            3.3  !  2010-09  (C. Ethe) TRA-TRC merge: add jpts, jp_tem & jp_sal
+   !!----------------------------------------------------------------------
+   USE par_kind          ! kind parameters
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !!----------------------------------------------------------------------
+   !!                   namcfg namelist parameters
+   !!----------------------------------------------------------------------
+   LOGICAL       ::   ln_read_cfg      !: (=T) read the domain configuration file or (=F) not
+   CHARACTER(lc) ::      cn_domcfg        !: filename the configuration file to be read
+   LOGICAL       ::   ln_write_cfg     !: (=T) create the domain configuration file
+   CHARACTER(lc) ::      cn_domcfg_out    !: filename the configuration file to be read
+   !
+   LOGICAL       ::   ln_use_jattr     !: input file read offset
+   !                                   !  Use file global attribute: open_ocean_jstart to determine start j-row 
+   !                                   !  when reading input from those netcdf files that have the 
+   !                                   !  attribute defined. This is designed to enable input files associated 
+   !                                   !  with the extended grids used in the under ice shelf configurations to 
+   !                                   !  be used without redundant rows when the ice shelves are not in use.
+   ! 
+
+   !!---------------------------------------------------------------------
+   !! Domain Matrix size 
+   !!---------------------------------------------------------------------
+   ! configuration name & resolution   (required only in ORCA family case)
+   CHARACTER(lc) ::   cn_cfg           !: name of the configuration
+   INTEGER       ::   nn_cfg           !: resolution of the configuration 
+
+   ! global domain size               !!! * total computational domain *
+   INTEGER       ::   jpiglo           !: 1st dimension of global domain --> i-direction
+   INTEGER       ::   jpjglo           !: 2nd    -                  -    --> j-direction
+   INTEGER       ::   jpkglo           !: 3nd    -                  -    --> k levels
+
+   ! global domain size for AGRIF     !!! * total AGRIF computational domain *
+   INTEGER, PUBLIC            ::   nbug_in_agrif_conv_do_not_remove_or_modify = 1 - 1
+   INTEGER, PUBLIC, PARAMETER ::   nbghostcells = 3                             !: number of ghost cells
+   INTEGER, PUBLIC            ::   nbcellsx   ! = jpiglo - 2 - 2*nbghostcells   !: number of cells in i-direction
+   INTEGER, PUBLIC            ::   nbcellsy   ! = jpjglo - 2 - 2*nbghostcells   !: number of cells in j-direction
+
+   ! local domain size                !!! * local computational domain *
+   INTEGER, PUBLIC ::   jpi   !                                                    !: first  dimension
+   INTEGER, PUBLIC ::   jpj   !                                                    !: second dimension
+   INTEGER, PUBLIC ::   jpk   ! = jpkglo                                           !: third  dimension
+   INTEGER, PUBLIC ::   jpim1 ! = jpi-1                                            !: inner domain indices
+   INTEGER, PUBLIC ::   jpjm1 ! = jpj-1                                            !:   -     -      -
+   INTEGER, PUBLIC ::   jpkm1 ! = jpk-1                                            !:   -     -      -
+   INTEGER, PUBLIC ::   jpij  ! = jpi*jpj                                          !:  jpi x jpj
+   INTEGER, PUBLIC ::   jpimax! = ( jpiglo-2*nn_hls + (jpni-1) ) / jpni + 2*nn_hls !: maximum jpi
+   INTEGER, PUBLIC ::   jpjmax! = ( jpjglo-2*nn_hls + (jpnj-1) ) / jpnj + 2*nn_hls !: maximum jpj
+
+   !!---------------------------------------------------------------------
+   !! Active tracer parameters
+   !!---------------------------------------------------------------------
+   INTEGER, PUBLIC, PARAMETER ::   jpts   = 2    !: Number of active tracers (=2, i.e. T & S )
+   INTEGER, PUBLIC, PARAMETER ::   jp_tem = 1    !: indice for temperature
+   INTEGER, PUBLIC, PARAMETER ::   jp_sal = 2    !: indice for salinity
+
+   !!----------------------------------------------------------------------
+   !!   Domain decomposition
+   !!----------------------------------------------------------------------
+   !! if we dont use massively parallel computer (parameters jpni=jpnj=1) so jpiglo=jpi and jpjglo=jpj
+   INTEGER, PUBLIC            ::   jpni         !: number of processors following i 
+   INTEGER, PUBLIC            ::   jpnj         !: number of processors following j
+   INTEGER, PUBLIC            ::   jpnij        !: nb of local domain = nb of processors ( <= jpni x jpnj )
+   INTEGER, PUBLIC, PARAMETER ::   jpr2di = 0   !: number of columns for extra outer halo 
+   INTEGER, PUBLIC, PARAMETER ::   jpr2dj = 0   !: number of rows    for extra outer halo 
+   INTEGER, PUBLIC, PARAMETER ::   nn_hls = 1   !: halo width (applies to both rows and columns)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE par_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step.F90	(revision 14097)
@@ -0,0 +1,331 @@
+MODULE step
+   !!======================================================================
+   !!                       ***  MODULE step  ***
+   !! Time-stepping   : manager of the ocean, tracer and ice time stepping
+   !!======================================================================
+   !! History :  OPA  !  1991-03  (G. Madec)  Original code
+   !!             -   !  1991-11  (G. Madec)
+   !!             -   !  1992-06  (M. Imbard)  add a first output record
+   !!             -   !  1996-04  (G. Madec)  introduction of dynspg
+   !!             -   !  1996-04  (M.A. Foujols)  introduction of passive tracer
+   !!            8.0  !  1997-06  (G. Madec)  new architecture of call
+   !!            8.2  !  1997-06  (G. Madec, M. Imbard, G. Roullet)  free surface
+   !!             -   !  1999-02  (G. Madec, N. Grima)  hpg implicit
+   !!             -   !  2000-07  (J-M Molines, M. Imbard)  Open Bondary Conditions
+   !!   NEMO     1.0  !  2002-06  (G. Madec)  free form, suppress macro-tasking
+   !!             -   !  2004-08  (C. Talandier) New trends organization
+   !!             -   !  2005-01  (C. Ethe) Add the KPP closure scheme
+   !!             -   !  2005-11  (G. Madec)  Reorganisation of tra and dyn calls
+   !!             -   !  2006-01  (L. Debreu, C. Mazauric)  Agrif implementation
+   !!             -   !  2006-07  (S. Masson)  restart using iom
+   !!            3.2  !  2009-02  (G. Madec, R. Benshila)  reintroduicing z*-coordinate
+   !!             -   !  2009-06  (S. Masson, G. Madec)  TKE restart compatible with key_cpl
+   !!            3.3  !  2010-05  (K. Mogensen, A. Weaver, M. Martin, D. Lea) Assimilation interface
+   !!             -   !  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
+   !!            3.6  !  2012-07  (J. Simeon, G. Madec. C. Ethe)  Online coarsening of outputs
+   !!            3.6  !  2014-04  (F. Roquet, G. Madec) New equations of state
+   !!            3.6  !  2014-10  (E. Clementi, P. Oddo) Add Qiao vertical mixing in case of waves
+   !!            3.7  !  2014-10  (G. Madec)  LDF simplication 
+   !!             -   !  2014-12  (G. Madec) remove KPP scheme
+   !!             -   !  2015-11  (J. Chanut) free surface simplification (remove filtered free surface)
+   !!            4.0  !  2017-05  (G. Madec)  introduction of the vertical physics manager (zdfphy)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   stp             : OPA system time-stepping
+   !!----------------------------------------------------------------------
+   USE step_oce         ! time stepping definition modules
+   !
+   USE iom              ! xIOs server
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   stp   ! called by nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if defined key_agrif
+   RECURSIVE SUBROUTINE stp( )
+      INTEGER             ::   kstp   ! ocean time-step index
+#else
+   SUBROUTINE stp( kstp )
+      INTEGER, INTENT(in) ::   kstp   ! ocean time-step index
+#endif
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE stp  ***
+      !!
+      !! ** Purpose : - Time stepping of OPA  (momentum and active tracer eqs.)
+      !!              - Time stepping of SI3 (dynamic and thermodynamic eqs.)
+      !!              - Time stepping of TRC  (passive tracer eqs.)
+      !!
+      !! ** Method  : -1- Update forcings and data
+      !!              -2- Update ocean physics
+      !!              -3- Compute the t and s trends
+      !!              -4- Update t and s
+      !!              -5- Compute the momentum trends
+      !!              -6- Update the horizontal velocity
+      !!              -7- Compute the diagnostics variables (rd,N2, hdiv,w)
+      !!              -8- Outputs and diagnostics
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk   ! dummy loop indice
+!!gm kcall can be removed, I guess
+      INTEGER ::   kcall        ! optional integer argument (dom_vvl_sf_nxt)
+      !! ---------------------------------------------------------------------
+#if defined key_agrif
+      IF( nstop > 0 ) RETURN   ! avoid to go further if an error was detected during previous time step (child grid)
+      kstp = nit000 + Agrif_Nb_Step()
+      IF( lk_agrif_debug ) THEN
+         IF( Agrif_Root() .and. lwp)   WRITE(*,*) '---'
+         IF(lwp)   WRITE(*,*) 'Grid Number', Agrif_Fixed(),' time step ', kstp, 'int tstep', Agrif_NbStepint()
+      ENDIF
+      IF( kstp == nit000 + 1 )   lk_agrif_fstep = .FALSE.
+# if defined key_iomput
+      IF( Agrif_Nbstepint() == 0 )   CALL iom_swap( cxios_context )
+# endif
+#endif
+      !
+      IF( ln_timing )   CALL timing_start('stp')
+      !
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! update I/O and calendar 
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( kstp == nit000 ) THEN                       ! initialize IOM context (must be done after nemo_init for AGRIF+XIOS+OASIS)
+                             CALL iom_init(      cxios_context          )  ! for model grid (including passible AGRIF zoom)
+         IF( ln_crs      )   CALL iom_init( TRIM(cxios_context)//"_crs" )  ! for coarse grid
+      ENDIF
+      IF( kstp /= nit000 )   CALL day( kstp )         ! Calendar (day was already called at nit000 in day_init)
+                             CALL iom_setkt( kstp - nit000 + 1,      cxios_context          )   ! tell IOM we are at time step kstp
+      IF( ln_crs         )   CALL iom_setkt( kstp - nit000 + 1, TRIM(cxios_context)//"_crs" )   ! tell IOM we are at time step kstp
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Update external forcing (tides, open boundaries, and surface boundary condition (including sea-ice)
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_tide    )   CALL sbc_tide( kstp )                   ! update tide potential
+      IF( ln_apr_dyn )   CALL sbc_apr ( kstp )                   ! atmospheric pressure (NB: call before bdy_dta which needs ssh_ib) 
+      IF( ln_bdy     )   CALL bdy_dta ( kstp, kt_offset = +1 )   ! update dynamic & tracer data at open boundaries
+                         CALL sbc     ( kstp )                   ! Sea Boundary Condition (including sea-ice)
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Update stochastic parameters and random T/S fluctuations
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      IF( ln_sto_eos ) CALL sto_par( kstp )          ! Stochastic parameters
+      IF( ln_sto_eos ) CALL sto_pts( tsn  )          ! Random T/S fluctuations
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Ocean physics update
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !  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
+                         CALL zdf_phy( kstp )         ! vertical physics update (top/bot drag, avt, avs, avm + MLD)
+
+      !  LATERAL  PHYSICS
+      !
+      IF( l_ldfslp ) THEN                             ! slope of lateral mixing
+                         CALL eos( tsb, rhd, gdept_0(:,:,:) )               ! before in situ density
+
+         IF( ln_zps .AND. .NOT. ln_isfcav)                               &
+            &            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 .AND.       ln_isfcav)                               &
+            &            CALL zps_hde_isf( kstp, jpts, tsb, gtsu, gtsv, gtui, gtvi,  &  ! Partial steps for top cell (ISF)
+            &                                          rhd, gru , grv , grui, grvi   )  ! of t, s, rd at the first ocean level
+         IF( ln_traldf_triad ) THEN 
+                         CALL ldf_slp_triad( kstp )                       ! before slope for triad operator
+         ELSE     
+                         CALL ldf_slp     ( kstp, rhd, rn2b )             ! before slope for standard operator
+         ENDIF
+      ENDIF
+      !                                                                   ! eddy diffusivity coeff.
+      IF( l_ldftra_time .OR. l_ldfeiv_time )   CALL ldf_tra( kstp )       !       and/or eiv coeff.
+      IF( l_ldfdyn_time                    )   CALL ldf_dyn( kstp )       ! eddy viscosity coeff. 
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      !  Ocean dynamics : hdiv, ssh, e3, u, v, w
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+
+                            CALL ssh_nxt       ( kstp )  ! after ssh (includes call to div_hor)
+      IF( .NOT.ln_linssh )  CALL dom_vvl_sf_nxt( kstp )  ! after vertical scale factors 
+                            CALL wzv           ( kstp )  ! now cross-level velocity 
+      IF( ln_zad_Aimp )     CALL wAimp         ( kstp )  ! Adaptive-implicit vertical advection partitioning
+                            CALL eos    ( tsn, rhd, rhop, gdept_n(:,:,:) )  ! now in situ density for hpg computation
+                            
+                            
+                         ua(:,:,:) = 0._wp            ! set dynamics trends to zero
+                         va(:,:,:) = 0._wp
+
+      IF(  lk_asminc .AND. ln_asmiau .AND. ln_dyninc )   &
+               &         CALL dyn_asm_inc   ( kstp )  ! apply dynamics assimilation increment
+      IF( ln_bdy     )   CALL bdy_dyn3d_dmp ( kstp )  ! bdy damping trends
+#if defined key_agrif
+      IF(.NOT. Agrif_Root())  & 
+               &         CALL Agrif_Sponge_dyn        ! momentum sponge
+#endif
+                         CALL dyn_adv       ( kstp )  ! advection (vector or flux form)
+                         CALL dyn_vor       ( kstp )  ! vorticity term including Coriolis
+                         CALL dyn_ldf       ( kstp )  ! lateral mixing
+      IF( ln_zdfosm  )   CALL dyn_osm       ( kstp )  ! OSMOSIS non-local velocity fluxes
+                         CALL dyn_hpg       ( kstp )  ! horizontal gradient of Hydrostatic pressure
+                         CALL dyn_spg       ( kstp )  ! surface pressure gradient
+
+                                                      ! With split-explicit free surface, since now transports have been updated and ssha as well
+      IF( ln_dynspg_ts ) THEN                         ! vertical scale factors and vertical velocity need to be updated
+                            CALL div_hor    ( kstp )              ! Horizontal divergence  (2nd call in time-split case)
+         IF(.NOT.ln_linssh) CALL dom_vvl_sf_nxt( kstp, kcall=2 )  ! after vertical scale factors (update depth average component)
+      ENDIF
+                            CALL dyn_zdf    ( kstp )  ! vertical diffusion
+      IF( ln_dynspg_ts ) THEN                         ! vertical scale factors and vertical velocity need to be updated
+                            CALL wzv        ( kstp )              ! now cross-level velocity 
+         IF( ln_zad_Aimp )  CALL wAimp      ( kstp )  ! Adaptive-implicit vertical advection partitioning
+      ENDIF
+      
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! cool skin
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+      IF ( ln_diurnal )  CALL stp_diurnal( kstp )
+      
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! diagnostics and outputs
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_floats  )   CALL flo_stp ( kstp )        ! drifting Floats
+      IF( ln_diacfl  )   CALL dia_cfl ( kstp )        ! Courant number diagnostics
+                         CALL dia_hth ( kstp )        ! Thermocline depth (20 degres isotherm depth)
+      IF( ln_diadct  )   CALL dia_dct ( kstp )        ! Transports
+                         CALL dia_ar5 ( kstp )        ! ar5 diag
+      IF( ln_diaptr  )   CALL dia_ptr                 ! Poleward adv/ldf TRansports diagnostics
+      IF( ln_diaharm )   CALL dia_harm( kstp )        ! Tidal harmonic analysis
+                         CALL dia_wri ( kstp )        ! ocean model: outputs
+      !
+      IF( ln_crs     )   CALL crs_fld       ( kstp )  ! ocean model: online field coarsening & output
+      
+#if defined key_top
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Passive Tracer Model
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         CALL trc_stp       ( kstp )  ! time-stepping
+#endif
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Active tracers                              
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         tsa(:,:,:,:) = 0._wp         ! set tracer trends to zero
+
+      IF(  lk_asminc .AND. ln_asmiau .AND. &
+         & ln_trainc )   CALL tra_asm_inc   ( kstp )  ! apply tracer assimilation increment
+                         CALL tra_sbc       ( kstp )  ! surface boundary condition
+      IF( ln_traqsr  )   CALL tra_qsr       ( kstp )  ! penetrative solar radiation qsr
+      IF( ln_trabbc  )   CALL tra_bbc       ( kstp )  ! bottom heat flux
+      IF( ln_trabbl  )   CALL tra_bbl       ( kstp )  ! advective (and/or diffusive) bottom boundary layer scheme
+      IF( ln_tradmp  )   CALL tra_dmp       ( kstp )  ! internal damping trends
+      IF( ln_bdy     )   CALL bdy_tra_dmp   ( kstp )  ! bdy damping trends
+#if defined key_agrif
+      IF(.NOT. Agrif_Root())  & 
+               &         CALL Agrif_Sponge_tra        ! tracers sponge
+#endif
+                         CALL tra_adv       ( kstp )  ! horizontal & vertical advection
+      IF( ln_zdfosm  )   CALL tra_osm       ( kstp )  ! OSMOSIS non-local tracer fluxes
+      IF( lrst_oce .AND. ln_zdfosm ) &
+           &             CALL osm_rst( kstp, 'WRITE' )! write OSMOSIS outputs + wn (so must do here) to restarts
+                         CALL tra_ldf       ( kstp )  ! lateral mixing
+
+                         CALL tra_zdf       ( kstp )  ! vertical mixing and after tracer fields
+      IF( ln_zdfnpc  )   CALL tra_npc       ( kstp )  ! update after fields by non-penetrative convection
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Set boundary conditions and Swap
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!!jc1: For agrif, it would be much better to finalize tracers/momentum here (e.g. bdy conditions) and move the swap 
+!!    (and time filtering) after Agrif update. Then restart would be done after and would contain updated fields. 
+!!    If so: 
+!!    (i) no need to call agrif update at initialization time
+!!    (ii) no need to update "before" fields 
+!!
+!!    Apart from creating new tra_swp/dyn_swp routines, this however: 
+!!    (i) makes boundary conditions at initialization time computed from updated fields which is not the case between 
+!!    two restarts => restartability issue. One can circumvent this, maybe, by assuming "interface separation", 
+!!    e.g. a shift of the feedback interface inside child domain. 
+!!    (ii) requires that all restart outputs of updated variables by agrif (e.g. passive tracers/tke/barotropic arrays) are done at the same
+!!    place.
+!! 
+!!jc2: dynnxt must be the latest call. e3t_b are indeed updated in that routine
+                         CALL tra_nxt       ( kstp )  ! finalize (bcs) tracer fields at next time step and swap
+                         CALL dyn_nxt       ( kstp )  ! finalize (bcs) velocities at next time step and swap (always called after tra_nxt)
+                         CALL ssh_swp       ( kstp )  ! swap of sea surface height
+      IF(.NOT.ln_linssh) CALL dom_vvl_sf_swp( kstp )  ! swap of vertical scale factors
+      !
+      IF( ln_diahsb  )   CALL dia_hsb       ( kstp )  ! - ML - global conservation diagnostics
+
+!!gm : This does not only concern the dynamics ==>>> add a new title
+!!gm2: why ouput restart before AGRIF update?
+!!
+!!jc: That would be better, but see comment above
+!!
+      IF( lrst_oce   )   CALL rst_write    ( kstp )   ! write output ocean restart file
+      IF( ln_sto_eos )   CALL sto_rst_write( kstp )   ! write restart file for stochastic parameters
+
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF recursive integration
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+                         CALL Agrif_Integrate_ChildGrids( stp )  ! allows to finish all the Child Grids before updating
+#endif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Control
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                         CALL stp_ctl      ( kstp )
+                         
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF update
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+      IF( Agrif_NbStepint() == 0 .AND. nstop == 0 ) THEN
+                         CALL Agrif_update_all( )                  ! Update all components
+      ENDIF
+#endif
+
+      IF( ln_diaobs  )   CALL dia_obs      ( kstp )      ! obs-minus-model (assimilation) diagnostics (call after dynamics update)
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! File manipulation at the end of the first time step
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nit000 ) THEN                          ! 1st time step only
+                                        CALL iom_close( numror )   ! close input  ocean restart file
+         IF(lwm)                        CALL FLUSH    ( numond )   ! flush output namelist oce
+         IF(lwm .AND. numoni /= -1 )    CALL FLUSH    ( numoni )   ! flush output namelist ice (if exist)
+      ENDIF
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Coupled mode
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!!gm why lk_oasis and not lk_cpl ????
+      IF( lk_oasis .AND. nstop == 0 )   CALL sbc_cpl_snd( kstp )     ! coupled mode : field exchanges
+      !
+#if defined key_iomput
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Finalize contextes if end of simulation or error detected
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nitend .OR. nstop > 0 ) THEN 
+                      CALL iom_context_finalize(       cxios_context         ) ! needed for XIOS+AGRIF
+         IF( lrxios ) CALL iom_context_finalize(      crxios_context         )
+         IF( ln_crs ) CALL iom_context_finalize( trim(cxios_context)//"_crs" ) ! 
+      ENDIF
+#endif
+      !
+      IF( ln_timing )   CALL timing_stop('stp')
+      !
+   END SUBROUTINE stp
+   !
+   !!======================================================================
+END MODULE step
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/step_oce.F90	(revision 14097)
@@ -0,0 +1,116 @@
+MODULE step_oce
+   !!======================================================================
+   !!                       ***  MODULE step_oce  ***
+   !! Ocean time-stepping : module used in both initialisation phase and time stepping
+   !!======================================================================
+   !! History :   3.3  !  2010-08  (C. Ethe)  Original code - reorganisation of the initial phase
+   !!             3.7  !  2014-01  (G. Madec) LDF simplication 
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables
+   USE zdf_oce         ! ocean vertical physics variables
+   USE zdfdrg  ,  ONLY : ln_drgimp   ! implicit top/bottom friction
+
+   USE daymod          ! calendar                         (day     routine)
+
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE sbcmod          ! surface boundary condition       (sbc     routine)
+   USE sbcrnf          ! surface boundary condition: runoff variables
+   USE sbccpl          ! surface boundary condition: coupled formulation (call send at end of step)
+   USE sbcapr          ! surface boundary condition: atmospheric pressure
+   USE sbctide         ! Tide initialisation
+   USE sbcwave         ! Wave intialisation
+
+   USE traqsr          ! solar radiation penetration      (tra_qsr routine)
+   USE trasbc          ! surface boundary condition       (tra_sbc routine)
+   USE trabbc          ! bottom boundary condition        (tra_bbc routine)
+   USE trabbl          ! bottom boundary layer            (tra_bbl routine)
+   USE tradmp          ! internal damping                 (tra_dmp routine)
+   USE traadv          ! advection scheme control     (tra_adv_ctl routine)
+   USE traldf          ! lateral mixing                   (tra_ldf routine)
+   USE trazdf          ! vertical mixing                  (tra_zdf routine)
+   USE tranxt          ! time-stepping                    (tra_nxt routine)
+   USE tranpc          ! non-penetrative convection       (tra_npc routine)
+
+   USE eosbn2          ! equation of state                (eos_bn2 routine)
+
+   USE divhor          ! horizontal divergence            (div_hor routine)
+   USE dynadv          ! advection                        (dyn_adv routine)
+   USE dynvor          ! vorticity term                   (dyn_vor routine)
+   USE dynhpg          ! hydrostatic pressure grad.       (dyn_hpg routine)
+   USE dynldf          ! lateral momentum diffusion       (dyn_ldf routine)
+   USE dynzdf          ! vertical diffusion               (dyn_zdf routine)
+   USE dynspg          ! surface pressure gradient        (dyn_spg routine)
+
+   USE dynnxt          ! time-stepping                    (dyn_nxt routine)
+
+   USE stopar          ! Stochastic parametrization       (sto_par routine)
+   USE stopts 
+
+   USE bdy_oce  , ONLY : ln_bdy
+   USE bdydta          ! open boundary condition data     (bdy_dta routine)
+   USE bdytra          ! bdy cond. for tracers            (bdy_tra routine)
+   USE bdydyn3d        ! bdy cond. for baroclinic vel.  (bdy_dyn3d routine)
+
+   USE sshwzv          ! vertical velocity and ssh        (ssh_nxt routine)
+   !                                                       (ssh_swp routine)
+   !                                                       (wzv     routine)
+   USE domvvl          ! variable vertical scale factors  (dom_vvl_sf_nxt routine)
+   !                                                       (dom_vvl_sf_swp routine)
+
+   USE ldfslp          ! iso-neutral slopes               (ldf_slp routine)
+   USE ldfdyn          ! lateral eddy viscosity coef.     (ldf_dyn routine)
+   USE ldftra          ! lateral eddy diffusive coef.     (ldf_tra routine)
+
+   USE zdfphy          ! vertical physics manager      (zdf_phy_init routine)
+   USE zdfosm  , ONLY : osm_rst, dyn_osm, tra_osm      ! OSMOSIS routines used in step.F90
+
+   USE step_diu        ! Time stepping for diurnal sst
+   USE diurnal_bulk    ! diurnal SST bulk routines  (diurnal_sst_takaya routine) 
+   USE cool_skin       ! diurnal cool skin correction (diurnal_sst_coolskin routine)   
+   USE sbc_oce         ! surface fluxes  
+   
+   USE zpshde          ! partial step: hor. derivative     (zps_hde routine)
+
+   USE diawri          ! Standard run outputs             (dia_wri routine)
+   USE diaptr          ! poleward transports              (dia_ptr routine)
+   USE diadct          ! sections transports              (dia_dct routine)
+   USE diaar5          ! AR5 diagnosics                   (dia_ar5 routine)
+   USE diahth          ! thermocline depth                (dia_hth routine)
+   USE diahsb          ! heat, salt and volume budgets    (dia_hsb routine)
+   USE diaharm
+   USE diacfl
+   USE diaobs          ! Observation operator
+   USE flo_oce         ! floats variables
+   USE floats          ! floats computation               (flo_stp routine)
+
+   USE crsfld          ! Standard output on coarse grid   (crs_fld routine)
+
+   USE asminc          ! assimilation increments      (tra_asm_inc routine)
+   !                                                   (dyn_asm_inc routine)
+   USE asmbkg
+   USE stpctl          ! time stepping control            (stp_ctl routine)
+   USE restart         ! ocean restart                    (rst_wri routine)
+   USE prtctl          ! Print control                    (prt_ctl routine)
+
+   USE in_out_manager  ! I/O manager
+   USE iom             !
+   USE lbclnk
+   USE timing          ! Timing
+
+#if defined key_iomput
+   USE xios            ! I/O server
+#endif
+#if defined key_agrif
+   USE agrif_oce_sponge ! Momemtum and tracers sponges
+   USE agrif_all_update ! Main update driver
+#endif
+#if defined key_top
+   USE trcstp           ! passive tracer time-stepping      (trc_stp routine)
+#endif
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE step_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/stpctl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/stpctl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/stpctl.F90	(revision 14097)
@@ -0,0 +1,290 @@
+MODULE stpctl
+   !!======================================================================
+   !!                       ***  MODULE  stpctl  ***
+   !! Ocean run control :  gross check of the ocean time stepping
+   !!======================================================================
+   !! History :  OPA  ! 1991-03  (G. Madec) Original code
+   !!            6.0  ! 1992-06  (M. Imbard)
+   !!            8.0  ! 1997-06  (A.M. Treguier)
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            2.0  ! 2009-07  (G. Madec)  Add statistic for time-spliting
+   !!            3.7  ! 2016-09  (G. Madec)  Remove solver
+   !!            4.0  ! 2017-04  (G. Madec)  regroup global communications
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   stp_ctl      : Control the run
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables 
+   USE c1d             ! 1D vertical configuration
+   USE diawri          ! Standard run outputs       (dia_wri_state routine)
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! distributed memory computing
+   USE zdf_oce ,  ONLY : ln_zad_Aimp       ! ocean vertical physics variables
+   USE wet_dry,   ONLY : ll_wd, ssh_ref    ! reference depth for negative bathy
+
+   USE netcdf          ! NetCDF library
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC stp_ctl           ! routine called by step.F90
+
+   INTEGER  ::   idrun, idtime, idssh, idu, ids1, ids2, idt1, idt2, idc1, idw1, istatus
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE stp_ctl( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE stp_ctl  ***
+      !!                     
+      !! ** Purpose :   Control the run
+      !!
+      !! ** Method  : - Save the time step in numstp
+      !!              - Print it each 50 time steps
+      !!              - Stop the run IF problem encountered by setting nstop > 0
+      !!                Problems checked: |ssh| maximum larger than 10 m
+      !!                                  |U|   maximum larger than 10 m/s 
+      !!                                  negative sea surface salinity
+      !!
+      !! ** Actions :   "time.step" file = last ocean time-step
+      !!                "run.stat"  file = run statistics
+      !!                 nstop indicator sheared among all local domain
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt       ! ocean time-step index
+      !!
+      INTEGER                ::   ji, jj, jk          ! dummy loop indices
+      INTEGER,  DIMENSION(3) ::   ih, iu, is1, is2    ! min/max loc indices
+      INTEGER,  DIMENSION(9) ::   iareasum, iareamin, iareamax
+      REAL(wp)               ::   zzz                 ! local real 
+      REAL(wp), DIMENSION(9) ::   zmax, zmaxlocal
+      LOGICAL                ::   ll_wrtstp, ll_colruns, ll_wrtruns
+      LOGICAL, DIMENSION(jpi,jpj,jpk) ::   llmsk
+      CHARACTER(len=20) :: clname
+      !!----------------------------------------------------------------------
+      IF( nstop > 0 .AND. ngrdstop > -1 )   RETURN   !   stpctl was already called by a child grid
+      !
+      ll_wrtstp  = ( MOD( kt-nit000, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend )
+      ll_colruns = ll_wrtstp .AND. sn_cfctl%l_runstat .AND. jpnij > 1 
+      ll_wrtruns = ( ll_colruns .OR. jpnij == 1 ) .AND. lwm
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'stp_ctl : time-stepping control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !                                ! open time.step file
+         IF( lwm ) CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+         !                                ! open run.stat file(s) at start whatever
+         !                                ! the value of sn_cfctl%ptimincr
+         IF( ll_wrtruns ) THEN
+            CALL ctl_opn( numrun, 'run.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            clname = 'run.stat.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, idrun )
+            istatus = NF90_DEF_DIM( idrun, 'time', NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( idrun, 'abs_ssh_max', NF90_DOUBLE, (/ idtime /), idssh )
+            istatus = NF90_DEF_VAR( idrun,   'abs_u_max', NF90_DOUBLE, (/ idtime /), idu   )
+            istatus = NF90_DEF_VAR( idrun,       's_min', NF90_DOUBLE, (/ idtime /), ids1  )
+            istatus = NF90_DEF_VAR( idrun,       's_max', NF90_DOUBLE, (/ idtime /), ids2  )
+            istatus = NF90_DEF_VAR( idrun,       't_min', NF90_DOUBLE, (/ idtime /), idt1  )
+            istatus = NF90_DEF_VAR( idrun,       't_max', NF90_DOUBLE, (/ idtime /), idt2  )
+            IF( ln_zad_Aimp ) THEN
+               istatus = NF90_DEF_VAR( idrun,   'abs_wi_max', NF90_DOUBLE, (/ idtime /), idw1  )
+               istatus = NF90_DEF_VAR( idrun,       'Cf_max', NF90_DOUBLE, (/ idtime /), idc1  )
+            ENDIF
+            istatus = NF90_ENDDEF(idrun)
+         ENDIF
+      ENDIF
+      !
+      IF(lwm .AND. ll_wrtstp) THEN        !==  current time step  ==!   ("time.step" file)
+         WRITE ( numstp, '(1x, i8)' )   kt
+         REWIND( numstp )
+      ENDIF
+      !
+      !                                   !==  test of extrema  ==!
+      !
+      ! define zmax default value. needed for land processors
+      IF( ll_colruns ) THEN    ! default value: must not be kept when calling mpp_max -> must be as small as possible
+         zmax(:) = -HUGE(1._wp)
+      ELSE                     ! default value: must not give true for any of the tests bellow (-> avoid manipulating HUGE...)
+         zmax(:) =  0._wp
+         zmax(3) = -1._wp      ! avoid salinity minimum at 0.
+      ENDIF
+      !
+      IF( ll_wd ) THEN
+         zmax(1) = MAXVAL(  ABS( sshn(:,:) + ssh_ref*tmask(:,:,1) )  )        ! ssh max 
+      ELSE
+         zmax(1) = MAXVAL(  ABS( sshn(:,:) )  )                               ! ssh max
+      ENDIF
+      zmax(2) = MAXVAL(  ABS( un(:,:,:) )  )                                  ! velocity max (zonal only)
+      llmsk(:,:,:) = tmask(:,:,:) == 1._wp
+      IF( COUNT( llmsk(:,:,:) ) > 0 ) THEN   ! avoid huge values sent back for land processors...      
+         zmax(3) = MAXVAL( -tsn(:,:,:,jp_sal) , mask = llmsk )   ! minus salinity max
+         zmax(4) = MAXVAL(  tsn(:,:,:,jp_sal) , mask = llmsk )   !       salinity max
+         IF( ll_colruns .OR. jpnij == 1 ) THEN     ! following variables are used only in the netcdf file
+            zmax(5) = MAXVAL( -tsn(:,:,:,jp_tem) , mask = llmsk )   ! minus temperature max
+            zmax(6) = MAXVAL(  tsn(:,:,:,jp_tem) , mask = llmsk )   !       temperature max
+            IF( ln_zad_Aimp ) THEN
+               zmax(9) = MAXVAL(   Cu_adv(:,:,:)   , mask = llmsk ) ! partitioning coeff. max
+               llmsk(:,:,:) = wmask(:,:,:) == 1._wp
+               IF( COUNT( llmsk(:,:,:) ) > 0 ) THEN   ! avoid huge values sent back for land processors...
+                  zmax(8) = MAXVAL(  ABS( wi(:,:,:) ) , mask = wmask(:,:,:) == 1._wp ) ! implicit vertical vel. max
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+      zmax(7) = REAL( nstop , wp )                                            ! stop indicator
+      !
+      IF( ll_colruns ) THEN
+         zmaxlocal(:) = zmax(:)
+         CALL mpp_max( "stpctl", zmax )          ! max over the global domain
+         nstop = NINT( zmax(7) )                 ! nstop indicator sheared among all local domains
+      ENDIF
+      !                                   !==  run statistics  ==!   ("run.stat" files)
+      IF( ll_wrtruns ) THEN
+         WRITE(numrun,9500) kt, zmax(1), zmax(2), -zmax(3), zmax(4)
+         istatus = NF90_PUT_VAR( idrun, idssh, (/ zmax(1)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,   idu, (/ zmax(2)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  ids1, (/-zmax(3)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  ids2, (/ zmax(4)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  idt1, (/-zmax(5)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  idt2, (/ zmax(6)/), (/kt/), (/1/) )
+         IF( ln_zad_Aimp ) THEN
+            istatus = NF90_PUT_VAR( idrun,  idw1, (/ zmax(8)/), (/kt/), (/1/) )
+            istatus = NF90_PUT_VAR( idrun,  idc1, (/ zmax(9)/), (/kt/), (/1/) )
+         ENDIF
+         IF( kt == nitend ) istatus = NF90_CLOSE(idrun)
+      END IF
+      !                                   !==  error handling  ==!
+      IF(   zmax(1) >   20._wp .OR.   &                    ! too large sea surface height ( > 20 m )
+         &  zmax(2) >   10._wp .OR.   &                    ! too large velocity ( > 10 m/s)
+         &  zmax(3) >=   0._wp .OR.   &                    ! negative or zero sea surface salinity
+         &  zmax(4) >= 100._wp .OR.   &                    ! too large sea surface salinity ( > 100 )
+         &  zmax(4) <    0._wp .OR.   &                    ! too large sea surface salinity (keep this line for sea-ice)
+         &  ISNAN( zmax(1) + zmax(2) + zmax(3) ) .OR.  &   ! NaN encounter in the tests
+         &  ABS(   zmax(1) + zmax(2) + zmax(3) ) > HUGE(1._wp) ) THEN    ! Infinity encounter in the tests
+         IF( ll_colruns ) THEN
+            ! first: close the netcdf file, so we can read it
+            IF( lwm .AND. kt /= nitend )   istatus = NF90_CLOSE(idrun)
+            CALL mpp_maxloc( 'stpctl', ABS(sshn)        , ssmask(:,:)  , zzz, ih(1:2)  )   ;   ih(3) = 0
+            CALL mpp_maxloc( 'stpctl', ABS(un)          , umask (:,:,:), zzz, iu  )
+            CALL mpp_minloc( 'stpctl', tsn(:,:,:,jp_sal), tmask (:,:,:), zzz, is1 )
+            CALL mpp_maxloc( 'stpctl', tsn(:,:,:,jp_sal), tmask (:,:,:), zzz, is2 )
+            ! find which subdomain has the max.
+            iareamin(:) = jpnij+1   ;   iareamax(:) = 0   ;   iareasum(:) = 0
+            DO ji = 1, 9
+               IF( zmaxlocal(ji) == zmax(ji) ) THEN
+                  iareamin(ji) = narea   ;   iareamax(ji) = narea   ;   iareasum(ji) = 1
+               ENDIF
+            END DO
+            CALL mpp_min( "stpctl", iareamin )         ! min over the global domain
+            CALL mpp_max( "stpctl", iareamax )         ! max over the global domain
+            CALL mpp_sum( "stpctl", iareasum )         ! sum over the global domain
+         ELSE
+            ih(1:2)= MAXLOC( ABS( sshn(:,:)   )                              ) + (/ nimpp - 1, njmpp - 1    /)   ;   ih(3) = 0
+            iu(:)  = MAXLOC( ABS( un  (:,:,:) )                              ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            is1(:) = MINLOC( tsn(:,:,:,jp_sal), mask = tmask(:,:,:) == 1._wp ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            is2(:) = MAXLOC( tsn(:,:,:,jp_sal), mask = tmask(:,:,:) == 1._wp ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            iareamin(:) = narea   ;   iareamax(:) = narea   ;   iareasum(:) = 1         ! this is local information
+         ENDIF
+         !
+         WRITE(ctmp1,*) ' stp_ctl: |ssh| > 20 m  or  |U| > 10 m/s  or  S <= 0  or  S >= 100  or  NaN encounter in the tests'
+         CALL wrt_line(ctmp2, kt, ' |ssh| max ',   zmax(1), ih , iareasum(1), iareamin(1), iareamax(1) ) 
+         CALL wrt_line(ctmp3, kt, ' |U|   max ',   zmax(2), iu , iareasum(2), iareamin(2), iareamax(2) ) 
+         CALL wrt_line(ctmp4, kt, ' Sal   min ', - zmax(3), is1, iareasum(3), iareamin(3), iareamax(3) ) 
+         CALL wrt_line(ctmp5, kt, ' Sal   max ',   zmax(4), is2, iareasum(4), iareamin(4), iareamax(4) ) 
+         IF( Agrif_Root() ) THEN
+            WRITE(ctmp6,*) '      ===> output of last computed fields in output.abort* files'
+         ELSE
+            WRITE(ctmp6,*) '      ===> output of last computed fields in '//TRIM(Agrif_CFixed())//'_output.abort* files'
+         ENDIF
+         !
+         CALL dia_wri_state( 'output.abort' )    ! create an output.abort file
+         !
+         IF( ll_colruns .or. jpnij == 1 ) THEN   ! all processes synchronized -> use lwp to print in opened ocean.output files
+            IF(lwp) THEN   ;   CALL ctl_stop( ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+            ELSE           ;   nstop = MAX(1, nstop)   ! make sure nstop > 0 (automatically done when calling ctl_stop)
+            ENDIF
+         ELSE                                    ! only mpi subdomains with errors are here -> STOP now
+            CALL ctl_stop( 'STOP', ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( nstop > 0 ) THEN                                                  ! an error was detected and we did not abort yet...
+         ngrdstop = Agrif_Fixed()                                           ! store which grid got this error
+         IF( .NOT. ll_colruns .AND. jpnij > 1 )   CALL ctl_stop( 'STOP' )   ! we must abort here to avoid MPI deadlock
+      ENDIF
+      !
+9500  FORMAT(' it :', i8, '    |ssh|_max: ', D23.16, ' |U|_max: ', D23.16,' S_min: ', D23.16,' S_max: ', D23.16)
+      !
+   END SUBROUTINE stp_ctl
+
+
+   SUBROUTINE wrt_line( cdline, kt, cdprefix, pval, kloc, ksum, kmin, kmax )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE wrt_line  ***
+      !!
+      !! ** Purpose :   write information line
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),      INTENT(  out) ::   cdline
+      CHARACTER(len=*),      INTENT(in   ) ::   cdprefix
+      REAL(wp),              INTENT(in   ) ::   pval
+      INTEGER, DIMENSION(3), INTENT(in   ) ::   kloc
+      INTEGER,               INTENT(in   ) ::   kt, ksum, kmin, kmax
+      !
+      CHARACTER(len=80) ::   clsuff
+      CHARACTER(len=9 ) ::   clkt, clsum, clmin, clmax
+      CHARACTER(len=9 ) ::   cli, clj, clk
+      CHARACTER(len=1 ) ::   clfmt
+      CHARACTER(len=4 ) ::   cl4   ! needed to be able to compile with Agrif, I don't know why
+      INTEGER           ::   ifmtk
+      !!----------------------------------------------------------------------
+      WRITE(clkt , '(i9)') kt
+      
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpnij  ,wp))) + 1     ! how many digits to we need to write ? (we decide max = 9)
+      !!! WRITE(clsum, '(i'//clfmt//')') ksum                   ! this is creating a compilation error with AGRIF
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clsum, cl4) ksum
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1    ! how many digits to we need to write ? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clmin, cl4) kmin-1
+                                   WRITE(clmax, cl4) kmax-1
+      !
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpiglo,wp))) + 1      ! how many digits to we need to write jpiglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(cli, cl4) kloc(1)      ! this is ok with AGRIF
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpjglo,wp))) + 1      ! how many digits to we need to write jpjglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clj, cl4) kloc(2)      ! this is ok with AGRIF
+      !
+      IF( ksum == 1 ) THEN   ;   WRITE(clsuff,9100) TRIM(clmin)
+      ELSE                   ;   WRITE(clsuff,9200) TRIM(clsum), TRIM(clmin), TRIM(clmax)
+      ENDIF
+      IF(kloc(3) == 0) THEN
+         ifmtk = INT(LOG10(REAL(jpk,wp))) + 1                   ! how many digits to we need to write jpk? (we decide max = 9)
+         clk = REPEAT(' ', ifmtk)                               ! create the equivalent in blank string
+         WRITE(cdline,9300) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj), clk(1:ifmtk), TRIM(clsuff)
+      ELSE
+         WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpk,wp))) + 1      ! how many digits to we need to write jpk? (we decide max = 9)
+         !!! WRITE(clk, '(i'//clfmt//')') kloc(3)               ! this is creating a compilation error with AGRIF
+         cl4 = '(i'//clfmt//')'   ;   WRITE(clk, cl4) kloc(3)   ! this is ok with AGRIF
+         WRITE(cdline,9400) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj),    TRIM(clk), TRIM(clsuff)
+      ENDIF
+      !
+9100  FORMAT('MPI rank ', a)
+9200  FORMAT('found in ', a, ' MPI tasks, spread out among ranks ', a, ' to ', a)
+9300  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j   ', a, ' ', a, ' ', a, ' ', a)
+9400  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j k ', a, ' ', a, ' ', a, ' ', a)
+      !
+   END SUBROUTINE wrt_line
+
+
+   !!======================================================================
+END MODULE stpctl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/timing.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/timing.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/timing.F90	(revision 14097)
@@ -0,0 +1,868 @@
+MODULE timing
+   !!========================================================================
+   !!                     ***  MODULE  timing  ***
+   !!========================================================================
+   !! History : 4.0  ! 2001-05  (R. Benshila)   
+   !!------------------------------------------------------------------------
+
+   !!------------------------------------------------------------------------
+   !!   timming_init    : initialize timing process 
+   !!   timing_start    : start Timer
+   !!   timing_stop     : stop  Timer
+   !!   timing_reset    : end timing variable creation
+   !!   timing_finalize : compute stats and write output in calling w*_info 
+   !!   timing_ini_var  : create timing variables 
+   !!   timing_listing  : print instumented subroutines in ocean.output
+   !!   wcurrent_info   : compute and print detailed stats on the current CPU
+   !!   wave_info       : compute and print averaged statson all processors
+   !!   wmpi_info       : compute and write global stats  
+   !!   supress         : suppress an element of the timing linked list  
+   !!   insert          : insert an element of the timing linked list  
+   !!------------------------------------------------------------------------
+   USE in_out_manager  ! I/O manager 
+   USE dom_oce         ! ocean domain
+   USE lib_mpp          
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   timing_init, timing_finalize   ! called in nemogcm module 
+   PUBLIC   timing_reset                   ! called in step module 
+   PUBLIC   timing_start, timing_stop      ! called in each routine to time 
+   
+#if defined key_mpp_mpi
+   INCLUDE 'mpif.h'
+#endif
+
+   ! Variables for fine grain timing
+   TYPE timer
+      CHARACTER(LEN=20)  :: cname
+      CHARACTER(LEN=20)  :: surname
+      INTEGER :: rank
+      REAL(wp)  :: t_cpu, t_clock, tsum_cpu, tsum_clock, tmax_cpu, tmax_clock, tmin_cpu, tmin_clock, tsub_cpu, tsub_clock
+      INTEGER :: ncount, ncount_max, ncount_rate  
+      INTEGER :: niter
+      LOGICAL :: l_tdone
+      TYPE(timer), POINTER :: next => NULL()
+      TYPE(timer), POINTER :: prev => NULL()
+      TYPE(timer), POINTER :: parent_section => NULL()
+   END TYPE timer
+    
+   TYPE alltimer
+      CHARACTER(LEN=20), DIMENSION(:), POINTER :: cname => NULL()
+      REAL(wp), DIMENSION(:), POINTER :: tsum_cpu   => NULL()
+      REAL(wp), DIMENSION(:), POINTER :: tsum_clock => NULL()
+      INTEGER, DIMENSION(:), POINTER :: niter => NULL()
+      TYPE(alltimer), POINTER :: next => NULL()
+      TYPE(alltimer), POINTER :: prev => NULL()
+   END TYPE alltimer 
+ 
+   TYPE(timer), POINTER :: s_timer_root => NULL()
+   TYPE(timer), POINTER :: s_timer      => NULL()
+   TYPE(timer), POINTER :: s_timer_old      => NULL()
+
+   TYPE(timer), POINTER :: s_wrk        => NULL()
+   REAL(wp) :: t_overclock, t_overcpu
+   LOGICAL :: l_initdone = .FALSE.
+   INTEGER :: nsize
+   
+   ! Variables for coarse grain timing
+   REAL(wp) :: tot_etime, tot_ctime
+   REAL(kind=wp), DIMENSION(2)     :: t_elaps, t_cpu
+   REAL(wp), ALLOCATABLE, DIMENSION(:) :: all_etime, all_ctime
+   INTEGER :: nfinal_count, ncount, ncount_rate, ncount_max
+   INTEGER, DIMENSION(8)           :: nvalues
+   CHARACTER(LEN=8), DIMENSION(2)  :: cdate
+   CHARACTER(LEN=10), DIMENSION(2) :: ctime
+   CHARACTER(LEN=5)                :: czone
+    
+   ! From of ouput file (1/proc or one global)   !RB to put in nammpp or namctl
+   LOGICAL :: ln_onefile = .TRUE. 
+   LOGICAL :: lwriter
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE timing_start(cdinfo)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_start  ***
+      !! ** Purpose :   collect execution time
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) :: cdinfo
+      !
+       IF(ASSOCIATED(s_timer) ) s_timer_old => s_timer
+       !
+      ! Create timing structure at first call of the routine 
+       CALL timing_ini_var(cdinfo)
+   !   write(*,*) 'after inivar ', s_timer%cname
+
+      ! ici timing_ini_var a soit retrouve s_timer et fait return soit ajoute un maillon
+      ! maintenant on regarde si le call d'avant corrsspond a un parent ou si il est ferme
+      IF( .NOT. s_timer_old%l_tdone ) THEN      
+         s_timer%parent_section => s_timer_old
+      ELSE
+         s_timer%parent_section => NULL()
+      ENDIF    
+
+      s_timer%l_tdone = .FALSE.
+      s_timer%niter = s_timer%niter + 1
+      s_timer%t_cpu = 0.
+      s_timer%t_clock = 0.
+                  
+      ! CPU time collection
+      CALL CPU_TIME( s_timer%t_cpu  )
+      ! clock time collection
+#if defined key_mpp_mpi
+      s_timer%t_clock= MPI_Wtime()
+#else
+      CALL SYSTEM_CLOCK(COUNT_RATE=s_timer%ncount_rate, COUNT_MAX=s_timer%ncount_max)
+      CALL SYSTEM_CLOCK(COUNT = s_timer%ncount)
+#endif
+!      write(*,*) 'end of start ', s_timer%cname
+
+      !
+   END SUBROUTINE timing_start
+
+
+   SUBROUTINE timing_stop(cdinfo, csection)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_stop  ***
+      !! ** Purpose :   finalize timing and output
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) :: cdinfo
+      CHARACTER(len=*), INTENT(in), OPTIONAL :: csection
+      !
+      INTEGER  :: ifinal_count, iperiods    
+      REAL(wp) :: zcpu_end, zmpitime,zcpu_raw,zclock_raw
+      !
+      s_wrk => NULL()
+
+      ! clock time collection
+#if defined key_mpp_mpi
+      zmpitime = MPI_Wtime()
+#else
+      CALL SYSTEM_CLOCK(COUNT = ifinal_count)
+#endif
+      ! CPU time collection
+      CALL CPU_TIME( zcpu_end )
+
+!!$      IF(associated(s_timer%parent_section))then
+!!$        write(*,*) s_timer%cname,' <-- ', s_timer%parent_section%cname
+!!$      ENDIF  
+
+ !     No need to search ... : s_timer has the last value defined in start
+ !     s_timer => s_timer_root
+ !     DO WHILE( TRIM(s_timer%cname) /= TRIM(cdinfo) ) 
+ !        IF( ASSOCIATED(s_timer%next) ) s_timer => s_timer%next
+ !     END DO
+ 
+      ! CPU time correction
+      zcpu_raw = zcpu_end - s_timer%t_cpu - t_overcpu ! total time including child
+      s_timer%t_cpu  = zcpu_raw - s_timer%tsub_cpu
+  !    IF(s_timer%cname==trim('lbc_lnk_2d'))  write(*,*) s_timer%tsub_cpu,zcpu_end
+
+      ! clock time correction
+#if defined key_mpp_mpi
+      zclock_raw = zmpitime - s_timer%t_clock - t_overclock ! total time including child
+      s_timer%t_clock = zclock_raw - t_overclock - s_timer%tsub_clock
+#else
+      iperiods = ifinal_count - s_timer%ncount
+      IF( ifinal_count < s_timer%ncount )  &
+         iperiods = iperiods + s_timer%ncount_max 
+         zclock_raw = REAL(iperiods) / s_timer%ncount_rate !- t_overclock   
+         s_timer%t_clock  = zclock_raw - s_timer%tsub_clock
+#endif
+ !     IF(s_timer%cname==trim('lbc_lnk_2d')) write(*,*) zclock_raw , s_timer%tsub_clock
+      
+      ! Correction of parent section
+      IF( .NOT. PRESENT(csection) ) THEN
+         IF ( ASSOCIATED(s_timer%parent_section ) ) THEN
+            s_timer%parent_section%tsub_cpu   = zcpu_raw   + s_timer%parent_section%tsub_cpu 
+            s_timer%parent_section%tsub_clock = zclock_raw + s_timer%parent_section%tsub_clock             
+         ENDIF
+      ENDIF
+            
+      ! time diagnostics 
+      s_timer%tsum_clock = s_timer%tsum_clock + s_timer%t_clock 
+      s_timer%tsum_cpu   = s_timer%tsum_cpu   + s_timer%t_cpu
+!RB to use to get min/max during a time integration
+!      IF( .NOT. l_initdone ) THEN
+!         s_timer%tmin_clock = s_timer%t_clock 
+!         s_timer%tmin_cpu   = s_timer%t_cpu 
+!      ELSE
+!         s_timer%tmin_clock = MIN( s_timer%tmin_clock, s_timer%t_clock ) 
+!         s_timer%tmin_cpu   = MIN( s_timer%tmin_cpu  , s_timer%t_cpu   ) 
+!      ENDIF   
+!      s_timer%tmax_clock = MAX( s_timer%tmax_clock, s_timer%t_clock ) 
+!      s_timer%tmax_cpu   = MAX( s_timer%tmax_cpu  , s_timer%t_cpu   )  
+      !
+      s_timer%tsub_clock = 0.
+      s_timer%tsub_cpu = 0.
+      s_timer%l_tdone = .TRUE.
+      !
+      !
+      ! we come back
+      IF ( ASSOCIATED(s_timer%parent_section ) ) s_timer => s_timer%parent_section
+     
+!      write(*,*) 'end of stop ', s_timer%cname
+
+   END SUBROUTINE timing_stop
+ 
+ 
+   SUBROUTINE timing_init
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_init  ***
+      !! ** Purpose :   open timing output file
+      !!----------------------------------------------------------------------
+      INTEGER :: iperiods, istart_count, ifinal_count
+      REAL(wp) :: zdum
+      LOGICAL :: ll_f
+             
+      IF( ln_onefile ) THEN
+         IF( lwp) CALL ctl_opn( numtime, 'timing.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout,.TRUE., narea )
+         lwriter = lwp
+      ELSE
+         CALL ctl_opn( numtime, 'timing.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout,.FALSE., narea )
+         lwriter = .TRUE.
+      ENDIF
+      
+      IF( lwriter) THEN      
+         WRITE(numtime,*)
+         WRITE(numtime,*) '      CNRS - NERC - Met OFFICE - MERCATOR-ocean - CMCC - INGV'
+         WRITE(numtime,*) '                             NEMO team'
+         WRITE(numtime,*) '                  Ocean General Circulation Model'
+         WRITE(numtime,*) '                        version 4.0  (2019) '
+         WRITE(numtime,*)
+         WRITE(numtime,*) '                        Timing Informations '
+         WRITE(numtime,*)
+         WRITE(numtime,*)
+      ENDIF   
+      
+      ! Compute clock function overhead
+#if defined key_mpp_mpi        
+      t_overclock = MPI_WTIME()
+      t_overclock = MPI_WTIME() - t_overclock
+#else        
+      CALL SYSTEM_CLOCK(COUNT_RATE=ncount_rate, COUNT_MAX=ncount_max)
+      CALL SYSTEM_CLOCK(COUNT = istart_count)
+      CALL SYSTEM_CLOCK(COUNT = ifinal_count)
+      iperiods = ifinal_count - istart_count
+      IF( ifinal_count < istart_count )  &
+          iperiods = iperiods + ncount_max 
+      t_overclock = REAL(iperiods) / ncount_rate
+#endif
+
+      ! Compute cpu_time function overhead
+      CALL CPU_TIME(zdum)
+      CALL CPU_TIME(t_overcpu)
+      
+      ! End overhead omputation  
+      t_overcpu = t_overcpu - zdum        
+      t_overclock = t_overcpu + t_overclock        
+
+      ! Timing on date and time
+      CALL DATE_AND_TIME(cdate(1),ctime(1),czone,nvalues)
+    
+      CALL CPU_TIME(t_cpu(1))      
+#if defined key_mpp_mpi        
+      ! Start elapsed and CPU time counters
+      t_elaps(1) = MPI_WTIME()
+#else
+      CALL SYSTEM_CLOCK(COUNT_RATE=ncount_rate, COUNT_MAX=ncount_max)
+      CALL SYSTEM_CLOCK(COUNT = ncount)
+#endif                 
+      !
+   END SUBROUTINE timing_init
+
+
+   SUBROUTINE timing_finalize
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_finalize ***
+      !! ** Purpose :  compute average time 
+      !!               write timing output file
+      !!----------------------------------------------------------------------
+      TYPE(timer), POINTER :: s_temp
+      INTEGER :: idum, iperiods, icode
+      INTEGER :: ji
+      LOGICAL :: ll_ord, ll_averep
+      CHARACTER(len=120) :: clfmt            
+      REAL(wp), DIMENSION(:), ALLOCATABLE ::   timing_glob
+      REAL(wp) ::   zsypd   ! simulated years per day (Balaji 2017)
+      REAL(wp) ::   zperc, ztot
+
+      ll_averep = .TRUE.
+    
+      ! total CPU and elapse
+      CALL CPU_TIME(t_cpu(2))
+      t_cpu(2)   = t_cpu(2)    - t_cpu(1)   - t_overcpu
+#if defined key_mpp_mpi
+      t_elaps(2) = MPI_WTIME() - t_elaps(1) - t_overclock
+#else
+      CALL SYSTEM_CLOCK(COUNT = nfinal_count)
+      iperiods = nfinal_count - ncount
+      IF( nfinal_count < ncount )  &
+          iperiods = iperiods + ncount_max 
+      t_elaps(2) = REAL(iperiods) / ncount_rate - t_overclock
+#endif      
+
+      ! End of timings on date & time
+      CALL DATE_AND_TIME(cdate(2),ctime(2),czone,nvalues)
+       
+      ! Compute the numer of routines
+      nsize = 0 
+      s_timer => s_timer_root
+      DO WHILE( ASSOCIATED(s_timer) )
+         nsize = nsize + 1
+         s_timer => s_timer%next
+      END DO
+      idum = nsize
+      CALL mpp_sum('timing', idum)
+      IF( idum/jpnij /= nsize ) THEN
+         IF( lwriter ) WRITE(numtime,*) '        ===> W A R N I N G: '
+         IF( lwriter ) WRITE(numtime,*) ' Some CPU have different number of routines instrumented for timing'
+         IF( lwriter ) WRITE(numtime,*) ' No detailed report on averaged timing can be provided'
+         IF( lwriter ) WRITE(numtime,*) ' The following detailed report only deals with the current processor'
+         IF( lwriter ) WRITE(numtime,*)
+         ll_averep = .FALSE.
+      ENDIF   
+
+#if defined key_mpp_mpi      
+      ! in MPI gather some info
+      ALLOCATE( all_etime(jpnij), all_ctime(jpnij) )
+      CALL MPI_ALLGATHER(t_elaps(2), 1, MPI_DOUBLE_PRECISION,   &
+                         all_etime , 1, MPI_DOUBLE_PRECISION,   &
+                         MPI_COMM_OCE, icode)
+      CALL MPI_ALLGATHER(t_cpu(2) , 1, MPI_DOUBLE_PRECISION,   &
+                         all_ctime, 1, MPI_DOUBLE_PRECISION,   &
+                         MPI_COMM_OCE, icode)
+      tot_etime = SUM(all_etime(:))
+      tot_ctime = SUM(all_ctime(:))
+#else
+      tot_etime = t_elaps(2)
+      tot_ctime = t_cpu  (2)           
+#endif
+
+      ! write output file
+      IF( lwriter ) WRITE(numtime,*) 
+      IF( lwriter ) WRITE(numtime,*) 
+      IF( lwriter ) WRITE(numtime,*) 'Total timing (sum) :'
+      IF( lwriter ) WRITE(numtime,*) '--------------------'
+      IF( lwriter ) WRITE(numtime,"('Elapsed Time (s)  CPU Time (s)')")
+      IF( lwriter ) WRITE(numtime,'(5x,f12.3,1x,f12.3)')  tot_etime, tot_ctime
+      IF( lwriter ) WRITE(numtime,*) 
+#if defined key_mpp_mpi
+      IF( ll_averep ) CALL waver_info
+      CALL wmpi_info
+#endif      
+      IF( lwriter ) CALL wcurrent_info
+      
+      clfmt='(1X,"Timing started on ",2(A2,"/"),A4," at ",2(A2,":"),A2," MET ",A3,":",A2," from GMT")'
+      IF( lwriter ) WRITE(numtime, TRIM(clfmt)) &           
+      &       cdate(1)(7:8), cdate(1)(5:6), cdate(1)(1:4),   &
+      &       ctime(1)(1:2), ctime(1)(3:4), ctime(1)(5:6),   &
+      &       czone(1:3),    czone(4:5)                     
+      clfmt='(1X,  "Timing   ended on ",2(A2,"/"),A4," at ",2(A2,":"),A2," MET ",A3,":",A2," from GMT")'
+      IF( lwriter ) WRITE(numtime, TRIM(clfmt)) &           
+      &       cdate(2)(7:8), cdate(2)(5:6), cdate(2)(1:4),   &
+      &       ctime(2)(1:2), ctime(2)(3:4), ctime(2)(5:6),   &
+      &       czone(1:3),    czone(4:5)
+
+#if defined key_mpp_mpi
+      ALLOCATE(timing_glob(4*jpnij), stat=icode)
+      CALL MPI_GATHER( (/compute_time, waiting_time(1), waiting_time(2), elapsed_time/),   &
+         &             4, MPI_DOUBLE_PRECISION, timing_glob, 4, MPI_DOUBLE_PRECISION, 0, MPI_COMM_OCE, icode)
+      IF( narea == 1 ) THEN
+         WRITE(numtime,*) ' '
+         WRITE(numtime,*) ' Report on time spent on waiting MPI messages '
+         WRITE(numtime,*) '    total timing measured between nit000+1 and nitend-1 '
+         WRITE(numtime,*) '    warning: includes restarts writing time if output before nitend... '
+         WRITE(numtime,*) ' '
+         DO ji = 1, jpnij
+            ztot = SUM( timing_glob(4*ji-3:4*ji-1) )
+            WRITE(numtime,'(A28,F11.6,            A34,I8)') 'Computing       time : ',timing_glob(4*ji-3), ' on MPI rank : ', ji
+            IF ( ztot /= 0. ) zperc = timing_glob(4*ji-2) / ztot * 100.
+            WRITE(numtime,'(A28,F11.6,A2, F4.1,A3,A25,I8)') 'Waiting lbc_lnk time : ',timing_glob(4*ji-2)   &
+               &                                                         , ' (',      zperc,' %)',   ' on MPI rank : ', ji
+            IF ( ztot /= 0. ) zperc = timing_glob(4*ji-1) / ztot * 100.
+            WRITE(numtime,'(A28,F11.6,A2, F4.1,A3,A25,I8)') 'Waiting  global time : ',timing_glob(4*ji-1)   &
+               &                                                         , ' (',      zperc,' %)',   ' on MPI rank : ', ji
+            zsypd = rn_rdt * REAL(nitend-nit000-1, wp) / (timing_glob(4*ji) * 365.)
+            WRITE(numtime,'(A28,F11.6,A7,F10.3,A2,A15,I8)') 'Total           time : ',timing_glob(4*ji  )   &
+               &                                                         , ' (SYPD: ', zsypd, ')',   ' on MPI rank : ', ji
+         END DO
+      ENDIF
+      DEALLOCATE(timing_glob)
+#endif      
+
+      IF( lwriter ) CLOSE(numtime) 
+      !
+   END SUBROUTINE timing_finalize
+   
+
+   SUBROUTINE wcurrent_info
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE wcurrent_info ***
+      !! ** Purpose :  compute and write timing output file
+      !!----------------------------------------------------------------------
+      LOGICAL :: ll_ord
+      CHARACTER(len=2048) :: clfmt            
+   
+      ! reorder the current list by elapse time      
+      s_wrk => NULL()
+      s_timer => s_timer_root
+      DO
+         ll_ord = .TRUE.
+         s_timer => s_timer_root
+         DO WHILE ( ASSOCIATED( s_timer%next ) )
+         IF (.NOT. ASSOCIATED(s_timer%next)) EXIT
+            IF ( s_timer%tsum_clock < s_timer%next%tsum_clock ) THEN 
+               ALLOCATE(s_wrk)
+               s_wrk = s_timer%next
+               CALL insert  (s_timer, s_timer_root, s_wrk)
+               CALL suppress(s_timer%next)            
+               ll_ord = .FALSE.
+               CYCLE            
+            ENDIF           
+         IF( ASSOCIATED(s_timer%next) ) s_timer => s_timer%next
+         END DO         
+         IF( ll_ord ) EXIT
+      END DO
+            
+      ! write current info
+      WRITE(numtime,*) 'Detailed timing for proc :', narea-1
+      WRITE(numtime,*) '--------------------------'
+      WRITE(numtime,*) 'Section             ',            &
+      &   'Elapsed Time (s)  ','Elapsed Time (%)  ',   &
+      &   'CPU Time(s)  ','CPU Time (%)  ','CPU/Elapsed  ','Frequency' 
+      s_timer => s_timer_root  
+      clfmt = '(1x,a,4x,f12.3,6x,f12.3,x,f12.3,2x,f12.3,6x,f7.3,2x,i9)'
+      DO WHILE ( ASSOCIATED(s_timer) )
+         WRITE(numtime,TRIM(clfmt))   s_timer%cname,   &
+         &   s_timer%tsum_clock,s_timer%tsum_clock*100./t_elaps(2),            &
+         &   s_timer%tsum_cpu  ,s_timer%tsum_cpu*100./t_cpu(2)    ,            &
+         &   s_timer%tsum_cpu/s_timer%tsum_clock, s_timer%niter
+         s_timer => s_timer%next
+      END DO
+      WRITE(numtime,*)
+      !                  
+   END SUBROUTINE wcurrent_info
+
+#if defined key_mpp_mpi     
+   SUBROUTINE waver_info
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE wcurrent_info ***
+      !! ** Purpose :  compute and write averaged timing informations
+      !!----------------------------------------------------------------------
+      TYPE(alltimer), POINTER :: sl_timer_glob_root => NULL()
+      TYPE(alltimer), POINTER :: sl_timer_glob      => NULL()
+      TYPE(timer), POINTER :: sl_timer_ave_root => NULL()
+      TYPE(timer), POINTER :: sl_timer_ave      => NULL()
+      INTEGER :: icode
+      INTEGER :: ierr
+      LOGICAL :: ll_ord           
+      CHARACTER(len=200) :: clfmt              
+                 
+      ! Initialised the global strucutre   
+      ALLOCATE(sl_timer_glob_root, Stat=ierr)
+      IF(ierr /= 0)THEN
+         WRITE(numtime,*) 'Failed to allocate global timing structure in waver_info'
+         RETURN
+      END IF
+
+      ALLOCATE(sl_timer_glob_root%cname     (jpnij), &
+               sl_timer_glob_root%tsum_cpu  (jpnij), &
+               sl_timer_glob_root%tsum_clock(jpnij), &
+               sl_timer_glob_root%niter     (jpnij), Stat=ierr)
+      IF(ierr /= 0)THEN
+         WRITE(numtime,*) 'Failed to allocate global timing structure in waver_info'
+         RETURN
+      END IF
+      sl_timer_glob_root%cname(:)       = ''
+      sl_timer_glob_root%tsum_cpu(:)   = 0._wp
+      sl_timer_glob_root%tsum_clock(:) = 0._wp
+      sl_timer_glob_root%niter(:)      = 0
+      sl_timer_glob_root%next => NULL()
+      sl_timer_glob_root%prev => NULL()
+      !ARPDBG - don't need to allocate a pointer that's immediately then
+      !         set to point to some other object.
+      !ALLOCATE(sl_timer_glob)
+      !ALLOCATE(sl_timer_glob%cname     (jpnij))
+      !ALLOCATE(sl_timer_glob%tsum_cpu  (jpnij))
+      !ALLOCATE(sl_timer_glob%tsum_clock(jpnij))
+      !ALLOCATE(sl_timer_glob%niter     (jpnij))
+      sl_timer_glob => sl_timer_glob_root
+      !
+      IF( narea .EQ. 1 ) THEN
+         ALLOCATE(sl_timer_ave_root)
+         sl_timer_ave_root%cname       = ''
+         sl_timer_ave_root%t_cpu      = 0._wp
+         sl_timer_ave_root%t_clock    = 0._wp
+         sl_timer_ave_root%tsum_cpu   = 0._wp
+         sl_timer_ave_root%tsum_clock = 0._wp
+         sl_timer_ave_root%tmax_cpu   = 0._wp
+         sl_timer_ave_root%tmax_clock = 0._wp
+         sl_timer_ave_root%tmin_cpu   = 0._wp
+         sl_timer_ave_root%tmin_clock = 0._wp
+         sl_timer_ave_root%tsub_cpu   = 0._wp
+         sl_timer_ave_root%tsub_clock = 0._wp
+         sl_timer_ave_root%ncount      = 0
+         sl_timer_ave_root%ncount_rate = 0
+         sl_timer_ave_root%ncount_max  = 0
+         sl_timer_ave_root%niter       = 0
+         sl_timer_ave_root%l_tdone  = .FALSE.
+         sl_timer_ave_root%next => NULL()
+         sl_timer_ave_root%prev => NULL()
+         ALLOCATE(sl_timer_ave)
+         sl_timer_ave => sl_timer_ave_root            
+      ENDIF 
+
+      ! Gather info from all processors
+      s_timer => s_timer_root
+      DO WHILE ( ASSOCIATED(s_timer) )
+         CALL MPI_GATHER(s_timer%cname     , 20, MPI_CHARACTER,   &
+                         sl_timer_glob%cname, 20, MPI_CHARACTER,   &
+                         0, MPI_COMM_OCE, icode)
+         CALL MPI_GATHER(s_timer%tsum_clock     , 1, MPI_DOUBLE_PRECISION,   &
+                         sl_timer_glob%tsum_clock, 1, MPI_DOUBLE_PRECISION,   &
+                         0, MPI_COMM_OCE, icode)
+         CALL MPI_GATHER(s_timer%tsum_cpu     , 1, MPI_DOUBLE_PRECISION,   &
+                         sl_timer_glob%tsum_cpu, 1, MPI_DOUBLE_PRECISION,   &
+                         0, MPI_COMM_OCE, icode)
+         CALL MPI_GATHER(s_timer%niter     , 1, MPI_INTEGER,   &
+                         sl_timer_glob%niter, 1, MPI_INTEGER,   &
+                         0, MPI_COMM_OCE, icode)
+
+         IF( narea == 1 .AND. ASSOCIATED(s_timer%next) ) THEN
+            ALLOCATE(sl_timer_glob%next)
+            ALLOCATE(sl_timer_glob%next%cname     (jpnij))
+            ALLOCATE(sl_timer_glob%next%tsum_cpu  (jpnij))
+            ALLOCATE(sl_timer_glob%next%tsum_clock(jpnij))
+            ALLOCATE(sl_timer_glob%next%niter     (jpnij))
+            sl_timer_glob%next%prev => sl_timer_glob
+            sl_timer_glob%next%next => NULL()
+            sl_timer_glob           => sl_timer_glob%next
+         ENDIF              
+         s_timer => s_timer%next
+      END DO      
+      
+      IF( narea == 1 ) THEN    
+         ! Compute some stats
+         sl_timer_glob => sl_timer_glob_root
+         DO WHILE( ASSOCIATED(sl_timer_glob) )
+            sl_timer_ave%cname  = sl_timer_glob%cname(1)
+            sl_timer_ave%tsum_cpu   = SUM   (sl_timer_glob%tsum_cpu  (:)) / jpnij
+            sl_timer_ave%tsum_clock = SUM   (sl_timer_glob%tsum_clock(:)) / jpnij
+            sl_timer_ave%tmax_cpu   = MAXVAL(sl_timer_glob%tsum_cpu  (:))
+            sl_timer_ave%tmax_clock = MAXVAL(sl_timer_glob%tsum_clock(:))
+            sl_timer_ave%tmin_cpu   = MINVAL(sl_timer_glob%tsum_cpu  (:))
+            sl_timer_ave%tmin_clock = MINVAL(sl_timer_glob%tsum_clock(:))
+            sl_timer_ave%niter      = SUM   (sl_timer_glob%niter     (:))
+            !
+            IF( ASSOCIATED(sl_timer_glob%next) ) THEN
+               ALLOCATE(sl_timer_ave%next)          
+               sl_timer_ave%next%prev => sl_timer_ave
+               sl_timer_ave%next%next => NULL()           
+               sl_timer_ave           => sl_timer_ave%next
+            ENDIF
+            sl_timer_glob => sl_timer_glob%next                                
+         END DO
+      
+         ! reorder the averaged list by CPU time      
+         s_wrk => NULL()
+         sl_timer_ave => sl_timer_ave_root
+         DO
+            ll_ord = .TRUE.
+            sl_timer_ave => sl_timer_ave_root
+            DO WHILE( ASSOCIATED( sl_timer_ave%next ) )
+
+               IF( .NOT. ASSOCIATED(sl_timer_ave%next) ) EXIT
+
+               IF ( sl_timer_ave%tsum_clock < sl_timer_ave%next%tsum_clock ) THEN 
+                  ALLOCATE(s_wrk)
+                  ! Copy data into the new object pointed to by s_wrk
+                  s_wrk = sl_timer_ave%next
+                  ! Insert this new timer object before our current position
+                  CALL insert  (sl_timer_ave, sl_timer_ave_root, s_wrk)
+                  ! Remove the old object from the list
+                  CALL suppress(sl_timer_ave%next)            
+                  ll_ord = .FALSE.
+                  CYCLE            
+               ENDIF           
+               IF( ASSOCIATED(sl_timer_ave%next) ) sl_timer_ave => sl_timer_ave%next
+            END DO         
+            IF( ll_ord ) EXIT
+         END DO
+
+         ! write averaged info
+         WRITE(numtime,"('Averaged timing on all processors :')")
+         WRITE(numtime,"('-----------------------------------')")
+         WRITE(numtime,"('Section',13x,'Elap. Time(s)',2x,'Elap. Time(%)',2x, &
+         &   'CPU Time(s)',2x,'CPU Time(%)',2x,'CPU/Elap',1x,   &
+         &   'Max elap(%)',2x,'Min elap(%)',2x,            &           
+         &   'Freq')")
+         sl_timer_ave => sl_timer_ave_root  
+         clfmt = '((A),E15.7,2x,f6.2,5x,f12.2,5x,f6.2,5x,f7.2,2x,f12.2,4x,f6.2,2x,f9.2)'
+         DO WHILE ( ASSOCIATED(sl_timer_ave) )
+            WRITE(numtime,TRIM(clfmt))   sl_timer_ave%cname(1:18),                            &
+            &   sl_timer_ave%tsum_clock,sl_timer_ave%tsum_clock*100.*jpnij/tot_etime,   &
+            &   sl_timer_ave%tsum_cpu  ,sl_timer_ave%tsum_cpu*100.*jpnij/tot_ctime  ,   &
+            &   sl_timer_ave%tsum_cpu/sl_timer_ave%tsum_clock,                          &
+            &   sl_timer_ave%tmax_clock*100.*jpnij/tot_etime,                           &
+            &   sl_timer_ave%tmin_clock*100.*jpnij/tot_etime,                           &                                               
+            &   sl_timer_ave%niter/REAL(jpnij)
+            sl_timer_ave => sl_timer_ave%next
+         END DO
+         WRITE(numtime,*)
+         !
+         DEALLOCATE(sl_timer_ave_root)
+      ENDIF
+      !
+      DEALLOCATE(sl_timer_glob_root)
+      !                  
+   END SUBROUTINE waver_info
+  
+  
+   SUBROUTINE wmpi_info
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE wmpi_time  ***
+      !! ** Purpose :   compute and write a summary of MPI infos 
+      !!----------------------------------------------------------------------   
+      !   
+      INTEGER                            :: idum, icode
+      INTEGER, ALLOCATABLE, DIMENSION(:) :: iall_rank
+      REAL(wp) :: ztot_ratio
+      REAL(wp) :: zmax_etime, zmax_ctime, zmax_ratio, zmin_etime, zmin_ctime, zmin_ratio
+      REAL(wp) :: zavg_etime, zavg_ctime, zavg_ratio
+      REAL(wp), ALLOCATABLE, DIMENSION(:) :: zall_ratio
+      CHARACTER(LEN=128), dimension(8) :: cllignes
+      CHARACTER(LEN=128)               :: clhline, clstart_date, clfinal_date
+      CHARACTER(LEN=2048)              :: clfmt    
+   
+      ! Gather all times
+      ALLOCATE( zall_ratio(jpnij), iall_rank(jpnij) )
+      IF( narea == 1 ) THEN
+         iall_rank(:) = (/ (idum,idum=0,jpnij-1) /)
+   
+         ! Compute elapse user time
+         zavg_etime = tot_etime/REAL(jpnij,wp)
+         zmax_etime = MAXVAL(all_etime(:))
+         zmin_etime = MINVAL(all_etime(:))
+
+         ! Compute CPU user time
+         zavg_ctime = tot_ctime/REAL(jpnij,wp)
+         zmax_ctime = MAXVAL(all_ctime(:))
+         zmin_ctime = MINVAL(all_ctime(:))
+   
+         ! Compute cpu/elapsed ratio
+         zall_ratio(:) = all_ctime(:) / all_etime(:)
+         ztot_ratio    = SUM(all_ctime(:))/SUM(all_etime(:))
+         zavg_ratio    = SUM(zall_ratio(:))/REAL(jpnij,wp)
+         zmax_ratio    = MAXVAL(zall_ratio(:))
+         zmin_ratio    = MINVAL(zall_ratio(:))   
+   
+         ! Output Format
+         clhline    ='1x,13("-"),"|",18("-"),"|",14("-"),"|",18("-"),/,'
+         cllignes(1)='(1x,"MPI summary report :",/,'
+         cllignes(2)='1x,"--------------------",//,'
+         cllignes(3)='1x,"Process Rank |"," Elapsed Time (s) |"," CPU Time (s) |"," Ratio CPU/Elapsed",/,'
+         cllignes(4)='      (4x,i6,4x,"|",f12.3,6x,"|",f12.3,2x,"|",4x,f7.3,/),'
+         WRITE(cllignes(4)(1:6),'(I6)') jpnij
+         cllignes(5)='1x,"Total        |",f12.3,6x,"|",F12.3,2x,"|",4x,f7.3,/,'
+         cllignes(6)='1x,"Minimum      |",f12.3,6x,"|",F12.3,2x,"|",4x,f7.3,/,'
+         cllignes(7)='1x,"Maximum      |",f12.3,6x,"|",F12.3,2x,"|",4x,f7.3,/,'
+         cllignes(8)='1x,"Average      |",f12.3,6x,"|",F12.3,2x,"|",4x,f7.3)'
+         clfmt=TRIM(cllignes(1))// TRIM(cllignes(2))//TRIM(cllignes(3))//          &
+           & TRIM(clhline)//TRIM(cllignes(4))//TRIM(clhline)//TRIM(cllignes(5))//  &
+           & TRIM(clhline)//TRIM(cllignes(6))//TRIM(clhline)//TRIM(cllignes(7))//  &
+           & TRIM(clhline)//TRIM(cllignes(8))
+         WRITE(numtime, TRIM(clfmt)) &
+             (iall_rank(idum),all_etime(idum),all_ctime(idum),zall_ratio(idum),idum=1, jpnij), &
+             tot_etime,     tot_ctime,     ztot_ratio,   &
+             zmin_etime,    zmin_ctime,    zmin_ratio,   &
+             zmax_etime,    zmax_ctime,    zmax_ratio,   &
+             zavg_etime,    zavg_ctime,    zavg_ratio
+         WRITE(numtime,*)    
+      END IF
+      !
+      DEALLOCATE(zall_ratio, iall_rank)
+      !
+   END SUBROUTINE wmpi_info
+#endif   
+
+
+   SUBROUTINE timing_ini_var(cdinfo)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_ini_var  ***
+      !! ** Purpose :   create timing structure 
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*), INTENT(in) :: cdinfo
+      LOGICAL :: ll_section
+       
+      !
+      IF( .NOT. ASSOCIATED(s_timer_root) ) THEN
+         ALLOCATE(s_timer_root)
+         s_timer_root%cname       = cdinfo
+         s_timer_root%t_cpu      = 0._wp
+         s_timer_root%t_clock    = 0._wp
+         s_timer_root%tsum_cpu   = 0._wp
+         s_timer_root%tsum_clock = 0._wp
+         s_timer_root%tmax_cpu   = 0._wp
+         s_timer_root%tmax_clock = 0._wp
+         s_timer_root%tmin_cpu   = 0._wp
+         s_timer_root%tmin_clock = 0._wp
+         s_timer_root%tsub_cpu   = 0._wp
+         s_timer_root%tsub_clock = 0._wp
+         s_timer_root%ncount      = 0
+         s_timer_root%ncount_rate = 0
+         s_timer_root%ncount_max  = 0
+         s_timer_root%niter       = 0
+         s_timer_root%l_tdone  = .FALSE.
+         s_timer_root%next => NULL()
+         s_timer_root%prev => NULL()
+         s_timer => s_timer_root
+         !
+         ALLOCATE(s_wrk)
+         s_wrk => NULL()
+         !
+         ALLOCATE(s_timer_old)
+         s_timer_old%cname       = cdinfo
+         s_timer_old%t_cpu      = 0._wp
+         s_timer_old%t_clock    = 0._wp
+         s_timer_old%tsum_cpu   = 0._wp
+         s_timer_old%tsum_clock = 0._wp
+         s_timer_old%tmax_cpu   = 0._wp
+         s_timer_old%tmax_clock = 0._wp
+         s_timer_old%tmin_cpu   = 0._wp
+         s_timer_old%tmin_clock = 0._wp
+         s_timer_old%tsub_cpu   = 0._wp
+         s_timer_old%tsub_clock = 0._wp
+         s_timer_old%ncount      = 0
+         s_timer_old%ncount_rate = 0
+         s_timer_old%ncount_max  = 0
+         s_timer_old%niter       = 0
+         s_timer_old%l_tdone  = .TRUE.
+         s_timer_old%next => NULL()
+         s_timer_old%prev => NULL()
+
+      ELSE
+         s_timer => s_timer_root
+         ! case of already existing area (typically inside a loop)
+   !         write(*,*) 'in ini_var for routine : ', cdinfo
+         DO WHILE( ASSOCIATED(s_timer) ) 
+            IF( TRIM(s_timer%cname) .EQ. TRIM(cdinfo) ) THEN
+ !             write(*,*) 'in ini_var for routine : ', cdinfo,' we return'           
+               RETURN ! cdinfo is already in the chain
+            ENDIF
+            s_timer => s_timer%next
+         END DO
+
+         ! end of the chain
+         s_timer => s_timer_root
+         DO WHILE( ASSOCIATED(s_timer%next) )
+            s_timer => s_timer%next
+         END DO
+
+    !     write(*,*) 'after search', s_timer%cname
+         ! cdinfo is not part of the chain so we add it with initialisation          
+          ALLOCATE(s_timer%next)
+    !     write(*,*) 'after allocation of next'
+  
+         s_timer%next%cname       = cdinfo
+         s_timer%next%t_cpu      = 0._wp
+         s_timer%next%t_clock    = 0._wp
+         s_timer%next%tsum_cpu   = 0._wp
+         s_timer%next%tsum_clock = 0._wp  
+         s_timer%next%tmax_cpu   = 0._wp
+         s_timer%next%tmax_clock = 0._wp
+         s_timer%next%tmin_cpu   = 0._wp
+         s_timer%next%tmin_clock = 0._wp
+         s_timer%next%tsub_cpu   = 0._wp
+         s_timer%next%tsub_clock = 0._wp
+         s_timer%next%ncount      = 0
+         s_timer%next%ncount_rate = 0
+         s_timer%next%ncount_max  = 0
+         s_timer%next%niter       = 0
+         s_timer%next%l_tdone  = .FALSE.
+         s_timer%next%parent_section => NULL()
+         s_timer%next%prev => s_timer
+         s_timer%next%next => NULL()
+         s_timer => s_timer%next
+      ENDIF 
+      !    write(*,*) 'after allocation'
+     !
+   END SUBROUTINE timing_ini_var
+
+
+   SUBROUTINE timing_reset
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE timing_reset  ***
+      !! ** Purpose :   go to root of timing tree 
+      !!----------------------------------------------------------------------
+      l_initdone = .TRUE. 
+!      IF(lwp) WRITE(numout,*)
+!      IF(lwp) WRITE(numout,*) 'timing_reset : instrumented routines for timing'
+!      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      CALL timing_list(s_timer_root)
+!      WRITE(numout,*)
+      !
+   END SUBROUTINE timing_reset
+
+
+   RECURSIVE SUBROUTINE timing_list(ptr)
+   
+      TYPE(timer), POINTER, INTENT(inout) :: ptr
+      !
+      IF( ASSOCIATED(ptr%next) ) CALL timing_list(ptr%next)
+      IF(lwp) WRITE(numout,*)'   ', ptr%cname   
+      !
+   END SUBROUTINE timing_list
+
+
+   SUBROUTINE insert(sd_current, sd_root ,sd_ptr)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE insert  ***
+      !! ** Purpose :   insert an element in timer structure
+      !!----------------------------------------------------------------------
+      TYPE(timer), POINTER, INTENT(inout) :: sd_current, sd_root, sd_ptr
+      !
+     
+      IF( ASSOCIATED( sd_current, sd_root ) ) THEN
+         ! If our current element is the root element then
+         ! replace it with the one being inserted
+         sd_root => sd_ptr
+      ELSE
+         sd_current%prev%next => sd_ptr
+      END IF
+      sd_ptr%next     => sd_current
+      sd_ptr%prev     => sd_current%prev
+      sd_current%prev => sd_ptr
+      ! Nullify the pointer to the new element now that it is held
+      ! within the list. If we don't do this then a subsequent call
+      ! to ALLOCATE memory to this pointer will fail.
+      sd_ptr => NULL()
+      !    
+   END SUBROUTINE insert
+  
+  
+   SUBROUTINE suppress(sd_ptr)
+      !!----------------------------------------------------------------------
+      !!               ***  ROUTINE suppress  ***
+      !! ** Purpose :   supress an element in timer structure
+      !!----------------------------------------------------------------------
+      TYPE(timer), POINTER, INTENT(inout) :: sd_ptr
+      !
+      TYPE(timer), POINTER :: sl_temp
+    
+      sl_temp => sd_ptr
+      sd_ptr => sd_ptr%next    
+      IF ( ASSOCIATED(sl_temp%next) ) sl_temp%next%prev => sl_temp%prev
+      DEALLOCATE(sl_temp)
+      sl_temp => NULL()
+      !
+    END SUBROUTINE suppress
+
+   !!=====================================================================
+END MODULE timing
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/trc_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/trc_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/trc_oce.F90	(revision 14097)
@@ -0,0 +1,259 @@
+MODULE trc_oce
+   !!======================================================================
+   !!                      ***  MODULE  trc_oce  ***
+   !! Ocean passive tracer  :  share SMS/Ocean variables
+   !!======================================================================
+   !! History :  1.0  !  2004-03  (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trc_oce_rgb   : tabulated attenuation coefficients for RGB light penetration         
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+   USE dom_oce        ! ocean space and time domain
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_oce_rgb        ! routine called by traqsr.F90
+   PUBLIC   trc_oce_rgb_read   ! routine called by traqsr.F90
+   PUBLIC   trc_oce_ext_lev    ! function called by traqsr.F90 at least
+   PUBLIC   trc_oce_alloc      ! function called by nemogcm.F90
+
+   LOGICAL , PUBLIC ::   l_co2cpl  = .false.   !: atmospheric pco2 recieved from oasis
+   LOGICAL , PUBLIC ::   l_offline = .false.   !: offline passive tracers flag
+   INTEGER , PUBLIC ::   nn_dttrc              !: frequency of step on passive tracers
+   REAL(wp), PUBLIC ::   r_si2                 !: largest depth of extinction (blue & 0.01 mg.m-3)  (RGB)
+   !
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   etot3     !: light absortion coefficient
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   oce_co2   !: ocean carbon flux
+
+#if defined key_top 
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                 bio-model          
+   !!----------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_top     = .TRUE.   !: TOP model
+#else
+   !!----------------------------------------------------------------------
+   !! Default option                          No bio-model light absorption      
+   !!----------------------------------------------------------------------
+   LOGICAL, PUBLIC, PARAMETER ::   lk_top     = .FALSE.   !: TOP model
+#endif
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trc_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  trc_oce_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( etot3(jpi,jpj,jpk), oce_co2(jpi,jpj), STAT=trc_oce_alloc )
+      IF( trc_oce_alloc /= 0 )   CALL ctl_warn('trc_oce_alloc: failed to allocate etot3 array')
+      !
+   END FUNCTION trc_oce_alloc
+
+
+   SUBROUTINE trc_oce_rgb( prgb )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_opt_init  ***
+      !!
+      !! ** Purpose :   Initialization of of the optical scheme
+      !!
+      !! ** Method  :   Set a look up table for the optical coefficients
+      !!                i.e. the attenuation coefficient for R-G-B light 
+      !!                tabulated in Chlorophyll class (from JM Andre)
+      !!
+      !! ** Action  :   prgb(3,61) tabulated R-G-B attenuation coef. 
+      !!
+      !! Reference  : Lengaigne et al. 2007, Clim. Dyn., V28, 5, 503-516.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(3,61), INTENT(out) ::   prgb   ! tabulated attenuation coefficient
+      !
+      INTEGER  ::   jc     ! dummy loop indice
+      INTEGER  ::   irgb   ! temporary integer
+      REAL(wp) ::   zchl   ! temporary scalar
+      REAL(wp), DIMENSION(4,61) ::   zrgb   ! tabulated attenuation coefficient (formerly read in 'kRGB61.txt')
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   trc_oce_rgb : Initialisation of the optical look-up table'
+         WRITE(numout,*) '   ~~~~~~~~~~~ '
+      ENDIF
+      !
+      !  Chlorophyll        !     Blue attenuation     !     Green attenuation    !     Red attenuation      !
+      zrgb(1, 1) =  0.010   ;   zrgb(2, 1) = 0.01618   ;   zrgb(3, 1) = 0.07464   ;   zrgb(4, 1) = 0.37807
+      zrgb(1, 2) =  0.011   ;   zrgb(2, 2) = 0.01654   ;   zrgb(3, 2) = 0.07480   ;   zrgb(4, 2) = 0.37823
+      zrgb(1, 3) =  0.013   ;   zrgb(2, 3) = 0.01693   ;   zrgb(3, 3) = 0.07499   ;   zrgb(4, 3) = 0.37840
+      zrgb(1, 4) =  0.014   ;   zrgb(2, 4) = 0.01736   ;   zrgb(3, 4) = 0.07518   ;   zrgb(4, 4) = 0.37859
+      zrgb(1, 5) =  0.016   ;   zrgb(2, 5) = 0.01782   ;   zrgb(3, 5) = 0.07539   ;   zrgb(4, 5) = 0.37879
+      zrgb(1, 6) =  0.018   ;   zrgb(2, 6) = 0.01831   ;   zrgb(3, 6) = 0.07562   ;   zrgb(4, 6) = 0.37900
+      zrgb(1, 7) =  0.020   ;   zrgb(2, 7) = 0.01885   ;   zrgb(3, 7) = 0.07586   ;   zrgb(4, 7) = 0.37923
+      zrgb(1, 8) =  0.022   ;   zrgb(2, 8) = 0.01943   ;   zrgb(3, 8) = 0.07613   ;   zrgb(4, 8) = 0.37948
+      zrgb(1, 9) =  0.025   ;   zrgb(2, 9) = 0.02005   ;   zrgb(3, 9) = 0.07641   ;   zrgb(4, 9) = 0.37976
+      zrgb(1,10) =  0.028   ;   zrgb(2,10) = 0.02073   ;   zrgb(3,10) = 0.07672   ;   zrgb(4,10) = 0.38005
+      zrgb(1,11) =  0.032   ;   zrgb(2,11) = 0.02146   ;   zrgb(3,11) = 0.07705   ;   zrgb(4,11) = 0.38036
+      zrgb(1,12) =  0.035   ;   zrgb(2,12) = 0.02224   ;   zrgb(3,12) = 0.07741   ;   zrgb(4,12) = 0.38070
+      zrgb(1,13) =  0.040   ;   zrgb(2,13) = 0.02310   ;   zrgb(3,13) = 0.07780   ;   zrgb(4,13) = 0.38107
+      zrgb(1,14) =  0.045   ;   zrgb(2,14) = 0.02402   ;   zrgb(3,14) = 0.07821   ;   zrgb(4,14) = 0.38146
+      zrgb(1,15) =  0.050   ;   zrgb(2,15) = 0.02501   ;   zrgb(3,15) = 0.07866   ;   zrgb(4,15) = 0.38189
+      zrgb(1,16) =  0.056   ;   zrgb(2,16) = 0.02608   ;   zrgb(3,16) = 0.07914   ;   zrgb(4,16) = 0.38235
+      zrgb(1,17) =  0.063   ;   zrgb(2,17) = 0.02724   ;   zrgb(3,17) = 0.07967   ;   zrgb(4,17) = 0.38285
+      zrgb(1,18) =  0.071   ;   zrgb(2,18) = 0.02849   ;   zrgb(3,18) = 0.08023   ;   zrgb(4,18) = 0.38338
+      zrgb(1,19) =  0.079   ;   zrgb(2,19) = 0.02984   ;   zrgb(3,19) = 0.08083   ;   zrgb(4,19) = 0.38396
+      zrgb(1,20) =  0.089   ;   zrgb(2,20) = 0.03131   ;   zrgb(3,20) = 0.08149   ;   zrgb(4,20) = 0.38458
+      zrgb(1,21) =  0.100   ;   zrgb(2,21) = 0.03288   ;   zrgb(3,21) = 0.08219   ;   zrgb(4,21) = 0.38526
+      zrgb(1,22) =  0.112   ;   zrgb(2,22) = 0.03459   ;   zrgb(3,22) = 0.08295   ;   zrgb(4,22) = 0.38598
+      zrgb(1,23) =  0.126   ;   zrgb(2,23) = 0.03643   ;   zrgb(3,23) = 0.08377   ;   zrgb(4,23) = 0.38676
+      zrgb(1,24) =  0.141   ;   zrgb(2,24) = 0.03842   ;   zrgb(3,24) = 0.08466   ;   zrgb(4,24) = 0.38761
+      zrgb(1,25) =  0.158   ;   zrgb(2,25) = 0.04057   ;   zrgb(3,25) = 0.08561   ;   zrgb(4,25) = 0.38852
+      zrgb(1,26) =  0.178   ;   zrgb(2,26) = 0.04289   ;   zrgb(3,26) = 0.08664   ;   zrgb(4,26) = 0.38950
+      zrgb(1,27) =  0.200   ;   zrgb(2,27) = 0.04540   ;   zrgb(3,27) = 0.08775   ;   zrgb(4,27) = 0.39056
+      zrgb(1,28) =  0.224   ;   zrgb(2,28) = 0.04811   ;   zrgb(3,28) = 0.08894   ;   zrgb(4,28) = 0.39171
+      zrgb(1,29) =  0.251   ;   zrgb(2,29) = 0.05103   ;   zrgb(3,29) = 0.09023   ;   zrgb(4,29) = 0.39294
+      zrgb(1,30) =  0.282   ;   zrgb(2,30) = 0.05420   ;   zrgb(3,30) = 0.09162   ;   zrgb(4,30) = 0.39428
+      zrgb(1,31) =  0.316   ;   zrgb(2,31) = 0.05761   ;   zrgb(3,31) = 0.09312   ;   zrgb(4,31) = 0.39572
+      zrgb(1,32) =  0.355   ;   zrgb(2,32) = 0.06130   ;   zrgb(3,32) = 0.09474   ;   zrgb(4,32) = 0.39727
+      zrgb(1,33) =  0.398   ;   zrgb(2,33) = 0.06529   ;   zrgb(3,33) = 0.09649   ;   zrgb(4,33) = 0.39894
+      zrgb(1,34) =  0.447   ;   zrgb(2,34) = 0.06959   ;   zrgb(3,34) = 0.09837   ;   zrgb(4,34) = 0.40075
+      zrgb(1,35) =  0.501   ;   zrgb(2,35) = 0.07424   ;   zrgb(3,35) = 0.10040   ;   zrgb(4,35) = 0.40270
+      zrgb(1,36) =  0.562   ;   zrgb(2,36) = 0.07927   ;   zrgb(3,36) = 0.10259   ;   zrgb(4,36) = 0.40480
+      zrgb(1,37) =  0.631   ;   zrgb(2,37) = 0.08470   ;   zrgb(3,37) = 0.10495   ;   zrgb(4,37) = 0.40707
+      zrgb(1,38) =  0.708   ;   zrgb(2,38) = 0.09056   ;   zrgb(3,38) = 0.10749   ;   zrgb(4,38) = 0.40952
+      zrgb(1,39) =  0.794   ;   zrgb(2,39) = 0.09690   ;   zrgb(3,39) = 0.11024   ;   zrgb(4,39) = 0.41216
+      zrgb(1,40) =  0.891   ;   zrgb(2,40) = 0.10374   ;   zrgb(3,40) = 0.11320   ;   zrgb(4,40) = 0.41502
+      zrgb(1,41) =  1.000   ;   zrgb(2,41) = 0.11114   ;   zrgb(3,41) = 0.11639   ;   zrgb(4,41) = 0.41809
+      zrgb(1,42) =  1.122   ;   zrgb(2,42) = 0.11912   ;   zrgb(3,42) = 0.11984   ;   zrgb(4,42) = 0.42142
+      zrgb(1,43) =  1.259   ;   zrgb(2,43) = 0.12775   ;   zrgb(3,43) = 0.12356   ;   zrgb(4,43) = 0.42500
+      zrgb(1,44) =  1.413   ;   zrgb(2,44) = 0.13707   ;   zrgb(3,44) = 0.12757   ;   zrgb(4,44) = 0.42887
+      zrgb(1,45) =  1.585   ;   zrgb(2,45) = 0.14715   ;   zrgb(3,45) = 0.13189   ;   zrgb(4,45) = 0.43304
+      zrgb(1,46) =  1.778   ;   zrgb(2,46) = 0.15803   ;   zrgb(3,46) = 0.13655   ;   zrgb(4,46) = 0.43754
+      zrgb(1,47) =  1.995   ;   zrgb(2,47) = 0.16978   ;   zrgb(3,47) = 0.14158   ;   zrgb(4,47) = 0.44240
+      zrgb(1,48) =  2.239   ;   zrgb(2,48) = 0.18248   ;   zrgb(3,48) = 0.14701   ;   zrgb(4,48) = 0.44765
+      zrgb(1,49) =  2.512   ;   zrgb(2,49) = 0.19620   ;   zrgb(3,49) = 0.15286   ;   zrgb(4,49) = 0.45331
+      zrgb(1,50) =  2.818   ;   zrgb(2,50) = 0.21102   ;   zrgb(3,50) = 0.15918   ;   zrgb(4,50) = 0.45942
+      zrgb(1,51) =  3.162   ;   zrgb(2,51) = 0.22703   ;   zrgb(3,51) = 0.16599   ;   zrgb(4,51) = 0.46601
+      zrgb(1,52) =  3.548   ;   zrgb(2,52) = 0.24433   ;   zrgb(3,52) = 0.17334   ;   zrgb(4,52) = 0.47313
+      zrgb(1,53) =  3.981   ;   zrgb(2,53) = 0.26301   ;   zrgb(3,53) = 0.18126   ;   zrgb(4,53) = 0.48080
+      zrgb(1,54) =  4.467   ;   zrgb(2,54) = 0.28320   ;   zrgb(3,54) = 0.18981   ;   zrgb(4,54) = 0.48909
+      zrgb(1,55) =  5.012   ;   zrgb(2,55) = 0.30502   ;   zrgb(3,55) = 0.19903   ;   zrgb(4,55) = 0.49803
+      zrgb(1,56) =  5.623   ;   zrgb(2,56) = 0.32858   ;   zrgb(3,56) = 0.20898   ;   zrgb(4,56) = 0.50768
+      zrgb(1,57) =  6.310   ;   zrgb(2,57) = 0.35404   ;   zrgb(3,57) = 0.21971   ;   zrgb(4,57) = 0.51810
+      zrgb(1,58) =  7.079   ;   zrgb(2,58) = 0.38154   ;   zrgb(3,58) = 0.23129   ;   zrgb(4,58) = 0.52934
+      zrgb(1,59) =  7.943   ;   zrgb(2,59) = 0.41125   ;   zrgb(3,59) = 0.24378   ;   zrgb(4,59) = 0.54147
+      zrgb(1,60) =  8.912   ;   zrgb(2,60) = 0.44336   ;   zrgb(3,60) = 0.25725   ;   zrgb(4,60) = 0.55457
+      zrgb(1,61) = 10.000   ;   zrgb(2,61) = 0.47804   ;   zrgb(3,61) = 0.27178   ;   zrgb(4,61) = 0.56870
+      !
+      prgb(:,:) = zrgb(2:4,:)
+      !
+      r_si2 = 1.e0 / zrgb(2, 1)        ! blue with the smallest chlorophyll concentration)
+      IF(lwp) WRITE(numout,*) '      RGB longest depth of extinction    r_si2 = ', r_si2
+      !
+      DO jc = 1, 61                         ! check
+         zchl = zrgb(1,jc)
+         irgb = NINT( 41 + 20.* LOG10( zchl ) + 1.e-15 )
+         IF(lwp .AND. nn_print >= 1 ) WRITE(numout,*) '    jc =', jc, '  Chl = ', zchl, '  irgb = ', irgb
+         IF( irgb /= jc ) THEN
+            IF(lwp) WRITE(numout,*) '    jc =', jc, '  Chl = ', zchl, '  Chl class = ', irgb
+            CALL ctl_stop( 'trc_oce_rgb : inconsistency in Chl tabulated attenuation coeff.' )
+         ENDIF
+      END DO
+      !
+   END SUBROUTINE trc_oce_rgb
+
+
+   SUBROUTINE trc_oce_rgb_read( prgb )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_opt_init  ***
+      !!
+      !! ** Purpose :   Initialization of of the optical scheme
+      !!
+      !! ** Method  :   read the look up table for the optical coefficients
+      !!
+      !! ** input   :   xkrgb(61) precomputed array corresponding to the  
+      !!                          attenuation coefficient (from JM Andre)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(3,61), INTENT(out) ::   prgb   ! tabulated attenuation coefficient
+      !
+      INTEGER  ::   jc, jb ! dummy loop indice
+      INTEGER  ::   irgb   ! temporary integer
+      REAL(wp) ::   zchl   ! temporary scalar
+      INTEGER  ::   numlight
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) ' trc_oce_rgb_read : optical look-up table read in kRGB61.txt file'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) 
+      ENDIF
+      !
+      CALL ctl_opn( numlight, 'kRGB61.txt', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+      DO jc = 1, 61
+         READ(numlight,*) zchl, ( prgb(jb,jc), jb = 1, 3 )
+         irgb = NINT( 41 + 20.* LOG10( zchl ) + 1.e-15 )   
+         IF(lwp) WRITE(numout,*) '    jc =', jc, '  Chl = ', zchl, '  irgb = ', irgb  
+         IF( irgb /= jc ) THEN  
+            IF(lwp) WRITE(numout,*) '    jc =', jc, '  Chl = ', zchl, '  Chl class = ', irgb
+            CALL ctl_stop( 'trc_oce_rgb_read : inconsistency in Chl tabulated attenuation coeff.' )
+         ENDIF
+      END DO
+      CLOSE( numlight )
+      !
+      r_si2 = 1.e0 / prgb(1, 1)      ! blue with the smallest chlorophyll concentration)
+      IF(lwp) WRITE(numout,*) '      RGB longest depth of extinction    r_si2 = ', r_si2
+      !
+   END SUBROUTINE trc_oce_rgb_read
+
+
+   FUNCTION trc_oce_ext_lev( prldex, pqsr_frc ) RESULT( pjl )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE trc_oce_ext_lev  ***
+      !!       
+      !! ** Purpose :   compute max. level for light penetration
+      !!          
+      !! ** Method  :   the function provides the level at which irradiance 
+      !!                becomes negligible (i.e. = 1.e-15 W/m2) for 3 or 2 bands light
+      !!                penetration: I(z) = pqsr_frc * EXP(hext/prldex) = 1.e-15 W/m2
+      !!                # prldex is the longest depth of extinction:
+      !!                   - prldex = 23 m (2 bands case)
+      !!                   - prldex = 62 m (3 bands case: blue waveband & 0.01 mg/m2 for the chlorophyll)
+      !!                # pqsr_frc is the fraction of solar radiation which penetrates,
+      !!                considering Qsr=240 W/m2 and rn_abs = 0.58:
+      !!                   - pqsr_frc = Qsr * (1-rn_abs)   = 1.00e2 W/m2 (2 bands case)
+      !!                   - pqsr_frc = Qsr * (1-rn_abs)/3 = 0.33e2 W/m2 (3 bands case & equi-partition)
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in) ::   prldex    ! longest depth of extinction
+      REAL(wp), INTENT(in) ::   pqsr_frc  ! frac. solar radiation which penetrates 
+      !
+      INTEGER  ::   jk, pjl            ! levels
+      REAL(wp) ::   zhext              ! deepest level till which light penetrates
+      REAL(wp) ::   zprec = 15._wp     ! precision to reach -LOG10(1.e-15)
+      REAL(wp) ::   zem                ! temporary scalar 
+      !!----------------------------------------------------------------------
+      !
+      ! It is not necessary to compute anything below the following depth
+      zhext = prldex * ( LOG(10._wp) * zprec + LOG(pqsr_frc) )
+      !
+      ! Level of light extinction
+      pjl = jpkm1
+      DO jk = jpkm1, 1, -1
+         IF(SUM(tmask(:,:,jk)) > 0 ) THEN
+            zem = MAXVAL( gdepw_0(:,:,jk+1) * tmask(:,:,jk) )
+            IF( zem >= zhext )   pjl = jk                       ! last T-level reached by Qsr
+         ELSE
+            pjl = jk                                            ! or regional sea-bed depth 
+         ENDIF
+      END DO
+      !
+   END FUNCTION trc_oce_ext_lev
+
+   !!======================================================================
+END MODULE trc_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/vectopt_loop_substitute.h90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/vectopt_loop_substitute.h90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OCE/vectopt_loop_substitute.h90	(revision 14097)
@@ -0,0 +1,18 @@
+   !!----------------------------------------------------------------------
+   !!                   ***  vectopt_loop_substitute  ***
+   !!----------------------------------------------------------------------
+   !! ** purpose :   substitute the inner loop start/end indices with CPP macro
+   !!                allow unrolling of do-loop (useful with vector processors)
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+#if defined key_vectopt_loop
+#  define   fs_2       1
+#  define   fs_jpim1   jpi
+#else
+#  define   fs_2       2
+#  define   fs_jpim1   jpim1
+#endif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/dtadyn.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/dtadyn.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/dtadyn.F90	(revision 14097)
@@ -0,0 +1,804 @@
+MODULE dtadyn
+   !!======================================================================
+   !!                       ***  MODULE  dtadyn  ***
+   !! Off-line : interpolation of the physical fields
+   !!======================================================================
+   !! History :   OPA  ! 1992-01 (M. Imbard) Original code
+   !!             8.0  ! 1998-04 (L.Bopp MA Foujols) slopes for isopyc. 
+   !!              -   ! 1998-05 (L. Bopp) read output of coupled run
+   !!             8.2  ! 2001-01 (M. Levy et M. Benjelloul) add netcdf FORMAT
+   !!   NEMO      1.0  ! 2005-03 (O. Aumont and A. El Moussaoui) F90
+   !!              -   ! 2005-12 (C. Ethe) Adapted for DEGINT
+   !!             3.0  ! 2007-06 (C. Ethe) use of iom module
+   !!             3.3  ! 2010-11 (C. Ethe) Full reorganization of the off-line: phasing with the on-line
+   !!             3.4  ! 2011-05 (C. Ethe) Use of fldread
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dta_dyn_init : initialization, namelist read, and SAVEs control
+   !!   dta_dyn      : Interpolation of the fields
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE c1d             ! 1D configuration: lk_c1d
+   USE dom_oce         ! ocean domain: variables
+   USE domvvl          ! variable volume
+   USE zdf_oce         ! ocean vertical physics: variables
+   USE sbc_oce         ! surface module: variables
+   USE trc_oce         ! share ocean/biogeo variables
+   USE phycst          ! physical constants
+   USE trabbl          ! active tracer: bottom boundary layer
+   USE ldfslp          ! lateral diffusion: iso-neutral slopes
+   USE sbcrnf          ! river runoffs
+   USE ldftra          ! ocean tracer   lateral physics
+   USE zdfmxl          ! vertical physics: mixed layer depth
+   USE eosbn2          ! equation of state - Brunt Vaisala frequency
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE zpshde          ! z-coord. with partial steps: horizontal derivatives
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O library
+   USE lib_mpp         ! distributed memory computing library
+   USE prtctl          ! print control
+   USE fldread         ! read input fields 
+   USE timing          ! Timing
+   USE trc, ONLY : ln_rsttr, numrtr, numrtw, lrst_trc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dta_dyn_init       ! called by opa.F90
+   PUBLIC   dta_dyn            ! called by step.F90
+   PUBLIC   dta_dyn_sed_init   ! called by opa.F90
+   PUBLIC   dta_dyn_sed        ! called by step.F90
+   PUBLIC   dta_dyn_swp        ! called by step.F90
+
+   CHARACTER(len=100) ::   cn_dir          !: Root directory for location of ssr files
+   LOGICAL            ::   ln_dynrnf       !: read runoff data in file (T) or set to zero (F)
+   LOGICAL            ::   ln_dynrnf_depth       !: read runoff data in file (T) or set to zero (F)
+   REAL(wp)           ::   fwbcorr
+
+
+   INTEGER  , PARAMETER ::   jpfld = 20     ! maximum number of fields to read
+   INTEGER  , SAVE      ::   jf_tem         ! index of temperature
+   INTEGER  , SAVE      ::   jf_sal         ! index of salinity
+   INTEGER  , SAVE      ::   jf_uwd         ! index of u-transport
+   INTEGER  , SAVE      ::   jf_vwd         ! index of v-transport
+   INTEGER  , SAVE      ::   jf_wwd         ! index of v-transport
+   INTEGER  , SAVE      ::   jf_avt         ! index of Kz
+   INTEGER  , SAVE      ::   jf_mld         ! index of mixed layer deptht
+   INTEGER  , SAVE      ::   jf_emp         ! index of water flux
+   INTEGER  , SAVE      ::   jf_empb        ! index of water flux
+   INTEGER  , SAVE      ::   jf_qsr         ! index of solar radiation
+   INTEGER  , SAVE      ::   jf_wnd         ! index of wind speed
+   INTEGER  , SAVE      ::   jf_ice         ! index of sea ice cover
+   INTEGER  , SAVE      ::   jf_rnf         ! index of river runoff
+   INTEGER  , SAVE      ::   jf_fmf         ! index of downward salt flux
+   INTEGER  , SAVE      ::   jf_ubl         ! index of u-bbl coef
+   INTEGER  , SAVE      ::   jf_vbl         ! index of v-bbl coef
+   INTEGER  , SAVE      ::   jf_div         ! index of e3t
+
+
+   TYPE(FLD), ALLOCATABLE, SAVE, DIMENSION(:) :: sf_dyn  ! structure of input fields (file informations, fields read)
+   !                                               ! 
+   REAL(wp) , ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) :: uslpdta    ! zonal isopycnal slopes
+   REAL(wp) , ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) :: vslpdta    ! meridional isopycnal slopes
+   REAL(wp) , ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) :: wslpidta   ! zonal diapycnal slopes
+   REAL(wp) , ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) :: wslpjdta   ! meridional diapycnal slopes
+
+   INTEGER, SAVE  :: nprevrec, nsecdyn
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OFF 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE dta_dyn( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dta_dyn  ***
+      !!
+      !! ** Purpose :  Prepares dynamics and physics fields from a NEMO run
+      !!               for an off-line simulation of passive tracers
+      !!
+      !! ** Method : calculates the position of data 
+      !!             - computes slopes if needed
+      !!             - interpolates data if needed
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER             ::   ji, jj, jk
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   zemp
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   zhdivtr
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'dta_dyn')
+      !
+      nsecdyn = nsec_year + nsec1jan000   ! number of seconds between Jan. 1st 00h of nit000 year and the middle of time step
+      !
+      IF( kt == nit000 ) THEN    ;    nprevrec = 0
+      ELSE                       ;    nprevrec = sf_dyn(jf_tem)%nrec_a(2)
+      ENDIF
+      CALL fld_read( kt, 1, sf_dyn )      !=  read data at kt time step   ==!
+      !
+      IF( l_ldfslp .AND. .NOT.lk_c1d )   CALL  dta_dyn_slp( kt )    ! Computation of slopes
+      !
+      tsn(:,:,:,jp_tem) = sf_dyn(jf_tem)%fnow(:,:,:)  * tmask(:,:,:)    ! temperature
+      tsn(:,:,:,jp_sal) = sf_dyn(jf_sal)%fnow(:,:,:)  * tmask(:,:,:)    ! salinity
+      wndm(:,:)         = sf_dyn(jf_wnd)%fnow(:,:,1)  * tmask(:,:,1)    ! wind speed - needed for gas exchange
+      fmmflx(:,:)       = sf_dyn(jf_fmf)%fnow(:,:,1)  * tmask(:,:,1)    ! downward salt flux (v3.5+)
+      fr_i(:,:)         = sf_dyn(jf_ice)%fnow(:,:,1)  * tmask(:,:,1)    ! Sea-ice fraction
+      qsr (:,:)         = sf_dyn(jf_qsr)%fnow(:,:,1)  * tmask(:,:,1)    ! solar radiation
+      emp (:,:)         = sf_dyn(jf_emp)%fnow(:,:,1)  * tmask(:,:,1)    ! E-P
+      IF( ln_dynrnf ) THEN 
+         rnf (:,:)      = sf_dyn(jf_rnf)%fnow(:,:,1) * tmask(:,:,1)    ! E-P
+         IF( ln_dynrnf_depth .AND. .NOT. ln_linssh )    CALL  dta_dyn_hrnf
+      ENDIF
+      !
+      un(:,:,:)        = sf_dyn(jf_uwd)%fnow(:,:,:) * umask(:,:,:)    ! effective u-transport
+      vn(:,:,:)        = sf_dyn(jf_vwd)%fnow(:,:,:) * vmask(:,:,:)    ! effective v-transport
+      wn(:,:,:)        = sf_dyn(jf_wwd)%fnow(:,:,:) * tmask(:,:,:)    ! effective v-transport
+      !
+      IF( .NOT.ln_linssh ) THEN
+         ALLOCATE( zemp(jpi,jpj) , zhdivtr(jpi,jpj,jpk) )
+         zhdivtr(:,:,:) = sf_dyn(jf_div)%fnow(:,:,:)  * tmask(:,:,:)    ! effective u-transport
+         emp_b  (:,:)   = sf_dyn(jf_empb)%fnow(:,:,1) * tmask(:,:,1)    ! E-P
+         zemp   (:,:)   = ( 0.5_wp * ( emp(:,:) + emp_b(:,:) ) + rnf(:,:) + fwbcorr ) * tmask(:,:,1)
+         CALL dta_dyn_ssh( kt, zhdivtr, sshb, zemp, ssha, e3t_a(:,:,:) )  !=  ssh, vertical scale factor & vertical transport
+         DEALLOCATE( zemp , zhdivtr )
+         !                                           Write in the tracer restart file
+         !                                          *********************************
+         IF( lrst_trc ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'dta_dyn_ssh : ssh field written in tracer restart file at it= ', kt,' date= ', ndastp
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+            CALL iom_rstput( kt, nitrst, numrtw, 'sshn', ssha )
+            CALL iom_rstput( kt, nitrst, numrtw, 'sshb', sshn )
+         ENDIF
+      ENDIF
+      !
+      CALL eos    ( tsn, rhd, rhop, gdept_0(:,:,:) ) ! In any case, we need rhop
+      CALL eos_rab( tsn, rab_n )       ! now    local thermal/haline expension ratio at T-points
+      CALL bn2    ( tsn, rab_n, rn2 ) ! before Brunt-Vaisala frequency need for zdfmxl
+
+      rn2b(:,:,:) = rn2(:,:,:)         ! need for zdfmxl
+      CALL zdf_mxl( kt )                                                   ! In any case, we need mxl
+      !
+      hmld(:,:)       = sf_dyn(jf_mld)%fnow(:,:,1) * tmask(:,:,1)    ! mixed layer depht
+      avt(:,:,:)      = sf_dyn(jf_avt)%fnow(:,:,:) * tmask(:,:,:)    ! vertical diffusive coefficient 
+      avs(:,:,:)      = avt(:,:,:)
+      !
+      IF( ln_trabbl .AND. .NOT.lk_c1d ) THEN       ! diffusive Bottom boundary layer param 
+         ahu_bbl(:,:) = sf_dyn(jf_ubl)%fnow(:,:,1) * umask(:,:,1)    ! bbl diffusive coef
+         ahv_bbl(:,:) = sf_dyn(jf_vbl)%fnow(:,:,1) * vmask(:,:,1)
+      ENDIF
+      !
+      !
+      CALL eos( tsn, rhd, rhop, gdept_0(:,:,:) ) ! In any case, we need rhop
+      !
+      IF(ln_ctl) THEN                  ! print control
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_tem), clinfo1=' tn      - : ', mask1=tmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_sal), clinfo1=' sn      - : ', mask1=tmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=un               , clinfo1=' un      - : ', mask1=umask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=vn               , clinfo1=' vn      - : ', mask1=vmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=wn               , clinfo1=' wn      - : ', mask1=tmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=avt              , clinfo1=' kz      - : ', mask1=tmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=uslp             , clinfo1=' slp  - u : ', tab3d_2=vslp, clinfo2=' v : ', kdim=jpk)
+         CALL prt_ctl(tab3d_1=wslpi            , clinfo1=' slp  - wi: ', tab3d_2=wslpj, clinfo2=' wj: ', kdim=jpk)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop( 'dta_dyn')
+      !
+   END SUBROUTINE dta_dyn
+
+
+   SUBROUTINE dta_dyn_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dta_dyn_init  ***
+      !!
+      !! ** Purpose :   Initialisation of the dynamical data     
+      !! ** Method  : - read the data namdta_dyn namelist
+      !!----------------------------------------------------------------------
+      INTEGER  :: ierr, ierr0, ierr1, ierr2, ierr3   ! return error code
+      INTEGER  :: ifpr                               ! dummy loop indice
+      INTEGER  :: jfld                               ! dummy loop arguments
+      INTEGER  :: inum, idv, idimv                   ! local integer
+      INTEGER  :: ios                                ! Local integer output status for namelist read
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcoef
+      INTEGER  :: nkrnf_max
+      REAL(wp) :: hrnf_max
+      !!
+      CHARACTER(len=100)            ::  cn_dir        !   Root directory for location of core files
+      TYPE(FLD_N), DIMENSION(jpfld) ::  slf_d         ! array of namelist informations on the fields to read
+      TYPE(FLD_N) :: sn_uwd, sn_vwd, sn_wwd, sn_empb, sn_emp  ! informations about the fields to be read
+      TYPE(FLD_N) :: sn_tem , sn_sal , sn_avt   !   "                 "
+      TYPE(FLD_N) :: sn_mld, sn_qsr, sn_wnd , sn_ice , sn_fmf   !   "               "
+      TYPE(FLD_N) :: sn_ubl, sn_vbl, sn_rnf    !   "              "
+      TYPE(FLD_N) :: sn_div  ! informations about the fields to be read
+      !!
+      NAMELIST/namdta_dyn/cn_dir, ln_dynrnf, ln_dynrnf_depth,  fwbcorr, &
+         &                sn_uwd, sn_vwd, sn_wwd, sn_emp,               &
+         &                sn_avt, sn_tem, sn_sal, sn_mld , sn_qsr ,     &
+         &                sn_wnd, sn_ice, sn_fmf,                       &
+         &                sn_ubl, sn_vbl, sn_rnf,                       &
+         &                sn_empb, sn_div 
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namdta_dyn in reference namelist : Offline: init. of dynamical data
+      READ  ( numnam_ref, namdta_dyn, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdta_dyn in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namdta_dyn in configuration namelist : Offline: init. of dynamical data
+      READ  ( numnam_cfg, namdta_dyn, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdta_dyn in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdta_dyn )
+      !                                         ! store namelist information in an array
+      !                                         ! Control print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dta_dyn : offline dynamics '
+         WRITE(numout,*) '~~~~~~~ '
+         WRITE(numout,*) '   Namelist namdta_dyn'
+         WRITE(numout,*) '      runoffs option enabled (T) or not (F)            ln_dynrnf        = ', ln_dynrnf
+         WRITE(numout,*) '      runoffs is spread in vertical                    ln_dynrnf_depth  = ', ln_dynrnf_depth
+         WRITE(numout,*) '      annual global mean of empmr for ssh correction   fwbcorr          = ', fwbcorr
+         WRITE(numout,*)
+      ENDIF
+      ! 
+      jf_uwd  = 1     ;   jf_vwd  = 2    ;   jf_wwd = 3    ;   jf_emp = 4    ;   jf_avt = 5
+      jf_tem  = 6     ;   jf_sal  = 7    ;   jf_mld = 8    ;   jf_qsr = 9
+      jf_wnd  = 10    ;   jf_ice  = 11   ;   jf_fmf = 12   ;   jfld   = jf_fmf
+      !
+      slf_d(jf_uwd)  = sn_uwd    ;   slf_d(jf_vwd)  = sn_vwd   ;   slf_d(jf_wwd) = sn_wwd
+      slf_d(jf_emp)  = sn_emp    ;   slf_d(jf_avt)  = sn_avt
+      slf_d(jf_tem)  = sn_tem    ;   slf_d(jf_sal)  = sn_sal   ;   slf_d(jf_mld) = sn_mld
+      slf_d(jf_qsr)  = sn_qsr    ;   slf_d(jf_wnd)  = sn_wnd   ;   slf_d(jf_ice) = sn_ice
+      slf_d(jf_fmf)  = sn_fmf
+      !
+      IF( .NOT.ln_linssh ) THEN
+               jf_div  = jfld + 1   ;         jf_empb  = jfld + 2    ;   jfld = jf_empb
+         slf_d(jf_div) = sn_div     ;   slf_d(jf_empb) = sn_empb
+      ENDIF
+      !
+      IF( ln_trabbl ) THEN
+               jf_ubl  = jfld + 1   ;         jf_vbl  = jfld + 2     ;   jfld = jf_vbl
+         slf_d(jf_ubl) = sn_ubl     ;   slf_d(jf_vbl) = sn_vbl
+      ENDIF
+      !
+      IF( ln_dynrnf ) THEN
+               jf_rnf  = jfld + 1   ;     jfld  = jf_rnf
+         slf_d(jf_rnf) = sn_rnf    
+      ELSE
+         rnf(:,:) = 0._wp
+      ENDIF
+
+      ALLOCATE( sf_dyn(jfld), STAT=ierr )         ! set sf structure
+      IF( ierr > 0 )  THEN
+         CALL ctl_stop( 'dta_dyn: unable to allocate sf structure' )   ;   RETURN
+      ENDIF
+      !                                         ! fill sf with slf_i and control print
+      CALL fld_fill( sf_dyn, slf_d, cn_dir, 'dta_dyn_init', 'Data in file', 'namdta_dyn' )
+      !
+      ! Open file for each variable to get his number of dimension
+      DO ifpr = 1, jfld
+         CALL fld_clopn( sf_dyn(ifpr), nyear, nmonth, nday )
+         idv   = iom_varid( sf_dyn(ifpr)%num , slf_d(ifpr)%clvar )        ! id of the variable sdjf%clvar
+         idimv = iom_file ( sf_dyn(ifpr)%num )%ndims(idv)                 ! number of dimension for variable sdjf%clvar
+         IF( sf_dyn(ifpr)%num /= 0 )   CALL iom_close( sf_dyn(ifpr)%num ) ! close file if already open
+         ierr1=0
+         IF( idimv == 3 ) THEN    ! 2D variable
+                                      ALLOCATE( sf_dyn(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
+            IF( slf_d(ifpr)%ln_tint ) ALLOCATE( sf_dyn(ifpr)%fdta(jpi,jpj,1,2)  , STAT=ierr1 )
+         ELSE                     ! 3D variable
+                                      ALLOCATE( sf_dyn(ifpr)%fnow(jpi,jpj,jpk)  , STAT=ierr0 )
+            IF( slf_d(ifpr)%ln_tint ) ALLOCATE( sf_dyn(ifpr)%fdta(jpi,jpj,jpk,2), STAT=ierr1 )
+         ENDIF
+         IF( ierr0 + ierr1 > 0 ) THEN
+            CALL ctl_stop( 'dta_dyn_init : unable to allocate sf_dyn array structure' )   ;   RETURN
+         ENDIF
+      END DO
+      !
+      IF( l_ldfslp .AND. .NOT.lk_c1d ) THEN                  ! slopes 
+         IF( sf_dyn(jf_tem)%ln_tint ) THEN      ! time interpolation
+            ALLOCATE( uslpdta (jpi,jpj,jpk,2), vslpdta (jpi,jpj,jpk,2),    &
+            &         wslpidta(jpi,jpj,jpk,2), wslpjdta(jpi,jpj,jpk,2), STAT=ierr2 )
+            !
+            IF( ierr2 > 0 )  THEN
+               CALL ctl_stop( 'dta_dyn_init : unable to allocate slope arrays' )   ;   RETURN
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( .NOT.ln_linssh ) THEN
+        IF( .NOT. sf_dyn(jf_uwd)%ln_clim .AND. ln_rsttr .AND.    &                     ! Restart: read in restart file
+           iom_varid( numrtr, 'sshn', ldstop = .FALSE. ) > 0 ) THEN
+           IF(lwp) WRITE(numout,*) ' sshn forcing fields read in the restart file for initialisation'
+           CALL iom_get( numrtr, jpdom_autoglo, 'sshn', sshn(:,:)   )
+           CALL iom_get( numrtr, jpdom_autoglo, 'sshb', sshb(:,:)   )
+        ELSE
+           IF(lwp) WRITE(numout,*) ' sshn forcing fields read in the restart file for initialisation'
+           CALL iom_open( 'restart', inum )
+           CALL iom_get( inum, jpdom_autoglo, 'sshn', sshn(:,:)   )
+           CALL iom_get( inum, jpdom_autoglo, 'sshb', sshb(:,:)   )
+           CALL iom_close( inum )                                        ! close file
+        ENDIF
+        !
+        DO jk = 1, jpkm1
+           e3t_n(:,:,jk) = e3t_0(:,:,jk) * ( 1._wp + sshn(:,:) * tmask(:,:,1) / ( ht_0(:,:) + 1.0 - tmask(:,:,1) ) )
+        ENDDO
+        e3t_a(:,:,jpk) = e3t_0(:,:,jpk)
+
+        ! Horizontal scale factor interpolations
+        ! --------------------------------------
+        CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+        CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+
+        ! Vertical scale factor interpolations
+        ! ------------------------------------
+        CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n(:,:,:), 'W' )
+  
+        e3t_b(:,:,:)  = e3t_n(:,:,:)
+        e3u_b(:,:,:)  = e3u_n(:,:,:)
+        e3v_b(:,:,:)  = e3v_n(:,:,:)
+
+        ! t- and w- points depth
+        ! ----------------------
+        gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+        gdepw_n(:,:,1) = 0.0_wp
+
+        DO jk = 2, jpk
+           DO jj = 1,jpj
+              DO ji = 1,jpi
+                !    zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))   ! 0 everywhere
+                !    tmask = wmask, ie everywhere expect at jk = mikt
+                                                                   ! 1 for jk =
+                                                                   ! mikt
+                 zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+                 gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+                 gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                     &                + (1-zcoef) * ( gdept_n(ji,jj,jk-1) + e3w_n(ji,jj,jk))
+              END DO
+           END DO
+        END DO
+
+        gdept_b(:,:,:) = gdept_n(:,:,:)
+        gdepw_b(:,:,:) = gdepw_n(:,:,:)
+        !
+      ENDIF
+      !
+      IF( ln_dynrnf .AND. ln_dynrnf_depth ) THEN       ! read depht over which runoffs are distributed
+         IF(lwp) WRITE(numout,*) 
+         IF(lwp) WRITE(numout,*) ' read in the file depht over which runoffs are distributed'
+         CALL iom_open ( "runoffs", inum )                           ! open file
+         CALL iom_get  ( inum, jpdom_data, 'rodepth', h_rnf )   ! read the river mouth array
+         CALL iom_close( inum )                                        ! close file
+         !
+         nk_rnf(:,:) = 0                               ! set the number of level over which river runoffs are applied
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( h_rnf(ji,jj) > 0._wp ) THEN
+                  jk = 2
+                  DO WHILE ( jk /= mbkt(ji,jj) .AND. gdept_0(ji,jj,jk) < h_rnf(ji,jj) ) ;  jk = jk + 1
+                  END DO
+                  nk_rnf(ji,jj) = jk
+               ELSEIF( h_rnf(ji,jj) == -1._wp   ) THEN   ;  nk_rnf(ji,jj) = 1
+               ELSEIF( h_rnf(ji,jj) == -999._wp ) THEN   ;  nk_rnf(ji,jj) = mbkt(ji,jj)
+               ELSE
+                  CALL ctl_stop( 'sbc_rnf_init: runoff depth not positive, and not -999 or -1, rnf value in file fort.999'  )
+                  WRITE(999,*) 'ji, jj, h_rnf(ji,jj) :', ji, jj, h_rnf(ji,jj)
+               ENDIF
+            END DO
+         END DO
+         DO jj = 1, jpj                                ! set the associated depth
+            DO ji = 1, jpi
+               h_rnf(ji,jj) = 0._wp
+               DO jk = 1, nk_rnf(ji,jj)
+                  h_rnf(ji,jj) = h_rnf(ji,jj) + e3t_n(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE                                       ! runoffs applied at the surface
+         nk_rnf(:,:) = 1
+         h_rnf (:,:) = e3t_n(:,:,1)
+      ENDIF
+      nkrnf_max = MAXVAL( nk_rnf(:,:) )
+      hrnf_max = MAXVAL( h_rnf(:,:) )
+      IF( lk_mpp )  THEN
+         CALL mpp_max( 'dtadyn', nkrnf_max )                 ! max over the  global domain
+         CALL mpp_max( 'dtadyn', hrnf_max )                 ! max over the  global domain
+      ENDIF
+      IF(lwp) WRITE(numout,*) ' '
+      IF(lwp) WRITE(numout,*) ' max depht of runoff : ', hrnf_max,'    max level  : ', nkrnf_max
+      IF(lwp) WRITE(numout,*) ' '
+      !
+      CALL dta_dyn( nit000 )
+      !
+   END SUBROUTINE dta_dyn_init
+
+   SUBROUTINE dta_dyn_sed( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dta_dyn  ***
+      !!
+      !! ** Purpose :  Prepares dynamics and physics fields from a NEMO run
+      !!               for an off-line simulation of passive tracers
+      !!
+      !! ** Method : calculates the position of data
+      !!             - computes slopes if needed
+      !!             - interpolates data if needed
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'dta_dyn_sed')
+      !
+      nsecdyn = nsec_year + nsec1jan000   ! number of seconds between Jan. 1st 00h of nit000 year and the middle of time step
+      !
+      IF( kt == nit000 ) THEN    ;    nprevrec = 0
+      ELSE                       ;    nprevrec = sf_dyn(jf_tem)%nrec_a(2)
+      ENDIF
+      CALL fld_read( kt, 1, sf_dyn )      !=  read data at kt time step   ==!
+      !
+      tsn(:,:,:,jp_tem) = sf_dyn(jf_tem)%fnow(:,:,:)  * tmask(:,:,:)    ! temperature
+      tsn(:,:,:,jp_sal) = sf_dyn(jf_sal)%fnow(:,:,:)  * tmask(:,:,:)    ! salinity
+      !
+      CALL eos    ( tsn, rhd, rhop, gdept_0(:,:,:) ) ! In any case, we need rhop
+
+      IF(ln_ctl) THEN                  ! print control
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_tem), clinfo1=' tn      - : ', mask1=tmask,  kdim=jpk   )
+         CALL prt_ctl(tab3d_1=tsn(:,:,:,jp_sal), clinfo1=' sn      - : ', mask1=tmask,  kdim=jpk   )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop( 'dta_dyn_sed')
+      !
+   END SUBROUTINE dta_dyn_sed
+
+
+   SUBROUTINE dta_dyn_sed_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dta_dyn_init  ***
+      !!
+      !! ** Purpose :   Initialisation of the dynamical data
+      !! ** Method  : - read the data namdta_dyn namelist
+      !!----------------------------------------------------------------------
+      INTEGER  :: ierr, ierr0, ierr1, ierr2, ierr3   ! return error code
+      INTEGER  :: ifpr                               ! dummy loop indice
+      INTEGER  :: jfld                               ! dummy loop arguments
+      INTEGER  :: inum, idv, idimv                   ! local integer
+      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(2) ::  slf_d         ! array of namelist informations on the fields to read
+      TYPE(FLD_N) :: sn_tem , sn_sal   !   "                 "
+      !!
+      NAMELIST/namdta_dyn/cn_dir, ln_dynrnf, ln_dynrnf_depth,  fwbcorr, &
+         &                sn_tem, sn_sal
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namdta_dyn in reference namelist : Offline: init. of dynamical data
+      READ  ( numnam_ref, namdta_dyn, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namdta_dyn in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namdta_dyn in configuration namelist : Offline: init. of dynamical data
+      READ  ( numnam_cfg, namdta_dyn, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namdta_dyn in configuration namelist' )
+      IF(lwm) WRITE ( numond, namdta_dyn )
+      !                                         ! store namelist information in an array
+      !                                         ! Control print
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dta_dyn : offline dynamics '
+         WRITE(numout,*) '~~~~~~~ '
+         WRITE(numout,*) '   Namelist namdta_dyn'
+         WRITE(numout,*) '      runoffs option enabled (T) or not (F)            ln_dynrnf        = ', ln_dynrnf
+         WRITE(numout,*) '      runoffs is spread in vertical                    ln_dynrnf_depth  = ', ln_dynrnf_depth
+         WRITE(numout,*) '      annual global mean of empmr for ssh correction   fwbcorr          = ', fwbcorr
+         WRITE(numout,*)
+      ENDIF
+      !
+      jf_tem  = 1     ;   jf_sal  = 2    ;   jfld   = jf_sal
+      !
+      slf_d(jf_tem)  = sn_tem    ;   slf_d(jf_sal)  = sn_sal
+      !
+      ALLOCATE( sf_dyn(jfld), STAT=ierr )         ! set sf structure
+      IF( ierr > 0 )  THEN
+         CALL ctl_stop( 'dta_dyn: unable to allocate sf structure' )   ;   RETURN
+      ENDIF
+      !                                         ! fill sf with slf_i and control print
+      CALL fld_fill( sf_dyn, slf_d, cn_dir, 'dta_dyn_init', 'Data in file', 'namdta_dyn' )
+      !
+      ! Open file for each variable to get his number of dimension
+      DO ifpr = 1, jfld
+         CALL fld_clopn( sf_dyn(ifpr), nyear, nmonth, nday )
+         idv   = iom_varid( sf_dyn(ifpr)%num , slf_d(ifpr)%clvar )        ! id of the variable sdjf%clvar
+         idimv = iom_file ( sf_dyn(ifpr)%num )%ndims(idv)                 ! number of dimension for variable sdjf%clvar
+         IF( sf_dyn(ifpr)%num /= 0 )   CALL iom_close( sf_dyn(ifpr)%num ) ! close file if already open
+         ierr1=0
+         IF( idimv == 3 ) THEN    ! 2D variable
+                                      ALLOCATE( sf_dyn(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
+            IF( slf_d(ifpr)%ln_tint ) ALLOCATE( sf_dyn(ifpr)%fdta(jpi,jpj,1,2)  , STAT=ierr1 )
+         ELSE                     ! 3D variable
+                                      ALLOCATE( sf_dyn(ifpr)%fnow(jpi,jpj,jpk)  , STAT=ierr0 )
+            IF( slf_d(ifpr)%ln_tint ) ALLOCATE( sf_dyn(ifpr)%fdta(jpi,jpj,jpk,2), STAT=ierr1 )
+         ENDIF
+         IF( ierr0 + ierr1 > 0 ) THEN
+            CALL ctl_stop( 'dta_dyn_init : unable to allocate sf_dyn array structure' )   ;   RETURN
+         ENDIF
+      END DO
+      !
+      CALL dta_dyn_sed( nit000 )
+      !
+   END SUBROUTINE dta_dyn_sed_init
+
+   SUBROUTINE dta_dyn_swp( kt )
+     !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE dta_dyn_swp  ***
+      !!
+      !! ** Purpose :   Swap and the data and compute the vertical scale factor 
+      !!              at U/V/W pointand the depht
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt       ! time step
+      !
+      INTEGER             :: ji, jj, jk
+      REAL(wp)            :: zcoef
+      !!---------------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'ssh_swp : Asselin time filter and swap of sea surface height'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+
+      sshb(:,:) = sshn(:,:) + atfp * ( sshb(:,:) - 2 * sshn(:,:) + ssha(:,:))  ! before <-- now filtered
+      sshn(:,:) = ssha(:,:)
+
+      e3t_n(:,:,:) = e3t_a(:,:,:)
+
+      ! Reconstruction of all vertical scale factors at now and before time steps
+      ! =============================================================================
+
+      ! Horizontal scale factor interpolations
+      ! --------------------------------------
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+
+      ! Vertical scale factor interpolations
+      ! ------------------------------------
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W' )
+
+      e3t_b(:,:,:)  = e3t_n(:,:,:)
+      e3u_b(:,:,:)  = e3u_n(:,:,:)
+      e3v_b(:,:,:)  = e3v_n(:,:,:)
+
+      ! t- and w- points depth
+      ! ----------------------
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+      gdepw_n(:,:,1) = 0.0_wp
+      !
+      DO jk = 2, jpk
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_n(ji,jj,jk-1) + e3w_n(ji,jj,jk))
+            END DO
+         END DO
+      END DO
+      !
+      gdept_b(:,:,:) = gdept_n(:,:,:)
+      gdepw_b(:,:,:) = gdepw_n(:,:,:)
+      !
+   END SUBROUTINE dta_dyn_swp
+   
+
+   SUBROUTINE dta_dyn_ssh( kt, phdivtr, psshb,  pemp, pssha, pe3ta )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dta_dyn_wzv  ***
+      !!                   
+      !! ** Purpose :   compute the after ssh (ssha) and the now vertical velocity
+      !!
+      !! ** Method  : Using the incompressibility hypothesis, 
+      !!        - the ssh increment is computed by integrating the horizontal divergence 
+      !!          and multiply by the time step.
+      !!
+      !!        - compute the after scale factor : repartition of ssh INCREMENT proportionnaly
+      !!                                           to the level thickness ( z-star case )
+      !!
+      !!        - the vertical velocity is computed by integrating the horizontal divergence  
+      !!          from the bottom to the surface minus the scale factor evolution.
+      !!          The boundary conditions are w=0 at the bottom (no flux)
+      !!
+      !! ** action  :   ssha / e3t_a / wn
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER,                                   INTENT(in )    :: kt        !  time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk)          , INTENT(in )   :: phdivtr   ! horizontal divergence transport
+      REAL(wp), DIMENSION(jpi,jpj)    , OPTIONAL, INTENT(in )   :: psshb     ! now ssh
+      REAL(wp), DIMENSION(jpi,jpj)    , OPTIONAL, INTENT(in )   :: pemp      ! evaporation minus precipitation
+      REAL(wp), DIMENSION(jpi,jpj)    , OPTIONAL, INTENT(inout) :: pssha     ! after ssh
+      REAL(wp), DIMENSION(jpi,jpj,jpk), OPTIONAL, INTENT(out)   :: pe3ta     ! after vertical scale factor
+      !
+      INTEGER                       :: jk
+      REAL(wp), DIMENSION(jpi,jpj)  :: zhdiv  
+      REAL(wp)  :: z2dt  
+      !!----------------------------------------------------------------------
+      !
+      z2dt = 2._wp * rdt
+      !
+      zhdiv(:,:) = 0._wp
+      DO jk = 1, jpkm1
+         zhdiv(:,:) = zhdiv(:,:) +  phdivtr(:,:,jk) * tmask(:,:,jk)
+      END DO
+      !                                                ! Sea surface  elevation time-stepping
+      pssha(:,:) = ( psshb(:,:) - z2dt * ( r1_rau0 * pemp(:,:)  + zhdiv(:,:) ) ) * ssmask(:,:)
+      !                                                 ! 
+      !                                                 ! After acale factors at t-points ( z_star coordinate )
+      DO jk = 1, jpkm1
+        pe3ta(:,:,jk) = e3t_0(:,:,jk) * ( 1._wp + pssha(:,:) * tmask(:,:,1) / ( ht_0(:,:) + 1.0 - tmask(:,:,1) ) )
+      END DO
+      !
+   END SUBROUTINE dta_dyn_ssh
+
+
+   SUBROUTINE dta_dyn_hrnf
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_rnf  ***
+      !!
+      !! ** Purpose :   update the horizontal divergence with the runoff inflow
+      !!
+      !! ** Method  :
+      !!                CAUTION : rnf is positive (inflow) decreasing the
+      !!                          divergence and expressed in m/s
+      !!
+      !! ** Action  :   phdivn   decreased by the runoff inflow
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      DO jj = 1, jpj                   ! update the depth over which runoffs are distributed
+         DO ji = 1, jpi
+            h_rnf(ji,jj) = 0._wp
+            DO jk = 1, nk_rnf(ji,jj)                           ! recalculates h_rnf to be the depth in metres
+                h_rnf(ji,jj) = h_rnf(ji,jj) + e3t_n(ji,jj,jk)   ! to the bottom of the relevant grid box
+            END DO
+        END DO
+      END DO
+      !
+   END SUBROUTINE dta_dyn_hrnf
+
+
+
+   SUBROUTINE dta_dyn_slp( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE dta_dyn_slp  ***
+      !!
+      !! ** Purpose : Computation of slope
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER,  INTENT(in) :: kt       ! time step
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) ::   ztinta     ! ratio applied to after  records when doing time interpolation
+      REAL(wp) ::   ztintb     ! ratio applied to before records when doing time interpolation
+      INTEGER  ::   iswap 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)      ::   zuslp, zvslp, zwslpi, zwslpj
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts) ::   zts
+      !!---------------------------------------------------------------------
+      !
+      IF( sf_dyn(jf_tem)%ln_tint ) THEN    ! Computes slopes (here avt is used as workspace)                       
+         IF( kt == nit000 ) THEN
+            IF(lwp) WRITE(numout,*) ' Compute new slopes at kt = ', kt
+            zts(:,:,:,jp_tem) = sf_dyn(jf_tem)%fdta(:,:,:,1) * tmask(:,:,:)   ! temperature
+            zts(:,:,:,jp_sal) = sf_dyn(jf_sal)%fdta(:,:,:,1) * tmask(:,:,:)   ! salinity 
+            avt(:,:,:)        = sf_dyn(jf_avt)%fdta(:,:,:,1) * tmask(:,:,:)   ! vertical diffusive coef.
+            CALL compute_slopes( kt, zts, zuslp, zvslp, zwslpi, zwslpj )
+            uslpdta (:,:,:,1) = zuslp (:,:,:) 
+            vslpdta (:,:,:,1) = zvslp (:,:,:) 
+            wslpidta(:,:,:,1) = zwslpi(:,:,:) 
+            wslpjdta(:,:,:,1) = zwslpj(:,:,:) 
+            !
+            zts(:,:,:,jp_tem) = sf_dyn(jf_tem)%fdta(:,:,:,2) * tmask(:,:,:)   ! temperature
+            zts(:,:,:,jp_sal) = sf_dyn(jf_sal)%fdta(:,:,:,2) * tmask(:,:,:)   ! salinity 
+            avt(:,:,:)        = sf_dyn(jf_avt)%fdta(:,:,:,2) * tmask(:,:,:)   ! vertical diffusive coef.
+            CALL compute_slopes( kt, zts, zuslp, zvslp, zwslpi, zwslpj )
+            uslpdta (:,:,:,2) = zuslp (:,:,:) 
+            vslpdta (:,:,:,2) = zvslp (:,:,:) 
+            wslpidta(:,:,:,2) = zwslpi(:,:,:) 
+            wslpjdta(:,:,:,2) = zwslpj(:,:,:) 
+         ELSE
+           ! 
+           iswap = 0
+           IF( sf_dyn(jf_tem)%nrec_a(2) - nprevrec /= 0 )  iswap = 1
+           IF( nsecdyn > sf_dyn(jf_tem)%nrec_b(2) .AND. iswap == 1 )  THEN    ! read/update the after data
+              IF(lwp) WRITE(numout,*) ' Compute new slopes at kt = ', kt
+              uslpdta (:,:,:,1) =  uslpdta (:,:,:,2)         ! swap the data
+              vslpdta (:,:,:,1) =  vslpdta (:,:,:,2)  
+              wslpidta(:,:,:,1) =  wslpidta(:,:,:,2) 
+              wslpjdta(:,:,:,1) =  wslpjdta(:,:,:,2) 
+              !
+              zts(:,:,:,jp_tem) = sf_dyn(jf_tem)%fdta(:,:,:,2) * tmask(:,:,:)   ! temperature
+              zts(:,:,:,jp_sal) = sf_dyn(jf_sal)%fdta(:,:,:,2) * tmask(:,:,:)   ! salinity 
+              avt(:,:,:)        = sf_dyn(jf_avt)%fdta(:,:,:,2) * tmask(:,:,:)   ! vertical diffusive coef.
+              CALL compute_slopes( kt, zts, zuslp, zvslp, zwslpi, zwslpj )
+              !
+              uslpdta (:,:,:,2) = zuslp (:,:,:) 
+              vslpdta (:,:,:,2) = zvslp (:,:,:) 
+              wslpidta(:,:,:,2) = zwslpi(:,:,:) 
+              wslpjdta(:,:,:,2) = zwslpj(:,:,:) 
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( sf_dyn(jf_tem)%ln_tint )  THEN
+         ztinta =  REAL( nsecdyn - sf_dyn(jf_tem)%nrec_b(2), wp )  &
+            &    / REAL( sf_dyn(jf_tem)%nrec_a(2) - sf_dyn(jf_tem)%nrec_b(2), wp )
+         ztintb =  1. - ztinta
+         IF( l_ldfslp .AND. .NOT.lk_c1d ) THEN    ! Computes slopes (here avt is used as workspace)
+            uslp (:,:,:) = ztintb * uslpdta (:,:,:,1)  + ztinta * uslpdta (:,:,:,2)  
+            vslp (:,:,:) = ztintb * vslpdta (:,:,:,1)  + ztinta * vslpdta (:,:,:,2)  
+            wslpi(:,:,:) = ztintb * wslpidta(:,:,:,1)  + ztinta * wslpidta(:,:,:,2)  
+            wslpj(:,:,:) = ztintb * wslpjdta(:,:,:,1)  + ztinta * wslpjdta(:,:,:,2)  
+         ENDIF
+      ELSE
+         zts(:,:,:,jp_tem) = sf_dyn(jf_tem)%fnow(:,:,:) * tmask(:,:,:)   ! temperature
+         zts(:,:,:,jp_sal) = sf_dyn(jf_sal)%fnow(:,:,:) * tmask(:,:,:)   ! salinity 
+         avt(:,:,:)        = sf_dyn(jf_avt)%fnow(:,:,:) * tmask(:,:,:)   ! vertical diffusive coef.
+         CALL compute_slopes( kt, zts, zuslp, zvslp, zwslpi, zwslpj )
+         !
+         IF( l_ldfslp .AND. .NOT.lk_c1d ) THEN    ! Computes slopes (here avt is used as workspace)
+            uslp (:,:,:) = zuslp (:,:,:)
+            vslp (:,:,:) = zvslp (:,:,:)
+            wslpi(:,:,:) = zwslpi(:,:,:)
+            wslpj(:,:,:) = zwslpj(:,:,:)
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE dta_dyn_slp
+
+
+   SUBROUTINE compute_slopes( kt, pts, puslp, pvslp, pwslpi, pwslpj )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE dta_dyn_slp  ***
+      !!
+      !! ** Purpose :   Computation of slope
+      !!---------------------------------------------------------------------
+      INTEGER ,                              INTENT(in ) :: kt       ! time step
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in ) :: pts      ! temperature/salinity
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: puslp    ! zonal isopycnal slopes
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: pvslp    ! meridional isopycnal slopes
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: pwslpi   ! zonal diapycnal slopes
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(out) :: pwslpj   ! meridional diapycnal slopes
+      !!---------------------------------------------------------------------
+      !
+      IF( l_ldfslp .AND. .NOT.lk_c1d ) THEN    ! Computes slopes (here avt is used as workspace)
+         CALL eos    ( pts, rhd, rhop, gdept_0(:,:,:) )
+         CALL eos_rab( pts, rab_n )       ! now local thermal/haline expension ratio at T-points
+         CALL bn2    ( pts, rab_n, rn2  ) ! now    Brunt-Vaisala
+
+      ! Partial steps: before Horizontal DErivative
+      IF( ln_zps  .AND. .NOT. ln_isfcav)                            &
+         &            CALL zps_hde    ( kt, jpts, pts, gtsu, gtsv,  &  ! Partial steps: before horizontal gradient
+         &                                        rhd, gru , grv    )  ! of t, s, rd at the last ocean level
+      IF( ln_zps .AND.        ln_isfcav)                            &
+         &            CALL zps_hde_isf( kt, jpts, pts, gtsu, gtsv, gtui, gtvi, &  ! Partial steps for top cell (ISF)
+         &                                        rhd, gru , grv , grui, grvi )  ! of t, s, rd at the first ocean level
+
+         rn2b(:,:,:) = rn2(:,:,:)         ! need for zdfmxl
+         CALL zdf_mxl( kt )            ! mixed layer depth
+         CALL ldf_slp( kt, rhd, rn2 )  ! slopes
+         puslp (:,:,:) = uslp (:,:,:)
+         pvslp (:,:,:) = vslp (:,:,:)
+         pwslpi(:,:,:) = wslpi(:,:,:)
+         pwslpj(:,:,:) = wslpj(:,:,:)
+     ELSE
+         puslp (:,:,:) = 0.            ! to avoid warning when compiling
+         pvslp (:,:,:) = 0.
+         pwslpi(:,:,:) = 0.
+         pwslpj(:,:,:) = 0.
+     ENDIF
+      !
+   END SUBROUTINE compute_slopes
+
+   !!======================================================================
+END MODULE dtadyn
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/nemogcm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/nemogcm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/OFF/nemogcm.F90	(revision 14097)
@@ -0,0 +1,575 @@
+MODULE nemogcm
+   !!======================================================================
+   !!                       ***  MODULE nemogcm   ***
+   !! Off-line Ocean   : passive tracer evolution, dynamics read in files
+   !!======================================================================
+   !! History :  3.3  ! 2010-05  (C. Ethe)  Full reorganization of the off-line: phasing with the on-line
+   !!            3.4  ! 2011-01  (C. Ethe, A. R. Porter, STFC Daresbury) dynamical allocation
+   !!            4.0  ! 2016-10  (C. Ethe, G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   nemo_gcm      : off-line: solve ocean tracer only
+   !!   nemo_gcm      : solve ocean dynamics, tracer, biogeochemistry and/or sea-ice
+   !!   nemo_init     : initialization of the NEMO system
+   !!   nemo_ctl      : initialisation of the contol print
+   !!   nemo_closefile: close remaining open files
+   !!   nemo_alloc    : dynamical allocation
+   !!   istate_init   : simple initialization to zero of ocean fields
+   !!   stp_ctl       : reduced step control (no dynamics in off-line)
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space domain variables
+   USE oce            ! dynamics and tracers variables
+   USE trc_oce        ! Shared ocean/passive tracers variables
+   USE c1d            ! 1D configuration
+   USE domain         ! domain initialization from coordinate & bathymetry (dom_init routine)
+   USE closea         ! treatment of closed seas (for ln_closea)
+   USE usrdef_nam     ! user defined configuration
+   USE eosbn2         ! equation of state            (eos bn2 routine)
+   !                  ! ocean physics
+   USE bdy_oce,  ONLY : ln_bdy
+   USE bdyini         ! open boundary cond. setting       (bdy_init routine)
+   USE ldftra         ! lateral diffusivity setting    (ldf_tra_init routine)
+   USE ldfslp         ! slopes of neutral surfaces     (ldf_slp_init routine)
+   USE traqsr         ! solar radiation penetration    (tra_qsr_init routine)
+   USE trabbl         ! bottom boundary layer          (tra_bbl_init routine)
+   USE traldf         ! lateral physics                (tra_ldf_init routine)
+   USE sbcmod         ! surface boundary condition     (sbc_init     routine)
+   USE phycst         ! physical constant                   (par_cst routine)
+   USE dtadyn         ! Lecture and Interpolation of the dynamical fields
+   USE trcini         ! Initilization of the passive tracers
+   USE daymod         ! calendar                            (day     routine)
+   USE trcstp         ! passive tracer time-stepping        (trc_stp routine)
+   USE dtadyn         ! Lecture and interpolation of the dynamical fields
+   !              ! Passive tracers needs
+   USE trc            ! passive tracer : variables
+   USE trcnam         ! passive tracer : namelist
+   USE trcrst         ! passive tracer restart
+   USE diaptr         ! Need to initialise this as some variables are used in if statements later
+   USE sbc_oce , ONLY : ln_rnf
+   USE sbcrnf         ! surface boundary condition : runoffs
+   !              ! I/O & MPP
+   USE iom            ! I/O library
+   USE in_out_manager ! I/O manager
+   USE mppini         ! shared/distributed memory setting (mpp_init routine)
+   USE lib_mpp        ! distributed memory computing
+#if defined key_iomput
+   USE xios           ! xIOserver
+#endif 
+   USE prtctl         ! Print control                    (prt_ctl_init routine)
+   USE timing         ! Timing
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+   USE lbcnfd  , ONLY : isendto, nsndto, nfsloop, nfeloop   ! Setup of north fold exchanges
+
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   nemo_gcm   ! called by nemo.F90
+
+   CHARACTER (len=64) ::   cform_aaa="( /, 'AAAAAAAA', / ) "   ! flag for output listing
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OFF 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE nemo_gcm
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_gcm  ***
+      !!
+      !! ** Purpose :   NEMO solves the primitive equations on an orthogonal
+      !!              curvilinear mesh on the sphere.
+      !!
+      !! ** Method  : - model general initialization
+      !!              - launch the time-stepping (dta_dyn and trc_stp)
+      !!              - finalize the run by closing files and communications
+      !!
+      !! References : Madec, Delecluse,Imbard, and Levy, 1997:  internal report, IPSL.
+      !!              Madec, 2008, internal report, IPSL.
+      !!----------------------------------------------------------------------
+      INTEGER :: istp, indic       ! time step index
+      !!----------------------------------------------------------------------
+
+      CALL nemo_init  ! Initializations
+
+      ! 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!
+      CALL mpp_max( 'nemogcm', nstop )
+
+      !                            !-----------------------!
+      !                            !==   time stepping   ==!
+      !                            !-----------------------!
+      istp = nit000
+      !
+      IF( ln_rnf )   CALL sbc_rnf(istp)   ! runoffs initialization 
+      ! 
+      CALL iom_init( cxios_context )      ! iom_put initialization (must be done after nemo_init for AGRIF+XIOS+OASIS)
+      ! 
+      DO WHILE ( istp <= nitend .AND. nstop == 0 )    !==  OFF time-stepping  ==!
+         !
+         IF( istp /= nit000 )   CALL day        ( istp )         ! Calendar (day was already called at nit000 in day_init)
+                                CALL iom_setkt  ( istp - nit000 + 1, cxios_context )   ! say to iom that we are at time step kstp
+#if defined key_sed_off
+                                CALL dta_dyn_sed( istp )         ! Interpolation of the dynamical fields
+#else
+                                CALL dta_dyn    ( istp )         ! Interpolation of the dynamical fields
+#endif
+                                CALL trc_stp    ( istp )         ! time-stepping
+#if ! defined key_sed_off
+         IF( .NOT.ln_linssh )   CALL dta_dyn_swp( istp )         ! swap of sea  surface height and vertical scale factors
+#endif
+                                CALL stp_ctl    ( istp, indic )  ! Time loop: control and print
+         istp = istp + 1
+      END DO
+      !
+#if defined key_iomput
+      CALL iom_context_finalize( cxios_context ) ! needed for XIOS+AGRIF
+#endif
+
+      !                            !------------------------!
+      !                            !==  finalize the run  ==!
+      !                            !------------------------!
+      IF(lwp) WRITE(numout,cform_aaa)                 ! Flag AAAAAAA
+
+      IF( nstop /= 0 .AND. lwp ) THEN                 ! error print
+         WRITE(ctmp1,*) '   ==>>>   nemo_gcm: a total of ', nstop, ' errors have been found'
+         WRITE(ctmp2,*) '           Look for "E R R O R" messages in all existing ocean_output* files'
+         CALL ctl_stop( ' ', ctmp1, ' ', ctmp2 )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_finalize
+      !
+      CALL nemo_closefile
+      !
+#if defined key_iomput
+                     CALL xios_finalize   ! end mpp communications with xios
+#else
+      IF( lk_mpp )   CALL mppstop         ! end mpp communications
+#endif
+      !
+      IF(lwm) THEN
+         IF( nstop == 0 ) THEN   ;   STOP 0
+         ELSE                    ;   STOP 123
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE nemo_gcm
+
+
+   SUBROUTINE nemo_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_init  ***
+      !!
+      !! ** Purpose :   initialization of the nemo model in off-line mode
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, ilocal_comm   ! local integers
+      !!
+      NAMELIST/namctl/ ln_ctl   , sn_cfctl, nn_print, nn_ictls, nn_ictle,   &
+         &             nn_isplt , nn_jsplt, nn_jctls, nn_jctle,             &
+         &             ln_timing, ln_diacfl
+      NAMELIST/namcfg/ ln_read_cfg, cn_domcfg, ln_closea, ln_write_cfg, cn_domcfg_out, ln_use_jattr
+      !!----------------------------------------------------------------------
+      !
+      cxios_context = 'nemo'
+      !
+      !                             !-------------------------------------------------!
+      !                             !     set communicator & select the local rank    !
+      !                             !  must be done as soon as possible to get narea  !
+      !                             !-------------------------------------------------!
+      !
+#if defined key_iomput
+      CALL xios_initialize( "for_xios_mpi_id", return_comm=ilocal_comm )   ! nemo local communicator given by xios
+      CALL mpp_start( ilocal_comm )
+#else
+      CALL mpp_start( )
+#endif
+      !
+      narea = mpprank + 1               ! mpprank: the rank of proc (0 --> mppsize -1 )
+      lwm = (narea == 1)                ! control of output namelists
+      !
+      !                             !---------------------------------------------------------------!
+      !                             ! Open output files, reference and configuration namelist files !
+      !                             !---------------------------------------------------------------!
+      !
+      ! open ocean.output as soon as possible to get all output prints (including errors messages)
+      IF( lwm )   CALL ctl_opn(     numout,        'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open reference and configuration namelist files
+                  CALL ctl_opn( numnam_ref,        'namelist_ref',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+                  CALL ctl_opn( numnam_cfg,        'namelist_cfg',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      IF( lwm )   CALL ctl_opn(     numond, 'output.namelist.dyn', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open /dev/null file to be able to supress output write easily
+      IF( Agrif_Root() ) THEN
+                  CALL ctl_opn(     numnul,           '/dev/null', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+#ifdef key_agrif
+      ELSE
+                  numnul = Agrif_Parent(numnul)
+#endif
+      ENDIF
+      !
+      !                             !--------------------!
+      !                             ! Open listing units !  -> need ln_ctl from namctl to define lwp
+      !                             !--------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namctl in reference namelist
+      READ  ( numnam_ref, namctl, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namctl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namctl in confguration namelist
+      READ  ( numnam_cfg, namctl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namctl in configuration namelist' )
+      !
+      lwp = (narea == 1) .OR. ln_ctl    ! control of all listing output print
+      !
+      IF(lwp) THEN                            ! open listing units
+         !
+         IF( .NOT. lwm )   &           ! alreay opened for narea == 1
+            &     CALL ctl_opn(     numout,        'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE., narea )
+         !
+         WRITE(numout,*)
+         WRITE(numout,*) '   CNRS - NERC - Met OFFICE - MERCATOR-ocean - CMCC'
+         WRITE(numout,*) '                       NEMO team'
+         WRITE(numout,*) '                   Off-line TOP Model'
+         WRITE(numout,*) '                NEMO version 4.0  (2019) '
+         WRITE(numout,*)
+         WRITE(numout,*) "           ._      ._      ._      ._      ._    "
+         WRITE(numout,*) "       _.-._)`\_.-._)`\_.-._)`\_.-._)`\_.-._)`\_ "
+         WRITE(numout,*)
+         WRITE(numout,*) "           o         _,           _,             "
+         WRITE(numout,*) "            o      .' (        .-' /             "
+         WRITE(numout,*) "           o     _/..._'.    .'   /              "
+         WRITE(numout,*) "      (    o .-'`      ` '-./  _.'               "
+         WRITE(numout,*) "       )    ( o)           ;= <_         (       "
+         WRITE(numout,*) "      (      '-.,\\__ __.-;`\   '.        )      "
+         WRITE(numout,*) "       )  )       \) |`\ \)  '.   \      (   (   "
+         WRITE(numout,*) "      (  (           \_/       '-._\      )   )  "
+         WRITE(numout,*) "       )  )                        `     (   (   "
+         WRITE(numout,*) "     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
+         WRITE(numout,*)
+         !
+         WRITE(numout,cform_aaa)                                        ! Flag AAAAAAA
+         !
+      ENDIF
+      !
+      ! finalize the definition of namctl variables
+      IF( sn_cfctl%l_config ) THEN
+         ! Activate finer control of report outputs
+         ! optionally switch off output from selected areas (note this only
+         ! applies to output which does not involve global communications)
+         IF( ( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax  ) .OR. &
+           & ( MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 ) )    &
+           &   CALL nemo_set_cfctl( sn_cfctl, .FALSE., .FALSE. )
+      ELSE
+         ! Use ln_ctl to turn on or off all options.
+         CALL nemo_set_cfctl( sn_cfctl, ln_ctl, .TRUE. )
+      ENDIF
+      !
+      IF(lwm) WRITE( numond, namctl )
+      !
+      !                             !------------------------------------!
+      !                             !  Set global domain size parameters !
+      !                             !------------------------------------!
+      !     
+      REWIND( numnam_ref )              ! Namelist namcfg in reference namelist
+      READ  ( numnam_ref, namcfg, IOSTAT = ios, ERR = 903 )
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcfg in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namcfg in confguration namelist
+      READ  ( numnam_cfg, namcfg, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcfg in configuration namelist' )   
+      !
+      IF( ln_read_cfg ) THEN              ! Read sizes in domain configuration file
+         CALL domain_cfg ( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ELSE                                ! user-defined namelist
+         CALL usr_def_nam( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ENDIF
+      !
+      IF(lwm)   WRITE( numond, namcfg )
+      l_offline = .true.                  ! passive tracers are run offline
+      !
+      !                             !-----------------------------------------!
+      !                             ! mpp parameters and domain decomposition !
+      !                             !-----------------------------------------!
+      !
+      CALL mpp_init
+
+      ! Now we know the dimensions of the grid and numout has been set: we can allocate arrays
+      CALL nemo_alloc()
+
+      !                             !-------------------------------!
+      !                             !  NEMO general initialization  !
+      !                             !-------------------------------!
+
+      CALL nemo_ctl                          ! Control prints
+      !
+      !                                      ! General initialization
+      IF( ln_timing    )   CALL timing_init
+      IF( ln_timing    )   CALL timing_start( 'nemo_init')
+      !
+                           CALL     phy_cst         ! Physical constants
+                           CALL     eos_init        ! Equation of state
+      IF( lk_c1d       )   CALL     c1d_init        ! 1D column configuration
+                           CALL     dom_init("OPA") ! Domain
+      IF( ln_ctl       )   CALL prt_ctl_init        ! Print control
+
+                           CALL  istate_init    ! ocean initial state (Dynamics and tracers)
+
+                           CALL     sbc_init    ! Forcings : surface module
+                           CALL     bdy_init    ! Open boundaries initialisation                          
+
+      !                                      ! Tracer physics
+                           CALL ldf_tra_init    ! Lateral ocean tracer physics
+                           CALL ldf_eiv_init    ! Eddy induced velocity param
+                           CALL tra_ldf_init    ! lateral mixing
+      IF( l_ldfslp     )   CALL ldf_slp_init    ! slope of lateral mixing
+      IF( ln_traqsr    )   CALL tra_qsr_init    ! penetrative solar radiation
+      IF( ln_trabbl    )   CALL tra_bbl_init    ! advective (and/or diffusive) bottom boundary layer scheme
+
+      !                                      ! Passive tracers
+                           CALL trc_nam_run    ! Needed to get restart parameters for passive tracers
+                           CALL trc_rst_cal( nit000, 'READ' )   ! calendar
+#if defined key_sed_off
+                           CALL dta_dyn_sed_init ! Initialization for the dynamics
+#else
+                           CALL dta_dyn_init   ! Initialization for the dynamics
+#endif
+
+                           CALL     trc_init   ! Passive tracers initialization
+                           CALL dia_ptr_init   ! Poleward TRansports initialization
+                           
+      IF(lwp) WRITE(numout,cform_aaa)           ! Flag AAAAAAA
+      !
+      IF( ln_timing    )   CALL timing_stop( 'nemo_init')
+      !
+   END SUBROUTINE nemo_init
+
+
+   SUBROUTINE nemo_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_ctl  ***
+      !!
+      !! ** Purpose :   control print setting
+      !!
+      !! ** Method  : - print namctl information and check some consistencies
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'nemo_ctl: Control prints'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist namctl'
+         WRITE(numout,*) '      run control (for debugging)     ln_ctl     = ', ln_ctl
+         WRITE(numout,*) '       finer control over o/p sn_cfctl%l_config  = ', sn_cfctl%l_config
+         WRITE(numout,*) '                              sn_cfctl%l_runstat = ', sn_cfctl%l_runstat
+         WRITE(numout,*) '                              sn_cfctl%l_trcstat = ', sn_cfctl%l_trcstat
+         WRITE(numout,*) '                              sn_cfctl%l_oceout  = ', sn_cfctl%l_oceout
+         WRITE(numout,*) '                              sn_cfctl%l_layout  = ', sn_cfctl%l_layout
+         WRITE(numout,*) '                              sn_cfctl%l_mppout  = ', sn_cfctl%l_mppout
+         WRITE(numout,*) '                              sn_cfctl%l_mpptop  = ', sn_cfctl%l_mpptop
+         WRITE(numout,*) '                              sn_cfctl%procmin   = ', sn_cfctl%procmin  
+         WRITE(numout,*) '                              sn_cfctl%procmax   = ', sn_cfctl%procmax  
+         WRITE(numout,*) '                              sn_cfctl%procincr  = ', sn_cfctl%procincr 
+         WRITE(numout,*) '                              sn_cfctl%ptimincr  = ', sn_cfctl%ptimincr 
+         WRITE(numout,*) '      level of print                  nn_print   = ', nn_print
+         WRITE(numout,*) '      Start i indice for SUM control  nn_ictls   = ', nn_ictls
+         WRITE(numout,*) '      End i indice for SUM control    nn_ictle   = ', nn_ictle
+         WRITE(numout,*) '      Start j indice for SUM control  nn_jctls   = ', nn_jctls
+         WRITE(numout,*) '      End j indice for SUM control    nn_jctle   = ', nn_jctle
+         WRITE(numout,*) '      number of proc. following i     nn_isplt   = ', nn_isplt
+         WRITE(numout,*) '      number of proc. following j     nn_jsplt   = ', nn_jsplt
+         WRITE(numout,*) '      timing by routine               ln_timing  = ', ln_timing
+         WRITE(numout,*) '      CFL diagnostics                 ln_diacfl  = ', ln_diacfl
+      ENDIF
+      !
+      nprint    = nn_print          ! convert DOCTOR namelist names into OLD names
+      nictls    = nn_ictls
+      nictle    = nn_ictle
+      njctls    = nn_jctls
+      njctle    = nn_jctle
+      isplt     = nn_isplt
+      jsplt     = nn_jsplt
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namcfg'
+         WRITE(numout,*) '      read domain configuration file              ln_read_cfg      = ', ln_read_cfg
+         WRITE(numout,*) '         filename to be read                         cn_domcfg     = ', TRIM(cn_domcfg)
+         WRITE(numout,*) '         keep closed seas in the domain (if exist)   ln_closea     = ', ln_closea
+         WRITE(numout,*) '      create a configuration definition file      ln_write_cfg     = ', ln_write_cfg
+         WRITE(numout,*) '         filename to be written                      cn_domcfg_out = ', TRIM(cn_domcfg_out)
+         WRITE(numout,*) '      use file attribute if exists as i/p j-start ln_use_jattr     = ', ln_use_jattr
+      ENDIF
+      IF( .NOT.ln_read_cfg )   ln_closea = .false.   ! dealing possible only with a domcfg file
+      !
+      !                             ! Parameter control
+      !
+      IF( ln_ctl ) THEN                 ! sub-domain area indices for the control prints
+         IF( lk_mpp .AND. jpnij > 1 ) THEN
+            isplt = jpni   ;   jsplt = jpnj   ;   ijsplt = jpni*jpnj   ! the domain is forced to the real split domain
+         ELSE
+            IF( isplt == 1 .AND. jsplt == 1  ) THEN
+               CALL ctl_warn( ' - isplt & jsplt are equal to 1',   &
+                  &           ' - the print control will be done over the whole domain' )
+            ENDIF
+            ijsplt = isplt * jsplt            ! total number of processors ijsplt
+         ENDIF
+         IF(lwp) WRITE(numout,*)'          - The total number of processors over which the'
+         IF(lwp) WRITE(numout,*)'            print control will be done is ijsplt : ', ijsplt
+         !
+         !                              ! indices used for the SUM control
+         IF( nictls+nictle+njctls+njctle == 0 )   THEN    ! print control done over the default area
+            lsp_area = .FALSE.
+         ELSE                                             ! print control done over a specific  area
+            lsp_area = .TRUE.
+            IF( nictls < 1 .OR. nictls > jpiglo )   THEN
+               CALL ctl_warn( '          - nictls must be 1<=nictls>=jpiglo, it is forced to 1' )
+               nictls = 1
+            ENDIF
+            IF( nictle < 1 .OR. nictle > jpiglo )   THEN
+               CALL ctl_warn( '          - nictle must be 1<=nictle>=jpiglo, it is forced to jpiglo' )
+               nictle = jpiglo
+            ENDIF
+            IF( njctls < 1 .OR. njctls > jpjglo )   THEN
+               CALL ctl_warn( '          - njctls must be 1<=njctls>=jpjglo, it is forced to 1' )
+               njctls = 1
+            ENDIF
+            IF( njctle < 1 .OR. njctle > jpjglo )   THEN
+               CALL ctl_warn( '          - njctle must be 1<=njctle>=jpjglo, it is forced to jpjglo' )
+               njctle = jpjglo
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( 1._wp /= SIGN(1._wp,-0._wp)  )   CALL ctl_stop( 'nemo_ctl: The intrinsec SIGN function follows f2003 standard.',  &
+         &                                                'Compile with key_nosignedzero enabled' )
+      !
+   END SUBROUTINE nemo_ctl
+
+
+   SUBROUTINE nemo_closefile
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_closefile  ***
+      !!
+      !! ** Purpose :   Close the files
+      !!----------------------------------------------------------------------
+      !
+      IF( lk_mpp )   CALL mppsync
+      !
+      CALL iom_close                                 ! close all input/output files managed by iom_*
+      !
+      IF( numstp     /= -1 )   CLOSE( numstp     )   ! time-step file
+      IF( numnam_ref /= -1 )   CLOSE( numnam_ref )   ! oce reference namelist
+      IF( numnam_cfg /= -1 )   CLOSE( numnam_cfg )   ! oce configuration namelist
+      IF( numout     /=  6 )   CLOSE( numout     )   ! standard model output file
+      IF( lwm.AND.numond  /= -1 )   CLOSE( numond          )   ! oce output namelist
+      !
+      numout = 6                                     ! redefine numout in case it is used after this point...
+      !
+   END SUBROUTINE nemo_closefile
+
+
+   SUBROUTINE nemo_alloc
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_alloc  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!
+      !! ** Method  :
+      !!----------------------------------------------------------------------
+      USE diawri ,   ONLY : dia_wri_alloc
+      USE dom_oce,   ONLY : dom_oce_alloc
+      USE zdf_oce,   ONLY : zdf_oce_alloc
+      USE trc_oce,   ONLY : trc_oce_alloc
+      USE bdy_oce,   ONLY : bdy_oce_alloc
+      !
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ierr =        oce_alloc    ()          ! ocean 
+      ierr = ierr + dia_wri_alloc()
+      ierr = ierr + dom_oce_alloc()          ! ocean domain
+      ierr = ierr + zdf_oce_alloc()          ! ocean vertical physics
+      ierr = ierr + trc_oce_alloc()          ! shared TRC / TRA arrays
+      ierr = ierr + bdy_oce_alloc()    ! bdy masks (incl. initialization)
+      
+      !
+      CALL mpp_sum( 'nemogcm', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'nemo_alloc: unable to allocate standard ocean arrays' )
+      !
+   END SUBROUTINE nemo_alloc
+
+   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto, for_all )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_set_cfctl  ***
+      !!
+      !! ** Purpose :   Set elements of the output control structure to setto.
+      !!                for_all should be .false. unless all areas are to be
+      !!                treated identically.
+      !!
+      !! ** Method  :   Note this routine can be used to switch on/off some
+      !!                types of output for selected areas but any output types
+      !!                that involve global communications (e.g. mpp_max, glob_sum)
+      !!                should be protected from selective switching by the
+      !!                for_all argument
+      !!----------------------------------------------------------------------
+      LOGICAL :: setto, for_all
+      TYPE(sn_ctl) :: sn_cfctl
+      !!----------------------------------------------------------------------
+      IF( for_all ) THEN
+         sn_cfctl%l_runstat = setto
+         sn_cfctl%l_trcstat = setto
+      ENDIF
+      sn_cfctl%l_oceout  = setto
+      sn_cfctl%l_layout  = setto
+      sn_cfctl%l_mppout  = setto
+      sn_cfctl%l_mpptop  = setto
+   END SUBROUTINE nemo_set_cfctl
+
+   SUBROUTINE istate_init
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE istate_init  ***
+      !!
+      !! ** Purpose :   Initialization to zero of the dynamics and tracers.
+      !!----------------------------------------------------------------------
+      !
+      !     now fields         !     after fields      !
+      un   (:,:,:)   = 0._wp   ;   ua(:,:,:) = 0._wp   !
+      vn   (:,:,:)   = 0._wp   ;   va(:,:,:) = 0._wp   !
+      wn   (:,:,:)   = 0._wp   !                       !
+      hdivn(:,:,:)   = 0._wp   !                       !
+      tsn  (:,:,:,:) = 0._wp   !                       !
+      !
+      rhd  (:,:,:) = 0.e0
+      rhop (:,:,:) = 0.e0
+      rn2  (:,:,:) = 0.e0
+      !
+   END SUBROUTINE istate_init
+
+
+   SUBROUTINE stp_ctl( kt, kindic )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE stp_ctl  ***
+      !!
+      !! ** Purpose :   Control the run
+      !!
+      !! ** Method  : - Save the time step in numstp
+      !!
+      !! ** Actions :   'time.step' file containing the last ocean time-step
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt      ! ocean time-step index
+      INTEGER, INTENT(inout) ::   kindic  ! indicator of solver convergence
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 .AND. lwm ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'stp_ctl : time-stepping control'
+         WRITE(numout,*) '~~~~~~~'
+         ! open time.step file
+         CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+      ENDIF
+      !
+      IF(lwm) WRITE ( numstp, '(1x, i8)' )   kt      !* save the current time step in numstp
+      IF(lwm) REWIND( numstp )                       ! --------------------------
+      !
+   END SUBROUTINE stp_ctl
+   !!======================================================================
+END MODULE nemogcm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/README.rst	(revision 14097)
@@ -0,0 +1,15 @@
+*******
+Sources
+*******
+
+.. todo::
+
+
+
+:file:`ICE`: |NEMO-ICE|
+
+:file:`NST`: AGRIF for embedded zooms
+
+:file:`OCE`: |NEMO-OCE|
+
+:file:`TOP`: |NEMO-MBG|
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/nemogcm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/nemogcm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/nemogcm.F90	(revision 14097)
@@ -0,0 +1,441 @@
+MODULE nemogcm
+   !!======================================================================
+   !!                       ***  MODULE nemogcm   ***
+   !! Ocean system   : NEMO GCM (ocean dynamics, on-line tracers, biochemistry and sea-ice)
+   !!======================================================================
+   !! History :  3.6  ! 2015-12  (A. Ryan) Original code   (from OCE/) 
+   !!            4.0  ! 2016-11  (G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   nemo_gcm      : solve ocean dynamics, tracer, biogeochemistry and/or sea-ice
+   !!   nemo_init     : initialization of the NEMO system
+   !!   nemo_ctl      : initialisation of the contol print
+   !!   nemo_closefile: close remaining open files
+   !!   nemo_alloc    : dynamical allocation
+   !!----------------------------------------------------------------------
+   USE step_oce       ! module used in the ocean time stepping module (step.F90)
+   USE domain         ! domain initialization   (dom_init & dom_cfg routines)
+   USE istate         ! initial state setting          (istate_init routine)
+   USE phycst         ! physical constant                  (par_cst routine)
+   USE step           ! NEMO time-stepping                 (stp     routine)
+   USE cpl_oasis3     ! OASIS3 coupling
+   USE diaobs         ! Observation diagnostics       (dia_obs_init routine)
+#if defined key_nemocice_decomp
+   USE ice_domain_size, only: nx_global, ny_global
+#endif
+   !           ! Stand Alone Observation operator modules
+   USE sao_data
+   USE sao_intp
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distributed memory computing
+   USE mppini         ! shared/distributed memory setting (mpp_init routine)
+   USE lbcnfd  , ONLY : isendto, nsndto, nfsloop, nfeloop ! Setup of north fold exchanges 
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+#if defined key_iomput
+   USE xios           ! xIOserver
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   nemo_gcm    ! called by model.F90
+   PUBLIC   nemo_init   ! needed by AGRIF
+   PUBLIC   nemo_alloc  ! needed by TAM
+
+   CHARACTER(lc) ::   cform_aaa="( /, 'AAAAAAAA', / ) "     ! flag for output listing
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE nemo_gcm
+         !!----------------------------------------------------------------------
+         !!                    ***  SUBROUTINE offline_obs_oper ***
+         !!
+         !! ** Purpose : To use NEMO components to interpolate model fields
+         !!              to observation space.
+         !!
+         !! ** Method : 1. Initialise NEMO
+         !!             2. Initialise offline obs_oper
+         !!             3. Cycle through match ups
+         !!             4. Write results to file
+         !!----------------------------------------------------------------------
+         !
+         CALL nemo_init       ! Initialise NEMO
+         !
+         CALL sao_data_init   ! Initialise Stand Alone Observation operator data
+         !
+         CALL dia_obs_init    ! Initialise obs_operator
+         !
+         CALL sao_interp      ! Interpolate to observation space
+         !
+         CALL dia_obs_wri     ! Pipe to output files
+         !
+         CALL dia_obs_dealloc ! Reset the obs_oper between
+         !
+         IF(lk_mpp)   CALL mppstop  ! Safely stop MPI (end mpp communications)
+         !
+   END SUBROUTINE nemo_gcm
+
+
+   SUBROUTINE nemo_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_init  ***
+      !!
+      !! ** Purpose :   initialization of the NEMO GCM
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, ilocal_comm   ! local integer
+      !
+      NAMELIST/namctl/ ln_ctl   , sn_cfctl, nn_print, nn_ictls, nn_ictle,   &
+         &             nn_isplt , nn_jsplt, nn_jctls, nn_jctle,             &
+         &             ln_timing, ln_diacfl
+      NAMELIST/namcfg/ ln_read_cfg, cn_domcfg, ln_closea, ln_write_cfg, cn_domcfg_out, ln_use_jattr
+      !!----------------------------------------------------------------------
+      !
+      cxios_context = 'nemo'
+      !
+      !                             !-------------------------------------------------!
+      !                             !     set communicator & select the local rank    !
+      !                             !  must be done as soon as possible to get narea  !
+      !                             !-------------------------------------------------!
+      !
+#if defined key_iomput
+      IF( Agrif_Root() ) THEN
+         IF( lk_oasis ) THEN
+            CALL cpl_init( "oceanx", ilocal_comm )                               ! nemo local communicator given by oasis
+            CALL xios_initialize( "not used"       , local_comm =ilocal_comm )   ! send nemo communicator to xios
+         ELSE
+            CALL xios_initialize( "for_xios_mpi_id", return_comm=ilocal_comm )   ! nemo local communicator given by xios
+         ENDIF
+      ENDIF
+      CALL mpp_start( ilocal_comm )
+#else
+      IF( lk_oasis ) THEN
+         IF( Agrif_Root() ) THEN
+            CALL cpl_init( "oceanx", ilocal_comm )          ! nemo local communicator given by oasis
+         ENDIF
+         CALL mpp_start( ilocal_comm )
+      ELSE
+         CALL mpp_start( )
+      ENDIF
+#endif
+      !
+      narea = mpprank + 1               ! mpprank: the rank of proc (0 --> mppsize -1 )
+      lwm = (narea == 1)                ! control of output namelists
+      !
+      !                             !---------------------------------------------------------------!
+      !                             ! Open output files, reference and configuration namelist files !
+      !                             !---------------------------------------------------------------!
+      !
+      ! open ocean.output as soon as possible to get all output prints (including errors messages)
+      IF( lwm )   CALL ctl_opn(     numout,        'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open reference and configuration namelist files
+                  CALL ctl_opn( numnam_ref,        'namelist_ref',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+                  CALL ctl_opn( numnam_cfg,        'namelist_cfg',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      IF( lwm )   CALL ctl_opn(     numond, 'output.namelist.dyn', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ! open /dev/null file to be able to supress output write easily
+      IF( Agrif_Root() ) THEN
+                  CALL ctl_opn(     numnul,           '/dev/null', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+#ifdef key_agrif
+      ELSE
+                  numnul = Agrif_Parent(numnul)
+#endif
+      ENDIF
+      !
+      !                             !--------------------!
+      !                             ! Open listing units !  -> need ln_ctl from namctl to define lwp
+      !                             !--------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namctl in reference namelist
+      READ  ( numnam_ref, namctl, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namctl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namctl in confguration namelist
+      READ  ( numnam_cfg, namctl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namctl in configuration namelist' )
+      !
+      lwp = (narea == 1) .OR. ln_ctl    ! control of all listing output print
+      !
+      IF(lwp) THEN                      ! open listing units
+         !
+         IF( .NOT. lwm )   &            ! alreay opened for narea == 1
+            &            CALL ctl_opn( numout, 'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE., narea )
+         !
+         WRITE(numout,*)
+         WRITE(numout,*) '   CNRS - NERC - Met OFFICE - MERCATOR-ocean - CMCC'
+         WRITE(numout,*) '                       NEMO team'
+         WRITE(numout,*) '            Stand Alone Observation operator'
+         WRITE(numout,*) '                NEMO version 4.0  (2019) '
+         WRITE(numout,*)
+         WRITE(numout,*) "           ._      ._      ._      ._      ._    "
+         WRITE(numout,*) "       _.-._)`\_.-._)`\_.-._)`\_.-._)`\_.-._)`\_ "
+         WRITE(numout,*)
+         WRITE(numout,*) "           o         _,           _,             "
+         WRITE(numout,*) "            o      .' (        .-' /             "
+         WRITE(numout,*) "           o     _/..._'.    .'   /              "
+         WRITE(numout,*) "      (    o .-'`      ` '-./  _.'               "
+         WRITE(numout,*) "       )    ( o)           ;= <_         (       "
+         WRITE(numout,*) "      (      '-.,\\__ __.-;`\   '.        )      "
+         WRITE(numout,*) "       )  )       \) |`\ \)  '.   \      (   (   "
+         WRITE(numout,*) "      (  (           \_/       '-._\      )   )  "
+         WRITE(numout,*) "       )  ) jgs                     `    (   (   "
+         WRITE(numout,*) "     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
+         WRITE(numout,*)
+         !
+         WRITE(numout,cform_aaa)                                        ! Flag AAAAAAA
+         !
+      ENDIF
+      !
+      ! finalize the definition of namctl variables
+      IF( sn_cfctl%l_config ) THEN
+         ! Activate finer control of report outputs
+         ! optionally switch off output from selected areas (note this only
+         ! applies to output which does not involve global communications)
+         IF( ( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax  ) .OR. &
+           & ( MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 ) )    &
+           &   CALL nemo_set_cfctl( sn_cfctl, .FALSE., .FALSE. )
+      ELSE
+         ! Use ln_ctl to turn on or off all options.
+         CALL nemo_set_cfctl( sn_cfctl, ln_ctl, .TRUE. )
+      ENDIF
+      !
+      IF(lwm) WRITE( numond, namctl )
+      !
+      !                             !------------------------------------!
+      !                             !  Set global domain size parameters !
+      !                             !------------------------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namcfg in reference namelist
+      READ  ( numnam_ref, namcfg, IOSTAT = ios, ERR = 903 )
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcfg in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namcfg in confguration namelist
+      READ  ( numnam_cfg, namcfg, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcfg in configuration namelist' )   
+      !
+      IF( ln_read_cfg ) THEN            ! Read sizes in domain configuration file
+         CALL domain_cfg ( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ELSE                              ! user-defined namelist
+         CALL usr_def_nam( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ENDIF
+      !
+      IF(lwm)   WRITE( numond, namcfg )
+      !
+      !                             !-----------------------------------------!
+      !                             ! mpp parameters and domain decomposition !
+      !                             !-----------------------------------------!
+      CALL mpp_init
+
+      ! Now we know the dimensions of the grid and numout has been set: we can allocate arrays
+      CALL nemo_alloc()
+
+      !                             !-------------------------------!
+      !                             !  NEMO general initialization  !
+      !                             !-------------------------------!
+
+      CALL nemo_ctl                          ! Control prints
+      !
+      !                                         ! General initialization
+      IF( ln_timing    )   CALL timing_init     ! timing
+      IF( ln_timing    )   CALL timing_start( 'nemo_init')
+      !
+                           CALL phy_cst            ! Physical constants
+                           CALL eos_init           ! Equation of state
+                           CALL dom_init('SAO')    ! Domain
+
+
+      IF( ln_ctl       )   CALL prt_ctl_init    ! Print control
+
+                           CALL istate_init     ! ocean initial state (Dynamics and tracers)
+   END SUBROUTINE nemo_init
+
+
+   SUBROUTINE nemo_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_ctl  ***
+      !!
+      !! ** Purpose :   control print setting
+      !!
+      !! ** Method  : - print namctl information and check some consistencies
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'nemo_ctl: Control prints'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist namctl'
+         WRITE(numout,*) '      run control (for debugging)     ln_ctl     = ', ln_ctl
+         WRITE(numout,*) '       finer control over o/p sn_cfctl%l_config  = ', sn_cfctl%l_config
+         WRITE(numout,*) '                              sn_cfctl%l_runstat = ', sn_cfctl%l_runstat
+         WRITE(numout,*) '                              sn_cfctl%l_trcstat = ', sn_cfctl%l_trcstat
+         WRITE(numout,*) '                              sn_cfctl%l_oceout  = ', sn_cfctl%l_oceout
+         WRITE(numout,*) '                              sn_cfctl%l_layout  = ', sn_cfctl%l_layout
+         WRITE(numout,*) '                              sn_cfctl%l_mppout  = ', sn_cfctl%l_mppout
+         WRITE(numout,*) '                              sn_cfctl%l_mpptop  = ', sn_cfctl%l_mpptop
+         WRITE(numout,*) '                              sn_cfctl%procmin   = ', sn_cfctl%procmin  
+         WRITE(numout,*) '                              sn_cfctl%procmax   = ', sn_cfctl%procmax  
+         WRITE(numout,*) '                              sn_cfctl%procincr  = ', sn_cfctl%procincr 
+         WRITE(numout,*) '                              sn_cfctl%ptimincr  = ', sn_cfctl%ptimincr 
+         WRITE(numout,*) '      level of print                  nn_print   = ', nn_print
+         WRITE(numout,*) '      Start i indice for SUM control  nn_ictls   = ', nn_ictls
+         WRITE(numout,*) '      End i indice for SUM control    nn_ictle   = ', nn_ictle
+         WRITE(numout,*) '      Start j indice for SUM control  nn_jctls   = ', nn_jctls
+         WRITE(numout,*) '      End j indice for SUM control    nn_jctle   = ', nn_jctle
+         WRITE(numout,*) '      number of proc. following i     nn_isplt   = ', nn_isplt
+         WRITE(numout,*) '      number of proc. following j     nn_jsplt   = ', nn_jsplt
+         WRITE(numout,*) '      timing by routine               ln_timing  = ', ln_timing
+         WRITE(numout,*) '      CFL diagnostics                 ln_diacfl  = ', ln_diacfl
+      ENDIF
+      !
+      nprint    = nn_print          ! convert DOCTOR namelist names into OLD names
+      nictls    = nn_ictls
+      nictle    = nn_ictle
+      njctls    = nn_jctls
+      njctle    = nn_jctle
+      isplt     = nn_isplt
+      jsplt     = nn_jsplt
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namcfg'
+         WRITE(numout,*) '      read domain configuration file                ln_read_cfg      = ', ln_read_cfg
+         WRITE(numout,*) '         filename to be read                           cn_domcfg     = ', TRIM(cn_domcfg)
+         WRITE(numout,*) '         keep closed seas in the domain (if exist)     ln_closea     = ', ln_closea
+         WRITE(numout,*) '      create a configuration definition file        ln_write_cfg     = ', ln_write_cfg
+         WRITE(numout,*) '         filename to be written                        cn_domcfg_out = ', TRIM(cn_domcfg_out)
+         WRITE(numout,*) '      use file attribute if exists as i/p j-start   ln_use_jattr     = ', ln_use_jattr
+      ENDIF
+      IF( .NOT.ln_read_cfg )   ln_closea = .false.   ! dealing possible only with a domcfg file
+      !
+      !                             ! Parameter control
+      !
+      IF( ln_ctl ) THEN                 ! sub-domain area indices for the control prints
+         IF( lk_mpp .AND. jpnij > 1 ) THEN
+            isplt = jpni   ;   jsplt = jpnj   ;   ijsplt = jpni*jpnj   ! the domain is forced to the real split domain
+         ELSE
+            IF( isplt == 1 .AND. jsplt == 1  ) THEN
+               CALL ctl_warn( ' - isplt & jsplt are equal to 1',   &
+                  &           ' - the print control will be done over the whole domain' )
+            ENDIF
+            ijsplt = isplt * jsplt            ! total number of processors ijsplt
+         ENDIF
+         IF(lwp) WRITE(numout,*)'          - The total number of processors over which the'
+         IF(lwp) WRITE(numout,*)'            print control will be done is ijsplt : ', ijsplt
+         !
+         !                              ! indices used for the SUM control
+         IF( nictls+nictle+njctls+njctle == 0 )   THEN    ! print control done over the default area
+            lsp_area = .FALSE.
+         ELSE                                             ! print control done over a specific  area
+            lsp_area = .TRUE.
+            IF( nictls < 1 .OR. nictls > jpiglo )   THEN
+               CALL ctl_warn( '          - nictls must be 1<=nictls>=jpiglo, it is forced to 1' )
+               nictls = 1
+            ENDIF
+            IF( nictle < 1 .OR. nictle > jpiglo )   THEN
+               CALL ctl_warn( '          - nictle must be 1<=nictle>=jpiglo, it is forced to jpiglo' )
+               nictle = jpiglo
+            ENDIF
+            IF( njctls < 1 .OR. njctls > jpjglo )   THEN
+               CALL ctl_warn( '          - njctls must be 1<=njctls>=jpjglo, it is forced to 1' )
+               njctls = 1
+            ENDIF
+            IF( njctle < 1 .OR. njctle > jpjglo )   THEN
+               CALL ctl_warn( '          - njctle must be 1<=njctle>=jpjglo, it is forced to jpjglo' )
+               njctle = jpjglo
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( 1._wp /= SIGN(1._wp,-0._wp)  )   CALL ctl_stop( 'nemo_ctl: The intrinsec SIGN function follows f2003 standard.',  &
+         &                                                'Compile with key_nosignedzero enabled:',   &
+         &                                                '--> add -Dkey_nosignedzero to the definition of %CPP in your arch file' )
+      !
+   END SUBROUTINE nemo_ctl
+
+
+   SUBROUTINE nemo_closefile
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_closefile  ***
+      !!
+      !! ** Purpose :   Close the files
+      !!----------------------------------------------------------------------
+      !
+      IF( lk_mpp )   CALL mppsync
+      !
+      CALL iom_close                                 ! close all input/output files managed by iom_*
+      !
+      IF( numstp          /= -1 )   CLOSE( numstp          )   ! time-step file
+      IF( numrun          /= -1 )   CLOSE( numrun          )   ! run statistics file
+      IF( numnam_ref      /= -1 )   CLOSE( numnam_ref      )   ! oce reference namelist
+      IF( numnam_cfg      /= -1 )   CLOSE( numnam_cfg      )   ! oce configuration namelist
+      IF( lwm.AND.numond  /= -1 )   CLOSE( numond          )   ! oce output namelist
+      IF( numnam_ice_ref  /= -1 )   CLOSE( numnam_ice_ref  )   ! ice reference namelist
+      IF( numnam_ice_cfg  /= -1 )   CLOSE( numnam_ice_cfg  )   ! ice configuration namelist
+      IF( lwm.AND.numoni  /= -1 )   CLOSE( numoni          )   ! ice output namelist
+      IF( numevo_ice      /= -1 )   CLOSE( numevo_ice      )   ! ice variables (temp. evolution)
+      IF( numout          /=  6 )   CLOSE( numout          )   ! standard model output file
+      IF( numdct_vol      /= -1 )   CLOSE( numdct_vol      )   ! volume transports
+      IF( numdct_heat     /= -1 )   CLOSE( numdct_heat     )   ! heat transports
+      IF( numdct_salt     /= -1 )   CLOSE( numdct_salt     )   ! salt transports
+      !
+      numout = 6                                     ! redefine numout in case it is used after this point...
+      !
+   END SUBROUTINE nemo_closefile
+
+
+   SUBROUTINE nemo_alloc
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_alloc  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!
+      !! ** Method  :
+      !!----------------------------------------------------------------------
+      USE diawri    , ONLY: dia_wri_alloc
+      USE dom_oce   , ONLY: dom_oce_alloc
+      !
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ierr =        oce_alloc       ()          ! ocean
+      ierr = ierr + dia_wri_alloc   ()
+      ierr = ierr + dom_oce_alloc   ()          ! ocean domain
+      !
+      CALL mpp_sum( 'nemogcm', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'nemo_alloc : unable to allocate standard ocean arrays' )
+      !
+   END SUBROUTINE nemo_alloc
+
+   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto, for_all )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_set_cfctl  ***
+      !!
+      !! ** Purpose :   Set elements of the output control structure to setto.
+      !!                for_all should be .false. unless all areas are to be
+      !!                treated identically.
+      !!
+      !! ** Method  :   Note this routine can be used to switch on/off some
+      !!                types of output for selected areas but any output types
+      !!                that involve global communications (e.g. mpp_max, glob_sum)
+      !!                should be protected from selective switching by the
+      !!                for_all argument
+      !!----------------------------------------------------------------------
+      LOGICAL :: setto, for_all
+      TYPE(sn_ctl) :: sn_cfctl
+      !!----------------------------------------------------------------------
+      IF( for_all ) THEN
+         sn_cfctl%l_runstat = setto
+         sn_cfctl%l_trcstat = setto
+      ENDIF
+      sn_cfctl%l_oceout  = setto
+      sn_cfctl%l_layout  = setto
+      sn_cfctl%l_mppout  = setto
+      sn_cfctl%l_mpptop  = setto
+   END SUBROUTINE nemo_set_cfctl
+
+   !!======================================================================
+END MODULE nemogcm
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/obs_fbm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/obs_fbm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/obs_fbm.F90	(revision 14097)
@@ -0,0 +1,1998 @@
+MODULE obs_fbm
+   !!======================================================================
+   !!                       ***  MODULE obs_fbm  ***
+   !! Observation operators : I/O + tools for feedback files
+   !!======================================================================
+   !! History : 
+   !!             !  08-11  (K. Mogensen) Initial version
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   init_obfbdata     :  Initialize sizes in obfbdata structure
+   !!   alloc_obfbdata    :  Allocate data in an obfbdata structure
+   !!   dealloc_obfbdata  :  Dellocate data in an obfbdata structure
+   !!   copy_obfbdata     :  Copy an obfbdata structure
+   !!   subsamp_obfbdata  :  Sumsample an obfbdata structure
+   !!   merge_obfbdata    :  Merge multiple obfbdata structures into an one.
+   !!   write_obfbdata    :  Write an obfbdata structure into a netCDF file.
+   !!   read_obfbdata     :  Read an obfbdata structure from a netCDF file.
+   !!----------------------------------------------------------------------
+   USE netcdf
+   USE obs_utils      ! Various utilities for observation operators
+
+   IMPLICIT NONE
+   PUBLIC
+
+   ! Type kinds for feedback data.
+
+   INTEGER, PARAMETER :: fbsp = SELECTED_REAL_KIND( 6, 37) !: single precision
+   INTEGER, PARAMETER :: fbdp = SELECTED_REAL_KIND(12,307) !: double precision
+
+   ! Parameters for string lengths.
+
+   INTEGER, PARAMETER    :: ilenwmo  = 8    !: Length of station identifier
+   INTEGER, PARAMETER    :: ilentyp  = 4    !: Length of type
+   INTEGER, PARAMETER    :: ilenname = 8    !: Length of variable names
+   INTEGER, PARAMETER    :: ilengrid = 1    !: Grid (e.g. 'T') length
+   INTEGER, PARAMETER    :: ilenjuld = 14   !: Lenght of reference julian date
+   INTEGER, PARAMETER    :: idefnqcf = 2    !: Default number of words in QC
+                                            !  flags
+   INTEGER, PARAMETER    :: ilenlong = 128  !: Length of long name
+   INTEGER, PARAMETER    :: ilenunit = 32   !: Length of units
+   
+   ! Missinge data indicators 
+   
+   INTEGER, PARAMETER    :: fbimdi = -99999   !: Integers
+   REAL(fbsp), PARAMETER :: fbrmdi =  99999   !: Reals
+ 
+   ! Main data structure for observation feedback data.
+
+   TYPE obfbdata
+      LOGICAL :: lalloc         !: Allocation status for data
+      LOGICAL :: lgrid          !: Include grid search info
+      INTEGER :: nvar           !: Number of variables
+      INTEGER :: nobs           !: Number of observations
+      INTEGER :: nlev           !: Number of levels
+      INTEGER :: nadd           !: Number of additional entries
+      INTEGER :: next           !: Number of extra variables
+      INTEGER :: nqcf           !: Number of words per qc flag
+      CHARACTER(LEN=ilenwmo), DIMENSION(:), POINTER :: &
+         & cdwmo                !: Identifier
+      CHARACTER(LEN=ilentyp), DIMENSION(:), POINTER :: &
+         & cdtyp                !: Instrument type
+      CHARACTER(LEN=ilenjuld) :: &
+         & cdjuldref            !: Julian date reference
+      INTEGER, DIMENSION(:), POINTER :: &
+         & kindex               !: Index of observations in the original file
+      INTEGER, DIMENSION(:), POINTER :: &
+         & ioqc, &              !: Observation QC
+         & ipqc, &              !: Position QC
+         & itqc                 !: Time QC
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & ioqcf, &             !: Observation QC flags
+         & ipqcf, &             !: Position QC flags
+         & itqcf                !: Time QC flags
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & idqc                 !: Depth QC
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & idqcf                !: Depth QC flags
+      REAL(KIND=fbdp), DIMENSION(:), POINTER :: &
+         & plam, &              !: Longitude
+         & pphi, &              !: Latitude
+         & ptim                 !: Time
+      REAL(KIND=fbsp), DIMENSION(:,:), POINTER :: &
+         & pdep                 !: Depth
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER  :: &
+         & cname                !: Name of variable
+      REAL(fbsp), DIMENSION(:,:,:), POINTER :: &
+         & pob                  !: Observation
+      CHARACTER(LEN=ilenlong), DIMENSION(:), POINTER :: &
+         & coblong              !: Observation long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:), POINTER :: &
+         & cobunit              !: Observation units (for output)
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & ivqc                 !: Variable QC
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & ivqcf                !: Variable QC flags
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & ivlqc                !: Variable level QC
+      INTEGER, DIMENSION(:,:,:,:), POINTER :: &
+         & ivlqcf               !: Variable level QC flags
+      INTEGER, DIMENSION(:,:), POINTER :: &
+         & iproc, &             !: Processor of obs (no I/O for this variable).
+         & iobsi, &             !: Global i index
+         & iobsj                !: Global j index
+      INTEGER, DIMENSION(:,:,:), POINTER :: &
+         & iobsk                !: k index
+      CHARACTER(LEN=ilengrid), DIMENSION(:), POINTER  :: &
+         & cgrid                !: Grid for this variable
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER :: &
+         & caddname             !: Additional entries names
+      CHARACTER(LEN=ilenlong), DIMENSION(:,:), POINTER :: &
+         & caddlong             !: Additional entries long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:,:), POINTER :: &
+         & caddunit             !: Additional entries units (for output)
+      REAL(fbsp), DIMENSION(:,:,:,:)   , POINTER :: &
+         & padd                 !: Additional entries
+      CHARACTER(LEN=ilenname), DIMENSION(:), POINTER :: &
+         & cextname             !: Extra variables names
+      CHARACTER(LEN=ilenlong), DIMENSION(:), POINTER :: &
+         & cextlong             !: Extra variables long name (for output)
+      CHARACTER(LEN=ilenunit), DIMENSION(:), POINTER :: &
+         & cextunit             !: Extra variables units (for output)
+      REAL(fbsp), DIMENSION(:,:,:)   , POINTER :: &
+         & pext                 !: Extra variables
+   END TYPE obfbdata
+
+   PRIVATE putvaratt_obfbdata
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE init_obfbdata( fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE init_obfbdata  ***
+      !!
+      !! ** Purpose :   Initialize sizes in obfbdata structure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata      ! obsfbdata structure
+
+      fbdata%nvar   = 0
+      fbdata%nobs   = 0
+      fbdata%nlev   = 0
+      fbdata%nadd   = 0
+      fbdata%next   = 0
+      fbdata%nqcf   = idefnqcf
+      fbdata%lalloc = .FALSE.
+      fbdata%lgrid  = .FALSE.
+
+   END SUBROUTINE init_obfbdata
+   
+   SUBROUTINE alloc_obfbdata( fbdata, kvar, kobs, klev, kadd, kext, lgrid, &
+      &                       kqcf)
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE alloc_obfbdata  ***
+      !!
+      !! ** Purpose :   Allocate data in an obfbdata structure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) ::  fbdata          ! obsfbdata structure to be allocated
+      INTEGER, INTENT(IN) :: kvar        ! Number of variables
+      INTEGER, INTENT(IN) :: kobs        ! Number of observations
+      INTEGER, INTENT(IN) :: klev        ! Number of levels
+      INTEGER, INTENT(IN) :: kadd        ! Number of additional entries
+      INTEGER, INTENT(IN) :: kext        ! Number of extra variables
+      LOGICAL, INTENT(IN) :: lgrid       ! Include grid search information
+      INTEGER, OPTIONAL ::  kqcf         ! Number of words for QC flags
+      !! * Local variables
+      INTEGER :: ji
+      INTEGER :: jv
+
+      ! Check allocation status and deallocate previous allocated structures
+
+      IF ( fbdata%lalloc ) THEN
+         CALL dealloc_obfbdata( fbdata )
+      ENDIF
+
+      ! Set dimensions
+
+      fbdata%lalloc = .TRUE.
+      fbdata%nvar   = kvar
+      fbdata%nobs   = kobs
+      fbdata%nlev   = MAX( klev, 1 )
+      fbdata%nadd   = kadd
+      fbdata%next   = kext
+      IF ( PRESENT(kqcf) ) THEN
+         fbdata%nqcf = kqcf
+      ELSE
+         fbdata%nqcf = idefnqcf
+      ENDIF
+
+      ! Set data not depending on number of observations
+
+      fbdata%cdjuldref  = REPEAT( 'X', ilenjuld )
+
+      ! Allocate and initialize standard data 
+
+      ALLOCATE( &
+         & fbdata%cname(fbdata%nvar),   &
+         & fbdata%coblong(fbdata%nvar), &
+         & fbdata%cobunit(fbdata%nvar)  &
+         & )
+      DO ji = 1, fbdata%nvar
+         WRITE(fbdata%cname(ji),'(A,I2.2)')'V_',ji
+         fbdata%coblong(ji) = REPEAT( ' ', ilenlong )
+         fbdata%cobunit(ji) = REPEAT( ' ', ilenunit )
+      END DO
+
+      ! Optionally also store grid search information
+      
+      IF ( lgrid ) THEN
+         ALLOCATE ( &
+            & fbdata%cgrid(fbdata%nvar) &
+            & )
+         fbdata%cgrid(:)      = REPEAT( 'X', ilengrid )
+         fbdata%lgrid         = .TRUE.
+      ENDIF
+         
+      ! Allocate and initialize additional entries if present
+         
+      IF ( fbdata%nadd > 0 ) THEN
+         ALLOCATE( &
+            & fbdata%caddname(fbdata%nadd),              &
+            & fbdata%caddlong(fbdata%nadd, fbdata%nvar), &
+            & fbdata%caddunit(fbdata%nadd, fbdata%nvar)  &
+            & )
+         DO ji = 1, fbdata%nadd
+            WRITE(fbdata%caddname(ji),'(A,I2.2)')'A',ji
+         END DO
+         DO jv = 1, fbdata%nvar
+            DO ji = 1, fbdata%nadd
+               fbdata%caddlong(ji,jv) = REPEAT( ' ', ilenlong )
+               fbdata%caddunit(ji,jv) = REPEAT( ' ', ilenunit )
+            END DO
+         END DO
+      ENDIF
+         
+      ! Allocate and initialize additional variables if present
+         
+      IF ( fbdata%next > 0 ) THEN
+         ALLOCATE( &
+            & fbdata%cextname(fbdata%next), &
+            & fbdata%cextlong(fbdata%next), &
+            & fbdata%cextunit(fbdata%next)  &
+            & )
+         DO ji = 1, fbdata%next
+            WRITE(fbdata%cextname(ji),'(A,I2.2)')'E_',ji
+            fbdata%cextlong(ji) = REPEAT( ' ', ilenlong )
+            fbdata%cextunit(ji) = REPEAT( ' ', ilenunit )
+         END DO
+      ENDIF
+
+      ! Data depending on number of observations is only allocated if nobs>0
+
+      IF ( fbdata%nobs > 0 ) THEN
+
+         ALLOCATE( &
+            & fbdata%cdwmo(fbdata%nobs),                                      &
+            & fbdata%cdtyp(fbdata%nobs),                                      &
+            & fbdata%ioqc(fbdata%nobs),                                       &
+            & fbdata%ioqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%ipqc(fbdata%nobs),                                       &
+            & fbdata%ipqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%itqc(fbdata%nobs),                                       &
+            & fbdata%itqcf(fbdata%nqcf,fbdata%nobs),                          &
+            & fbdata%idqc(fbdata%nlev,fbdata%nobs),                           &
+            & fbdata%idqcf(fbdata%nqcf,fbdata%nlev,fbdata%nobs),              &
+            & fbdata%plam(fbdata%nobs),                                       &
+            & fbdata%pphi(fbdata%nobs),                                       &
+            & fbdata%pdep(fbdata%nlev,fbdata%nobs),                           &
+            & fbdata%ptim(fbdata%nobs),                                       &
+            & fbdata%kindex(fbdata%nobs),                                     &
+            & fbdata%ivqc(fbdata%nobs,fbdata%nvar),                           &
+            & fbdata%ivqcf(fbdata%nqcf,fbdata%nobs,fbdata%nvar),              &
+            & fbdata%ivlqc(fbdata%nlev,fbdata%nobs,fbdata%nvar),              &
+            & fbdata%ivlqcf(fbdata%nqcf,fbdata%nlev,fbdata%nobs,fbdata%nvar), &
+            & fbdata%pob(fbdata%nlev,fbdata%nobs,fbdata%nvar)                 &
+            & )
+         fbdata%kindex(:)       = fbimdi
+         fbdata%cdwmo(:)        = REPEAT( 'X', ilenwmo )
+         fbdata%cdtyp(:)        = REPEAT( 'X', ilentyp )
+         fbdata%ioqc(:)         = fbimdi
+         fbdata%ioqcf(:,:)      = fbimdi
+         fbdata%ipqc(:)         = fbimdi
+         fbdata%ipqcf(:,:)      = fbimdi
+         fbdata%itqc(:)         = fbimdi
+         fbdata%itqcf(:,:)      = fbimdi
+         fbdata%idqc(:,:)       = fbimdi
+         fbdata%idqcf(:,:,:)    = fbimdi
+         fbdata%plam(:)         = fbrmdi
+         fbdata%pphi(:)         = fbrmdi
+         fbdata%pdep(:,:)       = fbrmdi
+         fbdata%ptim(:)         = fbrmdi
+         fbdata%ivqc(:,:)       = fbimdi
+         fbdata%ivqcf(:,:,:)    = fbimdi
+         fbdata%ivlqc(:,:,:)    = fbimdi
+         fbdata%ivlqcf(:,:,:,:) = fbimdi
+         fbdata%pob(:,:,:)      = fbrmdi
+         
+         ! Optionally also store grid search information
+         
+         IF ( lgrid ) THEN
+            ALLOCATE ( &
+               & fbdata%iproc(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsi(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsj(fbdata%nobs,fbdata%nvar),            &
+               & fbdata%iobsk(fbdata%nlev,fbdata%nobs,fbdata%nvar) &
+               & )
+            fbdata%iproc(:,:)    = fbimdi
+            fbdata%iobsi(:,:)    = fbimdi
+            fbdata%iobsj(:,:)    = fbimdi
+            fbdata%iobsk(:,:,:)  = fbimdi
+            fbdata%lgrid         = .TRUE.
+         ENDIF
+         
+         ! Allocate and initialize additional entries if present
+         
+         IF ( fbdata%nadd > 0 ) THEN
+            ALLOCATE( &
+               & fbdata%padd(fbdata%nlev,fbdata%nobs,fbdata%nadd,fbdata%nvar) &
+               & )
+            fbdata%padd(:,:,:,:) = fbrmdi
+         ENDIF
+         
+         ! Allocate and initialize additional variables if present
+         
+         IF ( fbdata%next > 0 ) THEN
+            ALLOCATE( &
+               & fbdata%pext(fbdata%nlev,fbdata%nobs,fbdata%next) &
+               & )
+            fbdata%pext(:,:,:) = fbrmdi
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE alloc_obfbdata
+
+   SUBROUTINE dealloc_obfbdata( fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE dealloc_obfbdata  ***
+      !!
+      !! ** Purpose :   Deallocate data in an obfbdata strucure
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata      ! obsfbdata structure
+
+      ! Deallocate data 
+
+      DEALLOCATE( &
+         & fbdata%cname,  &
+         & fbdata%coblong,&
+         & fbdata%cobunit &
+         & )
+
+      ! Deallocate optional grid search information
+      
+      IF ( fbdata%lgrid ) THEN
+         DEALLOCATE ( &
+            & fbdata%cgrid  &
+            & )
+      ENDIF
+
+      ! Deallocate additional entries
+
+      IF ( fbdata%nadd > 0 ) THEN
+         DEALLOCATE( &
+            & fbdata%caddname, &
+            & fbdata%caddlong, &
+            & fbdata%caddunit  &
+            & )
+      ENDIF
+
+      ! Deallocate extra variables
+
+      IF ( fbdata%next > 0 ) THEN
+         DEALLOCATE( &
+            & fbdata%cextname, &
+            & fbdata%cextlong, &
+            & fbdata%cextunit  &
+            & )
+      ENDIF
+
+      ! Deallocate arrays depending on number of obs (if nobs>0 only).
+
+      IF ( fbdata%nobs > 0 ) THEN
+
+         DEALLOCATE( &
+            & fbdata%cdwmo,  &
+            & fbdata%cdtyp,  &
+            & fbdata%ioqc,   &
+            & fbdata%ioqcf,  &
+            & fbdata%ipqc,   &
+            & fbdata%ipqcf,  &
+            & fbdata%itqc,   &
+            & fbdata%itqcf,  &
+            & fbdata%idqc,   &
+            & fbdata%idqcf,  &
+            & fbdata%plam,   &
+            & fbdata%pphi,   &
+            & fbdata%pdep,   &
+            & fbdata%ptim,   &
+            & fbdata%kindex, &
+            & fbdata%ivqc,   &
+            & fbdata%ivqcf,  &
+            & fbdata%ivlqc,  &
+            & fbdata%ivlqcf, &
+            & fbdata%pob     &
+            & )
+
+
+         ! Deallocate optional grid search information
+      
+         IF ( fbdata%lgrid ) THEN
+            DEALLOCATE ( &
+               & fbdata%iproc, &
+               & fbdata%iobsi, &
+               & fbdata%iobsj, &
+               & fbdata%iobsk  & 
+               & )
+         ENDIF
+
+         ! Deallocate additional entries
+
+         IF ( fbdata%nadd > 0 ) THEN
+            DEALLOCATE( &
+               & fbdata%padd       &
+               & )
+         ENDIF
+
+         ! Deallocate extra variables
+
+         IF ( fbdata%next > 0 ) THEN
+            DEALLOCATE( &
+               & fbdata%pext       &
+               & )
+         ENDIF
+
+      ENDIF
+
+      ! Reset arrays sizes
+
+      fbdata%lalloc = .FALSE.
+      fbdata%lgrid  = .FALSE.
+      fbdata%nvar   = 0
+      fbdata%nobs   = 0
+      fbdata%nlev   = 0
+      fbdata%nadd   = 0
+      fbdata%next   = 0
+   
+   END SUBROUTINE dealloc_obfbdata
+
+   SUBROUTINE copy_obfbdata( fbdata1, fbdata2, kadd, kext, lgrid, kqcf )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE copy_obfbdata  ***
+      !!
+      !! ** Purpose :   Copy an obfbdata structure
+      !!
+      !! ** Method  :   Copy all data from fbdata1 to fbdata2
+      !!                If fbdata2 is allocated it needs to be compliant
+      !!                with fbdata1.
+      !!                Additional entries can be added by setting nadd
+      !!                Additional extra fields can be added by setting next
+      !!                Grid information can be included with lgrid=.true.
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata1               ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdata2               ! Output obsfbdata structure
+      INTEGER, INTENT(IN), OPTIONAL :: kadd   ! Number of additional entries
+      INTEGER, INTENT(IN), OPTIONAL :: kext   ! Number of extra variables
+      INTEGER, INTENT(IN), OPTIONAL :: kqcf   ! Number of words per qc flags
+      LOGICAL, OPTIONAL :: lgrid              ! Grid info on output file
+
+      !! * Local variables
+      INTEGER :: nadd
+      INTEGER :: next
+      INTEGER :: nqcf
+      LOGICAL :: llgrid
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+
+      ! Check allocation status of fbdata1
+
+      IF ( .NOT. fbdata1%lalloc ) THEN
+         CALL fatal_error( 'copy_obfbdata: input data not allocated', &
+            &              __LINE__ )
+      ENDIF
+      
+      ! If nadd,next not specified use the ones from fbdata1
+      ! Otherwise check that they have large than the original ones
+      
+      IF ( PRESENT(kadd) ) THEN
+         nadd = kadd
+         IF ( nadd < fbdata1%nadd ) THEN
+            CALL warning    ( 'copy_obfbdata: ' // &
+               &              'nadd smaller than input nadd', __LINE__ )
+         ENDIF
+      ELSE
+         nadd = fbdata1%nadd
+      ENDIF
+      IF ( PRESENT(kext) ) THEN
+         next = kext
+         IF ( next < fbdata1%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'next smaller than input next', __LINE__ )
+         ENDIF
+      ELSE
+         next = fbdata1%next
+      ENDIF
+      IF ( PRESENT(lgrid) ) THEN
+         llgrid = lgrid
+         IF ( fbdata1%lgrid .AND. (.NOT. llgrid) ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'switching off grid info not possible', &
+               &              __LINE__ )
+         ENDIF
+      ELSE
+         llgrid = fbdata1%lgrid
+      ENDIF
+      IF ( PRESENT(kqcf) ) THEN
+         nqcf = kqcf
+         IF ( nqcf < fbdata1%nqcf ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'nqcf smaller than input nqcf', __LINE__ )
+         ENDIF
+      ELSE
+         nqcf = fbdata1%nqcf
+      ENDIF
+
+      ! Check allocation status of fbdata2 and 
+      ! a) check that it conforms in size if already allocated
+      ! b) allocate it if not already allocated
+      
+      IF ( fbdata2%lalloc ) THEN
+         IF ( fbdata1%nvar > fbdata2%nvar ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output kvar smaller than input kvar', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nobs > fbdata2%nobs ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output kobs smaller than input kobs', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nlev > fbdata2%nlev ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output klev smaller than input klev', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nadd > fbdata2%nadd ) THEN
+            CALL warning    ( 'copy_obfbdata: ' // &
+               &              'output nadd smaller than input nadd', __LINE__ )
+         ENDIF
+         IF ( fbdata1%next > fbdata2%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output next smaller than input next', __LINE__ )
+         ENDIF
+         IF ( fbdata1%lgrid .NEQV. fbdata2%lgrid ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'lgrid inconsistent', __LINE__ )
+         ENDIF
+         IF ( fbdata1%next > fbdata2%next ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output next smaller than input next', __LINE__ )
+         ENDIF
+         IF ( fbdata1%nqcf > fbdata2%nqcf ) THEN
+            CALL fatal_error( 'copy_obfbdata: ' // &
+               &              'output  smaller than input kext', __LINE__ )
+         ENDIF
+      ELSE
+         CALL alloc_obfbdata( fbdata2, fbdata1%nvar, fbdata1%nobs, &
+            &                 fbdata1%nlev, nadd, next, llgrid, kqcf = nqcf )
+      ENDIF
+
+      ! Copy the header data
+
+      fbdata2%cdjuldref = fbdata1%cdjuldref
+
+      DO ji = 1, fbdata1%nobs
+         fbdata2%cdwmo(ji)  = fbdata1%cdwmo(ji)
+         fbdata2%cdtyp(ji)  = fbdata1%cdtyp(ji)
+         fbdata2%ioqc(ji)   = fbdata1%ioqc(ji)
+         fbdata2%ipqc(ji)   = fbdata1%ipqc(ji)
+         fbdata2%itqc(ji)   = fbdata1%itqc(ji)
+         fbdata2%plam(ji)   = fbdata1%plam(ji)
+         fbdata2%pphi(ji)   = fbdata1%pphi(ji)
+         fbdata2%ptim(ji)   = fbdata1%ptim(ji)
+         fbdata2%kindex(ji) = fbdata1%kindex(ji)
+         DO jq = 1, fbdata1%nqcf
+            fbdata2%ioqcf(jq,ji)  = fbdata1%ioqcf(jq,ji)
+            fbdata2%ipqcf(jq,ji)  = fbdata1%ipqcf(jq,ji)
+            fbdata2%itqcf(jq,ji)  = fbdata1%itqcf(jq,ji)
+         END DO
+         DO jk = 1, fbdata1%nlev
+            fbdata2%idqc(jk,ji)  = fbdata1%idqc(jk,ji)
+            fbdata2%pdep(jk,ji)  = fbdata1%pdep(jk,ji)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%idqcf(jq,jk,ji) = fbdata1%idqcf(jq,jk,ji)
+            END DO
+         END DO
+      END DO
+
+      ! Copy the variable data
+
+      DO jv = 1, fbdata1%nvar
+         fbdata2%cname(jv) = fbdata1%cname(jv)
+         fbdata2%coblong(jv) = fbdata1%coblong(jv)
+         fbdata2%cobunit(jv) = fbdata1%cobunit(jv)
+         DO ji = 1, fbdata1%nobs
+            fbdata2%ivqc(ji,jv)  = fbdata1%ivqc(ji,jv)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%ivqcf(jq,ji,jv) = fbdata1%ivqcf(jq,ji,jv)
+            END DO
+            DO jk = 1, fbdata1%nlev
+               fbdata2%ivlqc(jk,ji,jv)  = fbdata1%ivlqc(jk,ji,jv)
+               fbdata2%pob(jk,ji,jv)    = fbdata1%pob(jk,ji,jv)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%ivlqcf(jq,jk,ji,jv) = fbdata1%ivlqcf(jq,jk,ji,jv)
+               END DO
+            END DO
+         END DO
+      END DO
+
+      ! Copy grid information
+      
+      IF ( fbdata1%lgrid ) THEN
+         DO jv = 1, fbdata1%nvar
+            fbdata2%cgrid(jv) = fbdata1%cgrid(jv)
+            DO ji = 1, fbdata1%nobs
+               fbdata2%iproc(ji,jv) = fbdata1%iproc(ji,jv)
+               fbdata2%iobsi(ji,jv) = fbdata1%iobsi(ji,jv)
+               fbdata2%iobsj(ji,jv) = fbdata1%iobsj(ji,jv)
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%iobsk(jk,ji,jv)  = fbdata1%iobsk(jk,ji,jv)
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      ! Copy additional information
+      
+      DO je = 1, MIN( fbdata1%nadd, fbdata2%nadd )
+         fbdata2%caddname(je) = fbdata1%caddname(je)
+      END DO
+      DO jv = 1, fbdata1%nvar
+         DO je = 1, MIN( fbdata1%nadd, fbdata2%nadd )
+            fbdata2%caddlong(je,jv) = fbdata1%caddlong(je,jv)
+            fbdata2%caddunit(je,jv) = fbdata1%caddunit(je,jv)
+            DO ji = 1, fbdata1%nobs
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%padd(jk,ji,je,jv) = fbdata1%padd(jk,ji,je,jv)
+               END DO
+            END DO
+         END DO
+      END DO
+      
+      ! Copy extra information
+
+      DO je = 1, fbdata1%next
+         fbdata2%cextname(je) = fbdata1%cextname(je)
+         fbdata2%cextlong(je) = fbdata1%cextlong(je)
+         fbdata2%cextunit(je) = fbdata1%cextunit(je)
+      END DO
+      DO je = 1, fbdata1%next
+         DO ji = 1, fbdata1%nobs
+            DO jk = 1, fbdata1%nlev
+               fbdata2%pext(jk,ji,je) = fbdata1%pext(jk,ji,je)
+            END DO
+         END DO
+      END DO
+
+   END SUBROUTINE copy_obfbdata
+
+   SUBROUTINE subsamp_obfbdata( fbdata1, fbdata2, llvalid )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE susbamp_obfbdata  ***
+      !!
+      !! ** Purpose :   Subsample an obfbdata structure based on the
+      !!                logical mask.
+      !!
+      !! ** Method  :   Copy all data from fbdata1 to fbdata2 if
+      !!                llvalid(obs)==true
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata1           ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdata2           ! Output obsfbdata structure
+      LOGICAL, DIMENSION(fbdata1%nobs) :: llvalid     ! Grid info on output file
+      !! * Local variables
+      INTEGER :: nobs
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+      INTEGER :: ij
+
+      ! Check allocation status of fbdata1
+
+      IF ( .NOT. fbdata1%lalloc ) THEN
+         CALL fatal_error( 'copy_obfbdata: input data not allocated', &
+            &              __LINE__ )
+      ENDIF
+      
+      ! Check allocation status of fbdata2 and abort if already allocated
+      
+      IF ( fbdata2%lalloc ) THEN
+         CALL fatal_error( 'subsample_obfbdata: ' // &
+            &              'fbdata2 already allocated', __LINE__ )
+      ENDIF
+      
+      ! Count number of subsampled observations
+
+      nobs = COUNT(llvalid)
+      
+      ! Allocate new data structure
+
+      CALL alloc_obfbdata( fbdata2, fbdata1%nvar, nobs, &
+         &                 fbdata1%nlev, fbdata1%nadd, fbdata1%next, &
+         &                 fbdata1%lgrid, kqcf = fbdata1%nqcf )
+
+      ! Copy the header data
+
+      fbdata2%cdjuldref = fbdata1%cdjuldref
+      
+      ij = 0
+      DO ji = 1, fbdata1%nobs
+         IF ( llvalid(ji) ) THEN
+            ij = ij +1
+            fbdata2%cdwmo(ij)  = fbdata1%cdwmo(ji)
+            fbdata2%cdtyp(ij)  = fbdata1%cdtyp(ji)
+            fbdata2%ioqc(ij)   = fbdata1%ioqc(ji)
+            fbdata2%ipqc(ij)   = fbdata1%ipqc(ji)
+            fbdata2%itqc(ij)   = fbdata1%itqc(ji)
+            fbdata2%plam(ij)   = fbdata1%plam(ji)
+            fbdata2%pphi(ij)   = fbdata1%pphi(ji)
+            fbdata2%ptim(ij)   = fbdata1%ptim(ji)
+            fbdata2%kindex(ij) = fbdata1%kindex(ji)
+            DO jq = 1, fbdata1%nqcf
+               fbdata2%ioqcf(jq,ij)  = fbdata1%ioqcf(jq,ji)
+               fbdata2%ipqcf(jq,ij)  = fbdata1%ipqcf(jq,ji)
+               fbdata2%itqcf(jq,ij)  = fbdata1%itqcf(jq,ji)
+            END DO
+            DO jk = 1, fbdata1%nlev
+               fbdata2%idqc(jk,ij)  = fbdata1%idqc(jk,ji)
+               fbdata2%pdep(jk,ij)  = fbdata1%pdep(jk,ji)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%idqcf(jq,jk,ij) = fbdata1%idqcf(jq,jk,ji)
+               END DO
+            END DO
+         ENDIF
+      END DO
+
+      ! Copy the variable data
+
+      DO jv = 1, fbdata1%nvar
+         fbdata2%cname(jv) = fbdata1%cname(jv)
+         fbdata2%coblong(jv) = fbdata1%coblong(jv)
+         fbdata2%cobunit(jv) = fbdata1%cobunit(jv)
+         ij = 0
+         DO ji = 1, fbdata1%nobs
+            IF ( llvalid(ji) ) THEN
+               ij = ij + 1
+               fbdata2%ivqc(ij,jv)  = fbdata1%ivqc(ji,jv)
+               DO jq = 1, fbdata1%nqcf
+                  fbdata2%ivqcf(jq,ij,jv) = fbdata1%ivqcf(jq,ji,jv)
+               END DO
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%ivlqc(jk,ij,jv)  = fbdata1%ivlqc(jk,ji,jv)
+                  fbdata2%pob(jk,ij,jv)    = fbdata1%pob(jk,ji,jv)
+                  DO jq = 1, fbdata1%nqcf
+                     fbdata2%ivlqcf(jq,jk,ij,jv) = fbdata1%ivlqcf(jq,jk,ji,jv)
+                  END DO
+               END DO
+            ENDIF
+         END DO
+      END DO
+
+      ! Copy grid information
+      
+      IF ( fbdata1%lgrid ) THEN
+         DO jv = 1, fbdata1%nvar
+            fbdata2%cgrid(jv) = fbdata1%cgrid(jv)
+            ij = 0
+            DO ji = 1, fbdata1%nobs
+               IF ( llvalid(ji) ) THEN
+                  ij = ij + 1
+                  fbdata2%iproc(ij,jv) = fbdata1%iproc(ji,jv)
+                  fbdata2%iobsi(ij,jv) = fbdata1%iobsi(ji,jv)
+                  fbdata2%iobsj(ij,jv) = fbdata1%iobsj(ji,jv)
+                  DO jk = 1, fbdata1%nlev
+                     fbdata2%iobsk(jk,ij,jv)  = fbdata1%iobsk(jk,ji,jv)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+      ENDIF
+
+      ! Copy additional information
+      
+      DO je = 1, fbdata1%nadd
+         fbdata2%caddname(je) = fbdata1%caddname(je)
+      END DO
+      DO jv = 1, fbdata1%nvar
+         DO je = 1, fbdata1%nadd
+            fbdata2%caddlong(je,jv) = fbdata1%caddlong(je,jv)
+            fbdata2%caddunit(je,jv) = fbdata1%caddunit(je,jv)
+            ij = 0
+            DO ji = 1, fbdata1%nobs
+               IF ( llvalid(ji) ) THEN
+                  ij = ij + 1
+                  DO jk = 1, fbdata1%nlev
+                     fbdata2%padd(jk,ij,je,jv) = fbdata1%padd(jk,ji,je,jv)
+                  END DO
+               ENDIF
+            END DO
+         END DO
+      END DO
+      
+      ! Copy extra information
+
+      DO je = 1, fbdata1%next
+         fbdata2%cextname(je) = fbdata1%cextname(je)
+         fbdata2%cextlong(je) = fbdata1%cextlong(je)
+         fbdata2%cextunit(je) = fbdata1%cextunit(je)
+      END DO
+      DO je = 1, fbdata1%next
+         ij = 0
+         DO ji = 1, fbdata1%nobs
+            IF ( llvalid(ji) ) THEN
+               ij = ij + 1
+               DO jk = 1, fbdata1%nlev
+                  fbdata2%pext(jk,ij,je) = fbdata1%pext(jk,ji,je)
+               END DO
+            ENDIF
+         END DO
+      END DO
+
+   END SUBROUTINE subsamp_obfbdata
+
+   SUBROUTINE merge_obfbdata( nsets, fbdatain, fbdataout, iset, inum, iind )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE merge_obfbdata  ***
+      !!
+      !! ** Purpose :   Merge multiple obfbdata structures into an one.
+      !!
+      !! ** Method  :   The order of elements is based on the indices in
+      !!                iind.
+      !!                All input data are assumed to be consistent. This
+      !!                is assumed to be checked before calling this routine.
+      !!                Likewise output data is assume to be consistent as 
+      !!                well without error checking.
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(IN):: nsets      ! Number of input data sets 
+      TYPE(obfbdata), DIMENSION(nsets) :: fbdatain  ! Input obsfbdata structure
+      TYPE(obfbdata) :: fbdataout      ! Output obsfbdata structure
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & iset                 ! Set number for a given obs.
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & inum                 ! Number within set for an obs
+      INTEGER, INTENT(IN), DIMENSION(fbdataout%nobs) :: &
+         & iind                 ! Indices for copying.
+      !! * Local variables
+
+      INTEGER :: js
+      INTEGER :: jo
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ji
+      INTEGER :: jk
+      INTEGER :: jq
+
+      ! Check allocation status of fbdatain 
+      
+      DO js = 1, nsets
+         IF ( .NOT. fbdatain(js)%lalloc ) THEN
+            CALL fatal_error( 'merge_obfbdata: input data not allocated', &
+               &              __LINE__ )
+         ENDIF
+      END DO
+
+      ! Check allocation status of fbdataout
+      
+      IF ( .NOT.fbdataout%lalloc ) THEN
+         CALL fatal_error( 'merge_obfbdata: output data not allocated', &
+            &              __LINE__ )
+      ENDIF
+
+      ! Merge various names
+
+      DO jv = 1, fbdatain(1)%nvar
+         fbdataout%cname(jv) = fbdatain(1)%cname(jv)
+         fbdataout%coblong(jv) = fbdatain(1)%coblong(jv)
+         fbdataout%cobunit(jv) = fbdatain(1)%cobunit(jv)
+         IF ( fbdatain(1)%lgrid ) THEN
+            fbdataout%cgrid(jv) = fbdatain(1)%cgrid(jv)
+         ENDIF
+      END DO
+      DO jv = 1, fbdatain(1)%nadd
+         fbdataout%caddname(jv) = fbdatain(1)%caddname(jv)
+      END DO
+      DO jv = 1, fbdatain(1)%nvar
+         DO je = 1, fbdatain(1)%nadd
+            fbdataout%caddlong(je,jv) = fbdatain(1)%caddlong(je,jv)
+            fbdataout%caddunit(je,jv) = fbdatain(1)%caddunit(je,jv)
+         END DO
+      END DO
+      DO jv = 1, fbdatain(1)%next
+         fbdataout%cextname(jv) = fbdatain(1)%cextname(jv)
+         fbdataout%cextlong(jv) = fbdatain(1)%cextlong(jv)
+         fbdataout%cextunit(jv) = fbdatain(1)%cextunit(jv)
+      END DO
+      fbdataout%cdjuldref = fbdatain(1)%cdjuldref
+
+      ! Loop over total views
+
+      DO jo = 1, fbdataout%nobs
+
+         js = iset(iind(jo))
+         ji = inum(iind(jo))
+
+         ! Merge the header data
+
+         fbdataout%cdwmo(jo)  = fbdatain(js)%cdwmo(ji)
+         fbdataout%cdtyp(jo)  = fbdatain(js)%cdtyp(ji)
+         fbdataout%ioqc(jo)   = fbdatain(js)%ioqc(ji)
+         fbdataout%ipqc(jo)   = fbdatain(js)%ipqc(ji)
+         fbdataout%itqc(jo)   = fbdatain(js)%itqc(ji)
+         fbdataout%plam(jo)   = fbdatain(js)%plam(ji)
+         fbdataout%pphi(jo)   = fbdatain(js)%pphi(ji)
+         fbdataout%ptim(jo)   = fbdatain(js)%ptim(ji)
+         fbdataout%kindex(jo) = fbdatain(js)%kindex(ji)
+         DO jq = 1, fbdatain(js)%nqcf
+            fbdataout%ioqcf(jq,jo)  = fbdatain(js)%ioqcf(jq,ji)
+            fbdataout%ipqcf(jq,jo)  = fbdatain(js)%ipqcf(jq,ji)
+            fbdataout%itqcf(jq,jo)  = fbdatain(js)%itqcf(jq,ji)
+         END DO
+         DO jk = 1, fbdatain(js)%nlev
+            fbdataout%pdep(jk,jo)  = fbdatain(js)%pdep(jk,ji)
+            fbdataout%idqc(jk,jo)  = fbdatain(js)%idqc(jk,ji)
+            DO jq = 1, fbdatain(js)%nqcf
+               fbdataout%idqcf(jq,jk,jo) = fbdatain(js)%idqcf(jq,jk,ji)
+            END DO
+         END DO
+
+         ! Merge the variable data
+
+         DO jv = 1, fbdatain(js)%nvar
+            fbdataout%ivqc(jo,jv)  = fbdatain(js)%ivqc(ji,jv)
+            DO jq = 1, fbdatain(js)%nqcf
+               fbdataout%ivqcf(jq,jo,jv) = fbdatain(js)%ivqcf(jq,ji,jv)
+            END DO
+            DO jk = 1, fbdatain(js)%nlev
+               fbdataout%ivlqc(jk,jo,jv)  = fbdatain(js)%ivlqc(jk,ji,jv)
+               fbdataout%pob(jk,jo,jv)    = fbdatain(js)%pob(jk,ji,jv)
+               DO jq = 1, fbdatain(js)%nqcf
+                  fbdataout%ivlqcf(jq,jk,jo,jv) = &
+                     &                     fbdatain(js)%ivlqcf(jq,jk,ji,jv)
+               END DO
+            END DO
+         END DO
+
+         ! Merge grid information
+         
+         IF ( fbdatain(js)%lgrid ) THEN
+            DO jv = 1, fbdatain(js)%nvar
+               fbdataout%cgrid(jv) = fbdatain(js)%cgrid(jv)
+               fbdataout%iproc(jo,jv) = fbdatain(js)%iproc(ji,jv)
+               fbdataout%iobsi(jo,jv) = fbdatain(js)%iobsi(ji,jv)
+               fbdataout%iobsj(jo,jv) = fbdatain(js)%iobsj(ji,jv)
+               DO jk = 1, fbdatain(js)%nlev
+                  fbdataout%iobsk(jk,jo,jv)  = fbdatain(js)%iobsk(jk,ji,jv)
+               END DO
+            END DO
+         ENDIF
+
+         ! Merge additional information
+      
+         DO jv = 1, fbdatain(js)%nvar
+            DO je = 1, fbdatain(js)%nadd
+               DO jk = 1, fbdatain(js)%nlev
+                  fbdataout%padd(jk,jo,je,jv) = fbdatain(js)%padd(jk,ji,je,jv)
+               END DO
+            END DO
+         END DO
+         
+         ! Merge extra information
+         
+         DO je = 1, fbdatain(js)%next
+            DO jk = 1, fbdatain(js)%nlev
+               fbdataout%pext(jk,jo,je) = fbdatain(js)%pext(jk,ji,je)
+            END DO
+         END DO
+
+      END DO
+
+   END SUBROUTINE merge_obfbdata
+
+   SUBROUTINE write_obfbdata( cdfilename, fbdata )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE write_obfbdata  ***
+      !!
+      !! ** Purpose :   Write an obfbdata structure into a netCDF file.
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      CHARACTER(len=*) :: cdfilename ! Output filename
+      TYPE(obfbdata)   :: fbdata     ! obsfbdata structure
+      !! * Local variables
+      CHARACTER(LEN=14), PARAMETER :: cpname = 'write_obfbdata'
+      ! Dimension ids
+      INTEGER :: idfile
+      INTEGER :: idodim
+      INTEGER :: idldim
+      INTEGER :: idvdim
+      INTEGER :: idadim
+      INTEGER :: idedim
+      INTEGER :: idsndim
+      INTEGER :: idsgdim
+      INTEGER :: idswdim
+      INTEGER :: idstdim
+      INTEGER :: idjddim
+      INTEGER :: idqcdim
+      INTEGER :: idvard
+      INTEGER :: idaddd
+      INTEGER :: idextd
+      INTEGER :: idcdwmo
+      INTEGER :: idcdtyp
+      INTEGER :: idplam
+      INTEGER :: idpphi
+      INTEGER :: idpdep
+      INTEGER :: idptim
+      INTEGER :: idptimr
+      INTEGER :: idioqc         
+      INTEGER :: idioqcf         
+      INTEGER :: idipqc
+      INTEGER :: idipqcf
+      INTEGER :: iditqc
+      INTEGER :: iditqcf
+      INTEGER :: ididqc
+      INTEGER :: ididqcf
+      INTEGER :: idkindex
+      INTEGER, DIMENSION(fbdata%nvar) :: &
+         & idpob,    &
+         & idivqc,   &
+         & idivqcf,  &
+         & idivlqc,  &
+         & idivlqcf, &
+         & idiobsi,  &
+         & idiobsj,  &
+         & idiobsk,  &
+         & idcgrid
+      INTEGER, DIMENSION(fbdata%nadd,fbdata%nvar) :: idpadd
+      INTEGER, DIMENSION(fbdata%next) :: idpext
+      INTEGER, DIMENSION(1) :: incdim1
+      INTEGER, DIMENSION(2) :: incdim2
+      INTEGER, DIMENSION(3) :: incdim3
+      INTEGER, DIMENSION(4) :: incdim4
+
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: ioldfill
+      CHARACTER(len=nf90_max_name) :: &
+         & cdtmp
+      CHARACTER(len=16), PARAMETER :: &
+         & cdqcconv = 'q where q =[0,9]'
+      CHARACTER(len=24), PARAMETER :: &
+         & cdqcfconv = 'NEMOVAR flag conventions'
+      CHARACTER(len=ilenlong) :: &
+         & cdltmp
+
+      ! Open output filename
+
+      CALL chkerr( nf90_create( TRIM( cdfilename ), nf90_clobber, idfile ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_set_fill( idfile, nf90_nofill, ioldfill ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_put_att( idfile, nf90_global, 'title', &
+         &                       'NEMO observation operator output' ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_put_att( idfile, nf90_global, 'Convention', &
+         &                       'NEMO unified observation operator output' ),&
+         &         cpname,__LINE__ )
+
+      ! Create the dimensions
+
+      CALL chkerr( nf90_def_dim( idfile, 'N_OBS'  , fbdata%nobs, idodim ),  &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_LEVELS', fbdata%nlev, idldim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_VARS', fbdata%nvar, idvdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'N_QCF', fbdata%nqcf, idqcdim ),&
+         &         cpname,__LINE__ )
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'N_ENTRIES', fbdata%nadd, idadim ), &
+            &         cpname,__LINE__ )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'N_EXTRA', fbdata%next, idedim ), &
+            &         cpname,__LINE__ )
+      ENDIF
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGNAM', ilenname, idsndim ), &
+         &         cpname,__LINE__ )
+      IF (fbdata%lgrid) THEN
+         CALL chkerr( nf90_def_dim( idfile, 'STRINGGRID', ilengrid, idsgdim ),&
+            &         cpname,__LINE__ )
+      ENDIF
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGWMO', ilenwmo, idswdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGTYP', ilentyp, idstdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_def_dim( idfile, 'STRINGJULD', ilenjuld, idjddim ), &
+         &         cpname,__LINE__ )
+      
+      ! Define netCDF variables for header information
+      
+      incdim2(1) = idsndim
+      incdim2(2) = idvdim
+
+      CALL chkerr( nf90_def_var( idfile, 'VARIABLES', nf90_char, incdim2, &
+         &                       idvard ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata( idfile, idvard, &
+         &                     'List of variables in feedback files' )
+      
+      IF ( fbdata%nadd > 0 ) THEN
+         incdim2(1) = idsndim
+         incdim2(2) = idadim
+         CALL chkerr( nf90_def_var( idfile, 'ENTRIES', nf90_char, incdim2, &
+            &                       idaddd ), cpname, __LINE__ )
+         CALL putvaratt_obfbdata( idfile, idaddd,  &
+            &                     'List of additional entries for each '// &
+            &                     'variable in feedback files' )
+      ENDIF
+   
+      IF ( fbdata%next > 0 ) THEN
+         incdim2(1) = idsndim
+         incdim2(2) = idedim
+         CALL chkerr( nf90_def_var( idfile, 'EXTRA', nf90_char, incdim2, &
+            &                       idextd ), cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idextd, &
+            &                      'List of extra variables' )
+      ENDIF
+
+      incdim2(1) = idswdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'STATION_IDENTIFIER', &
+         &                       nf90_char, incdim2, &
+         &                       idcdwmo ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idcdwmo, &
+         &                      'Station identifier' )
+      incdim2(1) = idstdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'STATION_TYPE', &
+         &                       nf90_char, incdim2, &
+         &                       idcdtyp ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idcdtyp, &
+         &                      'Code instrument type' )
+      incdim1(1) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'LONGITUDE', &
+         &                       nf90_double, incdim1, &
+         &                       idplam ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idplam, &
+         &                      'Longitude', cdunits = 'degrees_east', &
+         &                      rfillvalue = fbrmdi )
+      CALL chkerr( nf90_def_var( idfile, 'LATITUDE', &
+         &                       nf90_double, incdim1, &
+         &                       idpphi ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idpphi, &
+         &                      'Latitude', cdunits = 'degrees_north', &
+         &                      rfillvalue = fbrmdi )
+      incdim2(1) = idldim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH', &
+         &                       nf90_double, incdim2, &
+         &                       idpdep ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idpdep, &
+         &                      'Depth', cdunits = 'metre', &
+         &                      rfillvalue = fbrmdi )
+      incdim3(1) = idqcdim
+      incdim3(2) = idldim
+      incdim3(3) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH_QC', &
+         &                       nf90_int, incdim2, &
+         &                       ididqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, ididqc, &
+         &                      'Quality on depth',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'DEPTH_QC_FLAGS', &
+         &                       nf90_int, incdim3, &
+         &                       ididqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, ididqcf, &
+         &                      'Quality flags on depth',  &
+         &                      conventions = cdqcfconv )
+      CALL chkerr( nf90_def_var( idfile, 'JULD', &
+         &                       nf90_double, incdim1, &
+         &                       idptim ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idptim, &
+         &                      'Julian day', &
+         &                      cdunits = 'days since JULD_REFERENCE', &
+         &                      conventions = 'relative julian days with '// &
+         &                                 'decimal part (as parts of day)', &
+         &                      rfillvalue = fbrmdi )
+      incdim1(1) = idjddim
+      CALL chkerr( nf90_def_var( idfile, 'JULD_REFERENCE', &
+         &                       nf90_char, incdim1, &
+         &                       idptimr ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idptimr, &
+         &                      'Date of reference for julian days ', &
+         &                      conventions = 'YYYYMMDDHHMMSS' )
+      incdim1(1) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'OBSERVATION_QC', &
+         &                       nf90_int, incdim1, &
+         &                       idioqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idioqc, &
+         &                      'Quality on observation',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      incdim2(1) = idqcdim
+      incdim2(2) = idodim
+      CALL chkerr( nf90_def_var( idfile, 'OBSERVATION_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       idioqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idioqcf, &
+         &                      'Quality flags on observation',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'POSITION_QC', &
+         &                       nf90_int, incdim1, &
+         &                       idipqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idipqc, &
+         &                      'Quality on position (latitude and longitude)',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'POSITION_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       idipqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idipqcf, &
+         &                      'Quality flags on position',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'JULD_QC', &
+         &                       nf90_int, incdim1, &
+         &                       iditqc ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, iditqc, &
+         &                      'Quality on date and time',  &
+         &                      conventions = cdqcconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'JULD_QC_FLAGS', &
+         &                       nf90_int, incdim2, &
+         &                       iditqcf ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, iditqcf, &
+         &                      'Quality flags on date and time',  &
+         &                      conventions = cdqcfconv, &
+         &                      ifillvalue = 0 )
+      CALL chkerr( nf90_def_var( idfile, 'ORIGINAL_FILE_INDEX', &
+         &                       nf90_int, incdim1, &
+         &                       idkindex ), cpname, __LINE__ )
+      CALL putvaratt_obfbdata(  idfile, idkindex, &
+         &                      'Index in original data file',  &
+         &                      ifillvalue = fbimdi )
+
+      ! Define netCDF variables for individual variables
+
+      DO jv = 1, fbdata%nvar
+
+         incdim1(1) = idodim
+         incdim2(1) = idldim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+            &                       incdim2, idpob(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idpob(jv), &
+            &                      fbdata%coblong(jv),  &
+            &                      cdunits =  fbdata%cobunit(jv), &
+            &                      rfillvalue = fbrmdi )
+
+         IF ( fbdata%nadd > 0 ) THEN
+            DO je = 1, fbdata%nadd
+               WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                  &                TRIM(fbdata%caddname(je))
+               CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+                  &                       incdim2, idpadd(je,jv) ), &
+                  &         cpname, __LINE__ )
+               CALL putvaratt_obfbdata(  idfile, idpadd(je,jv), &
+                  &                      fbdata%caddlong(je,jv), &
+                  &                      cdunits =  fbdata%caddunit(je,jv), &
+                  &                      rfillvalue = fbrmdi )
+            END DO
+         ENDIF
+
+         cdltmp = fbdata%coblong(jv)
+         IF (( cdltmp(1:1) >= 'A' ).AND.( cdltmp(1:1) <= 'Z' )) &
+            & cdltmp(1:1) = ACHAR(IACHAR(cdltmp(1:1)) + 32)
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim1, idivqc(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivqc(jv), &
+            &                      'Quality on '//cdltmp,  &
+            &                      conventions = cdqcconv, &
+            &                      ifillvalue = 0 )
+         incdim2(1) = idqcdim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC_FLAGS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim2, idivqcf(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivqcf(jv), &
+            &                      'Quality flags on '//cdltmp,  &
+            &                      conventions = cdqcfconv, &
+            &                      ifillvalue = 0 )
+         incdim2(1) = idldim
+         incdim2(2) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim2, idivlqc(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivlqc(jv), &
+            &                      'Quality for each level on '//cdltmp,  &
+            &                      conventions = cdqcconv, &
+            &                      ifillvalue = 0 )
+         incdim3(1) = idqcdim
+         incdim3(2) = idldim
+         incdim3(3) = idodim
+         WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC_FLAGS'
+         CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+            &                       incdim3, idivlqcf(jv) ), &
+            &         cpname, __LINE__ )
+         CALL putvaratt_obfbdata(  idfile, idivlqcf(jv), &
+            &                      'Quality flags for each level on '//&
+            &                      cdltmp,  &
+            &                      conventions = cdqcfconv, &
+            &                      ifillvalue = 0 )
+
+         IF (fbdata%lgrid) THEN
+            incdim2(1) = idldim
+            incdim2(2) = idodim
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSI'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim1, idiobsi(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsi(jv), &
+               &                      'ORCA grid search I coordinate')
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSJ'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim1, idiobsj(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsj(jv), &
+               &                      'ORCA grid search J coordinate')
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSK'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_int, &
+               &                       incdim2, idiobsk(jv) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idiobsk(jv), &
+               &                      'ORCA grid search K coordinate')
+            incdim1(1) = idsgdim
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_GRID'
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_char, incdim1, &
+               &                       idcgrid(jv) ), cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idcgrid(jv), &
+               &                      'ORCA grid search grid (T,U,V)')
+         ENDIF
+
+      END DO
+
+      IF ( fbdata%next > 0 ) THEN
+         DO je = 1, fbdata%next
+            incdim2(1) = idldim
+            incdim2(2) = idodim
+            WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+            CALL chkerr( nf90_def_var( idfile, cdtmp, nf90_float, &
+               &                       incdim2, idpext(je) ), &
+               &         cpname, __LINE__ )
+            CALL putvaratt_obfbdata(  idfile, idpext(je), &
+               &                      fbdata%cextlong(je),  &
+               &                      cdunits =  fbdata%cextunit(je), &
+               &                      rfillvalue = fbrmdi )
+         END DO
+      ENDIF
+      
+      ! Stop definitions
+
+      CALL chkerr( nf90_enddef( idfile ), cpname, __LINE__ )
+      
+      ! Write the variables
+      
+      CALL chkerr( nf90_put_var( idfile, idvard, fbdata%cname ), &
+         &         cpname, __LINE__ )
+      
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_put_var( idfile, idaddd, fbdata%caddname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+      
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_put_var( idfile, idextd, fbdata%cextname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+
+      CALL chkerr( nf90_put_var( idfile, idptimr, fbdata%cdjuldref ), &
+         &         cpname, __LINE__ )
+
+      ! Only write the data if observation is available
+      
+      IF ( fbdata%nobs > 0 ) THEN
+
+         CALL chkerr( nf90_put_var( idfile, idcdwmo, fbdata%cdwmo ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idcdtyp, fbdata%cdtyp ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idplam, fbdata%plam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idpphi, fbdata%pphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idpdep, fbdata%pdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idptim, fbdata%ptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idioqc, fbdata%ioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idioqcf, fbdata%ioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idipqc, fbdata%ipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idipqcf, fbdata%ipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, iditqc, fbdata%itqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, iditqcf, fbdata%itqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, ididqc, fbdata%idqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, ididqcf, fbdata%idqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_put_var( idfile, idkindex, fbdata%kindex ), &
+            &         cpname, __LINE__ )
+
+         DO jv = 1, fbdata%nvar
+            CALL chkerr( nf90_put_var( idfile, idpob(jv), fbdata%pob(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  CALL chkerr( nf90_put_var( idfile, idpadd(je,jv), &
+                     &                       fbdata%padd(:,:,je,jv) ), &
+                     &         cpname, __LINE__ )
+               END DO
+            ENDIF
+            CALL chkerr( nf90_put_var( idfile, idivqc(jv), &
+               &                       fbdata%ivqc(:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivqcf(jv), &
+               &                       fbdata%ivqcf(:,:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivlqc(jv), &
+               &                       fbdata%ivlqc(:,:,jv) ),&
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_put_var( idfile, idivlqcf(jv), &
+               &                       fbdata%ivlqcf(:,:,:,jv) ),&
+               &         cpname, __LINE__ )
+            IF (fbdata%lgrid) THEN
+               CALL chkerr( nf90_put_var( idfile, idiobsi(jv), &
+                  &                       fbdata%iobsi(:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idiobsj(jv), &
+                  &                       fbdata%iobsj(:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idiobsk(jv), &
+                  &                       fbdata%iobsk(:,:,jv) ),&
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_put_var( idfile, idcgrid(jv), &
+                  &                       fbdata%cgrid(jv) ), &
+                  &         cpname, __LINE__ )
+            ENDIF
+         END DO
+
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               CALL chkerr( nf90_put_var( idfile, idpext(je), &
+                  &                       fbdata%pext(:,:,je) ), &
+                  &         cpname, __LINE__ )
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Close the file
+
+      CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+
+      
+   END SUBROUTINE write_obfbdata
+
+   SUBROUTINE putvaratt_obfbdata( idfile, idvar, cdlongname, cdunits, &
+      &                           conventions, cfillvalue, &
+      &                           ifillvalue, rfillvalue )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE putvaratt_obfbdata  ***
+      !!
+      !! ** Purpose :   Write netcdf attributes for variable
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER :: idfile                    ! File netcdf id.
+      INTEGER :: idvar                     ! Variable netcdf id.
+      CHARACTER(len=*) :: cdlongname       ! Long name for variable
+      CHARACTER(len=*), OPTIONAL :: cdunits       ! Units for variable
+      CHARACTER(len=*), OPTIONAL :: cfillvalue    ! Fill value for character variables
+      INTEGER, OPTIONAL :: ifillvalue             ! Fill value for integer variables
+      REAL(kind=fbsp), OPTIONAL :: rfillvalue     ! Fill value for real variables
+      CHARACTER(len=*), OPTIONAL :: conventions   ! Conventions for variable
+      !! * Local variables
+      CHARACTER(LEN=18), PARAMETER :: &
+         & cpname = 'putvaratt_obfbdata'
+
+      CALL chkerr( nf90_put_att( idfile, idvar, 'long_name', &
+         &                       TRIM(cdlongname) ), &
+         &                       cpname, __LINE__ )
+      
+      IF ( PRESENT(cdunits) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, 'units', &
+            &                       TRIM(cdunits) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(conventions) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, 'Conventions', &
+            &                       TRIM(conventions) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(cfillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       TRIM(cfillvalue) ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(ifillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       ifillvalue ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+      IF ( PRESENT(rfillvalue) ) THEN
+
+         CALL chkerr( nf90_put_att( idfile, idvar, '_Fillvalue', &
+            &                       rfillvalue ), &
+            &                       cpname, __LINE__ )
+
+      ENDIF
+
+   END SUBROUTINE putvaratt_obfbdata
+
+   SUBROUTINE read_obfbdata( cdfilename, fbdata, ldgrid )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE read_obfbdata  ***
+      !!
+      !! ** Purpose :   Read an obfbdata structure from a netCDF file.
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      CHARACTER(len=*) :: cdfilename  ! Input filename
+      TYPE(obfbdata)   :: fbdata      ! obsfbdata structure
+      LOGICAL, OPTIONAL :: ldgrid     ! Allow forcing of grid info
+      !! * Local variables
+      CHARACTER(LEN=14), PARAMETER :: cpname = 'read_obfbdata'
+      INTEGER :: idfile
+      INTEGER :: idodim
+      INTEGER :: idldim
+      INTEGER :: idvdim
+      INTEGER :: idadim
+      INTEGER :: idedim
+      INTEGER :: idgdim
+      INTEGER :: idvard
+      INTEGER :: idaddd
+      INTEGER :: idextd
+      INTEGER :: idcdwmo
+      INTEGER :: idcdtyp
+      INTEGER :: idplam
+      INTEGER :: idpphi
+      INTEGER :: idpdep
+      INTEGER :: idptim
+      INTEGER :: idptimr
+      INTEGER :: idioqc        
+      INTEGER :: idioqcf
+      INTEGER :: idipqc
+      INTEGER :: idipqcf
+      INTEGER :: ididqc
+      INTEGER :: ididqcf
+      INTEGER :: iditqc
+      INTEGER :: iditqcf
+      INTEGER :: idkindex
+      INTEGER, DIMENSION(:), ALLOCATABLE :: &
+         & idpob,    &
+         & idivqc,   &
+         & idivqcf,  &
+         & idivlqc,  &
+         & idivlqcf, &
+         & idiobsi,  &
+         & idiobsj,  &
+         & idiobsk,  &
+         & idcgrid,  &
+         & idpext
+      INTEGER, DIMENSION(:,:), ALLOCATABLE :: &
+         & idpadd
+      INTEGER :: jv
+      INTEGER :: je
+      INTEGER :: nvar
+      INTEGER :: nobs
+      INTEGER :: nlev
+      INTEGER :: nadd
+      INTEGER :: next
+      LOGICAL :: lgrid
+      CHARACTER(len=NF90_MAX_NAME) :: cdtmp
+
+      ! Check allocation status and deallocate previous allocated structures
+
+      IF ( fbdata%lalloc ) THEN
+         CALL dealloc_obfbdata( fbdata )
+      ENDIF
+
+      ! Open input filename
+
+      CALL chkerr( nf90_open( TRIM( cdfilename ), nf90_nowrite, idfile ), &
+         &         cpname, __LINE__ )
+
+      ! Get input dimensions
+
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_OBS'  , idodim ),  &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idodim, len=nobs ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_LEVELS', idldim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idldim, len=nlev ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inq_dimid( idfile, 'N_VARS', idvdim ), &
+         &         cpname,__LINE__ )
+      CALL chkerr( nf90_inquire_dimension( idfile, idvdim, len=nvar ), &
+         &         cpname,__LINE__ )
+      IF ( nf90_inq_dimid( idfile, 'N_ENTRIES',  idadim ) == 0 ) THEN
+         CALL chkerr( nf90_inquire_dimension( idfile, idadim, len=nadd ), &
+            &         cpname,__LINE__ )
+      ELSE
+         nadd = 0
+      ENDIF
+      IF ( nf90_inq_dimid( idfile, 'N_EXTRA',  idedim ) == 0 ) THEN
+         CALL chkerr( nf90_inquire_dimension( idfile, idedim, len=next ), &
+            &         cpname,__LINE__ )
+      ELSE
+         next = 0
+      ENDIF
+      !
+      ! Check if this input file  contains grid search informations
+      !
+      lgrid = ( nf90_inq_dimid( idfile, 'STRINGGRID',  idgdim ) == 0 )
+
+      ! Allocate data structure
+
+      IF ( PRESENT(ldgrid) ) THEN
+         CALL alloc_obfbdata( fbdata, nvar, nobs, nlev, nadd, next, &
+            & lgrid.OR.ldgrid )
+      ELSE
+         CALL alloc_obfbdata( fbdata, nvar, nobs, nlev, nadd, next, &
+            & lgrid )
+      ENDIF
+
+      ! Allocate netcdf identifiers
+
+      ALLOCATE( &
+         & idpob(fbdata%nvar),    &
+         & idivqc(fbdata%nvar),   &
+         & idivqcf(fbdata%nvar),  &
+         & idivlqc(fbdata%nvar),  &
+         & idivlqcf(fbdata%nvar), &
+         & idiobsi(fbdata%nvar),  &
+         & idiobsj(fbdata%nvar),  &
+         & idiobsk(fbdata%nvar),  &
+         & idcgrid(fbdata%nvar)   &
+         & )
+      IF ( fbdata%nadd > 0 ) THEN
+         ALLOCATE( &
+            & idpadd(fbdata%nadd,fbdata%nvar) &
+            & )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         ALLOCATE( &
+            & idpext(fbdata%next) &
+            & )
+      ENDIF
+
+      ! Read variables for header information
+
+      CALL chkerr( nf90_inq_varid( idfile, 'VARIABLES',idvard ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_get_var( idfile, idvard, fbdata%cname ), &
+         &         cpname, __LINE__ )
+      IF ( fbdata%nadd > 0 ) THEN
+         CALL chkerr( nf90_inq_varid( idfile, 'ENTRIES', idaddd ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idaddd, fbdata%caddname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+      IF ( fbdata%next > 0 ) THEN
+         CALL chkerr( nf90_inq_varid( idfile, 'EXTRA', idextd ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idextd, fbdata%cextname ), &
+            &         cpname, __LINE__ )
+      ENDIF
+
+      CALL chkerr( nf90_inq_varid( idfile, 'JULD_REFERENCE', idptimr ), &
+         &         cpname, __LINE__ )
+      CALL chkerr( nf90_get_var( idfile, idptimr, fbdata%cdjuldref ), &
+         &         cpname, __LINE__ )
+
+      IF  ( fbdata%nobs > 0 ) THEN
+         
+         CALL chkerr( nf90_inq_varid( idfile, 'STATION_IDENTIFIER', idcdwmo ),&
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idcdwmo, fbdata%cdwmo ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'STATION_TYPE', idcdtyp ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idcdtyp, fbdata%cdtyp), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'LONGITUDE', idplam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idplam, fbdata%plam ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'LATITUDE', idpphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idpphi, fbdata%pphi ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH', idpdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idpdep, fbdata%pdep ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD', idptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idptim, fbdata%ptim ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'OBSERVATION_QC', idioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idioqc, fbdata%ioqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'OBSERVATION_QC_FLAGS', idioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idioqcf, fbdata%ioqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'POSITION_QC', idipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idipqc, fbdata%ipqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'POSITION_QC_FLAGS', idipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idipqcf, fbdata%ipqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH_QC', ididqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, ididqc, fbdata%idqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'DEPTH_QC_FLAGS', ididqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, ididqcf, fbdata%idqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD_QC', iditqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, iditqc, fbdata%itqc ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'JULD_QC_FLAGS', iditqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, iditqcf, fbdata%itqcf ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_inq_varid( idfile, 'ORIGINAL_FILE_INDEX', idkindex ), &
+            &         cpname, __LINE__ )
+         CALL chkerr( nf90_get_var( idfile, idkindex, fbdata%kindex ), &
+            &         cpname, __LINE__ )
+         
+         ! Read netCDF variables for individual variables
+         
+         DO jv = 1, fbdata%nvar
+            
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpob(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idpob(jv), &
+               &                       fbdata%pob(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            CALL getvaratt_obfbdata( idfile, idpob(jv), &
+               &                     fbdata%coblong(jv), &
+               &                     fbdata%cobunit(jv) )
+            
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                     &                TRIM(fbdata%caddname(je))
+                  CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpadd(je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL chkerr( nf90_get_var( idfile, idpadd(je,jv), &
+                     &                       fbdata%padd(:,:,je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL getvaratt_obfbdata( idfile, idpadd(je,jv), &
+                     &                     fbdata%caddlong(je,jv), &
+                     &                     fbdata%caddunit(je,jv) )
+               END DO
+            ENDIF
+            
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivqc(jv) ), &
+            &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivqc(jv), &
+               &                       fbdata%ivqc(:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_QC_FLAGS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivqcf(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivqcf(jv), &
+               &                       fbdata%ivqcf(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivlqc(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivlqc(jv), &
+               &                       fbdata%ivlqc(:,:,jv) ), &
+               &         cpname, __LINE__ )
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_LEVEL_QC_FLAGS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idivlqcf(jv) ), &
+               &         cpname, __LINE__ )
+            CALL chkerr( nf90_get_var( idfile, idivlqcf(jv), &
+               &                       fbdata%ivlqcf(:,:,:,jv) ), &
+               &         cpname, __LINE__ )
+            IF ( lgrid ) THEN
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSI'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsi(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsi(jv), &
+                  &                       fbdata%iobsi(:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSJ'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsj(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsj(jv), &
+                  &                       fbdata%iobsj(:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_IOBSK'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idiobsk(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idiobsk(jv), &
+                  &                       fbdata%iobsk(:,:,jv) ), &
+                  &         cpname, __LINE__ )
+               WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_GRID'
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idcgrid(jv) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idcgrid(jv), &
+                  &                       fbdata%cgrid(jv) ), &
+                  &         cpname, __LINE__ )
+            ENDIF
+            
+         END DO
+         
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpext(je) ), &
+                  &         cpname, __LINE__ )
+               CALL chkerr( nf90_get_var( idfile, idpext(je), &
+                  &                       fbdata%pext(:,:,je) ), &
+                  &         cpname, __LINE__ )
+               CALL getvaratt_obfbdata( idfile, idpext(je), &
+                  &                     fbdata%cextlong(je), &
+                  &                     fbdata%cextunit(je) )
+            END DO
+         ENDIF
+
+      ELSE ! if no observations only get attributes
+
+         DO jv = 1, fbdata%nvar            
+
+            WRITE(cdtmp,'(2A)') TRIM(fbdata%cname(jv)),'_OBS'
+            CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpob(jv) ), &
+               &         cpname, __LINE__ )
+            CALL getvaratt_obfbdata( idfile, idpob(jv), &
+               &                     fbdata%coblong(jv), &
+               &                     fbdata%cobunit(jv) )
+            
+            IF ( fbdata%nadd > 0 ) THEN
+               DO je = 1, fbdata%nadd
+                  WRITE(cdtmp,'(3A)') TRIM(fbdata%cname(jv)),'_',&
+                     &                TRIM(fbdata%caddname(je))
+                  CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpadd(je,jv) ), &
+                     &         cpname, __LINE__ )
+                  CALL getvaratt_obfbdata( idfile, idpadd(je,jv), &
+                     &                     fbdata%caddlong(je,jv), &
+                     &                     fbdata%caddunit(je,jv) )
+               END DO
+            ENDIF
+            
+         END DO
+         
+         IF ( fbdata%next > 0 ) THEN
+            DO je = 1, fbdata%next
+               WRITE(cdtmp,'(A)') TRIM(fbdata%cextname(je))
+               CALL chkerr( nf90_inq_varid( idfile, cdtmp, idpext(je) ), &
+                  &         cpname, __LINE__ )
+               CALL getvaratt_obfbdata( idfile, idpext(je), &
+                  &                     fbdata%cextlong(je), &
+                  &                     fbdata%cextunit(je) )
+            END DO
+         ENDIF
+
+      ENDIF
+
+      ! Close the file
+
+      CALL chkerr( nf90_close( idfile ), cpname, __LINE__ )
+
+   END SUBROUTINE read_obfbdata
+
+   SUBROUTINE getvaratt_obfbdata( idfile, idvar, cdlongname, cdunits )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE putvaratt_obfbdata  ***
+      !!
+      !! ** Purpose :   Read netcdf attributes for variable
+      !!
+      !! ** Method  :   
+      !!
+      !! ** Action  : 
+      !!
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER :: idfile      ! File netcdf id.
+      INTEGER :: idvar       ! Variable netcdf id.
+      CHARACTER(len=*) :: cdlongname  ! Long name for variable
+      CHARACTER(len=*) :: cdunits     ! Units for variable
+      !! * Local variables
+      CHARACTER(LEN=18), PARAMETER :: cpname = 'getvaratt_obfbdata'
+
+      CALL chkerr( nf90_get_att( idfile, idvar, 'long_name', &
+         &                       cdlongname ), &
+         &                       cpname, __LINE__ )
+
+      CALL chkerr( nf90_get_att( idfile, idvar, 'units', &
+         &                       cdunits ), &
+         &                       cpname, __LINE__ )
+
+   END SUBROUTINE getvaratt_obfbdata
+
+END MODULE obs_fbm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao.nml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao.nml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao.nml	(revision 14097)
@@ -0,0 +1,10 @@
+!----------------------------------------------------------------------
+!       namsao Stand Alone Observation operator namelist
+!----------------------------------------------------------------------
+!   sao_files     specifies the files containing the model counterpart
+!   nn_sao_idx    specifies the index within the model file
+!   nn_sao_freq   specifies the number of timesteps between file reads
+&namsao
+   sao_files = 'fcst.0.nc'
+   nn_sao_idx = 1
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_data.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_data.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_data.F90	(revision 14097)
@@ -0,0 +1,81 @@
+MODULE sao_data
+   !!======================================================================
+   !!                       ***  MODULE sao_data  ***
+   !!======================================================================
+   !! History :  3.6  ! 2015-12  (A. Ryan)  Original code
+   !!----------------------------------------------------------------------
+   USE par_kind, ONLY: lc
+   USE lib_mpp         ! distributed memory computing
+   USE in_out_manager
+
+   IMPLICIT NONE
+
+   INTEGER, PARAMETER :: MaxNumFiles = 1000
+
+   !! Stand Alone Observation operator settings
+   CHARACTER(len=lc) ::   sao_files(MaxNumFiles)   !: model files
+   INTEGER           ::   n_files                  !: number of files
+   INTEGER           :: nn_sao_idx(MaxNumFiles)    !: time_counter indices
+   INTEGER           :: nn_sao_freq                !: read frequency in time steps
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sao_data_init()
+      !!----------------------------------------------------------------------
+      !!                    ***  SUBROUTINE sao_data_init ***
+      !!
+      !! ** Purpose : To read namelists and initialise offline_oper run.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   jf                   ! file dummy loop index
+      LOGICAL ::   lmask(MaxNumFiles)   ! Logical mask used for counting
+      INTEGER ::   ios
+      !!
+      NAMELIST/namsao/sao_files, nn_sao_idx, nn_sao_freq
+      !!----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sao_data_init : offline obs operator initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+
+      ! Standard offline obs_oper initialisation
+      n_files       =  0         ! number of files to cycle through
+      sao_files(:)  = ''         ! list of files to read in
+      nn_sao_idx(:) =  0         ! list of indices inside each file
+      nn_sao_freq   = -1         ! input frequency in time steps
+
+      ! Standard offline obs_oper settings
+      REWIND( numnam_ref )              ! Namelist namctl in reference namelist : Control prints & Benchmark
+      READ  ( numnam_ref, namsao, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsao in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namctl in confguration namelist : Control prints & Benchmark
+      READ  ( numnam_cfg, namsao, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsao in configuration namelist' )
+     
+      lmask(:) = .FALSE.               ! count input files
+      WHERE( sao_files(:) /= '' )   lmask(:) = .TRUE.
+      n_files = COUNT(lmask)
+      !
+      IF(nn_sao_freq == -1) THEN      ! Initialise sub obs window frequency
+         nn_sao_freq = nitend - nit000 + 1      ! Run length
+      ENDIF
+      !
+      IF(lwp) THEN                     ! Print summary of settings
+         WRITE(numout,*) '   Namelist namsao : set stand alone obs_oper parameters'
+         DO jf = 1, n_files
+            WRITE(numout,'(1X,2A)') '      Input forecast file name         forecastfile  = ', TRIM(sao_files(jf))
+            WRITE(numout,*)         '      Input forecast file index        forecastindex = ', nn_sao_idx(jf)
+         END DO
+      END IF
+      !
+   END SUBROUTINE sao_data_init
+
+   !!======================================================================
+END MODULE sao_data
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_intp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_intp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_intp.F90	(revision 14097)
@@ -0,0 +1,58 @@
+MODULE sao_intp
+   !!======================================================================
+   !!                    ***  MODULE sao_intp ***
+   !! ** Purpose : Run NEMO observation operator in offline mode
+   !!======================================================================
+   !! History :  3.6  ! 2015-12  (A. Ryan)  Original code
+   !!----------------------------------------------------------------------
+   !        ! NEMO modules
+   USE in_out_manager
+   USE diaobs
+   !        ! Stand Alone Observation operator modules
+   USE sao_read
+   USE sao_data
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sao_interp
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sao_interp
+      !!----------------------------------------------------------------------
+      !!                    ***  SUBROUTINE sao_interp ***
+      !!
+      !! ** Purpose : To interpolate the model as if it were running online.
+      !!
+      !! ** Method : 1. Populate model counterparts
+      !!             2. Call dia_obs at appropriate time steps
+      !!----------------------------------------------------------------------
+      INTEGER ::   istp    ! time step index
+      INTEGER ::   ifile   ! file index
+      !!----------------------------------------------------------------------
+      istp = nit000 - 1
+      nstop = 0
+      ifile = 1
+      CALL sao_rea_dri(ifile)
+      !
+      DO WHILE ( istp <= nitend .AND. nstop == 0 )
+         IF (ifile <= n_files + 1) THEN
+            IF ( MOD(istp, nn_sao_freq) == nit000 ) THEN
+               CALL sao_rea_dri(ifile)
+               ifile = ifile + 1
+            ENDIF
+            CALL dia_obs(istp)
+         ENDIF
+         istp = istp + 1
+      END DO
+      !
+   END SUBROUTINE sao_interp
+
+   !!======================================================================
+END MODULE sao_intp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_read.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_read.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAO/sao_read.F90	(revision 14097)
@@ -0,0 +1,173 @@
+MODULE sao_read
+   !!======================================================================
+   !!                      ***  MODULE sao_read  ***
+   !! Read routines : I/O for Stand Alone Observation operator
+   !!======================================================================
+   USE mppini
+   USE lib_mpp
+   USE in_out_manager
+   USE par_kind, ONLY: lc
+   USE netcdf
+   USE oce,     ONLY: tsn, sshn
+   USE dom_oce, ONLY: nlci, nlcj, nimpp, njmpp, tmask
+   USE par_oce, ONLY: jpi, jpj, jpk
+   !
+   USE obs_fbm, ONLY: fbimdi, fbrmdi, fbsp, fbdp
+   USE sao_data
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sao_rea_dri
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sao_rea_dri( kfile )
+      !!------------------------------------------------------------------------
+      !!             *** sao_rea_dri ***
+      !!
+      !! Purpose : To choose appropriate read method
+      !! Method  :
+      !!
+      !! Author  : A. Ryan Oct 2013
+      !!
+      !!------------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kfile         ! File number
+      !
+      CHARACTER(len=lc)   ::   cdfilename    ! File name
+      INTEGER ::   kindex        ! File index to read
+      !!------------------------------------------------------------------------
+      !
+      cdfilename = TRIM( sao_files(kfile) )
+      kindex = nn_sao_idx(kfile)
+      CALL sao_read_file( TRIM( cdfilename ), kindex )
+      !
+   END SUBROUTINE sao_rea_dri
+
+
+   SUBROUTINE sao_read_file( filename, ifcst )
+      !!------------------------------------------------------------------------
+      !!                         ***  sao_read_file  ***
+      !!
+      !! Purpose : To fill tn and sn with dailymean field from netcdf files
+      !! Method  : Use subdomain indices to create start and count matrices
+      !!           for netcdf read.
+      !!
+      !! Author  : A. Ryan Oct 2010
+      !!------------------------------------------------------------------------
+      INTEGER,          INTENT(in) ::   ifcst
+      CHARACTER(len=*), INTENT(in) ::   filename
+      INTEGER                      ::   ncid, varid, istat, ntimes
+      INTEGER                      ::   tdim, xdim, ydim, zdim
+      INTEGER                      ::   ii, ij, ik
+      INTEGER, DIMENSION(4)        ::   start_n, count_n
+      INTEGER, DIMENSION(3)        ::   start_s, count_s
+      REAL(fbdp)                   ::   fill_val
+      REAL(fbdp), DIMENSION(:,:,:), ALLOCATABLE ::   temp_tn, temp_sn
+      REAL(fbdp), DIMENSION(:,:)  , ALLOCATABLE ::   temp_sshn
+
+      ! DEBUG
+      INTEGER ::   istage
+      !!------------------------------------------------------------------------
+
+      IF (TRIM(filename) == 'nofile') THEN
+         tsn (:,:,:,:) = fbrmdi
+         sshn(:,:)     = fbrmdi
+      ELSE
+         WRITE(numout,*) "Opening :", TRIM(filename)
+         ! Open Netcdf file to find dimension id
+         istat = nf90_open(path=TRIM(filename), mode=nf90_nowrite, ncid=ncid)
+         IF ( istat /= nf90_noerr ) THEN
+             WRITE(numout,*) "WARNING: Could not open ", trim(filename)
+             WRITE(numout,*) "ERROR: ", nf90_strerror(istat)
+         ENDIF
+         istat = nf90_inq_dimid(ncid,'x',xdim)
+         istat = nf90_inq_dimid(ncid,'y',ydim)
+         istat = nf90_inq_dimid(ncid,'deptht',zdim)
+         istat = nf90_inq_dimid(ncid,'time_counter',tdim)
+         istat = nf90_inquire_dimension(ncid, tdim, len=ntimes)
+         IF (ifcst .LE. ntimes) THEN
+            ! Allocate temporary temperature array
+            ALLOCATE(temp_tn(nlci,nlcj,jpk))
+            ALLOCATE(temp_sn(nlci,nlcj,jpk))
+            ALLOCATE(temp_sshn(nlci,nlcj))
+
+            ! Set temp_tn, temp_sn to 0.
+            temp_tn(:,:,:) = fbrmdi
+            temp_sn(:,:,:) = fbrmdi
+            temp_sshn(:,:) = fbrmdi
+
+            ! Create start and count arrays
+            start_n = (/ nimpp, njmpp, 1,   ifcst /)
+            count_n = (/ nlci,  nlcj,  jpk, 1     /)
+            start_s = (/ nimpp, njmpp, ifcst /)
+            count_s = (/ nlci,  nlcj,  1     /)
+
+            ! Read information into temporary arrays
+            ! retrieve varid and read in temperature
+            istat = nf90_inq_varid(ncid,'votemper',varid)
+            istat = nf90_get_att(ncid, varid, '_FillValue', fill_val)
+            istat = nf90_get_var(ncid, varid, temp_tn, start_n, count_n)
+            WHERE(temp_tn(:,:,:) == fill_val) temp_tn(:,:,:) = fbrmdi
+
+            ! retrieve varid and read in salinity
+            istat = nf90_inq_varid(ncid,'vosaline',varid)
+            istat = nf90_get_att(ncid, varid, '_FillValue', fill_val)
+            istat = nf90_get_var(ncid, varid, temp_sn, start_n, count_n)
+            WHERE(temp_sn(:,:,:) == fill_val) temp_sn(:,:,:) = fbrmdi
+
+            ! retrieve varid and read in SSH
+            istat = nf90_inq_varid(ncid,'sossheig',varid)
+            IF (istat /= nf90_noerr) THEN
+               ! Altimeter bias
+               istat = nf90_inq_varid(ncid,'altbias',varid)
+            END IF
+
+            istat = nf90_get_att(ncid, varid, '_FillValue', fill_val)
+            istat = nf90_get_var(ncid, varid, temp_sshn, start_s, count_s)
+            WHERE(temp_sshn(:,:) == fill_val) temp_sshn(:,:) = fbrmdi
+
+            ! Initialise tsn, sshn to fbrmdi
+            tsn(:,:,:,:) = fbrmdi
+            sshn(:,:) = fbrmdi
+
+            ! Mask out missing data index
+            tsn(1:nlci,1:nlcj,1:jpk,1) = temp_tn(:,:,:) * tmask(1:nlci,1:nlcj,1:jpk)
+            tsn(1:nlci,1:nlcj,1:jpk,2) = temp_sn(:,:,:) * tmask(1:nlci,1:nlcj,1:jpk)
+            sshn(1:nlci,1:nlcj)        = temp_sshn(:,:) * tmask(1:nlci,1:nlcj,1)
+
+            ! Remove halo from tmask, tsn, sshn to prevent double obs counting
+            IF (jpi > nlci) THEN
+                tmask(nlci+1:,:,:) = 0
+                tsn(nlci+1:,:,:,1) = 0
+                tsn(nlci+1:,:,:,2) = 0
+                sshn(nlci+1:,:) = 0
+            END IF
+            IF (jpj > nlcj) THEN
+                tmask(:,nlcj+1:,:) = 0
+                tsn(:,nlcj+1:,:,1) = 0
+                tsn(:,nlcj+1:,:,2) = 0
+                sshn(:,nlcj+1:) = 0
+            END IF
+
+            ! Deallocate arrays
+            DEALLOCATE(temp_tn, temp_sn, temp_sshn)
+         ELSE
+            ! Mark all as missing data
+            tsn(:,:,:,:) = fbrmdi
+            sshn(:,:) = fbrmdi
+         ENDIF
+         ! Close netcdf file
+         WRITE(numout,*) "Closing :", TRIM(filename)
+         istat = nf90_close(ncid)
+      END IF
+      !
+   END SUBROUTINE sao_read_file
+   
+   !!------------------------------------------------------------------------
+END MODULE sao_read
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/README.rst	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../doc/rst/source/coupling.rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/daymod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/daymod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/daymod.F90	(revision 14097)
@@ -0,0 +1,419 @@
+MODULE daymod
+   !!======================================================================
+   !!                       ***  MODULE  daymod  ***
+   !! Ocean :   management of the model calendar
+   !!=====================================================================
+   !! History :  OPA  ! 1994-09  (M. Pontaud M. Imbard)  Original code
+   !!                 ! 1997-03  (O. Marti)
+   !!                 ! 1997-05  (G. Madec)
+   !!                 ! 1997-08  (M. Imbard)
+   !!   NEMO     1.0  ! 2003-09  (G. Madec)  F90 + nyear, nmonth, nday
+   !!                 ! 2004-01  (A.M. Treguier) new calculation based on adatrj
+   !!                 ! 2006-08  (G. Madec)  surface module major update
+   !!                 ! 2015-11  (D. Lea) Allow non-zero initial time of day
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   day        : calendar
+   !!----------------------------------------------------------------------
+   !!                    ----------- WARNING -----------
+   !!                    -------------------------------
+   !!   sbcmod assume that the time step is dividing the number of second of 
+   !!   in a day, i.e. ===> MOD( rday, rdt ) == 0 
+   !!   except when user defined forcing is used (see sbcmod.F90)
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE ioipsl  , ONLY :   ymds2ju      ! for calendar
+   USE trc_oce , ONLY :   l_offline   ! offline flag
+   !
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE iom            ! I/O manager
+   USE timing         ! Timing
+   USE restart        ! restart
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   day        ! called by step.F90
+   PUBLIC   day_init   ! called by istate.F90
+   PUBLIC   day_mth    ! Needed by TAM
+
+   INTEGER, PUBLIC ::   nsecd, nsecd05, ndt, ndt05   !: (PUBLIC for TAM)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE day_init
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE day_init  ***
+      !!
+      !! ** Purpose :   Initialization of the calendar values to their values 1 time step before nit000
+      !!                because day will be called at the beginning of step
+      !!
+      !! ** Action  : - nyear        : current year
+      !!              - nmonth       : current month of the year nyear
+      !!              - nday         : current day of the month nmonth
+      !!              - nday_year    : current day of the year nyear
+      !!              - nsec_year    : current time step counted in second since 00h jan 1st of the current year
+      !!              - nsec_month   : current time step counted in second since 00h 1st day of the current month
+      !!              - nsec_day     : current time step counted in second since 00h of the current day
+      !!              - nsec1jan000  : second since Jan. 1st 00h of nit000 year and Jan. 1st 00h of the current year
+      !!              - nmonth_len, nyear_len, nmonth_half, nmonth_end through day_mth
+      !!----------------------------------------------------------------------
+      INTEGER  ::   inbday, idweek   ! local integers
+      REAL(wp) ::   zjul             ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      ! max number of seconds between each restart
+      IF( REAL( nitend - nit000 + 1 ) * rdt > REAL( HUGE( nsec1jan000 ) ) ) THEN
+         CALL ctl_stop( 'The number of seconds between each restart exceeds the integer 4 max value: 2^31-1. ',   &
+            &           'You must do a restart at higher frequency (or remove this stop and recompile the code in I8)' )
+      ENDIF
+      nsecd   = NINT( rday       )
+      nsecd05 = NINT( 0.5 * rday )
+      ndt     = NINT(       rdt  )
+      ndt05   = NINT( 0.5 * rdt  )
+
+      IF( .NOT. l_offline )   CALL day_rst( nit000, 'READ' )
+
+      ! set the calandar from ndastp (read in restart file and namelist)
+      nyear   =   ndastp / 10000
+      nmonth  = ( ndastp - (nyear * 10000) ) / 100
+      nday    =   ndastp - (nyear * 10000) - ( nmonth * 100 )
+
+      nhour   =   nn_time0 / 100
+      nminute = ( nn_time0 - nhour * 100 )
+
+      CALL ymds2ju( nyear, nmonth, nday, nhour*3600._wp+nminute*60._wp, fjulday )  
+      IF( ABS(fjulday - REAL(NINT(fjulday),wp)) < 0.1 / rday )   fjulday = REAL(NINT(fjulday),wp)   ! avoid truncation error
+      IF( nn_time0*3600 - ndt05 .lt. 0 ) fjulday = fjulday + 1.                    ! move back to the day at nit000 (and not at nit000 - 1)
+
+      nsec1jan000 = 0
+      CALL day_mth
+
+      IF ( nday == 0 ) THEN     !   for ex if ndastp = ndate0 - 1
+         nmonth = nmonth - 1
+         nday = nmonth_len(nmonth)
+      ENDIF
+      IF ( nmonth == 0 ) THEN   ! go at the end of previous year
+         nmonth = 12
+         nyear = nyear - 1
+         nsec1jan000 = nsec1jan000 - nsecd * nyear_len(0)
+         IF( nleapy == 1 )   CALL day_mth
+      ENDIF
+
+      ! day since january 1st
+      nday_year = nday + SUM( nmonth_len(1:nmonth - 1) )
+
+      !compute number of days between last monday and today
+      CALL ymds2ju( 1900, 01, 01, 0.0, zjul )  ! compute julian day value of 01.01.1900 (our reference that was a Monday)
+      inbday = FLOOR(fjulday - zjul)            ! compute nb day between  01.01.1900 and start of current day
+      idweek = MOD(inbday, 7)                  ! compute nb day between last monday and current day
+      IF (idweek .lt. 0) idweek=idweek+7       ! Avoid negative values for dates before 01.01.1900
+
+      ! number of seconds since the beginning of current year/month/week/day at the middle of the time-step
+      IF (nhour*3600+nminute*60-ndt05 .gt. 0) THEN
+         ! 1 timestep before current middle of first time step is still the same day
+         nsec_year  = (nday_year-1) * nsecd + nhour*3600+nminute*60 - ndt05 
+         nsec_month = (nday-1)      * nsecd + nhour*3600+nminute*60 - ndt05    
+      ELSE
+         ! 1 time step before the middle of the first time step is the previous day 
+         nsec_year  = nday_year * nsecd + nhour*3600+nminute*60 - ndt05 
+         nsec_month = nday      * nsecd + nhour*3600+nminute*60 - ndt05   
+      ENDIF
+      nsec_week  = idweek    * nsecd + nhour*3600+nminute*60 - ndt05
+      nsec_day   =             nhour*3600+nminute*60 - ndt05 
+      IF( nsec_day .lt. 0 ) nsec_day = nsec_day + nsecd
+      IF( nsec_week .lt. 0 ) nsec_week = nsec_week + nsecd*7
+
+      ! control print
+      IF(lwp) WRITE(numout,'(a,i6,a,i2,a,i2,a,i8,a,i8,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, '  &
+           &                   nsec_month:', nsec_month , '  nsec_year:' , nsec_year
+
+      ! Up to now, calendar parameters are related to the end of previous run (nit000-1)
+      ! call day to set the calendar parameters at the begining of the current simulaton. needed by iom_init
+      CALL day( nit000 )
+      IF( lwxios ) THEN
+        CALL iom_set_rstw_var_active('kt')
+        CALL iom_set_rstw_var_active('ndastp')
+        CALL iom_set_rstw_var_active('adatrj')
+        CALL iom_set_rstw_var_active('ntime')
+      ENDIF
+      !
+   END SUBROUTINE day_init
+
+
+   SUBROUTINE day_mth
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE day_init  ***
+      !!
+      !! ** Purpose :   calendar values related to the months
+      !!
+      !! ** Action  : - nmonth_len    : length in days of the months of the current year
+      !!              - nyear_len     : length in days of the previous/current year
+      !!              - nmonth_half   : second since the beginning of the year and the halft of the months
+      !!              - nmonth_end    : second since the beginning of the year and the end of the months
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jm               ! dummy loop indice
+      !!----------------------------------------------------------------------
+
+      ! length of the month of the current year (from nleapy, read in namelist)
+      IF ( nleapy < 2 ) THEN
+         nmonth_len(:) = (/ 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31 /)
+         nyear_len(:) = 365
+         IF ( nleapy == 1 ) THEN   ! we are using calandar with leap years
+            IF ( MOD(nyear-1, 4) == 0 .AND. ( MOD(nyear-1, 400) == 0 .OR. MOD(nyear-1, 100) /= 0 ) ) THEN
+               nyear_len(0)  = 366
+            ENDIF
+            IF ( MOD(nyear  , 4) == 0 .AND. ( MOD(nyear  , 400) == 0 .OR. MOD(nyear  , 100) /= 0 ) ) THEN
+               nmonth_len(2) = 29
+               nyear_len(1)  = 366
+            ENDIF
+            IF ( MOD(nyear+1, 4) == 0 .AND. ( MOD(nyear+1, 400) == 0 .OR. MOD(nyear+1, 100) /= 0 ) ) THEN
+               nyear_len(2)  = 366
+            ENDIF
+         ENDIF
+      ELSE
+         nmonth_len(:) = nleapy   ! all months with nleapy days per year
+         nyear_len(:) = 12 * nleapy
+      ENDIF
+
+      ! half month in second since the begining of the year:
+      ! time since Jan 1st   0     1     2    ...    11    12    13
+      !          ---------*--|--*--|--*--| ... |--*--|--*--|--*--|--------------------------------------
+      !                 <---> <---> <--->  ...  <---> <---> <--->
+      ! month number      0     1     2    ...    11    12    13
+      !
+      ! nmonth_half(jm) = rday * REAL( 0.5 * nmonth_len(jm) + SUM(nmonth_len(1:jm-1)) )
+      nmonth_half(0) = - nsecd05 * nmonth_len(0)
+      DO jm = 1, 13
+         nmonth_half(jm) = nmonth_half(jm-1) + nsecd05 * ( nmonth_len(jm-1) + nmonth_len(jm) )
+      END DO
+
+      nmonth_end(0) = 0
+      DO jm = 1, 13
+         nmonth_end(jm) = nmonth_end(jm-1) + nsecd * nmonth_len(jm)
+      END DO
+      !
+   END SUBROUTINE
+
+
+   SUBROUTINE day( kt )
+      !!----------------------------------------------------------------------
+      !!                      ***  ROUTINE day  ***
+      !!
+      !! ** Purpose :   Compute the date with a day iteration IF necessary.
+      !!
+      !! ** Method  : - ???
+      !!
+      !! ** Action  : - nyear     : current year
+      !!              - nmonth    : current month of the year nyear
+      !!              - nday      : current day of the month nmonth
+      !!              - nday_year : current day of the year nyear
+      !!              - ndastp    : = nyear*10000 + nmonth*100 + nday
+      !!              - adatrj    : date in days since the beginning of the run
+      !!              - nsec_year : current time of the year (in second since 00h, jan 1st)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt        ! ocean time-step indices
+      !
+      CHARACTER (len=25) ::   charout
+      REAL(wp)           ::   zprec      ! fraction of day corresponding to 0.1 second
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('day')
+      !
+      zprec = 0.1 / rday
+      !                                                 ! New time-step
+      nsec_year  = nsec_year  + ndt
+      nsec_month = nsec_month + ndt
+      nsec_week  = nsec_week  + ndt
+      nsec_day   = nsec_day   + ndt
+      adatrj  = adatrj  + rdt / rday
+      fjulday = fjulday + rdt / rday
+      IF( ABS(fjulday - REAL(NINT(fjulday),wp)) < zprec )   fjulday = REAL(NINT(fjulday),wp)   ! avoid truncation error
+      IF( ABS(adatrj  - REAL(NINT(adatrj ),wp)) < zprec )   adatrj  = REAL(NINT(adatrj ),wp)   ! avoid truncation error
+
+      IF( nsec_day > nsecd ) THEN                       ! New day
+         !
+         nday      = nday + 1
+         nday_year = nday_year + 1
+         nsec_day  = ndt05
+         !
+         IF( nday == nmonth_len(nmonth) + 1 ) THEN      ! New month
+            nday   = 1
+            nmonth = nmonth + 1
+            nsec_month = ndt05
+            IF( nmonth == 13 ) THEN                     ! New year
+               nyear     = nyear + 1
+               nmonth    = 1
+               nday_year = 1
+               nsec_year = ndt05
+               nsec1jan000 = nsec1jan000 + nsecd * nyear_len(1)
+               IF( nleapy == 1 )   CALL day_mth
+            ENDIF
+         ENDIF
+         !
+         ndastp = nyear * 10000 + nmonth * 100 + nday   ! New date
+         !
+         !compute first day of the year in julian days
+         CALL ymds2ju( nyear, 01, 01, 0.0, fjulstartyear )
+         !
+         IF(lwp) WRITE(numout,'(a,i8,a,i4.4,a,i2.2,a,i2.2,a,i3.3)') '======>> time-step =', kt,   &
+              &   '      New day, DATE Y/M/D = ', nyear, '/', nmonth, '/', nday, '      nday_year = ', nday_year
+         IF(lwp) WRITE(numout,'(a,i8,a,i7,a,i5)') '         nsec_year = ', nsec_year,   &
+              &   '   nsec_month = ', nsec_month, '   nsec_day = ', nsec_day, '   nsec_week = ', nsec_week
+      ENDIF
+
+      IF( nsec_week > 7*nsecd )   nsec_week = ndt05     ! New week
+
+      IF(ln_ctl) THEN
+         WRITE(charout,FMT="('kt =', I4,'  d/m/y =',I2,I2,I4)") kt, nday, nmonth, nyear
+         CALL prt_ctl_info(charout)
+      ENDIF
+
+      IF( .NOT. l_offline ) CALL rst_opn( kt )               ! Open the restart file if needed and control lrst_oce
+      IF( lrst_oce         ) CALL day_rst( kt, 'WRITE' )      ! write day restart information
+      !
+      IF( ln_timing )   CALL timing_stop('day')
+      !
+   END SUBROUTINE day
+
+
+   SUBROUTINE day_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE ts_rst  ***
+      !!
+      !!  ** Purpose : Read or write calendar in restart file:
+      !!
+      !!  WRITE(READ) mode:
+      !!       kt        : number of time step since the begining of the experiment at the
+      !!                   end of the current(previous) run
+      !!       adatrj(0) : number of elapsed days since the begining of the experiment at the
+      !!                   end of the current(previous) run (REAL -> keep fractions of day)
+      !!       ndastp    : date at the end of the current(previous) run (coded as yyyymmdd integer)
+      !!
+      !!   According to namelist parameter nrstdt,
+      !!       nrstdt = 0  no control on the date (nit000 is  arbitrary).
+      !!       nrstdt = 1  we verify that nit000 is equal to the last
+      !!                   time step of previous run + 1.
+      !!       In both those options, the  exact duration of the experiment
+      !!       since the beginning (cumulated duration of all previous restart runs)
+      !!       is not stored in the restart and is assumed to be (nit000-1)*rdt.
+      !!       This is valid is the time step has remained constant.
+      !!
+      !!       nrstdt = 2  the duration of the experiment in days (adatrj)
+      !!                    has been stored in the restart file.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      !
+      REAL(wp) ::   zkt, zndastp, zdayfrac, ksecs, ktime
+      INTEGER  ::   ihour, iminute
+      !!----------------------------------------------------------------------
+
+      IF( TRIM(cdrw) == 'READ' ) THEN
+
+         IF( iom_varid( numror, 'kt', ldstop = .FALSE. ) > 0 ) THEN
+            ! Get Calendar informations
+            CALL iom_get( numror, 'kt', zkt, ldxios = lrxios )   ! last time-step of previous run
+            IF(lwp) THEN
+               WRITE(numout,*) ' *** Info read in restart : '
+               WRITE(numout,*) '   previous time-step                               : ', NINT( zkt )
+               WRITE(numout,*) ' *** restart option'
+               SELECT CASE ( nrstdt )
+               CASE ( 0 )   ;   WRITE(numout,*) ' nrstdt = 0 : no control of nit000'
+               CASE ( 1 )   ;   WRITE(numout,*) ' nrstdt = 1 : no control the date at nit000 (use ndate0 read in the namelist)'
+               CASE ( 2 )   ;   WRITE(numout,*) ' nrstdt = 2 : calendar parameters read in restart'
+               END SELECT
+               WRITE(numout,*)
+            ENDIF
+            ! Control of date
+            IF( nit000 - NINT( zkt ) /= 1 .AND. nrstdt /= 0 )                                         &
+                 &   CALL ctl_stop( ' ===>>>> : problem with nit000 for the restart',                 &
+                 &                  ' verify the restart file or rerun with nrstdt = 0 (namelist)' )
+            ! define ndastp and adatrj
+            IF ( nrstdt == 2 ) THEN
+               ! read the parameters corresponding to nit000 - 1 (last time step of previous run)
+               CALL iom_get( numror, 'ndastp', zndastp, ldxios = lrxios )
+               ndastp = NINT( zndastp )
+               CALL iom_get( numror, 'adatrj', adatrj , ldxios = lrxios )
+	       CALL iom_get( numror, 'ntime' , ktime  , ldxios = lrxios )
+	       nn_time0=INT(ktime)
+               ! calculate start time in hours and minutes
+	       zdayfrac=adatrj-INT(adatrj)
+	       ksecs = NINT(zdayfrac*86400)	       ! Nearest second to catch rounding errors in adatrj	       
+	       ihour = INT(ksecs/3600)
+	       iminute = ksecs/60-ihour*60
+ 	        
+               ! Add to nn_time0
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+	       nminute=nminute+iminute
+	       
+	       IF( nminute >= 60 ) THEN
+	          nminute=nminute-60
+		  nhour=nhour+1
+	       ENDIF
+	       nhour=nhour+ihour
+	       IF( nhour >= 24 ) THEN
+		  nhour=nhour-24
+	          adatrj=adatrj+1
+	       ENDIF	       
+	       nn_time0 = nhour * 100 + nminute
+	       adatrj = INT(adatrj)                    ! adatrj set to integer as nn_time0 updated	       
+            ELSE
+               ! parameters corresponding to nit000 - 1 (as we start the step loop with a call to day)
+               ndastp = ndate0        ! ndate0 read in the namelist in dom_nam
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+               IF( nhour*3600+nminute*60-ndt05 .lt. 0 )  ndastp=ndastp-1      ! Start hour is specified in the namelist (default 0)
+               adatrj = ( REAL( nit000-1, wp ) * rdt ) / rday
+               ! note this is wrong if time step has changed during run
+            ENDIF
+         ELSE
+            ! parameters corresponding to nit000 - 1 (as we start the step loop with a call to day)
+            ndastp = ndate0           ! ndate0 read in the namelist in dom_nam
+            nhour   =   nn_time0 / 100
+	    nminute = ( nn_time0 - nhour * 100 )
+            IF( nhour*3600+nminute*60-ndt05 .lt. 0 )  ndastp=ndastp-1      ! Start hour is specified in the namelist (default 0)
+            adatrj = ( REAL( nit000-1, wp ) * rdt ) / rday
+         ENDIF
+         IF( ABS(adatrj  - REAL(NINT(adatrj),wp)) < 0.1 / rday )   adatrj = REAL(NINT(adatrj),wp)   ! avoid truncation error
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) ' *** Info used values : '
+            WRITE(numout,*) '   date ndastp                                      : ', ndastp
+            WRITE(numout,*) '   number of elapsed days since the begining of run : ', adatrj
+	    WRITE(numout,*) '   nn_time0                                         : ',nn_time0
+            WRITE(numout,*)
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
+         !
+         IF( kt == nitrst ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'rst_write : write oce restart file  kt =', kt
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         ! calendar control
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         CALL iom_rstput( kt, nitrst, numrow, 'kt'     , REAL( kt    , wp)  , ldxios = lwxios )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrow, 'ndastp' , REAL( ndastp, wp)  , ldxios = lwxios )   ! date
+         CALL iom_rstput( kt, nitrst, numrow, 'adatrj' , adatrj             , ldxios = lwxios )   ! number of elapsed days since
+         !                                                                     ! the begining of the run [s]
+	 CALL iom_rstput( kt, nitrst, numrow, 'ntime'  , REAL( nn_time0, wp), ldxios = lwxios ) ! time
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE day_rst
+
+   !!======================================================================
+END MODULE daymod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/diawri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/diawri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/diawri.F90	(revision 14097)
@@ -0,0 +1,387 @@
+MODULE diawri
+   !!======================================================================
+   !!                     ***  MODULE  diawri  ***
+   !! Ocean diagnostics :  write ocean output files
+   !!=====================================================================
+   !! History :  OPA  ! 1991-03  (M.-A. Foujols)  Original code
+   !!            4.0  ! 1991-11  (G. Madec)
+   !!                 ! 1992-06  (M. Imbard)  correction restart file
+   !!                 ! 1992-07  (M. Imbard)  split into diawri and rstwri
+   !!                 ! 1993-03  (M. Imbard)  suppress writibm
+   !!                 ! 1998-01  (C. Levy)  NETCDF format using ioipsl INTERFACE
+   !!                 ! 1999-02  (E. Guilyardi)  name of netCDF files + variables
+   !!            8.2  ! 2000-06  (M. Imbard)  Original code (diabort.F)
+   !!   NEMO     1.0  ! 2002-06  (A.Bozec, E. Durand)  Original code (diainit.F)
+   !!             -   ! 2002-09  (G. Madec)  F90: Free form and module
+   !!             -   ! 2002-12  (G. Madec)  merge of diabort and diainit, F90
+   !!                 ! 2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            3.2  ! 2008-11  (B. Lemaire) creation from old diawri
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_wri       : create the standart output files
+   !!   dia_wri_state : create an output NetCDF file for a single instantaeous ocean state and forcing fields
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers 
+   USE dom_oce         ! ocean space and time domain
+   USE zdf_oce         ! ocean vertical physics
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE sbcssr          ! restoring term toward SST/SSS climatology
+   USE phycst          ! physical constants
+   USE zdfmxl          ! mixed layer
+   USE dianam          ! build name of file (routine)
+   USE zdfddm          ! vertical  physics: double diffusion
+   USE diahth          ! thermocline diagnostics
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  ! I/O manager
+   USE iom
+   USE ioipsl
+#if defined key_si3
+   USE ice
+   USE icewri
+#endif
+   USE lib_mpp         ! MPP library
+   USE timing          ! preformance summary
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_wri                 ! routines called by step.F90
+   PUBLIC   dia_wri_state
+   PUBLIC   dia_wri_alloc           ! Called by nemogcm module
+
+   INTEGER ::   nid_T, nz_T, nh_T, ndim_T, ndim_hT   ! grid_T file
+   INTEGER ::   nid_U, nz_U, nh_U, ndim_U, ndim_hU   ! grid_U file
+   INTEGER ::   nid_V, nz_V, nh_V, ndim_V, ndim_hV   ! grid_V file
+   INTEGER ::   ndex(1)                              ! ???
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_hT, ndex_hU, ndex_hV
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+# if defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_iomput'                                        use IOM library
+   !!----------------------------------------------------------------------
+   INTEGER FUNCTION dia_wri_alloc()
+      !
+      dia_wri_alloc = 0
+      !
+   END FUNCTION dia_wri_alloc
+
+   
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!      Standalone surface scheme 
+      !!
+      !! ** Method  :  use iom_put
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!----------------------------------------------------------------------
+      ! 
+      ! Output the initial state and forcings
+      IF( ninist == 1 ) THEN
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+      !
+   END SUBROUTINE dia_wri
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                  use IOIPSL  library
+   !!----------------------------------------------------------------------
+   INTEGER FUNCTION dia_wri_alloc()
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( ndex_hT(jpi*jpj), ndex_hU(jpi*jpj), ndex_hV(jpi*jpj), STAT=dia_wri_alloc )
+      CALL mpp_sum( 'diawri', dia_wri_alloc )
+      !
+   END FUNCTION dia_wri_alloc
+   
+  
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!
+      !! ** Method  :   At the beginning of the first time step (nit000), 
+      !!      define all the NETCDF files and fields
+      !!      At each time step call histdef to compute the mean if ncessary
+      !!      Each nn_write time step, output the instantaneous or mean fields
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!
+      LOGICAL ::   ll_print = .FALSE.                        ! =T print and flush numout
+      CHARACTER (len=40) ::   clhstnam, clop, clmx           ! local names
+      INTEGER  ::   inum = 11                                ! temporary logical unit
+      INTEGER  ::   ji, jj, jk                               ! dummy loop indices
+      INTEGER  ::   ierr                                     ! error code return from allocation
+      INTEGER  ::   iimi, iima, ipk, it, itmod, ijmi, ijma   ! local integers
+      REAL(wp) ::   zsto, zout, zmax, zjulian                ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      ! Output the initial state and forcings
+      IF( ninist == 1 ) THEN                       
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+      !
+      IF( nn_write == -1 )   RETURN   ! we will never do any output
+      ! 
+      IF( ln_timing )   CALL timing_start('dia_wri')
+      !
+      ! 0. Initialisation
+      ! -----------------
+
+      ! local variable for debugging
+      ll_print = .FALSE.
+      ll_print = ll_print .AND. lwp
+
+      ! 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
+      zsto = nn_write * rdt
+      clop = "inst("//TRIM(clop)//")"
+#else
+      zsto=rdt
+      clop = "ave("//TRIM(clop)//")"
+#endif
+      zout = nn_write * rdt
+      zmax = ( nitend - nit000 + 1 ) * rdt
+
+      ! Define indices of the horizontal output zoom and vertical limit storage
+      iimi = 1      ;      iima = jpi
+      ijmi = 1      ;      ijma = jpj
+      ipk = jpk
+
+      ! define time axis
+      it = kt
+      itmod = kt - nit000 + 1
+
+
+      ! 1. Define NETCDF files and fields at beginning of first time step
+      ! -----------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+
+         ! Define the NETCDF files (one per grid)
+
+         ! 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
+         IF(lwp)WRITE(numout,*) ' indexes of zoom = ', iimi, iima, ijmi, ijma,   &
+                                 ' limit storage in depth = ', ipk
+
+         ! WRITE root name in date.file for use by postpro
+         IF(lwp) THEN
+            CALL dia_nam( clhstnam, nn_write,' ' )
+            CALL ctl_opn( inum, 'date.file', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            WRITE(inum,*) clhstnam
+            CLOSE(inum)
+         ENDIF
+
+         ! Define the T grid FILE ( nid_T )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_T' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_T, nid_T, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_T, "deptht", "Vertical T levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_T, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj    , tmask, 1, 1., ndex_hT, ndim_hT )      ! surface
+
+         ! Define the U grid FILE ( nid_U )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_U' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamu, jpj, gphiu,           &  ! Horizontal grid: glamu and gphiu
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_U, nid_U, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_U, "depthu", "Vertical U levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_U, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj    , umask, 1, 1., ndex_hU, ndim_hU )      ! surface
+
+         ! Define the V grid FILE ( nid_V )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_V' )                   ! filename
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam
+         CALL histbeg( clhstnam, jpi, glamv, jpj, gphiv,           &  ! Horizontal grid: glamv and gphiv
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_V, nid_V, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_V, "depthv", "Vertical V levels",      &  ! Vertical grid : gdept
+            &          "m", ipk, gdept_1d, nz_V, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj    , vmask, 1, 1., ndex_hV, ndim_hV )      ! surface
+
+         ! No W grid FILE
+
+         ! Declare all the output fields as NETCDF variables
+
+         !                                                                                      !!! nid_T : 3D
+         CALL histdef( nid_T, "sst_m", "Sea Surface temperature"            , "C"      ,   &  ! sst
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sss_m", "Sea Surface Salinity"               , "PSU"    ,   &  ! sss
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowaflup", "Net Upward Water Flux"              , "Kg/m2/s",   &  ! (emp-rnf)
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sosfldow", "downward salt flux"                 , "PSU/m2/s",  &  ! (sfx)
+             &         jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sohefldo", "Net Downward Heat Flux"             , "W/m2"   ,   &  ! qns + qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soshfldo", "Shortwave Radiation"                , "W/m2"   ,   &  ! qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soicecov", "Ice fraction"                       , "[0,1]"  ,   &  ! fr_i
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowindsp", "wind speed at 10m"                  , "m/s"    ,   &  ! wndm
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+
+         CALL histend( nid_T, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_U : 3D
+         CALL histdef( nid_U, "ssu_m", "Velocity component in x-direction", "m/s"   ,         &  ! ssu
+            &          jpi, jpj, nh_U, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+         CALL histdef( nid_U, "sozotaux", "Wind Stress along i-axis"           , "N/m2"   ,   &  ! utau
+            &          jpi, jpj, nh_U, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_U, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_V : 3D
+         CALL histdef( nid_V, "ssv_m", "Velocity component in y-direction", "m/s",            &  ! ssv_m
+            &          jpi, jpj, nh_V, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+         CALL histdef( nid_V, "sometauy", "Wind Stress along j-axis"           , "N/m2"   ,   &  ! vtau
+            &          jpi, jpj, nh_V, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_V, snc4chunks=snc4set )
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'End of NetCDF Initialization'
+         IF(ll_print) CALL FLUSH(numout )
+
+      ENDIF
+
+      ! 2. Start writing data
+      ! ---------------------
+
+      ! ndex(1) est utilise ssi l'avant dernier argument est diffferent de 
+      ! la taille du tableau en sortie. Dans ce cas , l'avant dernier argument
+      ! donne le nombre d'elements, et ndex la liste des indices a sortir
+
+      IF( lwp .AND. MOD( itmod, nn_write ) == 0 ) THEN 
+         WRITE(numout,*) 'dia_wri : write model outputs in NetCDF files at ', kt, 'time-step'
+         WRITE(numout,*) '~~~~~~ '
+      ENDIF
+
+      ! Write fields on T grid
+      CALL histwrite( nid_T, "sst_m", it, sst_m, ndim_hT, ndex_hT )   ! sea surface temperature
+      CALL histwrite( nid_T, "sss_m", it, sss_m, ndim_hT, ndex_hT )   ! sea surface salinity
+      CALL histwrite( nid_T, "sowaflup", it, (emp - rnf )  , ndim_hT, ndex_hT )   ! upward water flux
+      CALL histwrite( nid_T, "sosfldow", it, sfx           , ndim_hT, ndex_hT )   ! downward salt flux 
+                                                                                  ! (includes virtual salt flux beneath ice 
+                                                                                  ! in linear free surface case)
+
+      CALL histwrite( nid_T, "sohefldo", it, qns + qsr     , ndim_hT, ndex_hT )   ! total heat flux
+      CALL histwrite( nid_T, "soshfldo", it, qsr           , ndim_hT, ndex_hT )   ! solar heat flux
+      CALL histwrite( nid_T, "soicecov", it, fr_i          , ndim_hT, ndex_hT )   ! ice fraction   
+      CALL histwrite( nid_T, "sowindsp", it, wndm          , ndim_hT, ndex_hT )   ! wind speed   
+
+         ! Write fields on U grid
+      CALL histwrite( nid_U, "ssu_m"   , it, ssu_m         , ndim_hU, ndex_hU )   ! i-current speed
+      CALL histwrite( nid_U, "sozotaux", it, utau          , ndim_hU, ndex_hU )   ! i-wind stress
+
+         ! Write fields on V grid
+      CALL histwrite( nid_V, "ssv_m"   , it, ssv_m         , ndim_hV, ndex_hV )   ! j-current speed
+      CALL histwrite( nid_V, "sometauy", it, vtau          , ndim_hV, ndex_hV )   ! j-wind stress
+
+      ! 3. Close all files
+      ! ---------------------------------------
+      IF( kt == nitend ) THEN
+         CALL histclo( nid_T )
+         CALL histclo( nid_U )
+         CALL histclo( nid_V )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_wri')
+      !
+   END SUBROUTINE dia_wri
+#endif
+
+   SUBROUTINE dia_wri_state( cdfile_name )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_wri_state  ***
+      !!        
+      !! ** Purpose :   create a NetCDF file named cdfile_name which contains 
+      !!      the instantaneous ocean state and forcing fields.
+      !!        Used to find errors in the initial state or save the last
+      !!      ocean state in case of abnormal end of a simulation
+      !!
+      !! ** Method  :   NetCDF files using ioipsl
+      !!      File 'output.init.nc'  is created if ninist = 1 (namelist)
+      !!      File 'output.abort.nc' is created in case of abnormal job end
+      !!----------------------------------------------------------------------
+      CHARACTER (len=* ), INTENT( in ) ::   cdfile_name      ! name of the file created
+      !!
+      INTEGER :: inum
+      !!----------------------------------------------------------------------
+      ! 
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dia_wri_state : single instantaneous ocean state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~   and forcing fields file created '
+      IF(lwp) WRITE(numout,*) '                and named :', cdfile_name, '...nc'
+
+#if defined key_si3
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE., kdlev = jpl )
+#else
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE. )
+#endif
+
+      CALL iom_rstput( 0, 0, inum, 'votemper', tsn(:,:,:,jp_tem) )    ! now temperature
+      CALL iom_rstput( 0, 0, inum, 'vosaline', tsn(:,:,:,jp_sal) )    ! now salinity
+      CALL iom_rstput( 0, 0, inum, 'sossheig', sshn              )    ! sea surface height
+      CALL iom_rstput( 0, 0, inum, 'vozocrtx', un                )    ! now i-velocity
+      CALL iom_rstput( 0, 0, inum, 'vomecrty', vn                )    ! now j-velocity
+      CALL iom_rstput( 0, 0, inum, 'vovecrtz', wn                )    ! now k-velocity
+      CALL iom_rstput( 0, 0, inum, 'sowaflup', emp - rnf         )    ! freshwater budget
+      CALL iom_rstput( 0, 0, inum, 'sohefldo', qsr + qns         )    ! total heat flux
+      CALL iom_rstput( 0, 0, inum, 'soshfldo', qsr               )    ! solar heat flux
+      CALL iom_rstput( 0, 0, inum, 'soicecov', fr_i              )    ! ice fraction
+      CALL iom_rstput( 0, 0, inum, 'sozotaux', utau              )    ! i-wind stress
+      CALL iom_rstput( 0, 0, inum, 'sometauy', vtau              )    ! j-wind stress
+ 
+#if defined key_si3
+      IF( nn_ice == 2 ) THEN   ! condition needed in case agrif + ice-model but no-ice in child grid
+         CALL ice_wri_state( inum )
+      ENDIF
+#endif
+      !
+      CALL iom_close( inum )
+      !
+   END SUBROUTINE dia_wri_state
+
+   !!======================================================================
+END MODULE diawri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/nemogcm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/nemogcm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/nemogcm.F90	(revision 14097)
@@ -0,0 +1,568 @@
+MODULE nemogcm
+   !!======================================================================
+   !!                       ***  MODULE nemogcm   ***
+   !! StandAlone Surface module : surface fluxes + sea-ice + iceberg floats
+   !!======================================================================
+   !! History :  3.6  ! 2011-11  (S. Alderson, G. Madec) original code
+   !!             -   ! 2013-06  (I. Epicoco, S. Mocavero, CMCC) nemo_northcomms: setup avoiding MPI communication 
+   !!             -   ! 2014-12  (G. Madec) remove KPP scheme and cross-land advection (cla)
+   !!            4.0  ! 2016-10  (G. Madec, S. Flavoni)  domain configuration / user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   nemo_gcm      : solve ocean dynamics, tracer, biogeochemistry and/or sea-ice
+   !!   nemo_init     : initialization of the NEMO system
+   !!   nemo_ctl      : initialisation of the contol print
+   !!   nemo_closefile: close remaining open files
+   !!   nemo_alloc    : dynamical allocation
+   !!----------------------------------------------------------------------
+   USE step_oce       ! module used in the ocean time stepping module
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE phycst         ! physical constant                  (par_cst routine)
+   USE domain         ! domain initialization   (dom_init & dom_cfg routines)
+   USE closea         ! treatment of closed seas (for ln_closea)
+   USE usrdef_nam     ! user defined configuration
+   USE daymod         ! calendar
+   USE restart        ! open  restart file
+   USE step           ! NEMO time-stepping                 (stp     routine)
+   USE cpl_oasis3     !
+   USE sbcssm         !
+   USE icbini         ! handle bergs, initialisation
+   USE icbstp         ! handle bergs, calving, themodynamics and transport
+   USE bdyini         ! open boundary cond. setting       (bdy_init routine). mandatory for sea-ice
+   USE bdydta         ! open boundary cond. setting   (bdy_dta_init routine). mandatory for sea-ice
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distributed memory computing
+   USE mppini         ! shared/distributed memory setting (mpp_init routine)
+   USE lbcnfd  , ONLY : isendto, nsndto, nfsloop, nfeloop   ! Setup of north fold exchanges
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
+#if defined key_iomput
+   USE xios           ! xIOserver
+#endif
+#if defined key_agrif && defined key_si3
+   USE agrif_ice_update ! ice update
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   nemo_gcm    ! called by model.F90
+   PUBLIC   nemo_init   ! needed by AGRIF
+
+   CHARACTER(lc) ::   cform_aaa="( /, 'AAAAAAAA', / ) "     ! flag for output listing
+
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE nemo_gcm
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_gcm  ***
+      !!
+      !! ** Purpose :   NEMO solves the primitive equations on an orthogonal
+      !!              curvilinear mesh on the sphere.
+      !!
+      !! ** Method  : - model general initialization
+      !!              - launch the time-stepping (stp routine)
+      !!              - finalize the run by closing files and communications
+      !!
+      !! References : Madec, Delecluse, Imbard, and Levy, 1997:  internal report, IPSL.
+      !!              Madec, 2008, internal report, IPSL.
+      !!----------------------------------------------------------------------
+      INTEGER ::   istp   ! time step index
+      !!----------------------------------------------------------------------
+      !
+#if defined key_agrif
+      CALL Agrif_Init_Grids()      ! AGRIF: set the meshes
+#endif
+      !                            !-----------------------!
+      CALL nemo_init               !==  Initialisations  ==!
+      !                            !-----------------------!
+#if defined key_agrif
+      CALL Agrif_Declare_Var_dom   ! AGRIF: set the meshes for DOM
+      CALL Agrif_Declare_Var       !  "      "   "   "      "  DYN/TRA 
+# if defined key_top
+      CALL Agrif_Declare_Var_top   !  "      "   "   "      "  TOP
+# endif
+# if defined key_si3
+      CALL Agrif_Declare_Var_ice   !  "      "   "   "      "  Sea ice
+# 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!
+      CALL mpp_max( 'nemogcm', nstop )
+
+      IF(lwp) WRITE(numout,cform_aaa)   ! Flag AAAAAAA
+
+      !                            !-----------------------!
+      !                            !==   time stepping   ==!
+      !                            !-----------------------!
+      istp = nit000
+      !
+#if defined key_agrif
+      !                                               !==  AGRIF time-stepping  ==!
+      CALL Agrif_Regrid()
+      !
+#if defined key_si3
+      ! Recursive update from highest nested level to lowest:
+      CALL Agrif_step_child_adj(Agrif_update_ice)
+#endif
+      !
+      DO WHILE( istp <= nitend .AND. nstop == 0 )
+         CALL stp
+         istp = istp + 1
+      END DO
+      !
+      IF( .NOT. Agrif_Root() ) THEN
+         CALL Agrif_ParentGrid_To_ChildGrid()
+         IF( ln_timing )   CALL timing_finalize
+         CALL Agrif_ChildGrid_To_ParentGrid()
+      ENDIF
+      !
+#else
+      !
+      IF( .NOT.ln_diurnal_only ) THEN                 !==  Standard time-stepping  ==!
+         !
+         DO WHILE( istp <= nitend .AND. nstop == 0 )
+            CALL stp        ( istp ) 
+            istp = istp + 1
+         END DO
+         !
+      ELSE                                            !==  diurnal SST time-steeping only  ==!
+         !
+         DO WHILE( istp <= nitend .AND. nstop == 0 )
+            CALL stp_diurnal( istp )   ! time step only the diurnal SST 
+            istp = istp + 1
+         END DO
+         !
+      ENDIF
+      !
+#endif
+      !
+      IF( ln_icebergs )   CALL icb_end( nitend )
+
+      !                            !------------------------!
+      !                            !==  finalize the run  ==!
+      !                            !------------------------!
+      IF(lwp) WRITE(numout,cform_aaa)        ! Flag AAAAAAA
+      !
+      IF( nstop /= 0 .AND. lwp ) THEN        ! error print
+         WRITE(ctmp1,*) '   ==>>>   nemo_gcm: a total of ', nstop, ' errors have been found'
+         WRITE(ctmp2,*) '           Look for "E R R O R" messages in all existing ocean_output* files'
+         CALL ctl_stop( ' ', ctmp1, ' ', ctmp2 )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_finalize
+      !
+      CALL nemo_closefile
+      !
+#if defined key_iomput
+                                    CALL xios_finalize  ! end mpp communications with xios
+      IF( lk_oasis     )            CALL cpl_finalize   ! end coupling and mpp communications with OASIS
+#else
+      IF    ( lk_oasis ) THEN   ;   CALL cpl_finalize   ! end coupling and mpp communications with OASIS
+      ELSEIF( lk_mpp   ) THEN   ;   CALL mppstop        ! end mpp communications
+      ENDIF
+#endif
+      !
+      IF(lwm) THEN
+         IF( nstop == 0 ) THEN   ;   STOP 0
+         ELSE                    ;   STOP 123
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE nemo_gcm
+
+
+   SUBROUTINE nemo_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_init  ***
+      !!
+      !! ** Purpose :   initialization of the NEMO GCM
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, ilocal_comm   ! local integers
+      !!
+      NAMELIST/namctl/ ln_ctl   , sn_cfctl, nn_print, nn_ictls, nn_ictle,   &
+         &             nn_isplt , nn_jsplt, nn_jctls, nn_jctle,             &
+         &             ln_timing, ln_diacfl
+      NAMELIST/namcfg/ ln_read_cfg, cn_domcfg, ln_closea, ln_write_cfg, cn_domcfg_out, ln_use_jattr
+      !!----------------------------------------------------------------------
+      !
+      IF( lk_oasis ) THEN   ;   cxios_context = 'sas'
+      ELSE                  ;   cxios_context = 'nemo'
+      ENDIF
+      !
+      !                             !-------------------------------------------------!
+      !                             !     set communicator & select the local rank    !
+      !                             !  must be done as soon as possible to get narea  !
+      !                             !-------------------------------------------------!
+      !
+#if defined key_iomput
+      IF( Agrif_Root() ) THEN
+         IF( lk_oasis ) THEN
+            CALL cpl_init( "sas", ilocal_comm )                                  ! nemo local communicator given by oasis 
+            CALL xios_initialize( "not used",local_comm=ilocal_comm )            ! send nemo communicator to xios
+         ELSE
+            CALL xios_initialize( "for_xios_mpi_id",return_comm=ilocal_comm )    ! nemo local communicator given by xios
+         ENDIF
+      ENDIF
+      CALL mpp_start( ilocal_comm )
+#else
+      IF( lk_oasis ) THEN
+         IF( Agrif_Root() ) THEN
+            CALL cpl_init( "sas", ilocal_comm )             ! nemo local communicator given by oasis
+         ENDIF
+         CALL mpp_start( ilocal_comm )
+      ELSE
+         CALL mpp_start( )
+      ENDIF
+#endif
+      !
+      narea = mpprank + 1                                   ! mpprank: the rank of proc (0 --> mppsize -1 )
+      lwm = (narea == 1)                ! control of output namelists
+      !
+      !                             !---------------------------------------------------------------!
+      !                             ! Open output files, reference and configuration namelist files !
+      !                             !---------------------------------------------------------------!
+      !
+      ! open ocean.output as soon as possible to get all output prints (including errors messages)
+      IF( lk_oasis ) THEN
+         IF( lwm )   CALL ctl_opn(     numout,              'sas.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+         ! open reference and configuration namelist files
+                     CALL ctl_opn( numnam_ref,        'namelist_sas_ref',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+                     CALL ctl_opn( numnam_cfg,        'namelist_sas_cfg',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+         IF( lwm )   CALL ctl_opn(     numond, 'output.namelist_sas.dyn', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ELSE
+         IF( lwm )   CALL ctl_opn(     numout,            'ocean.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+         ! open reference and configuration namelist files
+                     CALL ctl_opn( numnam_ref,            'namelist_ref',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+                     CALL ctl_opn( numnam_cfg,            'namelist_cfg',     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+         IF( lwm )   CALL ctl_opn(     numond,     'output.namelist.dyn', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+      ENDIF
+      ! open /dev/null file to be able to supress output write easily
+      IF( Agrif_Root() ) THEN
+                     CALL ctl_opn(     numnul,               '/dev/null', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, -1, .FALSE. )
+#ifdef key_agrif
+      ELSE
+                     numnul = Agrif_Parent(numnul)
+#endif
+      ENDIF
+      !
+      !                             !--------------------!
+      !                             ! Open listing units !  -> need ln_ctl from namctl to define lwp
+      !                             !--------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namctl in reference namelist
+      READ  ( numnam_ref, namctl, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namctl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namctl in confguration namelist
+      READ  ( numnam_cfg, namctl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namctl in configuration namelist' )
+      !
+      lwp = (narea == 1) .OR. ln_ctl    ! control of all listing output print
+      !
+      IF(lwp) THEN                      ! open listing units
+         !
+         IF( .NOT. lwm ) THEN           ! alreay opened for narea == 1
+            IF(lk_oasis) THEN   ;   CALL ctl_opn( numout,   'sas.output','REPLACE','FORMATTED','SEQUENTIAL',-1,-1, .FALSE., narea )
+            ELSE                ;   CALL ctl_opn( numout, 'ocean.output','REPLACE','FORMATTED','SEQUENTIAL',-1,-1, .FALSE., narea )
+            ENDIF
+         ENDIF
+         !
+         WRITE(numout,*)
+         WRITE(numout,*) '   CNRS - NERC - Met OFFICE - MERCATOR-ocean - CMCC'
+         WRITE(numout,*) '                       NEMO team'
+         WRITE(numout,*) '            Ocean General Circulation Model'
+         WRITE(numout,*) '                NEMO version 4.0  (2019) '
+         WRITE(numout,*) '             StandAlone Surface version (SAS) '
+         WRITE(numout,*) "           ._      ._      ._      ._      ._    "
+         WRITE(numout,*) "       _.-._)`\_.-._)`\_.-._)`\_.-._)`\_.-._)`\_ "
+         WRITE(numout,*)
+         WRITE(numout,*) "           o         _,           _,             "
+         WRITE(numout,*) "            o      .' (        .-' /             "
+         WRITE(numout,*) "           o     _/..._'.    .'   /              "
+         WRITE(numout,*) "      (    o .-'`      ` '-./  _.'               "
+         WRITE(numout,*) "       )    ( o)           ;= <_         (       "
+         WRITE(numout,*) "      (      '-.,\\__ __.-;`\   '.        )      "
+         WRITE(numout,*) "       )  )       \) |`\ \)  '.   \      (   (   "
+         WRITE(numout,*) "      (  (           \_/       '-._\      )   )  "
+         WRITE(numout,*) "       )  ) jgs                    `     (   (   "
+         WRITE(numout,*) "     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
+         WRITE(numout,*)
+         WRITE(numout,*)
+         !
+         WRITE(numout,cform_aaa)                                        ! Flag AAAAAAA
+         !
+      ENDIF
+     !
+      ! finalize the definition of namctl variables
+      IF( sn_cfctl%l_config ) THEN
+         ! Activate finer control of report outputs
+         ! optionally switch off output from selected areas (note this only
+         ! applies to output which does not involve global communications)
+         IF( ( narea < sn_cfctl%procmin .OR. narea > sn_cfctl%procmax  ) .OR. &
+           & ( MOD( narea - sn_cfctl%procmin, sn_cfctl%procincr ) /= 0 ) )    &
+           &   CALL nemo_set_cfctl( sn_cfctl, .FALSE., .FALSE. )
+      ELSE
+         ! Use ln_ctl to turn on or off all options.
+         CALL nemo_set_cfctl( sn_cfctl, ln_ctl, .TRUE. )
+      ENDIF
+      !
+      IF(lwm) WRITE( numond, namctl )
+      !
+      !                             !------------------------------------!
+      !                             !  Set global domain size parameters !
+      !                             !------------------------------------!
+      !
+      REWIND( numnam_ref )              ! Namelist namcfg in reference namelist
+      READ  ( numnam_ref, namcfg, IOSTAT = ios, ERR = 903 )
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcfg in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namcfg in confguration namelist
+      READ  ( numnam_cfg, namcfg, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcfg in configuration namelist' )   
+      !
+      IF( ln_read_cfg ) THEN            ! Read sizes in domain configuration file
+         CALL domain_cfg ( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ELSE                              ! user-defined namelist
+         CALL usr_def_nam( cn_cfg, nn_cfg, jpiglo, jpjglo, jpkglo, jperio )
+      ENDIF
+      !
+      IF(lwm)   WRITE( numond, namcfg )
+      !
+      !                             !-----------------------------------------!
+      !                             ! mpp parameters and domain decomposition !
+      !                             !-----------------------------------------!
+      CALL mpp_init
+
+      ! Now we know the dimensions of the grid and numout has been set: we can allocate arrays
+      CALL nemo_alloc()
+
+      !                             !-------------------------------!
+      !                             !  NEMO general initialization  !
+      !                             !-------------------------------!
+
+      CALL nemo_ctl                          ! Control prints
+      !
+      !                                      ! General initialization
+      IF( ln_timing    )   CALL timing_init     ! timing
+      IF( ln_timing    )   CALL timing_start( 'nemo_init')
+
+                           CALL phy_cst         ! Physical constants
+                           CALL eos_init        ! Equation of seawater
+                           CALL dom_init('SAS') ! Domain
+      IF( ln_ctl      )    CALL prt_ctl_init    ! Print control
+      
+                           CALL day_init        ! model calendar (using both namelist and restart infos)
+      IF( ln_rstart )      CALL rst_read_open
+
+      !                                      ! external forcing 
+                           CALL sbc_init        ! Forcings : surface module 
+
+      ! ==> clem: open boundaries init. is mandatory for sea-ice because ice BDY is not decoupled from  
+      !           the environment of ocean BDY. Therefore bdy is called in both OPA and SAS modules. 
+      !           This is not clean and should be changed in the future. 
+                           CALL bdy_init
+      ! ==>
+                           CALL icb_init( rdt, nit000)   ! initialise icebergs instance
+      !
+      IF(lwp) WRITE(numout,cform_aaa)           ! Flag AAAAAAA
+      !
+      IF( ln_timing    )   CALL timing_stop( 'nemo_init')
+      !
+   END SUBROUTINE nemo_init
+
+
+   SUBROUTINE nemo_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_ctl  ***
+      !!
+      !! ** Purpose :   control print setting
+      !!
+      !! ** Method  : - print namctl information and check some consistencies
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'nemo_ctl: Control prints'
+         WRITE(numout,*) '~~~~~~~~'
+         WRITE(numout,*) '   Namelist namctl'
+         WRITE(numout,*) '      run control (for debugging)     ln_ctl     = ', ln_ctl
+         WRITE(numout,*) '       finer control over o/p sn_cfctl%l_config  = ', sn_cfctl%l_config
+         WRITE(numout,*) '                              sn_cfctl%l_runstat = ', sn_cfctl%l_runstat
+         WRITE(numout,*) '                              sn_cfctl%l_trcstat = ', sn_cfctl%l_trcstat
+         WRITE(numout,*) '                              sn_cfctl%l_oceout  = ', sn_cfctl%l_oceout
+         WRITE(numout,*) '                              sn_cfctl%l_layout  = ', sn_cfctl%l_layout
+         WRITE(numout,*) '                              sn_cfctl%l_mppout  = ', sn_cfctl%l_mppout
+         WRITE(numout,*) '                              sn_cfctl%l_mpptop  = ', sn_cfctl%l_mpptop
+         WRITE(numout,*) '                              sn_cfctl%procmin   = ', sn_cfctl%procmin  
+         WRITE(numout,*) '                              sn_cfctl%procmax   = ', sn_cfctl%procmax  
+         WRITE(numout,*) '                              sn_cfctl%procincr  = ', sn_cfctl%procincr 
+         WRITE(numout,*) '                              sn_cfctl%ptimincr  = ', sn_cfctl%ptimincr 
+         WRITE(numout,*) '      level of print                  nn_print   = ', nn_print
+         WRITE(numout,*) '      Start i indice for SUM control  nn_ictls   = ', nn_ictls
+         WRITE(numout,*) '      End i indice for SUM control    nn_ictle   = ', nn_ictle
+         WRITE(numout,*) '      Start j indice for SUM control  nn_jctls   = ', nn_jctls
+         WRITE(numout,*) '      End j indice for SUM control    nn_jctle   = ', nn_jctle
+         WRITE(numout,*) '      number of proc. following i     nn_isplt   = ', nn_isplt
+         WRITE(numout,*) '      number of proc. following j     nn_jsplt   = ', nn_jsplt
+         WRITE(numout,*) '      timing by routine               ln_timing  = ', ln_timing
+         WRITE(numout,*) '      CFL diagnostics                 ln_diacfl  = ', ln_diacfl
+      ENDIF
+      !
+      nprint    = nn_print          ! convert DOCTOR namelist names into OLD names
+      nictls    = nn_ictls
+      nictle    = nn_ictle
+      njctls    = nn_jctls
+      njctle    = nn_jctle
+      isplt     = nn_isplt
+      jsplt     = nn_jsplt
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist namcfg'
+         WRITE(numout,*) '      read domain configuration file                ln_read_cfg      = ', ln_read_cfg
+         WRITE(numout,*) '         filename to be read                           cn_domcfg     = ', TRIM(cn_domcfg)
+         WRITE(numout,*) '         keep closed seas in the domain (if exist)     ln_closea     = ', ln_closea
+         WRITE(numout,*) '      create a configuration definition file        ln_write_cfg     = ', ln_write_cfg
+         WRITE(numout,*) '         filename to be written                        cn_domcfg_out = ', TRIM(cn_domcfg_out)
+         WRITE(numout,*) '      use file attribute if exists as i/p j-start   ln_use_jattr     = ', ln_use_jattr
+      ENDIF
+      IF( .NOT.ln_read_cfg )   ln_closea = .false.   ! dealing possible only with a domcfg file
+      !
+      !                             ! Parameter control
+      !
+      IF( ln_ctl ) THEN                 ! sub-domain area indices for the control prints
+         IF( lk_mpp .AND. jpnij > 1 ) THEN
+            isplt = jpni   ;   jsplt = jpnj   ;   ijsplt = jpni*jpnj   ! the domain is forced to the real split domain
+         ELSE
+            IF( isplt == 1 .AND. jsplt == 1  ) THEN
+               CALL ctl_warn( ' - isplt & jsplt are equal to 1',   &
+                  &           ' - the print control will be done over the whole domain' )
+            ENDIF
+            ijsplt = isplt * jsplt            ! total number of processors ijsplt
+         ENDIF
+         IF(lwp) WRITE(numout,*)'          - The total number of processors over which the'
+         IF(lwp) WRITE(numout,*)'            print control will be done is ijsplt : ', ijsplt
+         !
+         !                              ! indices used for the SUM control
+         IF( nictls+nictle+njctls+njctle == 0 )   THEN    ! print control done over the default area
+            lsp_area = .FALSE.
+         ELSE                                             ! print control done over a specific  area
+            lsp_area = .TRUE.
+            IF( nictls < 1 .OR. nictls > jpiglo )   THEN
+               CALL ctl_warn( '          - nictls must be 1<=nictls>=jpiglo, it is forced to 1' )
+               nictls = 1
+            ENDIF
+            IF( nictle < 1 .OR. nictle > jpiglo )   THEN
+               CALL ctl_warn( '          - nictle must be 1<=nictle>=jpiglo, it is forced to jpiglo' )
+               nictle = jpiglo
+            ENDIF
+            IF( njctls < 1 .OR. njctls > jpjglo )   THEN
+               CALL ctl_warn( '          - njctls must be 1<=njctls>=jpjglo, it is forced to 1' )
+               njctls = 1
+            ENDIF
+            IF( njctle < 1 .OR. njctle > jpjglo )   THEN
+               CALL ctl_warn( '          - njctle must be 1<=njctle>=jpjglo, it is forced to jpjglo' )
+               njctle = jpjglo
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF( 1._wp /= SIGN(1._wp,-0._wp)  )   CALL ctl_stop( 'nemo_ctl: The intrinsec SIGN function follows f2003 standard.',  &
+         &                                                'Compile with key_nosignedzero enabled:',   &
+         &                                                '--> add -Dkey_nosignedzero to the definition of %CPP in your arch file' )
+      !
+#if defined key_agrif
+      IF( ln_timing )   CALL ctl_stop( 'AGRIF not implemented with ln_timing = true')
+#endif
+      !
+   END SUBROUTINE nemo_ctl
+
+
+   SUBROUTINE nemo_closefile
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_closefile  ***
+      !!
+      !! ** Purpose :   Close the files
+      !!----------------------------------------------------------------------
+      !
+      IF( lk_mpp )   CALL mppsync
+      !
+      CALL iom_close                                 ! close all input/output files managed by iom_*
+      !
+      IF( numstp          /= -1 )   CLOSE( numstp          )   ! time-step file      
+      IF( numrun          /= -1 )   CLOSE( numrun          )   ! run statistics file
+      IF( numnam_ref      /= -1 )   CLOSE( numnam_ref      )   ! oce reference namelist
+      IF( numnam_cfg      /= -1 )   CLOSE( numnam_cfg      )   ! oce configuration namelist
+      IF( lwm.AND.numond  /= -1 )   CLOSE( numond          )   ! oce output namelist
+      IF( numnam_ice_ref  /= -1 )   CLOSE( numnam_ice_ref  )   ! ice reference namelist
+      IF( numnam_ice_cfg  /= -1 )   CLOSE( numnam_ice_cfg  )   ! ice configuration namelist
+      IF( lwm.AND.numoni  /= -1 )   CLOSE( numoni          )   ! ice output namelist
+      IF( numevo_ice      /= -1 )   CLOSE( numevo_ice      )   ! ice variables (temp. evolution)
+      IF( numout          /=  6 )   CLOSE( numout          )   ! standard model output file
+      !
+      numout = 6                                     ! redefine numout in case it is used after this point...
+      !
+   END SUBROUTINE nemo_closefile
+
+
+   SUBROUTINE nemo_alloc
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_alloc  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!
+      !! ** Method  :
+      !!----------------------------------------------------------------------
+      USE diawri    , ONLY : dia_wri_alloc
+      USE dom_oce   , ONLY : dom_oce_alloc
+      USE bdy_oce   , ONLY : ln_bdy, bdy_oce_alloc
+      USE oce       ! mandatory for sea-ice because needed for bdy arrays
+      !
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      ierr =        dia_wri_alloc()
+      ierr = ierr + dom_oce_alloc()          ! ocean domain
+      ierr = ierr + oce_alloc    ()          ! (tsn...) needed for agrif and/or SI3 and bdy
+      ierr = ierr + bdy_oce_alloc()          ! bdy masks (incl. initialization)
+      !
+      CALL mpp_sum( 'nemogcm', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'nemo_alloc: unable to allocate standard ocean arrays' )
+      !
+   END SUBROUTINE nemo_alloc
+
+   SUBROUTINE nemo_set_cfctl(sn_cfctl, setto, for_all )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE nemo_set_cfctl  ***
+      !!
+      !! ** Purpose :   Set elements of the output control structure to setto.
+      !!                for_all should be .false. unless all areas are to be
+      !!                treated identically.
+      !!
+      !! ** Method  :   Note this routine can be used to switch on/off some
+      !!                types of output for selected areas but any output types
+      !!                that involve global communications (e.g. mpp_max, glob_sum)
+      !!                should be protected from selective switching by the
+      !!                for_all argument
+      !!----------------------------------------------------------------------
+      LOGICAL :: setto, for_all
+      TYPE(sn_ctl) :: sn_cfctl
+      !!----------------------------------------------------------------------
+      IF( for_all ) THEN
+         sn_cfctl%l_runstat = setto
+         sn_cfctl%l_trcstat = setto
+      ENDIF
+      sn_cfctl%l_oceout  = setto
+      sn_cfctl%l_layout  = setto
+      sn_cfctl%l_mppout  = setto
+      sn_cfctl%l_mpptop  = setto
+   END SUBROUTINE nemo_set_cfctl
+
+   !!======================================================================
+END MODULE nemogcm
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/sbcssm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/sbcssm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/sbcssm.F90	(revision 14097)
@@ -0,0 +1,319 @@
+MODULE sbcssm
+   !!======================================================================
+   !!                       ***  MODULE  sbcssm  ***
+   !! Off-line : interpolation of the physical fields
+   !!======================================================================
+   !! History :  3.4  ! 2012-03 (S. Alderson)  original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_ssm_init  : initialization, namelist read, and SAVEs control
+   !!   sbc_ssm       : Interpolation of the fields
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE c1d            ! 1D configuration: lk_c1d
+   USE dom_oce        ! ocean domain: variables
+   USE zdf_oce        ! ocean vertical physics: variables
+   USE sbc_oce        ! surface module: variables
+   USE phycst         ! physical constants
+   USE eosbn2         ! equation of state - Brunt Vaisala frequency
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE zpshde         ! z-coord. with partial steps: horizontal derivatives
+   USE closea         ! for ln_closea
+   !
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O library
+   USE lib_mpp        ! distributed memory computing library
+   USE prtctl         ! print control
+   USE fldread        ! read input fields 
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_ssm_init   ! called by sbc_init
+   PUBLIC   sbc_ssm        ! called by sbc
+
+   CHARACTER(len=100) ::   cn_dir        ! Root directory for location of ssm files
+   LOGICAL            ::   ln_3d_uve     ! specify whether input velocity data is 3D
+   LOGICAL            ::   ln_read_frq   ! specify whether we must read frq or not
+   
+   LOGICAL            ::   l_sasread     ! Ice intilisation: =T read a file ; =F anaytical initilaistion
+   LOGICAL            ::   l_initdone = .false.
+   INTEGER     ::   nfld_3d
+   INTEGER     ::   nfld_2d
+
+   INTEGER     ::   jf_tem         ! index of temperature
+   INTEGER     ::   jf_sal         ! index of salinity
+   INTEGER     ::   jf_usp         ! index of u velocity component
+   INTEGER     ::   jf_vsp         ! index of v velocity component
+   INTEGER     ::   jf_ssh         ! index of sea surface height
+   INTEGER     ::   jf_e3t         ! index of first T level thickness
+   INTEGER     ::   jf_frq         ! index of fraction of qsr absorbed in the 1st T level
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) :: sf_ssm_3d  ! structure of input fields (file information, fields read)
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) :: sf_ssm_2d  ! structure of input fields (file information, fields read)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE sbc_ssm( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ssm  ***
+      !!
+      !! ** Purpose :  Prepares dynamics and physics fields from a NEMO run
+      !!               for an off-line simulation using surface processes only
+      !!
+      !! ** Method : calculates the position of data 
+      !!             - interpolates data if needed
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      REAL(wp) ::   ztinta     ! ratio applied to after  records when doing time interpolation
+      REAL(wp) ::   ztintb     ! ratio applied to before records when doing time interpolation
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start( 'sbc_ssm')
+     
+      IF ( l_sasread ) THEN
+         IF( nfld_3d > 0 ) CALL fld_read( kt, 1, sf_ssm_3d )      !==   read data at kt time step   ==!
+         IF( nfld_2d > 0 ) CALL fld_read( kt, 1, sf_ssm_2d )      !==   read data at kt time step   ==!
+         ! 
+         IF( ln_3d_uve ) THEN
+            IF( .NOT. ln_linssh ) THEN
+               e3t_m(:,:) = sf_ssm_3d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor 
+            ELSE
+               e3t_m(:,:) = e3t_0(:,:,1)                                 ! vertical scale factor
+            ENDIF
+            ssu_m(:,:) = sf_ssm_3d(jf_usp)%fnow(:,:,1) * umask(:,:,1)    ! u-velocity
+            ssv_m(:,:) = sf_ssm_3d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity 
+         ELSE
+            IF( .NOT. ln_linssh ) THEN
+               e3t_m(:,:) = sf_ssm_2d(jf_e3t)%fnow(:,:,1) * tmask(:,:,1) ! vertical scale factor 
+            ELSE
+               e3t_m(:,:) = e3t_0(:,:,1)                                 ! vertical scale factor
+            ENDIF
+            ssu_m(:,:) = sf_ssm_2d(jf_usp)%fnow(:,:,1) * umask(:,:,1)    ! u-velocity
+            ssv_m(:,:) = sf_ssm_2d(jf_vsp)%fnow(:,:,1) * vmask(:,:,1)    ! v-velocity 
+         ENDIF
+         !
+         sst_m(:,:) = sf_ssm_2d(jf_tem)%fnow(:,:,1) * tmask(:,:,1)    ! temperature
+         sss_m(:,:) = sf_ssm_2d(jf_sal)%fnow(:,:,1) * tmask(:,:,1)    ! salinity
+         ssh_m(:,:) = sf_ssm_2d(jf_ssh)%fnow(:,:,1) * tmask(:,:,1)    ! sea surface height
+         IF( ln_read_frq ) THEN
+            frq_m(:,:) = sf_ssm_2d(jf_frq)%fnow(:,:,1) * tmask(:,:,1) ! solar penetration
+         ELSE
+            frq_m(:,:) = 1._wp
+         ENDIF
+      ELSE
+         sss_m(:,:) = 35._wp                             ! =35. to obtain a physical value for the freezing point
+         CALL eos_fzp( sss_m(:,:), sst_m(:,:) )          ! sst_m is set at the freezing point
+         ssu_m(:,:) = 0._wp
+         ssv_m(:,:) = 0._wp
+         ssh_m(:,:) = 0._wp
+         IF( .NOT. ln_linssh ) e3t_m(:,:) = e3t_0(:,:,1) !clem: necessary at least for sas2D
+         frq_m(:,:) = 1._wp                              !              - -
+         sshn (:,:) = 0._wp                              !              - -
+      ENDIF
+      
+      IF ( nn_ice == 1 ) THEN
+         tsn(:,:,1,jp_tem) = sst_m(:,:)
+         tsn(:,:,1,jp_sal) = sss_m(:,:)
+         tsb(:,:,1,jp_tem) = sst_m(:,:)
+         tsb(:,:,1,jp_sal) = sss_m(:,:)
+      ENDIF
+      ub (:,:,1) = ssu_m(:,:)
+      vb (:,:,1) = ssv_m(:,:)
+ 
+      IF(ln_ctl) THEN                  ! print control
+         CALL prt_ctl(tab2d_1=sst_m, clinfo1=' sst_m   - : ', mask1=tmask   )
+         CALL prt_ctl(tab2d_1=sss_m, clinfo1=' sss_m   - : ', mask1=tmask   )
+         CALL prt_ctl(tab2d_1=ssu_m, clinfo1=' ssu_m   - : ', mask1=umask   )
+         CALL prt_ctl(tab2d_1=ssv_m, clinfo1=' ssv_m   - : ', mask1=vmask   )
+         CALL prt_ctl(tab2d_1=ssh_m, clinfo1=' ssh_m   - : ', mask1=tmask   )
+         IF( .NOT.ln_linssh )   CALL prt_ctl(tab2d_1=ssh_m, clinfo1=' e3t_m   - : ', mask1=tmask   )
+         IF( ln_read_frq    )   CALL prt_ctl(tab2d_1=frq_m, clinfo1=' frq_m   - : ', mask1=tmask   )
+      ENDIF
+      !
+      IF( l_initdone ) THEN          !   Mean value at each nn_fsbc time-step   !
+         CALL iom_put( 'ssu_m', ssu_m )
+         CALL iom_put( 'ssv_m', ssv_m )
+         CALL iom_put( 'sst_m', sst_m )
+         CALL iom_put( 'sss_m', sss_m )
+         CALL iom_put( 'ssh_m', ssh_m )
+         IF( .NOT.ln_linssh )   CALL iom_put( 'e3t_m', e3t_m )
+         IF( ln_read_frq    )   CALL iom_put( 'frq_m', frq_m )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop( 'sbc_ssm')
+      !
+   END SUBROUTINE sbc_ssm
+
+
+   SUBROUTINE sbc_ssm_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ssm_init  ***
+      !!
+      !! ** Purpose :   Initialisation of sea surface mean data     
+      !!----------------------------------------------------------------------
+      INTEGER  :: ierr, ierr0, ierr1, ierr2, ierr3   ! return error code
+      INTEGER  :: ifpr                               ! dummy loop indice
+      INTEGER  :: inum, idv, idimv, jpm              ! local integer
+      INTEGER  ::   ios                              ! Local integer output status for namelist read
+      !!
+      CHARACTER(len=100)                     ::  cn_dir       ! Root directory for location of core files
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) ::  slf_3d       ! array of namelist information on the fields to read
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) ::  slf_2d       ! array of namelist information on the fields to read
+      TYPE(FLD_N) ::   sn_tem, sn_sal                     ! information about the fields to be read
+      TYPE(FLD_N) ::   sn_usp, sn_vsp
+      TYPE(FLD_N) ::   sn_ssh, sn_e3t, sn_frq
+      !!
+      NAMELIST/namsbc_sas/ l_sasread, cn_dir, ln_3d_uve, ln_read_frq,   &
+         &                 sn_tem, sn_sal, sn_usp, sn_vsp, sn_ssh, sn_e3t, sn_frq
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_rstart .AND. nn_components == jp_iam_sas )   RETURN
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'sbc_ssm_init : sea surface mean data initialisation '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+      !
+      REWIND( numnam_ref )              ! Namelist namsbc_sas in reference namelist : Input fields
+      READ  ( numnam_ref, namsbc_sas, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namsbc_sas in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist namsbc_sas in configuration namelist : Input fields
+      READ  ( numnam_cfg, namsbc_sas, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namsbc_sas in configuration namelist' )
+      IF(lwm) WRITE ( numond, namsbc_sas )
+      !           
+      IF(lwp) THEN                              ! Control print
+         WRITE(numout,*) '   Namelist namsbc_sas'
+         WRITE(numout,*) '      Initialisation using an input file                                 l_sasread   = ', l_sasread 
+         WRITE(numout,*) '      Are we supplying a 3D u,v and e3 field                             ln_3d_uve   = ', ln_3d_uve
+         WRITE(numout,*) '      Are we reading frq (fraction of qsr absorbed in the 1st T level)   ln_read_frq = ', ln_read_frq
+      ENDIF
+      !
+      !! switch off stuff that isn't sensible with a standalone module
+      !! note that we need sbc_ssm called first in sbc
+      !
+      IF( ln_apr_dyn ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   No atmospheric gradient needed with StandAlone Surface scheme'
+         ln_apr_dyn = .FALSE.
+      ENDIF
+      IF( ln_rnf ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   No runoff needed with StandAlone Surface scheme'
+         ln_rnf = .FALSE.
+      ENDIF
+      IF( ln_ssr ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   No surface relaxation needed with StandAlone Surface scheme'
+         ln_ssr = .FALSE.
+      ENDIF
+      IF( nn_fwb > 0 ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   No freshwater budget adjustment needed with StandAlone Surface scheme'
+         nn_fwb = 0
+      ENDIF
+      IF( ln_closea ) THEN
+         IF( lwp ) WRITE(numout,*) '         ==>>>   No closed seas adjustment needed with StandAlone Surface scheme'
+         ln_closea = .false.
+      ENDIF
+      
+      !                  
+      IF( l_sasread ) THEN                       ! store namelist information in an array
+         ! 
+         !! following code is a bit messy, but distinguishes between when u,v are 3d arrays and
+         !! when we have other 3d arrays that we need to read in
+         !! so if a new field is added i.e. jf_new, just give it the next integer in sequence
+         !! for the corresponding dimension (currently if ln_3d_uve is true, 4 for 2d and 3 for 3d,
+         !! alternatively if ln_3d_uve is false, 6 for 2d and 1 for 3d), reset nfld_3d, nfld_2d,
+         !! and the rest of the logic should still work
+         !
+         jf_tem = 1   ;   jf_ssh = 3   ! default 2D fields index
+         jf_sal = 2   ;   jf_frq = 4   !
+         !
+         IF( ln_3d_uve ) THEN
+            jf_usp = 1   ;   jf_vsp = 2   ;   jf_e3t = 3     ! define 3D fields index
+            nfld_3d  = 2 + COUNT( (/.NOT.ln_linssh/) )       ! number of 3D fields to read
+            nfld_2d  = 3 + COUNT( (/ln_read_frq/) )          ! number of 2D fields to read
+         ELSE
+            jf_usp = 4   ;   jf_e3t = 6                      ! update 2D fields index
+            jf_vsp = 5   ;   jf_frq = 6 + COUNT( (/.NOT.ln_linssh/) )
+            !
+            nfld_3d  = 0                                     ! no 3D fields to read
+            nfld_2d  = 5 + COUNT( (/.NOT.ln_linssh/) ) + COUNT( (/ln_read_frq/) )    ! number of 2D fields to read
+         ENDIF
+         !
+         IF( nfld_3d > 0 ) THEN
+            ALLOCATE( slf_3d(nfld_3d), STAT=ierr )         ! set slf structure
+            IF( ierr > 0 ) THEN
+               CALL ctl_stop( 'sbc_ssm_init: unable to allocate slf 3d structure' )   ;   RETURN
+            ENDIF
+            slf_3d(jf_usp) = sn_usp
+            slf_3d(jf_vsp) = sn_vsp
+            IF( .NOT.ln_linssh )   slf_3d(jf_e3t) = sn_e3t
+         ENDIF
+         !
+         IF( nfld_2d > 0 ) THEN
+            ALLOCATE( slf_2d(nfld_2d), STAT=ierr )         ! set slf structure
+            IF( ierr > 0 ) THEN
+               CALL ctl_stop( 'sbc_ssm_init: unable to allocate slf 2d structure' )   ;   RETURN
+            ENDIF
+            slf_2d(jf_tem) = sn_tem   ;   slf_2d(jf_sal) = sn_sal   ;   slf_2d(jf_ssh) = sn_ssh
+            IF( ln_read_frq )   slf_2d(jf_frq) = sn_frq
+            IF( .NOT. ln_3d_uve ) THEN
+               slf_2d(jf_usp) = sn_usp ; slf_2d(jf_vsp) = sn_vsp
+               IF( .NOT.ln_linssh )   slf_2d(jf_e3t) = sn_e3t
+            ENDIF
+         ENDIF
+         !
+         ierr1 = 0    ! default definition if slf_?d(ifpr)%ln_tint = .false. 
+         IF( nfld_3d > 0 ) THEN
+            ALLOCATE( sf_ssm_3d(nfld_3d), STAT=ierr )         ! set sf structure
+            IF( ierr > 0 ) THEN
+               CALL ctl_stop( 'sbc_ssm_init: unable to allocate sf structure' )   ;   RETURN
+            ENDIF
+            DO ifpr = 1, nfld_3d
+                                            ALLOCATE( sf_ssm_3d(ifpr)%fnow(jpi,jpj,jpk)    , STAT=ierr0 )
+               IF( slf_3d(ifpr)%ln_tint )   ALLOCATE( sf_ssm_3d(ifpr)%fdta(jpi,jpj,jpk,2)  , STAT=ierr1 )
+               IF( ierr0 + ierr1 > 0 ) THEN
+                  CALL ctl_stop( 'sbc_ssm_init : unable to allocate sf_ssm_3d array structure' )   ;   RETURN
+               ENDIF
+            END DO
+            !                                         ! fill sf with slf_i and control print
+            CALL fld_fill( sf_ssm_3d, slf_3d, cn_dir, 'sbc_ssm_init', '3D Data in file', 'namsbc_ssm' )
+         ENDIF
+         !
+         IF( nfld_2d > 0 ) THEN
+            ALLOCATE( sf_ssm_2d(nfld_2d), STAT=ierr )         ! set sf structure
+            IF( ierr > 0 ) THEN
+               CALL ctl_stop( 'sbc_ssm_init: unable to allocate sf 2d structure' )   ;   RETURN
+            ENDIF
+            DO ifpr = 1, nfld_2d
+                                            ALLOCATE( sf_ssm_2d(ifpr)%fnow(jpi,jpj,1)    , STAT=ierr0 )
+               IF( slf_2d(ifpr)%ln_tint )   ALLOCATE( sf_ssm_2d(ifpr)%fdta(jpi,jpj,1,2)  , STAT=ierr1 )
+               IF( ierr0 + ierr1 > 0 ) THEN
+                  CALL ctl_stop( 'sbc_ssm_init : unable to allocate sf_ssm_2d array structure' )   ;   RETURN
+               ENDIF
+            END DO
+            !
+            CALL fld_fill( sf_ssm_2d, slf_2d, cn_dir, 'sbc_ssm_init', '2D Data in file', 'namsbc_ssm' )
+         ENDIF
+         !
+         IF( nfld_3d > 0 )   DEALLOCATE( slf_3d, STAT=ierr )
+         IF( nfld_2d > 0 )   DEALLOCATE( slf_2d, STAT=ierr )
+         !
+      ENDIF
+      !
+      CALL sbc_ssm( nit000 )   ! need to define ss?_m arrays used in iceistate
+      l_initdone = .TRUE.
+      !
+   END SUBROUTINE sbc_ssm_init
+
+   !!======================================================================
+END MODULE sbcssm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/step.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/step.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/step.F90	(revision 14097)
@@ -0,0 +1,158 @@
+MODULE step
+   !!======================================================================
+   !!                       ***  MODULE step  ***
+   !! Time-stepping    : manager of the ocean, tracer and ice time stepping
+   !!                    version for standalone surface scheme
+   !!======================================================================
+   !! History :  OPA  !  1991-03  (G. Madec)  Original code
+   !!             .   !    .                                                     
+   !!             .   !    .                                                     
+   !!   NEMO     3.5  !  2012-03  (S. Alderson)
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   stp             : OPA system time-stepping
+   !!----------------------------------------------------------------------
+   USE oce              ! ocean dynamics and tracers variables
+   USE dom_oce          ! ocean space and time domain variables 
+   USE daymod           ! calendar                         (day     routine)
+   USE sbc_oce          ! surface boundary condition: fields
+   USE sbcmod           ! surface boundary condition       (sbc     routine)
+   USE sbcrnf           ! surface boundary condition: runoff variables
+   USE sbccpl           ! surface boundary condition: coupled interface
+   USE eosbn2           ! equation of state                (eos_bn2 routine)
+   USE diawri           ! Standard run outputs             (dia_wri routine)
+   USE bdy_oce   , ONLY: ln_bdy
+   USE bdydta           ! mandatory for sea-ice
+   USE stpctl           ! time stepping control            (stp_ctl routine)
+   !
+   USE in_out_manager   ! I/O manager
+   USE prtctl           ! Print control                    (prt_ctl routine)
+   USE iom              !
+   USE lbclnk           !
+   USE timing           ! Timing            
+#if defined key_iomput
+   USE xios
+#endif
+
+#if defined key_agrif
+   USE agrif_oce, ONLY: lk_agrif_debug
+#if defined key_si3
+   USE agrif_ice_update
+#endif
+#endif
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   stp   ! called by nemogcm.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if defined key_agrif
+   RECURSIVE SUBROUTINE stp( )
+      INTEGER             ::   kstp   ! ocean time-step index
+#else
+   SUBROUTINE stp( kstp )
+      INTEGER, INTENT(in) ::   kstp   ! ocean time-step index
+#endif
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE stp  ***
+      !!                      
+      !! ** Purpose : - Time stepping of SBC (surface boundary)
+      !! 
+      !! ** Method  : -1- Update forcings and data  
+      !!              -2- Outputs and diagnostics
+      !!----------------------------------------------------------------------
+      INTEGER ::   indic    ! error indicator if < 0
+      !! ---------------------------------------------------------------------
+
+#if defined key_agrif
+      IF( nstop > 0 ) return   ! avoid to go further if an error was detected during previous time step 
+      kstp = nit000 + Agrif_Nb_Step()
+      IF ( lk_agrif_debug ) THEN
+         IF ( Agrif_Root() .and. lwp) Write(*,*) '---'
+         IF (lwp) Write(*,*) 'Grid Number',Agrif_Fixed(),' time step ',kstp, 'int tstep',Agrif_NbStepint()
+      ENDIF
+
+      IF ( kstp == (nit000 + 1) ) lk_agrif_fstep = .FALSE.
+
+# if defined key_iomput
+      IF( Agrif_Nbstepint() == 0 )   CALL iom_swap( cxios_context )
+# endif   
+#endif   
+                             indic = 0                    ! although indic is not changed in stp_ctl
+                                                          ! need to keep the same interface 
+      IF( kstp == nit000 )   CALL iom_init( cxios_context ) ! iom_put initialization (must be done after nemo_init for AGRIF+XIOS+OASIS)
+      IF( kstp /= nit000 )   CALL day( kstp )             ! Calendar (day was already called at nit000 in day_init)
+                             CALL iom_setkt( kstp - nit000 + 1, cxios_context )   ! tell iom we are at time step kstp
+
+      ! ==> clem: open boundaries is mandatory for sea-ice because ice BDY is not decoupled from  
+      !           the environment of ocean BDY. Therefore bdy is called in both OPA and SAS modules.
+      !           From SAS: ocean bdy data are wrong  (but we do not care) and ice bdy data are OK.  
+      !           This is not clean and should be changed in the future. 
+      IF( ln_bdy     )       CALL bdy_dta ( kstp, kt_offset=+1 )   ! update dynamic & tracer data at open boundaries
+      ! ==>
+                             CALL sbc    ( kstp )         ! Sea Boundary Condition (including sea-ice)
+
+                             CALL dia_wri( kstp )         ! ocean model: outputs
+
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF recursive integration
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+                             CALL Agrif_Integrate_ChildGrids( stp )  
+#endif                 
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Control
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+                             CALL stp_ctl( kstp, indic )
+      IF( indic < 0  )  THEN
+                             CALL ctl_stop( 'step: indic < 0' )
+                             CALL dia_wri_state( 'output.abort' )
+      ENDIF
+#if defined key_agrif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! AGRIF update
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<      
+      IF( Agrif_NbStepint() == 0 .AND. nstop == 0 ) THEN                       ! AGRIF Update from zoom N to zoom 1 then to Parent 
+#if defined key_si3
+                             CALL Agrif_Update_ice( )   ! update sea-ice
+#endif
+      ENDIF
+#endif
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! File manipulation at the end of the first time step
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                         
+      IF( kstp == nit000   ) CALL iom_close( numror )                          ! close input  ocean restart file
+      
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Coupled mode
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( lk_oasis    )  CALL sbc_cpl_snd( kstp )     ! coupled mode : field exchanges if OASIS-coupled ice
+
+#if defined key_iomput
+      IF( kstp == nitrst ) THEN
+         IF(.NOT.lwxios) THEN
+            CALL iom_close( numrow )     
+         ELSE
+            CALL iom_context_finalize( cwxios_context )
+         ENDIF
+         lrst_oce = .FALSE.
+      ENDIF
+      IF( kstp == nitend .OR. indic < 0 ) THEN
+                             CALL iom_context_finalize( cxios_context ) ! needed for XIOS+AGRIF
+      ENDIF
+#endif
+      !
+      IF( ln_timing .AND.  kstp == nit000  )   CALL timing_reset
+      !
+   END SUBROUTINE stp
+
+   !!======================================================================
+END MODULE step
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/stpctl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/stpctl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/SAS/stpctl.F90	(revision 14097)
@@ -0,0 +1,117 @@
+MODULE stpctl
+   !!======================================================================
+   !!                       ***  MODULE  stpctl  ***
+   !! Ocean run control :  gross check of the ocean time stepping
+   !!                      version for standalone surface scheme
+   !!======================================================================
+   !! History :  OPA  ! 1991-03  (G. Madec) Original code
+   !!            6.0  ! 1992-06  (M. Imbard)
+   !!            8.0  ! 1997-06  (A.M. Treguier)
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            2.0  ! 2009-07  (G. Madec)  Add statistic for time-spliting
+   !!            3.5  ! 2012-03  (S. Alderson)
+   !!            4.0  ! 2017-04  (G. Madec)  regroup global communications
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   stp_ctl      : Control the run
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables 
+   USE ice      , ONLY : vt_i, u_ice, tm_i
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! distributed memory computing
+
+   USE netcdf          ! NetCDF library
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC stp_ctl           ! routine called by step.F90
+
+   INTEGER  ::   idrun, idtime, idssh, idu, ids, istatus
+   !!----------------------------------------------------------------------
+   !! NEMO/SAS 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE stp_ctl( kt, kindic )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE stp_ctl  ***
+      !!                     
+      !! ** Purpose :   Control the run
+      !!
+      !! ** Method  : - Save the time step in numstp
+      !!              - Print it each 50 time steps
+      !!
+      !! ** Actions :   "time.step" file = last ocean time-step
+      !!                "run.stat"  file = run statistics
+      !!                
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in    ) ::   kt       ! ocean time-step index
+      INTEGER, INTENT( inout ) ::   kindic   ! indicator of solver convergence
+      !!
+      REAL(wp), DIMENSION(3) ::   zmax
+      LOGICAL                ::   ll_wrtstp, ll_colruns, ll_wrtruns
+      CHARACTER(len=20) :: clname
+      !!----------------------------------------------------------------------
+      !
+      ll_wrtstp  = ( MOD( kt-nit000, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend )
+      ll_colruns = ll_wrtstp .AND. sn_cfctl%l_runstat .AND. jpnij > 1 
+      ll_wrtruns = ( ll_colruns .OR. jpnij == 1 ) .AND. lwm
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'stp_ctl : time-stepping control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !                                ! open time.step file
+         IF( lwm ) CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+         !                                ! open run.stat file(s) at start whatever
+         !                                ! the value of sn_cfctl%ptimincr
+         IF( ll_wrtruns ) THEN
+            CALL ctl_opn( numrun, 'run.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            clname = 'run.stat.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( 'run.stat.nc', NF90_CLOBBER, idrun )
+            istatus = NF90_DEF_DIM( idrun, 'time'     , NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( idrun, 'vt_i_max' , NF90_DOUBLE, (/ idtime /), idssh )
+            istatus = NF90_DEF_VAR( idrun, 'abs_u_max', NF90_DOUBLE, (/ idtime /), idu )
+            istatus = NF90_DEF_VAR( idrun, 'tm_i_min' , NF90_DOUBLE, (/ idtime /), ids )
+            istatus = NF90_ENDDEF(idrun)
+         ENDIF
+      ENDIF
+      !
+      IF(lwm .AND. ll_wrtstp) THEN        !==  current time step  ==!   ("time.step" file)
+         WRITE ( numstp, '(1x, i8)' )   kt
+         REWIND( numstp )
+      ENDIF
+      !                                   !==  test of extrema  ==!
+      IF( ll_colruns .OR. jpnij == 1 ) THEN
+         zmax(1) = MAXVAL(      vt_i (:,:) )                                           ! max ice thickness
+         zmax(2) = MAXVAL( ABS( u_ice(:,:) ) )                                         ! max ice velocity (zonal only)
+         zmax(3) = MAXVAL(     -tm_i (:,:)+273.15_wp , mask = ssmask(:,:) == 1._wp )   ! min ice temperature
+         IF( ll_colruns )   CALL mpp_max( "stpctl", zmax )                             ! max over the global domain
+      END IF
+      !                                            !==  run statistics  ==!   ("run.stat" file)
+      IF( ll_wrtruns ) THEN
+         WRITE(numrun,9500) kt, zmax(1), zmax(2), - zmax(3)
+         istatus = NF90_PUT_VAR( idrun, idssh, (/ zmax(1)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,   idu, (/ zmax(2)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,   ids, (/-zmax(3)/), (/kt/), (/1/) )
+         IF( MOD( kt , 100 ) == 0 ) istatus = NF90_SYNC(idrun)
+         IF( kt == nitend         ) istatus = NF90_CLOSE(idrun)
+      END IF
+      !
+9500  FORMAT(' it :', i8, '    vt_i_max: ', D23.16, ' |u|_max: ', D23.16,' tm_i_min: ', D23.16)
+      !
+   END SUBROUTINE stp_ctl
+
+   !!======================================================================
+END MODULE stpctl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/par_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/par_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/par_age.F90	(revision 14097)
@@ -0,0 +1,17 @@
+MODULE par_age
+   !!======================================================================
+   !!                        ***  par_age  ***
+   !! TOP :   set the AGE parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+   IMPLICIT NONE
+
+   INTEGER, PUBLIC  :: jp_age    !: number of passive tracers in PISCES
+
+   !!======================================================================
+END MODULE par_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcice_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcice_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcice_age.F90	(revision 14097)
@@ -0,0 +1,31 @@
+MODULE trcice_age
+   !!======================================================================
+   !!                         ***  MODULE trcice_age  ***
+   !!======================================================================
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_age       ! called by trcice.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_age
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ice_ageb  ***
+      !!
+      !!----------------------------------------------------------------------
+      !
+      !
+   END SUBROUTINE trc_ice_ini_age
+
+   !!======================================================================
+END MODULE trcice_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcini_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcini_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcini_age.F90	(revision 14097)
@@ -0,0 +1,64 @@
+MODULE trcini_age
+   !!======================================================================
+   !!                         ***  MODULE trcini_age  ***
+   !! TOP :   initialisation of the AGE tracer
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (G. Nurser, G. Madec, C. Ethe ) Original code
+   !!----------------------------------------------------------------------
+   !! trc_ini_age   : MY_TRC model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc
+   USE trc
+   USE trcnam_age
+   USE trcsms_age
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_age   ! called by trcini.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_age
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_age  ***  
+      !!
+      !! ** Purpose :   initialization for AGE model
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER    ::  jn
+      CHARACTER(len = 20)  ::  cltra
+      !!----------------------------------------------------------------------
+      !
+      CALL trc_nam_age
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_age: passive tracer age'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*)
+
+      rryear  = 1._wp / ( nyear_len(1) * rday )    ! recip number of seconds in one year
+
+      !! BUG in s-coordinate this does not work!
+      nlb_age = MINLOC( gdepw_1d, mask = gdepw_1d > rn_age_depth, dim = 1 ) ! shallowest W level Below age_depth
+                                                                            !  = shallowest T level wholly below age_depth
+      nl_age  = nlb_age - 1                                                 ! deepest    W level Above age_depth
+                                                                            !  = T level surrounding age_depth
+
+      nla_age = nl_age - 1                                                   ! deepest    T level wholly above age_depth
+
+      frac_kill_age = ( rn_age_depth - gdepw_1d(nl_age) ) / e3t_1d(nl_age)      ! fraction of level nl_age above age_depth
+      frac_add_age  = 1._wp -  frac_kill_age                                    ! fraction of level nl_age below age_depth
+
+      
+      IF( .NOT. ln_rsttr ) trn(:,:,:,jp_age) = 0.
+      !
+   END SUBROUTINE trc_ini_age
+
+   !!======================================================================
+END MODULE trcini_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcnam_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcnam_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcnam_age.F90	(revision 14097)
@@ -0,0 +1,74 @@
+MODULE trcnam_age
+   !!======================================================================
+   !!                         ***  MODULE trcnam_age  ***
+   !! TOP :   initialisation of some run parameters for Age tracer
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) 
+   !!----------------------------------------------------------------------
+   !! trc_nam_age      : AGE tracer initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trc             ! Ocean variables
+   USE trcsms_age      ! AGE specific variable
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_age   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_nam_age
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_nam_age  ***
+      !!                 
+      !! ** Purpose :   Definition some run parameter for AGE model
+      !!
+      !! ** input   :   Namelist namage
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namage/ rn_age_depth, rn_age_kill_rate 
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' Sea Age Tracer'
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_nam_age : Read namage namelist for Age passive tracer'
+         WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+
+      ! Variable setting
+      ctrcnm    (jp_age) = 'Age'
+      ctrcln    (jp_age) = 'Sea water age since surface contact'
+      ctrcun    (jp_age) = 'year'
+      ln_trc_ini(jp_age) = .false.
+      ln_trc_sbc(jp_age) = .false.
+      ln_trc_cbc(jp_age) = .false.
+      ln_trc_obc(jp_age) = .false.
+      !
+      REWIND( numnat_ref )              ! Namelist namagedate in reference namelist : AGE parameters
+      READ  ( numnat_ref, namage, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namage in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namagedate in configuration namelist : AGE parameters
+      READ  ( numnat_cfg, namage, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namage in configuration namelist' )
+      IF(lwm) WRITE ( numont, namage )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist : namage'
+         WRITE(numout,*) '      depth over which age tracer reset to zero     rn_age_depth      = ', rn_age_depth 
+         WRITE(numout,*) '      recip of relaxation timescale                 rn_age_kill_rate  = ', rn_age_kill_rate, '[s]'
+         WRITE(numout,*) '      (for age tracer shallower than age_depth) '
+      ENDIF
+      !
+   END SUBROUTINE trc_nam_age
+   
+   !!======================================================================
+END MODULE trcnam_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcsms_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcsms_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcsms_age.F90	(revision 14097)
@@ -0,0 +1,76 @@
+MODULE trcsms_age
+   !!======================================================================
+   !!                         ***  MODULE trcsms_age  ***
+   !! TOP :   Main module of the AGE tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!----------------------------------------------------------------------
+   !! trc_sms_age       : AGE model main routine
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+   USE trd_oce
+   USE trdtrc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_age       ! called by trcsms.F90 module
+
+   INTEGER , PUBLIC :: nl_age             ! T level surrounding age_depth
+   INTEGER , PUBLIC :: nla_age            ! T level wholly above age_depth
+   INTEGER , PUBLIC :: nlb_age            ! T level wholly below age_depth
+
+   REAL(wp), PUBLIC :: rn_age_depth       ! = 10       depth over which age tracer reset to zero
+   REAL(wp), PUBLIC :: rn_age_kill_rate   ! = -1./7200  recip of relaxation timescale (s) for  age tracer shallower than age_depth
+   
+   REAL(wp), PUBLIC :: rryear          !: recip number of seconds in one year
+   REAL(wp), PUBLIC :: frac_kill_age   !: fraction of level nl_age above age_depth where it is relaxed towards zero
+   REAL(wp), PUBLIC :: frac_add_age    !: fraction of level nl_age below age_depth where it is incremented
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_age( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_sms_age  ***
+      !!
+      !! ** Purpose :   main routine of AGE model
+      !!
+      !! ** Method  : -
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      INTEGER ::   jn, jk   ! dummy loop index
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sms_age')
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_sms_age:  AGE model'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+
+
+      DO jk = 1, nla_age
+         tra(:,:,jk,jp_age) = rn_age_kill_rate * trb(:,:,jk,jp_age)
+      END DO
+      !
+      tra(:,:,nl_age,jp_age) = frac_kill_age * rn_age_kill_rate * trb(:,:,nl_age,jp_age)  &
+          &                   + frac_add_age  * rryear * tmask(:,:,nl_age)
+      !
+      DO jk = nlb_age, jpk
+         tra(:,:,jk,jp_age) = tmask(:,:,jk) * rryear
+      END DO
+      !
+      IF( l_trdtrc ) CALL trd_trc( tra(:,:,:,jp_age), jn, jptra_sms, kt )   ! save trends
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sms_age')
+      !
+   END SUBROUTINE trc_sms_age
+
+   !!======================================================================
+END MODULE trcsms_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcwri_age.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcwri_age.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/AGE/trcwri_age.F90	(revision 14097)
@@ -0,0 +1,56 @@
+MODULE trcwri_age
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    age :   Output of age tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_top &&  defined key_iomput
+   !!----------------------------------------------------------------------
+   !! trc_wri_age   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE par_age     
+   USE trc         
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_age 
+
+CONTAINS
+
+   SUBROUTINE trc_wri_age
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+
+      ! write the tracer concentrations in the file
+
+      cltra = TRIM( ctrcnm(jp_age) )                  ! short title for tracer
+      CALL iom_put( cltra, trn(:,:,:,jp_age) )
+
+      !
+   END SUBROUTINE trc_wri_age
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_age
+CONTAINS
+   SUBROUTINE trc_wri_age                     ! Empty routine  
+   END SUBROUTINE trc_wri_age
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcwri_age
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/par_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/par_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/par_c14.F90	(revision 14097)
@@ -0,0 +1,13 @@
+MODULE par_c14
+   !!======================================================================
+   !!                        ***  par_c14 ***
+   !! TOP :   set the C14 parameters
+   !!======================================================================
+   !! History :   2.0  !  2008-12  (C. Ethe, G. Madec)  revised architecture
+   !! History :        !  2015 (A.Mouchet) equilibrium + transient C14
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   INTEGER, PUBLIC ::  jp_c14    !: number of c14 tracer
+
+END MODULE par_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/sms_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/sms_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/sms_c14.F90	(revision 14097)
@@ -0,0 +1,75 @@
+MODULE sms_c14
+   !!======================================================================
+   !!                      ***  MODULE trcsms_c14  ***
+   !! TOP :  C14 main module
+   !!======================================================================
+   !! History     -   ! 1994-05 ( J. Orr ) original code
+   !!            1.0  ! 2006-02 ( J.M. Molines )  Free form + modularity
+   !!            2.0  ! 2008-12 ( C. Ethe ) reorganisation
+   !!            4.0  ! 2011-02 ( A.R. Porter, STFC Daresbury ) Dynamic memory
+   !!                 ! 2015    (A. Mouchet) general C14 + update formulas
+   !!----------------------------------------------------------------------
+   !!   sms_c14 :  compute and add C14 suface forcing to C14 trends
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE par_trc
+
+
+   IMPLICIT NONE
+   PUBLIC  
+
+
+   LOGICAL  :: ln_chemh                             ! Chemical enhancement (yes/no)
+   INTEGER  :: kc14typ                              ! C14 tracer type
+   REAL(wp) :: tyrc14_beg                           ! year start atmospheric scenario !! See below
+   REAL(wp) :: pco2at, rc14at                       ! atm co2, atm 14C ratio (global, reference)
+   REAL(wp) :: rc14init                             ! ocean 14C ratio for initialization
+   REAL(wp) :: xkwind, xdicsur                      ! wind coeff, ref DIC
+   REAL(wp) :: rlam14                               ! C14 decay  rate
+
+   !
+   CHARACTER (len=20)                           :: cfileco2, cfilec14  ! Name of atmospheric forcing files
+   !
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)  ::   c14sbc   ! atmospheric c14 ratio
+   REAL(wp)                                     ::   co2sbc   ! atmospheric co2 pressure
+  
+   REAL(wp),  ALLOCATABLE, SAVE, DIMENSION(:,:) ::   exch_c14   ! exch. vel. for C14/C
+   REAL(wp),  ALLOCATABLE, SAVE, DIMENSION(:,:) ::   exch_co2   ! CO2 invasion rate
+   REAL(wp),  ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qtr_c14    ! flux at surface
+   REAL(wp),  ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qint_c14   ! cumulative flux
+
+   INTEGER , PARAMETER                          ::   nc14zon     = 3  ! number of zones for bomb c14
+   !
+   INTEGER                                       ::   nrecco2, nrecc14  ! nb record atm co2 & cc14
+   REAL(wp)                                      ::   tyrc14_now ! current yr for transient experiment relative to tyrc14_beg
+   INTEGER                                       ::   m1_co2, m1_c14  ! index of first co2 and c14 records to consider
+   INTEGER                                       ::   m2_co2, m2_c14  ! index of second co2 and c14 records to consider
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   bomb       ! C14 atm data (bomb - 3 zones)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   atmc14     ! C14 atm data (paleo - 1 zone)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   tyrc14     ! Time (yr) atmospheric C14 data
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   fareaz     ! Spatial Interpolation Factors
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   spco2      ! Atmospheric CO2
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:)     ::   tyrco2     ! Time (yr) atmospheric CO2 data
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+
+   INTEGER FUNCTION sms_c14_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_sms_c14_alloc  ***
+      !!----------------------------------------------------------------------
+      sms_c14_alloc = 0
+      ALLOCATE( exch_c14(jpi,jpj)        ,  exch_co2(jpi,jpj)        ,   &
+         &      qtr_c14(jpi,jpj)         ,  qint_c14(jpi,jpj)        ,   &
+         &      c14sbc(jpi,jpj)          ,  STAT = sms_c14_alloc )
+         !
+      !
+   END FUNCTION sms_c14_alloc
+
+  !!======================================================================
+END MODULE sms_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcatm_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcatm_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcatm_c14.F90	(revision 14097)
@@ -0,0 +1,302 @@
+MODULE trcatm_c14
+   !!======================================================================
+   !!                     ***  MODULE  trcatm_c14  ***
+   !! TOP :  read and manages atmospheric values for radiocarbon model  
+   !!=====================================================================
+   !! History: Based on trcini_c14b & trcsms_c14b : 
+   !!          Anne Mouchet
+   !!----------------------------------------------------------------------
+   !!   trc_atm_c14_ini  : initialize c14atm & pco2atm
+   !!   trc_atm_c14      : read and time interpolate  c14atm & pco2atm
+   !!----------------------------------------------------------------------
+   USE par_trc       !  passive tracers parameters
+   USE oce_trc       !  shared variables between ocean and passive tracers
+   USE trc           !  passive tracers common variables
+   USE sms_c14    ! c14 simulation type, atm default values...
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_atm_c14         ! called in trcsms_c14.F90
+   PUBLIC   trc_atm_c14_ini     ! called in trcini_c14.F90
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_atm_c14_ini
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_c14_ini  ***
+      !!                    
+      !! ** Purpose :   initialisation of sbc for radiocarbon
+      !! 
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      !
+      CHARACTER (len=20)        :: clfile                        ! forcing file name
+      INTEGER                   :: ji,jj,jn                        ! dummy loop indice
+      INTEGER                   :: ierr1,ierr2,ierr3,izco2         ! temporary integers
+      INTEGER                   :: inum1,inum2,incom,iyear         ! temporary integers
+      REAL(wp) ::   ys40 = -40.     ! 40 degrees south
+      REAL(wp) ::   ys20 = -20.     ! 20 degrees south
+      REAL(wp) ::   yn20 =  20.     ! 20 degrees north
+      REAL(wp) ::   yn40 =  40.     ! 40 degrees north
+      REAL(wp), ALLOCATABLE, DIMENSION(:)   :: zco2, zyrco2  ! temporary arrays for swap
+      !
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_atm_c14_ini')
+      !
+      
+      IF( lwp ) WRITE(numout,*) ' '
+      IF( lwp ) WRITE(numout,*) ' trc_atm_c14_ini : initialize atm CO2 & C14-ratio '
+      IF( lwp ) WRITE(numout,*) ' '
+      !
+      tyrc14_now = 0._wp   ! initialize
+      !
+      IF(kc14typ >= 1) THEN  ! Transient atmospheric forcing: CO2
+      !
+         clfile = TRIM( cfileco2 )
+         IF(lwp) WRITE(numout,*) 'Read CO2 atmospheric concentrations file ',clfile
+         CALL ctl_opn( inum1, clfile, 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+         REWIND(inum1)
+      
+         READ(inum1,*) nrecco2,incom
+         DO jn = 1, incom        ! Skip over descriptor lines
+            READ(inum1,'(1x)')
+         END DO
+         ALLOCATE( spco2(nrecco2), tyrco2(nrecco2)       , STAT=ierr1 )
+         IF( ierr1 /= 0 )   CALL ctl_stop( 'STOP', 'trc_atm_c14_ini: unable to allocate co2 arrays' )
+      ! get  CO2 data
+         DO jn = 1, nrecco2
+            READ(inum1, *)  tyrco2(jn), spco2(jn)
+         END DO
+         CLOSE(inum1)
+      !
+         IF(kc14typ==2) THEN
+            ALLOCATE( zco2(nrecco2), zyrco2(nrecco2) )
+            zco2(:)=spco2(:)
+            zyrco2(:)=tyrco2(:)
+      ! Set CO2 times on AD time scale & swap records : In CO2 file : youngest first
+            DO jn = 1, nrecco2
+               izco2=nrecco2-jn+1
+               spco2(izco2)=zco2(jn)
+               tyrco2(izco2)=1950._wp-zyrco2(jn)         ! BP to AD dates
+            END DO
+            DEALLOCATE( zco2,zyrco2 )
+         ENDIF
+      !
+      !        ! Transient atmospheric forcing: Bomb C14 & Paleo C14 : open file
+      !
+         clfile = TRIM( cfilec14 )
+         IF (lwp) WRITE(numout,*) 'Read C-14 atmospheric concentrations file ',clfile
+         CALL ctl_opn( inum2, clfile, 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+         REWIND(inum2)
+      !
+      ! Bomb C14: 3 zones for atm C14 !
+         IF(kc14typ == 1) THEN  ! Transient atmospheric forcing: Bomb C14
+      ! 
+            READ(inum2,*) nrecc14,incom
+            DO jn = 1, incom        ! Skip over descriptor lines
+               READ(inum2,'(1x)')
+            END DO
+            ALLOCATE( bomb(nrecc14,nc14zon), tyrc14(nrecc14)       , STAT=ierr2 )
+            IF( ierr2 /= 0 )   CALL ctl_stop( 'STOP', 'trc_atm_c14_ini: unable to allocate c14 arrays' )
+      ! get bomb c14 data
+            DO jn = 1, nrecc14
+               READ(inum2,*) tyrc14(jn), bomb(jn,1), bomb(jn,2), bomb(jn,3)
+            END DO
+            CLOSE(inum2)
+
+       ! Linear  interpolation of the C-14 source fonction
+       ! in linear latitude bands  (20N,40N) and (20S,40S)
+       !------------------------------------------------------
+            ALLOCATE( fareaz  (jpi,jpj ,nc14zon) , STAT=ierr3 )
+            IF( ierr3 /= 0 )   CALL ctl_stop( 'STOP', 'trc_atm_c14_ini: unable to allocate fareaz' )
+      !
+            DO jj = 1 , jpj                       ! from C14b package
+              DO ji = 1 , jpi
+                 IF( gphit(ji,jj) >= yn40 ) THEN
+                    fareaz(ji,jj,1) = 0.
+                    fareaz(ji,jj,2) = 0.
+                    fareaz(ji,jj,3) = 1.
+                 ELSE IF( gphit(ji,jj ) <= ys40) THEN
+                    fareaz(ji,jj,1) = 1.
+                    fareaz(ji,jj,2) = 0.
+                    fareaz(ji,jj,3) = 0.
+                 ELSE IF( gphit(ji,jj) >= yn20 ) THEN
+                    fareaz(ji,jj,1) = 0.
+                    fareaz(ji,jj,2) = 2. * ( 1. - gphit(ji,jj) / yn40 )
+                    fareaz(ji,jj,3) = 2. * gphit(ji,jj) / yn40 - 1.
+                 ELSE IF( gphit(ji,jj) <= ys20 ) THEN
+                    fareaz(ji,jj,1) = 2. * gphit(ji,jj) / ys40 - 1.
+                    fareaz(ji,jj,2) = 2. * ( 1. - gphit(ji,jj) / ys40 )
+                    fareaz(ji,jj,3) = 0.
+                 ELSE
+                    fareaz(ji,jj,1) = 0.
+                    fareaz(ji,jj,2) = 1.
+                    fareaz(ji,jj,3) = 0.
+                 ENDIF
+              END DO
+           END DO
+      !
+         ENDIF
+      !
+      ! Paleo C14: 1 zone for atm C14 !
+         IF(kc14typ == 2) THEN  ! Transient atmospheric forcing: Paleo C14
+      ! 
+            READ(inum2,*) nrecc14,incom
+            DO jn = 1, incom        ! Skip over descriptor lines
+               READ(inum2,'(1x)')
+            END DO
+            ALLOCATE( atmc14(nrecc14), tyrc14(nrecc14)       , STAT=ierr2 )
+            IF( ierr2 /= 0 )   CALL ctl_stop( 'STOP', 'trc_atm_c14_ini: unable to allocate c14 arrays' )
+      ! get past c14 data
+            DO jn = 1, nrecc14
+               READ(inum2,*) iyear,incom,incom,atmc14(jn)
+               tyrc14(jn)=1950._wp-REAL(iyear,wp)                ! BP to AD dates
+            END DO
+            CLOSE(inum2)
+      !
+         ENDIF
+      !
+      ! Note on dates: 
+      !   In files dates have dimension yr; either AD or BP; if BP date is changed into AD here
+      !   When dealing with dates previous to 0. AD one needs to set tyrc14_beg to the actual starting year
+      !   Do not forget to appropriately set nn_date0 and nn_rstctl in namelist
+      !                           AND        nn_rsttr in namelist_top  if offline run
+      !   All details are given in NEMO-C14.pdf report
+      !  
+         tyrc14_now=nyear                                ! actual initial yr - Bomb 
+         if(kc14typ == 2) tyrc14_now=nyear+tyrc14_beg-1  ! actual initial yr - Paleo
+      !                                     ! we suppose we start on tyrc14_now/01/01 @ 0h
+         m1_c14= 1
+         m1_co2= 1
+         DO jn = 1,nrecco2
+            IF ( tyrc14_now >= tyrco2(jn) ) m1_co2 = jn  ! index of first co2 record to consider
+         END DO
+         DO jn = 1,nrecc14
+            IF ( tyrc14_now >= tyrc14(jn) ) m1_c14 = jn  ! index of first c14 record to consider
+         END DO
+         IF (lwp) WRITE(numout,*) 'Initial yr for experiment', tyrc14_now
+         IF (lwp) WRITE(numout,*) '   CO2 & C14 start years:', tyrco2(m1_co2),tyrc14(m1_c14)
+      !
+         m2_c14= m1_c14
+         m2_co2= m1_co2
+      !
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_atm_c14_ini')
+      !
+   END SUBROUTINE trc_atm_c14_ini
+
+
+   SUBROUTINE trc_atm_c14( kt, co2sbc, c14sbc )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_flx  ***
+      !!                    
+      !! ** Purpose :   provides sbc for co2 & c14 at kt
+      !! 
+      !! ** Method  :  read files
+      !!
+      !! ** Action  :   atmospheric values interpolated at time-step kt
+      !!----------------------------------------------------------------------
+      INTEGER                 , INTENT(in   )   ::   kt       ! ocean time-step
+      REAL(wp), DIMENSION(:,:), INTENT(  out)   ::   c14sbc   ! atm c14 ratio
+      REAL(wp),                 INTENT(  out)   ::   co2sbc   ! atm co2 p
+      INTEGER                                   ::   jz       ! dummy loop indice
+      REAL(wp)                              ::   zdint,zint   ! work
+      REAL(wp), DIMENSION(nc14zon)              ::   zonbc14  ! work
+      !
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_atm_c14')
+      !
+      IF( kc14typ == 0) THEN
+         co2sbc=pco2at
+         c14sbc(:,:)=rc14at
+      ENDIF
+      !
+      IF(kc14typ >= 1) THEN  ! Transient C14 & CO2
+      !
+         tyrc14_now = tyrc14_now + ( rdt / ( rday * nyear_len(1)) )    !  current time step in yr relative to tyrc14_beg
+      !
+      ! CO2 --------------------------------------------------------
+      !
+      ! time interpolation of CO2 concentrations     ! if out of record keeps first/last value
+         IF( tyrc14_now > tyrco2(m2_co2) ) THEN     ! next interval
+           m1_co2 = m2_co2
+           m2_co2 = MIN ( m2_co2 + 1 , nrecco2 )
+         ENDIF
+      !
+         zdint  = tyrco2(m2_co2) - tyrco2(m1_co2)
+         co2sbc = spco2(m2_co2)                        ! if out of record keeps first/last value
+         zint = 0._wp
+         IF ( zdint > 0._wp ) THEN                     ! if within record interpolate:
+            zint = ( tyrco2(m2_co2) - tyrc14_now ) / zdint
+            co2sbc = spco2(m2_co2) + zint * ( spco2(m1_co2) - spco2(m2_co2) )
+         ENDIF
+      !
+         IF( lwp .AND.  kt == nitend )  THEN
+            WRITE(numout, '(3(A,F12.4))') 't1/tn/t2:',tyrco2(m1_co2),'/', tyrc14_now,'/',tyrco2(m2_co2)
+            WRITE(numout, *) 'CO2:',spco2(m1_co2),co2sbc ,spco2(m2_co2)
+         ENDIF
+      !
+      ! C14 --------------------------------------------------------
+      !
+      ! time interpolation of C14 concentrations 
+         IF ( tyrc14_now > tyrc14(m2_c14) ) THEN     ! next interval
+           m1_c14 = m2_c14
+           m2_c14 = MIN ( m2_c14 + 1 , nrecc14 )
+         ENDIF
+         zdint = tyrc14(m2_c14) - tyrc14(m1_c14)
+         zint=0._wp
+         IF ( zdint > 0._wp ) zint = ( tyrc14(m2_c14) - tyrc14_now ) / zdint ! if  within record
+         IF( lwp .AND.  kt == nitend )  &
+            &     WRITE(numout,'(3(A,F12.4))') 't1/tn/t2:',tyrc14(m1_c14),'/', tyrc14_now,'/',tyrc14(m2_c14)
+      !
+      ! ------- Bomb C14  ------------------------------------------
+      !
+         IF( kc14typ == 1) THEN
+      !                                          ! time interpolation
+          zonbc14(:) = bomb(m2_c14,:)                ! if out of record keeps first/last value
+      !                                          !    if within record interpolate:
+          IF ( zdint > 0._wp ) zonbc14(:) = bomb(m2_c14,:) + zint * ( bomb(m1_c14,:)  - bomb(m2_c14,:)  )
+      ! 
+            IF(lwp .AND.  kt == nitend )  &
+                 &      WRITE(numout, *)  'C14:',bomb(m1_c14,1),zonbc14(1),bomb(m2_c14,1)
+      !   Transform DeltaC14 --> C14 ratio
+            zonbc14(:) = 1._wp + zonbc14(:)/1.d03
+      !
+      !  For each (i,j)-box, with information from the fractional area
+      !  (zonmean), computes area-weighted mean to give the atmospheric C-14
+      !  ----------------------------------------------------------------
+            c14sbc(:,:) = zonbc14(1) * fareaz(:,:,1)   &
+               &          + zonbc14(2) * fareaz(:,:,2)   &
+               &          + zonbc14(3) * fareaz(:,:,3)
+         ENDIF
+      !
+      ! ------- Paleo C14  -----------------------------------------
+      !
+         IF( kc14typ == 2 ) THEN
+      !                                          ! time interpolation
+            zonbc14(1) = atmc14(m2_c14)          ! if out of record keeps first/last value
+         !                                       !    if within record interpolate:
+            IF ( zdint > 0._wp ) zonbc14(1) = atmc14(m2_c14) + zint * ( atmc14(m1_c14) - atmc14(m2_c14) )
+            IF(lwp .AND.  kt == nitend )  &
+                 &      WRITE(numout, *)  'C14: ',atmc14(m1_c14),zonbc14(1),atmc14(m2_c14)
+      !   Transform DeltaC14 --> C14 ratio
+            c14sbc(:,:) = 1._wp + zonbc14(1)/1.d03
+         ENDIF
+      !
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_atm_c14')
+      !
+   END SUBROUTINE trc_atm_c14
+
+   !!======================================================================
+END MODULE trcatm_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcice_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcice_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcice_c14.F90	(revision 14097)
@@ -0,0 +1,31 @@
+MODULE trcice_c14
+   !!======================================================================
+   !!                         ***  MODULE trcice_c14  ***
+   !!======================================================================
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_c14       ! called by trcice.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_c14
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ice_c14b  ***
+      !!
+      !!----------------------------------------------------------------------
+      !
+      !
+   END SUBROUTINE trc_ice_ini_c14
+
+   !!======================================================================
+END MODULE trcice_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcini_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcini_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcini_c14.F90	(revision 14097)
@@ -0,0 +1,97 @@
+MODULE trcini_c14
+   !!======================================================================
+   !!                         ***  MODULE trcini_c14  ***
+   !! TOP :   initialisation of the C14 tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !! History :   3.0  !  2015 (A. Mouchet) C14 Code
+   !!----------------------------------------------------------------------
+   !! trc_ini_c14   : C14 model initialisation
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc
+   USE trc
+   USE sms_c14
+   USE trcatm_c14
+   USE trcnam_c14
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_c14   ! called by trcini.F90 module
+   
+   !
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_c14
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_c14  ***  
+      !!
+      !! ** Purpose :   initialization for C14 model
+      !!
+      !! ** Method  : 
+      !!----------------------------------------------------------------------
+      !
+      REAL(wp) :: ztrai
+      INTEGER  :: jn
+      CHARACTER(len = 20)  ::  cltra
+      !!----------------------------------------------------------------------
+      !
+      CALL trc_nam_c14
+      !                       ! Allocate c14 arrays
+      IF( sms_c14_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_ini_c14: unable to allocate C14 arrays' )
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_c14: initialisation of C14 model'
+      !
+      IF( .NOT. ln_rsttr )  THEN
+         !
+         IF(lwp) WRITE(numout,*) '                      ==>    PRESCRIBED initial VALUES'
+         IF(lwp) WRITE(numout,*) '                      ==>    Ocean C14/C :', rc14init 
+         !
+         trn(:,:,:,jp_c14) = rc14init * tmask(:,:,:)
+         !
+         qtr_c14(:,:) = 0._wp           ! Init of air-sea BC
+         !
+      ELSE
+
+        IF(lwp) WRITE(numout,*)
+        IF(lwp) WRITE(numout,*) ' trc_rst_read_c14 : Read specific variables for c14 model '
+        IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+        ! 
+        CALL iom_get( numrtr, 'co2sbc', co2sbc ) 
+        CALL iom_get( numrtr, jpdom_autoglo, 'c14sbc', c14sbc ) 
+        CALL iom_get( numrtr, jpdom_autoglo, 'exch_co2', exch_co2 ) 
+        CALL iom_get( numrtr, jpdom_autoglo, 'exch_c14', exch_c14 ) 
+        CALL iom_get( numrtr, jpdom_autoglo, 'qtr_c14', qtr_c14 )
+        !
+      END IF
+      !
+      IF( ( nn_rsttr == 0 ) .OR. ( .NOT. ln_rsttr ) ) THEN
+      !
+      !                         !  qint set to zero <=== Initial of transient
+      !                         !                   <=== Restart=false
+         IF(lwp) WRITE(numout,*) '                    ==>    qint reset to ZERO '
+         qint_c14(:,:) = 0._wp
+      !
+      ELSE
+        !
+        CALL iom_get( numrtr, jpdom_autoglo, 'qint_c14', qint_c14 ) 
+        !
+      ENDIF
+      !
+      CALL trc_atm_c14_ini   ! Init atm values
+      !
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      !
+   END SUBROUTINE trc_ini_c14
+
+   !!======================================================================
+END MODULE trcini_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcnam_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcnam_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcnam_c14.F90	(revision 14097)
@@ -0,0 +1,119 @@
+MODULE trcnam_c14
+   !!======================================================================
+   !!                         ***  MODULE trcnam_c14  ***
+   !! TOP :   initialisation of some run parameters for C14 chemical model
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) from trcnam.cfc.h90
+   !! History :        !  2015 (A.Mouchet) equilibrium + transient C14
+   !!----------------------------------------------------------------------
+   !! trc_nam_c14      : C14 model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+   USE sms_c14
+
+   IMPLICIT NONE
+   PRIVATE
+   !!
+   PUBLIC   trc_nam_c14   ! called by trcnam.F90 module
+   !!
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_nam_c14
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_nam_c14  ***
+      !!                 
+      !! ** Purpose :   Definition some run parameter for C14 model
+      !!
+      !! ** Method  :   Read the namc14 namelist and check the parameter 
+      !!       values called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist namelist_c14
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !! 
+      NAMELIST/namc14_typ/ kc14typ,rc14at, pco2at, rc14init   ! type of C14 tracer, default values of C14/C, pco2, & ocean r14
+      NAMELIST/namc14_sbc/ ln_chemh, xkwind, xdicsur          ! chem enh, wind coeff, ref DIC 
+      NAMELIST/namc14_fcg/ cfileco2, cfilec14, tyrc14_beg     ! for transient exps; atm forcing
+      !!-------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Radiocarbon C14'
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' trc_nam_c14 : Read C14 namelists'
+         WRITE(numout,*) ' ~~~~~~~~~~~'
+      ENDIF
+      !
+      ! Variable setting
+      ctrcnm    (jp_c14) = 'RC14'
+      ctrcln    (jp_c14) = 'Radiocarbon ratio'
+      ctrcun    (jp_c14) = '-'
+      ln_trc_ini(jp_c14) = .false.
+      ln_trc_sbc(jp_c14) = .false.
+      ln_trc_cbc(jp_c14) = .false.
+      ln_trc_obc(jp_c14) = .false.
+      !
+      REWIND( numtrc_ref )              ! Namelist namc14_typ in reference namelist :
+      READ  ( numtrc_ref, namc14_typ, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc14_typ in reference namelist' )
+      REWIND( numtrc_cfg )              ! Namelist namcfcdate in configuration namelist 
+      READ  ( numtrc_cfg, namc14_typ, IOSTAT = ios, ERR = 902)
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc14_typ in configuration namelist' )
+      IF(lwm) WRITE ( numonr, namc14_typ )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist : namc14_typ'
+         WRITE(numout,*) '      Type of C14 tracer (0=equilibrium; 1=bomb transient; 2=past transient) kc14typ = ', kc14typ
+         WRITE(numout,*) '      Default value for atmospheric C14/C (used for equil run)               rc14at  = ', rc14at
+         WRITE(numout,*) '      Default value for atmospheric pcO2 [atm] (used for equil run)          pco2at  = ', pco2at
+         WRITE(numout,*) '      Default value for initial C14/C in the ocean (used for equil run)      rc14init= ', rc14init
+         WRITE(numout,*)
+      ENDIF
+
+      REWIND( numtrc_ref )              ! Namelist namc14_typ in reference namelist :
+      READ  ( numtrc_ref, namc14_sbc, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc14_sbc in reference namelist' )
+      REWIND( numtrc_cfg )              ! Namelist namcfcdate in configuration namelist 
+      READ  ( numtrc_cfg, namc14_sbc, IOSTAT = ios, ERR = 904)
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc14_sbc in configuration namelist' )
+      IF(lwm) WRITE( numonr, namc14_sbc )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist namc14_sbc'
+         WRITE(numout,*) '      Chemical enhancement in piston velocity   ln_chemh = ', ln_chemh
+         WRITE(numout,*) '      Coefficient for gas exchange velocity     xkwind   = ', xkwind
+         WRITE(numout,*) '      Reference DIC concentration (mol/m3)      xdicsur  = ', xdicsur
+         WRITE(numout,*)
+      ENDIF
+
+      REWIND( numtrc_ref )              ! Namelist namc14_typ in reference namelist :
+      READ  ( numtrc_ref, namc14_fcg, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namc14_fcg in reference namelist' )
+      REWIND( numtrc_cfg )              ! Namelist namcfcdate in configuration namelist 
+      READ  ( numtrc_cfg, namc14_fcg, IOSTAT = ios, ERR = 906)
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'namc14_fcg in configuration namelist' )
+      IF(lwm) WRITE ( numonr, namc14_fcg )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist namc14_fcg'
+         WRITE(numout,*) '      Atmospheric co2 file ( bomb )           cfileco2   = ', TRIM( cfileco2 )
+         WRITE(numout,*) '      Atmospheric c14 file ( bomb )           cfilec14   = ', TRIM( cfilec14 )
+         WRITE(numout,*) '      Starting year of experiment             tyrc14_beg = ', tyrc14_beg
+      ENDIF
+
+      !
+      IF( kc14typ == 2 )    tyrc14_beg = 1950._wp - tyrc14_beg   ! BP to AD dates
+      ! set units 
+      rlam14 = LOG(2._wp) / 5730._wp / rsiyea    ! C14 decay  rate: yr^-1 --> s^-1
+      !                                          ! radiocarbon half-life is 5730 yr
+   END SUBROUTINE trc_nam_c14
+   
+   !!======================================================================
+END MODULE trcnam_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcsms_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcsms_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcsms_c14.F90	(revision 14097)
@@ -0,0 +1,166 @@
+MODULE trcsms_c14
+   !!======================================================================
+   !!                      ***  MODULE trcsms_c14  ***
+   !! TOP : Bomb C14 main module
+   !!======================================================================
+   !! History     -   ! 1994-05 ( J. Orr ) original code
+   !!            1.0  ! 2006-02 ( J.M. Molines )  Free form + modularity
+   !!            2.0  ! 2008-12 ( C. Ethe ) reorganisation
+   !!            4.0  ! 2011-02 ( A.R. Porter, STFC Daresbury ) Dynamic memory
+   !!                 ! 2015    (A. Mouchet) general C14 + update formulas
+   !!----------------------------------------------------------------------
+   !!   trc_sms_c14 :  compute and add C14 suface forcing to C14 trends
+   !!----------------------------------------------------------------------
+   USE oce_trc       ! Ocean variables
+   USE par_trc       ! TOP parameters
+   USE trc           ! TOP variables
+   USE trd_oce    ! trends
+   USE trdtrc    ! trends
+   USE sms_c14    ! atmospheric forcing
+   USE trcatm_c14    ! atmospheric forcing
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_c14       ! called in trcsms.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_c14( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_sms_c14  ***
+      !!
+      !! ** Purpose :   Compute the surface boundary contition on C14
+      !!      passive tracer associated with air-sea fluxes and add it to 
+      !!      the general trend of tracers equations.
+      !
+      !    Method: 
+      !          - transport the ratio C14/C as in Toggweiler et al. (JGR,1989)
+      !          - if on-line a passive tracer (jpcref; NO sms) allows compensating for
+      !            freshwater fluxes which should not impact the C14/C ratio
+      !
+      !        =>   Delta-C14= ( trn(...jp_c14) -1)*1000.
+      !!
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !
+      INTEGER  :: ji, jj, jk         ! dummy loop indices 
+      REAL(wp) :: zt, ztp, zsk      ! dummy variables
+      REAL(wp) :: zsol              ! solubility
+      REAL(wp) :: zsch              ! schmidt number
+      REAL(wp) :: zv2               ! wind speed ( square)
+      REAL(wp) :: zpv               ! piston velocity
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sms_c14')
+      !
+      IF( kt ==  nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_sms_c14:  C14 model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      ENDIF
+      !
+      ! Get co2sbc & c14sbc(ji,jj): at 1st iter for all, at each time step for transient
+      IF( kc14typ >= 1 .OR.  kt ==  nittrc000 )   CALL trc_atm_c14( kt, co2sbc, c14sbc ) 
+
+      ! -------------------------------------------------------------------
+      !  Gas exchange coefficient (Wanninkhof, 1992, JGR, 97,7373-7382)
+      !  Schmidt number of CO2 in seawater (Wanninkhof, 1992 & 2014)
+      !  CO2 solubility (Weiss, 1974; Wanninkhof, 2014) 
+      ! -------------------------------------------------------------------
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi  
+            IF( tmask(ji,jj,1) >  0. ) THEN
+               !
+               zt   = MIN( 40. , tsn(ji,jj,1,jp_tem) )
+               !
+               !  Computation of solubility zsol in [mol/(L * atm)]
+               !   after Wanninkhof (2014) referencing Weiss (1974)
+               ztp  = ( zt + 273.16 ) * 0.01
+               zsk  = 0.027766 + ztp * ( -0.025888 + 0.0050578 * ztp )   ! [mol/(L * atm)]
+               zsol = EXP( -58.0931 + 90.5069 / ztp  + 22.2940 * LOG( ztp ) + zsk * tsn(ji,jj,1,jp_sal) )
+               ! convert solubilities [mol/(L * atm)] -> [mol/(m^3 * ppm)]
+               zsol = zsol * 1.e-03
+
+               ! Computes the Schmidt number of CO2 in seawater
+               !               Wanninkhof-2014
+               zsch = 2116.8 + zt * ( -136.25 + zt * (4.7353 + zt * (-0.092307 + 0.0007555 * zt ) ) )
+
+               ! Wanninkhof Piston velocity: zpv in units [m/s]
+               zv2 = xkwind * (wndm(ji,jj) * wndm(ji,jj))              ! wind speed module at T points
+               ! chemical enhancement (Wanninkhof & Knox, 1996)
+               IF( ln_chemh ) zv2 = zv2 + 2.5 * ( 0.5246 + zt * (0.016256 + 0.00049946  * zt ) )
+               zv2 = zv2/360000._wp                                    ! conversion cm/h -> m/s
+               !
+               zpv  = ( zv2 * SQRT( 660./ zsch ) ) * ( 1. - fr_i(ji,jj) ) * tmask(ji,jj,1)
+
+               ! CO2 piston velocity (m/s)
+               exch_co2(ji,jj)= zpv
+               ! CO2 invasion rate (mol/ppm/m2/s) = 1st part of 14C/C exchange velocity
+               exch_c14(ji,jj)= zpv * zsol
+            ELSE
+               exch_co2(ji,jj) = 0._wp
+               exch_c14(ji,jj) = 0._wp
+            ENDIF
+         END DO
+      END DO
+
+      ! Exchange velocity for 14C/C ratio (m/s)
+      zt = co2sbc / xdicsur
+      exch_c14(:,:) = zt * exch_c14(:,:)
+      !
+      ! Flux of C-14 from air-to-sea; units: (C14/C ratio) x m/s
+      !                               already masked
+      qtr_c14(:,:) = exch_c14(:,:) * ( c14sbc(:,:) - trb(:,:,1,jp_c14) )
+            
+      ! cumulation of air-to-sea flux at each time step
+      qint_c14(:,:) = qint_c14(:,:) + qtr_c14(:,:) * rdttrc
+      !
+      ! Add the surface flux to the trend of jp_c14
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            tra(ji,jj,1,jp_c14) = tra(ji,jj,1,jp_c14) + qtr_c14(ji,jj) / e3t_n(ji,jj,1) 
+         END DO
+      END DO
+      !
+      ! Computation of decay effects on jp_c14
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !
+               tra(ji,jj,jk,jp_c14) = tra(ji,jj,jk,jp_c14) - rlam14 * trb(ji,jj,jk,jp_c14) * tmask(ji,jj,jk) 
+               !
+            END DO
+         END DO
+      END DO
+      !
+      IF( lrst_trc ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' trc_rst_wri_c14 : Write specific variables from c14 model '
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+         !
+         CALL iom_rstput( kt, nitrst, numrtw, 'co2sbc', co2sbc )       ! These five need      &
+         CALL iom_rstput( kt, nitrst, numrtw, 'c14sbc', c14sbc )     ! &    to be written   &
+         CALL iom_rstput( kt, nitrst, numrtw, 'exch_co2', exch_co2 ) ! &    for temporal    &
+         CALL iom_rstput( kt, nitrst, numrtw, 'exch_c14', exch_c14 ) ! &    averages        &
+         CALL iom_rstput( kt, nitrst, numrtw, 'qtr_c14', qtr_c14 )   ! &    to be coherent.
+         CALL iom_rstput( kt, nitrst, numrtw, 'qint_c14', qint_c14 ) ! Cumulative
+         !
+      ENDIF
+
+      IF( l_trdtrc )  CALL trd_trc( tra(:,:,:,jp_c14), 1, jptra_sms, kt )   ! save trends
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sms_c14')
+      !
+   END SUBROUTINE trc_sms_c14
+
+  !!======================================================================
+END MODULE trcsms_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcwri_c14.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcwri_c14.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/C14/trcwri_c14.F90	(revision 14097)
@@ -0,0 +1,137 @@
+MODULE trcwri_c14
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    MY_SRC :   Additional outputs for C14 tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !! History :   2.0  !  2015 (A. Mouchet)  adapted code for C14
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput
+   !!----------------------------------------------------------------------
+   !! trc_wri_c14   :  outputs of ventilation fields
+   !!----------------------------------------------------------------------
+   USE oce_trc       ! Ocean variables
+   USE trc         ! passive tracers common variables 
+   USE iom         ! I/O manager 
+   USE sms_c14
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_c14
+   !
+   !   Standard ratio: 1.176E-12 ; Avogadro's nbr = 6.022E+23 at/mol ; bomb C14 traditionally reported as 1.E+26 atoms
+   REAL(wp), PARAMETER  :: atomc14 = 1.176 * 6.022E-15   ! conversion factor 
+
+
+CONTAINS
+
+   SUBROUTINE trc_wri_c14
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_c14  ***
+      !!
+      !! ** Purpose :   output additional C14 tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra         ! short title for tracer
+      INTEGER              :: ji,jj,jk,jn   ! dummy loop indexes
+      REAL(wp)             :: zage,zarea,ztemp   ! temporary
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   :: zres, z2d ! temporary storage 2D
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: z3d , zz3d ! temporary storage 3D
+      !!---------------------------------------------------------------------
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      cltra = TRIM( ctrcnm(jp_c14) )                  ! short title for tracer
+      CALL iom_put( cltra, trn(:,:,:,jp_c14) )
+
+      ! compute and write the tracer diagnostic in the file
+      ! ---------------------------------------
+      
+      IF( iom_use("DeltaC14") .OR. iom_use("C14Age") .OR. iom_use("RAge")   ) THEN
+         !
+         ALLOCATE( z2d(jpi,jpj), zres(jpi,jpj) )
+         ALLOCATE( z3d(jpi,jpj,jpk), zz3d(jpi,jpj,jpk) )
+         !
+         zage = -1._wp / rlam14 / rsiyea  ! factor for radioages in year
+         z3d(:,:,:)  = 1._wp
+         zz3d(:,:,:) = 0._wp
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( tmask(ji,jj,jk) > 0._wp) THEN
+                     z3d (ji,jj,jk) = trn(ji,jj,jk,jp_c14)
+                     zz3d(ji,jj,jk) = LOG( z3d(ji,jj,jk) )
+                  ENDIF
+               ENDDO
+            ENDDO
+         ENDDO
+         zres(:,:) = z3d(:,:,1)
+
+         ! Reservoir age [yr]
+         z2d(:,:) =0._wp
+         jk = 1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ztemp = zres(ji,jj) / c14sbc(ji,jj)
+               IF( ztemp > 0._wp .AND. tmask(ji,jj,jk) > 0._wp ) z2d(ji,jj) = LOG( ztemp )
+            ENDDO
+         ENDDO
+         !
+         z3d(:,:,:) = 1.d03 * ( z3d(:,:,:) - 1._wp )
+         CALL iom_put( "DeltaC14" , z3d(:,:,:)  )  ! Delta C14 [permil]
+         CALL iom_put( "C14Age"   , zage * zz3d(:,:,:) )            !  Radiocarbon age [yr]
+
+         CALL iom_put( "qtr_c14", rsiyea * qtr_c14(:,:)  )            !  Radiocarbon surf flux [./m2/yr]
+         CALL iom_put( "qint_c14" , qint_c14  )                       ! cumulative flux [./m2]
+         CALL iom_put( "RAge" , zage * z2d(:,:) )                     ! Reservoir age [yr]
+         !
+         DEALLOCATE( z2d, zres, z3d, zz3d )
+         !
+      ENDIF
+      !
+      !  0-D fields
+      !
+      CALL iom_put( "AtmCO2", co2sbc )  !     global atmospheric CO2 [ppm]
+    
+      IF( iom_use("AtmC14") ) THEN
+         zarea = glob_sum( 'trcwri_c14', e1e2t(:,:) )           ! global ocean surface
+         ztemp = glob_sum( 'trcwri_c14', c14sbc(:,:) * e1e2t(:,:) )
+         ztemp = ( ztemp / zarea - 1._wp ) * 1000._wp
+         CALL iom_put( "AtmC14" , ztemp )   ! Global atmospheric DeltaC14 [permil]
+      ENDIF
+      IF( iom_use("K_C14") ) THEN
+         ztemp = glob_sum ( 'trcwri_c14', exch_c14(:,:) * e1e2t(:,:) )
+         ztemp = rsiyea * ztemp / zarea
+         CALL iom_put( "K_C14" , ztemp )   ! global mean exchange velocity for C14/C ratio [m/yr]
+      ENDIF
+      IF( iom_use("K_CO2") ) THEN
+         zarea = glob_sum( 'trcwri_c14', e1e2t(:,:) )           ! global ocean surface
+         ztemp = glob_sum ( 'trcwri_c14', exch_co2(:,:) * e1e2t(:,:) )
+         ztemp = 360000._wp * ztemp / zarea       ! cm/h units: directly comparable with literature
+         CALL iom_put( "K_CO2", ztemp )  !  global mean CO2 piston velocity [cm/hr]
+      ENDIF
+      IF( iom_use("C14Inv") ) THEN
+         ztemp = glob_sum( 'trcwri_c14', trn(:,:,:,jp_c14) * cvol(:,:,:) )
+         ztemp = atomc14 * xdicsur * ztemp
+         CALL iom_put( "C14Inv", ztemp )  !  Radiocarbon ocean inventory [10^26 atoms]
+      END IF
+      !
+   END SUBROUTINE trc_wri_c14
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No C14 tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_c14
+CONTAINS
+   SUBROUTINE trc_wri_c14                     ! Empty routine  
+   END SUBROUTINE trc_wri_c14
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcwri_c14
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/par_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/par_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/par_cfc.F90	(revision 14097)
@@ -0,0 +1,17 @@
+MODULE par_cfc
+   !!======================================================================
+   !!                        ***  par_cfc  ***
+   !! TOP :   set the CFC parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+   INTEGER, PUBLIC  :: jp_cfc0, jp_cfc1  !:  First/last index of CFC tracers
+
+   !!======================================================================
+END MODULE par_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcice_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcice_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcice_cfc.F90	(revision 14097)
@@ -0,0 +1,39 @@
+MODULE trcice_cfc
+   !!======================================================================
+   !!                         ***  MODULE trcice_cfc  ***
+   !! TOP :   Main module of the MY_TRC tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) Original code
+   !!----------------------------------------------------------------------
+   !! trc_ice_cfc       : MY_TRC model main routine
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_cfc       ! called by trcice.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_cfc
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ice_cfc  ***
+      !!
+      !! ** Purpose :   main routine of MY_TRC model
+      !!
+      !! ** Method  : -
+      !!----------------------------------------------------------------------
+      !
+      !
+   END SUBROUTINE trc_ice_ini_cfc
+
+   !!======================================================================
+END MODULE trcice_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcini_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcini_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcini_cfc.F90	(revision 14097)
@@ -0,0 +1,146 @@
+MODULE trcini_cfc
+   !!======================================================================
+   !!                         ***  MODULE trcini_cfc  ***
+   !! TOP :   initialisation of the CFC tracers
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) 
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !! trc_ini_cfc      : CFC model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+   USE trcnam_cfc      ! CFC SMS namelist
+   USE trcsms_cfc      ! CFC sms trends
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_cfc   ! called by trcini.F90 module
+
+   INTEGER  ::   inum                   ! unit number
+   REAL(wp) ::   ylats = -10.           ! 10 degrees south
+   REAL(wp) ::   ylatn =  10.           ! 10 degrees north
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_cfc
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_cfc  ***  
+      !!
+      !! ** Purpose :   initialization for cfc model
+      !!
+      !! ** Method  : - Read the namcfc namelist and check the parameter values
+      !!----------------------------------------------------------------------
+      INTEGER  ::  ji, jj, jn, jl, jm, js, io, ierr
+      INTEGER  ::  iskip = 6   ! number of 1st descriptor lines
+      REAL(wp) ::  zyy, zyd
+      CHARACTER(len = 20)  ::  cltra
+      !!----------------------------------------------------------------------
+      !
+      CALL trc_nam_cfc
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_cfc: initialisation of CFC chemical model'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~'
+      !
+      IF(lwp) WRITE(numout,*) 'Read annual atmospheric concentratioins from formatted file : ' // TRIM(clname)
+      
+      CALL ctl_opn( inum, clname, 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      REWIND(inum)
+      
+      ! compute the number of year in the file
+      ! file starts in 1931 do jn represent the year in the century
+      jn = 31 
+      DO 
+        READ(inum,'(1x)',END=100) 
+        jn = jn + 1
+      END DO
+ 100  jpyear = jn - 1 - iskip
+      IF ( lwp) WRITE(numout,*) '   --->  ', jpyear ,' years read'
+      !                                ! Allocate CFC arrays
+
+      ALLOCATE( p_cfc(jpyear,jphem,3), STAT=ierr )
+      IF( ierr > 0 ) THEN
+         CALL ctl_stop( 'trc_ini_cfc: unable to allocate p_cfc array' )   ;   RETURN
+      ENDIF
+      IF( trc_sms_cfc_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_ini_cfc: unable to allocate CFC arrays' )
+
+
+      ! Initialization of boundaries conditions
+      ! --------------------------------------- 
+      xphem (:,:)    = 0._wp
+      p_cfc(:,:,:)   = 0._wp
+      
+      ! Initialization of qint in case of  no restart 
+      !----------------------------------------------
+      qtr_cfc(:,:,:) = 0._wp
+      IF( .NOT. ln_rsttr ) THEN    
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'Initialisation of qint ; No restart : qint equal zero '
+         ENDIF
+         qint_cfc(:,:,:) = 0._wp
+         DO jl = 1, jp_cfc
+            jn = jp_cfc0 + jl - 1
+            trn(:,:,:,jn) = 0._wp
+         END DO
+      ENDIF
+
+      REWIND(inum)
+      
+      DO jm = 1, iskip        ! Skip over 1st six descriptor lines
+         READ(inum,'(1x)')
+      END DO
+      ! file starts in 1931 do jn represent the year in the century.jhh
+      ! Read file till the end
+      jn = 31
+      DO 
+        READ(inum,*, IOSTAT=io) zyy, p_cfc(jn,1:2,1), p_cfc(jn,1:2,2), p_cfc(jn,1:2,3)
+        IF( io < 0 ) exit
+        jn = jn + 1
+      END DO
+
+      !p_cfc(32,1:2,1) = 5.e-4      ! modify the values of the first years
+      !p_cfc(33,1:2,1) = 8.e-4
+      !p_cfc(34,1:2,1) = 1.e-6
+      !p_cfc(35,1:2,1) = 2.e-3
+      !p_cfc(36,1:2,1) = 4.e-3
+      !p_cfc(37,1:2,1) = 6.e-3
+      !p_cfc(38,1:2,1) = 8.e-3
+      !p_cfc(39,1:2,1) = 1.e-2
+      IF(lwp) THEN        ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) ' Year   c11NH     c11SH     c12NH     c12SH     SF6NH     SF6SH'
+         DO jn = 30, jpyear
+            WRITE(numout, '( 1I4, 6F10.4)') jn, p_cfc(jn,1:2,1), p_cfc(jn,1:2,2), p_cfc(jn,1:2,3)
+         END DO
+      ENDIF
+
+
+      ! Interpolation factor of atmospheric partial pressure
+      ! Linear interpolation between 2 hemispheric function of latitud between ylats and ylatn
+      !---------------------------------------------------------------------------------------
+      zyd = ylatn - ylats      
+      DO jj = 1 , jpj
+         DO ji = 1 , jpi
+            IF(     gphit(ji,jj) >= ylatn ) THEN   ;   xphem(ji,jj) = 1.e0
+            ELSEIF( gphit(ji,jj) <= ylats ) THEN   ;   xphem(ji,jj) = 0.e0
+            ELSE                                   ;   xphem(ji,jj) = ( gphit(ji,jj) - ylats) / zyd
+            ENDIF
+         END DO
+      END DO
+      !
+      IF(lwp) WRITE(numout,*) 'Initialization of CFC tracers done'
+      IF(lwp) WRITE(numout,*) ' '
+      !
+   END SUBROUTINE trc_ini_cfc
+
+   !!======================================================================
+END MODULE trcini_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcnam_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcnam_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcnam_cfc.F90	(revision 14097)
@@ -0,0 +1,108 @@
+MODULE trcnam_cfc
+   !!======================================================================
+   !!                         ***  MODULE trcnam_cfc  ***
+   !! TOP :   initialisation of some run parameters for CFC chemical model
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec) from trcnam.cfc.h90
+   !!----------------------------------------------------------------------
+   !! trc_nam_cfc      : CFC model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+   USE trcsms_cfc      ! CFC specific variable
+
+   IMPLICIT NONE
+   PRIVATE
+
+   CHARACTER(len=34), PUBLIC ::   clname ! Input filename of CFCs atm. concentrations
+
+   PUBLIC   trc_nam_cfc   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_nam_cfc
+      !!-------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_nam_cfc  ***
+      !!                 
+      !! ** Purpose :   Definition some run parameter for CFC model
+      !!
+      !! ** Method  :   Read the namcfc namelist and check the parameter 
+      !!       values called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist namcfc
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      INTEGER ::   jl, jn
+      !!
+      NAMELIST/namcfc/ ndate_beg, nyear_res, clname
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' CFCs'
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' trc_nam_cfc : Read namcfc namelist for CFC chemical model'
+         WRITE(numout,*) ' ~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numtrc_ref )              ! Namelist namcfcdate in reference namelist : CFC parameters
+      READ  ( numtrc_ref, namcfc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namcfc in reference namelist' )
+      REWIND( numtrc_cfg )              ! Namelist namcfcdate in configuration namelist : CFC parameters
+      READ  ( numtrc_cfg, namcfc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namcfc in configuration namelist' )
+      IF(lwm) WRITE( numonr, namcfc )
+      IF(lwm) CALL FLUSH ( numonr )     ! flush output namelist CFC
+
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist : namcfc'
+         WRITE(numout,*) '      initial calendar date (aammjj) for CFC     ndate_beg = ', ndate_beg, '[yymmdd]'
+         WRITE(numout,*) '      restoring time constant (year)             nyear_res = ', nyear_res
+      ENDIF
+      nyear_beg = ndate_beg / 10000
+      IF(lwp) WRITE(numout,*) '      associated initial year (aa)               nyear_beg = ', nyear_beg, '[yy]'
+      !
+      jn = jp_cfc0 - 1
+      ! Variables setting
+      IF( ln_cfc11 ) THEN
+         jn = jn + 1
+         ctrcnm    (jn) = 'CFC11'
+         ctrcln    (jn) = 'Chlorofluoro carbon 11 Concentration'
+         ctrcun    (jn) = 'umolC/L'
+         ln_trc_ini(jn) = .false.
+         ln_trc_sbc(jn) = .false.
+         ln_trc_cbc(jn) = .false.
+         ln_trc_obc(jn) = .false.
+      ENDIF
+      !
+      IF( ln_cfc12 ) THEN
+         jn = jn + 1
+         ctrcnm    (jn) = 'CFC12'
+         ctrcln    (jn) = 'Chlorofluoro carbon 12 Concentration'
+         ctrcun    (jn) = 'umolC/L'
+         ln_trc_ini(jn) = .false.
+         ln_trc_sbc(jn) = .false.
+         ln_trc_cbc(jn) = .false.
+         ln_trc_obc(jn) = .false.
+      ENDIF
+      !
+      IF( ln_sf6 ) THEN
+         jn = jn + 1
+         ctrcnm    (jn) = 'SF6'
+         ctrcln    (jn) = 'Sulfur hexafluoride Concentration'
+         ctrcun    (jn) = 'umol/L'
+         ln_trc_ini(jn) = .false.
+         ln_trc_sbc(jn) = .false.
+         ln_trc_cbc(jn) = .false.
+         ln_trc_obc(jn) = .false.
+      ENDIF
+      !
+   END SUBROUTINE trc_nam_cfc
+   
+   !!======================================================================
+END MODULE trcnam_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcsms_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcsms_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcsms_cfc.F90	(revision 14097)
@@ -0,0 +1,321 @@
+MODULE trcsms_cfc
+   !!======================================================================
+   !!                      ***  MODULE trcsms_cfc  ***
+   !! TOP : CFC main model
+   !!======================================================================
+   !! History :  OPA  !  1999-10  (JC. Dutay)  original code
+   !!  NEMO      1.0  !  2004-03  (C. Ethe) free form + modularity
+   !!            2.0  !  2007-12  (C. Ethe, G. Madec)  reorganisation
+   !!            4.0  !  2016-11  (T. Lovato) Add SF6, Update Schmidt number
+   !!----------------------------------------------------------------------
+   !!   trc_sms_cfc  :  compute and add CFC suface forcing to CFC trends
+   !!   cfc_init     :  sets constants for CFC surface forcing computation
+   !!----------------------------------------------------------------------
+   USE oce_trc       ! Ocean variables
+   USE par_trc       ! TOP parameters
+   USE trc           ! TOP variables
+   USE trd_oce
+   USE trdtrc
+   USE iom           ! I/O library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_cfc         ! called in ???    
+   PUBLIC   trc_sms_cfc_alloc   ! called in trcini_cfc.F90
+
+   INTEGER , PUBLIC, PARAMETER ::   jphem  =   2   ! parameter for the 2 hemispheres
+   INTEGER , PUBLIC            ::   jpyear         ! Number of years read in input data file (in trcini_cfc)
+   INTEGER , PUBLIC            ::   ndate_beg      ! initial calendar date (aammjj) for CFC
+   INTEGER , PUBLIC            ::   nyear_res      ! restoring time constant (year)
+   INTEGER , PUBLIC            ::   nyear_beg      ! initial year (aa) 
+   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   p_cfc    ! partial hemispheric pressure for all CFC
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   xphem    ! spatial interpolation factor for patm
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qtr_cfc  ! flux at surface
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qint_cfc ! cumulative flux 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   atm_cfc  ! partial hemispheric pressure for used CFC
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   patm     ! atmospheric function
+
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   soa      ! coefficient for solubility of CFC [mol/l/atm]
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sob      !    "               "
+   REAL(wp),         ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   sca      ! coefficients for schmidt number in degrees Celsius
+   !                          ! coefficients for conversion
+   REAL(wp) ::   xconv1 = 1.0          ! conversion from to 
+   REAL(wp) ::   xconv2 = 0.01/3600.   ! conversion from cm/h to m/s: 
+   REAL(wp) ::   xconv3 = 1.0e+3       ! conversion from mol/l/atm to mol/m3/atm
+   REAL(wp) ::   xconv4 = 1.0e-12      ! conversion from mol/m3/atm to mol/m3/pptv 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_cfc( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms_cfc  ***
+      !!
+      !! ** Purpose :   Compute the surface boundary contition on CFC 11 
+      !!             passive tracer associated with air-mer fluxes and add it 
+      !!             to the general trend of tracers equations.
+      !!
+      !! ** Method  : - get the atmospheric partial pressure - given in pico -
+      !!              - computation of solubility ( in 1.e-12 mol/l then in 1.e-9 mol/m3)
+      !!              - computation of transfert speed ( given in cm/hour ----> cm/s )
+      !!              - the input function is given by : 
+      !!                speed * ( concentration at equilibrium - concentration at surface )
+      !!              - the input function is in pico-mol/m3/s and the
+      !!                CFC concentration in pico-mol/m3
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jn, jl, jm
+      INTEGER  ::   iyear_beg, iyear_end
+      INTEGER  ::   im1, im2, ierr
+      REAL(wp) ::   ztap, zdtap        
+      REAL(wp) ::   zt1, zt2, zt3, zt4, zv2
+      REAL(wp) ::   zsol      ! solubility
+      REAL(wp) ::   zsch      ! schmidt number 
+      REAL(wp) ::   zpp_cfc   ! atmospheric partial pressure of CFC
+      REAL(wp) ::   zca_cfc   ! concentration at equilibrium
+      REAL(wp) ::   zak_cfc   ! transfert coefficients
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)  ::   zpatm     ! atmospheric function
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sms_cfc')
+      !
+      ALLOCATE( zpatm(jphem,jp_cfc), STAT=ierr )
+      IF( ierr > 0 ) THEN
+         CALL ctl_stop( 'trc_sms_cfc: unable to allocate zpatm array' )   ;   RETURN
+      ENDIF
+
+      IF( kt == nittrc000 )   CALL cfc_init
+
+      ! Temporal interpolation
+      ! ----------------------
+      iyear_beg = nyear - 1900
+      IF ( nmonth <= 6 ) THEN
+         iyear_beg = iyear_beg - 1
+         im1       =  6 - nmonth + 1
+         im2       =  6 + nmonth - 1
+      ELSE
+         im1       = 12 - nmonth + 7
+         im2       =      nmonth - 7
+      ENDIF
+      ! Avoid bad interpolation if starting date is =< 1900
+      IF( iyear_beg .LE. 0      )  iyear_beg = 1
+      IF( iyear_beg .GE. jpyear )  iyear_beg = jpyear - 1
+      !
+      iyear_end = iyear_beg + 1
+
+      !                                                  !------------!
+      DO jl = 1, jp_cfc                                  !  CFC loop  !
+         !                                               !------------!
+         jn = jp_cfc0 + jl - 1
+         ! time interpolation at time kt
+         DO jm = 1, jphem
+            zpatm(jm,jl) = (  atm_cfc(iyear_beg, jm, jl) * REAL(im1, wp)  &
+               &           +  atm_cfc(iyear_end, jm, jl) * REAL(im2, wp) ) / 12.
+         END DO
+         
+         !                                                         !------------!
+         DO jj = 1, jpj                                            !  i-j loop  !
+            DO ji = 1, jpi                                         !------------!
+ 
+               ! space interpolation
+               zpp_cfc  =       xphem(ji,jj)   * zpatm(1,jl)   &
+                  &     + ( 1.- xphem(ji,jj) ) * zpatm(2,jl)
+
+               ! Computation of concentration at equilibrium : in picomol/l
+               ! coefficient for solubility for CFC-11/12 in  mol/l/atm
+               IF( tmask(ji,jj,1) .GE. 0.5 ) THEN
+                  ztap  = ( tsn(ji,jj,1,jp_tem) + 273.16 ) * 0.01
+                  zdtap = sob(1,jl) + ztap * ( sob(2,jl) + ztap * sob(3,jl) ) 
+                  zsol  =  EXP( soa(1,jl) + soa(2,jl) / ztap + soa(3,jl) * LOG( ztap )   &
+                     &                    + soa(4,jl) * ztap * ztap + tsn(ji,jj,1,jp_sal) * zdtap ) 
+               ELSE
+                  zsol  = 0.e0
+               ENDIF
+               ! conversion from mol/l/atm to mol/m3/atm and from mol/m3/atm to mol/m3/pptv    
+               zsol = xconv4 * xconv3 * zsol * tmask(ji,jj,1)  
+               ! concentration at equilibrium
+               zca_cfc = xconv1 * zpp_cfc * zsol * tmask(ji,jj,1)             
+  
+               ! Computation of speed transfert
+               !    Schmidt number revised in Wanninkhof (2014)
+               zt1  = tsn(ji,jj,1,jp_tem)
+               zt2  = zt1 * zt1 
+               zt3  = zt1 * zt2
+               zt4  = zt2 * zt2
+               zsch = sca(1,jl) + sca(2,jl) * zt1 + sca(3,jl) * zt2 + sca(4,jl) * zt3 + sca(5,jl) * zt4
+
+               !    speed transfert : formulae revised in Wanninkhof (2014)
+               zv2     = wndm(ji,jj) * wndm(ji,jj)
+               zsch    = zsch / 660.
+               zak_cfc = ( 0.251 * xconv2 * zv2 / SQRT(zsch) ) * tmask(ji,jj,1)
+
+               ! Input function  : speed *( conc. at equil - concen at surface )
+               ! trn in pico-mol/l idem qtr; ak in en m/a
+               qtr_cfc(ji,jj,jl) = -zak_cfc * ( trb(ji,jj,1,jn) - zca_cfc )   &
+                  &                         * tmask(ji,jj,1) * ( 1. - fr_i(ji,jj) )
+               ! Add the surface flux to the trend
+               tra(ji,jj,1,jn) = tra(ji,jj,1,jn) + qtr_cfc(ji,jj,jl) / e3t_n(ji,jj,1) 
+
+               ! cumulation of surface flux at each time step
+               qint_cfc(ji,jj,jl) = qint_cfc(ji,jj,jl) + qtr_cfc(ji,jj,jl) * rdt
+               !                                               !----------------!
+            END DO                                             !  end i-j loop  !
+         END DO                                                !----------------!
+         !                                                  !----------------!
+      END DO                                                !  end CFC loop  !
+      !
+      IF( lrst_trc ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_sms_cfc : cumulated input function fields written in ocean restart file ',   &
+            &                    'at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         jl = 0
+         DO jn = jp_cfc0, jp_cfc1
+             jl = jl + 1
+            CALL iom_rstput( kt, nitrst, numrtw, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jl) )
+         END DO
+      ENDIF                                            
+      !
+      IF( lk_iomput ) THEN
+         jl = 0
+         DO jn = jp_cfc0, jp_cfc1
+            jl = jl + 1
+            CALL iom_put( 'qtr_'//TRIM(ctrcnm(jn)) , qtr_cfc (:,:,jl) )
+            CALL iom_put( 'qint_'//TRIM(ctrcnm(jn)), qint_cfc(:,:,jl) )
+         ENDDO
+      END IF
+      !
+      IF( l_trdtrc ) THEN
+          DO jn = jp_cfc0, jp_cfc1
+            CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
+          END DO
+      END IF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sms_cfc')
+      !
+   END SUBROUTINE trc_sms_cfc
+
+
+   SUBROUTINE cfc_init
+      !!---------------------------------------------------------------------
+      !!                     ***  cfc_init  ***  
+      !!
+      !! ** Purpose : sets constants for CFC model
+      !!---------------------------------------------------------------------
+      INTEGER ::   jn, jl   !
+      !!----------------------------------------------------------------------
+      !
+      jn = 0 
+      ! coefficient for CFC11 
+      !----------------------
+      if ( ln_cfc11 ) then
+         jn = jn + 1
+         ! Solubility
+         soa(1,jn) = -229.9261 
+         soa(2,jn) =  319.6552
+         soa(3,jn) =  119.4471
+         soa(4,jn) =  -1.39165
+
+         sob(1,jn) =  -0.142382
+         sob(2,jn) =   0.091459
+         sob(3,jn) =  -0.0157274
+
+         ! Schmidt number 
+         sca(1,jn) = 3579.2
+         sca(2,jn) = -222.63
+         sca(3,jn) = 7.5749
+         sca(4,jn) = -0.14595
+         sca(5,jn) = 0.0011874
+
+         ! atm. concentration
+         atm_cfc(:,:,jn) = p_cfc(:,:,1)
+      endif
+
+      ! coefficient for CFC12 
+      !----------------------
+      if ( ln_cfc12 ) then
+         jn = jn + 1
+         ! Solubility
+         soa(1,jn) = -218.0971
+         soa(2,jn) =  298.9702
+         soa(3,jn) =  113.8049
+         soa(4,jn) =  -1.39165
+
+         sob(1,jn) =  -0.143566
+         sob(2,jn) =   0.091015
+         sob(3,jn) =  -0.0153924
+
+         ! schmidt number 
+         sca(1,jn) = 3828.1
+         sca(2,jn) = -249.86
+         sca(3,jn) = 8.7603
+         sca(4,jn) = -0.1716
+         sca(5,jn) = 0.001408
+
+         ! atm. concentration
+         atm_cfc(:,:,jn) = p_cfc(:,:,2)
+      endif
+
+      ! coefficient for SF6
+      !----------------------
+      if ( ln_sf6 ) then
+         jn = jn + 1
+         ! Solubility
+         soa(1,jn) = -80.0343
+         soa(2,jn) = 117.232
+         soa(3,jn) =  29.5817
+         soa(4,jn) =   0.0
+
+         sob(1,jn) =  0.0335183 
+         sob(2,jn) = -0.0373942 
+         sob(3,jn) =  0.00774862
+
+         ! schmidt number
+         sca(1,jn) = 3177.5
+         sca(2,jn) = -200.57
+         sca(3,jn) = 6.8865
+         sca(4,jn) = -0.13335
+         sca(5,jn) = 0.0010877
+  
+         ! atm. concentration
+         atm_cfc(:,:,jn) = p_cfc(:,:,3)
+       endif
+
+      IF( ln_rsttr ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' Read specific variables from CFC model '
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+         !
+         jl = 0
+         DO jn = jp_cfc0, jp_cfc1
+            jl = jl + 1
+            CALL iom_get( numrtr, jpdom_autoglo, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jl) ) 
+         END DO
+      ENDIF
+      IF(lwp) WRITE(numout,*)
+      !
+   END SUBROUTINE cfc_init
+
+
+   INTEGER FUNCTION trc_sms_cfc_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms_cfc_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( xphem   (jpi,jpj)        , atm_cfc(jpyear,jphem,jp_cfc)  ,    &
+         &      qtr_cfc (jpi,jpj,jp_cfc) , qint_cfc(jpi,jpj,jp_cfc)      ,    &
+         &      soa(4,jp_cfc)    ,  sob(3,jp_cfc)   ,  sca(5,jp_cfc)     ,    &
+         &      STAT=trc_sms_cfc_alloc )
+         !
+      IF( trc_sms_cfc_alloc /= 0 ) CALL ctl_stop( 'STOP', 'trc_sms_cfc_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION trc_sms_cfc_alloc
+
+   !!======================================================================
+END MODULE trcsms_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcwri_cfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcwri_cfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/CFC/trcwri_cfc.F90	(revision 14097)
@@ -0,0 +1,56 @@
+MODULE trcwri_cfc
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    cfc :   Output of cfc tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput
+   !!----------------------------------------------------------------------
+   !! trc_wri_cfc   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE trc         ! passive tracers common variables 
+   USE iom         ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_cfc 
+
+CONTAINS
+
+   SUBROUTINE trc_wri_cfc
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      DO jn = jp_cfc0, jp_cfc1
+         cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+         CALL iom_put( cltra, trn(:,:,:,jn) )
+      END DO
+      !
+   END SUBROUTINE trc_wri_cfc
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_cfc
+CONTAINS
+   SUBROUTINE trc_wri_cfc                     ! Empty routine  
+   END SUBROUTINE trc_wri_cfc
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcwri_cfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/par_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/par_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/par_my_trc.F90	(revision 14097)
@@ -0,0 +1,19 @@
+MODULE par_my_trc
+   !!======================================================================
+   !!                        ***  par_my_trc  ***
+   !! TOP :   set the MY_TRC parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+
+   ! Starting/ending PISCES do-loop indices (N.B. no PISCES : jpl_pcs < jpf_pcs the do-loop are never done)
+   INTEGER, PUBLIC ::   jp_myt0             !: First index of MY_TRC passive tracers
+   INTEGER, PUBLIC ::   jp_myt1             !: Last  index of MY_TRC passive tracers
+   !!======================================================================
+END MODULE par_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcice_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcice_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcice_my_trc.F90	(revision 14097)
@@ -0,0 +1,35 @@
+MODULE trcice_my_trc
+   !!======================================================================
+   !!                         ***  MODULE trcice_my_trc  ***
+   !!----------------------------------------------------------------------
+   !! trc_ice_my_trc       : MY_TRC model seaice coupling routine
+   !!----------------------------------------------------------------------
+   !! History :        !  2016  (C. Ethe, T. Lovato) Revised architecture
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_my_trc       ! called by trcice.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_my_trc
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ice_my_trc  ***
+      !!
+      !!----------------------------------------------------------------------
+      !
+      !
+   END SUBROUTINE trc_ice_ini_my_trc
+
+   !!======================================================================
+END MODULE trcice_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcini_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcini_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcini_my_trc.F90	(revision 14097)
@@ -0,0 +1,57 @@
+MODULE trcini_my_trc
+   !!======================================================================
+   !!                         ***  MODULE trcini_my_trc  ***
+   !! TOP :   initialisation of the MY_TRC tracers
+   !!======================================================================
+   !! History :        !  2007  (C. Ethe, G. Madec) Original code
+   !!                  !  2016  (C. Ethe, T. Lovato) Revised architecture
+   !!----------------------------------------------------------------------
+   !! trc_ini_my_trc   : MY_TRC model initialisation
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc
+   USE trc
+   USE par_my_trc
+   USE trcnam_my_trc     ! MY_TRC SMS namelist
+   USE trcsms_my_trc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_my_trc   ! called by trcini.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_my_trc
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_ini_my_trc  ***  
+      !!
+      !! ** Purpose :   initialization for MY_TRC model
+      !!
+      !! ** Method  : - Read the namcfc namelist and check the parameter values
+      !!----------------------------------------------------------------------
+      !
+      CALL trc_nam_my_trc
+      !
+      !                       ! Allocate MY_TRC arrays
+      IF( trc_sms_my_trc_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_ini_my_trc: unable to allocate MY_TRC arrays' )
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ini_my_trc: passive tracer unit vector'
+      IF(lwp) WRITE(numout,*) ' To check conservation : '
+      IF(lwp) WRITE(numout,*) '   1 - No sea-ice model '
+      IF(lwp) WRITE(numout,*) '   2 - No runoff ' 
+      IF(lwp) WRITE(numout,*) '   3 - precipitation and evaporation equal to 1 : E=P=1 ' 
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+      
+      IF( .NOT. ln_rsttr ) trn(:,:,:,jp_myt0:jp_myt1) = 1.
+      !
+   END SUBROUTINE trc_ini_my_trc
+
+   !!======================================================================
+END MODULE trcini_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcnam_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcnam_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcnam_my_trc.F90	(revision 14097)
@@ -0,0 +1,43 @@
+MODULE trcnam_my_trc
+   !!======================================================================
+   !!                      ***  MODULE trcnam_my_trc  ***
+   !! TOP :   initialisation of some run parameters for MY_TRC bio-model
+   !!======================================================================
+   !! History :      !  2007  (C. Ethe, G. Madec) Original code
+   !!                !  2016  (C. Ethe, T. Lovato) Revised architecture
+   !!----------------------------------------------------------------------
+   !! trc_nam_my_trc      : MY_TRC model initialisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_my_trc   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_nam_my_trc
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_nam_my_trc  ***  
+      !!
+      !! ** Purpose :   read MY_TRC namelist
+      !!
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_nam_my_trc : read MY_TRC namelists'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~~'
+      !
+   END SUBROUTINE trc_nam_my_trc
+   
+   !!======================================================================
+END MODULE trcnam_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcsms_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcsms_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcsms_my_trc.F90	(revision 14097)
@@ -0,0 +1,85 @@
+MODULE trcsms_my_trc
+   !!======================================================================
+   !!                         ***  MODULE trcsms_my_trc  ***
+   !! TOP :   Main module of the MY_TRC tracers
+   !!======================================================================
+   !! History :      !  2007  (C. Ethe, G. Madec)  Original code
+   !!                !  2016  (C. Ethe, T. Lovato) Revised architecture
+   !!----------------------------------------------------------------------
+   !! trc_sms_my_trc       : MY_TRC model main routine
+   !! trc_sms_my_trc_alloc : allocate arrays specific to MY_TRC sms
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE oce_trc         ! Ocean variables
+   USE trc             ! TOP variables
+   USE trd_oce
+   USE trdtrc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_my_trc       ! called by trcsms.F90 module
+   PUBLIC   trc_sms_my_trc_alloc ! called by trcini_my_trc.F90 module
+
+   ! Defined HERE the arrays specific to MY_TRC sms and ALLOCATE them in trc_sms_my_trc_alloc
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_my_trc( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_sms_my_trc  ***
+      !!
+      !! ** Purpose :   main routine of MY_TRC model
+      !!
+      !! ** Method  : -
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      INTEGER ::   jn   ! dummy loop index
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ztrmyt
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sms_my_trc')
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_sms_my_trc:  MY_TRC model'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+
+      IF( l_trdtrc )  ALLOCATE( ztrmyt(jpi,jpj,jpk) )
+
+      ! add here the call to BGC model
+
+      ! Save the trends in the mixed layer
+      IF( l_trdtrc ) THEN
+          DO jn = jp_myt0, jp_myt1
+            ztrmyt(:,:,:) = tra(:,:,:,jn)
+            CALL trd_trc( ztrmyt, jn, jptra_sms, kt )   ! save trends
+          END DO
+          DEALLOCATE( ztrmyt )
+      END IF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sms_my_trc')
+      !
+   END SUBROUTINE trc_sms_my_trc
+
+
+   INTEGER FUNCTION trc_sms_my_trc_alloc()
+      !!----------------------------------------------------------------------
+      !!              ***  ROUTINE trc_sms_my_trc_alloc  ***
+      !!----------------------------------------------------------------------
+      !
+      ! ALLOCATE here the arrays specific to MY_TRC
+      ! ALLOCATE( tab(...) , STAT=trc_sms_my_trc_alloc )
+      trc_sms_my_trc_alloc = 0      ! set to zero if no array to be allocated
+      !
+      IF( trc_sms_my_trc_alloc /= 0 ) CALL ctl_stop( 'STOP', 'trc_sms_my_trc_alloc : failed to allocate arrays' )
+      !
+   END FUNCTION trc_sms_my_trc_alloc
+
+   !!======================================================================
+END MODULE trcsms_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcwri_my_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcwri_my_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/MY_TRC/trcwri_my_trc.F90	(revision 14097)
@@ -0,0 +1,56 @@
+MODULE trcwri_my_trc
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!     trc_wri_my_trc   :  outputs of concentration fields
+   !!======================================================================
+#if defined key_top && defined key_iomput
+   !!----------------------------------------------------------------------
+   !! History :      !  2007  (C. Ethe, G. Madec)  Original code
+   !!                !  2016  (C. Ethe, T. Lovato) Revised architecture
+   !!----------------------------------------------------------------------
+   USE par_trc         ! passive tracers common variables
+   USE trc         ! passive tracers common variables 
+   USE iom         ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_my_trc 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_wri_my_trc
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)   :: cltra
+      INTEGER              :: jn
+      !!---------------------------------------------------------------------
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      DO jn = jp_myt0, jp_myt1
+         cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+         CALL iom_put( cltra, trn(:,:,:,jn) )
+      END DO
+      !
+   END SUBROUTINE trc_wri_my_trc
+
+#else
+
+CONTAINS
+
+   SUBROUTINE trc_wri_my_trc
+      !
+   END SUBROUTINE trc_wri_my_trc
+
+#endif
+
+END MODULE trcwri_my_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zbio.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zbio.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zbio.F90	(revision 14097)
@@ -0,0 +1,492 @@
+MODULE p2zbio
+   !!======================================================================
+   !!                         ***  MODULE p2zbio  ***
+   !! TOP :   LOBSTER
+   !!======================================================================
+   !! History :    -   !  1999-07  (M. Levy) Original code
+   !!              -   !  2000-12  (E. Kestenare) assign a parameter to name individual tracers
+   !!              -   !  2001-03  (M. Levy)  LNO3 + dia2d 
+   !!             2.0  !  2007-12  (C. Deltel, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   p2z_bio        :  
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trc             ! 
+   USE sms_pisces      !
+   USE p2zopt          !
+   USE trd_oce         !
+   USE trdtrc          !
+   !
+   USE lbclnk          ! 
+   USE prtctl_trc      ! Print control for debbuging
+   USE iom             !
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p2z_bio         ! called in ???
+   PUBLIC   p2z_bio_init    ! called in ???
+
+   REAL(wp) ::   tmumax     ! maximal phytoplankton growth rate            [s-1]
+   REAL(wp) ::   rgamma     ! phytoplankton exudation fraction             [%]
+   REAL(wp) ::   fphylab    ! NH4 fraction of phytoplankton exsudation
+   REAL(wp) ::   tmminp     ! minimal phytoplancton mortality rate         [0.05/86400 s-1=20 days]
+   REAL(wp) ::   aki        ! light photosynthesis half saturation constant[W/m2]
+   !
+   REAL(wp) ::   akno3      ! nitrate limitation half-saturation value     [mmol/m3]
+   REAL(wp) ::   aknh4      ! ammonium limitation half-saturation value    [mmol/m3]
+   REAL(wp) ::   taunn      ! nitrification rate                           [s-1]
+   REAL(wp) ::   psinut     ! inhibition of nitrate uptake by ammonium
+   !
+   REAL(wp) ::   taudn      ! detritus breakdown rate                        [0.1/86400 s-1=10 days]
+   REAL(wp) ::   fdetlab    ! NH4 fraction of detritus dissolution
+   !
+   REAL(wp) ::   taudomn    ! DOM breakdown rate                             [s-1]
+   !                        ! slow remineralization rate of semi-labile dom to nh4 (1 month)
+   !
+   REAL(wp) ::   rppz       ! ivlev coeff for zoo mortality
+   REAL(wp) ::   taus       ! specific zooplankton maximal grazing rate              [s-1]
+   !                                     ! 0.75/86400 s-1=8.680555E-6    1/86400 = 1.15e-5
+   REAL(wp) ::   aks        ! half-saturation constant for total zooplankton grazing [mmolN.m-3]
+   REAL(wp) ::   rpnaz      ! non-assimilated phytoplankton by zooplancton           [%]
+   REAL(wp) ::   rdnaz      ! non-assimilated detritus by zooplankton                [%]
+   REAL(wp) ::   tauzn      ! zooplancton specific excretion rate                    [0.1/86400 s-1=10 days]
+   REAL(wp) ::   tmminz     ! minimal zooplankton mortality rate                     [(mmolN/m3)-1 d-1]
+   REAL(wp) ::   fzoolab    ! NH4 fraction of zooplankton excretion
+   REAL(wp) ::   fdbod      ! zooplankton mortality fraction that goes to detritus
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p2z_bio( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_bio  ***
+      !!
+      !! ** Purpose :   compute the now trend due to biogeochemical processes
+      !!              and add it to the general trend of passive tracers equations
+      !!
+      !! ** Method  :   each now biological flux is calculated in function of now
+      !!              concentrations of tracers.
+      !!              depending on the tracer, these fluxes are sources or sinks.
+      !!              the total of the sources and sinks for each tracer
+      !!              is added to the general trend.
+      !!        
+      !!                      tra = tra + zf...tra - zftra...
+      !!                                     |         |
+      !!                                     |         |
+      !!                                  source      sink
+      !!        
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !
+      INTEGER  ::   ji, jj, jk, jl
+      REAL(wp) ::   zdet, zzoo, zphy, zno3, znh4, zdom      ! now concentrations
+      REAL(wp) ::   zlno3, zlnh4, zle, zlt                  ! limitation terms for phyto
+      REAL(wp) ::   zno3phy, znh4phy, zphynh4, zphydom
+      REAL(wp) ::   zphydet, zphyzoo, zdetzoo
+      REAL(wp) ::   zzoonh4, zzoodom, zzoodet, zdetnh4, zdetdom
+      REAL(wp) ::   znh4no3, zdomnh4, zppz, zpdz, zpppz, zppdz, zfood
+      REAL(wp) ::   zfilpz, zfildz, zphya, zzooa, zno3a
+      REAL(wp) ::   znh4a, zdeta, zdoma, zzoobod, zboddet, zdomaju
+      REAL(wp) ::   ze3t
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:)   ::   zw2d
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   zw3d
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p2z_bio')
+      !
+      IF( lk_iomput )   ALLOCATE( zw2d(jpi,jpj,17), zw3d(jpi,jpj,jpk,3) )
+
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' p2z_bio: LOBSTER bio-model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+      ENDIF
+
+      xksi(:,:) = 0.e0        ! zooplakton closure ( fbod)
+      IF( lk_iomput ) THEN
+         zw2d  (:,:,:) = 0._wp
+         zw3d(:,:,:,:) = 0._wp
+      ENDIF
+
+      !                                      ! -------------------------- !
+      DO jk = 1, jpkbm1                      !  Upper ocean (bio-layers)  !
+         !                                   ! -------------------------- !
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1 
+               ! trophic variables( det, zoo, phy, no3, nh4, dom)
+               ! ------------------------------------------------
+
+               ! negative trophic variables DO not contribute to the fluxes
+               zdet = MAX( 0.e0, trn(ji,jj,jk,jpdet) )
+               zzoo = MAX( 0.e0, trn(ji,jj,jk,jpzoo) )
+               zphy = MAX( 0.e0, trn(ji,jj,jk,jpphy) )
+               zno3 = MAX( 0.e0, trn(ji,jj,jk,jpno3) )
+               znh4 = MAX( 0.e0, trn(ji,jj,jk,jpnh4) )
+               zdom = MAX( 0.e0, trn(ji,jj,jk,jpdom) )
+
+               ! Limitations
+               zlt   = 1.
+               zle   = 1. - EXP( -etot(ji,jj,jk) / aki / zlt )
+               ! psinut,akno3,aknh4 added by asklod AS Kremeur 2005-03
+               zlno3 = zno3 * EXP( -psinut * znh4 ) / ( akno3 + zno3 )
+               zlnh4 = znh4 / (znh4+aknh4)  
+
+               ! sinks and sources
+               !    phytoplankton production and exsudation
+               zno3phy = tmumax * zle * zlt * zlno3 * zphy
+               znh4phy = tmumax * zle * zlt * zlnh4 * zphy
+
+               !    fphylab added by asklod AS Kremeur 2005-03
+               zphydom = rgamma * (1 - fphylab) * (zno3phy + znh4phy)
+               zphynh4 = rgamma * fphylab * (zno3phy + znh4phy)
+               ! zooplankton production
+               !    preferences
+               zppz = rppz
+               zpdz = 1. - rppz
+               zpppz = ( zppz * zphy ) / ( ( zppz * zphy + zpdz * zdet ) + 1.e-13 )
+               zppdz = ( zpdz * zdet ) / ( ( zppz * zphy + zpdz * zdet ) + 1.e-13 )
+               zfood = zpppz * zphy + zppdz * zdet
+               !    filtration 
+               zfilpz = taus * zpppz / (aks + zfood)
+               zfildz = taus * zppdz / (aks + zfood)
+               !    grazing
+               zphyzoo = zfilpz * zphy * zzoo
+               zdetzoo = zfildz * zdet * zzoo
+
+               ! fecal pellets production
+               zzoodet = rpnaz * zphyzoo + rdnaz * zdetzoo
+
+               ! zooplankton liquide excretion
+               zzoonh4 = tauzn * fzoolab * zzoo  
+               zzoodom = tauzn * (1 - fzoolab) * zzoo
+
+               ! mortality
+               !    phytoplankton mortality
+               zphydet = tmminp * zphy
+
+               !    zooplankton mortality
+               !    closure : flux grazing is redistributed below level jpkbio
+               zzoobod = tmminz * zzoo * zzoo
+               xksi(ji,jj) = xksi(ji,jj) + (1-fdbod) * zzoobod * e3t_n(ji,jj,jk)
+               zboddet = fdbod * zzoobod
+
+               ! detritus and dom breakdown
+               zdetnh4 = taudn * fdetlab * zdet
+               zdetdom = taudn * (1 - fdetlab) * zdet
+
+               zdomnh4 = taudomn * zdom
+
+               ! flux added to express how the excess of nitrogen from 
+               ! PHY, ZOO and DET to DOM goes directly to NH4 (flux of ajustment)
+               zdomaju = (1 - redf/reddom) * (zphydom + zzoodom + zdetdom)
+
+               ! Nitrification 
+               znh4no3 = taunn * znh4
+
+               ! determination of trends
+               !    total trend for each biological tracer
+               zphya =   zno3phy + znh4phy - zphynh4 - zphydom - zphyzoo - zphydet
+               zzooa =   zphyzoo + zdetzoo - zzoodet - zzoodom - zzoonh4 - zzoobod
+               zno3a = - zno3phy + znh4no3
+               znh4a = - znh4phy - znh4no3 + zphynh4 + zzoonh4 + zdomnh4 + zdetnh4 + zdomaju
+               zdeta =   zphydet + zzoodet - zdetzoo - zdetnh4 - zdetdom + zboddet
+               zdoma =   zphydom + zzoodom + zdetdom - zdomnh4 - zdomaju
+
+               ! tracer flux at totox-point added to the general trend
+               tra(ji,jj,jk,jpdet) = tra(ji,jj,jk,jpdet) + zdeta
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) + zzooa
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) + zphya
+               tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) + zno3a
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + znh4a
+               tra(ji,jj,jk,jpdom) = tra(ji,jj,jk,jpdom) + zdoma
+
+                IF( lk_iomput ) THEN
+                  ! convert fluxes in per day
+                  ze3t = e3t_n(ji,jj,jk) * 86400._wp
+                  zw2d(ji,jj,1)  = zw2d(ji,jj,1)  + zno3phy * ze3t
+                  zw2d(ji,jj,2)  = zw2d(ji,jj,2)  + znh4phy * ze3t
+                  zw2d(ji,jj,3)  = zw2d(ji,jj,3)  + zphydom * ze3t
+                  zw2d(ji,jj,4)  = zw2d(ji,jj,4)  + zphynh4 * ze3t
+                  zw2d(ji,jj,5)  = zw2d(ji,jj,5)  + zphyzoo * ze3t
+                  zw2d(ji,jj,6)  = zw2d(ji,jj,6)  + zphydet * ze3t
+                  zw2d(ji,jj,7)  = zw2d(ji,jj,7)  + zdetzoo * ze3t
+                  zw2d(ji,jj,8)  = zw2d(ji,jj,8)  + zzoodet * ze3t
+                  zw2d(ji,jj,9)  = zw2d(ji,jj,9)  + zzoobod * ze3t
+                  zw2d(ji,jj,10) = zw2d(ji,jj,10) + zzoonh4 * ze3t
+                  zw2d(ji,jj,11) = zw2d(ji,jj,11) + zzoodom * ze3t
+                  zw2d(ji,jj,12) = zw2d(ji,jj,12) + znh4no3 * ze3t
+                  zw2d(ji,jj,13) = zw2d(ji,jj,13) + zdomnh4 * ze3t
+                  zw2d(ji,jj,14) = zw2d(ji,jj,14) + zdetnh4 * ze3t
+                  zw2d(ji,jj,15) = zw2d(ji,jj,15) + ( zno3phy + znh4phy - zphynh4 - zphydom - zphyzoo - zphydet ) * ze3t
+                  zw2d(ji,jj,16) = zw2d(ji,jj,16) + ( zphyzoo + zdetzoo - zzoodet - zzoobod - zzoonh4 - zzoodom ) * ze3t
+                  zw2d(ji,jj,17) = zw2d(ji,jj,17) + zdetdom * ze3t
+                  !   
+                  zw3d(ji,jj,jk,1) = zno3phy * 86400
+                  zw3d(ji,jj,jk,2) = znh4phy * 86400     
+                  zw3d(ji,jj,jk,3) = znh4no3 * 86400   
+                   ! 
+                ENDIF
+            END DO
+         END DO
+      END DO
+
+      !                                      ! -------------------------- !
+      DO jk = jpkb, jpkm1                    !  Upper ocean (bio-layers)  !
+         !                                   ! -------------------------- !
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1 
+               ! remineralisation of all quantities towards nitrate 
+
+               !    trophic variables( det, zoo, phy, no3, nh4, dom)
+               !       negative trophic variables DO not contribute to the fluxes
+               zdet = MAX( 0.e0, trn(ji,jj,jk,jpdet) )
+               zzoo = MAX( 0.e0, trn(ji,jj,jk,jpzoo) )
+               zphy = MAX( 0.e0, trn(ji,jj,jk,jpphy) )
+               zno3 = MAX( 0.e0, trn(ji,jj,jk,jpno3) )
+               znh4 = MAX( 0.e0, trn(ji,jj,jk,jpnh4) )
+               zdom = MAX( 0.e0, trn(ji,jj,jk,jpdom) )
+
+               !    Limitations
+               zlt   = 0.e0
+               zle   = 0.e0
+               zlno3 = 0.e0
+               zlnh4 = 0.e0
+
+               !    sinks and sources
+               !       phytoplankton production and exsudation
+               zno3phy = 0.e0
+               znh4phy = 0.e0
+               zphydom = 0.e0
+               zphynh4 = 0.e0
+
+               !    zooplankton production
+               zphyzoo = 0.e0      ! grazing
+               zdetzoo = 0.e0
+
+               zzoodet = 0.e0      ! fecal pellets production
+
+               zzoonh4 = tauzn * fzoolab * zzoo         ! zooplankton liquide excretion
+               zzoodom = tauzn * (1 - fzoolab) * zzoo
+
+               !    mortality
+               zphydet = tmminp * zphy      ! phytoplankton mortality
+
+               zzoobod = 0.e0               ! zooplankton mortality
+               zboddet = 0.e0               ! closure : flux fbod is redistributed below level jpkbio
+
+               !    detritus and dom breakdown
+               zdetnh4 = taudn * fdetlab * zdet
+               zdetdom = taudn * (1 - fdetlab) * zdet
+
+               zdomnh4 = taudomn * zdom
+               zdomaju = (1 - redf/reddom) * (zphydom + zzoodom + zdetdom)
+
+               !    Nitrification
+               znh4no3 = taunn * znh4
+
+
+               ! determination of trends
+               !     total trend for each biological tracer
+               zphya =   zno3phy + znh4phy - zphynh4 - zphydom - zphyzoo - zphydet
+               zzooa =   zphyzoo + zdetzoo - zzoodet - zzoodom - zzoonh4 - zzoobod
+               zno3a = - zno3phy + znh4no3 
+               znh4a = - znh4phy - znh4no3 + zphynh4 + zzoonh4 + zdomnh4 + zdetnh4 + zdomaju
+               zdeta = zphydet + zzoodet  - zdetzoo - zdetnh4 - zdetdom + zboddet
+               zdoma = zphydom + zzoodom + zdetdom - zdomnh4 - zdomaju
+
+               ! tracer flux at totox-point added to the general trend
+               tra(ji,jj,jk,jpdet) = tra(ji,jj,jk,jpdet) + zdeta
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) + zzooa
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) + zphya
+               tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) + zno3a
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + znh4a
+               tra(ji,jj,jk,jpdom) = tra(ji,jj,jk,jpdom) + zdoma
+               !
+                IF( lk_iomput ) THEN                  ! convert fluxes in per day
+                  ze3t = e3t_n(ji,jj,jk) * 86400._wp
+                  zw2d(ji,jj,1)  = zw2d(ji,jj,1)  + zno3phy * ze3t
+                  zw2d(ji,jj,2)  = zw2d(ji,jj,2)  + znh4phy * ze3t
+                  zw2d(ji,jj,3)  = zw2d(ji,jj,3)  + zphydom * ze3t
+                  zw2d(ji,jj,4)  = zw2d(ji,jj,4)  + zphynh4 * ze3t
+                  zw2d(ji,jj,5)  = zw2d(ji,jj,5)  + zphyzoo * ze3t
+                  zw2d(ji,jj,6)  = zw2d(ji,jj,6)  + zphydet * ze3t
+                  zw2d(ji,jj,7)  = zw2d(ji,jj,7)  + zdetzoo * ze3t
+                  zw2d(ji,jj,8)  = zw2d(ji,jj,8)  + zzoodet * ze3t
+                  zw2d(ji,jj,9)  = zw2d(ji,jj,9)  + zzoobod * ze3t
+                  zw2d(ji,jj,10) = zw2d(ji,jj,10) + zzoonh4 * ze3t
+                  zw2d(ji,jj,11) = zw2d(ji,jj,11) + zzoodom * ze3t
+                  zw2d(ji,jj,12) = zw2d(ji,jj,12) + znh4no3 * ze3t
+                  zw2d(ji,jj,13) = zw2d(ji,jj,13) + zdomnh4 * ze3t
+                  zw2d(ji,jj,14) = zw2d(ji,jj,14) + zdetnh4 * ze3t
+                  zw2d(ji,jj,15) = zw2d(ji,jj,15) + ( zno3phy + znh4phy - zphynh4 - zphydom - zphyzoo - zphydet ) * ze3t
+                  zw2d(ji,jj,16) = zw2d(ji,jj,16) + ( zphyzoo + zdetzoo - zzoodet - zzoobod - zzoonh4 - zzoodom ) * ze3t
+                  zw2d(ji,jj,17) = zw2d(ji,jj,17) + zdetdom * ze3t
+                  !   
+                  zw3d(ji,jj,jk,1) = zno3phy * 86400._wp
+                  zw3d(ji,jj,jk,2) = znh4phy * 86400._wp
+                  zw3d(ji,jj,jk,3) = znh4no3 * 86400._wp
+                  !
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput ) THEN
+         CALL lbc_lnk( 'p2zbio', zw2d(:,:,:),'T', 1. )
+         CALL lbc_lnk_multi( 'p2zbio', zw3d(:,:,:,1),'T', 1., zw3d(:,:,:,2),'T', 1., zw3d(:,:,:,3),'T', 1. )
+         ! 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) )
+         !
+      ENDIF
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('bio')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( lk_iomput )   DEALLOCATE( zw2d, zw3d )
+      !
+      IF( ln_timing )  CALL timing_stop('p2z_bio')
+      !
+   END SUBROUTINE p2z_bio
+
+
+   SUBROUTINE p2z_bio_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p2z_bio_init  ***
+      !!
+      !! ** Purpose :  biological parameters 
+      !!
+      !! ** Method  :   Read namelist and check the parameters
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namlobphy/ tmumax, rgamma, fphylab, tmminp, aki
+      NAMELIST/namlobnut/ akno3, aknh4, taunn, psinut
+      NAMELIST/namlobzoo/ rppz, taus, aks, rpnaz, rdnaz, tauzn, fzoolab, fdbod, tmminz
+      NAMELIST/namlobdet/ taudn, fdetlab
+      NAMELIST/namlobdom/ taudomn
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' p2z_bio_init : LOBSTER bio-model initialization'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~'
+      !
+      REWIND( numnatp_ref )              ! Namelist namlobphy in reference namelist : Lobster biological parameters
+      READ  ( numnatp_ref, namlobphy, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlobphy in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobphy in configuration namelist : Lobster biological parameters
+      READ  ( numnatp_cfg, namlobphy, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobphy in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobphy )
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist namlobphy'
+         WRITE(numout,*) '      phyto max growth rate                                tmumax    =', 86400 * tmumax, ' d'
+         WRITE(numout,*) '      phytoplankton exudation fraction                     rgamma    =', rgamma
+         WRITE(numout,*) '      NH4 fraction of phytoplankton exsudation             fphylab   =', fphylab
+         WRITE(numout,*) '      minimal phyto mortality rate                         tmminp    =', 86400 * tmminp
+         WRITE(numout,*) '      light hlaf saturation constant                       aki       =', aki
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist namlobnut in reference namelist : Lobster nutriments parameters
+      READ  ( numnatp_ref, namlobnut, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlobnut in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobnut in configuration namelist : Lobster nutriments parameters
+      READ  ( numnatp_cfg, namlobnut, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobnut in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobnut )
+
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) '   Namelist namlobnut'
+         WRITE(numout,*) '      half-saturation nutrient for no3 uptake              akno3     =', akno3
+         WRITE(numout,*) '      half-saturation nutrient for nh4 uptake              aknh4     =', aknh4
+         WRITE(numout,*) '      nitrification rate                                   taunn     =', taunn
+         WRITE(numout,*) '      inhibition of no3 uptake by nh4                      psinut    =', psinut
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist namlobzoo in reference namelist : Lobster zooplankton parameters
+      READ  ( numnatp_ref, namlobzoo, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlobzoo in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobzoo in configuration namelist : Lobster zooplankton parameters
+      READ  ( numnatp_cfg, namlobzoo, IOSTAT = ios, ERR = 906 )
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobzoo in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobzoo )
+
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) '   Namelist namlobzoo'
+         WRITE(numout,*) '      zoo preference for phyto                             rppz      =', rppz
+         WRITE(numout,*) '      maximal zoo grazing rate                             taus      =', 86400 * taus, ' d'
+         WRITE(numout,*) '      half saturation constant for zoo food                aks       =', aks
+         WRITE(numout,*) '      non-assimilated phyto by zoo                         rpnaz     =', rpnaz
+         WRITE(numout,*) '      non-assimilated detritus by zoo                      rdnaz     =', rdnaz
+         WRITE(numout,*) '      zoo specific excretion rate                          tauzn     =', 86400 * tauzn
+         WRITE(numout,*) '      minimal zoo mortality rate                           tmminz    =', 86400 * tmminz
+         WRITE(numout,*) '      NH4 fraction of zooplankton excretion                fzoolab   =', fzoolab
+         WRITE(numout,*) '      Zooplankton mortality fraction that goes to detritus fdbod     =', fdbod
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist namlobdet in reference namelist : Lobster detritus parameters
+      READ  ( numnatp_ref, namlobdet, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlobdet in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobdet in configuration namelist : Lobster detritus parameters
+      READ  ( numnatp_cfg, namlobdet, IOSTAT = ios, ERR = 908 )
+908   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobdet in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobdet )
+
+      IF(lwp) THEN
+          WRITE(numout,*) 
+          WRITE(numout,*) '   Namelist namlobdet'
+          WRITE(numout,*) '      detrital breakdown rate                              taudn     =', 86400 * taudn , ' d'
+          WRITE(numout,*) '      NH4 fraction of detritus dissolution                 fdetlab   =', fdetlab
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist namlobdom in reference namelist : Lobster DOM breakdown rate
+      READ  ( numnatp_ref, namlobdom, IOSTAT = ios, ERR = 909)
+909   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlobdom in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobdom in configuration namelist : Lobster DOM breakdown rate
+      READ  ( numnatp_cfg, namlobdom, IOSTAT = ios, ERR = 910 )
+910   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobdom in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobdom )
+
+      IF(lwp) THEN
+          WRITE(numout,*) 
+          WRITE(numout,*) '   Namelist namlobdom'
+          WRITE(numout,*) '      DOM breakdown rate                                 taudomn     =', 86400 * taudn , ' d'
+      ENDIF
+      !
+   END SUBROUTINE p2z_bio_init
+
+   !!======================================================================
+END MODULE p2zbio
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zexp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zexp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zexp.F90	(revision 14097)
@@ -0,0 +1,255 @@
+MODULE p2zexp
+   !!======================================================================
+   !!                         ***  MODULE p2zsed  ***
+   !! TOP :   LOBSTER Compute loss of organic matter in the sediments
+   !!======================================================================
+   !! History :    -   !  1999    (O. Aumont, C. Le Quere)  original code
+   !!              -   !  2001-05 (O. Aumont, E. Kestenare) add sediment computations
+   !!             1.0  !  2005-06 (A.-S. Kremeur) new temporal integration for sedpoc
+   !!             2.0  !  2007-12  (C. Deltel, G. Madec)  F90
+   !!             3.5  !  2012-03  (C. Ethe)  Merge PISCES-LOBSTER
+   !!----------------------------------------------------------------------
+   !!   p2z_exp        :  Compute loss of organic matter in the sediments
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trc
+   USE sms_pisces
+   USE p2zsed
+   USE lbclnk
+   USE prtctl_trc      ! Print control for debbuging
+   USE trd_oce
+   USE trdtrc
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p2z_exp    
+   PUBLIC   p2z_exp_init 
+   PUBLIC   p2z_exp_alloc
+
+   !
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   dminl     !: fraction of sinking POC released in sediments
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   dmin3     !: fraction of sinking POC released at each level
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   sedpocb   !: mass of POC in sediments
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   sedpocn   !: mass of POC in sediments
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   cmask     !: Coastal mask area
+   REAL(wp)                                ::   areacot   !: surface coastal area
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p2z_exp( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_exp  ***
+      !!
+      !! ** Purpose :   MODELS EXPORT OF BIOGENIC MATTER (POC ''SOFT
+      !!              TISSUE'') AND ITS DISTRIBUTION IN WATER COLUMN
+      !!
+      !! ** Method  : - IN THE SURFACE LAYER POC IS PRODUCED ACCORDING TO
+      !!              NURTRIENTS AVAILABLE AND GROWTH CONDITIONS. NUTRIENT UPTAKE
+      !!              KINETICS FOLLOW MICHAELIS-MENTON FORMULATION. 
+      !!              THE TOTAL PARTICLE AMOUNT PRODUCED, IS DISTRIBUTED IN THE WATER
+      !!              COLUMN BELOW THE SURFACE LAYER.
+      !!---------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !!
+      INTEGER  ::   ji, jj, jk, jl, ikt
+      REAL(wp) ::   zgeolpoc, zfact, zwork, ze3t, zsedpocd, zmaskt
+      REAL(wp), DIMENSION(jpi,jpj)   ::  zsedpoca
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p2z_exp')
+      !
+      IF( kt == nittrc000 )   CALL p2z_exp_init
+
+      zsedpoca(:,:) = 0.
+
+
+      ! VERTICAL DISTRIBUTION OF NEWLY PRODUCED BIOGENIC
+      ! POC IN THE WATER COLUMN
+      ! (PARTS OF NEWLY FORMED MATTER REMAINING IN THE DIFFERENT
+      ! LAYERS IS DETERMINED BY DMIN3 DEFINED IN sms_p2z.F90
+      ! ----------------------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               ze3t = 1. / e3t_n(ji,jj,jk)
+               tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) + ze3t * dmin3(ji,jj,jk) * xksi(ji,jj)
+            END DO
+         END DO
+      END DO
+
+      ! Find the last level of the water column
+      ! Compute fluxes due to sinking particles (slow)
+   
+
+      zgeolpoc = 0.e0         !     Initialization
+      ! Release of nutrients from the "simple" sediment
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1
+            ikt = mbkt(ji,jj) 
+            tra(ji,jj,ikt,jpno3) = tra(ji,jj,ikt,jpno3) + sedlam * sedpocn(ji,jj) / e3t_n(ji,jj,ikt) 
+            ! Deposition of organic matter in the sediment
+            zwork = vsed * trn(ji,jj,ikt,jpdet)
+            zsedpoca(ji,jj) = ( zwork + dminl(ji,jj) * xksi(ji,jj)   &
+               &           - sedlam * sedpocn(ji,jj) - sedlostpoc * sedpocn(ji,jj) ) * rdt
+            zgeolpoc = zgeolpoc + sedlostpoc * sedpocn(ji,jj) * e1e2t(ji,jj)
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1
+            tra(ji,jj,1,jpno3) = tra(ji,jj,1,jpno3) + zgeolpoc * cmask(ji,jj) / areacot / e3t_n(ji,jj,1)
+         END DO
+      END DO
+
+      CALL lbc_lnk( 'p2zexp', sedpocn, 'T', 1. )
+ 
+      ! Oa & Ek: diagnostics depending on jpdia2d !          left as example
+      IF( lk_iomput )  CALL iom_put( "SEDPOC" , sedpocn )
+
+      
+      ! Time filter and swap of arrays
+      ! ------------------------------
+      IF( neuler == 0 .AND. kt == nittrc000 ) THEN        ! Euler time-stepping at first time-step
+        !                                             ! (only swap)
+        sedpocn(:,:) = zsedpoca(:,:)
+        !                                              
+      ELSE
+        !
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              zsedpocd = zsedpoca(ji,jj) - 2. * sedpocn(ji,jj) + sedpocb(ji,jj)      ! time laplacian on tracers
+              sedpocb(ji,jj) = sedpocn(ji,jj) + atfp * zsedpocd                     ! sedpocb <-- filtered sedpocn
+              sedpocn(ji,jj) = zsedpoca(ji,jj)                                       ! sedpocn <-- sedpoca
+           END DO
+        END DO
+        ! 
+      ENDIF
+      !
+      IF( lrst_trc ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'p2z_exp : POC in sediment fields written in ocean restart file ',   &
+            &                    'at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         CALL iom_rstput( kt, nitrst, numrtw, 'SEDB'//ctrcnm(jpdet), sedpocb(:,:) )
+         CALL iom_rstput( kt, nitrst, numrtw, 'SEDN'//ctrcnm(jpdet), sedpocn(:,:) )
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('exp')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('p2z_exp')
+      !
+   END SUBROUTINE p2z_exp
+
+
+   SUBROUTINE p2z_exp_init
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE p4z_exp_init  ***
+      !! ** purpose :   specific initialisation for export
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zmaskt, zfluo, zfluu
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zrro
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdm0
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' p2z_exp: LOBSTER export'
+         WRITE(numout,*) ' ~~~~~~~'
+         WRITE(numout,*) '  compute remineralisation-damping arrays for tracers'
+      ENDIF
+      !
+
+      ! Calculate vertical distribution of newly formed biogenic poc
+      ! in the water column in the case of max. possible bottom depth
+      ! ------------------------------------------------------------
+      zdm0 = 0._wp
+      zrro = 1._wp
+      DO jk = jpkb, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zfluo = ( gdepw_n(ji,jj,jk  ) / gdepw_n(ji,jj,jpkb) )**xhr
+               zfluu = ( gdepw_n(ji,jj,jk+1) / gdepw_n(ji,jj,jpkb) )**xhr
+               IF( zfluo.GT.1. )   zfluo = 1._wp
+               zdm0(ji,jj,jk) = zfluo - zfluu
+               IF( jk <= jpkb-1 )   zdm0(ji,jj,jk) = 0._wp
+               zrro(ji,jj) = zrro(ji,jj) - zdm0(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      zdm0(:,:,jpk) = zrro(:,:)
+
+      ! Calculate vertical distribution of newly formed biogenic poc
+      ! in the water column with realistic topography (first "dry" layer
+      ! contains total fraction, which has passed to the upper layers)
+      ! ----------------------------------------------------------------------
+      dminl(:,:)   = 0._wp
+      dmin3(:,:,:) = zdm0
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( tmask(ji,jj,jk) == 0._wp ) THEN
+                  dminl(ji,jj) = dminl(ji,jj) + dmin3(ji,jj,jk)
+                  dmin3(ji,jj,jk) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( tmask(ji,jj,1) == 0 )   dmin3(ji,jj,1) = 0._wp
+         END DO
+      END DO
+
+      ! Coastal mask 
+      cmask(:,:) = 0._wp
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1
+            IF( tmask(ji,jj,1) /= 0. ) THEN
+               zmaskt = tmask(ji+1,jj,1) * tmask(ji-1,jj,1) * tmask(ji,jj+1,1) * tmask(ji,jj-1,1) 
+               IF( zmaskt == 0. )   cmask(ji,jj) = 1._wp
+            END IF
+         END DO
+      END DO
+      CALL lbc_lnk( 'p2zexp', cmask , 'T', 1. )      ! lateral boundary conditions on cmask   (sign unchanged)
+      areacot = glob_sum( 'p2zexp', e1e2t(:,:) * cmask(:,:) )
+      !
+      IF( ln_rsttr ) THEN
+         CALL iom_get( numrtr, jpdom_autoglo, 'SEDB'//ctrcnm(jpdet), sedpocb(:,:) )
+         CALL iom_get( numrtr, jpdom_autoglo, 'SEDN'//ctrcnm(jpdet), sedpocn(:,:) )
+      ELSE
+         sedpocb(:,:) = 0._wp
+         sedpocn(:,:) = 0._wp
+      ENDIF
+      !
+   END SUBROUTINE p2z_exp_init
+
+   INTEGER FUNCTION p2z_exp_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_exp_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( cmask(jpi,jpj) , dminl(jpi,jpj) , dmin3(jpi,jpj,jpk), &
+         &      sedpocb(jpi,jpj) , sedpocn(jpi,jpj),   STAT=p2z_exp_alloc )
+      IF( p2z_exp_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p2z_exp_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p2z_exp_alloc
+
+   !!======================================================================
+END MODULE p2zexp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zopt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zopt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zopt.F90	(revision 14097)
@@ -0,0 +1,203 @@
+MODULE p2zopt
+   !!======================================================================
+   !!                         ***  MODULE p2zopt  ***
+   !! TOP :   LOBSTER Compute the light availability in the water column
+   !!======================================================================
+   !! History :    -   !  1995-05  (M. Levy) Original code
+   !!              -   !  1999-09  (J.-M. Andre, M. Levy) 
+   !!              -   !  1999-11  (C. Menkes, M.-A. Foujols) itabe initial
+   !!              -   !  2000-02  (M.A. Foujols) change x**y par exp(y*log(x))
+   !!   NEMO      2.0  !  2007-12  (C. Deltel, G. Madec)  F90
+   !!             3.2  !  2009-04  (C. Ethe, G. Madec)  minor optimisation + style
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   p2z_opt        :   Compute the light availability in the water column
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trc
+   USE sms_pisces
+   USE prtctl_trc      ! Print control for debbuging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p2z_opt   !
+   PUBLIC   p2z_opt_init   !
+
+   REAL(wp), PUBLIC ::  xkr0      !: water coefficient absorption in red      
+   REAL(wp), PUBLIC ::  xkg0      !: water coefficient absorption in green    
+   REAL(wp), PUBLIC ::  xkrp      !: pigment coefficient absorption in red    
+   REAL(wp), PUBLIC ::  xkgp      !: pigment coefficient absorption in green  
+   REAL(wp), PUBLIC ::  xlr       !: exposant for pigment absorption in red  
+   REAL(wp), PUBLIC ::  xlg       !: exposant for pigment absorption in green 
+   REAL(wp), PUBLIC ::  rpig      !: chla/chla+phea ratio    
+   !                 
+   REAL(wp), PUBLIC ::  rcchl     ! Carbone/Chlorophyl ratio [mgC.mgChla-1]
+   REAL(wp), PUBLIC ::  redf      ! redfield ratio (C:N) for phyto
+   REAL(wp), PUBLIC ::  reddom    ! redfield ratio (C:N) for DOM
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p2z_opt( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_opt  ***
+      !!
+      !! ** Purpose :   computes the light propagation in the water column
+      !!              and the euphotic layer depth
+      !!
+      !! ** Method  :   local par is computed in w layers using light propagation
+      !!              mean par in t layers are computed by integration
+      !!
+!!gm please remplace the '???' by true comments
+      !! ** Action  :   etot   ???
+      !!                neln   ???
+      !!---------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   kt   ! index of the time stepping
+      !!
+      INTEGER  ::   ji, jj, jk          ! dummy loop indices
+      CHARACTER (len=25) ::   charout   ! temporary character
+      REAL(wp) ::   zpig                ! log of the total pigment
+      REAL(wp) ::   zkr, zkg            ! total absorption coefficient in red and green
+      REAL(wp) ::   zcoef               ! temporary scalar
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zpar100, zpar0m
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zparr, zparg
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p2z_opt')
+      !
+
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' p2z_opt : LOBSTER optic-model'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~ '
+      ENDIF
+
+      !                                          ! surface irradiance
+      !                                          ! ------------------
+      IF( ln_dm2dc ) THEN   ;   zpar0m(:,:) = qsr_mean(:,:) * 0.43
+      ELSE                  ;   zpar0m(:,:) = qsr     (:,:) * 0.43
+      ENDIF
+      zpar100(:,:)   = zpar0m(:,:) * 0.01
+      zparr  (:,:,1) = zpar0m(:,:) * 0.5
+      zparg  (:,:,1) = zpar0m(:,:) * 0.5
+
+      !                                          ! Photosynthetically Available Radiation (PAR)
+      zcoef = 12 * redf / rcchl / rpig           ! --------------------------------------
+      DO jk = 2, jpk                                  ! local par at w-levels
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zpig = LOG(  MAX( TINY(0.), trn(ji,jj,jk-1,jpphy) ) * zcoef  )
+               zkr  = xkr0 + xkrp * EXP( xlr * zpig )
+               zkg  = xkg0 + xkgp * EXP( xlg * zpig )
+               zparr(ji,jj,jk) = zparr(ji,jj,jk-1) * EXP( -zkr * e3t_n(ji,jj,jk-1) )
+               zparg(ji,jj,jk) = zparg(ji,jj,jk-1) * EXP( -zkg * e3t_n(ji,jj,jk-1) )
+            END DO
+        END DO
+      END DO
+      DO jk = 1, jpkm1                                ! mean par at t-levels
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zpig = LOG(  MAX( TINY(0.), trn(ji,jj,jk,jpphy) ) * zcoef  )
+               zkr  = xkr0 + xkrp * EXP( xlr * zpig )
+               zkg  = xkg0 + xkgp * EXP( xlg * zpig )
+               zparr(ji,jj,jk) = zparr(ji,jj,jk) / ( zkr * e3t_n(ji,jj,jk) ) * ( 1 - EXP( -zkr * e3t_n(ji,jj,jk) ) )
+               zparg(ji,jj,jk) = zparg(ji,jj,jk) / ( zkg * e3t_n(ji,jj,jk) ) * ( 1 - EXP( -zkg * e3t_n(ji,jj,jk) ) )
+               etot (ji,jj,jk) = MAX( zparr(ji,jj,jk) + zparg(ji,jj,jk), 1.e-15 )
+            END DO
+         END DO
+      END DO
+
+      !                                          ! Euphotic layer
+      !                                          ! --------------
+      neln(:,:) = 1                                   ! euphotic layer level
+      DO jk = 1, jpkm1                                ! (i.e. 1rst T-level strictly below EL bottom)
+         DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF( etot(ji,jj,jk) >= zpar100(ji,jj) )   neln(ji,jj) = jk + 1 
+           END DO
+         END DO
+      END DO
+      !                                               ! Euphotic layer depth
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            heup(ji,jj) = gdepw_n(ji,jj,neln(ji,jj))
+         END DO
+      END DO 
+
+
+      IF(ln_ctl) THEN      ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('opt')")
+         CALL prt_ctl_trc_info( charout )
+         CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p2z_opt')
+      !
+   END SUBROUTINE p2z_opt
+
+
+   SUBROUTINE p2z_opt_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p2z_opt_init  ***
+      !!
+      !! ** Purpose :  optical parameters 
+      !!
+      !! ** Method  :   Read the namlobopt namelist and check the parameters
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namlobopt/ xkg0, xkr0, xkgp, xkrp, xlg, xlr, rpig
+      NAMELIST/namlobrat/ rcchl, redf, reddom
+      !!----------------------------------------------------------------------
+
+      REWIND( numnatp_ref )              ! Namelist namlobopt in reference namelist : Lobster options
+      READ  ( numnatp_ref, namlobopt, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namlobopt in reference namelist' )
+
+      REWIND( numnatp_cfg )              ! Namelist namlobopt in configuration namelist : Lobster options
+      READ  ( numnatp_cfg, namlobopt, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namlobopt in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobopt )
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' Namelist namlobopt'
+         WRITE(numout,*) '    green   water absorption coeff                       xkg0  = ', xkg0
+         WRITE(numout,*) '    red water absorption coeff                           xkr0  = ', xkr0
+         WRITE(numout,*) '    pigment red absorption coeff                         xkrp  = ', xkrp
+         WRITE(numout,*) '    pigment green absorption coeff                       xkgp  = ', xkgp
+         WRITE(numout,*) '    green chl exposant                                   xlg   = ', xlg
+         WRITE(numout,*) '    red   chl exposant                                   xlr   = ', xlr
+         WRITE(numout,*) '    chla/chla+phea ratio                                 rpig  = ', rpig
+         WRITE(numout,*) ' '
+      ENDIF
+      !
+      REWIND( numnatp_ref )              ! Namelist namlobrat in reference namelist : Lobster ratios
+      READ  ( numnatp_ref, namlobrat, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namlobrat in reference namelist' )
+
+      REWIND( numnatp_cfg )              ! Namelist namlobrat in configuration namelist : Lobster ratios
+      READ  ( numnatp_cfg, namlobrat, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 ) CALL ctl_nam ( ios , 'namlobrat in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobrat )
+
+      IF(lwp) THEN
+          WRITE(numout,*) ' Namelist namlobrat'
+         WRITE(numout,*) '     carbone/chlorophyl ratio                             rcchl = ', rcchl
+          WRITE(numout,*) '    redfield ratio  c:n for phyto                        redf      =', redf
+          WRITE(numout,*) '    redfield ratio  c:n for DOM                          reddom    =', reddom
+          WRITE(numout,*) ' '
+      ENDIF
+      !
+   END SUBROUTINE p2z_opt_init
+
+   !!======================================================================
+END MODULE p2zopt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsed.F90	(revision 14097)
@@ -0,0 +1,154 @@
+MODULE p2zsed
+   !!======================================================================
+   !!                         ***  MODULE p2zsed  ***
+   !! TOP :   PISCES Compute loss of organic matter in the sediments
+   !!======================================================================
+   !! History :    -   !  1995-06 (M. Levy)  original code
+   !!              -   !  2000-12 (E. Kestenare)  clean up
+   !!             2.0  !  2007-12  (C. Deltel, G. Madec)  F90 + simplifications
+   !!----------------------------------------------------------------------
+   !!   p2z_sed        :  Compute loss of organic matter in the sediments
+   !!----------------------------------------------------------------------
+   USE oce_trc         !
+   USE trd_oce         !
+   USE trdtrc          !
+   USE trc             !
+   USE sms_pisces      !
+   !
+   USE lbclnk          !
+   USE iom             !
+   USE prtctl_trc      ! Print control for debbuging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p2z_sed         ! called in ???
+   PUBLIC   p2z_sed_init    ! called in ???
+
+   REAL(wp), PUBLIC ::   sedlam      !: time coefficient of POC remineralization in sediments
+   REAL(wp), PUBLIC ::   sedlostpoc  !: mass of POC lost in sediments 
+   REAL(wp), PUBLIC ::   vsed        !: detritus sedimentation speed [m/s] 
+   REAL(wp), PUBLIC ::   xhr         !: coeff for martin''s remineralisation profile
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p2z_sed( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_sed  ***
+      !!
+      !! ** Purpose :   compute the now trend due to the vertical sedimentation of
+      !!              detritus and add it to the general trend of detritus equations
+      !!
+      !! ** Method  :   this ROUTINE compute not exactly the advection but the
+      !!              transport term, i.e.  dz(wt) and dz(ws)., dz(wtr)
+      !!              using an upstream scheme
+      !!              the now vertical advection of tracers is given by:
+      !!                      dz(trn wn) = 1/bt dk+1( e1t e2t vsed (trn) )
+      !!              add this trend now to the general trend of tracer (ta,sa,tra):
+      !!                             tra = tra + dz(trn wn)
+      !!        
+      !!              IF 'key_diabio' is defined, the now vertical advection
+      !!              trend of passive tracers is saved for futher diagnostics.
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !
+      INTEGER  ::   ji, jj, jk, jl, ierr
+      CHARACTER (len=25) :: charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zw2d
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zwork, ztra
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p2z_sed')
+      !
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' p2z_sed: LOBSTER sedimentation'
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+      ENDIF
+
+      ! sedimentation of detritus  : upstream scheme
+      ! --------------------------------------------
+
+      ! for detritus sedimentation only - jpdet
+      zwork(:,:,1  ) = 0.e0      ! surface value set to zero
+      zwork(:,:,jpk) = 0.e0      ! bottom value  set to zero
+
+      ! tracer flux at w-point: we use -vsed (downward flux)  with simplification : no e1*e2
+      DO jk = 2, jpkm1
+         zwork(:,:,jk) = -vsed * trn(:,:,jk-1,jpdet)
+      END DO
+
+      ! tracer flux divergence at t-point added to the general trend
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ztra(ji,jj,jk)  = - ( zwork(ji,jj,jk) - zwork(ji,jj,jk+1) ) / e3t_n(ji,jj,jk)
+               tra(ji,jj,jk,jpdet) = tra(ji,jj,jk,jpdet) + ztra(ji,jj,jk) 
+            END DO
+         END DO
+      END DO
+
+      IF( lk_iomput )  THEN
+         IF( iom_use( "TDETSED" ) ) THEN
+            ALLOCATE( zw2d(jpi,jpj) )
+            zw2d(:,:) =  ztra(:,:,1) * e3t_n(:,:,1) * 86400._wp
+            DO jk = 2, jpkm1
+               zw2d(:,:) = zw2d(:,:) + ztra(:,:,jk) * e3t_n(:,:,jk) * 86400._wp
+            END DO
+            CALL iom_put( "TDETSED", zw2d )
+            DEALLOCATE( zw2d )
+         ENDIF
+      ENDIF
+      !
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('sed')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p2z_sed')
+      !
+   END SUBROUTINE p2z_sed
+
+
+   SUBROUTINE p2z_sed_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p2z_sed_init  ***
+      !!
+      !! ** Purpose :   Parameters from aphotic layers to sediment
+      !!
+      !! ** Method  :   Read the namlobsed namelist and check the parameters
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namlobsed/ sedlam, sedlostpoc, vsed, xhr
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnatp_ref )              ! Namelist namlobsed in reference namelist : Lobster sediments
+      READ  ( numnatp_ref, namlobsed, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namlosed in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist namlobsed in configuration namelist : Lobster sediments
+      READ  ( numnatp_cfg, namlobsed, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namlobsed in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namlobsed )
+      !
+      IF(lwp) THEN
+          WRITE(numout,*) '   Namelist namlobsed'
+          WRITE(numout,*) '      time coeff of POC in sediments                sedlam    =', sedlam
+          WRITE(numout,*) '      Sediment geol loss for POC                    sedlostpoc=', sedlostpoc
+          WRITE(numout,*) '      detritus sedimentation speed                  vsed      =', 86400 * vsed  , ' d'
+          WRITE(numout,*) '      coeff for martin''s remineralistion           xhr       =', xhr
+          WRITE(numout,*) ' '
+      ENDIF
+      !
+   END SUBROUTINE p2z_sed_init
+
+   !!======================================================================
+END MODULE p2zsed
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsms.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsms.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P2Z/p2zsms.F90	(revision 14097)
@@ -0,0 +1,70 @@
+MODULE p2zsms
+   !!======================================================================
+   !!                         ***  MODULE p2zsms  ***
+   !! TOP :   Time loop of LOBSTER model
+   !!======================================================================
+   !! History :   1.0  !            M. Levy
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   p2zsms        :  Time loop of passive tracers sms
+   !!----------------------------------------------------------------------
+   USE oce_trc          !
+   USE trc
+   USE sms_pisces
+   USE p2zbio
+   USE p2zopt
+   USE p2zsed
+   USE p2zexp
+   USE trd_oce
+   USE trdtrc_oce
+   USE trdtrc
+   USE trdmxl_trc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p2z_sms    ! called in p2zsms.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p2z_sms( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p2z_sms  ***
+      !!
+      !! ** Purpose :  Managment of the call to Biological sources and sinks 
+      !!               routines of LOBSTER bio-model 
+      !!
+      !! ** Method  : - ???
+      !! --------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !
+      INTEGER ::   jn   ! dummy loop index
+      !! --------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p2z_sms')
+      !
+      CALL p2z_opt( kt )      ! optical model
+      CALL p2z_bio( kt )      ! biological model
+      CALL p2z_sed( kt )      ! sedimentation model
+      CALL p2z_exp( kt )      ! export
+      !
+      IF( l_trdtrc ) THEN
+         DO jn = jp_pcs0, jp_pcs1
+           CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
+         END DO
+      END IF
+      !
+      IF ( lwm .AND. kt == nittrc000 ) CALL FLUSH    ( numonp )     ! flush output namelist PISCES
+      IF( ln_timing )   CALL timing_stop('p2z_sms')
+      !
+   END SUBROUTINE p2z_sms
+
+   !!======================================================================
+END MODULE p2zsms
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zagg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zagg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zagg.F90	(revision 14097)
@@ -0,0 +1,186 @@
+MODULE p4zagg
+   !!======================================================================
+   !!                         ***  MODULE p4zagg  ***
+   !! TOP :  PISCES  aggregation of particles
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Change aggregation formula
+   !!             3.5  !  2012-07  (O. Aumont) Introduce potential time-splitting
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   p4z_agg       :  Compute aggregation of particles
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE prtctl_trc      !  print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_agg         ! called in p4zbio.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_agg ( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_agg  ***
+      !!
+      !! ** Purpose :   Compute aggregation of particles
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   !
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zagg, zagg1, zagg2, zagg3, zagg4
+      REAL(wp) ::   zaggpoc1, zaggpoc2, zaggpoc3, zaggpoc4
+      REAL(wp) ::   zaggpoc , zaggfe, zaggdoc, zaggdoc2, zaggdoc3
+      REAL(wp) ::   zaggpon , zaggdon, zaggdon2, zaggdon3
+      REAL(wp) ::   zaggpop, zaggdop, zaggdop2, zaggdop3
+      REAL(wp) ::   zaggtmp, zfact, zmax
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_agg')
+      !
+      !  Exchange between organic matter compartments due to coagulation/disaggregation
+      !  ---------------------------------------------------
+      IF( ln_p4z ) THEN
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  zfact = xstep * xdiss(ji,jj,jk)
+                  !  Part I : Coagulation dependent on turbulence
+                  zagg1 = 25.9  * zfact * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jppoc)
+                  zagg2 = 4452. * zfact * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jpgoc)
+
+                  ! Part II : Differential settling
+
+                  !  Aggregation of small into large particles
+                  zagg3 =  47.1 * xstep * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jpgoc)
+                  zagg4 =  3.3  * xstep * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jppoc)
+
+                  zagg   = zagg1 + zagg2 + zagg3 + zagg4
+                  zaggfe = zagg * trb(ji,jj,jk,jpsfe) / ( trb(ji,jj,jk,jppoc) + rtrn )
+
+                  ! Aggregation of DOC to POC : 
+                  ! 1st term is shear aggregation of DOC-DOC
+                  ! 2nd term is shear aggregation of DOC-POC
+                  ! 3rd term is differential settling of DOC-POC
+                  zaggdoc  = ( ( 0.369 * 0.3 * trb(ji,jj,jk,jpdoc) + 102.4 * trb(ji,jj,jk,jppoc) ) * zfact       &
+                  &            + 2.4 * xstep * trb(ji,jj,jk,jppoc) ) * 0.3 * trb(ji,jj,jk,jpdoc)
+                  ! transfer of DOC to GOC : 
+                  ! 1st term is shear aggregation
+                  ! 2nd term is differential settling 
+                  zaggdoc2 = ( 3.53E3 * zfact + 0.1 * xstep ) * trb(ji,jj,jk,jpgoc) * 0.3 * trb(ji,jj,jk,jpdoc)
+                  ! tranfer of DOC to POC due to brownian motion
+                  zaggdoc3 =  114. * 0.3 * trb(ji,jj,jk,jpdoc) *xstep * 0.3 * trb(ji,jj,jk,jpdoc)
+
+                  !  Update the trends
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zagg + zaggdoc + zaggdoc3
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zagg + zaggdoc2
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zaggfe
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zaggfe
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) - zaggdoc - zaggdoc2 - zaggdoc3
+                  !
+                  conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zagg + zaggdoc + zaggdoc3
+                  prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zagg + zaggdoc2
+                  !
+               END DO
+            END DO
+         END DO
+      ELSE    ! ln_p5z
+        !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  zfact = xstep * xdiss(ji,jj,jk)
+                  !  Part I : Coagulation dependent on turbulence
+                  zaggtmp = 25.9  * zfact * trb(ji,jj,jk,jppoc)
+                  zaggpoc1 = zaggtmp * trb(ji,jj,jk,jppoc)
+                  zaggtmp = 4452. * zfact * trb(ji,jj,jk,jpgoc)
+                  zaggpoc2 = zaggtmp * trb(ji,jj,jk,jppoc)
+
+                  ! Part II : Differential settling
+   
+                  !  Aggregation of small into large particles
+                  zaggtmp =  47.1 * xstep * trb(ji,jj,jk,jpgoc)
+                  zaggpoc3 = zaggtmp * trb(ji,jj,jk,jppoc)
+                  zaggtmp =  3.3  * xstep * trb(ji,jj,jk,jppoc)
+                  zaggpoc4 = zaggtmp * trb(ji,jj,jk,jppoc)
+
+                  zaggpoc   = zaggpoc1 + zaggpoc2 + zaggpoc3 + zaggpoc4
+                  zaggpon = zaggpoc * trb(ji,jj,jk,jppon) / ( trb(ji,jj,jk,jppoc) + rtrn)
+                  zaggpop = zaggpoc * trb(ji,jj,jk,jppop) / ( trb(ji,jj,jk,jppoc) + rtrn)
+                  zaggfe = zaggpoc * trb(ji,jj,jk,jpsfe) / ( trb(ji,jj,jk,jppoc)  + rtrn )
+
+                  ! Aggregation of DOC to POC : 
+                  ! 1st term is shear aggregation of DOC-DOC
+                  ! 2nd term is shear aggregation of DOC-POC
+                  ! 3rd term is differential settling of DOC-POC
+                  zaggtmp = ( ( 0.369 * 0.3 * trb(ji,jj,jk,jpdoc) + 102.4 * trb(ji,jj,jk,jppoc) ) * zfact       &
+                  &            + 2.4 * xstep * trb(ji,jj,jk,jppoc) )
+                  zaggdoc  = zaggtmp * 0.3 * trb(ji,jj,jk,jpdoc)
+                  zaggdon  = zaggtmp * 0.3 * trb(ji,jj,jk,jpdon)
+                  zaggdop  = zaggtmp * 0.3 * trb(ji,jj,jk,jpdop)
+
+                  ! transfer of DOC to GOC : 
+                  ! 1st term is shear aggregation
+                  ! 2nd term is differential settling 
+                  zaggtmp = ( 3.53E3 * zfact + 0.1 * xstep ) * trb(ji,jj,jk,jpgoc)
+                  zaggdoc2 = zaggtmp * 0.3 * trb(ji,jj,jk,jpdoc)
+                  zaggdon2 = zaggtmp * 0.3 * trb(ji,jj,jk,jpdon)
+                  zaggdop2 = zaggtmp * 0.3 * trb(ji,jj,jk,jpdop)
+
+                  ! tranfer of DOC to POC due to brownian motion
+                  zaggtmp = ( 114. * 0.3 * trb(ji,jj,jk,jpdoc) ) * xstep
+                  zaggdoc3 =  zaggtmp * 0.3 * trb(ji,jj,jk,jpdoc)
+                  zaggdon3 =  zaggtmp * 0.3 * trb(ji,jj,jk,jpdon)
+                  zaggdop3 =  zaggtmp * 0.3 * trb(ji,jj,jk,jpdop)
+
+                  !  Update the trends
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zaggpoc + zaggdoc + zaggdoc3
+                  tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) - zaggpon + zaggdon + zaggdon3
+                  tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) - zaggpop + zaggdop + zaggdop3
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zaggpoc + zaggdoc2
+                  tra(ji,jj,jk,jpgon) = tra(ji,jj,jk,jpgon) + zaggpon + zaggdon2
+                  tra(ji,jj,jk,jpgop) = tra(ji,jj,jk,jpgop) + zaggpop + zaggdop2
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zaggfe
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zaggfe
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) - zaggdoc - zaggdoc2 - zaggdoc3
+                  tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) - zaggdon - zaggdon2 - zaggdon3
+                  tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) - zaggdop - zaggdop2 - zaggdop3
+                  !
+                  conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zaggpoc + zaggdoc + zaggdoc3
+                  prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zaggpoc + zaggdoc2
+                  !
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('agg')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_agg')
+      !
+   END SUBROUTINE p4z_agg
+
+   !!======================================================================
+END MODULE p4zagg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zbio.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zbio.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zbio.F90	(revision 14097)
@@ -0,0 +1,119 @@
+MODULE p4zbio
+   !!======================================================================
+   !!                         ***  MODULE p4zbio  ***
+   !! TOP :   PISCES bio-model
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   p4z_bio        :   computes the interactions between the different
+   !!                      compartments of PISCES
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zsink         !  vertical flux of particulate matter due to sinking
+   USE p4zopt          !  optical model
+   USE p4zlim          !  Co-limitations of differents nutrients
+   USE p4zprod         !  Growth rate of the 2 phyto groups
+   USE p4zmort         !  Mortality terms for phytoplankton
+   USE p4zmicro        !  Sources and sinks of microzooplankton
+   USE p4zmeso         !  Sources and sinks of mesozooplankton
+   USE p5zlim          !  Co-limitations of differents nutrients
+   USE p5zprod         !  Growth rate of the 2 phyto groups
+   USE p5zmort         !  Mortality terms for phytoplankton
+   USE p5zmicro        !  Sources and sinks of microzooplankton
+   USE p5zmeso         !  Sources and sinks of mesozooplankton
+   USE p4zrem          !  Remineralisation of organic matter
+   USE p4zpoc          !  Remineralization of organic particles
+   USE p4zagg          !  Aggregation of particles
+   USE p4zfechem
+   USE p4zligand       !  Prognostic ligand model
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+  
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC  p4z_bio    
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_bio ( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_bio  ***
+      !!
+      !! ** Purpose :   Ecosystem model in the whole ocean: computes the
+      !!              different interactions between the different compartments
+      !!              of PISCES
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt, knt
+      !
+      INTEGER             :: ji, jj, jk, jn
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_bio')
+      !
+      !     ASSIGN THE SHEAR RATE THAT IS USED FOR AGGREGATION
+      !     OF PHYTOPLANKTON AND DETRITUS
+
+      xdiss(:,:,:) = 1.
+!!gm the use of nmld should be better here?
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+!!gm  :  use nmln  and test on jk ...  less memory acces
+               IF( gdepw_n(ji,jj,jk+1) > hmld(ji,jj) )   xdiss(ji,jj,jk) = 0.01
+            END DO 
+         END DO
+      END DO
+
+      CALL p4z_opt     ( kt, knt )     ! Optic: PAR in the water column
+      CALL p4z_sink    ( kt, knt )     ! vertical flux of particulate organic matter
+      CALL p4z_fechem  ( kt, knt )     ! Iron chemistry/scavenging
+      !
+      IF( ln_p4z ) THEN
+         CALL p4z_lim  ( kt, knt )     ! co-limitations by the various nutrients
+         CALL p4z_prod ( kt, knt )     ! phytoplankton growth rate over the global ocean. 
+         !                             ! (for each element : C, Si, Fe, Chl )
+         CALL p4z_mort ( kt      )     ! phytoplankton mortality
+         !                             ! zooplankton sources/sinks routines 
+         CALL p4z_micro( kt, knt )           ! microzooplankton
+         CALL p4z_meso ( kt, knt )           ! mesozooplankton
+      ELSE
+         CALL p5z_lim  ( kt, knt )     ! co-limitations by the various nutrients
+         CALL p5z_prod ( kt, knt )     ! phytoplankton growth rate over the global ocean. 
+         !                             ! (for each element : C, Si, Fe, Chl )
+         CALL p5z_mort ( kt      )     ! phytoplankton mortality
+         !                             ! zooplankton sources/sinks routines 
+         CALL p5z_micro( kt, knt )           ! microzooplankton
+         CALL p5z_meso ( kt, knt )           ! mesozooplankton
+      ENDIF
+      !
+      CALL p4z_agg     ( kt, knt )     ! Aggregation of particles
+      CALL p4z_rem     ( kt, knt )     ! remineralization terms of organic matter+scavenging of Fe
+      CALL p4z_poc     ( kt, knt )     ! Remineralization of organic particles
+      !
+      IF( ln_ligand )  &
+      & CALL p4z_ligand( kt, knt )
+      !                                                             !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('bio ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_bio')
+      !
+   END SUBROUTINE p4z_bio
+
+   !!======================================================================
+END MODULE p4zbio
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zche.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zche.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zche.F90	(revision 14097)
@@ -0,0 +1,830 @@
+MODULE p4zche
+   !!======================================================================
+   !!                         ***  MODULE p4zche  ***
+   !! TOP :   PISCES Sea water chemistry computed following OCMIP protocol
+   !!======================================================================
+   !! History :   OPA  !  1988     (E. Maier-Reimer)  Original code
+   !!              -   !  1998     (O. Aumont)  addition
+   !!              -   !  1999     (C. Le Quere)  modification
+   !!   NEMO      1.0  !  2004     (O. Aumont)  modification
+   !!              -   !  2006     (R. Gangsto)  modification
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!                  !  2011-02  (J. Simeon, J.Orr ) update O2 solubility constants
+   !!             3.6  !  2016-03  (O. Aumont) Change chemistry to MOCSY standards
+   !!----------------------------------------------------------------------
+   !!   p4z_che      :  Sea water chemistry computed following OCMIP protocol
+   !!----------------------------------------------------------------------
+   USE oce_trc       !  shared variables between ocean and passive tracers
+   USE trc           !  passive tracers common variables
+   USE sms_pisces    !  PISCES Source Minus Sink variables
+   USE lib_mpp       !  MPP library
+   USE eosbn2, ONLY : neos
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_che          !
+   PUBLIC   p4z_che_alloc    !
+   PUBLIC   ahini_for_at     !
+   PUBLIC   solve_at_general !
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   :: sio3eq   ! chemistry of Si
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   :: fekeq    ! chemistry of Fe
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   :: chemc    ! Solubilities of O2 and CO2
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   :: chemo2    ! Solubilities of O2 and CO2
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) :: fesol    ! solubility of Fe
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   salinprac  ! Practical salinity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tempis   ! In situ temperature
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   akb3       !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   akw3       !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   akf3       !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aks3       !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ak1p3      !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ak2p3      !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ak3p3      !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aksi3      !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   borat      !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   fluorid    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sulfat     !: ???
+
+   !!* Variable for chemistry of the CO2 cycle
+
+   REAL(wp), PUBLIC ::   atcox  = 0.20946         ! units atm
+
+   REAL(wp) ::   o2atm  = 1. / ( 1000. * 0.20946 )  
+
+   REAL(wp) ::   rgas   = 83.14472      ! universal gas constants
+   REAL(wp) ::   oxyco  = 1. / 22.4144  ! converts from liters of an ideal gas to moles
+   !                                    ! coeff. for seawater pressure correction : millero 95
+   !                                    ! AGRIF doesn't like the DATA instruction
+   REAL(wp) :: devk10  = -25.5
+   REAL(wp) :: devk11  = -15.82
+   REAL(wp) :: devk12  = -29.48
+   REAL(wp) :: devk13  = -20.02
+   REAL(wp) :: devk14  = -18.03
+   REAL(wp) :: devk15  = -9.78
+   REAL(wp) :: devk16  = -48.76
+   REAL(wp) :: devk17  = -14.51
+   REAL(wp) :: devk18  = -23.12
+   REAL(wp) :: devk19  = -26.57
+   REAL(wp) :: devk110  = -29.48
+   !
+   REAL(wp) :: devk20  = 0.1271
+   REAL(wp) :: devk21  = -0.0219
+   REAL(wp) :: devk22  = 0.1622
+   REAL(wp) :: devk23  = 0.1119
+   REAL(wp) :: devk24  = 0.0466
+   REAL(wp) :: devk25  = -0.0090
+   REAL(wp) :: devk26  = 0.5304
+   REAL(wp) :: devk27  = 0.1211
+   REAL(wp) :: devk28  = 0.1758
+   REAL(wp) :: devk29  = 0.2020
+   REAL(wp) :: devk210  = 0.1622
+   !
+   REAL(wp) :: devk30  = 0.
+   REAL(wp) :: devk31  = 0.
+   REAL(wp) :: devk32  = 2.608E-3
+   REAL(wp) :: devk33  = -1.409e-3
+   REAL(wp) :: devk34  = 0.316e-3
+   REAL(wp) :: devk35  = -0.942e-3
+   REAL(wp) :: devk36  = 0.
+   REAL(wp) :: devk37  = -0.321e-3
+   REAL(wp) :: devk38  = -2.647e-3
+   REAL(wp) :: devk39  = -3.042e-3
+   REAL(wp) :: devk310  = -2.6080e-3
+   !
+   REAL(wp) :: devk40  = -3.08E-3
+   REAL(wp) :: devk41  = 1.13E-3
+   REAL(wp) :: devk42  = -2.84E-3
+   REAL(wp) :: devk43  = -5.13E-3
+   REAL(wp) :: devk44  = -4.53e-3
+   REAL(wp) :: devk45  = -3.91e-3
+   REAL(wp) :: devk46  = -11.76e-3
+   REAL(wp) :: devk47  = -2.67e-3
+   REAL(wp) :: devk48  = -5.15e-3
+   REAL(wp) :: devk49  = -4.08e-3
+   REAL(wp) :: devk410  = -2.84e-3
+   !
+   REAL(wp) :: devk50  = 0.0877E-3
+   REAL(wp) :: devk51  = -0.1475E-3     
+   REAL(wp) :: devk52  = 0.
+   REAL(wp) :: devk53  = 0.0794E-3      
+   REAL(wp) :: devk54  = 0.09e-3
+   REAL(wp) :: devk55  = 0.054e-3
+   REAL(wp) :: devk56  = 0.3692E-3
+   REAL(wp) :: devk57  = 0.0427e-3
+   REAL(wp) :: devk58  = 0.09e-3
+   REAL(wp) :: devk59  = 0.0714e-3
+   REAL(wp) :: devk510  = 0.0
+   !
+   ! General parameters
+   REAL(wp), PARAMETER :: pp_rdel_ah_target = 1.E-4_wp
+   REAL(wp), PARAMETER :: pp_ln10 = 2.302585092994045684018_wp
+
+   ! Maximum number of iterations for each method
+   INTEGER, PARAMETER :: jp_maxniter_atgen    = 20
+
+   ! Bookkeeping variables for each method
+   ! - SOLVE_AT_GENERAL
+   INTEGER :: niter_atgen    = jp_maxniter_atgen
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_che
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_che  ***
+      !!
+      !! ** Purpose :   Sea water chemistry computed following OCMIP protocol
+      !!
+      !! ** Method  : - ...
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   ztkel, ztkel1, zt , zsal  , zsal2 , zbuf1 , zbuf2
+      REAL(wp) ::   ztgg , ztgg2, ztgg3 , ztgg4 , ztgg5
+      REAL(wp) ::   zpres, ztc  , zcl   , zcpexp, zoxy  , zcpexp2
+      REAL(wp) ::   zsqrt, ztr  , zlogt , zcek1, zc1, zplat
+      REAL(wp) ::   zis  , zis2 , zsal15, zisqrt, za1, za2
+      REAL(wp) ::   zckb , zck1 , zck2  , zckw  , zak1 , zak2  , zakb , zaksp0, zakw
+      REAL(wp) ::   zck1p, zck2p, zck3p, zcksi, zak1p, zak2p, zak3p, zaksi
+      REAL(wp) ::   zst  , zft  , zcks  , zckf  , zaksp1
+      REAL(wp) ::   total2free, free2SWS, total2SWS, SWS2total
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_che')
+      !
+      ! Computation of chemical constants require practical salinity
+      ! Thus, when TEOS08 is used, absolute salinity is converted to 
+      ! practical salinity
+      ! -------------------------------------------------------------
+      IF (neos == -1) THEN
+         salinprac(:,:,:) = tsn(:,:,:,jp_sal) * 35.0 / 35.16504
+      ELSE
+         salinprac(:,:,:) = tsn(:,:,:,jp_sal)
+      ENDIF
+
+      !
+      ! Computations of chemical constants require in situ temperature
+      ! Here a quite simple formulation is used to convert 
+      ! potential temperature to in situ temperature. The errors is less than 
+      ! 0.04°C relative to an exact computation
+      ! ---------------------------------------------------------------------
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zpres = gdept_n(ji,jj,jk) / 1000.
+               za1 = 0.04 * ( 1.0 + 0.185 * tsn(ji,jj,jk,jp_tem) + 0.035 * (salinprac(ji,jj,jk) - 35.0) )
+               za2 = 0.0075 * ( 1.0 - tsn(ji,jj,jk,jp_tem) / 30.0 )
+               tempis(ji,jj,jk) = tsn(ji,jj,jk,jp_tem) - za1 * zpres + za2 * zpres**2
+            END DO
+         END DO
+      END DO
+      !
+      ! CHEMICAL CONSTANTS - SURFACE LAYER
+      ! ----------------------------------
+!CDIR NOVERRCHK
+      DO jj = 1, jpj
+!CDIR NOVERRCHK
+         DO ji = 1, jpi
+            !                             ! SET ABSOLUTE TEMPERATURE
+            ztkel = tempis(ji,jj,1) + 273.15
+            zt    = ztkel * 0.01
+            zsal  = salinprac(ji,jj,1) + ( 1.- tmask(ji,jj,1) ) * 35.
+            !                             ! LN(K0) OF SOLUBILITY OF CO2 (EQ. 12, WEISS, 1980)
+            !                             !     AND FOR THE ATMOSPHERE FOR NON IDEAL GAS
+            zcek1 = 9345.17/ztkel - 60.2409 + 23.3585 * LOG(zt) + zsal*(0.023517 - 0.00023656*ztkel    &
+            &       + 0.0047036e-4*ztkel**2)
+            chemc(ji,jj,1) = EXP( zcek1 ) * 1E-6 * rhop(ji,jj,1) / 1000. ! mol/(L atm)
+            chemc(ji,jj,2) = -1636.75 + 12.0408*ztkel - 0.0327957*ztkel**2 + 0.0000316528*ztkel**3
+            chemc(ji,jj,3) = 57.7 - 0.118*ztkel
+            !
+         END DO
+      END DO
+
+      ! OXYGEN SOLUBILITY - DEEP OCEAN
+      ! -------------------------------
+!CDIR NOVERRCHK
+      DO jk = 1, jpk
+!CDIR NOVERRCHK
+         DO jj = 1, jpj
+!CDIR NOVERRCHK
+            DO ji = 1, jpi
+              ztkel = tempis(ji,jj,jk) + 273.15
+              zsal  = salinprac(ji,jj,jk) + ( 1.- tmask(ji,jj,jk) ) * 35.
+              zsal2 = zsal * zsal
+              ztgg  = LOG( ( 298.15 - tempis(ji,jj,jk) ) / ztkel )  ! Set the GORDON & GARCIA scaled temperature
+              ztgg2 = ztgg  * ztgg
+              ztgg3 = ztgg2 * ztgg
+              ztgg4 = ztgg3 * ztgg
+              ztgg5 = ztgg4 * ztgg
+
+              zoxy  = 2.00856 + 3.22400 * ztgg + 3.99063 * ztgg2 + 4.80299 * ztgg3    &
+              &       + 9.78188e-1 * ztgg4 + 1.71069 * ztgg5 + zsal * ( -6.24097e-3   &
+              &       - 6.93498e-3 * ztgg - 6.90358e-3 * ztgg2 - 4.29155e-3 * ztgg3 )   &
+              &       - 3.11680e-7 * zsal2
+              chemo2(ji,jj,jk) = ( EXP( zoxy ) * o2atm ) * oxyco * atcox     ! mol/(L atm)
+            END DO
+          END DO
+        END DO
+
+      ! CHEMICAL CONSTANTS - DEEP OCEAN
+      ! -------------------------------
+!CDIR NOVERRCHK
+      DO jk = 1, jpk
+!CDIR NOVERRCHK
+         DO jj = 1, jpj
+!CDIR NOVERRCHK
+            DO ji = 1, jpi
+
+               ! SET PRESSION ACCORDING TO SAUNDER (1980)
+               zplat   = SIN ( ABS(gphit(ji,jj)*3.141592654/180.) )
+               zc1 = 5.92E-3 + zplat**2 * 5.25E-3
+               zpres = ((1-zc1)-SQRT(((1-zc1)**2)-(8.84E-6*gdept_n(ji,jj,jk)))) / 4.42E-6
+               zpres = zpres / 10.0
+
+               ! SET ABSOLUTE TEMPERATURE
+               ztkel   = tempis(ji,jj,jk) + 273.15
+               zsal    = salinprac(ji,jj,jk) + ( 1.-tmask(ji,jj,jk) ) * 35.
+               zsqrt  = SQRT( zsal )
+               zsal15  = zsqrt * zsal
+               zlogt  = LOG( ztkel )
+               ztr    = 1. / ztkel
+               zis    = 19.924 * zsal / ( 1000.- 1.005 * zsal )
+               zis2   = zis * zis
+               zisqrt = SQRT( zis )
+               ztc     = tempis(ji,jj,jk) + ( 1.- tmask(ji,jj,jk) ) * 20.
+
+               ! CHLORINITY (WOOSTER ET AL., 1969)
+               zcl     = zsal / 1.80655
+
+               ! TOTAL SULFATE CONCENTR. [MOLES/kg soln]
+               zst     = 0.14 * zcl /96.062
+
+               ! TOTAL FLUORIDE CONCENTR. [MOLES/kg soln]
+               zft     = 0.000067 * zcl /18.9984
+
+               ! DISSOCIATION CONSTANT FOR SULFATES on free H scale (Dickson 1990)
+               zcks    = EXP(-4276.1 * ztr + 141.328 - 23.093 * zlogt         &
+               &         + (-13856. * ztr + 324.57 - 47.986 * zlogt) * zisqrt &
+               &         + (35474. * ztr - 771.54 + 114.723 * zlogt) * zis    &
+               &         - 2698. * ztr * zis**1.5 + 1776.* ztr * zis2         &
+               &         + LOG(1.0 - 0.001005 * zsal))
+
+               ! DISSOCIATION CONSTANT FOR FLUORIDES on free H scale (Dickson and Riley 79)
+               zckf    = EXP( 1590.2*ztr - 12.641 + 1.525*zisqrt   &
+               &         + LOG(1.0d0 - 0.001005d0*zsal)            &
+               &         + LOG(1.0d0 + zst/zcks))
+
+               ! DISSOCIATION CONSTANT FOR CARBONATE AND BORATE
+               zckb=  (-8966.90 - 2890.53*zsqrt - 77.942*zsal        &
+               &      + 1.728*zsal15 - 0.0996*zsal*zsal)*ztr         &
+               &      + (148.0248 + 137.1942*zsqrt + 1.62142*zsal)   &
+               &      + (-24.4344 - 25.085*zsqrt - 0.2474*zsal)      & 
+               &      * zlogt + 0.053105*zsqrt*ztkel
+
+               ! DISSOCIATION COEFFICIENT FOR CARBONATE ACCORDING TO 
+               ! MEHRBACH (1973) REFIT BY MILLERO (1995), seawater scale
+               zck1    = -1.0*(3633.86*ztr - 61.2172 + 9.6777*zlogt  &
+                  - 0.011555*zsal + 0.0001152*zsal*zsal)
+               zck2    = -1.0*(471.78*ztr + 25.9290 - 3.16967*zlogt      &
+                  - 0.01781*zsal + 0.0001122*zsal*zsal)
+
+               ! PKW (H2O) (MILLERO, 1995) from composite data
+               zckw    = -13847.26 * ztr + 148.9652 - 23.6521 * zlogt + ( 118.67 * ztr    &
+                         - 5.977 + 1.0495 * zlogt ) * zsqrt - 0.01615 * zsal
+
+               ! CONSTANTS FOR PHOSPHATE (MILLERO, 1995)
+              zck1p    = -4576.752*ztr + 115.540 - 18.453*zlogt   &
+              &          + (-106.736*ztr + 0.69171) * zsqrt       &
+              &          + (-0.65643*ztr - 0.01844) * zsal
+
+              zck2p    = -8814.715*ztr + 172.1033 - 27.927*zlogt  &
+              &          + (-160.340*ztr + 1.3566)*zsqrt          &
+              &          + (0.37335*ztr - 0.05778)*zsal
+
+              zck3p    = -3070.75*ztr - 18.126                    &
+              &          + (17.27039*ztr + 2.81197) * zsqrt       &
+              &          + (-44.99486*ztr - 0.09984) * zsal 
+
+              ! CONSTANT FOR SILICATE, MILLERO (1995)
+              zcksi    = -8904.2*ztr  + 117.400 - 19.334*zlogt   &
+              &          + (-458.79*ztr + 3.5913) * zisqrt       &
+              &          + (188.74*ztr - 1.5998) * zis           &
+              &          + (-12.1652*ztr + 0.07871) * zis2       &
+              &          + LOG(1.0 - 0.001005*zsal)
+
+               ! APPARENT SOLUBILITY PRODUCT K'SP OF CALCITE IN SEAWATER
+               !       (S=27-43, T=2-25 DEG C) at pres =0 (atmos. pressure) (MUCCI 1983)
+               zaksp0  = -171.9065 -0.077993*ztkel + 2839.319*ztr + 71.595*LOG10( ztkel )   &
+                  &      + (-0.77712 + 0.00284263*ztkel + 178.34*ztr) * zsqrt  &
+                  &      - 0.07711*zsal + 0.0041249*zsal15
+
+               ! CONVERT FROM DIFFERENT PH SCALES
+               total2free  = 1.0/(1.0 + zst/zcks)
+               free2SWS    = 1. + zst/zcks + zft/(zckf*total2free)
+               total2SWS   = total2free * free2SWS
+               SWS2total   = 1.0 / total2SWS
+
+               ! K1, K2 OF CARBONIC ACID, KB OF BORIC ACID, KW (H2O) (LIT.?)
+               zak1    = 10**(zck1) * total2SWS
+               zak2    = 10**(zck2) * total2SWS
+               zakb    = EXP( zckb ) * total2SWS
+               zakw    = EXP( zckw )
+               zaksp1  = 10**(zaksp0)
+               zak1p   = exp( zck1p )
+               zak2p   = exp( zck2p )
+               zak3p   = exp( zck3p )
+               zaksi   = exp( zcksi )
+               zckf    = zckf * total2SWS
+
+               ! FORMULA FOR CPEXP AFTER EDMOND & GIESKES (1970)
+               !        (REFERENCE TO CULBERSON & PYTKOQICZ (1968) AS MADE
+               !        IN BROECKER ET AL. (1982) IS INCORRECT; HERE RGAS IS
+               !        TAKEN TENFOLD TO CORRECT FOR THE NOTATION OF pres  IN
+               !        DBAR INSTEAD OF BAR AND THE EXPRESSION FOR CPEXP IS
+               !        MULTIPLIED BY LN(10.) TO ALLOW USE OF EXP-FUNCTION
+               !        WITH BASIS E IN THE FORMULA FOR AKSPP (CF. EDMOND
+               !        & GIESKES (1970), P. 1285-1286 (THE SMALL
+               !        FORMULA ON P. 1286 IS RIGHT AND CONSISTENT WITH THE
+               !        SIGN IN PARTIAL MOLAR VOLUME CHANGE AS SHOWN ON P. 1285))
+               zcpexp  = zpres / (rgas*ztkel)
+               zcpexp2 = zpres * zcpexp
+
+               ! KB OF BORIC ACID, K1,K2 OF CARBONIC ACID PRESSURE
+               !        CORRECTION AFTER CULBERSON AND PYTKOWICZ (1968)
+               !        (CF. BROECKER ET AL., 1982)
+
+               zbuf1  = -     ( devk10 + devk20 * ztc + devk30 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk40 + devk50 * ztc )
+               ak13(ji,jj,jk) = zak1 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk11 + devk21 * ztc + devk31 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk41 + devk51 * ztc )
+               ak23(ji,jj,jk) = zak2 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk12 + devk22 * ztc + devk32 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk42 + devk52 * ztc )
+               akb3(ji,jj,jk) = zakb * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk13 + devk23 * ztc + devk33 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk43 + devk53 * ztc )
+               akw3(ji,jj,jk) = zakw * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk14 + devk24 * ztc + devk34 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk44 + devk54 * ztc )
+               aks3(ji,jj,jk) = zcks * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk15 + devk25 * ztc + devk35 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk45 + devk55 * ztc )
+               akf3(ji,jj,jk) = zckf * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk17 + devk27 * ztc + devk37 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk47 + devk57 * ztc )
+               ak1p3(ji,jj,jk) = zak1p * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk18 + devk28 * ztc + devk38 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk48 + devk58 * ztc )
+               ak2p3(ji,jj,jk) = zak2p * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk19 + devk29 * ztc + devk39 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk49 + devk59 * ztc )
+               ak3p3(ji,jj,jk) = zak3p * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               zbuf1  =     - ( devk110 + devk210 * ztc + devk310 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk410 + devk510 * ztc )
+               aksi3(ji,jj,jk) = zaksi * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               ! CONVERT FROM DIFFERENT PH SCALES
+               total2free  = 1.0/(1.0 + zst/aks3(ji,jj,jk))
+               free2SWS    = 1. + zst/aks3(ji,jj,jk) + zft/akf3(ji,jj,jk)
+               total2SWS   = total2free * free2SWS
+               SWS2total   = 1.0 / total2SWS
+
+               ! Convert to total scale
+               ak13(ji,jj,jk)  = ak13(ji,jj,jk)  * SWS2total
+               ak23(ji,jj,jk)  = ak23(ji,jj,jk)  * SWS2total
+               akb3(ji,jj,jk)  = akb3(ji,jj,jk)  * SWS2total
+               akw3(ji,jj,jk)  = akw3(ji,jj,jk)  * SWS2total
+               ak1p3(ji,jj,jk) = ak1p3(ji,jj,jk) * SWS2total
+               ak2p3(ji,jj,jk) = ak2p3(ji,jj,jk) * SWS2total
+               ak3p3(ji,jj,jk) = ak3p3(ji,jj,jk) * SWS2total
+               aksi3(ji,jj,jk) = aksi3(ji,jj,jk) * SWS2total
+               akf3(ji,jj,jk)  = akf3(ji,jj,jk)  / total2free
+
+               ! APPARENT SOLUBILITY PRODUCT K'SP OF CALCITE 
+               !        AS FUNCTION OF PRESSURE FOLLOWING MILLERO
+               !        (P. 1285) AND BERNER (1976)
+               zbuf1  =     - ( devk16 + devk26 * ztc + devk36 * ztc * ztc )
+               zbuf2  = 0.5 * ( devk46 + devk56 * ztc )
+               aksp(ji,jj,jk) = zaksp1 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+               ! TOTAL F, S, and BORATE CONCENTR. [MOLES/L]
+               borat(ji,jj,jk) = 0.0002414 * zcl / 10.811
+               sulfat(ji,jj,jk) = zst
+               fluorid(ji,jj,jk) = zft 
+
+               ! Iron and SIO3 saturation concentration from ...
+               sio3eq(ji,jj,jk) = EXP(  LOG( 10.) * ( 6.44 - 968. / ztkel )  ) * 1.e-6
+               fekeq (ji,jj,jk) = 10**( 17.27 - 1565.7 / ztkel )
+
+               ! Liu and Millero (1999) only valid 5 - 50 degC
+               ztkel1 = MAX( 5. , tempis(ji,jj,jk) ) + 273.16
+               fesol(ji,jj,jk,1) = 10**(-13.486 - 0.1856* zis**0.5 + 0.3073*zis + 5254.0/ztkel1)
+               fesol(ji,jj,jk,2) = 10**(2.517 - 0.8885*zis**0.5 + 0.2139 * zis - 1320.0/ztkel1 )
+               fesol(ji,jj,jk,3) = 10**(0.4511 - 0.3305*zis**0.5 - 1996.0/ztkel1 )
+               fesol(ji,jj,jk,4) = 10**(-0.2965 - 0.7881*zis**0.5 - 4086.0/ztkel1 )
+               fesol(ji,jj,jk,5) = 10**(4.4466 - 0.8505*zis**0.5 - 7980.0/ztkel1 )
+            END DO
+         END DO
+      END DO
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_che')
+      !
+   END SUBROUTINE p4z_che
+
+   SUBROUTINE ahini_for_at(p_hini)
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE ahini_for_at  ***
+      !!
+      !! Subroutine returns the root for the 2nd order approximation of the
+      !! DIC -- B_T -- A_CB equation for [H+] (reformulated as a cubic 
+      !! polynomial) around the local minimum, if it exists.
+      !! Returns * 1E-03_wp if p_alkcb <= 0
+      !!         * 1E-10_wp if p_alkcb >= 2*p_dictot + p_bortot
+      !!         * 1E-07_wp if 0 < p_alkcb < 2*p_dictot + p_bortot
+      !!                    and the 2nd order approximation does not have 
+      !!                    a solution
+      !!---------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(OUT)  ::  p_hini
+      INTEGER  ::   ji, jj, jk
+      REAL(wp)  ::  zca1, zba1
+      REAL(wp)  ::  zd, zsqrtd, zhmin
+      REAL(wp)  ::  za2, za1, za0
+      REAL(wp)  ::  p_dictot, p_bortot, p_alkcb 
+      !!---------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('ahini_for_at')
+      !
+      DO jk = 1, jpk
+        DO jj = 1, jpj
+          DO ji = 1, jpi
+            p_alkcb  = trb(ji,jj,jk,jptal) * 1000. / (rhop(ji,jj,jk) + rtrn)
+            p_dictot = trb(ji,jj,jk,jpdic) * 1000. / (rhop(ji,jj,jk) + rtrn)
+            p_bortot = borat(ji,jj,jk)
+            IF (p_alkcb <= 0.) THEN
+                p_hini(ji,jj,jk) = 1.e-3
+            ELSEIF (p_alkcb >= (2.*p_dictot + p_bortot)) THEN
+                p_hini(ji,jj,jk) = 1.e-10_wp
+            ELSE
+                zca1 = p_dictot/( p_alkcb + rtrn )
+                zba1 = p_bortot/ (p_alkcb + rtrn )
+           ! Coefficients of the cubic polynomial
+                za2 = aKb3(ji,jj,jk)*(1. - zba1) + ak13(ji,jj,jk)*(1.-zca1)
+                za1 = ak13(ji,jj,jk)*akb3(ji,jj,jk)*(1. - zba1 - zca1)    &
+                &     + ak13(ji,jj,jk)*ak23(ji,jj,jk)*(1. - (zca1+zca1))
+                za0 = ak13(ji,jj,jk)*ak23(ji,jj,jk)*akb3(ji,jj,jk)*(1. - zba1 - (zca1+zca1))
+                                        ! Taylor expansion around the minimum
+                zd = za2*za2 - 3.*za1   ! Discriminant of the quadratic equation
+                                        ! for the minimum close to the root
+
+                IF(zd > 0.) THEN        ! If the discriminant is positive
+                  zsqrtd = SQRT(zd)
+                  IF(za2 < 0) THEN
+                    zhmin = (-za2 + zsqrtd)/3.
+                  ELSE
+                    zhmin = -za1/(za2 + zsqrtd)
+                  ENDIF
+                  p_hini(ji,jj,jk) = zhmin + SQRT(-(za0 + zhmin*(za1 + zhmin*(za2 + zhmin)))/zsqrtd)
+                ELSE
+                  p_hini(ji,jj,jk) = 1.e-7
+                ENDIF
+             !
+             ENDIF
+          END DO
+        END DO
+      END DO
+      !
+      IF( ln_timing )  CALL timing_stop('ahini_for_at')
+      !
+   END SUBROUTINE ahini_for_at
+
+   !===============================================================================
+
+   SUBROUTINE anw_infsup( p_alknw_inf, p_alknw_sup )
+
+   ! Subroutine returns the lower and upper bounds of "non-water-selfionization"
+   ! contributions to total alkalinity (the infimum and the supremum), i.e
+   ! inf(TA - [OH-] + [H+]) and sup(TA - [OH-] + [H+])
+
+   ! Argument variables
+   REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(OUT) :: p_alknw_inf
+   REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(OUT) :: p_alknw_sup
+
+   p_alknw_inf(:,:,:) =  -trb(:,:,:,jppo4) * 1000. / (rhop(:,:,:) + rtrn) - sulfat(:,:,:)  &
+   &              - fluorid(:,:,:)
+   p_alknw_sup(:,:,:) =   (2. * trb(:,:,:,jpdic) + 2. * trb(:,:,:,jppo4) + trb(:,:,:,jpsil) )    &
+   &               * 1000. / (rhop(:,:,:) + rtrn) + borat(:,:,:) 
+
+   END SUBROUTINE anw_infsup
+
+
+   SUBROUTINE solve_at_general( p_hini, zhi )
+
+   ! Universal pH solver that converges from any given initial value,
+   ! determines upper an lower bounds for the solution if required
+
+   ! Argument variables
+   !--------------------
+   REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(IN)   :: p_hini
+   REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(OUT)  :: zhi
+
+   ! Local variables
+   !-----------------
+   INTEGER   ::  ji, jj, jk, jn
+   REAL(wp)  ::  zh_ini, zh, zh_prev, zh_lnfactor
+   REAL(wp)  ::  zdelta, zh_delta
+   REAL(wp)  ::  zeqn, zdeqndh, zalka
+   REAL(wp)  ::  aphscale
+   REAL(wp)  ::  znumer_dic, zdnumer_dic, zdenom_dic, zalk_dic, zdalk_dic
+   REAL(wp)  ::  znumer_bor, zdnumer_bor, zdenom_bor, zalk_bor, zdalk_bor
+   REAL(wp)  ::  znumer_po4, zdnumer_po4, zdenom_po4, zalk_po4, zdalk_po4
+   REAL(wp)  ::  znumer_sil, zdnumer_sil, zdenom_sil, zalk_sil, zdalk_sil
+   REAL(wp)  ::  znumer_so4, zdnumer_so4, zdenom_so4, zalk_so4, zdalk_so4
+   REAL(wp)  ::  znumer_flu, zdnumer_flu, zdenom_flu, zalk_flu, zdalk_flu
+   REAL(wp)  ::  zalk_wat, zdalk_wat
+   REAL(wp)  ::  zfact, p_alktot, zdic, zbot, zpt, zst, zft, zsit
+   LOGICAL   ::  l_exitnow
+   REAL(wp), PARAMETER :: pz_exp_threshold = 1.0
+   REAL(wp), DIMENSION(jpi,jpj,jpk) :: zalknw_inf, zalknw_sup, rmask, zh_min, zh_max, zeqn_absmin
+
+   IF( ln_timing )  CALL timing_start('solve_at_general')
+
+   CALL anw_infsup( zalknw_inf, zalknw_sup )
+
+   rmask(:,:,:) = tmask(:,:,:)
+   zhi(:,:,:)   = 0.
+
+   ! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+   DO jk = 1, jpk
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF (rmask(ji,jj,jk) == 1.) THEN
+               p_alktot = trb(ji,jj,jk,jptal) * 1000. / (rhop(ji,jj,jk) + rtrn)
+               aphscale = 1. + sulfat(ji,jj,jk)/aks3(ji,jj,jk)
+               zh_ini = p_hini(ji,jj,jk)
+
+               zdelta = (p_alktot-zalknw_inf(ji,jj,jk))**2 + 4.*akw3(ji,jj,jk)/aphscale
+
+               IF(p_alktot >= zalknw_inf(ji,jj,jk)) THEN
+                 zh_min(ji,jj,jk) = 2.*akw3(ji,jj,jk) /( p_alktot-zalknw_inf(ji,jj,jk) + SQRT(zdelta) )
+               ELSE
+                 zh_min(ji,jj,jk) = aphscale*(-(p_alktot-zalknw_inf(ji,jj,jk)) + SQRT(zdelta) ) / 2.
+               ENDIF
+
+               zdelta = (p_alktot-zalknw_sup(ji,jj,jk))**2 + 4.*akw3(ji,jj,jk)/aphscale
+
+               IF(p_alktot <= zalknw_sup(ji,jj,jk)) THEN
+                 zh_max(ji,jj,jk) = aphscale*(-(p_alktot-zalknw_sup(ji,jj,jk)) + SQRT(zdelta) ) / 2.
+               ELSE
+                 zh_max(ji,jj,jk) = 2.*akw3(ji,jj,jk) /( p_alktot-zalknw_sup(ji,jj,jk) + SQRT(zdelta) )
+               ENDIF
+
+               zhi(ji,jj,jk) = MAX(MIN(zh_max(ji,jj,jk), zh_ini), zh_min(ji,jj,jk))
+            ENDIF
+         END DO
+      END DO
+   END DO
+
+   zeqn_absmin(:,:,:) = HUGE(1._wp)
+
+   DO jn = 1, jp_maxniter_atgen 
+   DO jk = 1, jpk
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF (rmask(ji,jj,jk) == 1.) THEN
+               zfact = rhop(ji,jj,jk) / 1000. + rtrn
+               p_alktot = trb(ji,jj,jk,jptal) / zfact
+               zdic  = trb(ji,jj,jk,jpdic) / zfact
+               zbot  = borat(ji,jj,jk)
+               zpt = trb(ji,jj,jk,jppo4) / zfact * po4r
+               zsit = trb(ji,jj,jk,jpsil) / zfact
+               zst = sulfat (ji,jj,jk)
+               zft = fluorid(ji,jj,jk)
+               aphscale = 1. + sulfat(ji,jj,jk)/aks3(ji,jj,jk)
+               zh = zhi(ji,jj,jk)
+               zh_prev = zh
+
+               ! H2CO3 - HCO3 - CO3 : n=2, m=0
+               znumer_dic = 2.*ak13(ji,jj,jk)*ak23(ji,jj,jk) + zh*ak13(ji,jj,jk)
+               zdenom_dic = ak13(ji,jj,jk)*ak23(ji,jj,jk) + zh*(ak13(ji,jj,jk) + zh)
+               zalk_dic   = zdic * (znumer_dic/zdenom_dic)
+               zdnumer_dic = ak13(ji,jj,jk)*ak13(ji,jj,jk)*ak23(ji,jj,jk) + zh     &
+                             *(4.*ak13(ji,jj,jk)*ak23(ji,jj,jk) + zh*ak13(ji,jj,jk))
+               zdalk_dic   = -zdic*(zdnumer_dic/zdenom_dic**2)
+
+
+               ! B(OH)3 - B(OH)4 : n=1, m=0
+               znumer_bor = akb3(ji,jj,jk)
+               zdenom_bor = akb3(ji,jj,jk) + zh
+               zalk_bor   = zbot * (znumer_bor/zdenom_bor)
+               zdnumer_bor = akb3(ji,jj,jk)
+               zdalk_bor   = -zbot*(zdnumer_bor/zdenom_bor**2)
+
+
+               ! H3PO4 - H2PO4 - HPO4 - PO4 : n=3, m=1
+               znumer_po4 = 3.*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak3p3(ji,jj,jk)  &
+               &            + zh*(2.*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk) + zh* ak1p3(ji,jj,jk))
+               zdenom_po4 = ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak3p3(ji,jj,jk)     &
+               &            + zh*( ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk) + zh*(ak1p3(ji,jj,jk) + zh))
+               zalk_po4   = zpt * (znumer_po4/zdenom_po4 - 1.) ! Zero level of H3PO4 = 1
+               zdnumer_po4 = ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak3p3(ji,jj,jk)  &
+               &             + zh*(4.*ak1p3(ji,jj,jk)*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak3p3(ji,jj,jk)         &
+               &             + zh*(9.*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)*ak3p3(ji,jj,jk)                         &
+               &             + ak1p3(ji,jj,jk)*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk)                                &
+               &             + zh*(4.*ak1p3(ji,jj,jk)*ak2p3(ji,jj,jk) + zh * ak1p3(ji,jj,jk) ) ) )
+               zdalk_po4   = -zpt * (zdnumer_po4/zdenom_po4**2)
+
+               ! H4SiO4 - H3SiO4 : n=1, m=0
+               znumer_sil = aksi3(ji,jj,jk)
+               zdenom_sil = aksi3(ji,jj,jk) + zh
+               zalk_sil   = zsit * (znumer_sil/zdenom_sil)
+               zdnumer_sil = aksi3(ji,jj,jk)
+               zdalk_sil   = -zsit * (zdnumer_sil/zdenom_sil**2)
+
+               ! HSO4 - SO4 : n=1, m=1
+               aphscale = 1.0 + zst/aks3(ji,jj,jk)
+               znumer_so4 = aks3(ji,jj,jk) * aphscale
+               zdenom_so4 = aks3(ji,jj,jk) * aphscale + zh
+               zalk_so4   = zst * (znumer_so4/zdenom_so4 - 1.)
+               zdnumer_so4 = aks3(ji,jj,jk)
+               zdalk_so4   = -zst * (zdnumer_so4/zdenom_so4**2)
+
+               ! HF - F : n=1, m=1
+               znumer_flu =  akf3(ji,jj,jk)
+               zdenom_flu =  akf3(ji,jj,jk) + zh
+               zalk_flu   =  zft * (znumer_flu/zdenom_flu - 1.)
+               zdnumer_flu = akf3(ji,jj,jk)
+               zdalk_flu   = -zft * (zdnumer_flu/zdenom_flu**2)
+
+               ! H2O - OH
+               aphscale = 1.0 + zst/aks3(ji,jj,jk)
+               zalk_wat   = akw3(ji,jj,jk)/zh - zh/aphscale
+               zdalk_wat  = -akw3(ji,jj,jk)/zh**2 - 1./aphscale
+
+               ! CALCULATE [ALK]([CO3--], [HCO3-])
+               zeqn = zalk_dic + zalk_bor + zalk_po4 + zalk_sil   &
+               &      + zalk_so4 + zalk_flu                       &
+               &      + zalk_wat - p_alktot
+
+               zalka = p_alktot - (zalk_bor + zalk_po4 + zalk_sil   &
+               &       + zalk_so4 + zalk_flu + zalk_wat)
+
+               zdeqndh = zdalk_dic + zdalk_bor + zdalk_po4 + zdalk_sil &
+               &         + zdalk_so4 + zdalk_flu + zdalk_wat
+
+               ! Adapt bracketing interval
+               IF(zeqn > 0._wp) THEN
+                 zh_min(ji,jj,jk) = zh_prev
+               ELSEIF(zeqn < 0._wp) THEN
+                 zh_max(ji,jj,jk) = zh_prev
+               ENDIF
+
+               IF(ABS(zeqn) >= 0.5_wp*zeqn_absmin(ji,jj,jk)) THEN
+               ! if the function evaluation at the current point is
+               ! not decreasing faster than with a bisection step (at least linearly)
+               ! in absolute value take one bisection step on [ph_min, ph_max]
+               ! ph_new = (ph_min + ph_max)/2d0
+               !
+               ! In terms of [H]_new:
+               ! [H]_new = 10**(-ph_new)
+               !         = 10**(-(ph_min + ph_max)/2d0)
+               !         = SQRT(10**(-(ph_min + phmax)))
+               !         = SQRT(zh_max * zh_min)
+                  zh = SQRT(zh_max(ji,jj,jk) * zh_min(ji,jj,jk))
+                  zh_lnfactor = (zh - zh_prev)/zh_prev ! Required to test convergence below
+               ELSE
+               ! dzeqn/dpH = dzeqn/d[H] * d[H]/dpH
+               !           = -zdeqndh * LOG(10) * [H]
+               ! \Delta pH = -zeqn/(zdeqndh*d[H]/dpH) = zeqn/(zdeqndh*[H]*LOG(10))
+               !
+               ! pH_new = pH_old + \deltapH
+               !
+               ! [H]_new = 10**(-pH_new)
+               !         = 10**(-pH_old - \Delta pH)
+               !         = [H]_old * 10**(-zeqn/(zdeqndh*[H]_old*LOG(10)))
+               !         = [H]_old * EXP(-LOG(10)*zeqn/(zdeqndh*[H]_old*LOG(10)))
+               !         = [H]_old * EXP(-zeqn/(zdeqndh*[H]_old))
+
+                  zh_lnfactor = -zeqn/(zdeqndh*zh_prev)
+
+                  IF(ABS(zh_lnfactor) > pz_exp_threshold) THEN
+                     zh          = zh_prev*EXP(zh_lnfactor)
+                  ELSE
+                     zh_delta    = zh_lnfactor*zh_prev
+                     zh          = zh_prev + zh_delta
+                  ENDIF
+
+                  IF( zh < zh_min(ji,jj,jk) ) THEN
+                     ! if [H]_new < [H]_min
+                     ! i.e., if ph_new > ph_max then
+                     ! take one bisection step on [ph_prev, ph_max]
+                     ! ph_new = (ph_prev + ph_max)/2d0
+                     ! In terms of [H]_new:
+                     ! [H]_new = 10**(-ph_new)
+                     !         = 10**(-(ph_prev + ph_max)/2d0)
+                     !         = SQRT(10**(-(ph_prev + phmax)))
+                     !         = SQRT([H]_old*10**(-ph_max))
+                     !         = SQRT([H]_old * zh_min)
+                     zh                = SQRT(zh_prev * zh_min(ji,jj,jk))
+                     zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+                  ENDIF
+
+                  IF( zh > zh_max(ji,jj,jk) ) THEN
+                     ! if [H]_new > [H]_max
+                     ! i.e., if ph_new < ph_min, then
+                     ! take one bisection step on [ph_min, ph_prev]
+                     ! ph_new = (ph_prev + ph_min)/2d0
+                     ! In terms of [H]_new:
+                     ! [H]_new = 10**(-ph_new)
+                     !         = 10**(-(ph_prev + ph_min)/2d0)
+                     !         = SQRT(10**(-(ph_prev + ph_min)))
+                     !         = SQRT([H]_old*10**(-ph_min))
+                     !         = SQRT([H]_old * zhmax)
+                     zh                = SQRT(zh_prev * zh_max(ji,jj,jk))
+                     zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+                  ENDIF
+               ENDIF
+
+               zeqn_absmin(ji,jj,jk) = MIN( ABS(zeqn), zeqn_absmin(ji,jj,jk))
+
+               ! Stop iterations once |\delta{[H]}/[H]| < rdel
+               ! <=> |(zh - zh_prev)/zh_prev| = |EXP(-zeqn/(zdeqndh*zh_prev)) -1| < rdel
+               ! |EXP(-zeqn/(zdeqndh*zh_prev)) -1| ~ |zeqn/(zdeqndh*zh_prev)|
+
+               ! Alternatively:
+               ! |\Delta pH| = |zeqn/(zdeqndh*zh_prev*LOG(10))|
+               !             ~ 1/LOG(10) * |\Delta [H]|/[H]
+               !             < 1/LOG(10) * rdel
+
+               ! Hence |zeqn/(zdeqndh*zh)| < rdel
+
+               ! rdel <-- pp_rdel_ah_target
+               l_exitnow = (ABS(zh_lnfactor) < pp_rdel_ah_target)
+
+               IF(l_exitnow) THEN 
+                  rmask(ji,jj,jk) = 0.
+               ENDIF
+
+               zhi(ji,jj,jk) =  zh
+
+               IF(jn >= jp_maxniter_atgen) THEN
+                  zhi(ji,jj,jk) = -1._wp
+               ENDIF
+
+            ENDIF
+         END DO
+      END DO
+   END DO
+   END DO
+   !
+
+      IF( ln_timing )   CALL timing_stop('solve_at_general')
+      !
+   END SUBROUTINE solve_at_general
+
+
+   INTEGER FUNCTION p4z_che_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_che_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER ::   ierr(3)        ! Local variables
+      !!----------------------------------------------------------------------
+
+      ierr(:) = 0
+
+      ALLOCATE( sio3eq(jpi,jpj,jpk), fekeq(jpi,jpj,jpk), chemc(jpi,jpj,3), chemo2(jpi,jpj,jpk), STAT=ierr(1) )
+
+      ALLOCATE( akb3(jpi,jpj,jpk)     , tempis(jpi, jpj, jpk),       &
+         &      akw3(jpi,jpj,jpk)     , borat (jpi,jpj,jpk)  ,       &
+         &      aks3(jpi,jpj,jpk)     , akf3(jpi,jpj,jpk)    ,       &
+         &      ak1p3(jpi,jpj,jpk)    , ak2p3(jpi,jpj,jpk)   ,       &
+         &      ak3p3(jpi,jpj,jpk)    , aksi3(jpi,jpj,jpk)   ,       &
+         &      fluorid(jpi,jpj,jpk)  , sulfat(jpi,jpj,jpk)  ,       &
+         &      salinprac(jpi,jpj,jpk),                 STAT=ierr(2) )
+
+      ALLOCATE( fesol(jpi,jpj,jpk,5), STAT=ierr(3) )
+
+      !* Variable for chemistry of the CO2 cycle
+      p4z_che_alloc = MAXVAL( ierr )
+      !
+      IF( p4z_che_alloc /= 0 )   CALL ctl_stop( 'STOP', 'p4z_che_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p4z_che_alloc
+
+   !!======================================================================
+END MODULE p4zche
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zfechem.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zfechem.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zfechem.F90	(revision 14097)
@@ -0,0 +1,282 @@
+MODULE p4zfechem
+   !!======================================================================
+   !!                         ***  MODULE p4zfechem  ***
+   !! TOP :   PISCES Compute iron chemistry and scavenging
+   !!======================================================================
+   !! History :   3.5  !  2012-07 (O. Aumont, A. Tagliabue, C. Ethe) Original code
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p4z_fechem       : Compute remineralization/scavenging of iron
+   !!   p4z_fechem_init  : Initialisation of parameters for remineralisation
+   !!   p4z_fechem_alloc : Allocate remineralisation variables
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zche          ! chemical model
+   USE p4zsbc           ! Boundary conditions from sediments
+   USE prtctl_trc      ! print control for debugging
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_fechem        ! called in p4zbio.F90
+   PUBLIC   p4z_fechem_init   ! called in trcsms_pisces.F90
+
+   LOGICAL          ::   ln_ligvar    !: boolean for variable ligand concentration following Tagliabue and voelker
+   REAL(wp), PUBLIC ::   xlam1        !: scavenging rate of Iron 
+   REAL(wp), PUBLIC ::   xlamdust     !: scavenging rate of Iron by dust 
+   REAL(wp), PUBLIC ::   ligand       !: ligand concentration in the ocean 
+   REAL(wp), PUBLIC ::   kfep         !: rate constant for nanoparticle formation
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_fechem( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_fechem  ***
+      !!
+      !! ** Purpose :   Compute remineralization/scavenging of iron
+      !!
+      !! ** Method  :   A simple chemistry model of iron from Aumont and Bopp (2006)
+      !!                based on one ligand and one inorganic form
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   ! ocean time step
+      !
+      INTEGER  ::   ji, jj, jk, jic, jn
+      REAL(wp) ::   zdep, zlam1a, zlam1b, zlamfac
+      REAL(wp) ::   zkeq, zfeequi, zfesatur, zfecoll, fe3sol
+      REAL(wp) ::   zdenom1, zscave, zaggdfea, zaggdfeb, zcoag
+      REAL(wp) ::   ztrc, zdust
+      REAL(wp) ::   zdenom2
+      REAL(wp) ::   zzFeL1, zzFeL2, zzFe2, zzFeP, zzFe3, zzstrn2
+      REAL(wp) ::   zrum, zcodel, zargu, zlight
+      REAL(wp) ::   zkox, zkph1, zkph2, zph, zionic, ztligand
+      REAL(wp) ::   za, zb, zc, zkappa1, zkappa2, za0, za1, za2
+      REAL(wp) ::   zxs, zfunc, zp, zq, zd, zr, zphi, zfff, zp3, zq2
+      REAL(wp) ::   ztfe, zoxy, zhplus, zxlam
+      REAL(wp) ::   zaggliga, zaggligb
+      REAL(wp) ::   dissol, zligco
+      REAL(wp) :: zrfact2
+      CHARACTER (len=25) :: charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zTL1, zFe3, ztotlig, precip, zFeL1
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zcoll3d, zscav3d, zlcoll3d
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_fechem')
+      !
+
+      ! Total ligand concentration : Ligands can be chosen to be constant or variable
+      ! Parameterization from Tagliabue and Voelker (2011)
+      ! -------------------------------------------------
+      IF( ln_ligvar ) THEN
+         ztotlig(:,:,:) =  0.09 * trb(:,:,:,jpdoc) * 1E6 + ligand * 1E9
+         ztotlig(:,:,:) =  MIN( ztotlig(:,:,:), 10. )
+      ELSE
+        IF( ln_ligand ) THEN  ;   ztotlig(:,:,:) = trb(:,:,:,jplgw) * 1E9
+        ELSE                  ;   ztotlig(:,:,:) = ligand * 1E9
+        ENDIF
+      ENDIF
+
+      ! ------------------------------------------------------------
+      !  from Aumont and Bopp (2006)
+      ! This model is based on one ligand and Fe' 
+      ! Chemistry is supposed to be fast enough to be at equilibrium
+      ! ------------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zTL1(ji,jj,jk)  = ztotlig(ji,jj,jk)
+               zkeq            = fekeq(ji,jj,jk)
+               zfesatur        = zTL1(ji,jj,jk) * 1E-9
+               ztfe            = trb(ji,jj,jk,jpfer) 
+               ! Fe' is the root of a 2nd order polynom
+               zFe3 (ji,jj,jk) = ( -( 1. + zfesatur * zkeq - zkeq * ztfe )               &
+                  &              + SQRT( ( 1. + zfesatur * zkeq - zkeq * ztfe )**2       &
+                  &              + 4. * ztfe * zkeq) ) / ( 2. * zkeq )
+               zFe3 (ji,jj,jk) = zFe3(ji,jj,jk) * 1E9
+               zFeL1(ji,jj,jk) = MAX( 0., trb(ji,jj,jk,jpfer) * 1E9 - zFe3(ji,jj,jk) )
+           END DO
+         END DO
+      END DO
+         !
+
+      zdust = 0.         ! if no dust available
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! Scavenging rate of iron. This scavenging rate depends on the load of particles of sea water. 
+               ! This parameterization assumes a simple second order kinetics (k[Particles][Fe]).
+               ! Scavenging onto dust is also included as evidenced from the DUNE experiments.
+               ! --------------------------------------------------------------------------------------
+               zhplus  = max( rtrn, hi(ji,jj,jk) )
+               fe3sol  = fesol(ji,jj,jk,1) * ( zhplus**3 + fesol(ji,jj,jk,2) * zhplus**2  &
+               &         + fesol(ji,jj,jk,3) * zhplus + fesol(ji,jj,jk,4)     &
+               &         + fesol(ji,jj,jk,5) / zhplus )
+               !
+               zfeequi = zFe3(ji,jj,jk) * 1E-9
+               zfecoll = 0.5 * zFeL1(ji,jj,jk) * 1E-9
+               ! precipitation of Fe3+, creation of nanoparticles
+               precip(ji,jj,jk) = MAX( 0., ( zFe3(ji,jj,jk) * 1E-9 - fe3sol ) ) * kfep * xstep
+               !
+               ztrc   = ( trb(ji,jj,jk,jppoc) + trb(ji,jj,jk,jpgoc) + trb(ji,jj,jk,jpcal) + trb(ji,jj,jk,jpgsi) ) * 1.e6 
+               IF( ln_dust )  zdust  = dust(ji,jj) / ( wdust / rday ) * tmask(ji,jj,jk) &
+               &  * EXP( -gdept_n(ji,jj,jk) / 540. )
+               IF (ln_ligand) THEN
+                  zxlam  = xlam1 * MAX( 1.E-3, EXP(-2 * etot(ji,jj,jk) / 10. ) * (1. - EXP(-2 * trb(ji,jj,jk,jpoxy) / 100.E-6 ) ))
+               ELSE
+                  zxlam  = xlam1 * 1.0
+               ENDIF
+               zlam1b = 3.e-5 + xlamdust * zdust + zxlam * ztrc
+               zscave = zfeequi * zlam1b * xstep
+
+               ! Compute the different ratios for scavenging of iron
+               ! to later allocate scavenged iron to the different organic pools
+               ! ---------------------------------------------------------
+               zdenom1 = zxlam * trb(ji,jj,jk,jppoc) / zlam1b
+               zdenom2 = zxlam * trb(ji,jj,jk,jpgoc) / zlam1b
+
+               !  Increased scavenging for very high iron concentrations found near the coasts 
+               !  due to increased lithogenic particles and let say it is unknown processes (precipitation, ...)
+               !  -----------------------------------------------------------
+               zlamfac = MAX( 0.e0, ( gphit(ji,jj) + 55.) / 30. )
+               zlamfac = MIN( 1.  , zlamfac )
+               zdep    = MIN( 1., 1000. / gdept_n(ji,jj,jk) )
+               zcoag   = 1E-4 * ( 1. - zlamfac ) * zdep * xstep * trb(ji,jj,jk,jpfer)
+
+               !  Compute the coagulation of colloidal iron. This parameterization 
+               !  could be thought as an equivalent of colloidal pumping.
+               !  It requires certainly some more work as it is very poorly constrained.
+               !  ----------------------------------------------------------------
+               zlam1a   = ( 0.369  * 0.3 * trb(ji,jj,jk,jpdoc) + 102.4  * trb(ji,jj,jk,jppoc) ) * xdiss(ji,jj,jk)    &
+                   &      + ( 114.   * 0.3 * trb(ji,jj,jk,jpdoc) )
+               zaggdfea = zlam1a * xstep * zfecoll
+               !
+               zlam1b   = 3.53E3 * trb(ji,jj,jk,jpgoc) * xdiss(ji,jj,jk)
+               zaggdfeb = zlam1b * xstep * zfecoll
+               !
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - zscave - zaggdfea - zaggdfeb &
+               &                     - zcoag - precip(ji,jj,jk)
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zscave * zdenom1 + zaggdfea
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zscave * zdenom2 + zaggdfeb
+               zscav3d(ji,jj,jk)   = zscave
+               zcoll3d(ji,jj,jk)   = zaggdfea + zaggdfeb
+               !
+            END DO
+         END DO
+      END DO
+      !
+      !  Define the bioavailable fraction of iron
+      !  ----------------------------------------
+      biron(:,:,:) = trb(:,:,:,jpfer) 
+      !
+      IF( ln_ligand ) THEN
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zlam1a   = ( 0.369  * 0.3 * trb(ji,jj,jk,jpdoc) + 102.4  * trb(ji,jj,jk,jppoc) ) * xdiss(ji,jj,jk)    &
+                      &    + ( 114.   * 0.3 * trb(ji,jj,jk,jpdoc) )
+                  !
+                  zlam1b   = 3.53E3 *   trb(ji,jj,jk,jpgoc) * xdiss(ji,jj,jk)
+                  zligco   = 0.5 * trn(ji,jj,jk,jplgw)
+                  zaggliga = zlam1a * xstep * zligco
+                  zaggligb = zlam1b * xstep * zligco
+                  tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) - zaggliga - zaggligb
+                  zlcoll3d(ji,jj,jk)  = zaggliga + zaggligb
+               END DO
+            END DO
+         END DO
+         !
+         plig(:,:,:) =  MAX( 0., ( ( zFeL1(:,:,:) * 1E-9 ) / ( trb(:,:,:,jpfer) +rtrn ) ) )
+         !
+      ENDIF
+      !  Output of some diagnostics variables
+      !     ---------------------------------
+      IF( lk_iomput ) THEN
+         IF( knt == nrdttrc ) THEN
+            zrfact2 = 1.e3 * rfact2r  ! conversion from mol/L/timestep into mol/m3/s
+            IF( iom_use("Fe3")  )  THEN
+               zFe3(:,:,jpk) = 0.  ;  CALL iom_put("Fe3" , zFe3(:,:,:) * tmask(:,:,:) )   ! Fe3+
+            ENDIF
+            IF( iom_use("FeL1") )  THEN
+              zFeL1(:,:,jpk) = 0.  ;  CALL iom_put("FeL1", zFeL1(:,:,:) * tmask(:,:,:) )   ! FeL1
+            ENDIF
+            IF( iom_use("TL1")  )  THEN
+              zTL1(:,:,jpk) = 0.   ;  CALL iom_put("TL1" , zTL1(:,:,:) * tmask(:,:,:) )   ! TL1
+            ENDIF
+            CALL iom_put("Totlig" , ztotlig(:,:,:)       * tmask(:,:,:) )   ! TL
+            CALL iom_put("Biron"  , biron  (:,:,:)  * 1e9 * tmask(:,:,:) )   ! biron
+            IF( iom_use("FESCAV") )  THEN
+               zscav3d (:,:,jpk) = 0.  ;  CALL iom_put("FESCAV" , zscav3d(:,:,:)  * 1e9 * tmask(:,:,:) * zrfact2 )
+            ENDIF
+            IF( iom_use("FECOLL") ) THEN
+               zcoll3d (:,:,jpk) = 0.  ;   CALL iom_put("FECOLL" , zcoll3d(:,:,:)  * 1e9 * tmask(:,:,:) * zrfact2 )
+            ENDIF
+            IF( iom_use("LGWCOLL")) THEN
+               zlcoll3d(:,:,jpk) = 0.  ;  CALL iom_put("LGWCOLL", zlcoll3d(:,:,:) * 1e9 * tmask(:,:,:) * zrfact2 )
+            ENDIF
+         ENDIF
+      ENDIF
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('fechem')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_fechem')
+      !
+   END SUBROUTINE p4z_fechem
+
+
+   SUBROUTINE p4z_fechem_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_fechem_init  ***
+      !!
+      !! ** Purpose :   Initialization of iron chemistry parameters
+      !!
+      !! ** Method  :   Read the nampisfer namelist and check the parameters
+      !!      called at the first timestep
+      !!
+      !! ** input   :   Namelist nampisfer
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer 
+      !!
+      NAMELIST/nampisfer/ ln_ligvar, xlam1, xlamdust, ligand, kfep 
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_rem_init : Initialization of iron chemistry parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampisfer, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisfer in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampisfer, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisfer in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampisfer )
+
+      IF(lwp) THEN                     ! control print
+         WRITE(numout,*) '   Namelist : nampisfer'
+         WRITE(numout,*) '      variable concentration of ligand          ln_ligvar    =', ln_ligvar
+         WRITE(numout,*) '      scavenging rate of Iron                   xlam1        =', xlam1
+         WRITE(numout,*) '      scavenging rate of Iron by dust           xlamdust     =', xlamdust
+         WRITE(numout,*) '      ligand concentration in the ocean         ligand       =', ligand
+         WRITE(numout,*) '      rate constant for nanoparticle formation  kfep         =', kfep
+      ENDIF
+      ! 
+   END SUBROUTINE p4z_fechem_init
+   
+   !!======================================================================
+END MODULE p4zfechem
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zflx.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zflx.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zflx.F90	(revision 14097)
@@ -0,0 +1,370 @@
+MODULE p4zflx
+   !!======================================================================
+   !!                         ***  MODULE p4zflx  ***
+   !! TOP :   PISCES CALCULATES GAS EXCHANGE AND CHEMISTRY AT SEA SURFACE
+   !!======================================================================
+   !! History :   -   !  1988-07  (E. MAIER-REIMER) Original code
+   !!             -   !  1998     (O. Aumont) additions
+   !!             -   !  1999     (C. Le Quere) modifications
+   !!            1.0  !  2004     (O. Aumont) modifications
+   !!            2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!                 !  2011-02  (J. Simeon, J. Orr) Include total atm P correction 
+   !!----------------------------------------------------------------------
+   !!   p4z_flx       :   CALCULATES GAS EXCHANGE AND CHEMISTRY AT SEA SURFACE
+   !!   p4z_flx_init  :   Read the namelist
+   !!   p4z_patm      :   Read sfc atm pressure [atm] for each grid cell
+   !!----------------------------------------------------------------------
+   USE oce_trc        !  shared variables between ocean and passive tracers 
+   USE trc            !  passive tracers common variables
+   USE sms_pisces     !  PISCES Source Minus Sink variables
+   USE p4zche         !  Chemical model
+   USE prtctl_trc     !  print control for debugging
+   USE iom            !  I/O manager
+   USE fldread        !  read input fields
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_flx  
+   PUBLIC   p4z_flx_init  
+   PUBLIC   p4z_flx_alloc  
+
+   !                                 !!** Namelist  nampisext  **
+   REAL(wp)          ::   atcco2      !: pre-industrial atmospheric [co2] (ppm) 	
+   LOGICAL           ::   ln_co2int   !: flag to read in a file and interpolate atmospheric pco2 or not
+   CHARACTER(len=34) ::   clname      !: filename of pco2 values
+   INTEGER           ::   nn_offset   !: Offset model-data start year (default = 0) 
+
+   !!  Variables related to reading atmospheric CO2 time history    
+   INTEGER                                   ::   nmaxrec, numco2   !
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) ::   atcco2h, years    !
+
+   !                                  !!* nampisatm namelist (Atmospheric PRessure) *
+   LOGICAL, PUBLIC ::   ln_presatm     !: ref. pressure: global mean Patm (F) or a constant (F)
+   LOGICAL, PUBLIC ::   ln_presatmco2  !: accounting for spatial atm CO2 in the compuation of carbon flux (T) or not (F)
+
+   REAL(wp) , ALLOCATABLE, SAVE, DIMENSION(:,:) ::   patm      ! atmospheric pressure at kt                 [N/m2]
+   TYPE(FLD), ALLOCATABLE,       DIMENSION(:)   ::   sf_patm   ! structure of input fields (file informations, fields read)
+   TYPE(FLD), ALLOCATABLE,       DIMENSION(:)   ::   sf_atmco2 ! structure of input fields (file informations, fields read)
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  satmco2   !: atmospheric pco2 
+
+   REAL(wp) ::   xconv  = 0.01_wp / 3600._wp   !: coefficients for conversion 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_flx ( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_flx  ***
+      !!
+      !! ** Purpose :   CALCULATES GAS EXCHANGE AND CHEMISTRY AT SEA SURFACE
+      !!
+      !! ** Method  : 
+      !!              - Include total atm P correction via Esbensen & Kushnir (1981) 
+      !!              - Remove Wanninkhof chemical enhancement;
+      !!              - Add option for time-interpolation of atcco2.txt  
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   !
+      !
+      INTEGER  ::   ji, jj, jm, iind, iindm1
+      REAL(wp) ::   ztc, ztc2, ztc3, ztc4, zws, zkgwan
+      REAL(wp) ::   zfld, zflu, zfld16, zflu16, zfact
+      REAL(wp) ::   zvapsw, zsal, zfco2, zxc2, xCO2approx, ztkel, zfugcoeff
+      REAL(wp) ::   zph, zdic, zsch_o2, zsch_co2
+      REAL(wp) ::   zyr_dec, zdco2dt
+      CHARACTER (len=25) ::   charout
+      REAL(wp), DIMENSION(jpi,jpj) ::   zkgco2, zkgo2, zh2co3, zoflx,  zpco2atm  
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_flx')
+      !
+      ! SURFACE CHEMISTRY (PCO2 AND [H+] IN
+      !     SURFACE LAYER); THE RESULT OF THIS CALCULATION
+      !     IS USED TO COMPUTE AIR-SEA FLUX OF CO2
+
+      IF( kt /= nit000 .AND. .NOT.l_co2cpl .AND. knt == 1 )   CALL p4z_patm( kt )   ! Get sea-level pressure (E&K [1981] climatology) for use in flux calcs
+
+      IF( ln_co2int .AND. .NOT.ln_presatmco2 .AND. .NOT.l_co2cpl ) THEN 
+         ! Linear temporal interpolation  of atmospheric pco2.  atcco2.txt has annual values.
+         ! Caveats: First column of .txt must be in years, decimal  years preferably. 
+         ! For nn_offset, if your model year is iyy, nn_offset=(years(1)-iyy) 
+         ! then the first atmospheric CO2 record read is at years(1)
+         zyr_dec = REAL( nyear + nn_offset, wp ) + REAL( nday_year, wp ) / REAL( nyear_len(1), wp )
+         jm = 1
+         DO WHILE( jm <= nmaxrec .AND. years(jm) < zyr_dec ) ;  jm = jm + 1 ;  END DO
+         iind = jm  ;   iindm1 = jm - 1
+         zdco2dt = ( atcco2h(iind) - atcco2h(iindm1) ) / ( years(iind) - years(iindm1) + rtrn )
+         atcco2  = zdco2dt * ( zyr_dec - years(iindm1) ) + atcco2h(iindm1)
+         satmco2(:,:) = atcco2 
+      ENDIF
+
+      IF( l_co2cpl )   satmco2(:,:) = atm_co2(:,:)
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ! DUMMY VARIABLES FOR DIC, H+, AND BORATE
+            zfact = rhop(ji,jj,1) / 1000. + rtrn
+            zdic  = trb(ji,jj,1,jpdic)
+            zph   = MAX( hi(ji,jj,1), 1.e-10 ) / zfact
+            ! CALCULATE [H2CO3]
+            zh2co3(ji,jj) = zdic/(1. + ak13(ji,jj,1)/zph + ak13(ji,jj,1)*ak23(ji,jj,1)/zph**2)
+         END DO
+      END DO
+
+      ! --------------
+      ! COMPUTE FLUXES
+      ! --------------
+
+      ! FIRST COMPUTE GAS EXCHANGE COEFFICIENTS
+      ! -------------------------------------------
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztc  = MIN( 35., tsn(ji,jj,1,jp_tem) )
+            ztc2 = ztc * ztc
+            ztc3 = ztc * ztc2 
+            ztc4 = ztc2 * ztc2 
+            ! Compute the schmidt Number both O2 and CO2
+            zsch_co2 = 2116.8 - 136.25 * ztc + 4.7353 * ztc2 - 0.092307 * ztc3 + 0.0007555 * ztc4
+            zsch_o2  = 1920.4 - 135.6  * ztc + 5.2122 * ztc2 - 0.109390 * ztc3 + 0.0009377 * ztc4
+            !  wind speed 
+            zws  = wndm(ji,jj) * wndm(ji,jj)
+            ! Compute the piston velocity for O2 and CO2
+            zkgwan = 0.251 * zws
+            zkgwan = zkgwan * xconv * ( 1.- fr_i(ji,jj) ) * tmask(ji,jj,1)
+            ! compute gas exchange for CO2 and O2
+            zkgco2(ji,jj) = zkgwan * SQRT( 660./ zsch_co2 )
+            zkgo2 (ji,jj) = zkgwan * SQRT( 660./ zsch_o2 )
+         END DO
+      END DO
+
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ztkel = tempis(ji,jj,1) + 273.15
+            zsal  = salinprac(ji,jj,1) + ( 1.- tmask(ji,jj,1) ) * 35.
+            zvapsw    = EXP(24.4543 - 67.4509*(100.0/ztkel) - 4.8489*LOG(ztkel/100) - 0.000544*zsal)
+            zpco2atm(ji,jj) = satmco2(ji,jj) * ( patm(ji,jj) - zvapsw )
+            zxc2      = ( 1.0 - zpco2atm(ji,jj) * 1E-6 )**2
+            zfugcoeff = EXP( patm(ji,jj) * (chemc(ji,jj,2) + 2.0 * zxc2 * chemc(ji,jj,3) )   &
+            &           / ( 82.05736 * ztkel ))
+            zfco2 = zpco2atm(ji,jj) * zfugcoeff
+
+            ! Compute CO2 flux for the sea and air
+            zfld = zfco2 * chemc(ji,jj,1) * zkgco2(ji,jj)  ! (mol/L) * (m/s)
+            zflu = zh2co3(ji,jj) * zkgco2(ji,jj)                                   ! (mol/L) (m/s) ?
+            oce_co2(ji,jj) = ( zfld - zflu ) * tmask(ji,jj,1) 
+            ! compute the trend
+            tra(ji,jj,1,jpdic) = tra(ji,jj,1,jpdic) + oce_co2(ji,jj) * rfact2 / e3t_n(ji,jj,1)
+
+            ! Compute O2 flux 
+            zfld16 = patm(ji,jj) * chemo2(ji,jj,1) * zkgo2(ji,jj)          ! (mol/L) * (m/s)
+            zflu16 = trb(ji,jj,1,jpoxy) * zkgo2(ji,jj)
+            zoflx(ji,jj) = ( zfld16 - zflu16 ) * tmask(ji,jj,1)
+            tra(ji,jj,1,jpoxy) = tra(ji,jj,1,jpoxy) + zoflx(ji,jj) * rfact2 / e3t_n(ji,jj,1)
+         END DO
+      END DO
+
+      IF( iom_use("tcflx") .OR. iom_use("tcflxcum") .OR. kt == nitrst   &
+         &                 .OR. (ln_check_mass .AND. kt == nitend) )    &
+         t_oce_co2_flx  = glob_sum( 'p4zflx', oce_co2(:,:) * e1e2t(:,:) * 1000. )                    !  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( 'p4zflx', 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 ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+         CALL iom_put( "AtmCo2"  , satmco2(:,:) * tmask(:,:,1) )   ! Atmospheric CO2 concentration
+         CALL iom_put( "Cflx"    , oce_co2(:,:) * 1000. ) 
+         CALL iom_put( "Oflx"    , zoflx(:,:) * 1000.  )
+         CALL iom_put( "Kg"      , zkgco2(:,:) * tmask(:,:,1)  )
+         CALL iom_put( "Dpco2"   , ( zpco2atm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1) )
+         CALL iom_put( "pCO2sea" , ( zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1) )
+         CALL iom_put( "Dpo2"    , ( atcox * patm(:,:) - atcox * trb(:,:,1,jpoxy) / ( chemo2(:,:,1) + rtrn ) ) * tmask(:,:,1) )
+         CALL iom_put( "tcflx"   , t_oce_co2_flx     )   ! molC/s
+         CALL iom_put( "tcflxcum", t_oce_co2_flx_cum )   ! molC
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_flx')
+      !
+   END SUBROUTINE p4z_flx
+
+
+   SUBROUTINE p4z_flx_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_flx_init  ***
+      !!
+      !! ** Purpose :   Initialization of atmospheric conditions
+      !!
+      !! ** Method  :   Read the nampisext namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampisext
+      !!----------------------------------------------------------------------
+      INTEGER ::   jm, ios   ! Local integer 
+      !!
+      NAMELIST/nampisext/ln_co2int, atcco2, clname, nn_offset
+      !!----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' p4z_flx_init : atmospheric conditions for air-sea flux calculation'
+         WRITE(numout,*) ' ~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampisext, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisext in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampisext, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisext in configuration namelist' )
+      IF(lwm) WRITE ( numonp, nampisext )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : nampisext --- parameters for air-sea exchange'
+         WRITE(numout,*) '      reading in the atm pCO2 file or constant value   ln_co2int =', ln_co2int
+      ENDIF
+      !
+      CALL p4z_patm( nit000 )
+      !
+      IF( .NOT.ln_co2int .AND. .NOT.ln_presatmco2 ) THEN
+         IF(lwp) THEN                         ! control print
+            WRITE(numout,*) '         Constant Atmospheric pCO2 value               atcco2    =', atcco2
+         ENDIF
+         satmco2(:,:)  = atcco2      ! Initialisation of atmospheric pco2
+      ELSEIF( ln_co2int .AND. .NOT.ln_presatmco2 ) THEN
+         IF(lwp)  THEN
+            WRITE(numout,*) '         Constant Atmospheric pCO2 value               atcco2    =', atcco2
+            WRITE(numout,*) '         Atmospheric pCO2 value  from file             clname    =', TRIM( clname )
+            WRITE(numout,*) '         Offset model-data start year                  nn_offset =', nn_offset
+         ENDIF
+         CALL ctl_opn( numco2, TRIM( clname) , 'OLD', 'FORMATTED', 'SEQUENTIAL', -1 , numout, lwp )
+         jm = 0                      ! Count the number of record in co2 file
+         DO
+           READ(numco2,*,END=100) 
+           jm = jm + 1
+         END DO
+ 100     nmaxrec = jm - 1 
+         ALLOCATE( years  (nmaxrec) )   ;   years  (:) = 0._wp
+         ALLOCATE( atcco2h(nmaxrec) )   ;   atcco2h(:) = 0._wp
+         !
+         REWIND(numco2)
+         DO jm = 1, nmaxrec          ! get  xCO2 data
+            READ(numco2, *)  years(jm), atcco2h(jm)
+            IF(lwp) WRITE(numout, '(f6.0,f7.2)')  years(jm), atcco2h(jm)
+         END DO
+         CLOSE(numco2)
+      ELSEIF( .NOT.ln_co2int .AND. ln_presatmco2 ) THEN
+         IF(lwp) WRITE(numout,*) '    Spatialized Atmospheric pCO2 from an external file'
+      ELSE
+         IF(lwp) WRITE(numout,*) '    Spatialized Atmospheric pCO2 from an external file'
+      ENDIF
+      !
+      oce_co2(:,:)  = 0._wp                ! Initialization of Flux of Carbon
+      t_oce_co2_flx = 0._wp
+      t_atm_co2_flx = 0._wp
+      !
+   END SUBROUTINE p4z_flx_init
+
+
+   SUBROUTINE p4z_patm( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_atm  ***
+      !!
+      !! ** Purpose :   Read and interpolate the external atmospheric sea-level pressure
+      !! ** Method  :   Read the files and interpolate the appropriate variables
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      INTEGER            ::   ierr, ios   ! Local integer
+      CHARACTER(len=100) ::   cn_dir      ! Root directory for location of ssr files
+      TYPE(FLD_N)        ::   sn_patm     ! informations about the fields to be read
+      TYPE(FLD_N)        ::   sn_atmco2   ! informations about the fields to be read
+      !!
+      NAMELIST/nampisatm/ ln_presatm, ln_presatmco2, sn_patm, sn_atmco2, cn_dir
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN    !==  First call kt=nittrc000  ==!
+         !
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) ' p4z_patm : sea-level atmospheric pressure'
+            WRITE(numout,*) ' ~~~~~~~~'
+         ENDIF
+         !
+         REWIND( numnatp_ref )
+         READ  ( numnatp_ref, nampisatm, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 ) CALL ctl_nam ( ios , 'nampisatm in reference namelist' )
+
+         REWIND( numnatp_cfg )
+         READ  ( numnatp_cfg, nampisatm, IOSTAT = ios, ERR = 902 )
+902      IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisatm in configuration namelist' )
+         IF(lwm) WRITE ( numonp, nampisatm )
+         !
+         !
+         IF(lwp) THEN                                 !* control print
+            WRITE(numout,*) '   Namelist : nampisatm --- Atmospheric Pressure as external forcing'
+            WRITE(numout,*) '      constant atmopsheric pressure (F) or from a file (T)  ln_presatm    = ', ln_presatm
+            WRITE(numout,*) '      spatial atmopsheric CO2 for flux calcs                ln_presatmco2 = ', ln_presatmco2
+         ENDIF
+         !
+         IF( ln_presatm ) THEN
+            ALLOCATE( sf_patm(1), STAT=ierr )           !* allocate and fill sf_patm (forcing structure) with sn_patm
+            IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'p4z_flx: unable to allocate sf_patm structure' )
+            !
+            CALL fld_fill( sf_patm, (/ sn_patm /), cn_dir, 'p4z_flx', 'Atmospheric pressure ', 'nampisatm' )
+                                   ALLOCATE( sf_patm(1)%fnow(jpi,jpj,1)   )
+            IF( sn_patm%ln_tint )  ALLOCATE( sf_patm(1)%fdta(jpi,jpj,1,2) )
+         ENDIF
+         !                                         
+         IF( ln_presatmco2 ) THEN
+            ALLOCATE( sf_atmco2(1), STAT=ierr )           !* allocate and fill sf_atmco2 (forcing structure) with sn_atmco2
+            IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'p4z_flx: unable to allocate sf_atmco2 structure' )
+            !
+            CALL fld_fill( sf_atmco2, (/ sn_atmco2 /), cn_dir, 'p4z_flx', 'Atmospheric co2 partial pressure ', 'nampisatm' )
+                                   ALLOCATE( sf_atmco2(1)%fnow(jpi,jpj,1)   )
+            IF( sn_atmco2%ln_tint )  ALLOCATE( sf_atmco2(1)%fdta(jpi,jpj,1,2) )
+         ENDIF
+         !
+         IF( .NOT.ln_presatm )   patm(:,:) = 1._wp    ! Initialize patm if no reading from a file
+         !
+      ENDIF
+      !
+      IF( ln_presatm ) THEN
+         CALL fld_read( kt, 1, sf_patm )               !* input Patm provided at kt + 1/2
+         patm(:,:) = sf_patm(1)%fnow(:,:,1)                        ! atmospheric pressure
+      ENDIF
+      !
+      IF( ln_presatmco2 ) THEN
+         CALL fld_read( kt, 1, sf_atmco2 )               !* input atmco2 provided at kt + 1/2
+         satmco2(:,:) = sf_atmco2(1)%fnow(:,:,1)                        ! atmospheric pressure
+      ELSE
+         satmco2(:,:) = atcco2    ! Initialize atmco2 if no reading from a file
+      ENDIF
+      !
+   END SUBROUTINE p4z_patm
+
+
+   INTEGER FUNCTION p4z_flx_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_flx_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( satmco2(jpi,jpj), patm(jpi,jpj), STAT=p4z_flx_alloc )
+      !
+      IF( p4z_flx_alloc /= 0 )   CALL ctl_stop( 'STOP', 'p4z_flx_alloc : failed to allocate arrays' )
+      !
+   END FUNCTION p4z_flx_alloc
+
+   !!======================================================================
+END MODULE p4zflx
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zint.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zint.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zint.F90	(revision 14097)
@@ -0,0 +1,67 @@
+MODULE p4zint
+   !!======================================================================
+   !!                         ***  MODULE p4zint  ***
+   !! TOP :   PISCES interpolation and computation of various accessory fields
+   !!======================================================================
+   !! History :   1.0  !  2004-03 (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   p4z_int        :  interpolation and computation of various accessory fields
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_int  
+   REAL(wp) ::   xksilim = 16.5e-6_wp   ! Half-saturation constant for the Si half-saturation constant computation
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_int( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_int  ***
+      !!
+      !! ** Purpose :   interpolation and computation of various accessory fields
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !
+      INTEGER  :: ji, jj                 ! dummy loop indices
+      REAL(wp) :: zvar                   ! local variable
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_int')
+      !
+      ! Computation of phyto and zoo metabolic rate
+      ! -------------------------------------------
+      tgfunc (:,:,:) = EXP( 0.063913 * tsn(:,:,:,jp_tem) )
+      tgfunc2(:,:,:) = EXP( 0.07608  * tsn(:,:,:,jp_tem) )
+
+      ! Computation of the silicon dependant half saturation  constant for silica uptake
+      ! ---------------------------------------------------
+      DO ji = 1, jpi
+         DO jj = 1, jpj
+            zvar = trb(ji,jj,1,jpsil) * trb(ji,jj,1,jpsil)
+            xksimax(ji,jj) = MAX( xksimax(ji,jj), ( 1.+ 7.* zvar / ( xksilim * xksilim + zvar ) ) * 1e-6 )
+         END DO
+      END DO
+      !
+      IF( nday_year == nyear_len(1) ) THEN
+         xksi   (:,:) = xksimax(:,:)
+         xksimax(:,:) = 0._wp
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_int')
+      !
+   END SUBROUTINE p4z_int
+
+   !!======================================================================
+END MODULE p4zint
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zligand.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zligand.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zligand.F90	(revision 14097)
@@ -0,0 +1,142 @@
+MODULE p4zligand
+   !!======================================================================
+   !!                         ***  MODULE p4zligand  ***
+   !! TOP :   PISCES Compute remineralization/dissolution of organic ligands
+   !!=========================================================================
+   !! History :   3.6  !  2016-03  (O. Aumont, A. Tagliabue) Quota model and reorganization
+   !!----------------------------------------------------------------------
+   !!   p4z_ligand     :  Compute remineralization/dissolution of organic ligands
+   !!   p4z_ligand_init:  Initialisation of parameters for remineralisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE prtctl_trc      ! print control for debugging
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_ligand         ! called in p4zbio.F90
+   PUBLIC   p4z_ligand_init    ! called in trcsms_pisces.F90
+
+   REAL(wp), PUBLIC ::  rlgw     !: lifetime (years) of weak ligands
+   REAL(wp), PUBLIC ::  rlgs     !: lifetime (years) of strong ligands
+   REAL(wp), PUBLIC ::  rlig     !: Remin ligand production
+   REAL(wp), PUBLIC ::  prlgw    !: Photochemical of weak ligand
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_ligand( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_ligand  ***
+      !!
+      !! ** Purpose :   Compute remineralization/scavenging of organic ligands
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt ! ocean time step
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zlgwp, zlgwpr, zlgwr, zlablgw
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zligrem, zligpr, zligprod
+      CHARACTER (len=25) ::   charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_ligand')
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !
+               ! ------------------------------------------------------------------
+               ! Remineralization of iron ligands
+               ! ------------------------------------------------------------------
+               ! production from remineralisation of organic matter
+               zlgwp = orem(ji,jj,jk) * rlig
+               ! decay of weak ligand
+               ! This is based on the idea that as LGW is lower
+               ! there is a larger fraction of refractory OM
+               zlgwr = max( rlgs , rlgw * exp( -2 * (trb(ji,jj,jk,jplgw)*1e9) ) ) ! years
+               zlgwr = 1. / zlgwr * tgfunc(ji,jj,jk) * ( xstep / nyear_len(1) ) * blim(ji,jj,jk) * trb(ji,jj,jk,jplgw)
+               ! photochem loss of weak ligand
+               zlgwpr = prlgw * xstep * etot(ji,jj,jk) * trb(ji,jj,jk,jplgw) * (1. - fr_i(ji,jj))
+               tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + zlgwp - zlgwr - zlgwpr
+               zligrem(ji,jj,jk)   = zlgwr
+               zligpr(ji,jj,jk)    = zlgwpr
+               zligprod(ji,jj,jk)  = zlgwp
+               !
+            END DO
+         END DO
+      END DO
+      !
+      !  Output of some diagnostics variables
+      !     ---------------------------------
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+         IF( iom_use( "LIGREM" ) ) THEN
+           zligrem(:,:,jpk) = 0.  ; CALL iom_put( "LIGREM", zligrem(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( iom_use( "LIGPR" ) ) THEN
+           zligpr(:,:,jpk) = 0.   ; CALL iom_put( "LIGPR" , zligpr(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( iom_use( "LPRODR" ) ) THEN
+           zligprod(:,:,jpk) = 0. ; CALL iom_put( "LPRODR", zligprod(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('ligand1')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_ligand')
+      !
+   END SUBROUTINE p4z_ligand
+
+
+   SUBROUTINE p4z_ligand_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_ligand_init  ***
+      !!
+      !! ** Purpose :   Initialization of remineralization parameters
+      !!
+      !! ** Method  :   Read the nampislig namelist and check the parameters
+      !!
+      !! ** input   :   Namelist nampislig
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer 
+      !
+      NAMELIST/nampislig/ rlgw, prlgw, rlgs, rlig
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_ligand_init : remineralization/scavenging of organic ligands'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~'
+      ENDIF
+
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampislig, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampislig in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampislig, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampislig in configuration namelist' )
+      IF(lwm) WRITE ( numonp, nampislig )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : nampislig'
+         WRITE(numout,*) '      Lifetime (years) of weak ligands             rlgw  =', rlgw
+         WRITE(numout,*) '      Remin ligand production per unit C           rlig  =', rlig
+         WRITE(numout,*) '      Photolysis of weak ligand                    prlgw =', prlgw
+         WRITE(numout,*) '      Lifetime (years) of strong ligands           rlgs  =', rlgs
+      ENDIF
+      !
+   END SUBROUTINE p4z_ligand_init
+
+   !!======================================================================
+END MODULE p4zligand
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlim.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlim.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlim.F90	(revision 14097)
@@ -0,0 +1,320 @@
+MODULE p4zlim
+   !!======================================================================
+   !!                         ***  MODULE p4zlim  ***
+   !! TOP :   PISCES 
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-04  (O. Aumont, C. Ethe) Limitation for iron modelled in quota 
+   !!----------------------------------------------------------------------
+   !!   p4z_lim        :   Compute the nutrients limitation terms 
+   !!   p4z_lim_init   :   Read the namelist 
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Shared ocean-passive tracers variables
+   USE trc             ! Tracers defined
+   USE sms_pisces      ! PISCES variables
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC p4z_lim    
+   PUBLIC p4z_lim_init    
+   PUBLIC p4z_lim_alloc
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC ::  concnno3    !:  NO3, PO4 half saturation   
+   REAL(wp), PUBLIC ::  concdno3    !:  Phosphate half saturation for diatoms  
+   REAL(wp), PUBLIC ::  concnnh4    !:  NH4 half saturation for phyto  
+   REAL(wp), PUBLIC ::  concdnh4    !:  NH4 half saturation for diatoms
+   REAL(wp), PUBLIC ::  concnfer    !:  Iron half saturation for nanophyto 
+   REAL(wp), PUBLIC ::  concdfer    !:  Iron half saturation for diatoms  
+   REAL(wp), PUBLIC ::  concbno3    !:  NO3 half saturation  for bacteria 
+   REAL(wp), PUBLIC ::  concbnh4    !:  NH4 half saturation for bacteria
+   REAL(wp), PUBLIC ::  xsizedia    !:  Minimum size criteria for diatoms
+   REAL(wp), PUBLIC ::  xsizephy    !:  Minimum size criteria for nanophyto
+   REAL(wp), PUBLIC ::  xsizern     !:  Size ratio for nanophytoplankton
+   REAL(wp), PUBLIC ::  xsizerd     !:  Size ratio for diatoms
+   REAL(wp), PUBLIC ::  xksi1       !:  half saturation constant for Si uptake 
+   REAL(wp), PUBLIC ::  xksi2       !:  half saturation constant for Si/C 
+   REAL(wp), PUBLIC ::  xkdoc       !:  2nd half-sat. of DOC remineralization  
+   REAL(wp), PUBLIC ::  concbfe     !:  Fe half saturation for bacteria 
+   REAL(wp), PUBLIC ::  oxymin      !:  half saturation constant for anoxia
+   REAL(wp), PUBLIC ::  qnfelim     !:  optimal Fe quota for nanophyto
+   REAL(wp), PUBLIC ::  qdfelim     !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  caco3r      !:  mean rainratio 
+
+   !!* Phytoplankton limitation terms
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xnanono3   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xdiatno3   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xnanonh4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xdiatnh4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xnanopo4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xdiatpo4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimphy    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimdia    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimnfe    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimdfe    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimsi     !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimbac    !: ??
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimbacl   !: ??
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   concdfe    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   concnfe    !: ???
+
+   ! Coefficient for iron limitation
+   REAL(wp) ::  xcoef1   = 0.0016  / 55.85  
+   REAL(wp) ::  xcoef2   = 1.21E-5 * 14. / 55.85 / 7.625 * 0.5 * 1.5
+   REAL(wp) ::  xcoef3   = 1.15E-4 * 14. / 55.85 / 7.625 * 0.5 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_lim( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_lim  ***
+      !!
+      !! ** Purpose :   Compute the co-limitations by the various nutrients
+      !!              for the various phytoplankton species
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in)  :: kt, knt
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zlim1, zlim2, zlim3, zlim4, zno3, zferlim
+      REAL(wp) ::   zconcd, zconcd2, zconcn, zconcn2
+      REAL(wp) ::   z1_trbdia, z1_trbphy, ztem1, ztem2, zetot1, zetot2
+      REAL(wp) ::   zdenom, zratio, zironmin
+      REAL(wp) ::   zconc1d, zconc1dnh4, zconc0n, zconc0nnh4   
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_lim')
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               
+               ! Tuning of the iron concentration to a minimum level that is set to the detection limit
+               !-------------------------------------
+               zno3    = trb(ji,jj,jk,jpno3) / 40.e-6
+               zferlim = MAX( 3e-11 * zno3 * zno3, 5e-12 )
+               zferlim = MIN( zferlim, 7e-11 )
+               trb(ji,jj,jk,jpfer) = MAX( trb(ji,jj,jk,jpfer), zferlim )
+
+               ! Computation of a variable Ks for iron on diatoms taking into account
+               ! that increasing biomass is made of generally bigger cells
+               !------------------------------------------------
+               zconcd   = MAX( 0.e0 , trb(ji,jj,jk,jpdia) - xsizedia )
+               zconcd2  = trb(ji,jj,jk,jpdia) - zconcd
+               zconcn   = MAX( 0.e0 , trb(ji,jj,jk,jpphy) - xsizephy )
+               zconcn2  = trb(ji,jj,jk,jpphy) - zconcn
+               z1_trbphy   = 1. / ( trb(ji,jj,jk,jpphy) + rtrn )
+               z1_trbdia   = 1. / ( trb(ji,jj,jk,jpdia) + rtrn )
+
+               concdfe(ji,jj,jk) = MAX( concdfer, ( zconcd2 * concdfer + concdfer * xsizerd * zconcd ) * z1_trbdia )
+               zconc1d           = MAX( concdno3, ( zconcd2 * concdno3 + concdno3 * xsizerd * zconcd ) * z1_trbdia )
+               zconc1dnh4        = MAX( concdnh4, ( zconcd2 * concdnh4 + concdnh4 * xsizerd * zconcd ) * z1_trbdia )
+
+               concnfe(ji,jj,jk) = MAX( concnfer, ( zconcn2 * concnfer + concnfer * xsizern * zconcn ) * z1_trbphy )
+               zconc0n           = MAX( concnno3, ( zconcn2 * concnno3 + concnno3 * xsizern * zconcn ) * z1_trbphy )
+               zconc0nnh4        = MAX( concnnh4, ( zconcn2 * concnnh4 + concnnh4 * xsizern * zconcn ) * z1_trbphy )
+
+               ! Michaelis-Menten Limitation term for nutrients Small bacteria
+               ! -------------------------------------------------------------
+               zdenom = 1. /  ( concbno3 * concbnh4 + concbnh4 * trb(ji,jj,jk,jpno3) + concbno3 * trb(ji,jj,jk,jpnh4) )
+               xnanono3(ji,jj,jk) = trb(ji,jj,jk,jpno3) * concbnh4 * zdenom
+               xnanonh4(ji,jj,jk) = trb(ji,jj,jk,jpnh4) * concbno3 * zdenom
+               !
+               zlim1    = xnanono3(ji,jj,jk) + xnanonh4(ji,jj,jk)
+               zlim2    = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + concbnh4 )
+               zlim3    = trb(ji,jj,jk,jpfer) / ( concbfe + trb(ji,jj,jk,jpfer) )
+               zlim4    = trb(ji,jj,jk,jpdoc) / ( xkdoc   + trb(ji,jj,jk,jpdoc) )
+               xlimbacl(ji,jj,jk) = MIN( zlim1, zlim2, zlim3 )
+               xlimbac (ji,jj,jk) = MIN( zlim1, zlim2, zlim3 ) * zlim4
+
+               ! Michaelis-Menten Limitation term for nutrients Small flagellates
+               ! -----------------------------------------------
+               zdenom = 1. /  ( zconc0n * zconc0nnh4 + zconc0nnh4 * trb(ji,jj,jk,jpno3) + zconc0n * trb(ji,jj,jk,jpnh4) )
+               xnanono3(ji,jj,jk) = trb(ji,jj,jk,jpno3) * zconc0nnh4 * zdenom
+               xnanonh4(ji,jj,jk) = trb(ji,jj,jk,jpnh4) * zconc0n    * zdenom
+               !
+               zlim1    = xnanono3(ji,jj,jk) + xnanonh4(ji,jj,jk)
+               zlim2    = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + zconc0nnh4 )
+               zratio   = trb(ji,jj,jk,jpnfe) * z1_trbphy 
+               zironmin = xcoef1 * trb(ji,jj,jk,jpnch) * z1_trbphy + xcoef2 * zlim1 + xcoef3 * xnanono3(ji,jj,jk)
+               zlim3    = MAX( 0.,( zratio - zironmin ) / qnfelim )
+               xnanopo4(ji,jj,jk) = zlim2
+               xlimnfe (ji,jj,jk) = MIN( 1., zlim3 )
+               xlimphy (ji,jj,jk) = MIN( zlim1, zlim2, zlim3 )
+               !
+               !   Michaelis-Menten Limitation term for nutrients Diatoms
+               !   ----------------------------------------------
+               zdenom   = 1. / ( zconc1d * zconc1dnh4 + zconc1dnh4 * trb(ji,jj,jk,jpno3) + zconc1d * trb(ji,jj,jk,jpnh4) )
+               xdiatno3(ji,jj,jk) = trb(ji,jj,jk,jpno3) * zconc1dnh4 * zdenom
+               xdiatnh4(ji,jj,jk) = trb(ji,jj,jk,jpnh4) * zconc1d    * zdenom
+               !
+               zlim1    = xdiatno3(ji,jj,jk) + xdiatnh4(ji,jj,jk)
+               zlim2    = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + zconc1dnh4  )
+               zlim3    = trb(ji,jj,jk,jpsil) / ( trb(ji,jj,jk,jpsil) + xksi(ji,jj) )
+               zratio   = trb(ji,jj,jk,jpdfe) * z1_trbdia
+               zironmin = xcoef1 * trb(ji,jj,jk,jpdch) * z1_trbdia + xcoef2 * zlim1 + xcoef3 * xdiatno3(ji,jj,jk)
+               zlim4    = MAX( 0., ( zratio - zironmin ) / qdfelim )
+               xdiatpo4(ji,jj,jk) = zlim2
+               xlimdfe (ji,jj,jk) = MIN( 1., zlim4 )
+               xlimdia (ji,jj,jk) = MIN( zlim1, zlim2, zlim3, zlim4 )
+               xlimsi  (ji,jj,jk) = MIN( zlim1, zlim2, zlim4 )
+           END DO
+         END DO
+      END DO
+
+      ! Compute the fraction of nanophytoplankton that is made of calcifiers
+      ! --------------------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zlim1 =  ( trb(ji,jj,jk,jpno3) * concnnh4 + trb(ji,jj,jk,jpnh4) * concnno3 )    &
+                  &   / ( concnno3 * concnnh4 + concnnh4 * trb(ji,jj,jk,jpno3) + concnno3 * trb(ji,jj,jk,jpnh4) ) 
+               zlim2  = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + concnnh4 )
+               zlim3  = trb(ji,jj,jk,jpfer) / ( trb(ji,jj,jk,jpfer) +  5.E-11   )
+               ztem1  = MAX( 0., tsn(ji,jj,jk,jp_tem) )
+               ztem2  = tsn(ji,jj,jk,jp_tem) - 10.
+               zetot1 = MAX( 0., etot_ndcy(ji,jj,jk) - 1.) / ( 4. + etot_ndcy(ji,jj,jk) ) 
+               zetot2 = 30. / ( 30. + etot_ndcy(ji,jj,jk) ) 
+
+               xfracal(ji,jj,jk) = caco3r * MIN( zlim1, zlim2, zlim3 )                  &
+                  &                       * ztem1 / ( 0.1 + ztem1 )                     &
+                  &                       * MAX( 1., trb(ji,jj,jk,jpphy) * 1.e6 / 2. )  &
+                  &                       * zetot1 * zetot2               &
+                  &                       * ( 1. + EXP(-ztem2 * ztem2 / 25. ) )         &
+                  &                       * MIN( 1., 50. / ( hmld(ji,jj) + rtrn ) )
+               xfracal(ji,jj,jk) = MIN( 0.8 , xfracal(ji,jj,jk) )
+               xfracal(ji,jj,jk) = MAX( 0.02, xfracal(ji,jj,jk) )
+            END DO
+         END DO
+      END DO
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! denitrification factor computed from O2 levels
+               nitrfac(ji,jj,jk) = MAX(  0.e0, 0.4 * ( 6.e-6  - trb(ji,jj,jk,jpoxy) )    &
+                  &                                / ( oxymin + trb(ji,jj,jk,jpoxy) )  )
+               nitrfac(ji,jj,jk) = MIN( 1., nitrfac(ji,jj,jk) )
+               !
+               ! denitrification factor computed from NO3 levels
+               nitrfac2(ji,jj,jk) = MAX( 0.e0,       ( 1.E-6 - trb(ji,jj,jk,jpno3) )  &
+                  &                                / ( 1.E-6 + trb(ji,jj,jk,jpno3) ) )
+               nitrfac2(ji,jj,jk) = MIN( 1., nitrfac2(ji,jj,jk) )
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput .AND. knt == 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
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_lim')
+      !
+   END SUBROUTINE p4z_lim
+
+
+   SUBROUTINE p4z_lim_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_lim_init  ***
+      !!
+      !! ** Purpose :   Initialization of nutrient limitation parameters
+      !!
+      !! ** Method  :   Read the nampislim namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampislim
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/namp4zlim/ concnno3, concdno3, concnnh4, concdnh4, concnfer, concdfer, concbfe,   &
+         &                concbno3, concbnh4, xsizedia, xsizephy, xsizern, xsizerd,          & 
+         &                xksi1, xksi2, xkdoc, qnfelim, qdfelim, caco3r, oxymin
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_lim_init : initialization of nutrient limitations'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp4zlim, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namp4zlim in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp4zlim, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namp4zlim in configuration namelist' )
+      IF(lwm) WRITE( numonp, namp4zlim )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : namp4zlim'
+         WRITE(numout,*) '      mean rainratio                           caco3r    = ', caco3r
+         WRITE(numout,*) '      NO3 half saturation of nanophyto         concnno3  = ', concnno3
+         WRITE(numout,*) '      NO3 half saturation of diatoms           concdno3  = ', concdno3
+         WRITE(numout,*) '      NH4 half saturation for phyto            concnnh4  = ', concnnh4
+         WRITE(numout,*) '      NH4 half saturation for diatoms          concdnh4  = ', concdnh4
+         WRITE(numout,*) '      half saturation constant for Si uptake   xksi1     = ', xksi1
+         WRITE(numout,*) '      half saturation constant for Si/C        xksi2     = ', xksi2
+         WRITE(numout,*) '      half-sat. of DOC remineralization        xkdoc     = ', xkdoc
+         WRITE(numout,*) '      Iron half saturation for nanophyto       concnfer  = ', concnfer
+         WRITE(numout,*) '      Iron half saturation for diatoms         concdfer  = ', concdfer
+         WRITE(numout,*) '      size ratio for nanophytoplankton         xsizern   = ', xsizern
+         WRITE(numout,*) '      size ratio for diatoms                   xsizerd   = ', xsizerd
+         WRITE(numout,*) '      NO3 half saturation of bacteria          concbno3  = ', concbno3
+         WRITE(numout,*) '      NH4 half saturation for bacteria         concbnh4  = ', concbnh4
+         WRITE(numout,*) '      Minimum size criteria for diatoms        xsizedia  = ', xsizedia
+         WRITE(numout,*) '      Minimum size criteria for nanophyto      xsizephy  = ', xsizephy
+         WRITE(numout,*) '      Fe half saturation for bacteria          concbfe   = ', concbfe
+         WRITE(numout,*) '      halk saturation constant for anoxia       oxymin   =' , oxymin
+         WRITE(numout,*) '      optimal Fe quota for nano.               qnfelim   = ', qnfelim
+         WRITE(numout,*) '      Optimal Fe quota for diatoms             qdfelim   = ', qdfelim
+      ENDIF
+      !
+      nitrfac (:,:,jpk) = 0._wp
+      nitrfac2(:,:,jpk) = 0._wp
+      xfracal (:,:,jpk) = 0._wp
+      xlimphy (:,:,jpk) = 0._wp
+      xlimdia (:,:,jpk) = 0._wp
+      xlimnfe (:,:,jpk) = 0._wp
+      xlimdfe (:,:,jpk) = 0._wp
+      !
+   END SUBROUTINE p4z_lim_init
+
+
+   INTEGER FUNCTION p4z_lim_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_lim_alloc  ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp , ONLY: ctl_stop
+      !!----------------------------------------------------------------------
+
+      !*  Biological arrays for phytoplankton growth
+      ALLOCATE( xnanono3(jpi,jpj,jpk), xdiatno3(jpi,jpj,jpk),       &
+         &      xnanonh4(jpi,jpj,jpk), xdiatnh4(jpi,jpj,jpk),       &
+         &      xnanopo4(jpi,jpj,jpk), xdiatpo4(jpi,jpj,jpk),       &
+         &      xlimphy (jpi,jpj,jpk), xlimdia (jpi,jpj,jpk),       &
+         &      xlimnfe (jpi,jpj,jpk), xlimdfe (jpi,jpj,jpk),       &
+         &      xlimbac (jpi,jpj,jpk), xlimbacl(jpi,jpj,jpk),       &
+         &      concnfe (jpi,jpj,jpk), concdfe (jpi,jpj,jpk),       &
+         &      xlimsi  (jpi,jpj,jpk), STAT=p4z_lim_alloc )
+      !
+      IF( p4z_lim_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p4z_lim_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p4z_lim_alloc
+
+   !!======================================================================
+END MODULE p4zlim
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlys.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlys.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zlys.F90	(revision 14097)
@@ -0,0 +1,189 @@
+MODULE p4zlys
+   !!======================================================================
+   !!                         ***  MODULE p4zlys  ***
+   !! TOP :   PISCES 
+   !!======================================================================
+   !! History :    -   !  1988-07  (E. MAIER-REIMER) Original code
+   !!              -   !  1998     (O. Aumont) additions
+   !!              -   !  1999     (C. Le Quere) modifications
+   !!             1.0  !  2004     (O. Aumont) modifications
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!                  !  2011-02  (J. Simeon, J. Orr)  Calcon salinity dependence
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Improvment of calcite dissolution
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p4z_lys        :   Compute the CaCO3 dissolution 
+   !!   p4z_lys_init   :   Read the namelist parameters
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zche          !  Chemical model
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_lys         ! called in trcsms_pisces.F90
+   PUBLIC   p4z_lys_init    ! called in trcsms_pisces.F90
+
+   REAL(wp), PUBLIC ::   kdca   !: diss. rate constant calcite
+   REAL(wp), PUBLIC ::   nca    !: order of reaction for calcite dissolution
+
+   INTEGER  ::   rmtss              ! number of seconds per month 
+   REAL(wp) ::   calcon = 1.03E-2   ! mean calcite concentration [Ca2+] in sea water [mole/kg solution]
+ 
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE p4z_lys( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_lys  ***
+      !!
+      !! ** Purpose :   CALCULATES DEGREE OF CACO3 SATURATION IN THE WATER
+      !!                COLUMN, DISSOLUTION/PRECIPITATION OF CACO3 AND LOSS
+      !!                OF CACO3 TO THE CACO3 SEDIMENT POOL.
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   ! ocean time step and ???
+      !
+      INTEGER  ::   ji, jj, jk, jn
+      REAL(wp) ::   zdispot, zfact, zcalcon
+      REAL(wp) ::   zomegaca, zexcess, zexcess0
+      CHARACTER (len=25) ::   charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zco3, zcaldiss, zhinit, zhi, zco3sat
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('p4z_lys')
+      !
+      zhinit  (:,:,:) = hi(:,:,:) * 1000. / ( rhop(:,:,:) + rtrn )
+      !
+      !     -------------------------------------------
+      !     COMPUTE [CO3--] and [H+] CONCENTRATIONS
+      !     -------------------------------------------
+
+      CALL solve_at_general( zhinit, zhi )
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zco3(ji,jj,jk) = trb(ji,jj,jk,jpdic) * ak13(ji,jj,jk) * ak23(ji,jj,jk) / (zhi(ji,jj,jk)**2   &
+                  &             + ak13(ji,jj,jk) * zhi(ji,jj,jk) + ak13(ji,jj,jk) * ak23(ji,jj,jk) + rtrn )
+               hi  (ji,jj,jk) = zhi(ji,jj,jk) * rhop(ji,jj,jk) / 1000.
+            END DO
+         END DO
+      END DO
+
+      !     ---------------------------------------------------------
+      !        CALCULATE DEGREE OF CACO3 SATURATION AND CORRESPONDING
+      !        DISSOLOUTION AND PRECIPITATION OF CACO3 (BE AWARE OF
+      !        MGCO3)
+      !     ---------------------------------------------------------
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+               ! DEVIATION OF [CO3--] FROM SATURATION VALUE
+               ! Salinity dependance in zomegaca and divide by rhop/1000 to have good units
+               zcalcon  = calcon * ( salinprac(ji,jj,jk) / 35._wp )
+               zfact    = rhop(ji,jj,jk) / 1000._wp
+               zomegaca = ( zcalcon * zco3(ji,jj,jk) ) / ( aksp(ji,jj,jk) * zfact + rtrn )
+               zco3sat(ji,jj,jk) = aksp(ji,jj,jk) * zfact / ( zcalcon + rtrn )
+
+               ! SET DEGREE OF UNDER-/SUPERSATURATION
+               excess(ji,jj,jk) = 1._wp - zomegaca
+               zexcess0 = MAX( 0., excess(ji,jj,jk) )
+               zexcess  = zexcess0**nca
+
+               ! AMOUNT CACO3 (12C) THAT RE-ENTERS SOLUTION
+               !       (ACCORDING TO THIS FORMULATION ALSO SOME PARTICULATE
+               !       CACO3 GETS DISSOLVED EVEN IN THE CASE OF OVERSATURATION)
+               zdispot = kdca * zexcess * trb(ji,jj,jk,jpcal)
+              !  CHANGE OF [CO3--] , [ALK], PARTICULATE [CACO3],
+              !       AND [SUM(CO2)] DUE TO CACO3 DISSOLUTION/PRECIPITATION
+              zcaldiss(ji,jj,jk)  = zdispot * rfact2 / rmtss ! calcite dissolution
+              !
+              tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + 2. * zcaldiss(ji,jj,jk)
+              tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) -      zcaldiss(ji,jj,jk)
+              tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) +      zcaldiss(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+         CALL iom_put( "PH"  , -1. * LOG10( MAX( hi(:,:,:), rtrn ) ) * tmask(:,:,:) )
+         IF( iom_use( "CO3" ) ) THEN
+            zco3(:,:,jpk) = 0.    ; CALL iom_put( "CO3"   , zco3(:,:,:)     * 1.e+3           * tmask(:,:,:) )
+         ENDIF
+         IF( iom_use( "CO3sat" ) ) THEN
+           zco3sat(:,:,jpk) = 0.  ; CALL iom_put( "CO3sat", zco3sat(:,:,:)  * 1.e+3           * tmask(:,:,:) )
+         ENDIF
+         IF( iom_use( "DCAL" ) ) THEN
+           zcaldiss(:,:,jpk) = 0. ; CALL iom_put( "DCAL"  , zcaldiss(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+        WRITE(charout, FMT="('lys ')")
+        CALL prt_ctl_trc_info(charout)
+        CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_lys')
+      !
+   END SUBROUTINE p4z_lys
+
+
+   SUBROUTINE p4z_lys_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_lys_init  ***
+      !!
+      !! ** Purpose :   Initialization of CaCO3 dissolution parameters
+      !!
+      !! ** Method  :   Read the nampiscal namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampiscal
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/nampiscal/ kdca, nca
+      !!----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_lys_init : initialization of CaCO3 dissolution'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampiscal, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampiscal in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampiscal, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampiscal in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampiscal )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : nampiscal'
+         WRITE(numout,*) '      diss. rate constant calcite (per month)        kdca =', kdca
+         WRITE(numout,*) '      order of reaction for calcite dissolution      nca  =', nca
+      ENDIF
+      !
+      ! Number of seconds per month 
+      rmtss =  nyear_len(1) * rday / raamo
+      !
+   END SUBROUTINE p4z_lys_init
+
+   !!======================================================================
+END MODULE p4zlys
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmeso.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmeso.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmeso.F90	(revision 14097)
@@ -0,0 +1,316 @@
+MODULE p4zmeso
+   !!======================================================================
+   !!                         ***  MODULE p4zmeso  ***
+   !! TOP :   PISCES Compute the sources/sinks for mesozooplankton
+   !!======================================================================
+   !! History :   1.0  !  2002     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!----------------------------------------------------------------------
+   !!   p4z_meso       : Compute the sources/sinks for mesozooplankton
+   !!   p4z_meso_init  : Initialization of the parameters for mesozooplankton
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zprod         ! production
+   USE prtctl_trc      ! print control for debugging
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_meso              ! called in p4zbio.F90
+   PUBLIC   p4z_meso_init         ! called in trcsms_pisces.F90
+
+   REAL(wp), PUBLIC ::  part2        !: part of calcite not dissolved in mesozoo guts
+   REAL(wp), PUBLIC ::  xpref2d      !: mesozoo preference for diatoms
+   REAL(wp), PUBLIC ::  xpref2n      !: mesozoo preference for nanophyto
+   REAL(wp), PUBLIC ::  xpref2z      !: mesozoo preference for microzooplankton
+   REAL(wp), PUBLIC ::  xpref2c      !: mesozoo preference for POC 
+   REAL(wp), PUBLIC ::  xthresh2zoo  !: zoo feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2dia  !: diatoms feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2phy  !: nanophyto feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2poc  !: poc feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2     !: feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  resrat2      !: exsudation rate of mesozooplankton
+   REAL(wp), PUBLIC ::  mzrat2       !: microzooplankton mortality rate 
+   REAL(wp), PUBLIC ::  grazrat2     !: maximal mesozoo grazing rate
+   REAL(wp), PUBLIC ::  xkgraz2      !: non assimilated fraction of P by mesozoo 
+   REAL(wp), PUBLIC ::  unass2       !: Efficicency of mesozoo growth 
+   REAL(wp), PUBLIC ::  sigma2       !: Fraction of mesozoo excretion as DOM 
+   REAL(wp), PUBLIC ::  epsher2      !: growth efficiency
+   REAL(wp), PUBLIC ::  epsher2min   !: minimum growth efficiency at high food for grazing 2
+   REAL(wp), PUBLIC ::  grazflux     !: mesozoo flux feeding rate
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_meso( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_meso  ***
+      !!
+      !! ** Purpose :   Compute the sources/sinks for mesozooplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   ! ocean time step and ???
+      !
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompadi, zcompaph, zcompapoc, zcompaz, zcompam
+      REAL(wp) :: zgraze2 , zdenom, zdenom2
+      REAL(wp) :: zfact   , zfood, zfoodlim, zproport, zbeta
+      REAL(wp) :: zmortzgoc, zfrac, zfracfe, zratio, zratio2, zfracal, zgrazcal
+      REAL(wp) :: zepsherf, zepshert, zepsherv, zepsherq 
+      REAL(wp) :: zgrarsig, zgraztotc, zgraztotn, zgraztotf
+      REAL(wp) :: zgrarem2, zgrafer2, zgrapoc2, zprcaca, zmortz, zgrasrat, zgrasratn
+      REAL(wp) :: zrespz, ztortz, zgrazd, zgrazz, zgrazpof
+      REAL(wp) :: zgrazn, zgrazpoc, zgraznf, zgrazf
+      REAL(wp) :: zgrazfffp, zgrazfffg, zgrazffep, zgrazffeg
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zgrazing2, zfezoo2, zz2ligprod
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_meso')
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompam   = MAX( ( trb(ji,jj,jk,jpmes) - 1.e-9 ), 0.e0 )
+               zfact     = xstep * tgfunc2(ji,jj,jk) * zcompam
+
+               !  Respiration rates of both zooplankton
+               !  -------------------------------------
+               zrespz    = resrat2 * zfact * ( trb(ji,jj,jk,jpmes) / ( xkmort + trb(ji,jj,jk,jpmes) )  &
+               &           + 3. * nitrfac(ji,jj,jk) )
+
+               !  Zooplankton mortality. A square function has been selected with
+               !  no real reason except that it seems to be more stable and may mimic predation
+               !  ---------------------------------------------------------------
+               ztortz    = mzrat2 * 1.e6 * zfact * trb(ji,jj,jk,jpmes)  * (1. - nitrfac(ji,jj,jk) )
+               !
+               zcompadi  = MAX( ( trb(ji,jj,jk,jpdia) - xthresh2dia ), 0.e0 )
+               zcompaz   = MAX( ( trb(ji,jj,jk,jpzoo) - xthresh2zoo ), 0.e0 )
+               zcompapoc = MAX( ( trb(ji,jj,jk,jppoc) - xthresh2poc ), 0.e0 )
+               ! Size effect of nanophytoplankton on grazing : the smaller it is, the less prone
+               ! it is to predation by mesozooplankton
+               ! -------------------------------------------------------------------------------
+               zcompaph  = MAX( ( trb(ji,jj,jk,jpphy) - xthresh2phy ), 0.e0 ) &
+                  &      * MIN(1., MAX( 0., ( quotan(ji,jj,jk) - 0.2) / 0.3 ) )
+
+               !   Mesozooplankton grazing
+               !   ------------------------
+               zfood     = xpref2d * zcompadi + xpref2z * zcompaz + xpref2n * zcompaph + xpref2c * zcompapoc 
+               zfoodlim  = MAX( 0., zfood - MIN( 0.5 * zfood, xthresh2 ) )
+               zdenom    = zfoodlim / ( xkgraz2 + zfoodlim )
+               zdenom2   = zdenom / ( zfood + rtrn )
+               zgraze2   = grazrat2 * xstep * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpmes) * (1. - nitrfac(ji,jj,jk)) 
+
+               zgrazd    = zgraze2  * xpref2d  * zcompadi  * zdenom2 
+               zgrazz    = zgraze2  * xpref2z  * zcompaz   * zdenom2 
+               zgrazn    = zgraze2  * xpref2n  * zcompaph  * zdenom2 
+               zgrazpoc  = zgraze2  * xpref2c  * zcompapoc * zdenom2 
+
+               zgraznf   = zgrazn   * trb(ji,jj,jk,jpnfe) / ( trb(ji,jj,jk,jpphy) + rtrn)
+               zgrazf    = zgrazd   * trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazpof  = zgrazpoc * trb(ji,jj,jk,jpsfe) / ( trb(ji,jj,jk,jppoc) + rtrn)
+
+               !  Mesozooplankton flux feeding on GOC
+               !  ----------------------------------
+               zgrazffeg = grazflux  * xstep * wsbio4(ji,jj,jk)      &
+               &           * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpgoc) * trb(ji,jj,jk,jpmes) &
+               &           * (1. - nitrfac(ji,jj,jk))
+               zgrazfffg = zgrazffeg * trb(ji,jj,jk,jpbfe) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zgrazffep = grazflux  * xstep *  wsbio3(ji,jj,jk)     &
+               &           * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jpmes) &
+               &           * (1. - nitrfac(ji,jj,jk))
+               zgrazfffp = zgrazffep * trb(ji,jj,jk,jpsfe) / (trb(ji,jj,jk,jppoc) + rtrn)
+               !
+               zgraztotc = zgrazd + zgrazz + zgrazn + zgrazpoc + zgrazffep + zgrazffeg
+               ! Compute the proportion of filter feeders
+               zproport  = (zgrazffep + zgrazffeg)/(rtrn + zgraztotc)
+               ! Compute fractionation of aggregates. It is assumed that 
+               ! diatoms based aggregates are more prone to fractionation
+               ! since they are more porous (marine snow instead of fecal pellets)
+               zratio    = trb(ji,jj,jk,jpgsi) / ( trb(ji,jj,jk,jpgoc) + rtrn )
+               zratio2   = zratio * zratio
+               zfrac     = zproport * grazflux  * xstep * wsbio4(ji,jj,jk)      &
+               &          * trb(ji,jj,jk,jpgoc) * trb(ji,jj,jk,jpmes)          &
+               &          * ( 0.2 + 3.8 * zratio2 / ( 1.**2 + zratio2 ) )
+               zfracfe   = zfrac * trb(ji,jj,jk,jpbfe) / (trb(ji,jj,jk,jpgoc) + rtrn)
+
+               zgrazffep = zproport * zgrazffep
+               zgrazffeg = zproport * zgrazffeg
+               zgrazfffp = zproport * zgrazfffp
+               zgrazfffg = zproport * zgrazfffg
+               zgraztotc = zgrazd + zgrazz + zgrazn + zgrazpoc + zgrazffep + zgrazffeg
+               zgraztotn = zgrazd * quotad(ji,jj,jk) + zgrazz + zgrazn * quotan(ji,jj,jk)   &
+               &   + zgrazpoc + zgrazffep + zgrazffeg
+               zgraztotf = zgrazf + zgraznf + zgrazz * ferat3 + zgrazpof + zgrazfffp + zgrazfffg
+
+               ! Total grazing ( grazing by microzoo is already computed in p4zmicro )
+               zgrazing2(ji,jj,jk) = zgraztotc
+
+               ! Mesozooplankton efficiency. 
+               ! We adopt a formulation proposed by Mitra et al. (2007)
+               ! The gross growth efficiency is controled by the most limiting nutrient.
+               ! Growth is also further decreased when the food quality is poor. This is currently
+               ! hard coded : it can be decreased by up to 50% (zepsherq)
+               ! GGE can also be decreased when food quantity is high, zepsherf (Montagnes and 
+               ! Fulton, 2012)
+               ! -----------------------------------------------------------------------------------
+               zgrasrat  =  ( zgraztotf + rtrn )/ ( zgraztotc + rtrn )
+               zgrasratn =  ( zgraztotn + rtrn )/ ( zgraztotc + rtrn )
+               zepshert  = MIN( 1., zgrasratn, zgrasrat / ferat3)
+               zbeta     = MAX(0., (epsher2 - epsher2min) )
+               zepsherf  = epsher2min + zbeta / ( 1.0 + 0.04E6 * 12. * zfood * zbeta ) 
+               zepsherq  = 0.5 + (1.0 - 0.5) * zepshert * ( 1.0 + 1.0 ) / ( zepshert + 1.0 )
+               zepsherv  = zepsherf * zepshert * zepsherq 
+
+               zgrarem2  = zgraztotc * ( 1. - zepsherv - unass2 ) &
+               &         + ( 1. - epsher2 - unass2 ) / ( 1. - epsher2 ) * ztortz
+               zgrafer2  = zgraztotc * MAX( 0. , ( 1. - unass2 ) * zgrasrat - ferat3 * zepsherv )    &
+               &         + ferat3 * ( ( 1. - epsher2 - unass2 ) /( 1. - epsher2 ) * ztortz )
+               zgrapoc2  = zgraztotc * unass2
+
+               !   Update the arrays TRA which contain the biological sources and sinks
+               zgrarsig  = zgrarem2 * sigma2
+               tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zgrarsig
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zgrarsig
+               tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zgrarem2 - zgrarsig
+               !
+               IF( ln_ligand ) THEN 
+                  tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + (zgrarem2 - zgrarsig) * ldocz
+                  zz2ligprod(ji,jj,jk) = (zgrarem2 - zgrarsig) * ldocz
+               ENDIF
+               !
+               tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - o2ut * zgrarsig
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zgrafer2
+               zfezoo2(ji,jj,jk)   = zgrafer2
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrarsig
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * zgrarsig              
+
+               zmortz = ztortz + zrespz
+               zmortzgoc = unass2 / ( 1. - epsher2 ) * ztortz + zrespz
+               tra(ji,jj,jk,jpmes) = tra(ji,jj,jk,jpmes) - zmortz + zepsherv * zgraztotc 
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zgrazd
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) - zgrazz
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zgrazn
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zgrazn * trb(ji,jj,jk,jpnch) / ( trb(ji,jj,jk,jpphy) + rtrn )
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zgrazd * trb(ji,jj,jk,jpdch) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zgrazd * trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zgrazd * trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zgraznf
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zgrazf
+
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zgrazpoc - zgrazffep + zfrac
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + zfrac
+               conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zgrazpoc - zgrazffep
+               tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zmortzgoc - zgrazffeg + zgrapoc2 - zfrac
+               prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zmortzgoc + zgrapoc2
+               consgoc(ji,jj,jk) = consgoc(ji,jj,jk) - zgrazffeg - zfrac
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zgrazpof - zgrazfffp + zfracfe
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + ferat3 * zmortzgoc - zgrazfffg     &
+                 &                + zgraztotf * unass2 - zfracfe
+               zfracal = trb(ji,jj,jk,jpcal) / (trb(ji,jj,jk,jppoc) + trb(ji,jj,jk,jpgoc) + rtrn )
+               zgrazcal = (zgrazffeg + zgrazpoc) * (1. - part2) * zfracal
+               ! calcite production
+               zprcaca = xfracal(ji,jj,jk) * zgrazn
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               !
+               zprcaca = part2 * zprcaca
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrazcal - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2. * ( zgrazcal + zprcaca )
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) - zgrazcal + zprcaca
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+         CALL iom_put( "PCAL"  , prodcal(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) )  !  Calcite production 
+         IF( iom_use("GRAZ2") ) THEN  !   Total grazing of phyto by zooplankton
+           zgrazing2(:,:,jpk) = 0._wp ;  CALL iom_put( "GRAZ2" , zgrazing2(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) ) 
+         ENDIF
+         IF( iom_use("FEZOO2") ) THEN  
+           zfezoo2 (:,:,jpk) = 0._wp ; CALL iom_put( "FEZOO2", zfezoo2(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( ln_ligand ) THEN
+            zz2ligprod(:,:,jpk) = 0._wp ; CALL iom_put( "LPRODZ2", zz2ligprod(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:)  )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+        WRITE(charout, FMT="('meso')")
+        CALL prt_ctl_trc_info(charout)
+        CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_meso')
+      !
+   END SUBROUTINE p4z_meso
+
+
+   SUBROUTINE p4z_meso_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_meso_init  ***
+      !!
+      !! ** Purpose :   Initialization of mesozooplankton parameters
+      !!
+      !! ** Method  :   Read the nampismes namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampismes
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/namp4zmes/ part2, grazrat2, resrat2, mzrat2, xpref2n, xpref2d, xpref2z,   &
+         &                xpref2c, xthresh2dia, xthresh2phy, xthresh2zoo, xthresh2poc, &
+         &                xthresh2, xkgraz2, epsher2, epsher2min, sigma2, unass2, grazflux
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) 'p4z_meso_init : Initialization of mesozooplankton parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp4zmes, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namp4zmes in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp4zmes, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namp4zmes in configuration namelist' )
+      IF(lwm) WRITE( numonp, namp4zmes )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : namp4zmes'
+         WRITE(numout,*) '      part of calcite not dissolved in mesozoo guts  part2        =', part2
+         WRITE(numout,*) '      mesozoo preference for phyto                   xpref2n      =', xpref2n
+         WRITE(numout,*) '      mesozoo preference for diatoms                 xpref2d      =', xpref2d
+         WRITE(numout,*) '      mesozoo preference for zoo                     xpref2z      =', xpref2z
+         WRITE(numout,*) '      mesozoo preference for poc                     xpref2c      =', xpref2c
+         WRITE(numout,*) '      microzoo feeding threshold  for mesozoo        xthresh2zoo  =', xthresh2zoo
+         WRITE(numout,*) '      diatoms feeding threshold  for mesozoo         xthresh2dia  =', xthresh2dia
+         WRITE(numout,*) '      nanophyto feeding threshold for mesozoo        xthresh2phy  =', xthresh2phy
+         WRITE(numout,*) '      poc feeding threshold for mesozoo              xthresh2poc  =', xthresh2poc
+         WRITE(numout,*) '      feeding threshold for mesozooplankton          xthresh2     =', xthresh2
+         WRITE(numout,*) '      exsudation rate of mesozooplankton             resrat2      =', resrat2
+         WRITE(numout,*) '      mesozooplankton mortality rate                 mzrat2       =', mzrat2
+         WRITE(numout,*) '      maximal mesozoo grazing rate                   grazrat2     =', grazrat2
+         WRITE(numout,*) '      mesozoo flux feeding rate                      grazflux     =', grazflux
+         WRITE(numout,*) '      non assimilated fraction of P by mesozoo       unass2       =', unass2
+         WRITE(numout,*) '      Efficiency of Mesozoo growth                   epsher2      =', epsher2
+         WRITE(numout,*) '      Minimum Efficiency of Mesozoo growth           epsher2min  =', epsher2min
+         WRITE(numout,*) '      Fraction of mesozoo excretion as DOM           sigma2       =', sigma2
+         WRITE(numout,*) '      half sturation constant for grazing 2          xkgraz2      =', xkgraz2
+      ENDIF
+      !
+   END SUBROUTINE p4z_meso_init
+
+   !!======================================================================
+END MODULE p4zmeso
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmicro.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmicro.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmicro.F90	(revision 14097)
@@ -0,0 +1,270 @@
+MODULE p4zmicro
+   !!======================================================================
+   !!                         ***  MODULE p4zmicro  ***
+   !! TOP :   PISCES Compute the sources/sinks for microzooplankton
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!----------------------------------------------------------------------
+   !!   p4z_micro      : Compute the sources/sinks for microzooplankton
+   !!   p4z_micro_init : Initialize and read the appropriate namelist
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zlim          ! Co-limitations
+   USE p4zprod         ! production
+   USE iom             ! I/O manager
+   USE prtctl_trc      ! print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_micro         ! called in p4zbio.F90
+   PUBLIC   p4z_micro_init    ! called in trcsms_pisces.F90
+
+   REAL(wp), PUBLIC ::   part        !: part of calcite not dissolved in microzoo guts
+   REAL(wp), PUBLIC ::   xprefc      !: microzoo preference for POC 
+   REAL(wp), PUBLIC ::   xprefn      !: microzoo preference for nanophyto
+   REAL(wp), PUBLIC ::   xprefd      !: microzoo preference for diatoms
+   REAL(wp), PUBLIC ::   xthreshdia  !: diatoms feeding threshold for microzooplankton 
+   REAL(wp), PUBLIC ::   xthreshphy  !: nanophyto threshold for microzooplankton 
+   REAL(wp), PUBLIC ::   xthreshpoc  !: poc threshold for microzooplankton 
+   REAL(wp), PUBLIC ::   xthresh     !: feeding threshold for microzooplankton 
+   REAL(wp), PUBLIC ::   resrat      !: exsudation rate of microzooplankton
+   REAL(wp), PUBLIC ::   mzrat       !: microzooplankton mortality rate 
+   REAL(wp), PUBLIC ::   grazrat     !: maximal microzoo grazing rate
+   REAL(wp), PUBLIC ::   xkgraz      !: Half-saturation constant of assimilation
+   REAL(wp), PUBLIC ::   unass       !: Non-assimilated part of food
+   REAL(wp), PUBLIC ::   sigma1      !: Fraction of microzoo excretion as DOM 
+   REAL(wp), PUBLIC ::   epsher      !: growth efficiency for grazing 1 
+   REAL(wp), PUBLIC ::   epshermin   !: minimum growth efficiency for grazing 1
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_micro( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_micro  ***
+      !!
+      !! ** Purpose :   Compute the sources/sinks for microzooplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt    ! ocean time step
+      INTEGER, INTENT(in) ::   knt   ! ??? 
+      !
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompadi, zcompaz , zcompaph, zcompapoc
+      REAL(wp) :: zgraze  , zdenom, zdenom2
+      REAL(wp) :: zfact   , zfood, zfoodlim, zbeta
+      REAL(wp) :: zepsherf, zepshert, zepsherv, zepsherq
+      REAL(wp) :: zgrarsig, zgraztotc, zgraztotn, zgraztotf
+      REAL(wp) :: zgrarem, zgrafer, zgrapoc, zprcaca, zmortz
+      REAL(wp) :: zrespz, ztortz, zgrasrat, zgrasratn
+      REAL(wp) :: zgrazp, zgrazm, zgrazsd
+      REAL(wp) :: zgrazmf, zgrazsf, zgrazpf
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zgrazing, zfezoo, zzligprod
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_micro')
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompaz = MAX( ( trb(ji,jj,jk,jpzoo) - 1.e-9 ), 0.e0 )
+               zfact   = xstep * tgfunc2(ji,jj,jk) * zcompaz
+
+               !  Respiration rates of both zooplankton
+               !  -------------------------------------
+               zrespz = resrat * zfact * trb(ji,jj,jk,jpzoo) / ( xkmort + trb(ji,jj,jk,jpzoo) )  &
+                  &   + resrat * zfact * 3. * nitrfac(ji,jj,jk)
+
+               !  Zooplankton mortality. A square function has been selected with
+               !  no real reason except that it seems to be more stable and may mimic predation.
+               !  ---------------------------------------------------------------
+               ztortz = mzrat * 1.e6 * zfact * trb(ji,jj,jk,jpzoo) * (1. - nitrfac(ji,jj,jk))
+
+               zcompadi  = MIN( MAX( ( trb(ji,jj,jk,jpdia) - xthreshdia ), 0.e0 ), xsizedia )
+               zcompaph  = MAX( ( trb(ji,jj,jk,jpphy) - xthreshphy ), 0.e0 )
+               zcompapoc = MAX( ( trb(ji,jj,jk,jppoc) - xthreshpoc ), 0.e0 )
+               
+               !     Microzooplankton grazing
+               !     ------------------------
+               zfood     = xprefn * zcompaph + xprefc * zcompapoc + xprefd * zcompadi
+               zfoodlim  = MAX( 0. , zfood - min(xthresh,0.5*zfood) )
+               zdenom    = zfoodlim / ( xkgraz + zfoodlim )
+               zdenom2   = zdenom / ( zfood + rtrn )
+               zgraze    = grazrat * xstep * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpzoo) * (1. - nitrfac(ji,jj,jk))
+
+               zgrazp    = zgraze  * xprefn * zcompaph  * zdenom2 
+               zgrazm    = zgraze  * xprefc * zcompapoc * zdenom2 
+               zgrazsd   = zgraze  * xprefd * zcompadi  * zdenom2 
+
+               zgrazpf   = zgrazp  * trb(ji,jj,jk,jpnfe) / (trb(ji,jj,jk,jpphy) + rtrn)
+               zgrazmf   = zgrazm  * trb(ji,jj,jk,jpsfe) / (trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazsf   = zgrazsd * trb(ji,jj,jk,jpdfe) / (trb(ji,jj,jk,jpdia) + rtrn)
+               !
+               zgraztotc = zgrazp  + zgrazm  + zgrazsd 
+               zgraztotf = zgrazpf + zgrazsf + zgrazmf 
+               zgraztotn = zgrazp * quotan(ji,jj,jk) + zgrazm + zgrazsd * quotad(ji,jj,jk)
+
+               ! Grazing by microzooplankton
+               zgrazing(ji,jj,jk) = zgraztotc
+
+               ! Microzooplankton efficiency. 
+               ! We adopt a formulation proposed by Mitra et al. (2007)
+               ! The gross growth efficiency is controled by the most limiting nutrient.
+               ! Growth is also further decreased when the food quality is poor. This is currently
+               ! hard coded : it can be decreased by up to 50% (zepsherq)
+               ! GGE can also be decreased when food quantity is high, zepsherf (Montagnes and 
+               ! Fulton, 2012)
+               ! -----------------------------------------------------------------------------
+               zgrasrat  = ( zgraztotf + rtrn ) / ( zgraztotc + rtrn )
+               zgrasratn = ( zgraztotn + rtrn ) / ( zgraztotc + rtrn )
+               zepshert  =  MIN( 1., zgrasratn, zgrasrat / ferat3)
+               zbeta     = MAX(0., (epsher - epshermin) )
+               zepsherf  = epshermin + zbeta / ( 1.0 + 0.04E6 * 12. * zfood * zbeta )
+               zepsherq  = 0.5 + (1.0 - 0.5) * zepshert * ( 1.0 + 1.0 ) / ( zepshert + 1.0 )
+               zepsherv  = zepsherf * zepshert * zepsherq 
+
+               zgrafer   = zgraztotc * MAX( 0. , ( 1. - unass ) * zgrasrat - ferat3 * zepsherv ) 
+               zgrarem   = zgraztotc * ( 1. - zepsherv - unass )
+               zgrapoc   = zgraztotc * unass
+
+               !  Update of the TRA arrays
+               !  ------------------------
+               zgrarsig  = zgrarem * sigma1
+               tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zgrarsig
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zgrarsig
+               tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zgrarem - zgrarsig
+               !
+               IF( ln_ligand ) THEN
+                  tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + (zgrarem - zgrarsig) * ldocz
+                  zzligprod(ji,jj,jk) = (zgrarem - zgrarsig) * ldocz
+               ENDIF
+               !
+               tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - o2ut * zgrarsig
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zgrafer
+               zfezoo(ji,jj,jk)    = zgrafer
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zgrapoc
+               prodpoc(ji,jj,jk)   = prodpoc(ji,jj,jk) + zgrapoc
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zgraztotf * unass
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrarsig
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * zgrarsig
+               !   Update the arrays TRA which contain the biological sources and sinks
+               !   --------------------------------------------------------------------
+               zmortz = ztortz + zrespz
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) - zmortz + zepsherv * zgraztotc 
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zgrazp
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zgrazsd
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zgrazp  * trb(ji,jj,jk,jpnch)/(trb(ji,jj,jk,jpphy)+rtrn)
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zgrazsd * trb(ji,jj,jk,jpdch)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zgrazsd * trb(ji,jj,jk,jpdsi)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zgrazsd * trb(ji,jj,jk,jpdsi)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zgrazpf
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zgrazsf
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zmortz - zgrazm
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + zmortz
+               conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zgrazm
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + ferat3 * zmortz - zgrazmf
+               !
+               ! calcite production
+               zprcaca = xfracal(ji,jj,jk) * zgrazp
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               !
+               zprcaca = part * zprcaca
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2. * zprcaca
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) + zprcaca
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+       IF( iom_use("GRAZ1") ) THEN  !   Total grazing of phyto by zooplankton
+           zgrazing(:,:,jpk) = 0._wp   ; CALL iom_put( "GRAZ1" , zgrazing(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) ) 
+         ENDIF
+         IF( iom_use("FEZOO") ) THEN  
+           zfezoo (:,:,jpk) = 0._wp    ; CALL iom_put( "FEZOO" , zfezoo(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( ln_ligand ) THEN
+            zzligprod(:,:,jpk) = 0._wp ; CALL iom_put( "LPRODZ", zzligprod(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:))
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl) THEN      ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('micro')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_micro')
+      !
+   END SUBROUTINE p4z_micro
+
+
+   SUBROUTINE p4z_micro_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_micro_init  ***
+      !!
+      !! ** Purpose :   Initialization of microzooplankton parameters
+      !!
+      !! ** Method  :   Read the nampiszoo namelist and check the parameters
+      !!                called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampiszoo
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/namp4zzoo/ part, grazrat, resrat, mzrat, xprefn, xprefc, &
+         &                xprefd,  xthreshdia,  xthreshphy,  xthreshpoc, &
+         &                xthresh, xkgraz, epsher, epshermin, sigma1, unass
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) 'p4z_micro_init : Initialization of microzooplankton parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp4zzoo, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namp4zzoo in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp4zzoo, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namp4zzoo in configuration namelist' )
+      IF(lwm) WRITE( numonp, namp4zzoo )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : namp4zzoo'
+         WRITE(numout,*) '      part of calcite not dissolved in microzoo guts  part        =', part
+         WRITE(numout,*) '      microzoo preference for POC                     xprefc      =', xprefc
+         WRITE(numout,*) '      microzoo preference for nano                    xprefn      =', xprefn
+         WRITE(numout,*) '      microzoo preference for diatoms                 xprefd      =', xprefd
+         WRITE(numout,*) '      diatoms feeding threshold  for microzoo         xthreshdia  =', xthreshdia
+         WRITE(numout,*) '      nanophyto feeding threshold for microzoo        xthreshphy  =', xthreshphy
+         WRITE(numout,*) '      poc feeding threshold for microzoo              xthreshpoc  =', xthreshpoc
+         WRITE(numout,*) '      feeding threshold for microzooplankton          xthresh     =', xthresh
+         WRITE(numout,*) '      exsudation rate of microzooplankton             resrat      =', resrat
+         WRITE(numout,*) '      microzooplankton mortality rate                 mzrat       =', mzrat
+         WRITE(numout,*) '      maximal microzoo grazing rate                   grazrat     =', grazrat
+         WRITE(numout,*) '      non assimilated fraction of P by microzoo       unass       =', unass
+         WRITE(numout,*) '      Efficicency of microzoo growth                  epsher      =', epsher
+         WRITE(numout,*) '      Minimum efficicency of microzoo growth          epshermin   =', epshermin
+         WRITE(numout,*) '      Fraction of microzoo excretion as DOM           sigma1      =', sigma1
+         WRITE(numout,*) '      half sturation constant for grazing 1           xkgraz      =', xkgraz
+      ENDIF
+      !
+   END SUBROUTINE p4z_micro_init
+
+   !!======================================================================
+END MODULE p4zmicro
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmort.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmort.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zmort.F90	(revision 14097)
@@ -0,0 +1,249 @@
+MODULE p4zmort
+   !!======================================================================
+   !!                         ***  MODULE p4zmort  ***
+   !! TOP :   PISCES Compute the mortality terms for phytoplankton
+   !!======================================================================
+   !! History :   1.0  !  2002     (O. Aumont)  Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   p4z_mort       : Compute the mortality terms for phytoplankton
+   !!   p4z_mort_init  : Initialize the mortality params for phytoplankton
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zprod         ! Primary productivity 
+   USE p4zlim          ! Phytoplankton limitation terms
+   USE prtctl_trc      ! print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_mort    
+   PUBLIC   p4z_mort_init    
+
+   REAL(wp), PUBLIC ::   wchl     !:
+   REAL(wp), PUBLIC ::   wchld    !:
+   REAL(wp), PUBLIC ::   wchldm   !:
+   REAL(wp), PUBLIC ::   mprat    !:
+   REAL(wp), PUBLIC ::   mprat2   !:
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_mort( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_mort  ***
+      !!
+      !! ** Purpose :   Calls the different subroutine to initialize and compute
+      !!                the different phytoplankton mortality terms
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      CALL p4z_nano            ! nanophytoplankton
+      !
+      CALL p4z_diat            ! diatoms
+      !
+   END SUBROUTINE p4z_mort
+
+
+   SUBROUTINE p4z_nano
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_nano  ***
+      !!
+      !! ** Purpose :   Compute the mortality terms for nanophytoplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zsizerat, zcompaph
+      REAL(wp) ::   zfactfe, zfactch, zprcaca, zfracal
+      REAL(wp) ::   ztortp , zrespp , zmortp 
+      CHARACTER (len=25) ::   charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_nano')
+      !
+      prodcal(:,:,:) = 0._wp   ! calcite production variable set to zero
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompaph = MAX( ( trb(ji,jj,jk,jpphy) - 1e-8 ), 0.e0 )
+               !     When highly limited by macronutrients, very small cells 
+               !     dominate the community. As a consequence, aggregation
+               !     due to turbulence is negligible. Mortality is also set
+               !     to 0
+               zsizerat = MIN(1., MAX( 0., (quotan(ji,jj,jk) - 0.2) / 0.3) ) * trb(ji,jj,jk,jpphy)
+               !     Squared mortality of Phyto similar to a sedimentation term during
+               !     blooms (Doney et al. 1996)
+               zrespp = wchl * 1.e6 * xstep * xdiss(ji,jj,jk) * zcompaph * zsizerat 
+
+               !     Phytoplankton mortality. This mortality loss is slightly
+               !     increased when nutrients are limiting phytoplankton growth
+               !     as observed for instance in case of iron limitation.
+               ztortp = mprat * xstep * zcompaph / ( xkmort + trb(ji,jj,jk,jpphy) ) * zsizerat
+
+               zmortp = zrespp + ztortp
+
+               !   Update the arrays TRA which contains the biological sources and sinks
+
+               zfactfe = trb(ji,jj,jk,jpnfe)/(trb(ji,jj,jk,jpphy)+rtrn)
+               zfactch = trb(ji,jj,jk,jpnch)/(trb(ji,jj,jk,jpphy)+rtrn)
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zmortp
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zmortp * zfactch
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zmortp * zfactfe
+               zprcaca = xfracal(ji,jj,jk) * zmortp
+               !
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               !
+               zfracal = 0.5 * xfracal(ji,jj,jk)
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2. * zprcaca
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) + zprcaca
+               tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zfracal * zmortp
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + ( 1. - zfracal ) * zmortp
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + ( 1. - zfracal ) * zmortp
+               prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zfracal * zmortp
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + ( 1. - zfracal ) * zmortp * zfactfe
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zfracal * zmortp * zfactfe
+            END DO
+         END DO
+      END DO
+      !
+       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('nano')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_nano')
+      !
+   END SUBROUTINE p4z_nano
+
+
+   SUBROUTINE p4z_diat
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_diat  ***
+      !!
+      !! ** Purpose :   Compute the mortality terms for diatoms
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zfactfe,zfactsi,zfactch, zcompadi
+      REAL(wp) ::   zrespp2, ztortp2, zmortp2
+      REAL(wp) ::   zlim2, zlim1
+      CHARACTER (len=25) ::   charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_diat')
+      !
+      !    Aggregation term for diatoms is increased in case of nutrient
+      !    stress as observed in reality. The stressed cells become more
+      !    sticky and coagulate to sink quickly out of the euphotic zone
+      !     ------------------------------------------------------------
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+               zcompadi = MAX( ( trb(ji,jj,jk,jpdia) - 1e-9), 0. )
+
+               !    Aggregation term for diatoms is increased in case of nutrient
+               !    stress as observed in reality. The stressed cells become more
+               !    sticky and coagulate to sink quickly out of the euphotic zone
+               !     ------------------------------------------------------------
+               !  Phytoplankton respiration 
+               !     ------------------------
+               zlim2   = xlimdia(ji,jj,jk) * xlimdia(ji,jj,jk)
+               zlim1   = 0.25 * ( 1. - zlim2 ) / ( 0.25 + zlim2 ) 
+               zrespp2 = 1.e6 * xstep * (  wchld + wchldm * zlim1 ) * xdiss(ji,jj,jk) * zcompadi * trb(ji,jj,jk,jpdia)
+
+               !     Phytoplankton mortality. 
+               !     ------------------------
+               ztortp2 = mprat2 * xstep * trb(ji,jj,jk,jpdia)  / ( xkmort + trb(ji,jj,jk,jpdia) ) * zcompadi 
+
+               zmortp2 = zrespp2 + ztortp2
+
+               !   Update the arrays tra which contains the biological sources and sinks
+               !   ---------------------------------------------------------------------
+               zfactch = trb(ji,jj,jk,jpdch) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactfe = trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactsi = trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zmortp2 
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zmortp2 * zfactch
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zmortp2 * zfactfe
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zmortp2 * zfactsi
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zmortp2 * zfactsi
+               tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zrespp2 + 0.5 * ztortp2
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + 0.5 * ztortp2
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + 0.5 * ztortp2
+               prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zrespp2 + 0.5 * ztortp2
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + 0.5 * ztortp2 * zfactfe
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + ( zrespp2 + 0.5 * ztortp2 ) * zfactfe
+            END DO
+         END DO
+      END DO
+      !
+      IF(ln_ctl) THEN      ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('diat')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_diat')
+      !
+   END SUBROUTINE p4z_diat
+
+
+   SUBROUTINE p4z_mort_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_mort_init  ***
+      !!
+      !! ** Purpose :   Initialization of phytoplankton parameters
+      !!
+      !! ** Method  :   Read the nampismort namelist and check the parameters
+      !!              called at the first timestep
+      !!
+      !! ** input   :   Namelist nampismort
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/namp4zmort/ wchl, wchld, wchldm, mprat, mprat2
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) 'p4z_mort_init : Initialization of phytoplankton mortality parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )              ! Namelist nampismort in reference namelist : Pisces phytoplankton
+      READ  ( numnatp_ref, namp4zmort, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namp4zmort in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampismort in configuration namelist : Pisces phytoplankton
+      READ  ( numnatp_cfg, namp4zmort, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namp4zmort in configuration namelist' )
+      IF(lwm) WRITE( numonp, namp4zmort )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : namp4zmort'
+         WRITE(numout,*) '      quadratic mortality of phytoplankton        wchl   =', wchl
+         WRITE(numout,*) '      maximum quadratic mortality of diatoms      wchld  =', wchld
+         WRITE(numout,*) '      maximum quadratic mortality of diatoms      wchldm =', wchldm
+         WRITE(numout,*) '      phytoplankton mortality rate                mprat  =', mprat
+         WRITE(numout,*) '      Diatoms mortality rate                      mprat2 =', mprat2
+      ENDIF
+      !
+   END SUBROUTINE p4z_mort_init
+
+   !!======================================================================
+END MODULE p4zmort
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zopt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zopt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zopt.F90	(revision 14097)
@@ -0,0 +1,460 @@
+MODULE p4zopt
+   !!======================================================================
+   !!                         ***  MODULE p4zopt  ***
+   !! TOP - PISCES : Compute the light availability in the water column
+   !!======================================================================
+   !! History :  1.0  !  2004     (O. Aumont) Original code
+   !!            2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!            3.2  !  2009-04  (C. Ethe, G. Madec)  optimisation
+   !!            3.4  !  2011-06  (O. Aumont, C. Ethe) Improve light availability of nano & diat
+   !!----------------------------------------------------------------------
+   !!   p4z_opt       : light availability in the water column
+   !!----------------------------------------------------------------------
+   USE trc            ! tracer variables
+   USE oce_trc        ! tracer-ocean share variables
+   USE sms_pisces     ! Source Minus Sink of PISCES
+   USE iom            ! I/O manager
+   USE fldread        !  time interpolation
+   USE prtctl_trc     !  print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_opt        ! called in p4zbio.F90 module
+   PUBLIC   p4z_opt_init   ! called in trcsms_pisces.F90 module
+   PUBLIC   p4z_opt_alloc
+
+   !! * Shared module variables
+
+   LOGICAL  ::   ln_varpar   ! boolean for variable PAR fraction
+   REAL(wp) ::   parlux      ! Fraction of shortwave as PAR
+   REAL(wp) ::   xparsw      ! parlux/3
+   REAL(wp) ::   xsi0r       ! 1. /rn_si0
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_par      ! structure of input par
+   INTEGER , PARAMETER :: nbtimes = 366  !: maximum number of times record in a file
+   INTEGER  :: ntimes_par                ! number of time steps in a file
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   par_varsw      ! PAR fraction of shortwave
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ekb, ekg, ekr  ! wavelength (Red-Green-Blue)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_opt( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_opt  ***
+      !!
+      !! ** Purpose :   Compute the light availability in the water column
+      !!              depending on the depth and the chlorophyll concentration
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   ! ocean time step
+      !
+      INTEGER  ::   ji, jj, jk
+      INTEGER  ::   irgb
+      REAL(wp) ::   zchl
+      REAL(wp) ::   zc0 , zc1 , zc2, zc3, z1_dep
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:  ) :: zetmp5
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zdepmoy, zetmp1, zetmp2, zetmp3, zetmp4
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zqsr100, zqsr_corr
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpar, ze0, ze1, ze2, ze3, zchl3d
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_opt')
+
+      IF( knt == 1 .AND. ln_varpar )   CALL p4z_opt_sbc( kt )
+
+      !     Initialisation of variables used to compute PAR
+      !     -----------------------------------------------
+      ze1(:,:,:) = 0._wp
+      ze2(:,:,:) = 0._wp
+      ze3(:,:,:) = 0._wp
+      !
+      !                                        !* attenuation coef. function of Chlorophyll and wavelength (Red-Green-Blue)
+      !                                        !  --------------------------------------------------------
+                     zchl3d(:,:,:) = trb(:,:,:,jpnch) + trb(:,:,:,jpdch)
+      IF( ln_p5z )   zchl3d(:,:,:) = zchl3d(:,:,:)    + trb(:,:,:,jppch)
+      !
+      DO jk = 1, jpkm1   
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zchl = ( zchl3d(ji,jj,jk) + rtrn ) * 1.e6
+               zchl = MIN(  10. , MAX( 0.05, zchl )  )
+               irgb = NINT( 41 + 20.* LOG10( zchl ) + rtrn )
+               !                                                         
+               ekb(ji,jj,jk) = rkrgb(1,irgb) * e3t_n(ji,jj,jk)
+               ekg(ji,jj,jk) = rkrgb(2,irgb) * e3t_n(ji,jj,jk)
+               ekr(ji,jj,jk) = rkrgb(3,irgb) * e3t_n(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !                                        !* Photosynthetically Available Radiation (PAR)
+      !                                        !  --------------------------------------
+      IF( l_trcdm2dc ) THEN                     !  diurnal cycle
+         !
+         zqsr_corr(:,:) = qsr_mean(:,:) / ( 1.-fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3, pqsr100 = zqsr100 ) 
+         !
+         DO jk = 1, nksr      
+            etot_ndcy(:,:,jk) =        ze1(:,:,jk) +        ze2(:,:,jk) +       ze3(:,:,jk)
+            enano    (:,:,jk) =  1.85 * ze1(:,:,jk) + 0.69 * ze2(:,:,jk) + 0.46 * ze3(:,:,jk)
+            ediat    (:,:,jk) =  1.62 * ze1(:,:,jk) + 0.74 * ze2(:,:,jk) + 0.63 * ze3(:,:,jk)
+         END DO
+         IF( ln_p5z ) THEN
+            DO jk = 1, nksr      
+              epico  (:,:,jk) =  1.94 * ze1(:,:,jk) + 0.66 * ze2(:,:,jk) + 0.4 * ze3(:,:,jk)
+            END DO
+         ENDIF
+         !
+         zqsr_corr(:,:) = qsr(:,:) / ( 1.-fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3 ) 
+         !
+         DO jk = 1, nksr      
+            etot(:,:,jk) =  ze1(:,:,jk) + ze2(:,:,jk) + ze3(:,:,jk)
+         END DO
+         !
+      ELSE
+         !
+         zqsr_corr(:,:) = qsr(:,:) / ( 1.-fr_i(:,:) + rtrn )
+         !
+         CALL p4z_opt_par( kt, zqsr_corr, ze1, ze2, ze3, pqsr100 = zqsr100  ) 
+         !
+         DO jk = 1, nksr      
+            etot (:,:,jk) =         ze1(:,:,jk) +        ze2(:,:,jk) +       ze3(:,:,jk)
+            enano(:,:,jk) =  1.85 * ze1(:,:,jk) + 0.69 * ze2(:,:,jk) + 0.46 * ze3(:,:,jk)
+            ediat(:,:,jk) =  1.62 * ze1(:,:,jk) + 0.74 * ze2(:,:,jk) + 0.63 * ze3(:,:,jk)
+         END DO
+         IF( ln_p5z ) THEN
+            DO jk = 1, nksr      
+              epico(:,:,jk) =  1.94 * ze1(:,:,jk) + 0.66 * ze2(:,:,jk) + 0.4 * ze3(:,:,jk)
+            END DO
+         ENDIF
+         etot_ndcy(:,:,:) =  etot(:,:,:) 
+      ENDIF
+
+
+      IF( ln_qsr_bio ) THEN                    !* heat flux accros w-level (used in the dynamics)
+         !                                     !  ------------------------
+         CALL p4z_opt_par( kt, qsr, ze1, ze2, ze3, pe0=ze0 )
+         !
+         etot3(:,:,1) =  qsr(:,:) * tmask(:,:,1)
+         DO jk = 2, nksr + 1
+            etot3(:,:,jk) =  ( ze0(:,:,jk) + ze1(:,:,jk) + ze2(:,:,jk) + ze3(:,:,jk) ) * tmask(:,:,jk)
+         END DO
+         !                                     !  ------------------------
+      ENDIF
+      !                                        !* Euphotic depth and level
+      neln   (:,:) = 1                            !  ------------------------
+      heup   (:,:) = gdepw_n(:,:,2)
+      heup_01(:,:) = gdepw_n(:,:,2)
+
+      DO jk = 2, nksr
+         DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF( etot_ndcy(ji,jj,jk) * tmask(ji,jj,jk) >=  zqsr100(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
+                 heup(ji,jj) = gdepw_n(ji,jj,jk+1)     ! Euphotic layer depth
+              ENDIF
+              IF( etot_ndcy(ji,jj,jk) * tmask(ji,jj,jk) >= 0.50 )  THEN
+                 heup_01(ji,jj) = gdepw_n(ji,jj,jk+1)  ! Euphotic layer depth (light level definition)
+              ENDIF
+           END DO
+        END DO
+      END DO
+      !
+      heup   (:,:) = MIN( 300., heup   (:,:) )
+      heup_01(:,:) = MIN( 300., heup_01(:,:) )
+      !                                        !* mean light over the mixed layer
+      zdepmoy(:,:)   = 0.e0                    !  -------------------------------
+      zetmp1 (:,:)   = 0.e0
+      zetmp2 (:,:)   = 0.e0
+
+      DO jk = 1, nksr
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( gdepw_n(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                  zetmp1 (ji,jj) = zetmp1 (ji,jj) + etot     (ji,jj,jk) * e3t_n(ji,jj,jk) ! remineralisation
+                  zetmp2 (ji,jj) = zetmp2 (ji,jj) + etot_ndcy(ji,jj,jk) * e3t_n(ji,jj,jk) ! production
+                  zdepmoy(ji,jj) = zdepmoy(ji,jj) +                       e3t_n(ji,jj,jk)
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      emoy(:,:,:) = etot(:,:,:)       ! remineralisation
+      zpar(:,:,:) = etot_ndcy(:,:,:)  ! diagnostic : PAR with no diurnal cycle 
+      !
+      DO jk = 1, nksr
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( gdepw_n(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                  z1_dep = 1. / ( zdepmoy(ji,jj) + rtrn )
+                  emoy (ji,jj,jk) = zetmp1(ji,jj) * z1_dep
+                  zpar (ji,jj,jk) = zetmp2(ji,jj) * z1_dep
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      zdepmoy(:,:)   = 0.e0
+      zetmp3 (:,:)   = 0.e0
+      zetmp4 (:,:)   = 0.e0
+      !
+      DO jk = 1, nksr
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( gdepw_n(ji,jj,jk+1) <= MIN(hmld(ji,jj), heup_01(ji,jj)) ) THEN
+                  zetmp3 (ji,jj) = zetmp3 (ji,jj) + enano    (ji,jj,jk) * e3t_n(ji,jj,jk) ! production
+                  zetmp4 (ji,jj) = zetmp4 (ji,jj) + ediat    (ji,jj,jk) * e3t_n(ji,jj,jk) ! production
+                  zdepmoy(ji,jj) = zdepmoy(ji,jj) +                       e3t_n(ji,jj,jk)
+               ENDIF
+            END DO
+         END DO
+      END DO
+      enanom(:,:,:) = enano(:,:,:)
+      ediatm(:,:,:) = ediat(:,:,:)
+      !
+      DO jk = 1, nksr
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( gdepw_n(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                  z1_dep = 1. / ( zdepmoy(ji,jj) + rtrn )
+                  enanom(ji,jj,jk) = zetmp3(ji,jj) * z1_dep
+                  ediatm(ji,jj,jk) = zetmp4(ji,jj) * z1_dep
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      IF( ln_p5z ) THEN
+         ALLOCATE( zetmp5(jpi,jpj) )  ;   zetmp5 (:,:) = 0.e0
+         DO jk = 1, nksr
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( gdepw_n(ji,jj,jk+1) <= MIN(hmld(ji,jj), heup_01(ji,jj)) ) THEN
+                     zetmp5(ji,jj)  = zetmp5 (ji,jj) + epico(ji,jj,jk) * e3t_n(ji,jj,jk) ! production
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         epicom(:,:,:) = epico(:,:,:)
+         !
+         DO jk = 1, nksr
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( gdepw_n(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                     z1_dep = 1. / ( zdepmoy(ji,jj) + rtrn )
+                     epicom(ji,jj,jk) = zetmp5(ji,jj) * z1_dep
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         DEALLOCATE( zetmp5 )
+      ENDIF
+      !
+      IF( lk_iomput .AND.  knt == nrdttrc ) THEN
+         CALL iom_put( "Heup" , heup(:,:  ) * tmask(:,:,1) )  ! euphotic layer deptht
+         CALL iom_put( "PARDM", zpar(:,:,:) * tmask(:,:,:) )  ! Photosynthetically Available Radiation
+         CALL iom_put( "PAR"  , emoy(:,:,:) * tmask(:,:,:) )  ! Photosynthetically Available Radiation
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_opt')
+      !
+   END SUBROUTINE p4z_opt
+
+
+   SUBROUTINE p4z_opt_par( kt, pqsr, pe1, pe2, pe3, pe0, pqsr100 ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  routine p4z_opt_par  ***
+      !!
+      !! ** purpose :   compute PAR of each wavelength (Red-Green-Blue)
+      !!                for a given shortwave radiation
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in)              ::   kt                ! ocean time-step
+      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(in   )           ::   pqsr              ! shortwave
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout)           ::   pe1 , pe2 , pe3   ! PAR ( R-G-B)
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout), OPTIONAL ::   pe0               !
+      REAL(wp), DIMENSION(jpi,jpj)    , INTENT(  out), OPTIONAL ::   pqsr100           !
+      !
+      INTEGER    ::   ji, jj, jk     ! dummy loop indices
+      REAL(wp), DIMENSION(jpi,jpj) ::  zqsr   ! shortwave
+      !!----------------------------------------------------------------------
+
+      !  Real shortwave
+      IF( ln_varpar ) THEN  ;  zqsr(:,:) = par_varsw(:,:) * pqsr(:,:)
+      ELSE                  ;  zqsr(:,:) = xparsw         * pqsr(:,:)
+      ENDIF
+      
+      !  Light at the euphotic depth 
+      IF( PRESENT( pqsr100 ) )   pqsr100(:,:) = 0.01 * 3. * zqsr(:,:)
+
+      IF( PRESENT( pe0 ) ) THEN     !  W-level
+         !
+         pe0(:,:,1) = pqsr(:,:) - 3. * zqsr(:,:)    !   ( 1 - 3 * alpha ) * q
+         pe1(:,:,1) = zqsr(:,:)         
+         pe2(:,:,1) = zqsr(:,:)
+         pe3(:,:,1) = zqsr(:,:)
+         !
+         DO jk = 2, nksr + 1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  pe0(ji,jj,jk) = pe0(ji,jj,jk-1) * EXP( -e3t_n(ji,jj,jk-1) * xsi0r )
+                  pe1(ji,jj,jk) = pe1(ji,jj,jk-1) * EXP( -ekb  (ji,jj,jk-1 )        )
+                  pe2(ji,jj,jk) = pe2(ji,jj,jk-1) * EXP( -ekg  (ji,jj,jk-1 )        )
+                  pe3(ji,jj,jk) = pe3(ji,jj,jk-1) * EXP( -ekr  (ji,jj,jk-1 )        )
+               END DO
+              !
+            END DO
+            !
+         END DO
+        !
+      ELSE   ! T- level
+        !
+        pe1(:,:,1) = zqsr(:,:) * EXP( -0.5 * ekb(:,:,1) )
+        pe2(:,:,1) = zqsr(:,:) * EXP( -0.5 * ekg(:,:,1) )
+        pe3(:,:,1) = zqsr(:,:) * EXP( -0.5 * ekr(:,:,1) )
+        !
+        DO jk = 2, nksr      
+           DO jj = 1, jpj
+              DO ji = 1, jpi
+                 pe1(ji,jj,jk) = pe1(ji,jj,jk-1) * EXP( -0.5 * ( ekb(ji,jj,jk-1) + ekb(ji,jj,jk) ) )
+                 pe2(ji,jj,jk) = pe2(ji,jj,jk-1) * EXP( -0.5 * ( ekg(ji,jj,jk-1) + ekg(ji,jj,jk) ) )
+                 pe3(ji,jj,jk) = pe3(ji,jj,jk-1) * EXP( -0.5 * ( ekr(ji,jj,jk-1) + ekr(ji,jj,jk) ) )
+              END DO
+           END DO
+        END DO    
+        !
+      ENDIF
+      ! 
+   END SUBROUTINE p4z_opt_par
+
+
+   SUBROUTINE p4z_opt_sbc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine p4z_opt_sbc  ***
+      !!
+      !! ** purpose :   read and interpolate the variable PAR fraction
+      !!                of shortwave radiation
+      !!
+      !! ** method  :   read the files and interpolate the appropriate variables
+      !!
+      !! ** input   :   external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      INTEGER  :: ji,jj
+      REAL(wp) :: zcoef
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('p4z_optsbc')
+      !
+      ! Compute par_varsw at nit000 or only if there is more than 1 time record in par coefficient file
+      IF( ln_varpar ) THEN
+         IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_par > 1 ) ) THEN
+            CALL fld_read( kt, 1, sf_par )
+            par_varsw(:,:) = ( sf_par(1)%fnow(:,:,1) ) / 3.0
+         ENDIF
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_optsbc')
+      !
+   END SUBROUTINE p4z_opt_sbc
+
+
+   SUBROUTINE p4z_opt_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_opt_init  ***
+      !!
+      !! ** Purpose :   Initialization of tabulated attenuation coef
+      !!                and of the percentage of PAR in Shortwave
+      !!
+      !! ** Input   :   external ascii and netcdf files
+      !!----------------------------------------------------------------------
+      INTEGER :: numpar, ierr, ios   ! Local integer 
+      !
+      CHARACTER(len=100) ::  cn_dir          ! Root directory for location of ssr files
+      TYPE(FLD_N) ::   sn_par                ! informations about the fields to be read
+      !
+      NAMELIST/nampisopt/cn_dir, sn_par, ln_varpar, parlux
+      !!----------------------------------------------------------------------
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_opt_init : '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampisopt, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisopt in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampisopt, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisopt in configuration namelist' )
+      IF(lwm) WRITE ( numonp, nampisopt )
+
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist : nampisopt '
+         WRITE(numout,*) '      PAR as a variable fraction of SW     ln_varpar      = ', ln_varpar
+         WRITE(numout,*) '      Default value for the PAR fraction   parlux         = ', parlux
+      ENDIF
+      !
+      xparsw = parlux / 3.0
+      xsi0r  = 1.e0 / rn_si0
+      !
+      ! Variable PAR at the surface of the ocean
+      ! ----------------------------------------
+      IF( ln_varpar ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   initialize variable par fraction (ln_varpar=T)'
+         !
+         ALLOCATE( par_varsw(jpi,jpj) )
+         !
+         ALLOCATE( sf_par(1), STAT=ierr )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+         IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'p4z_opt_init: unable to allocate sf_par structure' )
+         !
+         CALL fld_fill( sf_par, (/ sn_par /), cn_dir, 'p4z_opt_init', 'Variable PAR fraction ', 'nampisopt' )
+                                   ALLOCATE( sf_par(1)%fnow(jpi,jpj,1)   )
+         IF( sn_par%ln_tint )      ALLOCATE( sf_par(1)%fdta(jpi,jpj,1,2) )
+
+         CALL iom_open (  TRIM( sn_par%clname ) , numpar )
+         ntimes_par = iom_getszuld( numpar )   ! get number of record in file
+      ENDIF
+      !
+                         ekr      (:,:,:) = 0._wp
+                         ekb      (:,:,:) = 0._wp
+                         ekg      (:,:,:) = 0._wp
+                         etot     (:,:,:) = 0._wp
+                         etot_ndcy(:,:,:) = 0._wp
+                         enano    (:,:,:) = 0._wp
+                         ediat    (:,:,:) = 0._wp
+      IF( ln_p5z     )   epico    (:,:,:) = 0._wp
+      IF( ln_qsr_bio )   etot3    (:,:,:) = 0._wp
+      ! 
+   END SUBROUTINE p4z_opt_init
+
+
+   INTEGER FUNCTION p4z_opt_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_opt_alloc  ***
+      !!----------------------------------------------------------------------
+      !
+      ALLOCATE( ekb(jpi,jpj,jpk), ekr(jpi,jpj,jpk),  &
+                ekg(jpi,jpj,jpk), STAT= p4z_opt_alloc  ) 
+      !
+      IF( p4z_opt_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p4z_opt_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p4z_opt_alloc
+
+   !!======================================================================
+END MODULE p4zopt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zpoc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zpoc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zpoc.F90	(revision 14097)
@@ -0,0 +1,938 @@
+MODULE p4zpoc
+   !!======================================================================
+   !!                         ***  MODULE p4zpoc  ***
+   !! TOP :   PISCES Compute remineralization of organic particles
+   !!=========================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!             3.6  !  2016-03  (O. Aumont) Quota model and diverse
+   !!----------------------------------------------------------------------
+   !!   p4z_poc       :  Compute remineralization/dissolution of organic compounds
+   !!   p4z_poc_init  :  Initialisation of parameters for remineralisation
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_poc         ! called in p4zbio.F90
+   PUBLIC   p4z_poc_init    ! called in trcsms_pisces.F90
+   PUBLIC   alngam          !
+   PUBLIC   gamain          !
+
+   REAL(wp), PUBLIC ::   xremip     !: remineralisation rate of DOC
+   REAL(wp), PUBLIC ::   xremipc    !: remineralisation rate of DOC
+   REAL(wp), PUBLIC ::   xremipn    !: remineralisation rate of DON
+   REAL(wp), PUBLIC ::   xremipp    !: remineralisation rate of DOP
+   INTEGER , PUBLIC ::   jcpoc      !: number of lability classes
+   REAL(wp), PUBLIC ::   rshape     !: shape factor of the gamma distribution
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   alphan, reminp   !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   alphap           !:
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_poc( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_poc  ***
+      !!
+      !! ** Purpose :   Compute remineralization of organic particles
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   ! ocean time step and ???
+      !
+      INTEGER  ::   ji, jj, jk, jn
+      REAL(wp) ::   zremip, zremig, zdep, zorem, zorem2, zofer
+      REAL(wp) ::   zopon, zopop, zopoc, zopoc2, zopon2, zopop2
+      REAL(wp) ::   zsizek, zsizek1, alphat, remint, solgoc, zpoc
+      REAL(wp) ::   zofer2, zofer3
+      REAL(wp) ::   zrfact2
+      CHARACTER (len=25) :: charout
+      REAL(wp), DIMENSION(jpi,jpj  )   :: totprod, totthick, totcons 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)   :: zremipoc, zremigoc, zorem3, ztremint, zfolimi
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jcpoc) :: alphag
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('p4z_poc')
+      !
+      ! Initialization of local variables
+      ! ---------------------------------
+
+      ! Here we compute the GOC -> POC rate due to the shrinking
+      ! of the fecal pellets/aggregates as a result of bacterial
+      ! solubilization
+      ! This is based on a fractal dimension of 2.56 and a spectral
+      ! slope of -3.6 (identical to what is used in p4zsink to compute
+      ! aggregation
+      solgoc = 0.04/ 2.56 * 1./ ( 1.-50**(-0.04) )
+
+      ! Initialisation of temprary arrys
+      IF( ln_p4z ) THEN
+         zremipoc(:,:,:) = xremip
+         zremigoc(:,:,:) = xremip
+      ELSE    ! ln_p5z
+         zremipoc(:,:,:) = xremipc
+         zremigoc(:,:,:) = xremipc
+      ENDIF
+      zorem3(:,:,:)   = 0.
+      orem  (:,:,:)   = 0.
+      ztremint(:,:,:) = 0.
+      zfolimi (:,:,:) = 0.
+
+      DO jn = 1, jcpoc
+        alphag(:,:,:,jn) = alphan(jn)
+        alphap(:,:,:,jn) = alphan(jn)
+      END DO
+
+     ! -----------------------------------------------------------------------
+     ! Lability parameterization. This is the big particles part (GOC)
+     ! This lability parameterization can be activated only with the standard
+     ! particle scheme. Does not work with Kriest parameterization.
+     ! -----------------------------------------------------------------------
+     ztremint(:,:,:) = zremigoc(:,:,:)
+     DO jk = 2, jpkm1
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF (tmask(ji,jj,jk) == 1.) THEN
+                zdep = hmld(ji,jj)
+                !
+                ! In the case of GOC, lability is constant in the mixed layer 
+                ! It is computed only below the mixed layer depth
+                ! ------------------------------------------------------------
+                !
+                IF( gdept_n(ji,jj,jk) > zdep ) THEN
+                  alphat = 0.
+                  remint = 0.
+                  !
+                  zsizek1  = e3t_n(ji,jj,jk-1) / 2. / (wsbio4(ji,jj,jk-1) + rtrn) * tgfunc(ji,jj,jk-1)
+                  zsizek = e3t_n(ji,jj,jk) / 2. / (wsbio4(ji,jj,jk) + rtrn) * tgfunc(ji,jj,jk)
+                  !
+                  IF ( gdept_n(ji,jj,jk-1) <= zdep ) THEN
+                    ! 
+                    ! The first level just below the mixed layer needs a 
+                    ! specific treatment because lability is supposed constant
+                    ! everywhere within the mixed layer. This means that 
+                    ! change in lability in the bottom part of the previous cell
+                    ! should not be computed
+                    ! ----------------------------------------------------------
+                    !
+                    ! POC concentration is computed using the lagrangian 
+                    ! framework. It is only used for the lability param
+                    zpoc = trb(ji,jj,jk-1,jpgoc) + consgoc(ji,jj,jk) * rday / rfact2               &
+                    &   * e3t_n(ji,jj,jk) / 2. / (wsbio4(ji,jj,jk) + rtrn)
+                    zpoc = MAX(0., zpoc)
+                    !
+                    DO jn = 1, jcpoc
+                       !
+                       ! Lagrangian based algorithm. The fraction of each 
+                       ! lability class is computed starting from the previous
+                       ! level
+                       ! -----------------------------------------------------
+                       !
+                       ! the concentration of each lability class is calculated
+                       ! as the sum of the different sources and sinks
+                       ! Please note that production of new GOC experiences
+                       ! degradation 
+                       alphag(ji,jj,jk,jn) = alphag(ji,jj,jk-1,jn) * exp( -reminp(jn) * zsizek ) * zpoc &
+                       &   + prodgoc(ji,jj,jk) * alphan(jn) / tgfunc(ji,jj,jk) / reminp(jn)             &
+                       &   * ( 1. - exp( -reminp(jn) * zsizek ) ) * rday / rfact2 
+                       alphat = alphat + alphag(ji,jj,jk,jn)
+                       remint = remint + alphag(ji,jj,jk,jn) * reminp(jn)
+                    END DO
+                  ELSE
+                    !
+                    ! standard algorithm in the rest of the water column
+                    ! See the comments in the previous block.
+                    ! ---------------------------------------------------
+                    !
+                    zpoc = trb(ji,jj,jk-1,jpgoc) + consgoc(ji,jj,jk-1) * rday / rfact2               &
+                    &   * e3t_n(ji,jj,jk-1) / 2. / (wsbio4(ji,jj,jk-1) + rtrn) + consgoc(ji,jj,jk)   &
+                    &   * rday / rfact2 * e3t_n(ji,jj,jk) / 2. / (wsbio4(ji,jj,jk) + rtrn)
+                    zpoc = max(0., zpoc)
+                    !
+                    DO jn = 1, jcpoc
+                       alphag(ji,jj,jk,jn) = alphag(ji,jj,jk-1,jn) * exp( -reminp(jn) * ( zsizek              &
+                       &   + zsizek1 ) ) * zpoc + ( prodgoc(ji,jj,jk-1) / tgfunc(ji,jj,jk-1) * ( 1.           &
+                       &   - exp( -reminp(jn) * zsizek1 ) ) * exp( -reminp(jn) * zsizek ) + prodgoc(ji,jj,jk) &
+                       &   / tgfunc(ji,jj,jk) * ( 1. - exp( -reminp(jn) * zsizek ) ) ) * rday / rfact2 / reminp(jn) * alphan(jn) 
+                       alphat = alphat + alphag(ji,jj,jk,jn)
+                       remint = remint + alphag(ji,jj,jk,jn) * reminp(jn)
+                    END DO
+                  ENDIF
+                  !
+                  DO jn = 1, jcpoc
+                     ! The contribution of each lability class at the current
+                     ! level is computed
+                     alphag(ji,jj,jk,jn) = alphag(ji,jj,jk,jn) / ( alphat + rtrn)
+                  END DO
+                  ! Computation of the mean remineralisation rate
+                  ztremint(ji,jj,jk) =  MAX(0., remint / ( alphat + rtrn) )
+                  !
+                ENDIF
+              ENDIF
+            END DO
+         END DO
+      END DO
+
+      IF( ln_p4z ) THEN   ;   zremigoc(:,:,:) = MIN( xremip , ztremint(:,:,:) )
+      ELSE                ;   zremigoc(:,:,:) = MIN( xremipc, ztremint(:,:,:) )
+      ENDIF
+
+      IF( ln_p4z ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! POC disaggregation by turbulence and bacterial activity. 
+                  ! --------------------------------------------------------
+                  zremig = zremigoc(ji,jj,jk) * xstep * tgfunc(ji,jj,jk)
+                  zorem2  = zremig * trb(ji,jj,jk,jpgoc)
+                  orem(ji,jj,jk)      = zorem2
+                  zorem3(ji,jj,jk) = zremig * solgoc * trb(ji,jj,jk,jpgoc)
+                  zofer2 = zremig * trb(ji,jj,jk,jpbfe)
+                  zofer3 = zremig * solgoc * trb(ji,jj,jk,jpbfe)
+
+                  ! -------------------------------------
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zorem3(ji,jj,jk)
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) - zorem2 - zorem3(ji,jj,jk)
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zofer3
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) - zofer2 - zofer3
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zorem2
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zofer2
+                  zfolimi(ji,jj,jk)   = zofer2
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                   ! POC disaggregation by turbulence and bacterial activity. 
+                  ! --------------------------------------------------------
+                  zremig = zremigoc(ji,jj,jk) * xstep * tgfunc(ji,jj,jk)
+                  zopoc2 = zremig  * trb(ji,jj,jk,jpgoc)
+                  orem(ji,jj,jk) = zopoc2
+                  zorem3(ji,jj,jk) = zremig * solgoc * trb(ji,jj,jk,jpgoc)
+                  zopon2 = xremipn / xremipc * zremig * trb(ji,jj,jk,jpgon)
+                  zopop2 = xremipp / xremipc * zremig * trb(ji,jj,jk,jpgop)
+                  zofer2 = xremipn / xremipc * zremig * trb(ji,jj,jk,jpbfe)
+
+                  ! -------------------------------------
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zorem3(ji,jj,jk)
+                  tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + solgoc * zopon2 
+                  tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + solgoc * zopop2
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + solgoc * zofer2
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zopoc2
+                  tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + zopon2
+                  tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + zopop2
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zofer2
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) - zopoc2 - zorem3(ji,jj,jk)
+                  tra(ji,jj,jk,jpgon) = tra(ji,jj,jk,jpgon) - zopon2 * (1. + solgoc)
+                  tra(ji,jj,jk,jpgop) = tra(ji,jj,jk,jpgop) - zopop2 * (1. + solgoc)
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) - zofer2 * (1. + solgoc)
+                  zfolimi(ji,jj,jk)   = zofer2
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+     IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+        WRITE(charout, FMT="('poc1')")
+        CALL prt_ctl_trc_info(charout)
+        CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+     ENDIF
+
+     ! ------------------------------------------------------------------
+     ! Lability parameterization for the small OM particles. This param 
+     ! is based on the same theoretical background as the big particles.
+     ! However, because of its low sinking speed, lability is not supposed
+     ! to be equal to its initial value (the value of the freshly produced
+     ! organic matter). It is however uniform in the mixed layer.
+     ! -------------------------------------------------------------------
+     !
+     totprod (:,:) = 0.
+     totthick(:,:) = 0.
+     totcons (:,:) = 0.
+     ! intregrated production and consumption of POC in the mixed layer
+     ! ----------------------------------------------------------------
+     ! 
+     DO jk = 1, jpkm1
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              zdep = hmld(ji,jj)
+              IF (tmask(ji,jj,jk) == 1. .AND. gdept_n(ji,jj,jk) <= zdep ) THEN
+                totprod(ji,jj) = totprod(ji,jj) + prodpoc(ji,jj,jk) * e3t_n(ji,jj,jk) * rday/ rfact2
+                ! The temperature effect is included here
+                totthick(ji,jj) = totthick(ji,jj) + e3t_n(ji,jj,jk)* tgfunc(ji,jj,jk)
+                totcons(ji,jj) = totcons(ji,jj) - conspoc(ji,jj,jk) * e3t_n(ji,jj,jk) * rday/ rfact2    &
+                &                / ( trb(ji,jj,jk,jppoc) + rtrn )
+              ENDIF
+           END DO
+        END DO
+     END DO
+
+     ! Computation of the lability spectrum in the mixed layer. In the mixed 
+     ! layer, this spectrum is supposed to be uniform.
+     ! ---------------------------------------------------------------------
+     ztremint(:,:,:) = zremipoc(:,:,:)
+     DO jk = 1, jpkm1
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF (tmask(ji,jj,jk) == 1.) THEN
+                zdep = hmld(ji,jj)
+                alphat = 0.0
+                remint = 0.0
+                IF( gdept_n(ji,jj,jk) <= zdep ) THEN
+                   DO jn = 1, jcpoc
+                      ! For each lability class, the system is supposed to be 
+                      ! at equilibrium: Prod - Sink - w alphap = 0.
+                      alphap(ji,jj,jk,jn) = totprod(ji,jj) * alphan(jn) / ( reminp(jn)    &
+                      &                     * totthick(ji,jj) + totcons(ji,jj) + wsbio + rtrn )
+                      alphat = alphat + alphap(ji,jj,jk,jn)
+                   END DO
+                   DO jn = 1, jcpoc
+                      alphap(ji,jj,jk,jn) = alphap(ji,jj,jk,jn) / ( alphat + rtrn)
+                      remint = remint + alphap(ji,jj,jk,jn) * reminp(jn)
+                   END DO
+                   ! Mean remineralization rate in the mixed layer
+                   ztremint(ji,jj,jk) =  MAX( 0., remint )
+                ENDIF
+              ENDIF
+           END DO
+        END DO
+     END DO
+     !
+     IF( ln_p4z ) THEN   ;  zremipoc(:,:,:) = MIN( xremip , ztremint(:,:,:) )
+     ELSE                ;  zremipoc(:,:,:) = MIN( xremipc, ztremint(:,:,:) )
+     ENDIF
+
+     ! -----------------------------------------------------------------------
+     ! The lability parameterization is used here. The code is here 
+     ! almost identical to what is done for big particles. The only difference
+     ! is that an additional source from GOC to POC is included. This means 
+     ! that since we need the lability spectrum of GOC, GOC spectrum 
+     ! should be determined before.
+     ! -----------------------------------------------------------------------
+     !
+     DO jk = 2, jpkm1
+        DO jj = 1, jpj
+           DO ji = 1, jpi
+              IF (tmask(ji,jj,jk) == 1.) THEN
+                zdep = hmld(ji,jj)
+                IF( gdept_n(ji,jj,jk) > zdep ) THEN
+                  alphat = 0.
+                  remint = 0.
+                  !
+                  ! the scale factors are corrected with temperature
+                  zsizek1  = e3t_n(ji,jj,jk-1) / 2. / (wsbio3(ji,jj,jk-1) + rtrn) * tgfunc(ji,jj,jk-1)
+                  zsizek = e3t_n(ji,jj,jk) / 2. / (wsbio3(ji,jj,jk) + rtrn) * tgfunc(ji,jj,jk)
+                  !
+                  ! Special treatment of the level just below the MXL
+                  ! See the comments in the GOC section
+                  ! ---------------------------------------------------
+                  !
+                  IF ( gdept_n(ji,jj,jk-1) <= zdep ) THEN
+                    !
+                    ! Computation of the POC concentration using the 
+                    ! lagrangian algorithm
+                    zpoc = trb(ji,jj,jk-1,jppoc) + conspoc(ji,jj,jk) * rday / rfact2               &
+                    &   * e3t_n(ji,jj,jk) / 2. / (wsbio3(ji,jj,jk) + rtrn)
+                    zpoc = max(0., zpoc)
+                    ! 
+                    DO jn = 1, jcpoc
+                       ! computation of the lability spectrum applying the 
+                       ! different sources and sinks
+                       alphap(ji,jj,jk,jn) = alphap(ji,jj,jk-1,jn) * exp( -reminp(jn) * zsizek ) * zpoc  &
+                       &   + ( prodpoc(ji,jj,jk) * alphan(jn) + zorem3(ji,jj,jk) * alphag(ji,jj,jk,jn) ) &
+                       &   / tgfunc(ji,jj,jk) / reminp(jn) * rday / rfact2 * ( 1. - exp( -reminp(jn)     &
+                       &   * zsizek ) )
+                       alphap(ji,jj,jk,jn) = MAX( 0., alphap(ji,jj,jk,jn) )
+                       alphat = alphat + alphap(ji,jj,jk,jn)
+                    END DO
+                  ELSE
+                    !
+                    ! Lability parameterization for the interior of the ocean
+                    ! This is very similar to what is done in the previous 
+                    ! block
+                    ! --------------------------------------------------------
+                    !
+                    zpoc = trb(ji,jj,jk-1,jppoc) + conspoc(ji,jj,jk-1) * rday / rfact2               &
+                    &   * e3t_n(ji,jj,jk-1) / 2. / (wsbio3(ji,jj,jk-1) + rtrn) + conspoc(ji,jj,jk)   &
+                    &   * rday / rfact2 * e3t_n(ji,jj,jk) / 2. / (wsbio3(ji,jj,jk) + rtrn)
+                    zpoc = max(0., zpoc)
+                    !
+                    DO jn = 1, jcpoc
+                       alphap(ji,jj,jk,jn) = alphap(ji,jj,jk-1,jn) * exp( -reminp(jn)                       &
+                       &   * ( zsizek + zsizek1 ) ) * zpoc + ( prodpoc(ji,jj,jk-1) * alphan(jn)             & 
+                       &   + zorem3(ji,jj,jk-1) * alphag(ji,jj,jk-1,jn) ) * rday / rfact2 / reminp(jn)      &
+                       &   / tgfunc(ji,jj,jk-1) * ( 1. - exp( -reminp(jn) * zsizek1 ) ) * exp( -reminp(jn)  &
+                       &   * zsizek ) + ( prodpoc(ji,jj,jk) * alphan(jn) + zorem3(ji,jj,jk)                 &
+                       &   * alphag(ji,jj,jk,jn) ) * rday / rfact2 / reminp(jn) / tgfunc(ji,jj,jk) * ( 1.   &
+                       &   - exp( -reminp(jn) * zsizek ) )
+                       alphap(ji,jj,jk,jn) = max(0., alphap(ji,jj,jk,jn) )
+                       alphat = alphat + alphap(ji,jj,jk,jn)
+                    END DO
+                  ENDIF
+                  ! Normalization of the lability spectrum so that the 
+                  ! integral is equal to 1
+                  DO jn = 1, jcpoc
+                     alphap(ji,jj,jk,jn) = alphap(ji,jj,jk,jn) / ( alphat + rtrn)
+                     remint = remint + alphap(ji,jj,jk,jn) * reminp(jn)
+                  END DO
+                  ! Mean remineralization rate in the water column
+                  ztremint(ji,jj,jk) =  MAX( 0., remint )
+                ENDIF
+              ENDIF
+            END DO
+         END DO
+      END DO
+
+     IF( ln_p4z ) THEN   ;   zremipoc(:,:,:) = MIN( xremip , ztremint(:,:,:) )
+     ELSE                ;   zremipoc(:,:,:) = MIN( xremipc, ztremint(:,:,:) )
+     ENDIF
+
+     IF( ln_p4z ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF (tmask(ji,jj,jk) == 1.) THEN
+                    ! POC disaggregation by turbulence and bacterial activity. 
+                    ! --------------------------------------------------------
+                    zremip          = zremipoc(ji,jj,jk) * xstep * tgfunc(ji,jj,jk)
+                    zorem           = zremip * trb(ji,jj,jk,jppoc)
+                    zofer           = zremip * trb(ji,jj,jk,jpsfe)
+
+                    tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zorem
+                    orem(ji,jj,jk)      = orem(ji,jj,jk) + zorem
+                    tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zofer
+                    tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zorem
+                    tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zofer
+                    zfolimi(ji,jj,jk)   = zfolimi(ji,jj,jk) + zofer
+                  ENDIF
+               END DO
+            END DO
+         END DO
+     ELSE
+       DO jk = 1, jpkm1
+          DO jj = 1, jpj
+             DO ji = 1, jpi
+                ! POC disaggregation by turbulence and bacterial activity. 
+                ! --------------------------------------------------------
+                zremip = zremipoc(ji,jj,jk) * xstep * tgfunc(ji,jj,jk)
+                zopoc  = zremip * trb(ji,jj,jk,jppoc)
+                orem(ji,jj,jk)  = orem(ji,jj,jk) + zopoc
+                zopon  = xremipn / xremipc * zremip * trb(ji,jj,jk,jppon)
+                zopop  = xremipp / xremipc * zremip * trb(ji,jj,jk,jppop)
+                zofer  = xremipn / xremipc * zremip * trb(ji,jj,jk,jpsfe)
+
+                tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zopoc
+                tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) - zopon
+                tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) - zopop
+                tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zofer
+                tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zopoc
+                tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + zopon 
+                tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + zopop 
+                tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zofer 
+                zfolimi(ji,jj,jk)   = zfolimi(ji,jj,jk) + zofer
+             END DO
+           END DO
+        END DO
+     ENDIF
+
+     IF( lk_iomput ) THEN
+        IF( knt == nrdttrc ) THEN
+          zrfact2 = 1.e3 * rfact2r
+          CALL iom_put( "REMINP" , zremipoc(:,:,:) * tmask(:,:,:) )  ! Remineralisation rate
+          CALL iom_put( "REMING" , zremigoc(:,:,:) * tmask(:,:,:) )  ! Remineralisation rate
+          CALL iom_put( "REMINF" , zfolimi(:,:,:)  * tmask(:,:,:)  * 1.e+9 * zrfact2 )  ! Remineralisation rate
+        ENDIF
+     ENDIF
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('poc2')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_poc')
+      !
+   END SUBROUTINE p4z_poc
+
+
+   SUBROUTINE p4z_poc_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_poc_init  ***
+      !!
+      !! ** Purpose :   Initialization of remineralization parameters
+      !!
+      !! ** Method  :   Read the nampispoc namelist and check the parameters
+      !!              called at the first timestep
+      !!
+      !! ** input   :   Namelist nampispoc
+      !!----------------------------------------------------------------------
+      INTEGER ::   jn            ! dummy loop index
+      INTEGER ::   ios, ifault   ! Local integer
+      REAL(wp)::   remindelta, reminup, remindown
+      !!
+      NAMELIST/nampispoc/ xremip , jcpoc  , rshape,  &
+         &                xremipc, xremipn, xremipp
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_poc_init : Initialization of remineralization parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )              ! Namelist nampisrem in reference namelist : Pisces remineralization
+      READ  ( numnatp_ref, nampispoc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampispoc in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampisrem in configuration namelist : Pisces remineralization
+      READ  ( numnatp_cfg, nampispoc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampispoc in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampispoc )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : nampispoc'
+         IF( ln_p4z ) THEN
+            WRITE(numout,*) '      remineralisation rate of POC              xremip    =', xremip
+         ELSE
+            WRITE(numout,*) '      remineralisation rate of POC              xremipc   =', xremipc
+            WRITE(numout,*) '      remineralisation rate of PON              xremipn   =', xremipn
+            WRITE(numout,*) '      remineralisation rate of POP              xremipp   =', xremipp
+         ENDIF
+         WRITE(numout,*) '      Number of lability classes for POC        jcpoc     =', jcpoc
+         WRITE(numout,*) '      Shape factor of the gamma distribution    rshape    =', rshape
+      ENDIF
+      !
+      ! Discretization along the lability space
+      ! ---------------------------------------
+      !
+      ALLOCATE( alphan(jcpoc) , reminp(jcpoc) , alphap(jpi,jpj,jpk,jcpoc) )
+      !
+      IF (jcpoc > 1) THEN
+         !
+         remindelta = LOG(4. * 1000. ) / REAL(jcpoc-1, wp)
+         reminup = 1./ 400. * EXP(remindelta)
+         !
+         ! Discretization based on incomplete gamma functions
+         ! As incomplete gamma functions are not available in standard 
+         ! fortran 95, they have been coded as functions in this module (gamain)
+         ! ---------------------------------------------------------------------
+         !
+         alphan(1) = gamain(reminup, rshape, ifault)
+         reminp(1) = gamain(reminup, rshape+1.0, ifault) * xremip / alphan(1)
+         DO jn = 2, jcpoc-1
+            reminup = 1./ 400. * EXP( REAL(jn, wp) * remindelta)
+            remindown = 1. / 400. * EXP( REAL(jn-1, wp) * remindelta)
+            alphan(jn) = gamain(reminup, rshape, ifault) - gamain(remindown, rshape, ifault)
+            reminp(jn) = gamain(reminup, rshape+1.0, ifault) - gamain(remindown, rshape+1.0, ifault)
+            reminp(jn) = reminp(jn) * xremip / alphan(jn)
+         END DO
+         remindown = 1. / 400. * EXP( REAL(jcpoc-1, wp) * remindelta)
+         alphan(jcpoc) = 1.0 - gamain(remindown, rshape, ifault)
+         reminp(jcpoc) = 1.0 - gamain(remindown, rshape+1.0, ifault)
+         reminp(jcpoc) = reminp(jcpoc) * xremip / alphan(jcpoc)
+
+      ELSE
+         alphan(jcpoc) = 1.
+         reminp(jcpoc) = xremip
+      ENDIF
+
+      DO jn = 1, jcpoc
+         alphap(:,:,:,jn) = alphan(jn)
+      END DO
+
+   END SUBROUTINE p4z_poc_init
+
+
+   REAL FUNCTION alngam( xvalue, ifault )
+      !*****************************************************************************80
+      !
+      !! ALNGAM computes the logarithm of the gamma function.
+      !
+      !  Modified:    13 January 2008
+      !
+      !  Author  :    Allan Macleod
+      !               FORTRAN90 version by John Burkardt
+      !
+      !  Reference:
+      !    Allan Macleod, Algorithm AS 245,
+      !    A Robust and Reliable Algorithm for the Logarithm of the Gamma Function,
+      !    Applied Statistics,
+      !    Volume 38, Number 2, 1989, pages 397-402.
+      !
+      !  Parameters:
+      !
+      !    Input, real ( kind = 8 ) XVALUE, the argument of the Gamma function.
+      !
+      !    Output, integer ( kind = 4 ) IFAULT, error flag.
+      !    0, no error occurred.
+      !    1, XVALUE is less than or equal to 0.
+      !    2, XVALUE is too big.
+      !
+      !    Output, real ( kind = 8 ) ALNGAM, the logarithm of the gamma function of X.
+      !*****************************************************************************80
+  implicit none
+
+  real(wp), parameter :: alr2pi = 0.918938533204673E+00
+  integer:: ifault
+  real(wp), dimension ( 9 ) :: r1 = (/ &
+    -2.66685511495E+00, &
+    -24.4387534237E+00, &
+    -21.9698958928E+00, &
+     11.1667541262E+00, &
+     3.13060547623E+00, &
+     0.607771387771E+00, &
+     11.9400905721E+00, &
+     31.4690115749E+00, &
+     15.2346874070E+00 /)
+  real(wp), dimension ( 9 ) :: r2 = (/ &
+    -78.3359299449E+00, &
+    -142.046296688E+00, &
+     137.519416416E+00, &
+     78.6994924154E+00, &
+     4.16438922228E+00, &
+     47.0668766060E+00, &
+     313.399215894E+00, &
+     263.505074721E+00, &
+     43.3400022514E+00 /)
+  real(wp), dimension ( 9 ) :: r3 = (/ &
+    -2.12159572323E+05, &
+     2.30661510616E+05, &
+     2.74647644705E+04, &
+    -4.02621119975E+04, &
+    -2.29660729780E+03, &
+    -1.16328495004E+05, &
+    -1.46025937511E+05, &
+    -2.42357409629E+04, &
+    -5.70691009324E+02 /)
+  real(wp), dimension ( 5 ) :: r4 = (/ &
+     0.279195317918525E+00, &
+     0.4917317610505968E+00, &
+     0.0692910599291889E+00, &
+     3.350343815022304E+00, &
+     6.012459259764103E+00 /)
+  real (wp) :: x
+  real (wp) :: x1
+  real (wp) :: x2
+  real (wp), parameter :: xlge = 5.10E+05
+  real (wp), parameter :: xlgst = 1.0E+30
+  real (wp) :: xvalue
+  real (wp) :: y
+
+  x = xvalue
+  alngam = 0.0E+00
+!
+!  Check the input.
+!
+  if ( xlgst <= x ) then
+    ifault = 2
+    return
+  end if
+  if ( x <= 0.0E+00 ) then
+    ifault = 1
+    return
+  end if
+
+  ifault = 0
+!
+!  Calculation for 0 < X < 0.5 and 0.5 <= X < 1.5 combined.
+!
+  if ( x < 1.5E+00 ) then
+
+    if ( x < 0.5E+00 ) then
+      alngam = - log ( x )
+      y = x + 1.0E+00
+!
+!  Test whether X < machine epsilon.
+!
+      if ( y == 1.0E+00 ) then
+        return
+      end if
+
+    else
+
+      alngam = 0.0E+00
+      y = x
+      x = ( x - 0.5E+00 ) - 0.5E+00
+
+    end if
+
+    alngam = alngam + x * (((( &
+        r1(5)   * y &
+      + r1(4) ) * y &
+      + r1(3) ) * y &
+      + r1(2) ) * y &
+      + r1(1) ) / (((( &
+                  y &
+      + r1(9) ) * y &
+      + r1(8) ) * y &
+      + r1(7) ) * y &
+      + r1(6) )
+
+    return
+
+  end if
+!
+!  Calculation for 1.5 <= X < 4.0.
+!
+  if ( x < 4.0E+00 ) then
+
+    y = ( x - 1.0E+00 ) - 1.0E+00
+
+    alngam = y * (((( &
+        r2(5)   * x &
+      + r2(4) ) * x &
+      + r2(3) ) * x &
+      + r2(2) ) * x &
+      + r2(1) ) / (((( &
+                  x &
+      + r2(9) ) * x &
+      + r2(8) ) * x &
+      + r2(7) ) * x &
+      + r2(6) )
+!
+!  Calculation for 4.0 <= X < 12.0.
+!
+  else if ( x < 12.0E+00 ) then
+
+    alngam = (((( &
+        r3(5)   * x &
+      + r3(4) ) * x &
+      + r3(3) ) * x &
+      + r3(2) ) * x &
+      + r3(1) ) / (((( &
+                  x &
+      + r3(9) ) * x &
+      + r3(8) ) * x &
+      + r3(7) ) * x &
+      + r3(6) )
+!
+!  Calculation for 12.0 <= X.
+!
+  else
+
+    y = log ( x )
+    alngam = x * ( y - 1.0E+00 ) - 0.5E+00 * y + alr2pi
+
+    if ( x <= xlge ) then
+
+      x1 = 1.0E+00 / x
+      x2 = x1 * x1
+
+      alngam = alngam + x1 * ( ( &
+             r4(3)   * &
+        x2 + r4(2) ) * &
+        x2 + r4(1) ) / ( ( &
+        x2 + r4(5) ) * &
+        x2 + r4(4) )
+
+    end if
+
+   end if
+
+   END FUNCTION alngam
+
+
+   REAL FUNCTION gamain( x, p, ifault )
+!*****************************************************************************80
+!
+!! GAMAIN computes the incomplete gamma ratio.
+!
+!  Discussion:
+!
+!    A series expansion is used if P > X or X <= 1.  Otherwise, a
+!    continued fraction approximation is used.
+!
+!  Modified:
+!
+!    17 January 2008
+!
+!  Author:
+!
+!    G Bhattacharjee
+!    FORTRAN90 version by John Burkardt
+!
+!  Reference:
+!
+!    G Bhattacharjee,
+!    Algorithm AS 32:
+!    The Incomplete Gamma Integral,
+!    Applied Statistics,
+!    Volume 19, Number 3, 1970, pages 285-287.
+!
+!  Parameters:
+!
+!    Input, real ( kind = 8 ) X, P, the parameters of the incomplete 
+!    gamma ratio.  0 <= X, and 0 < P.
+!
+!    Output, integer ( kind = 4 ) IFAULT, error flag.
+!    0, no errors.
+!    1, P <= 0.
+!    2, X < 0.
+!    3, underflow.
+!    4, error return from the Log Gamma routine.
+!
+!    Output, real ( kind = 8 ) GAMAIN, the value of the incomplete
+!    gamma ratio.
+!
+  implicit none
+
+  real (wp) a
+  real (wp), parameter :: acu = 1.0E-08
+  real (wp) an
+  real (wp) arg
+  real (wp) b
+  real (wp) dif
+  real (wp) factor
+  real (wp) g
+  real (wp) gin
+  integer i
+  integer ifault
+  real (wp), parameter :: oflo = 1.0E+37
+  real (wp) p
+  real (wp) pn(6)
+  real (wp) rn
+  real (wp) term
+  real (wp), parameter :: uflo = 1.0E-37
+  real (wp) x
+!
+!  Check the input.
+!
+  if ( p <= 0.0E+00 ) then
+    ifault = 1
+    gamain = 0.0E+00
+    return
+  end if
+
+  if ( x < 0.0E+00 ) then
+    ifault = 2
+    gamain = 0.0E+00
+    return
+  end if
+
+  if ( x == 0.0E+00 ) then
+    ifault = 0
+    gamain = 0.0E+00
+    return
+  end if
+
+  g = alngam ( p, ifault )
+
+  if ( ifault /= 0 ) then
+    ifault = 4
+    gamain = 0.0E+00
+    return
+  end if
+
+  arg = p * log ( x ) - x - g
+
+  if ( arg < log ( uflo ) ) then
+    ifault = 3
+    gamain = 0.0E+00
+    return
+  end if
+
+  ifault = 0
+  factor = exp ( arg )
+!
+!  Calculation by series expansion.
+!
+  if ( x <= 1.0E+00 .or. x < p ) then
+
+    gin = 1.0E+00
+    term = 1.0E+00
+    rn = p
+
+    do
+
+      rn = rn + 1.0E+00
+      term = term * x / rn
+      gin = gin + term
+
+      if ( term <= acu ) then
+        exit
+      end if
+
+    end do
+
+    gamain = gin * factor / p
+    return
+
+  end if
+!
+!  Calculation by continued fraction.
+!
+  a = 1.0E+00 - p
+  b = a + x + 1.0E+00
+  term = 0.0E+00
+
+  pn(1) = 1.0E+00
+  pn(2) = x
+  pn(3) = x + 1.0E+00
+  pn(4) = x * b
+
+  gin = pn(3) / pn(4)
+
+  do
+
+    a = a + 1.0E+00
+    b = b + 2.0E+00
+    term = term + 1.0E+00
+    an = a * term
+    do i = 1, 2
+      pn(i+4) = b * pn(i+2) - an * pn(i)
+    end do
+
+    if ( pn(6) /= 0.0E+00 ) then
+
+      rn = pn(5) / pn(6)
+      dif = abs ( gin - rn )
+!
+!  Absolute error tolerance satisfied?
+!
+      if ( dif <= acu ) then
+!
+!  Relative error tolerance satisfied?
+!
+        if ( dif <= acu * rn ) then
+          gamain = 1.0E+00 - factor * gin
+          exit
+        end if
+
+      end if
+
+      gin = rn
+
+    end if
+
+    do i = 1, 4
+      pn(i) = pn(i+2)
+    end do
+    if ( oflo <= abs ( pn(5) ) ) then
+
+      do i = 1, 4
+        pn(i) = pn(i) / oflo
+      end do
+
+    end if
+
+  end do
+
+  END FUNCTION gamain
+
+   !!======================================================================
+END MODULE p4zpoc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zprod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zprod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zprod.F90	(revision 14097)
@@ -0,0 +1,446 @@
+MODULE p4zprod
+   !!======================================================================
+   !!                         ***  MODULE p4zprod  ***
+   !! TOP :  Growth Rate of the two phytoplanktons groups 
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-05  (O. Aumont, C. Ethe) New parameterization of light limitation
+   !!----------------------------------------------------------------------
+   !!   p4z_prod       : Compute the growth Rate of the two phytoplanktons groups
+   !!   p4z_prod_init  : Initialization of the parameters for growth
+   !!   p4z_prod_alloc : Allocate variables for growth
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zlim          ! Co-limitations of differents nutrients
+   USE prtctl_trc      ! print control for debugging
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_prod         ! called in p4zbio.F90
+   PUBLIC   p4z_prod_init    ! called in trcsms_pisces.F90
+   PUBLIC   p4z_prod_alloc
+
+   REAL(wp), PUBLIC ::   pislopen     !:
+   REAL(wp), PUBLIC ::   pisloped     !:
+   REAL(wp), PUBLIC ::   xadap        !:
+   REAL(wp), PUBLIC ::   excretn      !:
+   REAL(wp), PUBLIC ::   excretd      !:
+   REAL(wp), PUBLIC ::   bresp        !:
+   REAL(wp), PUBLIC ::   chlcnm       !:
+   REAL(wp), PUBLIC ::   chlcdm       !:
+   REAL(wp), PUBLIC ::   chlcmin      !:
+   REAL(wp), PUBLIC ::   fecnm        !:
+   REAL(wp), PUBLIC ::   fecdm        !:
+   REAL(wp), PUBLIC ::   grosip       !:
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   quotan   !: proxy of N quota in Nanophyto
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   quotad   !: proxy of N quota in diatomee
+   
+   REAL(wp) ::   r1_rday    ! 1 / rday
+   REAL(wp) ::   texcretn   ! 1 - excretn 
+   REAL(wp) ::   texcretd   ! 1 - excretd        
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_prod( kt , knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_prod  ***
+      !!
+      !! ** Purpose :   Compute the phytoplankton production depending on
+      !!              light, temperature and nutrient availability
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt   !
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zsilfac, znanotot, zdiattot, zconctemp, zconctemp2
+      REAL(wp) ::   zratio, zmax, zsilim, ztn, zadap, zlim, zsilfac2, zsiborn
+      REAL(wp) ::   zprod, zproreg, zproreg2, zprochln, zprochld
+      REAL(wp) ::   zmaxday, zdocprod, zpislopen, zpisloped
+      REAL(wp) ::   zmxltst, zmxlday
+      REAL(wp) ::   zrum, zcodel, zargu, zval, zfeup, chlcnm_n, chlcdm_n
+      REAL(wp) ::   zfact
+      CHARACTER (len=25) :: charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zw2d
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: zw3d
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zstrn, zmixnano, zmixdiat
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprmaxn,zprmaxd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpislopeadn, zpislopeadd, zysopt  
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprdia, zprbio, zprdch, zprnch   
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprorcan, zprorcad, zprofed, zprofen
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpronewn, zpronewd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zmxl_fac, zmxl_chl
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpligprod1, zpligprod2
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_prod')
+      !
+      !  Allocate temporary workspace
+      !
+      zprorcan(:,:,:) = 0._wp ; zprorcad(:,:,:) = 0._wp ; zprofed (:,:,:) = 0._wp
+      zprofen (:,:,:) = 0._wp ; zysopt  (:,:,:) = 0._wp
+      zpronewn(:,:,:) = 0._wp ; zpronewd(:,:,:) = 0._wp ; zprdia  (:,:,:) = 0._wp
+      zprbio  (:,:,:) = 0._wp ; zprdch  (:,:,:) = 0._wp ; zprnch  (:,:,:) = 0._wp 
+      zmxl_fac(:,:,:) = 0._wp ; zmxl_chl(:,:,:) = 0._wp 
+
+      ! Computation of the optimal production
+      zprmaxn(:,:,:) = 0.8_wp * r1_rday * tgfunc(:,:,:)
+      zprmaxd(:,:,:) = zprmaxn(:,:,:)
+
+      ! compute the day length depending on latitude and the day
+      zrum = REAL( nday_year - 80, wp ) / REAL( nyear_len(1), wp )
+      zcodel = ASIN(  SIN( zrum * rpi * 2._wp ) * SIN( rad * 23.5_wp )  )
+
+      ! day length in hours
+      zstrn(:,:) = 0.
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zargu = TAN( zcodel ) * TAN( gphit(ji,jj) * rad )
+            zargu = MAX( -1., MIN(  1., zargu ) )
+            zstrn(ji,jj) = MAX( 0.0, 24. - 2. * ACOS( zargu ) / rad / 15. )
+         END DO
+      END DO
+
+      ! Impact of the day duration and light intermittency on phytoplankton growth
+      DO jk = 1, jpkm1
+         DO jj = 1 ,jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  zval = MAX( 1., zstrn(ji,jj) )
+                  IF( gdept_n(ji,jj,jk) <= hmld(ji,jj) ) THEN
+                     zval = zval * MIN(1., heup_01(ji,jj) / ( hmld(ji,jj) + rtrn ))
+                  ENDIF
+                  zmxl_chl(ji,jj,jk) = zval / 24.
+                  zmxl_fac(ji,jj,jk) = 1.5 * zval / ( 12. + zval )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      zprbio(:,:,:) = zprmaxn(:,:,:) * zmxl_fac(:,:,:)
+      zprdia(:,:,:) = zprmaxd(:,:,:) * zmxl_fac(:,:,:)
+
+      ! Maximum light intensity
+      WHERE( zstrn(:,:) < 1.e0 ) zstrn(:,:) = 24.
+
+      ! Computation of the P-I slope for nanos and diatoms
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  ztn         = MAX( 0., tsn(ji,jj,jk,jp_tem) - 15. )
+                  zadap       = xadap * ztn / ( 2.+ ztn )
+                  zconctemp   = MAX( 0.e0 , trb(ji,jj,jk,jpdia) - xsizedia )
+                  zconctemp2  = trb(ji,jj,jk,jpdia) - zconctemp
+                  !
+                  zpislopeadn(ji,jj,jk) = pislopen * ( 1.+ zadap  * EXP( -0.25 * enano(ji,jj,jk) ) )  &
+                  &                   * trb(ji,jj,jk,jpnch) /( trb(ji,jj,jk,jpphy) * 12. + rtrn)
+                  !
+                  zpislopeadd(ji,jj,jk) = (pislopen * zconctemp2 + pisloped * zconctemp) / ( trb(ji,jj,jk,jpdia) + rtrn )   &
+                  &                   * trb(ji,jj,jk,jpdch) /( trb(ji,jj,jk,jpdia) * 12. + rtrn)
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                   ! Computation of production function for Carbon
+                   !  ---------------------------------------------
+                   zpislopen = zpislopeadn(ji,jj,jk) / ( ( r1_rday + bresp * r1_rday ) &
+                   &            * zmxl_fac(ji,jj,jk) * rday + rtrn)
+                   zpisloped = zpislopeadd(ji,jj,jk) / ( ( r1_rday + bresp * r1_rday ) &
+                   &            * zmxl_fac(ji,jj,jk) * rday + rtrn)
+                   zprbio(ji,jj,jk) = zprbio(ji,jj,jk) * ( 1.- EXP( -zpislopen * enano(ji,jj,jk) )  )
+                   zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * ( 1.- EXP( -zpisloped * ediat(ji,jj,jk) )  )
+                   !  Computation of production function for Chlorophyll
+                   !--------------------------------------------------
+                   zpislopen = zpislopeadn(ji,jj,jk) / ( zprmaxn(ji,jj,jk) * zmxl_chl(ji,jj,jk) * rday + rtrn )
+                   zpisloped = zpislopeadd(ji,jj,jk) / ( zprmaxd(ji,jj,jk) * zmxl_chl(ji,jj,jk) * rday + rtrn )
+                   zprnch(ji,jj,jk) = zprmaxn(ji,jj,jk) * ( 1.- EXP( -zpislopen * enanom(ji,jj,jk) ) )
+                   zprdch(ji,jj,jk) = zprmaxd(ji,jj,jk) * ( 1.- EXP( -zpisloped * ediatm(ji,jj,jk) ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      !  Computation of a proxy of the N/C ratio
+      !  ---------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+                zval = MIN( xnanopo4(ji,jj,jk), ( xnanonh4(ji,jj,jk) + xnanono3(ji,jj,jk) ) )   &
+                &      * zprmaxn(ji,jj,jk) / ( zprbio(ji,jj,jk) + rtrn )
+                quotan(ji,jj,jk) = MIN( 1., 0.2 + 0.8 * zval )
+                zval = MIN( xdiatpo4(ji,jj,jk), ( xdiatnh4(ji,jj,jk) + xdiatno3(ji,jj,jk) ) )   &
+                &      * zprmaxd(ji,jj,jk) / ( zprdia(ji,jj,jk) + rtrn )
+                quotad(ji,jj,jk) = MIN( 1., 0.2 + 0.8 * zval )
+            END DO
+         END DO
+      END DO
+
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+                IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                   !    Si/C of diatoms
+                   !    ------------------------
+                   !    Si/C increases with iron stress and silicate availability
+                   !    Si/C is arbitrariliy increased for very high Si concentrations
+                   !    to mimic the very high ratios observed in the Southern Ocean (silpot2)
+                  zlim  = trb(ji,jj,jk,jpsil) / ( trb(ji,jj,jk,jpsil) + xksi1 )
+                  zsilim = MIN( zprdia(ji,jj,jk) / ( zprmaxd(ji,jj,jk) + rtrn ), xlimsi(ji,jj,jk) )
+                  zsilfac = 4.4 * EXP( -4.23 * zsilim ) * MAX( 0.e0, MIN( 1., 2.2 * ( zlim - 0.5 ) )  ) + 1.e0
+                  zsiborn = trb(ji,jj,jk,jpsil) * trb(ji,jj,jk,jpsil) * trb(ji,jj,jk,jpsil)
+                  IF (gphit(ji,jj) < -30 ) THEN
+                    zsilfac2 = 1. + 2. * zsiborn / ( zsiborn + xksi2**3 )
+                  ELSE
+                    zsilfac2 = 1. +      zsiborn / ( zsiborn + xksi2**3 )
+                  ENDIF
+                  zysopt(ji,jj,jk) = grosip * zlim * zsilfac * zsilfac2
+              ENDIF
+            END DO
+         END DO
+      END DO
+
+      !  Mixed-layer effect on production 
+      !  Sea-ice effect on production
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zprbio(ji,jj,jk) = zprbio(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
+               zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
+            END DO
+         END DO
+      END DO
+
+      ! Computation of the various production terms 
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for nanophyto. (C)
+                  zprorcan(ji,jj,jk) = zprbio(ji,jj,jk)  * xlimphy(ji,jj,jk) * trb(ji,jj,jk,jpphy) * rfact2
+                  zpronewn(ji,jj,jk)  = zprorcan(ji,jj,jk)* xnanono3(ji,jj,jk) / ( xnanono3(ji,jj,jk) + xnanonh4(ji,jj,jk) + rtrn )
+                  !
+                  zratio = trb(ji,jj,jk,jpnfe) / ( trb(ji,jj,jk,jpphy) * fecnm + rtrn )
+                  zmax   = MAX( 0., ( 1. - zratio ) / ABS( 1.05 - zratio ) ) 
+                  zprofen(ji,jj,jk) = fecnm * zprmaxn(ji,jj,jk) * ( 1.0 - fr_i(ji,jj) )  &
+                  &             * ( 4. - 4.5 * xlimnfe(ji,jj,jk) / ( xlimnfe(ji,jj,jk) + 0.5 ) )    &
+                  &             * biron(ji,jj,jk) / ( biron(ji,jj,jk) + concnfe(ji,jj,jk) )  &
+                  &             * zmax * trb(ji,jj,jk,jpphy) * rfact2
+                  !  production terms for diatoms (C)
+                  zprorcad(ji,jj,jk) = zprdia(ji,jj,jk) * xlimdia(ji,jj,jk) * trb(ji,jj,jk,jpdia) * rfact2
+                  zpronewd(ji,jj,jk) = zprorcad(ji,jj,jk) * xdiatno3(ji,jj,jk) / ( xdiatno3(ji,jj,jk) + xdiatnh4(ji,jj,jk) + rtrn )
+                  !
+                  zratio = trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) * fecdm + rtrn )
+                  zmax   = MAX( 0., ( 1. - zratio ) / ABS( 1.05 - zratio ) ) 
+                  zprofed(ji,jj,jk) = fecdm * zprmaxd(ji,jj,jk) * ( 1.0 - fr_i(ji,jj) )  &
+                  &             * ( 4. - 4.5 * xlimdfe(ji,jj,jk) / ( xlimdfe(ji,jj,jk) + 0.5 ) )    &
+                  &             * biron(ji,jj,jk) / ( biron(ji,jj,jk) + concdfe(ji,jj,jk) )  &
+                  &             * zmax * trb(ji,jj,jk,jpdia) * rfact2
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      ! Computation of the chlorophyll production terms
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for nanophyto. ( chlorophyll )
+                  znanotot = enanom(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprod    = rday * zprorcan(ji,jj,jk) * zprnch(ji,jj,jk) * xlimphy(ji,jj,jk)
+                  zprochln = chlcmin * 12. * zprorcan (ji,jj,jk)
+                  chlcnm_n   = MIN ( chlcnm, ( chlcnm / (1. - 1.14 / 43.4 *tsn(ji,jj,jk,jp_tem))) * (1. - 1.14 / 43.4 * 20.))
+                  zprochln = zprochln + (chlcnm_n-chlcmin) * 12. * zprod / &
+                                        & (  zpislopeadn(ji,jj,jk) * znanotot +rtrn)
+                  !  production terms for diatoms ( chlorophyll )
+                  zdiattot = ediatm(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprod    = rday * zprorcad(ji,jj,jk) * zprdch(ji,jj,jk) * xlimdia(ji,jj,jk)
+                  zprochld = chlcmin * 12. * zprorcad(ji,jj,jk)
+                  chlcdm_n   = MIN ( chlcdm, ( chlcdm / (1. - 1.14 / 43.4 * tsn(ji,jj,jk,jp_tem))) * (1. - 1.14 / 43.4 * 20.))
+                  zprochld = zprochld + (chlcdm_n-chlcmin) * 12. * zprod / &
+                                        & ( zpislopeadd(ji,jj,jk) * zdiattot +rtrn )
+                  !   Update the arrays TRA which contain the Chla sources and sinks
+                  tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) + zprochln * texcretn
+                  tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) + zprochld * texcretd
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      !   Update the arrays TRA which contain the biological sources and sinks
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+           DO ji =1 ,jpi
+              IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                 zproreg  = zprorcan(ji,jj,jk) - zpronewn(ji,jj,jk)
+                 zproreg2 = zprorcad(ji,jj,jk) - zpronewd(ji,jj,jk)
+                 zdocprod = excretd * zprorcad(ji,jj,jk) + excretn * zprorcan(ji,jj,jk)
+                 tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) - zprorcan(ji,jj,jk) - zprorcad(ji,jj,jk)
+                 tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) - zpronewn(ji,jj,jk) - zpronewd(ji,jj,jk)
+                 tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) - zproreg - zproreg2
+                 tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) + zprorcan(ji,jj,jk) * texcretn
+                 tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) + zprofen(ji,jj,jk) * texcretn
+                 tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) + zprorcad(ji,jj,jk) * texcretd
+                 tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) + zprofed(ji,jj,jk) * texcretd
+                 tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) + zprorcad(ji,jj,jk) * zysopt(ji,jj,jk) * texcretd
+                 tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zdocprod
+                 tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) + o2ut * ( zproreg + zproreg2) &
+                 &                   + ( o2ut + o2nit ) * ( zpronewn(ji,jj,jk) + zpronewd(ji,jj,jk) )
+                 !
+                 zfeup = texcretn * zprofen(ji,jj,jk) + texcretd * zprofed(ji,jj,jk)
+                 tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - zfeup
+                 tra(ji,jj,jk,jpsil) = tra(ji,jj,jk,jpsil) - texcretd * zprorcad(ji,jj,jk) * zysopt(ji,jj,jk)
+                 tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) - zprorcan(ji,jj,jk) - zprorcad(ji,jj,jk)
+                 tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * ( zpronewn(ji,jj,jk) + zpronewd(ji,jj,jk) ) &
+                 &                                         - rno3 * ( zproreg + zproreg2 )
+              ENDIF
+           END DO
+        END DO
+     END DO
+     !
+     IF( ln_ligand ) THEN
+         zpligprod1(:,:,:) = 0._wp    ;    zpligprod2(:,:,:) = 0._wp
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+              DO ji =1 ,jpi
+                 IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                    zdocprod = excretd * zprorcad(ji,jj,jk) + excretn * zprorcan(ji,jj,jk)
+                    zfeup    = texcretn * zprofen(ji,jj,jk) + texcretd * zprofed(ji,jj,jk)
+                    tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + zdocprod * ldocp - zfeup * plig(ji,jj,jk) * lthet
+                    zpligprod1(ji,jj,jk) = zdocprod * ldocp
+                    zpligprod2(ji,jj,jk) = zfeup * plig(ji,jj,jk) * lthet
+                 ENDIF
+              END DO
+           END DO
+        END DO
+     ENDIF
+
+
+    ! Total primary production per year
+    IF( iom_use( "tintpp" ) .OR. ( ln_check_mass .AND. kt == nitend .AND. knt == nrdttrc )  )  &
+         & tpp = glob_sum( 'p4zprod', ( zprorcan(:,:,:) + zprorcad(:,:,:) ) * cvol(:,:,:) )
+
+    IF( lk_iomput .AND.  knt == nrdttrc ) THEN
+       zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+       !
+       CALL iom_put( "PPPHYN"  , zprorcan(:,:,:) * zfact * tmask(:,:,:) )  ! primary production by nanophyto
+       CALL iom_put( "PPPHYD"  , zprorcad(:,:,:) * zfact * tmask(:,:,:)   ) ! primary production by diatomes
+       CALL iom_put( "PPNEWN"  , zpronewn(:,:,:) * zfact * tmask(:,:,:)    ) ! new primary production by nanophyto
+       CALL iom_put( "PPNEWD"  , zpronewd(:,:,:) * zfact * tmask(:,:,:)   ) ! new primary production by diatomes
+       CALL iom_put( "PBSi"    , zprorcad(:,:,:) * zfact * tmask(:,:,:) * zysopt(:,:,:)  ) ! biogenic silica production
+       CALL iom_put( "PFeN"    , zprofen(:,:,:) * zfact * tmask(:,:,:)  ) ! biogenic iron production by nanophyto
+       CALL iom_put( "PFeD"    , zprofed(:,:,:) * zfact * tmask(:,:,:)  ) ! biogenic iron production by  diatomes
+       IF( ln_ligand ) THEN
+         CALL iom_put( "LPRODP"  , zpligprod1(:,:,:) * 1e9 * zfact * tmask(:,:,:) )
+         CALL iom_put( "LDETP"   , zpligprod2(:,:,:) * 1e9 * zfact * tmask(:,:,:) )
+       ENDIF
+       CALL iom_put( "Mumax"   , zprmaxn(:,:,:) * 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 (:,:,:) / (zprmaxn(:,:,:) + rtrn) * tmask(:,:,:)  )  ! light limitation term
+       CALL iom_put( "LDlight" , zprdia (:,:,:) / (zprmaxd(:,:,:) + rtrn) * tmask(:,:,:)   )
+       CALL iom_put( "TPP"     , ( zprorcan(:,:,:) + zprorcad(:,:,:) ) * zfact * tmask(:,:,:)  )  ! total primary production
+       CALL iom_put( "TPNEW"   , ( zpronewn(:,:,:) + zpronewd(:,:,:) ) * zfact * tmask(:,:,:)  ) ! total new production
+       CALL iom_put( "TPBFE"   , ( zprofen(:,:,:) + zprofed(:,:,:) ) * zfact * tmask(:,:,:)  )  ! total biogenic iron production
+       CALL iom_put( "tintpp"  , tpp * zfact )  !  global total integrated primary production molC/s
+     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
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_prod')
+      !
+   END SUBROUTINE p4z_prod
+
+
+   SUBROUTINE p4z_prod_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_prod_init  ***
+      !!
+      !! ** Purpose :   Initialization of phytoplankton production parameters
+      !!
+      !! ** Method  :   Read the nampisprod namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampisprod
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !
+      NAMELIST/namp4zprod/ pislopen, pisloped, xadap, bresp, excretn, excretd,  &
+         &                 chlcnm, chlcdm, chlcmin, fecnm, fecdm, grosip
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_prod_init : phytoplankton growth'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp4zprod, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namp4zprod in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp4zprod, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namp4zprod in configuration namelist' )
+      IF(lwm) WRITE( numonp, namp4zprod )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : namp4zprod'
+         WRITE(numout,*) '      mean Si/C ratio                           grosip       =', grosip
+         WRITE(numout,*) '      P-I slope                                 pislopen     =', pislopen
+         WRITE(numout,*) '      Acclimation factor to low light           xadap        =', xadap
+         WRITE(numout,*) '      excretion ratio of nanophytoplankton      excretn      =', excretn
+         WRITE(numout,*) '      excretion ratio of diatoms                excretd      =', excretd
+         WRITE(numout,*) '      basal respiration in phytoplankton        bresp        =', bresp
+         WRITE(numout,*) '      Maximum Chl/C in phytoplankton            chlcmin      =', chlcmin
+         WRITE(numout,*) '      P-I slope  for diatoms                    pisloped     =', pisloped
+         WRITE(numout,*) '      Minimum Chl/C in nanophytoplankton        chlcnm       =', chlcnm
+         WRITE(numout,*) '      Minimum Chl/C in diatoms                  chlcdm       =', chlcdm
+         WRITE(numout,*) '      Maximum Fe/C in nanophytoplankton         fecnm        =', fecnm
+         WRITE(numout,*) '      Minimum Fe/C in diatoms                   fecdm        =', fecdm
+      ENDIF
+      !
+      r1_rday   = 1._wp / rday 
+      texcretn  = 1._wp - excretn
+      texcretd  = 1._wp - excretd
+      tpp       = 0._wp
+      !
+   END SUBROUTINE p4z_prod_init
+
+
+   INTEGER FUNCTION p4z_prod_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_prod_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( quotan(jpi,jpj,jpk), quotad(jpi,jpj,jpk), STAT = p4z_prod_alloc )
+      !
+      IF( p4z_prod_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p4z_prod_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p4z_prod_alloc
+
+   !!======================================================================
+END MODULE p4zprod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zrem.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zrem.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zrem.F90	(revision 14097)
@@ -0,0 +1,358 @@
+MODULE p4zrem
+   !!======================================================================
+   !!                         ***  MODULE p4zrem  ***
+   !! TOP :   PISCES Compute remineralization/dissolution of organic compounds
+   !!=========================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!----------------------------------------------------------------------
+   !!   p4z_rem       :  Compute remineralization/dissolution of organic compounds
+   !!   p4z_rem_init  :  Initialisation of parameters for remineralisation
+   !!   p4z_rem_alloc :  Allocate remineralisation variables
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zche          !  chemical model
+   USE p4zprod         !  Growth rate of the 2 phyto groups
+   USE p4zlim
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_rem         ! called in p4zbio.F90
+   PUBLIC   p4z_rem_init    ! called in trcsms_pisces.F90
+   PUBLIC   p4z_rem_alloc
+
+   REAL(wp), PUBLIC ::   xremikc    !: remineralisation rate of DOC 
+   REAL(wp), PUBLIC ::   xremikn    !: remineralisation rate of DON 
+   REAL(wp), PUBLIC ::   xremikp    !: remineralisation rate of DOP 
+   REAL(wp), PUBLIC ::   xremik     !: remineralisation rate of POC 
+   REAL(wp), PUBLIC ::   nitrif     !: NH4 nitrification rate 
+   REAL(wp), PUBLIC ::   xsirem     !: remineralisation rate of POC 
+   REAL(wp), PUBLIC ::   xsiremlab  !: fast remineralisation rate of POC 
+   REAL(wp), PUBLIC ::   xsilab     !: fraction of labile biogenic silica 
+   REAL(wp), PUBLIC ::   feratb     !: Fe/C quota in bacteria
+   REAL(wp), PUBLIC ::   xkferb     !: Half-saturation constant for bacteria Fe/C
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   denitr   !: denitrification array
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_rem( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_rem  ***
+      !!
+      !! ** Purpose :   Compute remineralization/scavenging of organic compounds
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt ! ocean time step
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zremik, zremikc, zremikn, zremikp, zsiremin, zfact 
+      REAL(wp) ::   zsatur, zsatur2, znusil, znusil2, zdep, zdepmin, zfactdep
+      REAL(wp) ::   zbactfer, zolimit, zonitr, zrfact2
+      REAL(wp) ::   zammonic, zoxyremc, zoxyremn, zoxyremp
+      REAL(wp) ::   zosil, ztem, zdenitnh4, zolimic, zolimin, zolimip, zdenitrn, zdenitrp
+      CHARACTER (len=25) :: charout
+      REAL(wp), DIMENSION(jpi,jpj    ) :: ztempbac
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zdepbac, zolimi, zdepprod, zfacsi, zfacsib, zdepeff, zfebact
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_rem')
+      !
+      ! Initialisation of arrys
+      zdepprod(:,:,:) = 1._wp
+      zdepeff (:,:,:) = 0.3_wp
+      ztempbac(:,:)   = 0._wp
+      zfacsib(:,:,:)  = xsilab / ( 1.0 - xsilab )
+      zfebact(:,:,:)  = 0._wp
+      zfacsi(:,:,:)   = xsilab
+
+      ! Computation of the mean phytoplankton concentration as
+      ! a crude estimate of the bacterial biomass
+      ! this parameterization has been deduced from a model version
+      ! that was modeling explicitely bacteria
+      ! -------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zdep = MAX( hmld(ji,jj), heup(ji,jj) )
+               IF( gdept_n(ji,jj,jk) < zdep ) THEN
+                  zdepbac(ji,jj,jk) = MIN( 0.7 * ( trb(ji,jj,jk,jpzoo) + 2.* trb(ji,jj,jk,jpmes) ), 4.e-6 )
+                  ztempbac(ji,jj)   = zdepbac(ji,jj,jk)
+               ELSE
+                  zdepmin = MIN( 1., zdep / gdept_n(ji,jj,jk) )
+                  zdepbac (ji,jj,jk) = zdepmin**0.683 * ztempbac(ji,jj)
+                  zdepprod(ji,jj,jk) = zdepmin**0.273
+                  zdepeff (ji,jj,jk) = zdepeff(ji,jj,jk) * zdepmin**0.3
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      IF( ln_p4z ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! DOC ammonification. Depends on depth, phytoplankton biomass
+                  ! and a limitation term which is supposed to be a parameterization of the bacterial activity. 
+                  zremik = xremik * xstep / 1.e-6 * xlimbac(ji,jj,jk) * zdepbac(ji,jj,jk) 
+                  zremik = MAX( zremik, 2.74e-4 * xstep )
+                  ! Ammonification in oxic waters with oxygen consumption
+                  ! -----------------------------------------------------
+                  zolimit = zremik * ( 1.- nitrfac(ji,jj,jk) ) * trb(ji,jj,jk,jpdoc) 
+                  zolimi(ji,jj,jk) = MIN( ( trb(ji,jj,jk,jpoxy) - rtrn ) / o2ut, zolimit ) 
+                  ! Ammonification in suboxic waters with denitrification
+                  ! -------------------------------------------------------
+                  zammonic = zremik * nitrfac(ji,jj,jk) * trb(ji,jj,jk,jpdoc)
+                  denitr(ji,jj,jk)  = zammonic * ( 1. - nitrfac2(ji,jj,jk) )
+                  denitr(ji,jj,jk)  = MIN( ( trb(ji,jj,jk,jpno3) - rtrn ) / rdenit, denitr(ji,jj,jk) )
+                  zoxyremc          = zammonic - denitr(ji,jj,jk)
+                  !
+                  zolimi (ji,jj,jk) = MAX( 0.e0, zolimi (ji,jj,jk) )
+                  denitr (ji,jj,jk) = MAX( 0.e0, denitr (ji,jj,jk) )
+                  zoxyremc          = MAX( 0.e0, zoxyremc )
+
+                  !
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zolimi (ji,jj,jk) + denitr(ji,jj,jk) + zoxyremc
+                  tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zolimi (ji,jj,jk) + denitr(ji,jj,jk) + zoxyremc
+                  tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) - denitr (ji,jj,jk) * rdenit
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) - zolimi (ji,jj,jk) - denitr(ji,jj,jk) - zoxyremc
+                  tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - zolimi (ji,jj,jk) * o2ut
+                  tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zolimi (ji,jj,jk) + denitr(ji,jj,jk) + zoxyremc
+                  tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * ( zolimi(ji,jj,jk) + zoxyremc    &
+                  &                     + ( rdenit + 1.) * denitr(ji,jj,jk) )
+               END DO
+            END DO
+         END DO
+      ELSE
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! DOC ammonification. Depends on depth, phytoplankton biomass
+                  ! and a limitation term which is supposed to be a parameterization of the bacterial activity. 
+                  ! -----------------------------------------------------------------
+                  zremik = xstep / 1.e-6 * MAX(0.01, xlimbac(ji,jj,jk)) * zdepbac(ji,jj,jk) 
+                  zremik = MAX( zremik, 2.74e-4 * xstep / xremikc )
+
+                  zremikc = xremikc * zremik
+                  zremikn = xremikn / xremikc
+                  zremikp = xremikp / xremikc
+
+                  ! Ammonification in oxic waters with oxygen consumption
+                  ! -----------------------------------------------------
+                  zolimit = zremikc * ( 1.- nitrfac(ji,jj,jk) ) * trb(ji,jj,jk,jpdoc) 
+                  zolimic = MAX( 0.e0, MIN( ( trb(ji,jj,jk,jpoxy) - rtrn ) / o2ut, zolimit ) ) 
+                  zolimi(ji,jj,jk) = zolimic
+                  zolimin = zremikn * zolimic * trb(ji,jj,jk,jpdon) / ( trb(ji,jj,jk,jpdoc) + rtrn )
+                  zolimip = zremikp * zolimic * trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdoc) + rtrn ) 
+
+                  ! Ammonification in suboxic waters with denitrification
+                  ! -------------------------------------------------------
+                  zammonic = zremikc * nitrfac(ji,jj,jk) * trb(ji,jj,jk,jpdoc)
+                  denitr(ji,jj,jk)  = zammonic * ( 1. - nitrfac2(ji,jj,jk) )
+                  denitr(ji,jj,jk)  = MAX(0., MIN(  ( trb(ji,jj,jk,jpno3) - rtrn ) / rdenit, denitr(ji,jj,jk) ) )
+                  zoxyremc          = MAX(0., zammonic - denitr(ji,jj,jk))
+                  zdenitrn  = zremikn * denitr(ji,jj,jk) * trb(ji,jj,jk,jpdon) / ( trb(ji,jj,jk,jpdoc) + rtrn )
+                  zdenitrp  = zremikp * denitr(ji,jj,jk) * trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdoc) + rtrn )
+                  zoxyremn  = zremikn * zoxyremc * trb(ji,jj,jk,jpdon) / ( trb(ji,jj,jk,jpdoc) + rtrn )
+                  zoxyremp  = zremikp * zoxyremc * trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdoc) + rtrn )
+
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zolimip + zdenitrp + zoxyremp
+                  tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zolimin + zdenitrn + zoxyremn
+                  tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) - denitr(ji,jj,jk) * rdenit
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) - zolimic - denitr(ji,jj,jk) - zoxyremc
+                  tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) - zolimin - zdenitrn - zoxyremn
+                  tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) - zolimip - zdenitrp - zoxyremp
+                  tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - zolimic * o2ut
+                  tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zolimic + denitr(ji,jj,jk) + zoxyremc
+                  tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * ( zolimin + zoxyremn + ( rdenit + 1.) * zdenitrn )
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
+
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! NH4 nitrification to NO3. Ceased for oxygen concentrations
+               ! below 2 umol/L. Inhibited at strong light 
+               ! ----------------------------------------------------------
+               zonitr  = nitrif * xstep * trb(ji,jj,jk,jpnh4) * ( 1.- nitrfac(ji,jj,jk) )  &
+               &         / ( 1.+ emoy(ji,jj,jk) ) * ( 1. + fr_i(ji,jj) * emoy(ji,jj,jk) ) 
+               zdenitnh4 = nitrif * xstep * trb(ji,jj,jk,jpnh4) * nitrfac(ji,jj,jk)
+               zdenitnh4 = MIN(  ( trb(ji,jj,jk,jpno3) - rtrn ) / rdenita, zdenitnh4 ) 
+               ! Update of the tracers trends
+               ! ----------------------------
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) - zonitr - zdenitnh4
+               tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) + zonitr - rdenita * zdenitnh4
+               tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - o2nit * zonitr
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2 * rno3 * zonitr + rno3 * ( rdenita - 1. ) * zdenitnh4
+            END DO
+         END DO
+      END DO
+
+       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('rem1')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+               ! Bacterial uptake of iron. No iron is available in DOC. So
+               ! Bacteries are obliged to take up iron from the water. Some
+               ! studies (especially at Papa) have shown this uptake to be significant
+               ! ----------------------------------------------------------
+               zbactfer = feratb *  rfact2 * 0.6_wp / rday * tgfunc(ji,jj,jk) * xlimbacl(ji,jj,jk)     &
+                  &              * trb(ji,jj,jk,jpfer) / ( xkferb + trb(ji,jj,jk,jpfer) )    &
+                  &              * zdepprod(ji,jj,jk) * zdepeff(ji,jj,jk) * zdepbac(ji,jj,jk)
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - zbactfer*0.33
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zbactfer*0.25
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zbactfer*0.08
+               zfebact(ji,jj,jk)   = zbactfer * 0.33
+               blim(ji,jj,jk)      = xlimbacl(ji,jj,jk)  * zdepbac(ji,jj,jk) / 1.e-6 * zdepprod(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('rem2')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+
+      ! Initialization of the array which contains the labile fraction
+      ! of bSi. Set to a constant in the upper ocean
+      ! ---------------------------------------------------------------
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zdep     = MAX( hmld(ji,jj), heup_01(ji,jj) )
+               zsatur   = MAX( rtrn, ( sio3eq(ji,jj,jk) - trb(ji,jj,jk,jpsil) ) / ( sio3eq(ji,jj,jk) + rtrn ) )
+               zsatur2  = ( 1. + tsn(ji,jj,jk,jp_tem) / 400.)**37
+               znusil   = 0.225  * ( 1. + tsn(ji,jj,jk,jp_tem) / 15.) * zsatur + 0.775 * zsatur2 * zsatur**9.25
+               ! Remineralization rate of BSi depedant on T and saturation
+               ! ---------------------------------------------------------
+               IF ( gdept_n(ji,jj,jk) > zdep ) THEN
+                  zfacsib(ji,jj,jk) = zfacsib(ji,jj,jk-1) * EXP( -0.5 * ( xsiremlab - xsirem )  &
+                  &                   * znusil * e3t_n(ji,jj,jk) / wsbio4(ji,jj,jk) )
+                  zfacsi(ji,jj,jk)  = zfacsib(ji,jj,jk) / ( 1.0 + zfacsib(ji,jj,jk) )
+                  zfacsib(ji,jj,jk) = zfacsib(ji,jj,jk) * EXP( -0.5 * ( xsiremlab - xsirem )    &
+                  &                   * znusil * e3t_n(ji,jj,jk) / wsbio4(ji,jj,jk) )
+               ENDIF
+               zsiremin = ( xsiremlab * zfacsi(ji,jj,jk) + xsirem * ( 1. - zfacsi(ji,jj,jk) ) ) * xstep * znusil
+               zosil    = zsiremin * trb(ji,jj,jk,jpgsi)
+               !
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) - zosil
+               tra(ji,jj,jk,jpsil) = tra(ji,jj,jk,jpsil) + zosil
+            END DO
+         END DO
+      END DO
+
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('rem3')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+          zrfact2 = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+          !
+          IF( iom_use( "REMIN" ) )  THEN !  Remineralisation rate
+             zolimi(:,:,jpk) = 0. ; CALL iom_put( "REMIN"  , zolimi(:,:,:) * tmask(:,:,:) * zrfact2  )
+          ENDIF
+          CALL iom_put( "DENIT"  , denitr(:,:,:) * rdenit * rno3 * tmask(:,:,:) * zrfact2 ) ! Denitrification 
+          IF( iom_use( "BACT" ) )  THEN ! Bacterial biomass
+             zdepbac(:,:,jpk) = 0.  ;   CALL iom_put( "BACT", zdepbac(:,:,:) * 1.E6 * tmask(:,:,:) )
+          ENDIF
+          CALL iom_put( "FEBACT" , zfebact(:,:,:) * 1E9 * tmask(:,:,:) * zrfact2  )
+       ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_rem')
+      !
+   END SUBROUTINE p4z_rem
+
+
+   SUBROUTINE p4z_rem_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_rem_init  ***
+      !!
+      !! ** Purpose :   Initialization of remineralization parameters
+      !!
+      !! ** Method  :   Read the nampisrem namelist and check the parameters
+      !!      called at the first timestep
+      !!
+      !! ** input   :   Namelist nampisrem
+      !!
+      !!----------------------------------------------------------------------
+      NAMELIST/nampisrem/ xremik, nitrif, xsirem, xsiremlab, xsilab, feratb, xkferb, & 
+         &                xremikc, xremikn, xremikp
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_rem_init : Initialization of remineralization parameters'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, nampisrem, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisrem in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, nampisrem, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisrem in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampisrem )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist parameters for remineralization, nampisrem'
+         IF( ln_p4z ) THEN
+            WRITE(numout,*) '      remineralization rate of DOC              xremik    =', xremik
+         ELSE
+            WRITE(numout,*) '      remineralization rate of DOC              xremikc   =', xremikc
+            WRITE(numout,*) '      remineralization rate of DON              xremikn   =', xremikn
+            WRITE(numout,*) '      remineralization rate of DOP              xremikp   =', xremikp
+         ENDIF
+         WRITE(numout,*) '      remineralization rate of Si               xsirem    =', xsirem
+         WRITE(numout,*) '      fast remineralization rate of Si          xsiremlab =', xsiremlab
+         WRITE(numout,*) '      fraction of labile biogenic silica        xsilab    =', xsilab
+         WRITE(numout,*) '      NH4 nitrification rate                    nitrif    =', nitrif
+         WRITE(numout,*) '      Bacterial Fe/C ratio                      feratb    =', feratb
+         WRITE(numout,*) '      Half-saturation constant for bact. Fe/C   xkferb    =', xkferb
+      ENDIF
+      !
+      denitr(:,:,:) = 0._wp
+      !
+   END SUBROUTINE p4z_rem_init
+
+
+   INTEGER FUNCTION p4z_rem_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_rem_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( denitr(jpi,jpj,jpk), STAT=p4z_rem_alloc )
+      !
+      IF( p4z_rem_alloc /= 0 )   CALL ctl_stop( 'STOP', 'p4z_rem_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION p4z_rem_alloc
+
+   !!======================================================================
+END MODULE p4zrem
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsbc.F90	(revision 14097)
@@ -0,0 +1,490 @@
+MODULE p4zsbc
+   !!======================================================================
+   !!                         ***  MODULE p4sbc  ***
+   !! TOP :   PISCES surface boundary conditions of external inputs of nutrients
+   !!======================================================================
+   !! History :   3.5  !  2012-07 (O. Aumont, C. Ethe) Original code
+   !!----------------------------------------------------------------------
+   !!   p4z_sbc        :  Read and interpolate time-varying nutrients fluxes
+   !!   p4z_sbc_init   :  Initialization of p4z_sbc
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE iom             !  I/O manager
+   USE fldread         !  time interpolation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_sbc
+   PUBLIC   p4z_sbc_init   
+
+   LOGICAL , PUBLIC ::   ln_dust      !: boolean for dust input from the atmosphere
+   LOGICAL , PUBLIC ::   ln_solub     !: boolean for variable solubility of atmospheric iron
+   LOGICAL , PUBLIC ::   ln_river     !: boolean for river input of nutrients
+   LOGICAL , PUBLIC ::   ln_ndepo     !: boolean for atmospheric deposition of N
+   LOGICAL , PUBLIC ::   ln_ironsed   !: boolean for Fe input from sediments
+   LOGICAL , PUBLIC ::   ln_hydrofe   !: boolean for Fe input from hydrothermal vents
+   REAL(wp), PUBLIC ::   sedfeinput   !: Coastal release of Iron
+   REAL(wp), PUBLIC ::   dustsolub    !: Solubility of the dust
+   REAL(wp), PUBLIC ::   mfrac        !: Mineral Content of the dust
+   REAL(wp), PUBLIC ::   icefeinput   !: Iron concentration in sea ice
+   REAL(wp), PUBLIC ::   wdust        !: Sinking speed of the dust 
+   REAL(wp), PUBLIC ::   nitrfix      !: Nitrogen fixation rate   
+   REAL(wp), PUBLIC ::   diazolight   !: Nitrogen fixation sensitivty to light 
+   REAL(wp), PUBLIC ::   concfediaz   !: Fe half-saturation Cste for diazotrophs 
+   REAL(wp)         ::   hratio       !: Fe:3He ratio assumed for vent iron supply
+   REAL(wp)         ::   distcoast    !: Distance off the coast for Iron from sediments
+   REAL(wp), PUBLIC ::   lgw_rath     !: Weak ligand ratio from hydro sources
+
+   LOGICAL , PUBLIC ::   ll_sbc
+   LOGICAL          ::   ll_solub
+
+   INTEGER , PARAMETER  :: jpriv  = 7   !: Maximum number of river input fields
+   INTEGER , PARAMETER  :: jr_dic = 1   !: index of dissolved inorganic carbon
+   INTEGER , PARAMETER  :: jr_doc = 2   !: index of dissolved organic carbon
+   INTEGER , PARAMETER  :: jr_din = 3   !: index of dissolved inorganic nitrogen
+   INTEGER , PARAMETER  :: jr_don = 4   !: index of dissolved organic nitrogen
+   INTEGER , PARAMETER  :: jr_dip = 5   !: index of dissolved inorganic phosporus
+   INTEGER , PARAMETER  :: jr_dop = 6   !: index of dissolved organic phosphorus
+   INTEGER , PARAMETER  :: jr_dsi = 7   !: index of dissolved silicate
+
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_dust      ! structure of input dust
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_solub     ! structure of input dust
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_river     ! structure of input riverdic
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_ndepo     ! structure of input nitrogen deposition
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_ironsed   ! structure of input iron from sediment
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_hydrofe   ! structure of input iron from hydrothermal vents
+
+   INTEGER , PARAMETER ::   nbtimes = 365                          ! maximum number of times record in a file
+   INTEGER             ::   ntimes_dust, ntimes_riv, ntimes_ndep   ! number of time steps in a file
+   INTEGER             ::   ntimes_solub, ntimes_hydro             ! number of time steps in a file
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   dust  , solub    !: dust fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rivdic, rivalk   !: river input fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rivdin, rivdip   !: river input fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rivdon, rivdop   !: river input fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rivdoc           !: river input fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   rivdsi           !: river input fields
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nitdep           !: atmospheric N deposition 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ironsed          !: Coastal supply of iron
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hydrofe          !: Hydrothermal vent supply of iron
+
+   REAL(wp), PUBLIC :: sedsilfrac, sedcalfrac
+   REAL(wp), PUBLIC :: rivalkinput, rivdicinput
+   REAL(wp), PUBLIC :: rivdininput, rivdipinput, rivdsiinput
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_sbc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine p4z_sbc  ***
+      !!
+      !! ** purpose :   read and interpolate the external sources of nutrients
+      !!
+      !! ** method  :   read the files and interpolate the appropriate variables
+      !!
+      !! ** input   :   external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      INTEGER  ::   ji, jj 
+      REAL(wp) ::   zcoef, zyyss
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_sbc')
+      !
+      ! Compute dust at nit000 or only if there is more than 1 time record in dust file
+      IF( ln_dust ) THEN
+         IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_dust > 1 ) ) THEN
+            CALL fld_read( kt, 1, sf_dust )
+            dust(:,:) = MAX( rtrn, sf_dust(1)%fnow(:,:,1) ) * ( 1.0 - fr_i(:,:) )
+         ENDIF
+      ENDIF
+      !
+      IF( ll_solub ) THEN
+         IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_solub > 1 ) ) THEN
+            CALL fld_read( kt, 1, sf_solub )
+            solub(:,:) = sf_solub(1)%fnow(:,:,1)
+         ENDIF
+      ENDIF
+
+      ! N/P and Si releases due to coastal rivers
+      ! Compute river at nit000 or only if there is more than 1 time record in river file
+      ! -----------------------------------------
+      IF( ln_river ) THEN
+         IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_riv > 1 ) ) THEN
+            CALL fld_read( kt, 1, sf_river )
+            IF( ln_p4z ) THEN
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zcoef = ryyss * e1e2t(ji,jj) * h_rnf(ji,jj) 
+                     rivalk(ji,jj) =   sf_river(jr_dic)%fnow(ji,jj,1)  &
+                        &              * 1.E3        / ( 12. * zcoef + rtrn )
+                     rivdic(ji,jj) =   sf_river(jr_dic)%fnow(ji,jj,1)  &
+                        &              * 1.E3         / ( 12. * zcoef + rtrn )
+                     rivdin(ji,jj) =   sf_river(jr_din)%fnow(ji,jj,1)  &
+                        &              * 1.E3 / rno3 / ( 14. * zcoef + rtrn )
+                     rivdip(ji,jj) =   sf_river(jr_dip)%fnow(ji,jj,1)  &
+                        &              * 1.E3 / po4r / ( 31. * zcoef + rtrn )
+                     rivdsi(ji,jj) =   sf_river(jr_dsi)%fnow(ji,jj,1)  &
+                        &              * 1.E3        / ( 28.1 * zcoef + rtrn )
+                     rivdoc(ji,jj) =   sf_river(jr_doc)%fnow(ji,jj,1)  &
+                        &              * 1.E3        / ( 12. * zcoef + rtrn ) 
+                  END DO
+               END DO
+            ELSE    !  ln_p5z
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     zcoef = ryyss * e1e2t(ji,jj) * h_rnf(ji,jj) 
+                     rivalk(ji,jj) =   sf_river(jr_dic)%fnow(ji,jj,1)                                    &
+                        &              * 1.E3        / ( 12. * zcoef + rtrn )
+                     rivdic(ji,jj) = ( sf_river(jr_dic)%fnow(ji,jj,1) ) &
+                        &              * 1.E3 / ( 12. * zcoef + rtrn ) * tmask(ji,jj,1)
+                     rivdin(ji,jj) = ( sf_river(jr_din)%fnow(ji,jj,1) ) &
+                        &              * 1.E3 / rno3 / ( 14. * zcoef + rtrn ) * tmask(ji,jj,1)
+                     rivdip(ji,jj) = ( sf_river(jr_dip)%fnow(ji,jj,1) ) &
+                        &              * 1.E3 / po4r / ( 31. * zcoef + rtrn ) * tmask(ji,jj,1)
+                     rivdon(ji,jj) = ( sf_river(jr_don)%fnow(ji,jj,1) ) &
+                        &              * 1.E3 / rno3 / ( 14. * zcoef + rtrn ) * tmask(ji,jj,1)
+                     rivdop(ji,jj) = ( sf_river(jr_dop)%fnow(ji,jj,1) ) &
+                        &              * 1.E3 / po4r / ( 31. * zcoef + rtrn ) * tmask(ji,jj,1)
+                     rivdsi(ji,jj) =   sf_river(jr_dsi)%fnow(ji,jj,1)  &
+                        &              * 1.E3        / ( 28.1 * zcoef + rtrn )
+                     rivdoc(ji,jj) =   sf_river(jr_doc)%fnow(ji,jj,1)  &
+                        &              * 1.E3        / ( 12. * zcoef + rtrn )
+                  END DO
+               END DO
+            ENDIF
+         ENDIF
+      ENDIF
+
+      ! Compute N deposition at nit000 or only if there is more than 1 time record in N deposition file
+      IF( ln_ndepo ) THEN
+         IF( kt == nit000 .OR. ( kt /= nit000 .AND. ntimes_ndep > 1 ) ) THEN
+             zcoef = 14. * rno3
+             CALL fld_read( kt, 1, sf_ndepo )
+             nitdep(:,:) = MAX( rtrn, sf_ndepo(1)%fnow(:,:,1) / zcoef / e3t_n(:,:,1) )
+         ENDIF
+         IF( .NOT.ln_linssh ) THEN
+            zcoef = 14. * rno3
+            nitdep(:,:) = MAX( rtrn, sf_ndepo(1)%fnow(:,:,1) / zcoef / e3t_n(:,:,1) )
+         ENDIF
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_sbc')
+      !
+   END SUBROUTINE p4z_sbc
+
+
+   SUBROUTINE p4z_sbc_init
+      !!----------------------------------------------------------------------
+      !!                  ***  routine p4z_sbc_init  ***
+      !!
+      !! ** purpose :   initialization of the external sources of nutrients
+      !!
+      !! ** method  :   read the files and compute the budget
+      !!                called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   external netcdf files
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER  :: ji, jj, jk, jm, ifpr
+      INTEGER  :: ii0, ii1, ij0, ij1
+      INTEGER  :: numdust, numsolub, numriv, numiron, numdepo, numhydro
+      INTEGER  :: ierr, ierr1, ierr2, ierr3
+      INTEGER  :: ios                 ! Local integer output status for namelist read
+      INTEGER  :: ik50                !  last level where depth less than 50 m
+      INTEGER  :: isrow             ! index for ORCA1 starting row
+      REAL(wp) :: zexpide, zdenitide, zmaskt, zsurfc, zsurfp,ze3t, ze3t2, zcslp
+      REAL(wp) :: ztimes_dust, ztimes_riv, ztimes_ndep 
+      REAL(wp), DIMENSION(:), ALLOCATABLE :: rivinput
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: zriver, zcmask
+      !
+      CHARACTER(len=100) ::  cn_dir          ! Root directory for location of ssr files
+      TYPE(FLD_N), DIMENSION(jpriv) ::  slf_river    ! array of namelist informations on the fields to read
+      TYPE(FLD_N) ::   sn_dust, sn_solub, sn_ndepo, sn_ironsed, sn_hydrofe   ! informations about the fields to be read
+      TYPE(FLD_N) ::   sn_riverdoc, sn_riverdic, sn_riverdsi   ! informations about the fields to be read
+      TYPE(FLD_N) ::   sn_riverdin, sn_riverdon, sn_riverdip, sn_riverdop
+      !!
+      NAMELIST/nampissbc/cn_dir, sn_dust, sn_solub, sn_riverdic, sn_riverdoc, sn_riverdin, sn_riverdon,     &
+        &                sn_riverdip, sn_riverdop, sn_riverdsi, sn_ndepo, sn_ironsed, sn_hydrofe, &
+        &                ln_dust, ln_solub, ln_river, ln_ndepo, ln_ironsed, ln_ironice, ln_hydrofe,    &
+        &                sedfeinput, distcoast, dustsolub, icefeinput, wdust, mfrac, nitrfix, diazolight, concfediaz, &
+        &                hratio, lgw_rath
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_sbc_init : initialization of the external sources of nutrients '
+         WRITE(numout,*) '~~~~~~~~~~~~ '
+      ENDIF
+      !                            !* set file information
+      REWIND( numnatp_ref )              ! Namelist nampissbc in reference namelist : Pisces external sources of nutrients
+      READ  ( numnatp_ref, nampissbc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampissbc in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampissbc in configuration namelist : Pisces external sources of nutrients
+      READ  ( numnatp_cfg, nampissbc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampissbc in configuration namelist' )
+      IF(lwm) WRITE ( numonp, nampissbc )
+
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist : nampissbc '
+         WRITE(numout,*) '      dust input from the atmosphere           ln_dust     = ', ln_dust
+         WRITE(numout,*) '      Variable solubility of iron input        ln_solub    = ', ln_solub
+         WRITE(numout,*) '      river input of nutrients                 ln_river    = ', ln_river
+         WRITE(numout,*) '      atmospheric deposition of n              ln_ndepo    = ', ln_ndepo
+         WRITE(numout,*) '      Fe input from sediments                  ln_ironsed  = ', ln_ironsed
+         WRITE(numout,*) '      Fe input from seaice                     ln_ironice  = ', ln_ironice
+         WRITE(numout,*) '      fe input from hydrothermal vents         ln_hydrofe  = ', ln_hydrofe
+         WRITE(numout,*) '      coastal release of iron                  sedfeinput  = ', sedfeinput
+         WRITE(numout,*) '      distance off the coast                   distcoast   = ', distcoast
+         WRITE(numout,*) '      solubility of the dust                   dustsolub   = ', dustsolub
+         WRITE(numout,*) '      Mineral Fe content of the dust           mfrac       = ', mfrac
+         WRITE(numout,*) '      Iron concentration in sea ice            icefeinput  = ', icefeinput
+         WRITE(numout,*) '      sinking speed of the dust                wdust       = ', wdust
+         WRITE(numout,*) '      nitrogen fixation rate                   nitrfix     = ', nitrfix
+         WRITE(numout,*) '      nitrogen fixation sensitivty to light    diazolight  = ', diazolight
+         WRITE(numout,*) '      Fe half-saturation cste for diazotrophs  concfediaz  = ', concfediaz
+         WRITE(numout,*) '      Fe to 3He ratio assumed for vent iron supply hratio  = ', hratio
+         IF( ln_ligand ) THEN
+            WRITE(numout,*) '      Weak ligand ratio from sed hydro sources  lgw_rath   = ', lgw_rath
+         ENDIF
+      END IF
+
+      IF( ln_dust .OR. ln_river .OR. ln_ndepo ) THEN   ;   ll_sbc = .TRUE.
+      ELSE                                             ;   ll_sbc = .FALSE.
+      ENDIF
+
+      IF( ln_dust .AND. ln_solub ) THEN                ;   ll_solub = .TRUE.
+      ELSE                                             ;   ll_solub = .FALSE.
+      ENDIF
+
+      ! dust input from the atmosphere
+      ! ------------------------------
+      IF( ln_dust ) THEN 
+         !
+         IF(lwp) WRITE(numout,*) '    initialize dust input from atmosphere '
+         IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
+         !
+         ALLOCATE( dust(jpi,jpj) )    ! allocation
+         !
+         ALLOCATE( sf_dust(1), STAT=ierr )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+         IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'p4z_sed_init: unable to allocate sf_dust structure' )
+         !
+         CALL fld_fill( sf_dust, (/ sn_dust /), cn_dir, 'p4z_sed_init', 'Atmospheric dust deposition', 'nampissed' )
+                                   ALLOCATE( sf_dust(1)%fnow(jpi,jpj,1)   )
+         IF( sn_dust%ln_tint )     ALLOCATE( sf_dust(1)%fdta(jpi,jpj,1,2) )
+         !
+         IF( Agrif_Root() ) THEN   !  Only on the master grid
+            ! Get total input dust ; need to compute total atmospheric supply of Si in a year
+            CALL iom_open (  TRIM( sn_dust%clname ) , numdust )
+            ntimes_dust = iom_getszuld( numdust )   ! get number of record in file
+         END IF
+      END IF
+
+      ! Solubility of dust deposition of iron
+      ! Only if ln_dust and ln_solubility set to true (ll_solub = .true.)
+      ! -----------------------------------------------------------------
+      IF( ll_solub ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   ll_solub=T , initialize variable solubility of Fe '
+         !
+         ALLOCATE( solub(jpi,jpj) )    ! allocation
+         !
+         ALLOCATE( sf_solub(1), STAT=ierr )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+         IF( ierr > 0 )   CALL ctl_stop( 'STOP', 'p4z_sed_init: unable to allocate sf_solub structure' )
+         !
+         CALL fld_fill( sf_solub, (/ sn_solub /), cn_dir, 'p4z_sed_init', 'Solubility of atm. iron ', 'nampissed' )
+                                   ALLOCATE( sf_solub(1)%fnow(jpi,jpj,1)   )
+         IF( sn_solub%ln_tint )    ALLOCATE( sf_solub(1)%fdta(jpi,jpj,1,2) )
+         ! get number of record in file
+         CALL iom_open (  TRIM( sn_solub%clname ) , numsolub )
+         ntimes_solub = iom_getszuld( numsolub )   ! get number of record in file
+         CALL iom_close( numsolub )
+      ENDIF
+
+      ! nutrient input from rivers
+      ! --------------------------
+      IF( ln_river ) THEN
+         !
+         slf_river(jr_dic) = sn_riverdic   ;   slf_river(jr_doc) = sn_riverdoc   ;   slf_river(jr_din) = sn_riverdin 
+         slf_river(jr_don) = sn_riverdon   ;   slf_river(jr_dip) = sn_riverdip   ;   slf_river(jr_dop) = sn_riverdop
+         slf_river(jr_dsi) = sn_riverdsi  
+         !
+         ALLOCATE( rivdic(jpi,jpj), rivalk(jpi,jpj), rivdin(jpi,jpj), rivdip(jpi,jpj), rivdsi(jpi,jpj), rivdoc(jpi,jpj) ) 
+         IF( ln_p5z )  ALLOCATE( rivdon(jpi,jpj), rivdop(jpi,jpj) )
+         !
+         ALLOCATE( sf_river(jpriv), rivinput(jpriv), STAT=ierr1 )    !* allocate and fill sf_river (forcing structure) with sn_river_
+         rivinput(:) = 0._wp
+
+         IF( ierr1 > 0 )   CALL ctl_stop( 'STOP', 'p4z_sed_init: unable to allocate sf_irver structure' )
+         !
+         CALL fld_fill( sf_river, slf_river, cn_dir, 'p4z_sed_init', 'Input from river ', 'nampissed' )
+         DO ifpr = 1, jpriv
+                                          ALLOCATE( sf_river(ifpr)%fnow(jpi,jpj,1  ) )
+            IF( slf_river(ifpr)%ln_tint ) ALLOCATE( sf_river(ifpr)%fdta(jpi,jpj,1,2) )
+         END DO
+         IF( Agrif_Root() ) THEN   !  Only on the master grid
+            ! Get total input rivers ; need to compute total river supply in a year
+            DO ifpr = 1, jpriv
+               CALL iom_open ( TRIM( slf_river(ifpr)%clname ), numriv )
+               ntimes_riv = iom_getszuld( numriv )
+               ALLOCATE( zriver(jpi,jpj,ntimes_riv) )
+               DO jm = 1, ntimes_riv
+                  CALL iom_get( numriv, jpdom_data, TRIM( slf_river(ifpr)%clvar ), zriver(:,:,jm), jm )
+               END DO
+               CALL iom_close( numriv )
+               ztimes_riv = 1._wp / REAL(ntimes_riv, wp) 
+               DO jm = 1, ntimes_riv
+                  rivinput(ifpr) = rivinput(ifpr) + glob_sum( 'p4zsbc', zriver(:,:,jm) * tmask(:,:,1) * ztimes_riv ) 
+               END DO
+               DEALLOCATE( zriver)
+            END DO
+            ! N/P and Si releases due to coastal rivers
+            ! -----------------------------------------
+            rivdicinput = (rivinput(jr_dic) + rivinput(jr_doc) ) * 1E3 / 12._wp
+            rivdininput = (rivinput(jr_din) + rivinput(jr_don) ) * 1E3 / rno3 / 14._wp
+            rivdipinput = (rivinput(jr_dip) + rivinput(jr_dop) ) * 1E3 / po4r / 31._wp
+            rivdsiinput = rivinput(jr_dsi) * 1E3 / 28.1_wp
+            rivalkinput = rivinput(jr_dic) * 1E3 / 12._wp
+            !
+         ENDIF
+      ELSE
+         rivdicinput = 0._wp
+         rivdininput = 0._wp
+         rivdipinput = 0._wp
+         rivdsiinput = 0._wp
+         rivalkinput = 0._wp
+      END IF 
+      ! nutrient input from dust
+      ! ------------------------
+      IF( ln_ndepo ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   ln_ndepo=T , initialize the nutrient input by dust from NetCDF file'
+         !
+         ALLOCATE( nitdep(jpi,jpj) )    ! allocation
+         !
+         ALLOCATE( sf_ndepo(1), STAT=ierr3 )           !* allocate and fill sf_sst (forcing structure) with sn_sst
+         IF( ierr3 > 0 )   CALL ctl_stop( 'STOP', 'p4z_sed_init: unable to allocate sf_ndepo structure' )
+         !
+         CALL fld_fill( sf_ndepo, (/ sn_ndepo /), cn_dir, 'p4z_sed_init', 'Nutrient atmospheric depositon ', 'nampissed' )
+                                   ALLOCATE( sf_ndepo(1)%fnow(jpi,jpj,1)   )
+         IF( sn_ndepo%ln_tint )    ALLOCATE( sf_ndepo(1)%fdta(jpi,jpj,1,2) )
+         !
+         IF( Agrif_Root() ) THEN   !  Only on the master grid
+            ! Get total input dust ; need to compute total atmospheric supply of N in a year
+            CALL iom_open ( TRIM( sn_ndepo%clname ), numdepo )
+            ntimes_ndep = iom_getszuld( numdepo )
+         ENDIF
+      ENDIF
+
+      ! coastal and island masks
+      ! ------------------------
+      IF( ln_ironsed ) THEN     
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   ln_ironsed=T , computation of an island mask to enhance coastal supply of iron'
+         !
+         ALLOCATE( ironsed(jpi,jpj,jpk) )    ! allocation
+         !
+         CALL iom_open ( TRIM( sn_ironsed%clname ), numiron )
+         ALLOCATE( zcmask(jpi,jpj,jpk) )
+         CALL iom_get  ( numiron, jpdom_data, TRIM( sn_ironsed%clvar ), zcmask(:,:,:), 1 )
+         CALL iom_close( numiron )
+         !
+         ik50 = 5        !  last level where depth less than 50 m
+         DO jk = jpkm1, 1, -1
+            IF( gdept_1d(jk) > 50. )   ik50 = jk - 1
+         END DO
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' Level corresponding to 50m depth ',  ik50,' ', gdept_1d(ik50+1)
+         DO jk = 1, ik50
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  ze3t   = e3t_0(ji,jj,jk)
+                  zsurfc =  e1u(ji,jj) * ( 1. - umask(ji  ,jj  ,jk) )   &
+                          + e1u(ji,jj) * ( 1. - umask(ji-1,jj  ,jk) )   &
+                          + e2v(ji,jj) * ( 1. - vmask(ji  ,jj  ,jk) )   &
+                          + e2v(ji,jj) * ( 1. - vmask(ji  ,jj-1,jk) )
+                  zsurfp = zsurfc * ze3t / e1e2t(ji,jj)
+                  ! estimation of the coastal slope : 5 km off the coast
+                  ze3t2 = ze3t * ze3t
+                  zcslp = SQRT( ( distcoast*distcoast + ze3t2 ) / ze3t2 )
+                  !
+                  zcmask(ji,jj,jk) = zcmask(ji,jj,jk) + zcslp * zsurfp
+               END DO
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( 'p4zsbc', zcmask , 'T', 1. )      ! lateral boundary conditions on cmask   (sign unchanged)
+         !
+         DO jk = 1, jpk
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zexpide   = MIN( 8.,( gdept_n(ji,jj,jk) / 500. )**(-1.5) )
+                  zdenitide = -0.9543 + 0.7662 * LOG( zexpide ) - 0.235 * LOG( zexpide )**2
+                  zcmask(ji,jj,jk) = zcmask(ji,jj,jk) * MIN( 1., EXP( zdenitide ) / 0.5 )
+               END DO
+            END DO
+         END DO
+         ! Coastal supply of iron
+         ! -------------------------
+         ironsed(:,:,jpk) = 0._wp
+         DO jk = 1, jpkm1
+            ironsed(:,:,jk) = sedfeinput * zcmask(:,:,jk) / ( e3t_0(:,:,jk) * rday )
+         END DO
+         DEALLOCATE( zcmask)
+      ENDIF
+      !
+      ! Iron from Hydrothermal vents
+      ! ------------------------
+      IF( ln_hydrofe ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) '   ==>>>   ln_hydrofe=T , Input of iron from hydrothermal vents'
+         !
+         ALLOCATE( hydrofe(jpi,jpj,jpk) )    ! allocation
+         !
+         CALL iom_open ( TRIM( sn_hydrofe%clname ), numhydro )
+         CALL iom_get  ( numhydro, jpdom_data, TRIM( sn_hydrofe%clvar ), hydrofe(:,:,:), 1 )
+         CALL iom_close( numhydro )
+         !
+         DO jk = 1, jpk
+            hydrofe(:,:,jk) = ( hydrofe(:,:,jk) * hratio ) / ( e1e2t(:,:) * e3t_0(:,:,jk) * ryyss + rtrn ) / 1000._wp
+         ENDDO
+         !
+      ENDIF
+      ! 
+      IF( ll_sbc ) CALL p4z_sbc( nit000 ) 
+      !
+      IF(lwp) THEN 
+         WRITE(numout,*)
+         WRITE(numout,*) '    Total input of elements from river supply'
+         WRITE(numout,*) '    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    N Supply   : ', rivdininput*rno3*1E3/1E12*14.,' TgN/yr'
+         WRITE(numout,*) '    Si Supply  : ', rivdsiinput*1E3/1E12*28.1    ,' TgSi/yr'
+         WRITE(numout,*) '    P Supply   : ', rivdipinput*1E3*po4r/1E12*31.,' TgP/yr'
+         WRITE(numout,*) '    Alk Supply : ', rivalkinput*1E3/1E12         ,' Teq/yr'
+         WRITE(numout,*) '    DIC Supply : ', rivdicinput*1E3*12./1E12     ,' TgC/yr'
+         WRITE(numout,*) 
+      ENDIF
+      !
+      sedsilfrac = 0.03     ! percentage of silica loss in the sediments
+      sedcalfrac = 0.6      ! percentage of calcite loss in the sediments
+      !
+   END SUBROUTINE p4z_sbc_init
+
+   !!======================================================================
+END MODULE p4zsbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsed.F90	(revision 14097)
@@ -0,0 +1,497 @@
+MODULE p4zsed
+   !!======================================================================
+   !!                         ***  MODULE p4sed  ***
+   !! TOP :   PISCES Compute loss of organic matter in the sediments
+   !!======================================================================
+   !! History :   1.0  !  2004-03 (O. Aumont) Original code
+   !!             2.0  !  2007-12 (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06 (C. Ethe) USE of fldread
+   !!             3.5  !  2012-07 (O. Aumont) improvment of river input of nutrients 
+   !!----------------------------------------------------------------------
+   !!   p4z_sed        :  Compute loss of organic matter in the sediments
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zlim          !  Co-limitations of differents nutrients
+   USE p4zsbc          !  External source of nutrients 
+   USE p4zint          !  interpolation and computation of various fields
+   USE sed             !  Sediment module
+   USE iom             !  I/O manager
+   USE prtctl_trc      !  print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_sed  
+   PUBLIC   p4z_sed_alloc
+ 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: nitrpot    !: Nitrogen fixation 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:  ) :: sdenit     !: Nitrate reduction in the sediments
+   REAL(wp) :: r1_rday                  !: inverse of rday
+   LOGICAL, SAVE :: lk_sed
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_sed( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_sed  ***
+      !!
+      !! ** Purpose :   Compute loss of organic matter in the sediments. This
+      !!              is by no way a sediment model. The loss is simply 
+      !!              computed to balance the inout from rivers and dust
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) ::   kt, knt ! ocean time step
+      INTEGER  ::  ji, jj, jk, ikt
+      REAL(wp) ::  zrivalk, zrivsil, zrivno3
+      REAL(wp) ::  zwflux, zlim, zfact, zfactcal
+      REAL(wp) ::  zo2, zno3, zflx, zpdenit, z1pdenit, zolimit
+      REAL(wp) ::  zsiloss, zcaloss, zws3, zws4, zwsc, zdep
+      REAL(wp) ::  zwstpoc, zwstpon, zwstpop
+      REAL(wp) ::  ztrfer, ztrpo4s, ztrdp, zwdust, zmudia, ztemp
+      REAL(wp) ::  xdiano3, xdianh4
+      !
+      CHARACTER (len=25) :: charout
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zdenit2d, zbureff, zwork
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zwsbio3, zwsbio4
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zsedcal, zsedsi, zsedc
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zsoufer, zlight
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: ztrpo4, ztrdop, zirondep, zpdep
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:  ) :: zsidep, zironice
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('p4z_sed')
+      !
+      IF( kt == nittrc000 .AND. knt == 1 )   THEN
+          r1_rday  = 1. / rday
+          IF (ln_sediment .AND. ln_sed_2way) THEN
+             lk_sed = .TRUE.
+          ELSE
+             lk_sed = .FALSE.
+          ENDIF
+      ENDIF
+      !
+      IF( kt == nittrc000 .AND. knt == 1 )   r1_rday  = 1. / rday
+      !
+      ! Allocate temporary workspace
+      ALLOCATE( ztrpo4(jpi,jpj,jpk) )
+      IF( ln_p5z )    ALLOCATE( ztrdop(jpi,jpj,jpk) )
+
+      zdenit2d(:,:) = 0.e0
+      zbureff (:,:) = 0.e0
+      zwork   (:,:) = 0.e0
+      zsedsi  (:,:) = 0.e0
+      zsedcal (:,:) = 0.e0
+      zsedc   (:,:) = 0.e0
+
+      ! Iron input/uptake due to sea ice : Crude parameterization based on Lancelot et al.
+      ! ----------------------------------------------------
+      IF( ln_ironice ) THEN  
+         !                                              
+         ALLOCATE( zironice(jpi,jpj) )
+         !                                              
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zdep    = rfact2 / e3t_n(ji,jj,1)
+               zwflux  = fmmflx(ji,jj) / 1000._wp
+               zironice(ji,jj) =  MAX( -0.99 * trb(ji,jj,1,jpfer), -zwflux * icefeinput * zdep )
+            END DO
+         END DO
+         !
+         tra(:,:,1,jpfer) = tra(:,:,1,jpfer) + zironice(:,:) 
+         ! 
+         IF( lk_iomput .AND. knt == nrdttrc )   &
+            &   CALL iom_put( "Ironice", zironice(:,:) * 1.e+3 * rfact2r * e3t_n(:,:,1) * tmask(:,:,1) ) ! iron flux from ice
+         !
+         DEALLOCATE( zironice )
+         !                                              
+      ENDIF
+
+      ! Add the external input of nutrients from dust deposition
+      ! ----------------------------------------------------------
+      IF( ln_dust ) THEN
+         !                                              
+         ALLOCATE( zsidep(jpi,jpj), zpdep(jpi,jpj,jpk), zirondep(jpi,jpj,jpk) )
+         !                                              ! Iron and Si deposition at the surface
+         IF( ln_solub ) THEN
+            zirondep(:,:,1) = solub(:,:) * dust(:,:) * mfrac * rfact2 / e3t_n(:,:,1) / 55.85 + 3.e-10 * r1_ryyss 
+         ELSE
+            zirondep(:,:,1) = dustsolub  * dust(:,:) * mfrac * rfact2 / e3t_n(:,:,1) / 55.85 + 3.e-10 * r1_ryyss 
+         ENDIF
+         zsidep(:,:)   = 8.8 * 0.075 * dust(:,:) * mfrac * rfact2 / e3t_n(:,:,1) / 28.1 
+         zpdep (:,:,1) = 0.1 * 0.021 * dust(:,:) * mfrac * rfact2 / e3t_n(:,:,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
+         zwdust = 0.03 * rday / ( wdust * 55.85 ) / ( 270. * rday )
+         DO jk = 2, jpkm1
+            zirondep(:,:,jk) = dust(:,:) * mfrac * zwdust * rfact2 * EXP( -gdept_n(:,:,jk) / 540. )
+            zpdep   (:,:,jk) = zirondep(:,:,jk) * 0.023
+         END DO
+         !                                              ! Iron solubilization of particles in the water column
+         tra(:,:,1,jpsil) = tra(:,:,1,jpsil) + zsidep  (:,:)
+         DO jk = 1, jpkm1
+            tra(:,:,jk,jppo4) = tra(:,:,jk,jppo4) + zpdep   (:,:,jk)
+            tra(:,:,jk,jpfer) = tra(:,:,jk,jpfer) + zirondep(:,:,jk) 
+         ENDDO
+         ! 
+         IF( lk_iomput .AND. knt == nrdttrc ) THEN
+             CALL iom_put( "Irondep", zirondep(:,:,1) * 1.e+3 * rfact2r * e3t_n(:,:,1) * tmask(:,:,1) ) ! surface downward dust depo of iron
+             CALL iom_put( "pdust"  , dust(:,:) / ( wdust * rday )  * tmask(:,:,1) ) ! dust concentration at surface
+         ENDIF
+         DEALLOCATE( zsidep, zpdep, zirondep )
+         !                                              
+      ENDIF
+     
+      ! Add the external input of nutrients from river
+      ! ----------------------------------------------------------
+      IF( ln_river ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               DO jk = 1, nk_rnf(ji,jj)
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) +  rivdip(ji,jj) * rfact2
+                  tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) +  rivdin(ji,jj) * rfact2
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) +  rivdic(ji,jj) * 5.e-5 * rfact2
+                  tra(ji,jj,jk,jpsil) = tra(ji,jj,jk,jpsil) +  rivdsi(ji,jj) * rfact2
+                  tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) +  rivdic(ji,jj) * rfact2
+                  tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) +  ( rivalk(ji,jj) - rno3 * rivdin(ji,jj) ) * rfact2
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) +  rivdoc(ji,jj) * rfact2
+               ENDDO
+            ENDDO
+         ENDDO
+         IF (ln_ligand) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  DO jk = 1, nk_rnf(ji,jj)
+                     tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) +  rivdic(ji,jj) * 5.e-5 * rfact2
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDIF
+         IF( ln_p5z ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  DO jk = 1, nk_rnf(ji,jj)
+                     tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + rivdop(ji,jj) * rfact2
+                     tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + rivdon(ji,jj) * rfact2
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDIF
+      ENDIF
+      
+      ! Add the external input of nutrients from nitrogen deposition
+      ! ----------------------------------------------------------
+      IF( ln_ndepo ) THEN
+         tra(:,:,1,jpno3) = tra(:,:,1,jpno3) + nitdep(:,:) * rfact2
+         tra(:,:,1,jptal) = tra(:,:,1,jptal) - rno3 * nitdep(:,:) * rfact2
+      ENDIF
+
+      ! Add the external input of iron from hydrothermal vents
+      ! ------------------------------------------------------
+      IF( ln_hydrofe ) THEN
+            tra(:,:,:,jpfer) = tra(:,:,:,jpfer) + hydrofe(:,:,:) * rfact2
+         IF( ln_ligand ) THEN
+            tra(:,:,:,jplgw) = tra(:,:,:,jplgw) + ( hydrofe(:,:,:) * lgw_rath ) * rfact2
+         ENDIF
+         !
+         IF( lk_iomput .AND. knt == nrdttrc )   &
+            &   CALL iom_put( "HYDR", hydrofe(:,:,:) * 1.e+3 * tmask(:,:,:) ) ! hydrothermal iron input
+      ENDIF
+
+      ! OA: Warning, the following part is necessary to avoid CFL problems above the sediments
+      ! --------------------------------------------------------------------
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ikt  = mbkt(ji,jj)
+            zdep = e3t_n(ji,jj,ikt) / xstep
+            zwsbio4(ji,jj) = MIN( 0.99 * zdep, wsbio4(ji,jj,ikt) )
+            zwsbio3(ji,jj) = MIN( 0.99 * zdep, wsbio3(ji,jj,ikt) )
+         END DO
+      END DO
+      !
+      IF( .NOT.lk_sed ) THEN
+!
+         ! Add the external input of iron from sediment mobilization
+         ! ------------------------------------------------------
+         IF( ln_ironsed ) THEN
+                            tra(:,:,:,jpfer) = tra(:,:,:,jpfer) + ironsed(:,:,:) * rfact2
+            !
+            IF( lk_iomput .AND. knt == nrdttrc )   &
+               &   CALL iom_put( "Ironsed", ironsed(:,:,:) * 1.e+3 * tmask(:,:,:) ) ! iron inputs from sediments
+         ENDIF
+
+         ! Computation of the sediment denitrification proportion: The metamodel from midlleburg (2006) is being used
+         ! Computation of the fraction of organic matter that is permanently buried from Dunne's model
+         ! -------------------------------------------------------
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+              IF( tmask(ji,jj,1) == 1 ) THEN
+                 ikt = mbkt(ji,jj)
+                 zflx = (  trb(ji,jj,ikt,jpgoc) * zwsbio4(ji,jj)   &
+                   &     + trb(ji,jj,ikt,jppoc) * zwsbio3(ji,jj) )  * 1E3 * 1E6 / 1E4
+                 zflx  = LOG10( MAX( 1E-3, zflx ) )
+                 zo2   = LOG10( MAX( 10. , trb(ji,jj,ikt,jpoxy) * 1E6 ) )
+                 zno3  = LOG10( MAX( 1.  , trb(ji,jj,ikt,jpno3) * 1E6 * rno3 ) )
+                 zdep  = LOG10( gdepw_n(ji,jj,ikt+1) )
+                 zdenit2d(ji,jj) = -2.2567 - 1.185 * zflx - 0.221 * zflx**2 - 0.3995 * zno3 * zo2 + 1.25 * zno3    &
+                   &                + 0.4721 * zo2 - 0.0996 * zdep + 0.4256 * zflx * zo2
+                 zdenit2d(ji,jj) = 10.0**( zdenit2d(ji,jj) )
+                   !
+                 zflx = (  trb(ji,jj,ikt,jpgoc) * zwsbio4(ji,jj)   &
+                   &     + trb(ji,jj,ikt,jppoc) * zwsbio3(ji,jj) ) * 1E6
+                 zbureff(ji,jj) = 0.013 + 0.53 * zflx**2 / ( 7.0 + zflx )**2
+              ENDIF
+            END DO
+         END DO 
+         !
+      ENDIF
+
+      ! This loss is scaled at each bottom grid cell for equilibrating the total budget of silica in the ocean.
+      ! Thus, the amount of silica lost in the sediments equal the supply at the surface (dust+rivers)
+      ! ------------------------------------------------------
+      IF( .NOT.lk_sed )  zrivsil = 1._wp - sedsilfrac
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ikt  = mbkt(ji,jj)
+            zdep = xstep / e3t_n(ji,jj,ikt) 
+            zwsc = zwsbio4(ji,jj) * zdep
+            zsiloss = trb(ji,jj,ikt,jpgsi) * zwsc
+            zcaloss = trb(ji,jj,ikt,jpcal) * zwsc
+            !
+            tra(ji,jj,ikt,jpgsi) = tra(ji,jj,ikt,jpgsi) - zsiloss
+            tra(ji,jj,ikt,jpcal) = tra(ji,jj,ikt,jpcal) - zcaloss
+         END DO
+      END DO
+      !
+      IF( .NOT.lk_sed ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikt  = mbkt(ji,jj)
+               zdep = xstep / e3t_n(ji,jj,ikt) 
+               zwsc = zwsbio4(ji,jj) * zdep
+               zsiloss = trb(ji,jj,ikt,jpgsi) * zwsc
+               zcaloss = trb(ji,jj,ikt,jpcal) * zwsc
+               tra(ji,jj,ikt,jpsil) = tra(ji,jj,ikt,jpsil) + zsiloss * zrivsil 
+               !
+               zfactcal = MIN( excess(ji,jj,ikt), 0.2 )
+               zfactcal = MIN( 1., 1.3 * ( 0.2 - zfactcal ) / ( 0.4 - zfactcal ) )
+               zrivalk  = sedcalfrac * zfactcal
+               tra(ji,jj,ikt,jptal) =  tra(ji,jj,ikt,jptal) + zcaloss * zrivalk * 2.0
+               tra(ji,jj,ikt,jpdic) =  tra(ji,jj,ikt,jpdic) + zcaloss * zrivalk
+               zsedcal(ji,jj) = (1.0 - zrivalk) * zcaloss * e3t_n(ji,jj,ikt) 
+               zsedsi (ji,jj) = (1.0 - zrivsil) * zsiloss * e3t_n(ji,jj,ikt) 
+            END DO
+         END DO
+      ENDIF
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ikt  = mbkt(ji,jj)
+            zdep = xstep / e3t_n(ji,jj,ikt) 
+            zws4 = zwsbio4(ji,jj) * zdep
+            zws3 = zwsbio3(ji,jj) * zdep
+            tra(ji,jj,ikt,jpgoc) = tra(ji,jj,ikt,jpgoc) - trb(ji,jj,ikt,jpgoc) * zws4 
+            tra(ji,jj,ikt,jppoc) = tra(ji,jj,ikt,jppoc) - trb(ji,jj,ikt,jppoc) * zws3
+            tra(ji,jj,ikt,jpbfe) = tra(ji,jj,ikt,jpbfe) - trb(ji,jj,ikt,jpbfe) * zws4
+            tra(ji,jj,ikt,jpsfe) = tra(ji,jj,ikt,jpsfe) - trb(ji,jj,ikt,jpsfe) * zws3
+         END DO
+      END DO
+      !
+      IF( ln_p5z ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikt  = mbkt(ji,jj)
+               zdep = xstep / e3t_n(ji,jj,ikt) 
+               zws4 = zwsbio4(ji,jj) * zdep
+               zws3 = zwsbio3(ji,jj) * zdep
+               tra(ji,jj,ikt,jpgon) = tra(ji,jj,ikt,jpgon) - trb(ji,jj,ikt,jpgon) * zws4
+               tra(ji,jj,ikt,jppon) = tra(ji,jj,ikt,jppon) - trb(ji,jj,ikt,jppon) * zws3
+               tra(ji,jj,ikt,jpgop) = tra(ji,jj,ikt,jpgop) - trb(ji,jj,ikt,jpgop) * zws4
+               tra(ji,jj,ikt,jppop) = tra(ji,jj,ikt,jppop) - trb(ji,jj,ikt,jppop) * zws3
+            END DO
+         END DO
+      ENDIF
+
+      IF( .NOT.lk_sed ) THEN
+         ! The 0.5 factor in zpdenit is to avoid negative NO3 concentration after
+         ! denitrification in the sediments. Not very clever, but simpliest option.
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikt  = mbkt(ji,jj)
+               zdep = xstep / e3t_n(ji,jj,ikt) 
+               zws4 = zwsbio4(ji,jj) * zdep
+               zws3 = zwsbio3(ji,jj) * zdep
+               zrivno3 = 1. - zbureff(ji,jj)
+               zwstpoc = trb(ji,jj,ikt,jpgoc) * zws4 + trb(ji,jj,ikt,jppoc) * zws3
+               zpdenit  = MIN( 0.5 * ( trb(ji,jj,ikt,jpno3) - rtrn ) / rdenit, zdenit2d(ji,jj) * zwstpoc * zrivno3 )
+               z1pdenit = zwstpoc * zrivno3 - zpdenit
+               zolimit = MIN( ( trb(ji,jj,ikt,jpoxy) - rtrn ) / o2ut, z1pdenit * ( 1.- nitrfac(ji,jj,ikt) ) )
+               tra(ji,jj,ikt,jpdoc) = tra(ji,jj,ikt,jpdoc) + z1pdenit - zolimit
+               tra(ji,jj,ikt,jppo4) = tra(ji,jj,ikt,jppo4) + zpdenit + zolimit
+               tra(ji,jj,ikt,jpnh4) = tra(ji,jj,ikt,jpnh4) + zpdenit + zolimit
+               tra(ji,jj,ikt,jpno3) = tra(ji,jj,ikt,jpno3) - rdenit * zpdenit
+               tra(ji,jj,ikt,jpoxy) = tra(ji,jj,ikt,jpoxy) - zolimit * o2ut
+               tra(ji,jj,ikt,jptal) = tra(ji,jj,ikt,jptal) + rno3 * (zolimit + (1.+rdenit) * zpdenit )
+               tra(ji,jj,ikt,jpdic) = tra(ji,jj,ikt,jpdic) + zpdenit + zolimit 
+               sdenit(ji,jj) = rdenit * zpdenit * e3t_n(ji,jj,ikt)
+               zsedc(ji,jj)   = (1. - zrivno3) * zwstpoc * e3t_n(ji,jj,ikt)
+               IF( ln_p5z ) THEN
+                  zwstpop              = trb(ji,jj,ikt,jpgop) * zws4 + trb(ji,jj,ikt,jppop) * zws3
+                  zwstpon              = trb(ji,jj,ikt,jpgon) * zws4 + trb(ji,jj,ikt,jppon) * zws3
+                  tra(ji,jj,ikt,jpdon) = tra(ji,jj,ikt,jpdon) + ( z1pdenit - zolimit ) * zwstpon / (zwstpoc + rtrn)
+                  tra(ji,jj,ikt,jpdop) = tra(ji,jj,ikt,jpdop) + ( z1pdenit - zolimit ) * zwstpop / (zwstpoc + rtrn)
+               ENDIF
+            END DO
+         END DO
+       ENDIF
+
+
+      ! Nitrogen fixation process
+      ! Small source iron from particulate inorganic iron
+      !-----------------------------------
+      DO jk = 1, jpkm1
+         zlight (:,:,jk) =  ( 1.- EXP( -etot_ndcy(:,:,jk) / diazolight ) ) * ( 1. - fr_i(:,:) ) 
+         zsoufer(:,:,jk) = zlight(:,:,jk) * 2E-11 / ( 2E-11 + biron(:,:,jk) )
+      ENDDO
+      IF( ln_p4z ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !                      ! Potential nitrogen fixation dependant on temperature and iron
+                  ztemp = tsn(ji,jj,jk,jp_tem)
+                  zmudia = MAX( 0.,-0.001096*ztemp**2 + 0.057*ztemp -0.637 ) * 7.625
+                  !       Potential nitrogen fixation dependant on temperature and iron
+                  xdianh4 = trb(ji,jj,jk,jpnh4) / ( concnnh4 + trb(ji,jj,jk,jpnh4) )
+                  xdiano3 = trb(ji,jj,jk,jpno3) / ( concnno3 + trb(ji,jj,jk,jpno3) ) * (1. - xdianh4)
+                  zlim = ( 1.- xdiano3 - xdianh4 )
+                  IF( zlim <= 0.1 )   zlim = 0.01
+                  zfact = zlim * rfact2
+                  ztrfer = biron(ji,jj,jk) / ( concfediaz + biron(ji,jj,jk) )
+                  ztrpo4(ji,jj,jk) = trb(ji,jj,jk,jppo4) / ( 1E-6 + trb(ji,jj,jk,jppo4) )
+                  ztrdp = ztrpo4(ji,jj,jk)
+                  nitrpot(ji,jj,jk) =  zmudia * r1_rday * zfact * MIN( ztrfer, ztrdp ) * zlight(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ELSE       ! p5z
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !                      ! Potential nitrogen fixation dependant on temperature and iron
+                  ztemp = tsn(ji,jj,jk,jp_tem)
+                  zmudia = MAX( 0.,-0.001096*ztemp**2 + 0.057*ztemp -0.637 ) * 7.625
+                  !       Potential nitrogen fixation dependant on temperature and iron
+                  xdianh4 = trb(ji,jj,jk,jpnh4) / ( concnnh4 + trb(ji,jj,jk,jpnh4) )
+                  xdiano3 = trb(ji,jj,jk,jpno3) / ( concnno3 + trb(ji,jj,jk,jpno3) ) * (1. - xdianh4)
+                  zlim = ( 1.- xdiano3 - xdianh4 )
+                  IF( zlim <= 0.1 )   zlim = 0.01
+                  zfact = zlim * rfact2
+                  ztrfer = biron(ji,jj,jk) / ( concfediaz + biron(ji,jj,jk) )
+                  ztrpo4(ji,jj,jk) = trb(ji,jj,jk,jppo4) / ( 1E-6 + trb(ji,jj,jk,jppo4) )
+                  ztrdop(ji,jj,jk) = trb(ji,jj,jk,jpdop) / ( 1E-6 + trb(ji,jj,jk,jpdop) ) * (1. - ztrpo4(ji,jj,jk))
+                  ztrdp = ztrpo4(ji,jj,jk) + ztrdop(ji,jj,jk)
+                  nitrpot(ji,jj,jk) =  zmudia * r1_rday * zfact * MIN( ztrfer, ztrdp ) * zlight(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+      ENDIF
+
+      ! Nitrogen change due to nitrogen fixation
+      ! ----------------------------------------
+      IF( ln_p4z ) THEN
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zfact = nitrpot(ji,jj,jk) * nitrfix
+                  tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zfact / 3.0
+                  tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * zfact / 3.0
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) - zfact * 2.0 / 3.0
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zfact * 1.0 / 3.0
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zfact * 1.0 / 3.0 * 2.0 / 3.0
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zfact * 1.0 / 3.0 * 1.0 / 3.0
+                  tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) + ( o2ut + o2nit ) * zfact * 2.0 / 3.0 + o2nit * zfact / 3.0
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - 30E-6 * zfact * 1.0 / 3.0
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + 30E-6 * zfact * 1.0 / 3.0 * 2.0 / 3.0
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + 30E-6 * zfact * 1.0 / 3.0 * 1.0 / 3.0
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + 0.002 * 4E-10 * zsoufer(ji,jj,jk) * rfact2 / rday
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + concdnh4 / ( concdnh4 + trb(ji,jj,jk,jppo4) ) &
+                  &                     * 0.001 * trb(ji,jj,jk,jpdoc) * xstep
+              END DO
+            END DO 
+         END DO
+      ELSE    ! p5z
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zfact = nitrpot(ji,jj,jk) * nitrfix
+                  tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zfact / 3.0
+                  tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * zfact / 3.0
+                  tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) - 16.0 / 46.0 * zfact * ( 1.0 - 1.0 / 3.0 ) &
+                  &                     * ztrpo4(ji,jj,jk) / (ztrpo4(ji,jj,jk) + ztrdop(ji,jj,jk) + rtrn)
+                  tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + zfact * 1.0 / 3.0
+                  tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zfact * 1.0 / 3.0
+                  tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + 16.0 / 46.0 * zfact / 3.0  &
+                  &                     - 16.0 / 46.0 * zfact * ztrdop(ji,jj,jk)   &
+                  &                     / (ztrpo4(ji,jj,jk) + ztrdop(ji,jj,jk) + rtrn)
+                  tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zfact * 1.0 / 3.0 * 2.0 / 3.0
+                  tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + zfact * 1.0 / 3.0 * 2.0 /3.0
+                  tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + 16.0 / 46.0 * zfact * 1.0 / 3.0 * 2.0 /3.0
+                  tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zfact * 1.0 / 3.0 * 1.0 / 3.0
+                  tra(ji,jj,jk,jpgon) = tra(ji,jj,jk,jpgon) + zfact * 1.0 / 3.0 * 1.0 /3.0
+                  tra(ji,jj,jk,jpgop) = tra(ji,jj,jk,jpgop) + 16.0 / 46.0 * zfact * 1.0 / 3.0 * 1.0 /3.0
+                  tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) + ( o2ut + o2nit ) * zfact * 2.0 / 3.0 + o2nit * zfact / 3.0
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - 30E-6 * zfact * 1.0 / 3.0 
+                  tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + 30E-6 * zfact * 1.0 / 3.0 * 2.0 / 3.0
+                  tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + 30E-6 * zfact * 1.0 / 3.0 * 1.0 / 3.0
+                  tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + 0.002 * 4E-10 * zsoufer(ji,jj,jk) * rfact2 / rday
+              END DO
+            END DO 
+         END DO
+         !
+      ENDIF
+
+      IF( lk_iomput ) THEN
+         IF( knt == nrdttrc ) THEN
+            zfact = 1.e+3 * rfact2r !  conversion from molC/l/kt  to molN/m3/s
+            CALL iom_put( "Nfix", nitrpot(:,:,:) * nitrfix * rno3 * zfact * tmask(:,:,:) )  ! nitrogen fixation 
+            CALL iom_put( "SedCal", zsedcal(:,:) * zfact )
+            CALL iom_put( "SedSi",  zsedsi (:,:) * zfact )
+            CALL iom_put( "SedC",   zsedc  (:,:) * zfact )
+            CALL iom_put( "Sdenit", sdenit (:,:) * zfact * rno3 )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl) THEN  ! print mean trends (USEd for debugging)
+         WRITE(charout, fmt="('sed ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_p5z )    DEALLOCATE( ztrpo4, ztrdop )
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_sed')
+      !
+   END SUBROUTINE p4z_sed
+
+
+   INTEGER FUNCTION p4z_sed_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_sed_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( nitrpot(jpi,jpj,jpk), sdenit(jpi,jpj), STAT=p4z_sed_alloc )
+      !
+      IF( p4z_sed_alloc /= 0 )   CALL ctl_stop( 'STOP', 'p4z_sed_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION p4z_sed_alloc
+
+   !!======================================================================
+END MODULE p4zsed
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsink.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsink.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsink.F90	(revision 14097)
@@ -0,0 +1,197 @@
+MODULE p4zsink
+   !!======================================================================
+   !!                         ***  MODULE p4zsink  ***
+   !! TOP :  PISCES  vertical flux of particulate matter due to gravitational sinking
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Change aggregation formula
+   !!             3.5  !  2012-07  (O. Aumont) Introduce potential time-splitting
+   !!----------------------------------------------------------------------
+   !!   p4z_sink       :  Compute vertical flux of particulate matter due to gravitational sinking
+   !!   p4z_sink_init  :  Unitialisation of sinking speed parameters
+   !!   p4z_sink_alloc :  Allocate sinking speed variables
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE trcsink         !  General routine to compute sedimentation
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+   USE lib_mpp
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_sink         ! called in p4zbio.F90
+   PUBLIC   p4z_sink_init    ! called in trcsms_pisces.F90
+   PUBLIC   p4z_sink_alloc
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinking, sinking2  !: POC sinking fluxes 
+   !                                                          !  (different meanings depending on the parameterization)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinkingn, sinking2n  !: POC sinking fluxes 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinkingp, sinking2p  !: POC sinking fluxes 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinkcal, sinksil   !: CaCO3 and BSi sinking fluxes
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinkfer            !: Small BFe sinking fluxes
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sinkfer2           !: Big iron sinking fluxes
+
+   INTEGER  :: ik100
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   !!----------------------------------------------------------------------
+   !!   'standard sinking parameterisation'                  ???
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE p4z_sink ( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_sink  ***
+      !!
+      !! ** Purpose :   Compute vertical flux of particulate matter due to 
+      !!                gravitational sinking
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) :: kt, knt
+      INTEGER  ::   ji, jj, jk
+      CHARACTER (len=25) :: charout
+      REAL(wp) :: zmax, zfact
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_sink')
+
+      ! Initialization of some global variables
+      ! ---------------------------------------
+      prodpoc(:,:,:) = 0.
+      conspoc(:,:,:) = 0.
+      prodgoc(:,:,:) = 0.
+      consgoc(:,:,:) = 0.
+
+      !
+      !    Sinking speeds of detritus is increased with depth as shown
+      !    by data and from the coagulation theory
+      !    -----------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1,jpi
+               zmax  = MAX( heup_01(ji,jj), hmld(ji,jj) )
+               zfact = MAX( 0., gdepw_n(ji,jj,jk+1) - zmax ) / wsbio2scale
+               wsbio4(ji,jj,jk) = wsbio2 + MAX(0., ( wsbio2max - wsbio2 )) * zfact
+            END DO
+         END DO
+      END DO
+
+      ! limit the values of the sinking speeds to avoid numerical instabilities  
+      wsbio3(:,:,:) = wsbio
+
+      !
+      !  Initializa to zero all the sinking arrays 
+      !   -----------------------------------------
+      sinking (:,:,:) = 0.e0
+      sinking2(:,:,:) = 0.e0
+      sinkcal (:,:,:) = 0.e0
+      sinkfer (:,:,:) = 0.e0
+      sinksil (:,:,:) = 0.e0
+      sinkfer2(:,:,:) = 0.e0
+
+      !   Compute the sedimentation term using p4zsink2 for all the sinking particles
+      !   -----------------------------------------------------
+      CALL trc_sink( kt, wsbio3, sinking , jppoc, rfact2 )
+      CALL trc_sink( kt, wsbio3, sinkfer , jpsfe, rfact2 )
+      CALL trc_sink( kt, wsbio4, sinking2, jpgoc, rfact2 )
+      CALL trc_sink( kt, wsbio4, sinkfer2, jpbfe, rfact2 )
+      CALL trc_sink( kt, wsbio4, sinksil , jpgsi, rfact2 )
+      CALL trc_sink( kt, wsbio4, sinkcal , jpcal, rfact2 )
+
+      IF( ln_p5z ) THEN
+         sinkingn (:,:,:) = 0.e0
+         sinking2n(:,:,:) = 0.e0
+         sinkingp (:,:,:) = 0.e0
+         sinking2p(:,:,:) = 0.e0
+
+         !   Compute the sedimentation term using p4zsink2 for all the sinking particles
+         !   -----------------------------------------------------
+         CALL trc_sink( kt, wsbio3, sinkingn , jppon, rfact2 )
+         CALL trc_sink( kt, wsbio3, sinkingp , jppop, rfact2 )
+         CALL trc_sink( kt, wsbio4, sinking2n, jpgon, rfact2 )
+         CALL trc_sink( kt, wsbio4, sinking2p, jpgop, rfact2 )
+      ENDIF
+
+     ! Total carbon export per year
+     IF( iom_use( "tcexp" ) .OR. ( ln_check_mass .AND. kt == nitend .AND. knt == nrdttrc )  )  &
+        &   t_oce_co2_exp = glob_sum( 'p4zsink', ( sinking(:,:,ik100) + sinking2(:,:,ik100) ) * e1e2t(:,:) * tmask(:,:,1) )
+     !
+     IF( lk_iomput .AND.  knt == nrdttrc ) THEN
+       zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+       !
+       CALL iom_put( "EPC100"  , ( sinking(:,:,ik100) + sinking2(:,:,ik100) ) * zfact * tmask(:,:,1) ) ! Export of carbon at 100m 
+       CALL iom_put( "EPFE100" , ( sinkfer(:,:,ik100) + sinkfer2(:,:,ik100) ) * zfact * tmask(:,:,1) ) ! Export of iron at 100m 
+       CALL iom_put( "EPCAL100", sinkcal(:,:,ik100) * zfact * tmask(:,:,1) )      ! Export of calcite at 100m 
+       CALL iom_put( "EPSI100" , sinksil(:,:,ik100) * zfact * tmask(:,:,1) )          ! Export of bigenic silica at 100m 
+       CALL iom_put( "EXPC"    , ( sinking(:,:,:) + sinking2(:,:,:) ) * zfact * tmask(:,:,:) ) ! Export of carbon in the water column 
+       CALL iom_put( "EXPFE"   , ( sinkfer(:,:,:) + sinkfer2(:,:,:) ) * zfact * tmask(:,:,:) ) ! Export of iron  
+       CALL iom_put( "EXPCAL"  , sinkcal(:,:,:) * zfact * tmask(:,:,:) )      ! Export of calcite 
+       CALL iom_put( "EXPSI"   , sinksil(:,:,:) * zfact * tmask(:,:,:) )      ! Export of bigenic silica
+       CALL iom_put( "tcexp"   , t_oce_co2_exp * zfact )   ! molC/s
+       ! 
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('sink')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p4z_sink')
+      !
+   END SUBROUTINE p4z_sink
+
+
+   SUBROUTINE p4z_sink_init
+      !!----------------------------------------------------------------------
+      !!                  ***  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
+      !
+   END SUBROUTINE p4z_sink_init
+
+   INTEGER FUNCTION p4z_sink_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_sink_alloc  ***
+      !!----------------------------------------------------------------------
+      INTEGER :: ierr(2)
+      !!----------------------------------------------------------------------
+      !
+      ierr(:) = 0
+      !
+      ALLOCATE( sinking(jpi,jpj,jpk) , sinking2(jpi,jpj,jpk)                    ,     &                
+         &      sinkcal(jpi,jpj,jpk) , sinksil (jpi,jpj,jpk)                    ,     &                
+         &      sinkfer2(jpi,jpj,jpk)                                           ,     &                
+         &      sinkfer(jpi,jpj,jpk)                                            , STAT=ierr(1) )                
+         !
+      IF( ln_p5z    ) ALLOCATE( sinkingn(jpi,jpj,jpk), sinking2n(jpi,jpj,jpk)   ,     &
+         &                      sinkingp(jpi,jpj,jpk), sinking2p(jpi,jpj,jpk)   , STAT=ierr(2) )
+      !
+      p4z_sink_alloc = MAXVAL( ierr )
+      IF( p4z_sink_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p4z_sink_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p4z_sink_alloc
+   
+   !!======================================================================
+END MODULE p4zsink
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsms.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsms.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p4zsms.F90	(revision 14097)
@@ -0,0 +1,592 @@
+MODULE p4zsms
+   !!======================================================================
+   !!                         ***  MODULE p4zsms  ***
+   !! TOP :   PISCES Source Minus Sink manager
+   !!======================================================================
+   !! History :   1.0  !  2004-03 (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   p4z_sms        : Time loop of passive tracers sms
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables 
+   USE trcdta          ! 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE p4zbio          ! Biological model
+   USE p4zche          ! Chemical model
+   USE p4zlys          ! Calcite saturation
+   USE p4zflx          ! Gas exchange
+   USE p4zsbc          ! External source of nutrients
+   USE p4zsed          ! Sedimentation
+   USE p4zint          ! time interpolation
+   USE p4zrem          ! remineralisation
+   USE iom             ! I/O manager
+   USE trd_oce         ! Ocean trends variables
+   USE trdtrc          ! TOP trends variables
+   USE sedmodel        ! Sediment model
+   USE prtctl_trc      ! print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p4z_sms_init   ! called in p4zsms.F90
+   PUBLIC   p4z_sms        ! called in p4zsms.F90
+
+   INTEGER ::    numco2, numnut, numnit      ! logical unit for co2 budget
+   REAL(wp) ::   alkbudget, no3budget, silbudget, ferbudget, po4budget
+   REAL(wp) ::   xfact, xfact1, xfact2, xfact3
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xnegtr     ! Array used to indicate negative tracer values
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p4z_sms( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_sms  ***
+      !!
+      !! ** Purpose :   Managment of the call to Biological sources and sinks 
+      !!              routines of PISCES bio-model
+      !!
+      !! ** Method  : - at each new day ...
+      !!              - several calls of bio and sed ???
+      !!              - ...
+      !!---------------------------------------------------------------------
+      !
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !!
+      INTEGER ::   ji, jj, jk, jnt, jn, jl
+      REAL(wp) ::  ztra
+      CHARACTER (len=25) :: charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:    ) :: zw2d
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:  ) :: zw3d
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jp_pisces) :: ztrbbio
+
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p4z_sms')
+      !
+      IF( kt == nittrc000 ) THEN
+        !
+        ALLOCATE( xnegtr(jpi,jpj,jpk) )
+        !
+        IF( .NOT. ln_rsttr ) THEN
+            CALL p4z_che                              ! initialize the chemical constants
+            CALL ahini_for_at(hi)   !  set PH at kt=nit000
+            t_oce_co2_flx_cum = 0._wp
+        ELSE
+            CALL p4z_rst( nittrc000, 'READ' )  !* read or initialize all required fields
+        ENDIF
+        !
+      ENDIF
+      !
+      IF( ln_pisdmp .AND. MOD( kt - nn_dttrc, nn_pisdmp ) == 0 )   CALL p4z_dmp( kt )      ! Relaxation of some tracers
+      !
+      rfact = r2dttrc
+      !
+      IF( ( ln_top_euler .AND. kt == nittrc000 )  .OR. ( .NOT.ln_top_euler .AND. kt <= nittrc000 + nn_dttrc ) ) THEN
+         rfactr  = 1. / rfact
+         rfact2  = rfact / REAL( nrdttrc, wp )
+         rfact2r = 1. / rfact2
+         xstep = rfact2 / rday         ! Time step duration for biology
+         xfact = 1.e+3 * rfact2r
+         IF(lwp) WRITE(numout,*) 
+         IF(lwp) WRITE(numout,*) '    Passive Tracer  time step    rfact  = ', rfact, ' rdt = ', rdt
+         IF(lwp) write(numout,*) '    PISCES  Biology time step    rfact2 = ', rfact2
+         IF(lwp) WRITE(numout,*)
+      ENDIF
+
+      IF( ( neuler == 0 .AND. kt == nittrc000 ) .OR. ln_top_euler ) THEN
+         DO jn = jp_pcs0, jp_pcs1              !   SMS on tracer without Asselin time-filter
+            trb(:,:,:,jn) = trn(:,:,:,jn)
+         END DO
+      ENDIF
+
+      DO jn = jp_pcs0, jp_pcs1              !   Store the tracer concentrations before entering PISCES
+         ztrbbio(:,:,:,jn) = trb(:,:,:,jn)
+      END DO
+
+      !
+      IF( ll_sbc ) CALL p4z_sbc( kt )   ! external sources of nutrients 
+      !
+#if ! defined key_sed_off
+      CALL p4z_che              ! computation of chemical constants
+      CALL p4z_int( kt )        ! computation of various rates for biogeochemistry
+      !
+      DO jnt = 1, nrdttrc          ! Potential time splitting if requested
+         !
+         CALL p4z_bio( kt, jnt )   ! Biology
+         CALL p4z_lys( kt, jnt )   ! Compute CaCO3 saturation
+         CALL p4z_sed( kt, jnt )   ! Surface and Bottom boundary conditions
+         CALL p4z_flx( kt, jnt )   ! Compute surface fluxes
+         !
+         xnegtr(:,:,:) = 1.e0
+         DO jn = jp_pcs0, jp_pcs1
+            DO jk = 1, jpk
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( ( trb(ji,jj,jk,jn) + tra(ji,jj,jk,jn) ) < 0.e0 ) THEN
+                        ztra             = ABS( trb(ji,jj,jk,jn) ) / ( ABS( tra(ji,jj,jk,jn) ) + rtrn )
+                        xnegtr(ji,jj,jk) = MIN( xnegtr(ji,jj,jk),  ztra )
+                     ENDIF
+                 END DO
+               END DO
+            END DO
+         END DO
+         !                                ! where at least 1 tracer concentration becomes negative
+         !                                ! 
+         DO jn = jp_pcs0, jp_pcs1
+           trb(:,:,:,jn) = trb(:,:,:,jn) + xnegtr(:,:,:) * tra(:,:,:,jn)
+         END DO
+        
+        !
+        IF(  iom_use( 'INTdtAlk' ) .OR. iom_use( 'INTdtDIC' ) .OR. iom_use( 'INTdtFer' ) .OR.  &
+          &  iom_use( 'INTdtDIN' ) .OR. iom_use( 'INTdtDIP' ) .OR. iom_use( 'INTdtSil' ) )  THEN
+          !
+          ALLOCATE( zw3d(jpi,jpj,jpk), zw2d(jpi,jpj) )
+          zw3d(:,:,jpk) = 0.
+          DO jk = 1, jpkm1
+              zw3d(:,:,jk) = xnegtr(:,:,jk) * xfact * e3t_n(:,:,jk) * tmask(:,:,jk)
+          ENDDO
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * tra(:,:,jk,jptal)
+          ENDDO
+          CALL iom_put( 'INTdtAlk', zw2d )
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * tra(:,:,jk,jpdic)
+          ENDDO
+          CALL iom_put( 'INTdtDIC', zw2d )
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * rno3 * ( tra(:,:,jk,jpno3) + tra(:,:,jk,jpnh4) )
+          ENDDO
+          CALL iom_put( 'INTdtDIN', zw2d )
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * po4r * tra(:,:,jk,jppo4)
+          ENDDO
+          CALL iom_put( 'INTdtDIP', zw2d )
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * tra(:,:,jk,jpfer)
+          ENDDO
+          CALL iom_put( 'INTdtFer', zw2d )
+          !
+          zw2d(:,:) = 0.
+          DO jk = 1, jpkm1
+             zw2d(:,:) = zw2d(:,:) + zw3d(:,:,jk) * tra(:,:,jk,jpsil)
+          ENDDO
+          CALL iom_put( 'INTdtSil', zw2d )
+          !
+          DEALLOCATE( zw3d, zw2d )
+        ENDIF
+        !
+        DO jn = jp_pcs0, jp_pcs1
+           tra(:,:,:,jn) = 0._wp
+        END DO
+        !
+      END DO
+      !
+#endif
+      !
+      IF( ln_sediment ) THEN 
+         !
+         CALL sed_model( kt )     !  Main program of Sediment model
+         !
+      ENDIF
+      !
+      DO jn = jp_pcs0, jp_pcs1
+         tra(:,:,:,jn) = ( trb(:,:,:,jn) - ztrbbio(:,:,:,jn) ) * rfactr
+         trb(:,:,:,jn) = ztrbbio(:,:,:,jn)
+         ztrbbio(:,:,:,jn) = 0._wp
+      END DO
+      !
+      IF( l_trdtrc ) THEN
+         DO jn = jp_pcs0, jp_pcs1
+           CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
+         END DO
+      END IF
+      !  
+      IF( lrst_trc )  CALL p4z_rst( kt, 'WRITE' )  !* Write PISCES informations in restart file 
+      !
+
+      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
+      !
+      IF( ln_timing )  CALL timing_stop('p4z_sms')
+      !
+   END SUBROUTINE p4z_sms
+
+
+   SUBROUTINE p4z_sms_init
+      !!----------------------------------------------------------------------
+      !!                     ***  p4z_sms_init  ***  
+      !!
+      !! ** Purpose :   read PISCES namelist
+      !!
+      !! ** input   :   file 'namelist.trc.s' containing the following
+      !!             namelist: natext, natbio, natsms
+      !!----------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/nampisbio/ nrdttrc, wsbio, xkmort, ferat3, wsbio2, wsbio2max, wsbio2scale,    &
+         &                   ldocp, ldocz, lthet, no3rat3, po4rat3
+         !
+      NAMELIST/nampisdmp/ ln_pisdmp, nn_pisdmp
+      NAMELIST/nampismass/ ln_check_mass
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'p4z_sms_init : PISCES initialization'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist nampisbio in reference namelist : Pisces variables
+      READ  ( numnatp_ref, nampisbio, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisbio in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampisbio in configuration namelist : Pisces variables
+      READ  ( numnatp_cfg, nampisbio, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisbio in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampisbio )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) '   Namelist : nampisbio'
+         WRITE(numout,*) '      frequency for the biology                 nrdttrc     =', nrdttrc
+         WRITE(numout,*) '      POC sinking speed                         wsbio       =', wsbio
+         WRITE(numout,*) '      half saturation constant for mortality    xkmort      =', xkmort 
+         IF( ln_p5z ) THEN
+            WRITE(numout,*) '      N/C in zooplankton                        no3rat3     =', no3rat3
+            WRITE(numout,*) '      P/C in zooplankton                        po4rat3     =', po4rat3
+         ENDIF
+         WRITE(numout,*) '      Fe/C in zooplankton                       ferat3      =', ferat3
+         WRITE(numout,*) '      Big particles sinking speed               wsbio2      =', wsbio2
+         WRITE(numout,*) '      Big particles maximum sinking speed       wsbio2max   =', wsbio2max
+         WRITE(numout,*) '      Big particles sinking speed length scale  wsbio2scale =', wsbio2scale
+         IF( ln_ligand ) THEN
+            IF( ln_p4z ) THEN
+               WRITE(numout,*) '      Phyto ligand production per unit doc           ldocp  =', ldocp
+               WRITE(numout,*) '      Zoo ligand production per unit doc             ldocz  =', ldocz
+               WRITE(numout,*) '      Proportional loss of ligands due to Fe uptake  lthet  =', lthet
+            ENDIF
+         ENDIF
+      ENDIF
+
+
+      REWIND( numnatp_ref )              ! Namelist nampisdmp in reference namelist : Pisces damping
+      READ  ( numnatp_ref, nampisdmp, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampisdmp in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampisdmp in configuration namelist : Pisces damping
+      READ  ( numnatp_cfg, nampisdmp, IOSTAT = ios, ERR = 906 )
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampisdmp in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampisdmp )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist : nampisdmp --- relaxation to GLODAP'
+         WRITE(numout,*) '      Relaxation of tracer to glodap mean value   ln_pisdmp =', ln_pisdmp
+         WRITE(numout,*) '      Frequency of Relaxation                     nn_pisdmp =', nn_pisdmp
+      ENDIF
+
+      REWIND( numnatp_ref )              ! Namelist nampismass in reference namelist : Pisces mass conservation check
+      READ  ( numnatp_ref, nampismass, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampismass in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampismass in configuration namelist : Pisces mass conservation check 
+      READ  ( numnatp_cfg, nampismass, IOSTAT = ios, ERR = 908 )
+908   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampismass in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampismass )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Namelist : nampismass  --- mass conservation checking'
+         WRITE(numout,*) '      Flag to check mass conservation of NO3/Si/TALK   ln_check_mass = ', ln_check_mass
+      ENDIF
+      !
+   END SUBROUTINE p4z_sms_init
+
+
+   SUBROUTINE p4z_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE p4z_rst  ***
+      !!
+      !!  ** Purpose : Read or write variables in restart file:
+      !!
+      !!  WRITE(READ) mode:
+      !!       kt        : number of time step since the begining of the experiment at the
+      !!                   end of the current(previous) run
+      !!---------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      !!---------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) ' p4z_rst : Read specific variables from pisces model '
+         IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~'
+         ! 
+         IF( iom_varid( numrtr, 'PH', ldstop = .FALSE. ) > 0 ) THEN
+            CALL iom_get( numrtr, jpdom_autoglo, 'PH' , hi(:,:,:)  )
+         ELSE
+            CALL p4z_che                              ! initialize the chemical constants
+            CALL ahini_for_at(hi)
+         ENDIF
+         CALL iom_get( numrtr, jpdom_autoglo, 'Silicalim', xksi(:,:) )
+         IF( iom_varid( numrtr, 'Silicamax', ldstop = .FALSE. ) > 0 ) THEN
+            CALL iom_get( numrtr, jpdom_autoglo, 'Silicamax' , xksimax(:,:)  )
+         ELSE
+            xksimax(:,:) = xksi(:,:)
+         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
+         !
+         IF( ln_p5z ) THEN
+            IF( iom_varid( numrtr, 'sized', ldstop = .FALSE. ) > 0 ) THEN
+               CALL iom_get( numrtr, jpdom_autoglo, 'sizep' , sizep(:,:,:)  )
+               CALL iom_get( numrtr, jpdom_autoglo, 'sizen' , sizen(:,:,:)  )
+               CALL iom_get( numrtr, jpdom_autoglo, 'sized' , sized(:,:,:)  )
+            ELSE
+               sizep(:,:,:) = 1.
+               sizen(:,:,:) = 1.
+               sized(:,:,:) = 1.
+            ENDIF
+        ENDIF
+        !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
+         IF( kt == nitrst ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'p4z_rst : write pisces restart file  kt =', kt
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         CALL iom_rstput( kt, nitrst, numrtw, 'PH', hi(:,:,:) )
+         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 )
+         IF( ln_p5z ) THEN
+            CALL iom_rstput( kt, nitrst, numrtw, 'sizep', sizep(:,:,:) )
+            CALL iom_rstput( kt, nitrst, numrtw, 'sizen', sizen(:,:,:) )
+            CALL iom_rstput( kt, nitrst, numrtw, 'sized', sized(:,:,:) )
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE p4z_rst
+
+
+   SUBROUTINE p4z_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  p4z_dmp  ***
+      !!
+      !! ** purpose  : Relaxation of some tracers
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT( in )  ::     kt ! time step
+      !
+      REAL(wp) ::  alkmean = 2426.     ! mean value of alkalinity ( Glodap ; for Goyet 2391. )
+      REAL(wp) ::  po4mean = 2.165     ! mean value of phosphates
+      REAL(wp) ::  no3mean = 30.90     ! mean value of nitrate
+      REAL(wp) ::  silmean = 91.51     ! mean value of silicate
+      !
+      REAL(wp) :: zarea, zalksumn, zpo4sumn, zno3sumn, zsilsumn
+      REAL(wp) :: zalksumb, zpo4sumb, zno3sumb, zsilsumb
+      !!---------------------------------------------------------------------
+
+      IF(lwp)  WRITE(numout,*)
+      IF(lwp)  WRITE(numout,*) ' p4z_dmp : Restoring of nutrients at time-step kt = ', kt
+      IF(lwp)  WRITE(numout,*)
+
+      IF( cn_cfg == "ORCA" .OR. cn_cfg == "orca") THEN
+         IF( .NOT. lk_c1d ) THEN      ! ORCA configuration (not 1D) !
+            !                                                ! --------------------------- !
+            ! set total alkalinity, phosphate, nitrate & silicate
+            zarea          = 1._wp / glob_sum( 'p4zsms', cvol(:,:,:) ) * 1e6              
+
+            zalksumn = glob_sum( 'p4zsms', trn(:,:,:,jptal) * cvol(:,:,:)  ) * zarea
+            zpo4sumn = glob_sum( 'p4zsms', trn(:,:,:,jppo4) * cvol(:,:,:)  ) * zarea * po4r
+            zno3sumn = glob_sum( 'p4zsms', trn(:,:,:,jpno3) * cvol(:,:,:)  ) * zarea * rno3
+            zsilsumn = glob_sum( 'p4zsms', trn(:,:,:,jpsil) * cvol(:,:,:)  ) * zarea
+ 
+            IF(lwp) WRITE(numout,*) '       TALKN mean : ', zalksumn
+            trn(:,:,:,jptal) = trn(:,:,:,jptal) * alkmean / zalksumn
+
+            IF(lwp) WRITE(numout,*) '       PO4N  mean : ', zpo4sumn
+            trn(:,:,:,jppo4) = trn(:,:,:,jppo4) * po4mean / zpo4sumn
+
+            IF(lwp) WRITE(numout,*) '       NO3N  mean : ', zno3sumn
+            trn(:,:,:,jpno3) = trn(:,:,:,jpno3) * no3mean / zno3sumn
+
+            IF(lwp) WRITE(numout,*) '       SiO3N mean : ', zsilsumn
+            trn(:,:,:,jpsil) = MIN( 400.e-6,trn(:,:,:,jpsil) * silmean / zsilsumn )
+            !
+            !
+            IF( .NOT. ln_top_euler ) THEN
+               zalksumb = glob_sum( 'p4zsms', trb(:,:,:,jptal) * cvol(:,:,:)  ) * zarea
+               zpo4sumb = glob_sum( 'p4zsms', trb(:,:,:,jppo4) * cvol(:,:,:)  ) * zarea * po4r
+               zno3sumb = glob_sum( 'p4zsms', trb(:,:,:,jpno3) * cvol(:,:,:)  ) * zarea * rno3
+               zsilsumb = glob_sum( 'p4zsms', trb(:,:,:,jpsil) * cvol(:,:,:)  ) * zarea
+ 
+               IF(lwp) WRITE(numout,*) ' '
+               IF(lwp) WRITE(numout,*) '       TALKB mean : ', zalksumb
+               trb(:,:,:,jptal) = trb(:,:,:,jptal) * alkmean / zalksumb
+
+               IF(lwp) WRITE(numout,*) '       PO4B  mean : ', zpo4sumb
+               trb(:,:,:,jppo4) = trb(:,:,:,jppo4) * po4mean / zpo4sumb
+
+               IF(lwp) WRITE(numout,*) '       NO3B  mean : ', zno3sumb
+               trb(:,:,:,jpno3) = trb(:,:,:,jpno3) * no3mean / zno3sumb
+
+               IF(lwp) WRITE(numout,*) '       SiO3B mean : ', zsilsumb
+               trb(:,:,:,jpsil) = MIN( 400.e-6,trb(:,:,:,jpsil) * silmean / zsilsumb )
+           ENDIF
+        ENDIF
+        !
+      ENDIF
+        !
+   END SUBROUTINE p4z_dmp
+
+
+   SUBROUTINE p4z_chk_mass( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p4z_chk_mass  ***
+      !!
+      !! ** Purpose :  Mass conservation check 
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      REAL(wp)             ::  zrdenittot, zsdenittot, znitrpottot
+      CHARACTER(LEN=100)   ::   cltxt
+      INTEGER :: jk
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zwork
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nittrc000 ) THEN 
+         xfact1 = rfact2r * 12. / 1.e15 * ryyss    ! conversion molC/kt --> PgC/yr
+         xfact2 = 1.e+3 * rno3 * 14. / 1.e12 * ryyss   ! conversion molC/l/s ----> TgN/m3/yr
+         xfact3 = 1.e+3 * rfact2r * rno3   ! conversion molC/l/kt ----> molN/m3/s
+         IF( ln_check_mass .AND. lwp) THEN      !   Open budget file of NO3, ALK, Si, Fer
+            CALL ctl_opn( numco2, 'carbon.budget'  , 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, 6, .FALSE., narea )
+            CALL ctl_opn( numnut, 'nutrient.budget', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, 6, .FALSE., narea )
+            CALL ctl_opn( numnit, 'nitrogen.budget', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, 6, .FALSE., narea )
+            cltxt='time-step   Alkalinity        Nitrate        Phosphorus         Silicate           Iron'
+            IF( lwp ) WRITE(numnut,*)  TRIM(cltxt)
+            IF( lwp ) WRITE(numnut,*) 
+         ENDIF
+      ENDIF
+
+      IF( iom_use( "pno3tot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         !   Compute the budget of NO3, ALK, Si, Fer
+         IF( ln_p4z ) THEN
+            zwork(:,:,:) =    trn(:,:,:,jpno3) + trn(:,:,:,jpnh4)                      &
+               &          +   trn(:,:,:,jpphy) + trn(:,:,:,jpdia)                      &
+               &          +   trn(:,:,:,jppoc) + trn(:,:,:,jpgoc)  + trn(:,:,:,jpdoc)  &        
+               &          +   trn(:,:,:,jpzoo) + trn(:,:,:,jpmes) 
+        ELSE
+            zwork(:,:,:) =    trn(:,:,:,jpno3) + trn(:,:,:,jpnh4) + trn(:,:,:,jpnph)   &
+               &          +   trn(:,:,:,jpndi) + trn(:,:,:,jpnpi)                      & 
+               &          +   trn(:,:,:,jppon) + trn(:,:,:,jpgon) + trn(:,:,:,jpdon)   &
+               &          + ( trn(:,:,:,jpzoo) + trn(:,:,:,jpmes) ) * no3rat3 
+        ENDIF
+        !
+        no3budget = glob_sum( 'p4zsms', zwork(:,:,:) * cvol(:,:,:)  )  
+        no3budget = no3budget / areatot
+        CALL iom_put( "pno3tot", no3budget )
+      ENDIF
+      !
+      IF( iom_use( "ppo4tot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         IF( ln_p4z ) THEN
+            zwork(:,:,:) =    trn(:,:,:,jppo4)                                         &
+               &          +   trn(:,:,:,jpphy) + trn(:,:,:,jpdia)                      &
+               &          +   trn(:,:,:,jppoc) + trn(:,:,:,jpgoc)  + trn(:,:,:,jpdoc)  &        
+               &          +   trn(:,:,:,jpzoo) + trn(:,:,:,jpmes) 
+        ELSE
+            zwork(:,:,:) =    trn(:,:,:,jppo4) + trn(:,:,:,jppph)                      &
+               &          +   trn(:,:,:,jppdi) + trn(:,:,:,jpppi)                      & 
+               &          +   trn(:,:,:,jppop) + trn(:,:,:,jpgop) + trn(:,:,:,jpdop)   &
+               &          + ( trn(:,:,:,jpzoo) + trn(:,:,:,jpmes) ) * po4rat3 
+        ENDIF
+        !
+        po4budget = glob_sum( 'p4zsms', zwork(:,:,:) * cvol(:,:,:)  )  
+        po4budget = po4budget / areatot
+        CALL iom_put( "ppo4tot", po4budget )
+      ENDIF
+      !
+      IF( iom_use( "psiltot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         zwork(:,:,:) =  trn(:,:,:,jpsil) + trn(:,:,:,jpgsi) + trn(:,:,:,jpdsi) 
+         !
+         silbudget = glob_sum( 'p4zsms', zwork(:,:,:) * cvol(:,:,:)  )  
+         silbudget = silbudget / areatot
+         CALL iom_put( "psiltot", silbudget )
+      ENDIF
+      !
+      IF( iom_use( "palktot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         zwork(:,:,:) =  trn(:,:,:,jpno3) * rno3 + trn(:,:,:,jptal) + trn(:,:,:,jpcal) * 2.              
+         !
+         alkbudget = glob_sum( 'p4zsms', zwork(:,:,:) * cvol(:,:,:)  )         !
+         alkbudget = alkbudget / areatot
+         CALL iom_put( "palktot", alkbudget )
+      ENDIF
+      !
+      IF( iom_use( "pfertot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         zwork(:,:,:) =   trn(:,:,:,jpfer) + trn(:,:,:,jpnfe) + trn(:,:,:,jpdfe)   &
+            &         +   trn(:,:,:,jpbfe) + trn(:,:,:,jpsfe)                      &
+            &         + ( trn(:,:,:,jpzoo) + trn(:,:,:,jpmes) )  * ferat3    
+         !
+         ferbudget = glob_sum( 'p4zsms', zwork(:,:,:) * cvol(:,:,:)  )  
+         ferbudget = ferbudget / areatot
+         CALL iom_put( "pfertot", ferbudget )
+      ENDIF
+      !
+      ! Global budget of N SMS : denitrification in the water column and in the sediment
+      !                          nitrogen fixation by the diazotrophs
+      ! --------------------------------------------------------------------------------
+      IF( iom_use( "tnfix" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
+         znitrpottot  = glob_sum ( 'p4zsms', nitrpot(:,:,:) * nitrfix * cvol(:,:,:) )
+         CALL iom_put( "tnfix"  , znitrpottot * xfact3 )  ! Global  nitrogen fixation molC/l  to molN/m3 
+      ENDIF
+      !
+      IF( iom_use( "tdenit" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
+         zrdenittot = glob_sum ( 'p4zsms', denitr(:,:,:) * rdenit * xnegtr(:,:,:) * cvol(:,:,:) )
+         zsdenittot = glob_sum ( 'p4zsms', sdenit(:,:) * e1e2t(:,:) * tmask(:,:,1) )
+         CALL iom_put( "tdenit" , ( zrdenittot + zsdenittot ) * xfact3 )  ! Total denitrification molC/l to molN/m3 
+      ENDIF
+      !
+      IF( ln_check_mass .AND. kt == nitend ) THEN   ! Compute the budget of NO3, ALK, Si, Fer
+         t_atm_co2_flx  = t_atm_co2_flx / glob_sum( 'p4zsms', e1e2t(:,:) )
+         t_oce_co2_flx  = t_oce_co2_flx         * xfact1 * (-1 )
+         tpp            = tpp           * 1000. * xfact1
+         t_oce_co2_exp  = t_oce_co2_exp * 1000. * xfact1
+         IF( lwp ) WRITE(numco2,9000) ndastp, t_atm_co2_flx, t_oce_co2_flx, tpp, t_oce_co2_exp
+         IF( lwp ) WRITE(numnut,9100) ndastp, alkbudget        * 1.e+06, &
+             &                                no3budget * rno3 * 1.e+06, &
+             &                                po4budget * po4r * 1.e+06, &
+             &                                silbudget        * 1.e+06, &
+             &                                ferbudget        * 1.e+09
+         !
+         IF( lwp ) WRITE(numnit,9200) ndastp, znitrpottot * xfact2  , &
+            &                             zrdenittot  * xfact2  , &
+            &                             zsdenittot  * xfact2
+      ENDIF
+      !
+ 9000  FORMAT(i8,f10.5,e18.10,f10.5,f10.5)
+ 9100  FORMAT(i8,5e18.10)
+ 9200  FORMAT(i8,3f10.5)
+       !
+   END SUBROUTINE p4z_chk_mass
+
+   !!======================================================================
+END MODULE p4zsms 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zlim.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zlim.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zlim.F90	(revision 14097)
@@ -0,0 +1,575 @@
+MODULE p5zlim
+   !!======================================================================
+   !!                         ***  MODULE p5zlim  ***
+   !! TOP :   PISCES with variable stoichiometry 
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-04  (O. Aumont, C. Ethe) Limitation for iron modelled in quota 
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p5z_lim        :   Compute the nutrients limitation terms 
+   !!   p5z_lim_init   :   Read the namelist 
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Shared ocean-passive tracers variables
+   USE trc             ! Tracers defined
+   USE p4zlim
+   USE sms_pisces      ! PISCES variables
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC p5z_lim    
+   PUBLIC p5z_lim_init    
+   PUBLIC p5z_lim_alloc
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC ::  concpno3    !:  NO3, PO4 half saturation   
+   REAL(wp), PUBLIC ::  concpnh4    !:  NH4 half saturation for phyto  
+   REAL(wp), PUBLIC ::  concnpo4    !:  NH4 half saturation for diatoms
+   REAL(wp), PUBLIC ::  concppo4    !:  NH4 half saturation for diatoms
+   REAL(wp), PUBLIC ::  concdpo4    !:  NH4 half saturation for diatoms
+   REAL(wp), PUBLIC ::  concpfer    !:  Iron half saturation for nanophyto 
+   REAL(wp), PUBLIC ::  concbpo4    !:  PO4 half saturation for bacteria
+   REAL(wp), PUBLIC ::  xsizepic    !:  Minimum size criteria for diatoms
+   REAL(wp), PUBLIC ::  xsizerp     !:  Size ratio for nanophytoplankton
+   REAL(wp), PUBLIC ::  qfnopt      !:  optimal Fe quota for nanophyto
+   REAL(wp), PUBLIC ::  qfpopt      !:  optimal Fe quota for nanophyto
+   REAL(wp), PUBLIC ::  qfdopt      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qnnmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qnnmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qpnmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qpnmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qnpmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qnpmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qppmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qppmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qndmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qndmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qpdmin      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qpdmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qfnmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qfpmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  qfdmax      !:  optimal Fe quota for diatoms
+   REAL(wp), PUBLIC ::  zpsinh4
+   REAL(wp), PUBLIC ::  zpsino3
+   REAL(wp), PUBLIC ::  zpsiuptk
+
+   !!*  Allometric variations of the quotas
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqnnmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqnnmax    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqpnmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqpnmax    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqnpmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqnpmax    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqppmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqppmax    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqndmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqndmax    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqpdmin    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE,   DIMENSION(:,:,:)  ::   xqpdmax    !: ???
+
+   !!* Phytoplankton limitation terms
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xpicono3   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xpiconh4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xpicopo4   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xnanodop   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xpicodop   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xdiatdop   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xnanofer   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xpicofer   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xdiatfer   !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimpic    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   xlimpfe    !: ???
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   fvnuptk
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   fvpuptk
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   fvduptk
+
+   ! Coefficient for iron limitation
+   REAL(wp) ::  xcoef1   = 0.00167  / 55.85
+   REAL(wp) ::  xcoef2   = 1.21E-5 * 14. / 55.85 / 7.625 * 0.5 * 1.5
+   REAL(wp) ::  xcoef3   = 1.15E-4 * 14. / 55.85 / 7.625 * 0.5 
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE p5z_lim( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_lim  ***
+      !!
+      !! ** Purpose :   Compute the co-limitations by the various nutrients
+      !!              for the various phytoplankton species
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in)  :: kt, knt
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zlim1, zlim2, zlim3, zlim4, zno3, zferlim
+      REAL(wp) ::   z1_trndia, z1_trnpic, z1_trnphy, ztem1, ztem2, zetot1
+      REAL(wp) ::   zratio, zration, zratiof, znutlim, zfalim
+      REAL(wp) ::   zconc1d, zconc1dnh4, zconc0n, zconc0nnh4, zconc0npo4, zconc0dpo4
+      REAL(wp) ::   zconc0p, zconc0pnh4, zconc0ppo4, zconcpfe, zconcnfe, zconcdfe
+      REAL(wp) ::   fanano, fananop, fananof, fadiat, fadiatp, fadiatf
+      REAL(wp) ::   fapico, fapicop, fapicof
+      REAL(wp) ::   zrpho, zrass, zcoef, zfuptk, zratchl
+      REAL(wp) ::   zfvn, zfvp, zfvf, zsizen, zsizep, zsized, znanochl, zpicochl, zdiatchl
+      REAL(wp) ::   zqfemn, zqfemp, zqfemd, zbactno3, zbactnh4
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_lim')
+      !
+      zratchl = 6.0
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! 
+               ! Tuning of the iron concentration to a minimum level that is set to the detection limit
+               !-------------------------------------
+               zno3    = trb(ji,jj,jk,jpno3) / 40.e-6
+               zferlim = MAX( 3e-11 * zno3 * zno3, 5e-12 )
+               zferlim = MIN( zferlim, 7e-11 )
+               trb(ji,jj,jk,jpfer) = MAX( trb(ji,jj,jk,jpfer), zferlim )
+
+               ! Computation of the mean relative size of each community
+               ! -------------------------------------------------------
+               z1_trnphy   = 1. / ( trb(ji,jj,jk,jpphy) + rtrn )
+               z1_trnpic   = 1. / ( trb(ji,jj,jk,jppic) + rtrn )
+               z1_trndia   = 1. / ( trb(ji,jj,jk,jpdia) + rtrn )
+               znanochl = trb(ji,jj,jk,jpnch) * z1_trnphy
+               zpicochl = trb(ji,jj,jk,jppch) * z1_trnpic
+               zdiatchl = trb(ji,jj,jk,jpdch) * z1_trndia
+
+               ! Computation of a variable Ks for iron on diatoms taking into account
+               ! that increasing biomass is made of generally bigger cells
+               !------------------------------------------------
+               zsized            = sized(ji,jj,jk)**0.81
+               zconcdfe          = concdfer * zsized
+               zconc1d           = concdno3 * zsized
+               zconc1dnh4        = concdnh4 * zsized
+               zconc0dpo4        = concdpo4 * zsized
+
+               zsizep            = 1.
+               zconcpfe          = concpfer * zsizep
+               zconc0p           = concpno3 * zsizep
+               zconc0pnh4        = concpnh4 * zsizep
+               zconc0ppo4        = concppo4 * zsizep
+
+               zsizen            = 1.
+               zconcnfe          = concnfer * zsizen
+               zconc0n           = concnno3 * zsizen
+               zconc0nnh4        = concnnh4 * zsizen
+               zconc0npo4        = concnpo4 * zsizen
+
+               ! Allometric variations of the minimum and maximum quotas
+               ! From Talmy et al. (2014) and Maranon et al. (2013)
+               ! -------------------------------------------------------
+               xqnnmin(ji,jj,jk) = qnnmin
+               xqnnmax(ji,jj,jk) = qnnmax
+               xqndmin(ji,jj,jk) = qndmin * sized(ji,jj,jk)**(-0.27) 
+               xqndmax(ji,jj,jk) = qndmax
+               xqnpmin(ji,jj,jk) = qnpmin
+               xqnpmax(ji,jj,jk) = qnpmax
+
+               ! Computation of the optimal allocation parameters
+               ! Based on the different papers by Pahlow et al., and Smith et al.
+               ! -----------------------------------------------------------------
+               znutlim = MAX( trb(ji,jj,jk,jpnh4) / zconc0nnh4,    &
+                 &         trb(ji,jj,jk,jpno3) / zconc0n)
+               fanano = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = trb(ji,jj,jk,jppo4) / zconc0npo4
+               fananop = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = biron(ji,jj,jk) / zconcnfe
+               fananof = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = MAX( trb(ji,jj,jk,jpnh4) / zconc0pnh4,    &
+                 &         trb(ji,jj,jk,jpno3) / zconc0p)
+               fapico = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = trb(ji,jj,jk,jppo4) / zconc0ppo4
+               fapicop = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = biron(ji,jj,jk) / zconcpfe
+               fapicof = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = MAX( trb(ji,jj,jk,jpnh4) / zconc1dnh4,    &
+                 &         trb(ji,jj,jk,jpno3) / zconc1d )
+               fadiat = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = trb(ji,jj,jk,jppo4) / zconc0dpo4
+               fadiatp = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               znutlim = biron(ji,jj,jk) / zconcdfe
+               fadiatf = MAX(0.01, MIN(0.99, 1. / ( SQRT(znutlim) + 1.) ) )
+               !
+               ! Michaelis-Menten Limitation term for nutrients Small bacteria
+               ! -------------------------------------------------------------
+               zbactnh4 = trb(ji,jj,jk,jpnh4) / ( concbnh4 + trb(ji,jj,jk,jpnh4) )
+               zbactno3 = trb(ji,jj,jk,jpno3) / ( concbno3 + trb(ji,jj,jk,jpno3) ) * (1. - zbactnh4)
+               !
+               zlim1    = zbactno3 + zbactnh4
+               zlim2    = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + concbpo4)
+               zlim3    = biron(ji,jj,jk) / ( concbfe + biron(ji,jj,jk) )
+               zlim4    = trb(ji,jj,jk,jpdoc) / ( xkdoc   + trb(ji,jj,jk,jpdoc) )
+               xlimbacl(ji,jj,jk) = MIN( zlim1, zlim2, zlim3 )
+               xlimbac (ji,jj,jk) = xlimbacl(ji,jj,jk) * zlim4
+               !
+               ! Michaelis-Menten Limitation term for nutrients Small flagellates
+               ! -----------------------------------------------
+               zfalim = (1.-fanano) / fanano
+               xnanonh4(ji,jj,jk) = (1. - fanano) * trb(ji,jj,jk,jpnh4) / ( zfalim * zconc0nnh4 + trb(ji,jj,jk,jpnh4) )
+               xnanono3(ji,jj,jk) = (1. - fanano) * trb(ji,jj,jk,jpno3) / ( zfalim * zconc0n + trb(ji,jj,jk,jpno3) )  &
+               &                    * (1. - xnanonh4(ji,jj,jk))
+               !
+               zfalim = (1.-fananop) / fananop
+               xnanopo4(ji,jj,jk) = (1. - fananop) * trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + zfalim * zconc0npo4 )
+               xnanodop(ji,jj,jk) = trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdop) + xkdoc )   &
+               &                    * ( 1.0 - xnanopo4(ji,jj,jk) )
+               xnanodop(ji,jj,jk) = 0.
+               !
+               zfalim = (1.-fananof) / fananof
+               xnanofer(ji,jj,jk) = (1. - fananof) * biron(ji,jj,jk) / ( biron(ji,jj,jk) + zfalim * zconcnfe )
+               !
+               zratiof   = trb(ji,jj,jk,jpnfe) * z1_trnphy
+               zqfemn = xcoef1 * znanochl + xcoef2 + xcoef3 * xnanono3(ji,jj,jk)
+               !
+               zration = trb(ji,jj,jk,jpnph) * z1_trnphy
+               zration = MIN(xqnnmax(ji,jj,jk), MAX( 2. * xqnnmin(ji,jj,jk), zration ))
+               fvnuptk(ji,jj,jk) = 1. / zpsiuptk * rno3 * 2. * xqnnmin(ji,jj,jk) / (zration + rtrn)  &
+               &                   * MAX(0., (1. - zratchl * znanochl / 12. ) )
+               !
+               zlim1    = max(0., (zration - 2. * xqnnmin(ji,jj,jk) )  &
+               &          / (xqnnmax(ji,jj,jk) - 2. * xqnnmin(ji,jj,jk) ) ) * xqnnmax(ji,jj,jk)  &
+               &          / (zration + rtrn)
+               zlim3    = MAX( 0.,( zratiof - zqfemn ) / qfnopt ) 
+               xlimnfe(ji,jj,jk) = MIN( 1., zlim3 )
+               xlimphy(ji,jj,jk) = MIN( 1., zlim1, zlim3 )
+               !
+               ! Michaelis-Menten Limitation term for nutrients picophytoplankton
+               ! ----------------------------------------------------------------
+               zfalim = (1.-fapico) / fapico 
+               xpiconh4(ji,jj,jk) = (1. - fapico) * trb(ji,jj,jk,jpnh4) / ( zfalim * zconc0pnh4 + trb(ji,jj,jk,jpnh4) )
+               xpicono3(ji,jj,jk) = (1. - fapico) * trb(ji,jj,jk,jpno3) / ( zfalim * zconc0p + trb(ji,jj,jk,jpno3) )  &
+               &                    * (1. - xpiconh4(ji,jj,jk))
+               !
+               zfalim = (1.-fapicop) / fapicop 
+               xpicopo4(ji,jj,jk) = (1. - fapicop) * trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + zfalim * zconc0ppo4 )
+               xpicodop(ji,jj,jk) = trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdop) + xkdoc )   &
+               &                    * ( 1.0 - xpicopo4(ji,jj,jk) )
+               xpicodop(ji,jj,jk) = 0.
+               !
+               zfalim = (1.-fapicof) / fapicof
+               xpicofer(ji,jj,jk) = (1. - fapicof) * biron(ji,jj,jk) / ( biron(ji,jj,jk) + zfalim * zconcpfe )
+               !
+               zratiof   = trb(ji,jj,jk,jppfe) * z1_trnpic
+               zqfemp = xcoef1 * zpicochl + xcoef2 + xcoef3 * xpicono3(ji,jj,jk)
+               !
+               zration   = trb(ji,jj,jk,jpnpi) * z1_trnpic
+               zration = MIN(xqnpmax(ji,jj,jk), MAX( 2. * xqnpmin(ji,jj,jk), zration ))
+               fvpuptk(ji,jj,jk) = 1. / zpsiuptk * rno3 * 2. * xqnpmin(ji,jj,jk) / (zration + rtrn)  &
+               &                   * MAX(0., (1. - zratchl * zpicochl / 12. ) ) 
+               !
+               zlim1    = max(0., (zration - 2. * xqnpmin(ji,jj,jk) )  &
+               &          / (xqnpmax(ji,jj,jk) - 2. * xqnpmin(ji,jj,jk) ) ) * xqnpmax(ji,jj,jk)  &
+               &          / (zration + rtrn)
+               zlim3    = MAX( 0.,( zratiof - zqfemp ) / qfpopt )
+               xlimpfe(ji,jj,jk) = MIN( 1., zlim3 )
+               xlimpic(ji,jj,jk) = MIN( 1., zlim1, zlim3 )
+               !
+               !   Michaelis-Menten Limitation term for nutrients Diatoms
+               !   ------------------------------------------------------
+               zfalim = (1.-fadiat) / fadiat 
+               xdiatnh4(ji,jj,jk) = (1. - fadiat) * trb(ji,jj,jk,jpnh4) / ( zfalim * zconc1dnh4 + trb(ji,jj,jk,jpnh4) )
+               xdiatno3(ji,jj,jk) = (1. - fadiat) * trb(ji,jj,jk,jpno3) / ( zfalim * zconc1d + trb(ji,jj,jk,jpno3) )  &
+               &                    * (1. - xdiatnh4(ji,jj,jk))
+               !
+               zfalim = (1.-fadiatp) / fadiatp
+               xdiatpo4(ji,jj,jk) = (1. - fadiatp) * trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + zfalim * zconc0dpo4 )
+               xdiatdop(ji,jj,jk) = trb(ji,jj,jk,jpdop) / ( trb(ji,jj,jk,jpdop) + xkdoc )  &
+               &                    * ( 1.0 - xdiatpo4(ji,jj,jk) )
+               xdiatdop(ji,jj,jk) = 0.
+               !
+               zfalim = (1.-fadiatf) / fadiatf
+               xdiatfer(ji,jj,jk) = (1. - fadiatf) * biron(ji,jj,jk) / ( biron(ji,jj,jk) + zfalim * zconcdfe )
+               !
+               zratiof   = trb(ji,jj,jk,jpdfe) * z1_trndia
+               zqfemd = xcoef1 * zdiatchl + xcoef2 + xcoef3 * xdiatno3(ji,jj,jk)
+               !
+               zration   = trb(ji,jj,jk,jpndi) * z1_trndia
+               zration = MIN(xqndmax(ji,jj,jk), MAX( 2. * xqndmin(ji,jj,jk), zration ))
+               fvduptk(ji,jj,jk) = 1. / zpsiuptk * rno3 * 2. * xqndmin(ji,jj,jk) / (zration + rtrn)   &
+               &                   * MAX(0., (1. - zratchl * zdiatchl / 12. ) ) 
+               !
+               zlim1    = max(0., (zration - 2. * xqndmin(ji,jj,jk) )    &
+               &          / (xqndmax(ji,jj,jk) - 2. * xqndmin(ji,jj,jk) ) )   &
+               &          * xqndmax(ji,jj,jk) / (zration + rtrn)
+               zlim3    = trb(ji,jj,jk,jpsil) / ( trb(ji,jj,jk,jpsil) + xksi(ji,jj) )
+               zlim4    = MAX( 0., ( zratiof - zqfemd ) / qfdopt )
+               xlimdfe(ji,jj,jk) = MIN( 1., zlim4 )
+               xlimdia(ji,jj,jk) = MIN( 1., zlim1, zlim3, zlim4 )
+               xlimsi(ji,jj,jk)  = MIN( zlim1, zlim4 )
+            END DO
+         END DO
+      END DO
+      !
+      ! Compute the phosphorus quota values. It is based on Litchmann et al., 2004 and Daines et al, 2013.
+      ! The relative contribution of three fonctional pools are computed: light harvesting apparatus, 
+      ! nutrient uptake pool and assembly machinery. DNA is assumed to represent 1% of the dry mass of 
+      ! phytoplankton (see Daines et al., 2013). 
+      ! --------------------------------------------------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! Size estimation of nanophytoplankton
+               ! ------------------------------------
+               zfvn = 2. * fvnuptk(ji,jj,jk)
+               sizen(ji,jj,jk) = MAX(1., MIN(xsizern, 1.0 / ( MAX(rtrn, zfvn) ) ) )
+
+               ! N/P ratio of nanophytoplankton
+               ! ------------------------------
+               zfuptk = 0.23 * zfvn
+               zrpho = 2.24 * trb(ji,jj,jk,jpnch) / ( trb(ji,jj,jk,jpnph) * rno3 * 15. + rtrn )
+               zrass = 1. - 0.2 - zrpho - zfuptk
+               xqpnmax(ji,jj,jk) = ( zfuptk + zrpho ) * 0.0128 * 16. + zrass * 1./ 7.2 * 16.
+               xqpnmax(ji,jj,jk) = xqpnmax(ji,jj,jk) * trb(ji,jj,jk,jpnph) / ( trb(ji,jj,jk,jpphy) + rtrn ) + 0.13
+               xqpnmin(ji,jj,jk) = 0.13 + 0.23 * 0.0128 * 16.
+
+               ! Size estimation of picophytoplankton
+               ! ------------------------------------
+               zfvn = 2. * fvpuptk(ji,jj,jk)
+               sizep(ji,jj,jk) = MAX(1., MIN(xsizerp, 1.0 / ( MAX(rtrn, zfvn) ) ) )
+
+               ! N/P ratio of picophytoplankton
+               ! ------------------------------
+               zfuptk = 0.35 * zfvn
+               zrpho = 2.24 * trb(ji,jj,jk,jppch) / ( trb(ji,jj,jk,jpnpi) * rno3 * 15. + rtrn )
+               zrass = 1. - 0.4 - zrpho - zfuptk
+               xqppmax(ji,jj,jk) =  (zrpho + zfuptk) * 0.0128 * 16. + zrass * 1./ 9. * 16.
+               xqppmax(ji,jj,jk) = xqppmax(ji,jj,jk) * trb(ji,jj,jk,jpnpi) / ( trb(ji,jj,jk,jppic) + rtrn ) + 0.13
+               xqppmin(ji,jj,jk) = 0.13
+
+               ! Size estimation of diatoms
+               ! --------------------------
+               zfvn = 2. * fvduptk(ji,jj,jk)
+               sized(ji,jj,jk) = MAX(1., MIN(xsizerd, 1.0 / ( MAX(rtrn, zfvn) ) ) )
+               zcoef = trb(ji,jj,jk,jpdia) - MIN(xsizedia, trb(ji,jj,jk,jpdia) )
+               sized(ji,jj,jk) = 1. + xsizerd * zcoef *1E6 / ( 1. + zcoef * 1E6 )
+
+               ! N/P ratio of diatoms
+               ! --------------------
+               zfuptk = 0.2 * zfvn
+               zrpho = 2.24 * trb(ji,jj,jk,jpdch) / ( trb(ji,jj,jk,jpndi) * rno3 * 15. + rtrn )
+               zrass = 1. - 0.2 - zrpho - zfuptk
+               xqpdmax(ji,jj,jk) = ( zfuptk + zrpho ) * 0.0128 * 16. + zrass * 1./ 7.2 * 16.
+               xqpdmax(ji,jj,jk) = xqpdmax(ji,jj,jk) * trb(ji,jj,jk,jpndi) / ( trb(ji,jj,jk,jpdia) + rtrn ) + 0.13
+               xqpdmin(ji,jj,jk) = 0.13 + 0.2 * 0.0128 * 16.
+
+            END DO
+         END DO
+      END DO
+
+      ! Compute the fraction of nanophytoplankton that is made of calcifiers
+      ! --------------------------------------------------------------------
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zlim1 =  trb(ji,jj,jk,jpnh4) / ( trb(ji,jj,jk,jpnh4) + concnnh4 ) + trb(ji,jj,jk,jpno3)    &
+               &        / ( trb(ji,jj,jk,jpno3) + concnno3 ) * ( 1.0 - trb(ji,jj,jk,jpnh4)   &
+               &        / ( trb(ji,jj,jk,jpnh4) + concnnh4 ) )
+               zlim2  = trb(ji,jj,jk,jppo4) / ( trb(ji,jj,jk,jppo4) + concnpo4 )
+               zlim3  = trb(ji,jj,jk,jpfer) / ( trb(ji,jj,jk,jpfer) +  5.E-11 ) 
+               ztem1  = MAX( 0., tsn(ji,jj,jk,jp_tem) )
+               ztem2  = tsn(ji,jj,jk,jp_tem) - 10.
+               zetot1 = MAX( 0., etot(ji,jj,jk) - 1.) / ( 4. + etot(ji,jj,jk) ) * 20. / ( 20. + etot(ji,jj,jk) ) 
+
+!               xfracal(ji,jj,jk) = caco3r * MIN( zlim1, zlim2, zlim3 )                  &
+               xfracal(ji,jj,jk) = caco3r                 &
+               &                   * ztem1 / ( 1. + ztem1 ) * MAX( 1., trb(ji,jj,jk,jpphy)*1E6 )   &
+                  &                * ( 1. + EXP(-ztem2 * ztem2 / 25. ) )         &
+                  &                * zetot1 * MIN( 1., 50. / ( hmld(ji,jj) + rtrn ) )
+               xfracal(ji,jj,jk) = MAX( 0.02, MIN( 0.8 , xfracal(ji,jj,jk) ) )
+            END DO
+         END DO
+      END DO
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! denitrification factor computed from O2 levels
+               nitrfac(ji,jj,jk) = MAX(  0.e0, 0.4 * ( 6.e-6  - trb(ji,jj,jk,jpoxy) )    &
+                  &                                / ( oxymin + trb(ji,jj,jk,jpoxy) )  )
+               nitrfac(ji,jj,jk) = MIN( 1., nitrfac(ji,jj,jk) )
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput .AND. knt == 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( "LPnut"  , xlimpic(:,:,:) * 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( "LPFe"   , xlimpfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+        CALL iom_put( "LDFe"   , xlimdfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+        CALL iom_put( "SIZEN"  , sizen  (:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+        CALL iom_put( "SIZEP"  , sizep  (:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+        CALL iom_put( "SIZED"  , sized  (:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('p5z_lim')
+      !
+   END SUBROUTINE p5z_lim
+
+
+   SUBROUTINE p5z_lim_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p5z_lim_init  ***
+      !!
+      !! ** Purpose :   Initialization of nutrient limitation parameters
+      !!
+      !! ** Method  :   Read the nampislim and nampisquota namelists and check
+      !!      the parameters called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampislim
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/namp5zlim/ concnno3, concpno3, concdno3, concnnh4, concpnh4, concdnh4,  &
+         &                concnfer, concpfer, concdfer, concbfe, concnpo4, concppo4,   &
+         &                concdpo4, concbno3, concbnh4, concbpo4, xsizedia, xsizepic,  &
+         &                xsizephy, xsizern, xsizerp, xsizerd, xksi1, xksi2, xkdoc,    &
+         &                caco3r, oxymin
+         !
+      NAMELIST/namp5zquota/ qnnmin, qnnmax, qpnmin, qpnmax, qnpmin, qnpmax, qppmin,      &
+         &                  qppmax, qndmin, qndmax, qpdmin, qpdmax, qfnmax, qfpmax, qfdmax,  &
+         &                  qfnopt, qfpopt, qfdopt
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp5zlim, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nampislim in reference namelist' )
+      !
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp5zlim, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'nampislim in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zlim )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Namelist parameters for nutrient limitations, namp5zlim'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    mean rainratio                           caco3r    = ', caco3r
+         WRITE(numout,*) '    NO3 half saturation of nanophyto         concnno3  = ', concnno3
+         WRITE(numout,*) '    NO3 half saturation of picophyto         concpno3  = ', concpno3
+         WRITE(numout,*) '    NO3 half saturation of diatoms           concdno3  = ', concdno3
+         WRITE(numout,*) '    NH4 half saturation for phyto            concnnh4  = ', concnnh4
+         WRITE(numout,*) '    NH4 half saturation for pico             concpnh4  = ', concpnh4
+         WRITE(numout,*) '    NH4 half saturation for diatoms          concdnh4  = ', concdnh4
+         WRITE(numout,*) '    PO4 half saturation for phyto            concnpo4  = ', concnpo4
+         WRITE(numout,*) '    PO4 half saturation for pico             concppo4  = ', concppo4
+         WRITE(numout,*) '    PO4 half saturation for diatoms          concdpo4  = ', concdpo4
+         WRITE(numout,*) '    half saturation constant for Si uptake   xksi1     = ', xksi1
+         WRITE(numout,*) '    half saturation constant for Si/C        xksi2     = ', xksi2
+         WRITE(numout,*) '    half-sat. of DOC remineralization        xkdoc     = ', xkdoc
+         WRITE(numout,*) '    Iron half saturation for nanophyto       concnfer  = ', concnfer
+         WRITE(numout,*) '    Iron half saturation for picophyto       concpfer  = ', concpfer
+         WRITE(numout,*) '    Iron half saturation for diatoms         concdfer  = ', concdfer
+         WRITE(numout,*) '    size ratio for nanophytoplankton         xsizern   = ', xsizern
+         WRITE(numout,*) '    size ratio for picophytoplankton         xsizerp   = ', xsizerp
+         WRITE(numout,*) '    size ratio for diatoms                   xsizerd   = ', xsizerd
+         WRITE(numout,*) '    NO3 half saturation of bacteria          concbno3  = ', concbno3
+         WRITE(numout,*) '    NH4 half saturation for bacteria         concbnh4  = ', concbnh4
+         WRITE(numout,*) '    Minimum size criteria for diatoms        xsizedia  = ', xsizedia
+         WRITE(numout,*) '    Minimum size criteria for picophyto      xsizepic  = ', xsizepic
+         WRITE(numout,*) '    Minimum size criteria for nanophyto      xsizephy  = ', xsizephy
+         WRITE(numout,*) '    Fe half saturation for bacteria          concbfe   = ', concbfe
+         WRITE(numout,*) '    halk saturation constant for anoxia       oxymin   =' , oxymin
+      ENDIF
+
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp5zquota, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nampisquota in reference namelist' )
+      !
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp5zquota, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 ) CALL ctl_nam ( ios , 'nampisquota in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zquota )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Namelist parameters for nutrient limitations, namp5zquota'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    optimal Fe quota for nano.               qfnopt    = ', qfnopt
+         WRITE(numout,*) '    optimal Fe quota for pico.               qfpopt    = ', qfpopt
+         WRITE(numout,*) '    Optimal Fe quota for diatoms             qfdopt    = ', qfdopt
+         WRITE(numout,*) '    Minimal N quota for nano                 qnnmin    = ', qnnmin
+         WRITE(numout,*) '    Maximal N quota for nano                 qnnmax    = ', qnnmax
+         WRITE(numout,*) '    Minimal P quota for nano                 qpnmin    = ', qpnmin
+         WRITE(numout,*) '    Maximal P quota for nano                 qpnmax    = ', qpnmax
+         WRITE(numout,*) '    Minimal N quota for pico                 qnpmin    = ', qnpmin
+         WRITE(numout,*) '    Maximal N quota for pico                 qnpmax    = ', qnpmax
+         WRITE(numout,*) '    Minimal P quota for pico                 qppmin    = ', qppmin
+         WRITE(numout,*) '    Maximal P quota for pico                 qppmax    = ', qppmax
+         WRITE(numout,*) '    Minimal N quota for diatoms              qndmin    = ', qndmin
+         WRITE(numout,*) '    Maximal N quota for diatoms              qndmax    = ', qndmax
+         WRITE(numout,*) '    Minimal P quota for diatoms              qpdmin    = ', qpdmin
+         WRITE(numout,*) '    Maximal P quota for diatoms              qpdmax    = ', qpdmax
+         WRITE(numout,*) '    Maximal Fe quota for nanophyto.          qfnmax    = ', qfnmax
+         WRITE(numout,*) '    Maximal Fe quota for picophyto.          qfpmax    = ', qfpmax
+         WRITE(numout,*) '    Maximal Fe quota for diatoms             qfdmax    = ', qfdmax
+      ENDIF
+      !
+      zpsino3 = 2.3 * rno3
+      zpsinh4 = 1.8 * rno3
+      zpsiuptk = 2.3 * rno3
+      !
+      nitrfac(:,:,jpk) = 0._wp
+      xfracal(:,:,jpk) = 0._wp
+      xlimphy(:,:,jpk) = 0._wp
+      xlimpic(:,:,jpk) = 0._wp
+      xlimdia(:,:,jpk) = 0._wp
+      xlimnfe(:,:,jpk) = 0._wp
+      xlimpfe(:,:,jpk) = 0._wp
+      xlimdfe(:,:,jpk) = 0._wp
+      sizen  (:,:,jpk) = 0._wp
+      sizep  (:,:,jpk) = 0._wp
+      sized  (:,:,jpk) = 0._wp
+      !
+   END SUBROUTINE p5z_lim_init
+
+
+   INTEGER FUNCTION p5z_lim_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_lim_alloc  ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp , ONLY: ctl_stop
+      INTEGER ::   ierr(2)        ! Local variables
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      !*  Biological arrays for phytoplankton growth
+      ALLOCATE( xpicono3(jpi,jpj,jpk), xpiconh4(jpi,jpj,jpk),       &
+         &      xpicopo4(jpi,jpj,jpk), xpicodop(jpi,jpj,jpk),       &
+         &      xnanodop(jpi,jpj,jpk), xdiatdop(jpi,jpj,jpk),       &
+         &      xnanofer(jpi,jpj,jpk), xdiatfer(jpi,jpj,jpk),       &
+         &      xpicofer(jpi,jpj,jpk), xlimpfe (jpi,jpj,jpk),       &
+         &      fvnuptk (jpi,jpj,jpk), fvduptk (jpi,jpj,jpk),       &
+         &      fvpuptk (jpi,jpj,jpk), xlimpic (jpi,jpj,jpk),    STAT=ierr(1) )
+         !
+      !*  Minimum/maximum quotas of phytoplankton
+      ALLOCATE( xqnnmin (jpi,jpj,jpk), xqnnmax(jpi,jpj,jpk),       &
+         &      xqpnmin (jpi,jpj,jpk), xqpnmax(jpi,jpj,jpk),       &
+         &      xqnpmin (jpi,jpj,jpk), xqnpmax(jpi,jpj,jpk),       &
+         &      xqppmin (jpi,jpj,jpk), xqppmax(jpi,jpj,jpk),       &
+         &      xqndmin (jpi,jpj,jpk), xqndmax(jpi,jpj,jpk),       &
+         &      xqpdmin (jpi,jpj,jpk), xqpdmax(jpi,jpj,jpk),     STAT=ierr(2) )
+         !
+      p5z_lim_alloc = MAXVAL( ierr )
+      !
+      IF( p5z_lim_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p5z_lim_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p5z_lim_alloc
+   !!======================================================================
+END MODULE p5zlim
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmeso.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmeso.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmeso.F90	(revision 14097)
@@ -0,0 +1,435 @@
+MODULE p5zmeso
+   !!======================================================================
+   !!                         ***  MODULE p5zmeso  ***
+   !! TOP :   PISCES Compute the sources/sinks for mesozooplankton
+   !!======================================================================
+   !! History :   1.0  !  2002     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p5z_meso       :   Compute the sources/sinks for mesozooplankton
+   !!   p5z_meso_init  :   Initialization of the parameters for mesozooplankton
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p5z_meso              ! called in p5zbio.F90
+   PUBLIC   p5z_meso_init         ! called in trcsms_pisces.F90
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC ::  part2        !: part of calcite not dissolved in mesozoo guts
+   REAL(wp), PUBLIC ::  xpref2c      !: mesozoo preference for POC 
+   REAL(wp), PUBLIC ::  xpref2n      !: mesozoo preference for nanophyto
+   REAL(wp), PUBLIC ::  xpref2z      !: mesozoo preference for zooplankton
+   REAL(wp), PUBLIC ::  xpref2d      !: mesozoo preference for Diatoms 
+   REAL(wp), PUBLIC ::  xpref2m      !: mesozoo preference for mesozoo
+   REAL(wp), PUBLIC ::  xthresh2zoo  !: zoo feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2dia  !: diatoms feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2phy  !: nanophyto feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2poc  !: poc feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2mes  !: mesozoo feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  xthresh2     !: feeding threshold for mesozooplankton 
+   REAL(wp), PUBLIC ::  resrat2      !: exsudation rate of mesozooplankton
+   REAL(wp), PUBLIC ::  mzrat2       !: microzooplankton mortality rate 
+   REAL(wp), PUBLIC ::  grazrat2     !: maximal mesozoo grazing rate
+   REAL(wp), PUBLIC ::  xkgraz2      !: Half-saturation constant of assimilation
+   REAL(wp), PUBLIC ::  unass2c      !: Non-assimilated fraction of food
+   REAL(wp), PUBLIC ::  unass2n      !: Non-assimilated fraction of food
+   REAL(wp), PUBLIC ::  unass2p      !: Non-assimilated fraction of food
+   REAL(wp), PUBLIC ::  epsher2      !: Growth efficiency of mesozoo
+   REAL(wp), PUBLIC ::  epsher2min   !: Minimum growth efficiency of mesozoo
+   REAL(wp), PUBLIC ::  ssigma2      !: Fraction excreted as semi-labile DOM
+   REAL(wp), PUBLIC ::  srespir2     !: Active respiration
+   REAL(wp), PUBLIC ::  grazflux     !: mesozoo flux feeding rate
+   LOGICAL,  PUBLIC ::  bmetexc2     !: Use of excess carbon for respiration
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE p5z_meso( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_meso  ***
+      !!
+      !! ** Purpose :   Compute the sources/sinks for mesozooplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt, knt ! ocean time step
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompadi, zcompaph, zcompapoc, zcompaz, zcompam, zcompames
+      REAL(wp) :: zgraze2, zdenom, zfact, zfood, zfoodlim, zproport
+      REAL(wp) :: zmortzgoc, zfracc, zfracn, zfracp, zfracfe, zratio, zratio2
+      REAL(wp) :: zepsherf, zepshert, zepsherv, zrespirc, zrespirn, zrespirp, zbasresb, zbasresi
+      REAL(wp) :: zgraztotc, zgraztotn, zgraztotp, zgraztotf, zbasresn, zbasresp, zbasresf
+      REAL(wp) :: zgradoc, zgradon, zgradop, zgratmp, zgradoct, zgradont, zgrareft, zgradopt
+      REAL(wp) :: zgrapoc, zgrapon, zgrapop, zgrapof, zprcaca, zmortz
+      REAL(wp) :: zexcess, zgrarem, zgraren, zgrarep, zgraref
+      REAL(wp) :: zbeta, zrespz, ztortz, zgrasratp, zgrasratn, zgrasratf
+      REAL(wp) :: ztmp1, ztmp2, ztmp3, ztmp4, ztmp5, ztmptot
+      REAL(wp) :: zgrazdc, zgrazz, zgrazm, zgrazpof, zgrazcal, zfracal
+      REAL(wp) :: zgraznc, zgrazpoc, zgrazpon, zgrazpop, zgraznf, zgrazdf
+      REAL(wp) :: zgraznp, zgraznn, zgrazdn, zgrazdp
+      REAL(wp) :: zgrazfffp, zgrazfffg, zgrazffep, zgrazffeg
+      REAL(wp) :: zgrazffnp, zgrazffng, zgrazffpp, zgrazffpg
+      CHARACTER (len=25) :: charout
+      REAL(wp) :: zrfact2, zmetexcess
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zgrazing2, zfezoo2, zz2ligprod
+
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_meso')
+      !
+
+      zmetexcess = 0.0
+      IF ( bmetexc2 ) zmetexcess = 1.0
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompam   = MAX( ( trb(ji,jj,jk,jpmes) - 1.e-9 ), 0.e0 )
+               zfact     = xstep * tgfunc2(ji,jj,jk) * zcompam
+
+               !   Michaelis-Menten mortality rates of mesozooplankton
+               !   ---------------------------------------------------
+               zrespz   = resrat2 * zfact * ( trb(ji,jj,jk,jpmes) / ( xkmort + trb(ji,jj,jk,jpmes) )  &
+               &          + 3. * nitrfac(ji,jj,jk) )
+
+               !   Zooplankton mortality. A square function has been selected with
+               !   no real reason except that it seems to be more stable and may mimic predation
+               !   ---------------------------------------------------------------
+               ztortz   = mzrat2 * 1.e6 * zfact * trb(ji,jj,jk,jpmes) * (1. - nitrfac(ji,jj,jk))
+
+               !   Computation of the abundance of the preys
+               !   A threshold can be specified in the namelist
+               !   --------------------------------------------
+               zcompadi  = MAX( ( trb(ji,jj,jk,jpdia) - xthresh2dia ), 0.e0 )
+               zcompaz   = MAX( ( trb(ji,jj,jk,jpzoo) - xthresh2zoo ), 0.e0 )
+               zcompaph  = MAX( ( trb(ji,jj,jk,jpphy) - xthresh2phy ), 0.e0 )
+               zcompapoc = MAX( ( trb(ji,jj,jk,jppoc) - xthresh2poc ), 0.e0 )
+               zcompames = MAX( ( trb(ji,jj,jk,jpmes) - xthresh2mes ), 0.e0 )
+
+               !   Mesozooplankton grazing
+               !   ------------------------
+               zfood     = xpref2d * zcompadi + xpref2z * zcompaz + xpref2n * zcompaph + xpref2c * zcompapoc   &
+               &           + xpref2m * zcompames 
+               zfoodlim  = MAX( 0., zfood - MIN( 0.5 * zfood, xthresh2 ) )
+               zdenom    = zfoodlim / ( xkgraz2 + zfoodlim )
+               zgraze2   = grazrat2 * xstep * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpmes) * (1. - nitrfac(ji,jj,jk)) 
+
+               !   An active switching parameterization is used here.
+               !   We don't use the KTW parameterization proposed by 
+               !   Vallina et al. because it tends to produce to steady biomass
+               !   composition and the variance of Chl is too low as it grazes
+               !   too strongly on winning organisms. Thus, instead of a square
+               !   a 1.5 power value is used which decreases the pressure on the
+               !   most abundant species
+               !   ------------------------------------------------------------  
+               ztmp1 = xpref2n * zcompaph**1.5
+               ztmp2 = xpref2m * zcompames**1.5
+               ztmp3 = xpref2c * zcompapoc**1.5
+               ztmp4 = xpref2d * zcompadi**1.5
+               ztmp5 = xpref2z * zcompaz**1.5
+               ztmptot = ztmp1 + ztmp2 + ztmp3 + ztmp4 + ztmp5 + rtrn
+               ztmp1 = ztmp1 / ztmptot
+               ztmp2 = ztmp2 / ztmptot
+               ztmp3 = ztmp3 / ztmptot
+               ztmp4 = ztmp4 / ztmptot
+               ztmp5 = ztmp5 / ztmptot
+
+               !   Mesozooplankton regular grazing on the different preys
+               !   ------------------------------------------------------
+               zgrazdc   = zgraze2 * ztmp4 * zdenom
+               zgrazdn   = zgrazdc * trb(ji,jj,jk,jpndi) / ( trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazdp   = zgrazdc * trb(ji,jj,jk,jppdi) / ( trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazdf   = zgrazdc * trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazz    = zgraze2 * ztmp5 * zdenom
+               zgrazm    = zgraze2 * ztmp2 * zdenom
+               zgraznc   = zgraze2 * ztmp1 * zdenom
+               zgraznn   = zgraznc * trb(ji,jj,jk,jpnph) / ( trb(ji,jj,jk,jpphy) + rtrn)
+               zgraznp   = zgraznc * trb(ji,jj,jk,jppph) / ( trb(ji,jj,jk,jpphy) + rtrn)
+               zgraznf   = zgraznc * trb(ji,jj,jk,jpnfe) / ( trb(ji,jj,jk,jpphy) + rtrn)
+               zgrazpoc  = zgraze2 * ztmp3 * zdenom
+               zgrazpon  = zgrazpoc * trb(ji,jj,jk,jppon) / ( trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazpop  = zgrazpoc * trb(ji,jj,jk,jppop) / ( trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazpof  = zgrazpoc * trb(ji,jj,jk,jpsfe) / ( trb(ji,jj,jk,jppoc) + rtrn)
+
+               !   Mesozooplankton flux feeding on GOC
+               !   ----------------------------------
+               zgrazffeg = grazflux  * xstep * wsbio4(ji,jj,jk)      &
+               &           * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpgoc) * trb(ji,jj,jk,jpmes)  &
+               &           * (1. - nitrfac(ji,jj,jk))
+               zgrazfffg = zgrazffeg * trb(ji,jj,jk,jpbfe) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zgrazffng = zgrazffeg * trb(ji,jj,jk,jpgon) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zgrazffpg = zgrazffeg * trb(ji,jj,jk,jpgop) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zgrazffep = grazflux  * xstep *  wsbio3(ji,jj,jk)     &
+               &           * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jppoc) * trb(ji,jj,jk,jpmes)   &
+               &           * (1. - nitrfac(ji,jj,jk))
+               zgrazfffp = zgrazffep * trb(ji,jj,jk,jpsfe) / (trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazffnp = zgrazffep * trb(ji,jj,jk,jppon) / (trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazffpp = zgrazffep * trb(ji,jj,jk,jppop) / (trb(ji,jj,jk,jppoc) + rtrn)
+               !
+               zgraztotc  = zgrazdc + zgrazz + zgraznc + zgrazm + zgrazpoc + zgrazffep + zgrazffeg
+
+               !   Compute the proportion of filter feeders
+               !   ----------------------------------------  
+               zproport  = (zgrazffep + zgrazffeg)/(rtrn + zgraztotc)
+
+               !   Compute fractionation of aggregates. It is assumed that 
+               !   diatoms based aggregates are more prone to fractionation
+               !   since they are more porous (marine snow instead of fecal pellets)
+               !   ----------------------------------------------------------------
+               zratio    = trb(ji,jj,jk,jpgsi) / ( trb(ji,jj,jk,jpgoc) + rtrn )
+               zratio2   = zratio * zratio
+               zfracc    = zproport * grazflux  * xstep * wsbio4(ji,jj,jk)      &
+               &          * trb(ji,jj,jk,jpgoc) * trb(ji,jj,jk,jpmes)          &
+               &          * ( 0.2 + 3.8 * zratio2 / ( 1.**2 + zratio2 ) )
+               zfracfe   = zfracc * trb(ji,jj,jk,jpbfe) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zfracn    = zfracc * trb(ji,jj,jk,jpgon) / (trb(ji,jj,jk,jpgoc) + rtrn)
+               zfracp    = zfracc * trb(ji,jj,jk,jpgop) / (trb(ji,jj,jk,jpgoc) + rtrn)
+
+               zgrazffep = zproport * zgrazffep   ;   zgrazffeg = zproport * zgrazffeg
+               zgrazfffp = zproport * zgrazfffp   ;   zgrazfffg = zproport * zgrazfffg
+               zgrazffnp = zproport * zgrazffnp   ;   zgrazffng = zproport * zgrazffng
+               zgrazffpp = zproport * zgrazffpp   ;   zgrazffpg = zproport * zgrazffpg
+
+               zgraztotc  = zgrazdc + zgrazz + zgraznc + zgrazm + zgrazpoc + zgrazffep + zgrazffeg
+               zgraztotf  = zgrazdf + zgraznf + ( zgrazz + zgrazm ) * ferat3 + zgrazpof &
+               &            + zgrazfffp + zgrazfffg
+               zgraztotn  = zgrazdn + (zgrazm + zgrazz) * no3rat3 + zgraznn + zgrazpon  &
+               &            + zgrazffnp + zgrazffng
+               zgraztotp  = zgrazdp + (zgrazz + zgrazm) * po4rat3 + zgraznp + zgrazpop  &
+               &            + zgrazffpp + zgrazffpg
+
+
+               ! Total grazing ( grazing by microzoo is already computed in p5zmicro )
+               zgrazing2(ji,jj,jk) = zgraztotc
+
+               !   Stoichiometruc ratios of the food ingested by zooplanton 
+               !   --------------------------------------------------------
+               zgrasratf  =  (zgraztotf + rtrn) / ( zgraztotc + rtrn )
+               zgrasratn  =  (zgraztotn + rtrn) / ( zgraztotc + rtrn )
+               zgrasratp  =  (zgraztotp + rtrn) / ( zgraztotc + rtrn )
+
+               !   Growth efficiency is made a function of the quality 
+               !   and the quantity of the preys
+               !   ---------------------------------------------------
+               zepshert  = MIN( 1., zgrasratn/ no3rat3, zgrasratp/ po4rat3, zgrasratf / ferat3)
+               zbeta     = MAX(0., (epsher2 - epsher2min) )
+               zepsherf  = epsher2min + zbeta / ( 1.0 + 0.04E6 * 12. * zfood * zbeta )
+               zepsherv  = zepsherf * zepshert
+
+               !   Respiration of mesozooplankton
+               !   Excess carbon in the food is used preferentially
+               !   ----------------  ------------------------------
+               zexcess  = zgraztotc * zepsherf * (1.0 - zepshert) * zmetexcess 
+               zbasresb = MAX(0., zrespz - zexcess)
+               zbasresi = zexcess + MIN(0., zrespz - zexcess)
+               zrespirc = srespir2 * zepsherv * zgraztotc + zbasresb
+
+               !   When excess carbon is used, the other elements in excess
+               !   are also used proportionally to their abundance
+               !   --------------------------------------------------------
+               zexcess  = ( zgrasratn/ no3rat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresn = zbasresi * zexcess * zgrasratn
+               zexcess  = ( zgrasratp/ po4rat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresp = zbasresi * zexcess * zgrasratp
+               zexcess  = ( zgrasratf/ ferat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresf = zbasresi * zexcess * zgrasratf
+
+               !   Voiding of the excessive elements as organic matter
+               !   --------------------------------------------------------
+               zgradoct = (1. - unass2c - zepsherv) * zgraztotc - zbasresi
+               zgradont = (1. - unass2n) * zgraztotn - zepsherv * no3rat3 * zgraztotc - zbasresn
+               zgradopt = (1. - unass2p) * zgraztotp - zepsherv * po4rat3 * zgraztotc - zbasresp
+               zgrareft = (1. - unass2c) * zgraztotf - zepsherv * ferat3 * zgraztotc - zbasresf
+               ztmp1   = ( 1. - epsher2 - unass2c ) /( 1. - 0.8 * epsher2 ) * ztortz
+               zgradoc = (zgradoct + ztmp1) * ssigma2
+               zgradon = (zgradont + no3rat3 * ztmp1) * ssigma2
+               zgradop = (zgradopt + po4rat3 * ztmp1) * ssigma2
+               zgratmp = 0.2 * epsher2 /( 1. - 0.8 * epsher2 ) * ztortz
+
+               !  Since only semilabile DOM is represented in PISCES
+               !  part of DOM is in fact labile and is then released
+               !  as dissolved inorganic compounds (ssigma2)
+               !  --------------------------------------------------
+               zgrarem = zgratmp + ( zgradoct + ztmp1 ) * (1.0 - ssigma2)
+               zgraren = no3rat3 * zgratmp + ( zgradont + no3rat3 * ztmp1 ) * (1.0 - ssigma2)
+               zgrarep = po4rat3 * zgratmp + ( zgradopt + po4rat3 * ztmp1 ) * (1.0 - ssigma2)
+               zgraref = zgrareft + ferat3 * ( ztmp1 + zgratmp )
+
+               !   Defecation as a result of non assimilated products
+               !   --------------------------------------------------
+               zgrapoc  = zgraztotc * unass2c + unass2c / ( 1. - 0.8 * epsher2 ) * ztortz
+               zgrapon  = zgraztotn * unass2n + no3rat3 * unass2n / ( 1. - 0.8 * epsher2 ) * ztortz
+               zgrapop  = zgraztotp * unass2p + po4rat3 * unass2p / ( 1. - 0.8 * epsher2 ) * ztortz
+               zgrapof  = zgraztotf * unass2c + ferat3  * unass2c / ( 1. - 0.8 * epsher2 ) * ztortz
+
+               !  Addition of respiration to the release of inorganic nutrients
+               !  -------------------------------------------------------------
+               zgrarem = zgrarem + zbasresi + zrespirc
+               zgraren = zgraren + zbasresn + zrespirc * no3rat3
+               zgrarep = zgrarep + zbasresp + zrespirc * po4rat3
+               zgraref = zgraref + zbasresf + zrespirc * ferat3
+
+               !   Update the arrays TRA which contain the biological sources and
+               !   sinks
+               !   --------------------------------------------------------------
+               tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zgrarep 
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zgraren
+               tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zgradoc
+               !
+               IF( ln_ligand ) THEN
+                  tra(ji,jj,jk,jplgw)  = tra(ji,jj,jk,jplgw) + zgradoc * ldocz
+                  zz2ligprod(ji,jj,jk) = zgradoc * ldocz
+               ENDIF
+               !
+               tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + zgradon
+               tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + zgradop
+               tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - o2ut * zgrarem
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zgraref
+               zfezoo2(ji,jj,jk)   = zgraref
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrarem
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * zgraren
+               tra(ji,jj,jk,jpmes) = tra(ji,jj,jk,jpmes) + zepsherv * zgraztotc - zrespirc   &
+               &                     - ztortz - zgrazm
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zgrazdc
+               tra(ji,jj,jk,jpndi) = tra(ji,jj,jk,jpndi) - zgrazdn
+               tra(ji,jj,jk,jppdi) = tra(ji,jj,jk,jppdi) - zgrazdp
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zgrazdf
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) - zgrazz
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zgraznc
+               tra(ji,jj,jk,jpnph) = tra(ji,jj,jk,jpnph) - zgraznn
+               tra(ji,jj,jk,jppph) = tra(ji,jj,jk,jppph) - zgraznp
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zgraznf
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zgraznc * trb(ji,jj,jk,jpnch) / ( trb(ji,jj,jk,jpphy) + rtrn )
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zgrazdc * trb(ji,jj,jk,jpdch) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zgrazdc * trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zgrazdc * trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) - zgrazpoc - zgrazffep + zfracc
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + zfracc
+               conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zgrazpoc - zgrazffep
+               tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) - zgrazpon - zgrazffnp + zfracn
+               tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) - zgrazpop - zgrazffpp + zfracp
+               tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) - zgrazffeg + zgrapoc - zfracc
+               prodgoc(ji,jj,jk) = prodgoc(ji,jj,jk) + zgrapoc
+               consgoc(ji,jj,jk) = consgoc(ji,jj,jk) - zgrazffeg - zfracc
+               tra(ji,jj,jk,jpgon) = tra(ji,jj,jk,jpgon) - zgrazffng + zgrapon - zfracn
+               tra(ji,jj,jk,jpgop) = tra(ji,jj,jk,jpgop) - zgrazffpg + zgrapop - zfracp
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) - zgrazpof - zgrazfffp + zfracfe
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) - zgrazfffg + zgrapof - zfracfe
+               zfracal = trb(ji,jj,jk,jpcal) / ( trb(ji,jj,jk,jpgoc) + rtrn )
+               zgrazcal = zgrazffeg * (1. - part2) * zfracal
+
+               !  calcite production
+               !  ------------------
+               zprcaca = xfracal(ji,jj,jk) * zgraznc
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               zprcaca = part2 * zprcaca
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrazcal - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + 2. * ( zgrazcal - zprcaca )
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) - zgrazcal + zprcaca
+            END DO
+         END DO
+      END DO
+      !
+       IF( lk_iomput .AND. knt == nrdttrc ) THEN
+         CALL iom_put( "PCAL"  , prodcal(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) )  !  Calcite production 
+         IF( iom_use("GRAZ2") ) THEN  !   Total grazing of phyto by zooplankton
+           zgrazing2(:,:,jpk) = 0._wp ;  CALL iom_put( "GRAZ2" , zgrazing2(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) ) 
+         ENDIF
+         IF( iom_use("FEZOO2") ) THEN  
+           zfezoo2 (:,:,jpk) = 0._wp ; CALL iom_put( "FEZOO2", zfezoo2(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( ln_ligand ) THEN
+            zz2ligprod(:,:,jpk) = 0._wp ; CALL iom_put( "LPRODZ2", zz2ligprod(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:)  )
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+        WRITE(charout, FMT="('meso')")
+        CALL prt_ctl_trc_info(charout)
+        CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_meso')
+      !
+   END SUBROUTINE p5z_meso
+
+
+   SUBROUTINE p5z_meso_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p5z_meso_init  ***
+      !!
+      !! ** Purpose :   Initialization of mesozooplankton parameters
+      !!
+      !! ** Method  :   Read the nampismes namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampismes
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/namp5zmes/part2, bmetexc2, grazrat2, resrat2, mzrat2, xpref2c, xpref2n, xpref2z, &
+         &                xpref2m, xpref2d, xthresh2dia, xthresh2phy, xthresh2zoo, xthresh2poc, &
+         &                xthresh2mes, xthresh2, xkgraz2, epsher2, epsher2min, ssigma2, unass2c, &
+         &                unass2n, unass2p, srespir2, grazflux
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp5zmes, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nampismes in reference namelist' )
+      !
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp5zmes, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'nampismes in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zmes )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' ' 
+         WRITE(numout,*) ' Namelist parameters for mesozooplankton, namp5zmes'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    part of calcite not dissolved in mesozoo guts  part2       = ', part2
+         WRITE(numout,*) '    mesozoo preference for nano.                   xpref2n     = ', xpref2n
+         WRITE(numout,*) '    mesozoo preference for diatoms                 xpref2d     = ', xpref2d
+         WRITE(numout,*) '    mesozoo preference for zoo                     xpref2z     = ', xpref2z
+         WRITE(numout,*) '    mesozoo preference for mesozoo                 xpref2m     = ', xpref2m
+         WRITE(numout,*) '    mesozoo preference for poc                     xpref2c     = ', xpref2c
+         WRITE(numout,*) '    microzoo feeding threshold  for mesozoo        xthresh2zoo = ', xthresh2zoo
+         WRITE(numout,*) '    diatoms feeding threshold  for mesozoo         xthresh2dia = ', xthresh2dia
+         WRITE(numout,*) '    nanophyto feeding threshold for mesozoo        xthresh2phy = ', xthresh2phy
+         WRITE(numout,*) '    poc feeding threshold for mesozoo              xthresh2poc = ', xthresh2poc
+         WRITE(numout,*) '    mesozoo feeding threshold for mesozoo          xthresh2mes = ', xthresh2mes
+         WRITE(numout,*) '    feeding threshold for mesozooplankton          xthresh2    = ', xthresh2
+         WRITE(numout,*) '    exsudation rate of mesozooplankton             resrat2     = ', resrat2
+         WRITE(numout,*) '    mesozooplankton mortality rate                 mzrat2      = ', mzrat2
+         WRITE(numout,*) '    maximal mesozoo grazing rate                   grazrat2    = ', grazrat2
+         WRITE(numout,*) '    mesozoo flux feeding rate                      grazflux    = ', grazflux
+         WRITE(numout,*) '    C egested fraction of food by mesozoo          unass2c     = ', unass2c
+         WRITE(numout,*) '    N egested fraction of food by mesozoo          unass2n     = ', unass2n
+         WRITE(numout,*) '    P egested fraction of food by mesozoo          unass2p     = ', unass2p
+         WRITE(numout,*) '    Efficicency of Mesozoo growth                  epsher2     = ', epsher2
+         WRITE(numout,*) '    Minimum Efficiency of Mesozoo growth           epsher2min  =', epsher2min
+         WRITE(numout,*) '    Fraction excreted as semi-labile DOM           ssigma2     = ', ssigma2
+         WRITE(numout,*) '    Active respiration                             srespir2    = ', srespir2
+         WRITE(numout,*) '    half sturation constant for grazing 2          xkgraz2     = ', xkgraz2
+         WRITE(numout,*) '    Use excess carbon for respiration              bmetexc2    = ', bmetexc2
+      ENDIF
+      !
+   END SUBROUTINE p5z_meso_init
+
+   !!======================================================================
+END MODULE p5zmeso
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmicro.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmicro.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmicro.F90	(revision 14097)
@@ -0,0 +1,380 @@
+MODULE p5zmicro
+   !!======================================================================
+   !!                         ***  MODULE p5zmicro  ***
+   !! TOP :   PISCES Compute the sources/sinks for microzooplankton
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Quota model for iron
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p5z_micro       :   Compute the sources/sinks for microzooplankton
+   !!   p5z_micro_init  :   Initialize and read the appropriate namelist
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zlim
+   USE p5zlim          !  Phytoplankton limitation terms
+   USE iom             !  I/O manager
+   USE prtctl_trc      !  print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p5z_micro         ! called in p5zbio.F90
+   PUBLIC   p5z_micro_init    ! called in trcsms_pisces.F90
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC ::  part        !: part of calcite not dissolved in microzoo guts
+   REAL(wp), PUBLIC ::  xprefc     !: microzoo preference for POC 
+   REAL(wp), PUBLIC ::  xprefn     !: microzoo preference for nanophyto
+   REAL(wp), PUBLIC ::  xprefp     !: microzoo preference for picophyto
+   REAL(wp), PUBLIC ::  xprefd     !: microzoo preference for diatoms
+   REAL(wp), PUBLIC ::  xprefz     !: microzoo preference for microzoo
+   REAL(wp), PUBLIC ::  xthreshdia  !: diatoms feeding threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  xthreshpic  !: picophyto feeding threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  xthreshphy  !: nanophyto threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  xthreshzoo  !: microzoo threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  xthreshpoc  !: poc threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  xthresh     !: feeding threshold for microzooplankton 
+   REAL(wp), PUBLIC ::  resrat      !: exsudation rate of microzooplankton
+   REAL(wp), PUBLIC ::  mzrat       !: microzooplankton mortality rate 
+   REAL(wp), PUBLIC ::  grazrat     !: maximal microzoo grazing rate
+   REAL(wp), PUBLIC ::  xkgraz      !: Half-saturation constant of assimilation
+   REAL(wp), PUBLIC ::  unassc      !: Non-assimilated part of food
+   REAL(wp), PUBLIC ::  unassn      !: Non-assimilated part of food
+   REAL(wp), PUBLIC ::  unassp      !: Non-assimilated part of food
+   REAL(wp), PUBLIC ::  epsher      !: Growth efficiency for microzoo
+   REAL(wp), PUBLIC ::  epshermin   !: Minimum growth efficiency for microzoo
+   REAL(wp), PUBLIC ::  srespir     !: half sturation constant for grazing 1 
+   REAL(wp), PUBLIC ::  ssigma      !: Fraction excreted as semi-labile DOM
+   LOGICAL,  PUBLIC ::  bmetexc     !: Use of excess carbon for respiration
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE p5z_micro( kt, knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_micro  ***
+      !!
+      !! ** Purpose :   Compute the sources/sinks for microzooplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::  kt  ! ocean time step
+      INTEGER, INTENT(in) ::  knt 
+      !
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompadi, zcompaz , zcompaph, zcompapoc, zcompapon, zcompapop
+      REAL(wp) :: zcompapi, zgraze  , zdenom, zfact, zfood, zfoodlim
+      REAL(wp) :: ztmp1, ztmp2, ztmp3, ztmp4, ztmp5, ztmptot
+      REAL(wp) :: zepsherf, zepshert, zepsherv, zrespirc, zrespirn, zrespirp, zbasresb, zbasresi
+      REAL(wp) :: zgraztotc, zgraztotn, zgraztotp, zgraztotf, zbasresn, zbasresp, zbasresf
+      REAL(wp) :: zgradoc, zgradon, zgradop, zgraref, zgradoct, zgradont, zgradopt, zgrareft
+      REAL(wp) :: zexcess, zgraren, zgrarep, zgrarem
+      REAL(wp) :: zgrapoc, zgrapon, zgrapop, zgrapof, zprcaca, zmortz
+      REAL(wp) :: zrespz, ztortz, zgrasratf, zgrasratn, zgrasratp
+      REAL(wp) :: zgraznc, zgraznn, zgraznp, zgrazpoc, zgrazpon, zgrazpop, zgrazpof
+      REAL(wp) :: zgrazdc, zgrazdn, zgrazdp, zgrazdf, zgraznf, zgrazz
+      REAL(wp) :: zgrazpc, zgrazpn, zgrazpp, zgrazpf, zbeta, zrfact2, zmetexcess
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zgrazing, zfezoo, zzligprod
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_micro')
+      !
+      zmetexcess = 0.0
+      IF ( bmetexc ) zmetexcess = 1.0
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompaz = MAX( ( trb(ji,jj,jk,jpzoo) - 1.e-9 ), 0.e0 )
+               zfact   = xstep * tgfunc2(ji,jj,jk) * zcompaz
+
+               !   Michaelis-Menten mortality rates of microzooplankton
+               !   -----------------------------------------------------
+               zrespz = resrat * zfact * ( trb(ji,jj,jk,jpzoo) / ( xkmort + trb(ji,jj,jk,jpzoo) )  &
+               &        + 3. * nitrfac(ji,jj,jk) )
+
+               !   Zooplankton mortality. A square function has been selected with
+               !   no real reason except that it seems to be more stable and may mimic predation.
+               !   ------------------------------------------------------------------------------
+               ztortz = mzrat * 1.e6 * zfact * trb(ji,jj,jk,jpzoo) * (1. - nitrfac(ji,jj,jk))
+
+               !   Computation of the abundance of the preys
+               !   A threshold can be specified in the namelist
+               !   --------------------------------------------
+               zcompadi  = MIN( MAX( ( trb(ji,jj,jk,jpdia) - xthreshdia ), 0.e0 ), xsizedia )
+               zcompaph  = MAX( ( trb(ji,jj,jk,jpphy) - xthreshphy ), 0.e0 )
+               zcompaz   = MAX( ( trb(ji,jj,jk,jpzoo) - xthreshzoo ), 0.e0 )
+               zcompapi  = MAX( ( trb(ji,jj,jk,jppic) - xthreshpic ), 0.e0 )
+               zcompapoc = MAX( ( trb(ji,jj,jk,jppoc) - xthreshpoc ), 0.e0 )
+               
+               !   Microzooplankton grazing
+               !   ------------------------
+               zfood     = xprefn * zcompaph + xprefc * zcompapoc + xprefd * zcompadi   &
+               &           + xprefz * zcompaz + xprefp * zcompapi
+               zfoodlim  = MAX( 0. , zfood - min(xthresh,0.5*zfood) )
+               zdenom    = zfoodlim / ( xkgraz + zfoodlim )
+               zgraze    = grazrat * xstep * tgfunc2(ji,jj,jk) * trb(ji,jj,jk,jpzoo) * (1. - nitrfac(ji,jj,jk)) 
+
+               !   An active switching parameterization is used here.
+               !   We don't use the KTW parameterization proposed by 
+               !   Vallina et al. because it tends to produce to steady biomass
+               !   composition and the variance of Chl is too low as it grazes
+               !   too strongly on winning organisms. Thus, instead of a square
+               !   a 1.5 power value is used which decreases the pressure on the
+               !   most abundant species
+               !   ------------------------------------------------------------  
+               ztmp1 = xprefn * zcompaph**1.5
+               ztmp2 = xprefp * zcompapi**1.5
+               ztmp3 = xprefc * zcompapoc**1.5
+               ztmp4 = xprefd * zcompadi**1.5
+               ztmp5 = xprefz * zcompaz**1.5
+               ztmptot = ztmp1 + ztmp2 + ztmp3 + ztmp4 + ztmp5 + rtrn
+               ztmp1 = ztmp1 / ztmptot
+               ztmp2 = ztmp2 / ztmptot
+               ztmp3 = ztmp3 / ztmptot
+               ztmp4 = ztmp4 / ztmptot
+               ztmp5 = ztmp5 / ztmptot
+
+               !   Microzooplankton regular grazing on the different preys
+               !   -------------------------------------------------------
+               zgraznc   = zgraze  * ztmp1  * zdenom
+               zgraznn   = zgraznc * trb(ji,jj,jk,jpnph) / (trb(ji,jj,jk,jpphy) + rtrn)
+               zgraznp   = zgraznc * trb(ji,jj,jk,jppph) / (trb(ji,jj,jk,jpphy) + rtrn)
+               zgraznf   = zgraznc * trb(ji,jj,jk,jpnfe) / (trb(ji,jj,jk,jpphy) + rtrn)
+               zgrazpc   = zgraze  * ztmp2  * zdenom
+               zgrazpn   = zgrazpc * trb(ji,jj,jk,jpnpi) / (trb(ji,jj,jk,jppic) + rtrn)
+               zgrazpp   = zgrazpc * trb(ji,jj,jk,jpppi) / (trb(ji,jj,jk,jppic) + rtrn)
+               zgrazpf   = zgrazpc * trb(ji,jj,jk,jppfe) / (trb(ji,jj,jk,jppic) + rtrn)
+               zgrazz    = zgraze  * ztmp5   * zdenom
+               zgrazpoc  = zgraze  * ztmp3   * zdenom
+               zgrazpon  = zgrazpoc * trb(ji,jj,jk,jppon) / ( trb(ji,jj,jk,jppoc) + rtrn )
+               zgrazpop  = zgrazpoc * trb(ji,jj,jk,jppop) / ( trb(ji,jj,jk,jppoc) + rtrn )
+               zgrazpof  = zgrazpoc* trb(ji,jj,jk,jpsfe) / (trb(ji,jj,jk,jppoc) + rtrn)
+               zgrazdc   = zgraze  * ztmp4  * zdenom
+               zgrazdn   = zgrazdc * trb(ji,jj,jk,jpndi) / (trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazdp   = zgrazdc * trb(ji,jj,jk,jppdi) / (trb(ji,jj,jk,jpdia) + rtrn)
+               zgrazdf   = zgrazdc * trb(ji,jj,jk,jpdfe) / (trb(ji,jj,jk,jpdia) + rtrn)
+               !
+               zgraztotc = zgraznc + zgrazpoc + zgrazdc + zgrazz + zgrazpc
+               zgraztotn = zgraznn + zgrazpn + zgrazpon + zgrazdn + zgrazz * no3rat3
+               zgraztotp = zgraznp + zgrazpp + zgrazpop + zgrazdp + zgrazz * po4rat3
+               zgraztotf = zgraznf + zgrazpf + zgrazpof + zgrazdf + zgrazz * ferat3
+               !
+               ! Grazing by microzooplankton
+               zgrazing(ji,jj,jk) = zgraztotc
+
+               !   Stoichiometruc ratios of the food ingested by zooplanton 
+               !   --------------------------------------------------------
+               zgrasratf =  (zgraztotf + rtrn) / ( zgraztotc + rtrn )
+               zgrasratn =  (zgraztotn + rtrn) / ( zgraztotc + rtrn )
+               zgrasratp =  (zgraztotp + rtrn) / ( zgraztotc + rtrn )
+
+               !   Growth efficiency is made a function of the quality 
+               !   and the quantity of the preys
+               !   ---------------------------------------------------
+               zepshert  = MIN( 1., zgrasratn/ no3rat3, zgrasratp/ po4rat3, zgrasratf / ferat3)
+               zbeta     = MAX( 0., (epsher - epshermin) )
+               zepsherf  = epshermin + zbeta / ( 1.0 + 0.04E6 * 12. * zfood * zbeta )
+               zepsherv  = zepsherf * zepshert
+
+               !   Respiration of microzooplankton
+               !   Excess carbon in the food is used preferentially
+               !   ------------------------------------------------
+               zexcess  = zgraztotc * zepsherf * (1.0 - zepshert) * zmetexcess
+               zbasresb = MAX(0., zrespz - zexcess)
+               zbasresi = zexcess + MIN(0., zrespz - zexcess)  
+               zrespirc = srespir * zepsherv * zgraztotc + zbasresb
+               
+               !   When excess carbon is used, the other elements in excess
+               !   are also used proportionally to their abundance
+               !   --------------------------------------------------------
+               zexcess  = ( zgrasratn/ no3rat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresn = zbasresi * zexcess * zgrasratn 
+               zexcess  = ( zgrasratp/ po4rat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresp = zbasresi * zexcess * zgrasratp
+               zexcess  = ( zgrasratf/ ferat3 - zepshert ) / ( 1.0 - zepshert + rtrn)
+               zbasresf = zbasresi * zexcess * zgrasratf
+
+               !   Voiding of the excessive elements as DOM
+               !   ----------------------------------------
+               zgradoct   = (1. - unassc - zepsherv) * zgraztotc - zbasresi  
+               zgradont   = (1. - unassn) * zgraztotn - zepsherv * no3rat3 * zgraztotc - zbasresn
+               zgradopt   = (1. - unassp) * zgraztotp - zepsherv * po4rat3 * zgraztotc - zbasresp
+               zgrareft   = (1. - unassc) * zgraztotf - zepsherv * ferat3 * zgraztotc - zbasresf
+
+               !  Since only semilabile DOM is represented in PISCES
+               !  part of DOM is in fact labile and is then released
+               !  as dissolved inorganic compounds (ssigma)
+               !  --------------------------------------------------
+               zgradoc =  zgradoct * ssigma
+               zgradon =  zgradont * ssigma
+               zgradop =  zgradopt * ssigma
+               zgrarem = (1.0 - ssigma) * zgradoct
+               zgraren = (1.0 - ssigma) * zgradont
+               zgrarep = (1.0 - ssigma) * zgradopt
+               zgraref = zgrareft
+
+               !   Defecation as a result of non assimilated products
+               !   --------------------------------------------------
+               zgrapoc   = zgraztotc * unassc
+               zgrapon   = zgraztotn * unassn
+               zgrapop   = zgraztotp * unassp
+               zgrapof   = zgraztotf * unassc
+
+               !  Addition of respiration to the release of inorganic nutrients
+               !  -------------------------------------------------------------
+               zgrarem = zgrarem + zbasresi + zrespirc
+               zgraren = zgraren + zbasresn + zrespirc * no3rat3
+               zgrarep = zgrarep + zbasresp + zrespirc * po4rat3
+               zgraref = zgraref + zbasresf + zrespirc * ferat3
+
+               !   Update of the TRA arrays
+               !   ------------------------
+               tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) + zgrarep
+               tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) + zgraren
+               tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + zgradoc
+               !
+               IF( ln_ligand ) THEN 
+                  tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + zgradoc * ldocz
+                  zzligprod(ji,jj,jk) = zgradoc * ldocz
+               ENDIF
+               !
+               tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + zgradon
+               tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + zgradop
+               tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) - o2ut * zgrarem 
+               tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) + zgraref
+               zfezoo(ji,jj,jk)    = zgraref
+               tra(ji,jj,jk,jpzoo) = tra(ji,jj,jk,jpzoo) + zepsherv * zgraztotc - zrespirc - ztortz - zgrazz
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zgraznc
+               tra(ji,jj,jk,jpnph) = tra(ji,jj,jk,jpnph) - zgraznn
+               tra(ji,jj,jk,jppph) = tra(ji,jj,jk,jppph) - zgraznp
+               tra(ji,jj,jk,jppic) = tra(ji,jj,jk,jppic) - zgrazpc
+               tra(ji,jj,jk,jpnpi) = tra(ji,jj,jk,jpnpi) - zgrazpn
+               tra(ji,jj,jk,jpppi) = tra(ji,jj,jk,jpppi) - zgrazpp
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zgrazdc
+               tra(ji,jj,jk,jpndi) = tra(ji,jj,jk,jpndi) - zgrazdn
+               tra(ji,jj,jk,jppdi) = tra(ji,jj,jk,jppdi) - zgrazdp
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zgraznc * trb(ji,jj,jk,jpnch)/(trb(ji,jj,jk,jpphy)+rtrn)
+               tra(ji,jj,jk,jppch) = tra(ji,jj,jk,jppch) - zgrazpc * trb(ji,jj,jk,jppch)/(trb(ji,jj,jk,jppic)+rtrn)
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zgrazdc * trb(ji,jj,jk,jpdch)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zgrazdc * trb(ji,jj,jk,jpdsi)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zgrazdc * trb(ji,jj,jk,jpdsi)/(trb(ji,jj,jk,jpdia)+rtrn)
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zgraznf
+               tra(ji,jj,jk,jppfe) = tra(ji,jj,jk,jppfe) - zgrazpf
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zgrazdf
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + ztortz + zgrapoc - zgrazpoc 
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + ztortz + zgrapoc
+               conspoc(ji,jj,jk) = conspoc(ji,jj,jk) - zgrazpoc
+               tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + no3rat3 * ztortz + zgrapon - zgrazpon
+               tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + po4rat3 * ztortz + zgrapop - zgrazpop
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + ferat3 * ztortz  + zgrapof - zgrazpof
+               !
+               ! calcite production
+               zprcaca = xfracal(ji,jj,jk) * zgraznc
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               !
+               zprcaca = part * zprcaca
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) + zgrarem - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2. * zprcaca     &
+               &                     + rno3 * zgraren
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) + zprcaca
+            END DO
+         END DO
+      END DO
+      !
+      IF( lk_iomput .AND. knt == nrdttrc ) THEN
+        IF( iom_use("GRAZ1") ) THEN  !   Total grazing of phyto by zooplankton
+           zgrazing(:,:,jpk) = 0._wp   ; CALL iom_put( "GRAZ1" , zgrazing(:,:,:) * 1.e+3  * rfact2r * tmask(:,:,:) ) 
+         ENDIF
+         IF( iom_use("FEZOO") ) THEN  
+           zfezoo (:,:,jpk) = 0._wp    ; CALL iom_put( "FEZOO" , zfezoo(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:) )
+         ENDIF
+         IF( ln_ligand ) THEN
+            zzligprod(:,:,jpk) = 0._wp ; CALL iom_put( "LPRODZ", zzligprod(:,:,:) * 1e9 * 1.e+3 * rfact2r * tmask(:,:,:))
+         ENDIF
+      ENDIF
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('micro')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_micro')
+      !
+   END SUBROUTINE p5z_micro
+
+
+   SUBROUTINE p5z_micro_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p5z_micro_init  ***
+      !!
+      !! ** Purpose :   Initialization of microzooplankton parameters
+      !!
+      !! ** Method  :   Read the nampiszoo namelist and check the parameters
+      !!                called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampiszoo
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namp5zzoo/ part, grazrat, bmetexc, resrat, mzrat, xprefc, xprefn, &
+         &                xprefp, xprefd, xprefz, xthreshdia, xthreshphy, &
+         &                xthreshpic, xthreshpoc, xthreshzoo, xthresh, xkgraz, &
+         &                epsher, epshermin, ssigma, srespir, unassc, unassn, unassp
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp5zzoo, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namp5zzoo in reference namelist' )
+      !
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp5zzoo, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namp5zzoo in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zzoo )
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Namelist parameters for microzooplankton, nampiszooq'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    part of calcite not dissolved in microzoo guts  part        =', part
+         WRITE(numout,*) '    microzoo preference for POC                     xprefc     =', xprefc
+         WRITE(numout,*) '    microzoo preference for nano                    xprefn     =', xprefn
+         WRITE(numout,*) '    microzoo preference for pico                    xprefp     =', xprefp
+         WRITE(numout,*) '    microzoo preference for diatoms                 xprefd     =', xprefd
+         WRITE(numout,*) '    microzoo preference for microzoo                xprefz     =', xprefz
+         WRITE(numout,*) '    diatoms feeding threshold  for microzoo         xthreshdia  =', xthreshdia
+         WRITE(numout,*) '    nanophyto feeding threshold for microzoo        xthreshphy  =', xthreshphy
+         WRITE(numout,*) '    picophyto feeding threshold for microzoo        xthreshpic  =', xthreshpic
+         WRITE(numout,*) '    poc feeding threshold for microzoo              xthreshpoc  =', xthreshpoc
+         WRITE(numout,*) '    microzoo feeding threshold for microzoo         xthreshzoo  =', xthreshzoo
+         WRITE(numout,*) '    feeding threshold for microzooplankton          xthresh     =', xthresh
+         WRITE(numout,*) '    exsudation rate of microzooplankton             resrat      =', resrat
+         WRITE(numout,*) '    microzooplankton mortality rate                 mzrat       =', mzrat
+         WRITE(numout,*) '    maximal microzoo grazing rate                   grazrat     =', grazrat
+         WRITE(numout,*) '    C egested fraction of fodd by microzoo          unassc      =', unassc
+         WRITE(numout,*) '    N egested fraction of fodd by microzoo          unassn      =', unassn
+         WRITE(numout,*) '    P egested fraction of fodd by microzoo          unassp      =', unassp
+         WRITE(numout,*) '    Efficicency of microzoo growth                  epsher      =', epsher
+         WRITE(numout,*) '    Minimum Efficiency of Microzoo growth           epshermin   =', epshermin
+         WRITE(numout,*) '    Fraction excreted as semi-labile DOM            ssigma      =', ssigma
+         WRITE(numout,*) '    Active respiration                              srespir     =', srespir
+         WRITE(numout,*) '    half sturation constant for grazing 1           xkgraz      =', xkgraz
+         WRITE(numout,*) '    Use of excess carbon for respiration            bmetexc     =', bmetexc
+      ENDIF
+      !
+   END SUBROUTINE p5z_micro_init
+
+   !!======================================================================
+END MODULE p5zmicro
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmort.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmort.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zmort.F90	(revision 14097)
@@ -0,0 +1,313 @@
+MODULE p5zmort
+   !!======================================================================
+   !!                         ***  MODULE p5zmort  ***
+   !! TOP :   PISCES Compute the mortality terms for phytoplankton
+   !!======================================================================
+   !! History :   1.0  !  2002     (O. Aumont)  Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p5z_mort       :   Compute the mortality terms for phytoplankton
+   !!   p5z_mort_init  :   Initialize the mortality params for phytoplankton
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zlim
+   USE p5zlim          !  Phytoplankton limitation terms
+   USE prtctl_trc      !  print control for debugging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p5z_mort    
+   PUBLIC   p5z_mort_init    
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC :: wchln    !:
+   REAL(wp), PUBLIC :: wchlp   !:
+   REAL(wp), PUBLIC :: wchld   !:
+   REAL(wp), PUBLIC :: wchldm  !:
+   REAL(wp), PUBLIC :: mpratn   !:
+   REAL(wp), PUBLIC :: mpratp  !:
+   REAL(wp), PUBLIC :: mpratd  !:
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE p5z_mort( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_mort  ***
+      !!
+      !! ** Purpose :   Calls the different subroutine to initialize and compute
+      !!                the different phytoplankton mortality terms
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt ! ocean time step
+      !!---------------------------------------------------------------------
+
+      CALL p5z_nano            ! nanophytoplankton
+      CALL p5z_pico            ! picophytoplankton
+      CALL p5z_diat            ! diatoms
+
+   END SUBROUTINE p5z_mort
+
+
+   SUBROUTINE p5z_nano
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_nano  ***
+      !!
+      !! ** Purpose :   Compute the mortality terms for nanophytoplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompaph
+      REAL(wp) :: zfactfe, zfactch, zfactn, zfactp, zprcaca
+      REAL(wp) :: ztortp , zrespp , zmortp
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_nano')
+      !
+      prodcal(:,:,:) = 0.  !: calcite production variable set to zero
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompaph = MAX( ( trb(ji,jj,jk,jpphy) - 1e-9 ), 0.e0 )
+               !   Squared mortality of Phyto similar to a sedimentation term during
+               !   blooms (Doney et al. 1996)
+               !   -----------------------------------------------------------------
+               zrespp = wchln * 1.e6 * xstep * xdiss(ji,jj,jk) * zcompaph * trb(ji,jj,jk,jpphy)
+
+               !   Phytoplankton linear mortality
+               !   ------------------------------
+               ztortp = mpratn * xstep  * zcompaph
+               zmortp = zrespp + ztortp
+
+               !   Update the arrays TRA which contains the biological sources and sinks
+
+               zfactn  = trb(ji,jj,jk,jpnph)/(trb(ji,jj,jk,jpphy)+rtrn)
+               zfactp  = trb(ji,jj,jk,jppph)/(trb(ji,jj,jk,jpphy)+rtrn)
+               zfactfe = trb(ji,jj,jk,jpnfe)/(trb(ji,jj,jk,jpphy)+rtrn)
+               zfactch = trb(ji,jj,jk,jpnch)/(trb(ji,jj,jk,jpphy)+rtrn)
+               tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) - zmortp
+               tra(ji,jj,jk,jpnph) = tra(ji,jj,jk,jpnph) - zmortp * zfactn
+               tra(ji,jj,jk,jppph) = tra(ji,jj,jk,jppph) - zmortp * zfactp
+               tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) - zmortp * zfactch
+               tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) - zmortp * zfactfe
+               zprcaca = xfracal(ji,jj,jk) * zmortp
+               !
+               prodcal(ji,jj,jk) = prodcal(ji,jj,jk) + zprcaca  ! prodcal=prodcal(nanophy)+prodcal(microzoo)+prodcal(mesozoo)
+               !
+               tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) - zprcaca
+               tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) - 2. * zprcaca
+               tra(ji,jj,jk,jpcal) = tra(ji,jj,jk,jpcal) + zprcaca
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zmortp
+               tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + zmortp * zfactn
+               tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + zmortp * zfactp
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + zmortp
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zmortp * zfactfe
+            END DO
+         END DO
+      END DO
+      !
+       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('nano')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_nano')
+      !
+   END SUBROUTINE p5z_nano
+
+
+   SUBROUTINE p5z_pico
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_pico  ***
+      !!
+      !! ** Purpose :   Compute the mortality terms for picophytoplankton
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER  :: ji, jj, jk
+      REAL(wp) :: zcompaph
+      REAL(wp) :: zfactfe, zfactch, zfactn, zfactp
+      REAL(wp) :: ztortp , zrespp , zmortp 
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_pico')
+      !
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcompaph = MAX( ( trb(ji,jj,jk,jppic) - 1e-9 ), 0.e0 )
+               !  Squared mortality of Phyto similar to a sedimentation term during
+               !  blooms (Doney et al. 1996)
+               !  -----------------------------------------------------------------
+               zrespp = wchlp * 1.e6 * xstep * xdiss(ji,jj,jk) * zcompaph * trb(ji,jj,jk,jppic)
+
+               !     Phytoplankton mortality 
+               ztortp = mpratp * xstep  * zcompaph
+               zmortp = zrespp + ztortp
+
+               !   Update the arrays TRA which contains the biological sources and sinks
+
+               zfactn = trb(ji,jj,jk,jpnpi)/(trb(ji,jj,jk,jppic)+rtrn)
+               zfactp = trb(ji,jj,jk,jpppi)/(trb(ji,jj,jk,jppic)+rtrn)
+               zfactfe = trb(ji,jj,jk,jppfe)/(trb(ji,jj,jk,jppic)+rtrn)
+               zfactch = trb(ji,jj,jk,jppch)/(trb(ji,jj,jk,jppic)+rtrn)
+               tra(ji,jj,jk,jppic) = tra(ji,jj,jk,jppic) - zmortp
+               tra(ji,jj,jk,jpnpi) = tra(ji,jj,jk,jpnpi) - zmortp * zfactn
+               tra(ji,jj,jk,jpppi) = tra(ji,jj,jk,jpppi) - zmortp * zfactp
+               tra(ji,jj,jk,jppch) = tra(ji,jj,jk,jppch) - zmortp * zfactch
+               tra(ji,jj,jk,jppfe) = tra(ji,jj,jk,jppfe) - zmortp * zfactfe
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + zmortp
+               tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + zmortp * zfactn
+               tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + zmortp * zfactp
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + zmortp * zfactfe
+               prodpoc(ji,jj,jk) = prodpoc(ji,jj,jk) + zmortp
+            END DO
+         END DO
+      END DO
+      !
+       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('pico')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+       ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_pico')
+      !
+   END SUBROUTINE p5z_pico
+
+
+   SUBROUTINE p5z_diat
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_diat  ***
+      !!
+      !! ** Purpose :   Compute the mortality terms for diatoms
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER  ::  ji, jj, jk
+      REAL(wp) ::  zfactfe,zfactsi,zfactch, zfactn, zfactp, zcompadi
+      REAL(wp) ::  zrespp2, ztortp2, zmortp2
+      REAL(wp) ::  zlim2, zlim1
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_diat')
+      !
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+               zcompadi = MAX( ( trb(ji,jj,jk,jpdia) - 1E-9), 0. )
+
+               !   Aggregation term for diatoms is increased in case of nutrient
+               !   stress as observed in reality. The stressed cells become more
+               !   sticky and coagulate to sink quickly out of the euphotic zone
+               !   -------------------------------------------------------------
+               !  Phytoplankton squared mortality
+               !  -------------------------------
+               zlim2   = xlimdia(ji,jj,jk) * xlimdia(ji,jj,jk)
+               zlim1   = 0.25 * ( 1. - zlim2 ) / ( 0.25 + zlim2 ) 
+               zrespp2 = 1.e6 * xstep * (  wchld + wchldm * zlim1 ) * xdiss(ji,jj,jk) * zcompadi * trb(ji,jj,jk,jpdia)
+
+               !  Phytoplankton linear mortality 
+               !  ------------------------------
+               ztortp2 = mpratd * xstep  * zcompadi
+               zmortp2 = zrespp2 + ztortp2
+
+               !   Update the arrays tra which contains the biological sources and sinks
+               !   ---------------------------------------------------------------------
+               zfactn  = trb(ji,jj,jk,jpndi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactp  = trb(ji,jj,jk,jppdi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactch = trb(ji,jj,jk,jpdch) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactfe = trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               zfactsi = trb(ji,jj,jk,jpdsi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+               tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) - zmortp2 
+               tra(ji,jj,jk,jpndi) = tra(ji,jj,jk,jpndi) - zmortp2 * zfactn
+               tra(ji,jj,jk,jppdi) = tra(ji,jj,jk,jppdi) - zmortp2 * zfactp
+               tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) - zmortp2 * zfactch
+               tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) - zmortp2 * zfactfe
+               tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) - zmortp2 * zfactsi
+               tra(ji,jj,jk,jpgsi) = tra(ji,jj,jk,jpgsi) + zmortp2 * zfactsi
+               tra(ji,jj,jk,jpgoc) = tra(ji,jj,jk,jpgoc) + zrespp2 
+               tra(ji,jj,jk,jpgon) = tra(ji,jj,jk,jpgon) + zrespp2 * zfactn
+               tra(ji,jj,jk,jpgop) = tra(ji,jj,jk,jpgop) + zrespp2 * zfactp
+               tra(ji,jj,jk,jpbfe) = tra(ji,jj,jk,jpbfe) + zrespp2 * zfactfe
+               tra(ji,jj,jk,jppoc) = tra(ji,jj,jk,jppoc) + ztortp2
+               tra(ji,jj,jk,jppon) = tra(ji,jj,jk,jppon) + ztortp2 * zfactn
+               tra(ji,jj,jk,jppop) = tra(ji,jj,jk,jppop) + ztortp2 * zfactp
+               tra(ji,jj,jk,jpsfe) = tra(ji,jj,jk,jpsfe) + ztortp2 * zfactfe
+               prodpoc(ji,jj,jk)   = prodpoc(ji,jj,jk) + ztortp2
+               prodgoc(ji,jj,jk)   = prodgoc(ji,jj,jk) + zrespp2
+            END DO
+         END DO
+      END DO
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('diat')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_diat')
+      !
+   END SUBROUTINE p5z_diat
+
+
+   SUBROUTINE p5z_mort_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p5z_mort_init  ***
+      !!
+      !! ** Purpose :   Initialization of phytoplankton parameters
+      !!
+      !! ** Method  :   Read the nampismort namelist and check the parameters
+      !!      called at the first timestep
+      !!
+      !! ** input   :   Namelist nampismort
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/namp5zmort/ wchln, wchlp, wchld, wchldm, mpratn, mpratp, mpratd
+      !!----------------------------------------------------------------------
+
+      REWIND( numnatp_ref )              ! Namelist nampismort in reference namelist : Pisces phytoplankton
+      READ  ( numnatp_ref, namp5zmort, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namp5zmort in reference namelist' )
+
+      REWIND( numnatp_cfg )              ! Namelist nampismort in configuration namelist : Pisces phytoplankton
+      READ  ( numnatp_cfg, namp5zmort, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namp5zmort in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zmort )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Namelist parameters for phytoplankton mortality, namp5zmort'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    quadratic mortality of phytoplankton      wchln     =', wchln
+         WRITE(numout,*) '    quadratic mortality of picophyto.         wchlp     =', wchlp
+         WRITE(numout,*) '    quadratic mortality of diatoms            wchld     =', wchld
+         WRITE(numout,*) '    Additional quadratic mortality of diatoms wchldm    =', wchldm
+         WRITE(numout,*) '    nanophyto. mortality rate                 mpratn    =', mpratn
+         WRITE(numout,*) '    picophyto. mortality rate                 mpratp    =', mpratp
+         WRITE(numout,*) '    Diatoms mortality rate                    mpratd    =', mpratd
+      ENDIF
+
+   END SUBROUTINE p5z_mort_init
+
+   !!======================================================================
+END MODULE p5zmort
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zprod.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zprod.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/P4Z/p5zprod.F90	(revision 14097)
@@ -0,0 +1,574 @@
+MODULE p5zprod
+   !!======================================================================
+   !!                         ***  MODULE p5zprod  ***
+   !! TOP :  Growth Rate of the two phytoplanktons groups 
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-05  (O. Aumont, C. Ethe) New parameterization of light limitation
+   !!             3.6  !  2015-05  (O. Aumont) PISCES quota
+   !!----------------------------------------------------------------------
+   !!   p5z_prod       :   Compute the growth Rate of the two phytoplanktons groups
+   !!   p5z_prod_init  :   Initialization of the parameters for growth
+   !!   p5z_prod_alloc :   Allocate variables for growth
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE p4zlim
+   USE p5zlim          !  Co-limitations of differents nutrients
+   USE prtctl_trc      !  print control for debugging
+   USE iom             !  I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   p5z_prod         ! called in p5zbio.F90
+   PUBLIC   p5z_prod_init    ! called in trcsms_pisces.F90
+   PUBLIC   p5z_prod_alloc
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC ::  pislopen        !:
+   REAL(wp), PUBLIC ::  pislopep        !:
+   REAL(wp), PUBLIC ::  pisloped        !:
+   REAL(wp), PUBLIC ::  xadap           !:
+   REAL(wp), PUBLIC ::  excretn         !:
+   REAL(wp), PUBLIC ::  excretp         !:
+   REAL(wp), PUBLIC ::  excretd         !:
+   REAL(wp), PUBLIC ::  bresp           !:
+   REAL(wp), PUBLIC ::  thetanpm        !:
+   REAL(wp), PUBLIC ::  thetannm        !:
+   REAL(wp), PUBLIC ::  thetandm        !:
+   REAL(wp), PUBLIC ::  chlcmin         !:
+   REAL(wp), PUBLIC ::  grosip          !:
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   zdaylen
+   
+   REAL(wp) :: r1_rday                !: 1 / rday
+   REAL(wp) :: texcretn               !: 1 - excret 
+   REAL(wp) :: texcretp               !: 1 - excretp 
+   REAL(wp) :: texcretd               !: 1 - excret2        
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE p5z_prod( kt , knt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_prod  ***
+      !!
+      !! ** Purpose :   Compute the phytoplankton production depending on
+      !!              light, temperature and nutrient availability
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) :: kt, knt
+      !
+      INTEGER  ::   ji, jj, jk
+      REAL(wp) ::   zsilfac, znanotot, zpicotot, zdiattot, zconctemp, zconctemp2
+      REAL(wp) ::   zration, zratiop, zratiof, zmax, zmax2, zsilim, ztn, zadap
+      REAL(wp) ::   zpronmax, zpropmax, zprofmax, zrat
+      REAL(wp) ::   zlim, zsilfac2, zsiborn, zprod, zprontot, zproptot, zprodtot
+      REAL(wp) ::   zprnutmax, zdocprod, zprochln, zprochld, zprochlp
+      REAL(wp) ::   zpislopen, zpislopep, zpisloped, thetannm_n, thetandm_n, thetanpm_n
+      REAL(wp) ::   zrum, zcodel, zargu, zval, zfeup
+      REAL(wp) ::   zfact, zrfact2
+      CHARACTER (len=25) :: charout
+      REAL(wp), DIMENSION(jpi,jpj    ) :: zmixnano, zmixpico, zmixdiat, zstrn
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpislopeadn, zpislopeadp, zpislopeadd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprnut, zprmaxp, zprmaxn, zprmaxd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprbio, zprpic, zprdia, zysopt
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprchln, zprchlp, zprchld
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprorcan, zprorcap, zprorcad 
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprofed, zprofep, zprofen
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpronewn, zpronewp, zpronewd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zproregn, zproregp, zproregd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpropo4n, zpropo4p, zpropo4d
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zprodopn, zprodopp, zprodopd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zrespn, zrespp, zrespd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zcroissn, zcroissp, zcroissd
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zmxl_fac, zmxl_chl
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zpligprod1, zpligprod2
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('p5z_prod')
+      !
+      zprorcan(:,:,:) = 0._wp ; zprorcap(:,:,:) = 0._wp ; zprorcad(:,:,:) = 0._wp
+      zcroissn(:,:,:) = 0._wp ; zcroissp(:,:,:) = 0._wp ; zcroissd(:,:,:) = 0._wp
+      zprofed (:,:,:) = 0._wp ; zprofep (:,:,:) = 0._wp ; zprofen (:,:,:) = 0._wp
+      zpronewn(:,:,:) = 0._wp ; zpronewp(:,:,:) = 0._wp ; zpronewd(:,:,:) = 0._wp
+      zproregn(:,:,:) = 0._wp ; zproregp(:,:,:) = 0._wp ; zproregd(:,:,:) = 0._wp 
+      zpropo4n(:,:,:) = 0._wp ; zpropo4p(:,:,:) = 0._wp ; zpropo4d(:,:,:) = 0._wp
+      zprdia  (:,:,:) = 0._wp ; zprpic  (:,:,:) = 0._wp ; zprbio  (:,:,:) = 0._wp
+      zprodopn(:,:,:) = 0._wp ; zprodopp(:,:,:) = 0._wp ; zprodopd(:,:,:) = 0._wp
+      zysopt  (:,:,:) = 0._wp 
+      zrespn  (:,:,:) = 0._wp ; zrespp  (:,:,:) = 0._wp ; zrespd  (:,:,:) = 0._wp 
+
+      ! Computation of the optimal production
+      zprnut (:,:,:) = 0.65_wp * r1_rday * tgfunc(:,:,:)
+      zprmaxn(:,:,:) = ( 0.65_wp * (1. + zpsino3 * qnpmax ) ) * r1_rday * tgfunc(:,:,:)
+      zprmaxp(:,:,:) = 0.5 / 0.65 * zprmaxn(:,:,:) 
+      zprmaxd(:,:,:) = zprmaxn(:,:,:) 
+
+      ! compute the day length depending on latitude and the day
+      zrum = REAL( nday_year - 80, wp ) / REAL( nyear_len(1), wp )
+      zcodel = ASIN(  SIN( zrum * rpi * 2._wp ) * SIN( rad * 23.5_wp )  )
+
+      ! day length in hours
+      zstrn(:,:) = 0.
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zargu = TAN( zcodel ) * TAN( gphit(ji,jj) * rad )
+            zargu = MAX( -1., MIN(  1., zargu ) )
+            zstrn(ji,jj) = MAX( 0.0, 24. - 2. * ACOS( zargu ) / rad / 15. )
+         END DO
+      END DO
+
+         ! Impact of the day duration on phytoplankton growth
+      DO jk = 1, jpkm1
+         DO jj = 1 ,jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  zval = MAX( 1., zstrn(ji,jj) )
+                  IF( gdepw_n(ji,jj,jk+1) <= hmld(ji,jj) ) THEN
+                     zval = zval * MIN(1., heup_01(ji,jj) / ( hmld(ji,jj) + rtrn ))
+                  ENDIF
+                  zmxl_chl(ji,jj,jk) = zval / 24.
+                  zmxl_fac(ji,jj,jk) = 1.5 * zval / ( 12. + zval )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      zprbio(:,:,:) = zprmaxn(:,:,:) * zmxl_fac(:,:,:)
+      zprdia(:,:,:) = zprmaxd(:,:,:) * zmxl_fac(:,:,:)
+      zprpic(:,:,:) = zprmaxp(:,:,:) * zmxl_fac(:,:,:)
+
+
+      ! Maximum light intensity
+      zdaylen(:,:) = MAX(1., zstrn(:,:)) / 24.
+      WHERE( zstrn(:,:) < 1.e0 ) zstrn(:,:) = 24.
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  ! Computation of the P-I slope for nanos and diatoms
+                  ztn         = MAX( 0., tsn(ji,jj,jk,jp_tem) - 15. )
+                  zadap       = xadap * ztn / ( 2.+ ztn )
+                  !
+                  zpislopeadn(ji,jj,jk) = pislopen * trb(ji,jj,jk,jpnch)    &
+                  &                       /( trb(ji,jj,jk,jpphy) * 12. + rtrn)
+                  zpislopeadp(ji,jj,jk) = pislopep * ( 1. + zadap * EXP( -0.25 * epico(ji,jj,jk) ) )   &
+                  &                       * trb(ji,jj,jk,jppch) /( trb(ji,jj,jk,jppic) * 12. + rtrn)
+                  zpislopeadd(ji,jj,jk) = pisloped * trb(ji,jj,jk,jpdch)    &
+                     &                    /( trb(ji,jj,jk,jpdia) * 12. + rtrn)
+                  !
+                  zpislopen = zpislopeadn(ji,jj,jk) / ( zprbio(ji,jj,jk) * rday * xlimphy(ji,jj,jk) + rtrn )
+                  zpislopep = zpislopeadp(ji,jj,jk) / ( zprpic(ji,jj,jk) * rday * xlimpic(ji,jj,jk) + rtrn )
+                  zpisloped = zpislopeadd(ji,jj,jk) / ( zprdia(ji,jj,jk) * rday * xlimdia(ji,jj,jk) + rtrn )
+
+                  ! Computation of production function for Carbon
+                  !  ---------------------------------------------
+                  zprbio(ji,jj,jk) = zprbio(ji,jj,jk) * ( 1.- EXP( -zpislopen * enano(ji,jj,jk) )  )
+                  zprpic(ji,jj,jk) = zprpic(ji,jj,jk) * ( 1.- EXP( -zpislopep * epico(ji,jj,jk) )  )
+                  zprdia(ji,jj,jk) = zprdia(ji,jj,jk) * ( 1.- EXP( -zpisloped * ediat(ji,jj,jk) )  )
+
+                  ! Computation of production function for Chlorophyll
+                  !  -------------------------------------------------
+                  zpislopen = zpislopen * zmxl_fac(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zpisloped = zpisloped * zmxl_fac(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zpislopep = zpislopep * zmxl_fac(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprchln(ji,jj,jk) = zprmaxn(ji,jj,jk) * ( 1.- EXP( -zpislopen * enanom(ji,jj,jk) )  )
+                  zprchlp(ji,jj,jk) = zprmaxp(ji,jj,jk) * ( 1.- EXP( -zpislopep * epicom(ji,jj,jk) )  )
+                  zprchld(ji,jj,jk) = zprmaxd(ji,jj,jk) * ( 1.- EXP( -zpisloped * ediatm(ji,jj,jk) )  )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+
+                IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !    Si/C of diatoms
+                  !    ------------------------
+                  !    Si/C increases with iron stress and silicate availability
+                  !    Si/C is arbitrariliy increased for very high Si concentrations
+                  !    to mimic the very high ratios observed in the Southern Ocean (silpot2)
+                  zlim  = trb(ji,jj,jk,jpsil) / ( trb(ji,jj,jk,jpsil) + xksi1 )
+                  zsilim = MIN( zprdia(ji,jj,jk) / ( zprmaxd(ji,jj,jk) + rtrn ), xlimsi(ji,jj,jk) )
+                  zsilfac = 3.4 * EXP( -4.23 * zsilim ) * MAX( 0.e0, MIN( 1., 2.2 * ( zlim - 0.5 ) )  ) + 1.e0
+                  zsiborn = trb(ji,jj,jk,jpsil) * trb(ji,jj,jk,jpsil) * trb(ji,jj,jk,jpsil)
+                  IF (gphit(ji,jj) < -30 ) THEN
+                    zsilfac2 = 1. + 2. * zsiborn / ( zsiborn + xksi2**3 )
+                  ELSE
+                    zsilfac2 = 1. +      zsiborn / ( zsiborn + xksi2**3 )
+                  ENDIF
+                  zysopt(ji,jj,jk) = grosip * zlim * zsilfac * zsilfac2
+              ENDIF
+            END DO
+         END DO
+      END DO
+
+      !  Sea-ice effect on production                                                                               
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zprbio(ji,jj,jk)  = zprbio(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
+               zprpic(ji,jj,jk)  = zprpic(ji,jj,jk) * ( 1. - fr_i(ji,jj) ) 
+               zprdia(ji,jj,jk)  = zprdia(ji,jj,jk) * ( 1. - fr_i(ji,jj) ) 
+               zprnut(ji,jj,jk)  = zprnut(ji,jj,jk) * ( 1. - fr_i(ji,jj) )
+            END DO
+         END DO
+      END DO
+
+      ! Computation of the various production terms of nanophytoplankton 
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for nanophyto.
+                  zprorcan(ji,jj,jk) = zprbio(ji,jj,jk)  * xlimphy(ji,jj,jk) * trb(ji,jj,jk,jpphy) * rfact2
+                  !
+                  zration = trb(ji,jj,jk,jpnph) / ( trb(ji,jj,jk,jpphy) + rtrn )
+                  zratiop = trb(ji,jj,jk,jppph) / ( trb(ji,jj,jk,jpphy) + rtrn )
+                  zratiof = trb(ji,jj,jk,jpnfe) / ( trb(ji,jj,jk,jpphy) + rtrn )
+                  zprnutmax = zprnut(ji,jj,jk) * fvnuptk(ji,jj,jk) / rno3 * trb(ji,jj,jk,jpphy) * rfact2
+                  ! Uptake of nitrogen
+                  zrat = MIN( 1., zration / (xqnnmax(ji,jj,jk) + rtrn) ) 
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zpronmax = zprnutmax * zmax * MAX(0., MIN(1., ( zratiop - xqpnmin(ji,jj,jk) )   &
+                  &          / ( xqpnmax(ji,jj,jk) - xqpnmin(ji,jj,jk) + rtrn ), xlimnfe(ji,jj,jk) ) )
+                  zpronewn(ji,jj,jk) = zpronmax * zdaylen(ji,jj) * xnanono3(ji,jj,jk)
+                  zproregn(ji,jj,jk) = zpronmax * xnanonh4(ji,jj,jk)
+                  ! Uptake of phosphorus
+                  zrat = MIN( 1., zratiop / (xqpnmax(ji,jj,jk) + rtrn) )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zpropmax = zprnutmax * zmax * xlimnfe(ji,jj,jk)
+                  zpropo4n(ji,jj,jk) = zpropmax * xnanopo4(ji,jj,jk)
+                  zprodopn(ji,jj,jk) = zpropmax * xnanodop(ji,jj,jk)
+                  ! Uptake of iron
+                  zrat = MIN( 1., zratiof / qfnmax )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zprofmax = zprnutmax * qfnmax * zmax
+                  zprofen(ji,jj,jk) = zprofmax * xnanofer(ji,jj,jk) * ( 3. - 2.4 * xlimnfe(ji,jj,jk)    &
+                  &          / ( xlimnfe(ji,jj,jk) + 0.2 ) ) * (1. + 0.8 * xnanono3(ji,jj,jk) / ( rtrn  &
+                  &          + xnanono3(ji,jj,jk) + xnanonh4(ji,jj,jk) ) * (1. - xnanofer(ji,jj,jk) ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      ! Computation of the various production terms of picophytoplankton 
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for picophyto.
+                  zprorcap(ji,jj,jk) = zprpic(ji,jj,jk)  * xlimpic(ji,jj,jk) * trb(ji,jj,jk,jppic) * rfact2
+                  !
+                  zration = trb(ji,jj,jk,jpnpi) / ( trb(ji,jj,jk,jppic) + rtrn )
+                  zratiop = trb(ji,jj,jk,jpppi) / ( trb(ji,jj,jk,jppic) + rtrn )
+                  zratiof = trb(ji,jj,jk,jppfe) / ( trb(ji,jj,jk,jppic) + rtrn )
+                  zprnutmax = zprnut(ji,jj,jk) * fvpuptk(ji,jj,jk) / rno3 * trb(ji,jj,jk,jppic) * rfact2
+                  ! Uptake of nitrogen
+                  zrat = MIN( 1., zration / (xqnpmax(ji,jj,jk) + rtrn) )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zpronmax = zprnutmax * zmax * MAX(0., MIN(1., ( zratiop - xqppmin(ji,jj,jk) )   &
+                  &          / ( xqppmax(ji,jj,jk) - xqppmin(ji,jj,jk) + rtrn ), xlimpfe(ji,jj,jk) ) )
+                  zpronewp(ji,jj,jk) = zpronmax * zdaylen(ji,jj) * xpicono3(ji,jj,jk) 
+                  zproregp(ji,jj,jk) = zpronmax * xpiconh4(ji,jj,jk)
+                  ! Uptake of phosphorus
+                  zrat = MIN( 1., zratiop / (xqppmax(ji,jj,jk) + rtrn) )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zpropmax = zprnutmax * zmax * xlimpfe(ji,jj,jk)
+                  zpropo4p(ji,jj,jk) = zpropmax * xpicopo4(ji,jj,jk)
+                  zprodopp(ji,jj,jk) = zpropmax * xpicodop(ji,jj,jk)
+                  ! Uptake of iron
+                  zrat = MIN( 1., zratiof / qfpmax )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zprofmax = zprnutmax * qfpmax * zmax
+                  zprofep(ji,jj,jk) = zprofmax * xpicofer(ji,jj,jk) * ( 3. - 2.4 * xlimpfe(ji,jj,jk)   &
+                  &          / ( xlimpfe(ji,jj,jk) + 0.2 ) ) * (1. + 0.8 * xpicono3(ji,jj,jk) / ( rtrn   &
+                  &          + xpicono3(ji,jj,jk) + xpiconh4(ji,jj,jk) ) * (1. - xpicofer(ji,jj,jk) ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      ! Computation of the various production terms of diatoms
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                  !  production terms for diatomees
+                  zprorcad(ji,jj,jk) = zprdia(ji,jj,jk) * xlimdia(ji,jj,jk) * trb(ji,jj,jk,jpdia) * rfact2
+                  ! Computation of the respiration term according to pahlow 
+                  ! & oschlies (2013)
+                  !
+                  zration = trb(ji,jj,jk,jpndi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+                  zratiop = trb(ji,jj,jk,jppdi) / ( trb(ji,jj,jk,jpdia) + rtrn )
+                  zratiof = trb(ji,jj,jk,jpdfe) / ( trb(ji,jj,jk,jpdia) + rtrn )
+                  zprnutmax = zprnut(ji,jj,jk) * fvduptk(ji,jj,jk) / rno3 * trb(ji,jj,jk,jpdia) * rfact2
+                  ! Uptake of nitrogen
+                  zrat = MIN( 1., zration / (xqndmax(ji,jj,jk) + rtrn) )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05)) 
+                  zpronmax = zprnutmax * zmax * MAX(0., MIN(1., ( zratiop - xqpdmin(ji,jj,jk) )   &
+                  &          / ( xqpdmax(ji,jj,jk) - xqpdmin(ji,jj,jk) + rtrn ), xlimdfe(ji,jj,jk) ) )
+                  zpronewd(ji,jj,jk) = zpronmax * zdaylen(ji,jj) * xdiatno3(ji,jj,jk)
+                  zproregd(ji,jj,jk) = zpronmax * xdiatnh4(ji,jj,jk)
+                  ! Uptake of phosphorus
+                  zrat = MIN( 1., zratiop / (xqpdmax(ji,jj,jk) + rtrn) )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05)) 
+                  zpropmax = zprnutmax * zmax * xlimdfe(ji,jj,jk)
+                  zpropo4d(ji,jj,jk) = zpropmax * xdiatpo4(ji,jj,jk)
+                  zprodopd(ji,jj,jk) = zpropmax * xdiatdop(ji,jj,jk)
+                  ! Uptake of iron
+                  zrat = MIN( 1., zratiof / qfdmax )
+                  zmax = MAX(0., MIN(1., (1. - zrat)/ (1.05 - zrat) * 1.05))
+                  zprofmax = zprnutmax * qfdmax * zmax
+                  zprofed(ji,jj,jk) = zprofmax * xdiatfer(ji,jj,jk) * ( 3. - 2.4 * xlimdfe(ji,jj,jk)     &
+                  &          / ( xlimdfe(ji,jj,jk) + 0.2 ) ) * (1. + 0.8 * xdiatno3(ji,jj,jk) / ( rtrn   &
+                  &          + xdiatno3(ji,jj,jk) + xdiatnh4(ji,jj,jk) ) * (1. - xdiatfer(ji,jj,jk) ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( etot_ndcy(ji,jj,jk) > 1.E-3 ) THEN
+                     !  production terms for nanophyto. ( chlorophyll )
+                  znanotot = enanom(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprod = rday * (zpronewn(ji,jj,jk) + zproregn(ji,jj,jk)) * zprchln(ji,jj,jk) * xlimphy(ji,jj,jk)
+                  thetannm_n   = MIN ( thetannm, ( thetannm / (1. - 1.14 / 43.4 *tsn(ji,jj,jk,jp_tem)))   &
+                  &               * (1. - 1.14 / 43.4 * 20.))
+                  zprochln = thetannm_n * zprod / ( zpislopeadn(ji,jj,jk) * znanotot + rtrn )
+                  zprochln = MAX(zprochln, chlcmin * 12. * zprorcan (ji,jj,jk) )
+                     !  production terms for picophyto. ( chlorophyll )
+                  zpicotot = epicom(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprod = rday * (zpronewp(ji,jj,jk) + zproregp(ji,jj,jk)) * zprchlp(ji,jj,jk) * xlimpic(ji,jj,jk)
+                  thetanpm_n   = MIN ( thetanpm, ( thetanpm / (1. - 1.14 / 43.4 *tsn(ji,jj,jk,jp_tem)))   &
+                  &               * (1. - 1.14 / 43.4 * 20.))
+                  zprochlp = thetanpm_n * zprod / ( zpislopeadp(ji,jj,jk) * zpicotot + rtrn )
+                  zprochlp = MAX(zprochlp, chlcmin * 12. * zprorcap(ji,jj,jk) )
+                  !  production terms for diatomees ( chlorophyll )
+                  zdiattot = ediatm(ji,jj,jk) / ( zmxl_chl(ji,jj,jk) + rtrn )
+                  zprod = rday * (zpronewd(ji,jj,jk) + zproregd(ji,jj,jk)) * zprchld(ji,jj,jk) * xlimdia(ji,jj,jk)
+                  thetandm_n   = MIN ( thetandm, ( thetandm / (1. - 1.14 / 43.4 *tsn(ji,jj,jk,jp_tem)))   &
+                  &               * (1. - 1.14 / 43.4 * 20.))
+                  zprochld = thetandm_n * zprod / ( zpislopeadd(ji,jj,jk) * zdiattot + rtrn )
+                  zprochld = MAX(zprochld, chlcmin * 12. * zprorcad(ji,jj,jk) )
+                  !   Update the arrays TRA which contain the Chla sources and sinks
+                  tra(ji,jj,jk,jpnch) = tra(ji,jj,jk,jpnch) + zprochln * texcretn
+                  tra(ji,jj,jk,jpdch) = tra(ji,jj,jk,jpdch) + zprochld * texcretd
+                  tra(ji,jj,jk,jppch) = tra(ji,jj,jk,jppch) + zprochlp * texcretp
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      !   Update the arrays TRA which contain the biological sources and sinks
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+           DO ji =1 ,jpi
+              zprontot = zpronewn(ji,jj,jk) + zproregn(ji,jj,jk)
+              zproptot = zpronewp(ji,jj,jk) + zproregp(ji,jj,jk)
+              zprodtot = zpronewd(ji,jj,jk) + zproregd(ji,jj,jk)
+              zdocprod = excretd * zprorcad(ji,jj,jk) + excretn * zprorcan(ji,jj,jk)  &
+              &          + excretp * zprorcap(ji,jj,jk)
+              tra(ji,jj,jk,jppo4) = tra(ji,jj,jk,jppo4) - zpropo4n(ji,jj,jk) - zpropo4d(ji,jj,jk)  &
+              &                     - zpropo4p(ji,jj,jk)
+              tra(ji,jj,jk,jpno3) = tra(ji,jj,jk,jpno3) - zpronewn(ji,jj,jk) - zpronewd(ji,jj,jk)  &
+              &                     - zpronewp(ji,jj,jk)
+              tra(ji,jj,jk,jpnh4) = tra(ji,jj,jk,jpnh4) - zproregn(ji,jj,jk) - zproregd(ji,jj,jk)  &
+              &                     - zproregp(ji,jj,jk)
+              tra(ji,jj,jk,jpphy) = tra(ji,jj,jk,jpphy) + zprorcan(ji,jj,jk) * texcretn    &
+                 &                  - zpsino3 * zpronewn(ji,jj,jk) - zpsinh4 * zproregn(ji,jj,jk)   &
+                 &                  - zrespn(ji,jj,jk) 
+              zcroissn(ji,jj,jk) = tra(ji,jj,jk,jpphy) / rfact2/ (trb(ji,jj,jk,jpphy) + rtrn)
+              tra(ji,jj,jk,jpnph) = tra(ji,jj,jk,jpnph) + zprontot * texcretn
+              tra(ji,jj,jk,jppph) = tra(ji,jj,jk,jppph) + zpropo4n(ji,jj,jk) * texcretn   &
+              &                     + zprodopn(ji,jj,jk) * texcretn
+              tra(ji,jj,jk,jpnfe) = tra(ji,jj,jk,jpnfe) + zprofen(ji,jj,jk) * texcretn
+              tra(ji,jj,jk,jppic) = tra(ji,jj,jk,jppic) + zprorcap(ji,jj,jk) * texcretp     &
+                 &                  - zpsino3 * zpronewp(ji,jj,jk) - zpsinh4 * zproregp(ji,jj,jk)   &
+                 &                  - zrespp(ji,jj,jk) 
+              zcroissp(ji,jj,jk) = tra(ji,jj,jk,jppic) / rfact2/ (trb(ji,jj,jk,jppic) + rtrn)
+              tra(ji,jj,jk,jpnpi) = tra(ji,jj,jk,jpnpi) + zproptot * texcretp
+              tra(ji,jj,jk,jpppi) = tra(ji,jj,jk,jpppi) + zpropo4p(ji,jj,jk) * texcretp   &
+              &                     + zprodopp(ji,jj,jk) * texcretp
+              tra(ji,jj,jk,jppfe) = tra(ji,jj,jk,jppfe) + zprofep(ji,jj,jk) * texcretp
+              tra(ji,jj,jk,jpdia) = tra(ji,jj,jk,jpdia) + zprorcad(ji,jj,jk) * texcretd   &
+                 &                  - zpsino3 * zpronewd(ji,jj,jk) - zpsinh4 * zproregd(ji,jj,jk)   &
+                 &                  - zrespd(ji,jj,jk) 
+              zcroissd(ji,jj,jk) = tra(ji,jj,jk,jpdia) / rfact2 / (trb(ji,jj,jk,jpdia) + rtrn)
+              tra(ji,jj,jk,jpndi) = tra(ji,jj,jk,jpndi) + zprodtot * texcretd
+              tra(ji,jj,jk,jppdi) = tra(ji,jj,jk,jppdi) + zpropo4d(ji,jj,jk) * texcretd   &
+              &                     + zprodopd(ji,jj,jk) * texcretd
+              tra(ji,jj,jk,jpdfe) = tra(ji,jj,jk,jpdfe) + zprofed(ji,jj,jk) * texcretd
+              tra(ji,jj,jk,jpdsi) = tra(ji,jj,jk,jpdsi) + zprorcad(ji,jj,jk) * zysopt(ji,jj,jk) * texcretd
+              tra(ji,jj,jk,jpdoc) = tra(ji,jj,jk,jpdoc) + excretd * zprorcad(ji,jj,jk) + excretn * zprorcan(ji,jj,jk)  &
+              &                     + excretp * zprorcap(ji,jj,jk)
+              tra(ji,jj,jk,jpdon) = tra(ji,jj,jk,jpdon) + excretd * zprodtot + excretn * zprontot   &
+              &                     + excretp * zproptot
+              tra(ji,jj,jk,jpdop) = tra(ji,jj,jk,jpdop) + excretd * zpropo4d(ji,jj,jk) + excretn * zpropo4n(ji,jj,jk)   &
+              &    - texcretn * zprodopn(ji,jj,jk) - texcretd * zprodopd(ji,jj,jk) + excretp * zpropo4p(ji,jj,jk)     &
+              &    - texcretp * zprodopp(ji,jj,jk)
+              tra(ji,jj,jk,jpoxy) = tra(ji,jj,jk,jpoxy) + o2ut * ( zproregn(ji,jj,jk) + zproregd(ji,jj,jk)   &
+                 &                + zproregp(ji,jj,jk) ) + ( o2ut + o2nit ) * ( zpronewn(ji,jj,jk)           &
+                 &                + zpronewd(ji,jj,jk) + zpronewp(ji,jj,jk) )   &
+                 &                - o2ut * ( zrespn(ji,jj,jk) + zrespp(ji,jj,jk) + zrespd(ji,jj,jk) )
+              zfeup = texcretn * zprofen(ji,jj,jk) + texcretd * zprofed(ji,jj,jk) + texcretp * zprofep(ji,jj,jk)
+              tra(ji,jj,jk,jpfer) = tra(ji,jj,jk,jpfer) - zfeup
+              tra(ji,jj,jk,jpsil) = tra(ji,jj,jk,jpsil) - texcretd * zprorcad(ji,jj,jk) * zysopt(ji,jj,jk)
+              tra(ji,jj,jk,jpdic) = tra(ji,jj,jk,jpdic) - zprorcan(ji,jj,jk) - zprorcad(ji,jj,jk) - zprorcap(ji,jj,jk)  &
+              &                     + zpsino3 * zpronewn(ji,jj,jk) + zpsinh4 * zproregn(ji,jj,jk)   &
+              &                     + zpsino3 * zpronewp(ji,jj,jk) + zpsinh4 * zproregp(ji,jj,jk)   &
+              &                     + zpsino3 * zpronewd(ji,jj,jk) + zpsinh4 * zproregd(ji,jj,jk)  &
+              &                     + zrespn(ji,jj,jk) + zrespd(ji,jj,jk) + zrespp(ji,jj,jk) 
+              tra(ji,jj,jk,jptal) = tra(ji,jj,jk,jptal) + rno3 * ( zpronewn(ji,jj,jk) + zpronewd(ji,jj,jk)  &
+              &                     + zpronewp(ji,jj,jk) ) - rno3 * ( zproregn(ji,jj,jk) + zproregd(ji,jj,jk)     &
+              &                     + zproregp(ji,jj,jk) ) 
+          END DO
+        END DO
+     END DO
+     !
+     IF( ln_ligand ) THEN
+         zpligprod1(:,:,:) = 0._wp    ;    zpligprod2(:,:,:) = 0._wp        
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+              DO ji =1 ,jpi
+                 zdocprod = excretd * zprorcad(ji,jj,jk) + excretn * zprorcan(ji,jj,jk) + excretp * zprorcap(ji,jj,jk)
+                 zfeup    = texcretn * zprofen(ji,jj,jk) + texcretd * zprofed(ji,jj,jk) + texcretp * zprofep(ji,jj,jk)
+                 tra(ji,jj,jk,jplgw) = tra(ji,jj,jk,jplgw) + zdocprod * ldocp - zfeup * plig(ji,jj,jk) * lthet
+                 zpligprod1(ji,jj,jk) = zdocprod * ldocp
+                 zpligprod2(ji,jj,jk) = zfeup * plig(ji,jj,jk) * lthet
+              END DO
+           END DO
+        END DO
+     ENDIF
+
+
+     ! Total primary production per year
+
+    ! Total primary production per year
+    IF( iom_use( "tintpp" ) .OR. ( ln_check_mass .AND. kt == nitend .AND. knt == nrdttrc )  )  &
+      & tpp = glob_sum( 'p5zprod', ( zprorcan(:,:,:) + zprorcad(:,:,:) + zprorcap(:,:,:) ) * cvol(:,:,:) )
+
+    IF( lk_iomput .AND.  knt == nrdttrc ) THEN
+       zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+       !
+       CALL iom_put( "PPPHYP"  , zprorcap(:,:,:) * zfact * tmask(:,:,:)   ) ! primary production by picophyto
+       CALL iom_put( "PPPHYN"  , zprorcan(:,:,:) * zfact * tmask(:,:,:) )  ! primary production by nanophyto
+       CALL iom_put( "PPPHYD"  , zprorcad(:,:,:) * zfact * tmask(:,:,:)   ) ! primary production by diatomes
+       CALL iom_put( "PPNEWN"  , zpronewp(:,:,:) * zfact * tmask(:,:,:)    ) ! new primary production by picophyto
+       CALL iom_put( "PPNEWN"  , zpronewn(:,:,:) * zfact * tmask(:,:,:)    ) ! new primary production by nanophyto
+       CALL iom_put( "PPNEWD"  , zpronewd(:,:,:) * zfact * tmask(:,:,:)   ) ! new primary production by diatomes
+       CALL iom_put( "PBSi"    , zprorcad(:,:,:) * zfact * tmask(:,:,:) * zysopt(:,:,:)  ) ! biogenic silica production
+       CALL iom_put( "PFeP"    , zprofep(:,:,:) * zfact * tmask(:,:,:)  ) ! biogenic iron production by picophyto
+       CALL iom_put( "PFeN"    , zprofen(:,:,:) * zfact * tmask(:,:,:)  ) ! biogenic iron production by nanophyto
+       CALL iom_put( "PFeD"    , zprofed(:,:,:) * zfact * tmask(:,:,:)  ) ! biogenic iron production by  diatomes
+       IF( ln_ligand ) THEN
+         CALL iom_put( "LPRODP"  , zpligprod1(:,:,:) * 1e9 * zfact * tmask(:,:,:) )
+         CALL iom_put( "LDETP"   , zpligprod2(:,:,:) * 1e9 * zfact * tmask(:,:,:) )
+       ENDIF
+       CALL iom_put( "Mumax"   , zprmaxn(:,:,:) * tmask(:,:,:)  ) ! Maximum growth rate
+       CALL iom_put( "MuP"     , zprpic(:,:,:) * xlimpic(:,:,:) * tmask(:,:,:) ) ! Realized growth rate for picophyto
+       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( "LPlight" , zprpic(:,:,:) / (zprmaxp(:,:,:) + rtrn) * tmask(:,:,:)  )  ! light limitation term
+       CALL iom_put( "LNlight" , zprbio(:,:,:) / (zprmaxn(:,:,:) + rtrn) * tmask(:,:,:)  )  ! light limitation term
+       CALL iom_put( "LDlight" , zprdia(:,:,:) / (zprmaxd(:,:,:) + rtrn) * tmask(:,:,:)   )
+       CALL iom_put( "MunetP"  , zcroissp(:,:,:) * tmask(:,:,:) ) ! Realized growth rate for picophyto
+       CALL iom_put( "MunetN"  , zcroissn(:,:,:) * tmask(:,:,:) ) ! Realized growth rate for nanophyto
+       CALL iom_put( "MunetD"  , zcroissd(:,:,:) * tmask(:,:,:) ) ! Realized growth rate for diatoms
+       CALL iom_put( "TPP"     , ( zprorcap(:,:,:) + zprorcan(:,:,:) + zprorcad(:,:,:) ) * zfact * tmask(:,:,:)  )  ! total primary production
+       CALL iom_put( "TPNEW"   , ( zpronewp(:,:,:) + zpronewn(:,:,:) + zpronewd(:,:,:) ) * zfact * tmask(:,:,:)  ) ! total new production
+       CALL iom_put( "TPBFE"   , ( zprofep (:,:,:) + zprofen (:,:,:) + zprofed (:,:,:) ) * zfact * tmask(:,:,:)  )  ! total biogenic iron production
+       CALL iom_put( "tintpp"  , tpp * zfact )  !  global total integrated primary production molC/s
+     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
+      !
+      IF( ln_timing )   CALL timing_stop('p5z_prod')
+      !
+   END SUBROUTINE p5z_prod
+
+
+   SUBROUTINE p5z_prod_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE p5z_prod_init  ***
+      !!
+      !! ** Purpose :   Initialization of phytoplankton production parameters
+      !!
+      !! ** Method  :   Read the nampisprod namelist and check the parameters
+      !!      called at the first timestep (nittrc000)
+      !!
+      !! ** input   :   Namelist nampisprod
+      !!----------------------------------------------------------------------
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      !!
+      NAMELIST/namp5zprod/ pislopen, pislopep, pisloped, excretn, excretp, excretd,     &
+         &                 thetannm, thetanpm, thetandm, chlcmin, grosip, bresp, xadap
+      !!----------------------------------------------------------------------
+
+      REWIND( numnatp_ref )
+      READ  ( numnatp_ref, namp5zprod, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namp5zprod in reference namelist' )
+
+      REWIND( numnatp_cfg )
+      READ  ( numnatp_cfg, namp5zprod, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'namp5zprod in configuration namelist' )
+      IF(lwm) WRITE ( numonp, namp5zprod )
+
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*) ' '
+         WRITE(numout,*) ' Namelist parameters for phytoplankton growth, namp5zprod'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numout,*) '    mean Si/C ratio                           grosip       =', grosip
+         WRITE(numout,*) '    P-I slope                                 pislopen     =', pislopen
+         WRITE(numout,*) '    P-I slope  for diatoms                    pisloped     =', pisloped
+         WRITE(numout,*) '    P-I slope  for picophytoplankton          pislopep     =', pislopep
+         WRITE(numout,*) '    Acclimation factor to low light           xadap        =', xadap
+         WRITE(numout,*) '    excretion ratio of nanophytoplankton      excretn      =', excretn
+         WRITE(numout,*) '    excretion ratio of picophytoplankton      excretp      =', excretp
+         WRITE(numout,*) '    excretion ratio of diatoms                excretd      =', excretd
+         WRITE(numout,*) '    basal respiration in phytoplankton        bresp        =', bresp
+         WRITE(numout,*) '    Maximum Chl/C in phytoplankton            chlcmin      =', chlcmin
+         WRITE(numout,*) '    Minimum Chl/N in nanophytoplankton        thetannm     =', thetannm
+         WRITE(numout,*) '    Minimum Chl/N in picophytoplankton        thetanpm     =', thetanpm
+         WRITE(numout,*) '    Minimum Chl/N in diatoms                  thetandm     =', thetandm
+      ENDIF
+      !
+      r1_rday   = 1._wp / rday 
+      texcretn  = 1._wp - excretn
+      texcretp  = 1._wp - excretp
+      texcretd  = 1._wp - excretd
+      tpp       = 0._wp
+      !
+   END SUBROUTINE p5z_prod_init
+
+
+   INTEGER FUNCTION p5z_prod_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p5z_prod_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( zdaylen(jpi,jpj), STAT = p5z_prod_alloc )
+      !
+      IF( p5z_prod_alloc /= 0 ) CALL ctl_stop( 'STOP', 'p5z_prod_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION p5z_prod_alloc
+   !!======================================================================
+END MODULE p5zprod
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/oce_sed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/oce_sed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/oce_sed.F90	(revision 14097)
@@ -0,0 +1,56 @@
+MODULE oce_sed
+   !!======================================================================
+   !!                        ***  sed  ***
+   !! Sediment :   set sediment global variables
+   !!======================================================================
+   !! History :
+   !!        !  06-12  (C. Ethe)  Orignal
+   !!----------------------------------------------------------------------
+   USE par_sed
+   USE timing
+   USE par_trc
+
+   USE dom_oce , ONLY :   glamt     =>   glamt          !: longitude of t-point (degre)
+   USE dom_oce , ONLY :   gphit     =>   gphit          !: latitude  of t-point (degre)
+   USE dom_oce , ONLY :   e3t_n     =>   e3t_n          !: latitude  of t-point (degre)
+   USE dom_oce , ONLY :   e3t_1d    =>   e3t_1d         !: reference depth of t-points (m)
+   USE dom_oce , ONLY :   gdepw_0   =>   gdepw_0        !: reference depth of t-points (m)
+   USE dom_oce , ONLY :   mbkt      =>   mbkt           !: vertical index of the bottom last T- ocean level
+   USE dom_oce , ONLY :   tmask     =>   tmask          !: land/ocean mask at t-points
+   USE dom_oce , ONLY :   rdt       =>   rdt            !: time step for the dynamics
+   USE dom_oce , ONLY :   nyear     =>   nyear          !: Current year
+   USE dom_oce , ONLY :   ndastp    =>   ndastp         !: time step date in year/month/day aammjj
+   USE dom_oce , ONLY :   adatrj    =>   adatrj         !: number of elapsed days since the begining of the run
+   USE trc     , ONLY :  nittrc000  =>   nittrc000
+   !                                !: it is the accumulated duration of previous runs
+   !                                !: that may have been run with different time steps.
+
+   USE oce     , ONLY :  tsn        =>   tsn             !: pot. temperature (celsius) and salinity (psu)
+   USE trc     , ONLY :  trb        =>   trb             !: pot. temperature (celsius) and salinity (psu)
+
+   USE sms_pisces, ONLY : wsbio4    =>   wsbio4          !: sinking flux for POC
+   USE sms_pisces, ONLY : wsbio3    =>   wsbio3          !: sinking flux for GOC
+   USE sms_pisces, ONLY : wsbio2    =>   wsbio2           !: sinking flux for calcite
+   USE sms_pisces, ONLY : wsbio     =>   wsbio           !: sinking flux for calcite
+   USE sms_pisces, ONLY : ln_p5z    =>   ln_p5z          !: PISCES-QUOTA flag
+   USE p4zche, ONLY     : akb3      =>   akb3            !: Chemical constants  
+   USE sms_pisces, ONLY : ak13      =>   ak13            !: Chemical constants  
+   USE sms_pisces, ONLY : ak23      =>   ak23            !: Chemical constants  
+   USE p4zche, ONLY     : akw3      =>   akw3            !: Chemical constants  
+   USE sms_pisces, ONLY : aksp      =>   aksp            !: Chemical constants  
+   USE p4zche, ONLY     : borat     =>   borat           !: Chemical constants ( borat ) 
+   USE p4zche, ONLY     : ak1p3     =>   ak1p3           !: Chemical constants  
+   USE p4zche, ONLY     : ak2p3     =>   ak2p3           !: Chemical constants  
+   USE p4zche, ONLY     : ak3p3     =>   ak3p3           !: Chemical constants  
+   USE p4zche, ONLY     : aksi3     =>   aksi3           !: Chemical constants  
+   USE p4zche, ONLY     : aks3      =>   aks3            !: Chemical constants  
+   USE p4zche, ONLY     : akf3      =>   akf3            !: Chemical constants  
+   USE p4zche, ONLY     : fluorid   =>   fluorid         !: Chemical constants  
+   USE p4zche, ONLY     : sulfat    =>   sulfat          !: Chemical constants  
+   USE p4zche, ONLY     : sio3eq    =>   sio3eq          !: Chemical constants  
+   USE p4zsbc, ONLY     : dust      =>   dust
+   USE trc       , ONLY : r2dttrc   =>   r2dttrc
+
+END MODULE oce_sed
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/par_sed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/par_sed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/par_sed.F90	(revision 14097)
@@ -0,0 +1,66 @@
+MODULE par_sed
+   !!======================================================================
+   !!                        ***  par_sed  ***
+   !! Sediment :   set sediment parameter
+   !!======================================================================
+   !! History :
+   !!        !  06-12  (C. Ethe)  Orignal
+   !!----------------------------------------------------------------------
+   !! $Id$
+
+   !! Domain characteristics
+   USE par_kind
+   USE par_oce , ONLY :       &
+      jpi      =>   jpi   ,  & !: first  dimension of grid --> i
+      jpj      =>   jpj   ,  & !: second dimension of grid --> j
+      jpim1    =>   jpim1 ,  & !: jpi - 1
+      jpjm1    =>   jpjm1 ,  & !: jpj - 1
+      jpij     =>   jpij  ,  & !: jpi x jpj
+      jp_tem   =>   jp_tem,  & !: indice of temperature
+      jp_sal   =>   jp_sal     !: indice of salintity
+
+   INTEGER, PARAMETER :: jpdta = 17
+
+   ! Vertical sediment geometry
+   INTEGER, PUBLIC   ::      &
+      jpksed   = 11 ,        &
+      jpksedm1 = 10
+
+   ! sediment tracer species
+   INTEGER, PARAMETER ::    &
+      jpsol =  8,           &  !: number of solid component
+      jpwat = 10,           &   !: number of pore water component
+      jpwatp1 = jpwat +1,   &
+      jpsol1 = jpsol - 1
+
+   
+   ! pore water components       
+   INTEGER, PARAMETER :: &
+      jwsil  = 1,        & !: silic acid
+      jwoxy  = 2,        & !: oxygen
+      jwdic  = 3,        & !: dissolved inorganic carbon
+      jwno3  = 4,        & !: nitrate
+      jwpo4  = 5,        & !: phosphate
+      jwalk  = 6,        & !: alkalinity
+      jwnh4  = 7,        & !: Ammonium
+      jwh2s  = 8,        & !: Sulfate
+      jwso4  = 9,        & !: H2S
+      jwfe2  = 10          !: Fe2+
+
+   ! solid components       
+   INTEGER, PARAMETER ::  &
+      jsopal  = 1,        & !: opal sediment
+      jsclay  = 2,        & !: clay
+      jspoc   = 3,        & !: organic carbon
+      jscal   = 4,        & !: calcite
+      jspos   = 5,        & !: semi-ref POC
+      jspor   = 6,        & !: refractory POC
+      jsfeo   = 7,        & !: iron hydroxides
+      jsfes   = 8           !: FeS
+
+   INTEGER, PARAMETER ::  &
+      jptrased   = jpsol + jpwat , &
+      jpdia3dsed = 2             , &
+      jpdia2dsed = 12
+
+END MODULE par_sed
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed.F90	(revision 14097)
@@ -0,0 +1,172 @@
+MODULE sed
+   !!======================================================================
+   !!                        ***  sed  ***
+   !! Sediment :   set sediment global variables
+   !!======================================================================
+   !! History :
+   !!        !  06-12  (C. Ethe)  Orignal
+   !!----------------------------------------------------------------------
+   USE par_sed
+   USE oce_sed
+   USE in_out_manager
+
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC sed_alloc
+
+   !! Namelist
+   REAL(wp), PUBLIC               ::  reac_sil            !: reactivity of silicate in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_clay           !: reactivity of clay in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_ligc           !: reactivity of Ligands [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_pocl           !: reactivity of pocl in  [s-1]
+   REAL(wp), PUBLIC               ::  reac_pocs           !: reactivity of pocs in  [s-1]
+   REAL(wp), PUBLIC               ::  reac_pocr           !: reactivity of pocr in  [s-1]
+   REAL(wp), PUBLIC               ::  reac_nh4            !: reactivity of NH4 in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_h2s            !: reactivity of ODU in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_fe2            !: reactivity of Fe2+ in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_feh2s          !: reactivity of Fe2+ in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_fes            !: reactivity of Fe with H2S in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_feso           !: reactivity of FeS with O2 in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  reac_cal            !: reactivity of cal in  [l.mol-1.s-1]
+   REAL(wp), PUBLIC               ::  adsnh4              !: adsorption coefficient of NH4
+   REAL(wp), PUBLIC               ::  ratligc             !: C/L ratio in POC
+   REAL(wp), PUBLIC               ::  so2ut 
+   REAL(wp), PUBLIC               ::  srno3 
+   REAL(wp), PUBLIC               ::  spo4r 
+   REAL(wp), PUBLIC               ::  srDnit 
+   REAL(wp), PUBLIC               ::  dtsed               !: sedimentation time step
+   REAL(wp), PUBLIC               ::  dtsed2              !: sedimentation time step
+   INTEGER , PUBLIC               ::  nitsed000
+   INTEGER , PUBLIC               ::  nitsedend
+   INTEGER, PUBLIC                ::  nrseddt
+   REAL    , PUBLIC               ::  sedmask
+   REAL(wp), PUBLIC               ::  denssol                !: density of solid material
+   INTEGER , PUBLIC               ::  numrsr, numrsw   !: logical unit for sed restart (read and write)
+   LOGICAL , PUBLIC               ::  lrst_sed       !: logical to control the trc restart write
+   LOGICAL , PUBLIC               ::  ln_rst_sed  = .TRUE.     !: initialisation from a restart file or not
+   LOGICAL , PUBLIC               ::  ln_btbz     = .FALSE.    !: Depth variation of the bioturbation coefficient
+   LOGICAL , PUBLIC               ::  ln_irrig    = .FALSE.    !: iActivation of the bioirrigation
+   LOGICAL , PUBLIC               ::  ln_sed_2way = .FALSE.    !: 2 way coupling with PISCES
+   LOGICAL , PUBLIC               ::  ln_sediment_offline = .FALSE. !: Offline mode for sediment module
+   INTEGER             , PUBLIC   ::  nn_rstsed      !: control of the time step ( 0 or 1 ) for pass. tr.
+   INTEGER , PUBLIC               ::  nn_dtsed = 1   !: frequency of step on passive tracers
+   CHARACTER(len = 80) , PUBLIC   ::  cn_sedrst_in   !: suffix of pass. tracer restart name (input)
+   CHARACTER(len = 256), PUBLIC   ::  cn_sedrst_indir  !: restart input directory
+   CHARACTER(len = 80) , PUBLIC   ::  cn_sedrst_out  !: suffix of pass. tracer restart name (output)
+   CHARACTER(len = 256), PUBLIC   ::  cn_sedrst_outdir  !: restart output directory
+
+   !
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  pwcp       !: pore water sediment data at given time-step
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  pwcp0      !: pore water sediment data at initial time
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  solcp      !: solid sediment data at given time-step
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  solcp0     !: solid sediment data at initial time
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  trc_dta
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  diff
+
+   !! * Shared module variables
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  pwcp_dta   !: pore water data at given time-step
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  rainrm_dta !: rain data at at initial time
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  rainrm     !: rain data at given time-step
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  rainrg     !: rain of each solid component in [g/(cm**2.s)]
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  fromsed    !:
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  tosed      !:
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  rloss      !: 
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  tokbot        
+   !
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  temp       !: temperature
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  salt       !: salinity
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  press      !: pressure
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  raintg     !: total massic flux rained in each cell (sum of sol. comp.)
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  fecratio   !: Fe/C ratio in falling particles to the sediments
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  dzdep      !: total thickness of solid material rained [cm] in each cell
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  zkbot      !: total thickness of solid material rained [cm] in each cell
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  wacc       !: total thickness of solid material rained [cm] in each cell
+   !
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  hipor      !: [h+] in mol/kg*densSW 
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  co3por     !: [co3--]solid sediment at initial time
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  dz3d       !:  ???
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  volw3d     !:  ???
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  vols3d     !:  ???
+
+
+   !! Chemistry
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  densSW 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  borats 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  calcon2
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  akbs  
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak1s 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak2s   
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  akws  
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak12s  
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak1ps 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak2ps  
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak3ps 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak12ps 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  ak123ps
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  aksis 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  aksps 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  sieqs
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  aks3s
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  akf3s
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  sulfats
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  fluorids
+
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  mol_wgt    !: molecular weight of solid sediment data
+ 
+   REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::  trc_data    !: tracer data to share with sediment model
+   !! Geometry
+   INTEGER , PUBLIC, SAVE                          ::  jpoce, indoce !: Ocean points ( number/indices )
+   INTEGER , PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  iarroce       !: Computation of 1D array of sediments points
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  epkbot        !: ocean bottom layer thickness
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  gdepbot       !: Depth of the sediment
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  dzkbot        !: ocean bottom layer thickness in meters
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  dz            !: sediment layers thickness
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  por           !: porosity profile     
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  por1          !: 1-por 
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  volw          !: volume of pore water cell fraction
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  vols          !: volume of solid cell fraction
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  db            !: bioturbation ceofficient
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE ::  irrig        !: bioturbation ceofficient
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  rdtsed        !:  sediment model time-step
+   REAL(wp), PUBLIC, DIMENSION(:,:  ), ALLOCATABLE :: sedligand
+   REAL(wp)  ::   dens               !: density of solid material
+   !! Inputs / Outputs
+   CHARACTER( len = 80 ), DIMENSION(jptrased  ) ::  sedtrcl
+   CHARACTER( len = 20 ), DIMENSION(jptrased  ) ::  sedtrcd , sedtrcu
+   CHARACTER( len = 80 ), DIMENSION(jpdia3dsed) ::  seddia3l 
+   CHARACTER( len = 20 ), DIMENSION(jpdia3dsed) ::  seddia3d, seddia3u
+   CHARACTER( len = 80 ), DIMENSION(jpdia2dsed) ::  seddia2l 
+   CHARACTER( len = 20 ), DIMENSION(jpdia2dsed) ::  seddia2d, seddia2u
+   !
+   REAL(wp), PUBLIC, DIMENSION(:,:,:,:), ALLOCATABLE ::  trcsedi
+   REAL(wp), PUBLIC, DIMENSION(:,:,:,:), ALLOCATABLE ::  flxsedi3d
+   REAL(wp), PUBLIC, DIMENSION(:,:,:  ), ALLOCATABLE ::  flxsedi2d
+
+   INTEGER, PUBLIC ::  numsed = 27    ! units
+
+   !! $Id$
+CONTAINS
+
+   INTEGER FUNCTION sed_alloc()
+      !!-------------------------------------------------------------------
+      !!                    *** ROUTINE sed_alloc ***
+      !!-------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop
+      !!-------------------------------------------------------------------
+      !
+      ALLOCATE( trc_data(jpi,jpj,jpdta)                                   ,   &
+         &      epkbot(jpi,jpj), gdepbot(jpi,jpj)        ,   &
+         &      dz(jpksed)  , por(jpksed) , por1(jpksed)                  ,   &
+         &      volw(jpksed), vols(jpksed), rdtsed(jpksed)  ,   &
+         &      trcsedi  (jpi,jpj,jpksed,jptrased)                        ,   &
+         &      flxsedi3d(jpi,jpj,jpksed,jpdia3dsed)                      ,   &
+         &      flxsedi2d(jpi,jpj,jpdia2dsed)                             ,   &
+         &      mol_wgt(jpsol),                                           STAT=sed_alloc )
+
+      IF( sed_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sed_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION sed_alloc
+
+END MODULE sed
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sed_oce.F90	(revision 14097)
@@ -0,0 +1,36 @@
+MODULE sed_oce
+   !!======================================================================
+   !!                        ***  sed  ***
+   !! Sediment :   set sediment global variables
+   !!======================================================================
+
+   !! History :
+   !!        !  06-12  (C. Ethe)  Orignal
+   !!----------------------------------------------------------------------
+   USE par_sed
+   USE trc, ONLY : profsed
+
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC sed_oce_alloc
+
+   REAL(wp), PUBLIC, DIMENSION(:    ), ALLOCATABLE ::  profsedw       !: depth of middle of each layer
+
+   !! $Id$
+CONTAINS
+
+   INTEGER FUNCTION sed_oce_alloc()
+      !!-------------------------------------------------------------------
+      !!                    *** ROUTINE sed_alloc ***
+      !!-------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop
+      !!-------------------------------------------------------------------
+      !
+      ALLOCATE( profsed(jpksed) , profsedw(jpksed) , STAT=sed_oce_alloc )
+
+      IF( sed_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sed_oce_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION sed_oce_alloc
+
+END MODULE sed_oce
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedadv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedadv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedadv.F90	(revision 14097)
@@ -0,0 +1,442 @@
+MODULE sedadv
+   !!======================================================================
+   !!              ***  MODULE  sedadv  ***
+   !!    Sediment : vertical advection and burial
+   !!=====================================================================
+   !! * Modules used
+   !!----------------------------------------------------------------------
+   !!   sed_adv :
+   !!----------------------------------------------------------------------
+   USE sed     ! sediment global variable
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_adv
+   PUBLIC sed_adv_alloc
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) :: dvolsp, dvolsm
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:) :: c2por, ckpor
+
+   REAL(wp) :: cpor
+   REAL(wp) :: por1clay 
+   REAL(wp) :: eps = 1.e-13
+
+   !! $Id$
+CONTAINS
+
+   SUBROUTINE sed_adv( kt )
+      !!-------------------------------------------------------------------------
+      !!                  ***  ROUTINE sed_adv  ***
+      !!
+      !! ** Purpose : vertical solid sediment advection and burial 
+      !!
+      !! ** Method  : At each grid point the 1-dimensional solid sediment column
+      !!              is shifted according the rain added to the top layer and
+      !!              the gaps produced through redissolution so that in the end
+      !!              the original sediment mixed layer geometry is reestablished.
+      !!
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) F90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!-------------------------------------------------------------------------
+      !!* Arguments
+      INTEGER, INTENT(in) ::  &
+         kt                     ! time step
+      ! * local variables
+      INTEGER :: ji, jk, js 
+      INTEGER :: jn, ntimes, nztime, ikwneg
+      
+      REAL(wp), DIMENSION(jpksed,jpsol) :: zsolcpno
+      REAL(wp), DIMENSION(jpksed)       :: zfilled, zfull, zfromup, zempty
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zgap, zwb
+      REAL(wp), DIMENSION(jpoce,jpsol) :: zrainrf
+      REAL(wp), DIMENSION(:  ), ALLOCATABLE :: zraipush
+
+      REAL(wp) :: zkwnup, zkwnlo, zfrac,  zfromce, zrest, sumtot, zsumtot1
+
+      !------------------------------------------------------------------------
+
+
+      IF( ln_timing )  CALL timing_start('sed_adv')
+!
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) THEN
+            WRITE(numsed,*) ' '
+            WRITE(numsed,*) ' sed_adv : vertical sediment advection  '
+            WRITE(numsed,*) ' '
+         ENDIF
+         por1clay = denssol * por1(jpksed) * dz(jpksed)
+         cpor     = por1(jpksed) / por1(2)
+         DO jk = 2, jpksed
+            c2por(jk) = por1(2)      / por1(jk)
+            ckpor(jk) = por1(jpksed) / por1(jk)
+         ENDDO
+         DO jk = jpksedm1, 2, -1
+            dvolsp(jk) = vols(jk+1) / vols(jk)
+         ENDDO
+         DO jk = 3, jpksed
+           dvolsm(jk) = vols(jk-1) / vols(jk)
+        ENDDO
+      ENDIF
+
+      ! Initialization of data for mass balance calculation
+      !---------------------------------------------------
+      fromsed(:,:) = 0.
+      tosed  (:,:) = 0. 
+      rloss  (:,:) = 0.
+      ikwneg = 1
+      nztime = jpksed
+
+      ALLOCATE( zraipush(nztime) )
+
+      ! Initiate gap 
+      !--------------
+      zgap(:,:) = 0.
+      DO js = 1, jpsol
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce
+               zgap(ji,jk) = zgap(ji,jk) + solcp(ji,jk,js)
+            END DO
+         ENDDO
+      ENDDO
+
+      zgap(1:jpoce,1:jpksed) = 1. - zgap(1:jpoce,1:jpksed)   
+
+      ! Initiate burial rates
+      !-----------------------
+      zwb(:,:) = 0.
+      DO jk = 2, jpksed
+         zfrac =  dtsed / ( denssol * por1(jk) )     
+         DO ji = 1, jpoce
+            zwb(ji,jk) = zfrac * raintg(ji)
+         END DO
+      ENDDO
+
+
+      DO ji = 1, jpoce
+         zwb(ji,2) = zwb(ji,2) - zgap(ji,2) * dz(2)
+      ENDDO
+
+      DO jk = 3, jpksed
+         zfrac = por1(jk-1) / por1(jk)
+         DO ji = 1, jpoce
+            zwb(ji,jk) = zwb(ji,jk-1) * zfrac - zgap(ji,jk) * dz(jk)
+         END DO
+      ENDDO
+
+      zrainrf(:,:) = 0.
+      DO ji = 1, jpoce
+         IF( raintg(ji) /= 0. )  &
+            &   zrainrf(ji,:) = rainrg(ji,:) / raintg(ji)
+      ENDDO
+
+
+      ! Computation of full and empty solid fraction in each layer
+      ! for all 'burial' case
+      !----------------------------------------------------------
+
+
+      DO ji = 1, jpoce
+
+         ! computation of total weight fraction in sediment
+         !-------------------------------------------------
+         zfilled(:) = 0.
+         DO js = 1, jpsol
+            DO jk = 2, jpksed
+               zfilled(jk) = zfilled(jk) + solcp(ji,jk,js)
+            ENDDO
+         ENDDO
+         
+         DO js = 1, jpsol
+            DO jk = 2, jpksed
+               zsolcpno(jk,js) = solcp(ji,jk,js) / zfilled(jk)
+            ENDDO
+         ENDDO
+
+         ! burial  3 cases: 
+         ! zwb > 0 ==> rain > total rection loss 
+         ! zwb = 0 ==> rain = 0
+         ! zwb < 0 ==> rain > 0 and rain < total reaction loss
+         !----------------------------------------------------------------
+
+         IF( zwb(ji,jpksed) > 0. ) THEN
+
+            zfull (jpksed) = zfilled(jpksed)
+            zempty(jpksed) = 1. - zfull(jpksed)
+            DO jk = jpksedm1, 2, -1
+               zfull (jk) = zfilled(jk)
+               zfull (jk) = zfull(jk) - zempty(jk+1) * dvolsp(jk)
+               zempty(jk) = 1. - zfull(jk)
+            ENDDO
+
+            ! Computation of solid sediment species
+            !--------------------------------------
+            ! push entire sediment column downward to account rest of rain
+            DO js = 1, jpsol
+               DO jk = jpksed, 3, -1
+                  solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk-1,js)
+               ENDDO
+
+               solcp(ji,2,js) = zfull(2) * zsolcpno(2,js) + zempty(2) * zrainrf(ji,js)
+
+               DO jk = 2, jpksed
+                  zsolcpno(jk,js) = solcp(ji,jk,js)
+               END DO
+            ENDDO
+
+            zrest = zwb(ji,jpksed) * cpor
+            ! what is remaining is less than dz(2)
+            IF( zrest <= dz(2) ) THEN           
+
+               zfromup(2) = zrest / dz(2)
+               DO jk = 3, jpksed
+                  zfromup(jk) = zwb(ji,jpksed) * ckpor(jk) / dz(jk)
+               ENDDO
+               DO js = 1, jpsol
+                  zfromce = 1. - zfromup(2)
+                  solcp(ji,2,js) = zfromce * zsolcpno(2,js) + zfromup(2) * zrainrf(ji,js)
+                  DO jk = 3, jpksed
+                     zfromce = 1. - zfromup(jk)
+                     solcp(ji,jk,js) = zfromce * zsolcpno(jk,js) + zfromup(jk) * zsolcpno(jk-1,js)
+                  ENDDO
+                  fromsed(ji,js) = 0.
+                  ! quantities to push in deeper sediment
+                  tosed  (ji,js) = zsolcpno(jpksed,js) &
+                     &           * zwb(ji,jpksed) * denssol * por1(jpksed)
+               ENDDO
+
+            ELSE ! what is remaining is great than dz(2)
+
+               ntimes = INT( zrest / dz(2) ) + 1
+               IF( ntimes > nztime ) CALL ctl_stop( 'STOP', 'sed_adv : rest too large ' )
+               zraipush(1) = dz(2)
+               zrest = zrest - zraipush(1)
+               DO jn = 2, ntimes
+                  IF( zrest >= dz(2) ) THEN
+                     zraipush(jn) = dz(2)
+                     zrest = zrest - zraipush(jn)
+                  ELSE
+                     zraipush(jn) = zrest
+                     zrest = 0.
+                  ENDIF
+               ENDDO
+
+               DO jn = 1, ntimes
+                  DO js = 1, jpsol
+                     DO jk = 2, jpksed
+                        zsolcpno(jk,js) = solcp(ji,jk,js)
+                     END DO
+                  ENDDO
+                  
+                  zfromup(2) = zraipush(jn) / dz(2)
+                  DO jk = 3, jpksed
+                     zfromup(jk) = ( zraipush(jn) / dz(jk) ) * c2por(jk)
+                  ENDDO
+
+                  DO js = 1, jpsol
+                     zfromce = 1. - zfromup(2)
+                     solcp(ji,2,js) = zfromce * zsolcpno(2,js) + zfromup(2) * zrainrf(ji,js)
+                     DO jk = 3, jpksed
+                        zfromce = 1. - zfromup(jk)
+                        solcp(ji,jk,js) = zfromce * zsolcpno(jk,js) + zfromup(jk) * zsolcpno(jk-1,js)
+                     ENDDO
+                     fromsed(ji,js) = 0.
+                     tosed  (ji,js) = tosed(ji,js) + zsolcpno(jpksed,js) * zraipush(jn) &
+                        &             * denssol * por1(2) 
+                  ENDDO
+               ENDDO
+ 
+            ENDIF
+
+         ELSE IF( raintg(ji) < eps ) THEN ! rain  = 0
+!! Nadia    rloss(:,:) = rainrm(:,:)   bug ??????           
+
+            rloss(ji,1:jpsol) = rainrm(ji,1:jpsol)
+
+            zfull (2) = zfilled(2)
+            zempty(2) = 1. - zfull(2)
+            DO jk = 3, jpksed
+               zfull (jk) = zfilled(jk)
+               zfull (jk) = zfull (jk) - zempty(jk-1) * dvolsm(jk)
+               zempty(jk) = 1. - zfull(jk)
+            ENDDO
+
+            ! fill boxes with weight fraction from underlying box
+            DO js = 1, jpsol
+               DO jk = 2, jpksedm1
+                  solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk+1,js)
+               END DO
+               solcp(ji,jpksed,js) = zsolcpno(jpksed,js) * zfull(jpksed)
+               tosed  (ji,js) = 0.
+               fromsed(ji,js) = 0.
+            ENDDO
+            ! for the last layer, one make go up clay 
+            solcp(ji,jpksed,jsclay) = solcp(ji,jpksed,jsclay) + zempty(jpksed) * 1.
+            fromsed(ji,jsclay) = zempty(jpksed) * 1. * por1clay
+         ELSE  ! rain > 0 and rain < total reaction loss
+
+
+            DO jk = 2, jpksed
+               zfull (jk) = zfilled(jk)
+               zempty(jk) = 1. - zfull(jk)
+            ENDDO
+
+            ! Determination of indice of layer - ikwneg - where advection is reversed
+            !------------------------------------------------------------------------
+ iflag:     DO jk = 2, jpksed
+               IF( zwb(ji,jk) < 0.  ) THEN
+                  ikwneg = jk
+                  EXIT iflag
+               ENDIF
+            ENDDO iflag
+
+            ! computation of zfull and zempty 
+            ! 3 cases : a/ ikwneg=2, b/ikwneg=3...jpksedm1, c/ikwneg=jpksed    
+            !-------------------------------------------------------------      
+            IF( ikwneg == 2 ) THEN ! advection is reversed in the first sediment layer
+
+               zkwnup = rdtsed(ikwneg) * raintg(ji) / dz(ikwneg)
+               zkwnlo = ABS( zwb(ji,ikwneg) ) / dz(ikwneg)
+               zfull (ikwneg+1) = zfilled(ikwneg+1) - zkwnlo * dvolsm(ikwneg+1)
+               zempty(ikwneg+1) = 1. - zfull(ikwneg+1)
+               DO jk = ikwneg+2, jpksed
+                  zfull (jk) = zfilled(jk) - zempty(jk-1) * dvolsm(jk)
+                  zempty(jk) = 1. - zfull(jk)
+               ENDDO
+               DO js = 1, jpsol
+                  solcp(ji,2,js) = zfull(2) * zsolcpno(2,js)+ zkwnlo * zsolcpno(3,js) &
+                     &                                      + zkwnup * zrainrf(ji,js)
+                  DO jk = 3, jpksedm1
+                     solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk+1,js)
+                  ENDDO
+                  solcp(ji,jpksed,js) = zfull(jpksed) * zsolcpno(jpksed,js)
+                  tosed(ji,js)   = 0.
+                  fromsed(ji,js) = 0.
+               ENDDO
+               solcp(ji,jpksed,jsclay) =  solcp(ji,jpksed,jsclay) + zempty(jpksed) * 1.
+               !! C. Heinze  fromsed(ji,jsclay) = zempty(jpksed) * 1. * denssol * por1(jpksed) / mol_wgt(jsclay)
+               fromsed(ji,jsclay) = zempty(jpksed) * 1. * por1clay
+               
+            ELSE IF( ikwneg == jpksed ) THEN
+
+               zkwnup = ABS( zwb(ji,ikwneg-1) ) * dvolsm(ikwneg) / dz(ikwneg)
+               zkwnlo = ABS( zwb(ji,ikwneg) ) / dz(ikwneg)
+               zfull (ikwneg-1) = zfilled(ikwneg-1) - zkwnup * dvolsp(ikwneg-1)
+               zempty(ikwneg-1) = 1. - zfull(ikwneg-1)
+               DO jk = ikwneg-2, 2, -1
+                  zfull (jk) = zfilled(jk) - zempty(jk+1) * dvolsp(jk)
+                  zempty(jk) = 1. - zfull(jk) 
+               ENDDO
+               DO  js = 1, jpsol
+                  solcp(ji,2,js) = zfull(2) * zsolcpno(2,js) + zempty(2) * zrainrf(ji,js)
+               ENDDO
+               DO  js = 1, jpsol
+                  DO jk = jpksedm1, 3, -1
+                     solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk-1,js)
+                  ENDDO
+                  solcp(ji,jpksed,js) = zfull(jpksed) * zsolcpno(jpksed,js) &
+                     &                       + zkwnup * zsolcpno(jpksedm1,js)
+                  tosed(ji,js)   = 0.
+                  fromsed(ji,js) = 0.
+               ENDDO
+               solcp(ji,jpksed,jsclay) = solcp(ji,jpksed,jsclay) + zkwnlo * 1.
+               ! Heinze  fromsed(ji,jsclay) = zkwnlo * 1. * denssol * por1(jpksed) / mol_wgt(jsclay)
+               fromsed(ji,jsclay) = zkwnlo * 1.* por1clay
+            ELSE   ! 2 < ikwneg(ji) <= jpksedm1
+
+               zkwnup = ABS( zwb(ji,ikwneg-1) ) * por1(ikwneg-1) / ( dz(ikwneg) * por1(ikwneg) )
+               zkwnlo = ABS( zwb(ji,ikwneg) ) / dz(ikwneg)
+
+               IF( ikwneg > 3 ) THEN
+
+                  zfull (ikwneg-1) = zfilled(ikwneg-1) - zkwnup * dvolsp(ikwneg-1)
+                  zempty(ikwneg-1) = 1. - zfull(ikwneg-1) 
+                  DO jk = ikwneg-2, 2, -1
+                     zfull (jk) = zfilled(jk) - zempty(jk+1) * dvolsp(jk)
+                     zempty(jk)    = 1. - zfull(jk) 
+                  ENDDO
+                  DO js = 1, jpsol
+                     solcp(ji,2,js) = zfull(2) * zsolcpno(2,js) + zempty(2) * zrainrf(ji,js)
+                  ENDDO
+                  DO js = 1, jpsol
+                     DO jk = ikwneg-1, 3, -1
+                        solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk-1,js)
+                     ENDDO
+                  ENDDO
+               ELSE ! ikw = 3
+
+
+                  zfull (2) = zfilled(2) - zkwnup * dvolsm(3)
+                  zempty(2) = 1. - zfull(2)
+                  DO js = 1, jpsol
+                     solcp(ji,2,js) = zfull(2) * zsolcpno(2,js) + zempty(2) * zrainrf(ji,js)
+                  ENDDO
+               ENDIF
+
+               IF( ikwneg < jpksedm1) THEN
+
+                  zfull (ikwneg+1) = zfilled(ikwneg+1) - zkwnlo * dvolsm(ikwneg+1)
+                  zempty(ikwneg+1) = 1. - zfull(ikwneg+1) 
+                  DO jk = ikwneg+2, jpksed
+                     zfull (jk) = zfilled(jk) - zempty(jk-1) * dvolsm(jk)
+                     zempty(jk) = 1. - zfull(jk)
+                  ENDDO
+                  DO js = 1, jpsol
+                     DO jk = ikwneg+1, jpksedm1
+                        solcp(ji,jk,js) = zfull(jk) * zsolcpno(jk,js) + zempty(jk) * zsolcpno(jk+1,js) 
+                     ENDDO
+                     solcp(ji,jpksed,js) = zfull(jpksed) * zsolcpno(jpksed,js)
+                  ENDDO
+                  solcp(ji,jpksed,jsclay) = solcp(ji,jpksed,jsclay) + zempty(jpksed) * 1.
+               ELSE
+
+                  zfull (jpksed) = zfilled(jpksed) - zkwnlo * dvolsm(jpksed)
+                  zempty(jpksed) = 1. - zfull(jpksed)                
+                  DO js = 1, jpsol
+                     solcp(ji,jpksed,js) = zfull(jpksed) * zsolcpno(jpksed,js)
+                  ENDDO
+                  solcp(ji,jpksed,jsclay) = solcp(ji,jpksed,jsclay) + zempty(jpksed) * 1.
+               ENDIF ! jpksedm1
+               
+               ! ikwneg = jpksedm1  ; ikwneg+1 = jpksed ; ikwneg-1 = jpksed - 2
+               DO js = 1, jpsol
+                  solcp(ji,ikwneg,js) =  zfull(ikwneg) * zsolcpno(ikwneg  ,js) &
+                     &                +  zkwnup        * zsolcpno(ikwneg-1,js) &
+                     &                +  zkwnlo        * zsolcpno(ikwneg+1,js)   
+                  tosed  (ji,js)   = 0.
+                  fromsed(ji,js)   = 0.
+               ENDDO
+               ! Heinze  fromsed(ji,jsclay) = zempty * 1. * denssol * por1(jpksed) / mol_wgt(jsclay)
+               fromsed(ji,jsclay) = zempty(jpksed) * 1. * por1clay
+
+            ENDIF ! ikwneg(ji) = 2
+         ENDIF  ! zwb > 0
+      ENDDO  ! ji = 1, jpoce
+
+      rainrm(:,:) = 0.
+      rainrg(:,:) = 0.
+      raintg(:)   = 0.
+
+      DEALLOCATE( zraipush )
+
+      IF( ln_timing )  CALL timing_stop('sed_adv')
+
+   END SUBROUTINE sed_adv
+
+
+   INTEGER FUNCTION sed_adv_alloc()
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE p4z_prod_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( dvolsp(jpksed), dvolsm(jpksed), c2por(jpksed),         &
+      &         ckpor(jpksed) ,           STAT = sed_adv_alloc )
+      !
+      IF( sed_adv_alloc /= 0 ) CALL ctl_stop( 'STOP', 'sed_adv_alloc : failed to allocate arrays.' )
+      !
+   END FUNCTION sed_adv_alloc
+
+END MODULE sedadv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedarr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedarr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedarr.F90	(revision 14097)
@@ -0,0 +1,136 @@
+MODULE sedarr
+   !!======================================================================
+   !!                       ***  MODULE sedarr   ***
+   !!              transform 1D (2D) array to a 2D (1D) table
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !!   arr_2d_1d  : 2-D to 1-D
+   !!   arr_1d_2d  : 1-D to 2-D
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE par_sed
+   USE dom_oce
+   USE sed
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE pack_arr
+      MODULE PROCEDURE pack_arr_2d_1d , pack_arr_3d_2d 
+   END INTERFACE
+
+   INTERFACE unpack_arr
+      MODULE PROCEDURE unpack_arr_1d_2d , unpack_arr_2d_3d 
+   END INTERFACE
+
+   !! * Routine accessibility
+   PUBLIC pack_arr
+   PUBLIC unpack_arr
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE pack_arr_2d_1d ( ndim1d, tab1d, tab2d, tab_ind )
+
+      INTEGER, INTENT(in) ::  ndim1d
+      REAL(wp), DIMENSION (jpi, jpj), INTENT(in) :: tab2d
+      INTEGER, DIMENSION (ndim1d), INTENT (in) :: tab_ind
+      REAL(wp), DIMENSION(ndim1d), INTENT (out) ::  tab1d
+
+      INTEGER ::  jn, jid, jjd
+
+      IF( ln_timing )   CALL timing_start('pack_arr_2d_1d')
+        
+      DO jn = 1, ndim1d
+         jid        = MOD( tab_ind(jn) - 1, jpi ) + 1
+         jjd        = ( tab_ind(jn) - 1 ) / jpi + 1
+         tab1d(jn)  = tab2d(jid, jjd)
+      END DO 
+
+      IF( ln_timing )   CALL timing_stop('pack_arr_2d_1d')
+
+   END SUBROUTINE pack_arr_2d_1d
+
+   SUBROUTINE unpack_arr_1d_2d ( ndim1d, tab2d, tab_ind, tab1d )
+
+      INTEGER, INTENT ( in) ::  ndim1d
+      INTEGER, DIMENSION (ndim1d) , INTENT (in) ::   tab_ind
+      REAL(wp), DIMENSION(ndim1d), INTENT (in) ::   tab1d  
+      REAL(wp), DIMENSION (jpi, jpj), INTENT ( out) ::  tab2d
+      INTEGER ::  jn, jid, jjd
+
+      IF( ln_timing )   CALL timing_start('unpack_arr_1d_2d')
+
+      DO jn = 1, ndim1d
+         jid             = MOD( tab_ind(jn) - 1, jpi) + 1
+         jjd             =    ( tab_ind(jn) - 1 ) / jpi  + 1
+         tab2d(jid, jjd) = tab1d(jn)
+      END DO
+
+      IF( ln_timing )   CALL timing_stop('unpack_arr_1d_2d')
+
+   END SUBROUTINE unpack_arr_1d_2d
+
+   SUBROUTINE pack_arr_3d_2d ( ndim1d, tab2d, tab3d, tab_ind )
+
+      INTEGER, INTENT(in) :: ndim1d      
+      REAL(wp), DIMENSION(jpi,jpj,jpksed), INTENT(in) ::   tab3d      
+      INTEGER, DIMENSION(ndim1d), INTENT (in) ::   tab_ind      
+      REAL(wp), DIMENSION(ndim1d,jpksed), INTENT (out) ::    tab2d 
+      INTEGER, DIMENSION(ndim1d) ::  jid, jjd        
+      INTEGER ::    jk, jn , ji, jj
+
+      IF( ln_timing )   CALL timing_start('pack_arr_2d_3d')
+      
+      DO jn = 1, ndim1d
+         jid(jn) = MOD( tab_ind(jn) - 1, jpi ) + 1
+         jjd(jn) = ( tab_ind(jn) - 1 ) / jpi + 1
+      END DO
+ 
+      DO jk = 1, jpksed
+         DO jn = 1, ndim1d
+            ji = jid(jn)
+            jj = jjd(jn)
+            tab2d(jn,jk)  = tab3d(ji,jj,jk) 
+         ENDDO
+      ENDDO
+
+      IF( ln_timing )   CALL timing_stop('pack_arr_2d_3d')
+      
+   END SUBROUTINE pack_arr_3d_2d
+
+
+   SUBROUTINE unpack_arr_2d_3d ( ndim1d, tab3d, tab_ind, tab2d )
+
+      INTEGER, INTENT(in) :: ndim1d      
+      REAL(wp), DIMENSION(ndim1d,jpksed), INTENT(in) ::   tab2d      
+      INTEGER, DIMENSION(ndim1d), INTENT (in) ::   tab_ind      
+      REAL(wp), DIMENSION(jpi,jpj,jpksed), INTENT (out) ::    tab3d 
+      INTEGER, DIMENSION(ndim1d) ::  jid, jjd        
+      INTEGER ::   jk, jn , ji, jj
+      !
+      IF( ln_timing )   CALL timing_start('unpack_arr_2d_3d')
+      !
+      DO jn = 1, ndim1d
+         jid(jn) = MOD( tab_ind(jn) - 1, jpi ) + 1
+         jjd(jn) = ( tab_ind(jn) - 1 ) / jpi + 1
+      END DO
+ 
+      DO jk = 1, jpksed
+         DO jn = 1, ndim1d
+            ji = jid(jn)
+            jj = jjd(jn)
+            tab3d(ji, jj, jk) = tab2d(jn,jk)
+         ENDDO
+      ENDDO
+
+      IF( ln_timing )   CALL timing_stop('unpack_arr_2d_3d')
+
+   END SUBROUTINE unpack_arr_2d_3d
+
+END MODULE sedarr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedbtb.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedbtb.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedbtb.F90	(revision 14097)
@@ -0,0 +1,79 @@
+MODULE sedbtb
+   !!======================================================================
+   !!              ***  MODULE  sedbtb  ***
+   !!    Sediment : bioturbation of the solid components
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sedmat  ! linear system of equations
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_btb
+
+
+   !! $Id$
+CONTAINS
+   
+   SUBROUTINE sed_btb( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sed_btb  ***
+      !!
+      !! ** Purpose :  performs bioturbation of the solid sediment components
+      !!
+      !! ** Method  :  ``diffusion'' of solid sediment components. 
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) F90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      !!* Arguments
+      INTEGER, INTENT(in) ::  kt              ! time step
+
+      ! * local variables
+      INTEGER :: ji, jk, js
+      REAL(wp), DIMENSION(jpoce,jpksedm1,jpsol) ::  zsol  !   solution
+      !------------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_btb')
+
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) WRITE(numsed,*) ' sed_btb : Bioturbation  '
+         IF (lwp) WRITE(numsed,*) ' '
+      ENDIF
+
+      ! Initializations
+      !----------------
+      zsol(:,:,:) = 0.
+
+      ! right hand side of coefficient matrix
+      !--------------------------------------
+      DO js = 1, jpsol
+         DO jk = 1, jpksedm1
+            DO ji = 1, jpoce
+               zsol(ji,jk,js) = solcp(ji,jk+1,js)
+            ENDDO
+         ENDDO
+      ENDDO
+
+      CALL sed_mat( jpsol, jpoce, jpksedm1, zsol, dtsed / 2.0 )
+
+
+      ! store solution of the tridiagonal system
+      !------------------------
+      DO js = 1, jpsol
+         DO jk = 1, jpksedm1
+            DO ji = 1, jpoce
+               solcp(ji,jk+1,js) = zsol(ji,jk,js)
+            ENDDO
+         ENDDO
+      ENDDO
+
+      IF( ln_timing )  CALL timing_stop('sed_btb')
+
+   END SUBROUTINE sed_btb
+
+END MODULE sedbtb
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedchem.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedchem.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedchem.F90	(revision 14097)
@@ -0,0 +1,784 @@
+MODULE sedchem
+
+   !!======================================================================
+   !!                        ***  Module sedchem  ***
+   !! sediment :   Variable for chemistry of the CO2 cycle
+   !!======================================================================
+   !!   modules used
+   USE sed     ! sediment global variable
+   USE sedarr
+   USE eosbn2, ONLY : neos
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Accessibility
+   PUBLIC sed_chem
+   PUBLIC ahini_for_at_sed     !
+   PUBLIC solve_at_general_sed !
+
+   ! Maximum number of iterations for each method
+   INTEGER, PARAMETER :: jp_maxniter_atgen    = 20
+   REAL(wp), PARAMETER :: pp_rdel_ah_target = 1.E-4_wp
+
+   !! * Module variables
+   REAL(wp) :: &
+      calcon = 1.03E-2        ! mean calcite concentration [Ca2+] in sea water [mole/kg solution] 
+
+   REAL(wp) ::   rgas   = 83.14472      ! universal gas constants
+
+   ! coeff. for density of sea water (Millero & Poisson 1981) 
+   REAL(wp), DIMENSION(5)  :: Adsw                       
+   DATA Adsw/8.24493E-1, -4.0899E-3, 7.6438E-5 , -8.246E-7, 5.3875E-9 /
+
+   REAL(wp), DIMENSION(3)  :: Bdsw 
+   DATA Bdsw / -5.72466E-3, 1.0227E-4, -1.6546E-6 /
+
+   REAL(wp)  :: Cdsw = 4.8314E-4
+
+   REAL(wp), DIMENSION(6)  :: Ddsw                    
+   DATA Ddsw / 999.842594 , 6.793952E-2 , -9.095290E-3, 1.001685E-4, -1.120083E-6, 6.536332E-9/
+
+  REAL(wp) :: devk10  = -25.5
+   REAL(wp) :: devk11  = -15.82
+   REAL(wp) :: devk12  = -29.48
+   REAL(wp) :: devk13  = -20.02
+   REAL(wp) :: devk14  = -18.03
+   REAL(wp) :: devk15  = -9.78
+   REAL(wp) :: devk16  = -48.76
+   REAL(wp) :: devk17  = -14.51
+   REAL(wp) :: devk18  = -23.12
+   REAL(wp) :: devk19  = -26.57
+   REAL(wp) :: devk110  = -29.48
+   !
+   REAL(wp) :: devk20  = 0.1271
+   REAL(wp) :: devk21  = -0.0219
+   REAL(wp) :: devk22  = 0.1622
+   REAL(wp) :: devk23  = 0.1119
+   REAL(wp) :: devk24  = 0.0466
+   REAL(wp) :: devk25  = -0.0090
+   REAL(wp) :: devk26  = 0.5304
+   REAL(wp) :: devk27  = 0.1211
+   REAL(wp) :: devk28  = 0.1758
+   REAL(wp) :: devk29  = 0.2020
+   REAL(wp) :: devk210  = 0.1622
+   !
+   REAL(wp) :: devk30  = 0.
+   REAL(wp) :: devk31  = 0.
+   REAL(wp) :: devk32  = 2.608E-3
+   REAL(wp) :: devk33  = -1.409e-3
+   REAL(wp) :: devk34  = 0.316e-3
+   REAL(wp) :: devk35  = -0.942e-3
+   REAL(wp) :: devk36  = 0.
+   REAL(wp) :: devk37  = -0.321e-3
+   REAL(wp) :: devk38  = -2.647e-3
+   REAL(wp) :: devk39  = -3.042e-3
+   REAL(wp) :: devk310  = -2.6080e-3
+   !
+   REAL(wp) :: devk40  = -3.08E-3
+   REAL(wp) :: devk41  = 1.13E-3
+   REAL(wp) :: devk42  = -2.84E-3
+   REAL(wp) :: devk43  = -5.13E-3
+   REAL(wp) :: devk44  = -4.53e-3
+   REAL(wp) :: devk45  = -3.91e-3
+   REAL(wp) :: devk46  = -11.76e-3
+   REAL(wp) :: devk47  = -2.67e-3
+   REAL(wp) :: devk48  = -5.15e-3
+   REAL(wp) :: devk49  = -4.08e-3
+   REAL(wp) :: devk410  = -2.84e-3
+   !
+   REAL(wp) :: devk50  = 0.0877E-3
+   REAL(wp) :: devk51  = -0.1475E-3
+   REAL(wp) :: devk52  = 0.
+   REAL(wp) :: devk53  = 0.0794E-3
+   REAL(wp) :: devk54  = 0.09e-3
+   REAL(wp) :: devk55  = 0.054e-3
+   REAL(wp) :: devk56  = 0.3692E-3
+   REAL(wp) :: devk57  = 0.0427e-3
+   REAL(wp) :: devk58  = 0.09e-3
+   REAL(wp) :: devk59  = 0.0714e-3
+   REAL(wp) :: devk510  = 0.0
+
+   !! $Id$
+CONTAINS
+
+   SUBROUTINE sed_chem( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_chem  ***
+      !!
+      !! ** Purpose :   set chemical constants
+      !!
+      !!   History :
+      !!        !  04-10  (N. Emprin, M. Gehlen )  Original code
+      !!        !  06-04  (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      !!* Arguments
+      INTEGER, INTENT(in) :: kt                     ! time step
+
+      INTEGER  :: ji, jj, ikt
+      REAL(wp) :: ztc, ztc2
+      REAL(wp) :: zsal, zsal15  
+      REAL(wp) :: zdens0, zaw, zbw, zcw    
+      REAL(wp), DIMENSION(jpi,jpj,15) ::   zchem_data
+      !!----------------------------------------------------------------------
+
+
+      IF( ln_timing )  CALL timing_start('sed_chem')
+
+      IF (lwp) WRITE(numsed,*) ' Getting Chemical constants from tracer model at time kt = ', kt
+      IF (lwp) WRITE(numsed,*) ' '
+
+      ! reading variables
+      zchem_data(:,:,:) = rtrn
+
+      IF (ln_sediment_offline) THEN
+         CALL sed_chem_cst
+      ELSE
+         DO jj = 1,jpj
+            DO ji = 1, jpi
+               ikt = mbkt(ji,jj) 
+               IF ( tmask(ji,jj,ikt) == 1 ) THEN
+                  zchem_data(ji,jj,1) = ak13  (ji,jj,ikt)
+                  zchem_data(ji,jj,2) = ak23  (ji,jj,ikt)
+                  zchem_data(ji,jj,3) = akb3  (ji,jj,ikt)
+                  zchem_data(ji,jj,4) = akw3  (ji,jj,ikt)
+                  zchem_data(ji,jj,5) = aksp  (ji,jj,ikt)
+                  zchem_data(ji,jj,6) = borat (ji,jj,ikt)
+                  zchem_data(ji,jj,7) = ak1p3 (ji,jj,ikt)
+                  zchem_data(ji,jj,8) = ak2p3 (ji,jj,ikt)
+                  zchem_data(ji,jj,9) = ak3p3 (ji,jj,ikt)
+                  zchem_data(ji,jj,10)= aksi3 (ji,jj,ikt)
+                  zchem_data(ji,jj,11)= sio3eq(ji,jj,ikt)
+                  zchem_data(ji,jj,12)= aks3  (ji,jj,ikt)
+                  zchem_data(ji,jj,13)= akf3  (ji,jj,ikt)
+                  zchem_data(ji,jj,14)= sulfat(ji,jj,ikt)
+                  zchem_data(ji,jj,15)= fluorid(ji,jj,ikt)
+               ENDIF
+            ENDDO
+         ENDDO
+
+         CALL pack_arr ( jpoce, ak1s  (1:jpoce), zchem_data(1:jpi,1:jpj,1) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, ak2s  (1:jpoce), zchem_data(1:jpi,1:jpj,2) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, akbs  (1:jpoce), zchem_data(1:jpi,1:jpj,3) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, akws  (1:jpoce), zchem_data(1:jpi,1:jpj,4) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, aksps (1:jpoce), zchem_data(1:jpi,1:jpj,5) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, borats(1:jpoce), zchem_data(1:jpi,1:jpj,6) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, ak1ps (1:jpoce), zchem_data(1:jpi,1:jpj,7) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, ak2ps (1:jpoce), zchem_data(1:jpi,1:jpj,8) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, ak3ps (1:jpoce), zchem_data(1:jpi,1:jpj,9) , iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, aksis (1:jpoce), zchem_data(1:jpi,1:jpj,10), iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, sieqs (1:jpoce), zchem_data(1:jpi,1:jpj,11), iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, aks3s (1:jpoce), zchem_data(1:jpi,1:jpj,12), iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, akf3s (1:jpoce), zchem_data(1:jpi,1:jpj,13), iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, sulfats(1:jpoce), zchem_data(1:jpi,1:jpj,14), iarroce(1:jpoce) )
+         CALL pack_arr ( jpoce, fluorids(1:jpoce), zchem_data(1:jpi,1:jpj,15), iarroce(1:jpoce) )
+      ENDIF
+
+      DO ji = 1, jpoce
+         ztc     = temp(ji)
+         ztc2    = ztc * ztc
+         ! zqtt    = ztkel * 0.01
+         zsal    = salt(ji)
+         zsal15  = SQRT( zsal ) * zsal
+
+         ! Density of Sea Water - F(temp,sal) [kg/m3]
+         zdens0 =  Ddsw(1) + Ddsw(2) * ztc + Ddsw(3) * ztc2 &
+                  + Ddsw(4) * ztc * ztc2 + Ddsw(5) * ztc2 * ztc2 &
+                  + Ddsw(6) * ztc * ztc2 * ztc2
+         zaw =  Adsw(1) + Adsw(2) * ztc + Adsw(3)* ztc2 + Adsw(4) * ztc * ztc2 &
+              + Adsw(5) * ztc2 * ztc2
+         zbw =  Bdsw(1) + Bdsw(2) * ztc + Bdsw(3) * ztc2
+         zcw =  Cdsw
+         densSW(ji) = zdens0 + zaw * zsal + zbw * zsal15 + zcw * zsal * zsal
+         densSW(ji) = densSW(ji) * 1E-3   ! to get dens in [kg/l]
+
+         ak12s  (ji) = ak1s (ji) * ak2s (ji)
+         ak12ps (ji) = ak1ps(ji) * ak2ps(ji)
+         ak123ps(ji) = ak1ps(ji) * ak2ps(ji) * ak3ps(ji)
+
+         calcon2(ji) = 0.01028 * ( salt(ji) / 35. ) * densSW(ji)
+      ENDDO
+       
+      IF( ln_timing )  CALL timing_stop('sed_chem')
+
+   END SUBROUTINE sed_chem
+
+   SUBROUTINE ahini_for_at_sed(p_hini)
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE ahini_for_at  ***
+      !!
+      !! Subroutine returns the root for the 2nd order approximation of the
+      !! DIC -- B_T -- A_CB equation for [H+] (reformulated as a cubic 
+      !! polynomial) around the local minimum, if it exists.
+      !! Returns * 1E-03_wp if p_alkcb <= 0
+      !!         * 1E-10_wp if p_alkcb >= 2*p_dictot + p_bortot
+      !!         * 1E-07_wp if 0 < p_alkcb < 2*p_dictot + p_bortot
+      !!                    and the 2nd order approximation does not have 
+      !!                    a solution
+      !!---------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpoce,jpksed), INTENT(OUT)  ::  p_hini
+      INTEGER  ::   ji, jk
+      REAL(wp)  ::  zca1, zba1
+      REAL(wp)  ::  zd, zsqrtd, zhmin
+      REAL(wp)  ::  za2, za1, za0
+      REAL(wp)  ::  p_dictot, p_bortot, p_alkcb
+
+      IF( ln_timing )  CALL timing_start('ahini_for_at_sed')
+      !
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            p_alkcb  = pwcp(ji,jk,jwalk) / densSW(ji)
+            p_dictot = pwcp(ji,jk,jwdic) / densSW(ji) 
+            p_bortot = borats(ji) / densSW(ji)
+            IF (p_alkcb <= 0.) THEN
+                p_hini(ji,jk) = 1.e-3
+            ELSEIF (p_alkcb >= (2.*p_dictot + p_bortot)) THEN
+                p_hini(ji,jk) = 1.e-10_wp
+            ELSE
+                zca1 = p_dictot/( p_alkcb + rtrn )
+                zba1 = p_bortot/ (p_alkcb + rtrn )
+           ! Coefficients of the cubic polynomial
+                za2 = aKbs(ji)*(1. - zba1) + ak1s(ji)*(1.-zca1)
+                za1 = ak1s(ji)*akbs(ji)*(1. - zba1 - zca1)    &
+                &     + ak1s(ji)*ak2s(ji)*(1. - (zca1+zca1))
+                za0 = ak1s(ji)*ak2s(ji)*akbs(ji)*(1. - zba1 - (zca1+zca1))
+                                        ! Taylor expansion around the minimum
+                zd = za2*za2 - 3.*za1   ! Discriminant of the quadratic equation
+                                        ! for the minimum close to the root
+
+                IF(zd > 0.) THEN        ! If the discriminant is positive
+                  zsqrtd = SQRT(zd)
+                  IF(za2 < 0) THEN
+                    zhmin = (-za2 + zsqrtd)/3.
+                  ELSE
+                    zhmin = -za1/(za2 + zsqrtd)
+                  ENDIF
+                  p_hini(ji,jk) = zhmin + SQRT(-(za0 + zhmin*(za1 + zhmin*(za2 + zhmin)))/zsqrtd)
+                ELSE
+                  p_hini(ji,jk) = 1.e-7
+                ENDIF
+             !
+            ENDIF
+         END DO
+      END DO
+      !
+      IF( ln_timing )  CALL timing_stop('ahini_for_at_sed')
+      !
+   END SUBROUTINE ahini_for_at_sed
+
+   !===============================================================================
+   SUBROUTINE anw_infsup_sed( p_alknw_inf, p_alknw_sup )
+
+   ! Subroutine returns the lower and upper bounds of "non-water-selfionization"
+   ! contributions to total alkalinity (the infimum and the supremum), i.e
+   ! inf(TA - [OH-] + [H+]) and sup(TA - [OH-] + [H+])
+
+   ! Argument variables
+   INTEGER :: jk
+   REAL(wp), DIMENSION(jpoce,jpksed), INTENT(OUT) :: p_alknw_inf
+   REAL(wp), DIMENSION(jpoce,jpksed), INTENT(OUT) :: p_alknw_sup
+
+   DO jk = 1, jpksed
+      p_alknw_inf(:,jk) =  -pwcp(:,jk,jwpo4) / densSW(:)
+      p_alknw_sup(:,jk) =   (2. * pwcp(:,jk,jwdic) + 2. * pwcp(:,jk,jwpo4) + pwcp(:,jk,jwsil)     &
+   &                        + borats(:) ) / densSW(:)
+   END DO
+
+   END SUBROUTINE anw_infsup_sed
+
+
+   SUBROUTINE solve_at_general_sed( p_hini, zhi )
+
+   ! Universal pH solver that converges from any given initial value,
+   ! determines upper an lower bounds for the solution if required
+
+   ! Argument variables
+   !--------------------
+   REAL(wp), DIMENSION(jpoce,jpksed), INTENT(IN)   :: p_hini
+   REAL(wp), DIMENSION(jpoce,jpksed), INTENT(OUT)  :: zhi
+
+   ! Local variables
+   !-----------------
+   INTEGER   ::  ji, jk, jn
+   REAL(wp)  ::  zh_ini, zh, zh_prev, zh_lnfactor
+   REAL(wp)  ::  zdelta, zh_delta
+   REAL(wp)  ::  zeqn, zdeqndh, zalka
+   REAL(wp)  ::  aphscale
+   REAL(wp)  ::  znumer_dic, zdnumer_dic, zdenom_dic, zalk_dic, zdalk_dic
+   REAL(wp)  ::  znumer_bor, zdnumer_bor, zdenom_bor, zalk_bor, zdalk_bor
+   REAL(wp)  ::  znumer_po4, zdnumer_po4, zdenom_po4, zalk_po4, zdalk_po4
+   REAL(wp)  ::  znumer_sil, zdnumer_sil, zdenom_sil, zalk_sil, zdalk_sil
+   REAL(wp)  ::  znumer_so4, zdnumer_so4, zdenom_so4, zalk_so4, zdalk_so4
+   REAL(wp)  ::  znumer_flu, zdnumer_flu, zdenom_flu, zalk_flu, zdalk_flu
+   REAL(wp)  ::  zalk_wat, zdalk_wat
+   REAL(wp)  ::  zfact, p_alktot, zdic, zbot, zpt, zst, zft, zsit
+   LOGICAL   ::  l_exitnow
+   REAL(wp), PARAMETER :: pz_exp_threshold = 1.0
+   REAL(wp), DIMENSION(jpoce,jpksed) :: zalknw_inf, zalknw_sup, rmask, zh_min, zh_max, zeqn_absmin
+
+   IF( ln_timing )  CALL timing_start('solve_at_general_sed')
+      !  Allocate temporary workspace
+   CALL anw_infsup_sed( zalknw_inf, zalknw_sup )
+
+   rmask(:,:) = 1.0
+   zhi(:,:)   = 0.
+
+   ! TOTAL H+ scale: conversion factor for Htot = aphscale * Hfree
+   DO jk = 1, jpksed
+      DO ji = 1, jpoce
+         IF (rmask(ji,jk) == 1.) THEN
+            p_alktot = pwcp(ji,jk,jwalk) / densSW(ji)
+            aphscale = 1. + sulfats(ji)/aks3s(ji)
+            zh_ini = p_hini(ji,jk)
+
+            zdelta = (p_alktot-zalknw_inf(ji,jk))**2 + 4.*akws(ji) / aphscale
+
+            IF(p_alktot >= zalknw_inf(ji,jk)) THEN
+               zh_min(ji,jk) = 2.*akws(ji) /( p_alktot-zalknw_inf(ji,jk) + SQRT(zdelta) )
+            ELSE
+               zh_min(ji,jk) = aphscale * (-(p_alktot-zalknw_inf(ji,jk)) + SQRT(zdelta) ) / 2.
+            ENDIF
+
+            zdelta = (p_alktot-zalknw_sup(ji,jk))**2 + 4.*akws(ji) / aphscale
+
+            IF(p_alktot <= zalknw_sup(ji,jk)) THEN
+               zh_max(ji,jk) = aphscale * (-(p_alktot-zalknw_sup(ji,jk)) + SQRT(zdelta) ) / 2.
+            ELSE
+               zh_max(ji,jk) = 2.*akws(ji) /( p_alktot-zalknw_sup(ji,jk) + SQRT(zdelta) )
+            ENDIF
+
+            zhi(ji,jk) = MAX(MIN(zh_max(ji,jk), zh_ini), zh_min(ji,jk))
+         ENDIF
+      END DO
+   END DO
+
+   zeqn_absmin(:,:) = HUGE(1._wp)
+
+   DO jn = 1, jp_maxniter_atgen
+   DO jk = 1, jpksed
+      DO ji = 1, jpoce
+         IF (rmask(ji,jk) == 1.) THEN
+
+            p_alktot = pwcp(ji,jk,jwalk) / densSW(ji)
+            zdic  = pwcp(ji,jk,jwdic) / densSW(ji)
+            zbot  = borats(ji) / densSW(ji)
+            zpt =  pwcp(ji,jk,jwpo4) / densSW(ji)
+            zsit = pwcp(ji,jk,jwsil) / densSW(ji)
+            zst = sulfats(ji)
+            zft = fluorids(ji)
+            aphscale = 1. + sulfats(ji)/aks3s(ji)
+            zh = zhi(ji,jk)
+            zh_prev = zh
+
+            ! H2CO3 - HCO3 - CO3 : n=2, m=0
+            znumer_dic = 2.*ak1s(ji)*ak2s(ji) + zh*ak1s(ji)
+            zdenom_dic = ak1s(ji)*ak2s(ji) + zh*(ak1s(ji) + zh)
+            zalk_dic   = zdic * (znumer_dic/zdenom_dic)
+            zdnumer_dic = ak1s(ji)*ak1s(ji)*ak2s(ji) + zh     &
+                          *(4.*ak1s(ji)*ak2s(ji) + zh*ak1s(ji))
+            zdalk_dic   = -zdic*(zdnumer_dic/zdenom_dic**2)
+
+
+            ! B(OH)3 - B(OH)4 : n=1, m=0
+            znumer_bor = akbs(ji)
+            zdenom_bor = akbs(ji) + zh
+            zalk_bor   = zbot * (znumer_bor/zdenom_bor)
+            zdnumer_bor = akbs(ji)
+            zdalk_bor   = -zbot*(zdnumer_bor/zdenom_bor**2)
+
+
+            ! H3PO4 - H2PO4 - HPO4 - PO4 : n=3, m=1
+            znumer_po4 = 3.*ak1ps(ji)*ak2ps(ji)*ak3ps(ji)  &
+            &            + zh*(2.*ak1ps(ji)*ak2ps(ji) + zh* ak1ps(ji))
+            zdenom_po4 = ak1ps(ji)*ak2ps(ji)*ak3ps(ji)     &
+            &            + zh*( ak1ps(ji)*ak2ps(ji) + zh*(ak1ps(ji) + zh))
+            zalk_po4   = zpt * (znumer_po4/zdenom_po4 - 1.) ! Zero level of H3PO4 = 1
+            zdnumer_po4 = ak1ps(ji)*ak2ps(ji)*ak1ps(ji)*ak2ps(ji)*ak3ps(ji)  &
+            &             + zh*(4.*ak1ps(ji)*ak1ps(ji)*ak2ps(ji)*ak3ps(ji)         &
+            &             + zh*(9.*ak1ps(ji)*ak2ps(ji)*ak3ps(ji)                         &
+            &             + ak1ps(ji)*ak1ps(ji)*ak2ps(ji)                                &
+            &             + zh*(4.*ak1ps(ji)*ak2ps(ji) + zh * ak1ps(ji) ) ) )
+            zdalk_po4   = -zpt * (zdnumer_po4/zdenom_po4**2)
+
+            ! H4SiO4 - H3SiO4 : n=1, m=0
+            znumer_sil = aksis(ji)
+            zdenom_sil = aksis(ji) + zh
+            zalk_sil   = zsit * (znumer_sil/zdenom_sil)
+            zdnumer_sil = aksis(ji)
+            zdalk_sil   = -zsit * (zdnumer_sil/zdenom_sil**2)
+
+            ! HSO4 - SO4 : n=1, m=1
+            aphscale = 1.0 + zst/aks3s(ji)
+            znumer_so4 = aks3s(ji) * aphscale
+            zdenom_so4 = aks3s(ji) * aphscale + zh
+            zalk_so4   = zst * (znumer_so4/zdenom_so4 - 1.)
+            zdnumer_so4 = aks3s(ji) * aphscale
+            zdalk_so4   = -zst * (zdnumer_so4/zdenom_so4**2)
+
+            ! HF - F : n=1, m=1
+            znumer_flu =  akf3s(ji)
+            zdenom_flu =  akf3s(ji) + zh
+            zalk_flu   =  zft * (znumer_flu/zdenom_flu - 1.)
+            zdnumer_flu = akf3s(ji)
+            zdalk_flu   = -zft * (zdnumer_flu/zdenom_flu**2)
+
+            ! H2O - OH
+            zalk_wat   = akws(ji)/zh - zh/aphscale
+            zdalk_wat  = -akws(ji)/zh**2 - 1./aphscale
+
+            ! CALCULATE [ALK]([CO3--], [HCO3-])
+            zeqn = zalk_dic + zalk_bor + zalk_po4 + zalk_sil   &
+            &      + zalk_so4 + zalk_flu                       &
+            &      + zalk_wat - p_alktot
+
+            zalka = p_alktot - (zalk_bor + zalk_po4 + zalk_sil   &
+            &       + zalk_so4 + zalk_flu + zalk_wat)
+
+            zdeqndh = zdalk_dic + zdalk_bor + zdalk_po4 + zdalk_sil &
+            &         + zdalk_so4 + zdalk_flu + zdalk_wat
+
+            ! Adapt bracketing interval
+            IF(zeqn > 0._wp) THEN
+               zh_min(ji,jk) = zh_prev
+            ELSEIF(zeqn < 0._wp) THEN
+               zh_max(ji,jk) = zh_prev
+            ENDIF
+
+            IF(ABS(zeqn) >= 0.5_wp*zeqn_absmin(ji,jk)) THEN
+            ! if the function evaluation at the current point is
+            ! not decreasing faster than with a bisection step (at least linearly)
+            ! in absolute value take one bisection step on [ph_min, ph_max]
+            ! ph_new = (ph_min + ph_max)/2d0
+            !
+            ! In terms of [H]_new:
+            ! [H]_new = 10**(-ph_new)
+            !         = 10**(-(ph_min + ph_max)/2d0)
+            !         = SQRT(10**(-(ph_min + phmax)))
+            !         = SQRT(zh_max * zh_min)
+               zh = SQRT(zh_max(ji,jk) * zh_min(ji,jk))
+               zh_lnfactor = (zh - zh_prev)/zh_prev ! Required to test convergence below
+            ELSE
+            ! dzeqn/dpH = dzeqn/d[H] * d[H]/dpH
+            !           = -zdeqndh * LOG(10) * [H]
+            ! \Delta pH = -zeqn/(zdeqndh*d[H]/dpH) = zeqn/(zdeqndh*[H]*LOG(10))
+            !
+            ! pH_new = pH_old + \deltapH
+            !
+            ! [H]_new = 10**(-pH_new)
+            !         = 10**(-pH_old - \Delta pH)
+            !         = [H]_old * 10**(-zeqn/(zdeqndh*[H]_old*LOG(10)))
+            !         = [H]_old * EXP(-LOG(10)*zeqn/(zdeqndh*[H]_old*LOG(10)))
+            !         = [H]_old * EXP(-zeqn/(zdeqndh*[H]_old))
+
+               zh_lnfactor = -zeqn/(zdeqndh*zh_prev)
+
+               IF(ABS(zh_lnfactor) > pz_exp_threshold) THEN
+                  zh          = zh_prev*EXP(zh_lnfactor)
+               ELSE
+                  zh_delta    = zh_lnfactor*zh_prev
+                  zh          = zh_prev + zh_delta
+               ENDIF
+
+               IF( zh < zh_min(ji,jk) ) THEN
+               ! if [H]_new < [H]_min
+               ! i.e., if ph_new > ph_max then
+               ! take one bisection step on [ph_prev, ph_max]
+               ! ph_new = (ph_prev + ph_max)/2d0
+               ! In terms of [H]_new:
+               ! [H]_new = 10**(-ph_new)
+               !         = 10**(-(ph_prev + ph_max)/2d0)
+               !         = SQRT(10**(-(ph_prev + phmax)))
+               !         = SQRT([H]_old*10**(-ph_max))
+               !         = SQRT([H]_old * zh_min)
+                  zh                = SQRT(zh_prev * zh_min(ji,jk))
+                  zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+               ENDIF
+
+               IF( zh > zh_max(ji,jk) ) THEN
+               ! if [H]_new > [H]_max
+               ! i.e., if ph_new < ph_min, then
+               ! take one bisection step on [ph_min, ph_prev]
+               ! ph_new = (ph_prev + ph_min)/2d0
+               ! In terms of [H]_new:
+               ! [H]_new = 10**(-ph_new)
+               !         = 10**(-(ph_prev + ph_min)/2d0)
+               !         = SQRT(10**(-(ph_prev + ph_min)))
+               !         = SQRT([H]_old*10**(-ph_min))
+               !         = SQRT([H]_old * zhmax)
+                  zh                = SQRT(zh_prev * zh_max(ji,jk))
+                  zh_lnfactor       = (zh - zh_prev)/zh_prev ! Required to test convergence below
+               ENDIF
+            ENDIF
+
+            zeqn_absmin(ji,jk) = MIN( ABS(zeqn), zeqn_absmin(ji,jk))
+
+            ! Stop iterations once |\delta{[H]}/[H]| < rdel
+            ! <=> |(zh - zh_prev)/zh_prev| = |EXP(-zeqn/(zdeqndh*zh_prev)) -1| < rdel
+            ! |EXP(-zeqn/(zdeqndh*zh_prev)) -1| ~ |zeqn/(zdeqndh*zh_prev)|
+            ! Alternatively:
+            ! |\Delta pH| = |zeqn/(zdeqndh*zh_prev*LOG(10))|
+            !             ~ 1/LOG(10) * |\Delta [H]|/[H]
+            !             < 1/LOG(10) * rdel
+
+            ! Hence |zeqn/(zdeqndh*zh)| < rdel
+
+            ! rdel <-- pp_rdel_ah_target
+            l_exitnow = (ABS(zh_lnfactor) < pp_rdel_ah_target)
+
+            IF(l_exitnow) THEN
+               rmask(ji,jk) = 0.
+            ENDIF
+
+            zhi(ji,jk) =  zh
+
+            IF(jn >= jp_maxniter_atgen) THEN
+               zhi(ji,jk) = -1._wp
+            ENDIF
+
+         ENDIF
+      END DO
+   END DO
+   END DO
+   !
+   IF( ln_timing )  CALL timing_stop('solve_at_general_sed')
+
+   END SUBROUTINE solve_at_general_sed
+
+   SUBROUTINE sed_chem_cst
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sed_chem_cst  ***
+      !!
+      !! ** Purpose :   Sea water chemistry computed following MOCSY protocol
+      !!                Computation is done at the bottom of the ocean only
+      !!
+      !! ** Method  : - ...
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ji
+      REAL(wp), DIMENSION(jpoce) :: saltprac, temps
+      REAL(wp) ::   ztkel, ztkel1, zt , zsal  , zsal2 , zbuf1 , zbuf2
+      REAL(wp) ::   ztgg , ztgg2, ztgg3 , ztgg4 , ztgg5
+      REAL(wp) ::   zpres, ztc  , zcl   , zcpexp, zoxy  , zcpexp2
+      REAL(wp) ::   zsqrt, ztr  , zlogt , zcek1, zc1, zplat
+      REAL(wp) ::   zis  , zis2 , zsal15, zisqrt, za1, za2
+      REAL(wp) ::   zckb , zck1 , zck2  , zckw  , zak1 , zak2  , zakb , zaksp0, zakw
+      REAL(wp) ::   zck1p, zck2p, zck3p, zcksi, zak1p, zak2p, zak3p, zaksi
+      REAL(wp) ::   zst  , zft  , zcks  , zckf  , zaksp1
+      REAL(wp) ::   total2free, free2SWS, total2SWS, SWS2total
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('sed_chem_cst')
+      !
+      ! Computation of chemical constants require practical salinity
+      ! Thus, when TEOS08 is used, absolute salinity is converted to
+      ! practical salinity
+      ! -------------------------------------------------------------
+      IF (neos == -1) THEN
+         saltprac(:) = salt(:) * 35.0 / 35.16504
+      ELSE
+         saltprac(:) = salt(:)
+      ENDIF
+
+      !
+      ! Computations of chemical constants require in situ temperature
+      ! Here a quite simple formulation is used to convert
+      ! potential temperature to in situ temperature. The errors is less than
+      ! 0.04°C relative to an exact computation
+      ! ---------------------------------------------------------------------
+         DO ji = 1, jpoce
+            zpres = zkbot(ji) / 1000.
+            za1 = 0.04 * ( 1.0 + 0.185 * temp(ji) + 0.035 * (saltprac(ji) - 35.0) )
+            za2 = 0.0075 * ( 1.0 - temp(ji) / 30.0 )
+            temps(ji) = temp(ji) - za1 * zpres + za2 * zpres**2
+         END DO
+
+      ! CHEMICAL CONSTANTS - DEEP OCEAN
+      ! -------------------------------
+      DO ji = 1, jpoce
+         ! SET PRESSION ACCORDING TO SAUNDER (1980)
+         zc1 = 5.92E-3 
+         zpres = ((1-zc1)-SQRT(((1-zc1)**2)-(8.84E-6*zkbot(ji)))) / 4.42E-6
+         zpres = zpres / 10.0
+
+         ! SET ABSOLUTE TEMPERATURE
+         ztkel   = temps(ji) + 273.15
+         zsal    = saltprac(ji)
+         zsqrt  = SQRT( zsal )
+         zsal15  = zsqrt * zsal
+         zlogt  = LOG( ztkel )
+         ztr    = 1. / ztkel
+         zis    = 19.924 * zsal / ( 1000.- 1.005 * zsal )
+         zis2   = zis * zis
+         zisqrt = SQRT( zis )
+         ztc    = temps(ji)
+
+         ! CHLORINITY (WOOSTER ET AL., 1969)
+         zcl     = zsal / 1.80655
+
+         ! TOTAL SULFATE CONCENTR. [MOLES/kg soln]
+         zst     = 0.14 * zcl /96.062
+
+         ! TOTAL FLUORIDE CONCENTR. [MOLES/kg soln]
+         zft     = 0.000067 * zcl /18.9984
+
+         ! DISSOCIATION CONSTANT FOR SULFATES on free H scale (Dickson 1990)
+         zcks    = EXP(-4276.1 * ztr + 141.328 - 23.093 * zlogt         &
+         &         + (-13856. * ztr + 324.57 - 47.986 * zlogt) * zisqrt &
+         &         + (35474. * ztr - 771.54 + 114.723 * zlogt) * zis    &
+         &         - 2698. * ztr * zis**1.5 + 1776.* ztr * zis2         &
+         &         + LOG(1.0 - 0.001005 * zsal))
+
+         ! DISSOCIATION CONSTANT FOR FLUORIDES on free H scale (Dickson and Riley 79)
+         zckf    = EXP( 1590.2*ztr - 12.641 + 1.525*zisqrt   &
+         &         + LOG(1.0d0 - 0.001005d0*zsal)            &
+         &         + LOG(1.0d0 + zst/zcks))
+
+         ! DISSOCIATION CONSTANT FOR CARBONATE AND BORATE
+         zckb=  (-8966.90 - 2890.53*zsqrt - 77.942*zsal        &
+         &      + 1.728*zsal15 - 0.0996*zsal*zsal)*ztr         &
+         &      + (148.0248 + 137.1942*zsqrt + 1.62142*zsal)   &
+         &      + (-24.4344 - 25.085*zsqrt - 0.2474*zsal)      &
+         &      * zlogt + 0.053105*zsqrt*ztkel
+
+         ! DISSOCIATION COEFFICIENT FOR CARBONATE ACCORDING TO
+         ! MEHRBACH (1973) REFIT BY MILLERO (1995), seawater scale
+         zck1    = -1.0*(3633.86*ztr - 61.2172 + 9.6777*zlogt  &
+                   - 0.011555*zsal + 0.0001152*zsal*zsal)
+         zck2    = -1.0*(471.78*ztr + 25.9290 - 3.16967*zlogt      &
+                   - 0.01781*zsal + 0.0001122*zsal*zsal)
+
+         ! PKW (H2O) (MILLERO, 1995) from composite data
+         zckw    = -13847.26 * ztr + 148.9652 - 23.6521 * zlogt + ( 118.67 * ztr    &
+                   - 5.977 + 1.0495 * zlogt ) * zsqrt - 0.01615 * zsal
+
+         ! CONSTANTS FOR PHOSPHATE (MILLERO, 1995)
+         zck1p    = -4576.752*ztr + 115.540 - 18.453*zlogt   &
+         &          + (-106.736*ztr + 0.69171) * zsqrt       &
+         &          + (-0.65643*ztr - 0.01844) * zsal
+
+         zck2p    = -8814.715*ztr + 172.1033 - 27.927*zlogt  &
+         &          + (-160.340*ztr + 1.3566)*zsqrt          &
+         &          + (0.37335*ztr - 0.05778)*zsal
+
+         zck3p    = -3070.75*ztr - 18.126                    &
+         &          + (17.27039*ztr + 2.81197) * zsqrt       &
+         &          + (-44.99486*ztr - 0.09984) * zsal
+
+         ! CONSTANT FOR SILICATE, MILLERO (1995)
+         zcksi    = -8904.2*ztr  + 117.400 - 19.334*zlogt   &
+         &          + (-458.79*ztr + 3.5913) * zisqrt       &
+         &          + (188.74*ztr - 1.5998) * zis           &
+         &          + (-12.1652*ztr + 0.07871) * zis2       &
+         &          + LOG(1.0 - 0.001005*zsal)
+
+         ! APPARENT SOLUBILITY PRODUCT K'SP OF CALCITE IN SEAWATER
+         !       (S=27-43, T=2-25 DEG C) at pres =0 (atmos. pressure) (MUCCI 1983)
+         zaksp0  = -171.9065 -0.077993*ztkel + 2839.319*ztr + 71.595*LOG10( ztkel )   &
+         &         + (-0.77712 + 0.00284263*ztkel + 178.34*ztr) * zsqrt  &
+         &         - 0.07711*zsal + 0.0041249*zsal15
+
+         ! CONVERT FROM DIFFERENT PH SCALES
+         total2free  = 1.0/(1.0 + zst/zcks)
+         free2SWS    = 1. + zst/zcks + zft/(zckf*total2free)
+         total2SWS   = total2free * free2SWS
+         SWS2total   = 1.0 / total2SWS
+
+
+         ! K1, K2 OF CARBONIC ACID, KB OF BORIC ACID, KW (H2O) (LIT.?)
+         zak1    = 10**(zck1) * total2SWS
+         zak2    = 10**(zck2) * total2SWS
+         zakb    = EXP( zckb ) * total2SWS
+         zakw    = EXP( zckw )
+         zaksp1  = 10**(zaksp0)
+         zak1p   = exp( zck1p )
+         zak2p   = exp( zck2p )
+         zak3p   = exp( zck3p )
+         zaksi   = exp( zcksi )
+         zckf    = zckf * total2SWS
+
+         ! FORMULA FOR CPEXP AFTER EDMOND & GIESKES (1970)
+         !        (REFERENCE TO CULBERSON & PYTKOQICZ (1968) AS MADE
+         !        IN BROECKER ET AL. (1982) IS INCORRECT; HERE RGAS IS
+         !        TAKEN TENFOLD TO CORRECT FOR THE NOTATION OF pres  IN
+         !        DBAR INSTEAD OF BAR AND THE EXPRESSION FOR CPEXP IS
+         !        MULTIPLIED BY LN(10.) TO ALLOW USE OF EXP-FUNCTION
+         !        WITH BASIS E IN THE FORMULA FOR AKSPP (CF. EDMOND
+         !        & GIESKES (1970), P. 1285-1286 (THE SMALL
+         !        FORMULA ON P. 1286 IS RIGHT AND CONSISTENT WITH THE
+         !        SIGN IN PARTIAL MOLAR VOLUME CHANGE AS SHOWN ON P. 1285))
+         zcpexp  = zpres / (rgas*ztkel)
+         zcpexp2 = zpres * zcpexp
+
+         ! KB OF BORIC ACID, K1,K2 OF CARBONIC ACID PRESSURE
+         !        CORRECTION AFTER CULBERSON AND PYTKOWICZ (1968)
+         !        (CF. BROECKER ET AL., 1982)
+
+         zbuf1  = -     ( devk10 + devk20 * ztc + devk30 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk40 + devk50 * ztc )
+         ak1s(ji) = zak1 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk11 + devk21 * ztc + devk31 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk41 + devk51 * ztc )
+         ak2s(ji) = zak2 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk12 + devk22 * ztc + devk32 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk42 + devk52 * ztc )
+         akbs(ji) = zakb * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk13 + devk23 * ztc + devk33 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk43 + devk53 * ztc )
+         akws(ji) = zakw * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk14 + devk24 * ztc + devk34 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk44 + devk54 * ztc )
+         aks3s(ji) = zcks * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk15 + devk25 * ztc + devk35 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk45 + devk55 * ztc )
+         akf3s(ji) = zckf * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk17 + devk27 * ztc + devk37 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk47 + devk57 * ztc )
+         ak1ps(ji) = zak1p * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk18 + devk28 * ztc + devk38 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk48 + devk58 * ztc )
+         ak2ps(ji) = zak2p * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         zbuf1  =     - ( devk110 + devk210 * ztc + devk310 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk410 + devk510 * ztc )
+         aksis(ji) = zaksi * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         ! Convert to total scale
+         ak1s(ji)  = ak1s(ji)  * SWS2total
+         ak2s(ji)  = ak2s(ji)  * SWS2total
+         akbs(ji)  = akbs(ji)  * SWS2total
+         akws(ji)  = akws(ji)  * SWS2total
+         ak1ps(ji) = ak1ps(ji) * SWS2total
+         ak2ps(ji) = ak2ps(ji) * SWS2total
+         ak3ps(ji) = ak3ps(ji) * SWS2total
+         aksis(ji) = aksis(ji) * SWS2total
+         akf3s(ji) = akf3s(ji) / total2free
+
+         ! APPARENT SOLUBILITY PRODUCT K'SP OF CALCITE
+         !        AS FUNCTION OF PRESSURE FOLLOWING MILLERO
+         !        (P. 1285) AND BERNER (1976)
+         zbuf1  =     - ( devk16 + devk26 * ztc + devk36 * ztc * ztc )
+         zbuf2  = 0.5 * ( devk46 + devk56 * ztc )
+         aksps(ji) = zaksp1 * EXP( zbuf1 * zcpexp + zbuf2 * zcpexp2 )
+
+         ! TOTAL F, S, and BORATE CONCENTR. [MOLES/L]
+         borats(ji)   = 0.0002414 * zcl / 10.811
+         sulfats(ji)  = zst
+         fluorids(ji) = zft
+
+         ! Iron and SIO3 saturation concentration from ...
+         sieqs(ji) = EXP(  LOG( 10.) * ( 6.44 - 968. / ztkel )  ) * 1.e-6
+      END DO
+      !
+      IF( ln_timing )  CALL timing_stop('sed_chem_cst')
+      !
+   END SUBROUTINE sed_chem_cst
+
+
+END MODULE sedchem
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedco3.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedco3.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedco3.F90	(revision 14097)
@@ -0,0 +1,80 @@
+MODULE sedco3
+   !!======================================================================
+   !!              ***  MODULE  sedco3  ***
+   !!    Sediment : carbonate in sediment pore water
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sedchem
+   USE lib_mpp         ! distribued memory computing library
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! *  Routine accessibility
+   PUBLIC sed_co3     
+
+   !!----------------------------------------------------------------------
+   !!   OPA 9.0   !   LODYC-IPSL   (2003)
+   !!----------------------------------------------------------------------
+
+   !! $Id$
+CONTAINS
+
+
+   SUBROUTINE sed_co3( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_co3  ***
+      !!
+      !! ** Purpose :  carbonate ion and proton concentration 
+      !!               in sediment pore water
+      !!
+      !! ** Methode :  - solving nonlinear equation for [H+] with given alkalinity
+      !!               and total co2 
+      !!               - one dimensional newton-raphson algorithm for [H+])
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) coupled with PISCES
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      !! * Arguments
+      INTEGER, INTENT(in)  :: kt   ! time step
+      !
+      !---Local variables
+      INTEGER  :: ji, jk           ! dummy loop indices
+
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zhinit, zhi
+     !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_co3')
+
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) WRITE(numsed,*) ' sed_co3 : carbonate ion and proton concentration calculation  '
+         IF (lwp) WRITE(numsed,*) ' '
+      ENDIF
+
+      DO jk = 1, jpksed
+         zhinit(:,jk)   = hipor(:,jk) / densSW(:)
+      END DO
+
+      !     -------------------------------------------
+      !     COMPUTE [CO3--] and [H+] CONCENTRATIONS
+      !     -------------------------------------------
+
+      CALL solve_at_general_sed(zhinit, zhi)
+
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            co3por(ji,jk) = pwcp(ji,jk,jwdic) * ak1s(ji) * ak2s(ji) / (zhi(ji,jk)**2   &
+            &               + ak1s(ji) * zhi(ji,jk) + ak1s(ji) * ak2s(ji) + rtrn )
+            hipor(ji,jk)  = zhi(ji,jk) * densSW(ji)
+         END DO
+      END DO
+
+     IF( ln_timing )  CALL timing_stop('sed_co3')
+
+   END SUBROUTINE sed_co3
+
+END MODULE sedco3
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddiff.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddiff.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddiff.F90	(revision 14097)
@@ -0,0 +1,120 @@
+MODULE seddiff
+   !!======================================================================
+   !!              ***  MODULE  seddsr  ***
+   !!    Sediment : dissolution and reaction in pore water related 
+   !!    related to organic matter
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedmat  ! linear system of equations
+   USE sedini
+   USE lib_mpp         ! distribued memory computing library
+   USE lib_fortran
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_diff
+
+   !! * Module variables
+
+   !! $Id$
+CONTAINS
+   
+   SUBROUTINE sed_diff( kt, knt ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_diff  ***
+      !! 
+      !!  ** Purpose :  computes pore water diffusion
+      !!
+      !!  ** Methode :  implicit computation of undersaturation
+      !!               resulting from diffusive pore water transport.
+      !!
+      !!  ** Remarks :
+      !!              - undersaturation : deviation from saturation concentration
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) f90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!        !  19-08 (O. Aumont) Debugging and improvement of the model
+      !!----------------------------------------------------------------------
+      !! Arguments
+      INTEGER, INTENT(in) ::   kt, knt       ! number of iteration
+      ! --- local variables
+      INTEGER :: ji, jk, js   ! dummy looop indices
+
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zrearat1, zrearat2   ! reaction rate in pore water
+      !!
+      !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_diff')
+!
+      IF( kt == nitsed000 .AND. knt == 1 ) THEN
+         IF (lwp) THEN
+            WRITE(numsed,*) ' sed_diff : pore-water diffusion '
+            WRITE(numsed,*) ' '
+         ENDIF
+      ENDIF
+
+     ! Initializations
+     !----------------------
+      zrearat1(:,:)   = 0.
+      zrearat2(:,:) = 0.
+
+      !---------------------------
+      ! Solves PO4 diffusion 
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwpo4, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwpo4), dtsed2 / 2.0 )
+
+      !---------------------------
+      ! Solves NH4 diffusion 
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwnh4, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwnh4), dtsed2 / 2.0 )
+
+      !---------------------------
+      ! Solves Fe2+ diffusion 
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwfe2, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwfe2), dtsed2 / 2.0 )
+
+      !---------------------------
+      ! Solves H2S diffusion 
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwh2s, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwh2s), dtsed2 / 2.0  )
+
+      !---------------------------
+      ! Solves SO4 diffusion 
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwso4, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwso4), dtsed2 / 2.0 )
+
+      !---------------------------
+      ! Solves O2 diffusion
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwoxy, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwoxy), dtsed2 / 2.0 )
+
+      !---------------------------
+      ! Solves NO3 diffusion
+      !----------------------------
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwno3, jpoce, jpksed, zrearat1, zrearat2, pwcp(:,:,jwno3), dtsed2 / 2.0 )
+
+      CALL sed_mat( jwdic, jpoce, jpksed, zrearat1, zrearat2, sedligand(:,:), dtsed2 / 2.0 )
+
+      IF( ln_timing )  CALL timing_stop('sed_diff')
+!      
+   END SUBROUTINE sed_diff
+
+END MODULE seddiff
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddsr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddsr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddsr.F90	(revision 14097)
@@ -0,0 +1,749 @@
+MODULE seddsr
+   !!======================================================================
+   !!              ***  MODULE  seddsr  ***
+   !!    Sediment : dissolution and reaction in pore water related 
+   !!    related to organic matter
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedini
+   USE lib_mpp         ! distribued memory computing library
+   USE lib_fortran
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_dsr
+
+   !! * Module variables
+
+   REAL(wp) :: zadsnh4
+   REAL(wp), DIMENSION(jpsol), PUBLIC      :: dens_mol_wgt  ! molecular density 
+   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: zvolc    ! temp. variables
+
+
+   !! $Id$
+CONTAINS
+   
+   SUBROUTINE sed_dsr( kt, knt ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_dsr  ***
+      !! 
+      !!  ** Purpose :  computes pore water dissolution and reaction
+      !!
+      !!  ** Methode :  Computation of the redox reactions in sediment.
+      !!                The main redox reactions are solved in sed_dsr whereas
+      !!                the secondary reactions are solved in sed_dsr_redoxb.
+      !!                A strand spliting approach is being used here (see 
+      !!                sed_dsr_redoxb for more information). 
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) f90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!        !  19-08 (O. Aumont) Debugging and improvement of the model.
+      !!                             The original method is replaced by a 
+      !!                              Strand splitting method which deals 
+      !!                              well with stiff reactions.
+      !!----------------------------------------------------------------------
+      !! Arguments
+      INTEGER, INTENT(in) ::   kt, knt       ! number of iteration
+      ! --- local variables
+      INTEGER :: ji, jk, js, jw, jn   ! dummy looop indices
+
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zrearat1, zrearat2, zrearat3    ! reaction rate in pore water
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zundsat    ! undersaturation ; indice jpwatp1 is for calcite   
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zkpoc, zkpos, zkpor, zlimo2, zlimno3, zlimso4, zlimfeo    ! undersaturation ; indice jpwatp1 is for calcite   
+      REAL(wp), DIMENSION(jpoce)        :: zsumtot
+      REAL(wp)  ::  zsolid1, zsolid2, zsolid3, zvolw, zreasat
+      REAL(wp)  ::  zsatur, zsatur2, znusil, zkpoca, zkpocb, zkpocc
+      REAL(wp)  ::  zratio, zgamma, zbeta, zlimtmp, zundsat2
+      !!
+      !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_dsr')
+!
+      IF( kt == nitsed000 .AND. knt == 1 ) THEN
+         IF (lwp) THEN
+            WRITE(numsed,*) ' sed_dsr : Dissolution reaction '
+            WRITE(numsed,*) ' '
+         ENDIF
+      ENDIF
+
+     ! Initializations
+     !----------------------
+      
+      zrearat1(:,:)   = 0.    ;   zundsat(:,:) = 0. ; zkpoc(:,:) = 0.
+      zlimo2 (:,:)    = 0.    ;   zlimno3(:,:) = 0. ; zrearat2(:,:) = 0.
+      zlimso4(:,:)    = 0.    ;   zkpor(:,:)   = 0. ; zrearat3(:,:) = 0.
+      zkpos  (:,:)    = 0.
+      zsumtot(:)      = rtrn
+  
+      ALLOCATE( zvolc(jpoce, jpksed, jpsol) )
+      zvolc(:,:,:)    = 0.
+      zadsnh4 = 1.0 / ( 1.0 + adsnh4 )
+
+      ! Inhibition terms for the different redox equations
+      ! --------------------------------------------------
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zkpoc(ji,jk) = reac_pocl 
+            zkpos(ji,jk) = reac_pocs
+            zkpor(ji,jk) = reac_pocr
+         END DO
+      END DO
+
+      ! Conversion of volume units
+      !----------------------------
+      DO js = 1, jpsol
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce
+               zvolc(ji,jk,js) = ( vols3d(ji,jk) * dens_mol_wgt(js) ) /  &
+                  &              ( volw3d(ji,jk) * 1.e-3 )
+            ENDDO
+         ENDDO
+      ENDDO
+
+      !----------------------------------------------------------
+      ! 5.  Beginning of solid reaction
+      !---------------------------------------------------------
+      
+      ! Definition of reaction rates [rearat]=sans dim 
+      ! For jk=1 no reaction (pure water without solid) for each solid compo
+      zrearat1(:,:) = 0.
+      zrearat2(:,:) = 0.
+      zrearat3(:,:) = 0.
+
+      zundsat(:,:) = pwcp(:,:,jwoxy)
+
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zlimo2(ji,jk) = 1.0 / ( zundsat(ji,jk) + xksedo2 )
+            zsolid1 = zvolc(ji,jk,jspoc)  * solcp(ji,jk,jspoc)
+            zsolid2 = zvolc(ji,jk,jspos)  * solcp(ji,jk,jspos)
+            zsolid3 = zvolc(ji,jk,jspor)  * solcp(ji,jk,jspor)
+            zkpoca  = zkpoc(ji,jk) * zlimo2(ji,jk)
+            zkpocb  = zkpos(ji,jk) * zlimo2(ji,jk)
+            zkpocc  = zkpor(ji,jk) * zlimo2(ji,jk)
+            zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+            &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+            zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+            &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+            zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+            &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+         ENDDO
+      ENDDO
+
+      ! left hand side of coefficient matrix
+!      DO jn = 1, 5
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+jflag1:     DO jn = 1, 10
+               zsolid1 = zvolc(ji,jk,jspoc)  * solcp(ji,jk,jspoc)
+               zsolid2 = zvolc(ji,jk,jspos)  * solcp(ji,jk,jspos)
+               zsolid3 = zvolc(ji,jk,jspor)  * solcp(ji,jk,jspor)
+               zbeta   = xksedo2 - pwcp(ji,jk,jwoxy) + so2ut * ( zrearat1(ji,jk)    &
+               &         + zrearat2(ji,jk) + zrearat3(ji,jk) )
+               zgamma = - xksedo2 * pwcp(ji,jk,jwoxy)
+               zundsat2 = zundsat(ji,jk)
+               zundsat(ji,jk) = ( - zbeta + SQRT( zbeta**2 - 4.0 * zgamma ) ) / 2.0
+               zlimo2(ji,jk) = 1.0 / ( zundsat(ji,jk) + xksedo2 )
+               zkpoca  = zkpoc(ji,jk) * zlimo2(ji,jk)
+               zkpocb  = zkpos(ji,jk) * zlimo2(ji,jk)
+               zkpocc  = zkpor(ji,jk) * zlimo2(ji,jk)
+               zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+               &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+               zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+               &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+               zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+               &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+               IF ( ABS( (zundsat(ji,jk)-zundsat2)/(zundsat2+rtrn)) < 1E-8 ) THEN
+                  EXIT jflag1
+               ENDIF
+            END DO jflag1
+         END DO
+      END DO
+
+      ! New solid concentration values (jk=2 to jksed) for each couple 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zlimo2(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspoc)
+            solcp(ji,jk,jspoc) = solcp(ji,jk,jspoc) - zreasat
+            zreasat = zrearat2(ji,jk) * zlimo2(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspos)
+            solcp(ji,jk,jspos) = solcp(ji,jk,jspos) - zreasat
+            zreasat = zrearat3(ji,jk) * zlimo2(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspor)
+            solcp(ji,jk,jspor) = solcp(ji,jk,jspor) - zreasat
+         ENDDO
+      ENDDO
+
+      ! New pore water concentrations    
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            ! Acid Silicic 
+            pwcp(ji,jk,jwoxy)  = zundsat(ji,jk)
+            zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) * zlimo2(ji,jk) * zundsat(ji,jk)    ! oxygen         
+            ! For DIC
+            pwcp(ji,jk,jwdic)  = pwcp(ji,jk,jwdic) + zreasat
+            zsumtot(ji) = zsumtot(ji) + zreasat / dtsed2 * volw3d(ji,jk) * 1.e-3 * 86400. * 365. * 1E3
+            ! For Phosphate (in mol/l)
+            pwcp(ji,jk,jwpo4)  = pwcp(ji,jk,jwpo4) + zreasat * spo4r
+            ! For iron (in mol/l)
+            pwcp(ji,jk,jwfe2)  = pwcp(ji,jk,jwfe2) + fecratio(ji) * zreasat
+            ! For alkalinity
+            pwcp(ji,jk,jwalk)  = pwcp(ji,jk,jwalk) + zreasat * ( srno3 * zadsnh4 - 2.* spo4r )
+            ! Ammonium
+            pwcp(ji,jk,jwnh4)  = pwcp(ji,jk,jwnh4) + zreasat * srno3 * zadsnh4
+            ! Ligands
+            sedligand(ji,jk)   = sedligand(ji,jk) + ratligc * zreasat - reac_ligc * sedligand(ji,jk)
+         ENDDO
+      ENDDO
+
+      !--------------------------------------------------------------------
+      ! Begining POC denitrification and NO3- diffusion
+      ! (indice n°5 for couple POC/NO3- ie solcp(:,:,jspoc)/pwcp(:,:,jwno3))
+      !--------------------------------------------------------------------
+
+      zrearat1(:,:) = 0.
+      zrearat2(:,:) = 0.
+      zrearat3(:,:) = 0.
+
+      zundsat(:,:) = pwcp(:,:,jwno3)
+
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zlimno3(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) / ( zundsat(ji,jk) + xksedno3 )
+            zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+            zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+            zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+            zkpoca = zkpoc(ji,jk) * zlimno3(ji,jk)
+            zkpocb = zkpos(ji,jk) * zlimno3(ji,jk)
+            zkpocc = zkpor(ji,jk) * zlimno3(ji,jk)
+            zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+            &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+            zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+            &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+            zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+            &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+        END DO
+      END DO
+
+!      DO jn = 1, 5
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+jflag2:    DO jn = 1, 10
+               zlimtmp = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) )
+               zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+               zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+               zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+               zbeta   = xksedno3 - pwcp(ji,jk,jwno3) + srDnit * ( zrearat1(ji,jk)    &
+               &         + zrearat2(ji,jk) + zrearat3(ji,jk) ) * zlimtmp
+               zgamma = - xksedno3 * pwcp(ji,jk,jwno3)
+               zundsat2 = zundsat(ji,jk)
+               zundsat(ji,jk) = ( - zbeta + SQRT( zbeta**2 - 4.0 * zgamma ) ) / 2.0
+               zlimno3(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) / ( zundsat(ji,jk) + xksedno3 )
+               zkpoca  = zkpoc(ji,jk) * zlimno3(ji,jk)
+               zkpocb  = zkpos(ji,jk) * zlimno3(ji,jk)
+               zkpocc  = zkpor(ji,jk) * zlimno3(ji,jk)
+               zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+               &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+               zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+               &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+               zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+               &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+               IF ( ABS( (zundsat(ji,jk)-zundsat2)/(zundsat2+rtrn)) < 1E-8 ) THEN
+                  EXIT jflag2
+               ENDIF
+            END DO jflag2
+         END DO
+      END DO
+
+
+      ! New solid concentration values (jk=2 to jksed) for each couple 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zlimno3(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspoc)
+            solcp(ji,jk,jspoc) = solcp(ji,jk,jspoc) - zreasat
+            zreasat = zrearat2(ji,jk) * zlimno3(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspos)
+            solcp(ji,jk,jspos) = solcp(ji,jk,jspos) - zreasat
+            zreasat = zrearat3(ji,jk) * zlimno3(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspor)
+            solcp(ji,jk,jspor) = solcp(ji,jk,jspor) - zreasat
+         ENDDO
+      ENDDO
+
+      ! New dissolved concentrations
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            ! For nitrates
+            pwcp(ji,jk,jwno3)  =  zundsat(ji,jk)
+            zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) * zlimno3(ji,jk) * zundsat(ji,jk)
+            ! For DIC
+            pwcp(ji,jk,jwdic)  = pwcp(ji,jk,jwdic) + zreasat
+            zsumtot(ji) = zsumtot(ji) + zreasat / dtsed2 * volw3d(ji,jk) * 1.e-3 * 86400. * 365. * 1E3
+            ! For Phosphate (in mol/l)
+            pwcp(ji,jk,jwpo4)  = pwcp(ji,jk,jwpo4) + zreasat * spo4r            
+            ! Ligands
+            sedligand(ji,jk)   = sedligand(ji,jk) + ratligc * zreasat
+            ! For iron (in mol/l)
+            pwcp(ji,jk,jwfe2)  = pwcp(ji,jk,jwfe2) + fecratio(ji) * zreasat
+            ! For alkalinity
+            pwcp(ji,jk,jwalk)  = pwcp(ji,jk,jwalk) + zreasat * ( srDnit + srno3 * zadsnh4 - 2.* spo4r )           
+            ! Ammonium
+            pwcp(ji,jk,jwnh4)  = pwcp(ji,jk,jwnh4) + zreasat * srno3 * zadsnh4
+         ENDDO
+      ENDDO
+
+      !--------------------------------------------------------------------
+      ! Begining POC iron reduction
+      ! (indice nï¿½5 for couple POFe(OH)3 ie solcp(:,:,jspoc)/pwcp(:,:,jsfeo))
+      !--------------------------------------------------------------------
+
+      zrearat1(:,:) = 0.
+      zrearat2(:,:) = 0.
+      zrearat3(:,:) = 0.
+
+      zundsat(:,:) = solcp(:,:,jsfeo)
+
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zlimfeo(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+            &                / ( pwcp(ji,jk,jwno3) + xksedno3 ) ) / ( zundsat(ji,jk) + xksedfeo )
+            zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+            zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+            zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+            zkpoca = zkpoc(ji,jk) * zlimfeo(ji,jk)
+            zkpocb = zkpos(ji,jk) * zlimfeo(ji,jk)
+            zkpocc = zkpor(ji,jk) * zlimfeo(ji,jk)
+            zrearat1(ji,jk) = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+            &                    ( 1. + zkpoca * zundsat(ji,jk) * dtsed2 )
+            zrearat2(ji,jk) = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+            &                    ( 1. + zkpocb * zundsat(ji,jk) * dtsed2 )
+            zrearat3(ji,jk) = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+            &                    ( 1. + zkpocc * zundsat(ji,jk) * dtsed2 )
+         END DO
+      END DO
+
+!      DO jn = 1, 5
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+jflag3:     DO jn = 1, 10
+               zlimtmp = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+               &                / ( pwcp(ji,jk,jwno3) + xksedno3 ) )
+               zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+               zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+               zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+               zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) / zvolc(ji,jk,jsfeo)
+               zbeta   = xksedfeo - solcp(ji,jk,jsfeo) + 4.0 * zreasat * zlimtmp
+               zgamma  = -xksedfeo * solcp(ji,jk,jsfeo)
+               zundsat2 = zundsat(ji,jk)
+               zundsat(ji,jk) = ( - zbeta + SQRT( zbeta**2 - 4.0 * zgamma ) ) / 2.0
+               zlimfeo(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+               &                / ( pwcp(ji,jk,jwno3) + xksedno3 ) ) / ( zundsat(ji,jk) + xksedfeo )
+               zkpoca  = zkpoc(ji,jk) * zlimfeo(ji,jk)
+               zkpocb  = zkpos(ji,jk) * zlimfeo(ji,jk)
+               zkpocc  = zkpor(ji,jk) * zlimfeo(ji,jk)
+               zrearat1(ji,jk) = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+               &                    ( 1. + zkpoca * zundsat(ji,jk) * dtsed2 )
+               zrearat2(ji,jk) = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+               &                    ( 1. + zkpocb * zundsat(ji,jk) * dtsed2 )
+               zrearat3(ji,jk) = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+               &                    ( 1. + zkpocc * zundsat(ji,jk) * dtsed2 )
+               IF ( ABS( (zundsat(ji,jk)-zundsat2)/( MAX(0.,zundsat2)+rtrn)) < 1E-8 ) THEN
+                  EXIT jflag3
+               ENDIF
+            END DO jflag3
+         END DO
+      END DO
+
+
+         ! New solid concentration values (jk=2 to jksed) for each couple 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zlimfeo(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspoc)
+            solcp(ji,jk,jspoc) = solcp(ji,jk,jspoc) - zreasat
+            zreasat = zrearat2(ji,jk) * zlimfeo(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspos)
+            solcp(ji,jk,jspos) = solcp(ji,jk,jspos) - zreasat
+            zreasat = zrearat3(ji,jk) * zlimfeo(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspor)
+            solcp(ji,jk,jspor) = solcp(ji,jk,jspor) - zreasat
+         END DO
+      END DO
+
+      ! New dissolved concentrations
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) * zlimfeo(ji,jk) * zundsat(ji,jk)
+            ! For FEOH
+            solcp(ji,jk,jsfeo) = zundsat(ji,jk)
+            ! For DIC
+            pwcp(ji,jk,jwdic)  = pwcp(ji,jk,jwdic) + zreasat
+            zsumtot(ji) = zsumtot(ji) + zreasat / dtsed2 * volw3d(ji,jk) * 1.e-3 * 86400. * 365. * 1E3
+            ! For Phosphate (in mol/l)
+            pwcp(ji,jk,jwpo4)  = pwcp(ji,jk,jwpo4) + zreasat * ( spo4r + 4.0 * redfep )
+            ! Ligands
+            sedligand(ji,jk)   = sedligand(ji,jk) + ratligc * zreasat
+            ! For iron (in mol/l)
+            pwcp(ji,jk,jwfe2)  = pwcp(ji,jk,jwfe2) + fecratio(ji) * zreasat
+            ! For alkalinity
+            pwcp(ji,jk,jwalk)  = pwcp(ji,jk,jwalk) + zreasat * ( srno3 * zadsnh4 - 2.* spo4r ) + 8.0 * zreasat
+            ! Ammonium
+            pwcp(ji,jk,jwnh4)  = pwcp(ji,jk,jwnh4) + zreasat * srno3 * zadsnh4
+            pwcp(ji,jk,jwfe2)  = pwcp(ji,jk,jwfe2) + zreasat * 4.0
+         ENDDO
+      ENDDO
+
+      !--------------------------------------------------------------------
+      ! Begining POC denitrification and NO3- diffusion
+      ! (indice nï¿½5 for couple POC/NO3- ie solcp(:,:,jspoc)/pwcp(:,:,jwno3))
+      !--------------------------------------------------------------------
+
+      zrearat1(:,:) = 0.
+      zrearat2(:,:) = 0.
+      zrearat3(:,:) = 0.
+
+      zundsat(:,:) = pwcp(:,:,jwso4)
+
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zlimso4(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+            &                / ( pwcp(ji,jk,jwno3) + xksedno3 ) ) * ( 1. - solcp(ji,jk,jsfeo)  &
+            &                / ( solcp(ji,jk,jsfeo) + xksedfeo ) ) / ( zundsat(ji,jk) + xksedso4 )
+            zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+            zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+            zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+            zkpoca = zkpoc(ji,jk) * zlimso4(ji,jk)
+            zkpocb = zkpos(ji,jk) * zlimso4(ji,jk)
+            zkpocc = zkpor(ji,jk) * zlimso4(ji,jk)
+            zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+            &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+            zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+            &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+            zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+            &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+        END DO
+      END DO
+!
+!      DO jn = 1, 5 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+jflag4:     DO jn = 1, 10
+               zlimtmp = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+               &         / ( pwcp(ji,jk,jwno3) + xksedno3 ) ) * ( 1. - solcp(ji,jk,jsfeo)  &
+               &         / ( solcp(ji,jk,jsfeo) + xksedfeo ) ) 
+               zsolid1 = zvolc(ji,jk,jspoc) * solcp(ji,jk,jspoc)
+               zsolid2 = zvolc(ji,jk,jspos) * solcp(ji,jk,jspos)
+               zsolid3 = zvolc(ji,jk,jspor) * solcp(ji,jk,jspor)
+               zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) 
+               zbeta   = xksedso4 - pwcp(ji,jk,jwso4) + 0.5 * zreasat * zlimtmp
+               zgamma = - xksedso4 * pwcp(ji,jk,jwso4)
+               zundsat2 = zundsat(ji,jk)
+               zundsat(ji,jk) = ( - zbeta + SQRT( zbeta**2 - 4.0 * zgamma ) ) / 2.0
+               zlimso4(ji,jk) = ( 1.0 - pwcp(ji,jk,jwoxy) * zlimo2(ji,jk) ) * ( 1.0 - pwcp(ji,jk,jwno3)    &
+               &                / ( pwcp(ji,jk,jwno3) + xksedno3 ) ) * ( 1. - solcp(ji,jk,jsfeo)  &
+               &                / ( solcp(ji,jk,jsfeo) + xksedfeo ) ) / ( zundsat(ji,jk) + xksedso4 )
+               zkpoca  = zkpoc(ji,jk) * zlimso4(ji,jk)
+               zkpocb  = zkpos(ji,jk) * zlimso4(ji,jk)
+               zkpocc  = zkpor(ji,jk) * zlimso4(ji,jk)
+               zrearat1(ji,jk)  = ( zkpoc(ji,jk) * dtsed2 * zsolid1 ) / &
+               &                 ( 1. + zkpoca * zundsat(ji,jk ) * dtsed2 )
+               zrearat2(ji,jk)  = ( zkpos(ji,jk) * dtsed2 * zsolid2 ) / &
+               &                 ( 1. + zkpocb * zundsat(ji,jk ) * dtsed2 )
+               zrearat3(ji,jk)  = ( zkpor(ji,jk) * dtsed2 * zsolid3 ) / &
+               &                 ( 1. + zkpocc * zundsat(ji,jk ) * dtsed2 )
+               IF ( ABS( (zundsat(ji,jk)-zundsat2)/(zundsat2+rtrn)) < 1E-8 ) THEN
+                  EXIT jflag4
+               ENDIF
+            END DO jflag4
+         END DO
+      END DO
+
+     ! New solid concentration values (jk=2 to jksed) for each couple 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zlimso4(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspoc)
+            solcp(ji,jk,jspoc) = solcp(ji,jk,jspoc) - zreasat
+            zreasat = zrearat2(ji,jk) * zlimso4(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspos)
+            solcp(ji,jk,jspos) = solcp(ji,jk,jspos) - zreasat
+            zreasat = zrearat3(ji,jk) * zlimso4(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jspor)
+            solcp(ji,jk,jspor) = solcp(ji,jk,jspor) - zreasat
+         ENDDO
+      ENDDO
+!
+      ! New dissolved concentrations
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            ! For sulfur
+            pwcp(ji,jk,jwh2s)  = pwcp(ji,jk,jwh2s) - ( zundsat(ji,jk) - pwcp(ji,jk,jwso4) ) 
+            pwcp(ji,jk,jwso4)  =  zundsat(ji,jk)
+            zreasat = ( zrearat1(ji,jk) + zrearat2(ji,jk) + zrearat3(ji,jk) ) * zlimso4(ji,jk) * zundsat(ji,jk)
+            ! For DIC
+            pwcp(ji,jk,jwdic)  = pwcp(ji,jk,jwdic) + zreasat
+            zsumtot(ji) = zsumtot(ji) + zreasat / dtsed2 * volw3d(ji,jk) * 1.e-3 * 86400. * 365. * 1E3
+            ! For Phosphate (in mol/l)
+            pwcp(ji,jk,jwpo4)  = pwcp(ji,jk,jwpo4) + zreasat * spo4r
+            ! Ligands
+            sedligand(ji,jk)   = sedligand(ji,jk) + ratligc * zreasat
+            ! For iron (in mol/l)
+            pwcp(ji,jk,jwfe2)  = pwcp(ji,jk,jwfe2) + fecratio(ji) * zreasat
+            ! For alkalinity
+            pwcp(ji,jk,jwalk)  = pwcp(ji,jk,jwalk) + zreasat * ( srno3 * zadsnh4 - 2.* spo4r ) + zreasat
+            ! Ammonium
+            pwcp(ji,jk,jwnh4)  = pwcp(ji,jk,jwnh4) + zreasat * srno3 * zadsnh4
+         ENDDO
+      ENDDO
+
+      ! Oxydation of the reduced products. Here only ammonium and ODU is accounted for
+      ! There are two options here: A simple time splitting scheme and a modified 
+     ! Patankar scheme
+      ! ------------------------------------------------------------------------------
+
+      call sed_dsr_redoxb
+
+      ! -------------------------------------------------------------- 
+      !    4/ Computation of the bioturbation coefficient
+      !       This parameterization is taken from Archer et al. (2002)
+      ! --------------------------------------------------------------
+
+      DO ji = 1, jpoce
+         db(ji,:) = dbiot * zsumtot(ji) * pwcp(ji,1,jwoxy) / (pwcp(ji,1,jwoxy) + 20.E-6)
+      END DO
+
+      ! ------------------------------------------------------
+      !    Vertical variations of the bioturbation coefficient
+      ! ------------------------------------------------------
+      IF (ln_btbz) THEN
+         DO ji = 1, jpoce
+            db(ji,:) = db(ji,:) * exp( -(profsedw(:) / dbtbzsc)**2 ) / (365.0 * 86400.0)
+         END DO
+      ELSE
+         DO jk = 1, jpksed
+            IF (profsedw(jk) > dbtbzsc) THEN
+                db(:,jk) = 0.0
+            ENDIF
+         END DO
+      ENDIF
+
+      IF (ln_irrig) THEN
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce
+               irrig(ji,jk) = ( 7.63752 - 7.4465 * exp( -0.89603 * zsumtot(ji) ) ) * pwcp(ji,1,jwoxy)  &
+               &             / (pwcp(ji,1,jwoxy) + 20.E-6) 
+               irrig(ji,jk) = irrig(ji,jk) * exp( -(profsedw(jk) / xirrzsc) )
+            END DO
+         END DO
+      ELSE
+         irrig(:,:) = 0.0
+      ENDIF
+
+      DEALLOCATE( zvolc )
+
+      IF( ln_timing )  CALL timing_stop('sed_dsr')
+!      
+   END SUBROUTINE sed_dsr
+
+   SUBROUTINE sed_dsr_redoxb
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_dsr_redox  ***
+      !! 
+      !!  ** Purpose :  computes secondary redox reactions
+      !!
+      !!  ** Methode :  It uses Strand splitter algorithm proposed by 
+      !!                Nguyen et al. (2009) and modified by Wang et al. (2018)
+      !!                Basically, each equation is solved analytically when 
+      !!                feasible, otherwise numerically at t+1/2. Then 
+      !!                the last equation is solved at t+1. The other equations
+      !!                are then solved at t+1 starting in the reverse order.
+      !!                Ideally, it's better to start from the fastest reaction
+      !!                to the slowest and then reverse the order to finish up
+      !!                with the fastest one. But random order works well also.
+      !!                The scheme is second order, positive and mass 
+      !!                conserving. It works well for stiff systems.
+      !! 
+      !!   History :
+      !!        !  18-08 (O. Aumont)  Original code
+      !!----------------------------------------------------------------------
+      !! Arguments
+      ! --- local variables
+      INTEGER   ::  ji, jk, jn   ! dummy looop indices
+
+      REAL, DIMENSION(6)  :: zsedtrn, zsedtra
+      REAL(wp)  ::  zalpha, zbeta, zgamma, zdelta, zepsi, zsedfer
+      !!
+      !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_dsr_redoxb')
+
+      DO ji = 1, jpoce
+         DO jk = 2, jpksed
+            zsedtrn(1)  = pwcp(ji,jk,jwoxy)
+            zsedtrn(2)  = MAX(0., pwcp(ji,jk,jwh2s) )
+            zsedtrn(3)  = pwcp(ji,jk,jwnh4)
+            zsedtrn(4)  = MAX(0., pwcp(ji,jk,jwfe2) - sedligand(ji,jk) )
+            zsedfer     = MIN(0., pwcp(ji,jk,jwfe2) - sedligand(ji,jk) )
+            zsedtrn(5)  = solcp(ji,jk,jsfeo) * zvolc(ji,jk,jsfeo)
+            zsedtrn(6)  = solcp(ji,jk,jsfes) * zvolc(ji,jk,jsfes)
+            zsedtra(:)  = zsedtrn(:) 
+
+            ! First pass of the scheme. At the end, it is 1st order 
+            ! -----------------------------------------------------
+            ! Fe + O2
+            zalpha = zsedtra(1) - 0.25 * zsedtra(4)
+            zbeta  = zsedtra(4) + zsedtra(5) 
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(4)
+            zdelta = pwcp(ji,jk,jwpo4) - redfep * zsedtra(4)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(4) = zsedtra(4) / ( 1.0 + zsedtra(4) * reac_fe2 * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(4) = ( zsedtra(4) * zalpha ) / ( 0.25 * zsedtra(4) * ( exp( reac_fe2 * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_fe2 * zalpha * dtsed2 / 2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 0.25 * zsedtra(4) 
+            zsedtra(5) = zbeta  - zsedtra(4)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(4)
+            pwcp(ji,jk,jwpo4) = zdelta + redfep * zsedtra(4)
+            ! H2S + O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(2)
+            zbeta  = pwcp(ji,jk,jwso4) + zsedtra(2)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(2)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(2) = zsedtra(2) / ( 1.0 + zsedtra(2) * reac_h2s * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(2) = ( zsedtra(2) * zalpha ) / ( 2.0 * zsedtra(2) * ( exp( reac_h2s * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_h2s * zalpha * dtsed2 / 2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(2)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(2)
+            pwcp(ji,jk,jwso4) = zbeta - zsedtra(2)
+            ! NH4 + O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(3)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(3)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(3) = zsedtra(3) / ( 1.0 + zsedtra(3) * reac_nh4 * zadsnh4 * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(3) = ( zsedtra(3) * zalpha ) / ( 2.0 * zsedtra(3) * ( exp( reac_nh4 * zadsnh4 * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_nh4 * zadsnh4 * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(3)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(3)
+            ! FeS - O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(6)
+            zbeta  = zsedtra(4) + zsedtra(6)
+            zgamma = pwcp(ji,jk,jwso4) + zsedtra(6)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(6) = zsedtra(6) / ( 1.0 + zsedtra(6) * reac_feso * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(6) = ( zsedtra(6) * zalpha ) / ( 2.0 * zsedtra(6) * ( exp( reac_feso * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_feso * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(6)
+            zsedtra(4) = zbeta  - zsedtra(6)
+            pwcp(ji,jk,jwso4) = zgamma - zsedtra(6)
+!            ! Fe - H2S
+            zalpha = zsedtra(2) - zsedtra(4)
+            zbeta  = zsedtra(4) + zsedtra(6)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(4)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(4) = zsedtra(4) / ( 1.0 + zsedtra(4) * reac_fes * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(4) = ( zsedtra(4) * zalpha ) / ( zsedtra(4) * ( exp( reac_fes * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_fes * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(2) = zalpha + zsedtra(4)
+            zsedtra(6) = zbeta  - zsedtra(4)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(4)
+            ! FEOH + H2S
+            zalpha = zsedtra(5) - 2.0 * zsedtra(2)
+            zbeta  = zsedtra(5) + zsedtra(4)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(4)
+            zdelta = pwcp(ji,jk,jwso4) + zsedtra(2)
+            zepsi  = pwcp(ji,jk,jwpo4) + redfep * zsedtra(5)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(2) = zsedtra(2) / ( 1.0 + zsedtra(2) * reac_feh2s * dtsed2 )
+            ELSE
+               zsedtra(2) = ( zsedtra(2) * zalpha ) / ( 2.0 * zsedtra(2) * ( exp( reac_feh2s * zalpha * dtsed2 ) - 1.0 )  &
+               &            + zalpha * exp( reac_feh2s * zalpha * dtsed2 ) )
+            ENDIF
+            zsedtra(5) = zalpha + 2.0 * zsedtra(2)
+            zsedtra(4) = zbeta  - zsedtra(5)
+            pwcp(ji,jk,jwso4) = zdelta - zsedtra(2)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(4)
+            pwcp(ji,jk,jwpo4) = zepsi - redfep * zsedtra(5)
+            ! Fe - H2S
+            zalpha = zsedtra(2) - zsedtra(4)
+            zbeta  = zsedtra(4) + zsedtra(6)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(4)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(4) = zsedtra(4) / ( 1.0 + zsedtra(4) * reac_fes * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(4) = ( zsedtra(4) * zalpha ) / ( zsedtra(4) * ( exp( reac_fes * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_fes * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(2) = zalpha + zsedtra(4)
+            zsedtra(6) = zbeta  - zsedtra(4)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(4)
+            ! FeS - O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(6)
+            zbeta  = zsedtra(4) + zsedtra(6)
+            zgamma = pwcp(ji,jk,jwso4) + zsedtra(6)
+            IF (zalpha == 0.) THEN
+               zsedtra(6) = zsedtra(6) / ( 1.0 + zsedtra(6) * reac_feso * dtsed2 / 2. )
+            ELSE
+               zsedtra(6) = ( zsedtra(6) * zalpha ) / ( 2.0 * zsedtra(6) * ( exp( reac_feso * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_feso * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(6)
+            zsedtra(4) = zbeta  - zsedtra(6)
+            pwcp(ji,jk,jwso4) = zgamma - zsedtra(6)
+            ! NH4 + O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(3)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(3)
+            IF (zalpha == 0.) THEN
+               zsedtra(3) = zsedtra(3) / ( 1.0 + zsedtra(3) * reac_nh4 * zadsnh4 * dtsed2 / 2.0) 
+            ELSE
+               zsedtra(3) = ( zsedtra(3) * zalpha ) / ( 2.0 * zsedtra(3) * ( exp( reac_nh4 * zadsnh4 * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_nh4 * zadsnh4 * zalpha * dtsed2 /2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(3)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(3)
+            ! H2S + O2
+            zalpha = zsedtra(1) - 2.0 * zsedtra(2)
+            zbeta  = pwcp(ji,jk,jwso4) + zsedtra(2)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(2)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(2) = zsedtra(2) / ( 1.0 + zsedtra(2) * reac_h2s * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(2) = ( zsedtra(2) * zalpha ) / ( 2.0 * zsedtra(2) * ( exp( reac_h2s * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_h2s * zalpha * dtsed2 / 2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 2.0 * zsedtra(2)
+            pwcp(ji,jk,jwso4) = zbeta - zsedtra(2)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(2)
+            ! Fe + O2
+            zalpha = zsedtra(1) - 0.25 * zsedtra(4)
+            zbeta  = zsedtra(4) + zsedtra(5)
+            zgamma = pwcp(ji,jk,jwalk) - 2.0 * zsedtra(4)
+            zdelta = pwcp(ji,jk,jwpo4) - redfep * zsedtra(4)
+            IF ( zalpha == 0. ) THEN
+               zsedtra(4) = zsedtra(4) / ( 1.0 + zsedtra(4) * reac_fe2 * dtsed2 / 2.0 )
+            ELSE
+               zsedtra(4) = ( zsedtra(4) * zalpha ) / ( 0.25 * zsedtra(4) * ( exp( reac_fe2 * zalpha * dtsed2 / 2. ) - 1.0 )  &
+               &            + zalpha * exp( reac_fe2 * zalpha * dtsed2 / 2. ) )
+            ENDIF
+            zsedtra(1) = zalpha + 0.25 * zsedtra(4)
+            zsedtra(5) = zbeta  - zsedtra(4)
+            pwcp(ji,jk,jwpo4) = zdelta + redfep * zsedtra(4)
+            pwcp(ji,jk,jwalk) = zgamma + 2.0 * zsedtra(4)
+            pwcp(ji,jk,jwoxy)  = zsedtra(1)
+            pwcp(ji,jk,jwh2s)  = zsedtra(2)
+            pwcp(ji,jk,jwnh4)  = zsedtra(3)
+            pwcp(ji,jk,jwfe2)  = zsedtra(4) + sedligand(ji,jk) + zsedfer
+            pwcp(ji,jk,jwno3)  = pwcp(ji,jk,jwno3)  + ( zsedtrn(3) - pwcp(ji,jk,jwnh4) )
+            solcp(ji,jk,jsfeo) = zsedtra(5) / zvolc(ji,jk,jsfeo)
+            solcp(ji,jk,jsfes) = zsedtra(6) / zvolc(ji,jk,jsfes)
+         END DO
+      END DO
+
+      IF( ln_timing )  CALL timing_stop('sed_dsr_redoxb')
+
+  END SUBROUTINE sed_dsr_redoxb
+
+END MODULE seddsr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddta.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddta.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/seddta.F90	(revision 14097)
@@ -0,0 +1,226 @@
+MODULE seddta
+   !!======================================================================
+   !!                     ***  MODULE  seddta  ***
+   !! Sediment data  :  read sediment input data from a file
+   !!=====================================================================
+
+   !! * Modules used
+   USE sed
+   USE sedarr
+   USE phycst, ONLY : rday
+   USE iom
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Routine accessibility
+   PUBLIC sed_dta   ! 
+
+   !! *  Module variables
+   REAL(wp) ::  rsecday  ! number of second per a day
+   REAL(wp) ::  conv2    ! [kg/m2/month]-->[g/cm2/s] ( 1 month has 30 days )
+
+   !! $Id$
+CONTAINS
+
+   !!---------------------------------------------------------------------------
+   !!   sed_dta  : read the NetCDF data file in online version using module iom
+   !!---------------------------------------------------------------------------
+
+   SUBROUTINE sed_dta( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_dta  ***
+      !!                    
+      !! ** Purpose :   Reads data from a netcdf file and 
+      !!                initialization of rain and pore water (k=1) components
+      !! 
+      !!
+      !!   History :
+      !!        !  04-10  (N. Emprin, M. Gehlen )  Original code
+      !!        !  06-04  (C. Ethe)  Re-organization ; Use of iom
+      !!----------------------------------------------------------------------
+
+      !! Arguments
+      INTEGER, INTENT(in) ::  kt    ! time-step
+
+      !! * Local declarations
+      INTEGER  ::  ji, jj, js, jw, ikt
+
+      REAL(wp), DIMENSION(jpoce) :: zdtap, zdtag
+      REAL(wp), DIMENSION(jpi,jpj) :: zwsbio4, zwsbio3
+      REAL(wp) :: zf0, zf1, zf2, zkapp, zratio, zdep
+
+      !----------------------------------------------------------------------
+
+      ! Initialization of sediment variable 
+      ! Spatial dimension is merged, and unity converted if needed
+      !-------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_dta')
+
+      IF (lwp) THEN
+         WRITE(numsed,*)
+         WRITE(numsed,*) ' sed_dta : Bottom layer fields'
+         WRITE(numsed,*) ' ~~~~~~'
+         WRITE(numsed,*) ' Data from SMS model'
+         WRITE(numsed,*)
+      ENDIF
+
+
+      ! open file
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) WRITE(numsed,*) ' sed_dta : Sediment fields'
+         dtsed = r2dttrc
+         rsecday = 60.* 60. * 24.
+!         conv2   = 1.0e+3 / ( 1.0e+4 * rsecday * 30. )
+         conv2 = 1.0e+3 /  1.0e+4 
+         rdtsed(2:jpksed) = dtsed / ( denssol * por1(2:jpksed) )
+      ENDIF
+
+      ! Initialization of temporaries arrays  
+      zdtap(:)    = 0. 
+      zdtag(:)    = 0.  
+
+      ! reading variables
+      IF (lwp) WRITE(numsed,*)
+      IF (lwp) WRITE(numsed,*) ' sed_dta : Bottom layer fields at time  kt = ', kt
+      ! reading variables
+      !
+      !    Sinking speeds of detritus is increased with depth as shown
+      !    by data and from the coagulation theory
+      !    -----------------------------------------------------------
+      IF (ln_sediment_offline) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikt = mbkt(ji,jj)
+               zwsbio4(ji,jj) = wsbio2 / rday
+               zwsbio3(ji,jj) = wsbio  / rday
+            END DO
+         END DO
+      ELSE
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikt = mbkt(ji,jj)
+               zdep = e3t_n(ji,jj,ikt) / r2dttrc
+               zwsbio4(ji,jj) = MIN( 0.99 * zdep, wsbio4(ji,jj,ikt) / rday )
+               zwsbio3(ji,jj) = MIN( 0.99 * zdep, wsbio3(ji,jj,ikt) / rday )
+            END DO
+         END DO
+      ENDIF
+
+      trc_data(:,:,:) = 0.
+      DO jj = 1,jpj
+         DO ji = 1, jpi
+            ikt = mbkt(ji,jj)
+            IF ( tmask(ji,jj,ikt) == 1 ) THEN
+               trc_data(ji,jj,1)   = trb(ji,jj,ikt,jpsil)
+               trc_data(ji,jj,2)   = trb(ji,jj,ikt,jpoxy)
+               trc_data(ji,jj,3)   = trb(ji,jj,ikt,jpdic)
+               trc_data(ji,jj,4)   = trb(ji,jj,ikt,jpno3) / 7.625
+               trc_data(ji,jj,5)   = trb(ji,jj,ikt,jppo4) / 122.
+               trc_data(ji,jj,6)   = trb(ji,jj,ikt,jptal)
+               trc_data(ji,jj,7)   = trb(ji,jj,ikt,jpnh4) / 7.625
+               trc_data(ji,jj,8)   = 0.0
+               trc_data(ji,jj,9)   = 28.0E-3
+               trc_data(ji,jj,10)  = trb(ji,jj,ikt,jpfer)
+               trc_data(ji,jj,11 ) = MIN(trb(ji,jj,ikt,jpgsi), 1E-4) * zwsbio4(ji,jj) * 1E3
+               trc_data(ji,jj,12 ) = MIN(trb(ji,jj,ikt,jppoc), 1E-4) * zwsbio3(ji,jj) * 1E3
+               trc_data(ji,jj,13 ) = MIN(trb(ji,jj,ikt,jpgoc), 1E-4) * zwsbio4(ji,jj) * 1E3
+               trc_data(ji,jj,14)  = MIN(trb(ji,jj,ikt,jpcal), 1E-4) * zwsbio4(ji,jj) * 1E3
+               trc_data(ji,jj,15)  = tsn(ji,jj,ikt,jp_tem)
+               trc_data(ji,jj,16)  = tsn(ji,jj,ikt,jp_sal)
+               trc_data(ji,jj,17 ) = ( trb(ji,jj,ikt,jpsfe) * zwsbio3(ji,jj) + trb(ji,jj,ikt,jpbfe)  &
+               &                     * zwsbio4(ji,jj)  ) * 1E3 / ( trc_data(ji,jj,12 ) + trc_data(ji,jj,13 ) + rtrn )
+               trc_data(ji,jj,17 ) = MIN(1E-3, trc_data(ji,jj,17 ) )
+            ENDIF
+         ENDDO
+      ENDDO
+
+      ! Pore water initial concentration [mol/l] in  k=1
+      !-------------------------------------------------
+      DO jw = 1, jpwat
+         CALL pack_arr ( jpoce,  pwcp_dta(1:jpoce,jw), trc_data(1:jpi,1:jpj,jw), iarroce(1:jpoce) )
+      END DO
+      !  Solid components : 
+      !-----------------------
+      !  Sinking fluxes for OPAL in mol.m-2.s-1 ; conversion in mol.cm-2.s-1
+      CALL pack_arr ( jpoce, rainrm_dta(1:jpoce,jsopal), trc_data(1:jpi,1:jpj,11), iarroce(1:jpoce) ) 
+      rainrm_dta(1:jpoce,jsopal) = rainrm_dta(1:jpoce,jsopal) * 1e-4
+      !  Sinking fluxes for POC in mol.m-2.s-1 ; conversion in mol.cm-2.s-1
+      CALL pack_arr ( jpoce, zdtap(1:jpoce), trc_data(1:jpi,1:jpj,12) , iarroce(1:jpoce) )      
+      CALL pack_arr ( jpoce, zdtag(1:jpoce), trc_data(1:jpi,1:jpj,13) , iarroce(1:jpoce) )
+      DO ji = 1, jpoce
+!        zkapp  = MIN( (1.0 - 0.02 ) * reac_poc, 3731.0 * max(100.0, zkbot(ji) )**(-1.011) / ( 365.0 * 24.0 * 3600.0 ) )
+!        zkapp   = MIN( 0.98 * reac_poc, 100.0 * max(100.0, zkbot(ji) )**(-0.6) / ( 365.0 * 24.0 * 3600.0 ) )
+!        zratio = ( ( 1.0 - 0.02 ) * reac_poc + 0.02 * reac_poc * 0. - zkapp) / ( ( 0.02 - 1.0 ) * reac_poc / 100. - 0.02 * reac_poc * 0. + zkapp )
+!        zf1    = ( 0.02 * (reac_poc - reac_poc * 0.) + zkapp - reac_poc ) / ( reac_poc / 100. - reac_poc )
+!        zf1    = MIN(0.98, MAX(0., zf1 ) )
+         zf1    = 0.48
+         zf0    = 1.0 - 0.02 - zf1
+         zf2    = 0.02
+         rainrm_dta(ji,jspoc) =   ( zdtap(ji) +  zdtag(ji) ) * 1e-4 * zf0
+         rainrm_dta(ji,jspos) =   ( zdtap(ji) +  zdtag(ji) ) * 1e-4 * zf1
+         rainrm_dta(ji,jspor) =   ( zdtap(ji) +  zdtag(ji) ) * 1e-4 * zf2
+      END DO
+      !  Sinking fluxes for Calcite in mol.m-2.s-1 ; conversion in mol.cm-2.s-1
+      CALL pack_arr ( jpoce,  rainrm_dta(1:jpoce,jscal), trc_data(1:jpi,1:jpj,14), iarroce(1:jpoce) )
+      rainrm_dta(1:jpoce,jscal) = rainrm_dta(1:jpoce,jscal) * 1e-4
+      ! vector temperature [°C] and salinity 
+      CALL pack_arr ( jpoce,  temp(1:jpoce), trc_data(1:jpi,1:jpj,15), iarroce(1:jpoce) )
+      CALL pack_arr ( jpoce,  salt(1:jpoce), trc_data(1:jpi,1:jpj,16), iarroce(1:jpoce) )
+      
+      ! Clay rain rate in [mol/(cm**2.s)] 
+      ! inputs data in [kg.m-2.sec-1] ---> 1e+3/(1e+4) [g.cm-2.s-1]   
+      ! divided after by molecular weight g.mol-1      
+      CALL pack_arr ( jpoce,  rainrm_dta(1:jpoce,jsclay), dust(1:jpi,1:jpj), iarroce(1:jpoce) )
+      rainrm_dta(1:jpoce,jsclay) = rainrm_dta(1:jpoce,jsclay) * conv2 / mol_wgt(jsclay)   &
+      &                            + wacc(1:jpoce) * por1(2) * denssol / mol_wgt(jsclay) / ( rsecday * 365.0 )
+      rainrm_dta(1:jpoce,jsclay) = rainrm_dta(1:jpoce,jsclay) * 0.965
+      rainrm_dta(1:jpoce,jsfeo)  = rainrm_dta(1:jpoce,jsclay) * mol_wgt(jsclay) / mol_wgt(jsfeo) * 0.035 / 0.965
+!    rainrm_dta(1:jpoce,jsclay) = 1.0E-4 * conv2 / mol_wgt(jsclay)
+
+      ! Iron monosulphide rain rates. Set to 0
+      rainrm_dta(1:jpoce,jsfes)  = 0. 
+
+      ! Fe/C ratio in sinking particles that fall to the sediments
+      CALL pack_arr ( jpoce,  fecratio(1:jpoce), trc_data(1:jpi,1:jpj,17), iarroce(1:jpoce) )
+
+      sedligand(:,1) = 1.E-9
+
+      ! sediment pore water at 1st layer (k=1)
+      DO jw = 1, jpwat
+         pwcp(1:jpoce,1,jw) = pwcp_dta(1:jpoce,jw)
+      ENDDO
+
+      !  rain
+      DO js = 1, jpsol
+         rainrm(1:jpoce,js) = rainrm_dta(1:jpoce,js)
+      ENDDO
+
+      ! Calculation of raintg of each sol. comp.: rainrm in [g/(cm**2.s)]
+      DO js = 1, jpsol
+         rainrg(1:jpoce,js) = rainrm(1:jpoce,js) *  mol_wgt(js)
+      ENDDO
+
+      ! Calculation of raintg = total massic flux rained in each cell (sum of sol. comp.)
+      raintg(:) = 0.
+      DO js = 1, jpsol
+         raintg(1:jpoce) = raintg(1:jpoce) + rainrg(1:jpoce,js)
+      ENDDO
+
+      ! computation of dzdep = total thickness of solid material rained [cm] in each cell
+      dzdep(1:jpoce) = raintg(1:jpoce) * rdtsed(2) 
+
+      IF( lk_iomput ) THEN
+          IF( iom_use("sflxclay" ) ) CALL iom_put( "sflxclay", dust(:,:) * conv2 * 1E4 )
+          IF( iom_use("sflxcal" ) )  CALL iom_put( "sflxcal", trc_data(:,:,13) )
+          IF( iom_use("sflxbsi" ) )  CALL iom_put( "sflxbsi", trc_data(:,:,10) )
+          IF( iom_use("sflxpoc" ) )  CALL iom_put( "sflxpoc", trc_data(:,:,11) + trc_data(:,:,12) )
+      ENDIF
+
+      IF( ln_timing )  CALL timing_stop('sed_dta')
+      
+   END SUBROUTINE sed_dta
+
+END MODULE seddta
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedini.F90	(revision 14097)
@@ -0,0 +1,693 @@
+MODULE sedini
+   !!======================================================================
+   !!              ***  MODULE  sedini  ***
+   !! Sediment : define sediment variables
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   sed_init    : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedarr
+   USE sedadv
+   USE trc_oce, ONLY : nn_dttrc
+   USE trcdmp_sed
+   USE trcdta
+   USE iom
+   USE lib_mpp         ! distribued memory computing library
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! Module variables
+   REAL(wp)    ::  &
+      sedzmin = 0.3    ,  &  !: Minimum vertical spacing
+      sedhmax = 10.0   ,  &  !: Maximum depth of the sediment
+      sedkth  = 5.0    ,  &  !: Default parameters
+      sedacr  = 3.0          !: Default parameters
+      
+   REAL(wp)    ::  &
+      porsurf =  0.95  ,  &  !: Porosity at the surface
+      porinf  =  0.75  ,  &  !: Porosity at infinite depth
+      rhox    =  2.0         !: Vertical length scale of porosity variation 
+
+   REAL(wp)    ::  &
+      rcopal  =   40.  ,  &  !: reactivity for si    [l.mol-1.an-1]
+      dcoef   =  8.e-6       !: diffusion coefficient (*por)   [cm**2/s]
+
+   REAL(wp), PUBLIC    ::  &
+      redO2    =  172.  ,  &  !: Redfield coef for Oxygen
+      redNo3   =   16.  ,  &  !: Redfield coef for Nitrate
+      redPo4   =    1.  ,  &  !: Redfield coef for Phosphate
+      redC     =  122.  ,  &  !: Redfield coef for Carbon
+      redfep   =  0.175 ,  &  !: Ratio for iron bound phosphorus
+      rcorgl   =   50.  ,  &  !: reactivity for POC/O2 [l.mol-1.an-1]    
+      rcorgs   =   0.5  ,  &  !: reactivity of the semi-labile component
+      rcorgr   =   1E-4 ,  &  !: reactivity of the refractory component
+      rcnh4    =   10E6 ,  &  !: reactivity for O2/NH4 [l.mol-1.an-1]  
+      rch2s    =   1.E5 ,  &  !: reactivity for O2/ODU [l.mol-1.an-1] 
+      rcfe2    =   5.E8 ,  &  !: reactivity for O2/Fe2+ [l.mol-1.an-1]
+      rcfeh2s  =   1.E4 ,  &  !: Reactivity for FEOH/H2S [l.mol-1.an-1]
+      rcfes    =   1.E5 ,  &  !: Reactivity for FE2+/H2S [l.mol-1.an-1]
+      rcfeso   =   3.E5 ,  &  !: Reactivity for FES/O2 [l.mol-1.an-1]
+      xksedo2  =   5E-6 ,  &  !: half-sturation constant for oxic remin.
+      xksedno3 =   5E-6 ,  &  !: half-saturation constant for denitrification
+      xksedfeo =   0.6  ,  & !: half-saturation constant for iron remin
+      xksedso4 =   2E-3       !: half-saturation constant for SO4 remin
+
+   REAL(wp)    ::  &
+      rccal   = 1000.,      & !: reactivity for calcite         [l.mol-1.an-1]
+      rcligc  = 1.E-4         !: L/C ratio in POC
+
+   REAL(wp), PUBLIC    ::  dbiot   = 15. , &  !: coefficient for bioturbation    [cm**2.(n-1)]
+      dbtbzsc =  10.0  ,    &  !: Vertical scale of variation. If no variation, mixed layer in the sed [cm]
+      xirrzsc = 2.0            !: Vertical scale of irrigation variation.
+   REAL(wp)    ::  &
+      ryear = 365. * 24. * 3600. !:  1 year converted in second
+
+   REAL(wp), DIMENSION(jpwat), PUBLIC  :: diff1
+   DATA diff1/4.59E-6, 1.104E-5, 4.81E-6 , 9.78E-6, 3.58E-6, 4.01E-6, 9.8E-6, 9.73E-6, 5.0E-6, 3.31E-6 /
+
+   REAL(wp), DIMENSION(jpwat), PUBLIC  :: diff2
+   DATA diff2/1.74E-7, 4.47E-7, 2.51E-7, 3.89E-7, 1.77E-7, 2.5E-7, 3.89E-7, 3.06E-7, 2.5E-7, 1.5E-7 /
+
+
+
+   !! *  Routine accessibility
+   PUBLIC sed_init          ! routine called by opa.F90
+
+   !! $Id$
+CONTAINS
+
+
+   SUBROUTINE sed_init
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_init  ***
+      !!
+      !! ** Purpose :  Initialization of sediment module
+      !!               - Reading namelist
+      !!               - Read the deepest water layer thickness
+      !!                 ( using as mask ) in Netcdf file
+      !!               - Convert unity if necessary
+      !!               - sets initial sediment composition
+      !!                 ( only clay or reading restart file )
+      !!               - sets sediment grid, porosity and others constants
+      !!
+      !!   History :
+      !!        !  04-10  (N. Emprin, M. Gehlen )  Original code
+      !!        !  06-07  (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      INTEGER :: ji, jj, ikt, ierr
+      !!----------------------------------------------------------------------
+
+
+      ! Reading namelist.sed variables
+      !---------------------------------------
+
+      CALL ctl_opn( numsed, 'sediment.output', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+
+      IF (lwp) THEN
+         WRITE(numsed,*)
+         WRITE(numsed,*) '                 PISCES framework'
+         WRITE(numsed,*) '                 SEDIMENT model'
+         WRITE(numsed,*) '                version 3.0  (2018) '
+         WRITE(numsed,*)
+         WRITE(numsed,*)
+      ENDIF
+
+      IF(lwp) WRITE(numsed,*) ' sed_init : Initialization of sediment module  '
+      IF(lwp) WRITE(numsed,*) ' '
+
+      ! Read sediment Namelist
+      !-------------------------
+      CALL sed_init_nam
+
+      ! Allocate SEDIMENT arrays
+      ierr =        sed_alloc()
+      ierr = ierr + sed_oce_alloc()
+      ierr = ierr + sed_adv_alloc() 
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'sed_ini: unable to allocate sediment model arrays' )
+
+      ! Determination of sediments number of points and allocate global variables
+      epkbot(:,:) = 0.
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ikt = mbkt(ji,jj) 
+            IF( tmask(ji,jj,ikt) == 1 ) epkbot(ji,jj) = e3t_1d(ikt)
+            gdepbot(ji,jj) = gdepw_0(ji,jj,ikt)
+         ENDDO
+      ENDDO
+
+      ! computation of total number of ocean points
+      !--------------------------------------------
+      sedmask = 0.
+      IF ( COUNT( epkbot(:,:) > 0. ) == 0 ) THEN 
+          sedmask = 0.
+      ELSE
+          sedmask = 1.
+      ENDIF 
+      jpoce  = MAX( COUNT( epkbot(:,:) > 0. ) , 1 )
+
+      ! Allocate memory size of global variables
+      ALLOCATE( pwcp (jpoce,jpksed,jpwat) )  ;  ALLOCATE( pwcp0 (jpoce,jpksed,jpwat) ) ;  ALLOCATE( pwcp_dta  (jpoce,jpwat) )
+      ALLOCATE( solcp(jpoce,jpksed,jpsol) )  ;  ALLOCATE( solcp0(jpoce,jpksed,jpsol) ) ;  ALLOCATE( rainrm_dta(jpoce,jpsol) )
+      ALLOCATE( rainrm(jpoce,jpsol) )        ;  ALLOCATE( rainrg(jpoce,jpsol) )        ;  ALLOCATE( raintg(jpoce) ) 
+      ALLOCATE( dzdep(jpoce) )               ;  ALLOCATE( iarroce(jpoce) )             ;  ALLOCATE( dzkbot(jpoce) )
+      ALLOCATE( zkbot(jpoce) )               ;  ALLOCATE( db(jpoce,jpksed) )
+      ALLOCATE( temp(jpoce) )                ;  ALLOCATE( salt(jpoce) )  
+      ALLOCATE( diff(jpoce,jpksed,jpwat ) )  ;  ALLOCATE( irrig(jpoce, jpksed) )
+      ALLOCATE( wacc(jpoce) )                ;  ALLOCATE( fecratio(jpoce) )
+      ALLOCATE( press(jpoce) )               ;  ALLOCATE( densSW(jpoce) ) 
+      ALLOCATE( hipor(jpoce,jpksed) )        ;  ALLOCATE( co3por(jpoce,jpksed) )
+      ALLOCATE( dz3d(jpoce,jpksed) )         ;  ALLOCATE( volw3d(jpoce,jpksed) )       ;  ALLOCATE( vols3d(jpoce,jpksed) )
+      ALLOCATE( sedligand(jpoce, jpksed) )
+
+      ! Initialization of global variables
+      pwcp  (:,:,:) = 0.   ;  pwcp0 (:,:,:) = 0.  ; pwcp_dta  (:,:) = 0.  
+      solcp (:,:,:) = 0.   ;  solcp0(:,:,:) = 0.  ; rainrm_dta(:,:) = 0.
+      rainrm(:,:  ) = 0.   ;  rainrg(:,:  ) = 0.  ; raintg    (:  ) = 0. 
+      dzdep (:    ) = 0.   ;  iarroce(:   ) = 0   ; dzkbot    (:  ) = 0.
+      temp  (:    ) = 0.   ;  salt   (:   ) = 0.  ; zkbot     (:  ) = 0.
+      press (:    ) = 0.   ;  densSW (:   ) = 0.  ; db        (:,:) = 0. 
+      hipor (:,:  ) = 0.   ;  co3por (:,: ) = 0.  ; irrig     (:,:) = 0. 
+      dz3d  (:,:  ) = 0.   ;  volw3d (:,: ) = 0.  ; vols3d    (:,:) = 0. 
+      fecratio(:)   = 1E-5 
+      sedligand(:,:) = 0.6E-9
+
+      ! Chemical variables      
+      ALLOCATE( akbs  (jpoce) )  ;  ALLOCATE( ak1s   (jpoce) )  ;  ALLOCATE( ak2s  (jpoce) ) ;  ALLOCATE( akws  (jpoce) )     
+      ALLOCATE( ak1ps (jpoce) )  ;  ALLOCATE( ak2ps  (jpoce) )  ;  ALLOCATE( ak3ps (jpoce) ) ;  ALLOCATE( aksis (jpoce) )    
+      ALLOCATE( aksps (jpoce) )  ;  ALLOCATE( ak12s  (jpoce) )  ;  ALLOCATE( ak12ps(jpoce) ) ;  ALLOCATE( ak123ps(jpoce) )    
+      ALLOCATE( borats(jpoce) )  ;  ALLOCATE( calcon2(jpoce) )  ;  ALLOCATE( sieqs (jpoce) ) 
+      ALLOCATE( aks3s(jpoce) )   ;  ALLOCATE( akf3s(jpoce) )    ;  ALLOCATE( sulfats(jpoce) )
+      ALLOCATE( fluorids(jpoce) )
+
+      akbs  (:) = 0. ;   ak1s   (:) = 0. ;  ak2s  (:) = 0. ;   akws   (:) = 0.
+      ak1ps (:) = 0. ;   ak2ps  (:) = 0. ;  ak3ps (:) = 0. ;   aksis  (:) = 0.
+      aksps (:) = 0. ;   ak12s  (:) = 0. ;  ak12ps(:) = 0. ;   ak123ps(:) = 0.
+      borats(:) = 0. ;   calcon2(:) = 0. ;  sieqs (:) = 0.
+      aks3s(:)  = 0. ;   akf3s(:)   = 0. ;  sulfats(:) = 0. ;  fluorids(:) = 0.
+
+      ! Mass balance calculation  
+      ALLOCATE( fromsed(jpoce, jpsol) ) ; ALLOCATE( tosed(jpoce, jpsol) ) ;  ALLOCATE( rloss(jpoce, jpsol) )
+      ALLOCATE( tokbot (jpoce, jpwat) ) 
+
+      fromsed(:,:) = 0.    ;   tosed(:,:) = 0. ;  rloss(:,:) = 0.  ;   tokbot(:,:) = 0. 
+
+      ! Initialization of sediment geometry
+      !------------------------------------
+      CALL sed_init_geom
+
+      ! Offline specific mode
+      ! ---------------------
+      ln_sediment_offline = .FALSE.
+
+#if defined key_sed_off
+      ln_sediment_offline = .TRUE.
+      IF (lwp) write(numsed,*) 'Sediment module is run in offline mode'
+      IF (lwp) write(numsed,*) 'key_sed_off is activated at compilation time'
+      IF (lwp) write(numsed,*) 'ln_sed_2way is forced to false'
+      IF (lwp) write(numsed,*) '--------------------------------------------'
+      ln_sed_2way = .FALSE.
+#endif
+      ! Initialisation of tracer damping
+      ! --------------------------------
+      IF (ln_sediment_offline) THEN
+         CALL trc_dta_ini(jptra)
+         CALL trc_dmp_sed_ini
+      ENDIF
+
+   END SUBROUTINE sed_init
+
+   SUBROUTINE sed_init_geom
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_init_geom  ***
+      !!
+      !! ** Purpose :  Initialization of sediment geometry
+      !!               - Read the deepest water layer thickness
+      !!                 ( using as mask ) in Netcdf file
+      !!               - sets sediment grid, porosity and molecular weight
+      !!                 and others constants
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  Original
+      !!----------------------------------------------------------------------
+      !! * Modules used
+      !! * local declarations
+      INTEGER  :: ji, jj, jk, jn
+      REAL(wp) :: za0, za1, zt, zw, zsum, zsur, zprof, zprofw
+      REAL(wp) :: ztmp1, ztmp2
+      !---------------------------------------------------------- 
+
+      IF(lwp) WRITE(numsed,*) ' sed_init_geom : Initialization of sediment geometry '
+      IF(lwp) WRITE(numsed,*) ' '
+
+      ! Computation of 1D array of sediments points
+      indoce = 0
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF (  epkbot(ji,jj) > 0. ) THEN
+               indoce          = indoce + 1
+               iarroce(indoce) = (jj - 1) * jpi + ji
+            ENDIF
+         END DO
+      END DO
+
+      IF ( indoce .EQ. 0 ) THEN
+         indoce = 1
+         iarroce(indoce) = 1
+      ENDIF
+
+      IF( indoce .NE. jpoce ) THEN
+         CALL ctl_stop( 'STOP', 'sed_ini: number of ocean points indoce doesn''t match  number of point' )
+      ELSE
+         IF (lwp) WRITE(numsed,*) ' '
+         IF (lwp) WRITE(numsed,*) ' total number of ocean points jpoce =  ',jpoce
+         IF (lwp) WRITE(numsed,*) ' '
+      ENDIF
+
+      ! initialization of dzkbot in [cm]
+      !------------------------------------------------    
+      CALL pack_arr ( jpoce, dzkbot(1:jpoce), epkbot(1:jpi,1:jpj), iarroce(1:jpoce) )
+      dzkbot(1:jpoce) = dzkbot(1:jpoce) * 1.e+2 
+      CALL pack_arr ( jpoce, zkbot(1:jpoce), gdepbot(1:jpi,1:jpj), iarroce(1:jpoce) )
+
+      ! Geometry and  constants 
+      ! sediment layer thickness [cm]
+      ! (1st layer= diffusive layer = pur water) 
+      !------------------------------------------
+      za1  = (  sedzmin - sedhmax / FLOAT(jpksed-1)  )                                                      &
+         & / ( TANH((1-sedkth)/sedacr) - sedacr/FLOAT(jpksed-1) * (  LOG( COSH( (jpksed - sedkth) / sedacr) )      &
+         &                                                   - LOG( COSH( ( 1  - sedkth) / sedacr) )  )  )
+      za0  = sedzmin - za1 * TANH( (1-sedkth) / sedacr )
+      zsur = - za0 - za1 * sedacr * LOG( COSH( (1-sedkth) / sedacr )  )
+
+      profsedw(1) = 0.0
+      profsed(1) = -dz(1) / 2.
+      DO jk = 2, jpksed
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) - 0.5_wp
+         profsed(jk)  = ( zsur + za0 * zt + za1 * sedacr * LOG ( COSH( (zt-sedkth) / sedacr ) )  ) 
+         profsedw(jk) = ( zsur + za0 * zw + za1 * sedacr * LOG ( COSH( (zw-sedkth) / sedacr ) )  )
+      END DO
+
+      dz(1) = 0.1
+      DO jk = 2, jpksed
+         dz(jk) = profsedw(jk) - profsedw(jk-1)
+      END DO
+
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            dz3d(ji,jk) = dz(jk)
+         END DO
+      ENDDO
+
+      !  Porosity profile [0]
+      !---------------------
+      por(1) = 1.0
+      DO jk = 2, jpksed
+         por(jk) = porinf + ( porsurf-porinf) * exp(-rhox * (profsed(jk) ) )
+      END DO
+ 
+      ! inverse of  Porosity profile
+      !-----------------------------
+      por1(:) = 1. - por(:)
+
+      ! Volumes of pore water and solid fractions (vector and array)
+      !     WARNING : volw(1) and vols(1) are sublayer volums
+      volw(:) = dz(:) * por(:)
+      vols(:) = dz(:) * por1(:)
+
+      ! temporary new value for dz3d(:,1) 
+      dz3d(1:jpoce,1) = dzkbot(1:jpoce)
+
+      ! WARNING : volw3d(:,1) and vols3d(:,1) are deepest water column volums
+      DO jk = 1, jpksed
+         volw3d(1:jpoce,jk) = dz3d(1:jpoce,jk) * por (jk)
+         vols3d(1:jpoce,jk) = dz3d(1:jpoce,jk) * por1(jk)
+      ENDDO
+
+      ! Back to the old sublayer vlaue for dz3d(:,1)
+      dz3d(1:jpoce,1) = dz(1)
+
+      !---------------------------------------------
+      ! Molecular weight [g/mol] for solid species
+      !---------------------------------------------
+
+      ! opal=sio2*0.4(h20)=28+2*16+0.4*(2+16)
+      !---------------------------------------
+      mol_wgt(jsopal) = 28. + 2. * 16. + 0.4 * ( 2. + 16. )  
+
+      !  clay
+      !  some kind of Illit (according to Pape)
+      !  K0.58(Al 1.38 Fe(III)0.37Fe(II)0.04Mg0.34)[(OH)2|(Si3.41Al0.59)O10]
+      !--------------------------------------------------------------------
+      mol_wgt(jsclay) = 0.58 * 39. + 1.38 * 27. + ( 0.37 + 0.04 ) * 56.+ &
+         &              0.34 * 24. + 2. * ( 16. + 1. ) + 3.41 * 38. +    &
+         &              0.59 * 27. + 10. * 16.
+
+      mol_wgt(jsfeo)  = 55.0 + 3.0 * ( 16.0 + 1.0)
+
+      mol_wgt(jsfes)  = 55.0 + 32.0
+
+      ! for chemistry Poc : C(122)H(244)O(86)N(16)P(1)
+      ! But den sity of Poc is an Hydrated material (= POC + 30H2O)
+      ! So C(122)H(355)O(120)N(16)P(1)
+      !------------------------------------------------------------
+      mol_wgt(jspoc) = ( 122. * 12. + 355. + 120. * 16.+ &
+         &                16. * 14. + 31. ) / 122.
+      mol_wgt(jspos) = mol_wgt(jspoc)
+      mol_wgt(jspor) = mol_wgt(jspoc)
+
+      ! CaCO3
+      !---------
+      mol_wgt(jscal) = 40. + 12. + 3. * 16.
+
+      ! Density of solid material in sediment [g/cm**3]
+      !------------------------------------------------
+      denssol = 2.6
+
+      ! Initialization of diffusion coefficient as function of porosity [cm**2/s]
+      !--------------------------------------------------------------------
+!      DO jn = 1, jpsol
+!         DO jk = 1, jpksed
+!            DO ji = 1, jpoce
+!               diff(ji,jk,jn) = dcoef / ( 1.0 - 2.0 * log(por(jk)) )
+!            END DO
+!         END DO
+!      END DO
+
+      ! Accumulation rate from Burwicz et al. (2011). This is used to
+      ! compute the flux of clays and minerals
+      ! --------------------------------------------------------------
+      DO ji = 1, jpoce
+          ztmp1 = 0.117 / ( 1.0 + ( zkbot(ji) / 200.)**3 )
+          ztmp2 = 0.006 / ( 1.0 + ( zkbot(ji) / 4000.)**10 )
+          wacc(ji) = ztmp1 + ztmp2
+      END DO
+
+
+      ! Initialization of time step as function of porosity [cm**2/s]
+      !------------------------------------------------------------------
+   END SUBROUTINE sed_init_geom
+
+   SUBROUTINE sed_init_nam
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_init_nam  ***
+      !!
+      !! ** Purpose :  Initialization of sediment geometry
+      !!               - Reading namelist and defines constants variables
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  Original
+      !!----------------------------------------------------------------------
+
+      INTEGER ::   numnamsed_ref = -1           !! Logical units for namelist sediment
+      INTEGER ::   numnamsed_cfg = -1           !! Logical units for namelist sediment
+      INTEGER :: ios                 ! Local integer output status for namelist read
+      CHARACTER(LEN=20)   ::   clname
+
+      TYPE PSED
+         CHARACTER(len = 20)  :: snamesed   !: short name
+         CHARACTER(len = 80 ) :: lnamesed   !: long name
+         CHARACTER(len = 20 ) :: unitsed    !: unit
+      END TYPE PSED
+
+      TYPE(PSED) , DIMENSION(jpsol     ) :: sedsol
+      TYPE(PSED) , DIMENSION(jpwat     ) :: sedwat
+      TYPE(PSED) , DIMENSION(jpdia3dsed) :: seddiag3d
+      TYPE(PSED) , DIMENSION(jpdia2dsed) :: seddiag2d
+
+      NAMELIST/nam_run/nrseddt,ln_sed_2way
+      NAMELIST/nam_geom/jpksed, sedzmin, sedhmax, sedkth, sedacr, porsurf, porinf, rhox
+      NAMELIST/nam_trased/sedsol, sedwat
+      NAMELIST/nam_diased/seddiag3d, seddiag2d
+      NAMELIST/nam_inorg/rcopal, dcoef, rccal, ratligc, rcligc
+      NAMELIST/nam_poc/redO2, redNo3, redPo4, redC, redfep, rcorgl, rcorgs,  &
+         &             rcorgr, rcnh4, rch2s, rcfe2, rcfeh2s, rcfes, rcfeso,  &
+         &             xksedo2, xksedno3, xksedfeo, xksedso4
+      NAMELIST/nam_btb/dbiot, ln_btbz, dbtbzsc, adsnh4, ln_irrig, xirrzsc
+      NAMELIST/nam_rst/ln_rst_sed, cn_sedrst_indir, cn_sedrst_outdir, cn_sedrst_in, cn_sedrst_out
+
+      INTEGER :: ji, jn, jn1
+      !-------------------------------------------------------
+
+      IF(lwp) WRITE(numsed,*) ' sed_init_nam : Read namelists '
+      IF(lwp) WRITE(numsed,*) ' '
+
+      ! ryear = 1 year converted in second
+      !------------------------------------
+      IF (lwp) THEN
+         WRITE(numsed,*) ' '
+         WRITE(numsed,*) 'number of seconds in one year : ryear = ', ryear
+         WRITE(numsed,*) ' '     
+      ENDIF
+
+      ! Reading namelist.sed variables
+      !---------------------------------
+      clname = 'namelist_sediment'
+      IF(lwp) WRITE(numsed,*) ' sed_init_nam : read SEDIMENT namelist'
+      IF(lwp) WRITE(numsed,*) ' ~~~~~~~~~~~~~~'
+      CALL ctl_opn( numnamsed_ref, TRIM( clname )//'_ref', 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnamsed_cfg, TRIM( clname )//'_cfg', 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+
+      nitsed000 = nittrc000
+      nitsedend = nitend
+      ! Namelist nam_run
+      REWIND( numnamsed_ref )              ! Namelist nam_run in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_run, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_run in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_run in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_run, IOSTAT = ios, ERR = 902)
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_run in configuration namelist' )
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_run'
+         WRITE(numsed,*) ' Nb of iterations for fast species    nrseddt = ', nrseddt
+         WRITE(numsed,*) ' 2-way coupling between PISCES and Sed ln_sed_2way = ', ln_sed_2way
+      ENDIF
+
+      IF ( ln_p5z .AND. ln_sed_2way ) CALL ctl_stop( '2 ways coupling with sediment cannot be activated with PISCES-QUOTA' )
+
+      REWIND( numnamsed_ref )              ! Namelist nam_geom in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_geom, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_geom in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_geom in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_geom, IOSTAT = ios, ERR = 904)
+904   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_geom in configuration namelist' )
+
+      IF (lwp) THEN 
+         WRITE(numsed,*) ' namelist nam_geom'
+         WRITE(numsed,*) ' Number of vertical layers            jpksed  = ', jpksed
+         WRITE(numsed,*) ' Minimum vertical spacing             sedzmin = ', sedzmin
+         WRITE(numsed,*) ' Maximum depth of the sediment        sedhmax = ', sedhmax
+         WRITE(numsed,*) ' Default parameter                    sedkth  = ', sedkth
+         WRITE(numsed,*) ' Default parameter                    sedacr  = ', sedacr
+         WRITE(numsed,*) ' Sediment porosity at the surface     porsurf = ', porsurf
+         WRITE(numsed,*) ' Sediment porosity at infinite depth  porinf  = ', porinf
+         WRITE(numsed,*) ' Length scale of porosity variation   rhox    = ', rhox
+      ENDIF
+
+      jpksedm1  = jpksed - 1
+      dtsed = r2dttrc
+
+      REWIND( numnamsed_ref )              ! Namelist nam_trased in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_trased, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_trased in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_trased in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_trased, IOSTAT = ios, ERR = 906)
+906   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_trased in configuration namelist' )
+
+      DO jn = 1, jpsol
+         sedtrcd(jn) = sedsol(jn)%snamesed
+         sedtrcl(jn) = sedsol(jn)%lnamesed
+         sedtrcu(jn) = sedsol(jn)%unitsed
+      END DO
+
+      DO jn = 1, jpwat
+         jn1 = jn + jpsol
+         sedtrcd(jn1) = sedwat(jn)%snamesed
+         sedtrcl(jn1) = sedwat(jn)%lnamesed
+         sedtrcu(jn1) = sedwat(jn)%unitsed
+      END DO
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_trased'
+         WRITE(numsed,*) ' '
+         DO jn = 1, jptrased
+            WRITE(numsed,*) 'name of 3d output sediment field number :',jn,' : ',TRIM(sedtrcd(jn))
+            WRITE(numsed,*) 'long name ', TRIM(sedtrcl(jn))
+            WRITE(numsed,*) ' in unit = ', TRIM(sedtrcu(jn))
+            WRITE(numsed,*) ' '
+         END DO
+         WRITE(numsed,*) ' '
+      ENDIF
+
+      REWIND( numnamsed_ref )              ! Namelist nam_diased in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_diased, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_diased in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_diased in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_diased, IOSTAT = ios, ERR = 908)
+908   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_diased in configuration namelist' )
+      
+      DO jn = 1, jpdia3dsed
+         seddia3d(jn) = seddiag3d(jn)%snamesed
+         seddia3l(jn) = seddiag3d(jn)%lnamesed
+         seddia3u(jn) = seddiag3d(jn)%unitsed
+      END DO
+
+      DO jn = 1, jpdia2dsed
+         seddia2d(jn) = seddiag2d(jn)%snamesed
+         seddia2l(jn) = seddiag2d(jn)%lnamesed
+         seddia2u(jn) = seddiag2d(jn)%unitsed
+      END DO
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_diased'
+         WRITE(numsed,*) ' '
+         DO jn = 1, jpdia3dsed
+            WRITE(numsed,*) 'name of 3D output diag number :',jn, ' : ', TRIM(seddia3d(jn))
+            WRITE(numsed,*) 'long name ', TRIM(seddia3l(jn))
+            WRITE(numsed,*) ' in unit = ',TRIM(seddia3u(jn))
+            WRITE(numsed,*) ' '
+         END DO
+
+         DO jn = 1, jpdia2dsed
+            WRITE(numsed,*) 'name of 2D output diag number :',jn, ' : ', TRIM(seddia2d(jn))
+            WRITE(numsed,*) 'long name ', TRIM(seddia2l(jn))
+            WRITE(numsed,*) ' in unit = ',TRIM(seddia2u(jn))
+            WRITE(numsed,*) ' '
+         END DO
+
+         WRITE(numsed,*) ' '
+      ENDIF
+
+      ! Inorganic chemistry parameters
+      !----------------------------------
+      REWIND( numnamsed_ref )              ! Namelist nam_inorg in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_inorg, IOSTAT = ios, ERR = 909)
+909   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_inorg in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_inorg in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_inorg, IOSTAT = ios, ERR = 910)
+910   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_inorg in configuration namelist' )
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_inorg'
+         WRITE(numsed,*) ' reactivity for Si      rcopal  = ', rcopal
+         WRITE(numsed,*) ' diff. coef for por.    dcoef   = ', dcoef
+         WRITE(numsed,*) ' reactivity for calcite rccal   = ', rccal
+         WRITE(numsed,*) ' L/C ratio in POC       ratligc = ', ratligc
+         WRITE(numsed,*) ' reactivity for ligands rcligc  = ', rcligc
+         WRITE(numsed,*) ' '
+      ENDIF
+
+      ! Unity conversion to get saturation conc. psat in [mol.l-1]
+      ! and reactivity rc in  [l.mol-1.s-1]
+      !----------------------------------------------------------
+      reac_sil   = rcopal / ryear     
+      reac_ligc  = rcligc / ryear
+
+      ! Additional parameter linked to POC/O2/No3/Po4
+      !----------------------------------------------
+      REWIND( numnamsed_ref )              ! Namelist nam_poc in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_poc, IOSTAT = ios, ERR = 911)
+911   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_poc in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_poc in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_poc, IOSTAT = ios, ERR = 912)
+912   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_poc in configuration namelist' )
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_poc'
+         WRITE(numsed,*) ' Redfield coef for oxy            redO2    = ', redO2
+         WRITE(numsed,*) ' Redfield coef for no3            redNo3   = ', redNo3
+         WRITE(numsed,*) ' Redfield coef for po4            redPo4   = ', redPo4
+         WRITE(numsed,*) ' Redfield coef for carbon         redC     = ', redC
+         WRITE(numsed,*) ' Ration for iron bound P          redfep   = ', redfep
+         WRITE(numsed,*) ' reactivity for labile POC        rcorgl   = ', rcorgl
+         WRITE(numsed,*) ' reactivity for semi-refract. POC rcorgs   = ', rcorgs
+         WRITE(numsed,*) ' reactivity for refractory POC    rcorgr   = ', rcorgr
+         WRITE(numsed,*) ' reactivity for NH4               rcnh4    = ', rcnh4
+         WRITE(numsed,*) ' reactivity for H2S               rch2s    = ', rch2s
+         WRITE(numsed,*) ' reactivity for Fe2+              rcfe2    = ', rcfe2
+         WRITE(numsed,*) ' reactivity for FeOH/H2S          rcfeh2s  = ', rcfeh2s
+         WRITE(numsed,*) ' reactivity for Fe2+/H2S          rcfes    = ', rcfes
+         WRITE(numsed,*) ' reactivity for FeS/O2            rcfeso   = ', rcfeso
+         WRITE(numsed,*) ' Half-sat. cste for oxic remin    xksedo2  = ', xksedo2
+         WRITE(numsed,*) ' Half-sat. cste for denit.        xksedno3 = ', xksedno3
+         WRITE(numsed,*) ' Half-sat. cste for iron remin    xksedfeo = ', xksedfeo
+         WRITE(numsed,*) ' Half-sat. cste for SO4 remin     xksedso4 = ', xksedso4
+         WRITE(numsed,*) ' '
+      ENDIF
+
+
+      so2ut  = redO2    / redC
+      srno3  = redNo3   / redC
+      spo4r  = redPo4   / redC
+      srDnit = ( (redO2 + 32. ) * 0.8 - redNo3 - redNo3 * 0.6 ) / redC
+      ! reactivity rc in  [l.mol-1.s-1]
+      reac_pocl  = rcorgl / ryear
+      reac_pocs  = rcorgs / ryear
+      reac_pocr  = rcorgr / ryear
+      reac_nh4   = rcnh4  / ryear
+      reac_h2s   = rch2s  / ryear
+      reac_fe2   = rcfe2  / ryear
+      reac_feh2s = rcfeh2s/ ryear
+      reac_fes   = rcfes  / ryear
+      reac_feso  = rcfeso / ryear
+
+      ! reactivity rc in  [l.mol-1.s-1]      
+      reac_cal = rccal / ryear
+
+      ! Bioturbation parameter
+      !------------------------
+      REWIND( numnamsed_ref )              ! Namelist nam_btb in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_btb, IOSTAT = ios, ERR = 913)
+913   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_btb in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_btb in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_btb, IOSTAT = ios, ERR = 914)
+914   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_btb in configuration namelist' )
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist nam_btb ' 
+         WRITE(numsed,*) ' coefficient for bioturbation      dbiot    = ', dbiot
+         WRITE(numsed,*) ' Depth varying bioturbation        ln_btbz  = ', ln_btbz
+         WRITE(numsed,*) ' coefficient for btb attenuation   dbtbzsc  = ', dbtbzsc
+         WRITE(numsed,*) ' Adsorption coefficient of NH4     adsnh4   = ', adsnh4
+         WRITE(numsed,*) ' Bioirrigation in sediment         ln_irrig = ', ln_irrig
+         WRITE(numsed,*) ' coefficient for irrig attenuation xirrzsc  = ', xirrzsc
+         WRITE(numsed,*) ' '
+      ENDIF
+
+      ! Initial value (t=0) for sediment pore water and solid components
+      !----------------------------------------------------------------
+      REWIND( numnamsed_ref )              ! Namelist nam_rst in reference namelist : Pisces variables
+      READ  ( numnamsed_ref, nam_rst, IOSTAT = ios, ERR = 915)
+915   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_rst in reference namelist' )
+
+      REWIND( numnamsed_cfg )              ! Namelist nam_rst in reference namelist : Pisces variables
+      READ  ( numnamsed_cfg, nam_rst, IOSTAT = ios, ERR = 916)
+916   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nam_rst in configuration namelist' )
+
+      IF (lwp) THEN
+         WRITE(numsed,*) ' namelist  nam_rst ' 
+         WRITE(numsed,*) '  boolean term for restart (T or F) ln_rst_sed = ', ln_rst_sed 
+         WRITE(numsed,*) ' '
+      ENDIF
+      nn_dtsed = nn_dttrc
+
+      CLOSE( numnamsed_cfg )
+      CLOSE( numnamsed_ref )
+
+   END SUBROUTINE sed_init_nam
+
+END MODULE sedini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinitrc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinitrc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinitrc.F90	(revision 14097)
@@ -0,0 +1,192 @@
+MODULE sedinitrc
+   !!======================================================================
+   !!              ***  MODULE  sedinitrc  ***
+   !! Sediment : define sediment variables
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   sed_init    : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedini
+   USE seddta
+   USE sedrst
+   USE sedco3
+   USE sedchem
+   USE sedarr
+   USE lib_mpp         ! distribued memory computing library
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   REAL(wp)    ::  &
+      ryear = 365. * 24. * 3600. !:  1 year converted in second
+
+   !! *  Routine accessibility
+   PUBLIC sed_initrc          ! routine called by opa.F90
+
+   !! $Id$
+CONTAINS
+
+
+   SUBROUTINE sed_initrc
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_init  ***
+      !!
+      !! ** Purpose :  Initialization of sediment module
+      !!               - Reading namelist
+      !!               - Read the deepest water layer thickness
+      !!                 ( using as mask ) in Netcdf file
+      !!               - Convert unity if necessary
+      !!               - sets initial sediment composition
+      !!                 ( only clay or reading restart file )
+      !!               - sets sediment grid, porosity and others constants
+      !!
+      !!   History :
+      !!        !  04-10  (N. Emprin, M. Gehlen )  Original code
+      !!        !  06-07  (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      INTEGER :: ji, jj, ikt
+      !!----------------------------------------------------------------------
+
+
+      ! Initialize the sediment tracers concentrations
+      !------------------------------------------------
+
+      IF(lwp) WRITE(numsed,*) ' sed_initrc : Initialization of sediment concentration '
+      IF(lwp) WRITE(numsed,*) ' '
+
+      ! Determination of sediments number of points and allocate global variables
+
+      ! sets initial sediment composition
+      ! ( only clay or reading restart file )
+      !---------------------------------------
+      CALL sed_init_data
+
+
+      CALL sed_init_wri
+
+
+   END SUBROUTINE sed_initrc
+
+
+   SUBROUTINE sed_init_data
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_init_data  ***
+      !!
+      !! ** Purpose :  Initialization of sediment module
+      !!               - sets initial sediment composition
+      !!                 ( only clay or reading restart file )
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  original
+      !!----------------------------------------------------------------------
+ 
+      ! local variables
+      INTEGER :: &
+         ji, jk, zhipor
+
+      !--------------------------------------------------------------------
+ 
+
+      IF( .NOT. ln_rst_sed ) THEN
+
+         IF (lwp) WRITE(numsed,*) ' Initilization of default values of sediment components'
+
+         ! default values for initial pore water concentrations [mol/l]
+         pwcp(:,:,:) = 0.
+         ! default value for initial solid component (fraction of dry weight dim=[0])
+         ! clay
+         solcp(:,:,:) = 0.
+         solcp(:,2:jpksed,jsclay) = 1.0 * 0.965
+         solcp(:,2:jpksed,jsfeo)  = 1.0 * 0.035
+
+         ! Initialization of [h+] and [co3--]
+
+         zhipor = 8.0
+         ! Initialization of [h+] in mol/kg
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce
+               hipor (ji,jk) = 10.**( -1. * zhipor )
+            ENDDO
+         ENDDO
+
+         co3por(:,:) = 1E-6
+
+      ELSE   
+  
+         IF (lwp) WRITE(numsed,*) ' Initilization of Sediment components from restart'
+
+         CALL sed_rst_cal( nitsed000, 'READ' )
+         CALL sed_rst_read
+
+      ENDIF
+
+
+      ! Load initial Pisces Data for bot. wat. Chem and fluxes
+      CALL sed_dta ( nitsed000 ) 
+
+      ! Initialization of chemical constants
+      CALL sed_chem ( nitsed000 )
+
+      ! Stores initial sediment data for mass balance calculation
+      pwcp0 (1:jpoce,1:jpksed,1:jpwat ) = pwcp (1:jpoce,1:jpksed,1:jpwat ) 
+      solcp0(1:jpoce,1:jpksed,1:jpsol ) = solcp(1:jpoce,1:jpksed,1:jpsol) 
+
+      ! Conversion of [h+] in mol/Kg to get it in mol/l ( multiplication by density)
+      DO jk = 1, jpksed
+         hipor(1:jpoce,jk) = hipor(1:jpoce,jk) * densSW(1:jpoce)
+      ENDDO
+
+
+      ! In default case - no restart - sedco3 is run to initiate [h+] and [co32-]
+      ! Otherwise initiate values of pH and co3 read in restart
+      IF( .NOT. ln_rst_sed ) THEN
+         ! sedco3 is run to initiate[h+] [co32-] in mol/l of solution
+         CALL sed_co3 ( nitsed000 )
+
+      ENDIF
+            
+   END SUBROUTINE sed_init_data
+
+   SUBROUTINE sed_init_wri
+
+      INTEGER :: jk
+
+      IF (lwp) THEN
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'======== Write summary of sediment char.  ============'
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'-------------------------------------------------------------------'
+         WRITE(numsed,*)' Initial Conditions '
+         WRITE(numsed,*)'-------------------------------------------------------------------'
+         WRITE(numsed,*)'dzm = dzkbot minimum to calculate ', 0.
+         WRITE(numsed,*)'Local zone : jpi, jpj, jpksed : ',jpi, jpj, jpksed
+         WRITE(numsed,*)'jpoce = ',jpoce,' nbtot pts = ',jpij,' nb earth pts = ',jpij - jpoce
+         WRITE(numsed,*)'sublayer thickness dz(1) [cm] : ', dz(1)
+         WRITE(numsed,*)'Vertical domain of the sediment'
+         WRITE(numsed,*)'-------------------------------'
+         WRITE(numsed,*)' Indice, profsed, dz'
+         DO jk = 2, jpksed
+            WRITE(numsed,*) jk,profsed(jk),dz(jk) 
+         END DO
+         WRITE(numsed,*)' nb solid comp : ',jpsol
+         WRITE(numsed,*)'(1=opal,2=clay,3=POC,4=CaCO3), 5=POS, 6=POR, 7=FEO, 8=FeS'
+         WRITE(numsed,*)'weight mol 1,2,3,4,5,6,7'
+         WRITE(numsed,'(8(F0.2,3X))')mol_wgt(jsopal),mol_wgt(jsclay),mol_wgt(jspoc),mol_wgt(jscal),mol_wgt(jspos),mol_wgt(jspor),mol_wgt(jsfeo),mol_wgt(jsfes)
+         WRITE(numsed,*)'nb dissolved comp',jpwat
+         WRITE(numsed,*)'1=silicic acid,,2=O2,3=DIC,4=NO3,5=PO4,6=Alk,7=NH4,8=ODU'
+         WRITE(numsed,*)'redfield coef C,O,N P Dit '
+         WRITE(numsed,'(5(F0.2,3X))')1./spo4r,so2ut/spo4r,srno3/spo4r,spo4r/spo4r,srDnit/spo4r
+         WRITE(numsed,*) ' '
+         WRITE(numsed,*) ' End Of Initialization '
+         WRITE(numsed,*) ' '
+      ENDIF
+!
+   END SUBROUTINE sed_init_wri
+
+END MODULE sedinitrc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinorg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinorg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedinorg.F90	(revision 14097)
@@ -0,0 +1,301 @@
+MODULE sedinorg
+   !!======================================================================
+   !!              ***  MODULE  sedinorg  ***
+   !!    Sediment : dissolution and reaction in pore water of 
+   !!               inorganic species
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedmat  ! linear system of equations
+   USE sedco3  ! carbonate ion and proton concentration 
+   USE sedini
+   USE seddsr
+   USE lib_mpp         ! distribued memory computing library
+   USE lib_fortran
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_inorg
+
+   !! $Id$
+CONTAINS
+   
+   SUBROUTINE sed_inorg( kt ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_inorg  ***
+      !! 
+      !!  ** Purpose :  computes pore water dissolution and reaction
+      !!
+      !!  ** Methode :  implicit simultaneous computation of undersaturation
+      !!               resulting from diffusive pore water transport and chemical
+      !!               pore water reactions. Solid material is consumed according
+      !!               to redissolution and remineralisation
+      !!
+      !!  ** Remarks :
+      !!              - undersaturation : deviation from saturation concentration
+      !!              - reaction rate   : sink of undersaturation from dissolution
+      !!                                 of solid material 
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) f90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!        !  19-08 (O. Aumont) Debugging and improvement of the model
+      !!----------------------------------------------------------------------
+      !! Arguments
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      ! --- local variables
+      INTEGER :: ji, jk, js, jw         ! dummy looop indices
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zrearat1, zrearat2    ! reaction rate in pore water
+      REAL(wp), DIMENSION(jpoce,jpksed) :: zundsat    ! undersaturation ; indice jpwatp1 is for calcite   
+      REAL(wp), DIMENSION(jpoce) :: zco3eq
+      REAL(wp), DIMENSION(jpoce,jpksed,jpsol) :: zvolc    ! temp. variables
+      REAL(wp), DIMENSION(jpoce) :: zsieq
+      REAL(wp)  ::  zsolid1, zvolw, zreasat
+      REAL(wp)  ::  zsatur, zsatur2, znusil, zsolcpcl, zsolcpsi
+      !!
+      !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_inorg')
+!
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) THEN
+            WRITE(numsed,*) ' sed_inorg : Dissolution reaction '
+            WRITE(numsed,*) ' '
+         ENDIF
+!         ! 
+      ENDIF
+
+     ! Initializations
+     !----------------------
+      
+      zrearat1(:,:) = 0.    ;   zundsat(:,:)  = 0. 
+      zrearat2(:,:) = 0.    ;   zrearat2(:,:) = 0.
+      zco3eq(:)     = rtrn
+      zvolc(:,:,:)  = 0.
+
+      ! -----------------------------------------------
+      ! Computation of Si solubility
+      ! Param of Ridgwell et al. 2002
+      ! -----------------------------------------------
+
+      DO ji = 1, jpoce
+         zsolcpcl = 0.0
+         zsolcpsi = 0.0
+         DO jk = 1, jpksed
+            zsolcpsi = zsolcpsi + solcp(ji,jk,jsopal) * dz(jk)
+            zsolcpcl = zsolcpcl + solcp(ji,jk,jsclay) * dz(jk)
+         END DO
+         zsolcpsi = MAX( zsolcpsi, rtrn )
+         zsieq(ji) = sieqs(ji) * MAX(0.25, 1.0 - (0.045 * zsolcpcl / zsolcpsi )**0.58 )
+         zsieq(ji) = MAX( rtrn, sieqs(ji) )
+      END DO
+
+      DO js = 1, jpsol
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce    
+               zvolc(ji,jk,js) = ( vols3d(ji,jk) * dens_mol_wgt(js) ) /  &
+                  &              ( volw3d(ji,jk) * 1.e-3  )     
+            ENDDO
+         ENDDO
+      ENDDO
+
+      !----------------------------------------------------------
+      ! 5.  Beginning of  Pore Water diffusion and solid reaction
+      !---------------------------------------------------------
+      
+      !-----------------------------------------------------------------------------
+      ! For jk=2,jpksed, and for couple 
+      !  1 : jwsil/jsopal  ( SI/Opal )
+      !  2 : jsclay/jsclay ( clay/clay ) 
+      !  3 : jwoxy/jspoc   ( O2/POC )
+      !  reaction rate is a function of solid=concentration in solid reactif in [mol/l] 
+      !  and undersaturation in [mol/l].
+      !  Solid weight fractions should be in ie [mol/l])
+      !  second member and solution are in zundsat variable
+      !-------------------------------------------------------------------------
+
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            ! For Silicic Acid and clay
+            zundsat(ji,jk) = zsieq(ji) - pwcp(ji,jk,jwsil)
+         ENDDO
+      ENDDO
+      
+      ! Definition of reaction rates [rearat]=sans dim 
+      ! For jk=1 no reaction (pure water without solid) for each solid compo
+      DO ji = 1, jpoce
+         zrearat1(ji,:) = 0.
+         zrearat2(ji,:) = 0.
+      ENDDO
+
+      ! left hand side of coefficient matrix
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zsolid1 = zvolc(ji,jk,jsopal) * solcp(ji,jk,jsopal)
+            zsatur = MAX(0., zundsat(ji,jk) / zsieq(ji) )
+            zsatur2 = (1.0 + temp(ji) / 400.0 )**37
+            znusil = ( 0.225 * ( 1.0 + temp(ji) / 15.) + 0.775 * zsatur2 * zsatur**2.25 ) / zsieq(ji)
+            zrearat1(ji,jk)  = ( reac_sil * znusil * dtsed * zsolid1 ) / &
+               &                ( 1. + reac_sil * znusil * dtsed * zundsat(ji,jk) )
+         ENDDO
+      ENDDO
+
+      CALL sed_mat( jwsil, jpoce, jpksed, zrearat1, zrearat2, zundsat, dtsed )
+
+      ! New solid concentration values (jk=2 to jksed) for each couple 
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zundsat(ji,jk) / ( zvolc(ji,jk,jsopal) )
+            solcp(ji,jk,jsopal) = solcp(ji,jk,jsopal) - zreasat
+         ENDDO
+      ENDDO
+
+      ! New pore water concentrations    
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            ! Acid Silicic 
+            pwcp(ji,jk,jwsil)  = zsieq(ji) - zundsat(ji,jk)
+         ENDDO
+      ENDDO
+
+      !---------------------------------------------------------------
+      ! Performs CaCO3 particle deposition and redissolution (indice 9)
+      !--------------------------------------------------------------
+
+      ! computes co3por from the updated pwcp concentrations (note [co3por] = mol/l)
+
+      CALL sed_co3( kt )
+
+      ! *densSW(l)**2 converts aksps [mol2/kg sol2] into [mol2/l2] to get [undsat] in [mol/l]
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zco3eq(ji)     = aksps(ji) * densSW(ji) * densSW(ji) / ( calcon2(ji) + rtrn )
+            zco3eq(ji)     = MAX( rtrn, zco3eq(ji) ) 
+            zundsat(ji,jk) = MAX(0., zco3eq(ji) - co3por(ji,jk) )
+         ENDDO
+      ENDDO
+
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zsolid1 = zvolc(ji,jk,jscal) * solcp(ji,jk,jscal)
+            zrearat1(ji,jk) = ( reac_cal * dtsed * zsolid1 / zco3eq(ji) ) / &
+                  &               ( 1. + reac_cal * dtsed * zundsat(ji,jk) / zco3eq(ji) )
+         END DO
+      END DO
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwdic, jpoce, jpksed, zrearat1, zrearat2, zundsat, dtsed )
+
+      ! New solid concentration values (jk=2 to jksed) for cacO3
+      DO jk = 2, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zundsat(ji,jk) / zvolc(ji,jk,jscal)
+            solcp(ji,jk,jscal) = solcp(ji,jk,jscal) - zreasat
+         ENDDO
+      ENDDO
+
+      ! New dissolved concentrations
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zreasat = zrearat1(ji,jk) * zundsat(ji,jk)    
+            ! For DIC
+            pwcp(ji,jk,jwdic)  = pwcp(ji,jk,jwdic) + zreasat
+            ! For alkalinity
+            pwcp(ji,jk,jwalk)  = pwcp(ji,jk,jwalk) + 2.0 * zreasat 
+         ENDDO
+      ENDDO
+
+      !-------------------------------------------------
+      ! Beginning DIC, Alkalinity 
+      !-------------------------------------------------
+      
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce      
+            zundsat(ji,jk)   = pwcp(ji,jk,jwdic)
+            zrearat1(ji,jk)  = 0.
+         ENDDO
+      ENDDO
+
+      ! solves tridiagonal system
+      CALL sed_mat( jwdic, jpoce, jpksed, zrearat1, zrearat2, zundsat, dtsed )
+
+     ! New dissolved concentrations      
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce                      
+            pwcp(ji,jk,jwdic) = zundsat(ji,jk)
+         ENDDO
+      ENDDO            
+
+      !-------------------------------------------------
+      ! Beginning DIC, Alkalinity 
+      !-------------------------------------------------
+
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zundsat(ji,jk) = pwcp(ji,jk,jwalk)
+            zrearat1(ji,jk) = 0.
+         ENDDO
+      ENDDO
+!
+!      ! solves tridiagonal system
+      CALL sed_mat( jwalk, jpoce, jpksed, zrearat1, zrearat2, zundsat, dtsed )
+!
+!      ! New dissolved concentrations      
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            pwcp(ji,jk,jwalk) = zundsat(ji,jk)
+         ENDDO
+      ENDDO
+      
+      !----------------------------------
+      !   Back to initial geometry
+      !-----------------------------
+      
+      !---------------------------------------------------------------------
+      !   1/ Compensation for ajustement of the bottom water concentrations
+      !      (see note n° 1 about *por(2))
+      !--------------------------------------------------------------------
+      DO jw = 1, jpwat
+         DO ji = 1, jpoce
+            pwcp(ji,1,jw) = pwcp(ji,1,jw) + &
+               &            pwcp(ji,2,jw) * dzdep(ji) * por(2) / dzkbot(ji)
+         END DO
+      ENDDO
+      
+      !-----------------------------------------------------------------------
+      !    2/ Det of new rainrg taking account of the new weight fraction obtained 
+      !      in dz3d(2) after diffusion/reaction (react/diffu are also in dzdep!)
+      !      This new rain (rgntg rm) will be used in advection/burial routine
+      !------------------------------------------------------------------------
+      DO js = 1, jpsol
+         DO ji = 1, jpoce
+            rainrg(ji,js) = raintg(ji) * solcp(ji,2,js)
+            rainrm(ji,js) = rainrg(ji,js) / mol_wgt(js)
+         END DO
+      ENDDO
+
+      !  New raintg
+      raintg(:) = 0.
+      DO js = 1, jpsol
+         DO ji = 1, jpoce
+            raintg(ji) = raintg(ji) + rainrg(ji,js)
+         END DO
+      ENDDO
+      
+      !--------------------------------
+      !    3/ back to initial geometry
+      !--------------------------------
+      DO ji = 1, jpoce
+         dz3d  (ji,2) = dz(2)
+         volw3d(ji,2) = dz3d(ji,2) * por(2)
+         vols3d(ji,2) = dz3d(ji,2) * por1(2)
+      ENDDO
+
+      IF( ln_timing )  CALL timing_stop('sed_inorg')
+!      
+   END SUBROUTINE sed_inorg
+
+END MODULE sedinorg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmat.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmat.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmat.F90	(revision 14097)
@@ -0,0 +1,265 @@
+MODULE sedmat
+   !!======================================================================
+   !!              ***  MODULE  sedmat  ***
+   !!    Sediment : linear system of equations
+   !!=====================================================================
+   !! * Modules used
+   !!----------------------------------------------------------------------
+
+   USE sed     ! sediment global variable
+   USE lib_mpp         ! distribued memory computing library
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_mat 
+
+   INTERFACE sed_mat
+      MODULE PROCEDURE sed_mat_dsr, sed_mat_btb
+   END INTERFACE
+
+   INTEGER, PARAMETER :: nmax = 30 
+
+
+   !! $Id$
+ CONTAINS
+
+    SUBROUTINE sed_mat_dsr( nvar, ndim, nlev, preac, psms, psol, dtsed_in )
+       !!---------------------------------------------------------------------
+       !!                  ***  ROUTINE sed_mat_dsr  ***
+       !!
+       !! ** Purpose :  solves tridiagonal system of linear equations 
+       !!
+       !! ** Method  : 
+       !!        1 - computes left hand side of linear system of equations
+       !!            for dissolution reaction
+       !!         For mass balance in kbot+sediment :
+       !!              dz3d  (:,1) = dz(1) = 0.5 cm
+       !!              volw3d(:,1) = dzkbot ( see sedini.F90 ) 
+       !!              dz(2)       = 0.3 cm 
+       !!              dz3d(:,2)   = 0.3 + dzdep   ( see seddsr.F90 )     
+       !!              volw3d(:,2) and vols3d(l,2) are thickened ( see seddsr.F90 ) 
+       !!
+       !!         2 - forward/backward substitution. 
+       !!
+       !!   History :
+       !!        !  04-10 (N. Emprin, M. Gehlen ) original
+       !!        !  06-04 (C. Ethe)  Module Re-organization
+       !!----------------------------------------------------------------------
+       !! * Arguments
+       INTEGER , INTENT(in) ::  nvar  ! number of variable
+       INTEGER , INTENT(in) ::  ndim  ! number of points
+       INTEGER , INTENT(in) ::  nlev  ! number of sediment levels
+
+       REAL(wp), DIMENSION(ndim,nlev), INTENT(in   ) :: preac  ! reaction rates
+       REAL(wp), DIMENSION(ndim,nlev), INTENT(in   ) :: psms  ! reaction rates
+       REAL(wp), DIMENSION(ndim,nlev), INTENT(inout) :: psol   ! solution ( undersaturation values )
+       REAL(wp), INTENT(in) ::  dtsed_in
+ 
+       !---Local declarations
+       INTEGER  ::  ji, jk, jn
+       REAL(wp), DIMENSION(ndim,nlev) :: za, zb, zc, zr
+       REAL(wp), DIMENSION(ndim)      :: zbet
+       REAL(wp), DIMENSION(ndim,nmax) :: zgamm
+
+       REAL(wp) ::  aplus,aminus  
+       REAL(wp) ::  rplus,rminus   
+       REAL(wp) ::  dxplus,dxminus
+
+       !----------------------------------------------------------------------
+
+       IF( ln_timing )  CALL timing_start('sed_mat_dsr')
+
+       ! Computation left hand side of linear system of 
+       ! equations for dissolution reaction
+       !---------------------------------------------
+
+
+       jn = nvar
+       ! first sediment level          
+       DO ji = 1, ndim
+          aplus  = ( ( volw3d(ji,1) / ( dz3d(ji,1) ) ) + &
+                        ( volw3d(ji,2) / ( dz3d(ji,2) ) ) ) / 2.
+          dxplus = ( dz3d(ji,1) + dz3d(ji,2) ) / 2.
+          rplus  = ( dtsed_in / ( volw3d(ji,1) ) ) * diff(ji,1,jn) * aplus / dxplus 
+
+          za(ji,1) = 0.
+          zb(ji,1) = 1. + rplus
+          zc(ji,1) = -rplus
+       ENDDO
+ 
+       DO jk = 2, nlev - 1
+          DO ji = 1, ndim
+             aminus  = ( ( volw3d(ji,jk-1) / ( dz3d(ji,jk-1) ) ) + &
+             &        ( volw3d(ji,jk  ) / ( dz3d(ji,jk  ) ) ) ) / 2.
+             dxminus = ( dz3d(ji,jk-1) + dz3d(ji,jk) ) / 2.
+
+             aplus   = ( ( volw3d(ji,jk  ) / ( dz3d(ji,jk  ) ) ) + &
+             &        ( volw3d(ji,jk+1) / ( dz3d(ji,jk+1) ) ) ) / 2.
+             dxplus  = ( dz3d(ji,jk) + dz3d(ji,jk+1) ) / 2
+                !
+             rminus  = ( dtsed_in / volw3d(ji,jk) ) * diff(ji,jk-1,jn) * aminus / dxminus
+             rplus   = ( dtsed_in / volw3d(ji,jk) ) * diff(ji,jk,jn)   * aplus / dxplus
+                !     
+             za(ji,jk) = -rminus
+             zb(ji,jk) = 1. + rminus + rplus 
+             zc(ji,jk) = -rplus
+          END DO
+       END DO
+
+       DO ji = 1, ndim
+          aminus  = ( ( volw3d(ji,nlev-1) / dz3d(ji,nlev-1)  ) + &
+          &        ( volw3d(ji,nlev)  / dz3d(ji,nlev) ) ) / 2.
+          dxminus = ( dz3d(ji,nlev-1) + dz3d(ji,nlev) ) / 2.
+          rminus  = ( dtsed_in / volw3d(ji,nlev) ) * diff(ji,nlev-1,jn) * aminus / dxminus
+          !
+          za(ji,nlev) = -rminus
+          zb(ji,nlev) = 1. + rminus
+          zc(ji,nlev) = 0.
+       END DO
+
+
+       ! solves tridiagonal system of linear equations 
+       ! -----------------------------------------------
+
+       zr  (:,:) = psol(:,:) + psms(:,:)
+       zb  (:,:) = zb(:,:) + preac(:,:)
+       zbet(:  ) = zb(:,1)
+       psol(:,1) = zr(:,1) / zbet(:)
+
+          ! 
+       DO jk = 2, nlev
+          DO ji = 1, ndim
+             zgamm(ji,jk) =  zc(ji,jk-1) / zbet(ji)
+             zbet(ji)     =  zb(ji,jk) - za(ji,jk) * zgamm(ji,jk)
+             psol(ji,jk)  = ( zr(ji,jk) - za(ji,jk) * psol(ji,jk-1) ) / zbet(ji)
+          END DO
+       ENDDO
+          ! 
+       DO jk = nlev - 1, 1, -1
+          DO ji = 1,ndim
+             psol(ji,jk) = psol(ji,jk) - zgamm(ji,jk+1) * psol(ji,jk+1)
+          END DO
+       ENDDO
+
+       IF( ln_timing )  CALL timing_stop('sed_mat_dsr')
+
+
+    END SUBROUTINE sed_mat_dsr
+
+    SUBROUTINE sed_mat_btb( nvar, ndim, nlev, psol, dtsed_in )
+       !!---------------------------------------------------------------------
+       !!                  ***  ROUTINE sed_mat_btb  ***
+       !!
+       !! ** Purpose :  solves tridiagonal system of linear equations 
+       !!
+       !! ** Method  : 
+       !!        1 - computes left hand side of linear system of equations
+       !!            for dissolution reaction
+       !!
+       !!         2 - forward/backward substitution. 
+       !!
+       !!   History :
+       !!        !  04-10 (N. Emprin, M. Gehlen ) original
+       !!        !  06-04 (C. Ethe)  Module Re-organization
+       !!----------------------------------------------------------------------
+       !! * Arguments
+       INTEGER , INTENT(in) :: &
+          nvar , &  ! number of variables
+          ndim , &  ! number of points
+          nlev      ! number of sediment levels
+
+      REAL(wp), DIMENSION(ndim,nlev,nvar), INTENT(inout) :: &
+          psol      ! solution
+
+      REAL(wp), INTENT(in) :: dtsed_in
+
+       !---Local declarations
+       INTEGER  ::  &
+          ji, jk, jn
+
+       REAL(wp) ::  &
+          aplus,aminus   ,  & 
+          rplus,rminus   ,  &
+          dxplus,dxminus 
+
+       REAL(wp), DIMENSION(nlev)      :: za, zb, zc
+       REAL(wp), DIMENSION(ndim,nlev) :: zr
+       REAL(wp), DIMENSION(nmax)      :: zgamm 
+       REAL(wp) ::  zbet
+
+ 
+       !----------------------------------------------------------------------
+
+       ! Computation left hand side of linear system of 
+       ! equations for dissolution reaction
+       !---------------------------------------------
+
+
+      IF( ln_timing )  CALL timing_start('sed_mat_btb')
+
+       ! first sediment level          
+      DO ji = 1, ndim
+         aplus  = ( ( vols(2) / dz(2) ) + ( vols(3) / dz(3) ) ) / 2.
+         dxplus = ( dz(2) + dz(3) ) / 2.
+         rplus  = ( dtsed_in / vols(2) ) * db(ji,2) * aplus / dxplus 
+
+         za(1) = 0.
+         zb(1) = 1. + rplus
+         zc(1) = -rplus
+
+             
+         DO jk = 2, nlev - 1
+            aminus  = ( ( vols(jk) / dz(jk) ) + ( vols(jk+1) / dz(jk+1) ) ) / 2.
+            dxminus = ( dz(jk) + dz(jk+1) ) / 2.
+            rminus  = ( dtsed_in / vols(jk+1) ) * db(ji,jk) * aminus / dxminus
+            !
+            aplus   = ( ( vols(jk+1) / dz(jk+1  ) ) + ( vols(jk+2) / dz(jk+2) ) ) / 2.
+            dxplus  = ( dz(jk+1) + dz(jk+2) ) / 2.
+            rplus   = ( dtsed_in / vols(jk+1) ) * db(ji,jk+1) * aplus / dxplus
+            !     
+            za(jk) = -rminus
+            zb(jk) = 1. + rminus + rplus 
+            zc(jk) = -rplus
+         ENDDO
+ 
+         aminus  = ( ( vols(nlev) / dz(nlev) ) + ( vols(nlev+1) / dz(nlev+1) ) ) / 2.
+         dxminus = ( dz(nlev) + dz(nlev+1) ) / 2.
+         rminus  = ( dtsed_in / vols(nlev+1) ) * db(ji,nlev) * aminus / dxminus
+         !
+         za(nlev) = -rminus
+         zb(nlev) = 1. + rminus
+         zc(nlev) = 0.
+
+
+         ! solves tridiagonal system of linear equations 
+         ! -----------------------------------------------    
+         DO jn = 1, nvar
+          
+            DO jk = 1, nlev
+               zr  (ji,jk)    = psol(ji,jk,jn)
+            END DO
+            zbet          = zb(1)
+            psol(ji,1,jn) = zr(ji,1) / zbet
+            ! 
+            DO jk = 2, nlev
+               zgamm(jk) =  zc(jk-1) / zbet
+               zbet      =  zb(jk) - za(jk) * zgamm(jk)
+               psol(ji,jk,jn) = ( zr(ji,jk) - za(jk) * psol(ji,jk-1,jn) ) / zbet
+            ENDDO
+            ! 
+            DO jk = nlev - 1, 1, -1
+                psol(ji,jk,jn) = psol(ji,jk,jn) - zgamm(jk+1) * psol(ji,jk+1,jn)
+            ENDDO
+
+         ENDDO
+
+       END DO
+       !
+       IF( ln_timing )  CALL timing_stop('sed_mat_btb')
+
+       
+    END SUBROUTINE sed_mat_btb
+
+ END MODULE sedmat
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmbc.F90	(revision 14097)
@@ -0,0 +1,257 @@
+MODULE sedmbc
+   !!======================================================================
+   !!              ***  MODULE  sedmbc  ***
+   !! Sediment : mass balance calculation
+   !!=====================================================================
+
+   !!----------------------------------------------------------------------
+   !!   sed_mbc    : 
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE seddsr
+   USE lib_mpp         ! distribued memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! *  Routine accessibility
+   PUBLIC sed_mbc
+
+   !! * Module variables
+   REAL(wp), DIMENSION(jpsol) :: rain_tot      ! total input rain
+   REAL(wp), DIMENSION(jpsol) :: fromsed_tot   ! tota input from sediment
+   REAL(wp), DIMENSION(jpsol) :: tosed_tot     ! total output from sediment
+   REAL(wp), DIMENSION(jpsol) :: rloss_tot     ! total rain loss
+
+   REAL(wp), DIMENSION(jpwat) :: diss_in_tot   ! total input in pore water
+   REAL(wp), DIMENSION(jpwat) :: diss_out_tot  ! total output from pore water
+
+   !! $Id$
+CONTAINS
+
+
+   SUBROUTINE sed_mbc( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_mbc  ***
+      !!
+      !! ** Purpose :  computation of total tracer inventories for checking
+      !!               mass conservation.
+      !!
+      !!
+      !! ** Method   : tracer inventories of each reservoir are computed and added
+      !!               subsequently.
+      !!
+      !!   History :
+      !!        !  04-10  (N. Emprin, M. Gehlen )  Original code
+      !!        !  06-07  (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+
+      !! Arguments
+      INTEGER, INTENT(in) :: kt     ! time step
+
+      !! local declarations
+      INTEGER  :: ji,js, jw, jk
+      REAL(wp) :: zinit, zfinal 
+      REAL(wp) :: zinput, zoutput
+      REAL(wp) :: zdsw, zvol
+      REAL, DIMENSION(jpsol) :: zsolcp_inv_i, zsolcp_inv_f
+      REAL, DIMENSION(jpwat) :: zpwcp_inv_i, zpwcp_inv_f
+      REAL(wp) ::  zdelta_sil, zdelta_clay
+      REAL(wp) ::  zdelta_co2, zdelta_fe
+      REAL(wp) ::  zdelta_po4, zdelta_no3
+
+      !!----------------------------------------------------------------------
+      ! Initilization
+      !---------------
+      IF( ln_timing )  CALL timing_start('sed_mbc')
+!
+      IF( kt == nitsed000 ) THEN
+
+         DO js = 1, jpsol
+            rain_tot   (js) = 0.
+            fromsed_tot(js) = 0.
+            tosed_tot  (js) = 0.
+            rloss_tot  (js) = 0.
+         ENDDO
+
+         DO jw = 1, jpwat
+            diss_in_tot (jw) = 0.
+            diss_out_tot(jw) = 0.
+         ENDDO
+
+      ENDIF
+
+
+      ! Calculation of the cumulativ input and output
+      ! for mass balance check
+      !----------------------------------------------
+
+      ! cumulativ solid
+      DO js = 1, jpsol
+         DO ji = 1, jpoce
+            ! input [mol]
+            rain_tot   (js) = rain_tot   (js) + dtsed * rainrm_dta(ji,js)
+            fromsed_tot(js) = fromsed_tot(js) + fromsed(ji,js) / mol_wgt(js)
+            ! output [mol]
+            tosed_tot  (js) = tosed_tot (js) + tosed(ji,js) / mol_wgt(js)
+            rloss_tot  (js) = rloss_tot (js) + rloss(ji,js) / mol_wgt(js)
+         ENDDO
+      ENDDO
+
+      ! cumulativ dissolved
+      DO jw = 1, jpwat
+         DO ji = 1, jpoce
+            ! input [mol]
+            diss_in_tot (jw) = diss_in_tot (jw) + pwcp_dta(ji,jw) * 1.e-3 * dzkbot(ji)
+            ! output [mol]
+            diss_out_tot(jw) = diss_out_tot(jw) + tokbot(ji,jw)
+         ENDDO
+      ENDDO
+
+      ! Mass balance check
+      !---------------------
+      IF( kt == nitsedend ) THEN
+         ! initial and final inventories for solid component (mole/dx.dy) in sediment
+         zsolcp_inv_i(:) = 0.
+         zsolcp_inv_f(:) = 0.
+         zpwcp_inv_i (:) = 0.       
+         zpwcp_inv_f (:) = 0.        
+         DO js = 1, jpsol
+            zdsw = denssol / mol_wgt(js)
+            DO jk = 2, jpksed
+               DO ji = 1, jpoce
+                  zvol = vols3d(ji,jk) * zdsw
+                  zsolcp_inv_i(js) = zsolcp_inv_i(js) + solcp0(ji,jk,js) * zvol 
+                  zsolcp_inv_f(js) = zsolcp_inv_f(js) + solcp (ji,jk,js) * zvol
+               ENDDO
+            END DO
+         ENDDO
+
+         ! initial and final inventories for dissolved component (mole/dx.dy) in sediment
+         DO jw = 1, jpwat
+            DO jk = 2, jpksed
+               DO ji = 1, jpoce 
+                  zvol = volw3d(ji,jk) * 1.e-3
+                  zpwcp_inv_i(jw) = zpwcp_inv_i(jw) + pwcp0(ji,jk,jw) * zvol
+                  zpwcp_inv_f(jw) = zpwcp_inv_f(jw) + pwcp (ji,jk,jw) * zvol
+               ENDDO
+            END DO
+         ENDDO
+
+         ! mass balance for Silica/opal
+         zinit      = zsolcp_inv_i(jsopal) + zpwcp_inv_i(jwsil)
+         zfinal     = zsolcp_inv_f(jsopal) + zpwcp_inv_f(jwsil)
+         zinput     = rain_tot    (jsopal) + diss_in_tot (jwsil)
+         zoutput    = tosed_tot   (jsopal) + rloss_tot  (jsopal) + diss_out_tot(jwsil)
+         zdelta_sil = ( zfinal + zoutput ) - ( zinit + zinput )
+
+
+         ! mass balance for Clay
+         zinit      = zsolcp_inv_i(jsclay) 
+         zfinal     = zsolcp_inv_f(jsclay) 
+         zinput     = rain_tot   (jsclay) + fromsed_tot(jsclay) 
+         zoutput    = tosed_tot  (jsclay) + rloss_tot  (jsclay) 
+         zdelta_clay= ( zfinal + zoutput ) - ( zinit + zinput )
+
+         ! mass balance for carbon ( carbon in POC, CaCo3, DIC )
+         zinit      = zsolcp_inv_i(jspoc) + zsolcp_inv_i(jspos) + zsolcp_inv_i(jspor) &
+         &          + zsolcp_inv_i(jscal) + zpwcp_inv_i(jwdic)
+         zfinal     = zsolcp_inv_f(jspoc) + zsolcp_inv_f(jspos) + zsolcp_inv_f(jspor) &
+         &          + zsolcp_inv_f(jscal) + zpwcp_inv_f(jwdic)
+         zinput     = rain_tot (jspoc) + rain_tot   (jspos)  +  rain_tot   (jspor) &
+         &          + rain_tot (jscal) + diss_in_tot(jwdic)
+         zoutput    = tosed_tot(jspoc) + tosed_tot(jspos) + tosed_tot(jspor) + tosed_tot(jscal) + diss_out_tot(jwdic) &
+            &       + rloss_tot(jspoc) + rloss_tot(jspos) + rloss_tot(jspor) + rloss_tot(jscal) 
+         zdelta_co2 = ( zfinal + zoutput ) - ( zinit + zinput )
+
+         ! mass balance for Sulfur
+         zinit      = zpwcp_inv_i(jwso4) + zpwcp_inv_i(jwh2s)   &
+         &          + zsolcp_inv_i(jsfes) 
+         zfinal     = zpwcp_inv_f(jwso4) + zpwcp_inv_f(jwh2s)   &
+         &          + zsolcp_inv_f(jsfes)
+         zinput     = diss_in_tot (jwso4) + diss_in_tot (jwh2s) &
+         &          + rain_tot (jsfes)
+         zoutput    = diss_out_tot(jwso4) + diss_out_tot(jwh2s) &
+         &          + tosed_tot(jsfes)    + rloss_tot(jsfes)
+         zdelta_no3 = ( zfinal + zoutput ) - ( zinit + zinput )
+
+         ! mass balance for iron
+         zinit      = zpwcp_inv_i(jwfe2)  + zsolcp_inv_i(jsfeo)   &
+         &          + zsolcp_inv_i(jsfes)
+         zfinal     = zpwcp_inv_f(jwfe2)  + zsolcp_inv_f(jsfeo)   &
+         &          + zsolcp_inv_f(jsfes)
+         zinput     = diss_in_tot (jwfe2) + rain_tot (jsfeo) &
+         &          + rain_tot (jsfes)
+         zoutput    = diss_out_tot(jwfe2) + tosed_tot(jsfeo) &
+         &          + tosed_tot(jsfes)    + rloss_tot(jsfes) + rloss_tot(jsfeo)
+         zdelta_fe  = ( zfinal + zoutput ) - ( zinit + zinput )
+
+
+      END IF
+
+      IF( kt == nitsedend) THEN 
+
+         IF (lwp) THEN
+         WRITE(numsed,*)
+         WRITE(numsed,*)'==================    General mass balance   ==================  '
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)' Initial total solid Masses (mole/dx.dy)        '
+         WRITE(numsed,*)' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numsed,*)'    Opal,      Clay,       POC,       POS,      POR,        CaCO3,     FeOH,     FeS'
+         WRITE(numsed,'(8x,4(1PE10.3,2X))')zsolcp_inv_i(jsopal),zsolcp_inv_i(jsclay),zsolcp_inv_i(jspoc), &
+            & zsolcp_inv_i(jspos),zsolcp_inv_i(jspor),zsolcp_inv_i(jscal),zsolcp_inv_i(jsfeo),zsolcp_inv_i(jsfes)
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)' Initial total dissolved Masses (mole/dx.dy)    '
+         WRITE(numsed,*)' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+         WRITE(numsed,*)'    Si,         O2,         DIC,        Nit,         Phos,         Fe2+'
+         WRITE(numsed,'(5x,5(1PE10.3,2X))') zpwcp_inv_i(jwsil), zpwcp_inv_i(jwoxy), &
+            & zpwcp_inv_i(jwdic), zpwcp_inv_i(jwno3), zpwcp_inv_i(jwpo4), zpwcp_inv_i(jwfe2)
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'  Solid inputs :  Opale,      Clay,       POC,        CaCO3,        Fe'
+         WRITE(numsed,'(A4,10X,5(1PE10.3,2X))')'Rain : ',rain_tot(jsopal),rain_tot(jsclay),rain_tot(jspoc) + rain_tot(jspos) + rain_tot(jspor),&
+            & rain_tot(jscal), rain_tot(jsfeo)
+         WRITE(numsed,'(A12,6x,5(1PE10.3,2X))')' From Sed : ',fromsed_tot(jsopal), fromsed_tot(jsclay), &
+            & fromsed_tot(jspoc)+fromsed_tot(jspos)+fromsed_tot(jspor), fromsed_tot(jscal),    &
+            & fromsed_tot(jsfeo) + fromsed_tot(jsfes)
+         WRITE(numsed,*)'Diss. inputs : Si,    O2,         DIC,         Nit,       Phos,      Fe'
+         WRITE(numsed,'(A9,1x,6(1PE10.3,2X))')' From Pisc : ', diss_in_tot(jwsil), &
+            & diss_in_tot(jwoxy), diss_in_tot(jwdic), diss_in_tot(jwno3), diss_in_tot(jwpo4), diss_in_tot(jwfe2)
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'Solid output : Opale,      Clay,       POC,        CaCO3,        Fe'
+         WRITE(numsed,'(A6,8x,5(1PE10.3,2X))')'To sed', tosed_tot(jsopal),tosed_tot(jsclay),tosed_tot(jspoc) &
+            & +tosed_tot(jspos)+tosed_tot(jspor),tosed_tot(jscal), tosed_tot(jsfeo)+tosed_tot(jsfes)
+         WRITE(numsed,'(A5,9x,5(1PE10.3,2X))')'Perdu', rloss_tot(jsopal),rloss_tot(jsclay),rloss_tot(jspoc) &
+            & +rloss_tot(jspos)+rloss_tot(jspor),rloss_tot(jscal),rloss_tot(jsfeo)+rloss_tot(jsfes)
+         WRITE(numsed,*)'Diss. output : Si,     O2,        DIC,          Nit,       Phos,        Fe '  
+         WRITE(numsed,'(A7,2x,6(1PE10.3,2X))')'To kbot', diss_out_tot(jwsil), &
+            & diss_out_tot(jwoxy), diss_out_tot(jwdic), diss_out_tot(jwno3), diss_out_tot(jwpo4), diss_out_tot(jwfe2)
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'Final solid  Masses (mole/dx.dy) '
+         WRITE(numsed,*)'    Opale,      Clay,       POC,        CaCO3,      Fe'
+         WRITE(numsed,'(4x,5(1PE10.3,2X))')zsolcp_inv_f(jsopal),zsolcp_inv_f(jsclay),zsolcp_inv_f(jspoc)  &
+            & +zsolcp_inv_f(jspos)+zsolcp_inv_f(jspor),zsolcp_inv_f(jscal),zsolcp_inv_f(jsfeo)+zsolcp_inv_f(jsfes)
+         WRITE(numsed,*)' '
+         WRITE(numsed,*)'Final dissolved  Masses (mole/dx.dy) (k=2-11)'
+         WRITE(numsed,*)'    Si,        O2,         DIC,        Nit,        Phos,        Fe'
+         WRITE(numsed,'(4x,6(1PE10.3,2X))') zpwcp_inv_f(jwsil), zpwcp_inv_f(jwoxy), &
+            & zpwcp_inv_f(jwdic), zpwcp_inv_f(jwno3), zpwcp_inv_f(jwpo4), zpwcp_inv_f(jwfe2)
+         WRITE(numsed,*)' '     
+         WRITE(numsed,*)'Delta : Opale,      Clay,       C,         Fe,          S,'
+         WRITE(numsed,'(7x,6(1PE11.3,1X))') zdelta_sil / ( zsolcp_inv_i(jsopal) + zpwcp_inv_i(jwsil) ) , &
+         &            zdelta_clay / ( zsolcp_inv_i(jsclay) ) ,      & 
+         &            zdelta_co2 / ( zsolcp_inv_i(jspoc) + zsolcp_inv_i(jspos) + zsolcp_inv_i(jspor) &
+         &          + zsolcp_inv_i(jscal) + zpwcp_inv_i(jwdic) ),     &
+         &            zdelta_fe / ( zpwcp_inv_i(jwfe2) + zsolcp_inv_i(jsfeo) + zsolcp_inv_i(jsfes) ) ,  &
+         &            zdelta_no3 / ( zpwcp_inv_i(jwso4) + zpwcp_inv_i(jwh2s) + zsolcp_inv_i(jsfes) )
+         WRITE(numsed,*)'=========================================================================='
+
+      ENDIF
+      ENDIF
+
+      IF( ln_timing )  CALL timing_stop('sed_mbc')
+  
+   END SUBROUTINE sed_mbc
+
+END MODULE sedmbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmodel.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmodel.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedmodel.F90	(revision 14097)
@@ -0,0 +1,43 @@
+MODULE sedmodel
+   !!======================================================================
+   !!                       ***  MODULE sedmodel   ***
+   !!   Sediment model : Main routine of sediment model 
+   !!======================================================================
+   USE sed
+   USE sedstp   ! time stepping
+   USE sedinitrc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Routine accessibility
+   PUBLIC sed_model  ! called by step.F90
+
+CONTAINS
+
+   SUBROUTINE sed_model ( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sed_model  ***
+      !!
+      !! ** Purpose :   main routine of sediment model
+      !!
+      !!
+      !! ** Method  : - model general initialization
+      !!              - launch the time-stepping (stp routine)
+      !!
+      !!   History :
+      !!        !  07-02 (C. Ethe)  Original
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+
+
+      IF( ln_timing )  CALL timing_start('sed_model')
+
+      IF( kt == nittrc000 ) CALL sed_initrc       ! Initialization of sediment model
+                            CALL sed_stp( kt )  ! Time stepping of Sediment model
+
+      IF( ln_timing )  CALL timing_stop('sed_model')
+
+   END SUBROUTINE sed_model
+
+END MODULE sedmodel
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedorg.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedorg.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedorg.F90	(revision 14097)
@@ -0,0 +1,159 @@
+MODULE sedorg
+   !!======================================================================
+   !!              ***  MODULE  seddsr  ***
+   !!    Sediment : dissolution and reaction in pore water related 
+   !!    related to organic matter
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sed_oce
+   USE sedini
+   USE seddiff
+   USE seddsr
+   USE lib_mpp         ! distribued memory computing library
+   USE lib_fortran
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC sed_org
+
+   !! * Module variables
+
+   REAL(wp) :: zadsnh4
+
+   !! $Id$
+CONTAINS
+   
+   SUBROUTINE sed_org( kt ) 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_org  ***
+      !! 
+      !!  ** Purpose :  computes pore water diffusion and reaction
+      !!
+      !!  ** Methode :  Computation of the redox reactions in sediment.
+      !!                The main redox reactions are solved in sed_dsr whereas
+      !!                the secondary reactions are solved in sed_dsr_redoxb.
+      !!                A strand spliting approach is being used here (see 
+      !!                sed_dsr_redoxb for more information). 
+      !!                Diffusive fluxes are computed in sed_diff
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) f90
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!        !  19-08 (O. Aumont) Debugging and improvement of the model.
+      !!                             The original method is replaced by a 
+      !!                             Strand splitting method which deals 
+      !!                             well with stiff reactions.
+      !!----------------------------------------------------------------------
+      !! Arguments
+      INTEGER, INTENT(in) ::   kt
+      ! --- local variables
+      INTEGER  :: ji, jk, js, jw, jnt   ! dummy looop indices
+      REAL(wp) :: zadsnh4
+      !!
+      !!----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_org')
+!
+      IF( kt == nitsed000 ) THEN
+         IF (lwp) THEN
+            WRITE(numsed,*) ' sed_org : Organic degradation related reactions and diffusion'
+            WRITE(numsed,*) ' '
+         ENDIF
+!         ! 
+         dens_mol_wgt(1:jpsol) = denssol / mol_wgt(1:jpsol)
+         ! 
+      ENDIF
+
+      dtsed2 = dtsed / REAL( nrseddt, wp )
+
+      ! 1. Change of geometry
+      !    Increase of dz3d(2) thickness : dz3d(2) = dz3d(2)+dzdep
+      !    Warning : no change for dz(2)
+      !---------------------------------------------------------
+      dz3d(1:jpoce,2) = dz3d(1:jpoce,2) + dzdep(1:jpoce)
+
+      ! New values for volw3d(:,2) and vols3d(:,2)
+      ! Warning : no change neither for volw(2) nor  vols(2)
+      !------------------------------------------------------
+      volw3d(1:jpoce,2) = dz3d(1:jpoce,2) * por(2)
+      vols3d(1:jpoce,2) = dz3d(1:jpoce,2) * por1(2)
+
+      ! 2. Change of previous solid fractions (due to volum changes) for k=2
+      !---------------------------------------------------------------------
+
+      DO js = 1, jpsol
+         DO ji = 1, jpoce
+            solcp(ji,2,js) = solcp(ji,2,js) * dz(2) / dz3d(ji,2)
+         ENDDO
+      END DO
+
+      ! 3. New solid fractions (including solid rain fractions) for k=2
+      !------------------------------------------------------------------
+      DO js = 1, jpsol
+         DO ji = 1, jpoce
+            IF (raintg(ji) .ne. 0) THEN
+               solcp(ji,2,js) = solcp(ji,2,js) + &
+               &           ( rainrg(ji,js) / raintg(ji) ) * ( dzdep(ji) / dz3d(ji,2) )
+               ! rainrm are temporary cancel
+               rainrm(ji,js) = 0.
+            ENDIF
+         END DO
+      ENDDO
+
+      ! 4.  Adjustment of bottom water concen.(pwcp(1)):
+      !     We impose that pwcp(2) is constant. Including dzdep in dz3d(:,2) we assume
+      !     that dzdep has got a porosity of por(2). So pore water volum of jk=2 increase.
+      !     To keep pwcp(2) cste we must compensate this "increase" by a slight adjusment
+      !     of bottom water concentration.
+      !     This adjustment is compensate at the end of routine
+      !-------------------------------------------------------------
+      DO jw = 1, jpwat
+         DO ji = 1, jpoce
+            pwcp(ji,1,jw) = pwcp(ji,1,jw) - &
+               &            pwcp(ji,2,jw) * dzdep(ji) * por(2) / ( dzkbot(ji) + rtrn )
+         END DO
+      ENDDO
+
+      zadsnh4 = 1.0 / ( 1.0 + adsnh4 )
+
+      ! --------------------------------------------------
+      ! Computation of the diffusivities
+      ! --------------------------------------------------
+
+      DO js = 1, jpwat
+         DO jk = 1, jpksed
+            DO ji = 1, jpoce
+               diff(ji,jk,js) = ( diff1(js) + diff2(js) * temp(ji) ) / ( 1.0 - 2.0 * log( por(jk) ) )
+            END DO
+         END DO
+      END DO
+
+      ! Impact of bioirrigation and adsorption on diffusion
+      ! ---------------------------------------------------
+
+      diff(:,:,jwnh4) = diff(:,:,jwnh4) * ( 1.0 + irrig(:,:) ) * zadsnh4
+      diff(:,:,jwsil) = diff(:,:,jwsil) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwoxy) = diff(:,:,jwoxy) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwdic) = diff(:,:,jwdic) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwno3) = diff(:,:,jwno3) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwpo4) = diff(:,:,jwpo4) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwalk) = diff(:,:,jwalk) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwh2s) = diff(:,:,jwh2s) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwso4) = diff(:,:,jwso4) * ( 1.0 + irrig(:,:) )
+      diff(:,:,jwfe2) = diff(:,:,jwfe2) * ( 1.0 + 0.2 * irrig(:,:) )
+
+      DO jnt = 1, nrseddt
+         CALL sed_diff( kt, jnt )        ! 1st pass in diffusion to get values at t+1/2
+         CALL sed_dsr ( kt, jnt )        ! Dissolution reaction
+         CALL sed_diff( kt, jnt )        ! 2nd pass in diffusion to get values at t+1
+      END DO
+
+
+      IF( ln_timing )  CALL timing_stop('sed_org')
+!      
+   END SUBROUTINE sed_org
+
+END MODULE sedorg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedrst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedrst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedrst.F90	(revision 14097)
@@ -0,0 +1,413 @@
+MODULE sedrst
+   !!======================================================================
+   !!                       *** MODULE sedrst ***
+   !!   Read and write the restart files for sediment
+   !!======================================================================
+
+   !!----------------------------------------------------------------------
+   !! * Modules used
+   !! ==============
+   USE sed
+   USE sedarr
+   USE trc_oce, ONLY : l_offline, nn_dttrc
+   USE phycst , ONLY : rday
+   USE iom
+   USE daymod
+   USE lib_mpp         ! distribued memory computing library
+
+
+   !! * Accessibility
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Accessibility
+   PUBLIC sed_rst_opn       ! called by ???
+   PUBLIC sed_rst_read
+   PUBLIC sed_rst_wri
+   PUBLIC sed_rst_cal
+
+   !! $Id$
+CONTAINS
+
+
+   SUBROUTINE sed_rst_opn( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  sed_rst_opn  ***
+      !!
+      !! ** purpose  :   output of sed-trc variable in a netcdf file
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      !
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step define as a character
+      CHARACTER(LEN=50)   ::   clname   ! trc output restart file name
+      CHARACTER(LEN=256)  ::   clpath   ! full path to ocean output restart file
+      !!----------------------------------------------------------------------
+      !
+      IF( l_offline ) THEN
+         IF( kt == nittrc000 ) THEN
+            lrst_sed = .FALSE.
+            IF( ln_rst_list ) THEN
+               nrst_lst = 1
+               nitrst = nn_stocklist( nrst_lst )
+            ELSE
+               nitrst = nitend
+            ENDIF
+         ENDIF
+         IF( .NOT. ln_rst_list .AND. MOD( kt - 1, nn_stock ) == 0 ) THEN
+            ! we use kt - 1 and not kt - nittrc000 to keep the same periodicity from the beginning of the experiment
+            nitrst = kt + nn_stock - 1                  ! define the next value of nitrst for restart writing
+            IF( nitrst > nitend )   nitrst = nitend   ! make sure we write a restart at the end of the run
+         ENDIF
+      ELSE
+         IF( kt == nittrc000 ) lrst_sed = .FALSE.
+      ENDIF
+
+      IF( .NOT. ln_rst_list .AND. nn_stock == -1 )   RETURN   ! we will never do any restart
+
+      ! to get better performances with NetCDF format:
+      ! we open and define the tracer restart file one tracer time step before writing the data (-> at nitrst - 2*nn_dttrc + 1)
+      ! except if we write tracer restart files every tracer time step or if a tracer restart file was writen at nitend - 2*nn_dttrc + 1
+      IF( kt == nitrst - 2*nn_dtsed .OR. nn_stock == nn_dtsed .OR. ( kt == nitend - nn_dtsed .AND. .NOT. lrst_sed ) ) THEN
+         ! beware of the format used to write kt (default is i8.8, that should be large enough)
+         IF( nitrst > 1.0e9 ) THEN   ;   WRITE(clkt,*       ) nitrst
+         ELSE                        ;   WRITE(clkt,'(i8.8)') nitrst
+         ENDIF
+         ! create the file
+         IF(lwp) WRITE(numsed,*)
+         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_sedrst_out)
+         clpath = TRIM(cn_sedrst_outdir)
+         IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+         IF(lwp) WRITE(numsed,*) &
+             '             open sed restart.output NetCDF file: ',TRIM(clpath)//clname
+         CALL iom_open( TRIM(clpath)//TRIM(clname), numrsw, ldwrt = .TRUE., kdlev = jpksed )
+         lrst_sed = .TRUE.
+      ENDIF
+      !
+   END SUBROUTINE sed_rst_opn
+
+   SUBROUTINE sed_rst_read 
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_rst_read  ***
+      !!
+      !! ** Purpose :  Initialization of sediment module
+      !!               - sets initial sediment composition
+      !!                 ( only clay or reading restart file )
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  original
+      !!----------------------------------------------------------------------
+
+      !! * local declarations
+      INTEGER :: ji, jj, jk, jn 
+      REAL(wp), DIMENSION(jpi,jpj,jpksed,jptrased) :: zdta
+      REAL(wp), DIMENSION(jpi,jpj,jpksed,2)        :: zdta1 
+      REAL(wp), DIMENSION(jpi,jpj,jpksed)          :: zdta2
+      REAL(wp), DIMENSION(jpoce,jpksed)            :: zhipor
+      REAL(wp) :: zkt
+      CHARACTER(len = 20) ::   cltra
+      CHARACTER(LEN=20)   ::   name1
+      LOGICAL             ::   llok
+      !--------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_rst_read')
+
+      IF (lwp) WRITE(numsed,*) ' '      
+      IF (lwp) WRITE(numsed,*) ' Initilization of Sediment components from restart'
+      IF (lwp) WRITE(numsed,*) ' '
+
+      zdta  = 1.
+      zdta1 = 1.
+      zdta2 = 0.
+
+      DO jn = 1, jptrased
+         cltra = TRIM(sedtrcd(jn))
+         IF( iom_varid( numrsr, TRIM(cltra) , ldstop = .FALSE. ) > 0 ) THEN
+            CALL iom_get( numrsr, jpdom_autoglo, TRIM(cltra), zdta(:,:,:,jn) )
+         ELSE
+            zdta(:,:,:,jn) = 0.0
+         ENDIF
+      ENDDO
+
+      DO jn = 1, jpsol
+         CALL pack_arr( jpoce, solcp(1:jpoce,1:jpksed,jn), &
+         &              zdta(1:jpi,1:jpj,1:jpksed,jn), iarroce(1:jpoce) )
+      END DO
+
+      DO jn = 1, jpwat
+         CALL pack_arr( jpoce, pwcp(1:jpoce,1:jpksed,jn), &
+         &              zdta(1:jpi,1:jpj,1:jpksed,jpsol+jn), iarroce(1:jpoce) )
+      END DO
+
+      DO jn = 1, 2
+         cltra = TRIM(seddia3d(jn))
+         IF( iom_varid( numrsr, TRIM(cltra) , ldstop = .FALSE. ) > 0 ) THEN
+            CALL iom_get( numrsr, jpdom_autoglo, TRIM(cltra), zdta1(:,:,:,jn) )
+         ELSE
+            zdta1(:,:,:,jn) = 0.0
+         ENDIF
+      ENDDO
+
+      zhipor(:,:) = 0.
+      CALL pack_arr( jpoce, zhipor(1:jpoce,1:jpksed), &
+         &             zdta1(1:jpi,1:jpj,1:jpksed,1), iarroce(1:jpoce) )
+
+      ! Initialization of [h+] in mol/kg
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            hipor (ji,jk) = 10.**( -1. * zhipor(ji,jk) )
+         ENDDO
+      ENDDO
+
+      CALL pack_arr( jpoce, co3por(1:jpoce,1:jpksed), &
+         &             zdta1(1:jpi,1:jpj,1:jpksed,2), iarroce(1:jpoce) )
+
+      ! Initialization of sediment composant only ie jk=2 to jk=jpksed 
+      ! ( nothing in jk=1)
+      solcp(1:jpoce,1,:) = 0.
+      pwcp (1:jpoce,1,:) = 0.
+
+      cltra = "dbioturb"
+      IF( iom_varid( numrsr, TRIM(cltra) , ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numrsr, jpdom_autoglo, TRIM(cltra), zdta2(:,:,:) )
+      ELSE
+         zdta2(:,:,:) = 0.0
+      ENDIF
+
+      CALL pack_arr( jpoce, db(1:jpoce,1:jpksed), &
+         &             zdta2(1:jpi,1:jpj,1:jpksed), iarroce(1:jpoce) )
+
+      cltra = "irrig"
+      IF( iom_varid( numrsr, TRIM(cltra) , ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numrsr, jpdom_autoglo, TRIM(cltra), zdta2(:,:,:) )
+      ELSE
+         zdta2(:,:,:) = 0.0
+      ENDIF
+
+      CALL pack_arr( jpoce, irrig(1:jpoce,1:jpksed), &
+         &             zdta2(1:jpi,1:jpj,1:jpksed), iarroce(1:jpoce) )
+
+      cltra = "sedligand"
+      IF( iom_varid( numrsr, TRIM(cltra) , ldstop = .FALSE. ) > 0 ) THEN
+         CALL iom_get( numrsr, jpdom_autoglo, TRIM(cltra), zdta2(:,:,:) )
+      ELSE
+         zdta2(:,:,:) = 0.0
+      ENDIF
+
+      CALL pack_arr( jpoce, sedligand(1:jpoce,1:jpksed), &
+         &             zdta2(1:jpi,1:jpj,1:jpksed), iarroce(1:jpoce) )
+
+      IF( ln_timing )  CALL timing_stop('sed_rst_read')
+     
+   END SUBROUTINE sed_rst_read
+
+   SUBROUTINE sed_rst_wri( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_rst_wri  ***
+      !!
+      !! ** Purpose :  save field which are necessary for sediment restart
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  original
+      !!----------------------------------------------------------------------
+      !!* Modules used
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      !! * local declarations
+      INTEGER  :: ji, jj, jk, jn
+      REAL(wp), DIMENSION(1) ::  zinfo
+      CHARACTER(len=50) :: clname
+      CHARACTER(len=20) :: cltra, name1 
+      REAL(wp), DIMENSION(jpoce,jpksed)   :: zdta   
+      REAL(wp), DIMENSION(jpi,jpj,jpksed) :: zdta2
+      !! -----------------------------------------------------------------------
+
+      IF( ln_timing )  CALL timing_start('sed_rst_wri')
+
+         !! 0. initialisations
+         !! ------------------
+         
+      IF(lwp) WRITE(numsed,*) ' '
+      IF(lwp) WRITE(numsed,*) 'sed_rst_write : write the sediment restart file in NetCDF format ',   &
+            'at it= ',kt
+      IF(lwp) WRITE(numsed,*) '~~~~~~~~~'
+
+
+      trcsedi(:,:,:,:)   = 0.0
+      flxsedi3d(:,:,:,:) = 0.0
+      zdta(:,:)          = 1.0
+      zdta2(:,:,:)       = 0.0
+
+         
+      !! 1. WRITE in nutwrs
+      !! ------------------
+
+      zinfo(1) = REAL( kt)
+      CALL iom_rstput( kt, nitrst, numrsw, 'kt', zinfo  )
+
+      ! Back to 2D geometry
+      DO jn = 1, jpsol
+         CALL unpack_arr( jpoce, trcsedi(1:jpi,1:jpj,1:jpksed,jn) , iarroce(1:jpoce), &
+         &                       solcp(1:jpoce,1:jpksed,jn ) )
+      END DO
+
+      DO jn = 1, jpwat
+         CALL unpack_arr( jpoce, trcsedi(1:jpi,1:jpj,1:jpksed,jpsol+jn) , iarroce(1:jpoce), &
+         &                       pwcp(1:jpoce,1:jpksed,jn  )  )
+      END DO
+      ! pH
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zdta(ji,jk) = -LOG10( hipor(ji,jk) / ( densSW(ji) + rtrn ) + rtrn )
+         ENDDO
+      ENDDO
+
+      CALL unpack_arr( jpoce, flxsedi3d(1:jpi,1:jpj,1:jpksed,1)  , iarroce(1:jpoce), &
+      &                   zdta(1:jpoce,1:jpksed)  )
+         
+      CALL unpack_arr( jpoce, flxsedi3d(1:jpi,1:jpj,1:jpksed,2)  , iarroce(1:jpoce), &
+      &                   co3por(1:jpoce,1:jpksed)  )
+
+      ! prognostic variables
+      ! --------------------
+
+      DO jn = 1, jptrased
+         cltra = TRIM(sedtrcd(jn))
+         CALL iom_rstput( kt, nitrst, numrsw, TRIM(cltra), trcsedi(:,:,:,jn) )
+      ENDDO
+
+      DO jn = 1, 2
+         cltra = TRIM(seddia3d(jn))
+         CALL iom_rstput( kt, nitrst, numrsw, TRIM(cltra), flxsedi3d(:,:,:,jn) )
+      ENDDO
+
+      CALL unpack_arr( jpoce, zdta2(1:jpi,1:jpj,1:jpksed)  , iarroce(1:jpoce), &
+      &                   db(1:jpoce,1:jpksed)  )
+
+      cltra = "dbioturb"
+      CALL iom_rstput( kt, nitrst, numrsw, TRIM(cltra), zdta2(:,:,:) )
+
+      CALL unpack_arr( jpoce, zdta2(1:jpi,1:jpj,1:jpksed)  , iarroce(1:jpoce), &
+      &                   irrig(1:jpoce,1:jpksed)  )
+
+      cltra = "irrig"
+      CALL iom_rstput( kt, nitrst, numrsw, TRIM(cltra), zdta2(:,:,:) )
+
+      CALL unpack_arr( jpoce, zdta2(1:jpi,1:jpj,1:jpksed)  , iarroce(1:jpoce), &
+      &                   sedligand(1:jpoce,1:jpksed)  )
+
+      cltra = "sedligand"
+      CALL iom_rstput( kt, nitrst, numrsw, TRIM(cltra), zdta2(:,:,:) )
+
+      IF( kt == nitrst ) THEN
+          CALL iom_close( numrsw )     ! close the restart file (only at last time step)
+          IF( l_offline .AND. ln_rst_list ) THEN
+             nrst_lst = nrst_lst + 1
+             nitrst = nn_stocklist( nrst_lst )
+          ENDIF
+      ENDIF
+
+      IF( ln_timing )  CALL timing_stop('sed_rst_wri')
+         
+   END SUBROUTINE sed_rst_wri
+
+
+   SUBROUTINE sed_rst_cal( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_rst_cal  ***
+      !!
+      !!  ** Purpose : Read or write calendar in restart file:
+      !!
+      !!  WRITE(READ) mode:
+      !!       kt        : number of time step since the begining of the experiment at the
+      !!                   end of the current(previous) run
+      !!       adatrj(0) : number of elapsed days since the begining of the experiment at the
+      !!                   end of the current(previous) run (REAL -> keep fractions of day)
+      !!       ndastp    : date at the end of the current(previous) run (coded as yyyymmdd integer)
+      !!
+      !!   According to namelist parameter nrstdt,
+      !!       nn_rsttr = 0  no control on the date (nittrc000 is  arbitrary).
+      !!       nn_rsttr = 1  we verify that nittrc000 is equal to the last
+      !!                   time step of previous run + 1.
+      !!       In both those options, the  exact duration of the experiment
+      !!       since the beginning (cumulated duration of all previous restart runs)
+      !!       is not stored in the restart and is assumed to be (nittrc000-1)*rdt.
+      !!       This is valid is the time step has remained constant.
+      !!
+      !!       nn_rsttr = 2  the duration of the experiment in days (adatrj)
+      !!                    has been stored in the restart file.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      !
+      LOGICAL  ::  llok
+      REAL(wp) ::  zkt, zrdttrc1
+      REAL(wp) ::  zndastp
+
+      ! Time domain : restart
+      ! ---------------------
+
+      IF( TRIM(cdrw) == 'READ' ) THEN
+
+         IF(lwp) WRITE(numsed,*)
+         IF(lwp) WRITE(numsed,*) 'sed_rst_cal : read the SED restart file for calendar'
+         IF(lwp) WRITE(numsed,*) '~~~~~~~~~~~~'
+
+         IF( ln_rst_sed ) THEN
+            CALL iom_open( TRIM(cn_sedrst_indir)//'/'//cn_sedrst_in, numrsr )
+            CALL iom_get ( numrsr, 'kt', zkt )   ! last time-step of previous run
+
+            IF(lwp) THEN
+               WRITE(numsed,*) ' *** Info read in restart : '
+               WRITE(numsed,*) '   previous time-step                               : ', NINT( zkt )
+               WRITE(numsed,*) ' *** restart option'
+               SELECT CASE ( nn_rstsed )
+               CASE ( 0 )   ;   WRITE(numsed,*) ' nn_rstsed = 0 : no control of nittrc000'
+               CASE ( 1 )   ;   WRITE(numsed,*) ' nn_rstsed = 1 : no control the date at nittrc000 (use ndate0 read in the namelist)'
+               CASE ( 2 )   ;   WRITE(numsed,*) ' nn_rstsed = 2 : calendar parameters read in restart'
+               END SELECT
+               WRITE(numsed,*)
+            ENDIF
+            ! Control of date 
+            IF( nittrc000  - NINT( zkt ) /= nn_dtsed .AND.  nn_rstsed /= 0 )                                  &
+               &   CALL ctl_stop( ' ===>>>> : problem with nittrc000 for the restart',                 &
+               &                  ' verify the restart file or rerun with nn_rsttr = 0 (namelist)' )
+         ENDIF
+         !
+         IF( l_offline ) THEN
+            !                                          ! set the date in offline mode
+            IF( ln_rst_sed .AND. nn_rstsed == 2 ) THEN
+               CALL iom_get( numrsr, 'ndastp', zndastp )
+               ndastp = NINT( zndastp )
+               CALL iom_get( numrsr, 'adatrj', adatrj  )
+             ELSE
+               ndastp = ndate0 - 1     ! ndate0 read in the namelist in dom_nam
+               adatrj = ( REAL( nittrc000-1, wp ) * rdt ) / rday
+               ! note this is wrong if time step has changed during run
+            ENDIF
+            !
+            IF(lwp) THEN
+              WRITE(numsed,*) ' *** Info used values : '
+              WRITE(numsed,*) '   date ndastp                                      : ', ndastp
+              WRITE(numsed,*) '   number of elapsed days since the begining of run : ', adatrj
+              WRITE(numsed,*)
+            ENDIF
+            !
+            CALL day_init          ! compute calendar
+            !
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
+         !
+         IF(  kt == nitrst ) THEN
+            IF(lwp) WRITE(numsed,*)
+            IF(lwp) WRITE(numsed,*) 'trc_wri : write the TOP restart file (NetCDF) at it= ', kt, ' date= ', ndastp
+            IF(lwp) WRITE(numsed,*) '~~~~~~~'
+         ENDIF
+         CALL iom_rstput( kt, nitrst, numrsw, 'kt'     , REAL( kt    , wp) )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrsw, 'ndastp' , REAL( ndastp, wp) )   ! date
+         CALL iom_rstput( kt, nitrst, numrsw, 'adatrj' , adatrj            )   ! number of elapsed days since
+         !                                                                     ! the begining of the run [s]
+      ENDIF
+
+   END SUBROUTINE sed_rst_cal
+
+END MODULE sedrst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedsfc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedsfc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedsfc.F90	(revision 14097)
@@ -0,0 +1,67 @@
+MODULE sedsfc
+   !!======================================================================
+   !!              ***  MODULE  sedsfc  ***
+   !!    Sediment : Data at sediment surface
+   !!=====================================================================
+   !! * Modules used
+   USE sed     ! sediment global variable
+   USE sedarr
+   USE seddta
+
+   PUBLIC sed_sfc
+
+   !! $Id$
+CONTAINS
+
+   SUBROUTINE sed_sfc( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sed_sfc ***
+      !!
+      !! ** Purpose :  Give data from sediment model to tracer model
+      !!
+      !!
+      !!   History :
+      !!        !  06-04 (C. Ethe)  Orginal code
+      !!----------------------------------------------------------------------
+      !!* Arguments
+      INTEGER, INTENT(in) ::  kt              ! time step
+
+      ! * local variables
+      INTEGER :: ji, jj, ikt     ! dummy loop indices
+
+      !------------------------------------------------------------------------
+      ! reading variables
+
+      IF( ln_timing )  CALL timing_start('sed_sfc')
+
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,1), iarroce(1:jpoce), pwcp(1:jpoce,1,jwalk) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,2), iarroce(1:jpoce), pwcp(1:jpoce,1,jwdic) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,3), iarroce(1:jpoce), pwcp(1:jpoce,1,jwno3) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,4), iarroce(1:jpoce), pwcp(1:jpoce,1,jwpo4) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,5), iarroce(1:jpoce), pwcp(1:jpoce,1,jwoxy) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,6), iarroce(1:jpoce), pwcp(1:jpoce,1,jwsil) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,7), iarroce(1:jpoce), pwcp(1:jpoce,1,jwnh4) )
+      CALL unpack_arr ( jpoce, trc_data(1:jpi,1:jpj,8), iarroce(1:jpoce), pwcp(1:jpoce,1,jwfe2) )
+
+
+      DO jj = 1,jpj
+         DO ji = 1, jpi
+            ikt = mbkt(ji,jj)
+            IF ( tmask(ji,jj,ikt) == 1 ) THEN
+               trb(ji,jj,ikt,jptal) = trc_data(ji,jj,1)
+               trb(ji,jj,ikt,jpdic) = trc_data(ji,jj,2)
+               trb(ji,jj,ikt,jpno3) = trc_data(ji,jj,3) * 7.625
+               trb(ji,jj,ikt,jppo4) = trc_data(ji,jj,4) * 122.
+               trb(ji,jj,ikt,jpoxy) = trc_data(ji,jj,5)
+               trb(ji,jj,ikt,jpsil) = trc_data(ji,jj,6)
+               trb(ji,jj,ikt,jpnh4) = trc_data(ji,jj,7) * 7.625
+               trb(ji,jj,ikt,jpfer) = trc_data(ji,jj,8)
+            ENDIF
+         ENDDO
+      ENDDO
+
+      IF( ln_timing )  CALL timing_stop('sed_sfc')
+
+   END SUBROUTINE sed_sfc
+
+END MODULE sedsfc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedstp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedstp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedstp.F90	(revision 14097)
@@ -0,0 +1,97 @@
+MODULE sedstp
+   !!======================================================================
+   !!                       ***  MODULE sedstp   ***
+   !!   Sediment model : Sediment model time-stepping
+   !!======================================================================
+   USE sed      ! sediment global variables
+   USE seddta   ! data read
+   USE sedchem  ! chemical constant
+   USE sedco3   ! carbonate in sediment pore water
+   USE sedorg   ! Organic reactions and diffusion
+   USE sedinorg ! Inorganic dissolution
+   USE sedbtb   ! bioturbation
+   USE sedadv   ! vertical advection
+   USE sedmbc   ! mass balance calculation
+   USE sedsfc   ! sediment surface data
+   USE sedrst   ! restart
+   USE sedwri   ! outputs
+   USE trcdmp_sed
+   USE lib_mpp         ! distribued memory computing library
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Routine accessibility
+   PUBLIC sed_stp  ! called by step.F90
+
+   !! $Id$
+CONTAINS
+
+   SUBROUTINE sed_stp ( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sed_stp  ***
+      !!
+      !! ** Purpose :   Sediment time stepping
+      !!                Simulation of pore water chemistry
+      !!
+      !! ** Action  :
+      !!
+      !!
+      !!   History :
+      !!        !  98-08 (E. Maier-Reimer, Christoph Heinze )  Original code
+      !!        !  04-10 (N. Emprin, M. Gehlen ) coupled with PISCES
+      !!        !  06-04 (C. Ethe)  Re-organization
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      INTEGER :: ji,jk,js,jn,jw
+      !!----------------------------------------------------------------------
+      IF( ln_timing )      CALL timing_start('sed_stp')
+        !
+                                CALL sed_rst_opn  ( kt )       ! Open tracer restart file 
+      IF( lrst_sed )            CALL sed_rst_cal  ( kt, 'WRITE' )   ! calenda
+
+      IF(ln_sediment_offline)   CALL trc_dmp_sed  ( kt )
+
+      dtsed  = r2dttrc
+!      dtsed2 = dtsed
+      IF (kt /= nitsed000) THEN
+         CALL sed_dta( kt )       ! Load  Data for bot. wat. Chem and fluxes
+      ENDIF
+
+      IF (sedmask == 1. ) THEN
+         IF( kt /= nitsed000 )  THEN
+           CALL sed_chem( kt )      ! update of chemical constant to account for salinity, temperature changes
+         ENDIF
+
+         CALL sed_btb( kt )         ! 1st pass of bioturbation at t+1/2
+         CALL sed_org( kt )         ! Organic related reactions and diffusion
+         CALL sed_inorg( kt )       ! Dissolution reaction
+         CALL sed_btb( kt )         ! 2nd pass of bioturbation at t+1
+         tokbot(:,:) = 0.0
+         DO jw = 1, jpwat
+            DO ji = 1, jpoce
+               tokbot(ji,jw) = pwcp(ji,1,jw) * 1.e-3 * dzkbot(ji)
+            END DO
+         ENDDO
+         CALL sed_adv( kt )         ! advection
+         CALL sed_co3( kt )         ! pH actualization for saving
+         ! This routine is commented out since it does not work at all
+         CALL sed_mbc( kt )         ! cumulation for mass balance calculation
+
+         IF (ln_sed_2way) CALL sed_sfc( kt )         ! Give back new bottom wat chem to tracer model
+      ENDIF
+      CALL sed_wri( kt )         ! outputs
+      IF( kt == nitsed000 ) THEN
+          CALL iom_close( numrsr )       ! close input tracer restart file
+!          IF(lwm) CALL FLUSH( numont )   ! flush namelist output
+      ENDIF
+      IF( lrst_sed )            CALL sed_rst_wri( kt )   ! restart file output
+
+      IF( kt == nitsedend )  CLOSE( numsed )
+
+      IF( ln_timing )   CALL timing_stop('sed_stp')
+
+   END SUBROUTINE sed_stp
+
+END MODULE sedstp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedwri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedwri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/sedwri.F90	(revision 14097)
@@ -0,0 +1,138 @@
+MODULE sedwri
+   !!======================================================================
+   !!                     ***  MODULE  sedwri  ***
+   !!         Sediment diagnostics :  write sediment output files
+   !!======================================================================
+   USE sed
+   USE sedarr
+   USE lib_mpp         ! distribued memory computing library
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   !! * Accessibility
+   PUBLIC sed_wri 
+
+   !! $Id$
+CONTAINS
+
+   !!----------------------------------------------------------------------
+   !!                                                   NetCDF output file
+   !!----------------------------------------------------------------------
+   SUBROUTINE sed_wri( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE sed_wri  ***
+      !!
+      !! ** Purpose :  output of sediment passive tracer
+      !!
+      !!   History :
+      !!        !  06-07  (C. Ethe)  original
+      !!----------------------------------------------------------------------
+
+      INTEGER, INTENT(in) :: kt
+
+      INTEGER  :: ji, jj, jk, js, jw, jn
+      INTEGER  :: it
+      CHARACTER(len = 20)  ::  cltra 
+      REAL(wp)  :: zrate
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) :: zdta, zflx
+
+      !!-------------------------------------------------------------------
+
+
+      ! Initialisation
+      ! ----------------- 
+
+      ! 1.  Initilisations
+      ! -----------------------------------------------------------------
+      IF( ln_timing )  CALL timing_start('sed_wri')
+!
+      IF (lwp) WRITE(numsed,*) ' '
+      IF (lwp) WRITE(numsed,*) 'sed_wri kt = ', kt
+      IF (lwp) WRITE(numsed,*) ' '
+      
+      ALLOCATE( zdta(jpoce,jpksed) )    ;   ALLOCATE( zflx(jpoce,jpwatp1) )
+
+      ! Initialize variables
+      ! --------------------
+
+      trcsedi(:,:,:,:)   = 0.0
+      flxsedi3d(:,:,:,:) = 0.0
+      flxsedi2d(:,:,:)   = 0.0
+
+      ! 2.  Back to 2D geometry
+      ! -----------------------------------------------------------------
+      DO jn = 1, jpsol
+         CALL unpack_arr( jpoce, trcsedi(1:jpi,1:jpj,1:jpksed,jn) , iarroce(1:jpoce), &
+         &                       solcp(1:jpoce,1:jpksed,jn ) )
+      END DO
+      
+      DO jn = 1, jpwat
+         CALL unpack_arr( jpoce, trcsedi(1:jpi,1:jpj,1:jpksed,jpsol + jn) , iarroce(1:jpoce), &
+         &                       pwcp(1:jpoce,1:jpksed,jn  )  )
+      END DO      
+
+      ! porosity
+      zdta(:,:) = 0.
+      DO jk = 1, jpksed
+         DO ji = 1, jpoce
+            zdta(ji,jk) = -LOG10( hipor(ji,jk) / ( densSW(ji) + rtrn ) + rtrn )
+         ENDDO
+      ENDDO
+
+      CALL unpack_arr( jpoce, flxsedi3d(1:jpi,1:jpj,1:jpksed,1)  , iarroce(1:jpoce), &
+         &                   zdta(1:jpoce,1:jpksed)  )
+      
+      CALL unpack_arr( jpoce, flxsedi3d(1:jpi,1:jpj,1:jpksed,2)  , iarroce(1:jpoce), &
+         &                   co3por(1:jpoce,1:jpksed)  )
+      
+!      flxsedi3d = 0.
+      zflx(:,:) = 0.    
+      ! Calculation of fluxes mol/cm2/s
+      DO jw = 1, jpwat
+         DO ji = 1, jpoce
+            zflx(ji,jw) = ( pwcp(ji,1,jw) - pwcp_dta(ji,jw) ) &
+               &         * 1.e3 / 1.e2 * dzkbot(ji) / r2dttrc
+         ENDDO
+      ENDDO
+
+      ! Calculation of accumulation rate per dt
+      DO js = 1, jpsol
+         zrate =  1.0 / ( denssol * por1(jpksed) ) / r2dttrc
+         DO ji = 1, jpoce
+            zflx(ji,jpwatp1) = zflx(ji,jpwatp1) + ( tosed(ji,js) - fromsed(ji,js) ) * zrate
+         ENDDO
+      ENDDO
+
+      DO jn = 1, jpdia2dsed - 1 
+         CALL unpack_arr( jpoce, flxsedi2d(1:jpi,1:jpj,jn), iarroce(1:jpoce), zflx(1:jpoce,jn)  )
+      END DO
+      zflx(:,1) = dzdep(:) / dtsed
+      CALL unpack_arr( jpoce, flxsedi2d(1:jpi,1:jpj,jpdia2dsed), iarroce(1:jpoce), zflx(1:jpoce,1) )
+
+       ! Start writing data
+       ! ---------------------
+       DO jn = 1, jptrased
+          cltra = sedtrcd(jn) ! short title for 3D diagnostic
+          CALL iom_put( cltra, trcsedi(:,:,:,jn) )
+       END DO
+
+       DO jn = 1, jpdia3dsed
+          cltra = seddia3d(jn) ! short title for 3D diagnostic
+          CALL iom_put( cltra, flxsedi3d(:,:,:,jn) )
+       END DO
+
+       DO jn = 1, jpdia2dsed
+          cltra = seddia2d(jn) ! short title for 2D diagnostic
+          CALL iom_put( cltra, flxsedi2d(:,:,jn) )
+       END DO
+
+
+      DEALLOCATE( zdta )    ;   DEALLOCATE( zflx )
+
+      IF( ln_timing )  CALL timing_stop('sed_wri')
+
+   END SUBROUTINE sed_wri
+
+END MODULE sedwri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/trcdmp_sed.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/trcdmp_sed.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/SED/trcdmp_sed.F90	(revision 14097)
@@ -0,0 +1,157 @@
+MODULE trcdmp_sed
+   !!======================================================================
+   !!                       ***  MODULE  trcdmp  ***
+   !! Ocean physics: internal restoring trend on passive tracers
+   !!======================================================================
+   !! History :  OPA  !  1991-03  (O. Marti, G. Madec)  Original code
+   !!                 !  1996-01  (G. Madec) statement function for e3
+   !!                 !  1997-05  (H. Loukos)  adapted for passive tracers
+   !!    NEMO    9.0  !  2004-03  (C. Ethe)    free form + modules
+   !!            3.2  !  2007-02  (C. Deltel)  Diagnose ML trends for passive tracers
+   !!            3.3  !  2010-06  (C. Ethe, G. Madec) merge TRA-TRC 
+   !!----------------------------------------------------------------------
+#if  defined key_top
+   !!----------------------------------------------------------------------
+   !!   trc_dmp      : update the tracer trend with the internal damping
+   !!   trc_dmp_init : initialization, namlist read, parameters control
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! ocean dynamics and tracers variables
+   USE trc             ! ocean passive tracers variables
+   USE sed , ONLY : dtsed => dtsed      ! ocean dynamics and tracers variables
+   USE trc             ! ocean passive tracers variables
+   USE trcdta
+   USE prtctl_trc      ! Print control for debbuging
+   USE iom
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_dmp_sed      
+   PUBLIC trc_dmp_sed_alloc  
+   PUBLIC trc_dmp_sed_ini    
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   restosed   ! restoring coeff. on tracers (s-1)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trc_dmp_sed_alloc()
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dmp_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( restosed(jpi,jpj,jpk) , STAT=trc_dmp_sed_alloc )
+      !
+      IF( trc_dmp_sed_alloc /= 0 )   CALL ctl_warn('trc_dmp_sed_alloc: failed to allocate array')
+      !
+   END FUNCTION trc_dmp_sed_alloc
+
+
+   SUBROUTINE trc_dmp_sed( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dmp_sed  ***
+      !!                  
+      !! ** Purpose :   Compute the passive tracer trend due to a newtonian damping
+      !!      of the tracer field towards given data field and add it to the
+      !!      general tracer trends.
+      !!
+      !! ** Method  :   Newtonian damping towards trdta computed 
+      !!      and add to the general tracer trends:
+      !!                     trn = tra + restotr * (trdta - trb)
+      !!         The trend is computed either throughout the water column
+      !!      (nlmdmptr=0) or in area of weak vertical mixing (nlmdmptr=1) or
+      !!      below the well mixed layer (nlmdmptr=2)
+      !!
+      !! ** Action  : - update the tracer trends tra with the newtonian 
+      !!                damping trends.
+      !!              - save the trends ('key_trdmxl_trc')
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk, jn, jl, ikt   ! dummy loop indices
+      CHARACTER (len=22) ::   charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ztrcdta   ! 3D  workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('trc_dmp_sed')
+      !
+      !
+      IF( nb_trcdta > 0 ) THEN  ! Initialisation of tracer from a file that may also be used for damping
+         !
+         DO jn = 1, jptra                                           ! tracer loop
+            !                                                       ! ===========
+            IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
+               !
+               jl = n_trc_index(jn) 
+               CALL trc_dta( kt, sf_trcdta(jl), rf_trfac(jl), ztrcdta )   ! read tracer data at nit000
+               !
+               DO jj = 1, jpj
+                  DO ji = 1, jpi   ! vector opt.
+                     ikt = mbkt(ji,jj)
+                     trb(ji,jj,ikt,jn) = ztrcdta(ji,jj,ikt) + ( trb(ji,jj,ikt,jn) -  ztrcdta(ji,jj,ikt) )     &
+                     &                  * exp( -restosed(ji,jj,ikt) * dtsed )
+                  END DO
+               END DO
+               ! 
+            ENDIF
+         END DO                                                     ! tracer loop
+         !                                                          ! ===========
+      ENDIF
+      !
+      !                                          ! print mean trends (used for debugging)
+      IF( ln_ctl ) THEN
+         WRITE(charout, FMT="('dmp ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('trc_dmp_sed')
+      !
+   END SUBROUTINE trc_dmp_sed
+
+
+   SUBROUTINE trc_dmp_sed_ini
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_dmp_ini  ***
+      !! 
+      !! ** Purpose :   Initialization for the newtonian damping 
+      !!
+      !! ** Method  :   read the nammbf namelist and check the parameters
+      !!              called by trc_dmp at the first timestep (nittrc000)
+      !!----------------------------------------------------------------------
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )  CALL timing_start('trc_dmp_sed_ini')
+
+      IF (lwp) WRITE(numout,*) '   tracer damping throughout the water column'
+      !
+      IF( trc_dmp_sed_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_dmp_sed_ini: unable to allocate arrays' )
+      !
+      IF( .NOT.lk_c1d ) THEN
+         !Read in mask from file
+          restosed(:,:,:) = 0.5 / rday
+         !
+      ENDIF
+      IF( ln_timing )  CALL timing_stop('trc_dmp_sed_ini')
+     !
+   END SUBROUTINE trc_dmp_sed_ini
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_dmp_sed( kt )        ! Empty routine
+      INTEGER, INTENT(in) :: kt
+      WRITE(*,*) 'trc_dmp_sed: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_dmp_sed
+#endif
+
+   !!======================================================================
+END MODULE trcdmp_sed
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/par_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/par_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/par_pisces.F90	(revision 14097)
@@ -0,0 +1,70 @@
+MODULE par_pisces
+   !!======================================================================
+   !!                        ***  par_pisces  ***
+   !! TOP :   set the PISCES parameters
+   !!======================================================================
+   !! History :   2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+
+   IMPLICIT NONE
+
+   ! productive layer depth
+   INTEGER, PUBLIC ::   jpkb       !: first vertical layers where biology is active
+   INTEGER, PUBLIC ::   jpkbm1     !: first vertical layers where biology is active
+
+   ! assign an index in trc arrays for each LOBSTER prognostic variables
+   INTEGER, PUBLIC ::   jpdet     !: detritus                   
+   INTEGER, PUBLIC ::   jpdom     !: dissolved organic matter 
+   INTEGER, PUBLIC ::   jpdic     !: dissolved inoganic carbon concentration 
+   INTEGER, PUBLIC ::   jptal     !: total alkalinity 
+   INTEGER, PUBLIC ::   jpoxy     !: oxygen carbon concentration 
+   INTEGER, PUBLIC ::   jpcal     !: calcite  concentration 
+   INTEGER, PUBLIC ::   jppo4     !: phosphate concentration 
+   INTEGER, PUBLIC ::   jppoc     !: small particulate organic phosphate concentration
+   INTEGER, PUBLIC ::   jpsil     !: silicate concentration
+   INTEGER, PUBLIC ::   jpphy     !: phytoplancton concentration 
+   INTEGER, PUBLIC ::   jpzoo     !: zooplancton concentration
+   INTEGER, PUBLIC ::   jpdoc     !: dissolved organic carbon concentration 
+   INTEGER, PUBLIC ::   jpdia     !: Diatoms Concentration
+   INTEGER, PUBLIC ::   jpmes     !: Mesozooplankton Concentration
+   INTEGER, PUBLIC ::   jpdsi     !: Diatoms Silicate Concentration
+   INTEGER, PUBLIC ::   jpfer     !: Iron Concentration
+   INTEGER, PUBLIC ::   jpbfe     !: Big iron particles Concentration
+   INTEGER, PUBLIC ::   jpgoc     !: big particulate organic phosphate concentration
+   INTEGER, PUBLIC ::   jpsfe     !: Small iron particles Concentration
+   INTEGER, PUBLIC ::   jpdfe     !: Diatoms iron Concentration
+   INTEGER, PUBLIC ::   jpgsi     !: (big) Silicate Concentration
+   INTEGER, PUBLIC ::   jpnfe     !: Nano iron Concentration
+   INTEGER, PUBLIC ::   jpnch     !: Nano Chlorophyll Concentration
+   INTEGER, PUBLIC ::   jpdch     !: Diatoms Chlorophyll Concentration
+   INTEGER, PUBLIC ::   jpno3     !: Nitrates Concentration
+   INTEGER, PUBLIC ::   jpnh4     !: Ammonium Concentration
+   INTEGER, PUBLIC ::   jpdon     !: dissolved organic nitrogen concentration
+   INTEGER, PUBLIC ::   jpdop     !: dissolved organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppon     !: small particulate organic nitrogen concentration
+   INTEGER, PUBLIC ::   jppop     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jpnph     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppph     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jpndi     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppdi     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppic     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jpnpi     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jpppi     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppfe     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jppch     !: small particulate organic phosphorus concentration
+   INTEGER, PUBLIC ::   jpgon     !: Big nitrogen particles Concentration
+   INTEGER, PUBLIC ::   jpgop     !: Big phosphorus particles Concentration
+   INTEGER, PUBLIC ::   jplgw     !: Weak Ligands
+
+   !!---------------------------------------------------------------------
+   !!   Default                                   No CFC geochemical model
+   ! Starting/ending PISCES do-loop indices (N.B. no PISCES : jpl_pcs < jpf_pcs the do-loop are never done)
+   INTEGER, PUBLIC  ::   jp_pcs0  !: First index of PISCES tracers
+   INTEGER, PUBLIC  ::   jp_pcs1  !: Last  index of PISCES tracers
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE par_pisces
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/sms_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/sms_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/sms_pisces.F90	(revision 14097)
@@ -0,0 +1,194 @@
+MODULE sms_pisces   
+   !!----------------------------------------------------------------------
+   !!                     ***  sms_pisces.F90  ***  
+   !! TOP :   PISCES Source Minus Sink variables
+   !!----------------------------------------------------------------------
+   !! History :   1.0  !  2000-02 (O. Aumont) original code
+   !!             3.2  !  2009-04 (C. Ethe & NEMO team) style
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE par_trc
+
+   IMPLICIT NONE
+   PUBLIC
+
+   INTEGER ::   numnatp_ref = -1           !! Logical units for namelist pisces
+   INTEGER ::   numnatp_cfg = -1           !! Logical units for namelist pisces
+   INTEGER ::   numonp      = -1           !! Logical unit for namelist pisces output
+
+   !                                                       !:  PISCES  : silicon dependant half saturation
+
+   !!* Model used
+   LOGICAL  ::  ln_p2z            !: Flag to use LOBSTER model
+   LOGICAL  ::  ln_p4z            !: Flag to use PISCES  model
+   LOGICAL  ::  ln_p5z            !: Flag to use PISCES  quota model
+   LOGICAL  ::  ln_ligand         !: Flag to enable organic ligands
+   LOGICAL  ::  ln_sediment       !: Flag to enable sediment module
+
+   !!*  Time variables
+   INTEGER  ::   nrdttrc           !: ???
+   REAL(wp) ::   rfact , rfactr    !: ???
+   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 
+   REAL(wp) ::   rno3              !: ???
+   REAL(wp) ::   o2ut              !: ???
+   REAL(wp) ::   po4r              !: ???
+   REAL(wp) ::   rdenit            !: ???
+   REAL(wp) ::   rdenita           !: ???
+   REAL(wp) ::   o2nit             !: ???
+   REAL(wp) ::   wsbio, wsbio2     !: ???
+   REAL(wp) ::   wsbio2max         !: ???
+   REAL(wp) ::   wsbio2scale       !: ???
+   REAL(wp) ::   xkmort            !: ???
+   REAL(wp) ::   ferat3            !: ???
+   REAL(wp) ::   ldocp             !: ???
+   REAL(wp) ::   ldocz             !: ???
+   REAL(wp) ::   lthet             !: ???
+   REAL(wp) ::   no3rat3           !: ???
+   REAL(wp) ::   po4rat3           !: ???
+
+
+   !!*  diagnostic parameters 
+   REAL(wp) ::  tpp                !: total primary production
+   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
+
+   !!* restoring
+   LOGICAL  ::  ln_pisdmp          !: restoring or not of nutrients to a mean value
+   INTEGER  ::  nn_pisdmp          !: frequency of relaxation or not of nutrients to a mean value
+
+   !!* Mass conservation
+   LOGICAL  ::  ln_check_mass      !: Flag to check mass conservation
+   LOGICAL , PUBLIC ::   ln_ironice   !: boolean for Fe input from sea ice
+
+   !!*  Biological fluxes for light : variables shared by pisces & lobster
+   INTEGER , ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  neln  !: number of T-levels + 1 in the euphotic layer
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  heup  !: euphotic layer depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  etot  !: par (photosynthetic available radiation)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  etot_ndcy      !: PAR over 24h in case of diurnal cycle
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  enano, ediat   !: PAR for phyto, nano and diat 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  enanom, ediatm !: PAR for phyto, nano and diat 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  epico          !: PAR for pico
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  epicom         !: PAR for pico
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  emoy           !: averaged PAR in the mixed layer
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  heup_01 !: Absolute euphotic layer depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  xksi  !:  LOBSTER : zooplakton closure
+
+   !!*  Biological fluxes for primary production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)    ::   xksimax    !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   biron      !: bioavailable fraction of iron
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:)  ::   plig       !: proportion of iron organically complexed
+
+   !!*  Sinking speed
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   wsbio3   !: POC sinking speed 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   wsbio4   !: GOC sinking speed
+
+   !!*  SMS for the organic matter
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xfracal    !: ??
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   nitrfac    !: ??
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   nitrfac2   !: ??
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   orem       !: ??
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xdiss      !: ??
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   prodcal    !: Calcite production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   prodpoc    !: Calcite production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   conspoc    !: Calcite production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   prodgoc    !: Calcite production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   consgoc    !: Calcite production
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   blim       !: bacterial production factor
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sizen      !: size of diatoms 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sizep      !: size of diatoms 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   sized      !: size of diatoms 
+
+
+   !!* Variable for chemistry of the CO2 cycle
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ak13       !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ak23       !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aksp       !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   hi         !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   excess     !: ???
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   aphscale   !: 
+
+
+   !!* Temperature dependancy of SMS terms
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tgfunc    !: Temp. dependancy of various biological rates
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tgfunc2   !: Temp. dependancy of mesozooplankton rates
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION sms_pisces_alloc()
+      !!----------------------------------------------------------------------
+      !!        *** ROUTINE sms_pisces_alloc ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp , ONLY: ctl_stop
+      INTEGER ::   ierr(10)        ! Local variables
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !*  Biological fluxes for light : shared variables for pisces & lobster
+      ALLOCATE( etot(jpi,jpj,jpk), neln(jpi,jpj), heup(jpi,jpj),    &
+        &       heup_01(jpi,jpj) , xksi(jpi,jpj)               ,  STAT=ierr(1) )
+      !
+  
+      IF( ln_p4z .OR. ln_p5z ) THEN
+         !*  Biological fluxes for light 
+         ALLOCATE(  enano(jpi,jpj,jpk)    , ediat(jpi,jpj,jpk) ,   &
+           &        enanom(jpi,jpj,jpk)   , ediatm(jpi,jpj,jpk),   &
+           &        etot_ndcy(jpi,jpj,jpk), emoy(jpi,jpj,jpk)  ,  STAT=ierr(2) ) 
+
+         !*  Biological fluxes for primary production
+         ALLOCATE( xksimax(jpi,jpj)  , biron(jpi,jpj,jpk)      ,  STAT=ierr(3) )
+         !
+         !*  SMS for the organic matter
+         ALLOCATE( xfracal (jpi,jpj,jpk), orem(jpi,jpj,jpk)    ,    &
+            &      nitrfac(jpi,jpj,jpk), nitrfac2(jpi,jpj,jpk) ,    &
+            &      prodcal(jpi,jpj,jpk) , xdiss   (jpi,jpj,jpk),    &
+            &      prodpoc(jpi,jpj,jpk) , conspoc(jpi,jpj,jpk) ,    &
+            &      prodgoc(jpi,jpj,jpk) , consgoc(jpi,jpj,jpk) ,    &
+            &      blim   (jpi,jpj,jpk) ,                         STAT=ierr(4) )
+
+         !* Variable for chemistry of the CO2 cycle
+         ALLOCATE( ak13  (jpi,jpj,jpk) ,                            &
+            &      ak23(jpi,jpj,jpk)    , aksp  (jpi,jpj,jpk) ,     &
+            &      hi  (jpi,jpj,jpk)    , excess(jpi,jpj,jpk) ,     &
+            &      aphscale(jpi,jpj,jpk),                         STAT=ierr(5) )
+         !
+         !* Temperature dependancy of SMS terms
+         ALLOCATE( tgfunc(jpi,jpj,jpk)  , tgfunc2(jpi,jpj,jpk),   STAT=ierr(6) )
+         !
+         !* Sinkong speed
+         ALLOCATE( wsbio3 (jpi,jpj,jpk) , wsbio4 (jpi,jpj,jpk),     &
+            &                             STAT=ierr(7) )   
+         ! 
+         IF( ln_ligand ) THEN
+           ALLOCATE( plig(jpi,jpj,jpk)  ,                         STAT=ierr(8) )
+         ENDIF
+      ENDIF
+      !
+      IF( ln_p5z ) THEN
+         !       
+         ALLOCATE( epico(jpi,jpj,jpk)   , epicom(jpi,jpj,jpk) ,   STAT=ierr(9) ) 
+
+         !*  Size of phytoplankton cells
+         ALLOCATE( sizen(jpi,jpj,jpk), sizep(jpi,jpj,jpk),         &
+           &       sized(jpi,jpj,jpk),                            STAT=ierr(10) )
+      ENDIF
+      !
+      sms_pisces_alloc = MAXVAL( ierr )
+      !
+      IF( sms_pisces_alloc /= 0 )   CALL ctl_stop( 'STOP', 'sms_pisces_alloc: failed to allocate arrays' ) 
+      !
+   END FUNCTION sms_pisces_alloc
+
+   !!======================================================================   
+END MODULE sms_pisces    
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcice_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcice_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcice_pisces.F90	(revision 14097)
@@ -0,0 +1,352 @@
+MODULE trcice_pisces
+   !!======================================================================
+   !!                         ***  MODULE trcice_pisces  ***
+   !! TOP :   initialisation of the PISCES biochemical model
+   !!======================================================================
+   !! History :  3.5  ! 2013    (M. Vancoppenolle, O. Aumont, G. Madec), original code
+   !!----------------------------------------------------------------------
+   !! trc_ice_pisces   : PISCES fake sea ice model setting
+   !!----------------------------------------------------------------------
+   USE par_trc         ! TOP parameters
+   USE par_pisces      ! PISCES parameters
+   USE oce_trc         ! Shared variables between ocean and passive tracers
+   USE trc             ! Passive tracers common variables 
+   USE sms_pisces      ! PISCES Source Minus Sink variables
+   USE in_out_manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ice_ini_pisces ! called by trcini.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ice_ini_pisces
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_ini_pisces ***
+      !!
+      !! ** Purpose :   Initialisation of the PISCES biochemical model
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_p4z .OR. ln_p5z ) THEN  ;   CALL p4z_ice_ini   !  PISCES
+      ELSE                           ;   CALL p2z_ice_ini   !  LOBSTER
+      ENDIF
+      !
+   END SUBROUTINE trc_ice_ini_pisces
+
+
+   SUBROUTINE p4z_ice_ini
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p4z_ice_ini ***
+      !!
+      !! ** Purpose :   PISCES fake sea ice model setting
+      !!    Method  :   Assign prescribe values to tracer concentrations in sea ice
+      !!
+      !! For levitating sea ice, constant ocean tracer concentrations also have to be defined. 
+      !! This is done specifically for Global, Arctic, Antarctic and Baltic regions
+      !! 
+      !! Sea ice concentrations are by default prescribed as follows
+      !!  trc_i = zratio * trc_o
+      !!
+      !! This formulation is modulated by the namelist parameter trc_ice_ratio
+      !!
+      !! trc_ice_ratio  * betw 0 and 1: prescribed ice/ocean tracer concentration ratio
+      !!                * -1 => the ice-ocean tracer concentration ratio follows the
+      !!                         ice-ocean salinity ratio
+      !!                * -2 => no ice-ocean tracer concentration is used
+      !!                        instead, the tracer concentration in sea ice 
+      !!                        is prescribed to trc_ice_prescr
+      !! 
+      !! cn_trc_o  specifies which disinctions are made for prescribed tracer concentration
+      !!                * 'GL' use global ocean values making distinction for Baltic Sea only
+      !!                * 'AA' use Arctic/Antarctic contrasted values, + Baltic
+      !!
+      !!----------------------------------------------------------------------
+
+                                        !--- Dummy variables
+      REAL(wp), DIMENSION(jpmaxtrc,2) :: zratio  ! effective ice-ocean tracer cc ratio
+      REAL(wp), DIMENSION(jpmaxtrc,4) :: zpisc   ! prescribes concentration 
+      !                                            !  1:global, 2:Arctic, 3:Antarctic, 4:Baltic
+
+      REAL(wp), DIMENSION(2) :: zrs  ! ice-ocean salinity ratio, 1 - global, 2- Baltic
+      REAL(wp) :: zsice_bal          ! prescribed ice salinity in the Baltic
+      REAL(wp) :: zsoce_bal          ! prescribed ocean salinity in the Baltic
+      REAL(wp) :: zfeoce_glo         ! prescribed iron concentration in the global ocean
+      REAL(wp) :: zfeoce_bal         ! prescribed iron concentration in the global ocean
+      INTEGER  :: jn                 ! dummy loop index
+
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' trc_ice_ini_pisces: Prescribed sea ice biogeochemistry '
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~'
+
+      !--------------------------------------------
+      ! Initialize ocean prescribed concentrations
+      !--------------------------------------------
+      ! values taken from a 500 yr equilibrium run
+      ! used only in the levitating sea ice case with virtual salt / tracer
+      ! fluxes
+
+      !--- Global values
+      zpisc(jpdic,1) =  1.99e-3_wp 
+      zpisc(jpdoc,1) =  2.04e-5_wp 
+      zpisc(jptal,1) =  2.31e-3_wp 
+      zpisc(jpoxy,1) =  2.47e-4_wp
+      zpisc(jpcal,1) =  1.04e-8_wp
+      zpisc(jppo4,1) =  5.77e-7_wp / po4r 
+      zpisc(jppoc,1) =  1.27e-6_wp  
+      zpisc(jpgoc,1) =  5.23e-8_wp  
+      zpisc(jpbfe,1) =  9.84e-13_wp 
+      zpisc(jpsil,1) =  7.36e-6_wp  
+      zpisc(jpdsi,1) =  1.07e-7_wp 
+      zpisc(jpgsi,1) =  1.53e-8_wp
+      zpisc(jpphy,1) =  9.57e-8_wp
+      zpisc(jpdia,1) =  4.24e-7_wp
+      zpisc(jpzoo,1) =  6.07e-7_wp
+      zpisc(jpmes,1) =  3.44e-7_wp
+      zpisc(jpfer,1) =  4.06e-10_wp
+      zpisc(jpsfe,1) =  2.51e-11_wp
+      zpisc(jpdfe,1) =  6.57e-12_wp
+      zpisc(jpnfe,1) =  1.76e-11_wp
+      zpisc(jpnch,1) =  1.67e-7_wp
+      zpisc(jpdch,1) =  1.02e-7_wp
+      zpisc(jpno3,1) =  5.79e-6_wp / rno3 
+      zpisc(jpnh4,1) =  3.22e-7_wp / rno3
+      zpisc(jplgw,1) =  1.0e-9_wp
+
+      ! ln_p5z
+      zpisc(jppic,1) =  9.57e-8_wp
+      zpisc(jpnpi,1) =  9.57e-8_wp
+      zpisc(jpppi,1) =  9.57e-8_wp
+      zpisc(jppfe,1) =  1.76e-11_wp
+      zpisc(jppch,1) =  1.67e-7_wp
+      zpisc(jpnph,1) =  9.57e-8_wp
+      zpisc(jppph,1) =  9.57e-8_wp
+      zpisc(jpndi,1) =  4.24e-7_wp
+      zpisc(jppdi,1) =  4.24e-7_wp
+      zpisc(jppon,1) =  9.57e-8_wp
+      zpisc(jppop,1) =  9.57e-8_wp
+      zpisc(jpdon,1) =  2.04e-5_wp
+      zpisc(jpdop,1) =  2.04e-5_wp
+      zpisc(jpgon,1) =  5.23e-8_wp
+      zpisc(jpgop,1) =  5.23e-8_wp
+
+      !--- Arctic specificities (dissolved inorganic & DOM)
+      zpisc(jpdic,2) =  1.98e-3_wp 
+      zpisc(jpdoc,2) =  6.00e-6_wp 
+      zpisc(jptal,2) =  2.13e-3_wp 
+      zpisc(jpoxy,2) =  3.65e-4_wp  
+      zpisc(jpcal,2) =  1.50e-9_wp  
+      zpisc(jppo4,2) =  4.09e-7_wp / po4r 
+      zpisc(jppoc,2) =  4.05e-7_wp  
+      zpisc(jpgoc,2) =  2.84e-8_wp  
+      zpisc(jpbfe,2) =  7.03e-13_wp 
+      zpisc(jpsil,2) =  6.87e-6_wp  
+      zpisc(jpdsi,2) =  1.73e-7_wp 
+      zpisc(jpgsi,2) =  7.93e-9_wp
+      zpisc(jpphy,2) =  5.25e-7_wp  
+      zpisc(jpdia,2) =  7.75e-7_wp 
+      zpisc(jpzoo,2) =  3.34e-7_wp
+      zpisc(jpmes,2) =  2.49e-7_wp  
+      zpisc(jpfer,2) =  1.43e-9_wp 
+      zpisc(jpsfe,2) =  2.21e-11_wp 
+      zpisc(jpdfe,2) =  2.04e-11_wp 
+      zpisc(jpnfe,2) =  1.75e-11_wp 
+      zpisc(jpnch,2) =  1.46e-07_wp 
+      zpisc(jpdch,2) =  2.36e-07_wp 
+      zpisc(jpno3,2) =  3.51e-06_wp / rno3 
+      zpisc(jpnh4,2) =  6.15e-08_wp / rno3 
+      zpisc(jplgw,2) =  1.0e-9_wp
+
+      ! ln_p5z
+      zpisc(jppic,2) =  5.25e-7_wp
+      zpisc(jpnpi,2) =  5.25e-7_wp
+      zpisc(jpppi,2) =  5.25e-7_wp
+      zpisc(jppfe,2) =  1.75e-11_wp
+      zpisc(jppch,2) =  1.46e-07_wp
+      zpisc(jpnph,2) =  5.25e-7_wp
+      zpisc(jppph,2) =  5.25e-7_wp
+      zpisc(jpndi,2) =  7.75e-7_wp
+      zpisc(jppdi,2) =  7.75e-7_wp
+      zpisc(jppon,2) =  4.05e-7_wp
+      zpisc(jppop,2) =  4.05e-7_wp
+      zpisc(jpdon,2) =  6.00e-6_wp
+      zpisc(jpdop,2) =  6.00e-6_wp
+      zpisc(jpgon,2) =  2.84e-8_wp
+      zpisc(jpgop,2) =  2.84e-8_wp
+
+      !--- Antarctic specificities (dissolved inorganic & DOM)
+      zpisc(jpdic,3) =  2.20e-3_wp  
+      zpisc(jpdoc,3) =  7.02e-6_wp  
+      zpisc(jptal,3) =  2.37e-3_wp  
+      zpisc(jpoxy,3) =  3.42e-4_wp  
+      zpisc(jpcal,3) =  3.17e-9_wp  
+      zpisc(jppo4,3) =  1.88e-6_wp / po4r  
+      zpisc(jppoc,3) =  1.13e-6_wp  
+      zpisc(jpgoc,3) =  2.89e-8_wp  
+      zpisc(jpbfe,3) =  5.63e-13_wp 
+      zpisc(jpsil,3) =  4.96e-5_wp  
+      zpisc(jpdsi,3) =  5.63e-7_wp 
+      zpisc(jpgsi,3) =  5.35e-8_wp
+      zpisc(jpphy,3) =  8.10e-7_wp  
+      zpisc(jpdia,3) =  5.77e-7_wp 
+      zpisc(jpzoo,3) =  6.68e-7_wp
+      zpisc(jpmes,3) =  3.55e-7_wp  
+      zpisc(jpfer,3) =  1.62e-10_wp
+      zpisc(jpsfe,3) =  2.29e-11_wp 
+      zpisc(jpdfe,3) =  8.75e-12_wp
+      zpisc(jpnfe,3) =  1.48e-11_wp 
+      zpisc(jpnch,3) =  2.02e-7_wp  
+      zpisc(jpdch,3) =  1.60e-7_wp  
+      zpisc(jpno3,3) =  2.64e-5_wp / rno3  
+      zpisc(jpnh4,3) =  3.39e-7_wp / rno3  
+      zpisc(jplgw,3) =  1.0e-9_wp
+
+      ! ln_p5z
+      zpisc(jppic,3) =  8.10e-7_wp
+      zpisc(jpnpi,3) =  8.10e-7_wp
+      zpisc(jpppi,3) =  8.10e-7_wp 
+      zpisc(jppfe,3) =  1.48e-11_wp
+      zpisc(jppch,3) =  2.02e-7_wp
+      zpisc(jpnph,3) =  9.57e-8_wp
+      zpisc(jppph,3) =  9.57e-8_wp
+      zpisc(jpndi,3) =  5.77e-7_wp
+      zpisc(jppdi,3) =  5.77e-7_wp
+      zpisc(jppon,3) =  1.13e-6_wp
+      zpisc(jppop,3) =  1.13e-6_wp
+      zpisc(jpdon,3) =  7.02e-6_wp
+      zpisc(jpdop,3) =  7.02e-6_wp
+      zpisc(jpgon,3) =  2.89e-8_wp
+      zpisc(jpgop,3) =  2.89e-8_wp
+
+
+      !--- Baltic Sea particular case for ORCA configurations
+      zpisc(jpdic,4) = 1.14e-3_wp
+      zpisc(jpdoc,4) = 1.06e-5_wp
+      zpisc(jptal,4) = 1.16e-3_wp
+      zpisc(jpoxy,4) = 3.71e-4_wp
+      zpisc(jpcal,4) = 1.51e-9_wp
+      zpisc(jppo4,4) = 2.85e-9_wp / po4r
+      zpisc(jppoc,4) = 4.84e-7_wp
+      zpisc(jpgoc,4) = 1.05e-8_wp
+      zpisc(jpbfe,4) = 4.97e-13_wp
+      zpisc(jpsil,4) = 4.91e-5_wp
+      zpisc(jpdsi,4) = 3.25e-7_wp
+      zpisc(jpgsi,4) = 1.93e-8_wp
+      zpisc(jpphy,4) = 6.64e-7_wp
+      zpisc(jpdia,4) = 3.41e-7_wp
+      zpisc(jpzoo,4) = 3.83e-7_wp
+      zpisc(jpmes,4) = 0.225e-6_wp
+      zpisc(jpfer,4) = 2.45e-9_wp
+      zpisc(jpsfe,4) = 3.89e-11_wp
+      zpisc(jpdfe,4) = 1.33e-11_wp
+      zpisc(jpnfe,4) = 2.62e-11_wp
+      zpisc(jpnch,4) = 1.17e-7_wp
+      zpisc(jpdch,4) = 9.69e-8_wp
+      zpisc(jpno3,4) = 5.36e-5_wp / rno3
+      zpisc(jpnh4,4) = 7.18e-7_wp / rno3
+      zpisc(jplgw,4) = 1.0e-9_wp
+
+      ! ln_p5z
+      zpisc(jppic,4) =  6.64e-7_wp
+      zpisc(jpnpi,4) =  6.64e-7_wp
+      zpisc(jpppi,4) =  6.64e-7_wp
+      zpisc(jppfe,4) =  3.89e-11_wp
+      zpisc(jppch,4) =  1.17e-7_wp
+      zpisc(jpnph,4) =  6.64e-7_wp
+      zpisc(jppph,4) =  6.64e-7_wp
+      zpisc(jpndi,4) =  3.41e-7_wp
+      zpisc(jppdi,4) =  3.41e-7_wp
+      zpisc(jppon,4) =  4.84e-7_wp
+      zpisc(jppop,4) =  4.84e-7_wp
+      zpisc(jpdon,4) =  1.06e-5_wp
+      zpisc(jpdop,4) =  1.06e-5_wp
+      zpisc(jpgon,4) =  1.05e-8_wp
+      zpisc(jpgop,4) =  1.05e-8_wp
+!
+!     ln_ironice and tracers in seaice are redundant. Thus, if tracers in ice
+!     is activated, ln_ironice should be set to false
+!     ------------------------------------------------------------------------
+      IF( nn_ice_tr /= 0 .AND. ln_ironice ) THEN
+         IF(lwp) THEN
+            WRITE(numout,*) '   ==>>>   ln_ironice incompatible with nn_ice_tr = ', nn_ice_tr
+            WRITE(numout,*) '           Specify your sea ice iron concentration in nampisice instead '
+            WRITE(numout,*) '           ln_ironice is forced to .FALSE. '
+         ENDIF
+         ln_ironice = .FALSE.
+      ENDIF
+! 
+      DO jn = jp_pcs0, jp_pcs1
+         IF( cn_trc_o(jn) == 'GL ' ) trc_o(:,:,jn) = zpisc(jn,1)  ! Global case
+         IF( cn_trc_o(jn) == 'AA ' ) THEN 
+            WHERE( gphit(:,:) >= 0._wp ) ; trc_o(:,:,jn) = zpisc(jn,2) ; END WHERE ! Arctic 
+            WHERE( gphit(:,:) <  0._wp ) ; trc_o(:,:,jn) = zpisc(jn,3) ; END WHERE ! Antarctic 
+         ENDIF
+         IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN     !  Baltic Sea particular case for ORCA configurations
+             WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
+                    54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
+                    trc_o(:,:,jn) = zpisc(jn,4)
+            END WHERE
+         ENDIF 
+      ENDDO
+
+
+
+      !-----------------------------
+      ! Assign ice-ocean cc ratios 
+      !-----------------------------
+      ! 0 means zero concentration in sea ice
+      ! 1 means same concentration in the sea ice as in the ocean
+
+      ! Ice ocean salinity ratio
+      zsoce_bal   = 4. ; zsice_bal   = 2. !! Baltic ocean and sea ice salinities
+      zrs(1) = sice / soce                !! ice-ocean salinity ratio, global case
+      zrs(2) = zsice_bal / zsoce_bal      !! ice-ocean salinity ratio, Baltic case
+
+      DO jn = jp_pcs0, jp_pcs1
+         IF( trc_ice_ratio(jn) >= 0._wp )  zratio(jn,:) = trc_ice_ratio(jn)
+         IF( trc_ice_ratio(jn) == -1._wp ) zratio(jn,:) = zrs(:)
+         IF( trc_ice_ratio(jn) == -2._wp ) zratio(jn,:) = -9999.99_wp
+      END DO
+
+      !-------------------------------
+      ! Sea ice tracer concentrations
+      !-------------------------------
+      DO jn = jp_pcs0, jp_pcs1
+         !-- Everywhere but in the Baltic
+         IF ( trc_ice_ratio(jn) >= -1._wp ) THEN ! no prescribed conc. ; typically everything but iron) 
+            trc_i(:,:,jn) = zratio(jn,1) * trc_o(:,:,jn) 
+         ELSE                                    ! prescribed concentration
+            trc_i(:,:,jn) = trc_ice_prescr(jn)
+         ENDIF
+         !-- Baltic
+         IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN     
+            IF ( trc_ice_ratio(jn) >= - 1._wp ) THEN ! no prescribed conc. ; typically everything but iron) 
+               WHERE( 14._wp <= glamt(:,:) .AND. glamt(:,:) <= 32._wp .AND.    &
+                      54._wp <= gphit(:,:) .AND. gphit(:,:) <= 66._wp )
+                     trc_i(:,:,jn) = zratio(jn,2) * trc_o(:,:,jn) 
+               END WHERE
+            ENDIF
+         ENDIF
+      !
+      END DO ! jn
+      !
+   END SUBROUTINE p4z_ice_ini
+
+   SUBROUTINE p2z_ice_ini
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p2z_ice_ini ***
+      !!
+      !! ** Purpose :   Initialisation of the LOBSTER biochemical model
+      !!----------------------------------------------------------------------
+   END SUBROUTINE p2z_ice_ini
+
+
+   !!======================================================================
+END MODULE trcice_pisces
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcini_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcini_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcini_pisces.F90	(revision 14097)
@@ -0,0 +1,358 @@
+MODULE trcini_pisces
+   !!======================================================================
+   !!                         ***  MODULE trcini_pisces  ***
+   !! TOP :   initialisation of the PISCES biochemical model
+   !!======================================================================
+   !! History :    -   !  1988-07  (E. Maier-Reiner) Original code
+   !!              -   !  1999-10  (O. Aumont, C. Le Quere)
+   !!              -   !  2002     (O. Aumont)  PISCES
+   !!             1.0  !  2005-03  (O. Aumont, A. El Moussaoui) F90
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec) from trcini.pisces.h90
+   !!             3.5  !  2012-05  (C. Ethe) Merge PISCES-LOBSTER
+   !!----------------------------------------------------------------------
+   !! trc_ini_pisces   : PISCES biochemical model initialisation
+   !!----------------------------------------------------------------------
+   USE par_trc         !  TOP parameters
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE trcnam_pisces   !  PISCES namelist
+   USE sms_pisces      !  PISCES Source Minus Sink variables
+   USE sedini          !  SEDIMENTS initialization routine
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ini_pisces   ! called by trcini.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ini_pisces
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_ini_pisces ***
+      !!
+      !! ** Purpose :   Initialisation of the PISCES biochemical model
+      !!----------------------------------------------------------------------
+      !
+      CALL trc_nam_pisces
+      !
+      IF( ln_p4z .OR. ln_p5z ) THEN  ;   CALL p4z_ini   !  PISCES
+      ELSE                           ;   CALL p2z_ini   !  LOBSTER
+      ENDIF
+
+   END SUBROUTINE trc_ini_pisces
+
+
+   SUBROUTINE p4z_ini
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p4z_ini ***
+      !!
+      !! ** Purpose :   Initialisation of the PISCES biochemical model
+      !!----------------------------------------------------------------------
+      USE p4zsms          ! Main P4Z routine
+      USE p4zche          !  Chemical model
+      USE p4zsink         !  vertical flux of particulate matter due to sinking
+      USE p4zopt          !  optical model
+      USE p4zsbc          !  Boundary conditions
+      USE p4zfechem       !  Iron chemistry
+      USE p4zrem          !  Remineralisation of organic matter
+      USE p4zflx          !  Gas exchange
+      USE p4zlim          !  Co-limitations of differents nutrients
+      USE p4zprod         !  Growth rate of the 2 phyto groups
+      USE p4zmicro        !  Sources and sinks of microzooplankton
+      USE p4zmeso         !  Sources and sinks of mesozooplankton
+      USE p4zmort         !  Mortality terms for phytoplankton
+      USE p4zlys          !  Calcite saturation
+      USE p4zsed          !  Sedimentation & burial
+      USE p4zpoc          !  Remineralization of organic particles
+      USE p4zligand       !  Remineralization of organic ligands
+      USE p5zlim          !  Co-limitations of differents nutrients
+      USE p5zprod         !  Growth rate of the 2 phyto groups
+      USE p5zmicro        !  Sources and sinks of microzooplankton
+      USE p5zmeso         !  Sources and sinks of mesozooplankton
+      USE p5zmort         !  Mortality terms for phytoplankton
+      !
+      REAL(wp), SAVE ::   sco2   =  2.312e-3_wp
+      REAL(wp), SAVE ::   alka0  =  2.426e-3_wp
+      REAL(wp), SAVE ::   oxyg0  =  177.6e-6_wp 
+      REAL(wp), SAVE ::   po4    =  2.165e-6_wp 
+      REAL(wp), SAVE ::   bioma0 =  1.000e-8_wp  
+      REAL(wp), SAVE ::   silic1 =  91.51e-6_wp  
+      REAL(wp), SAVE ::   no3    =  30.9e-6_wp * 7.625_wp
+      !
+      INTEGER  ::  ji, jj, jk, jn, ierr
+      REAL(wp) ::  zcaralk, zbicarb, zco3
+      REAL(wp) ::  ztmas, ztmas1
+      CHARACTER(len = 20)  ::  cltra
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         IF( ln_p4z ) THEN 
+            WRITE(numout,*) 'p4z_ini :   PISCES biochemical model initialisation'
+            WRITE(numout,*) '~~~~~~~'
+         ELSE
+            WRITE(numout,*) 'p5z_ini :   PISCES biochemical model initialisation'
+            WRITE(numout,*) '~~~~~~~     With variable stoichiometry'
+         ENDIF
+      ENDIF
+      !
+      ! Allocate PISCES arrays
+      ierr =         sms_pisces_alloc()          
+      ierr = ierr +  p4z_che_alloc()
+      ierr = ierr +  p4z_sink_alloc()
+      ierr = ierr +  p4z_opt_alloc()
+      ierr = ierr +  p4z_flx_alloc()
+      ierr = ierr +  p4z_sed_alloc()
+      ierr = ierr +  p4z_lim_alloc()
+      IF( ln_p4z ) THEN
+         ierr = ierr +  p4z_prod_alloc()
+      ELSE
+         ierr = ierr +  p5z_lim_alloc()
+         ierr = ierr +  p5z_prod_alloc()
+      ENDIF
+      ierr = ierr +  p4z_rem_alloc()
+      !
+      CALL mpp_sum( 'trcini_pisces', 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
+      !
+
+      ! assign an index in trc arrays for each prognostic variables
+      DO jn = 1, jptra
+        cltra = ctrcnm(jn) 
+        IF( cltra == 'DIC'      )   jpdic = jn      !: dissolved inoganic carbon concentration 
+        IF( cltra == 'Alkalini' )   jptal = jn      !: total alkalinity 
+        IF( cltra == 'O2'       )   jpoxy = jn      !: oxygen carbon concentration 
+        IF( cltra == 'CaCO3'    )   jpcal = jn      !: calcite  concentration 
+        IF( cltra == 'PO4'      )   jppo4 = jn      !: phosphate concentration 
+        IF( cltra == 'POC'      )   jppoc = jn      !: small particulate organic phosphate concentration
+        IF( cltra == 'Si'       )   jpsil = jn      !: silicate concentration
+        IF( cltra == 'PHY'      )   jpphy = jn      !: phytoplancton concentration 
+        IF( cltra == 'ZOO'      )   jpzoo = jn      !: zooplancton concentration
+        IF( cltra == 'DOC'      )   jpdoc = jn      !: dissolved organic carbon concentration 
+        IF( cltra == 'PHY2'     )   jpdia = jn      !: Diatoms Concentration
+        IF( cltra == 'ZOO2'     )   jpmes = jn      !: Mesozooplankton Concentration
+        IF( cltra == 'DSi'      )   jpdsi = jn      !: Diatoms Silicate Concentration
+        IF( cltra == 'Fer'      )   jpfer = jn      !: Iron Concentration
+        IF( cltra == 'BFe'      )   jpbfe = jn      !: Big iron particles Concentration
+        IF( cltra == 'GOC'      )   jpgoc = jn      !: Big particulate organic phosphate concentration
+        IF( cltra == 'SFe'      )   jpsfe = jn      !: Small iron particles Concentration
+        IF( cltra == 'DFe'      )   jpdfe = jn      !: Diatoms iron Concentration
+        IF( cltra == 'GSi'      )   jpgsi = jn      !: (big) Silicate Concentration
+        IF( cltra == 'NFe'      )   jpnfe = jn      !: Nano iron Concentration
+        IF( cltra == 'NCHL'     )   jpnch = jn      !: Nano Chlorophyll Concentration
+        IF( cltra == 'DCHL'     )   jpdch = jn      !: Diatoms Chlorophyll Concentration
+        IF( cltra == 'NO3'      )   jpno3 = jn      !: Nitrates Concentration
+        IF( cltra == 'NH4'      )   jpnh4 = jn      !: Ammonium Concentration
+        IF( cltra == 'DON'      )   jpdon = jn      !: Dissolved organic N Concentration
+        IF( cltra == 'DOP'      )   jpdop = jn      !: Dissolved organic P Concentration
+        IF( cltra == 'PON'      )   jppon = jn      !: Small Nitrogen particle Concentration
+        IF( cltra == 'POP'      )   jppop = jn      !: Small Phosphorus particle Concentration
+        IF( cltra == 'GON'      )   jpgon = jn      !: Big Nitrogen particles Concentration
+        IF( cltra == 'GOP'      )   jpgop = jn      !: Big Phosphorus Concentration
+        IF( cltra == 'PHYN'     )   jpnph = jn      !: Nanophytoplankton N biomass
+        IF( cltra == 'PHYP'     )   jppph = jn      !: Nanophytoplankton P biomass
+        IF( cltra == 'DIAN'     )   jpndi = jn      !: Diatoms N biomass
+        IF( cltra == 'DIAP'     )   jppdi = jn      !: Diatoms P biomass
+        IF( cltra == 'PIC'      )   jppic = jn      !: Picophytoplankton C biomass
+        IF( cltra == 'PICN'     )   jpnpi = jn      !: Picophytoplankton N biomass
+        IF( cltra == 'PICP'     )   jpppi = jn      !: Picophytoplankton P biomass
+        IF( cltra == 'PCHL'     )   jppch = jn      !: Diatoms Chlorophyll Concentration
+        IF( cltra == 'PFe'      )   jppfe = jn      !: Picophytoplankton Fe biomass
+        IF( cltra == 'LGW'      )   jplgw = jn      !: Weak ligands
+      END DO
+
+      CALL p4z_sms_init       !  Maint routine
+      !
+
+      ! Set biological ratios
+      ! ---------------------
+      rno3    =  16._wp / 122._wp
+      po4r    =   1._wp / 122._wp
+      o2nit   =  32._wp / 122._wp
+      o2ut    = 133._wp / 122._wp
+      rdenit  =  ( ( o2ut + o2nit ) * 0.80 - rno3 - rno3 * 0.60 ) / rno3
+      rdenita =   3._wp /  5._wp
+      IF( ln_p5z ) THEN
+         no3rat3 = no3rat3 / rno3
+         po4rat3 = po4rat3 / po4r
+      ENDIF
+
+      ! Initialization of tracer concentration in case of  no restart 
+      !--------------------------------------------------------------
+      IF( .NOT.ln_rsttr ) THEN  
+         trn(:,:,:,jpdic) = sco2
+         trn(:,:,:,jpdoc) = bioma0
+         trn(:,:,:,jptal) = alka0
+         trn(:,:,:,jpoxy) = oxyg0
+         trn(:,:,:,jpcal) = bioma0
+         trn(:,:,:,jppo4) = po4 / po4r
+         trn(:,:,:,jppoc) = bioma0
+         trn(:,:,:,jpgoc) = bioma0
+         trn(:,:,:,jpbfe) = bioma0 * 5.e-6
+         trn(:,:,:,jpsil) = silic1
+         trn(:,:,:,jpdsi) = bioma0 * 0.15
+         trn(:,:,:,jpgsi) = bioma0 * 5.e-6
+         trn(:,:,:,jpphy) = bioma0
+         trn(:,:,:,jpdia) = bioma0
+         trn(:,:,:,jpzoo) = bioma0
+         trn(:,:,:,jpmes) = bioma0
+         trn(:,:,:,jpfer) = 0.6E-9
+         trn(:,:,:,jpsfe) = bioma0 * 5.e-6
+         trn(:,:,:,jpdfe) = bioma0 * 5.e-6
+         trn(:,:,:,jpnfe) = bioma0 * 5.e-6
+         trn(:,:,:,jpnch) = bioma0 * 12. / 55.
+         trn(:,:,:,jpdch) = bioma0 * 12. / 55.
+         trn(:,:,:,jpno3) = no3
+         trn(:,:,:,jpnh4) = bioma0
+         IF( ln_ligand) THEN
+            trn(:,:,:,jplgw) = 0.6E-9
+         ENDIF
+         IF( ln_p5z ) THEN
+            trn(:,:,:,jpdon) = bioma0
+            trn(:,:,:,jpdop) = bioma0
+            trn(:,:,:,jppon) = bioma0
+            trn(:,:,:,jppop) = bioma0
+            trn(:,:,:,jpgon) = bioma0
+            trn(:,:,:,jpgop) = bioma0
+            trn(:,:,:,jpnph) = bioma0
+            trn(:,:,:,jppph) = bioma0
+            trn(:,:,:,jppic) = bioma0
+            trn(:,:,:,jpnpi) = bioma0
+            trn(:,:,:,jpppi) = bioma0
+            trn(:,:,:,jpndi) = bioma0
+            trn(:,:,:,jppdi) = bioma0
+            trn(:,:,:,jppfe) = bioma0 * 5.e-6
+            trn(:,:,:,jppch) = bioma0 * 12. / 55.
+         ENDIF
+         ! initialize the half saturation constant for silicate
+         ! ----------------------------------------------------
+         xksi(:,:)    = 2.e-6
+         xksimax(:,:) = xksi(:,:)
+         IF( ln_p5z ) THEN
+            sized(:,:,:) = 1.0
+            sizen(:,:,:) = 1.0
+            sized(:,:,:) = 1.0
+         ENDIF
+      END IF
+
+
+      CALL p4z_sink_init         !  vertical flux of particulate organic matter
+      CALL p4z_opt_init          !  Optic: PAR in the water column
+      IF( ln_p4z ) THEN
+         CALL p4z_lim_init       !  co-limitations by the various nutrients
+         CALL p4z_prod_init      !  phytoplankton growth rate over the global ocean.
+      ELSE
+         CALL p5z_lim_init       !  co-limitations by the various nutrients
+         CALL p5z_prod_init      !  phytoplankton growth rate over the global ocean.
+      ENDIF
+      CALL p4z_sbc_init          !  boundary conditions
+      CALL p4z_fechem_init       !  Iron chemistry
+      CALL p4z_rem_init          !  remineralisation
+      CALL p4z_poc_init          !  remineralisation of organic particles
+      IF( ln_ligand ) &
+         & CALL p4z_ligand_init  !  remineralisation of organic ligands
+
+      IF( ln_p4z ) THEN
+         CALL p4z_mort_init      !  phytoplankton mortality 
+         CALL p4z_micro_init     !  microzooplankton
+         CALL p4z_meso_init      !  mesozooplankton
+      ELSE
+         CALL p5z_mort_init      !  phytoplankton mortality 
+         CALL p5z_micro_init     !  microzooplankton
+         CALL p5z_meso_init      !  mesozooplankton
+      ENDIF
+      CALL p4z_lys_init          !  calcite saturation
+      IF( .NOT.l_co2cpl ) &
+        & CALL p4z_flx_init      !  gas exchange 
+
+      ! Initialization of the sediment model
+      IF( ln_sediment)   CALL sed_init
+
+      IF(lwp) WRITE(numout,*) 
+      IF(lwp) WRITE(numout,*) '   ==>>>   Initialization of PISCES tracers done'
+      IF(lwp) WRITE(numout,*) 
+      !
+   END SUBROUTINE p4z_ini
+
+
+   SUBROUTINE p2z_ini
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE p2z_ini ***
+      !!
+      !! ** Purpose :   Initialisation of the LOBSTER biochemical model
+      !!----------------------------------------------------------------------
+      !
+      USE p2zopt
+      USE p2zexp
+      USE p2zbio
+      USE p2zsed
+      !
+      INTEGER  ::  ji, jj, jk, jn, ierr
+      CHARACTER(len = 10)  ::  cltra
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) ' p2z_ini :   LOBSTER biochemical model initialisation'
+      IF(lwp) WRITE(numout,*) ' ~~~~~~~'
+
+      ierr =        sms_pisces_alloc()          
+      ierr = ierr + p2z_exp_alloc()
+      !
+      CALL mpp_sum( 'trcini_pisces', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'p2z_ini: unable to allocate LOBSTER arrays' )
+
+      DO jn = 1, jptra
+        cltra = ctrcnm(jn) 
+        IF( cltra == 'DET' )   jpdet = jn       !: detritus                    [mmoleN/m3]
+        IF( cltra == 'ZOO' )   jpzoo = jn       !: zooplancton concentration   [mmoleN/m3]
+        IF( cltra == 'PHY' )   jpphy = jn       !: phytoplancton concentration [mmoleN/m3]
+        IF( cltra == 'NO3' )   jpno3 = jn       !: nitrate concentration       [mmoleN/m3]
+        IF( cltra == 'NH4' )   jpnh4 = jn       !: ammonium concentration      [mmoleN/m3]
+        IF( cltra == 'DOM' )   jpdom = jn       !: dissolved organic matter    [mmoleN/m3]
+      ENDDO
+
+      jpkb = 10        !  last level where depth less than 200 m
+      DO jk = jpkm1, 1, -1
+         IF( gdept_1d(jk) > 200. ) jpkb = jk 
+      END DO
+      IF (lwp) WRITE(numout,*)
+      IF (lwp) WRITE(numout,*) ' first vertical layers where biology is active (200m depth ) ', jpkb
+      IF (lwp) WRITE(numout,*)
+      jpkbm1 = jpkb - 1
+      !
+
+
+      ! LOBSTER initialisation for GYRE : init NO3=f(density) by asklod AS Kremeur 2005-07
+      ! ----------------------
+      IF( .NOT. ln_rsttr ) THEN             ! in case of  no restart 
+         trn(:,:,:,jpdet) = 0.1 * tmask(:,:,:)
+         trn(:,:,:,jpzoo) = 0.1 * tmask(:,:,:)
+         trn(:,:,:,jpnh4) = 0.1 * tmask(:,:,:)
+         trn(:,:,:,jpphy) = 0.1 * tmask(:,:,:)
+         trn(:,:,:,jpdom) = 1.0 * tmask(:,:,:)
+         WHERE( rhd(:,:,:) <= 24.5e-3 )  ;  trn(:,:,:,jpno3) = 2._wp * tmask(:,:,:)
+         ELSE WHERE                      ;  trn(:,:,:,jpno3) = ( 15.55 * ( rhd(:,:,:) * 1000. ) - 380.11 ) * tmask(:,:,:)
+         END WHERE                       
+      ENDIF
+      !                       !  Namelist read
+      CALL p2z_opt_init       !  Optics parameters
+      CALL p2z_sed_init       !  sedimentation
+      CALL p2z_bio_init       !  biology
+      CALL p2z_exp_init       !  export 
+      !
+      IF(lwp) WRITE(numout,*) 
+      IF(lwp) WRITE(numout,*) '   ==>>>   Initialization of LOBSTER tracers done'
+      IF(lwp) WRITE(numout,*) 
+      !
+   END SUBROUTINE p2z_ini
+
+   !!======================================================================
+END MODULE trcini_pisces
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcnam_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcnam_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcnam_pisces.F90	(revision 14097)
@@ -0,0 +1,93 @@
+MODULE trcnam_pisces
+   !!======================================================================
+   !!                      ***  MODULE trcnam_pisces  ***
+   !! TOP :   initialisation of some run parameters for PISCES bio-model
+   !!======================================================================
+   !! History :    -   !  1999-10 (M.A. Foujols, M. Levy) original code
+   !!              -   !  2000-01 (L. Bopp) hamocc3, p3zd
+   !!             1.0  !  2003-08 (C. Ethe)  module F90
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec) from trcnam.pisces.h90
+   !!----------------------------------------------------------------------
+   !! trc_nam_pisces   : PISCES model namelist read
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! Ocean variables
+   USE par_trc         ! TOP parameters
+   USE trc             ! TOP variables
+   USE sms_pisces      ! sms trends
+   USE trdtrc_oce
+   USE iom             ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nam_pisces   ! called by trcnam.F90 module
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_nam_pisces
+      !!----------------------------------------------------------------------
+      !!                     ***  trc_nam_pisces  ***  
+      !!
+      !! ** Purpose :   read PISCES namelist
+      !!
+      !! ** input   :   file 'namelist.trc.sms' containing the following
+      !!             namelist: natext, natbio, natsms
+      !!----------------------------------------------------------------------
+      INTEGER :: jl, jn
+      INTEGER :: ios, ioptio         ! Local integer
+      CHARACTER(LEN=20)::   clname
+      !!
+      NAMELIST/nampismod/ln_p2z, ln_p4z, ln_p5z, ln_ligand, ln_sediment
+      !!----------------------------------------------------------------------
+
+      IF(lwp) WRITE(numout,*)
+      clname = 'namelist_pisces'
+
+      IF(lwp) WRITE(numout,*) 'trc_nam_pisces : read PISCES namelist'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'
+      CALL ctl_opn( numnatp_ref, TRIM( clname )//'_ref', 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnatp_cfg, TRIM( clname )//'_cfg', 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      IF(lwm) CALL ctl_opn( numonp     , 'output.namelist.pis' , 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      !
+      REWIND( numnatp_ref )              ! Namelist nampisbio in reference namelist : Pisces variables
+      READ  ( numnatp_ref, nampismod, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nampismod in reference namelist' )
+      REWIND( numnatp_cfg )              ! Namelist nampisbio in configuration namelist : Pisces variables
+      READ  ( numnatp_cfg, nampismod, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'nampismod in configuration namelist' )
+      IF(lwm) WRITE( numonp, nampismod )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*) '   Namelist : nampismod '
+         WRITE(numout,*) '      Flag to use LOBSTER model            ln_p2z      = ', ln_p2z
+         WRITE(numout,*) '      Flag to use PISCES standard model    ln_p4z      = ', ln_p4z
+         WRITE(numout,*) '      Flag to use PISCES quota    model    ln_p5z      = ', ln_p5z
+         WRITE(numout,*) '      Flag to ligand                       ln_ligand   = ', ln_ligand
+         WRITE(numout,*) '      Flag to use sediment                 ln_sediment = ', ln_sediment
+      ENDIF
+      !
+      IF(lwp) THEN                         ! control print
+         WRITE(numout,*)
+         IF( ln_p5z      )  WRITE(numout,*) '   ==>>>   PISCES QUOTA model is used'
+         IF( ln_p4z      )  WRITE(numout,*) '   ==>>>   PISCES STANDARD model is used'
+         IF( ln_p2z      )  WRITE(numout,*) '   ==>>>   LOBSTER model is used'
+         IF( ln_ligand )  WRITE(numout,*) '   ==>>>   Compute remineralization/dissolution of organic ligands'
+         IF( ln_sediment )  WRITE(numout,*) '   ==>>>   Sediment module is used'
+      ENDIF
+    
+      ioptio = 0
+      IF( ln_p2z )    ioptio = ioptio + 1
+      IF( ln_p4z )    ioptio = ioptio + 1
+      IF( ln_p5z )    ioptio = ioptio + 1
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE PISCES model namelist nampismod' )
+       !
+   END SUBROUTINE trc_nam_pisces
+
+   !!======================================================================
+END MODULE trcnam_pisces
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcsms_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcsms_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcsms_pisces.F90	(revision 14097)
@@ -0,0 +1,47 @@
+MODULE trcsms_pisces
+   !!======================================================================
+   !!                         ***  MODULE trcsms_pisces  ***
+   !! TOP :   PISCES Source Minus Sink manager
+   !!======================================================================
+   !! History :   1.0  !  2004-03 (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!----------------------------------------------------------------------
+   !!   trcsms_pisces        :  Time loop of passive tracers sms
+   !!----------------------------------------------------------------------
+   USE par_pisces
+   USE sms_pisces
+   USE p4zsms
+   USE p2zsms
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms_pisces    ! called in trcsms.F90
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms_pisces( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms_pisces  ***
+      !!
+      !! ** Purpose :   Managment of the call to Biological sources and sinks 
+      !!                routines of PISCES or LOBSTER bio-model
+      !!
+      !!---------------------------------------------------------------------
+      !
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_p4z .OR. ln_p5z ) THEN  ;   CALL p4z_sms( kt )   !  PISCES
+      ELSE                           ;   CALL p2z_sms( kt )   !  LOBSTER
+      ENDIF
+
+      !
+   END SUBROUTINE trc_sms_pisces
+
+   !!======================================================================
+END MODULE trcsms_pisces 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcwri_pisces.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcwri_pisces.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/PISCES/trcwri_pisces.F90	(revision 14097)
@@ -0,0 +1,103 @@
+MODULE trcwri_pisces
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    PISCES :   Output of PISCES tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput 
+   !!----------------------------------------------------------------------
+   !! trc_wri_pisces   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE trc         ! passive tracers common variables 
+   USE sms_pisces  ! PISCES variables
+   USE iom         ! I/O manager
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri_pisces 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_wri_pisces
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri_trc  ***
+      !!
+      !! ** Purpose :   output passive tracers fields 
+      !!---------------------------------------------------------------------
+      CHARACTER (len=20)           :: cltra
+      REAL(wp)                     :: zfact
+      INTEGER                      :: ji, jj, jk, jn
+      REAL(wp), DIMENSION(jpi,jpj) :: zdic, zo2min, zdepo2min
+      !!---------------------------------------------------------------------
+ 
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      IF( ln_p2z ) THEN
+         DO jn = jp_pcs0, jp_pcs1
+            cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
+            CALL iom_put( cltra, trn(:,:,:,jn) )
+         END DO
+      ELSE
+         DO jn = jp_pcs0, jp_pcs1
+            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( 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) * e3t_n(:,:,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(:,:) = gdepw_n(:,:,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) = gdepw_n(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
+      !
+   END SUBROUTINE trc_wri_pisces
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri_pisces
+CONTAINS
+   SUBROUTINE trc_wri_pisces                     ! Empty routine  
+   END SUBROUTINE trc_wri_pisces
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcwri_pisces
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/README.rst	(revision 14097)
@@ -0,0 +1,392 @@
+***************
+Oceanic tracers
+***************
+
+.. todo::
+
+
+
+.. contents::
+   :local:
+
+TOP (Tracers in the Ocean Paradigm) is the NEMO hardwired interface toward
+biogeochemical models and provide the physical constraints/boundaries for oceanic tracers.
+It consists of a modular framework to handle multiple ocean tracers,
+including also a variety of built-in modules.
+
+This component of the NEMO framework allows one to exploit available modules (see below) and
+further develop a range of applications, spanning from the implementation of a dye passive tracer to
+evaluate dispersion processes (by means of MY_TRC), track water masses age (AGE module),
+assess the ocean interior penetration of persistent chemical compounds
+(e.g., gases like CFC or even PCBs), up to the full set of equations involving
+marine biogeochemical cycles.
+
+Structure
+=========
+
+TOP interface has the following location in the source code :file:`./src/TOP` and
+the following modules are available:
+
+:file:`TRP`
+   Interface to NEMO physical core for computing tracers transport
+
+:file:`CFC`
+   Inert carbon tracers (CFC11,CFC12,SF6)
+
+:file:`C14`
+   Radiocarbon passive tracer
+
+:file:`AGE`
+   Water age tracking
+
+:file:`MY_TRC`
+   Template for creation of new modules and external BGC models coupling
+
+:file:`PISCES`
+   Built in BGC model. See :cite:`gmd-8-2465-2015` for a throughout description.
+
+The usage of TOP is activated
+*i)* by including in the configuration definition the component ``TOP`` and
+*ii)* by adding the macro ``key_top`` in the configuration CPP file
+(see for more details :forge:`"Learn more about the model" <wiki/Users>`).
+
+As an example, the user can refer to already available configurations in the code,
+``GYRE_PISCES`` being the NEMO biogeochemical demonstrator and
+``GYRE_BFM`` to see the required configuration elements to couple with an external biogeochemical model
+(see also Section 4) .
+
+Note that, since version 4.0,
+TOP interface core functionalities are activated by means of logical keys and
+all submodules preprocessing macros from previous versions were removed.
+
+Here below the list of preprocessing keys that applies to the TOP interface (beside ``key_top``):
+
+``key_iomput``
+   use XIOS I/O
+
+``key_agrif``
+   enable AGRIF coupling
+
+``key_trdtrc`` & ``key_trdmxl_trc``
+   trend computation for tracers
+
+Synthetic Workflow
+==================
+
+A synthetic description of the TOP interface workflow is given below to
+summarize the steps involved in the computation of biogeochemical and physical trends and
+their time integration and outputs,
+by reporting also the principal Fortran subroutine herein involved.
+
+Model initialization (:file:`./src/OCE/nemogcm.F90`)
+----------------------------------------------------
+
+Call to ``trc_init`` subroutine (:file:`./src/TOP/trcini.F90`) to initialize TOP.
+
+.. literalinclude:: ../../../src/TOP/trcini.F90
+   :language:        fortran
+   :lines:           41-86
+   :emphasize-lines: 21,30-32,38-40
+   :caption:         ``trc_init`` subroutine
+
+Time marching procedure (:file:`./src/OCE/step.F90`)
+----------------------------------------------------
+
+Call to ``trc_stp`` subroutine (:file:`./src/TOP/trcstp.F90`) to compute/update passive tracers.
+
+.. literalinclude:: ../../../src/TOP/trcstp.F90
+   :language:        fortran
+   :lines:           46-125
+   :emphasize-lines: 42,55-57
+   :caption:         ``trc_stp`` subroutine
+
+BGC trends computation for each submodule (:file:`./src/TOP/trcsms.F90`)
+------------------------------------------------------------------------
+
+.. literalinclude:: ../../../src/TOP/trcsms.F90
+   :language:        fortran
+   :lines:           21
+   :caption:         :file:`trcsms` snippet
+
+Physical trends computation (:file:`./src/TOP/TRP/trctrp.F90`)
+--------------------------------------------------------------
+
+.. literalinclude:: ../../../src/TOP/TRP/trctrp.F90
+   :language:        fortran
+   :lines:           46-95
+   :emphasize-lines: 17,21,29,33-35
+   :caption:         ``trc_trp`` subroutine
+
+Namelists walkthrough
+=====================
+
+:file:`namelist_top`
+--------------------
+
+Here below are listed the features/options of the TOP interface accessible through
+the :file:`namelist_top_ref` and modifiable by means of :file:`namelist_top_cfg`
+(as for NEMO physical ones).
+
+Note that ``##`` is used to refer to a number in an array field.
+
+.. literalinclude:: ../../namelists/namtrc_run
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_dta
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_adv
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_ldf
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_rad
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_snk
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_dmp
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_ice
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_trd
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_bc
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namtrc_bdy
+   :language: fortran
+
+.. literalinclude:: ../../namelists/namage
+   :language: fortran
+
+Two main types of data structure are used within TOP interface
+to initialize tracer properties (1) and
+to provide related initial and boundary conditions (2).
+
+1. TOP tracers initialization: ``sn_tracer`` (``&namtrc``)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Beside providing name and metadata for tracers,
+here are also defined the use of initial (``sn_tracer%llinit``) and
+boundary (``sn_tracer%llsbc, sn_tracer%llcbc, sn_tracer%llobc``) conditions.
+
+In the following, an example of the full structure definition is given for
+two idealized tracers both with initial conditions given,
+while the first has only surface boundary forcing and
+the second both surface and coastal forcings:
+
+.. code-block:: fortran
+
+   !             !    name   !           title of the field            !   units    ! initial data ! sbc   !   cbc  !   obc  !
+   sn_tracer(1)  = 'TRC1'    , 'Tracer 1 Concentration                ',   ' - '    ,  .true.      , .true., .false., .true.
+   sn_tracer(2)  = 'TRC2 '   , 'Tracer 2 Concentration                ',   ' - '    ,  .true.      , .true., .true. , .false.
+
+As tracers in BGC models are increasingly growing,
+the same structure can be written also in a more compact and readable way:
+
+.. code-block:: fortran
+
+   !             !    name   !           title of the field            !   units    ! initial data !
+   sn_tracer(1)  = 'TRC1'    , 'Tracer 1 Concentration                ',   ' - '    ,   .true.
+   sn_tracer(2)  = 'TRC2 '   , 'Tracer 2 Concentration                ',   ' - '    ,   .true.
+   ! sbc
+   sn_tracer(1)%llsbc = .true.
+   sn_tracer(2)%llsbc = .true.
+   ! cbc
+   sn_tracer(2)%llcbc = .true.
+
+The data structure is internally initialized by code with dummy names and
+all initialization/forcing logical fields set to ``.false.`` .
+
+2. Structures to read input initial and boundary conditions: ``&namtrc_dta`` (``sn_trcdta``), ``&namtrc_bc`` (``sn_trcsbc`` / ``sn_trccbc`` / ``sn_trcobc``)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The overall data structure (Fortran type) is based on the general one defined for NEMO core in the SBC component
+(see details in ``SBC`` Chapter of :doc:`Reference Manual <cite>` on Input Data specification).
+
+Input fields are prescribed within ``&namtrc_dta`` (with ``sn_trcdta`` structure),
+while Boundary Conditions are applied to the model by means of ``&namtrc_bc``,
+with dedicated structure fields for surface (``sn_trcsbc``), riverine (``sn_trccbc``), and
+lateral open (``sn_trcobc``) boundaries.
+
+The following example illustrates the data structure in the case of initial condition for
+a single tracer contained in the file named :file:`tracer_1_data.nc`
+(``.nc`` is implicitly assumed in namelist filename),
+with a doubled initial value, and located in the :file:`usr/work/model/inputdata` folder:
+
+.. code-block:: fortran
+
+   !               !  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_trcdta(1)  = 'tracer_1_data'        ,        -12        ,  'TRC1'   ,    .false.   , .true. , 'yearly'  , ''       , ''       , ''
+     rf_trfac(1) = 2.0
+     cn_dir = 'usr/work/model/inputdata/'
+
+Note that, the Lateral Open Boundaries conditions are applied on
+the segments defined for the physical core of NEMO
+(see ``BDY`` description in the :doc:`Reference Manual <cite>`).
+
+:file:`namelist_trc`
+--------------------
+
+Here below the description of :file:`namelist_trc_ref` used to handle Carbon tracers modules,
+namely CFC and C14.
+
+.. literalinclude:: ../../../cfgs/SHARED/namelist_trc_ref
+   :language: fortran
+   :lines: 7,17,26,34
+   :caption: :file:`namelist_trc_ref` snippet
+
+``MY_TRC`` interface for coupling external BGC models
+=====================================================
+
+The generalized interface is pivoted on MY_TRC module that contains template files to
+build the coupling between
+NEMO and any external BGC model.
+
+The call to MY_TRC is activated by setting ``ln_my_trc = .true.`` (in ``&namtrc``)
+
+The following 6 fortran files are available in MY_TRC with the specific purposes here described.
+
+:file:`par_my_trc.F90`
+   This module allows to define additional arrays and public variables to
+   be used within the MY_TRC interface
+
+:file:`trcini_my_trc.F90`
+   Here are initialized user defined namelists and
+   the call to the external BGC model initialization procedures to populate general tracer array
+   (``trn`` and ``trb``).
+   Here are also likely to be defined support arrays related to system metrics that
+   could be needed by the BGC model.
+
+:file:`trcnam_my_trc.F90`
+   This routine is called at the beginning of ``trcini_my_trc`` and
+   should contain the initialization of additional namelists for the BGC model or user-defined code.
+
+:file:`trcsms_my_trc.F90`
+   The routine performs the call to Boundary Conditions and its main purpose is to
+   contain the Source-Minus-Sinks terms due to the biogeochemical processes of the external model.
+   Be aware that lateral boundary conditions are applied in trcnxt routine.
+
+   .. warning::
+      The routines to compute the light penetration along the water column and
+      the tracer vertical sinking should be defined/called in here,
+      as generalized modules are still missing in the code.
+
+:file:`trcice_my_trc.F90`
+   Here it is possible to prescribe the tracers concentrations in the sea-ice that
+   will be used as boundary conditions when ice melting occurs (``nn_ice_tr = 1`` in ``&namtrc_ice``).
+   See e.g. the correspondent PISCES subroutine.
+
+:file:`trcwri_my_trc.F90`
+   This routine performs the output of the model tracers (only those defined in ``&namtrc``) using
+   IOM module (see chapter “Output and Diagnostics” in the :doc:`Reference Manual <cite>`).
+   It is possible to place here the output of additional variables produced by the model,
+   if not done elsewhere in the code, using the call to ``iom_put``.
+
+Coupling an external BGC model using NEMO framework
+===================================================
+
+The coupling with an external BGC model through the NEMO compilation framework can be achieved in
+different ways according to the degree of coding complexity of the Biogeochemical model, like e.g.,
+the whole code is made only by one file or
+it has multiple modules and interfaces spread across several subfolders.
+
+Beside the 6 core files of MY_TRC module, let’s assume an external BGC model named *MYBGC* and
+constituted by a rather essential coding structure, likely few Fortran files.
+The new coupled configuration name is *NEMO_MYBGC*.
+
+The best solution is to have all files (the modified ``MY_TRC`` routines and the BGC model ones)
+placed in a unique folder with root ``MYBGCPATH`` and
+to use the makenemo external readdressing of ``MY_SRC`` folder.
+
+The coupled configuration listed in :file:`work_cfgs.txt` will look like
+
+::
+
+   NEMO_MYBGC OCE TOP
+
+and the related ``cpp_MYBGC.fcm`` content will be
+
+.. code-block:: perl
+
+   bld::tool::fppkeys key_iomput key_mpp_mpi key_top
+
+the compilation with :file:`makenemo` will be executed through the following syntax
+
+.. code-block:: console
+
+   $ makenemo -n 'NEMO_MYBGC' -m '<arch_my_machine>' -j 8 -e '<MYBGCPATH>'
+
+The makenemo feature ``-e`` was introduced to
+readdress at compilation time the standard MY_SRC folder (usually found in NEMO configurations) with
+a user defined external one.
+
+The compilation of more articulated BGC model code & infrastructure,
+like in the case of BFM (|BFM man|_), requires some additional features.
+
+As before, let’s assume a coupled configuration name *NEMO_MYBGC*,
+but in this case MYBGC model root becomes :file:`MYBGC` path that
+contains 4 different subfolders for biogeochemistry,
+named :file:`initialization`, :file:`pelagic`, and :file:`benthic`,
+and a separate one named :file:`nemo_coupling` including the modified `MY_SRC` routines.
+The latter folder containing the modified NEMO coupling interface will be still linked using
+the makenemo ``-e`` option.
+
+In order to include the BGC model subfolders in the compilation of NEMO code,
+it will be necessary to extend the configuration :file:`cpp_NEMO_MYBGC.fcm` file to include the specific paths of :file:`MYBGC` folders, as in the following example
+
+.. code-block:: perl
+
+   bld::tool::fppkeys  key_iomput key_mpp_mpi key_top
+
+   src::MYBGC::initialization         <MYBGCPATH>/initialization
+   src::MYBGC::pelagic                <MYBGCPATH>/pelagic
+   src::MYBGC::benthic                <MYBGCPATH>/benthic
+
+   bld::pp::MYBGC      1
+   bld::tool::fppflags::MYBGC   %FPPFLAGS
+   bld::tool::fppkeys           %bld::tool::fppkeys MYBGC_MACROS
+
+where *MYBGC_MACROS* is the space delimited list of macros used in *MYBGC* model for
+selecting/excluding specific parts of the code.
+The BGC model code will be preprocessed in the configuration :file:`BLD` folder as for NEMO,
+but with an independent path, like :file:`NEMO_MYBGC/BLD/MYBGC/<subforlders>`.
+
+The compilation will be performed similarly to in the previous case with the following
+
+.. code-block:: console
+
+   $ makenemo -n 'NEMO_MYBGC' -m '<arch_my_machine>' -j 8 -e '<MYBGCPATH>/nemo_coupling'
+
+.. note::
+   The additional lines specific for the BGC model source and build paths can be written into
+   a separate file, e.g. named :file:`MYBGC.fcm`,
+   and then simply included in the :file:`cpp_NEMO_MYBGC.fcm` as follow
+
+   .. code-block:: perl
+
+      bld::tool::fppkeys  key_zdftke key_dynspg_ts key_iomput key_mpp_mpi key_top
+      inc <MYBGCPATH>/MYBGC.fcm
+
+   This will enable a more portable compilation structure for all MYBGC related configurations.
+
+.. warning::
+   The coupling interface contained in :file:`nemo_coupling` cannot be added using the FCM syntax,
+   as the same files already exists in NEMO and they are overridden only with
+   the readdressing of MY_SRC contents to avoid compilation conflicts due to duplicate routines.
+
+All modifications illustrated above, can be easily implemented using shell or python scripting
+to edit the NEMO configuration :file:`CPP.fcm` file and
+to create the BGC model specific FCM compilation file with code paths.
+
+.. |BFM man| replace:: BFM-NEMO coupling manual
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcadv.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcadv.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcadv.F90	(revision 14097)
@@ -0,0 +1,243 @@
+MODULE trcadv
+   !!==============================================================================
+   !!                       ***  MODULE  trcadv  ***
+   !! Ocean passive tracers:  advection trend 
+   !!==============================================================================
+   !! History :  2.0  !  2005-11  (G. Madec)  Original code
+   !!            3.0  !  2010-06  (C. Ethe)   Adapted to passive tracers
+   !!            3.7  !  2014-05  (G. Madec, C. Ethe)  Add 2nd/4th order cases for CEN and FCT schemes 
+   !!            4.0  !  2017-09  (G. Madec)  remove vertical time-splitting option
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_adv       : compute ocean tracer advection trend
+   !!   trc_adv_ini   : control the different options of advection scheme
+   !!----------------------------------------------------------------------
+   USE oce_trc        ! ocean dynamics and active tracers
+   USE trc            ! ocean passive tracers variables
+   USE sbcwave        ! wave module
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE traadv_cen     ! centered scheme           (tra_adv_cen  routine)
+   USE traadv_fct     ! FCT      scheme           (tra_adv_fct  routine)
+   USE traadv_mus     ! MUSCL    scheme           (tra_adv_mus  routine)
+   USE traadv_ubs     ! UBS      scheme           (tra_adv_ubs  routine)
+   USE traadv_qck     ! QUICKEST scheme           (tra_adv_qck  routine)
+   USE tramle         ! ML eddy induced transport (tra_adv_mle  routine)
+   USE ldftra         ! lateral diffusion: eddy diffusivity & EIV coeff.
+   USE ldfslp         ! Lateral diffusion: slopes of neutral surfaces
+   !
+   USE prtctl_trc     ! control print
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_adv       ! called by trctrp.F90
+   PUBLIC   trc_adv_ini   ! called by trcini.F90
+
+   !                            !!* Namelist namtrc_adv *
+   LOGICAL ::   ln_trcadv_OFF    ! no advection on passive tracers
+   LOGICAL ::   ln_trcadv_cen    ! centered scheme flag
+   INTEGER ::      nn_cen_h, nn_cen_v   ! =2/4 : horizontal and vertical choices of the order of CEN scheme
+   LOGICAL ::   ln_trcadv_fct    ! FCT scheme flag
+   INTEGER ::      nn_fct_h, nn_fct_v   ! =2/4 : horizontal and vertical choices of the order of FCT scheme
+   LOGICAL ::   ln_trcadv_mus    ! MUSCL scheme flag
+   LOGICAL ::      ln_mus_ups           ! use upstream scheme in vivcinity of river mouths
+   LOGICAL ::   ln_trcadv_ubs    ! UBS scheme flag
+   INTEGER ::      nn_ubs_v             ! =2/4 : vertical choice of the order of UBS scheme
+   LOGICAL ::   ln_trcadv_qck    ! QUICKEST scheme flag
+
+   INTEGER ::   nadv             ! choice of the type of advection scheme
+   !                             ! associated indices:
+   INTEGER, PARAMETER ::   np_NO_adv  = 0   ! no T-S advection
+   INTEGER, PARAMETER ::   np_CEN     = 1   ! 2nd/4th order centered scheme
+   INTEGER, PARAMETER ::   np_FCT     = 2   ! 2nd/4th order Flux Corrected Transport scheme
+   INTEGER, PARAMETER ::   np_MUS     = 3   ! MUSCL scheme
+   INTEGER, PARAMETER ::   np_UBS     = 4   ! 3rd order Upstream Biased Scheme
+   INTEGER, PARAMETER ::   np_QCK     = 5   ! QUICK scheme
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_adv( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_adv  ***
+      !!
+      !! ** Purpose :   compute the ocean tracer advection trend.
+      !!
+      !! ** Method  : - Update after tracers (tra) with the advection term following nadv
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   jk   ! dummy loop index
+      CHARACTER (len=22) ::   charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zun, zvn, zwn  ! effective velocity
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_adv')
+      !
+      !                                         !==  effective transport  ==!
+      IF( l_offline ) THEN
+         zun(:,:,:) = un(:,:,:)                    ! already in (un,vn,wn)
+         zvn(:,:,:) = vn(:,:,:)
+         zwn(:,:,:) = wn(:,:,:)
+      ELSE                                         ! build the effective transport
+         zun(:,:,jpk) = 0._wp
+         zvn(:,:,jpk) = 0._wp
+         zwn(:,:,jpk) = 0._wp
+         IF( ln_wave .AND. ln_sdw )  THEN
+            DO jk = 1, jpkm1                                                       ! eulerian transport + Stokes Drift
+               zun(:,:,jk) = e2u  (:,:) * e3u_n(:,:,jk) * ( un(:,:,jk) + usd(:,:,jk) )
+               zvn(:,:,jk) = e1v  (:,:) * e3v_n(:,:,jk) * ( vn(:,:,jk) + vsd(:,:,jk) )
+               zwn(:,:,jk) = e1e2t(:,:)                 * ( wn(:,:,jk) + wsd(:,:,jk) )
+            END DO
+         ELSE
+            DO jk = 1, jpkm1
+               zun(:,:,jk) = e2u  (:,:) * e3u_n(:,:,jk) * un(:,:,jk)                   ! eulerian transport
+               zvn(:,:,jk) = e1v  (:,:) * e3v_n(:,:,jk) * vn(:,:,jk)
+               zwn(:,:,jk) = e1e2t(:,:)                 * wn(:,:,jk)
+            END DO
+         ENDIF
+         !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN                                 ! add z-tilde and/or vvl corrections
+            zun(:,:,:) = zun(:,:,:) + un_td(:,:,:)
+            zvn(:,:,:) = zvn(:,:,:) + vn_td(:,:,:)
+         ENDIF
+         !
+         IF( ln_ldfeiv .AND. .NOT. ln_traldf_triad )   & 
+            &              CALL ldf_eiv_trp( kt, nittrc000, zun, zvn, zwn, 'TRC' )  ! add the eiv transport
+         !
+         IF( ln_mle    )   CALL tra_mle_trp( kt, nittrc000, zun, zvn, zwn, 'TRC' )  ! add the mle transport
+         !
+      ENDIF
+      !
+      SELECT CASE ( nadv )                      !==  compute advection trend and add it to general trend  ==!
+      !
+      CASE ( np_CEN )                                 ! Centered : 2nd / 4th order
+         CALL tra_adv_cen( kt, nittrc000,'TRC',          zun, zvn, zwn     , trn, tra, jptra, nn_cen_h, nn_cen_v )
+      CASE ( np_FCT )                                 ! FCT      : 2nd / 4th order
+         CALL tra_adv_fct( kt, nittrc000,'TRC', r2dttrc, zun, zvn, zwn, trb, trn, tra, jptra, nn_fct_h, nn_fct_v )
+      CASE ( np_MUS )                                 ! MUSCL
+         CALL tra_adv_mus( kt, nittrc000,'TRC', r2dttrc, zun, zvn, zwn, trb,      tra, jptra        , ln_mus_ups ) 
+      CASE ( np_UBS )                                 ! UBS
+         CALL tra_adv_ubs( kt, nittrc000,'TRC', r2dttrc, zun, zvn, zwn, trb, trn, tra, jptra          , nn_ubs_v )
+      CASE ( np_QCK )                                 ! QUICKEST
+         CALL tra_adv_qck( kt, nittrc000,'TRC', r2dttrc, zun, zvn, zwn, trb, trn, tra, jptra                     )
+      !
+      END SELECT
+      !                  
+      IF( ln_ctl ) THEN                         !== print mean trends (used for debugging)
+         WRITE(charout, FMT="('adv ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      END IF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_adv')
+      !
+   END SUBROUTINE trc_adv
+
+
+   SUBROUTINE trc_adv_ini
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_adv_ini  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options for 
+      !!              passive tracer advection schemes and set nadv
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios   ! Local integer
+      !!
+      NAMELIST/namtrc_adv/ ln_trcadv_OFF,                        &   ! No advection
+         &                 ln_trcadv_cen, nn_cen_h, nn_cen_v,    &   ! CEN
+         &                 ln_trcadv_fct, nn_fct_h, nn_fct_v,    &   ! FCT
+         &                 ln_trcadv_mus, ln_mus_ups,            &   ! MUSCL
+         &                 ln_trcadv_ubs,           nn_ubs_v,    &   ! UBS
+         &                 ln_trcadv_qck                             ! QCK
+      !!----------------------------------------------------------------------
+      !
+      !                                !==  Namelist  ==!
+      REWIND( numnat_ref )                   !  namtrc_adv in reference namelist 
+      READ  ( numnat_ref, namtrc_adv, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_adv in reference namelist' )
+      REWIND( numnat_cfg )                   ! namtrc_adv in configuration namelist
+      READ  ( numnat_cfg, namtrc_adv, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_adv in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_adv )
+      !
+      IF(lwp) THEN                           ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_adv_ini : choice/control of the tracer advection scheme'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtrc_adv : chose a advection scheme for tracers'
+         WRITE(numout,*) '      No advection on passive tracers           ln_trcadv_OFF = ', ln_trcadv_OFF
+         WRITE(numout,*) '      centered scheme                           ln_trcadv_cen = ', ln_trcadv_cen
+         WRITE(numout,*) '            horizontal 2nd/4th order               nn_cen_h   = ', nn_fct_h
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_cen_v   = ', nn_fct_v
+         WRITE(numout,*) '      Flux Corrected Transport scheme           ln_trcadv_fct = ', ln_trcadv_fct
+         WRITE(numout,*) '            horizontal 2nd/4th order               nn_fct_h   = ', nn_fct_h
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_fct_v   = ', nn_fct_v
+         WRITE(numout,*) '      MUSCL scheme                              ln_trcadv_mus = ', ln_trcadv_mus
+         WRITE(numout,*) '            + upstream scheme near river mouths    ln_mus_ups = ', ln_mus_ups
+         WRITE(numout,*) '      UBS scheme                                ln_trcadv_ubs = ', ln_trcadv_ubs
+         WRITE(numout,*) '            vertical   2nd/4th order               nn_ubs_v   = ', nn_ubs_v
+         WRITE(numout,*) '      QUICKEST scheme                           ln_trcadv_qck = ', ln_trcadv_qck
+      ENDIF
+      !
+      !                                !==  Parameter control & set nadv ==!
+      ioptio = 0
+      IF( ln_trcadv_OFF ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_NO_adv   ;   ENDIF
+      IF( ln_trcadv_cen ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_CEN      ;   ENDIF
+      IF( ln_trcadv_fct ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_FCT      ;   ENDIF
+      IF( ln_trcadv_mus ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_MUS      ;   ENDIF
+      IF( ln_trcadv_ubs ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_UBS      ;   ENDIF
+      IF( ln_trcadv_qck ) THEN   ;   ioptio = ioptio + 1   ;   nadv = np_QCK      ;   ENDIF
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'trc_adv_ini: Choose ONE advection option in namelist namtrc_adv' )
+      !
+      IF( ln_trcadv_cen .AND. ( nn_cen_h /= 2 .AND. nn_cen_h /= 4 )   &
+                        .AND. ( nn_cen_v /= 2 .AND. nn_cen_v /= 4 )   ) THEN
+        CALL ctl_stop( 'trc_adv_ini: CEN scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_trcadv_fct .AND. ( nn_fct_h /= 2 .AND. nn_fct_h /= 4 )   &
+                        .AND. ( nn_fct_v /= 2 .AND. nn_fct_v /= 4 )   ) THEN
+        CALL ctl_stop( 'trc_adv_ini: FCT scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_trcadv_ubs .AND. ( nn_ubs_v /= 2 .AND. nn_ubs_v /= 4 )   ) THEN
+        CALL ctl_stop( 'trc_adv_ini: UBS scheme, choose 2nd or 4th order' )
+      ENDIF
+      IF( ln_trcadv_ubs .AND. nn_ubs_v == 4 ) THEN
+         CALL ctl_warn( 'trc_adv_ini: UBS scheme, only 2nd FCT scheme available on the vertical. It will be used' )
+      ENDIF
+      IF( ln_isfcav ) THEN                                                       ! ice-shelf cavities
+         IF(  ln_trcadv_cen .AND. nn_cen_v == 4    .OR.   &                            ! NO 4th order with ISF
+            & ln_trcadv_fct .AND. nn_fct_v == 4   )   CALL ctl_stop( 'tra_adv_ini: 4th order COMPACT scheme not allowed with ISF' )
+      ENDIF
+      !
+      !                                !==  Print the choice  ==!  
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE ( nadv )
+         CASE( np_NO_adv  )   ;   WRITE(numout,*) '      ===>>   NO passive tracer advection'
+         CASE( np_CEN     )   ;   WRITE(numout,*) '      ===>>   CEN      scheme is used. Horizontal order: ', nn_cen_h,   &
+            &                                                                     ' Vertical   order: ', nn_cen_v
+         CASE( np_FCT     )   ;   WRITE(numout,*) '      ===>>   FCT      scheme is used. Horizontal order: ', nn_fct_h,   &
+            &                                                                      ' Vertical   order: ', nn_fct_v
+         CASE( np_MUS     )   ;   WRITE(numout,*) '      ===>>   MUSCL    scheme is used'
+         CASE( np_UBS     )   ;   WRITE(numout,*) '      ===>>   UBS      scheme is used'
+         CASE( np_QCK     )   ;   WRITE(numout,*) '      ===>>   QUICKEST scheme is used'
+         END SELECT
+      ENDIF
+      !
+   END SUBROUTINE trc_adv_ini
+   
+#endif
+
+  !!======================================================================
+END MODULE trcadv
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcbbl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcbbl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcbbl.F90	(revision 14097)
@@ -0,0 +1,102 @@
+MODULE trcbbl
+  !!======================================================================
+   !!                       ***  MODULE  trcbbl  ***
+   !! Ocean passive tracers physics :  advective and/or diffusive bottom boundary 
+   !!                                  layer scheme
+   !!======================================================================
+   !! History :  OPA  !  1996-06  (L. Mortier)  Original code
+   !!            8.0  !  1997-11  (G. Madec)    Optimization
+   !!   NEMO     1.0  !  2002-08  (G. Madec)  free form + modules
+   !!             -   !  2004-01  (A. de Miranda, G. Madec, J.M. Molines ) add advective bbl
+   !!            3.3  !  2009-11  (G. Madec)  merge trabbl and trabbl_adv + style + optimization 
+   !!             -   !  2010-04  (G. Madec)  Campin & Goosse advective bbl 
+   !!             -   !  2010-06  (C. Ethe, G. Madec)  merge TRA-TRC
+   !!            4.0  !  2017-04  (G. Madec)  ln_trabbl namelist variable instead of a CPP key
+   !!----------------------------------------------------------------------
+#if  defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!    trc_bbl      : update the tracer trends due to the bottom boundary layer (advective and/or diffusive)
+   !!----------------------------------------------------------------------
+   USE oce_trc        ! ocean dynamics and active tracers variables
+   USE trc            ! ocean passive tracers variables
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracer trends
+   USE trabbl         ! bottom boundary layer 
+   USE prtctl_trc     ! Print control for debbuging
+
+   PUBLIC   trc_bbl   !  routine called by trctrp.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_bbl( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE bbl  ***
+      !!                   
+      !! ** Purpose :   Compute the before tracer (t & s) trend associated 
+      !!     with the bottom boundary layer and add it to the general trend
+      !!     of tracer equations.
+      !!
+      !!----------------------------------------------------------------------  
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step 
+      INTEGER :: jn                   ! loop index
+      CHARACTER (len=22) :: charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ztrtrd
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_bbl')
+      !
+      IF( .NOT. l_offline .AND. nn_dttrc == 1 ) THEN
+         CALL bbl( kt, nittrc000, 'TRC' )      ! Online coupling with dynamics  : Computation of bbl coef and bbl transport
+         l_bbl = .FALSE.                       ! Offline coupling with dynamics : Read bbl coef and bbl transport from input files
+      ENDIF
+
+      IF( l_trdtrc )  THEN
+         ALLOCATE( ztrtrd(jpi,jpj,jpk,jptra) ) ! temporary save of trends
+         ztrtrd(:,:,:,:)  = tra(:,:,:,:)
+      ENDIF
+
+      !* Diffusive bbl :
+      IF( nn_bbl_ldf == 1 ) THEN
+         !
+         CALL tra_bbl_dif( trb, tra, jptra )  
+         IF( ln_ctl )   THEN
+            WRITE(charout, FMT="(' bbl_dif')")  ;  CALL prt_ctl_trc_info(charout)
+            CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+         ENDIF
+         !
+      ENDIF
+
+      !* Advective bbl : bbl upstream advective trends added to the tracer trends
+      IF( nn_bbl_adv /= 0 ) THEN
+         !
+         CALL tra_bbl_adv( trb, tra, jptra )  
+         IF( ln_ctl )   THEN
+            WRITE(charout, FMT="(' bbl_adv')")  ;  CALL prt_ctl_trc_info(charout)
+            CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+         ENDIF
+         !
+      ENDIF
+
+      IF( l_trdtrc )   THEN                      ! save the horizontal diffusive trends for further diagnostics
+        DO jn = 1, jptra
+           ztrtrd(:,:,:,jn) = tra(:,:,:,jn) - ztrtrd(:,:,:,jn)
+           CALL trd_tra( kt, 'TRC', jn, jptra_bbl, ztrtrd(:,:,:,jn) )
+        END DO
+        DEALLOCATE( ztrtrd ) ! temporary save of trends
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_bbl')
+      !
+   END SUBROUTINE trc_bbl
+
+#endif
+
+   !!======================================================================
+END MODULE trcbbl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcdmp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcdmp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcdmp.F90	(revision 14097)
@@ -0,0 +1,386 @@
+MODULE trcdmp
+   !!======================================================================
+   !!                       ***  MODULE  trcdmp  ***
+   !! Ocean physics: internal restoring trend on passive tracers
+   !!======================================================================
+   !! History :  OPA  !  1991-03  (O. Marti, G. Madec)  Original code
+   !!                 !  1996-01  (G. Madec) statement function for e3
+   !!                 !  1997-05  (H. Loukos)  adapted for passive tracers
+   !!    NEMO    9.0  !  2004-03  (C. Ethe)    free form + modules
+   !!            3.2  !  2007-02  (C. Deltel)  Diagnose ML trends for passive tracers
+   !!            3.3  !  2010-06  (C. Ethe, G. Madec) merge TRA-TRC 
+   !!----------------------------------------------------------------------
+#if  defined key_top 
+   !!----------------------------------------------------------------------
+   !!   trc_dmp      : update the tracer trend with the internal damping
+   !!   trc_dmp_init : initialization, namlist read, parameters control
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! ocean dynamics and tracers variables
+   USE trc             ! ocean passive tracers variables
+   USE trcdta
+   USE tradmp
+   USE trdtra
+   USE trd_oce
+   !
+   USE iom
+   USE prtctl_trc      ! Print control for debbuging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_dmp      
+   PUBLIC trc_dmp_clo   
+   PUBLIC trc_dmp_alloc  
+   PUBLIC trc_dmp_ini    
+
+   INTEGER            , PUBLIC ::   nn_zdmp_tr    !: = 0/1/2 flag for damping in the mixed layer
+   CHARACTER(LEN=200) , PUBLIC ::   cn_resto_tr   !: File containing restoration coefficient
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   restotr   ! restoring coeff. on tracers (s-1)
+
+   INTEGER, PARAMETER         ::   npncts = 8       ! number of closed sea
+   INTEGER, DIMENSION(npncts) ::   nctsi1, nctsj1   ! south-west closed sea limits (i,j)
+   INTEGER, DIMENSION(npncts) ::   nctsi2, nctsj2   ! north-east closed sea limits (i,j)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trc_dmp_alloc()
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dmp_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( restotr(jpi,jpj,jpk) , STAT=trc_dmp_alloc )
+      !
+      IF( trc_dmp_alloc /= 0 )   CALL ctl_warn('trc_dmp_alloc: failed to allocate array')
+      !
+   END FUNCTION trc_dmp_alloc
+
+
+   SUBROUTINE trc_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dmp  ***
+      !!                  
+      !! ** Purpose :   Compute the passive tracer trend due to a newtonian damping
+      !!      of the tracer field towards given data field and add it to the
+      !!      general tracer trends.
+      !!
+      !! ** Method  :   Newtonian damping towards trdta computed 
+      !!      and add to the general tracer trends:
+      !!                     trn = tra + restotr * (trdta - trb)
+      !!         The trend is computed either throughout the water column
+      !!      (nlmdmptr=0) or in area of weak vertical mixing (nlmdmptr=1) or
+      !!      below the well mixed layer (nlmdmptr=2)
+      !!
+      !! ** Action  : - update the tracer trends tra with the newtonian 
+      !!                damping trends.
+      !!              - save the trends ('key_trdmxl_trc')
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk, jn, jl   ! dummy loop indices
+      CHARACTER (len=22) ::   charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrtrd
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrcdta   ! 3D  workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_dmp')
+      !
+      IF( l_trdtrc )   ALLOCATE( ztrtrd(jpi,jpj,jpk) )   ! temporary save of trends
+      !
+      IF( nb_trcdta > 0 ) THEN  ! Initialisation of tracer from a file that may also be used for damping
+         !
+         ALLOCATE( ztrcdta(jpi,jpj,jpk) )    ! Memory allocation
+         !                                                          ! ===========
+         DO jn = 1, jptra                                           ! tracer loop
+            !                                                       ! ===========
+            IF( l_trdtrc ) ztrtrd(:,:,:) = tra(:,:,:,jn)    ! save trends 
+            !
+            IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
+               !
+               jl = n_trc_index(jn) 
+               CALL trc_dta( kt, sf_trcdta(jl), rf_trfac(jl), ztrcdta )   ! read tracer data at nit000
+               !
+               SELECT CASE ( nn_zdmp_tr )
+               !
+               CASE( 0 )                !==  newtonian damping throughout the water column  ==!
+                  DO jk = 1, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + restotr(ji,jj,jk) * ( ztrcdta(ji,jj,jk) - trb(ji,jj,jk,jn) )
+                        END DO
+                     END DO
+                  END DO
+                  !
+               CASE ( 1 )                !==  no damping in the turbocline (avt > 5 cm2/s)  ==!
+                  DO jk = 1, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           IF( avt(ji,jj,jk) <= avt_c )  THEN 
+                              tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + restotr(ji,jj,jk) * ( ztrcdta(ji,jj,jk) - trb(ji,jj,jk,jn) )
+                           ENDIF
+                        END DO
+                     END DO
+                  END DO
+                  !
+               CASE ( 2 )               !==  no damping in the mixed layer   ==! 
+                  DO jk = 1, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           IF( gdept_n(ji,jj,jk) >= hmlp (ji,jj) ) THEN
+                              tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + restotr(ji,jj,jk) * ( ztrcdta(ji,jj,jk) - trb(ji,jj,jk,jn) )
+                           END IF
+                        END DO
+                     END DO
+                  END DO
+                  !  
+               END SELECT
+               ! 
+            ENDIF
+            !
+            IF( l_trdtrc ) THEN
+               ztrtrd(:,:,:) = tra(:,:,:,jn) -  ztrtrd(:,:,:)
+               CALL trd_tra( kt, 'TRC', jn, jptra_dmp, ztrtrd )
+            END IF
+            !                                                       ! ===========
+         END DO                                                     ! tracer loop
+         !                                                          ! ===========
+         DEALLOCATE( ztrcdta )
+      ENDIF
+      !
+      IF( l_trdtrc )  DEALLOCATE( ztrtrd )
+      !                                          ! print mean trends (used for debugging)
+      IF( ln_ctl ) THEN
+         WRITE(charout, FMT="('dmp ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_dmp')
+      !
+   END SUBROUTINE trc_dmp
+
+
+   SUBROUTINE trc_dmp_ini
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_dmp_ini  ***
+      !! 
+      !! ** Purpose :   Initialization for the newtonian damping 
+      !!
+      !! ** Method  :   read the nammbf namelist and check the parameters
+      !!              called by trc_dmp at the first timestep (nittrc000)
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, imask  ! local integers
+      !!
+      NAMELIST/namtrc_dmp/ nn_zdmp_tr , cn_resto_tr
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnat_ref )              ! Namelist namtrc_dmp in reference namelist : Passive tracers newtonian damping
+      READ  ( numnat_ref, namtrc_dmp, IOSTAT = ios, ERR = 909)
+909   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_dmp in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc_dmp in configuration namelist : Passive tracers newtonian damping
+      READ  ( numnat_cfg, namtrc_dmp, IOSTAT = ios, ERR = 910)
+910   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_dmp in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_dmp )
+
+      IF(lwp) THEN                       ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_dmp : Passive tracers newtonian damping'
+         WRITE(numout,*) '~~~~~~~'
+         WRITE(numout,*) '   Namelist namtrc_dmp : set damping parameter'
+         WRITE(numout,*) '      mixed layer damping option     nn_zdmp_tr  = ', nn_zdmp_tr, '(zoom: forced to 0)'
+         WRITE(numout,*) '      Restoration coeff file         cn_resto_tr = ', cn_resto_tr
+      ENDIF
+      !                          ! Allocate arrays
+      IF( trc_dmp_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trc_dmp_ini: unable to allocate arrays' )
+      !
+      SELECT CASE ( nn_zdmp_tr )
+      CASE ( 0 )   ;   IF(lwp) WRITE(numout,*) '      ===>>   tracer damping throughout the water column'
+      CASE ( 1 )   ;   IF(lwp) WRITE(numout,*) '      ===>>   no tracer damping in the turbocline (avt > 5 cm2/s)'
+      CASE ( 2 )   ;   IF(lwp) WRITE(numout,*) '      ===>>   no tracer damping in the mixed layer'
+      CASE DEFAULT
+         WRITE(ctmp1,*) 'bad flag value for nn_zdmp_tr = ', nn_zdmp_tr
+         CALL ctl_stop(ctmp1)
+      END SELECT
+
+      IF( .NOT.lk_c1d ) THEN
+         IF( .NOT.ln_tradmp )   &
+            &   CALL ctl_stop( 'passive tracer damping need ln_tradmp to compute damping coef.' )
+         !
+         !                          ! Read damping coefficients from file
+         !Read in mask from file
+         CALL iom_open ( cn_resto_tr, imask)
+         CALL iom_get  ( imask, jpdom_autoglo, 'resto', restotr)
+         CALL iom_close( imask )
+         !
+      ENDIF
+      !
+   END SUBROUTINE trc_dmp_ini
+
+
+   SUBROUTINE trc_dmp_clo( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_dmp_clo  ***
+      !!
+      !! ** Purpose :   Closed sea domain initialization
+      !!
+      !! ** Method  :   if a closed sea is located only in a model grid point
+      !!                we restore to initial data
+      !!
+      !! ** Action  :   nctsi1(), nctsj1() : south-west closed sea limits (i,j)
+      !!                nctsi2(), nctsj2() : north-east Closed sea limits (i,j)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !
+      INTEGER :: ji , jj, jk, jn, jl, jc                    ! dummy loop indicesa
+      INTEGER :: isrow                                      ! local index
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrcdta       ! 3D  workspace
+      !!----------------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+         ! initial values
+         nctsi1(:) = 1  ;  nctsi2(:) = 1
+         nctsj1(:) = 1  ;  nctsj2(:) = 1
+
+         ! set the closed seas (in data domain indices)
+         ! -------------------
+
+         IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA") THEN
+            !
+            SELECT CASE ( nn_cfg )
+            !                                           ! =======================
+            CASE ( 1 )                                  ! eORCA_R1 configuration
+            !                                           ! =======================
+            isrow = 332 - jpjglo
+            !
+            nctsi1(1)   = 333  ; nctsj1(1)   = 243 - isrow   ! Caspian Sea
+            nctsi2(1)   = 342  ; nctsj2(1)   = 274 - isrow
+            !                                        
+            nctsi1(2)   = 198  ; nctsj1(2)   = 258 - isrow   ! Lake Superior
+            nctsi2(2)   = 204  ; nctsj2(2)   = 262 - isrow
+            !                                         
+            nctsi1(3)   = 201  ; nctsj1(3)   = 250 - isrow   ! Lake Michigan
+            nctsi2(3)   = 203  ; nctsj2(3)   = 256 - isrow
+            !                                        
+            nctsi1(4)   = 204  ; nctsj1(4)   = 252 - isrow   ! Lake Huron
+            nctsi2(4)   = 209  ; nctsj2(4)   = 256 - isrow
+            !                                        
+            nctsi1(5)   = 206  ; nctsj1(5)   = 249 - isrow   ! Lake Erie
+            nctsi2(5)   = 209  ; nctsj2(5)   = 251 - isrow
+            !                                        
+            nctsi1(6)   = 210  ; nctsj1(6)   = 252 - isrow   ! Lake Ontario
+            nctsi2(6)   = 212  ; nctsj2(6)   = 252 - isrow
+            !                                        
+            nctsi1(7)   = 321  ; nctsj1(7)   = 180 - isrow   ! Victoria Lake
+            nctsi2(7)   = 322  ; nctsj2(7)   = 189 - isrow
+            !                                        
+            nctsi1(8)   = 297  ; nctsj1(8)   = 270 - isrow   ! Baltic Sea
+            nctsi2(8)   = 308  ; nctsj2(8)   = 293 - isrow
+            !                                        
+            !                                           ! =======================
+            CASE ( 2 )                                  !  ORCA_R2 configuration
+               !                                        ! =======================
+               !                                      
+               nctsi1(1)   =  11  ;  nctsj1(1)   = 103       ! Caspian Sea
+               nctsi2(1)   =  17  ;  nctsj2(1)   = 112
+               !                                     
+               nctsi1(2)   =  97  ;  nctsj1(2)   = 107       ! Great North American Lakes
+               nctsi2(2)   = 103  ;  nctsj2(2)   = 111
+               !                                     
+               nctsi1(3)   = 174  ;  nctsj1(3)   = 107       ! Black Sea 1 : west part of the Black Sea
+               nctsi2(3)   = 181  ;  nctsj2(3)   = 112
+              !                                      
+               nctsi1(4)   =   2  ;  nctsj1(4)   = 107      ! Black Sea 2 : est part of the Black Sea
+               nctsi2(4)   =   6  ;  nctsj2(4)   = 112
+               !                                     
+               nctsi1(5)   =  145 ;  nctsj1(5)   = 116       ! Baltic Sea
+               nctsi2(5)   =  150 ;  nctsj2(5)   = 126
+               !                                        ! =======================
+            CASE ( 4 )                                  !  ORCA_R4 configuration
+               !                                        ! =======================
+               !                                   
+               nctsi1(1)   =  4  ;  nctsj1(1)   = 53         ! Caspian Sea
+               nctsi2(1)   =  4  ;  nctsj2(1)   = 56
+               !                                   
+               nctsi1(2)   = 49  ;  nctsj1(2)   = 55         ! Great North American Lakes
+               nctsi2(2)   = 51  ;  nctsj2(2)   = 56
+               !                                   
+               nctsi1(3)   = 88  ;  nctsj1(3)   = 55         ! Black Sea
+               nctsi2(3)   = 91  ;  nctsj2(3)   = 56
+               !                                   
+               nctsi1(4)   = 75  ;  nctsj1(4)   = 59         ! Baltic Sea
+               nctsi2(4)   = 76  ;  nctsj2(4)   = 61
+               !                                        ! =======================
+            CASE ( 025 )                                ! ORCA_R025 configuration
+               !                                        ! =======================
+               !                                   
+               nctsi1(1)   = 1330 ; nctsj1(1)   = 645        ! Caspian + Aral sea
+               nctsi2(1)   = 1400 ; nctsj2(1)   = 795
+               !                                    
+               nctsi1(2)   = 1284 ; nctsj1(2)   = 722        ! Azov Sea
+               nctsi2(2)   = 1304 ; nctsj2(2)   = 747
+               !
+            END SELECT
+            !
+         ENDIF
+         !
+         ! convert the position in local domain indices
+         ! --------------------------------------------
+         DO jc = 1, npncts
+            nctsi1(jc)   = mi0( nctsi1(jc) )
+            nctsj1(jc)   = mj0( nctsj1(jc) )
+            !
+            nctsi2(jc)   = mi1( nctsi2(jc) )
+            nctsj2(jc)   = mj1( nctsj2(jc) )
+         END DO
+         !
+      ENDIF
+
+      ! Restore close seas values to initial data
+      IF( ln_trcdta .AND. nb_trcdta > 0 )  THEN   ! Initialisation of tracer from a file that may also be used for damping
+         !
+         IF(lwp)  WRITE(numout,*)
+         IF(lwp)  WRITE(numout,*) ' trc_dmp_clo : Restoring of nutrients on close seas at time-step kt = ', kt
+         IF(lwp)  WRITE(numout,*)
+         !
+         ALLOCATE( ztrcdta(jpi,jpj,jpk) )   ! Memory allocation
+         !
+         DO jn = 1, jptra
+            IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
+                jl = n_trc_index(jn)
+                CALL trc_dta( kt, sf_trcdta(jl), rf_trfac(jl), ztrcdta )   ! read tracer data at nit000
+                DO jc = 1, npncts
+                   DO jk = 1, jpkm1
+                      DO jj = nctsj1(jc), nctsj2(jc)
+                         DO ji = nctsi1(jc), nctsi2(jc)
+                            trn(ji,jj,jk,jn) = ztrcdta(ji,jj,jk)
+                            trb(ji,jj,jk,jn) = trn(ji,jj,jk,jn)
+                         END DO
+                      END DO
+                   END DO
+                END DO
+             ENDIF
+          END DO
+          DEALLOCATE( ztrcdta )
+      ENDIF
+      !
+   END SUBROUTINE trc_dmp_clo
+ 
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_dmp( kt )        ! Empty routine
+      INTEGER, INTENT(in) :: kt
+      WRITE(*,*) 'trc_dmp: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_dmp
+#endif
+
+   !!======================================================================
+END MODULE trcdmp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcldf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcldf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcldf.F90	(revision 14097)
@@ -0,0 +1,195 @@
+MODULE trcldf
+   !!======================================================================
+   !!                       ***  MODULE  trcldf  ***
+   !! Ocean Passive tracers : lateral diffusive trends
+   !!=====================================================================
+   !! History :  1.0  ! 2005-11  (G. Madec)  Original code
+   !!            3.0  ! 2008-01  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!            3.7  ! 2014-03  (G. Madec)  LDF simplification
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_ldf       : update the tracer trend with the lateral diffusion
+   !!   trc_ldf_ini   : initialization, namelist read, and parameters control
+   !!----------------------------------------------------------------------
+   USE trc            ! ocean passive tracers variables
+   USE oce_trc        ! ocean dynamics and active tracers
+   USE ldftra         ! lateral diffusion: eddy diffusivity & EIV coeff.
+   USE ldfslp         ! Lateral diffusion: slopes of neutral surfaces
+   USE traldf_lap_blp ! lateral diffusion: lap/bilaplacian iso-level      operator  (tra_ldf_lap/_blp   routine)
+   USE traldf_iso     ! lateral diffusion: laplacian iso-neutral standard operator  (tra_ldf_iso        routine)
+   USE traldf_triad   ! lateral diffusion: laplacian iso-neutral triad    operator  (tra_ldf_     triad routine)
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers
+   !
+   USE prtctl_trc     ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_ldf    
+   PUBLIC   trc_ldf_ini   
+   !
+   !                                      !!: ** lateral mixing namelist (nam_trcldf) **
+   LOGICAL , PUBLIC ::   ln_trcldf_OFF     !: No operator (no explicit lateral diffusion)
+   LOGICAL , PUBLIC ::   ln_trcldf_tra     !: use active tracer operator
+   REAL(wp), PUBLIC ::      rn_ldf_multi      !: multiplier of T-S eddy diffusivity to obtain the passive tracer one
+   REAL(wp), PUBLIC ::      rn_fact_lap       !: enhanced Equatorial zonal diffusivity coefficent
+   !
+   INTEGER  ::   nldf_trc = 0   ! type of lateral diffusion used defined from ln_traldf_... (namlist logicals)
+   REAL(wp) ::   rldf           ! multiplier between active and passive tracers eddy diffusivity   [-]
+   
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_ldf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_ldf  ***
+      !!
+      !! ** Purpose :   compute the lateral ocean tracer physics.
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER            :: ji, jj, jk, jn
+      REAL(wp)           :: zdep
+      CHARACTER (len=22) :: charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk)   ::   zahu, zahv
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   ztrtrd
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_trcldf_OFF )   RETURN        ! not lateral diffusion applied on passive tracers
+      !
+      IF( ln_timing )   CALL timing_start('trc_ldf')
+      !
+      IF( l_trdtrc )  THEN
+         ALLOCATE( ztrtrd(jpi,jpj,jpk,jptra) )
+         ztrtrd(:,:,:,:)  = tra(:,:,:,:)
+      ENDIF
+      !                                  !* set the lateral diffusivity coef. for passive tracer      
+      zahu(:,:,:) = rldf * ahtu(:,:,:) 
+      zahv(:,:,:) = rldf * ahtv(:,:,:)
+      !                                  !* Enhanced zonal diffusivity coefficent in the equatorial domain
+      DO jk= 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( gdept_n(ji,jj,jk) > 200. .AND. gphit(ji,jj) < 5. .AND. gphit(ji,jj) > -5. ) THEN
+                  zdep = MAX( gdept_n(ji,jj,jk) - 1000., 0. ) / 1000.
+                  zahu(ji,jj,jk) = zahu(ji,jj,jk) * MAX( 1., rn_fact_lap * EXP( -zdep ) )
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      SELECT CASE ( nldf_trc )                 !* compute lateral mixing trend and add it to the general trend
+      !
+      CASE ( np_lap   )                               ! iso-level laplacian
+         CALL tra_ldf_lap  ( kt, nittrc000,'TRC', zahu, zahv, gtru, gtrv, gtrui, gtrvi, trb,      tra, jptra,    1     )
+      CASE ( np_lap_i )                               ! laplacian : standard iso-neutral operator (Madec)
+         CALL tra_ldf_iso  ( kt, nittrc000,'TRC', zahu, zahv, gtru, gtrv, gtrui, gtrvi, trb, trb, tra, jptra,    1     )
+      CASE ( np_lap_it )                              ! laplacian : triad iso-neutral operator (griffies)
+         CALL tra_ldf_triad( kt, nittrc000,'TRC', zahu, zahv, gtru, gtrv, gtrui, gtrvi, trb, trb, tra, jptra,    1     )
+      CASE ( np_blp , np_blp_i , np_blp_it )          ! bilaplacian: all operator (iso-level, -neutral)
+         CALL tra_ldf_blp  ( kt, nittrc000,'TRC', zahu, zahv, gtru, gtrv, gtrui, gtrvi, trb     , tra, jptra, nldf_trc )
+      END SELECT
+      !
+      IF( l_trdtrc )   THEN                    ! send the trends for further diagnostics
+        DO jn = 1, jptra
+           ztrtrd(:,:,:,jn) = tra(:,:,:,jn) - ztrtrd(:,:,:,jn)
+           CALL trd_tra( kt, 'TRC', jn, jptra_ldf, ztrtrd(:,:,:,jn) )
+        END DO
+        DEALLOCATE( ztrtrd )
+      ENDIF
+      !                
+      IF( ln_ctl ) THEN                        ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('ldf ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_ldf')
+      !
+   END SUBROUTINE trc_ldf
+
+
+   SUBROUTINE trc_ldf_ini
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE ldf_ctl  ***
+      !!
+      !! ** Purpose :   Define the operator for the lateral diffusion
+      !!
+      !! ** Method  : - ln_trcldf_tra=T : use nldf_tra set in ldftra module 
+      !!              to defined the passive tracer lateral diffusive operator
+      !!              - ln_trcldf_OFF=T : no explicit diffusion used
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios, ioptio   ! local integers
+      !!
+      NAMELIST/namtrc_ldf/ ln_trcldf_OFF , ln_trcldf_tra,   &   ! operator & direction
+         &                 rn_ldf_multi  , rn_fact_lap          ! coefficient
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_ldf_ini : lateral passive tracer diffusive operator'
+         WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnat_ref )             !  namtrc_ldf in reference namelist 
+      READ  ( numnat_ref, namtrc_ldf, IOSTAT = ios, ERR = 903)
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_ldf in reference namelist' )
+      !
+      REWIND( numnat_cfg )             !  namtrc_ldf in configuration namelist 
+      READ  ( numnat_cfg, namtrc_ldf, IOSTAT = ios, ERR = 904 )
+904   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_ldf in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_ldf )
+      !
+      IF(lwp) THEN                     ! Namelist print
+         WRITE(numout,*) '   Namelist namtrc_ldf : set lateral mixing parameters (type, direction, coefficients)'
+         WRITE(numout,*) '      no explicit diffusion                 ln_trcldf_OFF   = ', ln_trcldf_OFF
+         WRITE(numout,*) '      use active tracer operator            ln_trcldf_tra   = ', ln_trcldf_tra
+         WRITE(numout,*) '      diffusivity coefficient :'
+         WRITE(numout,*) '         multiplier of TRA coef. for TRC       rn_ldf_multi = ', rn_ldf_multi
+         WRITE(numout,*) '         enhanced zonal Eq. laplacian coef.    rn_fact_lap  = ', rn_fact_lap
+
+      ENDIF
+      !      
+      !                                ! control the namelist parameters
+      nldf_trc = np_ERROR
+      ioptio   = 0
+      IF( ln_trcldf_OFF  ) THEN   ;   nldf_trc = np_no_ldf   ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ln_trcldf_tra  ) THEN   ;   nldf_trc = nldf_tra    ;   ioptio = ioptio + 1   ;   ENDIF
+      IF( ioptio /=  1   )   CALL ctl_stop( 'trc_ldf_ini: use ONE of the 2 operator options (NONE/tra)' )
+      
+      !                                ! multiplier : passive/active tracers ration
+      IF( ln_traldf_lap ) THEN               ! laplacian operator
+         rldf = rn_ldf_multi                       ! simple multiplier
+      ELSEIF( ln_traldf_blp ) THEN           ! bilaplacian operator: 
+         rldf = SQRT( ABS( rn_ldf_multi )  )       ! the coef. used is the SQRT of the bilaplacian coef.
+      ENDIF
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         SELECT CASE( nldf_trc )
+         CASE( np_no_ldf )   ;   WRITE(numout,*) '      ===>>   NO lateral diffusion'
+         CASE( np_lap    )   ;   WRITE(numout,*) '      ===>>   laplacian iso-level operator'
+         CASE( np_lap_i  )   ;   WRITE(numout,*) '      ===>>   Rotated laplacian operator (standard)'
+         CASE( np_lap_it )   ;   WRITE(numout,*) '      ===>>   Rotated laplacian operator (triad)'
+         CASE( np_blp    )   ;   WRITE(numout,*) '      ===>>   bilaplacian iso-level operator'
+         CASE( np_blp_i  )   ;   WRITE(numout,*) '      ===>>   Rotated bilaplacian operator (standard)'
+         CASE( np_blp_it )   ;   WRITE(numout,*) '      ===>>   Rotated bilaplacian operator (triad)'
+         END SELECT
+      ENDIF
+      !
+   END SUBROUTINE trc_ldf_ini
+
+#endif
+   !!======================================================================
+END MODULE trcldf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcnxt.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcnxt.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcnxt.F90	(revision 14097)
@@ -0,0 +1,290 @@
+MODULE trcnxt
+   !!======================================================================
+   !!                       ***  MODULE  trcnxt  ***
+   !! Ocean passive tracers:  time stepping on passives tracers
+   !!======================================================================
+   !! History :  7.0  !  1991-11  (G. Madec)  Original code
+   !!                 !  1993-03  (M. Guyon)  symetrical conditions
+   !!                 !  1995-02  (M. Levy)   passive tracers
+   !!                 !  1996-02  (G. Madec & M. Imbard)  opa release 8.0
+   !!            8.0  !  1996-04  (A. Weaver)  Euler forward step
+   !!            8.2  !  1999-02  (G. Madec, N. Grima)  semi-implicit pressure grad.
+   !!  NEMO      1.0  !  2002-08  (G. Madec)  F90: Free form and module
+   !!                 !  2002-08  (G. Madec)  F90: Free form and module
+   !!                 !  2002-11  (C. Talandier, A-M Treguier) Open boundaries
+   !!                 !  2004-03  (C. Ethe) passive tracers
+   !!                 !  2007-02  (C. Deltel) Diagnose ML trends for passive tracers
+   !!            2.0  !  2006-02  (L. Debreu, C. Mazauric) Agrif implementation
+   !!            3.0  !  2008-06  (G. Madec)  time stepping always done in trazdf
+   !!            3.1  !  2009-02  (G. Madec, R. Benshila)  re-introduce the vvl option
+   !!            3.3  !  2010-06  (C. Ethe, G. Madec) Merge TRA-TRC
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_nxt     : time stepping on passive tracers
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! ocean dynamics and tracers variables
+   USE trc             ! ocean passive tracers variables
+   USE trd_oce
+   USE trdtra
+   USE tranxt
+   USE bdy_oce   , ONLY: ln_bdy
+   USE trcbdy          ! BDY open boundaries
+# if defined key_agrif
+   USE agrif_top_interp
+# endif
+   !
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE prtctl_trc      ! Print control for debbuging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_nxt   ! routine called by step.F90
+
+   REAL(wp) ::   rfact1, rfact2
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_nxt( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trcnxt  ***
+      !!
+      !! ** Purpose :   Compute the passive tracers fields at the 
+      !!      next time-step from their temporal trends and swap the fields.
+      !! 
+      !! ** Method  :   Apply lateral boundary conditions on (ua,va) through 
+      !!      call to lbc_lnk routine
+      !!   default:
+      !!      arrays swap
+      !!         (trn) = (tra) ; (tra) = (0,0)
+      !!         (trb) = (trn) 
+      !!
+      !!   For Arakawa or TVD Scheme : 
+      !!      A Asselin time filter applied on now tracers (trn) to avoid
+      !!      the divergence of two consecutive time-steps and tr arrays
+      !!      to prepare the next time_step:
+      !!         (trb) = (trn) + atfp [ (trb) + (tra) - 2 (trn) ]
+      !!         (trn) = (tra) ; (tra) = (0,0)
+      !!
+      !!
+      !! ** Action  : - update trb, trn
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt     ! ocean time-step index
+      !
+      INTEGER  ::   jk, jn   ! dummy loop indices
+      REAL(wp) ::   zfact            ! temporary scalar
+      CHARACTER (len=22) :: charout
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:,:) ::   ztrdt    ! 4D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_nxt')
+      !
+      IF( kt == nittrc000 .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_nxt : time stepping on passive tracers'
+      ENDIF
+      !
+#if defined key_agrif
+      CALL Agrif_trc                   ! AGRIF zoom boundaries
+#endif
+      ! Update after tracer on domain lateral boundaries
+      CALL lbc_lnk( 'trcnxt', tra(:,:,:,:), 'T', 1. )   
+
+      IF( ln_bdy )  CALL trc_bdy( kt )
+
+      IF( l_trdtrc )  THEN             ! trends: store now fields before the Asselin filter application
+         ALLOCATE( ztrdt(jpi,jpj,jpk,jptra) )
+         ztrdt(:,:,:,:)  = 0._wp
+         IF( ln_traldf_iso ) THEN                       ! diagnose the "pure" Kz diffusive trend 
+            DO jn = 1, jptra
+               CALL trd_tra( kt, 'TRC', jn, jptra_zdfp, ztrdt(:,:,:,jn) )
+            ENDDO
+         ENDIF
+
+         ! total trend for the non-time-filtered variables. 
+         zfact = 1.0 / rdttrc
+         ! G Nurser 23 Mar 2017. Recalculate trend as Delta(e3t*T)/e3tn; e3tn cancel from tsn terms
+         IF( ln_linssh ) THEN       ! linear sea surface height only
+            DO jn = 1, jptra
+               DO jk = 1, jpkm1
+                  ztrdt(:,:,jk,jn) = ( tra(:,:,jk,jn)*e3t_a(:,:,jk) / e3t_n(:,:,jk) - trn(:,:,jk,jn)) * zfact
+               END DO
+            END DO
+         ELSE
+            DO jn = 1, jptra
+               DO jk = 1, jpkm1
+                  ztrdt(:,:,jk,jn) = ( tra(:,:,jk,jn) - trn(:,:,jk,jn) ) * zfact
+               END DO
+            END DO
+         ENDIF
+         !
+         DO jn = 1, jptra
+            CALL trd_tra( kt, 'TRC', jn, jptra_tot, ztrdt(:,:,:,jn) )
+         ENDDO
+         !
+         IF( ln_linssh ) THEN       ! linear sea surface height only
+            ! Store now fields before applying the Asselin filter 
+            ! in order to calculate Asselin filter trend later.
+            ztrdt(:,:,:,:) = trn(:,:,:,:) 
+         ENDIF
+
+      ENDIF
+      !                                ! Leap-Frog + Asselin filter time stepping
+      IF( (neuler == 0 .AND. kt == nittrc000) ) THEN
+         ! set up for leapfrog on second timestep
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+               trb(:,:,jk,jn) = trn(:,:,jk,jn)  
+               trn(:,:,jk,jn) = tra(:,:,jk,jn)
+            END DO
+         END DO
+      ELSE IF( ln_top_euler ) THEN
+         ! always doing euler timestepping
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+               trn(:,:,jk,jn) = tra(:,:,jk,jn)
+               trb(:,:,jk,jn) = trn(:,:,jk,jn)  
+            END DO
+         END DO
+      ENDIF
+      IF( (neuler == 0 .AND. kt == nittrc000) .OR. ln_top_euler ) THEN    ! Euler time-stepping (only swap)
+         IF (l_trdtrc .AND. .NOT. ln_linssh ) THEN   ! Zero Asselin filter contribution must be explicitly written out since for vvl
+            !                                        ! Asselin filter is output by tra_nxt_vvl that is not called on this time step
+            ztrdt(:,:,:,:) = 0._wp            
+            DO jn = 1, jptra
+               CALL trd_tra( kt, 'TRC', jn, jptra_atf, ztrdt(:,:,:,jn) )
+            ENDDO
+         END IF
+         !
+      ELSE     
+         IF( .NOT. l_offline ) THEN ! Leap-Frog + Asselin filter time stepping
+            IF( ln_linssh ) THEN   ;   CALL tra_nxt_fix( kt, nittrc000,         'TRC', trb, trn, tra, jptra )  !     linear ssh
+            ELSE                   ;   CALL tra_nxt_vvl( kt, nittrc000, rdttrc, 'TRC', trb, trn, tra,      &
+              &                                                                   sbc_trc, sbc_trc_b, jptra )  ! non-linear ssh
+            ENDIF
+         ELSE
+                                       CALL trc_nxt_off( kt )       ! offline 
+         ENDIF
+         !
+         CALL lbc_lnk_multi( 'trcnxt', trb(:,:,:,:), 'T', 1._wp, trn(:,:,:,:), 'T', 1._wp, tra(:,:,:,:), 'T', 1._wp )
+      ENDIF
+      !
+      IF( l_trdtrc .AND. ln_linssh ) THEN      ! trend of the Asselin filter (tb filtered - tb)/dt )
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+               zfact = 1._wp / r2dttrc  
+               ztrdt(:,:,jk,jn) = ( trb(:,:,jk,jn) - ztrdt(:,:,jk,jn) ) * zfact 
+            END DO
+            CALL trd_tra( kt, 'TRC', jn, jptra_atf, ztrdt(:,:,:,jn) )
+         END DO
+      END IF
+      IF( l_trdtrc ) DEALLOCATE( ztrdt ) 
+      !
+      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('nxt')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc(tab4d=trn, mask=tmask, clinfo=ctrcnm)
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_nxt')
+      !
+   END SUBROUTINE trc_nxt
+
+
+   SUBROUTINE trc_nxt_off( kt )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE tra_nxt_vvl  ***
+      !!
+      !! ** Purpose :   Time varying volume: apply the Asselin time filter  
+      !!                and swap the tracer fields.
+      !! 
+      !! ** Method  : - Apply a thickness weighted Asselin time filter on now fields.
+      !!              - save in (ta,sa) a thickness weighted average over the three 
+      !!             time levels which will be used to compute rdn and thus the semi-
+      !!             implicit hydrostatic pressure gradient (ln_dynhpg_imp = T)
+      !!              - swap tracer fields to prepare the next time_step.
+      !!                This can be summurized for tempearture as:
+      !!             ztm = ( e3t_n*tn + rbcp*[ e3t_b*tb - 2 e3t_n*tn + e3t_a*ta ] )   ln_dynhpg_imp = T
+      !!                  /( e3t_n    + rbcp*[ e3t_b    - 2 e3t_n    + e3t_a    ] )   
+      !!             ztm = 0                                                       otherwise
+      !!             tb  = ( e3t_n*tn + atfp*[ e3t_b*tb - 2 e3t_n*tn + e3t_a*ta ] )
+      !!                  /( e3t_n    + atfp*[ e3t_b    - 2 e3t_n    + e3t_a    ] )
+      !!             tn  = ta 
+      !!             ta  = zt        (NB: reset to 0 after eos_bn2 call)
+      !!
+      !! ** Action  : - (tb,sb) and (tn,sn) ready for the next time step
+      !!              - (ta,sa) time averaged (t,s)   (ln_dynhpg_imp = T)
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in   )   ::  kt       ! ocean time-step index
+      !!     
+      INTEGER  ::   ji, jj, jk, jn              ! dummy loop indices
+      REAL(wp) ::   ztc_a , ztc_n , ztc_b , ztc_f , ztc_d    ! local scalar
+      REAL(wp) ::   ze3t_b, ze3t_n, ze3t_a, ze3t_f, ze3t_d   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( kt == nittrc000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_nxt_off : time stepping'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         IF( .NOT. ln_linssh ) THEN
+            rfact1 = atfp * rdttrc
+            rfact2 = rfact1 / rau0
+         ENDIF
+        !  
+      ENDIF
+      !
+      DO jn = 1, jptra      
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ze3t_b = e3t_b(ji,jj,jk)
+                  ze3t_n = e3t_n(ji,jj,jk)
+                  ze3t_a = e3t_a(ji,jj,jk)
+                  !                                         ! tracer content at Before, now and after
+                  ztc_b  = trb(ji,jj,jk,jn) * ze3t_b
+                  ztc_n  = trn(ji,jj,jk,jn) * ze3t_n
+                  ztc_a  = tra(ji,jj,jk,jn) * ze3t_a
+                  !
+                  ze3t_d = ze3t_a - 2. * ze3t_n + ze3t_b
+                  ztc_d  = ztc_a  - 2. * ztc_n  + ztc_b
+                  !
+                  ze3t_f = ze3t_n + atfp * ze3t_d
+                  ztc_f  = ztc_n  + atfp * ztc_d
+                  !
+                  IF( .NOT. ln_linssh .AND. jk == mikt(ji,jj) ) THEN           ! first level 
+                     ze3t_f = ze3t_f - rfact2 * ( emp_b(ji,jj)      - emp(ji,jj)   ) 
+                     ztc_f  = ztc_f  - rfact1 * ( sbc_trc(ji,jj,jn) - sbc_trc_b(ji,jj,jn) )
+                  ENDIF
+
+                  ze3t_f = 1.e0 / ze3t_f
+                  trb(ji,jj,jk,jn) = ztc_f * ze3t_f       ! ptb <-- ptn filtered
+                  trn(ji,jj,jk,jn) = tra(ji,jj,jk,jn)     ! ptn <-- pta
+                  !
+               END DO
+            END DO
+         END DO
+         ! 
+      END DO
+      !
+   END SUBROUTINE trc_nxt_off
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                         Empty module
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_nxt( kt )  
+      INTEGER, INTENT(in) :: kt
+      WRITE(*,*) 'trc_nxt: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_nxt
+#endif
+   !!======================================================================
+END MODULE trcnxt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcrad.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcrad.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcrad.F90	(revision 14097)
@@ -0,0 +1,295 @@
+MODULE trcrad
+   !!======================================================================
+   !!                       ***  MODULE  trcrad  ***
+   !! Ocean passive tracers:  correction of negative concentrations
+   !!======================================================================
+   !! History :   -   !  01-01  (O. Aumont & E. Kestenare)  Original code
+   !!            1.0  !  04-03  (C. Ethe)  free form F90
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_rad    : correction of negative concentrations
+   !!----------------------------------------------------------------------
+   USE par_trc             ! need jptra, number of passive tracers 
+   USE oce_trc             ! ocean dynamics and tracers variables
+   USE trc                 ! ocean passive tracers variables
+   USE trd_oce
+   USE trdtra
+   USE prtctl_trc          ! Print control for debbuging
+   USE lib_fortran
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_rad     
+   PUBLIC trc_rad_ini  
+
+   LOGICAL , PUBLIC ::   ln_trcrad           !: flag to artificially correct negative concentrations
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE::   gainmass
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_rad( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_rad  ***
+      !!
+      !! ** Purpose :   "crappy" routine to correct artificial negative
+      !!              concentrations due to isopycnal scheme
+      !!
+      !! ** Method  : - PISCES or LOBSTER: Set negative concentrations to zero
+      !!                while computing the corresponding tracer content that
+      !!                is added to the tracers. Then, adjust the tracer 
+      !!                concentration using a multiplicative factor so that 
+      !!                the total tracer concentration is preserved.
+      !!              - CFC: simply set to zero the negative CFC concentration
+      !!                (the total CFC content is not strictly preserved)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      CHARACTER (len=22) :: charout
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_rad')
+      !
+      IF( ln_age     )   CALL trc_rad_sms( kt, trb, trn, jp_age , jp_age                )  !  AGE
+      IF( ll_cfc     )   CALL trc_rad_sms( kt, trb, trn, jp_cfc0, jp_cfc1               )  !  CFC model
+      IF( ln_c14     )   CALL trc_rad_sms( kt, trb, trn, jp_c14 , jp_c14                )  !  C14
+      IF( ln_pisces  )   CALL trc_rad_sms( kt, trb, trn, jp_pcs0, jp_pcs1, cpreserv='Y' )  !  PISCES model
+      IF( ln_my_trc  )   CALL trc_rad_sms( kt, trb, trn, jp_myt0, jp_myt1               )  !  MY_TRC model
+      !
+      IF(ln_ctl) THEN      ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('rad')")
+         CALL prt_ctl_trc_info( charout )
+         CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_rad')
+      !
+   END SUBROUTINE trc_rad
+
+
+   SUBROUTINE trc_rad_ini
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trc _rad_ini ***
+      !!
+      !! ** Purpose :   read  namelist options 
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namtrc_rad/ ln_trcrad
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnat_ref )              ! namtrc_rad in reference namelist 
+      READ  ( numnat_ref, namtrc_rad, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_rad in reference namelist' )
+      REWIND( numnat_cfg )              ! namtrc_rad in configuration namelist 
+      READ  ( numnat_cfg, namtrc_rad, IOSTAT = ios, ERR = 908 )
+908   IF( ios > 0 )   CALL ctl_nam ( ios , 'namtrc_rad in configuration namelist' )
+      IF(lwm) WRITE( numont, namtrc_rad )
+
+      IF(lwp) THEN                     !   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_rad : Correct artificial negative concentrations '
+         WRITE(numout,*) '~~~~~~~ '
+         WRITE(numout,*) '   Namelist namtrc_rad : treatment of negative concentrations'
+         WRITE(numout,*) '      correct artificially negative concen. or not   ln_trcrad = ', ln_trcrad
+         WRITE(numout,*)
+         IF( ln_trcrad ) THEN   ;   WRITE(numout,*) '      ===>>   ensure the global tracer conservation'
+         ELSE                   ;   WRITE(numout,*) '      ===>>   NO strict global tracer conservation'      
+         ENDIF
+      ENDIF
+      !
+      ALLOCATE( gainmass(jptra,2) )
+      gainmass(:,:) = 0.
+      !
+   END SUBROUTINE trc_rad_ini
+
+
+   SUBROUTINE trc_rad_sms( kt, ptrb, ptrn, jp_sms0, jp_sms1, cpreserv )
+      !!-----------------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_rad_sms  ***
+      !!
+      !! ** Purpose :   "crappy" routine to correct artificial negative
+      !!              concentrations due to isopycnal scheme
+      !!
+      !! ** Method  : 2 cases :
+      !!                - Set negative concentrations to zero while computing
+      !!                  the corresponding tracer content that is added to the
+      !!                  tracers. Then, adjust the tracer concentration using
+      !!                  a multiplicative factor so that the total tracer 
+      !!                  concentration is preserved.
+      !!                - simply set to zero the negative CFC concentration
+      !!                  (the total content of concentration is not strictly preserved)
+      !!--------------------------------------------------------------------------------
+      INTEGER                                , INTENT(in   ) ::   kt                 ! ocean time-step index
+      INTEGER                                , INTENT(in   ) ::   jp_sms0, jp_sms1   ! First & last index of the passive tracer model
+      REAL(wp), DIMENSION (jpi,jpj,jpk,jptra), INTENT(inout) ::   ptrb    , ptrn     ! before and now traceur concentration
+      CHARACTER( len = 1), OPTIONAL          , INTENT(in   ) ::   cpreserv           ! flag to preserve content or not
+      !
+      INTEGER ::   ji, ji2, jj, jj2, jk, jn     ! dummy loop indices
+      INTEGER ::   icnt
+      LOGICAL ::   lldebug = .FALSE.            ! local logical
+      REAL(wp)::   zcoef, zs2rdt, ztotmass
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrneg, ztrpos
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrtrd   ! workspace arrays
+      !!----------------------------------------------------------------------
+      !
+      IF( l_trdtrc )   ALLOCATE( ztrtrd(jpi,jpj,jpk) )
+      zs2rdt = 1. / ( 2. * rdt * REAL( nn_dttrc, wp ) )
+      !
+      IF( PRESENT( cpreserv )  ) THEN     !==  total tracer concentration is preserved  ==!
+         !
+         ALLOCATE( ztrneg(1:jpi,1:jpj,jp_sms0:jp_sms1), ztrpos(1:jpi,1:jpj,jp_sms0:jp_sms1) )
+
+         DO jn = jp_sms0, jp_sms1
+            ztrneg(:,:,jn) = SUM( MIN( 0., ptrb(:,:,:,jn) ) * cvol(:,:,:), dim = 3 )   ! sum of the negative values
+            ztrpos(:,:,jn) = SUM( MAX( 0., ptrb(:,:,:,jn) ) * cvol(:,:,:), dim = 3 )   ! sum of the positive values
+         END DO
+         CALL sum3x3( ztrneg )
+         CALL sum3x3( ztrpos )
+         
+         DO jn = jp_sms0, jp_sms1
+            !
+            IF( l_trdtrc )   ztrtrd(:,:,:) = ptrb(:,:,:,jn)                            ! save input trb for trend computation           
+            !
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( ztrneg(ji,jj,jn) /= 0. ) THEN                                 ! if negative values over the 3x3 box
+                        !
+                        ptrb(ji,jj,jk,jn) = ptrb(ji,jj,jk,jn) * tmask(ji,jj,jk)   ! really needed?
+                        IF( ptrb(ji,jj,jk,jn) < 0. ) ptrb(ji,jj,jk,jn) = 0.       ! supress negative values
+                        IF( ptrb(ji,jj,jk,jn) > 0. ) THEN                         ! use positive values to compensate mass gain
+                           zcoef = 1. + ztrneg(ji,jj,jn) / ztrpos(ji,jj,jn)       ! ztrpos > 0 as ptrb > 0
+                           ptrb(ji,jj,jk,jn) = ptrb(ji,jj,jk,jn) * zcoef
+                           IF( zcoef < 0. ) THEN                                  ! if the compensation exceed the positive value
+                              gainmass(jn,1) = gainmass(jn,1) - ptrb(ji,jj,jk,jn) * cvol(ji,jj,jk)   ! we are adding mass...
+                              ptrb(ji,jj,jk,jn) = 0.                              ! limit the compensation to keep positive value
+                           ENDIF
+                        ENDIF
+                        !
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+            !
+            IF( l_trdtrc ) THEN
+               ztrtrd(:,:,:) = ( ptrb(:,:,:,jn) - ztrtrd(:,:,:) ) * zs2rdt
+               CALL trd_tra( kt, 'TRC', jn, jptra_radb, ztrtrd )       ! Asselin-like trend handling
+            ENDIF
+            !
+         END DO
+ 
+         IF( kt == nitend ) THEN
+            CALL mpp_sum( 'trcrad', gainmass(:,1) )
+            DO jn = jp_sms0, jp_sms1
+               IF( gainmass(jn,1) > 0. ) THEN
+                  ztotmass = glob_sum( 'trcrad', ptrb(:,:,:,jn) * cvol(:,:,:) )
+                  IF(lwp) WRITE(numout, '(a, i2, a, D23.16, a, D23.16)') 'trcrad ptrb, traceur ', jn  &
+                     &        , ' total mass : ', ztotmass, ', mass gain : ',  gainmass(jn,1)
+               END IF
+            END DO
+         ENDIF
+
+         DO jn = jp_sms0, jp_sms1
+            ztrneg(:,:,jn) = SUM( MIN( 0., ptrn(:,:,:,jn) ) * cvol(:,:,:), dim = 3 )   ! sum of the negative values
+            ztrpos(:,:,jn) = SUM( MAX( 0., ptrn(:,:,:,jn) ) * cvol(:,:,:), dim = 3 )   ! sum of the positive values
+         END DO
+         CALL sum3x3( ztrneg )
+         CALL sum3x3( ztrpos )
+         
+         DO jn = jp_sms0, jp_sms1
+            !
+            IF( l_trdtrc )   ztrtrd(:,:,:) = ptrn(:,:,:,jn)                            ! save input trb for trend computation
+            !
+            DO jk = 1, jpkm1
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( ztrneg(ji,jj,jn) /= 0. ) THEN                                 ! if negative values over the 3x3 box
+                        !
+                        ptrn(ji,jj,jk,jn) = ptrn(ji,jj,jk,jn) * tmask(ji,jj,jk)   ! really needed?
+                        IF( ptrn(ji,jj,jk,jn) < 0. ) ptrn(ji,jj,jk,jn) = 0.       ! supress negative values
+                        IF( ptrn(ji,jj,jk,jn) > 0. ) THEN                         ! use positive values to compensate mass gain
+                           zcoef = 1. + ztrneg(ji,jj,jn) / ztrpos(ji,jj,jn)       ! ztrpos > 0 as ptrb > 0
+                           ptrn(ji,jj,jk,jn) = ptrn(ji,jj,jk,jn) * zcoef
+                           IF( zcoef < 0. ) THEN                                  ! if the compensation exceed the positive value
+                              gainmass(jn,2) = gainmass(jn,2) - ptrn(ji,jj,jk,jn) * cvol(ji,jj,jk)   ! we are adding mass...
+                              ptrn(ji,jj,jk,jn) = 0.                              ! limit the compensation to keep positive value
+                           ENDIF
+                        ENDIF
+                        !
+                     ENDIF
+                  END DO
+               END DO
+            END DO
+            !
+            IF( l_trdtrc ) THEN
+               ztrtrd(:,:,:) = ( ptrn(:,:,:,jn) - ztrtrd(:,:,:) ) * zs2rdt
+               CALL trd_tra( kt, 'TRC', jn, jptra_radn, ztrtrd )       ! standard     trend handling
+            ENDIF
+            !
+         END DO
+ 
+         IF( kt == nitend ) THEN
+            CALL mpp_sum( 'trcrad', gainmass(:,2) )
+            DO jn = jp_sms0, jp_sms1
+               IF( gainmass(jn,2) > 0. ) THEN
+                  ztotmass = glob_sum( 'trcrad', ptrn(:,:,:,jn) * cvol(:,:,:) )
+                  WRITE(numout, '(a, i2, a, D23.16, a, D23.16)') 'trcrad ptrn, traceur ', jn  &
+                     &        , ' total mass : ', ztotmass, ', mass gain : ',  gainmass(jn,1)
+               END IF
+            END DO
+         ENDIF
+
+         DEALLOCATE( ztrneg, ztrpos )
+         !
+      ELSE                                !==  total CFC content is NOT strictly preserved  ==!
+         !
+         DO jn = jp_sms0, jp_sms1  
+            !
+            IF( l_trdtrc )   ztrtrd(:,:,:) = ptrb(:,:,:,jn)                        ! save input trb for trend computation
+            !
+            WHERE( ptrb(:,:,:,jn) < 0. )   ptrb(:,:,:,jn) = 0.
+            !
+            IF( l_trdtrc ) THEN
+               ztrtrd(:,:,:) = ( ptrb(:,:,:,jn) - ztrtrd(:,:,:) ) * zs2rdt
+               CALL trd_tra( kt, 'TRC', jn, jptra_radb, ztrtrd )       ! Asselin-like trend handling
+            ENDIF
+            !
+            IF( l_trdtrc )   ztrtrd(:,:,:) = ptrn(:,:,:,jn)                        ! save input trn for trend computation
+            !
+            WHERE( ptrn(:,:,:,jn) < 0. )   ptrn(:,:,:,jn) = 0.
+            !
+            IF( l_trdtrc ) THEN
+               ztrtrd(:,:,:) = ( ptrn(:,:,:,jn) - ztrtrd(:,:,:) ) * zs2rdt
+               CALL trd_tra( kt, 'TRC', jn, jptra_radn, ztrtrd )       ! standard     trend handling
+            ENDIF
+            !
+         END DO
+         !
+      ENDIF
+      !
+      IF( l_trdtrc )  DEALLOCATE( ztrtrd )
+      !
+   END SUBROUTINE trc_rad_sms
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module :                                         NO TOP model
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_rad( kt )              ! Empty routine
+      INTEGER, INTENT(in) ::   kt
+      WRITE(*,*) 'trc_rad: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_rad
+#endif
+   
+   !!======================================================================
+END MODULE trcrad
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsbc.F90	(revision 14097)
@@ -0,0 +1,215 @@
+MODULE trcsbc
+   !!==============================================================================
+   !!                       ***  MODULE  trcsbc  ***
+   !! Ocean passive tracers:  surface boundary condition
+   !!======================================================================
+   !! History :  8.2  !  1998-10  (G. Madec, G. Roullet, M. Imbard)  Original code
+   !!            8.2  !  2001-02  (D. Ludicone)  sea ice and free surface
+   !!            8.5  !  2002-06  (G. Madec)  F90: Free form and module
+   !!            9.0  !  2004-03  (C. Ethe)  adapted for passive tracers
+   !!                 !  2006-08  (C. Deltel) Diagnose ML trends for passive tracers
+   !!==============================================================================
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_sbc      : update the tracer trend at ocean surface
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! ocean dynamics and active tracers variables
+   USE trc             ! ocean  passive tracers variables
+   USE prtctl_trc      ! Print control for debbuging
+   USE iom
+   USE trd_oce
+   USE trdtra
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sbc   ! routine called by step.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sbc ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_sbc  ***
+      !!                   
+      !! ** Purpose :   Compute the tracer surface boundary condition trend of
+      !!      (concentration/dilution effect) and add it to the general 
+      !!       trend of tracer equations.
+      !!
+      !! ** Method :
+      !!      * concentration/dilution effect:
+      !!            The surface freshwater flux modify the ocean volume
+      !!         and thus the concentration of a tracer as :
+      !!            tra = tra + emp * trn / e3t   for k=1
+      !!         where emp, the surface freshwater budget (evaporation minus
+      !!         precipitation ) given in kg/m2/s is divided
+      !!         by 1035 kg/m3 (density of ocean water) to obtain m/s.
+      !!
+      !! ** Action  : - Update the 1st level of tra with the trend associated
+      !!                with the tracer surface boundary condition 
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jn                      ! dummy loop indices
+      REAL(wp) ::   zse3t, zrtrn, zfact     ! local scalars
+      REAL(wp) ::   zftra, zdtra, ztfx, ztra   !   -      -
+      CHARACTER (len=22) :: charout
+      REAL(wp), DIMENSION(jpi,jpj)   ::   zsfx
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   ztrtrd
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sbc')
+      !
+      ! Allocate temporary workspace
+      IF( l_trdtrc )  ALLOCATE( ztrtrd(jpi,jpj,jpk) )
+      !
+      zrtrn = 1.e-15_wp
+
+      IF( kt == nittrc000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_sbc : Passive tracers surface boundary condition'
+         IF(lwp) WRITE(numout,*) '~~~~~~~ '
+         !
+         IF( ln_rsttr .AND. .NOT.ln_top_euler .AND.   &                     ! Restart: read in restart  file
+            iom_varid( numrtr, 'sbc_'//TRIM(ctrcnm(1))//'_b', ldstop = .FALSE. ) > 0 ) THEN
+            IF(lwp) WRITE(numout,*) '          nittrc000-nn_dttrc surface tracer content forcing fields red in the restart file'
+            zfact = 0.5_wp
+            DO jn = 1, jptra
+               CALL iom_get( numrtr, jpdom_autoglo, 'sbc_'//TRIM(ctrcnm(jn))//'_b', sbc_trc_b(:,:,jn) )   ! before tracer content sbc
+            END DO
+         ELSE                                         ! No restart or restart not found: Euler forward time stepping
+           zfact = 1._wp
+           sbc_trc_b(:,:,:) = 0._wp
+         ENDIF
+      ELSE                                         ! Swap of forcing fields
+         IF( ln_top_euler ) THEN
+            zfact = 1._wp
+            sbc_trc_b(:,:,:) = 0._wp
+         ELSE
+            zfact = 0.5_wp
+            sbc_trc_b(:,:,:) = sbc_trc(:,:,:)
+         ENDIF
+         !
+      ENDIF
+
+      ! Coupling online : river runoff is added to the horizontal divergence (hdivn) in the subroutine sbc_rnf_div 
+      ! one only consider the concentration/dilution effect due to evaporation minus precipitation + freezing/melting of sea-ice
+      ! Coupling offline : runoff are in emp which contains E-P-R
+      !
+      IF( .NOT.ln_linssh ) THEN  ! online coupling with vvl
+         zsfx(:,:) = 0._wp
+      ELSE                                      ! online coupling free surface or offline with free surface
+         zsfx(:,:) = emp(:,:)
+      ENDIF
+
+      ! 0. initialization
+      SELECT CASE ( nn_ice_tr )
+
+      CASE ( -1 ) ! No tracers in sea ice (null concentration in sea ice)
+         !
+         DO jn = 1, jptra
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  sbc_trc(ji,jj,jn) = zsfx(ji,jj) * r1_rau0 * trn(ji,jj,1,jn)
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 0 )  ! Same concentration in sea ice and in the ocean
+         !
+         DO jn = 1, jptra
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  sbc_trc(ji,jj,jn) = ( zsfx(ji,jj) + fmmflx(ji,jj) ) * r1_rau0 * trn(ji,jj,1,jn)
+               END DO
+            END DO
+         END DO
+         !
+      CASE ( 1 )  ! Specific treatment of sea ice fluxes with an imposed concentration in sea ice 
+         !
+         DO jn = 1, jptra
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zse3t = 1. / e3t_n(ji,jj,1)
+                  ! tracer flux at the ice/ocean interface (tracer/m2/s)
+                  zftra = - trc_i(ji,jj,jn) * fmmflx(ji,jj) ! uptake of tracer in the sea ice
+                  !                                         ! only used in the levitating sea ice case
+                  ! tracer flux only       : add concentration dilution term in net tracer flux, no F-M in volume flux
+                  ! tracer and mass fluxes : no concentration dilution term in net tracer flux, F-M term in volume flux
+                  ztfx  = zftra                        ! net tracer flux
+                  !
+                  zdtra = r1_rau0 * ( ztfx + ( zsfx(ji,jj) + fmmflx(ji,jj) ) * trn(ji,jj,1,jn) ) 
+                  IF ( zdtra < 0. ) THEN
+                     zdtra  = MAX(zdtra, -trn(ji,jj,1,jn) * e3t_n(ji,jj,1) / r2dttrc )   ! avoid negative concentrations to arise
+                  ENDIF
+                  sbc_trc(ji,jj,jn) =  zdtra 
+               END DO
+            END DO
+         END DO
+      END SELECT
+      !
+      CALL lbc_lnk( 'trcsbc', sbc_trc(:,:,:), 'T', 1. )
+      !                                       Concentration dilution effect on tracers due to evaporation & precipitation 
+      DO jn = 1, jptra
+         !
+         IF( l_trdtrc )   ztrtrd(:,:,:) = tra(:,:,:,jn)  ! save trends
+         !
+         DO jj = 2, jpj
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zse3t = zfact / e3t_n(ji,jj,1)
+               tra(ji,jj,1,jn) = tra(ji,jj,1,jn) + ( sbc_trc_b(ji,jj,jn) + sbc_trc(ji,jj,jn) ) * zse3t
+            END DO
+         END DO
+         !
+         IF( l_trdtrc ) THEN
+            ztrtrd(:,:,:) = tra(:,:,:,jn) - ztrtrd(:,:,:)
+            CALL trd_tra( kt, 'TRC', jn, jptra_nsr, ztrtrd )
+         END IF
+         !                                                       ! ===========
+      END DO                                                     ! tracer loop
+      !                                                          ! ===========
+      !
+      !                                           Write in the tracer restar  file
+      !                                          *******************************
+      IF( lrst_trc .AND. .NOT.ln_top_euler ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'sbc : ocean surface tracer content forcing fields written in tracer restart file ',   &
+            &                    'at it= ', kt,' date= ', ndastp
+         IF(lwp) WRITE(numout,*) '~~~~'
+         DO jn = 1, jptra
+            CALL iom_rstput( kt, nitrst, numrtw, 'sbc_'//TRIM(ctrcnm(jn))//'_b', sbc_trc(:,:,jn) )
+         END DO
+      ENDIF
+      !
+      IF( ln_ctl )   THEN
+         WRITE(charout, FMT="('sbc ')") ;  CALL prt_ctl_trc_info(charout)
+                                           CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      ENDIF
+      IF( l_trdtrc )  DEALLOCATE( ztrtrd )
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sbc')
+      !
+   END SUBROUTINE trc_sbc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module :                      NO passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_sbc (kt)              ! Empty routine
+      INTEGER, INTENT(in) :: kt
+      WRITE(*,*) 'trc_sbc: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sbc
+#endif
+   
+   !!======================================================================
+END MODULE trcsbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsink.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsink.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trcsink.F90	(revision 14097)
@@ -0,0 +1,238 @@
+MODULE trcsink
+   !!======================================================================
+   !!                         ***  MODULE trcsink  ***
+   !! TOP :  vertical flux of particulate matter due to gravitational sinking
+   !!======================================================================
+   !! History :   1.0  !  2004     (O. Aumont) Original code
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  F90
+   !!             3.4  !  2011-06  (O. Aumont, C. Ethe) Change aggregation formula
+   !!             3.5  !  2012-07  (O. Aumont) Introduce potential time-splitting
+   !!             4.0  !  2018-12  (O. Aumont) Generalize the PISCES code to make it usable by any model
+   !!----------------------------------------------------------------------
+   !!   trc_sink       :  Compute vertical flux of particulate matter due to gravitational sinking
+   !!----------------------------------------------------------------------
+   USE oce_trc         !  shared variables between ocean and passive tracers
+   USE trc             !  passive tracers common variables 
+   USE lib_mpp
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_sink
+   PUBLIC trc_sink_ini
+
+   INTEGER, PUBLIC :: nitermax      !: Maximum number of iterations for sinking
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   !!----------------------------------------------------------------------
+   !!   'standard sinking parameterisation'                  ???
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE trc_sink ( kt, pwsink, psinkflx, jp_tra, rsfact )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sink  ***
+      !!
+      !! ** Purpose :   Compute vertical flux of particulate matter due to 
+      !!                gravitational sinking
+      !!
+      !! ** Method  : - ???
+      !!---------------------------------------------------------------------
+      INTEGER , INTENT(in)  :: kt
+      INTEGER , INTENT(in)  :: jp_tra    ! tracer index index      
+      REAL(wp), INTENT(in)  :: rsfact    ! time step duration
+      REAL(wp), INTENT(in)   , DIMENSION(jpi,jpj,jpk) :: pwsink
+      REAL(wp), INTENT(inout), DIMENSION(jpi,jpj,jpk) :: psinkflx
+      INTEGER  ::   ji, jj, jk
+      INTEGER, DIMENSION(jpi, jpj) ::   iiter
+      REAL(wp) ::   zfact, zwsmax, zmax
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zwsink
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sink')
+      !
+      !
+      ! OA This is (I hope) a temporary solution for the problem that may 
+      ! OA arise in specific situation where the CFL criterion is broken 
+      ! OA for vertical sedimentation of particles. To avoid this, a time
+      ! OA splitting algorithm has been coded. A specific maximum
+      ! OA iteration number is provided and may be specified in the namelist 
+      ! OA This is to avoid very large iteration number when explicit free
+      ! OA surface is used (for instance). When niter?max is set to 1, 
+      ! OA this computation is skipped. The crude old threshold method is 
+      ! OA then applied. This also happens when niter exceeds nitermax.
+      IF( nitermax == 1 ) THEN
+         iiter(:,:) = 1
+      ELSE
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               iiter(ji,jj) = 1
+               DO jk = 1, jpkm1
+                  IF( tmask(ji,jj,jk) == 1.0 ) THEN
+                      zwsmax =  0.5 * e3t_n(ji,jj,jk) * rday / rsfact
+                      iiter(ji,jj) =  MAX( iiter(ji,jj), INT( pwsink(ji,jj,jk) / zwsmax ) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         iiter(:,:) = MIN( iiter(:,:), nitermax )
+      ENDIF
+
+      DO jk = 1,jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( tmask(ji,jj,jk) == 1.0 ) THEN
+                 zwsmax = 0.5 * e3t_n(ji,jj,jk) * rday / rsfact
+                 zwsink(ji,jj,jk) = MIN( pwsink(ji,jj,jk), zwsmax * REAL( iiter(ji,jj), wp ) )
+               ELSE
+                 ! provide a default value so there is no use of undefinite value in trc_sink2 for zwsink2 initialization
+                 zwsink(ji,jj,jk) = 0.
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      !  Initializa to zero all the sinking arrays 
+      !  -----------------------------------------
+      psinkflx(:,:,:) = 0.e0
+
+      !   Compute the sedimentation term using trc_sink2 for the considered sinking particle
+      !   -----------------------------------------------------
+      CALL trc_sink2( zwsink, psinkflx, jp_tra, iiter, rsfact )
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sink')
+      !
+   END SUBROUTINE trc_sink
+
+   SUBROUTINE trc_sink2( pwsink, psinkflx, jp_tra, kiter, rsfact )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sink2  ***
+      !!
+      !! ** Purpose :   Compute the sedimentation terms for the various sinking
+      !!     particles. The scheme used to compute the trends is based
+      !!     on MUSCL.
+      !!
+      !! ** Method  : - this ROUTINE compute not exactly the advection but the
+      !!      transport term, i.e.  div(u*tra).
+      !!---------------------------------------------------------------------
+      INTEGER,  INTENT(in   )                         ::   jp_tra    ! tracer index index      
+      REAL(wp), INTENT(in   )                         ::   rsfact    ! duration of time step
+      INTEGER,  INTENT(in   ), DIMENSION(jpi,jpj)     ::   kiter     ! number of iterations for time-splitting 
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj,jpk) ::   pwsink    ! sinking speed
+      REAL(wp), INTENT(inout), DIMENSION(jpi,jpj,jpk) ::   psinkflx  ! sinking fluxe
+      !
+      INTEGER  ::   ji, jj, jk, jn
+      REAL(wp) ::   zigma,zew,zign, zflx, zstep
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: ztraz, zakz, zwsink2, ztrb 
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sink2')
+      !
+      ztraz(:,:,:) = 0.e0
+      zakz (:,:,:) = 0.e0
+      ztrb (:,:,:) = trb(:,:,:,jp_tra)
+
+      DO jk = 1, jpkm1
+         zwsink2(:,:,jk+1) = -pwsink(:,:,jk) / rday * tmask(:,:,jk+1) 
+      END DO
+      zwsink2(:,:,1) = 0.e0
+
+
+      ! Vertical advective flux
+      DO jn = 1, 2
+         !  first guess of the slopes interior values
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               !
+               zstep = rsfact / REAL( kiter(ji,jj), wp ) / 2.
+               !              
+               DO jk = 2, jpkm1
+                  ztraz(ji,jj,jk) = ( trb(ji,jj,jk-1,jp_tra) - trb(ji,jj,jk,jp_tra) ) * tmask(ji,jj,jk)
+               END DO
+               ztraz(ji,jj,1  ) = 0.0
+               ztraz(ji,jj,jpk) = 0.0
+
+               ! slopes
+               DO jk = 2, jpkm1
+                  zign = 0.25 + SIGN( 0.25, ztraz(ji,jj,jk) * ztraz(ji,jj,jk+1) )
+                  zakz(ji,jj,jk) = ( ztraz(ji,jj,jk) + ztraz(ji,jj,jk+1) ) * zign
+               END DO
+         
+               ! Slopes limitation
+               DO jk = 2, jpkm1
+                  zakz(ji,jj,jk) = SIGN( 1., zakz(ji,jj,jk) ) *        &
+                     &             MIN( ABS( zakz(ji,jj,jk) ), 2. * ABS(ztraz(ji,jj,jk+1)), 2. * ABS(ztraz(ji,jj,jk) ) )
+               END DO
+         
+               ! vertical advective flux
+               DO jk = 1, jpkm1
+                  zigma = zwsink2(ji,jj,jk+1) * zstep / e3w_n(ji,jj,jk+1)
+                  zew   = zwsink2(ji,jj,jk+1)
+                  psinkflx(ji,jj,jk+1) = -zew * ( trb(ji,jj,jk,jp_tra) - 0.5 * ( 1 + zigma ) * zakz(ji,jj,jk) ) * zstep
+               END DO
+               !
+               ! Boundary conditions
+               psinkflx(ji,jj,1  ) = 0.e0
+               psinkflx(ji,jj,jpk) = 0.e0
+         
+               DO jk=1,jpkm1
+                  zflx = ( psinkflx(ji,jj,jk) - psinkflx(ji,jj,jk+1) ) / e3t_n(ji,jj,jk)
+                  trb(ji,jj,jk,jp_tra) = trb(ji,jj,jk,jp_tra) + zflx
+               END DO
+            END DO
+         END DO
+      END DO
+
+      DO jk = 1,jpkm1
+         DO jj = 1,jpj
+            DO ji = 1, jpi
+               zflx = ( psinkflx(ji,jj,jk) - psinkflx(ji,jj,jk+1) ) / e3t_n(ji,jj,jk)
+               ztrb(ji,jj,jk) = ztrb(ji,jj,jk) + 2. * zflx
+            END DO
+         END DO
+      END DO
+
+      trb(:,:,:,jp_tra) = ztrb(:,:,:)
+      psinkflx(:,:,:)   = 2. * psinkflx(:,:,:)
+      !
+      IF( ln_timing )  CALL timing_stop('trc_sink2')
+      !
+   END SUBROUTINE trc_sink2
+
+  SUBROUTINE trc_sink_ini
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_sink_ini ***
+      !!
+      !! ** Purpose :   read  namelist options 
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! Local integer output status for namelist read
+      !!
+      NAMELIST/namtrc_snk/ nitermax
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnat_ref )              ! namtrc_rad in reference namelist 
+      READ  ( numnat_ref, namtrc_snk, IOSTAT = ios, ERR = 907)
+907   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_snk in reference namelist' )
+      REWIND( numnat_cfg )              ! namtrc_rad in configuration namelist 
+      READ  ( numnat_cfg, namtrc_snk, IOSTAT = ios, ERR = 908 )
+908   IF( ios > 0 )   CALL ctl_nam ( ios , 'namtrc_snk in configuration namelist' )
+      IF(lwm) WRITE( numont, namtrc_snk )
+
+      IF(lwp) THEN                     !   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_sink : Sedimentation of particles '
+         WRITE(numout,*) '~~~~~~~ '
+         WRITE(numout,*) '   Namelist namtrc_snk : sedimentation of particles'
+         WRITE(numout,*) '   Maximum number of iterations   nitermax = ', nitermax
+         WRITE(numout,*)
+      ENDIF
+
+   END SUBROUTINE trc_sink_ini
+
+   !!======================================================================
+END MODULE trcsink
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trctrp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trctrp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trctrp.F90	(revision 14097)
@@ -0,0 +1,111 @@
+MODULE trctrp
+   !!======================================================================
+   !!                       ***  MODULE trctrp  ***
+   !! Ocean Physics    : manage the passive tracer transport
+   !!======================================================================
+   !! History :   1.0  !  2004-03 (C. Ethe) Original code
+   !!             3.3  !  2010-07 (C. Ethe) Merge TRA-TRC
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_trp        : passive tracer transport
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! ocean dynamics and active tracers variables
+   USE trc             ! ocean passive tracers variables 
+   USE trcbbl          ! bottom boundary layer               (trc_bbl routine)
+   USE trcdmp          ! internal damping                    (trc_dmp routine)
+   USE trcldf          ! lateral mixing                      (trc_ldf routine)
+   USE trcadv          ! advection                           (trc_adv routine)
+   USE trczdf          ! vertical diffusion                  (trc_zdf routine)
+   USE trcnxt          ! time-stepping                       (trc_nxt routine)
+   USE trcrad          ! positivity                          (trc_rad routine)
+   USE trcsbc          ! surface boundary condition          (trc_sbc routine)
+   USE zpshde          ! partial step: hor. derivative       (zps_hde routine)
+   USE trcbc           ! Tracers boundary condtions          ( trc_bc routine)
+   USE bdy_oce   , ONLY: ln_bdy
+   USE trcbdy          ! BDY open boundaries
+
+#if defined key_agrif
+   USE agrif_top_sponge ! tracers sponges
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_trp    ! called by trc_stp
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trc_trp( kt )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_trp  ***
+      !!                      
+      !! ** Purpose :   Management of passive tracers transport
+      !! 
+      !! ** Method  : - Compute the passive tracers trends 
+      !!              - Update the passive tracers
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::  kt  ! ocean time-step index
+      !! ---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_trp')
+      !
+      IF( .NOT. lk_c1d ) THEN
+         !
+                                CALL trc_sbc    ( kt )      ! surface boundary condition
+         IF( ln_trabbl )        CALL trc_bbl    ( kt )      ! advective (and/or diffusive) bottom boundary layer scheme
+         IF( ln_trcdmp )        CALL trc_dmp    ( kt )      ! internal damping trends
+                                CALL trc_bc     ( kt )      ! BC for BDY
+         IF( ln_bdy )           CALL trc_bdy_dmp( kt )      ! BDY damping trends
+                                CALL trc_adv    ( kt )      ! horizontal & vertical advection 
+         !                                                         ! Partial top/bottom cell: GRADh( trb )  
+         IF( ln_zps ) THEN
+           IF( ln_isfcav ) THEN ; CALL zps_hde_isf( kt, jptra, trb, pgtu=gtru, pgtv=gtrv, pgtui=gtrui, pgtvi=gtrvi )  ! both top & bottom
+           ELSE                 ; CALL zps_hde    ( kt, jptra, trb, gtru, gtrv )                                      !  only bottom
+           ENDIF
+         ENDIF
+         !                                                      
+                                CALL trc_ldf    ( kt )      ! lateral mixing
+#if defined key_agrif
+         IF(.NOT. Agrif_Root()) CALL Agrif_Sponge_trc       ! tracers sponge
+#endif
+                                CALL trc_zdf    ( kt )      ! vertical mixing and after tracer fields
+                                CALL trc_nxt    ( kt )      ! tracer fields at next time step     
+         IF( ln_trcrad )        CALL trc_rad    ( kt )      ! Correct artificial negative concentrations
+         IF( ln_trcdmp_clo )    CALL trc_dmp_clo( kt )      ! internal damping trends on closed seas only
+
+         !
+      ELSE                                               ! 1D vertical configuration
+                                CALL trc_sbc( kt )            ! surface boundary condition
+         IF( ln_trcdmp )        CALL trc_dmp( kt )            ! internal damping trends
+                                CALL trc_zdf( kt )            ! vertical mixing and after tracer fields
+                                CALL trc_nxt( kt )            ! tracer fields at next time step     
+          IF( ln_trcrad )       CALL trc_rad( kt )            ! Correct artificial negative concentrations
+         !
+      END IF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_trp')
+      !
+   END SUBROUTINE trc_trp
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module :                                        No TOP models
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_trp( kt )              ! Empty routine
+      INTEGER, INTENT(in) ::   kt
+      WRITE(*,*) 'trc_trp: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_trp
+#endif
+   
+   !!======================================================================
+END MODULE trctrp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trczdf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trczdf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trczdf.F90	(revision 14097)
@@ -0,0 +1,88 @@
+MODULE trczdf
+   !!==============================================================================
+   !!                 ***  MODULE  trczdf  ***
+   !! Ocean Passive tracers : vertical diffusive trends 
+   !!=====================================================================
+   !! History :  9.0  ! 2005-11  (G. Madec)  Original code
+   !!       NEMO 3.0  ! 2008-01  (C. Ethe, G. Madec)  merge TRC-TRA 
+   !!            4.0  ! 2017-04  (G. Madec)  remove the explicit case
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_zdf      : update the tracer trend with the vertical diffusion
+   !!----------------------------------------------------------------------
+   USE trc           ! ocean passive tracers variables
+   USE oce_trc       ! ocean dynamics and active tracers
+   USE trd_oce       ! trends: ocean variables
+   USE trazdf        ! tracer: vertical diffusion
+!!gm do we really need this ?
+   USE trcldf        ! passive tracers: lateral diffusion
+!!gm
+   USE trdtra        ! trends manager: tracers 
+   USE prtctl_trc    ! Print control
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_zdf         ! called by step.F90 
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_zdf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trc_zdf  ***
+      !!
+      !! ** Purpose :   compute the vertical ocean tracer physics using
+      !!              an implicit time-stepping scheme.
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::  kt      ! ocean time-step index
+      !
+      INTEGER               ::  jk, jn
+      CHARACTER (len=22)    :: charout
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jptra) ::   ztrtrd   ! 4D workspace
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_zdf')
+      !
+      IF( l_trdtrc )   ztrtrd(:,:,:,:)  = tra(:,:,:,:)
+      !
+      CALL tra_zdf_imp( kt, nittrc000, 'TRC', r2dttrc, trb, tra, jptra )    !   implicit scheme          
+      !
+      IF( l_trdtrc )   THEN                      ! save the vertical diffusive trends for further diagnostics
+         DO jn = 1, jptra
+            DO jk = 1, jpkm1
+               ztrtrd(:,:,jk,jn) = ( ( tra(:,:,jk,jn) - trb(:,:,jk,jn) ) / r2dttrc ) - ztrtrd(:,:,jk,jn)
+            END DO
+            CALL trd_tra( kt, 'TRC', jn, jptra_zdf, ztrtrd(:,:,:,jn) )
+         END DO
+      ENDIF
+      !                                          ! print mean trends (used for debugging)
+      IF( ln_ctl )   THEN
+         WRITE(charout, FMT="('zdf ')")
+         CALL prt_ctl_trc_info(charout)
+         CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
+      END IF
+      !
+      IF( ln_timing )  CALL timing_stop('trc_zdf')
+      !
+   END SUBROUTINE trc_zdf
+   
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                         Empty module
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_zdf( kt )
+      INTEGER, INTENT(in) :: kt  
+      WRITE(*,*) 'trc_zdf: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_zdf
+#endif
+   !!==============================================================================
+END MODULE trczdf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc.F90	(revision 14097)
@@ -0,0 +1,991 @@
+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
+   !!----------------------------------------------------------------------
+   !!   '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 : avs  ! vert. diffusivity coef. at w-point for temp  
+   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
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trd_mxl_trc
+   PUBLIC trd_mxl_trc_alloc
+   PUBLIC trd_mxl_trc_init
+   PUBLIC trd_mxl_trc_zint
+
+   CHARACTER (LEN=40) ::  clhstnam                                ! name of the trends NetCDF file
+   INTEGER ::   nmoymltrd
+   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:) ::   ndextrd1, nidtrd, nh_t
+   INTEGER ::   ndimtrd1                        
+   INTEGER, SAVE ::  ionce, icount
+   LOGICAL :: llwarn  = .TRUE.                                    ! this should always be .TRUE.
+   LOGICAL :: lldebug = .TRUE.
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  ztmltrd2   !
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_mxl_trc_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_trc_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ztmltrd2(jpi,jpj,jpltrd_trc,jptra) ,      &
+         &      ndextrd1(jpi*jpj), nidtrd(jptra), nh_t(jptra),  STAT=trd_mxl_trc_alloc)
+         !
+      CALL mpp_sum ( 'trdmxl_trc', trd_mxl_trc_alloc )
+      IF( trd_mxl_trc_alloc /=0 )   CALL ctl_stop( 'STOP', '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), DIMENSION(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  )   ;   CALL ctl_stop( '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  ??? 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) = e3t_n(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
+      !
+   END SUBROUTINE trd_mxl_trc_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 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_ICE, 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), DIMENSION(jpi,jpj,jptra) ::   ztmltot             ! d(trc)/dt over the anlysis window (incl. Asselin)
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlres             ! residual = dh/dt entrainment term
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlatf             ! for storage only
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlrad             ! for storage only (for trb<0 corr in trcrad)
+      !
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmltot2            ! -+
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlres2            !  | working arrays to diagnose the trends
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmltrdm2           !  | associated with the time meaned ML
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlatf2            !  | passive tracers
+      REAL(wp), DIMENSION(jpi,jpj,jptra) ::   ztmlrad2            !  | (-> for trb<0 corr in trcrad)
+      !
+      CHARACTER (LEN=10) ::   clvar
+      !!----------------------------------------------------------------------
+
+
+      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 jn = 1, jptra
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ik = nmld_trc(ji,jj)
+                  IF( ln_trdtrc(jn) )    &
+                  tmltrd_trc(ji,jj,jpmxl_trc_zdf,jn) = - avs(ji,jj,ik) / e3w_n(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
+
+!!gm Test removed, nothing specific to a configuration should survive out of usrdef modules
+!!gm      IF ( cn_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration
+!!gm      ! GYRE : for diagnostic fields, are needed if cyclic B.C. are present, but not for purely MPI comm. 
+!!gm      ! 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( 'trdmxl_trc', tmltrd_trc(:,:,jl,jn), 'T', 1. )        ! lateral boundary conditions
+               END DO
+            ENDIF
+         END DO
+!!gm      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 ( cn_cfg .NE. 'gyre' ) THEN
+                  CALL lbc_lnk_multi( 'trdmxl_trc', ztmltot(:,:,jn) , 'T', 1. , ztmlres(:,:,jn) , 'T', 1., &
+                     &                ztmlatf(:,:,jn) , 'T', 1. , ztmlrad(:,:,jn) , 'T', 1. )
+               ENDIF
+
+
+#if defined key_diainstant
+               CALL ctl_stop( '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 ( cn_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration    
+                  CALL lbc_lnk_multi( 'trdmxl_trc', ztmltot2(:,:,jn), 'T', 1., ztmlres2(:,:,jn), 'T', 1. )
+                  DO jl = 1, jpltrd_trc
+                     CALL lbc_lnk( 'trdmxl_trc', 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 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
+
+      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)
+      !
+   END SUBROUTINE trd_mxl_trc
+
+   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(ctmp1,*) '                Your nitend parameter, nitend = ', nitend
+         WRITE(ctmp2,*) '                is no multiple of the trends diagnostics frequency        '
+         WRITE(ctmp3,*) '                          you defined, nn_trd_trc   = ', nn_trd_trc
+         WRITE(ctmp4,*) '                This will not allow you to restart from this simulation.  '
+         WRITE(ctmp5,*) '                You should reconsider this choice.                        ' 
+         WRITE(ctmp6,*) 
+         WRITE(ctmp7,*) '                N.B. the nitend parameter is also constrained to be a     '
+         WRITE(ctmp8,*) '                multiple of the sea-ice frequency parameter (typically 5) '
+         CALL ctl_stop( ctmp1, ctmp2, ctmp3, ctmp4, ctmp5, ctmp6, ctmp7, ctmp8 )
+      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(ctmp1,*) '                Currently, you can NOT use simultaneously tracer MUSCL    '
+         WRITE(ctmp2,*) '                advection and window averaged diagnostics of ML trends.   '
+         WRITE(ctmp3,*) '                WHY? Everything in trdmxl_trc is coded for leap-frog, and '
+         WRITE(ctmp4,*) '                MUSCL scheme is Euler forward for passive tracers (note   '
+         WRITE(ctmp5,*) '                that MUSCL is leap-frog for active tracers T/S).          '
+         WRITE(ctmp6,*) '                In particuliar, entrainment trend would be FALSE. However '
+         WRITE(ctmp7,*) '                this residual is correct for instantaneous ML diagnostics.'
+         CALL ctl_stop( ctmp1, ctmp2, ctmp3, ctmp4, ctmp5, ctmp6, ctmp7 )
+      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( 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 
+
+       ENDIF
+
+      icount = 1   ;   ionce  = 1  ! open specifier   
+
+
+      ! 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
+      ! ======================================================================
+
+      ! 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
+         CALL ctl_stop( '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
+
+      !-- 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
+         CALL ctl_stop( '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
+
+      !-- Leave IOIPSL/NetCDF define mode
+      DO jn = 1, jptra
+         IF( ln_trdtrc(jn) )  CALL histend( nidtrd(jn), snc4set )
+      END DO
+
+      IF(lwp) WRITE(numout,*)
+
+   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_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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc_rst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc_rst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdmxl_trc_rst.F90	(revision 14097)
@@ -0,0 +1,210 @@
+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 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!---------------------------------------------------------------------------------
+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   ! output restart file name
+      CHARACTER(LEN=256)  ::   clpath   ! full path to restart file
+      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)
+         clpath = TRIM(cn_trcrst_outdir)
+         IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+         IF(lwp) WRITE(numout,*) '             open ocean restart_mld_trc NetCDF  'TRIM(clpath)//TRIM(clname)
+         CALL iom_open( TRIM(clpath)//TRIM(clname), nummldw_trc, ldwrt = .TRUE. )
+      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
+            !                                                          ! ===========
+         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
+      LOGICAL ::  llok
+      CHARACTER(LEN=256)  ::   clpath   ! full path to restart file
+      !!-----------------------------------------------------------------------------
+      
+      IF(lwp)  THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_trc_rst_read : read the NetCDF MLD restart file'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~'
+      ENDIF
+      
+      clpath = TRIM(cn_trcrst_indir)
+      IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+      CALL iom_open( TRIM(clpath)//TRIM(cn_trdrst_trc_in), inum ) 
+      
+      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
+         !                                                          ! ===========
+
+         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 )
+    IMPLICIT NONE
+    INTEGER, INTENT( in ) :: 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
+    IMPLICIT NONE
+    INTEGER, INTENT( in ) :: kt
+    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
+    IMPLICIT NONE
+  END SUBROUTINE trd_mxl_trc_rst_read
+#endif
+
+  !!=================================================================================
+END MODULE trdmxl_trc_rst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc.F90	(revision 14097)
@@ -0,0 +1,125 @@
+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 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
+
+   PUBLIC trd_trc
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trd_trc( 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)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_yad  )  ;  WRITE (cltra,'("YAD_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_zad  )  ;  WRITE (cltra,'("ZAD_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_ldf  )  ;  WRITE (cltra,'("LDF_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_bbl  )  ;  WRITE (cltra,'("BBL_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_nsr  )  ;  WRITE (cltra,'("FOR_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_zdf  )  ;  WRITE (cltra,'("ZDF_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_zdfp )  ;  WRITE (cltra,'("ZDP_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_dmp  )  ;  WRITE (cltra,'("DMP_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_sms  )  ;  WRITE (cltra,'("SMS_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_tot  )  ;  WRITE (cltra,'("TOT_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_atf  )  ;  WRITE (cltra,'("ATF_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_radb )  ;  WRITE (cltra,'("RDB_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         CASE( jptra_radn )  ;  WRITE (cltra,'("RDN_",4a)')  ; cltra = TRIM(cltra)//TRIM(ctrcnm(kjn)) ; CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         END SELECT
+         !
+      END IF
+
+   END SUBROUTINE trd_trc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                       Empty module
+   !!----------------------------------------------------------------------
+
+   PUBLIC trd_trc
+
+CONTAINS
+
+   SUBROUTINE trd_trc( 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 : 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
+
+#endif
+   !!======================================================================
+END MODULE trdtrc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc_oce.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc_oce.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/TRP/trdtrc_oce.F90	(revision 14097)
@@ -0,0 +1,163 @@
+MODULE trdtrc_oce
+   !!======================================================================
+   !!                   ***  MODULE trdtrc_oce  ***
+   !! Ocean trends :   set tracer and momentum trend variables
+   !!======================================================================
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   '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(:), ALLOCATABLE ::   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
+   !!----------------------------------------------------------------------
+   !!   '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
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_trc_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!         *** ROUTINE trd_trc_oce_alloc ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop
+      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
+      !
+      trd_trc_oce_alloc = MAXVAL(ierr)
+      !
+      IF( trd_trc_oce_alloc /= 0 )   CALL ctl_stop( 'STOP', '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: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/oce_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/oce_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/oce_trc.F90	(revision 14097)
@@ -0,0 +1,101 @@
+MODULE oce_trc
+   !!======================================================================
+   !!                      ***  MODULE  oce_trc  ***
+   !! TOP :   variables shared between ocean and passive tracers
+   !!======================================================================
+   !! History :   1.0  !  2004-03  (C. Ethe)  original code
+   !!             2.0  !  2007-12 (C. Ethe, G. Madec)  rewritting
+   !!----------------------------------------------------------------------
+   !                                            !* Domain size *
+   USE par_oce , ONLY :   jpi      =>   jpi        !: first  dimension of grid --> i 
+   USE par_oce , ONLY :   jpj      =>   jpj        !: second dimension of grid --> j  
+   USE par_oce , ONLY :   jpk      =>   jpk        !: number of levels  
+   USE par_oce , ONLY :   jpim1    =>   jpim1      !: jpi - 1
+   USE par_oce , ONLY :   jpjm1    =>   jpjm1      !: jpj - 1 
+   USE par_oce , ONLY :   jpkm1    =>   jpkm1      !: jpk - 1  
+   USE par_oce , ONLY :   jpij     =>   jpij       !: jpi x jpj
+   USE par_oce , ONLY :   jp_tem   =>   jp_tem     !: indice for temperature
+   USE par_oce , ONLY :   jp_sal   =>   jp_sal     !: indice for salinity
+
+   USE in_out_manager                           !* IO manager *
+   USE timing                                   !* Timing * 
+   USE lib_mpp                                  !* MPP library                         
+   USE lib_fortran                              !* Fortran utilities                         
+   USE lbclnk                                   !* Lateral boundary conditions                         
+   USE phycst                                   !* physical constants *
+   USE c1d                                      !* 1D configuration
+
+   USE dom_oce                                  !* model domain *
+
+   USE domvvl, ONLY : un_td, vn_td          !: thickness diffusion transport
+   USE domvvl, ONLY : ln_vvl_ztilde         !: ztilde vertical coordinate
+   USE domvvl, ONLY : ln_vvl_layer          !: level  vertical coordinate
+
+   !* ocean fields: here now and after fields *
+   USE oce , ONLY :   un      =>    un      !: i-horizontal velocity (m s-1) 
+   USE oce , ONLY :   vn      =>    vn      !: j-horizontal velocity (m s-1)
+   USE oce , ONLY :   wn      =>    wn      !: vertical velocity (m s-1)  
+   USE oce , ONLY :   tsn     =>    tsn     !: 4D array contaning ( tn, sn )
+   USE oce , ONLY :   tsb     =>    tsb     !: 4D array contaning ( tb, sb )
+   USE oce , ONLY :   tsa     =>    tsa     !: 4D array contaning ( ta, sa )
+   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)
+   USE oce , ONLY :   hdivn   =>    hdivn   !: horizontal divergence (1/s)
+   USE oce , ONLY :   sshn    =>    sshn    !: sea surface height at t-point [m]   
+   USE oce , ONLY :   sshb    =>    sshb    !: sea surface height at t-point [m]   
+   USE oce , ONLY :   ssha    =>    ssha    !: sea surface height at t-point [m]   
+   USE oce , ONLY :   rab_n   =>    rab_n   !: local thermal/haline expension ratio at T-points
+
+   !* surface fluxes *
+   USE sbc_oce , ONLY :   utau       =>    utau       !: i-surface stress component
+   USE sbc_oce , ONLY :   vtau       =>    vtau       !: j-surface stress component
+   USE sbc_oce , ONLY :   wndm       =>    wndm       !: 10m wind speed 
+   USE sbc_oce , ONLY :   qsr        =>    qsr        !: penetrative solar radiation (w m-2)
+   USE sbc_oce , ONLY :   emp        =>    emp        !: freshwater budget: volume flux               [Kg/m2/s]
+   USE sbc_oce , ONLY :   emp_b      =>    emp_b      !: freshwater budget: volume flux               [Kg/m2/s]
+   USE sbc_oce , ONLY :   fmmflx     =>    fmmflx     !: freshwater budget: volume flux               [Kg/m2/s]
+   USE sbc_oce , ONLY :   rnf        =>    rnf        !: river runoff   [Kg/m2/s]
+   USE sbc_oce , ONLY :   rnf_b      =>    rnf_b      !: river runoff at previus step   [Kg/m2/s]
+   USE sbc_oce , ONLY :   ln_dm2dc   =>    ln_dm2dc   !: Diurnal Cycle 
+   USE sbc_oce , ONLY :   ln_cpl     =>    ln_cpl     !: ocean-atmosphere coupled formulation
+   USE sbc_oce , ONLY :   ncpl_qsr_freq   =>   ncpl_qsr_freq   !: qsr coupling frequency per days from atmospher
+   USE sbc_oce , ONLY :   ln_rnf     =>    ln_rnf     !: runoffs / runoff mouths
+   USE sbc_oce , ONLY :   fr_i       =>    fr_i       !: ice fraction (between 0 to 1)
+   USE sbc_oce , ONLY :   atm_co2    =>    atm_co2    !  atmospheric pCO2
+   USE traqsr  , ONLY :   rn_abs     =>    rn_abs     !: fraction absorbed in the very near surface
+   USE traqsr  , ONLY :   rn_si0     =>    rn_si0     !: very near surface depth of extinction
+   USE traqsr  , ONLY :   nksr       =>    nksr       !: levels below which the light cannot penetrate (depth larger than 391 m)
+   USE traqsr  , ONLY :   rkrgb      =>    rkrgb      !: tabulated attenuation coefficients for RGB absorption
+   USE traqsr  , ONLY :   ln_qsr_bio =>    ln_qsr_bio !: flag to use or not the biological fluxes for light
+   USE sbcrnf  , ONLY :   rnfmsk     =>    rnfmsk     !: mixed adv scheme in runoffs vicinity (hori.) 
+   USE sbcrnf  , ONLY :   rnfmsk_z   =>    rnfmsk_z   !: mixed adv scheme in runoffs vicinity (vert.)
+   USE sbcrnf  , ONLY :   h_rnf      =>    h_rnf      !: river runoff   [Kg/m2/s]
+   USE sbcrnf  , ONLY :   nk_rnf     =>    nk_rnf     !: depth of runoff in model level
+   USE sbcrnf  , ONLY :   rn_rfact   =>    rn_rfact   !: multiplicative factor for runoff
+
+   USE trc_oce
+     
+!!gm  this can be removed if :
+!!gm    in trcadv.F90 and trcsub.F90  we add a USE ldfslp
+   !* direction of lateral diffusion *
+   USE ldfslp , ONLY :   l_ldfslp  =>  l_ldfslp       !: slopes flag
+   USE ldfslp , ONLY :   uslp       =>   uslp         !: i-slope at u-point
+   USE ldfslp , ONLY :   vslp       =>   vslp         !: j-slope at v-point
+   USE ldfslp , ONLY :   wslpi      =>   wslpi        !: i-slope at w-point
+   USE ldfslp , ONLY :   wslpj      =>   wslpj        !: j-slope at w-point
+   USE ldfslp , ONLY :   ln_traldf_triad => ln_traldf_triad   !: use of triad scheme
+   USE ldfslp , ONLY :   ln_traldf_iso => ln_traldf_iso   !: use of isopycnal scheme
+!!gm end
+
+   !* vertical diffusion *
+   USE zdf_oce , ONLY :   avs        =>   avs         !: vert. diffusivity coef. for salinity    (w-point)
+   USE zdf_oce , ONLY :   avt        =>   avt         !: vert. diffusivity coef. for temperature (w-point)
+
+   !* mixing & mixed layer depth *
+   USE zdfmxl , ONLY :   nmln        =>   nmln        !: number of level in the mixed layer
+   USE zdfmxl , ONLY :   hmld        =>   hmld        !: mixing layer depth (turbocline)
+   USE zdfmxl , ONLY :   hmlp        =>   hmlp        !: mixed layer depth  (rho=rho0+zdcrit) (m)
+   USE zdfmxl , ONLY :   hmlpt       =>   hmlpt       !: mixed layer depth at t-points (m)
+   USE zdfmxl , ONLY :   avt_c       =>   avt_c       !: Kz criterion for the turbocline depth
+
+END MODULE oce_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/par_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/par_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/par_trc.F90	(revision 14097)
@@ -0,0 +1,43 @@
+MODULE par_trc
+   !!======================================================================
+   !!                        ***  par_trc  ***
+   !! TOP :   set the passive tracers parameters
+   !!======================================================================
+   !! History :    -   !  1996-01  (M. Levy)  original code
+   !!              -   !  2000-04  (O. Aumont, M.A. Foujols)  HAMOCC3 and P3ZD
+   !!             1.0  !  2004-03  (C. Ethe) Free form and module
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+   USE par_kind          ! kind parameters
+   USE par_pisces        ! PISCES model  parameters
+   USE par_cfc           ! CFCs  tracers parameters
+   USE par_c14           ! C14 tracer    parameters
+   USE par_age           ! AGE tracer    parameters
+   USE par_my_trc        ! MY_TRC model  parameters
+   !
+
+   IMPLICIT NONE
+
+   INTEGER, PUBLIC,  PARAMETER :: jpmaxtrc = 100  ! Maximum number of tracers
+
+   INTEGER, PUBLIC             :: jptra           !: Total number of passive tracers
+   INTEGER, PUBLIC             :: jp_pisces       !: number of passive tracers in PISCES model
+   INTEGER, PUBLIC             :: jp_cfc          !: number of CFC passive tracers 
+   INTEGER, PUBLIC             :: jp_my_trc       !: number of passive tracers in MY_TRC model
+   INTEGER, PUBLIC             :: jp_bgc          !: number of passive tracers for the BGC model
+
+   INTEGER, PUBLIC             :: jp_dia3d        !: number of 3D diagnostic variables
+   INTEGER, PUBLIC             :: jp_dia2d        !: number of 2D diagnostic variables
+
+   LOGICAL, PUBLIC             :: ln_pisces       !: PISCES flag 
+   LOGICAL, PUBLIC             :: ln_age          !: AGE flag 
+   LOGICAL, PUBLIC             :: ln_cfc11        !: CFC11 flag 
+   LOGICAL, PUBLIC             :: ln_cfc12        !: CFC12 flag 
+   LOGICAL, PUBLIC             :: ln_sf6          !: SF6 flag 
+   LOGICAL, PUBLIC             :: ll_cfc          !: CFC flag 
+   LOGICAL, PUBLIC             :: ln_c14          !: C14 flag 
+   LOGICAL, PUBLIC             :: ln_my_trc       !: MY_TRC flag 
+
+   REAL(wp), PUBLIC            :: rtrn  = 0.5 * EPSILON( 1.e0 )    !: truncation value
+
+END MODULE par_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/prtctl_trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/prtctl_trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/prtctl_trc.F90	(revision 14097)
@@ -0,0 +1,295 @@
+MODULE prtctl_trc
+   !!======================================================================
+   !!                         ***  MODULE prtctl_trc  ***
+   !! TOP :   print all SUM trends for each processor domain
+   !!======================================================================
+   !! History :    -   !  2005-07  (C. Talandier) original code for OPA
+   !!             1.0  !  2005-10  (C. Ethe     ) adapted to passive tracer
+   !!----------------------------------------------------------------------
+   !!   prt_ctl_trc      :   control print in mpp for passive tracers
+   !!   prt_ctl_trc_info :   ???
+   !!   prt_ctl_trc_init :   ???
+   !!----------------------------------------------------------------------
+   USE par_trc          ! TOP parameters
+   USE oce_trc          ! ocean space and time domain variables
+   USE prtctl           ! print control for OPA
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   numid_trc          !: logical unit 
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nlditl , nldjtl    !: first, last indoor index for each i-domain
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nleitl , nlejtl    !: first, last indoor index for each j-domain
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nimpptl, njmpptl   !: i-, j-indexes for each processor
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   nlcitl , nlcjtl    !: dimensions of every subdomain
+   INTEGER , DIMENSION(:), ALLOCATABLE ::   ibonitl, ibonjtl
+
+   REAL(wp), DIMENSION(:,:), ALLOCATABLE ::   tra_ctl         !: previous trend values
+
+   PUBLIC prt_ctl_trc         ! called by all subroutines
+   PUBLIC prt_ctl_trc_info    !
+   PUBLIC prt_ctl_trc_init    ! called by opa.F90
+
+CONTAINS
+
+   SUBROUTINE prt_ctl_trc( tab4d, mask, clinfo, ovlap, kdim, clinfo2 )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl  ***
+      !!
+      !! ** Purpose : - print sum control 3D arrays over the same area 
+      !!                in mono and mpp case. This way can be usefull when
+      !!                debugging a new parametrization in mono or mpp. 
+      !!
+      !! ** Method  : 2 possibilities exist when setting the ln_ctl parameter to
+      !!                .true. in the ocean namelist:
+      !!              - to debug a MPI run .vs. a mono-processor one; 
+      !!                the control print will be done over each sub-domain.
+      !!                The nictl[se] and njctl[se] parameters in the namelist must 
+      !!                be set to zero and [ij]splt to the corresponding splitted
+      !!                domain in MPI along respectively i-, j- directions.
+      !!              - to debug a mono-processor run over the whole domain/a specific area; 
+      !!                in the first case the nictl[se] and njctl[se] parameters must be set
+      !!                to zero else to the indices of the area to be controled. In both cases
+      !!                isplt and jsplt must be set to 1.
+      !!              - All arguments of the above calling sequence are optional so their
+      !!                name must be explicitly typed if used. For instance if the mask
+      !!                array tmask(:,:,:) must be passed through the prt_ctl subroutine, 
+      !!                it must looks like: CALL prt_ctl( mask=tmask ).
+      !!----------------------------------------------------------------------
+      REAL(wp)         , DIMENSION(:,:,:,:), INTENT(in), OPTIONAL ::   tab4d     ! 4D array
+      REAL(wp)         , DIMENSION(:,:,:)  , INTENT(in), OPTIONAL ::   mask      ! 3D mask to apply to the tab4d array
+      CHARACTER (len=*), DIMENSION(:)      , INTENT(in), OPTIONAL ::   clinfo    ! information about the tab3d array
+      CHARACTER (len=*)                    , INTENT(in), OPTIONAL ::   clinfo2   ! ???
+      INTEGER                              , INTENT(in), OPTIONAL ::   ovlap     ! overlap value
+      INTEGER                              , INTENT(in), OPTIONAL ::   kdim      ! k- direction for 4D arrays
+      !!
+      INTEGER  ::   overlap, jn, js, sind, eind, kdir, j_id
+      REAL(wp) ::   zsum, zvctl
+      CHARACTER (len=20), ALLOCATABLE, DIMENSION(:) ::   cl
+      CHARACTER (len=10) ::   cl2
+      REAL(wp), DIMENSION(jpi,jpj,jpk)  :: zmask, ztab3d 
+      !!----------------------------------------------------------------------
+
+      ALLOCATE( cl(jptra) )
+      !                                      ! Arrays, scalars initialization 
+      overlap       = 0
+      kdir          = jpkm1
+      zsum          = 0.e0
+      zvctl         = 0.e0
+      cl(:)         = ''
+      cl2           = ''
+      ztab3d(:,:,:) = 0.e0
+      zmask (:,:,:) = 1.e0
+
+      !                                      ! Control of optional arguments
+      IF( PRESENT(ovlap)   )   overlap       = ovlap
+      IF( PRESENT(kdim)    )   kdir          = kdim
+      IF( PRESENT(clinfo ) )   cl(:)         = clinfo(:)
+      IF( PRESENT(clinfo2) )   cl2           = clinfo2
+      IF( PRESENT(mask)    )   zmask (:,:,:) = mask(:,:,:)
+
+      IF( lk_mpp )   THEN      ! processor number
+         sind = narea
+         eind = narea
+      ELSE                     ! processors total number
+         sind = 1
+         eind = ijsplt
+      ENDIF
+
+      ! Loop over each sub-domain, i.e. the total number of processors ijsplt
+      DO js = sind, eind
+         !
+         ! Set logical unit
+         j_id = numid_trc( js - narea + 1 )
+         ! Set indices for the SUM control
+         IF( .NOT. lsp_area ) THEN
+            IF (lk_mpp )   THEN
+               nictls = MAX( 1, nlditl(js) - overlap )
+               nictle = nleitl(js) + overlap * MIN( 1, nlcitl(js) - nleitl(js)) 
+               njctls = MAX( 1, nldjtl(js) - overlap )
+               njctle = nlejtl(js) + overlap * MIN( 1, nlcjtl(js) - nlejtl(js))
+               ! Do not take into account the bound of the domain
+               IF( ibonitl(js) == -1 .OR. ibonitl(js) == 2 )   nictls = MAX( 2, nictls )
+               IF( ibonitl(js) ==  1 .OR. ibonitl(js) == 2 )   nictle = MIN( nictle, nleitl(js) - 1 )
+               IF( ibonjtl(js) == -1 .OR. ibonjtl(js) == 2 )   njctls = MAX( 2, njctls )
+               IF( ibonjtl(js) ==  1 .OR. ibonjtl(js) == 2 )   njctle = MIN( njctle, nlejtl(js) - 1 )
+            ELSE
+               nictls = MAX( 1, nimpptl(js) + nlditl(js) - 1 - overlap )
+               nictle = nimpptl(js) + nleitl(js) - 1 + overlap * MIN( 1, nlcitl(js) - nleitl(js) ) 
+               njctls = MAX( 1, njmpptl(js) + nldjtl(js) - 1 - overlap )
+               njctle = njmpptl(js) + nlejtl(js) - 1 + overlap * MIN( 1, nlcjtl(js) - nlejtl(js) ) 
+               ! Do not take into account the bound of the domain
+               IF( ibonitl(js) == -1 .OR. ibonitl(js) == 2 )   nictls = MAX( 2, nictls )
+               IF( ibonjtl(js) == -1 .OR. ibonjtl(js) == 2 )   njctls = MAX( 2, njctls )
+               IF( ibonitl(js) ==  1 .OR. ibonitl(js) == 2 )   nictle = MIN( nictle, nimpptl(js) + nleitl(js) - 2 )
+               IF( ibonjtl(js) ==  1 .OR. ibonjtl(js) == 2 )   njctle = MIN( njctle, njmpptl(js) + nlejtl(js) - 2 )
+            ENDIF
+         ENDIF
+         !
+         IF( PRESENT(clinfo2) ) THEN
+            DO jn = 1, jptra
+               zvctl  = tra_ctl(jn,js)
+               ztab3d(:,:,:) = tab4d(:,:,:,jn)
+               zsum          = SUM( ztab3d(nictls:nictle,njctls:njctle,1:kdir)   &
+                  &                * zmask(nictls:nictle,njctls:njctle,1:kdir) )
+               WRITE(j_id,FMT="(3x,a,' : ',D23.16)") cl(jn), zsum-zvctl
+               tra_ctl(jn,js) = zsum
+            END DO
+         ELSE
+            DO jn = 1, jptra
+               ztab3d(:,:,:) = tab4d(:,:,:,jn)
+               zsum          = SUM( ztab3d(nictls:nictle,njctls:njctle,1:kdir)   &
+                  &               *  zmask(nictls:nictle,njctls:njctle,1:kdir) )
+               WRITE(j_id,FMT="(3x,a,' : ',D23.16)") cl(jn), zsum
+            END DO
+         ENDIF
+         !
+      END DO
+      !
+      DEALLOCATE( cl )
+      !
+   END SUBROUTINE prt_ctl_trc
+
+
+   SUBROUTINE prt_ctl_trc_info( clinfo )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl_trc_info  ***
+      !!
+      !! ** Purpose : - print information without any computation
+      !!----------------------------------------------------------------------
+      CHARACTER (len=*), INTENT(in) ::   clinfo      ! information to print
+      !! 
+      INTEGER ::   js, sind, eind, j_id
+      !!----------------------------------------------------------------------
+
+      IF( lk_mpp ) THEN      ! processor number
+         sind = narea
+         eind = narea
+      ELSE                   ! total number of processors
+         sind = 1
+         eind = ijsplt
+      ENDIF
+
+      ! Loop over each sub-domain, i.e. number of processors ijsplt
+      DO js = sind, eind
+         j_id = numid_trc(js - narea + 1)
+         WRITE(j_id,*) clinfo
+      END DO
+      !
+   END SUBROUTINE prt_ctl_trc_info
+
+
+   SUBROUTINE prt_ctl_trc_init
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE prt_ctl_trc_init  ***
+      !!
+      !! ** Purpose :   open ASCII files & compute indices
+      !!----------------------------------------------------------------------
+      INTEGER            ::   js, sind, eind, j_id
+      CHARACTER (len=31) :: clfile_out
+      CHARACTER (len=27) :: clb_name
+      CHARACTER (len=19) :: cl_run
+      !!----------------------------------------------------------------------
+
+      !                             ! Allocate arrays
+      ALLOCATE( nlditl (ijsplt) )
+      ALLOCATE( nldjtl (ijsplt) )
+      ALLOCATE( nleitl (ijsplt) )
+      ALLOCATE( nlejtl (ijsplt) )
+      ALLOCATE( nimpptl(ijsplt) )
+      ALLOCATE( njmpptl(ijsplt) )
+      ALLOCATE( nlcitl (ijsplt) )
+      ALLOCATE( nlcjtl (ijsplt) )
+      ALLOCATE( tra_ctl(jptra,ijsplt) )
+      ALLOCATE( ibonitl(ijsplt) )
+      ALLOCATE( ibonjtl(ijsplt) )
+
+      tra_ctl(:,:) = 0.e0           ! Initialization to zero
+
+      IF( lk_mpp ) THEN
+         sind = narea
+         eind = narea
+         clb_name = "('mpp.top.output_',I4.4)"
+         cl_run = 'MULTI processor run'
+         ! use indices for each area computed by mpp_init subroutine
+         nlditl(1:jpnij) = nldit(:) 
+         nleitl(1:jpnij) = nleit(:) 
+         nldjtl(1:jpnij) = nldjt(:) 
+         nlejtl(1:jpnij) = nlejt(:) 
+         !
+         nimpptl(1:jpnij) = nimppt(:)
+         njmpptl(1:jpnij) = njmppt(:)
+         !
+         nlcitl(1:jpnij) = nlcit(:)
+         nlcjtl(1:jpnij) = nlcjt(:)
+         !
+         ibonitl(1:jpnij) = ibonit(:)
+         ibonjtl(1:jpnij) = ibonjt(:)
+      ELSE
+         sind = 1
+         eind = ijsplt
+         clb_name = "('mono.top.output_',I4.4)"
+         cl_run   = 'MONO processor run '
+         ! compute indices for each area as done in mpp_init subroutine
+         CALL sub_dom
+      ENDIF
+
+      ALLOCATE( numid_trc(eind-sind+1) )
+
+      DO js = sind, eind
+         WRITE(clfile_out,FMT=clb_name) js-1
+         CALL ctl_opn( numid_trc(js -narea + 1), clfile_out, 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+         j_id = numid_trc(js -narea + 1)
+         WRITE(j_id,*)
+         WRITE(j_id,*) '                 L O D Y C - I P S L'
+         WRITE(j_id,*) '                       N E M 0 '
+         WRITE(j_id,*) '            Ocean General Circulation Model'
+         WRITE(j_id,*) '               version TOP 1.0  (2005) '
+         WRITE(j_id,*)
+         WRITE(j_id,*) '                   PROC number: ', js
+         WRITE(j_id,*)
+         WRITE(j_id,FMT="(19x,a20)") cl_run
+
+         ! Print the SUM control indices
+         IF( .NOT. lsp_area )   THEN
+            IF ( lk_mpp )   THEN
+               nictls = nlditl(js) 
+               nictle = nleitl(js)
+               njctls = nldjtl(js)
+               njctle = nlejtl(js)
+            ELSE
+               nictls = nimpptl(js) + nlditl(js) - 1
+               nictle = nimpptl(js) + nleitl(js) - 1
+               njctls = njmpptl(js) + nldjtl(js) - 1
+               njctle = njmpptl(js) + nlejtl(js) - 1
+            ENDIF
+         ENDIF
+         WRITE(j_id,*) 
+         WRITE(j_id,*) 'prt_tra_ctl :  Sum control indices'
+         WRITE(j_id,*) '~~~~~~~'
+         WRITE(j_id,*)
+         WRITE(j_id,9000)'                                nlej   = ', nlejtl(js), '              '
+         WRITE(j_id,9000)'                  ------------- njctle = ', njctle, ' -------------'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9002)'           nictls = ', nictls,  '                           nictle = ', nictle
+         WRITE(j_id,9002)'           nldi   = ', nlditl(js),  '                           nlei   = ', nleitl(js)
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9001)'                  |                                       |'
+         WRITE(j_id,9004)'  njmpp  = ',njmpptl(js),'   ------------- njctls = ', njctls, ' -------------'
+         WRITE(j_id,9003)'           nimpp  = ', nimpptl(js), '        nldj   = ', nldjtl(js), '              '
+         WRITE(j_id,*)
+         WRITE(j_id,*)
+
+9000     FORMAT(a41,i4.4,a14)
+9001     FORMAT(a59)
+9002     FORMAT(a20,i4.4,a36,i3.3)
+9003     FORMAT(a20,i4.4,a17,i4.4)
+9004     FORMAT(a11,i4.4,a26,i4.4,a14)
+      END DO
+      !
+   END SUBROUTINE prt_ctl_trc_init
+
+END MODULE prtctl_trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trc.F90	(revision 14097)
@@ -0,0 +1,173 @@
+MODULE trc
+   !!======================================================================
+   !!                      ***  MODULE  trc  ***
+   !! Passive tracers   :  module for tracers defined
+   !!======================================================================
+   !! History :   OPA  !  1996-01  (M. Levy)  Original code
+   !!              -   !  2000-04  (O. Aumont, M.A. Foujols)  HAMOCC3 and P3ZD
+   !!   NEMO      1.0  !  2004-03  (C. Ethe)  Free form and module
+   !!----------------------------------------------------------------------
+   USE par_oce
+   USE par_trc
+   USE bdy_oce, only: jp_bdy, ln_bdy, nb_bdy, OBC_DATA
+   
+   IMPLICIT NONE
+   PUBLIC
+
+   PUBLIC   trc_alloc   ! called by nemogcm.F90
+
+   !                                     !!- logical units of passive tracers
+   INTEGER, PUBLIC ::   numnat_ref = -1   !: reference passive tracer namelist_top_ref
+   INTEGER, PUBLIC ::   numnat_cfg = -1   !: reference passive tracer namelist_top_cfg
+   INTEGER, PUBLIC ::   numont     = -1   !: reference passive tracer namelist output output.namelist.top
+   INTEGER, PUBLIC ::   numtrc_ref = -1   !: reference passive tracer namelist_top_ref
+   INTEGER, PUBLIC ::   numtrc_cfg = -1   !: reference passive tracer namelist_top_cfg
+   INTEGER, PUBLIC ::   numonr     = -1   !: reference passive tracer namelist output output.namelist.top
+   INTEGER, PUBLIC ::   numstr            !: tracer statistics
+   INTEGER, PUBLIC ::   numrtr            !: trc restart (read )
+   INTEGER, PUBLIC ::   numrtw            !: trc restart ( write )
+
+   !! passive tracers fields (before,now,after)
+   !! --------------------------------------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::  trai           !: initial total tracer
+   REAL(wp), PUBLIC                                        ::  areatot        !: total volume 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  cvol           !: volume correction -degrad option- 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  trn            !: tracer concentration for now time step
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  tra            !: tracer concentration for next time step
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  trb            !: tracer concentration for before time step
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  sbc_trc_b      !: Before sbc fluxes for tracers
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  sbc_trc        !: Now sbc fluxes for tracers
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  trc_i          !: prescribed tracer concentration in sea ice for SBC
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:  ) ::  trc_o          !: prescribed tracer concentration in ocean for SBC
+   INTEGER             , PUBLIC                            ::  nn_ice_tr      !: handling of sea ice tracers
+
+   !! interpolated gradient
+   !!--------------------------------------------------  
+   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
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  qsr_mean        !: daily mean qsr
+   
+   !! passive tracers  (input and output)
+   !! ------------------------------------------  
+   LOGICAL             , PUBLIC ::   ln_rsttr           !: boolean term for restart i/o for passive tracers (namelist)
+   LOGICAL             , PUBLIC ::   lrst_trc           !: logical to control the trc restart write
+   INTEGER             , PUBLIC ::   nn_writetrc        !: time step frequency for concentration outputs (namelist)
+   INTEGER             , PUBLIC ::   nutwrs             !: output FILE for passive tracers restart
+   INTEGER             , PUBLIC ::   nutrst             !: logical unit for restart FILE for passive tracers
+   INTEGER             , PUBLIC ::   nn_rsttr           !: control of the time step ( 0 or 1 ) for pass. tr.
+   CHARACTER(len = 80) , PUBLIC ::   cn_trcrst_in       !: suffix of pass. tracer restart name (input)
+   CHARACTER(len = 256), PUBLIC ::   cn_trcrst_indir    !: restart input directory
+   CHARACTER(len = 80) , PUBLIC ::   cn_trcrst_out      !: suffix of pass. tracer restart name (output)
+   CHARACTER(len = 256), PUBLIC ::   cn_trcrst_outdir   !: restart output directory
+   REAL(wp)            , PUBLIC ::   rdttrc             !: passive tracer time step
+   REAL(wp)            , PUBLIC ::   r2dttrc            !: = 2*rdttrc except at nit000 (=rdttrc) if neuler=0
+   LOGICAL             , PUBLIC ::   ln_top_euler       !: boolean term for euler integration 
+   LOGICAL             , PUBLIC ::   ln_trcdta          !: Read inputs data from files
+   LOGICAL             , PUBLIC ::   ln_trcdmp          !: internal damping flag
+   LOGICAL             , PUBLIC ::   ln_trcdmp_clo      !: internal damping flag on closed seas
+   INTEGER             , PUBLIC ::   nittrc000          !: first time step of passive tracers model
+   LOGICAL             , PUBLIC ::   l_trcdm2dc         !: Diurnal cycle for TOP
+
+   !! Information for the ice module for tracers
+   !! ------------------------------------------
+   TYPE, PUBLIC ::   TRC_I_NML         !: Ice tracer namelist structure
+         REAL(wp)         :: trc_ratio    ! ice-ocean trc ratio
+         REAL(wp)         :: trc_prescr   ! prescribed ice trc cc
+         CHARACTER(len=2) :: ctrc_o       ! choice of ocean trc cc
+   END TYPE
+   !
+   REAL(wp)        , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   trc_ice_ratio    !: ice-ocean tracer ratio
+   REAL(wp)        , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   trc_ice_prescr   !: prescribed ice trc cc
+   CHARACTER(len=2), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   cn_trc_o         !: choice of ocean tracer cc
+
+
+   !! information for outputs
+   !! --------------------------------------------------
+   TYPE, PUBLIC ::   PTRACER        !: Passive tracer type
+      CHARACTER(len=20) ::   clsname   ! short name
+      CHARACTER(len=80) ::   cllname   ! long name
+      CHARACTER(len=20) ::   clunit    ! unit
+      LOGICAL           ::   llinit    ! read in a file or not
+      LOGICAL           ::   llsbc     ! read in a file or not
+      LOGICAL           ::   llcbc     ! read in a file or not
+      LOGICAL           ::   llobc     ! read in a file or not
+   END TYPE PTRACER
+   !
+   CHARACTER(len=20), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ctrcnm   !: tracer name 
+   CHARACTER(len=80), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ctrcln   !: trccer field long name
+   CHARACTER(len=20), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ctrcun   !: tracer unit
+   !
+   TYPE, PUBLIC ::   DIAG         !: Passive trcacer ddditional diagnostic type
+      CHARACTER(len=20) ::   sname   ! short name
+      CHARACTER(len=80) ::   lname   ! long name
+      CHARACTER(len=20) ::   units   ! unit
+   END TYPE DIAG
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   trc3d   !: 3D diagnostics for tracers
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   trc2d   !: 2D diagnostics for tracers
+
+   !! information for inputs
+   !! --------------------------------------------------
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_ini    !: Initialisation from data input file
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_obc    !: Use open boundary condition data
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_sbc    !: Use surface boundary condition data
+   LOGICAL , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ln_trc_cbc    !: Use coastal boundary condition data
+   LOGICAL , PUBLIC                                  ::   ln_rnf_ctl    !: remove runoff dilution on tracers
+   REAL(wp), PUBLIC                                  ::   rn_bc_time    !: Time scaling factor for SBC and CBC data (seconds in a day)
+   !
+   CHARACTER(len=20), PUBLIC, DIMENSION(jp_bdy) :: cn_trc_dflt   ! Default OBC condition for all tracers
+   CHARACTER(len=20), PUBLIC, DIMENSION(jp_bdy) :: cn_trc        ! Choice of boundary condition for tracers
+   INTEGER,           PUBLIC, DIMENSION(jp_bdy) :: nn_trcdmp_bdy !: =T Tracer damping
+   !
+   ! Vertical axis used in the sediment module
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   profsed
+!$AGRIF_DO_NOT_TREAT
+   ! External data structure of BDY for TOP. Available elements: cn_obc, ll_trc, trcnow, dmp
+   TYPE(OBC_DATA), PUBLIC, ALLOCATABLE, DIMENSION(:,:), TARGET ::   trcdta_bdy   !: bdy external data (local process)
+!$AGRIF_END_DO_NOT_TREAT
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trc_alloc()
+      !!-------------------------------------------------------------------
+      !!                    *** ROUTINE trc_alloc ***
+      !!-------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop
+      !!-------------------------------------------------------------------
+      INTEGER :: ierr(4)
+      !!-------------------------------------------------------------------
+      ierr(:) = 0
+      !
+      ALLOCATE( trn(jpi,jpj,jpk,jptra), trb(jpi,jpj,jpk,jptra), tra(jpi,jpj,jpk,jptra),       &  
+         &      trc_i(jpi,jpj,jptra)  , trc_o(jpi,jpj,jptra)                          ,       &
+         &      gtru (jpi,jpj,jptra)  , gtrv (jpi,jpj,jptra)                          ,       &
+         &      gtrui(jpi,jpj,jptra)  , gtrvi(jpi,jpj,jptra)                          ,       &
+         &      trc_ice_ratio(jptra)  , trc_ice_prescr(jptra) , cn_trc_o(jptra)       ,       &
+         &      sbc_trc_b(jpi,jpj,jptra), sbc_trc(jpi,jpj,jptra)                      ,       &  
+         &      cvol(jpi,jpj,jpk)     , trai(jptra)           , qsr_mean(jpi,jpj)     ,       &
+         &      ctrcnm(jptra)         , ctrcln(jptra)         , ctrcun(jptra)         ,       &
+         &      ln_trc_ini(jptra)     ,                                                       &
+         &      ln_trc_sbc(jptra)     , ln_trc_cbc(jptra)     , ln_trc_obc(jptra)     ,       &
+         &      STAT = ierr(1)  )
+      !
+      IF( ln_bdy       )   ALLOCATE( trcdta_bdy(jptra, jp_bdy)  , STAT = ierr(2) )
+      !
+      IF (jp_dia3d > 0 )   ALLOCATE( trc3d(jpi,jpj,jpk,jp_dia3d), STAT = ierr(3) )
+      !
+      IF (jp_dia2d > 0 )   ALLOCATE( trc2d(jpi,jpj,jpk,jp_dia2d), STAT = ierr(4) )
+      ! 
+      trc_alloc = MAXVAL( ierr )
+      IF( trc_alloc /= 0 )   CALL ctl_stop( 'STOP', 'trc_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION trc_alloc
+
+   !!======================================================================
+END MODULE trc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbc.F90	(revision 14097)
@@ -0,0 +1,473 @@
+MODULE trcbc
+   !!======================================================================
+   !!                     ***  MODULE  trcbc  ***
+   !! TOP :  module for passive tracer boundary conditions
+   !!=====================================================================
+   !! History :  3.5 !  2014 (M. Vichi, T. Lovato)  Original
+   !!            3.6 !  2015 (T . Lovato) Revision and BDY support
+   !!            4.0 !  2016 (T . Lovato) Include application of sbc and cbc
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP model 
+   !!----------------------------------------------------------------------
+   !!   trc_bc       :  Apply tracer Boundary Conditions
+   !!----------------------------------------------------------------------
+   USE par_trc       !  passive tracers parameters
+   USE oce_trc       !  shared variables between ocean and passive tracers
+   USE trc           !  passive tracers common variables
+   USE iom           !  I/O manager
+   USE lib_mpp       !  MPP library
+   USE fldread       !  read input fields
+   USE bdy_oce,  ONLY: ln_bdy, nb_bdy , idx_bdy, ln_coords_file, rn_time_dmp, rn_time_dmp_out
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_bc         ! called in trcstp.F90 or within TOP modules
+   PUBLIC   trc_bc_ini     ! called in trcini.F90 
+
+   INTEGER  , SAVE, PUBLIC                             :: nb_trcobc    ! number of tracers with open BC
+   INTEGER  , SAVE, PUBLIC                             :: nb_trcsbc    ! number of tracers with surface BC
+   INTEGER  , SAVE, PUBLIC                             :: nb_trccbc    ! number of tracers with coastal BC
+   INTEGER  , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: n_trc_indobc ! index of tracer with OBC data
+   INTEGER  , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: n_trc_indsbc ! index of tracer with SBC data
+   INTEGER  , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: n_trc_indcbc ! index of tracer with CBC data
+   REAL(wp) , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: rf_trsfac    ! multiplicative factor for SBC tracer values
+   TYPE(FLD), SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: sf_trcsbc    ! structure of data input SBC (file informations, fields read)
+   REAL(wp) , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: rf_trcfac    ! multiplicative factor for CBC tracer values
+   TYPE(FLD), SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: sf_trccbc    ! structure of data input CBC (file informations, fields read)
+   REAL(wp) , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: rf_trofac    ! multiplicative factor for OBCtracer values
+#if defined key_agrif
+   TYPE(FLD), SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: sf_trcobc    ! structure of data input OBC (file informations, fields read)
+#else
+   TYPE(FLD), SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:), TARGET  :: sf_trcobc
+#endif
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_bc_ini( ntrc )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_bc_ini  ***
+      !!                    
+      !! ** Purpose :   initialisation of passive tracer BC data 
+      !! 
+      !! ** Method  : - Read namtsd namelist
+      !!              - allocates passive tracer BC data structure 
+      !!----------------------------------------------------------------------
+      INTEGER,INTENT(in) :: ntrc                           ! number of tracers
+      !
+      INTEGER            :: jl, jn , ib, ibd, ii, ij, ik   ! dummy loop indices
+      INTEGER            :: ierr0, ierr1, ierr2, ierr3     ! temporary integers
+      INTEGER            :: ios                            ! Local integer output status for namelist read
+      INTEGER            :: nblen, igrd                    ! support arrays for BDY
+      CHARACTER(len=100) :: clndta, clntrc
+      !
+      CHARACTER(len=100) :: cn_dir_sbc, cn_dir_cbc, cn_dir_obc
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) :: slf_i  ! local array of namelist informations on the fields to read
+      TYPE(FLD_N), DIMENSION(jpmaxtrc) :: sn_trcobc    ! open
+      TYPE(FLD_N), DIMENSION(jpmaxtrc) :: sn_trcsbc    ! surface
+      TYPE(FLD_N), DIMENSION(jpmaxtrc) :: sn_trccbc    ! coastal
+      REAL(wp)   , DIMENSION(jpmaxtrc) :: rn_trofac    ! multiplicative factor for tracer values
+      REAL(wp)   , DIMENSION(jpmaxtrc) :: rn_trsfac    ! multiplicative factor for tracer values
+      REAL(wp)   , DIMENSION(jpmaxtrc) :: rn_trcfac    ! multiplicative factor for tracer values
+      !!
+      NAMELIST/namtrc_bc/ cn_dir_obc, sn_trcobc, rn_trofac, cn_dir_sbc, sn_trcsbc, rn_trsfac, & 
+                        & cn_dir_cbc, sn_trccbc, rn_trcfac, ln_rnf_ctl, rn_bc_time
+      NAMELIST/namtrc_bdy/ cn_trc_dflt, cn_trc, nn_trcdmp_bdy
+      !!----------------------------------------------------------------------
+      !
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_bc_ini : Tracers Boundary Conditions (BC)'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+      ENDIF
+      !  Initialisation and local array allocation
+      ierr0 = 0   ;   ierr1 = 0   ;   ierr2 = 0   ;   ierr3 = 0  
+      ALLOCATE( slf_i(ntrc), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_bc_ini: unable to allocate local slf_i' )   ;   RETURN
+      ENDIF
+
+      ! Compute the number of tracers to be initialised with open, surface and boundary data
+      ALLOCATE( n_trc_indobc(ntrc), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_bc_ini: unable to allocate n_trc_indobc' )   ;   RETURN
+      ENDIF
+      nb_trcobc       = 0
+      n_trc_indobc(:) = 0
+      !
+      ALLOCATE( n_trc_indsbc(ntrc), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_bc_ini: unable to allocate n_trc_indsbc' )   ;   RETURN
+      ENDIF
+      nb_trcsbc       = 0
+      n_trc_indsbc(:) = 0
+      !
+      ALLOCATE( n_trc_indcbc(ntrc), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_bc_ini: unable to allocate n_trc_indcbc' )   ;   RETURN
+      ENDIF
+      nb_trccbc       = 0
+      n_trc_indcbc(:) = 0
+      !
+      ! Read Boundary Conditions Namelists
+      REWIND( numnat_ref )              ! Namelist namtrc_bc in reference namelist : Passive tracer data structure
+      READ  ( numnat_ref, namtrc_bc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_bc in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc_bc in configuration namelist : Passive tracer data structure
+      READ  ( numnat_cfg, namtrc_bc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_bc in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_bc )
+
+      IF ( ln_bdy ) THEN
+         REWIND( numnat_ref )              ! Namelist namtrc_bdy in reference namelist : Passive tracer data structure
+         READ  ( numnat_ref, namtrc_bdy, IOSTAT = ios, ERR = 903)
+903      IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_bdy in reference namelist' )
+         ! make sur that all elements of the namelist variables have a default definition from namelist_ref
+         cn_trc     (2:jp_bdy) = cn_trc     (1)
+         cn_trc_dflt(2:jp_bdy) = cn_trc_dflt(1)
+         REWIND( numnat_cfg )              ! Namelist namtrc_bdy in configuration namelist : Passive tracer data structure
+         READ  ( numnat_cfg, namtrc_bdy, IOSTAT = ios, ERR = 904 )
+904      IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_bdy in configuration namelist' )
+         IF(lwm) WRITE ( numont, namtrc_bdy )
+      
+         ! setup up preliminary informations for BDY structure
+         DO jn = 1, ntrc
+            DO ib = 1, nb_bdy
+               ! Set type of obc in BDY data structure (around here we may plug user override of obc type from nml)
+               IF ( ln_trc_obc(jn) ) THEN   ;   trcdta_bdy(jn,ib)%cn_obc = TRIM( cn_trc     (ib) )
+               ELSE                         ;   trcdta_bdy(jn,ib)%cn_obc = TRIM( cn_trc_dflt(ib) )
+               ENDIF
+               ! set damping use in BDY data structure
+               trcdta_bdy(jn,ib)%dmp = .false.
+               IF(nn_trcdmp_bdy(ib) == 1 .AND. ln_trc_obc(jn) )   trcdta_bdy(jn,ib)%dmp = .true.
+               IF(nn_trcdmp_bdy(ib) == 2                      )   trcdta_bdy(jn,ib)%dmp = .true.
+               IF(trcdta_bdy(jn,ib)%cn_obc == 'frs' .AND. nn_trcdmp_bdy(ib) /= 0 )  &
+                   & CALL ctl_stop( 'trc_bc_ini: Use FRS OR relaxation' )
+               IF(  .NOT.( 0 <= nn_trcdmp_bdy(ib)  .AND.  nn_trcdmp_bdy(ib) <= 2 )  )  &
+                   & CALL ctl_stop( 'trc_bc_ini: Not a valid option for nn_trcdmp_bdy. Allowed: 0,1,2.' )
+            END DO
+         END DO
+      ELSE
+         ! Force all tracers OBC to false if bdy not used
+         ln_trc_obc = .false.
+      ENDIF
+
+      ! compose BC data indexes
+      DO jn = 1, ntrc
+         IF( ln_trc_obc(jn) ) THEN
+             nb_trcobc       = nb_trcobc + 1   ;   n_trc_indobc(jn) = nb_trcobc
+         ENDIF
+         IF( ln_trc_sbc(jn) ) THEN
+             nb_trcsbc       = nb_trcsbc + 1   ;   n_trc_indsbc(jn) = nb_trcsbc
+         ENDIF
+         IF( ln_trc_cbc(jn) ) THEN
+             nb_trccbc       = nb_trccbc + 1   ;   n_trc_indcbc(jn) = nb_trccbc
+         ENDIF
+      END DO
+
+      ! Print summmary of Boundary Conditions
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,'(a,i3)') '   Total tracers to be initialized with SURFACE BCs data:', nb_trcsbc
+         IF ( nb_trcsbc > 0 ) THEN
+            WRITE(numout,*) '   #trc        NAME        Boundary     Mult.Fact. '
+            DO jn = 1, ntrc
+               IF ( ln_trc_sbc(jn) ) WRITE(numout,9001) jn, TRIM( sn_trcsbc(jn)%clvar ), 'SBC', rn_trsfac(jn)
+            END DO
+         ENDIF
+         WRITE(numout,'(2a)') '   SURFACE BC data repository : ', TRIM(cn_dir_sbc)
+         !
+         WRITE(numout,*)
+         WRITE(numout,'(a,i3)') '   Total tracers to be initialized with COASTAL BCs data:', nb_trccbc
+         IF( nb_trccbc > 0 ) THEN
+            WRITE(numout,*) '   #trc        NAME        Boundary     Mult.Fact. '
+            DO jn = 1, ntrc
+               IF ( ln_trc_cbc(jn) ) WRITE(numout, 9001) jn, TRIM( sn_trccbc(jn)%clvar ), 'CBC', rn_trcfac(jn)
+            END DO
+         ENDIF
+         WRITE(numout,'(2a)') '   COASTAL BC data repository : ', TRIM(cn_dir_cbc)
+         IF( .NOT.ln_rnf .OR. .NOT.ln_linssh )   ln_rnf_ctl = .FALSE.
+         IF( ln_rnf_ctl )  WRITE(numout,'(a)') &
+              &            ' -> Remove runoff dilution effect on tracers with absent river load (ln_rnf_ctl = .TRUE.)'
+         WRITE(numout,*)
+         WRITE(numout,'(a,i3)') '   Total tracers to be initialized with OPEN BCs data:', nb_trcobc
+
+         IF( ln_bdy .AND. nb_trcobc > 0 ) THEN
+            WRITE(numout,*) '   #trc        NAME        Boundary     Mult.Fact.   OBC Settings'
+            DO jn = 1, ntrc
+               IF (       ln_trc_obc(jn) )  WRITE(numout, 9001) jn, TRIM( sn_trcobc(jn)%clvar ), 'OBC', rn_trofac(jn), &
+                    &                                           (trcdta_bdy(jn,ib)%cn_obc,ib=1,nb_bdy)
+               IF ( .NOT. ln_trc_obc(jn) )  WRITE(numout, 9002) jn, 'Set data to IC and use default condition'       , &
+                    &                                           (trcdta_bdy(jn,ib)%cn_obc,ib=1,nb_bdy)
+            END DO
+            WRITE(numout,*) ' '
+            DO ib = 1, nb_bdy
+               IF(nn_trcdmp_bdy(ib) == 0) WRITE(numout,9003) '   Boundary ', ib, &
+                  &                                          ' -> NO damping of tracers'
+               IF(nn_trcdmp_bdy(ib) == 1) WRITE(numout,9003) '   Boundary ', ib, &
+                  &                                          ' -> damping ONLY for tracers with external data provided'
+               IF(nn_trcdmp_bdy(ib) == 2) WRITE(numout,9003) '   Boundary ', ib, &
+                  &                                          ' -> damping of ALL tracers'
+               IF(nn_trcdmp_bdy(ib) >  0) THEN
+                   WRITE(numout,9003) '     USE damping parameters from nambdy for boundary ', ib,' : '
+                   WRITE(numout,'(a,f10.2,a)') '     - Inflow damping time scale  : ',rn_time_dmp    (ib),' days'
+                   WRITE(numout,'(a,f10.2,a)') '     - Outflow damping time scale : ',rn_time_dmp_out(ib),' days'
+               ENDIF
+            END DO
+         ENDIF
+         !
+         WRITE(numout,'(2a)') '   OPEN BC data repository : ', TRIM(cn_dir_obc)
+      ENDIF
+9001  FORMAT(2x,i5, 3x, a15, 3x, a5, 6x, e11.3, 4x, 10a13)
+9002  FORMAT(2x,i5, 3x, a41, 3x, 10a13)
+9003  FORMAT(a, i5, a)
+      !
+      !
+      ! OPEN Lateral boundary conditions
+      IF( ln_bdy .AND. nb_trcobc > 0 ) THEN 
+         ALLOCATE ( sf_trcobc(nb_trcobc), rf_trofac(nb_trcobc), STAT=ierr1 )
+         IF( ierr1 > 0 ) THEN
+            CALL ctl_stop( 'trc_bc_ini: unable to allocate sf_trcobc structure' )   ;   RETURN
+         ENDIF
+         !
+         igrd = 1                       ! Everything is at T-points here
+         !
+         DO jn = 1, ntrc
+            DO ib = 1, nb_bdy
+               !
+               nblen = idx_bdy(ib)%nblen(igrd)
+               !
+               IF( ln_trc_obc(jn) ) THEN     !* Initialise from external data *!
+                  jl = n_trc_indobc(jn)
+                  slf_i(jl)    = sn_trcobc(jn)
+                  rf_trofac(jl) = rn_trofac(jn)
+                                                ALLOCATE( sf_trcobc(jl)%fnow(nblen,1,jpk)   , STAT=ierr2 )
+                  IF( sn_trcobc(jn)%ln_tint )   ALLOCATE( sf_trcobc(jl)%fdta(nblen,1,jpk,2) , STAT=ierr3 )
+                  IF( ierr2 + ierr3 > 0 ) THEN
+                    CALL ctl_stop( 'trc_bc_ini : unable to allocate passive tracer OBC data arrays' )   ;   RETURN
+                  ENDIF
+                  trcdta_bdy(jn,ib)%trc => sf_trcobc(jl)%fnow(:,1,:)
+                  trcdta_bdy(jn,ib)%rn_fac = rf_trofac(jl)
+               ELSE                          !* Initialise obc arrays from initial conditions *!
+                  ALLOCATE ( trcdta_bdy(jn,ib)%trc(nblen,jpk) )
+                  DO ibd = 1, nblen
+                     DO ik = 1, jpkm1
+                        ii = idx_bdy(ib)%nbi(ibd,igrd)
+                        ij = idx_bdy(ib)%nbj(ibd,igrd)
+                        trcdta_bdy(jn,ib)%trc(ibd,ik) = trn(ii,ij,ik,jn) * tmask(ii,ij,ik)
+                     END DO
+                  END DO
+                  trcdta_bdy(jn,ib)%rn_fac = 1._wp
+               ENDIF
+            END DO
+         END DO
+         !
+         CALL fld_fill( sf_trcobc, slf_i, cn_dir_obc, 'trc_bc_ini', 'Passive tracer OBC data', 'namtrc_bc' )
+         DO jn = 1, ntrc   ! define imap pointer, must be done after the call to fld_fill
+            DO ib = 1, nb_bdy
+               IF( ln_trc_obc(jn) ) THEN     !* Initialise from external data *!
+                  jl = n_trc_indobc(jn)
+                  sf_trcobc(jl)%imap => idx_bdy(ib)%nbmap(1:idx_bdy(ib)%nblen(igrd),igrd)
+               ENDIF
+            END DO
+         END DO
+         !
+      ENDIF
+
+      ! SURFACE Boundary conditions
+      IF( nb_trcsbc > 0 ) THEN       !  allocate only if the number of tracer to initialise is greater than zero
+         ALLOCATE( sf_trcsbc(nb_trcsbc), rf_trsfac(nb_trcsbc), STAT=ierr1 )
+         IF( ierr1 > 0 ) THEN
+            CALL ctl_stop( 'trc_bc_ini: unable to allocate  sf_trcsbc structure' )   ;   RETURN
+         ENDIF
+         !
+         DO jn = 1, ntrc
+            IF( ln_trc_sbc(jn) ) THEN      ! update passive tracers arrays with input data read from file
+               jl = n_trc_indsbc(jn)
+               slf_i(jl)    = sn_trcsbc(jn)
+               rf_trsfac(jl) = rn_trsfac(jn)
+                                            ALLOCATE( sf_trcsbc(jl)%fnow(jpi,jpj,1)   , STAT=ierr2 )
+               IF( sn_trcsbc(jn)%ln_tint )  ALLOCATE( sf_trcsbc(jl)%fdta(jpi,jpj,1,2) , STAT=ierr3 )
+               IF( ierr2 + ierr3 > 0 ) THEN
+                 CALL ctl_stop( 'trc_bc_ini : unable to allocate passive tracer SBC data arrays' )   ;   RETURN
+               ENDIF
+            ENDIF
+            !   
+         END DO
+         !                         ! fill sf_trcsbc with slf_i and control print
+         CALL fld_fill( sf_trcsbc, slf_i, cn_dir_sbc, 'trc_bc_ini', 'Passive tracer SBC data', 'namtrc_bc' )
+         !
+      ENDIF
+      !
+      ! COSTAL Boundary conditions
+      IF( nb_trccbc > 0 ) THEN       !  allocate only if the number of tracer to initialise is greater than zero
+         ALLOCATE( sf_trccbc(nb_trccbc), rf_trcfac(nb_trccbc), STAT=ierr1 )
+         IF( ierr1 > 0 ) THEN
+            CALL ctl_stop( 'trc_bc_ini: unable to allocate  sf_trccbc structure' )   ;   RETURN
+         ENDIF
+         !
+         DO jn = 1, ntrc
+            IF( ln_trc_cbc(jn) ) THEN      ! update passive tracers arrays with input data read from file
+               jl = n_trc_indcbc(jn)
+               slf_i(jl)    = sn_trccbc(jn)
+               rf_trcfac(jl) = rn_trcfac(jn)
+                                            ALLOCATE( sf_trccbc(jl)%fnow(jpi,jpj,1)   , STAT=ierr2 )
+               IF( sn_trccbc(jn)%ln_tint )  ALLOCATE( sf_trccbc(jl)%fdta(jpi,jpj,1,2) , STAT=ierr3 )
+               IF( ierr2 + ierr3 > 0 ) THEN
+                 CALL ctl_stop( 'trc_bc_ini : unable to allocate passive tracer CBC data arrays' )   ;   RETURN
+               ENDIF
+            ENDIF
+            !   
+         END DO
+         !                         ! fill sf_trccbc with slf_i and control print
+         CALL fld_fill( sf_trccbc, slf_i, cn_dir_cbc, 'trc_bc_ini', 'Passive tracer CBC data', 'namtrc_bc' )
+         !
+      ENDIF
+      !
+      DEALLOCATE( slf_i )          ! deallocate local field structure
+      !
+   END SUBROUTINE trc_bc_ini
+
+
+   SUBROUTINE trc_bc(kt, jit)
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_bc  ***
+      !!
+      !! ** Purpose :  Apply Boundary Conditions data to tracers
+      !!
+      !! ** Method  :  1) Read BC inputs and update data structures using fldread
+      !!               2) Apply Boundary Conditions to tracers
+      !!----------------------------------------------------------------------
+      USE fldread
+      !!      
+      INTEGER, INTENT(in)           ::   kt    ! ocean time-step index
+      INTEGER, INTENT(in), OPTIONAL ::   jit   ! subcycle time-step index (for timesplitting option)
+      !!
+      INTEGER  :: ji, jj, jk, jn, jl             ! Loop index
+      REAL(wp) :: zfact, zrnf
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_bc')
+
+      IF( kt == nit000 .AND. lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_bc : Surface boundary conditions for passive tracers.'
+         WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+
+      ! 1. Update Boundary conditions data
+      IF( PRESENT(jit) ) THEN 
+         !
+         ! OPEN boundary conditions (use kt_offset=+1 as they are applied at the end of the step)
+         IF( nb_trcobc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading OBC data for ', nb_trcobc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trcobc, kit=jit, kt_offset=+1)
+         ENDIF
+         !
+         ! SURFACE boundary conditions
+         IF( nb_trcsbc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading SBC data for ', nb_trcsbc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trcsbc, kit=jit)
+         ENDIF
+         !
+         ! COASTAL boundary conditions
+         IF( nb_trccbc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading CBC data for ', nb_trccbc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trccbc, kit=jit)
+         ENDIF
+         !
+      ELSE
+         !
+         ! OPEN boundary conditions (use kt_offset=+1 as they are applied at the end of the step)
+         IF( nb_trcobc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading OBC data for ', nb_trcobc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trcobc, kt_offset=+1)
+         ENDIF
+         !
+         ! SURFACE boundary conditions
+         IF( nb_trcsbc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading SBC data for ', nb_trcsbc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trcsbc )
+         ENDIF
+         !
+         ! COASTAL boundary conditions
+         IF( nb_trccbc > 0 ) THEN
+           if (lwp) write(numout,'(a,i5,a,i10)') '   reading CBC data for ', nb_trccbc ,' variable(s) at step ', kt
+           CALL fld_read( kt=kt, kn_fsbc=1, sd=sf_trccbc )
+         ENDIF
+         !
+      ENDIF
+
+      ! 2. Apply Boundary conditions data
+      ! 
+      DO jn = 1 , jptra
+         !
+         ! Remove river dilution for tracers with absent river load
+         IF( ln_rnf_ctl .AND. .NOT.ln_trc_cbc(jn) ) THEN
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1
+                  DO jk = 1, nk_rnf(ji,jj)
+                     zrnf = (rnf(ji,jj) + rnf_b(ji,jj)) * 0.5_wp * r1_rau0 / h_rnf(ji,jj)
+                     tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn)  + (trn(ji,jj,jk,jn) * zrnf)
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         !
+         ! OPEN boundary conditions: trcbdy is called in trcnxt !
+         !
+         ! SURFACE boundary conditions
+         IF( ln_trc_sbc(jn) ) THEN
+            jl = n_trc_indsbc(jn)
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zfact = 1. / ( e3t_n(ji,jj,1) * rn_bc_time )
+                  tra(ji,jj,1,jn) = tra(ji,jj,1,jn) + rf_trsfac(jl) * sf_trcsbc(jl)%fnow(ji,jj,1) * zfact
+               END DO
+            END DO
+         ENDIF
+         !
+         ! COASTAL boundary conditions
+         IF( ln_rnf .AND. ln_trc_cbc(jn) ) THEN
+            jl = n_trc_indcbc(jn)
+            DO jj = 2, jpj
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  DO jk = 1, nk_rnf(ji,jj)
+                     zfact = rn_rfact / ( e1e2t(ji,jj) * h_rnf(ji,jj) * rn_bc_time ) 
+                     tra(ji,jj,jk,jn) = tra(ji,jj,jk,jn) + rf_trcfac(jl) * sf_trccbc(jl)%fnow(ji,jj,1) * zfact
+                  END DO
+               END DO
+            END DO
+         ENDIF
+         !                                                       ! ===========
+      END DO                                                     ! tracer loop
+      !                                                          ! ===========
+      IF( ln_timing )   CALL timing_stop('trc_bc')
+      !
+   END SUBROUTINE trc_bc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                              NO 3D passive tracer data
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_bc_ini( ntrc )        ! Empty routine
+      INTEGER,INTENT(IN) :: ntrc                           ! number of tracers
+      WRITE(*,*) 'trc_bc_ini: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_bc_ini
+   SUBROUTINE trc_bc( kt )        ! Empty routine
+      WRITE(*,*) 'trc_bc: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_bc
+#endif
+
+   !!======================================================================
+END MODULE trcbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbdy.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbdy.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcbdy.F90	(revision 14097)
@@ -0,0 +1,164 @@
+MODULE trcbdy
+   !!======================================================================
+   !!                       ***  MODULE  bdytrc  ***
+   !! Ocean tracers:   Apply boundary conditions for tracers in TOP component
+   !!======================================================================
+   !! History :  1.0  !  2005-01  (J. Chanut, A. Sellar)  Original code
+   !!            3.0  !  2008-04  (NEMO team)  add in the reference version
+   !!            3.4  !  2011     (D. Storkey) rewrite in preparation for OBC-BDY merge
+   !!            3.5  !  2012     (S. Mocavero, I. Epicoco) Optimization of BDY communications
+   !!            3.6  !  2015     (T. Lovato) Adapt BDY for tracers in TOP component
+   !!            4.0  !  2016     (T. Lovato) Generalize OBC structure
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   trc_bdy       : Apply open boundary conditions & damping to tracers
+   !!----------------------------------------------------------------------
+   USE timing                       ! Timing
+   USE oce_trc                      ! ocean dynamics and tracers variables
+   USE par_trc
+   USE trc                          ! ocean space and time domain variables 
+   USE bdylib                       ! for orlanski library routines
+   USE lbclnk                       ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager               ! I/O manager
+   USE bdy_oce                      ! ocean open boundary conditions
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_bdy      ! routine called in trcnxt.F90 
+   PUBLIC trc_bdy_dmp  ! routine called in trcstp.F90 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_bdy( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE trc_bdy  ***
+      !!
+      !! ** Purpose : - Apply open boundary conditions for TOP tracers
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) :: kt     ! Main time step counter
+      !!
+      INTEGER                           :: ib_bdy ,ir, jn ,igrd ! Loop indices
+      REAL(wp), POINTER, DIMENSION(:,:) ::  ztrc
+      REAL(wp), POINTER                 ::  zfac
+      LOGICAL                           :: llrim0               ! indicate if rim 0 is treated
+      LOGICAL, DIMENSION(4)             :: llsend1, llrecv1     ! indicate how communications are to be carried out
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_bdy')
+      !
+      igrd = 1 
+      llsend1(:) = .false.  ;   llrecv1(:) = .false.
+      DO ir = 1, 0, -1   ! treat rim 1 before rim 0
+         IF( ir == 0 ) THEN   ;   llrim0 = .TRUE.
+         ELSE                 ;   llrim0 = .FALSE.
+         END IF
+         DO ib_bdy=1, nb_bdy
+            DO jn = 1, jptra
+               !
+               ztrc => trcdta_bdy(jn,ib_bdy)%trc 
+               zfac => trcdta_bdy(jn,ib_bdy)%rn_fac
+               !
+               SELECT CASE( TRIM(trcdta_bdy(jn,ib_bdy)%cn_obc) )
+               CASE('none'        )   ;   CYCLE
+               CASE('frs'         )   ! treat the whole boundary at once
+                  IF( ir == 0 ) CALL bdy_frs( idx_bdy(ib_bdy),                tra(:,:,:,jn), ztrc*zfac )
+               CASE('specified'   )   ! treat the whole rim      at once
+                  IF( ir == 0 ) CALL bdy_spe( idx_bdy(ib_bdy),                tra(:,:,:,jn), ztrc*zfac )
+               CASE('neumann'     )   ;   CALL bdy_nmn( idx_bdy(ib_bdy), igrd         , tra(:,:,:,jn) )   ! tra masked
+               CASE('orlanski'    )   ;   CALL bdy_orl( idx_bdy(ib_bdy), trb(:,:,:,jn), tra(:,:,:,jn), ztrc*zfac, ll_npo=.false. )
+               CASE('orlanski_npo')   ;   CALL bdy_orl( idx_bdy(ib_bdy), trb(:,:,:,jn), tra(:,:,:,jn), ztrc*zfac, ll_npo=.true. )
+               CASE DEFAULT           ;   CALL ctl_stop( 'trc_bdy : unrecognised option for open boundaries for passive tracers' )
+               END SELECT
+               !
+            END DO
+         END DO
+         !
+         IF( nn_hls > 1 .AND. ir == 1 ) CYCLE   ! at least 2 halos will be corrected -> no need to correct rim 1 before rim 0
+         IF( nn_hls == 1 ) THEN   ;   llsend1(:) = .false.   ;   llrecv1(:) = .false.   ;   END IF
+         DO ib_bdy=1, nb_bdy
+            SELECT CASE( TRIM(cn_tra(ib_bdy)) )
+            CASE('neumann')
+               llsend1(:) = llsend1(:) .OR. lsend_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+               llrecv1(:) = llrecv1(:) .OR. lrecv_bdyint(ib_bdy,1,:,ir)   ! possibly every direction, T points
+            CASE('orlanski','orlanski_npo')
+               llsend1(:) = llsend1(:) .OR. lsend_bdy(ib_bdy,1,:,ir)   ! possibly every direction, T points
+               llrecv1(:) = llrecv1(:) .OR. lrecv_bdy(ib_bdy,1,:,ir)   ! possibly every direction, T points
+            END SELECT
+         END DO
+         IF( ANY(llsend1) .OR. ANY(llrecv1) ) THEN   ! if need to send/recv in at least one direction
+            CALL lbc_lnk( 'trcbdy', tra, 'T',  1., kfillmode=jpfillnothing ,lsend=llsend1, lrecv=llrecv1 )
+         END IF
+         !
+      END DO   ! ir
+      !
+      IF( ln_timing )   CALL timing_stop('trc_bdy')
+      !
+   END SUBROUTINE trc_bdy
+
+
+   SUBROUTINE trc_bdy_dmp( kt )
+      !!----------------------------------------------------------------------
+      !!                 ***  SUBROUTINE trc_bdy_dmp  ***
+      !!                    
+      !! ** Purpose : Apply damping for tracers at open boundaries.
+      !!             It currently applies the damping to all tracers!!!
+      !! 
+      !!----------------------------------------------------------------------
+      INTEGER,         INTENT(in) ::   kt
+      !! 
+      INTEGER  ::   jn             ! Tracer index
+      REAL(wp) ::   zwgt           ! boundary weight
+      REAL(wp) ::   zta, zsa, ztime
+      INTEGER  ::   ib, ik, igrd   ! dummy loop indices
+      INTEGER  ::   ii, ij         ! 2D addresses
+      INTEGER  ::   ib_bdy         ! Loop index
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_bdy_dmp')
+      !
+      DO jn = 1, jptra
+         DO ib_bdy=1, nb_bdy
+            IF( trcdta_bdy(jn, ib_bdy)%dmp ) THEN
+               igrd = 1                       ! Everything is at T-points here
+               DO ib = 1, idx_bdy(ib_bdy)%nblen(igrd)
+                  ii = idx_bdy(ib_bdy)%nbi(ib,igrd)
+                  ij = idx_bdy(ib_bdy)%nbj(ib,igrd)
+                  zwgt = idx_bdy(ib_bdy)%nbd(ib,igrd)
+                  DO ik = 1, jpkm1
+                     zta = zwgt * ( trcdta_bdy(jn, ib_bdy)%trc(ib,ik) - trb(ii,ij,ik,jn) ) * tmask(ii,ij,ik)
+                     tra(ii,ij,ik,jn) = tra(ii,ij,ik,jn) + zta
+                  END DO
+               END DO
+            ENDIF
+         END DO
+      END DO
+      !
+      IF( ln_timing )   CALL timing_stop('trc_bdy_dmp')
+      !
+   END SUBROUTINE trc_bdy_dmp
+ 
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                   NO Unstruct Open Boundary Conditions
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_bdy(kt)      ! Empty routine
+      WRITE(*,*) 'trc_bdy: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_bdy
+
+   SUBROUTINE trc_bdy_dmp(kt)      ! Empty routine
+      WRITE(*,*) 'trc_bdy_dmp: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_bdy_dmp
+
+#endif
+
+   !!======================================================================
+END MODULE trcbdy
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcdta.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcdta.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcdta.F90	(revision 14097)
@@ -0,0 +1,258 @@
+MODULE trcdta
+   !!======================================================================
+   !!                     ***  MODULE  trcdta  ***
+   !! TOP :  reads passive tracer data 
+   !!=====================================================================
+   !! History :   1.0  !  2002-04  (O. Aumont)  original code
+   !!              -   !  2004-03  (C. Ethe)  module
+   !!              -   !  2005-03  (O. Aumont, A. El Moussaoui) F90
+   !!            3.4   !  2010-11  (C. Ethe, G. Madec)  use of fldread + dynamical allocation 
+   !!            3.5   !  2013-08  (M. Vichi)  generalization for other BGC models
+   !!            3.6   !  2015-03  (T. Lovato) revisit code I/O
+   !!----------------------------------------------------------------------
+#if defined key_top 
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP model 
+   !!----------------------------------------------------------------------
+   !!   trc_dta    : read and time interpolated passive tracer data
+   !!----------------------------------------------------------------------
+   USE par_trc       !  passive tracers parameters
+   USE oce_trc       !  shared variables between ocean and passive tracers
+   USE trc           !  passive tracers common variables
+   !
+   USE iom           !  I/O manager
+   USE lib_mpp       !  MPP library
+   USE fldread       !  read input fields
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_dta         ! called in trcini.F90 and trcdmp.F90
+   PUBLIC   trc_dta_ini     ! called in trcini.F90 
+
+   INTEGER  , SAVE, PUBLIC                             :: nb_trcdta   ! number of tracers to be initialised with data
+   INTEGER  , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: n_trc_index ! indice of tracer which is initialised with data
+   INTEGER  , SAVE, PUBLIC                             :: ntra        ! MAX( 1, nb_trcdta ) to avoid compilation error with bounds checking
+   REAL(wp) , SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: rf_trfac    ! multiplicative factor for tracer values
+!$AGRIF_DO_NOT_TREAT
+   TYPE(FLD), SAVE, PUBLIC, ALLOCATABLE, DIMENSION(:)  :: sf_trcdta   ! structure of input SST (file informations, fields read)
+!$AGRIF_END_DO_NOT_TREAT
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_dta_ini(ntrc)
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dta_ini  ***
+      !!                    
+      !! ** Purpose :   initialisation of passive tracer input data 
+      !! 
+      !! ** Method  : - Read namtsd namelist
+      !!              - allocates passive tracer data structure 
+      !!----------------------------------------------------------------------
+      INTEGER,INTENT(in) ::   ntrc   ! number of tracers
+      !
+      INTEGER ::   jl, jn                            ! dummy loop indices
+      INTEGER ::   ios, ierr0, ierr1, ierr2, ierr3   ! local integers
+      REAL(wp) ::   zfact
+      CHARACTER(len=100) ::   clndta, clntrc
+      !
+      CHARACTER(len=100) ::   cn_dir
+      TYPE(FLD_N), ALLOCATABLE, DIMENSION(:) :: slf_i ! array of namelist informations on the fields to read
+      TYPE(FLD_N), DIMENSION(jpmaxtrc) :: sn_trcdta
+      REAL(wp)   , DIMENSION(jpmaxtrc) :: rn_trfac    ! multiplicative factor for tracer values
+      !!
+      NAMELIST/namtrc_dta/ sn_trcdta, cn_dir, rn_trfac 
+      !!----------------------------------------------------------------------
+      !
+      IF( lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_dta_ini : Tracers Initial Conditions (IC)'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+      ENDIF
+      !
+      !  Initialisation
+      ierr0 = 0  ;  ierr1 = 0  ;  ierr2 = 0  ;  ierr3 = 0  
+      ! Compute the number of tracers to be initialised with data
+      ALLOCATE( n_trc_index(ntrc), slf_i(ntrc), STAT=ierr0 )
+      IF( ierr0 > 0 ) THEN
+         CALL ctl_stop( 'trc_dta_ini: unable to allocate n_trc_index' )   ;   RETURN
+      ENDIF
+      nb_trcdta      = 0
+      n_trc_index(:) = 0
+      DO jn = 1, ntrc
+         IF( ln_trc_ini(jn) ) THEN
+             nb_trcdta       = nb_trcdta + 1 
+             n_trc_index(jn) = nb_trcdta 
+         ENDIF
+      END DO
+      !
+      ntra = MAX( 1, nb_trcdta )   ! To avoid compilation error with bounds checking
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) '   number of passive tracers to be initialize by data :', ntra
+      ENDIF
+      !
+      REWIND( numnat_ref )              ! Namelist namtrc_dta in reference namelist : Passive tracer input data
+      READ  ( numnat_ref, namtrc_dta, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_dta_ini in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc_dta in configuration namelist : Passive tracer input data
+      READ  ( numnat_cfg, namtrc_dta, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_dta_ini in configuration namelist' )
+      IF(lwm) WRITE ( numont, namtrc_dta )
+
+      IF( lwp ) THEN
+         DO jn = 1, ntrc
+            IF( ln_trc_ini(jn) )  THEN    ! open input file only if ln_trc_ini(jn) is true
+               clndta = TRIM( sn_trcdta(jn)%clvar ) 
+               clntrc = TRIM( ctrcnm   (jn)       ) 
+               if (jn > jptra) clntrc='Dummy' ! By pass weird formats in ocean.output if ntrc > jptra
+               zfact  = rn_trfac(jn)
+               IF( clndta /=  clntrc ) THEN 
+                  CALL ctl_warn( 'trc_dta_ini: passive tracer data initialisation    ',   &
+                  &              'Input name of data file : '//TRIM(clndta)//   &
+                  &              ' differs from that of tracer : '//TRIM(clntrc)//' ')
+               ENDIF
+               WRITE(numout,*)
+               WRITE(numout,'(a, i4,3a,e11.3)') '   Read IC file for tracer number :', &
+               &            jn, ', name : ', TRIM(clndta), ', Multiplicative Scaling factor : ', zfact
+            ENDIF
+         END DO
+      ENDIF
+      !
+      IF( nb_trcdta > 0 ) THEN       !  allocate only if the number of tracer to initialise is greater than zero
+         ALLOCATE( sf_trcdta(nb_trcdta), rf_trfac(nb_trcdta), STAT=ierr1 )
+         IF( ierr1 > 0 ) THEN
+            CALL ctl_stop( 'trc_dta_ini: unable to allocate  sf_trcdta structure' )   ;   RETURN
+         ENDIF
+         !
+         DO jn = 1, ntrc
+            IF( ln_trc_ini(jn) ) THEN      ! update passive tracers arrays with input data read from file
+               jl = n_trc_index(jn)
+               slf_i(jl)    = sn_trcdta(jn)
+               rf_trfac(jl) = rn_trfac(jn)
+                                            ALLOCATE( sf_trcdta(jl)%fnow(jpi,jpj,jpk)   , STAT=ierr2 )
+               IF( sn_trcdta(jn)%ln_tint )  ALLOCATE( sf_trcdta(jl)%fdta(jpi,jpj,jpk,2) , STAT=ierr3 )
+               IF( ierr2 + ierr3 > 0 ) THEN
+                 CALL ctl_stop( 'trc_dta_ini : unable to allocate passive tracer data arrays' )   ;   RETURN
+               ENDIF
+            ENDIF
+            !   
+         ENDDO
+         !                         ! fill sf_trcdta with slf_i and control print
+         CALL fld_fill( sf_trcdta, slf_i, cn_dir, 'trc_dta_ini', 'Passive tracer data', 'namtrc' )
+         !
+      ENDIF
+      !
+      DEALLOCATE( slf_i )          ! deallocate local field structure
+      !
+   END SUBROUTINE trc_dta_ini
+
+
+   SUBROUTINE trc_dta( kt, sf_trcdta, ptrcfac, ptrcdta)
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_dta  ***
+      !!                    
+      !! ** Purpose :   provides passive tracer data at kt
+      !! 
+      !! ** Method  : - call fldread routine
+      !!              - s- or mixed z-s coordinate: vertical interpolation on model mesh
+      !!              - ln_trcdmp=F: deallocates the data structure as they are not used
+      !!
+      !! ** Action  :   sf_trcdta   passive tracer data on meld mesh and interpolated at time-step kt
+      !!----------------------------------------------------------------------
+      INTEGER                          , INTENT(in   )   ::   kt         ! ocean time-step
+      TYPE(FLD), DIMENSION(1)          , INTENT(inout)   ::   sf_trcdta  ! array of information on the field to read
+      REAL(wp)                         , INTENT(in   )   ::   ptrcfac    ! multiplication factor
+      REAL(wp),  DIMENSION(jpi,jpj,jpk), INTENT(inout  ) ::   ptrcdta    ! 3D data array
+      !
+      INTEGER ::   ji, jj, jk, jl, jkk, ik    ! dummy loop indices
+      REAL(wp)::   zl, zi
+      REAL(wp), DIMENSION(jpk) ::  ztp                ! 1D workspace
+      CHARACTER(len=100) :: clndta
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_dta')
+      !
+      IF( nb_trcdta > 0 ) THEN
+         !
+         ! read data at kt time step
+         CALL fld_read( kt, 1, sf_trcdta )
+         ptrcdta(:,:,:) = sf_trcdta(1)%fnow(:,:,:) * tmask(:,:,:)
+         ! 
+         IF( ln_sco ) THEN                !== s- or mixed s-zps-coordinate  ==!
+            !
+            IF( kt == nit000 .AND. lwp )THEN
+               WRITE(numout,*)
+               WRITE(numout,*) 'trc_dta: interpolates passive tracer data onto the s- or mixed s-z-coordinate mesh'
+            ENDIF
+            DO jj = 1, jpj                         ! vertical interpolation of T & S
+               DO ji = 1, jpi
+                  DO jk = 1, jpk                        ! determines the intepolated T-S profiles at each (i,j) points
+                     zl = gdept_n(ji,jj,jk)
+                     IF(     zl < gdept_1d(1  ) ) THEN         ! above the first level of data
+                        ztp(jk) = ptrcdta(ji,jj,1)
+                     ELSEIF( zl > gdept_1d(jpk) ) THEN         ! below the last level of data
+                        ztp(jk) = ptrcdta(ji,jj,jpkm1)
+                     ELSE                                      ! inbetween : vertical interpolation between jkk & jkk+1
+                        DO jkk = 1, jpkm1                                  ! when  gdept(jkk) < zl < gdept(jkk+1)
+                           IF( (zl-gdept_1d(jkk)) * (zl-gdept_1d(jkk+1)) <= 0._wp ) THEN
+                              zi = ( zl - gdept_1d(jkk) ) / (gdept_1d(jkk+1)-gdept_1d(jkk))
+                              ztp(jk) = ptrcdta(ji,jj,jkk) + ( ptrcdta(ji,jj,jkk+1) - ptrcdta(ji,jj,jkk) ) * zi
+                           ENDIF
+                        END DO
+                     ENDIF
+                  END DO
+                  DO jk = 1, jpkm1
+                     ptrcdta(ji,jj,jk) = ztp(jk) * tmask(ji,jj,jk)     ! mask required for mixed zps-s-coord
+                  END DO
+                  ptrcdta(ji,jj,jpk) = 0._wp
+                END DO
+            END DO
+            ! 
+         ELSE                                !==   z- or zps- coordinate   ==!
+            ! zps-coordinate (partial steps) interpolation at the last ocean level
+!            IF( ln_zps ) THEN
+!               DO jj = 1, jpj
+!                  DO ji = 1, jpi
+!                     ik = mbkt(ji,jj) 
+!                     IF( ik > 1 ) THEN
+!                        zl = ( gdept_1d(ik) - gdept_0(ji,jj,ik) ) / ( gdept_1d(ik) - gdept_1d(ik-1) )
+!                        ptrcdta(ji,jj,ik) = (1.-zl) * ptrcdta(ji,jj,ik) + zl * ptrcdta(ji,jj,ik-1)
+!                     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) )
+!                        ptrcdta(ji,jj,ik) = (1.-zl) * ptrcdta(ji,jj,ik) + zl * ptrcdta(ji,jj,ik+1)
+!                     ENDIF
+!                  END DO
+!              END DO
+!            ENDIF
+            !
+         ENDIF
+         !
+         ! Scale by multiplicative factor
+         ptrcdta(:,:,:) = ptrcdta(:,:,:) * ptrcfac
+         !
+      ENDIF
+      !
+      IF( ln_timing )  CALL timing_stop('trc_dta')
+      !
+   END SUBROUTINE trc_dta
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Dummy module                              NO 3D passive tracer data
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_dta( kt, sf_trcdta, ptrcfac, ptrcdta)        ! Empty routine
+      WRITE(*,*) 'trc_dta: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_dta
+#endif
+
+   !!======================================================================
+END MODULE trcdta
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcice.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcice.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcice.F90	(revision 14097)
@@ -0,0 +1,121 @@
+MODULE trcice
+   !!======================================================================
+   !!                         ***  MODULE trcice  ***
+   !! TOP :   Manage the communication between TOP and sea ice
+   !!======================================================================
+   !! History :  3.5  ! 2013    (M. Vancoppenolle, O. Aumont, G. Madec), original code
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_ice       :  Call the appropriate sea ice tracer subroutine
+   !!----------------------------------------------------------------------
+   USE oce_trc        ! shared variables between ocean and passive tracers
+   USE trc            ! passive tracers common variables
+   USE trcice_cfc     ! CFC      initialisation
+   USE trcice_pisces  ! PISCES   initialisation
+   USE trcice_c14     ! C14 bomb initialisation
+   USE trcice_age     ! AGE      initialisation
+   USE trcice_my_trc  ! MY_TRC   initialisation
+   
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   trc_ice_ini   ! called by trc_nam
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE trc_ice_ini
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ice_ini ***
+      !!
+      !! ** Purpose :   Initialization of the ice module for tracers
+      !!
+      !! ** Method  : - 
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_ice_ini : Initialize sea ice tracer boundary condition'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !
+      CALL trc_nam_ice
+      !
+      trc_i(:,:,:) = 0._wp   ! by default
+      trc_o(:,:,:) = 0._wp   ! by default
+      !
+      IF ( nn_ice_tr == 1 ) THEN
+         IF( ln_pisces  )    CALL trc_ice_ini_pisces       ! PISCES  bio-model
+         IF( ll_cfc     )    CALL trc_ice_ini_cfc          ! CFC     tracers
+         IF( ln_c14     )    CALL trc_ice_ini_c14          ! C14     tracer
+         IF( ln_age     )    CALL trc_ice_ini_age          ! AGE     tracer
+         IF( ln_my_trc  )    CALL trc_ice_ini_my_trc       ! MY_TRC  tracers
+      ENDIF
+      !
+   END SUBROUTINE trc_ice_ini
+
+
+   SUBROUTINE trc_nam_ice
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam_ice ***
+      !!
+      !! ** Purpose :   Read the namelist for the ice effect on tracers
+      !!
+      !! ** Method  : -
+      !!---------------------------------------------------------------------
+      INTEGER :: jn      ! dummy loop indices
+      INTEGER :: ios, ierr     ! Local integer output status for namelist read
+      !
+      TYPE(TRC_I_NML), DIMENSION(jpmaxtrc) ::   sn_tri_tracer
+      !!
+      NAMELIST/namtrc_ice/ nn_ice_tr, sn_tri_tracer
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_nam_ice : Read the namelist for trc_ice'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+      ENDIF
+      !
+      REWIND( numnat_ref )              ! Namelist namtrc_ice in reference namelist : Passive tracer input data
+      READ  ( numnat_ref, namtrc_ice, IOSTAT = ios, ERR = 901)
+ 901  IF( ios /= 0 )   CALL ctl_nam ( ios , ' namtrc_ice in reference namelist ' )
+      REWIND( numnat_cfg )              ! Namelist namtrc_ice in configuration namelist : Pisces external sources of nutrients
+      READ  ( numnat_cfg, namtrc_ice, IOSTAT = ios, ERR = 902 )
+ 902  IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_ice in configuration namelist' )
+
+      IF( lwp ) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) '   Namelist : namtrc_ice'
+         WRITE(numout,*) '      Sea ice tracers option (nn_ice_tr) : ', nn_ice_tr
+      ENDIF
+      !
+      ! Assign namelist stuff
+      DO jn = 1, jptra
+         trc_ice_ratio (jn) = sn_tri_tracer(jn)%trc_ratio
+         trc_ice_prescr(jn) = sn_tri_tracer(jn)%trc_prescr
+         cn_trc_o      (jn) = sn_tri_tracer(jn)%ctrc_o
+      END DO
+      !
+   END SUBROUTINE trc_nam_ice
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_ice_ini                   ! Dummy routine   
+   END SUBROUTINE trc_ice_ini
+   SUBROUTINE trc_nam_ice
+   END SUBROUTINE trc_nam_ice
+#endif
+
+   !!======================================================================
+END MODULE trcice
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcini.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcini.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcini.F90	(revision 14097)
@@ -0,0 +1,293 @@
+MODULE trcini
+   !!======================================================================
+   !!                         ***  MODULE trcini  ***
+   !! TOP :   Manage the passive tracer initialization
+   !!======================================================================
+   !! History :   -   ! 1991-03 (O. Marti)  original code
+   !!            1.0  ! 2005-03 (O. Aumont, A. El Moussaoui) F90
+   !!            2.0  ! 2005-10 (C. Ethe, G. Madec) revised architecture
+   !!            4.0  ! 2011-01 (A. R. Porter, STFC Daresbury) dynamical allocation
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_init  :   Initialization for passive tracer
+   !!   top_alloc :   allocate the TOP arrays
+   !!----------------------------------------------------------------------
+   USE oce_trc         ! shared variables between ocean and passive tracers
+   USE trc             ! passive tracers common variables
+   USE trcnam          ! Namelist read
+   USE daymod          ! calendar manager
+   USE prtctl_trc      ! Print control passive tracers (prt_ctl_trc_init routine)
+   USE trcsub          ! variables to substep passive tracers
+   USE trcrst
+   USE lib_mpp         ! distribued memory computing library
+   USE trcice          ! tracers in sea ice
+   USE trcbc,   only : trc_bc_ini ! generalized Boundary Conditions
+ 
+   IMPLICIT NONE
+   PRIVATE
+   
+   PUBLIC   trc_init   ! called by opa
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE trc_init
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_init  ***
+      !!
+      !! ** Purpose :   Initialization of the passive tracer fields 
+      !!
+      !! ** Method  : - read namelist
+      !!              - control the consistancy 
+      !!              - compute specific initialisations
+      !!              - set initial tracer fields (either read restart 
+      !!                or read data or analytical formulation
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_init')
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_init : initial set up of the passive tracers'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~'
+      !
+      CALL trc_nam       ! read passive tracers namelists
+      CALL top_alloc()   ! allocate TOP arrays
+      !
+      IF(.NOT.ln_trcdta )   ln_trc_ini(:) = .FALSE.
+      !
+      IF(lwp) WRITE(numout,*)
+      IF( ln_rsttr .AND. .NOT. l_offline ) CALL trc_rst_cal( nit000, 'READ' )   ! calendar
+      IF(lwp) WRITE(numout,*)
+      !
+      CALL trc_ini_sms   ! SMS
+      CALL trc_ini_trp   ! passive tracers transport
+      CALL trc_ice_ini   ! Tracers in sea ice
+      !
+      IF( lwm .AND. sn_cfctl%l_trcstat ) THEN
+         CALL ctl_opn( numstr, 'tracer.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp , narea )
+      ENDIF
+      !
+      CALL trc_ini_state  !  passive tracers initialisation : from a restart or from clim
+      IF( nn_dttrc /= 1 ) &
+      CALL trc_sub_ini    ! Initialize variables for substepping passive tracers
+      !
+      CALL trc_ini_inv   ! Inventories
+      !
+      IF( ln_timing )   CALL timing_stop('trc_init')
+      !
+   END SUBROUTINE trc_init
+
+
+   SUBROUTINE trc_ini_inv
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ini_stat  ***
+      !! ** Purpose :      passive tracers inventories at initialsation phase
+      !!----------------------------------------------------------------------
+      INTEGER ::  jk, jn    ! dummy loop indices
+      CHARACTER (len=25) :: charout
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_ini_inv : initial passive tracers inventories'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !                          ! masked grid volume
+      DO jk = 1, jpk
+         cvol(:,:,jk) = e1e2t(:,:) * e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+      !                          ! total volume of the ocean 
+      areatot = glob_sum( 'trcini', cvol(:,:,:) )
+      !
+      trai(:) = 0._wp            ! initial content of all tracers
+      DO jn = 1, jptra
+         trai(jn) = trai(jn) + glob_sum( 'trcini', trn(:,:,:,jn) * cvol(:,:,:)   )
+      END DO
+
+      IF(lwp) THEN               ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   ==>>>   Total number of passive tracer jptra = ', jptra
+         WRITE(numout,*) '           Total volume of ocean                = ', areatot
+         WRITE(numout,*) '           Total inital content of all tracers '
+         WRITE(numout,*)
+         DO jn = 1, jptra
+            WRITE(numout,9000) jn, TRIM( ctrcnm(jn) ), trai(jn)
+         ENDDO
+         WRITE(numout,*)
+      ENDIF
+      IF(lwp) WRITE(numout,*)
+      IF(ln_ctl) THEN            ! print mean trends (used for debugging)
+         CALL prt_ctl_trc_init
+         WRITE(charout, FMT="('ini ')")
+         CALL prt_ctl_trc_info( charout )
+         CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
+      ENDIF
+9000  FORMAT('      tracer nb : ',i2,'      name :',a10,'      initial content :',e18.10)
+      !
+   END SUBROUTINE trc_ini_inv
+
+
+   SUBROUTINE trc_ini_sms
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ini_sms  ***
+      !! ** Purpose :   SMS initialisation
+      !!----------------------------------------------------------------------
+      USE trcini_pisces  ! PISCES   initialisation
+      USE trcini_cfc     ! CFC      initialisation
+      USE trcini_c14     ! C14  initialisation
+      USE trcini_age     ! age initialisation
+      USE trcini_my_trc  ! MY_TRC   initialisation
+      !
+      INTEGER :: jn
+      !!----------------------------------------------------------------------
+      !
+      ! Pass sn_tracer fields to specialized arrays 
+      DO jn = 1, jp_bgc
+         ctrcnm    (jn) = TRIM( sn_tracer(jn)%clsname )
+         ctrcln    (jn) = TRIM( sn_tracer(jn)%cllname )
+         ctrcun    (jn) = TRIM( sn_tracer(jn)%clunit  )
+         ln_trc_ini(jn) =       sn_tracer(jn)%llinit
+         ln_trc_sbc(jn) =       sn_tracer(jn)%llsbc
+         ln_trc_cbc(jn) =       sn_tracer(jn)%llcbc
+         ln_trc_obc(jn) =       sn_tracer(jn)%llobc
+      END DO
+      !    
+      IF( ln_pisces      )   CALL trc_ini_pisces     !  PISCES model
+      IF( ln_my_trc      )   CALL trc_ini_my_trc     !  MY_TRC model
+      IF( ll_cfc         )   CALL trc_ini_cfc        !  CFC's
+      IF( ln_c14         )   CALL trc_ini_c14        !  C14 model
+      IF( ln_age         )   CALL trc_ini_age        !  AGE
+      !
+      IF(lwp) THEN                   ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'trc_init_sms : Summary for selected passive tracers'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '    ID     NAME     INI  SBC  CBC  OBC'
+         DO jn = 1, jptra
+            WRITE(numout,9001) jn, TRIM(ctrcnm(jn)), ln_trc_ini(jn), ln_trc_sbc(jn),ln_trc_cbc(jn),ln_trc_obc(jn)
+         END DO
+      ENDIF
+9001  FORMAT(3x,i3,1x,a10,3x,l2,3x,l2,3x,l2,3x,l2)
+      !
+   END SUBROUTINE trc_ini_sms
+
+
+   SUBROUTINE trc_ini_trp
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ini_trp  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!----------------------------------------------------------------------
+      USE trcdmp , ONLY:  trc_dmp_ini
+      USE trcadv , ONLY:  trc_adv_ini
+      USE trcldf , ONLY:  trc_ldf_ini
+      USE trcrad , ONLY:  trc_rad_ini
+      USE trcsink, ONLY:  trc_sink_ini
+      !
+      INTEGER :: ierr
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_trcdmp )  CALL  trc_dmp_ini          ! damping
+                       CALL  trc_adv_ini          ! advection
+                       CALL  trc_ldf_ini          ! lateral diffusion
+                       !                          ! vertical diffusion: always implicit time stepping scheme
+                       CALL  trc_rad_ini          ! positivity of passive tracers 
+                       CALL  trc_sink_ini         ! Vertical sedimentation of particles
+      !
+   END SUBROUTINE trc_ini_trp
+
+
+   SUBROUTINE trc_ini_state
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_ini_state ***
+      !! ** Purpose :          Initialisation of passive tracer concentration 
+      !!----------------------------------------------------------------------
+      USE zpshde          ! partial step: hor. derivative   (zps_hde routine)
+      USE trcrst          ! passive tracers restart
+      USE trcdta          ! initialisation from files
+      !
+      INTEGER :: jn, jl   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_trcdta )   CALL trc_dta_ini( jptra )      ! set initial tracers values
+      !
+      CALL trc_bc_ini ( jptra )      ! set tracers Boundary Conditions
+      !
+      !
+      IF( ln_rsttr ) THEN              ! restart from a file
+        !
+        CALL trc_rst_read
+        !
+      ELSE                             ! Initialisation of tracer from a file that may also be used for damping
+!!gm BUG ?   if damping and restart, what's happening ?
+        IF( ln_trcdta .AND. nb_trcdta > 0 ) THEN
+            ! update passive tracers arrays with input data read from file
+            DO jn = 1, jptra
+               IF( ln_trc_ini(jn) ) THEN
+                  jl = n_trc_index(jn) 
+                  CALL trc_dta( nit000, sf_trcdta(jl), rf_trfac(jl), trn(:,:,:,jn) )
+                  !
+                  ! deallocate data structure if data are not used for damping
+                  IF( .NOT.ln_trcdmp .AND. .NOT.ln_trcdmp_clo ) THEN
+                     IF(lwp) WRITE(numout,*) 'trc_ini_state: deallocate data arrays as they are only used to initialize the run'
+                                                  DEALLOCATE( sf_trcdta(jl)%fnow )
+                     IF( sf_trcdta(jl)%ln_tint )  DEALLOCATE( sf_trcdta(jl)%fdta )
+                     !
+                  ENDIF
+               ENDIF
+            END DO
+            !
+        ENDIF
+        !
+        trb(:,:,:,:) = trn(:,:,:,:)
+        ! 
+      ENDIF
+      !
+      tra(:,:,:,:) = 0._wp
+      !                                                         ! Partial top/bottom cell: GRADh(trn)
+   END SUBROUTINE trc_ini_state
+
+
+   SUBROUTINE top_alloc
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE top_alloc  ***
+      !!
+      !! ** Purpose :   Allocate all the dynamic arrays of the OPA modules
+      !!----------------------------------------------------------------------
+      USE trc           , ONLY:   trc_alloc
+      USE trdtrc_oce    , ONLY:   trd_trc_oce_alloc
+#if defined key_trdmxl_trc 
+      USE trdmxl_trc    , ONLY:   trd_mxl_trc_alloc
+#endif
+      !
+      INTEGER ::   ierr   ! local integer
+      !!----------------------------------------------------------------------
+      !
+      ierr =        trc_alloc()
+      ierr = ierr + trd_trc_oce_alloc()
+#if defined key_trdmxl_trc 
+      ierr = ierr + trd_mxl_trc_alloc()
+#endif
+      !
+      CALL mpp_sum( 'trcini', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'top_alloc : unable to allocate standard ocean arrays' )
+      !
+   END SUBROUTINE top_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_init                      ! Dummy routine   
+   END SUBROUTINE trc_init
+#endif
+
+   !!======================================================================
+END MODULE trcini
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcnam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcnam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcnam.F90	(revision 14097)
@@ -0,0 +1,298 @@
+MODULE trcnam
+   !!======================================================================
+   !!                       ***  MODULE trcnam  ***
+   !! TOP :   Read and print options for the passive tracer run (namelist)
+   !!======================================================================
+   !! History :    -   !  1996-11  (M.A. Foujols, M. Levy)  original code
+   !!              -   !  1998-04  (M.A Foujols, L. Bopp) ahtrb0 for isopycnal mixing
+   !!              -   !  1999-10  (M.A. Foujols, M. Levy) separation of sms
+   !!              -   !  2000-07  (A. Estublier) add TVD and MUSCL : Tests on ndttrc
+   !!              -   !  2000-11  (M.A Foujols, E Kestenare) trcrat, ahtrc0 and aeivtr0
+   !!              -   !  2001-01 (E Kestenare) suppress ndttrc=1 for CEN2 and TVD schemes
+   !!             1.0  !  2005-03 (O. Aumont, A. El Moussaoui) F90
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_nam    :  Read and print options for the passive tracer run (namelist)
+   !!----------------------------------------------------------------------
+   USE oce_trc     ! shared variables between ocean and passive tracers
+   USE trc         ! passive tracers common variables
+   USE trd_oce     !       
+   USE trdtrc_oce  !
+   USE iom         ! I/O manager
+#if defined key_mpp_mpi
+   USE lib_mpp, ONLY: ncom_dttrc
+#endif
+
+   IMPLICIT NONE
+   PRIVATE 
+
+   PUBLIC   trc_nam_run  ! called in trcini
+   PUBLIC   trc_nam      ! called in trcini
+
+   TYPE(PTRACER), DIMENSION(jpmaxtrc), PUBLIC  :: sn_tracer  !: type of tracer for saving if not key_iomput
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_nam
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam  ***
+      !!
+      !! ** Purpose :   READ and PRINT options for the passive tracer run (namelist) 
+      !!
+      !! ** Method  : - read passive tracer namelist 
+      !!              - read namelist of each defined SMS model
+      !!                ( (PISCES, CFC, MY_TRC )
+      !!---------------------------------------------------------------------
+      INTEGER  ::   jn   ! dummy loop indice
+      !!---------------------------------------------------------------------
+      !
+      IF( .NOT.l_offline )   CALL trc_nam_run     ! Parameters of the run                                  
+      !               
+      CALL trc_nam_trc                            ! passive tracer informations
+      !                                        
+      IF( ln_rsttr                     )   ln_trcdta = .FALSE.   ! restart : no need of clim data
+      !
+      IF( ln_trcdmp .OR. ln_trcdmp_clo )   ln_trcdta = .TRUE.    ! damping : need to have clim data
+      !
+      !
+      IF(lwp) THEN                   ! control print
+         IF( ln_rsttr ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   Read a restart file for passive tracer : ', TRIM( cn_trcrst_in )
+         ENDIF
+         IF( ln_trcdta .AND. .NOT.ln_rsttr ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   Some of the passive tracers are initialised from climatologies '
+         ENDIF
+         IF( .NOT.ln_trcdta ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '   ==>>>   All the passive tracers are initialised with constant values '
+         ENDIF
+      ENDIF
+      !
+      rdttrc = rdt * FLOAT( nn_dttrc )          ! passive tracer time-step      
+      ! 
+      IF(lwp) THEN                              ! control print
+        WRITE(numout,*) 
+        WRITE(numout,*) '   ==>>>   Passive Tracer  time step    rdttrc = nn_dttrc*rdt = ', rdttrc
+      ENDIF
+      !
+      IF( l_trdtrc )        CALL trc_nam_trd    ! Passive tracer trends
+      !
+   END SUBROUTINE trc_nam
+
+
+   SUBROUTINE trc_nam_run
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam  ***
+      !!
+      !! ** Purpose :   read options for the passive tracer run (namelist) 
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer
+      !!
+      NAMELIST/namtrc_run/ nn_dttrc, ln_rsttr, nn_rsttr, ln_top_euler, &
+        &                  cn_trcrst_indir, cn_trcrst_outdir, cn_trcrst_in, cn_trcrst_out
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_nam_run : read the passive tracer namelists'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      CALL ctl_opn( numnat_ref, 'namelist_top_ref'   , 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      CALL ctl_opn( numnat_cfg, 'namelist_top_cfg'   , 'OLD'    , 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+      IF(lwm) CALL ctl_opn( numont, 'output.namelist.top', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE., 1 )
+      !
+      REWIND( numnat_ref )              ! Namelist namtrc in reference namelist : Passive tracer variables
+      READ  ( numnat_ref, namtrc_run, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc in configuration namelist : Passive tracer variables
+      READ  ( numnat_cfg, namtrc_run, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc in configuration namelist' )
+      IF(lwm) WRITE( numont, namtrc_run )
+
+      nittrc000 = nit000 + nn_dttrc - 1      ! first time step of tracer model
+
+      IF(lwp) THEN                   ! control print
+         WRITE(numout,*) '   Namelist : namtrc_run'
+         WRITE(numout,*) '      time step freq. for passive tracer           nn_dttrc      = ', nn_dttrc
+         WRITE(numout,*) '      restart  for passive tracer                  ln_rsttr      = ', ln_rsttr
+         WRITE(numout,*) '      control of time step for passive tracer      nn_rsttr      = ', nn_rsttr
+         WRITE(numout,*) '      first time step for pass. trac.              nittrc000     = ', nittrc000
+         WRITE(numout,*) '      Use euler integration for TRC (y/n)          ln_top_euler  = ', ln_top_euler
+      ENDIF
+      !
+#if defined key_mpp_mpi
+      ncom_dttrc = nn_dttrc    ! make nn_fsbc available for lib_mpp
+#endif
+      !
+   END SUBROUTINE trc_nam_run
+
+
+   SUBROUTINE trc_nam_trc
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam  ***
+      !!
+      !! ** Purpose :   read options for the passive tracer run (namelist) 
+      !!
+      !!---------------------------------------------------------------------
+      INTEGER ::   ios, ierr, icfc       ! Local integer
+      !!
+      NAMELIST/namtrc/jp_bgc, ln_pisces, ln_my_trc, ln_age, ln_cfc11, ln_cfc12, ln_sf6, ln_c14, &
+         &            sn_tracer, ln_trcdta, ln_trcdmp, ln_trcdmp_clo, jp_dia3d, jp_dia2d
+      !!---------------------------------------------------------------------
+      ! Dummy settings to fill tracers data structure
+      !                  !   name   !   title   !   unit   !   init  !   sbc   !   cbc   !   obc  !
+      sn_tracer = PTRACER( 'NONAME' , 'NOTITLE' , 'NOUNIT' , .false. , .false. , .false. , .false.)
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_nam_trc : read the passive tracer namelists'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+
+      REWIND( numnat_ref )              ! Namelist namtrc in reference namelist : Passive tracer variables
+      READ  ( numnat_ref, namtrc, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc in configuration namelist : Passive tracer variables
+      READ  ( numnat_cfg, namtrc, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc in configuration namelist' )
+      IF(lwm) WRITE( numont, namtrc )
+
+      ! Control settings
+      IF( ln_pisces .AND. ln_my_trc )   CALL ctl_stop( 'Choose only ONE BGC model - PISCES or MY_TRC' )
+      IF( .NOT. ln_pisces .AND. .NOT. ln_my_trc )   jp_bgc = 0
+      ll_cfc = ln_cfc11 .OR. ln_cfc12 .OR. ln_sf6
+      !
+      jptra       =  0
+      jp_pisces   =  0    ;   jp_pcs0  =  0    ;   jp_pcs1  = 0
+      jp_my_trc   =  0    ;   jp_myt0  =  0    ;   jp_myt1  = 0
+      jp_cfc      =  0    ;   jp_cfc0  =  0    ;   jp_cfc1  = 0
+      jp_age      =  0    ;   jp_c14   =  0
+      !
+      IF( ln_pisces )  THEN
+         jp_pisces = jp_bgc
+         jp_pcs0   = 1
+         jp_pcs1   = jp_pisces
+      ENDIF
+      IF( ln_my_trc )  THEN
+          jp_my_trc = jp_bgc
+          jp_myt0   = 1
+          jp_myt1   = jp_my_trc
+      ENDIF
+      !
+      jptra  = jp_bgc
+      !
+      IF( ln_age )    THEN
+         jptra     = jptra + 1
+         jp_age    = jptra
+      ENDIF
+      IF( ln_cfc11 )  jp_cfc = jp_cfc + 1
+      IF( ln_cfc12 )  jp_cfc = jp_cfc + 1
+      IF( ln_sf6   )  jp_cfc = jp_cfc + 1
+      IF( ll_cfc )    THEN
+          jptra     = jptra + jp_cfc
+          jp_cfc0   = jptra - jp_cfc + 1
+          jp_cfc1   = jptra
+      ENDIF
+      IF( ln_c14 )    THEN
+           jptra     = jptra + 1
+           jp_c14    = jptra
+      ENDIF
+      !
+      IF( jptra == 0 )   CALL ctl_stop( 'All TOP tracers disabled: change namtrc setting or check if key_top is active' )
+      !
+      IF(lwp) THEN                   ! control print
+         WRITE(numout,*) '   Namelist : namtrc'
+         WRITE(numout,*) '      Total number of passive tracers              jptra         = ', jptra
+         WRITE(numout,*) '      Total number of BGC tracers                  jp_bgc        = ', jp_bgc
+         WRITE(numout,*) '      Simulating PISCES model                      ln_pisces     = ', ln_pisces
+         WRITE(numout,*) '      Simulating MY_TRC  model                     ln_my_trc     = ', ln_my_trc
+         WRITE(numout,*) '      Simulating water mass age                    ln_age        = ', ln_age
+         WRITE(numout,*) '      Simulating CFC11 passive tracer              ln_cfc11      = ', ln_cfc11
+         WRITE(numout,*) '      Simulating CFC12 passive tracer              ln_cfc12      = ', ln_cfc12
+         WRITE(numout,*) '      Simulating SF6 passive tracer                ln_sf6        = ', ln_sf6
+         WRITE(numout,*) '      Total number of CFCs tracers                 jp_cfc        = ', jp_cfc
+         WRITE(numout,*) '      Simulating C14   passive tracer              ln_c14        = ', ln_c14
+         WRITE(numout,*) '      Read inputs data from file (y/n)             ln_trcdta     = ', ln_trcdta
+         WRITE(numout,*) '      Damping of passive tracer (y/n)              ln_trcdmp     = ', ln_trcdmp
+         WRITE(numout,*) '      Restoring of tracer on closed seas           ln_trcdmp_clo = ', ln_trcdmp_clo
+      ENDIF
+      !
+      IF( ll_cfc .OR. ln_c14 ) THEN
+        !                             ! Open namelist files
+        CALL ctl_opn( numtrc_ref, 'namelist_trc_ref'   ,     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+        CALL ctl_opn( numtrc_cfg, 'namelist_trc_cfg'   ,     'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+        IF(lwm) CALL ctl_opn( numonr, 'output.namelist.trc', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL', -1, numout, .FALSE. )
+        !
+      ENDIF
+      !
+   END SUBROUTINE trc_nam_trc
+
+
+   SUBROUTINE trc_nam_trd
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_nam_dia  ***
+      !!
+      !! ** Purpose :   read options for the passive tracer diagnostics
+      !!
+      !! ** Method  : - read passive tracer namelist 
+      !!              - read namelist of each defined SMS model
+      !!                ( (PISCES, CFC, MY_TRC )
+      !!---------------------------------------------------------------------
+#if defined key_trdmxl_trc  || defined key_trdtrc
+      INTEGER  ::   ios, ierr                 ! Local integer
+      !!
+      NAMELIST/namtrc_trd/ nn_trd_trc, nn_ctls_trc, rn_ucf_trc, &
+         &                ln_trdmxl_trc_restart, ln_trdmxl_trc_instant, &
+         &                cn_trdrst_trc_in, cn_trdrst_trc_out, ln_trdtrc
+      !!---------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_nam_trd : read the passive tracer diagnostics options'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      ALLOCATE( ln_trdtrc(jptra) ) 
+      !
+      REWIND( numnat_ref )              ! Namelist namtrc_trd in reference namelist : Passive tracer trends
+      READ  ( numnat_ref, namtrc_trd, IOSTAT = ios, ERR = 905)
+905   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namtrc_trd in reference namelist' )
+      REWIND( numnat_cfg )              ! Namelist namtrc_trd in configuration namelist : Passive tracer trends
+      READ  ( numnat_cfg, namtrc_trd, IOSTAT = ios, ERR = 906 )
+906   IF( ios >  0 )   CALL ctl_nam ( ios , 'namtrc_trd in configuration namelist' )
+      IF(lwm) WRITE( numont, namtrc_trd )
+
+      IF(lwp) THEN
+         WRITE(numout,*) '   Namelist : namtrc_trd                    '
+         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_trdmxl_trc_restart  = ', ln_trdmxl_trc_restart
+         WRITE(numout,*) '      instantantaneous or mean trends   ln_trdmxl_trc_instant  = ', ln_trdmxl_trc_instant
+         WRITE(numout,*) '      unit conversion factor            rn_ucf_trc             = ', rn_ucf_trc
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) WRITE(numout,*) '      compute ML trends for tracer number :', jn
+         END DO
+      ENDIF
+#endif
+      !
+   END SUBROUTINE trc_nam_trd
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_nam                      ! Empty routine   
+   END SUBROUTINE trc_nam
+   SUBROUTINE trc_nam_run                      ! Empty routine   
+   END SUBROUTINE trc_nam_run
+#endif
+
+   !!======================================================================
+END MODULE trcnam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcrst.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcrst.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcrst.F90	(revision 14097)
@@ -0,0 +1,358 @@
+MODULE trcrst
+   !!======================================================================
+   !!                         ***  MODULE trcrst  ***
+   !! TOP :   Manage the passive tracer restart
+   !!======================================================================
+   !! History :    -   !  1991-03  ()  original code
+   !!             1.0  !  2005-03 (O. Aumont, A. El Moussaoui) F90
+   !!              -   !  2005-10 (C. Ethe) print control
+   !!             2.0  !  2005-10 (C. Ethe, G. Madec) revised architecture
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   trc_rst        : Restart for passive tracer
+   !!   trc_rst_opn    : open  restart file
+   !!   trc_rst_read   : read  restart file
+   !!   trc_rst_wri    : write restart file
+   !!----------------------------------------------------------------------
+   USE oce_trc
+   USE trc
+   USE iom
+   USE daymod
+   USE lib_mpp
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_rst_opn       ! called by ???
+   PUBLIC   trc_rst_read      ! called by ???
+   PUBLIC   trc_rst_wri       ! called by ???
+   PUBLIC   trc_rst_cal
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+   
+   SUBROUTINE trc_rst_opn( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_opn  ***
+      !!
+      !! ** purpose  :   output of sea-trc variable in a netcdf file
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt       ! number of iteration
+      !
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step define as a character
+      CHARACTER(LEN=50)   ::   clname   ! trc output restart file name
+      CHARACTER(LEN=256)  ::   clpath   ! full path to ocean output restart file
+      !!----------------------------------------------------------------------
+      !
+      IF( l_offline ) THEN
+         IF( kt == nittrc000 ) THEN
+            lrst_trc = .FALSE.
+            IF( ln_rst_list ) THEN
+               nrst_lst = 1
+               nitrst = nn_stocklist( nrst_lst )
+            ELSE
+               nitrst = nitend
+            ENDIF
+         ENDIF
+
+         IF( .NOT. ln_rst_list .AND. MOD( kt - 1, nn_stock ) == 0 ) THEN
+            ! we use kt - 1 and not kt - nittrc000 to keep the same periodicity from the beginning of the experiment
+            nitrst = kt + nn_stock - 1                  ! define the next value of nitrst for restart writing
+            IF( nitrst > nitend )   nitrst = nitend   ! make sure we write a restart at the end of the run
+         ENDIF
+      ELSE
+         IF( kt == nittrc000 ) lrst_trc = .FALSE.
+      ENDIF
+
+      IF( .NOT. ln_rst_list .AND. nn_stock == -1 )   RETURN   ! we will never do any restart
+
+      ! to get better performances with NetCDF format:
+      ! we open and define the tracer restart file one tracer time step before writing the data (-> at nitrst - 2*nn_dttrc + 1)
+      ! except if we write tracer restart files every tracer time step or if a tracer restart file was writen at nitend - 2*nn_dttrc + 1
+      IF( kt == nitrst - 2*nn_dttrc .OR. nn_stock == nn_dttrc .OR. ( kt == nitend - nn_dttrc .AND. .NOT. lrst_trc ) ) THEN
+         ! beware of the format used to write kt (default is i8.8, that should be large enough)
+         IF( nitrst > 1.0e9 ) THEN   ;   WRITE(clkt,*       ) nitrst
+         ELSE                        ;   WRITE(clkt,'(i8.8)') nitrst
+         ENDIF
+         ! create the file
+         IF(lwp) WRITE(numout,*)
+         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_trcrst_out)
+         clpath = TRIM(cn_trcrst_outdir)
+         IF( clpath(LEN_TRIM(clpath):) /= '/' ) clpath = TRIM(clpath) // '/'
+         IF(lwp) WRITE(numout,*) &
+             '             open trc restart.output NetCDF file: ',TRIM(clpath)//clname
+         CALL iom_open( TRIM(clpath)//TRIM(clname), numrtw, ldwrt = .TRUE. )
+         lrst_trc = .TRUE.
+      ENDIF
+      !
+   END SUBROUTINE trc_rst_opn
+
+   SUBROUTINE trc_rst_read
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_opn  ***
+      !!
+      !! ** purpose  :   read passive tracer fields in restart files
+      !!----------------------------------------------------------------------
+      INTEGER  ::  jn     
+
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_rst_read : read data in the TOP restart file'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+
+      ! READ prognostic variables and computes diagnostic variable
+      DO jn = 1, jptra
+         CALL iom_get( numrtr, jpdom_autoglo, 'TRN'//ctrcnm(jn), trn(:,:,:,jn) )
+      END DO
+
+      DO jn = 1, jptra
+         CALL iom_get( numrtr, jpdom_autoglo, 'TRB'//ctrcnm(jn), trb(:,:,:,jn) )
+      END DO
+      !
+      CALL iom_delay_rst( 'READ', 'TOP', numrtr )   ! read only TOP delayed global communication variables
+      
+   END SUBROUTINE trc_rst_read
+
+   SUBROUTINE trc_rst_wri( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_wri  ***
+      !!
+      !! ** purpose  :   write passive tracer fields in restart files
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt    ! ocean time-step index
+      !!
+      INTEGER  :: jn
+      !!----------------------------------------------------------------------
+      !
+      CALL iom_rstput( kt, nitrst, numrtw, 'rdttrc1', rdttrc )   ! passive tracer time step
+      ! prognostic variables 
+      ! -------------------- 
+      DO jn = 1, jptra
+         CALL iom_rstput( kt, nitrst, numrtw, 'TRN'//ctrcnm(jn), trn(:,:,:,jn) )
+      END DO
+
+      DO jn = 1, jptra
+         CALL iom_rstput( kt, nitrst, numrtw, 'TRB'//ctrcnm(jn), trb(:,:,:,jn) )
+      END DO
+      !
+      CALL iom_delay_rst( 'WRITE', 'TOP', numrtw )   ! save only TOP delayed global communication variables
+    
+      IF( kt == nitrst ) THEN
+          CALL trc_rst_stat            ! statistics
+          CALL iom_close( numrtw )     ! close the restart file (only at last time step)
+#if ! defined key_trdmxl_trc
+          lrst_trc = .FALSE.
+#endif
+          IF( l_offline .AND. ln_rst_list ) THEN
+             nrst_lst = nrst_lst + 1
+             nitrst = nn_stocklist( nrst_lst )
+          ENDIF
+      ENDIF
+      !
+   END SUBROUTINE trc_rst_wri 
+
+
+   SUBROUTINE trc_rst_cal( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE trc_rst_cal  ***
+      !!
+      !!  ** Purpose : Read or write calendar in restart file:
+      !!
+      !!  WRITE(READ) mode:
+      !!       kt        : number of time step since the begining of the experiment at the
+      !!                   end of the current(previous) run
+      !!       adatrj(0) : number of elapsed days since the begining of the experiment at the
+      !!                   end of the current(previous) run (REAL -> keep fractions of day)
+      !!       ndastp    : date at the end of the current(previous) run (coded as yyyymmdd integer)
+      !!
+      !!   According to namelist parameter nrstdt,
+      !!       nn_rsttr = 0  no control on the date (nittrc000 is  arbitrary).
+      !!       nn_rsttr = 1  we verify that nittrc000 is equal to the last
+      !!                   time step of previous run + 1.
+      !!       In both those options, the  exact duration of the experiment
+      !!       since the beginning (cumulated duration of all previous restart runs)
+      !!       is not stored in the restart and is assumed to be (nittrc000-1)*rdt.
+      !!       This is valid is the time step has remained constant.
+      !!
+      !!       nn_rsttr = 2  the duration of the experiment in days (adatrj)
+      !!                    has been stored in the restart file.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      !
+      LOGICAL  ::  llok
+      REAL(wp) ::  zrdttrc1, zkt, zndastp, zdayfrac, ksecs, ktime
+      INTEGER  ::   ihour, iminute
+
+      ! Time domain : restart
+      ! ---------------------
+
+      IF( TRIM(cdrw) == 'READ' ) THEN
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_rst_cal : read the TOP restart file for calendar'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+
+         IF( ln_rsttr ) THEN
+            CALL iom_open( TRIM(cn_trcrst_indir)//'/'//cn_trcrst_in, numrtr )
+            CALL iom_get ( numrtr, 'kt', zkt )   ! last time-step of previous run
+
+            IF(lwp) THEN
+               WRITE(numout,*) ' *** Info read in restart : '
+               WRITE(numout,*) '   previous time-step                               : ', NINT( zkt )
+               WRITE(numout,*) ' *** restart option'
+               SELECT CASE ( nn_rsttr )
+               CASE ( 0 )   ;   WRITE(numout,*) ' nn_rsttr = 0 : no control of nittrc000'
+               CASE ( 1 )   ;   WRITE(numout,*) ' nn_rsttr = 1 : no control the date at nittrc000 (use ndate0 read in the namelist)'
+               CASE ( 2 )   ;   WRITE(numout,*) ' nn_rsttr = 2 : calendar parameters read in restart'
+               END SELECT
+               WRITE(numout,*)
+            ENDIF
+            ! Control of date 
+            IF( nittrc000  - NINT( zkt ) /= nn_dttrc .AND.  nn_rsttr /= 0 )                                  &
+               &   CALL ctl_stop( ' ===>>>> : problem with nittrc000 for the restart',                 &
+               &                  ' verify the restart file or rerun with nn_rsttr = 0 (namelist)' )
+         ENDIF
+         !
+         IF( l_offline ) THEN    
+            !                                          ! set the date in offline mode
+            IF( ln_rsttr .AND. nn_rsttr == 2 ) THEN
+               CALL iom_get( numrtr, 'ndastp', zndastp )
+               ndastp = NINT( zndastp )
+               CALL iom_get( numrtr, 'adatrj', adatrj  )
+               CALL iom_get( numrtr, 'ntime' , ktime   )
+               nn_time0=INT(ktime)
+               ! calculate start time in hours and minutes
+               zdayfrac=adatrj-INT(adatrj)
+               ksecs = NINT(zdayfrac*86400)            ! Nearest second to catch rounding errors in adatrj              
+               ihour = INT(ksecs/3600)
+               iminute = ksecs/60-ihour*60
+                
+               ! Add to nn_time0
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+               nminute=nminute+iminute
+               
+               IF( nminute >= 60 ) THEN
+                  nminute=nminute-60
+                  nhour=nhour+1
+               ENDIF
+               nhour=nhour+ihour
+               IF( nhour >= 24 ) THEN
+                  nhour=nhour-24
+                  adatrj=adatrj+1
+               ENDIF           
+               nn_time0 = nhour * 100 + nminute
+               adatrj = INT(adatrj)                    ! adatrj set to integer as nn_time0 updated            
+             ELSE
+               ! parameters corresponding to nit000 - 1 (as we start the step
+               ! loop with a call to day)
+               ndastp = ndate0 - 1       ! ndate0 read in the namelist in dom_nam
+               nhour   =   nn_time0 / 100
+               nminute = ( nn_time0 - nhour * 100 )
+               IF( nhour*3600+nminute*60-ndt05 .lt. 0 )  ndastp=ndastp-1      ! Start hour is specified in the namelist (default 0)
+               adatrj = ( REAL( nit000-1, wp ) * rdt ) / rday
+               ! note this is wrong if time step has changed during run
+            ENDIF
+            IF( ABS(adatrj  - REAL(NINT(adatrj),wp)) < 0.1 / rday )   adatrj = REAL(NINT(adatrj),wp)   ! avoid truncation error
+            !
+            IF(lwp) THEN
+              WRITE(numout,*) ' *** Info used values : '
+              WRITE(numout,*) '   date ndastp                                      : ', ndastp
+              WRITE(numout,*) '   number of elapsed days since the begining of run : ', adatrj
+              WRITE(numout,*) '   nn_time0                                         : ', nn_time0
+              WRITE(numout,*)
+            ENDIF
+            !
+            IF( ln_rsttr )  THEN   ;    neuler = 1
+            ELSE                   ;    neuler = 0
+            ENDIF
+            !
+            CALL day_init          ! compute calendar
+            !
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
+         !
+         IF(  kt == nitrst ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'trc_wri : write the TOP restart file (NetCDF) at it= ', kt, ' date= ', ndastp
+            IF(lwp) WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         CALL iom_rstput( kt, nitrst, numrtw, 'kt'     , REAL( kt    , wp) )   ! time-step
+         CALL iom_rstput( kt, nitrst, numrtw, 'ndastp' , REAL( ndastp, wp) )   ! date
+         CALL iom_rstput( kt, nitrst, numrtw, 'adatrj' , adatrj            )   ! number of elapsed days since
+         !                                                                     ! the begining of the run [s]
+         CALL iom_rstput( kt, nitrst, numrtw, 'ntime'  , REAL( nn_time0, wp)) ! time
+      ENDIF
+
+   END SUBROUTINE trc_rst_cal
+
+
+   SUBROUTINE trc_rst_stat
+      !!----------------------------------------------------------------------
+      !!                    ***  trc_rst_stat  ***
+      !!
+      !! ** purpose  :   Compute tracers statistics
+      !!----------------------------------------------------------------------
+      INTEGER  :: jk, jn
+      REAL(wp) :: ztraf, zmin, zmax, zmean, zdrift
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zvol
+      !!----------------------------------------------------------------------
+
+      IF( lwp ) THEN
+         WRITE(numout,*) 
+         WRITE(numout,*) '           ----TRACER STAT----             '
+         WRITE(numout,*) 
+      ENDIF
+      !
+      DO jk = 1, jpk
+         zvol(:,:,jk) = e1e2t(:,:) * e3t_a(:,:,jk) * tmask(:,:,jk)
+      END DO
+      !
+      DO jn = 1, jptra
+         ztraf = glob_sum( 'trcrst', trn(:,:,:,jn) * zvol(:,:,:) )
+         zmin  = MINVAL( trn(:,:,:,jn), mask= ((tmask*SPREAD(tmask_i,DIM=3,NCOPIES=jpk).NE.0.)) )
+         zmax  = MAXVAL( trn(:,:,:,jn), mask= ((tmask*SPREAD(tmask_i,DIM=3,NCOPIES=jpk).NE.0.)) )
+         IF( lk_mpp ) THEN
+            CALL mpp_min( 'trcrst', zmin )      ! min over the global domain
+            CALL mpp_max( 'trcrst', zmax )      ! max over the global domain
+         END IF
+         zmean  = ztraf / areatot
+         zdrift = ( ( ztraf - trai(jn) ) / ( trai(jn) + 1.e-12 )  ) * 100._wp
+         IF(lwp) WRITE(numout,9000) jn, TRIM( ctrcnm(jn) ), zmean, zmin, zmax, zdrift
+      END DO
+      IF(lwp) WRITE(numout,*) 
+9000  FORMAT(' tracer nb :',i2,'    name :',a10,'    mean :',e18.10,'    min :',e18.10, &
+      &      '    max :',e18.10,'    drift :',e18.10, ' %')
+      !
+   END SUBROUTINE trc_rst_stat
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_rst_read                      ! Empty routines
+   END SUBROUTINE trc_rst_read
+   SUBROUTINE trc_rst_wri( kt )
+      INTEGER, INTENT ( in ) :: kt
+      WRITE(*,*) 'trc_rst_wri: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_rst_wri   
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcrst
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsms.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsms.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsms.F90	(revision 14097)
@@ -0,0 +1,79 @@
+MODULE trcsms
+   !!======================================================================
+   !!                         ***  MODULE trcsms  ***
+   !! TOP :   Time loop of passive tracers sms
+   !!======================================================================
+   !! History :   1.0  !  2005-03 (O. Aumont, A. El Moussaoui) F90
+   !!             2.0  !  2007-12  (C. Ethe, G. Madec)  revised architecture
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   !!   trc_sms        :  Time loop of passive tracers sms
+   !!----------------------------------------------------------------------
+   USE oce_trc            !
+   USE trc                !
+   USE trcsms_pisces      ! PISCES biogeo-model
+   USE trcsms_cfc         ! CFC 11 &/or 12
+   USE trcsms_c14         ! C14 
+   USE trcsms_age         ! AGE
+   USE trcsms_my_trc      ! MY_TRC  tracers
+   USE prtctl_trc         ! Print control for debbuging
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_sms    ! called in trcstp.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sms( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sms  ***
+      !!
+      !! ** Purpose :   Managment of the time loop of passive tracers sms 
+      !!
+      !! ** Method  : -  call the main routine of of each defined tracer model
+      !! -------------------------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      !!
+      CHARACTER (len=25) :: charout
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sms')
+      !
+      IF( ln_pisces  )   CALL trc_sms_pisces ( kt )    ! main program of PISCES 
+      IF( ll_cfc     )   CALL trc_sms_cfc    ( kt )    ! surface fluxes of CFC
+      IF( ln_c14     )   CALL trc_sms_c14    ( kt )    ! surface fluxes of C14
+      IF( ln_age     )   CALL trc_sms_age    ( kt )    ! Age tracer
+      IF( ln_my_trc  )   CALL trc_sms_my_trc ( kt )    ! MY_TRC  tracers
+
+      IF(ln_ctl) THEN      ! print mean trends (used for debugging)
+         WRITE(charout, FMT="('sms ')")
+         CALL prt_ctl_trc_info( charout )
+         CALL prt_ctl_trc( tab4d=trn, mask=tmask, clinfo=ctrcnm )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sms')
+      !
+   END SUBROUTINE trc_sms
+
+#else
+   !!======================================================================
+   !!  Dummy module :                                     No passive tracer
+   !!======================================================================
+CONTAINS
+   SUBROUTINE trc_sms( kt )                   ! Empty routine
+      INTEGER, INTENT( in ) ::   kt
+      WRITE(*,*) 'trc_sms: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sms
+#endif 
+
+   !!======================================================================
+END MODULE trcsms
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcstp.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcstp.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcstp.F90	(revision 14097)
@@ -0,0 +1,271 @@
+MODULE trcstp
+   !!======================================================================
+   !!                       ***  MODULE trcstp  ***
+   !! Time-stepping    : time loop of opa for passive tracer
+   !!======================================================================
+   !! History :  1.0  !  2004-03  (C. Ethe)  Original
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   trc_stp       : passive tracer system time-stepping
+   !!----------------------------------------------------------------------
+   USE oce_trc        ! ocean dynamics and active tracers variables
+   USE sbc_oce
+   USE trc
+   USE trctrp         ! passive tracers transport
+   USE trcsms         ! passive tracers sources and sinks
+   USE trcwri
+   USE trcrst
+   USE trcsub         !
+   USE trdtrc_oce
+   USE trdmxl_trc
+   USE sms_pisces,  ONLY : ln_check_mass
+   !
+   USE prtctl_trc     ! Print control for debbuging
+   USE iom            !
+   USE in_out_manager !
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trc_stp    ! called by step
+
+   LOGICAL  ::   llnew                   ! ???
+   REAL(wp) ::   rdt_sampl               ! ???
+   INTEGER  ::   nb_rec_per_day, ktdcy   ! ???
+   REAL(wp) ::   rsecfst, rseclast       ! ???
+   REAL(wp), DIMENSION(:,:,:), SAVE, ALLOCATABLE ::   qsr_arr   ! save qsr during TOP time-step
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_stp( kt )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_stp  ***
+      !!                      
+      !! ** Purpose :   Time loop of opa for passive tracer
+      !! 
+      !! ** Method  :   Compute the passive tracers trends 
+      !!                Update the passive tracers
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   jk, jn   ! dummy loop indices
+      REAL(wp)::   ztrai    ! local scalar
+      LOGICAL ::   ll_trcstat ! local logical
+      CHARACTER (len=25) ::   charout   !
+      !!-------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_stp')
+      !
+      IF( ( neuler == 0 .AND. kt == nittrc000 ) .OR. ln_top_euler ) THEN     ! at nittrc000
+         r2dttrc =  rdttrc           ! = rdttrc (use or restarting with Euler time stepping)
+      ELSEIF( kt <= nittrc000 + nn_dttrc ) THEN          ! at nittrc000 or nittrc000+1
+         r2dttrc = 2. * rdttrc       ! = 2 rdttrc (leapfrog)
+      ENDIF
+      !
+      ll_trcstat  = ( ln_ctl .OR. sn_cfctl%l_trcstat ) .AND. &
+     &              ( ( MOD( kt, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend ) )
+
+      IF( kt == nittrc000 )                      CALL trc_stp_ctl   ! control 
+      IF( kt == nittrc000 .AND. lk_trdmxl_trc )  CALL trd_mxl_trc_init    ! trends: Mixed-layer
+      !
+      IF( .NOT.ln_linssh ) THEN                                           ! update ocean volume due to ssh temporal evolution
+         DO jk = 1, jpk
+            cvol(:,:,jk) = e1e2t(:,:) * e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         IF ( ll_trcstat .OR. kt == nitrst .OR. ( ln_check_mass .AND. kt == nitend )          &
+            & .OR. iom_use( "pno3tot" ) .OR. iom_use( "ppo4tot" ) .OR. iom_use( "psiltot" )   &
+            & .OR. iom_use( "palktot" ) .OR. iom_use( "pfertot" ) )                           &
+            &     areatot = glob_sum( 'trcstp', cvol(:,:,:) )
+      ENDIF
+      !
+      IF( l_trcdm2dc )   CALL trc_mean_qsr( kt )
+      !    
+      IF( nn_dttrc /= 1 )   CALL trc_sub_stp( kt )  ! averaging physical variables for sub-stepping
+      !    
+      IF( MOD( kt , nn_dttrc ) == 0 ) THEN      ! only every nn_dttrc time step
+         !
+         IF(ln_ctl) THEN
+            WRITE(charout,FMT="('kt =', I4,'  d/m/y =',I2,I2,I4)") kt, nday, nmonth, nyear
+            CALL prt_ctl_trc_info(charout)
+         ENDIF
+         !
+         tra(:,:,:,:) = 0.e0
+         !
+                                   CALL trc_rst_opn  ( kt )       ! Open tracer restart file 
+         IF( lrst_trc )            CALL trc_rst_cal  ( kt, 'WRITE' )   ! calendar
+                                   CALL trc_wri      ( kt )       ! output of passive tracers with iom I/O manager
+                                   CALL trc_sms      ( kt )       ! tracers: sinks and sources
+                                   CALL trc_trp      ( kt )       ! transport of passive tracers
+         IF( kt == nittrc000 ) THEN
+            CALL iom_close( numrtr )       ! close input tracer restart file
+            IF(lwm) CALL FLUSH( numont )   ! flush namelist output
+         ENDIF
+         IF( lrst_trc )            CALL trc_rst_wri  ( kt )       ! write tracer restart file
+         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
+         !
+      ENDIF
+      !
+      IF (ll_trcstat) THEN
+         ztrai = 0._wp                                                   !  content of all tracers
+         DO jn = 1, jptra
+            ztrai = ztrai + glob_sum( 'trcstp', trn(:,:,:,jn) * cvol(:,:,:)   )
+         END DO
+         IF( lwm ) WRITE(numstr,9300) kt,  ztrai / areatot
+      ENDIF
+9300  FORMAT(i10,D23.16)
+      !
+      IF( ln_timing )   CALL timing_stop('trc_stp')
+      !
+   END SUBROUTINE trc_stp
+
+   SUBROUTINE trc_stp_ctl
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_stp_ctl  ***
+      !! ** Purpose :        Control  + ocean volume
+      !!----------------------------------------------------------------------
+      !
+      ! Define logical parameter ton control dirunal cycle in TOP
+      l_trcdm2dc = ln_dm2dc .OR. ( ln_cpl .AND. ncpl_qsr_freq /= 1 )
+      l_trcdm2dc = l_trcdm2dc  .AND. .NOT. l_offline
+      IF( l_trcdm2dc .AND. lwp )   CALL ctl_warn( 'Coupling with passive tracers and used of diurnal cycle.',   &
+         &                           'Computation of a daily mean shortwave for some biogeochemical models ' )
+      !
+   END SUBROUTINE trc_stp_ctl
+
+
+   SUBROUTINE trc_mean_qsr( kt )
+      !!----------------------------------------------------------------------
+      !!             ***  ROUTINE trc_mean_qsr  ***
+      !!
+      !! ** Purpose :  Compute daily mean qsr for biogeochemical model in case
+      !!               of diurnal cycle
+      !!
+      !! ** Method  : store in TOP the qsr every hour ( or every time-step if the latter 
+      !!              is greater than 1 hour ) and then, compute the  mean with 
+      !!              a moving average over 24 hours. 
+      !!              In coupled mode, the sampling is done at every coupling frequency 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   jn   ! dummy loop indices
+      REAL(wp) ::   zkt, zrec     ! local scalars
+      CHARACTER(len=1) ::   cl1   ! 1 character
+      CHARACTER(len=2) ::   cl2   ! 2 characters
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_mean_qsr')
+      !
+      IF( kt == nittrc000 ) THEN
+         IF( ln_cpl )  THEN  
+            rdt_sampl = rday / ncpl_qsr_freq
+            nb_rec_per_day = ncpl_qsr_freq
+         ELSE  
+            rdt_sampl = MAX( 3600., rdttrc )
+            nb_rec_per_day = INT( rday / rdt_sampl )
+         ENDIF
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) 
+            WRITE(numout,*) ' Sampling frequency dt = ', rdt_sampl, 's','   Number of sampling per day  nrec = ', nb_rec_per_day
+            WRITE(numout,*) 
+         ENDIF
+         !
+         ALLOCATE( qsr_arr(jpi,jpj,nb_rec_per_day ) )
+         !
+         !                                            !* Restart: read in restart file
+         IF( ln_rsttr .AND. nn_rsttr /= 0 .AND. iom_varid( numrtr, 'qsr_mean' , ldstop = .FALSE. ) > 0  &
+           &                              .AND. iom_varid( numrtr, 'qsr_arr_1', ldstop = .FALSE. ) > 0  &
+           &                              .AND. iom_varid( numrtr, 'ktdcy'    , ldstop = .FALSE. ) > 0  &
+           &                              .AND. iom_varid( numrtr, 'nrdcy'    , ldstop = .FALSE. ) > 0  ) THEN
+
+            CALL iom_get( numrtr, 'ktdcy', zkt )  
+            rsecfst = INT( zkt ) * rdttrc
+            IF(lwp) WRITE(numout,*) 'trc_qsr_mean:   qsr_mean read in the restart file at time-step rsecfst =', rsecfst, ' s '
+            CALL iom_get( numrtr, jpdom_autoglo, 'qsr_mean', qsr_mean )   !  A mean of qsr
+            CALL iom_get( numrtr, 'nrdcy', zrec )   !  Number of record per days
+            IF( INT( zrec ) == nb_rec_per_day ) THEN
+               DO jn = 1, nb_rec_per_day 
+                  IF( jn <= 9 )  THEN
+                    WRITE(cl1,'(i1)') jn
+                    CALL iom_get( numrtr, jpdom_autoglo, 'qsr_arr_'//cl1, qsr_arr(:,:,jn) )   !  A mean of qsr
+                  ELSE
+                    WRITE(cl2,'(i2.2)') jn
+                    CALL iom_get( numrtr, jpdom_autoglo, 'qsr_arr_'//cl2, qsr_arr(:,:,jn) )   !  A mean of qsr
+                  ENDIF
+              END DO
+            ELSE
+               DO jn = 1, nb_rec_per_day
+                  qsr_arr(:,:,jn) = qsr_mean(:,:)
+               ENDDO
+            ENDIF
+         ELSE                                         !* no restart: set from nit000 values
+            IF(lwp) WRITE(numout,*) 'trc_qsr_mean:   qsr_mean set to nit000 values'
+            rsecfst  = kt * rdttrc
+            !
+            qsr_mean(:,:) = qsr(:,:)
+            DO jn = 1, nb_rec_per_day
+               qsr_arr(:,:,jn) = qsr_mean(:,:)
+            END DO
+         ENDIF
+         !
+      ENDIF
+      !
+      rseclast = kt * rdttrc
+      !
+      llnew   = ( rseclast - rsecfst ) .ge.  rdt_sampl    !   new shortwave to store
+      IF( llnew ) THEN
+          ktdcy = kt
+          IF( lwp .AND. kt < nittrc000 + 100 ) WRITE(numout,*) ' New shortwave to sample for TOP at time kt = ', ktdcy, &
+             &                      ' time = ', rseclast/3600.,'hours '
+          rsecfst = rseclast
+          DO jn = 1, nb_rec_per_day - 1
+             qsr_arr(:,:,jn) = qsr_arr(:,:,jn+1)
+          ENDDO
+          qsr_arr (:,:,nb_rec_per_day) = qsr(:,:)
+          qsr_mean(:,:                ) = SUM( qsr_arr(:,:,:), 3 ) / nb_rec_per_day
+      ENDIF
+      !
+      IF( lrst_trc ) THEN    !* Write the mean of qsr in restart file 
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_mean_qsr : write qsr_mean in restart file  kt =', kt
+         IF(lwp) WRITE(numout,*) '~~~~~~~'
+         zkt  = REAL( ktdcy, wp )
+         zrec = REAL( nb_rec_per_day, wp )
+         CALL iom_rstput( kt, nitrst, numrtw, 'ktdcy', zkt  )
+         CALL iom_rstput( kt, nitrst, numrtw, 'nrdcy', zrec )
+          DO jn = 1, nb_rec_per_day 
+             IF( jn <= 9 )  THEN
+               WRITE(cl1,'(i1)') jn
+               CALL iom_rstput( kt, nitrst, numrtw, 'qsr_arr_'//cl1, qsr_arr(:,:,jn) )
+             ELSE
+               WRITE(cl2,'(i2.2)') jn
+               CALL iom_rstput( kt, nitrst, numrtw, 'qsr_arr_'//cl2, qsr_arr(:,:,jn) )
+             ENDIF
+         END DO
+         CALL iom_rstput( kt, nitrst, numrtw, 'qsr_mean', qsr_mean(:,:) )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_mean_qsr')
+      !
+   END SUBROUTINE trc_mean_qsr
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default key                                     NO passive tracers
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_stp( kt )        ! Empty routine
+      WRITE(*,*) 'trc_stp: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_stp
+#endif
+
+   !!======================================================================
+END MODULE trcstp
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsub.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsub.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcsub.F90	(revision 14097)
@@ -0,0 +1,597 @@
+MODULE trcsub
+   !!======================================================================
+   !!                       ***  MODULE trcsubstp  ***
+   !!   TOP :   Averages physics variables for TOP substepping. 
+   !!======================================================================
+   !! History :  1.0  !  2011-10  (K. Edwards)  Original
+   !!----------------------------------------------------------------------
+#if defined key_top
+   !!----------------------------------------------------------------------
+   !!   trc_sub       : passive tracer system sub-stepping 
+   !!----------------------------------------------------------------------
+   USE oce_trc        ! ocean dynamics and active tracers variables
+   USE trc
+   USE trabbl         ! bottom boundary layer
+   USE zdf_oce
+   USE domvvl
+   USE divhor         ! horizontal divergence
+   USE sbcrnf   , ONLY: h_rnf, nk_rnf    ! River runoff
+   USE bdy_oce  , ONLY: ln_bdy, bdytmask ! BDY
+   !
+   USE prtctl_trc     ! Print control for debbuging
+   USE in_out_manager ! 
+   USE iom
+   USE lbclnk
+#if defined key_agrif
+   USE agrif_oce_update
+   USE agrif_oce_interp
+#endif
+
+   IMPLICIT NONE
+
+   PUBLIC   trc_sub_stp     ! called by trc_stp
+   PUBLIC   trc_sub_ini     ! called by trc_ini to initialize substepping arrays.
+   PUBLIC   trc_sub_reset   ! called by trc_stp to reset physics variables
+   PUBLIC   trc_sub_ssh     ! called by trc_stp to reset physics variables
+
+   REAL(wp) :: r1_ndttrc     ! = 1 /  nn_dttrc 
+   REAL(wp) :: r1_ndttrcp1   ! = 1 / (nn_dttrc+1) 
+
+
+   !! averaged and temporary saved variables  (needed when a larger passive tracer time-step is used)
+   !! ----------------------------------------------------------------
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::    un_tm ,   un_temp   !: i-horizontal velocity average     [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::    vn_tm ,   vn_temp   !: j-horizontal velocity average     [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::              wn_temp   !: hold current values of avt, un, vn, wn
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   tsn_tm ,  tsn_temp   !: t/s average     [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   avs_tm ,  avs_temp   !: vertical diffusivity coeff. at  w-point   [m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::  rhop_tm , rhop_temp   !: 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  sshn_tm , sshn_temp   !: average ssh for the now step [m]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::    rnf_tm ,    rnf_temp   !: river runoff
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  h_rnf_tm ,  h_rnf_temp   !: depth in metres to the bottom of the relevant grid box
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   hmld_tm ,   hmld_temp   !: mixed layer depth average [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   fr_i_tm ,   fr_i_temp   !: average ice fraction     [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::    emp_tm ,    emp_temp   !: freshwater budget: volume flux [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     :: fmmflx_tm , fmmflx_temp   !: freshwater budget: freezing/melting [Kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     :: emp_b_hold,  emp_b_temp   !: hold emp from the beginning of each sub-stepping[m]  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::    qsr_tm ,    qsr_temp   !: solar radiation average [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   wndm_tm ,   wndm_temp   !: 10m wind average [m]
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  sshb_hold   !:hold sshb from the beginning of each sub-stepping[m]  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   sshb_temp, ssha_temp
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::  hdivn_temp, rotn_temp
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::  hdivb_temp, rotb_temp
+   !
+   !                                                    !!- bottom boundary layer param (ln_trabbl=T)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  ahu_bbl_tm, ahu_bbl_temp  ! BBL diffusive i-coef.
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  ahv_bbl_tm, ahv_bbl_temp  ! BBL diffusive j-coef.
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  utr_bbl_tm, utr_bbl_temp  ! BBL u-advection
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)     ::  vtr_bbl_tm, vtr_bbl_temp  ! BBL v-advection
+
+   !                                                      !!- iso-neutral slopes (if l_ldfslp=T)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   uslp_temp, vslp_temp, wslpi_temp, wslpj_temp   !: hold current values 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   uslp_tm  , vslp_tm  , wslpi_tm  , wslpj_tm     !: time mean 
+
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trc_sub_stp( kt )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_stp  ***
+      !!                      
+      !! ** Purpose : Average variables needed for sub-stepping passive tracers
+      !! 
+      !! ** Method  : Called every timestep to increment _tm (time mean) variables
+      !!              on TOP steps, calculate averages.
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp)::   z1_ne3t, z1_ne3u, z1_ne3v, z1_ne3w   ! local scalars
+      !!-------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sub_stp')
+      !
+      IF( kt == nit000 ) THEN
+           IF(lwp) WRITE(numout,*)
+           IF(lwp) WRITE(numout,*) 'trc_sub_stp : substepping of the passive tracers'
+           IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+           !
+           sshb_hold  (:,:) = sshn  (:,:)
+           emp_b_hold (:,:) = emp_b (:,:)
+           !
+           r1_ndttrc        = 1._wp / REAL( nn_dttrc    , wp ) 
+           r1_ndttrcp1      = 1._wp / REAL( nn_dttrc + 1, wp )
+      ENDIF  
+
+      IF( MOD( kt , nn_dttrc ) /= 0 ) THEN
+         !
+         un_tm   (:,:,:)        = un_tm   (:,:,:)        + un   (:,:,:)        * e3u_n(:,:,:) 
+         vn_tm   (:,:,:)        = vn_tm   (:,:,:)        + vn   (:,:,:)        * e3v_n(:,:,:) 
+         tsn_tm  (:,:,:,jp_tem) = tsn_tm  (:,:,:,jp_tem) + tsn  (:,:,:,jp_tem) * e3t_n(:,:,:)  
+         tsn_tm  (:,:,:,jp_sal) = tsn_tm  (:,:,:,jp_sal) + tsn  (:,:,:,jp_sal) * e3t_n(:,:,:)  
+         rhop_tm (:,:,:)        = rhop_tm (:,:,:)        + rhop (:,:,:)        * e3t_n(:,:,:)  
+         avs_tm  (:,:,:)        = avs_tm  (:,:,:)        + avs  (:,:,:)        * e3w_n(:,:,:)  
+         IF( l_ldfslp ) THEN
+            uslp_tm (:,:,:)      = uslp_tm (:,:,:)        + uslp (:,:,:)
+            vslp_tm (:,:,:)      = vslp_tm (:,:,:)        + vslp (:,:,:)
+            wslpi_tm(:,:,:)      = wslpi_tm(:,:,:)        + wslpi(:,:,:)
+            wslpj_tm(:,:,:)      = wslpj_tm(:,:,:)        + wslpj(:,:,:)
+         ENDIF
+         IF( ln_trabbl ) THEN
+            IF( nn_bbl_ldf == 1 ) THEN
+               ahu_bbl_tm(:,:)     = ahu_bbl_tm(:,:)        + ahu_bbl(:,:) 
+               ahv_bbl_tm(:,:)     = ahv_bbl_tm(:,:)        + ahv_bbl(:,:) 
+            ENDIF
+            IF( nn_bbl_adv == 1 ) THEN
+               utr_bbl_tm(:,:)     = utr_bbl_tm(:,:)        + utr_bbl(:,:) 
+               vtr_bbl_tm(:,:)     = vtr_bbl_tm(:,:)        + vtr_bbl(:,:) 
+            ENDIF
+         ENDIF 
+         !
+         sshn_tm  (:,:)         = sshn_tm  (:,:)         + sshn  (:,:) 
+         rnf_tm   (:,:)         = rnf_tm   (:,:)         + rnf   (:,:) 
+         h_rnf_tm (:,:)         = h_rnf_tm (:,:)         + h_rnf (:,:) 
+         hmld_tm  (:,:)         = hmld_tm  (:,:)         + hmld  (:,:)
+         fr_i_tm  (:,:)         = fr_i_tm  (:,:)         + fr_i  (:,:)
+         emp_tm   (:,:)         = emp_tm   (:,:)         + emp   (:,:) 
+         fmmflx_tm(:,:)         = fmmflx_tm(:,:)         + fmmflx(:,:)
+         qsr_tm   (:,:)         = qsr_tm   (:,:)         + qsr   (:,:)
+         wndm_tm  (:,:)         = wndm_tm  (:,:)         + wndm  (:,:)
+         !
+      ELSE                           !  It is time to substep 
+         !   1. set temporary arrays to hold physics/dynamical variables
+         un_temp    (:,:,:)      = un    (:,:,:)
+         vn_temp    (:,:,:)      = vn    (:,:,:)
+         wn_temp    (:,:,:)      = wn    (:,:,:)
+         tsn_temp   (:,:,:,:)    = tsn   (:,:,:,:)
+         rhop_temp  (:,:,:)      = rhop  (:,:,:)    
+         avs_temp   (:,:,:)      = avs   (:,:,:)
+         IF( l_ldfslp ) THEN
+            uslp_temp  (:,:,:)   = uslp  (:,:,:)   ;   wslpi_temp (:,:,:)   = wslpi (:,:,:)
+            vslp_temp  (:,:,:)   = vslp  (:,:,:)   ;   wslpj_temp (:,:,:)   = wslpj (:,:,:)
+         ENDIF
+         IF( ln_trabbl ) THEN
+            IF( nn_bbl_ldf == 1 ) THEN
+               ahu_bbl_temp(:,:)   = ahu_bbl(:,:)  
+               ahv_bbl_temp(:,:)   = ahv_bbl(:,:) 
+            ENDIF
+            IF( nn_bbl_adv == 1 ) THEN
+               utr_bbl_temp(:,:)   = utr_bbl(:,:) 
+               vtr_bbl_temp(:,:)   = vtr_bbl(:,:) 
+            ENDIF
+         ENDIF 
+         sshn_temp  (:,:)        = sshn  (:,:)
+         sshb_temp  (:,:)        = sshb  (:,:)
+         ssha_temp  (:,:)        = ssha  (:,:)
+         rnf_temp   (:,:)        = rnf   (:,:)
+         h_rnf_temp (:,:)        = h_rnf (:,:)
+         hmld_temp  (:,:)        = hmld  (:,:)
+         fr_i_temp  (:,:)        = fr_i  (:,:)
+         emp_temp   (:,:)        = emp   (:,:)
+         emp_b_temp (:,:)        = emp_b (:,:)
+         fmmflx_temp(:,:)        = fmmflx(:,:)
+         qsr_temp   (:,:)        = qsr   (:,:)
+         wndm_temp  (:,:)        = wndm  (:,:)
+         !                                    !  Variables reset in trc_sub_ssh
+         hdivn_temp (:,:,:)      = hdivn (:,:,:)
+         !
+         ! 2. Create averages and reassign variables
+         un_tm    (:,:,:)        = un_tm   (:,:,:)        + un   (:,:,:)        * e3u_n(:,:,:) 
+         vn_tm    (:,:,:)        = vn_tm   (:,:,:)        + vn   (:,:,:)        * e3v_n(:,:,:) 
+         tsn_tm   (:,:,:,jp_tem) = tsn_tm  (:,:,:,jp_tem) + tsn  (:,:,:,jp_tem) * e3t_n(:,:,:)  
+         tsn_tm   (:,:,:,jp_sal) = tsn_tm  (:,:,:,jp_sal) + tsn  (:,:,:,jp_sal) * e3t_n(:,:,:)  
+         rhop_tm (:,:,:)         = rhop_tm (:,:,:)        + rhop (:,:,:)        * e3t_n(:,:,:)  
+         avs_tm   (:,:,:)        = avs_tm  (:,:,:)        + avs  (:,:,:)        * e3w_n(:,:,:)  
+         IF( l_ldfslp ) THEN
+            uslp_tm  (:,:,:)     = uslp_tm (:,:,:)        + uslp (:,:,:) 
+            vslp_tm  (:,:,:)     = vslp_tm (:,:,:)        + vslp (:,:,:)
+            wslpi_tm (:,:,:)     = wslpi_tm(:,:,:)        + wslpi(:,:,:) 
+            wslpj_tm (:,:,:)     = wslpj_tm(:,:,:)        + wslpj(:,:,:) 
+         ENDIF
+         IF( ln_trabbl ) THEN
+            IF( nn_bbl_ldf == 1 ) THEN
+               ahu_bbl_tm(:,:)     = ahu_bbl_tm(:,:)        + ahu_bbl(:,:) 
+               ahv_bbl_tm(:,:)     = ahv_bbl_tm(:,:)        + ahv_bbl(:,:) 
+            ENDIF
+            IF( nn_bbl_adv == 1 ) THEN
+               utr_bbl_tm(:,:)     = utr_bbl_tm(:,:)        + utr_bbl(:,:) 
+               vtr_bbl_tm(:,:)     = vtr_bbl_tm(:,:)        + vtr_bbl(:,:) 
+            ENDIF
+         ENDIF 
+         sshn_tm  (:,:)          = sshn_tm    (:,:)       + sshn  (:,:) 
+         rnf_tm   (:,:)          = rnf_tm     (:,:)       + rnf   (:,:) 
+         h_rnf_tm (:,:)          = h_rnf_tm   (:,:)       + h_rnf (:,:) 
+         hmld_tm  (:,:)          = hmld_tm    (:,:)       + hmld  (:,:)
+         fr_i_tm  (:,:)          = fr_i_tm    (:,:)       + fr_i  (:,:)
+         emp_tm   (:,:)          = emp_tm     (:,:)       + emp   (:,:) 
+         fmmflx_tm(:,:)          = fmmflx_tm  (:,:)       + fmmflx(:,:)
+         qsr_tm   (:,:)          = qsr_tm     (:,:)       + qsr   (:,:)
+         wndm_tm  (:,:)          = wndm_tm    (:,:)       + wndm  (:,:)
+         !
+         sshn     (:,:)          = sshn_tm    (:,:) * r1_ndttrcp1 
+         sshb     (:,:)          = sshb_hold  (:,:)
+         rnf      (:,:)          = rnf_tm     (:,:) * r1_ndttrcp1 
+         h_rnf    (:,:)          = h_rnf_tm   (:,:) * r1_ndttrcp1 
+         hmld     (:,:)          = hmld_tm    (:,:) * r1_ndttrcp1 
+         !  variables that are initialized after averages
+         emp_b    (:,:) = emp_b_hold (:,:)
+         IF( kt == nittrc000 ) THEN
+            wndm  (:,:)          = wndm_tm    (:,:) * r1_ndttrc 
+            qsr   (:,:)          = qsr_tm     (:,:) * r1_ndttrc 
+            emp   (:,:)          = emp_tm     (:,:) * r1_ndttrc 
+            fmmflx(:,:)          = fmmflx_tm  (:,:) * r1_ndttrc 
+            fr_i  (:,:)          = fr_i_tm    (:,:) * r1_ndttrc
+            IF( ln_trabbl ) THEN
+               IF( nn_bbl_ldf == 1 ) THEN
+                  ahu_bbl(:,:)      = ahu_bbl_tm (:,:) * r1_ndttrc  
+                  ahv_bbl(:,:)      = ahv_bbl_tm (:,:) * r1_ndttrc 
+               ENDIF
+               IF( nn_bbl_adv == 1 ) THEN
+                  utr_bbl(:,:)      = utr_bbl_tm (:,:) * r1_ndttrc  
+                  vtr_bbl(:,:)      = vtr_bbl_tm (:,:) * r1_ndttrc 
+               ENDIF
+            ENDIF
+         ELSE
+            wndm  (:,:)          = wndm_tm    (:,:) * r1_ndttrcp1 
+            qsr   (:,:)          = qsr_tm     (:,:) * r1_ndttrcp1 
+            emp   (:,:)          = emp_tm     (:,:) * r1_ndttrcp1 
+            fmmflx(:,:)          = fmmflx_tm  (:,:) * r1_ndttrcp1 
+            fr_i  (:,:)          = fr_i_tm    (:,:) * r1_ndttrcp1 
+            IF( ln_trabbl ) THEN
+               IF( nn_bbl_ldf == 1 ) THEN
+                  ahu_bbl(:,:)      = ahu_bbl_tm (:,:) * r1_ndttrcp1  
+                  ahv_bbl(:,:)      = ahv_bbl_tm (:,:) * r1_ndttrcp1 
+               ENDIF
+               IF( nn_bbl_adv == 1 ) THEN
+                  utr_bbl(:,:)      = utr_bbl_tm (:,:) * r1_ndttrcp1  
+                  vtr_bbl(:,:)      = vtr_bbl_tm (:,:) * r1_ndttrcp1 
+               ENDIF
+            ENDIF
+         ENDIF
+         !
+         DO jk = 1, jpk
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z1_ne3t = r1_ndttrcp1  / e3t_n(ji,jj,jk)
+                  z1_ne3u = r1_ndttrcp1  / e3u_n(ji,jj,jk)
+                  z1_ne3v = r1_ndttrcp1  / e3v_n(ji,jj,jk)
+                  z1_ne3w = r1_ndttrcp1  / e3w_n(ji,jj,jk)
+                  !
+                  un   (ji,jj,jk)        = un_tm   (ji,jj,jk)        * z1_ne3u
+                  vn   (ji,jj,jk)        = vn_tm   (ji,jj,jk)        * z1_ne3v
+                  tsn  (ji,jj,jk,jp_tem) = tsn_tm  (ji,jj,jk,jp_tem) * z1_ne3t
+                  tsn  (ji,jj,jk,jp_sal) = tsn_tm  (ji,jj,jk,jp_sal) * z1_ne3t
+                  rhop (ji,jj,jk)        = rhop_tm (ji,jj,jk)        * z1_ne3t
+!!gm : BUG ==>> for avs I don't understand the division by e3w
+                  avs  (ji,jj,jk)        = avs_tm  (ji,jj,jk)        * z1_ne3w
+               END DO
+            END DO
+         END DO
+         IF( l_ldfslp ) THEN
+            wslpi(:,:,:)        = wslpi_tm(:,:,:) 
+            wslpj(:,:,:)        = wslpj_tm(:,:,:)
+            uslp (:,:,:)        = uslp_tm (:,:,:)
+            vslp (:,:,:)        = vslp_tm (:,:,:)
+         ENDIF
+         !
+         CALL trc_sub_ssh( kt )         ! after ssh & vertical velocity
+         !
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sub_stp')
+      !
+   END SUBROUTINE trc_sub_stp
+
+
+   SUBROUTINE trc_sub_ini
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sub_ini  ***
+      !!                      
+      !! ** Purpose : Initialize variables needed for sub-stepping passive tracers
+      !! 
+      !! ** Method  : 
+      !!              Compute the averages for sub-stepping
+      !!-------------------------------------------------------------------
+      INTEGER ::   ierr
+      !!-------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'trc_sub_ini : initial set up of the passive tracers substepping'
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+
+      ierr =  trc_sub_alloc    ()
+      CALL mpp_sum( 'trcsub', ierr )
+      IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'top_sub_alloc : unable to allocate standard ocean arrays' )
+
+      un_tm   (:,:,:)        = un   (:,:,:)        * e3u_n(:,:,:) 
+      vn_tm   (:,:,:)        = vn   (:,:,:)        * e3v_n(:,:,:) 
+      tsn_tm  (:,:,:,jp_tem) = tsn  (:,:,:,jp_tem) * e3t_n(:,:,:)  
+      tsn_tm  (:,:,:,jp_sal) = tsn  (:,:,:,jp_sal) * e3t_n(:,:,:)  
+      rhop_tm (:,:,:)        = rhop (:,:,:)        * e3t_n(:,:,:)  
+!!gm : BUG? ==>> for avt & avs I don't understand the division by e3w
+      avs_tm  (:,:,:)        = avs  (:,:,:)        * e3w_n(:,:,:)  
+      IF( l_ldfslp ) THEN
+         wslpi_tm(:,:,:)     = wslpi(:,:,:)
+         wslpj_tm(:,:,:)     = wslpj(:,:,:)
+         uslp_tm (:,:,:)     = uslp (:,:,:)
+         vslp_tm (:,:,:)     = vslp (:,:,:)
+      ENDIF
+      sshn_tm  (:,:) = sshn  (:,:) 
+      rnf_tm   (:,:) = rnf   (:,:) 
+      h_rnf_tm (:,:) = h_rnf (:,:) 
+      hmld_tm  (:,:) = hmld  (:,:)
+
+      ! Physics variables that are set after initialization:
+      fr_i_tm  (:,:) = 0._wp
+      emp_tm   (:,:) = 0._wp
+      fmmflx_tm(:,:)  = 0._wp
+      qsr_tm   (:,:) = 0._wp
+      wndm_tm  (:,:) = 0._wp
+      IF( ln_trabbl ) THEN
+         IF( nn_bbl_ldf == 1 ) THEN
+            ahu_bbl_tm(:,:) = 0._wp
+            ahv_bbl_tm(:,:) = 0._wp
+         ENDIF
+         IF( nn_bbl_adv == 1 ) THEN
+            utr_bbl_tm(:,:) = 0._wp
+            vtr_bbl_tm(:,:) = 0._wp
+         ENDIF
+      ENDIF
+      !
+   END SUBROUTINE trc_sub_ini
+
+
+   SUBROUTINE trc_sub_reset( kt )
+      !!-------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_sub_reset  ***
+      !!                      
+      !! ** Purpose : Reset physics variables averaged for substepping
+      !! 
+      !! ** Method  : 
+      !!              Compute the averages for sub-stepping
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::  kt  ! ocean time-step index
+      INTEGER :: jk                 ! dummy loop indices
+      !!-------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sub_reset')
+      !
+      !   restore physics variables
+      un    (:,:,:)   =  un_temp    (:,:,:)
+      vn    (:,:,:)   =  vn_temp    (:,:,:)
+      wn    (:,:,:)   =  wn_temp    (:,:,:)
+      tsn   (:,:,:,:) =  tsn_temp   (:,:,:,:)
+      rhop  (:,:,:)   =  rhop_temp  (:,:,:)
+      avs   (:,:,:)   =  avs_temp   (:,:,:)
+      IF( l_ldfslp ) THEN
+         wslpi (:,:,:)=  wslpi_temp (:,:,:)
+         wslpj (:,:,:)=  wslpj_temp (:,:,:)
+         uslp  (:,:,:)=  uslp_temp  (:,:,:)
+         vslp  (:,:,:)=  vslp_temp  (:,:,:)
+      ENDIF
+      sshn  (:,:)     =  sshn_temp  (:,:)
+      sshb  (:,:)     =  sshb_temp  (:,:)
+      ssha  (:,:)     =  ssha_temp  (:,:)
+      rnf   (:,:)     =  rnf_temp   (:,:)
+      h_rnf (:,:)     =  h_rnf_temp (:,:)
+      !
+      hmld  (:,:)     =  hmld_temp  (:,:)
+      fr_i  (:,:)     =  fr_i_temp  (:,:)
+      emp   (:,:)     =  emp_temp   (:,:)
+      fmmflx(:,:)     =  fmmflx_temp(:,:)
+      emp_b (:,:)     =  emp_b_temp (:,:)
+      qsr   (:,:)     =  qsr_temp   (:,:)
+      wndm  (:,:)     =  wndm_temp  (:,:)
+      IF( ln_trabbl ) THEN
+         IF( nn_bbl_ldf == 1 ) THEN
+            ahu_bbl(:,:) = ahu_bbl_temp(:,:) 
+            ahv_bbl(:,:) = ahv_bbl_temp(:,:) 
+         ENDIF
+         IF( nn_bbl_adv == 1 ) THEN
+            utr_bbl(:,:) = utr_bbl_temp(:,:) 
+            vtr_bbl(:,:) = vtr_bbl_temp(:,:) 
+         ENDIF
+      ENDIF
+      !
+      hdivn (:,:,:)   =  hdivn_temp (:,:,:)
+      !                                      
+      ! Start new averages
+         un_tm   (:,:,:)        = un   (:,:,:)        * e3u_n(:,:,:) 
+         vn_tm   (:,:,:)        = vn   (:,:,:)        * e3v_n(:,:,:) 
+         tsn_tm  (:,:,:,jp_tem) = tsn  (:,:,:,jp_tem) * e3t_n(:,:,:)  
+         tsn_tm  (:,:,:,jp_sal) = tsn  (:,:,:,jp_sal) * e3t_n(:,:,:)  
+         rhop_tm (:,:,:)        = rhop (:,:,:)        * e3t_n(:,:,:)  
+         avs_tm  (:,:,:)        = avs  (:,:,:)        * e3w_n(:,:,:)  
+      IF( l_ldfslp ) THEN
+         uslp_tm (:,:,:)        = uslp (:,:,:)
+         vslp_tm (:,:,:)        = vslp (:,:,:)
+         wslpi_tm(:,:,:)        = wslpi(:,:,:) 
+         wslpj_tm(:,:,:)        = wslpj(:,:,:)
+      ENDIF
+      !
+      sshb_hold  (:,:) = sshn  (:,:)
+      emp_b_hold (:,:) = emp   (:,:)
+      sshn_tm    (:,:) = sshn  (:,:) 
+      rnf_tm     (:,:) = rnf   (:,:) 
+      h_rnf_tm   (:,:) = h_rnf (:,:) 
+      hmld_tm    (:,:) = hmld  (:,:)
+      fr_i_tm    (:,:) = fr_i  (:,:)
+      emp_tm     (:,:) = emp   (:,:)
+      fmmflx_tm  (:,:) = fmmflx(:,:)
+      qsr_tm     (:,:) = qsr   (:,:)
+      wndm_tm    (:,:) = wndm  (:,:)
+      IF( ln_trabbl ) THEN
+         IF( nn_bbl_ldf == 1 ) THEN
+            ahu_bbl_tm(:,:) = ahu_bbl(:,:) 
+            ahv_bbl_tm(:,:) = ahv_bbl(:,:) 
+         ENDIF
+         IF( nn_bbl_adv == 1 ) THEN
+            utr_bbl_tm(:,:) = utr_bbl(:,:) 
+            vtr_bbl_tm(:,:) = vtr_bbl(:,:) 
+         ENDIF
+      ENDIF
+      !
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sub_reset')
+      !
+   END SUBROUTINE trc_sub_reset
+
+
+   SUBROUTINE trc_sub_ssh( kt ) 
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE trc_sub_ssh  ***
+      !!                   
+      !! ** Purpose :   compute the after ssh (ssha), the now vertical velocity
+      !!              and update the now vertical coordinate (ln_linssh=F).
+      !!
+      !! ** Method  : - Using the incompressibility hypothesis, the vertical 
+      !!      velocity is computed by integrating the horizontal divergence  
+      !!      from the bottom to the surface minus the scale factor evolution.
+      !!        The boundary conditions are w=0 at the bottom (no flux) and.
+      !!
+      !! ** action  :   ssha    : after sea surface height
+      !!                wn      : now vertical velocity
+      !!                sshu_a, sshv_a, sshf_a  : after sea surface height (ln_linssh=F)
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcoefu, zcoefv, zcoeff, z2dt, z1_2dt, z1_rau0   ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj) :: zhdiv
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_sub_ssh')
+      !
+
+      IF( kt == nittrc000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'trc_sub_ssh : after sea surface height and now vertical velocity '
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~ '
+         !
+         wn(:,:,jpk) = 0._wp                  ! bottom boundary condition: w=0 (set once for all)
+         !
+      ENDIF
+      !
+!!gm BUG here !   hdivn will include the runoff divergence at the wrong timestep !!!!
+      CALL div_hor( kt )                              ! Horizontal divergence & Relative vorticity
+      !
+      z2dt = 2._wp * rdt                              ! set time step size (Euler/Leapfrog)
+      IF( neuler == 0 .AND. kt == nittrc000 )   z2dt = rdt
+
+      !                                           !------------------------------!
+      !                                           !   After Sea Surface Height   !
+      !                                           !------------------------------!
+      zhdiv(:,:) = 0._wp
+      DO jk = 1, jpkm1                                 ! Horizontal divergence of barotropic transports
+        zhdiv(:,:) = zhdiv(:,:) + e3t_n(:,:,jk) * hdivn(:,:,jk)
+      END DO
+      !                                                ! Sea surface elevation time stepping
+      ! In forward Euler time stepping case, the same formulation as in the leap-frog case can be used
+      ! because emp_b field is initialized with the vlaues of emp field. Hence, 0.5 * ( emp + emp_b ) = emp
+      z1_rau0 = 0.5 / rau0
+      ssha(:,:) = (  sshb(:,:) - z2dt * ( z1_rau0 * ( emp_b(:,:) + emp(:,:) ) + zhdiv(:,:) )  ) * tmask(:,:,1)
+
+      IF( .NOT.ln_dynspg_ts ) THEN
+      ! These lines are not necessary with time splitting since
+      ! boundary condition on sea level is set during ts loop
+#if defined key_agrif
+      CALL agrif_ssh( kt )
+#endif
+         IF( ln_bdy ) THEN
+            ssha(:,:) = ssha(:,:) * bdytmask(:,:)
+            CALL lbc_lnk( 'trcsub', ssha, 'T', 1. ) 
+         ENDIF
+      ENDIF
+      !
+      !                                           !------------------------------!
+      !                                           !     Now Vertical Velocity    !
+      !                                           !------------------------------!
+      z1_2dt = 1.e0 / z2dt
+      DO jk = jpkm1, 1, -1                             ! integrate from the bottom the hor. divergence
+         ! - ML - need 3 lines here because replacement of e3t by its expression yields too long lines otherwise
+         wn(:,:,jk) = wn(:,:,jk+1) -   e3t_n(:,:,jk) * hdivn(:,:,jk)        &
+            &                      - ( e3t_a(:,:,jk) - e3t_b(:,:,jk) )    &
+            &                         * tmask(:,:,jk) * z1_2dt
+         IF( ln_bdy ) wn(:,:,jk) = wn(:,:,jk) * bdytmask(:,:)
+      END DO
+      !
+      IF( ln_timing )   CALL timing_stop('trc_sub_ssh')
+      !
+   END SUBROUTINE trc_sub_ssh
+
+
+   INTEGER FUNCTION trc_sub_alloc()
+      !!-------------------------------------------------------------------
+      !!                    *** ROUTINE trc_sub_alloc ***
+      !!-------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_stop
+      INTEGER ::  ierr(3)
+      !!-------------------------------------------------------------------
+      !
+      ierr(:) = 0
+      !
+      ALLOCATE( un_temp(jpi,jpj,jpk)      ,  vn_temp(jpi,jpj,jpk)   ,     &
+         &      wn_temp(jpi,jpj,jpk)      ,                               &
+         &      rhop_temp(jpi,jpj,jpk)    ,  rhop_tm(jpi,jpj,jpk)   ,     &
+         &      sshn_temp(jpi,jpj)        ,  sshb_temp(jpi,jpj)     ,     &
+         &      ssha_temp(jpi,jpj)        ,                               &
+         &      rnf_temp(jpi,jpj)         ,  h_rnf_temp(jpi,jpj)    ,     &
+         &      tsn_temp(jpi,jpj,jpk,2)   ,  emp_b_temp(jpi,jpj)    ,     &
+         &      emp_temp(jpi,jpj)         ,  fmmflx_temp(jpi,jpj)   ,     &
+         &      hmld_temp(jpi,jpj)        ,  qsr_temp(jpi,jpj)      ,     &
+         &      fr_i_temp(jpi,jpj)        ,  fr_i_tm(jpi,jpj)       ,     &
+         &      wndm_temp(jpi,jpj)        ,  wndm_tm(jpi,jpj)       ,     &
+         &      avs_tm(jpi,jpj,jpk)       ,  avs_temp(jpi,jpj,jpk)  ,     &
+         &      hdivn_temp(jpi,jpj,jpk)   ,  hdivb_temp(jpi,jpj,jpk),     &
+         &      un_tm(jpi,jpj,jpk)        ,  vn_tm(jpi,jpj,jpk)     ,     &
+         &      sshn_tm(jpi,jpj)          ,  sshb_hold(jpi,jpj)     ,     &
+         &      tsn_tm(jpi,jpj,jpk,2)     ,                               &
+         &      emp_tm(jpi,jpj)           ,  fmmflx_tm(jpi,jpj)     ,     &
+         &      emp_b_hold(jpi,jpj)       ,                               &
+         &      hmld_tm(jpi,jpj)          ,  qsr_tm(jpi,jpj)        ,     &
+         &      rnf_tm(jpi,jpj)           ,  h_rnf_tm(jpi,jpj)      , STAT=ierr(1) )  
+      !
+      IF( l_ldfslp ) THEN
+         ALLOCATE( uslp_temp(jpi,jpj,jpk) ,  wslpi_temp(jpi,jpj,jpk),     &
+            &      vslp_temp(jpi,jpj,jpk) ,  wslpj_temp(jpi,jpj,jpk),     &
+            &      uslp_tm  (jpi,jpj,jpk) ,  wslpi_tm  (jpi,jpj,jpk),     &
+            &      vslp_tm  (jpi,jpj,jpk) ,  wslpj_tm  (jpi,jpj,jpk), STAT=ierr(2) )
+      ENDIF
+      IF( ln_trabbl ) THEN
+         ALLOCATE( ahu_bbl_temp(jpi,jpj)  , utr_bbl_temp(jpi,jpj)   ,     &
+            &      ahv_bbl_temp(jpi,jpj)  , vtr_bbl_temp(jpi,jpj)   ,     &
+            &      ahu_bbl_tm  (jpi,jpj)  , utr_bbl_tm  (jpi,jpj)   ,     &
+            &      ahv_bbl_tm  (jpi,jpj)  , vtr_bbl_tm  (jpi,jpj)   , STAT=ierr(3) ) 
+      ENDIF
+      !
+      trc_sub_alloc = MAXVAL( ierr )
+      !
+      IF( trc_sub_alloc /= 0 )   CALL ctl_stop( 'STOP', 'trc_sub_alloc: failed to allocate arrays' )
+      !
+   END FUNCTION trc_sub_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default key                                     NO passive tracers
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trc_sub_stp( kt )        ! Empty routine
+      WRITE(*,*) 'trc_sub_stp: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sub_stp
+   SUBROUTINE trc_sub_ini        ! Empty routine
+      WRITE(*,*) 'trc_sub_ini: You should not have seen this print! error?', kt
+   END SUBROUTINE trc_sub_ini
+#endif
+
+   !!======================================================================
+END MODULE trcsub
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcwri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcwri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/src/TOP/trcwri.F90	(revision 14097)
@@ -0,0 +1,93 @@
+MODULE trcwri
+   !!======================================================================
+   !!                       *** MODULE trcwri ***
+   !!    TOP :   Output of passive tracers
+   !!======================================================================
+   !! History :   1.0  !  2009-05 (C. Ethe)  Original code
+   !!----------------------------------------------------------------------
+#if defined key_top && defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                           TOP models
+   !!----------------------------------------------------------------------
+   !! trc_wri_trc   :  outputs of concentration fields
+   !!----------------------------------------------------------------------
+   USE dom_oce     ! ocean space and time domain variables
+   USE oce_trc     ! shared variables between ocean and passive tracers
+   USE trc         ! passive tracers common variables 
+   USE iom         ! I/O manager
+   USE dianam      ! Output file name
+   USE trcwri_pisces
+   USE trcwri_cfc
+   USE trcwri_c14
+   USE trcwri_age
+   USE trcwri_my_trc
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trc_wri      
+
+CONTAINS
+
+   SUBROUTINE trc_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE trc_wri  ***
+      !! 
+      !! ** Purpose :   output passive tracers fields and dynamical trends
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT( in )     :: kt
+      !
+      INTEGER                   :: jn
+      CHARACTER (len=20)        :: cltra
+      CHARACTER (len=40)        :: clhstnam
+      INTEGER ::   inum = 11            ! temporary logical unit
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('trc_wri')
+      !
+      IF( l_offline ) THEN    ! WRITE root name in date.file for use by postpro
+         IF(  kt == nittrc000 .AND. lwp ) THEN    ! WRITE root name in date.file for use by postpro
+           CALL dia_nam( clhstnam, nn_writetrc,' ' )
+           CALL ctl_opn( inum, 'date.file', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+           WRITE(inum,*) clhstnam
+           CLOSE(inum)
+        ENDIF
+        ! Output of initial vertical scale factor
+        CALL iom_put("e3t_0", e3t_0(:,:,:) )
+        CALL iom_put("e3u_0", e3u_0(:,:,:) )
+        CALL iom_put("e3v_0", e3v_0(:,:,:) )
+        !
+        CALL iom_put( "e3t" , e3t_n(:,:,:) )
+        CALL iom_put( "e3u" , e3u_n(:,:,:) )
+        CALL iom_put( "e3v" , e3v_n(:,:,:) )
+        !
+      ENDIF
+      ! write the tracer concentrations in the file
+      ! ---------------------------------------
+      IF( ln_pisces  )   CALL trc_wri_pisces     ! PISCES 
+      IF( ll_cfc     )   CALL trc_wri_cfc        ! surface fluxes of CFC
+      IF( ln_c14     )   CALL trc_wri_c14        ! surface fluxes of C14
+      IF( ln_age     )   CALL trc_wri_age        ! AGE tracer
+      IF( ln_my_trc  )   CALL trc_wri_my_trc     ! MY_TRC  tracers
+      !
+      IF( ln_timing )   CALL timing_stop('trc_wri')
+      !
+   END SUBROUTINE trc_wri
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Dummy module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+   PUBLIC trc_wri
+CONTAINS
+   SUBROUTINE trc_wri( kt )                     ! Empty routine   
+   INTEGER, INTENT(in) :: kt
+   END SUBROUTINE trc_wri
+#endif
+
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!======================================================================
+END MODULE trcwri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca025
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca025	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca025	(revision 14097)
@@ -0,0 +1,639 @@
+    nb_cores 1 ( 1 x 1 ), nb_points 1740494 ( 1442 x 1207 )
+    nb_cores 2 ( 2 x 1 ), nb_points 871454 ( 722 x 1207 )
+    nb_cores 3 ( 3 x 1 ), nb_points 581774 ( 482 x 1207 )
+    nb_cores 4 ( 2 x 2 ), nb_points 436810 ( 722 x 605 )
+    nb_cores 5 ( 5 x 1 ), nb_points 350030 ( 290 x 1207 )
+    nb_cores 6 ( 3 x 2 ), nb_points 291610 ( 482 x 605 )
+    nb_cores 7 ( 7 x 1 ), nb_points 251056 ( 208 x 1207 )
+    nb_cores 8 ( 4 x 2 ), nb_points 219010 ( 362 x 605 )
+    nb_cores 9 ( 3 x 3 ), nb_points 194728 ( 482 x 404 )
+    nb_cores 10 ( 2 x 5 ), nb_points 175446 ( 722 x 243 )
+    nb_cores 11 ( 11 x 1 ), nb_points 160531 ( 133 x 1207 )
+    nb_cores 12 ( 4 x 3 ), nb_points 146248 ( 362 x 404 )
+    nb_cores 13 ( 13 x 1 ), nb_points 136391 ( 113 x 1207 )
+    nb_cores 14 ( 7 x 2 ), nb_points 125840 ( 208 x 605 )
+    nb_cores 15 ( 3 x 5 ), nb_points 117126 ( 482 x 243 )
+    nb_cores 16 ( 4 x 4 ), nb_points 110048 ( 362 x 304 )
+    nb_cores 17 ( 17 x 1 ), nb_points 105009 ( 87 x 1207 )
+    nb_cores 18 ( 6 x 3 ), nb_points 97768 ( 242 x 404 )
+    nb_cores 19 ( 19 x 1 ), nb_points 94146 ( 78 x 1207 )
+    nb_cores 20 ( 4 x 5 ), nb_points 87966 ( 362 x 243 )
+    nb_cores 21 ( 7 x 3 ), nb_points 84032 ( 208 x 404 )
+    nb_cores 22 ( 11 x 2 ), nb_points 80465 ( 133 x 605 )
+    nb_cores 23 ( 23 x 1 ), nb_points 78455 ( 65 x 1207 )
+    nb_cores 24 ( 4 x 6 ), nb_points 73486 ( 362 x 203 )
+    nb_cores 25 ( 5 x 5 ), nb_points 70470 ( 290 x 243 )
+    nb_cores 26 ( 13 x 2 ), nb_points 68365 ( 113 x 605 )
+    nb_cores 27 ( 9 x 3 ), nb_points 65448 ( 162 x 404 )
+    nb_cores 28 ( 7 x 4 ), nb_points 63232 ( 208 x 304 )
+    nb_cores 29 ( 29 x 1 ), nb_points 62764 ( 52 x 1207 )
+    nb_cores 30 ( 6 x 5 ), nb_points 58806 ( 242 x 243 )
+    nb_cores 32 ( 8 x 4 ), nb_points 55328 ( 182 x 304 )
+    nb_cores 33 ( 11 x 3 ), nb_points 53732 ( 133 x 404 )
+    nb_cores 34 ( 17 x 2 ), nb_points 52635 ( 87 x 605 )
+    nb_cores 35 ( 7 x 5 ), nb_points 50544 ( 208 x 243 )
+    nb_cores 36 ( 6 x 6 ), nb_points 49126 ( 242 x 203 )
+    nb_cores 38 ( 19 x 2 ), nb_points 47190 ( 78 x 605 )
+    nb_cores 39 ( 13 x 3 ), nb_points 45652 ( 113 x 404 )
+    nb_cores 40 ( 8 x 5 ), nb_points 44226 ( 182 x 243 )
+    nb_cores 42 ( 7 x 6 ), nb_points 42224 ( 208 x 203 )
+    nb_cores 44 ( 11 x 4 ), nb_points 40432 ( 133 x 304 )
+    nb_cores 45 ( 9 x 5 ), nb_points 39366 ( 162 x 243 )
+    nb_cores 46 ( 23 x 2 ), nb_points 39325 ( 65 x 605 )
+    nb_cores 48 ( 8 x 6 ), nb_points 36946 ( 182 x 203 )
+    nb_cores 49 ( 7 x 7 ), nb_points 36400 ( 208 x 175 )
+    nb_cores 50 ( 10 x 5 ), nb_points 35478 ( 146 x 243 )
+    nb_cores 51 ( 17 x 3 ), nb_points 35148 ( 87 x 404 )
+    nb_cores 52 ( 13 x 4 ), nb_points 34352 ( 113 x 304 )
+    nb_cores 54 ( 9 x 6 ), nb_points 32886 ( 162 x 203 )
+    nb_cores 55 ( 11 x 5 ), nb_points 32319 ( 133 x 243 )
+    nb_cores 56 ( 7 x 8 ), nb_points 31824 ( 208 x 153 )
+    nb_cores 57 ( 19 x 3 ), nb_points 31512 ( 78 x 404 )
+    nb_cores 58 ( 29 x 2 ), nb_points 31460 ( 52 x 605 )
+    nb_cores 60 ( 10 x 6 ), nb_points 29638 ( 146 x 203 )
+    nb_cores 62 ( 2 x 31 ), nb_points 29602 ( 722 x 41 )
+    nb_cores 63 ( 7 x 9 ), nb_points 28288 ( 208 x 136 )
+    nb_cores 64 ( 8 x 8 ), nb_points 27846 ( 182 x 153 )
+    nb_cores 65 ( 13 x 5 ), nb_points 27459 ( 113 x 243 )
+    nb_cores 66 ( 11 x 6 ), nb_points 26999 ( 133 x 203 )
+    nb_cores 68 ( 4 x 17 ), nb_points 26426 ( 362 x 73 )
+    nb_cores 69 ( 23 x 3 ), nb_points 26260 ( 65 x 404 )
+    nb_cores 70 ( 14 x 5 ), nb_points 25515 ( 105 x 243 )
+    nb_cores 72 ( 8 x 9 ), nb_points 24752 ( 182 x 136 )
+    nb_cores 75 ( 15 x 5 ), nb_points 23814 ( 98 x 243 )
+    nb_cores 76 ( 19 x 4 ), nb_points 23712 ( 78 x 304 )
+    nb_cores 77 ( 11 x 7 ), nb_points 23275 ( 133 x 175 )
+    nb_cores 78 ( 13 x 6 ), nb_points 22939 ( 113 x 203 )
+    nb_cores 80 ( 10 x 8 ), nb_points 22338 ( 146 x 153 )
+    nb_cores 81 ( 9 x 9 ), nb_points 22032 ( 162 x 136 )
+    nb_cores 84 ( 14 x 6 ), nb_points 21315 ( 105 x 203 )
+    nb_cores 85 ( 17 x 5 ), nb_points 21141 ( 87 x 243 )
+    nb_cores 87 ( 29 x 3 ), nb_points 21008 ( 52 x 404 )
+    nb_cores 88 ( 11 x 8 ), nb_points 20349 ( 133 x 153 )
+    nb_cores 90 ( 10 x 9 ), nb_points 19856 ( 146 x 136 )
+    nb_cores 91 ( 7 x 13 ), nb_points 19760 ( 208 x 95 )
+    nb_cores 95 ( 19 x 5 ), nb_points 18954 ( 78 x 243 )
+    nb_cores 96 ( 12 x 8 ), nb_points 18666 ( 122 x 153 )
+    nb_cores 98 ( 14 x 7 ), nb_points 18375 ( 105 x 175 )
+    nb_cores 99 ( 11 x 9 ), nb_points 18088 ( 133 x 136 )
+    nb_cores 100 ( 10 x 10 ), nb_points 17958 ( 146 x 123 )
+    nb_cores 102 ( 17 x 6 ), nb_points 17661 ( 87 x 203 )
+    nb_cores 104 ( 13 x 8 ), nb_points 17289 ( 113 x 153 )
+    nb_cores 105 ( 15 x 7 ), nb_points 17150 ( 98 x 175 )
+    nb_cores 108 ( 12 x 9 ), nb_points 16592 ( 122 x 136 )
+    nb_cores 110 ( 10 x 11 ), nb_points 16352 ( 146 x 112 )
+    nb_cores 112 ( 14 x 8 ), nb_points 16065 ( 105 x 153 )
+    nb_cores 114 ( 19 x 6 ), nb_points 15834 ( 78 x 203 )
+    nb_cores 115 ( 23 x 5 ), nb_points 15795 ( 65 x 243 )
+    nb_cores 117 ( 13 x 9 ), nb_points 15368 ( 113 x 136 )
+    nb_cores 119 ( 7 x 17 ), nb_points 15184 ( 208 x 73 )
+    nb_cores 120 ( 15 x 8 ), nb_points 14994 ( 98 x 153 )
+    nb_cores 121 ( 11 x 11 ), nb_points 14896 ( 133 x 112 )
+    nb_cores 124 ( 4 x 31 ), nb_points 14842 ( 362 x 41 )
+    nb_cores 125 ( 25 x 5 ), nb_points 14580 ( 60 x 243 )
+    nb_cores 126 ( 14 x 9 ), nb_points 14280 ( 105 x 136 )
+    nb_cores 128 ( 16 x 8 ), nb_points 14076 ( 92 x 153 )
+    nb_cores 130 ( 10 x 13 ), nb_points 13870 ( 146 x 95 )
+    nb_cores 132 ( 12 x 11 ), nb_points 13664 ( 122 x 112 )
+    nb_cores 133 ( 19 x 7 ), nb_points 13650 ( 78 x 175 )
+    nb_cores 135 ( 15 x 9 ), nb_points 13328 ( 98 x 136 )
+    nb_cores 136 ( 8 x 17 ), nb_points 13286 ( 182 x 73 )
+    nb_cores 138 ( 23 x 6 ), nb_points 13195 ( 65 x 203 )
+    nb_cores 140 ( 14 x 10 ), nb_points 12915 ( 105 x 123 )
+    nb_cores 143 ( 11 x 13 ), nb_points 12635 ( 133 x 95 )
+    nb_cores 144 ( 16 x 9 ), nb_points 12512 ( 92 x 136 )
+    nb_cores 147 ( 21 x 7 ), nb_points 12425 ( 71 x 175 )
+    nb_cores 150 ( 15 x 10 ), nb_points 12054 ( 98 x 123 )
+    nb_cores 152 ( 19 x 8 ), nb_points 11934 ( 78 x 153 )
+    nb_cores 153 ( 9 x 17 ), nb_points 11826 ( 162 x 73 )
+    nb_cores 154 ( 14 x 11 ), nb_points 11760 ( 105 x 112 )
+    nb_cores 156 ( 12 x 13 ), nb_points 11590 ( 122 x 95 )
+    nb_cores 160 ( 16 x 10 ), nb_points 11316 ( 92 x 123 )
+    nb_cores 162 ( 18 x 9 ), nb_points 11152 ( 82 x 136 )
+    nb_cores 165 ( 15 x 11 ), nb_points 10976 ( 98 x 112 )
+    nb_cores 168 ( 14 x 12 ), nb_points 10815 ( 105 x 103 )
+    nb_cores 169 ( 13 x 13 ), nb_points 10735 ( 113 x 95 )
+    nb_cores 170 ( 10 x 17 ), nb_points 10658 ( 146 x 73 )
+    nb_cores 171 ( 19 x 9 ), nb_points 10608 ( 78 x 136 )
+    nb_cores 174 ( 29 x 6 ), nb_points 10556 ( 52 x 203 )
+    nb_cores 175 ( 25 x 7 ), nb_points 10500 ( 60 x 175 )
+    nb_cores 176 ( 16 x 11 ), nb_points 10304 ( 92 x 112 )
+    nb_cores 180 ( 20 x 9 ), nb_points 10064 ( 74 x 136 )
+    nb_cores 182 ( 14 x 13 ), nb_points 9975 ( 105 x 95 )
+    nb_cores 184 ( 23 x 8 ), nb_points 9945 ( 65 x 153 )
+    nb_cores 186 ( 6 x 31 ), nb_points 9922 ( 242 x 41 )
+    nb_cores 187 ( 11 x 17 ), nb_points 9709 ( 133 x 73 )
+    nb_cores 189 ( 21 x 9 ), nb_points 9656 ( 71 x 136 )
+    nb_cores 190 ( 19 x 10 ), nb_points 9594 ( 78 x 123 )
+    nb_cores 192 ( 16 x 12 ), nb_points 9476 ( 92 x 103 )
+    nb_cores 195 ( 15 x 13 ), nb_points 9310 ( 98 x 95 )
+    nb_cores 198 ( 11 x 18 ), nb_points 9177 ( 133 x 69 )
+    nb_cores 200 ( 20 x 10 ), nb_points 9102 ( 74 x 123 )
+    nb_cores 203 ( 29 x 7 ), nb_points 9100 ( 52 x 175 )
+    nb_cores 204 ( 12 x 17 ), nb_points 8906 ( 122 x 73 )
+    nb_cores 207 ( 23 x 9 ), nb_points 8840 ( 65 x 136 )
+    nb_cores 208 ( 16 x 13 ), nb_points 8740 ( 92 x 95 )
+    nb_cores 209 ( 19 x 11 ), nb_points 8736 ( 78 x 112 )
+    nb_cores 210 ( 14 x 15 ), nb_points 8715 ( 105 x 83 )
+    nb_cores 216 ( 12 x 18 ), nb_points 8418 ( 122 x 69 )
+    nb_cores 220 ( 20 x 11 ), nb_points 8288 ( 74 x 112 )
+    nb_cores 221 ( 13 x 17 ), nb_points 8249 ( 113 x 73 )
+    nb_cores 224 ( 16 x 14 ), nb_points 8188 ( 92 x 89 )
+    nb_cores 225 ( 15 x 15 ), nb_points 8134 ( 98 x 83 )
+    nb_cores 228 ( 19 x 12 ), nb_points 8034 ( 78 x 103 )
+    nb_cores 230 ( 23 x 10 ), nb_points 7995 ( 65 x 123 )
+    nb_cores 231 ( 21 x 11 ), nb_points 7952 ( 71 x 112 )
+    nb_cores 234 ( 18 x 13 ), nb_points 7790 ( 82 x 95 )
+    nb_cores 238 ( 14 x 17 ), nb_points 7665 ( 105 x 73 )
+    nb_cores 240 ( 20 x 12 ), nb_points 7622 ( 74 x 103 )
+    nb_cores 242 ( 11 x 22 ), nb_points 7581 ( 133 x 57 )
+    nb_cores 247 ( 19 x 13 ), nb_points 7410 ( 78 x 95 )
+    nb_cores 250 ( 25 x 10 ), nb_points 7380 ( 60 x 123 )
+    nb_cores 252 ( 14 x 18 ), nb_points 7245 ( 105 x 69 )
+    nb_cores 255 ( 15 x 17 ), nb_points 7154 ( 98 x 73 )
+    nb_cores 260 ( 20 x 13 ), nb_points 7030 ( 74 x 95 )
+    nb_cores 264 ( 24 x 11 ), nb_points 6944 ( 62 x 112 )
+    nb_cores 266 ( 14 x 19 ), nb_points 6930 ( 105 x 66 )
+    nb_cores 270 ( 15 x 18 ), nb_points 6762 ( 98 x 69 )
+    nb_cores 272 ( 16 x 17 ), nb_points 6716 ( 92 x 73 )
+    nb_cores 276 ( 23 x 12 ), nb_points 6695 ( 65 x 103 )
+    nb_cores 279 ( 9 x 31 ), nb_points 6642 ( 162 x 41 )
+    nb_cores 280 ( 20 x 14 ), nb_points 6586 ( 74 x 89 )
+    nb_cores 285 ( 15 x 19 ), nb_points 6468 ( 98 x 66 )
+    nb_cores 286 ( 13 x 22 ), nb_points 6441 ( 113 x 57 )
+    nb_cores 288 ( 16 x 18 ), nb_points 6348 ( 92 x 69 )
+    nb_cores 294 ( 14 x 21 ), nb_points 6300 ( 105 x 60 )
+    nb_cores 296 ( 37 x 8 ), nb_points 6273 ( 41 x 153 )
+    nb_cores 297 ( 11 x 27 ), nb_points 6251 ( 133 x 47 )
+    nb_cores 299 ( 23 x 13 ), nb_points 6175 ( 65 x 95 )
+    nb_cores 300 ( 20 x 15 ), nb_points 6142 ( 74 x 83 )
+    nb_cores 304 ( 16 x 19 ), nb_points 6072 ( 92 x 66 )
+    nb_cores 306 ( 18 x 17 ), nb_points 5986 ( 82 x 73 )
+    nb_cores 308 ( 14 x 22 ), nb_points 5985 ( 105 x 57 )
+    nb_cores 312 ( 24 x 13 ), nb_points 5890 ( 62 x 95 )
+    nb_cores 315 ( 15 x 21 ), nb_points 5880 ( 98 x 60 )
+    nb_cores 319 ( 29 x 11 ), nb_points 5824 ( 52 x 112 )
+    nb_cores 320 ( 20 x 16 ), nb_points 5772 ( 74 x 78 )
+    nb_cores 323 ( 19 x 17 ), nb_points 5694 ( 78 x 73 )
+    nb_cores 324 ( 18 x 18 ), nb_points 5658 ( 82 x 69 )
+    nb_cores 330 ( 15 x 22 ), nb_points 5586 ( 98 x 57 )
+    nb_cores 333 ( 37 x 9 ), nb_points 5576 ( 41 x 136 )
+    nb_cores 336 ( 24 x 14 ), nb_points 5518 ( 62 x 89 )
+    nb_cores 338 ( 26 x 13 ), nb_points 5510 ( 58 x 95 )
+    nb_cores 340 ( 20 x 17 ), nb_points 5402 ( 74 x 73 )
+    nb_cores 342 ( 19 x 18 ), nb_points 5382 ( 78 x 69 )
+    nb_cores 348 ( 29 x 12 ), nb_points 5356 ( 52 x 103 )
+    nb_cores 350 ( 25 x 14 ), nb_points 5340 ( 60 x 89 )
+    nb_cores 351 ( 39 x 9 ), nb_points 5304 ( 39 x 136 )
+    nb_cores 352 ( 16 x 22 ), nb_points 5244 ( 92 x 57 )
+    nb_cores 357 ( 21 x 17 ), nb_points 5183 ( 71 x 73 )
+    nb_cores 360 ( 20 x 18 ), nb_points 5106 ( 74 x 69 )
+    nb_cores 368 ( 16 x 23 ), nb_points 5060 ( 92 x 55 )
+    nb_cores 370 ( 37 x 10 ), nb_points 5043 ( 41 x 123 )
+    nb_cores 372 ( 12 x 31 ), nb_points 5002 ( 122 x 41 )
+    nb_cores 374 ( 17 x 22 ), nb_points 4959 ( 87 x 57 )
+    nb_cores 377 ( 29 x 13 ), nb_points 4940 ( 52 x 95 )
+    nb_cores 378 ( 21 x 18 ), nb_points 4899 ( 71 x 69 )
+    nb_cores 380 ( 20 x 19 ), nb_points 4884 ( 74 x 66 )
+    nb_cores 384 ( 24 x 16 ), nb_points 4836 ( 62 x 78 )
+    nb_cores 390 ( 30 x 13 ), nb_points 4750 ( 50 x 95 )
+    nb_cores 391 ( 23 x 17 ), nb_points 4745 ( 65 x 73 )
+    nb_cores 396 ( 18 x 22 ), nb_points 4674 ( 82 x 57 )
+    nb_cores 400 ( 20 x 20 ), nb_points 4662 ( 74 x 63 )
+    nb_cores 403 ( 13 x 31 ), nb_points 4633 ( 113 x 41 )
+    nb_cores 405 ( 15 x 27 ), nb_points 4606 ( 98 x 47 )
+    nb_cores 407 ( 37 x 11 ), nb_points 4592 ( 41 x 112 )
+    nb_cores 408 ( 24 x 17 ), nb_points 4526 ( 62 x 73 )
+    nb_cores 414 ( 23 x 18 ), nb_points 4485 ( 65 x 69 )
+    nb_cores 416 ( 32 x 13 ), nb_points 4465 ( 47 x 95 )
+    nb_cores 418 ( 19 x 22 ), nb_points 4446 ( 78 x 57 )
+    nb_cores 420 ( 20 x 21 ), nb_points 4440 ( 74 x 60 )
+    nb_cores 425 ( 25 x 17 ), nb_points 4380 ( 60 x 73 )
+    nb_cores 429 ( 39 x 11 ), nb_points 4368 ( 39 x 112 )
+    nb_cores 432 ( 24 x 18 ), nb_points 4278 ( 62 x 69 )
+    nb_cores 440 ( 20 x 22 ), nb_points 4218 ( 74 x 57 )
+    nb_cores 448 ( 32 x 14 ), nb_points 4183 ( 47 x 89 )
+    nb_cores 450 ( 25 x 18 ), nb_points 4140 ( 60 x 69 )
+    nb_cores 456 ( 24 x 19 ), nb_points 4092 ( 62 x 66 )
+    nb_cores 459 ( 27 x 17 ), nb_points 4088 ( 56 x 73 )
+    nb_cores 460 ( 20 x 23 ), nb_points 4070 ( 74 x 55 )
+    nb_cores 462 ( 21 x 22 ), nb_points 4047 ( 71 x 57 )
+    nb_cores 465 ( 15 x 31 ), nb_points 4018 ( 98 x 41 )
+    nb_cores 468 ( 36 x 13 ), nb_points 3990 ( 42 x 95 )
+    nb_cores 475 ( 25 x 19 ), nb_points 3960 ( 60 x 66 )
+    nb_cores 476 ( 28 x 17 ), nb_points 3942 ( 54 x 73 )
+    nb_cores 480 ( 30 x 16 ), nb_points 3900 ( 50 x 78 )
+    nb_cores 481 ( 37 x 13 ), nb_points 3895 ( 41 x 95 )
+    nb_cores 484 ( 22 x 22 ), nb_points 3876 ( 68 x 57 )
+    nb_cores 486 ( 18 x 27 ), nb_points 3854 ( 82 x 47 )
+    nb_cores 493 ( 29 x 17 ), nb_points 3796 ( 52 x 73 )
+    nb_cores 496 ( 16 x 31 ), nb_points 3772 ( 92 x 41 )
+    nb_cores 504 ( 24 x 21 ), nb_points 3720 ( 62 x 60 )
+    nb_cores 506 ( 23 x 22 ), nb_points 3705 ( 65 x 57 )
+    nb_cores 510 ( 30 x 17 ), nb_points 3650 ( 50 x 73 )
+    nb_cores 518 ( 37 x 14 ), nb_points 3649 ( 41 x 89 )
+    nb_cores 520 ( 40 x 13 ), nb_points 3610 ( 38 x 95 )
+    nb_cores 522 ( 29 x 18 ), nb_points 3588 ( 52 x 69 )
+    nb_cores 527 ( 17 x 31 ), nb_points 3567 ( 87 x 41 )
+    nb_cores 528 ( 24 x 22 ), nb_points 3534 ( 62 x 57 )
+    nb_cores 540 ( 30 x 18 ), nb_points 3450 ( 50 x 69 )
+    nb_cores 544 ( 32 x 17 ), nb_points 3431 ( 47 x 73 )
+    nb_cores 550 ( 25 x 22 ), nb_points 3420 ( 60 x 57 )
+    nb_cores 552 ( 24 x 23 ), nb_points 3410 ( 62 x 55 )
+    nb_cores 555 ( 37 x 15 ), nb_points 3403 ( 41 x 83 )
+    nb_cores 558 ( 18 x 31 ), nb_points 3362 ( 82 x 41 )
+    nb_cores 561 ( 33 x 17 ), nb_points 3358 ( 46 x 73 )
+    nb_cores 567 ( 21 x 27 ), nb_points 3337 ( 71 x 47 )
+    nb_cores 570 ( 30 x 19 ), nb_points 3300 ( 50 x 66 )
+    nb_cores 576 ( 32 x 18 ), nb_points 3243 ( 47 x 69 )
+    nb_cores 585 ( 45 x 13 ), nb_points 3230 ( 34 x 95 )
+    nb_cores 589 ( 19 x 31 ), nb_points 3198 ( 78 x 41 )
+    nb_cores 594 ( 33 x 18 ), nb_points 3174 ( 46 x 69 )
+    nb_cores 600 ( 30 x 20 ), nb_points 3150 ( 50 x 63 )
+    nb_cores 608 ( 32 x 19 ), nb_points 3102 ( 47 x 66 )
+    nb_cores 612 ( 36 x 17 ), nb_points 3066 ( 42 x 73 )
+    nb_cores 620 ( 20 x 31 ), nb_points 3034 ( 74 x 41 )
+    nb_cores 629 ( 37 x 17 ), nb_points 2993 ( 41 x 73 )
+    nb_cores 638 ( 29 x 22 ), nb_points 2964 ( 52 x 57 )
+    nb_cores 640 ( 20 x 32 ), nb_points 2960 ( 74 x 40 )
+    nb_cores 646 ( 38 x 17 ), nb_points 2920 ( 40 x 73 )
+    nb_cores 648 ( 36 x 18 ), nb_points 2898 ( 42 x 69 )
+    nb_cores 660 ( 30 x 22 ), nb_points 2850 ( 50 x 57 )
+    nb_cores 663 ( 39 x 17 ), nb_points 2847 ( 39 x 73 )
+    nb_cores 666 ( 37 x 18 ), nb_points 2829 ( 41 x 69 )
+    nb_cores 672 ( 32 x 21 ), nb_points 2820 ( 47 x 60 )
+    nb_cores 680 ( 40 x 17 ), nb_points 2774 ( 38 x 73 )
+    nb_cores 684 ( 38 x 18 ), nb_points 2760 ( 40 x 69 )
+    nb_cores 690 ( 30 x 23 ), nb_points 2750 ( 50 x 55 )
+    nb_cores 696 ( 24 x 29 ), nb_points 2728 ( 62 x 44 )
+    nb_cores 702 ( 39 x 18 ), nb_points 2691 ( 39 x 69 )
+    nb_cores 704 ( 32 x 22 ), nb_points 2679 ( 47 x 57 )
+    nb_cores 713 ( 23 x 31 ), nb_points 2665 ( 65 x 41 )
+    nb_cores 720 ( 40 x 18 ), nb_points 2622 ( 38 x 69 )
+    nb_cores 736 ( 32 x 23 ), nb_points 2585 ( 47 x 55 )
+    nb_cores 740 ( 37 x 20 ), nb_points 2583 ( 41 x 63 )
+    nb_cores 741 ( 19 x 39 ), nb_points 2574 ( 78 x 33 )
+    nb_cores 741 ( 39 x 19 ), nb_points 2574 ( 39 x 66 )
+    nb_cores 744 ( 24 x 31 ), nb_points 2542 ( 62 x 41 )
+    nb_cores 756 ( 36 x 21 ), nb_points 2520 ( 42 x 60 )
+    nb_cores 760 ( 40 x 19 ), nb_points 2508 ( 38 x 66 )
+    nb_cores 765 ( 45 x 17 ), nb_points 2482 ( 34 x 73 )
+    nb_cores 768 ( 24 x 32 ), nb_points 2480 ( 62 x 40 )
+    nb_cores 775 ( 25 x 31 ), nb_points 2460 ( 60 x 41 )
+    nb_cores 780 ( 20 x 39 ), nb_points 2442 ( 74 x 33 )
+    nb_cores 792 ( 36 x 22 ), nb_points 2394 ( 42 x 57 )
+    nb_cores 806 ( 26 x 31 ), nb_points 2378 ( 58 x 41 )
+    nb_cores 810 ( 45 x 18 ), nb_points 2346 ( 34 x 69 )
+    nb_cores 814 ( 37 x 22 ), nb_points 2337 ( 41 x 57 )
+    nb_cores 816 ( 48 x 17 ), nb_points 2336 ( 32 x 73 )
+    nb_cores 828 ( 36 x 23 ), nb_points 2310 ( 42 x 55 )
+    nb_cores 832 ( 32 x 26 ), nb_points 2303 ( 47 x 49 )
+    nb_cores 836 ( 38 x 22 ), nb_points 2280 ( 40 x 57 )
+    nb_cores 846 ( 47 x 18 ), nb_points 2277 ( 33 x 69 )
+    nb_cores 850 ( 50 x 17 ), nb_points 2263 ( 31 x 73 )
+    nb_cores 851 ( 37 x 23 ), nb_points 2255 ( 41 x 55 )
+    nb_cores 855 ( 45 x 19 ), nb_points 2244 ( 34 x 66 )
+    nb_cores 858 ( 39 x 22 ), nb_points 2223 ( 39 x 57 )
+    nb_cores 864 ( 48 x 18 ), nb_points 2208 ( 32 x 69 )
+    nb_cores 870 ( 30 x 29 ), nb_points 2200 ( 50 x 44 )
+    nb_cores 880 ( 40 x 22 ), nb_points 2166 ( 38 x 57 )
+    nb_cores 891 ( 33 x 27 ), nb_points 2162 ( 46 x 47 )
+    nb_cores 896 ( 28 x 32 ), nb_points 2160 ( 54 x 40 )
+    nb_cores 897 ( 23 x 39 ), nb_points 2145 ( 65 x 33 )
+    nb_cores 897 ( 39 x 23 ), nb_points 2145 ( 39 x 55 )
+    nb_cores 899 ( 29 x 31 ), nb_points 2132 ( 52 x 41 )
+    nb_cores 912 ( 24 x 38 ), nb_points 2108 ( 62 x 34 )
+    nb_cores 920 ( 40 x 23 ), nb_points 2090 ( 38 x 55 )
+    nb_cores 928 ( 32 x 29 ), nb_points 2068 ( 47 x 44 )
+    nb_cores 930 ( 30 x 31 ), nb_points 2050 ( 50 x 41 )
+    nb_cores 936 ( 24 x 39 ), nb_points 2046 ( 62 x 33 )
+    nb_cores 945 ( 45 x 21 ), nb_points 2040 ( 34 x 60 )
+    nb_cores 957 ( 33 x 29 ), nb_points 2024 ( 46 x 44 )
+    nb_cores 960 ( 30 x 32 ), nb_points 2000 ( 50 x 40 )
+    nb_cores 968 ( 44 x 22 ), nb_points 1995 ( 35 x 57 )
+    nb_cores 972 ( 36 x 27 ), nb_points 1974 ( 42 x 47 )
+    nb_cores 986 ( 58 x 17 ), nb_points 1971 ( 27 x 73 )
+    nb_cores 988 ( 38 x 26 ), nb_points 1960 ( 40 x 49 )
+    nb_cores 990 ( 45 x 22 ), nb_points 1938 ( 34 x 57 )
+    nb_cores 992 ( 32 x 31 ), nb_points 1927 ( 47 x 41 )
+    nb_cores 1008 ( 48 x 21 ), nb_points 1920 ( 32 x 60 )
+    nb_cores 1014 ( 39 x 26 ), nb_points 1911 ( 39 x 49 )
+    nb_cores 1020 ( 60 x 17 ), nb_points 1898 ( 26 x 73 )
+    nb_cores 1023 ( 33 x 31 ), nb_points 1886 ( 46 x 41 )
+    nb_cores 1024 ( 32 x 32 ), nb_points 1880 ( 47 x 40 )
+    nb_cores 1035 ( 45 x 23 ), nb_points 1870 ( 34 x 55 )
+    nb_cores 1040 ( 40 x 26 ), nb_points 1862 ( 38 x 49 )
+    nb_cores 1044 ( 36 x 29 ), nb_points 1848 ( 42 x 44 )
+    nb_cores 1053 ( 39 x 27 ), nb_points 1833 ( 39 x 47 )
+    nb_cores 1056 ( 48 x 22 ), nb_points 1824 ( 32 x 57 )
+    nb_cores 1073 ( 37 x 29 ), nb_points 1804 ( 41 x 44 )
+    nb_cores 1080 ( 40 x 27 ), nb_points 1786 ( 38 x 47 )
+    nb_cores 1092 ( 28 x 39 ), nb_points 1782 ( 54 x 33 )
+    nb_cores 1100 ( 50 x 22 ), nb_points 1767 ( 31 x 57 )
+    nb_cores 1102 ( 38 x 29 ), nb_points 1760 ( 40 x 44 )
+    nb_cores 1110 ( 30 x 37 ), nb_points 1750 ( 50 x 35 )
+    nb_cores 1116 ( 36 x 31 ), nb_points 1722 ( 42 x 41 )
+    nb_cores 1131 ( 39 x 29 ), nb_points 1716 ( 39 x 44 )
+    nb_cores 1131 ( 29 x 39 ), nb_points 1716 ( 52 x 33 )
+    nb_cores 1140 ( 30 x 38 ), nb_points 1700 ( 50 x 34 )
+    nb_cores 1147 ( 37 x 31 ), nb_points 1681 ( 41 x 41 )
+    nb_cores 1152 ( 36 x 32 ), nb_points 1680 ( 42 x 40 )
+    nb_cores 1160 ( 40 x 29 ), nb_points 1672 ( 38 x 44 )
+    nb_cores 1170 ( 30 x 39 ), nb_points 1650 ( 50 x 33 )
+    nb_cores 1178 ( 38 x 31 ), nb_points 1640 ( 40 x 41 )
+    nb_cores 1188 ( 36 x 33 ), nb_points 1638 ( 42 x 39 )
+    nb_cores 1200 ( 48 x 25 ), nb_points 1632 ( 32 x 51 )
+    nb_cores 1209 ( 39 x 31 ), nb_points 1599 ( 39 x 41 )
+    nb_cores 1215 ( 45 x 27 ), nb_points 1598 ( 34 x 47 )
+    nb_cores 1224 ( 36 x 34 ), nb_points 1596 ( 42 x 38 )
+    nb_cores 1240 ( 40 x 31 ), nb_points 1558 ( 38 x 41 )
+    nb_cores 1248 ( 32 x 39 ), nb_points 1551 ( 47 x 33 )
+    nb_cores 1260 ( 30 x 42 ), nb_points 1550 ( 50 x 31 )
+    nb_cores 1276 ( 58 x 22 ), nb_points 1539 ( 27 x 57 )
+    nb_cores 1280 ( 40 x 32 ), nb_points 1520 ( 38 x 40 )
+    nb_cores 1287 ( 33 x 39 ), nb_points 1518 ( 46 x 33 )
+    nb_cores 1295 ( 37 x 35 ), nb_points 1517 ( 41 x 37 )
+    nb_cores 1296 ( 48 x 27 ), nb_points 1504 ( 32 x 47 )
+    nb_cores 1305 ( 45 x 29 ), nb_points 1496 ( 34 x 44 )
+    nb_cores 1320 ( 40 x 33 ), nb_points 1482 ( 38 x 39 )
+    nb_cores 1320 ( 60 x 22 ), nb_points 1482 ( 26 x 57 )
+    nb_cores 1330 ( 38 x 35 ), nb_points 1480 ( 40 x 37 )
+    nb_cores 1332 ( 36 x 37 ), nb_points 1470 ( 42 x 35 )
+    nb_cores 1344 ( 32 x 42 ), nb_points 1457 ( 47 x 31 )
+    nb_cores 1350 ( 30 x 45 ), nb_points 1450 ( 50 x 29 )
+    nb_cores 1360 ( 40 x 34 ), nb_points 1444 ( 38 x 38 )
+    nb_cores 1364 ( 44 x 31 ), nb_points 1435 ( 35 x 41 )
+    nb_cores 1368 ( 36 x 38 ), nb_points 1428 ( 42 x 34 )
+    nb_cores 1386 ( 63 x 22 ), nb_points 1425 ( 25 x 57 )
+    nb_cores 1392 ( 48 x 29 ), nb_points 1408 ( 32 x 44 )
+    nb_cores 1395 ( 45 x 31 ), nb_points 1394 ( 34 x 41 )
+    nb_cores 1404 ( 36 x 39 ), nb_points 1386 ( 42 x 33 )
+    nb_cores 1440 ( 45 x 32 ), nb_points 1360 ( 34 x 40 )
+    nb_cores 1443 ( 37 x 39 ), nb_points 1353 ( 41 x 33 )
+    nb_cores 1470 ( 30 x 49 ), nb_points 1350 ( 50 x 27 )
+    nb_cores 1476 ( 36 x 41 ), nb_points 1344 ( 42 x 32 )
+    nb_cores 1480 ( 40 x 37 ), nb_points 1330 ( 38 x 35 )
+    nb_cores 1482 ( 38 x 39 ), nb_points 1320 ( 40 x 33 )
+    nb_cores 1488 ( 48 x 31 ), nb_points 1312 ( 32 x 41 )
+    nb_cores 1512 ( 36 x 42 ), nb_points 1302 ( 42 x 31 )
+    nb_cores 1520 ( 40 x 38 ), nb_points 1292 ( 38 x 34 )
+    nb_cores 1521 ( 39 x 39 ), nb_points 1287 ( 39 x 33 )
+    nb_cores 1536 ( 48 x 32 ), nb_points 1280 ( 32 x 40 )
+    nb_cores 1550 ( 50 x 31 ), nb_points 1271 ( 31 x 41 )
+    nb_cores 1560 ( 40 x 39 ), nb_points 1254 ( 38 x 33 )
+    nb_cores 1584 ( 48 x 33 ), nb_points 1248 ( 32 x 39 )
+    nb_cores 1596 ( 38 x 42 ), nb_points 1240 ( 40 x 31 )
+    nb_cores 1612 ( 52 x 31 ), nb_points 1230 ( 30 x 41 )
+    nb_cores 1620 ( 36 x 45 ), nb_points 1218 ( 42 x 29 )
+    nb_cores 1632 ( 48 x 34 ), nb_points 1216 ( 32 x 38 )
+    nb_cores 1638 ( 39 x 42 ), nb_points 1209 ( 39 x 31 )
+    nb_cores 1650 ( 30 x 55 ), nb_points 1200 ( 50 x 24 )
+    nb_cores 1665 ( 37 x 45 ), nb_points 1189 ( 41 x 29 )
+    nb_cores 1677 ( 43 x 39 ), nb_points 1188 ( 36 x 33 )
+    nb_cores 1680 ( 40 x 42 ), nb_points 1178 ( 38 x 31 )
+    nb_cores 1692 ( 36 x 47 ), nb_points 1176 ( 42 x 28 )
+    nb_cores 1696 ( 32 x 53 ), nb_points 1175 ( 47 x 25 )
+    nb_cores 1710 ( 45 x 38 ), nb_points 1156 ( 34 x 34 )
+    nb_cores 1716 ( 44 x 39 ), nb_points 1155 ( 35 x 33 )
+    nb_cores 1728 ( 48 x 36 ), nb_points 1152 ( 32 x 36 )
+    nb_cores 1736 ( 56 x 31 ), nb_points 1148 ( 28 x 41 )
+    nb_cores 1740 ( 60 x 29 ), nb_points 1144 ( 26 x 44 )
+    nb_cores 1755 ( 45 x 39 ), nb_points 1122 ( 34 x 33 )
+    nb_cores 1776 ( 48 x 37 ), nb_points 1120 ( 32 x 35 )
+    nb_cores 1798 ( 58 x 31 ), nb_points 1107 ( 27 x 41 )
+    nb_cores 1800 ( 40 x 45 ), nb_points 1102 ( 38 x 29 )
+    nb_cores 1824 ( 48 x 38 ), nb_points 1088 ( 32 x 34 )
+    nb_cores 1848 ( 44 x 42 ), nb_points 1085 ( 35 x 31 )
+    nb_cores 1856 ( 58 x 32 ), nb_points 1080 ( 27 x 40 )
+    nb_cores 1860 ( 60 x 31 ), nb_points 1066 ( 26 x 41 )
+    nb_cores 1872 ( 48 x 39 ), nb_points 1056 ( 32 x 33 )
+    nb_cores 1890 ( 45 x 42 ), nb_points 1054 ( 34 x 31 )
+    nb_cores 1908 ( 36 x 53 ), nb_points 1050 ( 42 x 25 )
+    nb_cores 1920 ( 60 x 32 ), nb_points 1040 ( 26 x 40 )
+    nb_cores 1944 ( 72 x 27 ), nb_points 1034 ( 22 x 47 )
+    nb_cores 1950 ( 50 x 39 ), nb_points 1023 ( 31 x 33 )
+    nb_cores 1976 ( 52 x 38 ), nb_points 1020 ( 30 x 34 )
+    nb_cores 1980 ( 36 x 55 ), nb_points 1008 ( 42 x 24 )
+    nb_cores 2010 ( 30 x 67 ), nb_points 1000 ( 50 x 20 )
+    nb_cores 2016 ( 48 x 42 ), nb_points 992 ( 32 x 31 )
+    nb_cores 2025 ( 45 x 45 ), nb_points 986 ( 34 x 29 )
+    nb_cores 2035 ( 37 x 55 ), nb_points 984 ( 41 x 24 )
+    nb_cores 2067 ( 39 x 53 ), nb_points 975 ( 39 x 25 )
+    nb_cores 2088 ( 36 x 58 ), nb_points 966 ( 42 x 23 )
+    nb_cores 2090 ( 38 x 55 ), nb_points 960 ( 40 x 24 )
+    nb_cores 2106 ( 54 x 39 ), nb_points 957 ( 29 x 33 )
+    nb_cores 2115 ( 45 x 47 ), nb_points 952 ( 34 x 28 )
+    nb_cores 2120 ( 40 x 53 ), nb_points 950 ( 38 x 25 )
+    nb_cores 2139 ( 69 x 31 ), nb_points 943 ( 23 x 41 )
+    nb_cores 2144 ( 32 x 67 ), nb_points 940 ( 47 x 20 )
+    nb_cores 2145 ( 39 x 55 ), nb_points 936 ( 39 x 24 )
+    nb_cores 2160 ( 48 x 45 ), nb_points 928 ( 32 x 29 )
+    nb_cores 2184 ( 56 x 39 ), nb_points 924 ( 28 x 33 )
+    nb_cores 2200 ( 40 x 55 ), nb_points 912 ( 38 x 24 )
+    nb_cores 2220 ( 60 x 37 ), nb_points 910 ( 26 x 35 )
+    nb_cores 2232 ( 72 x 31 ), nb_points 902 ( 22 x 41 )
+    nb_cores 2250 ( 50 x 45 ), nb_points 899 ( 31 x 29 )
+    nb_cores 2256 ( 48 x 47 ), nb_points 896 ( 32 x 28 )
+    nb_cores 2262 ( 58 x 39 ), nb_points 891 ( 27 x 33 )
+    nb_cores 2280 ( 60 x 38 ), nb_points 884 ( 26 x 34 )
+    nb_cores 2304 ( 72 x 32 ), nb_points 880 ( 22 x 40 )
+    nb_cores 2320 ( 40 x 58 ), nb_points 874 ( 38 x 23 )
+    nb_cores 2340 ( 60 x 39 ), nb_points 858 ( 26 x 33 )
+    nb_cores 2385 ( 45 x 53 ), nb_points 850 ( 34 x 25 )
+    nb_cores 2412 ( 36 x 67 ), nb_points 840 ( 42 x 20 )
+    nb_cores 2436 ( 58 x 42 ), nb_points 837 ( 27 x 31 )
+    nb_cores 2440 ( 40 x 61 ), nb_points 836 ( 38 x 22 )
+    nb_cores 2448 ( 48 x 51 ), nb_points 832 ( 32 x 26 )
+    nb_cores 2457 ( 63 x 39 ), nb_points 825 ( 25 x 33 )
+    nb_cores 2475 ( 45 x 55 ), nb_points 816 ( 34 x 24 )
+    nb_cores 2520 ( 60 x 42 ), nb_points 806 ( 26 x 31 )
+    nb_cores 2544 ( 48 x 53 ), nb_points 800 ( 32 x 25 )
+    nb_cores 2556 ( 36 x 71 ), nb_points 798 ( 42 x 19 )
+    nb_cores 2574 ( 66 x 39 ), nb_points 792 ( 24 x 33 )
+    nb_cores 2610 ( 45 x 58 ), nb_points 782 ( 34 x 23 )
+    nb_cores 2613 ( 39 x 67 ), nb_points 780 ( 39 x 20 )
+    nb_cores 2627 ( 37 x 71 ), nb_points 779 ( 41 x 19 )
+    nb_cores 2640 ( 48 x 55 ), nb_points 768 ( 32 x 24 )
+    nb_cores 2680 ( 40 x 67 ), nb_points 760 ( 38 x 20 )
+    nb_cores 2691 ( 69 x 39 ), nb_points 759 ( 23 x 33 )
+    nb_cores 2700 ( 60 x 45 ), nb_points 754 ( 26 x 29 )
+    nb_cores 2736 ( 72 x 38 ), nb_points 748 ( 22 x 34 )
+    nb_cores 2750 ( 50 x 55 ), nb_points 744 ( 31 x 24 )
+    nb_cores 2769 ( 39 x 71 ), nb_points 741 ( 39 x 19 )
+    nb_cores 2784 ( 48 x 58 ), nb_points 736 ( 32 x 23 )
+    nb_cores 2808 ( 72 x 39 ), nb_points 726 ( 22 x 33 )
+    nb_cores 2835 ( 63 x 45 ), nb_points 725 ( 25 x 29 )
+    nb_cores 2840 ( 40 x 71 ), nb_points 722 ( 38 x 19 )
+    nb_cores 2860 ( 52 x 55 ), nb_points 720 ( 30 x 24 )
+    nb_cores 2880 ( 45 x 64 ), nb_points 714 ( 34 x 21 )
+    nb_cores 2898 ( 69 x 42 ), nb_points 713 ( 23 x 31 )
+    nb_cores 2928 ( 48 x 61 ), nb_points 704 ( 32 x 22 )
+    nb_cores 2940 ( 60 x 49 ), nb_points 702 ( 26 x 27 )
+    nb_cores 2948 ( 44 x 67 ), nb_points 700 ( 35 x 20 )
+    nb_cores 2964 ( 76 x 39 ), nb_points 693 ( 21 x 33 )
+    nb_cores 3015 ( 45 x 67 ), nb_points 680 ( 34 x 20 )
+    nb_cores 3060 ( 60 x 51 ), nb_points 676 ( 26 x 26 )
+    nb_cores 3072 ( 48 x 64 ), nb_points 672 ( 32 x 21 )
+    nb_cores 3105 ( 69 x 45 ), nb_points 667 ( 23 x 29 )
+    nb_cores 3120 ( 80 x 39 ), nb_points 660 ( 20 x 33 )
+    nb_cores 3180 ( 60 x 53 ), nb_points 650 ( 26 x 25 )
+    nb_cores 3190 ( 58 x 55 ), nb_points 648 ( 27 x 24 )
+    nb_cores 3195 ( 45 x 71 ), nb_points 646 ( 34 x 19 )
+    nb_cores 3216 ( 48 x 67 ), nb_points 640 ( 32 x 20 )
+    nb_cores 3240 ( 72 x 45 ), nb_points 638 ( 22 x 29 )
+    nb_cores 3300 ( 60 x 55 ), nb_points 624 ( 26 x 24 )
+    nb_cores 3350 ( 50 x 67 ), nb_points 620 ( 31 x 20 )
+    nb_cores 3384 ( 72 x 47 ), nb_points 616 ( 22 x 28 )
+    nb_cores 3408 ( 48 x 71 ), nb_points 608 ( 32 x 19 )
+    nb_cores 3465 ( 63 x 55 ), nb_points 600 ( 25 x 24 )
+    nb_cores 3480 ( 60 x 58 ), nb_points 598 ( 26 x 23 )
+    nb_cores 3510 ( 90 x 39 ), nb_points 594 ( 18 x 33 )
+    nb_cores 3550 ( 50 x 71 ), nb_points 589 ( 31 x 19 )
+    nb_cores 3572 ( 76 x 47 ), nb_points 588 ( 21 x 28 )
+    nb_cores 3600 ( 80 x 45 ), nb_points 580 ( 20 x 29 )
+    nb_cores 3630 ( 66 x 55 ), nb_points 576 ( 24 x 24 )
+    nb_cores 3654 ( 63 x 58 ), nb_points 575 ( 25 x 23 )
+    nb_cores 3660 ( 60 x 61 ), nb_points 572 ( 26 x 22 )
+    nb_cores 3692 ( 52 x 71 ), nb_points 570 ( 30 x 19 )
+    nb_cores 3712 ( 58 x 64 ), nb_points 567 ( 27 x 21 )
+    nb_cores 3744 ( 96 x 39 ), nb_points 561 ( 17 x 33 )
+    nb_cores 3752 ( 56 x 67 ), nb_points 560 ( 28 x 20 )
+    nb_cores 3780 ( 90 x 42 ), nb_points 558 ( 18 x 31 )
+    nb_cores 3795 ( 69 x 55 ), nb_points 552 ( 23 x 24 )
+    nb_cores 3816 ( 72 x 53 ), nb_points 550 ( 22 x 25 )
+    nb_cores 3840 ( 60 x 64 ), nb_points 546 ( 26 x 21 )
+    nb_cores 3886 ( 58 x 67 ), nb_points 540 ( 27 x 20 )
+    nb_cores 3960 ( 72 x 55 ), nb_points 528 ( 22 x 24 )
+    nb_cores 4020 ( 60 x 67 ), nb_points 520 ( 26 x 20 )
+    nb_cores 4118 ( 58 x 71 ), nb_points 513 ( 27 x 19 )
+    nb_cores 4176 ( 72 x 58 ), nb_points 506 ( 22 x 23 )
+    nb_cores 4180 ( 76 x 55 ), nb_points 504 ( 21 x 24 )
+    nb_cores 4221 ( 63 x 67 ), nb_points 500 ( 25 x 20 )
+    nb_cores 4260 ( 60 x 71 ), nb_points 494 ( 26 x 19 )
+    nb_cores 4320 ( 96 x 45 ), nb_points 493 ( 17 x 29 )
+    nb_cores 4392 ( 72 x 61 ), nb_points 484 ( 22 x 22 )
+    nb_cores 4400 ( 80 x 55 ), nb_points 480 ( 20 x 24 )
+    nb_cores 4473 ( 63 x 71 ), nb_points 475 ( 25 x 19 )
+    nb_cores 4560 ( 60 x 76 ), nb_points 468 ( 26 x 18 )
+    nb_cores 4608 ( 72 x 64 ), nb_points 462 ( 22 x 21 )
+    nb_cores 4623 ( 69 x 67 ), nb_points 460 ( 23 x 20 )
+    nb_cores 4675 ( 85 x 55 ), nb_points 456 ( 19 x 24 )
+    nb_cores 4770 ( 90 x 53 ), nb_points 450 ( 18 x 25 )
+    nb_cores 4824 ( 72 x 67 ), nb_points 440 ( 22 x 20 )
+    nb_cores 4899 ( 69 x 71 ), nb_points 437 ( 23 x 19 )
+    nb_cores 4950 ( 90 x 55 ), nb_points 432 ( 18 x 24 )
+    nb_cores 5088 ( 96 x 53 ), nb_points 425 ( 17 x 25 )
+    nb_cores 5092 ( 76 x 67 ), nb_points 420 ( 21 x 20 )
+    nb_cores 5112 ( 72 x 71 ), nb_points 418 ( 22 x 19 )
+    nb_cores 5220 ( 90 x 58 ), nb_points 414 ( 18 x 23 )
+    nb_cores 5280 ( 96 x 55 ), nb_points 408 ( 17 x 24 )
+    nb_cores 5360 ( 80 x 67 ), nb_points 400 ( 20 x 20 )
+    nb_cores 5396 ( 76 x 71 ), nb_points 399 ( 21 x 19 )
+    nb_cores 5472 ( 72 x 76 ), nb_points 396 ( 22 x 18 )
+    nb_cores 5568 ( 96 x 58 ), nb_points 391 ( 17 x 23 )
+    nb_cores 5580 ( 60 x 93 ), nb_points 390 ( 26 x 15 )
+    nb_cores 5665 ( 103 x 55 ), nb_points 384 ( 16 x 24 )
+    nb_cores 5680 ( 80 x 71 ), nb_points 380 ( 20 x 19 )
+    nb_cores 5760 ( 90 x 64 ), nb_points 378 ( 18 x 21 )
+    nb_cores 5832 ( 72 x 81 ), nb_points 374 ( 22 x 17 )
+    nb_cores 5974 ( 103 x 58 ), nb_points 368 ( 16 x 23 )
+    nb_cores 6030 ( 90 x 67 ), nb_points 360 ( 18 x 20 )
+    nb_cores 6144 ( 96 x 64 ), nb_points 357 ( 17 x 21 )
+    nb_cores 6264 ( 72 x 87 ), nb_points 352 ( 22 x 16 )
+    nb_cores 6360 ( 120 x 53 ), nb_points 350 ( 14 x 25 )
+    nb_cores 6390 ( 90 x 71 ), nb_points 342 ( 18 x 19 )
+    nb_cores 6432 ( 96 x 67 ), nb_points 340 ( 17 x 20 )
+    nb_cores 6592 ( 103 x 64 ), nb_points 336 ( 16 x 21 )
+    nb_cores 6696 ( 72 x 93 ), nb_points 330 ( 22 x 15 )
+    nb_cores 6816 ( 96 x 71 ), nb_points 323 ( 17 x 19 )
+    nb_cores 6901 ( 103 x 67 ), nb_points 320 ( 16 x 20 )
+    nb_cores 7068 ( 76 x 93 ), nb_points 315 ( 21 x 15 )
+    nb_cores 7205 ( 131 x 55 ), nb_points 312 ( 13 x 24 )
+    nb_cores 7272 ( 72 x 101 ), nb_points 308 ( 22 x 14 )
+    nb_cores 7290 ( 90 x 81 ), nb_points 306 ( 18 x 17 )
+    nb_cores 7313 ( 103 x 71 ), nb_points 304 ( 16 x 19 )
+    nb_cores 7437 ( 111 x 67 ), nb_points 300 ( 15 x 20 )
+    nb_cores 7590 ( 69 x 110 ), nb_points 299 ( 23 x 13 )
+    nb_cores 7676 ( 76 x 101 ), nb_points 294 ( 21 x 14 )
+    nb_cores 7776 ( 96 x 81 ), nb_points 289 ( 17 x 17 )
+    nb_cores 7828 ( 103 x 76 ), nb_points 288 ( 16 x 18 )
+    nb_cores 7881 ( 111 x 71 ), nb_points 285 ( 15 x 19 )
+    nb_cores 8040 ( 120 x 67 ), nb_points 280 ( 14 x 20 )
+    nb_cores 8343 ( 103 x 81 ), nb_points 272 ( 16 x 17 )
+    nb_cores 8370 ( 90 x 93 ), nb_points 270 ( 18 x 15 )
+    nb_cores 8520 ( 120 x 71 ), nb_points 266 ( 14 x 19 )
+    nb_cores 8712 ( 72 x 121 ), nb_points 264 ( 22 x 12 )
+    nb_cores 8777 ( 131 x 67 ), nb_points 260 ( 13 x 20 )
+    nb_cores 8928 ( 96 x 93 ), nb_points 255 ( 17 x 15 )
+    nb_cores 9090 ( 90 x 101 ), nb_points 252 ( 18 x 14 )
+    nb_cores 9301 ( 131 x 71 ), nb_points 247 ( 13 x 19 )
+    nb_cores 9579 ( 103 x 93 ), nb_points 240 ( 16 x 15 )
+    nb_cores 9696 ( 96 x 101 ), nb_points 238 ( 17 x 14 )
+    nb_cores 9900 ( 90 x 110 ), nb_points 234 ( 18 x 13 )
+    nb_cores 10184 ( 76 x 134 ), nb_points 231 ( 21 x 11 )
+    nb_cores 10224 ( 144 x 71 ), nb_points 228 ( 12 x 19 )
+    nb_cores 10323 ( 111 x 93 ), nb_points 225 ( 15 x 15 )
+    nb_cores 10403 ( 103 x 101 ), nb_points 224 ( 16 x 14 )
+    nb_cores 10560 ( 96 x 110 ), nb_points 221 ( 17 x 13 )
+    nb_cores 10720 ( 80 x 134 ), nb_points 220 ( 20 x 11 )
+    nb_cores 10720 ( 160 x 67 ), nb_points 220 ( 11 x 20 )
+    nb_cores 10890 ( 90 x 121 ), nb_points 216 ( 18 x 12 )
+    nb_cores 11160 ( 120 x 93 ), nb_points 210 ( 14 x 15 )
+    nb_cores 11330 ( 103 x 110 ), nb_points 208 ( 16 x 13 )
+    nb_cores 11616 ( 96 x 121 ), nb_points 204 ( 17 x 12 )
+    nb_cores 12060 ( 90 x 134 ), nb_points 198 ( 18 x 11 )
+    nb_cores 12120 ( 120 x 101 ), nb_points 196 ( 14 x 14 )
+    nb_cores 12183 ( 131 x 93 ), nb_points 195 ( 13 x 15 )
+    nb_cores 12463 ( 103 x 121 ), nb_points 192 ( 16 x 12 )
+    nb_cores 12780 ( 180 x 71 ), nb_points 190 ( 10 x 19 )
+    nb_cores 12864 ( 96 x 134 ), nb_points 187 ( 17 x 11 )
+    nb_cores 13200 ( 120 x 110 ), nb_points 182 ( 14 x 13 )
+    nb_cores 13392 ( 144 x 93 ), nb_points 180 ( 12 x 15 )
+    nb_cores 13802 ( 103 x 134 ), nb_points 176 ( 16 x 11 )
+    nb_cores 14410 ( 131 x 110 ), nb_points 169 ( 13 x 13 )
+    nb_cores 14520 ( 120 x 121 ), nb_points 168 ( 14 x 12 )
+    nb_cores 14874 ( 111 x 134 ), nb_points 165 ( 15 x 11 )
+    nb_cores 15553 ( 103 x 151 ), nb_points 160 ( 16 x 10 )
+    nb_cores 15840 ( 144 x 110 ), nb_points 156 ( 12 x 13 )
+    nb_cores 16080 ( 120 x 134 ), nb_points 154 ( 14 x 11 )
+    nb_cores 16608 ( 96 x 173 ), nb_points 153 ( 17 x 9 )
+    nb_cores 16740 ( 180 x 93 ), nb_points 150 ( 10 x 15 )
+    nb_cores 17424 ( 144 x 121 ), nb_points 144 ( 12 x 12 )
+    nb_cores 17554 ( 131 x 134 ), nb_points 143 ( 13 x 11 )
+    nb_cores 18120 ( 120 x 151 ), nb_points 140 ( 14 x 10 )
+    nb_cores 19158 ( 206 x 93 ), nb_points 135 ( 9 x 15 )
+    nb_cores 19296 ( 144 x 134 ), nb_points 132 ( 12 x 11 )
+    nb_cores 19781 ( 131 x 151 ), nb_points 130 ( 13 x 10 )
+    nb_cores 20703 ( 103 x 201 ), nb_points 128 ( 16 x 8 )
+    nb_cores 20760 ( 120 x 173 ), nb_points 126 ( 14 x 9 )
+    nb_cores 21440 ( 160 x 134 ), nb_points 121 ( 11 x 11 )
+    nb_cores 21744 ( 144 x 151 ), nb_points 120 ( 12 x 10 )
+    nb_cores 22660 ( 206 x 110 ), nb_points 117 ( 9 x 13 )
+    nb_cores 24120 ( 180 x 134 ), nb_points 110 ( 10 x 11 )
+    nb_cores 24912 ( 144 x 173 ), nb_points 108 ( 12 x 9 )
+    nb_cores 26331 ( 131 x 201 ), nb_points 104 ( 13 x 8 )
+    nb_cores 27180 ( 180 x 151 ), nb_points 100 ( 10 x 10 )
+    nb_cores 27604 ( 206 x 134 ), nb_points 99 ( 9 x 11 )
+    nb_cores 28920 ( 120 x 241 ), nb_points 98 ( 14 x 7 )
+    nb_cores 28944 ( 144 x 201 ), nb_points 96 ( 12 x 8 )
+    nb_cores 31106 ( 206 x 151 ), nb_points 90 ( 9 x 10 )
+    nb_cores 32160 ( 240 x 134 ), nb_points 88 ( 8 x 11 )
+    nb_cores 32160 ( 160 x 201 ), nb_points 88 ( 11 x 8 )
+    nb_cores 34704 ( 144 x 241 ), nb_points 84 ( 12 x 7 )
+    nb_cores 35638 ( 206 x 173 ), nb_points 81 ( 9 x 9 )
+    nb_cores 36180 ( 180 x 201 ), nb_points 80 ( 10 x 8 )
+    nb_cores 38560 ( 160 x 241 ), nb_points 77 ( 11 x 7 )
+    nb_cores 41406 ( 206 x 201 ), nb_points 72 ( 9 x 8 )
+    nb_cores 43380 ( 180 x 241 ), nb_points 70 ( 10 x 7 )
+    nb_cores 48240 ( 240 x 201 ), nb_points 64 ( 8 x 8 )
+    nb_cores 49646 ( 206 x 241 ), nb_points 63 ( 9 x 7 )
+    nb_cores 54360 ( 180 x 302 ), nb_points 60 ( 10 x 6 )
+    nb_cores 54360 ( 360 x 151 ), nb_points 60 ( 6 x 10 )
+    nb_cores 57840 ( 240 x 241 ), nb_points 56 ( 8 x 7 )
+    nb_cores 62212 ( 206 x 302 ), nb_points 54 ( 9 x 6 )
+    nb_cores 69408 ( 288 x 241 ), nb_points 49 ( 7 x 7 )
+    nb_cores 72360 ( 360 x 201 ), nb_points 48 ( 6 x 8 )
+    nb_cores 82812 ( 206 x 402 ), nb_points 45 ( 9 x 5 )
+    nb_cores 86760 ( 360 x 241 ), nb_points 42 ( 6 x 7 )
+    nb_cores 96480 ( 240 x 402 ), nb_points 40 ( 8 x 5 )
+    nb_cores 96480 ( 480 x 201 ), nb_points 40 ( 5 x 8 )
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca1
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca1	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca1	(revision 14097)
@@ -0,0 +1,205 @@
+    nb_cores 1 ( 1 x 1 ), nb_points 120184 ( 362 x 332 )
+    nb_cores 2 ( 2 x 1 ), nb_points 60424 ( 182 x 332 )
+    nb_cores 3 ( 3 x 1 ), nb_points 40504 ( 122 x 332 )
+    nb_cores 4 ( 2 x 2 ), nb_points 30394 ( 182 x 167 )
+    nb_cores 5 ( 5 x 1 ), nb_points 24568 ( 74 x 332 )
+    nb_cores 6 ( 3 x 2 ), nb_points 20374 ( 122 x 167 )
+    nb_cores 7 ( 7 x 1 ), nb_points 17928 ( 54 x 332 )
+    nb_cores 8 ( 4 x 2 ), nb_points 15364 ( 92 x 167 )
+    nb_cores 9 ( 3 x 3 ), nb_points 13664 ( 122 x 112 )
+    nb_cores 10 ( 5 x 2 ), nb_points 12358 ( 74 x 167 )
+    nb_cores 11 ( 1 x 11 ), nb_points 11584 ( 362 x 32 )
+    nb_cores 12 ( 4 x 3 ), nb_points 10304 ( 92 x 112 )
+    nb_cores 13 ( 13 x 1 ), nb_points 9960 ( 30 x 332 )
+    nb_cores 14 ( 7 x 2 ), nb_points 9018 ( 54 x 167 )
+    nb_cores 15 ( 5 x 3 ), nb_points 8288 ( 74 x 112 )
+    nb_cores 16 ( 4 x 4 ), nb_points 7820 ( 92 x 85 )
+    nb_cores 18 ( 6 x 3 ), nb_points 6944 ( 62 x 112 )
+    nb_cores 20 ( 4 x 5 ), nb_points 6256 ( 92 x 68 )
+    nb_cores 21 ( 7 x 3 ), nb_points 6048 ( 54 x 112 )
+    nb_cores 22 ( 2 x 11 ), nb_points 5824 ( 182 x 32 )
+    nb_cores 24 ( 4 x 6 ), nb_points 5244 ( 92 x 57 )
+    nb_cores 25 ( 5 x 5 ), nb_points 5032 ( 74 x 68 )
+    nb_cores 26 ( 13 x 2 ), nb_points 5010 ( 30 x 167 )
+    nb_cores 27 ( 9 x 3 ), nb_points 4704 ( 42 x 112 )
+    nb_cores 28 ( 7 x 4 ), nb_points 4590 ( 54 x 85 )
+    nb_cores 30 ( 6 x 5 ), nb_points 4216 ( 62 x 68 )
+    nb_cores 32 ( 8 x 4 ), nb_points 3995 ( 47 x 85 )
+    nb_cores 33 ( 3 x 11 ), nb_points 3904 ( 122 x 32 )
+    nb_cores 35 ( 7 x 5 ), nb_points 3672 ( 54 x 68 )
+    nb_cores 36 ( 6 x 6 ), nb_points 3534 ( 62 x 57 )
+    nb_cores 38 ( 19 x 2 ), nb_points 3507 ( 21 x 167 )
+    nb_cores 39 ( 13 x 3 ), nb_points 3360 ( 30 x 112 )
+    nb_cores 40 ( 8 x 5 ), nb_points 3196 ( 47 x 68 )
+    nb_cores 42 ( 7 x 6 ), nb_points 3078 ( 54 x 57 )
+    nb_cores 44 ( 4 x 11 ), nb_points 2944 ( 92 x 32 )
+    nb_cores 45 ( 9 x 5 ), nb_points 2856 ( 42 x 68 )
+    nb_cores 48 ( 8 x 6 ), nb_points 2679 ( 47 x 57 )
+    nb_cores 50 ( 10 x 5 ), nb_points 2584 ( 38 x 68 )
+    nb_cores 52 ( 13 x 4 ), nb_points 2550 ( 30 x 85 )
+    nb_cores 54 ( 9 x 6 ), nb_points 2394 ( 42 x 57 )
+    nb_cores 55 ( 5 x 11 ), nb_points 2368 ( 74 x 32 )
+    nb_cores 56 ( 8 x 7 ), nb_points 2350 ( 47 x 50 )
+    nb_cores 60 ( 10 x 6 ), nb_points 2166 ( 38 x 57 )
+    nb_cores 63 ( 9 x 7 ), nb_points 2100 ( 42 x 50 )
+    nb_cores 64 ( 8 x 8 ), nb_points 2068 ( 47 x 44 )
+    nb_cores 65 ( 13 x 5 ), nb_points 2040 ( 30 x 68 )
+    nb_cores 66 ( 6 x 11 ), nb_points 1984 ( 62 x 32 )
+    nb_cores 70 ( 7 x 10 ), nb_points 1890 ( 54 x 35 )
+    nb_cores 72 ( 12 x 6 ), nb_points 1824 ( 32 x 57 )
+    nb_cores 75 ( 15 x 5 ), nb_points 1768 ( 26 x 68 )
+    nb_cores 77 ( 7 x 11 ), nb_points 1728 ( 54 x 32 )
+    nb_cores 78 ( 13 x 6 ), nb_points 1710 ( 30 x 57 )
+    nb_cores 80 ( 8 x 10 ), nb_points 1645 ( 47 x 35 )
+    nb_cores 81 ( 9 x 9 ), nb_points 1638 ( 42 x 39 )
+    nb_cores 84 ( 14 x 6 ), nb_points 1596 ( 28 x 57 )
+    nb_cores 88 ( 8 x 11 ), nb_points 1504 ( 47 x 32 )
+    nb_cores 90 ( 9 x 10 ), nb_points 1470 ( 42 x 35 )
+    nb_cores 95 ( 19 x 5 ), nb_points 1428 ( 21 x 68 )
+    nb_cores 96 ( 12 x 8 ), nb_points 1408 ( 32 x 44 )
+    nb_cores 98 ( 14 x 7 ), nb_points 1400 ( 28 x 50 )
+    nb_cores 99 ( 9 x 11 ), nb_points 1344 ( 42 x 32 )
+    nb_cores 100 ( 10 x 10 ), nb_points 1330 ( 38 x 35 )
+    nb_cores 104 ( 8 x 13 ), nb_points 1316 ( 47 x 28 )
+    nb_cores 105 ( 7 x 15 ), nb_points 1296 ( 54 x 24 )
+    nb_cores 108 ( 12 x 9 ), nb_points 1248 ( 32 x 39 )
+    nb_cores 110 ( 10 x 11 ), nb_points 1216 ( 38 x 32 )
+    nb_cores 114 ( 19 x 6 ), nb_points 1197 ( 21 x 57 )
+    nb_cores 117 ( 13 x 9 ), nb_points 1170 ( 30 x 39 )
+    nb_cores 120 ( 12 x 10 ), nb_points 1120 ( 32 x 35 )
+    nb_cores 126 ( 9 x 14 ), nb_points 1092 ( 42 x 26 )
+    nb_cores 126 ( 14 x 9 ), nb_points 1092 ( 28 x 39 )
+    nb_cores 128 ( 8 x 16 ), nb_points 1081 ( 47 x 23 )
+    nb_cores 130 ( 13 x 10 ), nb_points 1050 ( 30 x 35 )
+    nb_cores 132 ( 12 x 11 ), nb_points 1024 ( 32 x 32 )
+    nb_cores 135 ( 9 x 15 ), nb_points 1008 ( 42 x 24 )
+    nb_cores 140 ( 14 x 10 ), nb_points 980 ( 28 x 35 )
+    nb_cores 143 ( 13 x 11 ), nb_points 960 ( 30 x 32 )
+    nb_cores 150 ( 15 x 10 ), nb_points 910 ( 26 x 35 )
+    nb_cores 154 ( 14 x 11 ), nb_points 896 ( 28 x 32 )
+    nb_cores 160 ( 10 x 16 ), nb_points 874 ( 38 x 23 )
+    nb_cores 162 ( 18 x 9 ), nb_points 858 ( 22 x 39 )
+    nb_cores 165 ( 15 x 11 ), nb_points 832 ( 26 x 32 )
+    nb_cores 171 ( 19 x 9 ), nb_points 819 ( 21 x 39 )
+    nb_cores 176 ( 8 x 22 ), nb_points 799 ( 47 x 17 )
+    nb_cores 180 ( 12 x 15 ), nb_points 768 ( 32 x 24 )
+    nb_cores 189 ( 9 x 21 ), nb_points 756 ( 42 x 18 )
+    nb_cores 190 ( 19 x 10 ), nb_points 735 ( 21 x 35 )
+    nb_cores 195 ( 13 x 15 ), nb_points 720 ( 30 x 24 )
+    nb_cores 198 ( 18 x 11 ), nb_points 704 ( 22 x 32 )
+    nb_cores 200 ( 20 x 10 ), nb_points 700 ( 20 x 35 )
+    nb_cores 208 ( 13 x 16 ), nb_points 690 ( 30 x 23 )
+    nb_cores 209 ( 19 x 11 ), nb_points 672 ( 21 x 32 )
+    nb_cores 216 ( 18 x 12 ), nb_points 660 ( 22 x 30 )
+    nb_cores 220 ( 20 x 11 ), nb_points 640 ( 20 x 32 )
+    nb_cores 225 ( 15 x 15 ), nb_points 624 ( 26 x 24 )
+    nb_cores 234 ( 18 x 13 ), nb_points 616 ( 22 x 28 )
+    nb_cores 240 ( 24 x 10 ), nb_points 595 ( 17 x 35 )
+    nb_cores 247 ( 19 x 13 ), nb_points 588 ( 21 x 28 )
+    nb_cores 252 ( 18 x 14 ), nb_points 572 ( 22 x 26 )
+    nb_cores 260 ( 20 x 13 ), nb_points 560 ( 20 x 28 )
+    nb_cores 260 ( 26 x 10 ), nb_points 560 ( 16 x 35 )
+    nb_cores 264 ( 12 x 22 ), nb_points 544 ( 32 x 17 )
+    nb_cores 264 ( 24 x 11 ), nb_points 544 ( 17 x 32 )
+    nb_cores 270 ( 18 x 15 ), nb_points 528 ( 22 x 24 )
+    nb_cores 280 ( 20 x 14 ), nb_points 520 ( 20 x 26 )
+    nb_cores 285 ( 19 x 15 ), nb_points 504 ( 21 x 24 )
+    nb_cores 300 ( 20 x 15 ), nb_points 480 ( 20 x 24 )
+    nb_cores 308 ( 14 x 22 ), nb_points 476 ( 28 x 17 )
+    nb_cores 315 ( 15 x 21 ), nb_points 468 ( 26 x 18 )
+    nb_cores 320 ( 20 x 16 ), nb_points 460 ( 20 x 23 )
+    nb_cores 330 ( 15 x 22 ), nb_points 442 ( 26 x 17 )
+    nb_cores 340 ( 20 x 17 ), nb_points 440 ( 20 x 22 )
+    nb_cores 345 ( 23 x 15 ), nb_points 432 ( 18 x 24 )
+    nb_cores 352 ( 16 x 22 ), nb_points 425 ( 25 x 17 )
+    nb_cores 360 ( 24 x 15 ), nb_points 408 ( 17 x 24 )
+    nb_cores 378 ( 18 x 21 ), nb_points 396 ( 22 x 18 )
+    nb_cores 384 ( 24 x 16 ), nb_points 391 ( 17 x 23 )
+    nb_cores 390 ( 26 x 15 ), nb_points 384 ( 16 x 24 )
+    nb_cores 396 ( 18 x 22 ), nb_points 374 ( 22 x 17 )
+    nb_cores 416 ( 26 x 16 ), nb_points 368 ( 16 x 23 )
+    nb_cores 418 ( 19 x 22 ), nb_points 357 ( 21 x 17 )
+    nb_cores 432 ( 18 x 24 ), nb_points 352 ( 22 x 16 )
+    nb_cores 440 ( 20 x 22 ), nb_points 340 ( 20 x 17 )
+    nb_cores 450 ( 30 x 15 ), nb_points 336 ( 14 x 24 )
+    nb_cores 468 ( 18 x 26 ), nb_points 330 ( 22 x 15 )
+    nb_cores 480 ( 20 x 24 ), nb_points 320 ( 20 x 16 )
+    nb_cores 494 ( 19 x 26 ), nb_points 315 ( 21 x 15 )
+    nb_cores 495 ( 15 x 33 ), nb_points 312 ( 26 x 12 )
+    nb_cores 495 ( 33 x 15 ), nb_points 312 ( 13 x 24 )
+    nb_cores 504 ( 24 x 21 ), nb_points 306 ( 17 x 18 )
+    nb_cores 520 ( 20 x 26 ), nb_points 300 ( 20 x 15 )
+    nb_cores 528 ( 24 x 22 ), nb_points 289 ( 17 x 17 )
+    nb_cores 540 ( 18 x 30 ), nb_points 286 ( 22 x 13 )
+    nb_cores 560 ( 20 x 28 ), nb_points 280 ( 20 x 14 )
+    nb_cores 570 ( 19 x 30 ), nb_points 273 ( 21 x 13 )
+    nb_cores 572 ( 26 x 22 ), nb_points 272 ( 16 x 17 )
+    nb_cores 588 ( 28 x 21 ), nb_points 270 ( 15 x 18 )
+    nb_cores 594 ( 18 x 33 ), nb_points 264 ( 22 x 12 )
+    nb_cores 600 ( 20 x 30 ), nb_points 260 ( 20 x 13 )
+    nb_cores 616 ( 28 x 22 ), nb_points 255 ( 15 x 17 )
+    nb_cores 627 ( 19 x 33 ), nb_points 252 ( 21 x 12 )
+    nb_cores 660 ( 30 x 22 ), nb_points 238 ( 14 x 17 )
+    nb_cores 690 ( 23 x 30 ), nb_points 234 ( 18 x 13 )
+    nb_cores 703 ( 19 x 37 ), nb_points 231 ( 21 x 11 )
+    nb_cores 720 ( 24 x 30 ), nb_points 221 ( 17 x 13 )
+    nb_cores 740 ( 20 x 37 ), nb_points 220 ( 20 x 11 )
+    nb_cores 756 ( 36 x 21 ), nb_points 216 ( 12 x 18 )
+    nb_cores 780 ( 26 x 30 ), nb_points 208 ( 16 x 13 )
+    nb_cores 792 ( 36 x 22 ), nb_points 204 ( 12 x 17 )
+    nb_cores 792 ( 24 x 33 ), nb_points 204 ( 17 x 12 )
+    nb_cores 840 ( 28 x 30 ), nb_points 195 ( 15 x 13 )
+    nb_cores 858 ( 26 x 33 ), nb_points 192 ( 16 x 12 )
+    nb_cores 880 ( 40 x 22 ), nb_points 187 ( 11 x 17 )
+    nb_cores 900 ( 30 x 30 ), nb_points 182 ( 14 x 13 )
+    nb_cores 924 ( 28 x 33 ), nb_points 180 ( 15 x 12 )
+    nb_cores 960 ( 40 x 24 ), nb_points 176 ( 11 x 16 )
+    nb_cores 990 ( 30 x 33 ), nb_points 168 ( 14 x 12 )
+    nb_cores 1036 ( 28 x 37 ), nb_points 165 ( 15 x 11 )
+    nb_cores 1080 ( 36 x 30 ), nb_points 156 ( 12 x 13 )
+    nb_cores 1110 ( 30 x 37 ), nb_points 154 ( 14 x 11 )
+    nb_cores 1144 ( 52 x 22 ), nb_points 153 ( 9 x 17 )
+    nb_cores 1170 ( 45 x 26 ), nb_points 150 ( 10 x 15 )
+    nb_cores 1188 ( 36 x 33 ), nb_points 144 ( 12 x 12 )
+    nb_cores 1200 ( 40 x 30 ), nb_points 143 ( 11 x 13 )
+    nb_cores 1260 ( 30 x 42 ), nb_points 140 ( 14 x 10 )
+    nb_cores 1260 ( 45 x 28 ), nb_points 140 ( 10 x 14 )
+    nb_cores 1320 ( 40 x 33 ), nb_points 132 ( 11 x 12 )
+    nb_cores 1350 ( 45 x 30 ), nb_points 130 ( 10 x 13 )
+    nb_cores 1430 ( 26 x 55 ), nb_points 128 ( 16 x 8 )
+    nb_cores 1440 ( 30 x 48 ), nb_points 126 ( 14 x 9 )
+    nb_cores 1480 ( 40 x 37 ), nb_points 121 ( 11 x 11 )
+    nb_cores 1485 ( 45 x 33 ), nb_points 120 ( 10 x 12 )
+    nb_cores 1560 ( 52 x 30 ), nb_points 117 ( 9 x 13 )
+    nb_cores 1650 ( 30 x 55 ), nb_points 112 ( 14 x 8 )
+    nb_cores 1665 ( 45 x 37 ), nb_points 110 ( 10 x 11 )
+    nb_cores 1716 ( 52 x 33 ), nb_points 108 ( 9 x 12 )
+    nb_cores 1800 ( 60 x 30 ), nb_points 104 ( 8 x 13 )
+    nb_cores 1890 ( 45 x 42 ), nb_points 100 ( 10 x 10 )
+    nb_cores 1920 ( 40 x 48 ), nb_points 99 ( 11 x 9 )
+    nb_cores 1980 ( 60 x 33 ), nb_points 96 ( 8 x 12 )
+    nb_cores 1980 ( 36 x 55 ), nb_points 96 ( 12 x 8 )
+    nb_cores 2160 ( 45 x 48 ), nb_points 90 ( 10 x 9 )
+    nb_cores 2200 ( 40 x 55 ), nb_points 88 ( 11 x 8 )
+    nb_cores 2376 ( 72 x 33 ), nb_points 84 ( 7 x 12 )
+    nb_cores 2376 ( 36 x 66 ), nb_points 84 ( 12 x 7 )
+    nb_cores 2475 ( 45 x 55 ), nb_points 80 ( 10 x 8 )
+    nb_cores 2640 ( 40 x 66 ), nb_points 77 ( 11 x 7 )
+    nb_cores 2860 ( 52 x 55 ), nb_points 72 ( 9 x 8 )
+    nb_cores 2970 ( 45 x 66 ), nb_points 70 ( 10 x 7 )
+    nb_cores 3300 ( 60 x 55 ), nb_points 64 ( 8 x 8 )
+    nb_cores 3432 ( 52 x 66 ), nb_points 63 ( 9 x 7 )
+    nb_cores 3735 ( 45 x 83 ), nb_points 60 ( 10 x 6 )
+    nb_cores 3960 ( 60 x 66 ), nb_points 56 ( 8 x 7 )
+    nb_cores 3960 ( 72 x 55 ), nb_points 56 ( 7 x 8 )
+    nb_cores 4316 ( 52 x 83 ), nb_points 54 ( 9 x 6 )
+    nb_cores 4752 ( 72 x 66 ), nb_points 49 ( 7 x 7 )
+    nb_cores 4950 ( 90 x 55 ), nb_points 48 ( 6 x 8 )
+    nb_cores 5720 ( 52 x 110 ), nb_points 45 ( 9 x 5 )
+    nb_cores 5940 ( 90 x 66 ), nb_points 42 ( 6 x 7 )
+    nb_cores 6600 ( 120 x 55 ), nb_points 40 ( 5 x 8 )
+    nb_cores 6600 ( 60 x 110 ), nb_points 40 ( 8 x 5 )
+    nb_cores 7470 ( 90 x 83 ), nb_points 36 ( 6 x 6 )
+    nb_cores 7920 ( 72 x 110 ), nb_points 35 ( 7 x 5 )
+    nb_cores 7920 ( 120 x 66 ), nb_points 35 ( 5 x 7 )
+    nb_cores 9900 ( 90 x 110 ), nb_points 30 ( 6 x 5 )
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca12
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca12	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/best_jpni_jpnj_eorca12	(revision 14097)
@@ -0,0 +1,1348 @@
+    nb_cores 1 ( 1 x 1 ), nb_points 13601334 ( 4322 x 3147 )
+    nb_cores 2 ( 2 x 1 ), nb_points 6803814 ( 2162 x 3147 )
+    nb_cores 3 ( 3 x 1 ), nb_points 4537974 ( 1442 x 3147 )
+    nb_cores 4 ( 4 x 1 ), nb_points 3405054 ( 1082 x 3147 )
+    nb_cores 5 ( 5 x 1 ), nb_points 2725302 ( 866 x 3147 )
+    nb_cores 6 ( 3 x 2 ), nb_points 2271150 ( 1442 x 1575 )
+    nb_cores 7 ( 7 x 1 ), nb_points 1951140 ( 620 x 3147 )
+    nb_cores 8 ( 4 x 2 ), nb_points 1704150 ( 1082 x 1575 )
+    nb_cores 9 ( 3 x 3 ), nb_points 1515542 ( 1442 x 1051 )
+    nb_cores 10 ( 5 x 2 ), nb_points 1363950 ( 866 x 1575 )
+    nb_cores 11 ( 11 x 1 ), nb_points 1243065 ( 395 x 3147 )
+    nb_cores 12 ( 6 x 2 ), nb_points 1137150 ( 722 x 1575 )
+    nb_cores 13 ( 13 x 1 ), nb_points 1054245 ( 335 x 3147 )
+    nb_cores 14 ( 7 x 2 ), nb_points 976500 ( 620 x 1575 )
+    nb_cores 15 ( 3 x 5 ), nb_points 909902 ( 1442 x 631 )
+    nb_cores 16 ( 8 x 2 ), nb_points 853650 ( 542 x 1575 )
+    nb_cores 17 ( 1 x 17 ), nb_points 808214 ( 4322 x 187 )
+    nb_cores 18 ( 6 x 3 ), nb_points 758822 ( 722 x 1051 )
+    nb_cores 19 ( 19 x 1 ), nb_points 723810 ( 230 x 3147 )
+    nb_cores 20 ( 4 x 5 ), nb_points 682742 ( 1082 x 631 )
+    nb_cores 21 ( 7 x 3 ), nb_points 651620 ( 620 x 1051 )
+    nb_cores 22 ( 11 x 2 ), nb_points 622125 ( 395 x 1575 )
+    nb_cores 23 ( 23 x 1 ), nb_points 597930 ( 190 x 3147 )
+    nb_cores 24 ( 8 x 3 ), nb_points 569642 ( 542 x 1051 )
+    nb_cores 25 ( 5 x 5 ), nb_points 546446 ( 866 x 631 )
+    nb_cores 26 ( 2 x 13 ), nb_points 527528 ( 2162 x 244 )
+    nb_cores 27 ( 9 x 3 ), nb_points 506582 ( 482 x 1051 )
+    nb_cores 28 ( 4 x 7 ), nb_points 489064 ( 1082 x 452 )
+    nb_cores 29 ( 29 x 1 ), nb_points 475197 ( 151 x 3147 )
+    nb_cores 30 ( 6 x 5 ), nb_points 455582 ( 722 x 631 )
+    nb_cores 31 ( 31 x 1 ), nb_points 446874 ( 142 x 3147 )
+    nb_cores 32 ( 8 x 4 ), nb_points 427638 ( 542 x 789 )
+    nb_cores 33 ( 11 x 3 ), nb_points 415145 ( 395 x 1051 )
+    nb_cores 34 ( 2 x 17 ), nb_points 404294 ( 2162 x 187 )
+    nb_cores 35 ( 7 x 5 ), nb_points 391220 ( 620 x 631 )
+    nb_cores 36 ( 9 x 4 ), nb_points 380298 ( 482 x 789 )
+    nb_cores 37 ( 37 x 1 ), nb_points 374493 ( 119 x 3147 )
+    nb_cores 38 ( 19 x 2 ), nb_points 362250 ( 230 x 1575 )
+    nb_cores 39 ( 3 x 13 ), nb_points 351848 ( 1442 x 244 )
+    nb_cores 40 ( 8 x 5 ), nb_points 342002 ( 542 x 631 )
+    nb_cores 41 ( 41 x 1 ), nb_points 339876 ( 108 x 3147 )
+    nb_cores 42 ( 6 x 7 ), nb_points 326344 ( 722 x 452 )
+    nb_cores 43 ( 43 x 1 ), nb_points 324141 ( 103 x 3147 )
+    nb_cores 44 ( 4 x 11 ), nb_points 311616 ( 1082 x 288 )
+    nb_cores 45 ( 9 x 5 ), nb_points 304142 ( 482 x 631 )
+    nb_cores 46 ( 23 x 2 ), nb_points 299250 ( 190 x 1575 )
+    nb_cores 47 ( 47 x 1 ), nb_points 295818 ( 94 x 3147 )
+    nb_cores 48 ( 12 x 4 ), nb_points 285618 ( 362 x 789 )
+    nb_cores 49 ( 7 x 7 ), nb_points 280240 ( 620 x 452 )
+    nb_cores 50 ( 10 x 5 ), nb_points 273854 ( 434 x 631 )
+    nb_cores 51 ( 3 x 17 ), nb_points 269654 ( 1442 x 187 )
+    nb_cores 52 ( 4 x 13 ), nb_points 264008 ( 1082 x 244 )
+    nb_cores 54 ( 9 x 6 ), nb_points 254014 ( 482 x 527 )
+    nb_cores 55 ( 11 x 5 ), nb_points 249245 ( 395 x 631 )
+    nb_cores 56 ( 8 x 7 ), nb_points 244984 ( 542 x 452 )
+    nb_cores 57 ( 19 x 3 ), nb_points 241730 ( 230 x 1051 )
+    nb_cores 58 ( 29 x 2 ), nb_points 237825 ( 151 x 1575 )
+    nb_cores 60 ( 12 x 5 ), nb_points 228422 ( 362 x 631 )
+    nb_cores 62 ( 31 x 2 ), nb_points 223650 ( 142 x 1575 )
+    nb_cores 63 ( 9 x 7 ), nb_points 217864 ( 482 x 452 )
+    nb_cores 64 ( 16 x 4 ), nb_points 214608 ( 272 x 789 )
+    nb_cores 65 ( 5 x 13 ), nb_points 211304 ( 866 x 244 )
+    nb_cores 66 ( 6 x 11 ), nb_points 207936 ( 722 x 288 )
+    nb_cores 68 ( 4 x 17 ), nb_points 202334 ( 1082 x 187 )
+    nb_cores 69 ( 23 x 3 ), nb_points 199690 ( 190 x 1051 )
+    nb_cores 70 ( 10 x 7 ), nb_points 196168 ( 434 x 452 )
+    nb_cores 72 ( 12 x 6 ), nb_points 190774 ( 362 x 527 )
+    nb_cores 74 ( 37 x 2 ), nb_points 187425 ( 119 x 1575 )
+    nb_cores 75 ( 15 x 5 ), nb_points 182990 ( 290 x 631 )
+    nb_cores 76 ( 19 x 4 ), nb_points 181470 ( 230 x 789 )
+    nb_cores 77 ( 11 x 7 ), nb_points 178540 ( 395 x 452 )
+    nb_cores 78 ( 6 x 13 ), nb_points 176168 ( 722 x 244 )
+    nb_cores 80 ( 16 x 5 ), nb_points 171632 ( 272 x 631 )
+    nb_cores 81 ( 9 x 9 ), nb_points 169664 ( 482 x 352 )
+    nb_cores 84 ( 12 x 7 ), nb_points 163624 ( 362 x 452 )
+    nb_cores 85 ( 5 x 17 ), nb_points 161942 ( 866 x 187 )
+    nb_cores 87 ( 29 x 3 ), nb_points 158701 ( 151 x 1051 )
+    nb_cores 88 ( 8 x 11 ), nb_points 156096 ( 542 x 288 )
+    nb_cores 90 ( 18 x 5 ), nb_points 152702 ( 242 x 631 )
+    nb_cores 91 ( 7 x 13 ), nb_points 151280 ( 620 x 244 )
+    nb_cores 92 ( 23 x 4 ), nb_points 149910 ( 190 x 789 )
+    nb_cores 93 ( 31 x 3 ), nb_points 149242 ( 142 x 1051 )
+    nb_cores 94 ( 47 x 2 ), nb_points 148050 ( 94 x 1575 )
+    nb_cores 95 ( 19 x 5 ), nb_points 145130 ( 230 x 631 )
+    nb_cores 96 ( 16 x 6 ), nb_points 143344 ( 272 x 527 )
+    nb_cores 98 ( 14 x 7 ), nb_points 140572 ( 311 x 452 )
+    nb_cores 99 ( 9 x 11 ), nb_points 138816 ( 482 x 288 )
+    nb_cores 100 ( 20 x 5 ), nb_points 137558 ( 218 x 631 )
+    nb_cores 102 ( 6 x 17 ), nb_points 135014 ( 722 x 187 )
+    nb_cores 104 ( 8 x 13 ), nb_points 132248 ( 542 x 244 )
+    nb_cores 105 ( 15 x 7 ), nb_points 131080 ( 290 x 452 )
+    nb_cores 108 ( 12 x 9 ), nb_points 127424 ( 362 x 352 )
+    nb_cores 110 ( 10 x 11 ), nb_points 124992 ( 434 x 288 )
+    nb_cores 112 ( 16 x 7 ), nb_points 122944 ( 272 x 452 )
+    nb_cores 114 ( 19 x 6 ), nb_points 121210 ( 230 x 527 )
+    nb_cores 115 ( 23 x 5 ), nb_points 119890 ( 190 x 631 )
+    nb_cores 116 ( 29 x 4 ), nb_points 119139 ( 151 x 789 )
+    nb_cores 117 ( 9 x 13 ), nb_points 117608 ( 482 x 244 )
+    nb_cores 119 ( 7 x 17 ), nb_points 115940 ( 620 x 187 )
+    nb_cores 120 ( 12 x 10 ), nb_points 114754 ( 362 x 317 )
+    nb_cores 121 ( 11 x 11 ), nb_points 113760 ( 395 x 288 )
+    nb_cores 123 ( 41 x 3 ), nb_points 113508 ( 108 x 1051 )
+    nb_cores 124 ( 31 x 4 ), nb_points 112038 ( 142 x 789 )
+    nb_cores 125 ( 25 x 5 ), nb_points 110425 ( 175 x 631 )
+    nb_cores 126 ( 18 x 7 ), nb_points 109384 ( 242 x 452 )
+    nb_cores 128 ( 16 x 8 ), nb_points 107712 ( 272 x 396 )
+    nb_cores 130 ( 10 x 13 ), nb_points 105896 ( 434 x 244 )
+    nb_cores 132 ( 12 x 11 ), nb_points 104256 ( 362 x 288 )
+    nb_cores 133 ( 19 x 7 ), nb_points 103960 ( 230 x 452 )
+    nb_cores 135 ( 15 x 9 ), nb_points 102080 ( 290 x 352 )
+    nb_cores 136 ( 8 x 17 ), nb_points 101354 ( 542 x 187 )
+    nb_cores 138 ( 23 x 6 ), nb_points 100130 ( 190 x 527 )
+    nb_cores 140 ( 10 x 14 ), nb_points 98518 ( 434 x 227 )
+    nb_cores 143 ( 11 x 13 ), nb_points 96380 ( 395 x 244 )
+    nb_cores 144 ( 16 x 9 ), nb_points 95744 ( 272 x 352 )
+    nb_cores 145 ( 29 x 5 ), nb_points 95281 ( 151 x 631 )
+    nb_cores 147 ( 21 x 7 ), nb_points 94016 ( 208 x 452 )
+    nb_cores 148 ( 37 x 4 ), nb_points 93891 ( 119 x 789 )
+    nb_cores 150 ( 15 x 10 ), nb_points 91930 ( 290 x 317 )
+    nb_cores 152 ( 8 x 19 ), nb_points 91056 ( 542 x 168 )
+    nb_cores 153 ( 9 x 17 ), nb_points 90134 ( 482 x 187 )
+    nb_cores 154 ( 14 x 11 ), nb_points 89568 ( 311 x 288 )
+    nb_cores 156 ( 12 x 13 ), nb_points 88328 ( 362 x 244 )
+    nb_cores 159 ( 53 x 3 ), nb_points 88284 ( 84 x 1051 )
+    nb_cores 160 ( 16 x 10 ), nb_points 86224 ( 272 x 317 )
+    nb_cores 161 ( 23 x 7 ), nb_points 85880 ( 190 x 452 )
+    nb_cores 162 ( 18 x 9 ), nb_points 85184 ( 242 x 352 )
+    nb_cores 165 ( 15 x 11 ), nb_points 83520 ( 290 x 288 )
+    nb_cores 168 ( 12 x 14 ), nb_points 82174 ( 362 x 227 )
+    nb_cores 169 ( 13 x 13 ), nb_points 81740 ( 335 x 244 )
+    nb_cores 170 ( 10 x 17 ), nb_points 81158 ( 434 x 187 )
+    nb_cores 171 ( 19 x 9 ), nb_points 80960 ( 230 x 352 )
+    nb_cores 174 ( 29 x 6 ), nb_points 79577 ( 151 x 527 )
+    nb_cores 175 ( 25 x 7 ), nb_points 79100 ( 175 x 452 )
+    nb_cores 176 ( 16 x 11 ), nb_points 78336 ( 272 x 288 )
+    nb_cores 180 ( 18 x 10 ), nb_points 76714 ( 242 x 317 )
+    nb_cores 182 ( 14 x 13 ), nb_points 75884 ( 311 x 244 )
+    nb_cores 184 ( 23 x 8 ), nb_points 75240 ( 190 x 396 )
+    nb_cores 185 ( 37 x 5 ), nb_points 75089 ( 119 x 631 )
+    nb_cores 186 ( 31 x 6 ), nb_points 74834 ( 142 x 527 )
+    nb_cores 187 ( 11 x 17 ), nb_points 73865 ( 395 x 187 )
+    nb_cores 189 ( 21 x 9 ), nb_points 73216 ( 208 x 352 )
+    nb_cores 190 ( 19 x 10 ), nb_points 72910 ( 230 x 317 )
+    nb_cores 192 ( 12 x 16 ), nb_points 72038 ( 362 x 199 )
+    nb_cores 195 ( 15 x 13 ), nb_points 70760 ( 290 x 244 )
+    nb_cores 196 ( 14 x 14 ), nb_points 70597 ( 311 x 227 )
+    nb_cores 198 ( 18 x 11 ), nb_points 69696 ( 242 x 288 )
+    nb_cores 200 ( 20 x 10 ), nb_points 69106 ( 218 x 317 )
+    nb_cores 203 ( 29 x 7 ), nb_points 68252 ( 151 x 452 )
+    nb_cores 204 ( 12 x 17 ), nb_points 67694 ( 362 x 187 )
+    nb_cores 207 ( 23 x 9 ), nb_points 66880 ( 190 x 352 )
+    nb_cores 208 ( 16 x 13 ), nb_points 66368 ( 272 x 244 )
+    nb_cores 209 ( 19 x 11 ), nb_points 66240 ( 230 x 288 )
+    nb_cores 210 ( 15 x 14 ), nb_points 65830 ( 290 x 227 )
+    nb_cores 215 ( 43 x 5 ), nb_points 64993 ( 103 x 631 )
+    nb_cores 216 ( 24 x 9 ), nb_points 64064 ( 182 x 352 )
+    nb_cores 220 ( 20 x 11 ), nb_points 62784 ( 218 x 288 )
+    nb_cores 221 ( 13 x 17 ), nb_points 62645 ( 335 x 187 )
+    nb_cores 224 ( 16 x 14 ), nb_points 61744 ( 272 x 227 )
+    nb_cores 225 ( 15 x 15 ), nb_points 61480 ( 290 x 212 )
+    nb_cores 228 ( 12 x 19 ), nb_points 60816 ( 362 x 168 )
+    nb_cores 230 ( 23 x 10 ), nb_points 60230 ( 190 x 317 )
+    nb_cores 231 ( 21 x 11 ), nb_points 59904 ( 208 x 288 )
+    nb_cores 232 ( 29 x 8 ), nb_points 59796 ( 151 x 396 )
+    nb_cores 234 ( 18 x 13 ), nb_points 59048 ( 242 x 244 )
+    nb_cores 238 ( 14 x 17 ), nb_points 58157 ( 311 x 187 )
+    nb_cores 240 ( 16 x 15 ), nb_points 57664 ( 272 x 212 )
+    nb_cores 242 ( 11 x 22 ), nb_points 57275 ( 395 x 145 )
+    nb_cores 243 ( 27 x 9 ), nb_points 57024 ( 162 x 352 )
+    nb_cores 245 ( 35 x 7 ), nb_points 56952 ( 126 x 452 )
+    nb_cores 246 ( 41 x 6 ), nb_points 56916 ( 108 x 527 )
+    nb_cores 247 ( 19 x 13 ), nb_points 56120 ( 230 x 244 )
+    nb_cores 250 ( 25 x 10 ), nb_points 55475 ( 175 x 317 )
+    nb_cores 252 ( 18 x 14 ), nb_points 54934 ( 242 x 227 )
+    nb_cores 253 ( 23 x 11 ), nb_points 54720 ( 190 x 288 )
+    nb_cores 255 ( 15 x 17 ), nb_points 54230 ( 290 x 187 )
+    nb_cores 256 ( 16 x 16 ), nb_points 54128 ( 272 x 199 )
+    nb_cores 259 ( 37 x 7 ), nb_points 53788 ( 119 x 452 )
+    nb_cores 260 ( 20 x 13 ), nb_points 53192 ( 218 x 244 )
+    nb_cores 261 ( 29 x 9 ), nb_points 53152 ( 151 x 352 )
+    nb_cores 264 ( 24 x 11 ), nb_points 52416 ( 182 x 288 )
+    nb_cores 266 ( 19 x 14 ), nb_points 52210 ( 230 x 227 )
+    nb_cores 270 ( 18 x 15 ), nb_points 51304 ( 242 x 212 )
+    nb_cores 272 ( 16 x 17 ), nb_points 50864 ( 272 x 187 )
+    nb_cores 273 ( 21 x 13 ), nb_points 50752 ( 208 x 244 )
+    nb_cores 275 ( 25 x 11 ), nb_points 50400 ( 175 x 288 )
+    nb_cores 276 ( 12 x 23 ), nb_points 50318 ( 362 x 139 )
+    nb_cores 279 ( 31 x 9 ), nb_points 49984 ( 142 x 352 )
+    nb_cores 280 ( 20 x 14 ), nb_points 49486 ( 218 x 227 )
+    nb_cores 285 ( 15 x 19 ), nb_points 48720 ( 290 x 168 )
+    nb_cores 286 ( 22 x 13 ), nb_points 48556 ( 199 x 244 )
+    nb_cores 288 ( 16 x 18 ), nb_points 48144 ( 272 x 177 )
+    nb_cores 289 ( 17 x 17 ), nb_points 48059 ( 257 x 187 )
+    nb_cores 290 ( 29 x 10 ), nb_points 47867 ( 151 x 317 )
+    nb_cores 294 ( 21 x 14 ), nb_points 47216 ( 208 x 227 )
+    nb_cores 296 ( 37 x 8 ), nb_points 47124 ( 119 x 396 )
+    nb_cores 297 ( 27 x 11 ), nb_points 46656 ( 162 x 288 )
+    nb_cores 299 ( 23 x 13 ), nb_points 46360 ( 190 x 244 )
+    nb_cores 300 ( 20 x 15 ), nb_points 46216 ( 218 x 212 )
+    nb_cores 304 ( 16 x 19 ), nb_points 45696 ( 272 x 168 )
+    nb_cores 306 ( 18 x 17 ), nb_points 45254 ( 242 x 187 )
+    nb_cores 308 ( 14 x 22 ), nb_points 45095 ( 311 x 145 )
+    nb_cores 310 ( 31 x 10 ), nb_points 45014 ( 142 x 317 )
+    nb_cores 312 ( 24 x 13 ), nb_points 44408 ( 182 x 244 )
+    nb_cores 315 ( 15 x 21 ), nb_points 44080 ( 290 x 152 )
+    nb_cores 319 ( 29 x 11 ), nb_points 43488 ( 151 x 288 )
+    nb_cores 320 ( 20 x 16 ), nb_points 43382 ( 218 x 199 )
+    nb_cores 322 ( 23 x 14 ), nb_points 43130 ( 190 x 227 )
+    nb_cores 323 ( 19 x 17 ), nb_points 43010 ( 230 x 187 )
+    nb_cores 324 ( 18 x 18 ), nb_points 42834 ( 242 x 177 )
+    nb_cores 325 ( 25 x 13 ), nb_points 42700 ( 175 x 244 )
+    nb_cores 329 ( 47 x 7 ), nb_points 42488 ( 94 x 452 )
+    nb_cores 330 ( 30 x 11 ), nb_points 42048 ( 146 x 288 )
+    nb_cores 333 ( 37 x 9 ), nb_points 41888 ( 119 x 352 )
+    nb_cores 336 ( 24 x 14 ), nb_points 41314 ( 182 x 227 )
+    nb_cores 338 ( 13 x 26 ), nb_points 41205 ( 335 x 123 )
+    nb_cores 340 ( 20 x 17 ), nb_points 40766 ( 218 x 187 )
+    nb_cores 342 ( 18 x 19 ), nb_points 40656 ( 242 x 168 )
+    nb_cores 345 ( 23 x 15 ), nb_points 40280 ( 190 x 212 )
+    nb_cores 348 ( 29 x 12 ), nb_points 40015 ( 151 x 265 )
+    nb_cores 350 ( 25 x 14 ), nb_points 39725 ( 175 x 227 )
+    nb_cores 351 ( 27 x 13 ), nb_points 39528 ( 162 x 244 )
+    nb_cores 352 ( 16 x 22 ), nb_points 39440 ( 272 x 145 )
+    nb_cores 357 ( 21 x 17 ), nb_points 38896 ( 208 x 187 )
+    nb_cores 360 ( 24 x 15 ), nb_points 38584 ( 182 x 212 )
+    nb_cores 363 ( 33 x 11 ), nb_points 38304 ( 133 x 288 )
+    nb_cores 364 ( 14 x 26 ), nb_points 38253 ( 311 x 123 )
+    nb_cores 368 ( 16 x 23 ), nb_points 37808 ( 272 x 139 )
+    nb_cores 370 ( 37 x 10 ), nb_points 37723 ( 119 x 317 )
+    nb_cores 372 ( 31 x 12 ), nb_points 37630 ( 142 x 265 )
+    nb_cores 374 ( 22 x 17 ), nb_points 37213 ( 199 x 187 )
+    nb_cores 375 ( 25 x 15 ), nb_points 37100 ( 175 x 212 )
+    nb_cores 377 ( 29 x 13 ), nb_points 36844 ( 151 x 244 )
+    nb_cores 378 ( 27 x 14 ), nb_points 36774 ( 162 x 227 )
+    nb_cores 380 ( 20 x 19 ), nb_points 36624 ( 218 x 168 )
+    nb_cores 384 ( 24 x 16 ), nb_points 36218 ( 182 x 199 )
+    nb_cores 390 ( 30 x 13 ), nb_points 35624 ( 146 x 244 )
+    nb_cores 391 ( 23 x 17 ), nb_points 35530 ( 190 x 187 )
+    nb_cores 396 ( 18 x 22 ), nb_points 35090 ( 242 x 145 )
+    nb_cores 399 ( 21 x 19 ), nb_points 34944 ( 208 x 168 )
+    nb_cores 400 ( 16 x 25 ), nb_points 34816 ( 272 x 128 )
+    nb_cores 403 ( 31 x 13 ), nb_points 34648 ( 142 x 244 )
+    nb_cores 405 ( 27 x 15 ), nb_points 34344 ( 162 x 212 )
+    nb_cores 406 ( 29 x 14 ), nb_points 34277 ( 151 x 227 )
+    nb_cores 407 ( 37 x 11 ), nb_points 34272 ( 119 x 288 )
+    nb_cores 408 ( 24 x 17 ), nb_points 34034 ( 182 x 187 )
+    nb_cores 414 ( 23 x 18 ), nb_points 33630 ( 190 x 177 )
+    nb_cores 416 ( 32 x 13 ), nb_points 33428 ( 137 x 244 )
+    nb_cores 418 ( 19 x 22 ), nb_points 33350 ( 230 x 145 )
+    nb_cores 420 ( 20 x 21 ), nb_points 33136 ( 218 x 152 )
+    nb_cores 423 ( 47 x 9 ), nb_points 33088 ( 94 x 352 )
+    nb_cores 425 ( 25 x 17 ), nb_points 32725 ( 175 x 187 )
+    nb_cores 429 ( 33 x 13 ), nb_points 32452 ( 133 x 244 )
+    nb_cores 432 ( 24 x 18 ), nb_points 32214 ( 182 x 177 )
+    nb_cores 435 ( 29 x 15 ), nb_points 32012 ( 151 x 212 )
+    nb_cores 437 ( 23 x 19 ), nb_points 31920 ( 190 x 168 )
+    nb_cores 440 ( 20 x 22 ), nb_points 31610 ( 218 x 145 )
+    nb_cores 442 ( 26 x 17 ), nb_points 31603 ( 169 x 187 )
+    nb_cores 444 ( 12 x 37 ), nb_points 31494 ( 362 x 87 )
+    nb_cores 448 ( 32 x 14 ), nb_points 31099 ( 137 x 227 )
+    nb_cores 450 ( 30 x 15 ), nb_points 30952 ( 146 x 212 )
+    nb_cores 455 ( 35 x 13 ), nb_points 30744 ( 126 x 244 )
+    nb_cores 456 ( 24 x 19 ), nb_points 30576 ( 182 x 168 )
+    nb_cores 459 ( 27 x 17 ), nb_points 30294 ( 162 x 187 )
+    nb_cores 462 ( 21 x 22 ), nb_points 30160 ( 208 x 145 )
+    nb_cores 464 ( 29 x 16 ), nb_points 30049 ( 151 x 199 )
+    nb_cores 468 ( 18 x 26 ), nb_points 29766 ( 242 x 123 )
+    nb_cores 473 ( 43 x 11 ), nb_points 29664 ( 103 x 288 )
+    nb_cores 475 ( 25 x 19 ), nb_points 29400 ( 175 x 168 )
+    nb_cores 476 ( 28 x 17 ), nb_points 29359 ( 157 x 187 )
+    nb_cores 480 ( 32 x 15 ), nb_points 29044 ( 137 x 212 )
+    nb_cores 481 ( 37 x 13 ), nb_points 29036 ( 119 x 244 )
+    nb_cores 483 ( 23 x 21 ), nb_points 28880 ( 190 x 152 )
+    nb_cores 484 ( 22 x 22 ), nb_points 28855 ( 199 x 145 )
+    nb_cores 486 ( 27 x 18 ), nb_points 28674 ( 162 x 177 )
+    nb_cores 490 ( 35 x 14 ), nb_points 28602 ( 126 x 227 )
+    nb_cores 492 ( 12 x 41 ), nb_points 28598 ( 362 x 79 )
+    nb_cores 493 ( 29 x 17 ), nb_points 28237 ( 151 x 187 )
+    nb_cores 495 ( 33 x 15 ), nb_points 28196 ( 133 x 212 )
+    nb_cores 500 ( 20 x 25 ), nb_points 27904 ( 218 x 128 )
+    nb_cores 504 ( 24 x 21 ), nb_points 27664 ( 182 x 152 )
+    nb_cores 506 ( 23 x 22 ), nb_points 27550 ( 190 x 145 )
+    nb_cores 510 ( 30 x 17 ), nb_points 27302 ( 146 x 187 )
+    nb_cores 512 ( 32 x 16 ), nb_points 27263 ( 137 x 199 )
+    nb_cores 513 ( 27 x 19 ), nb_points 27216 ( 162 x 168 )
+    nb_cores 517 ( 47 x 11 ), nb_points 27072 ( 94 x 288 )
+    nb_cores 518 ( 37 x 14 ), nb_points 27013 ( 119 x 227 )
+    nb_cores 520 ( 20 x 26 ), nb_points 26814 ( 218 x 123 )
+    nb_cores 522 ( 29 x 18 ), nb_points 26727 ( 151 x 177 )
+    nb_cores 525 ( 25 x 21 ), nb_points 26600 ( 175 x 152 )
+    nb_cores 527 ( 31 x 17 ), nb_points 26554 ( 142 x 187 )
+    nb_cores 528 ( 24 x 22 ), nb_points 26390 ( 182 x 145 )
+    nb_cores 532 ( 38 x 14 ), nb_points 26332 ( 116 x 227 )
+    nb_cores 539 ( 49 x 11 ), nb_points 26208 ( 91 x 288 )
+    nb_cores 540 ( 30 x 18 ), nb_points 25842 ( 146 x 177 )
+    nb_cores 544 ( 32 x 17 ), nb_points 25619 ( 137 x 187 )
+    nb_cores 546 ( 21 x 26 ), nb_points 25584 ( 208 x 123 )
+    nb_cores 550 ( 25 x 22 ), nb_points 25375 ( 175 x 145 )
+    nb_cores 551 ( 29 x 19 ), nb_points 25368 ( 151 x 168 )
+    nb_cores 552 ( 24 x 23 ), nb_points 25298 ( 182 x 139 )
+    nb_cores 555 ( 37 x 15 ), nb_points 25228 ( 119 x 212 )
+    nb_cores 558 ( 31 x 18 ), nb_points 25134 ( 142 x 177 )
+    nb_cores 559 ( 43 x 13 ), nb_points 25132 ( 103 x 244 )
+    nb_cores 560 ( 40 x 14 ), nb_points 24970 ( 110 x 227 )
+    nb_cores 561 ( 33 x 17 ), nb_points 24871 ( 133 x 187 )
+    nb_cores 567 ( 27 x 21 ), nb_points 24624 ( 162 x 152 )
+    nb_cores 570 ( 30 x 19 ), nb_points 24528 ( 146 x 168 )
+    nb_cores 572 ( 22 x 26 ), nb_points 24477 ( 199 x 123 )
+    nb_cores 575 ( 23 x 25 ), nb_points 24320 ( 190 x 128 )
+    nb_cores 576 ( 32 x 18 ), nb_points 24249 ( 137 x 177 )
+    nb_cores 580 ( 29 x 20 ), nb_points 24160 ( 151 x 160 )
+    nb_cores 585 ( 45 x 13 ), nb_points 23912 ( 98 x 244 )
+    nb_cores 588 ( 42 x 14 ), nb_points 23835 ( 105 x 227 )
+    nb_cores 592 ( 16 x 37 ), nb_points 23664 ( 272 x 87 )
+    nb_cores 594 ( 27 x 22 ), nb_points 23490 ( 162 x 145 )
+    nb_cores 598 ( 23 x 26 ), nb_points 23370 ( 190 x 123 )
+    nb_cores 600 ( 24 x 25 ), nb_points 23296 ( 182 x 128 )
+    nb_cores 608 ( 32 x 19 ), nb_points 23016 ( 137 x 168 )
+    nb_cores 609 ( 29 x 21 ), nb_points 22952 ( 151 x 152 )
+    nb_cores 611 ( 47 x 13 ), nb_points 22936 ( 94 x 244 )
+    nb_cores 612 ( 36 x 17 ), nb_points 22814 ( 122 x 187 )
+    nb_cores 616 ( 28 x 22 ), nb_points 22765 ( 157 x 145 )
+    nb_cores 620 ( 20 x 31 ), nb_points 22672 ( 218 x 104 )
+    nb_cores 621 ( 27 x 23 ), nb_points 22518 ( 162 x 139 )
+    nb_cores 624 ( 24 x 26 ), nb_points 22386 ( 182 x 123 )
+    nb_cores 627 ( 33 x 19 ), nb_points 22344 ( 133 x 168 )
+    nb_cores 629 ( 37 x 17 ), nb_points 22253 ( 119 x 187 )
+    nb_cores 630 ( 30 x 21 ), nb_points 22192 ( 146 x 152 )
+    nb_cores 638 ( 29 x 22 ), nb_points 21895 ( 151 x 145 )
+    nb_cores 640 ( 40 x 16 ), nb_points 21890 ( 110 x 199 )
+    nb_cores 644 ( 46 x 14 ), nb_points 21792 ( 96 x 227 )
+    nb_cores 646 ( 38 x 17 ), nb_points 21692 ( 116 x 187 )
+    nb_cores 648 ( 36 x 18 ), nb_points 21594 ( 122 x 177 )
+    nb_cores 650 ( 25 x 26 ), nb_points 21525 ( 175 x 123 )
+    nb_cores 656 ( 16 x 41 ), nb_points 21488 ( 272 x 79 )
+    nb_cores 658 ( 47 x 14 ), nb_points 21338 ( 94 x 227 )
+    nb_cores 660 ( 30 x 22 ), nb_points 21170 ( 146 x 145 )
+    nb_cores 663 ( 39 x 17 ), nb_points 21131 ( 113 x 187 )
+    nb_cores 666 ( 18 x 37 ), nb_points 21054 ( 242 x 87 )
+    nb_cores 667 ( 29 x 23 ), nb_points 20989 ( 151 x 139 )
+    nb_cores 672 ( 32 x 21 ), nb_points 20824 ( 137 x 152 )
+    nb_cores 675 ( 27 x 25 ), nb_points 20736 ( 162 x 128 )
+    nb_cores 680 ( 40 x 17 ), nb_points 20570 ( 110 x 187 )
+    nb_cores 684 ( 36 x 19 ), nb_points 20496 ( 122 x 168 )
+    nb_cores 690 ( 30 x 23 ), nb_points 20294 ( 146 x 139 )
+    nb_cores 693 ( 33 x 21 ), nb_points 20216 ( 133 x 152 )
+    nb_cores 696 ( 24 x 29 ), nb_points 20202 ( 182 x 111 )
+    nb_cores 697 ( 41 x 17 ), nb_points 20196 ( 108 x 187 )
+    nb_cores 700 ( 20 x 35 ), nb_points 20056 ( 218 x 92 )
+    nb_cores 702 ( 27 x 26 ), nb_points 19926 ( 162 x 123 )
+    nb_cores 704 ( 32 x 22 ), nb_points 19865 ( 137 x 145 )
+    nb_cores 713 ( 31 x 23 ), nb_points 19738 ( 142 x 139 )
+    nb_cores 714 ( 42 x 17 ), nb_points 19635 ( 105 x 187 )
+    nb_cores 720 ( 40 x 18 ), nb_points 19470 ( 110 x 177 )
+    nb_cores 725 ( 29 x 25 ), nb_points 19328 ( 151 x 128 )
+    nb_cores 726 ( 33 x 22 ), nb_points 19285 ( 133 x 145 )
+    nb_cores 729 ( 27 x 27 ), nb_points 19278 ( 162 x 119 )
+    nb_cores 731 ( 43 x 17 ), nb_points 19261 ( 103 x 187 )
+    nb_cores 735 ( 21 x 35 ), nb_points 19136 ( 208 x 92 )
+    nb_cores 736 ( 32 x 23 ), nb_points 19043 ( 137 x 139 )
+    nb_cores 740 ( 20 x 37 ), nb_points 18966 ( 218 x 87 )
+    nb_cores 744 ( 24 x 31 ), nb_points 18928 ( 182 x 104 )
+    nb_cores 748 ( 34 x 22 ), nb_points 18850 ( 130 x 145 )
+    nb_cores 750 ( 30 x 25 ), nb_points 18688 ( 146 x 128 )
+    nb_cores 754 ( 29 x 26 ), nb_points 18573 ( 151 x 123 )
+    nb_cores 756 ( 36 x 21 ), nb_points 18544 ( 122 x 152 )
+    nb_cores 759 ( 33 x 23 ), nb_points 18487 ( 133 x 139 )
+    nb_cores 760 ( 40 x 19 ), nb_points 18480 ( 110 x 168 )
+    nb_cores 765 ( 45 x 17 ), nb_points 18326 ( 98 x 187 )
+    nb_cores 768 ( 48 x 16 ), nb_points 18308 ( 92 x 199 )
+    nb_cores 770 ( 35 x 22 ), nb_points 18270 ( 126 x 145 )
+    nb_cores 774 ( 43 x 18 ), nb_points 18231 ( 103 x 177 )
+    nb_cores 775 ( 31 x 25 ), nb_points 18176 ( 142 x 128 )
+    nb_cores 777 ( 37 x 21 ), nb_points 18088 ( 119 x 152 )
+    nb_cores 780 ( 30 x 26 ), nb_points 17958 ( 146 x 123 )
+    nb_cores 782 ( 46 x 17 ), nb_points 17952 ( 96 x 187 )
+    nb_cores 792 ( 36 x 22 ), nb_points 17690 ( 122 x 145 )
+    nb_cores 798 ( 38 x 21 ), nb_points 17632 ( 116 x 152 )
+    nb_cores 799 ( 47 x 17 ), nb_points 17578 ( 94 x 187 )
+    nb_cores 800 ( 32 x 25 ), nb_points 17536 ( 137 x 128 )
+    nb_cores 805 ( 23 x 35 ), nb_points 17480 ( 190 x 92 )
+    nb_cores 806 ( 31 x 26 ), nb_points 17466 ( 142 x 123 )
+    nb_cores 810 ( 27 x 30 ), nb_points 17334 ( 162 x 107 )
+    nb_cores 814 ( 37 x 22 ), nb_points 17255 ( 119 x 145 )
+    nb_cores 816 ( 48 x 17 ), nb_points 17204 ( 92 x 187 )
+    nb_cores 819 ( 39 x 21 ), nb_points 17176 ( 113 x 152 )
+    nb_cores 825 ( 33 x 25 ), nb_points 17024 ( 133 x 128 )
+    nb_cores 828 ( 36 x 23 ), nb_points 16958 ( 122 x 139 )
+    nb_cores 832 ( 32 x 26 ), nb_points 16851 ( 137 x 123 )
+    nb_cores 836 ( 38 x 22 ), nb_points 16820 ( 116 x 145 )
+    nb_cores 840 ( 40 x 21 ), nb_points 16720 ( 110 x 152 )
+    nb_cores 846 ( 47 x 18 ), nb_points 16638 ( 94 x 177 )
+    nb_cores 850 ( 25 x 34 ), nb_points 16625 ( 175 x 95 )
+    nb_cores 851 ( 23 x 37 ), nb_points 16530 ( 190 x 87 )
+    nb_cores 855 ( 45 x 19 ), nb_points 16464 ( 98 x 168 )
+    nb_cores 858 ( 33 x 26 ), nb_points 16359 ( 133 x 123 )
+    nb_cores 864 ( 48 x 18 ), nb_points 16284 ( 92 x 177 )
+    nb_cores 867 ( 51 x 17 ), nb_points 16269 ( 87 x 187 )
+    nb_cores 870 ( 29 x 30 ), nb_points 16157 ( 151 x 107 )
+    nb_cores 874 ( 38 x 23 ), nb_points 16124 ( 116 x 139 )
+    nb_cores 875 ( 25 x 35 ), nb_points 16100 ( 175 x 92 )
+    nb_cores 880 ( 40 x 22 ), nb_points 15950 ( 110 x 145 )
+    nb_cores 888 ( 24 x 37 ), nb_points 15834 ( 182 x 87 )
+    nb_cores 891 ( 33 x 27 ), nb_points 15827 ( 133 x 119 )
+    nb_cores 893 ( 47 x 19 ), nb_points 15792 ( 94 x 168 )
+    nb_cores 896 ( 32 x 28 ), nb_points 15755 ( 137 x 115 )
+    nb_cores 897 ( 39 x 23 ), nb_points 15707 ( 113 x 139 )
+    nb_cores 899 ( 29 x 31 ), nb_points 15704 ( 151 x 104 )
+    nb_cores 900 ( 36 x 25 ), nb_points 15616 ( 122 x 128 )
+    nb_cores 910 ( 35 x 26 ), nb_points 15498 ( 126 x 123 )
+    nb_cores 912 ( 48 x 19 ), nb_points 15456 ( 92 x 168 )
+    nb_cores 918 ( 54 x 17 ), nb_points 15334 ( 82 x 187 )
+    nb_cores 920 ( 40 x 23 ), nb_points 15290 ( 110 x 139 )
+    nb_cores 924 ( 42 x 22 ), nb_points 15225 ( 105 x 145 )
+    nb_cores 928 ( 32 x 29 ), nb_points 15207 ( 137 x 111 )
+    nb_cores 930 ( 30 x 31 ), nb_points 15184 ( 146 x 104 )
+    nb_cores 935 ( 55 x 17 ), nb_points 15147 ( 81 x 187 )
+    nb_cores 936 ( 36 x 26 ), nb_points 15006 ( 122 x 123 )
+    nb_cores 945 ( 45 x 21 ), nb_points 14896 ( 98 x 152 )
+    nb_cores 950 ( 38 x 25 ), nb_points 14848 ( 116 x 128 )
+    nb_cores 957 ( 33 x 29 ), nb_points 14763 ( 133 x 111 )
+    nb_cores 960 ( 32 x 30 ), nb_points 14659 ( 137 x 107 )
+    nb_cores 962 ( 37 x 26 ), nb_points 14637 ( 119 x 123 )
+    nb_cores 966 ( 46 x 21 ), nb_points 14592 ( 96 x 152 )
+    nb_cores 969 ( 57 x 17 ), nb_points 14586 ( 78 x 187 )
+    nb_cores 972 ( 54 x 18 ), nb_points 14514 ( 82 x 177 )
+    nb_cores 975 ( 39 x 25 ), nb_points 14464 ( 113 x 128 )
+    nb_cores 980 ( 28 x 35 ), nb_points 14444 ( 157 x 92 )
+    nb_cores 984 ( 24 x 41 ), nb_points 14378 ( 182 x 79 )
+    nb_cores 986 ( 29 x 34 ), nb_points 14345 ( 151 x 95 )
+    nb_cores 987 ( 47 x 21 ), nb_points 14288 ( 94 x 152 )
+    nb_cores 988 ( 38 x 26 ), nb_points 14268 ( 116 x 123 )
+    nb_cores 990 ( 45 x 22 ), nb_points 14210 ( 98 x 145 )
+    nb_cores 999 ( 27 x 37 ), nb_points 14094 ( 162 x 87 )
+    nb_cores 1000 ( 40 x 25 ), nb_points 14080 ( 110 x 128 )
+    nb_cores 1008 ( 48 x 21 ), nb_points 13984 ( 92 x 152 )
+    nb_cores 1012 ( 46 x 22 ), nb_points 13920 ( 96 x 145 )
+    nb_cores 1014 ( 39 x 26 ), nb_points 13899 ( 113 x 123 )
+    nb_cores 1015 ( 29 x 35 ), nb_points 13892 ( 151 x 92 )
+    nb_cores 1020 ( 60 x 17 ), nb_points 13838 ( 74 x 187 )
+    nb_cores 1023 ( 33 x 31 ), nb_points 13832 ( 133 x 104 )
+    nb_cores 1025 ( 41 x 25 ), nb_points 13824 ( 108 x 128 )
+    nb_cores 1026 ( 27 x 38 ), nb_points 13770 ( 162 x 85 )
+    nb_cores 1034 ( 47 x 22 ), nb_points 13630 ( 94 x 145 )
+    nb_cores 1035 ( 45 x 23 ), nb_points 13622 ( 98 x 139 )
+    nb_cores 1040 ( 40 x 26 ), nb_points 13530 ( 110 x 123 )
+    nb_cores 1050 ( 30 x 35 ), nb_points 13432 ( 146 x 92 )
+    nb_cores 1056 ( 48 x 22 ), nb_points 13340 ( 92 x 145 )
+    nb_cores 1066 ( 41 x 26 ), nb_points 13284 ( 108 x 123 )
+    nb_cores 1071 ( 51 x 21 ), nb_points 13224 ( 87 x 152 )
+    nb_cores 1073 ( 29 x 37 ), nb_points 13137 ( 151 x 87 )
+    nb_cores 1080 ( 36 x 30 ), nb_points 13054 ( 122 x 107 )
+    nb_cores 1088 ( 32 x 34 ), nb_points 13015 ( 137 x 95 )
+    nb_cores 1092 ( 42 x 26 ), nb_points 12915 ( 105 x 123 )
+    nb_cores 1100 ( 50 x 22 ), nb_points 12905 ( 89 x 145 )
+    nb_cores 1102 ( 29 x 38 ), nb_points 12835 ( 151 x 85 )
+    nb_cores 1104 ( 48 x 23 ), nb_points 12788 ( 92 x 139 )
+    nb_cores 1110 ( 30 x 37 ), nb_points 12702 ( 146 x 87 )
+    nb_cores 1116 ( 36 x 31 ), nb_points 12688 ( 122 x 104 )
+    nb_cores 1118 ( 43 x 26 ), nb_points 12669 ( 103 x 123 )
+    nb_cores 1120 ( 32 x 35 ), nb_points 12604 ( 137 x 92 )
+    nb_cores 1125 ( 45 x 25 ), nb_points 12544 ( 98 x 128 )
+    nb_cores 1131 ( 29 x 39 ), nb_points 12533 ( 151 x 83 )
+    nb_cores 1134 ( 54 x 21 ), nb_points 12464 ( 82 x 152 )
+    nb_cores 1140 ( 30 x 38 ), nb_points 12410 ( 146 x 85 )
+    nb_cores 1147 ( 31 x 37 ), nb_points 12354 ( 142 x 87 )
+    nb_cores 1150 ( 46 x 25 ), nb_points 12288 ( 96 x 128 )
+    nb_cores 1155 ( 33 x 35 ), nb_points 12236 ( 133 x 92 )
+    nb_cores 1160 ( 40 x 29 ), nb_points 12210 ( 110 x 111 )
+    nb_cores 1166 ( 53 x 22 ), nb_points 12180 ( 84 x 145 )
+    nb_cores 1170 ( 45 x 26 ), nb_points 12054 ( 98 x 123 )
+    nb_cores 1175 ( 47 x 25 ), nb_points 12032 ( 94 x 128 )
+    nb_cores 1184 ( 32 x 37 ), nb_points 11919 ( 137 x 87 )
+    nb_cores 1188 ( 54 x 22 ), nb_points 11890 ( 82 x 145 )
+    nb_cores 1196 ( 46 x 26 ), nb_points 11808 ( 96 x 123 )
+    nb_cores 1200 ( 40 x 30 ), nb_points 11770 ( 110 x 107 )
+    nb_cores 1209 ( 39 x 31 ), nb_points 11752 ( 113 x 104 )
+    nb_cores 1210 ( 55 x 22 ), nb_points 11745 ( 81 x 145 )
+    nb_cores 1215 ( 45 x 27 ), nb_points 11662 ( 98 x 119 )
+    nb_cores 1216 ( 32 x 38 ), nb_points 11645 ( 137 x 85 )
+    nb_cores 1218 ( 29 x 42 ), nb_points 11627 ( 151 x 77 )
+    nb_cores 1221 ( 33 x 37 ), nb_points 11571 ( 133 x 87 )
+    nb_cores 1222 ( 47 x 26 ), nb_points 11562 ( 94 x 123 )
+    nb_cores 1230 ( 30 x 41 ), nb_points 11534 ( 146 x 79 )
+    nb_cores 1240 ( 40 x 31 ), nb_points 11440 ( 110 x 104 )
+    nb_cores 1242 ( 54 x 23 ), nb_points 11398 ( 82 x 139 )
+    nb_cores 1248 ( 48 x 26 ), nb_points 11316 ( 92 x 123 )
+    nb_cores 1254 ( 33 x 38 ), nb_points 11305 ( 133 x 85 )
+    nb_cores 1260 ( 36 x 35 ), nb_points 11224 ( 122 x 92 )
+    nb_cores 1269 ( 27 x 47 ), nb_points 11178 ( 162 x 69 )
+    nb_cores 1275 ( 51 x 25 ), nb_points 11136 ( 87 x 128 )
+    nb_cores 1280 ( 32 x 40 ), nb_points 11097 ( 137 x 81 )
+    nb_cores 1281 ( 61 x 21 ), nb_points 11096 ( 73 x 152 )
+    nb_cores 1287 ( 33 x 39 ), nb_points 11039 ( 133 x 83 )
+    nb_cores 1290 ( 43 x 30 ), nb_points 11021 ( 103 x 107 )
+    nb_cores 1292 ( 38 x 34 ), nb_points 11020 ( 116 x 95 )
+    nb_cores 1295 ( 37 x 35 ), nb_points 10948 ( 119 x 92 )
+    nb_cores 1300 ( 50 x 26 ), nb_points 10947 ( 89 x 123 )
+    nb_cores 1302 ( 42 x 31 ), nb_points 10920 ( 105 x 104 )
+    nb_cores 1305 ( 29 x 45 ), nb_points 10872 ( 151 x 72 )
+    nb_cores 1311 ( 57 x 23 ), nb_points 10842 ( 78 x 139 )
+    nb_cores 1312 ( 32 x 41 ), nb_points 10823 ( 137 x 79 )
+    nb_cores 1316 ( 47 x 28 ), nb_points 10810 ( 94 x 115 )
+    nb_cores 1320 ( 60 x 22 ), nb_points 10730 ( 74 x 145 )
+    nb_cores 1326 ( 51 x 26 ), nb_points 10701 ( 87 x 123 )
+    nb_cores 1330 ( 38 x 35 ), nb_points 10672 ( 116 x 92 )
+    nb_cores 1332 ( 36 x 37 ), nb_points 10614 ( 122 x 87 )
+    nb_cores 1342 ( 61 x 22 ), nb_points 10585 ( 73 x 145 )
+    nb_cores 1344 ( 32 x 42 ), nb_points 10549 ( 137 x 77 )
+    nb_cores 1350 ( 45 x 30 ), nb_points 10486 ( 98 x 107 )
+    nb_cores 1360 ( 40 x 34 ), nb_points 10450 ( 110 x 95 )
+    nb_cores 1363 ( 29 x 47 ), nb_points 10419 ( 151 x 69 )
+    nb_cores 1365 ( 39 x 35 ), nb_points 10396 ( 113 x 92 )
+    nb_cores 1368 ( 36 x 38 ), nb_points 10370 ( 122 x 85 )
+    nb_cores 1369 ( 37 x 37 ), nb_points 10353 ( 119 x 87 )
+    nb_cores 1378 ( 53 x 26 ), nb_points 10332 ( 84 x 123 )
+    nb_cores 1380 ( 46 x 30 ), nb_points 10272 ( 96 x 107 )
+    nb_cores 1386 ( 33 x 42 ), nb_points 10241 ( 133 x 77 )
+    nb_cores 1392 ( 48 x 29 ), nb_points 10212 ( 92 x 111 )
+    nb_cores 1395 ( 45 x 31 ), nb_points 10192 ( 98 x 104 )
+    nb_cores 1400 ( 40 x 35 ), nb_points 10120 ( 110 x 92 )
+    nb_cores 1404 ( 54 x 26 ), nb_points 10086 ( 82 x 123 )
+    nb_cores 1410 ( 47 x 30 ), nb_points 10058 ( 94 x 107 )
+    nb_cores 1425 ( 57 x 25 ), nb_points 9984 ( 78 x 128 )
+    nb_cores 1428 ( 42 x 34 ), nb_points 9975 ( 105 x 95 )
+    nb_cores 1430 ( 55 x 26 ), nb_points 9963 ( 81 x 123 )
+    nb_cores 1435 ( 41 x 35 ), nb_points 9936 ( 108 x 92 )
+    nb_cores 1440 ( 48 x 30 ), nb_points 9844 ( 92 x 107 )
+    nb_cores 1443 ( 39 x 37 ), nb_points 9831 ( 113 x 87 )
+    nb_cores 1450 ( 29 x 50 ), nb_points 9815 ( 151 x 65 )
+    nb_cores 1457 ( 47 x 31 ), nb_points 9776 ( 94 x 104 )
+    nb_cores 1458 ( 54 x 27 ), nb_points 9758 ( 82 x 119 )
+    nb_cores 1470 ( 42 x 35 ), nb_points 9660 ( 105 x 92 )
+    nb_cores 1476 ( 36 x 41 ), nb_points 9638 ( 122 x 79 )
+    nb_cores 1480 ( 40 x 37 ), nb_points 9570 ( 110 x 87 )
+    nb_cores 1488 ( 48 x 31 ), nb_points 9568 ( 92 x 104 )
+    nb_cores 1500 ( 60 x 25 ), nb_points 9472 ( 74 x 128 )
+    nb_cores 1504 ( 32 x 47 ), nb_points 9453 ( 137 x 69 )
+    nb_cores 1512 ( 36 x 42 ), nb_points 9394 ( 122 x 77 )
+    nb_cores 1520 ( 40 x 38 ), nb_points 9350 ( 110 x 85 )
+    nb_cores 1525 ( 61 x 25 ), nb_points 9344 ( 73 x 128 )
+    nb_cores 1530 ( 51 x 30 ), nb_points 9309 ( 87 x 107 )
+    nb_cores 1536 ( 48 x 32 ), nb_points 9292 ( 92 x 101 )
+    nb_cores 1539 ( 57 x 27 ), nb_points 9282 ( 78 x 119 )
+    nb_cores 1540 ( 70 x 22 ), nb_points 9280 ( 64 x 145 )
+    nb_cores 1548 ( 43 x 36 ), nb_points 9270 ( 103 x 90 )
+    nb_cores 1550 ( 62 x 25 ), nb_points 9216 ( 72 x 128 )
+    nb_cores 1551 ( 33 x 47 ), nb_points 9177 ( 133 x 69 )
+    nb_cores 1554 ( 42 x 37 ), nb_points 9135 ( 105 x 87 )
+    nb_cores 1560 ( 60 x 26 ), nb_points 9102 ( 74 x 123 )
+    nb_cores 1575 ( 45 x 35 ), nb_points 9016 ( 98 x 92 )
+    nb_cores 1584 ( 72 x 22 ), nb_points 8990 ( 62 x 145 )
+    nb_cores 1586 ( 61 x 26 ), nb_points 8979 ( 73 x 123 )
+    nb_cores 1591 ( 43 x 37 ), nb_points 8961 ( 103 x 87 )
+    nb_cores 1596 ( 42 x 38 ), nb_points 8925 ( 105 x 85 )
+    nb_cores 1600 ( 32 x 50 ), nb_points 8905 ( 137 x 65 )
+    nb_cores 1610 ( 46 x 35 ), nb_points 8832 ( 96 x 92 )
+    nb_cores 1620 ( 54 x 30 ), nb_points 8774 ( 82 x 107 )
+    nb_cores 1632 ( 48 x 34 ), nb_points 8740 ( 92 x 95 )
+    nb_cores 1638 ( 39 x 42 ), nb_points 8701 ( 113 x 77 )
+    nb_cores 1640 ( 40 x 41 ), nb_points 8690 ( 110 x 79 )
+    nb_cores 1645 ( 47 x 35 ), nb_points 8648 ( 94 x 92 )
+    nb_cores 1650 ( 33 x 50 ), nb_points 8645 ( 133 x 65 )
+    nb_cores 1656 ( 72 x 23 ), nb_points 8618 ( 62 x 139 )
+    nb_cores 1664 ( 64 x 26 ), nb_points 8610 ( 70 x 123 )
+    nb_cores 1665 ( 45 x 37 ), nb_points 8526 ( 98 x 87 )
+    nb_cores 1680 ( 48 x 35 ), nb_points 8464 ( 92 x 92 )
+    nb_cores 1692 ( 36 x 47 ), nb_points 8418 ( 122 x 69 )
+    nb_cores 1702 ( 46 x 37 ), nb_points 8352 ( 96 x 87 )
+    nb_cores 1710 ( 45 x 38 ), nb_points 8330 ( 98 x 85 )
+    nb_cores 1722 ( 42 x 41 ), nb_points 8295 ( 105 x 79 )
+    nb_cores 1728 ( 48 x 36 ), nb_points 8280 ( 92 x 90 )
+    nb_cores 1734 ( 51 x 34 ), nb_points 8265 ( 87 x 95 )
+    nb_cores 1739 ( 47 x 37 ), nb_points 8178 ( 94 x 87 )
+    nb_cores 1748 ( 46 x 38 ), nb_points 8160 ( 96 x 85 )
+    nb_cores 1755 ( 45 x 39 ), nb_points 8134 ( 98 x 83 )
+    nb_cores 1760 ( 80 x 22 ), nb_points 8120 ( 56 x 145 )
+    nb_cores 1764 ( 42 x 42 ), nb_points 8085 ( 105 x 77 )
+    nb_cores 1775 ( 71 x 25 ), nb_points 8064 ( 63 x 128 )
+    nb_cores 1776 ( 48 x 37 ), nb_points 8004 ( 92 x 87 )
+    nb_cores 1786 ( 47 x 38 ), nb_points 7990 ( 94 x 85 )
+    nb_cores 1794 ( 46 x 39 ), nb_points 7968 ( 96 x 83 )
+    nb_cores 1800 ( 60 x 30 ), nb_points 7918 ( 74 x 107 )
+    nb_cores 1813 ( 49 x 37 ), nb_points 7917 ( 91 x 87 )
+    nb_cores 1820 ( 70 x 26 ), nb_points 7872 ( 64 x 123 )
+    nb_cores 1824 ( 48 x 38 ), nb_points 7820 ( 92 x 85 )
+    nb_cores 1830 ( 61 x 30 ), nb_points 7811 ( 73 x 107 )
+    nb_cores 1833 ( 39 x 47 ), nb_points 7797 ( 113 x 69 )
+    nb_cores 1836 ( 54 x 34 ), nb_points 7790 ( 82 x 95 )
+    nb_cores 1840 ( 46 x 40 ), nb_points 7776 ( 96 x 81 )
+    nb_cores 1845 ( 45 x 41 ), nb_points 7742 ( 98 x 79 )
+    nb_cores 1850 ( 37 x 50 ), nb_points 7735 ( 119 x 65 )
+    nb_cores 1855 ( 53 x 35 ), nb_points 7728 ( 84 x 92 )
+    nb_cores 1860 ( 60 x 31 ), nb_points 7696 ( 74 x 104 )
+    nb_cores 1870 ( 85 x 22 ), nb_points 7685 ( 53 x 145 )
+    nb_cores 1872 ( 72 x 26 ), nb_points 7626 ( 62 x 123 )
+    nb_cores 1880 ( 40 x 47 ), nb_points 7590 ( 110 x 69 )
+    nb_cores 1886 ( 46 x 41 ), nb_points 7584 ( 96 x 79 )
+    nb_cores 1887 ( 51 x 37 ), nb_points 7569 ( 87 x 87 )
+    nb_cores 1890 ( 54 x 35 ), nb_points 7544 ( 82 x 92 )
+    nb_cores 1900 ( 38 x 50 ), nb_points 7540 ( 116 x 65 )
+    nb_cores 1917 ( 71 x 27 ), nb_points 7497 ( 63 x 119 )
+    nb_cores 1920 ( 48 x 40 ), nb_points 7452 ( 92 x 81 )
+    nb_cores 1927 ( 47 x 41 ), nb_points 7426 ( 94 x 79 )
+    nb_cores 1932 ( 46 x 42 ), nb_points 7392 ( 96 x 77 )
+    nb_cores 1944 ( 72 x 27 ), nb_points 7378 ( 62 x 119 )
+    nb_cores 1950 ( 39 x 50 ), nb_points 7345 ( 113 x 65 )
+    nb_cores 1961 ( 53 x 37 ), nb_points 7308 ( 84 x 87 )
+    nb_cores 1968 ( 48 x 41 ), nb_points 7268 ( 92 x 79 )
+    nb_cores 1974 ( 47 x 42 ), nb_points 7238 ( 94 x 77 )
+    nb_cores 1989 ( 51 x 39 ), nb_points 7221 ( 87 x 83 )
+    nb_cores 1995 ( 57 x 35 ), nb_points 7176 ( 78 x 92 )
+    nb_cores 1998 ( 54 x 37 ), nb_points 7134 ( 82 x 87 )
+    nb_cores 2016 ( 48 x 42 ), nb_points 7084 ( 92 x 77 )
+    nb_cores 2025 ( 45 x 45 ), nb_points 7056 ( 98 x 72 )
+    nb_cores 2035 ( 55 x 37 ), nb_points 7047 ( 81 x 87 )
+    nb_cores 2040 ( 60 x 34 ), nb_points 7030 ( 74 x 95 )
+    nb_cores 2050 ( 41 x 50 ), nb_points 7020 ( 108 x 65 )
+    nb_cores 2052 ( 54 x 38 ), nb_points 6970 ( 82 x 85 )
+    nb_cores 2068 ( 47 x 44 ), nb_points 6956 ( 94 x 74 )
+    nb_cores 2070 ( 46 x 45 ), nb_points 6912 ( 96 x 72 )
+    nb_cores 2080 ( 80 x 26 ), nb_points 6888 ( 56 x 123 )
+    nb_cores 2088 ( 72 x 29 ), nb_points 6882 ( 62 x 111 )
+    nb_cores 2091 ( 51 x 41 ), nb_points 6873 ( 87 x 79 )
+    nb_cores 2100 ( 60 x 35 ), nb_points 6808 ( 74 x 92 )
+    nb_cores 2106 ( 54 x 39 ), nb_points 6806 ( 82 x 83 )
+    nb_cores 2109 ( 57 x 37 ), nb_points 6786 ( 78 x 87 )
+    nb_cores 2115 ( 45 x 47 ), nb_points 6762 ( 98 x 69 )
+    nb_cores 2130 ( 71 x 30 ), nb_points 6741 ( 63 x 107 )
+    nb_cores 2135 ( 61 x 35 ), nb_points 6716 ( 73 x 92 )
+    nb_cores 2142 ( 51 x 42 ), nb_points 6699 ( 87 x 77 )
+    nb_cores 2150 ( 43 x 50 ), nb_points 6695 ( 103 x 65 )
+    nb_cores 2160 ( 48 x 45 ), nb_points 6624 ( 92 x 72 )
+    nb_cores 2183 ( 59 x 37 ), nb_points 6612 ( 76 x 87 )
+    nb_cores 2193 ( 43 x 51 ), nb_points 6592 ( 103 x 64 )
+    nb_cores 2196 ( 61 x 36 ), nb_points 6570 ( 73 x 90 )
+    nb_cores 2200 ( 55 x 40 ), nb_points 6561 ( 81 x 81 )
+    nb_cores 2201 ( 71 x 31 ), nb_points 6552 ( 63 x 104 )
+    nb_cores 2204 ( 58 x 38 ), nb_points 6545 ( 77 x 85 )
+    nb_cores 2205 ( 63 x 35 ), nb_points 6532 ( 71 x 92 )
+    nb_cores 2208 ( 46 x 48 ), nb_points 6528 ( 96 x 68 )
+    nb_cores 2209 ( 47 x 47 ), nb_points 6486 ( 94 x 69 )
+    nb_cores 2214 ( 54 x 41 ), nb_points 6478 ( 82 x 79 )
+    nb_cores 2220 ( 60 x 37 ), nb_points 6438 ( 74 x 87 )
+    nb_cores 2250 ( 45 x 50 ), nb_points 6370 ( 98 x 65 )
+    nb_cores 2256 ( 48 x 47 ), nb_points 6348 ( 92 x 69 )
+    nb_cores 2268 ( 54 x 42 ), nb_points 6314 ( 82 x 77 )
+    nb_cores 2280 ( 60 x 38 ), nb_points 6290 ( 74 x 85 )
+    nb_cores 2294 ( 62 x 37 ), nb_points 6264 ( 72 x 87 )
+    nb_cores 2300 ( 46 x 50 ), nb_points 6240 ( 96 x 65 )
+    nb_cores 2310 ( 55 x 42 ), nb_points 6237 ( 81 x 77 )
+    nb_cores 2318 ( 61 x 38 ), nb_points 6205 ( 73 x 85 )
+    nb_cores 2331 ( 63 x 37 ), nb_points 6177 ( 71 x 87 )
+    nb_cores 2337 ( 57 x 41 ), nb_points 6162 ( 78 x 79 )
+    nb_cores 2340 ( 60 x 39 ), nb_points 6142 ( 74 x 83 )
+    nb_cores 2350 ( 47 x 50 ), nb_points 6110 ( 94 x 65 )
+    nb_cores 2368 ( 64 x 37 ), nb_points 6090 ( 70 x 87 )
+    nb_cores 2376 ( 54 x 44 ), nb_points 6068 ( 82 x 74 )
+    nb_cores 2379 ( 61 x 39 ), nb_points 6059 ( 73 x 83 )
+    nb_cores 2385 ( 53 x 45 ), nb_points 6048 ( 84 x 72 )
+    nb_cores 2392 ( 92 x 26 ), nb_points 6027 ( 49 x 123 )
+    nb_cores 2394 ( 57 x 42 ), nb_points 6006 ( 78 x 77 )
+    nb_cores 2397 ( 51 x 47 ), nb_points 6003 ( 87 x 69 )
+    nb_cores 2400 ( 48 x 50 ), nb_points 5980 ( 92 x 65 )
+    nb_cores 2412 ( 36 x 67 ), nb_points 5978 ( 122 x 49 )
+    nb_cores 2418 ( 62 x 39 ), nb_points 5976 ( 72 x 83 )
+    nb_cores 2430 ( 54 x 45 ), nb_points 5904 ( 82 x 72 )
+    nb_cores 2448 ( 48 x 51 ), nb_points 5888 ( 92 x 64 )
+    nb_cores 2457 ( 39 x 63 ), nb_points 5876 ( 113 x 52 )
+    nb_cores 2460 ( 60 x 41 ), nb_points 5846 ( 74 x 79 )
+    nb_cores 2475 ( 55 x 45 ), nb_points 5832 ( 81 x 72 )
+    nb_cores 2479 ( 67 x 37 ), nb_points 5829 ( 67 x 87 )
+    nb_cores 2480 ( 80 x 31 ), nb_points 5824 ( 56 x 104 )
+    nb_cores 2484 ( 54 x 46 ), nb_points 5822 ( 82 x 71 )
+    nb_cores 2485 ( 71 x 35 ), nb_points 5796 ( 63 x 92 )
+    nb_cores 2496 ( 96 x 26 ), nb_points 5781 ( 47 x 123 )
+    nb_cores 2501 ( 61 x 41 ), nb_points 5767 ( 73 x 79 )
+    nb_cores 2516 ( 68 x 37 ), nb_points 5742 ( 66 x 87 )
+    nb_cores 2520 ( 60 x 42 ), nb_points 5698 ( 74 x 77 )
+    nb_cores 2538 ( 54 x 47 ), nb_points 5658 ( 82 x 69 )
+    nb_cores 2550 ( 51 x 50 ), nb_points 5655 ( 87 x 65 )
+    nb_cores 2562 ( 61 x 42 ), nb_points 5621 ( 73 x 77 )
+    nb_cores 2565 ( 57 x 45 ), nb_points 5616 ( 78 x 72 )
+    nb_cores 2583 ( 63 x 41 ), nb_points 5609 ( 71 x 79 )
+    nb_cores 2584 ( 76 x 34 ), nb_points 5605 ( 59 x 95 )
+    nb_cores 2585 ( 55 x 47 ), nb_points 5589 ( 81 x 69 )
+    nb_cores 2590 ( 70 x 37 ), nb_points 5568 ( 64 x 87 )
+    nb_cores 2604 ( 62 x 42 ), nb_points 5544 ( 72 x 77 )
+    nb_cores 2613 ( 39 x 67 ), nb_points 5537 ( 113 x 49 )
+    nb_cores 2622 ( 69 x 38 ), nb_points 5525 ( 65 x 85 )
+    nb_cores 2625 ( 75 x 35 ), nb_points 5520 ( 60 x 92 )
+    nb_cores 2627 ( 71 x 37 ), nb_points 5481 ( 63 x 87 )
+    nb_cores 2640 ( 60 x 44 ), nb_points 5476 ( 74 x 74 )
+    nb_cores 2646 ( 42 x 63 ), nb_points 5460 ( 105 x 52 )
+    nb_cores 2660 ( 76 x 35 ), nb_points 5428 ( 59 x 92 )
+    nb_cores 2664 ( 72 x 37 ), nb_points 5394 ( 62 x 87 )
+    nb_cores 2679 ( 57 x 47 ), nb_points 5382 ( 78 x 69 )
+    nb_cores 2698 ( 71 x 38 ), nb_points 5355 ( 63 x 85 )
+    nb_cores 2700 ( 60 x 45 ), nb_points 5328 ( 74 x 72 )
+    nb_cores 2720 ( 80 x 34 ), nb_points 5320 ( 56 x 95 )
+    nb_cores 2726 ( 58 x 47 ), nb_points 5313 ( 77 x 69 )
+    nb_cores 2730 ( 39 x 70 ), nb_points 5311 ( 113 x 47 )
+    nb_cores 2736 ( 72 x 38 ), nb_points 5270 ( 62 x 85 )
+    nb_cores 2745 ( 61 x 45 ), nb_points 5256 ( 73 x 72 )
+    nb_cores 2754 ( 54 x 51 ), nb_points 5248 ( 82 x 64 )
+    nb_cores 2760 ( 92 x 30 ), nb_points 5243 ( 49 x 107 )
+    nb_cores 2769 ( 71 x 39 ), nb_points 5229 ( 63 x 83 )
+    nb_cores 2775 ( 75 x 37 ), nb_points 5220 ( 60 x 87 )
+    nb_cores 2784 ( 96 x 29 ), nb_points 5217 ( 47 x 111 )
+    nb_cores 2788 ( 68 x 41 ), nb_points 5214 ( 66 x 79 )
+    nb_cores 2790 ( 62 x 45 ), nb_points 5184 ( 72 x 72 )
+    nb_cores 2800 ( 80 x 35 ), nb_points 5152 ( 56 x 92 )
+    nb_cores 2808 ( 72 x 39 ), nb_points 5146 ( 62 x 83 )
+    nb_cores 2812 ( 76 x 37 ), nb_points 5133 ( 59 x 87 )
+    nb_cores 2820 ( 60 x 47 ), nb_points 5106 ( 74 x 69 )
+    nb_cores 2835 ( 45 x 63 ), nb_points 5096 ( 98 x 52 )
+    nb_cores 2850 ( 57 x 50 ), nb_points 5070 ( 78 x 65 )
+    nb_cores 2867 ( 61 x 47 ), nb_points 5037 ( 73 x 69 )
+    nb_cores 2880 ( 72 x 40 ), nb_points 5022 ( 62 x 81 )
+    nb_cores 2888 ( 76 x 38 ), nb_points 5015 ( 59 x 85 )
+    nb_cores 2898 ( 46 x 63 ), nb_points 4992 ( 96 x 52 )
+    nb_cores 2911 ( 71 x 41 ), nb_points 4977 ( 63 x 79 )
+    nb_cores 2914 ( 62 x 47 ), nb_points 4968 ( 72 x 69 )
+    nb_cores 2923 ( 79 x 37 ), nb_points 4959 ( 57 x 87 )
+    nb_cores 2940 ( 70 x 42 ), nb_points 4928 ( 64 x 77 )
+    nb_cores 2952 ( 72 x 41 ), nb_points 4898 ( 62 x 79 )
+    nb_cores 2960 ( 80 x 37 ), nb_points 4872 ( 56 x 87 )
+    nb_cores 2982 ( 71 x 42 ), nb_points 4851 ( 63 x 77 )
+    nb_cores 3000 ( 60 x 50 ), nb_points 4810 ( 74 x 65 )
+    nb_cores 3015 ( 45 x 67 ), nb_points 4802 ( 98 x 49 )
+    nb_cores 3024 ( 72 x 42 ), nb_points 4774 ( 62 x 77 )
+    nb_cores 3040 ( 80 x 38 ), nb_points 4760 ( 56 x 85 )
+    nb_cores 3050 ( 61 x 50 ), nb_points 4745 ( 73 x 65 )
+    nb_cores 3060 ( 60 x 51 ), nb_points 4736 ( 74 x 64 )
+    nb_cores 3080 ( 40 x 77 ), nb_points 4730 ( 110 x 43 )
+    nb_cores 3082 ( 46 x 67 ), nb_points 4704 ( 96 x 49 )
+    nb_cores 3100 ( 62 x 50 ), nb_points 4680 ( 72 x 65 )
+    nb_cores 3111 ( 61 x 51 ), nb_points 4672 ( 73 x 64 )
+    nb_cores 3116 ( 76 x 41 ), nb_points 4661 ( 59 x 79 )
+    nb_cores 3120 ( 80 x 39 ), nb_points 4648 ( 56 x 83 )
+    nb_cores 3145 ( 85 x 37 ), nb_points 4611 ( 53 x 87 )
+    nb_cores 3149 ( 47 x 67 ), nb_points 4606 ( 94 x 49 )
+    nb_cores 3150 ( 90 x 35 ), nb_points 4600 ( 50 x 92 )
+    nb_cores 3168 ( 72 x 44 ), nb_points 4588 ( 62 x 74 )
+    nb_cores 3192 ( 76 x 42 ), nb_points 4543 ( 59 x 77 )
+    nb_cores 3195 ( 71 x 45 ), nb_points 4536 ( 63 x 72 )
+    nb_cores 3213 ( 51 x 63 ), nb_points 4524 ( 87 x 52 )
+    nb_cores 3216 ( 48 x 67 ), nb_points 4508 ( 92 x 49 )
+    nb_cores 3230 ( 85 x 38 ), nb_points 4505 ( 53 x 85 )
+    nb_cores 3239 ( 79 x 41 ), nb_points 4503 ( 57 x 79 )
+    nb_cores 3240 ( 72 x 45 ), nb_points 4464 ( 62 x 72 )
+    nb_cores 3280 ( 80 x 41 ), nb_points 4424 ( 56 x 79 )
+    nb_cores 3290 ( 94 x 35 ), nb_points 4416 ( 48 x 92 )
+    nb_cores 3290 ( 70 x 47 ), nb_points 4416 ( 64 x 69 )
+    nb_cores 3312 ( 72 x 46 ), nb_points 4402 ( 62 x 71 )
+    nb_cores 3315 ( 85 x 39 ), nb_points 4399 ( 53 x 83 )
+    nb_cores 3318 ( 79 x 42 ), nb_points 4389 ( 57 x 77 )
+    nb_cores 3330 ( 90 x 37 ), nb_points 4350 ( 50 x 87 )
+    nb_cores 3337 ( 71 x 47 ), nb_points 4347 ( 63 x 69 )
+    nb_cores 3348 ( 54 x 62 ), nb_points 4346 ( 82 x 53 )
+    nb_cores 3360 ( 80 x 42 ), nb_points 4312 ( 56 x 77 )
+    nb_cores 3384 ( 72 x 47 ), nb_points 4278 ( 62 x 69 )
+    nb_cores 3402 ( 54 x 63 ), nb_points 4264 ( 82 x 52 )
+    nb_cores 3404 ( 92 x 37 ), nb_points 4263 ( 49 x 87 )
+    nb_cores 3420 ( 76 x 45 ), nb_points 4248 ( 59 x 72 )
+    nb_cores 3444 ( 82 x 42 ), nb_points 4235 ( 55 x 77 )
+    nb_cores 3450 ( 46 x 75 ), nb_points 4224 ( 96 x 44 )
+    nb_cores 3456 ( 72 x 48 ), nb_points 4216 ( 62 x 68 )
+    nb_cores 3465 ( 55 x 63 ), nb_points 4212 ( 81 x 52 )
+    nb_cores 3478 ( 94 x 37 ), nb_points 4176 ( 48 x 87 )
+    nb_cores 3496 ( 92 x 38 ), nb_points 4165 ( 49 x 85 )
+    nb_cores 3500 ( 70 x 50 ), nb_points 4160 ( 64 x 65 )
+    nb_cores 3510 ( 90 x 39 ), nb_points 4150 ( 50 x 83 )
+    nb_cores 3520 ( 80 x 44 ), nb_points 4144 ( 56 x 74 )
+    nb_cores 3525 ( 47 x 75 ), nb_points 4136 ( 94 x 44 )
+    nb_cores 3534 ( 57 x 62 ), nb_points 4134 ( 78 x 53 )
+    nb_cores 3542 ( 46 x 77 ), nb_points 4128 ( 96 x 43 )
+    nb_cores 3550 ( 71 x 50 ), nb_points 4095 ( 63 x 65 )
+    nb_cores 3552 ( 96 x 37 ), nb_points 4089 ( 47 x 87 )
+    nb_cores 3570 ( 85 x 42 ), nb_points 4081 ( 53 x 77 )
+    nb_cores 3572 ( 76 x 47 ), nb_points 4071 ( 59 x 69 )
+    nb_cores 3588 ( 92 x 39 ), nb_points 4067 ( 49 x 83 )
+    nb_cores 3591 ( 57 x 63 ), nb_points 4056 ( 78 x 52 )
+    nb_cores 3600 ( 72 x 50 ), nb_points 4030 ( 62 x 65 )
+    nb_cores 3618 ( 54 x 67 ), nb_points 4018 ( 82 x 49 )
+    nb_cores 3648 ( 96 x 38 ), nb_points 3995 ( 47 x 85 )
+    nb_cores 3666 ( 94 x 39 ), nb_points 3984 ( 48 x 83 )
+    nb_cores 3672 ( 72 x 51 ), nb_points 3968 ( 62 x 64 )
+    nb_cores 3690 ( 90 x 41 ), nb_points 3950 ( 50 x 79 )
+    nb_cores 3710 ( 53 x 70 ), nb_points 3948 ( 84 x 47 )
+    nb_cores 3713 ( 79 x 47 ), nb_points 3933 ( 57 x 69 )
+    nb_cores 3720 ( 60 x 62 ), nb_points 3922 ( 74 x 53 )
+    nb_cores 3735 ( 45 x 83 ), nb_points 3920 ( 98 x 40 )
+    nb_cores 3737 ( 101 x 37 ), nb_points 3915 ( 45 x 87 )
+    nb_cores 3744 ( 96 x 39 ), nb_points 3901 ( 47 x 83 )
+    nb_cores 3750 ( 75 x 50 ), nb_points 3900 ( 60 x 65 )
+    nb_cores 3760 ( 80 x 47 ), nb_points 3864 ( 56 x 69 )
+    nb_cores 3780 ( 60 x 63 ), nb_points 3848 ( 74 x 52 )
+    nb_cores 3800 ( 76 x 50 ), nb_points 3835 ( 59 x 65 )
+    nb_cores 3811 ( 103 x 37 ), nb_points 3828 ( 44 x 87 )
+    nb_cores 3819 ( 57 x 67 ), nb_points 3822 ( 78 x 49 )
+    nb_cores 3825 ( 85 x 45 ), nb_points 3816 ( 53 x 72 )
+    nb_cores 3840 ( 96 x 40 ), nb_points 3807 ( 47 x 81 )
+    nb_cores 3843 ( 61 x 63 ), nb_points 3796 ( 73 x 52 )
+    nb_cores 3854 ( 94 x 41 ), nb_points 3792 ( 48 x 79 )
+    nb_cores 3864 ( 92 x 42 ), nb_points 3773 ( 49 x 77 )
+    nb_cores 3885 ( 111 x 35 ), nb_points 3772 ( 41 x 92 )
+    nb_cores 3900 ( 78 x 50 ), nb_points 3770 ( 58 x 65 )
+    nb_cores 3901 ( 47 x 83 ), nb_points 3760 ( 94 x 40 )
+    nb_cores 3906 ( 62 x 63 ), nb_points 3744 ( 72 x 52 )
+    nb_cores 3914 ( 103 x 38 ), nb_points 3740 ( 44 x 85 )
+    nb_cores 3936 ( 96 x 41 ), nb_points 3713 ( 47 x 79 )
+    nb_cores 3948 ( 94 x 42 ), nb_points 3696 ( 48 x 77 )
+    nb_cores 3969 ( 63 x 63 ), nb_points 3692 ( 71 x 52 )
+    nb_cores 3984 ( 48 x 83 ), nb_points 3680 ( 92 x 40 )
+    nb_cores 3990 ( 57 x 70 ), nb_points 3666 ( 78 x 47 )
+    nb_cores 3995 ( 85 x 47 ), nb_points 3657 ( 53 x 69 )
+    nb_cores 3996 ( 108 x 37 ), nb_points 3654 ( 42 x 87 )
+    nb_cores 4000 ( 80 x 50 ), nb_points 3640 ( 56 x 65 )
+    nb_cores 4020 ( 60 x 67 ), nb_points 3626 ( 74 x 49 )
+    nb_cores 4032 ( 96 x 42 ), nb_points 3619 ( 47 x 77 )
+    nb_cores 4050 ( 90 x 45 ), nb_points 3600 ( 50 x 72 )
+    nb_cores 4080 ( 80 x 51 ), nb_points 3584 ( 56 x 64 )
+    nb_cores 4087 ( 61 x 67 ), nb_points 3577 ( 73 x 49 )
+    nb_cores 4100 ( 82 x 50 ), nb_points 3575 ( 55 x 65 )
+    nb_cores 4104 ( 108 x 38 ), nb_points 3570 ( 42 x 85 )
+    nb_cores 4107 ( 111 x 37 ), nb_points 3567 ( 41 x 87 )
+    nb_cores 4120 ( 103 x 40 ), nb_points 3564 ( 44 x 81 )
+    nb_cores 4136 ( 94 x 44 ), nb_points 3552 ( 48 x 74 )
+    nb_cores 4140 ( 92 x 45 ), nb_points 3528 ( 49 x 72 )
+    nb_cores 4158 ( 54 x 77 ), nb_points 3526 ( 82 x 43 )
+    nb_cores 4182 ( 82 x 51 ), nb_points 3520 ( 55 x 64 )
+    nb_cores 4183 ( 89 x 47 ), nb_points 3519 ( 51 x 69 )
+    nb_cores 4200 ( 60 x 70 ), nb_points 3478 ( 74 x 47 )
+    nb_cores 4223 ( 103 x 41 ), nb_points 3476 ( 44 x 79 )
+    nb_cores 4230 ( 90 x 47 ), nb_points 3450 ( 50 x 69 )
+    nb_cores 4250 ( 85 x 50 ), nb_points 3445 ( 53 x 65 )
+    nb_cores 4266 ( 54 x 79 ), nb_points 3444 ( 82 x 42 )
+    nb_cores 4270 ( 61 x 70 ), nb_points 3431 ( 73 x 47 )
+    nb_cores 4288 ( 64 x 67 ), nb_points 3430 ( 70 x 49 )
+    nb_cores 4320 ( 96 x 45 ), nb_points 3384 ( 47 x 72 )
+    nb_cores 4324 ( 92 x 47 ), nb_points 3381 ( 49 x 69 )
+    nb_cores 4347 ( 69 x 63 ), nb_points 3380 ( 65 x 52 )
+    nb_cores 4374 ( 54 x 81 ), nb_points 3362 ( 82 x 41 )
+    nb_cores 4389 ( 57 x 77 ), nb_points 3354 ( 78 x 43 )
+    nb_cores 4392 ( 72 x 61 ), nb_points 3348 ( 62 x 54 )
+    nb_cores 4402 ( 71 x 62 ), nb_points 3339 ( 63 x 53 )
+    nb_cores 4410 ( 70 x 63 ), nb_points 3328 ( 64 x 52 )
+    nb_cores 4418 ( 94 x 47 ), nb_points 3312 ( 48 x 69 )
+    nb_cores 4440 ( 120 x 37 ), nb_points 3306 ( 38 x 87 )
+    nb_cores 4464 ( 72 x 62 ), nb_points 3286 ( 62 x 53 )
+    nb_cores 4473 ( 71 x 63 ), nb_points 3276 ( 63 x 52 )
+    nb_cores 4500 ( 90 x 50 ), nb_points 3250 ( 50 x 65 )
+    nb_cores 4512 ( 96 x 47 ), nb_points 3243 ( 47 x 69 )
+    nb_cores 4536 ( 72 x 63 ), nb_points 3224 ( 62 x 52 )
+    nb_cores 4575 ( 61 x 75 ), nb_points 3212 ( 73 x 44 )
+    nb_cores 4590 ( 54 x 85 ), nb_points 3198 ( 82 x 39 )
+    nb_cores 4600 ( 92 x 50 ), nb_points 3185 ( 49 x 65 )
+    nb_cores 4620 ( 60 x 77 ), nb_points 3182 ( 74 x 43 )
+    nb_cores 4635 ( 103 x 45 ), nb_points 3168 ( 44 x 72 )
+    nb_cores 4662 ( 111 x 42 ), nb_points 3157 ( 41 x 77 )
+    nb_cores 4680 ( 90 x 52 ), nb_points 3150 ( 50 x 63 )
+    nb_cores 4690 ( 70 x 67 ), nb_points 3136 ( 64 x 49 )
+    nb_cores 4700 ( 94 x 50 ), nb_points 3120 ( 48 x 65 )
+    nb_cores 4740 ( 60 x 79 ), nb_points 3108 ( 74 x 42 )
+    nb_cores 4747 ( 101 x 47 ), nb_points 3105 ( 45 x 69 )
+    nb_cores 4752 ( 72 x 66 ), nb_points 3100 ( 62 x 50 )
+    nb_cores 4757 ( 71 x 67 ), nb_points 3087 ( 63 x 49 )
+    nb_cores 4788 ( 76 x 63 ), nb_points 3068 ( 59 x 52 )
+    nb_cores 4800 ( 96 x 50 ), nb_points 3055 ( 47 x 65 )
+    nb_cores 4824 ( 72 x 67 ), nb_points 3038 ( 62 x 49 )
+    nb_cores 4841 ( 103 x 47 ), nb_points 3036 ( 44 x 69 )
+    nb_cores 4860 ( 108 x 45 ), nb_points 3024 ( 42 x 72 )
+    nb_cores 4896 ( 96 x 51 ), nb_points 3008 ( 47 x 64 )
+    nb_cores 4914 ( 117 x 42 ), nb_points 3003 ( 39 x 77 )
+    nb_cores 4920 ( 120 x 41 ), nb_points 3002 ( 38 x 79 )
+    nb_cores 4941 ( 61 x 81 ), nb_points 2993 ( 73 x 41 )
+    nb_cores 4944 ( 103 x 48 ), nb_points 2992 ( 44 x 68 )
+    nb_cores 4950 ( 99 x 50 ), nb_points 2990 ( 46 x 65 )
+    nb_cores 4958 ( 74 x 67 ), nb_points 2989 ( 61 x 49 )
+    nb_cores 4960 ( 80 x 62 ), nb_points 2968 ( 56 x 53 )
+    nb_cores 4970 ( 71 x 70 ), nb_points 2961 ( 63 x 47 )
+    nb_cores 4980 ( 60 x 83 ), nb_points 2960 ( 74 x 40 )
+    nb_cores 4995 ( 111 x 45 ), nb_points 2952 ( 41 x 72 )
+    nb_cores 5016 ( 76 x 66 ), nb_points 2950 ( 59 x 50 )
+    nb_cores 5025 ( 75 x 67 ), nb_points 2940 ( 60 x 49 )
+    nb_cores 5040 ( 80 x 63 ), nb_points 2912 ( 56 x 52 )
+    nb_cores 5076 ( 108 x 47 ), nb_points 2898 ( 42 x 69 )
+    nb_cores 5092 ( 76 x 67 ), nb_points 2891 ( 59 x 49 )
+    nb_cores 5100 ( 60 x 85 ), nb_points 2886 ( 74 x 39 )
+    nb_cores 5130 ( 114 x 45 ), nb_points 2880 ( 40 x 72 )
+    nb_cores 5150 ( 103 x 50 ), nb_points 2860 ( 44 x 65 )
+    nb_cores 5184 ( 72 x 72 ), nb_points 2852 ( 62 x 46 )
+    nb_cores 5185 ( 61 x 85 ), nb_points 2847 ( 73 x 39 )
+    nb_cores 5217 ( 111 x 47 ), nb_points 2829 ( 41 x 69 )
+    nb_cores 5250 ( 70 x 75 ), nb_points 2816 ( 64 x 44 )
+    nb_cores 5265 ( 117 x 45 ), nb_points 2808 ( 39 x 72 )
+    nb_cores 5280 ( 80 x 66 ), nb_points 2800 ( 56 x 50 )
+    nb_cores 5293 ( 79 x 67 ), nb_points 2793 ( 57 x 49 )
+    nb_cores 5320 ( 76 x 70 ), nb_points 2773 ( 59 x 47 )
+    nb_cores 5325 ( 71 x 75 ), nb_points 2772 ( 63 x 44 )
+    nb_cores 5355 ( 85 x 63 ), nb_points 2756 ( 53 x 52 )
+    nb_cores 5360 ( 80 x 67 ), nb_points 2744 ( 56 x 49 )
+    nb_cores 5400 ( 72 x 75 ), nb_points 2728 ( 62 x 44 )
+    nb_cores 5460 ( 78 x 70 ), nb_points 2726 ( 58 x 47 )
+    nb_cores 5467 ( 71 x 77 ), nb_points 2709 ( 63 x 43 )
+    nb_cores 5481 ( 87 x 63 ), nb_points 2704 ( 52 x 52 )
+    nb_cores 5490 ( 90 x 61 ), nb_points 2700 ( 50 x 54 )
+    nb_cores 5494 ( 82 x 67 ), nb_points 2695 ( 55 x 49 )
+    nb_cores 5499 ( 117 x 47 ), nb_points 2691 ( 39 x 69 )
+    nb_cores 5508 ( 108 x 51 ), nb_points 2688 ( 42 x 64 )
+    nb_cores 5530 ( 79 x 70 ), nb_points 2679 ( 57 x 47 )
+    nb_cores 5544 ( 72 x 77 ), nb_points 2666 ( 62 x 43 )
+    nb_cores 5550 ( 111 x 50 ), nb_points 2665 ( 41 x 65 )
+    nb_cores 5580 ( 90 x 62 ), nb_points 2650 ( 50 x 53 )
+    nb_cores 5600 ( 80 x 70 ), nb_points 2632 ( 56 x 47 )
+    nb_cores 5640 ( 120 x 47 ), nb_points 2622 ( 38 x 69 )
+    nb_cores 5670 ( 90 x 63 ), nb_points 2600 ( 50 x 52 )
+    nb_cores 5695 ( 85 x 67 ), nb_points 2597 ( 53 x 49 )
+    nb_cores 5700 ( 76 x 75 ), nb_points 2596 ( 59 x 44 )
+    nb_cores 5734 ( 94 x 61 ), nb_points 2592 ( 48 x 54 )
+    nb_cores 5740 ( 82 x 70 ), nb_points 2585 ( 55 x 47 )
+    nb_cores 5751 ( 71 x 81 ), nb_points 2583 ( 63 x 41 )
+    nb_cores 5760 ( 80 x 72 ), nb_points 2576 ( 56 x 46 )
+    nb_cores 5780 ( 68 x 85 ), nb_points 2574 ( 66 x 39 )
+    nb_cores 5796 ( 92 x 63 ), nb_points 2548 ( 49 x 52 )
+    nb_cores 5828 ( 94 x 62 ), nb_points 2544 ( 48 x 53 )
+    nb_cores 5832 ( 72 x 81 ), nb_points 2542 ( 62 x 41 )
+    nb_cores 5850 ( 117 x 50 ), nb_points 2535 ( 39 x 65 )
+    nb_cores 5893 ( 71 x 83 ), nb_points 2520 ( 63 x 40 )
+    nb_cores 5922 ( 94 x 63 ), nb_points 2496 ( 48 x 52 )
+    nb_cores 5950 ( 85 x 70 ), nb_points 2491 ( 53 x 47 )
+    nb_cores 5976 ( 72 x 83 ), nb_points 2480 ( 62 x 40 )
+    nb_cores 6000 ( 80 x 75 ), nb_points 2464 ( 56 x 44 )
+    nb_cores 6030 ( 90 x 67 ), nb_points 2450 ( 50 x 49 )
+    nb_cores 6048 ( 96 x 63 ), nb_points 2444 ( 47 x 52 )
+    nb_cores 6120 ( 72 x 85 ), nb_points 2418 ( 62 x 39 )
+    nb_cores 6157 ( 131 x 47 ), nb_points 2415 ( 35 x 69 )
+    nb_cores 6160 ( 80 x 77 ), nb_points 2408 ( 56 x 43 )
+    nb_cores 6164 ( 92 x 67 ), nb_points 2401 ( 49 x 49 )
+    nb_cores 6204 ( 94 x 66 ), nb_points 2400 ( 48 x 50 )
+    nb_cores 6230 ( 89 x 70 ), nb_points 2397 ( 51 x 47 )
+    nb_cores 6237 ( 99 x 63 ), nb_points 2392 ( 46 x 52 )
+    nb_cores 6258 ( 149 x 42 ), nb_points 2387 ( 31 x 77 )
+    nb_cores 6262 ( 101 x 62 ), nb_points 2385 ( 45 x 53 )
+    nb_cores 6283 ( 103 x 61 ), nb_points 2376 ( 44 x 54 )
+    nb_cores 6298 ( 94 x 67 ), nb_points 2352 ( 48 x 49 )
+    nb_cores 6300 ( 90 x 70 ), nb_points 2350 ( 50 x 47 )
+    nb_cores 6345 ( 135 x 47 ), nb_points 2346 ( 34 x 69 )
+    nb_cores 6363 ( 101 x 63 ), nb_points 2340 ( 45 x 52 )
+    nb_cores 6375 ( 85 x 75 ), nb_points 2332 ( 53 x 44 )
+    nb_cores 6390 ( 71 x 90 ), nb_points 2331 ( 63 x 37 )
+    nb_cores 6432 ( 96 x 67 ), nb_points 2303 ( 47 x 49 )
+    nb_cores 6460 ( 76 x 85 ), nb_points 2301 ( 59 x 39 )
+    nb_cores 6480 ( 72 x 90 ), nb_points 2294 ( 62 x 37 )
+    nb_cores 6489 ( 103 x 63 ), nb_points 2288 ( 44 x 52 )
+    nb_cores 6545 ( 85 x 77 ), nb_points 2279 ( 53 x 43 )
+    nb_cores 6550 ( 131 x 50 ), nb_points 2275 ( 35 x 65 )
+    nb_cores 6580 ( 94 x 70 ), nb_points 2256 ( 48 x 47 )
+    nb_cores 6624 ( 92 x 72 ), nb_points 2254 ( 49 x 46 )
+    nb_cores 6640 ( 80 x 83 ), nb_points 2240 ( 56 x 40 )
+    nb_cores 6678 ( 106 x 63 ), nb_points 2236 ( 43 x 52 )
+    nb_cores 6696 ( 108 x 62 ), nb_points 2226 ( 42 x 53 )
+    nb_cores 6715 ( 79 x 85 ), nb_points 2223 ( 57 x 39 )
+    nb_cores 6720 ( 96 x 70 ), nb_points 2209 ( 47 x 47 )
+    nb_cores 6750 ( 90 x 75 ), nb_points 2200 ( 50 x 44 )
+    nb_cores 6800 ( 80 x 85 ), nb_points 2184 ( 56 x 39 )
+    nb_cores 6840 ( 76 x 90 ), nb_points 2183 ( 59 x 37 )
+    nb_cores 6882 ( 111 x 62 ), nb_points 2173 ( 41 x 53 )
+    nb_cores 6900 ( 92 x 75 ), nb_points 2156 ( 49 x 44 )
+    nb_cores 6930 ( 90 x 77 ), nb_points 2150 ( 50 x 43 )
+    nb_cores 6970 ( 82 x 85 ), nb_points 2145 ( 55 x 39 )
+    nb_cores 6993 ( 111 x 63 ), nb_points 2132 ( 41 x 52 )
+    nb_cores 7040 ( 80 x 88 ), nb_points 2128 ( 56 x 38 )
+    nb_cores 7050 ( 94 x 75 ), nb_points 2112 ( 48 x 44 )
+    nb_cores 7084 ( 92 x 77 ), nb_points 2107 ( 49 x 43 )
+    nb_cores 7110 ( 90 x 79 ), nb_points 2100 ( 50 x 42 )
+    nb_cores 7182 ( 114 x 63 ), nb_points 2080 ( 40 x 52 )
+    nb_cores 7200 ( 96 x 75 ), nb_points 2068 ( 47 x 44 )
+    nb_cores 7225 ( 85 x 85 ), nb_points 2067 ( 53 x 39 )
+    nb_cores 7236 ( 108 x 67 ), nb_points 2058 ( 42 x 49 )
+    nb_cores 7290 ( 90 x 81 ), nb_points 2050 ( 50 x 41 )
+    nb_cores 7344 ( 72 x 102 ), nb_points 2046 ( 62 x 33 )
+    nb_cores 7371 ( 117 x 63 ), nb_points 2028 ( 39 x 52 )
+    nb_cores 7392 ( 96 x 77 ), nb_points 2021 ( 47 x 43 )
+    nb_cores 7426 ( 94 x 79 ), nb_points 2016 ( 48 x 42 )
+    nb_cores 7437 ( 111 x 67 ), nb_points 2009 ( 41 x 49 )
+    nb_cores 7470 ( 90 x 83 ), nb_points 2000 ( 50 x 40 )
+    nb_cores 7560 ( 108 x 70 ), nb_points 1974 ( 42 x 47 )
+    nb_cores 7614 ( 94 x 81 ), nb_points 1968 ( 48 x 41 )
+    nb_cores 7636 ( 92 x 83 ), nb_points 1960 ( 49 x 40 )
+    nb_cores 7650 ( 90 x 85 ), nb_points 1950 ( 50 x 39 )
+    nb_cores 7725 ( 103 x 75 ), nb_points 1936 ( 44 x 44 )
+    nb_cores 7770 ( 111 x 70 ), nb_points 1927 ( 41 x 47 )
+    nb_cores 7802 ( 94 x 83 ), nb_points 1920 ( 48 x 40 )
+    nb_cores 7820 ( 92 x 85 ), nb_points 1911 ( 49 x 39 )
+    nb_cores 7905 ( 85 x 93 ), nb_points 1908 ( 53 x 36 )
+    nb_cores 7920 ( 120 x 66 ), nb_points 1900 ( 38 x 50 )
+    nb_cores 7920 ( 90 x 88 ), nb_points 1900 ( 50 x 38 )
+    nb_cores 7931 ( 103 x 77 ), nb_points 1892 ( 44 x 43 )
+    nb_cores 7968 ( 96 x 83 ), nb_points 1880 ( 47 x 40 )
+    nb_cores 7990 ( 94 x 85 ), nb_points 1872 ( 48 x 39 )
+    nb_cores 8040 ( 120 x 67 ), nb_points 1862 ( 38 x 49 )
+    nb_cores 8100 ( 108 x 75 ), nb_points 1848 ( 42 x 44 )
+    nb_cores 8160 ( 96 x 85 ), nb_points 1833 ( 47 x 39 )
+    nb_cores 8253 ( 131 x 63 ), nb_points 1820 ( 35 x 52 )
+    nb_cores 8280 ( 92 x 90 ), nb_points 1813 ( 49 x 37 )
+    nb_cores 8316 ( 108 x 77 ), nb_points 1806 ( 42 x 43 )
+    nb_cores 8325 ( 111 x 75 ), nb_points 1804 ( 41 x 44 )
+    nb_cores 8370 ( 90 x 93 ), nb_points 1800 ( 50 x 36 )
+    nb_cores 8400 ( 120 x 70 ), nb_points 1786 ( 38 x 47 )
+    nb_cores 8460 ( 94 x 90 ), nb_points 1776 ( 48 x 37 )
+    nb_cores 8505 ( 135 x 63 ), nb_points 1768 ( 34 x 52 )
+    nb_cores 8532 ( 108 x 79 ), nb_points 1764 ( 42 x 42 )
+    nb_cores 8547 ( 111 x 77 ), nb_points 1763 ( 41 x 43 )
+    nb_cores 8549 ( 103 x 83 ), nb_points 1760 ( 44 x 40 )
+    nb_cores 8585 ( 101 x 85 ), nb_points 1755 ( 45 x 39 )
+    nb_cores 8640 ( 96 x 90 ), nb_points 1739 ( 47 x 37 )
+    nb_cores 8712 ( 72 x 121 ), nb_points 1736 ( 62 x 28 )
+    nb_cores 8742 ( 94 x 93 ), nb_points 1728 ( 48 x 36 )
+    nb_cores 8748 ( 108 x 81 ), nb_points 1722 ( 42 x 41 )
+    nb_cores 8755 ( 103 x 85 ), nb_points 1716 ( 44 x 39 )
+    nb_cores 8777 ( 131 x 67 ), nb_points 1715 ( 35 x 49 )
+    nb_cores 8880 ( 120 x 74 ), nb_points 1710 ( 38 x 45 )
+    nb_cores 8910 ( 90 x 99 ), nb_points 1700 ( 50 x 34 )
+    nb_cores 8910 ( 135 x 66 ), nb_points 1700 ( 34 x 50 )
+    nb_cores 8925 ( 85 x 105 ), nb_points 1696 ( 53 x 32 )
+    nb_cores 8928 ( 96 x 93 ), nb_points 1692 ( 47 x 36 )
+    nb_cores 8964 ( 108 x 83 ), nb_points 1680 ( 42 x 40 )
+    nb_cores 9000 ( 120 x 75 ), nb_points 1672 ( 38 x 44 )
+    nb_cores 9045 ( 135 x 67 ), nb_points 1666 ( 34 x 49 )
+    nb_cores 9072 ( 144 x 63 ), nb_points 1664 ( 32 x 52 )
+    nb_cores 9170 ( 131 x 70 ), nb_points 1645 ( 35 x 47 )
+    nb_cores 9180 ( 108 x 85 ), nb_points 1638 ( 42 x 39 )
+    nb_cores 9240 ( 120 x 77 ), nb_points 1634 ( 38 x 43 )
+    nb_cores 9270 ( 103 x 90 ), nb_points 1628 ( 44 x 37 )
+    nb_cores 9360 ( 80 x 117 ), nb_points 1624 ( 56 x 29 )
+    nb_cores 9380 ( 140 x 67 ), nb_points 1617 ( 33 x 49 )
+    nb_cores 9387 ( 149 x 63 ), nb_points 1612 ( 31 x 52 )
+    nb_cores 9432 ( 131 x 72 ), nb_points 1610 ( 35 x 46 )
+    nb_cores 9435 ( 111 x 85 ), nb_points 1599 ( 41 x 39 )
+    nb_cores 9450 ( 135 x 70 ), nb_points 1598 ( 34 x 47 )
+    nb_cores 9480 ( 120 x 79 ), nb_points 1596 ( 38 x 42 )
+    nb_cores 9540 ( 106 x 90 ), nb_points 1591 ( 43 x 37 )
+    nb_cores 9579 ( 103 x 93 ), nb_points 1584 ( 44 x 36 )
+    nb_cores 9648 ( 144 x 67 ), nb_points 1568 ( 32 x 49 )
+    nb_cores 9690 ( 114 x 85 ), nb_points 1560 ( 40 x 39 )
+    nb_cores 9720 ( 108 x 90 ), nb_points 1554 ( 42 x 37 )
+    nb_cores 9792 ( 96 x 102 ), nb_points 1551 ( 47 x 33 )
+    nb_cores 9810 ( 90 x 109 ), nb_points 1550 ( 50 x 31 )
+    nb_cores 9825 ( 131 x 75 ), nb_points 1540 ( 35 x 44 )
+    nb_cores 9870 ( 94 x 105 ), nb_points 1536 ( 48 x 32 )
+    nb_cores 9945 ( 117 x 85 ), nb_points 1521 ( 39 x 39 )
+    nb_cores 9960 ( 120 x 83 ), nb_points 1520 ( 38 x 40 )
+    nb_cores 9983 ( 149 x 67 ), nb_points 1519 ( 31 x 49 )
+    nb_cores 9990 ( 111 x 90 ), nb_points 1517 ( 41 x 37 )
+    nb_cores 10044 ( 108 x 93 ), nb_points 1512 ( 42 x 36 )
+    nb_cores 10080 ( 96 x 105 ), nb_points 1504 ( 47 x 32 )
+    nb_cores 10080 ( 144 x 70 ), nb_points 1504 ( 32 x 47 )
+    nb_cores 10125 ( 135 x 75 ), nb_points 1496 ( 34 x 44 )
+    nb_cores 10200 ( 120 x 85 ), nb_points 1482 ( 38 x 39 )
+    nb_cores 10260 ( 114 x 90 ), nb_points 1480 ( 40 x 37 )
+    nb_cores 10323 ( 111 x 93 ), nb_points 1476 ( 41 x 36 )
+    nb_cores 10349 ( 131 x 79 ), nb_points 1470 ( 35 x 42 )
+    nb_cores 10395 ( 135 x 77 ), nb_points 1462 ( 34 x 43 )
+    nb_cores 10430 ( 149 x 70 ), nb_points 1457 ( 31 x 47 )
+    nb_cores 10500 ( 140 x 75 ), nb_points 1452 ( 33 x 44 )
+    nb_cores 10530 ( 117 x 90 ), nb_points 1443 ( 39 x 37 )
+    nb_cores 10602 ( 114 x 93 ), nb_points 1440 ( 40 x 36 )
+    nb_cores 10611 ( 131 x 81 ), nb_points 1435 ( 35 x 41 )
+    nb_cores 10665 ( 135 x 79 ), nb_points 1428 ( 34 x 42 )
+    nb_cores 10720 ( 160 x 67 ), nb_points 1421 ( 29 x 49 )
+    nb_cores 10780 ( 140 x 77 ), nb_points 1419 ( 33 x 43 )
+    nb_cores 10800 ( 120 x 90 ), nb_points 1406 ( 38 x 37 )
+    nb_cores 10873 ( 131 x 83 ), nb_points 1400 ( 35 x 40 )
+    nb_cores 10935 ( 135 x 81 ), nb_points 1394 ( 34 x 41 )
+    nb_cores 10998 ( 94 x 117 ), nb_points 1392 ( 48 x 29 )
+    nb_cores 11016 ( 108 x 102 ), nb_points 1386 ( 42 x 33 )
+    nb_cores 11088 ( 144 x 77 ), nb_points 1376 ( 32 x 43 )
+    nb_cores 11132 ( 92 x 121 ), nb_points 1372 ( 49 x 28 )
+    nb_cores 11135 ( 131 x 85 ), nb_points 1365 ( 35 x 39 )
+    nb_cores 11175 ( 149 x 75 ), nb_points 1364 ( 31 x 44 )
+    nb_cores 11200 ( 160 x 70 ), nb_points 1363 ( 29 x 47 )
+    nb_cores 11205 ( 135 x 83 ), nb_points 1360 ( 34 x 40 )
+    nb_cores 11322 ( 111 x 102 ), nb_points 1353 ( 41 x 33 )
+    nb_cores 11340 ( 108 x 105 ), nb_points 1344 ( 42 x 32 )
+    nb_cores 11473 ( 149 x 77 ), nb_points 1333 ( 31 x 43 )
+    nb_cores 11475 ( 135 x 85 ), nb_points 1326 ( 34 x 39 )
+    nb_cores 11591 ( 173 x 67 ), nb_points 1323 ( 27 x 49 )
+    nb_cores 11616 ( 96 x 121 ), nb_points 1316 ( 47 x 28 )
+    nb_cores 11655 ( 111 x 105 ), nb_points 1312 ( 41 x 32 )
+    nb_cores 11771 ( 149 x 79 ), nb_points 1302 ( 31 x 42 )
+    nb_cores 11790 ( 131 x 90 ), nb_points 1295 ( 35 x 37 )
+    nb_cores 11880 ( 120 x 99 ), nb_points 1292 ( 38 x 34 )
+    nb_cores 11880 ( 135 x 88 ), nb_points 1292 ( 34 x 38 )
+    nb_cores 11900 ( 140 x 85 ), nb_points 1287 ( 33 x 39 )
+    nb_cores 11952 ( 144 x 83 ), nb_points 1280 ( 32 x 40 )
+    nb_cores 12000 ( 160 x 75 ), nb_points 1276 ( 29 x 44 )
+    nb_cores 12060 ( 180 x 67 ), nb_points 1274 ( 26 x 49 )
+    nb_cores 12069 ( 149 x 81 ), nb_points 1271 ( 31 x 41 )
+    nb_cores 12096 ( 96 x 126 ), nb_points 1269 ( 47 x 27 )
+    nb_cores 12150 ( 135 x 90 ), nb_points 1258 ( 34 x 37 )
+    nb_cores 12240 ( 144 x 85 ), nb_points 1248 ( 32 x 39 )
+    nb_cores 12320 ( 160 x 77 ), nb_points 1247 ( 29 x 43 )
+    nb_cores 12367 ( 149 x 83 ), nb_points 1240 ( 31 x 40 )
+    nb_cores 12463 ( 103 x 121 ), nb_points 1232 ( 44 x 28 )
+    nb_cores 12543 ( 111 x 113 ), nb_points 1230 ( 41 x 30 )
+    nb_cores 12555 ( 135 x 93 ), nb_points 1224 ( 34 x 36 )
+    nb_cores 12600 ( 120 x 105 ), nb_points 1216 ( 38 x 32 )
+    nb_cores 12665 ( 149 x 85 ), nb_points 1209 ( 31 x 39 )
+    nb_cores 12826 ( 106 x 121 ), nb_points 1204 ( 43 x 28 )
+    nb_cores 12865 ( 155 x 83 ), nb_points 1200 ( 30 x 40 )
+    nb_cores 12960 ( 144 x 90 ), nb_points 1184 ( 32 x 37 )
+    nb_cores 13068 ( 108 x 121 ), nb_points 1176 ( 42 x 28 )
+    nb_cores 13152 ( 96 x 137 ), nb_points 1175 ( 47 x 25 )
+    nb_cores 13175 ( 155 x 85 ), nb_points 1170 ( 30 x 39 )
+    nb_cores 13280 ( 160 x 83 ), nb_points 1160 ( 29 x 40 )
+    nb_cores 13362 ( 131 x 102 ), nb_points 1155 ( 35 x 33 )
+    nb_cores 13392 ( 144 x 93 ), nb_points 1152 ( 32 x 36 )
+    nb_cores 13410 ( 149 x 90 ), nb_points 1147 ( 31 x 37 )
+    nb_cores 13500 ( 180 x 75 ), nb_points 1144 ( 26 x 44 )
+    nb_cores 13560 ( 120 x 113 ), nb_points 1140 ( 38 x 30 )
+    nb_cores 13600 ( 160 x 85 ), nb_points 1131 ( 29 x 39 )
+    nb_cores 13728 ( 96 x 143 ), nb_points 1128 ( 47 x 24 )
+    nb_cores 13755 ( 131 x 105 ), nb_points 1120 ( 35 x 32 )
+    nb_cores 13857 ( 149 x 93 ), nb_points 1116 ( 31 x 36 )
+    nb_cores 13950 ( 155 x 90 ), nb_points 1110 ( 30 x 37 )
+    nb_cores 13986 ( 111 x 126 ), nb_points 1107 ( 41 x 27 )
+    nb_cores 14040 ( 120 x 117 ), nb_points 1102 ( 38 x 29 )
+    nb_cores 14100 ( 188 x 75 ), nb_points 1100 ( 25 x 44 )
+    nb_cores 14157 ( 117 x 121 ), nb_points 1092 ( 39 x 28 )
+    nb_cores 14175 ( 135 x 105 ), nb_points 1088 ( 34 x 32 )
+    nb_cores 14279 ( 131 x 109 ), nb_points 1085 ( 35 x 31 )
+    nb_cores 14359 ( 173 x 83 ), nb_points 1080 ( 27 x 40 )
+    nb_cores 14400 ( 160 x 90 ), nb_points 1073 ( 29 x 37 )
+    nb_cores 14520 ( 120 x 121 ), nb_points 1064 ( 38 x 28 )
+    nb_cores 14688 ( 144 x 102 ), nb_points 1056 ( 32 x 33 )
+    nb_cores 14705 ( 173 x 85 ), nb_points 1053 ( 27 x 39 )
+    nb_cores 14796 ( 108 x 137 ), nb_points 1050 ( 42 x 25 )
+    nb_cores 14880 ( 160 x 93 ), nb_points 1044 ( 29 x 36 )
+    nb_cores 14940 ( 180 x 83 ), nb_points 1040 ( 26 x 40 )
+    nb_cores 15004 ( 124 x 121 ), nb_points 1036 ( 37 x 28 )
+    nb_cores 15120 ( 144 x 105 ), nb_points 1024 ( 32 x 32 )
+    nb_cores 15198 ( 149 x 102 ), nb_points 1023 ( 31 x 33 )
+    nb_cores 15255 ( 135 x 113 ), nb_points 1020 ( 34 x 30 )
+    nb_cores 15300 ( 180 x 85 ), nb_points 1014 ( 26 x 39 )
+    nb_cores 15444 ( 108 x 143 ), nb_points 1008 ( 42 x 24 )
+    nb_cores 15570 ( 173 x 90 ), nb_points 999 ( 27 x 37 )
+    nb_cores 15645 ( 149 x 105 ), nb_points 992 ( 31 x 32 )
+    nb_cores 15795 ( 135 x 117 ), nb_points 986 ( 34 x 29 )
+    nb_cores 15851 ( 131 x 121 ), nb_points 980 ( 35 x 28 )
+    nb_cores 15980 ( 188 x 85 ), nb_points 975 ( 25 x 39 )
+    nb_cores 16089 ( 173 x 93 ), nb_points 972 ( 27 x 36 )
+    nb_cores 16200 ( 180 x 90 ), nb_points 962 ( 26 x 37 )
+    nb_cores 16241 ( 149 x 109 ), nb_points 961 ( 31 x 31 )
+    nb_cores 16272 ( 144 x 113 ), nb_points 960 ( 32 x 30 )
+    nb_cores 16320 ( 160 x 102 ), nb_points 957 ( 29 x 33 )
+    nb_cores 16335 ( 135 x 121 ), nb_points 952 ( 34 x 28 )
+    nb_cores 16440 ( 120 x 137 ), nb_points 950 ( 38 x 25 )
+    nb_cores 16506 ( 131 x 126 ), nb_points 945 ( 35 x 27 )
+    nb_cores 16650 ( 111 x 150 ), nb_points 943 ( 41 x 23 )
+    nb_cores 16731 ( 117 x 143 ), nb_points 936 ( 39 x 24 )
+    nb_cores 16800 ( 160 x 105 ), nb_points 928 ( 29 x 32 )
+    nb_cores 16920 ( 188 x 90 ), nb_points 925 ( 25 x 37 )
+    nb_cores 16940 ( 140 x 121 ), nb_points 924 ( 33 x 28 )
+    nb_cores 17010 ( 135 x 126 ), nb_points 918 ( 34 x 27 )
+    nb_cores 17160 ( 120 x 143 ), nb_points 912 ( 38 x 24 )
+    nb_cores 17280 ( 180 x 96 ), nb_points 910 ( 26 x 35 )
+    nb_cores 17424 ( 144 x 121 ), nb_points 896 ( 32 x 28 )
+    nb_cores 17640 ( 140 x 126 ), nb_points 891 ( 33 x 27 )
+    nb_cores 17730 ( 197 x 90 ), nb_points 888 ( 24 x 37 )
+    nb_cores 17820 ( 135 x 132 ), nb_points 884 ( 34 x 26 )
+    nb_cores 17820 ( 180 x 99 ), nb_points 884 ( 26 x 34 )
+    nb_cores 17928 ( 216 x 83 ), nb_points 880 ( 22 x 40 )
+    nb_cores 17947 ( 131 x 137 ), nb_points 875 ( 35 x 25 )
+    nb_cores 18000 ( 120 x 150 ), nb_points 874 ( 38 x 23 )
+    nb_cores 18029 ( 149 x 121 ), nb_points 868 ( 31 x 28 )
+    nb_cores 18144 ( 144 x 126 ), nb_points 864 ( 32 x 27 )
+    nb_cores 18360 ( 180 x 102 ), nb_points 858 ( 26 x 33 )
+    nb_cores 18360 ( 216 x 85 ), nb_points 858 ( 22 x 39 )
+    nb_cores 18495 ( 135 x 137 ), nb_points 850 ( 34 x 25 )
+    nb_cores 18720 ( 160 x 117 ), nb_points 841 ( 29 x 29 )
+    nb_cores 18733 ( 131 x 143 ), nb_points 840 ( 35 x 24 )
+    nb_cores 18774 ( 149 x 126 ), nb_points 837 ( 31 x 27 )
+    nb_cores 18900 ( 180 x 105 ), nb_points 832 ( 26 x 32 )
+    nb_cores 19158 ( 206 x 93 ), nb_points 828 ( 23 x 36 )
+    nb_cores 19176 ( 188 x 102 ), nb_points 825 ( 25 x 33 )
+    nb_cores 19305 ( 135 x 143 ), nb_points 816 ( 34 x 24 )
+    nb_cores 19360 ( 160 x 121 ), nb_points 812 ( 29 x 28 )
+    nb_cores 19530 ( 155 x 126 ), nb_points 810 ( 30 x 27 )
+    nb_cores 19620 ( 180 x 109 ), nb_points 806 ( 26 x 31 )
+    nb_cores 19650 ( 131 x 150 ), nb_points 805 ( 35 x 23 )
+    nb_cores 19728 ( 144 x 137 ), nb_points 800 ( 32 x 25 )
+    nb_cores 19920 ( 120 x 166 ), nb_points 798 ( 38 x 21 )
+    nb_cores 20020 ( 140 x 143 ), nb_points 792 ( 33 x 24 )
+    nb_cores 20160 ( 160 x 126 ), nb_points 783 ( 29 x 27 )
+    nb_cores 20250 ( 135 x 150 ), nb_points 782 ( 34 x 23 )
+    nb_cores 20340 ( 180 x 113 ), nb_points 780 ( 26 x 30 )
+    nb_cores 20413 ( 149 x 137 ), nb_points 775 ( 31 x 25 )
+    nb_cores 20592 ( 144 x 143 ), nb_points 768 ( 32 x 24 )
+    nb_cores 20933 ( 173 x 121 ), nb_points 756 ( 27 x 28 )
+    nb_cores 21060 ( 180 x 117 ), nb_points 754 ( 26 x 29 )
+    nb_cores 21235 ( 155 x 137 ), nb_points 750 ( 30 x 25 )
+    nb_cores 21307 ( 149 x 143 ), nb_points 744 ( 31 x 24 )
+    nb_cores 21600 ( 144 x 150 ), nb_points 736 ( 32 x 23 )
+    nb_cores 21746 ( 131 x 166 ), nb_points 735 ( 35 x 21 )
+    nb_cores 21780 ( 180 x 121 ), nb_points 728 ( 26 x 28 )
+    nb_cores 21920 ( 160 x 137 ), nb_points 725 ( 29 x 25 )
+    nb_cores 22165 ( 155 x 143 ), nb_points 720 ( 30 x 24 )
+    nb_cores 22350 ( 149 x 150 ), nb_points 713 ( 31 x 23 )
+    nb_cores 22680 ( 180 x 126 ), nb_points 702 ( 26 x 27 )
+    nb_cores 22748 ( 188 x 121 ), nb_points 700 ( 25 x 28 )
+    nb_cores 22880 ( 160 x 143 ), nb_points 696 ( 29 x 24 )
+    nb_cores 23240 ( 140 x 166 ), nb_points 693 ( 33 x 21 )
+    nb_cores 23250 ( 155 x 150 ), nb_points 690 ( 30 x 23 )
+    nb_cores 23542 ( 149 x 158 ), nb_points 682 ( 31 x 22 )
+    nb_cores 23625 ( 135 x 175 ), nb_points 680 ( 34 x 20 )
+    nb_cores 23688 ( 188 x 126 ), nb_points 675 ( 25 x 27 )
+    nb_cores 23837 ( 197 x 121 ), nb_points 672 ( 24 x 28 )
+    nb_cores 24000 ( 160 x 150 ), nb_points 667 ( 29 x 23 )
+    nb_cores 24235 ( 131 x 185 ), nb_points 665 ( 35 x 19 )
+    nb_cores 24408 ( 216 x 113 ), nb_points 660 ( 22 x 30 )
+    nb_cores 24660 ( 180 x 137 ), nb_points 650 ( 26 x 25 )
+    nb_cores 24739 ( 173 x 143 ), nb_points 648 ( 27 x 24 )
+    nb_cores 24926 ( 206 x 121 ), nb_points 644 ( 23 x 28 )
+    nb_cores 25200 ( 240 x 105 ), nb_points 640 ( 20 x 32 )
+    nb_cores 25200 ( 144 x 175 ), nb_points 640 ( 32 x 20 )
+    nb_cores 25272 ( 216 x 117 ), nb_points 638 ( 22 x 29 )
+    nb_cores 25730 ( 155 x 166 ), nb_points 630 ( 30 x 21 )
+    nb_cores 25740 ( 180 x 143 ), nb_points 624 ( 26 x 24 )
+    nb_cores 25950 ( 173 x 150 ), nb_points 621 ( 27 x 23 )
+    nb_cores 26075 ( 149 x 175 ), nb_points 620 ( 31 x 20 )
+    nb_cores 26136 ( 216 x 121 ), nb_points 616 ( 22 x 28 )
+    nb_cores 26560 ( 160 x 166 ), nb_points 609 ( 29 x 21 )
+    nb_cores 26640 ( 144 x 185 ), nb_points 608 ( 32 x 19 )
+    nb_cores 26884 ( 188 x 143 ), nb_points 600 ( 25 x 24 )
+    nb_cores 27000 ( 180 x 150 ), nb_points 598 ( 26 x 23 )
+    nb_cores 27216 ( 216 x 126 ), nb_points 594 ( 22 x 27 )
+    nb_cores 27565 ( 149 x 185 ), nb_points 589 ( 31 x 19 )
+    nb_cores 27588 ( 228 x 121 ), nb_points 588 ( 21 x 28 )
+    nb_cores 28000 ( 160 x 175 ), nb_points 580 ( 29 x 20 )
+    nb_cores 28171 ( 197 x 143 ), nb_points 576 ( 24 x 24 )
+    nb_cores 28200 ( 188 x 150 ), nb_points 575 ( 25 x 23 )
+    nb_cores 28440 ( 180 x 158 ), nb_points 572 ( 26 x 22 )
+    nb_cores 28675 ( 155 x 185 ), nb_points 570 ( 30 x 19 )
+    nb_cores 28718 ( 173 x 166 ), nb_points 567 ( 27 x 21 )
+    nb_cores 29040 ( 240 x 121 ), nb_points 560 ( 20 x 28 )
+    nb_cores 29353 ( 149 x 197 ), nb_points 558 ( 31 x 18 )
+    nb_cores 29458 ( 206 x 143 ), nb_points 552 ( 23 x 24 )
+    nb_cores 29592 ( 216 x 137 ), nb_points 550 ( 22 x 25 )
+    nb_cores 29880 ( 180 x 166 ), nb_points 546 ( 26 x 21 )
+    nb_cores 30240 ( 240 x 126 ), nb_points 540 ( 20 x 27 )
+    nb_cores 30855 ( 255 x 121 ), nb_points 532 ( 19 x 28 )
+    nb_cores 30888 ( 216 x 143 ), nb_points 528 ( 22 x 24 )
+    nb_cores 31208 ( 188 x 166 ), nb_points 525 ( 25 x 21 )
+    nb_cores 31500 ( 180 x 175 ), nb_points 520 ( 26 x 20 )
+    nb_cores 32005 ( 173 x 185 ), nb_points 513 ( 27 x 19 )
+    nb_cores 32400 ( 216 x 150 ), nb_points 506 ( 22 x 23 )
+    nb_cores 32604 ( 228 x 143 ), nb_points 504 ( 21 x 24 )
+    nb_cores 32880 ( 240 x 137 ), nb_points 500 ( 20 x 25 )
+    nb_cores 33300 ( 180 x 185 ), nb_points 494 ( 26 x 19 )
+    nb_cores 33600 ( 160 x 210 ), nb_points 493 ( 29 x 17 )
+    nb_cores 34020 ( 270 x 126 ), nb_points 486 ( 18 x 27 )
+    nb_cores 34128 ( 216 x 158 ), nb_points 484 ( 22 x 22 )
+    nb_cores 34196 ( 206 x 166 ), nb_points 483 ( 23 x 21 )
+    nb_cores 34320 ( 240 x 143 ), nb_points 480 ( 20 x 24 )
+    nb_cores 34780 ( 188 x 185 ), nb_points 475 ( 25 x 19 )
+    nb_cores 35460 ( 180 x 197 ), nb_points 468 ( 26 x 18 )
+    nb_cores 35856 ( 216 x 166 ), nb_points 462 ( 22 x 21 )
+    nb_cores 36000 ( 240 x 150 ), nb_points 460 ( 20 x 23 )
+    nb_cores 36288 ( 288 x 126 ), nb_points 459 ( 17 x 27 )
+    nb_cores 36445 ( 197 x 185 ), nb_points 456 ( 24 x 19 )
+    nb_cores 36990 ( 270 x 137 ), nb_points 450 ( 18 x 25 )
+    nb_cores 37389 ( 309 x 121 ), nb_points 448 ( 16 x 28 )
+    nb_cores 37800 ( 216 x 175 ), nb_points 440 ( 22 x 20 )
+    nb_cores 38110 ( 206 x 185 ), nb_points 437 ( 23 x 19 )
+    nb_cores 38610 ( 270 x 143 ), nb_points 432 ( 18 x 24 )
+    nb_cores 39456 ( 288 x 137 ), nb_points 425 ( 17 x 25 )
+    nb_cores 39840 ( 240 x 166 ), nb_points 420 ( 20 x 21 )
+    nb_cores 39960 ( 216 x 185 ), nb_points 418 ( 22 x 19 )
+    nb_cores 40500 ( 270 x 150 ), nb_points 414 ( 18 x 23 )
+    nb_cores 41184 ( 288 x 143 ), nb_points 408 ( 17 x 24 )
+    nb_cores 41866 ( 173 x 242 ), nb_points 405 ( 27 x 15 )
+    nb_cores 42000 ( 240 x 175 ), nb_points 400 ( 20 x 20 )
+    nb_cores 42180 ( 228 x 185 ), nb_points 399 ( 21 x 19 )
+    nb_cores 42552 ( 216 x 197 ), nb_points 396 ( 22 x 18 )
+    nb_cores 43200 ( 288 x 150 ), nb_points 391 ( 17 x 23 )
+    nb_cores 43560 ( 180 x 242 ), nb_points 390 ( 26 x 15 )
+    nb_cores 44187 ( 309 x 143 ), nb_points 384 ( 16 x 24 )
+    nb_cores 44400 ( 240 x 185 ), nb_points 380 ( 20 x 19 )
+    nb_cores 44820 ( 270 x 166 ), nb_points 378 ( 18 x 21 )
+    nb_cores 45360 ( 216 x 210 ), nb_points 374 ( 22 x 17 )
+    nb_cores 46350 ( 309 x 150 ), nb_points 368 ( 16 x 23 )
+    nb_cores 46350 ( 206 x 225 ), nb_points 368 ( 23 x 16 )
+    nb_cores 47175 ( 255 x 185 ), nb_points 361 ( 19 x 19 )
+    nb_cores 47250 ( 270 x 175 ), nb_points 360 ( 18 x 20 )
+    nb_cores 47808 ( 288 x 166 ), nb_points 357 ( 17 x 21 )
+    nb_cores 48600 ( 216 x 225 ), nb_points 352 ( 22 x 16 )
+    nb_cores 49320 ( 360 x 137 ), nb_points 350 ( 14 x 25 )
+    nb_cores 49852 ( 206 x 242 ), nb_points 345 ( 23 x 15 )
+    nb_cores 49950 ( 270 x 185 ), nb_points 342 ( 18 x 19 )
+    nb_cores 50400 ( 288 x 175 ), nb_points 340 ( 17 x 20 )
+    nb_cores 50400 ( 240 x 210 ), nb_points 340 ( 20 x 17 )
+    nb_cores 51294 ( 309 x 166 ), nb_points 336 ( 16 x 21 )
+    nb_cores 52272 ( 216 x 242 ), nb_points 330 ( 22 x 15 )
+    nb_cores 53190 ( 270 x 197 ), nb_points 324 ( 18 x 18 )
+    nb_cores 53280 ( 288 x 185 ), nb_points 323 ( 17 x 19 )
+    nb_cores 54000 ( 240 x 225 ), nb_points 320 ( 20 x 16 )
+    nb_cores 55176 ( 228 x 242 ), nb_points 315 ( 21 x 15 )
+    nb_cores 56199 ( 393 x 143 ), nb_points 312 ( 13 x 24 )
+    nb_cores 56700 ( 270 x 210 ), nb_points 306 ( 18 x 17 )
+    nb_cores 57165 ( 309 x 185 ), nb_points 304 ( 16 x 19 )
+    nb_cores 58080 ( 240 x 242 ), nb_points 300 ( 20 x 15 )
+    nb_cores 58916 ( 206 x 286 ), nb_points 299 ( 23 x 13 )
+    nb_cores 59760 ( 360 x 166 ), nb_points 294 ( 14 x 21 )
+    nb_cores 60480 ( 288 x 210 ), nb_points 289 ( 17 x 17 )
+    nb_cores 60750 ( 270 x 225 ), nb_points 288 ( 18 x 16 )
+    nb_cores 61605 ( 333 x 185 ), nb_points 285 ( 15 x 19 )
+    nb_cores 63000 ( 360 x 175 ), nb_points 280 ( 14 x 20 )
+    nb_cores 64800 ( 288 x 225 ), nb_points 272 ( 17 x 16 )
+    nb_cores 65340 ( 270 x 242 ), nb_points 270 ( 18 x 15 )
+    nb_cores 66600 ( 360 x 185 ), nb_points 266 ( 14 x 19 )
+    nb_cores 68040 ( 216 x 315 ), nb_points 264 ( 22 x 12 )
+    nb_cores 68640 ( 240 x 286 ), nb_points 260 ( 20 x 13 )
+    nb_cores 69525 ( 309 x 225 ), nb_points 256 ( 16 x 16 )
+    nb_cores 69696 ( 288 x 242 ), nb_points 255 ( 17 x 15 )
+    nb_cores 70920 ( 360 x 197 ), nb_points 252 ( 14 x 18 )
+    nb_cores 72705 ( 393 x 185 ), nb_points 247 ( 13 x 19 )
+    nb_cores 74778 ( 309 x 242 ), nb_points 240 ( 16 x 15 )
+    nb_cores 75600 ( 360 x 210 ), nb_points 238 ( 14 x 17 )
+    nb_cores 77220 ( 270 x 286 ), nb_points 234 ( 18 x 13 )
+    nb_cores 79680 ( 480 x 166 ), nb_points 231 ( 11 x 21 )
+    nb_cores 79920 ( 432 x 185 ), nb_points 228 ( 12 x 19 )
+    nb_cores 80586 ( 333 x 242 ), nb_points 225 ( 15 x 15 )
+    nb_cores 81000 ( 360 x 225 ), nb_points 224 ( 14 x 16 )
+    nb_cores 82368 ( 288 x 286 ), nb_points 221 ( 17 x 13 )
+    nb_cores 84000 ( 480 x 175 ), nb_points 220 ( 11 x 20 )
+    nb_cores 84000 ( 240 x 350 ), nb_points 220 ( 20 x 11 )
+    nb_cores 85050 ( 270 x 315 ), nb_points 216 ( 18 x 12 )
+    nb_cores 87120 ( 360 x 242 ), nb_points 210 ( 14 x 15 )
+    nb_cores 88374 ( 309 x 286 ), nb_points 208 ( 16 x 13 )
+    nb_cores 90720 ( 288 x 315 ), nb_points 204 ( 17 x 12 )
+    nb_cores 90720 ( 432 x 210 ), nb_points 204 ( 12 x 17 )
+    nb_cores 94500 ( 270 x 350 ), nb_points 198 ( 18 x 11 )
+    nb_cores 94680 ( 360 x 263 ), nb_points 196 ( 14 x 14 )
+    nb_cores 95106 ( 393 x 242 ), nb_points 195 ( 13 x 15 )
+    nb_cores 97200 ( 432 x 225 ), nb_points 192 ( 12 x 16 )
+    nb_cores 99900 ( 540 x 185 ), nb_points 190 ( 10 x 19 )
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca025_like
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca025_like	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca025_like	(revision 14097)
@@ -0,0 +1,220 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OPA  BENCH Configuration namelist : overwrite some defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =   'BENCH' !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    1000   !  last time step 
+   nn_stock    =      -1   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =      -1   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   BENCH configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   nn_isize   =   1442     ! number of point in i-direction of global(local) domain if >0 (<0)  
+   nn_jsize   =   1207  !!  1050    ! number of point in j-direction of global(local) domain if >0 (<0)  
+   nn_ksize   =   75       ! total number of point in k-direction
+   nn_perio   =   4        ! periodicity
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+   ln_nnogather=  .true.   !  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)
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   nn_print    =    0      !  level of print (0 no extra print)
+   ln_timing   = .false.   !  timing by routine write out in timing.output file
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =    900.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.05    !  asselin time filter parameter
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+
+!
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF =F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF =F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   nn_chldta   =      0      !  RGB : Chl data (=1) or cst value (=0)
+/
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin  = .true.   !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.   !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx     = 1       !  geothermal heat flux: = 1 constant flux
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.   !  Bottom Boundary Layer parameterisation flag
+/
+
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .true.         !  = Use TEOS-10
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.  !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_blp   = .true.   !    laplacian operator
+   ln_traldf_iso   = .true.   !  iso-neutral (standard operator)
+   !
+   ln_traldf_msc   = .true.   !  Method of Stabilizing Correction      (both operators)
+   nn_aht_ijk_t    = 20       !  space/time variation of eddy coefficient:
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .false.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .false.   ! use eddy induced velocity parameterization
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+   ln_vvl_dbg    = .false.          !  debug prints    (T/F)
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true. !  vector form (T) or flux form (F)
+      nn_dynkeg     = 1       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true. !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0  e3f = mi(mj(e3t))/4 
+      !                       ! =1  e3f = mi(mj(e3t))/mi(mj( tmask))
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts   = .true.   ! split-explicit free surface
+      ln_bt_auto    = .false.    ! Number of sub-step defined from:
+         nn_baro      =  30         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_blp =  .true.    !    laplacian operator
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 30           !  space/time variation of eddy coef
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+   ln_zdfddm   = .true.       ! double diffusive mixing
+   ln_zdfiwm   = .true.       ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca12_like
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca12_like	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca12_like	(revision 14097)
@@ -0,0 +1,216 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OPA  BENCH Configuration namelist : overwrite some defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =   'BENCH' !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    1000   !  last time step 
+   nn_stock    =      -1   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =      -1   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   BENCH configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   nn_isize   =   4322     ! number of point in i-direction of global(local) domain if >0 (<0)  
+   nn_jsize   =   3147     ! number of point in j-direction of global(local) domain if >0 (<0)  
+   nn_ksize   =   75       ! total number of point in k-direction
+   nn_perio   =   4        ! periodicity
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+   ln_nnogather=  .true.   !  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)
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   nn_print    =    0      !  level of print (0 no extra print)
+   ln_timing   = .false.   !  timing by routine write out in timing.output file
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =    300.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.05    !  asselin time filter parameter
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+
+!
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF =F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF =F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   nn_chldta   =      0      !  RGB : Chl data (=1) or cst value (=0)
+/
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin  = .true.   !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.   !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx     = 1       !  geothermal heat flux: = 1 constant flux
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.   !  Bottom Boundary Layer parameterisation flag
+/
+
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .true.         !  = Use TEOS-10
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.  !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_blp   = .true.   !    laplacian operator
+   ln_traldf_iso   = .true.   !  iso-neutral (standard operator)
+   !
+   ln_traldf_msc   = .true.   !  Method of Stabilizing Correction      (both operators)
+   nn_aht_ijk_t    = 20       !  space/time variation of eddy coefficient:
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .false.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .false.   ! use eddy induced velocity parameterization
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+   ln_vvl_dbg    = .false.          !  debug prints    (T/F)
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_ubs = .true. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true. !  energy & enstrophy scheme
+      nn_een_e3f = 0          ! =0  e3f = mi(mj(e3t))/4 
+      !                       ! =1  e3f = mi(mj(e3t))/mi(mj( tmask))
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts   = .true.   ! split-explicit free surface
+      ln_bt_auto    = .false.    ! Number of sub-step defined from:
+         nn_baro      =  30         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+   ln_zdfddm   = .true.       ! double diffusive mixing
+   ln_zdfiwm   = .true.       ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca1_like
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca1_like	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_cfg_orca1_like	(revision 14097)
@@ -0,0 +1,219 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OPA  BENCH Configuration namelist : overwrite some defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =   'BENCH' !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    1000   !  last time step 
+   nn_stock    =      -1   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =      -1   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   BENCH configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   nn_isize   =   362      ! number of point in i-direction of global(local) domain if >0 (<0)  
+   nn_jsize   =   332      ! number of point in j-direction of global(local) domain if >0 (<0)  
+   nn_ksize   =   75       ! total number of point in k-direction
+   nn_perio   =   6        ! periodicity
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+   ln_nnogather=  .true.   !  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)
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   nn_print    =    0      !  level of print (0 no extra print)
+   ln_timing   = .false.   !  timing by routine write out in timing.output file
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =   3600.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.05    !  asselin time filter parameter
+/
+
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_traqsr   = .true.    !  Light penetration in the ocean            (T => fill namtra_qsr)
+/
+
+!
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF =F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF =F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   !                       !  type of penetration                        (default: NO selection)
+   ln_qsr_rgb  = .true.      !  RGB light penetration (Red-Green-Blue)
+   nn_chldta   =      0      !  RGB : Chl data (=1) or cst value (=0)
+/
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_non_lin  = .true.   !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .true.   !  Apply a geothermal heating at the ocean bottom
+      nn_geoflx     = 1       !  geothermal heat flux: = 1 constant flux
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbl   = .true.   !  Bottom Boundary Layer parameterisation flag
+/
+
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10   = .true.         !  = Use TEOS-10
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct = .true.  !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   = .true.   !    laplacian operator
+   ln_traldf_iso   = .true.   !  iso-neutral (standard operator)
+   !
+   nn_aht_ijk_t    = 20       !  space/time variation of eddy coefficient:
+/
+!-----------------------------------------------------------------------
+&namtra_mle    !   mixed layer eddy parametrisation (Fox-Kemper)       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_mle      = .true.   ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!-----------------------------------------------------------------------
+&namtra_eiv    !   eddy induced velocity param.                         (default: OFF)
+!-----------------------------------------------------------------------
+   ln_ldfeiv   = .true.   ! use eddy induced velocity parameterization
+   !
+   nn_aei_ijk_t    = 20          !  space/time variation of eddy coefficient:
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  z-star vertical coordinate
+   ln_vvl_dbg    = .false.          !  debug prints    (T/F)
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true. !  vector form (T) or flux form (F)
+      nn_dynkeg     = 1       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_een = .true. !  energy & enstrophy scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts   = .true.   ! split-explicit free surface
+      ln_bt_auto    = .false.    ! Number of sub-step defined from:
+         nn_baro      =  30         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_lap =  .true.    !    laplacian operator
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 30           !  space/time variation of eddy coef
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+   ln_zdfddm   = .true.       ! double diffusive mixing
+   ln_zdfiwm   = .true.       ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,85 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface forcing                (namforcing)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namforcing     !   Ice surface forcing
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   rn_thres_sst     =   0.5           !  max delta temp. above Tfreeze with initial ice = (sst - tfreeze)
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_cfg	(revision 14097)
@@ -0,0 +1,140 @@
+!-----------------------------------------------------------------------
+&nampismod     !  Model used 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisext     !   air-sea exchange
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisatm     !  Atmospheric prrssure 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisbio     !   biological parameters
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zice     !   parameters for nutrient limitations for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zice     !   parameters for nutrient limitations PISCES QUOTA    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zquota   !   parameters for nutrient limitations PISCES quota    - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisopt     !   parameters for optics
+!-----------------------------------------------------------------------
+   ln_varpar   =  .false.   ! boolean for PAR variable
+/ 
+!-----------------------------------------------------------------------
+&namp4zprod    !   parameters for phytoplankton growth for PISCES std  - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zprod    !   parameters for phytoplankton growth for PISCES quota- ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmort    !   parameters for phytoplankton sinks for PISCES std   - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmort    !   parameters for phytoplankton sinks for PISCES quota - ln_p5z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zmes     !   parameters for mesozooplankton for PISCES std       - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zmes     !   parameters for mesozooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp4zzoo     !   parameters for microzooplankton for PISCES std      - ln_p4z
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namp5zzoo     !   parameters for microzooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisfer     !   parameters for iron chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------  
+&nampisrem     !   parameters for remineralization
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampispoc     !   parameters for organic particles
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampiscal     !   parameters for Calcite chemistry
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampissbc     !   parameters for inputs deposition
+!-----------------------------------------------------------------------
+   ln_dust     =  .false.   ! boolean for dust input from the atmosphere
+   ln_solub    =  .false.   ! boolean for variable solubility of atm. Iron
+   ln_river    =  .false.   ! boolean for river input of nutrients
+   ln_ndepo    =  .false.   ! boolean for atmospheric deposition of N
+   ln_ironsed  =  .false.   ! boolean for Fe input from sediments
+   ln_ironice  =  .false.   ! boolean for Fe input from sea ice
+   ln_hydrofe  =  .false.  ! boolean for from hydrothermal vents
+/
+!-----------------------------------------------------------------------
+&nampislig     !   Namelist parameters for ligands, nampislig
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisice     !   Prescribed sea ice tracers
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampisdmp     !   Damping 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nampismass    !   Mass conservation
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobphy     !   biological parameters for phytoplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobnut     !   biological parameters for nutrients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobzoo     !   biological parameters for zooplankton
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdet     !   biological parameters for detritus
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobdom     !   biological parameters for DOM
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobsed     !   parameters from aphotic layers to sediment
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobrat     !   general coefficients
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namlobopt     !   optical parameters
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_pisces_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_pisces_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_cfg	(revision 14097)
@@ -0,0 +1,110 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/TOP1 :  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_top_ref
+!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!-----------------------------------------------------------------------
+&namtrc_run      !   run information
+!-----------------------------------------------------------------------
+   ln_top_euler  = .true.
+/
+!-----------------------------------------------------------------------
+&namtrc          !   tracers definition
+!-----------------------------------------------------------------------
+   jp_bgc        =  24
+!
+   ln_pisces     =  .true.
+   ln_my_trc     =  .false.
+   ln_age        =  .false.
+   ln_cfc11      =  .false.
+   ln_cfc12      =  .false.
+   ln_c14        =  .false.
+!
+   ln_trcdta     =  .false.  !  Initialisation from data input file (T) or not (F)
+!                 !           !                                          !             !
+!                 !    name   !           title of the field             !   units     ! initial data from file or not !
+!                 !           !                                          !             !
+   sn_tracer(1)   = 'DIC     ' , 'Dissolved inorganic Concentration      ',  'mol-C/L' ,  .true.
+   sn_tracer(2)   = 'Alkalini' , 'Total Alkalinity Concentration         ',  'eq/L '   ,  .true.
+   sn_tracer(3)   = 'O2      ' , 'Dissolved Oxygen Concentration         ',  'mol-C/L' ,  .true.
+   sn_tracer(4)   = 'CaCO3   ' , 'Calcite Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(5)   = 'PO4     ' , 'Phosphate Concentration                ',  'mol-C/L' ,  .true.
+   sn_tracer(6)   = 'POC     ' , 'Small organic carbon Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(7)   = 'Si      ' , 'Silicate Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(8)   = 'PHY     ' , 'Nanophytoplankton Concentration        ',  'mol-C/L' ,  .false.
+   sn_tracer(9)   = 'ZOO     ' , 'Microzooplankton Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(10)  = 'DOC     ' , 'Dissolved organic Concentration        ',  'mol-C/L' ,  .true.
+   sn_tracer(11)  = 'PHY2    ' , 'Diatoms Concentration                  ',  'mol-C/L' ,  .false.
+   sn_tracer(12)  = 'ZOO2    ' , 'Mesozooplankton Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(13)  = 'DSi     ' , 'Diatoms Silicate Concentration         ',  'mol-C/L' ,  .false.
+   sn_tracer(14)  = 'Fer     ' , 'Dissolved Iron Concentration           ',  'mol-C/L' ,  .true.
+   sn_tracer(15)  = 'BFe     ' , 'Big iron particles Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(16)  = 'GOC     ' , 'Big organic carbon Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(17)  = 'SFe     ' , 'Small iron particles Concentration     ',  'mol-C/L' ,  .false.
+   sn_tracer(18)  = 'DFe     ' , 'Diatoms iron  Concentration            ',  'mol-C/L' ,  .false.
+   sn_tracer(19)  = 'GSi     ' , 'Sinking biogenic Silicate Concentration',  'mol-C/L' ,  .false.
+   sn_tracer(20)  = 'NFe     ' , 'Nano iron Concentration                ',  'mol-C/L' ,  .false.
+   sn_tracer(21)  = 'NCHL    ' , 'Nano chlorophyl Concentration          ',  'mol-C/L' ,  .false.
+   sn_tracer(22)  = 'DCHL    ' , 'Diatoms chlorophyl Concentration       ',  'mol-C/L' ,  .false.
+   sn_tracer(23)  = 'NO3     ' , 'Nitrates Concentration                 ',  'mol-C/L' ,  .true.
+   sn_tracer(24)  = 'NH4     ' , 'Ammonium Concentration                 ',  'mol-C/L' ,  .false.
+/
+!-----------------------------------------------------------------------
+&namage          !   AGE 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dta      !    Initialisation from data input file
+!-----------------------------------------------------------------------
+!          !  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_trcdta(1)  = 'data_DIC_nomask'        ,        -12.       ,  'DIC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(2)  = 'data_Alkalini_nomask'   ,        -12.       ,  'Alkalini',    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(3)  = 'data_O2_nomask'         ,        -1.        ,  'O2'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(5)  = 'data_PO4_nomask'        ,        -1.        ,  'PO4'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(7)  = 'data_Si_nomask'         ,        -1.        ,  'Si'      ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(10) = 'data_DOC_nomask'        ,        -12.       ,  'DOC'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(14) = 'data_Fer_nomask'        ,        -12.       ,  'Fer'     ,    .false.   , .true. , 'yearly'  , ''       , ''   , ''
+   sn_trcdta(23) = 'data_NO3_nomask'        ,        -1.        ,  'NO3'     ,    .true.    , .true. , 'yearly'  , ''       , ''   , ''
+   rn_trfac(1)   =   1.0e-06  !  multiplicative factor
+   rn_trfac(2)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(3)   =  44.6e-06  !  -      -      -     -
+   rn_trfac(5)   = 122.0e-06  !  -      -      -     -
+   rn_trfac(7)   =   1.0e-06  !  -      -      -     -
+   rn_trfac(10)  =   1.0      !  -      -      -     -
+   rn_trfac(14)  =   1.0      !  -      -      -     -
+   rn_trfac(23)  =   7.6e-06  !  -      -      -     -
+/
+!-----------------------------------------------------------------------
+&namtrc_adv      !   advection scheme for passive tracer                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcadv_mus =  .true.  !  MUSCL scheme
+      ln_mus_ups =  .false.         !  use upstream scheme near river mouths
+/
+!-----------------------------------------------------------------------
+&namtrc_ldf      !   lateral diffusion scheme for passive tracer        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_trcldf_tra   = .true.      !  use active tracer setting
+/
+!-----------------------------------------------------------------------
+&namtrc_rad      !  treatment of negative concentrations 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_dmp      !   passive tracer newtonian damping   
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_ice      !    Representation of sea ice growth & melt effects
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtrc_trd      !   diagnostics on tracer trends                       ('key_trdtrc')
+!----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bc       !   data for boundary conditions
+!-----------------------------------------------------------------------
+/
+!----------------------------------------------------------------------
+&namtrc_bdy      !   Setup of tracer boundary conditions
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/namelist_top_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_top_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/sh_bench
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/sh_bench	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/sh_bench	(revision 14097)
@@ -0,0 +1,59 @@
+#!/bin/bash
+set -u
+#set -xv
+
+resolution=${1:?"you must provide the resolution: 1 025 or 12"}
+mincore=${2:-1} # minimum number of core to be tested
+maxcore=${3:-0} # maximum number of core to be tested
+
+machine=$( hostname | sed -e "s/[0-9]*//g" )
+case $machine in 
+    "jean-zay")     ncore_node=40 ;;
+    "beaufixlogin") ncore_node=40 ;;
+    "curie")        ncore_node=16 ;;
+    "irene")        ncore_node=48 ;;
+    *) echo "you must add your machine \"$machine\" with its number of cores per node" ; exit 1 ;;
+esac
+
+[ $mincore -eq 1 ] && targetnb=$ncore_node || targetnb=$mincore
+#
+# build the list of experiences:
+# must be a multiple of ncore_node and as close as possible of the targeted number of core
+#
+n1=0
+list=""
+
+# Prepare gnuplot data file
+dateref=$( date "+%Y%m%d-%Hh%Mm%Ss" )
+echo "# nb_proc    jpi    jpj" > gnuplot_tbc_${resolution}_${dateref}.dat
+nbl=$( cat best_jpni_jpnj_eorca${resolution} | wc -l )
+for ll in $( seq 1 $nbl )
+do
+    line=$( sed -n ${ll}p best_jpni_jpnj_eorca${resolution} )    # for each line
+    nn=$( echo $line | sed -e "s/.*nb_cores \([0-9]*\).*/\1/" )  # get the number of core
+    [ $maxcore -gt 1 -a $nn -gt $maxcore ] && break              # if below $maxcore (if specified)
+        if [ $(( $nn % $ncore_node )) -eq 0 ]                    # if it is a multiple of $ncore_node
+        then
+            if [ $nn -lt $targetnb ]
+            then
+                n1=$nn       # store the number of core
+                line1=$line  # store the line
+            else
+                [ $(( $targetnb - $n1 )) -le $(( $nn -$targetnb )) ] && line=$line1   # keep the previous line
+                echo $line
+                nb=$( echo $line | sed -e "s/[^(]*( \([0-9]*\) x \([0-9]*\) .*/\1*\2/" ) # get jpni*jpnj
+                list="${list} ${nb}"
+                targetnb=$(( $targetnb * 2 ))
+                subsize=$( echo $line | awk {'printf "%d   %d", $11, $13'})
+                corenb=$( echo $line | awk {'printf "%d", $2'})
+                echo "$corenb  $subsize" >> gnuplot_tbc_${resolution}.dat
+            fi
+        fi
+done
+echo $list
+
+for cores in $list
+do
+    ./submit_bench $cores $ncore_node ${resolution} ${dateref}
+done
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/submit_bench
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/submit_bench	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/EXPREF/submit_bench	(revision 14097)
@@ -0,0 +1,276 @@
+#!/bin/bash
+#  
+#  BENCH launching scripts for beaufix, Meteo-France
+#                          and curie, TGCC
+#  To be modified for other machines
+#
+set -u
+#set -vx
+#
+cores=$1
+ncore_node=$2
+resolution=$3
+dateref=$4
+machine=$( hostname | sed -e "s/[0-9]*//g" )
+#
+# number of processes for each executable
+nproc_exe1=$( echo $cores | bc )
+nproc=$nproc_exe1
+nnode=$(( ( $nproc + $ncore_node - 1 )  / $ncore_node ))
+
+nproc5=$( printf "%05d\n" ${nproc_exe1} )
+
+case ${resolution} in
+    "1")
+	if [ $nproc_exe1 -lt 50 ]
+	then
+	    timejob=3600
+	elif [ $nproc_exe1 -lt 100 ]
+	then
+	    timejob=1800
+	elif [ $nproc_exe1 -lt 200 ]
+	then
+	    timejob=900
+	else
+	    timejob=600
+	fi
+	;;
+    "025")
+	if [ $nproc_exe1 -lt 50 ]
+	then
+	    timejob=15000
+	elif [ $nproc_exe1 -lt 100 ]
+	then
+	    timejob=7000
+	elif [ $nproc_exe1 -lt 200 ]
+	then
+	    timejob=3600
+	elif [ $nproc_exe1 -lt 400 ]
+	then
+	    timejob=2000
+	elif [ $nproc_exe1 -lt 800 ]
+	then
+	    timejob=1000
+	else
+	    timejob=600
+	fi
+	;;
+    "12")
+	if [ $nproc_exe1 -lt 200 ]
+	then
+	    timejob=30000
+	elif [ $nproc_exe1 -lt 400 ]
+	then
+	    timejob=15000
+	elif [ $nproc_exe1 -lt 800 ]
+	then
+	    timejob=20000
+	elif [ $nproc_exe1 -lt 1600 ]
+	then
+	    timejob=15000
+	elif [ $nproc_exe1 -lt 3200 ]
+	then
+	    timejob=7500
+	elif [ $nproc_exe1 -lt 10000 ]
+	then
+	    timejob=5000
+	elif [ $nproc_exe1 -lt 20000 ]
+	then
+	    timejob=2500
+	else
+	    timejob=1200
+	fi
+	;;
+esac
+
+
+######################################################################
+### beaufixlogin
+######################################################################
+
+if [ "$machine" == "beaufixlogin" ]
+then
+    
+cat > Log/run_bench << EOF
+#!/bin/bash
+#SBATCH --time=00:1:00
+#SBATCH -p  normal64         # partition/queue
+#SBATCH --job-name=bench      # job name
+#SBATCH -N $nnode            # number of nodes
+#SBATCH -n $nproc            # number of procs
+#SBATCH -o /scratch/work/cglo315/ESIWACE/dev_r9759_HPC09_ESIWACE/tests/LBENCH_RN/EXP00/Log/job.out%j
+#SBATCH -e /scratch/work/cglo315/ESIWACE/dev_r9759_HPC09_ESIWACE/tests/LBENCH_RN/EXP00/Log/job.out%j
+#SBATCH --exclusive
+
+module unload intelmpi intel grib_api
+module load intel/16.1.150 intelmpi/5.1.2.150
+
+itac=0
+xpmpi=0
+
+if [ \$xpmpi == 1 ]; then
+  module load bullxde
+  module load xPMPI/1.1_intelmpi
+fi
+
+[ \$itac == 1 ] && module load itac/2017.2.028
+
+set -vx
+
+cd \${TMPDIR}
+cp /scratch/work/cglo315/ESIWACE/dev_r9759_HPC09_ESIWACE/tests/LBENCH_RN/EXP00/* .
+
+# Best decompositions BENCH-1
+jpni=${cores/\**/}
+jpnj=${cores/?*\*/}
+
+sed -e "s/jpni *=.*/jpni = \${jpni}/" -e "s/jpnj *=.*/jpnj = \${jpnj}/" namelist_cfg_orca${resolution}_like > namelist_cfg
+
+export OMP_NUM_THREADS=1
+ulimit -s unlimited
+#
+if [ \$itac == 1 ]; then
+  source /opt/softs/intel/2017/update_1/itac_latest/bin/itacvars.sh
+  time mpirun -ordered-output -prepend-rank -trace -np $nproc_exe1 ./nemo > jobout 2>joberr
+else
+  time mpirun -ordered-output -prepend-rank -np $nproc_exe1 ./nemo > jobout_${resolution}_${nproc5}
+fi
+/opt/softs/bin/ja
+
+if [ \$xpmpi == 1 ]; then
+  module unload xPMPI/1.1_intelmpi
+  module unload bullxde
+fi
+#
+EOF
+
+
+### 4. Execute the model
+
+    echo 'Submitting the job to queue using sbatch'
+    sbatch Log/run_bench
+    squeue -u cglo315
+
+echo 'is executed or submitted to queue.'
+
+
+fi
+
+######################################################################
+### curie or irene
+######################################################################
+
+if [[ ( "$machine" == "curie" ) || ( "$machine" == "irene" ) ]]
+then
+
+    [ "$machine" == "curie" ] && queuename=standard || queuename=skylake
+    
+    EXPjob=../EXP_${resolution}_${nproc5}_${dateref}
+    mkdir -p ${EXPjob}
+    cd ${EXPjob}
+    jobname=jobbench
+    cat > $jobname << EOF
+#!/bin/bash
+#MSUB -r bench${nproc5}
+#MSUB -n ${nproc_exe1}
+#MSUB -T $timejob
+#MSUB -e bench_${resolution}_${nproc5}_%I.eo
+#MSUB -o bench_${resolution}_${nproc5}_%I.eo
+#MSUB -j oe
+#MSUB -x
+#MSUB -q ${queuename}
+#MSUB -A gen6895
+#==========================================
+set -u
+#
+
+cd \${BRIDGE_MSUB_PWD}
+
+for ff in \${BRIDGE_MSUB_PWD}/../EXPREF/namelist_*cfg \${BRIDGE_MSUB_PWD}/../EXPREF/namelist_*ref \${BRIDGE_MSUB_PWD}/../BLD/bin/nemo.exe
+do
+    cp \$ff .
+done
+
+jpni=${cores/\**/}
+jpnj=${cores/?*\*/}
+
+sed -e "s/jpni *=.*/jpni = \${jpni}/" \
+    -e "s/jpnj *=.*/jpnj = \${jpnj}/"\
+    -e "s/ln_timing *= *.false./ln_timing   =  .true./" \
+     \${BRIDGE_MSUB_PWD}/../EXPREF/namelist_cfg_orca${resolution}_like > namelist_cfg
+
+time ccc_mprun -n \${BRIDGE_MSUB_NPROC} ./nemo.exe > jobout_${resolution}_${nproc5}_${dateref} 2>&1
+
+EOF
+
+    ccc_msub $jobname
+
+fi
+
+######################################################################
+### Jean-Zay
+######################################################################
+
+if [ "$machine" == "jean-zay" ]
+then
+    hh=$( printf "%02d\n" $(( ${timejob} / 3600 )) )
+    mm=$( printf "%02d\n" $(( ( ${timejob} % 3600 ) / 60 )) )
+    ss=$( printf "%02d\n" $(( ( ${timejob} % 3600 ) % 60 )) )
+
+    EXPjob=../EXP_${resolution}_${nproc5}_${dateref}
+    mkdir -p ${EXPjob}
+    cd ${EXPjob}
+    jobname=jobbench
+    cat > $jobname << EOF
+#!/bin/bash
+#SBATCH --job-name=Seq        # nom du job
+#SBATCH --partition=cpu_gct3   # demande d'allocation sur la partition CPU
+#SBATCH --nodes=${nnode}             # nombre de noeuds
+#SBATCH --ntasks-per-node=${ncore_node}  # nombre de taches MPI par noeud
+#SBATCH --ntasks-per-core=1        # 1 processus MPI par coeur physique (pas d'hyperthreading)
+#SBATCH --time=${hh}:${mm}:${ss}       # temps d execution maximum demande (HH:MM:SS)
+#SBATCH --output=bench_${resolution}_${nproc5}_%j.eo        # nom du fichier de sortie
+#SBATCH --error=bench_${resolution}_${nproc5}_%j.eo         # nom du fichier d'erreur (ici en commun avec la sortie)
+#==========================================
+set -u
+#set -xv
+#
+#cd \${SLURM_SUBMIT_DIR}
+cd \${JOBSCRATCH}
+pwd
+
+for ff in \${SLURM_SUBMIT_DIR}/../EXPREF/namelist_*cfg \${SLURM_SUBMIT_DIR}/../EXPREF/namelist_*ref \${SLURM_SUBMIT_DIR}/../BLD/bin/nemo.exe
+do
+    cp \$ff .
+done
+
+jpni=${cores/\**/}
+jpnj=${cores/?*\*/}
+
+sed -e "s/jpni *=.*/jpni = \${jpni}/" \
+    -e "s/jpnj *=.*/jpnj = \${jpnj}/" \
+    -e "s/ln_timing *= *.false./ln_timing   =  .true./" \
+    \${SLURM_SUBMIT_DIR}/../EXPREF/namelist_cfg_orca${resolution}_like > namelist_cfg
+
+ls -l
+
+echo 
+echo 
+echo " =========== start the model ==========="
+echo 
+echo 
+
+time srun --mpi=pmi2 --cpu-bind=cores -K1 -n ${nproc} ./nemo.exe > jobout_${resolution}_${nproc5}_${dateref} 2>&1
+
+ls -l
+
+if [ "\$( pwd )" != "\${SLURM_SUBMIT_DIR}" ]
+then 
+    rsync -av namelist_cfg time.step ocean.output jobout_${resolution}_${nproc5}_${dateref} communication_report.txt layout.dat timing.output output.namelist* \${SLURM_SUBMIT_DIR}
+fi
+
+EOF
+
+    sbatch $jobname
+
+fi
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,118 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  BENCH configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for BENCH configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0, NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   square box mesh mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                BENCH configuration : beta-plance with uniform grid spacing (zres)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in grid points) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zres, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : BENCH configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          Beta-plane with regular grid-spacing'
+      IF(lwp) WRITE(numout,*) '          given by rn_dx and rn_dy' 
+      !
+      !                          
+      ! Position coordinates (in grid points)
+      !                          ==========         
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            
+            zti = REAL( ji - 1 + nimpp - 1, wp )          ;  ztj = REAL( jj - 1 + njmpp - 1, wp )
+            zui = REAL( ji - 1 + nimpp - 1, wp ) + 0.5_wp ;  zvj = REAL( jj - 1 + njmpp - 1, wp ) + 0.5_wp
+
+            plamt(ji,jj) = zti
+            plamu(ji,jj) = zui
+            plamv(ji,jj) = zti
+            plamf(ji,jj) = zui
+   
+            pphit(ji,jj) = ztj
+            pphiv(ji,jj) = zvj
+            pphiu(ji,jj) = ztj
+            pphif(ji,jj) = zvj
+            
+         END DO
+      END DO
+      !     
+      ! Horizontal scale factors (in meters)
+      !                              ======
+      zres = 1.e+5   !  100km
+      pe1t(:,:) = zres  ;   pe2t(:,:) = zres 
+      pe1u(:,:) = zres  ;   pe2u(:,:) = zres
+      pe1v(:,:) = zres  ;   pe2v(:,:) = zres
+      pe1f(:,:) = zres  ;   pe2f(:,:) = zres 
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_hgr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      zf0   = 2._wp * omega * SIN( rad * 45 )   ! constant coriolis factor corresponding to 45°N
+      pff_f(:,:) = zf0
+      pff_t(:,:) = zf0
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,92 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                      ===  BENCH configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO !
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce        
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lbclnk          ! lateral boundary conditions - mpp exchanges
+   !   
+   USE usrdef_nam
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here BENCH configuration 
+      !!
+      !! ** Method  :   Set a gaussian anomaly of pressure and associated
+      !!                geostrophic velocities
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      REAL(wp) ::   zfact
+      INTEGER  ::   ji, jj, jk
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : BENCH configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   '
+      !
+      ! define unique value on each point. z2d ranging from 0.05 to -0.05
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            z2d(ji,jj) = 0.1 * ( 0.5 - REAL( mig(ji) + mjg(jj) * jpiglo, wp ) / REAL( jpiglo * jpjglo, wp ) )
+         ENDDO
+      ENDDO
+      !
+      ! sea level:
+      pssh(:,:) = z2d(:,:)                                                ! +/- 0.05 m
+      !
+      DO jk = 1, jpk
+         zfact = REAL(jk-1,wp) / REAL(jpk-1,wp)   ! 0 to 1 to add a basic stratification
+         ! temperature choosen to lead to ~50% ice at the beginning if rn_thres_sst = 0.5
+         pts(:,:,jk,jp_tem) = 20._wp*z2d(:,:) - 1._wp - 0.5_wp * zfact    ! -1 to -1.5 +/-1.0 degG
+         ! salinity:  
+         pts(:,:,jk,jp_sal) = 30._wp + 1._wp * zfact + z2d(:,:)           ! 30 to 31 +/- 0.05 psu
+         ! velocities:
+         pu(:,:,jk) = z2d(:,:) * 0.1_wp                                   ! +/- 0.005  m/s
+         pv(:,:,jk) = z2d(:,:) * 0.01_wp                                  ! +/- 0.0005 m/s
+      ENDDO
+      !
+      CALL lbc_lnk('usrdef_istate', pssh, 'T',  1. )            ! apply boundary conditions
+      CALL lbc_lnk('usrdef_istate',  pts, 'T',  1. )            ! apply boundary conditions
+      CALL lbc_lnk('usrdef_istate',   pu, 'U', -1. )            ! apply boundary conditions
+      CALL lbc_lnk('usrdef_istate',   pv, 'V', -1. )            ! apply boundary conditions
+      
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,118 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  BENCH configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO !
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! to get ctl_nam
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+   
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here EW_CANAL configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      !
+      INTEGER ::   ios         ! Local integer
+      !                              !!* namusr_def namelist *!!
+      INTEGER ::   nn_isize    ! number of point in i-direction of global(local) domain if >0 (<0)  
+      INTEGER ::   nn_jsize    ! number of point in j-direction of global(local) domain if >0 (<0)  
+      INTEGER ::   nn_ksize    ! total number of point in k-direction
+      INTEGER ::   nn_perio    ! periodicity
+      !                              !!* nammpp namelist *!!
+      INTEGER          ::   jpni, jpnj
+      LOGICAL          ::   ln_nnogather, ln_listonly
+      !!
+      NAMELIST/namusr_def/ nn_isize, nn_jsize, nn_ksize, nn_perio
+      NAMELIST/nammpp/ jpni, jpnj, ln_nnogather, ln_listonly
+      !!----------------------------------------------------------------------     
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 903 )
+903   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )      
+      !
+      cd_cfg = 'BENCH'             ! name & resolution (not used)
+      kk_cfg = 0
+      !
+      IF( nn_isize < 0 .AND. nn_jsize < 0 ) THEN
+      !
+         REWIND( numnam_ref )              ! Namelist nammpp in reference namelist: mpi variables
+         READ  ( numnam_ref, nammpp, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 )   CALL ctl_nam ( ios , 'nammpp in reference namelist' )
+         !
+         REWIND( numnam_cfg )              ! Namelist nammpp in configuration namelist: mpi variables
+         READ  ( numnam_cfg, nammpp, IOSTAT = ios, ERR = 902 )
+902      IF( ios >  0 )   CALL ctl_nam ( ios , 'nammpp in configuration namelist' )
+
+         kpi = ( -nn_isize - 2*nn_hls ) * jpni + 2*nn_hls
+         kpj = ( -nn_jsize - 2*nn_hls ) * jpnj + 2*nn_hls
+      ELSE
+         kpi = nn_isize
+         kpj = nn_jsize
+      ENDIF
+      !
+      kpk = nn_ksize
+      kperio = nn_perio
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : BENCH test case'
+         IF( nn_isize > 0 ) THEN
+            WRITE(numout,*) '      global domain size-x            nn_isize = ',  nn_isize
+         ELSE
+            WRITE(numout,*) '                                          jpni = ', jpni
+            WRITE(numout,*) '       local domain size-x           -nn_isize = ', -nn_isize
+            WRITE(numout,*) '      global domain size-x                 kpi = ', kpi
+         ENDIF
+         IF( nn_jsize > 0 ) THEN
+            WRITE(numout,*) '      global domain size-y            nn_jsize = ', nn_jsize
+         ELSE
+            WRITE(numout,*) '                                          jpnj = ', jpnj
+            WRITE(numout,*) '       local domain size-y           -nn_jsize = ', -nn_jsize
+            WRITE(numout,*) '      global domain size-y                 kpj = ', kpj
+         ENDIF
+         WRITE(numout,*) '      global domain size-z            nn_ksize = ', nn_ksize
+         WRITE(numout,*) '      LBC of the global domain          kperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,167 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  BENCH configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in BENCH case
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce        
+   USE oce             ! ocean dynamics and tracers
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ocean fields
+   USE in_out_manager  ! I/O manager
+   USE phycst          ! physical constants
+   USE lib_mpp         ! MPP library
+   USE lbclnk          ! lateral boundary conditions - mpp exchanges
+
+#if defined key_si3
+   USE ice, ONLY       : at_i_b, a_i_b
+#endif
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by sbcice_lim.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by sbcice_lim.F90 for ice thermo
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for BENCH case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !     
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : BENCH case: surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !
+         utau_b(:,:) = 0._wp 
+         vtau_b(:,:) = 0._wp
+         emp_b (:,:) = 0._wp
+         sfx_b (:,:) = 0._wp
+         qns_b (:,:) = 0._wp
+         !
+      ENDIF
+      
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (momentum) condition over
+      !sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      INTEGER  ::   ji, jj
+      !!---------------------------------------------------------------------
+#if defined key_si3
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : BENCH case: constant stress forcing'
+      !
+      ! define unique value on each point. z2d ranging from 0.05 to -0.05
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            z2d(ji,jj) = 0.1 * ( 0.5 - REAL( nimpp + ji - 1 + ( njmpp + jj - 2 ) * jpiglo, wp ) / REAL( jpiglo * jpjglo, wp ) )
+         ENDDO
+      ENDDO
+      utau_ice(:,:) = 0.1_wp +  z2d(:,:)
+      vtau_ice(:,:) = 0.1_wp +  z2d(:,:)
+
+      CALL lbc_lnk_multi( 'usrdef_sbc', utau_ice, 'U', -1., vtau_ice, 'V', -1. )
+#endif
+      !
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (flux) condition over
+      !sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+      !!
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsnw   ! snw distribution after wind blowing
+      !!---------------------------------------------------------------------
+      !
+#if defined key_si3
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : BENCH case: NO flux forcing'
+      !
+      ! ocean variables (renaming)
+      emp_oce (:,:)   = 0._wp   ! uniform value for freshwater budget (E-P)
+      qsr_oce (:,:)   = 0._wp   ! uniform value for     solar radiation
+      qns_oce (:,:)   = 0._wp   ! uniform value for non-solar radiation
+
+      ! ice variables
+      alb_ice (:,:,:) = 0.7_wp  ! useless
+      qsr_ice (:,:,:) = 0._wp   ! uniform value for     solar radiation
+      qns_ice (:,:,:) = 0._wp   ! uniform value for non-solar radiation
+      sprecip (:,:)   = 0._wp   ! uniform value for snow precip
+      evap_ice(:,:,:) = 0._wp   ! uniform value for sublimation
+
+      ! ice fields deduced from above
+      zsnw(:,:) = 1._wp
+      emp_ice  (:,:)   = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw(:,:)
+      emp_oce  (:,:)   = emp_oce(:,:) - sprecip(:,:) * (1._wp - zsnw(:,:) )
+      qevap_ice(:,:,:) =   0._wp
+      qprec_ice(:,:)   =   rhos * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) !  in J/m3
+      qemp_oce (:,:)   = - emp_oce(:,:) * sst_m(:,:) * rcp
+      qemp_ice (:,:)   =   sprecip(:,:) * zsnw * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) ! solid precip (only)
+
+      ! total fluxes
+      emp_tot (:,:) = emp_ice  + emp_oce
+      qns_tot (:,:) = at_i_b(:,:) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 ) + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot (:,:) = at_i_b(:,:) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- shortwave radiation transmitted below the surface (W/m2)
+      qtr_ice_top(:,:,:) = 0._wp
+#endif
+
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,245 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                      ===  BENCH configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constants
+   USE depth_e3       ! depth <=> e3
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2016)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   inum   ! local logical unit
+      REAL(WP) ::   z_zco, z_zps, z_sco, z_cav
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : BENCH configuration (z-coordinate closed flat box ocean)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .TRUE.         ! BENCH case:  z-coordinate without ocean cavities
+      ld_zps    = .FALSE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      CALL zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      CALL zgr_msk_top_bot( k_top , k_bot )                 ! masked top and bottom ocean t-level indices
+      !
+      !                                                     ! z-coordinate (3D arrays) from the 1D z-coord.
+      CALL zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in  : 1D reference vertical coordinate
+         &          pdept   , pdepw   ,                     &   ! out : 3D t & w-points depth
+         &          pe3t    , pe3u    , pe3v   , pe3f   ,   &   !       vertical scale factors
+         &          pe3w    , pe3uw   , pe3vw             )     !           -      -      -
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z  ***
+      !!
+      !! ** Purpose :   set the 1D depth of model levels and the resulting 
+      !!              vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!           with at top and bottom :
+      !!                   e3w_1d( 1 ) = 2 * ( dept_1d( 1 ) - depw_1d( 1 ) )
+      !!                   e3t_1d(jpk) = 2 * ( dept_1d(jpk) - depw_1d(jpk) )
+      !!       The depth are then re-computed from the sum of e3. This ensures 
+      !!    that depths are identical when reading domain configuration file. 
+      !!    Indeed, only e3. are saved in this file, depth are compute by a call
+      !!    to the e3_to_depth subroutine.
+      !!
+      !!       Here the Madec & Imbard (1996) function is used.
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!
+      !! Reference : Marti, Madec & Delecluse, 1992, JGR, 97, No8, 12,763-12,766.
+      !!             Madec and Imbard, 1996, Clim. Dyn.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zd       ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zd = 5000./FLOAT(jpkm1)
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z   : Reference vertical z-coordinates '
+         WRITE(numout,*) '    ~~~~~~~'
+         WRITE(numout,*) '       BENCH case : uniform vertical grid :'
+         WRITE(numout,*) '                     with thickness = ', zd
+      ENDIF
+
+      !
+      ! 1D Reference z-coordinate    (using Madec & Imbard 1996 function)
+      ! -------------------------
+      !
+      pdepw_1d(1) = 0._wp
+      pdept_1d(1) = 0.5_wp * zd
+      ! 
+      DO jk = 2, jpk          ! depth at T and W-points
+         pdepw_1d(jk) = pdepw_1d(jk-1) + zd 
+         pdept_1d(jk) = pdept_1d(jk-1) + zd 
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d ) 
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d ) 
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z
+
+
+   SUBROUTINE zgr_msk_top_bot( k_top , k_bot )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_msk_top_bot  ***
+      !!
+      !! ** Purpose :   set the masked top and bottom ocean t-levels
+      !!
+      !! ** Method  :   BENCH case = closed flat box ocean without ocean cavities
+      !!                   k_top = 1     except along north, south, east and west boundaries
+      !!                   k_bot = jpk-1 except along north, south, east and west boundaries
+      !!
+      !! ** Action  : - k_top : first wet ocean level index
+      !!              - k_bot : last  wet ocean level index
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(out) ::   k_top , k_bot   ! first & last wet ocean level
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D local workspace
+      REAL(wp)                     ::   zmaxlam, zscl
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_bot : defines the top and bottom wet ocean levels.'
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '       BENCH case : closed flat box ocean without ocean cavities'
+      !
+      z2d(:,:) = REAL( jpkm1 , wp )          ! flat bottom
+      !
+      IF( jperio == 3 .OR. jperio ==4 ) THEN   ! add a small island in the upper corners to avoid model instabilities...
+         z2d(mi0(       1):mi1(     3),mj0(jpjglo-2):mj1(jpjglo)) = 0.
+         z2d(mi0(jpiglo-2):mi1(jpiglo),mj0(jpjglo-2):mj1(jpjglo)) = 0.
+      ENDIF
+      !
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )           ! set surrounding land to zero (here jperio=0 ==>> closed)
+      !
+      k_bot(:,:) = INT( z2d(:,:) )           ! =jpkm1 over the ocean point, =0 elsewhere
+      !
+      k_top(:,:) = MIN( 1 , k_bot(:,:) )     ! = 1    over the ocean point, =0 elsewhere
+      !
+   END SUBROUTINE zgr_msk_top_bot
+   
+
+   SUBROUTINE zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in : 1D reference vertical coordinate
+      &                pdept   , pdepw   ,                     &   ! out: 3D t & w-points depth
+      &                pe3t    , pe3u    , pe3v   , pe3f   ,   &   !      vertical scale factors
+      &                pe3w    , pe3uw   , pe3vw             )     !          -      -      -
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zgr_zco  ***
+      !!
+      !! ** Purpose :   define the reference z-coordinate system
+      !!
+      !! ** Method  :   set 3D coord. arrays to reference 1D array 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth       [m]
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pe3t_1d , pe3w_1d           ! 1D vertical scale factors [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth          [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors    [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         !    -       -      -
+      !
+      INTEGER  ::   jk
+      !!----------------------------------------------------------------------
+      !
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE zgr_zco
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/zdfiwm.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/zdfiwm.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/MY_SRC/zdfiwm.F90	(revision 14097)
@@ -0,0 +1,482 @@
+MODULE zdfiwm
+   !!========================================================================
+   !!                       ***  MODULE  zdfiwm  ***
+   !! Ocean physics: Internal gravity wave-driven vertical mixing
+   !!========================================================================
+   !! History :  1.0  !  2004-04  (L. Bessieres, G. Madec)  Original code
+   !!             -   !  2006-08  (A. Koch-Larrouy)  Indonesian strait
+   !!            3.3  !  2010-10  (C. Ethe, G. Madec)  reorganisation of initialisation phase
+   !!            3.6  !  2016-03  (C. de Lavergne)  New param: internal wave-driven mixing 
+   !!            4.0  !  2017-04  (G. Madec)  renamed module, remove the old param. and the CPP keys
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   zdf_iwm       : global     momentum & tracer Kz with wave induced Kz
+   !!   zdf_iwm_init  : global     momentum & tracer Kz with wave induced Kz
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE zdfddm         ! ocean vertical physics: double diffusive mixing
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE eosbn2         ! ocean equation of state
+   USE phycst         ! physical constants
+   !
+   USE prtctl         ! Print control
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O Manager
+   USE lib_mpp        ! MPP library
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   zdf_iwm        ! called in step module 
+   PUBLIC   zdf_iwm_init   ! called in nemogcm module 
+
+   !                      !!* Namelist  namzdf_iwm : internal wave-driven mixing *
+   INTEGER ::  nn_zpyc     ! pycnocline-intensified mixing energy proportional to N (=1) or N^2 (=2)
+   LOGICAL ::  ln_mevar    ! variable (=T) or constant (=F) mixing efficiency
+   LOGICAL ::  ln_tsdiff   ! account for differential T/S wave-driven mixing (=T) or not (=F)
+
+   REAL(wp)::  r1_6 = 1._wp / 6._wp
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ebot_iwm   ! power available from high-mode wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   epyc_iwm   ! power available from low-mode, pycnocline-intensified wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ecri_iwm   ! power available from low-mode, critical slope wave breaking (W/m2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hbot_iwm   ! WKB decay scale for high-mode energy dissipation (m)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hcri_iwm   ! decay scale for low-mode critical slope dissipation (m)
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL licence     (./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION zdf_iwm_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION zdf_iwm_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ebot_iwm(jpi,jpj),  epyc_iwm(jpi,jpj),  ecri_iwm(jpi,jpj) ,     &
+      &         hbot_iwm(jpi,jpj),  hcri_iwm(jpi,jpj)                     , STAT=zdf_iwm_alloc )
+      !
+      CALL mpp_sum ( 'zdfiwm', zdf_iwm_alloc )
+      IF( zdf_iwm_alloc /= 0 )   CALL ctl_stop( 'STOP', 'zdf_iwm_alloc: failed to allocate arrays' )
+   END FUNCTION zdf_iwm_alloc
+
+
+   SUBROUTINE zdf_iwm( kt, p_avm, p_avt, p_avs )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_iwm  ***
+      !!                   
+      !! ** Purpose :   add to the vertical mixing coefficients the effect of
+      !!              breaking internal waves.
+      !!
+      !! ** Method  : - internal wave-driven vertical mixing is given by:
+      !!                  Kz_wave = min(  100 cm2/s, f(  Reb = zemx_iwm /( Nu * N^2 )  )
+      !!              where zemx_iwm is the 3D space distribution of the wave-breaking 
+      !!              energy and Nu the molecular kinematic viscosity.
+      !!              The function f(Reb) is linear (constant mixing efficiency)
+      !!              if the namelist parameter ln_mevar = F and nonlinear if ln_mevar = T.
+      !!
+      !!              - Compute zemx_iwm, the 3D power density that allows to compute
+      !!              Reb and therefrom the wave-induced vertical diffusivity.
+      !!              This is divided into three components:
+      !!                 1. Bottom-intensified low-mode dissipation at critical slopes
+      !!                     zemx_iwm(z) = ( ecri_iwm / rau0 ) * EXP( -(H-z)/hcri_iwm )
+      !!                                   / ( 1. - EXP( - H/hcri_iwm ) ) * hcri_iwm
+      !!              where hcri_iwm is the characteristic length scale of the bottom 
+      !!              intensification, ecri_iwm a map of available power, and H the ocean depth.
+      !!                 2. Pycnocline-intensified low-mode dissipation
+      !!                     zemx_iwm(z) = ( epyc_iwm / rau0 ) * ( sqrt(rn2(z))^nn_zpyc )
+      !!                                   / SUM( sqrt(rn2(z))^nn_zpyc * e3w(z) )
+      !!              where epyc_iwm is a map of available power, and nn_zpyc
+      !!              is the chosen stratification-dependence of the internal wave
+      !!              energy dissipation.
+      !!                 3. WKB-height dependent high mode dissipation
+      !!                     zemx_iwm(z) = ( ebot_iwm / rau0 ) * rn2(z) * EXP(-z_wkb(z)/hbot_iwm)
+      !!                                   / SUM( rn2(z) * EXP(-z_wkb(z)/hbot_iwm) * e3w(z) )
+      !!              where hbot_iwm is the characteristic length scale of the WKB bottom 
+      !!              intensification, ebot_iwm is a map of available power, and z_wkb is the
+      !!              WKB-stretched height above bottom defined as
+      !!                    z_wkb(z) = H * SUM( sqrt(rn2(z'>=z)) * e3w(z'>=z) )
+      !!                                 / SUM( sqrt(rn2(z'))    * e3w(z')    )
+      !!
+      !!              - update the model vertical eddy viscosity and diffusivity: 
+      !!                     avt  = avt  +    av_wave
+      !!                     avm  = avm  +    av_wave
+      !!
+      !!              - if namelist parameter ln_tsdiff = T, account for differential mixing:
+      !!                     avs  = avt  +    av_wave * diffusivity_ratio(Reb)
+      !!
+      !! ** Action  : - avt, avs, avm, increased by tide internal wave-driven mixing    
+      !!
+      !! References :  de Lavergne et al. 2015, JPO; 2016, in prep.
+      !!----------------------------------------------------------------------
+      INTEGER                    , INTENT(in   ) ::   kt             ! ocean time step
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avm          ! momentum Kz (w-points)
+      REAL(wp), DIMENSION(:,:,:) , INTENT(inout) ::   p_avt, p_avs   ! tracer   Kz (w-points)
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zztmp        ! scalar workspace
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zfact       ! Used for vertical structure
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zhdep       ! Ocean depth
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zwkb        ! WKB-stretched height above bottom
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zweight     ! Weight for high mode vertical distribution
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   znu_t       ! Molecular kinematic viscosity (T grid)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   znu_w       ! Molecular kinematic viscosity (W grid)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zReb        ! Turbulence intensity parameter
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zemx_iwm    ! local energy density available for mixing (W/kg)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zav_ratio   ! S/T diffusivity ratio (only for ln_tsdiff=T)
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   zav_wave    ! Internal wave-induced diffusivity
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   z3d  ! 3D workspace used for iom_put 
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:)   ::   z2d  ! 2D     -      -    -     -
+      !!----------------------------------------------------------------------
+      !
+      !                       !* Set to zero the 1st and last vertical levels of appropriate variables
+      zemx_iwm (:,:,1) = 0._wp   ;   zemx_iwm (:,:,jpk) = 0._wp
+      zav_ratio(:,:,1) = 0._wp   ;   zav_ratio(:,:,jpk) = 0._wp
+      zav_wave (:,:,1) = 0._wp   ;   zav_wave (:,:,jpk) = 0._wp
+      !
+      !                       ! ----------------------------- !
+      !                       !  Internal wave-driven mixing  !  (compute zav_wave)
+      !                       ! ----------------------------- !
+      !                             
+      !                       !* Critical slope mixing: distribute energy over the time-varying ocean depth,
+      !                                                 using an exponential decay from the seafloor.
+      DO jj = 1, jpj                ! part independent of the level
+         DO ji = 1, jpi
+            zhdep(ji,jj) = gdepw_0(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean
+            zfact(ji,jj) = rau0 * (  1._wp - EXP( -zhdep(ji,jj) / hcri_iwm(ji,jj) )  )
+            IF( zfact(ji,jj) /= 0._wp )   zfact(ji,jj) = ecri_iwm(ji,jj) / zfact(ji,jj)
+         END DO
+      END DO
+!!gm gde3w ==>>>  check for ssh taken into account.... seem OK gde3w_n=gdept_n - sshn
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         zemx_iwm(:,:,jk) = zfact(:,:) * (  EXP( ( gde3w_n(:,:,jk  ) - zhdep(:,:) ) / hcri_iwm(:,:) )                      &
+            &                             - EXP( ( gde3w_n(:,:,jk-1) - zhdep(:,:) ) / hcri_iwm(:,:) )  ) * wmask(:,:,jk)   &
+            &                          / ( gde3w_n(:,:,jk) - gde3w_n(:,:,jk-1) )
+
+!!gm delta(gde3w_n) = e3t_n  !!  Please verify the grid-point position w versus t-point
+!!gm it seems to me that only 1/hcri_iwm  is used ==>  compute it one for all
+
+      END DO
+
+      !                        !* Pycnocline-intensified mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to sqrt(rn2)^nn_zpyc
+      !                                          ! (NB: N2 is masked, so no use of wmask here)
+      SELECT CASE ( nn_zpyc )
+      !
+      CASE ( 1 )               ! Dissipation scales as N (recommended)
+         !
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+         !
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+         !
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zfact(:,:) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         END DO
+         !
+      CASE ( 2 )               ! Dissipation scales as N^2
+         !
+         zfact(:,:) = 0._wp
+         DO jk = 2, jpkm1              ! part independent of the level
+            zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+         !
+         DO jj= 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = epyc_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+            END DO
+         END DO
+         !
+         DO jk = 2, jpkm1              ! complete with the level-dependent part
+            zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zfact(:,:) * MAX( 0._wp, rn2(:,:,jk) ) * wmask(:,:,jk)
+         END DO
+         !
+      END SELECT
+
+      !                        !* WKB-height dependent mixing: distribute energy over the time-varying 
+      !                        !* ocean depth as proportional to rn2 * exp(-z_wkb/rn_hbot)
+      !
+      zwkb (:,:,:) = 0._wp
+      zfact(:,:)   = 0._wp
+      DO jk = 2, jpkm1
+         zfact(:,:) = zfact(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  ) * wmask(:,:,jk)
+         zwkb(:,:,jk) = zfact(:,:)
+      END DO
+!!gm even better:
+!      DO jk = 2, jpkm1
+!         zwkb(:,:) = zwkb(:,:) + e3w_n(:,:,jk) * SQRT(  MAX( 0._wp, rn2(:,:,jk) )  )
+!      END DO
+!      zfact(:,:) = zwkb(:,:,jpkm1)
+!!gm or just use zwkb(k=jpk-1) instead of zfact...
+!!gm
+      !
+      DO jk = 2, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( zfact(ji,jj) /= 0 )   zwkb(ji,jj,jk) = zhdep(ji,jj) * ( zfact(ji,jj) - zwkb(ji,jj,jk) )   &
+                  &                                     * wmask(ji,jj,jk) / zfact(ji,jj)
+            END DO
+         END DO
+      END DO
+      zwkb(:,:,1) = zhdep(:,:) * wmask(:,:,1)
+      !
+      zweight(:,:,:) = 0._wp
+      DO jk = 2, jpkm1
+         zweight(:,:,jk) = MAX( 0._wp, rn2(:,:,jk) ) * hbot_iwm(:,:) * wmask(:,:,jk)                    &
+            &   * (  EXP( -zwkb(:,:,jk) / hbot_iwm(:,:) ) - EXP( -zwkb(:,:,jk-1) / hbot_iwm(:,:) )  )
+      END DO
+      !
+      zfact(:,:) = 0._wp
+      DO jk = 2, jpkm1              ! part independent of the level
+         zfact(:,:) = zfact(:,:) + zweight(:,:,jk)
+      END DO
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = ebot_iwm(ji,jj) / ( rau0 * zfact(ji,jj) )
+         END DO
+      END DO
+      !
+      DO jk = 2, jpkm1              ! complete with the level-dependent part
+         zemx_iwm(:,:,jk) = zemx_iwm(:,:,jk) + zweight(:,:,jk) * zfact(:,:) * wmask(:,:,jk)   &
+            &                                / ( gde3w_n(:,:,jk) - gde3w_n(:,:,jk-1) )
+!!gm  use of e3t_n just above?
+      END DO
+      !
+!!gm  this is to be replaced by just a constant value znu=1.e-6 m2/s
+      ! Calculate molecular kinematic viscosity
+      znu_t(:,:,:) = 1.e-4_wp * (  17.91_wp - 0.53810_wp * tsn(:,:,:,jp_tem) + 0.00694_wp * tsn(:,:,:,jp_tem) * tsn(:,:,:,jp_tem)  &
+         &                                  + 0.02305_wp * tsn(:,:,:,jp_sal)  ) * tmask(:,:,:) * r1_rau0
+      DO jk = 2, jpkm1
+         znu_w(:,:,jk) = 0.5_wp * ( znu_t(:,:,jk-1) + znu_t(:,:,jk) ) * wmask(:,:,jk)
+      END DO
+!!gm end
+      !
+      ! Calculate turbulence intensity parameter Reb
+      DO jk = 2, jpkm1
+         zReb(:,:,jk) = zemx_iwm(:,:,jk) / MAX( 1.e-20_wp, znu_w(:,:,jk) * rn2(:,:,jk) )
+      END DO
+      !
+      ! Define internal wave-induced diffusivity
+      DO jk = 2, jpkm1
+         zav_wave(:,:,jk) = znu_w(:,:,jk) * zReb(:,:,jk) * r1_6   ! This corresponds to a constant mixing efficiency of 1/6
+      END DO
+      !
+      IF( ln_mevar ) THEN              ! Variable mixing efficiency case : modify zav_wave in the
+         DO jk = 2, jpkm1              ! energetic (Reb > 480) and buoyancy-controlled (Reb <10.224 ) regimes
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( zReb(ji,jj,jk) > 480.00_wp ) THEN
+                     zav_wave(ji,jj,jk) = 3.6515_wp * znu_w(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ELSEIF( zReb(ji,jj,jk) < 10.224_wp ) THEN
+                     zav_wave(ji,jj,jk) = 0.052125_wp * znu_w(ji,jj,jk) * zReb(ji,jj,jk) * SQRT( zReb(ji,jj,jk) )
+                  ENDIF
+               END DO
+            END DO
+         END DO
+      ENDIF
+      !
+      DO jk = 2, jpkm1                 ! Bound diffusivity by molecular value and 100 cm2/s
+         zav_wave(:,:,jk) = MIN(  MAX( 1.4e-7_wp, zav_wave(:,:,jk) ), 1.e-2_wp  ) * wmask(:,:,jk)
+      END DO
+      !
+      IF( kt == nit000 ) THEN        !* Control print at first time-step: diagnose the energy consumed by zav_wave
+         zztmp = 0._wp
+!!gm used of glosum 3D....
+         DO jk = 2, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zztmp = zztmp + e3w_n(ji,jj,jk) * e1e2t(ji,jj)   &
+                     &          * MAX( 0._wp, rn2(ji,jj,jk) ) * zav_wave(ji,jj,jk) * wmask(ji,jj,jk) * tmask_i(ji,jj)
+               END DO
+            END DO
+         END DO
+         CALL mpp_sum( 'zdfiwm', zztmp )
+         zztmp = rau0 * zztmp ! Global integral of rauo * Kz * N^2 = power contributing to mixing 
+         !
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'zdf_iwm : Internal wave-driven mixing (iwm)'
+            WRITE(numout,*) '~~~~~~~ '
+            WRITE(numout,*)
+            WRITE(numout,*) '      Total power consumption by av_wave =  ', zztmp * 1.e-12_wp, 'TW'
+         ENDIF
+      ENDIF
+
+      !                          ! ----------------------- !
+      !                          !   Update  mixing coefs  !                          
+      !                          ! ----------------------- !
+      !      
+      IF( ln_tsdiff ) THEN          !* Option for differential mixing of salinity and temperature
+         DO jk = 2, jpkm1              ! Calculate S/T diffusivity ratio as a function of Reb
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zav_ratio(ji,jj,jk) = ( 0.505_wp + 0.495_wp *                                                                  &
+                      &   TANH(    0.92_wp * (   LOG10(  MAX( 1.e-20_wp, zReb(ji,jj,jk) * 5._wp * r1_6 )  ) - 0.60_wp   )    )   &
+                      &                 ) * wmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "av_ratio", zav_ratio )
+         DO jk = 2, jpkm1           !* update momentum & tracer diffusivity with wave-driven mixing
+            p_avs(:,:,jk) = p_avs(:,:,jk) + zav_wave(:,:,jk) * zav_ratio(:,:,jk)
+            p_avt(:,:,jk) = p_avt(:,:,jk) + zav_wave(:,:,jk)
+            p_avm(:,:,jk) = p_avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+         !
+      ELSE                          !* update momentum & tracer diffusivity with wave-driven mixing
+         DO jk = 2, jpkm1
+            p_avs(:,:,jk) = p_avs(:,:,jk) + zav_wave(:,:,jk)
+            p_avt(:,:,jk) = p_avt(:,:,jk) + zav_wave(:,:,jk)
+            p_avm(:,:,jk) = p_avm(:,:,jk) + zav_wave(:,:,jk)
+         END DO
+      ENDIF
+
+      !                             !* output internal wave-driven mixing coefficient
+      CALL iom_put( "av_wave", zav_wave )
+                                    !* output useful diagnostics: Kz*N^2 , 
+!!gm Kz*N2 should take into account the ratio avs/avt if it is used.... (see diaar5)
+                                    !  vertical integral of rau0 * Kz * N^2 , energy density (zemx_iwm)
+      IF( iom_use("bflx_iwm") .OR. iom_use("pcmap_iwm") ) THEN
+         ALLOCATE( z2d(jpi,jpj) , z3d(jpi,jpj,jpk) )
+         z3d(:,:,:) = MAX( 0._wp, rn2(:,:,:) ) * zav_wave(:,:,:)
+         z2d(:,:) = 0._wp
+         DO jk = 2, jpkm1
+            z2d(:,:) = z2d(:,:) + e3w_n(:,:,jk) * z3d(:,:,jk) * wmask(:,:,jk)
+         END DO
+         z2d(:,:) = rau0 * z2d(:,:)
+         CALL iom_put( "bflx_iwm", z3d )
+         CALL iom_put( "pcmap_iwm", z2d )
+         DEALLOCATE( z2d , z3d )
+      ENDIF
+      CALL iom_put( "emix_iwm", zemx_iwm )
+      
+      IF(ln_ctl)   CALL prt_ctl(tab3d_1=zav_wave , clinfo1=' iwm - av_wave: ', tab3d_2=avt, clinfo2=' avt: ', kdim=jpk)
+      !
+   END SUBROUTINE zdf_iwm
+
+
+   SUBROUTINE zdf_iwm_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zdf_iwm_init  ***
+      !!                     
+      !! ** Purpose :   Initialization of the wave-driven vertical mixing, reading
+      !!              of input power maps and decay length scales in netcdf files.
+      !!
+      !! ** Method  : - Read the namzdf_iwm namelist and check the parameters
+      !!
+      !!              - Read the input data in NetCDF files :
+      !!              power available from high-mode wave breaking (mixing_power_bot.nc)
+      !!              power available from pycnocline-intensified wave-breaking (mixing_power_pyc.nc)
+      !!              power available from critical slope wave-breaking (mixing_power_cri.nc)
+      !!              WKB decay scale for high-mode wave-breaking (decay_scale_bot.nc)
+      !!              decay scale for critical slope wave-breaking (decay_scale_cri.nc)
+      !!
+      !! ** input   : - Namlist namzdf_iwm
+      !!              - NetCDF files : mixing_power_bot.nc, mixing_power_pyc.nc, mixing_power_cri.nc,
+      !!              decay_scale_bot.nc decay_scale_cri.nc
+      !!
+      !! ** Action  : - Increase by 1 the nstop flag is setting problem encounter
+      !!              - Define ebot_iwm, epyc_iwm, ecri_iwm, hbot_iwm, hcri_iwm
+      !!
+      !! References : de Lavergne et al. JPO, 2015 ; de Lavergne PhD 2016
+      !!              de Lavergne et al. in prep., 2017
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   inum         ! local integer
+      INTEGER  ::   ios
+      REAL(wp) ::   zbot, zpyc, zcri   ! local scalars
+      !!
+      NAMELIST/namzdf_iwm/ nn_zpyc, ln_mevar, ln_tsdiff
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namzdf_iwm in reference namelist : Wave-driven mixing
+      READ  ( numnam_ref, namzdf_iwm, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namzdf_iwm in reference namelist' )
+      !
+      REWIND( numnam_cfg )              ! Namelist namzdf_iwm in configuration namelist : Wave-driven mixing
+      READ  ( numnam_cfg, namzdf_iwm, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 )   CALL ctl_nam ( ios , 'namzdf_iwm in configuration namelist' )
+      IF(lwm) WRITE ( numond, namzdf_iwm )
+      !
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'zdf_iwm_init : internal wave-driven mixing'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namzdf_iwm : set wave-driven mixing parameters'
+         WRITE(numout,*) '      Pycnocline-intensified diss. scales as N (=1) or N^2 (=2) = ', nn_zpyc
+         WRITE(numout,*) '      Variable (T) or constant (F) mixing efficiency            = ', ln_mevar
+         WRITE(numout,*) '      Differential internal wave-driven mixing (T) or not (F)   = ', ln_tsdiff
+      ENDIF
+      
+      ! The new wave-driven mixing parameterization elevates avt and avm in the interior, and
+      ! ensures that avt remains larger than its molecular value (=1.4e-7). Therefore, avtb should 
+      ! be set here to a very small value, and avmb to its (uniform) molecular value (=1.4e-6).
+      avmb(:) = 1.4e-6_wp        ! viscous molecular value
+      avtb(:) = 1.e-10_wp        ! very small diffusive minimum (background avt is specified in zdf_iwm)    
+      avtb_2d(:,:) = 1.e0_wp     ! uniform 
+      IF(lwp) THEN                  ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) '   Force the background value applied to avm & avt in TKE to be everywhere ',   &
+            &               'the viscous molecular value & a very small diffusive value, resp.'
+      ENDIF
+            
+      !                             ! allocate iwm arrays
+      IF( zdf_iwm_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'zdf_iwm_init : unable to allocate iwm arrays' )
+      !
+      !                             ! read necessary fields
+!!$      CALL iom_open('mixing_power_bot',inum)       ! energy flux for high-mode wave breaking [W/m2]
+!!$      CALL iom_get  (inum, jpdom_data, 'field', ebot_iwm, 1 ) 
+!!$      CALL iom_close(inum)
+      ebot_iwm(:,:) = 1.e-6
+      !
+!!$      CALL iom_open('mixing_power_pyc',inum)       ! energy flux for pynocline-intensified wave breaking [W/m2]
+!!$      CALL iom_get  (inum, jpdom_data, 'field', epyc_iwm, 1 )
+!!$      CALL iom_close(inum)
+      epyc_iwm(:,:) = 1.e-6
+      !
+!!$      CALL iom_open('mixing_power_cri',inum)       ! energy flux for critical slope wave breaking [W/m2]
+!!$      CALL iom_get  (inum, jpdom_data, 'field', ecri_iwm, 1 )
+!!$      CALL iom_close(inum)
+      ecri_iwm(:,:) = 1.e-10
+      !
+!!$      CALL iom_open('decay_scale_bot',inum)        ! spatially variable decay scale for high-mode wave breaking [m]
+!!$      CALL iom_get  (inum, jpdom_data, 'field', hbot_iwm, 1 )
+!!$      CALL iom_close(inum)
+      hbot_iwm(:,:) = 100.
+      !
+!!$      CALL iom_open('decay_scale_cri',inum)        ! spatially variable decay scale for critical slope wave breaking [m]
+!!$      CALL iom_get  (inum, jpdom_data, 'field', hcri_iwm, 1 )
+!!$      CALL iom_close(inum)
+      hcri_iwm(:,:) = 100.
+
+      ebot_iwm(:,:) = ebot_iwm(:,:) * ssmask(:,:)
+      epyc_iwm(:,:) = epyc_iwm(:,:) * ssmask(:,:)
+      ecri_iwm(:,:) = ecri_iwm(:,:) * ssmask(:,:)
+
+      zbot = glob_sum( 'zdfiwm', e1e2t(:,:) * ebot_iwm(:,:) )
+      zpyc = glob_sum( 'zdfiwm', e1e2t(:,:) * epyc_iwm(:,:) )
+      zcri = glob_sum( 'zdfiwm', e1e2t(:,:) * ecri_iwm(:,:) )
+      IF(lwp) THEN
+         WRITE(numout,*) '      High-mode wave-breaking energy:             ', zbot * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Pycnocline-intensifed wave-breaking energy: ', zpyc * 1.e-12_wp, 'TW'
+         WRITE(numout,*) '      Critical slope wave-breaking energy:        ', zcri * 1.e-12_wp, 'TW'
+      ENDIF
+      !
+   END SUBROUTINE zdf_iwm_init
+
+   !!======================================================================
+END MODULE zdfiwm
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/cpp_BENCH.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/cpp_BENCH.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/BENCH/cpp_BENCH.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys key_mpp_mpi key_si3 key_top
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@" sync_freq="10d" min_digits="4">
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="toce" /> 
+	  <field field_ref="soce" /> 
+	  <field field_ref="ssh"  />
+	  <field field_ref="socegrad"  />
+	  <field field_ref="eken_int"  />
+	  <field field_ref="relvor"  />
+	  <field field_ref="potvor"  />
+	  <field field_ref="saltc"  />
+	  <field field_ref="salt2c"  />
+	</file>
+
+	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="utau"  />
+	  <field field_ref="uoce" />
+	  <field_group group_ref="trendU"  />  
+	</file>
+	
+	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="vtau"  />
+	  <field field_ref="voce" />
+	  <field_group group_ref="trendV"  />  
+	</file>
+	
+	<file id="file5" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="woce" />
+	</file>
+
+      </file_group>
+
+   </file_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,25 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,373 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO Configuration namelist : overwrite some defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                          CANAL configuration                       !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   CANAL configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   rn_domszx   =   2000.   !  x horizontal size         [km]
+   rn_domszy   =   1000.   !  y horizontal size         [km]
+   rn_domszz   =   1000.   !  z vertical size            [m]
+   rn_dx       =     10.   !  x horizontal resolution   [km]
+   rn_dy       =     10.   !  y horizontal resolution   [km]
+   rn_dz       =   1000.   !  z vertical resolution      [m]
+   rn_0xratio  =      0.5  !  x-domain ratio of the 0
+   rn_0yratio  =      0.5  !  y-domain ratio of the 0
+   nn_fcase    =      0    !  F computation (0:f0, 1:Beta, 2:real)
+   rn_ppgphi0  =    38.5   !  Reference latitude      [degrees]
+   rn_u10      =      0.   !  10m wind speed              [m/s]
+     rn_windszx =   90.    !  longitudinal wind extension   [km]
+     rn_windszy =   90.    !  latitudinal wind extension    [km]
+!!clem     rn_uofac  =     0.    !  Uoce multiplicative factor (0.:absolute or 1.:relative winds)
+   rn_vtxmax   =      1.   !  initial vortex max current  [m/s]
+   rn_uzonal   =      1.   !  initial zonal current       [m/s]
+     rn_ujetszx =   4000.  !  longitudinal jet extension   [km]
+     rn_ujetszy =   400.   !  latitudinal jet extension    [km]
+   nn_botcase  =      0    !  bottom definition (0:flat, 1:bump)
+   nn_initcase =      1    !  initial condition case
+   !                       !          -1 : stratif at rest
+   !                       !           0 : rest
+   !                       !           1 : zonal current
+   !                       !           2 : current shear
+   !                       !           3 : gaussian zonal current
+   !                       !           4 : geostrophic zonal pulse
+   !                       !           5 : baroclinic vortex
+   ln_sshnoise =  .FALSE.  !  add random noise on initial ssh
+   rn_lambda   =     50.   !  gaussian lambda
+   nn_perio    = 1
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   'CANAL' !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =     100   !  last time step 
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   99999   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   99999   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   =  .false.  !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_rdt      =   1200.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.0     !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+      cn_domcfg_out = "domain_cfg" ! newly created domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF =F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF =F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T & S) namelists                    !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                            !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.28        !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF = .false. !  No tracer advection
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  2            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  2            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .false. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .true.  !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   = .true.    !  No explicit diffusion
+   ln_traldf_lap   = .false.   !    laplacian operator
+   ln_traldf_blp   = .false.   !  bilaplacian operator
+   !
+   !                       !  Direction of action:
+   ln_traldf_lev   = .false.   !  iso-level
+   ln_traldf_hor   = .true.    !  horizontal  (geopotential)
+   ln_traldf_iso   = .false.   !  iso-neutral (standard operator)
+   ln_traldf_triad = .false.   !  iso-neutral (triad    operator)
+   !
+   !                             !  iso-neutral options:
+   ln_traldf_msc   = .false.   !  Method of Stabilizing Correction      (both operators)
+   rn_slpmax       =  0.01     !  slope limit                           (both operators)
+   ln_triad_iso    = .false.   !  pure horizontal mixing in ML              (triad only)
+   rn_sw_triad     = 1         !  =1 switching triad ; =0 all 4 triads used (triad only)
+   ln_botmix_triad = .false.   !  lateral mixing on bottom                  (triad only)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 31         !  space/time variation of eddy coefficient:
+      !                             !   =-20 (=-30)    read in eddy_diffusivity_2D.nc (..._3D.nc) file
+      !                             !   =  0           constant
+      !                             !   = 10 F(k)      =ldf_c1d
+      !                             !   = 20 F(i,j)    =ldf_c2d
+      !                             !   = 21 F(i,j,t)  =Treguier et al. JPO 1997 formulation
+      !                             !   = 30 F(i,j,k)  =ldf_c2d * ldf_c1d
+      !                             !   = 31 F(i,j,k,t)=F(local velocity and grid-spacing)
+      !                        !  time invariant coefficients:  aht0 = 1/2  Ud*Ld   (lap case)
+      !                             !                           or   = 1/12 Ud*Ld^3 (blp case)
+      rn_Ud        = 0.01           !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld        = 200.e+3        !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+      nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs  = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false.  !  energy conserving scheme
+   ln_dynvor_ens = .false.  !  enstrophy conserving scheme
+   ln_dynvor_mix = .false.  !  mixed scheme
+   ln_dynvor_een = .false.  !  energy & enstrophy scheme
+   ln_dynvor_enT = .false.  !  energy conserving scheme (T-point)
+   ln_dynvor_eeT = .true.   !  energy conserving scheme (een using e3t)
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_exp  = .false. 
+   ln_dynspg_ts   = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.    ! Number of sub-step defined from:
+         nn_baro      =  24         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 31           !  space/time variation of eddy coef
+      !                             !  =-30  read in eddy_viscosity_3D.nc file
+      !                             !  =-20  read in eddy_viscosity_2D.nc file
+      !                             !  =  0  constant 
+      !                             !  = 10  F(k)=c1d
+      !                             !  = 20  F(i,j)=F(grid spacing)=c2d
+      !                             !  = 30  F(i,j,k)=c2d*c1d
+      !                             !  = 31  F(i,j,k)=F(grid spacing and local velocity)
+      !                             !  = 32  F(i,j,k)=F(local gridscale and deformation rate)
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 0.1              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 30.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+      !                       !  Smagorinsky settings  (nn_ahm_ijk_t= 32) :
+      rn_csmc       = 3.5         !  Smagorinsky constant of proportionality
+      rn_minfac     = 1.0         !  multiplier of theorectical lower limit
+      rn_maxfac     = 1.0         !  multiplier of theorectical upper limit
+      !                       !  iso-neutral laplacian operator (ln_dynldf_iso=T) :
+      rn_ahm_b      = 0.0         !  background eddy viscosity  [m2/s]
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      ("key_float")
+!!   nam_diaharm  Harmonic analysis of tidal constituents               ("key_diaharm")
+!!   namdct       transports through some sections                      ("key_diadct")
+!!   nam_diatmb   Top Middle Bottom Output                              (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default: OFF)
+!-----------------------------------------------------------------------
+   ln_glo_trd  = .false.   ! (T) global domain averaged diag for T, T^2, KE, and PE
+   ln_dyn_trd  = .true.    ! (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)
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+!!   jpni        =   8       !  jpni   number of processors following i (set automatically if < 1)
+!!   jpnj        =   1       !  jpnj   number of processors following j (set automatically if < 1)
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+   ln_timing   = .true.   !  timing by routine write out in timing.output file
+!!   ln_diacfl   = .true.   !  CFL diagnostics write out in cfl_diagnostics.ascii
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/diawri.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/diawri.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/diawri.F90	(revision 14097)
@@ -0,0 +1,1008 @@
+MODULE diawri
+   !!======================================================================
+   !!                     ***  MODULE  diawri  ***
+   !! Ocean diagnostics :  write ocean output files
+   !!=====================================================================
+   !! History :  OPA  ! 1991-03  (M.-A. Foujols)  Original code
+   !!            4.0  ! 1991-11  (G. Madec)
+   !!                 ! 1992-06  (M. Imbard)  correction restart file
+   !!                 ! 1992-07  (M. Imbard)  split into diawri and rstwri
+   !!                 ! 1993-03  (M. Imbard)  suppress writibm
+   !!                 ! 1998-01  (C. Levy)  NETCDF format using ioipsl INTERFACE
+   !!                 ! 1999-02  (E. Guilyardi)  name of netCDF files + variables
+   !!            8.2  ! 2000-06  (M. Imbard)  Original code (diabort.F)
+   !!   NEMO     1.0  ! 2002-06  (A.Bozec, E. Durand)  Original code (diainit.F)
+   !!             -   ! 2002-09  (G. Madec)  F90: Free form and module
+   !!             -   ! 2002-12  (G. Madec)  merge of diabort and diainit, F90
+   !!                 ! 2005-11  (V. Garnier) Surface pressure gradient organization
+   !!            3.2  ! 2008-11  (B. Lemaire) creation from old diawri
+   !!            3.7  ! 2014-01  (G. Madec) remove eddy induced velocity from no-IOM output
+   !!                 !                     change name of output variables in dia_wri_state
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dia_wri       : create the standart output files
+   !!   dia_wri_state : create an output NetCDF file for a single instantaeous ocean state and forcing fields
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers 
+   USE dom_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   USE dianam         ! build name of file (routine)
+   USE diahth         ! thermocline diagnostics
+   USE dynadv   , ONLY: ln_dynadv_vec
+   USE icb_oce        ! Icebergs
+   USE icbdia         ! Iceberg budgets
+   USE ldftra         ! lateral physics: eddy diffusivity coef.
+   USE ldfdyn         ! lateral physics: eddy viscosity   coef.
+   USE sbc_oce        ! Surface boundary condition: ocean fields
+   USE sbc_ice        ! Surface boundary condition: ice fields
+   USE sbcssr         ! restoring term toward SST/SSS climatology
+   USE sbcwave        ! wave parameters
+   USE wet_dry        ! wetting and drying
+   USE zdf_oce        ! ocean vertical physics
+   USE zdfdrg         ! ocean vertical physics: top/bottom friction
+   USE zdfmxl         ! mixed layer
+   !
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager ! I/O manager
+   USE dia25h         ! 25h Mean output
+   USE iom            ! 
+   USE ioipsl         ! 
+
+#if defined key_si3
+   USE ice 
+   USE icewri 
+#endif
+   USE lib_mpp         ! MPP library
+   USE timing          ! preformance summary
+   USE diurnal_bulk    ! diurnal warm layer
+   USE cool_skin       ! Cool skin
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   dia_wri                 ! routines called by step.F90
+   PUBLIC   dia_wri_state
+   PUBLIC   dia_wri_alloc           ! Called by nemogcm module
+
+   INTEGER ::   nid_T, nz_T, nh_T, ndim_T, ndim_hT   ! grid_T file
+   INTEGER ::          nb_T              , ndim_bT   ! grid_T file
+   INTEGER ::   nid_U, nz_U, nh_U, ndim_U, ndim_hU   ! grid_U file
+   INTEGER ::   nid_V, nz_V, nh_V, ndim_V, ndim_hV   ! grid_V file
+   INTEGER ::   nid_W, nz_W, nh_W                    ! grid_W file
+   INTEGER ::   ndex(1)                              ! ???
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_hT, ndex_hU, ndex_hV
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_T, ndex_U, ndex_V
+   INTEGER, SAVE, ALLOCATABLE, DIMENSION(:) :: ndex_bT
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+#if defined key_iomput
+   !!----------------------------------------------------------------------
+   !!   'key_iomput'                                        use IOM library
+   !!----------------------------------------------------------------------
+   INTEGER FUNCTION dia_wri_alloc()
+      !
+      dia_wri_alloc = 0
+      !
+   END FUNCTION dia_wri_alloc
+
+   
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!
+      !! ** Method  :  use iom_put
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index
+      !!
+      INTEGER ::   ji, jj, jk       ! dummy loop indices
+      INTEGER ::   ikbot            ! local integer
+      REAL(wp)::   zztmp , zztmpx   ! local scalar
+      REAL(wp)::   zztmp2, zztmpy   !   -      -
+      REAL(wp)::   ze3   !   -      -
+      REAL(wp), DIMENSION(jpi,jpj)     ::   z2d   ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   z3d   ! 3D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   bu, bv   ! volume of u- and v-boxes
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   r1_bt    ! inverse of t-box volume
+      !!----------------------------------------------------------------------
+      ! 
+      IF( ln_timing )   CALL timing_start('dia_wri')
+      ! 
+      ! Output the initial state and forcings
+      IF( ninist == 1 ) THEN                       
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+
+      ! Output of initial vertical scale factor
+      CALL iom_put("e3t_0", e3t_0(:,:,:) )
+      CALL iom_put("e3u_0", e3u_0(:,:,:) )
+      CALL iom_put("e3v_0", e3v_0(:,:,:) )
+      !
+      CALL iom_put( "e3t" , e3t_n(:,:,:) )
+      CALL iom_put( "e3u" , e3u_n(:,:,:) )
+      CALL iom_put( "e3v" , e3v_n(:,:,:) )
+      CALL iom_put( "e3w" , e3w_n(:,:,:) )
+      IF( iom_use("e3tdef") )   &
+         CALL iom_put( "e3tdef"  , ( ( e3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2 )
+
+      IF( ll_wd ) THEN
+         CALL iom_put( "ssh" , (sshn+ssh_ref)*tmask(:,:,1) )   ! sea surface height (brought back to the reference used for wetting and drying)
+      ELSE
+         CALL iom_put( "ssh" , sshn )              ! sea surface height
+      ENDIF
+
+      IF( iom_use("wetdep") )   &                  ! wet depth
+         CALL iom_put( "wetdep" , ht_0(:,:) + sshn(:,:) )
+      
+      CALL iom_put( "toce", tsn(:,:,:,jp_tem) )    ! 3D temperature
+      CALL iom_put(  "sst", tsn(:,:,1,jp_tem) )    ! surface temperature
+      IF ( iom_use("sbt") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkt(ji,jj)
+               z2d(ji,jj) = tsn(ji,jj,ikbot,jp_tem)
+            END DO
+         END DO
+         CALL iom_put( "sbt", z2d )                ! bottom temperature
+      ENDIF
+      
+      CALL iom_put( "soce", tsn(:,:,:,jp_sal) )    ! 3D salinity
+      CALL iom_put(  "sss", tsn(:,:,1,jp_sal) )    ! surface salinity
+      IF ( iom_use("sbs") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkt(ji,jj)
+               z2d(ji,jj) = tsn(ji,jj,ikbot,jp_sal)
+            END DO
+         END DO
+         CALL iom_put( "sbs", z2d )                ! bottom salinity
+      ENDIF
+
+      IF ( iom_use("taubot") ) THEN                ! bottom stress
+         zztmp = rau0 * 0.25
+         z2d(:,:) = 0._wp
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zztmp2 = (  ( rCdU_bot(ji+1,jj)+rCdU_bot(ji  ,jj) ) * un(ji  ,jj,mbku(ji  ,jj))  )**2   &
+                  &   + (  ( rCdU_bot(ji  ,jj)+rCdU_bot(ji-1,jj) ) * un(ji-1,jj,mbku(ji-1,jj))  )**2   &
+                  &   + (  ( rCdU_bot(ji,jj+1)+rCdU_bot(ji,jj  ) ) * vn(ji,jj  ,mbkv(ji,jj  ))  )**2   &
+                  &   + (  ( rCdU_bot(ji,jj  )+rCdU_bot(ji,jj-1) ) * vn(ji,jj-1,mbkv(ji,jj-1))  )**2
+               z2d(ji,jj) = zztmp * SQRT( zztmp2 ) * tmask(ji,jj,1) 
+               !
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', 1. )
+         CALL iom_put( "taubot", z2d )           
+      ENDIF
+         
+      CALL iom_put( "uoce", un(:,:,:) )            ! 3D i-current
+      CALL iom_put(  "ssu", un(:,:,1) )            ! surface i-current
+      IF ( iom_use("sbu") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbku(ji,jj)
+               z2d(ji,jj) = un(ji,jj,ikbot)
+            END DO
+         END DO
+         CALL iom_put( "sbu", z2d )                ! bottom i-current
+      ENDIF
+      
+      CALL iom_put( "voce", vn(:,:,:) )            ! 3D j-current
+      CALL iom_put(  "ssv", vn(:,:,1) )            ! surface j-current
+      IF ( iom_use("sbv") ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ikbot = mbkv(ji,jj)
+               z2d(ji,jj) = vn(ji,jj,ikbot)
+            END DO
+         END DO
+         CALL iom_put( "sbv", z2d )                ! bottom j-current
+      ENDIF
+
+      CALL iom_put( "woce", wn )                   ! vertical velocity
+      IF( iom_use('w_masstr') .OR. iom_use('w_masstr2') ) THEN   ! vertical mass transport & its square value
+         ! Caution: in the VVL case, it only correponds to the baroclinic mass transport.
+         z2d(:,:) = rau0 * e1e2t(:,:)
+         DO jk = 1, jpk
+            z3d(:,:,jk) = wn(:,:,jk) * z2d(:,:)
+         END DO
+         CALL iom_put( "w_masstr" , z3d )  
+         IF( iom_use('w_masstr2') )   CALL iom_put( "w_masstr2", z3d(:,:,:) * z3d(:,:,:) )
+      ENDIF
+
+      CALL iom_put( "avt" , avt )                  ! T vert. eddy diff. coef.
+      CALL iom_put( "avs" , avs )                  ! S vert. eddy diff. coef.
+      CALL iom_put( "avm" , avm )                  ! T vert. eddy visc. coef.
+
+      IF( iom_use('logavt') )   CALL iom_put( "logavt", LOG( MAX( 1.e-20_wp, avt(:,:,:) ) ) )
+      IF( iom_use('logavs') )   CALL iom_put( "logavs", LOG( MAX( 1.e-20_wp, avs(:,:,:) ) ) )
+
+      IF ( iom_use("socegrad") .OR. iom_use("socegrad2") ) THEN
+         z3d(:,:,jpk) = 0.
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1                                    ! sal gradient
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zztmp  = tsn(ji,jj,jk,jp_sal)
+                  zztmpx = ( tsn(ji+1,jj,jk,jp_sal) - zztmp ) * r1_e1u(ji,jj) + ( zztmp - tsn(ji-1,jj  ,jk,jp_sal) ) * r1_e1u(ji-1,jj)
+                  zztmpy = ( tsn(ji,jj+1,jk,jp_sal) - zztmp ) * r1_e2v(ji,jj) + ( zztmp - tsn(ji  ,jj-1,jk,jp_sal) ) * r1_e2v(ji,jj-1)
+                  z3d(ji,jj,jk) = 0.25 * ( zztmpx * zztmpx + zztmpy * zztmpy )   &
+                     &                 * umask(ji,jj,jk) * umask(ji-1,jj,jk) * vmask(ji,jj,jk) * umask(ji,jj-1,jk)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z3d, 'T', 1. )
+         CALL iom_put( "socegrad2",  z3d )          ! square of module of sal gradient
+         z3d(:,:,:) = SQRT( z3d(:,:,:) )
+         CALL iom_put( "socegrad" ,  z3d )          ! module of sal gradient
+      ENDIF
+         
+      IF ( iom_use("sstgrad") .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 ) * r1_e1u(ji,jj) + ( zztmp - tsn(ji-1,jj  ,1,jp_tem) ) * r1_e1u(ji-1,jj)
+               zztmpy = ( tsn(ji,jj+1,1,jp_tem) - zztmp ) * r1_e2v(ji,jj) + ( zztmp - tsn(ji  ,jj-1,1,jp_tem) ) * r1_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( 'diawri', z2d, 'T', 1. )
+         CALL iom_put( "sstgrad2",  z2d )          ! square of module of sst gradient
+         z2d(:,:) = SQRT( z2d(:,:) )
+         CALL iom_put( "sstgrad" ,  z2d )          ! module of sst gradient
+      ENDIF
+         
+      ! heat and salt contents
+      IF( iom_use("heatc") ) THEN
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         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 = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "saltc", rau0 * z2d )          ! vertically integrated salt content (PSU*kg/m2)
+      ENDIF
+      !
+      IF( iom_use("salt2c") ) THEN
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_sal) * tsn(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "salt2c", rau0 * z2d )          ! vertically integrated squared salt content (PSU*kg/m2)
+      ENDIF
+      !
+      IF ( iom_use("eken") .OR. iom_use("eken_int") ) THEN
+         z3d(:,:,jpk) = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  zztmpx = 0.5 * ( un(ji-1,jj  ,jk) + un(ji,jj,jk) )
+                  zztmpy = 0.5 * ( vn(ji  ,jj-1,jk) + vn(ji,jj,jk) )
+                  z3d(ji,jj,jk) = 0.5 * ( zztmpx*zztmpx + zztmpy*zztmpy )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z3d, 'T', 1. )
+         CALL iom_put( "eken", z3d )                 ! kinetic energy
+
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + e3t_n(ji,jj,jk) * z3d(ji,jj,jk) * e1e2t(ji,jj) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "eken_int", z2d )   ! vertically integrated kinetic energy
+      ENDIF
+      !
+      CALL iom_put( "hdiv", hdivn )                  ! Horizontal divergence
+
+      IF ( iom_use("relvor") .OR. iom_use("absvor") .OR. iom_use("potvor") ) THEN
+         
+         z3d(:,:,jpk) = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  z3d(ji,jj,jk) = (  e2v(ji+1,jj  ) * vn(ji+1,jj  ,jk) - e2v(ji,jj) * vn(ji,jj,jk)    &
+                     &             - e1u(ji  ,jj+1) * un(ji  ,jj+1,jk) + e1u(ji,jj) * un(ji,jj,jk)  ) * r1_e1e2f(ji,jj)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z3d, 'F', 1. )
+         CALL iom_put( "relvor", z3d )                  ! relative vorticity
+
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z3d(ji,jj,jk) = ff_f(ji,jj) + z3d(ji,jj,jk) 
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "absvor", z3d )                  ! absolute vorticity
+
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  ze3  = (  e3t_n(ji,jj+1,jk)*tmask(ji,jj+1,jk) + e3t_n(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
+                     &    + e3t_n(ji,jj  ,jk)*tmask(ji,jj  ,jk) + e3t_n(ji+1,jj  ,jk)*tmask(ji+1,jj  ,jk)  )
+                  IF( ze3 /= 0._wp ) THEN   ;   ze3 = 4._wp / ze3
+                  ELSE                      ;   ze3 = 0._wp
+                  ENDIF
+                  z3d(ji,jj,jk) = ze3 * z3d(ji,jj,jk) 
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z3d, 'F', 1. )
+         CALL iom_put( "potvor", z3d )                  ! potential vorticity
+
+      ENDIF
+   
+      !
+      IF( iom_use("u_masstr") .OR. iom_use("u_masstr_vint") .OR. iom_use("u_heattr") .OR. iom_use("u_salttr") ) THEN
+         z3d(:,:,jpk) = 0.e0
+         z2d(:,:) = 0.e0
+         DO jk = 1, jpkm1
+            z3d(:,:,jk) = rau0 * un(:,:,jk) * e2u(:,:) * e3u_n(:,:,jk) * umask(:,:,jk)
+            z2d(:,:) = z2d(:,:) + z3d(:,:,jk)
+         END DO
+         CALL iom_put( "u_masstr"     , z3d )         ! mass transport in i-direction
+         CALL iom_put( "u_masstr_vint", z2d )         ! mass transport in i-direction vertical sum
+      ENDIF
+      
+      IF( iom_use("u_heattr") ) 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) + 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( 'diawri', z2d, 'U', -1. )
+         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) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', 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(:,:) * e3v_n(:,:,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( 'diawri', z2d, 'V', -1. )
+         CALL iom_put( "v_heattr", 0.5*rcp * z2d )    !  heat transport in j-direction
+      ENDIF
+
+      IF( iom_use("v_salttr") ) 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) + 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( 'diawri', z2d, 'V', -1. )
+         CALL iom_put( "v_salttr", 0.5 * z2d )        !  heat transport in j-direction
+      ENDIF
+
+      IF( iom_use("tosmint") ) 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) + e3t_n(ji,jj,jk) *  tsn(ji,jj,jk,jp_tem)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', -1. )
+         CALL iom_put( "tosmint", rau0 * z2d )        ! Vertical integral of temperature
+      ENDIF
+      IF( iom_use("somint") ) 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) + e3t_n(ji,jj,jk) * tsn(ji,jj,jk,jp_sal)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'diawri', z2d, 'T', -1. )
+         CALL iom_put( "somint", rau0 * z2d )         ! Vertical integral of salinity
+      ENDIF
+
+      CALL iom_put( "bn2", rn2 )                      ! Brunt-Vaisala buoyancy frequency (N^2)
+      !
+          
+      IF (ln_dia25h)   CALL dia_25h( kt )             ! 25h averaging
+
+      IF( ln_timing )   CALL timing_stop('dia_wri')
+      !
+   END SUBROUTINE dia_wri
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option                                  use IOIPSL  library
+   !!----------------------------------------------------------------------
+
+   INTEGER FUNCTION dia_wri_alloc()
+      !!----------------------------------------------------------------------
+      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) ,     &
+         &      ndex_hV(jpi*jpj) , ndex_V(jpi*jpj*jpk) , STAT=ierr(1) )
+         !
+      dia_wri_alloc = MAXVAL(ierr)
+      CALL mpp_sum( 'diawri', dia_wri_alloc )
+      !
+   END FUNCTION dia_wri_alloc
+
+   
+   SUBROUTINE dia_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_wri  ***
+      !!                   
+      !! ** Purpose :   Standard output of opa: dynamics and tracer fields 
+      !!      NETCDF format is used by default 
+      !!
+      !! ** Method  :   At the beginning of the first time step (nit000), 
+      !!      define all the NETCDF files and fields
+      !!      At each time step call histdef to compute the mean if ncessary
+      !!      Each nn_write time step, output the instantaneous or mean fields
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      LOGICAL ::   ll_print = .FALSE.                        ! =T print and flush numout
+      CHARACTER (len=40) ::   clhstnam, clop, clmx           ! local names
+      INTEGER  ::   inum = 11                                ! temporary logical unit
+      INTEGER  ::   ji, jj, jk                               ! dummy loop indices
+      INTEGER  ::   ierr                                     ! error code return from allocation
+      INTEGER  ::   iimi, iima, ipk, it, itmod, ijmi, ijma   ! local integers
+      INTEGER  ::   jn, ierror                               ! local integers
+      REAL(wp) ::   zsto, zout, zmax, zjulian                ! local scalars
+      !
+      REAL(wp), DIMENSION(jpi,jpj)   :: zw2d       ! 2D workspace
+      REAL(wp), DIMENSION(jpi,jpj,jpk) :: zw3d       ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF( ninist == 1 ) THEN     !==  Output the initial state and forcings  ==!
+         CALL dia_wri_state( 'output.init' )
+         ninist = 0
+      ENDIF
+      !
+      IF( nn_write == -1 )   RETURN   ! we will never do any output
+      ! 
+      IF( ln_timing )   CALL timing_start('dia_wri')
+      !
+      ! 0. Initialisation
+      ! -----------------
+
+      ll_print = .FALSE.                  ! local variable for debugging
+      ll_print = ll_print .AND. lwp
+
+      ! Define frequency of output and means
+      clop = "x"         ! no use of the mask value (require less cpu time and otherwise the model crashes)
+#if defined key_diainstant
+      zsto = nn_write * rdt
+      clop = "inst("//TRIM(clop)//")"
+#else
+      zsto=rdt
+      clop = "ave("//TRIM(clop)//")"
+#endif
+      zout = nn_write * rdt
+      zmax = ( nitend - nit000 + 1 ) * rdt
+
+      ! Define indices of the horizontal output zoom and vertical limit storage
+      iimi = 1      ;      iima = jpi
+      ijmi = 1      ;      ijma = jpj
+      ipk = jpk
+
+      ! define time axis
+      it = kt
+      itmod = kt - nit000 + 1
+
+
+      ! 1. Define NETCDF files and fields at beginning of first time step
+      ! -----------------------------------------------------------------
+
+      IF( kt == nit000 ) THEN
+
+         ! Define the NETCDF files (one per grid)
+
+         ! 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
+         IF(lwp)WRITE(numout,*) ' indexes of zoom = ', iimi, iima, ijmi, ijma,   &
+                                 ' limit storage in depth = ', ipk
+
+         ! WRITE root name in date.file for use by postpro
+         IF(lwp) THEN
+            CALL dia_nam( clhstnam, nn_write,' ' )
+            CALL ctl_opn( inum, 'date.file', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            WRITE(inum,*) clhstnam
+            CLOSE(inum)
+         ENDIF
+
+         ! Define the T grid FILE ( nid_T )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_T' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_T, nid_T, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_T, "deptht", "Vertical T levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_T, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, tmask, 1, 1., ndex_T , ndim_T  )      ! volume
+         CALL wheneq( jpi*jpj    , tmask, 1, 1., ndex_hT, ndim_hT )      ! surface
+         !
+         IF( ln_icebergs ) THEN
+            !
+            !! allocation cant go in dia_wri_alloc because ln_icebergs is only set after 
+            !! that routine is called from nemogcm, so do it here immediately before its needed
+            ALLOCATE( ndex_bT(jpi*jpj*nclasses), STAT=ierror )
+            CALL mpp_sum( 'diawri', ierror )
+            IF( ierror /= 0 ) THEN
+               CALL ctl_stop('dia_wri: failed to allocate iceberg diagnostic array')
+               RETURN
+            ENDIF
+            !
+            !! iceberg vertical coordinate is class number
+            CALL histvert( nid_T, "class", "Iceberg class",      &  ! Vertical grid: class
+               &           "number", nclasses, class_num, nb_T )
+            !
+            !! each class just needs the surface index pattern
+            ndim_bT = 3
+            DO jn = 1,nclasses
+               ndex_bT((jn-1)*jpi*jpj+1:jn*jpi*jpj) = ndex_hT(1:jpi*jpj)
+            ENDDO
+            !
+         ENDIF
+
+         ! Define the U grid FILE ( nid_U )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_U' )
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam    ! filename
+         CALL histbeg( clhstnam, jpi, glamu, jpj, gphiu,           &  ! Horizontal grid: glamu and gphiu
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_U, nid_U, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_U, "depthu", "Vertical U levels",      &  ! Vertical grid: gdept
+            &           "m", ipk, gdept_1d, nz_U, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, umask, 1, 1., ndex_U , ndim_U  )      ! volume
+         CALL wheneq( jpi*jpj    , umask, 1, 1., ndex_hU, ndim_hU )      ! surface
+
+         ! Define the V grid FILE ( nid_V )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_V' )                   ! filename
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam
+         CALL histbeg( clhstnam, jpi, glamv, jpj, gphiv,           &  ! Horizontal grid: glamv and gphiv
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_V, nid_V, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_V, "depthv", "Vertical V levels",      &  ! Vertical grid : gdept
+            &          "m", ipk, gdept_1d, nz_V, "down" )
+         !                                                            ! Index of ocean points
+         CALL wheneq( jpi*jpj*ipk, vmask, 1, 1., ndex_V , ndim_V  )      ! volume
+         CALL wheneq( jpi*jpj    , vmask, 1, 1., ndex_hV, ndim_hV )      ! surface
+
+         ! Define the W grid FILE ( nid_W )
+
+         CALL dia_nam( clhstnam, nn_write, 'grid_W' )                   ! filename
+         IF(lwp) WRITE(numout,*) " Name of NETCDF file ", clhstnam
+         CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,           &  ! Horizontal grid: glamt and gphit
+            &          iimi, iima-iimi+1, ijmi, ijma-ijmi+1,       &
+            &          nit000-1, zjulian, rdt, nh_W, nid_W, domain_id=nidom, snc4chunks=snc4set )
+         CALL histvert( nid_W, "depthw", "Vertical W levels",      &  ! Vertical grid: gdepw
+            &          "m", ipk, gdepw_1d, nz_W, "down" )
+
+
+         ! Declare all the output fields as NETCDF variables
+
+         !                                                                                      !!! nid_T : 3D
+         CALL histdef( nid_T, "votemper", "Temperature"                        , "C"      ,   &  ! tn
+            &          jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         CALL histdef( nid_T, "vosaline", "Salinity"                           , "PSU"    ,   &  ! sn
+            &          jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         IF(  .NOT.ln_linssh  ) THEN
+            CALL histdef( nid_T, "vovvle3t", "Level thickness"                    , "m"      ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+            CALL histdef( nid_T, "vovvldep", "T point depth"                      , "m"      ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+            CALL histdef( nid_T, "vovvldef", "Squared level deformation"          , "%^2"    ,&  ! e3t_n
+            &             jpi, jpj, nh_T, ipk, 1, ipk, nz_T, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_T : 2D
+         CALL histdef( nid_T, "sosstsst", "Sea Surface temperature"            , "C"      ,   &  ! sst
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sosaline", "Sea Surface Salinity"               , "PSU"    ,   &  ! sss
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sossheig", "Sea Surface Height"                 , "m"      ,   &  ! ssh
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowaflup", "Net Upward Water Flux"              , "Kg/m2/s",   &  ! (emp-rnf)
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sorunoff", "River runoffs"                      , "Kg/m2/s",   &  ! runoffs
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sosfldow", "downward salt flux"                 , "PSU/m2/s",  &  ! sfx
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         IF(  ln_linssh  ) THEN
+            CALL histdef( nid_T, "sosst_cd", "Concentration/Dilution term on temperature"     &  ! emp * tsn(:,:,1,jp_tem)
+            &                                                                  , "KgC/m2/s",  &  ! sosst_cd
+            &             jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sosss_cd", "Concentration/Dilution term on salinity"        &  ! emp * tsn(:,:,1,jp_sal)
+            &                                                                  , "KgPSU/m2/s",&  ! sosss_cd
+            &             jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         ENDIF
+         CALL histdef( nid_T, "sohefldo", "Net Downward Heat Flux"             , "W/m2"   ,   &  ! qns + qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soshfldo", "Shortwave Radiation"                , "W/m2"   ,   &  ! qsr
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "somixhgt", "Turbocline Depth"                   , "m"      ,   &  ! hmld
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "somxl010", "Mixed Layer Depth 0.01"             , "m"      ,   &  ! hmlp
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "soicecov", "Ice fraction"                       , "[0,1]"  ,   &  ! fr_i
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sowindsp", "wind speed at 10m"                  , "m/s"    ,   &  ! wndm
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+!
+         IF( ln_icebergs ) THEN
+            CALL histdef( nid_T, "calving"             , "calving mass input"                       , "kg/s"   , &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "calving_heat"        , "calving heat flux"                        , "XXXX"   , &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "berg_floating_melt"  , "Melt rate of icebergs + bits"             , "kg/m2/s", &
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "berg_stored_ice"     , "Accumulated ice mass by class"            , "kg"     , &
+               &          jpi, jpj, nh_T, nclasses  , 1, nclasses  , nb_T , 32, clop, zsto, zout )
+            IF( ln_bergdia ) THEN
+               CALL histdef( nid_T, "berg_melt"           , "Melt rate of icebergs"                    , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_buoy_melt"      , "Buoyancy component of iceberg melt rate"  , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_eros_melt"      , "Erosion component of iceberg melt rate"   , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_conv_melt"      , "Convective component of iceberg melt rate", "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_virtual_area"   , "Virtual coverage by icebergs"             , "m2"     , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_src"           , "Mass source of bergy bits"                , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_melt"          , "Melt rate of bergy bits"                  , "kg/m2/s", &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "bits_mass"          , "Bergy bit density field"                  , "kg/m2"  , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_mass"           , "Iceberg density field"                    , "kg/m2"  , &
+                  &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+               CALL histdef( nid_T, "berg_real_calving"   , "Calving into iceberg class"               , "kg/s"   , &
+                  &          jpi, jpj, nh_T, nclasses  , 1, nclasses  , nb_T , 32, clop, zsto, zout )
+            ENDIF
+         ENDIF
+
+         IF( ln_ssr ) 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 
+!            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clmx, zsto, zout )
+#if defined key_diahth
+         CALL histdef( nid_T, "sothedep", "Thermocline Depth"                  , "m"      ,   & ! hth
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "so20chgt", "Depth of 20C isotherm"              , "m"      ,   & ! hd20
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "so28chgt", "Depth of 28C isotherm"              , "m"      ,   & ! hd28
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         CALL histdef( nid_T, "sohtc300", "Heat content 300 m"                 , "J/m2"   ,   & ! htc3
+            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+#endif
+
+         CALL histend( nid_T, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_U : 3D
+         CALL histdef( nid_U, "vozocrtx", "Zonal Current"                      , "m/s"    ,   &  ! un
+            &          jpi, jpj, nh_U, ipk, 1, ipk, nz_U, 32, clop, zsto, zout )
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_U, "sdzocrtx", "Stokes Drift Zonal Current"         , "m/s"    ,   &  ! usd
+               &          jpi, jpj, nh_U, ipk, 1, ipk, nz_U, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_U : 2D
+         CALL histdef( nid_U, "sozotaux", "Wind Stress along i-axis"           , "N/m2"   ,   &  ! utau
+            &          jpi, jpj, nh_U, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_U, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_V : 3D
+         CALL histdef( nid_V, "vomecrty", "Meridional Current"                 , "m/s"    ,   &  ! vn
+            &          jpi, jpj, nh_V, ipk, 1, ipk, nz_V, 32, clop, zsto, zout )
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_V, "sdmecrty", "Stokes Drift Meridional Current"    , "m/s"    ,   &  ! vsd
+               &          jpi, jpj, nh_V, ipk, 1, ipk, nz_V, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_V : 2D
+         CALL histdef( nid_V, "sometauy", "Wind Stress along j-axis"           , "N/m2"   ,   &  ! vtau
+            &          jpi, jpj, nh_V, 1  , 1, 1  , - 99, 32, clop, zsto, zout )
+
+         CALL histend( nid_V, snc4chunks=snc4set )
+
+         !                                                                                      !!! nid_W : 3D
+         CALL histdef( nid_W, "vovecrtz", "Vertical Velocity"                  , "m/s"    ,   &  ! wn
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         CALL histdef( nid_W, "votkeavt", "Vertical Eddy Diffusivity"          , "m2/s"   ,   &  ! avt
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         CALL histdef( nid_W, "votkeavm", "Vertical Eddy Viscosity"             , "m2/s"  ,   &  ! avm
+            &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+
+         IF( ln_zdfddm ) THEN
+            CALL histdef( nid_W,"voddmavs","Salt Vertical Eddy Diffusivity"    , "m2/s"   ,   &  ! avs
+               &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         ENDIF
+         
+         IF( ln_wave .AND. ln_sdw) THEN
+            CALL histdef( nid_W, "sdvecrtz", "Stokes Drift Vertical Current"   , "m/s"    ,   &  ! wsd
+               &          jpi, jpj, nh_W, ipk, 1, ipk, nz_W, 32, clop, zsto, zout )
+         ENDIF
+         !                                                                                      !!! nid_W : 2D
+         CALL histend( nid_W, snc4chunks=snc4set )
+
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'End of NetCDF Initialization'
+         IF(ll_print) CALL FLUSH(numout )
+
+      ENDIF
+
+      ! 2. Start writing data
+      ! ---------------------
+
+      ! ndex(1) est utilise ssi l'avant dernier argument est different de 
+      ! la taille du tableau en sortie. Dans ce cas , l'avant dernier argument
+      ! donne le nombre d'elements, et ndex la liste des indices a sortir
+
+      IF( lwp .AND. MOD( itmod, nn_write ) == 0 ) THEN 
+         WRITE(numout,*) 'dia_wri : write model outputs in NetCDF files at ', kt, 'time-step'
+         WRITE(numout,*) '~~~~~~ '
+      ENDIF
+
+      IF( .NOT.ln_linssh ) THEN
+         CALL histwrite( nid_T, "votemper", it, tsn(:,:,:,jp_tem) * e3t_n(:,:,:) , ndim_T , ndex_T  )   ! heat content
+         CALL histwrite( nid_T, "vosaline", it, tsn(:,:,:,jp_sal) * e3t_n(:,:,:) , ndim_T , ndex_T  )   ! salt content
+         CALL histwrite( nid_T, "sosstsst", it, tsn(:,:,1,jp_tem) * e3t_n(:,:,1) , ndim_hT, ndex_hT )   ! sea surface heat content
+         CALL histwrite( nid_T, "sosaline", it, tsn(:,:,1,jp_sal) * e3t_n(:,:,1) , ndim_hT, ndex_hT )   ! sea surface salinity content
+      ELSE
+         CALL histwrite( nid_T, "votemper", it, tsn(:,:,:,jp_tem) , ndim_T , ndex_T  )   ! temperature
+         CALL histwrite( nid_T, "vosaline", it, tsn(:,:,:,jp_sal) , ndim_T , ndex_T  )   ! salinity
+         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( .NOT.ln_linssh ) THEN
+         zw3d(:,:,:) = ( ( e3t_n(:,:,:) - e3t_0(:,:,:) ) / e3t_0(:,:,:) * 100 * tmask(:,:,:) ) ** 2
+         CALL histwrite( nid_T, "vovvle3t", it, e3t_n (:,:,:) , ndim_T , ndex_T  )   ! level thickness
+         CALL histwrite( nid_T, "vovvldep", it, gdept_n(:,:,:) , ndim_T , ndex_T  )   ! t-point depth
+         CALL histwrite( nid_T, "vovvldef", it, zw3d             , ndim_T , ndex_T  )   ! level thickness deformation
+      ENDIF
+      CALL histwrite( nid_T, "sossheig", it, sshn          , ndim_hT, ndex_hT )   ! sea surface height
+      CALL histwrite( nid_T, "sowaflup", it, ( emp-rnf )   , ndim_hT, ndex_hT )   ! upward water flux
+      CALL histwrite( nid_T, "sorunoff", it, rnf           , ndim_hT, ndex_hT )   ! river runoffs
+      CALL histwrite( nid_T, "sosfldow", it, sfx           , ndim_hT, ndex_hT )   ! downward salt flux 
+                                                                                  ! (includes virtual salt flux beneath ice 
+                                                                                  ! in linear free surface case)
+      IF( ln_linssh ) THEN
+         zw2d(:,:) = emp (:,:) * tsn(:,:,1,jp_tem)
+         CALL histwrite( nid_T, "sosst_cd", it, zw2d, ndim_hT, ndex_hT )          ! c/d term on sst
+         zw2d(:,:) = emp (:,:) * tsn(:,:,1,jp_sal)
+         CALL histwrite( nid_T, "sosss_cd", it, zw2d, ndim_hT, ndex_hT )          ! c/d term on sss
+      ENDIF
+      CALL histwrite( nid_T, "sohefldo", it, qns + qsr     , ndim_hT, ndex_hT )   ! total heat flux
+      CALL histwrite( nid_T, "soshfldo", it, qsr           , ndim_hT, ndex_hT )   ! solar heat flux
+      CALL histwrite( nid_T, "somixhgt", it, hmld          , ndim_hT, ndex_hT )   ! turbocline depth
+      CALL histwrite( nid_T, "somxl010", it, hmlp          , ndim_hT, ndex_hT )   ! mixed layer depth
+      CALL histwrite( nid_T, "soicecov", it, fr_i          , ndim_hT, ndex_hT )   ! ice fraction   
+      CALL histwrite( nid_T, "sowindsp", it, wndm          , ndim_hT, ndex_hT )   ! wind speed   
+!
+      IF( ln_icebergs ) THEN
+         !
+         CALL histwrite( nid_T, "calving"             , it, berg_grid%calving      , ndim_hT, ndex_hT )  
+         CALL histwrite( nid_T, "calving_heat"        , it, berg_grid%calving_hflx , ndim_hT, ndex_hT )         
+         CALL histwrite( nid_T, "berg_floating_melt"  , it, berg_grid%floating_melt, ndim_hT, ndex_hT )  
+         !
+         CALL histwrite( nid_T, "berg_stored_ice"     , it, berg_grid%stored_ice   , ndim_bT, ndex_bT )
+         !
+         IF( ln_bergdia ) THEN
+            CALL histwrite( nid_T, "berg_melt"           , it, berg_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_buoy_melt"      , it, buoy_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_eros_melt"      , it, eros_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_conv_melt"      , it, conv_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_virtual_area"   , it, virtual_area     , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_src"            , it, bits_src         , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_melt"           , it, bits_melt        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "bits_mass"           , it, bits_mass        , ndim_hT, ndex_hT   )  
+            CALL histwrite( nid_T, "berg_mass"           , it, berg_mass        , ndim_hT, ndex_hT   )  
+            !
+            CALL histwrite( nid_T, "berg_real_calving"   , it, real_calving     , ndim_bT, ndex_bT   )
+         ENDIF
+      ENDIF
+
+      IF( ln_ssr ) 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
+         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
+      CALL histwrite( nid_T, "sothedep", it, hth           , ndim_hT, ndex_hT )   ! depth of the thermocline
+      CALL histwrite( nid_T, "so20chgt", it, hd20          , ndim_hT, ndex_hT )   ! depth of the 20 isotherm
+      CALL histwrite( nid_T, "so28chgt", it, hd28          , ndim_hT, ndex_hT )   ! depth of the 28 isotherm
+      CALL histwrite( nid_T, "sohtc300", it, htc3          , ndim_hT, ndex_hT )   ! first 300m heaat content
+#endif
+
+      CALL histwrite( nid_U, "vozocrtx", it, un            , ndim_U , ndex_U )    ! i-current
+      CALL histwrite( nid_U, "sozotaux", it, utau          , ndim_hU, ndex_hU )   ! i-wind stress
+
+      CALL histwrite( nid_V, "vomecrty", it, vn            , ndim_V , ndex_V  )   ! j-current
+      CALL histwrite( nid_V, "sometauy", it, vtau          , ndim_hV, ndex_hV )   ! j-wind stress
+
+      CALL histwrite( nid_W, "vovecrtz", it, wn             , ndim_T, ndex_T )    ! vert. current
+      CALL histwrite( nid_W, "votkeavt", it, avt            , ndim_T, ndex_T )    ! T vert. eddy diff. coef.
+      CALL histwrite( nid_W, "votkeavm", it, avm            , ndim_T, ndex_T )    ! T vert. eddy visc. coef.
+      IF( ln_zdfddm ) THEN
+         CALL histwrite( nid_W, "voddmavs", it, avs         , ndim_T, ndex_T )    ! S vert. eddy diff. coef.
+      ENDIF
+
+      IF( ln_wave .AND. ln_sdw ) THEN
+         CALL histwrite( nid_U, "sdzocrtx", it, usd         , ndim_U , ndex_U )    ! i-StokesDrift-current
+         CALL histwrite( nid_V, "sdmecrty", it, vsd         , ndim_V , ndex_V )    ! j-StokesDrift-current
+         CALL histwrite( nid_W, "sdvecrtz", it, wsd         , ndim_T , ndex_T )    ! StokesDrift vert. current
+      ENDIF
+
+      ! 3. Close all files
+      ! ---------------------------------------
+      IF( kt == nitend ) THEN
+         CALL histclo( nid_T )
+         CALL histclo( nid_U )
+         CALL histclo( nid_V )
+         CALL histclo( nid_W )
+      ENDIF
+      !
+      IF( ln_timing )   CALL timing_stop('dia_wri')
+      !
+   END SUBROUTINE dia_wri
+#endif
+
+   SUBROUTINE dia_wri_state( cdfile_name )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE dia_wri_state  ***
+      !!        
+      !! ** Purpose :   create a NetCDF file named cdfile_name which contains 
+      !!      the instantaneous ocean state and forcing fields.
+      !!        Used to find errors in the initial state or save the last
+      !!      ocean state in case of abnormal end of a simulation
+      !!
+      !! ** Method  :   NetCDF files using ioipsl
+      !!      File 'output.init.nc'  is created if ninist = 1 (namelist)
+      !!      File 'output.abort.nc' is created in case of abnormal job end
+      !!----------------------------------------------------------------------
+      CHARACTER (len=* ), INTENT( in ) ::   cdfile_name      ! name of the file created
+      !!
+      INTEGER :: inum
+      !!----------------------------------------------------------------------
+      ! 
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dia_wri_state : single instantaneous ocean state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~   and forcing fields file created '
+      IF(lwp) WRITE(numout,*) '                and named :', cdfile_name, '...nc'
+
+#if defined key_si3
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE., kdlev = jpl )
+#else
+     CALL iom_open( TRIM(cdfile_name), inum, ldwrt = .TRUE. )
+#endif
+
+      CALL iom_rstput( 0, 0, inum, 'votemper', tsn(:,:,:,jp_tem) )    ! now temperature
+      CALL iom_rstput( 0, 0, inum, 'vosaline', tsn(:,:,:,jp_sal) )    ! now salinity
+      CALL iom_rstput( 0, 0, inum, 'sossheig', sshn              )    ! sea surface height
+      CALL iom_rstput( 0, 0, inum, 'vozocrtx', un                )    ! now i-velocity
+      CALL iom_rstput( 0, 0, inum, 'vomecrty', vn                )    ! now j-velocity
+      CALL iom_rstput( 0, 0, inum, 'vovecrtz', wn                )    ! now k-velocity
+      IF( ALLOCATED(ahtu) ) THEN
+         CALL iom_rstput( 0, 0, inum,  'ahtu', ahtu              )    ! aht at u-point
+         CALL iom_rstput( 0, 0, inum,  'ahtv', ahtv              )    ! aht at v-point
+      ENDIF
+      IF( ALLOCATED(ahmt) ) THEN
+         CALL iom_rstput( 0, 0, inum,  'ahmt', ahmt              )    ! ahmt at u-point
+         CALL iom_rstput( 0, 0, inum,  'ahmf', ahmf              )    ! ahmf at v-point
+      ENDIF
+      CALL iom_rstput( 0, 0, inum, 'sowaflup', emp - rnf         )    ! freshwater budget
+      CALL iom_rstput( 0, 0, inum, 'sohefldo', qsr + qns         )    ! total heat flux
+      CALL iom_rstput( 0, 0, inum, 'soshfldo', qsr               )    ! solar heat flux
+      CALL iom_rstput( 0, 0, inum, 'soicecov', fr_i              )    ! ice fraction
+      CALL iom_rstput( 0, 0, inum, 'sozotaux', utau              )    ! i-wind stress
+      CALL iom_rstput( 0, 0, inum, 'sometauy', vtau              )    ! j-wind stress
+      IF(  .NOT.ln_linssh  ) THEN             
+         CALL iom_rstput( 0, 0, inum, 'vovvldep', gdept_n        )    !  T-cell depth 
+         CALL iom_rstput( 0, 0, inum, 'vovvle3t', e3t_n          )    !  T-cell thickness  
+      END IF
+      IF( ln_wave .AND. ln_sdw ) THEN
+         CALL iom_rstput( 0, 0, inum, 'sdzocrtx', usd            )    ! now StokesDrift i-velocity
+         CALL iom_rstput( 0, 0, inum, 'sdmecrty', vsd            )    ! now StokesDrift j-velocity
+         CALL iom_rstput( 0, 0, inum, 'sdvecrtz', wsd            )    ! now StokesDrift k-velocity
+      ENDIF
+ 
+#if defined key_si3
+      IF( nn_ice == 2 ) THEN   ! condition needed in case agrif + ice-model but no-ice in child grid
+         CALL ice_wri_state( inum )
+      ENDIF
+#endif
+      !
+      CALL iom_close( inum )
+      ! 
+   END SUBROUTINE dia_wri_state
+
+   !!======================================================================
+END MODULE diawri
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/domvvl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/domvvl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/domvvl.F90	(revision 14097)
@@ -0,0 +1,1053 @@
+MODULE domvvl
+   !!======================================================================
+   !!                       ***  MODULE domvvl   ***
+   !! Ocean : 
+   !!======================================================================
+   !! History :  2.0  !  2006-06  (B. Levier, L. Marie)  original code
+   !!            3.1  !  2009-02  (G. Madec, M. Leclair, R. Benshila)  pure z* coordinate
+   !!            3.3  !  2011-10  (M. Leclair) totally rewrote domvvl: vvl option includes z_star and z_tilde coordinates
+   !!            3.6  !  2014-11  (P. Mathiot) add ice shelf capability
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_vvl_init     : define initial vertical scale factors, depths and column thickness
+   !!   dom_vvl_sf_nxt   : Compute next vertical scale factors
+   !!   dom_vvl_sf_swp   : Swap vertical scale factors and update the vertical grid
+   !!   dom_vvl_interpol : Interpolate vertical scale factors from one grid point to another
+   !!   dom_vvl_rst      : read/write restart file
+   !!   dom_vvl_ctl      : Check the vvl options
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE phycst          ! physical constant
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! ocean surface boundary condition
+   USE wet_dry         ! wetting and drying
+   USE usrdef_istate   ! user defined initial state (wad only)
+   USE restart         ! ocean restart
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distributed memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC  dom_vvl_init       ! called by domain.F90
+   PUBLIC  dom_vvl_sf_nxt     ! called by step.F90
+   PUBLIC  dom_vvl_sf_swp     ! called by step.F90
+   PUBLIC  dom_vvl_interpol   ! called by dynnxt.F90
+
+   !                                                      !!* Namelist nam_vvl
+   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 = .FALSE.                ! debug control prints
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: un_td, vn_td                ! thickness diffusion transport
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: hdiv_lf                     ! low frequency part of hz divergence
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_b, tilde_e3t_n    ! baroclinic scale factors
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_a, dtilde_e3t_a   ! baroclinic scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_e3t                 ! retoring period for scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_hdv                 ! retoring period for low freq. divergence
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dom_vvl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION dom_vvl_alloc  ***
+      !!----------------------------------------------------------------------
+      IF( ln_vvl_zstar )   dom_vvl_alloc = 0
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         ALLOCATE( tilde_e3t_b(jpi,jpj,jpk)  , tilde_e3t_n(jpi,jpj,jpk) , tilde_e3t_a(jpi,jpj,jpk) ,   &
+            &      dtilde_e3t_a(jpi,jpj,jpk) , un_td  (jpi,jpj,jpk)     , vn_td  (jpi,jpj,jpk)     ,   &
+            &      STAT = dom_vvl_alloc        )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+         un_td = 0._wp
+         vn_td = 0._wp
+      ENDIF
+      IF( ln_vvl_ztilde ) THEN
+         ALLOCATE( frq_rst_e3t(jpi,jpj) , frq_rst_hdv(jpi,jpj) , hdiv_lf(jpi,jpj,jpk) , STAT= dom_vvl_alloc )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+      ENDIF
+      !
+   END FUNCTION dom_vvl_alloc
+
+
+   SUBROUTINE dom_vvl_init
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_init  ***
+      !!                   
+      !! ** Purpose :  Initialization of all scale factors, depths
+      !!               and water column heights
+      !!
+      !! ** Method  :  - use restart file and/or initialize
+      !!               - interpolate scale factors
+      !!
+      !! ** Action  : - e3t_(n/b) and tilde_e3t_(n/b)
+      !!              - Regrid: e3(u/v)_n
+      !!                        e3(u/v)_b       
+      !!                        e3w_n           
+      !!                        e3(u/v)w_b      
+      !!                        e3(u/v)w_n      
+      !!                        gdept_n, gdepw_n and gde3w_n
+      !!              - h(t/u/v)_0
+      !!              - frq_rst_e3t and frq_rst_hdv
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   ii0, ii1, ij0, ij1
+      REAL(wp)::   zcoef
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dom_vvl_init : Variable volume activated'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      !
+      CALL dom_vvl_ctl     ! choose vertical coordinate (z_star, z_tilde or layer)
+      !
+      !                    ! Allocate module arrays
+      IF( dom_vvl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_init : unable to allocate arrays' )
+      !
+      !                    ! Read or initialize e3t_(b/n), tilde_e3t_(b/n) and hdiv_lf
+      CALL dom_vvl_rst( nit000, 'READ' )
+      e3t_a(:,:,jpk) = e3t_0(:,:,jpk)  ! last level always inside the sea floor set one for all
+      !
+      !                    !== Set of all other vertical scale factors  ==!  (now and before)
+      !                                ! Horizontal interpolation of e3t
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )    ! from T to U
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )    ! from T to V 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )    ! from U to F
+      !                                ! Vertical interpolation of e3t,u,v 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )  ! from T to W
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3w_b (:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )  ! from U to UW
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )  ! from V to UW
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! We need to define e3[tuv]_a for AGRIF initialisation (should not be a problem for the restartability...)
+      e3t_a(:,:,:) = e3t_n(:,:,:)
+      e3u_a(:,:,:) = e3u_n(:,:,:)
+      e3v_a(:,:,:) = e3v_n(:,:,:)
+      !
+      !                    !==  depth of t and w-point  ==!   (set the isf depth as it is in the initial timestep)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)       ! reference to the ocean surface (used for MLD and light penetration)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)  ! reference to a common level z=0 for hpg
+      gdept_b(:,:,1) = 0.5_wp * e3w_b(:,:,1)
+      gdepw_b(:,:,1) = 0.0_wp
+      DO jk = 2, jpk                               ! vertical sum
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               !    zcoef = tmask - wmask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+               !                             ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
+               !                             ! 0.5 where jk = mikt     
+!!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
+               zcoef = ( tmask(ji,jj,jk) - wmask(ji,jj,jk) )
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk)) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+               gdepw_b(ji,jj,jk) = gdepw_b(ji,jj,jk-1) + e3t_b(ji,jj,jk-1)
+               gdept_b(ji,jj,jk) =      zcoef  * ( gdepw_b(ji,jj,jk  ) + 0.5 * e3w_b(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_b(ji,jj,jk-1) +       e3w_b(ji,jj,jk)) 
+            END DO
+         END DO
+      END DO
+      !
+      !                    !==  thickness of the water column  !!   (ocean portion only)
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)   !!gm  BUG  :  this should be 1/2 * e3w(k=1) ....
+      hu_b(:,:) = e3u_b(:,:,1) * umask(:,:,1)
+      hu_n(:,:) = e3u_n(:,:,1) * umask(:,:,1)
+      hv_b(:,:) = e3v_b(:,:,1) * vmask(:,:,1)
+      hv_n(:,:) = e3v_n(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         hu_b(:,:) = hu_b(:,:) + e3u_b(:,:,jk) * umask(:,:,jk)
+         hu_n(:,:) = hu_n(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+         hv_b(:,:) = hv_b(:,:) + e3v_b(:,:,jk) * vmask(:,:,jk)
+         hv_n(:,:) = hv_n(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !
+      !                    !==  inverse of water column thickness   ==!   (u- and v- points)
+      r1_hu_b(:,:) = ssumask(:,:) / ( hu_b(:,:) + 1._wp - ssumask(:,:) )    ! _i mask due to ISF
+      r1_hu_n(:,:) = ssumask(:,:) / ( hu_n(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_b(:,:) = ssvmask(:,:) / ( hv_b(:,:) + 1._wp - ssvmask(:,:) )
+      r1_hv_n(:,:) = ssvmask(:,:) / ( hv_n(:,:) + 1._wp - ssvmask(:,:) )
+
+      !                    !==   z_tilde coordinate case  ==!   (Restoring frequencies)
+      IF( ln_vvl_ztilde ) THEN
+!!gm : idea: add here a READ in a file of custumized restoring frequency
+         !                                   ! Values in days provided via the namelist
+         !                                   ! use rsmall to avoid possible division by zero errors with faulty settings
+         frq_rst_e3t(:,:) = 2._wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.0_wp )
+         frq_rst_hdv(:,:) = 2._wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.0_wp )
+         !
+         IF( ln_vvl_ztilde_as_zstar ) THEN   ! z-star emulation using z-tile
+            frq_rst_e3t(:,:) = 0._wp               !Ignore namelist settings
+            frq_rst_hdv(:,:) = 1._wp / rdt
+         ENDIF
+         IF ( ln_vvl_zstar_at_eqtor ) THEN   ! use z-star in vicinity of the Equator
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+!!gm  case |gphi| >= 6 degrees is useless   initialized just above by default
+                  IF( ABS(gphit(ji,jj)) >= 6.) THEN
+                     ! values outside the equatorial band and transition zone (ztilde)
+                     frq_rst_e3t(ji,jj) =  2.0_wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.e0_wp )
+                     frq_rst_hdv(ji,jj) =  2.0_wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.e0_wp )
+                  ELSEIF( ABS(gphit(ji,jj)) <= 2.5) THEN    ! Equator strip ==> z-star
+                     ! values inside the equatorial band (ztilde as zstar)
+                     frq_rst_e3t(ji,jj) =  0.0_wp
+                     frq_rst_hdv(ji,jj) =  1.0_wp / rdt
+                  ELSE                                      ! transition band (2.5 to 6 degrees N/S)
+                     !                                      ! (linearly transition from z-tilde to z-star)
+                     frq_rst_e3t(ji,jj) = 0.0_wp + (frq_rst_e3t(ji,jj)-0.0_wp)*0.5_wp   &
+                        &            * (  1.0_wp - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                     frq_rst_hdv(ji,jj) = (1.0_wp / rdt)                                &
+                        &            + (  frq_rst_hdv(ji,jj)-(1.e0_wp / rdt) )*0.5_wp   &
+                        &            * (  1._wp  - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                  ENDIF
+               END DO
+            END DO
+            IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
+               IF( nn_cfg == 3 ) THEN   ! ORCA2: Suppress ztilde in the Foxe Basin for ORCA2
+                  ii0 = 103   ;   ii1 = 111       
+                  ij0 = 128   ;   ij1 = 135   ;   
+                  frq_rst_e3t( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  0.0_wp
+                  frq_rst_hdv( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  1.e0_wp / rdt
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF(lwxios) THEN
+! define variables in restart file when writing with XIOS
+         CALL iom_set_rstw_var_active('e3t_b')
+         CALL iom_set_rstw_var_active('e3t_n')
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_set_rstw_var_active('tilde_e3t_b')
+            CALL iom_set_rstw_var_active('tilde_e3t_n')
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_set_rstw_var_active('hdiv_lf')
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_init
+
+
+   SUBROUTINE dom_vvl_sf_nxt( kt, kcall ) 
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_nxt  ***
+      !!                   
+      !! ** Purpose :  - compute the after scale factors used in tra_zdf, dynnxt,
+      !!                 tranxt and dynspg routines
+      !!
+      !! ** Method  :  - z_star case:  Repartition of ssh INCREMENT proportionnaly to the level thickness.
+      !!               - z_tilde_case: after scale factor increment = 
+      !!                                    high frequency part of horizontal divergence
+      !!                                  + retsoring towards the background grid
+      !!                                  + thickness difusion
+      !!                               Then repartition of ssh INCREMENT proportionnaly
+      !!                               to the "baroclinic" level thickness.
+      !!
+      !! ** Action  :  - hdiv_lf    : restoring towards full baroclinic divergence in z_tilde case
+      !!               - tilde_e3t_a: after increment of vertical scale factor 
+      !!                              in z_tilde case
+      !!               - e3(t/u/v)_a
+      !!
+      !! Reference  : Leclair, M., and Madec, G. 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )           ::   kt      ! time step
+      INTEGER, INTENT( in ), OPTIONAL ::   kcall   ! optional argument indicating call sequence
+      !
+      INTEGER                ::   ji, jj, jk            ! dummy loop indices
+      INTEGER , DIMENSION(3) ::   ijk_max, ijk_min      ! temporary integers
+      REAL(wp)               ::   z2dt, z_tmin, z_tmax  ! local scalars
+      LOGICAL                ::   ll_do_bclinic         ! local logical
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zht, z_scale, zwu, zwv, zhdiv
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ze3t
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_nxt')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_nxt : compute after scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'
+      ENDIF
+
+      ll_do_bclinic = .TRUE.
+      IF( PRESENT(kcall) ) THEN
+         IF( kcall == 2 .AND. ln_vvl_ztilde )   ll_do_bclinic = .FALSE.
+      ENDIF
+
+      ! ******************************* !
+      ! After acale factors at t-points !
+      ! ******************************* !
+      !                                                ! --------------------------------------------- !
+      !                                                ! z_star coordinate and barotropic z-tilde part !
+      !                                                ! --------------------------------------------- !
+      !
+      z_scale(:,:) = ( ssha(:,:) - sshb(:,:) ) * ssmask(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+      DO jk = 1, jpkm1
+         ! formally this is the same as e3t_a = e3t_0*(1+ssha/ht_0)
+         e3t_a(:,:,jk) = e3t_b(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+      END DO
+      !
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer .AND. ll_do_bclinic ) THEN   ! z_tilde or layer coordinate !
+         !                                                            ! ------baroclinic part------ !
+         ! I - initialization
+         ! ==================
+
+         ! 1 - barotropic divergence
+         ! -------------------------
+         zhdiv(:,:) = 0._wp
+         zht(:,:)   = 0._wp
+         DO jk = 1, jpkm1
+            zhdiv(:,:) = zhdiv(:,:) + e3t_n(:,:,jk) * hdivn(:,:,jk)
+            zht  (:,:) = zht  (:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         zhdiv(:,:) = zhdiv(:,:) / ( zht(:,:) + 1. - tmask_i(:,:) )
+
+         ! 2 - Low frequency baroclinic horizontal divergence  (z-tilde case only)
+         ! --------------------------------------------------
+         IF( ln_vvl_ztilde ) THEN
+            IF( kt > nit000 ) THEN
+               DO jk = 1, jpkm1
+                  hdiv_lf(:,:,jk) = hdiv_lf(:,:,jk) - rdt * frq_rst_hdv(:,:)   &
+                     &          * ( hdiv_lf(:,:,jk) - e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) )
+               END DO
+            ENDIF
+         ENDIF
+
+         ! II - after z_tilde increments of vertical scale factors
+         ! =======================================================
+         tilde_e3t_a(:,:,:) = 0._wp  ! tilde_e3t_a used to store tendency terms
+
+         ! 1 - High frequency divergence term
+         ! ----------------------------------
+         IF( ln_vvl_ztilde ) THEN     ! z_tilde case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - ( e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) - hdiv_lf(:,:,jk) )
+            END DO
+         ELSE                         ! layer case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) -   e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) * tmask(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 2 - Restoring term (z-tilde case only)
+         ! ------------------
+         IF( ln_vvl_ztilde ) THEN
+            DO jk = 1, jpk
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - frq_rst_e3t(:,:) * tilde_e3t_b(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 3 - Thickness diffusion term
+         ! ----------------------------
+         zwu(:,:) = 0._wp
+         zwv(:,:) = 0._wp
+         DO jk = 1, jpkm1        ! a - first derivative: diffusive fluxes
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  un_td(ji,jj,jk) = rn_ahe3 * umask(ji,jj,jk) * e2_e1u(ji,jj)           &
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji+1,jj  ,jk) )
+                  vn_td(ji,jj,jk) = rn_ahe3 * vmask(ji,jj,jk) * e1_e2v(ji,jj)           & 
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji  ,jj+1,jk) )
+                  zwu(ji,jj) = zwu(ji,jj) + un_td(ji,jj,jk)
+                  zwv(ji,jj) = zwv(ji,jj) + vn_td(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         DO jj = 1, jpj          ! b - correction for last oceanic u-v points
+            DO ji = 1, jpi
+               un_td(ji,jj,mbku(ji,jj)) = un_td(ji,jj,mbku(ji,jj)) - zwu(ji,jj)
+               vn_td(ji,jj,mbkv(ji,jj)) = vn_td(ji,jj,mbkv(ji,jj)) - zwv(ji,jj)
+            END DO
+         END DO
+         DO jk = 1, jpkm1        ! c - second derivative: divergence of diffusive fluxes
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  tilde_e3t_a(ji,jj,jk) = tilde_e3t_a(ji,jj,jk) + (   un_td(ji-1,jj  ,jk) - un_td(ji,jj,jk)    &
+                     &                                          +     vn_td(ji  ,jj-1,jk) - vn_td(ji,jj,jk)    &
+                     &                                            ) * r1_e1e2t(ji,jj)
+               END DO
+            END DO
+         END DO
+         !                       ! d - thickness diffusion transport: boundary conditions
+         !                             (stored for tracer advction and continuity equation)
+         CALL lbc_lnk_multi( 'domvvl', un_td , 'U' , -1._wp, vn_td , 'V' , -1._wp)
+
+         ! 4 - Time stepping of baroclinic scale factors
+         ! ---------------------------------------------
+         ! Leapfrog time stepping
+         ! ~~~~~~~~~~~~~~~~~~~~~~
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            z2dt =  rdt
+         ELSE
+            z2dt = 2.0_wp * rdt
+         ENDIF
+         CALL lbc_lnk( 'domvvl', tilde_e3t_a(:,:,:), 'T', 1._wp )
+         tilde_e3t_a(:,:,:) = tilde_e3t_b(:,:,:) + z2dt * tmask(:,:,:) * tilde_e3t_a(:,:,:)
+
+         ! Maximum deformation control
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         ze3t(:,:,jpk) = 0._wp
+         DO jk = 1, jpkm1
+            ze3t(:,:,jk) = tilde_e3t_a(:,:,jk) / e3t_0(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:)
+         END DO
+         z_tmax = MAXVAL( ze3t(:,:,:) )
+         CALL mpp_max( 'domvvl', z_tmax )                 ! max over the global domain
+         z_tmin = MINVAL( ze3t(:,:,:) )
+         CALL mpp_min( 'domvvl', z_tmin )                 ! min over the global domain
+         ! - ML - test: for the moment, stop simulation for too large e3_t variations
+         IF( ( z_tmax >  rn_zdef_max ) .OR. ( z_tmin < - rn_zdef_max ) ) THEN
+            IF( lk_mpp ) THEN
+               CALL mpp_maxloc( 'domvvl', ze3t, tmask, z_tmax, ijk_max )
+               CALL mpp_minloc( 'domvvl', ze3t, tmask, z_tmin, ijk_min )
+            ELSE
+               ijk_max = MAXLOC( ze3t(:,:,:) )
+               ijk_max(1) = ijk_max(1) + nimpp - 1
+               ijk_max(2) = ijk_max(2) + njmpp - 1
+               ijk_min = MINLOC( ze3t(:,:,:) )
+               ijk_min(1) = ijk_min(1) + nimpp - 1
+               ijk_min(2) = ijk_min(2) + njmpp - 1
+            ENDIF
+            IF (lwp) THEN
+               WRITE(numout, *) 'MAX( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmax
+               WRITE(numout, *) 'at i, j, k=', ijk_max
+               WRITE(numout, *) 'MIN( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmin
+               WRITE(numout, *) 'at i, j, k=', ijk_min            
+               CALL ctl_stop( 'STOP', 'MAX( ABS( tilde_e3t_a(:,:,: ) ) / e3t_0(:,:,:) ) too high')
+            ENDIF
+         ENDIF
+         ! - ML - end test
+         ! - ML - Imposing these limits will cause a baroclinicity error which is corrected for below
+         tilde_e3t_a(:,:,:) = MIN( tilde_e3t_a(:,:,:),   rn_zdef_max * e3t_0(:,:,:) )
+         tilde_e3t_a(:,:,:) = MAX( tilde_e3t_a(:,:,:), - rn_zdef_max * e3t_0(:,:,:) )
+
+         !
+         ! "tilda" change in the after scale factor
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - tilde_e3t_b(:,:,jk)
+         END DO
+         ! III - Barotropic repartition of the sea surface height over the baroclinic profile
+         ! ==================================================================================
+         ! add ( ssh increment + "baroclinicity error" ) proportionly to e3t(n)
+         ! - ML - baroclinicity error should be better treated in the future
+         !        i.e. locally and not spread over the water column.
+         !        (keep in mind that the idea is to reduce Eulerian velocity as much as possible)
+         zht(:,:) = 0.
+         DO jk = 1, jpkm1
+            zht(:,:)  = zht(:,:) + tilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_scale(:,:) =  - zht(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = dtilde_e3t_a(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+         END DO
+
+      ENDIF
+
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer )  THEN   ! z_tilde or layer coordinate !
+      !                                           ! ---baroclinic part--------- !
+         DO jk = 1, jpkm1
+            e3t_a(:,:,jk) = e3t_a(:,:,jk) + dtilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+      ENDIF
+
+      IF( ln_vvl_dbg .AND. .NOT. ll_do_bclinic ) THEN   ! - ML - test: control prints for debuging
+         !
+         IF( lwp ) WRITE(numout, *) 'kt =', kt
+         IF ( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+            z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( zht(:,:) ) )
+            CALL mpp_max( 'domvvl', z_tmax )                             ! max over the global domain
+            IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(SUM(tilde_e3t_a))) =', z_tmax
+         END IF
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshn(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshn-SUM(e3t_n))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + ssha(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+ssha-SUM(e3t_a))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_b(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshb(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshb-SUM(e3t_b))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshb(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshb))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshn(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshn))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( ssha(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ssha))) =', z_tmax
+      END IF
+
+      ! *********************************** !
+      ! After scale factors at u- v- points !
+      ! *********************************** !
+
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3u_a(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3v_a(:,:,:), 'V' )
+
+      ! *********************************** !
+      ! After depths at u- v points         !
+      ! *********************************** !
+
+      hu_a(:,:) = e3u_a(:,:,1) * umask(:,:,1)
+      hv_a(:,:) = e3v_a(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         hu_a(:,:) = hu_a(:,:) + e3u_a(:,:,jk) * umask(:,:,jk)
+         hv_a(:,:) = hv_a(:,:) + e3v_a(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !                                        ! Inverse of the local depth
+!!gm BUG ?  don't understand the use of umask_i here .....
+      r1_hu_a(:,:) = ssumask(:,:) / ( hu_a(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_a(:,:) = ssvmask(:,:) / ( hv_a(:,:) + 1._wp - ssvmask(:,:) )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_nxt')
+      !
+   END SUBROUTINE dom_vvl_sf_nxt
+
+
+   SUBROUTINE dom_vvl_sf_swp( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_swp  ***
+      !!                   
+      !! ** Purpose :  compute time filter and swap of scale factors 
+      !!               compute all depths and related variables for next time step
+      !!               write outputs and restart file
+      !!
+      !! ** Method  :  - swap of e3t with trick for volume/tracer conservation
+      !!               - reconstruct scale factor at other grid points (interpolate)
+      !!               - recompute depths and water height fields
+      !!
+      !! ** Action  :  - e3t_(b/n), tilde_e3t_(b/n) and e3(u/v)_n ready for next time step
+      !!               - Recompute:
+      !!                    e3(u/v)_b       
+      !!                    e3w_n           
+      !!                    e3(u/v)w_b      
+      !!                    e3(u/v)w_n      
+      !!                    gdept_n, gdepw_n  and gde3w_n
+      !!                    h(u/v) and h(u/v)r
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!              Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcoef        ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_swp')
+      !
+      IF( kt == nit000 )   THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_swp : - time filter and swap of scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   - interpolate scale factors and compute depths for next time step'
+      ENDIF
+      !
+      ! Time filter and swap of scale factors
+      ! =====================================
+      ! - ML - e3(t/u/v)_b are allready computed in dynnxt.
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:)
+         ELSE
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:) & 
+            &         + atfp * ( tilde_e3t_b(:,:,:) - 2.0_wp * tilde_e3t_n(:,:,:) + tilde_e3t_a(:,:,:) )
+         ENDIF
+         tilde_e3t_n(:,:,:) = tilde_e3t_a(:,:,:)
+      ENDIF
+      gdept_b(:,:,:) = gdept_n(:,:,:)
+      gdepw_b(:,:,:) = gdepw_n(:,:,:)
+
+      e3t_n(:,:,:) = e3t_a(:,:,:)
+      e3u_n(:,:,:) = e3u_a(:,:,:)
+      e3v_n(:,:,:) = e3v_a(:,:,:)
+
+      ! Compute all missing vertical scale factor and depths
+      ! ====================================================
+      ! Horizontal scale factor interpolations
+      ! --------------------------------------
+      ! - ML - e3u_b and e3v_b are allready computed in dynnxt
+      ! - JC - hu_b, hv_b, hur_b, hvr_b also
+      
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F'  )
+      
+      ! Vertical scale factor interpolations
+      CALL dom_vvl_interpol( e3t_n(:,:,:),  e3w_n(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:),  e3w_b(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! t- and w- points depth (set the isf depth as it is in the initial step)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+      DO jk = 2, jpk
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+              !    zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))   ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+                                                                 ! 1 for jk = mikt
+               zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =    zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk) )  &
+                   &             + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk) ) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+            END DO
+         END DO
+      END DO
+
+      ! Local depth and Inverse of the local depth of the water
+      ! -------------------------------------------------------
+      hu_n(:,:) = hu_a(:,:)   ;   r1_hu_n(:,:) = r1_hu_a(:,:)
+      hv_n(:,:) = hv_a(:,:)   ;   r1_hv_n(:,:) = r1_hv_a(:,:)
+      !
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+
+      ! write restart file
+      ! ==================
+      IF( lrst_oce  )   CALL dom_vvl_rst( kt, 'WRITE' )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_swp')
+      !
+   END SUBROUTINE dom_vvl_sf_swp
+
+
+   SUBROUTINE dom_vvl_interpol( pe3_in, pe3_out, pout )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl__interpol  ***
+      !!
+      !! ** Purpose :   interpolate scale factors from one grid point to another
+      !!
+      !! ** Method  :   e3_out = e3_0 + interpolation(e3_in - e3_0)
+      !!                - horizontal interpolation: grid cell surface averaging
+      !!                - vertical interpolation: simple averaging
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::  pe3_in    ! input e3 to be interpolated
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::  pe3_out   ! output interpolated e3
+      CHARACTER(LEN=*)                , INTENT(in   ) ::  pout      ! grid point of out scale factors
+      !                                                             !   =  'U', 'V', 'W, 'F', 'UW' or 'VW'
+      !
+      INTEGER ::   ji, jj, jk                                       ! dummy loop indices
+      REAL(wp) ::  zlnwd                                            ! =1./0. when ln_wd_il = T/F
+      !!----------------------------------------------------------------------
+      !
+      IF(ln_wd_il) THEN
+        zlnwd = 1.0_wp
+      ELSE
+        zlnwd = 0.0_wp
+      END IF
+      !
+      SELECT CASE ( pout )    !==  type of interpolation  ==!
+         !
+      CASE( 'U' )                   !* from T- to U-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2u(ji,jj)   &
+                     &                       * (   e1e2t(ji  ,jj) * ( pe3_in(ji  ,jj,jk) - e3t_0(ji  ,jj,jk) )     &
+                     &                           + e1e2t(ji+1,jj) * ( pe3_in(ji+1,jj,jk) - e3t_0(ji+1,jj,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'U', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3u_0(:,:,:)
+         !
+      CASE( 'V' )                   !* from T- to V-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * ( vmask(ji,jj,jk)  * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2v(ji,jj)   &
+                     &                       * (   e1e2t(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3t_0(ji,jj  ,jk) )     &
+                     &                           + e1e2t(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3t_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'V', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3v_0(:,:,:)
+         !
+      CASE( 'F' )                   !* from U-point to F-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * umask(ji,jj+1,jk) * (1.0_wp - zlnwd) + zlnwd ) &
+                     &                       *    r1_e1e2f(ji,jj)                                                  &
+                     &                       * (   e1e2u(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3u_0(ji,jj  ,jk) )     &
+                     &                           + e1e2u(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3u_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'F', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3f_0(:,:,:)
+         !
+      CASE( 'W' )                   !* from T- to W-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3w_0(:,:,1) + pe3_in(:,:,1) - e3t_0(:,:,1)
+         ! - ML - The use of mask in this formulea enables the special treatment of the last w-point without indirect adressing
+!!gm BUG? use here wmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3w_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )   &
+               &                            * ( pe3_in(:,:,jk-1) - e3t_0(:,:,jk-1) )                               &
+               &                            +            0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )     &
+               &                            * ( pe3_in(:,:,jk  ) - e3t_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'UW' )                  !* from U- to UW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3uw_0(:,:,1) + pe3_in(:,:,1) - e3u_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wumask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3uw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3u_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3u_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'VW' )                  !* from V- to VW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3vw_0(:,:,1) + pe3_in(:,:,1) - e3v_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wvmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3vw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3v_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3v_0(:,:,jk  ) )
+         END DO
+      END SELECT
+      !
+   END SUBROUTINE dom_vvl_interpol
+
+
+   SUBROUTINE dom_vvl_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dom_vvl_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write VVL file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain vertical scale factors,
+      !!                they are set to the _0 values
+      !!                if the restart does not contain vertical scale factors increments (z_tilde),
+      !!                they are set to 0.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   id1, id2, id3, id4, id5     ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ===============
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            CALL rst_read_open                  !  open the restart file if necessary
+            CALL iom_get( numror, jpdom_autoglo, 'sshn'   , sshn, ldxios = lrxios    )
+            !
+            id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'e3t_n', ldstop = .FALSE. )
+            id3 = iom_varid( numror, 'tilde_e3t_b', ldstop = .FALSE. )
+            id4 = iom_varid( numror, 'tilde_e3t_n', ldstop = .FALSE. )
+            id5 = iom_varid( numror, 'hdiv_lf', ldstop = .FALSE. )
+            !                             ! --------- !
+            !                             ! all cases !
+            !                             ! --------- !
+            IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               ! needed to restart if land processor not computed 
+               IF(lwp) write(numout,*) 'dom_vvl_rst : e3t_b and e3t_n found in restart files'
+               WHERE ( tmask(:,:,:) == 0.0_wp ) 
+                  e3t_n(:,:,:) = e3t_0(:,:,:)
+                  e3t_b(:,:,:) = e3t_0(:,:,:)
+               END WHERE
+               IF( neuler == 0 ) THEN
+                  e3t_b(:,:,:) = e3t_n(:,:,:)
+               ENDIF
+            ELSE IF( id1 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               e3t_n(:,:,:) = e3t_b(:,:,:)
+               neuler = 0
+            ELSE IF( id2 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_b not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ELSE
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart file'
+               IF(lwp) write(numout,*) 'Compute scale factor from sshn'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:) ) &
+                      &                          / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                      &          + e3t_0(:,:,jk)                               * (1._wp -tmask(:,:,jk))
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ENDIF
+            !                             ! ----------- !
+            IF( ln_vvl_zstar ) THEN       ! z_star case !
+               !                          ! ----------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN
+                  CALL ctl_stop( 'dom_vvl_rst: z_star cannot restart from a z_tilde or layer run' )
+               ENDIF
+               !                          ! ----------------------- !
+            ELSE                          ! z_tilde and layer cases !
+               !                          ! ----------------------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+               ELSE                            ! one at least array is missing
+                  tilde_e3t_b(:,:,:) = 0.0_wp
+                  tilde_e3t_n(:,:,:) = 0.0_wp
+               ENDIF
+               !                          ! ------------ !
+               IF( ln_vvl_ztilde ) THEN   ! z_tilde case !
+                  !                       ! ------------ !
+                  IF( id5 > 0 ) THEN  ! required array exists
+                     CALL iom_get( numror, jpdom_autoglo, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                  ELSE                ! array is missing
+                     hdiv_lf(:,:,:) = 0.0_wp
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+         ELSE                                   !* Initialize at "rest"
+            !
+
+            IF( ll_wd ) THEN   ! MJB ll_wd edits start here - these are essential 
+               !
+               IF( cn_cfg == 'wad' ) THEN
+                  ! Wetting and drying test case
+                  CALL usr_def_istate( gdept_b, tmask, tsb, ub, vb, sshb  )
+                  tsn  (:,:,:,:) = tsb (:,:,:,:)       ! set now values from to before ones
+                  sshn (:,:)     = sshb(:,:)
+                  un   (:,:,:)   = ub  (:,:,:)
+                  vn   (:,:,:)   = vb  (:,:,:)
+               ELSE
+                  ! if not test case
+                  sshn(:,:) = -ssh_ref
+                  sshb(:,:) = -ssh_ref
+
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        IF( ht_0(ji,jj)-ssh_ref <  rn_wdmin1 ) THEN ! if total depth is less than min depth
+
+                           sshb(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           sshn(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           ssha(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDIF !If test case else
+
+               ! Adjust vertical metrics for all wad
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:)  ) &
+                    &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                    &            + e3t_0(:,:,jk) * ( 1._wp - tmask(:,:,jk) )
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     IF ( ht_0(ji,jj) .LE. 0.0 .AND. NINT( ssmask(ji,jj) ) .EQ. 1) THEN
+                       CALL ctl_stop( 'dom_vvl_rst: ht_0 must be positive at potentially wet points' )
+                     ENDIF
+                  END DO 
+               END DO 
+               !
+            ELSE
+               !
+               ! usr_def_istate called here only to get sshb, that is needed to initialize e3t_b and e3t_n
+               CALL usr_def_istate( gdept_0, tmask, tsb, ub, vb, sshb  )  
+               ! usr_def_istate will be called again in istate_init to initialize ts(bn), ssh(bn), u(bn) and v(bn)
+               !
+               DO jk=1,jpk
+                  e3t_b(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshb(:,:) ) &
+                    &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                    &            + e3t_0(:,:,jk) * ( 1._wp - tmask(:,:,jk) )   ! make sure e3t_b != 0 on land points
+               END DO
+               e3t_n(:,:,:) = e3t_b(:,:,:)
+               sshn(:,:) = sshb(:,:)   ! needed later for gde3w
+!!$                e3t_n(:,:,:)=e3t_0(:,:,:)
+!!$                e3t_b(:,:,:)=e3t_0(:,:,:)
+               !
+            END IF           ! end of ll_wd edits
+
+            IF( ln_vvl_ztilde .OR. ln_vvl_layer) THEN
+               tilde_e3t_b(:,:,:) = 0._wp
+               tilde_e3t_n(:,:,:) = 0._wp
+               IF( ln_vvl_ztilde ) hdiv_lf(:,:,:) = 0._wp
+            END IF
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! ===================
+         IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         !                                           ! --------- !
+         !                                           ! all cases !
+         !                                           ! --------- !
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t_b(:,:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t_n(:,:,:), ldxios = lwxios )
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+         ENDIF
+         !
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_rst
+
+
+   SUBROUTINE dom_vvl_ctl
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl_ctl  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options
+      !!                for vertical coordinate
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios
+      !!
+      NAMELIST/nam_vvl/ ln_vvl_zstar, ln_vvl_ztilde, ln_vvl_layer, ln_vvl_ztilde_as_zstar, &
+         &              ln_vvl_zstar_at_eqtor      , rn_ahe3     , rn_rst_e3t            , &
+         &              rn_lf_cutoff               , rn_zdef_max , ln_vvl_dbg                ! not yet implemented: ln_vvl_kepe
+      !!---------------------------------------------------------------------- 
+      !
+      REWIND( numnam_ref )              ! Namelist nam_vvl in reference namelist : 
+      READ  ( numnam_ref, nam_vvl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_vvl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_vvl in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, nam_vvl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'nam_vvl in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_vvl )
+      !
+      IF(lwp) THEN                    ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_vvl_ctl : choice/control of the variable vertical coordinate'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist nam_vvl : chose a vertical coordinate'
+         WRITE(numout,*) '      zstar                      ln_vvl_zstar   = ', ln_vvl_zstar
+         WRITE(numout,*) '      ztilde                     ln_vvl_ztilde  = ', ln_vvl_ztilde
+         WRITE(numout,*) '      layer                      ln_vvl_layer   = ', ln_vvl_layer
+         WRITE(numout,*) '      ztilde as zstar   ln_vvl_ztilde_as_zstar  = ', ln_vvl_ztilde_as_zstar
+         WRITE(numout,*) '      ztilde near the equator    ln_vvl_zstar_at_eqtor  = ', ln_vvl_zstar_at_eqtor
+         WRITE(numout,*) '      !'
+         WRITE(numout,*) '      thickness diffusion coefficient                      rn_ahe3      = ', rn_ahe3
+         WRITE(numout,*) '      maximum e3t deformation fractional change            rn_zdef_max  = ', rn_zdef_max
+         IF( ln_vvl_ztilde_as_zstar ) THEN
+            WRITE(numout,*) '      ztilde running in zstar emulation mode (ln_vvl_ztilde_as_zstar=T) '
+            WRITE(numout,*) '         ignoring namelist timescale parameters and using:'
+            WRITE(numout,*) '            hard-wired : z-tilde to zstar restoration timescale (days)'
+            WRITE(numout,*) '                         rn_rst_e3t     = 0.e0'
+            WRITE(numout,*) '            hard-wired : z-tilde cutoff frequency of low-pass filter (days)'
+            WRITE(numout,*) '                         rn_lf_cutoff   = 1.0/rdt'
+         ELSE
+            WRITE(numout,*) '      z-tilde to zstar restoration timescale (days)        rn_rst_e3t   = ', rn_rst_e3t
+            WRITE(numout,*) '      z-tilde cutoff frequency of low-pass filter (days)   rn_lf_cutoff = ', rn_lf_cutoff
+         ENDIF
+         WRITE(numout,*) '         debug prints flag                                 ln_vvl_dbg   = ', ln_vvl_dbg
+      ENDIF
+      !
+      ioptio = 0                      ! Parameter control
+      IF( ln_vvl_ztilde_as_zstar )   ln_vvl_ztilde = .true.
+      IF( ln_vvl_zstar           )   ioptio = ioptio + 1
+      IF( ln_vvl_ztilde          )   ioptio = ioptio + 1
+      IF( ln_vvl_layer           )   ioptio = ioptio + 1
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE vertical coordinate in namelist nam_vvl' )
+      IF( .NOT. ln_vvl_zstar .AND. ln_isf ) CALL ctl_stop( 'Only vvl_zstar has been tested with ice shelf cavity' )
+      !
+      IF(lwp) THEN                   ! Print the choice
+         WRITE(numout,*)
+         IF( ln_vvl_zstar           ) WRITE(numout,*) '      ==>>>   zstar vertical coordinate is used'
+         IF( ln_vvl_ztilde          ) WRITE(numout,*) '      ==>>>   ztilde vertical coordinate is used'
+         IF( ln_vvl_layer           ) WRITE(numout,*) '      ==>>>   layer vertical coordinate is used'
+         IF( ln_vvl_ztilde_as_zstar ) WRITE(numout,*) '      ==>>>   to emulate a zstar coordinate'
+      ENDIF
+      !
+#if defined key_agrif
+      IF( (.NOT.Agrif_Root()).AND.(.NOT.ln_vvl_zstar) )   CALL ctl_stop( 'AGRIF is implemented with zstar coordinate only' )
+#endif
+      !
+   END SUBROUTINE dom_vvl_ctl
+
+   !!======================================================================
+END MODULE domvvl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/stpctl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/stpctl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/stpctl.F90	(revision 14097)
@@ -0,0 +1,290 @@
+MODULE stpctl
+   !!======================================================================
+   !!                       ***  MODULE  stpctl  ***
+   !! Ocean run control :  gross check of the ocean time stepping
+   !!======================================================================
+   !! History :  OPA  ! 1991-03  (G. Madec) Original code
+   !!            6.0  ! 1992-06  (M. Imbard)
+   !!            8.0  ! 1997-06  (A.M. Treguier)
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!            2.0  ! 2009-07  (G. Madec)  Add statistic for time-spliting
+   !!            3.7  ! 2016-09  (G. Madec)  Remove solver
+   !!            4.0  ! 2017-04  (G. Madec)  regroup global communications
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   stp_ctl      : Control the run
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables 
+   USE c1d             ! 1D vertical configuration
+   USE diawri          ! Standard run outputs       (dia_wri_state routine)
+   !
+   USE in_out_manager  ! I/O manager
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp         ! distributed memory computing
+   USE zdf_oce ,  ONLY : ln_zad_Aimp       ! ocean vertical physics variables
+   USE wet_dry,   ONLY : ll_wd, ssh_ref    ! reference depth for negative bathy
+
+   USE netcdf          ! NetCDF library
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC stp_ctl           ! routine called by step.F90
+
+   INTEGER  ::   idrun, idtime, idssh, idu, ids1, ids2, idt1, idt2, idc1, idw1, istatus
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE stp_ctl( kt )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE stp_ctl  ***
+      !!                     
+      !! ** Purpose :   Control the run
+      !!
+      !! ** Method  : - Save the time step in numstp
+      !!              - Print it each 50 time steps
+      !!              - Stop the run IF problem encountered by setting nstop > 0
+      !!                Problems checked: |ssh| maximum larger than 10 m
+      !!                                  |U|   maximum larger than 10 m/s 
+      !!                                  negative sea surface salinity
+      !!
+      !! ** Actions :   "time.step" file = last ocean time-step
+      !!                "run.stat"  file = run statistics
+      !!                 nstop indicator sheared among all local domain
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in   ) ::   kt       ! ocean time-step index
+      !!
+      INTEGER                ::   ji, jj, jk          ! dummy loop indices
+      INTEGER,  DIMENSION(3) ::   ih, iu, is1, is2    ! min/max loc indices
+      INTEGER,  DIMENSION(9) ::   iareasum, iareamin, iareamax
+      REAL(wp)               ::   zzz                 ! local real 
+      REAL(wp), DIMENSION(9) ::   zmax, zmaxlocal
+      LOGICAL                ::   ll_wrtstp, ll_colruns, ll_wrtruns
+      LOGICAL, DIMENSION(jpi,jpj,jpk) ::   llmsk
+      CHARACTER(len=20) :: clname
+      !!----------------------------------------------------------------------
+      IF( nstop > 0 .AND. ngrdstop > -1 )   RETURN   !   stpctl was already called by a child grid
+      !
+      ll_wrtstp  = ( MOD( kt-nit000, sn_cfctl%ptimincr ) == 0 ) .OR. ( kt == nitend )
+      ll_colruns = ll_wrtstp .AND. sn_cfctl%l_runstat .AND. jpnij > 1 
+      ll_wrtruns = ( ll_colruns .OR. jpnij == 1 ) .AND. lwm
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF( lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'stp_ctl : time-stepping control'
+            WRITE(numout,*) '~~~~~~~'
+         ENDIF
+         !                                ! open time.step file
+         IF( lwm ) CALL ctl_opn( numstp, 'time.step', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+         !                                ! open run.stat file(s) at start whatever
+         !                                ! the value of sn_cfctl%ptimincr
+         IF( ll_wrtruns ) THEN
+            CALL ctl_opn( numrun, 'run.stat', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp, narea )
+            clname = 'run.stat.nc'
+            IF( .NOT. Agrif_Root() )   clname = TRIM(Agrif_CFixed())//"_"//TRIM(clname)
+            istatus = NF90_CREATE( TRIM(clname), NF90_CLOBBER, idrun )
+            istatus = NF90_DEF_DIM( idrun, 'time', NF90_UNLIMITED, idtime )
+            istatus = NF90_DEF_VAR( idrun, 'abs_ssh_max', NF90_DOUBLE, (/ idtime /), idssh )
+            istatus = NF90_DEF_VAR( idrun,   'abs_u_max', NF90_DOUBLE, (/ idtime /), idu   )
+            istatus = NF90_DEF_VAR( idrun,       's_min', NF90_DOUBLE, (/ idtime /), ids1  )
+            istatus = NF90_DEF_VAR( idrun,       's_max', NF90_DOUBLE, (/ idtime /), ids2  )
+            istatus = NF90_DEF_VAR( idrun,       't_min', NF90_DOUBLE, (/ idtime /), idt1  )
+            istatus = NF90_DEF_VAR( idrun,       't_max', NF90_DOUBLE, (/ idtime /), idt2  )
+            IF( ln_zad_Aimp ) THEN
+               istatus = NF90_DEF_VAR( idrun,   'abs_wi_max', NF90_DOUBLE, (/ idtime /), idw1  )
+               istatus = NF90_DEF_VAR( idrun,       'Cf_max', NF90_DOUBLE, (/ idtime /), idc1  )
+            ENDIF
+            istatus = NF90_ENDDEF(idrun)
+         ENDIF
+      ENDIF
+      !
+      IF(lwm .AND. ll_wrtstp) THEN        !==  current time step  ==!   ("time.step" file)
+         WRITE ( numstp, '(1x, i8)' )   kt
+         REWIND( numstp )
+      ENDIF
+      !
+      !                                   !==  test of extrema  ==!
+      !
+      ! define zmax default value. needed for land processors
+      IF( ll_colruns ) THEN    ! default value: must not be kept when calling mpp_max -> must be as small as possible
+         zmax(:) = -HUGE(1._wp)
+      ELSE                     ! default value: must not give true for any of the tests bellow (-> avoid manipulating HUGE...)
+         zmax(:) =  0._wp
+         zmax(3) = -1._wp      ! avoid salinity minimum at 0.
+      ENDIF
+      !
+      IF( ll_wd ) THEN
+         zmax(1) = MAXVAL(  ABS( sshn(:,:) + ssh_ref*tmask(:,:,1) )  )        ! ssh max 
+      ELSE
+         zmax(1) = MAXVAL(  ABS( sshn(:,:) )  )                               ! ssh max
+      ENDIF
+      zmax(2) = MAXVAL(  ABS( un(:,:,:) )  )                                  ! velocity max (zonal only)
+      llmsk(:,:,:) = tmask(:,:,:) == 1._wp
+      IF( COUNT( llmsk(:,:,:) ) > 0 ) THEN   ! avoid huge values sent back for land processors...      
+         zmax(3) = MAXVAL( -tsn(:,:,:,jp_sal) , mask = llmsk )   ! minus salinity max
+         zmax(4) = MAXVAL(  tsn(:,:,:,jp_sal) , mask = llmsk )   !       salinity max
+         IF( ll_colruns .OR. jpnij == 1 ) THEN     ! following variables are used only in the netcdf file
+            zmax(5) = MAXVAL( -tsn(:,:,:,jp_tem) , mask = llmsk )   ! minus temperature max
+            zmax(6) = MAXVAL(  tsn(:,:,:,jp_tem) , mask = llmsk )   !       temperature max
+            IF( ln_zad_Aimp ) THEN
+               zmax(9) = MAXVAL(   Cu_adv(:,:,:)   , mask = llmsk ) ! partitioning coeff. max
+               llmsk(:,:,:) = wmask(:,:,:) == 1._wp
+               IF( COUNT( llmsk(:,:,:) ) > 0 ) THEN   ! avoid huge values sent back for land processors...
+                  zmax(8) = MAXVAL(  ABS( wi(:,:,:) ) , mask = wmask(:,:,:) == 1._wp ) ! implicit vertical vel. max
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+      zmax(7) = REAL( nstop , wp )                                            ! stop indicator
+      !
+      IF( ll_colruns ) THEN
+         zmaxlocal(:) = zmax(:)
+         CALL mpp_max( "stpctl", zmax )          ! max over the global domain
+         nstop = NINT( zmax(7) )                 ! nstop indicator sheared among all local domains
+      ENDIF
+      !                                   !==  run statistics  ==!   ("run.stat" files)
+      IF( ll_wrtruns ) THEN
+         WRITE(numrun,9500) kt, zmax(1), zmax(2), -zmax(3), zmax(4)
+         istatus = NF90_PUT_VAR( idrun, idssh, (/ zmax(1)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,   idu, (/ zmax(2)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  ids1, (/-zmax(3)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  ids2, (/ zmax(4)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  idt1, (/-zmax(5)/), (/kt/), (/1/) )
+         istatus = NF90_PUT_VAR( idrun,  idt2, (/ zmax(6)/), (/kt/), (/1/) )
+         IF( ln_zad_Aimp ) THEN
+            istatus = NF90_PUT_VAR( idrun,  idw1, (/ zmax(8)/), (/kt/), (/1/) )
+            istatus = NF90_PUT_VAR( idrun,  idc1, (/ zmax(9)/), (/kt/), (/1/) )
+         ENDIF
+         IF( kt == nitend ) istatus = NF90_CLOSE(idrun)
+      END IF
+      !                                   !==  error handling  ==!
+      IF(   zmax(1) >   20._wp .OR.   &                    ! too large sea surface height ( > 20 m )
+         &  zmax(2) >   10._wp .OR.   &                    ! too large velocity ( > 10 m/s)
+!!$         &  zmax(3) >=   0._wp .OR.   &                    ! negative or zero sea surface salinity
+!!$         &  zmax(4) >= 100._wp .OR.   &                    ! too large sea surface salinity ( > 100 )
+!!$         &  zmax(4) <    0._wp .OR.   &                    ! too large sea surface salinity (keep this line for sea-ice)
+         &  ISNAN( zmax(1) + zmax(2) + zmax(3) ) .OR.  &   ! NaN encounter in the tests
+         &  ABS(   zmax(1) + zmax(2) + zmax(3) ) > HUGE(1._wp) ) THEN    ! Infinity encounter in the tests
+         IF( ll_colruns ) THEN
+            ! first: close the netcdf file, so we can read it
+            IF( lwm .AND. kt /= nitend )   istatus = NF90_CLOSE(idrun)
+            CALL mpp_maxloc( 'stpctl', ABS(sshn)        , ssmask(:,:)  , zzz, ih(1:2)  )   ;   ih(3) = 0
+            CALL mpp_maxloc( 'stpctl', ABS(un)          , umask (:,:,:), zzz, iu  )
+            CALL mpp_minloc( 'stpctl', tsn(:,:,:,jp_sal), tmask (:,:,:), zzz, is1 )
+            CALL mpp_maxloc( 'stpctl', tsn(:,:,:,jp_sal), tmask (:,:,:), zzz, is2 )
+            ! find which subdomain has the max.
+            iareamin(:) = jpnij+1   ;   iareamax(:) = 0   ;   iareasum(:) = 0
+            DO ji = 1, 9
+               IF( zmaxlocal(ji) == zmax(ji) ) THEN
+                  iareamin(ji) = narea   ;   iareamax(ji) = narea   ;   iareasum(ji) = 1
+               ENDIF
+            END DO
+            CALL mpp_min( "stpctl", iareamin )         ! min over the global domain
+            CALL mpp_max( "stpctl", iareamax )         ! max over the global domain
+            CALL mpp_sum( "stpctl", iareasum )         ! sum over the global domain
+         ELSE
+            ih(1:2)= MAXLOC( ABS( sshn(:,:)   )                              ) + (/ nimpp - 1, njmpp - 1    /)   ;   ih(3) = 0
+            iu(:)  = MAXLOC( ABS( un  (:,:,:) )                              ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            is1(:) = MINLOC( tsn(:,:,:,jp_sal), mask = tmask(:,:,:) == 1._wp ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            is2(:) = MAXLOC( tsn(:,:,:,jp_sal), mask = tmask(:,:,:) == 1._wp ) + (/ nimpp - 1, njmpp - 1, 0 /)
+            iareamin(:) = narea   ;   iareamax(:) = narea   ;   iareasum(:) = 1         ! this is local information
+         ENDIF
+         !
+         WRITE(ctmp1,*) ' stp_ctl: |ssh| > 20 m  or  |U| > 10 m/s  or  S <= 0  or  S >= 100  or  NaN encounter in the tests'
+         CALL wrt_line(ctmp2, kt, ' |ssh| max ',   zmax(1), ih , iareasum(1), iareamin(1), iareamax(1) ) 
+         CALL wrt_line(ctmp3, kt, ' |U|   max ',   zmax(2), iu , iareasum(2), iareamin(2), iareamax(2) ) 
+         CALL wrt_line(ctmp4, kt, ' Sal   min ', - zmax(3), is1, iareasum(3), iareamin(3), iareamax(3) ) 
+         CALL wrt_line(ctmp5, kt, ' Sal   max ',   zmax(4), is2, iareasum(4), iareamin(4), iareamax(4) ) 
+         IF( Agrif_Root() ) THEN
+            WRITE(ctmp6,*) '      ===> output of last computed fields in output.abort* files'
+         ELSE
+            WRITE(ctmp6,*) '      ===> output of last computed fields in '//TRIM(Agrif_CFixed())//'_output.abort* files'
+         ENDIF
+         !
+         CALL dia_wri_state( 'output.abort' )    ! create an output.abort file
+         !
+         IF( ll_colruns .or. jpnij == 1 ) THEN   ! all processes synchronized -> use lwp to print in opened ocean.output files
+            IF(lwp) THEN   ;   CALL ctl_stop( ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+            ELSE           ;   nstop = MAX(1, nstop)   ! make sure nstop > 0 (automatically done when calling ctl_stop)
+            ENDIF
+         ELSE                                    ! only mpi subdomains with errors are here -> STOP now
+            CALL ctl_stop( 'STOP', ctmp1, ' ', ctmp2, ctmp3, ctmp4, ctmp5, ' ', ctmp6 )
+         ENDIF
+         !
+      ENDIF
+      !
+      IF( nstop > 0 ) THEN                                                  ! an error was detected and we did not abort yet...
+         ngrdstop = Agrif_Fixed()                                           ! store which grid got this error
+         IF( .NOT. ll_colruns .AND. jpnij > 1 )   CALL ctl_stop( 'STOP' )   ! we must abort here to avoid MPI deadlock
+      ENDIF
+      !
+9500  FORMAT(' it :', i8, '    |ssh|_max: ', D23.16, ' |U|_max: ', D23.16,' S_min: ', D23.16,' S_max: ', D23.16)
+      !
+   END SUBROUTINE stp_ctl
+
+
+   SUBROUTINE wrt_line( cdline, kt, cdprefix, pval, kloc, ksum, kmin, kmax )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE wrt_line  ***
+      !!
+      !! ** Purpose :   write information line
+      !!
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*),      INTENT(  out) ::   cdline
+      CHARACTER(len=*),      INTENT(in   ) ::   cdprefix
+      REAL(wp),              INTENT(in   ) ::   pval
+      INTEGER, DIMENSION(3), INTENT(in   ) ::   kloc
+      INTEGER,               INTENT(in   ) ::   kt, ksum, kmin, kmax
+      !
+      CHARACTER(len=80) ::   clsuff
+      CHARACTER(len=9 ) ::   clkt, clsum, clmin, clmax
+      CHARACTER(len=9 ) ::   cli, clj, clk
+      CHARACTER(len=1 ) ::   clfmt
+      CHARACTER(len=4 ) ::   cl4   ! needed to be able to compile with Agrif, I don't know why
+      INTEGER           ::   ifmtk
+      !!----------------------------------------------------------------------
+      WRITE(clkt , '(i9)') kt
+      
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpnij  ,wp))) + 1     ! how many digits to we need to write ? (we decide max = 9)
+      !!! WRITE(clsum, '(i'//clfmt//')') ksum                   ! this is creating a compilation error with AGRIF
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clsum, cl4) ksum
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(MAX(1,jpnij-1),wp))) + 1    ! how many digits to we need to write ? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clmin, cl4) kmin-1
+                                   WRITE(clmax, cl4) kmax-1
+      !
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpiglo,wp))) + 1      ! how many digits to we need to write jpiglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(cli, cl4) kloc(1)      ! this is ok with AGRIF
+      WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpjglo,wp))) + 1      ! how many digits to we need to write jpjglo? (we decide max = 9)
+      cl4 = '(i'//clfmt//')'   ;   WRITE(clj, cl4) kloc(2)      ! this is ok with AGRIF
+      !
+      IF( ksum == 1 ) THEN   ;   WRITE(clsuff,9100) TRIM(clmin)
+      ELSE                   ;   WRITE(clsuff,9200) TRIM(clsum), TRIM(clmin), TRIM(clmax)
+      ENDIF
+      IF(kloc(3) == 0) THEN
+         ifmtk = INT(LOG10(REAL(jpk,wp))) + 1                   ! how many digits to we need to write jpk? (we decide max = 9)
+         clk = REPEAT(' ', ifmtk)                               ! create the equivalent in blank string
+         WRITE(cdline,9300) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj), clk(1:ifmtk), TRIM(clsuff)
+      ELSE
+         WRITE(clfmt, '(i1)') INT(LOG10(REAL(jpk,wp))) + 1      ! how many digits to we need to write jpk? (we decide max = 9)
+         !!! WRITE(clk, '(i'//clfmt//')') kloc(3)               ! this is creating a compilation error with AGRIF
+         cl4 = '(i'//clfmt//')'   ;   WRITE(clk, cl4) kloc(3)   ! this is ok with AGRIF
+         WRITE(cdline,9400) TRIM(ADJUSTL(clkt)), TRIM(ADJUSTL(cdprefix)), pval, TRIM(cli), TRIM(clj),    TRIM(clk), TRIM(clsuff)
+      ENDIF
+      !
+9100  FORMAT('MPI rank ', a)
+9200  FORMAT('found in ', a, ' MPI tasks, spread out among ranks ', a, ' to ', a)
+9300  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j   ', a, ' ', a, ' ', a, ' ', a)
+9400  FORMAT('kt ', a, ' ', a, ' ', 1pg11.4, ' at i j k ', a, ' ', a, ' ', a, ' ', a)
+      !
+   END SUBROUTINE wrt_line
+
+
+   !!======================================================================
+END MODULE stpctl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/trazdf.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/trazdf.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/trazdf.F90	(revision 14097)
@@ -0,0 +1,271 @@
+MODULE trazdf
+   !!==============================================================================
+   !!                 ***  MODULE  trazdf  ***
+   !! Ocean active tracers:  vertical component of the tracer mixing trend
+   !!==============================================================================
+   !! History :  1.0  !  2005-11  (G. Madec)  Original code
+   !!            3.0  !  2008-01  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!            4.0  !  2017-06  (G. Madec)  remove explict time-stepping option
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   tra_zdf       : Update the tracer trend with the vertical diffusion
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables 
+   USE domvvl         ! variable volume
+   USE phycst         ! physical constant
+   USE zdf_oce        ! ocean vertical physics variables
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE ldftra         ! lateral diffusion: eddy diffusivity
+   USE ldfslp         ! lateral diffusion: iso-neutral slope 
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends: tracer trend manager
+   !
+   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 timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   tra_zdf       ! called by step.F90
+   PUBLIC   tra_zdf_imp   ! called by trczdf.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE tra_zdf( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_zdf  ***
+      !!
+      !! ** Purpose :   compute the vertical ocean tracer physics.
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   jk   ! Dummy loop indices
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   ztrdt, ztrds   ! 3D workspace
+      !!---------------------------------------------------------------------
+      !
+      IF( ln_timing )   CALL timing_start('tra_zdf')
+      !
+      IF( kt == nit000 )  THEN
+         IF(lwp)WRITE(numout,*)
+         IF(lwp)WRITE(numout,*) 'tra_zdf : implicit vertical mixing on T & S'
+         IF(lwp)WRITE(numout,*) '~~~~~~~ '
+      ENDIF
+      !
+      IF( neuler == 0 .AND. kt == nit000 ) THEN   ;   r2dt =      rdt   ! at nit000, =   rdt (restarting with Euler time stepping)
+      ELSEIF( kt <= nit000 + 1           ) THEN   ;   r2dt = 2. * rdt   ! otherwise, = 2 rdt (leapfrog)
+      ENDIF
+      !
+      IF( l_trdtra )   THEN                  !* Save ta and sa trends
+         ALLOCATE( ztrdt(jpi,jpj,jpk) , ztrds(jpi,jpj,jpk) )
+         ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
+         ztrds(:,:,:) = tsa(:,:,:,jp_sal)
+      ENDIF
+      !
+      !                                      !* compute lateral mixing trend and add it to the general trend
+      CALL tra_zdf_imp( kt, nit000, 'TRA', r2dt, tsb, tsa, jpts ) 
+
+!!gm WHY here !   and I don't like that !
+      ! DRAKKAR SSS control {
+      ! JMM avoid negative salinities near river outlet ! Ugly fix
+      ! JMM : restore negative salinities to small salinities:
+!!$      WHERE( tsa(:,:,:,jp_sal) < 0._wp )   tsa(:,:,:,jp_sal) = 0.1_wp
+!!gm
+
+      IF( l_trdtra )   THEN                      ! save the vertical diffusive trends for further diagnostics
+         DO jk = 1, jpkm1
+            ztrdt(:,:,jk) = ( ( tsa(:,:,jk,jp_tem)*e3t_a(:,:,jk) - tsb(:,:,jk,jp_tem)*e3t_b(:,:,jk) ) &
+               &          / (e3t_n(:,:,jk)*r2dt) ) - ztrdt(:,:,jk)
+            ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal)*e3t_a(:,:,jk) - tsb(:,:,jk,jp_sal)*e3t_b(:,:,jk) ) &
+              &           / (e3t_n(:,:,jk)*r2dt) ) - ztrds(:,:,jk)
+         END DO
+!!gm this should be moved in trdtra.F90 and done on all trends
+         CALL lbc_lnk_multi( 'trazdf', ztrdt, 'T', 1. , ztrds, 'T', 1. )
+!!gm
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdf, ztrds )
+         DEALLOCATE( ztrdt , ztrds )
+      ENDIF
+      !                                          ! print mean trends (used for debugging)
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' zdf  - Ta: ', mask1=tmask,               &
+         &                       tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
+      !
+      IF( ln_timing )   CALL timing_stop('tra_zdf')
+      !
+   END SUBROUTINE tra_zdf
+
+ 
+   SUBROUTINE tra_zdf_imp( kt, kit000, cdtype, p2dt, ptb, pta, kjpt ) 
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_zdf_imp  ***
+      !!
+      !! ** Purpose :   Compute the after tracer through a implicit computation
+      !!     of the vertical tracer diffusion (including the vertical component 
+      !!     of lateral mixing (only for 2nd order operator, for fourth order 
+      !!     it is already computed and add to the general trend in traldf) 
+      !!
+      !! ** Method  :  The vertical diffusion of a tracer ,t , is given by:
+      !!          difft = dz( avt dz(t) ) = 1/e3t dk+1( avt/e3w dk(t) )
+      !!      It is computed using a backward time scheme (t=after field)
+      !!      which provide directly the after tracer field.
+      !!      If ln_zdfddm=T, use avs for salinity or for passive tracers
+      !!      Surface and bottom boundary conditions: no diffusive flux on
+      !!      both tracers (bottom, applied through the masked field avt).
+      !!      If iso-neutral mixing, add to avt the contribution due to lateral mixing.
+      !!
+      !! ** Action  : - pta  becomes the after tracer
+      !!---------------------------------------------------------------------
+      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)                             , INTENT(in   ) ::   p2dt     ! tracer time-step
+      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      ! in: tracer trend ; out: after tracer field
+      !
+      INTEGER  ::  ji, jj, jk, jn   ! dummy loop indices
+      REAL(wp) ::  zrhs, zzwi, zzws ! local scalars
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::  zwi, zwt, zwd, zws
+      !!---------------------------------------------------------------------
+      !
+      !                                               ! ============= !
+      DO jn = 1, kjpt                                 !  tracer loop  !
+         !                                            ! ============= !
+         !  Matrix construction
+         ! --------------------
+         ! Build matrix if temperature or salinity (only in double diffusion case) or first passive tracer
+         !
+         IF(  ( cdtype == 'TRA' .AND. ( jn == jp_tem .OR. ( jn == jp_sal .AND. ln_zdfddm ) ) ) .OR.   &
+            & ( cdtype == 'TRC' .AND. jn == 1 )  )  THEN
+            !
+            ! vertical mixing coef.: avt for temperature, avs for salinity and passive tracers
+            IF( cdtype == 'TRA' .AND. jn == jp_tem ) THEN   ;   zwt(:,:,2:jpk) = avt(:,:,2:jpk)
+            ELSE                                            ;   zwt(:,:,2:jpk) = avs(:,:,2:jpk)
+            ENDIF
+            zwt(:,:,1) = 0._wp
+            !
+            IF( l_ldfslp ) THEN            ! isoneutral diffusion: add the contribution 
+               IF( ln_traldf_msc  ) THEN     ! MSC iso-neutral operator 
+                  DO jk = 2, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           zwt(ji,jj,jk) = zwt(ji,jj,jk) + akz(ji,jj,jk)  
+                        END DO
+                     END DO
+                  END DO
+               ELSE                          ! standard or triad iso-neutral operator
+                  DO jk = 2, jpkm1
+                     DO jj = 2, jpjm1
+                        DO ji = fs_2, fs_jpim1   ! vector opt.
+                           zwt(ji,jj,jk) = zwt(ji,jj,jk) + ah_wslp2(ji,jj,jk)
+                        END DO
+                     END DO
+                  END DO
+               ENDIF
+            ENDIF
+            !
+            ! Diagonal, lower (i), upper (s)  (including the bottom boundary condition since avt is masked)
+            IF( ln_zad_Aimp ) THEN         ! Adaptive implicit vertical advection
+               DO jk = 1, jpkm1
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1   ! vector opt. (ensure same order of calculation as below if wi=0.)
+                        zzwi = - p2dt * zwt(ji,jj,jk  ) / e3w_n(ji,jj,jk  )
+                        zzws = - p2dt * zwt(ji,jj,jk+1) / e3w_n(ji,jj,jk+1)
+                        zwd(ji,jj,jk) = e3t_a(ji,jj,jk) - zzwi - zzws   &
+                           &                 + p2dt * ( MAX( wi(ji,jj,jk  ) , 0._wp ) - MIN( wi(ji,jj,jk+1) , 0._wp ) )
+                        zwi(ji,jj,jk) = zzwi + p2dt *   MIN( wi(ji,jj,jk  ) , 0._wp )
+                        zws(ji,jj,jk) = zzws - p2dt *   MAX( wi(ji,jj,jk+1) , 0._wp )
+                    END DO
+                  END DO
+               END DO
+            ELSE
+               DO jk = 1, jpkm1
+                  DO jj = 2, jpjm1
+                     DO ji = fs_2, fs_jpim1   ! vector opt.
+                        zwi(ji,jj,jk) = - p2dt * zwt(ji,jj,jk  ) / e3w_n(ji,jj,jk)
+                        zws(ji,jj,jk) = - p2dt * zwt(ji,jj,jk+1) / e3w_n(ji,jj,jk+1)
+                        zwd(ji,jj,jk) = e3t_a(ji,jj,jk) - zwi(ji,jj,jk) - zws(ji,jj,jk)
+                    END DO
+                  END DO
+               END DO
+            ENDIF
+            !
+            !! Matrix inversion from the first level
+            !!----------------------------------------------------------------------
+            !   solve m.x = y  where m is a tri diagonal matrix ( jpk*jpk )
+            !
+            !        ( zwd1 zws1   0    0    0  )( zwx1 ) ( zwy1 )
+            !        ( zwi2 zwd2 zws2   0    0  )( zwx2 ) ( zwy2 )
+            !        (  0   zwi3 zwd3 zws3   0  )( zwx3 )=( zwy3 )
+            !        (        ...               )( ...  ) ( ...  )
+            !        (  0    0    0   zwik zwdk )( zwxk ) ( zwyk )
+            !
+            !   m is decomposed in the product of an upper and lower triangular matrix.
+            !   The 3 diagonal terms are in 3d arrays: zwd, zws, zwi.
+            !   Suffices i,s and d indicate "inferior" (below diagonal), diagonal
+            !   and "superior" (above diagonal) components of the tridiagonal system.
+            !   The solution will be in the 4d array pta.
+            !   The 3d array zwt is used as a work space array.
+            !   En route to the solution pta is used a to evaluate the rhs and then 
+            !   used as a work space array: its value is modified.
+            !
+            DO jj = 2, jpjm1        !* 1st recurrence:   Tk = Dk - Ik Sk-1 / Tk-1   (increasing k)
+               DO ji = fs_2, fs_jpim1            ! done one for all passive tracers (so included in the IF instruction)
+                  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)
+                  END DO
+               END DO
+            END DO
+            !
+         ENDIF 
+         !         
+         DO jj = 2, jpjm1           !* 2nd recurrence:    Zk = Yk - Ik / Tk-1  Zk-1
+            DO ji = fs_2, fs_jpim1
+               pta(ji,jj,1,jn) = e3t_b(ji,jj,1) * ptb(ji,jj,1,jn) + p2dt * e3t_n(ji,jj,1) * pta(ji,jj,1,jn)
+            END DO
+         END DO
+         DO jk = 2, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zrhs = e3t_b(ji,jj,jk) * ptb(ji,jj,jk,jn) + p2dt * e3t_n(ji,jj,jk) * pta(ji,jj,jk,jn)   ! zrhs=right hand side
+                  pta(ji,jj,jk,jn) = zrhs - zwi(ji,jj,jk) / zwt(ji,jj,jk-1) * pta(ji,jj,jk-1,jn)
+               END DO
+            END DO
+         END DO
+         !
+         DO jj = 2, jpjm1           !* 3d recurrence:    Xk = (Zk - Sk Xk+1 ) / Tk   (result is the after tracer)
+            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
+                  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)
+               END DO
+            END DO
+         END DO
+         !                                            ! ================= !
+      END DO                                          !  end tracer loop  !
+      !                                               ! ================= !
+   END SUBROUTINE tra_zdf_imp
+
+   !!==============================================================================
+END MODULE trazdf
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,141 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  CANAL configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2017-11  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for CANAL configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, rn_0xratio, rn_0yratio, rn_ppgphi0, nn_fcase
+   !                                                  and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                CANAL configuration : beta-plance with uniform grid spacing (rn_dx)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : CANAL configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          Beta-plane with regular grid-spacing'
+      IF(lwp) WRITE(numout,*) '          given by rn_dx and rn_dy' 
+      !
+      !                          
+      ! Position coordinates (in kilometers)
+      !                          ==========
+      zlam0 = -REAL(NINT(jpiglo*rn_0xratio)-1, wp) * rn_dx
+      zphi0 = -REAL(NINT(jpjglo*rn_0yratio)-1, wp) * rn_dy 
+
+#if defined key_agrif
+      ! ! let lower left longitude and latitude from parent
+      IF (.NOT.Agrif_root()) THEN
+          zlam0 = (0.5_wp-(Agrif_parent(jpiglo)-1)/2)*Agrif_irhox()*rn_dx &
+             &+(Agrif_Ix()+nbghostcells-1)*Agrif_irhox()*rn_dx-(0.5_wp+nbghostcells)*rn_dx
+          zphi0 = (0.5_wp-(Agrif_parent(jpjglo)-1)/2)*Agrif_irhoy()*rn_dy &
+             &+(Agrif_Iy()+nbghostcells-1)*Agrif_irhoy()*rn_dy-(0.5_wp+nbghostcells)*rn_dy
+      ENDIF 
+#endif
+         
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+            zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+            plamt(ji,jj) = zlam0 + rn_dx * zti
+            plamu(ji,jj) = zlam0 + rn_dx * zui
+            plamv(ji,jj) = plamt(ji,jj) 
+            plamf(ji,jj) = plamu(ji,jj) 
+   
+            pphit(ji,jj) = zphi0 + rn_dy * ztj
+            pphiv(ji,jj) = zphi0 + rn_dy * zvj
+            pphiu(ji,jj) = pphit(ji,jj) 
+            pphif(ji,jj) = pphiv(ji,jj) 
+         END DO
+      END DO
+      !     
+      ! Horizontal scale factors (in meters)
+      !                              ======
+      pe1t(:,:) = rn_dx * 1.e+3  ;   pe2t(:,:) = rn_dy * 1.e+3 
+      pe1u(:,:) = rn_dx * 1.e+3  ;   pe2u(:,:) = rn_dy * 1.e+3
+      pe1v(:,:) = rn_dx * 1.e+3  ;   pe2v(:,:) = rn_dy * 1.e+3
+      pe1f(:,:) = rn_dx * 1.e+3  ;   pe2f(:,:) = rn_dy * 1.e+3 
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_hgr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      SELECT CASE(nn_fcase)
+      CASE(0)
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0
+         pff_t(:,:) = zf0
+      CASE(1)
+         zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+         pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      CASE(2)
+         pff_f(:,:) = 2._wp * omega * SIN( rad * ( rn_ppgphi0 + pphif(:,:)/110. ) )
+         pff_t(:,:) = 2._wp * omega * SIN( rad * ( rn_ppgphi0 + pphit(:,:)/110. ) )
+      END SELECT
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,322 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                      ===  CANAL configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2017-11  (J. Chanut) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce        
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   !   
+   USE usrdef_nam
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here CANAL configuration 
+      !!
+      !! ** Method  :   Set a gaussian anomaly of pressure and associated
+      !!                geostrophic velocities
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  :: ji, jj, jk, jl  ! dummy loop indices
+      REAL(wp) :: zx, zy, zP0, zumax, zlambda, zr_lambda2, zn2, zf0, zH, zrho1, za, zf, zdzF
+      REAL(wp) :: zpsurf, zdyPs, zdxPs
+      REAL(wp) :: zdt, zdu, zdv
+      REAL(wp) :: zjetx, zjety, zbeta
+      REAL(wp), DIMENSION(jpi,jpj)  ::   zrandom
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : CANAL configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   '
+      !
+      zjetx = ABS(rn_ujetszx)/2.
+      zjety = ABS(rn_ujetszy)/2.
+      !
+      zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+      !
+      SELECT CASE(nn_initcase)
+
+      CASE(-1)    ! stratif at rest
+
+         ! sea level:
+         pssh(:,:) = 0.
+         ! temperature:
+         pts(:,:,1,jp_tem) = 25. !!30._wp
+         pts(:,:,2:jpk,jp_tem) = 22. !!24._wp
+         ! salinity:  
+         pts(:,:,:,jp_sal) = 35._wp
+         ! velocities:
+         pu(:,:,:) = 0.
+         pv(:,:,:) = 0.
+
+      CASE(0)    ! rest
+         
+         ! sea level:
+         pssh(:,:) = 0.
+         ! temperature:
+         pts(:,:,:,jp_tem) = 10._wp
+         ! salinity:  
+         pts(:,:,:,jp_sal) = 35._wp
+         ! velocities:
+         pu(:,:,:) = 0.
+         pv(:,:,:) = 0.
+         
+      CASE(1)    ! geostrophic zonal jet from -zjety to +zjety
+
+         ! sea level:
+         SELECT CASE( nn_fcase )
+         CASE(0)    ! f = f0
+            ! sea level: ssh = - fuy / g
+            WHERE( ABS(gphit) <= zjety )
+               pssh(:,:) = - ff_t(:,:) * rn_uzonal * gphit(:,:) * 1.e3 / grav
+            ELSEWHERE
+               pssh(:,:) = - ff_t(:,:) * rn_uzonal * SIGN(zjety, gphit(:,:)) * 1.e3 / grav
+            END WHERE
+         CASE(1)    ! f = f0 + beta*y
+            ! sea level: ssh = - u / g * ( fy + 0.5 * beta * y^2 )
+            zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+            WHERE( ABS(gphit) <= zjety )
+               pssh(:,:) = - rn_uzonal / grav * ( zf0 * gphit(:,:) * 1.e3 + 0.5 * zbeta * gphit(:,:) * gphit(:,:) * 1.e6 )
+            ELSEWHERE
+               pssh(:,:) = - rn_uzonal / grav * ( zf0 * SIGN(zjety, gphit(:,:)) * 1.e3   &
+                  &                             + 0.5 * zbeta * zjety * zjety * 1.e6 )
+            END WHERE
+         END SELECT
+         ! temperature:
+         pts(:,:,:,jp_tem) = 10._wp
+         ! salinity:  
+         pts(:,:,jpk,jp_sal) = 0.
+         DO jk=1, jpkm1
+            WHERE( ABS(gphit) <= zjety )
+!!$            WHERE( ABS(gphit) <= zjety*0.5 .AND. ABS(glamt) <= zjety*0.5 ) ! for a square of salt
+               pts(:,:,jk,jp_sal) = 35.
+            ELSEWHERE
+               pts(:,:,jk,jp_sal) = 30.
+            END WHERE                    
+         END DO
+         ! velocities:
+         pu(:,:,:) = 0.
+         DO jk=1, jpkm1
+            WHERE( ABS(gphit) <= zjety ) pu(:,:,jk) = rn_uzonal
+         END DO
+         pv(:,:,:) = 0.
+         !                  
+      CASE(2)    ! geostrophic zonal current shear
+      
+         ! sea level:
+         SELECT CASE( nn_fcase )
+         CASE(0)    ! f = f0
+            ! sea level: ssh = - fuy / g
+            WHERE( ABS(gphit) <= zjety )
+               pssh(:,:) = - ff_t(:,:) * rn_uzonal * ABS(gphit(:,:)) * 1.e3 / grav
+            ELSEWHERE
+               pssh(:,:) = - ff_t(:,:) * rn_uzonal * zjety * 1.e3 / grav
+            END WHERE
+         CASE(1)    ! f = f0 + beta*y
+            ! sea level: ssh = - u / g * ( fy + 0.5 * beta * y^2 )
+            zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+            WHERE( ABS(gphit) <= zjety )
+               pssh(:,:) = - SIGN(rn_uzonal, gphit(:,:)) / grav   &
+                  &        * ( zf0 * gphit(:,:) * 1.e3 + 0.5 * zbeta * gphit(:,:) * gphit(:,:) * 1.e6 )
+            ELSEWHERE
+               pssh(:,:) = - SIGN(rn_uzonal, gphit(:,:)) / grav   &
+                  &        * ( zf0 * SIGN(zjety, gphit(:,:)) * 1.e3 + 0.5 * zbeta * zjety * zjety * 1.e6 )
+            END WHERE
+         END SELECT
+         ! temperature:
+         pts(:,:,:,jp_tem) = 10._wp
+         ! salinity:  
+         pts(:,:,:,jp_sal) = 30.
+         DO jk=1, jpkm1
+            WHERE( ABS(gphiv) <= zjety ) pts(:,:,jk,jp_sal) = 30. + SIGN(1.,gphiv(:,:))
+         END DO
+         ! velocities:
+         pu(:,:,:) = 0.
+         DO jk=1, jpkm1
+            WHERE( ABS(gphiv) <= zjety ) pu(:,:,jk) = SIGN(rn_uzonal,gphit(:,:))*SIGN(1.,rn_uzonal)
+            WHERE( ABS(gphiv) == 0.    ) pu(:,:,jk) = 0.  
+         END DO
+         pv(:,:,:) = 0.
+         !                  
+      CASE(3)    ! gaussian zonal currant
+
+         ! zonal current
+         DO jk=1, jpkm1
+            ! gphit and lambda are both in km
+            pu(:,:,jk) = rn_uzonal * EXP( - 0.5 * gphit(:,:)**2 / rn_lambda**2 )
+         END DO
+         
+         ! sea level:
+         pssh(:,1) = - ff_t(:,1) / grav * pu(:,1,1) * e2t(:,1)
+         DO jl=1, jpnj
+            DO jj=nldj, nlej
+               DO ji=nldi, nlei
+                  pssh(ji,jj) = pssh(ji,jj-1) - ff_t(ji,jj) / grav * pu(ji,jj,1) * e2t(ji,jj)
+               END DO
+            END DO
+            CALL lbc_lnk( 'usrdef_istate', pssh, 'T',  1. )
+         END DO
+         
+         ! temperature:
+         pts(:,:,:,jp_tem) = 10._wp
+         ! salinity:  
+         DO jk=1, jpkm1
+            pts(:,:,jk,jp_sal) = pssh(:,:)
+         END DO
+         ! velocities:
+         pv(:,:,:) = 0.
+         !            
+      CASE(4)    ! geostrophic zonal pulse
+   
+         DO jj=1, jpj
+            DO ji=1, jpi
+               IF ( ABS(glamt(ji,jj)) <= zjetx ) THEN
+                  zdu = rn_uzonal
+               ELSEIF ( ABS(glamt(ji,jj)) <= zjetx + 100. ) THEN
+                  zdu = rn_uzonal * ( ( zjetx-ABS(glamt(ji,jj)) )/100. + 1. )
+               ELSE
+                  zdu = 0.
+               END IF
+               IF ( ABS(gphit(ji,jj)) <= zjety ) THEN
+                  pssh(ji,jj) = - ff_t(ji,jj) * zdu * gphit(ji,jj) * 1.e3 / grav
+                  pu(ji,jj,:) = zdu
+                  pts(ji,jj,:,jp_sal) = zdu / rn_uzonal + 1.
+               ELSE
+                  pssh(ji,jj) = - ff_t(ji,jj) * zdu * SIGN(zjety,gphit(ji,jj)) * 1.e3 / grav 
+                  pu(ji,jj,:) = 0.
+                  pts(ji,jj,:,jp_sal) = 1.
+               END IF
+            END DO
+         END DO
+         
+         ! temperature:
+         pts(:,:,:,jp_tem) = 10._wp * ptmask(:,:,:)        
+         pv(:,:,:) = 0.
+         
+         
+       CASE(5)    ! vortex
+                  !
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         zumax = rn_vtxmax * SIGN(1._wp, zf0) ! Here Anticyclonic: set zumax=-1 for cyclonic
+         zlambda = SQRT(2._wp)*rn_lambda*1.e3       ! Horizontal scale in meters 
+         zn2 = 3.e-3**2
+         zH = 0.5_wp * 5000._wp
+         !
+         zr_lambda2 = 1._wp / zlambda**2
+         zP0 = rau0 * zf0 * zumax * zlambda * SQRT(EXP(1._wp)/2._wp)
+         !
+         DO jj=1, jpj
+            DO ji=1, jpi
+               zx = glamt(ji,jj) * 1.e3
+               zy = gphit(ji,jj) * 1.e3
+               ! Surface pressure: P(x,y,z) = F(z) * Psurf(x,y)
+               zpsurf = zP0 * EXP(-(zx**2+zy**2)*zr_lambda2) - rau0 * ff_t(ji,jj) * rn_uzonal * zy
+               ! Sea level:
+               pssh(ji,jj) = 0.
+               DO jl=1,5
+                  zdt = pssh(ji,jj)
+                  zdzF = (1._wp - EXP(zdt-zH)) / (zH - 1._wp + EXP(-zH))   ! F'(z)
+                  zrho1 = rau0 * (1._wp + zn2*zdt/grav) - zdzF * zpsurf / grav    ! -1/g Dz(P) = -1/g * F'(z) * Psurf(x,y)
+                  pssh(ji,jj) = zpsurf / (zrho1*grav) * ptmask(ji,jj,1)   ! ssh = Psurf / (Rho*g)
+               END DO
+               ! temperature:
+               DO jk=1,jpk
+                  zdt =  pdept(ji,jj,jk) 
+                  zrho1 = rau0 * (1._wp + zn2*zdt/grav)
+                  IF (zdt < zH) THEN
+                     zdzF = (1._wp-EXP(zdt-zH)) / (zH-1._wp + EXP(-zH))   ! F'(z)
+                     zrho1 = zrho1 - zdzF * zpsurf / grav    ! -1/g Dz(P) = -1/g * F'(z) * Psurf(x,y)
+                  ENDIF
+                  !               pts(ji,jj,jk,jp_tem) = (20._wp + (rau0-zrho1) / 0.28_wp) * ptmask(ji,jj,jk)
+                  pts(ji,jj,jk,jp_tem) = (10._wp + (rau0-zrho1) / 0.28_wp) * ptmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !
+         ! salinity:  
+         pts(:,:,:,jp_sal) = 35._wp * ptmask(:,:,:) 
+         !
+         ! velocities:
+         za = 2._wp * zP0 / zlambda**2
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               zx = glamu(ji,jj) * 1.e3
+               zy = gphiu(ji,jj) * 1.e3
+               DO jk=1, jpk
+                  zdu = 0.5_wp * (pdept(ji,jj,jk) + pdept(ji+1,jj,jk))
+                  IF (zdu < zH) THEN
+                     zf = (zH-1._wp-zdu+EXP(zdu-zH)) / (zH-1._wp+EXP(-zH))
+                     zdyPs = - za * zy * EXP(-(zx**2+zy**2)*zr_lambda2) - rau0 * ff_t(ji,jj) * rn_uzonal
+                     pu(ji,jj,jk) = - zf / ( rau0 * ff_t(ji,jj) ) * zdyPs * ptmask(ji,jj,jk) * ptmask(ji+1,jj,jk)
+                  ELSE
+                     pu(ji,jj,jk) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               zx = glamv(ji,jj) * 1.e3
+               zy = gphiv(ji,jj) * 1.e3
+               DO jk=1, jpk
+                  zdv = 0.5_wp * (pdept(ji,jj,jk) + pdept(ji,jj+1,jk))
+                  IF (zdv < zH) THEN
+                     zf = (zH-1._wp-zdv+EXP(zdv-zH)) / (zH-1._wp+EXP(-zH))
+                     zdxPs = - za * zx * EXP(-(zx**2+zy**2)*zr_lambda2)
+                     pv(ji,jj,jk) = zf / ( rau0 * ff_f(ji,jj) ) * zdxPs * ptmask(ji,jj,jk) * ptmask(ji,jj+1,jk)
+                  ELSE
+                     pv(ji,jj,jk) = 0._wp
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !            
+         CALL lbc_lnk_multi( 'usrdef_istate', pu, 'U', -1., pv, 'V', -1. )
+
+      END SELECT
+
+      IF (ln_sshnoise) THEN
+         CALL RANDOM_SEED()
+         CALL RANDOM_NUMBER(zrandom)
+         pssh(:,:) = pssh(:,:) + ( 0.1  * zrandom(:,:) - 0.05 )
+      END IF
+  
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,162 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  EW_CANAL configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2017-10  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                              !!* namusr_def namelist *!!
+   REAL(wp)         ::   rn_domszx  = 1800.  ! x horizontal size         [km]
+   REAL(wp)         ::   rn_domszy  = 1800.  ! y horizontal size         [km]
+   REAL(wp), PUBLIC ::   rn_domszz  = 5000.  ! z horizontal size          [m]
+   REAL(wp), PUBLIC ::   rn_dx      =   30.  ! x horizontal resolution   [km]
+   REAL(wp), PUBLIC ::   rn_dy      =   30.  ! y horizontal resolution   [km]
+   REAL(wp), PUBLIC ::   rn_dz      =  500.  ! vertical resolution        [m]
+   REAL(wp), PUBLIC ::   rn_0xratio =    0.5 ! x domain ratio of the 0
+   REAL(wp), PUBLIC ::   rn_0yratio =    0.5 ! x domain ratio of the 0
+   INTEGER , PUBLIC ::   nn_fcase   =    1   ! F computation (0:f0, 1:Beta, 2:real)
+   REAL(wp), PUBLIC ::   rn_ppgphi0 =   38.5 ! reference latitude for beta-plane 
+   REAL(wp), PUBLIC ::   rn_u10     =    0.  ! 10m wind speed              [m/s]
+   REAL(wp), PUBLIC ::   rn_windszx =  150.  ! longitudinal wind extension  [km]
+   REAL(wp), PUBLIC ::   rn_windszy =  150.  ! latitudinal wind extension   [km]
+   REAL(wp), PUBLIC ::   rn_uofac   =    0.  ! Uoce multiplicative factor (0.:absolute or 1.:relative winds)
+   REAL(wp), PUBLIC ::   rn_vtxmax  =    0.  ! initial canal max current  [m/s]
+   REAL(wp), PUBLIC ::   rn_uzonal  =    0.  ! initial zonal current       [m/s]
+   REAL(wp), PUBLIC ::   rn_ujetszx =  150.  ! longitudinal jet extension  [km]
+   REAL(wp), PUBLIC ::   rn_ujetszy =  150.  ! latitudinal jet extension   [km]
+   INTEGER , PUBLIC ::   nn_botcase =    0   ! bottom definition (0:flat, 1:bump)
+   INTEGER , PUBLIC ::   nn_initcase=    0   ! initial condition case (0=rest, 1=zonal current, 2=canal)
+   LOGICAL , PUBLIC ::   ln_sshnoise=.false. ! add random noise on initial ssh
+   REAL(wp), PUBLIC ::   rn_lambda  = 50.    ! gaussian lambda
+   INTEGER , PUBLIC ::   nn_perio   =    0   ! periodicity of the channel (0=closed, 1=E-W)
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here EW_CANAL configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios      ! Local integer
+      REAL(wp)::   zh       ! Local scalars
+      !!
+      NAMELIST/namusr_def/  rn_domszx, rn_domszy, rn_domszz, rn_dx, rn_dy, rn_dz, rn_0xratio, rn_0yratio   &
+         &                 , nn_fcase, rn_ppgphi0, rn_u10, rn_windszx, rn_windszy & !!, rn_uofac   &
+         &                 , rn_vtxmax, rn_uzonal, rn_ujetszx, rn_ujetszy  &
+         &                 , nn_botcase, nn_initcase, ln_sshnoise, rn_lambda, nn_perio
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+#if defined key_agrif 
+      ! Domain parameters are taken from parent:
+      IF( .NOT. Agrif_Root() ) THEN
+         rn_dx = Agrif_Parent(rn_dx)/Agrif_Rhox()
+         rn_dy = Agrif_Parent(rn_dy)/Agrif_Rhoy()
+         rn_dz = Agrif_Parent(rn_dz)
+         rn_ppgphi0 = Agrif_Parent(rn_ppgphi0)
+      ENDIF
+      rn_0xratio = 0.5
+      rn_0yratio = 0.5
+#endif
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'EW_CANAL'             ! name & resolution (not used)
+      kk_cfg = INT( rn_dx )
+      !
+      ! Global Domain size:  EW_CANAL global domain is  1800 km x 1800 Km x 5000 m
+      kpi = NINT( rn_domszx / rn_dx ) + 1
+      kpj = NINT( rn_domszy / rn_dy ) + 3
+      kpk = NINT( rn_domszz / rn_dz ) + 1
+#if defined key_agrif
+      IF( .NOT. Agrif_Root() ) THEN
+         kpi  = nbcellsx + 2 + 2*nbghostcells
+         kpj  = nbcellsy + 2 + 2*nbghostcells
+      ENDIF
+#endif
+      !
+      zh  = (kpk-1)*rn_dz
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 1                    ! EW_CANAL configuration : closed basin
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : EW_CANAL test case'
+         WRITE(numout,*) '      horizontal domain size-x          rn_domszx  = ', rn_domszx, ' km'
+         WRITE(numout,*) '      horizontal domain size-y          rn_domszy  = ', rn_domszy, ' km'
+         WRITE(numout,*) '      vertical   domain size-z          rn_domszz  = ', rn_domszz, '  m'
+         WRITE(numout,*) '      horizontal x-resolution           rn_dx      = ',     rn_dx, ' km'
+         WRITE(numout,*) '      horizontal y-resolution           rn_dy      = ',     rn_dy, ' km'
+         WRITE(numout,*) '      vertical resolution               rn_dz      = ',     rn_dz, '  m'
+         WRITE(numout,*) '      x-domain ratio of the 0           rn_0xratio = ', rn_0xratio
+         WRITE(numout,*) '      y-domain ratio of the 0           rn_0yratio = ', rn_0yratio
+         WRITE(numout,*) '          H [m] : ', zh
+         WRITE(numout,*) '      F computation                     nn_fcase   = ',   nn_fcase
+         WRITE(numout,*) '      Reference latitude                rn_ppgphi0 = ', rn_ppgphi0
+         WRITE(numout,*) '      10m wind speed                    rn_u10     = ',     rn_u10, ' m/s'
+         WRITE(numout,*) '         wind latitudinal extension     rn_windszy = ', rn_windszy, ' km'
+         WRITE(numout,*) '         wind longitudinal extension    rn_windszx = ', rn_windszx, ' km'
+         WRITE(numout,*) '         Uoce multiplicative factor     rn_uofac   = ',   rn_uofac
+         WRITE(numout,*) '      initial Canal max current         rn_vtxmax  = ',  rn_vtxmax, ' m/s'
+         WRITE(numout,*) '      initial zonal current             rn_uzonal  = ',  rn_uzonal, ' m/s'
+         WRITE(numout,*) '         Jet latitudinal extension      rn_ujetszy = ', rn_ujetszy, ' km'
+         WRITE(numout,*) '         Jet longitudinal extension     rn_ujetszx = ', rn_ujetszx, ' km'
+         WRITE(numout,*) '      bottom definition (0:flat)        nn_botcase = ', nn_botcase
+         WRITE(numout,*) '      initial condition case            nn_initcase= ', nn_initcase
+         WRITE(numout,*) '                   (0:rest, 1:zonal current, 10:shear)'
+         WRITE(numout,*) '      add random noise on initial ssh   ln_sshnoise= ', ln_sshnoise
+         WRITE(numout,*) '      Gaussian lambda parameter          rn_lambda = ', rn_lambda
+         WRITE(numout,*) '      Periodicity of the basin            nn_perio = ', nn_perio
+      ENDIF
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = nn_perio                    ! EW_CANAL configuration : closed basin
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,117 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  CANAL configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2017-11  (J.Chanut)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in OVERFLOW case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY : rn_u10, rn_uofac, rn_windszy, rn_windszx 
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for CANAL case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) :: zrhoair = 1.22     ! approximate air density [Kg/m3]
+      REAL(wp) :: zcd = 1.13e-3      ! approximate drag coefficient
+      REAL(wp) :: zrhocd             ! Rho * Cd
+      REAL(wp), DIMENSION(jpi,jpj) :: zwndrel   ! relative wind
+      !!---------------------------------------------------------------------
+      !
+      zrhocd = zrhoair * zcd
+      
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : EW_CANAL case: surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+
+      IF( rn_u10 /= 0. .AND. rn_windszy > 0. ) THEN
+         IF( nyear == 1 .AND. nmonth == 1 .AND. nday <= 10 ) THEN
+            WHERE( ABS(gphit) <= rn_windszy/2. .AND. ABS(glamt) <= rn_windszx/2. ) utau(:,:) = zrhocd * rn_u10 * rn_u10
+         ELSE
+            utau(:,:) = 0.
+         ENDIF
+      ENDIF
+
+      IF( rn_uofac /= 0. ) THEN
+         
+         WHERE( ABS(gphit) <= rn_windszy/2. )
+            zwndrel(:,:) = rn_u10 - rn_uofac * un(:,:,1)
+         ELSEWHERE
+            zwndrel(:,:) =        - rn_uofac * un(:,:,1)
+         END WHERE
+         utau(:,:) = zrhocd * zwndrel(:,:) * zwndrel(:,:)
+
+         zwndrel(:,:) = - rn_uofac * vn(:,:,1)
+         vtau(:,:) = zrhocd * zwndrel(:,:) * zwndrel(:,:)
+
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,250 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                      ===  CANAL configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2017-11  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE phycst         ! physical constants
+   USE usrdef_nam, ONLY: rn_domszz, nn_botcase
+   USE depth_e3       ! depth <=> e3
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   inum   ! local logical unit
+      REAL(WP) ::   z_zco, z_zps, z_sco, z_cav
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : CANAL configuration (z-coordinate closed flat box ocean)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .TRUE.         ! CANAL case:  z-coordinate without ocean cavities
+      ld_zps    = .FALSE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      CALL zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      CALL zgr_msk_top_bot( k_top , k_bot )                 ! masked top and bottom ocean t-level indices
+      !
+      !                                                     ! z-coordinate (3D arrays) from the 1D z-coord.
+      CALL zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in  : 1D reference vertical coordinate
+         &          pdept   , pdepw   ,                     &   ! out : 3D t & w-points depth
+         &          pe3t    , pe3u    , pe3v   , pe3f   ,   &   !       vertical scale factors
+         &          pe3w    , pe3uw   , pe3vw             )     !           -      -      -
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z  ***
+      !!
+      !! ** Purpose :   set the 1D depth of model levels and the resulting 
+      !!              vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!           with at top and bottom :
+      !!                   e3w_1d( 1 ) = 2 * ( dept_1d( 1 ) - depw_1d( 1 ) )
+      !!                   e3t_1d(jpk) = 2 * ( dept_1d(jpk) - depw_1d(jpk) )
+      !!       The depth are then re-computed from the sum of e3. This ensures 
+      !!    that depths are identical when reading domain configuration file. 
+      !!    Indeed, only e3. are saved in this file, depth are compute by a call
+      !!    to the e3_to_depth subroutine.
+      !!
+      !!       Here the Madec & Imbard (1996) function is used.
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!
+      !! Reference : Marti, Madec & Delecluse, 1992, JGR, 97, No8, 12,763-12,766.
+      !!             Madec and Imbard, 1996, Clim. Dyn.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zd       ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zd = rn_domszz/FLOAT(jpkm1)
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z   : Reference vertical z-coordinates '
+         WRITE(numout,*) '    ~~~~~~~'
+         WRITE(numout,*) '       CANAL case : uniform vertical grid :'
+         WRITE(numout,*) '                     with thickness = ', zd
+      ENDIF
+
+      !
+      ! 1D Reference z-coordinate    (using Madec & Imbard 1996 function)
+      ! -------------------------
+      !
+      pdepw_1d(1) = 0._wp
+      pdept_1d(1) = 0.5_wp * zd
+      ! 
+      DO jk = 2, jpk          ! depth at T and W-points
+         pdepw_1d(jk) = pdepw_1d(jk-1) + zd 
+         pdept_1d(jk) = pdept_1d(jk-1) + zd 
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d ) 
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d ) 
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z
+
+
+   SUBROUTINE zgr_msk_top_bot( k_top , k_bot )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_msk_top_bot  ***
+      !!
+      !! ** Purpose :   set the masked top and bottom ocean t-levels
+      !!
+      !! ** Method  :   CANAL case = closed flat box ocean without ocean cavities
+      !!                   k_top = 1     except along north, south, east and west boundaries
+      !!                   k_bot = jpk-1 except along north, south, east and west boundaries
+      !!
+      !! ** Action  : - k_top : first wet ocean level index
+      !!              - k_bot : last  wet ocean level index
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(out) ::   k_top , k_bot   ! first & last wet ocean level
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D local workspace
+      REAL(wp)                     ::   zmaxlam, zscl
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_bot : defines the top and bottom wet ocean levels.'
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '       CANAL case : closed flat box ocean without ocean cavities'
+      !
+      SELECT CASE(nn_botcase)
+      CASE(0)
+         z2d(:,:) = REAL( jpkm1 , wp )          ! flat bottom
+      CASE(1)
+         zmaxlam = MAXVAL(glamt)
+         CALL mpp_max( 'usrdef_zgr', zmaxlam )                 ! max over the global domain
+         zscl = 0.5 * rpi / zmaxlam
+         z2d(:,:) = COS( glamt(:,:) * zscl )
+         z2d(:,:) = REAL(jpkm1 - NINT( 0.5 * REAL(jpkm1,wp) * z2d(:,:) ), wp)
+      END SELECT
+      !
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )           ! set surrounding land to zero (here jperio=0 ==>> closed)
+      !
+      k_bot(:,:) = INT( z2d(:,:) )           ! =jpkm1 over the ocean point, =0 elsewhere
+      !
+      k_top(:,:) = MIN( 1 , k_bot(:,:) )     ! = 1    over the ocean point, =0 elsewhere
+      !
+   END SUBROUTINE zgr_msk_top_bot
+   
+
+   SUBROUTINE zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in : 1D reference vertical coordinate
+      &                pdept   , pdepw   ,                     &   ! out: 3D t & w-points depth
+      &                pe3t    , pe3u    , pe3v   , pe3f   ,   &   !      vertical scale factors
+      &                pe3w    , pe3uw   , pe3vw             )     !          -      -      -
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zgr_zco  ***
+      !!
+      !! ** Purpose :   define the reference z-coordinate system
+      !!
+      !! ** Method  :   set 3D coord. arrays to reference 1D array 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth       [m]
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pe3t_1d , pe3w_1d           ! 1D vertical scale factors [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth          [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors    [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         !    -       -      -
+      !
+      INTEGER  ::   jk
+      !!----------------------------------------------------------------------
+      !
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE zgr_zco
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/cpp_CANAL.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/cpp_CANAL.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/CANAL/cpp_CANAL.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys key_iomput key_mpp_mpi 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,68 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+============================================================================================================
+  -->
+    
+    <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 day files -->   	
+
+	<file id="file1" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+        <!-- ice mask -->
+        <field field_ref="icemask"          name="simsk"   />
+
+        <!-- general -->
+        <field field_ref="snwvolu"          name="snvolu" />
+        <field field_ref="icethic"          name="sithic" />
+        <field field_ref="icethic"          name="sithic_max" operation="maximum" />
+        <field field_ref="icethic"          name="sithic_min" operation="minimum" />
+        <field field_ref="iceneg_pres"      name="sineg_pres" />
+        <field field_ref="iceneg_volu"      name="sineg_volu" />
+        <field field_ref="fasticepres"      name="fasticepres" />
+        <field field_ref="icevolu"          name="sivolu" />
+        <field field_ref="iceconc"          name="siconc" />
+        <field field_ref="icesalt"          name="sisali" />
+        <field field_ref="iceapnd"          name="siapnd" />
+        <field field_ref="icevpnd"          name="sivpnd" />
+        <field field_ref="sst_m"            name="sst_m"  />
+        <field field_ref="sss_m"            name="sss_m"  />
+
+        <!-- momentum -->
+        <field field_ref="uice"             name="sivelu"  />
+        <field field_ref="vice"             name="sivelv"  />
+        <field field_ref="icevel"           name="sivelo"  />
+
+        <!-- rheology -->
+        <field field_ref="icediv"           name="sidive"  />
+
+        <!-- categories -->
+        <field field_ref="icemask_cat"      name="simskcat"/>
+        <field field_ref="snwthic_cat"      name="snthicat"/>
+        <field field_ref="iceconc_cat"      name="siconcat"/>
+        <field field_ref="icethic_cat"      name="sithicat"/>
+
+        </file>
+
+      </file_group>
+
+      <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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context                                         =
+=                                         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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+	  <!--
+          <variable id="optimal_buffer_size"       type="string">memory</variable>
+          <variable id="buffer_size_factor"        type="double">1.0</variable>
+	  -->
+	  <variable id="info_level"                type="int">10</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/make_initice.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/make_initice.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/make_initice.py	(revision 14097)
@@ -0,0 +1,120 @@
+#!/usr/bin/python
+
+import os,sys
+from netCDF4 import Dataset as netcdf
+import numpy as np
+import matplotlib.pyplot as plt
+from math import exp
+from math import ceil
+
+resname=''
+
+# input file
+###fcoord='coordinates_'+str(resname)+'.nc'
+#fcoord='mesh_mask_'+str(resname)+'.nc'
+fcoord='mesh_mask.nc'
+
+# output file
+#fflx='initice_'+str(resname)+'.nc'
+fflx='initice_60pts.nc'
+
+print '   creating init ice file  ' +fflx
+
+# Reading coordinates file
+nccoord=netcdf(fcoord,'r')
+nav_lon=nccoord.variables['nav_lon']
+nav_lat=nccoord.variables['nav_lat']
+time_counter=1
+LON1= nav_lon.shape[1]
+LAT1= nav_lon.shape[0]
+print 'nav_lon.shape[1]' ,nav_lon.shape[1]
+print 'LON1 ', LON1
+print 'LAT1 ', LAT1
+
+# Creating INITICE netcdf file
+nc=netcdf(fflx,'w')
+nc.createDimension('y',LAT1)
+nc.createDimension('x',LON1)
+nc.createDimension('time_counter',None)    # Setting dimension size to 0 or None makes it unlimited. 
+
+cdflon=nc.createVariable('nav_lon','f',('y','x'))
+cdflat=nc.createVariable('nav_lat','f',('y','x'))
+cdftimecounter=nc.createVariable('time_counter','f',('time_counter'))
+
+# ati : Fraction of open waters in sea ice - units %
+# hti : Sea ice thickness - units m
+# hts : Snow thickness - units m
+# smi :
+# tmi : Sea ice internal temperature - units K
+# tsu : Sea ice surface temperature - units K
+#
+# Take constant values from namelist &namiceini of NEMO
+rn_hti_ini=2.0
+rn_hts_ini=0.2            #  initial real snow thickness (m)
+rn_ati_ini=0.9            #  initial ice concentration   (-)
+rn_smi_ini=6.3            #  initial ice salinity     (g/kg)
+rn_tmi_ini=270.           #  initial ice/snw temperature (K)
+rn_tsu_ini=270.           #  initial sea ice temperature (K)
+#
+cdfati=nc.createVariable('ati','f',('time_counter','y','x'))
+cdfati.units='Percentage'
+cdfati.long_name='Sea ice concentration'
+cdfhti=nc.createVariable('hti','f',('time_counter','y','x'))
+cdfhti.long_name='Sea ice thickness'
+cdfhti.units='m'
+cdfhts=nc.createVariable('hts','f',('time_counter','y','x'))
+cdfhts.long_name='Snow thickness'
+cdfhts.units='m'
+cdfsmi=nc.createVariable('smi','f',('time_counter','y','x'))
+cdfsmi.long_name='Sea ice salinity'
+cdfsmi.units='pss'
+cdftmi=nc.createVariable('tmi','f',('time_counter','y','x'))
+cdftmi.long_name='Sea ice internal temperature'
+cdftmi.units='Kelvin'
+cdftsu=nc.createVariable('tsu','f',('time_counter','y','x'))
+cdftsu.long_name='Sea ice surface temperature'
+cdftsu.units='Kelvin'
+
+cdflon[:,:]=nav_lon[:,:]
+cdflat[:,:]=nav_lat[:,:]
+cdftimecounter[0]=1
+
+# Fill fields
+#print 'cdfati[:,1]', cdfati[:,1]  -> 32 values
+
+# Add a gaussian for sea ice thickness here
+cdfhti[:,:,:]=0.
+cdfhts[:,:,:]=0.
+cdfati[:,:,:]=0.
+cdfsmi[:,:,:]=0.
+cdftmi[:,:,:]=rn_tmi_ini
+cdftsu[:,:,:]=rn_tsu_ini
+
+# --------------------------------------
+# for basin=99x99km with dx=1km ; dy=1km
+
+# --- Lipscomb 2004 experiment ---
+cdfhti[:,:,:]=1.
+# thickness
+for y in np.arange(0,LAT1,1) :
+    for x in np.arange(0,LON1,1) :
+        if (x >= 15. and x <= 43.):
+            cdfhti[:,y,x] = 0.2
+#        elif (x < 10. or x > 50.):
+#            cdfhti[:,y,x] = 0.
+
+cdfati[:,:,:]=0.001
+# concentration
+for y in np.arange(0,LAT1,1) :
+    for x in np.arange(0,LON1,1) :
+        if (x >= 10. and x <= 29.):
+            cdfati[:,y,x] = 0.9 * (x - 9.) / 20.
+        elif (x > 29. and x <= 48.):
+            cdfati[:,y,x] = 0.9
+
+# ---------------------------------------
+
+nc.close()
+nccoord.close()
+
+#sys.exit()
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_ADV1D configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_ADV1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    4.   ! horizontal resolution in meters
+   rn_dy       =    4.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_ADV1D" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =      40      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      =   2.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_ADV1D_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.     !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_120pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_120pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_120pts	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_ADV1D configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_ADV1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    4.   ! horizontal resolution in meters
+   rn_dy       =    4.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_ADV1D" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =      80      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      =   2.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_ADV1D_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_240pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_240pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_240pts	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_ADV1D configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_ADV1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    4.   ! horizontal resolution in meters
+   rn_dy       =    4.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_ADV1D" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =     160      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      =   2.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_ADV1D_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_60pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_60pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_cfg_60pts	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_ADV1D configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_ADV1D user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    4.   ! horizontal resolution in meters
+   rn_dy       =    4.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_ADV1D" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =      40      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      =   2.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_ADV1D_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,107 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   1             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .true.          !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   1.            !        prescribed ice u-velocity
+      rn_vice       =   0.            !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization
+
+   sn_hti = 'initice_60pts'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice_60pts'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice_60pts'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice_60pts'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice_60pts'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice_60pts'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_120pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_120pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_120pts	(revision 14097)
@@ -0,0 +1,107 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface forcing                (namforcing)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   1             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .true.          !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   1.            !        prescribed ice u-velocity
+      rn_vice       =   0.            !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namforcing     !   Ice surface forcing
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization 
+
+   sn_hti = 'initice_120pts'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice_120pts'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice_120pts'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice_120pts'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice_120pts'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice_120pts'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_240pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_240pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_240pts	(revision 14097)
@@ -0,0 +1,107 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface forcing                (namforcing)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   1             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .true.          !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   1.            !        prescribed ice u-velocity
+      rn_vice       =   0.            !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namforcing     !   Ice surface forcing
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization 
+
+   sn_hti = 'initice_240pts'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice_240pts'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice_240pts'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice_240pts'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice_240pts'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice_240pts'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_60pts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_60pts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_cfg_60pts	(revision 14097)
@@ -0,0 +1,107 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface forcing                (namforcing)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   jpl              =   1             !  number of ice  categories
+   nlay_i           =   2             !  number of ice  layers
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .true.          !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   1.            !        prescribed ice u-velocity
+      rn_vice       =   0.            !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namforcing     !   Ice surface forcing
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization 
+
+   sn_hti = 'initice_60pts'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice_60pts'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice_60pts'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice_60pts'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice_60pts'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice_60pts'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,125 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  ICE_ADV1D configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ICE_ADV1D configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, ln_corio, rn_ppgphi0   ! horizontal resolution in meters
+   !                                                            coriolis and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ICE_ADV1D configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : ICE_ADV1D configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          f-plane with regular grid-spacing rn_dx, rn_dy'
+
+      !                          ==========
+      zlam0 = -(jpiglo-1)/2 * 1.e-3 * rn_dx
+      zphi0 = -(jpjglo-1)/2 * 1.e-3 * rn_dy
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+            zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+            plamt(ji,jj) = zlam0 + rn_dx * 1.e-3 * zti
+            plamu(ji,jj) = zlam0 + rn_dx * 1.e-3 * zui
+            plamv(ji,jj) = plamt(ji,jj) 
+            plamf(ji,jj) = plamu(ji,jj) 
+   
+            pphit(ji,jj) = zphi0 + rn_dy * 1.e-3 * ztj
+            pphiv(ji,jj) = zphi0 + rn_dy * 1.e-3 * zvj
+            pphiu(ji,jj) = pphit(ji,jj) 
+            pphif(ji,jj) = pphiv(ji,jj) 
+         END DO
+      END DO
+         
+      ! constant scale factors
+      pe1t(:,:) = rn_dx
+      pe2t(:,:) = rn_dy
+         
+      pe1u(:,:) = pe1t(:,:)      ;      pe2u(:,:) = pe2t(:,:)
+      pe1v(:,:) = pe1t(:,:)      ;      pe2v(:,:) = pe2t(:,:)
+      pe1f(:,:) = pe1t(:,:)      ;      pe2f(:,:) = pe2t(:,:)
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      IF( ln_corio ) THEN
+         zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+         pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      ELSE
+         pff_f(:,:) = 0.
+         pff_t(:,:) = 0.
+      ENDIF
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,106 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  ICE_ADV1D configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                               !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dy      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_ppgphi0 ! reference latitude for beta-plane 
+   LOGICAL , PUBLIC ::   ln_corio   ! set coriolis at 0 (ln_corio=F) or not 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ICE_ADV1D configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios       ! Local integer
+      REAL(wp)::   zlx, zly  ! Local scalars
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dy, ln_corio, rn_ppgphi0
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ICE_ADV1D'           ! name & resolution (not used)
+      kk_cfg = INT( rn_dx )
+      !
+      ! Global Domain size:  ICE_ADV1D domain is  480 m x 480 m x 10 m
+      kpi = INT( 480.*0.5 / rn_dx ) -1
+      kpj = INT( 480.*0.5 / rn_dy ) -1
+      kpk = 1
+      !
+      zlx = kpi*rn_dx*1.e-3
+      zly = kpj*rn_dy*1.e-3
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! ICE_ADV1D configuration : bi-periodic basin
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ICE_ADV1D test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      horizontal resolution                    rn_dy  = ', rn_dy, ' meters'
+         WRITE(numout,*) '      ICE_ADV1D domain  '
+         WRITE(numout,*) '         LX [km]: ', zlx
+         WRITE(numout,*) '         LY [km]: ', zly
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '         Coriolis:', ln_corio
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ICE_ADV1D : closed basin                 jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,164 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  ICE_ADV1D configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ICE_ADV1D case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   USE ice, ONLY       : at_i_b, a_i_b
+   USE icethd_dh       ! for CALL ice_thd_snwblow
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called by sbcmod.F90 for sbc ocean
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ICE_ADV1D case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp)   WRITE(numout,*)' usrdef_sbc_oce : ICE_ADV1D case: NO surface forcing'
+         ! --- oce variables --- !
+         utau(:,:) = 0._wp 
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !
+         utau_b(:,:) = 0._wp 
+         vtau_b(:,:) = 0._wp
+         emp_b (:,:) = 0._wp
+         sfx_b (:,:) = 0._wp
+         qns_b (:,:) = 0._wp
+         !
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (momentum) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_ADV1D case: no stress forcing'
+      !
+      utau_ice(:,:) = 0._wp
+      vtau_ice(:,:) = 0._wp
+      !
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (flux) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+      !!
+      INTEGER  ::   jl
+      REAL(wp) ::   zfr1, zfr2                 ! local variables
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsnw   ! snw distribution after wind blowing
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztri
+      !!---------------------------------------------------------------------
+      !
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_ADV1D case: NO flux forcing'
+      !
+      ! ocean variables (renaming)
+      emp_oce (:,:)   = 0._wp   ! uniform value for freshwater budget (E-P)
+      qsr_oce (:,:)   = 0._wp   ! uniform value for     solar radiation
+      qns_oce (:,:)   = 0._wp   ! uniform value for non-solar radiation
+
+      ! ice variables
+      alb_ice (:,:,:) = 0.7_wp  ! useless
+      qsr_ice (:,:,:) = 0._wp   ! uniform value for     solar radiation
+      qns_ice (:,:,:) = 0._wp   ! uniform value for non-solar radiation
+      sprecip (:,:)   = 0._wp   ! uniform value for snow precip
+      evap_ice(:,:,:) = 0._wp   ! uniform value for sublimation
+
+      ! ice fields deduced from above
+      zsnw(:,:) = 1._wp
+      !!CALL lim_thd_snwblow( at_i_b, zsnw )  ! snow distribution over ice after wind blowing 
+      emp_ice  (:,:)   = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw(:,:)
+      emp_oce  (:,:)   = emp_oce(:,:) - sprecip(:,:) * (1._wp - zsnw(:,:) )
+      qevap_ice(:,:,:) =   0._wp
+      qprec_ice(:,:)   =   rhos * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) !  in J/m3
+      qemp_oce (:,:)   = - emp_oce(:,:) * sst_m(:,:) * rcp
+      qemp_ice (:,:)   =   sprecip(:,:) * zsnw * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) ! solid precip (only)
+
+      ! total fluxes
+      emp_tot (:,:) = emp_ice  + emp_oce
+      qns_tot (:,:) = at_i_b(:,:) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 ) + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot (:,:) = at_i_b(:,:) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- shortwave radiation transmitted below the surface (W/m2, see Grenfell Maykut 77) --- !
+      cloud_fra(:,:) = pp_cldf
+      ztri(:,:) = 0.18 * ( 1.0 - cloud_fra(:,:) ) + 0.35 * cloud_fra(:,:)  ! surface transmission when hi>10cm
+      !
+      DO jl = 1, jpl
+         WHERE    ( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) <  0.1_wp )     ! linear decrease from hi=0 to 10cm  
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ( ztri(:,:) + ( 1._wp - ztri(:,:) ) * ( 1._wp - phi(:,:,jl) * 10._wp ) )
+         ELSEWHERE( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) >= 0.1_wp )     ! constant (ztri) when hi>10cm
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ztri(:,:)
+         ELSEWHERE                                                         ! zero when hs>0
+            qtr_ice_top(:,:,jl) = 0._wp
+         END WHERE
+      ENDDO
+         
+ 
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,111 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===      ICE_ADV1D case     ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk, k_dz  ! dummy indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ICE_ADV1D configuration (slab ocean - advection of ice in one direction)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate  ==>>>   here ICE_ADV1D : slab ocean always
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-full-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! 
+      k_dz = 1
+      DO jk = 1, jpk
+         pdepw_1d(jk) =    k_dz
+         pdept_1d(jk) =    k_dz
+         pe3w_1d (jk) =    k_dz
+         pe3t_1d (jk) =    k_dz
+      END DO
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      k_top(:,:) = 1
+      !
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !                                !* bottom ocean compute from the depth of grid-points
+      jpkm1 = jpk
+      k_bot(:,:) = 1    ! here use k_top as a land mask
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/cpp_ICE_ADV1D.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/cpp_ICE_ADV1D.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV1D/cpp_ICE_ADV1D.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys key_si3 key_mpp_mpi key_nosignedzero key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/README
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/README	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/README	(revision 14097)
@@ -0,0 +1,61 @@
+WARNING: For now, the test case ICE_ADV2D only works if the logical "ll_neg" is set to FALSE in the routine icedyn_adv_umx.F90
+                  (it is still unclear why)
+-------
+Purpose
+-------
+This demonstration case can serve different purposes:
+
+1) The main one: study of the advection of a patch of ice in a bi-periodic channel with a slab ocean (i.e. 1 ocean layer)
+              ==> set ln_icethd=false in namelist_ice_cfg
+
+2) Secondary: study of ice thermodynamics in the same basin
+              ==> set ln_icedyn=false in namelist_ice_cfg
+              ==> eventually change usrdef_sbc.F90 in MY_SRC to fit your needs
+
+-----------
+Experiments
+-----------
+Two experiments can be configured:
+
+a) A simple channel at 3km horizontal resolution (slightly variable => +- 10%)
+              ==> in MY_SRC/usrdef_hgr.F90, uncomment the part "variable scale factors" and comment part "constant scale factors"
+
+b) A simple channel at 3km horizontal resolution (constant scale factors)
+              ==> in MY_SRC/usrdef_hgr.F90, comment the part "variable scale factors" and uncomment part "constant scale factors"
+
+----------
+How to run
+----------
+
+a) Compile and run the model once to get a mesh_mask.nc file with the following command:
+../../../makenemo -r ICE_ADV2D -n ICE_ADV2D -m X64_ADA -j 4
+mpirun ./nemo -np 1
+
+b) Create the initial condition file for sea-ice (initice.nc) by running this python script: 
+python ./make_INITICE.py
+
+c) Run the model a second time
+mpirun ./nemo -np 4
+
+---------------
+What to look at
+---------------
+In case of purpose 1, One can test
+---
+a) the advection scheme: Ultimate-Macho (ln_adv_UMx=T) versus Prather (ln_adv_Pra=T)
+   for a square (ice concentration) or a gaussian (ice volume)
+      with either a constant velocity (ln_dynADV2D=T)
+               or a constant ice-atm. stress, thus velocity is calculated by rheology (ln_dynRHGADV=T)
+      with 1 or 5 ice categories (jpl=1 or 5).
+         (note that ln_dynADV2D=T only works with jpl=1)
+
+In case of purpose 2, one can test conservation of properties:
+---
+b) ice should not change at all if surface fluxes = 0 and SST = freezing temperature
+
+--------------------------------------
+Interpretation of the results (remarks)
+--------------------------------------
+- Prather conserves the max values but also creates side lobes
+- UM does not conserve the max but does not create side lobes
+- The "unmoving" ice (if any) is due to ice rheology which states that ice mass below a certain thresold (1kg/m2) is considered to move at the ocean velocity (thus 0 m/s)
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,40 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"   type="float" > 1.e20 </variable>
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,107 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+============================================================================================================
+  -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+    
+      <file_group id="5ts" output_freq="5ts"  output_level="10" enabled=".TRUE.">  <!-- 1 day files -->   	
+
+	<file id="file1" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+        <!-- ice mask -->
+        <field field_ref="icemask"          name="simsk"   />
+
+        <!-- general -->
+        <field field_ref="snwvolu"          name="snvolu" />
+        <field field_ref="icethic"          name="sithic" />
+        <field field_ref="icethic"          name="sithic_max" operation="maximum" />
+        <field field_ref="icethic"          name="sithic_min" operation="minimum" />
+        <field field_ref="iceneg_pres"      name="sineg_pres" />
+        <field field_ref="iceneg_volu"      name="sineg_volu" />
+        <field field_ref="fasticepres"      name="fasticepres" />
+        <field field_ref="icevolu"          name="sivolu" />
+        <field field_ref="iceconc"          name="siconc" />
+        <field field_ref="icesalt"          name="sisali" />
+        <field field_ref="iceapnd"          name="siapnd" />
+        <field field_ref="icevpnd"          name="sivpnd" />
+        <field field_ref="sst_m"            name="sst_m"  />
+        <field field_ref="sss_m"            name="sss_m"  />
+
+        <!-- heat -->
+        <field field_ref="icetemp"          name="sitemp" />
+        <field field_ref="icettop"          name="sittop" />
+        <field field_ref="icetbot"          name="sitbot" />
+        <field field_ref="icetsni"          name="sitsni" />
+
+        <!-- momentum -->
+        <field field_ref="uice"             name="sivelu"  />
+        <field field_ref="vice"             name="sivelv"  />
+        <field field_ref="icevel"           name="sivelo"  />
+        <field field_ref="utau_ai"          name="utau_ai" />
+        <field field_ref="vtau_ai"          name="vtau_ai" />
+        <field field_ref="utau_oi"          name="utau_oi" />
+        <field field_ref="vtau_oi"          name="vtau_oi" />
+
+        <!-- rheology -->
+        <field field_ref="icediv"           name="sidive"  />
+        <field field_ref="iceshe"           name="sishea"  />
+        <field field_ref="icestr"           name="sistre"  />
+        <field field_ref="normstr"          name="normstr" />
+        <field field_ref="sheastr"          name="sheastr" />
+
+        <!-- heat fluxes -->
+        <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+        <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+        <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+        <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+        <field field_ref="qt_ice"           name="qt_ice"     />
+        <field field_ref="qsr_ice"          name="qsr_ice"    />
+        <field field_ref="qns_ice"          name="qns_ice"    />
+        <field field_ref="qemp_ice"         name="qemp_ice"   />
+        <field field_ref="albedo"           name="albedo"     />
+
+        <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+        <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+        <field field_ref="hfxsensib"        name="hfxsensib"  />
+
+        <!-- salt fluxes -->
+        <field field_ref="sfxice"           name="sfxice" />
+
+        <!-- mass fluxes -->
+        <field field_ref="vfxice"           name="vfxice" />
+        <field field_ref="vfxsnw"           name="vfxsnw" />
+
+        <!-- categories -->
+        <field field_ref="icemask_cat"      name="simskcat"/>
+        <field field_ref="snwthic_cat"      name="snthicat"/>
+        <field field_ref="iceconc_cat"      name="siconcat"/>
+        <field field_ref="icethic_cat"      name="sithicat"/>
+        <field field_ref="icesalt_cat"      name="sisalcat"/>
+        <field field_ref="icetemp_cat"      name="sitemcat"/>
+
+        </file>
+
+      </file_group>
+
+      <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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context                                         =
+=                                         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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+	  <!--
+          <variable id="optimal_buffer_size"       type="string">memory</variable>
+          <variable id="buffer_size_factor"        type="double">1.0</variable>
+	  -->
+	  <variable id="info_level"                type="int">10</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/make_INITICE.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/make_INITICE.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/make_INITICE.py	(revision 14097)
@@ -0,0 +1,119 @@
+#!/usr/bin/python
+
+import os,sys
+from netCDF4 import Dataset as netcdf
+import numpy as np
+import matplotlib.pyplot as plt
+from math import exp
+from math import ceil
+
+resname=''
+
+# input file
+fcoord='mesh_mask.nc'
+
+# output file
+fflx='initice.nc'
+
+print '   creating init ice file  ' +fflx
+
+# Reading coordinates file
+nccoord=netcdf(fcoord,'r')
+nav_lon=nccoord.variables['nav_lon']
+nav_lat=nccoord.variables['nav_lat']
+time_counter=1
+LON1= nav_lon.shape[1]
+LAT1= nav_lon.shape[0]
+print 'nav_lon.shape[1]' ,nav_lon.shape[1]
+print 'LON1 ', LON1
+print 'LAT1 ', LAT1
+
+# Creating INITICE netcdf file
+nc=netcdf(fflx,'w')
+nc.createDimension('y',LAT1)
+nc.createDimension('x',LON1)
+nc.createDimension('time_counter',None)    # Setting dimension size to 0 or None makes it unlimited. 
+
+cdflon=nc.createVariable('nav_lon','f',('y','x'))
+cdflat=nc.createVariable('nav_lat','f',('y','x'))
+cdftimecounter=nc.createVariable('time_counter','f',('time_counter'))
+
+# ati : Fraction of open waters in sea ice - units %
+# hti : Sea ice thickness - units m
+# hts : Snow thickness - units m
+# smi : Sea ice salinity:
+# tmi : Sea ice internal temperature - units K
+# tsu : Sea ice surface temperature - units K
+#
+# Take constant values from namelist &namiceini of NEMO
+rn_hti_ini=2.0
+rn_hts_ini=0.2            #  initial real snow thickness (m)
+rn_ati_ini=0.9            #  initial ice concentration   (-)
+rn_smi_ini=6.3            #  initial ice salinity     (g/kg)
+rn_tmi_ini=270.           #  initial ice/snw temperature (K)
+rn_tsu_ini=270.           #  initial sea ice temperature (K)
+#
+cdfati=nc.createVariable('ati','f',('time_counter','y','x'))
+cdfati.units='Percentage'
+cdfati.long_name='Sea ice concentration'
+cdfhti=nc.createVariable('hti','f',('time_counter','y','x'))
+cdfhti.long_name='Sea ice thickness'
+cdfhti.units='m'
+cdfhts=nc.createVariable('hts','f',('time_counter','y','x'))
+cdfhts.long_name='Snow thickness'
+cdfhts.units='m'
+cdfsmi=nc.createVariable('smi','f',('time_counter','y','x'))
+cdfsmi.long_name='Sea ice salinity'
+cdfsmi.units='pss'
+cdftmi=nc.createVariable('tmi','f',('time_counter','y','x'))
+cdftmi.long_name='Sea ice internal temperature'
+cdftmi.units='Kelvin'
+cdftsu=nc.createVariable('tsu','f',('time_counter','y','x'))
+cdftsu.long_name='Sea ice surface temperature'
+cdftsu.units='Kelvin'
+
+cdflon[:,:]=nav_lon[:,:]
+cdflat[:,:]=nav_lat[:,:]
+cdftimecounter[0]=1
+
+# Fill fields
+#print 'cdfati[:,1]', cdfati[:,1]  -> 32 values
+
+# Add a gaussian for sea ice thickness here
+cdfhti[:,:,:]=0.
+cdfhts[:,:,:]=0.
+cdfati[:,:,:]=0.
+cdfsmi[:,:,:]=0.
+cdftmi[:,:,:]=rn_tmi_ini
+cdftsu[:,:,:]=rn_tsu_ini
+
+# --------------------------------------
+# for basin=99x99km with dx=1km ; dy=3km
+#sigx=-0.04
+#sigy=-0.04*9.
+#xshift=50.-1.
+#yshift=17.-1.
+#dlat=7
+#dlon=21
+
+# --------------------------------------
+# for basin=99x99km with dx=3km ; dy=3km
+sigx=-0.04
+sigy=-0.04
+xshift=50.-1.
+yshift=50.-1.
+dlat=21
+dlon=21
+
+# --- gaussian and square experiment ---
+for y in np.arange(dlat,LAT1-dlat,1) :
+    for x in np.arange(dlon,LON1-dlon,1) :
+        cdfhti[:,y,x] = rn_hti_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+        cdfhts[:,y,x] = rn_hts_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+        cdfati[:,y,x] = rn_ati_ini
+        cdfsmi[:,y,x] = rn_smi_ini
+
+nc.close()
+nccoord.close()
+
+#sys.exit()
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_ADV2D configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_ADV2D user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    3000.   ! horizontal resolution in meters
+   rn_dy       =    3000.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_ADV2D" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =     485      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 1200.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_ADV2D_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.     !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,105 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .false.         !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .true.          !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   0.5           !        prescribed ice u-velocity
+      rn_vice       =   0.5           !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization 
+
+   sn_hti = 'initice'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,162 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  ICE_ADV2D configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ICE_ADV2D configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, ln_corio, rn_ppgphi0   ! horizontal resolution in meters
+   !                                                            coriolis and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ICE_ADV2D configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : ICE_ADV2D configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          f-plane with regular or irregular grid-spacing (+- 10%)'
+      IF(lwp) WRITE(numout,*) '          the max is given by rn_dx and rn_dy' 
+
+      !                          ==========
+      zlam0 = -(jpiglo-1)/2 * 1.e-3 * rn_dx
+      zphi0 = -(jpjglo-1)/2 * 1.e-3 * rn_dy
+
+#if defined key_agrif 
+      IF( .NOT. Agrif_Root() ) THEN
+!clem         zlam0  = Agrif_Parent(zlam0) + (Agrif_ix())*Agrif_Parent(rn_dx) * 1.e-5
+!clem         zphi0  = Agrif_Parent(zphi0) + (Agrif_iy())*Agrif_Parent(rn_dy) * 1.e-5
+         zlam0 = ( 0.5_wp - ( Agrif_parent(jpiglo) - 1 ) / 2 ) * 1.e-3 * Agrif_irhox() * rn_dx  &
+            &  + ( Agrif_Ix() + nbghostcells - 1 ) * Agrif_irhox() * rn_dx * 1.e-3 - ( 0.5_wp + nbghostcells ) * rn_dx * 1.e-3
+         zphi0 = ( 0.5_wp - ( Agrif_parent(jpjglo) - 1 ) / 2 ) * 1.e-3 * Agrif_irhoy() * rn_dy  &
+            &  + ( Agrif_Iy() + nbghostcells - 1 ) * Agrif_irhoy() * rn_dy * 1.e-3 - ( 0.5_wp + nbghostcells ) * rn_dy * 1.e-3
+      ENDIF
+#endif         
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+            zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+            plamt(ji,jj) = zlam0 + rn_dx * 1.e-3 * zti
+            plamu(ji,jj) = zlam0 + rn_dx * 1.e-3 * zui
+            plamv(ji,jj) = plamt(ji,jj) 
+            plamf(ji,jj) = plamu(ji,jj) 
+   
+            pphit(ji,jj) = zphi0 + rn_dy * 1.e-3 * ztj
+            pphiv(ji,jj) = zphi0 + rn_dy * 1.e-3 * zvj
+            pphiu(ji,jj) = pphit(ji,jj) 
+            pphif(ji,jj) = pphiv(ji,jj) 
+         END DO
+      END DO
+         
+         ! Horizontal scale factors (in meters)
+         !                              ======
+!! ==> EITHER 1) variable scale factors
+!! clem: This can be used with a 1proc simulation but I think it breaks repro when >1procs are used      
+!!         DO jj = 1, jpj
+!!            DO ji = 1, jpi
+!!               !!pe1t(ji,jj) = rn_dx * EXP( -0.8/REAL(jpiglo**2) * (mi0(ji)-REAL(jpiglo+1)*0.5)**2 )  ! gaussian shape
+!!               !!pe2t(ji,jj) = rn_dy * EXP( -0.8/REAL(jpjglo**2) * (mj0(jj)-REAL(jpjglo+1)*0.5)**2 )  ! gaussian shape
+!!               pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5) ) ! linear shape
+!!               pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5) ) ! linear shape
+!!            END DO
+!!         END DO
+!!#if defined key_agrif 
+!!         IF( .NOT. Agrif_Root() ) THEN ! only works if the zoom is positioned at the center of the parent grid
+!!            DO jj = 1, jpj
+!!               DO ji = 1, jpi
+!!                  pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5)  &
+!!                     &                            * REAL(jpiglo) / REAL(Agrif_Parent(jpiglo) * Agrif_Rhox()) )       ! factor to match parent grid
+!!                  pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5)  &
+!!                     &                            * REAL(jpjglo) / REAL(Agrif_Parent(jpjglo) * Agrif_Rhoy()) )       ! factor to match parent grid
+!!               END DO
+!!            END DO
+!!         ENDIF
+!!#endif
+!! ==> OR 2) constant scale factors
+         pe1t(:,:) = rn_dx
+         pe2t(:,:) = rn_dy
+!! ==> END
+         
+      pe1u(:,:) = pe1t(:,:)      ;      pe2u(:,:) = pe2t(:,:)
+      pe1v(:,:) = pe1t(:,:)      ;      pe2v(:,:) = pe2t(:,:)
+      pe1f(:,:) = pe1t(:,:)      ;      pe2f(:,:) = pe2t(:,:)
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      IF( ln_corio ) THEN
+         zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+         pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      ELSE
+         pff_f(:,:) = 0.
+         pff_t(:,:) = 0.
+      ENDIF
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,125 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  ICE_ADV2D configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                               !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dy      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_ppgphi0 ! reference latitude for beta-plane 
+   LOGICAL , PUBLIC ::   ln_corio   ! set coriolis at 0 (ln_corio=F) or not 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ICE_ADV2D configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios       ! Local integer
+      REAL(wp)::   zlx, zly  ! Local scalars
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dy, ln_corio, rn_ppgphi0
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+#if defined key_agrif 
+      ! Domain parameters are taken from parent:
+      IF( .NOT. Agrif_Root() ) THEN
+         rn_dx = Agrif_Parent(rn_dx)/Agrif_Rhox()
+         rn_dy = Agrif_Parent(rn_dy)/Agrif_Rhoy()
+         rn_ppgphi0 = Agrif_Parent(rn_ppgphi0)
+      ENDIF
+#endif
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ICE_ADV2D'           ! name & resolution (not used)
+      kk_cfg = NINT( rn_dx )
+      !
+      IF( Agrif_Root() ) THEN        ! Global Domain size:  ICE_AGRIF domain is  300 km x 300 Km x 10 m
+         kpi = NINT( 300.e3 / rn_dx ) - 1
+         kpj = NINT( 300.e3 / rn_dy ) - 1
+      ELSE
+         kpi = nbcellsx + 2 + 2*nbghostcells
+         kpj = nbcellsy + 2 + 2*nbghostcells
+      ENDIF
+      kpk = 1
+      !
+!!      zlx = (kpi-2)*rn_dx*1.e-3
+!!      zly = (kpj-2)*rn_dy*1.e-3
+      zlx = kpi*rn_dx*1.e-3
+      zly = kpj*rn_dy*1.e-3
+      !
+      IF( Agrif_Root() ) THEN   ;   kperio = 7     ! ICE_AGRIF configuration : bi-periodic basin
+      ELSE                      ;   kperio = 0     ! closed periodicity for the zoom
+      ENDIF
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ICE_ADV2D test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      horizontal resolution                    rn_dy  = ', rn_dy, ' meters'
+         WRITE(numout,*) '      ICE_ADV2D domain = 300 km x 300Km x 1 grid-point '
+         WRITE(numout,*) '         LX [km]: ', zlx
+         WRITE(numout,*) '         LY [km]: ', zly
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '         Coriolis:', ln_corio
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ICE_ADV2D : bi-periodic basin            jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,164 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  ICE_ADV2D configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ICE_ADV2D case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   USE ice, ONLY       : at_i_b, a_i_b
+   USE icethd_dh       ! for CALL ice_thd_snwblow
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called by sbcmod.F90 for sbc ocean
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ICE_ADV2D case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp)   WRITE(numout,*)' usrdef_sbc_oce : ICE_ADV2D case: NO surface forcing'
+         ! --- oce variables --- !
+         utau(:,:) = 0._wp 
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !
+         utau_b(:,:) = 0._wp 
+         vtau_b(:,:) = 0._wp
+         emp_b (:,:) = 0._wp
+         sfx_b (:,:) = 0._wp
+         qns_b (:,:) = 0._wp
+         !
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (momentum) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_ADV2D case: constant stress forcing'
+      !
+      utau_ice(:,:) = 1.3_wp   ! <=> 0.5 m/s
+      vtau_ice(:,:) = 0._wp
+      !
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (flux) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   phi    ! ice thickness
+      !!
+      INTEGER  ::   jl
+      REAL(wp) ::   zfr1, zfr2                 ! local variables
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsnw   ! snw distribution after wind blowing
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztri
+      !!---------------------------------------------------------------------
+      !
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_ADV2D case: NO flux forcing'
+      !
+      ! ocean variables (renaming)
+      emp_oce (:,:)   = 0._wp   ! uniform value for freshwater budget (E-P)
+      qsr_oce (:,:)   = 0._wp   ! uniform value for     solar radiation
+      qns_oce (:,:)   = 0._wp   ! uniform value for non-solar radiation
+
+      ! ice variables
+      alb_ice (:,:,:) = 0.7_wp  ! useless
+      qsr_ice (:,:,:) = 0._wp   ! uniform value for     solar radiation
+      qns_ice (:,:,:) = 0._wp   ! uniform value for non-solar radiation
+      sprecip (:,:)   = 0._wp   ! uniform value for snow precip
+      evap_ice(:,:,:) = 0._wp   ! uniform value for sublimation
+
+      ! ice fields deduced from above
+      zsnw(:,:) = 1._wp
+      !!CALL lim_thd_snwblow( at_i_b, zsnw )  ! snow distribution over ice after wind blowing 
+      emp_ice  (:,:)   = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw(:,:)
+      emp_oce  (:,:)   = emp_oce(:,:) - sprecip(:,:) * (1._wp - zsnw(:,:) )
+      qevap_ice(:,:,:) =   0._wp
+      qprec_ice(:,:)   =   rhos * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) !  in J/m3
+      qemp_oce (:,:)   = - emp_oce(:,:) * sst_m(:,:) * rcp
+      qemp_ice (:,:)   =   sprecip(:,:) * zsnw * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) ! solid precip (only)
+
+      ! total fluxes
+      emp_tot (:,:) = emp_ice  + emp_oce
+      qns_tot (:,:) = at_i_b(:,:) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 ) + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot (:,:) = at_i_b(:,:) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- shortwave radiation transmitted below the surface (W/m2, see Grenfell Maykut 77) --- !
+      cloud_fra(:,:) = pp_cldf
+      ztri(:,:) = 0.18 * ( 1.0 - cloud_fra(:,:) ) + 0.35 * cloud_fra(:,:)  ! surface transmission when hi>10cm
+      !
+      DO jl = 1, jpl
+         WHERE    ( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) <  0.1_wp )     ! linear decrease from hi=0 to 10cm  
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ( ztri(:,:) + ( 1._wp - ztri(:,:) ) * ( 1._wp - phi(:,:,jl) * 10._wp ) )
+         ELSEWHERE( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) >= 0.1_wp )     ! constant (ztri) when hi>10cm
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ztri(:,:)
+         ELSEWHERE                                                         ! zero when hs>0
+            qtr_ice_top(:,:,jl) = 0._wp
+         END WHERE
+      ENDDO
+         
+ 
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,111 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===      ICE_ADV2D case     ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk, k_dz  ! dummy indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ICE_ADV2D configuration '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   (slab ocean - advection of an ice patch in a biperiodic square box domain)'
+      !
+      !
+      ! type of vertical coordinate  ==>>>   here ICE_ADV2D : slab ocean always
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-full-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! 
+      k_dz = 1
+      DO jk = 1, jpk
+         pdepw_1d(jk) =    k_dz
+         pdept_1d(jk) =    k_dz
+         pe3w_1d (jk) =    k_dz
+         pe3t_1d (jk) =    k_dz
+      END DO
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      k_top(:,:) = 1
+      !
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !                                !* bottom ocean compute from the depth of grid-points
+      jpkm1 = jpk
+      k_bot(:,:) = 1    ! here use k_top as a land mask
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/cpp_ICE_ADV2D.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/cpp_ICE_ADV2D.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_ADV2D/cpp_ICE_ADV2D.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys key_si3 key_mpp_mpi key_nosignedzero key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_context_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link context_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_cfg	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_AGRIF configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_AGRIF user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    1000.   ! horizontal resolution in meters
+   rn_dy       =    1000.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis to 0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_AGRIF" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =    1500      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 400.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_AGRIF_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                   (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                           (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  !  =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,96 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .true.          !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   0.5           !        prescribed ice u-velocity
+      rn_vice       =   0.5           !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .false.          !  activate ice initialization (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/1_namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
@@ -0,0 +1,3 @@
+1
+34 63 34 63 3 3 3
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_1ghost
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_1ghost	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_1ghost	(revision 14097)
@@ -0,0 +1,3 @@
+1
+36 65 36 65 3 3 3
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_3ghosts
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_3ghosts	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/AGRIF_FixedGrids.in_3ghosts	(revision 14097)
@@ -0,0 +1,3 @@
+1
+34 63 34 63 3 3 3
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/README
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/README	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/README	(revision 14097)
@@ -0,0 +1,40 @@
+-------
+Purpose
+-------
+This demonstration case can be used to study the advection of a patch of ice in a bi-periodic channel
+with a slab ocean (i.e. 1 ocean layer) and an agrif zoom in the center
+
+-----------
+Experiments
+-----------
+Two experiments can be configured:
+
+a) A simple channel at 3km horizontal resolution (slightly variable => +- 10%)
+              ==> in MY_SRC/usrdef_hgr.F90, uncomment the part "variable scale factors" and comment part "constant scale factors"
+
+b) A simple channel at 3km horizontal resolution (constant scale factors)
+              ==> in MY_SRC/usrdef_hgr.F90, comment the part "variable scale factors" and uncomment part "constant scale factors"
+
+----------
+How to run
+----------
+
+a) Compile and run the model once to get a mesh_mask.nc file with the following command:
+../../../makenemo -r ICE_AGRIF -n ICE_AGRIF -m X64_ADA -j 4
+mpirun ./nemo -np 1
+
+b) Create the initial condition file for sea-ice (initice.nc) by running this python script: 
+python ./make_INITICE.py
+
+c) Run the model a second time
+mpirun ./nemo -np 4
+
+---------------
+What to look at
+---------------
+the advection through an agrif zoom 1:3
+   for a square (ice concentration) or a gaussian (ice volume)
+      with either a constant velocity (ln_dynADV2D=T and define rn_uice & rn_vice)
+               or a constant ice-atm. stress, thus velocity is calculated by rheology (ln_dynRHGADV=T)
+      with 1 or 5 ice categories (jpl=1 or 5)
+         (note that ln_dynADV2D=T only works with jpl=1)
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,50 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+<!-- $id$ -->
+    <variable_definition>
+    <!-- Year of time origin for NetCDF files; defaults to 1800 -->
+       <variable id="ref_year" type="int"   > 1800 </variable>
+       <variable id="rau0"     type="float" > 1026.0 </variable>
+       <variable id="cpocean"  type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu" type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"    type="float" > 917.0 </variable>
+       <variable id="rhosn"    type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>
+    </variable_definition>
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>    <!--  NEMO ocean dynamics     -->
+    <field_definition src="./field_def_nemo-ice.xml"/>    <!--  NEMO sea-ice model      -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics      -->
+    <file_definition src="./file_def_nemo-ice.xml"/>     <!--  NEMO sea-ice model       -->
+    <!-- 
+============================================================================================================
+= 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="1"                 />
+      <axis id="ncatice" long_name="Ice category"       unit="1"                 />
+      <axis id="iax_20C" long_name="20 degC isotherm"   unit="degC"              />
+      <axis id="iax_28C" long_name="28 degC isotherm"   unit="degC"              />
+      <axis id="deptht_surface" axis_ref="deptht" > 
+	<zoom_axis begin=" 1 " n=" 1 " /> 
+      </axis>
+    </axis_definition>
+ 
+    <domain_definition src="./domain_def_nemo.xml"/>
+  
+    <grid_definition src="./grid_def_nemo.xml"/>
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-ice.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-ice.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-ice.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-ice.xml	(revision 14097)
@@ -0,0 +1,105 @@
+<?xml version="1.0"?>
+    <!-- $id$ -->
+    
+ <!--
+============================================================================================================
+=                                           output files definition                                        =
+============================================================================================================
+  -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+    
+      <file_group id="5ts" output_freq="5ts"  output_level="10" enabled=".TRUE.">  <!-- 1 day files -->   	
+
+	<file id="file1" name_suffix="_icemod" description="ice variables" enabled=".true." >
+
+        <!-- ice mask -->
+        <field field_ref="icemask"          name="simsk"   />
+
+        <!-- general -->
+        <field field_ref="snwvolu"          name="snvolu" />
+        <field field_ref="icethic"          name="sithic" />
+        <field field_ref="icethic"          name="sithic_max" operation="maximum" />
+        <field field_ref="icethic"          name="sithic_min" operation="minimum" />
+        <field field_ref="fasticepres"      name="fasticepres" />
+        <field field_ref="icevolu"          name="sivolu" />
+        <field field_ref="iceconc"          name="siconc" />
+        <field field_ref="icesalt"          name="sisali" />
+        <field field_ref="iceapnd"          name="siapnd" />
+        <field field_ref="icevpnd"          name="sivpnd" />
+        <field field_ref="sst_m"            name="sst_m"  />
+        <field field_ref="sss_m"            name="sss_m"  />
+
+        <!-- heat -->
+        <field field_ref="icetemp"          name="sitemp" />
+        <field field_ref="icettop"          name="sittop" />
+        <field field_ref="icetbot"          name="sitbot" />
+        <field field_ref="icetsni"          name="sitsni" />
+
+        <!-- momentum -->
+        <field field_ref="uice"             name="sivelu"  />
+        <field field_ref="vice"             name="sivelv"  />
+        <field field_ref="icevel"           name="sivelo"  />
+        <field field_ref="utau_ai"          name="utau_ai" />
+        <field field_ref="vtau_ai"          name="vtau_ai" />
+        <field field_ref="utau_oi"          name="utau_oi" />
+        <field field_ref="vtau_oi"          name="vtau_oi" />
+
+        <!-- rheology -->
+        <field field_ref="icediv"           name="sidive"  />
+        <field field_ref="iceshe"           name="sishea"  />
+        <field field_ref="icestr"           name="sistre"  />
+        <field field_ref="normstr"          name="normstr" />
+        <field field_ref="sheastr"          name="sheastr" />
+
+        <!-- heat fluxes -->
+        <field field_ref="qt_oce_ai"        name="qt_oce_ai"  />
+        <field field_ref="qt_atm_oi"        name="qt_atm_oi"  />
+        <field field_ref="qtr_ice_top"      name="qtr_ice_top"/>
+        <field field_ref="qtr_ice_bot"      name="qtr_ice_bot"/>
+        <field field_ref="qt_ice"           name="qt_ice"     />
+        <field field_ref="qsr_ice"          name="qsr_ice"    />
+        <field field_ref="qns_ice"          name="qns_ice"    />
+        <field field_ref="qemp_ice"         name="qemp_ice"   />
+        <field field_ref="albedo"           name="albedo"     />
+
+        <field field_ref="hfxcndtop"        name="hfxcndtop"  />
+        <field field_ref="hfxcndbot"        name="hfxcndbot"  />
+        <field field_ref="hfxsensib"        name="hfxsensib"  />
+
+        <!-- salt fluxes -->
+        <field field_ref="sfxice"           name="sfxice" />
+
+        <!-- mass fluxes -->
+        <field field_ref="vfxice"           name="vfxice" />
+        <field field_ref="vfxsnw"           name="vfxsnw" />
+
+        <!-- categories -->
+        <field field_ref="icemask_cat"      name="simskcat"/>
+        <field field_ref="snwthic_cat"      name="snthicat"/>
+        <field field_ref="iceconc_cat"      name="siconcat"/>
+        <field field_ref="icethic_cat"      name="sithicat"/>
+        <field field_ref="icesalt_cat"      name="sisalcat"/>
+        <field field_ref="icetemp_cat"      name="sitemcat"/>
+
+        </file>
+
+      </file_group>
+
+      <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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+
+<!--
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own filesfor ocean dynamics context                                         =
+=                                         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="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d 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="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>
+    
+
+
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<simulation> 
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+	  <!--
+          <variable id="optimal_buffer_size"       type="string">memory</variable>
+          <variable id="buffer_size_factor"        type="double">1.0</variable>
+	  -->
+	  <variable id="info_level"                type="int">10</variable>
+	  <variable id="using_server"              type="bool">false</variable>
+	  <variable id="using_oasis"               type="bool">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  <context id="1_nemo" src="./1_context_nemo.xml"/>
+<!--
+  <context id="2_nemo" src="./2_context_nemo.xml"/>  
+-->
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/make_INITICE.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/make_INITICE.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/make_INITICE.py	(revision 14097)
@@ -0,0 +1,127 @@
+#!/usr/bin/python
+
+import os,sys
+from netCDF4 import Dataset as netcdf
+import numpy as np
+import matplotlib.pyplot as plt
+from math import exp
+from math import ceil
+
+resname=''
+
+# input file
+fcoord='mesh_mask.nc'
+
+# output file
+fflx='initice.nc'
+
+print '   creating init ice file  ' +fflx
+
+# Reading coordinates file
+nccoord=netcdf(fcoord,'r')
+nav_lon=nccoord.variables['nav_lon']
+nav_lat=nccoord.variables['nav_lat']
+time_counter=1
+LON1= nav_lon.shape[1]
+LAT1= nav_lon.shape[0]
+print 'nav_lon.shape[1]' ,nav_lon.shape[1]
+print 'LON1 ', LON1
+print 'LAT1 ', LAT1
+
+# Creating INITICE netcdf file
+nc=netcdf(fflx,'w')
+nc.createDimension('y',LAT1)
+nc.createDimension('x',LON1)
+nc.createDimension('time_counter',None)    # Setting dimension size to 0 or None makes it unlimited. 
+
+cdflon=nc.createVariable('nav_lon','f',('y','x'))
+cdflat=nc.createVariable('nav_lat','f',('y','x'))
+cdftimecounter=nc.createVariable('time_counter','f',('time_counter'))
+
+# ati : Fraction of open waters in sea ice - units %
+# hti : Sea ice thickness - units m
+# hts : Snow thickness - units m
+# smi : Sea ice salinity:
+# tmi : Sea ice internal temperature - units K
+# tsu : Sea ice surface temperature - units K
+#
+# Take constant values from namelist &namiceini of NEMO
+rn_hti_ini=2.0
+rn_hts_ini=0.2            #  initial real snow thickness (m)
+rn_ati_ini=0.9            #  initial ice concentration   (-)
+rn_smi_ini=6.3            #  initial ice salinity     (g/kg)
+rn_tmi_ini=270.           #  initial ice/snw temperature (K)
+rn_tsu_ini=270.           #  initial sea ice temperature (K)
+#
+cdfati=nc.createVariable('ati','f',('time_counter','y','x'))
+cdfati.units='Percentage'
+cdfati.long_name='Sea ice concentration'
+cdfhti=nc.createVariable('hti','f',('time_counter','y','x'))
+cdfhti.long_name='Sea ice thickness'
+cdfhti.units='m'
+cdfhts=nc.createVariable('hts','f',('time_counter','y','x'))
+cdfhts.long_name='Snow thickness'
+cdfhts.units='m'
+cdfsmi=nc.createVariable('smi','f',('time_counter','y','x'))
+cdfsmi.long_name='Sea ice salinity'
+cdfsmi.units='pss'
+cdftmi=nc.createVariable('tmi','f',('time_counter','y','x'))
+cdftmi.long_name='Sea ice internal temperature'
+cdftmi.units='Kelvin'
+cdftsu=nc.createVariable('tsu','f',('time_counter','y','x'))
+cdftsu.long_name='Sea ice surface temperature'
+cdftsu.units='Kelvin'
+
+cdflon[:,:]=nav_lon[:,:]
+cdflat[:,:]=nav_lat[:,:]
+cdftimecounter[0]=1
+
+# Fill fields
+#print 'cdfati[:,1]', cdfati[:,1]  -> 32 values
+
+# Add a gaussian for sea ice thickness here
+cdfhti[:,:,:]=0.
+cdfhts[:,:,:]=0.
+cdfati[:,:,:]=0.
+cdfsmi[:,:,:]=0.
+cdftmi[:,:,:]=rn_tmi_ini
+cdftsu[:,:,:]=rn_tsu_ini
+
+# --------------------------------------
+# for basin=99x99km with dx=1km ; dy=1km
+#sigx=-0.04
+#sigy=-0.04
+#xshift=50.-1.
+#yshift=50.-1.
+#dlat=21
+#dlon=21
+
+# --- gaussian and square experiment ---
+#for y in np.arange(dlat,LAT1-dlat,1) :
+#    for x in np.arange(dlon,LON1-dlon,1) :
+#        cdfhti[:,y,x] = rn_hti_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+#        cdfhts[:,y,x] = rn_hts_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+#        cdfati[:,y,x] = rn_ati_ini
+#        cdfsmi[:,y,x] = rn_smi_ini
+#
+            
+# ----------------------------------------------
+# for basin=300x300km with dx=3km ; dy=3km + AGRIF
+sigx=-0.012
+sigy=-0.012
+xshift=20.-1.
+yshift=50.-1.
+dlat=18
+dlon=18
+for y in np.arange(32,66,1) :
+    for x in np.arange(2,36,1) :
+        cdfhti[:,y,x] = rn_hti_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+        cdfhts[:,y,x] = rn_hts_ini*exp(sigx*(x-xshift)**2)*exp(sigy*(y-yshift)**2)
+        cdfati[:,y,x] = rn_ati_ini   
+        cdfsmi[:,y,x] = rn_smi_ini
+# ------------------------------------------------
+
+nc.close()
+nccoord.close()
+
+#sys.exit()
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,236 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!               ICE_AGRIF configuration                              !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   ICE_AGRIF user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    3000.   ! horizontal resolution in meters
+   rn_dy       =    3000.   ! horizontal resolution in meters
+   ln_corio    =    .false. ! set coriolis=0 (false) or not (true)
+      rn_ppgphi0  =  70.    ! Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0      !  job number (no more used...)
+   cn_exp      =  "ICE_AGRIF" !  experience name
+   nn_it000    =       1      !  first time step
+   nn_itend    =     500      !  last  time step (std 5475)
+   nn_istate   =       1      !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .true.    !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_rdt      = 1200.     !  time step for the dynamics (and tracer if nn_acc=0)
+   !
+   ln_meshmask = .true.   !  =T  create a mesh file
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.    !  (=T) read the domain configuration file
+      !                     !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+      cn_domcfg = "ICE_AGRIF_domcfg"    ! domain configuration filename
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_usr      = .true.   !  user defined formulation                  (T => check usrdef_sbc)
+   ln_blk      = .false.  !  Bulk formulation                          (T => fill namsbc_blk )
+   nn_fsbc     =  1       !  frequency of surface boundary condition computation
+   nn_ice      =  2       !  sea-ice model
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   Stand-Alone Surface module: ocean data               (SAS_SRC  only)
+!-----------------------------------------------------------------------
+   l_sasread   = .false.  ! =T Read in file ;  =F set all to 0. (see sbcssm.F90)
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10    = .true.         !  = Use TEOS-10 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.    !  FCT scheme
+      nn_fct_h   =  4               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!----------------------------------------------------------------------------------
+   ln_traldf_OFF    =  .true.   !    laplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .true. !  linear dynamics (no momentum advection)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .true.   !  z-coordinate - full steps
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_OFF = .true.     !  No operator (i.e. no explicit diffusion)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_zdfcst   = .true.       !  constant mixing
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_cfg	(revision 14097)
@@ -0,0 +1,105 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! SI3 configuration namelist: Overwrites SHARED/namelist_ice_ref
+!!              1 - Generic parameters                 (nampar)
+!!              2 - Ice thickness discretization       (namitd)
+!!              3 - Ice dynamics                       (namdyn)
+!!              4 - Ice ridging/rafting                (namdyn_rdgrft)
+!!              5 - Ice rheology                       (namdyn_rhg)
+!!              6 - Ice advection                      (namdyn_adv)
+!!              7 - Ice surface boundary conditions    (namsbc)
+!!              8 - Ice thermodynamics                 (namthd)
+!!              9 - Ice heat diffusion                 (namthd_zdf)
+!!             10 - Ice lateral melting                (namthd_da)
+!!             11 - Ice growth in open water           (namthd_do)
+!!             12 - Ice salinity                       (namthd_sal)
+!!             13 - Ice melt ponds                     (namthd_pnd)
+!!             14 - Ice initialization                 (namini)
+!!             15 - Ice/snow albedos                   (namalb)
+!!             16 - Ice diagnostics                    (namdia)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!------------------------------------------------------------------------------
+&nampar         !   Generic parameters
+!------------------------------------------------------------------------------
+   ln_icedyn        = .true.          !  ice dynamics (T) or not (F)
+   ln_icethd        = .false.         !  ice thermo   (T) or not (F)
+/
+!------------------------------------------------------------------------------
+&namitd         !   Ice discretization
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn         !   Ice dynamics
+!------------------------------------------------------------------------------
+   ln_dynALL        = .false.         !  dyn.: full ice dynamics               (rheology + advection + ridging/rafting + correction)
+   ln_dynRHGADV     = .true.          !  dyn.: no ridge/raft & no corrections  (rheology + advection)
+   ln_dynADV1D      = .false.         !  dyn.: only advection 1D                  (Schar & Smolarkiewicz 1996 test case)
+   ln_dynADV2D      = .false.         !  dyn.: only advection 2D w prescribed vel.(rn_uvice + advection)
+      rn_uice       =   0.5           !        prescribed ice u-velocity
+      rn_vice       =   0.5           !        prescribed ice v-velocity
+/
+!------------------------------------------------------------------------------
+&namdyn_rdgrft  !   Ice ridging/rafting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_rhg     !   Ice rheology
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdyn_adv     !   Ice advection
+!------------------------------------------------------------------------------
+   ln_adv_Pra       = .false.         !  Advection scheme (Prather)
+   ln_adv_UMx       = .true.          !  Advection scheme (Ultimate-Macho)
+      nn_UMx        =   5             !     order of the scheme for UMx (1-5 ; 20=centered 2nd order)
+/
+!------------------------------------------------------------------------------
+&namsbc         !   Ice surface boundary conditions
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd         !   Ice thermodynamics
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_zdf     !   Ice heat diffusion
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_da      !   Ice lateral melting
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_do      !   Ice growth in open water
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_sal     !   Ice salinity
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namthd_pnd     !   Melt ponds
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namini         !   Ice initialization
+!------------------------------------------------------------------------------
+   ln_iceini        = .true.          !  activate ice initialization (T) or not (F)
+   nn_iceini_file   =  1              !  netcdf file provided for initialization 
+
+   sn_hti = 'initice'                 , -12 ,'hti'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_hts = 'initice'                 , -12 ,'hts'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_ati = 'initice'                 , -12 ,'ati'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tsu = 'initice'                 , -12 ,'tsu'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_tmi = 'initice'                 , -12 ,'tmi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   sn_smi = 'initice'                 , -12 ,'smi'   ,  .false.  , .true., 'yearly'  , '' , '', ''
+   cn_dir='./'
+/
+!------------------------------------------------------------------------------
+&namalb         !   albedo parameters
+!------------------------------------------------------------------------------
+/
+!------------------------------------------------------------------------------
+&namdia         !   Diagnostics
+!------------------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ice_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ice_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,162 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  ICE_AGRIF configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ICE_AGRIF configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, ln_corio, rn_ppgphi0   ! horizontal resolution in meters
+   !                                                            coriolis and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ICE_AGRIF configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : ICE_AGRIF configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          f-plane with irregular grid-spacing (+- 10%)'
+      IF(lwp) WRITE(numout,*) '          the max is given by rn_dx and rn_dy' 
+
+      !                          ==========
+      zlam0 = -(jpiglo-1)/2 * 1.e-3 * rn_dx
+      zphi0 = -(jpjglo-1)/2 * 1.e-3 * rn_dy
+
+#if defined key_agrif 
+      IF( .NOT. Agrif_Root() ) THEN
+!clem         zlam0  = Agrif_Parent(zlam0) + (Agrif_ix())*Agrif_Parent(rn_dx) * 1.e-5
+!clem         zphi0  = Agrif_Parent(zphi0) + (Agrif_iy())*Agrif_Parent(rn_dy) * 1.e-5
+         zlam0 = ( 0.5_wp - ( Agrif_parent(jpiglo) - 1 ) / 2 ) * 1.e-3 * Agrif_irhox() * rn_dx  &
+            &  + ( Agrif_Ix() + nbghostcells - 1 ) * Agrif_irhox() * rn_dx * 1.e-3 - ( 0.5_wp + nbghostcells ) * rn_dx * 1.e-3
+         zphi0 = ( 0.5_wp - ( Agrif_parent(jpjglo) - 1 ) / 2 ) * 1.e-3 * Agrif_irhoy() * rn_dy  &
+            &  + ( Agrif_Iy() + nbghostcells - 1 ) * Agrif_irhoy() * rn_dy * 1.e-3 - ( 0.5_wp + nbghostcells ) * rn_dy * 1.e-3
+      ENDIF
+#endif         
+
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+            zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+            plamt(ji,jj) = zlam0 + rn_dx * 1.e-3 * zti
+            plamu(ji,jj) = zlam0 + rn_dx * 1.e-3 * zui
+            plamv(ji,jj) = plamt(ji,jj) 
+            plamf(ji,jj) = plamu(ji,jj) 
+   
+            pphit(ji,jj) = zphi0 + rn_dy * 1.e-3 * ztj
+            pphiv(ji,jj) = zphi0 + rn_dy * 1.e-3 * zvj
+            pphiu(ji,jj) = pphit(ji,jj) 
+            pphif(ji,jj) = pphiv(ji,jj) 
+         END DO
+      END DO
+         
+         ! Horizontal scale factors (in meters)
+         !                              ======
+!! ==> EITHER 1) variable scale factors
+!! clem: This can be used with a 1proc simulation but I think it breaks repro when >1procs are used      
+!!         DO jj = 1, jpj
+!!            DO ji = 1, jpi
+!!               !!pe1t(ji,jj) = rn_dx * EXP( -0.8/REAL(jpiglo**2) * (mi0(ji)-REAL(jpiglo+1)*0.5)**2 )  ! gaussian shape
+!!               !!pe2t(ji,jj) = rn_dy * EXP( -0.8/REAL(jpjglo**2) * (mj0(jj)-REAL(jpjglo+1)*0.5)**2 )  ! gaussian shape
+!!               pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5) ) ! linear shape
+!!               pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5) ) ! linear shape
+!!            END DO
+!!         END DO
+!!#if defined key_agrif 
+!!         IF( .NOT. Agrif_Root() ) THEN ! only works if the zoom is positioned at the center of the parent grid
+!!            DO jj = 1, jpj
+!!               DO ji = 1, jpi
+!!                  pe1t(ji,jj) = rn_dx * ( 1. -0.1 * ABS(REAL(mi0(ji))-REAL(jpiglo+1)*0.5) / (1.-REAL(jpiglo+1)*0.5)  &
+!!                     &                            * REAL(jpiglo) / REAL(Agrif_Parent(jpiglo) * Agrif_Rhox()) )       ! factor to match parent grid
+!!                  pe2t(ji,jj) = rn_dy * ( 1. -0.1 * ABS(REAL(mj0(jj))-REAL(jpjglo+1)*0.5) / (1.-REAL(jpjglo+1)*0.5)  &
+!!                     &                            * REAL(jpjglo) / REAL(Agrif_Parent(jpjglo) * Agrif_Rhoy()) )       ! factor to match parent grid
+!!               END DO
+!!            END DO
+!!         ENDIF
+!!#endif
+!! ==> OR 2) constant scale factors
+         pe1t(:,:) = rn_dx
+         pe2t(:,:) = rn_dy
+!! ==> END
+         
+      pe1u(:,:) = pe1t(:,:)      ;      pe2u(:,:) = pe2t(:,:)
+      pe1v(:,:) = pe1t(:,:)      ;      pe2v(:,:) = pe2t(:,:)
+      pe1f(:,:) = pe1t(:,:)      ;      pe2f(:,:) = pe2t(:,:)
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      IF( ln_corio ) THEN
+         zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+         zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+         pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+         pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      ELSE
+         pff_f(:,:) = 0.
+         pff_t(:,:) = 0.
+      ENDIF
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,125 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  ICE_AGRIF configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                               !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dy      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_ppgphi0 ! reference latitude for beta-plane 
+   LOGICAL , PUBLIC ::   ln_corio   ! set coriolis at 0 (ln_corio=F) or not 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ICE_AGRIF configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios       ! Local integer
+      REAL(wp)::   zlx, zly  ! Local scalars
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dy, ln_corio, rn_ppgphi0
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+#if defined key_agrif 
+      ! Domain parameters are taken from parent:
+      IF( .NOT. Agrif_Root() ) THEN
+         rn_dx = Agrif_Parent(rn_dx)/Agrif_Rhox()
+         rn_dy = Agrif_Parent(rn_dy)/Agrif_Rhoy()
+         rn_ppgphi0 = Agrif_Parent(rn_ppgphi0)
+      ENDIF
+#endif
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ICE_AGRIF'           ! name & resolution (not used)
+      kk_cfg = NINT( rn_dx )
+      !
+      IF( Agrif_Root() ) THEN        ! Global Domain size:  ICE_AGRIF domain is  300 km x 300 Km x 10 m
+         kpi = NINT( 300.e3 / rn_dx ) - 1
+         kpj = NINT( 300.e3 / rn_dy ) - 1
+      ELSE
+         kpi = nbcellsx + 2 + 2*nbghostcells
+         kpj = nbcellsy + 2 + 2*nbghostcells
+      ENDIF
+      kpk = 2
+      !
+!!      zlx = (kpi-2)*rn_dx*1.e-3
+!!      zly = (kpj-2)*rn_dy*1.e-3
+      zlx = kpi*rn_dx*1.e-3
+      zly = kpj*rn_dy*1.e-3
+      !
+      IF( Agrif_Root() ) THEN   ;   kperio = 7     ! ICE_AGRIF configuration : bi-periodic basin
+      ELSE                      ;   kperio = 0     ! closed periodicity for the zoom
+      ENDIF
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ICE_AGRIF test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      horizontal resolution                    rn_dy  = ', rn_dy, ' meters'
+         WRITE(numout,*) '      ICE_AGRIF domain = 300 km x 300Km x 1 grid-point '
+         WRITE(numout,*) '         LX [km]: ', zlx
+         WRITE(numout,*) '         LY [km]: ', zly
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '         Coriolis:', ln_corio
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ICE_AGRIF : bi-periodic basin            jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,163 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  ICE_AGRIF configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ICE_AGRIF case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   USE ice, ONLY       : at_i_b, a_i_b
+   USE icethd_dh       ! for CALL ice_thd_snwblow
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called by sbcmod.F90 for sbc ocean
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ICE_AGRIF case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp)   WRITE(numout,*)' usrdef_sbc_oce : ICE_AGRIF case: NO surface forcing'
+         ! --- oce variables --- !
+         utau(:,:) = 0._wp 
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !
+         utau_b(:,:) = 0._wp 
+         vtau_b(:,:) = 0._wp
+         emp_b (:,:) = 0._wp
+         sfx_b (:,:) = 0._wp
+         qns_b (:,:) = 0._wp
+         !
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_tau  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (momentum) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_AGRIF case: constant stress forcing'
+      !
+      utau_ice(:,:) = 1.3_wp   ! <=> 0.5 m/s
+      vtau_ice(:,:) = 0._wp
+      !
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt, phs, phi )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE usrdef_sbc_ice_flx  ***
+      !!
+      !! ** Purpose :   provide the surface boundary (flux) condition over sea-ice
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phs    ! snow thickness
+      REAL(wp), DIMENSION(:,:,:), INTENT(in)  ::   phi    ! ice thickness
+      !!
+      INTEGER  ::   jl
+      REAL(wp) ::   zfr1, zfr2                 ! local variables
+      REAL(wp), DIMENSION(jpi,jpj) ::   zsnw   ! snw distribution after wind blowing
+      REAL(wp), DIMENSION(jpi,jpj) ::   ztri
+      !!---------------------------------------------------------------------
+      !
+      IF( kt==nit000 .AND. lwp)   WRITE(numout,*)' usrdef_sbc_ice : ICE_AGRIF case: NO flux forcing'
+      !
+      ! ocean variables (renaming)
+      emp_oce (:,:)   = 0._wp   ! uniform value for freshwater budget (E-P)
+      qsr_oce (:,:)   = 0._wp   ! uniform value for     solar radiation
+      qns_oce (:,:)   = 0._wp   ! uniform value for non-solar radiation
+
+      ! ice variables
+      alb_ice (:,:,:) = 0.7_wp  ! useless
+      qsr_ice (:,:,:) = 0._wp   ! uniform value for     solar radiation
+      qns_ice (:,:,:) = 0._wp   ! uniform value for non-solar radiation
+      sprecip (:,:)   = 0._wp   ! uniform value for snow precip
+      evap_ice(:,:,:) = 0._wp   ! uniform value for sublimation
+
+      ! ice fields deduced from above
+      zsnw(:,:) = 1._wp
+      !!CALL lim_thd_snwblow( at_i_b, zsnw )  ! snow distribution over ice after wind blowing 
+      emp_ice  (:,:)   = SUM( a_i_b(:,:,:) * evap_ice(:,:,:), dim=3 ) - sprecip(:,:) * zsnw(:,:)
+      emp_oce  (:,:)   = emp_oce(:,:) - sprecip(:,:) * (1._wp - zsnw(:,:) )
+      qevap_ice(:,:,:) =   0._wp
+      qprec_ice(:,:)   =   rhos * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) !  in J/m3
+      qemp_oce (:,:)   = - emp_oce(:,:) * sst_m(:,:) * rcp
+      qemp_ice (:,:)   =   sprecip(:,:) * zsnw * ( sst_m(:,:) * rcpi - rLfus ) * tmask(:,:,1) ! solid precip (only)
+
+      ! total fluxes
+      emp_tot (:,:) = emp_ice  + emp_oce
+      qns_tot (:,:) = at_i_b(:,:) * qns_oce(:,:) + SUM( a_i_b(:,:,:) * qns_ice(:,:,:), dim=3 ) + qemp_ice(:,:) + qemp_oce(:,:)
+      qsr_tot (:,:) = at_i_b(:,:) * qsr_oce(:,:) + SUM( a_i_b(:,:,:) * qsr_ice(:,:,:), dim=3 )
+
+      ! --- shortwave radiation transmitted below the surface (W/m2, see Grenfell Maykut 77) --- !
+      cloud_fra(:,:) = pp_cldf
+      ztri(:,:) = 0.18 * ( 1.0 - cloud_fra(:,:) ) + 0.35 * cloud_fra(:,:)  ! surface transmission when hi>10cm
+      !
+      DO jl = 1, jpl
+         WHERE    ( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) <  0.1_wp )     ! linear decrease from hi=0 to 10cm  
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ( ztri(:,:) + ( 1._wp - ztri(:,:) ) * ( 1._wp - phi(:,:,jl) * 10._wp ) )
+         ELSEWHERE( phs(:,:,jl) <= 0._wp .AND. phi(:,:,jl) >= 0.1_wp )     ! constant (ztri) when hi>10cm
+            qtr_ice_top(:,:,jl) = qsr_ice(:,:,jl) * ztri(:,:)
+         ELSEWHERE                                                         ! zero when hs>0
+            qtr_ice_top(:,:,jl) = 0._wp
+         END WHERE
+      ENDDO
+          
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,111 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===      ICE_AGRIF case     ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk, k_dz  ! dummy indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ICE_AGRIF configuration '
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   (slab ocean - advection of an ice patch in a biperiodic square box domain)'
+      !
+      !
+      ! type of vertical coordinate  ==>>>   here ICE_AGRIF : slab ocean always
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-full-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! 
+      k_dz = 1
+      DO jk = 1, jpk
+         pdepw_1d(jk) =    k_dz
+         pdept_1d(jk) =    k_dz
+         pe3w_1d (jk) =    k_dz
+         pe3t_1d (jk) =    k_dz
+      END DO
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      k_top(:,:) = 1
+      !
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !                                !* bottom ocean compute from the depth of grid-points
+      jpkm1 = jpk-1
+      k_bot(:,:) = 1    ! here use k_top as a land mask
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/cpp_ICE_AGRIF.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/cpp_ICE_AGRIF.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ICE_AGRIF/cpp_ICE_AGRIF.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys key_agrif key_si3 key_mpp_mpi key_iomput
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/README
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/README	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/README	(revision 14097)
@@ -0,0 +1,25 @@
+# ISOMIP is a simple TEST_CASE to test the iceshelves in NEMO.
+# no input files are needed (all is prescribed in MY_SRC/usr_def routines
+# for a reference documentation on the ISOMIP test case, see experiement 1 on http://efdl.cims.nyu.edu/project_oisi/isomip/experiments/phase_I/idealized_numerical_models_5.pdf
+
+# default namelist is setup for a 30y run on 32 processors with the minimum output using XIOS in attached mode with single file output
+
+# How to build moc.nc and psi.nc
+   - Download or clone the CDFTOOLS (see https://github.com/meom-group/CDFTOOLS)
+   - Compile all the tools (or at least cdfpsi and cdfmoc) on your cluster (see https://github.com/meom-group/CDFTOOLS#using-cdftools)
+   - if mesh_mask.nc is splitted, you need to rebuild them using the rebuild NEMO tools (see in NEMOGCM/TOOLS) or run 1 (or more) time step on a single processor (nn_itend variable in the namelist). 
+   - set the correct link: ln -s mesh_mask.nc mask.nc ; ln -s mesh_mask.nc mesh_hgr.nc ; ln -s mesh_mask.nc mesh_zgr.nc
+   - run the cdftools : 
+        - cdfmoc ISOMIP_1m_00010101_00301231_grid_V.nc                                       => moc.nc
+        - cdfpsi ISOMIP_1m_00010101_00301231_grid_U.nc ISOMIP_1m_00010101_00301231_grid_V.nc => psi.nc
+
+# How to plt moc/psi and melt (python with netcdf and matplotlib library requiried):
+   - psi.png => python2.7 plot_psi.py -f psi.nc -v sobarstf
+   - moc.png => python2.7 plot_moc.py -f moc.nc -v zomsfglo
+   - mlt.png => python2.7 plot_mlt.py -f ISOMIP_1m_00010101_00301231_grid_T.nc -v sowflisf
+by default the last time frame is plotted.
+
+# location the expected circulation and melt plot after 30y of run:
+   - ISOMIP/EXP00/ISOMIP_psi.png
+   - ISOMIP/EXP00/ISOMIP_moc.png
+   - ISOMIP/EXP00/ISOMIP_mlt.png
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,51 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           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="ssh"          name="sossheig"  />
+          <!-- variable for ice shelf -->
+          <field field_ref="qlatisf"      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>
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,307 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                         ISOMIP configuration                       !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "ISOMIP" !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =  525600   !  last  time step
+   nn_leapy    =       0   !  Leap year calendar (1) or not (0)
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =  99999999 !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =      48   !  frequency of write in the output file   (modulo referenced to nn_it000)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namusr_def    !   ISOMIP user defined namelist  
+!-----------------------------------------------------------------------
+   ln_zps      = .true.    ! z-partial-step coordinate
+   ln_zco      = .false.   ! z-full-step coordinate
+   ln_sco      = .false.   ! s-coordinate
+   rn_e1deg    =   0.3     !  zonal      grid-spacing (degrees)
+   rn_e2deg    =   0.1     !  meridional grid-spacing (degrees)
+   rn_e3       =   30.     !  vertical resolution
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_rdt      = 1800.     !  time step for the dynamics (and tracer if nn_acc=0)
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of surface boundary condition computation
+   ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+   ln_isf      = .true.    !  ice shelf melting/freezing                (T => fill namsbc_isf)
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF)                              (ln_isfcav =T : read (ln_read_cfg=T) 
+!-----------------------------------------------------------------------             or set or usr_def_zgr )
+!              ! file name ! frequency (hours) ! variable ! time interpol. !  clim   ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
+!              !           !  (if <0  months)  !   name   !    (logical)   !  (T/F)  ! 'monthly' ! filename ! pairing  ! filename      !
+! nn_isf == 4
+   sn_fwfisf   = 'rnfisf'  ,         -12.      ,'sowflisf',     .false.    , .true.  , 'yearly'  ,  ''      ,   ''     , ''
+! nn_isf == 3
+   sn_rnfisf   = 'rnfisf'  ,         -12.      ,'sofwfisf',     .false.    , .true.  , 'yearly'  ,  ''      ,   ''     , ''
+! nn_isf == 2 and 3
+   sn_depmax_isf = 'rnfisf' ,        -12.      ,'sozisfmax' ,   .false.    , .true.  , 'yearly'  ,  ''      ,   ''     , ''
+   sn_depmin_isf = 'rnfisf' ,        -12.      ,'sozisfmin' ,   .false.    , .true.  , 'yearly'  ,  ''      ,   ''     , ''
+! nn_isf == 2
+   sn_Leff_isf = 'rnfisf'  ,         -12.      ,'Leff'    ,     .false.    , .true.  , 'yearly'  ,  ''      ,   ''     , ''
+! for all case
+   nn_isf      = 1         !  ice shelf melting/freezing
+                           !  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)
+! 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 or 4
+   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
+! only for nn_isf = 1
+   nn_isfblk   = 1        ! 1 ISOMIP  like: 2 equations formulation (Hunter et al., 2006)
+                          ! 2 ISOMIP+ like: 3 equations formulation (Asay-Davis et al., 2015)
+   nn_gammablk = 0        ! 0 = cst Gammat (= gammat/s)
+                          ! 1 = velocity dependend Gamma (u* * gammat/s)  (Jenkins et al. 2010)
+                          ! 2 = velocity and stability dependent Gamma    (Holland et al. 1999)
+/
+!-----------------------------------------------------------------------
+&namsbc_iscpl  !   land ice / ocean coupling option                     
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .false.   !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .true.     !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .false.    !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_isfcav=T)
+!-----------------------------------------------------------------------
+   rn_Cd0     =  2.5e-3    !  drag coefficient [-]
+   rn_Uc0     =  0.16      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax   =  0.1       !  drag value maximum [-] (logarithmic drag)
+   rn_ke0     =  0.0e-0    !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0      =  3.0e-3    !  roughness [m] (ln_loglayer=T)
+   ln_boost   = .false.    !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.          !  local boost factor  [-]
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+   rn_Cd0     =  1.e-3    !  drag coefficient [-]
+   rn_Uc0     =  0.4      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax   =  0.1      !  drag value maximum [-] (logarithmic drag)
+   rn_ke0     =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0      =  3.e-3    !  roughness [m] (ln_loglayer=T)
+   ln_boost   = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_eos80    = .true.          !  = Use EOS80 equation of state
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_lap   =  .true.   !    laplacian operator
+   ln_traldf_hor   =  .true.   !  horizontal (geopotential)
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 0         !  =  0   constant = 1/2  Ud*Ld   (lap case) 
+      rn_Ud        = 0.02           !  lateral diffusive velocity [m/s]
+      rn_Ld        = 10.e+3         !  lateral diffusive length   [m]
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+      nn_dynkeg  = 0          ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  energy conserving scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_isf  = .true.    !  s-coordinate adapted for isf (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_lev =  .true.     !  iso-level
+   nn_ahm_ijk_t  = 0           !  = 0  constant = 1/2  Uv*Lv   (lap case) 
+      rn_Uv      = 0.12             !  lateral viscous velocity [m/s]
+      rn_Lv      = 10.e+3           !  lateral viscous length   [m]
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+      nn_evdm     =    1         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =   0.1        ! mixing coefficient [m2/s]
+   !                       ! coefficients
+   rn_avm0     =   1.e-3     !  vertical eddy viscosity   [m2/s]
+   rn_avt0     =   5.e-5     !  vertical eddy diffusivity [m2/s]
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_mlt.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_mlt.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_mlt.py	(revision 14097)
@@ -0,0 +1,47 @@
+from netCDF4 import Dataset
+import numpy as np
+from numpy import ma
+import argparse
+import matplotlib.pyplot as plt
+import matplotlib
+
+parser = argparse.ArgumentParser()
+parser.add_argument("-f" , metavar='file_name'   , help="names of input files" , type=str  , nargs="+", required=True )
+parser.add_argument("-v" , metavar='var_name'    , help="variable list"        , type=str  , nargs=1  , required=True )
+args = parser.parse_args()
+
+# read mesh_mask
+ncid   = Dataset('mesh_mask.nc')
+lat2d  = ncid.variables['gphit'    ][  :,:].squeeze()
+lon2d  = ncid.variables['glamt'    ][  :,:].squeeze()
+msk    = ncid.variables['tmaskutil'][0,:,:].squeeze()
+ncid.close()
+
+plt.figure(figsize=np.array([210,210]) / 25.4)
+
+# read psi.nc
+ncid   = Dataset(args.f[0])
+var2d  = ncid.variables[args.v[0]][-1,:,:].squeeze() 
+var2dm = ma.masked_where(msk==0.0,var2d)
+# convert in m/y
+var2dm = var2dm * 86400 * 365 / 1e3
+ncid.close()
+ 
+# define colorbar 
+vlevel=np.arange(-1.6,1.8,0.2)
+pcol = plt.contourf(lon2d,lat2d,var2dm,levels=vlevel,extend='both')
+vlevel=np.arange(-1.6,1.8,0.4)
+matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
+plt.contour(lon2d,lat2d,var2dm,levels=vlevel,colors='k')
+plt.grid()
+plt.title('melt rate ISOMIP (m/y)')
+plt.ylabel('Latitude',fontsize=14)
+plt.xlabel('Longitude',fontsize=14)
+cbar = plt.colorbar(pcol, ticks=vlevel)
+cbar.ax.tick_params(labelsize=14)
+
+# save figure
+plt.savefig('mlt.png', format='png', dpi=300)
+
+plt.show()
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_moc.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_moc.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_moc.py	(revision 14097)
@@ -0,0 +1,60 @@
+from netCDF4 import Dataset
+import numpy as np
+import argparse
+import matplotlib.pyplot as plt
+
+# read argument
+parser = argparse.ArgumentParser()
+parser.add_argument("-f" , metavar='file_name'   , help="names of input files" , type=str  , nargs=1  , required=True )
+parser.add_argument("-v" , metavar='var_name'    , help="variable list"        , type=str  , nargs=1  , required=True )
+args = parser.parse_args()
+
+# read mesh mask
+ncid  = Dataset('mesh_mask.nc')
+vx2d  = ncid.variables['gphit'  ][0,:,0].squeeze()
+vx2dv = ncid.variables['gphiv'  ][0,:,0].squeeze()
+y2d   = ncid.variables['gdepw_0'][0,:,:,1].squeeze()*-1
+y2dt  = ncid.variables['gdept_0'][0,:,:,1].squeeze()*-1
+msk   = ncid.variables['tmask'  ][0,:,:,1].squeeze()
+ncid.close()
+
+# build x 2d array
+x2d=y2d*0.0
+x2dv=y2d*0.0
+for jk in range(0,y2d.shape[0]):
+   x2d[jk,:]=vx2d[:]
+   x2dv[jk,:]=vx2d[:]
+
+plt.figure(figsize=np.array([210,210]) / 25.4)
+
+# read data and mask it
+ncid   = Dataset(args.f[0])
+var2d  = ncid.variables[args.v[0]][-1,:,:,:].squeeze() 
+var2dm = var2d[:,:]
+var2dm[msk==0] = -1
+ncid.close()
+
+# define colorbar
+vlevel=np.arange(0,0.13,0.01)  
+pcol = plt.contourf(x2d,y2d,var2dm,levels=vlevel)
+plt.clf()
+
+# plot contour
+ax = plt.subplot(1, 1, 1)
+ax.contour(x2dv,y2dt,var2dm,levels=vlevel)
+ax.grid()
+ax.set_title('MOC ISOMIP (Sv)')
+ax.set_ylabel('Depth (m)',fontsize=14)
+ax.set_xlabel('Latitude',fontsize=14)
+
+# plot colorbar
+plt.subplots_adjust(left=0.1,right=0.89, bottom=0.1, top=0.89, wspace=0.1, hspace=0.1)
+cax = plt.axes([0.91, 0.1, 0.02, 0.79])
+cbar= plt.colorbar(pcol, ticks=vlevel, cax=cax)
+cbar.ax.tick_params(labelsize=14)
+
+# save figure
+plt.savefig('moc.png', format='png', dpi=300)
+
+plt.show()
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_psi.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_psi.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/EXPREF/plot_psi.py	(revision 14097)
@@ -0,0 +1,52 @@
+from netCDF4 import Dataset
+import numpy as np
+from numpy import ma
+import argparse
+import matplotlib.pyplot as plt
+
+parser = argparse.ArgumentParser()
+parser.add_argument("-f" , metavar='file_name'   , help="names of input files" , type=str  , nargs="+", required=True )
+parser.add_argument("-v" , metavar='var_name'    , help="variable list"        , type=str  , nargs=1  , required=True )
+args = parser.parse_args()
+
+# read mesh_mask
+ncid   = Dataset('mesh_mask.nc')
+lat2d  = ncid.variables['gphit'    ][  :,:].squeeze()
+lon2d  = ncid.variables['glamt'    ][  :,:].squeeze()
+msk    = ncid.variables['tmaskutil'][0,:,:].squeeze()
+ncid.close()
+
+plt.figure(figsize=np.array([210,210]) / 25.4)
+
+# read psi.nc
+ncid   = Dataset(args.f[0])
+var2d  = ncid.variables[args.v[0]][-1,:,:].squeeze() 
+var2dm = ma.masked_where(msk==0.0,var2d)
+# convert in Sv
+var2dm = var2dm / 1e6
+ncid.close()
+ 
+# define colorbar 
+vlevel=np.arange(0.00,0.36,0.02)
+pcol = plt.contourf(lon2d,lat2d,var2dm,levels=vlevel)
+plt.clf()
+
+# plot contour
+ax = plt.subplot(1, 1, 1)
+ax.contour(lon2d,lat2d,var2dm,levels=vlevel)
+ax.grid()
+ax.set_title('PSI ISOMIP (Sv)')
+ax.set_ylabel('Latitude',fontsize=14)
+ax.set_xlabel('Longitude',fontsize=14)
+
+# plot colorbar
+plt.subplots_adjust(left=0.1,right=0.89, bottom=0.1, top=0.89, wspace=0.1, hspace=0.1)
+cax = plt.axes([0.91, 0.1, 0.02, 0.79])
+cbar= plt.colorbar(pcol, ticks=vlevel, cax=cax)
+cbar.ax.tick_params(labelsize=14)
+
+# save figure
+plt.savefig('psi.png', format='png', dpi=300)
+
+plt.show()
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,120 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE usrdef_hgr   ***
+   !!
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)   Original code
+   !!                  ! 2017-02  (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for ISOMIP configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce  ,  ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_e1deg, rn_e2deg   ! horizontal resolution in meters
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                ISOMIP configuration
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zfact, zti, zui, zvi, zfi, ztj, zuj, zvj, zfj      ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'usr_def_hgr : ISOMIP configuration'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*)
+         WRITE(numout,*) '   ===>>  geographical mesh on the sphere with regular grid-spacing'
+         WRITE(numout,*) '          given by rn_e1deg and rn_e2deg'
+      ENDIF
+      !
+      !                       !==  grid point position  ==!   (in degrees)
+      DO jj = 1, jpj
+         DO ji = 1, jpi             ! longitude   (west coast at lon=0°)
+            plamt(ji,jj) = rn_e1deg * (  - 0.5 + REAL( ji-1 + nimpp-1 , wp )  )  
+            plamu(ji,jj) = rn_e1deg * (          REAL( ji-1 + nimpp-1 , wp )  )
+            plamv(ji,jj) = plamt(ji,jj)
+            plamf(ji,jj) = plamu(ji,jj)
+            !                       ! latitude   (south coast at lat= 81°)
+            pphit(ji,jj) = rn_e2deg * (  - 0.5 + REAL( jj-1 + njmpp-1 , wp )  ) - 80._wp
+            pphiu(ji,jj) = pphit(ji,jj)
+            pphiv(ji,jj) = rn_e2deg * (          REAL( jj-1 + njmpp-1 , wp )  ) - 80_wp
+            pphif(ji,jj) = pphiv(ji,jj)
+         END DO
+      END DO
+      !
+      !                       !==  Horizontal scale factors  ==!   (in meters)
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !                       ! e1   (zonal)
+            pe1t(ji,jj) = ra * rad * COS( rad * pphit(ji,jj) ) * rn_e1deg
+            pe1u(ji,jj) = ra * rad * COS( rad * pphiu(ji,jj) ) * rn_e1deg
+            pe1v(ji,jj) = ra * rad * COS( rad * pphiv(ji,jj) ) * rn_e1deg
+            pe1f(ji,jj) = ra * rad * COS( rad * pphif(ji,jj) ) * rn_e1deg
+            !                       ! e2   (meridional)
+            pe2t(ji,jj) = ra * rad * rn_e2deg
+            pe2u(ji,jj) = ra * rad * rn_e2deg
+            pe2v(ji,jj) = ra * rad * rn_e2deg
+            pe2f(ji,jj) = ra * rad * rn_e2deg
+         END DO
+      END DO
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v    = 0               !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 0                       ! Coriolis parameter calculated on the sphere
+      pff_f(:,:) = 0._wp            ! CAUTION: set to zero to avoid error with some compilers that
+      pff_t(:,:) = 0._wp            !             require an initialization of INTENT(out) arguments
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,69 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                  ===  ISOMIP configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-11 (S. Flavoni)             Original code
+   !!                 ! 2017-02 (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce , ONLY : glamt 
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here ISOMIP configuration 
+      !!
+      !! ** Method  : - set temperature field
+      !!              - set salinity    field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  ::   jk     ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : ISOMIP configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with a constant salinity and temperature.      '
+      pu  (:,:,:) = 0._wp        ! ocean at rest
+      pv  (:,:,:) = 0._wp
+      pssh(:,:)   = 0._wp
+      !
+      !                          ! T & S profiles
+      pts(:,:,:,jp_tem) = - 1.9 * ptmask(:,:,:)          ! ISOMIP configuration : start from constant T+S fields
+      pts(:,:,:,jp_sal) =  34.4 * ptmask(:,:,:)
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,109 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                     ===  ISOMIP configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)   Original code
+   !!                 ! 2017-02  (P. Mathiot, S. Flavoni) Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE dom_oce  , ONLY: ln_zco, ln_zps, ln_sco   ! flag of type of coordinate
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                                         !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_e1deg, rn_e2deg   !: horizontal resolution   [degrees]
+   REAL(wp), PUBLIC ::   rn_e3                !: vertical   resolution         [m]
+   
+   REAL(wp), PARAMETER, PUBLIC ::   rbathy = 900._wp   !: depth of the seafloor   [m]
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here ISOMIP configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ ln_zco, ln_zps, ln_sco, rn_e1deg, rn_e2deg, rn_e3
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'ISOMIP'           ! name & resolution (not used)
+      kk_cfg = INT( rn_e3 )
+      !
+      ! Global Domain size:  ISOMIP domain is  15° x 10° x 900 m
+      kpi = INT(  15.0  / rn_e1deg ) + 2     ! add 2 for t-point in the east  & west  coasts
+      kpj = INT(  10.0  / rn_e2deg ) + 2     !     -        -           north & south   -
+      kpk = INT( rbathy / rn_e3    ) + 1     ! add 1 for t-point in the seafloor
+      !
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! ISOMIP configuration : close basin
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : ISOMIP test case'
+         WRITE(numout,*) '      type of vertical coordinate : '
+         WRITE(numout,*) '         z-coordinate flag                     ln_zco   = ', ln_zco
+         WRITE(numout,*) '         z-partial-step coordinate flag        ln_zps   = ', ln_zps
+         WRITE(numout,*) '         s-coordinate flag                     ln_sco   = ', ln_sco
+         WRITE(numout,*) '      resolution'
+         WRITE(numout,*) '         zonal      resolution                 rn_e1deg = ', rn_e1deg, ' degrees'
+         WRITE(numout,*) '         meridional resolution                 rn_e1deg = ', rn_e1deg, ' degrees'
+         WRITE(numout,*) '         vertical   resolution                 rn_e3    = ', rn_e3   , ' meters'
+         WRITE(numout,*) '      ISOMIP domain = 15° x 10° x 900 m'
+         WRITE(numout,*) '         resulting global domain size :        jpiglo   = ', kpi
+         WRITE(numout,*) '                                               jpjglo   = ', kpj
+         WRITE(numout,*) '                                               jpkglo   = ', kpk
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      ISOMIP : closed basin                    jperio   = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,88 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE usrdef_sbc  ***
+   !! 
+   !!                  ===  ISOMIP configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)   user defined interface
+   !!                  ! 2017-02  (P. Mathiot, S. Flavoni) adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in ISOMIP case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for ISOMIP case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : ISOMIP case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,250 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                     ***  MODULE usrdef_zgr  ***
+   !!
+   !!                       ===  ISOMIP case  ===
+   !!
+   !! user defined :  vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec,   S. Flavoni)  Original code
+   !!                 ! 2017-02  (P. Mathiot, S. Flavoni)  Adapt code to ISOMIP case
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!       zgr_z1d   : reference 1D z-coordinate 
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce ,  ONLY: mj0   , mj1   , nimpp , njmpp   ! ocean space and time domain
+   USE dom_oce ,  ONLY: glamt , gphit                   ! ocean space and time domain
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(in   ) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags ( read in namusr_def )
+      LOGICAL                   , INTENT(  out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(  out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(  out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(  out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   ji , jj, jk       ! dummy indices
+      INTEGER  ::   ij0, ij1          ! dummy indices  
+      INTEGER  ::   ik                ! local integers
+      REAL(wp) ::   zfact, z1_jpkm1   ! local scalar
+      REAL(wp) ::   ze3min, zdepth    ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj) ::   zht  , zhu         ! bottom depth
+      REAL(wp), DIMENSION(jpi,jpj) ::   zhisf, zhisfu      ! top depth
+      REAL(wp), DIMENSION(jpi,jpj) ::   zmsk 
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d                ! 2d workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : ISOMIP configuration (z(ps)- or s-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ! set in usrdef_nam.F90 by reading the namusr_def namelist except for ISF
+      ld_isfcav = .TRUE.       ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  isfdraft  ==!
+      !
+      ! the ocean basin surrounded by land (1 grid-point) set through lbc_lnk call as jperio=0 
+      z2d(:,:) = 1._wp                    ! surface ocean is the 1st level
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )        ! closed basin since jperio = 0 (see userdef_nam.F90)
+      zmsk(:,:) = NINT( z2d(:,:) )
+      !
+      !
+      zht  (:,:) = rbathy 
+      zhisf(:,:) = 200._wp
+      ij0 = 1 ; ij1 = 40
+      DO jj = mj0(ij0), mj1(ij1)
+         zhisf(:,jj)=700.0_wp-(gphit(:,jj)+80.0_wp)*125.0_wp
+      END DO
+      zhisf(:,:) = zhisf(:,:) * zmsk(:,:)
+      !
+      CALL zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      IF ( ld_zps ) THEN      !==  zps-coordinate  ==!   (partial bottom-steps)
+         !
+         ze3min = 0.1_wp * rn_e3
+         IF(lwp) WRITE(numout,*) '   minimum thickness of the partial cells = 10 % of e3 = ', ze3min
+         !
+         !                                !* bottom ocean compute from the depth of grid-points
+         k_bot(:,:) = jpkm1
+         DO jk = jpkm1, 1, -1
+            WHERE( zht(:,:) < pdepw_1d(jk) + ze3min )   k_bot(:,:) = jk-1
+         END DO
+         !                                !* top ocean compute from the depth of grid-points
+         k_top(:,:) = 1                   ! 
+         DO jk = 2, jpkm1
+            zdepth = pdepw_1d(jk+1) - ze3min
+            WHERE( zhisf(:,:) > 0.0 .AND. zhisf(:,:) >= zdepth )   k_top(:,:) = (jk + 1) 
+         END DO
+         !
+         !                                   !* vertical coordinate system
+         DO jk = 1, jpk                      ! initialization to the reference z-coordinate
+            pdept(:,:,jk) = pdept_1d(jk)
+            pdepw(:,:,jk) = pdepw_1d(jk)
+            pe3t (:,:,jk) = pe3t_1d (jk)
+            pe3u (:,:,jk) = pe3t_1d (jk)
+            pe3v (:,:,jk) = pe3t_1d (jk)
+            pe3f (:,:,jk) = pe3t_1d (jk)
+            pe3w (:,:,jk) = pe3w_1d (jk)
+            pe3uw(:,:,jk) = pe3w_1d (jk)
+            pe3vw(:,:,jk) = pe3w_1d (jk)
+         END DO
+         DO jj = 1, jpj                      ! top scale factors and depth at T- and W-points
+            DO ji = 1, jpi
+               ik = k_top(ji,jj)
+               IF ( ik > 2 ) THEN
+                  ! pdeptw at the interface
+                  pdepw(ji,jj,ik  ) = MAX( zhisf(ji,jj) , pdepw(ji,jj,ik) )
+                  ! e3t in both side of the interface
+                  pe3t (ji,jj,ik  ) = pdepw(ji,jj,ik+1) - pdepw(ji,jj,ik)
+                  ! pdept in both side of the interface (from previous e3t)
+                  pdept(ji,jj,ik  ) = pdepw(ji,jj,ik  ) + pe3t (ji,jj,ik  ) * 0.5_wp
+                  pdept(ji,jj,ik-1) = pdepw(ji,jj,ik  ) - pe3t (ji,jj,ik  ) * 0.5_wp
+                  ! pe3w on both side of the interface
+                  pe3w (ji,jj,ik+1) = pdept(ji,jj,ik+1) - pdept(ji,jj,ik  )
+                  pe3w (ji,jj,ik  ) = pdept(ji,jj,ik  ) - pdept(ji,jj,ik-1)
+                  ! e3t into the ice shelf
+                  pe3t (ji,jj,ik-1) = pdepw(ji,jj,ik  ) - pdepw(ji,jj,ik-1)
+                  pe3w (ji,jj,ik-1) = pdept(ji,jj,ik-1) - pdept(ji,jj,ik-2)
+               END IF
+            END DO
+         END DO         
+         DO jj = 1, jpj                      ! bottom scale factors and depth at T- and W-points
+            DO ji = 1, jpi
+               ik = k_bot(ji,jj)
+               pdepw(ji,jj,ik+1) = MIN( zht(ji,jj) , pdepw_1d(ik+1) )
+               pe3t (ji,jj,ik  ) = pdepw(ji,jj,ik+1) - pdepw(ji,jj,ik)
+               pe3t (ji,jj,ik+1) = pe3t (ji,jj,ik  ) 
+               !
+               pdept(ji,jj,ik  ) = pdepw(ji,jj,ik  ) + pe3t (ji,jj,ik  ) * 0.5_wp
+               pdept(ji,jj,ik+1) = pdepw(ji,jj,ik+1) + pe3t (ji,jj,ik+1) * 0.5_wp
+               pe3w (ji,jj,ik+1) = pdept(ji,jj,ik+1) - pdept(ji,jj,ik)
+            END DO
+         END DO         
+         !                                   ! bottom scale factors and depth at  U-, V-, UW and VW-points
+         pe3u (:,:,:) = pe3t(:,:,:)
+         pe3uw(:,:,:) = pe3w(:,:,:)
+         DO jk = 1, jpk                      ! Computed as the minimum of neighbooring scale factors
+            DO jj = 1, jpjm1
+               DO ji = 1, jpi
+                  pe3v (ji,jj,jk) = MIN( pe3t(ji,jj,jk), pe3t(ji,jj+1,jk) )
+                  pe3vw(ji,jj,jk) = MIN( pe3w(ji,jj,jk), pe3w(ji,jj+1,jk) )
+                  pe3f (ji,jj,jk) = pe3v(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'usrdef_zgr', pe3v , 'V', 1._wp )   ;   CALL lbc_lnk( 'usrdef_zgr', pe3vw, 'V', 1._wp )
+         CALL lbc_lnk( 'usrdef_zgr', pe3f , 'F', 1._wp )
+         DO jk = 1, jpk
+            ! set to z-scale factor if zero (i.e. along closed boundaries) because of lbclnk
+            WHERE( pe3u (:,:,jk) == 0._wp )   pe3u (:,:,jk) = pe3t_1d(jk)
+            WHERE( pe3v (:,:,jk) == 0._wp )   pe3v (:,:,jk) = pe3t_1d(jk)
+            WHERE( pe3f (:,:,jk) == 0._wp )   pe3f (:,:,jk) = pe3t_1d(jk)
+            WHERE( pe3uw(:,:,jk) == 0._wp )   pe3uw(:,:,jk) = pe3w_1d(jk)
+            WHERE( pe3vw(:,:,jk) == 0._wp )   pe3vw(:,:,jk) = pe3w_1d(jk)
+         END DO
+         !
+      ENDIF
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z1d  ***
+      !!
+      !! ** Purpose :   set the depth of model levels and the resulting 
+      !!      vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!
+      !!            ===    Here constant vertical resolution   ===
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zt, zw   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z1d : Reference vertical z-coordinates: uniform dz = ', rn_e3
+         WRITE(numout,*) '    ~~~~~~~'
+      ENDIF
+      !
+      ! Reference z-coordinate (depth - scale factor at T- and W-points)   ! Madec & Imbard 1996 function
+      ! ----------------------
+      DO jk = 1, jpk
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) =    rn_e3 *   REAL( jk-1 , wp )
+         pdept_1d(jk) =    rn_e3 * ( REAL( jk-1 , wp ) + 0.5_wp )
+         pe3w_1d (jk) =    rn_e3
+         pe3t_1d (jk) =    rn_e3
+      END DO
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z1d
+   
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/cpp_ISOMIP.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/cpp_ISOMIP.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/ISOMIP/cpp_ISOMIP.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_iomput key_mpp_mpi 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@" sync_freq="10d" min_digits="4">
+      <file_group id="30mi" output_freq="30mi"  output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="e3t"          name="e3t_inst"     long_name="instantaneous T-cell thickness"                operation="instant" />
+	  <field field_ref="toce"         name="thetao_inst"  long_name="instantaneous sea water potential temperature" operation="instant" /> 
+	  <field field_ref="ssh"          name="ssh_inst"     long_name="instantaneous sea surface height above geoid"  operation="instant" />
+	</file>
+
+	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u"          name="e3u_inst"     long_name="instantaneous U-cell thickness"        operation="instant" />
+	  <field field_ref="uoce"         name="uo_inst"      long_name="instantaneous sea water x velocity"    operation="instant" />
+	</file>
+	
+	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v"          name="e3v_inst"     long_name="instantaneous V-cell thickness"        operation="instant" />
+	  <field field_ref="voce"         name="vo_inst"      long_name="instantaneous sea water y velocity"    operation="instant" />
+	</file>
+	
+	<file id="file5" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w"          name="e3w_inst"     long_name="instantaneous W-cell thickness"        operation="instant" />
+	  <field field_ref="woce"         name="wo_inst"      long_name="instantaneous ocean vertical velocity" operation="instant" />
+	</file>
+
+      </file_group>
+
+   </file_definition>
+    
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_cen2_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_cen2_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_cen2_cfg	(revision 14097)
@@ -0,0 +1,200 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_flux_cen2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .true.  !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,312 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                    LOCK EXCHANGE configuration                     !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef 
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_eenH_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_eenH_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_eenH_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_vect_eenH"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 1       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_een_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_een_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_een_cfg	(revision 14097)
@@ -0,0 +1,198 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_vect_een"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ene_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ene_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ene_cfg	(revision 14097)
@@ -0,0 +1,198 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_vect_ene"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  enstrophy conserving scheme
+   ln_dynvor_ens = .false. !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ens_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ens_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT2_vect_ens_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT2_vect_ens"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_cen2_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_cen2_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_cen2_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_flux_cen2"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .true.  !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef 
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_eenH_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_eenH_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_eenH_cfg	(revision 14097)
@@ -0,0 +1,198 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_vect_eenH"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 1       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_een_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_een_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_een_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_vect_een"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ene_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ene_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ene_cfg	(revision 14097)
@@ -0,0 +1,200 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_vect_ene"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .true.  !  enstrophy conserving scheme
+   ln_dynvor_ens = .false. !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ens_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ens_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_FCT4_vect_ens_cfg	(revision 14097)
@@ -0,0 +1,199 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   LOCK_EXCHANGE user defined namelist
+!-----------------------------------------------------------------------
+   rn_dx       =    500.   ! horizontal resolution in meters
+   rn_dz       =      1.   ! vertical   resolution in meters
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "LOCK_FCT4_vect_ens"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   61200   ! for 17h of simulation  (=61200 time-step)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   61200   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   61200   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .false.   !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   rn_isfhmin  =    0.00   !  treshold (m) to discriminate grounding ice to floating ice
+   !
+   rn_rdt      =    1.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   !
+   ln_crs      = .false.   !  Logical switch for coarsening module
+   !
+   ln_meshmask = .false.   !  =T create a mesh file
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                     ! S-EOS coefficients (nn_eos=1):
+   !                          !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  0.          !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+  !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.     !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 4.e-5            !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 500.             !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,1 @@
+link namelist_FCT2_flux_ubs_cfg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,109 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE usrdef_hgr   ***
+   !!
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for LOCK_EXCHANGE configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce  ,  ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx   ! horizontal resolution in meters
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                LOCK_EXCHANGE configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zfact      ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : LOCK_EXCHANGE configuration bassin'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   uniform grid spacing WITHOUT Coriolis force (f=0)'
+      !
+      !                       !==  grid point position  ==!   (in kilometers)
+      zfact = rn_dx * 1.e-3         ! conversion in km
+      DO jj = 1, jpj
+         DO ji = 1, jpi             ! longitude
+            plamt(ji,jj) = zfact * (  - 0.5 + REAL( ji-1 + nimpp-1 , wp )  )  
+            plamu(ji,jj) = zfact * (          REAL( ji-1 + nimpp-1 , wp )  )
+            plamv(ji,jj) = plamt(ji,jj)
+            plamf(ji,jj) = plamu(ji,jj)
+            !                       ! latitude
+            pphit(ji,jj) = zfact * (  - 0.5 + REAL( jj-1 + njmpp-1 , wp )  )
+            pphiu(ji,jj) = pphit(ji,jj)
+            pphiv(ji,jj) = zfact * (          REAL( jj-1 + njmpp-1 , wp )  )
+            pphif(ji,jj) = pphiv(ji,jj)
+         END DO
+      END DO
+      !
+      !                       !==  Horizontal scale factors  ==!   (in meters) 
+      pe1t(:,:) = rn_dx   ;   pe2t(:,:) = rn_dx
+      pe1u(:,:) = rn_dx   ;   pe2u(:,:) = rn_dx
+      pe1v(:,:) = rn_dx   ;   pe2v(:,:) = rn_dx
+      pe1f(:,:) = rn_dx   ;   pe2f(:,:) = rn_dx
+      !
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      pff_f(:,:) = 0._wp            ! here No earth rotation: f=0
+      pff_t(:,:) = 0._wp
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,81 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce , ONLY : glamt 
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here LOCK_EXCHANGE configuration 
+      !!
+      !! ** Method  : - set temprature field
+      !!              - set salinity   field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  ::   jk     ! dummy loop indices
+      REAL(wp) ::   zdam   ! location of dam [Km]
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : LOCK_EXCHANGE configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with a constant salinity (not used as rho=F(T) '
+      IF(lwp) WRITE(numout,*) '                 and a vertical density front with a 5 kg/m3 difference located at glam=32km'
+      IF(lwp) WRITE(numout,*) '                 (i.e. a temperature difference of 25 degrees with rn_a0 = 0.2'
+      !
+      !  rn_a0 =  0.2   !  thermal expension coefficient (nn_eos= 1)
+      !  rho = rau0 - rn_a0 * (T-10) 
+      !  delta_T = 25 degrees  ==>>  delta_rho = 25 * rn_a0 = 5 kg/m3
+      !
+      pu  (:,:,:) = 0._wp        ! ocean at rest
+      pv  (:,:,:) = 0._wp
+      pssh(:,:)   = 0._wp
+      !
+      !                          ! T & S profiles
+      zdam = 32.                      ! density front position in kilometers
+      pts(:,:,:,jp_tem) = 30._wp * ptmask(:,:,:)
+      DO jk = 1, jpkm1
+         WHERE( glamt(:,:) <= zdam )   pts(:,:,jk,jp_tem) = 5._wp * ptmask(:,:,jk)
+      END DO
+      !
+      pts(:,:,:,jp_sal) = 35._wp * ptmask(:,:,:)
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,99 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE usrdef_nam  ***
+   !!
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                              !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx     ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dz     ! resolution in meters defining the vertical   domain size
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here LOCK_EXCHANGE configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dz
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      !
+      cd_cfg = 'LOCK_EXCHANGE'      ! name & resolution (not used)
+      kk_cfg = INT( rn_dx )
+      !
+      ! Global Domain size:  LOCK_EXCHANGE domain is 64 km x 3 grid-points x 20 m
+      kpi = INT(  64.e3 / rn_dx ) + 2
+      kpj = 3
+      kpk = INT(  20.  / rn_dz ) + 1
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! LOCK_EXCHANGE configuration : closed domain
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : LOCK_EXCHANGE test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      vertical   resolution                    rn_dz  = ', rn_dz, ' meters'
+         WRITE(numout,*) '      LOCK_EXCHANGE domain = 64 km  x  3 grid-points  x  20 m'
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      closed                                   jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,87 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE usrdef_sbc  ***
+   !! 
+   !!                  ===  LOCK_EXCHANGE configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in LOCK_EXCHANGE case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for LOCK_EXCHANGE case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : LOCK_EXCHANGE case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,168 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===  LOCK_EXCHANGE case  ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!       zgr_z1d   : reference 1D z-coordinate 
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   jk   ! dummy indices
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : LOCK_EXCHANGE configuration (z-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate   ==>>>   here LOCK EXCHANGE : flat bottom always 
+      ! ---------------------------
+      ld_zco    = .TRUE.       ! z-partial-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .FALSE.      ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! flat bassin (20m deep and 64000m wide, set through the jpk and jpi (see userdef_nam.F90))
+      CALL zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      ! the ocean basin surrounded by land (1 grid-point) set through lbc_lnk call as jperio=0 
+      z2d(:,:) = 1._wp                    ! surface ocean is the 1st level
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )        ! closed basin since jperio = 0 (see userdef_nam.F90)
+      k_top(:,:) = NINT( z2d(:,:) )
+      !
+      !                              
+      !                       !==  z-coordinate  ==!   (step-like topography)
+      !
+      !                                !* bottom ocean compute from the depth of grid-points
+      k_bot(:,:) = jpkm1 * k_top(:,:)     ! here use k_top as a land mask
+      !                                !* horizontally uniform coordinate (reference z-co everywhere)
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z1d  ***
+      !!
+      !! ** Purpose :   set the depth of model levels and the resulting 
+      !!      vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!
+      !!            ===    Here constant vertical resolution   ===
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zt, zw   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z1d : Reference vertical z-coordinates: uniform dz = ', rn_dz
+         WRITE(numout,*) '    ~~~~~~~'
+      ENDIF
+      !
+      ! Reference z-coordinate (depth - scale factor at T- and W-points)   ! Madec & Imbard 1996 function
+      ! ----------------------
+      DO jk = 1, jpk
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) =    rn_dz *   REAL( jk-1 , wp )
+         pdept_1d(jk) =    rn_dz * ( REAL( jk-1 , wp ) + 0.5_wp )
+         pe3w_1d (jk) =    rn_dz
+         pe3t_1d (jk) =    rn_dz
+      END DO
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z1d
+   
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/cpp_LOCK_EXCHANGE.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/cpp_LOCK_EXCHANGE.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/LOCK_EXCHANGE/cpp_LOCK_EXCHANGE.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_iomput key_mpp_mpi 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@" sync_freq="10d" min_digits="4">
+      <file_group id="30mi" output_freq="30mi"  output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="e3t"          name="e3t_inst"     long_name="instantaneous T-cell thickness"                operation="instant" />
+	  <field field_ref="toce"         name="thetao_inst"  long_name="instantaneous sea water potential temperature" operation="instant" /> 
+	  <field field_ref="ssh"          name="ssh_inst"     long_name="instantaneous sea surface height above geoid"  operation="instant" />
+	</file>
+
+	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u"          name="e3u_inst"     long_name="instantaneous U-cell thickness"        operation="instant" />
+	  <field field_ref="uoce"         name="uo_inst"      long_name="instantaneous sea water x velocity"    operation="instant" />
+	</file>
+	
+	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v"          name="e3v_inst"     long_name="instantaneous V-cell thickness"        operation="instant" />
+	  <field field_ref="voce"         name="vo_inst"      long_name="instantaneous sea water y velocity"    operation="instant" />
+	</file>
+	
+	<file id="file5" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w"          name="e3w_inst"     long_name="instantaneous W-cell thickness"        operation="instant" />
+	  <field field_ref="woce"         name="wo_inst"      long_name="instantaneous ocean vertical velocity" operation="instant" />
+	</file>
+
+      </file_group>
+
+   </file_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,1 @@
+link namelist_zps_FCT4_flux_ubs_cfg
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_cen-ahm1000_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_cen-ahm1000_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_cen-ahm1000_cfg	(revision 14097)
@@ -0,0 +1,223 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .false.      ! z-partial-step coordinate
+   ln_sco      = .true.       ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_sco_FCT2_flux_cen-ahm1000"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   !nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    6120   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    6120   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .true.  !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .false.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .true.     !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT2_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,223 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .false.      ! z-partial-step coordinate
+   ln_sco      = .true.       ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_sco_FCT2_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   !nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    1080   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    1080   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.     !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_cen-ahm1000_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_cen-ahm1000_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_cen-ahm1000_cfg	(revision 14097)
@@ -0,0 +1,223 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .false.      ! z-partial-step coordinate
+   ln_sco      = .true.       ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_sco_FCT4_flux_cen-ahm1000"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   !nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    6120   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    6120   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .true.  !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .false.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .true.     !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0e      !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_sco_FCT4_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,223 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .false.      ! z-partial-step coordinate
+   ln_sco      = .true.       ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_sco_FCT4_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   !nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    1080   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    1080   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT2_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT2_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT2_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,224 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .true.       ! z-partial-step coordinate
+   ln_sco      = .false.      ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_zps_FCT2_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   !nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    1080   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    1080   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   ln_zdfosm   = .false.      !  OSMOSIS BL closure                     (T =>   fill namzdf_osm)
+   !   
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc 
+      nn_npcp     =  365         ! npc control print frequency
+   !   
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !   
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !   
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_flux_ubs_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_flux_ubs_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_flux_ubs_cfg	(revision 14097)
@@ -0,0 +1,328 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                        OVERFLOW configuration                      !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .true.       ! z-partial-step coordinate
+   ln_sco      = .false.      ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_zps_FCT4_flux_ubs"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6120   ! here 17h of simulation  (=6120 time-step) 
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    6120   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    6120   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd        !    Temperature & Salinity Data  (init/dmp)             (default: OFF)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.     !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynvor_ene = .false. !  enstrophy conserving scheme
+   ln_dynvor_ens = .true.  !  energy conserving scheme
+   ln_dynvor_mix = .false. !  mixed scheme
+   ln_dynvor_een = .false. !  energy & enstrophy scheme
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.     !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! adaptive-implicit vertical advection
+   ln_zad_Aimp = .true.       !  Courant number dependent scheme (Shchepetkin 2015)
+   !
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !   
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc 
+      nn_npcp     =  365         ! npc control print frequency
+   !   
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !   
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !   
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_vect_een_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_vect_een_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/EXPREF/namelist_zps_FCT4_vect_een_cfg	(revision 14097)
@@ -0,0 +1,223 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : used to overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   OVERFLOW configuration 
+!-----------------------------------------------------------------------
+   !                       !  type of vertical coordinate
+   ln_zco      = .false.      ! z-coordinate
+   ln_zps      = .true.       ! z-partial-step coordinate
+   ln_sco      = .false.      ! s-coordinate   
+   rn_dx       =   1000.   !  horizontal resolution   [meters]
+   rn_dz       =     20.   !  vertical   resolution   [meters]
+/
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      =   "OVF_zps_FCT4_vect_een"  !  experience name
+   nn_it000    =       1   !  first time step
+   !nn_itend    =    6120  ! here 17h of simulation  (=6120 time-step) 
+   nn_itend    =    5760   ! here 16h of simulation  (=5760 time-step) abort after 5802 for zps: pb of physics conditions
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =    1080   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =    1080   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   rn_rdt      =   10.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!======================================================================
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_isfcav=T)
+!!   namdrg_bot    bottom friction
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg            !   top/bottom drag coefficient                      (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.    !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+   ln_lin     = .false.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin = .false.    !  non-linear  drag: Cd = Cd0 |U|
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   !
+   ln_drgimp  = .true.     !  implicit top/bottom friction flag
+/
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.2         !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  4            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  4            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!-----------------------------------------------------------------------
+   !                       !  Operator type:    both false = No lateral diffusion
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .true. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   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                             (default: zstar)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   Surface pressure gradient
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .true.     ! Number of sub-step defined from:
+         nn_baro      =  1         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .false.    !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .true.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .true.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 1000.            !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!======================================================================
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure (required)
+   ln_zdfcst   = .true.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .false.      !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   !   
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+      nn_evdm     =    0         ! apply on tracer (=0) or on tracer and momentum (=1) 
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc 
+      nn_npcp     =  365         ! npc control print frequency
+   !   
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !   
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !   
+   !                       ! coefficients
+   rn_avm0     =   1.e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0        !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0        !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,109 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                     ===  OVERFLOW configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2016-08  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for OVERFLOW configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce  ,  ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx   ! horizontal resolution in meters
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                OVERFLOW configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zfact      ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : OVERFLOW configuration bassin'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   uniform grid spacing WITHOUT Coriolis force (f=0)'
+      !
+      !                       !==  grid point position  ==!   (in kilometers)
+      zfact = rn_dx * 1.e-3         ! conversion in km
+      DO jj = 1, jpj
+         DO ji = 1, jpi             ! longitude
+            plamt(ji,jj) = zfact * (  - 0.5 + REAL( ji-1 + nimpp-1 , wp )  )  
+            plamu(ji,jj) = zfact * (          REAL( ji-1 + nimpp-1 , wp )  )
+            plamv(ji,jj) = plamt(ji,jj)
+            plamf(ji,jj) = plamu(ji,jj)
+            !                       ! latitude
+            pphit(ji,jj) = zfact * (  - 0.5 + REAL( jj-1 + njmpp-1 , wp )  )
+            pphiu(ji,jj) = pphit(ji,jj)
+            pphiv(ji,jj) = zfact * (          REAL( jj-1 + njmpp-1 , wp )  )
+            pphif(ji,jj) = pphiv(ji,jj)
+         END DO
+      END DO
+      !
+      !                       !==  Horizontal scale factors  ==!   (in meters) 
+      pe1t(:,:) = rn_dx   ;   pe2t(:,:) = rn_dx
+      pe1u(:,:) = rn_dx   ;   pe2u(:,:) = rn_dx
+      pe1v(:,:) = rn_dx   ;   pe2v(:,:) = rn_dx
+      pe1f(:,:) = rn_dx   ;   pe2f(:,:) = rn_dx
+      !
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      pff_f(:,:) = 0._wp            ! here No earth rotation: f=0
+      pff_t(:,:) = 0._wp
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,81 @@
+MODULE usrdef_istate
+   !!==============================================================================
+   !!                       ***  MODULE usrdef_istate  ***
+   !!
+   !!                      ===  OVERFLOW configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!==============================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce , ONLY : glamt 
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here OVERFLOW configuration 
+      !!
+      !! ** Method  : - set temprature field
+      !!              - set salinity   field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  ::   jk     ! dummy loop indices
+      REAL(wp) ::   zdam   ! location of dam [Km]
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : OVERFLOW configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with a constant salinity (not used as rho=F(T) '
+      IF(lwp) WRITE(numout,*) '                 and a vertical density front with a 2 kg/m3 difference located at glam=20km'
+      IF(lwp) WRITE(numout,*) '                 (i.e. a temperature difference of 10 degrees with rn_a0 = 0.2'
+      !
+      !  rn_a0 =  0.2   !  thermal expension coefficient (nn_eos= 1)
+      !  rho = rau0 - rn_a0 * (T-10) 
+      !  delta_T = 10 degrees  ==>>  delta_rho = 10 * rn_a0 = 2 kg/m3
+      !
+      pu  (:,:,:) = 0._wp        ! ocean at rest
+      pv  (:,:,:) = 0._wp
+      pssh(:,:)   = 0._wp
+      !
+      !                          ! T & S profiles
+      zdam = 20.                      ! density front position in kilometers
+      pts(:,:,:,jp_tem) = 20._wp * ptmask(:,:,:)
+      DO jk = 1, jpkm1
+         WHERE( glamt(:,:) <= zdam )   pts(:,:,jk,jp_tem) = 10._wp * ptmask(:,:,jk)
+      END DO
+      !
+      pts(:,:,:,jp_sal) = 35._wp * ptmask(:,:,:)
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,103 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                     ===  OVERFLOW configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE dom_oce  , ONLY: ln_zco, ln_zps, ln_sco   ! flag of type of coordinate
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                              !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx     ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dz     ! resolution in meters defining the vertical   domain size
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here OVERFLOW configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ ln_zco, ln_zps, ln_sco, rn_dx, rn_dz
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'OVERFLOW'           ! name & resolution (not used)
+      kk_cfg = INT( rn_dx )
+      !
+      ! Global Domain size:  OVERFLOW domain is  200 km x 3 grid-points x 2000 m
+      kpi = INT( 200.e3 / rn_dx ) + 2
+      kpj = 3
+      kpk = INT(  2000. / rn_dz ) + 1
+      !
+      !                             ! control print
+      WRITE(numout,*) '   '
+      WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+      WRITE(numout,*) '~~~~~~~~~~~ '
+      WRITE(numout,*) '   Namelist namusr_def : OVERFLOW test case'
+      WRITE(numout,*) '      type of vertical coordinate : '
+      WRITE(numout,*) '         z-coordinate flag                     ln_zco = ', ln_zco
+      WRITE(numout,*) '         z-partial-step coordinate flag        ln_zps = ', ln_zps
+      WRITE(numout,*) '         s-coordinate flag                     ln_sco = ', ln_sco
+      WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+      WRITE(numout,*) '      vertical   resolution                    rn_dz  = ', rn_dz, ' meters'
+      WRITE(numout,*) '      OVERFLOW domain = 200 km x 3 grid-points x 2000 m'
+      WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+      WRITE(numout,*) '                                               jpjglo = ', kpj
+      WRITE(numout,*) '                                               jpkglo = ', kpk
+      !
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! OVERFLOW configuration : close basin
+      !
+      WRITE(numout,*) '   '
+      WRITE(numout,*) '   Lateral boundary condition of the global domain'
+      WRITE(numout,*) '      OVERFLOW : closed basin                  jperio = ', kperio
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,87 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                     ===  OVERFLOW configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in OVERFLOW case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields 
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for OVERFLOW case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : OVERFLOW case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,265 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                     ***  MODULE usrdef_zgr  ***
+   !!
+   !!                       ===  OVERFLOW case  ===
+   !!
+   !! user defined :  vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-08  (G. Madec, S. Flavoni)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!       zgr_z1d   : reference 1D z-coordinate 
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce ,  ONLY: mi0, mi1, nimpp, njmpp   ! ocean space and time domain
+   USE dom_oce ,  ONLY: glamt                    ! ocean space and time domain
+   USE usrdef_nam     ! User defined : namelist variables
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+   USE timing         ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr   ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v , pe3f ,               &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw,                      &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(in   ) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags ( read in namusr_def )
+      LOGICAL                   , INTENT(  out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(  out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(  out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(  out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   ji, jj, jk        ! dummy indices
+      INTEGER  ::   ik                ! local integers
+      REAL(wp) ::   zfact, z1_jpkm1   ! local scalar
+      REAL(wp) ::   ze3min            ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj) ::   zht, zhu, z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : OVERFLOW configuration (z(ps)- or s-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ! already set in usrdef_nam.F90 by reading the namusr_def namelist except for ISF
+      ld_isfcav = .FALSE.
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+      ! western continental shelf (500m deep) and eastern deep ocean (2000m deep)
+      ! (set through the jpk and jpi (see userdef_nam.F90))
+      ! with a hyperbolic tangent transition centered at 40km
+      ! NB: here glamt is in kilometers
+      !
+      zht(:,:) = + (  500. + 0.5 * 1500. * ( 1.0 + tanh( (glamt(:,:) - 40.) / 7. ) )  )
+      !
+      ! at u-point: averaging zht
+      DO ji = 1, jpim1
+         zhu(ji,:) = 0.5_wp * ( zht(ji,:) + zht(ji+1,:) )
+      END DO
+      CALL lbc_lnk( 'usrdef_zgr', zhu, 'U', 1. )     ! boundary condition: this mask the surrouding grid-points
+      !                                ! ==>>>  set by hand non-zero value on first/last columns & rows 
+      DO ji = mi0(1), mi1(1)              ! first row of global domain only
+         zhu(ji,2) = zht(ji,2)
+      END DO
+       DO ji = mi0(jpiglo), mi1(jpiglo)   ! last  row of global domain only
+         zhu(ji,2) = zht(ji,2)
+      END DO
+      zhu(:,1) = zhu(:,2)
+      zhu(:,3) = zhu(:,2)
+      !     
+      CALL zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      ! the ocean basin surrounded by land (1 grid-point) set through lbc_lnk call as jperio=0 
+      z2d(:,:) = 1._wp                    ! surface ocean is the 1st level
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )        ! closed basin since jperio = 0 (see userdef_nam.F90)
+      k_top(:,:) = NINT( z2d(:,:) )
+      !
+      !                              
+      !
+      IF ( ld_sco ) THEN      !==  s-coordinate  ==!   (terrain-following coordinate)
+         !
+         k_bot(:,:) = jpkm1 * k_top(:,:)  !* bottom ocean = jpk-1 (here use k_top as a land mask)
+         !
+         !                                !* terrain-following coordinate with e3.(k)=cst)
+         !                                !  OVERFLOW case : identical with j-index (T=V, U=F)
+         z1_jpkm1 = 1._wp / REAL( jpkm1 , wp)
+         DO jk = 1, jpk
+            pdept(:,:,jk) = zht(:,:) * z1_jpkm1 * ( REAL( jk   , wp ) - 0.5_wp )
+            pdepw(:,:,jk) = zht(:,:) * z1_jpkm1 * ( REAL( jk-1 , wp )          )
+            pe3t (:,:,jk) = zht(:,:) * z1_jpkm1
+            pe3u (:,:,jk) = zhu(:,:) * z1_jpkm1
+            pe3v (:,:,jk) = zht(:,:) * z1_jpkm1
+            pe3f (:,:,jk) = zhu(:,:) * z1_jpkm1
+            pe3w (:,:,jk) = zht(:,:) * z1_jpkm1
+            pe3uw(:,:,jk) = zhu(:,:) * z1_jpkm1
+            pe3vw(:,:,jk) = zht(:,:) * z1_jpkm1
+         END DO      
+      ENDIF
+      !
+      !
+      IF ( ld_zco ) THEN      !==  z-coordinate  ==!   (step-like topography)
+         !
+         !                                !* bottom ocean compute from the depth of grid-points
+         k_bot(:,:) = jpkm1 * k_top(:,:)     ! here use k_top as a land mask
+         DO jk = 1, jpkm1
+            WHERE( pdept_1d(jk) < zht(:,:) .AND. zht(:,:) <= pdept_1d(jk+1) )   k_bot(:,:) = jk * k_top(:,:)
+         END DO
+         !                                !* horizontally uniform coordinate (reference z-co everywhere)
+         DO jk = 1, jpk
+            pdept(:,:,jk) = pdept_1d(jk)
+            pdepw(:,:,jk) = pdepw_1d(jk)
+            pe3t (:,:,jk) = pe3t_1d (jk)
+            pe3u (:,:,jk) = pe3t_1d (jk)
+            pe3v (:,:,jk) = pe3t_1d (jk)
+            pe3f (:,:,jk) = pe3t_1d (jk)
+            pe3w (:,:,jk) = pe3w_1d (jk)
+            pe3uw(:,:,jk) = pe3w_1d (jk)
+            pe3vw(:,:,jk) = pe3w_1d (jk)
+         END DO
+      ENDIF
+      !
+      !
+      IF ( ld_zps ) THEN      !==  zps-coordinate  ==!   (partial bottom-steps)
+         !
+         ze3min = 0.1_wp * rn_dz
+         IF(lwp) WRITE(numout,*) '   minimum thickness of the partial cells = 10 % of e3 = ', ze3min
+         !
+         !
+         !                                !* bottom ocean compute from the depth of grid-points
+         k_bot(:,:) = jpkm1
+         DO jk = jpkm1, 1, -1
+            WHERE( zht(:,:) < pdepw_1d(jk) + ze3min )   k_bot(:,:) = jk-1
+         END DO
+         !
+         !                                !* vertical coordinate system
+         DO jk = 1, jpk                      ! initialization to the reference z-coordinate
+            pdept(:,:,jk) = pdept_1d(jk)
+            pdepw(:,:,jk) = pdepw_1d(jk)
+            pe3t (:,:,jk) = pe3t_1d (jk)
+            pe3u (:,:,jk) = pe3t_1d (jk)
+            pe3v (:,:,jk) = pe3t_1d (jk)
+            pe3f (:,:,jk) = pe3t_1d (jk)
+            pe3w (:,:,jk) = pe3w_1d (jk)
+            pe3uw(:,:,jk) = pe3w_1d (jk)
+            pe3vw(:,:,jk) = pe3w_1d (jk)
+         END DO
+         DO jj = 1, jpj                      ! bottom scale factors and depth at T- and W-points
+            DO ji = 1, jpi
+               ik = k_bot(ji,jj)
+                  pdepw(ji,jj,ik+1) = MIN( zht(ji,jj) , pdepw_1d(ik+1) )
+                  pe3t (ji,jj,ik  ) = pdepw(ji,jj,ik+1) - pdepw(ji,jj,ik)
+                  pe3t (ji,jj,ik+1) = pe3t (ji,jj,ik  ) 
+                  !
+                  pdept(ji,jj,ik  ) = pdepw(ji,jj,ik  ) + pe3t (ji,jj,ik  ) * 0.5_wp
+                  pdept(ji,jj,ik+1) = pdepw(ji,jj,ik+1) + pe3t (ji,jj,ik+1) * 0.5_wp
+                  pe3w (ji,jj,ik+1) = pdept(ji,jj,ik+1) - pdept(ji,jj,ik)              ! = pe3t (ji,jj,ik  )
+            END DO
+         END DO         
+         !                                   ! bottom scale factors and depth at  U-, V-, UW and VW-points
+         !                                   ! usually Computed as the minimum of neighbooring scale factors
+         pe3u (:,:,:) = pe3t(:,:,:)          ! HERE OVERFLOW configuration : 
+         pe3v (:,:,:) = pe3t(:,:,:)          !    e3 increases with i-index and identical with j-index
+         pe3f (:,:,:) = pe3t(:,:,:)          !    so e3 minimum of (i,i+1) points is (i) point
+         pe3uw(:,:,:) = pe3w(:,:,:)          !    in j-direction e3v=e3t and e3f=e3v
+         pe3vw(:,:,:) = pe3w(:,:,:)          !    ==>>  no need of lbc_lnk calls
+         !      
+      ENDIF
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z1d( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z1d  ***
+      !!
+      !! ** Purpose :   set the depth of model levels and the resulting 
+      !!      vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!
+      !!            ===    Here constant vertical resolution   ===
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zt, zw   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z1d : Reference vertical z-coordinates: uniform dz = ', rn_dz
+         WRITE(numout,*) '    ~~~~~~~'
+      ENDIF
+      !
+      ! Reference z-coordinate (depth - scale factor at T- and W-points)   ! Madec & Imbard 1996 function
+      ! ----------------------
+      DO jk = 1, jpk
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) =    rn_dz *   REAL( jk-1 , wp )
+         pdept_1d(jk) =    rn_dz * ( REAL( jk-1 , wp ) + 0.5_wp )
+         pe3w_1d (jk) =    rn_dz
+         pe3t_1d (jk) =    rn_dz
+      END DO
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z1d
+   
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/cpp_OVERFLOW.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/cpp_OVERFLOW.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/OVERFLOW/cpp_OVERFLOW.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+bld::tool::fppkeys   key_mpp_mpi key_iomput 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/README.rst
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/README.rst	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/README.rst	(revision 14097)
@@ -0,0 +1,206 @@
+**********************
+Explore the test cases
+**********************
+
+.. todo::
+
+   CANAL animated gif is missing
+
+.. contents::
+   :local:
+   :depth: 1
+
+Installation
+============
+
+Download
+--------
+
+| The complete and up-to-date set of test cases is available on
+  :github:`NEMO test cases repository <NEMO-examples>`.
+| Download it directly into the :file:`./tests` root directory with
+
+.. code-block:: console
+
+   $ git clone http://github.com/NEMO-ocean/NEMO-examples
+
+Compilation
+-----------
+
+The compilation of the test cases is very similar to
+the manner the reference configurations are compiled.
+If you are not familiar on how to compile NEMO,
+it is first recomended to read :doc:`the instructions <install>`.
+
+| As the reference configurations are compiled with ``-r`` option,
+  test cases can be compiled by the use of :file:`makenemo` with ``-a`` option.
+| Here an example to compile a copy named WAD2 of the wetting and drying test case (WAD):
+
+.. code-block:: console
+
+   $ ./makenemo -n 'WAD2' -a 'WAD' -m 'my_arch' -j '4'
+
+Run and analysis
+----------------
+
+There no requirement of specific input file for the test_cases presented here.
+The XIOS xml input files and namelist are already setup correctly.
+For detailed description and Jupyter notebook, the reader is directed on
+the :github:`NEMO test cases repository <NEMO-examples>`
+
+The description below is a brief advertisement of some test cases.
+
+List of test cases
+==================
+
+ICE_AGRIF
+---------
+
+.. figure:: _static/ICE_AGRIF_UDIAG_43days_UM5.gif
+   :width: 200px
+   :align: left
+
+   ..
+
+| This test case illustrates the advection of an ice patch across
+  an East/West and North/South periodic channel over a slab ocean (i.e. one ocean layer),
+  and with an AGRIF zoom (1:3) in the center.
+| The purpose of this configuration is to
+  test the advection of the ice patch in and across the AGRIF boundary.
+  One can either impose ice velocities or ice-atm.
+  Stresses and let rheology define velocities (see :file:`README` for details)
+
+VORTEX
+------
+
+.. figure:: _static/VORTEX_anim.gif
+   :width: 200px
+   :align: right
+
+   ..
+
+This test case illustrates the propagation of an anticyclonic eddy over a Beta plan and a flat bottom.
+It is implemented here with an online refined subdomain (1:3) out of which the vortex propagates.
+It serves as a benchmark for quantitative estimates of nesting errors as in :cite:`DEBREU2012`,
+:cite:`PENVEN2006` or :cite:`SPALL1991`.
+
+The animation (sea level anomaly in meters) illustrates with
+two 1:2 successively nested grids how the vortex smoothly propagates out of the refined grids.
+
+ISOMIP
+------
+
+.. figure:: _static/ISOMIP_moc.png
+   :width: 200px
+   :align: left
+
+   ..
+
+| The purpose of this test case is to evaluate the impact of various schemes and new development with
+  the iceshelf cavities circulation and melt.
+  This configuration served as initial assesment of the ice shelf module in :cite:`LOSCH2008` and
+  :cite:`MATHIOT2017`.
+  The default setup is the one described |ISOMIP|_.
+| The figure (meridional overturning circulation) illustrates
+  the circulation generated after 10000 days by the ice shelf melting (ice pump).
+
+.. |ISOMIP| replace:: here
+
+LOCK_EXCHANGE
+-------------
+
+.. figure:: _static/LOCK-FCT4_flux_ubs.gif
+   :width: 200px
+   :align: right
+
+   ..
+
+| The LOCK EXCHANGE experiment is a classical fluid dynamics experiment that has been adapted
+  by :cite:`HAIDVOGEL1999` for testing advection schemes in ocean circulation models.
+  It has been used by several authors including :cite:`BURCHARD2002` and :cite:`ILICAK2012`.
+  The LOCK EXCHANGE experiment can in particular illustrate
+  the impact of different choices of numerical schemes and/or subgrid closures on
+  spurious interior mixing.
+| Here the animation of the LOCK_EXCHANGE test case using
+  the advection scheme FCT4 (forth order) for tracer and ubs for dynamics.
+
+OVERFLOW
+--------
+
+.. figure:: _static/OVF-sco_FCT4_flux_cen-ahm1000.gif
+   :width: 200px
+   :align: left
+
+   ..
+
+| The OVERFLOW experiment illustrates the impact of different choices of numerical schemes and/or
+  subgrid closures on spurious interior mixing close to bottom topography.
+  The OVERFLOW experiment is adapted from the non-rotating overflow configuration described in
+  :cite:`HAIDVOGEL1999` and further used by :cite:`ILICAK2012`.
+  Here we can assess the behaviour of the second-order tracer advection scheme FCT2 and
+  forth-order FCT4, z-coordinate and sigma coordinate (...).
+| Here the animation of the OVERFLOW test case in sigma coordinate with
+  the forth-order advection scheme FCT4.
+
+WAD
+---
+
+.. figure:: _static/wad_testcase_7.gif
+   :width: 200px
+   :align: right
+
+   ..
+
+| A set of simple closed basin geometries for testing the Wetting and drying capabilities.
+  Examples range from a closed channel with EW linear bottom slope to
+  a parabolic EW channel with a Gaussian ridge.
+| Here the animation of the test case 7.
+  This test case is a simple linear slope with a mid-depth shelf with
+  an open boundary forced with a sinusoidally varying ssh.
+  This test case has been introduced to emulate a typical coastal application with
+  a tidally forced open boundary with an adverse SSH gradient that,
+  when released, creates a surge up the slope.
+  The parameters are chosen such that
+  the surge rises above sea-level before falling back and oscillating towards an equilibrium position.
+
+CANAL
+-----
+
+.. figure:: _static/CANAL_image.gif
+   :width: 200px
+   :align: left
+
+   ..
+
+East-west periodic canal of variable size with several initial states and
+associated geostrophic currents (zonal jets or vortex).
+
+ICE_ADV2D
+---------
+
+| This test case illustrates the advection of an ice patch across
+  an East/West and North/South periodic channel over a slab ocean (i.e. one ocean layer).
+  The configuration is similar to ICE_AGRIF, except for the AGRIF zoom.
+| The purpose of this configuration is to test the advection schemes available in the sea-ice code
+  (for now, Prather and Ultimate-Macho from 1st to 5th order),
+  especially the occurence of overshoots in ice thickness
+
+ICE_ADV1D
+---------
+
+| This experiment is the classical :cite:`SCHAR1996` test case ,
+  which has been used in :cite:`LIPSCOMB2004`, and in which very specific shapes of ice concentration,
+  thickness and volume converge toward the center of a basin.
+  Convergence is unidirectional (in x) while fields are homogeneous in y.
+| The purpose of this configuration is to
+  test the caracteristics of advection schemes available in the sea-ice code
+  (for now, Prather and Ultimate-Macho from 1st to 5th order),
+  especially the constitency between concentration, thickness and volume,
+  and the preservation of initial shapes.
+
+.. rubric:: References
+
+.. bibliography:: tests.bib
+   :all:
+   :style: unsrt
+   :labelprefix: T
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="1_nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_cfg	(revision 14097)
@@ -0,0 +1,307 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite defaults values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                         VORTEX configuration                       !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   VORTEX configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   rn_dx       =  30000.   !  x horizontal resolution   [meters]
+   rn_dy       =  30000.   !  y horizontal resolution   [meters]
+   rn_dz       =    500.   !  z vertical resolution [meters]
+   rn_ppgphi0  =   38.5    !  Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      = "VORTEX"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =   18000   !  last time step 
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   99999   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   99999   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   =  .false.  !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_rdt      =    480.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.05    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+  rn_shlat     =    0.    !  free slip
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+   ln_spc_dyn    = .true.  !  use 0 as special value for dynamics
+   rn_sponge_tra =  800.   !  coefficient for tracer   sponge layer [m2/s]
+   rn_sponge_dyn =  800.   !  coefficient for dynamics sponge layer [m2/s]
+   ln_chk_bathy  = .FALSE. !
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF = .true.     !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+      !                            !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+      rn_a0       =  0.28        !  thermal expension coefficient (for simplified equation of state)
+      rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+      rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+      rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+      rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+      rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+      rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true.  !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: OFF)
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dynspg_exp  = .false. 
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .false.    ! Number of sub-step defined from:
+         nn_baro      =  24         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.     !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .true.     !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 0.1              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 30.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/1_namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/AGRIF_FixedGrids.in
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/AGRIF_FixedGrids.in	(revision 14097)
@@ -0,0 +1,3 @@
+1
+19 38 19 38 3 3 3 
+0
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@" sync_freq="10d" min_digits="4">
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE." >  <!-- 5d files -->  
+ 
+	<file id="file1" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="e3t"          name="e3t_inst"     long_name="instantaneous T-cell thickness"                operation="instant" />
+	  <field field_ref="toce"         name="thetao_inst"  long_name="instantaneous sea water potential temperature" operation="instant" /> 
+	  <field field_ref="ssh"          name="ssh_inst"     long_name="instantaneous sea surface height above geoid"  operation="instant" />
+	</file>
+
+	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <field field_ref="e3u"          name="e3u_inst"     long_name="instantaneous U-cell thickness"        operation="instant" />
+	  <field field_ref="uoce"         name="uo_inst"      long_name="instantaneous sea water x velocity"    operation="instant" />
+	</file>
+	
+	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
+	  <field field_ref="e3v"          name="e3v_inst"     long_name="instantaneous V-cell thickness"        operation="instant" />
+	  <field field_ref="voce"         name="vo_inst"      long_name="instantaneous sea water y velocity"    operation="instant" />
+	</file>
+	
+	<file id="file5" name_suffix="_grid_W" description="ocean W grid variables" >
+	  <field field_ref="e3w"          name="e3w_inst"     long_name="instantaneous W-cell thickness"        operation="instant" />
+	  <field field_ref="woce"         name="wo_inst"      long_name="instantaneous ocean vertical velocity" operation="instant" />
+	</file>
+
+      </file_group>
+
+   </file_definition>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">false</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+  <context id="1_nemo" src="./1_context_nemo.xml"/>   <!--  NEMO       -->
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,298 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                         VORTEX configuration                       !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !   User defined :   VORTEX configuration: Flat bottom, beta-plane
+!-----------------------------------------------------------------------
+   rn_dx       =  30000.   !  x horizontal resolution   [meters]
+   rn_dy       =  30000.   !  y horizontal resolution   [meters]
+   rn_dz       =    500.   !  z vertical resolution [meters]
+   rn_ppgphi0  =   38.5    !  Reference latitude [degrees]
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =       0   !  job number (no more used...)
+   cn_exp      = "VORTEX"  !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =    6000   !  last time step 
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =   99999   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =   99999   !  frequency of write in the output file   (modulo referenced to nn_it000)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   =  .false.  !  =T  linear free surface  ==>>  model level are fixed in time
+   rn_rdt      =   1440.   !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =   0.05    !  asselin time filter parameter
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: use namusr_def in namelist_cfg)
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition manager                   (default: NO selection)
+!-----------------------------------------------------------------------
+  nn_fsbc     = 1         !  frequency of surface boundary condition computation
+                          !     (also = the frequency of sea-ice & iceberg model call)
+  ln_usr      = .true.    !  user defined formulation                  (T => check usrdef_sbc)
+  ln_blk      = .false.   !  Bulk formulation                          (T => fill namsbc_blk )
+  nn_ice      = 0         !  =0 no ice boundary condition   
+  ln_traqsr   = .false.   !  Light penetration in the ocean            (T => fill namtra_qsr )
+  ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+  ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+  nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+  rn_shlat     =    0.    !  free slip
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_drg_OFF  = .true.   !  free-slip       : Cd = 0                  (F => fill namdrg_bot
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_seos     = .true.         !  = Use simplified equation of state (S-EOS)
+   !                            !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  0.28        !  thermal expension coefficient (for simplified equation of state)
+   rn_b0       =  0.          !  saline  expension coefficient (for simplified equation of state)
+   rn_lambda1  =  0.          !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  0.          !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  0.          !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  0.          !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  0.          !  cabbeling coeff in T*S  (=0 for linear eos)
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_cen = .false. !  2nd order centered scheme
+      nn_cen_h   =  4            !  =2/4, horizontal 2nd order CEN / 4th order CEN
+      nn_cen_v   =  4            !  =2/4, vertical   2nd order CEN / 4th order COMPACT
+   ln_traadv_fct = .true. !  FCT scheme
+      nn_fct_h   =  2            !  =2/4, horizontal 2nd / 4th order
+      nn_fct_v   =  2            !  =2/4, vertical   2nd / COMPACT 4th order
+   ln_traadv_mus = .false. !  MUSCL scheme
+      ln_mus_ups = .false.       !  use upstream scheme near river mouths
+   ln_traadv_ubs = .false. !  UBS scheme
+      nn_ubs_v   =  2            !  =2  , vertical 2nd order FCT / COMPACT 4th order
+   ln_traadv_qck = .false. !  QUICKEST scheme
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traldf_OFF   =  .true.  !  No explicit diffusion
+   ln_traldf_lap   =  .false.  !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nam_vvl       !   vertical coordinate options                          (default: z-star)
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .true.           !  zstar vertical coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_vec = .false. !  vector form (T) or flux form (F)
+   nn_dynkeg     = 0       ! scheme for grad(KE): =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .true.  !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: OFF)
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.  !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.   !  s-coordinate (standard jacobian formulation)
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dynspg_exp = .false. 
+   ln_dynspg_ts  = .true.   ! split-explicit free surface
+      ln_bt_fw      = .true.     ! Forward integration of barotropic Eqs.
+      ln_bt_av      = .true.     ! Time filtering of barotropic variables
+         nn_bt_flt     = 1          ! Time filter choice  = 0 None
+         !                          !                     = 1 Boxcar over   nn_baro sub-steps
+         !                          !                     = 2 Boxcar over 2*nn_baro  "    "
+      ln_bt_auto    = .false.    ! Number of sub-step defined from:
+         nn_baro      =  24         ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_OFF =  .true.     !  No operator (i.e. no explicit diffusion)
+   ln_dynldf_lap =  .false.    !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .false.    !  iso-level
+   ln_dynldf_hor =  .true.     !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            bhm = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 0.1              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 30.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics manager                             (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .true.       !  constant mixing
+   !
+   !                       ! convection
+   ln_zdfevd   = .false.      !  enhanced vertical diffusion
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.e-4      !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   0.e0       !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default; OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/domvvl.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/domvvl.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/domvvl.F90	(revision 14097)
@@ -0,0 +1,1053 @@
+MODULE domvvl
+   !!======================================================================
+   !!                       ***  MODULE domvvl   ***
+   !! Ocean : 
+   !!======================================================================
+   !! History :  2.0  !  2006-06  (B. Levier, L. Marie)  original code
+   !!            3.1  !  2009-02  (G. Madec, M. Leclair, R. Benshila)  pure z* coordinate
+   !!            3.3  !  2011-10  (M. Leclair) totally rewrote domvvl: vvl option includes z_star and z_tilde coordinates
+   !!            3.6  !  2014-11  (P. Mathiot) add ice shelf capability
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   dom_vvl_init     : define initial vertical scale factors, depths and column thickness
+   !!   dom_vvl_sf_nxt   : Compute next vertical scale factors
+   !!   dom_vvl_sf_swp   : Swap vertical scale factors and update the vertical grid
+   !!   dom_vvl_interpol : Interpolate vertical scale factors from one grid point to another
+   !!   dom_vvl_rst      : read/write restart file
+   !!   dom_vvl_ctl      : Check the vvl options
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE phycst          ! physical constant
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! ocean surface boundary condition
+   USE wet_dry         ! wetting and drying
+   USE usrdef_istate   ! user defined initial state (wad only)
+   USE restart         ! ocean restart
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O manager library
+   USE lib_mpp         ! distributed memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE timing          ! Timing
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC  dom_vvl_init       ! called by domain.F90
+   PUBLIC  dom_vvl_sf_nxt     ! called by step.F90
+   PUBLIC  dom_vvl_sf_swp     ! called by step.F90
+   PUBLIC  dom_vvl_interpol   ! called by dynnxt.F90
+
+   !                                                      !!* Namelist nam_vvl
+   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 = .FALSE.                ! debug control prints
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: un_td, vn_td                ! thickness diffusion transport
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: hdiv_lf                     ! low frequency part of hz divergence
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_b, tilde_e3t_n    ! baroclinic scale factors
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: tilde_e3t_a, dtilde_e3t_a   ! baroclinic scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_e3t                 ! retoring period for scale factors
+   REAL(wp)        , ALLOCATABLE, SAVE, DIMENSION(:,:)   :: frq_rst_hdv                 ! retoring period for low freq. divergence
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION dom_vvl_alloc()
+      !!----------------------------------------------------------------------
+      !!                ***  FUNCTION dom_vvl_alloc  ***
+      !!----------------------------------------------------------------------
+      IF( ln_vvl_zstar )   dom_vvl_alloc = 0
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         ALLOCATE( tilde_e3t_b(jpi,jpj,jpk)  , tilde_e3t_n(jpi,jpj,jpk) , tilde_e3t_a(jpi,jpj,jpk) ,   &
+            &      dtilde_e3t_a(jpi,jpj,jpk) , un_td  (jpi,jpj,jpk)     , vn_td  (jpi,jpj,jpk)     ,   &
+            &      STAT = dom_vvl_alloc        )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+         un_td = 0._wp
+         vn_td = 0._wp
+      ENDIF
+      IF( ln_vvl_ztilde ) THEN
+         ALLOCATE( frq_rst_e3t(jpi,jpj) , frq_rst_hdv(jpi,jpj) , hdiv_lf(jpi,jpj,jpk) , STAT= dom_vvl_alloc )
+         CALL mpp_sum ( 'domvvl', dom_vvl_alloc )
+         IF( dom_vvl_alloc /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_alloc: failed to allocate arrays' )
+      ENDIF
+      !
+   END FUNCTION dom_vvl_alloc
+
+
+   SUBROUTINE dom_vvl_init
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_init  ***
+      !!                   
+      !! ** Purpose :  Initialization of all scale factors, depths
+      !!               and water column heights
+      !!
+      !! ** Method  :  - use restart file and/or initialize
+      !!               - interpolate scale factors
+      !!
+      !! ** Action  : - e3t_(n/b) and tilde_e3t_(n/b)
+      !!              - Regrid: e3(u/v)_n
+      !!                        e3(u/v)_b       
+      !!                        e3w_n           
+      !!                        e3(u/v)w_b      
+      !!                        e3(u/v)w_n      
+      !!                        gdept_n, gdepw_n and gde3w_n
+      !!              - h(t/u/v)_0
+      !!              - frq_rst_e3t and frq_rst_hdv
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   ii0, ii1, ij0, ij1
+      REAL(wp)::   zcoef
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'dom_vvl_init : Variable volume activated'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~'
+      !
+      CALL dom_vvl_ctl     ! choose vertical coordinate (z_star, z_tilde or layer)
+      !
+      !                    ! Allocate module arrays
+      IF( dom_vvl_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'dom_vvl_init : unable to allocate arrays' )
+      !
+      !                    ! Read or initialize e3t_(b/n), tilde_e3t_(b/n) and hdiv_lf
+      CALL dom_vvl_rst( nit000, 'READ' )
+      e3t_a(:,:,jpk) = e3t_0(:,:,jpk)  ! last level always inside the sea floor set one for all
+      !
+      !                    !== Set of all other vertical scale factors  ==!  (now and before)
+      !                                ! Horizontal interpolation of e3t
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3u_b(:,:,:), 'U' )    ! from T to U
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3u_n(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3v_b(:,:,:), 'V' )    ! from T to V 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3v_n(:,:,:), 'V' )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F' )    ! from U to F
+      !                                ! Vertical interpolation of e3t,u,v 
+      CALL dom_vvl_interpol( e3t_n(:,:,:), e3w_n (:,:,:), 'W'  )  ! from T to W
+      CALL dom_vvl_interpol( e3t_b(:,:,:), e3w_b (:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )  ! from U to UW
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )  ! from V to UW
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! We need to define e3[tuv]_a for AGRIF initialisation (should not be a problem for the restartability...)
+      e3t_a(:,:,:) = e3t_n(:,:,:)
+      e3u_a(:,:,:) = e3u_n(:,:,:)
+      e3v_a(:,:,:) = e3v_n(:,:,:)
+      !
+      !                    !==  depth of t and w-point  ==!   (set the isf depth as it is in the initial timestep)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)       ! reference to the ocean surface (used for MLD and light penetration)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)  ! reference to a common level z=0 for hpg
+      gdept_b(:,:,1) = 0.5_wp * e3w_b(:,:,1)
+      gdepw_b(:,:,1) = 0.0_wp
+      DO jk = 2, jpk                               ! vertical sum
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               !    zcoef = tmask - wmask    ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+               !                             ! 1 everywhere from mbkt to mikt + 1 or 1 (if no isf)
+               !                             ! 0.5 where jk = mikt     
+!!gm ???????   BUG ?  gdept_n as well as gde3w_n  does not include the thickness of ISF ??
+               zcoef = ( tmask(ji,jj,jk) - wmask(ji,jj,jk) )
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =      zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk)) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+               gdepw_b(ji,jj,jk) = gdepw_b(ji,jj,jk-1) + e3t_b(ji,jj,jk-1)
+               gdept_b(ji,jj,jk) =      zcoef  * ( gdepw_b(ji,jj,jk  ) + 0.5 * e3w_b(ji,jj,jk))  &
+                  &                + (1-zcoef) * ( gdept_b(ji,jj,jk-1) +       e3w_b(ji,jj,jk)) 
+            END DO
+         END DO
+      END DO
+      !
+      !                    !==  thickness of the water column  !!   (ocean portion only)
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)   !!gm  BUG  :  this should be 1/2 * e3w(k=1) ....
+      hu_b(:,:) = e3u_b(:,:,1) * umask(:,:,1)
+      hu_n(:,:) = e3u_n(:,:,1) * umask(:,:,1)
+      hv_b(:,:) = e3v_b(:,:,1) * vmask(:,:,1)
+      hv_n(:,:) = e3v_n(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         hu_b(:,:) = hu_b(:,:) + e3u_b(:,:,jk) * umask(:,:,jk)
+         hu_n(:,:) = hu_n(:,:) + e3u_n(:,:,jk) * umask(:,:,jk)
+         hv_b(:,:) = hv_b(:,:) + e3v_b(:,:,jk) * vmask(:,:,jk)
+         hv_n(:,:) = hv_n(:,:) + e3v_n(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !
+      !                    !==  inverse of water column thickness   ==!   (u- and v- points)
+      r1_hu_b(:,:) = ssumask(:,:) / ( hu_b(:,:) + 1._wp - ssumask(:,:) )    ! _i mask due to ISF
+      r1_hu_n(:,:) = ssumask(:,:) / ( hu_n(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_b(:,:) = ssvmask(:,:) / ( hv_b(:,:) + 1._wp - ssvmask(:,:) )
+      r1_hv_n(:,:) = ssvmask(:,:) / ( hv_n(:,:) + 1._wp - ssvmask(:,:) )
+
+      !                    !==   z_tilde coordinate case  ==!   (Restoring frequencies)
+      IF( ln_vvl_ztilde ) THEN
+!!gm : idea: add here a READ in a file of custumized restoring frequency
+         !                                   ! Values in days provided via the namelist
+         !                                   ! use rsmall to avoid possible division by zero errors with faulty settings
+         frq_rst_e3t(:,:) = 2._wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.0_wp )
+         frq_rst_hdv(:,:) = 2._wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.0_wp )
+         !
+         IF( ln_vvl_ztilde_as_zstar ) THEN   ! z-star emulation using z-tile
+            frq_rst_e3t(:,:) = 0._wp               !Ignore namelist settings
+            frq_rst_hdv(:,:) = 1._wp / rdt
+         ENDIF
+         IF ( ln_vvl_zstar_at_eqtor ) THEN   ! use z-star in vicinity of the Equator
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+!!gm  case |gphi| >= 6 degrees is useless   initialized just above by default
+                  IF( ABS(gphit(ji,jj)) >= 6.) THEN
+                     ! values outside the equatorial band and transition zone (ztilde)
+                     frq_rst_e3t(ji,jj) =  2.0_wp * rpi / ( MAX( rn_rst_e3t  , rsmall ) * 86400.e0_wp )
+                     frq_rst_hdv(ji,jj) =  2.0_wp * rpi / ( MAX( rn_lf_cutoff, rsmall ) * 86400.e0_wp )
+                  ELSEIF( ABS(gphit(ji,jj)) <= 2.5) THEN    ! Equator strip ==> z-star
+                     ! values inside the equatorial band (ztilde as zstar)
+                     frq_rst_e3t(ji,jj) =  0.0_wp
+                     frq_rst_hdv(ji,jj) =  1.0_wp / rdt
+                  ELSE                                      ! transition band (2.5 to 6 degrees N/S)
+                     !                                      ! (linearly transition from z-tilde to z-star)
+                     frq_rst_e3t(ji,jj) = 0.0_wp + (frq_rst_e3t(ji,jj)-0.0_wp)*0.5_wp   &
+                        &            * (  1.0_wp - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                     frq_rst_hdv(ji,jj) = (1.0_wp / rdt)                                &
+                        &            + (  frq_rst_hdv(ji,jj)-(1.e0_wp / rdt) )*0.5_wp   &
+                        &            * (  1._wp  - COS( rad*(ABS(gphit(ji,jj))-2.5_wp)  &
+                        &                                          * 180._wp / 3.5_wp ) )
+                  ENDIF
+               END DO
+            END DO
+            IF( cn_cfg == "orca" .OR. cn_cfg == "ORCA" ) THEN
+               IF( nn_cfg == 3 ) THEN   ! ORCA2: Suppress ztilde in the Foxe Basin for ORCA2
+                  ii0 = 103   ;   ii1 = 111       
+                  ij0 = 128   ;   ij1 = 135   ;   
+                  frq_rst_e3t( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  0.0_wp
+                  frq_rst_hdv( mi0(ii0):mi1(ii1) , mj0(ij0):mj1(ij1) ) =  1.e0_wp / rdt
+               ENDIF
+            ENDIF
+         ENDIF
+      ENDIF
+      !
+      IF(lwxios) THEN
+! define variables in restart file when writing with XIOS
+         CALL iom_set_rstw_var_active('e3t_b')
+         CALL iom_set_rstw_var_active('e3t_n')
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_set_rstw_var_active('tilde_e3t_b')
+            CALL iom_set_rstw_var_active('tilde_e3t_n')
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_set_rstw_var_active('hdiv_lf')
+         ENDIF
+         !
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_init
+
+
+   SUBROUTINE dom_vvl_sf_nxt( kt, kcall ) 
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_nxt  ***
+      !!                   
+      !! ** Purpose :  - compute the after scale factors used in tra_zdf, dynnxt,
+      !!                 tranxt and dynspg routines
+      !!
+      !! ** Method  :  - z_star case:  Repartition of ssh INCREMENT proportionnaly to the level thickness.
+      !!               - z_tilde_case: after scale factor increment = 
+      !!                                    high frequency part of horizontal divergence
+      !!                                  + retsoring towards the background grid
+      !!                                  + thickness difusion
+      !!                               Then repartition of ssh INCREMENT proportionnaly
+      !!                               to the "baroclinic" level thickness.
+      !!
+      !! ** Action  :  - hdiv_lf    : restoring towards full baroclinic divergence in z_tilde case
+      !!               - tilde_e3t_a: after increment of vertical scale factor 
+      !!                              in z_tilde case
+      !!               - e3(t/u/v)_a
+      !!
+      !! Reference  : Leclair, M., and Madec, G. 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )           ::   kt      ! time step
+      INTEGER, INTENT( in ), OPTIONAL ::   kcall   ! optional argument indicating call sequence
+      !
+      INTEGER                ::   ji, jj, jk            ! dummy loop indices
+      INTEGER , DIMENSION(3) ::   ijk_max, ijk_min      ! temporary integers
+      REAL(wp)               ::   z2dt, z_tmin, z_tmax  ! local scalars
+      LOGICAL                ::   ll_do_bclinic         ! local logical
+      REAL(wp), DIMENSION(jpi,jpj)     ::   zht, z_scale, zwu, zwv, zhdiv
+      REAL(wp), DIMENSION(jpi,jpj,jpk) ::   ze3t
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_nxt')
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_nxt : compute after scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~'
+      ENDIF
+
+      ll_do_bclinic = .TRUE.
+      IF( PRESENT(kcall) ) THEN
+         IF( kcall == 2 .AND. ln_vvl_ztilde )   ll_do_bclinic = .FALSE.
+      ENDIF
+
+      ! ******************************* !
+      ! After acale factors at t-points !
+      ! ******************************* !
+      !                                                ! --------------------------------------------- !
+      !                                                ! z_star coordinate and barotropic z-tilde part !
+      !                                                ! --------------------------------------------- !
+      !
+      z_scale(:,:) = ( ssha(:,:) - sshb(:,:) ) * ssmask(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+      DO jk = 1, jpkm1
+         ! formally this is the same as e3t_a = e3t_0*(1+ssha/ht_0)
+         e3t_a(:,:,jk) = e3t_b(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+      END DO
+      !
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer .AND. ll_do_bclinic ) THEN   ! z_tilde or layer coordinate !
+         !                                                            ! ------baroclinic part------ !
+         ! I - initialization
+         ! ==================
+
+         ! 1 - barotropic divergence
+         ! -------------------------
+         zhdiv(:,:) = 0._wp
+         zht(:,:)   = 0._wp
+         DO jk = 1, jpkm1
+            zhdiv(:,:) = zhdiv(:,:) + e3t_n(:,:,jk) * hdivn(:,:,jk)
+            zht  (:,:) = zht  (:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         zhdiv(:,:) = zhdiv(:,:) / ( zht(:,:) + 1. - tmask_i(:,:) )
+
+         ! 2 - Low frequency baroclinic horizontal divergence  (z-tilde case only)
+         ! --------------------------------------------------
+         IF( ln_vvl_ztilde ) THEN
+            IF( kt > nit000 ) THEN
+               DO jk = 1, jpkm1
+                  hdiv_lf(:,:,jk) = hdiv_lf(:,:,jk) - rdt * frq_rst_hdv(:,:)   &
+                     &          * ( hdiv_lf(:,:,jk) - e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) )
+               END DO
+            ENDIF
+         ENDIF
+
+         ! II - after z_tilde increments of vertical scale factors
+         ! =======================================================
+         tilde_e3t_a(:,:,:) = 0._wp  ! tilde_e3t_a used to store tendency terms
+
+         ! 1 - High frequency divergence term
+         ! ----------------------------------
+         IF( ln_vvl_ztilde ) THEN     ! z_tilde case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - ( e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) - hdiv_lf(:,:,jk) )
+            END DO
+         ELSE                         ! layer case
+            DO jk = 1, jpkm1
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) -   e3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) * tmask(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 2 - Restoring term (z-tilde case only)
+         ! ------------------
+         IF( ln_vvl_ztilde ) THEN
+            DO jk = 1, jpk
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - frq_rst_e3t(:,:) * tilde_e3t_b(:,:,jk)
+            END DO
+         ENDIF
+
+         ! 3 - Thickness diffusion term
+         ! ----------------------------
+         zwu(:,:) = 0._wp
+         zwv(:,:) = 0._wp
+         DO jk = 1, jpkm1        ! a - first derivative: diffusive fluxes
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  un_td(ji,jj,jk) = rn_ahe3 * umask(ji,jj,jk) * e2_e1u(ji,jj)           &
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji+1,jj  ,jk) )
+                  vn_td(ji,jj,jk) = rn_ahe3 * vmask(ji,jj,jk) * e1_e2v(ji,jj)           & 
+                     &            * ( tilde_e3t_b(ji,jj,jk) - tilde_e3t_b(ji  ,jj+1,jk) )
+                  zwu(ji,jj) = zwu(ji,jj) + un_td(ji,jj,jk)
+                  zwv(ji,jj) = zwv(ji,jj) + vn_td(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         DO jj = 1, jpj          ! b - correction for last oceanic u-v points
+            DO ji = 1, jpi
+               un_td(ji,jj,mbku(ji,jj)) = un_td(ji,jj,mbku(ji,jj)) - zwu(ji,jj)
+               vn_td(ji,jj,mbkv(ji,jj)) = vn_td(ji,jj,mbkv(ji,jj)) - zwv(ji,jj)
+            END DO
+         END DO
+         DO jk = 1, jpkm1        ! c - second derivative: divergence of diffusive fluxes
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  tilde_e3t_a(ji,jj,jk) = tilde_e3t_a(ji,jj,jk) + (   un_td(ji-1,jj  ,jk) - un_td(ji,jj,jk)    &
+                     &                                          +     vn_td(ji  ,jj-1,jk) - vn_td(ji,jj,jk)    &
+                     &                                            ) * r1_e1e2t(ji,jj)
+               END DO
+            END DO
+         END DO
+         !                       ! d - thickness diffusion transport: boundary conditions
+         !                             (stored for tracer advction and continuity equation)
+         CALL lbc_lnk_multi( 'domvvl', un_td , 'U' , -1._wp, vn_td , 'V' , -1._wp)
+
+         ! 4 - Time stepping of baroclinic scale factors
+         ! ---------------------------------------------
+         ! Leapfrog time stepping
+         ! ~~~~~~~~~~~~~~~~~~~~~~
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            z2dt =  rdt
+         ELSE
+            z2dt = 2.0_wp * rdt
+         ENDIF
+         CALL lbc_lnk( 'domvvl', tilde_e3t_a(:,:,:), 'T', 1._wp )
+         tilde_e3t_a(:,:,:) = tilde_e3t_b(:,:,:) + z2dt * tmask(:,:,:) * tilde_e3t_a(:,:,:)
+
+         ! Maximum deformation control
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         ze3t(:,:,jpk) = 0._wp
+         DO jk = 1, jpkm1
+            ze3t(:,:,jk) = tilde_e3t_a(:,:,jk) / e3t_0(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:)
+         END DO
+         z_tmax = MAXVAL( ze3t(:,:,:) )
+         CALL mpp_max( 'domvvl', z_tmax )                 ! max over the global domain
+         z_tmin = MINVAL( ze3t(:,:,:) )
+         CALL mpp_min( 'domvvl', z_tmin )                 ! min over the global domain
+         ! - ML - test: for the moment, stop simulation for too large e3_t variations
+         IF( ( z_tmax >  rn_zdef_max ) .OR. ( z_tmin < - rn_zdef_max ) ) THEN
+            IF( lk_mpp ) THEN
+               CALL mpp_maxloc( 'domvvl', ze3t, tmask, z_tmax, ijk_max )
+               CALL mpp_minloc( 'domvvl', ze3t, tmask, z_tmin, ijk_min )
+            ELSE
+               ijk_max = MAXLOC( ze3t(:,:,:) )
+               ijk_max(1) = ijk_max(1) + nimpp - 1
+               ijk_max(2) = ijk_max(2) + njmpp - 1
+               ijk_min = MINLOC( ze3t(:,:,:) )
+               ijk_min(1) = ijk_min(1) + nimpp - 1
+               ijk_min(2) = ijk_min(2) + njmpp - 1
+            ENDIF
+            IF (lwp) THEN
+               WRITE(numout, *) 'MAX( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmax
+               WRITE(numout, *) 'at i, j, k=', ijk_max
+               WRITE(numout, *) 'MIN( tilde_e3t_a(:,:,:) / e3t_0(:,:,:) ) =', z_tmin
+               WRITE(numout, *) 'at i, j, k=', ijk_min            
+               CALL ctl_stop( 'STOP', 'MAX( ABS( tilde_e3t_a(:,:,: ) ) / e3t_0(:,:,:) ) too high')
+            ENDIF
+         ENDIF
+         ! - ML - end test
+         ! - ML - Imposing these limits will cause a baroclinicity error which is corrected for below
+         tilde_e3t_a(:,:,:) = MIN( tilde_e3t_a(:,:,:),   rn_zdef_max * e3t_0(:,:,:) )
+         tilde_e3t_a(:,:,:) = MAX( tilde_e3t_a(:,:,:), - rn_zdef_max * e3t_0(:,:,:) )
+
+         !
+         ! "tilda" change in the after scale factor
+         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) - tilde_e3t_b(:,:,jk)
+         END DO
+         ! III - Barotropic repartition of the sea surface height over the baroclinic profile
+         ! ==================================================================================
+         ! add ( ssh increment + "baroclinicity error" ) proportionly to e3t(n)
+         ! - ML - baroclinicity error should be better treated in the future
+         !        i.e. locally and not spread over the water column.
+         !        (keep in mind that the idea is to reduce Eulerian velocity as much as possible)
+         zht(:,:) = 0.
+         DO jk = 1, jpkm1
+            zht(:,:)  = zht(:,:) + tilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_scale(:,:) =  - zht(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
+         DO jk = 1, jpkm1
+            dtilde_e3t_a(:,:,jk) = dtilde_e3t_a(:,:,jk) + e3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
+         END DO
+
+      ENDIF
+
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer )  THEN   ! z_tilde or layer coordinate !
+      !                                           ! ---baroclinic part--------- !
+         DO jk = 1, jpkm1
+            e3t_a(:,:,jk) = e3t_a(:,:,jk) + dtilde_e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+      ENDIF
+
+      IF( ln_vvl_dbg .AND. .NOT. ll_do_bclinic ) THEN   ! - ML - test: control prints for debuging
+         !
+         IF( lwp ) WRITE(numout, *) 'kt =', kt
+         IF ( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+            z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( zht(:,:) ) )
+            CALL mpp_max( 'domvvl', z_tmax )                             ! max over the global domain
+            IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(SUM(tilde_e3t_a))) =', z_tmax
+         END IF
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshn(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshn-SUM(e3t_n))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_a(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + ssha(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+ssha-SUM(e3t_a))) =', z_tmax
+         !
+         zht(:,:) = 0.0_wp
+         DO jk = 1, jpkm1
+            zht(:,:) = zht(:,:) + e3t_b(:,:,jk) * tmask(:,:,jk)
+         END DO
+         z_tmax = MAXVAL( tmask(:,:,1) * tmask_i(:,:) * ABS( ht_0(:,:) + sshb(:,:) - zht(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ht_0+sshb-SUM(e3t_b))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshb(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshb))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( sshn(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(sshn))) =', z_tmax
+         !
+         z_tmax = MAXVAL( tmask(:,:,1) *  ABS( ssha(:,:) ) )
+         CALL mpp_max( 'domvvl', z_tmax )                                ! max over the global domain
+         IF( lwp    ) WRITE(numout, *) kt,' MAXVAL(abs(ssha))) =', z_tmax
+      END IF
+
+      ! *********************************** !
+      ! After scale factors at u- v- points !
+      ! *********************************** !
+
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3u_a(:,:,:), 'U' )
+      CALL dom_vvl_interpol( e3t_a(:,:,:), e3v_a(:,:,:), 'V' )
+
+      ! *********************************** !
+      ! After depths at u- v points         !
+      ! *********************************** !
+
+      hu_a(:,:) = e3u_a(:,:,1) * umask(:,:,1)
+      hv_a(:,:) = e3v_a(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         hu_a(:,:) = hu_a(:,:) + e3u_a(:,:,jk) * umask(:,:,jk)
+         hv_a(:,:) = hv_a(:,:) + e3v_a(:,:,jk) * vmask(:,:,jk)
+      END DO
+      !                                        ! Inverse of the local depth
+!!gm BUG ?  don't understand the use of umask_i here .....
+      r1_hu_a(:,:) = ssumask(:,:) / ( hu_a(:,:) + 1._wp - ssumask(:,:) )
+      r1_hv_a(:,:) = ssvmask(:,:) / ( hv_a(:,:) + 1._wp - ssvmask(:,:) )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_nxt')
+      !
+   END SUBROUTINE dom_vvl_sf_nxt
+
+
+   SUBROUTINE dom_vvl_sf_swp( kt )
+      !!----------------------------------------------------------------------
+      !!                ***  ROUTINE dom_vvl_sf_swp  ***
+      !!                   
+      !! ** Purpose :  compute time filter and swap of scale factors 
+      !!               compute all depths and related variables for next time step
+      !!               write outputs and restart file
+      !!
+      !! ** Method  :  - swap of e3t with trick for volume/tracer conservation
+      !!               - reconstruct scale factor at other grid points (interpolate)
+      !!               - recompute depths and water height fields
+      !!
+      !! ** Action  :  - e3t_(b/n), tilde_e3t_(b/n) and e3(u/v)_n ready for next time step
+      !!               - Recompute:
+      !!                    e3(u/v)_b       
+      !!                    e3w_n           
+      !!                    e3(u/v)w_b      
+      !!                    e3(u/v)w_n      
+      !!                    gdept_n, gdepw_n  and gde3w_n
+      !!                    h(u/v) and h(u/v)r
+      !!
+      !! Reference  : Leclair, M., and G. Madec, 2009, Ocean Modelling.
+      !!              Leclair, M., and G. Madec, 2011, Ocean Modelling.
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! time step
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcoef        ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF( ln_linssh )   RETURN      ! No calculation in linear free surface
+      !
+      IF( ln_timing )   CALL timing_start('dom_vvl_sf_swp')
+      !
+      IF( kt == nit000 )   THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'dom_vvl_sf_swp : - time filter and swap of scale factors'
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   - interpolate scale factors and compute depths for next time step'
+      ENDIF
+      !
+      ! Time filter and swap of scale factors
+      ! =====================================
+      ! - ML - e3(t/u/v)_b are allready computed in dynnxt.
+      IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN
+         IF( neuler == 0 .AND. kt == nit000 ) THEN
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:)
+         ELSE
+            tilde_e3t_b(:,:,:) = tilde_e3t_n(:,:,:) & 
+            &         + atfp * ( tilde_e3t_b(:,:,:) - 2.0_wp * tilde_e3t_n(:,:,:) + tilde_e3t_a(:,:,:) )
+         ENDIF
+         tilde_e3t_n(:,:,:) = tilde_e3t_a(:,:,:)
+      ENDIF
+      gdept_b(:,:,:) = gdept_n(:,:,:)
+      gdepw_b(:,:,:) = gdepw_n(:,:,:)
+
+      e3t_n(:,:,:) = e3t_a(:,:,:)
+      e3u_n(:,:,:) = e3u_a(:,:,:)
+      e3v_n(:,:,:) = e3v_a(:,:,:)
+
+      ! Compute all missing vertical scale factor and depths
+      ! ====================================================
+      ! Horizontal scale factor interpolations
+      ! --------------------------------------
+      ! - ML - e3u_b and e3v_b are allready computed in dynnxt
+      ! - JC - hu_b, hv_b, hur_b, hvr_b also
+      
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3f_n(:,:,:), 'F'  )
+      
+      ! Vertical scale factor interpolations
+      CALL dom_vvl_interpol( e3t_n(:,:,:),  e3w_n(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_n(:,:,:), e3uw_n(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_n(:,:,:), e3vw_n(:,:,:), 'VW' )
+      CALL dom_vvl_interpol( e3t_b(:,:,:),  e3w_b(:,:,:), 'W'  )
+      CALL dom_vvl_interpol( e3u_b(:,:,:), e3uw_b(:,:,:), 'UW' )
+      CALL dom_vvl_interpol( e3v_b(:,:,:), e3vw_b(:,:,:), 'VW' )
+
+      ! t- and w- points depth (set the isf depth as it is in the initial step)
+      gdept_n(:,:,1) = 0.5_wp * e3w_n(:,:,1)
+      gdepw_n(:,:,1) = 0.0_wp
+      gde3w_n(:,:,1) = gdept_n(:,:,1) - sshn(:,:)
+      DO jk = 2, jpk
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+              !    zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))   ! 0 everywhere tmask = wmask, ie everywhere expect at jk = mikt
+                                                                 ! 1 for jk = mikt
+               zcoef = (tmask(ji,jj,jk) - wmask(ji,jj,jk))
+               gdepw_n(ji,jj,jk) = gdepw_n(ji,jj,jk-1) + e3t_n(ji,jj,jk-1)
+               gdept_n(ji,jj,jk) =    zcoef  * ( gdepw_n(ji,jj,jk  ) + 0.5 * e3w_n(ji,jj,jk) )  &
+                   &             + (1-zcoef) * ( gdept_n(ji,jj,jk-1) +       e3w_n(ji,jj,jk) ) 
+               gde3w_n(ji,jj,jk) = gdept_n(ji,jj,jk) - sshn(ji,jj)
+            END DO
+         END DO
+      END DO
+
+      ! Local depth and Inverse of the local depth of the water
+      ! -------------------------------------------------------
+      hu_n(:,:) = hu_a(:,:)   ;   r1_hu_n(:,:) = r1_hu_a(:,:)
+      hv_n(:,:) = hv_a(:,:)   ;   r1_hv_n(:,:) = r1_hv_a(:,:)
+      !
+      ht_n(:,:) = e3t_n(:,:,1) * tmask(:,:,1)
+      DO jk = 2, jpkm1
+         ht_n(:,:) = ht_n(:,:) + e3t_n(:,:,jk) * tmask(:,:,jk)
+      END DO
+
+      ! write restart file
+      ! ==================
+      IF( lrst_oce  )   CALL dom_vvl_rst( kt, 'WRITE' )
+      !
+      IF( ln_timing )   CALL timing_stop('dom_vvl_sf_swp')
+      !
+   END SUBROUTINE dom_vvl_sf_swp
+
+
+   SUBROUTINE dom_vvl_interpol( pe3_in, pe3_out, pout )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl__interpol  ***
+      !!
+      !! ** Purpose :   interpolate scale factors from one grid point to another
+      !!
+      !! ** Method  :   e3_out = e3_0 + interpolation(e3_in - e3_0)
+      !!                - horizontal interpolation: grid cell surface averaging
+      !!                - vertical interpolation: simple averaging
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::  pe3_in    ! input e3 to be interpolated
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::  pe3_out   ! output interpolated e3
+      CHARACTER(LEN=*)                , INTENT(in   ) ::  pout      ! grid point of out scale factors
+      !                                                             !   =  'U', 'V', 'W, 'F', 'UW' or 'VW'
+      !
+      INTEGER ::   ji, jj, jk                                       ! dummy loop indices
+      REAL(wp) ::  zlnwd                                            ! =1./0. when ln_wd_il = T/F
+      !!----------------------------------------------------------------------
+      !
+      IF(ln_wd_il) THEN
+        zlnwd = 1.0_wp
+      ELSE
+        zlnwd = 0.0_wp
+      END IF
+      !
+      SELECT CASE ( pout )    !==  type of interpolation  ==!
+         !
+      CASE( 'U' )                   !* from T- to U-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2u(ji,jj)   &
+                     &                       * (   e1e2t(ji  ,jj) * ( pe3_in(ji  ,jj,jk) - e3t_0(ji  ,jj,jk) )     &
+                     &                           + e1e2t(ji+1,jj) * ( pe3_in(ji+1,jj,jk) - e3t_0(ji+1,jj,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'U', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3u_0(:,:,:)
+         !
+      CASE( 'V' )                   !* from T- to V-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * ( vmask(ji,jj,jk)  * (1.0_wp - zlnwd) + zlnwd ) * r1_e1e2v(ji,jj)   &
+                     &                       * (   e1e2t(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3t_0(ji,jj  ,jk) )     &
+                     &                           + e1e2t(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3t_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'V', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3v_0(:,:,:)
+         !
+      CASE( 'F' )                   !* from U-point to F-point : hor. surface weighted mean
+         DO jk = 1, jpk
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  pe3_out(ji,jj,jk) = 0.5_wp * (  umask(ji,jj,jk) * umask(ji,jj+1,jk) * (1.0_wp - zlnwd) + zlnwd ) &
+                     &                       *    r1_e1e2f(ji,jj)                                                  &
+                     &                       * (   e1e2u(ji,jj  ) * ( pe3_in(ji,jj  ,jk) - e3u_0(ji,jj  ,jk) )     &
+                     &                           + e1e2u(ji,jj+1) * ( pe3_in(ji,jj+1,jk) - e3u_0(ji,jj+1,jk) ) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( 'domvvl', pe3_out(:,:,:), 'F', 1._wp )
+         pe3_out(:,:,:) = pe3_out(:,:,:) + e3f_0(:,:,:)
+         !
+      CASE( 'W' )                   !* from T- to W-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3w_0(:,:,1) + pe3_in(:,:,1) - e3t_0(:,:,1)
+         ! - ML - The use of mask in this formulea enables the special treatment of the last w-point without indirect adressing
+!!gm BUG? use here wmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3w_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )   &
+               &                            * ( pe3_in(:,:,jk-1) - e3t_0(:,:,jk-1) )                               &
+               &                            +            0.5_wp * ( tmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )     &
+               &                            * ( pe3_in(:,:,jk  ) - e3t_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'UW' )                  !* from U- to UW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3uw_0(:,:,1) + pe3_in(:,:,1) - e3u_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wumask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3uw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3u_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( umask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3u_0(:,:,jk  ) )
+         END DO
+         !
+      CASE( 'VW' )                  !* from V- to VW-point : vertical simple mean
+         !
+         pe3_out(:,:,1) = e3vw_0(:,:,1) + pe3_in(:,:,1) - e3v_0(:,:,1)
+         ! - ML - The use of mask in this formaula enables the special treatment of the last w- point without indirect adressing
+!!gm BUG? use here wvmask in case of ISF ?  to be checked
+         DO jk = 2, jpk
+            pe3_out(:,:,jk) = e3vw_0(:,:,jk) + ( 1.0_wp - 0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd ) )  &
+               &                             * ( pe3_in(:,:,jk-1) - e3v_0(:,:,jk-1) )                              &
+               &                             +            0.5_wp * ( vmask(:,:,jk) * (1.0_wp - zlnwd) + zlnwd )    &
+               &                             * ( pe3_in(:,:,jk  ) - e3v_0(:,:,jk  ) )
+         END DO
+      END SELECT
+      !
+   END SUBROUTINE dom_vvl_interpol
+
+
+   SUBROUTINE dom_vvl_rst( kt, cdrw )
+      !!---------------------------------------------------------------------
+      !!                   ***  ROUTINE dom_vvl_rst  ***
+      !!                     
+      !! ** Purpose :   Read or write VVL file in restart file
+      !!
+      !! ** Method  :   use of IOM library
+      !!                if the restart does not contain vertical scale factors,
+      !!                they are set to the _0 values
+      !!                if the restart does not contain vertical scale factors increments (z_tilde),
+      !!                they are set to 0.
+      !!----------------------------------------------------------------------
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
+      !
+      INTEGER ::   ji, jj, jk
+      INTEGER ::   id1, id2, id3, id4, id5     ! local integers
+      !!----------------------------------------------------------------------
+      !
+      IF( TRIM(cdrw) == 'READ' ) THEN        ! Read/initialise 
+         !                                   ! ===============
+         IF( ln_rstart ) THEN                   !* Read the restart file
+            CALL rst_read_open                  !  open the restart file if necessary
+            CALL iom_get( numror, jpdom_autoglo, 'sshn'   , sshn, ldxios = lrxios    )
+            !
+            id1 = iom_varid( numror, 'e3t_b', ldstop = .FALSE. )
+            id2 = iom_varid( numror, 'e3t_n', ldstop = .FALSE. )
+            id3 = iom_varid( numror, 'tilde_e3t_b', ldstop = .FALSE. )
+            id4 = iom_varid( numror, 'tilde_e3t_n', ldstop = .FALSE. )
+            id5 = iom_varid( numror, 'hdiv_lf', ldstop = .FALSE. )
+            !                             ! --------- !
+            !                             ! all cases !
+            !                             ! --------- !
+            IF( MIN( id1, id2 ) > 0 ) THEN       ! all required arrays exist
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               ! needed to restart if land processor not computed 
+               IF(lwp) write(numout,*) 'dom_vvl_rst : e3t_b and e3t_n found in restart files'
+               WHERE ( tmask(:,:,:) == 0.0_wp ) 
+                  e3t_n(:,:,:) = e3t_0(:,:,:)
+                  e3t_b(:,:,:) = e3t_0(:,:,:)
+               END WHERE
+               IF( neuler == 0 ) THEN
+                  e3t_b(:,:,:) = e3t_n(:,:,:)
+               ENDIF
+            ELSE IF( id1 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_n set equal to e3t_b.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_b', e3t_b(:,:,:), ldxios = lrxios )
+               e3t_n(:,:,:) = e3t_b(:,:,:)
+               neuler = 0
+            ELSE IF( id2 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_b not found in restart files'
+               IF(lwp) write(numout,*) 'e3t_b set equal to e3t_n.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'e3t_n', e3t_n(:,:,:), ldxios = lrxios )
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ELSE
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : e3t_n not found in restart file'
+               IF(lwp) write(numout,*) 'Compute scale factor from sshn'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:) ) &
+                      &                          / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                      &          + e3t_0(:,:,jk)                               * (1._wp -tmask(:,:,jk))
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+               neuler = 0
+            ENDIF
+            !                             ! ----------- !
+            IF( ln_vvl_zstar ) THEN       ! z_star case !
+               !                          ! ----------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN
+                  CALL ctl_stop( 'dom_vvl_rst: z_star cannot restart from a z_tilde or layer run' )
+               ENDIF
+               !                          ! ----------------------- !
+            ELSE                          ! z_tilde and layer cases !
+               !                          ! ----------------------- !
+               IF( MIN( id3, id4 ) > 0 ) THEN  ! all required arrays exist
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lrxios )
+                  CALL iom_get( numror, jpdom_autoglo, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lrxios )
+               ELSE                            ! one at least array is missing
+                  tilde_e3t_b(:,:,:) = 0.0_wp
+                  tilde_e3t_n(:,:,:) = 0.0_wp
+               ENDIF
+               !                          ! ------------ !
+               IF( ln_vvl_ztilde ) THEN   ! z_tilde case !
+                  !                       ! ------------ !
+                  IF( id5 > 0 ) THEN  ! required array exists
+                     CALL iom_get( numror, jpdom_autoglo, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lrxios )
+                  ELSE                ! array is missing
+                     hdiv_lf(:,:,:) = 0.0_wp
+                  ENDIF
+               ENDIF
+            ENDIF
+            !
+         ELSE                                   !* Initialize at "rest"
+            !
+
+            IF( ll_wd ) THEN   ! MJB ll_wd edits start here - these are essential 
+               !
+               IF( cn_cfg == 'wad' ) THEN
+                  ! Wetting and drying test case
+                  CALL usr_def_istate( gdept_b, tmask, tsb, ub, vb, sshb  )
+                  tsn  (:,:,:,:) = tsb (:,:,:,:)       ! set now values from to before ones
+                  sshn (:,:)     = sshb(:,:)
+                  un   (:,:,:)   = ub  (:,:,:)
+                  vn   (:,:,:)   = vb  (:,:,:)
+               ELSE
+                  ! if not test case
+                  sshn(:,:) = -ssh_ref
+                  sshb(:,:) = -ssh_ref
+
+                  DO jj = 1, jpj
+                     DO ji = 1, jpi
+                        IF( ht_0(ji,jj)-ssh_ref <  rn_wdmin1 ) THEN ! if total depth is less than min depth
+
+                           sshb(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           sshn(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                           ssha(ji,jj) = rn_wdmin1 - (ht_0(ji,jj) )
+                        ENDIF
+                     ENDDO
+                  ENDDO
+               ENDIF !If test case else
+
+               ! Adjust vertical metrics for all wad
+               DO jk = 1, jpk
+                  e3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:)  ) &
+                    &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                    &            + e3t_0(:,:,jk) * ( 1._wp - tmask(:,:,jk) )
+               END DO
+               e3t_b(:,:,:) = e3t_n(:,:,:)
+
+               DO ji = 1, jpi
+                  DO jj = 1, jpj
+                     IF ( ht_0(ji,jj) .LE. 0.0 .AND. NINT( ssmask(ji,jj) ) .EQ. 1) THEN
+                       CALL ctl_stop( 'dom_vvl_rst: ht_0 must be positive at potentially wet points' )
+                     ENDIF
+                  END DO 
+               END DO 
+               !
+            ELSE
+               !
+               ! usr_def_istate called here only to get sshb, that is needed to initialize e3t_b and e3t_n
+               CALL usr_def_istate( gdept_0, tmask, tsb, ub, vb, sshb  )  
+               ! usr_def_istate will be called again in istate_init to initialize ts(bn), ssh(bn), u(bn) and v(bn)
+               !
+               DO jk=1,jpk
+                  e3t_b(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshb(:,:) ) &
+                    &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk)   &
+                    &            + e3t_0(:,:,jk) * ( 1._wp - tmask(:,:,jk) )   ! make sure e3t_b != 0 on land points
+               END DO
+               e3t_n(:,:,:) = e3t_b(:,:,:)
+               sshn(:,:) = sshb(:,:)   ! needed later for gde3w
+!!$                e3t_n(:,:,:)=e3t_0(:,:,:)
+!!$                e3t_b(:,:,:)=e3t_0(:,:,:)
+               !
+            END IF           ! end of ll_wd edits
+
+            IF( ln_vvl_ztilde .OR. ln_vvl_layer) THEN
+               tilde_e3t_b(:,:,:) = 0._wp
+               tilde_e3t_n(:,:,:) = 0._wp
+               IF( ln_vvl_ztilde ) hdiv_lf(:,:,:) = 0._wp
+            END IF
+         ENDIF
+         !
+      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
+         !                                   ! ===================
+         IF(lwp) WRITE(numout,*) '---- dom_vvl_rst ----'
+         IF( lwxios ) CALL iom_swap(      cwxios_context          )
+         !                                           ! --------- !
+         !                                           ! all cases !
+         !                                           ! --------- !
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_b', e3t_b(:,:,:), ldxios = lwxios )
+         CALL iom_rstput( kt, nitrst, numrow, 'e3t_n', e3t_n(:,:,:), ldxios = lwxios )
+         !                                           ! ----------------------- !
+         IF( ln_vvl_ztilde .OR. ln_vvl_layer ) THEN  ! z_tilde and layer cases !
+            !                                        ! ----------------------- !
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_b', tilde_e3t_b(:,:,:), ldxios = lwxios)
+            CALL iom_rstput( kt, nitrst, numrow, 'tilde_e3t_n', tilde_e3t_n(:,:,:), ldxios = lwxios)
+         END IF
+         !                                           ! -------------!    
+         IF( ln_vvl_ztilde ) THEN                    ! z_tilde case !
+            !                                        ! ------------ !
+            CALL iom_rstput( kt, nitrst, numrow, 'hdiv_lf', hdiv_lf(:,:,:), ldxios = lwxios)
+         ENDIF
+         !
+         IF( lwxios ) CALL iom_swap(      cxios_context          )
+      ENDIF
+      !
+   END SUBROUTINE dom_vvl_rst
+
+
+   SUBROUTINE dom_vvl_ctl
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE dom_vvl_ctl  ***
+      !!                
+      !! ** Purpose :   Control the consistency between namelist options
+      !!                for vertical coordinate
+      !!----------------------------------------------------------------------
+      INTEGER ::   ioptio, ios
+      !!
+      NAMELIST/nam_vvl/ ln_vvl_zstar, ln_vvl_ztilde, ln_vvl_layer, ln_vvl_ztilde_as_zstar, &
+         &              ln_vvl_zstar_at_eqtor      , rn_ahe3     , rn_rst_e3t            , &
+         &              rn_lf_cutoff               , rn_zdef_max , ln_vvl_dbg                ! not yet implemented: ln_vvl_kepe
+      !!---------------------------------------------------------------------- 
+      !
+      REWIND( numnam_ref )              ! Namelist nam_vvl in reference namelist : 
+      READ  ( numnam_ref, nam_vvl, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 )   CALL ctl_nam ( ios , 'nam_vvl in reference namelist' )
+      REWIND( numnam_cfg )              ! Namelist nam_vvl in configuration namelist : Parameters of the run
+      READ  ( numnam_cfg, nam_vvl, IOSTAT = ios, ERR = 902 )
+902   IF( ios >  0 ) CALL ctl_nam ( ios , 'nam_vvl in configuration namelist' )
+      IF(lwm) WRITE ( numond, nam_vvl )
+      !
+      IF(lwp) THEN                    ! Namelist print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dom_vvl_ctl : choice/control of the variable vertical coordinate'
+         WRITE(numout,*) '~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist nam_vvl : chose a vertical coordinate'
+         WRITE(numout,*) '      zstar                      ln_vvl_zstar   = ', ln_vvl_zstar
+         WRITE(numout,*) '      ztilde                     ln_vvl_ztilde  = ', ln_vvl_ztilde
+         WRITE(numout,*) '      layer                      ln_vvl_layer   = ', ln_vvl_layer
+         WRITE(numout,*) '      ztilde as zstar   ln_vvl_ztilde_as_zstar  = ', ln_vvl_ztilde_as_zstar
+         WRITE(numout,*) '      ztilde near the equator    ln_vvl_zstar_at_eqtor  = ', ln_vvl_zstar_at_eqtor
+         WRITE(numout,*) '      !'
+         WRITE(numout,*) '      thickness diffusion coefficient                      rn_ahe3      = ', rn_ahe3
+         WRITE(numout,*) '      maximum e3t deformation fractional change            rn_zdef_max  = ', rn_zdef_max
+         IF( ln_vvl_ztilde_as_zstar ) THEN
+            WRITE(numout,*) '      ztilde running in zstar emulation mode (ln_vvl_ztilde_as_zstar=T) '
+            WRITE(numout,*) '         ignoring namelist timescale parameters and using:'
+            WRITE(numout,*) '            hard-wired : z-tilde to zstar restoration timescale (days)'
+            WRITE(numout,*) '                         rn_rst_e3t     = 0.e0'
+            WRITE(numout,*) '            hard-wired : z-tilde cutoff frequency of low-pass filter (days)'
+            WRITE(numout,*) '                         rn_lf_cutoff   = 1.0/rdt'
+         ELSE
+            WRITE(numout,*) '      z-tilde to zstar restoration timescale (days)        rn_rst_e3t   = ', rn_rst_e3t
+            WRITE(numout,*) '      z-tilde cutoff frequency of low-pass filter (days)   rn_lf_cutoff = ', rn_lf_cutoff
+         ENDIF
+         WRITE(numout,*) '         debug prints flag                                 ln_vvl_dbg   = ', ln_vvl_dbg
+      ENDIF
+      !
+      ioptio = 0                      ! Parameter control
+      IF( ln_vvl_ztilde_as_zstar )   ln_vvl_ztilde = .true.
+      IF( ln_vvl_zstar           )   ioptio = ioptio + 1
+      IF( ln_vvl_ztilde          )   ioptio = ioptio + 1
+      IF( ln_vvl_layer           )   ioptio = ioptio + 1
+      !
+      IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE vertical coordinate in namelist nam_vvl' )
+      IF( .NOT. ln_vvl_zstar .AND. ln_isf ) CALL ctl_stop( 'Only vvl_zstar has been tested with ice shelf cavity' )
+      !
+      IF(lwp) THEN                   ! Print the choice
+         WRITE(numout,*)
+         IF( ln_vvl_zstar           ) WRITE(numout,*) '      ==>>>   zstar vertical coordinate is used'
+         IF( ln_vvl_ztilde          ) WRITE(numout,*) '      ==>>>   ztilde vertical coordinate is used'
+         IF( ln_vvl_layer           ) WRITE(numout,*) '      ==>>>   layer vertical coordinate is used'
+         IF( ln_vvl_ztilde_as_zstar ) WRITE(numout,*) '      ==>>>   to emulate a zstar coordinate'
+      ENDIF
+      !
+#if defined key_agrif
+      IF( (.NOT.Agrif_Root()).AND.(.NOT.ln_vvl_zstar) )   CALL ctl_stop( 'AGRIF is implemented with zstar coordinate only' )
+#endif
+      !
+   END SUBROUTINE dom_vvl_ctl
+
+   !!======================================================================
+END MODULE domvvl
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,131 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_hgr  ***
+   !!
+   !!                      ===  VORTEX configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  NEMO  ! 2017-11  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for VORTEX configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx, rn_dy, rn_ppgphi0   ! horizontal resolution in meters
+   !                                                  and reference latitude
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                VORTEX configuration : beta-plance with uniform grid spacing (rn_dx)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zphi0, zlam0, zbeta, zf0
+      REAL(wp) ::   zti, zui, ztj, zvj   ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : VORTEX configuration bassin'
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          Beta-plane with regular grid-spacing'
+      IF(lwp) WRITE(numout,*) '          given by rn_dx and rn_dy' 
+      !
+      !                          
+      ! Position coordinates (in kilometers)
+      !                          ==========
+      zlam0 = -(jpiglo-1)/2 * 1.e-3 * rn_dx
+      zphi0 = -(jpjglo-1)/2 * 1.e-3 * rn_dy 
+
+#if defined key_agrif
+      ! ! let lower left longitude and latitude from parent
+      IF (.NOT.Agrif_root()) THEN
+          zlam0 = (0.5_wp-(Agrif_parent(jpiglo)-1)/2)*1.e-3*Agrif_irhox()*rn_dx &
+             &+(Agrif_Ix()+nbghostcells-1)*Agrif_irhox()*rn_dx*1.e-3-(0.5_wp+nbghostcells)*rn_dx*1.e-3
+          zphi0 = (0.5_wp-(Agrif_parent(jpjglo)-1)/2)*1.e-3*Agrif_irhoy()*rn_dy &
+             &+(Agrif_Iy()+nbghostcells-1)*Agrif_irhoy()*rn_dy*1.e-3-(0.5_wp+nbghostcells)*rn_dy*1.e-3
+      ENDIF 
+#endif
+         
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zti = FLOAT( ji - 1 + nimpp - 1 )          ;  ztj = FLOAT( jj - 1 + njmpp - 1 )
+            zui = FLOAT( ji - 1 + nimpp - 1 ) + 0.5_wp ;  zvj = FLOAT( jj - 1 + njmpp - 1 ) + 0.5_wp
+
+            plamt(ji,jj) = zlam0 + rn_dx * 1.e-3 * zti
+            plamu(ji,jj) = zlam0 + rn_dx * 1.e-3 * zui
+            plamv(ji,jj) = plamt(ji,jj) 
+            plamf(ji,jj) = plamu(ji,jj) 
+   
+            pphit(ji,jj) = zphi0 + rn_dy * 1.e-3 * ztj
+            pphiv(ji,jj) = zphi0 + rn_dy * 1.e-3 * zvj
+            pphiu(ji,jj) = pphit(ji,jj) 
+            pphif(ji,jj) = pphiv(ji,jj) 
+         END DO
+      END DO
+      !     
+      ! Horizontal scale factors (in meters)
+      !                              ======
+      pe1t(:,:) = rn_dx  ;   pe2t(:,:) = rn_dy 
+      pe1u(:,:) = rn_dx  ;   pe2u(:,:) = rn_dy 
+      pe1v(:,:) = rn_dx  ;   pe2v(:,:) = rn_dy 
+      pe1f(:,:) = rn_dx  ;   pe2f(:,:) = rn_dy 
+
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_hgr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      zbeta = 2._wp * omega * COS( rad * rn_ppgphi0 ) / ra
+      zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+      pff_f(:,:) = zf0 + zbeta * pphif(:,:) * 1.e+3
+      pff_t(:,:) = zf0 + zbeta * pphit(:,:) * 1.e+3
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,144 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                      ===  VORTEX configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2017-11  (J. Chanut) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce , ONLY : glamt, gphit, glamu, gphiu, glamv, gphiv  
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   !   
+   USE usrdef_nam, ONLY : rn_ppgphi0  ! Reference latitude   
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called by istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here VORTEX configuration 
+      !!
+      !! ** Method  :   Set a gaussian anomaly of pressure and associated
+      !!                geostrophic velocities
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      !
+      INTEGER  :: ji, jj, jk  ! dummy loop indices
+      REAL(wp) :: zx, zy, zP0, zumax, zlambda, zn2, zf0, zH, zrho1, za, zf
+      REAL(wp) :: zdt, zdu, zdv
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : VORTEX configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   '
+      !
+      !
+      !
+      zf0   = 2._wp * omega * SIN( rad * rn_ppgphi0 )
+      zumax = 1._wp * SIGN(1._wp, zf0) ! Here Anticyclonic: set zumax=-1 for cyclonic
+      zlambda = SQRT(2._wp)*60.e3      ! Horizontal scale in meters 
+      zn2 = 3.e-3**2
+      zH = 0.5_wp * 5000._wp
+      !
+      zP0 = rau0 * zf0 * zumax * zlambda * SQRT(EXP(1._wp)/2._wp)
+      !
+      ! Sea level:
+      za = -zP0 * (1._wp-EXP(-zH)) / (grav*(zH-1._wp + EXP(-zH)))
+      DO ji=1, jpi
+         DO jj=1, jpj
+            zx = glamt(ji,jj) * 1.e3
+            zy = gphit(ji,jj) * 1.e3
+            zrho1 = rau0 + za * EXP(-(zx**2+zy**2)/zlambda**2)
+            pssh(ji,jj) = zP0 * EXP(-(zx**2+zy**2)/zlambda**2)/(zrho1*grav) * ptmask(ji,jj,1)
+         END DO
+      END DO
+      !
+      ! temperature:         
+      DO ji=1, jpi
+         DO jj=1, jpj
+            zx = glamt(ji,jj) * 1.e3
+            zy = gphit(ji,jj) * 1.e3
+            DO jk=1,jpk
+               zdt =  pdept(ji,jj,jk) 
+               zrho1 = rau0 * (1._wp + zn2*zdt/grav)
+               IF (zdt < zH) THEN
+                  zrho1 = zrho1 - zP0 * (1._wp-EXP(zdt-zH)) &
+                          & * EXP(-(zx**2+zy**2)/zlambda**2) / (grav*(zH -1._wp + exp(-zH)));
+               ENDIF
+               pts(ji,jj,jk,jp_tem) = (20._wp + (rau0-zrho1) / 0.28_wp) * ptmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      ! salinity:  
+      pts(:,:,:,jp_sal) = 35._wp 
+      !
+      ! velocities:
+      za = 2._wp * zP0 / (zf0 * rau0 * zlambda**2)
+      DO ji=1, jpim1
+         DO jj=1, jpj
+            zx = glamu(ji,jj) * 1.e3
+            zy = gphiu(ji,jj) * 1.e3
+            DO jk=1, jpk
+               zdu = 0.5_wp * (pdept(ji  ,jj,jk) + pdept(ji+1,jj,jk))
+               IF (zdu < zH) THEN
+                  zf = (zH-1._wp-zdu+EXP(zdu-zH)) / (zH-1._wp+EXP(-zH))
+                  pu(ji,jj,jk) = (za * zf * zy * EXP(-(zx**2+zy**2)/zlambda**2)) * ptmask(ji,jj,jk) * ptmask(ji+1,jj,jk)
+               ELSE
+                  pu(ji,jj,jk) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      END DO
+      !
+      DO ji=1, jpi
+         DO jj=1, jpjm1
+            zx = glamv(ji,jj) * 1.e3
+            zy = gphiv(ji,jj) * 1.e3
+            DO jk=1, jpk
+               zdv = 0.5_wp * (pdept(ji  ,jj,jk) + pdept(ji,jj+1,jk))
+               IF (zdv < zH) THEN
+                  zf = (zH-1._wp-zdv+EXP(zdv-zH)) / (zH-1._wp+EXP(-zH))
+                  pv(ji,jj,jk) = -(za * zf * zx * EXP(-(zx**2+zy**2)/zlambda**2)) * ptmask(ji,jj,jk) * ptmask(ji,jj+1,jk)
+               ELSE
+                  pv(ji,jj,jk) = 0._wp
+               ENDIF
+            END DO
+         END DO
+      END DO
+
+      CALL lbc_lnk( 'usrdef_istate', pu, 'U', -1. )
+      CALL lbc_lnk( 'usrdef_istate', pv, 'V', -1. )
+      !   
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,120 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_nam  ***
+   !!
+   !!                      ===  VORTEX configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  NEMO ! 2017-10  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                              !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dy      ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dz      ! vertical resolution 
+   REAL(wp), PUBLIC ::   rn_ppgphi0 ! reference latitude for beta-plane 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here VORTEX configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios          ! Local integer
+      REAL(wp)::   zlx, zly, zh ! Local scalars
+      !!
+      NAMELIST/namusr_def/  rn_dx, rn_dy, rn_dz, rn_ppgphi0
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+#if defined key_agrif 
+      ! Domain parameters are taken from parent:
+      IF( .NOT. Agrif_Root() ) THEN
+         rn_dx = Agrif_Parent(rn_dx)/Agrif_Rhox()
+         rn_dy = Agrif_Parent(rn_dy)/Agrif_Rhoy()
+         rn_dz = Agrif_Parent(rn_dz)
+         rn_ppgphi0 = Agrif_Parent(rn_ppgphi0)
+      ENDIF
+#endif
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      cd_cfg = 'VORTEX'             ! name & resolution (not used)
+      kk_cfg = nINT( rn_dx )
+      !
+      IF( Agrif_Root() ) THEN       ! Global Domain size:  VORTEX global domain is  1800 km x 1800 Km x 5000 m
+         kpi = NINT( 1800.e3  / rn_dx ) + 3  
+         kpj = NINT( 1800.e3  / rn_dy ) + 3 
+      ELSE
+         kpi  = nbcellsx + 2 + 2*nbghostcells
+         kpj  = nbcellsy + 2 + 2*nbghostcells
+      ENDIF
+      kpk = NINT( 5000._wp / rn_dz ) + 1
+      !
+      zlx = (kpi-2)*rn_dx*1.e-3
+      zly = (kpj-2)*rn_dy*1.e-3
+      zh  = (kpk-1)*rn_dz
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! VORTEX configuration : closed basin
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : VORTEX test case'
+         WRITE(numout,*) '      horizontal resolution             rn_dx  = ', rn_dx, ' m'
+         WRITE(numout,*) '      horizontal resolution             rn_dy  = ', rn_dy, ' m'
+         WRITE(numout,*) '      vertical resolution               rn_dz  = ', rn_dz, ' m'
+         WRITE(numout,*) '      VORTEX domain: '
+         WRITE(numout,*) '         LX [km]: ', zlx
+         WRITE(numout,*) '         LY [km]: ', zly
+         WRITE(numout,*) '          H [m] : ', zh
+         WRITE(numout,*) '      Reference latitude            rn_ppgphi0 = ', rn_ppgphi0
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      VORTEX : closed basin            jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,86 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_sbc  ***
+   !! 
+   !!                      ===  VORTEX configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2017-11  (J.Chanut)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_sbc    : user defined surface bounday conditions in OVERFLOW case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for VORTEX case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : VORTEX case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,238 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                       ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                      ===  VORTEX configuration  ===
+   !!
+   !! User defined : vertical coordinate system of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2017-11  (J. Chanut)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system
+   !!      zgr_z      : reference 1D z-coordinate 
+   !!      zgr_top_bot: ocean top and bottom level indices
+   !!      zgr_zco    : 3D verticl coordinate in pure z-coordinate case
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce        ! ocean domain
+   USE depth_e3       ! depth <=> e3
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+  !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   inum   ! local logical unit
+      REAL(WP) ::   z_zco, z_zps, z_sco, z_cav
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : VORTEX configuration (z-coordinate closed flat box ocean)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate
+      ! ---------------------------
+      ld_zco    = .TRUE.         ! VORTEX case:  z-coordinate without ocean cavities
+      ld_zps    = .FALSE.
+      ld_sco    = .FALSE.
+      ld_isfcav = .FALSE.
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      CALL zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      CALL zgr_msk_top_bot( k_top , k_bot )                 ! masked top and bottom ocean t-level indices
+      !
+      !                                                     ! z-coordinate (3D arrays) from the 1D z-coord.
+      CALL zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in  : 1D reference vertical coordinate
+         &          pdept   , pdepw   ,                     &   ! out : 3D t & w-points depth
+         &          pe3t    , pe3u    , pe3v   , pe3f   ,   &   !       vertical scale factors
+         &          pe3w    , pe3uw   , pe3vw             )     !           -      -      -
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z  ***
+      !!
+      !! ** Purpose :   set the 1D depth of model levels and the resulting 
+      !!              vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!           with at top and bottom :
+      !!                   e3w_1d( 1 ) = 2 * ( dept_1d( 1 ) - depw_1d( 1 ) )
+      !!                   e3t_1d(jpk) = 2 * ( dept_1d(jpk) - depw_1d(jpk) )
+      !!       The depth are then re-computed from the sum of e3. This ensures 
+      !!    that depths are identical when reading domain configuration file. 
+      !!    Indeed, only e3. are saved in this file, depth are compute by a call
+      !!    to the e3_to_depth subroutine.
+      !!
+      !!       Here the Madec & Imbard (1996) function is used.
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!
+      !! Reference : Marti, Madec & Delecluse, 1992, JGR, 97, No8, 12,763-12,766.
+      !!             Madec and Imbard, 1996, Clim. Dyn.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zd       ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zd = 5000._wp/FLOAT(jpkm1)
+      !
+      IF(lwp) THEN            ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z   : Reference vertical z-coordinates '
+         WRITE(numout,*) '    ~~~~~~~'
+         WRITE(numout,*) '       VORTEX case : uniform vertical grid :'
+         WRITE(numout,*) '                     with thickness = ', zd
+      ENDIF
+
+      !
+      ! 1D Reference z-coordinate    (using Madec & Imbard 1996 function)
+      ! -------------------------
+      !
+      pdepw_1d(1) = 0._wp
+      pdept_1d(1) = 0.5_wp * zd
+      ! 
+      DO jk = 2, jpk          ! depth at T and W-points
+         pdepw_1d(jk) = pdepw_1d(jk-1) + zd 
+         pdept_1d(jk) = pdept_1d(jk-1) + zd 
+      END DO
+      !
+      !                       ! e3t and e3w from depth
+      CALL depth_to_e3( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d ) 
+      !
+      !                       ! recompute depths from SUM(e3)  <== needed
+      CALL e3_to_depth( pe3t_1d, pe3w_1d, pdept_1d, pdepw_1d ) 
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z
+
+
+   SUBROUTINE zgr_msk_top_bot( k_top , k_bot )
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_msk_top_bot  ***
+      !!
+      !! ** Purpose :   set the masked top and bottom ocean t-levels
+      !!
+      !! ** Method  :   VORTEX case = closed flat box ocean without ocean cavities
+      !!                   k_top = 1     except along north, south, east and west boundaries
+      !!                   k_bot = jpk-1 except along north, south, east and west boundaries
+      !!
+      !! ** Action  : - k_top : first wet ocean level index
+      !!              - k_bot : last  wet ocean level index
+      !!----------------------------------------------------------------------
+      INTEGER , DIMENSION(:,:), INTENT(out) ::   k_top , k_bot   ! first & last wet ocean level
+      !
+      REAL(wp), DIMENSION(jpi,jpj) ::   z2d   ! 2D local workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_bot : defines the top and bottom wet ocean levels.'
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~'
+      IF(lwp) WRITE(numout,*) '       VORTEX case : closed flat box ocean without ocean cavities'
+      !
+      z2d(:,:) = REAL( jpkm1 , wp )          ! flat bottom
+      !
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )           ! set surrounding land to zero (here jperio=0 ==>> closed)
+      !
+      k_bot(:,:) = INT( z2d(:,:) )           ! =jpkm1 over the ocean point, =0 elsewhere
+      !
+      k_top(:,:) = MIN( 1 , k_bot(:,:) )     ! = 1    over the ocean point, =0 elsewhere
+      !
+   END SUBROUTINE zgr_msk_top_bot
+   
+
+   SUBROUTINE zgr_zco( pdept_1d, pdepw_1d, pe3t_1d, pe3w_1d,   &   ! in : 1D reference vertical coordinate
+      &                pdept   , pdepw   ,                     &   ! out: 3D t & w-points depth
+      &                pe3t    , pe3u    , pe3v   , pe3f   ,   &   !      vertical scale factors
+      &                pe3w    , pe3uw   , pe3vw             )     !          -      -      -
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE zgr_zco  ***
+      !!
+      !! ** Purpose :   define the reference z-coordinate system
+      !!
+      !! ** Method  :   set 3D coord. arrays to reference 1D array 
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth       [m]
+      REAL(wp), DIMENSION(:)    , INTENT(in   ) ::   pe3t_1d , pe3w_1d           ! 1D vertical scale factors [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pdept, pdepw                ! grid-point depth          [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors    [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   pe3w , pe3uw, pe3vw         !    -       -      -
+      !
+      INTEGER  ::   jk
+      !!----------------------------------------------------------------------
+      !
+      DO jk = 1, jpk
+         pdept(:,:,jk) = pdept_1d(jk)
+         pdepw(:,:,jk) = pdepw_1d(jk)
+         pe3t (:,:,jk) = pe3t_1d (jk)
+         pe3u (:,:,jk) = pe3t_1d (jk)
+         pe3v (:,:,jk) = pe3t_1d (jk)
+         pe3f (:,:,jk) = pe3t_1d (jk)
+         pe3w (:,:,jk) = pe3w_1d (jk)
+         pe3uw(:,:,jk) = pe3w_1d (jk)
+         pe3vw(:,:,jk) = pe3w_1d (jk)
+      END DO
+      !
+   END SUBROUTINE zgr_zco
+
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/cpp_VORTEX.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/cpp_VORTEX.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/VORTEX/cpp_VORTEX.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys key_iomput key_mpp_mpi key_agrif
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/README.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/README.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/README.py	(revision 14097)
@@ -0,0 +1,5 @@
+ncks -O -d y,17,17,1 WAD_1ts_00010101_00010101_grid_T.nc sshtime.nc
+ncks -4 -A -v gdepw_0,ht_wd -d y,17,17,1 -d z,10,10,1 -C mesh_mask.nc sshtime.nc
+
+python2.7 matpoly2.py sshtime.nc
+animate wadfr*.png
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/axis_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/axis_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/axis_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/axis_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/context_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/context_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/context_nemo.xml	(revision 14097)
@@ -0,0 +1,37 @@
+<!--
+ ============================================================================================== 
+    NEMO context
+============================================================================================== 
+-->
+<context id="nemo">
+    <!-- $id$ -->
+    <variable_definition>
+       <!-- Year/Month/Day of time origin for NetCDF files; defaults to 1800-01-01 -->
+       <variable id="ref_year"  type="int"> 1900 </variable>
+       <variable id="ref_month" type="int"> 01 </variable>
+       <variable id="ref_day"   type="int"> 01 </variable>
+       <variable id="rau0"      type="float" > 1026.0 </variable>
+       <variable id="cpocean"   type="float" > 3991.86795711963 </variable>
+       <variable id="convSpsu"  type="float" > 0.99530670233846  </variable>
+       <variable id="rhoic"     type="float" > 917.0 </variable>
+       <variable id="rhosn"     type="float" > 330.0 </variable>
+       <variable id="missval"  type="float" > 1.e20 </variable>	       
+    </variable_definition>
+
+<!-- Fields definition -->
+    <field_definition src="./field_def_nemo-oce.xml"/>   <!--  NEMO ocean dynamics                     -->
+
+<!-- Files definition -->
+    <file_definition src="./file_def_nemo-oce.xml"/>     <!--  NEMO ocean dynamics                     -->
+
+<!-- Axis definition -->
+    <axis_definition src="./axis_def_nemo.xml"/>
+ 
+<!-- Domain definition -->
+    <domain_definition src="./domain_def_nemo.xml"/>
+
+<!-- Grids definition -->
+    <grid_definition   src="./grid_def_nemo.xml"/>
+  
+
+</context>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/domain_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/domain_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/domain_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/domain_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/field_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/field_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/field_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/field_def_nemo-oce.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/file_def_nemo-oce.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/file_def_nemo-oce.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/file_def_nemo-oce.xml	(revision 14097)
@@ -0,0 +1,103 @@
+<?xml version="1.0"?>
+    <!-- 
+============================================================================================================
+=                                           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 id="file96" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="ssh"          name="sossheig"  />
+          <field field_ref="sss"          name="sosaline"  />
+	  <!--
+	  <field field_ref="wdmask"       name="wdmask"  />
+	  <field field_ref="wetdep"       name="wetdepth"  />
+          <field field_ref="toce"         name="votemper"  />
+          <field field_ref="soce"         name="vosaline"  />
+          -->
+        </file>
+	<file id="file87" name_suffix="_grid_U" description="ocean U grid variables" >
+	  <!--
+          <field field_ref="un_b"         name="un_b"    operation="instant"/>
+          <field field_ref="uoce"         name="vozocrtx" operation="instant"  />
+          -->
+          <field field_ref="ubar"         name="ubaro"    operation="instant"/>
+	  <!--
+          <field field_ref="un_b"         name="un_b"    operation="instant"/>
+          <field field_ref="ucli"         name="uc_un" operation="instant"  />
+          <field field_ref="ucli2"         name="uc_un2" operation="instant"  />
+          <field field_ref="ssu"         name="r1_hu_a" operation="instant"  />
+          <field field_ref="wdlmtu"         name="wdlmtu" operation="instant"  />
+          -->
+        </file>
+	<file id="file88" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="vbar"         name="vbaro"    operation="instant"/>
+        </file>
+      </file_group>
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."> <!-- 1h files -->
+	<file id="file97" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="ssh"          name="sossheig"  operation="instant"  />
+	  <field field_ref="e3t"          name="e3t"  operation="instant"  />
+          <field field_ref="toce"         name="votemper"  />
+      </file>
+      <file id="file98" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="ubar"         name="ubaro"    operation="instant"/>
+      </file>
+      </file_group>
+      <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 id="file1" 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"  />
+	  <field field_ref="empmr"        name="sowaflup"  />
+	  <field field_ref="qsr"          name="soshfldo"  />
+      <field field_ref="saltflx"      name="sosfldow"  />
+	  <field field_ref="qt"           name="sohefldo"  />
+	  <field field_ref="mldr10_1"     name="somxl010"  />
+	  <field field_ref="mldkz5"       name="somixhgt"  />
+    </file>
+	
+	<file id="file2" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="vozocrtx"  />
+          <field field_ref="utau"         name="sozotaux"  />
+    </file>
+	
+	<file id="file3" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vomecrty"  /> 
+          <field field_ref="vtau"         name="sometauy"  /> 
+    </file>
+	
+	<file id="file4" name_suffix="_grid_W" description="ocean W grid variables" >
+          <field field_ref="woce"         name="vovecrtz" />
+          <field field_ref="avt"          name="votkeavt" />
+    </file>
+
+      </file_group>
+
+      <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="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>
+
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/grid_def_nemo.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/grid_def_nemo.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/grid_def_nemo.xml	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/grid_def_nemo.xml
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/iodef.xml
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/iodef.xml	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/iodef.xml	(revision 14097)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<simulation>
+
+<!-- ============================================================================================ -->
+<!-- XIOS context                                                                                 -->
+<!-- ============================================================================================ -->
+
+  <context id="xios" >
+
+      <variable_definition>
+
+          <variable id="info_level"                type="int">10</variable>
+          <variable id="using_server"              type="bool">true</variable>
+          <variable id="using_oasis"               type="bool">false</variable>
+          <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+
+      </variable_definition>
+  </context>
+
+<!-- ============================================================================================ -->
+<!-- NEMO  CONTEXT add and suppress the components you need                                       -->
+<!-- ============================================================================================ -->
+
+  <context id="nemo" src="./context_nemo.xml"/>       <!--  NEMO       -->
+
+</simulation>
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/makebdy_tc7.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/makebdy_tc7.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/makebdy_tc7.py	(revision 14097)
@@ -0,0 +1,80 @@
+from netCDF4 import Dataset
+import numpy as np
+
+pathout = "bdyssh_tc7"
+
+nx = 34 
+ny = 1
+nt = 24
+ndays=4
+
+#-------------------------------------------------------
+# Create bdyssh_tc7_m01d01.nc, bdyssh_tc7_m01d02.nc etc.
+#-------------------------------------------------------
+
+pathstart="{}_m12d30.nc".format(pathout)
+for nd in range(ndays):
+ print pathstart
+ ssh = np.zeros((nt,ny,nx))
+ for nnt in range(nd*nt,(nd+1)*nt):
+   tx = 2.5*np.cos((3.141592654/6.0)*(nnt+1.0))
+   print nnt, tx
+   for nnx in range(nx):
+     for nny in range(ny):
+       ssh[nnt-nd*nt,nny,nnx] = tx
+
+
+ fo = Dataset(pathstart, 'w', format='NETCDF4')
+ nxo = fo.createDimension('x', nx)
+ nyo = fo.createDimension('y', ny)
+ nto = fo.createDimension('t', None)
+ ssho = fo.createVariable('sshbdy', 'f4',('t','y','x'))
+
+ ssho[:,:,:] = ssh[:,:,:]
+ ssho.long_name = 'bdy ssh boundary condition'
+ ssho.standard_name = 'sshbdy'
+ ssho.units = 'm'
+#
+ fo.close()
+ pathstart="{}_m01d{:0>2d}.nc".format(pathout,nd+1)
+
+#-------------------------------------------------------
+# Create bdyuv_tc7_m01d01.nc, bdyuv_tc7_m01d02.nc etc.
+# u is -(1/H)*d(ssh)/dt; v =0.0
+#-------------------------------------------------------
+
+pathout = "bdyuv_tc7"
+
+
+pathstart="{}_m12d30.nc".format(pathout)
+for nd in range(ndays):
+ print pathstart
+ u = np.zeros((nt,ny,nx))
+ for nnt in range(nd*nt,(nd+1)*nt):
+  tx = 2.5*(3.141592654/6.0)*np.sin((3.141592654/6.0)*(nnt+1.0))/10.0
+  print nnt, tx
+  for nnx in range(nx):
+    for nny in range(ny):
+       u[nnt-nd*nt,nny,nnx] = tx
+
+ v = np.zeros((nt,ny,nx))
+
+ fo = Dataset(pathstart, 'w', format='NETCDF4')
+ nxo = fo.createDimension('x', nx)
+ nyo = fo.createDimension('y', ny)
+ nto = fo.createDimension('t', None)
+ uo = fo.createVariable('ubdy', 'f4',('t','y','x'))
+ vo = fo.createVariable('vbdy', 'f4',('t','y','x'))
+
+ uo[:,:,:] = u[:,:,:]
+ uo.long_name = 'bdy u boundary condition'
+ uo.standard_name = 'ubdy'
+ uo.units = 'm/s'
+#
+ vo[:,:,:] = v[:,:,:]
+ vo.long_name = 'bdy v boundary condition'
+ vo.standard_name = 'vbdy'
+ vo.units = 'm/s'
+#
+ fo.close()
+ pathstart="{}_m01d{:0>2d}.nc".format(pathout,nd+1)
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_cfg
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_cfg	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_cfg	(revision 14097)
@@ -0,0 +1,477 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OCE  Configuration namelist : overwrite default values defined in SHARED/namelist_ref
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!!                      Wetting & Drying configuration                !!
+!!======================================================================
+!!              ***  Domain & Run management namelists  ***           !!
+!!                                                                    !!
+!!   namrun       parameters of the run
+!!   namdom       space and time domain
+!!   namcfg       parameters of the configuration                       (default: user defined GYRE)
+!!   namwad       Wetting and drying                                    (default: OFF)
+!!   namtsd       data: temperature & salinity                          (default: OFF)
+!!   namcrs       coarsened grid (for outputs and/or TOP)               (ln_crs =T)
+!!   namc1d       1D configuration options                              ("key_c1d")
+!!   namc1d_dyndmp 1D newtonian damping applied on currents             ("key_c1d")
+!!   namc1d_uvd   1D data (currents)                                    ("key_c1d")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namusr_def    !    Wetting and Drying TEST CASE
+!-----------------------------------------------------------------------
+   rn_dx       = 1500.0    ! horizontal resolution
+   rn_dz       = 1.0       ! vertical   resolution
+   nn_wad_test = 1         ! ???
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   cn_exp      =  "WAD"    !  experience name
+   nn_it000    =       1   !  first time step
+   nn_itend    =     3840  !  last  time step
+   !nn_itend   =       6   !  last  time step
+   nn_leapy    =      30   !  Leap year calendar (1) or not (0)
+   nn_stock    =    48000  !  frequency of creation of a restart file (modulo referenced to 1)
+
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+/
+!-----------------------------------------------------------------------
+&namdom        !   time and space domain
+!-----------------------------------------------------------------------
+   ln_linssh   = .false.   !  =T  linear free surface  ==>>  model level are fixed in time
+   !
+   ln_meshmask = .true.    !  create (>0) a mesh file or not (=0)
+   rn_rdt      =    18.    !  time step for the dynamics 
+/
+!-----------------------------------------------------------------------
+&namcfg        !   parameters of the configuration                      (default: user defined GYRE)
+!-----------------------------------------------------------------------
+   ln_read_cfg = .false.   !  (=T) read the domain configuration file
+      !                    !  (=F) user defined configuration  ==>>>  see usrdef(_...) modules
+   ln_write_cfg = .true.    !  (=T) create the domain configuration file
+/
+!-----------------------------------------------------------------------
+&namwad        !   Wetting and Drying (WaD)                             (default: OFF)
+!-----------------------------------------------------------------------
+   ln_wd_il    = .false    ! T/F activation of iterative   limiter
+   ln_wd_dl    = .true.    ! T/F activation of directional limiter
+   ln_wd_dl_bc = .true.    ! T/F Directional limiteer Baroclinic option
+   ln_wd_dl_rmp = .true.    ! T/F Turn on directional limiter ramp
+   rn_wdmin0   =  0.30     ! depth at which WaD starts
+   rn_wdmin1   =  0.2      ! Minimum wet depth on dried cells
+   rn_wdmin2   =  0.0001   ! Tolerance of min wet depth on dried cells
+   rn_wdld     =  2.5      ! Land elevation below which WaD is allowed
+   nn_wdit     =   20      ! Max iterations for WaD limiter
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***          !!
+!!                                                                    !!
+!!   namsbc          surface boundary condition manager                 (default: NO selection)
+!!   namsbc_flx      flux               formulation                     (ln_flx     =T)
+!!   namsbc_blk      Bulk formulae formulation                          (ln_blk     =T)
+!!   namsbc_cpl      CouPLed            formulation                     ("key_oasis3" )
+!!   namsbc_sas      Stand-Alone Surface module                         (SAS_SRC  only)
+!!   namsbc_iif      Ice-IF: use observed ice cover                     (nn_ice = 1   )
+!!   namtra_qsr      penetrative solar radiation                        (ln_traqsr  =T)
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)        (ln_ssr     =T)
+!!   namsbc_rnf      river runoffs                                      (ln_rnf     =T)
+!!   namsbc_apr      Atmospheric Pressure                               (ln_apr_dyn =T)
+!!   namsbc_isf      ice shelf melting/freezing                         (ln_isfcav  =T : read (ln_read_cfg=T) or set or usr_def_zgr )
+!!   namsbc_iscpl    coupling option between land ice model and ocean   (ln_isfcav  =T)
+!!   namsbc_wave     external fields from wave model                    (ln_wave    =T)
+!!   namberg         iceberg floats                                     (ln_icebergs=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 1         !  frequency of surface boundary condition computation
+   !                       !     (also = the frequency of sea-ice model call)
+   ln_usr      = .true.    !  analytical formulation                    (T => check usrdef_sbc)
+   nn_ice      = 0         !  =0 no ice boundary condition   ,
+   ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf )
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr )
+   nn_fwb      = 0         !  FreshWater Budget: =0 unchecked
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation                          (ln_traqsr =T)
+!-----------------------------------------------------------------------
+   ln_qsr_rgb  = .false.   !  RGB (Red-Green-Blue) light penetration
+   ln_qsr_2bd  = .true.    !  2 bands              light penetration
+   nn_chldta   =      0    !  RGB : Chl data (=1) or cst value (=0)
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring   (ln_ssr =T)
+!-----------------------------------------------------------------------
+   nn_sssr     =     0     !  add a damping     term in the surface freshwater flux (=2)
+   rn_deds     =   -27.7   !  magnitude of the damping on salinity   [mm/day]
+   ln_sssr_bnd =   .false. !  flag to bound erp term (associated with nn_sssr=2)
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs namelist surface boundary condition          (ln_rnf =T)
+!-----------------------------------------------------------------------
+   ln_rnf_mouth = .false.   !  specific treatment at rivers mouths
+/
+!!======================================================================
+!!               ***  Lateral boundary condition  ***                 !!
+!!                                                                    !!
+!!   namlbc        lateral momentum boundary condition                  (default: NO selection)
+!!   namagrif      agrif nested grid   (read by child model only)       ("key_agrif")
+!!   nam_tide      Tidal forcing                                        (default: OFF)
+!!   nambdy        Unstructured open boundaries                         (default: OFF)
+!!   nambdy_dta    Unstructured open boundaries - external data         (see  nambdy)
+!!   nambdy_tide   tidal forcing at open boundaries                     (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition                  (default: NO selection)
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  free slip
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          
+!-----------------------------------------------------------------------
+    ln_bdy         = .false.            
+    nb_bdy         = 0                    !  number of open boundary sets
+    ln_coords_file = .false.              !  =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       = 'flather'            !
+    nn_dyn2d_dta   =  1                   !  = 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        =  'frs'                !
+    nn_tra_dta    =  0                    !  = 0, bdy data are equal to the initial state
+                                          !  = 1, bdy data are read in 'bdydata   .nc' files
+    cn_ice        =  'none'               !
+    nn_ice_dta    =  0                    !  = 0, bdy data are equal to the initial state
+                                          !  = 1, bdy data are read in 'bdydata   .nc' files
+    rn_ice_tem    = 270.                  !  si3 only: arbitrary temperature of incoming sea ice
+    rn_ice_sal    = 10.                   !  si3 only:      --   salinity           --
+    rn_ice_age    = 30.                   !  si3 only:      --   age                --
+
+    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_index
+!-----------------------------------------------------------------------
+    ctypebdy = 'E'
+    nbdyind  = 50
+    nbdybeg  = 1
+    nbdyend  = 34
+    !ctypebdy = 'W'
+    !nbdyind  = 2
+    !nbdybeg  = 1
+    !nbdyend  = 34
+/
+!-----------------------------------------------------------------------
+&nambdy_dta    !  open boundaries - external data                       
+!-----------------------------------------------------------------------
+   ln_zinterp  = .false.      !  T if a vertical interpolation is required. Variables gdep[tuv] and e3[tuv] must exist in the file
+   !                          !  automatically defined to T if the number of vertical levels in bdy dta /= jpk
+   ln_full_vel = .false.      !  T if [uv]3d are "full" velocities and not only its baroclinic components
+   !                          !  in this case, baroclinic and barotropic velocities will be recomputed -> [uv]2d not needed
+   !
+   cn_dir  =  './'
+!              !  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 =     'bdyssh_tc7' ,         1.       , 'sshbdy',     .true.     , .true.  ,  'daily'  ,    ''    ,   ''     , ''
+   bn_u2d =     'bdyuv_tc7'  ,         1.       , 'ubdy'  ,     .true.     , .true.  ,  'daily'  ,    ''    ,   ''     , ''
+   bn_v2d =     'bdyuv_tc7'  ,         1.       , 'vbdy'  ,     .true.     , .true.  ,  'daily'  ,    ''    ,   ''     , ''
+/
+!-----------------------------------------------------------------------
+&nambdy_tide   !  tidal forcing at open boundaries
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                ***  Top/Bottom boundary condition  ***             !!
+!!                                                                    !!
+!!   namdrg        top/bottom drag coefficient                          (default: NO selection)
+!!   namdrg_top    top    friction                                      (ln_drg_OFF=F & ln_isfcav=T)
+!!   namdrg_bot    bottom friction                                      (ln_drg_OFF=F)
+!!   nambbc        bottom temperature boundary condition                (default: OFF)
+!!   nambbl        bottom boundary layer scheme                         (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdrg        !   top/bottom drag coefficient                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_loglayer = .false.    !  logarithmic drag: Cd = vkarmn/log(z/z0) |U|
+   ln_lin      = .true.    !      linear  drag: Cd = Cd0 Uc0                   &   namdrg_top)
+   ln_non_lin  = .false.   !  non-linear  drag: Cd = Cd0 |U|
+/
+!-----------------------------------------------------------------------
+&namdrg_top    !   TOP friction                                         (ln_isfcav=T)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdrg_bot    !   BOTTOM friction                                  
+!-----------------------------------------------------------------------
+   rn_Cd0     =  1.e-4    !  drag coefficient [-]
+   rn_Uc0     =  0.1      !  ref. velocity [m/s] (linear drag=Cd0*Uc0) 
+   rn_Cdmax   =  1.e-4    !  drag value maximum [-] (logarithmic drag)
+   rn_ke0     =  2.5e-3   !  background kinetic energy  [m2/s2] (non-linear cases)
+   rn_z0      =  3.e-3    !  roughness [m] (ln_loglayer=T)
+   ln_boost   = .false.   !  =T regional boost of Cd0 ; =F constant
+      rn_boost =  50.         !  local boost factor  [-]
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition                (default: OFF)
+!-----------------------------------------------------------------------
+   ln_trabbc   = .false.   !  Apply a geothermal heating at the ocean bottom
+   nn_geoflx   =    0      !  geothermal heat flux: = 0 no flux
+/
+!!======================================================================
+!!                        Tracer (T-S) namelists                      !!
+!!                                                                    !!
+!!   nameos        equation of state                                    (default: NO selection)
+!!   namtra_adv    advection scheme                                     (default: NO selection)
+!!   namtra_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namtra_mle    mixed layer eddy param. (Fox-Kemper param.)          (default: OFF)
+!!   namtra_eiv    eddy induced velocity param.                         (default: OFF)
+!!   namtra_dmp    T & S newtonian damping                              (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean Equation Of Seawater                           (default: OFF)
+!-----------------------------------------------------------------------
+   ln_teos10   = .false.         !  = Use TEOS-10 equation of state
+   ln_eos80    = .false.         !  = Use EOS80 equation of state
+   ln_seos     = .true.          !  = Use simplified equation of state (S-EOS)
+                                 !
+   !                     ! S-EOS coefficients (ln_seos=T):
+   !                             !  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                          (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_traadv_OFF =  .false.  !  No tracer advection
+   ln_traadv_cen =  .false.  !  2nd order centered scheme
+   ln_traadv_mus =  .false.  !  MUSCL scheme
+   ln_traadv_fct =  .true.   !  FCT scheme
+      nn_fct_h   =  2               !  =2/4, horizontal 2nd / 4th order 
+      nn_fct_v   =  2               !  =2/4, vertical   2nd / COMPACT 4th order 
+/
+!-----------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers                 (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap   =  .true.   !    laplacian operator
+   ln_traldf_blp   =  .false.  !  bilaplacian operator
+   !                       !  Direction of action:
+   ln_traldf_lev   =  .false.  !  iso-level
+   ln_traldf_hor   =  .false.  !  horizontal (geopotential)
+   ln_traldf_iso   =  .true.   !  iso-neutral
+   ln_traldf_triad =  .false.  !  iso-neutral using Griffies triads
+   !
+   !		       	         !  iso-neutral options:        
+   ln_traldf_msc   =  .false.  !  Method of Stabilizing Correction (both operators)
+   rn_slpmax       =   0.01    !  slope limit                      (both operators)
+   ln_triad_iso    =  .false.  !  pure horizontal mixing in ML     (triad only)
+   rn_sw_triad     =  1        !  =1 switching triad ; =0 all 4 triads used (triad only)
+   ln_botmix_triad =  .false.  !  lateral mixing on bottom         (triad only)
+   !
+   !                       !  Coefficients:
+   nn_aht_ijk_t    = 0         !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  aht = 1/2  Uv*Lv   (lap case) 
+      !                             !                            or  = 1/12 Uv*Lv^3 (blp case)
+      rn_Ud      = 0.2              !  lateral diffusive velocity [m/s] (nn_aht_ijk_t= 0, 10, 20, 30)
+      rn_Ld      = 10.e+3           !  lateral diffusive length   [m]   (nn_aht_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                      ***  Dynamics namelists  ***                  !!
+!!                                                                    !!
+!!   nam_vvl       vertical coordinate options                          (default: z-star)
+!!   namdyn_adv    formulation of the momentum advection                (default: NO selection)
+!!   namdyn_vor    advection scheme                                     (default: NO selection)
+!!   namdyn_hpg    hydrostatic pressure gradient                        (default: NO selection)
+!!   namdyn_spg    surface pressure gradient                            (default: NO selection)
+!!   namdyn_ldf    lateral diffusion scheme                             (default: NO selection)
+!!   namdta_dyn    offline TOP: dynamics read in files                  (OFF_SRC only)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection                (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_dynadv_OFF = .false. !  linear dynamics (no momentum advection)
+   ln_dynadv_vec = .true. !  vector form - 2nd centered scheme
+     nn_dynkeg     = 0        ! grad(KE) scheme: =0   C2  ;  =1   Hollingsworth correction
+   ln_dynadv_cen2 = .false. !  flux form - 2nd order centered scheme
+   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   Vorticity / Coriolis scheme                          (default: OFF)
+!-----------------------------------------------------------------------
+   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
+      nn_een_e3f = 0             !  e3f = masked averaging of e3t divided by 4 (=0) or by the sum of mask (=1)
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option                 (default: NO selection)
+!-----------------------------------------------------------------------
+   ln_hpg_zco  = .false.   !  z-coordinate - full steps
+   ln_hpg_zps  = .false.   !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.    !  s-coordinate
+/
+!-----------------------------------------------------------------------
+&namdyn_spg    !   surface pressure gradient                            (default: OFF)
+!-----------------------------------------------------------------------
+   ln_dynspg_ts  = .true.  !  split-explicit free surface
+   ln_bt_auto    = .false. ! Number of sub-step defined from:
+   nn_baro       =  12     ! =F : the number of sub-step in rn_rdt seconds
+/
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum                        (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   !                           !  no diffusion: set ln_dynldf_lap=..._blp=F 
+   ln_dynldf_lap =  .true.     !    laplacian operator
+   ln_dynldf_blp =  .false.    !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_lev =  .true.     !  iso-level
+   ln_dynldf_hor =  .false.    !  horizontal (geopotential)
+   ln_dynldf_iso =  .false.    !  iso-neutral
+   !                       !  Coefficient
+   nn_ahm_ijk_t  = 0           !  space/time variation of eddy coef
+      !                             !  =  0  constant 
+      !                        !  time invariant coefficients :  ahm = 1/2  Uv*Lv   (lap case) 
+      !                             !                            or  = 1/12 Uv*Lv^3 (blp case)
+      rn_Uv      = 2.0              !  lateral viscous velocity [m/s] (nn_ahm_ijk_t= 0, 10, 20, 30)
+      rn_Lv      = 10.e+3           !  lateral viscous length   [m]   (nn_ahm_ijk_t= 0, 10)
+/
+!!======================================================================
+!!                     vertical physics namelists                     !!
+!!                                                                    !!
+!!    namzdf        vertical physics manager                            (default: NO selection)
+!!    namzdf_ric    richardson number vertical mixing                   (ln_zdfric=T)
+!!    namzdf_tke    TKE vertical mixing                                 (ln_zdftke=T)
+!!    namzdf_gls    GLS vertical mixing                                 (ln_zdfgls=T)
+!!    namzdf_osm    OSM vertical diffusion                              (ln_zdfosm=T)
+!!    namzdf_iwm    tidal mixing parameterization                       (ln_zdfiwm=T)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics                                     (default: NO selection)
+!-----------------------------------------------------------------------
+   !                       ! type of vertical closure
+   ln_zdfcst   = .false.      !  constant mixing
+   ln_zdfric   = .false.      !  local Richardson dependent formulation (T =>   fill namzdf_ric)
+   ln_zdftke   = .true.       !  Turbulent Kinetic Energy closure       (T =>   fill namzdf_tke)
+   ln_zdfgls   = .false.      !  Generic Length Scale closure           (T =>   fill namzdf_gls)
+   ln_zdfosm   = .false.      !  OSMOSIS BL closure                     (T =>   fill namzdf_osm)
+   !
+   !                       ! convection
+   ln_zdfevd   = .true.       !  enhanced vertical diffusion
+      nn_evdm     =    1         ! apply on tracer (=0) or on tracer and momentum (=1)
+      rn_evd      =  100.        ! mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.      !  Non-Penetrative Convective algorithm
+      nn_npc      =    1         ! frequency of application of npc
+      nn_npcp     =  365         ! npc control print frequency
+   !
+   ln_zdfddm   = .false.   ! double diffusive mixing
+      rn_avts  =    1.e-4     !  maximum avs (vertical mixing on salinity)
+      rn_hsbfr =    1.6       !  heat/salt buoyancy flux ratio
+   !
+   !                       ! gravity wave-driven vertical mixing
+   ln_zdfiwm   = .false.      ! internal wave-induced mixing            (T =>   fill namzdf_iwm)
+   ln_zdfswm   = .false.      ! surface  wave-induced mixing            (T => ln_wave=ln_sdw=T )
+   !
+   !                       ! coefficients
+   rn_avm0     =   1.2e-4     !  vertical eddy viscosity   [m2/s]       (background Kz if ln_zdfcst=F)
+   rn_avt0     =   1.2e-5     !  vertical eddy diffusivity [m2/s]       (background Kz if ln_zdfcst=F)
+   nn_avb      =    0         !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0         !  horizontal shape for avtb (=1) or not (=0)
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  (ln_zdftke =T)
+!-----------------------------------------------------------------------
+   nn_etau     =   0       !  penetration of tke below the mixed layer (ML) due to internal & intertial waves
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***                   !!
+!!                                                                    !!
+!!   namtrd       dynamics and/or tracer trends                         (default: OFF)
+!!   namptr       Poleward Transport Diagnostics                        (default: OFF)
+!!   namhsb       Heat and salt budgets                                 (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namdiu       Cool skin and warm layer models                       (default: OFF)
+!!   namflo       float parameters                                      (default: OFF)
+!!   nam_diaharm  Harmonic analysis of tidal constituents               (default: OFF)
+!!   nam_diadct   transports through some sections                      (default: OFF)
+!!   nam_dia25h   25h Mean Output                                       (default: OFF)
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namtrd        !   trend diagnostics                                    (default F)
+!-----------------------------------------------------------------------
+   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)
+/
+!-----------------------------------------------------------------------
+&nam_diadct    !   transports through some sections                     (default: OFF)
+!-----------------------------------------------------------------------
+    ln_diadct  = .false.   ! Calculate transport thru sections or not
+    nn_dct      = 60       !  time step frequency for transports computing
+    nn_dctwri   = 60       !  time step frequency for transports writing
+    nn_secdebug = 0        !      0 : no section to debug
+/
+!!======================================================================
+!!               ***  Observation & Assimilation  ***                 !!
+!!                                                                    !!
+!!   namobs       observation and model comparison                      (default: OFF)
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***                 !!
+!!                                                                    !!
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi")
+!!   namctl            Control prints                                   (default: OFF)
+!!   namsto            Stochastic parametrization of EOS                (default: OFF)
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints                                       (default: OFF)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsto        ! Stochastic parametrization of EOS                      (default: OFF)
+!-----------------------------------------------------------------------
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_ref
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_ref	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/namelist_ref	(revision 14097)
@@ -0,0 +1,1 @@
+link ../../../cfgs/SHARED/namelist_ref
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/plotframes.py
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/plotframes.py	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/EXPREF/plotframes.py	(revision 14097)
@@ -0,0 +1,304 @@
+#!/usr/bin/env python
+################################################################################## 
+# Utility to produce animation frames directly from the WAD_TEST_CASE output.
+# It can be used without arguments, i.e.:
+#     python plotframes.py
+# in which case a frame is created every tenth time level from SSH data extracted from
+# WAD_1ts_00010101_00010101_grid_T.nc along the centre of the basin (j=17). A closed 
+# basin is assumed and frames are named wadfr0000.png etc. Bathymetry information is 
+# extracted from the mesh_mask.nc file. The frames are annotated with a timestamp that
+# assumes an 18s baroclinic timestep.
+# 
+# All these settings can be overridden with command-line arguments. See:
+#     python plotframes.py -h 
+# for details. For example:
+#     python plotframes.py  -nt 300 -stride 30 -froot mywad
+# 
+# Two major variations are also supported for specific test cases:
+#     python plotframes.py -obc
+# plots the right-hand side of the basin as an open boundary (test case 7) and:
+#     python plotframes.py -use_sal
+# colours each gridcell according to its salinity value (test case 6)
+################################################################################## 
+import os, sys
+from argparse import ArgumentParser
+import numpy as np
+import netCDF4
+
+import matplotlib.pyplot as plt
+import matplotlib
+from matplotlib.patches import Polygon
+from matplotlib.collections import PatchCollection
+from netCDF4 import Dataset
+
+#
+# Turn off the unhelpful warning about open figures
+#
+matplotlib.rcParams['figure.max_open_warning'] = 0
+
+if __name__ == '__main__':
+    parser = ArgumentParser(description=
+    """
+    produce frames for the animation of results from the WAD_TEST_CASES.
+    Mostly this can be run without arguments but command line arguments may be
+    used to override defaults. These are necessary in cases with open boundaries
+    (e.g. nn_wad_test=7) and cases where it is desired to show variations in salinity
+    (e.g. nn_wad_test=6).
+     e.g. plotframes.py -tfile <T-grid file> -bfile  <bathymetry file>
+    -froot <root name for frames>
+    -nt <maximum number of time frames to process>
+    -stride <stride through time frames> 
+    -rdt <length of baroclinic timestep (s)> 
+    -obc
+    -use_sal
+    """)
+    parser.add_argument('-tfile',dest='tfile',help='T-grid file if not WAD_1ts_00010101_00010101_grid_T.nc', default='WAD_1ts_00010101_00010101_grid_T.nc')
+    parser.add_argument('-bfile',dest='bfile',help='Bathymetry file if not mesh_mask.nc', default='mesh_mask.nc')
+    parser.add_argument('-j',dest='jrow',help='jrow; j-row to extract and plot (default: 17 (fortran index))', type=int, default=16)
+    parser.add_argument('-froot',dest='froot',help='froot; root name for frames (default: wadfr)', default='wadfr')
+    parser.add_argument('-nt',dest='nfmax',help='nfmax; maximum number of frames to produce', type=int, default=None)
+    parser.add_argument('-stride',dest='tinc',help='tinc; stride through time frames (default: 10)', type=int, default=10)
+    parser.add_argument('-rdt',dest='rdt',help='rdt; length of baroclinic timestep (s) (default: 18.0)', type=float, default=18.0)
+    parser.add_argument('-obc',help='Right-hand side boundary is open', action="store_true")
+    parser.add_argument('-use_sal',help='colour polygons according to salinity variations', action="store_true")
+    args   = parser.parse_args()
+    tfile  = args.tfile
+    bfile  = args.bfile
+    jrow   = args.jrow
+    froot  = args.froot
+    nfmax  = args.nfmax
+    stride = args.tinc
+    rdt    = args.rdt
+    obc    = args.obc
+    use_sal= args.use_sal
+
+
+fw = Dataset(tfile)
+ssh = fw.variables['sossheig'][:,jrow,:]
+vot = fw.variables['sosaline'][:,jrow,:]
+if use_sal:
+ sal = fw.variables['vosaline'][:,:,jrow,:]
+ nz = sal.shape[1]
+fw.close()
+
+fw = Dataset(bfile)
+bat = fw.variables['ht_wd'][0,jrow,:]
+if use_sal:
+ mbat = fw.variables['mbathy'][0,jrow,:]
+fw.close()
+
+#print "ssh"
+#print ssh.shape
+#print "bat"
+#print bat.shape 
+#print "vot"
+#print vot.shape 
+nt = ssh.shape[0]
+nx = ssh.shape[1]
+#print nx,nt
+
+bat = -1.*bat
+batmin = np.amin(bat)
+batmax = np.amax(bat)
+brange = batmax - batmin
+tol = 0.1*brange
+#print batmin,batmax,' ho'
+if obc:
+ batrhs = batmin
+else:
+ batrhs = batmax
+
+if nfmax is None:
+  nfmax = nt
+
+nf = 0
+ntmax = np.minimum(nt,nfmax*stride)
+
+if not use_sal:
+#
+# plot solid single colour polygons just showing ssh variation
+#
+  for t in range(0,ntmax,stride):
+   wadfr = froot+"{:0>4d}.png".format(nf)
+   nf = nf + 1
+  
+   tfac = rdt/3600.0
+   t24  = np.int(np.mod(t*tfac,24))
+   dy   = np.int(t*tfac/24.0)
+   mn   = np.int(np.rint((np.mod(t*tfac,24) - t24 )*60))
+   hour  = "t={:0>2d}:{:0>2d}:{:0>2d} ".format(dy,t24,mn)
+   hour2  = "  (days:hrs:mins)"
+   batpts = np.zeros((nx+4,2))
+   sshpts = np.zeros((2*nx,2))
+   votpts = np.zeros((nx,2))
+  
+   for pt in range(nx):
+      batpts[pt+2,0] = pt
+      batpts[pt+2,1] = bat[pt]
+      sshpts[pt,0] = pt
+      sshpts[pt,1] = ssh[t,pt]
+      votpts[pt,0] = pt
+      votpts[pt,1] = np.minimum(36.,vot[t,pt])
+      votpts[pt,1] = np.maximum(30.0,votpts[pt,1])
+      votpts[pt,1] = batmin +0.2*brange + (votpts[pt,1]-30.)*brange/6.0
+  
+   batpts[nx+1,1] = batrhs
+   batpts[nx+2,0] = nx-1
+   batpts[nx+2,1] = batrhs
+   batpts[nx+3,0] = nx-1
+   batpts[nx+3,1] = batmin
+   batpts[0,0] = 0.0
+   batpts[0,1] = batmin
+   batpts[1,0] = 0.0
+   batpts[1,1] = batmax
+   batpts[2,1] = batmax
+   sshpts[nx-1,0] = nx-1
+   sshpts[nx-1,1] = sshpts[nx-2,1]
+   sshpts[0,0] = 0.0
+   votpts[nx-2,0] = nx-1
+   votpts[nx-1,0] = nx-1
+   votpts[0,0] = 0.0
+   votpts[nx-1,1] = batmax + tol
+   votpts[0,1] = batmax + tol
+   sshpts[0,1] = sshpts[1,1]
+   for pt in range(nx):
+      sshpts[pt+nx,0]=batpts[nx+1-pt,0]
+      sshpts[pt+nx,1]=batpts[nx+1-pt,1]
+   
+  
+   xs, ys = zip(*votpts)
+   fig, ax = plt.subplots()
+  
+   patches = []
+   polygon = Polygon(batpts, True)
+   patches.append(polygon)
+   p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
+   p.set_facecolors(['#f1a9a9'])
+  
+   patches = []
+   polygon2 = Polygon(sshpts, True)
+   patches.append(polygon2)
+   p2 = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
+   p2.set_facecolors(['#44a1ff'])
+   
+# Maximum depth set here to -10m
+   ax.set_ylim([-10., 6.0])
+   ax.set_xlim([0., 51.0])
+   ax.add_collection(p2)
+   ax.add_collection(p)
+   ax.plot(xs,ys, '--', color='black', ms=10)
+  
+   plt.annotate(hour,xy=(2,batmin+0.1*brange))
+   plt.annotate(hour2,xy=(2,batmin+0.05*brange))
+   plt.savefig(wadfr)
+
+else:
+#
+# plot each gridcell coloured according to its salinity value
+#
+  for t in range(0,ntmax,stride):
+   wadfr = froot+"{:0>4d}.png".format(nf)
+   nf = nf + 1
+
+   tfac = rdt/3600.0
+   t24  = np.int(np.mod(t*tfac,24))
+   dy   = np.int(t*tfac/24.0)
+   mn   = np.int(np.rint((np.mod(t*tfac,24) - t24 )*60))
+   hour  = "t={:0>2d}:{:0>2d}:{:0>2d} ".format(dy,t24,mn)
+   hour2  = "  (days:hrs:mins)"
+   batpts = np.zeros((nx+4,2))
+   votpts = np.zeros((nx,2))
+   salpts = np.zeros((nx*nz,6,2))
+   salmin = 28.
+   salmax = 37.
+   salrange = salmax - salmin
+   faccol = np.zeros((nx*nz))
+   cl = 0
+   for pt in range(nx):
+      batpts[pt+2,0] = pt
+      batpts[pt+2,1] = bat[pt]
+      votpts[pt,0] = pt
+      votpts[pt,1] = np.minimum(35.,vot[t,pt])
+      votpts[pt,1] = np.maximum(30.0,votpts[pt,1])
+      votpts[pt,1] = batmin +0.2*brange + (votpts[pt,1]-30.)*brange/6.0
+   batpts[nx+1,1] = batmax
+   batpts[nx+2,0] = nx-1
+   batpts[nx+2,1] = batmax
+   batpts[nx+3,0] = nx-1
+   batpts[nx+3,1] = batmin
+   batpts[0,0] = 0.0
+   batpts[0,1] = batmin
+   batpts[1,0] = 0.0
+   batpts[1,1] = batmax
+   batpts[2,1] = batmax
+   votpts[nx-2,0] = nx-1
+   votpts[nx-1,0] = nx-1
+   votpts[0,0] = 0.0
+   votpts[nx-1,1] = batmax + tol
+   votpts[0,1] = batmax + tol
+  
+   cl = 0
+   for pt in range(nx):
+      mz = np.maximum(1,mbat[pt])
+      im1 = np.maximum(pt-1,1)
+      ip1 = np.minimum(pt+1,nx-1)
+      dz  = (ssh[t,pt] - batpts[pt+2,1] )/mz
+      dz1 = 0.5*(ssh[t,pt] + ssh[t,im1] - batpts[pt+2,1] - batpts[im1+2,1] )/mz
+      dz2 = 0.5*(ssh[t,pt] + ssh[t,ip1] - batpts[pt+2,1] - batpts[ip1+2,1] )/mz
+      dz  = np.maximum(dz ,0.0)
+      dz1 = np.maximum(dz1,0.0)
+      dz2 = np.maximum(dz2,0.0)
+      bat1 = 0.5*( batpts[pt+2,1] + batpts[im1+2,1] )
+      bat2 = 0.5*( batpts[pt+2,1] + batpts[ip1+2,1] )
+      ptm = np.maximum(pt-0.5,0.0)
+      ptx = np.minimum(pt+0.5,nx-1)
+      for z in range(mz):
+        if ( sal[t,mz-1-z,pt] > 0.0 ):
+          salpts[cl,0,0] = pt
+          salpts[cl,1,0] = ptm
+          salpts[cl,2,0] = ptm
+          salpts[cl,3,0] = pt
+          salpts[cl,4,0] = ptx
+          salpts[cl,5,0] = ptx
+          salpts[cl,0,1] = batpts[pt+2,1] +dz*z
+          salpts[cl,1,1] = bat1 +dz1*z
+          salpts[cl,2,1] = bat1 +dz1*(z+1)
+          salpts[cl,3,1] = batpts[pt+2,1] +dz*(z+1)
+          salpts[cl,4,1] = bat2 +dz2*(z+1)
+          salpts[cl,5,1] = bat2 +dz2*z
+          faccol[cl] = 100*(sal[t,mz-1-z,pt] - salmin) / salrange
+          faccol[cl] = np.maximum(faccol[cl],0.0)
+          faccol[cl] = np.minimum(faccol[cl],100.0)
+          cl = cl + 1
+   
+  
+   votpts2 = votpts[2:nx-4,:]
+   xs, ys = zip(*votpts2)
+   fig, ax = plt.subplots()
+   patches = []
+  
+   for pt in range(cl-1):
+      polygon = Polygon(salpts[pt,:,:], True)
+      patches.append(polygon)
+  
+   p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
+   
+   p.set_array(faccol)
+   p.set_edgecolor('face')
+  
+   patches = []
+   polygon = Polygon(batpts, True)
+   patches.append(polygon)
+   p2 = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
+   p2.set_facecolors(['#f1a9a9'])
+  
+# Maximum depth set here to -8m (suitable for test case 6 only)
+   ax.set_ylim([-8., 6.0])
+   ax.set_xlim([0., 51.0])
+   ax.add_collection(p)
+   ax.add_collection(p2)
+   ax.plot(xs,ys, '--', color='black', ms=10)
+  
+   plt.annotate(hour,xy=(2,batmin+0.1*brange))
+   plt.annotate(hour2,xy=(2,batmin+0.05*brange))
+   plt.savefig(wadfr)
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad	(revision 14097)
@@ -0,0 +1,15 @@
+!-----------------------------------------------------------------------
+&namwad  !   Wetting and drying
+!-----------------------------------------------------------------------
+   ln_wd_il          = .false   ! T/F activation of iterative limiter for  wetting and drying scheme
+   ln_wd_dl          = .true.   ! T/F activation of directional llimiter for wetting drying scheme
+   ln_wd_dl_bc       = .true.   ! T/F Directional limiteer Baroclinic option
+   ln_wd_dl_rmp      = .true.   ! T/F Turn on directional limiter ramp
+   rn_wdmin0         =  0.30    ! dpoth at which wetting/drying starts
+   rn_wdmin1         =  0.2     ! Minimum wet depth on dried cells
+   rn_wdmin2         =  0.0001  ! Tolerance of min wet depth on dried cells
+   rn_wdld           =  2.5     ! Land elevation below which wetting/drying is allowed
+   nn_wdit           =   20     ! Max iterations for W/D limiter
+   rn_wd_sbcdep      =  5.0     ! Depth at which to taper sbc fluxes
+   rn_wd_sbcfra      =  0.999   ! Fraction of SBC fluxes at taper depth (Must be <1)
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc1
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc1	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc1	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 1
+/
+!-----------------------------------------------------------------------
+&namwad  !   Wetting and drying
+!-----------------------------------------------------------------------
+   rn_wdmin1         =  0.075   ! Minimum wet depth on dried cells
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc2
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc2	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc2	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 2
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc3
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc3	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc3	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 3
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc4
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc4	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc4	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 4
+/
+!-----------------------------------------------------------------------
+&namwad  !   Wetting and drying
+!-----------------------------------------------------------------------
+   rn_wdmin1         =  0.45    ! Minimum wet depth on dried cells
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc5
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc5	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc5	(revision 14097)
@@ -0,0 +1,10 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 5
+/
+!-----------------------------------------------------------------------
+&namwad  !   Wetting and drying
+!-----------------------------------------------------------------------
+   rn_wdmin1         =  0.15    ! Minimum wet depth on dried cells
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc6
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc6	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc6	(revision 14097)
@@ -0,0 +1,5 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 6
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc7
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc7	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_tc7	(revision 14097)
@@ -0,0 +1,21 @@
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   nn_wad_test = 7
+/
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_itend    =      9600  !  last  time step
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries
+!-----------------------------------------------------------------------
+    ln_bdy         = .true.             
+    nb_bdy         = 1                    !  number of open boundary sets
+/
+!-----------------------------------------------------------------------
+&namwad  !   Wetting and drying
+!-----------------------------------------------------------------------
+   rn_wdmin1         =  0.150   ! Minimum wet depth on dried cells
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_usr
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_usr	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Namelists/nam_wad_usr	(revision 14097)
@@ -0,0 +1,8 @@
+!
+!-----------------------------------------------------------------------
+&namusr_def
+!-----------------------------------------------------------------------
+   rn_dx = 1000.0
+   rn_dz = 1.0
+   nn_wad_test = 1
+/
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Preamble.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Preamble.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/Preamble.tex	(revision 14097)
@@ -0,0 +1,175 @@
+\documentclass[a4paper,11pt]{book}
+%\documentclass[a4paper,11pt,makeidx]{book} <== may need this to generate index
+
+%  makeindex NEMO_book  <== to regenerate the index
+%  bibtex    NEMO_book	<== to generate  the bibliography
+
+%\usepackage[french]{babel}
+%\usepackage{color}
+\usepackage{rotating, graphicx}			           % allows insertion of pictures
+%\usepackage{graphics}			                   % allows insertion of pictures
+\graphicspath{{Figures/}}                                  % Set global directory for pictures
+\DeclareGraphicsExtensions{.pdf,.eps}                      % Use .eps for LaTeX2HTML
+%\usepackage{xcolor}                                       % Incompatibility with color -> graphicx
+\usepackage[capbesideposition={top,center}]{floatrow}      % allows captions
+\floatsetup[table]{style=plaintop}                         % beside pictures
+\usepackage[margin=10pt,font={small},                      % Gives small font for captions
+labelsep=colon,labelfont={bf}]{caption}                    %
+\usepackage{enumitem}                                      % allows non-bold description items
+\usepackage{longtable}                                     % allows multipage tables
+%\usepackage{colortbl}                                     % gives coloured panels behind table columns
+
+%hyperref
+\usepackage[pdftitle={NEMO ocean engine},pdfauthor={Gurvan Madec},pdfstartview=FitH,
+bookmarks=true,bookmarksopen=true,breaklinks=true,colorlinks=true,
+linkcolor=blue,anchorcolor=blue,citecolor=blue,filecolor=blue,menucolor=blue,urlcolor=blue]{hyperref}
+% pdfsubject={The preprint document class
+%   elsart},% pdfkeywords={diapycnal diffusion,numerical mixing,z-level models},%%  usage of exteranl hyperlink :  \href{mailto:my_address@wikibooks.org}{my\_address@wikibooks.org}
+%                                                 \url{http://www.wikibooks.org}
+%                                     or         \href{http://www.wikibooks.org}{wikibooks home}
+
+
+%%%% page styles etc................
+\usepackage{fancyhdr}
+\pagestyle{fancy}
+% with this we ensure that the chapter and section
+% headings are in lowercase.
+\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
+\renewcommand{\sectionmark}[1]{\markright{\thesection.\ #1}}
+\fancyhf{}             % delete current setting for header and footer
+\fancyhead[LE,RO]{\bfseries\thepage}
+\fancyhead[LO]{\bfseries\hspace{-0em}\rightmark}
+\fancyhead[RE]{\bfseries\leftmark}
+\renewcommand{\headrulewidth}{0.5pt}
+\renewcommand{\footrulewidth}{0pt  }
+\addtolength{\headheight}{2.6pt}   % make space for the rule
+%\addtolength{\headheight}{1.6pt}   % make space for the rule
+% get rid of headers on plain pages
+\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}}
+
+
+%%%%  Section number in Margin.......
+% typeset the number of each section in the left margin, with the start of each instance of
+% sectional heading text aligned with the left hand edge of  the body text.
+\makeatletter
+\def\@seccntformat#1{\protect\makebox[0pt][r]{\csname the#1\endcsname\quad}}
+\makeatother
+
+% Leave blank pages completely empty, w/o header
+\makeatletter
+\def\cleardoublepage{\clearpage\if@twoside \ifodd\c@page\else
+  \hbox{}
+  \vspace*{\fill}
+  \vspace{\fill}
+  \thispagestyle{empty}
+  \newpage
+  \if@twocolumn\hbox{}\newpage\fi\fi\fi}
+\makeatother
+
+%%%% define the chapter  style ................
+\usepackage{minitoc}				%In French : \usepackage[french]{minitoc}
+%\usepackage{mtcoff}				% invalidate the use of minitocs
+\usepackage{fancybox}
+
+\makeatletter
+\def\LigneVerticale{\vrule height 5cm depth 2cm\hspace{0.1cm}\relax}
+\def\LignesVerticales{%
+  \let\LV\LigneVerticale\LV\LV\LV\LV\LV\LV\LV\LV\LV\LV}
+\def\GrosCarreAvecUnChiffre#1{%
+  \rlap{\vrule height 0.8cm width 1cm depth 0.2cm}%
+ \rlap{\hbox to 1cm{\hss\mbox{\color{white} #1}\hss}}%
+  \vrule height 0pt width 1cm depth 0pt}
+\def\GrosCarreAvecTroisChiffre#1{%
+  \rlap{\vrule height 0.8cm width 1.6cm depth 0.2cm}%
+ \rlap{\hbox to 1.5cm{\hss\mbox{\color{white} #1}\hss}}%
+  \vrule height 0pt width 1cm depth 0pt}
+
+\def\@makechapterhead#1{\hbox{%
+   \huge
+    \LignesVerticales
+    \hspace{-0.5cm}%
+    \GrosCarreAvecUnChiffre{\thechapter}
+    \hspace{0.2cm}\hbox{#1}%
+%    \GrosCarreAvecTroisChiffre{\thechapter}
+%    \hspace{1cm}\hbox{#1}%
+%}\par\vskip 2cm}
+}\par\vskip 1cm}
+\def\@makeschapterhead#1{\hbox{%
+   \huge
+    \LignesVerticales
+    %\hspace{0.5cm}%
+    \hbox{#1}%
+}\par\vskip 2cm}
+\makeatother
+
+%\def\thechapter{\Roman{chapter}}   	% chapter number to be Roman
+
+
+%%%%           Mathematics...............
+%\documentclass{amsart}
+\usepackage{xspace}                              % helpd ensure correct spacing after macros
+\usepackage{latexsym,amssymb,amsmath}
+\allowdisplaybreaks[1]				% allow page breaks in the middle of equations
+\usepackage{TexFiles/Styles/math_abbrev}    % use maths shortcuts
+
+\usepackage{times}			 	 % use times font for text
+%\usepackage{mathtime}                          % font for illustrator to work (belleek fonts )
+%\usepackage[latin1]{inputenc}                % allows some unicode removed (agn)
+
+
+%%% essai commande
+\newcommand{\nl}[1]{\texttt{\small{\textcolor{blue}{#1}}}}
+\newcommand{\nlv}[1]{\texttt{\footnotesize#1}\xspace}
+\newcommand{\smnlv}[1]{\texttt{\scriptsize#1}\xspace}
+
+%%%% namelist & code display................................
+\usepackage{alltt,verbatim}  	%%  alltt & verbatim for namelist
+% namelists
+\newcommand{\namdisplay}[1]{\begin{alltt}{\tiny\verbatiminput{Namelists/#1}}\end{alltt}\vspace{-10pt}}
+\newcommand{\namtools}[1]{\begin{alltt}{\tiny\verbatiminput{Namelists/#1}}\end{alltt}\vspace{-10pt}}
+% code display
+%\newcommand{\codedisplay} [1] {\begin{alltt}{\tiny {\begin{verbatim} {#1}} \end{verbatim}} \end{alltt}      }
+
+
+
+%%%% commands for working with text................................
+% command to "comment out" portions of text ({} argument) or not ({#1} argument)
+\newcommand{\amtcomment}[1]{}   	% command to "commented out" portions of text or not (#1 in argument)
+\newcommand{\sgacomment}[1]{}   	% command to "commented out" portions of
+\newcommand{\gmcomment}[1]{}   	% command to "commented out" portions of
+%                                    				% text that span line breaks
+%Red (NR) or Yellow(WARN)
+%\newcommand{\NR}   {\colorbox{red}   {#1}}
+%\newcommand{\WARN} {\colorbox{yellow}{#1}}
+
+
+
+%%% index commands......................
+\usepackage{makeidx}
+%\usepackage{showidx}				% show the index entry
+
+\newcommand{\mdl}[1]{\textit{#1.F90}\index{Modules!#1}}	%module (mdl)
+\newcommand{\rou}[1]{\textit{#1}\index{Routines!#1}}	%module (routine)
+\newcommand{\hf}[1]{\textit{#1.h90}\index{h90 file!#1}}	%module (h90 files)
+\newcommand{\ngn}[1]{\textit{#1}\index{Namelist Group Name!#1}}	%namelist name (nampar)
+\newcommand{\np}[1]{\textit{#1}\index{Namelist variables!#1}}        %namelist variable
+\newcommand{\jp}[1]{\textit{#1}\index{Model parameters!#1}}	%model parameter (jp)
+\newcommand{\pp}[1]{\textit{#1}\index{Model parameters!#1}} 	%namelist parameter (pp)
+\newcommand{\ifile}[1]{\textit{#1.nc  }\index{Input NetCDF files!#1.nc}}	%input NetCDF files (.nc)
+\newcommand{\key}[1]{\textbf{key\_#1}\index{CPP keys!key\_#1}}	%key_cpp (key)
+\newcommand{\NEMO}{\textit{NEMO}\xspace}	%NEMO (nemo)
+
+%%%%   Bibliography   .............
+\usepackage[nottoc,notlof,notlot]{tocbibind}
+\usepackage[square,comma]{natbib}
+\bibpunct{[}{]}{,}{a}{}{;}                           %suppress "," after "et al."
+\providecommand{\bibfont}{\small}
+
+\usepackage{subfiles}                          % Separate compilation of chapters from whole manual
+%\newcommand{\onlyinsubfile}[1]{#1}             % New commands for printing parts according to
+%\newcommand{\notinsubfile}[1]{}                % the file being compiled
+% Commands to use in the documentfile
+%\renewcommand{\onlyinsubfile}[1]{}                      % Appears only if chapter   .tex file is compiled
+%\renewcommand{\notinsubfile}[1]{#1}                     %    "    ""   "" NEMO_book .tex file is compiled
+
+\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/WAD_doc.tex
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/WAD_doc.tex	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/WAD_doc.tex	(revision 14097)
@@ -0,0 +1,248 @@
+\include{Preamble}
+
+\begin{document}
+
+\title{Draft description of NEMO wetting and drying scheme:     29 November 2017 }
+
+\author{ Enda O'Dea, Hedong Liu, Jason Holt, Andrew Coward  and Michael J. Bell  }
+
+%------------------------------------------------------------------------
+% End of temporary latex header (to be removed) 
+%------------------------------------------------------------------------
+
+% ================================================================
+% Chapter Ocean Dynamics (DYN)
+% ================================================================
+\chapter{Ocean Dynamics (DYN)}
+\label{DYN}
+\minitoc
+
+% add a figure for  dynvor ens, ene latices
+
+$\ $\newline    % force a new ligne
+
+% ================================================================
+% Wetting and drying 
+% ================================================================
+ 
+%----------------------------------------------------------------------------------------
+%      The WAD test cases
+%----------------------------------------------------------------------------------------
+\section   [The WAD test cases (\textit{usrdef\_zgr})]
+			{The WAD test cases (\mdl{usrdef\_zgr})}
+\label{WAD_test_cases}
+
+This section contains details of the seven test cases that can be run as part of the
+WAD\_TEST\_CASES configuration. All the test cases are shallow (less than 10m deep),
+basins or channels with 4m high walls and some of topography that can wet and dry up to
+2.5m above sea-level. The horizontal grid is uniform with a 1km resolution and measures
+52km by 34km. These dimensions are determined by a combination of code in the
+\mdl{usrdef\_nam} module located in the WAD\_TEST\_CASES/MY\_SRC directory and setting
+read in from the namusr\_def namelist. The first six test cases are closed systems with no
+rotation or external forcing and motion is simply initiated by an initial ssh slope. The
+seventh test case introduces and open boundary at the right-hand end of the channel which
+is forced with sinousoidally varying ssh and barotropic velocities.
+
+\namdisplay{nam_wad_usr}
+
+The $\mathrm{nn\_wad\_test}$ parameter can takes values 1 to 7 and it is this parameter
+that determines which of the test cases will be run. Most cases can be run with the
+default settings but the simple linear slope cases (tests 1 and 5) can be run with lower
+values of $\mathrm{rn\_wdmin1}$. Any recommended changes to the default namelist settings
+will be stated in the individual subsections.
+
+Test case 7 requires additional {\tt namelist\_cfg} changes to activate the open boundary
+and lengthen the duration of the run (in order to demonstrate the full forcing cycle).
+There is also a simple python script which needs to be run in order to generate the
+boundary forcing files.  Full details are given in subsection (\ref{WAD_test_case7}).
+
+\clearpage
+\subsection [WAD test case 1 : A simple linear slope]
+                    {WAD test case 1 : A simple linear slope}
+\label{WAD_test_case1}
+
+The first test case is a simple linear slope (in the x-direction, uniform in y) with an
+adverse SSH gradient that, when released, creates a surge up the slope. The parameters are
+chosen such that the surge rises above sea-level before falling back and oscillating
+towards an equilibrium position. This case can be run with $\mathrm{rn\_wdmin1}$ values as
+low as 0.075m. I.e. the following change may be made to the default values in {\tt
+namelist\_cfg} (for this test only):
+
+\namdisplay{nam_wad_tc1}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC1}
+\caption{ \label{Fig_WAD_TC1}
+The evolution of the sea surface height in WAD\_TEST\_CASE 1 from the initial state (t=0)
+over the first three hours of simulation. Note that in this time-frame the resultant surge
+reaches to nearly 2m above sea-level before retreating.}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 2 : A parabolic channel ]
+                    {WAD test case 2 : A parabolic channel}
+\label{WAD_test_case2}
+
+The second and third test cases use a closed channel which is parabolic in x and uniform
+in y.  Test case 2 uses a gentler initial SSH slope which nevertheless demonstrates the
+ability to wet and dry on both sides of the channel. This solution requires values of
+$\mathrm{rn\_wdmin1}$ at least 0.3m ({\it Q.: A function of the maximum topographic
+slope?})
+
+\namdisplay{nam_wad_tc2}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC2}
+\caption{ \label{Fig_WAD_TC2}
+The evolution of the sea surface height in WAD\_TEST\_CASE 2 from the initial state (t=0)
+over the first three hours of simulation. Note that in this time-frame the resultant sloshing
+causes wetting and drying on both sides of the parabolic channel.}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 3 : A parabolic channel (extreme slope) ]
+                    {WAD test case 3 : A parabolic channel (extreme slope)}
+\label{WAD_test_case3}
+
+Similar to test case 2 but with a steeper initial SSH slope. The solution is similar but more vigorous.
+
+\namdisplay{nam_wad_tc3}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC3}
+\caption{ \label{Fig_WAD_TC3}
+The evolution of the sea surface height in WAD\_TEST\_CASE 3 from the initial state (t=0)
+over the first three hours of simulation. Note that in this time-frame the resultant sloshing
+causes wetting and drying on both sides of the parabolic channel.}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 4 : A parabolic bowl ]
+                    {WAD test case 4 : A parabolic bowl}
+\label{WAD_test_case4}
+
+Test case 4 includes variation in the y-direction in the form of a parabolic bowl. The
+initial condition is now a raised bulge centred over the bowl. Figure \ref{Fig_WAD_TC4}
+shows a cross-section of the SSH in the X-direction but features can be seen to propagate
+in all directions and interfere when return paths cross.
+
+\namdisplay{nam_wad_tc4}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC4}
+\caption{ \label{Fig_WAD_TC4}
+The evolution of the sea surface height in WAD\_TEST\_CASE 4 from the initial state (t=0)
+over the first three hours of simulation. Note that this test case is a parabolic bowl with
+variations occurring in the y-direction too (not shown here).}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 5 : A double slope with shelf channel ]
+                    {WAD test case 5 : A double slope with shelf channel}
+\label{WAD_test_case5}
+
+Similar in nature to test case 1 but with a change in slope and a mid-depth shelf.
+
+\namdisplay{nam_wad_tc5}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC5}
+\caption{ \label{Fig_WAD_TC5}
+The evolution of the sea surface height in WAD\_TEST\_CASE 5 from the initial state (t=0)
+over the first three hours of simulation. The surge resulting in this case wets to the full 
+depth permitted (2.5m above sea-level) and is only halted by the 4m high side walls.}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 6 : A parabolic channel with central bar ]
+                    {WAD test case 6 : A parabolic channel with central bar}
+\label{WAD_test_case6}
+
+Test cases 1 to 5 have all used uniform T and S conditions. The dashed line in each plot
+shows the surface salinity along the y=17 line which remains satisfactorily constant. Test
+case 6 introduces variation in salinity by taking a parabolic channel divided by a central
+bar (gaussian) and using two different salinity values in each half of the channel. This
+step change in salinity is initially enforced by the central bar but the bar is
+subsequently over-topped after the initial SSH gradient is released. The time series in
+this case shows the SSH evolution with the water coloured according to local salinity
+values. Encroachment of the high salinity (red) waters into the low salinity (blue) basin
+can clearly be seen.
+
+\namdisplay{nam_wad_tc6}
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{figure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC6}
+\caption{ \label{Fig_WAD_TC6}
+The evolution of the sea surface height in WAD\_TEST\_CASE 6 from the initial state (t=0)
+over the first three hours of simulation. Water is coloured according to local salinity
+values. Encroachment of the high salinity (red) waters into the low salinity (blue) basin
+can clearly be seen although the largest influx occurs early in the sequence between the
+frames shown.}
+\end{center}\end{figure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+\clearpage
+\subsection [WAD test case 7 : A double slope with shelf, open-ended channel ]
+                    {WAD test case 7 : A double slope with shelf, open-ended channel}
+\label{WAD_test_case7}
+
+Similar in nature to test case 5 but with an open boundary forced with a sinusoidally
+varying ssh. This test case has been introduced to emulate a typical coastal application
+with a tidally forced open boundary. The bathymetry and setup is identical to test case 5
+except the right hand end of the channel is now open and has simple ssh and barotropic
+velocity boundary conditions applied at the open boundary. Several additional steps and
+namelist changes are required to run this test.
+
+\namdisplay{nam_wad_tc7}
+
+In addition, the boundary condition files must be generated using the python script
+provided.
+
+\begin{verbatim}
+python ./makebdy_tc7.py
+\end{verbatim}
+
+will create the following boundary files for this test (assuming a suitably configured
+python environment: python2.7 with netCDF4 and numpy):
+
+\begin{verbatim}
+  bdyssh_tc7_m12d30.nc   bdyuv_tc7_m12d30.nc
+  bdyssh_tc7_m01d01.nc   bdyuv_tc7_m01d01.nc
+  bdyssh_tc7_m01d02.nc   bdyuv_tc7_m01d02.nc
+  bdyssh_tc7_m01d03.nc   bdyuv_tc7_m01d03.nc
+\end{verbatim}
+
+These are sufficient for up to a three day simulation; the script is easily adapted if
+longer periods are required.
+
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+\begin{sidewaysfigure}[htb] \begin{center}
+\includegraphics[width=0.8\textwidth]{Fig_WAD_TC7}
+\caption{ \label{Fig_WAD_TC7}
+The evolution of the sea surface height in WAD\_TEST\_CASE 7 from the initial state (t=0)
+over the first 24 hours of simulation. After the initial surge the solution settles into a
+simulated tidal cycle with an amplitude of 5m. This is enough to repeatedly wet and dry
+both shelves.}
+
+\end{center}\end{sidewaysfigure}
+%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+
+% ================================================================
+
+%\bibliographystyle{wileyqj}
+%\bibliographystyle{../../../doc/latex/NEMO/main/ametsoc.bst}
+%\bibliography{references}
+
+\end{document}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/references.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/references.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_DOCS/references.bib	(revision 14097)
@@ -0,0 +1,36 @@
+@article{Oey05,
+	author = {L-Y Oey},
+	title = {{A wetting and drying scheme for POM}},
+	journal = {Ocean Mod.},
+	year = {2005},
+	volume = {9},
+	pages = {133--150}}
+
+@article{Oey06,
+   title = "An OGCM with movable land-sea boundaries",
+   journal = "Ocean Modelling",
+   volume = "13",
+   number = "2",
+   pages = "176 - 195",
+   year = "2006",
+   issn = "1463-5003",
+   doi = "https://doi.org/10.1016/j.ocemod.2006.01.001",
+   url = "http://www.sciencedirect.com/science/article/pii/S1463500306000084",
+   author = "Lie-Yauw Oey",
+   keywords = "Wetting and drying, Inundations, Ocean general circulation model (OGCM), Princeton Ocean Model (POM), Tides, Tsunamis, Estuarine outflows",
+   abstract = "An ocean general circulation model (OGCM) with wetting and drying (WAD) capabilities removes the vertical-wall coastal assumption and allows simultaneous modeling of open-ocean currents and water run-up (and run-down) across movable land-sea boundaries. This paper implements and tests such a WAD scheme for the Princeton Ocean Model (POM) in its most general three-dimensional setting with stratification, bathymetry and forcing. The scheme can be easily exported to other OGCM's."
+}
+
+@article{WarnerEtal13,
+   title = "A wetting and drying scheme for ROMS",
+   journal = "Computers \& Geosciences",
+   volume = "58",
+   pages = "54 - 61",
+   year = "2013",
+   issn = "0098-3004",
+   doi = "https://doi.org/10.1016/j.cageo.2013.05.004",
+   url = "http://www.sciencedirect.com/science/article/pii/S0098300413001362",
+   author = "John C. Warner and Zafer Defne and Kevin Haas and Hernan G. Arango",
+   keywords = "Wetting and drying, ROMS, Cell-face blocking",
+   abstract = "The processes of wetting and drying have many important physical and biological impacts on shallow water systems. Inundation and dewatering effects on coastal mud flats and beaches occur on various time scales ranging from storm surge, periodic rise and fall of the tide, to infragravity wave motions. To correctly simulate these physical processes with a numerical model requires the capability of the computational cells to become inundated and dewatered. In this paper, we describe a method for wetting and drying based on an approach consistent with a cell-face blocking algorithm. The method allows water to always flow into any cell, but prevents outflow from a cell when the total depth in that cell is less than a user defined critical value. We describe the method, the implementation into the three-dimensional Regional Oceanographic Modeling System (ROMS), and exhibit the new capability under three scenarios: an analytical expression for shallow water flows, a dam break test case, and a realistic application to part of a wetland area along the Georgia Coast, USA."
+}
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_hgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_hgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_hgr.F90	(revision 14097)
@@ -0,0 +1,109 @@
+MODULE usrdef_hgr
+   !!======================================================================
+   !!                       ***  MODULE usrdef_hgr   ***
+   !!
+   !!                  ===  WAD_TEST_CASES configuration  ===
+   !!
+   !! User defined :   mesh and Coriolis parameter of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_hgr    : initialize the horizontal mesh for WAD_TEST_CASES configuration
+   !!----------------------------------------------------------------------
+   USE dom_oce  ,  ONLY: nimpp, njmpp       ! ocean space and time domain
+   USE par_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE usrdef_nam, ONLY: rn_dx   ! horizontal resolution in meters
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_hgr   ! called by domhgr.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_hgr( plamt , plamu , plamv  , plamf  ,   &   ! geographic position (required)
+      &                    pphit , pphiu , pphiv  , pphif  ,   &   !
+      &                    kff   , pff_f , pff_t  ,            &   ! Coriolis parameter  (if domain not on the sphere)
+      &                    pe1t  , pe1u  , pe1v   , pe1f   ,   &   ! scale factors       (required)
+      &                    pe2t  , pe2u  , pe2v   , pe2f   ,   &   !
+      &                    ke1e2u_v      , pe1e2u , pe1e2v     )   ! u- & v-surfaces (if gridsize reduction is used in strait(s))
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE usr_def_hgr  ***
+      !!
+      !! ** Purpose :   user defined mesh and Coriolis parameter
+      !!
+      !! ** Method  :   set all intent(out) argument to a proper value
+      !!                WAD_TEST_CASES configuration : uniform grid spacing (rn_dx)
+      !!                without Coriolis force (f=0)
+      !!
+      !! ** Action  : - define longitude & latitude of t-, u-, v- and f-points (in degrees) 
+      !!              - define coriolis parameter at f-point if the domain in not on the sphere (on beta-plane)
+      !!              - define i- & j-scale factors at t-, u-, v- and f-points (in meters)
+      !!              - define u- & v-surfaces (if gridsize reduction is used in some straits) (in m2)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   plamt, plamu, plamv, plamf   ! longitude outputs                     [degrees]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pphit, pphiu, pphiv, pphif   ! latitude outputs                      [degrees]
+      INTEGER                 , INTENT(out) ::   kff                          ! =1 Coriolis parameter computed here, =0 otherwise
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pff_f, pff_t                 ! Coriolis factor at f-point                [1/s]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1t, pe1u, pe1v, pe1f       ! i-scale factors                             [m]
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe2t, pe2u, pe2v, pe2f       ! j-scale factors                             [m]
+      INTEGER                 , INTENT(out) ::   ke1e2u_v                     ! =1 u- & v-surfaces computed here, =0 otherwise 
+      REAL(wp), DIMENSION(:,:), INTENT(out) ::   pe1e2u, pe1e2v               ! u- & v-surfaces (if reduction in strait)   [m2]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zfact      ! local scalars
+      !!-------------------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_hgr : WAD_TEST_CASES configuration basin'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~   uniform grid spacing WITHOUT Coriolis force (f=0)'
+      !
+      !                       !==  grid point position  ==!   (in kilometers)
+      zfact = rn_dx * 1.e-3         ! conversion in km
+      DO jj = 1, jpj
+         DO ji = 1, jpi             ! longitude
+            plamt(ji,jj) = zfact * (  - 0.5 + REAL( ji-1 + nimpp-1 , wp )  )  
+            plamu(ji,jj) = zfact * (          REAL( ji-1 + nimpp-1 , wp )  )
+            plamv(ji,jj) = plamt(ji,jj)
+            plamf(ji,jj) = plamu(ji,jj)
+            !                       ! latitude
+            pphit(ji,jj) = zfact * (  - 0.5 + REAL( jj-1 + njmpp-1 , wp )  )
+            pphiu(ji,jj) = pphit(ji,jj)
+            pphiv(ji,jj) = zfact * (          REAL( jj-1 + njmpp-1 , wp )  )
+            pphif(ji,jj) = pphiv(ji,jj)
+         END DO
+      END DO
+      !
+      !                       !==  Horizontal scale factors  ==!   (in meters) 
+      pe1t(:,:) = rn_dx   ;   pe2t(:,:) = rn_dx
+      pe1u(:,:) = rn_dx   ;   pe2u(:,:) = rn_dx
+      pe1v(:,:) = rn_dx   ;   pe2v(:,:) = rn_dx
+      pe1f(:,:) = rn_dx   ;   pe2f(:,:) = rn_dx
+      !
+      !                             ! NO reduction of grid size in some straits 
+      ke1e2u_v = 0                  !    ==>> u_ & v_surfaces will be computed in dom_ghr routine
+      pe1e2u(:,:) = 0._wp           !    CAUTION: set to zero to avoid error with some compilers that
+      pe1e2v(:,:) = 0._wp           !             require an initialization of INTENT(out) arguments
+      !
+      !
+      !                       !==  Coriolis parameter  ==!
+      kff = 1                       !  indicate not to compute Coriolis parameter afterward
+      !
+      pff_f(:,:) = 0._wp            ! here No earth rotation: f=0
+      pff_t(:,:) = 0._wp
+      !
+   END SUBROUTINE usr_def_hgr
+
+   !!======================================================================
+END MODULE usrdef_hgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_istate.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_istate.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_istate.F90	(revision 14097)
@@ -0,0 +1,187 @@
+MODULE usrdef_istate
+   !!======================================================================
+   !!                     ***  MODULE usrdef_istate   ***
+   !!
+   !!                  ===  WAD_TEST_CASES configuration  ===
+   !!
+   !! User defined : set the initial state of a user configuration
+   !!======================================================================
+   !! History :  4.0 ! 2016-03  (S. Flavoni) Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!  usr_def_istate : initial state in Temperature and salinity
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean space and time domain
+   USE dom_oce , ONLY : mi0, mig, mjg, glamt, gphit, ht_0
+   USE phycst         ! physical constants
+   USE wet_dry        ! Wetting and drying
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_istate   ! called in istate.F90
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE usr_def_istate( pdept, ptmask, pts, pu, pv, pssh )
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE usr_def_istate  ***
+      !! 
+      !! ** Purpose :   Initialization of the dynamics and tracers
+      !!                Here WAD_TEST_CASES configuration 
+      !!
+      !! ** Method  : - set temprature field
+      !!              - set salinity   field
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   pdept   ! depth of t-point               [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(in   ) ::   ptmask  ! t-point ocean mask             [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pts     ! T & S fields      [Celsius ; g/kg]
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pu      ! i-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pv      ! j-component of the velocity  [m/s] 
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(  out) ::   pssh    ! sea-surface height
+      INTEGER  ::   ji, jj            ! dummy loop indices
+      REAL(wp) ::   zi, zj
+      !
+      INTEGER  ::   jk     ! dummy loop indices
+      REAL(wp) ::   zdam   ! location of dam [Km]
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD_TEST_CASES configuration, analytical definition of initial state'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~   Ocean at rest, with a constant temperature                    '
+      IF(lwp) WRITE(numout,*) '                 and  constant salinity (not used as rho=F(T) '
+      !
+      !
+      pu  (:,:,:) = 0._wp        ! ocean at rest
+      pv  (:,:,:) = 0._wp
+      pssh(:,:)   = 0._wp
+      !
+      !                          ! T & S profiles
+      pts(:,:,:,jp_tem) = 10._wp * ptmask(:,:,:)
+      !
+      pts(:,:,:,jp_sal) = 35._wp * ptmask(:,:,:)
+      !!----------------------------------------------------------------------
+      !
+      !!----------------------------------------------------------------------
+      !
+      ! Uniform T & S in most test cases
+      pts(:,:,:,jp_tem) = 10._wp
+      pts(:,:,:,jp_sal) = 35._wp
+      SELECT CASE ( nn_cfg ) 
+         !                                        ! ====================
+         CASE ( 1 )                               ! WAD 1 configuration
+            !                                     ! ====================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Closed box with EW linear bottom slope'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            do ji = 1,jpi
+             pssh(ji,:) = ( -5.5_wp + 7.4_wp*glamt(ji,1)/50._wp)*ptmask(ji,:,1)
+            end do
+            !                                     ! ====================
+         CASE ( 2, 8 )                            ! WAD 2 configuration
+            !                                     ! ====================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Parobolic EW channel, mid-range initial ssh slope'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            do ji = 1,jpi
+             pssh(ji,:) = ( -1.5_wp + 5.0_wp*glamt(ji,1)/50._wp)*ptmask(ji,:,1)
+            end do
+            !                                     ! ====================
+         CASE ( 3 )                               ! WAD 3 configuration
+            !                                     ! ====================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Parobolic EW channel, extreme initial ssh slope' 
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            do ji = 1,jpi
+             pssh(ji,:) = ( -4.5_wp + 6.8_wp*glamt(ji,1)/50._wp)*ptmask(ji,:,1)
+            end do
+
+            !
+            !                                     ! ====================
+         CASE ( 4 )                               ! WAD 4 configuration
+            !                                     ! ====================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Parobolic bowl, mid-range initial ssh slope' 
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            DO ji = 1, jpi
+               zi = MAX(1.0-((glamt(ji,1)-25._wp)**2)/400.0, 0.0 )
+               DO jj = 1, jpj
+                  zj = MAX(1.0-((gphit(1,jj)-17._wp)**2)/144.0, 0.0 )
+                  pssh(ji,jj) = -2.5_wp + 5.4_wp*zi*zj
+               END DO
+            END DO
+
+            !
+            !                                    ! ===========================
+         CASE ( 5, 7 )                           ! WAD 5 and 7 configurations
+            !                                    ! ===========================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Double slope with shelf'
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            do ji = 1,jpi
+             pssh(ji,:) = ( -2.5_wp + 5.5_wp*glamt(ji,1)/50._wp)*ptmask(ji,:,1)
+            end do
+
+            !
+            !                                     ! ====================
+         CASE ( 6 )                               ! WAD 6 configuration
+            !                                     ! ====================
+            !
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'usr_def_istate : WAD Parobolic EW channel with gaussian ridge' 
+            IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+            !
+            do ji = 1,jpi
+             pssh(ji,:) = ( -2.5_wp + 5.5_wp*(50._wp-glamt(ji,1))/50._wp)*ptmask(ji,:,1)
+            end do
+            !
+            do ji = mi0(jpiglo/2), mi0(jpiglo)
+             pts(ji,:,:,jp_sal) = 30._wp
+             pssh(ji,:) = -0.1*ptmask(ji,:,1)
+            end do
+            !
+            !
+            !                                    ! ===========================
+         CASE DEFAULT                            ! NONE existing configuration
+            !                                    ! ===========================
+            WRITE(ctmp1,*) 'WAD test with a ', nn_cfg,' option is not coded'
+            !
+            CALL ctl_stop( ctmp1 )
+            !
+      END SELECT
+
+
+      !
+      ! Apply minimum wetdepth criterion
+      !
+      do jj = 1,jpj
+         do ji = 1,jpi
+            IF( ht_0(ji,jj) + pssh(ji,jj) < rn_wdmin1 ) THEN
+               pssh(ji,jj) = ptmask(ji,jj,1)*( rn_wdmin1 - ht_0(ji,jj) )
+            ENDIF
+         end do
+      end do
+      !
+   END SUBROUTINE usr_def_istate
+
+   !!======================================================================
+END MODULE usrdef_istate
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_nam.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_nam.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_nam.F90	(revision 14097)
@@ -0,0 +1,102 @@
+MODULE usrdef_nam
+   !!======================================================================
+   !!                       ***  MODULE usrdef_nam  ***
+   !!
+   !!                  ===  WAD_TEST_CASES configuration  ===
+   !!
+   !! User defined : set the domain characteristics of a user configuration
+   !!======================================================================
+   !! History :  4.0  ! 2016-03  (S. Flavoni, G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_nam   : read user defined namelist and set global domain size
+   !!   usr_def_hgr   : initialize the horizontal mesh 
+   !!----------------------------------------------------------------------
+   USE dom_oce  , ONLY: nimpp , njmpp            ! i- & j-indices of the local domain
+   USE par_oce        ! ocean space and time domain
+   USE phycst         ! physical constants
+   !
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+   USE timing         ! Timing
+   
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_nam   ! called by nemogcm.F90
+
+   !                              !!* namusr_def namelist *!!
+   REAL(wp), PUBLIC ::   rn_dx     ! resolution in meters defining the horizontal domain size
+   REAL(wp), PUBLIC ::   rn_dz     ! resolution in meters defining the vertical   domain size
+   INTEGER , PUBLIC :: nn_wad_test ! resolution in meters defining the vertical   domain size
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usr_def_nam( cd_cfg, kk_cfg, kpi, kpj, kpk, kperio )
+      !!----------------------------------------------------------------------
+      !!                     ***  ROUTINE dom_nam  ***
+      !!                    
+      !! ** Purpose :   read user defined namelist and define the domain size
+      !!
+      !! ** Method  :   read in namusr_def containing all the user specific namelist parameter
+      !!
+      !!                Here WAD_TEST_CASES configuration
+      !!
+      !! ** input   : - namusr_def namelist found in namelist_cfg
+      !!----------------------------------------------------------------------
+      CHARACTER(len=*)              , INTENT(out) ::   cd_cfg          ! configuration name
+      INTEGER                       , INTENT(out) ::   kk_cfg          ! configuration resolution
+      INTEGER                       , INTENT(out) ::   kpi, kpj, kpk   ! global domain sizes 
+      INTEGER                       , INTENT(out) ::   kperio          ! lateral global domain b.c. 
+      !
+      INTEGER ::   ios   ! Local integer
+      !!
+      NAMELIST/namusr_def/ rn_dx, rn_dz, nn_wad_test
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_cfg )          ! Namelist namusr_def (exist in namelist_cfg only)
+      READ  ( numnam_cfg, namusr_def, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 )   CALL ctl_nam ( ios , 'namusr_def in configuration namelist' )
+      !
+      IF(lwm)   WRITE( numond, namusr_def )
+      !
+      !
+      cd_cfg = 'wad'      ! name & resolution (not used)
+      nn_cfg = nn_wad_test
+      kk_cfg = nn_wad_test
+      !
+      ! Global Domain size:  WAD_TEST_CASES domain is 52 km x 34 km x 10 m
+      kpi = INT(  50.e3 / rn_dx ) + 2
+      kpj = INT(  32.e3 / rn_dx ) + 2
+      kpk = INT(  10.  / rn_dz ) + 1
+      !                             ! Set the lateral boundary condition of the global domain
+      kperio = 0                    ! WAD_TEST_CASES configuration : closed domain
+      IF( nn_wad_test == 8 ) kperio = 7 ! North-South cyclic test
+      !
+      !                             ! control print
+      IF(lwp) THEN
+         WRITE(numout,*) '   '
+         WRITE(numout,*) 'usr_def_nam  : read the user defined namelist (namusr_def) in namelist_cfg'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '   Namelist namusr_def : WAD_TEST_CASES test case'
+         WRITE(numout,*) '      horizontal resolution                    rn_dx  = ', rn_dx, ' meters'
+         WRITE(numout,*) '      vertical   resolution                    rn_dz  = ', rn_dz, ' meters'
+         WRITE(numout,*) '      WAD_TEST_CASES domain = 52 km  x  34 km x 10 m'
+         WRITE(numout,*) '         resulting global domain size :        jpiglo = ', kpi
+         WRITE(numout,*) '                                               jpjglo = ', kpj
+         WRITE(numout,*) '                                               jpkglo = ', kpk
+         WRITE(numout,*) '   '
+         WRITE(numout,*) '   Lateral boundary condition of the global domain'
+         WRITE(numout,*) '      closed                                   jperio = ', kperio
+      ENDIF
+      !
+   END SUBROUTINE usr_def_nam
+
+   !!======================================================================
+END MODULE usrdef_nam
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_sbc.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_sbc.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_sbc.F90	(revision 14097)
@@ -0,0 +1,87 @@
+MODULE usrdef_sbc
+   !!======================================================================
+   !!                       ***  MODULE usrdef_sbc  ***
+   !! 
+   !!                  ===  WAD_TEST_CASES configuration  ===
+   !!
+   !! User defined :   surface forcing of a user configuration
+   !!======================================================================
+   !! History :  4.0   ! 2016-03  (S. Flavoni, G. Madec)  user defined interface
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usrdef_sbc     : user defined surface bounday conditions in WAD_TEST_CASES case
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE sbc_oce         ! Surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: ice fields
+   USE phycst          ! physical constants
+   !
+   USE in_out_manager  ! I/O manager
+   USE lib_mpp         ! distribued memory computing library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined) 
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usrdef_sbc_oce      ! routine called in sbcmod module
+   PUBLIC   usrdef_sbc_ice_tau  ! routine called by icestp.F90 for ice dynamics
+   PUBLIC   usrdef_sbc_ice_flx  ! routine called by icestp.F90 for ice thermo
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE usrdef_sbc_oce( kt )
+      !!---------------------------------------------------------------------
+      !!                    ***  ROUTINE usr_def_sbc  ***
+      !!              
+      !! ** Purpose :   provide at each time-step the surface boundary
+      !!              condition, i.e. the momentum, heat and freshwater fluxes.
+      !!
+      !! ** Method  :   all 0 fields, for WAD_TEST_CASES case
+      !!                CAUTION : never mask the surface stress field !
+      !!
+      !! ** Action  : - set to ZERO all the ocean surface boundary condition, i.e.   
+      !!                   utau, vtau, taum, wndm, qns, qsr, emp, sfx
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+      !!---------------------------------------------------------------------
+      !
+      IF( kt == nit000 ) THEN
+         !
+         IF(lwp) WRITE(numout,*)' usr_sbc : WAD_TEST_CASES case: NO surface forcing'
+         IF(lwp) WRITE(numout,*)' ~~~~~~~~~~~   utau = vtau = taum = wndm = qns = qsr = emp = sfx = 0'
+         !
+         utau(:,:) = 0._wp
+         vtau(:,:) = 0._wp
+         taum(:,:) = 0._wp
+         wndm(:,:) = 0._wp
+         !
+         emp (:,:) = 0._wp
+         sfx (:,:) = 0._wp
+         qns (:,:) = 0._wp
+         qsr (:,:) = 0._wp
+         !         
+      ENDIF
+      !
+   END SUBROUTINE usrdef_sbc_oce
+
+   SUBROUTINE usrdef_sbc_ice_tau( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_tau
+
+   SUBROUTINE usrdef_sbc_ice_flx( kt )
+      INTEGER, INTENT(in) ::   kt   ! ocean time step
+   END SUBROUTINE usrdef_sbc_ice_flx
+
+   !!======================================================================
+END MODULE usrdef_sbc
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_zgr.F90
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_zgr.F90	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/MY_SRC/usrdef_zgr.F90	(revision 14097)
@@ -0,0 +1,390 @@
+MODULE usrdef_zgr
+   !!======================================================================
+   !!                   ***  MODULE  usrdef_zgr  ***
+   !!
+   !!                   ===  WAD_TEST_CASES case  ===
+   !!
+   !! Ocean domain : user defined vertical coordinate system 
+   !!======================================================================
+   !! History :  4.0  ! 2016-06  (G. Madec)  Original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   usr_def_zgr   : user defined vertical coordinate system (required)
+   !!       zgr_z     : reference 1D z-coordinate 
+   !!---------------------------------------------------------------------
+   USE oce            ! ocean variables
+   USE dom_oce ,  ONLY: ht_0, mi0, mi1, nimpp, njmpp,  &
+                      & mj0, mj1, glamt, gphit         ! ocean space and time domain
+   USE usrdef_nam     ! User defined : namelist variables
+   USE wet_dry ,  ONLY: rn_wdmin1, rn_wdmin2, rn_wdld  ! Wetting and drying
+   !
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp        ! distributed memory computing library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   usr_def_zgr        ! called by domzgr.F90
+
+   !! * Substitutions
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OCE 4.0 , NEMO Consortium (2018)
+   !! $Id$
+   !! Software governed by the CeCILL license (see ./LICENSE)
+   !!----------------------------------------------------------------------
+CONTAINS             
+
+   SUBROUTINE usr_def_zgr( ld_zco  , ld_zps  , ld_sco  , ld_isfcav,    &   ! type of vertical coordinate
+      &                    pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d  ,    &   ! 1D reference vertical coordinate
+      &                    pdept , pdepw ,                             &   ! 3D t & w-points depth
+      &                    pe3t  , pe3u  , pe3v   , pe3f ,             &   ! vertical scale factors
+      &                    pe3w  , pe3uw , pe3vw         ,             &   !     -      -      -
+      &                    k_top  , k_bot    )                             ! top & bottom ocean level
+      !!---------------------------------------------------------------------
+      !!              ***  ROUTINE usr_def_zgr  ***
+      !!
+      !! ** Purpose :   User defined the vertical coordinates
+      !!
+      !!----------------------------------------------------------------------
+      LOGICAL                   , INTENT(out) ::   ld_zco, ld_zps, ld_sco      ! vertical coordinate flags
+      LOGICAL                   , INTENT(out) ::   ld_isfcav                   ! under iceshelf cavity flag
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pdept_1d, pdepw_1d          ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:)    , INTENT(out) ::   pe3t_1d , pe3w_1d           ! 1D grid-point depth     [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pdept, pdepw                ! grid-point depth        [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3t , pe3u , pe3v , pe3f   ! vertical scale factors  [m]
+      REAL(wp), DIMENSION(:,:,:), INTENT(out) ::   pe3w , pe3uw, pe3vw         ! i-scale factors 
+      INTEGER , DIMENSION(:,:)  , INTENT(out) ::   k_top, k_bot                ! first & last ocean level
+      !
+      INTEGER  ::   ji, jj, jk        ! dummy indices
+      INTEGER  ::   ik                ! local integers
+      REAL(wp) ::   zfact, z1_jpkm1   ! local scalar
+      REAL(wp) ::   ze3min            ! local scalar
+      REAL(wp) ::   zi, zj, zbathy    ! local scalar
+      REAL(wp) ::   ztmpu, ztmpv, ztmpf, ztmpu1, ztmpv1, ztmpf1, zwet
+      REAL(wp), DIMENSION(jpi,jpj) ::   zht, zhu, zhv, z2d   ! 2D workspace
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) 'usr_def_zgr : WAD_TEST_CASES configuration (s-coordinate closed box ocean without cavities)'
+      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      !
+      !
+      ! type of vertical coordinate ==>>>   here WAD_TEST_CASES : s-coordinate always
+      ! ---------------------------
+      ld_zco    = .FALSE.      ! z-partial-step coordinate
+      ld_zps    = .FALSE.      ! z-partial-step coordinate
+      ld_sco    = .TRUE.       ! s-coordinate
+      ld_isfcav = .FALSE.      ! ISF Ice Shelves Flag
+      !
+      !
+      ! Build the vertical coordinate system
+      ! ------------------------------------
+      !
+      !                       !==  UNmasked meter bathymetry  ==!
+      !
+!
+      zbathy=10.0
+      IF( cn_cfg == 'wad' ) THEN
+         SELECT CASE ( nn_cfg )
+            !                                        ! ====================
+            CASE ( 1 )                               ! WAD 1 configuration
+               !                                     ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Closed box with EW linear bottom slope'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               zht = 1.5_wp
+               DO ji = 1, jpi
+                 zi = MIN((glamt(ji,1) - 10.0)/40.0, 1.0 )
+                 zht(ji,:) = MAX(zbathy*zi, -2.0) 
+               END DO
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(mi0(jpiglo):mi1(jpiglo),:) = -4._wp
+               zht(:,mj0(1):mj1(1)) = -4._wp
+               zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+               !                                     ! ====================
+            CASE ( 2, 3, 8 )                         ! WAD 2 or 3  configuration
+               !                                     ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Parobolic EW channel'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               DO ji = 1, jpi
+                 zi = MAX(1.0-((glamt(ji,1)-25.0)**2)/484.0, -0.3 )
+                 zht(ji,:) = MAX(zbathy*zi, -2.0)
+               END DO
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(mi0(jpiglo):mi1(jpiglo),:) = -4._wp
+               IF( nn_cfg /= 8 ) THEN
+                  zht(:,mj0(1):mj1(1)) = -4._wp
+                  zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+               ENDIF
+               !                                     ! ====================
+            CASE ( 4 )                               ! WAD 4 configuration
+               !                                     ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Parobolic bowl'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               DO ji = 1, jpi
+                 zi = MAX(1.0-((glamt(ji,1)-25.0)**2)/484.0, -2.0 )
+               DO jj = 1, jpj
+                 zj = MAX(1.0-((gphit(1,jj)-17.0)**2)/196.0, -2.0 )
+                 zht(ji,jj) = MAX(zbathy*zi*zj, -2.0)
+               END DO
+               END DO
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(mi0(jpiglo):mi1(jpiglo),:) = -4._wp
+               zht(:,mj0(1):mj1(1)) = -4._wp
+               zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+               !                                    ! ===========================
+            CASE ( 5 )                              ! WAD 5 configuration
+               !                                    ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Double slope with shelf'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               DO ji = 1, jpi
+                 zi = MIN(glamt(ji,1)/45.0, 1.0 )
+                 zht(ji,:) = MAX(zbathy*zi, -2.0)
+                 IF( glamt(ji,1) >= 46.0 ) THEN
+                   zht(ji,:) = 10.0
+                 ELSE IF( glamt(ji,1) >= 20.0 .AND. glamt(ji,1) < 46.0 ) THEN
+                   zi = 7.5/25.
+                   zht(ji,:) = MAX(10. - zi*(47.-glamt(ji,1)),2.5)
+                 ELSE IF( glamt(ji,1) >= 15.0 .AND. glamt(ji,1) < 20.0 ) THEN
+                   zht(ji,:) = 2.5
+                 ELSE IF( glamt(ji,1) >= 4.0 .AND. glamt(ji,1) < 15.0 ) THEN
+                   zi = 4.5/11.0
+                   zht(ji,:) = MAX(2.5 - zi*(16.0-glamt(ji,1)), -2.0)
+                 ELSE IF( glamt(ji,1) >= 0.0 .AND. glamt(ji,1) < 4.0 ) THEN
+                   zht(ji,:) = -2.0
+                 ENDIF
+               END DO
+               !                                    ! ===========================
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(mi0(jpiglo):mi1(jpiglo),:) = -4._wp
+               zht(:,mj0(1):mj1(1)) = -4._wp
+               zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+               !                                    ! ===========================
+            CASE ( 6 )                              ! WAD 6 configuration
+               !                                    ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Parabolic channel with gaussian ridge'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               DO ji = 1, jpi
+                 zi = MAX(1.0-((glamt(ji,1)-25.0)**2)/484.0, -2.0 )
+                 zj = 1.075*MAX(EXP(-1.0*((glamt(ji,1)-25.0)**2)/32.0) , 0.0 )
+                 zht(ji,:) = MAX(zbathy*(zi-zj), -2.0)
+               END DO
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(mi0(jpiglo):mi1(jpiglo),:) = -4._wp
+               zht(:,mj0(1):mj1(1)) = -4._wp
+               zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+               !                                    ! ===========================
+            CASE ( 7 )                              ! WAD 7 configuration
+               !                                    ! ====================
+               !
+               IF(lwp) WRITE(numout,*)
+               IF(lwp) WRITE(numout,*) 'usr_def_zgr (WAD) : Double slope with open boundary'
+               IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
+               !
+               DO ji = 1, jpi
+                 zi = MIN(glamt(ji,1)/45.0, 1.0 )
+                 zht(ji,:) = MAX(zbathy*zi, -2.0)
+                 IF( glamt(ji,1) >= 46.0 ) THEN
+                   zht(ji,:) = 10.0
+                 ELSE IF( glamt(ji,1) >= 20.0 .AND. glamt(ji,1) < 46.0 ) THEN
+                   zi = 7.5/25.
+                   zht(ji,:) = MAX(10. - zi*(47.-glamt(ji,1)),2.5)
+                 ELSE IF( glamt(ji,1) >= 15.0 .AND. glamt(ji,1) < 20.0 ) THEN
+                   zht(ji,:) = 2.5
+                 ELSE IF( glamt(ji,1) >= 4.0 .AND. glamt(ji,1) < 15.0 ) THEN
+                   zi = 4.5/11.0
+                   zht(ji,:) = MAX(2.5 - zi*(16.0-glamt(ji,1)), -2.0)
+                 ELSE IF( glamt(ji,1) >= 0.0 .AND. glamt(ji,1) < 4.0 ) THEN
+                   zht(ji,:) = -2.0
+                 ENDIF
+               END DO
+               !                                    ! ===========================
+               zht(mi0(1):mi1(1),:) = -4._wp
+               zht(:,mj0(1):mj1(1)) = -4._wp
+               zht(:,mj0(jpjglo):mj1(jpjglo)) = -4._wp
+            CASE DEFAULT
+               !                                    ! ===========================
+               WRITE(ctmp1,*) 'WAD test with a ', nn_cfg,' option is not coded'
+               !
+               CALL ctl_stop( ctmp1 )
+               !
+         END SELECT
+      END IF
+              
+
+      ! at u-point: averaging zht
+      DO ji = 1, jpim1
+         zhu(ji,:) = 0.5_wp * ( zht(ji,:) + zht(ji+1,:) )
+      END DO
+      CALL lbc_lnk( 'usrdef_zgr', zhu, 'U', 1. )     ! boundary condition: this mask the surrounding grid-points
+      !                                ! ==>>>  set by hand non-zero value on first/last columns & rows 
+      DO ji = mi0(1), mi1(1)              ! first row of global domain only
+         zhu(ji,:) = zht(1,:)
+      END DO
+       DO ji = mi0(jpiglo), mi1(jpiglo)   ! last  row of global domain only
+         zhu(ji,:) = zht(jpi,:)
+      END DO
+      ! at v-point: averaging zht
+      zhv = 0._wp
+      DO jj = 1, jpjm1
+         zhv(:,jj) = 0.5_wp * ( zht(:,jj) + zht(:,jj+1) )
+      END DO
+      CALL lbc_lnk( 'usrdef_zgr', zhv, 'V', 1. )     ! boundary condition: this mask the surrounding grid-points
+      DO jj = mj0(1), mj1(1)   ! first  row of global domain only
+         zhv(:,jj) = zht(:,jj)
+      END DO
+      DO jj = mj0(jpjglo), mj1(jpjglo)   ! last  row of global domain only
+         zhv(:,jj) = zht(:,jj)
+      END DO
+      !     
+      CALL zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! Reference z-coordinate system
+      !
+      !
+      !                       !==  top masked level bathymetry  ==!  (all coordinates)
+      !
+      ! no ocean cavities : top ocean level is ONE, except over land
+      ! the ocean basin surrounnded by land (1 grid-point) set through lbc_lnk call as jperio=0 
+      z2d(:,:) = 1._wp                    ! surface ocean is the 1st level
+      z2d(mi0(1):mi1(1),:) = 0._wp
+      z2d(mi0(jpiglo):mi1(jpiglo),:) = 0._wp
+      z2d(:,mj0(1):mj1(1)) = 0._wp
+      z2d(:,mj0(jpjglo):mj1(jpjglo)) = 0._wp
+
+
+
+
+
+      CALL lbc_lnk( 'usrdef_zgr', z2d, 'T', 1. )        ! closed basin since jperio = 0 (see userdef_nam.F90)
+      k_top(:,:) = NINT( z2d(:,:) )
+      !
+      !                              
+      !
+      IF ( ld_sco ) THEN      !==  s-coordinate  ==!   (terrain-following coordinate)
+         !
+         ht_0 = zht
+         k_bot(:,:) = jpkm1 * k_top(:,:)  !* bottom ocean = jpk-1 (here use k_top as a land mask)
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+              IF( zht(ji,jj) <= -(rn_wdld - rn_wdmin2)) THEN
+                k_bot(ji,jj) = 0
+                k_top(ji,jj) = 0
+              ENDIF
+           END DO
+         END DO
+         !
+         !                                !* terrain-following coordinate with e3.(k)=cst)
+         !                                !  OVERFLOW case : identical with j-index (T=V, U=F)
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+              z1_jpkm1 = 1._wp / REAL( k_bot(ji,jj) - k_top(ji,jj) + 1 , wp)
+              DO jk = 1, jpk
+                  zwet = MAX( zht(ji,jj), rn_wdmin1 )
+                  pdept(ji,jj,jk) = zwet * z1_jpkm1 * ( REAL( jk   , wp ) - 0.5_wp )
+                  pdepw(ji,jj,jk) = zwet * z1_jpkm1 * ( REAL( jk-1 , wp )          )
+                  pe3t (ji,jj,jk) = zwet * z1_jpkm1
+                  pe3w (ji,jj,jk) = zwet * z1_jpkm1
+                  zwet = MAX( zhu(ji,jj), rn_wdmin1 )
+                  pe3u (ji,jj,jk) = zwet * z1_jpkm1
+                  pe3uw(ji,jj,jk) = zwet * z1_jpkm1
+                  pe3f (ji,jj,jk) = zwet * z1_jpkm1
+                  zwet = MAX( zhv(ji,jj), rn_wdmin1 )
+                  pe3v (ji,jj,jk) = zwet * z1_jpkm1
+                  pe3vw(ji,jj,jk) = zwet * z1_jpkm1
+              END DO      
+           END DO      
+         END DO      
+         CALL lbc_lnk( 'usrdef_zgr', pdept, 'T', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pdepw, 'T', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3t , 'T', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3w , 'T', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3u , 'U', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3uw, 'U', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3f , 'F', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3v , 'V', 1. )
+         CALL lbc_lnk( 'usrdef_zgr', pe3vw, 'V', 1. )
+         WHERE( pe3t (:,:,:) == 0._wp )   pe3t (:,:,:) = 1._wp
+         WHERE( pe3u (:,:,:) == 0._wp )   pe3u (:,:,:) = 1._wp
+         WHERE( pe3v (:,:,:) == 0._wp )   pe3v (:,:,:) = 1._wp
+         WHERE( pe3f (:,:,:) == 0._wp )   pe3f (:,:,:) = 1._wp
+         WHERE( pe3w (:,:,:) == 0._wp )   pe3w (:,:,:) = 1._wp
+         WHERE( pe3uw(:,:,:) == 0._wp )   pe3uw(:,:,:) = 1._wp
+         WHERE( pe3vw(:,:,:) == 0._wp )   pe3vw(:,:,:) = 1._wp
+      ENDIF
+      !
+      !
+      !
+   END SUBROUTINE usr_def_zgr
+
+
+   SUBROUTINE zgr_z( pdept_1d, pdepw_1d, pe3t_1d , pe3w_1d )   ! 1D reference vertical coordinate
+      !!----------------------------------------------------------------------
+      !!                   ***  ROUTINE zgr_z  ***
+      !!
+      !! ** Purpose :   set the depth of model levels and the resulting 
+      !!      vertical scale factors.
+      !!
+      !! ** Method  :   1D z-coordinate system (use in all type of coordinate)
+      !!       The depth of model levels is set from dep(k), an analytical function:
+      !!                   w-level: depw_1d  = dep(k)
+      !!                   t-level: dept_1d  = dep(k+0.5)
+      !!       The scale factors are the discrete derivative of the depth:
+      !!                   e3w_1d(jk) = dk[ dept_1d ] 
+      !!                   e3t_1d(jk) = dk[ depw_1d ]
+      !!
+      !!            ===    Here constant vertical resolution   ===
+      !!
+      !! ** Action  : - pdept_1d, pdepw_1d : depth of T- and W-point (m)
+      !!              - pe3t_1d , pe3w_1d  : scale factors at T- and W-levels (m)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pdept_1d, pdepw_1d   ! 1D grid-point depth        [m]
+      REAL(wp), DIMENSION(:), INTENT(out) ::   pe3t_1d , pe3w_1d    ! 1D vertical scale factors  [m]
+      !
+      INTEGER  ::   jk       ! dummy loop indices
+      REAL(wp) ::   zt, zw   ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN                         ! Parameter print
+         WRITE(numout,*)
+         WRITE(numout,*) '    zgr_z : Reference vertical z-coordinates: uniform dz = ', rn_dz
+         WRITE(numout,*) '    ~~~~~~~'
+      ENDIF
+      !
+      ! Reference z-coordinate (depth - scale factor at T- and W-points)   ! Madec & Imbard 1996 function
+      ! ----------------------
+      DO jk = 1, jpk
+         zw = REAL( jk , wp )
+         zt = REAL( jk , wp ) + 0.5_wp
+         pdepw_1d(jk) =    rn_dz *   REAL( jk-1 , wp )
+         pdept_1d(jk) =    rn_dz * ( REAL( jk-1 , wp ) + 0.5_wp )
+         pe3w_1d (jk) =    rn_dz
+         pe3t_1d (jk) =    rn_dz
+      END DO
+      !
+      IF(lwp) THEN                        ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) '              Reference 1D z-coordinate depth and scale factors:'
+         WRITE(numout, "(9x,' level  gdept_1d  gdepw_1d  e3t_1d   e3w_1d  ')" )
+         WRITE(numout, "(10x, i4, 4f9.2)" ) ( jk, pdept_1d(jk), pdepw_1d(jk), pe3t_1d(jk), pe3w_1d(jk), jk = 1, jpk )
+      ENDIF
+      !
+   END SUBROUTINE zgr_z
+   
+   !!======================================================================
+END MODULE usrdef_zgr
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/cpp_WAD.fcm
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/cpp_WAD.fcm	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/WAD/cpp_WAD.fcm	(revision 14097)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys   key_iomput key_mpp_mpi 
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/demo_cfgs.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/demo_cfgs.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/demo_cfgs.txt	(revision 14097)
@@ -0,0 +1,10 @@
+CANAL OCE
+ISOMIP OCE
+LOCK_EXCHANGE OCE
+OVERFLOW OCE
+ICE_AGRIF OCE NST SAS ICE
+ICE_ADV1D OCE SAS ICE
+ICE_ADV2D OCE SAS ICE
+VORTEX OCE NST
+WAD OCE
+BENCH OCE ICE TOP
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/rmt_cfgs.txt
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/rmt_cfgs.txt	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/rmt_cfgs.txt	(revision 14097)
@@ -0,0 +1,3 @@
+ORCA1_CICE # ORCA2_LIM # OCE TOP  # http://gws-access.ceda.ac.uk/public/nemo/uspconfigs/ORCA1_CICE/v3.6.0/ORCA1_CICE_ctl.txt
+ISOMIP     # GYRE      # OCE      # http://gws-access.ceda.ac.uk/public/nemo/uspconfigs/ISOMIP/trunk/ISOMIP_ctl.txt
+IRISHSEA   # GYRE      # OCE      # http://gws-access.ceda.ac.uk/public/nemo/uspconfigs/IRISHSEA/v3.7.0/IRISHSEA_ctl.txt
Index: NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/test_cases.bib
===================================================================
--- NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/test_cases.bib	(revision 14097)
+++ NEMO/branches/UKMO/NEMO_4.0.4_GO6_mixing/tests/test_cases.bib	(revision 14097)
@@ -0,0 +1,116 @@
+@book{HAIDVOGEL1999,
+   author = {D. B. Haidvogel and A. Beckmann},
+   publisher = {Imperial College Press, London},
+   year = {1999},
+   title = {Numerical ocean circulation modeling}
+}
+
+@book{BURCHARD2002,
+   title={GETM: A General Estuarine Transport Model; Scientific Documentation},
+   author={Burchard, Hans and Bolding, Karsten},
+   year={2002},
+   publisher={European Commission, Joint Research Centre, Institute for Environment and Sustainability}
+}
+
+@article{ILICAK2012,
+   title = "Spurious dianeutral mixing and the role of momentum closure",
+   journal = "Ocean Modelling",
+   volume = "45-46",
+   pages = "37 - 58",
+   year = "2012",
+   issn = "1463-5003",
+   doi = "10.1016/j.ocemod.2011.10.003",
+   author = "Mehmet Ilicak and Alistair J. Adcroft and Stephen M. Griffies and Robert W. Hallberg",
+   keywords = "Spurious dianeutral transport, Cabbeling, Overflows, Exchange-flow, Ocean models, Momentum transport, Tracer advection, Reference potential energy"
+}
+
+@article{DEBREU2012,
+   title = "Two-way nesting in split-explicit ocean models: Algorithms, implementation and validation",
+   journal = "Ocean Modelling",
+   volume = "49-50",
+   pages = "1 - 21",
+   year = "2012",
+   issn = "1463-5003",
+   doi = "10.1016/j.ocemod.2012.03.003",
+   author = "Laurent Debreu and Patrick Marchesiello and Pierrick Penven and Gildas Cambon",
+   keywords = "Two-way nesting, Finite difference method, Modeling, Boundary conditions, Coastal upwelling"
+}
+
+@article{PENVEN2006,
+   title = "Evaluation and application of the ROMS 1-way embedding procedure to the central california upwelling system",
+   journal = "Ocean Modelling",
+   volume = "12",
+   number = "1",
+   pages = "157 - 187",
+   year = "2006",
+   issn = "1463-5003",
+   doi = "10.1016/j.ocemod.2005.05.002",
+   author = "Pierrick Penven and Laurent Debreu and Patrick Marchesiello and James C. McWilliams",
+   keywords = "Ocean models, Boundary conditions, Embedding, Coastal upwelling, Mesoscale eddies, Eddy kinetic energy, North America, West Coast, Central upwelling system, Monterey Bay, 35–41°N, 128–121°W"
+}
+
+@article{SPALL1991,
+   author = {Spall, M. A. and Holland, W. R.},
+   title = {A Nested Primitive Equation Model for Oceanic Applications},
+   journal = {Journal of Physical Oceanography},
+   volume = {21},
+   number = {2},
+   pages = {205-220},
+   year = {1991},
+   doi = {10.1175/1520-0485(1991)021<0205:ANPEMF>2.0.CO;2},
+}
+
+@article{MATHIOT2017,
+   author = {Mathiot, P. and Jenkins, A. and Harris, C. and Madec, G.},
+   title = {Explicit representation and parametrised impacts of under ice shelf seas in the ${z}^{\ast}$ coordinate ocean model NEMO 3.6},
+   journal = {Geoscientific Model Development},
+   volume = {10},
+   year = {2017},
+   number = {7},
+   pages = {2849--2874},
+   url = {https://www.geosci-model-dev.net/10/2849/2017/},
+   doi = {10.5194/gmd-10-2849-2017}
+}
+
+@article{LOSCH2008,
+   author = {Losch, M.},
+   title = {Modeling ice shelf cavities in a z coordinate ocean general circulation model},
+   journal = {Journal of Geophysical Research: Oceans},
+   volume = {113},
+   year = {2008},
+   number = {C8},
+   pages = {},
+   keywords = {Ice shelf cavities, numerical ocean modeling, z coordinates},
+   doi = {10.1029/2007JC004368},
+   url = {https://agupubs.onlinelibrary.wiley.com/doi/abs/10.1029/2007JC004368},
+   eprint = {https://agupubs.onlinelibrary.wiley.com/doi/pdf/10.1029/2007JC004368},
+   abstract = {Processes at the ice shelf-ocean interface and in particular in ice shelf cavities around Antarctica have an observable effect on the solutions of basin scale to global coupled ice-ocean models. Despite this, these processes are not routinely represented in global ocean and climate models. It is shown that a new ice shelf cavity model for z coordinate models can reproduce results from an intercomparison project of earlier approaches with vertical ?~C or isopycnic coordinates. As a proof of concept, ice shelves are incorporated in a 100-year global integration of a z coordinate model. In this simulation, glacial meltwater can be traced as far as north as 15??S. The observed effects of processes in the ice shelf cavities agree with previous results from a ?~C coordinate model, notably the increase in sea ice thickness. However, melt rates are overestimated probably because the parameterization of basal melting does not suit the low resolution of this configuration.}
+}
+
+@article{LIPSCOMB2004,
+   author = {Lipscomb, William H. and Hunke, Elizabeth C.},
+   title = {Modeling Sea Ice Transport Using Incremental Remapping},
+   journal = {Monthly Weather Review},
+   volume = {132},
+   number = {6},
+   pages = {1341-1354},
+   year = {2004},
+   doi = {10.1175/1520-0493(2004)132<1341:MSITUI>2.0.CO;2},
+   URL = {https://doi.org/10.1175/1520-0493(2004)132<1341:MSITUI>2.0.CO;2},
+   eprint = {https://doi.org/10.1175/1520-0493(2004)132<1341:MSITUI>2.0.CO;2},
+   abstract = { Abstract Sea ice models contain transport equations for the area, volume, and energy of ice and snow in various thickness categories. These equations typically are solved with first-order-accurate upwind schemes, which are very diffusive; with second-order-accurate centered schemes, which are highly oscillatory; or with more sophisticated second-order schemes that are computationally costly if many quantities must be transported [e.g., multidimensional positive-definite advection transport algorithm (MPDATA)]. Here an incremental remapping scheme, originally designed for horizontal transport in ocean models, is adapted for sea ice transport. This scheme has several desirable features: it preserves the monotonicity of both conserved quantities and tracers; it is second-order accurate except where the accuracy is reduced locally to preserve monotonicity; and it efficiently solves the large number of equations in sea ice models with multiple thickness categories and tracers. Remapping outperforms the first-order upwind scheme and basic MPDATA scheme in several simple test problems. In realistic model runs, remapping is less diffusive than the upwind scheme and about twice as fast as MPDATA. }
+}
+
+@article{SCHAR1996,
+   author = {Christoph Schär and Piotr K. Smolarkiewicz},
+   title = {A Synchronous and Iterative Flux-Correction Formalism for Coupled Transport Equations},
+   journal = {Journal of Computational Physics},
+   volume = {128},
+   number = {1},
+   pages = {101 - 120},
+   year = {1996},
+   issn = {0021-9991},
+   doi = {https://doi.org/10.1006/jcph.1996.0198},
+   url = {http://www.sciencedirect.com/science/article/pii/S0021999196901989},
+   abstract = {Many problems of fluid dynamics involve the coupled transport of several, density-like, dependent variables (for instance, densities of mass and momenta in elastic flows). In this paper, a conservative and synchronous flux-corrected transport (FCT) formalism is developed which aims at a consistent transport of such variables. The technique differs from traditional FCT algorithms in two respects. First, the limiting of transportive fluxes of the primary variables (e.g., mass and momentum) does not derive from smooth estimates of the variables, but it derives from analytic constraints implied by the Lagrangian form of the governing continuity equations, which are imposed on the specific mixing ratios of the variables (e.g., velocity components). Second, the traditional FCT limiting based on sufficiency conditions is augmented by an iterative procedure which approaches the necessity requirements. This procedure can also be used in the framework of traditional FCT schemes, and a demonstration is provided that it can significantly reduce some of the pathological behaviors of FCT algorithms. Although the approach derived is applicable to the transport of arbitrary conserved quantities, it is particularly useful for the synchronous transport of mass and momenta in elastic flows, where it assures intrinsic stability of the algorithm regardless of the magnitude of the mass-density variable. This latter property becomes especially important in fluids with large density variations, or in models with a material “vertical” coordinate (e.g., geophysical hydrostatic stratified flows in isopycnic/isentropic coordinates), where material surfaces can collapse to zero-mass layers admitting, therefore, arbitrarily large local Courant numbers.}
+}
